forked from nillerusr/source-engine
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsaverestore_filesystem.cpp
1478 lines (1267 loc) · 46 KB
/
saverestore_filesystem.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Filesystem abstraction for CSaveRestore - allows for storing temp save files
// either in memory or on disk.
//
//===========================================================================//
#ifdef _WIN32
#include "winerror.h"
#endif
#include "filesystem_engine.h"
#include "saverestore_filesystem.h"
#include "host_saverestore.h"
#include "host.h"
#include "sys.h"
#include "tier1/utlbuffer.h"
#include "tier1/lzss.h"
#include "tier1/convar.h"
#include "ixboxsystem.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
extern ConVar save_spew;
extern IXboxSystem *g_pXboxSystem;
#define SaveMsg if ( !save_spew.GetBool() ) ; else Msg
void SaveInMemoryCallback( IConVar *var, const char *pOldString, float flOldValue );
#ifdef _X360
ConVar save_in_memory( "save_in_memory", "1", 1, "Set to 1 to save to memory instead of disk (Xbox 360)", SaveInMemoryCallback );
#else
ConVar save_in_memory( "save_in_memory", "0", 0, "Set to 1 to save to memory instead of disk (Xbox 360)", SaveInMemoryCallback );
#endif // _X360
#define INVALID_INDEX (GetDirectory().InvalidIndex())
enum { READ_ONLY, WRITE_ONLY };
static float g_fPrevSaveInMemoryValue;
static bool SaveFileLessFunc( const CUtlSymbol &lhs, const CUtlSymbol &rhs )
{
return lhs < rhs;
}
//----------------------------------------------------------------------------
// Simulates the save directory in RAM.
//----------------------------------------------------------------------------
class CSaveDirectory
{
public:
CSaveDirectory()
{
m_Files.SetLessFunc( SaveFileLessFunc );
file_t dummy;
dummy.name = m_SymbolTable.AddString( "dummy" );
m_Files.Insert( dummy.name, dummy );
}
~CSaveDirectory()
{
int i = m_Files.FirstInorder();
while ( m_Files.IsValidIndex( i ) )
{
int idx = i;
i = m_Files.NextInorder( i );
delete m_Files[idx].pBuffer;
delete m_Files[idx].pCompressedBuffer;
m_Files.RemoveAt( idx );
}
}
struct file_t
{
file_t()
{
pBuffer = NULL;
pCompressedBuffer = NULL;
nSize = 0;
nCompressedSize = 0;
}
int eType;
CUtlSymbol name;
unsigned int nSize;
unsigned int nCompressedSize;
CUtlBuffer *pBuffer;
CUtlBuffer *pCompressedBuffer;
};
CUtlSymbolTable m_SymbolTable;
CUtlMap<CUtlSymbol, file_t> m_Files;
};
typedef CSaveDirectory::file_t SaveFile_t;
//----------------------------------------------------------------------------
// CSaveRestoreFileSystem: Manipulates files in the CSaveDirectory
//----------------------------------------------------------------------------
class CSaveRestoreFileSystem : public ISaveRestoreFileSystem
{
public:
CSaveRestoreFileSystem()
{
m_pSaveDirectory = new CSaveDirectory();
m_iContainerOpens = 0;
}
~CSaveRestoreFileSystem()
{
delete m_pSaveDirectory;
}
bool FileExists( const char *pFileName, const char *pPathID = NULL );
void RenameFile( char const *pOldPath, char const *pNewPath, const char *pathID = NULL );
void RemoveFile( char const* pRelativePath, const char *pathID = NULL );
FileHandle_t Open( const char *pFileName, const char *pOptions, const char *pathID = NULL );
void Close( FileHandle_t );
int Read( void *pOutput, int size, FileHandle_t file );
int Write( void const* pInput, int size, FileHandle_t file );
void Seek( FileHandle_t file, int pos, FileSystemSeek_t method );
unsigned int Tell( FileHandle_t file );
unsigned int Size( FileHandle_t file );
unsigned int Size( const char *pFileName, const char *pPathID = NULL );
void AsyncFinishAllWrites( void );
void AsyncRelease( FSAsyncControl_t hControl );
FSAsyncStatus_t AsyncWrite( const char *pFileName, const void *pSrc, int nSrcBytes, bool bFreeMemory, bool bAppend, FSAsyncControl_t *pControl = NULL );
FSAsyncStatus_t AsyncFinish( FSAsyncControl_t hControl, bool wait = false );
FSAsyncStatus_t AsyncAppend( const char *pFileName, const void *pSrc, int nSrcBytes, bool bFreeMemory, FSAsyncControl_t *pControl = NULL );
FSAsyncStatus_t AsyncAppendFile( const char *pDestFileName, const char *pSrcFileName, FSAsyncControl_t *pControl = NULL );
void DirectoryCopy( const char *pPath, const char *pDestFileName, bool bIsXSave );
void DirectorCopyToMemory( const char *pPath, const char *pDestFileName );
bool DirectoryExtract( FileHandle_t pFile, int fileCount, bool bIsXSave );
int DirectoryCount( const char *pPath );
void DirectoryClear( const char *pPath, bool bIsXSave );
void WriteSaveDirectoryToDisk( void );
void LoadSaveDirectoryFromDisk( const char *pPath );
void DumpSaveDirectory( void );
void Compress( SaveFile_t *pFile );
void Uncompress( SaveFile_t *pFile );
void AuditFiles( void );
bool LoadFileFromDisk( const char *pFilename );
private:
CSaveDirectory *m_pSaveDirectory;
CUtlMap<CUtlSymbol, SaveFile_t> &GetDirectory( void ) { return m_pSaveDirectory->m_Files; }
SaveFile_t &GetFile( const int idx ) { return m_pSaveDirectory->m_Files[idx]; }
SaveFile_t &GetFile( const FileHandle_t hFile ) { return GetFile( (uintp)hFile ); }
FileHandle_t GetFileHandle( const char *pFileName );
int GetFileIndex( const char *pFileName );
bool HandleIsValid( FileHandle_t hFile );
unsigned int CompressedSize( const char *pFileName );
CUtlSymbol AddString( const char *str )
{
char szString[ MAX_PATH ];
Q_strncpy( szString, str, sizeof( szString ) );
return m_pSaveDirectory->m_SymbolTable.AddString( Q_strlower( szString ) );
}
const char *GetString( CUtlSymbol &id ) { return m_pSaveDirectory->m_SymbolTable.String( id ); }
int m_iContainerOpens;
};
//#define TEST_LZSS_WINDOW_SIZES
//----------------------------------------------------------------------------
// Compress the file data
//----------------------------------------------------------------------------
void CSaveRestoreFileSystem::Compress( SaveFile_t *pFile )
{
pFile->pCompressedBuffer->Purge();
#ifdef TEST_LZSS_WINDOW_SIZES
// Compress the data here
CLZSS compressor_test;
CLZSS newcompressor_test( 2048 );
pFile->nCompressedSize = 0;
float start = Plat_FloatTime();
for(int i=0;i<10;i++)
{
uint32 sz;
unsigned char *pCompressedBuffer = compressor_test.Compress(
(unsigned char *) pFile->pBuffer->Base(), pFile->nSize, &sz );
delete[] pCompressedBuffer;
}
Warning(" old compressor_test %f", Plat_FloatTime() - start );
start = Plat_FloatTime();
for(int i=0;i<10;i++)
{
uint32 sz;
unsigned char *pCompressedBuffer = newcompressor_test.Compress(
(unsigned char *) pFile->pBuffer->Base(), pFile->nSize, &sz );
delete[] pCompressedBuffer;
}
Warning(" new compressor_test %f", Plat_FloatTime() - start );
if ( 1)
{
uint32 sz;
uint32 sz1;
unsigned char *pNewCompressedBuffer = newcompressor_test.Compress(
(unsigned char *) pFile->pBuffer->Base(), pFile->nSize, &sz );
unsigned char *pOldCompressedBuffer = compressor_test.Compress(
(unsigned char *) pFile->pBuffer->Base(), pFile->nSize, &sz1 );
if ( ! pNewCompressedBuffer )
Warning("new no comp");
if ( ! pOldCompressedBuffer )
Warning("old no comp");
if ( pNewCompressedBuffer && pOldCompressedBuffer )
{
if ( sz != sz1 )
Warning(" new size = %d old = %d", sz, sz1 );
if ( memcmp( pNewCompressedBuffer, pOldCompressedBuffer, sz ) )
Warning("data mismatch");
}
delete[] pOldCompressedBuffer;
delete[] pNewCompressedBuffer;
}
#endif
CLZSS compressor( 2048 );
unsigned char *pCompressedBuffer = compressor.Compress( (unsigned char *) pFile->pBuffer->Base(), pFile->nSize, &pFile->nCompressedSize );
if ( pCompressedBuffer == NULL )
{
// Just copy the buffer uncompressed
pFile->pCompressedBuffer->Put( pFile->pBuffer->Base(), pFile->nSize );
pFile->nCompressedSize = pFile->nSize;
}
else
{
// Take the compressed buffer as our own
pFile->pCompressedBuffer->AssumeMemory( pCompressedBuffer, pFile->nCompressedSize, pFile->nCompressedSize ); // ?
}
// end compression
pFile->pCompressedBuffer->SeekGet( CUtlBuffer::SEEK_HEAD, 0 );
pFile->pCompressedBuffer->SeekPut( CUtlBuffer::SEEK_HEAD, pFile->nCompressedSize );
// Don't want the uncompressed memory hanging around
pFile->pBuffer->Purge();
unsigned int srcBytes = pFile->nSize;
pFile->nSize = 0;
unsigned int destBytes = pFile->nCompressedSize;
float percent = 0.f;
if ( srcBytes )
percent = 100.0f * (1.0f - (float)destBytes/(float)srcBytes);
SaveMsg( "SIM: SaveDir: (%s) Compressed %d bytes to %d bytes. (%.0f%%)\n", GetString( pFile->name ), srcBytes, destBytes, percent );
}
//----------------------------------------------------------------------------
// Uncompress the file data
//----------------------------------------------------------------------------
void CSaveRestoreFileSystem::Uncompress( SaveFile_t *pFile )
{
pFile->pBuffer->Purge();
// Uncompress the data here
CLZSS compressor;
unsigned int nUncompressedSize = compressor.GetActualSize( (unsigned char *) pFile->pCompressedBuffer->Base() );
if ( nUncompressedSize != 0 )
{
unsigned char *pUncompressBuffer = (unsigned char *) malloc( nUncompressedSize );
nUncompressedSize = compressor.Uncompress( (unsigned char *) pFile->pCompressedBuffer->Base(), pUncompressBuffer );
pFile->pBuffer->AssumeMemory( pUncompressBuffer, nUncompressedSize, nUncompressedSize ); // ?
}
else
{
// Put it directly into our target
pFile->pBuffer->Put( (unsigned char *) pFile->pCompressedBuffer->Base(), pFile->nCompressedSize );
}
// end decompression
pFile->nSize = pFile->pBuffer->TellMaxPut();
pFile->pBuffer->SeekGet( CUtlBuffer::SEEK_HEAD, 0 );
pFile->pBuffer->SeekPut( CUtlBuffer::SEEK_HEAD, pFile->nSize );
unsigned int srcBytes = pFile->nCompressedSize;
unsigned int destBytes = pFile->nSize;
SaveMsg( "SIM: SaveDir: (%s) Uncompressed %d bytes to %d bytes.\n", GetString( pFile->name ), srcBytes, destBytes );
}
//----------------------------------------------------------------------------
// Access the save files
//----------------------------------------------------------------------------
int CSaveRestoreFileSystem::GetFileIndex( const char *filename )
{
CUtlSymbol id = AddString( Q_UnqualifiedFileName( filename ) );
return GetDirectory().Find( id );
}
FileHandle_t CSaveRestoreFileSystem::GetFileHandle( const char *filename )
{
intp idx = GetFileIndex( filename );
if ( idx == INVALID_INDEX )
{
idx = 0;
}
return (FileHandle_t)idx;
}
//-----------------------------------------------------------------------------
// Purpose: Returns whether the named memory block exists
//-----------------------------------------------------------------------------
bool CSaveRestoreFileSystem::FileExists( const char *pFileName, const char *pPathID )
{
return ( GetFileHandle( pFileName ) != NULL );
}
//-----------------------------------------------------------------------------
// Purpose: Validates a file handle
//-----------------------------------------------------------------------------
bool CSaveRestoreFileSystem::HandleIsValid( FileHandle_t hFile )
{
return hFile && GetDirectory().IsValidIndex( (uintp)hFile );
}
//-----------------------------------------------------------------------------
// Purpose: Renames a block of memory
//-----------------------------------------------------------------------------
void CSaveRestoreFileSystem::RenameFile( char const *pOldPath, char const *pNewPath, const char *pathID )
{
intp idx = GetFileIndex( pOldPath );
if ( idx != INVALID_INDEX )
{
CUtlSymbol newID = AddString( Q_UnqualifiedFileName( pNewPath ) );
GetFile( idx ).name = newID;
GetDirectory().Reinsert( newID, idx );
}
}
//-----------------------------------------------------------------------------
// Purpose: Removes a memory block from CSaveDirectory and frees it.
//-----------------------------------------------------------------------------
void CSaveRestoreFileSystem::RemoveFile( char const* pRelativePath, const char *pathID )
{
int idx = GetFileIndex( pRelativePath );
if ( idx != INVALID_INDEX )
{
delete GetFile( idx ).pBuffer;
delete GetFile( idx ).pCompressedBuffer;
GetDirectory().RemoveAt( idx );
}
}
//-----------------------------------------------------------------------------
// Purpose: Access an existing memory block if it exists, else allocate one.
//-----------------------------------------------------------------------------
FileHandle_t CSaveRestoreFileSystem::Open( const char *pFullName, const char *pOptions, const char *pathID )
{
SaveFile_t *pFile = NULL;
CUtlSymbol id = AddString( Q_UnqualifiedFileName( pFullName ) );
intp idx = GetDirectory().Find( id );
if ( idx == INVALID_INDEX )
{
// Don't create a read-only file
if ( Q_stricmp( pOptions, "rb" ) )
{
// Create new file
SaveFile_t newFile;
newFile.name = id;
newFile.pBuffer = new CUtlBuffer();
newFile.pCompressedBuffer = new CUtlBuffer();
idx = GetDirectory().Insert( id, newFile );
}
else
{
return (void*)0;
}
}
pFile = &GetFile( idx );
if ( !Q_stricmp( pOptions, "rb" ) )
{
Uncompress( pFile );
pFile->eType = READ_ONLY;
}
else if ( !Q_stricmp( pOptions, "wb" ) )
{
pFile->pBuffer->Clear();
pFile->eType = WRITE_ONLY;
}
else if ( !Q_stricmp( pOptions, "a" ) )
{
Uncompress( pFile );
pFile->eType = WRITE_ONLY;
}
else if ( !Q_stricmp( pOptions, "ab+" ) )
{
Uncompress( pFile );
pFile->eType = WRITE_ONLY;
pFile->pBuffer->SeekPut( CUtlBuffer::SEEK_TAIL, 0 );
}
else
{
Assert( 0 );
Warning( "CSaveRestoreFileSystem: Attempted to open %s with unsupported option %s\n", pFullName, pOptions );
return (void*)0;
}
return (void*)idx;
}
//-----------------------------------------------------------------------------
// Purpose: No need to close files in memory. Could perform post processing here.
//-----------------------------------------------------------------------------
void CSaveRestoreFileSystem::Close( FileHandle_t hFile )
{
// Compress the file
if ( HandleIsValid( hFile ) )
{
SaveFile_t &file = GetFile( hFile );
// Files opened for read don't need to be recompressed
if ( file.eType == READ_ONLY )
{
SaveMsg("SIM: Closed file: %s\n", GetString( file.name ) );
file.pBuffer->Purge();
file.nSize = 0;
}
else
{
Compress( &file );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Reads data from memory.
//-----------------------------------------------------------------------------
int CSaveRestoreFileSystem::Read( void *pOutput, int size, FileHandle_t hFile )
{
int readSize = 0;
if ( HandleIsValid( hFile ) )
{
SaveFile_t &file = GetFile( hFile );
if( file.eType == READ_ONLY )
{
readSize = file.pBuffer->GetUpTo( pOutput, size );
}
else
{
Warning( "Read: Attempted to read from a write-only file" );
readSize = 0;
Assert( 0 );
}
}
return readSize;
}
//-----------------------------------------------------------------------------
// Purpose: Writes data to memory.
//-----------------------------------------------------------------------------
int CSaveRestoreFileSystem::Write( void const* pInput, int size, FileHandle_t hFile )
{
int writeSize = 0;
if ( HandleIsValid( hFile ) )
{
SaveFile_t &file = GetFile( hFile );
if( file.eType == WRITE_ONLY )
{
file.pBuffer->Put( pInput, size );
file.nSize = file.pBuffer->TellMaxPut();
writeSize = size;
}
else
{
Warning( "Write: Attempted to write to a read-only file" );
writeSize = 0;
Assert( 0 );
}
}
return writeSize;
}
//-----------------------------------------------------------------------------
// Purpose: Seek in memory. Seeks the UtlBuffer put or get pos depending
// on whether the file was opened for read or write.
//-----------------------------------------------------------------------------
void CSaveRestoreFileSystem::Seek( FileHandle_t hFile, int pos, FileSystemSeek_t method )
{
if ( HandleIsValid( hFile ) )
{
SaveFile_t &file = GetFile( hFile );
if ( file.eType == READ_ONLY )
{
file.pBuffer->SeekGet( (CUtlBuffer::SeekType_t)method, pos );
}
else if ( file.eType == WRITE_ONLY )
{
file.pBuffer->SeekPut( (CUtlBuffer::SeekType_t)method, pos );
}
else
{
Assert( 0 );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Return position in memory. Returns UtlBuffer put or get pos depending
// on whether the file was opened for read or write.
//-----------------------------------------------------------------------------
unsigned int CSaveRestoreFileSystem::Tell( FileHandle_t hFile )
{
unsigned int pos = 0;
if ( HandleIsValid( hFile ) )
{
SaveFile_t &file = GetFile( hFile );
if ( file.eType == READ_ONLY )
{
pos = file.pBuffer->TellGet();
}
else if ( file.eType == WRITE_ONLY )
{
pos = file.pBuffer->TellPut();
}
else
{
Assert( 0 );
}
}
return pos;
}
//-----------------------------------------------------------------------------
// Purpose: Return uncompressed memory size
//-----------------------------------------------------------------------------
unsigned int CSaveRestoreFileSystem::Size( FileHandle_t hFile )
{
if ( HandleIsValid( hFile ) )
{
return GetFile( hFile ).nSize;
}
return 0;
}
//-----------------------------------------------------------------------------
// Purpose: Return uncompressed size of data in memory
//-----------------------------------------------------------------------------
unsigned int CSaveRestoreFileSystem::Size( const char *pFileName, const char *pPathID )
{
return Size( GetFileHandle( pFileName ) );
}
//-----------------------------------------------------------------------------
// Purpose: Return compressed size of data in memory
//-----------------------------------------------------------------------------
unsigned int CSaveRestoreFileSystem::CompressedSize( const char *pFileName )
{
FileHandle_t hFile = GetFileHandle( pFileName );
if ( hFile )
{
return GetFile( hFile ).nCompressedSize;
}
return 0;
}
//-----------------------------------------------------------------------------
// Purpose: Writes data to memory. Function is NOT async.
//-----------------------------------------------------------------------------
FSAsyncStatus_t CSaveRestoreFileSystem::AsyncWrite( const char *pFileName, const void *pSrc, int nSrcBytes, bool bFreeMemory, bool bAppend, FSAsyncControl_t *pControl )
{
FSAsyncStatus_t retval = FSASYNC_ERR_FAILURE;
FileHandle_t hFile = Open( pFileName, "wb" );
if ( hFile )
{
SaveFile_t &file = GetFile( (uintp)hFile );
if( file.eType == WRITE_ONLY )
{
file.pBuffer->Put( pSrc, nSrcBytes );
file.nSize = file.pBuffer->TellMaxPut();
Compress( &file );
retval = FSASYNC_OK;
}
else
{
Warning( "AsyncWrite: Attempted to write to a read-only file" );
Assert( 0 );
}
}
if ( bFreeMemory )
free( const_cast< void * >( pSrc ) );
return retval;
}
//-----------------------------------------------------------------------------
// Purpose: Appends data to a memory block. Function is NOT async.
//-----------------------------------------------------------------------------
FSAsyncStatus_t CSaveRestoreFileSystem::AsyncAppend(const char *pFileName, const void *pSrc, int nSrcBytes, bool bFreeMemory, FSAsyncControl_t *pControl )
{
FSAsyncStatus_t retval = FSASYNC_ERR_FAILURE;
FileHandle_t hFile = Open( pFileName, "a" );
if ( hFile )
{
SaveFile_t &file = GetFile( hFile );
if( file.eType == WRITE_ONLY )
{
file.pBuffer->Put( pSrc, nSrcBytes );
file.nSize = file.pBuffer->TellMaxPut();
Compress( &file );
retval = FSASYNC_OK;
}
else
{
Warning( "AsyncAppend: Attempted to write to a read-only file" );
Assert( 0 );
}
}
if ( bFreeMemory )
free( const_cast< void * >( pSrc ) );
return retval;
}
//-----------------------------------------------------------------------------
// Purpose: Appends a memory block to another memory block. Function is NOT async.
//-----------------------------------------------------------------------------
FSAsyncStatus_t CSaveRestoreFileSystem::AsyncAppendFile(const char *pDestFileName, const char *pSrcFileName, FSAsyncControl_t *pControl )
{
FileHandle_t hFile = Open( pSrcFileName, "rb" );
if ( hFile )
{
SaveFile_t &file = GetFile( hFile );
return AsyncAppend( pDestFileName, file.pBuffer->Base(), file.nSize, false );
}
return FSASYNC_ERR_FILEOPEN;
}
//-----------------------------------------------------------------------------
// Purpose: All operations in memory are synchronous
//-----------------------------------------------------------------------------
FSAsyncStatus_t CSaveRestoreFileSystem::AsyncFinish( FSAsyncControl_t hControl, bool wait )
{
// do nothing
return FSASYNC_OK;
}
void CSaveRestoreFileSystem::AsyncRelease( FSAsyncControl_t hControl )
{
// do nothing
}
void CSaveRestoreFileSystem::AsyncFinishAllWrites( void )
{
// Do nothing
}
//-----------------------------------------------------------------------------
// Purpose: Package up all intermediate files to a save game as per usual, but keep them in memory instead of commiting them to disk
//-----------------------------------------------------------------------------
void CSaveRestoreFileSystem::DirectorCopyToMemory( const char *pPath, const char *pDestFileName )
{
// Write the save file
FileHandle_t hSaveFile = Open( pDestFileName, "ab+", pPath );
if ( !hSaveFile )
return;
SaveFile_t &saveFile = GetFile( hSaveFile );
// At this point, we're going to be sneaky and spoof the uncompressed buffer back into the compressed one
// We need to do this because the file goes out to disk as a mixture of an uncompressed header and tags, and compressed
// intermediate files, so this emulates that in memory
saveFile.pCompressedBuffer->Purge();
saveFile.nCompressedSize = 0;
saveFile.pCompressedBuffer->Put( saveFile.pBuffer->Base(), saveFile.nSize );
unsigned int nNumFilesPacked = 0;
for ( int i = GetDirectory().FirstInorder(); GetDirectory().IsValidIndex( i ); i = GetDirectory().NextInorder( i ) )
{
SaveFile_t &file = GetFile( i );
const char *pName = GetString( file.name );
char szFileName[MAX_PATH];
if ( Q_stristr( pName, ".hl" ) )
{
int fileSize = CompressedSize( pName );
if ( fileSize )
{
Assert( Q_strlen( pName ) <= MAX_PATH );
memset( szFileName, 0, sizeof( szFileName ) );
Q_strncpy( szFileName, pName, sizeof( szFileName ) );
saveFile.pCompressedBuffer->Put( szFileName, sizeof( szFileName ) );
saveFile.pCompressedBuffer->Put( &fileSize, sizeof(fileSize) );
saveFile.pCompressedBuffer->Put( file.pCompressedBuffer->Base(), file.nCompressedSize );
SaveMsg("SIM: Packed: %s [Size: %.02f KB]\n", GetString( file.name ), (float)file.nCompressedSize / 1024.0f );
nNumFilesPacked++;
}
}
}
// Set the final, complete size of the file
saveFile.nCompressedSize = saveFile.pCompressedBuffer->TellMaxPut();
SaveMsg("SIM: (%s) Total Files Packed: %d [Size: %.02f KB]\n", GetString( saveFile.name ), nNumFilesPacked, (float) saveFile.nCompressedSize / 1024.0f );
}
//-----------------------------------------------------------------------------
// Purpose: Copies the compressed contents of the CSaveDirectory into the save file on disk.
// Note: This expects standard saverestore behavior, and does NOT
// currently use pPath to filter the filename search.
//-----------------------------------------------------------------------------
void CSaveRestoreFileSystem::DirectoryCopy( const char *pPath, const char *pDestFileName, bool bIsXSave )
{
if ( !Q_stristr( pPath, "*.hl?" ) )
{
// Function depends on known behavior
Assert( 0 );
return;
}
// If we don't have a valid storage device, save this to memory instead
if ( saverestore->StorageDeviceValid() == false )
{
DirectorCopyToMemory( pPath, pDestFileName );
return;
}
// Write the save file
FileHandle_t hSaveFile = Open( pDestFileName, "rb", pPath );
if ( !hSaveFile )
return;
SaveFile_t &saveFile = GetFile( hSaveFile );
// Find out how large this is going to be
unsigned int nWriteSize = saveFile.nSize;
for ( int i = GetDirectory().FirstInorder(); GetDirectory().IsValidIndex( i ); i = GetDirectory().NextInorder( i ) )
{
SaveFile_t &file = GetFile( i );
const char *pName = GetString( file.name );
if ( Q_stristr( pName, ".hl" ) )
{
// Account for the lump header size
nWriteSize += MAX_PATH + sizeof(int) + file.nCompressedSize;
}
}
// Fail to write
#if defined( _X360 )
if ( nWriteSize > XBX_SAVEGAME_BYTES )
{
// FIXME: This error is now lost in the ether!
return;
}
#endif
g_pFileSystem->AsyncWriteFile( pDestFileName, saveFile.pBuffer, saveFile.nSize, true, false );
// AsyncWriteFile() takes control of the utlbuffer, so don't let RemoveFile() delete it.
saveFile.pBuffer = NULL;
RemoveFile( pDestFileName );
// write the list of files to the save file
for ( int i = GetDirectory().FirstInorder(); GetDirectory().IsValidIndex( i ); i = GetDirectory().NextInorder( i ) )
{
SaveFile_t &file = GetFile( i );
const char *pName = GetString( file.name );
if ( Q_stristr( pName, ".hl" ) )
{
int fileSize = CompressedSize( pName );
if ( fileSize )
{
Assert( Q_strlen( pName ) <= MAX_PATH );
g_pFileSystem->AsyncAppend( pDestFileName, memcpy( new char[MAX_PATH], pName, MAX_PATH), MAX_PATH, true );
g_pFileSystem->AsyncAppend( pDestFileName, new int(fileSize), sizeof(int), true );
// This behaves like AsyncAppendFile (due to 5th param) but gets src file from memory instead of off disk.
g_pFileSystem->AsyncWriteFile( pDestFileName, file.pCompressedBuffer, file.nCompressedSize, false, true );
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Extracts all the files contained within pFile.
// Does not Uncompress the extracted data.
//-----------------------------------------------------------------------------
bool CSaveRestoreFileSystem::DirectoryExtract( FileHandle_t pFile, int fileCount, bool bIsXSave )
{
int fileSize;
FileHandle_t pCopy;
char fileName[ MAX_PATH ];
// Read compressed files from disk into the virtual directory
for ( int i = 0; i < fileCount; i++ )
{
Read( fileName, MAX_PATH, pFile );
Read( &fileSize, sizeof(int), pFile );
if ( !fileSize )
return false;
pCopy = Open( fileName, "wb" );
if ( !pCopy )
return false;
SaveFile_t &destFile = GetFile( pCopy );
destFile.pCompressedBuffer->EnsureCapacity( fileSize );
// Must read in the correct amount of data
if ( Read( destFile.pCompressedBuffer->PeekPut(), fileSize, pFile ) != fileSize )
return false;
destFile.pCompressedBuffer->SeekPut( CUtlBuffer::SEEK_HEAD, fileSize );
destFile.nCompressedSize = fileSize;
SaveMsg("SIM: Extracted: %s [Size: %d KB]\n", GetString( destFile.name ), destFile.nCompressedSize / 1024 );
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pFilename -
//-----------------------------------------------------------------------------
bool CSaveRestoreFileSystem::LoadFileFromDisk( const char *pFilename )
{
// Open a new file for writing in memory
FileHandle_t hMemoryFile = Open( pFilename, "wb" );
if ( !hMemoryFile )
return false;
// Open the file off the disk
FileHandle_t hDiskFile = g_pFileSystem->OpenEx( pFilename, "rb", ( IsX360() ) ? FSOPEN_NEVERINPACK : 0 );
if ( !hDiskFile )
return false;
// Read it in off of the disk to memory
SaveFile_t &memoryFile = GetFile( hMemoryFile );
if ( g_pFileSystem->ReadToBuffer( hDiskFile, *memoryFile.pCompressedBuffer ) == false )
return false;
// Hold the compressed size
memoryFile.nCompressedSize = memoryFile.pCompressedBuffer->TellMaxPut();
// Close the disk file
g_pFileSystem->Close( hDiskFile );
SaveMsg("SIM: Loaded %s into memory\n", pFilename );
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Returns the number of save files in the specified filter
// Note: This expects standard saverestore behavior, and does NOT
// currently use pPath to filter file search.
//-----------------------------------------------------------------------------
int CSaveRestoreFileSystem::DirectoryCount( const char *pPath )
{
if ( !Q_stristr( pPath, "*.hl?" ) )
{
// Function depends on known behavior
Assert( 0 );
return 0;
}
int count = 0;
for ( int i = GetDirectory().FirstInorder(); GetDirectory().IsValidIndex( i ); i = GetDirectory().NextInorder( i ) )
{
SaveFile_t &file = GetFile( i );
if ( Q_stristr( GetString( file.name ), ".hl" ) )
{
++count;
}
}
return count;
}
//-----------------------------------------------------------------------------
// Purpose: Clears the save directory of temporary save files (*.hl)
// Note: This expects standard saverestore behavior, and does NOT
// currently use pPath to filter file search.
//-----------------------------------------------------------------------------
void CSaveRestoreFileSystem::DirectoryClear( const char *pPath, bool bIsXSave )
{
if ( !Q_stristr( pPath, "*.hl?" ) )
{
// Function depends on known behavior
Assert( 0 );
return;
}
int i = GetDirectory().FirstInorder();
while ( GetDirectory().IsValidIndex( i ) )
{
SaveFile_t &file = GetFile( i );
i = GetDirectory().NextInorder( i );
if ( Q_stristr( GetString( file.name ), ".hl" ) )
{
SaveMsg("SIM: Cleared: %s\n", GetString( file.name ) );
// Delete the temporary save file
RemoveFile( GetString( file.name ) );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Transfer all save files from memory to disk.
//-----------------------------------------------------------------------------
void CSaveRestoreFileSystem::WriteSaveDirectoryToDisk( void )
{
char szPath[ MAX_PATH ];
int i = GetDirectory().FirstInorder();
while ( GetDirectory().IsValidIndex( i ) )
{
SaveFile_t &file = GetFile( i );
i = GetDirectory().NextInorder( i );
const char *pName = GetString( file.name );
if ( Q_stristr( pName, ".hl" ) )
{
// Write the temporary save file to disk
Open( pName, "rb" );
Q_snprintf( szPath, sizeof( szPath ), "%s%s", saverestore->GetSaveDir(), pName );
g_pFileSystem->WriteFile( szPath, "GAME", *file.pBuffer );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Transfer all save files from disk to memory.
//-----------------------------------------------------------------------------
void CSaveRestoreFileSystem::LoadSaveDirectoryFromDisk( const char *pPath )
{
char const *findfn;
char szPath[ MAX_PATH ];
findfn = Sys_FindFirstEx( pPath, "DEFAULT_WRITE_PATH", NULL, 0 );
while ( findfn != NULL )
{
Q_snprintf( szPath, sizeof( szPath ), "%s%s", saverestore->GetSaveDir(), findfn );
// Add the temporary save file
FileHandle_t hFile = Open( findfn, "wb" );
if ( hFile )
{
SaveFile_t &file = GetFile( hFile );
g_pFileSystem->ReadFile( szPath, "GAME", *file.pBuffer );
file.nSize = file.pBuffer->TellMaxPut();
Close( hFile );
}
// Any more save files
findfn = Sys_FindNext( NULL, 0 );
}
Sys_FindClose();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSaveRestoreFileSystem::AuditFiles( void )
{
unsigned int nTotalFiles = 0;
unsigned int nTotalCompressed = 0;
unsigned int nTotalUncompressed = 0;
int i = GetDirectory().FirstInorder();
while ( GetDirectory().IsValidIndex( i ) )
{
SaveFile_t &file = GetFile( i );
i = GetDirectory().NextInorder( i );
nTotalFiles++;
nTotalCompressed += file.nCompressedSize;
nTotalUncompressed += file.nSize;
Msg("SIM: File: %s [c: %.02f KB / u: %.02f KB]\n", GetString( file.name ), (float)file.nCompressedSize/1024.0f, (float)file.nSize/1024.0f );
}
Msg("SIM: ------------------------------------------------------------");