Ejemplo n.º 1
0
        public void TestDropSpeedLevel9()
        {
            var romLoader = new RomLoader();
            var rom       = romLoader.Load("Roms/tetris.gb");

            var emulator = new Emulator();

            emulator.Load(rom);

            emulator.Execute(125);
            emulator.Hit(Button.Start);
            emulator.Hit(Button.Start);
            emulator.Hit(Button.Right);
            emulator.Hit(Button.Right);
            emulator.Hit(Button.Right);
            emulator.Hit(Button.Right);
            emulator.Hit(Button.Down);
            emulator.Hit(Button.Start);

            emulator.Press(Button.Down);

            for (int i = 0; i < 14; i++)
            {
                emulator.Show();
                emulator.Execute(3);
            }
        }
Ejemplo n.º 2
0
        public void Sgrom_LoadImage()
        {
            var sc       = new ServiceContainer();
            var cfgSvc   = new Mock <IConfigurationService>();
            var openv    = new Mock <PlatformDefinition>();
            var listener = new Mock <DecompilerEventListener>();
            var arch     = new M68kArchitecture(sc, "m68k");
            var platform = new SegaGenesisPlatform(sc, arch);

            cfgSvc.Setup(c => c.GetArchitecture("m68k")).Returns(arch);
            cfgSvc.Setup(c => c.GetEnvironment("sega-genesis")).Returns(openv.Object);
            openv.Setup(o => o.Load(sc, arch)).Returns(platform);
            sc.AddService <IConfigurationService>(cfgSvc.Object);
            sc.AddService <DecompilerEventListener>(listener.Object);
            Given_AbsoluteMemoryMap(platform);

            var rawBytes = new byte[0x300];
            var sgrom    = new RomLoader(sc, "foo.bin", rawBytes);
            var program  = sgrom.Load(Address.Ptr32(0));

            var romSegment = program.SegmentMap.Segments.Values.First();
            var bmem       = (ByteMemoryArea)romSegment.MemoryArea;

            Assert.IsNotNull(romSegment.MemoryArea, "ROM image should have been loaded into first segment");
            Assert.AreSame(rawBytes, bmem.Bytes, "ROM image should have been loaded into first segment");
            Assert.AreEqual(rawBytes.Length, romSegment.ContentSize);
            var ramSegment = program.SegmentMap.Segments.Values.First(s => s.Name == ".data");

            Assert.IsNotNull(ramSegment.MemoryArea, "RAM segment should have a MemoryArea");
        }
Ejemplo n.º 3
0
        public void Sgrom_LoadImage()
        {
            var sc       = new ServiceContainer();
            var cfgSvc   = mr.Stub <IConfigurationService>();
            var openv    = mr.Stub <OperatingEnvironment>();
            var diagSvc  = mr.StrictMock <IDiagnosticsService>();
            var arch     = new M68kArchitecture("m68k");
            var platform = new SegaGenesisPlatform(sc, arch);

            cfgSvc.Expect(c => c.GetArchitecture("m68k")).Return(arch);
            cfgSvc.Expect(c => c.GetEnvironment("sega-genesis")).Return(openv);
            openv.Expect(o => o.Load(sc, arch)).Return(platform);
            sc.AddService <IConfigurationService>(cfgSvc);
            sc.AddService <IDiagnosticsService>(diagSvc);
            Given_AbsoluteMemoryMap(platform);
            mr.ReplayAll();

            var rawBytes = new byte[0x300];
            var sgrom    = new RomLoader(sc, "foo.bin", rawBytes);
            var program  = sgrom.Load(Address.Ptr32(0));

            var romSegment = program.SegmentMap.Segments.Values.First();

            Assert.IsNotNull(romSegment.MemoryArea, "ROM image should have been loaded into first segment");
            Assert.AreSame(rawBytes, romSegment.MemoryArea.Bytes, "ROM image should have been loaded into first segment");
            Assert.AreEqual(rawBytes.Length, romSegment.ContentSize);
            var ramSegment = program.SegmentMap.Segments.Values.First(s => s.Name == ".data");

            Assert.IsNotNull(ramSegment.MemoryArea, "RAM segment should have a MemoryArea");
        }
Ejemplo n.º 4
0
    private IEnumerator Init()
    {
        yield return(null);

        var files = RomLoader.Discover();
        var rom   = RomLoader.Load(files[0]);

        emulatorManager.LoadRom(rom);
    }
Ejemplo n.º 5
0
        public BatchRunner(MainForm mainForm, IEnumerable <string> files, int numFrames)
        {
            _files     = new List <string>(files);
            _numFrames = numFrames;

            _ldr               = new RomLoader();
            _ldr.OnLoadError  += OnLoadError;
            _ldr.ChooseArchive = ChooseArchive;
            _comm              = mainForm.CreateCoreComm();
        }
Ejemplo n.º 6
0
        private void LoadRom()
        {
            var romPath = _config.Read("Emulator.Rom.Path", "Roms/tetris.gb");
            var game    = new RomLoader().Load(romPath);

            lock (_emulator)
            {
                _emulator.Load(game);
            }
        }
