Ejemplo n.º 1
0
        //private static void CorruptTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        //{
        //    lock (CorruptLock)
        //    {
        //        if (!VanguardCore.vanguardConnected || AllSpec.CorruptCoreSpec == null || (p?.HasExited ?? true))
        //        {
        //            AutoCorruptTimer.Start();
        //            return;
        //        }

        //        try
        //        {
        //            if (!DontChangeMemoryProtection)
        //            {
        //                foreach (var m in MemoryDomains.MemoryInterfaces?.Values ?? Enumerable.Empty<MemoryDomainProxy>())
        //                {
        //                    if (m.MD is ProcessMemoryDomain pmd)
        //                    {
        //                        pmd.SetMemoryProtection(ProcessExtensions.MemoryProtection.ExecuteReadWrite);
        //                        if (p?.HasExited ?? false)
        //                        {
        //                            Console.WriteLine($"Bad! {pmd.Name}");
        //                        }
        //                    }
        //                }
        //            }

        //            try
        //            {
        //                RtcClock.StepCorrupt(true, true);

        //                if (p?.HasExited ?? false)
        //                {
        //                    Console.WriteLine($"Bad2!");
        //                }
        //            }
        //            catch (Exception ex)
        //            {
        //                Console.WriteLine($"STEP_CORRUPT Error!\n{ex.Message}\n{ex.StackTrace}");
        //            }
        //        }
        //        finally
        //        {
        //            if (!DontChangeMemoryProtection)
        //            {
        //                foreach (var m in MemoryDomains.MemoryInterfaces?.Values ?? Enumerable.Empty<MemoryDomainProxy>())
        //                {
        //                    if (m.MD is ProcessMemoryDomain pmd)
        //                    {
        //                        pmd.ResetMemoryProtection();
        //                        pmd.FlushInstructionCache();
        //                    }

        //                    if (p?.HasExited ?? false)
        //                    {
        //                        Console.WriteLine($"Bad3!");
        //                    }
        //                }
        //            }
        //        }
        //    }

        //    if (p.HasExited)
        //    {
        //        Console.WriteLine($"Bad4!");
        //    }
        //    AutoCorruptTimer.Start();
        //}

        //private static void AutoHookTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        //{
        //    try
        //    {
        //        if (p?.HasExited == false)
        //            return;
        //        SyncObjectSingleton.FormExecute(() => S.GET<StubForm>().lbTargetStatus.Text = "Waiting...");
        //        var procToFind = S.GET<StubForm>().tbClientAddr.Text;
        //        if (string.IsNullOrWhiteSpace(procToFind))
        //            return;

        //        SyncObjectSingleton.FormExecute(() => S.GET<StubForm>().lbTargetStatus.Text = "Hooking...");
        //        var _p = Process.GetProcesses().First(x => x.ProcessName == procToFind);
        //        if (_p != null)
        //        {
        //            Thread.Sleep(2000); //Give the process 2 seconds
        //            SyncObjectSingleton.FormExecute(() =>
        //            {
        //                LoadTarget(_p);

        //                if (!VanguardCore.vanguardConnected)
        //                    VanguardCore.Start();

        //                S.GET<StubForm>().EnableTargetInterface();
        //            });
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Console.WriteLine($"AutoHook failed.\n{ex.Message}\n{ex.StackTrace}");
        //    }
        //    AutoHookTimer.Start();
        //}

        //internal static bool LoadTarget(Process _p = null)
        //{
        //    lock (CorruptLock)
        //    {
        //        if (_p == null)
        //        {
        //            using (var f = new HookProcessForm())
        //            {
        //                if (f.ShowDialog() != DialogResult.OK)
        //                    return false;

        //                if (f.RequestedProcess == null || (f.RequestedProcess?.HasExited ?? true))
        //                {
        //                    return false;
        //                }

        //                if (IsProcessBlacklisted(f.RequestedProcess))
        //                {
        //                    MessageBox.Show("Blacklisted process");
        //                    return false;
        //                }

        //                p = f.RequestedProcess;
        //            }
        //        }
        //        else
        //            p = _p;
        //        /*
        //        if (UseExceptionHandler)
        //        {
        //            ProcessExtensions.IsWow64Process(p.Handle, out bool is32BitProcess); //This method is stupid and returns the inverse
        //            string path = is32BitProcess
        //                ? Path.Combine(currentDir, "ExceptionHandler_x86.dll")
        //                : Path.Combine(currentDir, "ExceptionHandler_x64.dll");
        //            if (File.Exists(path))
        //            {
        //                try
        //                {
        //                    using (var i = new Injector(InjectionMethod.CreateThread, p.Id, path))
        //                    {
        //                        if ((ulong) i.InjectDll() != 0)
        //                        {
        //                            Console.WriteLine("Injected exception helper successfully");
        //                        }
        //                    }
        //                }
        //                catch (Exception e)
        //                {
        //                    Console.WriteLine($"Injection failed! {e}");
        //                }
        //            }
        //        }*/

        //        Action<object, EventArgs> action = (ob, ea) =>
        //        {
        //            if (VanguardCore.vanguardConnected)
        //                UpdateDomains();
        //        };

        //        Action<object, EventArgs> postAction = (ob, ea) =>
        //        {
        //            if (p == null)
        //            {
        //                MessageBox.Show("Failed to load target");
        //                S.GET<StubForm>().DisableTargetInterface();
        //                return;
        //            }

        //            S.GET<StubForm>().lbTarget.Text = p.ProcessName;
        //            S.GET<StubForm>().lbTargetStatus.Text = "Hooked!";

        //            //Refresh the UI
        //            //RefreshUIPostLoad();
        //        };
        //        S.GET<StubForm>().RunProgressBar($"Loading target...", 0, action, postAction);
        //    }

        //    return true;
        //}

        //internal static bool CloseTarget(bool updateDomains = true)
        //{
        //    p = null;
        //    if (updateDomains)
        //        UpdateDomains();
        //    return true;
        //}

        public static void UpdateDomains()
        {
            if (!VanguardCore.vanguardConnected)
            {
                return;
            }
            try
            {
                PartialSpec gameDone = new PartialSpec("VanguardSpec");
                gameDone[VSPEC.SYSTEM]          = "Linux";
                gameDone[VSPEC.GAMENAME]        = "IGNORE";
                gameDone[VSPEC.SYSTEMPREFIX]    = "Linux";
                gameDone[VSPEC.SYSTEMCORE]      = "Linux";
                gameDone[VSPEC.OPENROMFILENAME] = "IGNORE";
                gameDone[VSPEC.MEMORYDOMAINS_BLACKLISTEDDOMAINS] = Array.Empty <string>();
                gameDone[VSPEC.MEMORYDOMAINS_INTERFACES]         = GetInterfaces();
                gameDone[VSPEC.CORE_DISKBASED] = false;
                AllSpec.VanguardSpec.Update(gameDone);

                //This is local. If the domains changed it propgates over netcore
                LocalNetCoreRouter.Route(RTCV.NetCore.Endpoints.CorruptCore, RTCV.NetCore.Commands.Remote.EventDomainsUpdated, true, true);

                //Asks RTC to restrict any features unsupported by the stub
                LocalNetCoreRouter.Route(RTCV.NetCore.Endpoints.CorruptCore, RTCV.NetCore.Commands.Remote.EventRestrictFeatures, true, true);
            }
            catch (Exception ex)
            {
                if (VanguardCore.ShowErrorDialog(ex) == DialogResult.Abort)
                {
                    throw new RTCV.NetCore.AbortEverythingException();
                }
            }
        }
        public static void UpdateDomains()
        {
            try
            {
                PartialSpec gameDone = new PartialSpec("VanguardSpec");
                gameDone[VSPEC.SYSTEM]       = "FileSystem";
                gameDone[VSPEC.GAMENAME]     = FileWatch.currentFileInfo.targetShortName;
                gameDone[VSPEC.SYSTEMPREFIX] = "FileStub";
                gameDone[VSPEC.SYSTEMCORE]   = "FileStub";
                //gameDone[VSPEC.SYNCSETTINGS] = BIZHAWK_GETSET_SYNCSETTINGS;
                gameDone[VSPEC.OPENROMFILENAME] = currentFileInfo.targetFullName;
                gameDone[VSPEC.MEMORYDOMAINS_BLACKLISTEDDOMAINS] = new string[0];
                gameDone[VSPEC.MEMORYDOMAINS_INTERFACES]         = GetInterfaces();
                gameDone[VSPEC.CORE_DISKBASED] = false;
                AllSpec.VanguardSpec.Update(gameDone);

                //This is local. If the domains changed it propgates over netcore
                LocalNetCoreRouter.Route(NetcoreCommands.CORRUPTCORE, NetcoreCommands.REMOTE_EVENT_DOMAINSUPDATED, true, true);

                //Asks RTC to restrict any features unsupported by the stub
                LocalNetCoreRouter.Route(NetcoreCommands.CORRUPTCORE, NetcoreCommands.REMOTE_EVENT_RESTRICTFEATURES, true, true);
            }
            catch (Exception ex)
            {
                if (VanguardCore.ShowErrorDialog(ex) == DialogResult.Abort)
                {
                    throw new RTCV.NetCore.AbortEverythingException();
                }
            }
        }
