Exemplo n.º 1
0
 private static PadSchema ConsoleButtons(Octoshock psx)
 {
     return(new PadSchema
     {
         DisplayName = "Console",
         IsConsole = true,
         DefaultSize = new Size(310, 400),
         Buttons = new[]
         {
             new PadSchema.ButtonSchema
             {
                 Name = "Reset",
                 DisplayName = "Reset",
                 Location = new Point(10, 15),
                 Type = PadSchema.PadInputType.Boolean
             },
             new PadSchema.ButtonSchema
             {
                 Name = "Disc Select",                         // not really, but shuts up a warning
                 Type = PadSchema.PadInputType.DiscManager,
                 Location = new Point(10, 54),
                 TargetSize = new Size(300, 300),
                 OwnerEmulator = psx,
                 SecondaryNames = new[] { "Open", "Close", "Disc Select" }
             }
         }
     });
 }
Exemplo n.º 2
0
        private void SyncLabels()
        {
            var temp     = _settings.Clone();
            var syncTemp = _syncSettings.Clone();

            SyncSettingsFromGui(temp, syncTemp);
            _settings.Validate();

            // actually, I think this is irrelevant. But it's nice in case we want to do some kind of a more detailed simulation later
            int w = _previewVideoSize.Width;
            int h = _previewVideoSize.Height;

            temp.ResolutionMode = Octoshock.eResolutionMode.PixelPro;
            var ri = Octoshock.CalculateResolution(_previewVideoStandard, temp, w, h);

            lblPixelPro.Text = _lblPixelProText.Replace("800x480", $"{ri.Resolution.Width}x{ri.Resolution.Height}");

            temp.ResolutionMode = Octoshock.eResolutionMode.Mednafen;
            ri = Octoshock.CalculateResolution(_previewVideoStandard, temp, w, h);
            lblMednafen.Text = _lblMednafenText.Replace("320x240", $"{ri.Resolution.Width}x{ri.Resolution.Height}");

            temp.ResolutionMode = Octoshock.eResolutionMode.TweakedMednafen;
            ri = Octoshock.CalculateResolution(_previewVideoStandard, temp, w, h);
            lblTweakedMednafen.Text = _lblTweakedMednafenText.Replace("400x300", $"{ri.Resolution.Width}x{ri.Resolution.Height}");
        }
Exemplo n.º 3
0
 private static PadSchema ConsoleButtons(Octoshock psx)
 {
     return(new ConsoleSchema
     {
         Size = new Size(310, 400),
         Buttons = new PadSchemaControl[]
         {
             new ButtonSchema(10, 15, "Reset"),
             new DiscManagerSchema(10, 54, new Size(300, 300), psx, new[] { "Open", "Close", "Disc Select" })
         }
     });
 }
Exemplo n.º 4
0
        void SyncLabels()
        {
            var temp = _settings.Clone();

            SyncGuiToTheseSettings(temp);
            _settings.Validate();

            //actually, I think this is irrelevant. But it's nice in case we want to do some kind of a more detailed simulation later
            int w = _previewVideoSize.Width;
            int h = _previewVideoSize.Height;

            temp.ResolutionMode = Octoshock.eResolutionMode.PixelPro;
            var size = Octoshock.CalculateResolution(_previewVideoStandard, temp, w, h);

            lblPixelPro.Text = lblPixelPro_text.Replace("800x480", string.Format("{0}x{1}", size.Width, size.Height));;

            temp.ResolutionMode = Octoshock.eResolutionMode.Mednafen;
            size             = Octoshock.CalculateResolution(_previewVideoStandard, temp, w, h);
            lblMednafen.Text = lblMednafen_text.Replace("320x240", string.Format("{0}x{1}", size.Width, size.Height));

            temp.ResolutionMode = Octoshock.eResolutionMode.TweakedMednafen;
            size = Octoshock.CalculateResolution(_previewVideoStandard, temp, w, h);
            lblTweakedMednafen.Text = lblTweakedMednafen_text.Replace("400x300", string.Format("{0}x{1}", size.Width, size.Height));
        }
Exemplo n.º 5
0
        protected void parseTextInputLog(BinaryReader br, Bk2Movie movie, MiscHeaderInfo info)
        {
            Octoshock.SyncSettings settings    = new Octoshock.SyncSettings();
            SimpleController       controllers = new SimpleController();

            settings.FIOConfig.Devices8 =
                new[] {
                info.player1Type,
                OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None,
                info.player2Type,
                OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None
            };
            controllers.Type = Octoshock.CreateControllerDefinition(settings);

            string[] buttons = { "Select", "L3", "R3", "Start", "Up",       "Right",  "Down",  "Left",
                                 "L2",     "R2", "L1", "R1",    "Triangle", "Circle", "Cross", "Square" };

            bool isCdTrayOpen = false;
            int  cdNumber     = 1;

            for (int frame = 0; frame < info.frameCount; ++frame)
            {
                if (info.player1Type != OctoshockDll.ePeripheralType.None)
                {
                    // As L3 and R3 don't exist on a standard gamepad, handle them separately later.  Unfortunately
                    // due to the layout, we handle select separately too first.
                    controllers["P1 Select"] = br.ReadChar() != '.';

                    if (info.player1Type == OctoshockDll.ePeripheralType.DualShock)
                    {
                        controllers["P1 L3"] = br.ReadChar() != '.';
                        controllers["P1 R3"] = br.ReadChar() != '.';
                    }

                    for (int button = 3; button < buttons.Length; button++)
                    {
                        controllers["P1 " + buttons[button]] = br.ReadChar() != '.';
                    }

                    if (info.player1Type == OctoshockDll.ePeripheralType.DualShock)
                    {
                        // The analog controls are encoded as four space-separated numbers with a leading space
                        string leftXRaw  = new string(br.ReadChars(4)).Trim();
                        string leftYRaw  = new string(br.ReadChars(4)).Trim();
                        string rightXRaw = new string(br.ReadChars(4)).Trim();
                        string rightYRaw = new string(br.ReadChars(4)).Trim();


                        Tuple <string, float> leftX  = new Tuple <string, float>("P1 LStick X", float.Parse(leftXRaw));
                        Tuple <string, float> leftY  = new Tuple <string, float>("P1 LStick Y", float.Parse(leftYRaw));
                        Tuple <string, float> rightX = new Tuple <string, float>("P1 RStick X", float.Parse(rightXRaw));
                        Tuple <string, float> rightY = new Tuple <string, float>("P1 RStick Y", float.Parse(rightYRaw));

                        controllers.AcceptNewFloats(new[] { leftX, leftY, rightX, rightY });
                    }
                }

                // Each controller is terminated with a pipeline.
                br.ReadChar();

                if (info.player2Type != OctoshockDll.ePeripheralType.None)
                {
                    // As L3 and R3 don't exist on a standard gamepad, handle them separately later.  Unfortunately
                    // due to the layout, we handle select separately too first.
                    controllers["P2 Select"] = br.ReadChar() != '.';

                    if (info.player2Type == OctoshockDll.ePeripheralType.DualShock)
                    {
                        controllers["P2 L3"] = br.ReadChar() != '.';
                        controllers["P2 R3"] = br.ReadChar() != '.';
                    }

                    for (int button = 3; button < buttons.Length; button++)
                    {
                        controllers["P2 " + buttons[button]] = br.ReadChar() != '.';
                    }

                    if (info.player2Type == OctoshockDll.ePeripheralType.DualShock)
                    {
                        // The analog controls are encoded as four space-separated numbers with a leading space
                        string leftXRaw  = new string(br.ReadChars(4)).Trim();
                        string leftYRaw  = new string(br.ReadChars(4)).Trim();
                        string rightXRaw = new string(br.ReadChars(4)).Trim();
                        string rightYRaw = new string(br.ReadChars(4)).Trim();


                        Tuple <string, float> leftX  = new Tuple <string, float>("P2 LStick X", float.Parse(leftXRaw));
                        Tuple <string, float> leftY  = new Tuple <string, float>("P2 LStick Y", float.Parse(leftYRaw));
                        Tuple <string, float> rightX = new Tuple <string, float>("P2 RStick X", float.Parse(rightXRaw));
                        Tuple <string, float> rightY = new Tuple <string, float>("P2 RStick Y", float.Parse(rightYRaw));

                        controllers.AcceptNewFloats(new[] { leftX, leftY, rightX, rightY });
                    }
                }

                // Each controller is terminated with a pipeline.
                br.ReadChar();

                byte controlState = br.ReadByte();
                controllers["Reset"] = (controlState & 0x02) != 0;
                if ((controlState & 0x04) != 0)
                {
                    if (isCdTrayOpen)
                    {
                        controllers["Close"] = true;
                        cdNumber++;
                    }
                    else
                    {
                        controllers["Open"] = true;
                    }
                    isCdTrayOpen = !isCdTrayOpen;
                }
                else
                {
                    controllers["Close"] = false;
                    controllers["Open"]  = false;
                }

                Tuple <string, float> discSelect = new Tuple <string, float>("Disc Select", cdNumber);
                controllers.AcceptNewFloats(new[] { discSelect });

                if ((controlState & 0xFC) != 0)
                {
                    Result.Warnings.Add("Ignored toggle hack flag on frame " + frame.ToString());
                }

                // Each controller is terminated with a pipeline.
                br.ReadChar();

                movie.AppendFrame(controllers);
            }
        }
