forked from scummvm/scummvm
/
resource.cpp
1614 lines (1329 loc) · 42.4 KB
/
resource.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
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* 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 Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "common/str.h"
#ifndef MACOSX
#include "common/config-manager.h"
#endif
#include "scumm/charset.h"
#include "scumm/dialogs.h"
#include "scumm/file.h"
#include "scumm/imuse/imuse.h"
#include "scumm/imuse_digi/dimuse.h"
#include "scumm/he/intern_he.h"
#include "scumm/object.h"
#include "scumm/resource.h"
#include "scumm/scumm.h"
#include "scumm/scumm_v5.h"
#include "scumm/scumm_v8.h"
#include "scumm/sound.h"
#include "scumm/util.h"
#include "scumm/verbs.h"
namespace Scumm {
enum {
RF_LOCK = 0x80,
RF_USAGE = 0x7F,
RF_USAGE_MAX = RF_USAGE,
RS_MODIFIED = 0x10,
RF_OFFHEAP = 0x40
};
extern const char *nameOfResType(ResType type);
static uint16 newTag2Old(uint32 newTag);
static const byte *findResourceSmall(uint32 tag, const byte *searchin);
static bool checkTryMedia(BaseScummFile *handle);
/* Open a room */
void ScummEngine::openRoom(const int room) {
bool result;
byte encByte = 0;
debugC(DEBUG_GENERAL, "openRoom(%d)", room);
assert(room >= 0);
/* Don't load the same room again */
if (_lastLoadedRoom == room)
return;
_lastLoadedRoom = room;
/* Room -1 means close file */
if (room == -1) {
deleteRoomOffsets();
_fileHandle->close();
return;
}
// Load the disk numer / room offs (special case for room 0 exists because
// room 0 contains the data which is used to create the roomno / roomoffs
// tables -- hence obviously we mustn't use those when loading room 0.
const uint32 diskNumber = room ? _res->_types[rtRoom][room]._roomno : 0;
const uint32 room_offs = room ? _res->_types[rtRoom][room]._roomoffs : 0;
// FIXME: Since room_offs is const, clearly the following loop either
// is never entered, or loops forever (if it wasn't for the return/error
// statements in it, that is). -> This should be cleaned up!
// Maybe we should re-enabled the looping properly, to deal with disc
// changes in COMI ?
while (room_offs != RES_INVALID_OFFSET) {
if (room_offs != 0 && room != 0 && _game.heversion < 98) {
_fileOffset = _res->_types[rtRoom][room]._roomoffs;
return;
}
Common::String filename(generateFilename(room));
// Determine the encryption, if any.
if (_game.features & GF_USE_KEY) {
if (_game.version <= 3)
encByte = 0xFF;
else if ((_game.version == 4) && (room == 0 || room >= 900))
encByte = 0;
else
encByte = 0x69;
} else
encByte = 0;
if (room > 0 && (_game.version == 8))
VAR(VAR_CURRENTDISK) = diskNumber;
// Try to open the file
result = openResourceFile(filename, encByte);
if (result) {
if (room == 0)
return;
deleteRoomOffsets();
readRoomsOffsets();
_fileOffset = _res->_types[rtRoom][room]._roomoffs;
if (_fileOffset != 8)
return;
error("Room %d not in %s", room, filename.c_str());
return;
}
askForDisk(filename.c_str(), diskNumber);
}
do {
char buf[16];
snprintf(buf, sizeof(buf), "%.3d.lfl", room);
encByte = 0;
if (openResourceFile(buf, encByte))
break;
askForDisk(buf, diskNumber);
} while (1);
deleteRoomOffsets();
_fileOffset = 0; // start of file
}
void ScummEngine::closeRoom() {
if (_lastLoadedRoom != -1) {
_lastLoadedRoom = -1;
deleteRoomOffsets();
_fileHandle->close();
}
}
/** Delete the currently loaded room offsets. */
void ScummEngine::deleteRoomOffsets() {
for (int i = 0; i < _numRooms; i++) {
if (_res->_types[rtRoom][i]._roomoffs != RES_INVALID_OFFSET)
_res->_types[rtRoom][i]._roomoffs = 0;
}
}
/** Read room offsets */
void ScummEngine::readRoomsOffsets() {
if (_game.features & GF_SMALL_HEADER) {
_fileHandle->seek(12, SEEK_SET); // Directly searching for the room offset block would be more generic...
} else {
_fileHandle->seek(16, SEEK_SET);
}
int num = _fileHandle->readByte();
while (num--) {
int room = _fileHandle->readByte();
int offset = _fileHandle->readUint32LE();
if (_res->_types[rtRoom][room]._roomoffs != RES_INVALID_OFFSET) {
_res->_types[rtRoom][room]._roomoffs = offset;
}
}
}
bool ScummEngine::openFile(BaseScummFile &file, const Common::String &filename, bool resourceFile) {
bool result = false;
if (!_containerFile.empty()) {
file.close();
file.open(_containerFile);
assert(file.isOpen());
result = file.openSubFile(filename);
}
if (!result) {
file.close();
result = file.open(filename);
}
return result;
}
bool ScummEngine::openResourceFile(const Common::String &filename, byte encByte) {
debugC(DEBUG_GENERAL, "openResourceFile(%s)", filename.c_str());
if (openFile(*_fileHandle, filename, true)) {
_fileHandle->setEnc(encByte);
return true;
}
return false;
}
void ScummEngine::askForDisk(const char *filename, int disknum) {
char buf[128];
if (_game.version == 8) {
#ifdef ENABLE_SCUMM_7_8
char result;
_imuseDigital->stopAllSounds();
#ifdef MACOSX
sprintf(buf, "Cannot find file: '%s'\nPlease insert disc %d.\nPress OK to retry, Quit to exit", filename, disknum);
#else
sprintf(buf, "Cannot find file: '%s'\nInsert disc %d into drive %s\nPress OK to retry, Quit to exit", filename, disknum, ConfMan.get("path").c_str());
#endif
result = displayMessage("Quit", "%s", buf);
if (!result) {
error("Cannot find file: '%s'", filename);
}
#endif
} else {
sprintf(buf, "Cannot find file: '%s'", filename);
InfoDialog dialog(this, (char *)buf);
runDialog(dialog);
error("Cannot find file: '%s'", filename);
}
}
void ScummEngine::readIndexFile() {
uint32 blocktype, itemsize;
int numblock = 0;
debugC(DEBUG_GENERAL, "readIndexFile()");
closeRoom();
openRoom(0);
if (_game.version <= 5) {
// Figure out the sizes of various resources
while (true) {
blocktype = _fileHandle->readUint32BE();
itemsize = _fileHandle->readUint32BE();
if (_fileHandle->eos() || _fileHandle->err())
break;
switch (blocktype) {
case MKTAG('D','O','B','J'):
_numGlobalObjects = _fileHandle->readUint16LE();
itemsize -= 2;
break;
case MKTAG('D','R','O','O'):
_numRooms = _fileHandle->readUint16LE();
itemsize -= 2;
break;
case MKTAG('D','S','C','R'):
_numScripts = _fileHandle->readUint16LE();
itemsize -= 2;
break;
case MKTAG('D','C','O','S'):
_numCostumes = _fileHandle->readUint16LE();
itemsize -= 2;
break;
case MKTAG('D','S','O','U'):
_numSounds = _fileHandle->readUint16LE();
itemsize -= 2;
break;
}
_fileHandle->seek(itemsize - 8, SEEK_CUR);
}
_fileHandle->seek(0, SEEK_SET);
}
if (checkTryMedia(_fileHandle)) {
displayMessage(NULL, "You're trying to run game encrypted by ActiveMark. This is not supported.");
quitGame();
return;
}
while (true) {
blocktype = _fileHandle->readUint32BE();
itemsize = _fileHandle->readUint32BE();
if (_fileHandle->eos() || _fileHandle->err())
break;
numblock++;
debug(2, "Reading index block of type '%s', size %d", tag2str(blocktype), itemsize);
readIndexBlock(blocktype, itemsize);
}
// if (numblock!=9)
// error("Not enough blocks read from directory");
closeRoom();
}
#define TRYMEDIA_MARK_LEN 6
bool checkTryMedia(BaseScummFile *handle) {
byte buf[TRYMEDIA_MARK_LEN];
bool matched = true;
const byte magic[2][TRYMEDIA_MARK_LEN] =
{{ 0x00, 'T', 'M', 'S', 'A', 'M' },
{ 'i', '=', '$', ':', '(', '$' }}; // Same but 0x69 xored
handle->read(buf, TRYMEDIA_MARK_LEN);
for (int i = 0; i < 2; i++) {
matched = true;
for (int j = 0; j < TRYMEDIA_MARK_LEN; j++)
if (buf[j] != magic[i][j]) {
matched = false;
break;
}
if (matched)
break;
}
if (matched)
return true;
handle->seek(0, SEEK_SET);
return false;
}
#ifdef ENABLE_SCUMM_7_8
void ScummEngine_v7::readIndexBlock(uint32 blocktype, uint32 itemsize) {
int num;
char *ptr;
switch (blocktype) {
case MKTAG('A','N','A','M'): // Used by: The Dig, FT
num = _fileHandle->readUint16LE();
ptr = (char *)malloc(num * 9);
_fileHandle->read(ptr, num * 9);
_imuseDigital->setAudioNames(num, ptr);
break;
case MKTAG('D','R','S','C'): // Used by: COMI
readResTypeList(rtRoomScripts);
break;
default:
ScummEngine::readIndexBlock(blocktype, itemsize);
}
}
#endif
void ScummEngine_v70he::readIndexBlock(uint32 blocktype, uint32 itemsize) {
int i;
switch (blocktype) {
case MKTAG('D','I','R','I'):
readResTypeList(rtRoomImage);
break;
case MKTAG('D','I','R','M'):
readResTypeList(rtImage);
break;
case MKTAG('D','I','R','T'):
readResTypeList(rtTalkie);
break;
case MKTAG('D','L','F','L'):
i = _fileHandle->readUint16LE();
_fileHandle->seek(-2, SEEK_CUR);
_heV7RoomOffsets = (byte *)calloc(2 + (i * 4), 1);
_fileHandle->read(_heV7RoomOffsets, (2 + (i * 4)) );
break;
case MKTAG('D','I','S','K'):
i = _fileHandle->readUint16LE();
_heV7DiskOffsets = (byte *)calloc(i, 1);
_fileHandle->read(_heV7DiskOffsets, i);
break;
case MKTAG('S','V','E','R'):
// Index version number
_fileHandle->seek(itemsize - 8, SEEK_CUR);
break;
case MKTAG('I','N','I','B'):
_fileHandle->seek(itemsize - 8, SEEK_CUR);
debug(2, "INIB index block not yet handled, skipping");
break;
default:
ScummEngine::readIndexBlock(blocktype, itemsize);
}
}
void ScummEngine::readIndexBlock(uint32 blocktype, uint32 itemsize) {
int i;
switch (blocktype) {
case MKTAG('D','C','H','R'):
case MKTAG('D','I','R','F'):
readResTypeList(rtCharset);
break;
case MKTAG('D','O','B','J'):
readGlobalObjects();
break;
case MKTAG('R','N','A','M'):
// Names of rooms. Maybe we should put them into a table, for use by the debugger?
if (_game.heversion >= 80) {
for (int room; (room = _fileHandle->readUint16LE()); ) {
char buf[100];
i = 0;
for (byte s; (s = _fileHandle->readByte()) && i < ARRAYSIZE(buf) - 1; ) {
buf[i++] = s;
}
buf[i] = 0;
debug(5, "Room %d: '%s'", room, buf);
}
} else {
for (int room; (room = _fileHandle->readByte()); ) {
char buf[10];
_fileHandle->read(buf, 9);
buf[9] = 0;
for (i = 0; i < 9; i++)
buf[i] ^= 0xFF;
debug(5, "Room %d: '%s'", room, buf);
}
}
break;
case MKTAG('D','R','O','O'):
case MKTAG('D','I','R','R'):
readResTypeList(rtRoom);
break;
case MKTAG('D','S','C','R'):
case MKTAG('D','I','R','S'):
readResTypeList(rtScript);
break;
case MKTAG('D','C','O','S'):
case MKTAG('D','I','R','C'):
readResTypeList(rtCostume);
break;
case MKTAG('M','A','X','S'):
readMAXS(itemsize);
allocateArrays();
break;
case MKTAG('D','I','R','N'):
case MKTAG('D','S','O','U'):
readResTypeList(rtSound);
break;
case MKTAG('A','A','R','Y'):
readArrayFromIndexFile();
break;
default:
error("Bad ID %04X('%s') found in index file directory", blocktype,
tag2str(blocktype));
}
}
void ScummEngine::readArrayFromIndexFile() {
error("readArrayFromIndexFile() not supported in pre-V6 games");
}
int ScummEngine::readResTypeList(ResType type) {
uint num;
ResId idx;
if (_game.version == 8)
num = _fileHandle->readUint32LE();
else
num = _fileHandle->readUint16LE();
if (num != _res->_types[type].size()) {
error("Invalid number of %ss (%d) in directory", nameOfResType(type), num);
}
debug(2, " readResTypeList(%s): %d entries", nameOfResType(type), num);
for (idx = 0; idx < num; idx++) {
_res->_types[type][idx]._roomno = _fileHandle->readByte();
}
for (idx = 0; idx < num; idx++) {
_res->_types[type][idx]._roomoffs = _fileHandle->readUint32LE();
}
return num;
}
int ScummEngine_v70he::readResTypeList(ResType type) {
uint num;
ResId idx;
num = ScummEngine::readResTypeList(type);
if (type == rtRoom)
for (idx = 0; idx < num; idx++) {
_heV7RoomIntOffsets[idx] = _res->_types[rtRoom][idx]._roomoffs;
}
for (idx = 0; idx < num; idx++) {
// The globsize is currently not being used
/*_res->_types[type][idx]._globsize =*/ _fileHandle->readUint32LE();
}
return num;
}
void ResourceManager::allocResTypeData(ResType type, uint32 tag, int num, ResTypeMode mode) {
debug(2, "allocResTypeData(%s,%s,%d,%d)", nameOfResType(type), tag2str(TO_BE_32(tag)), num, mode);
assert(type >= 0 && type < (int)(ARRAYSIZE(_types)));
if (num >= 8000)
error("Too many %s resources (%d) in directory", nameOfResType(type), num);
_types[type]._mode = mode;
_types[type]._tag = tag;
// If there was data in there, let's clear it out completely. This is important
// in case we are restarting the game.
_types[type].clear();
_types[type].resize(num);
/*
TODO: Use multiple Resource subclasses, one for each res mode; then,
given them serializability.
if (mode) {
_types[type].roomno = (byte *)calloc(num, sizeof(byte));
_types[type].roomoffs = (uint32 *)calloc(num, sizeof(uint32));
}
if (_vm->_game.heversion >= 70) {
_types[type].globsize = (uint32 *)calloc(num, sizeof(uint32));
}
*/
}
void ScummEngine::loadCharset(int no) {
int i;
byte *ptr;
debugC(DEBUG_GENERAL, "loadCharset(%d)", no);
/* FIXME - hack around crash in Indy4 (occurs if you try to load after dieing) */
if (_game.id == GID_INDY4 && no == 0)
no = 1;
/* for Humongous catalogs */
if (_game.heversion >= 70 && _numCharsets == 1) {
debug(0, "Not loading charset as it doesn't seem to exist?");
return;
}
assert(no < (int)sizeof(_charsetData) / 16);
assertRange(1, no, _numCharsets - 1, "charset");
ptr = getResourceAddress(rtCharset, no);
for (i = 0; i < 15; i++) {
_charsetData[no][i + 1] = ptr[i + 14];
}
}
void ScummEngine::nukeCharset(int i) {
assertRange(1, i, _numCharsets - 1, "charset");
_res->nukeResource(rtCharset, i);
}
void ScummEngine::ensureResourceLoaded(ResType type, ResId idx) {
debugC(DEBUG_RESOURCE, "ensureResourceLoaded(%s,%d)", nameOfResType(type), idx);
if ((type == rtRoom) && idx > 0x7F && _game.version < 7 && _game.heversion <= 71) {
idx = _resourceMapper[idx & 0x7F];
}
// FIXME: This check used to be "idx==0". However, that causes
// problems when using this function to ensure charset 0 is loaded.
// This is done for many games, e.g. Zak256 or Indy3 (EGA and VGA).
// For now we restrict the check to anything which is not a charset.
// Question: Why was this check like that in the first place?
// Answer: costumes with an index of zero in the newer games at least.
// TODO: determine why the heck anything would try to load a costume
// with id 0. Is that "normal", or is it caused by yet another bug in
// our code base? After all we also have to add special cases for many
// of our script opcodes that check for the (invalid) actor 0... so
// maybe both issues are related...
if (type != rtCharset && idx == 0)
return;
if (idx <= _res->_types[type].size() && _res->_types[type][idx]._address)
return;
loadResource(type, idx);
if (_game.version == 5 && type == rtRoom && (int)idx == _roomResource)
VAR(VAR_ROOM_FLAG) = 1;
}
int ScummEngine::loadResource(ResType type, ResId idx) {
int roomNr;
uint32 fileOffs;
uint32 size, tag;
debugC(DEBUG_RESOURCE, "loadResource(%s,%d)", nameOfResType(type), idx);
if (type == rtCharset && (_game.features & GF_SMALL_HEADER)) {
loadCharset(idx);
return 1;
}
roomNr = getResourceRoomNr(type, idx);
if (idx >= _res->_types[type].size())
error("%s %d undefined %d %d", nameOfResType(type), idx, _res->_types[type].size(), roomNr);
if (roomNr == 0)
roomNr = _roomResource;
fileOffs = getResourceRoomOffset(type, idx);
if (fileOffs == RES_INVALID_OFFSET)
return 0;
openRoom(roomNr);
_fileHandle->seek(fileOffs + _fileOffset, SEEK_SET);
if (_game.features & GF_OLD_BUNDLE) {
if ((_game.version == 3) && !(_game.platform == Common::kPlatformAmiga) && (type == rtSound)) {
return readSoundResourceSmallHeader(idx);
} else {
size = _fileHandle->readUint16LE();
_fileHandle->seek(-2, SEEK_CUR);
}
} else if (_game.features & GF_SMALL_HEADER) {
if (_game.version == 4)
_fileHandle->seek(8, SEEK_CUR);
size = _fileHandle->readUint32LE();
tag = _fileHandle->readUint16LE();
_fileHandle->seek(-6, SEEK_CUR);
if ((type == rtSound) && !(_game.platform == Common::kPlatformAmiga) && !(_game.platform == Common::kPlatformFMTowns)) {
return readSoundResourceSmallHeader(idx);
}
} else {
if (type == rtSound) {
return readSoundResource(idx);
}
// Sanity check: Is this the right tag for this resource type?
//
// Currently disabled for newer HE games because they use different
// tags. For example, for rtRoom, 'ROOM' changed to 'RMDA'; and for
// rtImage, 'AWIZ' and 'MULT' can both occur simultaneously.
// On the long run, it would be preferable to not turn this check off,
// but instead to explicitly support the variations in the HE games.
tag = _fileHandle->readUint32BE();
if (tag != _res->_types[type]._tag && _game.heversion < 70) {
error("Unknown res tag '%s' encountered (expected '%s') "
"while trying to load res (%s,%d) in room %d at %d+%d in file %s",
tag2str(tag), tag2str(_res->_types[type]._tag),
nameOfResType(type), idx, roomNr,
_fileOffset, fileOffs, _fileHandle->getName());
}
size = _fileHandle->readUint32BE();
_fileHandle->seek(-8, SEEK_CUR);
}
_fileHandle->read(_res->createResource(type, idx, size), size);
// dump the resource if requested
if (_dumpScripts && type == rtScript) {
dumpResource("script-", idx, getResourceAddress(rtScript, idx));
}
if (_fileHandle->err() || _fileHandle->eos()) {
error("Cannot read resource");
}
return 1;
}
int ScummEngine::getResourceRoomNr(ResType type, ResId idx) {
if (type == rtRoom && _game.heversion < 70)
return idx;
return _res->_types[type][idx]._roomno;
}
uint32 ScummEngine::getResourceRoomOffset(ResType type, ResId idx) {
if (type == rtRoom) {
return (_game.version == 8) ? 8 : 0;
}
return _res->_types[type][idx]._roomoffs;
}
uint32 ScummEngine_v70he::getResourceRoomOffset(ResType type, ResId idx) {
if (type == rtRoom) {
return _heV7RoomIntOffsets[idx];
}
return _res->_types[type][idx]._roomoffs;
}
int ScummEngine::getResourceSize(ResType type, ResId idx) {
byte *ptr = getResourceAddress(type, idx);
assert(ptr);
return _res->_types[type][idx]._size;
}
byte *ScummEngine::getResourceAddress(ResType type, ResId idx) {
byte *ptr;
if (_game.heversion >= 80 && type == rtString)
idx &= ~0x33539000;
if (!_res->validateResource("getResourceAddress", type, idx))
return NULL;
// If the resource is missing, but loadable from the game data files, try to do so.
if (!_res->_types[type][idx]._address && _res->_types[type]._mode != kDynamicResTypeMode) {
ensureResourceLoaded(type, idx);
}
ptr = (byte *)_res->_types[type][idx]._address;
if (!ptr) {
debugC(DEBUG_RESOURCE, "getResourceAddress(%s,%d) == NULL", nameOfResType(type), idx);
return NULL;
}
_res->setResourceCounter(type, idx, 1);
debugC(DEBUG_RESOURCE, "getResourceAddress(%s,%d) == %p", nameOfResType(type), idx, ptr);
return ptr;
}
byte *ScummEngine::getStringAddress(ResId idx) {
byte *addr = getResourceAddress(rtString, idx);
return addr;
}
byte *ScummEngine_v6::getStringAddress(ResId idx) {
byte *addr = getResourceAddress(rtString, idx);
if (addr == NULL)
return NULL;
// Skip over the ArrayHeader
return addr + 6;
}
byte *ScummEngine::getStringAddressVar(int i) {
return getStringAddress(_scummVars[i]);
}
void ResourceManager::increaseExpireCounter() {
++_expireCounter;
if (_expireCounter == 0) { // overflow?
increaseResourceCounters();
}
}
void ResourceManager::increaseResourceCounters() {
for (ResType type = rtFirst; type <= rtLast; type = ResType(type + 1)) {
ResId idx = _types[type].size();
while (idx-- > 0) {
byte counter = _types[type][idx].getResourceCounter();
if (counter && counter < RF_USAGE_MAX) {
setResourceCounter(type, idx, counter + 1);
}
}
}
}
void ResourceManager::setResourceCounter(ResType type, ResId idx, byte counter) {
_types[type][idx].setResourceCounter(counter);
}
void ResourceManager::Resource::setResourceCounter(byte counter) {
_flags &= RF_LOCK; // Clear lower 7 bits, preserve the lock bit.
_flags |= counter; // Update the usage counter
}
byte ResourceManager::Resource::getResourceCounter() const {
return _flags & RF_USAGE;
}
/* 2 bytes safety area to make "precaching" of bytes in the gdi drawer easier */
#define SAFETY_AREA 2
byte *ResourceManager::createResource(ResType type, ResId idx, uint32 size) {
debugC(DEBUG_RESOURCE, "_res->createResource(%s,%d,%d)", nameOfResType(type), idx, size);
if (!validateResource("allocating", type, idx))
return NULL;
if (_vm->_game.version <= 2) {
// Nuking and reloading a resource can be harmful in some
// cases. For instance, Zak tries to reload the intro music
// while it's playing. See bug #1253171.
if (_types[type][idx]._address && (type == rtSound || type == rtScript || type == rtCostume))
return _types[type][idx]._address;
}
nukeResource(type, idx);
expireResources(size);
byte *ptr = new byte[size + SAFETY_AREA];
if (ptr == NULL) {
error("createResource(%s,%d): Out of memory while allocating %d", nameOfResType(type), idx, size);
}
memset(ptr, 0, size + SAFETY_AREA);
_allocatedSize += size;
_types[type][idx]._address = ptr;
_types[type][idx]._size = size;
setResourceCounter(type, idx, 1);
return ptr;
}
ResourceManager::Resource::Resource() {
_address = 0;
_size = 0;
_flags = 0;
_status = 0;
_roomno = 0;
_roomoffs = 0;
}
ResourceManager::Resource::~Resource() {
delete[] _address;
_address = 0;
}
void ResourceManager::Resource::nuke() {
delete[] _address;
_address = 0;
_size = 0;
_flags = 0;
_status &= ~RS_MODIFIED;
}
ResourceManager::ResTypeData::ResTypeData() {
_mode = kDynamicResTypeMode;
_tag = 0;
}
ResourceManager::ResTypeData::~ResTypeData() {
}
ResourceManager::ResourceManager(ScummEngine *vm) : _vm(vm) {
_allocatedSize = 0;
_maxHeapThreshold = 0;
_minHeapThreshold = 0;
_expireCounter = 0;
}
ResourceManager::~ResourceManager() {
freeResources();
}
void ResourceManager::setHeapThreshold(int min, int max) {
assert(0 < max);
assert(min <= max);
_maxHeapThreshold = max;
_minHeapThreshold = min;
}
bool ResourceManager::validateResource(const char *str, ResType type, ResId idx) const {
if (type < rtFirst || type > rtLast || (uint)idx >= (uint)_types[type].size()) {
error("%s Illegal Glob type %s (%d) num %d", str, nameOfResType(type), type, idx);
return false;
}
return true;
}
void ResourceManager::nukeResource(ResType type, ResId idx) {
byte *ptr = _types[type][idx]._address;
if (ptr != NULL) {
debugC(DEBUG_RESOURCE, "nukeResource(%s,%d)", nameOfResType(type), idx);
_allocatedSize -= _types[type][idx]._size;
_types[type][idx].nuke();
}
}
const byte *ScummEngine::findResourceData(uint32 tag, const byte *ptr) {
if (_game.features & GF_OLD_BUNDLE)
error("findResourceData must not be used in GF_OLD_BUNDLE games");
else if (_game.features & GF_SMALL_HEADER)
ptr = findResourceSmall(tag, ptr);
else
ptr = findResource(tag, ptr);
if (ptr == NULL)
return NULL;
return ptr + _resourceHeaderSize;
}
int ScummEngine::getResourceDataSize(const byte *ptr) const {
if (ptr == NULL)
return 0;
if (_game.features & GF_OLD_BUNDLE)
return READ_LE_UINT16(ptr) - _resourceHeaderSize;
else if (_game.features & GF_SMALL_HEADER)
return READ_LE_UINT32(ptr) - _resourceHeaderSize;
else
return READ_BE_UINT32(ptr - 4) - _resourceHeaderSize;
}
void ResourceManager::lock(ResType type, ResId idx) {
if (!validateResource("Locking", type, idx))
return;
_types[type][idx].lock();
}
void ResourceManager::unlock(ResType type, ResId idx) {
if (!validateResource("Unlocking", type, idx))
return;
_types[type][idx].unlock();
}
bool ResourceManager::isLocked(ResType type, ResId idx) const {
if (!validateResource("isLocked", type, idx))
return false;
return _types[type][idx].isLocked();
}
void ResourceManager::Resource::lock() {
_flags |= RF_LOCK;
}
void ResourceManager::Resource::unlock() {
_flags &= ~RF_LOCK;
}
bool ResourceManager::Resource::isLocked() const {
return (_flags & RF_LOCK) != 0;
}
bool ScummEngine::isResourceInUse(ResType type, ResId idx) const {
if (!_res->validateResource("isResourceInUse", type, idx))
return false;
switch (type) {
case rtRoom:
return _roomResource == (byte)idx;
case rtRoomImage:
return _roomResource == (byte)idx;
case rtRoomScripts:
return _roomResource == (byte)idx;
case rtScript:
return isScriptInUse(idx);
case rtCostume:
return isCostumeInUse(idx);
case rtSound:
// Sound resource 1 is used for queued speech
if (_game.heversion >= 60 && idx == 1)
return true;
else
return _sound->isSoundInUse(idx);
case rtCharset:
return _charset->getCurID() == (int)idx;
case rtImage:
return _res->isModified(type, idx) != 0;
case rtSpoolBuffer:
return _sound->isSoundRunning(10000 + idx) != 0;
default:
return false;
}
}
void ResourceManager::setModified(ResType type, ResId idx) {
if (!validateResource("Modified", type, idx))
return;
_types[type][idx].setModified();
}
void ResourceManager::setOffHeap(ResType type, ResId idx) {
if (!validateResource("setOffHeap", type, idx))
return;
_types[type][idx].setOffHeap();