Ejemplo n.º 3
0
        public void Update(PartialSpec _partialSpec, bool propagate = true, bool synced = true)
        {
            if (name != _partialSpec.Name)
            {
                throw new Exception("Name mismatch between PartialSpec and FullSpec");
            }

            //For initial
            foreach (var key in _partialSpec.specDico.Keys)
            {
                base[key] = _partialSpec.specDico[key];
            }

            //Increment the version
            base.version++;

            if (propagationIsEnabled && propagate)
            {
                OnSpecUpdated(new SpecUpdateEventArgs()
                {
                    partialSpec  = _partialSpec,
                    syncedUpdate = synced
                });
            }
        }
Ejemplo n.º 4
0
        public static PartialSpec getDefaultPartial()
        {
            var partial = new PartialSpec("RTCSpec");

            partial[RTCSPEC.RENDER_AT_LOAD] = false;
            return(partial);
        }
Ejemplo n.º 5
0
        public static void UpdateDomains()
        {
            try
            {
                PartialSpec gameDone = new PartialSpec("VanguardSpec");
                gameDone[VSPEC.SYSTEM]       = "FileSystem";
                gameDone[VSPEC.GAMENAME]     = FileWatch.currentSession.targetShortName;
                gameDone[VSPEC.SYSTEMPREFIX] = "FileStub";
                gameDone[VSPEC.SYSTEMCORE]   = "FileStub";
                //gameDone[VSPEC.SYNCSETTINGS] = BIZHAWK_GETSET_SYNCSETTINGS;
                gameDone[VSPEC.OPENROMFILENAME] = currentSession.targetFullName;
                gameDone[VSPEC.MEMORYDOMAINS_BLACKLISTEDDOMAINS] = Array.Empty <string>();
                gameDone[VSPEC.MEMORYDOMAINS_INTERFACES]         = GetInterfaces();
                gameDone[VSPEC.CORE_DISKBASED] = false;
                AllSpec.VanguardSpec.Update(gameDone);

                //This is local. If the domains changed it propgates over netcore
                LocalNetCoreRouter.Route(RTCV.NetCore.Endpoints.CorruptCore, RTCV.NetCore.Commands.Remote.EventDomainsUpdated, true, true);

                //Asks RTC to restrict any features unsupported by the stub
                LocalNetCoreRouter.Route(RTCV.NetCore.Endpoints.CorruptCore, RTCV.NetCore.Commands.Remote.EventRestrictFeatures, true, true);
            }
            catch (Exception ex)
            {
                if (VanguardCore.ShowErrorDialog(ex) == DialogResult.Abort)
                {
                    throw new RTCV.NetCore.AbortEverythingException();
                }
            }
        }