Exemplo n.º 6
0
        protected void parseBinaryInputLog(BinaryReader br, Bk2Movie movie, MiscHeaderInfo info)
        {
            Octoshock.SyncSettings settings    = new Octoshock.SyncSettings();
            SimpleController       controllers = new SimpleController();

            settings.FIOConfig.Devices8 =
                new[] {
                info.player1Type,
                OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None,
                info.player2Type,
                OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None
            };
            controllers.Type = Octoshock.CreateControllerDefinition(settings);

            string[] buttons = { "Select", "L3", "R3", "Start", "Up",       "Right",  "Down",  "Left",
                                 "L2",     "R2", "L1", "R1",    "Triangle", "Circle", "Cross", "Square" };

            bool isCdTrayOpen = false;
            int  cdNumber     = 1;

            for (int frame = 0; frame < info.frameCount; ++frame)
            {
                if (info.player1Type != OctoshockDll.ePeripheralType.None)
                {
                    UInt16 controllerState = br.ReadUInt16();

                    // As L3 and R3 don't exist on a standard gamepad, handle them separately later.  Unfortunately
                    // due to the layout, we handle select separately too first.
                    controllers["P1 Select"] = (controllerState & 0x1) != 0;

                    for (int button = 3; button < buttons.Length; button++)
                    {
                        controllers["P1 " + buttons[button]] = (((controllerState >> button) & 0x1) != 0);
                        if (((controllerState >> button) & 0x1) != 0 && button > 15)
                        {
                            continue;
                        }
                    }

                    if (info.player1Type == OctoshockDll.ePeripheralType.DualShock)
                    {
                        controllers["P1 L3"] = (controllerState & 0x2) != 0;
                        controllers["P1 R3"] = (controllerState & 0x4) != 0;
                        Tuple <string, float> leftX  = new Tuple <string, float>("P1 LStick X", (float)br.ReadByte());
                        Tuple <string, float> leftY  = new Tuple <string, float>("P1 LStick Y", (float)br.ReadByte());
                        Tuple <string, float> rightX = new Tuple <string, float>("P1 RStick X", (float)br.ReadByte());
                        Tuple <string, float> rightY = new Tuple <string, float>("P1 RStick Y", (float)br.ReadByte());

                        controllers.AcceptNewFloats(new[] { leftX, leftY, rightX, rightY });
                    }
                }

                if (info.player2Type != OctoshockDll.ePeripheralType.None)
                {
                    UInt16 controllerState = br.ReadUInt16();
                    for (int button = 0; button < buttons.Length; button++)
                    {
                        controllers["P2 " + buttons[button]] = (((controllerState >> button) & 0x1) != 0);
                        if (((controllerState >> button) & 0x1) != 0 && button > 15)
                        {
                            continue;
                        }
                    }

                    if (info.player2Type == OctoshockDll.ePeripheralType.DualShock)
                    {
                        Tuple <string, float> leftX  = new Tuple <string, float>("P2 LStick X", (float)br.ReadByte());
                        Tuple <string, float> leftY  = new Tuple <string, float>("P2 LStick Y", (float)br.ReadByte());
                        Tuple <string, float> rightX = new Tuple <string, float>("P2 RStick X", (float)br.ReadByte());
                        Tuple <string, float> rightY = new Tuple <string, float>("P2 RStick Y", (float)br.ReadByte());

                        controllers.AcceptNewFloats(new[] { leftX, leftY, rightX, rightY });
                    }
                }

                byte controlState = br.ReadByte();
                controllers["Reset"] = (controlState & 0x02) != 0;
                if ((controlState & 0x04) != 0)
                {
                    if (isCdTrayOpen)
                    {
                        controllers["Close"] = true;
                        cdNumber++;
                    }
                    else
                    {
                        controllers["Open"] = true;
                    }
                    isCdTrayOpen = !isCdTrayOpen;
                }
                else
                {
                    controllers["Close"] = false;
                    controllers["Open"]  = false;
                }

                Tuple <string, float> discSelect = new Tuple <string, float>("Disc Select", cdNumber);
                controllers.AcceptNewFloats(new[] { discSelect });

                if ((controlState & 0xFC) != 0)
                {
                    Result.Warnings.Add("Ignored toggle hack flag on frame " + frame.ToString());
                }

                movie.AppendFrame(controllers);
            }
        }
Exemplo n.º 7
0
        public static DialogResult DoSettingsDialog(IMainFormForConfig mainForm, Config config, Octoshock psx)
        {
            var s    = psx.GetSettings();
            var ss   = psx.GetSyncSettings();
            var vid  = psx.SystemVidStandard;
            var size = psx.CurrentVideoSize;

            using var dlg = new PSXOptions(mainForm, config, s, ss, vid, size);

            var result = mainForm.ShowDialogAsChild(dlg);

            return(result);
        }
