-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathFF1Rom.cs
More file actions
2002 lines (1597 loc) · 63 KB
/
Copy pathFF1Rom.cs
File metadata and controls
2002 lines (1597 loc) · 63 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
global using System;
global using System.Collections.Generic;
global using System.IO;
global using System.Linq;
global using System.Text;
global using System.Threading.Tasks;
global using RomUtilities;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using FF1Lib.Procgen;
using FF1Lib.Assembly;
namespace FF1Lib;
// ReSharper disable once InconsistentNaming
public partial class FF1Rom : NesRom
{
public const int RngOffset = 0x7F100;
public const int BattleRngOffset = 0x7FCF1;
public const int RngSize = 256;
public const int LevelRequirementsOffset = 0x6CC81;
public const int LevelRequirementsSize = 3;
public const int LevelRequirementsCount = 49;
public const int StartingGoldOffset = 0x0301C;
public const int GoldItemOffset = 108; // 108 items before gold chests
public const int GoldItemCount = 68;
public List<int> UnusedGoldItems = new List<int> { 110, 111, 112, 113, 114, 116, 120, 121, 122, 124, 125, 127, 132, 158, 165, 166, 167, 168, 170, 171, 172 };
public ItemNames ItemsText;
public GearPermissions ArmorPermissions;
public GearPermissions WeaponPermissions;
public SpellPermissions SpellPermissions;
public GameClasses ClassData;
public DeepDungeon DeepDungeon;
private SanityCheckerV2 sanityChecker = null;
private IncentiveData incentivesData = null;
private Blob SavedHash;
public new void Put(int index, Blob data)
{
//Debug.Assert(index <= 0x4000 * 0x0E + 0x9F48 - 0x8000 && (index + data.Length) > 0x4000 * 0x0E + 0x9F48 - 0x8000);
base.Put(index, data);
}
public void PutInBank(int bank, int address, Blob data)
{
if (bank == 0x1F)
{
if ((address - 0xC000) + data.Length >= 0x4000)
{
throw new Exception("Data is too large to fit within its bank.");
}
int offset = (bank * 0x4000) + (address - 0xC000);
this.Put(offset, data);
}
else
{
if ((address - 0x8000) + data.Length >= 0x4000)
{
throw new Exception("Data is too large to fit within its bank.");
}
int offset = (bank * 0x4000) + (address - 0x8000);
this.Put(offset, data);
}
}
public Blob GetFromBank(int bank, int address, int length)
{
if (bank == 0x1F)
{
if ((address - 0xC000) + length > 0x4000)
{
throw new Exception("Data is too large to fit within one bank.");
}
int offset = (bank * 0x4000) + (address - 0xC000);
return this.Get(offset, length);
}
else
{
if ((address - 0x8000) + length > 0x4000)
{
throw new Exception("Data is too large to fit within one bank.");
}
int offset = (bank * 0x4000) + (address - 0x8000);
return this.Get(offset, length);
}
}
public void ApplyIpsPatch(Blob patch)
{
var romBytes = (Header + Data).ToBytes();
var patchBytes = (byte[])patch;
var startSig = Encoding.ASCII.GetBytes("PATCH");
var endSig = Encoding.ASCII.GetBytes("EOF");
var t = patchBytes.Take(startSig.Length).ToArray();
if (patch.Length < startSig.Length + endSig.Length
|| !Enumerable.SequenceEqual(patchBytes.Take(startSig.Length).ToArray(), startSig))
throw new Exception("Data is not a valid IPS patch");
var patchBuff = new BinaryBuffer(patchBytes);
patchBuff.Position = startSig.Length;
int endOffs = patchBytes.Length - 3;
var endBuff = new byte[3];
while (patchBuff.Position + 6 < endOffs)
{
patchBuff.Read(endBuff, 0, null, false);
if (Enumerable.SequenceEqual(endBuff, endSig))
break;
byte offsHi = patchBuff.ReadByte();
int offs = ((int)offsHi << 16) | patchBuff.ReadUInt16BE();
if (offs >= romBytes.Length)
throw new Exception($"Invalid patch offset at offset {patchBuff.Position - 3}");
int size = patchBuff.ReadUInt16BE();
if (size != 0)
{
// Direct patch
if (offs + size > romBytes.Length)
throw new Exception($"Invalid patch size at offset {patchBuff.Position - 2}");
patchBuff.Read(romBytes, offs, size);
}
else
{
// RLE patch
size = patchBuff.ReadUInt16BE();
if (offs + size > romBytes.Length)
throw new Exception($"Invalid patch RLE size at offset {patchBuff.Position - 2}");
byte value = patchBuff.ReadByte();
(new Span<byte>(romBytes, offs, size)).Fill(value);
}
}
patchBuff.Read(endBuff, 0, null, false);
if (!Enumerable.SequenceEqual(endBuff, endSig))
throw new Exception($"Invalid patch termination at offset {patchBuff.Position}");
Array.Copy(romBytes, (byte[])Header, 16);
Array.Copy(romBytes, 16, (byte[])Data, 0, romBytes.Length - 16);
}
public Blob CreateLongJumpTableEntry(byte bank, ushort addr)
{
List<byte> tmp = new List<byte> { 0x20, 0xC8, 0xD7 }; // JSR $D7C8, beginning of each table entry
var addrBytes = BitConverter.GetBytes(addr); // next add the address to jump to
tmp.Add(addrBytes[0]);
tmp.Add(addrBytes[1]);
tmp.Add(bank); //finally, add the bank that the routine is located in
return tmp.ToArray();
}
public FF1Rom(string filename) : base(filename)
{ }
public FF1Rom(Stream readStream) : base(readStream)
{ }
private FF1Rom()
{ }
public static async Task<FF1Rom> CreateAsync(Stream readStream)
{
var rom = new FF1Rom();
await rom.LoadAsync(readStream);
return rom;
}
public void LoadSharedDataTables()
{
ItemsText = new ItemNames(this);
ArmorPermissions = new GearPermissions(0x3BFA0, (int)Item.Cloth, this);
WeaponPermissions = new GearPermissions(0x3BF50, (int)Item.WoodenNunchucks, this);
SpellPermissions = new SpellPermissions(this);
ClassData = new GameClasses(WeaponPermissions, ArmorPermissions, SpellPermissions, this);
}
public delegate Task ProgressMessage(int step, int max, string message);
public delegate Task ReportProgress(string message="", int addMax=0);
int currentStep = 0;
int maxSteps = 0;
public ProgressMessage ProgressCallback;
public async Task Progress(string message="", int addMax=0)
{
maxSteps += addMax;
currentStep += 1;
if (ProgressCallback != null) {
await ProgressCallback(currentStep, maxSteps, message);
}
}
public async Task Randomize(Blob seed, Flags flags, Preferences preferences)
{
Flags flagsForRng = flags;
if (flags.OwMapExchange == OwMapExchanges.GenerateNewOverworld ||
flags.OwMapExchange == OwMapExchanges.LostWoods)
{
// Procgen maps can be either
// generated or imported. All else
// being equal, we want the user who
// generated the map
// (OwMapExchange == GenerateNewOverworld)
// and the user who imported the map
// (OwMapExchange == ImportCustomMap)
// to get the same ROM, so for the
// purposes of initializing the RNG
// consider them all to be
// "ImportCustomMap".
flagsForRng = flags.ShallowCopy();
flagsForRng.OwMapExchange = OwMapExchanges.ImportCustomMap;
}
Blob resourcesPackHash = new byte[1];
MT19337 rng;
using (SHA256 hasher = SHA256.Create())
{
if (flags.ResourcePack != null) {
var rp = new MemoryStream(Convert.FromBase64String(flags.ResourcePack));
if (flags.TournamentSafe || ResourcePackHasGameplayChanges(rp)) {
rp.Seek(0, SeekOrigin.Begin);
resourcesPackHash = hasher.ComputeHash(rp).ToArray();
}
}
Blob FlagsBlob = Encoding.UTF8.GetBytes(Flags.EncodeFlagsText(flagsForRng));
Blob SeedAndFlags = Blob.Concat(new Blob[] { FlagsBlob, seed, resourcesPackHash });
Blob hash = hasher.ComputeHash(SeedAndFlags);
rng = new MT19337(BitConverter.ToUInt32(hash, 0));
}
// We have to do "fun" stuff last because it alters the RNG state.
// Back up Rng so that fun flags are uniform when different ones are selected
uint funRngSeed = rng.Next();
await this.Progress("Beginning Randomization", 22);
if (flags.TournamentSafe) AssureSafe();
UpgradeToMMC3();
MakeSpace();
Bank1E();
Bank1B();
ApplyFfft();
EasterEggs();
DynamicWindowColor(preferences.MenuColor);
PermanentCaravan();
ShiftEarthOrbDown();
CastableItemTargeting();
FixEnemyPalettes(); // fixes a bug in the original game's programming that causes third enemy slot's palette to render incorrectly
FixWarpBug(); // The warp bug must be fixed for magic level shuffle and spellcrafter
UnifySpellSystem();
ExpandNormalTeleporters();
SeparateUnrunnables();
DrawCanoeUnderBridge();
LoadSharedDataTables();
await this.Progress();
DeepDungeon = new DeepDungeon(this);
var talkroutines = new TalkRoutines();
var npcdata = new NPCdata(this);
UpdateDialogs(npcdata, flags);
FF1Text.AddNewIcons(this, flags);
if (flags.TournamentSafe) Put(0x3FFE3, Blob.FromHex("66696E616C2066616E74617379"));
flags = Flags.ConvertAllTriState(flags, rng);
var palettes = OverworldMap.GeneratePalettes(Get(OverworldMap.MapPaletteOffset, MapCount * OverworldMap.MapPaletteSize).Chunk(OverworldMap.MapPaletteSize));
var overworldMap = new OverworldMap(this, flags, palettes);
var owMapExchange = await OwMapExchange.FromFlags(this, overworldMap, flags, rng);
owMapExchange?.ExecuteStep1();
await this.Progress();
TeleportShuffle teleporters = new TeleportShuffle(this, owMapExchange?.Data);
overworldMap.Teleporters = teleporters;
var shipLocations = owMapExchange?.ShipLocations ?? OwMapExchange.GetDefaultShipLocations(this);
// Ships found at Matoya's need to spawn at Coneria when Matoya's Dock no longer exists
if ((bool)flags.MapBridgeLefein == true) {
var ChangeDockLocation = shipLocations.GetShipLocation((int)OverworldTeleportIndex.MatoyasCave);
ChangeDockLocation.X = Dock.Coneria[0];
ChangeDockLocation.Y = Dock.Coneria[1];
ItemLocations.ShipLocations[MapLocation.MatoyasCave] = Dock.Coneria;
}
var maps = ReadMaps();
var shopItemLocation = ItemLocations.CaravanItemShop1;
var oldItemNames = ItemsText.ToList();
if ((bool)flags.NPCItems || (bool)flags.NPCFetchItems)
{
NPCShuffleDialogs();
}
if (flags.DesertOfDeath)
{
DesertOfDeath.ApplyDesertModifications(this, owMapExchange, npcdata);
}
await this.Progress();
if (flags.EFGWaterfall)
{
MapRequirements reqs;
MapGeneratorStrategy strategy;
MapGenerator generator = new MapGenerator();
reqs = new MapRequirements
{
MapId = MapId.Waterfall,
Rom = this,
};
strategy = MapGeneratorStrategy.WaterfallClone;
CompleteMap waterfall = generator.Generate(rng, strategy, reqs);
// Should add more into the reqs so that this can be done inside the generator.
teleporters.Waterfall.SetEntrance(waterfall.Entrance);
overworldMap.PutOverworldTeleport(OverworldTeleportIndex.Waterfall, teleporters.Waterfall);
maps[(int)MapId.Waterfall] = waterfall.Map;
}
if((bool)flags.OWDamageTiles || flags.DesertOfDeath)
{
EnableDamageTile();
}
if ((bool)flags.DamageTilesKill)
{
DamageTilesKill(flags.SaveGameWhenGameOver);
}
// Adjustable lava damage - run if anything other than the default of 1 damage
if ((int)flags.DamageTileLow != 1 || (int)flags.DamageTileHigh != 1)
{
int DamageTileAmount = rng.Between(flags.DamageTileLow, flags.DamageTileHigh);
AdjustDamageTileDamage(DamageTileAmount, (bool)flags.DamageTilesKill);
}
if ((bool)flags.MoveToFBats) {
MoveToFBats();
}
var mapFlipper = new FlippedMaps(this, maps, flags, rng);
var vflippedMaps = mapFlipper.VerticalFlipStep1();
if ((bool)flags.ReversedFloors) new ReversedFloors(this, maps, rng, vflippedMaps).Work();
var flippedMaps = new List<MapId>();
mapFlipper.VerticalFlipStep2();
teleporters.LoadData();
if ((bool)flags.FlipDungeons)
{
flippedMaps = mapFlipper.HorizontalFlip(rng, maps, teleporters, overworldMap);
}
if ((bool)flags.RandomizeFormationEnemizer)
{
DoEnemizer(rng, (bool)flags.RandomizeEnemizer, (bool)flags.RandomizeFormationEnemizer, flags.EnemizerDontMakeNewScripts);
}
await this.Progress();
if (preferences.ModernBattlefield)
{
EnableModernBattlefield();
}
if ((bool)flags.TitansTrove)
{
EnableTitansTrove(maps);
}
if (flags.GameMode == GameModes.DeepDungeon)
{
await this.Progress("Generating Deep Dungeon's Floors...", 2);
DeepDungeon.Generate(rng, overworldMap, maps, flags);
DeepDungeonFloorIndicator();
UnusedGoldItems = new List<int> { };
await this.Progress("Generating Deep Dungeon's Floors... Done!");
}
int warmMechFloor = DeepDungeon.WarMechFloor;
if ((bool)flags.LefeinShops)
{
EnableLefeinShops(maps);
}
if ((bool)flags.MelmondClinic)
{
EnableMelmondClinic(maps);
}
MapId attackedTown = MapId.Melmond;
if ((bool)flags.RandomVampAttack)
{
attackedTown = RandomVampireAttack(maps, (bool)flags.LefeinShops, (bool)flags.RandomVampAttackIncludesConeria, rng);
}
ShufflePravoka(flags, rng, maps, attackedTown == MapId.Pravoka);
if ((bool)flags.GaiaShortcut)
{
EnableGaiaShortcut(maps);
if ((bool)flags.MoveGaiaItemShop)
{
MoveGaiaItemShop(maps, rng);
}
}
if ((bool)flags.LefeinSuperStore && (flags.ShopKillMode_White == ShopKillMode.None && flags.ShopKillMode_Black == ShopKillMode.None))
{
EnableLefeinSuperStore(maps);
}
// This has to be done before we shuffle spell levels.
if (flags.SpellBugs)
{
FixSpellBugs();
FixEnemyAOESpells();
FixEnemyElementalResistances();
}
await this.Progress();
//must be done before spells get shuffled around otherwise we'd be changing a spell that isnt lock
if (flags.LockMode != LockHitMode.Vanilla)
{
ChangeLockMode(flags.LockMode);
}
if (flags.AllSpellLevelsForKnightNinja)
{
KnightNinjaChargesForAllLevels();
}
if ((bool)flags.AlternateFiends && !flags.SpookyFlag)
{
await this.Progress("Creating new Fiends", 1);
AlternativeFiends(rng);
}
if (flags.BuffTier1DamageSpells)
{
BuffTier1DamageSpells();
}
if (flags.BuffHealingSpells)
{
BuffHealingSpells();
}
UpdateMagicAutohitThreshold(rng, flags.MagicAutohitThreshold);
if ((bool)flags.GenerateNewSpellbook)
{
CraftNewSpellbook(rng, (bool)flags.SpellcrafterMixSpells, flags.LockMode, (bool)flags.MagicLevels, (bool)flags.SpellcrafterRetainPermissions);
}
if ((bool)flags.Weaponizer) {
Weaponizer(rng, (bool)flags.WeaponizerNamesUseQualityOnly, (bool)flags.WeaponizerCommonWeaponsHavePowers, flags.ItemMagicMode == ItemMagicMode.None);
}
if ((bool)flags.ArmorCrafter) {
ArmorCrafter(rng, flags.ItemMagicMode == ItemMagicMode.None, flags.RibbonMode == RibbonMode.Split);
}
if (flags.ItemMagicMode != ItemMagicMode.None && flags.ItemMagicMode != ItemMagicMode.Vanilla)
{
ShuffleItemMagic(rng, flags);
}
if (flags.GuaranteedDefenseItem != GuaranteedDefenseItem.None && !(flags.ItemMagicMode == ItemMagicMode.None))
{
CraftDefenseItem(flags);
}
await this.Progress();
if (flags.GuaranteedPowerItem != GuaranteedPowerItem.None && !(flags.ItemMagicMode == ItemMagicMode.None))
{
CraftPowerItem(flags);
}
new RibbonShuffle(this, rng, flags, ItemsText, ArmorPermissions).Work();
if ((bool)flags.ShortToFR)
{
ShortenToFR(maps, (bool)flags.PreserveFiendRefights, (bool)flags.PreserveAllFiendRefights, (bool)flags.ExitToFR, rng);
}
if ((bool)flags.ChaosFloorEncounters)
{
EnableChaosFloorEncounters(maps);
}
if ((bool)flags.ExitToFR)
{
EnableToFRExit(maps);
}
if (((bool)flags.Treasures) && flags.ShardHunt)
{
EnableShardHunt(rng, talkroutines, flags.ShardCount, preferences.randomShardNames);
}
if (!flags.ShardHunt && (flags.GameMode != GameModes.DeepDungeon))
{
SetOrbRequirement(rng, talkroutines, flags.OrbsRequiredCount, flags.OrbsRequiredMode, (bool)flags.OrbsRequiredSpoilers);
}
if (flags.TransformFinalFormation != FinalFormation.None && !flags.SpookyFlag)
{
TransformFinalFormation(flags.TransformFinalFormation, flags.EvadeCap, rng);
}
if ((bool)flags.EarlyOrdeals)
{
EnableEarlyOrdeals();
}
if ((bool)flags.OrdealsPillars)
{
ShuffleOrdeals(rng, maps);
}
if (flags.SkyCastle4FMazeMode == SkyCastle4FMazeMode.Maze && flags.GameMode != GameModes.DeepDungeon)
{
DoSkyCastle4FMaze(rng, maps);
}
else if (flags.SkyCastle4FMazeMode == SkyCastle4FMazeMode.Teleporters && flags.GameMode != GameModes.DeepDungeon)
{
ShuffleSkyCastle4F(rng, maps);
}
await this.Progress();
if ((bool)flags.EarlyKing)
{
EnableEarlyKing(npcdata);
}
if ((bool)flags.EarlySarda)
{
EnableEarlySarda(npcdata);
}
if ((bool)flags.EarlySage)
{
EnableEarlySage(npcdata);
}
if ((bool)flags.ChaosRush)
{
EnableChaosRush();
}
if ((bool)flags.IsBridgeFree && (!flags.DesertOfDeath))
{
EnableFreeBridge();
}
if ((bool)flags.IsAirshipFree)
{
EnableFreeAirship();
}
if ((bool)flags.IsShipFree)
{
EnableFreeShip();
}
if ((bool)flags.IsCanalFree)
{
EnableFreeCanal((bool)flags.NPCItems, npcdata);
}
await this.Progress();
if ((bool)flags.IsCanoeFree)
{
EnableFreeCanoe();
}
if ((bool)flags.FreeLute)
{
EnableFreeLute();
}
if ((bool)flags.FreeTail && !(bool)flags.NoTail)
{
EnableFreeTail();
}
if ((bool)flags.MapHallOfDragons) {
BahamutB1Encounters(maps);
}
DragonsHoard(maps, (bool)flags.MapDragonsHoard);
MermaidPrison(maps, (bool)flags.MermaidPrison);
var shopData = new ShopData(this);
shopData.LoadData();
var extConsumables = new ExtConsumables(this, flags, rng, shopData);
extConsumables.AddNormalShopEntries();
overworldMap.ApplyMapEdits();
if ((bool)flags.ShuffleChimeAccess) {
overworldMap.ShuffleChime(rng, (bool)flags.ShuffleChimeIncludeTowns);
}
if (flags.NoOverworld)
{
await this.Progress("Linking NoOverworld's Map", 1);
NoOverworld(overworldMap, maps, talkroutines, npcdata, flippedMaps, flags, rng);
}
if (flags.DraculasFlag)
{
// Needs to happen before item placement because it swaps some entrances around.
DraculasCurse(talkroutines, npcdata, rng, flags);
}
await this.Progress();
if ((bool)flags.ClassAsNpcFiends || (bool)flags.ClassAsNpcKeyNPC)
{
ClassAsNPC(flags, talkroutines, npcdata, flippedMaps, vflippedMaps, rng);
}
if (flags.NPCSwatter)
{
EnableNPCSwatter(npcdata);
}
if (flags.SpeedHacks)
{
SpeedHacksMoveNpcs();
}
if ((bool)flags.FightBahamut && !flags.SpookyFlag && !(bool)flags.RandomizeFormationEnemizer)
{
FightBahamut(talkroutines, npcdata, (bool)flags.NoTail, (bool)flags.SwoleBahamut, (flags.GameMode == GameModes.DeepDungeon), flags.EvadeCap, rng);
}
// NOTE: logic checking for relocated chests
// accounts for NPC locations and whether they
// are fightable/killable, so it needs to
// happen after anything that adds, removes or
// relocates NPCs or changes their routines.
if ((bool)flags.RelocateChests && flags.GameMode != GameModes.DeepDungeon)
{
await this.RandomlyRelocateChests(rng, maps, npcdata, flags);
}
EnterTeleData enterBackup = new EnterTeleData(this);
NormTeleData normBackup = new NormTeleData(this);
enterBackup.LoadData();
normBackup.LoadData();
var maxRetries = 3;
for (var i = 0; i < maxRetries; i++)
{
try
{
await this.Progress((bool)flags.Treasures ? "Shuffling Treasures - Retries: " + i : "Placing Treasures", 3);
enterBackup.StoreData();
normBackup.StoreData();
overworldMap = new OverworldMap(this, flags, palettes);
overworldMap.Teleporters = teleporters;
if (((bool)flags.Entrances || (bool)flags.Floors || (bool)flags.Towns) && ((bool)flags.Treasures) && ((bool)flags.NPCItems) && flags.GameMode == GameModes.Standard)
{
overworldMap.ShuffleEntrancesAndFloors(rng, flags);
}
// Disable the Princess Warp back to Castle Coneria
if ((bool)flags.Entrances || (bool)flags.Floors || (flags.GameMode == GameModes.Standard && flags.OwMapExchange != OwMapExchanges.None) || (flags.OrbsRequiredCount == 0 && !flags.ShardHunt))
talkroutines.ReplaceChunk(newTalkRoutines.Talk_Princess1, Blob.FromHex("20CC90"), Blob.FromHex("EAEAEA"));
if ((bool)flags.Treasures && (bool)flags.ShuffleObjectiveNPCs && (flags.GameMode != GameModes.DeepDungeon))
{
overworldMap.ShuffleObjectiveNPCs(rng);
}
incentivesData = new IncentiveData(rng, flags, overworldMap, shopItemLocation, new SanityCheckerV1());
await this.Progress();
if (((bool)flags.Shops))
{
var excludeItemsFromRandomShops = new List<Item>();
if ((bool)flags.Treasures)
{
excludeItemsFromRandomShops = incentivesData.ForcedItemPlacements.Select(x => x.Item).Concat(incentivesData.IncentiveItems).ToList();
}
if (!((bool)flags.RandomWaresIncludesSpecialGear))
{
excludeItemsFromRandomShops.AddRange(ItemLists.SpecialGear);
if (flags.GuaranteedDefenseItem != GuaranteedDefenseItem.None && !(flags.ItemMagicMode == ItemMagicMode.None))
excludeItemsFromRandomShops.Add(Item.PowerRod);
if (flags.GuaranteedPowerItem != GuaranteedPowerItem.None && !(flags.ItemMagicMode == ItemMagicMode.None))
excludeItemsFromRandomShops.Add(Item.PowerGauntlets);
}
if ((bool)flags.NoMasamune)
{
excludeItemsFromRandomShops.Add(Item.Masamune);
}
if ((bool)flags.NoXcalber)
{
excludeItemsFromRandomShops.Add(Item.Xcalber);
}
shopItemLocation = ShuffleShops(rng, (bool)flags.ImmediatePureAndSoftRequired, ((bool)flags.RandomWares), excludeItemsFromRandomShops, flags.WorldWealth, overworldMap.ConeriaTownEntranceItemShopIndex);
incentivesData = new IncentiveData(rng, flags, overworldMap, shopItemLocation, new SanityCheckerV1());
}
await this.Progress();
if (flags.GameMode == GameModes.DeepDungeon)
{
sanityChecker = new SanityCheckerV2(maps, overworldMap, npcdata, this, shopItemLocation, shipLocations);
generatedPlacement = DeepDungeon.ShuffleTreasures(flags, incentivesData, rng);
}
else if ((bool)flags.Treasures)
{
sanityChecker = new SanityCheckerV2(maps, overworldMap, npcdata, this, shopItemLocation, shipLocations);
generatedPlacement = ShuffleTreasures(rng, flags, incentivesData, shopItemLocation, overworldMap, teleporters, sanityChecker);
}
else if (owMapExchange != null)
{
sanityChecker = new SanityCheckerV2(maps, overworldMap, npcdata, this, shopItemLocation, shipLocations);
if (!sanityChecker.CheckSanity(ItemLocations.AllQuestItemLocations.ToList(), null, flags).Complete) throw new InsaneException("Not Completable");
}
break;
}
catch (InsaneException e)
{
Console.WriteLine(e.Message);
if (maxRetries > (i + 1)) continue;
throw new InvalidOperationException(e.Message);
}
}
List<string> funMessages = new()
{
"Placing Out of Bound Bat",
"Cleaning up Lich's closet",
"Labelling pots in Sarda's Cave",
"Partying in the Bat Party Room",
"Buffing up NPC's path-blocking AI",
"Debugging WarMech's software",
"Knocking down some impertinent fools",
"Sending Garland 2,000 years in the past",
"Giving a snack to Titan while waiting for the main course",
"Disguising Astos",
"Cursing the Elf Prince",
"Stealing Matoya's Crystal",
"Abducting Princess Sara",
"Placing the worst skills in Medusa's script",
"Applying for a Bridge building permit",
"Reticulating Splines",
"Digging Cave Holes",
"Bottling the Fairy",
"Floating the Sky Castle",
"Locking the door in Temple of Fiends",
"Teaching Kraken Kung Fu",
"Raising the Lich",
};
funMessages.AddRange(Enumerable.Repeat("Finalizing", funMessages.Count * 4).ToList());
await this.Progress(funMessages.PickRandom(rng));
// Change Astos routine so item isn't lost in wall of text
if ((bool)flags.NPCItems || (bool)flags.NPCFetchItems || (bool)flags.ShuffleAstos)
talkroutines.Replace(newTalkRoutines.Talk_Astos, Blob.FromHex("A674F005BD2060F027A57385612080B1B020A572203D96A5752020B1A476207F90207392A5611820109F201896A9F060A57060"));
npcdata.UpdateItemPlacement(generatedPlacement);
if ((bool)flags.MagicShopLocs)
{
ShuffleMagicLocations(rng, (bool)flags.MagicShopLocationPairs);
}
if (((bool)flags.MagicShops))
{
ShuffleMagicShops(rng);
}
if (((bool)flags.MagicLevels))
{
ShuffleMagicLevels(rng, ((bool)flags.MagicPermissions), (bool)flags.MagicLevelsTiered, (bool)flags.MagicLevelsMixed, (bool)!flags.GenerateNewSpellbook);
}
new StartingInventory(rng, flags, this).SetStartingInventory();
new StartingEquipment(rng, flags, this).SetStartingEquipment();
new ShopKiller(rng, flags, maps, this).KillShops();
shopData.LoadData();
new LegendaryShops(rng, flags, maps, flippedMaps, vflippedMaps, shopData, this).PlaceShops();
if (flags.GameMode == GameModes.DeepDungeon)
{
shopData.Shops.Find(x => x.Type == FF1Lib.ShopType.Item && x.Entries.Contains(Item.Bottle)).Entries.Remove(Item.Bottle);
shopData.StoreData();
}
//has to be done before modifying itemnames and after modifying spellnames...
extConsumables.LoadSpells();
await this.Progress();
if (preferences.AccessibleSpellNames)
{
AccessibleSpellNames(flags);
}
if (flags.SpellNameMadness != SpellNameMadness.None)
{
MixUpSpellNames(flags.SpellNameMadness, rng);
}
if (flags.EnableSoftInBattle)
{
EnableSoftInBattle();
}
if (flags.EnableLifeInBattle != LifeInBattleSetting.LifeInBattleOff)
{
EnableLifeInBattle(flags);
}
if (flags.TranceHasStatusElement)
{
TranceHasStatusElement();
}
/*
if (flags.WeaponPermissions)
{
ShuffleWeaponPermissions(rng);
}
if (flags.ArmorPermissions)
{
ShuffleArmorPermissions(rng);
}
*/
if (flags.SaveGameWhenGameOver)
{
EnableSaveOnDeath(flags, owMapExchange);
}
// Ordered before RNG shuffle. In the event that both flags are on, RNG shuffle depends on this.
if (((bool)flags.FixMissingBattleRngEntry))
{
FixMissingBattleRngEntry();
}
if (((bool)flags.Rng))
{
ShuffleRng(rng);
}
ShuffleEnemyScripts(rng, flags);
ShuffleEnemySkillsSpells(rng, flags);
StatusAttacks(flags, rng);
await this.Progress();
if ((bool)flags.UnrunnableShuffle) {
int UnrunnablePercent = rng.Between(flags.UnrunnablesLow, flags.UnrunnablesHigh);
// This is separate because the basic Imp formation is not otherwise included in the possible unrunnable formations
if (UnrunnablePercent >= 100)
CompletelyUnrunnable();
else
ShuffleUnrunnable(rng, flags, UnrunnablePercent);
}
// Always on to supply the correct changes for WaitWhenUnrunnable
AllowStrikeFirstAndSurprise(flags.WaitWhenUnrunnable, (bool)flags.UnrunnablesStrikeFirstAndSurprise);
if ((bool)flags.EnemyFormationsSurprise)
{
ShuffleSurpriseBonus(rng);
}
// Put this before other encounter / trap tile edits.
if ((bool)flags.AllowUnsafeMelmond)
{
EnableMelmondGhetto(flags.EnemizerEnabled);
}
// Weighted; Vanilla, Unleashed, and All are less likely
if (flags.WarMECHMode == WarMECHMode.Random)
{
int RandWarMECHMode = rng.Between(1, 100);
if (RandWarMECHMode <= 15)
flags.WarMECHMode = WarMECHMode.Vanilla; // 15%
else if (RandWarMECHMode <= 45)
flags.WarMECHMode = WarMECHMode.Patrolling; // 30%
else if (RandWarMECHMode <= 75)
flags.WarMECHMode = WarMECHMode.Required; // 30%
else if (RandWarMECHMode <= 90)
flags.WarMECHMode = WarMECHMode.Unleashed; // 15%
else
flags.WarMECHMode = WarMECHMode.All; // 10%
}
// After unrunnable shuffle and before formation shuffle. Perfect!
if (flags.WarMECHMode != WarMECHMode.Vanilla)
{
WarMECHNpc(flags.WarMECHMode, npcdata, rng, maps, flags.GameMode == GameModes.DeepDungeon, (MapId)warmMechFloor);
}
if (flags.WarMECHMode == WarMECHMode.Unleashed || flags.WarMECHMode == WarMECHMode.All)
{
UnleashWarMECH();
}
if ((bool)flags.FiendShuffle)
{
FiendShuffle(rng);
}
if (flags.FormationShuffleMode != FormationShuffleMode.None && !flags.EnemizerEnabled)
{
ShuffleEnemyFormations(rng, flags.FormationShuffleMode);
}
if (flags.EnemyTrapTiles == TrapTileMode.Remove)
{
RemoveTrapTiles(flags.EnemizerEnabled || flags.SetRNG);
}
await this.Progress();
if (flags.EnemyTrapTiles != TrapTileMode.Vanilla && flags.EnemyTrapTiles != TrapTileMode.Remove &&!flags.EnemizerEnabled)
{
ShuffleTrapTiles(rng, flags.EnemyTrapTiles, (bool)flags.FightBahamut);
}
if ((bool)flags.ConfusedOldMen)
{
EnableConfusedOldMen(rng);
}
if (flags.NoPartyShuffle)
{
DisablePartyShuffle();
}
if (flags.SpeedHacks)