Ejemplo n.º 6
0
        public static void Start(Form standaloneForm = null)
        {
            S.formRegister.FormRegistered += FormRegister_FormRegistered;
            //registerFormEvents(S.GET<RTC_Core_Form>());
            registerFormEvents(S.GET <UI_CoreForm>());
            registerHotkeyBlacklistControls(S.GET <UI_CoreForm>());

            if (!RtcCore.Attached)
            {
                S.SET((RTC_Standalone_Form)standaloneForm);
            }

            Form   dummy  = new Form();
            IntPtr Handle = dummy.Handle;

            SyncObjectSingleton.SyncObject = dummy;

            UI_VanguardImplementation.StartServer();

            PartialSpec p = new PartialSpec("UISpec");

            p["SELECTEDDOMAINS"] = new string[] { };

            RTCV.NetCore.AllSpec.UISpec              = new FullSpec(p, !CorruptCore.RtcCore.Attached);
            RTCV.NetCore.AllSpec.UISpec.SpecUpdated += (o, e) =>
            {
                PartialSpec partial = e.partialSpec;

                LocalNetCoreRouter.Route(CORRUPTCORE, REMOTE_PUSHUISPECUPDATE, partial, e.syncedUpdate);
            };

            CorruptCore.RtcCore.StartUISide();

            //Loading RTC Params

            S.GET <RTC_SettingsGeneral_Form>().cbDisableEmulatorOSD.Checked       = RTCV.NetCore.Params.IsParamSet(RTCSPEC.CORE_EMULATOROSDDISABLED);
            S.GET <RTC_SettingsGeneral_Form>().cbAllowCrossCoreCorruption.Checked = RTCV.NetCore.Params.IsParamSet("ALLOW_CROSS_CORE_CORRUPTION");
            S.GET <RTC_SettingsGeneral_Form>().cbDontCleanAtQuit.Checked          = RTCV.NetCore.Params.IsParamSet("DONT_CLEAN_SAVESTATES_AT_QUIT");
            S.GET <RTC_SettingsGeneral_Form>().cbUncapIntensity.Checked           = RTCV.NetCore.Params.IsParamSet("UNCAP_INTENSITY");

            //Initialize input code. Poll every 16ms
            Input.Input.Initialize();
            inputCheckTimer           = new System.Timers.Timer();
            inputCheckTimer.Elapsed  += ProcessInputCheck;
            inputCheckTimer.AutoReset = false;
            inputCheckTimer.Interval  = 10;
            inputCheckTimer.Start();

            if (FirstConnect)
            {
                UI_DefaultGrids.connectionStatus.LoadToMain();
            }

            LoadRTCColor();
            S.GET <UI_CoreForm>().Show();
            Initialized.Set();
            LoadRTCColor();
        }
Ejemplo n.º 7
0
        public void partial_object_maps_to_partial_class()
        {
            var obj     = JObject.Parse(@"{ 'Name': 'changed' }").ToObject <PartialSpec>();
            var compare = new PartialSpec()
            {
                Name = "changed"
            };

            Assert.IsTrue(obj.Name == compare.Name);
        }
Ejemplo n.º 8
0
        public static PartialSpec getDefaultPartial()
        {
            var partial = new PartialSpec("CorruptCore");

            partial[RTCSPEC.STEP_MAXINFINITEBLASTUNITS.ToString()]    = 50;
            partial[RTCSPEC.STEP_LOCKEXECUTION.ToString()]            = false;
            partial[RTCSPEC.STEP_CLEARSTEPACTIONSONREWIND.ToString()] = false;

            return(partial);
        }
Ejemplo n.º 9
0
        public PartialSpec GetPartialSpec()
        {
            PartialSpec p = new PartialSpec(name);

            foreach (var key in specDico.Keys)
            {
                p[key] = base[key];
            }

            p.version = base.version;
            return(p);
        }
        public static void LOAD_GAME_DONE()
        {
            try
            {
                if (disableRTC)
                {
                    return;
                }


                //Glitch Harvester warning for archives



                //prepare memory domains in advance on bizhawk side
                bool domainsChanged = RefreshDomains(false);

                PartialSpec gameDone = new PartialSpec("VanguardSpec");
                gameDone[VSPEC.SYSTEM]          = EMU_GET_CURRENTLYLOADEDSYSTEMNAME().ToUpper();
                gameDone[VSPEC.GAMENAME]        = EMU_GET_FILESYSTEMGAMENAME();
                gameDone[VSPEC.SYSTEMPREFIX]    = EMU_GET_SAVESTATEPREFIX();
                gameDone[VSPEC.SYSTEMCORE]      = EMU_GET_SYSTEMCORENAME("");
                gameDone[VSPEC.SYNCSETTINGS]    = EMU_GETSET_SYNCSETTINGS;
                gameDone[VSPEC.OPENROMFILENAME] = Program.RomFilename;
                gameDone[VSPEC.MEMORYDOMAINS_BLACKLISTEDDOMAINS] = VanguardCore.GetBlacklistedDomains(EMU_GET_CURRENTLYLOADEDSYSTEMNAME().ToUpper());
                gameDone[VSPEC.MEMORYDOMAINS_INTERFACES]         = GetInterfaces();
                VanguardCore.VanguardSpec.Update(gameDone);

                //This is local. If the domains changed it propgates over netcore
                LocalNetCoreRouter.Route(CORRUPTCORE, REMOTE_EVENT_DOMAINSUPDATED, domainsChanged, true);


                if (VanguardCore.GameName != lastGameName)
                {
                }
                else
                {
                }

                lastGameName = VanguardCore.GameName;
            }
            catch (Exception ex)
            {
                if (VanguardCore.ShowErrorDialog(ex) == DialogResult.Abort)
                {
                    throw new RTCV.NetCore.AbortEverythingException();
                }
            }
        }
Ejemplo n.º 11
0
        public FullSpec(PartialSpec partialSpec, bool _propagationEnabled)
        {
            propagationIsEnabled = _propagationEnabled;

            //Creating a FullSpec requires a template
            template     = partialSpec;
            base.version = 1;
            name         = partialSpec.Name;
            Update(template);

            //Set the version after the update
            if (partialSpec.version != 1)
            {
                base.version = partialSpec.version;
            }
        }
Ejemplo n.º 12
0
        private void btnCustomTemplateLoad_Click(object sender, EventArgs e)
        {
            PartialSpec spec = RTC_CustomEngine.LoadTemplateFile();

            if (spec == null)
            {
                return;
            }
            RTC_CustomEngine.Name2TemplateDico[spec[RTCSPEC.CUSTOM_NAME.ToString()].ToString()] = spec;
            RTCV.NetCore.AllSpec.CorruptCoreSpec.Update(spec);
            RestoreUIStateFromSpec();
            Refresh();
            if (!cbSelectedTemplate.Items.Contains(spec[RTCSPEC.CUSTOM_NAME.ToString()].ToString()))
            {
                cbSelectedTemplate.Items.Add(spec[RTCSPEC.CUSTOM_NAME.ToString()].ToString());
            }
            cbSelectedTemplate.SelectedItem = spec[RTCSPEC.CUSTOM_NAME.ToString()].ToString();
        }