Exemplo n.º 8
0
        public bool LoadRom(string path, CoreComm nextComm, bool forceAccurateCore = false)         // forceAccurateCore is currently just for Quicknes vs Neshawk but could be used for other situations
        {
            bool cancel = false;

            if (path == null)
            {
                return(false);
            }

            using (var file = new HawkFile())
            {
                var romExtensions = new[] { "SMS", "SMC", "SFC", "PCE", "SGX", "GG", "SG", "BIN", "GEN", "MD", "SMD", "GB", "NES", "FDS", "ROM", "INT", "GBC", "UNF", "A78", "CRT", "COL", "XML", "Z64", "V64", "N64", "WS", "WSC", "GBA" };

                // lets not use this unless we need to
                // file.NonArchiveExtensions = romExtensions;
                file.Open(path);

                // if the provided file doesnt even exist, give up!
                if (!file.Exists)
                {
                    return(false);
                }

                // try binding normal rom extensions first
                if (!file.IsBound)
                {
                    file.BindSoleItemOf(romExtensions);
                }

                // if we have an archive and need to bind something, then pop the dialog
                if (file.IsArchive && !file.IsBound)
                {
                    int?result = HandleArchive(file);
                    if (result.HasValue)
                    {
                        file.BindArchiveMember(result.Value);
                    }
                    else
                    {
                        return(false);
                    }
                }

                // set this here so we can see what file we tried to load even if an error occurs
                CanonicalFullPath = file.CanonicalFullPath;

                IEmulator nextEmulator = null;
                RomGame   rom          = null;
                GameInfo  game         = null;

                try
                {
                    var ext = file.Extension.ToLower();
                    if (ext == ".m3u")
                    {
                        //HACK ZONE - currently only psx supports m3u
                        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");
                        }
                        //load discs for all the m3u
                        m3u.Rebase(Path.GetDirectoryName(path));
                        List <Disc>   discs     = new List <Disc>();
                        List <string> discNames = new List <string>();
                        foreach (var e in m3u.Entries)
                        {
                            Disc   disc     = null;
                            string discPath = e.Path;
                            string discExt  = Path.GetExtension(discPath).ToLower();
                            if (discExt == ".iso")
                            {
                                disc = Disc.FromIsoPath(discPath);
                            }
                            if (discExt == ".cue")
                            {
                                disc = Disc.FromCuePath(discPath, new CueBinPrefs());
                            }
                            if (discExt == ".ccd")
                            {
                                disc = Disc.FromCCDPath(discPath);
                            }
                            if (disc == null)
                            {
                                throw new InvalidOperationException("Can't load one of the files specified in the M3U");
                            }
                            discNames.Add(Path.GetFileNameWithoutExtension(discPath));
                            discs.Add(disc);
                        }
                        nextEmulator = new Octoshock(nextComm, discs, discNames, null, GetCoreSettings <Octoshock>(), GetCoreSyncSettings <Octoshock>());
                        nextEmulator.CoreComm.RomStatusDetails = "PSX etc.";
                        game = new GameInfo {
                            Name = Path.GetFileNameWithoutExtension(file.Name)
                        };
                        game.System = "PSX";
                    }
                    else if (ext == ".iso" || ext == ".cue" || ext == ".ccd")
                    {
                        if (file.IsArchive)
                        {
                            throw new InvalidOperationException("Can't load CD files from archives!");
                        }

                        Disc disc = null;
                        if (ext == ".iso")
                        {
                            disc = Disc.FromIsoPath(path);
                        }
                        if (ext == ".cue")
                        {
                            disc = Disc.FromCuePath(path, new CueBinPrefs());
                        }
                        if (ext == ".ccd")
                        {
                            disc = Disc.FromCCDPath(path);
                        }

                        var hash = disc.GetHash();
                        game = Database.CheckDatabase(hash);
                        if (game == null)
                        {
                            // try to use our wizard methods
                            game = new GameInfo {
                                Name = Path.GetFileNameWithoutExtension(file.Name), Hash = hash
                            };

                            switch (disc.DetectDiscType())
                            {
                            case DiscType.SegaSaturn:
                                game.System = "SAT";
                                break;

                            case DiscType.SonyPSP:
                                game.System = "PSP";
                                break;

                            default:
                            case DiscType.SonyPSX:
                                game.System = "PSX";
                                break;

                            case DiscType.MegaCD:
                                game.System = "GEN";
                                break;

                            case DiscType.TurboCD:
                            case DiscType.UnknownCDFS:
                            case DiscType.UnknownFormat:
                                game.System = "PCECD";
                                break;
                            }
                        }

                        switch (game.System)
                        {
                        case "GEN":
                            var genesis = new GPGX(
                                nextComm, null, disc, GetCoreSettings <GPGX>(), GetCoreSyncSettings <GPGX>());
                            nextEmulator = genesis;
                            break;

                        case "SAT":
                            nextEmulator = new Yabause(nextComm, disc, GetCoreSyncSettings <Yabause>());
                            break;

                        case "PSP":
                            nextEmulator = new PSP(nextComm, file.Name);
                            break;

                        case "PSX":
                            nextEmulator = new Octoshock(nextComm, new List <Disc>(new[] { disc }), new List <string>(new[] { Path.GetFileNameWithoutExtension(path) }), null, GetCoreSettings <Octoshock>(), GetCoreSyncSettings <Octoshock>());
                            nextEmulator.CoreComm.RomStatusDetails = "PSX etc.";
                            break;

                        case "PCE":
                        case "PCECD":
                            nextEmulator = new PCEngine(nextComm, game, disc, GetCoreSettings <PCEngine>(), GetCoreSyncSettings <PCEngine>());
                            break;
                        }
                    }
                    else if (file.Extension.ToLower() == ".xml")
                    {
                        try
                        {
                            var xmlGame = XmlGame.Create(file);                             // if load fails, are we supposed to retry as a bsnes XML????????
                            game = xmlGame.GI;

                            switch (game.System)
                            {
                            case "DGB":
                                var left  = Database.GetGameInfo(xmlGame.Assets["LeftRom"], "left.gb");
                                var right = Database.GetGameInfo(xmlGame.Assets["RightRom"], "right.gb");
                                nextEmulator = new GambatteLink(
                                    nextComm,
                                    left,
                                    xmlGame.Assets["LeftRom"],
                                    right,
                                    xmlGame.Assets["RightRom"],
                                    GetCoreSettings <GambatteLink>(),
                                    GetCoreSyncSettings <GambatteLink>(),
                                    Deterministic);

                                // other stuff todo
                                break;

                            case "AppleII":
                                var assets = xmlGame.Assets.Select(a => Database.GetGameInfo(a.Value, a.Key));
                                var roms   = xmlGame.Assets.Select(a => a.Value);
                                nextEmulator = new AppleII(
                                    nextComm,
                                    assets,
                                    roms,
                                    GetCoreSettings <AppleII>());
                                break;

                            default:
                                return(false);
                            }
                        }
                        catch (Exception ex)
                        {
                            try
                            {
                                // need to get rid of this hack at some point
                                rom = new RomGame(file);
                                ((CoreFileProvider)nextComm.CoreFileProvider).SubfileDirectory = Path.GetDirectoryName(path.Replace("|", String.Empty));                                 // Dirty hack to get around archive filenames (since we are just getting the directory path, it is safe to mangle the filename
                                byte[] romData = null;
                                byte[] xmlData = rom.FileData;

                                game        = rom.GameInfo;
                                game.System = "SNES";

                                var snes = new LibsnesCore(game, romData, Deterministic, xmlData, nextComm, GetCoreSettings <LibsnesCore>(), GetCoreSyncSettings <LibsnesCore>());
                                nextEmulator = snes;
                            }
                            catch
                            {
                                DoLoadErrorCallback(ex.ToString(), "DGB", LoadErrorType.XML);
                                return(false);
                            }
                        }
                    }
                    else                     // most extensions
                    {
                        rom = new RomGame(file);

                        //hacky for now
                        if (file.Extension.ToLower() == ".exe")
                        {
                            rom.GameInfo.System = "PSX";
                        }

                        if (string.IsNullOrEmpty(rom.GameInfo.System))
                        {
                            // Has the user picked a preference for this extension?
                            if (PreferredPlatformIsDefined(rom.Extension.ToLower()))
                            {
                                rom.GameInfo.System = Global.Config.PreferredPlatformsForExtensions[rom.Extension.ToLower()];
                            }
                            else if (ChoosePlatform != null)
                            {
                                var result = ChoosePlatform(rom);
                                if (!string.IsNullOrEmpty(result))
                                {
                                    rom.GameInfo.System = ChoosePlatform(rom);
                                }
                                else
                                {
                                    cancel = true;
                                }
                            }
                        }

                        game = rom.GameInfo;

                        var isXml = false;

                        // other xml has already been handled
                        if (file.Extension.ToLower() == ".xml")
                        {
                            game.System = "SNES";
                            isXml       = true;
                        }


                        CoreInventory.Core core = null;

                        switch (game.System)
                        {
                        default:
                            core = CoreInventory.Instance[game.System];
                            break;

                        case null:
                            // The user picked nothing in the Core picker
                            break;

                        case "83P":
                            var ti83Bios     = ((CoreFileProvider)nextComm.CoreFileProvider).GetFirmware("TI83", "Rom", true);
                            var ti83BiosPath = ((CoreFileProvider)nextComm.CoreFileProvider).GetFirmwarePath("TI83", "Rom", true);
                            using (var ti83AsHawkFile = new HawkFile())
                            {
                                ti83AsHawkFile.Open(ti83BiosPath);
                                var ti83BiosAsRom = new RomGame(ti83AsHawkFile);
                                var ti83          = new TI83(nextComm, ti83BiosAsRom.GameInfo, ti83Bios, GetCoreSettings <TI83>());
                                ti83.LinkPort.SendFileToCalc(File.OpenRead(path), false);
                                nextEmulator = ti83;
                            }
                            break;

                        case "SNES":
                            if (Global.Config.SNES_InSnes9x && VersionInfo.DeveloperBuild)
                            {
                                core = CoreInventory.Instance["SNES", "Snes9x"];
                            }
                            else
                            {
                                // need to get rid of this hack at some point
                                ((CoreFileProvider)nextComm.CoreFileProvider).SubfileDirectory = Path.GetDirectoryName(path.Replace("|", String.Empty));                                         // Dirty hack to get around archive filenames (since we are just getting the directory path, it is safe to mangle the filename
                                var romData = isXml ? null : rom.FileData;
                                var xmlData = isXml ? rom.FileData : null;
                                var snes    = new LibsnesCore(game, romData, Deterministic, xmlData, nextComm, GetCoreSettings <LibsnesCore>(), GetCoreSyncSettings <LibsnesCore>());
                                nextEmulator = snes;
                            }

                            break;

                        case "NES":
                            if (!Global.Config.NES_InQuickNES || forceAccurateCore)
                            {
                                core = CoreInventory.Instance["NES", "NesHawk"];
                            }
                            else
                            {
                                core = CoreInventory.Instance["NES", "QuickNes"];
                            }

                            break;

                        case "GB":
                        case "GBC":
                            if (!Global.Config.GB_AsSGB)
                            {
                                core = CoreInventory.Instance["GB", "Gambatte"];
                            }
                            else
                            {
                                try
                                {
                                    game.System = "SNES";
                                    game.AddOption("SGB");
                                    var snes = new LibsnesCore(game, rom.FileData, Deterministic, null, nextComm, GetCoreSettings <LibsnesCore>(), GetCoreSyncSettings <LibsnesCore>());
                                    nextEmulator = snes;
                                }
                                catch
                                {
                                    // failed to load SGB bios or game does not support SGB mode.
                                    // To avoid catch-22, disable SGB mode
                                    Global.Config.GB_AsSGB = false;
                                    throw;
                                }
                            }

                            break;

                        case "A78":
                            var gamedbpath = Path.Combine(PathManager.GetExeDirectoryAbsolute(), "gamedb", "EMU7800.csv");
                            nextEmulator = new Atari7800(nextComm, game, rom.RomData, gamedbpath);
                            break;

                        case "C64":
                            var c64 = new C64(nextComm, game, rom.RomData, rom.Extension);
                            nextEmulator = c64;
                            break;

                        case "AppleII":
                            var appleII = new AppleII(nextComm, game, rom.RomData, rom.Extension);
                            nextEmulator = appleII;
                            break;

                        case "GBA":
                            //core = CoreInventory.Instance["GBA", "Meteor"];
                            core = CoreInventory.Instance["GBA", "VBA-Next"];
                            break;

                        case "PSX":
                            nextEmulator = new Octoshock(nextComm, null, null, rom.FileData, GetCoreSettings <Octoshock>(), GetCoreSyncSettings <Octoshock>());
                            nextEmulator.CoreComm.RomStatusDetails = "PSX etc.";
                            break;

                        case "DEBUG":
                            if (VersionInfo.DeveloperBuild)
                            {
                                nextEmulator = LibRetroEmulator.CreateDebug(nextComm, rom.RomData);
                            }

                            break;
                        }

                        if (core != null)
                        {
                            // use coreinventory
                            nextEmulator = core.Create(nextComm, game, rom.RomData, rom.FileData, Deterministic, GetCoreSettings(core.Type), GetCoreSyncSettings(core.Type));
                        }
                    }

                    if (nextEmulator == null)
                    {
                        if (!cancel)
                        {
                            DoLoadErrorCallback("No core could load the rom.", null);
                        }
                        return(false);
                    }
                }
                catch (Exception ex)
                {
                    string system = null;
                    if (game != null)
                    {
                        system = game.System;
                    }

                    // 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;
                    }

                    // Specific hack here, as we get more cores of the same system, this isn't scalable
                    if (ex is UnsupportedGameException)
                    {
                        if (system == "NES")
                        {
                            DoMessageCallback("Unable to use quicknes, using NESHawk instead");
                        }

                        return(LoadRom(path, nextComm, forceAccurateCore: true));
                    }
                    else if (ex is MissingFirmwareException)
                    {
                        DoLoadErrorCallback(ex.Message, system, LoadErrorType.MissingFirmware);
                    }
                    else if (ex is CGBNotSupportedException)
                    {
                        // Note: GB as SGB was set to false by this point, otherwise we would want to do it here
                        DoMessageCallback("Failed to load a GB rom in SGB mode.  Disabling SGB Mode.");
                        return(LoadRom(path, nextComm));
                    }
                    else
                    {
                        DoLoadErrorCallback("A core accepted the rom, but threw an exception while loading it:\n\n" + ex, system);
                    }

                    return(false);
                }

                Rom            = rom;
                LoadedEmulator = nextEmulator;
                Game           = game;
                return(true);
            }
        }