Ejemplo n.º 7
0
        public BatchRunner(CoreComm comm, IEnumerable <string> files, int numFrames)
        {
            _files     = new List <string>(files);
            _numFrames = numFrames;

            _ldr               = new RomLoader(GlobalWin.Config);
            _ldr.OnLoadError  += OnLoadError;
            _ldr.ChooseArchive = ChooseArchive;
            _comm              = comm;
        }
Ejemplo n.º 8
0
        public BatchRunner(IEnumerable <string> files, int numframes)
        {
            this.files     = new List <string>(files);
            this.numframes = numframes;

            ldr               = new RomLoader();
            ldr.OnLoadError  += OnLoadError;
            ldr.ChooseArchive = ChooseArchive;
            Comm              = new CoreComm(CommMessage, CommMessage);
            CoreFileProvider.SyncCoreCommInputSignals(Comm);
        }
Ejemplo n.º 9
0
		public BatchRunner(IEnumerable<string> files, int numframes)
		{
			this.files = new List<string>(files);
			this.numframes = numframes;

			ldr = new RomLoader();
			ldr.OnLoadError += OnLoadError;
			ldr.ChooseArchive = ChooseArchive;
			Comm = new CoreComm(CommMessage, CommMessage);
			CoreFileProvider.SyncCoreCommInputSignals(Comm);
		}
Ejemplo n.º 10
0
        public BatchRunner(MainForm mainForm, IEnumerable <string> files, int numFrames)
        {
            _files     = new List <string>(files);
            _numFrames = numFrames;

            _ldr               = new RomLoader();
            _ldr.OnLoadError  += OnLoadError;
            _ldr.ChooseArchive = ChooseArchive;
            var cfp = new CoreFileProvider(CommMessage, Global.FirmwareManager, Global.Config.PathEntries, Global.Config.FirmwareUserSpecifications);

            _comm = mainForm.CreateCoreComm();
        }
Ejemplo n.º 11
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.Error.WriteLine(USAGE);
                Environment.Exit(1);
            }

            ConfigureLogging();

            Rom rom = RomLoader.Load(args[0], failIfCorrupted: false);

            PrintRomInformation(rom.Information);
            Emulator.Init(rom);
        }
Ejemplo n.º 12
0
        public void TestEntryDelayDuration()
        {
            var romLoader = new RomLoader();
            var rom       = romLoader.Load("Roms/tetris.gb");

            var emulator = new Emulator();

            emulator.Load(rom);

            emulator.Execute(125);
            emulator.Hit(Button.Start);
            emulator.Hit(Button.Start);
            emulator.Hit(Button.Start);

            emulator.Execute(16 * 53); // just landed after this
            emulator.Execute(53);      // placed
            emulator.Execute(3);
            emulator.Show();
            return;
        }
Ejemplo n.º 13
0
        public void TestFallSpeedLevel0()
        {
            var romLoader = new RomLoader();
            var rom       = romLoader.Load("Roms/tetris.gb");

            var emulator = new Emulator();

            emulator.Load(rom);

            emulator.Execute(125);
            emulator.Hit(Button.Start);
            emulator.Hit(Button.Start);
            emulator.Hit(Button.Start);

            for (int i = 0; i < 14; i++)
            {
                emulator.Show();
                emulator.Execute(53);
            }
        }
Ejemplo n.º 14
0
        public void Rotate()
        {
            var list = new List <dynamic>();

            list.Add(new { Button = Button.Start, Duration = 2.5 });
            list.Add(new { Button = Button.Start, Duration = 2.7 });
            list.Add(new { Button = Button.Start, Duration = 0 });
            for (int i = 0; i < 4; i++)
            {
                list.Add(new { Button = Button.A, Duration = 0 });
            }

            var loader = new RomLoader();
            var game   = loader.Load("Roms/tetris.gb");

            var emulator = new Emulator();

            emulator.Load(game);

            RunSimulation(emulator, list, _saveImages);
        }
Ejemplo n.º 15
0
        public void Simulate()
        {
            var list = new List <Button>();

            list.Add(Button.Start);
            list.Add(Button.Start);
            list.Add(Button.Start);
            list.Add(Button.Left);
            list.Add(Button.Left);
            list.Add(Button.Left);
            list.Add(Button.Down);

            var loader = new RomLoader();
            var game   = loader.Load("Roms/tetris.gb");

            var emulator = new Emulator();

            emulator.Load(game);

            RunSimulation(emulator, list, _saveImages);
        }
Ejemplo n.º 16
0
		private bool ReloadRom(EmulatorWindow ew)
		{
			bool deterministic = ew.Emulator.DeterministicEmulation;
			string path = ew.CurrentRomPath;

			var loader = new RomLoader
			{
				ChooseArchive = LoadArhiveChooser,
				ChoosePlatform = ChoosePlatformForRom,
				Deterministic = deterministic,
				MessageCallback = AddMessage
			};


			loader.OnLoadError += ShowLoadError;
			loader.OnLoadSettings += CoreSettings;
			loader.OnLoadSyncSettings += CoreSyncSettings;

			var nextComm = new CoreComm(ShowMessageCoreComm, AddMessage);

			var result = loader.LoadRom(path, nextComm);

			if (result)
			{
				ew.SaveRam();
				ew.Emulator.Dispose();
				ew.Emulator = loader.LoadedEmulator;
				ew.CoreComm = nextComm;

				_inputManager.SyncControls();

				if (EmulatorWindows.First() == ew)
				{
					Global.Emulator = ew.Emulator;
				}

				return true;
			}
			else
			{
				return false;
			}
		}