Ejemplo n.º 13
0
        private void cbSelectedTemplate_SelectedIndexChanged(object sender, EventArgs e)
        {
            PartialSpec spec = new PartialSpec("RTCSpec");

            bool readOnlyTemplate = false;

            switch (cbSelectedTemplate.SelectedItem.ToString())
            {
            case "Nightmare Engine":
            case "Hellgenie Engine":
            case "Distortion Engine":
            case "Freeze Engine":
            case "Pipe Engine":
            case "Vector Engine":
                readOnlyTemplate = true;
                break;
            }

            if (readOnlyTemplate)
            {
                btnCustomTemplateSave.Enabled   = false;
                btnCustomTemplateSave.BackColor = Color.LightGray;
                btnCustomTemplateSave.ForeColor = Color.DimGray;
            }
            else
            {
                btnCustomTemplateSave.Enabled   = true;
                btnCustomTemplateSave.BackColor = Color.Tomato;
                btnCustomTemplateSave.ForeColor = Color.Black;
            }

            if (RTC_CustomEngine.LoadTemplate(cbSelectedTemplate.SelectedItem.ToString()))
            {
                RTCV.NetCore.AllSpec.CorruptCoreSpec.Update(spec);
                RestoreUIStateFromSpec();
                updateUILock();
                Refresh();
            }
        }
Ejemplo n.º 14
0
        public void Update(string key, object value, bool propagate = true, bool synced = true)
        {
            /*
             * //Make a partial spec and pass it into Update(PartialSpec)
             * if (RTC_NetcoreImplementation.isStandaloneEmu && name == "RTCSpec" && key != RTCSPEC.CORE_AUTOCORRUPT.ToString())
             *  throw new Exception("Tried updating the RTCSpec from Emuhawk");
             *
             * if (RTC_NetcoreImplementation.isStandaloneUI && name == "EmuSpec")
             *  throw new Exception("Tried updating the EmuSpec from StandaloneRTC");
             */
            /*
             * if(value is bool)
             * {
             *  bool boolValue = (bool)value;
             *  if (boolValue == false)
             *      value = null;
             * }*/

            PartialSpec spec = new PartialSpec(name);

            spec[key] = value;
            Update(spec, propagate, synced);
        }
