forked from shokunin000/te120
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxzp.cpp
1323 lines (1051 loc) · 34.7 KB
/
xzp.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:
//
//=============================================================================
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <malloc.h>
#ifdef _WIN32
#include <process.h>
#include <io.h>
#endif
#include <stddef.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "tier1/utlbuffer.h"
#include "tier1/strtools.h"
#include "tier2/riff.h"
#if defined( _WIN32 ) && !defined( _X360 )
#include <windows.h>
#endif
#ifdef MAKE_GAMEDATA_TOOL
#include "../public/materialsystem/shader_vcs_version.h"
#include "../public/materialsystem/imaterial.h"
#include "../public/materialsystem/hardwareverts.h"
#include "../public/vtf/vtf.h"
#else
#include "materialsystem/shader_vcs_version.h"
#include "materialsystem/imaterial.h"
#include "materialsystem/hardwareverts.h"
#endif
#include "xwvfile.h"
#include "xzp.h"
CByteswap g_xzpSwap;
extern IFileReadBinary *g_pSndIO;
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//-----------------------------------------------------------------------------
// Datadesc blocks for byteswapping:
//-----------------------------------------------------------------------------
BEGIN_BYTESWAP_DATADESC( xZipHeader_t )
DEFINE_FIELD( Magic, FIELD_INTEGER ),
DEFINE_FIELD( Version, FIELD_INTEGER ),
DEFINE_FIELD( PreloadDirectoryEntries, FIELD_INTEGER ),
DEFINE_FIELD( DirectoryEntries, FIELD_INTEGER ),
DEFINE_FIELD( PreloadBytes, FIELD_INTEGER ),
DEFINE_FIELD( HeaderLength, FIELD_INTEGER ),
DEFINE_FIELD( FilenameEntries, FIELD_INTEGER ),
DEFINE_FIELD( FilenameStringsOffset, FIELD_INTEGER ),
DEFINE_FIELD( FilenameStringsLength, FIELD_INTEGER ),
END_BYTESWAP_DATADESC()
BEGIN_BYTESWAP_DATADESC( xZipDirectoryEntry_t )
DEFINE_FIELD( FilenameCRC, FIELD_INTEGER ),
DEFINE_FIELD( Length, FIELD_INTEGER ),
DEFINE_FIELD( StoredOffset, FIELD_INTEGER ),
END_BYTESWAP_DATADESC()
BEGIN_BYTESWAP_DATADESC( xZipFilenameEntry_t )
DEFINE_FIELD( FilenameCRC, FIELD_INTEGER ),
DEFINE_FIELD( FilenameOffset, FIELD_INTEGER ),
DEFINE_FIELD( TimeStamp, FIELD_INTEGER ),
END_BYTESWAP_DATADESC()
BEGIN_BYTESWAP_DATADESC( xZipFooter_t )
DEFINE_FIELD( Size, FIELD_INTEGER ),
DEFINE_FIELD( Magic, FIELD_INTEGER ),
END_BYTESWAP_DATADESC()
CXZip::CXZip()
{
// Ensure that the header doesn't contain a valid magic yet.
m_Header.Magic = 0;
m_pPreloadedData = NULL;
m_nPreloadStart = 0;
m_pDirectory = NULL;
m_pPreloadDirectory = NULL;
m_nRegular2PreloadEntryMapping = NULL;
m_bByteSwapped = false;
m_pFilenames = NULL;
m_hZip = NULL;
m_pRead = NULL;
m_hUser = 0;
m_nMonitorLevel = 0;
}
CXZip::CXZip( const char* filename )
{
// Ensure that the header doesn't contain a valid magic yet.
m_Header.Magic = 0;
m_nPreloadStart = 0;
m_pPreloadedData = NULL;
m_pDirectory = NULL;
m_pPreloadDirectory = NULL;
m_nRegular2PreloadEntryMapping = NULL;
m_bByteSwapped = false;
m_pFilenames = NULL;
m_hZip = NULL;
m_pRead = NULL;
m_hUser = 0;
m_nMonitorLevel = 0;
Load( filename );
}
CXZip::CXZip( FILE* handle, int offset, int size ) // file handle and offset of the zip file
{
m_pRead = NULL;
m_hUser = 0;
m_nPreloadStart = 0;
m_pDirectory = NULL;
m_pPreloadDirectory = NULL;
m_nRegular2PreloadEntryMapping = NULL;
m_bByteSwapped = false;
m_pFilenames = NULL;
m_pPreloadedData = NULL;
m_nMonitorLevel = 0;
Load( handle, offset, size );
}
CXZip::~CXZip()
{
Unload();
}
bool CXZip::InstallAlternateIO( int (*read)( void* buffer, int offset, int length, int nDestLength, int hUser), int hUser )
{
m_pRead = read;
m_hUser = hUser;
return true;
}
// Loads an xZip file into memory:
bool CXZip::Load( const char* filename, bool bPreload )
{
FILE* hZip = fopen( filename, "rb" );
fseek(hZip,0,SEEK_END);
int nSize = ftell( hZip );
return Load( hZip, 0, nSize, bPreload );
}
bool CXZip::Load( FILE* handle, int nOffset, int nSize, bool bPreload ) // Load a pack file into this instance. Returns true on success.
{
Unload();
m_bByteSwapped = false;
m_hZip = handle;
m_nOffset = nOffset;
m_nSize = nSize;
// Hacky, clean up:
if( m_hZip && !m_pRead )
{
InstallAlternateIO( defaultRead, (int)m_hZip );
}
if( m_hZip == NULL && m_pRead == NULL )
{
return false;
}
// Read the header:
m_pRead( &m_Header, 0, -1, sizeof(m_Header), m_hUser );
// Validate the Magic number and at the same time determine if I am reading a regular or swappped xZip file:
switch( m_Swap.SourceIsNativeEndian<int>( m_Header.Magic, xZipHeader_t::MAGIC ) )
{
// Does the magic match exactly?
case 1:
m_Swap.ActivateByteSwapping( false );
m_bByteSwapped = false;
break;
// Does the magic match, but is swapped?
case 0:
m_bByteSwapped = true;
m_Swap.ActivateByteSwapping( true ); // We must be reading the opposite endianness.
m_Swap.SwapFieldsToTargetEndian<xZipHeader_t>( &m_Header );
break;
default:
assert( 0 );
// Fail gently in release:
// The magic doesn't match in any respect:
case -1:
{
printf("Invalid xZip file\n");
if( m_hZip )
{
fclose( m_hZip );
m_hZip = NULL;
}
return false;
}
}
// Validate the archive version:
if( m_Header.Version != xZipHeader_t::VERSION )
{
// Backward compatable support for version 1
Msg("Incorrect xZip version found %u - expected %u\n", m_Header.Version, xZipHeader_t::VERSION );
if( m_hZip )
{
fclose( m_hZip );
m_hZip = NULL;
}
m_Header.Magic = xZipHeader_t::FREE;
return false;
}
// Read the directory:
{
MEM_ALLOC_CREDIT();
m_pDirectory = (xZipDirectoryEntry_t*)malloc( sizeof(xZipDirectoryEntry_t) * m_Header.DirectoryEntries );
m_pRead( m_pDirectory, m_Header.HeaderLength, -1, sizeof( xZipDirectoryEntry_t ) * m_Header.DirectoryEntries, m_hUser );
// Swap the directory entries if nessecary
if( m_bByteSwapped )
{
for( unsigned nDirectoryEntry = 0; nDirectoryEntry < m_Header.DirectoryEntries; nDirectoryEntry++ )
{
m_Swap.SwapFieldsToTargetEndian<xZipDirectoryEntry_t>( &( m_pDirectory[nDirectoryEntry] ) );
}
}
m_nPreloadStart = m_Header.HeaderLength + ( sizeof( xZipDirectoryEntry_t ) * m_Header.DirectoryEntries );
}
// Preload the preload chunk if desired:
if( bPreload )
{
PreloadData();
}
return true;
}
void CXZip::Unload()
{
DiscardPreloadedData();
// Dump the directory:
if( m_pDirectory )
{
free( m_pDirectory );
m_pDirectory = NULL;
}
if( m_pFilenames )
{
free( m_pFilenames );
m_pFilenames = NULL;
}
// Invalidate the header:
m_Header.Magic = 0;
if( m_hZip )
{
fclose( m_hZip );
m_hZip = NULL;
}
}
//-----------------------------------------------------------------------------
// CXZip::PreloadData
//
// Loads the preloaded data if it isn't already.
//-----------------------------------------------------------------------------
void CXZip::PreloadData()
{
Assert( IsValid() );
// Ensure it isn't already preloaded
if( m_pPreloadedData )
return;
// If I don't have a preloaded section, ignore the request.
if( !m_Header.PreloadBytes || !m_Header.PreloadDirectoryEntries )
return;
// Allocate and read the data block in:
#ifndef _X360
MEM_ALLOC_CREDIT_( "xZip" );
m_pPreloadedData = malloc( m_Header.PreloadBytes );
// Just drop out if allocation fails;
if ( !m_pPreloadedData )
return;
m_pRead( m_pPreloadedData, m_nPreloadStart, -1, m_Header.PreloadBytes, m_hUser );
#else
int nAlignedStart = AlignValue( ( m_nPreloadStart - XBOX_HDD_SECTORSIZE ) + 1, XBOX_HDD_SECTORSIZE );
int nBytesToRead = AlignValue( ( m_nPreloadStart - nAlignedStart ) + m_Header.PreloadBytes, XBOX_HDD_SECTORSIZE );
int nBytesBuffer = AlignValue( nBytesToRead, XBOX_HDD_SECTORSIZE );
byte *pReadData = (byte *)malloc( nBytesBuffer );
// Just drop out if allocation fails;
if ( !pReadData )
return;
MEM_ALLOC_CREDIT_( "xZip" );
m_pRead( pReadData, nAlignedStart, nBytesBuffer,nBytesToRead, m_hUser );
m_pPreloadedData = pReadData + ( m_nPreloadStart - nAlignedStart );
#endif
// Set up the preload directory:
m_pPreloadDirectory = (xZipDirectoryEntry_t*)m_pPreloadedData;
// Swap the preload directory:
if ( m_bByteSwapped )
{
for ( unsigned nDirectoryEntry = 0; nDirectoryEntry < m_Header.PreloadDirectoryEntries; nDirectoryEntry++ )
{
m_Swap.SwapFieldsToTargetEndian<xZipDirectoryEntry_t>( &( m_pPreloadDirectory[nDirectoryEntry] ) );
}
}
// Set up the regular 2 preload mapping section:
m_nRegular2PreloadEntryMapping = (unsigned short*)(((unsigned char*)m_pPreloadDirectory) + ( sizeof(xZipDirectoryEntry_t) * m_Header.PreloadDirectoryEntries ));
// Swap the regular to preload mapping
if ( m_bByteSwapped )
{
m_Swap.SwapBufferToTargetEndian<short>( (short *)m_nRegular2PreloadEntryMapping, (short *)m_nRegular2PreloadEntryMapping, m_Header.DirectoryEntries );
}
}
//-----------------------------------------------------------------------------
// CXZip::DiscardPreloadedData
//
// frees the preloaded data cache if it's present.
//-----------------------------------------------------------------------------
void CXZip::DiscardPreloadedData()
{
if ( m_pPreloadedData )
{
#ifndef _X360
free( m_pPreloadedData );
#else
int nAlignedStart = AlignValue( ( m_nPreloadStart - XBOX_HDD_SECTORSIZE ) + 1, XBOX_HDD_SECTORSIZE );
byte *pReadData = (byte *)m_pPreloadedData - ( m_nPreloadStart - nAlignedStart );
free( pReadData );
#endif
m_pPreloadedData = NULL;
m_pPreloadDirectory = NULL;
m_nRegular2PreloadEntryMapping = NULL;
}
}
int CXZip::defaultRead( void* buffer, int offset, int destLength, int length, int hUser)
{
fseek( (FILE*)hUser, offset, SEEK_SET );
return fread( buffer, 1, length, (FILE*)hUser );
}
char* CXZip::GetEntryFileName( unsigned CRC, char* pDefault )
{
Assert( IsValid() );
if( IsRetail() )
{
return pDefault;
}
else
{
// Make sure I have a filename section:
if( m_Header.FilenameStringsOffset == 0 || m_Header.FilenameEntries == 0 || CRC == 0 )
{
return pDefault;
}
// If the filename chunk isn't here, load it up:
if( !m_pFilenames )
{
MEM_ALLOC_CREDIT_("xZip");
m_pFilenames = (xZipFilenameEntry_t*)malloc( m_Header.FilenameStringsLength );
m_pRead( m_pFilenames, m_Header.FilenameStringsOffset, -1, m_Header.FilenameStringsLength, m_hUser );
// TODO: Swap!
for( unsigned int i=0; i< m_Header.FilenameEntries;i++ )
{
m_Swap.SwapFieldsToTargetEndian<xZipFilenameEntry_t>(&m_pFilenames[i]);
}
}
// Find this entry in the preload directory
xZipFilenameEntry_t entry;
entry.FilenameCRC = CRC;
xZipFilenameEntry_t* found = (xZipFilenameEntry_t*)bsearch( &entry, m_pFilenames, m_Header.FilenameEntries, sizeof(xZipFilenameEntry_t), xZipFilenameEntry_t::xZipFilenameEntryCompare );
if( !found )
return pDefault;
return (((char*)m_pFilenames) + found->FilenameOffset) - m_Header.FilenameStringsOffset;
}
}
// Sanity checks that the zip file is ready and readable:
bool CXZip::IsValid()
{
if( m_Header.Magic != xZipHeader_t::MAGIC )
return false;
if( m_Header.Version > xZipHeader_t::VERSION )
return false;
if( !m_pDirectory )
return false;
return true;
}
void CXZip::WarningDir()
{
Assert( IsValid());
for( unsigned i = 0; i< m_Header.DirectoryEntries; i++ )
{
Msg( GetEntryFileName( m_pDirectory[i].FilenameCRC ) );
}
}
int CXZip::ReadIndex( int nEntryIndex, int nFileOffset, int nDestBytes, int nLength, void* pBuffer )
{
Assert( IsValid() );
if( nLength <=0 || nEntryIndex < 0 )
return 0;
// HACK HACK HACK - convert the pack file index to a local file index (ie, assuming the full file index is being passed in)
nFileOffset -= m_pDirectory[nEntryIndex].StoredOffset;
// HACK HACK HACK
// If I've got my preload section loaded, first check there:
xZipDirectoryEntry_t* pPreloadEntry = GetPreloadEntry(nEntryIndex);
if( pPreloadEntry )
{
Assert( pPreloadEntry->FilenameCRC == m_pDirectory[nEntryIndex].FilenameCRC );
if( nFileOffset + nLength <= (int)pPreloadEntry->Length )
{
if( m_nMonitorLevel >= 2 )
{
char* filename = GetEntryFileName( m_pDirectory[nEntryIndex].FilenameCRC, "(!!! unknown !!!)" );
Msg("PACK(preload) %s: length:%i offset:%i",filename,nLength, nFileOffset);
}
memcpy( pBuffer, (char*)m_pPreloadedData + pPreloadEntry->StoredOffset + nFileOffset - m_nPreloadStart, nLength );
return nLength;
}
}
// Offset int the zip to start the read:
int ZipOffset = m_pDirectory[nEntryIndex].StoredOffset + nFileOffset;
int nBytesRead = m_pRead( pBuffer, ZipOffset, nDestBytes, nLength, m_hUser);
if( m_nMonitorLevel )
{
char* filename = GetEntryFileName( m_pDirectory[nEntryIndex].FilenameCRC, "(!!! unknown !!!)" );
unsigned preload = 0;
if( m_pPreloadedData && m_nRegular2PreloadEntryMapping[nEntryIndex] != 0xFFFF )
{
// Find this entry in the preload directory
xZipDirectoryEntry_t* entry = &(m_pPreloadDirectory[m_nRegular2PreloadEntryMapping[nEntryIndex]]);
Assert(entry->FilenameCRC == m_pDirectory[nEntryIndex].FilenameCRC);
preload = entry->Length;
}
Msg("PACK %s: length:%i offset:%i (preload bytes:%i)",filename,nLength, nFileOffset, preload);
}
return nBytesRead;
}
bool CXZip::GetSimpleFileOffsetLength( const char* FileName, int& nBaseIndex, int &nFileOffset, int &nLength )
{
Assert( IsValid() );
xZipDirectoryEntry_t entry;
entry.FilenameCRC = xZipCRCFilename( FileName );
xZipDirectoryEntry_t* found = (xZipDirectoryEntry_t*)bsearch( &entry, m_pDirectory, m_Header.DirectoryEntries, sizeof(xZipDirectoryEntry_t), xZipDirectoryEntry_t::xZipDirectoryEntryFindCompare );
if( found == NULL )
return false;
nFileOffset = found[0].StoredOffset;
nLength = found[0].Length;
nBaseIndex = (((int)((char*)found - (char*)m_pDirectory))/sizeof(xZipDirectoryEntry_t));
return true;
}
bool CXZip::ExtractFile( const char* FileName )
{
return false;
}
// Compares to xZipDirectoryEntries.
//
// Sorts in the following order:
// FilenameCRC
// FileOffset
// Length
// StoredOffset
//
// The sort function may look overly complex, but it is actually useful for locating different pieces of
// the same file in a meaningful order.
//
int __cdecl xZipDirectoryEntry_t::xZipDirectoryEntrySortCompare( const void* left, const void* right )
{
xZipDirectoryEntry_t *l = (xZipDirectoryEntry_t*)left,
*r = (xZipDirectoryEntry_t*)right;
if( l->FilenameCRC < r->FilenameCRC )
{
return -1;
}
else if( l->FilenameCRC > r->FilenameCRC )
{
return 1;
}
// else l->FileOffset == r->FileOffset
if( l->Length < r->Length )
{
return -1;
}
else if( l->Length > r->Length )
{
return 1;
}
// else l->Length == r->Length
if( l->StoredOffset < r->StoredOffset )
{
return -1;
}
else if( l->StoredOffset > r->StoredOffset )
{
return 1;
}
// else everything is identical:
return 0;
}
// Find an entry with matching CRC only
int __cdecl xZipDirectoryEntry_t::xZipDirectoryEntryFindCompare( const void* left, const void* right )
{
xZipDirectoryEntry_t *l = (xZipDirectoryEntry_t*)left,
*r = (xZipDirectoryEntry_t*)right;
if( l->FilenameCRC < r->FilenameCRC )
{
return -1;
}
else if( l->FilenameCRC > r->FilenameCRC )
{
return 1;
}
return 0;
}
int __cdecl xZipFilenameEntry_t::xZipFilenameEntryCompare( const void* left, const void* right )
{
xZipFilenameEntry_t *l = (xZipFilenameEntry_t*)left,
*r = (xZipFilenameEntry_t*)right;
if( l->FilenameCRC < r->FilenameCRC )
{
return -1;
}
else if( l->FilenameCRC > r->FilenameCRC )
{
return 1;
}
return 0;
}
// CRC's an individual xZip filename:
unsigned xZipCRCFilename( const char* filename )
{
unsigned hash = 0xAAAAAAAA; // Alternating 1's and 0's
for( ; *filename ; filename++ )
{
char c = *filename;
// Fix slashes
if( c == '/' )
c = '\\';
else
c = (char)tolower(c);
hash = hash * 33 + c;
}
return hash;
}
#if defined( MAKE_GAMEDATA_TOOL )
// ------------
xZipHeader_t Header;
xZipDirectoryEntry_t *pDirectoryEntries = NULL;
xZipDirectoryEntry_t *pPreloadDirectoryEntries = NULL;
xZipFilenameEntry_t *pFilenameEntries = NULL;
char *pFilenameData = NULL;
unsigned nFilenameDataLength = 0;
unsigned InputFileBytes = 0;
char* CleanFilename( char* filename )
{
// Trim leading white space:
while( isspace(*filename) )
filename++;
// Trim trailing white space:
while( isspace( filename[strlen(filename)-1] ) )
{
filename[strlen(filename)-1] = '\0';
}
return filename;
}
bool CopyFileBytes( FILE* hDestination, FILE* hSource, unsigned nBytes )
{
char buffer[16384];
while( nBytes > 0 )
{
int nBytesRead = fread( buffer, 1, nBytes > sizeof(buffer) ? sizeof(buffer) : nBytes, hSource );
fwrite(buffer, 1, nBytesRead, hDestination );
nBytes -= nBytesRead;
}
return true;
}
bool WriteFileBytes( FILE* hDestination, CUtlBuffer &source, unsigned nBytes )
{
unsigned int nBytesWritten = fwrite(source.Base(), 1, nBytes, hDestination );
return (nBytesWritten == nBytes);
}
void PadFileBytes(FILE* hFile, int nPreloadPadding )
{
if( nPreloadPadding < 0 || nPreloadPadding >= 512)
{
puts("Invalid padding");
return;
}
char padding[512];
memset(padding,0,nPreloadPadding);
fwrite(padding,1,nPreloadPadding,hFile);
}
void AddFilename( const char* filename )
{
unsigned CRCfilename = xZipCRCFilename( filename );
// If we already have this filename don't add it again:
for( int i = 0; i < (int)Header.FilenameEntries; i++ )
{
if( pFilenameEntries[i].FilenameCRC == CRCfilename )
{
return;
}
}
Header.FilenameEntries++;
// Add the file to the file string table:
pFilenameEntries = (xZipFilenameEntry_t*)realloc( pFilenameEntries, sizeof(xZipFilenameEntry_t) * Header.FilenameEntries );
int filenameLength = (int)strlen(filename) + 1;
pFilenameEntries[Header.FilenameEntries-1].FilenameCRC = CRCfilename;
pFilenameEntries[Header.FilenameEntries-1].FilenameOffset = nFilenameDataLength;
// Grab the timestamp for the file:
struct stat buf;
if( stat( filename, &buf ) != -1 )
{
pFilenameEntries[Header.FilenameEntries - 1].TimeStamp = buf.st_mtime;
}
else
{
pFilenameEntries[Header.FilenameEntries - 1].TimeStamp = 0;
}
nFilenameDataLength += filenameLength;
pFilenameData = (char*)realloc(pFilenameData, nFilenameDataLength);
memcpy(pFilenameData + nFilenameDataLength - filenameLength, filename, filenameLength);
}
FILE* hTempFilePreload;
FILE* hTempFileData;
FILE* hOutputFile;
bool xZipAddFile( const char* filename, CUtlBuffer &fileBuff, bool bPrecacheEntireFile, bool bProcessPrecacheHeader, bool bProcessPrecacheHeaderOnly )
{
unsigned int fileSize = fileBuff.TellMaxPut();
// Track total input bytes for stats reasons
InputFileBytes += fileSize;
unsigned customPreloadSize = 0;
if( bPrecacheEntireFile )
{
customPreloadSize = fileSize;
}
else if( bProcessPrecacheHeader )
{
customPreloadSize = xZipComputeCustomPreloads( filename );
}
else if( bProcessPrecacheHeaderOnly )
{
customPreloadSize = xZipComputeCustomPreloads( filename );
fileSize = min( fileSize, customPreloadSize );
}
unsigned CRC = xZipCRCFilename( filename );
// Does this file have a split header?
if( customPreloadSize > 0 )
{
// Initialize the entry header:
xZipDirectoryEntry_t entry;
memset( &entry, 0, sizeof( entry ) );
entry.FilenameCRC = CRC;
entry.Length = customPreloadSize;
entry.StoredOffset = ftell(hTempFilePreload);
// Add the directory entry to the preload table:
Header.PreloadDirectoryEntries++;
pPreloadDirectoryEntries = (xZipDirectoryEntry_t*)realloc( pPreloadDirectoryEntries, sizeof( xZipDirectoryEntry_t ) * Header.PreloadDirectoryEntries );
memcpy( pPreloadDirectoryEntries + Header.PreloadDirectoryEntries - 1, &entry, sizeof( entry ) );
// Concatenate the data in the preload file:
fileBuff.SeekGet( CUtlBuffer::SEEK_HEAD, 0 );
WriteFileBytes( hTempFilePreload, fileBuff, entry.Length );
fileBuff.SeekGet( CUtlBuffer::SEEK_HEAD, 0 );
// Add the filename entry:
AddFilename( filename );
// Spew it:
printf("+Preload: \"%s\": Length:%u\n", filename, entry.Length );
}
// Copy the file to the regular data region:
xZipDirectoryEntry_t entry;
memset(&entry,0,sizeof(entry));
entry.FilenameCRC = CRC;
entry.Length = fileSize;
entry.StoredOffset = ftell(hTempFileData);
// Add the directory entry to the table:
Header.DirectoryEntries++;
pDirectoryEntries = (xZipDirectoryEntry_t*)realloc( pDirectoryEntries, sizeof( xZipDirectoryEntry_t ) * Header.DirectoryEntries );
memcpy( pDirectoryEntries + Header.DirectoryEntries - 1, &entry, sizeof( entry ) );
WriteFileBytes( hTempFileData, fileBuff, entry.Length );
// Align the data region to a 512 byte boundry: (has to be on last entry as well to ensure enough space to perform the final read,
// and initial alignment is taken careof by assembexzip)
int nPadding = ( XBOX_HDD_SECTORSIZE - ( ftell( hTempFileData ) % XBOX_HDD_SECTORSIZE) ) % XBOX_HDD_SECTORSIZE;
PadFileBytes( hTempFileData, nPadding );
// Add the file to the file string table:
AddFilename( filename );
// Print a summary
printf("+File: \"%s\": Length:%u Padding:%i\n", filename, entry.Length, nPadding );
return true;
}
bool xZipAddFile( const char* zipname, bool bPrecacheEntireFile, bool bProcessPrecacheHeader, bool bProcessPrecacheHeaderOnly )
{
// Clean up the filename:
char buffer[MAX_PATH];
strcpy(buffer, zipname);
// Fix slashes and convert it to lower case:
char *filename;
for( filename = buffer; *filename; filename++ )
{
if( *filename == '/' )
*filename = '\\';
else
{
*filename = (char)tolower(*filename);
}
}
// Skip leading white space:
for( filename = buffer; isspace(*filename); filename++ )
;
// Obliterate trailing white space:
for(;;)
{
int len = (int)strlen( filename );
if( len <= 0 )
{
printf("!!!! BAD FILENAME: \"%s\"\n", filename );
return false;
}
if( isspace( filename[len-1] ) )
filename[len-1]='\0';
else
break;
}
// Ensure we don't already have this file:
unsigned CRC = xZipCRCFilename( filename );
for( unsigned i=0; i < Header.DirectoryEntries; i++ )
{
if( pDirectoryEntries[i].FilenameCRC == CRC )
{
printf("!!!! NOT ADDING DUPLICATE FILENAME: \"%s\"\n", filename );
return false;
}
}
// Attempt to open the file:
FILE* hFile = fopen( filename, "rb" );
if( !hFile )
{
printf("!!!! FAILED TO OPEN FILE: \"%s\"\n", filename );
return false;
}
// Get the length of the file:
fseek(hFile,0,SEEK_END);
unsigned fileSize = ftell(hFile);
fseek(hFile,0,SEEK_SET);
CUtlBuffer fileBuff;
fileBuff.EnsureCapacity( fileSize );
fread( fileBuff.Base(), fileSize, 1, hFile );
fclose( hFile );
fileBuff.SeekPut( CUtlBuffer::SEEK_HEAD, fileSize );
return xZipAddFile( zipname, fileBuff, bPrecacheEntireFile, bProcessPrecacheHeader, bProcessPrecacheHeaderOnly );
}
int xZipBegin( const char* fileNameXzip )
{
// Create and initialize the header:
memset( &Header, 0, sizeof(Header) ); // Zero out the header:
Header.Magic = xZipHeader_t::MAGIC;
Header.Version = xZipHeader_t::VERSION;
Header.HeaderLength = sizeof(Header);
// Open the output file:
hOutputFile = fopen(fileNameXzip,"wb+");
if( !hOutputFile )
{
printf("Failed to open \"%s\" for writing.\n", fileNameXzip);
exit( EXIT_FAILURE);
}
// Create a temporary file for storing the preloaded data:
hTempFilePreload = tmpfile();
if( !hTempFilePreload )
{
printf( "Error: failed to create temporary file\n" );
return EXIT_FAILURE;
}
// Create a temporary file for storing the non preloaded data
hTempFileData = tmpfile();
if( !hTempFileData )
{
printf( "Error: failed to create temporary file\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
bool xZipEnd()
{
int nPreloadDirectorySize = sizeof(xZipDirectoryEntry_t)*Header.PreloadDirectoryEntries;
int nRegular2PreloadSize = sizeof(unsigned short) * Header.DirectoryEntries;
// Compute the size of the preloaded section:
if( Header.PreloadDirectoryEntries )
{
fseek( hTempFilePreload, 0, SEEK_END );
Header.PreloadBytes = ftell(hTempFilePreload) + nPreloadDirectorySize + nRegular2PreloadSize; // Raw# of bytes to preload
fseek( hTempFilePreload, 0, SEEK_SET );
}
else
{
Header.PreloadBytes = 0;
}
// Number of bytes preceeding the preloaded section:
int nPreloadOffset = sizeof( Header ) + ( sizeof( xZipDirectoryEntry_t ) * Header.DirectoryEntries );
// Number of bytes to pad between the end of the preload section and the start of the data section:
int nPadding = ( 512 - ( ( nPreloadOffset + Header.PreloadBytes ) % 512) ) %512; // Number of alignment bytes after the preload section
// Offset past the preload section:
int nDataOffset = nPreloadOffset + Header.PreloadBytes + nPadding;
// Write out the header: (will need to be rewritten at the end as well) - note: not even bothering to byteswap at this point
fwrite(&Header,sizeof(Header),1,hOutputFile);
// Fixup each of the directory entries to make them relative to the beginning of the file.
for( unsigned i=0; i< Header.DirectoryEntries;i++ )
{
xZipDirectoryEntry_t* pDir = &(pDirectoryEntries[i]);
// Adjust files in the regular data area:
pDir->StoredOffset = nDataOffset + pDir->StoredOffset;
}
// Sort and write the directory:
printf("Sorting and writing %i directory entries...\n",Header.DirectoryEntries);
qsort(pDirectoryEntries,Header.DirectoryEntries,sizeof(xZipDirectoryEntry_t),&xZipDirectoryEntry_t::xZipDirectoryEntrySortCompare);
// Swap the directory entries:
for( unsigned i=0; i < Header.DirectoryEntries; i++ )
{
g_xzpSwap.SwapFieldsToTargetEndian<xZipDirectoryEntry_t>(&pDirectoryEntries[i]);
}
fwrite(pDirectoryEntries,Header.DirectoryEntries*sizeof(xZipDirectoryEntry_t),1, hOutputFile);
// Swap the directory back for later use:
for( unsigned i=0; i < Header.DirectoryEntries; i++ )
{
g_xzpSwap.SwapFieldsToTargetEndian<xZipDirectoryEntry_t>(&pDirectoryEntries[i]);
}