Ejemplo n.º 17
0
		void OnLoadError(object sender, RomLoader.RomErrorArgs e)
		{
			current.Status = Result.EStatus.ErrorOnLoad;
			current.Messages.Add(string.Format("OnLoadError: {0}, {1}, {2}", e.AttemptedCoreLoad, e.Message, e.Type.ToString()));
		}
Ejemplo n.º 18
0
        // Still needs a good bit of refactoring
        public bool LoadRom(string path, bool? deterministicemulation = null)
        {
            // If deterministic emulation is passed in, respect that value regardless, else determine a good value (currently that simply means movies require deterministic emulaton)
            bool deterministic = deterministicemulation.HasValue ?
                deterministicemulation.Value :
                Global.MovieSession.QueuedMovie != null;
                //Global.MovieSession.Movie.IsActive;

            if (!GlobalWin.Tools.AskSave())
            {
                return false;
            }

            var loader = new RomLoader
                {
                    ChooseArchive = LoadArhiveChooser,
                    ChoosePlatform = ChoosePlatformForRom,
                    Deterministic = deterministic,
                    MessageCallback = GlobalWin.OSD.AddMessage
                };
            Global.FirmwareManager.RecentlyServed.Clear();

            loader.OnLoadError += ShowLoadError;
            loader.OnLoadSettings += CoreSettings;
            loader.OnLoadSyncSettings += CoreSyncSettings;

            // this also happens in CloseGame().  but it needs to happen here since if we're restarting with the same core,
            // any settings changes that we made need to make it back to config before we try to instantiate that core with
            // the new settings objects
            CommitCoreSettingsToConfig(); // adelikat: I Think by reordering things, this isn't necessary anymore
            CloseGame();

            var nextComm = CreateCoreComm();
            CoreFileProvider.SyncCoreCommInputSignals(nextComm);
            var result = loader.LoadRom(path, nextComm);

            if (result)
            {
                Global.Emulator = loader.LoadedEmulator;
                Global.Game = loader.Game;
                CoreFileProvider.SyncCoreCommInputSignals(nextComm);
                InputManager.SyncControls();

                if (Global.Emulator is TI83 && Global.Config.TI83autoloadKeyPad)
                {
                    GlobalWin.Tools.Load<TI83KeyPad>();
                }

                if (loader.LoadedEmulator is NES)
                {
                    var nes = loader.LoadedEmulator as NES;
                    if (!string.IsNullOrWhiteSpace(nes.GameName))
                    {
                        Global.Game.Name = nes.GameName;
                    }

                    Global.Game.Status = nes.RomStatus;
                }
                else if (loader.LoadedEmulator is QuickNES)
                {
                    var qns = loader.LoadedEmulator as QuickNES;
                    if (!string.IsNullOrWhiteSpace(qns.BootGodName))
                    {
                        Global.Game.Name = qns.BootGodName;
                    }
                    if (qns.BootGodStatus.HasValue)
                    {
                        Global.Game.Status = qns.BootGodStatus.Value;
                    }
                }

                Global.Rewinder.ResetRewindBuffer();

                if (Global.Emulator.CoreComm.RomStatusDetails == null && loader.Rom != null)
                {
                    Global.Emulator.CoreComm.RomStatusDetails = string.Format(
                        "{0}\r\nSHA1:{1}\r\nMD5:{2}\r\n",
                        loader.Game.Name,
                        loader.Rom.RomData.HashSHA1(),
                        loader.Rom.RomData.HashMD5());
                }

                if (Global.Emulator.BoardName != null)
                {
                    Console.WriteLine("Core reported BoardID: \"{0}\"", Global.Emulator.BoardName);
                }

                // restarts the lua console if a different rom is loaded.
                // im not really a fan of how this is done..
                if (Global.Config.RecentRoms.Empty || Global.Config.RecentRoms.MostRecent != loader.CanonicalFullPath)
                {
                    GlobalWin.Tools.Restart<LuaConsole>();
                }

                Global.Config.RecentRoms.Add(loader.CanonicalFullPath);
                JumpLists.AddRecentItem(loader.CanonicalFullPath);

                // Don't load Save Ram if a movie is being loaded
                if (!Global.MovieSession.MovieIsQueued && File.Exists(PathManager.SaveRamPath(loader.Game)))
                {
                    LoadSaveRam();
                }

                GlobalWin.Tools.Restart();

                if (Global.Config.LoadCheatFileByGame)
                {
                    if (Global.CheatList.AttemptToLoadCheatFile())
                    {
                        GlobalWin.OSD.AddMessage("Cheats file loaded");
                    }
                }

                SetWindowText();
                CurrentlyOpenRom = loader.CanonicalFullPath;
                HandlePlatformMenus();
                _stateSlots.Clear();
                UpdateCoreStatusBarButton();
                UpdateDumpIcon();
                SetMainformMovieInfo();

                Global.Rewinder.CaptureRewindState();

                Global.StickyXORAdapter.ClearStickies();
                Global.StickyXORAdapter.ClearStickyFloats();
                Global.AutofireStickyXORAdapter.ClearStickies();

                RewireSound();
                ToolHelpers.UpdateCheatRelatedTools(null, null);
                if (Global.Config.AutoLoadLastSaveSlot && _stateSlots.HasSlot(Global.Config.SaveSlot))
                {
                    LoadQuickSave("QuickSave" + Global.Config.SaveSlot);
                }

                if (Global.FirmwareManager.RecentlyServed.Count > 0)
                {
                    Console.WriteLine("Active Firmwares:");
                    foreach (var f in Global.FirmwareManager.RecentlyServed)
                    {
                        Console.WriteLine("  {0} : {1}", f.FirmwareId, f.Hash);
                    }
                }
                return true;
            }
            else
            {
                //This shows up if there's a problem
                // TODO: put all these in a single method or something
                HandlePlatformMenus();
                _stateSlots.Clear();
                UpdateStatusSlots();
                UpdateCoreStatusBarButton();
                UpdateDumpIcon();
                SetMainformMovieInfo();
                SetWindowText();
                return false;
            }
        }