Ejemplo n.º 15
0
        public object OnMessageReceived(object sender, NetCoreEventArgs e)
        {
            try
            { //Use setReturnValue to handle returns
                var message         = e.message;
                var advancedMessage = message as NetCoreAdvancedMessage;

                switch (e.message.Type)
                {
                case "GETSPECDUMPS":
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine("Spec Dump from CorruptCore");
                    sb.AppendLine();
                    sb.AppendLine("UISpec");
                    RTCV.NetCore.AllSpec.UISpec?.GetDump().ForEach(x => sb.AppendLine(x));
                    sb.AppendLine("CorruptCoreSpec");
                    RTCV.NetCore.AllSpec.CorruptCoreSpec?.GetDump().ForEach(x => sb.AppendLine(x));
                    sb.AppendLine("VanguardSpec");
                    RTCV.NetCore.AllSpec.VanguardSpec?.GetDump().ForEach(x => sb.AppendLine(x));
                    e.setReturnValue(sb.ToString());
                    break;

                //UI sent its spec
                case REMOTE_PUSHUISPEC:
                {
                    SyncObjectSingleton.FormExecute(() =>
                        {
                            RTCV.NetCore.AllSpec.UISpec = new FullSpec((PartialSpec)advancedMessage.objectValue, !RtcCore.Attached);
                        });
                    break;
                }

                //UI sent a spec update
                case REMOTE_PUSHUISPECUPDATE:
                    SyncObjectSingleton.FormExecute(() =>
                    {
                        RTCV.NetCore.AllSpec.UISpec?.Update((PartialSpec)advancedMessage.objectValue);
                    });
                    break;

                //Vanguard sent a copy of its spec
                case REMOTE_PUSHVANGUARDSPEC:

                    SyncObjectSingleton.FormExecute(() =>
                    {
                        if (!RtcCore.Attached)
                        {
                            RTCV.NetCore.AllSpec.VanguardSpec = new FullSpec((PartialSpec)advancedMessage.objectValue, !RtcCore.Attached);
                        }
                    });
                    break;

                //Vanguard sent a spec update
                case REMOTE_PUSHVANGUARDSPECUPDATE:
                    RTCV.NetCore.AllSpec.VanguardSpec?.Update((PartialSpec)advancedMessage.objectValue, false);
                    break;

                //UI sent a copy of the CorruptCore spec
                case REMOTE_PUSHCORRUPTCORESPEC:
                    SyncObjectSingleton.FormExecute(() =>
                    {
                        //So here's the deal. The UI doesn't actually have the full memory domains (md isn't sent across) so if we take them from it, it results in them going null
                        //Instead, we stick with what we have, then tell the UI to use that.

                        var temp = new FullSpec((PartialSpec)advancedMessage.objectValue, !RtcCore.Attached);

                        //Stick with what we have if it exists to prevent any exceptions if autocorrupt was on or something, then call refresh
                        temp.Update("MEMORYINTERFACES", AllSpec.CorruptCoreSpec?["MEMORYINTERFACES"] ?? new Dictionary <string, MemoryDomainProxy>());

                        RTCV.NetCore.AllSpec.CorruptCoreSpec              = new FullSpec(temp.GetPartialSpec(), !RtcCore.Attached);
                        RTCV.NetCore.AllSpec.CorruptCoreSpec.SpecUpdated += (ob, eas) =>
                        {
                            PartialSpec partial = eas.partialSpec;
                            LocalNetCoreRouter.Route(NetcoreCommands.UI, NetcoreCommands.REMOTE_PUSHCORRUPTCORESPECUPDATE, partial, true);
                        };
                        RTCV.CorruptCore.MemoryDomains.RefreshDomains();
                    });
                    e.setReturnValue(true);
                    break;

                //UI sent an update of the CorruptCore spec
                case REMOTE_PUSHCORRUPTCORESPECUPDATE:
                    SyncObjectSingleton.FormExecute(() =>
                    {
                        RTCV.NetCore.AllSpec.CorruptCoreSpec?.Update((PartialSpec)advancedMessage.objectValue, false);
                    });
                    break;

                case REMOTE_EVENT_DOMAINSUPDATED:
                    var domainsChanged = (bool)advancedMessage.objectValue;
                    MemoryDomains.RefreshDomains(domainsChanged);
                    break;

                case REMOTE_EVENT_RESTRICTFEATURES:
                {
                    if (!RTCV.NetCore.AllSpec.VanguardSpec?.Get <bool>(VSPEC.SUPPORTS_SAVESTATES) ?? true)
                    {
                        LocalNetCoreRouter.Route(NetcoreCommands.UI, NetcoreCommands.REMOTE_DISABLESAVESTATESUPPORT);
                    }

                    if (!RTCV.NetCore.AllSpec.VanguardSpec?.Get <bool>(VSPEC.SUPPORTS_REALTIME) ?? true)
                    {
                        LocalNetCoreRouter.Route(NetcoreCommands.UI, NetcoreCommands.REMOTE_DISABLEREALTIMESUPPORT);
                    }

                    if (!RTCV.NetCore.AllSpec.VanguardSpec?.Get <bool>(VSPEC.SUPPORTS_KILLSWITCH) ?? true)
                    {
                        LocalNetCoreRouter.Route(NetcoreCommands.UI, NetcoreCommands.REMOTE_DISABLEKILLSWITCHSUPPORT);
                    }

                    if (!RTCV.NetCore.AllSpec.VanguardSpec?.Get <bool>(VSPEC.SUPPORTS_GAMEPROTECTION) ?? true)
                    {
                        LocalNetCoreRouter.Route(NetcoreCommands.UI, NetcoreCommands.REMOTE_DISABLEGAMEPROTECTIONSUPPORT);
                    }

                    break;
                }

                case REMOTE_EVENT_SHUTDOWN:
                {
                    RtcCore.Shutdown();
                    break;
                }

                case REMOTE_OPENHEXEDITOR:
                {
                    if ((bool?)AllSpec.VanguardSpec[VSPEC.USE_INTEGRATED_HEXEDITOR] ?? false)
                    {
                        LocalNetCoreRouter.Route(NetcoreCommands.VANGUARD, NetcoreCommands.REMOTE_OPENHEXEDITOR, true);
                    }
                    else
                    {
                        //Route it to the plugin if loaded
                        if (RtcCore.PluginHost.LoadedPlugins.Any(x => x.Name == "Hex Editor"))
                        {
                            LocalNetCoreRouter.Route("HEXEDITOR", NetcoreCommands.REMOTE_OPENHEXEDITOR, true);
                        }
                        else
                        {
                            MessageBox.Show("The current Vanguard implementation does not include a\n hex editor & the hex editor plugin isn't loaded. Aborting.");
                        }
                    }
                }
                break;

                case EMU_OPEN_HEXEDITOR_ADDRESS:
                {
                    if ((bool?)AllSpec.VanguardSpec[VSPEC.USE_INTEGRATED_HEXEDITOR] ?? false)
                    {
                        LocalNetCoreRouter.Route(NetcoreCommands.VANGUARD, NetcoreCommands.EMU_OPEN_HEXEDITOR_ADDRESS, advancedMessage.objectValue, true);
                    }
                    else
                    {
                        //Route it to the plugin if loaded
                        if (RtcCore.PluginHost.LoadedPlugins.Any(x => x.Name == "Hex Editor"))
                        {
                            LocalNetCoreRouter.Route("HEXEDITOR", NetcoreCommands.EMU_OPEN_HEXEDITOR_ADDRESS, advancedMessage.objectValue, true);
                        }
                        else
                        {
                            MessageBox.Show("The current Vanguard implementation does not include a\n hex editor & the hex editor plugin isn't loaded. Aborting.");
                        }
                    }
                    break;
                }

                case MANUALBLAST:
                {
                    RtcCore.GenerateAndBlast();
                }
                break;

                case GENERATEBLASTLAYER:
                {
                    var      val = advancedMessage.objectValue as object[];
                    StashKey sk  = val[0] as StashKey;
                    bool     loadBeforeCorrupt = (bool)val[1];
                    bool     applyBlastLayer   = (bool)val[2];
                    bool     backup            = (bool)val[3];

                    BlastLayer bl = null;

                    bool UseSavestates = (bool)AllSpec.VanguardSpec[VSPEC.SUPPORTS_SAVESTATES];

                    void a()
                    {
                        lock (loadLock)
                        {
                            //Load the game from the main thread
                            if (UseSavestates && loadBeforeCorrupt)
                            {
                                SyncObjectSingleton.FormExecute(() =>
                                    {
                                        StockpileManager_EmuSide.LoadRom_NET(sk);
                                    });
                            }

                            if (UseSavestates && loadBeforeCorrupt)
                            {
                                StockpileManager_EmuSide.LoadState_NET(sk, false);
                            }

                            //We pull the domains here because if the syncsettings changed, there's a chance the domains changed
                            string[] domains = (string[])AllSpec.UISpec["SELECTEDDOMAINS"];

                            var cpus = Environment.ProcessorCount;

                            if (cpus == 1 || AllSpec.VanguardSpec[VSPEC.SUPPORTS_MULTITHREAD] == null)
                            {
                                bl = RtcCore.GenerateBlastLayer(domains);
                            }
                            else
                            {
                                //if emulator supports multithreaded access of the domains, disregard the emulation thread and just span threads...

                                long reminder = RtcCore.Intensity % (cpus - 1);

                                long splitintensity = (RtcCore.Intensity - reminder) / (cpus - 1);

                                Task <BlastLayer>[] tasks = new Task <BlastLayer> [cpus];
                                for (int i = 0; i < cpus; i++)
                                {
                                    long requestedIntensity = splitintensity;

                                    if (i == 0 && reminder != 0)
                                    {
                                        requestedIntensity = reminder;
                                    }

                                    tasks[i] = Task.Factory.StartNew(() =>
                                                                     RtcCore.GenerateBlastLayer(domains, requestedIntensity));
                                }

                                Task.WaitAll(tasks);

                                bl = tasks[0]
                                     .Result ?? new BlastLayer();

                                if (tasks.Length > 1)
                                {
                                    for (int i = 1; i < tasks.Length; i++)
                                    {
                                        if (tasks[i]
                                            .Result != null)
                                        {
                                            bl.Layer.AddRange(tasks[i]
                                                              .Result.Layer);
                                        }
                                    }
                                }

                                if (bl.Layer.Count == 0)
                                {
                                    bl = null;
                                }
                            }

                            if (applyBlastLayer)
                            {
                                bl?.Apply(backup);
                            }
                        }
                    }
                    //If the emulator uses callbacks, we do everything on the main thread and once we're done, we unpause emulation
                    if ((bool?)AllSpec.VanguardSpec[VSPEC.LOADSTATE_USES_CALLBACKS] ?? false)
                    {
                        SyncObjectSingleton.FormExecute(a);
                        e.setReturnValue(LocalNetCoreRouter.Route(NetcoreCommands.VANGUARD, NetcoreCommands.REMOTE_RESUMEEMULATION, true));
                    }
                    else         //We can just do everything on the emulation thread as it'll block
                    {
                        SyncObjectSingleton.EmuThreadExecute(a, true);
                    }

                    if (advancedMessage.requestGuid != null)
                    {
                        e.setReturnValue(bl);
                    }
                    break;
                }

                case APPLYBLASTLAYER:
                {
                    var        temp   = advancedMessage.objectValue as object[];
                    BlastLayer bl     = (BlastLayer)temp[0];
                    bool       backup = (bool)temp[1];

                    void a()
                    {
                        bl.Apply(backup, true);
                    }

                    SyncObjectSingleton.EmuThreadExecute(a, true);
                    break;
                }

                /*
                 * case STASHKEY:
                 *  {
                 *      var temp = advancedMessage.objectValue as object[];
                 *
                 *      var sk = temp[0] as StashKey;
                 *      var romFilename = temp[1] as String;
                 *      var romData = temp[2] as Byte[];
                 *
                 *      if (!File.Exists(CorruptCore.rtcDir + Path.DirectorySeparatorChar + "WORKING" + Path.DirectorySeparatorChar + "SKS" + Path.DirectorySeparatorChar + romFilename))
                 *          File.WriteAllBytes(CorruptCore.rtcDir + Path.DirectorySeparatorChar + "WORKING" + Path.DirectorySeparatorChar + "SKS" + Path.DirectorySeparatorChar + romFilename, romData);
                 *
                 *      sk.RomFilename = CorruptCore.rtcDir + Path.DirectorySeparatorChar + "WORKING" + Path.DirectorySeparatorChar + "SKS" + Path.DirectorySeparatorChar + CorruptCore_Extensions.getShortFilenameFromPath(romFilename);
                 *      sk.DeployState();
                 *      sk.Run();
                 *  }
                 *  break;
                 */

                case REMOTE_PUSHRTCSPEC:
                    RTCV.NetCore.AllSpec.CorruptCoreSpec = new FullSpec((PartialSpec)advancedMessage.objectValue, !RtcCore.Attached);
                    e.setReturnValue(true);
                    break;

                case REMOTE_PUSHRTCSPECUPDATE:
                    RTCV.NetCore.AllSpec.CorruptCoreSpec?.Update((PartialSpec)advancedMessage.objectValue, false);
                    break;

                case BLASTGENERATOR_BLAST:
                {
                    List <BlastGeneratorProto> returnList = null;
                    StashKey sk = (StashKey)(advancedMessage.objectValue as object[])[0];
                    List <BlastGeneratorProto> blastGeneratorProtos = (List <BlastGeneratorProto>)(advancedMessage.objectValue as object[])[1];
                    bool loadBeforeCorrupt = (bool)(advancedMessage.objectValue as object[])[2];
                    bool applyAfterCorrupt = (bool)(advancedMessage.objectValue as object[])[3];
                    bool resumeAfter       = (bool)(advancedMessage.objectValue as object[])[4];
                    void a()
                    {
                        //Load the game from the main thread
                        if (loadBeforeCorrupt)
                        {
                            SyncObjectSingleton.FormExecute(() =>
                                {
                                    StockpileManager_EmuSide.LoadRom_NET(sk);
                                });
                        }

                        if (loadBeforeCorrupt)
                        {
                            StockpileManager_EmuSide.LoadState_NET(sk, false);
                        }

                        returnList = BlastTools.GenerateBlastLayersFromBlastGeneratorProtos(blastGeneratorProtos, sk);
                        if (applyAfterCorrupt)
                        {
                            BlastLayer bl = new BlastLayer();
                            foreach (var p in returnList.Where(x => x != null))
                            {
                                bl.Layer.AddRange(p.bl.Layer);
                            }
                            bl.Apply(true);
                        }
                    }
                    //If the emulator uses callbacks, we do everything on the main thread and once we're done, we unpause emulation
                    if ((bool?)AllSpec.VanguardSpec[VSPEC.LOADSTATE_USES_CALLBACKS] ?? false)
                    {
                        SyncObjectSingleton.FormExecute(a);
                        if (resumeAfter)
                        {
                            e.setReturnValue(LocalNetCoreRouter.Route(NetcoreCommands.VANGUARD, NetcoreCommands.REMOTE_RESUMEEMULATION, true));
                        }
                    }
                    else
                    {
                        SyncObjectSingleton.EmuThreadExecute(a, false);
                    }

                    e.setReturnValue(returnList);

                    break;
                }

                case REMOTE_LOADSTATE:
                {
                    lock (loadLock)
                    {
                        StashKey sk            = (StashKey)(advancedMessage.objectValue as object[])[0];
                        bool     reloadRom     = (bool)(advancedMessage.objectValue as object[])[1];
                        bool     runBlastLayer = (bool)(advancedMessage.objectValue as object[])[2];

                        bool returnValue = false;

                        //Load the game from the main thread
                        if (reloadRom)
                        {
                            SyncObjectSingleton.FormExecute(() =>
                                {
                                    StockpileManager_EmuSide.LoadRom_NET(sk);
                                });
                        }
                        void a()
                        {
                            returnValue = StockpileManager_EmuSide.LoadState_NET(sk, runBlastLayer);
                        }
                        //If the emulator uses callbacks, we do everything on the main thread and once we're done, we unpause emulation
                        if ((bool?)AllSpec.VanguardSpec[VSPEC.LOADSTATE_USES_CALLBACKS] ?? false)
                        {
                            SyncObjectSingleton.FormExecute(a);
                            e.setReturnValue(LocalNetCoreRouter.Route(NetcoreCommands.VANGUARD, NetcoreCommands.REMOTE_RESUMEEMULATION, true));
                        }
                        else         //We're loading on the emulator thread which'll block
                        {
                            SyncObjectSingleton.EmuThreadExecute(a, false);
                        }
                        e.setReturnValue(returnValue);
                    }
                }
                break;

                case REMOTE_SAVESTATE:
                {
                    StashKey sk = null;
                    void a()
                    {
                        sk = StockpileManager_EmuSide.SaveState_NET(advancedMessage.objectValue as StashKey);         //Has to be nullable cast
                    }
                    SyncObjectSingleton.EmuThreadExecute(a, false);
                    e.setReturnValue(sk);
                }
                break;

                case REMOTE_SAVESTATELESS:
                {
                    StashKey sk = null;
                    void a()
                    {
                        sk = StockpileManager_EmuSide.SaveStateLess_NET(advancedMessage.objectValue as StashKey);         //Has to be nullable cast
                    }
                    SyncObjectSingleton.EmuThreadExecute(a, false);
                    e.setReturnValue(sk);
                }
                break;

                case REMOTE_BACKUPKEY_REQUEST:
                {
                    //We don't store this in the spec as it'd be horrible to push it to the UI and it doesn't care
                    //if (!LocalNetCoreRouter.QueryRoute<bool>(NetcoreCommands.VANGUARD, NetcoreCommands.REMOTE_ISNORMALADVANCE))
                    //break;

                    StashKey sk = null;
                    //We send an unsynced command back
                    SyncObjectSingleton.FormExecute(() =>
                        {
                            sk = StockpileManager_EmuSide.SaveState_NET();
                        });

                    if (sk != null)
                    {
                        LocalNetCoreRouter.Route(NetcoreCommands.UI, REMOTE_BACKUPKEY_STASH, sk, false);
                    }

                    break;
                }

                case REMOTE_DOMAIN_GETDOMAINS:
                    e.setReturnValue(LocalNetCoreRouter.Route(NetcoreCommands.VANGUARD, NetcoreCommands.REMOTE_DOMAIN_GETDOMAINS, true));
                    break;

                case REMOTE_PUSHVMDPROTOS:
                    MemoryDomains.VmdPool.Clear();
                    foreach (var proto in (advancedMessage.objectValue as VmdPrototype[]))
                    {
                        MemoryDomains.AddVMD(proto);
                    }

                    break;

                case REMOTE_DOMAIN_VMD_ADD:
                    MemoryDomains.AddVMD_NET((advancedMessage.objectValue as VmdPrototype));
                    break;

                case REMOTE_DOMAIN_VMD_REMOVE:
                {
                    StepActions.ClearStepBlastUnits();
                    MemoryDomains.RemoveVMD_NET((advancedMessage.objectValue as string));
                }
                break;

                case REMOTE_DOMAIN_ACTIVETABLE_MAKEDUMP:
                {
                    void a()
                    {
                        MemoryDomains.GenerateActiveTableDump((string)(advancedMessage.objectValue as object[])[0],
                                                              (string)(advancedMessage.objectValue as object[])[1]);
                    }

                    SyncObjectSingleton.EmuThreadExecute(a, false);
                }
                break;

                case REMOTE_BLASTTOOLS_GETAPPLIEDBACKUPLAYER:
                {
                    var bl = (BlastLayer)(advancedMessage.objectValue as object[])[0];
                    var sk = (StashKey)(advancedMessage.objectValue as object[])[1];

                    void a()
                    {
                        e.setReturnValue(BlastTools.GetAppliedBackupLayer(bl, sk));
                    }

                    SyncObjectSingleton.EmuThreadExecute(a, false);
                    break;
                }

                case REMOTE_LONGARRAY_FILTERDOMAIN:
                {
                    lock (loadLock)
                    {
                        var      objValues       = (advancedMessage.objectValue as object[]);
                        string   domain          = (string)objValues[0];
                        string   LimiterListHash = (string)objValues[1];
                        StashKey sk = objValues[2] as StashKey;         //Intentionally nullable

                        void a()
                        {
                            if (sk != null)         //If a stashkey was passed in, we want to load then profile
                            {
                                StockpileManager_EmuSide.LoadState_NET(sk, false);
                            }

                            MemoryInterface mi = MemoryDomains.MemoryInterfaces[domain];
                            List <long>     allLegalAdresses = new List <long>();

                            int listItemSize = Filtering.GetPrecisionFromHash(LimiterListHash);

                            for (long i = 0; i < mi.Size; i += listItemSize)
                            {
                                if (Filtering.LimiterPeekBytes(i, i + listItemSize, mi.Name, LimiterListHash, mi))
                                {
                                    for (int j = 0; j < listItemSize; j++)
                                    {
                                        allLegalAdresses.Add(i + j);
                                    }
                                }
                            }

                            e.setReturnValue(allLegalAdresses.ToArray());
                        }

                        //If the emulator uses callbacks and we're loading a state, we do everything on the main thread and once we're done, we unpause emulation
                        if (sk != null && ((bool?)AllSpec.VanguardSpec[VSPEC.LOADSTATE_USES_CALLBACKS] ?? false))
                        {
                            SyncObjectSingleton.FormExecute(a);
                            LocalNetCoreRouter.Route(NetcoreCommands.VANGUARD, NetcoreCommands.REMOTE_RESUMEEMULATION, true);
                        }
                        else         //We can just do everything on the emulation thread as it'll block
                        {
                            SyncObjectSingleton.EmuThreadExecute(a, true);
                        }
                    }
                }
                break;

                case REMOTE_KEY_GETRAWBLASTLAYER:
                {
                    void a()
                    {
                        e.setReturnValue(StockpileManager_EmuSide.GetRawBlastlayer());
                    }
                    SyncObjectSingleton.EmuThreadExecute(a, false);
                }
                break;

                case REMOTE_BL_GETDIFFBLASTLAYER:
                {
                    string filename = (advancedMessage.objectValue as string);
                    void a()
                    {
                        e.setReturnValue(BlastDiff.GetBlastLayer(filename));
                    }
                    SyncObjectSingleton.EmuThreadExecute(a, false);
                }
                break;

                case REMOTE_SET_APPLYUNCORRUPTBL:
                {
                    void a()
                    {
                        if (StockpileManager_EmuSide.UnCorruptBL != null)
                        {
                            StockpileManager_EmuSide.UnCorruptBL.Apply(true);
                        }
                    }
                    SyncObjectSingleton.EmuThreadExecute(a, false);
                }
                break;

                case REMOTE_SET_APPLYCORRUPTBL:
                {
                    void a()
                    {
                        if (StockpileManager_EmuSide.CorruptBL != null)
                        {
                            StockpileManager_EmuSide.CorruptBL.Apply(false);
                        }
                    }
                    SyncObjectSingleton.EmuThreadExecute(a, false);
                }
                break;

                case REMOTE_CLEARSTEPBLASTUNITS:
                    SyncObjectSingleton.FormExecute(() =>
                    {
                        StepActions.ClearStepBlastUnits();
                    });
                    break;

                case REMOTE_LOADPLUGINS:
                    SyncObjectSingleton.FormExecute(() =>
                    {
                        string emuPluginDir = "";
                        try
                        {
                            emuPluginDir = System.IO.Path.Combine(RtcCore.EmuDir, "RTC", "PLUGINS");
                        }
                        catch (Exception e)
                        {
                            RTCV.Common.Logging.GlobalLogger.Error(e, "Unable to find plugin dir in {dir}", RtcCore.EmuDir + "\\RTC" + "\\PLUGINS");
                        }
                        RtcCore.LoadPlugins(new[] { RtcCore.pluginDir, emuPluginDir });
                    });

                    break;

                case REMOTE_REMOVEEXCESSINFINITESTEPUNITS:
                    SyncObjectSingleton.FormExecute(() =>
                    {
                        StepActions.RemoveExcessInfiniteStepUnits();
                    });
                    break;

                default:
                    new object();
                    break;
                }

                return(e.returnMessage);
            }
            catch (Exception ex)
            {
                if (CloudDebug.ShowErrorDialog(ex, true) == DialogResult.Abort)
                {
                    throw new RTCV.NetCore.AbortEverythingException();
                }

                return(e.returnMessage);
            }
        }