Exemplo n.º 9
0
        public bool LoadRom(string path, CoreComm nextComm, bool forceAccurateCore = false,
                            int recursiveCount = 0) // forceAccurateCore is currently just for Quicknes vs Neshawk but could be used for other situations
        {
            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 cancel = false;

            if (path == null)
            {
                return(false);
            }

            using (var file = new HawkFile())
            {
                //only try mounting a file if a filename was given
                if (!string.IsNullOrEmpty(path))
                {
                    // lets not use this unless we need to
                    // file.NonArchiveExtensions = romExtensions;
                    file.Open(path);

                    // if the provided file doesnt even exist, give up!
                    if (!file.Exists)
                    {
                        return(false);
                    }
                }

                CanonicalFullPath = file.CanonicalFullPath;

                IEmulator nextEmulator = null;
                RomGame   rom          = null;
                GameInfo  game         = null;

                try
                {
                    string ext = null;

                    if (AsLibretro)
                    {
                        string codePathPart = Path.GetFileNameWithoutExtension(nextComm.LaunchLibretroCore);

                        var retro = new LibRetroEmulator(nextComm, nextComm.LaunchLibretroCore);
                        nextEmulator = retro;

                        //kind of dirty.. we need to stash this, and then we can unstash it in a moment, in case the core doesnt fail
                        var oldGame = Global.Game;

                        if (retro.Description.SupportsNoGame && string.IsNullOrEmpty(path))
                        {
                            //must be done before LoadNoGame (which triggers retro_init and the paths to be consumed by the core)
                            //game name == name of core
                            var gameName = codePathPart;
                            Global.Game = game = new GameInfo {
                                Name = gameName, System = "Libretro"
                            };

                            //if we are allowed to run NoGame and we dont have a game, boot up the core that way
                            bool ret = retro.LoadNoGame();

                            Global.Game = oldGame;

                            if (!ret)
                            {
                                DoLoadErrorCallback("LibretroNoGame failed to load. This is weird", "Libretro");
                                retro.Dispose();
                                return(false);
                            }
                        }
                        else
                        {
                            bool ret;

                            //must be done before LoadNoGame (which triggers retro_init and the paths to be consumed by the core)
                            //game name == name of core + extensionless_game_filename
                            var gameName = Path.Combine(codePathPart, Path.GetFileNameWithoutExtension(file.Name));
                            Global.Game = game = new GameInfo {
                                Name = gameName, System = "Libretro"
                            };

                            //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");
                                }

                                if (retro.Description.NeedsRomAsPath)
                                {
                                    ret = retro.LoadPath(file.FullPathWithoutMember);
                                }
                                else
                                {
                                    ret = HandleArchiveBinding(file);
                                    if (ret)
                                    {
                                        ret = retro.LoadData(file.ReadAllBytes());
                                    }
                                }
                            }

                            Global.Game = oldGame;

                            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.", "Libretro");
                                retro.Dispose();
                                return(false);
                            }
                        }
                    }
                    else
                    {
                        //if not libretro:

                        //do extension checknig
                        ext = file.Extension.ToLowerInvariant();

                        //do the archive binding we had to skip
                        if (!HandleArchiveBinding(file))
                        {
                            return(false);
                        }
                    }

                    if (string.IsNullOrEmpty(ext))
                    {
                    }
                    else if (ext == ".m3u")
                    {
                        //HACK ZONE - currently only psx supports m3u
                        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");
                        }
                        //load discs for all the m3u
                        m3u.Rebase(Path.GetDirectoryName(path));
                        List <Disc>   discs     = new List <Disc>();
                        List <string> discNames = new List <string>();
                        StringWriter  sw        = new StringWriter();
                        foreach (var e in m3u.Entries)
                        {
                            Disc   disc     = null;
                            string discPath = e.Path;

                            //--- load the disc in a context which will let us abort if it's going to take too long
                            var discMountJob = new DiscMountJob {
                                IN_FromPath = discPath
                            };
                            discMountJob.IN_SlowLoadAbortThreshold = 8;
                            discMountJob.Run();
                            disc = discMountJob.OUT_Disc;

                            if (discMountJob.OUT_SlowLoadAborted)
                            {
                                DoLoadErrorCallback("This disc would take too long to load. Run it through discohawk first, or find a new rip because this one is probably junk", "", LoadErrorType.DiscError);
                                return(false);
                            }

                            if (discMountJob.OUT_ErrorLevel)
                            {
                                throw new InvalidOperationException("\r\n" + discMountJob.OUT_Log);
                            }

                            if (disc == null)
                            {
                                throw new InvalidOperationException("Can't load one of the files specified in the M3U");
                            }

                            var discName = Path.GetFileNameWithoutExtension(discPath);
                            discNames.Add(discName);
                            discs.Add(disc);

                            var discType = new DiscIdentifier(disc).DetectDiscType();
                            sw.WriteLine("{0}", Path.GetFileName(discPath));
                            if (discType == DiscType.SonyPSX)
                            {
                                string discHash = new DiscHasher(disc).Calculate_PSX_BizIDHash().ToString("X8");
                                game = Database.CheckDatabase(discHash);
                                if (game == null || game.IsRomStatusBad() || game.Status == RomStatus.NotInDatabase)
                                {
                                    sw.WriteLine("Disc could not be identified as known-good. Look for a better rip.");
                                }
                                else
                                {
                                    sw.WriteLine("Disc was identified (99.99% confidently) as known good with disc id hash CRC32:{0:X8}", discHash);
                                    sw.WriteLine("Nonetheless it could be an unrecognized romhack or patched version.");
                                    sw.WriteLine("According to redump.org, the ideal hash for entire disc is: CRC32:{0:X8}", game.GetStringValue("dh"));
                                    sw.WriteLine("The file you loaded hasn't been hashed entirely (it would take too long)");
                                    sw.WriteLine("Compare it with the full hash calculated by the PSX menu's Hash Discs tool");
                                }
                            }
                            else
                            {
                                sw.WriteLine("Not a PSX disc");
                            }
                            sw.WriteLine("-------------------------");
                        }

                        nextEmulator = new Octoshock(nextComm, discs, discNames, null, GetCoreSettings <Octoshock>(), GetCoreSyncSettings <Octoshock>());
                        nextEmulator.CoreComm.RomStatusDetails = sw.ToString();
                        game = new GameInfo {
                            Name = Path.GetFileNameWithoutExtension(file.Name)
                        };
                        game.System = "PSX";
                    }
                    else if (ext == ".iso" || ext == ".cue" || ext == ".ccd")
                    {
                        if (file.IsArchive)
                        {
                            throw new InvalidOperationException("Can't load CD files from archives!");
                        }

                        string discHash = null;

                        //--- load the disc in a context which will let us abort if it's going to take too long
                        var discMountJob = new DiscMountJob {
                            IN_FromPath = path
                        };
                        discMountJob.IN_SlowLoadAbortThreshold = 8;
                        discMountJob.Run();

                        if (discMountJob.OUT_SlowLoadAborted)
                        {
                            DoLoadErrorCallback("This disc would take too long to load. Run it through discohawk first, or find a new rip because this one is probably junk", "", LoadErrorType.DiscError);
                            return(false);
                        }

                        if (discMountJob.OUT_ErrorLevel)
                        {
                            throw new InvalidOperationException("\r\n" + discMountJob.OUT_Log);
                        }

                        var disc = discMountJob.OUT_Disc;
                        //-----------

                        //TODO - use more sophisticated IDer
                        var discType = new DiscIdentifier(disc).DetectDiscType();
                        if (discType == DiscType.SonyPSX)
                        {
                            discHash = new DiscHasher(disc).Calculate_PSX_BizIDHash().ToString("X8");
                        }
                        else
                        {
                            discHash = new DiscHasher(disc).OldHash();
                        }

                        game = Database.CheckDatabase(discHash);
                        if (game == null)
                        {
                            // try to use our wizard methods
                            game = new GameInfo {
                                Name = Path.GetFileNameWithoutExtension(file.Name), Hash = discHash
                            };

                            switch (new DiscIdentifier(disc).DetectDiscType())
                            {
                            case DiscType.SegaSaturn:
                                game.System = "SAT";
                                break;

                            case DiscType.SonyPSP:
                                game.System = "PSP";
                                break;

                            default:
                            case DiscType.SonyPSX:
                                game.System = "PSX";
                                break;

                            case DiscType.MegaCD:
                                game.System = "GEN";
                                break;

                            case DiscType.AudioDisc:
                            case DiscType.TurboCD:
                            case DiscType.UnknownCDFS:
                            case DiscType.UnknownFormat:
                                game.System = "PCECD";
                                break;
                            }
                        }

                        switch (game.System)
                        {
                        case "GEN":
                            var genesis = new GPGX(
                                nextComm, null, disc, GetCoreSettings <GPGX>(), GetCoreSyncSettings <GPGX>());
                            nextEmulator = genesis;
                            break;

                        case "SAT":
                            nextEmulator = new Yabause(nextComm, disc, GetCoreSyncSettings <Yabause>());
                            break;

                        case "PSP":
                            nextEmulator = new PSP(nextComm, file.Name);
                            break;

                        case "PSX":
                            nextEmulator = new Octoshock(nextComm, new List <Disc>(new[] { disc }), new List <string>(new[] { Path.GetFileNameWithoutExtension(path) }), null, GetCoreSettings <Octoshock>(), GetCoreSyncSettings <Octoshock>());
                            if (game.IsRomStatusBad() || game.Status == RomStatus.NotInDatabase)
                            {
                                nextEmulator.CoreComm.RomStatusDetails = "Disc could not be identified as known-good. Look for a better rip.";
                            }
                            else
                            {
                                StringWriter sw = new StringWriter();
                                sw.WriteLine("Disc was identified (99.99% confidently) as known good with disc id hash CRC32:{0:X8}", discHash);
                                sw.WriteLine("Nonetheless it could be an unrecognized romhack or patched version.");
                                sw.WriteLine("According to redump.org, the ideal hash for entire disc is: CRC32:{0:X8}", game.GetStringValue("dh"));
                                sw.WriteLine("The file you loaded hasn't been hashed entirely (it would take too long)");
                                sw.WriteLine("Compare it with the full hash calculated by the PSX menu's Hash Discs tool");
                                nextEmulator.CoreComm.RomStatusDetails = sw.ToString();
                            }
                            break;

                        case "PCE":
                        case "PCECD":
                            nextEmulator = new PCEngine(nextComm, game, disc, GetCoreSettings <PCEngine>(), GetCoreSyncSettings <PCEngine>());
                            break;
                        }
                    }
                    else if (file.Extension.ToLowerInvariant() == ".xml")
                    {
                        try
                        {
                            var xmlGame = XmlGame.Create(file);                             // if load fails, are we supposed to retry as a bsnes XML????????
                            game = xmlGame.GI;

                            switch (game.System)
                            {
                            case "GB":
                            case "DGB":
                                // adelikat: remove need for tags to be hardcoded to left and right, we should clean this up, also maybe the DGB core should just take the xml file and handle it itself
                                var leftBytes  = xmlGame.Assets.First().Value;
                                var rightBytes = xmlGame.Assets.Skip(1).First().Value;

                                var left  = Database.GetGameInfo(leftBytes, "left.gb");
                                var right = Database.GetGameInfo(rightBytes, "right.gb");
                                nextEmulator = new GambatteLink(
                                    nextComm,
                                    left,
                                    leftBytes,
                                    right,
                                    rightBytes,
                                    GetCoreSettings <GambatteLink>(),
                                    GetCoreSyncSettings <GambatteLink>(),
                                    Deterministic);

                                // other stuff todo
                                break;

                            case "AppleII":
                                var assets = xmlGame.Assets.Select(a => Database.GetGameInfo(a.Value, a.Key));
                                var roms   = xmlGame.Assets.Select(a => a.Value);
                                nextEmulator = new AppleII(
                                    nextComm,
                                    assets,
                                    roms,
                                    (AppleII.Settings)GetCoreSettings <AppleII>());
                                break;

                            case "C64":
                                nextEmulator = new C64(
                                    nextComm,
                                    xmlGame.Assets.Select(a => a.Value),
                                    (C64.C64Settings)GetCoreSettings <C64>(),
                                    (C64.C64SyncSettings)GetCoreSyncSettings <C64>()
                                    );
                                break;

                            case "PSX":
                                var entries   = xmlGame.AssetFullPaths;
                                var discs     = new List <Disc>();
                                var discNames = new List <string>();
                                var sw        = new StringWriter();
                                foreach (var e in entries)
                                {
                                    Disc   disc     = null;
                                    string discPath = e;

                                    //--- load the disc in a context which will let us abort if it's going to take too long
                                    var discMountJob = new DiscMountJob {
                                        IN_FromPath = discPath
                                    };
                                    discMountJob.IN_SlowLoadAbortThreshold = 8;
                                    discMountJob.Run();
                                    disc = discMountJob.OUT_Disc;

                                    if (discMountJob.OUT_SlowLoadAborted)
                                    {
                                        DoLoadErrorCallback("This disc would take too long to load. Run it through discohawk first, or find a new rip because this one is probably junk", "PSX", LoadErrorType.DiscError);
                                        return(false);
                                    }

                                    if (discMountJob.OUT_ErrorLevel)
                                    {
                                        throw new InvalidOperationException("\r\n" + discMountJob.OUT_Log);
                                    }

                                    if (disc == null)
                                    {
                                        throw new InvalidOperationException("Can't load one of the files specified in the M3U");
                                    }

                                    var discName = Path.GetFileNameWithoutExtension(discPath);
                                    discNames.Add(discName);
                                    discs.Add(disc);

                                    var discType = new DiscIdentifier(disc).DetectDiscType();
                                    sw.WriteLine("{0}", Path.GetFileName(discPath));
                                    if (discType == DiscType.SonyPSX)
                                    {
                                        string discHash = new DiscHasher(disc).Calculate_PSX_BizIDHash().ToString("X8");
                                        game = Database.CheckDatabase(discHash);
                                        if (game == null || game.IsRomStatusBad() || game.Status == RomStatus.NotInDatabase)
                                        {
                                            sw.WriteLine("Disc could not be identified as known-good. Look for a better rip.");
                                        }
                                        else
                                        {
                                            sw.WriteLine("Disc was identified (99.99% confidently) as known good with disc id hash CRC32:{0:X8}", discHash);
                                            sw.WriteLine("Nonetheless it could be an unrecognized romhack or patched version.");
                                            sw.WriteLine("According to redump.org, the ideal hash for entire disc is: CRC32:{0:X8}", game.GetStringValue("dh"));
                                            sw.WriteLine("The file you loaded hasn't been hashed entirely (it would take too long)");
                                            sw.WriteLine("Compare it with the full hash calculated by the PSX menu's Hash Discs tool");
                                        }
                                    }
                                    else
                                    {
                                        sw.WriteLine("Not a PSX disc");
                                    }
                                    sw.WriteLine("-------------------------");
                                }

                                // todo: copy pasta from PSX .cue section
                                nextEmulator = new Octoshock(nextComm, discs, discNames, null, GetCoreSettings <Octoshock>(), GetCoreSyncSettings <Octoshock>());
                                nextEmulator.CoreComm.RomStatusDetails = sw.ToString();
                                game = new GameInfo {
                                    Name = Path.GetFileNameWithoutExtension(file.Name)
                                };
                                game.System = "PSX";

                                break;

                            default:
                                return(false);
                            }
                        }
                        catch (Exception ex)
                        {
                            try
                            {
                                // need to get rid of this hack at some point
                                rom = new RomGame(file);
                                ((CoreFileProvider)nextComm.CoreFileProvider).SubfileDirectory = Path.GetDirectoryName(path.Replace("|", string.Empty));                                 // Dirty hack to get around archive filenames (since we are just getting the directory path, it is safe to mangle the filename
                                byte[] romData = null;
                                byte[] xmlData = rom.FileData;

                                game        = rom.GameInfo;
                                game.System = "SNES";

                                var snes = new LibsnesCore(game, romData, Deterministic, xmlData, nextComm, GetCoreSettings <LibsnesCore>(), GetCoreSyncSettings <LibsnesCore>());
                                nextEmulator = snes;
                            }
                            catch
                            {
                                DoLoadErrorCallback(ex.ToString(), "DGB", LoadErrorType.XML);
                                return(false);
                            }
                        }
                    }
                    else if (file.Extension.ToLowerInvariant() == ".psf" || file.Extension.ToLowerInvariant() == ".minipsf")
                    {
                        Func <Stream, int, byte[]> cbDeflater = (Stream instream, int size) =>
                        {
                            var          inflater = new ICSharpCode.SharpZipLib.Zip.Compression.Inflater(false);
                            var          iis      = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream(instream, inflater);
                            MemoryStream ret      = new MemoryStream();
                            iis.CopyTo(ret);
                            return(ret.ToArray());
                        };
                        PSF psf = new PSF();
                        psf.Load(path, cbDeflater);
                        nextEmulator = new Octoshock(nextComm, psf, GetCoreSettings <Octoshock>(), GetCoreSyncSettings <Octoshock>());
                        nextEmulator.CoreComm.RomStatusDetails = "It's a PSF, what do you want. Oh, tags maybe?";

                        //total garbage, this
                        rom  = new RomGame(file);
                        game = rom.GameInfo;
                    }
                    else if (ext != null)                     // most extensions
                    {
                        rom = new RomGame(file);

                        //hacky for now
                        if (file.Extension.ToLowerInvariant() == ".exe")
                        {
                            rom.GameInfo.System = "PSX";
                        }
                        else if (file.Extension.ToLowerInvariant() == ".nsf")
                        {
                            rom.GameInfo.System = "NES";
                        }


                        if (string.IsNullOrEmpty(rom.GameInfo.System))
                        {
                            // Has the user picked a preference for this extension?
                            if (PreferredPlatformIsDefined(rom.Extension.ToLowerInvariant()))
                            {
                                rom.GameInfo.System = Global.Config.PreferredPlatformsForExtensions[rom.Extension.ToLowerInvariant()];
                            }
                            else if (ChoosePlatform != null)
                            {
                                var result = ChoosePlatform(rom);
                                if (!string.IsNullOrEmpty(result))
                                {
                                    rom.GameInfo.System = result;
                                }
                                else
                                {
                                    cancel = true;
                                }
                            }
                        }

                        game = rom.GameInfo;

                        var isXml = false;

                        // other xml has already been handled
                        if (file.Extension.ToLowerInvariant() == ".xml")
                        {
                            game.System = "SNES";
                            isXml       = true;
                        }


                        CoreInventory.Core core = null;

                        switch (game.System)
                        {
                        default:
                            core = CoreInventory.Instance[game.System];
                            break;

                        case null:
                            // The user picked nothing in the Core picker
                            break;

                        case "83P":
                            var ti83Bios     = ((CoreFileProvider)nextComm.CoreFileProvider).GetFirmware("TI83", "Rom", true);
                            var ti83BiosPath = ((CoreFileProvider)nextComm.CoreFileProvider).GetFirmwarePath("TI83", "Rom", true);
                            using (var ti83AsHawkFile = new HawkFile())
                            {
                                ti83AsHawkFile.Open(ti83BiosPath);
                                var ti83BiosAsRom = new RomGame(ti83AsHawkFile);
                                var ti83          = new TI83(nextComm, ti83BiosAsRom.GameInfo, ti83Bios, GetCoreSettings <TI83>());
                                ti83.LinkPort.SendFileToCalc(File.OpenRead(path), false);
                                nextEmulator = ti83;
                            }
                            break;

                        case "SNES":
                            if (Global.Config.SNES_InSnes9x && VersionInfo.DeveloperBuild)
                            {
                                core = CoreInventory.Instance["SNES", "Snes9x"];
                            }
                            else
                            {
                                // need to get rid of this hack at some point
                                ((CoreFileProvider)nextComm.CoreFileProvider).SubfileDirectory = Path.GetDirectoryName(path.Replace("|", String.Empty));                                         // Dirty hack to get around archive filenames (since we are just getting the directory path, it is safe to mangle the filename
                                var romData = isXml ? null : rom.FileData;
                                var xmlData = isXml ? rom.FileData : null;
                                var snes    = new LibsnesCore(game, romData, Deterministic, xmlData, nextComm, GetCoreSettings <LibsnesCore>(), GetCoreSyncSettings <LibsnesCore>());
                                nextEmulator = snes;
                            }

                            break;

                        case "NES":
                            if (!Global.Config.NES_InQuickNES || forceAccurateCore)
                            {
                                core = CoreInventory.Instance["NES", "NesHawk"];
                            }
                            else
                            {
                                core = CoreInventory.Instance["NES", "QuickNes"];
                            }

                            break;

                        case "GB":
                        case "GBC":
                            if (!Global.Config.GB_AsSGB)
                            {
                                core = CoreInventory.Instance["GB", "Gambatte"];
                            }
                            else
                            {
                                try
                                {
                                    game.System = "SNES";
                                    game.AddOption("SGB");
                                    var snes = new LibsnesCore(game, rom.FileData, Deterministic, null, nextComm, GetCoreSettings <LibsnesCore>(), GetCoreSyncSettings <LibsnesCore>());
                                    nextEmulator = snes;
                                }
                                catch
                                {
                                    // failed to load SGB bios or game does not support SGB mode.
                                    // To avoid catch-22, disable SGB mode
                                    Global.Config.GB_AsSGB = false;
                                    throw;
                                }
                            }

                            break;

                        case "A78":
                            var gamedbpath = Path.Combine(PathManager.GetExeDirectoryAbsolute(), "gamedb", "EMU7800.csv");
                            nextEmulator = new Atari7800(nextComm, game, rom.RomData, gamedbpath);
                            break;

                        case "C64":
                            var c64 = new C64(nextComm, Enumerable.Repeat(rom.RomData, 1), GetCoreSettings <C64>(), GetCoreSyncSettings <C64>());
                            nextEmulator = c64;
                            break;

                        case "GBA":
                            //core = CoreInventory.Instance["GBA", "Meteor"];
                            if (Global.Config.GBA_UsemGBA)
                            {
                                core = CoreInventory.Instance["GBA", "mGBA"];
                            }
                            else
                            {
                                core = CoreInventory.Instance["GBA", "VBA-Next"];
                            }
                            break;

                        case "PSX":
                            nextEmulator = new Octoshock(nextComm, null, null, rom.FileData, GetCoreSettings <Octoshock>(), GetCoreSyncSettings <Octoshock>());
                            nextEmulator.CoreComm.RomStatusDetails = "PSX etc.";
                            break;
                        }

                        if (core != null)
                        {
                            // use coreinventory
                            nextEmulator = core.Create(nextComm, game, rom.RomData, rom.FileData, Deterministic, GetCoreSettings(core.Type), GetCoreSyncSettings(core.Type));
                        }
                    }

                    if (nextEmulator == null)
                    {
                        if (!cancel)
                        {
                            DoLoadErrorCallback("No core could load the rom.", null);
                        }
                        return(false);
                    }
                }
                catch (Exception ex)
                {
                    string system = null;
                    if (game != null)
                    {
                        system = game.System;
                    }

                    // 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;
                    }

                    // Specific hack here, as we get more cores of the same system, this isn't scalable
                    if (ex is UnsupportedGameException)
                    {
                        if (system == "NES")
                        {
                            DoMessageCallback("Unable to use quicknes, using NESHawk instead");
                        }

                        return(LoadRom(path, nextComm, true, recursiveCount + 1));
                    }
                    else if (ex is MissingFirmwareException)
                    {
                        DoLoadErrorCallback(ex.Message, system, path, Deterministic, LoadErrorType.MissingFirmware);
                    }
                    else if (ex is CGBNotSupportedException)
                    {
                        // Note: GB as SGB was set to false by this point, otherwise we would want to do it here
                        DoMessageCallback("Failed to load a GB rom in SGB mode.  Disabling SGB Mode.");
                        return(LoadRom(path, nextComm, false, recursiveCount + 1));
                    }
                    else
                    {
                        DoLoadErrorCallback("A core accepted the rom, but threw an exception while loading it:\n\n" + ex, system);
                    }

                    return(false);
                }

                Rom            = rom;
                LoadedEmulator = nextEmulator;
                Game           = game;
                return(true);
            }
        }
        protected void ParseTextInputLog(BinaryReader br, IMovie movie, MiscHeaderInfo info)
        {
            Octoshock.SyncSettings settings    = new Octoshock.SyncSettings();
            SimpleController       controllers = new SimpleController();

            settings.FIOConfig.Devices8 = new[]
            {
                info.Player1Type,
                OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None,
                info.Player2Type,
                OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None
            };
            controllers.Definition = Octoshock.CreateControllerDefinition(settings);

            string[] buttons =
            {
                "Start", "Up", "Right", "Down", "Left",
                "L2",    "R2", "L1",    "R1",   "Triangle","Circle","Cross", "Square"
            };

            bool isCdTrayOpen = false;
            int  cdNumber     = 1;

            int player1Count = info.Player1Type == OctoshockDll.ePeripheralType.None ? 1 : info.Player1Type == OctoshockDll.ePeripheralType.Pad ? 15 : 33;
            int player2Count = info.Player2Type == OctoshockDll.ePeripheralType.None ? 1 : info.Player2Type == OctoshockDll.ePeripheralType.Pad ? 15 : 33;
            int strCount     = player1Count + player2Count + 4;         // 2 for control byte and pipe and line feed chars

            for (int frame = 0; frame < info.FrameCount; ++frame)
            {
                var mnemonicStr = new string(br.ReadChars(strCount));

                // Junk whitespace at the end of a file
                if (string.IsNullOrWhiteSpace(mnemonicStr))
                {
                    continue;
                }

                // Gross, if not CR LF, this will fail, but will the PSXjin?
                if (!mnemonicStr.EndsWith("|\r\n"))
                {
                    Result.Errors.Add("Unable to parse text input, unknown configuration");
                }

                var split      = mnemonicStr.Replace("\r\n", "").Split('|');
                var player1Str = split[0];
                var player2Str = split[1];
                var controlStr = split[2];
                if (info.Player1Type != OctoshockDll.ePeripheralType.None)
                {
                    // As L3 and R3 don't exist on a standard gamepad, handle them separately later.  Unfortunately
                    // due to the layout, we handle select separately too first.
                    controllers["P1 Select"] = player1Str[0] != '.';

                    if (info.Player1Type == OctoshockDll.ePeripheralType.DualShock)
                    {
                        controllers["P1 L3"] = player1Str[1] != '.';
                        controllers["P1 R3"] = player1Str[2] != '.';
                    }

                    int offSet = info.Player1Type == OctoshockDll.ePeripheralType.Pad ? 0 : 2;
                    for (int button = 1; button < buttons.Length; button++)
                    {
                        controllers[$"P1 {buttons[button]}"] = player1Str[button + offSet] != '.';
                    }

                    if (info.Player1Type == OctoshockDll.ePeripheralType.DualShock)
                    {
                        // The analog controls are encoded as four space-separated numbers with a leading space
                        string leftXRaw  = player1Str.Substring(16, 4);
                        string leftYRaw  = player1Str.Substring(20, 4);
                        string rightXRaw = player1Str.Substring(24, 4);
                        string rightYRaw = player1Str.Substring(28, 4);

                        var leftX  = ("P1 LStick X", (int)float.Parse(leftXRaw));
                        var leftY  = ("P1 LStick Y", (int)float.Parse(leftYRaw));
                        var rightX = ("P1 RStick X", (int)float.Parse(rightXRaw));
                        var rightY = ("P1 RStick Y", (int)float.Parse(rightYRaw));

                        controllers.AcceptNewAxes(new[] { leftX, leftY, rightX, rightY });
                    }
                }

                if (info.Player2Type != OctoshockDll.ePeripheralType.None)
                {
                    // As L3 and R3 don't exist on a standard gamepad, handle them separately later.  Unfortunately
                    // due to the layout, we handle select separately too first.
                    controllers["P2 Select"] = player2Str[0] != '.';

                    if (info.Player2Type == OctoshockDll.ePeripheralType.DualShock)
                    {
                        controllers["P2 L3"] = player2Str[1] != '.';
                        controllers["P2 R3"] = player2Str[2] != '.';
                    }

                    int offSet = info.Player2Type == OctoshockDll.ePeripheralType.Pad ? 0 : 2;
                    for (int button = 1; button < buttons.Length; button++)
                    {
                        controllers[$"P2 {buttons[button]}"] = player2Str[button + offSet] != '.';
                    }

                    if (info.Player2Type == OctoshockDll.ePeripheralType.DualShock)
                    {
                        // The analog controls are encoded as four space-separated numbers with a leading space
                        string leftXRaw  = player2Str.Substring(16, 4);
                        string leftYRaw  = player2Str.Substring(20, 4);
                        string rightXRaw = player2Str.Substring(24, 4);
                        string rightYRaw = player2Str.Substring(28, 4);

                        var leftX  = ("P2 LStick X", (int)float.Parse(leftXRaw));
                        var leftY  = ("P2 LStick Y", (int)float.Parse(leftYRaw));
                        var rightX = ("P2 RStick X", (int)float.Parse(rightXRaw));
                        var rightY = ("P2 RStick Y", (int)float.Parse(rightYRaw));

                        controllers.AcceptNewAxes(new[] { leftX, leftY, rightX, rightY });
                    }
                }

                byte controlState = (byte)controlStr[0];
                controllers["Reset"] = (controlState & 0x02) != 0;
                if ((controlState & 0x04) != 0)
                {
                    if (isCdTrayOpen)
                    {
                        controllers["Close"] = true;
                        cdNumber++;
                    }
                    else
                    {
                        controllers["Open"] = true;
                    }

                    isCdTrayOpen = !isCdTrayOpen;
                }
                else
                {
                    controllers["Close"] = false;
                    controllers["Open"]  = false;
                }

                var discSelect = ("Disc Select", cdNumber);
                controllers.AcceptNewAxes(new[] { discSelect });

                if ((controlState & 0xFC) != 0)
                {
                    Result.Warnings.Add($"Ignored toggle hack flag on frame {frame}");
                }

                movie.AppendFrame(controllers);
            }
        }