Ejemplo n.º 19
0
        private void ShowLoadError(object sender, RomLoader.RomErrorArgs e)
        {
            if (e.Type == RomLoader.LoadErrorType.MissingFirmware)
            {
                var result = MessageBox.Show(
                    "You are missing the needed firmware files to load this Rom\n\nWould you like to open the firmware manager now and configure your firmwares?",
                    e.Message,
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Error);
                if (result == DialogResult.Yes)
                {
                    FirmwaresMenuItem_Click(null, null);
                }
            }
            else
            {
                string title = "load error";
                if (e.AttemptedCoreLoad != null)
                {
                    title = e.AttemptedCoreLoad + " load error";
                }

                MessageBox.Show(this, e.Message, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Ejemplo n.º 20
0
		// Still needs a good bit of refactoring
		public bool LoadRom(string path, LoadRomArgs args)
		{
			//default args
			if (args == null) args = new LoadRomArgs();

			//if this is the first call to LoadRom (they will come in recursively) then stash the args
			bool firstCall = false;
			if (CurrentLoadRomArgs == null)
			{
				firstCall = true;
				CurrentLoadRomArgs = args;
			}
			else
			{
				args = CurrentLoadRomArgs;
			}

			try
			{
				// If deterministic emulation is passed in, respect that value regardless, else determine a good value (currently that simply means movies require deterministic emulaton)
				bool deterministic = args.Deterministic.HasValue ?
					args.Deterministic.Value :
					Global.MovieSession.QueuedMovie != null;
				//Global.MovieSession.Movie.IsActive;

				if (!GlobalWin.Tools.AskSave())
				{
					return false;
				}

				bool asLibretro = (args.OpenAdvanced is OpenAdvanced_Libretro || args.OpenAdvanced is OpenAdvanced_LibretroNoGame);

				var loader = new RomLoader
				{
					ChooseArchive = LoadArhiveChooser,
					ChoosePlatform = ChoosePlatformForRom,
					Deterministic = deterministic,
					MessageCallback = GlobalWin.OSD.AddMessage,
					AsLibretro = asLibretro
				};
				Global.FirmwareManager.RecentlyServed.Clear();

				loader.OnLoadError += ShowLoadError;
				loader.OnLoadSettings += CoreSettings;
				loader.OnLoadSyncSettings += CoreSyncSettings;

				// this also happens in CloseGame().  but it needs to happen here since if we're restarting with the same core,
				// any settings changes that we made need to make it back to config before we try to instantiate that core with
				// the new settings objects
				CommitCoreSettingsToConfig(); // adelikat: I Think by reordering things, this isn't necessary anymore
				CloseGame();

				var nextComm = CreateCoreComm();

				//we need to inform LoadRom which Libretro core to use...
				IOpenAdvanced ioa = args.OpenAdvanced;
				if (ioa is IOpenAdvancedLibretro)
				{
					var ioaretro = ioa as IOpenAdvancedLibretro;

					//prepare a core specification
					//if it wasnt already specified, use the current default
					if (ioaretro.CorePath == null) ioaretro.CorePath = Global.Config.LibretroCore;
					nextComm.LaunchLibretroCore = ioaretro.CorePath;
					if (nextComm.LaunchLibretroCore == null)
						throw new InvalidOperationException("Can't load a file via Libretro until a core is specified");
				}

				CoreFileProvider.SyncCoreCommInputSignals(nextComm);
				var result = loader.LoadRom(path, nextComm);

				//we need to replace the path in the OpenAdvanced with the canonical one the user chose.
				//It can't be done until loder.LoadRom happens (for CanonicalFullPath)
				//i'm not sure this needs to be more abstractly engineered yet until we have more OpenAdvanced examples
				if (ioa is OpenAdvanced_Libretro)
				{
					var oaretro = ioa as OpenAdvanced_Libretro;
					oaretro.token.Path = loader.CanonicalFullPath;
				}
				if (ioa is OpenAdvanced_OpenRom) ((OpenAdvanced_OpenRom)ioa).Path = loader.CanonicalFullPath;
				string loaderName = "*" + OpenAdvancedSerializer.Serialize(ioa);

				if (result)
				{
					Global.Emulator = loader.LoadedEmulator;
					Global.Game = loader.Game;
					CoreFileProvider.SyncCoreCommInputSignals(nextComm);
					InputManager.SyncControls();

					if (Global.Emulator is TI83 && Global.Config.TI83autoloadKeyPad)
					{
						GlobalWin.Tools.Load<TI83KeyPad>();
					}

					if (loader.LoadedEmulator is NES)
					{
						var nes = loader.LoadedEmulator as NES;
						if (!string.IsNullOrWhiteSpace(nes.GameName))
						{
							Global.Game.Name = nes.GameName;
						}

						Global.Game.Status = nes.RomStatus;
					}
					else if (loader.LoadedEmulator is QuickNES)
					{
						var qns = loader.LoadedEmulator as QuickNES;
						if (!string.IsNullOrWhiteSpace(qns.BootGodName))
						{
							Global.Game.Name = qns.BootGodName;
						}
						if (qns.BootGodStatus.HasValue)
						{
							Global.Game.Status = qns.BootGodStatus.Value;
						}
					}

					Global.Rewinder.ResetRewindBuffer();

					if (Global.Emulator.CoreComm.RomStatusDetails == null && loader.Rom != null)
					{
						Global.Emulator.CoreComm.RomStatusDetails = string.Format(
							"{0}\r\nSHA1:{1}\r\nMD5:{2}\r\n",
							loader.Game.Name,
							loader.Rom.RomData.HashSHA1(),
							loader.Rom.RomData.HashMD5());
					}

					if (Global.Emulator.BoardName != null)
					{
						Console.WriteLine("Core reported BoardID: \"{0}\"", Global.Emulator.BoardName);
					}

					// restarts the lua console if a different rom is loaded.
					// im not really a fan of how this is done..
					if (Global.Config.RecentRoms.Empty || Global.Config.RecentRoms.MostRecent != loaderName)
					{
						GlobalWin.Tools.Restart<LuaConsole>();
					}

					Global.Config.RecentRoms.Add(loaderName);
					JumpLists.AddRecentItem(loaderName, ioa.DisplayName);

					// Don't load Save Ram if a movie is being loaded
					if (!Global.MovieSession.MovieIsQueued && File.Exists(PathManager.SaveRamPath(loader.Game)))
					{
						LoadSaveRam();
					}

					GlobalWin.Tools.Restart();

					if (Global.Config.LoadCheatFileByGame)
					{
						if (Global.CheatList.AttemptToLoadCheatFile())
						{
							GlobalWin.OSD.AddMessage("Cheats file loaded");
						}
					}

					SetWindowText();
					CurrentlyOpenRom = loaderName;
					HandlePlatformMenus();
					_stateSlots.Clear();
					UpdateCoreStatusBarButton();
					UpdateDumpIcon();
					SetMainformMovieInfo();
					CurrentlyOpenRomArgs = args;

					Global.Rewinder.CaptureRewindState();

					Global.StickyXORAdapter.ClearStickies();
					Global.StickyXORAdapter.ClearStickyFloats();
					Global.AutofireStickyXORAdapter.ClearStickies();

					RewireSound();
					ToolHelpers.UpdateCheatRelatedTools(null, null);
					if (Global.Config.AutoLoadLastSaveSlot && _stateSlots.HasSlot(Global.Config.SaveSlot))
					{
						LoadQuickSave("QuickSave" + Global.Config.SaveSlot);
					}

					if (Global.FirmwareManager.RecentlyServed.Count > 0)
					{
						Console.WriteLine("Active Firmwares:");
						foreach (var f in Global.FirmwareManager.RecentlyServed)
						{
							Console.WriteLine("  {0} : {1}", f.FirmwareId, f.Hash);
						}
					}
					return true;
				}
				else
				{
					//This shows up if there's a problem                
					// TODO: put all these in a single method or something

					//The ROM has been loaded by a recursive invocation of the LoadROM method.
					if (!(Global.Emulator is NullEmulator))
					{
						return true;
					}

					HandlePlatformMenus();
					_stateSlots.Clear();
					UpdateStatusSlots();
					UpdateCoreStatusBarButton();
					UpdateDumpIcon();
					SetMainformMovieInfo();
					SetWindowText();
					return false;
				}
			}
			finally
			{
				if (firstCall)
				{
					CurrentLoadRomArgs = null;
				}
			}
		}
Ejemplo n.º 21
0
		private void CoreSyncSettings(object sender, RomLoader.SettingsLoadArgs e)
		{
			if (Global.MovieSession.QueuedMovie != null)
			{
				if (!string.IsNullOrWhiteSpace(Global.MovieSession.QueuedMovie.SyncSettingsJson))
				{
					e.Settings = ConfigService.LoadWithType(Global.MovieSession.QueuedMovie.SyncSettingsJson);
				}
				else
				{
					e.Settings = Global.Config.GetCoreSyncSettings(e.Core);

					// adelikat: only show this nag if the core actually has sync settings, not all cores do
					if (e.Settings != null && !_supressSyncSettingsWarning)
					{
						MessageBox.Show(
						"No sync settings found, using currently configured settings for this core.",
						"No sync settings found",
						MessageBoxButtons.OK,
						MessageBoxIcon.Warning
						);
					}
				}
			}
			else
			{
				e.Settings = Global.Config.GetCoreSyncSettings(e.Core);
			}

		}
Ejemplo n.º 22
0
        static async Task Main(string[] args)
        {
            if (args.Length < 2 || string.Equals(args[0], "--help", StringComparison.OrdinalIgnoreCase))
            {
                PrintUsage();
                return;
            }

            var arguments = new Queue <string>();

            foreach (var argument in args)
            {
                arguments.Enqueue(argument);
            }

            var fileSystem = PhysicalFileSystem.Instance;
            var context    = new ConsoleContext
            {
                FileSystem     = fileSystem,
                RomLibrary     = new Library("Library", fileSystem),
                VerboseLogging = args.Any(arg => arg == "--verbose")
            };

            while (arguments.TryDequeue(out var arg))
            {
                if (string.Equals(arg, "--save", StringComparison.OrdinalIgnoreCase))
                {
                    if (context.Rom == null)
                    {
                        throw new InvalidOperationException("Argument '--save' must follow a ROM directory argument");
                    }
                    if (!(context.Rom is ISaveable saveableRom))
                    {
                        throw new NotSupportedException($"ROM of type {context.Rom.GetType().Name} does not implement ISaveable");
                    }

                    await saveableRom.Save();

                    if (context.VerboseLogging)
                    {
                        Console.WriteLine("Saved");
                    }
                }
                else if (string.Equals(arg, "--save-to", StringComparison.OrdinalIgnoreCase))
                {
                    if (context.Rom == null)
                    {
                        throw new InvalidOperationException("Argument '--save-to' must follow a ROM directory argument");
                    }

                    if (!arguments.TryDequeue(out var target))
                    {
                        throw new ArgumentException("Argument '--save-to' must be followed by a ROM directory argument");
                    }

                    if (!(context.Rom is ISaveableToDirectory saveableRom))
                    {
                        throw new NotSupportedException($"ROM of type {context.Rom.GetType().Name} does not implement ISaveableToDirectory");
                    }

                    var targetDirectory = GetRomDirectory(target, context);

                    await saveableRom.Save(targetDirectory, fileSystem);

                    if (context.VerboseLogging)
                    {
                        Console.WriteLine("Saved to " + targetDirectory);
                    }
                }
                else if (arg.StartsWith("library:"))
                {
                    var libraryItemName = arg.Split(':', 2)[1];
                    var libraryItem     = context.RomLibrary.GetItem(libraryItemName);
                    if (libraryItem == null)
                    {
                        throw new DirectoryNotFoundException($"Could not find a library item with the name '{libraryItemName}'");
                    }

                    var rom = await RomLoader.LoadRom(libraryItem.FullPath, fileSystem) ?? throw new ArgumentException($"Unable to determine the type of ROM located at {arg}");

                    context.Rom     = rom;
                    context.RomPath = libraryItem.FullPath;
                    if (context.VerboseLogging)
                    {
                        Console.WriteLine($"Loaded {arg}");
                    }
                }
                else if (Directory.Exists(arg))
                {
                    if (File.Exists(Path.Combine(arg, "modpack.json")) || File.Exists(Path.Combine(arg, "mod.json")))
                    {
                        await ApplyMod(arg, context);
                    }
                    else
                    {
                        var rom = await RomLoader.LoadRom(arg, fileSystem);

                        context.Rom     = rom ?? throw new ArgumentException($"Unable to determine the type of ROM located at {arg}");
                        context.RomPath = arg;
                        if (context.VerboseLogging)
                        {
                            Console.WriteLine($"Loaded {arg}");
                        }
                    }
                }
                else if (File.Exists(arg))
                {
                    var rom = await RomLoader.LoadRom(arg, fileSystem);

                    if (rom != null)
                    {
                        context.Rom     = rom;
                        context.RomPath = arg;
                        if (context.VerboseLogging)
                        {
                            Console.WriteLine($"Loaded {arg}");
                        }
                    }
                    else
                    {
                        // Assume it's a mod
                        await ApplyMod(arg, context);
                    }
                }
                else if (Commands.TryGetValue(arg, out var command))
                {
                    await command(arguments, context);
                }
                else if (arg == "--verbose")
                {
                    // Do nothing, verbose logging has already been enabled
                }
                else
                {
                    if (context.VerboseLogging)
                    {
                        Console.WriteLine($"Unrecognized argument '{arg}'");
                    }
                    return;
                }
            }
        }
Ejemplo n.º 23
0
		private static void CoreSettings(object sender, RomLoader.SettingsLoadArgs e)
		{
			e.Settings = Global.Config.GetCoreSettings(e.Core);
		}
Ejemplo n.º 24
0
        static void Main(string[] args)
        {
            var pathToRom = @"Contra (USA).nes";

            Global.Config = new Config();

            Global.Config.ResolveDefaults();
            HawkFile.ArchiveHandlerFactory = new SevenZipSharpArchiveHandler();

            Global.Config.NES_InQuickNES = false;
            Global.FirmwareManager = new FirmwareManager();

            Global.ActiveController = new Controller(NullEmulator.NullController);

            //NES.BootGodDB.GetDatabaseBytes = () => { return new byte[0]; };

            NES.BootGodDB.GetDatabaseBytes = () =>
            {
                using (var stream = new StreamReader(@"NesCarts (2012-10-22).xml"))
                {
                    return stream.BaseStream.ReadAllBytes();
                }

                //using (var NesCartFile =
                //        new HawkFile(Path.Combine(@"C:\Users\jeff\GitHub\BizHawk\output", "gamedb", "NesCarts.7z")).BindFirst())
                //{
                //    return NesCartFile
                //        .GetStream()
                //        .ReadAllBytes();
                //}
            };

            var loader = new RomLoader
            {
                //ChooseArchive = LoadArhiveChooser,
                ChoosePlatform = ChoosePlatformForRom,
                //Deterministic = deterministic,
                //MessageCallback = GlobalWin.OSD.AddMessage
            };

            var coreComm = new CoreComm(null, null);
            CoreFileProvider.SyncCoreCommInputSignals(coreComm);

            var result = loader.LoadRom(pathToRom, coreComm);

            if(!result)
            {
                Console.WriteLine("Could not load rom");
                Environment.Exit(1);
            }

            var emulator = loader.LoadedEmulator;
            var game = loader.Game;

            emulator.Controller = new Controller(emulator.ControllerDefinition);

            NES nes = (NES)emulator;
            APU apu = nes.apu;

            nes.apu.DebugCallbackDivider = 1;
            int lastP0Note = 0, lastP1Note = 0, lastTriNote = 0;

            int callbackCount = 0;

            nes.apu.DebugCallback = () => {
                callbackCount++;

                int pulse0_period = apu.pulse[0].timer_reload_value;
                float pulse0_freq = 1789773.0f / (16.0f * (pulse0_period + 1));
                int pulse0_note = FindNearestNote(pulse0_freq);

                int pulse1_period = apu.pulse[1].timer_reload_value;
                float pulse1_freq = 1789773.0f / (16.0f * (pulse1_period + 1));
                int pulse1_note = FindNearestNote(pulse1_freq);

                int tri_period = apu.triangle.Debug_PeriodValue;
                float tri_freq = 1789773.0f / (32.0f * (tri_period + 1));
                int tri_note = FindNearestNote(tri_freq);

                if (pulse0_note != lastP0Note || pulse1_note != lastP1Note || tri_note != lastTriNote)
                {
                    //Console.WriteLine("{0},{1},{2},{3}", callbackCount, NameForNote(pulse0_note), NameForNote(pulse1_note), NameForNote(tri_note));
                    Console.WriteLine("{0},{1},{2},{3}", callbackCount, pulse0_freq, pulse1_freq, tri_freq);

                    lastP0Note = pulse0_note;
                    lastP1Note = pulse1_note;
                    lastTriNote = tri_note;
                }
            };

            for (int i = 0; i < 60 * 10; i++)
            {
                emulator.FrameAdvance(false, true);
            }
        }
Ejemplo n.º 25
0
        public void TestLineRemoveDuration()
        {
            var romLoader = new RomLoader();
            var rom       = romLoader.Load("Roms/tetris.gb");

            var emulator = new Emulator();

            emulator.Load(rom);

            emulator.Execute(125);
            emulator.Hit(Button.Start);
            emulator.Hit(Button.Start);
            emulator.Hit(Button.Start);

            // I
            emulator.Hit(Button.Right);
            emulator.Hit(Button.Right);
            emulator.Hit(Button.Right);
            emulator.Press(Button.Down);
            emulator.Execute(3 * 17);
            emulator.Release(Button.Down);
            emulator.Execute(2);


            // S
            emulator.Hit(Button.Right);
            emulator.Press(Button.Down);
            emulator.Execute(3 * 17);
            emulator.Release(Button.Down);
            emulator.Execute(2);

            // O
            emulator.Hit(Button.Left);
            emulator.Hit(Button.Left);
            emulator.Hit(Button.Left);
            emulator.Hit(Button.Left);
            emulator.Press(Button.Down);
            emulator.Execute(3 * 17);
            emulator.Release(Button.Down);
            emulator.Execute(2);

            // T
            emulator.Hit(Button.Right);
            emulator.Hit(Button.Right);
            emulator.Hit(Button.Right);
            emulator.Press(Button.Down);
            emulator.Execute(3 * 17);
            emulator.Release(Button.Down);
            emulator.Execute(2);

            // J
            emulator.Hit(Button.A);
            emulator.Hit(Button.Left);
            emulator.Press(Button.Down);
            emulator.Execute(3 * 15);
            emulator.Release(Button.Down);

            emulator.Show();
            emulator.Execute(93);
            emulator.Show();
        }
Ejemplo n.º 26
0
		private bool LoadRom(string path)
		{
			bool deterministic = true;

			var loader = new RomLoader
			{
				ChooseArchive = LoadArhiveChooser,
				ChoosePlatform = ChoosePlatformForRom,
				Deterministic = deterministic,
				MessageCallback = AddMessage
			};


			loader.OnLoadError += ShowLoadError;
			loader.OnLoadSettings += CoreSettings;
			loader.OnLoadSyncSettings += CoreSyncSettings;

			var nextComm = new CoreComm(ShowMessageCoreComm, AddMessage);

			var result = loader.LoadRom(path, nextComm);

			if (result)
			{
				var ew = new EmulatorWindow(this)
				{
					TopLevel = false,
					Text = Path.GetFileNameWithoutExtension(StripArchivePath(path)),
					Emulator = loader.LoadedEmulator,

					GL = new Bizware.BizwareGL.Drivers.OpenTK.IGL_TK(),
					GLManager = GLManager.Instance,
					Game = loader.Game,
					CurrentRomPath = loader.CanonicalFullPath
				};

				nextComm.RequestGLContext = () => ew.GLManager.CreateGLContext();
				nextComm.ActivateGLContext = (gl) => ew.GLManager.Activate((GLManager.ContextRef)ew.GL);
				nextComm.DeactivateGLContext = () => ew.GLManager.Deactivate();

				ew.CoreComm = nextComm;
				ew.Init();

				if (EmulatorWindows.Any())
				{
					// Attempt to open the window is a smart location
					var last = EmulatorWindows.Last();

					int x = last.Location.X + last.Width + 5;
					int y = last.Location.Y;
					if (x + (last.Width / 2) > Width) // If it will go too far off screen
					{
						y += last.Height + 5;
						x = EmulatorWindows.First().Location.X;
					}

					ew.Location = new Point(x, y);
				}
				

				EmulatorWindows.Add(ew);

				WorkspacePanel.Controls.Add(ew);
				ew.Show();

				Global.Config.RecentRoms.Add(loader.CanonicalFullPath);

				if (EmulatorWindows.Count == 1)
				{
					Global.Emulator = ew.Emulator;
				}

				_inputManager.SyncControls();

				return true;
			}
			else
			{
				return false;
			}
		}
Ejemplo n.º 27
0
		private void ShowLoadError(object sender, RomLoader.RomErrorArgs e)
		{
			string title = "load error";
			if (e.AttemptedCoreLoad != null)
			{
				title = e.AttemptedCoreLoad + " load error";
			}

			MessageBox.Show(this, e.Message, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
		}
Ejemplo n.º 28
0
		private void ShowLoadError(object sender, RomLoader.RomErrorArgs e)
		{
			if (e.Type == RomLoader.LoadErrorType.MissingFirmware)
			{
				var result = MessageBox.Show(
					"You are missing the needed firmware files to load this Rom\n\nWould you like to open the firmware manager now and configure your firmwares?",
					e.Message,
					MessageBoxButtons.YesNo,
					MessageBoxIcon.Error);
				if (result == DialogResult.Yes)
				{
					FirmwaresMenuItem_Click(null, e);
					if (e.Retry)
					{
						// Retry loading the ROM here. This leads to recursion, as the original call to LoadRom has not exited yet,
						// but unless the user tries and fails to set his firmware a lot of times, nothing should happen.
						// Refer to how RomLoader implemented its LoadRom method for a potential fix on this.
						LoadRom(e.RomPath, CurrentLoadRomArgs);
					}
				}
			}
			else
			{
				string title = "load error";
				if (e.AttemptedCoreLoad != null)
				{
					title = e.AttemptedCoreLoad + " load error";
				}

				MessageBox.Show(this, e.Message, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
Ejemplo n.º 29
0
		private void CoreSyncSettings(object sender, RomLoader.SettingsLoadArgs e)
		{
			if (Global.MovieSession.QueuedMovie != null)
			{
				if (!string.IsNullOrWhiteSpace(Global.MovieSession.QueuedMovie.SyncSettingsJson))
				{
					e.Settings = ConfigService.LoadWithType(Global.MovieSession.QueuedMovie.SyncSettingsJson);
				}
				else
				{
					MessageBox.Show(
						"No sync settings found, using currently configured settings for this core.",
						"No sync settings found",
						MessageBoxButtons.OK,
						MessageBoxIcon.Warning
						);

					e.Settings = Global.Config.GetCoreSyncSettings(e.Core);
				}
			}
			else
			{
				e.Settings = Global.Config.GetCoreSyncSettings(e.Core);
			}

		}
Ejemplo n.º 30
0
		private void CoreSyncSettings(object sender, RomLoader.SettingsLoadArgs e)
		{
			if (Global.MovieSession.QueuedMovie != null)
			{
				e.Settings = ConfigService.LoadWithType(Global.MovieSession.QueuedMovie.SyncSettingsJson);
			}
			else
			{
				e.Settings = Global.Config.GetCoreSyncSettings(e.Core);
			}

		}