Ejemplo n.º 16
0
		public static void LOAD_GAME_DONE()
		{
			try
			{
				if (disableRTC) return;

				if (AllSpec.UISpec == null)
				{
					CLOSE_GAME();
					GlobalWin.MainForm.CloseRom();
					MessageBox.Show("It appears you haven't connected to StandaloneRTC. Please make sure that the RTC is running and not just Bizhawk.\nIf you have an antivirus, it might be blocking the RTC from launching.\n\nIf you keep getting this message, poke the RTC devs for help (Discord is in the launcher).", "RTC Not Connected");
					return;
				}

				//Glitch Harvester warning for archives

				string uppercaseFilename = GlobalWin.MainForm.CurrentlyOpenRom.ToUpper();
				if (uppercaseFilename.Contains(".ZIP") || uppercaseFilename.Contains(".7Z"))
				{
					MessageBox.Show($"The selected file {Path.GetFileName(uppercaseFilename.Split('|')[0])} is an archive.\nThe RTC does not support archived rom files. Please extract the file then try again.");
					CLOSE_GAME(true);
					return;
				}

				//Load Game vars into RTC_Core
				PathEntry pathEntry = Global.Config.PathEntries[Global.Game.System, "Savestates"] ??
				Global.Config.PathEntries[Global.Game.System, "Base"];



				//prepare memory domains in advance on bizhawk side
				bool domainsChanged = RefreshDomains(false);

				PartialSpec gameDone = new PartialSpec("VanguardSpec");
				gameDone[VSPEC.SYSTEM] = BIZHAWK_GET_CURRENTLYLOADEDSYSTEMNAME().ToUpper();
				gameDone[VSPEC.GAMENAME] = BIZHAWK_GET_FILESYSTEMGAMENAME();
				gameDone[VSPEC.SYSTEMPREFIX] = BIZHAWK_GET_SAVESTATEPREFIX();
				gameDone[VSPEC.SYSTEMCORE] = BIZHAWK_GET_SYSTEMCORENAME(Global.Game.System);
				gameDone[VSPEC.SYNCSETTINGS] = BIZHAWK_GETSET_SYNCSETTINGS;
				gameDone[VSPEC.OPENROMFILENAME] = GlobalWin.MainForm.CurrentlyOpenRom;
				gameDone[VSPEC.MEMORYDOMAINS_BLACKLISTEDDOMAINS] = VanguardCore.GetBlacklistedDomains(BIZHAWK_GET_CURRENTLYLOADEDSYSTEMNAME().ToUpper());
				gameDone[VSPEC.MEMORYDOMAINS_INTERFACES] = GetInterfaces();
				gameDone[VSPEC.CORE_DISKBASED] = isCurrentCoreDiskBased();
				AllSpec.VanguardSpec.Update(gameDone);

				//This is local. If the domains changed it propgates over netcore
				LocalNetCoreRouter.Route(Endpoints.CorruptCore, Remote.EventDomainsUpdated, domainsChanged, true);

				if (VanguardCore.GameName != lastGameName)
				{
					LocalNetCoreRouter.Route(Endpoints.UI, Basic.ResetGameProtectionIfRunning, true);
				}
				lastGameName = VanguardCore.GameName;

				RtcCore.InvokeLoadGameDone();
				VanguardCore.RTE_API.LOAD_GAME();
			}
			catch (Exception ex)
			{
				if (VanguardCore.ShowErrorDialog(ex) == DialogResult.Abort)
					throw new AbortEverythingException();
			}
		}