/
fs_main.cpp
2020 lines (1719 loc) · 57 KB
/
fs_main.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
/**
* @file fs_main.cpp
*
* @ingroup fs
*
* @author Copyright © 2003-2012 Jaakko Keränen <jaakko.keranen@iki.fi>
* @author Copyright © 2006-2012 Daniel Swanson <danij@dengine.net>
* @author Copyright © 2006 Jamie Jones <jamie_jones_au@yahoo.com.au>
* @author Copyright © 1993-1996 by id Software, Inc.
*
* @par License
* GPL: http://www.gnu.org/licenses/gpl.html
*
* <small>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. This program is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details. You should have received a copy of the GNU
* General Public License along with this program; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA</small>
*/
#include <cstdlib>
#include <cctype>
#include <ctime>
#include "de_base.h"
#include "de_console.h"
#include "de_filesys.h"
#include "fileid.h"
#include "game.h"
#include "file.h"
#include "lumpindex.h"
#include "fileinfo.h"
#include "lumpfileadaptor.h"
#include "m_misc.h" // for M_FindWhite()
#include "wad.h"
#include "zip.h"
#include <QList>
#include <QtAlgorithms>
#include <de/Log>
#include <de/memory.h>
using namespace de;
D_CMD(Dir);
D_CMD(DumpLump);
D_CMD(ListFiles);
D_CMD(ListLumps);
static FS1* fileSystem;
struct FileInterpreter
{
resourcetype_t resourceType;
de::File1* (*interpret)(de::FileHandle& hndl, char const* path, FileInfo const& info);
};
static de::File1* interpretAsZipFile(de::FileHandle& hndl, char const* path, FileInfo const& info)
{
if(!Zip::recognise(hndl)) return 0;
LOG_VERBOSE("Interpreted \"") << F_PrettyPath(path) << "\" as a Zip (archive)";
return new Zip(hndl, path, info);
}
static de::File1* interpretAsWadFile(de::FileHandle& hndl, char const* path, FileInfo const& info)
{
if(!Wad::recognise(hndl)) return 0;
LOG_VERBOSE("Interpreted \"") << F_PrettyPath(path) << "\" as a Wad (archive)";
return new Wad(hndl, path, info);
}
/// @todo Order here should be determined by the resource locator.
static FileInterpreter interpreters[] = {
{ RT_ZIP, interpretAsZipFile },
{ RT_WAD, interpretAsWadFile },
{ RT_NONE, NULL }
};
typedef QList<FileId> FileIds;
/**
* Virtual (file) path => Lump name mapping.
*
* @todo We can't presently use a Map or Hash for these. Although the paths are
* unique, several of the existing algorithms which match using patterns
* assume they are sorted in a quasi load ordering.
*/
typedef QPair<QString, QString> LumpMapping;
typedef QList<LumpMapping> LumpMappings;
/**
* Virtual file-directory mapping.
* Maps one (absolute) path in the virtual file system to another.
*
* @todo We can't presently use a Map or Hash for these. Although the paths are
* unique, several of the existing algorithms which match using patterns
* assume they are sorted in a quasi load ordering.
*/
typedef QPair<QString, QString> PathMapping;
typedef QList<PathMapping> PathMappings;
static bool applyPathMapping(ddstring_t* path, PathMapping const& vdm);
struct FS1::Instance
{
/// Base for indicies in the auxiliary lump index.
static int const AUXILIARY_BASE = 100000000;
FS1* self;
/// @c true= Flag newly opened files as "startup".
bool loadingForStartup;
/// List of currently opened files.
FileList openFiles;
/// List of all loaded files present in the file system.
FileList loadedFiles;
/// Database of unique identifiers for all loaded/opened files.
FileIds fileIds;
LumpIndex zipLumpIndex;
LumpIndex primaryWadLumpIndex;
LumpIndex auxiliaryWadLumpIndex;
// @c true = one or more files have been opened using the auxiliary index.
bool auxiliaryWadLumpIndexInUse;
// Currently selected lump index.
LumpIndex* ActiveWadLumpIndex;
/// Virtual (file) path => Lump name mapping.
LumpMappings lumpMappings;
/// Virtual file-directory mapping.
PathMappings pathMappings;
Instance(FS1* d) : self(d), loadingForStartup(true),
openFiles(), loadedFiles(), fileIds(),
zipLumpIndex(LIF_UNIQUE_PATHS), primaryWadLumpIndex(),
auxiliaryWadLumpIndex(), auxiliaryWadLumpIndexInUse(false),
ActiveWadLumpIndex(&primaryWadLumpIndex)
{}
~Instance()
{
clearLoadedFiles();
clearOpenFiles();
clearLumpIndexes();
fileIds.clear(); // Should be null-op if bookkeeping is correct.
pathMappings.clear();
lumpMappings.clear();
}
/// @return @c true if the FileId associated with @a path was released.
bool releaseFileId(char const* path)
{
if(path && path[0])
{
FileId fileId = FileId::fromPath(path);
FileIds::iterator place = qLowerBound(fileIds.begin(), fileIds.end(), fileId);
if(place != fileIds.end() && *place == fileId)
{
#if _DEBUG
LOG_VERBOSE("Released FileId %s - \"%s\"") << *place << fileId.path();
#endif
fileIds.erase(place);
return true;
}
}
return false;
}
void clearLoadedFiles(de::LumpIndex* index = 0)
{
// Unload in reverse load order.
for(int i = loadedFiles.size() - 1; i >= 0; i--)
{
FileHandle& hndl = *(loadedFiles[i]);
if(!index || index->catalogues(hndl.file()))
{
releaseFileId(Str_Text(hndl.file().path()));
self->deindex(hndl.file());
loadedFiles.removeAt(i);
self->deleteFile(hndl);
}
}
}
void clearOpenFiles()
{
while(!openFiles.empty())
{ self->deleteFile(*openFiles.back()); }
}
/**
* Handles conversion to a logical index that is independent of the lump index currently in use.
*/
inline lumpnum_t logicalLumpNum(lumpnum_t lumpNum)
{
return (lumpNum < 0 ? -1 :
ActiveWadLumpIndex == &auxiliaryWadLumpIndex? lumpNum += AUXILIARY_BASE : lumpNum);
}
void clearLumpIndexes()
{
primaryWadLumpIndex.clear();
auxiliaryWadLumpIndex.clear();
zipLumpIndex.clear();
ActiveWadLumpIndex = 0;
}
void usePrimaryWadLumpIndex()
{
ActiveWadLumpIndex = &primaryWadLumpIndex;
}
bool useAuxiliaryWadLumpIndex()
{
if(!auxiliaryWadLumpIndexInUse) return false;
ActiveWadLumpIndex = &auxiliaryWadLumpIndex;
return true;
}
/**
* Selects which lump index to use, given a logical lump number.
* The lump number is then translated into range for the selected index.
* This should be called in all functions that access lumps by logical lump number.
*/
void selectWadLumpIndex(lumpnum_t& lumpNum)
{
if(lumpNum >= AUXILIARY_BASE)
{
useAuxiliaryWadLumpIndex();
lumpNum -= AUXILIARY_BASE;
}
else
{
usePrimaryWadLumpIndex();
}
}
de::FileHandle* tryOpenLump(char const* path, char const* /*mode*/, size_t /*baseOffset*/,
bool allowDuplicate, FileInfo& retInfo)
{
DENG_ASSERT(path && path[0]);
// Convert to an absolute path.
AutoStr* absSearchPath = AutoStr_FromTextStd(path);
F_PrependBasePath(absSearchPath, absSearchPath);
File1 const* found = 0;
// First check the Zip lump index.
lumpnum_t lumpNum = zipLumpIndex.indexForPath(Str_Text(absSearchPath));
if(lumpNum >= 0)
{
found = &zipLumpIndex.lump(lumpNum);
}
// Nope. Any applicable dir/WAD redirects?
else if(!lumpMappings.empty())
{
// We must have an absolute path - prepend the CWD if necessary.
Str_Set(absSearchPath, path);
F_PrependWorkPath(absSearchPath, absSearchPath);
DENG2_FOR_EACH(i, lumpMappings, LumpMappings::const_iterator)
{
LumpMapping const& mapping = *i;
QByteArray foundPathUtf8 = mapping.first.toUtf8();
if(qstricmp(foundPathUtf8.constData(), Str_Text(absSearchPath))) continue;
QByteArray foundLumpNameUtf8 = mapping.second.toUtf8();
lumpnum_t absoluteLumpNum = self->lumpNumForName(foundLumpNameUtf8.constData());
if(absoluteLumpNum < 0) continue;
found = &self->nameIndexForLump(absoluteLumpNum).lump(absoluteLumpNum);
}
}
// Nothing?
if(!found) return 0;
// Do not read files twice.
if(!allowDuplicate && !self->checkFileId(path)) return 0;
// Get a handle to the lump we intend to open.
/// @todo The way this buffering works is nonsensical it should not be done here
/// but should instead be deferred until the content of the lump is read.
FileHandle* hndl = FileHandleBuilder::fromFileLump(found->container(), found->info().lumpIdx, false/*dontBuffer*/);
// Prepare a temporary info descriptor.
retInfo = found->info();
return hndl;
}
de::FileHandle* tryOpenNativeFile(char const* path, char const* mymode, size_t baseOffset,
bool allowDuplicate, FileInfo& info)
{
DENG_ASSERT(path && path[0]);
// Translate mymode to the C-lib's fopen() mode specifiers.
char mode[8] = "";
if(strchr(mymode, 'r')) strcat(mode, "r");
else if(strchr(mymode, 'w')) strcat(mode, "w");
if(strchr(mymode, 'b')) strcat(mode, "b");
else if(strchr(mymode, 't')) strcat(mode, "t");
AutoStr* nativePath = AutoStr_FromTextStd(path);
F_ExpandBasePath(nativePath, nativePath);
// We must have an absolute path - prepend the CWD if necessary.
F_PrependWorkPath(nativePath, nativePath);
F_ToNativeSlashes(nativePath, nativePath);
AutoStr* foundPath = 0;
// First try a real native file at this absolute path.
FILE* nativeFile = fopen(Str_Text(nativePath), mode);
if(nativeFile)
{
foundPath = nativePath;
}
// Nope. Any applicable virtual directory mappings?
else if(!pathMappings.empty())
{
AutoStr* mapped = AutoStr_NewStd();
DENG2_FOR_EACH(i, pathMappings, PathMappings::const_iterator)
{
Str_Set(mapped, path);
if(!applyPathMapping(mapped, *i)) continue;
// The mapping was successful.
F_ToNativeSlashes(nativePath, mapped);
nativeFile = fopen(Str_Text(nativePath), mode);
if(nativeFile)
{
LOG_DEBUG("FS::tryOpenNativeFile: \"%s\" opened as %s.")
<< F_PrettyPath(Str_Text(mapped)) << path;
foundPath = mapped;
break;
}
}
}
// Nothing?
if(!nativeFile) return 0;
// Do not read files twice.
if(!allowDuplicate && !self->checkFileId(Str_Text(foundPath)))
{
fclose(nativeFile);
return 0;
}
// Acquire a handle on the file we intend to open.
FileHandle* hndl = FileHandleBuilder::fromNativeFile(*nativeFile, baseOffset);
// Prepare the temporary info descriptor.
info = FileInfo(F_GetLastModified(Str_Text(foundPath)));
return hndl;
}
de::File1* tryOpenFile(char const* path, char const* mode, size_t baseOffset,
bool allowDuplicate)
{
if(!path || !path[0]) return 0;
if(!mode) mode = "";
bool const reqNativeFile = !!strchr(mode, 'f');
// Make it a full path.
AutoStr* searchPath = AutoStr_FromTextStd(path);
F_FixSlashes(searchPath, searchPath);
F_ExpandBasePath(searchPath, searchPath);
DEBUG_VERBOSE2_Message(("FS1::tryOpenFile: trying to open %s\n", Str_Text(searchPath)));
FileHandle* hndl = 0;
FileInfo info; // The temporary info descriptor.
// First check for lumps?
if(!reqNativeFile)
{
hndl = tryOpenLump(Str_Text(searchPath), mode, baseOffset, allowDuplicate, info);
}
// Not found? - try a native file.
if(!hndl)
{
hndl = tryOpenNativeFile(Str_Text(searchPath), mode, baseOffset, allowDuplicate, info);
}
// Nothing?
if(!hndl) return 0;
// Search path is used here rather than found path as the latter may have
// been mapped to another location. We want the file to be attributed with
// the path it is to be known by throughout the virtual file system.
File1& file = self->interpret(*hndl, Str_Text(searchPath), info);
if(loadingForStartup)
{
file.setStartup(true);
}
return &file;
}
};
FS1::FS1()
{
d = new Instance(this);
FileHandleBuilder::init();
}
FS1::~FS1()
{
closeAuxiliary();
delete d;
FileHandleBuilder::shutdown();
}
void FS1::consoleRegister()
{
C_CMD("dir", "", Dir);
C_CMD("ls", "", Dir); // Alias
C_CMD("dir", "s*", Dir);
C_CMD("ls", "s*", Dir); // Alias
C_CMD("dump", "s", DumpLump);
C_CMD("listfiles", "", ListFiles);
C_CMD("listlumps", "", ListLumps);
}
/**
* @note Performance is O(n).
* @return @c iterator pointing to list->end() if not found.
*/
static FS1::FileList::iterator findListFileByPath(FS1::FileList& list, char const* path_)
{
if(list.empty()) return list.end();
if(!path_ || !path_[0]) return list.end();
// Transform the path into one we can process.
AutoStr* path = AutoStr_FromTextStd(path_);
F_FixSlashes(path, path);
// Perform the search.
FS1::FileList::iterator i;
for(i = list.begin(); i != list.end(); ++i)
{
de::File1& file = (*i)->file();
if(!Str_CompareIgnoreCase(file.path(), Str_Text(path)))
{
break; // This is the node we are looking for.
}
}
return i;
}
void FS1::index(de::File1& file)
{
// Publish lumps to an index?
if(Zip* zip = dynamic_cast<Zip*>(&file))
{
if(zip->empty()) return;
LumpIndex& index = d->zipLumpIndex;
// Insert the lumps into their rightful places in the index.
index.catalogLumps(*zip, 0, zip->lumpCount());
return;
}
if(Wad* wad = dynamic_cast<Wad*>(&file))
{
if(wad->empty()) return;
LumpIndex& index = *d->ActiveWadLumpIndex;
// Insert the lumps into their rightful places in the index.
index.catalogLumps(*wad, 0, wad->lumpCount());
return;
}
if(LumpFileAdaptor* lump = dynamic_cast<LumpFileAdaptor*>(&file))
{
LumpIndex& index = *d->ActiveWadLumpIndex;
// This *is* the lump, so insert ourself as a lump of our container in the index.
index.catalogLumps(lump->container(), lump->info().lumpIdx, lump->lumpCount());
return;
}
}
void FS1::deindex(de::File1& file)
{
d->zipLumpIndex.pruneByFile(file);
d->primaryWadLumpIndex.pruneByFile(file);
if(d->auxiliaryWadLumpIndexInUse)
d->auxiliaryWadLumpIndex.pruneByFile(file);
}
bool FS1::unloadFile(char const* path, bool permitRequired, bool quiet)
{
// Convert to an absolute path.
AutoStr* absolutePath = AutoStr_FromTextStd(path);
F_PrependBasePath(absolutePath, absolutePath);
FileList::iterator found = findListFileByPath(d->loadedFiles, Str_Text(absolutePath));
if(found == d->loadedFiles.end()) return false;
// Do not attempt to unload a resource required by the current game.
if(!permitRequired)
{
bool isRequired = false;
if(AbstractResource* const* records = reinterpret_cast<de::Game*>(App_CurrentGame())->resources(RC_PACKAGE, 0))
{
// Is this resource from a container?
lumpnum_t lumpNum = d->zipLumpIndex.indexForPath(Str_Text(absolutePath));
if(lumpNum >= 0)
{
// Yes; use the container's path instead.
Str_Copy(absolutePath, d->zipLumpIndex.lump(lumpNum).container().path());
}
for(AbstractResource* const* i = records; *i; i++)
{
AbstractResource* record = *i;
if(AbstractResource_ResourceFlags(record) & RF_STARTUP)
{
ddstring_t const* resolvedPath = AbstractResource_ResolvedPath(record, true);
if(resolvedPath && !Str_CompareIgnoreCase(resolvedPath, Str_Text(absolutePath)))
{
isRequired = true;
break;
}
}
}
}
if(isRequired)
{
if(!quiet)
{
Con_Message("\"%s\" is required by the current game.\n"
"Required game files cannot be unloaded in isolation.\n",
F_PrettyPath(Str_Text(absolutePath)));
}
return false;
}
}
if(!quiet && verbose >= 1)
{
Con_Message("Unloading \"%s\"...\n", F_PrettyPath(Str_Text(absolutePath)));
}
FileHandle& hndl = *(*found);
d->releaseFileId(Str_Text(hndl.file().path()));
deindex(hndl.file());
d->loadedFiles.erase(found);
deleteFile(hndl);
return true;
}
#if _DEBUG
static void printFileIds(FileIds const& fileIds)
{
uint idx = 0;
DENG2_FOR_EACH(i, fileIds, FileIds::const_iterator)
{
LOG_MSG(" %u - %s : \"%s\"") << idx << *i << i->path();
++idx;
}
}
#endif
#if _DEBUG
static void printFileList(FS1::FileList& list)
{
uint idx = 0;
DENG2_FOR_EACH(i, list, FS1::FileList::const_iterator)
{
de::FileHandle* hndl = *i;
de::File1& file = hndl->file();
FileId fileId = FileId::fromPath(Str_Text(file.path()));
LOG_MSG(" %c%d: %s - \"%s\" (handle: %p)")
<< (file.hasStartup()? '*' : ' ') << idx
<< fileId << fileId.path() << (void*)&hndl;
++idx;
}
}
#endif
FS1& FS1::unloadAllNonStartupFiles(int* retNumUnloaded)
{
#if _DEBUG
// List all open files with their identifiers.
if(verbose)
{
LOG_MSG("Open files at reset:");
printFileList(d->openFiles);
LOG_MSG("End\n");
}
#endif
// Perform non-startup file unloading (in reverse load order).
int numUnloaded = 0;
for(int i = d->loadedFiles.size() - 1; i >= 0; i--)
{
FileHandle& hndl = *(d->loadedFiles[i]);
File1& file = hndl.file();
if(file.hasStartup()) continue;
if(unloadFile(Str_Text(file.path()), true/*allow unloading game resources*/, true/*quiet please*/))
{
numUnloaded += 1;
}
}
#if _DEBUG
// Sanity check: look for orphaned identifiers.
if(!d->fileIds.empty())
{
LOG_MSG("Warning: Orphan FileIds:");
printFileIds(d->fileIds);
}
#endif
if(retNumUnloaded) *retNumUnloaded = numUnloaded;
return *this;
}
bool FS1::checkFileId(char const* path)
{
DENG_ASSERT(path);
if(!accessFile(path)) return false;
// Calculate the identifier.
FileId fileId = FileId::fromPath(path);
FileIds::iterator place = qLowerBound(d->fileIds.begin(), d->fileIds.end(), fileId);
if(place != d->fileIds.end() && *place == fileId) return false;
#if _DEBUG
LOG_VERBOSE("Added FileId %s - \"%s\"") << fileId << fileId.path();
#endif
d->fileIds.insert(place, fileId);
return true;
}
void FS1::resetFileIds()
{
d->fileIds.clear();
}
void FS1::endStartup()
{
d->loadingForStartup = false;
d->usePrimaryWadLumpIndex();
}
LumpIndex const& FS1::nameIndex() const
{
DENG_ASSERT(d->ActiveWadLumpIndex);
return *d->ActiveWadLumpIndex;
}
LumpIndex const& FS1::nameIndexForLump(lumpnum_t& absoluteLumpNum) const
{
if(absoluteLumpNum >= Instance::AUXILIARY_BASE)
{
absoluteLumpNum -= Instance::AUXILIARY_BASE;
return d->auxiliaryWadLumpIndex;
}
return d->primaryWadLumpIndex;
}
typedef enum lumpsizecondition_e {
LSCOND_NONE,
LSCOND_EQUAL,
LSCOND_GREATER_OR_EQUAL,
LSCOND_LESS_OR_EQUAL
} lumpsizecondition_t;
/**
* Modifies the name so that the size condition is removed.
*/
static void checkSizeConditionInName(ddstring_t* name, lumpsizecondition_t* pCond, size_t* pSize)
{
DENG_ASSERT(pCond != 0);
DENG_ASSERT(pSize != 0);
*pCond = LSCOND_NONE;
*pSize = 0;
int i, argPos = 0;
int len = Str_Length(name);
char const* txt = Str_Text(name);
for(i = 0; i < len - 2; ++i, ++txt)
{
if(!strncmp(txt, "==", 2))
{
*pCond = LSCOND_EQUAL;
argPos = i + 2;
break;
}
if(!strncmp(txt, ">=", 2))
{
*pCond = LSCOND_GREATER_OR_EQUAL;
argPos = i + 2;
break;
}
if(!strncmp(txt, "<=", 2))
{
*pCond = LSCOND_LESS_OR_EQUAL;
argPos = i + 2;
break;
}
}
if(!argPos) return;
// Get the argument.
*pSize = strtoul(txt + 2, NULL, 10);
// Remove it from the name.
Str_Truncate(name, i);
}
lumpnum_t FS1::lumpNumForName(char const* name, bool silent)
{
lumpnum_t lumpNum = -1;
if(name && name[0])
{
lumpsizecondition_t sizeCond;
size_t lumpSize = 0, refSize;
ddstring_t searchPath;
Str_InitStd(&searchPath); Str_Set(&searchPath, name);
// The name may contain a size condition (==, >=, <=).
checkSizeConditionInName(&searchPath, &sizeCond, &refSize);
// Append a .lmp extension if none is specified.
if(!F_FindFileExtension(name))
{
Str_Append(&searchPath, ".lmp");
}
// We have to check both the primary and auxiliary lump indexes
// because we've only got a name and don't know where it is located.
// Start with the auxiliary lumps because they have precedence.
if(d->useAuxiliaryWadLumpIndex())
{
lumpNum = d->ActiveWadLumpIndex->indexForPath(Str_Text(&searchPath));
if(lumpNum >= 0 && sizeCond != LSCOND_NONE)
{
// Get the size as well for the condition check.
lumpSize = d->ActiveWadLumpIndex->lump(lumpNum).info().size;
}
}
// Found it yet?
if(lumpNum < 0)
{
d->usePrimaryWadLumpIndex();
lumpNum = d->ActiveWadLumpIndex->indexForPath(Str_Text(&searchPath));
if(lumpNum >= 0 && sizeCond != LSCOND_NONE)
{
// Get the size as well for the condition check.
lumpSize = d->ActiveWadLumpIndex->lump(lumpNum).info().size;
}
}
// Check the condition.
switch(sizeCond)
{
case LSCOND_EQUAL:
if(lumpSize != refSize) lumpNum = -1;
break;
case LSCOND_GREATER_OR_EQUAL:
if(lumpSize < refSize) lumpNum = -1;
break;
case LSCOND_LESS_OR_EQUAL:
if(lumpSize > refSize) lumpNum = -1;
break;
default:
break;
}
// If still not found, warn the user.
if(!silent && lumpNum < 0)
{
if(sizeCond == LSCOND_NONE)
{
Con_Message("Warning: FS1::lumpNumForName: Lump \"%s\" not found.\n", name);
}
else
{
Con_Message("Warning: FS1::lumpNumForName: Lump \"%s\" with size%s%i not found.\n",
Str_Text(&searchPath), sizeCond==LSCOND_EQUAL? "==" :
sizeCond==LSCOND_GREATER_OR_EQUAL? ">=" : "<=", (int)refSize);
}
}
Str_Free(&searchPath);
}
else if(!silent)
{
Con_Message("Warning: FS1::lumpNumForName: Empty name, returning invalid lumpnum.\n");
}
return d->logicalLumpNum(lumpNum);
}
lumpnum_t FS1::openAuxiliary(char const* filePath, size_t baseOffset)
{
/// @todo Allow opening Zip files too.
File1* file = d->tryOpenFile(filePath, "rb", baseOffset, true /*allow duplicates*/);
if(Wad* wad = dynamic_cast<Wad*>(file))
{
if(d->auxiliaryWadLumpIndexInUse)
{
closeAuxiliary();
}
d->ActiveWadLumpIndex = &d->auxiliaryWadLumpIndex;
d->auxiliaryWadLumpIndexInUse = true;
index(*wad);
// Add a handle to the open files list.
FileHandle* openFilesHndl = FileHandleBuilder::fromFile(*wad);
d->openFiles.push_back(openFilesHndl); openFilesHndl->setList(reinterpret_cast<struct filelist_s*>(&d->openFiles));
// Add a handle to the loaded files list.
FileHandle* loadedFilesHndl = FileHandleBuilder::dup(*openFilesHndl);
d->loadedFiles.push_back(loadedFilesHndl); loadedFilesHndl->setList(reinterpret_cast<struct filelist_s*>(&d->loadedFiles));
return Instance::AUXILIARY_BASE;
}
delete file;
return -1;
}
void FS1::closeAuxiliary()
{
if(d->useAuxiliaryWadLumpIndex())
{
d->clearLoadedFiles(&d->auxiliaryWadLumpIndex);
d->auxiliaryWadLumpIndexInUse = false;
}
d->usePrimaryWadLumpIndex();
}
void FS1::releaseFile(de::File1& file)
{
for(int i = d->openFiles.size() - 1; i >= 0; i--)
{
FileHandle& hndl = *(d->openFiles[i]);
if(&hndl.file() == &file)
{
d->openFiles.removeAt(i);
}
}
}
void FS1::closeFile(de::FileHandle& hndl)
{
hndl.close();
}
void FS1::deleteFile(de::FileHandle& hndl)
{
closeFile(hndl);
delete &hndl.file();
delete &hndl;
}
/// @return @c NULL= Not found.
static Wad* findFirstWadFile(FS1::FileList& list, bool custom)
{
if(list.empty()) return 0;
DENG2_FOR_EACH(i, list, FS1::FileList::iterator)
{
de::File1& file = (*i)->file();
if(custom != file.hasCustom()) continue;
Wad* wad = dynamic_cast<Wad*>(&file);
if(wad) return wad;
}
return 0;
}
uint FS1::loadedFilesCRC()
{
/**
* We define the CRC as that of the lump directory of the first loaded IWAD.
* @todo Really kludgy...
*/
Wad* iwad = findFirstWadFile(d->loadedFiles, false/*not-custom*/);
if(!iwad) return 0;
return iwad->calculateCRC();
}
int FS1::findAll(FS1::FileList& found) const
{
int numFound = 0;
DENG2_FOR_EACH(i, d->loadedFiles, FS1::FileList::const_iterator)
{
found.push_back(*i);
numFound += 1;
}
return numFound;
}
int FS1::findAll(bool (*predicate)(de::FileHandle* hndl, void* parameters), void* parameters,
FS1::FileList& found) const
{
int numFound = 0;
DENG2_FOR_EACH(i, d->loadedFiles, FS1::FileList::const_iterator)
{
// Interested in this file?
if(predicate && !predicate(*i, parameters)) continue; // Nope.
found.push_back(*i);
numFound += 1;
}
return numFound;
}
int FS1::findAllPaths(char const* rawSearchPattern, int flags, FS1::PathList& found)
{
int const numFoundSoFar = found.count();
// First normalize the raw search pattern into one we can process.
AutoStr* searchPattern = AutoStr_NewStd();
Str_Set(searchPattern, rawSearchPattern);
Str_Strip(searchPattern);
F_FixSlashes(searchPattern, searchPattern);
F_ExpandBasePath(searchPattern, searchPattern);
// An absolute path is required so resolve relative to the base path.
// if not already absolute.
F_PrependBasePath(searchPattern, searchPattern);
PathMap patternMap;
PathMap_Initialize(&patternMap, PathDirectory::hashPathFragment, Str_Text(searchPattern));
/*
* Check the Zip directory.
*/
DENG2_FOR_EACH(i, d->zipLumpIndex.lumps(), LumpIndex::Lumps::const_iterator)
{
File1 const& lump = **i;
PathDirectoryNode const& node = lump.container().lumpDirectoryNode(lump.info().lumpIdx);
AutoStr* filePath = 0;
bool patternMatched;
if(!(flags & SPF_NO_DESCEND))
{
filePath = lump.container().composeLumpPath(lump.info().lumpIdx);
patternMatched = F_MatchFileName(Str_Text(filePath), Str_Text(searchPattern));
}
else
{
patternMatched = node.matchDirectory(PCF_MATCH_FULL, &patternMap);
if(patternMatched)
{
filePath = lump.container().composeLumpPath(lump.info().lumpIdx);
}
}
if(!patternMatched) continue;
found.push_back(PathListItem(Str_Text(filePath), node.type() == PT_BRANCH? A_SUBDIR : 0));
}
PathMap_Destroy(&patternMap);
/*
* Check the dir/WAD direcs.
*/