forked from wario-land/WL4Editor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathROMUtils.cpp
More file actions
1242 lines (1146 loc) · 52.6 KB
/
ROMUtils.cpp
File metadata and controls
1242 lines (1146 loc) · 52.6 KB
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
#include "ROMUtils.h"
#include "Compress.h"
#include <QFile>
#include <QTranslator>
#include "WL4EditorWindow.h"
#include <cassert>
#include <iostream>
#include <QtDebug>
extern WL4EditorWindow *singleton;
// Helper function to find the number of characters matched in ptr to a pattern
static inline int StrMatch(unsigned char *ptr, const char *pattern)
{
int matched = 0;
do
{
if (ptr[matched] != *pattern)
break;
++matched;
} while (*++pattern);
return matched;
}
// Helper function to validate RATS at an address
static inline bool ValidRATS(unsigned char *ptr)
{
if (strncmp(reinterpret_cast<const char *>(ptr), "STAR", 4))
return false;
short chunkLen = *reinterpret_cast<short *>(ptr + 4);
short chunkComp = *reinterpret_cast<short *>(ptr + 6);
return chunkLen == ~chunkComp;
}
namespace ROMUtils
{
unsigned char *CurrentFile;
unsigned int CurrentFileSize;
QString ROMFilePath;
unsigned char *tmpCurrentFile;
unsigned int tmpCurrentFileSize;
QString tmpROMFilePath;
unsigned int SaveDataIndex;
LevelComponents::Tileset *singletonTilesets[92];
LevelComponents::EntitySet *entitiessets[90];
LevelComponents::Entity *entities[129];
/// <summary>
/// Get a 4-byte, little-endian integer from ROM data.
/// </summary>
/// <param name="data">
/// The ROM data to read from.
/// </param>
/// <param name="address">
/// The address to get the integer from.
/// </param>
/// <param name="loadFromTmpROM">
/// Ture when load from a temp ROM.
/// </param>
unsigned int IntFromData(int address, bool loadFromTmpROM)
{
return *reinterpret_cast<unsigned int *>((loadFromTmpROM ? tmpCurrentFile: CurrentFile) + address);
}
/// <summary>
/// Get a pointer value from ROM data.
/// </summary>
/// <remarks>
/// The pointer which is returned does not include the upper byte, which is only necessary for the GBA memory map.
/// The returned int value can be used to index the ROM data.
/// </remarks>
/// <param name="data">
/// The ROM data to read from.
/// </param>
/// <param name="address">
/// The address to get the pointer from.
/// </param>
/// <param name="loadFromTmpROM">
/// Ture when load from a temp ROM.
/// </param>
unsigned int PointerFromData(int address, bool loadFromTmpROM)
{
unsigned int ret = IntFromData(address, loadFromTmpROM) & 0x7FFFFFF;
if(loadFromTmpROM ? ret >= tmpCurrentFileSize: ret >= CurrentFileSize)
{
singleton->GetOutputWidgetPtr()->PrintString(QT_TR_NOOP("Internal or corruption error: Attempted to read a pointer which is larger than the ROM's file size"));
}
return ret;
}
/// <summary>
/// Reverse the endianness of an integer.
/// </summary>
/// <param name="n">
/// The integer to reverse.
/// </param>
/// <return>
/// 08 FF A1 C9 -> C9 A1 FF 08
/// </return>
uint32_t EndianReverse(uint32_t n)
{
return (n << 24) | ((n & 0xFF00) << 8) | ((n & 0xFF0000) >> 8) | ((n >> 24) & 0xFF);
}
/// <summary>
/// Decompress ROM data that was compressed with run-length encoding.
/// </summary>
/// <remarks>
/// The <paramref name="outputSize"/> parameter specifies the predicted output size in bytes.
/// The return unsigned char * is on the heap, delete it after using.
/// </remarks>
/// <param name="data">
/// A pointer into the ROM data to start reading from.
/// </param>
/// <param name="outputSize">
/// The predicted size of the output data.(unit: Byte)
/// </param>
/// <return>A pointer to decompressed data.</return>
unsigned char *LayerRLEDecompress(int address, size_t outputSize)
{
unsigned char *OutputLayerData = new unsigned char[outputSize];
int runData;
for (int i = 0; i < 2; i++)
{
unsigned char *dst = OutputLayerData + i;
if (ROMUtils::CurrentFile[address++] == 1)
{
while (1)
{
int ctrl = CurrentFile[address++];
if (!ctrl)
{
break;
}
size_t temp = dst - OutputLayerData;
if (temp > outputSize)
{
delete[] OutputLayerData;
return nullptr;
}
else if (ctrl & 0x80)
{
runData = ctrl & 0x7F;
for (int j = 0; j < runData; j++)
{
dst[2 * j] = CurrentFile[address];
}
address++;
}
else
{
runData = ctrl;
for (int j = 0; j < runData; j++)
{
dst[2 * j] = CurrentFile[address + j];
}
address += runData;
}
dst += 2 * runData;
}
}
else // RLE16
{
while (1)
{
int ctrl = (static_cast<int>(CurrentFile[address]) << 8) | CurrentFile[address + 1];
address += 2; // offset + 2
if (!ctrl)
{
break;
}
size_t temp = dst - OutputLayerData;
if (temp > outputSize)
{
delete[] OutputLayerData;
return nullptr;
}
if (ctrl & 0x8000)
{
runData = ctrl & 0x7FFF;
for (int j = 0; j < runData; j++)
{
dst[2 * j] = CurrentFile[address];
}
address++;
}
else
{
runData = ctrl;
for (int j = 0; j < runData; j++)
{
dst[2 * j] = CurrentFile[address + j];
}
address += runData;
}
dst += 2 * runData;
}
}
}
return OutputLayerData;
}
/// <summary>
/// compress Layer data by run-length encoding.
/// </summary>
/// <remarks>
/// the first and second byte as the layer width and height information will not be generated in the function
/// you have to add them by yourself when saving compressed data.
/// </remarks>
/// <param name="_layersize">
/// the size of the layer, the value equal to (layerwidth * layerheight).
/// </param>
/// <param name="LayerData">
/// unsigned char pointer to the uncompressed layer data.
/// </param>
/// <param name="OutputCompressedData">
/// unsigned char pointer to the compressed layer data.
/// </param>
/// <return>the length of compressed data.</return>
unsigned int LayerRLECompress(unsigned int _layersize, unsigned short *LayerData,
unsigned char **OutputCompressedData)
{
// Separate short data into char arrays
unsigned char *separatedBytes = new unsigned char[_layersize * 2];
for (unsigned int i = 0; i < _layersize; ++i)
{
unsigned short s = LayerData[i];
separatedBytes[i] = static_cast<unsigned char>(s);
separatedBytes[i + _layersize] = static_cast<unsigned char>(s >> 8);
}
// Decide on 8 or 16 bit compression for the arrays
RLEMetadata8Bit Lower8Bit(separatedBytes, _layersize);
RLEMetadata16Bit Lower16Bit(separatedBytes, _layersize);
RLEMetadata8Bit Upper8Bit(separatedBytes + _layersize, _layersize);
RLEMetadata16Bit Upper16Bit(separatedBytes + _layersize, _layersize);
RLEMetadata *Lower = Lower8Bit.GetCompressedLength() < Lower16Bit.GetCompressedLength()
? (RLEMetadata *) &Lower8Bit
: (RLEMetadata *) &Lower16Bit;
RLEMetadata *Upper = Upper8Bit.GetCompressedLength() < Upper16Bit.GetCompressedLength()
? (RLEMetadata *) &Upper8Bit
: (RLEMetadata *) &Upper16Bit;
// Create the data to return
unsigned int lowerLength = Lower->GetCompressedLength(), upperLength = Upper->GetCompressedLength();
unsigned int size = lowerLength + upperLength + 1;
*OutputCompressedData = new unsigned char[size];
void *lowerData = Lower->GetCompressedData();
void *upperData = Upper->GetCompressedData();
memcpy(*OutputCompressedData, lowerData, lowerLength);
memcpy(*OutputCompressedData + lowerLength, upperData, upperLength);
(*OutputCompressedData)[lowerLength + upperLength] = '\0';
// Clean up
delete[] separatedBytes;
return size;
}
/// <summary>
/// Get the savedata chunks from a Tileset.
/// </summary>
/// <param name="TilesetId">
/// Select a Tileset by its Id.
/// </param>
/// <param name="chunks">
/// Push new chunks to it.
/// </param>
void GenerateTilesetSaveChunks(int TilesetId, QVector<SaveData> &chunks)
{
int tilesetPtr = singletonTilesets[TilesetId]->getTilesetPtr();
// Create Map16EventTable chunk
struct ROMUtils::SaveData Map16EventTablechunk = { static_cast<unsigned int>(tilesetPtr + 28),
0x600,
(unsigned char *) malloc(0x600),
ROMUtils::SaveDataIndex++,
true,
0,
ROMUtils::PointerFromData(tilesetPtr + 28),
ROMUtils::SaveDataChunkType::TilesetMap16EventTableChunkType };
memcpy(Map16EventTablechunk.data, singletonTilesets[TilesetId]->GetEventTablePtr(), 0x600);
chunks.append(Map16EventTablechunk);
// Create FGTile8x8GraphicData chunk
int FGTileGfxDataLen = singletonTilesets[TilesetId]->GetfgGFXlen();
unsigned char FGmap8x8tiledata[(1024 - 65) * 32];
QVector<LevelComponents::Tile8x8 *> tile8x8array = singletonTilesets[TilesetId]->GetTile8x8arrayPtr();
for (int j = 0; j < (FGTileGfxDataLen / 32); ++j)
{
memcpy(&FGmap8x8tiledata[32 * j], tile8x8array[j + 0x41]->CreateGraphicsData().data(), 32);
}
struct ROMUtils::SaveData FGTile8x8GraphicDataChunk = { static_cast<unsigned int>(tilesetPtr),
static_cast<unsigned int>(FGTileGfxDataLen),
(unsigned char *) malloc(FGTileGfxDataLen),
ROMUtils::SaveDataIndex++,
true,
0,
ROMUtils::PointerFromData(tilesetPtr),
ROMUtils::SaveDataChunkType::TilesetForegroundTile8x8DataChunkType };
memcpy(FGTile8x8GraphicDataChunk.data, FGmap8x8tiledata, FGTileGfxDataLen);
chunks.append(FGTile8x8GraphicDataChunk);
// Create Map16TerrainType chunk
struct ROMUtils::SaveData Map16TerrainTypechunk = { static_cast<unsigned int>(tilesetPtr + 24),
0x300,
(unsigned char *) malloc(0x300),
ROMUtils::SaveDataIndex++,
true,
0,
ROMUtils::PointerFromData(tilesetPtr + 24),
ROMUtils::SaveDataChunkType::TilesetMap16TerrainChunkType };
memcpy(Map16TerrainTypechunk.data, singletonTilesets[TilesetId]->GetTerrainTypeIDTablePtr(), 0x300);
chunks.append(Map16TerrainTypechunk);
// Save palettes
singletonTilesets[TilesetId]->ReGeneratePaletteData();
struct ROMUtils::SaveData TilesetPalettechunk = { static_cast<unsigned int>(tilesetPtr + 8),
16 * 16 * 2,
(unsigned char *) malloc(16 * 16 * 2),
ROMUtils::SaveDataIndex++,
true,
0,
ROMUtils::PointerFromData(tilesetPtr + 8),
ROMUtils::SaveDataChunkType::TilesetPaletteDataChunkType };
memcpy(TilesetPalettechunk.data, singletonTilesets[TilesetId]->GetTilesetPaletteDataPtr(), 16 * 16 * 2);
chunks.append(TilesetPalettechunk);
// Create Map16Data chunk
QVector<LevelComponents::TileMap16 *> map16data = singletonTilesets[TilesetId]->GetMap16arrayPtr();
struct ROMUtils::SaveData Map16Datachunk = { static_cast<unsigned int>(tilesetPtr + 20),
0x300 * 8,
(unsigned char *) malloc(0x300 * 8),
ROMUtils::SaveDataIndex++,
true,
0,
ROMUtils::PointerFromData(tilesetPtr + 20),
ROMUtils::SaveDataChunkType::TilesetMap16DataChunkType };
unsigned short map16tilePtr[0x300 * 4];
for (int j = 0; j < 0x300; ++j)
{
map16tilePtr[j * 4] = map16data[j]->GetTile8X8(LevelComponents::TileMap16::TILE8_TOPLEFT)->GetValue();
map16tilePtr[j * 4 + 1] = map16data[j]->GetTile8X8(LevelComponents::TileMap16::TILE8_TOPRIGHT)->GetValue();
map16tilePtr[j * 4 + 2] = map16data[j]->GetTile8X8(LevelComponents::TileMap16::TILE8_BOTTOMLEFT)->GetValue();
map16tilePtr[j * 4 + 3] = map16data[j]->GetTile8X8(LevelComponents::TileMap16::TILE8_BOTTOMRIGHT)->GetValue();
}
memcpy(Map16Datachunk.data, (unsigned char*)map16tilePtr, 0x300 * 8);
chunks.append(Map16Datachunk);
}
/// <summary>
/// Find the next chunk of a specific type.
/// </summary>
/// <param name="ROMData">
/// The pointer to the ROM data being processed.
/// </param>
/// <param name="ROMLength">
/// The length of the ROM data.
/// </param>
/// <param name="startAddr">
/// The start address to search from.
/// </param>
/// <param name="chunkType">
/// The chunk type to search for in the ROM.
/// </param>
/// <param name="anyChunk">
/// If true, then return any chunk instead of specific types specified by <paramref name="chunkType"/>.
/// </param>
/// <returns>
/// The next chunk of a specific type, or 0 if none exists.
/// </returns>
unsigned int FindChunkInROM(unsigned char *ROMData, unsigned int ROMLength, unsigned int startAddr, enum SaveDataChunkType chunkType, bool anyChunk)
{
if(startAddr >= ROMLength) return 0; // fail if not enough room in ROM
while(startAddr < ROMLength)
{
// Optimize search by incrementing more with partial matches
int STARmatch = StrMatch(ROMData + startAddr, "STAR");
if(STARmatch < 4)
{
// STAR not found at current address
startAddr += qMax(STARmatch, 1);
}
else
{
// STAR found at current address: validate the RATS checksum and chunk type
if(ValidRATS(ROMData + startAddr) && (anyChunk || ROMData[startAddr + 8] == chunkType))
{
return startAddr;
}
else
{
// Invalid RATS or chunk type not found: advance
startAddr += 4;
}
}
}
return 0;
}
/// <summary>
/// Find all chunks of a specific type.
/// </summary>
/// <param name="ROMData">
/// The pointer to the ROM data being processed.
/// </param>
/// <param name="ROMLength">
/// The length of the ROM data.
/// </param>
/// <param name="startAddr">
/// The start address to search from.
/// </param>
/// <param name="chunkType">
/// The chunk type to search for in the ROM.
/// </param>
/// <param name="anyChunk">
/// If true, then return any chunk instead of specific types specified by <paramref name="chunkType"/>.
/// </param>
/// <returns>
/// A list of all chunks of a specific type.
/// </returns>
QVector<unsigned int> FindAllChunksInROM(unsigned char *ROMData, unsigned int ROMLength, unsigned int startAddr, enum SaveDataChunkType chunkType, bool anyChunk)
{
QVector<unsigned int> chunks;
while(startAddr < ROMLength)
{
unsigned int chunkAddr = FindChunkInROM(ROMData, ROMLength, startAddr, chunkType, anyChunk);
if(chunkAddr)
{
chunks.append(chunkAddr);
unsigned int chunkLen = *reinterpret_cast<unsigned short*>(ROMData + chunkAddr + 4);
unsigned int extLen = (unsigned int) *reinterpret_cast<unsigned char*>(ROMData + chunkAddr + 9) << 16;
startAddr = chunkAddr + chunkLen + extLen + 12;
}
else break;
}
return chunks;
}
/// <summary>
/// Find all free space regions in the ROM.
/// </summary>
/// <param name="ROMData">
/// The pointer to the ROM data being processed.
/// </param>
/// <param name="ROMLength">
/// The length of the ROM data.
/// </param>
/// <returns>
/// A list of all free space regions.
/// </returns>
QVector<struct FreeSpaceRegion> FindAllFreeSpaceInROM(unsigned char *ROMData, unsigned int ROMLength)
{
QVector<struct FreeSpaceRegion> freeSpace;
unsigned int startAddr = WL4Constants::AvailableSpaceBeginningInROM;
unsigned int freeSpaceStart = startAddr;
// Search through ROM for chunks. The space between them is free space
while(startAddr < ROMLength)
{
// Optimize search by incrementing more with partial matches
int STARmatch = StrMatch(ROMData + startAddr, "STAR");
if(STARmatch < 4)
{
// STAR not found at current address
startAddr += qMax(STARmatch, 1);
}
else
{
// STAR found at current address: validate the RATS checksum and chunk type
if(ValidRATS(ROMData + startAddr))
{
// Chunk found. The space up to this point is free space
if(startAddr > freeSpaceStart)
{
freeSpace.append({freeSpaceStart, startAddr - freeSpaceStart});
}
// Continue search after this chunk
unsigned int chunkLen = *reinterpret_cast<unsigned short*>(ROMData + startAddr + 4);
unsigned int extLen = (unsigned int) *reinterpret_cast<unsigned char*>(ROMData + startAddr + 9) << 16;
startAddr += chunkLen + extLen + 12;
freeSpaceStart = startAddr;
}
else
{
// Invalid RATS or chunk type not found: advance
startAddr += 4;
}
}
}
// The last space in the ROM is a free space region
if(startAddr > freeSpaceStart)
{
freeSpace.append({freeSpaceStart, startAddr - freeSpaceStart});
}
return freeSpace;
}
/// <summary>
/// Save a list of chunks to the ROM file.
/// </summary>
/// <param name="filePath">
/// The file name to use when saving the ROM.
/// </param>
/// <param name="invalidationChunks">
/// Addresses of chunks to invalidate.
/// </param>
/// <param name="ChunkAllocator">
/// Callback function that allocates chunks.
/// The SaveFile function will offer potential free areas to the allocator, which will then
/// accept or reject the free area depending on how much space is actually needed.
/// </param>
/// <param name="PostProcessingCallback">
/// Post-processing to perform after writing the save chunks, but before saving the file itself.
/// This function returns an error string if unsuccessful, or an empty string if successful.
/// </param>
/// <returns>
/// True if the save was successful.
/// </returns>
bool SaveFile(QString filePath, QVector<unsigned int> invalidationChunks,
std::function<ChunkAllocationStatus (unsigned char*, struct FreeSpaceRegion, struct SaveData*, bool)> ChunkAllocator,
std::function<QString (unsigned char*, std::map<int, int>)> PostProcessingCallback)
{
// Finding space for the chunks can be done faster if the chunks are ordered by size
unsigned char *TempFile = (unsigned char *) malloc(CurrentFileSize);
unsigned int TempLength = CurrentFileSize;
memcpy(TempFile, CurrentFile, CurrentFileSize);
std::map<int, int> chunkIDtoIndex;
// Invalidate old chunk data
for(unsigned int invalidationChunk : invalidationChunks)
{
// Sanity check
if(invalidationChunk > CurrentFileSize)
{
singleton->GetOutputWidgetPtr()->PrintString(QString(QT_TR_NOOP("Internal error while saving changes to ROM: Invalidation chunk out of range of entire ROM. Address: %1"))
.arg("0x" + QString::number(invalidationChunk - 12, 16).toUpper()));
}
// Chunks can only be invalidated within valid chunk area
if (invalidationChunk > WL4Constants::AvailableSpaceBeginningInROM)
{
unsigned char *RATSaddr = TempFile + invalidationChunk - 12;
if (ValidRATS(RATSaddr)) // old_chunk_addr should point to the start of the chunk data, not the RATS tag
{
strncpy((char *) RATSaddr, "STAR_INV", 8);
}
else
{
singleton->GetOutputWidgetPtr()->PrintString(QString(QT_TR_NOOP("Internal error while saving changes to ROM: Invalidation chunk references an invalid RATS identifier for existing chunk. Address: %1. Changes not saved."))
.arg("0x" + QString::number(invalidationChunk - 12, 16).toUpper()));
return false;
}
}
}
// Find free space in the ROM and attempt to offer the free regions to the chunk allocator
QVector<struct FreeSpaceRegion> freeSpaceRegions;
QVector<struct SaveData> chunksToAdd;
std::map<int, int> indexToChunkPtr;
bool success = false;
bool resizerom = false; // act as a trigger to reset index in ChunkAllocator
resized:freeSpaceRegions.clear();
chunksToAdd.clear();
indexToChunkPtr.clear();
freeSpaceRegions = FindAllFreeSpaceInROM(TempFile, TempLength);
do
{
// Order free space regions by increasing size
std::sort(freeSpaceRegions.begin(), freeSpaceRegions.end(),
[](const struct FreeSpaceRegion &a, const struct FreeSpaceRegion &b)
{return a.size < b.size;});
// Offer free space to chunk allocator (starting with size of 12)
unsigned int lastSize = 11, newSize;
struct SaveData sd;
int i;
for(i = 0; i < freeSpaceRegions.size(); ++i)
{
if(freeSpaceRegions[i].size <= lastSize) continue;
ChunkAllocationStatus status = ChunkAllocator(TempFile, freeSpaceRegions[i], &sd, resizerom);
resizerom = false;
switch(status)
{
case Success:
goto spaceFound;
case NoMoreChunks:
goto allocationComplete;
case ProcessingError:
goto error;
case InsufficientSpace:
lastSize = freeSpaceRegions[i].size;
continue;
}
}
// No free space regions capable of accommodating chunk. Expand ROM
newSize = (TempLength << 1) & ~0x7FFFFF;
if(newSize <= 0x2000000)
{
unsigned char *newTempFile = (unsigned char*) realloc(TempFile, newSize);
if(!newTempFile)
{
// Realloc failed due to system memory constraints
QMessageBox::warning(
singleton,
QT_TR_NOOP("Out of memory"),
QT_TR_NOOP("Unable to save changes because your computer is out of memory."),
QMessageBox::Ok,
QMessageBox::Ok
);
goto error;
}
TempFile = newTempFile;
memset(TempFile + TempLength, 0xFF, newSize - TempLength);
TempLength = newSize;
resizerom = true;
goto resized;
}
else
{
// ROM size cannot exceed 32MB
QMessageBox::warning(
singleton,
QT_TR_NOOP("ROM too large"),
QString(QT_TR_NOOP("Unable to save changes because there is not enough free space, and the ROM file cannot be expanded larger than 32MB.")),
QMessageBox::Ok,
QMessageBox::Ok
);
goto error;
}
spaceFound:
// Split the free space region
struct FreeSpaceRegion freeSpace = freeSpaceRegions[i];
unsigned char *destPtr = TempFile + freeSpace.addr;
freeSpaceRegions.remove(i);
// Determine where the chunk starts if alignment would modify it
unsigned int alignedAddr = freeSpace.addr;
if(sd.alignment)
{
alignedAddr = (alignedAddr + 3) & ~3;
}
unsigned int alignmentOffset = alignedAddr - freeSpace.addr;
// If chunk data starts at an offset due to alignment, split on left side of data
if(alignmentOffset)
{
freeSpaceRegions.append({freeSpace.addr, alignmentOffset});
}
// If chunk data is smaller than free space, split on right side of data
if(alignmentOffset + sd.size < freeSpace.size)
{
freeSpaceRegions.append({
freeSpace.addr + alignmentOffset + sd.size + 12,
freeSpace.size - (alignmentOffset + sd.size) - 12
});
}
// Write the chunk metadata with RATS format
// Only write chunk headers after the alignment setting of the next chunk has been decided
destPtr += alignmentOffset;
strncpy(reinterpret_cast<char*>(destPtr), "STAR", 4);
unsigned short chunkLen = (unsigned short) (sd.size & 0xFFFF);
unsigned char extLen = (unsigned char) ((sd.size >> 16) & 0xFF);
*reinterpret_cast<unsigned short*>(destPtr + 4) = chunkLen;
*reinterpret_cast<unsigned short*>(destPtr + 6) = ~chunkLen;
*reinterpret_cast<unsigned int*>(destPtr + 8) = 0;
destPtr[8] = sd.ChunkType;
destPtr[9] = extLen;
// We cannot write the chunk data here because invalidated chunk data may still be used as part of new chunk creation at this step
indexToChunkPtr[sd.index] = alignedAddr;
chunksToAdd.append(sd);
} while(1);
allocationComplete:
// Generate chunkIDtoIndex map
for(int k = 0; k < chunksToAdd.size(); k++)
{
chunkIDtoIndex[chunksToAdd[k].index] = k;
}
// Apply source pointer modifications to applicable chunk types
for(struct SaveData chunk : chunksToAdd)
{
switch(chunk.ChunkType)
{
case SaveDataChunkType::InvalidationChunk:
singleton->GetOutputWidgetPtr()->PrintString(QT_TR_NOOP("Internal error: Chunk allocator created an invalidation chunk"));
case SaveDataChunkType::PatchListChunk:
case SaveDataChunkType::PatchChunk:
continue; // the above chunk types are not associated with a modified pointer in main ROM
default:;
}
unsigned char *ptrLoc = chunk.dest_index ?
// Source pointer is in another chunk
chunksToAdd[chunkIDtoIndex[chunk.dest_index]].data + chunk.ptr_addr
:
// Source pointer is in main ROM
TempFile + chunk.ptr_addr;
// We add 12 to the pointer location because the chunk ptr starts at the chunk's RATS tag
*reinterpret_cast<unsigned int*>(ptrLoc) = static_cast<unsigned int>((indexToChunkPtr[chunk.index] + 12) | 0x8000000);
}
// Write chunk data to TempFile
for(struct SaveData chunk : chunksToAdd)
{
if (chunk.ChunkType == SaveDataChunkType::InvalidationChunk)
{
continue;
}
// Write the chunk data
unsigned char *destPtr = TempFile + indexToChunkPtr[chunk.index];
memcpy(destPtr + 12, chunk.data, (unsigned short) chunk.size);
}
// Perform post-processing before saving the file
if(PostProcessingCallback)
{
QString ret(PostProcessingCallback(TempFile, indexToChunkPtr));
if(ret != "")
{
success = false;
goto error;
}
}
{ // Prevent goto from crossing initialization of variables here
// Save the rom file from the CurrentFile copy
QFile file(filePath);
file.open(QIODevice::WriteOnly);
if (file.isOpen())
{
file.write(reinterpret_cast<const char*>(TempFile), TempLength);
}
else
{
// Couldn't open the file to save the ROM
QMessageBox::warning(singleton, QT_TR_NOOP("Could not save file"),
QT_TR_NOOP("Unable to write to or create the ROM file for saving."), QMessageBox::Ok,
QMessageBox::Ok);
goto error;
}
file.close();
// Set the CurrentFile to the copied CurrentFile data
auto temp = CurrentFile;
CurrentFile = TempFile;
delete[] temp;
CurrentFileSize = TempLength;
}
// Set that there are no changes to the ROM now (so no save prompt is given)
singleton->SetUnsavedChanges(false);
// Clean up heap data and return
success = true;
if (0)
{
error: free(TempFile); // free up temporary file if there was a processing error
}
for(struct SaveData chunk : chunksToAdd)
{
if (chunk.ChunkType != SaveDataChunkType::InvalidationChunk)
{
free(chunk.data);
}
}
return success;
}
/// <summary>
/// Save the currently loaded level to the ROM file.
/// </summary>
/// <param name="filePath">
/// The file name to use when saving the ROM.
/// </param>
/// <returns>
/// True if the save was successful.
/// </returns>
bool SaveLevel(QString filePath)
{
SaveDataIndex = 1;
QVector<struct SaveData> chunks;
// Get save chunks for the level
LevelComponents::Level *currentLevel = singleton->GetCurrentLevel();
int levelHeaderOffset = WL4Constants::LevelHeaderIndexTable + currentLevel->GetPassage() * 24 + currentLevel->GetStage() * 4;
int levelHeaderIndex = ROMUtils::IntFromData(levelHeaderOffset);
int levelHeaderPointer = WL4Constants::LevelHeaderTable + levelHeaderIndex * 12;
if(!currentLevel->GetSaveChunks(chunks))
{
return false;
}
// Get Global instances chunks
for(int i = 0; i < 92; ++i)
{
if(singletonTilesets[i]->IsNewTileset())
{
GenerateTilesetSaveChunks(i, chunks);
}
}
for(int i = 0x11; i < 129; ++i) // we skip the first 0x10 sprites, they should be addressed differently
{
if(entities[i]->IsNewEntity())
{
GenerateEntitySaveChunks(i, chunks);
}
}
for(int i = 0; i < 90; ++i)
{
if(entitiessets[i]->IsNewEntitySet())
{
GenerateEntitySetSaveChunks(i, chunks);
}
}
// Isolate the room header chunk for post-processing
struct SaveData roomHeaderChunk = *std::find_if(chunks.begin(), chunks.end(), [](const struct SaveData &chunk) {
return chunk.ChunkType == SaveDataChunkType::RoomHeaderChunkType;
});
unsigned int roomHeaderInROM;
QVector<unsigned int> invalidationChunks;
QVector<struct SaveData> addedChunks;
for(int i = 0; i < chunks.size(); ++i)
{
if(chunks[i].ChunkType == SaveDataChunkType::InvalidationChunk)
{
invalidationChunks.append(chunks[i].old_chunk_addr);
}
else
{
if(chunks[i].old_chunk_addr >= WL4Constants::AvailableSpaceBeginningInROM)
{
invalidationChunks.append(chunks[i].old_chunk_addr);
}
addedChunks.append(chunks[i]);
}
}
// Save the level
int chunkIndex = 0;
bool ret = SaveFile(filePath, invalidationChunks,
// ChunkAllocator
[&chunkIndex, addedChunks]
(unsigned char *TempFile, struct FreeSpaceRegion freeSpace, struct SaveData *sd, bool resetchunkIndex)
{
(void) TempFile;
// This part of code will be triggered when rom size needs to be expanded
// So all the chunks will be reallocated
if(resetchunkIndex)
{
chunkIndex = 0;
}
if(chunkIndex >= addedChunks.size())
{
return ChunkAllocationStatus::NoMoreChunks;
}
// Get the size of the space that would be needed at this address depending on alignment
unsigned int alignOffset = 0;
if(addedChunks[chunkIndex].alignment)
{
unsigned int startAddr = (freeSpace.addr + 3) & ~3;
alignOffset = startAddr - freeSpace.addr;
}
// Check if there is space for the chunk in the offered area
// required_size > (freespace.size - alignment - 12 bytes (for header))
if(addedChunks[chunkIndex].size > freeSpace.size - alignOffset - 12)
{
// This will request a larger free area
return ChunkAllocationStatus::InsufficientSpace;
}
else
{
// Accept the offered free area for this save chunk
*sd = addedChunks[chunkIndex++];
return ChunkAllocationStatus::Success;
}
},
// PostProcessingCallback
[levelHeaderPointer, currentLevel, roomHeaderChunk, &roomHeaderInROM]
(unsigned char *TempFile, std::map<int, int> indexToChunkPtr)
{
// Capture pointer to new room header location
roomHeaderInROM = static_cast<unsigned int>(indexToChunkPtr[roomHeaderChunk.index] + 12);
// Write the level header to the ROM
memcpy(TempFile + levelHeaderPointer, currentLevel->GetLevelHeader(), sizeof(struct LevelComponents::__LevelHeader));
// Write Tileset data length and animtated tiles info
for(int i = 0; i < 92; ++i)
{
if(singletonTilesets[i]->IsNewTileset())
{
// Save Animated Tile info table
unsigned short *AnimatedTileInfoTable = singletonTilesets[i]->GetAnimatedTileData(0);
memcpy(TempFile + i * 32 + WL4Constants::AnimatedTileIdTableSwitchOff, (unsigned char*)AnimatedTileInfoTable, 32);
unsigned short *AnimatedTileInfoTable2 = singletonTilesets[i]->GetAnimatedTileData(1);
memcpy(TempFile + i * 32 + WL4Constants::AnimatedTileIdTableSwitchOn, (unsigned char*)AnimatedTileInfoTable2, 32);
unsigned char *AnimatedTileSwitchInfoTable = singletonTilesets[i]->GetAnimatedTileSwitchTable();
memcpy(TempFile + i * 16 + WL4Constants::AnimatedTileSwitchInfoTable, (unsigned char*)AnimatedTileSwitchInfoTable, 16);
// Reset size_of bgGFXLen and fgGBXLen
int tilesetPtr = singletonTilesets[i]->getTilesetPtr();
int fgGFXLenaddr = singletonTilesets[i]->GetfgGFXlen();
*(int *) (TempFile + tilesetPtr + 4) = fgGFXLenaddr;
int bgGFXLenaddr = singletonTilesets[i]->GetbgGFXlen();
*(int *) (TempFile + tilesetPtr + 16) = bgGFXLenaddr;
// don't needed, because this is done in the following internal pointers reset code
// singletonTilesets[i]->SetChanged(false);
}
}
// Write Sprite data length info
for(int i = 0x11; i < 129; ++i) // we skip the first 0x10 sprites, they should be addressed differently
{
if(entities[i]->IsNewEntity())
{
*(unsigned int *) (TempFile + WL4Constants::EntityTilesetLengthTable + 4 * (i - 0x10)) = entities[i]->GetPalNum() * (32 * 32 * 2);
}
}
return QString("");
}
);
if(!ret) return false;
// Set the new internal data pointers for LevelComponents objects, and mark dirty objects as clean
// --------------------------------------------------------------------
// Rooms instances internal pointers reset
// TODO: move out the unset dirty code, it is headache to do all of them here
// TODO: code needs to be changed if we are going to support saving all the changes in the whole ROM, every level, i mean
std::vector<LevelComponents::Room*> rooms = currentLevel->GetRooms();
for(unsigned int i = 0; i < rooms.size(); ++i)
{
struct LevelComponents::__RoomHeader *roomHeader = (struct LevelComponents::__RoomHeader*)
(CurrentFile + roomHeaderInROM + i * sizeof(struct LevelComponents::__RoomHeader));
unsigned int *layerDataPtrs = (unsigned int*) &roomHeader->Layer0Data;
LevelComponents::Room *room = rooms[i];
for(unsigned int j = 0; j < 4; ++j)
{
LevelComponents::Layer *layer = room->GetLayer(j);
layer->SetDataPtr(layerDataPtrs[j] & 0x7FFFFFF);
layer->SetDirty(false);
}
for(unsigned int j = 0; j < 3; ++j)
{
room->SetEntityListDirty(j, false);
}
struct LevelComponents::__RoomHeader newroomheader;
memcpy(&newroomheader, roomHeader, sizeof(newroomheader));
room->ResetRoomHeader(newroomheader);
}
// Tilesets instances internal pointers reset
for(int i = 0; i < 92; ++i)
{
if(singletonTilesets[i]->IsNewTileset())
{
int tilesetPtr = singletonTilesets[i]->getTilesetPtr();
singletonTilesets[i]->SetfgGFXptr(ROMUtils::PointerFromData(tilesetPtr));
singletonTilesets[i]->SetPaletteAddr(ROMUtils::PointerFromData(tilesetPtr + 8));
singletonTilesets[i]->Setmap16ptr(ROMUtils::PointerFromData(tilesetPtr + 0x14));
singletonTilesets[i]->SetChanged(false);
}
}
// Entities and Entitysets members reset
for(int i = 0x11; i < 129; ++i) // we skip the first 0x10 sprites, they should be addressed differently
{