Exemplo n.º 11
0
 public PSXHashDiscs(Octoshock psx)
 {
     _psx = psx;
     InitializeComponent();
 }
Exemplo n.º 12
0
        public bool LoadRom(string path, CoreComm nextComm, bool forceAccurateCore = false)         // forceAccurateCore is currently just for Quicknes vs Neshawk but could be used for other situations
        {
            if (path == null)
            {
                return(false);
            }

            using (var file = new HawkFile())
            {
                var romExtensions = new[] { "SMS", "SMC", "SFC", "PCE", "SGX", "GG", "SG", "BIN", "GEN", "MD", "SMD", "GB", "NES", "FDS", "ROM", "INT", "GBC", "UNF", "A78", "CRT", "COL", "XML", "Z64", "V64", "N64", "WS", "WSC" };

                // lets not use this unless we need to
                // file.NonArchiveExtensions = romExtensions;
                file.Open(path);

                // if the provided file doesnt even exist, give up!
                if (!file.Exists)
                {
                    return(false);
                }

                // try binding normal rom extensions first
                if (!file.IsBound)
                {
                    file.BindSoleItemOf(romExtensions);
                }

                // if we have an archive and need to bind something, then pop the dialog
                if (file.IsArchive && !file.IsBound)
                {
                    var result = HandleArchive(file);
                    if (result.HasValue)
                    {
                        file.BindArchiveMember(result.Value);
                    }
                    else
                    {
                        return(false);
                    }
                }

                // set this here so we can see what file we tried to load even if an error occurs
                CanonicalFullPath = file.CanonicalFullPath;

                IEmulator nextEmulator = null;
                RomGame   rom          = null;
                GameInfo  game         = null;

                try
                {
                    var ext = file.Extension.ToLower();
                    if (ext == ".iso" || ext == ".cue")
                    {
                        var disc = ext == ".iso" ? Disc.FromIsoPath(path) : Disc.FromCuePath(path, new CueBinPrefs());
                        var hash = disc.GetHash();
                        game = Database.CheckDatabase(hash);
                        if (game == null)
                        {
                            // try to use our wizard methods
                            game = new GameInfo {
                                Name = Path.GetFileNameWithoutExtension(file.Name), Hash = hash
                            };

                            switch (disc.DetectDiscType())
                            {
                            case DiscType.SegaSaturn:
                                game.System = "SAT";
                                break;

                            case DiscType.SonyPSP:
                                game.System = "PSP";
                                break;

                            case DiscType.SonyPSX:
                                game.System = "PSX";
                                break;

                            case DiscType.MegaCD:
                                game.System = "GEN";
                                break;

                            case DiscType.TurboCD:
                            case DiscType.UnknownCDFS:
                            case DiscType.UnknownFormat:
                            default:                                     // PCECD was bizhawk's first CD core,
                                // and during that time, all CDs were blindly sent to it
                                // so this prevents regressions
                                game.System = "PCECD";
                                break;
                            }
                        }

                        switch (game.System)
                        {
                        case "GEN":
                            var genesis = new GPGX(
                                nextComm, null, disc, "GEN", GetCoreSettings <GPGX>(), GetCoreSyncSettings <GPGX>());
                            nextEmulator = genesis;
                            break;

                        case "SAT":
                            nextEmulator = new Yabause(nextComm, disc, GetCoreSyncSettings <Yabause>());
                            break;

                        case "PSP":
                            nextEmulator = new PSP(nextComm, file.Name);
                            break;

                        case "PSX":
                            nextEmulator = new Octoshock(nextComm);
                            (nextEmulator as Octoshock).LoadCuePath(file.CanonicalFullPath);
                            nextEmulator.CoreComm.RomStatusDetails = "PSX etc.";
                            break;

                        case "PCE":
                        case "PCECD":
                            nextEmulator = new PCEngine(nextComm, game, disc, GetCoreSettings <PCEngine>(), GetCoreSyncSettings <PCEngine>());
                            break;
                        }
                    }
                    else if (file.Extension.ToLower() == ".xml")
                    {
                        try
                        {
                            var xmlGame = XmlGame.Create(file);                             // if load fails, are we supposed to retry as a bsnes XML????????
                            game = xmlGame.GI;

                            switch (game.System)
                            {
                            case "DGB":
                                var left  = Database.GetGameInfo(xmlGame.Assets["LeftRom"], "left.gb");
                                var right = Database.GetGameInfo(xmlGame.Assets["RightRom"], "right.gb");
                                nextEmulator = new GambatteLink(
                                    nextComm,
                                    left,
                                    xmlGame.Assets["LeftRom"],
                                    right,
                                    xmlGame.Assets["RightRom"],
                                    GetCoreSettings <GambatteLink>(),
                                    GetCoreSyncSettings <GambatteLink>(),
                                    Deterministic);

                                // other stuff todo
                                break;

                            default:
                                return(false);
                            }
                        }
                        catch (Exception ex)
                        {
                            DoLoadErrorCallback(ex.ToString(), "DGB", LoadErrorType.XML);
                            return(false);
                        }
                    }
                    else                     // most extensions
                    {
                        rom = new RomGame(file);

                        if (string.IsNullOrEmpty(rom.GameInfo.System))
                        {
                            // Has the user picked a preference for this extension?
                            if (PreferredPlatformIsDefined(rom.Extension.ToLower()))
                            {
                                rom.GameInfo.System = Global.Config.PreferredPlatformsForExtensions[rom.Extension.ToLower()];
                            }
                            else if (ChoosePlatform != null)
                            {
                                rom.GameInfo.System = ChoosePlatform(rom);
                            }
                        }

                        game = rom.GameInfo;

                        var isXml = false;

                        // other xml has already been handled
                        if (file.Extension.ToLower() == ".xml")
                        {
                            game.System = "SNES";
                            isXml       = true;
                        }

                        switch (game.System)
                        {
                        case "SNES":
                            if (Global.Config.SNES_InSnes9x && VersionInfo.DeveloperBuild)
                            {
                                var snes = new Emulation.Cores.Nintendo.SNES9X.Snes9x(nextComm, rom.FileData);
                                nextEmulator = snes;
                            }
                            else
                            {
                                // need to get rid of this hack at some point
                                ((CoreFileProvider)nextComm.CoreFileProvider).SubfileDirectory = Path.GetDirectoryName(path.Replace("|", String.Empty));                                         // Dirty hack to get around archive filenames (since we are just getting the directory path, it is safe to mangle the filename
                                var romData = isXml ? null : rom.FileData;
                                var xmlData = isXml ? rom.FileData : null;
                                var snes    = new LibsnesCore(game, romData, Deterministic, xmlData, nextComm, GetCoreSettings <LibsnesCore>(), GetCoreSyncSettings <LibsnesCore>());
                                nextEmulator = snes;
                            }

                            RACore.OnLoad(RAConsoleID.SNES, rom.GameInfo.Name, rom.GameInfo.Hash);

                            break;

                        case "SMS":
                        case "SG":
                        case "GG":
                            nextEmulator = new SMS(nextComm, game, rom.RomData, GetCoreSettings <SMS>(), GetCoreSyncSettings <SMS>());
                            RACore.OnLoad(RAConsoleID.MasterSystem, rom.GameInfo.Name, rom.GameInfo.Hash);
                            break;

                        case "A26":
                            nextEmulator = new Atari2600(
                                nextComm,
                                game,
                                rom.FileData,
                                GetCoreSettings <Atari2600>(),
                                GetCoreSyncSettings <Atari2600>());
                            break;

                        case "PCE":
                        case "PCECD":
                        case "SGX":
                            nextEmulator = new PCEngine(nextComm, game, rom.RomData, GetCoreSettings <PCEngine>(), GetCoreSyncSettings <PCEngine>());
                            RACore.OnLoad(RAConsoleID.PCEngine, rom.GameInfo.Name, rom.GameInfo.Hash);
                            break;

                        case "GEN":
                            nextEmulator = new GPGX(nextComm, rom.RomData, null, "GEN", GetCoreSettings <GPGX>(), GetCoreSyncSettings <GPGX>());
                            RACore.OnLoad(RAConsoleID.MegaDrive, rom.GameInfo.Name, rom.GameInfo.Hash);
                            break;

                        case "TI83":
                            nextEmulator = new TI83(nextComm, game, rom.RomData, GetCoreSettings <TI83>());
                            break;

                        case "NES":
                            if (!Global.Config.NES_InQuickNES || forceAccurateCore)
                            {
                                nextEmulator = new NES(
                                    nextComm,
                                    game,
                                    rom.FileData,
                                    GetCoreSettings <NES>(),
                                    GetCoreSyncSettings <NES>());
                            }
                            else
                            {
                                nextEmulator = new QuickNES(nextComm, rom.FileData, GetCoreSettings <QuickNES>());
                            }

                            RACore.OnLoad(RAConsoleID.NES, rom.GameInfo.Name, rom.GameInfo.Hash);
                            break;

                        case "GB":
                        case "GBC":
                            if (!Global.Config.GB_AsSGB)
                            {
                                nextEmulator = new Gameboy(
                                    nextComm,
                                    game,
                                    rom.FileData,
                                    GetCoreSettings <Gameboy>(),
                                    GetCoreSyncSettings <Gameboy>(),
                                    Deterministic);
                            }
                            else
                            {
                                try
                                {
                                    game.System = "SNES";
                                    game.AddOption("SGB");
                                    var snes = new LibsnesCore(game, rom.FileData, Deterministic, null, nextComm, GetCoreSettings <LibsnesCore>(), GetCoreSyncSettings <LibsnesCore>());
                                    nextEmulator = snes;
                                }
                                catch
                                {
                                    // failed to load SGB bios or game does not support SGB mode.
                                    // To avoid catch-22, disable SGB mode
                                    Global.Config.GB_AsSGB = false;
                                    throw;
                                }
                            }

                            if (game.System == "GB")
                            {
                                RACore.OnLoad(RAConsoleID.Gameboy, rom.GameInfo.Name, rom.GameInfo.Hash);
                            }
                            else if (game.System == "GBC")
                            {
                                RACore.OnLoad(RAConsoleID.GameboyColor, rom.GameInfo.Name, rom.GameInfo.Hash);
                            }

                            break;

                        case "Coleco":
                            nextEmulator = new ColecoVision(nextComm, game, rom.RomData, GetCoreSyncSettings <ColecoVision>());
                            break;

                        case "INTV":
                            nextEmulator = new Intellivision(nextComm, game, rom.RomData);
                            break;

                        case "A78":
                            var gamedbpath = Path.Combine(PathManager.GetExeDirectoryAbsolute(), "gamedb", "EMU7800.csv");
                            nextEmulator = new Atari7800(nextComm, game, rom.RomData, gamedbpath);
                            break;

                        case "C64":
                            var c64 = new C64(nextComm, game, rom.RomData, rom.Extension);
                            nextEmulator = c64;
                            break;

                        case "GBA":
                            if (false)
                            {
                                //var gba = new GBA(nextComm);
                                //gba.Load(rom.RomData);
                                //nextEmulator = gba;
                            }
                            else
                            {
                                var gba = new VBANext(rom.RomData, nextComm);
                                nextEmulator = gba;

                                RACore.OnLoad(RAConsoleID.GameboyAdvance, rom.GameInfo.Name, rom.GameInfo.Hash);
                            }
                            break;

                        case "N64":
                            nextEmulator = new N64(nextComm, game, rom.RomData, GetCoreSettings <N64>(), GetCoreSyncSettings <N64>());
                            RACore.OnLoad(RAConsoleID.Nintendo64, rom.GameInfo.Name, rom.GameInfo.Hash);
                            break;

                        case "WSWAN":
                            nextEmulator = new WonderSwan(nextComm, rom.RomData, Deterministic,
                                                          GetCoreSettings <WonderSwan>(), GetCoreSyncSettings <WonderSwan>());
                            break;

                        case "DEBUG":
                            if (VersionInfo.DeveloperBuild)
                            {
                                nextEmulator = LibRetroEmulator.CreateDebug(nextComm, rom.RomData);
                            }

                            break;
                        }
                    }

                    if (nextEmulator == null)
                    {
                        DoLoadErrorCallback("No core could load the rom.", null);
                        return(false);
                    }
                }
                catch (Exception ex)
                {
                    string system = null;
                    if (game != null)
                    {
                        system = game.System;
                    }

                    // Specific hack here, as we get more cores of the same system, this isn't scalable
                    if (ex is UnsupportedMapperException)
                    {
                        return(LoadRom(path, nextComm, forceAccurateCore: true));
                    }
                    else if (ex is MissingFirmwareException)
                    {
                        DoLoadErrorCallback(ex.Message, system, LoadErrorType.MissingFirmware);
                    }
                    else if (ex is CGBNotSupportedException)
                    {
                        // Note: GB as SGB was set to false by this point, otherwise we would want to do it here
                        DoMessageCallback("Failed to load a GB rom in SGB mode.  Disabling SGB Mode.");
                        return(LoadRom(path, nextComm));
                    }
                    else
                    {
                        DoLoadErrorCallback("A core accepted the rom, but threw an exception while loading it:\n\n" + ex, system);
                    }

                    return(false);
                }

                Rom            = rom;
                LoadedEmulator = nextEmulator;
                Game           = game;
                return(true);
            }
        }