forked from TASEmulators/BizHawk
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRomLoader.cs
More file actions
1148 lines (1015 loc) · 38.9 KB
/
RomLoader.cs
File metadata and controls
1148 lines (1015 loc) · 38.9 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
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using BizHawk.Common;
using BizHawk.Common.IOExtensions;
using BizHawk.Common.StringExtensions;
using BizHawk.Emulation.Common;
using BizHawk.Emulation.Cores;
using BizHawk.Emulation.Cores.Libretro;
using BizHawk.Emulation.Cores.Nintendo.Sameboy;
using BizHawk.Emulation.Cores.Nintendo.SNES;
using BizHawk.Emulation.Cores.Sony.PSX;
using BizHawk.Emulation.Cores.Arcades.MAME;
using BizHawk.Emulation.DiscSystem;
namespace BizHawk.Client.Common
{
public class RomLoader
{
private class DiscAsset : IDiscAsset
{
public Disc DiscData { get; set; }
public DiscType DiscType { get; set; }
public string DiscName { get; set; }
}
private class RomAsset : IRomAsset
{
public byte[] RomData { get; set; }
public byte[] FileData { get; set; }
public string Extension { get; set; }
public string RomPath { get; set; }
public GameInfo Game { get; set; }
}
private class CoreInventoryParameters : ICoreInventoryParameters
{
private readonly RomLoader _parent;
public CoreInventoryParameters(RomLoader parent)
{
_parent = parent;
}
public CoreComm Comm { get; set; }
public GameInfo Game { get; set; }
public List<IRomAsset> Roms { get; set; } = new List<IRomAsset>();
public List<IDiscAsset> Discs { get; set; } = new List<IDiscAsset>();
public bool DeterministicEmulationRequested => _parent.Deterministic;
public object FetchSettings(Type emulatorType, Type settingsType)
=> _parent.GetCoreSettings(emulatorType, settingsType);
public object FetchSyncSettings(Type emulatorType, Type syncSettingsType)
=> _parent.GetCoreSyncSettings(emulatorType, syncSettingsType);
}
private readonly Config _config;
public RomLoader(Config config)
{
_config = config;
}
public enum LoadErrorType
{
Unknown,
MissingFirmware,
Xml,
DiscError,
}
// helper methods for the settings events
private TSetting GetCoreSettings<TCore, TSetting>()
where TCore : IEmulator
{
return (TSetting)GetCoreSettings(typeof(TCore), typeof(TSetting));
}
private TSync GetCoreSyncSettings<TCore, TSync>()
where TCore : IEmulator
{
return (TSync)GetCoreSyncSettings(typeof(TCore), typeof(TSync));
}
private object GetCoreSettings(Type t, Type settingsType)
{
var e = new SettingsLoadArgs(t, settingsType);
if (OnLoadSettings == null)
throw new InvalidOperationException("Frontend failed to provide a settings getter");
OnLoadSettings(this, e);
if (e.Settings != null && e.Settings.GetType() != settingsType)
throw new InvalidOperationException($"Frontend did not provide the requested settings type: Expected {settingsType}, got {e.Settings.GetType()}");
return e.Settings;
}
private object GetCoreSyncSettings(Type t, Type syncSettingsType)
{
var e = new SettingsLoadArgs(t, syncSettingsType);
if (OnLoadSyncSettings == null)
throw new InvalidOperationException("Frontend failed to provide a sync settings getter");
OnLoadSyncSettings(this, e);
if (e.Settings != null && e.Settings.GetType() != syncSettingsType)
throw new InvalidOperationException($"Frontend did not provide the requested sync settings type: Expected {syncSettingsType}, got {e.Settings.GetType()}");
return e.Settings;
}
// For not throwing errors but simply outputting information to the screen
public Action<string, int?> MessageCallback { get; set; }
// TODO: reconsider the need for exposing these;
public IEmulator LoadedEmulator { get; private set; }
public GameInfo Game { get; private set; }
public RomGame Rom { get; private set; }
public string CanonicalFullPath { get; private set; }
public bool Deterministic { get; set; }
public class RomErrorArgs : EventArgs
{
// TODO: think about naming here, what to pass, a lot of potential good information about what went wrong could go here!
public RomErrorArgs(string message, string systemId, LoadErrorType type)
{
Message = message;
AttemptedCoreLoad = systemId;
Type = type;
}
public RomErrorArgs(string message, string systemId, string path, bool? det, LoadErrorType type)
: this(message, systemId, type)
{
Deterministic = det;
RomPath = path;
}
public string Message { get; }
public string AttemptedCoreLoad { get; }
public string RomPath { get; }
public bool? Deterministic { get; set; }
public bool Retry { get; set; }
public LoadErrorType Type { get; }
}
public class SettingsLoadArgs : EventArgs
{
public object Settings { get; set; }
public Type Core { get; }
public Type SettingsType { get; }
public SettingsLoadArgs(Type t, Type s)
{
Core = t;
SettingsType = s;
Settings = null;
}
}
public delegate void SettingsLoadEventHandler(object sender, SettingsLoadArgs e);
public event SettingsLoadEventHandler OnLoadSettings;
public event SettingsLoadEventHandler OnLoadSyncSettings;
public delegate void LoadErrorEventHandler(object sender, RomErrorArgs e);
public event LoadErrorEventHandler OnLoadError;
public Func<HawkFile, int?> ChooseArchive { get; set; }
public Func<RomGame, string> ChoosePlatform { get; set; }
// in case we get sent back through the picker more than once, use the same choice the second time
private int? _previousChoice;
private int? HandleArchive(HawkFile file)
{
if (_previousChoice.HasValue)
{
return _previousChoice;
}
if (ChooseArchive != null)
{
_previousChoice = ChooseArchive(file);
return _previousChoice;
}
return null;
}
// May want to phase out this method in favor of the overload with more parameters
private void DoLoadErrorCallback(string message, string systemId, LoadErrorType type = LoadErrorType.Unknown)
{
OnLoadError?.Invoke(this, new RomErrorArgs(message, systemId, type));
}
private void DoLoadErrorCallback(string message, string systemId, string path, bool det, LoadErrorType type = LoadErrorType.Unknown)
{
OnLoadError?.Invoke(this, new RomErrorArgs(message, systemId, path, det, type));
}
public IOpenAdvanced OpenAdvanced { get; set; }
private bool HandleArchiveBinding(HawkFile file, bool showDialog = true)
{
// try binding normal rom extensions first
if (!file.IsBound)
{
file.BindSoleItemOf(RomFileExtensions.AutoloadFromArchive);
}
// ...including unrecognised extensions that the user has set a platform for
if (!file.IsBound)
{
var exts = _config.PreferredPlatformsForExtensions.Where(static kvp => !string.IsNullOrEmpty(kvp.Value))
.Select(static kvp => kvp.Key)
.ToList();
if (exts.Count is not 0) file.BindSoleItemOf(exts);
}
// if we have an archive and need to bind something, then pop the dialog
if (file.IsArchive && !file.IsBound)
{
var result = showDialog ? HandleArchive(file) : null;
if (result.HasValue)
{
file.BindArchiveMember(result.Value);
}
else
{
return false;
}
}
CanonicalFullPath = file.CanonicalFullPath;
return true;
}
private GameInfo MakeGameFromDisc(Disc disc, string ext, string name, bool fastFailUnsupportedSystems = true)
{
// TODO - use more sophisticated IDer
var discType = new DiscIdentifier(disc).DetectDiscType();
var discHasher = new DiscHasher(disc);
var discHash = discHasher.CalculateBizHash(discType);
var game = Database.CheckDatabase(discHash);
if (game is not null) return game;
// else try to use our wizard methods
game = new GameInfo { Name = name, Hash = discHash };
void NoCoreForSystem(string sysID)
{
// no supported emulator core for these (yet)
game.System = sysID;
if (fastFailUnsupportedSystems) throw new NoAvailableCoreException(sysID);
}
switch (discType)
{
case DiscType.DOS:
game.System = VSystemID.Raw.DOS;
break;
case DiscType.SegaSaturn:
game.System = VSystemID.Raw.SAT;
break;
case DiscType.MegaCD:
game.System = VSystemID.Raw.GEN;
break;
case DiscType.PCFX:
game.System = VSystemID.Raw.PCFX;
break;
case DiscType.TurboGECD:
case DiscType.TurboCD:
game.System = VSystemID.Raw.PCE;
break;
case DiscType.JaguarCD:
game.System = VSystemID.Raw.Jaguar;
break;
case DiscType.Amiga:
NoCoreForSystem(VSystemID.Raw.Amiga);
break;
case DiscType.CDi:
NoCoreForSystem(VSystemID.Raw.PhillipsCDi);
break;
case DiscType.Dreamcast:
NoCoreForSystem(VSystemID.Raw.Dreamcast);
break;
case DiscType.GameCube:
NoCoreForSystem(VSystemID.Raw.GameCube);
break;
case DiscType.NeoGeoCD:
NoCoreForSystem(VSystemID.Raw.NeoGeoCD);
break;
case DiscType.Panasonic3DO:
NoCoreForSystem(VSystemID.Raw.Panasonic3DO);
break;
case DiscType.Playdia:
NoCoreForSystem(VSystemID.Raw.Playdia);
break;
case DiscType.SonyPS2:
NoCoreForSystem(VSystemID.Raw.PS2);
break;
case DiscType.SonyPSP:
NoCoreForSystem(VSystemID.Raw.PSP);
break;
case DiscType.Wii:
NoCoreForSystem(VSystemID.Raw.Wii);
break;
case DiscType.AudioDisc:
case DiscType.UnknownCDFS:
case DiscType.UnknownFormat:
game.System = _config.TryGetChosenSystemForFileExt(ext, out var sysID) ? sysID : VSystemID.Raw.NULL;
break;
default: //"for an unknown disc, default to psx instead of pce-cd, since that is far more likely to be what they are attempting to open" [5e07ab3ec3b8b8de9eae71b489b55d23a3909f55, year 2015]
case DiscType.SonyPSX:
game.System = VSystemID.Raw.PSX;
break;
}
return game;
}
private Disc/*?*/ InstantiateDiscFor(string path)
=> DiscExtensions.CreateAnyType(
path,
str => DoLoadErrorCallback(message: str, systemId: "???"/*TODO we should NOT be doing this, even if it's just for error display*/, LoadErrorType.DiscError));
private bool LoadDisc(string path, CoreComm nextComm, HawkFile file, string ext, string forcedCoreName, out IEmulator nextEmulator, out GameInfo game)
{
var disc = InstantiateDiscFor(path);
if (disc == null)
{
game = null;
nextEmulator = null;
return false;
}
game = MakeGameFromDisc(disc, ext, Path.GetFileNameWithoutExtension(file.Name));
var cip = new CoreInventoryParameters(this)
{
Comm = nextComm,
Game = game,
Discs =
{
new DiscAsset
{
DiscData = disc,
DiscType = new DiscIdentifier(disc).DetectDiscType(),
DiscName = Path.GetFileNameWithoutExtension(path),
},
},
};
nextEmulator = MakeCoreFromCoreInventory(cip, forcedCoreName);
return true;
}
private void LoadM3U(string path, CoreComm nextComm, HawkFile file, string forcedCoreName, out IEmulator nextEmulator, out GameInfo game)
{
M3U_File m3u;
using (var sr = new StreamReader(path))
m3u = M3U_File.Read(sr);
if (m3u.Entries.Count == 0)
throw new InvalidOperationException("Can't load an empty M3U");
m3u.Rebase(Path.GetDirectoryName(path));
var discs = m3u.Entries
.Select(e => e.Path)
.Where(p => Disc.IsValidExtension(Path.GetExtension(p)))
.Select(p => (p, d: DiscExtensions.CreateAnyType(p, str => DoLoadErrorCallback(str, "???", LoadErrorType.DiscError))))
.Where(a => a.d != null)
.Select(a => (IDiscAsset)new DiscAsset
{
DiscData = a.d,
DiscType = new DiscIdentifier(a.d).DetectDiscType(),
DiscName = Path.GetFileNameWithoutExtension(a.p),
})
.ToList();
if (discs.Count == 0)
throw new InvalidOperationException("Couldn't load any contents of the M3U as discs");
game = MakeGameFromDisc(discs[0].DiscData, Path.GetExtension(m3u.Entries[0].Path), discs[0].DiscName);
var cip = new CoreInventoryParameters(this)
{
Comm = nextComm,
Game = game,
Discs = discs,
};
nextEmulator = MakeCoreFromCoreInventory(cip, forcedCoreName);
}
private IEmulator MakeCoreFromCoreInventory(CoreInventoryParameters cip, string forcedCoreName = null)
{
IReadOnlyCollection<CoreInventory.Core> cores;
if (forcedCoreName != null)
{
var singleCore = CoreInventory.Instance.GetCores(cip.Game.System).SingleOrDefault(c => c.Name == forcedCoreName);
cores = singleCore != null ? new[] { singleCore } : Array.Empty<CoreInventory.Core>();
}
else
{
_ = _config.PreferredCores.TryGetValue(cip.Game.System, out var preferredCore);
var dbForcedCoreName = cip.Game.ForcedCore;
cores = CoreInventory.Instance.GetCores(cip.Game.System)
.OrderBy(c =>
{
if (c.Name == preferredCore)
{
return (int)CorePriority.UserPreference;
}
if (c.Name.EqualsIgnoreCase(dbForcedCoreName))
{
return (int)CorePriority.GameDbPreference;
}
return (int)c.Priority;
})
.ToList();
if (cores.Count == 0) throw new InvalidOperationException("No core was found to try on the game");
}
var exceptions = new List<Exception>();
foreach (var core in cores)
{
try
{
return core.Create(cip);
}
catch (Exception e)
{
if (_config.DontTryOtherCores || e is MissingFirmwareException || e.InnerException is MissingFirmwareException)
throw;
exceptions.Add(e);
}
}
throw new AggregateException("No core could load the game", exceptions);
}
private void LoadOther(
CoreComm nextComm,
HawkFile file,
string ext,
string forcedCoreName,
out IEmulator nextEmulator,
out RomGame rom,
out GameInfo game,
out bool cancel)
{
cancel = false;
rom = new RomGame(file);
// hacky for now
rom.GameInfo.System = ext switch
{
".exe" => VSystemID.Raw.PSX,
".nsf" => VSystemID.Raw.NES,
".gbs" => VSystemID.Raw.GB,
_ => rom.GameInfo.System,
};
Util.DebugWriteLine(rom.GameInfo.System);
if (string.IsNullOrEmpty(rom.GameInfo.System))
{
// Has the user picked a preference for this extension?
if (_config.TryGetChosenSystemForFileExt(rom.Extension.ToLowerInvariant(), out var systemID))
{
rom.GameInfo.System = systemID;
}
else if (ChoosePlatform != null)
{
var result = ChoosePlatform(rom);
if (!string.IsNullOrEmpty(result))
{
rom.GameInfo.System = result;
}
else
{
cancel = true;
}
}
}
game = rom.GameInfo;
nextEmulator = null;
if (game.System == null)
return; // The user picked nothing in the Core picker
switch (game.System)
{
case VSystemID.Raw.GB:
case VSystemID.Raw.GBC:
if (ext == ".gbs")
{
nextEmulator = new Sameboy(
nextComm,
rom.GameInfo,
rom.FileData,
GetCoreSettings<Sameboy, Sameboy.SameboySettings>(),
GetCoreSyncSettings<Sameboy, Sameboy.SameboySyncSettings>()
);
return;
}
if (_config.GbAsSgb)
{
game.System = VSystemID.Raw.SGB;
}
break;
case VSystemID.Raw.PSX when ext is ".bin":
if (TryLoadSiblingCue(
nextComm,
binFilePath: file.Name,
forcedCoreName: forcedCoreName,
out var nextEmulator1,
out var game1,
out cancel))
{
nextEmulator = nextEmulator1;
rom = null;
game = game1;
return;
}
if (cancel) break; //TODO return? the cancel earlier in this method doesn't
const string FILE_EXT_CUE = ".cue";
var crc32Digest = CRC32Checksum.ComputeDigestHex(file.GetStream().ReadAllBytes()); // slow!
var cuePath = Path.Combine(Path.GetTempPath(), $"synthesised for {crc32Digest}{FILE_EXT_CUE}");
DiscMountJob.CreateSyntheticCue(cueFilePath: cuePath, binFilePath: file.Name);
var gameBak = game;
var nextEmulatorBak = nextEmulator;
try
{
if (LoadDisc(
path: cuePath,
nextComm,
new(cuePath),
ext: FILE_EXT_CUE,
forcedCoreName: forcedCoreName,
out nextEmulator,
out game))
{
return;
}
Console.WriteLine("synthesised .cue failed to load");
}
catch (Exception e)
{
Console.WriteLine($"synthesised .cue failed to load: {e}");
}
game = gameBak;
nextEmulator = nextEmulatorBak;
break;
}
var cip = new CoreInventoryParameters(this)
{
Comm = nextComm,
Game = game,
Roms =
{
new RomAsset
{
RomData = rom.RomData,
FileData = rom.FileData,
Extension = rom.Extension,
RomPath = file.CanonicalFullPath,
Game = game,
},
},
};
nextEmulator = MakeCoreFromCoreInventory(cip, forcedCoreName);
}
private bool TryLoadSiblingCue(
CoreComm nextComm,
string binFilePath,
string forcedCoreName,
out IEmulator nextEmulator,
out GameInfo game,
out bool cancel)
{
nextEmulator = null;
game = null;
cancel = false;
const string FILE_EXT_CUE = ".cue";
const string FMT_STR_ASK = "Found \"{0}\".\nLoad that instead? Select \"No\" to synthesise a new .cue file for this game.";
HawkFile/*?*/ hfChosen = null;
//TODO can probably express this logic flow in a better way
HawkFile hfMatching = new(binFilePath.RemoveSuffix(".bin") + ".cue");
if (hfMatching.Exists)
{
var result = nextComm.Question(string.Format(FMT_STR_ASK, hfMatching.Name));
if (result is null)
{
cancel = true;
return false;
}
if (result is true)
{
hfChosen = hfMatching;
}
}
if (hfChosen is null)
{
var soleCueSiblingPath = Directory.EnumerateFiles(Path.GetDirectoryName(binFilePath))
.Where(static s => s.EndsWithOrdinal(FILE_EXT_CUE))
.Except([ hfMatching.Name ]) // seen but denied by user; don't prompt for the same file again
.SingleOrDefault();
HawkFile hfSoleSibling = soleCueSiblingPath is null ? null : new(soleCueSiblingPath);
if (hfSoleSibling is { Exists: true })
{
var result = nextComm.Question(string.Format(FMT_STR_ASK, hfSoleSibling.Name));
if (result is null)
{
cancel = true;
return false;
}
if (result is true)
{
hfChosen = hfSoleSibling;
}
}
}
if (hfChosen is null) return false;
return LoadDisc(
path: hfChosen.Name,
nextComm,
file: hfChosen,
ext: FILE_EXT_CUE,
forcedCoreName: forcedCoreName,
out nextEmulator,
out game);
}
private void LoadPSF(string path, CoreComm nextComm, HawkFile file, out IEmulator nextEmulator, out RomGame rom, out GameInfo game)
{
// TODO: Why does the PSF loader need CbDeflater provided? Surely this is a matter internal to it.
static byte[] CbDeflater(Stream instream, int size)
{
return new GZipStream(instream, CompressionMode.Decompress).ReadAllBytes();
}
var psf = new PSF();
psf.Load(path, CbDeflater);
nextEmulator = new Octoshock(
nextComm,
psf,
GetCoreSettings<Octoshock, Octoshock.Settings>(),
GetCoreSyncSettings<Octoshock, Octoshock.SyncSettings>()
);
// total garbage, this
rom = new RomGame(file);
game = rom.GameInfo;
}
// HACK due to MAME wanting CHDs as hard drives / handling it on its own (bad design, I know!)
// only matters for XML, as CHDs are never the "main" rom for MAME
// (in general, this is kind of bad as CHD hard drives might be useful for other future cores?)
private static bool IsDiscForXML(string system, string path)
{
if (HawkFile.PathContainsPipe(path))
{
return false;
}
var ext = Path.GetExtension(path);
if (system is VSystemID.Raw.Arcade && ".chd".EqualsIgnoreCase(ext))
{
return false;
}
return Disc.IsValidExtension(ext);
}
private bool LoadXML(string path, CoreComm nextComm, HawkFile file, string forcedCoreName, out IEmulator nextEmulator, out RomGame rom, out GameInfo game)
{
nextEmulator = null;
rom = null;
game = null;
try
{
var xmlGame = XmlGame.Create(file); // if load fails, are we supposed to retry as a bsnes XML????????
game = xmlGame.GI;
var system = game.System;
var cip = new CoreInventoryParameters(this)
{
Comm = nextComm,
Game = game,
Roms = xmlGame.Assets
.Where(pfd => !IsDiscForXML(system, pfd.Filename))
.Select(IRomAsset (pfd) => new RomAsset
{
RomData = pfd.FileData, // TODO: Do RomGame RomData conversions here
FileData = pfd.FileData,
Extension = Path.GetExtension(pfd.Filename),
RomPath = pfd.Path,
Game = Database.GetGameInfo(pfd.FileData, Path.GetFileName(pfd.Filename)),
})
.ToList(),
Discs = xmlGame.Assets
.Where(pfd => IsDiscForXML(system, pfd.Path))
.Select(pfd => (p: pfd.Path, d: DiscExtensions.CreateAnyType(pfd.Path, str => DoLoadErrorCallback(str, system, LoadErrorType.DiscError))))
.Where(a => a.d != null)
.Select(IDiscAsset (a) => new DiscAsset
{
DiscData = a.d,
DiscType = new DiscIdentifier(a.d).DetectDiscType(),
DiscName = Path.GetFileNameWithoutExtension(a.p),
})
.ToList(),
};
nextEmulator = MakeCoreFromCoreInventory(cip, forcedCoreName);
return true;
}
catch (Exception ex)
{
try
{
// need to get rid of this hack at some point
rom = new RomGame(file);
game = rom.GameInfo;
game.System = VSystemID.Raw.SNES;
nextEmulator = new LibsnesCore(
game,
null,
rom.FileData,
Path.GetDirectoryName(path.SubstringBefore('|')),
nextComm,
GetCoreSettings<LibsnesCore, LibsnesCore.SnesSettings>(),
GetCoreSyncSettings<LibsnesCore, LibsnesCore.SnesSyncSettings>()
);
return true;
}
catch
{
DoLoadErrorCallback(ex.ToString(), game?.System ?? VSystemID.Raw.SNES, LoadErrorType.Xml);
return false;
}
}
}
private void LoadMAME(
string path,
CoreComm nextComm,
HawkFile file,
string ext,
out IEmulator nextEmulator,
out RomGame rom,
out GameInfo game,
out bool cancel)
{
try
{
LoadOther(nextComm, file, ext: ext, forcedCoreName: null, out nextEmulator, out rom, out game, out cancel);
}
catch (Exception mex) // ok, MAME threw, let's try another core...
{
try
{
using var f = new HawkFile(path, allowArchives: true);
// we want to avoid opening up the choose file from archive dialog
// as it is very likely in this case this is actually a MAME ROM
// which case, we do want the error to be shown immediately, other cores won't load this
if (!HandleArchiveBinding(f, showDialog: false)) throw;
LoadOther(nextComm, f, ext: ext, forcedCoreName: null, out nextEmulator, out rom, out game, out cancel);
}
catch (Exception oex)
{
if (mex == oex) throw mex;
throw new AggregateException(mex, oex);
}
}
}
public bool LoadRom(string path, CoreComm nextComm, string launchLibretroCore, string forcedCoreName = null, int recursiveCount = 0)
{
if (path == null) return false;
if (recursiveCount > 1) // hack to stop recursive calls from endlessly rerunning if we can't load it
{
DoLoadErrorCallback("Failed multiple attempts to load ROM.", "");
return false;
}
bool allowArchives = true;
if (OpenAdvanced is OpenAdvanced_MAME || MAMEMachineDB.IsMAMEMachine(path)) allowArchives = false;
using var file = new HawkFile(path, false, allowArchives);
if (!file.Exists && OpenAdvanced is not OpenAdvanced_LibretroNoGame) return false; // if the provided file doesn't even exist, give up! (unless libretro no game is used)
CanonicalFullPath = file.CanonicalFullPath;
IEmulator nextEmulator;
RomGame rom = null;
GameInfo game = null;
try
{
var cancel = false;
if (OpenAdvanced is OpenAdvanced_Libretro or OpenAdvanced_LibretroNoGame)
{
// must be done before LoadNoGame (which triggers retro_init and the paths to be consumed by the core)
// game name == name of core
game = Disc.IsValidExtension(file.Extension)
? MakeGameFromDisc(
InstantiateDiscFor(path),
ext: file.Extension,
name: Path.GetFileNameWithoutExtension(file.Name),
fastFailUnsupportedSystems: false)
: new RomGame(file).GameInfo;
game.Name = $"{game.Name} [{Path.GetFileNameWithoutExtension(launchLibretroCore)}]";
game.System = VSystemID.Raw.Libretro;
var retro = new LibretroHost(nextComm, game, launchLibretroCore);
nextEmulator = retro;
if (retro.Description.SupportsNoGame && string.IsNullOrEmpty(path))
{
// if we are allowed to run NoGame and we don't have a game, boot up the core that way
if (!retro.LoadNoGame())
{
DoLoadErrorCallback("LibretroNoGame failed to load. This is weird", VSystemID.Raw.Libretro);
retro.Dispose();
return false;
}
}
else
{
bool ret;
// if the core requires an archive file, then try passing the filename of the archive
// (but do we ever need to actually load the contents of the archive file into ram?)
if (retro.Description.NeedsArchives)
{
if (file.IsArchiveMember)
{
throw new InvalidOperationException("Should not have bound file member for libretro block_extract core");
}
ret = retro.LoadPath(file.FullPathWithoutMember);
}
else
{
// otherwise load the data or pass the filename, as requested. but..
if (retro.Description.NeedsRomAsPath && file.IsArchiveMember)
{
throw new InvalidOperationException("Cannot pass archive member to libretro needs_fullpath core");
}
ret = retro.Description.NeedsRomAsPath
? retro.LoadPath(file.FullPathWithoutMember)
: HandleArchiveBinding(file) && retro.LoadData(file.ReadAllBytes(), file.Name);
}
if (!ret)
{
DoLoadErrorCallback("Libretro failed to load the given file. This is probably due to a core/content mismatch. Moreover, the process is now likely to be hosed. We suggest you restart the program.", VSystemID.Raw.Libretro);
retro.Dispose();
return false;
}
}
}
else
{
// do the archive binding we had to skip
if (!HandleArchiveBinding(file))
{
return false;
}
// not libretro: do extension checking
var ext = file.Extension;
switch (ext)
{
case ".m3u":
LoadM3U(path, nextComm, file, forcedCoreName, out nextEmulator, out game);
break;
case ".xml":
if (!LoadXML(path, nextComm, file, forcedCoreName, out nextEmulator, out rom, out game))
return false;
break;
case ".psf":
case ".minipsf":
LoadPSF(path, nextComm, file, out nextEmulator, out rom, out game);
break;
case ".zip" when forcedCoreName is null:
case ".7z" when forcedCoreName is null:
LoadMAME(path: path, nextComm, file, ext: ext, out nextEmulator, out rom, out game, out cancel);
break;
default:
if (Disc.IsValidExtension(ext))
{
if (file.IsArchive)
throw new InvalidOperationException("Can't load CD files from archives!");
if (!LoadDisc(path, nextComm, file, ext, forcedCoreName, out nextEmulator, out game))
return false;
}
else
{
// must be called after LoadXML because of SNES hacks
LoadOther(
nextComm,
file,
ext: ext,
forcedCoreName: forcedCoreName,
out nextEmulator,
out rom,
out game,
out cancel);
}
break;
}
}
if (nextEmulator == null)
{
if (!cancel)
{
DoLoadErrorCallback("No core could load the rom.", null);
}
return false;
}
if (game is null) throw new Exception("RomLoader returned core but no GameInfo"); // shouldn't be null if `nextEmulator` isn't? just in case
}
catch (Exception ex)
{
var system = game?.System;
DispatchErrorMessage(ex, system: system, path: path);
return false;
}
Rom = rom;
LoadedEmulator = nextEmulator;
Game = game;
return true;
}
private void DispatchErrorMessage(Exception ex, string system, string path)
{
if (ex is AggregateException agg)
{
// all cores failed to load a game, so tell the user everything that went wrong and maybe they can fix it
if (agg.InnerExceptions.Count > 1)
{
DoLoadErrorCallback("Multiple cores failed to load the rom:", system);
}
foreach (Exception e in agg.InnerExceptions)
{
DispatchErrorMessage(e, system: system, path: path);
}
return;
}
// all of the specific exceptions we're trying to catch here aren't expected to have inner exceptions,
// so drill down in case we got a TargetInvocationException or something like that
while (ex.InnerException != null)
ex = ex.InnerException;
if (ex is MissingFirmwareException)
{
DoLoadErrorCallback(ex.Message, system, path, Deterministic, LoadErrorType.MissingFirmware);
}
else if (ex is CGBNotSupportedException)
{
// failed to load SGB bios or game does not support SGB mode.
DoLoadErrorCallback("Failed to load a GB rom in SGB mode. You might try disabling SGB Mode.", system);
}
else if (ex is NoAvailableCoreException)
{
// handle exceptions thrown by the new detected systems that BizHawk does not have cores for
DoLoadErrorCallback($"{ex.Message}\n\n{ex}", system);
}
else
{
DoLoadErrorCallback($"A core accepted the rom, but threw an exception while loading it:\n\n{ex}", system);
}
}
/// <remarks>roms ONLY; when an archive is loaded with a single file whose extension is one of these, the user prompt is skipped</remarks>
private static class RomFileExtensions
{
public static readonly IReadOnlyCollection<string> A26 = new[] { "a26" };
public static readonly IReadOnlyCollection<string> A78 = new[] { "a78" };
public static readonly IReadOnlyCollection<string> Amiga = new[] { "adf", "adz", "dms", "fdi", /*"hdf", "ipf", "lha"*/ };
public static readonly IReadOnlyCollection<string> AppleII = new[] { "dsk", "do", "po" };
public static readonly IReadOnlyCollection<string> Arcade = new[] { "zip", "7z", "chd" };
public static readonly IReadOnlyCollection<string> C64 = new[] { "prg", "d64", "g64", "crt", "tap" };