diff --git a/Assets/gamedb/gamedb_Odyssey2.txt b/Assets/gamedb/gamedb_Odyssey2.txt index 1fb1843ce7..1f10881f12 100644 --- a/Assets/gamedb/gamedb_Odyssey2.txt +++ b/Assets/gamedb/gamedb_Odyssey2.txt @@ -4,5 +4,7 @@ SHA1:38D4AAB263E10B1DAC3410C120536EE079826BCB Fatso 2 O2 SHA1:3720DD6B5EE3DC62C5AF2EA9D915A2B83DE9463D Chief Chef O2 SHA1:FEB358E28587DE70D1E89BF0F9A3209CE0B67C57 Haunted House O2 SHA1:B1D65BEDB56FE7A9CF60AA054A9FD9BB7F65B77C 3D Box O2 +SHA1:0270047E2B1FC07581BF0FF9E55035925CF0EFF0 Guiseppe apr14 O2 + diff --git a/Assets/gamedb/gamedb_a2600.txt b/Assets/gamedb/gamedb_a2600.txt index 3799a538aa..6afc385507 100644 --- a/Assets/gamedb/gamedb_a2600.txt +++ b/Assets/gamedb/gamedb_a2600.txt @@ -2703,3 +2703,5 @@ sha1:341BB93E67C21063F3910845D1AF59FEA129FF21 Bang! A26 m=F4SC sha1:62E7A3CE40BE1C29870D892639FBD394977281F5 DHmoveValues(rev2) A26 m=F6SC sha1:FBB0FE0A859BF764D060E264561734B8F7CFC9D7 REF A26 m=4K;NTSC=true sha1:58AA6BBA1D0D26C1287135FC9237B684A984B6BE Princess Rescue A26 m=F4;NTSC=true +sha1:29404640B4579938057969D93A77C9A676AF9965 Crazy Balloon A26 m=4K;NTSC=true + diff --git a/BizHawk.Client.Common/Api/Classes/MovieApi.cs b/BizHawk.Client.Common/Api/Classes/MovieApi.cs index 0a70b83bf1..63473f9e13 100644 --- a/BizHawk.Client.Common/Api/Classes/MovieApi.cs +++ b/BizHawk.Client.Common/Api/Classes/MovieApi.cs @@ -15,13 +15,13 @@ namespace BizHawk.Client.Common private readonly Action LogCallback; - public bool StartsFromSavestate() => Global.MovieSession.Movie.IsActive && Global.MovieSession.Movie.StartsFromSavestate; + public bool StartsFromSavestate() => Global.MovieSession.Movie.IsActive() && Global.MovieSession.Movie.StartsFromSavestate; - public bool StartsFromSaveram() => Global.MovieSession.Movie.IsActive && Global.MovieSession.Movie.StartsFromSaveRam; + public bool StartsFromSaveram() => Global.MovieSession.Movie.IsActive() && Global.MovieSession.Movie.StartsFromSaveRam; public Dictionary GetInput(int frame) { - if (!Global.MovieSession.Movie.IsActive) + if (Global.MovieSession.Movie.NotActive()) { LogCallback("No movie loaded"); return null; @@ -40,7 +40,10 @@ namespace BizHawk.Client.Common public string GetInputAsMnemonic(int frame) { - if (!Global.MovieSession.Movie.IsActive || frame >= Global.MovieSession.Movie.InputLogLength) return string.Empty; + if (Global.MovieSession.Movie.NotActive() || frame >= Global.MovieSession.Movie.InputLogLength) + { + return string.Empty; + } var lg = Global.MovieSession.LogGeneratorInstance(); lg.SetSource(Global.MovieSession.Movie.GetInputState(frame)); return lg.GenerateLogEntry(); @@ -48,7 +51,11 @@ namespace BizHawk.Client.Common public void Save(string filename = null) { - if (!Global.MovieSession.Movie.IsActive) return; + if (Global.MovieSession.Movie.NotActive()) + { + return; + } + if (!string.IsNullOrEmpty(filename)) { filename += $".{Global.MovieSession.Movie.PreferredExtension}"; @@ -65,7 +72,10 @@ namespace BizHawk.Client.Common public Dictionary GetHeader() { var table = new Dictionary(); - if (!Global.MovieSession.Movie.IsActive) return table; + if (Global.MovieSession.Movie.NotActive()) + { + return table; + } foreach (var kvp in Global.MovieSession.Movie.HeaderEntries) table[kvp.Key] = kvp.Value; return table; } @@ -73,7 +83,11 @@ namespace BizHawk.Client.Common public List GetComments() { var list = new List(Global.MovieSession.Movie.Comments.Count); - if (!Global.MovieSession.Movie.IsActive) return list; + if (Global.MovieSession.Movie.NotActive()) + { + return list; + } + for (var i = 0; i < Global.MovieSession.Movie.Comments.Count; i++) list[i] = Global.MovieSession.Movie.Comments[i]; return list; } @@ -81,7 +95,11 @@ namespace BizHawk.Client.Common public List GetSubtitles() { var list = new List(Global.MovieSession.Movie.Subtitles.Count); - if (!Global.MovieSession.Movie.IsActive) return list; + if (Global.MovieSession.Movie.NotActive()) + { + return list; + } + for (var i = 0; i < Global.MovieSession.Movie.Subtitles.Count; i++) list[i] = Global.MovieSession.Movie.Subtitles[i].ToString(); return list; } @@ -94,17 +112,11 @@ namespace BizHawk.Client.Common public bool GetRerecordCounting() => Global.MovieSession.Movie.IsCountingRerecords; - public bool IsLoaded() => Global.MovieSession.Movie.IsActive; + public bool IsLoaded() => Global.MovieSession.Movie.IsActive(); public double Length() => Global.MovieSession.Movie.FrameCount; - public string Mode() => Global.MovieSession.Movie.IsFinished - ? "FINISHED" - : Global.MovieSession.Movie.IsPlaying - ? "PLAY" - : Global.MovieSession.Movie.IsRecording - ? "RECORD" - : "INACTIVE"; + public string Mode() => Global.MovieSession.Movie.Mode.ToString().ToUpper(); public void SetReadOnly(bool readOnly) => Global.MovieSession.ReadOnly = readOnly; @@ -117,7 +129,11 @@ namespace BizHawk.Client.Common public double GetFps() { var movie = Global.MovieSession.Movie; - if (!movie.IsActive) return default; + if (movie.NotActive()) + { + return default; + } + return new PlatformFrameRates()[ movie.HeaderEntries[HeaderKeys.PLATFORM], movie.HeaderEntries.TryGetValue(HeaderKeys.PAL, out var isPal) && isPal == "1" diff --git a/BizHawk.Client.Common/BizHawk.Client.Common.csproj b/BizHawk.Client.Common/BizHawk.Client.Common.csproj index 99ff3d0770..8def528ea1 100644 --- a/BizHawk.Client.Common/BizHawk.Client.Common.csproj +++ b/BizHawk.Client.Common/BizHawk.Client.Common.csproj @@ -120,6 +120,7 @@ + @@ -208,10 +209,10 @@ Bk2Movie.cs - - - - + + + + diff --git a/BizHawk.Client.Common/Global.cs b/BizHawk.Client.Common/Global.cs index aaa2849701..99eb936ed6 100644 --- a/BizHawk.Client.Common/Global.cs +++ b/BizHawk.Client.Common/Global.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using BizHawk.Emulation.Common; -using BizHawk.Emulation.Cores.Sega.MasterSystem; // ReSharper disable StyleCop.SA1401 namespace BizHawk.Client.Common @@ -70,103 +69,6 @@ namespace BizHawk.Client.Common // This relies on a client specific implementation! public static SimpleController ControllerInputCoalescer; - public static SystemInfo SystemInfo - { - get - { - switch (Emulator.SystemId) - { - default: - case "NULL": - return SystemInfo.Null; - case "NES": - return SystemInfo.Nes; - case "INTV": - return SystemInfo.Intellivision; - case "SG": - return SystemInfo.SG; - case "SMS": - if (Emulator is SMS gg && gg.IsGameGear) - { - return SystemInfo.GG; - } - - if (Emulator is SMS sg && sg.IsSG1000) - { - return SystemInfo.SG; - } - - return SystemInfo.SMS; - case "PCECD": - return SystemInfo.PCECD; - case "PCE": - return SystemInfo.PCE; - case "SGX": - return SystemInfo.SGX; - case "GEN": - return SystemInfo.Genesis; - case "TI83": - return SystemInfo.TI83; - case "SNES": - return SystemInfo.SNES; - case "GB": - /* - if ((Emulator as IGameboyCommon).IsCGBMode()) - { - return SystemInfo.GBC; - } - */ - return SystemInfo.GB; - case "A26": - return SystemInfo.Atari2600; - case "A78": - return SystemInfo.Atari7800; - case "C64": - return SystemInfo.C64; - case "Coleco": - return SystemInfo.Coleco; - case "GBA": - return SystemInfo.GBA; - case "N64": - return SystemInfo.N64; - case "SAT": - return SystemInfo.Saturn; - case "DGB": - return SystemInfo.DualGB; - case "GB3x": - return SystemInfo.GB3x; - case "GB4x": - return SystemInfo.GB4x; - case "WSWAN": - return SystemInfo.WonderSwan; - case "Lynx": - return SystemInfo.Lynx; - case "PSX": - return SystemInfo.PSX; - case "AppleII": - return SystemInfo.AppleII; - case "Libretro": - return SystemInfo.Libretro; - case "VB": - return SystemInfo.VirtualBoy; - case "VEC": - return SystemInfo.Vectrex; - case "NGP": - return SystemInfo.NeoGeoPocket; - case "ZXSpectrum": - return SystemInfo.ZXSpectrum; - case "AmstradCPC": - return SystemInfo.AmstradCPC; - case "ChannelF": - return SystemInfo.ChannelF; - case "O2": - return SystemInfo.O2; - case "MAME": - return SystemInfo.MAME; - } - } - } - public static Dictionary UserBag = new Dictionary(); } } diff --git a/BizHawk.Client.Common/PathManager.cs b/BizHawk.Client.Common/PathManager.cs index 9ff2d1741e..810dd1c10e 100644 --- a/BizHawk.Client.Common/PathManager.cs +++ b/BizHawk.Client.Common/PathManager.cs @@ -261,7 +261,7 @@ namespace BizHawk.Client.Common public static string SaveRamPath(GameInfo game) { var name = FilesystemSafeName(game); - if (Global.MovieSession.Movie.IsActive) + if (Global.MovieSession.Movie.IsActive()) { name += $".{Path.GetFileNameWithoutExtension(Global.MovieSession.Movie.Filename)}"; } @@ -288,7 +288,7 @@ namespace BizHawk.Client.Common name = FilesystemSafeName(game); } - if (Global.MovieSession.Movie.IsActive) + if (Global.MovieSession.Movie.IsActive()) { name = Path.Combine(name, $"movie-{Path.GetFileNameWithoutExtension(Global.MovieSession.Movie.Filename)}"); } @@ -363,7 +363,7 @@ namespace BizHawk.Client.Common name += $".{Global.Emulator.Attributes().CoreName}"; } - if (Global.MovieSession.Movie.IsActive) + if (Global.MovieSession.Movie.IsActive()) { name += $".{Path.GetFileNameWithoutExtension(Global.MovieSession.Movie.Filename)}"; } diff --git a/BizHawk.Client.Common/SavestateManager.cs b/BizHawk.Client.Common/SavestateManager.cs index dd9b505f51..3b1820f3f4 100644 --- a/BizHawk.Client.Common/SavestateManager.cs +++ b/BizHawk.Client.Common/SavestateManager.cs @@ -65,7 +65,7 @@ namespace BizHawk.Client.Common } } - if (Global.MovieSession.Movie.IsActive) + if (Global.MovieSession.Movie.IsActive()) { bs.PutLump(BinaryStateLump.Input, delegate(TextWriter tw) @@ -86,7 +86,7 @@ namespace BizHawk.Client.Common }); } - if (Global.MovieSession.Movie.IsActive && Global.MovieSession.Movie is TasMovie) + if (Global.MovieSession.Movie.IsActive() && Global.MovieSession.Movie is TasMovie) { bs.PutLump(BinaryStateLump.LagLog, delegate(TextWriter tw) @@ -139,7 +139,7 @@ namespace BizHawk.Client.Common { var succeed = false; - if (Global.MovieSession.Movie.IsActive) + if (Global.MovieSession.Movie.IsActive()) { bl.GetLump(BinaryStateLump.Input, true, tr => succeed = Global.MovieSession.HandleMovieLoadState_HackyStep1(tr)); if (!succeed) @@ -179,7 +179,7 @@ namespace BizHawk.Client.Common Global.UserBag = (Dictionary)ConfigService.LoadWithType(userData); } - if (Global.MovieSession.Movie.IsActive && Global.MovieSession.Movie is TasMovie) + if (Global.MovieSession.Movie.IsActive() && Global.MovieSession.Movie is TasMovie) { bl.GetLump(BinaryStateLump.LagLog, false, delegate(TextReader tr) { diff --git a/BizHawk.Client.Common/SystemInfo.cs b/BizHawk.Client.Common/SystemInfo.cs index d41436c514..49763fe101 100644 --- a/BizHawk.Client.Common/SystemInfo.cs +++ b/BizHawk.Client.Common/SystemInfo.cs @@ -14,7 +14,7 @@ namespace BizHawk.Client.Common private const JoypadButton UpDownLeftRight = JoypadButton.Up | JoypadButton.Down | JoypadButton.Left | JoypadButton.Right; private const JoypadButton StandardButtons = JoypadButton.A | JoypadButton.B | JoypadButton.Start | JoypadButton.Select | UpDownLeftRight; - private static readonly List _allSystemInfos = new List(); + private static readonly List AllSystemInfos = new List(); #endregion @@ -34,7 +34,7 @@ namespace BizHawk.Client.Common MaxControllers = maxControllers; AvailableButtons = availableButtons; - _allSystemInfos.Add(this); + AllSystemInfos.Add(this); } #endregion @@ -184,7 +184,7 @@ namespace BizHawk.Client.Common public static SystemInfo TI83 { get; } = new SystemInfo("TI - 83", CoreSystem.TI83, 1); /// - /// Gets the instance for Wonderswan + /// Gets the instance for WonderSwan /// public static SystemInfo WonderSwan { get; } = new SystemInfo("WonderSwan", CoreSystem.WonderSwan, 1); @@ -196,7 +196,7 @@ namespace BizHawk.Client.Common /// /// Gets the instance for Vectrex /// - public static SystemInfo Vectrex { get; } = new SystemInfo("Vextrex", CoreSystem.Vectrex, 2); + public static SystemInfo Vectrex { get; } = new SystemInfo("Vectrex", CoreSystem.Vectrex, 2); /// /// Gets the instance for TI-83 @@ -206,12 +206,12 @@ namespace BizHawk.Client.Common /// /// Gets the instance for ZXSpectrum /// - public static SystemInfo ZXSpectrum { get; } = new SystemInfo("ZX Spectrum", CoreSystem.ZXSpectrum, 2); + public static SystemInfo ZxSpectrum { get; } = new SystemInfo("ZX Spectrum", CoreSystem.ZXSpectrum, 2); /// /// Gets the instance for AmstradCPC /// - public static SystemInfo AmstradCPC { get; } = new SystemInfo("Amstrad CPC", CoreSystem.AmstradCPC, 2); + public static SystemInfo AmstradCpc { get; } = new SystemInfo("Amstrad CPC", CoreSystem.AmstradCPC, 2); /// /// Gets the instance for GGL @@ -231,7 +231,7 @@ namespace BizHawk.Client.Common /// /// Gets the instance for MAME /// - public static SystemInfo MAME { get; } = new SystemInfo("MAME", CoreSystem.MAME, 4); + public static SystemInfo Mame { get; } = new SystemInfo("MAME", CoreSystem.MAME, 4); #endregion Get SystemInfo @@ -242,7 +242,7 @@ namespace BizHawk.Client.Common /// public static SystemInfo FindByCoreSystem(CoreSystem system) { - return _allSystemInfos.Find(s => s.System == system); + return AllSystemInfos.Find(s => s.System == system); } /// @@ -252,16 +252,16 @@ namespace BizHawk.Client.Common /// True if object is equal to this instance; otherwise, false public override bool Equals(object obj) { - if (obj is SystemInfo) + if (obj is SystemInfo info) { - return this == (SystemInfo)obj; + return this == info; } return base.Equals(obj); } /// - /// Gets the haschode for current instance + /// Gets the hashcode for current instance /// /// This instance hashcode public override int GetHashCode() diff --git a/BizHawk.Client.Common/config/Config.cs b/BizHawk.Client.Common/config/Config.cs index f01e16208d..0142ba184d 100644 --- a/BizHawk.Client.Common/config/Config.cs +++ b/BizHawk.Client.Common/config/Config.cs @@ -239,44 +239,6 @@ namespace BizHawk.Client.Common /// public bool DispAlternateVsync = false; - public static class DefaultMessageOptions - { - public const int - DispFPSx = 0, - DispFPSy = 0, - DispFrameCx = 0, - DispFrameCy = 14, - DispLagx = 0, - DispLagy = 42, - DispInpx = 0, - DispInpy = 28, - DispRecx = 0, - DispRecy = 56, - DispMultix = 0, - DispMultiy = 14, - DispMessagex = 3, - DispMessagey = 0, - DispAutoholdx = 0, - DispAutoholdy = 0, - DispRamWatchx = 0, - DispRamWatchy = 70, - - MessagesColor = -1, - AlertMessageColor = -65536, - LastInputColor = -23296, - MovieInput = -8355712, - - DispFPSanchor = 0, // 0 = UL, 1 = UR, 2 = DL, 3 = DR - DispFrameanchor = 0, - DispLaganchor = 0, - DispInpanchor = 0, - DispWatchAnchor = 0, - DispRecanchor = 0, - DispMultianchor = 1, - DispMessageanchor = 2, - DispAutoholdanchor = 1; - } - // Display options public bool DisplayFPS = false; public bool DisplayFrameCounter = false; @@ -291,39 +253,20 @@ namespace BizHawk.Client.Common public bool DispAutoPrescale = true; public int DispSpeedupFeatures = 2; - public int DispFPSx = DefaultMessageOptions.DispFPSx; - public int DispFPSy = DefaultMessageOptions.DispFPSy; - public int DispFrameCx = DefaultMessageOptions.DispFrameCx; - public int DispFrameCy = DefaultMessageOptions.DispFrameCy; - public int DispLagx = DefaultMessageOptions.DispLagx; - public int DispLagy = DefaultMessageOptions.DispLagy; - public int DispInpx = DefaultMessageOptions.DispInpx; - public int DispInpy = DefaultMessageOptions.DispInpy; - public int DispRecx = DefaultMessageOptions.DispRecx; - public int DispRecy = DefaultMessageOptions.DispRecy; - public int DispMultix = DefaultMessageOptions.DispMultix; - public int DispMultiy = DefaultMessageOptions.DispMultiy; - public int DispRamWatchx = DefaultMessageOptions.DispRamWatchx; - public int DispRamWatchy = DefaultMessageOptions.DispRamWatchy; - public int DispMessagex = DefaultMessageOptions.DispMessagex; - public int DispMessagey = DefaultMessageOptions.DispMessagey; - public int DispAutoholdx = DefaultMessageOptions.DispAutoholdx; - public int DispAutoholdy = DefaultMessageOptions.DispAutoholdy; + public MessagePosition Fps = DefaultMessagePositions.Fps.Clone(); + public MessagePosition FrameCounter = DefaultMessagePositions.FrameCounter.Clone(); + public MessagePosition LagCounter = DefaultMessagePositions.LagCounter.Clone(); + public MessagePosition InputDisplay = DefaultMessagePositions.InputDisplay.Clone(); + public MessagePosition ReRecordCounter = DefaultMessagePositions.ReRecordCounter.Clone(); + public MessagePosition MultitrackRecorder = DefaultMessagePositions.MultitrackRecorder.Clone(); + public MessagePosition Messages = DefaultMessagePositions.Messages.Clone(); + public MessagePosition Autohold = DefaultMessagePositions.Autohold.Clone(); + public MessagePosition RamWatches = DefaultMessagePositions.RamWatches.Clone(); - public int DispFPSanchor = DefaultMessageOptions.DispFPSanchor; // 0 = UL, 1 = UR, 2 = DL, 3 = DR - public int DispFrameanchor = DefaultMessageOptions.DispFrameanchor; - public int DispLaganchor = DefaultMessageOptions.DispLaganchor; - public int DispInpanchor = DefaultMessageOptions.DispInpanchor; - public int DispWatchesanchor = DefaultMessageOptions.DispWatchAnchor; - public int DispRecanchor = DefaultMessageOptions.DispRecanchor; - public int DispMultianchor = DefaultMessageOptions.DispMultianchor; - public int DispMessageanchor = DefaultMessageOptions.DispMessageanchor; - public int DispAutoholdanchor = DefaultMessageOptions.DispAutoholdanchor; - - public int MessagesColor = DefaultMessageOptions.MessagesColor; - public int AlertMessageColor = DefaultMessageOptions.AlertMessageColor; - public int LastInputColor = DefaultMessageOptions.LastInputColor; - public int MovieInput = DefaultMessageOptions.MovieInput; + public int MessagesColor = DefaultMessagePositions.MessagesColor; + public int AlertMessageColor = DefaultMessagePositions.AlertMessageColor; + public int LastInputColor = DefaultMessagePositions.LastInputColor; + public int MovieInput = DefaultMessagePositions.MovieInput; public int DispPrescale = 1; diff --git a/BizHawk.Client.Common/config/DefaultMessageOptions.cs b/BizHawk.Client.Common/config/DefaultMessageOptions.cs new file mode 100644 index 0000000000..0273e3d3bc --- /dev/null +++ b/BizHawk.Client.Common/config/DefaultMessageOptions.cs @@ -0,0 +1,56 @@ +namespace BizHawk.Client.Common +{ + public class MessagePosition + { + public int X { get; set; } + public int Y { get; set; } + public AnchorType Anchor { get; set; } + + public enum AnchorType + { + TopLeft = 0, + TopRight = 1, + BottomLeft = 2, + BottomRight = 3 + } + + public MessagePosition Clone() + { + return (MessagePosition)MemberwiseClone(); + } + } + + public static class MessageOptionExtensions + { + public static bool IsTop(this MessagePosition.AnchorType type) + { + return type == MessagePosition.AnchorType.TopLeft + || type == MessagePosition.AnchorType.TopRight; + } + + public static bool IsLeft(this MessagePosition.AnchorType type) + { + return type == MessagePosition.AnchorType.TopLeft + || type == MessagePosition.AnchorType.BottomLeft; + } + } + + public static class DefaultMessagePositions + { + public static MessagePosition Fps = new MessagePosition { X = 0, Y = 0 }; + public static MessagePosition FrameCounter = new MessagePosition { X = 0, Y = 14 }; + public static MessagePosition LagCounter = new MessagePosition { X = 0, Y = 42 }; + public static MessagePosition InputDisplay = new MessagePosition { X = 0, Y = 28 }; + public static MessagePosition ReRecordCounter = new MessagePosition { X = 0, Y = 56 }; + public static MessagePosition MultitrackRecorder = new MessagePosition { X = 0, Y = 14, Anchor = MessagePosition.AnchorType.TopRight }; + public static MessagePosition Messages = new MessagePosition { X = 0, Y = 0, Anchor = MessagePosition.AnchorType.BottomLeft }; + public static MessagePosition Autohold = new MessagePosition { X = 0, Y = 0, Anchor = MessagePosition.AnchorType.TopRight }; + public static MessagePosition RamWatches = new MessagePosition { X = 0, Y = 70 }; + + public const int + MessagesColor = -1, + AlertMessageColor = -65536, + LastInputColor = -23296, + MovieInput = -8355712; + } +} diff --git a/BizHawk.Client.Common/lua/LuaFunctionList.cs b/BizHawk.Client.Common/lua/LuaFunctionList.cs index 7d93144f9d..4983c3b783 100644 --- a/BizHawk.Client.Common/lua/LuaFunctionList.cs +++ b/BizHawk.Client.Common/lua/LuaFunctionList.cs @@ -37,7 +37,7 @@ namespace BizHawk.Client.Common } } - public void ClearAll() + public new void Clear() { if (Global.Emulator.InputCallbacksAvailable()) { @@ -50,7 +50,7 @@ namespace BizHawk.Client.Common memoryCallbacks.RemoveAll(this.Select(w => w.MemCallback)); } - Clear(); + base.Clear(); } } diff --git a/BizHawk.Client.Common/movie/MovieSession.cs b/BizHawk.Client.Common/movie/MovieSession.cs index ea24c43fad..68b061b7e9 100644 --- a/BizHawk.Client.Common/movie/MovieSession.cs +++ b/BizHawk.Client.Common/movie/MovieSession.cs @@ -64,7 +64,7 @@ namespace BizHawk.Client.Common { get { - if (Movie.IsActive && !Movie.IsFinished && Global.Emulator.Frame > 0) + if (Movie.IsPlayingOrRecording() && Global.Emulator.Frame > 0) { return Movie.GetInputState(Global.Emulator.Frame - 1); } @@ -77,7 +77,7 @@ namespace BizHawk.Client.Common { get { - if (Movie.IsActive && !Movie.IsFinished && Global.Emulator.Frame > 1) + if (Movie.IsPlayingOrRecording() && Global.Emulator.Frame > 1) { return Movie.GetInputState(Global.Emulator.Frame - 2); } @@ -170,18 +170,18 @@ namespace BizHawk.Client.Common public void StopMovie(bool saveChanges = true) { var message = "Movie "; - if (Movie.IsRecording) + if (Movie.IsRecording()) { message += "recording "; } - else if (Movie.IsPlaying) + else if (Movie.IsPlaying()) { message += "playback "; } message += "stopped."; - if (Movie.IsActive) + if (Movie.IsActive()) { var result = Movie.Stop(saveChanges); if (result) @@ -199,7 +199,7 @@ namespace BizHawk.Client.Common public void HandleMovieSaveState(TextWriter writer) { - if (Movie.IsActive) + if (Movie.IsActive()) { Movie.WriteInputLog(writer); } @@ -207,7 +207,7 @@ namespace BizHawk.Client.Common public void ClearFrame() { - if (Movie.IsPlaying) + if (Movie.IsPlaying()) { Movie.ClearFrame(Global.Emulator.Frame); Output($"Scrubbed input at frame {Global.Emulator.Frame}"); @@ -216,11 +216,11 @@ namespace BizHawk.Client.Common public void HandleMovieOnFrameLoop() { - if (!Movie.IsActive) + if (!Movie.IsActive()) { LatchInputFromPlayer(Global.MovieInputSourceAdapter); } - else if (Movie.IsFinished) + else if (Movie.IsFinished()) { if (Global.Emulator.Frame < Movie.FrameCount) // This scenario can happen from rewinding (suddenly we are back in the movie, so hook back up to the movie { @@ -232,18 +232,18 @@ namespace BizHawk.Client.Common LatchInputFromPlayer(Global.MovieInputSourceAdapter); } } - else if (Movie.IsPlaying) + else if (Movie.IsPlaying()) { LatchInputFromLog(); - if (Movie.IsRecording) // The movie end situation can cause the switch to record mode, in that case we need to capture some input for this frame + if (Movie.IsRecording()) // The movie end situation can cause the switch to record mode, in that case we need to capture some input for this frame { HandleFrameLoopForRecordMode(); } else { // Movie may go into finished mode as a result from latching - if (!Movie.IsFinished) + if (!Movie.IsFinished()) { if (Global.ClientControls.IsPressed("Scrub Input")) { @@ -269,7 +269,7 @@ namespace BizHawk.Client.Common } } } - else if (Movie.IsRecording) + else if (Movie.IsRecording()) { HandleFrameLoopForRecordMode(); } @@ -278,7 +278,7 @@ namespace BizHawk.Client.Common private void HandleFrameLoopForRecordMode() { // we don't want TasMovie to latch user input outside its internal recording mode, so limit it to autohold - if (Movie is TasMovie && Movie.IsPlaying) + if (Movie is TasMovie && Movie.IsPlaying()) { MovieControllerAdapter.LatchSticky(); } @@ -304,12 +304,12 @@ namespace BizHawk.Client.Common if (Movie is TasMovie tasMovie) { tasMovie.GreenzoneCurrentFrame(); - if (tasMovie.IsPlaying && Global.Emulator.Frame >= tasMovie.InputLogLength) + if (tasMovie.IsPlaying() && Global.Emulator.Frame >= tasMovie.InputLogLength) { HandleFrameLoopForRecordMode(); } } - else if (Movie.IsPlaying && !Movie.IsFinished && Global.Emulator.Frame >= Movie.InputLogLength) + else if (Movie.Mode == MovieMode.Play && Global.Emulator.Frame >= Movie.InputLogLength) { HandlePlaybackEnd(); } @@ -324,7 +324,7 @@ namespace BizHawk.Client.Common // TODO: maybe someone who understands more about what's going on here could rename these step1 and step2 into something more descriptive public bool HandleMovieLoadState_HackyStep2(TextReader reader) { - if (!Movie.IsActive) + if (Movie.NotActive()) { return true; } @@ -361,7 +361,7 @@ namespace BizHawk.Client.Common public bool HandleMovieLoadState_HackyStep1(TextReader reader) { - if (!Movie.IsActive) + if (!Movie.IsActive()) { return true; } @@ -375,22 +375,22 @@ namespace BizHawk.Client.Common return false; } - if (Movie.IsRecording) + if (Movie.IsRecording()) { Movie.SwitchToPlay(); } - else if (Movie.IsFinished) + else if (Movie.IsFinished()) { LatchInputFromPlayer(Global.MovieInputSourceAdapter); } } else { - if (Movie.IsFinished) + if (Movie.IsFinished()) { Movie.StartNewRecording(); } - else if (Movie.IsPlaying) + else if (Movie.IsPlaying()) { Movie.SwitchToRecord(); } @@ -401,7 +401,7 @@ namespace BizHawk.Client.Common public void ToggleMultitrack() { - if (Movie.IsActive) + if (Movie.IsActive()) { if (Global.Config.VBAStyleMovieLoadState) { diff --git a/BizHawk.Client.Common/movie/bk2/Bk2Movie.InputLog.cs b/BizHawk.Client.Common/movie/bk2/Bk2Movie.InputLog.cs index da2d16a3ea..bcbbdfe705 100644 --- a/BizHawk.Client.Common/movie/bk2/Bk2Movie.InputLog.cs +++ b/BizHawk.Client.Common/movie/bk2/Bk2Movie.InputLog.cs @@ -176,7 +176,7 @@ namespace BizHawk.Client.Common Truncate(Log.Count); } - Mode = Moviemode.Finished; + Mode = MovieMode.Finished; } if (IsCountingRerecords) @@ -245,7 +245,7 @@ namespace BizHawk.Client.Common if (Log.Count < stateFrame) { - if (IsFinished) + if (this.IsFinished()) { return true; } @@ -267,18 +267,18 @@ namespace BizHawk.Client.Common if (stateFrame > newLog.Count) // stateFrame is greater than state input log, so movie finished mode { - if (Mode == Moviemode.Play || Mode == Moviemode.Finished) + if (Mode == MovieMode.Play || Mode == MovieMode.Finished) { - Mode = Moviemode.Finished; + Mode = MovieMode.Finished; return true; } return false; } - if (Mode == Moviemode.Finished) + if (Mode == MovieMode.Finished) { - Mode = Moviemode.Play; + Mode = MovieMode.Play; } return true; diff --git a/BizHawk.Client.Common/movie/bk2/Bk2Movie.ModeApi.cs b/BizHawk.Client.Common/movie/bk2/Bk2Movie.ModeApi.cs index 84ba6b80e0..76c6c706e7 100644 --- a/BizHawk.Client.Common/movie/bk2/Bk2Movie.ModeApi.cs +++ b/BizHawk.Client.Common/movie/bk2/Bk2Movie.ModeApi.cs @@ -4,24 +4,11 @@ namespace BizHawk.Client.Common { public partial class Bk2Movie { - protected enum Moviemode - { - Inactive, Play, Record, Finished - } - - protected Moviemode Mode { get; set; } = Moviemode.Inactive; - - public bool IsActive => Mode != Moviemode.Inactive; - - public bool IsPlaying => Mode == Moviemode.Play || Mode == Moviemode.Finished; - - public bool IsRecording => Mode == Moviemode.Record; - - public bool IsFinished => Mode == Moviemode.Finished; + public MovieMode Mode { get; protected set; } = MovieMode.Inactive; public virtual void StartNewRecording() { - Mode = Moviemode.Record; + Mode = MovieMode.Record; if (Global.Config.EnableBackupMovies && MakeBackup && Log.Any()) { SaveBackup(); @@ -33,17 +20,17 @@ namespace BizHawk.Client.Common public virtual void StartNewPlayback() { - Mode = Moviemode.Play; + Mode = MovieMode.Play; } public virtual void SwitchToRecord() { - Mode = Moviemode.Record; + Mode = MovieMode.Record; } public virtual void SwitchToPlay() { - Mode = Moviemode.Play; + Mode = MovieMode.Play; } public virtual bool Stop(bool saveChanges = true) @@ -51,7 +38,7 @@ namespace BizHawk.Client.Common bool saved = false; if (saveChanges) { - if (Mode == Moviemode.Record || (IsActive && Changes)) + if (Mode == MovieMode.Record || (this.IsActive() && Changes)) { Save(); saved = true; @@ -59,14 +46,14 @@ namespace BizHawk.Client.Common } Changes = false; - Mode = Moviemode.Inactive; + Mode = MovieMode.Inactive; return saved; } public void FinishedMode() { - Mode = Moviemode.Finished; + Mode = MovieMode.Finished; } } } diff --git a/BizHawk.Client.Common/movie/bk2/Bk2Movie.cs b/BizHawk.Client.Common/movie/bk2/Bk2Movie.cs index b207e150d1..5342a80a0d 100644 --- a/BizHawk.Client.Common/movie/bk2/Bk2Movie.cs +++ b/BizHawk.Client.Common/movie/bk2/Bk2Movie.cs @@ -23,7 +23,7 @@ namespace BizHawk.Client.Common Filename = ""; IsCountingRerecords = true; - Mode = Moviemode.Inactive; + Mode = MovieMode.Inactive; MakeBackup = true; Header[HeaderKeys.MOVIEVERSION] = "BizHawk v2.0.0"; diff --git a/BizHawk.Client.Common/movie/bkm/BkmControllerAdapter.cs b/BizHawk.Client.Common/movie/import/bkm/BkmControllerAdapter.cs similarity index 95% rename from BizHawk.Client.Common/movie/bkm/BkmControllerAdapter.cs rename to BizHawk.Client.Common/movie/import/bkm/BkmControllerAdapter.cs index 504db375b5..c729276ca5 100644 --- a/BizHawk.Client.Common/movie/bkm/BkmControllerAdapter.cs +++ b/BizHawk.Client.Common/movie/import/bkm/BkmControllerAdapter.cs @@ -1,632 +1,632 @@ -using System; - -using BizHawk.Common; -using BizHawk.Emulation.Common; - -namespace BizHawk.Client.Common -{ - internal class BkmControllerAdapter : IController - { - #region IController Implementation - - public ControllerDefinition Definition { get; set; } - - public bool IsPressed(string button) - { - return _myBoolButtons[button]; - } - - public float GetFloat(string name) - { - return _myFloatControls[name]; - } - - #endregion - - /// - /// latches all buttons from the supplied mnemonic string - /// - public void SetControllersAsMnemonic(string mnemonic) - { - if (ControlType == "Null Controller") - { - return; - } - - if (ControlType == "Lynx Controller") - { - SetLynxControllersAsMnemonic(mnemonic); - return; - } - - if (ControlType == "SNES Controller") - { - SetSNESControllersAsMnemonic(mnemonic); - return; - } - - if (ControlType == "Commodore 64 Controller") - { - SetC64ControllersAsMnemonic(mnemonic); - return; - } - - if (ControlType == "GBA Controller") - { - SetGBAControllersAsMnemonic(mnemonic); - return; - } - - if (ControlType == "Atari 7800 ProLine Joystick Controller") - { - SetAtari7800AsMnemonic(mnemonic); - return; - } - - if (ControlType == "Dual Gameboy Controller") - { - SetDualGameBoyControllerAsMnemonic(mnemonic); - return; - } - - if (ControlType == "WonderSwan Controller") - { - SetWonderSwanControllerAsMnemonic(mnemonic); - return; - } - - if (ControlType == "Nintendo 64 Controller") - { - SetN64ControllersAsMnemonic(mnemonic); - return; - } - - if (ControlType == "Saturn Controller") - { - SetSaturnControllersAsMnemonic(mnemonic); - return; - } - - if (ControlType == "PSP Controller") - { - // TODO - return; - } - - if (ControlType == "GPGX Genesis Controller") - { - if (IsGenesis6Button()) - { - SetGenesis6ControllersAsMnemonic(mnemonic); - } - else - { - SetGenesis3ControllersAsMnemonic(mnemonic); - } - - return; - } - - var c = new MnemonicChecker(mnemonic); - - _myBoolButtons.Clear(); - - int start = 3; - if (ControlType == "NES Controller") - { - if (mnemonic.Length < 2) - { - return; - } - else if (mnemonic[1] == 'P') - { - Force("Power", true); - } - else if (mnemonic[1] == 'E') - { - Force("FDS Eject", true); - } - else if (mnemonic[1] == '0') - { - Force("FDS Insert 0", true); - } - else if (mnemonic[1] == '1') - { - Force("FDS Insert 1", true); - } - else if (mnemonic[1] == '2') - { - Force("FDS Insert 2", true); - } - else if (mnemonic[1] == '3') - { - Force("FDS Insert 3", true); - } - else if (mnemonic[1] == 'c') - { - Force("VS Coin 1", true); - } - else if (mnemonic[1] == 'C') - { - Force("VS Coin 2", true); - } - else if (mnemonic[1] != '.') - { - Force("Reset", true); - } - } - - if (ControlType == "Gameboy Controller") - { - if (mnemonic.Length < 2) - { - return; - } - - Force("Power", mnemonic[1] != '.'); - } - - if (ControlType == "Genesis 3-Button Controller") - { - if (mnemonic.Length < 2) - { - return; - } - - Force("Reset", mnemonic[1] != '.'); - } - - if (ControlType == "SMS Controller" || ControlType == "TI83 Controller" || ControlType == "ColecoVision Basic Controller") - { - start = 1; - } - - if (ControlType == "Atari 2600 Basic Controller") - { - if (mnemonic.Length < 2) - { - return; - } - - Force("Reset", mnemonic[1] != '.' && mnemonic[1] != '0'); - Force("Select", mnemonic[2] != '.' && mnemonic[2] != '0'); - start = 4; - } - - for (int player = 1; player <= BkmMnemonicConstants.Players[ControlType]; player++) - { - int srcindex = (player - 1) * (BkmMnemonicConstants.Buttons[ControlType].Count + 1); - int ctr = start; - if (mnemonic.Length < srcindex + ctr + BkmMnemonicConstants.Buttons[ControlType].Count - 1) - { - return; - } - - string prefix = ""; - if (ControlType != "Gameboy Controller" && ControlType != "TI83 Controller") - { - prefix = $"P{player} "; - } - - foreach (string button in BkmMnemonicConstants.Buttons[ControlType].Keys) - { - Force(prefix + button, c[srcindex + ctr++]); - } - } - - if (ControlType == "SMS Controller") - { - int srcindex = BkmMnemonicConstants.Players[ControlType] * (BkmMnemonicConstants.Buttons[ControlType].Count + 1); - int ctr = start; - foreach (var command in BkmMnemonicConstants.Commands[ControlType].Keys) - { - Force(command, c[srcindex + ctr++]); - } - } - } - - private readonly WorkingDictionary _myBoolButtons = new WorkingDictionary(); - private readonly WorkingDictionary _myFloatControls = new WorkingDictionary(); - - private bool IsGenesis6Button() - { - return Definition.BoolButtons.Contains("P1 X"); - } - - private void Force(string button, bool state) - { - _myBoolButtons[button] = state; - } - - private void Force(string name, float state) - { - _myFloatControls[name] = state; - } - - private string ControlType => Definition.Name; - - private void SetGBAControllersAsMnemonic(string mnemonic) - { - MnemonicChecker c = new MnemonicChecker(mnemonic); - _myBoolButtons.Clear(); - if (mnemonic.Length < 2) - { - return; - } - - if (mnemonic[1] == 'P') - { - Force("Power", true); - } - - int start = 3; - foreach (string button in BkmMnemonicConstants.Buttons[ControlType].Keys) - { - Force(button, c[start++]); - } - } - - private void SetGenesis6ControllersAsMnemonic(string mnemonic) - { - MnemonicChecker c = new MnemonicChecker(mnemonic); - _myBoolButtons.Clear(); - - if (mnemonic.Length < 2) - { - return; - } - - if (mnemonic[1] == 'P') - { - Force("Power", true); - } - else if (mnemonic[1] != '.' && mnemonic[1] != '0') - { - Force("Reset", true); - } - - if (mnemonic.Length < 9) - { - return; - } - - for (int player = 1; player <= BkmMnemonicConstants.Players[ControlType]; player++) - { - int srcindex = (player - 1) * (BkmMnemonicConstants.Buttons[ControlType].Count + 1); - - if (mnemonic.Length < srcindex + 3 + BkmMnemonicConstants.Buttons[ControlType].Count - 1) - { - return; - } - - int start = 3; - foreach (string button in BkmMnemonicConstants.Buttons[ControlType].Keys) - { - Force($"P{player} {button}", c[srcindex + start++]); - } - } - } - - private void SetGenesis3ControllersAsMnemonic(string mnemonic) - { - MnemonicChecker c = new MnemonicChecker(mnemonic); - _myBoolButtons.Clear(); - - if (mnemonic.Length < 2) - { - return; - } - - if (mnemonic[1] == 'P') - { - Force("Power", true); - } - else if (mnemonic[1] != '.' && mnemonic[1] != '0') - { - Force("Reset", true); - } - - if (mnemonic.Length < 9) - { - return; - } - - for (int player = 1; player <= BkmMnemonicConstants.Players[ControlType]; player++) - { - int srcindex = (player - 1) * (BkmMnemonicConstants.Buttons["GPGX 3-Button Controller"].Count + 1); - - if (mnemonic.Length < srcindex + 3 + BkmMnemonicConstants.Buttons["GPGX 3-Button Controller"].Count - 1) - { - return; - } - - int start = 3; - foreach (string button in BkmMnemonicConstants.Buttons["GPGX 3-Button Controller"].Keys) - { - Force($"P{player} {button}", c[srcindex + start++]); - } - } - } - - private void SetSNESControllersAsMnemonic(string mnemonic) - { - var c = new MnemonicChecker(mnemonic); - _myBoolButtons.Clear(); - - if (mnemonic.Length < 2) - { - return; - } - - if (mnemonic[1] == 'P') - { - Force("Power", true); - } - else if (mnemonic[1] != '.' && mnemonic[1] != '0') - { - Force("Reset", true); - } - - for (int player = 1; player <= BkmMnemonicConstants.Players[ControlType]; player++) - { - int srcindex = (player - 1) * (BkmMnemonicConstants.Buttons[ControlType].Count + 1); - - if (mnemonic.Length < srcindex + 3 + BkmMnemonicConstants.Buttons[ControlType].Count - 1) - { - return; - } - - int start = 3; - foreach (var button in BkmMnemonicConstants.Buttons[ControlType].Keys) - { - Force($"P{player} {button}", c[srcindex + start++]); - } - } - } - - private void SetLynxControllersAsMnemonic(string mnemonic) - { - var c = new MnemonicChecker(mnemonic); - _myBoolButtons.Clear(); - - if (mnemonic.Length < 2) - { - return; - } - - if (mnemonic[1] == 'P') - { - Force("Power", true); - } - - for (int player = 1; player <= BkmMnemonicConstants.Players[ControlType]; player++) - { - int srcindex = (player - 1) * (BkmMnemonicConstants.Buttons[ControlType].Count + 1); - - if (mnemonic.Length < srcindex + 3 + BkmMnemonicConstants.Buttons[ControlType].Count - 1) - { - return; - } - - int start = 3; - foreach (var button in BkmMnemonicConstants.Buttons[ControlType].Keys) - { - Force(button, c[srcindex + start++]); - } - } - } - - private void SetN64ControllersAsMnemonic(string mnemonic) - { - MnemonicChecker c = new MnemonicChecker(mnemonic); - _myBoolButtons.Clear(); - - if (mnemonic.Length < 2) - { - return; - } - - if (mnemonic[1] == 'P') - { - Force("Power", true); - } - else if (mnemonic[1] != '.' && mnemonic[1] != '0') - { - Force("Reset", true); - } - - for (int player = 1; player <= BkmMnemonicConstants.Players[ControlType]; player++) - { - int srcindex = (player - 1) * (BkmMnemonicConstants.Buttons[ControlType].Count + (BkmMnemonicConstants.Analogs[ControlType].Count * 4) + 1 + 1); - - if (mnemonic.Length < srcindex + 3 + BkmMnemonicConstants.Buttons[ControlType].Count - 1) - { - return; - } - - int start = 3; - foreach (string button in BkmMnemonicConstants.Buttons[ControlType].Keys) - { - Force($"P{player} {button}", c[srcindex + start++]); - } - - foreach (string name in BkmMnemonicConstants.Analogs[ControlType].Keys) - { - Force($"P{player} {name}", int.Parse(mnemonic.Substring(srcindex + start, 4))); - start += 5; - } - } - } - - private void SetSaturnControllersAsMnemonic(string mnemonic) - { - MnemonicChecker c = new MnemonicChecker(mnemonic); - _myBoolButtons.Clear(); - - if (mnemonic.Length < 2) - { - return; - } - - if (mnemonic[1] == 'P') - { - Force("Power", true); - } - else if (mnemonic[1] != '.' && mnemonic[1] != '0') - { - Force("Reset", true); - } - - for (int player = 1; player <= BkmMnemonicConstants.Players[ControlType]; player++) - { - int srcindex = (player - 1) * (BkmMnemonicConstants.Buttons[ControlType].Count + 1); - - if (mnemonic.Length < srcindex + 3 + BkmMnemonicConstants.Buttons[ControlType].Count - 1) - { - return; - } - - int start = 3; - foreach (string button in BkmMnemonicConstants.Buttons[ControlType].Keys) - { - Force($"P{player} {button}", c[srcindex + start++]); - } - } - } - - private void SetAtari7800AsMnemonic(string mnemonic) - { - MnemonicChecker c = new MnemonicChecker(mnemonic); - _myBoolButtons.Clear(); - - if (mnemonic.Length < 5) - { - return; - } - - if (mnemonic[1] == 'P') - { - Force("Power", true); - } - - if (mnemonic[2] == 'r') - { - Force("Reset", true); - } - - if (mnemonic[3] == 's') - { - Force("Select", true); - } - - if (mnemonic[4] == 'p') - { - Force("Pause", true); - } - - for (int player = 1; player <= BkmMnemonicConstants.Players[ControlType]; player++) - { - int srcindex = (player - 1) * (BkmMnemonicConstants.Buttons[ControlType].Count + 1); - int start = 6; - if (mnemonic.Length < srcindex + start + BkmMnemonicConstants.Buttons[ControlType].Count) - { - return; - } - - foreach (string button in BkmMnemonicConstants.Buttons[ControlType].Keys) - { - Force($"P{player} {button}", c[srcindex + start++]); - } - } - } - - private void SetDualGameBoyControllerAsMnemonic(string mnemonic) - { - var checker = new MnemonicChecker(mnemonic); - _myBoolButtons.Clear(); - for (int i = 0; i < BkmMnemonicConstants.DgbMnemonic.Length; i++) - { - var t = BkmMnemonicConstants.DgbMnemonic[i]; - if (t.Item1 != null) - { - Force(t.Item1, checker[i]); - } - } - } - - private void SetWonderSwanControllerAsMnemonic(string mnemonic) - { - var checker = new MnemonicChecker(mnemonic); - _myBoolButtons.Clear(); - for (int i = 0; i < BkmMnemonicConstants.WsMnemonic.Length; i++) - { - var t = BkmMnemonicConstants.WsMnemonic[i]; - if (t.Item1 != null) - { - Force(t.Item1, checker[i]); - } - } - } - - private void SetC64ControllersAsMnemonic(string mnemonic) - { - var c = new MnemonicChecker(mnemonic); - _myBoolButtons.Clear(); - - for (int player = 1; player <= BkmMnemonicConstants.Players[ControlType]; player++) - { - int srcindex = (player - 1) * (BkmMnemonicConstants.Buttons[ControlType].Count + 1); - - if (mnemonic.Length < srcindex + 1 + BkmMnemonicConstants.Buttons[ControlType].Count - 1) - { - return; - } - - int start = 1; - foreach (var button in BkmMnemonicConstants.Buttons[ControlType].Keys) - { - Force($"P{player} {button}", c[srcindex + start++]); - } - } - - int startk = 13; - foreach (string button in BkmMnemonicConstants.Buttons["Commodore 64 Keyboard"].Keys) - { - Force(button, c[startk++]); - } - } - - private sealed class MnemonicChecker - { - private readonly string _mnemonic; - - public MnemonicChecker(string mnemonic) - { - _mnemonic = mnemonic; - } - - public bool this[int c] - { - get - { - if (string.IsNullOrEmpty(_mnemonic)) - { - return false; - } - - if (_mnemonic[c] == '.') - { - return false; - } - - if (_mnemonic[c] == '?') - { - return new Random((int)DateTime.Now.Ticks).Next(0, 10) > 5; - } - - return true; - } - } - } - } -} +using System; + +using BizHawk.Common; +using BizHawk.Emulation.Common; + +namespace BizHawk.Client.Common +{ + internal class BkmControllerAdapter : IController + { + #region IController Implementation + + public ControllerDefinition Definition { get; set; } + + public bool IsPressed(string button) + { + return _myBoolButtons[button]; + } + + public float GetFloat(string name) + { + return _myFloatControls[name]; + } + + #endregion + + /// + /// latches all buttons from the supplied mnemonic string + /// + public void SetControllersAsMnemonic(string mnemonic) + { + if (ControlType == "Null Controller") + { + return; + } + + if (ControlType == "Lynx Controller") + { + SetLynxControllersAsMnemonic(mnemonic); + return; + } + + if (ControlType == "SNES Controller") + { + SetSNESControllersAsMnemonic(mnemonic); + return; + } + + if (ControlType == "Commodore 64 Controller") + { + SetC64ControllersAsMnemonic(mnemonic); + return; + } + + if (ControlType == "GBA Controller") + { + SetGBAControllersAsMnemonic(mnemonic); + return; + } + + if (ControlType == "Atari 7800 ProLine Joystick Controller") + { + SetAtari7800AsMnemonic(mnemonic); + return; + } + + if (ControlType == "Dual Gameboy Controller") + { + SetDualGameBoyControllerAsMnemonic(mnemonic); + return; + } + + if (ControlType == "WonderSwan Controller") + { + SetWonderSwanControllerAsMnemonic(mnemonic); + return; + } + + if (ControlType == "Nintendo 64 Controller") + { + SetN64ControllersAsMnemonic(mnemonic); + return; + } + + if (ControlType == "Saturn Controller") + { + SetSaturnControllersAsMnemonic(mnemonic); + return; + } + + if (ControlType == "PSP Controller") + { + // TODO + return; + } + + if (ControlType == "GPGX Genesis Controller") + { + if (IsGenesis6Button()) + { + SetGenesis6ControllersAsMnemonic(mnemonic); + } + else + { + SetGenesis3ControllersAsMnemonic(mnemonic); + } + + return; + } + + var c = new MnemonicChecker(mnemonic); + + _myBoolButtons.Clear(); + + int start = 3; + if (ControlType == "NES Controller") + { + if (mnemonic.Length < 2) + { + return; + } + else if (mnemonic[1] == 'P') + { + Force("Power", true); + } + else if (mnemonic[1] == 'E') + { + Force("FDS Eject", true); + } + else if (mnemonic[1] == '0') + { + Force("FDS Insert 0", true); + } + else if (mnemonic[1] == '1') + { + Force("FDS Insert 1", true); + } + else if (mnemonic[1] == '2') + { + Force("FDS Insert 2", true); + } + else if (mnemonic[1] == '3') + { + Force("FDS Insert 3", true); + } + else if (mnemonic[1] == 'c') + { + Force("VS Coin 1", true); + } + else if (mnemonic[1] == 'C') + { + Force("VS Coin 2", true); + } + else if (mnemonic[1] != '.') + { + Force("Reset", true); + } + } + + if (ControlType == "Gameboy Controller") + { + if (mnemonic.Length < 2) + { + return; + } + + Force("Power", mnemonic[1] != '.'); + } + + if (ControlType == "Genesis 3-Button Controller") + { + if (mnemonic.Length < 2) + { + return; + } + + Force("Reset", mnemonic[1] != '.'); + } + + if (ControlType == "SMS Controller" || ControlType == "TI83 Controller" || ControlType == "ColecoVision Basic Controller") + { + start = 1; + } + + if (ControlType == "Atari 2600 Basic Controller") + { + if (mnemonic.Length < 2) + { + return; + } + + Force("Reset", mnemonic[1] != '.' && mnemonic[1] != '0'); + Force("Select", mnemonic[2] != '.' && mnemonic[2] != '0'); + start = 4; + } + + for (int player = 1; player <= BkmMnemonicConstants.Players[ControlType]; player++) + { + int srcindex = (player - 1) * (BkmMnemonicConstants.Buttons[ControlType].Count + 1); + int ctr = start; + if (mnemonic.Length < srcindex + ctr + BkmMnemonicConstants.Buttons[ControlType].Count - 1) + { + return; + } + + string prefix = ""; + if (ControlType != "Gameboy Controller" && ControlType != "TI83 Controller") + { + prefix = $"P{player} "; + } + + foreach (string button in BkmMnemonicConstants.Buttons[ControlType].Keys) + { + Force(prefix + button, c[srcindex + ctr++]); + } + } + + if (ControlType == "SMS Controller") + { + int srcindex = BkmMnemonicConstants.Players[ControlType] * (BkmMnemonicConstants.Buttons[ControlType].Count + 1); + int ctr = start; + foreach (var command in BkmMnemonicConstants.Commands[ControlType].Keys) + { + Force(command, c[srcindex + ctr++]); + } + } + } + + private readonly WorkingDictionary _myBoolButtons = new WorkingDictionary(); + private readonly WorkingDictionary _myFloatControls = new WorkingDictionary(); + + private bool IsGenesis6Button() + { + return Definition.BoolButtons.Contains("P1 X"); + } + + private void Force(string button, bool state) + { + _myBoolButtons[button] = state; + } + + private void Force(string name, float state) + { + _myFloatControls[name] = state; + } + + private string ControlType => Definition.Name; + + private void SetGBAControllersAsMnemonic(string mnemonic) + { + MnemonicChecker c = new MnemonicChecker(mnemonic); + _myBoolButtons.Clear(); + if (mnemonic.Length < 2) + { + return; + } + + if (mnemonic[1] == 'P') + { + Force("Power", true); + } + + int start = 3; + foreach (string button in BkmMnemonicConstants.Buttons[ControlType].Keys) + { + Force(button, c[start++]); + } + } + + private void SetGenesis6ControllersAsMnemonic(string mnemonic) + { + MnemonicChecker c = new MnemonicChecker(mnemonic); + _myBoolButtons.Clear(); + + if (mnemonic.Length < 2) + { + return; + } + + if (mnemonic[1] == 'P') + { + Force("Power", true); + } + else if (mnemonic[1] != '.' && mnemonic[1] != '0') + { + Force("Reset", true); + } + + if (mnemonic.Length < 9) + { + return; + } + + for (int player = 1; player <= BkmMnemonicConstants.Players[ControlType]; player++) + { + int srcindex = (player - 1) * (BkmMnemonicConstants.Buttons[ControlType].Count + 1); + + if (mnemonic.Length < srcindex + 3 + BkmMnemonicConstants.Buttons[ControlType].Count - 1) + { + return; + } + + int start = 3; + foreach (string button in BkmMnemonicConstants.Buttons[ControlType].Keys) + { + Force($"P{player} {button}", c[srcindex + start++]); + } + } + } + + private void SetGenesis3ControllersAsMnemonic(string mnemonic) + { + MnemonicChecker c = new MnemonicChecker(mnemonic); + _myBoolButtons.Clear(); + + if (mnemonic.Length < 2) + { + return; + } + + if (mnemonic[1] == 'P') + { + Force("Power", true); + } + else if (mnemonic[1] != '.' && mnemonic[1] != '0') + { + Force("Reset", true); + } + + if (mnemonic.Length < 9) + { + return; + } + + for (int player = 1; player <= BkmMnemonicConstants.Players[ControlType]; player++) + { + int srcindex = (player - 1) * (BkmMnemonicConstants.Buttons["GPGX 3-Button Controller"].Count + 1); + + if (mnemonic.Length < srcindex + 3 + BkmMnemonicConstants.Buttons["GPGX 3-Button Controller"].Count - 1) + { + return; + } + + int start = 3; + foreach (string button in BkmMnemonicConstants.Buttons["GPGX 3-Button Controller"].Keys) + { + Force($"P{player} {button}", c[srcindex + start++]); + } + } + } + + private void SetSNESControllersAsMnemonic(string mnemonic) + { + var c = new MnemonicChecker(mnemonic); + _myBoolButtons.Clear(); + + if (mnemonic.Length < 2) + { + return; + } + + if (mnemonic[1] == 'P') + { + Force("Power", true); + } + else if (mnemonic[1] != '.' && mnemonic[1] != '0') + { + Force("Reset", true); + } + + for (int player = 1; player <= BkmMnemonicConstants.Players[ControlType]; player++) + { + int srcindex = (player - 1) * (BkmMnemonicConstants.Buttons[ControlType].Count + 1); + + if (mnemonic.Length < srcindex + 3 + BkmMnemonicConstants.Buttons[ControlType].Count - 1) + { + return; + } + + int start = 3; + foreach (var button in BkmMnemonicConstants.Buttons[ControlType].Keys) + { + Force($"P{player} {button}", c[srcindex + start++]); + } + } + } + + private void SetLynxControllersAsMnemonic(string mnemonic) + { + var c = new MnemonicChecker(mnemonic); + _myBoolButtons.Clear(); + + if (mnemonic.Length < 2) + { + return; + } + + if (mnemonic[1] == 'P') + { + Force("Power", true); + } + + for (int player = 1; player <= BkmMnemonicConstants.Players[ControlType]; player++) + { + int srcindex = (player - 1) * (BkmMnemonicConstants.Buttons[ControlType].Count + 1); + + if (mnemonic.Length < srcindex + 3 + BkmMnemonicConstants.Buttons[ControlType].Count - 1) + { + return; + } + + int start = 3; + foreach (var button in BkmMnemonicConstants.Buttons[ControlType].Keys) + { + Force(button, c[srcindex + start++]); + } + } + } + + private void SetN64ControllersAsMnemonic(string mnemonic) + { + MnemonicChecker c = new MnemonicChecker(mnemonic); + _myBoolButtons.Clear(); + + if (mnemonic.Length < 2) + { + return; + } + + if (mnemonic[1] == 'P') + { + Force("Power", true); + } + else if (mnemonic[1] != '.' && mnemonic[1] != '0') + { + Force("Reset", true); + } + + for (int player = 1; player <= BkmMnemonicConstants.Players[ControlType]; player++) + { + int srcindex = (player - 1) * (BkmMnemonicConstants.Buttons[ControlType].Count + (BkmMnemonicConstants.Analogs[ControlType].Count * 4) + 1 + 1); + + if (mnemonic.Length < srcindex + 3 + BkmMnemonicConstants.Buttons[ControlType].Count - 1) + { + return; + } + + int start = 3; + foreach (string button in BkmMnemonicConstants.Buttons[ControlType].Keys) + { + Force($"P{player} {button}", c[srcindex + start++]); + } + + foreach (string name in BkmMnemonicConstants.Analogs[ControlType].Keys) + { + Force($"P{player} {name}", int.Parse(mnemonic.Substring(srcindex + start, 4))); + start += 5; + } + } + } + + private void SetSaturnControllersAsMnemonic(string mnemonic) + { + MnemonicChecker c = new MnemonicChecker(mnemonic); + _myBoolButtons.Clear(); + + if (mnemonic.Length < 2) + { + return; + } + + if (mnemonic[1] == 'P') + { + Force("Power", true); + } + else if (mnemonic[1] != '.' && mnemonic[1] != '0') + { + Force("Reset", true); + } + + for (int player = 1; player <= BkmMnemonicConstants.Players[ControlType]; player++) + { + int srcindex = (player - 1) * (BkmMnemonicConstants.Buttons[ControlType].Count + 1); + + if (mnemonic.Length < srcindex + 3 + BkmMnemonicConstants.Buttons[ControlType].Count - 1) + { + return; + } + + int start = 3; + foreach (string button in BkmMnemonicConstants.Buttons[ControlType].Keys) + { + Force($"P{player} {button}", c[srcindex + start++]); + } + } + } + + private void SetAtari7800AsMnemonic(string mnemonic) + { + MnemonicChecker c = new MnemonicChecker(mnemonic); + _myBoolButtons.Clear(); + + if (mnemonic.Length < 5) + { + return; + } + + if (mnemonic[1] == 'P') + { + Force("Power", true); + } + + if (mnemonic[2] == 'r') + { + Force("Reset", true); + } + + if (mnemonic[3] == 's') + { + Force("Select", true); + } + + if (mnemonic[4] == 'p') + { + Force("Pause", true); + } + + for (int player = 1; player <= BkmMnemonicConstants.Players[ControlType]; player++) + { + int srcindex = (player - 1) * (BkmMnemonicConstants.Buttons[ControlType].Count + 1); + int start = 6; + if (mnemonic.Length < srcindex + start + BkmMnemonicConstants.Buttons[ControlType].Count) + { + return; + } + + foreach (string button in BkmMnemonicConstants.Buttons[ControlType].Keys) + { + Force($"P{player} {button}", c[srcindex + start++]); + } + } + } + + private void SetDualGameBoyControllerAsMnemonic(string mnemonic) + { + var checker = new MnemonicChecker(mnemonic); + _myBoolButtons.Clear(); + for (int i = 0; i < BkmMnemonicConstants.DgbMnemonic.Length; i++) + { + var t = BkmMnemonicConstants.DgbMnemonic[i]; + if (t.Item1 != null) + { + Force(t.Item1, checker[i]); + } + } + } + + private void SetWonderSwanControllerAsMnemonic(string mnemonic) + { + var checker = new MnemonicChecker(mnemonic); + _myBoolButtons.Clear(); + for (int i = 0; i < BkmMnemonicConstants.WsMnemonic.Length; i++) + { + var t = BkmMnemonicConstants.WsMnemonic[i]; + if (t.Item1 != null) + { + Force(t.Item1, checker[i]); + } + } + } + + private void SetC64ControllersAsMnemonic(string mnemonic) + { + var c = new MnemonicChecker(mnemonic); + _myBoolButtons.Clear(); + + for (int player = 1; player <= BkmMnemonicConstants.Players[ControlType]; player++) + { + int srcindex = (player - 1) * (BkmMnemonicConstants.Buttons[ControlType].Count + 1); + + if (mnemonic.Length < srcindex + 1 + BkmMnemonicConstants.Buttons[ControlType].Count - 1) + { + return; + } + + int start = 1; + foreach (var button in BkmMnemonicConstants.Buttons[ControlType].Keys) + { + Force($"P{player} {button}", c[srcindex + start++]); + } + } + + int startk = 13; + foreach (string button in BkmMnemonicConstants.Buttons["Commodore 64 Keyboard"].Keys) + { + Force(button, c[startk++]); + } + } + + private sealed class MnemonicChecker + { + private readonly string _mnemonic; + + public MnemonicChecker(string mnemonic) + { + _mnemonic = mnemonic; + } + + public bool this[int c] + { + get + { + if (string.IsNullOrEmpty(_mnemonic)) + { + return false; + } + + if (_mnemonic[c] == '.') + { + return false; + } + + if (_mnemonic[c] == '?') + { + return new Random((int)DateTime.Now.Ticks).Next(0, 10) > 5; + } + + return true; + } + } + } + } +} diff --git a/BizHawk.Client.Common/movie/bkm/BkmHeader.cs b/BizHawk.Client.Common/movie/import/bkm/BkmHeader.cs similarity index 94% rename from BizHawk.Client.Common/movie/bkm/BkmHeader.cs rename to BizHawk.Client.Common/movie/import/bkm/BkmHeader.cs index 40afd68d62..001fdf65bb 100644 --- a/BizHawk.Client.Common/movie/bkm/BkmHeader.cs +++ b/BizHawk.Client.Common/movie/import/bkm/BkmHeader.cs @@ -1,118 +1,118 @@ -using System.Collections.Generic; -using System.Text; - -namespace BizHawk.Client.Common -{ - internal class BkmHeader : Dictionary - { - public BkmHeader() - { - Comments = new List(); - Subtitles = new SubtitleList(); - - this[HeaderKeys.EMULATIONVERSION] = VersionInfo.GetEmuVersion(); - this[HeaderKeys.PLATFORM] = Global.Emulator != null ? Global.Emulator.SystemId : ""; - this[HeaderKeys.GAMENAME] = ""; - this[HeaderKeys.AUTHOR] = ""; - this[HeaderKeys.RERECORDS] = "0"; - } - - public List Comments { get; } - public SubtitleList Subtitles { get; } - - public string SavestateBinaryBase64Blob - { - get - { - if (ContainsKey(HeaderKeys.SAVESTATEBINARYBASE64BLOB)) - { - return this[HeaderKeys.SAVESTATEBINARYBASE64BLOB]; - } - - return null; - } - - set - { - if (value == null) - { - Remove(HeaderKeys.SAVESTATEBINARYBASE64BLOB); - } - else - { - Add(HeaderKeys.SAVESTATEBINARYBASE64BLOB, value); - } - } - } - - public new string this[string key] - { - get => ContainsKey(key) ? base[key] : ""; - - set - { - if (ContainsKey(key)) - { - base[key] = value; - } - else - { - Add(key, value); - } - } - } - - public new void Clear() - { - Comments.Clear(); - Subtitles.Clear(); - base.Clear(); - } - - public override string ToString() - { - var sb = new StringBuilder(); - - foreach (var kvp in this) - { - sb - .Append(kvp.Key) - .Append(' ') - .Append(kvp.Value) - .AppendLine(); - } - - sb.Append(Subtitles); - Comments.ForEach(comment => sb.AppendLine(comment)); - - return sb.ToString(); - } - - public bool ParseLineFromFile(string line) - { - if (!string.IsNullOrWhiteSpace(line)) - { - var splitLine = line.Split(new[] { ' ' }, 2); - - if (HeaderKeys.Contains(splitLine[0]) && !ContainsKey(splitLine[0])) - { - Add(splitLine[0], splitLine[1]); - } - else if (line.StartsWith("subtitle") || line.StartsWith("sub")) - { - Subtitles.AddFromString(line); - } - else if (line.StartsWith("comment")) - { - Comments.Add(line.Substring(8, line.Length - 8)); - } - else if (line.StartsWith("|")) - { - return false; - } - } - - return true; - } - } -} +using System.Collections.Generic; +using System.Text; + +namespace BizHawk.Client.Common +{ + internal class BkmHeader : Dictionary + { + public BkmHeader() + { + Comments = new List(); + Subtitles = new SubtitleList(); + + this[HeaderKeys.EMULATIONVERSION] = VersionInfo.GetEmuVersion(); + this[HeaderKeys.PLATFORM] = Global.Emulator != null ? Global.Emulator.SystemId : ""; + this[HeaderKeys.GAMENAME] = ""; + this[HeaderKeys.AUTHOR] = ""; + this[HeaderKeys.RERECORDS] = "0"; + } + + public List Comments { get; } + public SubtitleList Subtitles { get; } + + public string SavestateBinaryBase64Blob + { + get + { + if (ContainsKey(HeaderKeys.SAVESTATEBINARYBASE64BLOB)) + { + return this[HeaderKeys.SAVESTATEBINARYBASE64BLOB]; + } + + return null; + } + + set + { + if (value == null) + { + Remove(HeaderKeys.SAVESTATEBINARYBASE64BLOB); + } + else + { + Add(HeaderKeys.SAVESTATEBINARYBASE64BLOB, value); + } + } + } + + public new string this[string key] + { + get => ContainsKey(key) ? base[key] : ""; + + set + { + if (ContainsKey(key)) + { + base[key] = value; + } + else + { + Add(key, value); + } + } + } + + public new void Clear() + { + Comments.Clear(); + Subtitles.Clear(); + base.Clear(); + } + + public override string ToString() + { + var sb = new StringBuilder(); + + foreach (var kvp in this) + { + sb + .Append(kvp.Key) + .Append(' ') + .Append(kvp.Value) + .AppendLine(); + } + + sb.Append(Subtitles); + Comments.ForEach(comment => sb.AppendLine(comment)); + + return sb.ToString(); + } + + public bool ParseLineFromFile(string line) + { + if (!string.IsNullOrWhiteSpace(line)) + { + var splitLine = line.Split(new[] { ' ' }, 2); + + if (HeaderKeys.Contains(splitLine[0]) && !ContainsKey(splitLine[0])) + { + Add(splitLine[0], splitLine[1]); + } + else if (line.StartsWith("subtitle") || line.StartsWith("sub")) + { + Subtitles.AddFromString(line); + } + else if (line.StartsWith("comment")) + { + Comments.Add(line.Substring(8, line.Length - 8)); + } + else if (line.StartsWith("|")) + { + return false; + } + } + + return true; + } + } +} diff --git a/BizHawk.Client.Common/movie/bkm/BkmMnemonicConstants.cs b/BizHawk.Client.Common/movie/import/bkm/BkmMnemonicConstants.cs similarity index 97% rename from BizHawk.Client.Common/movie/bkm/BkmMnemonicConstants.cs rename to BizHawk.Client.Common/movie/import/bkm/BkmMnemonicConstants.cs index 24c28b26a6..8336d2ec98 100644 --- a/BizHawk.Client.Common/movie/bkm/BkmMnemonicConstants.cs +++ b/BizHawk.Client.Common/movie/import/bkm/BkmMnemonicConstants.cs @@ -1,237 +1,237 @@ -using System; -using System.Collections.Generic; - -namespace BizHawk.Client.Common -{ - internal static class BkmMnemonicConstants - { - public static readonly Dictionary> Buttons = new Dictionary> - { - { - "Gameboy Controller", new Dictionary - { - { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "Select", "s" }, { "Start", "S" }, { "B", "B" }, { "A", "A" } - } - }, - { - "Lynx Controller", new Dictionary - { - { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "Select", "s" }, { "Start", "S" }, { "B", "B" }, { "A", "A" } - } - }, - { - "GBA Controller", new Dictionary - { - { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "Select", "s" }, { "Start", "S" }, { "B", "B" }, - { "A", "A" }, { "L", "L" }, { "R", "R" } - } - }, - { - "Genesis 3-Button Controller", new Dictionary - { - { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "Start", "S" }, { "A", "A" }, { "B", "B" }, - { "C", "C" } - } - }, - { - "GPGX Genesis Controller", new Dictionary - { - { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "A", "A" }, { "B", "B" }, { "C", "C" }, - { "Start", "S" }, { "X", "X" }, { "Y", "Y" }, { "Z", "Z" }, { "Mode", "M" } - } - }, - { - "GPGX 3-Button Controller", new Dictionary - { - { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "A", "A" }, { "B", "B" }, - { "C", "C" }, { "Start", "S" }, - } - }, - { - "NES Controller", new Dictionary - { - { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "Select", "s" }, { "Start", "S" }, { "B", "B" }, - { "A", "A" } - } - }, - { - "SNES Controller", new Dictionary - { - { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "Select", "s" }, { "Start", "S" }, { "B", "B" }, - { "A", "A" }, { "X", "X" }, { "Y", "Y" }, { "L", "L" }, { "R", "R" } - } - }, - { - "PC Engine Controller", new Dictionary - { - { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "Select", "s" }, { "Run", "r" }, { "B2", "2" }, - { "B1", "1" } - } - }, - { - "SMS Controller", new Dictionary - { - { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "B1", "1" }, { "B2", "2" } - } - }, - { - "TI83 Controller", new Dictionary - { - { "0", "0" }, { "1", "1" }, { "2", "2" }, { "3", "3" }, { "4", "4" }, { "5", "5" }, { "6", "6" }, { "7", "7" }, - { "8", "8" }, { "9", "9" }, { "DOT", "`" }, { "ON", "O" }, { "ENTER", "=" }, { "UP", "U" }, { "DOWN", "D" }, - { "LEFT", "L" }, { "RIGHT", "R" }, { "PLUS", "+" }, { "MINUS", "_" }, { "MULTIPLY", "*" }, { "DIVIDE", "/" }, - { "CLEAR", "c" }, { "EXP", "^" }, { "DASH", "-" }, { "PARAOPEN", "(" }, { "PARACLOSE", ")" }, { "TAN", "T" }, - { "VARS", "V" }, { "COS", "C" }, { "PRGM", "P" }, { "STAT", "s" }, { "MATRIX", "m" }, { "X", "X" }, { "STO", ">" }, - { "LN", "n" }, { "LOG", "L" }, { "SQUARED", "2" }, { "NEG1", "1" }, { "MATH", "H" }, { "ALPHA", "A" }, - { "GRAPH", "G" }, { "TRACE", "t" }, { "ZOOM", "Z" }, { "WINDOW", "W" }, { "Y", "Y" }, { "2ND", "&" }, { "MODE", "O" }, - { "DEL", "D" }, { "COMMA", "," }, { "SIN", "S" } - } - }, - { - "Atari 2600 Basic Controller", new Dictionary - { - { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "Button", "B" } - } - }, - { - "Atari 7800 ProLine Joystick Controller", new Dictionary - { - { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "Trigger", "1" }, { "Trigger 2", "2" } - } - }, - { - "Commodore 64 Controller", new Dictionary - { - { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "Button", "B" } - } - }, - { - "Commodore 64 Keyboard", new Dictionary - { - { "Key F1", "1" }, { "Key F3", "3" }, { "Key F5", "5" }, { "Key F7", "7" }, - { "Key Left Arrow", "l" }, { "Key 1", "1" }, { "Key 2", "2" }, { "Key 3", "3" }, { "Key 4", "4" }, { "Key 5", "5" }, { "Key 6", "6" }, { "Key 7", "7" }, { "Key 8", "8" }, { "Key 9", "9" }, { "Key 0", "0" }, { "Key Plus", "+" }, { "Key Minus", "-" }, { "Key Pound", "l" }, { "Key Clear/Home", "c" }, { "Key Insert/Delete", "i" }, - { "Key Control", "c" }, { "Key Q", "Q" }, { "Key W", "W" }, { "Key E", "E" }, { "Key R", "R" }, { "Key T", "T" }, { "Key Y", "Y" }, { "Key U", "U" }, { "Key I", "I" }, { "Key O", "O" }, { "Key P", "P" }, { "Key At", "@" }, { "Key Asterisk", "*" }, { "Key Up Arrow", "u" }, { "Key Restore", "r" }, - { "Key Run/Stop", "s" }, { "Key Lck", "k" }, { "Key A", "A" }, { "Key S", "S" }, { "Key D", "D" }, { "Key F", "F" }, { "Key G", "G" }, { "Key H", "H" }, { "Key J", "J" }, { "Key K", "K" }, { "Key L", "L" }, { "Key Colon", ":" }, { "Key Semicolon", ";" }, { "Key Equal", "=" }, { "Key Return", "e" }, - { "Key Commodore", "o" }, { "Key Left Shift", "s" }, { "Key Z", "Z" }, { "Key X", "X" }, { "Key C", "C" }, { "Key V", "V" }, { "Key B", "B" }, { "Key N", "N" }, { "Key M", "M" }, { "Key Comma", "," }, { "Key Period", ">" }, { "Key Slash", "/" }, { "Key Right Shift", "s" }, { "Key Cursor Up/Down", "u" }, { "Key Cursor Left/Right", "l" }, - { "Key Space", "_" } - } - }, - { - "ColecoVision Basic Controller", new Dictionary - { - { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "L", "l" }, { "R", "r" }, - { "Key1", "1" }, { "Key2", "2" }, { "Key3", "3" }, { "Key4", "4" }, { "Key5", "5" }, { "Key6", "6" }, - { "Key7", "7" }, { "Key8", "8" }, { "Key9", "9" }, { "Star", "*" }, { "Key0", "0" }, { "Pound", "#" } - } - }, - { - "Nintendo 64 Controller", new Dictionary - { - { "DPad U", "U" }, { "DPad D", "D" }, { "DPad L", "L" }, { "DPad R", "R" }, - { "B", "B" }, { "A", "A" }, { "Z", "Z" }, { "Start", "S" }, { "L", "L" }, { "R", "R" }, - { "C Up", "u" }, { "C Down", "d" }, { "C Left", "l" }, { "C Right", "r" } - } - }, - { - "Saturn Controller", new Dictionary - { - { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, - { "Start", "S" }, { "X", "X" }, { "Y", "Y" }, { "Z", "Z" }, { "A", "A" }, { "B", "B" }, { "C", "C" }, - { "L", "l" }, { "R", "r" }, - } - } - }; - - public static readonly Dictionary> Analogs = new Dictionary> - { - { "Nintendo 64 Controller", new Dictionary { { "X Axis", "X" }, { "Y Axis", "Y" } } } - }; - - public static readonly Dictionary> Commands = new Dictionary> - { - { "Atari 2600 Basic Controller", new Dictionary { { "Reset", "r" }, { "Select", "s" } } }, - { "Atari 7800 ProLine Joystick Controller", new Dictionary { { "Reset", "r" }, { "Select", "s" } } }, - { "Gameboy Controller", new Dictionary { { "Power", "P" } } }, - { "GBA Controller", new Dictionary { { "Power", "P" } } }, - { "Genesis 3-Button Controller", new Dictionary { { "Reset", "r" } } }, - { "GPGX Genesis Controller", new Dictionary { { "Power", "P" }, { "Reset", "r" } } }, - { "NES Controller", new Dictionary { { "Reset", "r" }, { "Power", "P" }, { "FDS Eject", "E" }, { "FDS Insert 0", "0" }, { "FDS Insert 1", "1" }, { "VS Coin 1", "c" }, { "VS Coin 2", "C" } } }, - { "SNES Controller", new Dictionary { { "Power", "P" }, { "Reset", "r" } } }, - { "PC Engine Controller", new Dictionary() }, - { "SMS Controller", new Dictionary { { "Pause", "p" }, { "Reset", "r" } } }, - { "TI83 Controller", new Dictionary() }, - { "Nintendo 64 Controller", new Dictionary { { "Power", "P" }, { "Reset", "r" } } }, - { "Saturn Controller", new Dictionary { { "Power", "P" }, { "Reset", "r" } } }, - { "GPGX 3-Button Controller", new Dictionary { { "Power", "P" }, { "Reset", "r" } } } - }; - - public static readonly Dictionary Players = new Dictionary - { - { "Gameboy Controller", 1 }, { "GBA Controller", 1 }, { "Genesis 3-Button Controller", 2 }, { "GPGX Genesis Controller", 2 }, { "NES Controller", 4 }, - { "SNES Controller", 4 }, { "PC Engine Controller", 5 }, { "SMS Controller", 2 }, { "TI83 Controller", 1 }, { "Atari 2600 Basic Controller", 2 }, { "Atari 7800 ProLine Joystick Controller", 2 }, - { "ColecoVision Basic Controller", 2 }, { "Commodore 64 Controller", 2 }, { "Nintendo 64 Controller", 4 }, { "Saturn Controller", 2 }, - { "GPGX 3-Button Controller", 2 }, { "Lynx Controller", 1 } - }; - - // just experimenting with different possibly more painful ways to handle mnemonics - // |P|UDLRsSBA| - public static readonly Tuple[] DgbMnemonic = - { - new Tuple(null, '|'), - new Tuple("P1 Power", 'P'), - new Tuple(null, '|'), - new Tuple("P1 Up", 'U'), - new Tuple("P1 Down", 'D'), - new Tuple("P1 Left", 'L'), - new Tuple("P1 Right", 'R'), - new Tuple("P1 Select", 's'), - new Tuple("P1 Start", 'S'), - new Tuple("P1 B", 'B'), - new Tuple("P1 A", 'A'), - new Tuple(null, '|'), - new Tuple("P2 Power", 'P'), - new Tuple(null, '|'), - new Tuple("P2 Up", 'U'), - new Tuple("P2 Down", 'D'), - new Tuple("P2 Left", 'L'), - new Tuple("P2 Right", 'R'), - new Tuple("P2 Select", 's'), - new Tuple("P2 Start", 'S'), - new Tuple("P2 B", 'B'), - new Tuple("P2 A", 'A'), - new Tuple(null, '|') - }; - - public static readonly Tuple[] WsMnemonic = - { - new Tuple(null, '|'), - new Tuple("P1 X1", '1'), - new Tuple("P1 X3", '3'), - new Tuple("P1 X4", '4'), - new Tuple("P1 X2", '2'), - new Tuple("P1 Y1", '1'), - new Tuple("P1 Y3", '3'), - new Tuple("P1 Y4", '4'), - new Tuple("P1 Y2", '2'), - new Tuple("P1 Start", 'S'), - new Tuple("P1 B", 'B'), - new Tuple("P1 A", 'A'), - new Tuple(null, '|'), - new Tuple("P2 X1", '1'), - new Tuple("P2 X3", '3'), - new Tuple("P2 X4", '4'), - new Tuple("P2 X2", '2'), - new Tuple("P2 Y1", '1'), - new Tuple("P2 Y3", '3'), - new Tuple("P2 Y4", '4'), - new Tuple("P2 Y2", '2'), - new Tuple("P2 Start", 'S'), - new Tuple("P2 B", 'B'), - new Tuple("P2 A", 'A'), - new Tuple(null, '|'), - new Tuple("Power", 'P'), - new Tuple("Rotate", 'R'), - new Tuple(null, '|') - }; - } -} +using System; +using System.Collections.Generic; + +namespace BizHawk.Client.Common +{ + internal static class BkmMnemonicConstants + { + public static readonly Dictionary> Buttons = new Dictionary> + { + { + "Gameboy Controller", new Dictionary + { + { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "Select", "s" }, { "Start", "S" }, { "B", "B" }, { "A", "A" } + } + }, + { + "Lynx Controller", new Dictionary + { + { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "Select", "s" }, { "Start", "S" }, { "B", "B" }, { "A", "A" } + } + }, + { + "GBA Controller", new Dictionary + { + { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "Select", "s" }, { "Start", "S" }, { "B", "B" }, + { "A", "A" }, { "L", "L" }, { "R", "R" } + } + }, + { + "Genesis 3-Button Controller", new Dictionary + { + { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "Start", "S" }, { "A", "A" }, { "B", "B" }, + { "C", "C" } + } + }, + { + "GPGX Genesis Controller", new Dictionary + { + { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "A", "A" }, { "B", "B" }, { "C", "C" }, + { "Start", "S" }, { "X", "X" }, { "Y", "Y" }, { "Z", "Z" }, { "Mode", "M" } + } + }, + { + "GPGX 3-Button Controller", new Dictionary + { + { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "A", "A" }, { "B", "B" }, + { "C", "C" }, { "Start", "S" }, + } + }, + { + "NES Controller", new Dictionary + { + { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "Select", "s" }, { "Start", "S" }, { "B", "B" }, + { "A", "A" } + } + }, + { + "SNES Controller", new Dictionary + { + { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "Select", "s" }, { "Start", "S" }, { "B", "B" }, + { "A", "A" }, { "X", "X" }, { "Y", "Y" }, { "L", "L" }, { "R", "R" } + } + }, + { + "PC Engine Controller", new Dictionary + { + { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "Select", "s" }, { "Run", "r" }, { "B2", "2" }, + { "B1", "1" } + } + }, + { + "SMS Controller", new Dictionary + { + { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "B1", "1" }, { "B2", "2" } + } + }, + { + "TI83 Controller", new Dictionary + { + { "0", "0" }, { "1", "1" }, { "2", "2" }, { "3", "3" }, { "4", "4" }, { "5", "5" }, { "6", "6" }, { "7", "7" }, + { "8", "8" }, { "9", "9" }, { "DOT", "`" }, { "ON", "O" }, { "ENTER", "=" }, { "UP", "U" }, { "DOWN", "D" }, + { "LEFT", "L" }, { "RIGHT", "R" }, { "PLUS", "+" }, { "MINUS", "_" }, { "MULTIPLY", "*" }, { "DIVIDE", "/" }, + { "CLEAR", "c" }, { "EXP", "^" }, { "DASH", "-" }, { "PARAOPEN", "(" }, { "PARACLOSE", ")" }, { "TAN", "T" }, + { "VARS", "V" }, { "COS", "C" }, { "PRGM", "P" }, { "STAT", "s" }, { "MATRIX", "m" }, { "X", "X" }, { "STO", ">" }, + { "LN", "n" }, { "LOG", "L" }, { "SQUARED", "2" }, { "NEG1", "1" }, { "MATH", "H" }, { "ALPHA", "A" }, + { "GRAPH", "G" }, { "TRACE", "t" }, { "ZOOM", "Z" }, { "WINDOW", "W" }, { "Y", "Y" }, { "2ND", "&" }, { "MODE", "O" }, + { "DEL", "D" }, { "COMMA", "," }, { "SIN", "S" } + } + }, + { + "Atari 2600 Basic Controller", new Dictionary + { + { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "Button", "B" } + } + }, + { + "Atari 7800 ProLine Joystick Controller", new Dictionary + { + { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "Trigger", "1" }, { "Trigger 2", "2" } + } + }, + { + "Commodore 64 Controller", new Dictionary + { + { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "Button", "B" } + } + }, + { + "Commodore 64 Keyboard", new Dictionary + { + { "Key F1", "1" }, { "Key F3", "3" }, { "Key F5", "5" }, { "Key F7", "7" }, + { "Key Left Arrow", "l" }, { "Key 1", "1" }, { "Key 2", "2" }, { "Key 3", "3" }, { "Key 4", "4" }, { "Key 5", "5" }, { "Key 6", "6" }, { "Key 7", "7" }, { "Key 8", "8" }, { "Key 9", "9" }, { "Key 0", "0" }, { "Key Plus", "+" }, { "Key Minus", "-" }, { "Key Pound", "l" }, { "Key Clear/Home", "c" }, { "Key Insert/Delete", "i" }, + { "Key Control", "c" }, { "Key Q", "Q" }, { "Key W", "W" }, { "Key E", "E" }, { "Key R", "R" }, { "Key T", "T" }, { "Key Y", "Y" }, { "Key U", "U" }, { "Key I", "I" }, { "Key O", "O" }, { "Key P", "P" }, { "Key At", "@" }, { "Key Asterisk", "*" }, { "Key Up Arrow", "u" }, { "Key Restore", "r" }, + { "Key Run/Stop", "s" }, { "Key Lck", "k" }, { "Key A", "A" }, { "Key S", "S" }, { "Key D", "D" }, { "Key F", "F" }, { "Key G", "G" }, { "Key H", "H" }, { "Key J", "J" }, { "Key K", "K" }, { "Key L", "L" }, { "Key Colon", ":" }, { "Key Semicolon", ";" }, { "Key Equal", "=" }, { "Key Return", "e" }, + { "Key Commodore", "o" }, { "Key Left Shift", "s" }, { "Key Z", "Z" }, { "Key X", "X" }, { "Key C", "C" }, { "Key V", "V" }, { "Key B", "B" }, { "Key N", "N" }, { "Key M", "M" }, { "Key Comma", "," }, { "Key Period", ">" }, { "Key Slash", "/" }, { "Key Right Shift", "s" }, { "Key Cursor Up/Down", "u" }, { "Key Cursor Left/Right", "l" }, + { "Key Space", "_" } + } + }, + { + "ColecoVision Basic Controller", new Dictionary + { + { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, { "L", "l" }, { "R", "r" }, + { "Key1", "1" }, { "Key2", "2" }, { "Key3", "3" }, { "Key4", "4" }, { "Key5", "5" }, { "Key6", "6" }, + { "Key7", "7" }, { "Key8", "8" }, { "Key9", "9" }, { "Star", "*" }, { "Key0", "0" }, { "Pound", "#" } + } + }, + { + "Nintendo 64 Controller", new Dictionary + { + { "DPad U", "U" }, { "DPad D", "D" }, { "DPad L", "L" }, { "DPad R", "R" }, + { "B", "B" }, { "A", "A" }, { "Z", "Z" }, { "Start", "S" }, { "L", "L" }, { "R", "R" }, + { "C Up", "u" }, { "C Down", "d" }, { "C Left", "l" }, { "C Right", "r" } + } + }, + { + "Saturn Controller", new Dictionary + { + { "Up", "U" }, { "Down", "D" }, { "Left", "L" }, { "Right", "R" }, + { "Start", "S" }, { "X", "X" }, { "Y", "Y" }, { "Z", "Z" }, { "A", "A" }, { "B", "B" }, { "C", "C" }, + { "L", "l" }, { "R", "r" }, + } + } + }; + + public static readonly Dictionary> Analogs = new Dictionary> + { + { "Nintendo 64 Controller", new Dictionary { { "X Axis", "X" }, { "Y Axis", "Y" } } } + }; + + public static readonly Dictionary> Commands = new Dictionary> + { + { "Atari 2600 Basic Controller", new Dictionary { { "Reset", "r" }, { "Select", "s" } } }, + { "Atari 7800 ProLine Joystick Controller", new Dictionary { { "Reset", "r" }, { "Select", "s" } } }, + { "Gameboy Controller", new Dictionary { { "Power", "P" } } }, + { "GBA Controller", new Dictionary { { "Power", "P" } } }, + { "Genesis 3-Button Controller", new Dictionary { { "Reset", "r" } } }, + { "GPGX Genesis Controller", new Dictionary { { "Power", "P" }, { "Reset", "r" } } }, + { "NES Controller", new Dictionary { { "Reset", "r" }, { "Power", "P" }, { "FDS Eject", "E" }, { "FDS Insert 0", "0" }, { "FDS Insert 1", "1" }, { "VS Coin 1", "c" }, { "VS Coin 2", "C" } } }, + { "SNES Controller", new Dictionary { { "Power", "P" }, { "Reset", "r" } } }, + { "PC Engine Controller", new Dictionary() }, + { "SMS Controller", new Dictionary { { "Pause", "p" }, { "Reset", "r" } } }, + { "TI83 Controller", new Dictionary() }, + { "Nintendo 64 Controller", new Dictionary { { "Power", "P" }, { "Reset", "r" } } }, + { "Saturn Controller", new Dictionary { { "Power", "P" }, { "Reset", "r" } } }, + { "GPGX 3-Button Controller", new Dictionary { { "Power", "P" }, { "Reset", "r" } } } + }; + + public static readonly Dictionary Players = new Dictionary + { + { "Gameboy Controller", 1 }, { "GBA Controller", 1 }, { "Genesis 3-Button Controller", 2 }, { "GPGX Genesis Controller", 2 }, { "NES Controller", 4 }, + { "SNES Controller", 4 }, { "PC Engine Controller", 5 }, { "SMS Controller", 2 }, { "TI83 Controller", 1 }, { "Atari 2600 Basic Controller", 2 }, { "Atari 7800 ProLine Joystick Controller", 2 }, + { "ColecoVision Basic Controller", 2 }, { "Commodore 64 Controller", 2 }, { "Nintendo 64 Controller", 4 }, { "Saturn Controller", 2 }, + { "GPGX 3-Button Controller", 2 }, { "Lynx Controller", 1 } + }; + + // just experimenting with different possibly more painful ways to handle mnemonics + // |P|UDLRsSBA| + public static readonly Tuple[] DgbMnemonic = + { + new Tuple(null, '|'), + new Tuple("P1 Power", 'P'), + new Tuple(null, '|'), + new Tuple("P1 Up", 'U'), + new Tuple("P1 Down", 'D'), + new Tuple("P1 Left", 'L'), + new Tuple("P1 Right", 'R'), + new Tuple("P1 Select", 's'), + new Tuple("P1 Start", 'S'), + new Tuple("P1 B", 'B'), + new Tuple("P1 A", 'A'), + new Tuple(null, '|'), + new Tuple("P2 Power", 'P'), + new Tuple(null, '|'), + new Tuple("P2 Up", 'U'), + new Tuple("P2 Down", 'D'), + new Tuple("P2 Left", 'L'), + new Tuple("P2 Right", 'R'), + new Tuple("P2 Select", 's'), + new Tuple("P2 Start", 'S'), + new Tuple("P2 B", 'B'), + new Tuple("P2 A", 'A'), + new Tuple(null, '|') + }; + + public static readonly Tuple[] WsMnemonic = + { + new Tuple(null, '|'), + new Tuple("P1 X1", '1'), + new Tuple("P1 X3", '3'), + new Tuple("P1 X4", '4'), + new Tuple("P1 X2", '2'), + new Tuple("P1 Y1", '1'), + new Tuple("P1 Y3", '3'), + new Tuple("P1 Y4", '4'), + new Tuple("P1 Y2", '2'), + new Tuple("P1 Start", 'S'), + new Tuple("P1 B", 'B'), + new Tuple("P1 A", 'A'), + new Tuple(null, '|'), + new Tuple("P2 X1", '1'), + new Tuple("P2 X3", '3'), + new Tuple("P2 X4", '4'), + new Tuple("P2 X2", '2'), + new Tuple("P2 Y1", '1'), + new Tuple("P2 Y3", '3'), + new Tuple("P2 Y4", '4'), + new Tuple("P2 Y2", '2'), + new Tuple("P2 Start", 'S'), + new Tuple("P2 B", 'B'), + new Tuple("P2 A", 'A'), + new Tuple(null, '|'), + new Tuple("Power", 'P'), + new Tuple("Rotate", 'R'), + new Tuple(null, '|') + }; + } +} diff --git a/BizHawk.Client.Common/movie/bkm/BkmMovie.cs b/BizHawk.Client.Common/movie/import/bkm/BkmMovie.cs similarity index 94% rename from BizHawk.Client.Common/movie/bkm/BkmMovie.cs rename to BizHawk.Client.Common/movie/import/bkm/BkmMovie.cs index 41d736fc14..185d403053 100644 --- a/BizHawk.Client.Common/movie/bkm/BkmMovie.cs +++ b/BizHawk.Client.Common/movie/import/bkm/BkmMovie.cs @@ -1,150 +1,150 @@ -using System; -using System.Collections.Generic; -using System.IO; - -namespace BizHawk.Client.Common -{ - internal class BkmMovie - { - private readonly List _log = new List(); - private int? _loopOffset; - - public BkmMovie() - { - Header = new BkmHeader { [HeaderKeys.MOVIEVERSION] = "BizHawk v0.0.1" }; - } - - public string PreferredExtension => "bkm"; - - public BkmHeader Header { get; } - public string Filename { get; set; } = ""; - public bool Loaded { get; private set; } - - public int InputLogLength => _log.Count; - - public double FrameCount - { - get - { - if (_loopOffset.HasValue) - { - return double.PositiveInfinity; - } - - if (Loaded) - { - return _log.Count; - } - - return 0; - } - } - - public BkmControllerAdapter GetInputState(int frame) - { - if (frame < FrameCount && frame >= 0) - { - int getFrame; - - if (_loopOffset.HasValue) - { - if (frame < _log.Count) - { - getFrame = frame; - } - else - { - getFrame = ((frame - _loopOffset.Value) % (_log.Count - _loopOffset.Value)) + _loopOffset.Value; - } - } - else - { - getFrame = frame; - } - - var adapter = new BkmControllerAdapter - { - Definition = Global.MovieSession.MovieControllerAdapter.Definition - }; - adapter.SetControllersAsMnemonic(_log[getFrame]); - return adapter; - } - - return null; - } - - public IDictionary HeaderEntries => Header; - - public SubtitleList Subtitles => Header.Subtitles; - - public IList Comments => Header.Comments; - - public string SyncSettingsJson - { - get => Header[HeaderKeys.SYNCSETTINGS]; - set => Header[HeaderKeys.SYNCSETTINGS] = value; - } - - public string TextSavestate { get; set; } - public byte[] BinarySavestate { get; set; } - - public bool Load() - { - var file = new FileInfo(Filename); - - if (file.Exists == false) - { - Loaded = false; - return false; - } - - Header.Clear(); - _log.Clear(); - - using (var sr = file.OpenText()) - { - string line; - - while ((line = sr.ReadLine()) != null) - { - if (line == "") - { - continue; - } - - if (line.Contains("LoopOffset")) - { - try - { - _loopOffset = int.Parse(line.Split(new[] { ' ' }, 2)[1]); - } - catch (Exception) - { - continue; - } - } - else if (Header.ParseLineFromFile(line)) - { - continue; - } - else if (line.StartsWith("|")) - { - _log.Add(line); - } - else - { - Header.Comments.Add(line); - } - } - } - - if (Header.SavestateBinaryBase64Blob != null) - { - BinarySavestate = Convert.FromBase64String(Header.SavestateBinaryBase64Blob); - } - - Loaded = true; - return true; - } - } +using System; +using System.Collections.Generic; +using System.IO; + +namespace BizHawk.Client.Common +{ + internal class BkmMovie + { + private readonly List _log = new List(); + private int? _loopOffset; + + public BkmMovie() + { + Header = new BkmHeader { [HeaderKeys.MOVIEVERSION] = "BizHawk v0.0.1" }; + } + + public string PreferredExtension => "bkm"; + + public BkmHeader Header { get; } + public string Filename { get; set; } = ""; + public bool Loaded { get; private set; } + + public int InputLogLength => _log.Count; + + public double FrameCount + { + get + { + if (_loopOffset.HasValue) + { + return double.PositiveInfinity; + } + + if (Loaded) + { + return _log.Count; + } + + return 0; + } + } + + public BkmControllerAdapter GetInputState(int frame) + { + if (frame < FrameCount && frame >= 0) + { + int getFrame; + + if (_loopOffset.HasValue) + { + if (frame < _log.Count) + { + getFrame = frame; + } + else + { + getFrame = ((frame - _loopOffset.Value) % (_log.Count - _loopOffset.Value)) + _loopOffset.Value; + } + } + else + { + getFrame = frame; + } + + var adapter = new BkmControllerAdapter + { + Definition = Global.MovieSession.MovieControllerAdapter.Definition + }; + adapter.SetControllersAsMnemonic(_log[getFrame]); + return adapter; + } + + return null; + } + + public IDictionary HeaderEntries => Header; + + public SubtitleList Subtitles => Header.Subtitles; + + public IList Comments => Header.Comments; + + public string SyncSettingsJson + { + get => Header[HeaderKeys.SYNCSETTINGS]; + set => Header[HeaderKeys.SYNCSETTINGS] = value; + } + + public string TextSavestate { get; set; } + public byte[] BinarySavestate { get; set; } + + public bool Load() + { + var file = new FileInfo(Filename); + + if (file.Exists == false) + { + Loaded = false; + return false; + } + + Header.Clear(); + _log.Clear(); + + using (var sr = file.OpenText()) + { + string line; + + while ((line = sr.ReadLine()) != null) + { + if (line == "") + { + continue; + } + + if (line.Contains("LoopOffset")) + { + try + { + _loopOffset = int.Parse(line.Split(new[] { ' ' }, 2)[1]); + } + catch (Exception) + { + continue; + } + } + else if (Header.ParseLineFromFile(line)) + { + continue; + } + else if (line.StartsWith("|")) + { + _log.Add(line); + } + else + { + Header.Comments.Add(line); + } + } + } + + if (Header.SavestateBinaryBase64Blob != null) + { + BinarySavestate = Convert.FromBase64String(Header.SavestateBinaryBase64Blob); + } + + Loaded = true; + return true; + } + } } \ No newline at end of file diff --git a/BizHawk.Client.Common/movie/interfaces/IMovie.cs b/BizHawk.Client.Common/movie/interfaces/IMovie.cs index d951ce2871..fe1f64190e 100644 --- a/BizHawk.Client.Common/movie/interfaces/IMovie.cs +++ b/BizHawk.Client.Common/movie/interfaces/IMovie.cs @@ -6,17 +6,42 @@ using BizHawk.Emulation.Common; namespace BizHawk.Client.Common { + public enum MovieMode + { + /// + /// There is no movie loaded + /// + Inactive, + + /// + /// The movie is in playback mode + /// + Play, + + /// + /// The movie is currently recording + /// + Record, + + /// + /// The movie has played past the end, but is still loaded in memory + /// + Finished + } + // TODO: message callback / event handler // TODO: consider other event handlers, switching modes? public interface IMovie { #region Status + /// + /// Gets the current movie mode + /// + MovieMode Mode { get; } + bool IsCountingRerecords { get; set; } - bool IsActive { get; } - bool IsPlaying { get; } - bool IsRecording { get; } - bool IsFinished { get; } + bool Changes { get; } #endregion @@ -218,4 +243,14 @@ namespace BizHawk.Client.Common #endregion } + + public static class MovieExtensions + { + public static bool IsActive(this IMovie movie) => movie.Mode != MovieMode.Inactive; + public static bool NotActive(this IMovie movie) => movie.Mode == MovieMode.Inactive; + public static bool IsPlaying(this IMovie movie) => movie.Mode == MovieMode.Play || movie.Mode == MovieMode.Finished; + public static bool IsRecording(this IMovie movie) => movie.Mode == MovieMode.Record; + public static bool IsFinished(this IMovie movie) => movie.Mode == MovieMode.Finished; + public static bool IsPlayingOrRecording(this IMovie movie) => movie.Mode == MovieMode.Play && movie.Mode == MovieMode.Record; + } } diff --git a/BizHawk.Client.Common/movie/tasproj/TasMovie.Editing.cs b/BizHawk.Client.Common/movie/tasproj/TasMovie.Editing.cs index 13396678f7..70fbd444af 100644 --- a/BizHawk.Client.Common/movie/tasproj/TasMovie.Editing.cs +++ b/BizHawk.Client.Common/movie/tasproj/TasMovie.Editing.cs @@ -22,7 +22,7 @@ namespace BizHawk.Client.Common TasLagLog.RemoveFrom(frame); TasLagLog[frame] = Global.Emulator.AsInputPollable().IsLagFrame; - if (IsRecording) + if (this.IsRecording()) { TasStateManager.Invalidate(frame + 1); } diff --git a/BizHawk.Client.Common/movie/tasproj/TasMovie.cs b/BizHawk.Client.Common/movie/tasproj/TasMovie.cs index bc6c11d08b..766ee99768 100644 --- a/BizHawk.Client.Common/movie/tasproj/TasMovie.cs +++ b/BizHawk.Client.Common/movie/tasproj/TasMovie.cs @@ -115,12 +115,12 @@ namespace BizHawk.Client.Common public override void SwitchToPlay() { - Mode = Moviemode.Play; + Mode = MovieMode.Play; } public override void SwitchToRecord() { - Mode = Moviemode.Record; + Mode = MovieMode.Record; } /// @@ -379,7 +379,7 @@ namespace BizHawk.Client.Common Truncate(Log.Count); } - Mode = Moviemode.Finished; + Mode = MovieMode.Finished; } if (IsCountingRerecords) diff --git a/BizHawk.Client.Common/rewind/Rewinder.cs b/BizHawk.Client.Common/rewind/Rewinder.cs index c1343f32a8..0122e875d1 100644 --- a/BizHawk.Client.Common/rewind/Rewinder.cs +++ b/BizHawk.Client.Common/rewind/Rewinder.cs @@ -313,7 +313,7 @@ namespace BizHawk.Client.Common // each one records how to get back to the previous state, once we've gone back to // the second item, it's already resulted in the first state being loaded. The // first item is just a junk entry with the initial value of _lastState (0 bytes). - if (_rewindBuffer.Count <= 1 || (Global.MovieSession.Movie.IsActive && Global.MovieSession.Movie.InputLogLength == 0)) + if (_rewindBuffer.Count <= 1 || (Global.MovieSession.Movie.IsActive() && Global.MovieSession.Movie.InputLogLength == 0)) { break; } diff --git a/BizHawk.Client.EmuHawk/Api/ApiManager.cs b/BizHawk.Client.EmuHawk/Api/ApiManager.cs index ea14bf4d1d..812fba4a8a 100644 --- a/BizHawk.Client.EmuHawk/Api/ApiManager.cs +++ b/BizHawk.Client.EmuHawk/Api/ApiManager.cs @@ -1,10 +1,8 @@ using System; using System.Collections.Generic; -using System.IO; using System.Linq; using System.Reflection; -using BizHawk.Common.ReflectionExtensions; using BizHawk.Emulation.Common; using BizHawk.Client.ApiHawk; using BizHawk.Client.Common; @@ -14,8 +12,8 @@ namespace BizHawk.Client.EmuHawk { public static class ApiManager { - private static ApiContainer container; - private static void Register(IEmulatorServiceProvider serviceProvider) + private static ApiContainer _container; + private static IExternalApiProvider Register(IEmulatorServiceProvider serviceProvider) { foreach (var api in Assembly.Load("BizHawk.Client.Common").GetTypes() .Concat(Assembly.Load("BizHawk.Client.ApiHawk").GetTypes()) @@ -26,14 +24,15 @@ namespace BizHawk.Client.EmuHawk ServiceInjector.UpdateServices(serviceProvider, instance); Libraries.Add(api, instance); } - container = new ApiContainer(Libraries); - GlobalWin.ApiProvider = new BasicApiProvider(container); + _container = new ApiContainer(Libraries); + return new BasicApiProvider(_container); } + private static readonly Dictionary Libraries = new Dictionary(); - public static void Restart(IEmulatorServiceProvider newServiceProvider) + public static IExternalApiProvider Restart(IEmulatorServiceProvider newServiceProvider) { Libraries.Clear(); - Register(newServiceProvider); + return Register(newServiceProvider); } } } diff --git a/BizHawk.Client.EmuHawk/Api/Libraries/GuiApi.cs b/BizHawk.Client.EmuHawk/Api/Libraries/GuiApi.cs index a8faff5cda..3a173faae0 100644 --- a/BizHawk.Client.EmuHawk/Api/Libraries/GuiApi.cs +++ b/BizHawk.Client.EmuHawk/Api/Libraries/GuiApi.cs @@ -491,7 +491,9 @@ namespace BizHawk.Client.EmuHawk x -= Emulator.CoreComm.ScreenLogicalOffsetX; y -= Emulator.CoreComm.ScreenLogicalOffsetY; } - GlobalWin.OSD.AddGuiText(message, x, y, Color.Black, forecolor ?? Color.White, a); + + var pos = new MessagePosition{ X = x, Y = y, Anchor = (MessagePosition.AnchorType)a }; + GlobalWin.OSD.AddGuiText(message, pos, Color.Black, forecolor ?? Color.White); } public void Dispose() diff --git a/BizHawk.Client.EmuHawk/BizHawk.Client.EmuHawk.csproj b/BizHawk.Client.EmuHawk/BizHawk.Client.EmuHawk.csproj index 380c3d3eab..c48c36cea5 100644 --- a/BizHawk.Client.EmuHawk/BizHawk.Client.EmuHawk.csproj +++ b/BizHawk.Client.EmuHawk/BizHawk.Client.EmuHawk.csproj @@ -717,12 +717,6 @@ SubtitleMaker.cs - - Form - - - NameStateForm.cs - Form @@ -1172,7 +1166,7 @@ TI83KeyPad.cs - + Form @@ -1682,10 +1676,6 @@ RecordMovie.cs - - NameStateForm.cs - Designer - OpenAdvancedChooser.cs diff --git a/BizHawk.Client.EmuHawk/CoreFeatureAnalysis.cs b/BizHawk.Client.EmuHawk/CoreFeatureAnalysis.cs index d85e925adb..17b59b0246 100644 --- a/BizHawk.Client.EmuHawk/CoreFeatureAnalysis.cs +++ b/BizHawk.Client.EmuHawk/CoreFeatureAnalysis.cs @@ -7,7 +7,6 @@ using System.Reflection; using BizHawk.Emulation.Common; using BizHawk.Emulation.Common.IEmulatorExtensions; -using BizHawk.Client.Common; namespace BizHawk.Client.EmuHawk { @@ -18,7 +17,6 @@ namespace BizHawk.Client.EmuHawk private class CoreInfo { public string CoreName { get; set; } - public string TypeName { get; set; } public bool Released { get; set; } public Dictionary Services { get; set; } public List NotApplicableTypes { get; set; } @@ -26,7 +24,6 @@ namespace BizHawk.Client.EmuHawk public CoreInfo() { } public CoreInfo(IEmulator emu) { - TypeName = emu.GetType().ToString(); CoreName = emu.Attributes().CoreName; Released = emu.Attributes().Released; Services = new Dictionary(); @@ -37,12 +34,12 @@ namespace BizHawk.Client.EmuHawk Services.Add(si.TypeName, si); } - var notapplicableAttr = ((ServiceNotApplicableAttribute)Attribute + var notApplicableAttribute = ((ServiceNotApplicableAttribute)Attribute .GetCustomAttribute(emu.GetType(), typeof(ServiceNotApplicableAttribute))); - if (notapplicableAttr != null) + if (notApplicableAttribute != null) { - NotApplicableTypes = notapplicableAttr.NotApplicableTypes + NotApplicableTypes = notApplicableAttribute.NotApplicableTypes .Select(x => x.ToString()) .ToList(); } @@ -60,23 +57,19 @@ namespace BizHawk.Client.EmuHawk public List Functions { get; set; } public ServiceInfo() { } - public ServiceInfo(Type servicetype, object service) + public ServiceInfo(Type serviceType, object service) { - if (servicetype.IsGenericType) - { - TypeName = servicetype.GetGenericTypeDefinition().ToString(); - } - else - { - TypeName = servicetype.ToString(); - } + TypeName = serviceType.IsGenericType + ? serviceType.GetGenericTypeDefinition().ToString() + : serviceType.ToString(); + Functions = new List(); - IEnumerable methods = servicetype.GetMethods(); // .Concat(servicetype.GetProperties().Select(p => p.GetGetMethod())); + IEnumerable methods = serviceType.GetMethods(); - if (servicetype.IsInterface) + if (serviceType.IsInterface) { - var map = service.GetType().GetInterfaceMap(servicetype); + var map = service.GetType().GetInterfaceMap(serviceType); // project interface methods to actual implementations methods = methods.Select( m => map.TargetMethods[Array.IndexOf(map.InterfaceMethods, m)]); @@ -115,8 +108,9 @@ namespace BizHawk.Client.EmuHawk #endregion + // ReSharper disable once UnusedAutoPropertyAccessor.Local [RequiredService] - IEmulator emu { get; set; } + IEmulator Emulator { get; set; } public CoreFeatureAnalysis() { @@ -124,11 +118,6 @@ namespace BizHawk.Client.EmuHawk KnownCores = new Dictionary(); } - private void OkBtn_Click(object sender, EventArgs e) - { - Close(); - } - public void NewUpdate(ToolFormUpdateType type) { } private TreeNode CreateCoreTree(CoreInfo ci) @@ -167,13 +156,13 @@ namespace BizHawk.Client.EmuHawk } - var knownServies = Assembly.GetAssembly(typeof(IEmulator)) + var knownServices = Assembly.GetAssembly(typeof(IEmulator)) .GetTypes() .Where(t => typeof(IEmulatorService).IsAssignableFrom(t)) .Where(t => t != typeof(IEmulatorService)) .Where(t => t.IsInterface); - var additionalServices = knownServies + var additionalServices = knownServices .Where(t => !ci.Services.ContainsKey(t.ToString())) .Where(t => !ci.NotApplicableTypes.Contains(t.ToString())) .Where(t => !typeof(ISpecializedEmulatorService).IsAssignableFrom(t)); // We don't want to show these as unimplemented, they aren't expected services @@ -215,7 +204,7 @@ namespace BizHawk.Client.EmuHawk CoreTree.ImageList.Images.Add("Bad", Properties.Resources.ExclamationRed); CoreTree.ImageList.Images.Add("Unknown", Properties.Resources.RetroQuestion); - var possiblecoretypes = + var possibleCoreTypes = Assembly .Load("BizHawk.Emulation.Cores") .GetTypes() @@ -229,7 +218,7 @@ namespace BizHawk.Client.EmuHawk .ThenBy(t => t.CoreAttributes.CoreName) .ToList(); - toolStripStatusLabel1.Text = $"Total: {possiblecoretypes.Count} Released: {KnownCores.Values.Count(c => c.Released)} Profiled: {KnownCores.Count}"; + toolStripStatusLabel1.Text = $"Total: {possibleCoreTypes.Count} Released: {KnownCores.Values.Count(c => c.Released)} Profiled: {KnownCores.Count}"; CoreTree.Nodes.Clear(); CoreTree.BeginUpdate(); @@ -245,7 +234,7 @@ namespace BizHawk.Client.EmuHawk CoreTree.Nodes.Add(coreNode); } - foreach (var t in possiblecoretypes) + foreach (var t in possibleCoreTypes) { if (!KnownCores.ContainsKey(t.CoreAttributes.CoreName)) { @@ -277,22 +266,16 @@ namespace BizHawk.Client.EmuHawk public void Restart() { - var ci = new CoreInfo(emu); + var ci = new CoreInfo(Emulator); KnownCores[ci.CoreName] = ci; DoCurrentCoreTree(ci); DoAllCoresTree(ci); } - public bool AskSaveChanges() - { - return true; - } + public bool AskSaveChanges() => true; - public bool UpdateBefore - { - get { return false; } - } + public bool UpdateBefore => false; #endregion } diff --git a/BizHawk.Client.EmuHawk/DisplayManager/DisplayManager.cs b/BizHawk.Client.EmuHawk/DisplayManager/DisplayManager.cs index cf8783c48d..1a5223cc0b 100644 --- a/BizHawk.Client.EmuHawk/DisplayManager/DisplayManager.cs +++ b/BizHawk.Client.EmuHawk/DisplayManager/DisplayManager.cs @@ -6,32 +6,39 @@ using System.IO; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; +using System.Windows.Forms; -using BizHawk.Emulation.Common; +using BizHawk.Bizware.BizwareGL; +using BizHawk.Bizware.BizwareGL.Drivers.SlimDX; +using BizHawk.Bizware.BizwareGL.Drivers.OpenTK; using BizHawk.Client.Common; using BizHawk.Client.EmuHawk.FilterManager; -using BizHawk.Bizware.BizwareGL; +using BizHawk.Emulation.Common; +using BizHawk.Emulation.Cores.Sony.PSX; using OpenTK; -using BizHawk.Bizware.BizwareGL.Drivers.SlimDX; -using BizHawk.Bizware.BizwareGL.Drivers.GdiPlus; namespace BizHawk.Client.EmuHawk { /// /// A DisplayManager is destined forevermore to drive the PresentationPanel it gets initialized with. - /// Its job is to receive OSD and emulator outputs, and produce one single buffer (BitampBuffer? Texture2d?) for display by the PresentationPanel. + /// Its job is to receive OSD and emulator outputs, and produce one single buffer (BitmapBuffer? Texture2d?) for display by the PresentationPanel. /// Details TBD /// public class DisplayManager : IDisposable { - class DisplayManagerRenderTargetProvider : IRenderTargetProvider + private class DisplayManagerRenderTargetProvider : IRenderTargetProvider { - public DisplayManagerRenderTargetProvider(Func callback) { Callback = callback; } - Func Callback; + private readonly Func _callback; + RenderTarget IRenderTargetProvider.Get(Size size) { - return Callback(size); + return _callback(size); + } + + public DisplayManagerRenderTargetProvider(Func callback) + { + _callback = callback; } } @@ -43,45 +50,63 @@ namespace BizHawk.Client.EmuHawk GraphicsControl = this.presentationPanel.GraphicsControl; CR_GraphicsControl = GLManager.GetContextForGraphicsControl(GraphicsControl); - //it's sort of important for these to be initialized to something nonzero + // it's sort of important for these to be initialized to something nonzero currEmuWidth = currEmuHeight = 1; Renderer = GL.CreateRenderer(); VideoTextureFrugalizer = new TextureFrugalizer(GL); - ShaderChainFrugalizers = new RenderTargetFrugalizer[16]; //hacky hardcoded limit.. need some other way to manage these + ShaderChainFrugalizers = new RenderTargetFrugalizer[16]; // hacky hardcoded limit.. need some other way to manage these for (int i = 0; i < 16; i++) { ShaderChainFrugalizers[i] = new RenderTargetFrugalizer(GL); } using (var xml = typeof(Program).Assembly.GetManifestResourceStream("BizHawk.Client.EmuHawk.Resources.courier16px.fnt")) - using (var tex = typeof(Program).Assembly.GetManifestResourceStream("BizHawk.Client.EmuHawk.Resources.courier16px_0.png")) + { + using var tex = typeof(Program).Assembly.GetManifestResourceStream("BizHawk.Client.EmuHawk.Resources.courier16px_0.png"); TheOneFont = new StringRenderer(GL, xml, tex); + } - using (var gens = typeof(Program).Assembly.GetManifestResourceStream("BizHawk.Client.EmuHawk.Resources.gens.ttf")) + using (var gens = + typeof(Program).Assembly.GetManifestResourceStream("BizHawk.Client.EmuHawk.Resources.gens.ttf")) + { LoadCustomFont(gens); - using (var fceux = typeof(Program).Assembly.GetManifestResourceStream("BizHawk.Client.EmuHawk.Resources.fceux.ttf")) - LoadCustomFont(fceux); + } - if (GL is BizHawk.Bizware.BizwareGL.Drivers.OpenTK.IGL_TK || GL is BizHawk.Bizware.BizwareGL.Drivers.SlimDX.IGL_SlimDX9) + using (var fceux = + typeof(Program).Assembly.GetManifestResourceStream("BizHawk.Client.EmuHawk.Resources.fceux.ttf")) + { + LoadCustomFont(fceux); + } + + if (GL is IGL_TK || GL is IGL_SlimDX9) { var fiHq2x = new FileInfo(Path.Combine(PathManager.GetExeDirectoryAbsolute(), "Shaders/BizHawk/hq2x.cgp")); if (fiHq2x.Exists) - using (var stream = fiHq2x.OpenRead()) - ShaderChain_hq2x = new Filters.RetroShaderChain(GL, new Filters.RetroShaderPreset(stream), Path.Combine(PathManager.GetExeDirectoryAbsolute(), "Shaders/BizHawk")); + { + using var stream = fiHq2x.OpenRead(); + ShaderChain_hq2x = new Filters.RetroShaderChain(GL, new Filters.RetroShaderPreset(stream), Path.Combine(PathManager.GetExeDirectoryAbsolute(), "Shaders/BizHawk")); + } var fiScanlines = new FileInfo(Path.Combine(PathManager.GetExeDirectoryAbsolute(), "Shaders/BizHawk/BizScanlines.cgp")); if (fiScanlines.Exists) - using (var stream = fiScanlines.OpenRead()) - ShaderChain_scanlines = new Filters.RetroShaderChain(GL, new Filters.RetroShaderPreset(stream), Path.Combine(PathManager.GetExeDirectoryAbsolute(), "Shaders/BizHawk")); - string bicubic_path = "Shaders/BizHawk/bicubic-fast.cgp"; - if(GL is BizHawk.Bizware.BizwareGL.Drivers.SlimDX.IGL_SlimDX9) - bicubic_path = "Shaders/BizHawk/bicubic-normal.cgp"; - var fiBicubic = new FileInfo(Path.Combine(PathManager.GetExeDirectoryAbsolute(), bicubic_path)); + { + using var stream = fiScanlines.OpenRead(); + ShaderChain_scanlines = new Filters.RetroShaderChain(GL, new Filters.RetroShaderPreset(stream), Path.Combine(PathManager.GetExeDirectoryAbsolute(), "Shaders/BizHawk")); + } + + string bicubicPath = "Shaders/BizHawk/bicubic-fast.cgp"; + if (GL is IGL_SlimDX9) + { + bicubicPath = "Shaders/BizHawk/bicubic-normal.cgp"; + } + var fiBicubic = new FileInfo(Path.Combine(PathManager.GetExeDirectoryAbsolute(), bicubicPath)); if (fiBicubic.Exists) - using (var stream = fiBicubic.Open(FileMode.Open, FileAccess.Read, FileShare.Read)) - ShaderChain_bicubic = new Filters.RetroShaderChain(GL, new Filters.RetroShaderPreset(stream), Path.Combine(PathManager.GetExeDirectoryAbsolute(), "Shaders/BizHawk")); + { + using var stream = fiBicubic.Open(FileMode.Open, FileAccess.Read, FileShare.Read); + ShaderChain_bicubic = new Filters.RetroShaderChain(GL, new Filters.RetroShaderPreset(stream), Path.Combine(PathManager.GetExeDirectoryAbsolute(), "Shaders/BizHawk")); + } } LuaSurfaceSets["emu"] = new SwappableDisplaySurfaceSet(); @@ -100,28 +125,35 @@ namespace BizHawk.Client.EmuHawk Disposed = true; VideoTextureFrugalizer.Dispose(); foreach (var f in LuaSurfaceFrugalizers.Values) + { f.Dispose(); + } + foreach (var f in ShaderChainFrugalizers) - if (f != null) - f.Dispose(); + { + f?.Dispose(); + } + foreach (var s in new[] { ShaderChain_hq2x, ShaderChain_scanlines, ShaderChain_bicubic, ShaderChain_user }) - if (s != null) - s.Dispose(); + { + s?.Dispose(); + } + TheOneFont.Dispose(); Renderer.Dispose(); } - //rendering resources: - IGL GL; - GLManager GLManager; - StringRenderer TheOneFont; - IGuiRenderer Renderer; + // rendering resources: + private readonly IGL GL; + private readonly GLManager GLManager; + private readonly StringRenderer TheOneFont; + private readonly IGuiRenderer Renderer; - //layer resources - PresentationPanel presentationPanel; //well, its the final layer's target, at least - GraphicsControl GraphicsControl; //well, its the final layer's target, at least - GLManager.ContextRef CR_GraphicsControl; - FilterProgram CurrentFilterProgram; + // layer resources + private readonly PresentationPanel presentationPanel; // well, its the final layer's target, at least + private readonly GraphicsControl GraphicsControl; // well, its the final layer's target, at least + private readonly GLManager.ContextRef CR_GraphicsControl; + private FilterProgram _currentFilterProgram; /// /// these variables will track the dimensions of the last frame's (or the next frame? this is confusing) emulator native output size @@ -132,33 +164,32 @@ namespace BizHawk.Client.EmuHawk /// /// additional pixels added at the unscaled level for the use of lua drawing. essentially increases the input video provider dimensions /// - public System.Windows.Forms.Padding GameExtraPadding; + public Padding GameExtraPadding { get; set; } /// /// additional pixels added at the native level for the use of lua drawing. essentially just gets tacked onto the final calculated window sizes. /// - public System.Windows.Forms.Padding ClientExtraPadding; + public Padding ClientExtraPadding { get; set; } /// /// custom fonts that don't need to be installed on the user side /// public System.Drawing.Text.PrivateFontCollection CustomFonts = new System.Drawing.Text.PrivateFontCollection(); - TextureFrugalizer VideoTextureFrugalizer; - Dictionary LuaSurfaceFrugalizers = new Dictionary(); - RenderTargetFrugalizer[] ShaderChainFrugalizers; - Filters.RetroShaderChain ShaderChain_hq2x, ShaderChain_scanlines, ShaderChain_bicubic; - Filters.RetroShaderChain ShaderChain_user; + private readonly TextureFrugalizer VideoTextureFrugalizer; + private readonly Dictionary LuaSurfaceFrugalizers = new Dictionary(); + private readonly RenderTargetFrugalizer[] ShaderChainFrugalizers; + private readonly Filters.RetroShaderChain ShaderChain_hq2x, ShaderChain_scanlines, ShaderChain_bicubic; + private Filters.RetroShaderChain ShaderChain_user; public void RefreshUserShader() { - if (ShaderChain_user != null) - ShaderChain_user.Dispose(); + ShaderChain_user?.Dispose(); if (File.Exists(Global.Config.DispUserFilterPath)) { var fi = new FileInfo(Global.Config.DispUserFilterPath); - using (var stream = fi.OpenRead()) - ShaderChain_user = new Filters.RetroShaderChain(GL, new Filters.RetroShaderPreset(stream), Path.GetDirectoryName(Global.Config.DispUserFilterPath)); + using var stream = fi.OpenRead(); + ShaderChain_user = new Filters.RetroShaderChain(GL, new Filters.RetroShaderPreset(stream), Path.GetDirectoryName(Global.Config.DispUserFilterPath)); } } @@ -166,23 +197,23 @@ namespace BizHawk.Client.EmuHawk { var padding = new System.Windows.Forms.Padding(); - if(user) + if (user) + { padding += GameExtraPadding; + } - //an experimental feature - if(source) - if (Global.Emulator is BizHawk.Emulation.Cores.Sony.PSX.Octoshock) - { - var psx = Global.Emulator as BizHawk.Emulation.Cores.Sony.PSX.Octoshock; - var core_padding = psx.VideoProvider_Padding; - padding.Left += core_padding.Width / 2; - padding.Right += core_padding.Width - core_padding.Width / 2; - padding.Top += core_padding.Height / 2; - padding.Bottom += core_padding.Height - core_padding.Height / 2; - } + // an experimental feature + if (source && Global.Emulator is Octoshock psx) + { + var corePadding = psx.VideoProvider_Padding; + padding.Left += corePadding.Width / 2; + padding.Right += corePadding.Width - corePadding.Width / 2; + padding.Top += corePadding.Height / 2; + padding.Bottom += corePadding.Height - corePadding.Height / 2; + } - //apply user's crop selections as a negative padding (believe it or not, this largely works) - //is there an issue with the aspect ratio? I dont know--but if there is, there would be with the padding too + // apply user's crop selections as a negative padding (believe it or not, this largely works) + // is there an issue with the aspect ratio? I don't know--but if there is, there would be with the padding too padding.Left -= Global.Config.DispCropLeft; padding.Right -= Global.Config.DispCropRight; padding.Top -= Global.Config.DispCropTop; @@ -191,32 +222,43 @@ namespace BizHawk.Client.EmuHawk return padding; } - FilterProgram BuildDefaultChain(Size chain_insize, Size chain_outsize, bool includeOSD) + FilterProgram BuildDefaultChain(Size chainInSize, Size chainOutSize, bool includeOSD) { - //select user special FX shader chain - Dictionary selectedChainProperties = new Dictionary(); + // select user special FX shader chain + var selectedChainProperties = new Dictionary(); Filters.RetroShaderChain selectedChain = null; if (Global.Config.TargetDisplayFilter == 1 && ShaderChain_hq2x != null && ShaderChain_hq2x.Available) + { selectedChain = ShaderChain_hq2x; + } + if (Global.Config.TargetDisplayFilter == 2 && ShaderChain_scanlines != null && ShaderChain_scanlines.Available) { selectedChain = ShaderChain_scanlines; selectedChainProperties["uIntensity"] = 1.0f - Global.Config.TargetScanlineFilterIntensity / 256.0f; } - if (Global.Config.TargetDisplayFilter == 3 && ShaderChain_user != null && ShaderChain_user.Available) - selectedChain = ShaderChain_user; - Filters.FinalPresentation fPresent = new Filters.FinalPresentation(chain_outsize); - Filters.SourceImage fInput = new Filters.SourceImage(chain_insize); - Filters.OSD fOSD = new Filters.OSD(); + if (Global.Config.TargetDisplayFilter == 3 && ShaderChain_user != null && ShaderChain_user.Available) + { + selectedChain = ShaderChain_user; + } + + var fPresent = new Filters.FinalPresentation(chainOutSize); + var fInput = new Filters.SourceImage(chainInSize); + var fOSD = new Filters.OSD(); fOSD.RenderCallback = () => { if (!includeOSD) + { return; + } + var size = fOSD.FindInput().SurfaceFormat.Size; Renderer.Begin(size.Width, size.Height); - MyBlitter myBlitter = new MyBlitter(this); - myBlitter.ClipBounds = new Rectangle(0, 0, size.Width, size.Height); + var myBlitter = new MyBlitter(this) + { + ClipBounds = new Rectangle(0, 0, size.Width, size.Height) + }; Renderer.SetBlendState(GL.BlendNormal); GlobalWin.OSD.Begin(myBlitter); GlobalWin.OSD.DrawScreenInfo(myBlitter); @@ -229,16 +271,16 @@ namespace BizHawk.Client.EmuHawk //add the first filter, encompassing output from the emulator core chain.AddFilter(fInput, "input"); - //if a non-zero padding is required, add a filter to allow for that - //note, we have two sources of padding right now.. one can come from the videoprovider and one from the user. - //we're combining these now and just using black, for sake of being lean, despite the discussion below: - //keep in mind, the videoprovider design in principle might call for another color. - //we havent really been using this very hard, but users will probably want black there (they could fill it to another color if needed tho) - var padding = CalculateCompleteContentPadding(true,true); + // if a non-zero padding is required, add a filter to allow for that + // note, we have two sources of padding right now.. one can come from the VideoProvider and one from the user. + // we're combining these now and just using black, for sake of being lean, despite the discussion below: + // keep in mind, the VideoProvider design in principle might call for another color. + // we haven't really been using this very hard, but users will probably want black there (they could fill it to another color if needed tho) + var padding = CalculateCompleteContentPadding(true, true); if (padding.Vertical != 0 || padding.Horizontal != 0) { - //TODO - add another filter just for this, its cumbersome to use final presentation... I think. but maybe theres enough similarities to justify it. - Size size = chain_insize; + // TODO - add another filter just for this, its cumbersome to use final presentation... I think. but maybe there's enough similarities to justify it. + Size size = chainInSize; size.Width += padding.Horizontal; size.Height += padding.Vertical; Filters.FinalPresentation fPadding = new Filters.FinalPresentation(size); @@ -254,15 +296,15 @@ namespace BizHawk.Client.EmuHawk if (Global.Config.DispPrescale != 1) { - Filters.PrescaleFilter fPrescale = new Filters.PrescaleFilter() { Scale = Global.Config.DispPrescale }; + var fPrescale = new Filters.PrescaleFilter() { Scale = Global.Config.DispPrescale }; chain.AddFilter(fPrescale, "user_prescale"); } - //add user-selected retro shader + // add user-selected retro shader if (selectedChain != null) AppendRetroShaderChain(chain, "retroShader", selectedChain, selectedChainProperties); - //AutoPrescale makes no sense for a None final filter + // AutoPrescale makes no sense for a None final filter if (Global.Config.DispAutoPrescale && Global.Config.DispFinalFilter != (int)Filters.FinalPresentation.eFilterOption.None) { var apf = new Filters.AutoPrescaleFilter(); @@ -270,30 +312,43 @@ namespace BizHawk.Client.EmuHawk } //choose final filter - Filters.FinalPresentation.eFilterOption finalFilter = Filters.FinalPresentation.eFilterOption.None; - if (Global.Config.DispFinalFilter == 1) finalFilter = Filters.FinalPresentation.eFilterOption.Bilinear; - if (Global.Config.DispFinalFilter == 2) finalFilter = Filters.FinalPresentation.eFilterOption.Bicubic; - //if bicubic is selected and unavailable, dont use it. use bilinear instead I guess + var finalFilter = Filters.FinalPresentation.eFilterOption.None; + if (Global.Config.DispFinalFilter == 1) + { + finalFilter = Filters.FinalPresentation.eFilterOption.Bilinear; + } + + if (Global.Config.DispFinalFilter == 2) + { + finalFilter = Filters.FinalPresentation.eFilterOption.Bicubic; + } + + //if bicubic is selected and unavailable, don't use it. use bilinear instead I guess if (finalFilter == Filters.FinalPresentation.eFilterOption.Bicubic) { if (ShaderChain_bicubic == null || !ShaderChain_bicubic.Available) + { finalFilter = Filters.FinalPresentation.eFilterOption.Bilinear; + } } + fPresent.FilterOption = finalFilter; - //now if bicubic is chosen, insert it + // now if bicubic is chosen, insert it if (finalFilter == Filters.FinalPresentation.eFilterOption.Bicubic) + { AppendRetroShaderChain(chain, "bicubic", ShaderChain_bicubic, null); + } - //add final presentation + // add final presentation chain.AddFilter(fPresent, "presentation"); //add lua layer 'native' AppendLuaLayer(chain, "native"); - //and OSD goes on top of that - //TODO - things break if this isnt present (the final presentation filter gets messed up when used with prescaling) - //so, always include it (we'll handle this flag in the callback to do no rendering) + // and OSD goes on top of that + // TODO - things break if this isn't present (the final presentation filter gets messed up when used with prescaling) + // so, always include it (we'll handle this flag in the callback to do no rendering) //if (includeOSD) chain.AddFilter(fOSD, "osd"); @@ -312,17 +367,18 @@ namespace BizHawk.Client.EmuHawk } } - Filters.LuaLayer AppendLuaLayer(FilterProgram chain, string name) + void AppendLuaLayer(FilterProgram chain, string name) { - Texture2d luaNativeTexture = null; var luaNativeSurface = LuaSurfaceSets[name].GetCurrent(); if (luaNativeSurface == null) - return null; - luaNativeTexture = LuaSurfaceFrugalizers[name].Get(luaNativeSurface); + { + return; + } + + Texture2d luaNativeTexture = LuaSurfaceFrugalizers[name].Get(luaNativeSurface); var fLuaLayer = new Filters.LuaLayer(); fLuaLayer.SetTexture(luaNativeTexture); chain.AddFilter(fLuaLayer, name); - return fLuaLayer; } /// @@ -330,15 +386,15 @@ namespace BizHawk.Client.EmuHawk /// public Point UntransformPoint(Point p) { - //first, turn it into a window coordinate + // first, turn it into a window coordinate p = presentationPanel.Control.PointToClient(p); - //now, if theres no filter program active, just give up - if (CurrentFilterProgram == null) return p; + // now, if there's no filter program active, just give up + if (_currentFilterProgram == null) return p; - //otherwise, have the filter program untransform it + // otherwise, have the filter program untransform it Vector2 v = new Vector2(p.X, p.Y); - v = CurrentFilterProgram.UntransformPoint("default",v); + v = _currentFilterProgram.UntransformPoint("default", v); return new Point((int)v.X, (int)v.Y); } @@ -347,12 +403,15 @@ namespace BizHawk.Client.EmuHawk /// public Point TransformPoint(Point p) { - //now, if theres no filter program active, just give up - if (CurrentFilterProgram == null) return p; + //now, if there's no filter program active, just give up + if (_currentFilterProgram == null) + { + return p; + } - //otherwise, have the filter program untransform it + // otherwise, have the filter program untransform it Vector2 v = new Vector2(p.X, p.Y); - v = CurrentFilterProgram.TransformPoint("default", v); + v = _currentFilterProgram.TransformPoint("default", v); return new Point((int)v.X, (int)v.Y); } @@ -368,17 +427,17 @@ namespace BizHawk.Client.EmuHawk bool displayNothing = Global.Config.DispSpeedupFeatures == 0; var job = new JobInfo { - videoProvider = videoProvider, - simulate = displayNothing, - chain_outsize = GraphicsControl.Size, - includeOSD = true, + VideoProvider = videoProvider, + Simulate = displayNothing, + ChainOutsize = GraphicsControl.Size, + IncludeOSD = true, }; UpdateSourceInternal(job); } public BitmapBuffer RenderVideoProvider(IVideoProvider videoProvider) { - //TODO - we might need to gather more Global.Config.DispXXX properties here, so they can be overridden + // TODO - we might need to gather more Global.Config.DispXXX properties here, so they can be overridden var targetSize = new Size(videoProvider.BufferWidth, videoProvider.BufferHeight); var padding = CalculateCompleteContentPadding(true,true); targetSize.Width += padding.Horizontal; @@ -386,14 +445,14 @@ namespace BizHawk.Client.EmuHawk var job = new JobInfo { - videoProvider = videoProvider, - simulate = false, - chain_outsize = targetSize, - offscreen = true, - includeOSD = false + VideoProvider = videoProvider, + Simulate = false, + ChainOutsize = targetSize, + Offscreen = true, + IncludeOSD = false }; UpdateSourceInternal(job); - return job.offscreenBB; + return job.OffscreenBb; } /// @@ -403,19 +462,19 @@ namespace BizHawk.Client.EmuHawk { var job = new JobInfo { - videoProvider = videoProvider, - simulate = false, - chain_outsize = GraphicsControl.Size, - offscreen = true, - includeOSD = includeOSD + VideoProvider = videoProvider, + Simulate = false, + ChainOutsize = GraphicsControl.Size, + Offscreen = true, + IncludeOSD = includeOSD }; UpdateSourceInternal(job); - return job.offscreenBB; + return job.OffscreenBb; } - class FakeVideoProvider : IVideoProvider + private class FakeVideoProvider : IVideoProvider { - public int[] GetVideoBuffer() { return new int[] {}; } + public int[] GetVideoBuffer() => new int[] {}; public int VirtualWidth { get; set; } public int VirtualHeight { get; set; } @@ -424,61 +483,54 @@ namespace BizHawk.Client.EmuHawk public int BufferHeight { get; set; } public int BackgroundColor { get; set; } - public int VsyncNumerator - { - get { throw new InvalidOperationException(); } - } + public int VsyncNumerator => throw new InvalidOperationException(); - public int VsyncDenominator - { - get { throw new InvalidOperationException(); } - } + public int VsyncDenominator => throw new InvalidOperationException(); } - void FixRatio(float x, float y, int inw, int inh, out int outw, out int outh) + void FixRatio(float x, float y, int inw, int inh, out int outW, out int outH) { float ratio = x / y; if (ratio <= 1) { - //taller. weird. expand height. - outw = inw; - outh = (int)((float)inw / ratio); + // taller. weird. expand height. + outW = inw; + outH = (int)(inw / ratio); } else { - //wider. normal. expand width. - outw = (int)((float)inh * ratio); - outh = inh; + // wider. normal. expand width. + outW = (int)(inh * ratio); + outH = inh; } } /// /// Attempts to calculate a good client size with the given zoom factor, considering the user's DisplayManager preferences /// TODO - this needs to be redone with a concept different from zoom factor. - /// basically, each increment of a 'zoomlike' factor should definitely increase the viewable area somehow, even if it isnt strictly by an entire zoom level. + /// basically, each increment of a 'zoom-like' factor should definitely increase the viewable area somehow, even if it isnt strictly by an entire zoom level. /// public Size CalculateClientSize(IVideoProvider videoProvider, int zoom) { - bool ar_active = Global.Config.DispFixAspectRatio; - bool ar_system = Global.Config.DispManagerAR == Config.EDispManagerAR.System; - bool ar_custom = Global.Config.DispManagerAR == Config.EDispManagerAR.Custom; - bool ar_customRatio = Global.Config.DispManagerAR == Config.EDispManagerAR.CustomRatio; - bool ar_correct = ar_system || ar_custom || ar_customRatio; - bool ar_unity = !ar_correct; - bool ar_integer = Global.Config.DispFixScaleInteger; + bool arActive = Global.Config.DispFixAspectRatio; + bool arSystem = Global.Config.DispManagerAR == Config.EDispManagerAR.System; + bool arCustom = Global.Config.DispManagerAR == Config.EDispManagerAR.Custom; + bool arCustomRatio = Global.Config.DispManagerAR == Config.EDispManagerAR.CustomRatio; + bool arCorrect = arSystem || arCustom || arCustomRatio; + bool arInteger = Global.Config.DispFixScaleInteger; int bufferWidth = videoProvider.BufferWidth; int bufferHeight = videoProvider.BufferHeight; int virtualWidth = videoProvider.VirtualWidth; int virtualHeight = videoProvider.VirtualHeight; - if (ar_custom) + if (arCustom) { virtualWidth = Global.Config.DispCustomUserARWidth; virtualHeight = Global.Config.DispCustomUserARHeight; } - if (ar_customRatio) + if (arCustomRatio) { FixRatio(Global.Config.DispCustomUserARX, Global.Config.DispCustomUserARY, videoProvider.BufferWidth, videoProvider.BufferHeight, out virtualWidth, out virtualHeight); } @@ -491,42 +543,43 @@ namespace BizHawk.Client.EmuHawk bufferWidth += padding.Horizontal; bufferHeight += padding.Vertical; - //Console.WriteLine($"DISPZOOM {zoom}"); //test - - //old stuff - var fvp = new FakeVideoProvider(); - fvp.BufferWidth = bufferWidth; - fvp.BufferHeight = bufferHeight; - fvp.VirtualWidth = virtualWidth; - fvp.VirtualHeight = virtualHeight; - - Size chain_outsize = new Size(fvp.BufferWidth * zoom, fvp.BufferHeight * zoom); - - if (ar_active) + // old stuff + var fvp = new FakeVideoProvider { - if (ar_correct) + BufferWidth = bufferWidth, + BufferHeight = bufferHeight, + VirtualWidth = virtualWidth, + VirtualHeight = virtualHeight + }; + + Size chainOutsize; + + if (arActive) + { + if (arCorrect) { - if (ar_integer) + if (arInteger) { - //ALERT COPYPASTE LAUNDROMAT + // ALERT COPYPASTE LAUNDROMAT Vector2 VS = new Vector2(virtualWidth, virtualHeight); Vector2 BS = new Vector2(bufferWidth, bufferHeight); Vector2 AR = Vector2.Divide(VS, BS); - float target_par = (AR.X / AR.Y); + float targetPar = AR.X / AR.Y; - //this would malfunction for AR <= 0.5 or AR >= 2.0 - //EDIT - in fact, we have AR like that coming from PSX, sometimes, so maybe we should solve this better + // this would malfunction for AR <= 0.5 or AR >= 2.0 + // EDIT - in fact, we have AR like that coming from PSX, sometimes, so maybe we should solve this better Vector2 PS = new Vector2(1, 1); - //here's how we define zooming, in this case: - //make sure each step is an increment of zoom for at least one of the dimensions (or maybe both of them) - //look for the increment which helps the AR the best + // here's how we define zooming, in this case: + // make sure each step is an increment of zoom for at least one of the dimensions (or maybe both of them) + // look for the increment which helps the AR the best //TODO - this cant possibly support scale factors like 1.5x //TODO - also, this might be messing up zooms and stuff, we might need to run this on the output size of the filter chain for (int i = 1; i < zoom;i++) { //would not be good to run this per frame, but it seems to only run when the resolution changes, etc. - Vector2[] trials = new[] { + Vector2[] trials = + { PS + new Vector2(1, 0), PS + new Vector2(0, 1), PS + new Vector2(1, 1) @@ -536,65 +589,71 @@ namespace BizHawk.Client.EmuHawk for (int t = 0; t < trials.Length; t++) { //I. - float test_ar = trials[t].X / trials[t].Y; + float testAr = trials[t].X / trials[t].Y; - //II. + // II. //Vector2 calc = Vector2.Multiply(trials[t], VS); //float test_ar = calc.X / calc.Y; - //not clear which approach is superior - float deviation_linear = Math.Abs(test_ar - target_par); - float deviation_geom = test_ar / target_par; - if (deviation_geom < 1) deviation_geom = 1.0f / deviation_geom; + // not clear which approach is superior + float deviationLinear = Math.Abs(testAr - targetPar); + float deviationGeom = testAr / targetPar; + if (deviationGeom < 1) + { + deviationGeom = 1.0f / deviationGeom; + } - float value = deviation_linear; + float value = deviationLinear; if (value < bestValue) { bestIndex = t; bestValue = value; } } - //is it possible to get here without selecting one? doubtful. - //EDIT: YES IT IS. it happened with an 0,0 buffer size. of course, that was a mistake, but we shouldnt crash - if(bestIndex != -1) //so, what now? well, this will result in 0,0 getting picked, so thats probably all we can do + + // is it possible to get here without selecting one? doubtful. + // EDIT: YES IT IS. it happened with an 0,0 buffer size. of course, that was a mistake, but we shouldn't crash + if (bestIndex != -1) // so, what now? well, this will result in 0,0 getting picked, so that's probably all we can do + { PS = trials[bestIndex]; + } } - chain_outsize = new Size((int)(bufferWidth * PS.X), (int)(bufferHeight * PS.Y)); + chainOutsize = new Size((int)(bufferWidth * PS.X), (int)(bufferHeight * PS.Y)); } else { - //obey the AR, but allow free scaling: just zoom the virtual size - chain_outsize = new Size(virtualWidth * zoom, virtualHeight * zoom); + // obey the AR, but allow free scaling: just zoom the virtual size + chainOutsize = new Size(virtualWidth * zoom, virtualHeight * zoom); } } else { - //ar_unity: - //just choose to zoom the buffer (make no effort to incorporate AR) - chain_outsize = new Size(bufferWidth * zoom, bufferHeight * zoom); + // ar_unity: + // just choose to zoom the buffer (make no effort to incorporate AR) + chainOutsize = new Size(bufferWidth * zoom, bufferHeight * zoom); } } else { - //!ar_active: - //just choose to zoom the buffer (make no effort to incorporate AR) - chain_outsize = new Size(bufferWidth * zoom, bufferHeight * zoom); + // !ar_active: + // just choose to zoom the buffer (make no effort to incorporate AR) + chainOutsize = new Size(bufferWidth * zoom, bufferHeight * zoom); } - chain_outsize.Width += ClientExtraPadding.Horizontal; - chain_outsize.Height += ClientExtraPadding.Vertical; + chainOutsize.Width += ClientExtraPadding.Horizontal; + chainOutsize.Height += ClientExtraPadding.Vertical; var job = new JobInfo { - videoProvider = fvp, - simulate = true, - chain_outsize = chain_outsize, + VideoProvider = fvp, + Simulate = true, + ChainOutsize = chainOutsize, }; var filterProgram = UpdateSourceInternal(job); - //this only happens when we're forcing the client to size itself with autoload and the core says 0x0.... - //we need some other more sensible client size. + // this only happens when we're forcing the client to size itself with autoload and the core says 0x0.... + // we need some other more sensible client size. if (filterProgram == null) { return new Size(256, 192); @@ -605,35 +664,38 @@ namespace BizHawk.Client.EmuHawk return size; } - class JobInfo + private class JobInfo { - public IVideoProvider videoProvider; - public bool simulate; - public Size chain_outsize; - public bool offscreen; - public BitmapBuffer offscreenBB; - public bool includeOSD; + public IVideoProvider VideoProvider; + public bool Simulate; + public Size ChainOutsize; + public bool Offscreen; + public BitmapBuffer OffscreenBb; + public bool IncludeOSD; } - FilterProgram UpdateSourceInternal(JobInfo job) + private FilterProgram UpdateSourceInternal(JobInfo job) { //no drawing actually happens. it's important not to begin drawing on a control - if (!job.simulate && !job.offscreen) + if (!job.Simulate && !job.Offscreen) { GLManager.Activate(CR_GraphicsControl); - if (job.chain_outsize.Width == 0 || job.chain_outsize.Height == 0) + if (job.ChainOutsize.Width == 0 || job.ChainOutsize.Height == 0) { - //this has to be a NOP, because lots of stuff will malfunction on a 0-sized viewport - if (CurrentFilterProgram != null) + // this has to be a NOP, because lots of stuff will malfunction on a 0-sized viewport + if (_currentFilterProgram != null) + { UpdateSourceDrawingWork(job); //but we still need to do this, because of vsync + } + return null; } } - IVideoProvider videoProvider = job.videoProvider; - bool simulate = job.simulate; - Size chain_outsize = job.chain_outsize; + IVideoProvider videoProvider = job.VideoProvider; + bool simulate = job.Simulate; + Size chainOutsize = job.ChainOutsize; //simulate = true; @@ -680,26 +742,26 @@ namespace BizHawk.Client.EmuHawk } else { - //wrap the videoprovider data in a BitmapBuffer (no point to refactoring that many IVideoProviders) + //wrap the VideoProvider data in a BitmapBuffer (no point to refactoring that many IVideoProviders) bb = new BitmapBuffer(bufferWidth, bufferHeight, videoBuffer); bb.DiscardAlpha(); //now, acquire the data sent from the videoProvider into a texture videoTexture = VideoTextureFrugalizer.Get(bb); - //lets not use this. lets define BizwareGL to make clamp by default (TBD: check opengl) + // lets not use this. lets define BizwareGL to make clamp by default (TBD: check opengl) //GL.SetTextureWrapMode(videoTexture, true); } } - //record the size of what we received, since lua and stuff is gonna want to draw onto it + // record the size of what we received, since lua and stuff is gonna want to draw onto it currEmuWidth = bufferWidth; currEmuHeight = bufferHeight; //build the default filter chain and set it up with services filters will need - Size chain_insize = new Size(bufferWidth, bufferHeight); + Size chainInsize = new Size(bufferWidth, bufferHeight); - var filterProgram = BuildDefaultChain(chain_insize, chain_outsize, job.includeOSD); + var filterProgram = BuildDefaultChain(chainInsize, chainOutsize, job.IncludeOSD); filterProgram.GuiRenderer = Renderer; filterProgram.GL = GL; @@ -721,19 +783,19 @@ namespace BizHawk.Client.EmuHawk fPresent.GL = GL; - filterProgram.Compile("default", chain_insize, chain_outsize, !job.offscreen); + filterProgram.Compile("default", chainInsize, chainOutsize, !job.Offscreen); if (simulate) { } else { - CurrentFilterProgram = filterProgram; + _currentFilterProgram = filterProgram; UpdateSourceDrawingWork(job); } - //cleanup: - if (bb != null) bb.Dispose(); + // cleanup: + bb?.Dispose(); return filterProgram; } @@ -751,21 +813,21 @@ namespace BizHawk.Client.EmuHawk void UpdateSourceDrawingWork(JobInfo job) { - bool vsync = false; bool alternateVsync = false; - //only used by alternate vsync + + // only used by alternate vsync IGL_SlimDX9 dx9 = null; - if (!job.offscreen) + if (!job.Offscreen) { //apply the vsync setting (should probably try to avoid repeating this) - vsync = Global.Config.VSyncThrottle || Global.Config.VSync; + var vsync = Global.Config.VSyncThrottle || Global.Config.VSync; - //ok, now this is a bit undesireable. + //ok, now this is a bit undesirable. //maybe the user wants vsync, but not vsync throttle. - //this makes sense... but we dont have the infrastructure to support it now (we'd have to enable triple buffering or something like that) + //this makes sense... but we don't have the infrastructure to support it now (we'd have to enable triple buffering or something like that) //so what we're gonna do is disable vsync no matter what if throttling is off, and maybe nobody will notice. - //update 26-mar-2016: this upsets me. When fastforwarding and skipping frames, vsync should still work. But I'm not changing it yet + //update 26-mar-2016: this upsets me. When fast-forwarding and skipping frames, vsync should still work. But I'm not changing it yet if (Global.DisableSecondaryThrottling) vsync = false; @@ -797,30 +859,30 @@ namespace BizHawk.Client.EmuHawk } } - //begin rendering on this context - //should this have been done earlier? - //do i need to check this on an intel video card to see if running excessively is a problem? (it used to be in the FinalTarget command below, shouldnt be a problem) - //GraphicsControl.Begin(); //CRITICAL POINT for yabause+GL + // begin rendering on this context + // should this have been done earlier? + // do i need to check this on an intel video card to see if running excessively is a problem? (it used to be in the FinalTarget command below, shouldn't be a problem) + //GraphicsControl.Begin(); // CRITICAL POINT for yabause+GL //TODO - auto-create and age these (and dispose when old) int rtCounter = 0; - CurrentFilterProgram.RenderTargetProvider = new DisplayManagerRenderTargetProvider((size) => ShaderChainFrugalizers[rtCounter++].Get(size)); + _currentFilterProgram.RenderTargetProvider = new DisplayManagerRenderTargetProvider(size => ShaderChainFrugalizers[rtCounter++].Get(size)); GL.BeginScene(); - //run filter chain + // run filter chain Texture2d texCurr = null; RenderTarget rtCurr = null; bool inFinalTarget = false; - foreach (var step in CurrentFilterProgram.Program) + foreach (var step in _currentFilterProgram.Program) { switch (step.Type) { case FilterProgram.ProgramStepType.Run: { int fi = (int)step.Args; - var f = CurrentFilterProgram.Filters[fi]; + var f = _currentFilterProgram.Filters[fi]; f.SetInput(texCurr); f.Run(); var orec = f.FindOutput(); @@ -839,7 +901,7 @@ namespace BizHawk.Client.EmuHawk var size = (Size)step.Args; rtCurr = ShaderChainFrugalizers[rtCounter++].Get(size); rtCurr.Bind(); - CurrentFilterProgram.CurrRenderTarget = rtCurr; + _currentFilterProgram.CurrRenderTarget = rtCurr; break; } case FilterProgram.ProgramStepType.FinalTarget: @@ -847,7 +909,7 @@ namespace BizHawk.Client.EmuHawk var size = (Size)step.Args; inFinalTarget = true; rtCurr = null; - CurrentFilterProgram.CurrRenderTarget = null; + _currentFilterProgram.CurrRenderTarget = null; GL.BindRenderTarget(null); break; } @@ -856,10 +918,10 @@ namespace BizHawk.Client.EmuHawk GL.EndScene(); - if (job.offscreen) + if (job.Offscreen) { - job.offscreenBB = rtCurr.Texture2d.Resolve(); - job.offscreenBB.DiscardAlpha(); + job.OffscreenBb = rtCurr.Texture2d.Resolve(); + job.OffscreenBb.DiscardAlpha(); } else { @@ -874,33 +936,31 @@ namespace BizHawk.Client.EmuHawk //wait for vsync to end if (alternateVsync) dx9.AlternateVsyncPass(1); - //nope. dont do this. workaround for slow context switching on intel GPUs. just switch to another context when necessary before doing anything + //nope. don't do this. workaround for slow context switching on intel GPUs. just switch to another context when necessary before doing anything //presentationPanel.GraphicsControl.End(); } } - private void LoadCustomFont(Stream fontstream) + private void LoadCustomFont(Stream fontStream) { - System.IntPtr data = System.Runtime.InteropServices.Marshal.AllocCoTaskMem((int)fontstream.Length); - byte[] fontdata = new byte[fontstream.Length]; - fontstream.Read(fontdata, 0, (int)fontstream.Length); - System.Runtime.InteropServices.Marshal.Copy(fontdata, 0, data, (int)fontstream.Length); - CustomFonts.AddMemoryFont(data, fontdata.Length); - fontstream.Close(); + IntPtr data = System.Runtime.InteropServices.Marshal.AllocCoTaskMem((int)fontStream.Length); + byte[] fontData = new byte[fontStream.Length]; + fontStream.Read(fontData, 0, (int)fontStream.Length); + System.Runtime.InteropServices.Marshal.Copy(fontData, 0, data, (int)fontStream.Length); + CustomFonts.AddMemoryFont(data, fontData.Length); + fontStream.Close(); System.Runtime.InteropServices.Marshal.FreeCoTaskMem(data); } - bool? LastVsyncSetting; - GraphicsControl LastVsyncSettingGraphicsControl; + private bool? LastVsyncSetting; + private GraphicsControl LastVsyncSettingGraphicsControl; - Dictionary MapNameToLuaSurface = new Dictionary(); - Dictionary MapLuaSurfaceToName = new Dictionary(); - Dictionary LuaSurfaceSets = new Dictionary(); - SwappableDisplaySurfaceSet luaNativeSurfaceSet = new SwappableDisplaySurfaceSet(); - public void SetLuaSurfaceNativePreOSD(DisplaySurface surface) { luaNativeSurfaceSet.SetPending(surface); } + private Dictionary MapNameToLuaSurface = new Dictionary(); + private Dictionary MapLuaSurfaceToName = new Dictionary(); + private Dictionary LuaSurfaceSets = new Dictionary(); /// - /// Peeks a locked lua surface, or returns null if it isnt locked + /// Peeks a locked lua surface, or returns null if it isn't locked /// public DisplaySurface PeekLockedLuaSurface(string name) { @@ -915,16 +975,17 @@ namespace BizHawk.Client.EmuHawk public DisplaySurface LockLuaSurface(string name, bool clear=true) { if (MapNameToLuaSurface.ContainsKey(name)) + { throw new InvalidOperationException($"Lua surface is already locked: {name}"); + } - SwappableDisplaySurfaceSet sdss; - if (!LuaSurfaceSets.TryGetValue(name, out sdss)) + if (!LuaSurfaceSets.TryGetValue(name, out var sdss)) { sdss = new SwappableDisplaySurfaceSet(); LuaSurfaceSets.Add(name, sdss); } - //placeholder logic for more abstracted surface definitions from filter chain + // placeholder logic for more abstracted surface definitions from filter chain int currNativeWidth = presentationPanel.NativeSize.Width; int currNativeHeight = presentationPanel.NativeSize.Height; @@ -956,16 +1017,19 @@ namespace BizHawk.Client.EmuHawk var surf = PeekLockedLuaSurface(kvp.Key); DisplaySurface surfLocked = null; if (surf == null) - surf = surfLocked = LockLuaSurface(kvp.Key,true); - //zero 21-apr-2016 - we shouldnt need this - //surf.Clear(); + { + surfLocked = LockLuaSurface(kvp.Key,true); + } + if (surfLocked != null) + { UnlockLuaSurface(surfLocked); + } + LuaSurfaceSets[kvp.Key].SetPending(null); } catch (InvalidOperationException) { - } } } @@ -976,46 +1040,55 @@ namespace BizHawk.Client.EmuHawk public void UnlockLuaSurface(DisplaySurface surface) { if (!MapLuaSurfaceToName.ContainsKey(surface)) + { throw new InvalidOperationException("Surface was not locked as a lua surface"); + } + string name = MapLuaSurfaceToName[surface]; MapLuaSurfaceToName.Remove(surface); MapNameToLuaSurface.Remove(name); LuaSurfaceSets[name].SetPending(surface); } - //helper classes: - - class MyBlitter : IBlitter + // helper classes: + private class MyBlitter : IBlitter { - DisplayManager Owner; + private readonly DisplayManager _owner; + public MyBlitter(DisplayManager dispManager) { - Owner = dispManager; + _owner = dispManager; } - class FontWrapper : IBlitterFont + private class FontWrapper : IBlitterFont { public FontWrapper(StringRenderer font) { - this.font = font; + Font = font; } - public readonly StringRenderer font; + public readonly StringRenderer Font; + } + + IBlitterFont IBlitter.GetFontType(string fontType) + { + return new FontWrapper(_owner.TheOneFont); } - IBlitterFont IBlitter.GetFontType(string fontType) { return new FontWrapper(Owner.TheOneFont); } void IBlitter.DrawString(string s, IBlitterFont font, Color color, float x, float y) { - var stringRenderer = ((FontWrapper)font).font; - Owner.Renderer.SetModulateColor(color); - stringRenderer.RenderString(Owner.Renderer, x, y, s); - Owner.Renderer.SetModulateColorWhite(); + var stringRenderer = ((FontWrapper)font).Font; + _owner.Renderer.SetModulateColor(color); + stringRenderer.RenderString(_owner.Renderer, x, y, s); + _owner.Renderer.SetModulateColorWhite(); } + SizeF IBlitter.MeasureString(string s, IBlitterFont font) { - var stringRenderer = ((FontWrapper)font).font; + var stringRenderer = ((FontWrapper)font).Font; return stringRenderer.Measure(s); } + public Rectangle ClipBounds { get; set; } } } diff --git a/BizHawk.Client.EmuHawk/DisplayManager/OSDManager.cs b/BizHawk.Client.EmuHawk/DisplayManager/OSDManager.cs index ab7d406c5f..159b9b74c2 100644 --- a/BizHawk.Client.EmuHawk/DisplayManager/OSDManager.cs +++ b/BizHawk.Client.EmuHawk/DisplayManager/OSDManager.cs @@ -24,20 +24,18 @@ namespace BizHawk.Client.EmuHawk Rectangle ClipBounds { get; set; } } - class UIMessage + public class UIMessage { - public string Message; - public DateTime ExpireAt; + public string Message { get; set; } + public DateTime ExpireAt { get; set; } } - class UIDisplay + public class UIDisplay { - public string Message; - public int X; - public int Y; - public int Anchor; - public Color ForeColor; - public Color BackGround; + public string Message { get; set; } + public MessagePosition Position { get; set; } + public Color ForeColor { get; set; } + public Color BackGround { get; set; } } public class OSDManager @@ -53,41 +51,24 @@ namespace BizHawk.Client.EmuHawk public Color FixedMessagesColor => Color.FromArgb(Global.Config.MessagesColor); public Color FixedAlertMessageColor => Color.FromArgb(Global.Config.AlertMessageColor); - private float GetX(IBlitter g, int x, int anchor, string message) + private PointF GetCoordinates(IBlitter g, MessagePosition position, string message) { var size = g.MeasureString(message, MessageFont); + float x = position.Anchor.IsLeft() + ? position.X + : g.ClipBounds.Width - position.X - size.Width; - switch (anchor) - { - default: - case 0: //Top Left - case 2: //Bottom Left - return x; - case 1: //Top Right - case 3: //Bottom Right - return g.ClipBounds.Width - x - size.Width; - } - } + float y = position.Anchor.IsTop() + ? position.Y + : g.ClipBounds.Height - position.Y - size.Height; + - private float GetY(IBlitter g, int y, int anchor, string message) - { - var size = g.MeasureString(message, MessageFont); - - switch (anchor) - { - default: - case 0: //Top Left - case 1: //Top Right - return y; - case 2: //Bottom Left - case 3: //Bottom Right - return g.ClipBounds.Height - y - size.Height; - } + return new PointF(x, y); } private string MakeFrameCounter() { - if (Global.MovieSession.Movie.IsFinished) + if (Global.MovieSession.Movie.IsFinished()) { var sb = new StringBuilder(); sb @@ -98,7 +79,7 @@ namespace BizHawk.Client.EmuHawk return sb.ToString(); } - if (Global.MovieSession.Movie.IsPlaying) + if (Global.MovieSession.Movie.IsPlaying()) { var sb = new StringBuilder(); sb @@ -109,11 +90,6 @@ namespace BizHawk.Client.EmuHawk return sb.ToString(); } - if (Global.MovieSession.Movie.IsRecording) - { - return Global.Emulator.Frame.ToString(); - } - return Global.Emulator.Frame.ToString(); } @@ -125,16 +101,14 @@ namespace BizHawk.Client.EmuHawk _messages.Add(new UIMessage { Message = message, ExpireAt = DateTime.Now + TimeSpan.FromSeconds(2) }); } - public void AddGuiText(string message, int x, int y, Color backGround, Color foreColor, int anchor) + public void AddGuiText(string message, MessagePosition pos, Color backGround, Color foreColor) { _guiTextList.Add(new UIDisplay { Message = message, - X = x, - Y = y, + Position = pos, BackGround = backGround, - ForeColor = foreColor, - Anchor = anchor + ForeColor = foreColor }); } @@ -143,6 +117,13 @@ namespace BizHawk.Client.EmuHawk _guiTextList.Clear(); } + private void DrawMessage(IBlitter g, UIMessage message, int yOffset) + { + var point = GetCoordinates(g, Global.Config.Messages, message.Message); + var y = point.Y + yOffset; // TODO: clean me up + g.DrawString(message.Message, MessageFont, FixedMessagesColor, point.X, y); + } + public void DrawMessages(IBlitter g) { if (!Global.Config.DisplayMessages) @@ -151,43 +132,27 @@ namespace BizHawk.Client.EmuHawk } _messages.RemoveAll(m => DateTime.Now > m.ExpireAt); - int line = 1; - if (Global.Config.StackOSDMessages) - { - for (int i = _messages.Count - 1; i >= 0; i--, line++) - { - float x = GetX(g, Global.Config.DispMessagex, Global.Config.DispMessageanchor, _messages[i].Message); - float y = GetY(g, Global.Config.DispMessagey, Global.Config.DispMessageanchor, _messages[i].Message); - if (Global.Config.DispMessageanchor < 2) - { - y += (line - 1) * 18; - } - else - { - y -= (line - 1) * 18; - } - g.DrawString(_messages[i].Message, MessageFont, FixedMessagesColor, x, y); + if (_messages.Any()) + { + if (Global.Config.StackOSDMessages) + { + int line = 1; + for (int i = _messages.Count - 1; i >= 0; i--, line++) + { + int yOffset = (line - 1) * 18; + if (!Global.Config.Messages.Anchor.IsTop()) + { + yOffset = 0 - yOffset; + } + + DrawMessage(g, _messages[i], yOffset); + } } - } - else - { - if (_messages.Any()) + else { - int i = _messages.Count - 1; - - float x = GetX(g, Global.Config.DispMessagex, Global.Config.DispMessageanchor, _messages[i].Message); - float y = GetY(g, Global.Config.DispMessagey, Global.Config.DispMessageanchor, _messages[i].Message); - if (Global.Config.DispMessageanchor < 2) - { - y += (line - 1) * 18; - } - else - { - y -= (line - 1) * 18; - } - - g.DrawString(_messages[i].Message, MessageFont, FixedMessagesColor, x, y); + var message = _messages.Last(); + DrawMessage(g, message, 0); } } @@ -195,10 +160,8 @@ namespace BizHawk.Client.EmuHawk { try { - float posX = GetX(g, text.X, text.Anchor, text.Message); - float posY = GetY(g, text.Y, text.Anchor, text.Message); - - g.DrawString(text.Message, MessageFont, text.ForeColor, posX, posY); + var point = GetCoordinates(g, text.Position, text.Message); + g.DrawString(text.Message, MessageFont, text.ForeColor, point.X, point.Y); } catch (Exception) { @@ -225,7 +188,7 @@ namespace BizHawk.Client.EmuHawk public string InputPrevious() { - if (Global.MovieSession.Movie.IsActive && !Global.MovieSession.Movie.IsFinished) + if (Global.MovieSession.Movie.IsPlayingOrRecording()) { var lg = Global.MovieSession.LogGeneratorInstance(); var state = Global.MovieSession.Movie.GetInputState(Global.Emulator.Frame - 1); @@ -241,11 +204,9 @@ namespace BizHawk.Client.EmuHawk public string InputStrOrAll() { - var m = (Global.MovieSession.Movie.IsActive && - !Global.MovieSession.Movie.IsFinished && - Global.Emulator.Frame > 0) ? - Global.MovieSession.Movie.GetInputState(Global.Emulator.Frame - 1) : - Global.MovieSession.MovieControllerInstance(); + var m = Global.MovieSession.Movie.IsPlayingOrRecording() && Global.Emulator.Frame > 0 + ? Global.MovieSession.Movie.GetInputState(Global.Emulator.Frame - 1) + : Global.MovieSession.MovieControllerInstance(); var lg = Global.MovieSession.LogGeneratorInstance(); @@ -262,11 +223,11 @@ namespace BizHawk.Client.EmuHawk public string MakeIntersectImmediatePrevious() { - if (Global.MovieSession.Movie.IsActive) + if (Global.MovieSession.Movie.IsActive()) { - var m = Global.MovieSession.Movie.IsActive && !Global.MovieSession.Movie.IsFinished ? - Global.MovieSession.Movie.GetInputState(Global.Emulator.Frame - 1) : - Global.MovieSession.MovieControllerInstance(); + var m = Global.MovieSession.Movie.IsPlayingOrRecording() + ? Global.MovieSession.Movie.GetInputState(Global.Emulator.Frame - 1) + : Global.MovieSession.MovieControllerInstance(); var lg = Global.MovieSession.LogGeneratorInstance(); lg.SetSource(Global.AutofireStickyXORAdapter.And(m)); @@ -278,7 +239,7 @@ namespace BizHawk.Client.EmuHawk public string MakeRerecordCount() { - return Global.MovieSession.Movie.IsActive + return Global.MovieSession.Movie.IsActive() ? Global.MovieSession.Movie.Rerecords.ToString() : ""; } @@ -296,27 +257,24 @@ namespace BizHawk.Client.EmuHawk if (Global.Config.DisplayFrameCounter && !Global.Game.IsNullInstance()) { string message = MakeFrameCounter(); - float x = GetX(g, Global.Config.DispFrameCx, Global.Config.DispFrameanchor, message); - float y = GetY(g, Global.Config.DispFrameCy, Global.Config.DispFrameanchor, message); - - DrawOsdMessage(g, message, Color.FromArgb(Global.Config.MessagesColor), x, y); + var point = GetCoordinates(g, Global.Config.FrameCounter, message); + DrawOsdMessage(g, message, Color.FromArgb(Global.Config.MessagesColor), point.X, point.Y); if (GlobalWin.MainForm.IsLagFrame) { - DrawOsdMessage(g, Global.Emulator.Frame.ToString(), FixedAlertMessageColor, x, y); + DrawOsdMessage(g, Global.Emulator.Frame.ToString(), FixedAlertMessageColor, point.X, point.Y); } } if (Global.Config.DisplayInput && !Global.Game.IsNullInstance()) { - if ((Global.MovieSession.Movie.IsPlaying && !Global.MovieSession.Movie.IsFinished) - || (Global.MovieSession.Movie.IsFinished && Global.Emulator.Frame == Global.MovieSession.Movie.InputLogLength)) // Account for the last frame of the movie, the movie state is immediately "Finished" here but we still want to show the input + if (Global.MovieSession.Movie.Mode == MovieMode.Play + || (Global.MovieSession.Movie.IsFinished() && Global.Emulator.Frame == Global.MovieSession.Movie.InputLogLength)) // Account for the last frame of the movie, the movie state is immediately "Finished" here but we still want to show the input { var input = InputStrMovie(); - var x = GetX(g, Global.Config.DispInpx, Global.Config.DispInpanchor, input); - var y = GetY(g, Global.Config.DispInpy, Global.Config.DispInpanchor, input); + var point = GetCoordinates(g, Global.Config.InputDisplay, input); Color c = Color.FromArgb(Global.Config.MovieInput); - g.DrawString(input, MessageFont, c, x, y); + g.DrawString(input, MessageFont, c, point.X, point.Y); } else // TODO: message config -- allow setting of "previous", "mixed", and "auto" @@ -328,22 +286,21 @@ namespace BizHawk.Client.EmuHawk //we need some kind of string for calculating position when right-anchoring, of something like that var bgStr = InputStrOrAll(); - var x = GetX(g, Global.Config.DispInpx, Global.Config.DispInpanchor, bgStr); - var y = GetY(g, Global.Config.DispInpy, Global.Config.DispInpanchor, bgStr); + var point = GetCoordinates(g, Global.Config.InputDisplay, bgStr); // now, we're going to render these repeatedly, with higher-priority things overriding // first display previous frame's input. // note: that's only available in case we're working on a movie var previousStr = InputPrevious(); - g.DrawString(previousStr, MessageFont, previousColor, x, y); + g.DrawString(previousStr, MessageFont, previousColor, point.X, point.Y); // next, draw the immediate input. // that is, whatever is being held down interactively right this moment even if the game is paused // this includes things held down due to autohold or autofire // I know, this is all really confusing var immediate = InputStrImmediate(); - g.DrawString(immediate, MessageFont, immediateColor, x, y); + g.DrawString(immediate, MessageFont, immediateColor, point.X, point.Y); // next draw anything that's pressed because it's sticky. // this applies to autofire and autohold both. somehow. I don't understand it. @@ -351,46 +308,38 @@ namespace BizHawk.Client.EmuHawk // in order to achieve this we want to avoid drawing anything pink that isn't actually held down right now // so we make an AND adapter and combine it using immediate & sticky var autoString = MakeStringFor(Global.StickyXORAdapter.Source.Xor(Global.AutofireStickyXORAdapter).And(Global.AutofireStickyXORAdapter)); - g.DrawString(autoString, MessageFont, autoColor, x, y); + g.DrawString(autoString, MessageFont, autoColor, point.X, point.Y); //recolor everything that's changed from the previous input var immediateOverlay = MakeIntersectImmediatePrevious(); - g.DrawString(immediateOverlay, MessageFont, changedColor, x, y); + g.DrawString(immediateOverlay, MessageFont, changedColor, point.X, point.Y); } } if (Global.MovieSession.MultiTrack.IsActive) { - float x = GetX(g, Global.Config.DispMultix, Global.Config.DispMultianchor, Global.MovieSession.MultiTrack.Status); - float y = GetY(g, Global.Config.DispMultiy, Global.Config.DispMultianchor, Global.MovieSession.MultiTrack.Status); - - DrawOsdMessage(g, Global.MovieSession.MultiTrack.Status, FixedMessagesColor, x, y); + var point = GetCoordinates(g, Global.Config.MultitrackRecorder, Global.MovieSession.MultiTrack.Status); + DrawOsdMessage(g, Global.MovieSession.MultiTrack.Status, FixedMessagesColor, point.X, point.Y); } if (Global.Config.DisplayFPS && Fps != null) { - float x = GetX(g, Global.Config.DispFPSx, Global.Config.DispFPSanchor, Fps); - float y = GetY(g, Global.Config.DispFPSy, Global.Config.DispFPSanchor, Fps); - - DrawOsdMessage(g, Fps, FixedMessagesColor, x, y); + var point = GetCoordinates(g, Global.Config.Fps, Fps); + DrawOsdMessage(g, Fps, FixedMessagesColor, point.X, point.Y); } if (Global.Config.DisplayLagCounter && Global.Emulator.CanPollInput()) { var counter = Global.Emulator.AsInputPollable().LagCount.ToString(); - var x = GetX(g, Global.Config.DispLagx, Global.Config.DispLaganchor, counter); - var y = GetY(g, Global.Config.DispLagy, Global.Config.DispLaganchor, counter); - - DrawOsdMessage(g, counter, FixedAlertMessageColor, x, y); + var point = GetCoordinates(g, Global.Config.LagCounter, counter); + DrawOsdMessage(g, counter, FixedAlertMessageColor, point.X, point.Y); } if (Global.Config.DisplayRerecordCount) { string rerecordCount = MakeRerecordCount(); - float x = GetX(g, Global.Config.DispRecx, Global.Config.DispRecanchor, rerecordCount); - float y = GetY(g, Global.Config.DispRecy, Global.Config.DispRecanchor, rerecordCount); - - DrawOsdMessage(g, rerecordCount, FixedMessagesColor, x, y); + var point = GetCoordinates(g, Global.Config.ReRecordCounter, rerecordCount); + DrawOsdMessage(g, rerecordCount, FixedMessagesColor, point.X, point.Y); } if (Global.ClientControls["Autohold"] || Global.ClientControls["Autofire"]) @@ -411,16 +360,11 @@ namespace BizHawk.Client.EmuHawk } var message = sb.ToString(); - - g.DrawString( - message, - MessageFont, - Color.White, - GetX(g, Global.Config.DispAutoholdx, Global.Config.DispAutoholdanchor, message), - GetY(g, Global.Config.DispAutoholdy, Global.Config.DispAutoholdanchor, message)); + var point = GetCoordinates(g, Global.Config.Autohold, message); + g.DrawString(message, MessageFont, Color.White, point.X, point.Y); } - if (Global.MovieSession.Movie.IsActive && Global.Config.DisplaySubtitles) + if (Global.MovieSession.Movie.IsActive() && Global.Config.DisplaySubtitles) { var subList = Global.MovieSession.Movie.Subtitles.GetSubtitles(Global.Emulator.Frame); diff --git a/BizHawk.Client.EmuHawk/Extensions/CoreExtensions.cs b/BizHawk.Client.EmuHawk/Extensions/CoreExtensions.cs index 23b8af1fe1..9da20f852f 100644 --- a/BizHawk.Client.EmuHawk/Extensions/CoreExtensions.cs +++ b/BizHawk.Client.EmuHawk/Extensions/CoreExtensions.cs @@ -1,5 +1,5 @@ using System.Drawing; - +using BizHawk.Client.Common; using BizHawk.Emulation.Common; using BizHawk.Emulation.Common.IEmulatorExtensions; @@ -10,6 +10,7 @@ using BizHawk.Emulation.Cores.Nintendo.SNES9X; using BizHawk.Emulation.Cores.Consoles.Sega.gpgx; using BizHawk.Emulation.Cores.Sony.PSP; using BizHawk.Emulation.Cores.Arcades.MAME; +using BizHawk.Emulation.Cores.Sega.MasterSystem; namespace BizHawk.Client.EmuHawk.CoreExtensions { @@ -71,5 +72,99 @@ namespace BizHawk.Client.EmuHawk.CoreExtensions return str; } + + public static SystemInfo System(this IEmulator emulator) + { + switch (emulator.SystemId) + { + default: + case "NULL": + return SystemInfo.Null; + case "NES": + return SystemInfo.Nes; + case "INTV": + return SystemInfo.Intellivision; + case "SG": + return SystemInfo.SG; + case "SMS": + if (emulator is SMS gg && gg.IsGameGear) + { + return SystemInfo.GG; + } + + if (emulator is SMS sg && sg.IsSG1000) + { + return SystemInfo.SG; + } + + return SystemInfo.SMS; + case "PCECD": + return SystemInfo.PCECD; + case "PCE": + return SystemInfo.PCE; + case "SGX": + return SystemInfo.SGX; + case "GEN": + return SystemInfo.Genesis; + case "TI83": + return SystemInfo.TI83; + case "SNES": + return SystemInfo.SNES; + case "GB": + /* + if ((Emulator as IGameboyCommon).IsCGBMode()) + { + return SystemInfo.GBC; + } + */ + return SystemInfo.GB; + case "A26": + return SystemInfo.Atari2600; + case "A78": + return SystemInfo.Atari7800; + case "C64": + return SystemInfo.C64; + case "Coleco": + return SystemInfo.Coleco; + case "GBA": + return SystemInfo.GBA; + case "N64": + return SystemInfo.N64; + case "SAT": + return SystemInfo.Saturn; + case "DGB": + return SystemInfo.DualGB; + case "GB3x": + return SystemInfo.GB3x; + case "GB4x": + return SystemInfo.GB4x; + case "WSWAN": + return SystemInfo.WonderSwan; + case "Lynx": + return SystemInfo.Lynx; + case "PSX": + return SystemInfo.PSX; + case "AppleII": + return SystemInfo.AppleII; + case "Libretro": + return SystemInfo.Libretro; + case "VB": + return SystemInfo.VirtualBoy; + case "VEC": + return SystemInfo.Vectrex; + case "NGP": + return SystemInfo.NeoGeoPocket; + case "ZXSpectrum": + return SystemInfo.ZxSpectrum; + case "AmstradCPC": + return SystemInfo.AmstradCpc; + case "ChannelF": + return SystemInfo.ChannelF; + case "O2": + return SystemInfo.O2; + case "MAME": + return SystemInfo.Mame; + } + } } } diff --git a/BizHawk.Client.EmuHawk/GLManager.cs b/BizHawk.Client.EmuHawk/GLManager.cs index f22433bc54..547496936f 100644 --- a/BizHawk.Client.EmuHawk/GLManager.cs +++ b/BizHawk.Client.EmuHawk/GLManager.cs @@ -1,6 +1,7 @@ using System; using BizHawk.Bizware.BizwareGL; - +using BizHawk.Bizware.BizwareGL.Drivers.OpenTK; +using BizHawk.Bizware.BizwareGL.Drivers.SlimDX; namespace BizHawk.Client.EmuHawk { @@ -11,7 +12,6 @@ namespace BizHawk.Client.EmuHawk { private GLManager() { - } public void Dispose() @@ -20,28 +20,26 @@ namespace BizHawk.Client.EmuHawk public static GLManager Instance { get; private set; } - Bizware.BizwareGL.Drivers.OpenTK.IGL_TK MainContext; - - public static void CreateInstance(Bizware.BizwareGL.Drivers.OpenTK.IGL_TK mainContext) + public static void CreateInstance() { - if (Instance != null) throw new InvalidOperationException($"Attempted to create more than one {nameof(GLManager)}"); + if (Instance != null) + { + throw new InvalidOperationException($"Attempted to create more than one {nameof(GLManager)}"); + } + Instance = new GLManager(); - Instance.MainContext = mainContext; } public void ReleaseGLContext(object o) { - ContextRef cr = (ContextRef)o; - cr.gl.Dispose(); + var cr = (ContextRef)o; + cr.GL.Dispose(); } - //[System.Runtime.InteropServices.DllImport("opengl32.dll")] - //bool wglShareLists(IntPtr hglrc1, IntPtr hglrc2); - - public ContextRef CreateGLContext(int major_version, int minor_version, bool forward_compatible) + public ContextRef CreateGLContext(int majorVersion, int minorVersion, bool forwardCompatible) { - var gl = new Bizware.BizwareGL.Drivers.OpenTK.IGL_TK(major_version, minor_version, forward_compatible); - var ret = new ContextRef { gl = gl }; + var gl = new IGL_TK(majorVersion, minorVersion, forwardCompatible); + var ret = new ContextRef { GL = gl }; return ret; } @@ -49,27 +47,16 @@ namespace BizHawk.Client.EmuHawk { return new ContextRef { - gc = gc, - gl = gc.IGL + Gc = gc, + GL = gc.IGL }; } - /// - /// This might not be a GL implementation. If it isnt GL, then setting it as active context is just NOP - /// - public ContextRef GetContextForIGL(IGL gl) - { - return new ContextRef - { - gl = gl - }; - } - - ContextRef ActiveContext; + private ContextRef _activeContext; public void Invalidate() { - ActiveContext = null; + _activeContext = null; } public void Activate(ContextRef cr) @@ -77,26 +64,32 @@ namespace BizHawk.Client.EmuHawk bool begun = false; //this needs a begin signal to set the swap chain to the next backbuffer - if (cr.gl is BizHawk.Bizware.BizwareGL.Drivers.SlimDX.IGL_SlimDX9) + if (cr.GL is IGL_SlimDX9) { - cr.gc.Begin(); + cr.Gc.Begin(); begun = true; } - if (cr == ActiveContext) + if (cr == _activeContext) + { return; + } - ActiveContext = cr; - if (cr.gc != null) + _activeContext = cr; + if (cr.Gc != null) { //TODO - this is checking the current context inside to avoid an extra NOP context change. make this optional or remove it, since we're tracking it here - if(!begun) - cr.gc.Begin(); + if (!begun) + { + cr.Gc.Begin(); + } } - else if (cr.gl != null) + else { - if(cr.gl is BizHawk.Bizware.BizwareGL.Drivers.OpenTK.IGL_TK) - ((BizHawk.Bizware.BizwareGL.Drivers.OpenTK.IGL_TK)cr.gl).MakeDefaultCurrent(); + if (cr.GL is IGL_TK tk) + { + tk.MakeDefaultCurrent(); + } } } @@ -107,8 +100,8 @@ namespace BizHawk.Client.EmuHawk public class ContextRef { - public IGL gl; - public GraphicsControl gc; + public IGL GL { get; set; } + public GraphicsControl Gc { get; set; } } } } \ No newline at end of file diff --git a/BizHawk.Client.EmuHawk/GlobalWin.cs b/BizHawk.Client.EmuHawk/GlobalWin.cs index fa26cc5d71..2c2d78f161 100644 --- a/BizHawk.Client.EmuHawk/GlobalWin.cs +++ b/BizHawk.Client.EmuHawk/GlobalWin.cs @@ -1,5 +1,4 @@ using BizHawk.Bizware.BizwareGL; -using BizHawk.Client.ApiHawk; // ReSharper disable StyleCop.SA1401 namespace BizHawk.Client.EmuHawk @@ -8,7 +7,6 @@ namespace BizHawk.Client.EmuHawk { public static MainForm MainForm; public static ToolManager Tools; - public static BasicApiProvider ApiProvider; /// /// the IGL to be used for rendering diff --git a/BizHawk.Client.EmuHawk/JumpLists.cs b/BizHawk.Client.EmuHawk/JumpLists.cs index d36aabdb3f..d13c3caae7 100644 --- a/BizHawk.Client.EmuHawk/JumpLists.cs +++ b/BizHawk.Client.EmuHawk/JumpLists.cs @@ -1,7 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.IO; using System.Reflection; @@ -9,54 +6,60 @@ namespace BizHawk.Client.EmuHawk { public class JumpLists { - static readonly Assembly PresentationFramework; - static Type Application; - static Type JumpList; - static Type JumpTask; + private static readonly Type JumpList; + private static readonly Type JumpTask; - static object _app; static JumpLists() { try { - PresentationFramework = Assembly.Load("PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); - Application = PresentationFramework.GetType("System.Windows.Application"); - JumpList = PresentationFramework.GetType("System.Windows.Shell.JumpList"); - JumpTask = PresentationFramework.GetType("System.Windows.Shell.JumpTask"); - _app = Activator.CreateInstance(Application); + var presentationFramework = + Assembly.Load( + "PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); + var application = presentationFramework.GetType("System.Windows.Application"); + JumpList = presentationFramework.GetType("System.Windows.Shell.JumpList"); + JumpTask = presentationFramework.GetType("System.Windows.Shell.JumpTask"); + var app = Activator.CreateInstance(application); dynamic jmp = Activator.CreateInstance(JumpList); jmp.ShowRecentCategory = true; - JumpList.GetMethod("SetJumpList").Invoke(null, new[] { _app, jmp }); + JumpList + .GetMethod("SetJumpList") + ?.Invoke(null, new[] {app, jmp}); + } + catch + { + // Do nothing } - catch { } } /// /// add an item to the W7+ jumplist /// - /// fully qualified path, can include '|' character for archives - public static void AddRecentItem(string fullpath, string title) + /// fully qualified path, can include '|' character for archives + /// The text displayed in the jumplist entry + public static void AddRecentItem(string fullPath, string title) { - //string title; - //if (fullpath.Contains('|')) - // title = fullpath.Split('|')[1]; - //else - // title = Path.GetFileName(fullpath); try { - string exepath = Assembly.GetEntryAssembly().Location; + string execPath = Assembly.GetEntryAssembly() + ?.Location; dynamic ji = Activator.CreateInstance(JumpTask); - ji.ApplicationPath = exepath; - ji.Arguments = $"\"{fullpath}\""; + ji.ApplicationPath = execPath; + ji.Arguments = $"\"{fullPath}\""; ji.Title = title; // for some reason, this doesn't work - ji.WorkingDirectory = Path.GetDirectoryName(exepath); + ji.WorkingDirectory = Path.GetDirectoryName(execPath); - JumpList.GetMethod("AddToRecentCategory", new[] { JumpTask }).Invoke(null, new[] { ji }); + JumpList + .GetMethod("AddToRecentCategory", new[] {JumpTask}) + ?.Invoke(null, new[] {ji}); + } + catch + { + // Do nothing } - catch { } } } } diff --git a/BizHawk.Client.EmuHawk/LogConsole.cs b/BizHawk.Client.EmuHawk/LogConsole.cs index 92d54f4c68..7e49b26809 100644 --- a/BizHawk.Client.EmuHawk/LogConsole.cs +++ b/BizHawk.Client.EmuHawk/LogConsole.cs @@ -6,55 +6,39 @@ using System.Runtime.InteropServices; using BizHawk.Common; using BizHawk.Client.Common; -#pragma warning disable 162 - -//thanks! - http://sharp-developer.net/ru/CodeBank/WinForms/GuiConsole.aspx - -//todo - quit using Console.WriteLine (well, we can leave it hooked up as a backstop) -//use a different method instead, so we can collect unicode data -//also, collect log data independently of whether the log window is open -//we also need to dice it into lines so that we can have a backlog policy +// thanks! - http://sharp-developer.net/ru/CodeBank/WinForms/GuiConsole.aspx +// todo - quit using Console.WriteLine (well, we can leave it hooked up as a backstop) +// use a different method instead, so we can collect unicode data +// also, collect log data independently of whether the log window is open +// we also need to dice it into lines so that we can have a backlog policy namespace BizHawk.Client.EmuHawk { - static class LogConsole + internal static class LogConsole { - public static bool ConsoleVisible - { - get; - private set; - } + public static bool ConsoleVisible { get; private set; } - static LogWindow window; - static LogStream logStream; - static bool NeedToRelease; + private static LogWindow _window; + private static LogStream _logStream; + private static bool _needToRelease; - class LogStream : Stream + private class LogStream : Stream { - public override bool CanRead { get { return false; } } - public override bool CanSeek { get { return false; } } - public override bool CanWrite { get { return true; } } + public override bool CanRead => false; + public override bool CanSeek => false; + public override bool CanWrite => true; public override void Flush() { //TODO - maybe this will help with decoding } - public override long Length - { - get { throw new NotImplementedException(); } - } + public override long Length => throw new NotImplementedException(); public override long Position { - get - { - throw new NotImplementedException(); - } - set - { - throw new NotImplementedException(); - } + get => throw new NotImplementedException(); + set => throw new NotImplementedException(); } public override int Read(byte[] buffer, int offset, int count) @@ -77,18 +61,16 @@ namespace BizHawk.Client.EmuHawk //TODO - buffer undecoded characters (this may be important) //(use decoder = System.Text.Encoding.Unicode.GetDecoder()) string str = Encoding.ASCII.GetString(buffer, offset, count); - if (Emit != null) - Emit(str); + Emit?.Invoke(str); } public Action Emit; } - static string SkipEverythingButProgramInCommandLine(string cmdLine) { - //skip past the program name. can anyone think of a better way to do this? - //we could use CommandLineToArgvW (commented out below) but then we would just have to re-assemble and potentially re-quote it + // skip past the program name. can anyone think of a better way to do this? + // we could use CommandLineToArgvW (commented out below) but then we would just have to re-assemble and potentially re-quote it int childCmdLine = 0; int lastSlash = 0; int lastGood = 0; @@ -100,7 +82,10 @@ namespace BizHawk.Client.EmuHawk if (childCmdLine == cmdLine.Length) break; bool thisIsQuote = (cur == '\"'); if (cur == '\\' || cur == '/') + { lastSlash = childCmdLine; + } + if (quote) { if (thisIsQuote) @@ -121,10 +106,10 @@ namespace BizHawk.Client.EmuHawk return $"{path} {remainder}"; } - static IntPtr oldOut, conOut; - static bool hasConsole; - static bool attachedConsole; - static bool shouldRedirectStdout; + private static IntPtr oldOut, conOut; + private static bool hasConsole; + private static bool attachedConsole; + private static bool shouldRedirectStdout; public static void CreateConsole() { //(see desmume for the basis of some of this logic) @@ -135,7 +120,7 @@ namespace BizHawk.Client.EmuHawk if (oldOut == IntPtr.Zero) oldOut = ConsoleImports.GetStdHandle( -11 ); //STD_OUTPUT_HANDLE - ConsoleImports.FileType fileType = ConsoleImports.GetFileType(oldOut); + var fileType = ConsoleImports.GetFileType(oldOut); //stdout is already connected to something. keep using it and dont let the console interfere shouldRedirectStdout = (fileType == ConsoleImports.FileType.FileTypeUnknown || fileType == ConsoleImports.FileType.FileTypePipe); @@ -143,7 +128,7 @@ namespace BizHawk.Client.EmuHawk //attach to an existing console attachedConsole = false; - //ever since a recent KB, XP-based systems glitch out when attachconsole is called and theres no console to attach to. + //ever since a recent KB, XP-based systems glitch out when attachconsole is called and there's no console to attach to. if (Environment.OSVersion.Version.Major != 5) { if (ConsoleImports.AttachConsole(-1)) @@ -164,10 +149,12 @@ namespace BizHawk.Client.EmuHawk hasConsole = true; } else + { System.Windows.Forms.MessageBox.Show($"Couldn't allocate win32 console: {Marshal.GetLastWin32Error()}"); + } } - if(hasConsole) + if (hasConsole) { IntPtr ptr = ConsoleImports.GetCommandLine(); string commandLine = Marshal.PtrToStringAuto(ptr); @@ -195,7 +182,19 @@ namespace BizHawk.Client.EmuHawk static void ReleaseConsole() { if (!hasConsole) + { return; + } + + if (shouldRedirectStdout) + { + ConsoleImports.CloseHandle(conOut); + } + + if (!attachedConsole) + { + ConsoleImports.FreeConsole(); + } if(shouldRedirectStdout) ConsoleImports.CloseHandle(conOut); if(!attachedConsole) ConsoleImports.FreeConsole(); @@ -209,11 +208,15 @@ namespace BizHawk.Client.EmuHawk /// pops the console in front of the main window (where it should probably go after booting up the game). /// maybe this should be optional, or maybe we can somehow position the console sensibly. /// sometimes it annoys me, but i really need it on top while debugging or else i will be annoyed. - /// best of all would be to position it beneath the bizhawk main window somehow. + /// best of all would be to position it beneath the BizHawk main window somehow. /// public static void PositionConsole() { - if (ConsoleVisible == false) return; + if (ConsoleVisible == false) + { + return; + } + if (Global.Config.WIN32_CONSOLE) { IntPtr x = ConsoleImports.GetConsoleWindow(); @@ -228,61 +231,58 @@ namespace BizHawk.Client.EmuHawk if (Global.Config.WIN32_CONSOLE) { - NeedToRelease = true; + _needToRelease = true; CreateConsole(); - //not sure whether we need to set a buffer size here - //var sout = new StreamWriter(Console.OpenStandardOutput(),Encoding.ASCII,1) { AutoFlush = true }; - //var sout = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true }; - //Console.SetOut(sout); - //Console.Title = "BizHawk Message Log"; - //System.Runtime.InteropServices.SafeFi - //new Microsoft.Win32.SafeHandles.SafeFileHandle( } else { - logStream = new LogStream(); - Log.HACK_LOG_STREAM = logStream; - var sout = new StreamWriter(logStream) { AutoFlush = true }; - new StringBuilder(); //not using this right now - Console.SetOut(sout); - window = new LogWindow(); - window.Show(); - logStream.Emit = (str) => { window.Append(str); }; + _logStream = new LogStream(); + Log.HACK_LOG_STREAM = _logStream; + Console.SetOut(new StreamWriter(_logStream) { AutoFlush = true }); + _window = new LogWindow(); + _window.Show(); + _logStream.Emit = str => { _window.Append(str); }; } } public static void HideConsole() { - if (ConsoleVisible == false) return; + if (ConsoleVisible == false) + { + return; + } + Console.SetOut(TextWriter.Null); ConsoleVisible = false; - if (NeedToRelease) + if (_needToRelease) { ReleaseConsole(); - NeedToRelease = false; + _needToRelease = false; } else { - logStream.Close(); - logStream = null; + _logStream.Close(); + _logStream = null; Log.HACK_LOG_STREAM = null; - window.Close(); - window = null; + _window.Close(); + _window = null; } } - public static void notifyLogWindowClosing() + public static void NotifyLogWindowClosing() { Console.SetOut(TextWriter.Null); ConsoleVisible = false; - if(logStream != null) logStream.Close(); + _logStream?.Close(); Log.HACK_LOG_STREAM = null; } public static void SaveConfigSettings() { - if (window != null && window.IsHandleCreated) - window.SaveConfigSettings(); + if (_window != null && _window.IsHandleCreated) + { + _window.SaveConfigSettings(); + } } } } diff --git a/BizHawk.Client.EmuHawk/LogWindow.cs b/BizHawk.Client.EmuHawk/LogWindow.cs index ad2084337d..294f1f3fb2 100644 --- a/BizHawk.Client.EmuHawk/LogWindow.cs +++ b/BizHawk.Client.EmuHawk/LogWindow.cs @@ -26,7 +26,7 @@ namespace BizHawk.Client.EmuHawk { Global.Config.ShowLogWindow = false; GlobalWin.MainForm.NotifyLogWindowClosing(); - LogConsole.notifyLogWindowClosing(); + LogConsole.NotifyLogWindowClosing(); SaveConfigSettings(); }; ListView_ClientSizeChanged(null, null); diff --git a/BizHawk.Client.EmuHawk/MainForm.Events.cs b/BizHawk.Client.EmuHawk/MainForm.Events.cs index ca599666b6..d318625388 100644 --- a/BizHawk.Client.EmuHawk/MainForm.Events.cs +++ b/BizHawk.Client.EmuHawk/MainForm.Events.cs @@ -237,12 +237,12 @@ namespace BizHawk.Client.EmuHawk private void MovieSubMenu_DropDownOpened(object sender, EventArgs e) { FullMovieLoadstatesMenuItem.Enabled = !MovieSession.MultiTrack.IsActive; - StopMovieWithoutSavingMenuItem.Enabled = MovieSession.Movie.IsActive && MovieSession.Movie.Changes; + StopMovieWithoutSavingMenuItem.Enabled = MovieSession.Movie.IsActive() && MovieSession.Movie.Changes; StopMovieMenuItem.Enabled = PlayFromBeginningMenuItem.Enabled = SaveMovieMenuItem.Enabled = SaveMovieAsMenuItem.Enabled - = MovieSession.Movie.IsActive; + = MovieSession.Movie.IsActive(); ReadonlyMenuItem.Checked = MovieSession.ReadOnly; AutomaticallyBackupMoviesMenuItem.Checked = Config.EnableBackupMovies; @@ -684,11 +684,11 @@ namespace BizHawk.Client.EmuHawk { PauseMenuItem.Checked = _didMenuPause ? _wasPaused : EmulatorPaused; - SoftResetMenuItem.Enabled = Emulator.ControllerDefinition.BoolButtons.Contains("Reset") && - (!MovieSession.Movie.IsPlaying || MovieSession.Movie.IsFinished); + SoftResetMenuItem.Enabled = Emulator.ControllerDefinition.BoolButtons.Contains("Reset") + && MovieSession.Movie.Mode != MovieMode.Play; - HardResetMenuItem.Enabled = Emulator.ControllerDefinition.BoolButtons.Contains("Power") && - (!MovieSession.Movie.IsPlaying || MovieSession.Movie.IsFinished); + HardResetMenuItem.Enabled = Emulator.ControllerDefinition.BoolButtons.Contains("Power") + && MovieSession.Movie.Mode != MovieMode.Play;; PauseMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Pause"].Bindings; RebootCoreMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Reboot Core"].Bindings; @@ -994,7 +994,7 @@ namespace BizHawk.Client.EmuHawk private void MessagesMenuItem_Click(object sender, EventArgs e) { - using var form = new MessageConfig(); + using var form = new MessageConfig(Config); var result = form.ShowDialog(); AddOnScreenMessage(result.IsOk() ? "Message settings saved" @@ -1012,8 +1012,14 @@ namespace BizHawk.Client.EmuHawk using var form = new SoundConfig(Config); if (form.ShowDialog().IsOk()) { + Sound.StartSound(); + AddOnScreenMessage("Sound settings saved"); RewireSound(); } + else + { + AddOnScreenMessage("Sound config aborted"); + } } private void AutofireMenuItem_Click(object sender, EventArgs e) @@ -1546,10 +1552,10 @@ namespace BizHawk.Client.EmuHawk NESSoundChannelsMenuItem.Enabled = Tools.IsAvailable(); MovieSettingsMenuItem.Enabled = (Emulator is NES || Emulator is SubNESHawk) - && !MovieSession.Movie.IsActive; + && !MovieSession.Movie.IsActive(); NesControllerSettingsMenuItem.Enabled = Tools.IsAvailable() - && !MovieSession.Movie.IsActive; + && !MovieSession.Movie.IsActive(); barcodeReaderToolStripMenuItem.Enabled = ServiceInjector.IsAvailable(Emulator.ServiceProvider, typeof(BarcodeEntry)); @@ -1600,12 +1606,12 @@ namespace BizHawk.Client.EmuHawk { if (Emulator is NES nes) { - using var form = new NESGraphicsConfig(this, nes.GetSettings().Clone()); + using var form = new NESGraphicsConfig(this, Config, nes.GetSettings().Clone()); form.ShowDialog(this); } else if (Emulator is SubNESHawk sub) { - using var form = new NESGraphicsConfig(this, sub.GetSettings().Clone()); + using var form = new NESGraphicsConfig(this, Config, sub.GetSettings().Clone()); form.ShowDialog(this); } else if (Emulator is QuickNES quickNes) @@ -1636,7 +1642,7 @@ namespace BizHawk.Client.EmuHawk private void FdsEjectDiskMenuItem_Click(object sender, EventArgs e) { - if (!MovieSession.Movie.IsPlaying || MovieSession.Movie.IsFinished) + if (MovieSession.Movie.Mode != MovieMode.Play) { ClickyVirtualPadController.Click("FDS Eject"); AddOnScreenMessage("FDS disk ejected."); @@ -1648,7 +1654,7 @@ namespace BizHawk.Client.EmuHawk if (Emulator is NES nes && nes.IsVS || Emulator is SubNESHawk sub && sub.IsVs) { - if (!MovieSession.Movie.IsPlaying || MovieSession.Movie.IsFinished) + if (MovieSession.Movie.Mode != MovieMode.Play) { ClickyVirtualPadController.Click("Insert Coin P1"); AddOnScreenMessage("P1 Coin Inserted"); @@ -1661,7 +1667,7 @@ namespace BizHawk.Client.EmuHawk if (Emulator is NES nes && nes.IsVS || Emulator is SubNESHawk sub && sub.IsVs) { - if (!MovieSession.Movie.IsPlaying || MovieSession.Movie.IsFinished) + if (MovieSession.Movie.Mode != MovieMode.Play) { ClickyVirtualPadController.Click("Insert Coin P2"); AddOnScreenMessage("P2 Coin Inserted"); @@ -1674,7 +1680,7 @@ namespace BizHawk.Client.EmuHawk if (Emulator is NES nes && nes.IsVS || Emulator is SubNESHawk sub && sub.IsVs) { - if (!MovieSession.Movie.IsPlaying || MovieSession.Movie.IsFinished) + if (MovieSession.Movie.Mode != MovieMode.Play) { ClickyVirtualPadController.Click("Service Switch"); AddOnScreenMessage("Service Switch Pressed"); @@ -1728,8 +1734,7 @@ namespace BizHawk.Client.EmuHawk { var s = ((PCEngine)Emulator).GetSettings(); - PceControllerSettingsMenuItem.Enabled = !MovieSession.Movie.IsActive; - + PceControllerSettingsMenuItem.Enabled = MovieSession.Movie.NotActive(); PCEAlwaysPerformSpriteLimitMenuItem.Checked = s.SpriteLimit; PCEAlwaysEqualizeVolumesMenuItem.Checked = s.EqualizeVolume; PCEArcadeCardRewindEnableMenuItem.Checked = s.ArcadeCardRewindHack; @@ -2082,8 +2087,9 @@ namespace BizHawk.Client.EmuHawk private void A7800SubMenu_DropDownOpened(object sender, EventArgs e) { - A7800ControllerSettingsMenuItem.Enabled = !MovieSession.Movie.IsActive; - A7800FilterSettingsMenuItem.Enabled = !MovieSession.Movie.IsActive; + A7800ControllerSettingsMenuItem.Enabled + = A7800FilterSettingsMenuItem.Enabled + = MovieSession.Movie.NotActive(); } private void A7800ControllerSettingsToolStripMenuItem_Click(object sender, EventArgs e) @@ -2189,7 +2195,7 @@ namespace BizHawk.Client.EmuHawk private void PSXSubMenu_DropDownOpened(object sender, EventArgs e) { - PSXControllerSettingsMenuItem.Enabled = !MovieSession.Movie.IsActive; + PSXControllerSettingsMenuItem.Enabled = MovieSession.Movie.NotActive(); } private void PSXControllerSettingsMenuItem_Click(object sender, EventArgs e) @@ -2239,7 +2245,7 @@ namespace BizHawk.Client.EmuHawk SnesGBInSGBMenuItem.Visible = false; } - SNESControllerConfigurationMenuItem.Enabled = !MovieSession.Movie.IsActive; + SNESControllerConfigurationMenuItem.Enabled = MovieSession.Movie.NotActive(); SnesGfxDebuggerMenuItem.Enabled = !OSTailoredCode.IsUnixHost; } @@ -2290,7 +2296,7 @@ namespace BizHawk.Client.EmuHawk var ss = ((ColecoVision)Emulator).GetSyncSettings(); ColecoSkipBiosMenuItem.Checked = ss.SkipBiosIntro; ColecoUseSGMMenuItem.Checked = ss.UseSGM; - ColecoControllerSettingsMenuItem.Enabled = !MovieSession.Movie.IsActive; + ColecoControllerSettingsMenuItem.Enabled = MovieSession.Movie.NotActive(); } private void ColecoSkipBiosMenuItem_Click(object sender, EventArgs e) @@ -2324,8 +2330,8 @@ namespace BizHawk.Client.EmuHawk { N64PluginSettingsMenuItem.Enabled = N64ControllerSettingsMenuItem.Enabled = - N64ExpansionSlotMenuItem.Enabled = - !MovieSession.Movie.IsActive; + N64ExpansionSlotMenuItem.Enabled = + MovieSession.Movie.NotActive(); N64CircularAnalogRangeMenuItem.Checked = Config.N64UseCircularAnalogConstraint; @@ -2578,7 +2584,7 @@ namespace BizHawk.Client.EmuHawk private void IntVSubMenu_DropDownOpened(object sender, EventArgs e) { - IntVControllerSettingsMenuItem.Enabled = !MovieSession.Movie.IsActive; + IntVControllerSettingsMenuItem.Enabled = MovieSession.Movie.NotActive(); } private void IntVControllerSettingsMenuItem_Click(object sender, EventArgs e) @@ -2969,7 +2975,7 @@ namespace BizHawk.Client.EmuHawk RecordMovieContextMenuItem.Visible = PlayMovieContextMenuItem.Visible = LoadLastMovieContextMenuItem.Visible = - !Emulator.IsNull() && !MovieSession.Movie.IsActive; + !Emulator.IsNull() && MovieSession.Movie.NotActive(); RestartMovieContextMenuItem.Visible = StopMovieContextMenuItem.Visible = @@ -2977,13 +2983,13 @@ namespace BizHawk.Client.EmuHawk ViewCommentsContextMenuItem.Visible = SaveMovieContextMenuItem.Visible = SaveMovieAsContextMenuItem.Visible = - MovieSession.Movie.IsActive; + MovieSession.Movie.IsActive(); - BackupMovieContextMenuItem.Visible = MovieSession.Movie.IsActive; + BackupMovieContextMenuItem.Visible = MovieSession.Movie.IsActive(); - StopNoSaveContextMenuItem.Visible = MovieSession.Movie.IsActive && MovieSession.Movie.Changes; + StopNoSaveContextMenuItem.Visible = MovieSession.Movie.IsActive() && MovieSession.Movie.Changes; - AddSubtitleContextMenuItem.Visible = !Emulator.IsNull() && MovieSession.Movie.IsActive && !MovieSession.ReadOnly; + AddSubtitleContextMenuItem.Visible = !Emulator.IsNull() && MovieSession.Movie.IsActive() && !MovieSession.ReadOnly; ConfigContextMenuItem.Visible = _inFullscreen; @@ -2994,7 +3000,7 @@ namespace BizHawk.Client.EmuHawk LoadLastRomContextMenuItem.Enabled = !Config.RecentRoms.Empty; LoadLastMovieContextMenuItem.Enabled = !Config.RecentMovies.Empty; - if (MovieSession.Movie.IsActive) + if (MovieSession.Movie.IsActive()) { if (MovieSession.ReadOnly) { @@ -3094,7 +3100,7 @@ namespace BizHawk.Client.EmuHawk private void ViewSubtitlesContextMenuItem_Click(object sender, EventArgs e) { - if (MovieSession.Movie.IsActive) + if (MovieSession.Movie.IsActive()) { using var form = new EditSubtitlesForm { ReadOnly = MovieSession.ReadOnly }; form.GetMovie(MovieSession.Movie); @@ -3140,7 +3146,7 @@ namespace BizHawk.Client.EmuHawk private void ViewCommentsContextMenuItem_Click(object sender, EventArgs e) { - if (MovieSession.Movie.IsActive) + if (MovieSession.Movie.IsActive()) { using var form = new EditCommentsForm(); form.GetMovie(MovieSession.Movie); @@ -3247,7 +3253,7 @@ namespace BizHawk.Client.EmuHawk private void LinkConnectStatusBarButton_Click(object sender, EventArgs e) { // toggle Link status (only outside of a movie session) - if (!MovieSession.Movie.IsPlaying || MovieSession.Movie.IsFinished) + if (MovieSession.Movie.Mode != MovieMode.Play) { Emulator.AsLinkable().LinkConnected ^= true; Console.WriteLine("Cable connect status to {0}", Emulator.AsLinkable().LinkConnected); diff --git a/BizHawk.Client.EmuHawk/MainForm.Movie.cs b/BizHawk.Client.EmuHawk/MainForm.Movie.cs index 9ec784a65a..cd860fdf41 100644 --- a/BizHawk.Client.EmuHawk/MainForm.Movie.cs +++ b/BizHawk.Client.EmuHawk/MainForm.Movie.cs @@ -14,7 +14,7 @@ namespace BizHawk.Client.EmuHawk { // SuuperW: Check changes. adelikat: this could break bk2 movies // TODO: Clean up the saving process - if (movie.IsActive && (movie.Changes || !(movie is TasMovie))) + if (movie.IsActive() && (movie.Changes || !(movie is TasMovie))) { movie.Save(); } @@ -98,19 +98,19 @@ namespace BizHawk.Client.EmuHawk public void SetMainformMovieInfo() { - if (MovieSession.Movie.IsPlaying) + if (MovieSession.Movie.IsPlaying()) { PlayRecordStatusButton.Image = Properties.Resources.Play; PlayRecordStatusButton.ToolTipText = "Movie is in playback mode"; PlayRecordStatusButton.Visible = true; } - else if (MovieSession.Movie.IsRecording) + else if (MovieSession.Movie.IsRecording()) { PlayRecordStatusButton.Image = Properties.Resources.RecordHS; PlayRecordStatusButton.ToolTipText = "Movie is in record mode"; PlayRecordStatusButton.Visible = true; } - else if (!MovieSession.Movie.IsActive) + else if (!MovieSession.Movie.IsActive()) { PlayRecordStatusButton.Image = Properties.Resources.Blank; PlayRecordStatusButton.ToolTipText = "No movie is active"; @@ -129,7 +129,7 @@ namespace BizHawk.Client.EmuHawk } else { - if (MovieSession.Movie.IsActive) + if (MovieSession.Movie.IsActive()) { StartNewMovie(MovieSession.Movie, false); AddOnScreenMessage("Replaying movie file in read-only mode"); diff --git a/BizHawk.Client.EmuHawk/MainForm.cs b/BizHawk.Client.EmuHawk/MainForm.cs index 2d4724b920..aaa794cc7a 100644 --- a/BizHawk.Client.EmuHawk/MainForm.cs +++ b/BizHawk.Client.EmuHawk/MainForm.cs @@ -356,7 +356,7 @@ namespace BizHawk.Client.EmuHawk Sound.StartSound(); InputManager.RewireInputChain(); - GlobalWin.Tools = new ToolManager(this); + GlobalWin.Tools = new ToolManager(this, Config, Emulator); RewireSound(); // Workaround for windows, location is -32000 when minimized, if they close it during this time, that's what gets saved @@ -1010,14 +1010,6 @@ namespace BizHawk.Client.EmuHawk } } - public byte[] CurrentFrameBuffer(bool captureOSD) - { - using var bb = captureOSD ? CaptureOSD() : MakeScreenshotImage(); - using var img = bb.ToSysdrawingBitmap(); - ImageConverter converter = new ImageConverter(); - return (byte[])converter.ConvertTo(img, typeof(byte[])); - } - public void TakeScreenshotToClipboard() { using (var bb = Config.Screenshot_CaptureOSD ? CaptureOSD() : MakeScreenshotImage()) @@ -1076,10 +1068,6 @@ namespace BizHawk.Client.EmuHawk img.Save(fi.FullName, ImageFormat.Png); } - /* - using (var fs = new FileStream($"{path}_test.bmp", FileMode.OpenOrCreate, FileAccess.Write)) - QuickBmpFile.Save(Emulator.VideoProvider(), fs, r.Next(50, 500), r.Next(50, 500)); - */ AddOnScreenMessage($"{fi.Name} saved."); } @@ -1562,7 +1550,7 @@ namespace BizHawk.Client.EmuHawk str += $"{VersionInfo.CustomBuildString} "; } - str += Emulator.IsNull() ? "BizHawk" : Global.SystemInfo.DisplayName; + str += Emulator.IsNull() ? "BizHawk" : Emulator.System().DisplayName; if (VersionInfo.DeveloperBuild) { @@ -1573,7 +1561,7 @@ namespace BizHawk.Client.EmuHawk { str += $" - {Game.Name}"; - if (MovieSession.Movie.IsActive) + if (MovieSession.Movie.IsActive()) { str += $" - {Path.GetFileName(MovieSession.Movie.Filename)}"; } @@ -2393,7 +2381,7 @@ namespace BizHawk.Client.EmuHawk public void PutCoreSyncSettings(object o) { var settable = new SettingsAdapter(Emulator); - if (MovieSession.Movie.IsActive) + if (MovieSession.Movie.IsActive()) { AddOnScreenMessage("Attempt to change sync-relevant settings while recording BLOCKED."); } @@ -2490,7 +2478,7 @@ namespace BizHawk.Client.EmuHawk // is it enough to run this for one frame? maybe.. if (Emulator.ControllerDefinition.BoolButtons.Contains("Reset")) { - if (!MovieSession.Movie.IsPlaying || MovieSession.Movie.IsFinished) + if (MovieSession.Movie.Mode != MovieMode.Play) { ClickyVirtualPadController.Click("Reset"); AddOnScreenMessage("Reset button pressed."); @@ -2503,7 +2491,7 @@ namespace BizHawk.Client.EmuHawk // is it enough to run this for one frame? maybe.. if (Emulator.ControllerDefinition.BoolButtons.Contains("Power")) { - if (!MovieSession.Movie.IsPlaying || MovieSession.Movie.IsFinished) + if (MovieSession.Movie.Mode != MovieMode.Play) { ClickyVirtualPadController.Click("Power"); AddOnScreenMessage("Power button pressed."); @@ -2676,7 +2664,7 @@ namespace BizHawk.Client.EmuHawk private void SaveMovie() { - if (MovieSession.Movie.IsActive) + if (MovieSession.Movie.IsActive()) { MovieSession.Movie.Save(); AddOnScreenMessage($"{MovieSession.Movie.Filename} saved."); @@ -2785,7 +2773,7 @@ namespace BizHawk.Client.EmuHawk { if (Emulator.ControllerDefinition.BoolButtons.Contains(button)) { - if (!MovieSession.Movie.IsPlaying || MovieSession.Movie.IsFinished) + if (MovieSession.Movie.Mode != MovieMode.Play) { ClickyVirtualPadController.Click(button); AddOnScreenMessage(msg); @@ -3064,7 +3052,7 @@ namespace BizHawk.Client.EmuHawk MovieSession.Movie.SwitchToRecord(); } - if (isRewinding && !IsRewindSlave && MovieSession.Movie.IsRecording) + if (isRewinding && !IsRewindSlave && MovieSession.Movie.IsRecording()) { MovieSession.Movie.Truncate(Global.Emulator.Frame); } @@ -3602,7 +3590,7 @@ namespace BizHawk.Client.EmuHawk private string ChoosePlatformForRom(RomGame rom) { - using var platformChooser = new PlatformChooser + using var platformChooser = new PlatformChooser(Config) { RomGame = rom }; @@ -3841,12 +3829,11 @@ namespace BizHawk.Client.EmuHawk } } - ApiManager.Restart(Emulator.ServiceProvider); - Tools.Restart(); + Tools.Restart(Emulator); if (Config.LoadCheatFileByGame) { - CheatList.SetDefaultFileName(ToolManager.GenerateDefaultCheatFilename()); + CheatList.SetDefaultFileName(Tools.GenerateDefaultCheatFilename()); if (CheatList.AttemptToLoadCheatFile()) { AddOnScreenMessage("Cheats file loaded"); @@ -3887,19 +3874,19 @@ namespace BizHawk.Client.EmuHawk ClientApi.OnRomLoaded(Emulator); return true; } - else if (!(Emulator is NullEmulator)) - { - // The ROM has been loaded by a recursive invocation of the LoadROM method. - ClientApi.OnRomLoaded(Emulator); - return true; - } - else + else if (Emulator.IsNull()) { // This shows up if there's a problem ClientApi.UpdateEmulatorAndVP(Emulator); OnRomChanged(); return false; } + else + { + // The ROM has been loaded by a recursive invocation of the LoadROM method. + ClientApi.OnRomLoaded(Emulator); + return true; + } } finally { @@ -3932,7 +3919,7 @@ namespace BizHawk.Client.EmuHawk Config.PutCoreSettings(settable.GetSettings(), t); } - if (settable.HasSyncSettings && !MovieSession.Movie.IsActive) + if (settable.HasSyncSettings && !MovieSession.Movie.IsActive()) { // don't trample config with loaded-from-movie settings Config.PutCoreSyncSettings(settable.GetSyncSettings(), t); @@ -3972,7 +3959,7 @@ namespace BizHawk.Client.EmuHawk StopAv(); CommitCoreSettingsToConfig(); - if (MovieSession.Movie.IsActive) // Note: this must be called after CommitCoreSettingsToConfig() + if (MovieSession.Movie.IsActive()) // Note: this must be called after CommitCoreSettingsToConfig() { StopMovie(); } @@ -4011,8 +3998,7 @@ namespace BizHawk.Client.EmuHawk Emulator = new NullEmulator(coreComm); Global.Game = GameInfo.NullInstance; - Tools.Restart(); - ApiManager.Restart(Emulator.ServiceProvider); + Tools.Restart(Emulator); RewireSound(); ClearHolds(); ToolFormBase.UpdateCheatRelatedTools(null, null); @@ -4122,7 +4108,7 @@ namespace BizHawk.Client.EmuHawk UpdateToolsLoadstate(); AutoFireController.ClearStarts(); - if (!IsRewindSlave && MovieSession.Movie.IsActive) + if (!IsRewindSlave && MovieSession.Movie.IsActive()) { ClearRewindData(); } @@ -4419,7 +4405,7 @@ namespace BizHawk.Client.EmuHawk } else { - if (MovieSession.Movie.IsActive) + if (MovieSession.Movie.IsActive()) { MovieSession.ReadOnly ^= true; AddOnScreenMessage(MovieSession.ReadOnly ? "Movie read-only mode" : "Movie read+write mode"); @@ -4537,7 +4523,7 @@ namespace BizHawk.Client.EmuHawk { runFrame = Rewinder.Rewind(1) && Emulator.Frame > 1; - if (runFrame && MovieSession.Movie.IsRecording) + if (runFrame && MovieSession.Movie.IsRecording()) { MovieSession.Movie.SwitchToPlay(); returnToRecording = true; diff --git a/BizHawk.Client.EmuHawk/NameStateForm.Designer.cs b/BizHawk.Client.EmuHawk/NameStateForm.Designer.cs deleted file mode 100644 index a5d33a4619..0000000000 --- a/BizHawk.Client.EmuHawk/NameStateForm.Designer.cs +++ /dev/null @@ -1,103 +0,0 @@ -namespace BizHawk.Client.EmuHawk -{ - partial class NameStateForm - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.cancelButton = new System.Windows.Forms.Button(); - this.saveButton = new System.Windows.Forms.Button(); - this.label1 = new System.Windows.Forms.Label(); - this.stateLabelTextBox = new System.Windows.Forms.TextBox(); - this.SuspendLayout(); - // - // cancelButton - // - this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; - this.cancelButton.Location = new System.Drawing.Point(199, 51); - this.cancelButton.Name = "cancelButton"; - this.cancelButton.Size = new System.Drawing.Size(75, 23); - this.cancelButton.TabIndex = 0; - this.cancelButton.Text = "Cancel"; - this.cancelButton.UseVisualStyleBackColor = true; - this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click); - // - // saveButton - // - this.saveButton.Location = new System.Drawing.Point(118, 51); - this.saveButton.Name = "saveButton"; - this.saveButton.Size = new System.Drawing.Size(75, 23); - this.saveButton.TabIndex = 1; - this.saveButton.Text = "Save"; - this.saveButton.UseVisualStyleBackColor = true; - this.saveButton.Click += new System.EventHandler(this.saveButton_Click); - // - // label1 - // - this.label1.AutoSize = true; - this.label1.Location = new System.Drawing.Point(12, 9); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(181, 13); - this.label1.TabIndex = 2; - this.label1.Text = "Enter a short label for this save state:"; - // - // stateLabelTextBox - // - this.stateLabelTextBox.Location = new System.Drawing.Point(15, 25); - this.stateLabelTextBox.MaxLength = 248; - this.stateLabelTextBox.Name = "stateLabelTextBox"; - this.stateLabelTextBox.Size = new System.Drawing.Size(259, 20); - this.stateLabelTextBox.TabIndex = 3; - // - // NameStateForm - // - this.AcceptButton = this.saveButton; - this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.CancelButton = this.cancelButton; - this.ClientSize = new System.Drawing.Size(278, 81); - this.Controls.Add(this.stateLabelTextBox); - this.Controls.Add(this.label1); - this.Controls.Add(this.saveButton); - this.Controls.Add(this.cancelButton); - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; - this.Name = "NameStateForm"; - this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; - this.Text = "Label Save State"; - this.Shown += new System.EventHandler(this.NameStateForm_Shown); - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.Button cancelButton; - private System.Windows.Forms.Button saveButton; - private System.Windows.Forms.Label label1; - private System.Windows.Forms.TextBox stateLabelTextBox; - } -} \ No newline at end of file diff --git a/BizHawk.Client.EmuHawk/NameStateForm.cs b/BizHawk.Client.EmuHawk/NameStateForm.cs deleted file mode 100644 index ab17e1356f..0000000000 --- a/BizHawk.Client.EmuHawk/NameStateForm.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.Windows.Forms; - -namespace BizHawk.Client.EmuHawk -{ - public partial class NameStateForm : Form - { - public string Result; - public bool OK; - - public NameStateForm() - { - InitializeComponent(); - AcceptButton = saveButton; - CancelButton = cancelButton; - } - - private void cancelButton_Click(object sender, EventArgs e) - { - Close(); - } - - private void saveButton_Click(object sender, EventArgs e) - { - if (stateLabelTextBox.Text.Length != 0) - { - Result = stateLabelTextBox.Text; - OK = true; - Close(); - } - } - - private void NameStateForm_Shown(object sender, EventArgs e) - { - stateLabelTextBox.Focus(); - } - } -} diff --git a/BizHawk.Client.EmuHawk/NameStateForm.resx b/BizHawk.Client.EmuHawk/NameStateForm.resx deleted file mode 100644 index c7e0d4bdf1..0000000000 --- a/BizHawk.Client.EmuHawk/NameStateForm.resx +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/BizHawk.Client.EmuHawk/PlatformChooser.cs b/BizHawk.Client.EmuHawk/PlatformChooser.cs index 806071c570..d755208f46 100644 --- a/BizHawk.Client.EmuHawk/PlatformChooser.cs +++ b/BizHawk.Client.EmuHawk/PlatformChooser.cs @@ -1,10 +1,7 @@ using System; using System.Collections.Generic; -using System.ComponentModel; -using System.Data; using System.Drawing; using System.Linq; -using System.Text; using System.Windows.Forms; using BizHawk.Emulation.Common; @@ -14,41 +11,32 @@ namespace BizHawk.Client.EmuHawk { public partial class PlatformChooser : Form { + private readonly Config _config; + private readonly List _availableSystems = new SystemLookup().AllSystems.ToList(); + + + public PlatformChooser(Config config) + { + _config = config; + InitializeComponent(); + } + public RomGame RomGame { get; set; } public string PlatformChoice { get; set; } - private RadioButton SelectedRadio - { - get - { - return PlatformsGroupBox.Controls.OfType().FirstOrDefault(x => x.Checked); - } - } - - public PlatformChooser() - { - InitializeComponent(); - AvailableSystems = new SystemLookup().AllSystems.ToList(); - } - - private readonly List AvailableSystems; + private RadioButton SelectedRadio => PlatformsGroupBox.Controls.OfType().FirstOrDefault(x => x.Checked); private void PlatformChooser_Load(object sender, EventArgs e) { - if (RomGame.RomData.Length > 10 * 1024 * 1024) // If 10mb, show in megabytes - { - RomSizeLabel.Text = $"{RomGame.RomData.Length / 1024 / 1024:n0}mb"; - } - else - { - RomSizeLabel.Text = $"{RomGame.RomData.Length / 1024:n0}kb"; - } + RomSizeLabel.Text = RomGame.RomData.Length > 10 * 1024 * 1024 + ? $"{RomGame.RomData.Length / 1024 / 1024:n0}mb" + : $"{RomGame.RomData.Length / 1024:n0}kb"; ExtensionLabel.Text = RomGame.Extension.ToLower(); HashBox.Text = RomGame.GameInfo.Hash; int count = 0; int spacing = 25; - foreach (var platform in AvailableSystems) + foreach (var platform in _availableSystems) { var radio = new RadioButton { @@ -75,11 +63,11 @@ namespace BizHawk.Client.EmuHawk private void OkBtn_Click(object sender, EventArgs e) { var selectedValue = SelectedRadio != null ? SelectedRadio.Text : ""; - PlatformChoice = AvailableSystems.FirstOrDefault(x => x.FullName == selectedValue).SystemId; + PlatformChoice = _availableSystems.First(x => x.FullName == selectedValue).SystemId; if (AlwaysCheckbox.Checked) { - Global.Config.PreferredPlatformsForExtensions[RomGame.Extension.ToLower()] = PlatformChoice; + _config.PreferredPlatformsForExtensions[RomGame.Extension.ToLower()] = PlatformChoice; } Close(); diff --git a/BizHawk.Client.EmuHawk/Program.cs b/BizHawk.Client.EmuHawk/Program.cs index 7e438dad45..c4b6bc10ec 100644 --- a/BizHawk.Client.EmuHawk/Program.cs +++ b/BizHawk.Client.EmuHawk/Program.cs @@ -146,13 +146,15 @@ namespace BizHawk.Client.EmuHawk GlobalWin.IGL_GL = new Bizware.BizwareGL.Drivers.OpenTK.IGL_TK(2, 0, false); // setup the GL context manager, needed for coping with multiple opengl cores vs opengl display method - GLManager.CreateInstance(GlobalWin.IGL_GL); + GLManager.CreateInstance(); GlobalWin.GLManager = GLManager.Instance; //now create the "GL" context for the display method. we can reuse the IGL_TK context if opengl display method is chosen REDO_DISPMETHOD: if (Global.Config.DispMethod == Config.EDispMethod.GdiPlus) + { GlobalWin.GL = new Bizware.BizwareGL.Drivers.GdiPlus.IGL_GdiPlus(); + } else if (Global.Config.DispMethod == Config.EDispMethod.SlimDX9) { try @@ -172,7 +174,7 @@ namespace BizHawk.Client.EmuHawk { GlobalWin.GL = GlobalWin.IGL_GL; - // check the opengl version and dont even try to boot this crap up if its too old + // check the opengl version and don't even try to boot this crap up if its too old if (GlobalWin.IGL_GL.Version < 200) { // fallback @@ -221,27 +223,25 @@ namespace BizHawk.Client.EmuHawk } else { - using (var mf = new MainForm(args)) + using var mf = new MainForm(args); + var title = mf.Text; + mf.Show(); + mf.Text = title; + try { - var title = mf.Text; - mf.Show(); - mf.Text = title; - try + GlobalWin.ExitCode = mf.ProgramRunLoop(); + } + catch (Exception e) when (Global.MovieSession.Movie.IsActive() && !(Debugger.IsAttached || VersionInfo.DeveloperBuild)) + { + var result = MessageBox.Show( + "EmuHawk has thrown a fatal exception and is about to close.\nA movie has been detected. Would you like to try to save?\n(Note: Depending on what caused this error, this may or may not succeed)", + $"Fatal error: {e.GetType().Name}", + MessageBoxButtons.YesNo, + MessageBoxIcon.Exclamation + ); + if (result == DialogResult.Yes) { - GlobalWin.ExitCode = mf.ProgramRunLoop(); - } - catch (Exception e) when (Global.MovieSession.Movie.IsActive && !(Debugger.IsAttached || VersionInfo.DeveloperBuild)) - { - var result = MessageBox.Show( - "EmuHawk has thrown a fatal exception and is about to close.\nA movie has been detected. Would you like to try to save?\n(Note: Depending on what caused this error, this may or may not succeed)", - $"Fatal error: {e.GetType().Name}", - MessageBoxButtons.YesNo, - MessageBoxIcon.Exclamation - ); - if (result == DialogResult.Yes) - { - Global.MovieSession.Movie.Save(); - } + Global.MovieSession.Movie.Save(); } } } diff --git a/BizHawk.Client.EmuHawk/config/GB/GBPrefControl.cs b/BizHawk.Client.EmuHawk/config/GB/GBPrefControl.cs index 0e52e66db2..31130324c9 100644 --- a/BizHawk.Client.EmuHawk/config/GB/GBPrefControl.cs +++ b/BizHawk.Client.EmuHawk/config/GB/GBPrefControl.cs @@ -28,7 +28,7 @@ namespace BizHawk.Client.EmuHawk _s = s ?? new Gameboy.GambatteSettings(); _ss = ss ?? new Gameboy.GambatteSyncSettings(); propertyGrid1.SelectedObject = _ss; - propertyGrid1.Enabled = !Global.MovieSession.Movie.IsActive; + propertyGrid1.Enabled = Global.MovieSession.Movie.NotActive(); checkBoxMuted.Checked = _s.Muted; cbDisplayBG.Checked = _s.DisplayBG; cbDisplayOBJ.Checked = _s.DisplayOBJ; @@ -43,8 +43,8 @@ namespace BizHawk.Client.EmuHawk private void ButtonDefaults_Click(object sender, EventArgs e) { - PutSettings(null, Global.MovieSession.Movie.IsActive ? _ss : null); - if (!Global.MovieSession.Movie.IsActive) + PutSettings(null, Global.MovieSession.Movie.IsActive() ? _ss : null); + if (Global.MovieSession.Movie.NotActive()) { SyncSettingsChanged = true; } diff --git a/BizHawk.Client.EmuHawk/config/GenericCoreConfig.cs b/BizHawk.Client.EmuHawk/config/GenericCoreConfig.cs index d4c6b63e13..06f9338b42 100644 --- a/BizHawk.Client.EmuHawk/config/GenericCoreConfig.cs +++ b/BizHawk.Client.EmuHawk/config/GenericCoreConfig.cs @@ -52,7 +52,7 @@ namespace BizHawk.Client.EmuHawk tabControl1.TabPages.Remove(tabPage2); } - if (Global.MovieSession.Movie.IsActive) + if (Global.MovieSession.Movie.IsActive()) { propertyGrid2.Enabled = false; // disable changes to sync setting when movie, so as not to confuse user } diff --git a/BizHawk.Client.EmuHawk/config/MessageConfig.Designer.cs b/BizHawk.Client.EmuHawk/config/MessageConfig.Designer.cs index 6b72207b1b..d43f52c9c3 100644 --- a/BizHawk.Client.EmuHawk/config/MessageConfig.Designer.cs +++ b/BizHawk.Client.EmuHawk/config/MessageConfig.Designer.cs @@ -530,8 +530,7 @@ 0, 0, 0}); - this.XNumeric.Click += new System.EventHandler(this.XNumeric_Click); - this.XNumeric.KeyUp += new System.Windows.Forms.KeyEventHandler(this.XNumeric_KeyUp); + this.XNumeric.ValueChanged += new System.EventHandler(this.XNumeric_Changed); // // YNumeric // @@ -550,8 +549,7 @@ 0, 0, 0}); - this.YNumeric.Click += new System.EventHandler(this.YNumeric_Click); - this.YNumeric.KeyUp += new System.Windows.Forms.KeyEventHandler(this.YNumeric_KeyUp); + this.YNumeric.ValueChanged += new System.EventHandler(this.YNumeric_Changed); // // label1 // diff --git a/BizHawk.Client.EmuHawk/config/MessageConfig.cs b/BizHawk.Client.EmuHawk/config/MessageConfig.cs index 7dc063af71..53f1119c76 100644 --- a/BizHawk.Client.EmuHawk/config/MessageConfig.cs +++ b/BizHawk.Client.EmuHawk/config/MessageConfig.cs @@ -2,54 +2,55 @@ using System.Drawing; using System.Windows.Forms; -using BizHawk.Emulation.Common.IEmulatorExtensions; using BizHawk.Client.Common; +using BizHawk.Client.EmuHawk.WinFormExtensions; +using BizHawk.Emulation.Common; namespace BizHawk.Client.EmuHawk { public partial class MessageConfig : Form { - private int _dispFpSx = Global.Config.DispFPSx; - private int _dispFpSy = Global.Config.DispFPSy; - private int _dispFrameCx = Global.Config.DispFrameCx; - private int _dispFrameCy = Global.Config.DispFrameCy; - private int _dispLagx = Global.Config.DispLagx; - private int _dispLagy = Global.Config.DispLagy; - private int _dispInpx = Global.Config.DispInpx; - private int _dispInpy = Global.Config.DispInpy; - private int _dispWatchesx = Global.Config.DispRamWatchx; - private int _dispWatchesy = Global.Config.DispRamWatchy; - private int _lastInputColor = Global.Config.LastInputColor; - private int _dispRecx = Global.Config.DispRecx; - private int _dispRecy = Global.Config.DispRecy; - private int _dispMultix = Global.Config.DispMultix; - private int _dispMultiy = Global.Config.DispMultiy; - private int _dispMessagex = Global.Config.DispMessagex; - private int _dispMessagey = Global.Config.DispMessagey; - private int _dispAutoholdx = Global.Config.DispAutoholdx; - private int _dispAutoholdy = Global.Config.DispAutoholdy; + private readonly Config _config; - private int _messageColor = Global.Config.MessagesColor; - private int _alertColor = Global.Config.AlertMessageColor; - private int _movieInput = Global.Config.MovieInput; + private MessagePosition _fps; + private MessagePosition _frameCounter; + private MessagePosition _lagCounter; + private MessagePosition _inputDisplay; + private MessagePosition _reRecordCounter; + private MessagePosition _multitrackRecorder; + private MessagePosition _messages; + private MessagePosition _autohold; + private MessagePosition _ramWatches; + + private int _messageColor; + private int _alertColor; + private int _lastInputColor; + private int _movieInput; - private int _dispFpSanchor = Global.Config.DispFPSanchor; - private int _dispFrameanchor = Global.Config.DispFrameanchor; - private int _dispLaganchor = Global.Config.DispLaganchor; - private int _dispInputanchor = Global.Config.DispInpanchor; - private int _dispWatchesanchor = Global.Config.DispWatchesanchor; - private int _dispRecanchor = Global.Config.DispRecanchor; - private int _dispMultiAnchor = Global.Config.DispMultianchor; - private int _dispMessageAnchor = Global.Config.DispMessageanchor; - private int _dispAutoholdAnchor = Global.Config.DispAutoholdanchor; - - private readonly Brush _brush = Brushes.Black; private int _px; private int _py; private bool _mousedown; + private bool _programmaticallyChangingValues; - public MessageConfig() + public MessageConfig(Config config) { + _config = config; + + _fps = _config.Fps.Clone(); + _frameCounter = _config.FrameCounter.Clone(); + _lagCounter = _config.LagCounter.Clone(); + _inputDisplay = _config.InputDisplay.Clone(); + _reRecordCounter = _config.ReRecordCounter.Clone(); + _multitrackRecorder = _config.MultitrackRecorder.Clone(); + _messages = _config.Messages.Clone(); + _autohold = _config.Autohold.Clone(); + _ramWatches = _config.RamWatches.Clone(); + + _messageColor = _config.MessagesColor; + _alertColor = _config.AlertMessageColor; + _lastInputColor = _config.LastInputColor; + _movieInput = _config.MovieInput; + InitializeComponent(); } @@ -62,12 +63,12 @@ namespace BizHawk.Client.EmuHawk MovieInputColorDialog.Color = Color.FromArgb(_movieInput); SetColorBox(); SetPositionInfo(); - StackMessagesCheckbox.Checked = Global.Config.StackOSDMessages; + StackMessagesCheckbox.Checked = _config.StackOSDMessages; } private void SetMaxXy() { - var video = Global.Emulator.AsVideoProvider(); // TODO: this is objectively wrong, these are core agnostic settings, why is the current core used here? Also this will crash on a core without a video provider + var video = NullVideo.Instance; // Good enough XNumeric.Maximum = video.BufferWidth - 12; YNumeric.Maximum = video.BufferHeight - 12; PositionPanel.Size = new Size(video.BufferWidth + 2, video.BufferHeight + 2); @@ -96,99 +97,71 @@ namespace BizHawk.Client.EmuHawk MovieInputText.Text = $"{_movieInput:X8}"; } - private void SetAnchorRadio(int anchor) + private void SetFromOption(MessagePosition position) { - switch (anchor) + _programmaticallyChangingValues = true; + XNumeric.Value = position.X; + YNumeric.Value = position.Y; + _px = position.X; + _py = position.Y; + + switch (position.Anchor) { default: - case 0: + case MessagePosition.AnchorType.TopLeft: TL.Checked = true; break; - case 1: + case MessagePosition.AnchorType.TopRight: TR.Checked = true; break; - case 2: + case MessagePosition.AnchorType.BottomLeft: BL.Checked = true; break; - case 3: + case MessagePosition.AnchorType.BottomRight: BR.Checked = true; break; } + + _programmaticallyChangingValues = false; } private void SetPositionInfo() { if (FPSRadio.Checked) { - XNumeric.Value = _dispFpSx; - YNumeric.Value = _dispFpSy; - _px = _dispFpSx; - _py = _dispFpSy; - SetAnchorRadio(_dispFpSanchor); + SetFromOption(_fps); } else if (FrameCounterRadio.Checked) { - XNumeric.Value = _dispFrameCx; - YNumeric.Value = _dispFrameCy; - _px = _dispFrameCx; - _py = _dispFrameCy; - SetAnchorRadio(_dispFrameanchor); + SetFromOption(_frameCounter); } else if (LagCounterRadio.Checked) { - XNumeric.Value = _dispLagx; - YNumeric.Value = _dispLagy; - _px = _dispLagx; - _py = _dispLagy; - SetAnchorRadio(_dispLaganchor); + SetFromOption(_lagCounter); } else if (InputDisplayRadio.Checked) { - XNumeric.Value = _dispInpx; - XNumeric.Value = _dispInpy; - _px = _dispInpx; - _py = _dispInpy; - SetAnchorRadio(_dispInputanchor); + SetFromOption(_inputDisplay); } else if (WatchesRadio.Checked) { - XNumeric.Value = _dispWatchesx; - XNumeric.Value = _dispWatchesy; - _px = _dispWatchesx; - _py = _dispWatchesy; - SetAnchorRadio(_dispWatchesanchor); + SetFromOption(_ramWatches); } else if (MessagesRadio.Checked) { - XNumeric.Value = _dispMessagex; - YNumeric.Value = _dispMessagey; - _px = _dispMessagex; - _py = _dispMessagey; - SetAnchorRadio(_dispMessageAnchor); + SetFromOption(_messages); } else if (RerecordsRadio.Checked) { - XNumeric.Value = _dispRecx; - YNumeric.Value = _dispRecy; - _px = _dispRecx; - _py = _dispRecy; - SetAnchorRadio(_dispRecanchor); + SetFromOption(_reRecordCounter); } else if (MultitrackRadio.Checked) { - XNumeric.Value = _dispMultix; - YNumeric.Value = _dispMultiy; - _px = _dispMultix; - _py = _dispMultiy; - SetAnchorRadio(_dispMultiAnchor); + SetFromOption(_multitrackRecorder); } else if (AutoholdRadio.Checked) { - XNumeric.Value = _dispAutoholdx; - YNumeric.Value = _dispAutoholdy; - _px = _dispAutoholdx; - _py = _dispAutoholdy; - SetAnchorRadio(_dispAutoholdAnchor); + SetFromOption(_autohold); } PositionPanel.Refresh(); @@ -197,46 +170,25 @@ namespace BizHawk.Client.EmuHawk SetPositionLabels(); } - private void SaveSettings() - { - Global.Config.DispFPSx = _dispFpSx; - Global.Config.DispFPSy = _dispFpSy; - Global.Config.DispFrameCx = _dispFrameCx; - Global.Config.DispFrameCy = _dispFrameCy; - Global.Config.DispLagx = _dispLagx; - Global.Config.DispLagy = _dispLagy; - Global.Config.DispInpx = _dispInpx; - Global.Config.DispInpy = _dispInpy; - Global.Config.DispRamWatchx = _dispWatchesx; - Global.Config.DispRamWatchy = _dispWatchesy; - Global.Config.DispRecx = _dispRecx; - Global.Config.DispRecy = _dispRecy; - Global.Config.DispMultix = _dispMultix; - Global.Config.DispMultiy = _dispMultiy; - Global.Config.DispMessagex = _dispMessagex; - Global.Config.DispMessagey = _dispMessagey; - Global.Config.DispAutoholdx = _dispAutoholdx; - Global.Config.DispAutoholdy = _dispAutoholdy; - - Global.Config.MessagesColor = _messageColor; - Global.Config.AlertMessageColor = _alertColor; - Global.Config.LastInputColor = _lastInputColor; - Global.Config.MovieInput = _movieInput; - Global.Config.DispFPSanchor = _dispFpSanchor; - Global.Config.DispFrameanchor = _dispFrameanchor; - Global.Config.DispLaganchor = _dispLaganchor; - Global.Config.DispInpanchor = _dispInputanchor; - Global.Config.DispRecanchor = _dispRecanchor; - Global.Config.DispMultianchor = _dispMultiAnchor; - Global.Config.DispMessageanchor = _dispMessageAnchor; - Global.Config.DispAutoholdanchor = _dispAutoholdAnchor; - - Global.Config.StackOSDMessages = StackMessagesCheckbox.Checked; - } - private void Ok_Click(object sender, EventArgs e) { - SaveSettings(); + _config.Fps = _fps; + _config.FrameCounter = _frameCounter; + _config.LagCounter = _lagCounter; + _config.InputDisplay = _inputDisplay; + _config.ReRecordCounter = _reRecordCounter; + _config.MultitrackRecorder = _multitrackRecorder; + _config.Messages = _messages; + _config.Autohold = _autohold; + _config.RamWatches = _ramWatches; + + _config.MessagesColor = _messageColor; + _config.AlertMessageColor = _alertColor; + _config.LastInputColor = _lastInputColor; + _config.MovieInput = _movieInput; + + _config.StackOSDMessages = StackMessagesCheckbox.Checked; + DialogResult = DialogResult.OK; Close(); } @@ -250,20 +202,6 @@ namespace BizHawk.Client.EmuHawk SetPositionInfo(); } - private void XNumericChange() - { - _px = (int)XNumeric.Value; - SetPositionLabels(); - PositionPanel.Refresh(); - } - - private void YNumericChange() - { - _py = (int)YNumeric.Value; - SetPositionLabels(); - PositionPanel.Refresh(); - } - private void PositionPanel_MouseEnter(object sender, EventArgs e) { Cursor = Cursors.Hand; @@ -300,7 +238,7 @@ namespace BizHawk.Client.EmuHawk y = (int)YNumeric.Maximum - _py; } - using var p = new Pen(_brush); + using var p = new Pen(Color.Black); e.Graphics.DrawLine(p, new Point(x, y), new Point(x + 8, y + 8)); e.Graphics.DrawLine(p, new Point(x + 8, y), new Point(x, y + 8)); e.Graphics.DrawRectangle(p, new Rectangle(x, y, 8, 8)); @@ -321,6 +259,7 @@ namespace BizHawk.Client.EmuHawk private void SetNewPosition(int mx, int my) { + _programmaticallyChangingValues = true; if (mx < 0) mx = 0; if (my < 0) my = 0; if (mx > XNumeric.Maximum) mx = (int)XNumeric.Maximum; @@ -351,6 +290,8 @@ namespace BizHawk.Client.EmuHawk PositionPanel.Refresh(); SetPositionLabels(); + + _programmaticallyChangingValues = false; } private void PositionPanel_MouseMove(object sender, MouseEventArgs e) @@ -361,128 +302,83 @@ namespace BizHawk.Client.EmuHawk } } + private void SetOptionPosition(MessagePosition position) + { + position.X = _px; + position.Y = _py; + } + private void SetPositionLabels() { if (FPSRadio.Checked) { - _dispFpSx = _px; - _dispFpSy = _py; + SetOptionPosition(_fps); } else if (FrameCounterRadio.Checked) { - _dispFrameCx = _px; - _dispFrameCy = _py; + SetOptionPosition(_frameCounter); } else if (LagCounterRadio.Checked) { - _dispLagx = _px; - _dispLagy = _py; + SetOptionPosition(_lagCounter); } else if (InputDisplayRadio.Checked) { - _dispInpx = _px; - _dispInpy = _py; + SetOptionPosition(_inputDisplay); } else if (WatchesRadio.Checked) { - _dispWatchesx = _px; - _dispWatchesy = _py; + SetOptionPosition(_ramWatches); } else if (RerecordsRadio.Checked) { - _dispRecx = _px; - _dispRecy = _py; + SetOptionPosition(_reRecordCounter); } else if (MultitrackRadio.Checked) { - _dispMultix = _px; - _dispMultiy = _py; + SetOptionPosition(_multitrackRecorder); } else if (MessagesRadio.Checked) { - _dispMessagex = _px; - _dispMessagey = _py; + SetOptionPosition(_messages); } else if (AutoholdRadio.Checked) { - _dispAutoholdx = _px; - _dispAutoholdy = _py; + SetOptionPosition(_autohold); } - FpsPosLabel.Text = $"{_dispFpSx}, {_dispFpSy}"; - FCLabel.Text = $"{_dispFrameCx}, {_dispFrameCy}"; - LagLabel.Text = $"{_dispLagx}, {_dispLagy}"; - InpLabel.Text = $"{_dispInpx}, {_dispInpy}"; - WatchesLabel.Text = $"{_dispWatchesx}, {_dispWatchesy}"; - RerecLabel.Text = $"{_dispRecx}, {_dispRecy}"; - MultitrackLabel.Text = $"{_dispMultix}, {_dispMultiy}"; - MessLabel.Text = $"{_dispMessagex}, {_dispMessagey}"; - AutoholdLabel.Text = $"{_dispAutoholdx}, {_dispAutoholdy}"; + FpsPosLabel.Text = ToCoordinateStr(_fps); + FCLabel.Text = ToCoordinateStr(_frameCounter); + LagLabel.Text = ToCoordinateStr(_lagCounter); + InpLabel.Text = ToCoordinateStr(_inputDisplay); + WatchesLabel.Text = ToCoordinateStr(_ramWatches); + RerecLabel.Text = ToCoordinateStr(_reRecordCounter); + MultitrackLabel.Text = ToCoordinateStr(_multitrackRecorder); + MessLabel.Text = ToCoordinateStr(_messages); + AutoholdLabel.Text = ToCoordinateStr(_autohold); + } + + private string ToCoordinateStr(MessagePosition position) + { + return $"{position.X}, {position.Y}"; } private void ResetDefaultsButton_Click(object sender, EventArgs e) { - Global.Config.DispFPSx = Config.DefaultMessageOptions.DispFPSx; - Global.Config.DispFPSy = Config.DefaultMessageOptions.DispFPSy; - Global.Config.DispFrameCx = Config.DefaultMessageOptions.DispFrameCx; - Global.Config.DispFrameCy = Config.DefaultMessageOptions.DispFrameCy; - Global.Config.DispLagx = Config.DefaultMessageOptions.DispLagx; - Global.Config.DispLagy = Config.DefaultMessageOptions.DispLagy; - Global.Config.DispInpx = Config.DefaultMessageOptions.DispInpx; - Global.Config.DispInpy = Config.DefaultMessageOptions.DispInpy; - Global.Config.DispRecx = Config.DefaultMessageOptions.DispRecx; - Global.Config.DispRecy = Config.DefaultMessageOptions.DispRecy; - Global.Config.DispMultix = Config.DefaultMessageOptions.DispMultix; - Global.Config.DispMultiy = Config.DefaultMessageOptions.DispMultiy; - Global.Config.DispMessagex = Config.DefaultMessageOptions.DispMessagex; - Global.Config.DispMessagey = Config.DefaultMessageOptions.DispMessagey; - Global.Config.DispAutoholdx = Config.DefaultMessageOptions.DispAutoholdx; - Global.Config.DispAutoholdy = Config.DefaultMessageOptions.DispAutoholdy; + _fps = _config.Fps = DefaultMessagePositions.Fps.Clone(); + _frameCounter = _config.FrameCounter = DefaultMessagePositions.FrameCounter.Clone(); + _lagCounter = _config.LagCounter = DefaultMessagePositions.LagCounter.Clone(); + _inputDisplay = _config.InputDisplay = DefaultMessagePositions.InputDisplay.Clone(); + _reRecordCounter = _config.ReRecordCounter = DefaultMessagePositions.ReRecordCounter.Clone(); + _multitrackRecorder = _config.MultitrackRecorder = DefaultMessagePositions.MultitrackRecorder.Clone(); + _messages = _config.Messages = DefaultMessagePositions.Messages.Clone(); + _autohold = _config.Autohold = DefaultMessagePositions.Autohold.Clone(); + _ramWatches = _config.RamWatches = DefaultMessagePositions.RamWatches.Clone(); - Global.Config.DispFPSanchor = Config.DefaultMessageOptions.DispFPSanchor; - Global.Config.DispFrameanchor = Config.DefaultMessageOptions.DispFrameanchor; - Global.Config.DispLaganchor = Config.DefaultMessageOptions.DispLaganchor; - Global.Config.DispInpanchor = Config.DefaultMessageOptions.DispInpanchor; - Global.Config.DispRecanchor = Config.DefaultMessageOptions.DispRecanchor; - Global.Config.DispMultianchor = Config.DefaultMessageOptions.DispMultianchor; - Global.Config.DispMessageanchor = Config.DefaultMessageOptions.DispMessageanchor; - Global.Config.DispAutoholdanchor = Config.DefaultMessageOptions.DispAutoholdanchor; - - Global.Config.MessagesColor = Config.DefaultMessageOptions.MessagesColor; - Global.Config.AlertMessageColor = Config.DefaultMessageOptions.AlertMessageColor; - Global.Config.LastInputColor = Config.DefaultMessageOptions.LastInputColor; - Global.Config.MovieInput = Config.DefaultMessageOptions.MovieInput; - - _dispFpSx = Global.Config.DispFPSx; - _dispFpSy = Global.Config.DispFPSy; - _dispFrameCx = Global.Config.DispFrameCx; - _dispFrameCy = Global.Config.DispFrameCy; - _dispLagx = Global.Config.DispLagx; - _dispLagy = Global.Config.DispLagy; - _dispInpx = Global.Config.DispInpx; - _dispInpy = Global.Config.DispInpy; - _dispRecx = Global.Config.DispRecx; - _dispRecy = Global.Config.DispRecy; - _dispMultix = Global.Config.DispMultix; - _dispMultiy = Global.Config.DispMultiy; - _dispMessagex = Global.Config.DispMessagex; - _dispMessagey = Global.Config.DispMessagey; - _dispAutoholdx = Global.Config.DispAutoholdx; - _dispAutoholdy = Global.Config.DispAutoholdy; - - _dispFpSanchor = Global.Config.DispFPSanchor; - _dispFrameanchor = Global.Config.DispFrameanchor; - _dispLaganchor = Global.Config.DispLaganchor; - _dispInputanchor = Global.Config.DispInpanchor; - _dispRecanchor = Global.Config.DispRecanchor; - _dispMultiAnchor = Global.Config.DispMultianchor; - _dispMessageAnchor = Global.Config.DispMessageanchor; - _dispAutoholdAnchor = Global.Config.DispAutoholdanchor; - - _messageColor = Global.Config.MessagesColor; - _alertColor = Global.Config.AlertMessageColor; - _lastInputColor = Global.Config.LastInputColor; - _movieInput = Global.Config.MovieInput; + _messageColor = _config.MessagesColor = DefaultMessagePositions.MessagesColor; + _alertColor = _config.AlertMessageColor = DefaultMessagePositions.AlertMessageColor; + _lastInputColor = _config.LastInputColor = DefaultMessagePositions.LastInputColor; + _movieInput = _config.MovieInput = DefaultMessagePositions.MovieInput; MessageColorDialog.Color = Color.FromArgb(_messageColor); AlertColorDialog.Color = Color.FromArgb(_alertColor); @@ -493,46 +389,46 @@ namespace BizHawk.Client.EmuHawk SetColorBox(); SetPositionInfo(); - StackMessagesCheckbox.Checked = Global.Config.StackOSDMessages = true; + StackMessagesCheckbox.Checked = _config.StackOSDMessages = true; } - private void SetAnchorValue(int value) + private void SetAnchorValue(MessagePosition.AnchorType value) { if (FPSRadio.Checked) { - _dispFpSanchor = value; + _fps.Anchor = value; } else if (FrameCounterRadio.Checked) { - _dispFrameanchor = value; + _frameCounter.Anchor = value; } else if (LagCounterRadio.Checked) { - _dispLaganchor = value; + _lagCounter.Anchor = value; } else if (InputDisplayRadio.Checked) { - _dispInputanchor = value; + _inputDisplay.Anchor = value; } else if (WatchesRadio.Checked) { - _dispWatchesanchor = value; + _ramWatches.Anchor = value; } else if (MessagesRadio.Checked) { - _dispMessageAnchor = value; + _messages.Anchor = value; } else if (RerecordsRadio.Checked) { - _dispRecanchor = value; + _reRecordCounter.Anchor = value; } else if (MultitrackRadio.Checked) { - _dispMultiAnchor = value; + _multitrackRecorder.Anchor = value; } else if (AutoholdRadio.Checked) { - _dispAutoholdAnchor = value; + _autohold.Anchor = value; } } @@ -540,7 +436,7 @@ namespace BizHawk.Client.EmuHawk { if (TL.Checked) { - SetAnchorValue(0); + SetAnchorValue(MessagePosition.AnchorType.TopLeft); } PositionPanel.Refresh(); @@ -550,7 +446,7 @@ namespace BizHawk.Client.EmuHawk { if (TR.Checked) { - SetAnchorValue(1); + SetAnchorValue(MessagePosition.AnchorType.TopRight); } PositionPanel.Refresh(); @@ -560,8 +456,9 @@ namespace BizHawk.Client.EmuHawk { if (BL.Checked) { - SetAnchorValue(2); + SetAnchorValue(MessagePosition.AnchorType.BottomLeft); } + PositionPanel.Refresh(); } @@ -569,24 +466,35 @@ namespace BizHawk.Client.EmuHawk { if (BR.Checked) { - SetAnchorValue(3); + SetAnchorValue(MessagePosition.AnchorType.BottomRight); } + PositionPanel.Refresh(); } - private void XNumeric_Click(object sender, EventArgs e) + private void XNumeric_Changed(object sender, EventArgs e) { - XNumericChange(); + if (!_programmaticallyChangingValues) + { + _px = (int)XNumeric.Value; + SetPositionLabels(); + PositionPanel.Refresh(); + } } - private void YNumeric_Click(object sender, EventArgs e) + private void YNumeric_Changed(object sender, EventArgs e) { - YNumericChange(); + if (!_programmaticallyChangingValues) + { + _py = (int)YNumeric.Value; + SetPositionLabels(); + PositionPanel.Refresh(); + } } private void ColorPanel_Click(object sender, EventArgs e) { - if (MessageColorDialog.ShowDialog() == DialogResult.OK) + if (MessageColorDialog.ShowDialog().IsOk()) { SetColorBox(); } @@ -594,7 +502,7 @@ namespace BizHawk.Client.EmuHawk private void AlertColorPanel_Click(object sender, EventArgs e) { - if (AlertColorDialog.ShowDialog() == DialogResult.OK) + if (AlertColorDialog.ShowDialog().IsOk()) { SetColorBox(); } @@ -602,7 +510,7 @@ namespace BizHawk.Client.EmuHawk private void LInputColorPanel_Click(object sender, EventArgs e) { - if (LInputColorDialog.ShowDialog() == DialogResult.OK) + if (LInputColorDialog.ShowDialog().IsOk()) { SetColorBox(); } @@ -610,20 +518,10 @@ namespace BizHawk.Client.EmuHawk private void MovieInputColor_Click(object sender, EventArgs e) { - if (MovieInputColorDialog.ShowDialog() == DialogResult.OK) + if (MovieInputColorDialog.ShowDialog().IsOk()) { SetColorBox(); } } - - private void XNumeric_KeyUp(object sender, KeyEventArgs e) - { - XNumericChange(); - } - - private void YNumeric_KeyUp(object sender, KeyEventArgs e) - { - YNumericChange(); - } } } diff --git a/BizHawk.Client.EmuHawk/config/NES/NESGraphicsConfig.cs b/BizHawk.Client.EmuHawk/config/NES/NESGraphicsConfig.cs index 790b985d6b..6cea4a179c 100644 --- a/BizHawk.Client.EmuHawk/config/NES/NESGraphicsConfig.cs +++ b/BizHawk.Client.EmuHawk/config/NES/NESGraphicsConfig.cs @@ -5,7 +5,6 @@ using System.Windows.Forms; using BizHawk.Common; using BizHawk.Client.Common; using BizHawk.Emulation.Cores.Nintendo.NES; -using BizHawk.Emulation.Cores.Nintendo.SubNESHawk; namespace BizHawk.Client.EmuHawk { @@ -16,14 +15,17 @@ namespace BizHawk.Client.EmuHawk // Hotkeys for BG & Sprite display toggle // NTSC filter settings? Hue, Tint (This should probably be a client thing, not a nes specific thing?) private readonly MainForm _mainForm; + private readonly Config _config; private NES.NESSettings _settings; //private Bitmap _bmp; public NESGraphicsConfig( MainForm mainForm, + Config config, NES.NESSettings settings) { _mainForm = mainForm; + _config = config; _settings = settings; InitializeComponent(); } @@ -52,11 +54,11 @@ namespace BizHawk.Client.EmuHawk private void BrowsePalette_Click(object sender, EventArgs e) { using var ofd = new OpenFileDialog - { - InitialDirectory = PathManager.MakeAbsolutePath(Global.Config.PathEntries["NES", "Palettes"].Path, "NES"), - Filter = "Palette Files (.pal)|*.PAL|All Files (*.*)|*.*", - RestoreDirectory = true - }; + { + InitialDirectory = PathManager.MakeAbsolutePath(_config.PathEntries["NES", "Palettes"].Path, "NES"), + Filter = "Palette Files (.pal)|*.PAL|All Files (*.*)|*.*", + RestoreDirectory = true + }; var result = ofd.ShowDialog(); if (result != DialogResult.OK) @@ -71,7 +73,7 @@ namespace BizHawk.Client.EmuHawk private void SetPaletteImage() { - var pal = ResolvePalette(false); + var pal = ResolvePalette(); int w = pictureBoxPalette.Size.Width; int h = pictureBoxPalette.Size.Height; @@ -83,8 +85,8 @@ namespace BizHawk.Client.EmuHawk for (int i = 0; i < w; i++) { int cx = i * 16 / w; - int cindex = (cy * 16) + cx; - Color col = Color.FromArgb(0xff, pal[cindex, 0], pal[cindex, 1], pal[cindex, 2]); + int cIndex = (cy * 16) + cx; + Color col = Color.FromArgb(0xff, pal[cIndex, 0], pal[cIndex, 1], pal[cIndex, 2]); bmp.SetPixel(i, j, col); } } @@ -92,7 +94,7 @@ namespace BizHawk.Client.EmuHawk pictureBoxPalette.Image = bmp; } - private byte[,] ResolvePalette(bool showmsg = false) + private byte[,] ResolvePalette(bool showMsg = false) { if (AutoLoadPalette.Checked) // checkbox checked: try to load palette from file { @@ -103,9 +105,9 @@ namespace BizHawk.Client.EmuHawk if (palette.Exists) { var data = Palettes.Load_FCEUX_Palette(HawkFile.ReadAllBytes(palette.Name)); - if (showmsg) + if (showMsg) { - GlobalWin.OSD.AddMessage($"Palette file loaded: {palette.Name}"); + _mainForm.AddOnScreenMessage($"Palette file loaded: {palette.Name}"); } return data; @@ -115,9 +117,9 @@ namespace BizHawk.Client.EmuHawk } // no filename: interpret this as "reset to default" - if (showmsg) + if (showMsg) { - GlobalWin.OSD.AddMessage("Standard Palette set"); + _mainForm.AddOnScreenMessage("Standard Palette set"); } return (byte[,])Palettes.QuickNESPalette.Clone(); diff --git a/BizHawk.Client.EmuHawk/config/PathConfig.cs b/BizHawk.Client.EmuHawk/config/PathConfig.cs index c01eb67847..0dd30102f1 100644 --- a/BizHawk.Client.EmuHawk/config/PathConfig.cs +++ b/BizHawk.Client.EmuHawk/config/PathConfig.cs @@ -97,11 +97,11 @@ namespace BizHawk.Client.EmuHawk var tabPages = new List(systems.Count); int x = UIHelper.ScaleX(6); - int textboxWidth = UIHelper.ScaleX(70); + int textBoxWidth = UIHelper.ScaleX(70); int padding = UIHelper.ScaleX(5); int buttonWidth = UIHelper.ScaleX(26); int buttonHeight = UIHelper.ScaleY(23); - int buttonOffsetY = -1; // To align the top with the textbox I guess? Always 1 pixel regardless of scaling. + int buttonOffsetY = -1; // To align the top with the TextBox I guess? Always 1 pixel regardless of scaling. int widgetOffset = UIHelper.ScaleX(85); int rowHeight = UIHelper.ScaleY(30); @@ -127,7 +127,7 @@ namespace BizHawk.Client.EmuHawk { Text = path.Path, Location = new Point(x, y), - Width = textboxWidth, + Width = textBoxWidth, Name = path.Type, Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right, MinimumSize = new Size(UIHelper.ScaleX(26), UIHelper.ScaleY(23)), @@ -200,12 +200,6 @@ namespace BizHawk.Client.EmuHawk y += rowHeight; } - var sys = systemDisplayName; - if (systemDisplayName == "PCE") // Hack - { - sys = "PCECD"; - } - tabPages.Add(t); } diff --git a/BizHawk.Client.EmuHawk/config/SoundConfig.cs b/BizHawk.Client.EmuHawk/config/SoundConfig.cs index c3f193b131..2223e1ea5e 100644 --- a/BizHawk.Client.EmuHawk/config/SoundConfig.cs +++ b/BizHawk.Client.EmuHawk/config/SoundConfig.cs @@ -76,14 +76,11 @@ namespace BizHawk.Client.EmuHawk GlobalWin.Sound = new Sound(GlobalWin.MainForm.Handle); } - GlobalWin.Sound.StartSound(); - GlobalWin.OSD.AddMessage("Sound settings saved"); DialogResult = DialogResult.OK; } private void Cancel_Click(object sender, EventArgs e) { - GlobalWin.OSD.AddMessage("Sound config aborted"); Close(); } diff --git a/BizHawk.Client.EmuHawk/tools/BasicBot/BasicBot.cs b/BizHawk.Client.EmuHawk/tools/BasicBot/BasicBot.cs index 6df7321e47..7a7ca74e14 100644 --- a/BizHawk.Client.EmuHawk/tools/BasicBot/BasicBot.cs +++ b/BizHawk.Client.EmuHawk/tools/BasicBot/BasicBot.cs @@ -481,7 +481,7 @@ namespace BizHawk.Client.EmuHawk { var file = OpenFileDialog( CurrentFileName, - PathManager.MakeAbsolutePath(Global.Config.PathEntries.ToolsPathFragment, null), + PathManager.MakeAbsolutePath(Config.PathEntries.ToolsPathFragment, null), "Bot files", "bot" ); @@ -504,7 +504,7 @@ namespace BizHawk.Client.EmuHawk { var file = SaveFileDialog( CurrentFileName, - PathManager.MakeAbsolutePath(Global.Config.PathEntries.ToolsPathFragment, null), + PathManager.MakeAbsolutePath(Config.PathEntries.ToolsPathFragment, null), "Bot files", "bot" ); @@ -1099,7 +1099,7 @@ namespace BizHawk.Client.EmuHawk GoalGroupBox.Enabled = false; _currentBotAttempt = new BotAttempt { Attempt = Attempts }; - if (Global.MovieSession.Movie.IsRecording) + if (Global.MovieSession.Movie.IsRecording()) { _oldCountingSetting = Global.MovieSession.Movie.IsCountingRerecords; Global.MovieSession.Movie.IsCountingRerecords = false; @@ -1156,7 +1156,7 @@ namespace BizHawk.Client.EmuHawk _currentBotAttempt = null; GoalGroupBox.Enabled = true; - if (Global.MovieSession.Movie.IsRecording) + if (Global.MovieSession.Movie.IsRecording()) { Global.MovieSession.Movie.IsCountingRerecords = _oldCountingSetting; } diff --git a/BizHawk.Client.EmuHawk/tools/CDL.cs b/BizHawk.Client.EmuHawk/tools/CDL.cs index a233a9c117..4e5e093dc8 100644 --- a/BizHawk.Client.EmuHawk/tools/CDL.cs +++ b/BizHawk.Client.EmuHawk/tools/CDL.cs @@ -1,14 +1,11 @@ using System; -using System.Collections.Generic; using System.IO; -using System.Linq; using System.Windows.Forms; using BizHawk.Emulation.Common; using BizHawk.Client.Common; using BizHawk.Client.EmuHawk.ToolExtensions; -using BizHawk.Common; //TODO - select which memorydomains go out to the CDL file. will this cause a problem when re-importing it? //perhaps missing domains shouldnt fail a check @@ -27,20 +24,16 @@ namespace BizHawk.Client.EmuHawk [ConfigPersist] private RecentFiles _recent { - get - { return _recent_fld; } - set - { - _recent_fld = value; - } + get => _recent_fld; + set => _recent_fld = value; } void SetCurrentFilename(string fname) { _currentFilename = fname; - if (_currentFilename == null) - Text = "Code Data Logger"; - else Text = $"Code Data Logger - {fname}"; + Text = _currentFilename == null + ? "Code Data Logger" + : $"Code Data Logger - {fname}"; } [RequiredService] @@ -194,12 +187,12 @@ namespace BizHawk.Client.EmuHawk public bool AskSaveChanges() { - //nothing to fear: + // nothing to fear: if (_cdl == null) return true; - //try auto-saving if appropriate - if (Global.Config.CDLAutoSave) + // try auto-saving if appropriate + if (Config.CDLAutoSave) { if (_currentFilename != null) { @@ -209,7 +202,7 @@ namespace BizHawk.Client.EmuHawk } } - //TODO - I dont like this system. It's hard to figure out how to use it. It should be done in multiple passes. + // TODO - I don't like this system. It's hard to figure out how to use it. It should be done in multiple passes. var result = MessageBox.Show("Save changes to CDL session?", "CDL Auto Save", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.No) { @@ -224,29 +217,17 @@ namespace BizHawk.Client.EmuHawk ShutdownCDL(); return true; } - else - { - ShutdownCDL(); - return false; - } - } - else - { - RunSave(); + ShutdownCDL(); - return true; + return false; } + + RunSave(); + ShutdownCDL(); + return true; } - public bool UpdateBefore - { - get { return false; } - } - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - } + public bool UpdateBefore => false; bool autoloading = false; public void LoadFile(string path) @@ -269,7 +250,7 @@ namespace BizHawk.Client.EmuHawk //ok, it's all good: _cdl = newCDL; CodeDataLogger.SetCDL(null); - if (tsbLoggingActive.Checked || Global.Config.CDLAutoStart) + if (tsbLoggingActive.Checked || Config.CDLAutoStart) { tsbLoggingActive.Checked = true; CodeDataLogger.SetCDL(_cdl); @@ -290,9 +271,9 @@ namespace BizHawk.Client.EmuHawk DisassembleMenuItem.Enabled = _cdl != null; - miAutoSave.Checked = Global.Config.CDLAutoSave; - miAutoStart.Checked = Global.Config.CDLAutoStart; - miAutoResume.Checked = Global.Config.CDLAutoResume; + miAutoSave.Checked = Config.CDLAutoSave; + miAutoStart.Checked = Config.CDLAutoStart; + miAutoResume.Checked = Config.CDLAutoResume; } private void RecentSubMenu_DropDownOpened(object sender, EventArgs e) @@ -306,7 +287,7 @@ namespace BizHawk.Client.EmuHawk _cdl = new CodeDataLog(); CodeDataLogger.NewCDL(_cdl); - if (tsbLoggingActive.Checked || Global.Config.CDLAutoStart) + if (tsbLoggingActive.Checked || Config.CDLAutoStart) CodeDataLogger.SetCDL(_cdl); else CodeDataLogger.SetCDL(null); @@ -332,7 +313,7 @@ namespace BizHawk.Client.EmuHawk { var file = OpenFileDialog( _currentFilename, - PathManager.MakeAbsolutePath(Global.Config.PathEntries.LogPathFragment, null), + PathManager.MakeAbsolutePath(Config.PathEntries.LogPathFragment, null), "Code Data Logger Files", "cdl"); @@ -353,10 +334,8 @@ namespace BizHawk.Client.EmuHawk void RunSave() { _recent.Add(_currentFilename); - using (var fs = new FileStream(_currentFilename, FileMode.Create, FileAccess.Write)) - { - _cdl.Save(fs); - } + using var fs = new FileStream(_currentFilename, FileMode.Create, FileAccess.Write); + _cdl.Save(fs); } private void SaveMenuItem_Click(object sender, EventArgs e) @@ -383,7 +362,7 @@ namespace BizHawk.Client.EmuHawk { var file = SaveFileDialog( _currentFilename, - PathManager.MakeAbsolutePath(Global.Config.PathEntries.LogPathFragment, null), + PathManager.MakeAbsolutePath(Config.PathEntries.LogPathFragment, null), "Code Data Logger Files", "cdl"); @@ -410,24 +389,22 @@ namespace BizHawk.Client.EmuHawk { var file = ToolFormBase.OpenFileDialog( _currentFilename, - PathManager.MakeAbsolutePath(Global.Config.PathEntries.LogPathFragment, null), + PathManager.MakeAbsolutePath(Config.PathEntries.LogPathFragment, null), "Code Data Logger Files", "cdl"); if (file != null) { - using (var fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read)) + using var fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read); + var newCDL = new CodeDataLog(); + newCDL.Load(fs); + if (!_cdl.Check(newCDL)) { - var newCDL = new CodeDataLog(); - newCDL.Load(fs); - if (!_cdl.Check(newCDL)) - { - MessageBox.Show(this, "CDL file does not match emulator's current memory map!"); - return; - } - _cdl.LogicalOrFrom(newCDL); - UpdateDisplay(true); + MessageBox.Show(this, "CDL file does not match emulator's current memory map!"); + return; } + _cdl.LogicalOrFrom(newCDL); + UpdateDisplay(true); } } } @@ -461,10 +438,8 @@ namespace BizHawk.Client.EmuHawk var result = sfd.ShowDialog(this); if (result == DialogResult.OK) { - using (var fs = new FileStream(sfd.FileName, FileMode.Create, FileAccess.Write)) - { - CodeDataLogger.DisassembleCDL(fs, _cdl); - } + using var fs = new FileStream(sfd.FileName, FileMode.Create, FileAccess.Write); + CodeDataLogger.DisassembleCDL(fs, _cdl); } } @@ -489,7 +464,7 @@ namespace BizHawk.Client.EmuHawk protected override void OnShown(EventArgs e) { - if (Global.Config.CDLAutoStart) + if (Config.CDLAutoStart) { if (_cdl == null) NewFileLogic(); @@ -499,20 +474,18 @@ namespace BizHawk.Client.EmuHawk protected override void OnClosed(EventArgs e) { - //deactivate logger - if (CodeDataLogger != null) //just in case... - CodeDataLogger.SetCDL(null); + CodeDataLogger?.SetCDL(null); } private void CDL_Load(object sender, EventArgs e) { - if (Global.Config.CDLAutoResume) + if (Config.CDLAutoResume) { try { autoloading = true; var autoresume_file = $"{PathManager.FilesystemSafeName(Global.Game)}.cdl"; - var autoresume_dir = PathManager.MakeAbsolutePath(Global.Config.PathEntries.LogPathFragment, null); + var autoresume_dir = PathManager.MakeAbsolutePath(Config.PathEntries.LogPathFragment, null); var autoresume_path = Path.Combine(autoresume_dir, autoresume_file); if (File.Exists(autoresume_path)) LoadFile(autoresume_path); @@ -596,17 +569,17 @@ namespace BizHawk.Client.EmuHawk private void miAutoSave_Click(object sender, EventArgs e) { - Global.Config.CDLAutoSave ^= true; + Config.CDLAutoSave ^= true; } private void miAutoStart_Click(object sender, EventArgs e) { - Global.Config.CDLAutoStart ^= true; + Config.CDLAutoStart ^= true; } private void miAutoResume_Click(object sender, EventArgs e) { - Global.Config.CDLAutoResume ^= true; + Config.CDLAutoResume ^= true; } } } diff --git a/BizHawk.Client.EmuHawk/tools/Cheats/Cheats.cs b/BizHawk.Client.EmuHawk/tools/Cheats/Cheats.cs index 67e0ec4e0b..cd99681fcb 100644 --- a/BizHawk.Client.EmuHawk/tools/Cheats/Cheats.cs +++ b/BizHawk.Client.EmuHawk/tools/Cheats/Cheats.cs @@ -91,11 +91,11 @@ namespace BizHawk.Client.EmuHawk var loadResult = Global.CheatList.Load(path, append: false); if (!loadResult) { - Global.Config.RecentCheats.HandleLoadError(path); + Config.RecentCheats.HandleLoadError(path); } else { - Global.Config.RecentCheats.Add(path); + Config.RecentCheats.Add(path); UpdateDialog(); UpdateMessageLabel(); } @@ -131,7 +131,7 @@ namespace BizHawk.Client.EmuHawk Global.CheatList.Load(file.FullName, append); UpdateDialog(); UpdateMessageLabel(); - Global.Config.RecentCheats.Add(Global.CheatList.CurrentFileName); + Config.RecentCheats.Add(Global.CheatList.CurrentFileName); } } } @@ -185,7 +185,7 @@ namespace BizHawk.Client.EmuHawk { GameGenieToolbarSeparator.Visible = LoadGameGenieToolbarItem.Visible = - GlobalWin.Tools.IsAvailable(); + Tools.IsAvailable(); } private void AddCheat() @@ -352,7 +352,7 @@ namespace BizHawk.Client.EmuHawk var result = !Global.CheatList.Changes || AskSaveChanges(); if (result) { - Global.CheatList.NewList(ToolManager.GenerateDefaultCheatFilename()); + Global.CheatList.NewList(Tools.GenerateDefaultCheatFilename()); UpdateDialog(); UpdateMessageLabel(); ToggleGameGenieButton(); @@ -381,7 +381,7 @@ namespace BizHawk.Client.EmuHawk { RecentSubMenu.DropDownItems.Clear(); RecentSubMenu.DropDownItems.AddRange( - Global.Config.RecentCheats.RecentMenu(LoadFileFromRecent)); + Config.RecentCheats.RecentMenu(LoadFileFromRecent)); } private void NewMenuItem_Click(object sender, EventArgs e) @@ -445,7 +445,7 @@ namespace BizHawk.Client.EmuHawk GameGenieSeparator.Visible = OpenGameGenieEncoderDecoderMenuItem.Visible = - GlobalWin.Tools.IsAvailable(); + Tools.IsAvailable(); } private void RemoveCheatMenuItem_Click(object sender, EventArgs e) @@ -554,7 +554,7 @@ namespace BizHawk.Client.EmuHawk private void OpenGameGenieEncoderDecoderMenuItem_Click(object sender, EventArgs e) { - GlobalWin.Tools.LoadGameGenieEc(); + Tools.LoadGameGenieEc(); } #endregion @@ -563,10 +563,10 @@ namespace BizHawk.Client.EmuHawk private void OptionsSubMenu_DropDownOpened(object sender, EventArgs e) { - AlwaysLoadCheatsMenuItem.Checked = Global.Config.LoadCheatFileByGame; - AutoSaveCheatsMenuItem.Checked = Global.Config.CheatsAutoSaveOnClose; - DisableCheatsOnLoadMenuItem.Checked = Global.Config.DisableCheatsOnLoad; - AutoloadMenuItem.Checked = Global.Config.RecentCheats.AutoLoad; + AlwaysLoadCheatsMenuItem.Checked = Config.LoadCheatFileByGame; + AutoSaveCheatsMenuItem.Checked = Config.CheatsAutoSaveOnClose; + DisableCheatsOnLoadMenuItem.Checked = Config.DisableCheatsOnLoad; + AutoloadMenuItem.Checked = Config.RecentCheats.AutoLoad; SaveWindowPositionMenuItem.Checked = Settings.SaveWindowPosition; AlwaysOnTopMenuItem.Checked = Settings.TopMost; FloatingWindowMenuItem.Checked = Settings.FloatingWindow; @@ -574,22 +574,22 @@ namespace BizHawk.Client.EmuHawk private void AlwaysLoadCheatsMenuItem_Click(object sender, EventArgs e) { - Global.Config.LoadCheatFileByGame ^= true; + Config.LoadCheatFileByGame ^= true; } private void AutoSaveCheatsMenuItem_Click(object sender, EventArgs e) { - Global.Config.CheatsAutoSaveOnClose ^= true; + Config.CheatsAutoSaveOnClose ^= true; } private void CheatsOnOffLoadMenuItem_Click(object sender, EventArgs e) { - Global.Config.DisableCheatsOnLoad ^= true; + Config.DisableCheatsOnLoad ^= true; } private void AutoloadMenuItem_Click(object sender, EventArgs e) { - Global.Config.RecentCheats.AutoLoad ^= true; + Config.RecentCheats.AutoLoad ^= true; } private void SaveWindowPositionMenuItem_Click(object sender, EventArgs e) @@ -620,9 +620,9 @@ namespace BizHawk.Client.EmuHawk CheatsMenu.Items.Add(CheatListView.ToColumnsMenu(ColumnToggleCallback)); - Global.Config.DisableCheatsOnLoad = false; - Global.Config.LoadCheatFileByGame = true; - Global.Config.CheatsAutoSaveOnClose = true; + Config.DisableCheatsOnLoad = false; + Config.LoadCheatFileByGame = true; + Config.CheatsAutoSaveOnClose = true; RefreshFloatingWindowControl(Settings.FloatingWindow); CheatListView.AllColumns.Clear(); @@ -700,7 +700,7 @@ namespace BizHawk.Client.EmuHawk var selected = SelectedCheats.ToList(); if (selected.Any()) { - GlobalWin.Tools.Load(); + Tools.Load(); if (selected.Select(x => x.Domain).Distinct().Count() > 1) { diff --git a/BizHawk.Client.EmuHawk/tools/HexEditor/HexEditor.cs b/BizHawk.Client.EmuHawk/tools/HexEditor/HexEditor.cs index 32dab44a7a..58fdef9895 100644 --- a/BizHawk.Client.EmuHawk/tools/HexEditor/HexEditor.cs +++ b/BizHawk.Client.EmuHawk/tools/HexEditor/HexEditor.cs @@ -169,9 +169,9 @@ namespace BizHawk.Client.EmuHawk _maxRow = _domain.Size / 2; // Don't reset scroll bar if restarting the same rom - if (_lastRom != GlobalWin.MainForm.CurrentlyOpenRom) + if (_lastRom != MainForm.CurrentlyOpenRom) { - _lastRom = GlobalWin.MainForm.CurrentlyOpenRom; + _lastRom = MainForm.CurrentlyOpenRom; ResetScrollBar(); } @@ -365,9 +365,9 @@ namespace BizHawk.Client.EmuHawk return (char)val; } - private static bool CurrentRomIsArchive() + private bool CurrentRomIsArchive() { - var path = GlobalWin.MainForm.CurrentlyOpenRom; + var path = MainForm.CurrentlyOpenRom; if (path == null) { return false; @@ -384,9 +384,9 @@ namespace BizHawk.Client.EmuHawk return file.IsArchive; } - private static byte[] GetRomBytes() + private byte[] GetRomBytes() { - var path = GlobalWin.MainForm.CurrentlyOpenRomArgs.OpenAdvanced.SimplePath; + var path = MainForm.CurrentlyOpenRomArgs.OpenAdvanced.SimplePath; if (string.IsNullOrEmpty(path)) { return new byte[] { 0xFF }; @@ -460,11 +460,11 @@ namespace BizHawk.Client.EmuHawk private void LoadConfigSettings() { - HexMenuStrip.BackColor = Global.Config.HexMenubarColor; - MemoryViewerBox.BackColor = Global.Config.HexBackgrndColor; - MemoryViewerBox.ForeColor = Global.Config.HexForegrndColor; - Header.BackColor = Global.Config.HexBackgrndColor; - Header.ForeColor = Global.Config.HexForegrndColor; + HexMenuStrip.BackColor = Config.HexMenubarColor; + MemoryViewerBox.BackColor = Config.HexBackgrndColor; + MemoryViewerBox.ForeColor = Config.HexForegrndColor; + Header.BackColor = Config.HexBackgrndColor; + Header.ForeColor = Config.HexForegrndColor; } private void CloseHexFind() @@ -842,7 +842,7 @@ namespace BizHawk.Client.EmuHawk { get { - string path = Global.Config.RecentRoms.MostRecent; + string path = Config.RecentRoms.MostRecent; if (string.IsNullOrWhiteSpace(path)) { @@ -862,7 +862,7 @@ namespace BizHawk.Client.EmuHawk { get { - string path = Global.Config.RecentRoms.MostRecent; + string path = Config.RecentRoms.MostRecent; if (string.IsNullOrWhiteSpace(path)) { @@ -1213,7 +1213,7 @@ namespace BizHawk.Client.EmuHawk { if (!CurrentRomIsArchive()) { - SaveFileBinary(GlobalWin.MainForm.CurrentlyOpenRom); + SaveFileBinary(MainForm.CurrentlyOpenRom); } } @@ -1281,10 +1281,10 @@ namespace BizHawk.Client.EmuHawk private void LoadTableFileMenuItem_Click(object sender, EventArgs e) { - string initialDirectory = PathManager.MakeAbsolutePath(Global.Config.PathEntries.ToolsPathFragment, null); - var romName = Global.Config.RecentRoms.MostRecent.Contains('|') - ? Global.Config.RecentRoms.MostRecent.Split('|').Last() - : Global.Config.RecentRoms.MostRecent; + string initialDirectory = PathManager.MakeAbsolutePath(Config.PathEntries.ToolsPathFragment, null); + var romName = Config.RecentRoms.MostRecent.Contains('|') + ? Config.RecentRoms.MostRecent.Split('|').Last() + : Config.RecentRoms.MostRecent; using var ofd = new OpenFileDialog { @@ -1587,16 +1587,16 @@ namespace BizHawk.Client.EmuHawk { if (_highlightedAddress.HasValue || _secondaryHighlightedAddresses.Any()) { - GlobalWin.Tools.LoadRamWatch(true); + Tools.LoadRamWatch(true); } if (_highlightedAddress.HasValue) { - GlobalWin.Tools.RamWatch.AddWatch(MakeWatch(_highlightedAddress.Value)); + Tools.RamWatch.AddWatch(MakeWatch(_highlightedAddress.Value)); } _secondaryHighlightedAddresses.ForEach(addr => - GlobalWin.Tools.RamWatch.AddWatch(MakeWatch(addr))); + Tools.RamWatch.AddWatch(MakeWatch(addr))); } private void FreezeAddressMenuItem_Click(object sender, EventArgs e) @@ -1684,15 +1684,15 @@ namespace BizHawk.Client.EmuHawk { MemoryViewerBox.BackColor = Color.FromName("Control"); MemoryViewerBox.ForeColor = Color.FromName("ControlText"); - this.HexMenuStrip.BackColor = Color.FromName("Control"); + HexMenuStrip.BackColor = Color.FromName("Control"); Header.BackColor = Color.FromName("Control"); Header.ForeColor = Color.FromName("ControlText"); - Global.Config.HexMenubarColor = Color.FromName("Control"); - Global.Config.HexForegrndColor = Color.FromName("ControlText"); - Global.Config.HexBackgrndColor = Color.FromName("Control"); - Global.Config.HexFreezeColor = Color.LightBlue; - Global.Config.HexHighlightColor = Color.Pink; - Global.Config.HexHighlightFreezeColor = Color.Violet; + Config.HexMenubarColor = Color.FromName("Control"); + Config.HexForegrndColor = Color.FromName("ControlText"); + Config.HexBackgrndColor = Color.FromName("Control"); + Config.HexFreezeColor = Color.LightBlue; + Config.HexHighlightColor = Color.Pink; + Config.HexHighlightFreezeColor = Color.Violet; } #endregion @@ -2097,7 +2097,7 @@ namespace BizHawk.Client.EmuHawk var rect = new Rectangle(GetAddressCoordinates(cheat.Address ?? 0), new Size(width, _fontHeight)); e.Graphics.DrawRectangle(_blackPen, rect); - _freezeBrush.Color = Global.Config.HexFreezeColor; + _freezeBrush.Color = Config.HexFreezeColor; e.Graphics.FillRectangle(_freezeBrush, rect); } } @@ -2119,13 +2119,13 @@ namespace BizHawk.Client.EmuHawk if (Global.CheatList.IsActive(_domain, addressHighlighted)) { - _freezeHighlightBrush.Color = Global.Config.HexHighlightFreezeColor; + _freezeHighlightBrush.Color = Config.HexHighlightFreezeColor; e.Graphics.FillRectangle(_freezeHighlightBrush, rect); e.Graphics.FillRectangle(_freezeHighlightBrush, textRect); } else { - _highlightBrush.Color = Global.Config.HexHighlightColor; + _highlightBrush.Color = Config.HexHighlightColor; e.Graphics.FillRectangle(_highlightBrush, rect); e.Graphics.FillRectangle(_highlightBrush, textRect); } @@ -2146,13 +2146,13 @@ namespace BizHawk.Client.EmuHawk if (Global.CheatList.IsActive(_domain, address)) { - _freezeHighlightBrush.Color = Global.Config.HexHighlightFreezeColor; + _freezeHighlightBrush.Color = Config.HexHighlightFreezeColor; e.Graphics.FillRectangle(_freezeHighlightBrush, rect); e.Graphics.FillRectangle(_freezeHighlightBrush, textRect); } else { - _secondaryHighlightBrush.Color = Color.FromArgb(0x44, Global.Config.HexHighlightColor); + _secondaryHighlightBrush.Color = Color.FromArgb(0x44, Config.HexHighlightColor); e.Graphics.FillRectangle(_secondaryHighlightBrush, rect); e.Graphics.FillRectangle(_secondaryHighlightBrush, textRect); } diff --git a/BizHawk.Client.EmuHawk/tools/Lua/LuaConsole.cs b/BizHawk.Client.EmuHawk/tools/Lua/LuaConsole.cs index 6f8c4ebb37..17bd2b0336 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/LuaConsole.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/LuaConsole.cs @@ -74,13 +74,13 @@ namespace BizHawk.Client.EmuHawk if (GlobalWin.DisplayManager.ClientExtraPadding != Padding.Empty) { GlobalWin.DisplayManager.ClientExtraPadding = new Padding(0); - GlobalWin.MainForm.FrameBufferResized(); + MainForm.FrameBufferResized(); } if (GlobalWin.DisplayManager.GameExtraPadding != Padding.Empty) { GlobalWin.DisplayManager.GameExtraPadding = new Padding(0); - GlobalWin.MainForm.FrameBufferResized(); + MainForm.FrameBufferResized(); } LuaImp.GuiLibrary.DrawFinish(); @@ -131,15 +131,15 @@ namespace BizHawk.Client.EmuHawk LuaImp.ScriptList.ChangedCallback = SessionChangedCallback; LuaImp.ScriptList.LoadCallback = ClearOutputWindow; - if (Global.Config.RecentLuaSession.AutoLoad && !Global.Config.RecentLuaSession.Empty) + if (Config.RecentLuaSession.AutoLoad && !Config.RecentLuaSession.Empty) { - LoadSessionFromRecent(Global.Config.RecentLuaSession.MostRecent); + LoadSessionFromRecent(Config.RecentLuaSession.MostRecent); } - else if (Global.Config.RecentLua.AutoLoad) + else if (Config.RecentLua.AutoLoad) { - if (!Global.Config.RecentLua.Empty) + if (!Config.RecentLua.Empty) { - LoadLuaFile(Global.Config.RecentLua.MostRecent); + LoadLuaFile(Config.RecentLua.MostRecent); } } @@ -234,7 +234,7 @@ namespace BizHawk.Client.EmuHawk private void AddFileWatches() { - if (Global.Config.LuaReloadOnScriptFileChange) + if (Config.LuaReloadOnScriptFileChange) { _watches.Clear(); foreach (var item in LuaImp.ScriptList.Where(s => !s.IsSeparator)) @@ -285,7 +285,7 @@ namespace BizHawk.Client.EmuHawk foreach (var file in LuaImp.ScriptList .Where(file => processedPath == file.Path && file.Enabled == false - && !Global.Config.DisableLuaScriptsOnLoad)) + && !Config.DisableLuaScriptsOnLoad)) { if (file.Thread != null) { @@ -303,9 +303,9 @@ namespace BizHawk.Client.EmuHawk LuaImp.ScriptList.Add(luaFile); LuaListView.RowCount = LuaImp.ScriptList.Count; - Global.Config.RecentLua.Add(processedPath); + Config.RecentLua.Add(processedPath); - if (!Global.Config.DisableLuaScriptsOnLoad) + if (!Config.DisableLuaScriptsOnLoad) { luaFile.State = LuaFile.RunState.Running; EnableLuaFile(luaFile); @@ -315,7 +315,7 @@ namespace BizHawk.Client.EmuHawk luaFile.State = LuaFile.RunState.Disabled; } - if (Global.Config.LuaReloadOnScriptFileChange) + if (Config.LuaReloadOnScriptFileChange) { CreateFileWatcher(processedPath); } @@ -612,7 +612,7 @@ namespace BizHawk.Client.EmuHawk { if (!LuaImp.ScriptList.LoadLuaSession(path)) { - Global.Config.RecentLuaSession.HandleLoadError(path); + Config.RecentLuaSession.HandleLoadError(path); } else { @@ -682,14 +682,14 @@ namespace BizHawk.Client.EmuHawk { RecentSessionsSubMenu.DropDownItems.Clear(); RecentSessionsSubMenu.DropDownItems.AddRange( - Global.Config.RecentLuaSession.RecentMenu(LoadSessionFromRecent, true)); + Config.RecentLuaSession.RecentMenu(LoadSessionFromRecent, true)); } private void RecentScriptsSubMenu_DropDownOpened(object sender, EventArgs e) { RecentScriptsSubMenu.DropDownItems.Clear(); RecentScriptsSubMenu.DropDownItems.AddRange( - Global.Config.RecentLua.RecentMenu(LoadLuaFile, true)); + Config.RecentLua.RecentMenu(LoadLuaFile, true)); } private void NewSessionMenuItem_Click(object sender, EventArgs e) @@ -784,7 +784,7 @@ namespace BizHawk.Client.EmuHawk { InitialDirectory = !string.IsNullOrWhiteSpace(LuaImp.ScriptList.Filename) ? Path.GetDirectoryName(LuaImp.ScriptList.Filename) : - PathManager.MakeAbsolutePath(Global.Config.PathEntries.LuaPathFragment, null), + PathManager.MakeAbsolutePath(Config.PathEntries.LuaPathFragment, null), DefaultExt = ".lua", FileName = !string.IsNullOrWhiteSpace(LuaImp.ScriptList.Filename) ? Path.GetFileNameWithoutExtension(LuaImp.ScriptList.Filename) : @@ -839,7 +839,7 @@ namespace BizHawk.Client.EmuHawk private void ToggleScriptMenuItem_Click(object sender, EventArgs e) { - var files = !SelectedFiles.Any() && Global.Config.ToggleAllIfNoneSelected + var files = !SelectedFiles.Any() && Config.ToggleAllIfNoneSelected ? LuaImp.ScriptList : SelectedFiles; foreach (var file in files) @@ -870,7 +870,7 @@ namespace BizHawk.Client.EmuHawk // Shenanigans // We want any gui.text messages from a script to immediately update even when paused GlobalWin.OSD.ClearGuiText(); - GlobalWin.Tools.UpdateToolsAfter(); + Tools.UpdateToolsAfter(); LuaImp.EndLuaDrawing(); LuaImp.StartLuaDrawing(); } @@ -1066,26 +1066,26 @@ namespace BizHawk.Client.EmuHawk private void OptionsSubMenu_DropDownOpened(object sender, EventArgs e) { - DisableScriptsOnLoadMenuItem.Checked = Global.Config.DisableLuaScriptsOnLoad; - ReturnAllIfNoneSelectedMenuItem.Checked = Global.Config.ToggleAllIfNoneSelected; - ReloadWhenScriptFileChangesMenuItem.Checked = Global.Config.LuaReloadOnScriptFileChange; + DisableScriptsOnLoadMenuItem.Checked = Config.DisableLuaScriptsOnLoad; + ReturnAllIfNoneSelectedMenuItem.Checked = Config.ToggleAllIfNoneSelected; + ReloadWhenScriptFileChangesMenuItem.Checked = Config.LuaReloadOnScriptFileChange; } private void DisableScriptsOnLoadMenuItem_Click(object sender, EventArgs e) { - Global.Config.DisableLuaScriptsOnLoad ^= true; + Config.DisableLuaScriptsOnLoad ^= true; } private void ToggleAllIfNoneSelectedMenuItem_Click(object sender, EventArgs e) { - Global.Config.ToggleAllIfNoneSelected ^= true; + Config.ToggleAllIfNoneSelected ^= true; } private void ReloadWhenScriptFileChangesMenuItem_Click(object sender, EventArgs e) { - Global.Config.LuaReloadOnScriptFileChange ^= true; + Config.LuaReloadOnScriptFileChange ^= true; - if (Global.Config.LuaReloadOnScriptFileChange) + if (Config.LuaReloadOnScriptFileChange) { AddFileWatches(); } @@ -1161,7 +1161,7 @@ namespace BizHawk.Client.EmuHawk private void FunctionsListMenuItem_Click(object sender, EventArgs e) { - new LuaFunctionsForm().Show(); + new LuaFunctionsForm(LuaImp.Docs).Show(); } private void OnlineDocsMenuItem_Click(object sender, EventArgs e) @@ -1185,7 +1185,7 @@ namespace BizHawk.Client.EmuHawk LuaImp.ScriptList.Any(file => file.Enabled); ClearRegisteredFunctionsContextItem.Enabled = - GlobalWin.Tools.LuaConsole.LuaImp.RegisteredFunctions.Any(); + LuaImp.RegisteredFunctions.Any(); } private void ConsoleContextMenu_Opening(object sender, CancelEventArgs e) @@ -1197,7 +1197,7 @@ namespace BizHawk.Client.EmuHawk OutputBox.Text.Any(); ClearRegisteredFunctionsLogContextItem.Enabled = - GlobalWin.Tools.LuaConsole.LuaImp.RegisteredFunctions.Any(); + LuaImp.RegisteredFunctions.Any(); } private void ClearConsoleContextItem_Click(object sender, EventArgs e) @@ -1235,7 +1235,7 @@ namespace BizHawk.Client.EmuHawk private void ClearRegisteredFunctionsContextMenuItem_Click(object sender, EventArgs e) { - GlobalWin.Tools.LuaConsole.LuaImp.RegisteredFunctions.Clear(); + LuaImp.RegisteredFunctions.Clear(); } #endregion diff --git a/BizHawk.Client.EmuHawk/tools/Lua/LuaFunctionsForm.cs b/BizHawk.Client.EmuHawk/tools/Lua/LuaFunctionsForm.cs index c30ec46136..a516856712 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/LuaFunctionsForm.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/LuaFunctionsForm.cs @@ -10,11 +10,19 @@ namespace BizHawk.Client.EmuHawk { public partial class LuaFunctionsForm : Form { + private readonly LuaDocumentation _docs; private readonly Sorting _columnSort = new Sorting(); private List _functionList = new List(); private List _filteredList = new List(); + public LuaFunctionsForm(LuaDocumentation docs) + { + _docs = docs; + InitializeComponent(); + FunctionView.RetrieveVirtualItem += FunctionView_QueryItemText; + } + private void GenerateFilteredList() { if (!string.IsNullOrWhiteSpace(FilterBox.Text)) @@ -29,15 +37,9 @@ namespace BizHawk.Client.EmuHawk } } - public LuaFunctionsForm() - { - InitializeComponent(); - FunctionView.RetrieveVirtualItem += FunctionView_QueryItemText; - } - private void LuaFunctionList_Load(object sender, EventArgs e) { - _functionList = GlobalWin.Tools.LuaConsole.LuaImp.Docs + _functionList = _docs .OrderBy(l => l.Library) .ThenBy(l => l.Name) .ToList(); @@ -183,7 +185,7 @@ namespace BizHawk.Client.EmuHawk private void ToWikiMarkupButton_Click(object sender, EventArgs e) { - Clipboard.SetDataObject(GlobalWin.Tools.LuaConsole.LuaImp.Docs.ToTASVideosWikiMarkup()); + Clipboard.SetDataObject(_docs.ToTASVideosWikiMarkup()); } } } diff --git a/BizHawk.Client.EmuHawk/tools/Lua/LuaRegisteredFunctionsList.cs b/BizHawk.Client.EmuHawk/tools/Lua/LuaRegisteredFunctionsList.cs index fee2f09f21..254c661e85 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/LuaRegisteredFunctionsList.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/LuaRegisteredFunctionsList.cs @@ -102,7 +102,7 @@ namespace BizHawk.Client.EmuHawk private void RemoveAllBtn_Click(object sender, EventArgs e) { - GlobalWin.Tools.LuaConsole.LuaImp.RegisteredFunctions.ClearAll(); + GlobalWin.Tools.LuaConsole.LuaImp.RegisteredFunctions.Clear(); PopulateListView(); } diff --git a/BizHawk.Client.EmuHawk/tools/Macros/MacroInput.cs b/BizHawk.Client.EmuHawk/tools/Macros/MacroInput.cs index 5f5c434c64..036e620c20 100644 --- a/BizHawk.Client.EmuHawk/tools/Macros/MacroInput.cs +++ b/BizHawk.Client.EmuHawk/tools/Macros/MacroInput.cs @@ -20,10 +20,7 @@ namespace BizHawk.Client.EmuHawk private readonly List _unsavedZones = new List(); private bool _selecting = false; - private IMovie CurrentMovie - { - get { return Global.MovieSession.Movie; } - } + private IMovie CurrentMovie => Global.MovieSession.Movie; // Still need to make sure the user can't load and use macros that // have options only available for TasMovie @@ -39,7 +36,7 @@ namespace BizHawk.Client.EmuHawk { // Movie recording must be active (check TAStudio because opening a project re-loads the ROM, // which resets tools before the movie session becomes active) - if (!Global.MovieSession.Movie.IsActive && !GlobalWin.Tools.IsLoaded()) + if (!Global.MovieSession.Movie.IsActive() && !GlobalWin.Tools.IsLoaded()) { MessageBox.Show("In order to use this tool you must be recording a movie."); Close(); diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/PlaybackBox.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/PlaybackBox.cs index fba4cb4287..acd7cd3164 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/PlaybackBox.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/PlaybackBox.cs @@ -40,7 +40,7 @@ namespace BizHawk.Client.EmuHawk [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool RecordingMode { - get => Global.MovieSession.Movie.IsRecording; + get => Global.MovieSession.Movie.IsRecording(); set { RecordingModeCheckbox.Checked = value; diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.IControlMainForm.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.IControlMainForm.cs index e75103c97d..b07b5ab029 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.IControlMainForm.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.IControlMainForm.cs @@ -1,4 +1,6 @@ -namespace BizHawk.Client.EmuHawk +using BizHawk.Client.Common; + +namespace BizHawk.Client.EmuHawk { public partial class TAStudio : IControlMainform { @@ -60,11 +62,11 @@ public void ToggleReadOnly() { - if (CurrentTasMovie.IsPlaying) + if (CurrentTasMovie.IsPlaying()) { TastudioRecordMode(); } - else if (CurrentTasMovie.IsRecording) + else if (CurrentTasMovie.IsRecording()) { TastudioPlayMode(); } @@ -90,15 +92,15 @@ public bool Rewind() { // copy pasted from TasView_MouseWheel(), just without notch logic - if (Mainform.IsSeeking && !Mainform.EmulatorPaused) + if (MainForm.IsSeeking && !MainForm.EmulatorPaused) { - Mainform.PauseOnFrame--; + MainForm.PauseOnFrame--; // that's a weird condition here, but for whatever reason it works best - if (Emulator.Frame >= Mainform.PauseOnFrame) + if (Emulator.Frame >= MainForm.PauseOnFrame) { - Mainform.PauseEmulator(); - Mainform.PauseOnFrame = null; + MainForm.PauseEmulator(); + MainForm.PauseOnFrame = null; StopSeeking(); GoToPreviousFrame(); } diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.ListView.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.ListView.cs index a8118205c0..c441fb982c 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.ListView.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.ListView.cs @@ -81,19 +81,19 @@ namespace BizHawk.Client.EmuHawk if (!fromMiddleClick) { - if (Mainform.PauseOnFrame != null) + if (MainForm.PauseOnFrame != null) { StopSeeking(true); // don't restore rec mode just yet, as with heavy editing checkbox updating causes lag } _seekStartFrame = Emulator.Frame; } - Mainform.PauseOnFrame = frame.Value; - int? diff = Mainform.PauseOnFrame - _seekStartFrame; + MainForm.PauseOnFrame = frame.Value; + int? diff = MainForm.PauseOnFrame - _seekStartFrame; - WasRecording = CurrentTasMovie.IsRecording || WasRecording; + WasRecording = CurrentTasMovie.IsRecording() || WasRecording; TastudioPlayMode(); // suspend rec mode until seek ends, to allow mouse editing - Mainform.UnpauseEmulator(); + MainForm.UnpauseEmulator(); if (!_seekBackgroundWorker.IsBusy && diff > TasView.VisibleRows) { @@ -110,10 +110,10 @@ namespace BizHawk.Client.EmuHawk WasRecording = false; } - Mainform.PauseOnFrame = null; + MainForm.PauseOnFrame = null; if (_unpauseAfterSeeking) { - Mainform.UnpauseEmulator(); + MainForm.UnpauseEmulator(); _unpauseAfterSeeking = false; } @@ -173,7 +173,7 @@ namespace BizHawk.Client.EmuHawk offsetY = 5; } - if (index == Emulator.Frame && index == Mainform.PauseOnFrame) + if (index == Emulator.Frame && index == MainForm.PauseOnFrame) { bitmap = TasView.HorizontalOrientation ? ts_v_arrow_green_blue : @@ -262,11 +262,11 @@ namespace BizHawk.Client.EmuHawk { TasMovieRecord record = CurrentTasMovie[index]; - if (Mainform.IsSeeking && Mainform.PauseOnFrame == index) + if (MainForm.IsSeeking && MainForm.PauseOnFrame == index) { color = CurrentFrame_InputLog; } - else if (!Mainform.IsSeeking && Emulator.Frame == index) + else if (!MainForm.IsSeeking && Emulator.Frame == index) { color = CurrentFrame_InputLog; } @@ -514,7 +514,7 @@ namespace BizHawk.Client.EmuHawk if (e.Button == MouseButtons.Middle) { - if (Mainform.EmulatorPaused) + if (MainForm.EmulatorPaused) { TasMovieRecord record = CurrentTasMovie[LastPositionFrame]; if (!record.Lagged.HasValue && LastPositionFrame > Emulator.Frame) @@ -523,12 +523,12 @@ namespace BizHawk.Client.EmuHawk } else { - Mainform.UnpauseEmulator(); + MainForm.UnpauseEmulator(); } } else { - Mainform.PauseEmulator(); + MainForm.PauseEmulator(); } return; @@ -541,7 +541,7 @@ namespace BizHawk.Client.EmuHawk int frame = TasView.CurrentCell.RowIndex.Value; string buttonName = TasView.CurrentCell.Column.Name; - WasRecording = CurrentTasMovie.IsRecording || WasRecording; + WasRecording = CurrentTasMovie.IsRecording() || WasRecording; if (e.Button == MouseButtons.Left) { @@ -604,7 +604,7 @@ namespace BizHawk.Client.EmuHawk } else if (TasView.CurrentCell.Column.Type != ColumnType.Text) // User changed input { - bool wasPaused = Mainform.EmulatorPaused; + bool wasPaused = MainForm.EmulatorPaused; if (ControllerType.BoolButtons.Contains(buttonName)) { @@ -713,7 +713,7 @@ namespace BizHawk.Client.EmuHawk // taseditor behavior if (!wasPaused) { - Mainform.UnpauseEmulator(); + MainForm.UnpauseEmulator(); } } } @@ -877,15 +877,15 @@ namespace BizHawk.Client.EmuHawk } // warning: tastudio rewind hotkey/button logic is copy pasted from here! - if (Mainform.IsSeeking && !Mainform.EmulatorPaused) + if (MainForm.IsSeeking && !MainForm.EmulatorPaused) { - Mainform.PauseOnFrame -= notch; + MainForm.PauseOnFrame -= notch; // that's a weird condition here, but for whatever reason it works best - if (notch > 0 && Emulator.Frame >= Mainform.PauseOnFrame) + if (notch > 0 && Emulator.Frame >= MainForm.PauseOnFrame) { - Mainform.PauseEmulator(); - Mainform.PauseOnFrame = null; + MainForm.PauseEmulator(); + MainForm.PauseOnFrame = null; StopSeeking(); GoToFrame(Emulator.Frame - notch); } @@ -953,7 +953,7 @@ namespace BizHawk.Client.EmuHawk // skip rerecord counting on drawing entirely, mouse down is enough // avoid introducing another global bool wasCountingRerecords = CurrentTasMovie.IsCountingRerecords; - WasRecording = CurrentTasMovie.IsRecording || WasRecording; + WasRecording = CurrentTasMovie.IsRecording() || WasRecording; int startVal, endVal; int frame = e.NewCell.RowIndex.Value; @@ -976,7 +976,7 @@ namespace BizHawk.Client.EmuHawk } } - if (_startCursorDrag && !Mainform.IsSeeking) + if (_startCursorDrag && !MainForm.IsSeeking) { GoToFrame(e.NewCell.RowIndex.Value); } diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.MenuItems.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.MenuItems.cs index 6fa87657f3..fbac28b551 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.MenuItems.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.MenuItems.cs @@ -39,7 +39,7 @@ namespace BizHawk.Client.EmuHawk private void NewTasMenuItem_Click(object sender, EventArgs e) { - if (!Mainform.GameIsClosing) + if (!MainForm.GameIsClosing) { StartNewTasMovie(); } @@ -60,7 +60,7 @@ namespace BizHawk.Client.EmuHawk var ofd = new OpenFileDialog { FileName = filename, - InitialDirectory = PathManager.MakeAbsolutePath(Global.Config.PathEntries.MoviesPathFragment, null), + InitialDirectory = PathManager.MakeAbsolutePath(Config.PathEntries.MoviesPathFragment, null), Filter = string.Format( "All Available Files ({0})|{0}|TAS Project Files (*.{1})|*.{1}|Movie Files (*.{2})|*.{2}|All Files|*.*", all, TasMovie.Extension, MovieService.DefaultExtension) @@ -78,7 +78,7 @@ namespace BizHawk.Client.EmuHawk var result1 = MessageBox.Show("This is a regular movie, a new project must be created from it, in order to use in TAStudio\nProceed?", "Convert movie", MessageBoxButtons.OKCancel, MessageBoxIcon.Question); if (result1 == DialogResult.OK) { - Mainform.StartNewMovie(MovieService.Get(ofd.FileName), false); + MainForm.StartNewMovie(MovieService.Get(ofd.FileName), false); ConvertCurrentMovieToTasproj(); StartNewMovieWrapper(false); SetUpColumns(); @@ -145,7 +145,7 @@ namespace BizHawk.Client.EmuHawk var file = SaveFileDialog( filename, - PathManager.MakeAbsolutePath(Global.Config.PathEntries.MoviesPathFragment, null), + PathManager.MakeAbsolutePath(Config.PathEntries.MoviesPathFragment, null), "Tas Project Files", "tasproj"); @@ -168,7 +168,7 @@ namespace BizHawk.Client.EmuHawk _autosaveTimer.Start(); } - Mainform.SetWindowText(); + MainForm.SetWindowText(); GlobalWin.Sound.StartSound(); } @@ -264,7 +264,7 @@ namespace BizHawk.Client.EmuHawk private void RecentMacrosMenuItem_DropDownOpened(object sender, EventArgs e) { recentMacrosToolStripMenuItem.DropDownItems.Clear(); - recentMacrosToolStripMenuItem.DropDownItems.AddRange(Global.Config.RecentMacros.RecentMenu(DummyLoadMacro)); + recentMacrosToolStripMenuItem.DropDownItems.AddRange(Config.RecentMacros.RecentMenu(DummyLoadMacro)); } private void ToBk2MenuItem_Click(object sender, EventArgs e) @@ -357,16 +357,16 @@ namespace BizHawk.Client.EmuHawk StateHistoryIntegrityCheckMenuItem.Visible = VersionInfo.DeveloperBuild; - UndoMenuItem.ShortcutKeyDisplayString = Global.Config.HotkeyBindings["Undo"].Bindings; - RedoMenuItem.ShortcutKeyDisplayString = Global.Config.HotkeyBindings["Redo"].Bindings; - SelectBetweenMarkersMenuItem.ShortcutKeyDisplayString = Global.Config.HotkeyBindings["Select between Markers"].Bindings; - SelectAllMenuItem.ShortcutKeyDisplayString = Global.Config.HotkeyBindings["Select All"].Bindings; - ReselectClipboardMenuItem.ShortcutKeyDisplayString = Global.Config.HotkeyBindings["Reselect Clip."].Bindings; - ClearFramesMenuItem.ShortcutKeyDisplayString = Global.Config.HotkeyBindings["Clear Frames"].Bindings; - InsertFrameMenuItem.ShortcutKeyDisplayString = Global.Config.HotkeyBindings["Insert Frame"].Bindings; - InsertNumFramesMenuItem.ShortcutKeyDisplayString = Global.Config.HotkeyBindings["Insert # Frames"].Bindings; - DeleteFramesMenuItem.ShortcutKeyDisplayString = Global.Config.HotkeyBindings["Delete Frames"].Bindings; - CloneFramesMenuItem.ShortcutKeyDisplayString = Global.Config.HotkeyBindings["Clone Frames"].Bindings; + UndoMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Undo"].Bindings; + RedoMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Redo"].Bindings; + SelectBetweenMarkersMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Select between Markers"].Bindings; + SelectAllMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Select All"].Bindings; + ReselectClipboardMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Reselect Clip."].Bindings; + ClearFramesMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Clear Frames"].Bindings; + InsertFrameMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Insert Frame"].Bindings; + InsertNumFramesMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Insert # Frames"].Bindings; + DeleteFramesMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Delete Frames"].Bindings; + CloneFramesMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Clone Frames"].Bindings; } public void ClearFramesExternal() @@ -865,7 +865,7 @@ namespace BizHawk.Client.EmuHawk int goToFrame = CurrentTasMovie.LastStatedFrame; do { - Mainform.FrameAdvance(); + MainForm.FrameAdvance(); if (CurrentTasMovie.TasStateManager.HasState(Emulator.Frame)) { @@ -1106,7 +1106,7 @@ namespace BizHawk.Client.EmuHawk { new MovieHeaderEditor(CurrentTasMovie) { - Owner = Mainform, + Owner = Owner, Location = this.ChildPointToScreen(TasView) }.Show(); UpdateChangesIndicator(); @@ -1116,9 +1116,9 @@ namespace BizHawk.Client.EmuHawk { new StateHistorySettingsForm(CurrentTasMovie.TasStateManager.Settings) { - Owner = Mainform, + Owner = Owner, Location = this.ChildPointToScreen(TasView), - Statable = this.StatableEmulator + Statable = StatableEmulator }.ShowDialog(); CurrentTasMovie.TasStateManager.UpdateStateFrequency(); UpdateChangesIndicator(); @@ -1488,20 +1488,20 @@ namespace BizHawk.Client.EmuHawk StartFromNowSeparator.Visible = StartNewProjectFromNowMenuItem.Visible || StartANewProjectFromSaveRamMenuItem.Visible; RemoveMarkersContextMenuItem.Enabled = CurrentTasMovie.Markers.Any(m => TasView.SelectedRows.Contains(m.Frame)); // Disable the option to remove markers if no markers are selected (FCEUX does this). - CancelSeekContextMenuItem.Enabled = Mainform.PauseOnFrame.HasValue; + CancelSeekContextMenuItem.Enabled = MainForm.PauseOnFrame.HasValue; BranchContextMenuItem.Visible = TasView.CurrentCell?.RowIndex == Emulator.Frame; - SelectBetweenMarkersContextMenuItem.ShortcutKeyDisplayString = Global.Config.HotkeyBindings["Sel. bet. Markers"].Bindings; - InsertNumFramesContextMenuItem.ShortcutKeyDisplayString = Global.Config.HotkeyBindings["Insert # Frames"].Bindings; - ClearContextMenuItem.ShortcutKeyDisplayString = Global.Config.HotkeyBindings["Clear Frames"].Bindings; - InsertFrameContextMenuItem.ShortcutKeyDisplayString = Global.Config.HotkeyBindings["Insert Frame"].Bindings; - DeleteFramesContextMenuItem.ShortcutKeyDisplayString = Global.Config.HotkeyBindings["Delete Frames"].Bindings; - CloneContextMenuItem.ShortcutKeyDisplayString = Global.Config.HotkeyBindings["Clone Frames"].Bindings; + SelectBetweenMarkersContextMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Sel. bet. Markers"].Bindings; + InsertNumFramesContextMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Insert # Frames"].Bindings; + ClearContextMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Clear Frames"].Bindings; + InsertFrameContextMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Insert Frame"].Bindings; + DeleteFramesContextMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Delete Frames"].Bindings; + CloneContextMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Clone Frames"].Bindings; } private void CancelSeekContextMenuItem_Click(object sender, EventArgs e) { - Mainform.PauseOnFrame = null; + MainForm.PauseOnFrame = null; RefreshTasView(); } @@ -1519,7 +1519,7 @@ namespace BizHawk.Client.EmuHawk TasMovie newProject = CurrentTasMovie.ConvertToSavestateAnchoredMovie( index, (byte[])StatableEmulator.SaveStateBinary().Clone()); - Mainform.PauseEmulator(); + MainForm.PauseEmulator(); LoadFile(new FileInfo(newProject.Filename), true); } } @@ -1539,7 +1539,7 @@ namespace BizHawk.Client.EmuHawk GoToFrame(index); TasMovie newProject = CurrentTasMovie.ConvertToSaveRamAnchoredMovie( SaveRamEmulator.CloneSaveRam()); - Mainform.PauseEmulator(); + MainForm.PauseEmulator(); LoadFile(new FileInfo(newProject.Filename), true); } else diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.Navigation.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.Navigation.cs index 8cee89a134..a51eaff86c 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.Navigation.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.Navigation.cs @@ -1,4 +1,6 @@ -namespace BizHawk.Client.EmuHawk +using BizHawk.Client.Common; + +namespace BizHawk.Client.EmuHawk { public partial class TAStudio { @@ -11,7 +13,7 @@ { if (frame <= Emulator.Frame) { - if ((Mainform.EmulatorPaused || !Mainform.IsSeeking) + if ((MainForm.EmulatorPaused || !MainForm.IsSeeking) && !CurrentTasMovie.LastPositionStable) { LastPositionFrame = Emulator.Frame; @@ -27,7 +29,7 @@ { // If seeking to a frame before or at the end of the movie, use StartAtNearestFrameAndEmulate // Otherwise, load the latest state (if not already there) and seek while recording. - WasRecording = CurrentTasMovie.IsRecording || WasRecording; + WasRecording = CurrentTasMovie.IsRecording() || WasRecording; if (frame <= CurrentTasMovie.InputLogLength) { @@ -40,11 +42,11 @@ { if (frame == Emulator.Frame + 1) // We are at the end of the movie and advancing one frame, therefore we are recording, simply emulate a frame { - bool wasPaused = Mainform.EmulatorPaused; - Mainform.FrameAdvance(); + bool wasPaused = MainForm.EmulatorPaused; + MainForm.FrameAdvance(); if (!wasPaused) { - Mainform.UnpauseEmulator(); + MainForm.UnpauseEmulator(); } } else diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.cs index 4404836dd0..c08558a2b6 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.cs @@ -21,10 +21,9 @@ namespace BizHawk.Client.EmuHawk { // TODO: UI flow that conveniently allows to start from savestate public TasMovie CurrentTasMovie => Global.MovieSession.Movie as TasMovie; - private MainForm Mainform => GlobalWin.MainForm; public bool IsInMenuLoop { get; private set; } - public string StatesPath => PathManager.MakeAbsolutePath(Global.Config.PathEntries["Global", "TAStudio states"].Path, null); + public string StatesPath => PathManager.MakeAbsolutePath(Config.PathEntries["Global", "TAStudio states"].Path, null); private readonly List _tasClipboard = new List(); private const string CursorColumnName = "CursorColumn"; @@ -212,14 +211,14 @@ namespace BizHawk.Client.EmuHawk this.Invoke(() => SavingProgressBar.Visible = true); for (;;) { - if (_seekBackgroundWorker.CancellationPending || !IsHandleCreated || !Mainform.PauseOnFrame.HasValue) + if (_seekBackgroundWorker.CancellationPending || !IsHandleCreated || !MainForm.PauseOnFrame.HasValue) { e.Cancel = true; break; } int diff = Emulator.Frame - _seekStartFrame.Value; - int unit = Mainform.PauseOnFrame.Value - _seekStartFrame.Value; + int unit = MainForm.PauseOnFrame.Value - _seekStartFrame.Value; double progress = 0; if (diff != 0 && unit != 0) @@ -323,8 +322,8 @@ namespace BizHawk.Client.EmuHawk private bool InitializeOnLoad() { - Mainform.PauseOnFrame = null; - Mainform.PauseEmulator(); + MainForm.PauseOnFrame = null; + MainForm.PauseEmulator(); // Start Scenario 0: core needs a nag // But do not nag if auto-loading @@ -334,7 +333,7 @@ namespace BizHawk.Client.EmuHawk } // Start Scenario 1: A regular movie is active - if (Global.MovieSession.Movie.IsActive && !(Global.MovieSession.Movie is TasMovie)) + if (Global.MovieSession.Movie.IsActive() && !(Global.MovieSession.Movie is TasMovie)) { var result = MessageBox.Show("In order to use Tastudio, a new project must be created from the current movie\nThe current movie will be saved and closed, and a new project file will be created\nProceed?", "Convert movie", MessageBoxButtons.OKCancel, MessageBoxIcon.Question); if (result == DialogResult.OK) @@ -350,7 +349,7 @@ namespace BizHawk.Client.EmuHawk } // Start Scenario 2: A tasproj is already active - else if (Global.MovieSession.Movie.IsActive && Global.MovieSession.Movie is TasMovie) + else if (Global.MovieSession.Movie.IsActive() && Global.MovieSession.Movie is TasMovie) { bool result = LoadFile(new FileInfo(CurrentTasMovie.Filename), gotoFrame: Emulator.Frame); if (!result) @@ -489,7 +488,7 @@ namespace BizHawk.Client.EmuHawk BoolPatterns[BoolPatterns.Length - 2] = new AutoPatternBool(1, 0); BoolPatterns[BoolPatterns.Length - 1] = new AutoPatternBool( - Global.Config.AutofireOn, Global.Config.AutofireOff); + Config.AutofireOn, Config.AutofireOff); for (int i = fStart; i < FloatPatterns.Length - 2; i++) { @@ -498,7 +497,7 @@ namespace BizHawk.Client.EmuHawk FloatPatterns[FloatPatterns.Length - 2] = new AutoPatternFloat(new[] { 1f }); FloatPatterns[FloatPatterns.Length - 1] = new AutoPatternFloat( - 1f, Global.Config.AutofireOn, 0f, Global.Config.AutofireOff); + 1f, Config.AutofireOn, 0f, Config.AutofireOff); SetUpToolStripColumns(); } @@ -523,14 +522,14 @@ namespace BizHawk.Client.EmuHawk private void EngageTastudio() { - GlobalWin.OSD.AddMessage("TAStudio engaged"); + MainForm.AddOnScreenMessage("TAStudio engaged"); SetTasMovieCallbacks(); SetTextProperty(); - Mainform.RelinquishControl(this); - _originalEndAction = Global.Config.MovieEndAction; - Mainform.ClearRewindData(); - Global.Config.MovieEndAction = MovieEndAction.Record; - Mainform.SetMainformMovieInfo(); + MainForm.RelinquishControl(this); + _originalEndAction = Config.MovieEndAction; + MainForm.ClearRewindData(); + Config.MovieEndAction = MovieEndAction.Record; + MainForm.SetMainformMovieInfo(); Global.MovieSession.ReadOnly = true; SetSplicer(); } @@ -681,7 +680,7 @@ namespace BizHawk.Client.EmuHawk SetTasMovieCallbacks(movie as TasMovie); - bool result = Mainform.StartNewMovie(movie, record); + bool result = MainForm.StartNewMovie(movie, record); if (result) { CurrentTasMovie.TasStateManager.Capture(); // Capture frame 0 always. @@ -744,17 +743,17 @@ namespace BizHawk.Client.EmuHawk private void TastudioStopMovie() { Global.MovieSession.StopMovie(false); - Mainform.SetMainformMovieInfo(); + MainForm.SetMainformMovieInfo(); } private void DisengageTastudio() { - Mainform.PauseOnFrame = null; - GlobalWin.OSD.AddMessage("TAStudio disengaged"); + MainForm.PauseOnFrame = null; + MainForm.AddOnScreenMessage("TAStudio disengaged"); Global.MovieSession.Movie = MovieService.DefaultInstance; - Mainform.TakeBackControl(); - Global.Config.MovieEndAction = _originalEndAction; - Mainform.SetMainformMovieInfo(); + MainForm.TakeBackControl(); + Config.MovieEndAction = _originalEndAction; + MainForm.SetMainformMovieInfo(); // Do not keep TAStudio's disk save states. // if (Directory.Exists(statesPath)) Directory.Delete(statesPath, true); @@ -849,7 +848,7 @@ namespace BizHawk.Client.EmuHawk if (_autoRestorePaused.HasValue && !_autoRestorePaused.Value) { // this happens when we're holding the left button while unpaused - view scrolls down, new input gets drawn, seek pauses - Mainform.UnpauseEmulator(); + MainForm.UnpauseEmulator(); } _autoRestorePaused = null; @@ -863,7 +862,7 @@ namespace BizHawk.Client.EmuHawk return; } - _unpauseAfterSeeking = (fromRewinding || WasRecording) && !Mainform.EmulatorPaused; + _unpauseAfterSeeking = (fromRewinding || WasRecording) && !MainForm.EmulatorPaused; TastudioPlayMode(); var closestState = CurrentTasMovie.TasStateManager.GetStateClosestToFrame(frame); if (closestState.Value.Length > 0 && (frame < Emulator.Frame || closestState.Key > Emulator.Frame)) @@ -873,24 +872,24 @@ namespace BizHawk.Client.EmuHawk if (fromLua) { - bool wasPaused = Mainform.EmulatorPaused; + bool wasPaused = MainForm.EmulatorPaused; // why not use this? because I'm not letting the form freely run. it all has to be under this loop. // i could use this and then poll StepRunLoop_Core() repeatedly, but.. that's basically what I'm doing // PauseOnFrame = frame; // can't re-enter lua while doing this - Mainform.SuppressLua = true; + MainForm.SuppressLua = true; while (Emulator.Frame != frame) { - Mainform.SeekFrameAdvance(); + MainForm.SeekFrameAdvance(); } - Mainform.SuppressLua = false; + MainForm.SuppressLua = false; if (!wasPaused) { - Mainform.UnpauseEmulator(); + MainForm.UnpauseEmulator(); } // lua botting users will want to re-activate record mode automatically -- it should be like nothing ever happened @@ -906,7 +905,7 @@ namespace BizHawk.Client.EmuHawk if (frame > Emulator.Frame) { // make seek frame keep up with emulation on fast scrolls - if (Mainform.EmulatorPaused || Mainform.IsSeeking || fromRewinding || WasRecording) + if (MainForm.EmulatorPaused || MainForm.IsSeeking || fromRewinding || WasRecording) { StartSeeking(frame); } @@ -931,8 +930,8 @@ namespace BizHawk.Client.EmuHawk } _hackyDontUpdate = true; - GlobalWin.Tools.UpdateBefore(); - GlobalWin.Tools.UpdateAfter(); + Tools.UpdateBefore(); + Tools.UpdateAfter(); _hackyDontUpdate = false; } @@ -949,14 +948,14 @@ namespace BizHawk.Client.EmuHawk private void UpdateOtherTools() // a hack probably, surely there is a better way to do this { _hackyDontUpdate = true; - GlobalWin.Tools.UpdateBefore(); - GlobalWin.Tools.UpdateAfter(); + Tools.UpdateBefore(); + Tools.UpdateAfter(); _hackyDontUpdate = false; } public void TogglePause() { - Mainform.TogglePause(); + MainForm.TogglePause(); } private void SetSplicer() diff --git a/BizHawk.Client.EmuHawk/tools/TI83/TI83KeyPad.cs b/BizHawk.Client.EmuHawk/tools/TI83/TI83KeyPad.cs index 3a15f9d64d..b5f902d874 100644 --- a/BizHawk.Client.EmuHawk/tools/TI83/TI83KeyPad.cs +++ b/BizHawk.Client.EmuHawk/tools/TI83/TI83KeyPad.cs @@ -14,22 +14,22 @@ namespace BizHawk.Client.EmuHawk public TI83KeyPad() { InitializeComponent(); - TopMost = Global.Config.TI83KeypadSettings.TopMost; + TopMost = Config.TI83KeypadSettings.TopMost; Closing += (o, e) => { - Global.Config.TI83KeypadSettings.Wndx = Location.X; - Global.Config.TI83KeypadSettings.Wndy = Location.Y; + Config.TI83KeypadSettings.Wndx = Location.X; + Config.TI83KeypadSettings.Wndy = Location.Y; }; } private void TI83KeyPad_Load(object sender, EventArgs e) { - if (Global.Config.TI83KeypadSettings.UseWindowPosition && IsOnScreen(Global.Config.TI83KeypadSettings.TopLeft)) + if (Config.TI83KeypadSettings.UseWindowPosition && IsOnScreen(Config.TI83KeypadSettings.TopLeft)) { - Location = Global.Config.TI83KeypadSettings.WindowPosition; + Location = Config.TI83KeypadSettings.WindowPosition; } - if (Global.Config.TI83ToolTips) + if (Config.TI83ToolTips) { SetToolTips(); } @@ -62,7 +62,7 @@ namespace BizHawk.Client.EmuHawk private void SetToolTips() { // Set button hotkey mapping into tooltips - var mappings = Global.Config.AllTrollers["TI83 Controller"]; + var mappings = Config.AllTrollers["TI83 Controller"]; KeyPadToolTips.SetToolTip(ZeroButton, mappings["0"]); KeyPadToolTips.SetToolTip(OneButton, mappings["1"]); KeyPadToolTips.SetToolTip(TwoButton, mappings["2"]); @@ -131,17 +131,17 @@ namespace BizHawk.Client.EmuHawk private void OptionsSubMenu_DropDownOpened(object sender, EventArgs e) { - ShowHotkeysMenuItem.Checked = Global.Config.TI83ToolTips; - SaveWindowPositionMenuItem.Checked = Global.Config.TI83KeypadSettings.SaveWindowPosition; - AlwaysOnTopMenuItem.Checked = Global.Config.TI83KeypadSettings.TopMost; - FloatingWindowMenuItem.Checked = Global.Config.TI83KeypadSettings.FloatingWindow; + ShowHotkeysMenuItem.Checked = Config.TI83ToolTips; + SaveWindowPositionMenuItem.Checked = Config.TI83KeypadSettings.SaveWindowPosition; + AlwaysOnTopMenuItem.Checked = Config.TI83KeypadSettings.TopMost; + FloatingWindowMenuItem.Checked = Config.TI83KeypadSettings.FloatingWindow; } private void ShowHotkeysMenuItem_Click(object sender, EventArgs e) { - Global.Config.TI83ToolTips ^= true; + Config.TI83ToolTips ^= true; - if (Global.Config.TI83ToolTips) + if (Config.TI83ToolTips) { SetToolTips(); } @@ -153,19 +153,19 @@ namespace BizHawk.Client.EmuHawk private void SaveWindowPositionMenuItem_Click(object sender, EventArgs e) { - Global.Config.TI83KeypadSettings.SaveWindowPosition ^= true; + Config.TI83KeypadSettings.SaveWindowPosition ^= true; } private void AlwaysOnTopMenuItem_Click(object sender, EventArgs e) { - Global.Config.TI83KeypadSettings.TopMost ^= true; - TopMost = Global.Config.TI83KeypadSettings.TopMost; + Config.TI83KeypadSettings.TopMost ^= true; + TopMost = Config.TI83KeypadSettings.TopMost; } private void FloatingWindowMenuItem_Click(object sender, EventArgs e) { - Global.Config.TI83KeypadSettings.FloatingWindow ^= true; - RefreshFloatingWindowControl(Global.Config.TI83KeypadSettings.FloatingWindow); + Config.TI83KeypadSettings.FloatingWindow ^= true; + RefreshFloatingWindowControl(Config.TI83KeypadSettings.FloatingWindow); } #endregion @@ -424,7 +424,7 @@ namespace BizHawk.Client.EmuHawk protected override void OnShown(EventArgs e) { - RefreshFloatingWindowControl(Global.Config.TI83KeypadSettings.FloatingWindow); + RefreshFloatingWindowControl(Config.TI83KeypadSettings.FloatingWindow); base.OnShown(e); } diff --git a/BizHawk.Client.EmuHawk/tools/ToolBox.cs b/BizHawk.Client.EmuHawk/tools/ToolBox.cs index 3b98fc6d4c..d855737b34 100644 --- a/BizHawk.Client.EmuHawk/tools/ToolBox.cs +++ b/BizHawk.Client.EmuHawk/tools/ToolBox.cs @@ -6,8 +6,6 @@ using System.Reflection; using System.Windows.Forms; using BizHawk.Emulation.Common; -using BizHawk.Client.ApiHawk; -using BizHawk.Common; namespace BizHawk.Client.EmuHawk { @@ -31,8 +29,8 @@ namespace BizHawk.Client.EmuHawk public void NewUpdate(ToolFormUpdateType type) { } - public bool AskSaveChanges() { return true; } - public bool UpdateBefore { get { return false; } } + public bool AskSaveChanges() => true; + public bool UpdateBefore => false; public void UpdateValues() { } public void FastUpdate() diff --git a/BizHawk.Client.EmuHawk/tools/ToolHelpers.cs b/BizHawk.Client.EmuHawk/tools/ToolFormBase.cs similarity index 88% rename from BizHawk.Client.EmuHawk/tools/ToolHelpers.cs rename to BizHawk.Client.EmuHawk/tools/ToolFormBase.cs index 04b9a91465..4bc946f97d 100644 --- a/BizHawk.Client.EmuHawk/tools/ToolHelpers.cs +++ b/BizHawk.Client.EmuHawk/tools/ToolFormBase.cs @@ -1,116 +1,120 @@ -using System.Collections.Generic; -using System.IO; -using System.Windows.Forms; - -using BizHawk.Emulation.Common; -using BizHawk.Emulation.Common.IEmulatorExtensions; - -using BizHawk.Client.Common; -using BizHawk.Client.EmuHawk.WinFormExtensions; -using System.Drawing; - -namespace BizHawk.Client.EmuHawk -{ - public class ToolFormBase : Form - { - public static FileInfo OpenFileDialog(string currentFile, string path, string fileType, string fileExt) - { - if (!Directory.Exists(path)) - { - Directory.CreateDirectory(path); - } - - using var ofd = new OpenFileDialog - { - FileName = !string.IsNullOrWhiteSpace(currentFile) - ? Path.GetFileName(currentFile) - : $"{PathManager.FilesystemSafeName(Global.Game)}.{fileExt}", - InitialDirectory = path, - Filter = string.Format("{0} (*.{1})|*.{1}|All Files|*.*", fileType, fileExt), - RestoreDirectory = true - }; - - var result = ofd.ShowHawkDialog(); - if (result != DialogResult.OK) - { - return null; - } - - return new FileInfo(ofd.FileName); - } - - public static FileInfo SaveFileDialog(string currentFile, string path, string fileType, string fileExt) - { - if (!Directory.Exists(path)) - { - Directory.CreateDirectory(path); - } - - using var sfd = new SaveFileDialog - { - FileName = !string.IsNullOrWhiteSpace(currentFile) - ? Path.GetFileName(currentFile) - : $"{PathManager.FilesystemSafeName(Global.Game)}.{fileExt}", - InitialDirectory = path, - Filter = string.Format("{0} (*.{1})|*.{1}|All Files|*.*", fileType, fileExt), - RestoreDirectory = true, - }; - - var result = sfd.ShowHawkDialog(); - if (result != DialogResult.OK) - { - return null; - } - - return new FileInfo(sfd.FileName); - } - - public static FileInfo GetWatchFileFromUser(string currentFile) - { - return OpenFileDialog(currentFile, PathManager.MakeAbsolutePath(Global.Config.PathEntries.WatchPathFragment, null), "Watch Files", "wch"); - } - - public static FileInfo GetWatchSaveFileFromUser(string currentFile) - { - return SaveFileDialog(currentFile, PathManager.MakeAbsolutePath(Global.Config.PathEntries.WatchPathFragment, null), "Watch Files", "wch"); - } - - public static void UpdateCheatRelatedTools(object sender, CheatCollection.CheatListEventArgs e) - { - if (Global.Emulator.HasMemoryDomains()) - { - GlobalWin.Tools.UpdateValues(); - GlobalWin.Tools.UpdateValues(); - GlobalWin.Tools.UpdateValues(); - - if (GlobalWin.Tools.Has()) - { - GlobalWin.Tools.Cheats.UpdateDialog(); - } - - GlobalWin.MainForm.UpdateCheatStatus(); - } - } - - public static void ViewInHexEditor(MemoryDomain domain, IEnumerable addresses, WatchSize size) - { - GlobalWin.Tools.Load(); - GlobalWin.Tools.HexEditor.SetToAddresses(addresses, domain, size); - } - - protected void GenericDragEnter(object sender, DragEventArgs e) - { - e.Effect = e.Data.GetDataPresent(DataFormats.FileDrop) ? DragDropEffects.Copy : DragDropEffects.None; - } - - protected void RefreshFloatingWindowControl(bool floatingWindow) - { - Owner = floatingWindow ? null : GlobalWin.MainForm; - } - - protected bool IsOnScreen(Point topLeft) - { - return ToolManager.IsOnScreen(topLeft); - } - } -} +using System.Collections.Generic; +using System.IO; +using System.Windows.Forms; + +using BizHawk.Emulation.Common; +using BizHawk.Emulation.Common.IEmulatorExtensions; + +using BizHawk.Client.Common; +using BizHawk.Client.EmuHawk.WinFormExtensions; +using System.Drawing; + +namespace BizHawk.Client.EmuHawk +{ + public class ToolFormBase : Form + { + public ToolManager Tools { get; set; } + public Config Config { get; set; } + public MainForm MainForm { get; set; } + + public static FileInfo OpenFileDialog(string currentFile, string path, string fileType, string fileExt) + { + if (!Directory.Exists(path)) + { + Directory.CreateDirectory(path); + } + + using var ofd = new OpenFileDialog + { + FileName = !string.IsNullOrWhiteSpace(currentFile) + ? Path.GetFileName(currentFile) + : $"{PathManager.FilesystemSafeName(Global.Game)}.{fileExt}", + InitialDirectory = path, + Filter = string.Format("{0} (*.{1})|*.{1}|All Files|*.*", fileType, fileExt), + RestoreDirectory = true + }; + + var result = ofd.ShowHawkDialog(); + if (result != DialogResult.OK) + { + return null; + } + + return new FileInfo(ofd.FileName); + } + + public static FileInfo SaveFileDialog(string currentFile, string path, string fileType, string fileExt) + { + if (!Directory.Exists(path)) + { + Directory.CreateDirectory(path); + } + + using var sfd = new SaveFileDialog + { + FileName = !string.IsNullOrWhiteSpace(currentFile) + ? Path.GetFileName(currentFile) + : $"{PathManager.FilesystemSafeName(Global.Game)}.{fileExt}", + InitialDirectory = path, + Filter = string.Format("{0} (*.{1})|*.{1}|All Files|*.*", fileType, fileExt), + RestoreDirectory = true, + }; + + var result = sfd.ShowHawkDialog(); + if (result != DialogResult.OK) + { + return null; + } + + return new FileInfo(sfd.FileName); + } + + public static FileInfo GetWatchFileFromUser(string currentFile) + { + return OpenFileDialog(currentFile, PathManager.MakeAbsolutePath(Global.Config.PathEntries.WatchPathFragment, null), "Watch Files", "wch"); + } + + public static FileInfo GetWatchSaveFileFromUser(string currentFile) + { + return SaveFileDialog(currentFile, PathManager.MakeAbsolutePath(Global.Config.PathEntries.WatchPathFragment, null), "Watch Files", "wch"); + } + + public static void UpdateCheatRelatedTools(object sender, CheatCollection.CheatListEventArgs e) + { + if (Global.Emulator.HasMemoryDomains()) + { + GlobalWin.Tools.UpdateValues(); + GlobalWin.Tools.UpdateValues(); + GlobalWin.Tools.UpdateValues(); + + if (GlobalWin.Tools.Has()) + { + GlobalWin.Tools.Cheats.UpdateDialog(); + } + + GlobalWin.MainForm.UpdateCheatStatus(); + } + } + + public void ViewInHexEditor(MemoryDomain domain, IEnumerable addresses, WatchSize size) + { + Tools.Load(); + Tools.HexEditor.SetToAddresses(addresses, domain, size); + } + + protected void GenericDragEnter(object sender, DragEventArgs e) + { + e.Effect = e.Data.GetDataPresent(DataFormats.FileDrop) ? DragDropEffects.Copy : DragDropEffects.None; + } + + protected void RefreshFloatingWindowControl(bool floatingWindow) + { + Owner = floatingWindow ? null : GlobalWin.MainForm; + } + + protected bool IsOnScreen(Point topLeft) + { + return Tools.IsOnScreen(topLeft); + } + } +} diff --git a/BizHawk.Client.EmuHawk/tools/ToolManager.cs b/BizHawk.Client.EmuHawk/tools/ToolManager.cs index 62f8ec2e93..7a572eef5c 100644 --- a/BizHawk.Client.EmuHawk/tools/ToolManager.cs +++ b/BizHawk.Client.EmuHawk/tools/ToolManager.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Drawing; +using System.Globalization; using System.IO; using System.Linq; using System.Reflection; @@ -18,7 +19,10 @@ namespace BizHawk.Client.EmuHawk { public class ToolManager { - private readonly Form _owner; + private readonly MainForm _owner; + private readonly Config _config; + private IExternalApiProvider _apiProvider; + private IEmulator _emulator; // TODO: merge ToolHelper code where logical // For instance, add an IToolForm property called UsesCheats, so that a UpdateCheatRelatedTools() method can update all tools of this type @@ -28,10 +32,12 @@ namespace BizHawk.Client.EmuHawk /// /// Initializes a new instance of the class. /// - /// Form that handle the ToolManager - public ToolManager(Form owner) + public ToolManager(MainForm owner, Config config, IEmulator emulator) { _owner = owner; + _config = config; + _emulator = emulator; + _apiProvider = ApiManager.Restart(_emulator.ServiceProvider); } /// @@ -54,6 +60,17 @@ namespace BizHawk.Client.EmuHawk return (IToolForm)method.Invoke(this, new object[] { focus }); } + // If the form inherits ToolFormBase, it will set base properties such as Tools, Config, etc + private void SetBaseProperties(IToolForm form) + { + if (form is ToolFormBase tool) + { + tool.Tools = this; + tool.Config = _config; + tool.MainForm = _owner; + } + } + /// /// Loads the tool dialog T (T must implement ) , if it does not exist it will be created, if it is already open, it will be focused /// @@ -125,19 +142,20 @@ namespace BizHawk.Client.EmuHawk if (isExternal) { - ApiInjector.UpdateApis(GlobalWin.ApiProvider, newTool); + ApiInjector.UpdateApis(_apiProvider, newTool); } - ServiceInjector.UpdateServices(Global.Emulator.ServiceProvider, newTool); + ServiceInjector.UpdateServices(_emulator.ServiceProvider, newTool); + SetBaseProperties(newTool); string toolType = typeof(T).ToString(); // auto settings if (newTool is IToolFormAutoConfig tool) { - if (!Global.Config.CommonToolSettings.TryGetValue(toolType, out var settings)) + if (!_config.CommonToolSettings.TryGetValue(toolType, out var settings)) { settings = new ToolDialogSettings(); - Global.Config.CommonToolSettings[toolType] = settings; + _config.CommonToolSettings[toolType] = settings; } AttachSettingHooks(tool, settings); @@ -146,10 +164,10 @@ namespace BizHawk.Client.EmuHawk // custom settings if (HasCustomConfig(newTool)) { - if (!Global.Config.CustomToolSettings.TryGetValue(toolType, out var settings)) + if (!_config.CustomToolSettings.TryGetValue(toolType, out var settings)) { settings = new Dictionary(); - Global.Config.CustomToolSettings[toolType] = settings; + _config.CustomToolSettings[toolType] = settings; } InstallCustomConfig(newTool, settings); @@ -169,11 +187,11 @@ namespace BizHawk.Client.EmuHawk public void AutoLoad() { - var genericSettings = Global.Config.CommonToolSettings + var genericSettings = _config.CommonToolSettings .Where(kvp => kvp.Value.AutoLoad) .Select(kvp => kvp.Key); - var customSettings = Global.Config.CustomToolSettings + var customSettings = _config.CustomToolSettings .Where(list => list.Value.Any(kvp => kvp.Value is ToolDialogSettings settings && settings.AutoLoad)) .Select(kvp => kvp.Key); @@ -342,8 +360,7 @@ namespace BizHawk.Client.EmuHawk foreach (var prop in props) { - object val; - if (data.TryGetValue(prop.Name, out val)) + if (data.TryGetValue(prop.Name, out var val)) { if (val is string str && prop.PropertyType != typeof(string)) { @@ -354,12 +371,12 @@ namespace BizHawk.Client.EmuHawk // back on regular object serialization when needed. so try to undo a TypeConverter // operation here var converter = TypeDescriptor.GetConverter(prop.PropertyType); - val = converter.ConvertFromString(null, System.Globalization.CultureInfo.InvariantCulture, str); + val = converter.ConvertFromString(null, CultureInfo.InvariantCulture, str); } else if (!(val is bool) && prop.PropertyType.IsPrimitive) { // numeric constants are similarly hosed - val = Convert.ChangeType(val, prop.PropertyType, System.Globalization.CultureInfo.InvariantCulture); + val = Convert.ChangeType(val, prop.PropertyType, CultureInfo.InvariantCulture); } prop.SetValue(tool, val, null); @@ -374,7 +391,7 @@ namespace BizHawk.Client.EmuHawk data.Clear(); foreach (var prop in props) { - data.Add(prop.Name, prop.GetValue(tool, BindingFlags.GetProperty, Type.DefaultBinder, null, System.Globalization.CultureInfo.InvariantCulture)); + data.Add(prop.Name, prop.GetValue(tool, BindingFlags.GetProperty, Type.DefaultBinder, null, CultureInfo.InvariantCulture)); } } @@ -393,7 +410,7 @@ namespace BizHawk.Client.EmuHawk return false; } - public static bool IsOnScreen(Point topLeft) + public bool IsOnScreen(Point topLeft) { return Screen.AllScreens.Any( screen => screen.WorkingArea.Contains(topLeft)); @@ -417,26 +434,20 @@ namespace BizHawk.Client.EmuHawk return Load(false); } - public IEnumerable AvailableTools - { - get - { - return Assembly - .GetAssembly(typeof(IToolForm)) - .GetTypes() - .Where(t => typeof(IToolForm).IsAssignableFrom(t)) - .Where(t => !t.IsInterface) - .Where(IsAvailable); - } - } - + public IEnumerable AvailableTools => Assembly + .GetAssembly(typeof(IToolForm)) + .GetTypes() + .Where(t => typeof(IToolForm).IsAssignableFrom(t)) + .Where(t => !t.IsInterface) + .Where(IsAvailable); + public void UpdateBefore() { var beforeList = _tools.Where(t => t.UpdateBefore); foreach (var tool in beforeList) { if (!tool.IsDisposed - || (tool is RamWatch && Global.Config.DisplayRamWatch)) // RAM Watch hack, on screen display should run even if RAM Watch is closed + || (tool is RamWatch && _config.DisplayRamWatch)) // RAM Watch hack, on screen display should run even if RAM Watch is closed { tool.UpdateValues(); } @@ -457,7 +468,7 @@ namespace BizHawk.Client.EmuHawk foreach (var tool in afterList) { if (!tool.IsDisposed - || (tool is RamWatch && Global.Config.DisplayRamWatch)) // RAM Watch hack, on screen display should run even if RAM Watch is closed + || (tool is RamWatch && _config.DisplayRamWatch)) // RAM Watch hack, on screen display should run even if RAM Watch is closed { tool.UpdateValues(); } @@ -482,15 +493,17 @@ namespace BizHawk.Client.EmuHawk if (tool != null) { if (!tool.IsDisposed || - (tool is RamWatch && Global.Config.DisplayRamWatch)) // RAM Watch hack, on screen display should run even if RAM Watch is closed + (tool is RamWatch && _config.DisplayRamWatch)) // RAM Watch hack, on screen display should run even if RAM Watch is closed { tool.UpdateValues(); } } } - public void Restart() + public void Restart(IEmulator emulator) { + _emulator = emulator; + _apiProvider = ApiManager.Restart(_emulator.ServiceProvider); // If Cheat tool is loaded, restarting will restart the list too anyway if (!Has()) { @@ -501,14 +514,14 @@ namespace BizHawk.Client.EmuHawk foreach (var tool in _tools) { - if (ServiceInjector.IsAvailable(Global.Emulator.ServiceProvider, tool.GetType())) + if (ServiceInjector.IsAvailable(_emulator.ServiceProvider, tool.GetType())) { - ServiceInjector.UpdateServices(Global.Emulator.ServiceProvider, tool); + ServiceInjector.UpdateServices(_emulator.ServiceProvider, tool); if ((tool.IsHandleCreated && !tool.IsDisposed) || tool is RamWatch) // Hack for RAM Watch - in display watches mode it wants to keep running even closed, it will handle disposed logic { if (tool is IExternalToolForm) - ApiInjector.UpdateApis(GlobalWin.ApiProvider, tool); + ApiInjector.UpdateApis(_apiProvider, tool); tool.Restart(); } } @@ -541,7 +554,7 @@ namespace BizHawk.Client.EmuHawk /// public bool AskSave() { - if (Global.Config.SuppressAskSave) // User has elected to not be nagged + if (_config.SuppressAskSave) // User has elected to not be nagged { return true; } @@ -558,18 +571,13 @@ namespace BizHawk.Client.EmuHawk /// Type of tool public bool AskSave() where T : IToolForm { - if (Global.Config.SuppressAskSave) // User has elected to not be nagged + if (_config.SuppressAskSave) // User has elected to not be nagged { return true; } var tool = _tools.FirstOrDefault(t => t is T); - if (tool != null) - { - return tool.AskSaveChanges(); - } - - return false; + return tool != null && tool.AskSaveChanges(); } /// @@ -706,7 +714,7 @@ namespace BizHawk.Client.EmuHawk foreach (var tool in beforeList) { if (!tool.IsDisposed - || (tool is RamWatch && Global.Config.DisplayRamWatch)) // RAM Watch hack, on screen display should run even if RAM Watch is closed + || (tool is RamWatch && _config.DisplayRamWatch)) // RAM Watch hack, on screen display should run even if RAM Watch is closed { tool.FastUpdate(); } @@ -715,7 +723,7 @@ namespace BizHawk.Client.EmuHawk public void FastUpdateAfter(bool fromLua = false) { - if (!fromLua && Global.Config.RunLuaDuringTurbo && Has()) + if (!fromLua && _config.RunLuaDuringTurbo && Has()) { LuaConsole.ResumeScripts(true); } @@ -724,29 +732,28 @@ namespace BizHawk.Client.EmuHawk foreach (var tool in afterList) { if (!tool.IsDisposed - || (tool is RamWatch && Global.Config.DisplayRamWatch)) // RAM Watch hack, on screen display should run even if RAM Watch is closed + || (tool is RamWatch && _config.DisplayRamWatch)) // RAM Watch hack, on screen display should run even if RAM Watch is closed { tool.FastUpdate(); } } - if (Global.Config.RunLuaDuringTurbo && Has()) + if (_config.RunLuaDuringTurbo && Has()) { LuaConsole.LuaImp.EndLuaDrawing(); } } - private static readonly Lazy> lazyAsmTypes = new Lazy>(() => + private static readonly Lazy> LazyAsmTypes = new Lazy>(() => Assembly.GetAssembly(typeof(ToolManager)) // Confining the search to only EmuHawk, for now at least, we may want to broaden for ApiHawk one day .GetTypes() .Select(t => t.AssemblyQualifiedName) - .ToList() - ); + .ToList()); public bool IsAvailable(Type tool) { - if (!ServiceInjector.IsAvailable(Global.Emulator.ServiceProvider, tool) - || !lazyAsmTypes.Value.Contains(tool.AssemblyQualifiedName)) // not a tool + if (!ServiceInjector.IsAvailable(_emulator.ServiceProvider, tool) + || !LazyAsmTypes.Value.Contains(tool.AssemblyQualifiedName)) // not a tool { return false; } @@ -757,8 +764,8 @@ namespace BizHawk.Client.EmuHawk return true; // no ToolAttribute on given type -> assumed all supported } - var displayName = Global.Emulator.DisplayName(); - var systemId = Global.Emulator.SystemId; + var displayName = _emulator.DisplayName(); + var systemId = _emulator.SystemId; return !attr.UnsupportedCores.Contains(displayName) // not unsupported && (!attr.SupportedSystems.Any() || attr.SupportedSystems.Contains(systemId)); // supported (no supported list -> assumed all supported) } @@ -798,19 +805,7 @@ namespace BizHawk.Client.EmuHawk public LuaConsole LuaConsole => GetTool(); - public TAStudio TAStudio - { - get - { - // prevent nasty silent corruption - if (!IsLoaded()) - { - System.Diagnostics.Debug.Fail("TAStudio does not exist!"); - } - - return GetTool(); - } - } + public TAStudio TAStudio => GetTool(); #endregion @@ -827,9 +822,9 @@ namespace BizHawk.Client.EmuHawk if (IsAvailable()) // Just because we attempted to load it, doesn't mean it was, the current core may not have the correct dependencies { - if (Global.Config.RecentWatches.AutoLoad && !Global.Config.RecentWatches.Empty) + if (_config.RecentWatches.AutoLoad && !_config.RecentWatches.Empty) { - RamWatch.LoadFileFromRecent(Global.Config.RecentWatches.MostRecent); + RamWatch.LoadFileFromRecent(_config.RecentWatches.MostRecent); } if (!loadDialog) @@ -849,10 +844,10 @@ namespace BizHawk.Client.EmuHawk #endregion - public static string GenerateDefaultCheatFilename() + public string GenerateDefaultCheatFilename() { - var pathEntry = Global.Config.PathEntries[Global.Game.System, "Cheats"] - ?? Global.Config.PathEntries[Global.Game.System, "Base"]; + var pathEntry = _config.PathEntries[Global.Game.System, "Cheats"] + ?? _config.PathEntries[Global.Game.System, "Base"]; var path = PathManager.MakeAbsolutePath(pathEntry.Path, Global.Game.System); diff --git a/BizHawk.Client.EmuHawk/tools/VirtualPads/VirtualpadsTool.cs b/BizHawk.Client.EmuHawk/tools/VirtualPads/VirtualpadsTool.cs index 4e303320bb..ba1ca76605 100644 --- a/BizHawk.Client.EmuHawk/tools/VirtualPads/VirtualpadsTool.cs +++ b/BizHawk.Client.EmuHawk/tools/VirtualPads/VirtualpadsTool.cs @@ -29,11 +29,7 @@ namespace BizHawk.Client.EmuHawk public bool Readonly { - get - { - return _readOnly; - } - + get => _readOnly; set { _readOnly = value; @@ -149,8 +145,8 @@ namespace BizHawk.Client.EmuHawk #region IToolForm Implementation - public bool AskSaveChanges() { return true; } - public bool UpdateBefore { get { return false; } } + public bool AskSaveChanges() => true; + public bool UpdateBefore => false; public void Restart() { @@ -173,7 +169,7 @@ namespace BizHawk.Client.EmuHawk Pads.ForEach(p => p.SetPrevious(null)); // Not the cleanest way to clear this every frame - if (Global.MovieSession.Movie.IsPlaying && !Global.MovieSession.Movie.IsFinished) + if (Global.MovieSession.Movie.Mode == MovieMode.Play) { Readonly = true; if (Global.MovieSession.CurrentInput != null) @@ -183,7 +179,7 @@ namespace BizHawk.Client.EmuHawk } else { - if (Global.MovieSession.Movie.IsRecording) + if (Global.MovieSession.Movie.IsRecording()) { Pads.ForEach(p => p.SetPrevious(Global.MovieSession.PreviousFrame)); } diff --git a/BizHawk.Client.EmuHawk/tools/Watch/RamSearch.cs b/BizHawk.Client.EmuHawk/tools/Watch/RamSearch.cs index c33812e9be..3ee6ae775a 100644 --- a/BizHawk.Client.EmuHawk/tools/Watch/RamSearch.cs +++ b/BizHawk.Client.EmuHawk/tools/Watch/RamSearch.cs @@ -882,8 +882,8 @@ namespace BizHawk.Client.EmuHawk var watches = SelectedWatches.ToList(); if (watches.Any()) { - GlobalWin.Tools.LoadRamWatch(true); - watches.ForEach(GlobalWin.Tools.RamWatch.AddWatch); + Tools.LoadRamWatch(true); + watches.ForEach(Tools.RamWatch.AddWatch); if (Settings.AlwaysExcludeRamWatch) { RemoveRamWatchesFromList(); @@ -909,9 +909,9 @@ namespace BizHawk.Client.EmuHawk private void RemoveRamWatchesFromList() { - if (GlobalWin.Tools.Has()) + if (Tools.Has()) { - _searches.RemoveSmallWatchRange(GlobalWin.Tools.RamWatch.Watches); + _searches.RemoveSmallWatchRange(Tools.RamWatch.Watches); UpdateList(); } } diff --git a/BizHawk.Client.EmuHawk/tools/Watch/RamWatch.cs b/BizHawk.Client.EmuHawk/tools/Watch/RamWatch.cs index 9894d6ed62..701ee5395a 100644 --- a/BizHawk.Client.EmuHawk/tools/Watch/RamWatch.cs +++ b/BizHawk.Client.EmuHawk/tools/Watch/RamWatch.cs @@ -131,7 +131,7 @@ namespace BizHawk.Client.EmuHawk else { _watches.Save(); - Global.Config.RecentWatches.Add(_watches.CurrentFileName); + Config.RecentWatches.Add(_watches.CurrentFileName); } } else if (result == DialogResult.No) @@ -161,11 +161,11 @@ namespace BizHawk.Client.EmuHawk var loadResult = _watches.Load(path, append: false); if (!loadResult) { - Global.Config.RecentWatches.HandleLoadError(path); + Config.RecentWatches.HandleLoadError(path); } else { - Global.Config.RecentWatches.Add(path); + Config.RecentWatches.Add(path); WatchListView.RowCount = _watches.Count; UpdateWatchCount(); UpdateValues(); @@ -190,7 +190,7 @@ namespace BizHawk.Client.EmuHawk _watches.Load(file.FullName, append); WatchListView.RowCount = _watches.Count; UpdateWatchCount(); - Global.Config.RecentWatches.Add(_watches.CurrentFileName); + Config.RecentWatches.Add(_watches.CurrentFileName); UpdateStatusBar(); UpdateValues(); PokeAddressToolBarItem.Enabled = @@ -203,7 +203,7 @@ namespace BizHawk.Client.EmuHawk public void Restart() { - if ((!IsHandleCreated || IsDisposed) && !Global.Config.DisplayRamWatch) + if ((!IsHandleCreated || IsDisposed) && !Config.DisplayRamWatch) { return; } @@ -211,7 +211,7 @@ namespace BizHawk.Client.EmuHawk if (_watches != null && !string.IsNullOrWhiteSpace(_watches.CurrentFileName) && _watches.All(w => w.Domain == null || MemoryDomains.Select(m => m.Name).Contains(w.Domain.Name)) - && (Global.Config.RecentWatches.AutoLoad || (IsHandleCreated || !IsDisposed))) + && (Config.RecentWatches.AutoLoad || (IsHandleCreated || !IsDisposed))) { _watches.RefreshDomains(MemoryDomains); _watches.Reload(); @@ -229,6 +229,27 @@ namespace BizHawk.Client.EmuHawk { } + private void DisplayOnScreenWatches() + { + if (Config.DisplayRamWatch) + { + for (var i = 0; i < _watches.Count; i++) + { + var frozen = !_watches[i].IsSeparator && Global.CheatList.IsActive(_watches[i].Domain, _watches[i].Address); + GlobalWin.OSD.AddGuiText( + _watches[i].ToDisplayString(), + new MessagePosition + { + X = Config.RamWatches.X, + Y = Config.RamWatches.Y + (i * 14), + Anchor = Config.RamWatches.Anchor + }, + Color.Black, + frozen ? Color.Cyan : Color.White); + } + } + } + public void UpdateValues() { if (_paused) @@ -236,7 +257,7 @@ namespace BizHawk.Client.EmuHawk return; } - if ((!IsHandleCreated || IsDisposed) && !Global.Config.DisplayRamWatch) + if ((!IsHandleCreated || IsDisposed) && !Config.DisplayRamWatch) { return; } @@ -245,21 +266,7 @@ namespace BizHawk.Client.EmuHawk if (_watches.Any()) { _watches.UpdateValues(); - - if (Global.Config.DisplayRamWatch) - { - for (var i = 0; i < _watches.Count; i++) - { - var frozen = !_watches[i].IsSeparator && Global.CheatList.IsActive(_watches[i].Domain, _watches[i].Address); - GlobalWin.OSD.AddGuiText( - _watches[i].ToDisplayString(), - Global.Config.DispRamWatchx, - Global.Config.DispRamWatchy + (i * 14), - Color.Black, - frozen ? Color.Cyan : Color.White, - 0); - } - } + DisplayOnScreenWatches(); if (!IsHandleCreated || IsDisposed) { @@ -277,7 +284,7 @@ namespace BizHawk.Client.EmuHawk return; } - if ((!IsHandleCreated || IsDisposed) && !Global.Config.DisplayRamWatch) + if ((!IsHandleCreated || IsDisposed) && !Config.DisplayRamWatch) { return; } @@ -285,21 +292,7 @@ namespace BizHawk.Client.EmuHawk if (_watches.Any()) { _watches.UpdateValues(); - - if (Global.Config.DisplayRamWatch) - { - for (var i = 0; i < _watches.Count; i++) - { - var frozen = !_watches[i].IsSeparator && Global.CheatList.IsActive(_watches[i].Domain, _watches[i].Address); - GlobalWin.OSD.AddGuiText( - _watches[i].ToDisplayString(), - Global.Config.DispRamWatchx, - Global.Config.DispRamWatchy + (i * 14), - Color.Black, - frozen ? Color.Cyan : Color.White, - 0); - } - } + DisplayOnScreenWatches(); } } @@ -529,7 +522,7 @@ namespace BizHawk.Client.EmuHawk if (result) { UpdateStatusBar(saved: true); - Global.Config.RecentWatches.Add(_watches.CurrentFileName); + Config.RecentWatches.Add(_watches.CurrentFileName); } } @@ -677,7 +670,7 @@ namespace BizHawk.Client.EmuHawk { if (_watches.Save()) { - Global.Config.RecentWatches.Add(_watches.CurrentFileName); + Config.RecentWatches.Add(_watches.CurrentFileName); UpdateStatusBar(saved: true); } } @@ -696,7 +689,7 @@ namespace BizHawk.Client.EmuHawk { RecentSubMenu.DropDownItems.Clear(); RecentSubMenu.DropDownItems.AddRange( - Global.Config.RecentWatches.RecentMenu(LoadFileFromRecent, true)); + Config.RecentWatches.RecentMenu(LoadFileFromRecent, true)); } private void ExitMenuItem_Click(object sender, EventArgs e) @@ -971,7 +964,7 @@ namespace BizHawk.Client.EmuHawk private void OptionsSubMenu_DropDownOpened(object sender, EventArgs e) { - WatchesOnScreenMenuItem.Checked = Global.Config.DisplayRamWatch; + WatchesOnScreenMenuItem.Checked = Config.DisplayRamWatch; SaveWindowPositionMenuItem.Checked = Settings.SaveWindowPosition; AlwaysOnTopMenuItem.Checked = Settings.TopMost; FloatingWindowMenuItem.Checked = Settings.FloatingWindow; @@ -979,31 +972,31 @@ namespace BizHawk.Client.EmuHawk private void DefinePreviousValueSubMenu_DropDownOpened(object sender, EventArgs e) { - PreviousFrameMenuItem.Checked = Global.Config.RamWatchDefinePrevious == PreviousType.LastFrame; - LastChangeMenuItem.Checked = Global.Config.RamWatchDefinePrevious == PreviousType.LastChange; - OriginalMenuItem.Checked = Global.Config.RamWatchDefinePrevious == PreviousType.Original; + PreviousFrameMenuItem.Checked = Config.RamWatchDefinePrevious == PreviousType.LastFrame; + LastChangeMenuItem.Checked = Config.RamWatchDefinePrevious == PreviousType.LastChange; + OriginalMenuItem.Checked = Config.RamWatchDefinePrevious == PreviousType.Original; } private void PreviousFrameMenuItem_Click(object sender, EventArgs e) { - Global.Config.RamWatchDefinePrevious = PreviousType.LastFrame; + Config.RamWatchDefinePrevious = PreviousType.LastFrame; } private void LastChangeMenuItem_Click(object sender, EventArgs e) { - Global.Config.RamWatchDefinePrevious = PreviousType.LastChange; + Config.RamWatchDefinePrevious = PreviousType.LastChange; } private void OriginalMenuItem_Click(object sender, EventArgs e) { - Global.Config.RamWatchDefinePrevious = PreviousType.Original; + Config.RamWatchDefinePrevious = PreviousType.Original; } private void WatchesOnScreenMenuItem_Click(object sender, EventArgs e) { - Global.Config.DisplayRamWatch ^= true; + Config.DisplayRamWatch ^= true; - if (!Global.Config.DisplayRamWatch) + if (!Config.DisplayRamWatch) { GlobalWin.OSD.ClearGuiText(); } @@ -1041,7 +1034,7 @@ namespace BizHawk.Client.EmuHawk RamWatchMenu.Items.Add(WatchListView.ToColumnsMenu(ColumnToggleCallback)); - Global.Config.DisplayRamWatch = false; + Config.DisplayRamWatch = false; RefreshFloatingWindowControl(Settings.FloatingWindow); @@ -1083,7 +1076,7 @@ namespace BizHawk.Client.EmuHawk if (Path.GetExtension(filePaths[0]) == ".wch") { _watches.Load(filePaths[0], append: false); - Global.Config.RecentWatches.Add(_watches.CurrentFileName); + Config.RecentWatches.Add(_watches.CurrentFileName); WatchListView.RowCount = _watches.Count; UpdateValues(); } @@ -1152,7 +1145,7 @@ namespace BizHawk.Client.EmuHawk var selected = SelectedWatches.ToList(); if (selected.Any()) { - GlobalWin.Tools.Load(); + Tools.Load(); if (selected.Select(x => x.Domain).Distinct().Count() > 1) { @@ -1171,7 +1164,7 @@ namespace BizHawk.Client.EmuHawk if (selected.Any()) { - var debugger = GlobalWin.Tools.Load(); + var debugger = Tools.Load(); foreach (var watch in selected) { @@ -1186,7 +1179,7 @@ namespace BizHawk.Client.EmuHawk if (selected.Any()) { - var debugger = GlobalWin.Tools.Load(); + var debugger = Tools.Load(); foreach (var watch in selected) { diff --git a/BizHawk.Emulation.Common/Base Implementations/NullVideo.cs b/BizHawk.Emulation.Common/Base Implementations/NullVideo.cs index c18054c9ef..309fa086cd 100644 --- a/BizHawk.Emulation.Common/Base Implementations/NullVideo.cs +++ b/BizHawk.Emulation.Common/Base Implementations/NullVideo.cs @@ -7,10 +7,7 @@ /// public class NullVideo : IVideoProvider { - public int[] GetVideoBuffer() - { - return new int[BufferWidth * BufferHeight]; - } + public int[] GetVideoBuffer() => new int[BufferWidth * BufferHeight]; public static NullVideo Instance { get; } = new NullVideo(); diff --git a/BizHawk.Emulation.Cores/CPUs/Intel8048/I8048.cs b/BizHawk.Emulation.Cores/CPUs/Intel8048/I8048.cs index 518f44d4a1..9cb2c194b1 100644 --- a/BizHawk.Emulation.Cores/CPUs/Intel8048/I8048.cs +++ b/BizHawk.Emulation.Cores/CPUs/Intel8048/I8048.cs @@ -184,7 +184,16 @@ namespace BizHawk.Emulation.Common.Components.I8048 reg_l_ad = cur_instr[instr_pntr++]; reg_h_ad = cur_instr[instr_pntr++]; // direct value - Regs[reg_d_ad] = (ushort)(MB | (reg_h_ad << 8) | Regs[reg_l_ad]); + // bit 11 held low during interrupt + if (INT_MSTR) + { + Regs[reg_d_ad] = (ushort)(MB | (reg_h_ad << 8) | Regs[reg_l_ad]); + } + else + { + Regs[reg_d_ad] = (ushort)((reg_h_ad << 8) | Regs[reg_l_ad]); + } + break; case CLRA: Regs[A] = 0; diff --git a/BizHawk.Emulation.Cores/CPUs/Intel8048/OP_Tables.cs b/BizHawk.Emulation.Cores/CPUs/Intel8048/OP_Tables.cs index acc8dd13d7..5b4b708c36 100644 --- a/BizHawk.Emulation.Cores/CPUs/Intel8048/OP_Tables.cs +++ b/BizHawk.Emulation.Cores/CPUs/Intel8048/OP_Tables.cs @@ -129,14 +129,14 @@ namespace BizHawk.Emulation.Common.Components.I8048 public void BUS_PORT_OUT() { PopulateCURINSTR(IDLE, - IDLE, - IDLE, - IDLE, - IDLE, - IDLE, - IDLE, - IDLE, - WR_P, 0, A); + IDLE, + IDLE, + IDLE, + IDLE, + IDLE, + IDLE, + IDLE, + WR_P, 0, A); IRQS = 9; Console.WriteLine("OUT"); diff --git a/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.IEmulator.cs b/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.IEmulator.cs index 9f78a61fb3..86cdff16d7 100644 --- a/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.IEmulator.cs +++ b/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.IEmulator.cs @@ -18,7 +18,7 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk public bool FrameAdvance(IController controller, bool render, bool rendersound) { - // Console.WriteLine("-----------------------FRAME-----------------------"); + //Console.WriteLine("-----------------------FRAME-----------------------"); if (_tracer.Enabled) { @@ -62,7 +62,6 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk { ppu.tick(); ppu.tick(); - ppu.DMA_tick(); serialport.serial_transfer_tick(); ppu.Audio_tick(); cpu.ExecuteOne(); @@ -80,10 +79,10 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk { ppu.tick(); ppu.tick(); - ppu.DMA_tick(); serialport.serial_transfer_tick(); ppu.Audio_tick(); cpu.ExecuteOne(); + } public void GetControllerState(IController controller) diff --git a/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.ISettable.cs b/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.ISettable.cs index 8daf54077a..5448492140 100644 --- a/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.ISettable.cs +++ b/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.ISettable.cs @@ -43,6 +43,11 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk [DefaultValue(true)] public bool Show_Chars { get; set; } + [DisplayName("Display Quad Characters")] + [Description("When true, displays quad character.")] + [DefaultValue(true)] + public bool Show_Quads { get; set; } + [DisplayName("Display Sprites")] [Description("When true, displays sprites.")] [DefaultValue(true)] diff --git a/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/PPU.cs b/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/PPU.cs index df6444dd16..fcc0184bf1 100644 --- a/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/PPU.cs +++ b/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/PPU.cs @@ -1,4 +1,6 @@ using System; +using System.Diagnostics.Eventing.Reader; +using System.Runtime.InteropServices; using BizHawk.Common; using BizHawk.Common.NumberExtensions; using BizHawk.Emulation.Common; @@ -18,8 +20,11 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk public byte[] Grid_V = new byte[10]; public byte VDC_ctrl, VDC_status, VDC_collision, VDC_col_ret, VDC_color; - public byte Frame_Col, Pixel_Stat; + public byte Pixel_Stat; + public int bg_brightness; + public int grid_fill; + public byte grid_fill_col; public int LY; public int cycle; public bool VBL; @@ -126,6 +131,9 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk else if (addr == 0xA3) { VDC_color = value; + //Console.WriteLine("VDC_color: " + value + " " + Core.cpu.TotalExecutedCycles); + bg_brightness = VDC_color.Bit(6) ? 8 : 0; + //VDC_color |= 3; } else if (addr == 0xA4) { @@ -175,6 +183,21 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk if (LY < 240) { // background + Core._vidbuffer[LY * 186 + (cycle - 43)] = (int)Color_Palette_BG[((VDC_color >> 3) & 0x7) + bg_brightness]; + + // grid + if (grid_fill > 0) + { + Core._vidbuffer[LY * 186 + (cycle - 43)] = (int)Color_Palette_BG[(VDC_color & 0x7) + bg_brightness]; + Pixel_Stat |= grid_fill_col; + grid_fill--; + } + + if (VDC_ctrl.Bit(6)) + { + + } + if ((((cycle - 43) % 16) == 8) && ((LY - 24) >= 0)) { int k = (int)Math.Floor((cycle - 43) / 16.0); @@ -183,8 +206,11 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk { if (Grid_V[k].Bit(j)) { - Core._vidbuffer[LY * 186 + (cycle - 43)] = (int)Color_Palette_BG[VDC_color & 0x7]; + Core._vidbuffer[LY * 186 + (cycle - 43)] = (int)Color_Palette_BG[(VDC_color & 0x7) + bg_brightness]; Pixel_Stat |= 0x10; + if (VDC_ctrl.Bit(7)) { grid_fill = 15; } + else { grid_fill = 1; } + grid_fill_col = 0x10; } } } @@ -200,50 +226,24 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk { if (Grid_H[k + 9].Bit(0)) { - Core._vidbuffer[LY * 186 + (cycle - 43)] = (int)Color_Palette_BG[VDC_color & 0x7]; + Core._vidbuffer[LY * 186 + (cycle - 43)] = (int)Color_Palette_BG[(VDC_color & 0x7) + bg_brightness]; Pixel_Stat |= 0x20; + + if (((cycle - 43 - 8) % 16) == 15) { grid_fill = 2; grid_fill_col = 0x20; } } } else { if (Grid_H[k].Bit(j)) { - Core._vidbuffer[LY * 186 + (cycle - 43)] = (int)Color_Palette_BG[VDC_color & 0x7]; + Core._vidbuffer[LY * 186 + (cycle - 43)] = (int)Color_Palette_BG[(VDC_color & 0x7) + bg_brightness]; Pixel_Stat |= 0x20; - } - } - - } - } - - // sprites - for (int i = 3; i >= 0; i--) - { - int double_size = Sprites[i * 4 + 2].Bit(2) ? 4 : 2; - - if ((LY >= Sprites[i * 4]) && (LY < (Sprites[i * 4] + 8 * double_size))) - { - if (((cycle - 43) >= Sprites[i * 4 + 1]) && ((cycle - 43) < (Sprites[i * 4 + 1] + 8 * (double_size / 2)))) - { - // character is in drawing region, pick a pixel - int offset_y = (LY - Sprites[i * 4]) >> (double_size / 2); - int offset_x = ((cycle - 43) - Sprites[i * 4 + 1]) >> (double_size / 2 - 1); - - int pixel_pick = (Sprite_Shapes[i * 8 + offset_y] >> offset_x) & 1; - - if (pixel_pick == 1) - { - if (Core._settings.Show_Sprites) - { - Core._vidbuffer[LY * 186 + (cycle - 43)] = (int) Color_Palette_SPR[(Sprites[i * 4 + 2] >> 3) & 0x7]; - } - - Pixel_Stat |= (byte)(1 << i); + if (((cycle - 43 - 8) % 16) == 15) { grid_fill = 2; grid_fill_col = 0x20; } } } } } - + // single characters for (int i = 0; i < 12; i++) { @@ -319,7 +319,7 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk if (char_pick < 0) { char_pick &= 0xFF; - char_pick |= (Quad_Chars[i * 16 + 4 * quad_num + 3] & 1) << 7; + char_pick |= (Quad_Chars[i * 16 + 4 * quad_num + 3] & 1) << 8; } else { @@ -332,7 +332,11 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk if (pixel_pick == 1) { - Core._vidbuffer[LY * 186 + (cycle - 43)] = (int) Color_Palette_SPR[(Quad_Chars[i * 16 + 4 * quad_num + 3] >> 1) & 0x7]; + if (Core._settings.Show_Quads) + { + Core._vidbuffer[LY * 186 + (cycle - 43)] = (int) Color_Palette_SPR[(Quad_Chars[i * 16 + 4 * quad_num + 3] >> 1) & 0x7]; + } + Pixel_Stat |= 0x80; } } @@ -340,6 +344,34 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk } } + // sprites + for (int i = 3; i >= 0; i--) + { + int double_size = Sprites[i * 4 + 2].Bit(2) ? 4 : 2; + + if ((LY >= Sprites[i * 4]) && (LY < (Sprites[i * 4] + 8 * double_size))) + { + if (((cycle - 43) >= Sprites[i * 4 + 1]) && ((cycle - 43) < (Sprites[i * 4 + 1] + 8 * (double_size / 2)))) + { + // character is in drawing region, pick a pixel + int offset_y = (LY - Sprites[i * 4]) >> (double_size / 2); + int offset_x = ((cycle - 43) - Sprites[i * 4 + 1]) >> (double_size / 2 - 1); + + int pixel_pick = (Sprite_Shapes[i * 8 + offset_y] >> offset_x) & 1; + + if (pixel_pick == 1) + { + if (Core._settings.Show_Sprites) + { + Core._vidbuffer[LY * 186 + (cycle - 43)] = (int)Color_Palette_SPR[(Sprites[i * 4 + 2] >> 3) & 0x7]; + } + + Pixel_Stat |= (byte)(1 << i); + } + } + } + } + // calculate collision int col_bit = 0; for (int i = 7; i >= 0; i--) @@ -365,12 +397,10 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk { cycle = 0; HBL = true; - - - // send T1 pulses - Core.cpu.T1 = true; LY++; + + if (LY == 240) { VBL = true; @@ -388,8 +418,11 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk VBL = false; VDC_col_ret = 0; Core.in_vblank = false; - if (!VDC_ctrl.Bit(0)) { Core.cpu.IRQPending = false; } - Frame_Col = 0; + } + if (LY < 240) + { + // send T1 pulses + Core.cpu.T1 = true; } } } @@ -400,28 +433,11 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk } - public void render(int render_cycle) - { - - } - public void process_sprite() { } - // normal DMA moves twice as fast in double speed mode on GBC - // So give it it's own function so we can seperate it from PPU tick - public void DMA_tick() - { - - } - - public void OAM_scan(int OAM_cycle) - { - - } - public void Reset() { AudioReset(); @@ -474,7 +490,7 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk 0x66, 0x66, 0x66, 0x3C, 0x18, 0x18, 0x18, 00, // Y 0x2C 0xC6, 0xE6, 0xF6, 0xFE, 0xDE, 0xCE, 0xC6, 00, // N 0x2D 0x03, 0x06, 0x0C, 0x18, 0x30, 0x60, 0xC0, 00, // / 0x2E - 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 00, // (box) 0x2F + 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 00, // (box) 0x2F 0xCE, 0xDB, 0xDB, 0xDB, 0xDB, 0xDB, 0xCE, 00, // 10 0x30 0x00, 0x00, 0x3C, 0x7E, 0x7E, 0x7E, 0x3C, 00, // (ball) 0x31 0x38, 0x38, 0x30, 0x3C, 0x30, 0x30, 0x38, 00, // (person R) 0x32 @@ -496,11 +512,11 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk public static readonly uint[] Color_Palette_SPR = { 0xFF676767, // grey - 0xFF790000, // red - 0xFF006D07, // green 0xFFC75151, // light red - 0xFF1A37BE, // blue - 0xFF94309F, // violet + 0xFF56C469, // light green + 0xFFC6B869, // light yellow + 0xFF5C80F6, // light blue + 0xFFDC84D4, // light violet 0xFFCECECE, // light grey 0xFFFFFFFF, // white }; @@ -510,19 +526,19 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk 0xFF000000, // black 0xFF1A37BE, // blue 0xFF006D07, // green - 0xFF56C469, // light green + 0xFF2AAABE, // blue-green 0xFF790000, // red 0xFF94309F, // violet - 0xFFC75151, // light red + 0xFF77670B, // yellow 0xFF676767, // grey + 0xFF000000, // black + 0xFF5C80F6, // light blue + 0xFF56C469, // light green + 0xFF77E6EB, // light blue-green + 0xFFC75151, // light red + 0xFFDC84D4, // light violet 0xFFC6B869, // light yellow 0xFFCECECE, // light grey - 0xFF2AAABE, // blue-green - 0xFF77E6EB, // light blue-green - 0xFF5C80F6, // light blue - 0xFFDC84D4, // light violet - 0xFF77670B, // yellow - 0xFFFFFFFF, // white }; @@ -540,9 +556,11 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk ser.Sync(nameof(VDC_collision), ref VDC_collision); ser.Sync(nameof(VDC_col_ret), ref VDC_col_ret); ser.Sync(nameof(VDC_color), ref VDC_color); - ser.Sync(nameof(Frame_Col), ref Frame_Col); ser.Sync(nameof(Pixel_Stat), ref Pixel_Stat); + ser.Sync(nameof(bg_brightness), ref bg_brightness); + ser.Sync(nameof(grid_fill), ref grid_fill); + ser.Sync(nameof(grid_fill_col), ref grid_fill_col); ser.Sync(nameof(LY), ref LY); ser.Sync(nameof(cycle), ref cycle); ser.Sync(nameof(VBL), ref VBL); diff --git a/BizHawk.sln.DotSettings b/BizHawk.sln.DotSettings index 4db542a120..861c487949 100644 --- a/BizHawk.sln.DotSettings +++ b/BizHawk.sln.DotSettings @@ -190,8 +190,10 @@ True True True + True True True + True True True True @@ -216,6 +218,7 @@ True True True + True True True True @@ -242,6 +245,8 @@ True True True + True + True True True True @@ -261,6 +266,7 @@ True True True + True True True True @@ -311,6 +317,7 @@ True True True + True True True True @@ -318,6 +325,7 @@ True True True + True True True True @@ -361,6 +369,7 @@ True True True + True True True True