diff --git a/.editorconfig b/.editorconfig index de87d7b5b48..65a5481b0ce 100644 --- a/.editorconfig +++ b/.editorconfig @@ -12,9 +12,11 @@ csharp_indent_switch_labels = true csharp_indent_case_contents = true csharp_indent_labels = one_less_than_current +# Globalization rules +dotnet_code_quality.CA1305.excluded_symbol_names = T:System.Byte|T:System.SByte|T:System.Int16|T:System.UInt16|T:System.Int32|T:System.UInt32|T:System.Int64|T:System.UInt64|T:System.String|T:System.Text.StringBuilder|T:System.Convert + # Style rules # Can't be in .globalconfig because dotnet format doesn't respect that https://github.com/dotnet/format/issues/1643 - # Remove unnecessary cast dotnet_diagnostic.IDE0004.severity = warning # Remove unnecessary import @@ -49,6 +51,8 @@ dotnet_diagnostic.IDE0032.severity = suggestion dotnet_diagnostic.IDE0034.severity = suggestion # Use pattern matching to avoid is check followed by a cast (without variable) dotnet_diagnostic.IDE0038.severity = warning +# Use a local function instead of an anonymous function +dotnet_diagnostic.IDE0039.severity = none # Use is null check dotnet_diagnostic.IDE0041.severity = warning # Deconstruct variable declaration @@ -109,7 +113,7 @@ dotnet_diagnostic.IDE0260.severity = suggestion # Use nameof dotnet_diagnostic.IDE0280.severity = error -csharp_style_var_when_type_is_apparent = true +csharp_style_var_when_type_is_apparent = false csharp_style_var_elsewhere = true csharp_style_expression_bodied_methods = when_on_single_line diff --git a/Common.ruleset b/Common.ruleset index c0d05e8bfa2..b7517afcf77 100644 --- a/Common.ruleset +++ b/Common.ruleset @@ -14,7 +14,7 @@ - + diff --git a/contributing.md b/contributing.md index ff94122ffea..72b1533b2c1 100644 --- a/contributing.md +++ b/contributing.md @@ -76,7 +76,9 @@ It's probably a good idea to get the .NET SDK, even if you're not working on a . For EmuHawk and libraries in the main solution, which do not target .NET 6, we have [this page](https://github.com/TASEmulators/BizHawk/wiki/Available-C%23-and-.NET-features) documenting which features are actually available to use. +### Code Analysis +Visual Studio can detect and show issues and possible optimizations in the IDE before build time. In the Analyze menu pick Run Code Analysis -> On Solution. From there you can open the Error list in the bottom left and highlight issues of different severity level Errors/Warnings/Messages and adjust the scope as small as the open documents and as wide as the entire solution. Developers should target to have no code introduced flagging the Error and Warning levels. It's also good to minimize warnings at the Message severity level either by adopting the suggested fixes or by ignoring irrelevant Messages with `#pragma` directives. Many warnings can be auto-fixed by the `dotnet format` command or by the quick actions menu found on the left next to a line number when hovering a line. ## blip_buf > Audio resampling library. diff --git a/src/BizHawk.BizInvoke/BizExvoker.cs b/src/BizHawk.BizInvoke/BizExvoker.cs index 9afc683e5e7..3920284e1c1 100644 --- a/src/BizHawk.BizInvoke/BizExvoker.cs +++ b/src/BizHawk.BizInvoke/BizExvoker.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Reflection; @@ -23,7 +23,7 @@ public static class BizExvoker static BizExvoker() { - var aname = new AssemblyName("BizExvokeProxyAssembly"); + AssemblyName aname = new("BizExvokeProxyAssembly"); ImplAssemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(aname, AssemblyBuilderAccess.Run); ImplModuleBuilder = ImplAssemblyBuilder.DefineDynamicModule("BizExvokerModule"); } @@ -65,10 +65,10 @@ public DelegateStorage(Type type) var typeBuilder = ImplModuleBuilder.DefineType($"Bizhawk.BizExvokeHolder{type.Name}", TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed); - foreach (var a in methods) + foreach (var (Info, Attr) in methods) { - var delegateType = BizInvokeUtilities.CreateDelegateType(a.Info, a.Attr!.CallingConvention, typeBuilder, out _).CreateType()!; - DelegateTypes.Add(new StoredDelegateInfo(a.Info, delegateType, a.Attr.EntryPoint ?? a.Info.Name)); + var delegateType = BizInvokeUtilities.CreateDelegateType(Info, Attr!.CallingConvention, typeBuilder, out _).CreateType()!; + DelegateTypes.Add(new StoredDelegateInfo(Info, delegateType, Attr.EntryPoint ?? Info.Name)); } StorageType = typeBuilder.CreateType()!; OriginalType = type; @@ -77,15 +77,15 @@ public DelegateStorage(Type type) private class ExvokerImpl : IImportResolver { - private readonly Dictionary EntryPoints = new Dictionary(); + private readonly Dictionary EntryPoints = new(); - private readonly List Delegates = new List(); + private readonly List Delegates = new(); public ExvokerImpl(object o, DelegateStorage d, ICallingConventionAdapter a) { foreach (var sdt in d.DelegateTypes) { - var del = Delegate.CreateDelegate(sdt.DelegateType, o, sdt.Method); + Delegate del = Delegate.CreateDelegate(sdt.DelegateType, o, sdt.Method); Delegates.Add(del); // prevent garbage collection of the delegate, which would invalidate the pointer EntryPoints.Add(sdt.EntryPointName, a.GetFunctionPointerForDelegate(del)); } @@ -96,7 +96,7 @@ public ExvokerImpl(object o, DelegateStorage d, ICallingConventionAdapter a) public IntPtr GetProcAddrOrThrow(string entryPoint) => EntryPoints.TryGetValue(entryPoint, out var ret) ? ret : throw new InvalidOperationException($"could not find {entryPoint} in exports"); } - private static readonly Dictionary Impls = new Dictionary(); + private static readonly Dictionary Impls = new(); public static IImportResolver GetExvoker(object o, ICallingConventionAdapter a) diff --git a/src/BizHawk.BizInvoke/BizInvokeUtilities.cs b/src/BizHawk.BizInvoke/BizInvokeUtilities.cs index 0b9893bba19..dc2ae4fbeb5 100644 --- a/src/BizHawk.BizInvoke/BizInvokeUtilities.cs +++ b/src/BizHawk.BizInvoke/BizInvokeUtilities.cs @@ -47,7 +47,7 @@ public static TypeBuilder CreateDelegateType(MethodInfo method, CallingConventio for (int i = 0; i < paramInfos.Length; i++) { var p = delegateInvoke.DefineParameter(i + 1, ParameterAttributes.None, paramInfos[i].Name); - foreach (var a in paramInfos[i].GetCustomAttributes(false)) + foreach (object? a in paramInfos[i].GetCustomAttributes(false)) { p.SetCustomAttribute(GetAttributeBuilder(a)); } @@ -55,16 +55,16 @@ public static TypeBuilder CreateDelegateType(MethodInfo method, CallingConventio { var p = delegateInvoke.DefineParameter(0, ParameterAttributes.Retval, method.ReturnParameter!.Name); - foreach (var a in method.ReturnParameter.GetCustomAttributes(false)) + foreach (object? a in method.ReturnParameter.GetCustomAttributes(false)) { p.SetCustomAttribute(GetAttributeBuilder(a)); } } - delegateInvoke.SetImplementationFlags(MethodImplAttributes.Runtime | MethodImplAttributes.Managed); - - // add the [UnmanagedFunctionPointer] to the delegate so interop will know how to call it - var attr = new CustomAttributeBuilder( + delegateInvoke.SetImplementationFlags(MethodImplAttributes.Runtime | MethodImplAttributes.Managed); + + // add the [UnmanagedFunctionPointer] to the delegate so interop will know how to call it + CustomAttributeBuilder attr = new( typeof(UnmanagedFunctionPointerAttribute).GetConstructor(new[] { typeof(CallingConvention) })!, new object[] { nativeCall }); delegateType.SetCustomAttribute(attr); diff --git a/src/BizHawk.BizInvoke/BizInvoker.cs b/src/BizHawk.BizInvoke/BizInvoker.cs index 8e1351fa76c..37ba23a4e8c 100644 --- a/src/BizHawk.BizInvoke/BizInvoker.cs +++ b/src/BizHawk.BizInvoke/BizInvoker.cs @@ -52,7 +52,7 @@ public InvokerImpl( public object Create(IImportResolver dll, IMonitor? monitor, ICallingConventionAdapter adapter) { - var ret = Activator.CreateInstance(_implType)!; + object ret = Activator.CreateInstance(_implType)!; _connectCallingConventionAdapter(ret, adapter); foreach (var f in _hooks) { @@ -93,7 +93,7 @@ public object Create(IImportResolver dll, IMonitor? monitor, ICallingConventionA static BizInvoker() { - var aname = new AssemblyName("BizInvokeProxyAssembly"); + AssemblyName aname = new("BizInvokeProxyAssembly"); ImplAssemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(aname, AssemblyBuilderAccess.Run); ImplModuleBuilder = ImplAssemblyBuilder.DefineDynamicModule("BizInvokerModule"); ClassFieldOffset = BizInvokerUtilities.ComputeClassFirstFieldOffset(); @@ -109,7 +109,7 @@ static BizInvoker() public static T GetInvoker(IImportResolver dll, ICallingConventionAdapter adapter) where T : class { - var nonTrivialAdapter = adapter.GetType() != CallingConventionAdapters.Native.GetType(); + bool nonTrivialAdapter = adapter.GetType() != CallingConventionAdapters.Native.GetType(); InvokerImpl impl; lock (Impls) impl = Impls.GetValueOrPut( typeof(T), @@ -126,7 +126,7 @@ public static T GetInvoker(IImportResolver dll, ICallingConventionAdapter ada public static T GetInvoker(IImportResolver dll, IMonitor monitor, ICallingConventionAdapter adapter) where T : class { - var nonTrivialAdapter = adapter.GetType() != CallingConventionAdapters.Native.GetType(); + bool nonTrivialAdapter = adapter.GetType() != CallingConventionAdapters.Native.GetType(); InvokerImpl impl; lock (Impls) impl = Impls.GetValueOrPut( typeof(T), @@ -152,13 +152,8 @@ private static InvokerImpl CreateProxy(Type baseType, bool monitor, bool nonTriv throw new InvalidOperationException("Type must be public"); } - var baseConstructor = baseType.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null); - if (baseConstructor == null) - { - throw new InvalidOperationException("Base type must have a zero arg constructor"); - } - - var baseMethods = baseType.GetMethods(BindingFlags.Instance | BindingFlags.Public) + var baseConstructor = baseType.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null) ?? throw new InvalidOperationException("Base type must have a zero arg constructor"); + List<(MethodInfo Info, BizImportAttribute Attr)> baseMethods = baseType.GetMethods(BindingFlags.Instance | BindingFlags.Public) .Select(static m => (Info: m, Attr: m.GetCustomAttributes(true).OfType().FirstOrDefault())) .Where(a => a.Attr != null) .ToList(); @@ -179,7 +174,7 @@ private static InvokerImpl CreateProxy(Type baseType, bool monitor, bool nonTriv } // hooks that will be run on the created proxy object - var postCreateHooks = new List>(); + List> postCreateHooks = new(); var type = ImplModuleBuilder.DefineType($"Bizhawk.BizInvokeProxy{baseType.Name}", TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed, baseType); @@ -187,13 +182,13 @@ private static InvokerImpl CreateProxy(Type baseType, bool monitor, bool nonTriv var adapterField = type.DefineField("CallingConvention", typeof(ICallingConventionAdapter), FieldAttributes.Public); - foreach (var mi in baseMethods) + foreach (var (Info, Attr) in baseMethods) { - var entryPointName = mi.Attr!.EntryPoint ?? mi.Info.Name; + string entryPointName = Attr!.EntryPoint ?? Info.Name; - var hook = mi.Attr.Compatibility - ? ImplementMethodDelegate(type, mi.Info, mi.Attr.CallingConvention, entryPointName, monitorField, nonTrivialAdapter) - : ImplementMethodCalli(type, mi.Info, mi.Attr.CallingConvention, entryPointName, monitorField, adapterField); + var hook = Attr.Compatibility + ? ImplementMethodDelegate(type, Info, Attr.CallingConvention, entryPointName, monitorField, nonTrivialAdapter) + : ImplementMethodCalli(type, Info, Attr.CallingConvention, entryPointName, monitorField, adapterField); postCreateHooks.Add(hook); } @@ -336,7 +331,7 @@ private static Action Implem { var paramInfos = baseMethod.GetParameters(); var paramTypes = paramInfos.Select(p => p.ParameterType).ToArray(); - var paramLoadInfos = new List(); + List paramLoadInfos = new(); var returnType = baseMethod.ReturnType; if (returnType != typeof(void) && !returnType.IsPrimitive && !returnType.IsPointer && !returnType.IsEnum) { @@ -381,7 +376,7 @@ private static Action Implem bool WantsWinAPIBool() { - var attrs = baseMethod.ReturnTypeCustomAttributes.GetCustomAttributes(typeof(MarshalAsAttribute), false); + object[] attrs = baseMethod.ReturnTypeCustomAttributes.GetCustomAttributes(typeof(MarshalAsAttribute), false); return attrs.Length > 0 && ((MarshalAsAttribute)attrs[0]).Value is UnmanagedType.Bool; } diff --git a/src/BizHawk.BizInvoke/BizInvokerUtilities.cs b/src/BizHawk.BizInvoke/BizInvokerUtilities.cs index 502fab09914..d3436d14626 100644 --- a/src/BizHawk.BizInvoke/BizInvokerUtilities.cs +++ b/src/BizHawk.BizInvoke/BizInvokerUtilities.cs @@ -50,10 +50,7 @@ private class CF /// Computes the byte offset of the first field of any class relative to a class pointer. /// /// - public static int ComputeClassFirstFieldOffset() - { - return ComputeFieldOffset(typeof(CF).GetField("FirstField")); - } + public static int ComputeClassFirstFieldOffset() => ComputeFieldOffset(typeof(CF).GetField("FirstField")); /// /// Compute the byte offset of the first byte of string data (UTF16) relative to a pointer to the string. @@ -61,7 +58,7 @@ public static int ComputeClassFirstFieldOffset() /// public static int ComputeStringOffset() { - var s = new string(Array.Empty()); + string s = new(Array.Empty()); int ret; fixed(char* fx = s) { @@ -77,7 +74,7 @@ public static int ComputeStringOffset() /// public static int ComputeValueArrayElementOffset() { - var arr = new int[4]; + int[] arr = new int[4]; int ret; fixed (int* p = arr) { @@ -94,8 +91,8 @@ public static int ComputeValueArrayElementOffset() /// public static int ComputeObjectArrayElementOffset() { - var obj = new object[4]; - var method = new DynamicMethod("ComputeObjectArrayElementOffsetHelper", typeof(int), new[] { typeof(object[]) }, typeof(string).Module, true); + object[] obj = new object[4]; + DynamicMethod method = new("ComputeObjectArrayElementOffsetHelper", typeof(int), new[] { typeof(object[]) }, typeof(string).Module, true); var il = method.GetILGenerator(); var local = il.DeclareLocal(typeof(object[]), true); il.Emit(OpCodes.Ldarg_0); @@ -109,7 +106,7 @@ public static int ComputeObjectArrayElementOffset() il.Emit(OpCodes.Sub); il.Emit(OpCodes.Conv_I4); il.Emit(OpCodes.Ret); - var del = (Func)method.CreateDelegate(typeof(Func)); + Func del = (Func)method.CreateDelegate(typeof(Func)); return del(obj); } @@ -124,8 +121,8 @@ public static int ComputeFieldOffset(FieldInfo fi) throw new NotImplementedException("Only supported for class fields right now"); } - var obj = FormatterServices.GetUninitializedObject(fi.DeclaringType); - var method = new DynamicMethod("ComputeFieldOffsetHelper", typeof(int), new[] { typeof(object) }, typeof(string).Module, true); + object obj = FormatterServices.GetUninitializedObject(fi.DeclaringType); + DynamicMethod method = new("ComputeFieldOffsetHelper", typeof(int), new[] { typeof(object) }, typeof(string).Module, true); var il = method.GetILGenerator(); var local = il.DeclareLocal(fi.DeclaringType, true); il.Emit(OpCodes.Ldarg_0); @@ -138,7 +135,7 @@ public static int ComputeFieldOffset(FieldInfo fi) il.Emit(OpCodes.Sub); il.Emit(OpCodes.Conv_I4); il.Emit(OpCodes.Ret); - var del = (Func)method.CreateDelegate(typeof(Func)); + Func del = (Func)method.CreateDelegate(typeof(Func)); return del(obj); } } diff --git a/src/BizHawk.BizInvoke/CallingConventionAdapter.cs b/src/BizHawk.BizInvoke/CallingConventionAdapter.cs index 24b7b5e5219..2f72f622ea5 100644 --- a/src/BizHawk.BizInvoke/CallingConventionAdapter.cs +++ b/src/BizHawk.BizInvoke/CallingConventionAdapter.cs @@ -95,25 +95,13 @@ public static class CallingConventionAdapters { private class NativeConvention : ICallingConventionAdapter { - public IntPtr GetArrivalFunctionPointer(IntPtr p, ParameterInfo pp, object lifetime) - { - return p; - } + public IntPtr GetArrivalFunctionPointer(IntPtr p, ParameterInfo pp, object lifetime) => p; - public Delegate GetDelegateForFunctionPointer(IntPtr p, Type delegateType) - { - return Marshal.GetDelegateForFunctionPointer(p, delegateType); - } + public Delegate GetDelegateForFunctionPointer(IntPtr p, Type delegateType) => Marshal.GetDelegateForFunctionPointer(p, delegateType); - public IntPtr GetDepartureFunctionPointer(IntPtr p, ParameterInfo pp, object lifetime) - { - return p; - } + public IntPtr GetDepartureFunctionPointer(IntPtr p, ParameterInfo pp, object lifetime) => p; - public IntPtr GetFunctionPointerForDelegate(Delegate d) - { - return Marshal.GetFunctionPointerForDelegate(d); - } + public IntPtr GetFunctionPointerForDelegate(Delegate d) => Marshal.GetFunctionPointerForDelegate(d); } /// @@ -124,17 +112,11 @@ public IntPtr GetFunctionPointerForDelegate(Delegate d) /// /// waterbox calling convention, including thunk handling for stack marshalling /// - public static ICallingConventionAdapter MakeWaterbox(IEnumerable slots, ICallbackAdjuster waterboxHost) - { - return new WaterboxAdapter(slots, waterboxHost); - } + public static ICallingConventionAdapter MakeWaterbox(IEnumerable slots, ICallbackAdjuster waterboxHost) => new WaterboxAdapter(slots, waterboxHost); /// /// waterbox calling convention, including thunk handling for stack marshalling. Can only do callins, not callouts /// - public static ICallingConventionAdapter MakeWaterboxDepartureOnly(ICallbackAdjuster waterboxHost) - { - return new WaterboxAdapter(null, waterboxHost); - } + public static ICallingConventionAdapter MakeWaterboxDepartureOnly(ICallbackAdjuster waterboxHost) => new WaterboxAdapter(null, waterboxHost); /// /// Get a waterbox calling convention adapater, except no wrapping is done for stack marshalling and callback support. @@ -142,24 +124,15 @@ public static ICallingConventionAdapter MakeWaterboxDepartureOnly(ICallbackAdjus /// DO NOT USE THIS. /// /// - public static ICallingConventionAdapter GetWaterboxUnsafeUnwrapped() - { - return WaterboxAdapter.WaterboxWrapper; - } + public static ICallingConventionAdapter GetWaterboxUnsafeUnwrapped() => WaterboxAdapter.WaterboxWrapper; private class WaterboxAdapter : ICallingConventionAdapter { private class ReferenceEqualityComparer : IEqualityComparer { - public bool Equals(Delegate x, Delegate y) - { - return x == y; - } + public bool Equals(Delegate x, Delegate y) => x == y; - public int GetHashCode(Delegate obj) - { - return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj); - } + public int GetHashCode(Delegate obj) => System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj); } internal static readonly ICallingConventionAdapter WaterboxWrapper; @@ -190,7 +163,7 @@ public IntPtr GetArrivalFunctionPointer(IntPtr p, ParameterInfo pp, object lifet throw new InvalidOperationException("This calling convention adapter was created for departure only! Pass known delegate slots when constructing to enable arrival"); } if (lifetime is not Delegate d) throw new ArgumentException(message: "For this calling convention adapter, lifetimes must be delegate so guest slot can be inferred", paramName: nameof(lifetime)); - if (!_slots.TryGetValue(d, out var slot)) + if (!_slots.TryGetValue(d, out int slot)) { throw new InvalidOperationException("All callback delegates must be registered at load"); } @@ -215,7 +188,7 @@ public IntPtr GetFunctionPointerForDelegate(Delegate d) { throw new InvalidOperationException("This calling convention adapter was created for departure only! Pass known delegate slots when constructing to enable arrival"); } - if (!_slots.TryGetValue(d, out var slot)) + if (!_slots.TryGetValue(d, out int slot)) { throw new InvalidOperationException("All callback delegates must be registered at load"); } @@ -288,8 +261,8 @@ private static int VerifyDelegateSignature(ParameterInfo pp) VerifyParameter(pp.ReturnType); foreach (var ppp in pp.ParameterTypes) VerifyParameter(ppp); - var ret = pp.ParameterTypes.Count(t => t != typeof(float) && t != typeof(double)); - var fargs = pp.ParameterTypes.Count - ret; + int ret = pp.ParameterTypes.Count(t => t != typeof(float) && t != typeof(double)); + int fargs = pp.ParameterTypes.Count - ret; if (ret > 6 || fargs > 4) throw new InvalidOperationException("Too many parameters to marshal!"); // a function may only use exclusively floating point args or integer/pointer args @@ -304,7 +277,7 @@ private void WriteThunk(IntPtr thunkFunctionAddress, IntPtr calleeAddress, int i { _memory.Protect(_memory.Start, _memory.Size, MemoryBlock.Protection.RW); var ss = _memory.GetStream(_memory.Start + (ulong)index * BlockSize, BlockSize, true); - var bw = new BinaryWriter(ss); + BinaryWriter bw = new(ss); // The thunks all take the expected parameters in the expected places, but additionally take the parameter // of the function to call as a hidden extra parameter in rax. @@ -325,10 +298,7 @@ private void WriteThunk(IntPtr thunkFunctionAddress, IntPtr calleeAddress, int i _memory.Protect(_memory.Start, _memory.Size, MemoryBlock.Protection.RX); } - private IntPtr GetThunkAddress(int index) - { - return Z.US(_memory.Start + (ulong)index * BlockSize); - } + private IntPtr GetThunkAddress(int index) => Z.US(_memory.Start + (ulong)index * BlockSize); private void SetLifetime(int index, object lifetime) { @@ -342,7 +312,7 @@ public IntPtr GetFunctionPointerForDelegate(Delegate d) // on the same delegate and not leak extra memory, so the result has to be cached lock (_sync) { - var index = FindUsedIndex(d); + int index = FindUsedIndex(d); if (index != -1) { return GetThunkAddress(index); @@ -359,8 +329,8 @@ public IntPtr GetArrivalFunctionPointer(IntPtr p, ParameterInfo pp, object lifet { lock (_sync) { - var index = FindFreeIndex(); - var count = VerifyDelegateSignature(pp); + int index = FindFreeIndex(); + int count = VerifyDelegateSignature(pp); WriteThunk(ThunkDll.GetProcAddrOrThrow($"arrive{count}"), p, index); SetLifetime(index, lifetime); return GetThunkAddress(index); @@ -371,8 +341,8 @@ public Delegate GetDelegateForFunctionPointer(IntPtr p, Type delegateType) { lock (_sync) { - var index = FindFreeIndex(); - var count = VerifyDelegateSignature(new(delegateType)); + int index = FindFreeIndex(); + int count = VerifyDelegateSignature(new(delegateType)); WriteThunk(ThunkDll.GetProcAddrOrThrow($"depart{count}"), p, index); var ret = Marshal.GetDelegateForFunctionPointer(GetThunkAddress(index), delegateType); SetLifetime(index, ret); @@ -384,8 +354,8 @@ public IntPtr GetDepartureFunctionPointer(IntPtr p, ParameterInfo pp, object lif { lock (_sync) { - var index = FindFreeIndex(); - var count = VerifyDelegateSignature(pp); + int index = FindFreeIndex(); + int count = VerifyDelegateSignature(pp); WriteThunk(ThunkDll.GetProcAddrOrThrow($"depart{count}"), p, index); SetLifetime(index, lifetime); return GetThunkAddress(index); diff --git a/src/BizHawk.BizInvoke/FPCtrl.cs b/src/BizHawk.BizInvoke/FPCtrl.cs index dff5efbaed3..7cd22407691 100644 --- a/src/BizHawk.BizInvoke/FPCtrl.cs +++ b/src/BizHawk.BizInvoke/FPCtrl.cs @@ -37,7 +37,7 @@ static FPCtrl() _memory = new(4096); _memory.Protect(_memory.Start, _memory.Size, MemoryBlock.Protection.RW); var ss = _memory.GetStream(_memory.Start, 64, true); - var bw = new BinaryWriter(ss); + BinaryWriter bw = new(ss); // FYI: The push/pop is only needed on Windows, but doesn't do any harm on Linux diff --git a/src/BizHawk.BizInvoke/MemoryBlock.cs b/src/BizHawk.BizInvoke/MemoryBlock.cs index 56189105987..3d267d82f69 100644 --- a/src/BizHawk.BizInvoke/MemoryBlock.cs +++ b/src/BizHawk.BizInvoke/MemoryBlock.cs @@ -65,9 +65,9 @@ public void Protect(ulong start, ulong length, Protection prot) // Note: asking for prot.none on memory that was not previously committed, commits it - var computedStart = WaterboxUtils.AlignDown(start); - var computedEnd = WaterboxUtils.AlignUp(start + length); - var computedLength = computedEnd - computedStart; + ulong computedStart = WaterboxUtils.AlignDown(start); + ulong computedEnd = WaterboxUtils.AlignUp(start + length); + ulong computedLength = computedEnd - computedStart; _pal.Protect(computedStart, computedLength, prot); } diff --git a/src/BizHawk.BizInvoke/MemoryBlockLinuxPal.cs b/src/BizHawk.BizInvoke/MemoryBlockLinuxPal.cs index 1a4ac74c8b3..2f86cd17c54 100644 --- a/src/BizHawk.BizInvoke/MemoryBlockLinuxPal.cs +++ b/src/BizHawk.BizInvoke/MemoryBlockLinuxPal.cs @@ -20,7 +20,7 @@ internal sealed class MemoryBlockLinuxPal : IMemoryBlockPal /// public MemoryBlockLinuxPal(ulong size) { - var ptr = (ulong)mmap(IntPtr.Zero, Z.UU(size), MemoryProtection.None, 0x22 /* MAP_PRIVATE | MAP_ANON */, -1, IntPtr.Zero); + ulong ptr = (ulong)mmap(IntPtr.Zero, Z.UU(size), MemoryProtection.None, 0x22 /* MAP_PRIVATE | MAP_ANON */, -1, IntPtr.Zero); if (ptr == ulong.MaxValue) throw new InvalidOperationException($"{nameof(mmap)}() failed with error {Marshal.GetLastWin32Error()}"); _size = size; @@ -43,24 +43,19 @@ public void Dispose() private static MemoryProtection ToMemoryProtection(Protection prot) { - switch (prot) + return prot switch { - case Protection.None: - return MemoryProtection.None; - case Protection.R: - return MemoryProtection.Read; - case Protection.RW: - return MemoryProtection.Read | MemoryProtection.Write; - case Protection.RX: - return MemoryProtection.Read | MemoryProtection.Execute; - default: - throw new ArgumentOutOfRangeException(nameof(prot)); - } + Protection.None => MemoryProtection.None, + Protection.R => MemoryProtection.Read, + Protection.RW => MemoryProtection.Read | MemoryProtection.Write, + Protection.RX => MemoryProtection.Read | MemoryProtection.Execute, + _ => throw new ArgumentOutOfRangeException(nameof(prot)), + }; } public void Protect(ulong start, ulong size, Protection prot) { - var errorCode = mprotect( + int errorCode = mprotect( Z.US(start), Z.UU(size), ToMemoryProtection(prot) diff --git a/src/BizHawk.BizInvoke/MemoryBlockWindowsPal.cs b/src/BizHawk.BizInvoke/MemoryBlockWindowsPal.cs index bc6774b85f3..ce1b3677e30 100644 --- a/src/BizHawk.BizInvoke/MemoryBlockWindowsPal.cs +++ b/src/BizHawk.BizInvoke/MemoryBlockWindowsPal.cs @@ -12,7 +12,7 @@ internal sealed unsafe class MemoryBlockWindowsPal : IMemoryBlockPal public MemoryBlockWindowsPal(ulong size) { - var ptr = (ulong)Kernel32.VirtualAlloc( + ulong ptr = (ulong)Kernel32.VirtualAlloc( UIntPtr.Zero, Z.UU(size), Kernel32.AllocationType.MEM_RESERVE | Kernel32.AllocationType.MEM_COMMIT, Kernel32.MemoryProtection.NOACCESS); if (ptr == 0) throw new InvalidOperationException($"{nameof(Kernel32.VirtualAlloc)}() returned NULL"); @@ -28,15 +28,14 @@ public void Protect(ulong start, ulong size, Protection prot) private static Kernel32.MemoryProtection GetKernelMemoryProtectionValue(Protection prot) { - Kernel32.MemoryProtection p; - switch (prot) + var p = prot switch { - case Protection.None: p = Kernel32.MemoryProtection.NOACCESS; break; - case Protection.R: p = Kernel32.MemoryProtection.READONLY; break; - case Protection.RW: p = Kernel32.MemoryProtection.READWRITE; break; - case Protection.RX: p = Kernel32.MemoryProtection.EXECUTE_READ; break; - default: throw new ArgumentOutOfRangeException(nameof(prot)); - } + Protection.None => Kernel32.MemoryProtection.NOACCESS, + Protection.R => Kernel32.MemoryProtection.READONLY, + Protection.RW => Kernel32.MemoryProtection.READWRITE, + Protection.RX => Kernel32.MemoryProtection.EXECUTE_READ, + _ => throw new ArgumentOutOfRangeException(nameof(prot)), + }; return p; } diff --git a/src/BizHawk.BizInvoke/MemoryViewStream.cs b/src/BizHawk.BizInvoke/MemoryViewStream.cs index cc5559d58eb..2183fa9457e 100644 --- a/src/BizHawk.BizInvoke/MemoryViewStream.cs +++ b/src/BizHawk.BizInvoke/MemoryViewStream.cs @@ -57,22 +57,19 @@ public int Read(Span buffer) if (!_readable) throw new IOException(); EnsureNotDisposed(); - var count = (int)Math.Min(buffer.Length, _length - _pos); + int count = (int)Math.Min(buffer.Length, _length - _pos); new ReadOnlySpan(CurrentPointer(), count).CopyTo(buffer); _pos += count; return count; } - public override int Read(byte[] buffer, int offset, int count) - { - return Read(new Span(buffer, offset, count)); - } + public override int Read(byte[] buffer, int offset, int count) => Read(new Span(buffer, offset, count)); public override int ReadByte() { if (_pos < _length) { - var ret = *CurrentPointer(); + byte ret = *CurrentPointer(); _pos++; return ret; } @@ -84,28 +81,17 @@ public override int ReadByte() public override long Seek(long offset, SeekOrigin origin) { - long newpos; - switch (origin) + long newpos = origin switch { - default: - case SeekOrigin.Begin: - newpos = offset; - break; - case SeekOrigin.Current: - newpos = _pos + offset; - break; - case SeekOrigin.End: - newpos = _length + offset; - break; - } + SeekOrigin.Current => _pos + offset, + SeekOrigin.End => _length + offset, + _ => offset, + }; Position = newpos; return newpos; } - public override void SetLength(long value) - { - throw new IOException(); - } + public override void SetLength(long value) => throw new IOException(); public void Write(ReadOnlySpan buffer) { @@ -118,10 +104,7 @@ public void Write(ReadOnlySpan buffer) _pos += buffer.Length; } - public override void Write(byte[] buffer, int offset, int count) - { - Write(new ReadOnlySpan(buffer, offset, count)); - } + public override void Write(byte[] buffer, int offset, int count) => Write(new ReadOnlySpan(buffer, offset, count)); public override void WriteByte(byte value) { diff --git a/src/BizHawk.BizInvoke/WaterboxUtils.cs b/src/BizHawk.BizInvoke/WaterboxUtils.cs index a0c2c11f835..9a1d8bc5afa 100644 --- a/src/BizHawk.BizInvoke/WaterboxUtils.cs +++ b/src/BizHawk.BizInvoke/WaterboxUtils.cs @@ -10,7 +10,7 @@ public static class WaterboxUtils /// public static void CopySome(Stream src, Stream dst, long len) { - var buff = new byte[65536]; + byte[] buff = new byte[65536]; while (len > 0) { int r = src.Read(buff, 0, (int)Math.Min(len, 65536)); @@ -31,10 +31,7 @@ public static unsafe void ZeroMemory(IntPtr mem, long length) } } - public static long Timestamp() - { - return DateTime.UtcNow.Ticks; - } + public static long Timestamp() => DateTime.UtcNow.Ticks; /// /// system page size @@ -62,34 +59,22 @@ static WaterboxUtils() /// /// true if addr is aligned /// - public static bool Aligned(ulong addr) - { - return (addr & PageMask) == 0; - } + public static bool Aligned(ulong addr) => (addr & PageMask) == 0; /// /// align address down to previous page boundary /// - public static ulong AlignDown(ulong addr) - { - return addr & ~PageMask; - } + public static ulong AlignDown(ulong addr) => addr & ~PageMask; /// /// align address up to next page boundary /// - public static ulong AlignUp(ulong addr) - { - return ((addr - 1) | PageMask) + 1; - } + public static ulong AlignUp(ulong addr) => ((addr - 1) | PageMask) + 1; /// /// return the minimum number of pages needed to hold size /// - public static int PagesNeeded(ulong size) - { - return (int)((size + PageMask) >> PageShift); - } + public static int PagesNeeded(ulong size) => (int)((size + PageMask) >> PageShift); } // C# is annoying: arithmetic operators for native ints are not exposed. diff --git a/src/BizHawk.Bizware.Audio/DirectSoundSoundOutput.cs b/src/BizHawk.Bizware.Audio/DirectSoundSoundOutput.cs index 7a42a29f5de..b555c577d96 100644 --- a/src/BizHawk.Bizware.Audio/DirectSoundSoundOutput.cs +++ b/src/BizHawk.Bizware.Audio/DirectSoundSoundOutput.cs @@ -44,10 +44,7 @@ public void Dispose() _disposed = true; } - public static IEnumerable GetDeviceNames() - { - return DirectSound.GetDevices().Select(d => d.Description); - } + public static IEnumerable GetDeviceNames() => DirectSound.GetDevices().Select(d => d.Description); private int BufferSizeSamples { get; set; } @@ -65,7 +62,7 @@ private void StartPlaying() _filledBufferSizeBytes = 0; _lastWriteTime = 0; _lastWriteCursor = 0; - var attempts = _retryCounter; + int attempts = _retryCounter; while (!IsPlaying && attempts > 0) { attempts--; @@ -73,7 +70,7 @@ private void StartPlaying() { if (_deviceBuffer == null) { - var format = WaveFormat.CreateCustomFormat( + WaveFormat format = WaveFormat.CreateCustomFormat( tag: WaveFormatEncoding.Pcm, sampleRate: _sound.SampleRate, channels: _sound.ChannelCount, @@ -81,7 +78,7 @@ private void StartPlaying() blockAlign: _sound.BlockAlign, bitsPerSample: _sound.BytesPerSample * 8); - var desc = new SoundBufferDescription + SoundBufferDescription desc = new() { Format = format, Flags = @@ -143,7 +140,7 @@ public void StartSound() // severe glitches. At least on my Windows 8 machines, the distance between the // play and write cursors can be up to 30 milliseconds, so that would be the // absolute minimum we could use here. - var minBufferFullnessMs = Math.Min(35 + (_sound.ConfigBufferSizeMs - 60) / 2, 65); + int minBufferFullnessMs = Math.Min(35 + (_sound.ConfigBufferSizeMs - 60) / 2, 65); MaxSamplesDeficit = BufferSizeSamples - _sound.MillisecondsToSamples(minBufferFullnessMs); StartPlaying(); @@ -169,20 +166,20 @@ public void StopSound() public int CalculateSamplesNeeded() { - var samplesNeeded = 0; + int samplesNeeded = 0; if (IsPlaying) { try { - var currentWriteTime = Stopwatch.GetTimestamp(); - _deviceBuffer.GetCurrentPosition(out var playCursor, out var writeCursor); - var isInitializing = _actualWriteOffsetBytes == -1; - var detectedUnderrun = false; + long currentWriteTime = Stopwatch.GetTimestamp(); + _deviceBuffer.GetCurrentPosition(out int playCursor, out int writeCursor); + bool isInitializing = _actualWriteOffsetBytes == -1; + bool detectedUnderrun = false; if (!isInitializing) { - var elapsedSeconds = (currentWriteTime - _lastWriteTime) / (double)Stopwatch.Frequency; - var bufferSizeSeconds = (double) BufferSizeSamples / _sound.SampleRate; - var cursorDelta = CircularDistance(_lastWriteCursor, writeCursor, BufferSizeBytes); + double elapsedSeconds = (currentWriteTime - _lastWriteTime) / (double)Stopwatch.Frequency; + double bufferSizeSeconds = (double) BufferSizeSamples / _sound.SampleRate; + int cursorDelta = CircularDistance(_lastWriteCursor, writeCursor, BufferSizeBytes); cursorDelta += BufferSizeBytes * (int) Math.Round((elapsedSeconds - (cursorDelta / (double) (_sound.SampleRate * _sound.BlockAlign))) / bufferSizeSeconds); _filledBufferSizeBytes -= cursorDelta; detectedUnderrun = _filledBufferSizeBytes < 0; @@ -208,10 +205,7 @@ public int CalculateSamplesNeeded() return samplesNeeded; } - private static int CircularDistance(int start, int end, int size) - { - return (end - start + size) % size; - } + private static int CircularDistance(int start, int end, int size) => (end - start + size) % size; public void WriteSamples(short[] samples, int sampleOffset, int sampleCount) { diff --git a/src/BizHawk.Bizware.Audio/OpenALSoundOutput.cs b/src/BizHawk.Bizware.Audio/OpenALSoundOutput.cs index fc9eff3af3b..cf08b65f09a 100644 --- a/src/BizHawk.Bizware.Audio/OpenALSoundOutput.cs +++ b/src/BizHawk.Bizware.Audio/OpenALSoundOutput.cs @@ -58,10 +58,7 @@ public static IEnumerable GetDeviceNames() public int MaxSamplesDeficit { get; private set; } - public void ApplyVolumeSettings(double volume) - { - _al.SetSourceProperty(_sourceID, SourceFloat.Gain, (float)volume); - } + public void ApplyVolumeSettings(double volume) => _al.SetSourceProperty(_sourceID, SourceFloat.Gain, (float)volume); public void StartSound() { @@ -87,18 +84,18 @@ public void StopSound() public int CalculateSamplesNeeded() { - var currentSamplesPlayed = GetSource(GetSourceInteger.SampleOffset); + int currentSamplesPlayed = GetSource(GetSourceInteger.SampleOffset); var sourceState = GetSourceState(); - var isInitializing = sourceState == SourceState.Initial; - var detectedUnderrun = sourceState == SourceState.Stopped; + bool isInitializing = sourceState == SourceState.Initial; + bool detectedUnderrun = sourceState == SourceState.Stopped; if (detectedUnderrun) { // SampleOffset should reset to 0 when stopped; update the queued sample count to match UnqueueProcessedBuffers(); currentSamplesPlayed = 0; } - var samplesAwaitingPlayback = _currentSamplesQueued - currentSamplesPlayed; - var samplesNeeded = Math.Max(BufferSizeSamples - samplesAwaitingPlayback, 0); + int samplesAwaitingPlayback = _currentSamplesQueued - currentSamplesPlayed; + int samplesNeeded = Math.Max(BufferSizeSamples - samplesAwaitingPlayback, 0); if (isInitializing || detectedUnderrun) { _sound.HandleInitializationOrUnderrun(detectedUnderrun, ref samplesNeeded); @@ -110,7 +107,7 @@ public unsafe void WriteSamples(short[] samples, int sampleOffset, int sampleCou { if (sampleCount == 0) return; UnqueueProcessedBuffers(); - var byteCount = sampleCount * _sound.BlockAlign; + int byteCount = sampleCount * _sound.BlockAlign; if (sampleOffset != 0) { AllocateTempSampleBuffer(sampleCount); @@ -123,7 +120,7 @@ public unsafe void WriteSamples(short[] samples, int sampleOffset, int sampleCou { _al.BufferData(buffer.BufferID, BufferFormat.Stereo16, sptr, byteCount, _sound.SampleRate); } - var bid = buffer.BufferID; + uint bid = buffer.BufferID; _al.SourceQueueBuffers(_sourceID, 1, &bid); _currentSamplesQueued += sampleCount; if (GetSourceState() != SourceState.Playing) @@ -134,10 +131,10 @@ public unsafe void WriteSamples(short[] samples, int sampleOffset, int sampleCou private unsafe void UnqueueProcessedBuffers() { - var releaseCount = GetSource(GetSourceInteger.BuffersProcessed); - var bids = stackalloc uint[releaseCount]; + int releaseCount = GetSource(GetSourceInteger.BuffersProcessed); + uint* bids = stackalloc uint[releaseCount]; _al.SourceUnqueueBuffers(_sourceID, releaseCount, bids); - for (var i = 0; i < releaseCount; i++) + for (int i = 0; i < releaseCount; i++) { var releasedBuffer = _bufferPool.ReleaseOne(); _currentSamplesQueued -= releasedBuffer.Length / _sound.BlockAlign; @@ -146,7 +143,7 @@ private unsafe void UnqueueProcessedBuffers() private int GetSource(GetSourceInteger param) { - _al.GetSourceProperty(_sourceID, param, out var value); + _al.GetSourceProperty(_sourceID, param, out int value); return value; } @@ -155,7 +152,7 @@ private SourceState GetSourceState() private void AllocateTempSampleBuffer(int sampleCount) { - var length = sampleCount * _sound.ChannelCount; + int length = sampleCount * _sound.ChannelCount; if (_tempSampleBuffer == null || _tempSampleBuffer.Length < length) { _tempSampleBuffer = new short[length]; diff --git a/src/BizHawk.Bizware.Audio/XAudio2SoundOutput.cs b/src/BizHawk.Bizware.Audio/XAudio2SoundOutput.cs index caf89ffc932..fc4cb3430db 100644 --- a/src/BizHawk.Bizware.Audio/XAudio2SoundOutput.cs +++ b/src/BizHawk.Bizware.Audio/XAudio2SoundOutput.cs @@ -27,7 +27,7 @@ private static string GetDeviceId(string deviceName) return null; } - using var enumerator = new IMMDeviceEnumerator(); + using IMMDeviceEnumerator enumerator = new(); var devices = enumerator.EnumAudioEndpoints(DataFlow.Render); var device = devices.FirstOrDefault(capDevice => capDevice.FriendlyName == deviceName); if (device is null) @@ -62,7 +62,7 @@ public void Dispose() public static IEnumerable GetDeviceNames() { - using var enumerator = new IMMDeviceEnumerator(); + using IMMDeviceEnumerator enumerator = new(); var devices = enumerator.EnumAudioEndpoints(DataFlow.Render); return devices.Select(capDevice => capDevice.FriendlyName); } @@ -71,17 +71,14 @@ public static IEnumerable GetDeviceNames() public int MaxSamplesDeficit { get; private set; } - public void ApplyVolumeSettings(double volume) - { - _sourceVoice.Volume = (float)volume; - } + public void ApplyVolumeSettings(double volume) => _sourceVoice.Volume = (float)volume; public void StartSound() { BufferSizeSamples = _sound.MillisecondsToSamples(_sound.ConfigBufferSizeMs); MaxSamplesDeficit = BufferSizeSamples; - var format = new WaveFormat(_sound.SampleRate, _sound.BytesPerSample * 8, _sound.ChannelCount); + WaveFormat format = new(_sound.SampleRate, _sound.BytesPerSample * 8, _sound.ChannelCount); _sourceVoice = _device.CreateSourceVoice(format); _bufferPool = new(); @@ -104,10 +101,10 @@ public void StopSound() public int CalculateSamplesNeeded() { - var isInitializing = _runningSamplesQueued == 0; - var detectedUnderrun = !isInitializing && _sourceVoice.State.BuffersQueued == 0; - var samplesAwaitingPlayback = _runningSamplesQueued - (long)_sourceVoice.State.SamplesPlayed; - var samplesNeeded = (int)Math.Max(BufferSizeSamples - samplesAwaitingPlayback, 0); + bool isInitializing = _runningSamplesQueued == 0; + bool detectedUnderrun = !isInitializing && _sourceVoice.State.BuffersQueued == 0; + long samplesAwaitingPlayback = _runningSamplesQueued - (long)_sourceVoice.State.SamplesPlayed; + int samplesNeeded = (int)Math.Max(BufferSizeSamples - samplesAwaitingPlayback, 0); if (isInitializing || detectedUnderrun) { _sound.HandleInitializationOrUnderrun(detectedUnderrun, ref samplesNeeded); @@ -119,7 +116,7 @@ public void WriteSamples(short[] samples, int sampleOffset, int sampleCount) { if (sampleCount == 0) return; _bufferPool.Release(_sourceVoice.State.BuffersQueued); - var byteCount = sampleCount * _sound.BlockAlign; + int byteCount = sampleCount * _sound.BlockAlign; var item = _bufferPool.Obtain(byteCount); samples.AsSpan(sampleOffset * _sound.BlockAlign / 2, byteCount / 2) .CopyTo(item.AudioBuffer.AsSpan()); @@ -152,8 +149,8 @@ public BufferPoolItem Obtain(int length) private BufferPoolItem GetAvailableItem(int length) { - var foundIndex = -1; - for (var i = 0; i < _availableItems.Count; i++) + int foundIndex = -1; + for (int i = 0; i < _availableItems.Count; i++) { if (_availableItems[i].MaxLength >= length && (foundIndex == -1 || _availableItems[i].MaxLength < _availableItems[foundIndex].MaxLength)) foundIndex = i; diff --git a/src/BizHawk.Bizware.BizwareGL/ArtManager.cs b/src/BizHawk.Bizware.BizwareGL/ArtManager.cs index 2fee78e871f..503b6bde371 100644 --- a/src/BizHawk.Bizware.BizwareGL/ArtManager.cs +++ b/src/BizHawk.Bizware.BizwareGL/ArtManager.cs @@ -39,17 +39,14 @@ public void Open() /// /// Loads the given stream as an Art instance /// - public Art LoadArt(Stream stream) - { - return LoadArtInternal(new BitmapBuffer(stream, new BitmapLoadOptions())); - } + public Art LoadArt(Stream stream) => LoadArtInternal(new BitmapBuffer(stream, new BitmapLoadOptions())); /// /// Loads the given path as an Art instance. /// public Art LoadArt(string path) { - using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); + using FileStream fs = new(path, FileMode.Open, FileAccess.Read, FileShare.Read); return LoadArtInternal(new BitmapBuffer(path, new BitmapLoadOptions())); } @@ -57,7 +54,7 @@ private Art LoadArtInternal(BitmapBuffer tex) { AssertIsOpen(true); - var a = new Art(this); + Art a = new(this); ArtLooseTextureAssociation.Add((a, tex)); ManagedArts.Add(a); @@ -84,7 +81,7 @@ public void Close(bool forever = true) // prepare input for atlas process and perform atlas // add 2 extra pixels for padding on all sides - var atlasItems = ArtLooseTextureAssociation + List atlasItems = ArtLooseTextureAssociation .Select(kvp => new TexAtlas.RectItem(kvp.Bitmap.Width + 2, kvp.Bitmap.Height + 2, kvp)) .ToList(); var results = TexAtlas.PackAtlas(atlasItems); @@ -94,28 +91,28 @@ public void Close(bool forever = true) throw new InvalidOperationException("Art files too big for atlas"); // prepare the output buffer - var bmpResult = new BitmapBuffer(results[0].Size); + BitmapBuffer bmpResult = new(results[0].Size); //for each item, copy it into the output buffer and set the tex parameters on them - for (var i = 0; i < atlasItems.Count; i++) + for (int i = 0; i < atlasItems.Count; i++) { var item = results[0].Items[i]; var (art, bitmap) = ((Art, BitmapBuffer)) item.Item; - var w = bitmap.Width; - var h = bitmap.Height; - var dx = item.X + 1; - var dy = item.Y + 1; - for (var y = 0; y < h; y++) + int w = bitmap.Width; + int h = bitmap.Height; + int dx = item.X + 1; + int dy = item.Y + 1; + for (int y = 0; y < h; y++) { - for (var x = 0; x < w; x++) + for (int x = 0; x < w; x++) { - var pixel = bitmap.GetPixel(x, y); + int pixel = bitmap.GetPixel(x, y); bmpResult.SetPixel(x+dx,y+dy,pixel); } } - var myDestWidth = (float)bmpResult.Width; - var myDestHeight = (float)bmpResult.Height; + float myDestWidth = bmpResult.Width; + float myDestHeight = bmpResult.Height; art.u0 = dx / myDestWidth; art.v0 = dy / myDestHeight; diff --git a/src/BizHawk.Bizware.BizwareGL/BitmapBuffer.cs b/src/BizHawk.Bizware.BizwareGL/BitmapBuffer.cs index 7e03c06cde8..956543b4cf1 100644 --- a/src/BizHawk.Bizware.BizwareGL/BitmapBuffer.cs +++ b/src/BizHawk.Bizware.BizwareGL/BitmapBuffer.cs @@ -83,13 +83,13 @@ public void YFlip() { // TODO - could be faster var bmpdata = LockBits(); - var newPixels = new int[Width * Height]; - var s = (int*)bmpdata.Scan0.ToPointer(); + int[] newPixels = new int[Width * Height]; + int* s = (int*)bmpdata.Scan0.ToPointer(); fixed (int* d = newPixels) { for (int y = 0, si = 0, di = (Height - 1) * Width; y < Height; y++) { - for (var x = 0; x < Width; x++, si++, di++) + for (int x = 0; x < Width; x++, si++, di++) { d[di] = s[si]; } @@ -108,15 +108,15 @@ public void YFlip() public void Normalize(bool yflip) { var bmpdata = LockBits(); - var newPixels = new int[Width * Height]; - var s = (int*)bmpdata.Scan0.ToPointer(); + int[] newPixels = new int[Width * Height]; + int* s = (int*)bmpdata.Scan0.ToPointer(); fixed (int* d = newPixels) { if (yflip) { for (int y = 0, si = 0, di = (Height - 1) * Width; y < Height; y++) { - for (var x = 0; x < Width; x++, si++, di++) + for (int x = 0; x < Width; x++, si++, di++) { d[di] = s[si] | unchecked((int)0xFF000000); } @@ -127,7 +127,7 @@ public void Normalize(bool yflip) { for (int y = 0, i=0; y < Height; y++) { - for (var x = 0; x < Width; x++, i++) + for (int x = 0; x < Width; x++, i++) { d[i] = s[i] | unchecked((int)0xFF000000); } @@ -140,19 +140,13 @@ public void Normalize(bool yflip) Pixels = newPixels; } - public int GetPixel(int x, int y) - { - return Pixels[Width * y + x]; - } + public int GetPixel(int x, int y) => Pixels[Width * y + x]; - public void SetPixel(int x, int y, int value) - { - Pixels[Width * y + x] = value; - } + public void SetPixel(int x, int y, int value) => Pixels[Width * y + x] = value; public Color GetPixelAsColor(int x, int y) { - var c = Pixels[Width * y + x]; + int c = Pixels[Width * y + x]; return Color.FromArgb(c); } @@ -163,7 +157,7 @@ public void Alphafy(int tcol) { for (int y = 0, idx = 0; y < Height; y++) { - for (var x = 0; x < Width; x++, idx++) + for (int x = 0; x < Width; x++, idx++) { if (Pixels[idx] == tcol) { @@ -176,26 +170,23 @@ public void Alphafy(int tcol) /// /// copies this bitmap and trims out transparent pixels, returning the offset to the topleft pixel /// - public BitmapBuffer Trim() - { - return Trim(out _, out _); - } + public BitmapBuffer Trim() => Trim(out _, out _); /// /// copies this bitmap and trims out transparent pixels, returning the offset to the topleft pixel /// public BitmapBuffer Trim(out int xofs, out int yofs) { - var minx = int.MaxValue; - var maxx = int.MinValue; - var miny = int.MaxValue; - var maxy = int.MinValue; - for (var y = 0; y < Height; y++) + int minx = int.MaxValue; + int maxx = int.MinValue; + int miny = int.MaxValue; + int maxy = int.MinValue; + for (int y = 0; y < Height; y++) { - for (var x = 0; x < Width; x++) + for (int x = 0; x < Width; x++) { - var pixel = GetPixel(x, y); - var a = (pixel >> 24) & 0xFF; + int pixel = GetPixel(x, y); + int a = (pixel >> 24) & 0xFF; if (a != 0) { minx = Math.Min(minx, x); @@ -212,12 +203,12 @@ public BitmapBuffer Trim(out int xofs, out int yofs) return new(0, 0); } - var w = maxx - minx + 1; - var h = maxy - miny + 1; - var bbRet = new BitmapBuffer(w, h); - for (var y = 0; y < h; y++) + int w = maxx - minx + 1; + int h = maxy - miny + 1; + BitmapBuffer bbRet = new(w, h); + for (int y = 0; y < h; y++) { - for (var x = 0; x < w; x++) + for (int x = 0; x < w; x++) { bbRet.SetPixel(x, y, GetPixel(x + minx, y + miny)); } @@ -233,14 +224,14 @@ public BitmapBuffer Trim(out int xofs, out int yofs) /// public void Pad() { - var widthRound = NextHigher(Width); - var heightRound = NextHigher(Height); + int widthRound = NextHigher(Width); + int heightRound = NextHigher(Height); if (widthRound == Width && heightRound == Height) return; - var NewPixels = new int[heightRound * widthRound]; + int[] NewPixels = new int[heightRound * widthRound]; for (int y = 0, sptr = 0, dptr = 0; y < Height; y++) { - for (var x = 0; x < Width; x++) + for (int x = 0; x < Width; x++) { NewPixels[dptr++] = Pixels[sptr++]; } @@ -258,7 +249,7 @@ public void Pad() /// public BitmapBuffer(string fname, BitmapLoadOptions options) { - using var fs = new FileStream(fname, FileMode.Open, FileAccess.Read, FileShare.Read); + using FileStream fs = new(fname, FileMode.Open, FileAccess.Read, FileShare.Read); LoadInternal(fs, null, options); } @@ -301,15 +292,12 @@ public BitmapBuffer(int width, int height, int[] pixels) /// Suggests that this BitmapBuffer is now XRGB instead of ARGB but doesn't actually change any of the pixels data. /// Should affect how things get exported from here, though, I think /// - public void DiscardAlpha() - { - HasAlpha = false; - } + public void DiscardAlpha() => HasAlpha = false; private void LoadInternal(Stream stream, Bitmap bitmap, BitmapLoadOptions options) { - var cleanup = options.CleanupAlpha0; - var needsPad = true; + bool cleanup = options.CleanupAlpha0; + bool needsPad = true; var colorKey24bpp = options.ColorKey24bpp; using (var loadedBmp = bitmap == null ? new Bitmap(stream) : null) // sneaky! @@ -319,19 +307,19 @@ private void LoadInternal(Stream stream, Bitmap bitmap, BitmapLoadOptions option // if we have a 24bpp image and a colorkey callback, the callback can choose a colorkey color and we'll use that if (bmp.PixelFormat == PixelFormat.Format24bppRgb && colorKey24bpp != null) { - var colorKey = colorKey24bpp(bmp); - var w = bmp.Width; - var h = bmp.Height; + int colorKey = colorKey24bpp(bmp); + int w = bmp.Width; + int h = bmp.Height; InitSize(w, h); var bmpdata = bmp.LockBits(new(0, 0, w, h), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); - var ptr = (int*)bmpdata.Scan0.ToPointer(); + int* ptr = (int*)bmpdata.Scan0.ToPointer(); fixed (int* pPtr = &Pixels[0]) { for (int idx = 0, y = 0; y < h; y++) { - for (var x = 0; x < w; x++) + for (int x = 0; x < w; x++) { - var srcPixel = ptr[idx]; + int srcPixel = ptr[idx]; if (srcPixel == colorKey) { srcPixel = 0; @@ -346,22 +334,22 @@ private void LoadInternal(Stream stream, Bitmap bitmap, BitmapLoadOptions option } if (bmp.PixelFormat is PixelFormat.Format8bppIndexed or PixelFormat.Format4bppIndexed) { - var w = bmp.Width; - var h = bmp.Height; + int w = bmp.Width; + int h = bmp.Height; InitSize(w, h); var bmpdata = bmp.LockBits(new(0, 0, w, h), ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed); var palette = bmp.Palette.Entries; - var ptr = (byte*)bmpdata.Scan0.ToPointer(); + byte* ptr = (byte*)bmpdata.Scan0.ToPointer(); fixed (int* pPtr = &Pixels[0]) { for (int idx = 0, y = 0; y < h; y++) { - for (var x = 0; x < w; x++) + for (int x = 0; x < w; x++) { int srcPixel = ptr[idx]; if (srcPixel != 0) { - var color = palette[srcPixel].ToArgb(); + int color = palette[srcPixel].ToArgb(); // make transparent pixels turn into black to avoid filtering issues and other annoying issues with stray junk in transparent pixels. // (yes, we can have palette entries with transparency in them (PNGs support this, annoyingly)) @@ -385,12 +373,12 @@ private void LoadInternal(Stream stream, Bitmap bitmap, BitmapLoadOptions option else { // dump the supplied bitmap into our pixels array - var width = bmp.Width; - var height = bmp.Height; + int width = bmp.Width; + int height = bmp.Height; InitSize(width, height); var bmpdata = bmp.LockBits(new(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); - var ptr = (int*)bmpdata.Scan0; - var stride = bmpdata.Stride / 4; + int* ptr = (int*)bmpdata.Scan0; + int stride = bmpdata.Stride / 4; LoadFrom(width, stride, height, (byte*)ptr, options); bmp.UnlockBits(bmpdata); needsPad = false; @@ -409,7 +397,7 @@ private void LoadInternal(Stream stream, Bitmap bitmap, BitmapLoadOptions option /// public void LoadFrom(int width, int stride, int height, byte* data, BitmapLoadOptions options) { - var cleanup = options.CleanupAlpha0; + bool cleanup = options.CleanupAlpha0; Width = width; Height = height; Pixels = new int[width * height]; @@ -417,10 +405,10 @@ public void LoadFrom(int width, int stride, int height, byte* data, BitmapLoadOp { for (int idx = 0, y = 0; y < Height; y++) { - for (var x = 0; x < Width; x++) + for (int x = 0; x < Width; x++) { - var src = y * stride + x; - var srcVal = ((int*)data)[src]; + int src = y * stride + x; + int srcVal = ((int*)data)[src]; // make transparent pixels turn into black to avoid filtering issues and other annoying issues with stray junk in transparent pixels if (cleanup) @@ -447,10 +435,10 @@ public void LoadFrom(int width, int stride, int height, byte* data, BitmapLoadOp /// public static int PremultiplyColor(int srcVal) { - var b = (srcVal >> 0) & 0xFF; - var g = (srcVal >> 8) & 0xFF; - var r = (srcVal >> 16) & 0xFF; - var a = (srcVal >> 24) & 0xFF; + int b = (srcVal >> 0) & 0xFF; + int g = (srcVal >> 8) & 0xFF; + int r = (srcVal >> 16) & 0xFF; + int a = (srcVal >> 24) & 0xFF; r = (r * a) >> 8; g = (g * a) >> 8; b = (b * a) >> 8; @@ -489,21 +477,21 @@ public void ClearWithoutAlloc() // http://techmikael.blogspot.com/2009/12/filling-array-with-default-value.html // this guy says its faster - var size = Width * Height; + int size = Width * Height; const byte fillValue = 0; const ulong fillValueLong = 0; fixed (int* ptr = &Pixels[0]) { - var dest = (ulong*)ptr; - var length = size; + ulong* dest = (ulong*)ptr; + int length = size; while (length >= 8) { *dest = fillValueLong; dest++; length -= 8; } - var bDest = (byte*)dest; + byte* bDest = (byte*)dest; for (byte i = 0; i < length; i++) { *bDest = fillValue; @@ -525,12 +513,12 @@ private void InitSize(int width, int height) private static int NextHigher(int k) { k--; - for (var i = 1; i < 32; i <<= 1) + for (int i = 1; i < 32; i <<= 1) { k |= k >> i; } - var candidate = k + 1; + int candidate = k + 1; return candidate; } @@ -546,7 +534,7 @@ public Bitmap ToSysdrawingBitmap() } var pf = HasAlpha ? PixelFormat.Format32bppArgb : PixelFormat.Format24bppRgb; - var bmp = new Bitmap(Width, Height, pf); + Bitmap bmp = new(Width, Height, pf); ToSysdrawingBitmap(bmp); return bmp; } @@ -559,7 +547,7 @@ public void ToSysdrawingBitmap(Bitmap bmp) { if (WrappedBitmap != null) { - using var g = Graphics.FromImage(bmp); + using Graphics g = Graphics.FromImage(bmp); g.CompositingMode = CompositingMode.SourceCopy; g.CompositingQuality = CompositingQuality.HighSpeed; g.DrawImageUnscaled(WrappedBitmap, 0, 0); @@ -575,14 +563,14 @@ public void ToSysdrawingBitmap(Bitmap bmp) } else if (bmp.Width != 0 && bmp.Height != 0) { - var ptr = (int*)bmpdata.Scan0.ToPointer(); + int* ptr = (int*)bmpdata.Scan0.ToPointer(); fixed (int* pPtr = &Pixels[0]) { for (int idx = 0, y = 0; y < Height; y++) { - for (var x = 0; x < Width; x++) + for (int x = 0; x < Width; x++) { - var srcPixel = pPtr[idx]; + int srcPixel = pPtr[idx]; ptr[idx] = srcPixel; idx++; } diff --git a/src/BizHawk.Bizware.BizwareGL/Pipeline.cs b/src/BizHawk.Bizware.BizwareGL/Pipeline.cs index 92c0ecd02fe..fd5782c332c 100644 --- a/src/BizHawk.Bizware.BizwareGL/Pipeline.cs +++ b/src/BizHawk.Bizware.BizwareGL/Pipeline.cs @@ -49,7 +49,7 @@ public UniformWorkingDictionary(Pipeline owner) Owner = owner; } - private Pipeline Owner; + private readonly Pipeline Owner; public new PipelineUniform this[string key] { #if true @@ -80,9 +80,6 @@ public PipelineUniform TryGetUniform(string name) public bool Available { get; } public string Errors { get; set; } - public void Dispose() - { - Owner.FreePipeline(this); - } + public void Dispose() => Owner.FreePipeline(this); } } \ No newline at end of file diff --git a/src/BizHawk.Bizware.BizwareGL/PipelineUniform.cs b/src/BizHawk.Bizware.BizwareGL/PipelineUniform.cs index fb2464d80ec..392cd25644d 100644 --- a/src/BizHawk.Bizware.BizwareGL/PipelineUniform.cs +++ b/src/BizHawk.Bizware.BizwareGL/PipelineUniform.cs @@ -15,10 +15,7 @@ internal PipelineUniform(Pipeline owner) Owner = owner; } - internal void AddUniformInfo(UniformInfo ui) - { - _uniformInfos.Add(ui); - } + internal void AddUniformInfo(UniformInfo ui) => _uniformInfos.Add(ui); public IEnumerable UniformInfos => _uniformInfos; @@ -40,45 +37,21 @@ public UniformInfo Sole } public Pipeline Owner { get; } - - public void Set(Matrix4x4 mat, bool transpose = false) - { - Owner?.Owner.SetPipelineUniformMatrix(this, mat, transpose); - } - public void Set(Vector4 vec) - { - Owner?.Owner.SetPipelineUniform(this, vec); - } + public void Set(Matrix4x4 mat, bool transpose = false) => Owner?.Owner.SetPipelineUniformMatrix(this, mat, transpose); - public void Set(Vector2 vec) - { - Owner?.Owner.SetPipelineUniform(this, vec); - } + public void Set(Vector4 vec) => Owner?.Owner.SetPipelineUniform(this, vec); - public void Set(float f) - { - Owner?.Owner.SetPipelineUniform(this, f); - } + public void Set(Vector2 vec) => Owner?.Owner.SetPipelineUniform(this, vec); - public void Set(Vector4[] vecs) - { - Owner?.Owner.SetPipelineUniform(this, vecs); - } + public void Set(float f) => Owner?.Owner.SetPipelineUniform(this, f); - public void Set(ref Matrix4x4 mat, bool transpose = false) - { - Owner?.Owner.SetPipelineUniformMatrix(this, ref mat, transpose); - } + public void Set(Vector4[] vecs) => Owner?.Owner.SetPipelineUniform(this, vecs); - public void Set(bool value) - { - Owner?.Owner.SetPipelineUniform(this, value); - } + public void Set(ref Matrix4x4 mat, bool transpose = false) => Owner?.Owner.SetPipelineUniformMatrix(this, ref mat, transpose); - public void Set(Texture2d tex) - { - Owner?.Owner.SetPipelineUniformSampler(this, tex); - } + public void Set(bool value) => Owner?.Owner.SetPipelineUniform(this, value); + + public void Set(Texture2d tex) => Owner?.Owner.SetPipelineUniformSampler(this, tex); } } \ No newline at end of file diff --git a/src/BizHawk.Bizware.BizwareGL/RenderTarget.cs b/src/BizHawk.Bizware.BizwareGL/RenderTarget.cs index 8285cbbfb3a..430c346e7f7 100644 --- a/src/BizHawk.Bizware.BizwareGL/RenderTarget.cs +++ b/src/BizHawk.Bizware.BizwareGL/RenderTarget.cs @@ -11,28 +11,16 @@ public RenderTarget(IGL owner, object opaque, Texture2d tex) Texture2d = tex; } - public override string ToString() - { - return $"GL RT: {Texture2d.Width}x{Texture2d.Height}"; - } + public override string ToString() => $"GL RT: {Texture2d.Width}x{Texture2d.Height}"; public object Opaque { get; } public IGL Owner { get; } public Texture2d Texture2d { get; } - public void Unbind() - { - Owner.BindRenderTarget(null); - } + public void Unbind() => Owner.BindRenderTarget(null); - public void Bind() - { - Owner.BindRenderTarget(this); - } + public void Bind() => Owner.BindRenderTarget(this); - public void Dispose() - { - Owner.FreeRenderTarget(this); - } + public void Dispose() => Owner.FreeRenderTarget(this); } } \ No newline at end of file diff --git a/src/BizHawk.Bizware.BizwareGL/RetroShader.cs b/src/BizHawk.Bizware.BizwareGL/RetroShader.cs index 2eb7f3446fb..702e53b8ba5 100644 --- a/src/BizHawk.Bizware.BizwareGL/RetroShader.cs +++ b/src/BizHawk.Bizware.BizwareGL/RetroShader.cs @@ -21,8 +21,8 @@ public RetroShader(IGL owner, string source, bool debug = false) VertexLayout.DefineVertexAttribute("tex", 2, 2, VertexAttribPointerType.Float, AttribUsage.Texcoord0, false, 40, 32); VertexLayout.Close(); - var vsSource = $"#define VERTEX\r\n{source}"; - var psSource = $"#define FRAGMENT\r\n{source}"; + string vsSource = $"#define VERTEX\r\n{source}"; + string psSource = $"#define FRAGMENT\r\n{source}"; var vs = owner.CreateVertexShader(vsSource, "main_vertex", debug); var ps = owner.CreateFragmentShader(psSource, "main_fragment", debug); Pipeline = Owner.CreatePipeline(VertexLayout, vs, ps, debug, "retro"); @@ -65,11 +65,9 @@ public void Dispose() VertexLayout.Release(); } - public void Bind() - { + public void Bind() => // lame... Owner.BindPipeline(Pipeline); - } public unsafe void Run(Texture2d tex, Size InputSize, Size OutputSize, bool flip) { @@ -84,7 +82,7 @@ public unsafe void Run(Texture2d tex, Size InputSize, Size OutputSize, bool flip var Projection = Owner.CreateGuiProjectionMatrix(OutputSize); var Modelview = Owner.CreateGuiViewMatrix(OutputSize); - var mat = Matrix4x4.Transpose(Modelview * Projection); + Matrix4x4 mat = Matrix4x4.Transpose(Modelview * Projection); Pipeline["modelViewProj"].Set(mat, true); Owner.SetTextureWrapMode(tex, true); @@ -92,11 +90,11 @@ public unsafe void Run(Texture2d tex, Size InputSize, Size OutputSize, bool flip sampler0.Set(tex); Owner.SetViewport(OutputSize); - var time = DateTime.Now.Second + (float)DateTime.Now.Millisecond / 1000; + float time = DateTime.Now.Second + (float)DateTime.Now.Millisecond / 1000; Pipeline["Time"].Set(time); - var w = OutputSize.Width; - var h = OutputSize.Height; + int w = OutputSize.Width; + int h = OutputSize.Height; float v0, v1; if (flip) @@ -110,8 +108,8 @@ public unsafe void Run(Texture2d tex, Size InputSize, Size OutputSize, bool flip v1 = 1; } - var pData = stackalloc float[10 * 4]; - var i = 0; + float* pData = stackalloc float[10 * 4]; + int i = 0; pData[i++] = 0; pData[i++] = 0; pData[i++] = 0; pData[i++] = 1; //topleft vert pData[i++] = 0; pData[i++] = 0; pData[i++] = 0; pData[i++] = 0; //useless color pData[i++] = 0; pData[i++] = v0; diff --git a/src/BizHawk.Bizware.BizwareGL/Shader.cs b/src/BizHawk.Bizware.BizwareGL/Shader.cs index 5e8b7ff587e..773bd2719f4 100644 --- a/src/BizHawk.Bizware.BizwareGL/Shader.cs +++ b/src/BizHawk.Bizware.BizwareGL/Shader.cs @@ -32,10 +32,7 @@ public void Release() } } - public void AddRef() - { - RefCount++; - } + public void AddRef() => RefCount++; } } \ No newline at end of file diff --git a/src/BizHawk.Bizware.BizwareGL/StringRenderer.cs b/src/BizHawk.Bizware.BizwareGL/StringRenderer.cs index 21f423b0edf..47ae2d17e20 100644 --- a/src/BizHawk.Bizware.BizwareGL/StringRenderer.cs +++ b/src/BizHawk.Bizware.BizwareGL/StringRenderer.cs @@ -19,7 +19,7 @@ public StringRenderer(IGL owner, Stream xml, params Stream[] textures) FontInfo.LoadXml(xml); // load textures - for (var i=0; i nodes = new List(); + public readonly RectangleBinPack rbp = new(); + public readonly List nodes = new(); } public const int MaxSizeBits = 16; @@ -50,14 +50,14 @@ static void AddAtlas(ICollection<(Size, List)> atlases, IEnumerable(); - for (var i = 3; i <= MaxSizeBits; i++) + List todoSizes = new(); + for (int i = 3; i <= MaxSizeBits; i++) { - for (var j = 3; j <= MaxSizeBits; j++) + for (int j = 3; j <= MaxSizeBits; j++) { - var w = 1 << i; - var h = 1 << j; - var tfp = new TryFitParam(w, h); + int w = 1 << i; + int h = 1 << j; + TryFitParam tfp = new(w, h); todoSizes.Add(tfp); } } @@ -65,7 +65,7 @@ static void AddAtlas(ICollection<(Size, List)> atlases, IEnumerable { - var rbp = new RectangleBinPack(); + RectangleBinPack rbp = new(); rbp.Init(16384, 16384); param.rbp.Init(param.w, param.h); @@ -86,7 +86,7 @@ static void AddAtlas(ICollection<(Size, List)> atlases, IEnumerable)> atlases, IEnumerable best) { continue; // larger than best, not interested @@ -185,19 +185,18 @@ public void Init(int width, int height) /// Inserts a new rectangle of the given size into the bin. /// A pointer to the node that stores the newly added rectangle, or 0 if it didn't fit. /// Running time is linear to the number of rectangles that have been already packed. - public Node Insert(int width, int height) - { - return Insert(root, width, height); - } + public Node Insert(int width, int height) => Insert(root, width, height); +#pragma warning disable IDE0051 /// Computes the ratio of used surface area. private float Occupancy() { - var totalSurfaceArea = binWidth * binHeight; - var usedSurfaceArea = UsedSurfaceArea(root); + int totalSurfaceArea = binWidth * binHeight; + int usedSurfaceArea = UsedSurfaceArea(root); return (float)usedSurfaceArea / totalSurfaceArea; } + #pragma warning restore IDE0051 private Node root; @@ -210,7 +209,7 @@ private static int UsedSurfaceArea(Node node) { if (node.left != null || node.right != null) { - var usedSurfaceArea = node.width * node.height; + int usedSurfaceArea = node.width * node.height; if (node.left != null) usedSurfaceArea += UsedSurfaceArea(node.left); if (node.right != null) @@ -253,8 +252,8 @@ private static Node Insert(Node node, int width, int height) // The new cell will fit, split the remaining space along the shorter axis, // that is probably more optimal. - var w = node.width - width; - var h = node.height - height; + int w = node.width - width; + int h = node.height - height; node.left = new(); node.right = new(); if (w <= h) // Split the remaining space in horizontal direction. diff --git a/src/BizHawk.Bizware.BizwareGL/Texture2d.cs b/src/BizHawk.Bizware.BizwareGL/Texture2d.cs index 3040ce0a109..94902282832 100644 --- a/src/BizHawk.Bizware.BizwareGL/Texture2d.cs +++ b/src/BizHawk.Bizware.BizwareGL/Texture2d.cs @@ -12,10 +12,7 @@ public class Texture2d : IDisposable /// /// resolves the texture into a new BitmapBuffer /// - public BitmapBuffer Resolve() - { - return Owner.ResolveTexture2d(this); - } + public BitmapBuffer Resolve() => Owner.ResolveTexture2d(this); public void Dispose() { @@ -31,10 +28,7 @@ public Texture2d(IGL owner, object opaque, int width, int height) Height = height; } - public override string ToString() - { - return $"GL Tex: {Width}x{Height}"; - } + public override string ToString() => $"GL Tex: {Width}x{Height}"; public void LoadFrom(BitmapBuffer buffer) { diff --git a/src/BizHawk.Bizware.BizwareGL/VertexLayout.cs b/src/BizHawk.Bizware.BizwareGL/VertexLayout.cs index 6da0e46d3b2..f4aa93e7082 100644 --- a/src/BizHawk.Bizware.BizwareGL/VertexLayout.cs +++ b/src/BizHawk.Bizware.BizwareGL/VertexLayout.cs @@ -31,10 +31,7 @@ public void Release() } } - public void AddRef() - { - RefCount++; - } + public void AddRef() => RefCount++; /// already closed (by call to ) public void DefineVertexAttribute(string name, int index, int components, VertexAttribPointerType attribType, AttribUsage usage, bool normalized, int stride, int offset = 0) @@ -50,10 +47,7 @@ public void DefineVertexAttribute(string name, int index, int components, Vertex /// /// finishes this VertexLayout and renders it immutable /// - public void Close() - { - Closed = true; - } + public void Close() => Closed = true; public class LayoutItem { diff --git a/src/BizHawk.Bizware.Graphics.Controls/Controls/OpenGLControl.cs b/src/BizHawk.Bizware.Graphics.Controls/Controls/OpenGLControl.cs index 3edc4984909..e11b4b1bda4 100644 --- a/src/BizHawk.Bizware.Graphics.Controls/Controls/OpenGLControl.cs +++ b/src/BizHawk.Bizware.Graphics.Controls/Controls/OpenGLControl.cs @@ -74,15 +74,9 @@ public override void SetVsync(bool state) Context.SetVsync(state); } - public override void Begin() - { - MakeContextCurrent(); - } + public override void Begin() => MakeContextCurrent(); - public override void End() - { - SDL2OpenGLContext.MakeNoneCurrent(); - } + public override void End() => SDL2OpenGLContext.MakeNoneCurrent(); public override void SwapBuffers() { diff --git a/src/BizHawk.Bizware.Graphics/D3D9/IGL_D3D9.cs b/src/BizHawk.Bizware.Graphics/D3D9/IGL_D3D9.cs index 194a41e42c8..d4dc622cee0 100644 --- a/src/BizHawk.Bizware.Graphics/D3D9/IGL_D3D9.cs +++ b/src/BizHawk.Bizware.Graphics/D3D9/IGL_D3D9.cs @@ -65,7 +65,7 @@ public IGL_D3D9() } // get the native window handle - var wminfo = default(SDL_SysWMinfo); + SDL_SysWMinfo wminfo = default; SDL_GetVersion(out wminfo.version); SDL_GetWindowWMInfo(_offscreenSdl2Window, ref wminfo); if (wminfo.subsystem != SDL_SYSWM_TYPE.SDL_SYSWM_WINDOWS) @@ -93,7 +93,7 @@ public void AlternateVsyncPass(int pass) private void CreateDevice() { // this object is only used for creating a device, it's not needed afterwards - using var d3d9 = new Direct3D(); + using Direct3D d3d9 = new(); var pp = MakePresentParameters(); @@ -213,7 +213,7 @@ public void ClearColor(Color color) public void FreeTexture(Texture2d tex) { - var tw = (TextureWrapper)tex.Opaque; + TextureWrapper tw = (TextureWrapper)tex.Opaque; tw.Texture.Dispose(); } @@ -230,7 +230,7 @@ public Shader CreateFragmentShader(string source, string entry, bool required) { try { - var sw = new ShaderWrapper(); + ShaderWrapper sw = new(); // ShaderFlags.EnableBackwardsCompatibility - used this once upon a time (please leave a note about why) var result = ShaderBytecode.Compile( @@ -242,7 +242,7 @@ public Shader CreateFragmentShader(string source, string entry, bool required) sw.PS = new(_device, result); sw.Bytecode = result; - var s = new Shader(this, sw, true); + Shader s = new(this, sw, true); sw.IGLShader = s; return s; @@ -263,7 +263,7 @@ public Shader CreateVertexShader(string source, string entry, bool required) { try { - var sw = new ShaderWrapper(); + ShaderWrapper sw = new(); var result = ShaderBytecode.Compile( shaderSource: source, @@ -274,7 +274,7 @@ public Shader CreateVertexShader(string source, string entry, bool required) sw.VS = new(_device, result); sw.Bytecode = result; - var s = new Shader(this, sw, true); + Shader s = new(this, sw, true); sw.IGLShader = s; return s; @@ -315,7 +315,7 @@ public Pipeline CreatePipeline(VertexLayout vertexLayout, Shader vertexShader, S { if (!vertexShader.Available || !fragmentShader.Available) { - var errors = $"Vertex Shader:\r\n {vertexShader.Errors} \r\n-------\r\nFragment Shader:\r\n{fragmentShader.Errors}"; + string errors = $"Vertex Shader:\r\n {vertexShader.Errors} \r\n-------\r\nFragment Shader:\r\n{fragmentShader.Errors}"; if (required) { throw new InvalidOperationException($"Couldn't build required GL pipeline:\r\n{errors}"); @@ -324,8 +324,8 @@ public Pipeline CreatePipeline(VertexLayout vertexLayout, Shader vertexShader, S return new(this, null, false, null, null, null) { Errors = errors }; } - var ves = new VertexElement[vertexLayout.Items.Count + 1]; - var stride = 0; + VertexElement[] ves = new VertexElement[vertexLayout.Items.Count + 1]; + int stride = 0; foreach (var (i, item) in vertexLayout.Items) { DeclarationType declType; @@ -375,7 +375,7 @@ public Pipeline CreatePipeline(VertexLayout vertexLayout, Shader vertexShader, S // must be placed at the end ves[vertexLayout.Items.Count] = VertexElement.VertexDeclarationEnd; - var pw = new PipelineWrapper + PipelineWrapper pw = new() { VertexDeclaration = new(_device, ves), VertexShader = (ShaderWrapper)vertexShader.Opaque, @@ -384,14 +384,14 @@ public Pipeline CreatePipeline(VertexLayout vertexLayout, Shader vertexShader, S }; // scan uniforms from reflection - var uniforms = new List(); + List uniforms = new(); var vsct = pw.VertexShader.Bytecode.ConstantTable; var psct = pw.FragmentShader.Bytecode.ConstantTable; foreach (var ct in new[] { vsct, psct }) { - var todo = new Queue<(string, EffectHandle)>(); - var n = ct.Description.Constants; - for (var i = 0; i < n; i++) + Queue<(string, EffectHandle)> todo = new(); + int n = ct.Description.Constants; + for (int i = 0; i < n; i++) { var handle = ct.GetConstant(null, i); todo.Enqueue((string.Empty, handle)); @@ -406,8 +406,8 @@ public Pipeline CreatePipeline(VertexLayout vertexLayout, Shader vertexShader, S if (descr.StructMembers != 0) { - var newPrefix = $"{prefix}{descr.Name}."; - for (var j = 0; j < descr.StructMembers; j++) + string newPrefix = $"{prefix}{descr.Name}."; + for (int j = 0; j < descr.StructMembers; j++) { var subHandle = ct.GetConstant(handle, j); todo.Enqueue((newPrefix, subHandle)); @@ -416,11 +416,11 @@ public Pipeline CreatePipeline(VertexLayout vertexLayout, Shader vertexShader, S continue; } - var ui = new UniformInfo(); - var uw = new UniformWrapper(); + UniformInfo ui = new(); + UniformWrapper uw = new(); ui.Opaque = uw; - var name = prefix + descr.Name; + string name = prefix + descr.Name; // uniforms done through the entry point signature have $ in their names which isn't helpful, so get rid of that name = name.RemovePrefix('$'); @@ -457,7 +457,7 @@ public void FreePipeline(Pipeline pipeline) public void Internal_FreeShader(Shader shader) { - var sw = (ShaderWrapper)shader.Opaque; + ShaderWrapper sw = (ShaderWrapper)shader.Opaque; sw.Bytecode.Dispose(); sw.PS?.Dispose(); sw.VS?.Dispose(); @@ -500,7 +500,7 @@ public void BindPipeline(Pipeline pipeline) return; } - var pw = (PipelineWrapper)pipeline.Opaque; + PipelineWrapper pw = (PipelineWrapper)pipeline.Opaque; _device.PixelShader = pw.FragmentShader.PS; _device.VertexShader = pw.VertexShader.VS; _device.VertexDeclaration = pw.VertexDeclaration; @@ -510,7 +510,7 @@ public void SetPipelineUniform(PipelineUniform uniform, bool value) { foreach (var ui in uniform.UniformInfos) { - var uw = (UniformWrapper)ui.Opaque; + UniformWrapper uw = (UniformWrapper)ui.Opaque; uw.CT.SetValue(_device, uw.EffectHandle, value); } } @@ -522,7 +522,7 @@ public void SetPipelineUniformMatrix(PipelineUniform uniform, ref Matrix4x4 mat, { foreach (var ui in uniform.UniformInfos) { - var uw = (UniformWrapper)ui.Opaque; + UniformWrapper uw = (UniformWrapper)ui.Opaque; uw.CT.SetValue(_device, uw.EffectHandle, mat.ToSharpDXMatrix(!transpose)); } } @@ -531,7 +531,7 @@ public void SetPipelineUniform(PipelineUniform uniform, Vector4 value) { foreach (var ui in uniform.UniformInfos) { - var uw = (UniformWrapper)ui.Opaque; + UniformWrapper uw = (UniformWrapper)ui.Opaque; uw.CT.SetValue(_device, uw.EffectHandle, value.ToSharpDXVector4()); } } @@ -540,7 +540,7 @@ public void SetPipelineUniform(PipelineUniform uniform, Vector2 value) { foreach (var ui in uniform.UniformInfos) { - var uw = (UniformWrapper)ui.Opaque; + UniformWrapper uw = (UniformWrapper)ui.Opaque; uw.CT.SetValue(_device, uw.EffectHandle, value.ToSharpDXVector2()); } } @@ -549,7 +549,7 @@ public void SetPipelineUniform(PipelineUniform uniform, float value) { foreach (var ui in uniform.UniformInfos) { - var uw = (UniformWrapper)ui.Opaque; + UniformWrapper uw = (UniformWrapper)ui.Opaque; uw.CT.SetValue(_device, uw.EffectHandle, value); } } @@ -559,7 +559,7 @@ public void SetPipelineUniform(PipelineUniform uniform, Vector4[] values) var v = Array.ConvertAll(values, v => v.ToSharpDXVector4()); foreach (var ui in uniform.UniformInfos) { - var uw = (UniformWrapper)ui.Opaque; + UniformWrapper uw = (UniformWrapper)ui.Opaque; uw.CT.SetValue(_device, uw.EffectHandle, v); } } @@ -571,7 +571,7 @@ public void SetPipelineUniformSampler(PipelineUniform uniform, Texture2d tex) return; // uniform was optimized out } - var tw = (TextureWrapper)tex.Opaque; + TextureWrapper tw = (TextureWrapper)tex.Opaque; foreach (var ui in uniform.UniformInfos) { if (!ui.IsSampler) @@ -590,7 +590,7 @@ public void SetPipelineUniformSampler(PipelineUniform uniform, Texture2d tex) public void SetTextureWrapMode(Texture2d tex, bool clamp) { - var tw = (TextureWrapper)tex.Opaque; + TextureWrapper tw = (TextureWrapper)tex.Opaque; tw.WrapClamp = clamp ? TextureAddress.Clamp : TextureAddress.Wrap; } @@ -606,34 +606,32 @@ public void SetMagFilter(Texture2d texture, TextureMagFilter magFilter) public Texture2d LoadTexture(Bitmap bitmap) { - using var bmp = new BitmapBuffer(bitmap, new()); + using BitmapBuffer bmp = new(bitmap, new()); return LoadTexture(bmp); } public Texture2d LoadTexture(Stream stream) { - using var bmp = new BitmapBuffer(stream, new()); + using BitmapBuffer bmp = new(stream, new()); return LoadTexture(bmp); } public Texture2d CreateTexture(int width, int height) { - var tex = new Texture(_device, width, height, 1, Usage.None, Format.A8R8G8B8, Pool.Managed); - var tw = new TextureWrapper { Texture = tex }; - var ret = new Texture2d(this, tw, width, height); + Texture tex = new(_device, width, height, 1, Usage.None, Format.A8R8G8B8, Pool.Managed); + TextureWrapper tw = new() { Texture = tex }; + Texture2d ret = new(this, tw, width, height); return ret; } - public Texture2d WrapGLTexture2d(IntPtr glTexId, int width, int height) - { + public Texture2d WrapGLTexture2d(IntPtr glTexId, int width, int height) => // only used for OpenGL - return null; - } + null; /// GDI+ call returned unexpected data public unsafe void LoadTextureData(Texture2d tex, BitmapBuffer bmp) { - var tw = (TextureWrapper)tex.Opaque; + TextureWrapper tw = (TextureWrapper)tex.Opaque; var bmpData = bmp.LockBits(); try @@ -646,8 +644,8 @@ public unsafe void LoadTextureData(Texture2d tex, BitmapBuffer bmp) throw new InvalidOperationException(); } - var srcSpan = new ReadOnlySpan(bmpData.Scan0.ToPointer(), bmpData.Stride * bmp.Height); - var dstSpan = new Span(dr.DataPointer.ToPointer(), dr.Pitch * bmp.Height); + ReadOnlySpan srcSpan = new(bmpData.Scan0.ToPointer(), bmpData.Stride * bmp.Height); + Span dstSpan = new(dr.DataPointer.ToPointer(), dr.Pitch * bmp.Height); srcSpan.CopyTo(dstSpan); } finally @@ -668,8 +666,8 @@ public Texture2d LoadTexture(BitmapBuffer bmp) public BitmapBuffer ResolveTexture2d(Texture2d tex) { // TODO - lazy create and cache resolving target in RT - using var target = new Texture(_device, tex.IntWidth, tex.IntHeight, 1, Usage.None, Format.A8R8G8B8, Pool.SystemMemory); - var tw = (TextureWrapper)tex.Opaque; + using Texture target = new(_device, tex.IntWidth, tex.IntHeight, 1, Usage.None, Format.A8R8G8B8, Pool.SystemMemory); + TextureWrapper tw = (TextureWrapper)tex.Opaque; _device.GetRenderTargetData(tw.Texture.GetSurfaceLevel(0), target.GetSurfaceLevel(0)); @@ -681,8 +679,8 @@ public BitmapBuffer ResolveTexture2d(Texture2d tex) { throw new InvalidOperationException(); } - - var pixels = new int[tex.IntWidth * tex.IntHeight]; + + int[] pixels = new int[tex.IntWidth * tex.IntHeight]; Marshal.Copy(dr.DataPointer, pixels, 0, tex.IntWidth * tex.IntHeight); return new(tex.IntWidth, tex.IntHeight, pixels); } @@ -694,19 +692,13 @@ public BitmapBuffer ResolveTexture2d(Texture2d tex) public Texture2d LoadTexture(string path) { - using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); + using FileStream fs = new(path, FileMode.Open, FileAccess.Read, FileShare.Read); return LoadTexture(fs); } - public Matrix4x4 CreateGuiProjectionMatrix(int w, int h) - { - return CreateGuiProjectionMatrix(new(w, h)); - } + public Matrix4x4 CreateGuiProjectionMatrix(int w, int h) => CreateGuiProjectionMatrix(new(w, h)); - public Matrix4x4 CreateGuiViewMatrix(int w, int h, bool autoFlip) - { - return CreateGuiViewMatrix(new(w, h), autoFlip); - } + public Matrix4x4 CreateGuiViewMatrix(int w, int h, bool autoFlip) => CreateGuiViewMatrix(new(w, h), autoFlip); public Matrix4x4 CreateGuiProjectionMatrix(Size dims) { @@ -733,19 +725,13 @@ public void SetViewport(int x, int y, int width, int height) _device.ScissorRect = new(x, y, x + width, y + height); } - public void SetViewport(int width, int height) - { - SetViewport(0, 0, width, height); - } + public void SetViewport(int width, int height) => SetViewport(0, 0, width, height); - public void SetViewport(Size size) - { - SetViewport(size.Width, size.Height); - } + public void SetViewport(Size size) => SetViewport(size.Width, size.Height); public void FreeRenderTarget(RenderTarget rt) { - var tw = (TextureWrapper)rt.Texture2d.Opaque; + TextureWrapper tw = (TextureWrapper)rt.Texture2d.Opaque; tw.Texture.Dispose(); tw.Texture = null; _renderTargets.Remove(rt); @@ -753,9 +739,9 @@ public void FreeRenderTarget(RenderTarget rt) public RenderTarget CreateRenderTarget(int w, int h) { - var tw = new TextureWrapper { Texture = CreateRenderTargetTexture(w, h) }; - var tex = new Texture2d(this, tw, w, h); - var rt = new RenderTarget(this, tw, tex); + TextureWrapper tw = new() { Texture = CreateRenderTargetTexture(w, h) }; + Texture2d tex = new(this, tw, w, h); + RenderTarget rt = new(this, tw, tex); _renderTargets.Add(rt); return rt; } @@ -776,7 +762,7 @@ private void ResumeRenderTargets() { foreach (var rt in _renderTargets) { - var tw = (TextureWrapper)rt.Opaque; + TextureWrapper tw = (TextureWrapper)rt.Opaque; tw.Texture = CreateRenderTargetTexture(rt.Texture2d.IntWidth, rt.Texture2d.IntHeight); } } @@ -792,7 +778,7 @@ public void BindRenderTarget(RenderTarget rt) } // dispose doesn't seem necessary for reset here... - var tw = (TextureWrapper)rt.Opaque; + TextureWrapper tw = (TextureWrapper)rt.Opaque; using var texSurface = tw.Texture.GetSurfaceLevel(0); _device.SetRenderTarget(0, texSurface); _device.DepthStencilSurface = null; @@ -811,7 +797,7 @@ private void DrawPrimitiveUP(PrimitiveType primitiveType, int primitiveCount, In public void Draw(IntPtr data, int count) { - var pw = (PipelineWrapper)_currPipeline.Opaque; + PipelineWrapper pw = (PipelineWrapper)_currPipeline.Opaque; // this is stupid, sharpdx only public exposes DrawUserPrimatives // why is this bad? it takes in an array of T diff --git a/src/BizHawk.Bizware.Graphics/GDIPlus/GDIPlusRenderTarget.cs b/src/BizHawk.Bizware.Graphics/GDIPlus/GDIPlusRenderTarget.cs index 56aa376e9a6..f46da5afe37 100644 --- a/src/BizHawk.Bizware.Graphics/GDIPlus/GDIPlusRenderTarget.cs +++ b/src/BizHawk.Bizware.Graphics/GDIPlus/GDIPlusRenderTarget.cs @@ -50,7 +50,7 @@ public void CreateGraphics() } else { - var gtex = (GDIPlusTexture)Target.Texture2d.Opaque; + GDIPlusTexture gtex = (GDIPlusTexture)Target.Texture2d.Opaque; CurGraphics?.Dispose(); CurGraphics = SDGraphics.FromImage(gtex.SDBitmap); r = Target.Texture2d.Rectangle; diff --git a/src/BizHawk.Bizware.Graphics/GDIPlus/IGL_GDIPlus.cs b/src/BizHawk.Bizware.Graphics/GDIPlus/IGL_GDIPlus.cs index 12672eebc88..814ea0dbab5 100644 --- a/src/BizHawk.Bizware.Graphics/GDIPlus/IGL_GDIPlus.cs +++ b/src/BizHawk.Bizware.Graphics/GDIPlus/IGL_GDIPlus.cs @@ -16,10 +16,7 @@ public class IGL_GDIPlus : IGL { public EDispMethod DispMethodEnum => EDispMethod.GdiPlus; - public void Dispose() - { - BufferedGraphicsContext.Dispose(); - } + public void Dispose() => BufferedGraphicsContext.Dispose(); public void ClearColor(Color color) => GetCurrentGraphics().Clear(color); @@ -28,7 +25,7 @@ public void ClearColor(Color color) public void FreeTexture(Texture2d tex) { - var gtex = (GDIPlusTexture)tex.Opaque; + GDIPlusTexture gtex = (GDIPlusTexture)tex.Opaque; gtex.Dispose(); } @@ -52,10 +49,7 @@ public void DisableBlending() g.CompositingQuality = CompositingQuality.HighSpeed; } - public Pipeline CreatePipeline(VertexLayout vertexLayout, Shader vertexShader, Shader fragmentShader, bool required, string memo) - { - return null; - } + public Pipeline CreatePipeline(VertexLayout vertexLayout, Shader vertexShader, Shader fragmentShader, bool required, string memo) => null; public void FreePipeline(Pipeline pipeline) { @@ -125,29 +119,27 @@ public void SetMagFilter(Texture2d texture, TextureMagFilter magFilter) public Texture2d LoadTexture(Bitmap bitmap) { - var sdBitmap = (Bitmap)bitmap.Clone(); - var gtex = new GDIPlusTexture { SDBitmap = sdBitmap }; + Bitmap sdBitmap = (Bitmap)bitmap.Clone(); + GDIPlusTexture gtex = new() { SDBitmap = sdBitmap }; return new(this, gtex, bitmap.Width, bitmap.Height); } public Texture2d LoadTexture(Stream stream) { - using var bmp = new BitmapBuffer(stream, new()); + using BitmapBuffer bmp = new(stream, new()); return LoadTexture(bmp); } public Texture2d CreateTexture(int width, int height) => null; - public Texture2d WrapGLTexture2d(IntPtr glTexId, int width, int height) - { + public Texture2d WrapGLTexture2d(IntPtr glTexId, int width, int height) => // only used for OpenGL - return null; - } + null; public void LoadTextureData(Texture2d tex, BitmapBuffer bmp) { - var gtex = (GDIPlusTexture)tex.Opaque; + GDIPlusTexture gtex = (GDIPlusTexture)tex.Opaque; bmp.ToSysdrawingBitmap(gtex.SDBitmap); } @@ -155,51 +147,41 @@ public Texture2d LoadTexture(BitmapBuffer bmp) { // definitely needed (by TextureFrugalizer at least) var sdBitmap = bmp.ToSysdrawingBitmap(); - var gtex = new GDIPlusTexture { SDBitmap = sdBitmap }; + GDIPlusTexture gtex = new() { SDBitmap = sdBitmap }; return new(this, gtex, bmp.Width, bmp.Height); } public BitmapBuffer ResolveTexture2d(Texture2d tex) { - var gtex = (GDIPlusTexture)tex.Opaque; - var blow = new BitmapLoadOptions + GDIPlusTexture gtex = (GDIPlusTexture)tex.Opaque; + BitmapLoadOptions blow = new() { AllowWrap = false // must be an independent resource }; - var bb = new BitmapBuffer(gtex.SDBitmap, blow); + BitmapBuffer bb = new(gtex.SDBitmap, blow); return bb; } public Texture2d LoadTexture(string path) { - using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); + using FileStream fs = new(path, FileMode.Open, FileAccess.Read, FileShare.Read); return LoadTexture(fs); } - public Matrix4x4 CreateGuiProjectionMatrix(int w, int h) - { - return CreateGuiProjectionMatrix(new(w, h)); - } + public Matrix4x4 CreateGuiProjectionMatrix(int w, int h) => CreateGuiProjectionMatrix(new(w, h)); - public Matrix4x4 CreateGuiViewMatrix(int w, int h, bool autoFlip) - { - return CreateGuiViewMatrix(new(w, h), autoFlip); - } + public Matrix4x4 CreateGuiViewMatrix(int w, int h, bool autoFlip) => CreateGuiViewMatrix(new(w, h), autoFlip); - public Matrix4x4 CreateGuiProjectionMatrix(Size dims) - { + public Matrix4x4 CreateGuiProjectionMatrix(Size dims) => // see CreateGuiViewMatrix for more - return Matrix4x4.Identity; - } + Matrix4x4.Identity; - public Matrix4x4 CreateGuiViewMatrix(Size dims, bool autoFlip) - { + public Matrix4x4 CreateGuiViewMatrix(Size dims, bool autoFlip) => // on account of gdi+ working internally with a default view exactly like we want, we don't need to setup a new one here // furthermore, we _cant_, without inverting the GuiView and GuiProjection before drawing, to completely undo it // this might be feasible, but its kind of slow and annoying and worse, seemingly numerically unstable - return Matrix4x4.Identity; - } + Matrix4x4.Identity; public void SetViewport(int x, int y, int width, int height) { @@ -209,38 +191,33 @@ public void SetViewport(int width, int height) { } - public void SetViewport(Size size) - { - SetViewport(size.Width, size.Height); - } + public void SetViewport(Size size) => SetViewport(size.Width, size.Height); public void BeginScene() { } - public void EndScene() - { + public void EndScene() => // maybe an inconsistent semantic with other implementations.. // but accomplishes the needed goal of getting the current RT to render BindRenderTarget(null); - } public void FreeRenderTarget(RenderTarget rt) { - var grt = (GDIPlusRenderTarget)rt.Opaque; + GDIPlusRenderTarget grt = (GDIPlusRenderTarget)rt.Opaque; grt.Dispose(); } public RenderTarget CreateRenderTarget(int w, int h) { - var gtex = new GDIPlusTexture + GDIPlusTexture gtex = new() { SDBitmap = new(w, h, PixelFormat.Format32bppArgb) }; - var tex = new Texture2d(this, gtex, w, h); + Texture2d tex = new(this, gtex, w, h); - var grt = new GDIPlusRenderTarget(() => BufferedGraphicsContext); - var rt = new RenderTarget(this, grt, tex); + GDIPlusRenderTarget grt = new(() => BufferedGraphicsContext); + RenderTarget rt = new(this, grt, tex); grt.Target = rt; return rt; } @@ -260,7 +237,7 @@ public void BindRenderTarget(RenderTarget rt) } else { - var gtex = (GDIPlusTexture)rt.Texture2d.Opaque; + GDIPlusTexture gtex = (GDIPlusTexture)rt.Texture2d.Opaque; CurrentRenderTarget = (GDIPlusRenderTarget)rt.Opaque; _currOffscreenGraphics = SDGraphics.FromImage(gtex.SDBitmap); } @@ -281,10 +258,7 @@ public GDIPlusRenderTarget CreateControlRenderTarget(Func<(SDGraphics Graphics, private SDGraphics _currOffscreenGraphics; - public SDGraphics GetCurrentGraphics() - { - return _currOffscreenGraphics ?? CurrentRenderTarget.BufferedGraphics.Graphics; - } + public SDGraphics GetCurrentGraphics() => _currOffscreenGraphics ?? CurrentRenderTarget.BufferedGraphics.Graphics; public GDIPlusRenderTarget CurrentRenderTarget; diff --git a/src/BizHawk.Bizware.Graphics/OpenGL/IGL_OpenGL.cs b/src/BizHawk.Bizware.Graphics/OpenGL/IGL_OpenGL.cs index c94e48e8dc3..0b199620531 100644 --- a/src/BizHawk.Bizware.Graphics/OpenGL/IGL_OpenGL.cs +++ b/src/BizHawk.Bizware.Graphics/OpenGL/IGL_OpenGL.cs @@ -64,10 +64,7 @@ public void EndScene() { } - public void Dispose() - { - GL.Dispose(); - } + public void Dispose() => GL.Dispose(); public void ClearColor(Color color) { @@ -75,20 +72,11 @@ public void ClearColor(Color color) GL.Clear(ClearBufferMask.ColorBufferBit); } - public void FreeTexture(Texture2d tex) - { - GL.DeleteTexture((uint)tex.Opaque); - } + public void FreeTexture(Texture2d tex) => GL.DeleteTexture((uint)tex.Opaque); - public BizShader CreateFragmentShader(string source, string entry, bool required) - { - return CreateShader(ShaderType.FragmentShader, source, required); - } + public BizShader CreateFragmentShader(string source, string entry, bool required) => CreateShader(ShaderType.FragmentShader, source, required); - public BizShader CreateVertexShader(string source, string entry, bool required) - { - return CreateShader(ShaderType.VertexShader, source, required); - } + public BizShader CreateVertexShader(string source, string entry, bool required) => CreateShader(ShaderType.VertexShader, source, required); public void EnableBlending() { @@ -121,7 +109,7 @@ public Pipeline CreatePipeline(VertexLayout vertexLayout, BizShader vertexShader // if the shaders aren't available, the pipeline isn't either if (!vertexShader.Available || !fragmentShader.Available) { - var errors = $"Vertex Shader:\r\n {vertexShader.Errors} \r\n-------\r\nFragment Shader:\r\n{fragmentShader.Errors}"; + string errors = $"Vertex Shader:\r\n {vertexShader.Errors} \r\n-------\r\nFragment Shader:\r\n{fragmentShader.Errors}"; if (required) { throw new InvalidOperationException($"Couldn't build required GL pipeline:\r\n{errors}"); @@ -130,20 +118,20 @@ public Pipeline CreatePipeline(VertexLayout vertexLayout, BizShader vertexShader return new(this, null, false, null, null, null) { Errors = errors }; } - var success = true; + bool success = true; - var vsw = (ShaderWrapper)vertexShader.Opaque; - var fsw = (ShaderWrapper)fragmentShader.Opaque; + ShaderWrapper vsw = (ShaderWrapper)vertexShader.Opaque; + ShaderWrapper fsw = (ShaderWrapper)fragmentShader.Opaque; - var pid = GL.CreateProgram(); + uint pid = GL.CreateProgram(); GL.AttachShader(pid, vsw.sid); GL.AttachShader(pid, fsw.sid); _ = GL.GetError(); GL.LinkProgram(pid); - var errcode = (ErrorCode)GL.GetError(); - var resultLog = GL.GetProgramInfoLog(pid); + ErrorCode errcode = (ErrorCode)GL.GetError(); + string resultLog = GL.GetProgramInfoLog(pid); if (errcode != ErrorCode.NoError) { @@ -155,7 +143,7 @@ public Pipeline CreatePipeline(VertexLayout vertexLayout, BizShader vertexShader success = false; } - GL.GetProgram(pid, GLEnum.LinkStatus, out var linkStatus); + GL.GetProgram(pid, GLEnum.LinkStatus, out int linkStatus); if (linkStatus == 0) { if (required) @@ -206,16 +194,16 @@ public Pipeline CreatePipeline(VertexLayout vertexLayout, BizShader vertexShader #endif // get all the uniforms - var uniforms = new List(); - GL.GetProgram(pid, GLEnum.ActiveUniforms, out var nUniforms); - var samplers = new List(); + List uniforms = new(); + GL.GetProgram(pid, GLEnum.ActiveUniforms, out int nUniforms); + List samplers = new(); for (uint i = 0; i < nUniforms; i++) { GL.GetActiveUniform(pid, i, 1024, out _, out _, out UniformType type, out string name); - var loc = GL.GetUniformLocation(pid, name); + int loc = GL.GetUniformLocation(pid, name); - var ui = new UniformInfo { Name = name, Opaque = loc }; + UniformInfo ui = new() { Name = name, Opaque = loc }; if (type == UniformType.Sampler2D) { @@ -234,7 +222,7 @@ public Pipeline CreatePipeline(VertexLayout vertexLayout, BizShader vertexShader if (!vertexShader.Available) success = false; if (!fragmentShader.Available) success = false; - var pw = new PipelineWrapper { pid = pid, VertexShader = vertexShader, FragmentShader = fragmentShader, SamplerLocs = samplers }; + PipelineWrapper pw = new() { pid = pid, VertexShader = vertexShader, FragmentShader = fragmentShader, SamplerLocs = samplers }; return new(this, pw, success, vertexLayout, uniforms, memo); } @@ -255,7 +243,7 @@ public void FreePipeline(Pipeline pipeline) public void Internal_FreeShader(BizShader shader) { - var sw = (ShaderWrapper)shader.Opaque; + ShaderWrapper sw = (ShaderWrapper)shader.Opaque; GL.DeleteShader(sw.sid); } @@ -275,11 +263,11 @@ public void BindPipeline(Pipeline pipeline) throw new InvalidOperationException("Attempt to bind unavailable pipeline"); } - var pw = (PipelineWrapper)pipeline.Opaque; + PipelineWrapper pw = (PipelineWrapper)pipeline.Opaque; GL.UseProgram(pw.pid); // this is dumb and confusing, but we have to bind physical sampler numbers to sampler variables. - for (var i = 0; i < pw.SamplerLocs.Count; i++) + for (int i = 0; i < pw.SamplerLocs.Count; i++) { GL.Uniform1(pw.SamplerLocs[i], i); } @@ -294,7 +282,7 @@ private class VertexLayoutWrapper public VertexLayout CreateVertexLayout() { - var vlw = new VertexLayoutWrapper() + VertexLayoutWrapper vlw = new() { vao = GL.GenVertexArray(), vbo = GL.GenBuffer(), @@ -306,15 +294,12 @@ public VertexLayout CreateVertexLayout() public void Internal_FreeVertexLayout(VertexLayout vl) { - var vlw = (VertexLayoutWrapper)vl.Opaque; + VertexLayoutWrapper vlw = (VertexLayoutWrapper)vl.Opaque; GL.DeleteVertexArray(vlw.vao); GL.DeleteBuffer(vlw.vbo); } - private void BindTexture2d(Texture2d tex) - { - GL.BindTexture(TextureTarget.Texture2D, (uint)tex.Opaque); - } + private void BindTexture2d(Texture2d tex) => GL.BindTexture(TextureTarget.Texture2D, (uint)tex.Opaque); public void SetTextureWrapMode(Texture2d tex, bool clamp) { @@ -338,7 +323,7 @@ private void LegacyBindArrayData(VertexLayout vertexLayout, IntPtr pData) GL.DisableClientState(EnableCap.VertexArray); GL.DisableClientState(EnableCap.ColorArray); - for (var i = 1; i >= 0; i--) + for (int i = 1; i >= 0; i--) { GL.ClientActiveTexture(TextureUnit.Texture0 + i); GL.DisableClientState(EnableCap.TextureCoordArray); @@ -393,16 +378,16 @@ public void Draw(IntPtr data, int count) return; } - var vlw = (VertexLayoutWrapper)vertexLayout.Opaque; + VertexLayoutWrapper vlw = (VertexLayoutWrapper)vertexLayout.Opaque; GL.BindVertexArray(vlw.vao); GL.BindBuffer(GLEnum.ArrayBuffer, vlw.vbo); - var stride = vertexLayout.Items[0].Stride; + int stride = vertexLayout.Items[0].Stride; Debug.Assert(vertexLayout.Items.All(i => i.Value.Stride == stride)); unsafe { - var vertexes = new ReadOnlySpan(data.ToPointer(), count * stride); + ReadOnlySpan vertexes = new(data.ToPointer(), count * stride); // BufferData reallocs and BufferSubData doesn't, so only use the former if size changes if (vertexes.Length != vlw.bufferLen) @@ -441,15 +426,9 @@ public void Draw(IntPtr data, int count) GL.BindVertexArray(0); } - public void SetPipelineUniform(PipelineUniform uniform, bool value) - { - GL.Uniform1((int)uniform.Sole.Opaque, value ? 1 : 0); - } + public void SetPipelineUniform(PipelineUniform uniform, bool value) => GL.Uniform1((int)uniform.Sole.Opaque, value ? 1 : 0); - public unsafe void SetPipelineUniformMatrix(PipelineUniform uniform, Matrix4x4 mat, bool transpose) - { - GL.UniformMatrix4((int)uniform.Sole.Opaque, 1, transpose, (float*)&mat); - } + public unsafe void SetPipelineUniformMatrix(PipelineUniform uniform, Matrix4x4 mat, bool transpose) => GL.UniformMatrix4((int)uniform.Sole.Opaque, 1, transpose, (float*)&mat); public unsafe void SetPipelineUniformMatrix(PipelineUniform uniform, ref Matrix4x4 mat, bool transpose) { @@ -459,15 +438,9 @@ public unsafe void SetPipelineUniformMatrix(PipelineUniform uniform, ref Matrix4 } } - public void SetPipelineUniform(PipelineUniform uniform, Vector4 value) - { - GL.Uniform4((int)uniform.Sole.Opaque, value.X, value.Y, value.Z, value.W); - } + public void SetPipelineUniform(PipelineUniform uniform, Vector4 value) => GL.Uniform4((int)uniform.Sole.Opaque, value.X, value.Y, value.Z, value.W); - public void SetPipelineUniform(PipelineUniform uniform, Vector2 value) - { - GL.Uniform2((int)uniform.Sole.Opaque, value.X, value.Y); - } + public void SetPipelineUniform(PipelineUniform uniform, Vector2 value) => GL.Uniform2((int)uniform.Sole.Opaque, value.X, value.Y); public void SetPipelineUniform(PipelineUniform uniform, float value) { @@ -489,7 +462,7 @@ public unsafe void SetPipelineUniform(PipelineUniform uniform, Vector4[] values) public void SetPipelineUniformSampler(PipelineUniform uniform, Texture2d tex) { - var n = (int)uniform.Sole.Opaque >> 24; + int n = (int)uniform.Sole.Opaque >> 24; // set the sampler index into the uniform first GL.ActiveTexture(TextureUnit.Texture0 + n); @@ -512,26 +485,23 @@ public void SetMagFilter(Texture2d texture, BizTextureMagFilter magFilter) public Texture2d LoadTexture(Bitmap bitmap) { - using var bmp = new BitmapBuffer(bitmap, new()); + using BitmapBuffer bmp = new(bitmap, new()); return LoadTexture(bmp); } public Texture2d LoadTexture(Stream stream) { - using var bmp = new BitmapBuffer(stream, new()); + using BitmapBuffer bmp = new(stream, new()); return LoadTexture(bmp); } public Texture2d CreateTexture(int width, int height) { - var id = GL.GenTexture(); + uint id = GL.GenTexture(); return new(this, id, width, height); } - public Texture2d WrapGLTexture2d(IntPtr glTexId, int width, int height) - { - return new(this, (uint)glTexId.ToInt32(), width, height) { IsUpsideDown = true }; - } + public Texture2d WrapGLTexture2d(IntPtr glTexId, int width, int height) => new(this, (uint)glTexId.ToInt32(), width, height) { IsUpsideDown = true }; public unsafe void LoadTextureData(Texture2d tex, BitmapBuffer bmp) { @@ -557,8 +527,8 @@ public void FreeRenderTarget(RenderTarget rt) public unsafe RenderTarget CreateRenderTarget(int w, int h) { // create a texture for it - var texId = GL.GenTexture(); - var tex = new Texture2d(this, texId, w, h); + uint texId = GL.GenTexture(); + Texture2d tex = new(this, texId, w, h); GL.BindTexture(TextureTarget.Texture2D, texId); GL.TexImage2D(TextureTarget.Texture2D, 0, InternalFormat.Rgba8, (uint)w, (uint)h, 0, PixelFormat.Bgra, PixelType.UnsignedByte, null); @@ -566,7 +536,7 @@ public unsafe RenderTarget CreateRenderTarget(int w, int h) tex.SetMinFilter(BizTextureMinFilter.Nearest); // create the FBO - var fbId = GL.GenFramebuffer(); + uint fbId = GL.GenFramebuffer(); GL.BindFramebuffer(FramebufferTarget.Framebuffer, fbId); // bind the tex to the FBO @@ -602,7 +572,7 @@ public void BindRenderTarget(RenderTarget rt) public unsafe Texture2d LoadTexture(BitmapBuffer bmp) { Texture2d ret; - var id = GL.GenTexture(); + uint id = GL.GenTexture(); try { ret = new(this, id, bmp.Width, bmp.Height); @@ -627,7 +597,7 @@ public unsafe BitmapBuffer ResolveTexture2d(Texture2d tex) { // note - this is dangerous since it changes the bound texture. could we save it? BindTexture2d(tex); - var bb = new BitmapBuffer(tex.IntWidth, tex.IntHeight); + BitmapBuffer bb = new(tex.IntWidth, tex.IntHeight); var bmpdata = bb.LockBits(); GL.GetTexImage(TextureTarget.Texture2D, 0, PixelFormat.Bgra, PixelType.UnsignedByte, bmpdata.Scan0.ToPointer()); bb.UnlockBits(bmpdata); @@ -636,19 +606,13 @@ public unsafe BitmapBuffer ResolveTexture2d(Texture2d tex) public Texture2d LoadTexture(string path) { - using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); + using FileStream fs = new(path, FileMode.Open, FileAccess.Read, FileShare.Read); return LoadTexture(fs); } - public Matrix4x4 CreateGuiProjectionMatrix(int w, int h) - { - return CreateGuiProjectionMatrix(new(w, h)); - } + public Matrix4x4 CreateGuiProjectionMatrix(int w, int h) => CreateGuiProjectionMatrix(new(w, h)); - public Matrix4x4 CreateGuiViewMatrix(int w, int h, bool autoflip) - { - return CreateGuiViewMatrix(new(w, h), autoflip); - } + public Matrix4x4 CreateGuiViewMatrix(int w, int h, bool autoflip) => CreateGuiViewMatrix(new(w, h), autoflip); public Matrix4x4 CreateGuiProjectionMatrix(Size dims) { @@ -680,24 +644,18 @@ public void SetViewport(int x, int y, int width, int height) // BUT ALSO: new specifications.. viewport+scissor make sense together } - public void SetViewport(int width, int height) - { - SetViewport(0, 0, width, height); - } + public void SetViewport(int width, int height) => SetViewport(0, 0, width, height); - public void SetViewport(Size size) - { - SetViewport(size.Width, size.Height); - } + public void SetViewport(Size size) => SetViewport(size.Width, size.Height); private BizShader CreateShader(ShaderType type, string source, bool required) { - var sw = new ShaderWrapper(); - var info = string.Empty; + ShaderWrapper sw = new(); + string info = string.Empty; _ = GL.GetError(); - var sid = GL.CreateShader(type); - var ok = CompileShaderSimple(sid, source, required); + uint sid = GL.CreateShader(type); + bool ok = CompileShaderSimple(sid, source, required); if (!ok) { GL.GetShaderInfoLog(sid, out info); @@ -705,7 +663,7 @@ private BizShader CreateShader(ShaderType type, string source, bool required) sid = 0; } - var ret = new BizShader(this, sw, ok) + BizShader ret = new(this, sw, ok) { Errors = info }; @@ -717,9 +675,9 @@ private BizShader CreateShader(ShaderType type, string source, bool required) private bool CompileShaderSimple(uint sid, string source, bool required) { - var success = true; + bool success = true; - var errcode = (ErrorCode)GL.GetError(); + ErrorCode errcode = (ErrorCode)GL.GetError(); if (errcode != ErrorCode.NoError) { if (required) @@ -746,10 +704,10 @@ private bool CompileShaderSimple(uint sid, string source, bool required) GL.CompileShader(sid); errcode = (ErrorCode)GL.GetError(); - var resultLog = GL.GetShaderInfoLog(sid); + string resultLog = GL.GetShaderInfoLog(sid); if (errcode != ErrorCode.NoError) { - var message = $"Error compiling shader ({nameof(GL.CompileShader)}) {errcode}\r\n\r\n{resultLog}"; + string message = $"Error compiling shader ({nameof(GL.CompileShader)}) {errcode}\r\n\r\n{resultLog}"; if (required) { throw new InvalidOperationException(message); @@ -759,7 +717,7 @@ private bool CompileShaderSimple(uint sid, string source, bool required) success = false; } - GL.GetShader(sid, ShaderParameterName.CompileStatus, out var n); + GL.GetShader(sid, ShaderParameterName.CompileStatus, out int n); if (n == 0) { diff --git a/src/BizHawk.Bizware.Graphics/OpenGL/OpenGLVersion.cs b/src/BizHawk.Bizware.Graphics/OpenGL/OpenGLVersion.cs index e1c0114a14d..19371d8bb3e 100644 --- a/src/BizHawk.Bizware.Graphics/OpenGL/OpenGLVersion.cs +++ b/src/BizHawk.Bizware.Graphics/OpenGL/OpenGLVersion.cs @@ -23,10 +23,7 @@ public SavedOpenGLContext() _glContext = SDL_GL_GetCurrentContext(); } - public void Dispose() - { - _ = SDL_GL_MakeCurrent(_sdlWindow, _glContext); - } + public void Dispose() => _ = SDL_GL_MakeCurrent(_sdlWindow, _glContext); } private static readonly IDictionary _glSupport = new Dictionary(); @@ -42,11 +39,11 @@ private static bool CheckVersion(int requestedMajor, int requestedMinor) { using (new SDL2OpenGLContext(requestedMajor, requestedMinor, true, false)) { - using var gl = GL.GetApi(SDL2OpenGLContext.GetGLProcAddress); - var versionString = gl.GetStringS(StringName.Version); - var versionParts = versionString!.Split('.'); - var major = int.Parse(versionParts[0]); - var minor = int.Parse(versionParts[1][0].ToString()); + using GL gl = GL.GetApi(SDL2OpenGLContext.GetGLProcAddress); + string versionString = gl.GetStringS(StringName.Version); + string[] versionParts = versionString!.Split('.'); + int major = int.Parse(versionParts[0]); + int minor = int.Parse(versionParts[1][0].ToString()); return PackGLVersion(major, minor) >= PackGLVersion(requestedMajor, requestedMinor); } } diff --git a/src/BizHawk.Bizware.Graphics/OpenGL/SDL2OpenGLContext.cs b/src/BizHawk.Bizware.Graphics/OpenGL/SDL2OpenGLContext.cs index a81c39872be..bf04cd7eac1 100644 --- a/src/BizHawk.Bizware.Graphics/OpenGL/SDL2OpenGLContext.cs +++ b/src/BizHawk.Bizware.Graphics/OpenGL/SDL2OpenGLContext.cs @@ -133,17 +133,13 @@ public void Dispose() public bool IsCurrent => SDL_GL_GetCurrentContext() == _glContext; - public void MakeContextCurrent() - { + public void MakeContextCurrent() => // no-op if already current _ = SDL_GL_MakeCurrent(_sdlWindow, _glContext); - } - public static void MakeNoneCurrent() - { + public static void MakeNoneCurrent() => // no-op if nothing is current _ = SDL_GL_MakeCurrent(IntPtr.Zero, IntPtr.Zero); - } public static IntPtr GetGLProcAddress(string proc) => SDL_GL_GetProcAddress(proc); diff --git a/src/BizHawk.Bizware.Graphics/Renderers/GDIPlusGuiRenderer.cs b/src/BizHawk.Bizware.Graphics/Renderers/GDIPlusGuiRenderer.cs index 25d0fa66e25..38925efa2c4 100644 --- a/src/BizHawk.Bizware.Graphics/Renderers/GDIPlusGuiRenderer.cs +++ b/src/BizHawk.Bizware.Graphics/Renderers/GDIPlusGuiRenderer.cs @@ -27,10 +27,7 @@ public GDIPlusGuiRenderer(IGL_GDIPlus gdi) new(1.0f, 1.0f, 1.0f, 1.0f) }; - public void SetCornerColor(int which, Vector4 color) - { - CornerColors[which] = color; - } + public void SetCornerColor(int which, Vector4 color) => CornerColors[which] = color; /// does not have exactly 4 elements public void SetCornerColors(Vector4[] colors) @@ -42,16 +39,13 @@ public void SetCornerColors(Vector4[] colors) throw new ArgumentException("array must be size 4", nameof(colors)); } - for (var i = 0; i < 4; i++) + for (int i = 0; i < 4; i++) { CornerColors[i] = colors[i]; } } - public void Dispose() - { - CurrentImageAttributes?.Dispose(); - } + public void Dispose() => CurrentImageAttributes?.Dispose(); public void SetPipeline(Pipeline pipeline) { @@ -61,10 +55,7 @@ public void SetDefaultPipeline() { } - public void SetModulateColorWhite() - { - SetModulateColor(Color.White); - } + public void SetModulateColorWhite() => SetModulateColor(Color.White); private ImageAttributes CurrentImageAttributes; @@ -77,10 +68,10 @@ public void SetModulateColor(Color color) return; } - var r = color.R / 255.0f; - var g = color.G / 255.0f; - var b = color.B / 255.0f; - var a = color.A / 255.0f; + float r = color.R / 255.0f; + float g = color.G / 255.0f; + float b = color.B / 255.0f; + float a = color.A / 255.0f; float[][] colorMatrixElements = { @@ -91,19 +82,13 @@ public void SetModulateColor(Color color) new float[] { 0, 0, 0, 0, 1 }, }; - var colorMatrix = new ColorMatrix(colorMatrixElements); + ColorMatrix colorMatrix = new(colorMatrixElements); CurrentImageAttributes.SetColorMatrix(colorMatrix,ColorMatrixFlag.Default, ColorAdjustType.Bitmap); } - public void EnableBlending() - { - Owner.EnableBlending(); - } + public void EnableBlending() => Owner.EnableBlending(); - public void DisableBlending() - { - Owner.DisableBlending(); - } + public void DisableBlending() => Owner.DisableBlending(); private MatrixStack _Projection, _Modelview; @@ -127,10 +112,7 @@ public MatrixStack Modelview } } - public void Begin(Size size) - { - Begin(size.Width, size.Height); - } + public void Begin(Size size) => Begin(size.Width, size.Height); public void Begin(int width, int height) { @@ -176,16 +158,16 @@ public void RectFill(float x, float y, float w, float h) public void DrawSubrect(Texture2d tex, float x, float y, float w, float h, float u0, float v0, float u1, float v1) { - var gtex = (GDIPlusTexture)tex.Opaque; + GDIPlusTexture gtex = (GDIPlusTexture)tex.Opaque; var g = _gdi.GetCurrentGraphics(); PrepDraw(g, tex); SetupMatrix(g); - var x0 = u0 * tex.Width; - var y0 = v0 * tex.Height; - var x1 = u1 * tex.Width; - var y1 = v1 * tex.Height; + float x0 = u0 * tex.Width; + float y0 = v0 * tex.Height; + float x1 = u1 * tex.Width; + float y1 = v1 * tex.Height; PointF[] destPoints = { @@ -198,22 +180,19 @@ public void DrawSubrect(Texture2d tex, float x, float y, float w, float h, float g.Transform = new(); // .Reset() doesnt work? } - public void Draw(Art art) { DrawInternal(art, 0, 0, art.Width, art.Height, false, false); } - public void Draw(Art art, float x, float y) { DrawInternal(art, x, y, art.Width, art.Height, false, false); } - public void Draw(Art art, float x, float y, float width, float height) { DrawInternal(art, x, y, width, height, false, false); } - public void Draw(Art art, Vector2 pos) { DrawInternal(art, pos.X, pos.Y, art.Width, art.Height, false, false); } - public void Draw(Texture2d tex) { DrawInternal(tex, 0, 0, tex.Width, tex.Height); } - public void Draw(Texture2d tex, float x, float y) { DrawInternal(tex, x, y, tex.Width, tex.Height); } - public void DrawFlipped(Art art, bool xflip, bool yflip) { DrawInternal(art, 0, 0, art.Width, art.Height, xflip, yflip); } + public void Draw(Art art) => DrawInternal(art, 0, 0, art.Width, art.Height, false, false); + public void Draw(Art art, float x, float y) => DrawInternal(art, x, y, art.Width, art.Height, false, false); + public void Draw(Art art, float x, float y, float width, float height) => DrawInternal(art, x, y, width, height, false, false); + public void Draw(Art art, Vector2 pos) => DrawInternal(art, pos.X, pos.Y, art.Width, art.Height, false, false); + public void Draw(Texture2d tex) => DrawInternal(tex, 0, 0, tex.Width, tex.Height); + public void Draw(Texture2d tex, float x, float y) => DrawInternal(tex, x, y, tex.Width, tex.Height); + public void DrawFlipped(Art art, bool xflip, bool yflip) => DrawInternal(art, 0, 0, art.Width, art.Height, xflip, yflip); - public void Draw(Texture2d art, float x, float y, float width, float height) - { - DrawInternal(art, x, y, width, height); - } + public void Draw(Texture2d art, float x, float y, float width, float height) => DrawInternal(art, x, y, width, height); private static void PrepDraw(SDGraphics g, Texture2d tex) { - var tw = (GDIPlusTexture)tex.Opaque; + GDIPlusTexture tw = (GDIPlusTexture)tex.Opaque; // TODO - we can support bicubic for the final presentation... if ((int)tw.MagFilter != (int)tw.MinFilter) @@ -237,15 +216,9 @@ private void SetupMatrix(SDGraphics g) g.Transform = new(mat.M11, mat.M12, mat.M21, mat.M22, mat.M41, mat.M42); } - private void DrawInternal(Art art, float x, float y, float w, float h) - { - DrawInternal(art.BaseTexture, x, y, w, h, art.u0, art.v0, art.u1, art.v1); - } + private void DrawInternal(Art art, float x, float y, float w, float h) => DrawInternal(art.BaseTexture, x, y, w, h, art.u0, art.v0, art.u1, art.v1); - private void DrawInternal(Texture2d tex, float x, float y, float w, float h) - { - DrawInternal(tex, x, y, w, h, 0, 0, 1, 1); - } + private void DrawInternal(Texture2d tex, float x, float y, float w, float h) => DrawInternal(tex, x, y, w, h, 0, 0, 1, 1); private void DrawInternal(Texture2d tex, float x, float y, float w, float h, float u0, float v0, float u1, float v1) { @@ -261,14 +234,14 @@ private void DrawInternal(Texture2d tex, float x, float y, float w, float h, flo new(x, y+h), }; - var sx = tex.Width * u0; - var sy = tex.Height * v0; - var sx2 = tex.Width * u1; - var sy2 = tex.Height * v1; - var sw = sx2 - sx; - var sh = sy2 - sy; + float sx = tex.Width * u0; + float sy = tex.Height * v0; + float sx2 = tex.Width * u1; + float sy2 = tex.Height * v1; + float sw = sx2 - sx; + float sh = sy2 - sy; - var gtex = (GDIPlusTexture)tex.Opaque; + GDIPlusTexture gtex = (GDIPlusTexture)tex.Opaque; g.PixelOffsetMode = PixelOffsetMode.Half; g.DrawImage(gtex.SDBitmap, destPoints, new(sx, sy, sw, sh), GraphicsUnit.Pixel, CurrentImageAttributes); g.Transform = new(); // .Reset() doesn't work ? ? diff --git a/src/BizHawk.Bizware.Graphics/Renderers/GuiRenderer.cs b/src/BizHawk.Bizware.Graphics/Renderers/GuiRenderer.cs index 0d5df3a2bf3..fdb169185c2 100644 --- a/src/BizHawk.Bizware.Graphics/Renderers/GuiRenderer.cs +++ b/src/BizHawk.Bizware.Graphics/Renderers/GuiRenderer.cs @@ -66,7 +66,7 @@ public void SetCornerColors(Vector4[] colors) { Flush(); //don't really need to flush with current implementation. we might as well roll modulate color into it too. if (colors.Length != 4) throw new ArgumentException("array must be size 4", nameof(colors)); - for (var i = 0; i < 4; i++) + for (int i = 0; i < 4; i++) { CornerColors[i] = colors[i]; } @@ -92,15 +92,9 @@ public void SetPipeline(Pipeline pipeline) // save the modulate color? user beware, I guess, for now. } - public void SetDefaultPipeline() - { - SetPipeline(DefaultPipeline); - } + public void SetDefaultPipeline() => SetPipeline(DefaultPipeline); - public void SetModulateColorWhite() - { - SetModulateColor(Color.White); - } + public void SetModulateColorWhite() => SetModulateColor(Color.White); public void SetModulateColor(Color color) { @@ -140,10 +134,7 @@ public MatrixStack Modelview } } - public void Begin(Size size) - { - Begin(size.Width, size.Height); - } + public void Begin(Size size) => Begin(size.Width, size.Height); public void Begin(int width, int height) { @@ -201,54 +192,27 @@ public void RectFill(float x, float y, float w, float h) } - public void DrawSubrect(Texture2d tex, float x, float y, float w, float h, float u0, float v0, float u1, float v1) - { - DrawSubrectInternal(tex, x, y, w, h, u0, v0, u1, v1); - } + public void DrawSubrect(Texture2d tex, float x, float y, float w, float h, float u0, float v0, float u1, float v1) => DrawSubrectInternal(tex, x, y, w, h, u0, v0, u1, v1); - public void Draw(Art art) - { - DrawInternal(art, 0, 0, art.Width, art.Height, false, false); - } + public void Draw(Art art) => DrawInternal(art, 0, 0, art.Width, art.Height, false, false); - public void Draw(Art art, float x, float y) - { - DrawInternal(art, x, y, art.Width, art.Height, false, false); - } + public void Draw(Art art, float x, float y) => DrawInternal(art, x, y, art.Width, art.Height, false, false); - public void Draw(Art art, float x, float y, float width, float height) - { - DrawInternal(art, x, y, width, height, false, false); - } + public void Draw(Art art, float x, float y, float width, float height) => DrawInternal(art, x, y, width, height, false, false); - public void Draw(Art art, Vector2 pos) - { - DrawInternal(art, pos.X, pos.Y, art.Width, art.Height, false, false); - } + public void Draw(Art art, Vector2 pos) => DrawInternal(art, pos.X, pos.Y, art.Width, art.Height, false, false); - public void Draw(Texture2d tex) - { - DrawInternal(tex, 0, 0, tex.Width, tex.Height); - } + public void Draw(Texture2d tex) => DrawInternal(tex, 0, 0, tex.Width, tex.Height); - public void Draw(Texture2d tex, float x, float y) - { - DrawInternal(tex, x, y, tex.Width, tex.Height); - } + public void Draw(Texture2d tex, float x, float y) => DrawInternal(tex, x, y, tex.Width, tex.Height); - public void DrawFlipped(Art art, bool xflip, bool yflip) - { - DrawInternal(art, 0, 0, art.Width, art.Height, xflip, yflip); - } + public void DrawFlipped(Art art, bool xflip, bool yflip) => DrawInternal(art, 0, 0, art.Width, art.Height, xflip, yflip); - public void Draw(Texture2d art, float x, float y, float width, float height) - { - DrawInternal(art, x, y, width, height); - } + public void Draw(Texture2d art, float x, float y, float width, float height) => DrawInternal(art, x, y, width, height); private void DrawInternal(Texture2d tex, float x, float y, float w, float h) { - var art = new Art((ArtManager)null) + Art art = new((ArtManager)null) { Width = w, Height = h @@ -287,7 +251,7 @@ private unsafe void DrawInternal(Art art, float x, float y, float w, float h, bo v1 = art.v1; } - var data = stackalloc float[32] + float* data = stackalloc float[32] { x, y, u0, v0, CornerColors[0].X, CornerColors[0].Y, CornerColors[0].Z, CornerColors[0].W, @@ -326,7 +290,7 @@ private void PrepDrawSubrectInternal(Texture2d tex) private unsafe void EmitRectangleInternal(float x, float y, float w, float h, float u0, float v0, float u1, float v1) { - var pData = stackalloc float[32]; + float* pData = stackalloc float[32]; pData[0] = x; pData[1] = y; pData[2] = u0; diff --git a/src/BizHawk.Bizware.Input/DirectX/DGamepad.cs b/src/BizHawk.Bizware.Input/DirectX/DGamepad.cs index 29d1d2d21a6..6f0c6090baf 100644 --- a/src/BizHawk.Bizware.Input/DirectX/DGamepad.cs +++ b/src/BizHawk.Bizware.Input/DirectX/DGamepad.cs @@ -49,7 +49,7 @@ public static void Initialize(IntPtr mainFormHandle) } #else // hack due to the above problems - var dict = (Dictionary)typeof(IDirectInputDevice8) + Dictionary dict = (Dictionary)typeof(IDirectInputDevice8) .GetField("_mapNameToObjectFormat", BindingFlags.Instance | BindingFlags.NonPublic)! .GetValue(joystick); @@ -60,7 +60,7 @@ public static void Initialize(IntPtr mainFormHandle) #endif joystick.Acquire(); - var p = new DGamepad(joystick, Devices.Count); + DGamepad p = new(joystick, Devices.Count); Devices.Add(p); } } @@ -151,30 +151,18 @@ public void Update() private static readonly ImmutableArray _axesPropertyInfos = typeof(JoystickState).GetProperties().Where(pi => pi.PropertyType == typeof(int)).ToImmutableArray(); - public IEnumerable<(string AxisID, float Value)> GetAxes() - { - return _axesPropertyInfos.Select(pi => (pi.Name, 10.0f * (int)pi.GetValue(_state))); - } + public IEnumerable<(string AxisID, float Value)> GetAxes() => _axesPropertyInfos.Select(pi => (pi.Name, 10.0f * (int)pi.GetValue(_state))); /// FOR DEBUGGING ONLY - public JoystickState GetInternalState() - { - return _state; - } + public JoystickState GetInternalState() => _state; public int PlayerNumber { get; } public readonly string InputNamePrefix; - public string ButtonName(int index) - { - return _names[index]; - } + public string ButtonName(int index) => _names[index]; - public bool Pressed(int index) - { - return _actions[index](); - } + public bool Pressed(int index) => _actions[index](); public int NumButtons { get; private set; } @@ -248,17 +236,17 @@ private void InitializeCallbacks() // i don't know what the "Slider"s do, so they're omitted for the moment - for (var i = 0; i < _state.Buttons.Length; i++) + for (int i = 0; i < _state.Buttons.Length; i++) { - var j = i; + int j = i; AddItem($"B{i + 1}", () => _state.Buttons[j]); } - for (var i = 0; i < _state.PointOfViewControllers.Length; i++) + for (int i = 0; i < _state.PointOfViewControllers.Length; i++) { - var j = i; + int j = i; AddItem($"POV{i + 1}U", () => { - var t = _state.PointOfViewControllers[j]; + int t = _state.PointOfViewControllers[j]; return 0.RangeTo(4500).Contains(t) || 31500.RangeToExclusive(36000).Contains(t); }); AddItem($"POV{i + 1}D", () => 13500.RangeTo(22500).Contains(_state.PointOfViewControllers[j])); @@ -273,7 +261,7 @@ public void SetVibration(int left, int right) // my first clue that it doesn't work is that LEFT and RIGHT _AREN'T USED_ // I should just look for C++ examples instead of trying to look for SlimDX examples - var parameters = new EffectParameters + EffectParameters parameters = new() { Duration = 0x2710, Gain = 0x2710, @@ -282,7 +270,7 @@ public void SetVibration(int left, int right) TriggerRepeatInterval = 0x2710, Flags = EffectFlags.None }; - parameters.GetAxes(out var temp1, out var temp2); + parameters.GetAxes(out int[] temp1, out int[] temp2); parameters.SetAxes(temp1, temp2); var effect = _joystick.CreateEffect(EffectGuid.ConstantForce, parameters); effect.Start(1); diff --git a/src/BizHawk.Bizware.Input/DirectX/DKeyInput.cs b/src/BizHawk.Bizware.Input/DirectX/DKeyInput.cs index c88a1e8a87c..b82697c66d9 100644 --- a/src/BizHawk.Bizware.Input/DirectX/DKeyInput.cs +++ b/src/BizHawk.Bizware.Input/DirectX/DKeyInput.cs @@ -57,7 +57,7 @@ public static IEnumerable Update(Config config) { if (_keyboard == null || _keyboard.Acquire().Failure || _keyboard.Poll().Failure) return Enumerable.Empty(); - var eventList = new List(); + List eventList = new(); while (true) { try @@ -78,7 +78,7 @@ private static DInputKey MapToRealKeyViaScanCode(DInputKey key) { const uint MAPVK_VSC_TO_VK_EX = 0x03; // DInputKey is a scancode as is - var virtualKey = MapVirtualKey((uint) key, MAPVK_VSC_TO_VK_EX); + uint virtualKey = MapVirtualKey((uint) key, MAPVK_VSC_TO_VK_EX); return VKeyToDKeyMap.GetValueOrDefault(virtualKey, DInputKey.Unknown); } diff --git a/src/BizHawk.Bizware.Input/DirectX/DirectInputAdapter.cs b/src/BizHawk.Bizware.Input/DirectX/DirectInputAdapter.cs index 3a836f34a68..fe9cd2cee35 100644 --- a/src/BizHawk.Bizware.Input/DirectX/DirectInputAdapter.cs +++ b/src/BizHawk.Bizware.Input/DirectX/DirectInputAdapter.cs @@ -55,8 +55,8 @@ public void ProcessHostGamepads(Action handleBu continue; for (int b = 0, n = pad.NumButtons; b < n; b++) handleButton(pad.InputNamePrefix + pad.ButtonName(b), pad.Pressed(b), ClientInputFocus.Pad); foreach (var (axisName, f) in pad.GetAxes()) handleAxis(pad.InputNamePrefix + axisName, (int) f); - var leftStrength = _lastHapticsSnapshot.GetValueOrDefault(pad.InputNamePrefix + "Left"); - var rightStrength = _lastHapticsSnapshot.GetValueOrDefault(pad.InputNamePrefix + "Right"); + int leftStrength = _lastHapticsSnapshot.GetValueOrDefault(pad.InputNamePrefix + "Left"); + int rightStrength = _lastHapticsSnapshot.GetValueOrDefault(pad.InputNamePrefix + "Right"); pad.SetVibration(leftStrength, rightStrength); // values will be 0 if not found } foreach (var pad in DGamepad.EnumerateDevices()) diff --git a/src/BizHawk.Bizware.Input/DirectX/XGamepad.cs b/src/BizHawk.Bizware.Input/DirectX/XGamepad.cs index c6910ed044d..6f0a9d10588 100644 --- a/src/BizHawk.Bizware.Input/DirectX/XGamepad.cs +++ b/src/BizHawk.Bizware.Input/DirectX/XGamepad.cs @@ -144,8 +144,8 @@ public void Update() const float f = 32768 / 10000.0f; //since our whole input framework really only understands whole axes, let's make the triggers look like an axis - var lTrig = g.LeftTrigger / 255.0f * 2 - 1; - var rTrig = g.RightTrigger / 255.0f * 2 - 1; + float lTrig = g.LeftTrigger / 255.0f * 2 - 1; + float rTrig = g.RightTrigger / 255.0f * 2 - 1; lTrig *= 10000; rTrig *= 10000; diff --git a/src/BizHawk.Bizware.Input/IPC/IPCKeyInput.cs b/src/BizHawk.Bizware.Input/IPC/IPCKeyInput.cs index 431ec920851..0590a96ddc9 100644 --- a/src/BizHawk.Bizware.Input/IPC/IPCKeyInput.cs +++ b/src/BizHawk.Bizware.Input/IPC/IPCKeyInput.cs @@ -15,7 +15,7 @@ public static void Initialize() { if (!IPCActive) { - var t = new Thread(IPCThread) { IsBackground = true }; + Thread t = new(IPCThread) { IsBackground = true }; t.Start(); IPCActive = true; } @@ -27,21 +27,21 @@ public static void Initialize() private static void IPCThread() { - var pipeName = $"bizhawk-pid-{Process.GetCurrentProcess().Id}-IPCKeyInput"; + string pipeName = $"bizhawk-pid-{Process.GetCurrentProcess().Id}-IPCKeyInput"; while (true) { - using var pipe = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 1024, 1024); + using NamedPipeServerStream pipe = new(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 1024, 1024); try { pipe.WaitForConnection(); - var br = new BinaryReader(pipe); + BinaryReader br = new(pipe); while (true) { - var e = br.ReadUInt32(); - var pressed = (e & 0x80000000) != 0; + uint e = br.ReadUInt32(); + bool pressed = (e & 0x80000000) != 0; lock (PendingEventList) { PendingEventList.Add(new((DistinctKey)(e & 0x7FFFFFFF), pressed)); diff --git a/src/BizHawk.Bizware.Input/SDL2/SDL2Gamepad.cs b/src/BizHawk.Bizware.Input/SDL2/SDL2Gamepad.cs index c94eb182e4a..81b3212f6eb 100644 --- a/src/BizHawk.Bizware.Input/SDL2/SDL2Gamepad.cs +++ b/src/BizHawk.Bizware.Input/SDL2/SDL2Gamepad.cs @@ -62,10 +62,10 @@ public void Dispose() private static void RefreshIndexes() { - var njoysticks = SDL_NumJoysticks(); - for (var i = 0; i < njoysticks; i++) + int njoysticks = SDL_NumJoysticks(); + for (int i = 0; i < njoysticks; i++) { - var joystickId = SDL_JoystickGetDeviceInstanceID(i); + int joystickId = SDL_JoystickGetDeviceInstanceID(i); if (Gamepads.TryGetValue(joystickId, out var gamepad)) { gamepad.UpdateIndex(i); @@ -75,10 +75,10 @@ private static void RefreshIndexes() public static void AddDevice(int deviceIndex) { - var instanceId = SDL_JoystickGetDeviceInstanceID(deviceIndex); + int instanceId = SDL_JoystickGetDeviceInstanceID(deviceIndex); if (!Gamepads.ContainsKey(instanceId)) { - var gamepad = new SDL2Gamepad(deviceIndex); + SDL2Gamepad gamepad = new(deviceIndex); Gamepads.Add(gamepad.InstanceID, gamepad); } else @@ -183,27 +183,27 @@ public static IEnumerable EnumerateDevices() buttonGetters.Add(("P-", () => SDL_JoystickGetAxis(Opaque, 7) <= dzn)); buttonGetters.Add(("N+", () => SDL_JoystickGetAxis(Opaque, 8) >= dzp)); buttonGetters.Add(("N-", () => SDL_JoystickGetAxis(Opaque, 8) <= dzn)); - var naxes = SDL_JoystickNumAxes(Opaque); - for (var i = 9; i < naxes; i++) + int naxes = SDL_JoystickNumAxes(Opaque); + for (int i = 9; i < naxes; i++) { - var j = i; + int j = i; buttonGetters.Add(($"Axis{j}+", () => SDL_JoystickGetAxis(Opaque, j) >= dzp)); buttonGetters.Add(($"Axis{j}-", () => SDL_JoystickGetAxis(Opaque, j) <= dzn)); } // buttons - var nbuttons = SDL_JoystickNumButtons(Opaque); - for (var i = 0; i < nbuttons; i++) + int nbuttons = SDL_JoystickNumButtons(Opaque); + for (int i = 0; i < nbuttons; i++) { - var j = i; + int j = i; buttonGetters.Add(($"B{i + 1}", () => SDL_JoystickGetButton(Opaque, j) == 1)); } // hats - var nhats = SDL_JoystickNumHats(Opaque); - for (var i = 0; i < nhats; i++) + int nhats = SDL_JoystickNumHats(Opaque); + for (int i = 0; i < nhats; i++) { - var j = i; + int j = i; buttonGetters.Add(($"POV{j}U", () => (SDL_JoystickGetHat(Opaque, j) & SDL_HAT_UP) == SDL_HAT_UP)); buttonGetters.Add(($"POV{j}D", () => (SDL_JoystickGetHat(Opaque, j) & SDL_HAT_DOWN) == SDL_HAT_DOWN)); buttonGetters.Add(($"POV{j}L", () => (SDL_JoystickGetHat(Opaque, j) & SDL_HAT_LEFT) == SDL_HAT_LEFT)); @@ -282,10 +282,10 @@ private SDL2Gamepad(int index) ("N", Conv(SDL_JoystickGetAxis(Opaque, 8))), }; - var naxes = SDL_JoystickNumAxes(Opaque); - for (var i = 9; i < naxes; i++) + int naxes = SDL_JoystickNumAxes(Opaque); + for (int i = 9; i < naxes; i++) { - var j = i; + int j = i; values.Add(($"Axis{j}", Conv(SDL_JoystickGetAxis(Opaque, j)))); } diff --git a/src/BizHawk.Bizware.Input/SDL2/SDL2InputAdapter.cs b/src/BizHawk.Bizware.Input/SDL2/SDL2InputAdapter.cs index bad8f912eb0..9a0831429c0 100644 --- a/src/BizHawk.Bizware.Input/SDL2/SDL2InputAdapter.cs +++ b/src/BizHawk.Bizware.Input/SDL2/SDL2InputAdapter.cs @@ -38,7 +38,7 @@ static SDL2InputAdapter() private static void DoSDLEventLoop() { - var e = new SDL_Event[1]; + SDL_Event[] e = new SDL_Event[1]; // this loop somewhat models SDL_PollEvent while (true) { @@ -155,9 +155,9 @@ public override void ProcessHostGamepads(Action foreach (var pad in SDL2Gamepad.EnumerateDevices()) { - foreach (var but in pad.ButtonGetters) + foreach (var (ButtonName, GetIsPressed) in pad.ButtonGetters) { - handleButton(pad.InputNamePrefix + but.ButtonName, but.GetIsPressed(), ClientInputFocus.Pad); + handleButton(pad.InputNamePrefix + ButtonName, GetIsPressed(), ClientInputFocus.Pad); } foreach (var (axisID, f) in pad.GetAxes()) @@ -167,8 +167,8 @@ public override void ProcessHostGamepads(Action if (pad.HasRumble) { - var leftStrength = _lastHapticsSnapshot.GetValueOrDefault(pad.InputNamePrefix + "Left"); - var rightStrength = _lastHapticsSnapshot.GetValueOrDefault(pad.InputNamePrefix + "Right"); + int leftStrength = _lastHapticsSnapshot.GetValueOrDefault(pad.InputNamePrefix + "Left"); + int rightStrength = _lastHapticsSnapshot.GetValueOrDefault(pad.InputNamePrefix + "Right"); pad.SetVibration(leftStrength, rightStrength); } } diff --git a/src/BizHawk.Bizware.Input/X11/X11KeyInput.cs b/src/BizHawk.Bizware.Input/X11/X11KeyInput.cs index 7e8000d8503..ba06f609de9 100644 --- a/src/BizHawk.Bizware.Input/X11/X11KeyInput.cs +++ b/src/BizHawk.Bizware.Input/X11/X11KeyInput.cs @@ -37,7 +37,7 @@ public static void Initialize() { // check if we can use XKb int major = 1, minor = 0; - var supportsXkb = XkbQueryExtension(Display, out _, out _, out _, ref major, ref minor); + bool supportsXkb = XkbQueryExtension(Display, out _, out _, out _, ref major, ref minor); if (supportsXkb) { @@ -66,7 +66,7 @@ public static unsafe IEnumerable Update() { lock (_syncObject) { - var keys = stackalloc byte[32]; + byte* keys = stackalloc byte[32]; using (new XLock(Display)) { @@ -74,10 +74,10 @@ public static unsafe IEnumerable Update() _ = XQueryKeymap(Display, keys); } - var eventList = new List(); - for (var keycode = 0; keycode < 256; keycode++) + List eventList = new(); + for (int keycode = 0; keycode < 256; keycode++) { - var keystate = (keys[keycode >> 3] >> (keycode & 0x07) & 0x01) != 0; + bool keystate = (keys[keycode >> 3] >> (keycode & 0x07) & 0x01) != 0; if (LastKeyState[keycode] != keystate) { @@ -92,7 +92,7 @@ public static unsafe IEnumerable Update() private static unsafe void CreateKeyMap(bool supportsXkb) { - for (var i = 0; i < KeyEnumMap.Length; i++) + for (int i = 0; i < KeyEnumMap.Length; i++) { KeyEnumMap[i] = DistinctKey.Unknown; } @@ -106,7 +106,7 @@ private static unsafe void CreateKeyMap(bool supportsXkb) for (int i = keyboard->min_key_code; i <= keyboard->max_key_code; i++) { - var name = new string(keyboard->names->keys[i].name, 0, 4); + string name = new(keyboard->names->keys[i].name, 0, 4); var key = name switch { "TLDE" => DistinctKey.OemTilde, @@ -166,7 +166,7 @@ private static unsafe void CreateKeyMap(bool supportsXkb) } } - for (var i = 0; i < KeyEnumMap.Length; i++) + for (int i = 0; i < KeyEnumMap.Length; i++) { if (KeyEnumMap[i] == DistinctKey.Unknown) { @@ -201,7 +201,7 @@ private static unsafe void CreateKeyMap(bool supportsXkb) } else { - var e = new XKeyEvent + XKeyEvent e = new() { display = Display, keycode = i, diff --git a/src/BizHawk.Client.Common/Api/ApiInjector.cs b/src/BizHawk.Client.Common/Api/ApiInjector.cs index 352fee35669..244d2a7af2a 100644 --- a/src/BizHawk.Client.Common/Api/ApiInjector.cs +++ b/src/BizHawk.Client.Common/Api/ApiInjector.cs @@ -15,7 +15,7 @@ public static class ApiInjector /// public static void ClearApis(object target) { - Type targetType = target.GetType(); + var targetType = target.GetType(); object[] tmp = new object[1]; foreach (var mi in targetType.GetProperties(ReflectionExtensions.DI_TARGET_PROPS) .Where(static pi => pi.PropertyType == typeof(ApiContainer)) @@ -37,7 +37,7 @@ public static void ClearApis(object target) /// false if update failed public static bool UpdateApis(IExternalApiProvider source, object target) { - Type targetType = target.GetType(); + var targetType = target.GetType(); object[] tmp = new object[1]; foreach (var mi in targetType.GetProperties(ReflectionExtensions.DI_TARGET_PROPS) diff --git a/src/BizHawk.Client.Common/Api/BizHawkSystemIdToCoreSystemEnumConverter.cs b/src/BizHawk.Client.Common/Api/BizHawkSystemIdToCoreSystemEnumConverter.cs index 4776ff0de6c..484fd661fc0 100644 --- a/src/BizHawk.Client.Common/Api/BizHawkSystemIdToCoreSystemEnumConverter.cs +++ b/src/BizHawk.Client.Common/Api/BizHawkSystemIdToCoreSystemEnumConverter.cs @@ -76,10 +76,7 @@ public object Convert(object value, Type targetType, object parameter, CultureIn /// you want to convert /// A that is equivalent to BizHawk SystemId /// Thrown when SystemId hasn't been found - public CoreSystem Convert(string value) - { - return (CoreSystem)Convert(value, null, null, CultureInfo.CurrentCulture); - } + public CoreSystem Convert(string value) => (CoreSystem)Convert(value, null, null, CultureInfo.CurrentCulture); /// @@ -142,9 +139,6 @@ public object ConvertBack(object value, Type targetType, object parameter, Cultu /// you want to convert /// A that is used by BizHawk SystemId /// Thrown when hasn't been found - public string ConvertBack(CoreSystem value) - { - return (string)ConvertBack(value, null, null, CultureInfo.CurrentCulture); - } + public string ConvertBack(CoreSystem value) => (string)ConvertBack(value, null, null, CultureInfo.CurrentCulture); } } diff --git a/src/BizHawk.Client.Common/Api/Classes/CommApi.cs b/src/BizHawk.Client.Common/Api/Classes/CommApi.cs index 9888dffc184..c201e2804bc 100644 --- a/src/BizHawk.Client.Common/Api/Classes/CommApi.cs +++ b/src/BizHawk.Client.Common/Api/Classes/CommApi.cs @@ -4,7 +4,7 @@ namespace BizHawk.Client.Common { public sealed class CommApi : ICommApi { - private static readonly WebSocketServer _wsServer = new WebSocketServer(); + private static readonly WebSocketServer _wsServer = new(); private readonly (HttpCommunication? HTTP, MemoryMappedFiles MMF, SocketServer? Sockets) _networkingHelpers; diff --git a/src/BizHawk.Client.Common/Api/Classes/EmuClientApi.cs b/src/BizHawk.Client.Common/Api/Classes/EmuClientApi.cs index 745bef098a5..969be547f2e 100644 --- a/src/BizHawk.Client.Common/Api/Classes/EmuClientApi.cs +++ b/src/BizHawk.Client.Common/Api/Classes/EmuClientApi.cs @@ -114,7 +114,7 @@ public void OnBeforeQuickLoad(object sender, string quickSaveSlotName, out bool eventHandled = false; return; } - var e = new BeforeQuickLoadEventArgs(quickSaveSlotName); + BeforeQuickLoadEventArgs e = new(quickSaveSlotName); BeforeQuickLoad(sender, e); eventHandled = e.Handled; } @@ -126,15 +126,12 @@ public void OnBeforeQuickSave(object sender, string quickSaveSlotName, out bool eventHandled = false; return; } - var e = new BeforeQuickSaveEventArgs(quickSaveSlotName); + BeforeQuickSaveEventArgs e = new(quickSaveSlotName); BeforeQuickSave(sender, e); eventHandled = e.Handled; } - public void OnRomLoaded() - { - RomLoaded?.Invoke(null, EventArgs.Empty); - } + public void OnRomLoaded() => RomLoaded?.Invoke(null, EventArgs.Empty); public void OnStateLoaded(object sender, string stateName) => StateLoaded?.Invoke(sender, new StateLoadedEventArgs(stateName)); @@ -167,7 +164,7 @@ public void Screenshot(string path) public void SeekFrame(int frame) { - var wasPaused = _mainForm.EmulatorPaused; + bool wasPaused = _mainForm.EmulatorPaused; while (Emulator.Frame != frame) _mainForm.SeekFrameAdvance(); if (!wasPaused) _mainForm.UnpauseEmulator(); } @@ -195,7 +192,7 @@ public void SetSoundOn(bool enable) public void SetWindowSize(int size) { - if (size == 1 || size == 2 || size == 3 || size == 4 || size == 5 || size == 10) + if (size is 1 or 2 or 3 or 4 or 5 or 10) { _config.TargetZoomFactors[Emulator.SystemId] = size; _mainForm.FrameBufferResized(); diff --git a/src/BizHawk.Client.Common/Api/Classes/EmulationApi.cs b/src/BizHawk.Client.Common/Api/Classes/EmulationApi.cs index a7b43629806..69107b09c96 100644 --- a/src/BizHawk.Client.Common/Api/Classes/EmulationApi.cs +++ b/src/BizHawk.Client.Common/Api/Classes/EmulationApi.cs @@ -79,10 +79,10 @@ public int FrameCount() { if (DisassemblableCore != null) { - var disasm = DisassemblableCore.Disassemble( + string disasm = DisassemblableCore.Disassemble( string.IsNullOrEmpty(name) ? MemoryDomains!.SystemBus : MemoryDomains![name!]!, pc, - out var l + out int l ); return (disasm, l); } @@ -113,7 +113,7 @@ public IReadOnlyDictionary GetRegisters() { if (DebuggableCore != null) { - var table = new Dictionary(); + Dictionary table = new(); foreach (var (name, rv) in DebuggableCore.GetCpuFlagsAndRegisters()) table[name] = rv.Value; return table; } @@ -290,7 +290,7 @@ void SetQuickNES(QuickNES quicknes) { var s = quicknes.GetSettings(); // this core doesn't support disabling BG - var showSp = GetSetting(args, 0); + bool showSp = GetSetting(args, 0); if (showSp && s.NumSprites == 0) s.NumSprites = 8; else if (!showSp && s.NumSprites > 0) s.NumSprites = 0; quicknes.PutSettings(s); diff --git a/src/BizHawk.Client.Common/Api/Classes/GameInfoApi.cs b/src/BizHawk.Client.Common/Api/Classes/GameInfoApi.cs index 6e6dedc5f01..5dccfaf7018 100644 --- a/src/BizHawk.Client.Common/Api/Classes/GameInfoApi.cs +++ b/src/BizHawk.Client.Common/Api/Classes/GameInfoApi.cs @@ -27,7 +27,7 @@ public string GetBoardType() public IReadOnlyDictionary GetOptions() { - var options = new Dictionary(); + Dictionary options = new(); if (_game == null) return options; foreach (var (k, v) in ((GameInfo) _game).GetOptions()) options[k] = v; return options; diff --git a/src/BizHawk.Client.Common/Api/Classes/GuiApi.cs b/src/BizHawk.Client.Common/Api/Classes/GuiApi.cs index 3d1357b4ef1..ef230b2608b 100644 --- a/src/BizHawk.Client.Common/Api/Classes/GuiApi.cs +++ b/src/BizHawk.Client.Common/Api/Classes/GuiApi.cs @@ -25,15 +25,15 @@ public sealed class GuiApi : IGuiApi private readonly DisplayManagerBase _displayManager; - private readonly Dictionary _imageCache = new Dictionary(); + private readonly Dictionary _imageCache = new(); - private readonly Bitmap _nullGraphicsBitmap = new Bitmap(1, 1); + private readonly Bitmap _nullGraphicsBitmap = new(1, 1); - private readonly Dictionary _pens = new Dictionary(); + private readonly Dictionary _pens = new(); - private readonly Dictionary _solidBrushes = new Dictionary(); + private readonly Dictionary _solidBrushes = new(); - private ImageAttributes _attributes = new ImageAttributes(); + private ImageAttributes _attributes = new(); private CompositingMode _compositingMode = CompositingMode.SourceOver; @@ -478,8 +478,8 @@ public void DrawPolygon(Point[] points, Color? line = null, Color? background = public void DrawRectangle(int x, int y, int width, int height, Color? line = null, Color? background = null, DisplaySurfaceID? surfaceID = null) { using var g = GetGraphics(surfaceID); - var w = Math.Max(width, 0.1F); - var h = Math.Max(height, 0.1F); + float w = Math.Max(width, 0.1F); + float h = Math.Max(height, 0.1F); g.DrawRectangle(GetPen(line ?? _defaultForeground), x, y, w, h); var bg = background ?? _defaultBackground; if (bg != null) g.FillRectangle(GetBrush(bg.Value), x + 1, y + 1, Math.Max(w - 1, 0), Math.Max(h - 1, 0)); @@ -504,8 +504,8 @@ public void DrawString(int x, int y, string message, Color? forecolor = null, Co // The text isn't written out using GenericTypographic, so measuring it using GenericTypographic seemed to make it worse. // And writing it out with GenericTypographic just made it uglier. :p - var font = new Font(family, fontsize ?? 12, fstyle, GraphicsUnit.Pixel); - var sizeOfText = g.MeasureString(message, font, 0, new StringFormat(StringFormat.GenericDefault)).ToSize(); + Font font = new(family, fontsize ?? 12, fstyle, GraphicsUnit.Pixel); + Size sizeOfText = g.MeasureString(message, font, 0, new StringFormat(StringFormat.GenericDefault)).ToSize(); switch (horizalign?.ToLowerInvariant()) { @@ -539,7 +539,7 @@ public void DrawString(int x, int y, string message, Color? forecolor = null, Co if (bg != null) { var brush = GetBrush(bg.Value); - for (var xd = -1; xd <= 1; xd++) for (var yd = -1; yd <= 1; yd++) + for (int xd = -1; xd <= 1; xd++) for (int yd = -1; yd <= 1; yd++) { g.DrawString(message, font, brush, x + xd, y + yd); } @@ -595,8 +595,8 @@ public void PixelText( break; } using var g = GetGraphics(surfaceID); - var font = new Font(_displayManager.CustomFonts.Families[index], 8, FontStyle.Regular, GraphicsUnit.Pixel); - var sizeOfText = g.MeasureString(message, font, width: 0, PixelTextFormat).ToSize(); + Font font = new(_displayManager.CustomFonts.Families[index], 8, FontStyle.Regular, GraphicsUnit.Pixel); + Size sizeOfText = g.MeasureString(message, font, width: 0, PixelTextFormat).ToSize(); if (backcolor.HasValue) g.FillRectangle(GetBrush(backcolor.Value), new Rectangle(new Point(x, y), sizeOfText + new Size(1, 0))); g.TextRenderingHint = TextRenderingHint.SingleBitPerPixelGridFit; g.DrawString(message, font, GetBrush(forecolor ?? _defaultForeground), x + 1, y, PixelTextFormat); @@ -632,7 +632,7 @@ public void Text(int x, int y, string message, Color? forecolor = null, string a y -= oy; } - var pos = new MessagePosition{ X = x, Y = y, Anchor = (MessagePosition.AnchorType)a }; + MessagePosition pos = new() { X = x, Y = y, Anchor = (MessagePosition.AnchorType)a }; _displayManager.OSD.AddGuiText(message, pos, Color.Black, forecolor ?? Color.White); } diff --git a/src/BizHawk.Client.Common/Api/Classes/InputApi.cs b/src/BizHawk.Client.Common/Api/Classes/InputApi.cs index 9b7d2676c4e..c61d27e28a8 100644 --- a/src/BizHawk.Client.Common/Api/Classes/InputApi.cs +++ b/src/BizHawk.Client.Common/Api/Classes/InputApi.cs @@ -19,7 +19,7 @@ public InputApi(DisplayManagerBase displayManager, InputManager inputManager) public Dictionary Get() { - var buttons = new Dictionary(); + Dictionary buttons = new(); foreach (var (button, _) in _inputManager.ControllerInputCoalescer.BoolButtons().Where(kvp => kvp.Value)) buttons[button] = true; return buttons; } diff --git a/src/BizHawk.Client.Common/Api/Classes/JoypadApi.cs b/src/BizHawk.Client.Common/Api/Classes/JoypadApi.cs index 91b6aebb3d7..e5aeb0ad6de 100644 --- a/src/BizHawk.Client.Common/Api/Classes/JoypadApi.cs +++ b/src/BizHawk.Client.Common/Api/Classes/JoypadApi.cs @@ -21,20 +21,11 @@ public JoypadApi(Action logCallback, InputManager inputManager, IMovieSe _movieSession = movieSession; } - public IReadOnlyDictionary Get(int? controller = null) - { - return _inputManager.AutofireStickyXorAdapter.ToDictionary(controller); - } + public IReadOnlyDictionary Get(int? controller = null) => _inputManager.AutofireStickyXorAdapter.ToDictionary(controller); - public IReadOnlyDictionary GetWithMovie(int? controller = null) - { - return _inputManager.ControllerOutput.ToDictionary(controller); - } + public IReadOnlyDictionary GetWithMovie(int? controller = null) => _inputManager.ControllerOutput.ToDictionary(controller); - public IReadOnlyDictionary GetImmediate(int? controller = null) - { - return _inputManager.ActiveController.ToDictionary(controller); - } + public IReadOnlyDictionary GetImmediate(int? controller = null) => _inputManager.ActiveController.ToDictionary(controller); public void SetFromMnemonicStr(string inputLogEntry) { @@ -48,17 +39,17 @@ public void SetFromMnemonicStr(string inputLogEntry) LogCallback($"invalid mnemonic string: {inputLogEntry}"); return; } - foreach (var button in controller.Definition.BoolButtons) _inputManager.ButtonOverrideAdapter.SetButton(button, controller.IsPressed(button)); - foreach (var axis in controller.Definition.Axes.Keys) _inputManager.ButtonOverrideAdapter.SetAxis(axis, controller.AxisValue(axis)); + foreach (string button in controller.Definition.BoolButtons) _inputManager.ButtonOverrideAdapter.SetButton(button, controller.IsPressed(button)); + foreach (string axis in controller.Definition.Axes.Keys) _inputManager.ButtonOverrideAdapter.SetAxis(axis, controller.AxisValue(axis)); } public void Set(IReadOnlyDictionary buttons, int? controller = null) { // If a controller is specified, we need to iterate over unique button names. If not, we iterate over // ALL button names with P{controller} prefixes - foreach (var button in _inputManager.ActiveController.ToBoolButtonNameList(controller)) + foreach (string button in _inputManager.ActiveController.ToBoolButtonNameList(controller)) { - Set(button, buttons.TryGetValue(button, out var state) ? state : null, controller); + Set(button, buttons.TryGetValue(button, out bool state) ? state : null, controller); } } @@ -66,7 +57,7 @@ public void Set(string button, bool? state = null, int? controller = null) { try { - var buttonToSet = controller == null ? button : $"P{controller} {button}"; + string buttonToSet = controller == null ? button : $"P{controller} {button}"; if (state == null) _inputManager.ButtonOverrideAdapter.UnSet(buttonToSet); else _inputManager.ButtonOverrideAdapter.SetButton(buttonToSet, state.Value); diff --git a/src/BizHawk.Client.Common/Api/Classes/MemoryApi.cs b/src/BizHawk.Client.Common/Api/Classes/MemoryApi.cs index 5ce463ff57e..24b19b4b5c4 100644 --- a/src/BizHawk.Client.Common/Api/Classes/MemoryApi.cs +++ b/src/BizHawk.Client.Common/Api/Classes/MemoryApi.cs @@ -28,7 +28,7 @@ MemoryDomain LazyInit() { if (MemoryDomainCore == null) { - var error = $"Error: {Emulator.Attributes().CoreName} does not implement memory domains"; + string error = $"Error: {Emulator.Attributes().CoreName} does not implement memory domains"; LogCallback(error); throw new NotImplementedException(error); } @@ -46,7 +46,7 @@ public IMemoryDomains DomainList { if (MemoryDomainCore == null) { - var error = $"Error: {Emulator.Attributes().CoreName} does not implement memory domains"; + string error = $"Error: {Emulator.Attributes().CoreName} does not implement memory domains"; LogCallback(error); throw new NotImplementedException(error); } @@ -60,7 +60,7 @@ public string MainMemoryName { if (MemoryDomainCore == null) { - var error = $"Error: {Emulator.Attributes().CoreName} does not implement memory domains"; + string error = $"Error: {Emulator.Attributes().CoreName} does not implement memory domains"; LogCallback(error); throw new NotImplementedException(error); } @@ -90,32 +90,32 @@ private MemoryDomain NamedDomainOrCurrent(string name) private static int U2S(uint u, int size) { - var sh = 8 * (4 - size); + int sh = 8 * (4 - size); return ((int) u << sh) >> sh; } private uint ReadUnsignedLittle(long addr, int size, string domain = null) { uint v = 0; - for (var i = 0; i < size; i++) v |= ReadUnsigned(addr + i, 1, domain) << (8 * i); + for (int i = 0; i < size; i++) v |= ReadUnsigned(addr + i, 1, domain) << (8 * i); return v; } private uint ReadUnsignedBig(long addr, int size, string domain = null) { uint v = 0; - for (var i = 0; i < size; i++) v |= ReadUnsigned(addr + i, 1, domain) << (8 * (size - 1 - i)); + for (int i = 0; i < size; i++) v |= ReadUnsigned(addr + i, 1, domain) << (8 * (size - 1 - i)); return v; } private void WriteUnsignedLittle(long addr, uint v, int size, string domain = null) { - for (var i = 0; i < size; i++) WriteUnsigned(addr + i, (v >> (8 * i)) & 0xFF, 1, domain); + for (int i = 0; i < size; i++) WriteUnsigned(addr + i, (v >> (8 * i)) & 0xFF, 1, domain); } private void WriteUnsignedBig(long addr, uint v, int size, string domain = null) { - for (var i = 0; i < size; i++) WriteUnsigned(addr + i, (v >> (8 * (size - 1 - i))) & 0xFF, 1, domain); + for (int i = 0; i < size; i++) WriteUnsigned(addr + i, (v >> (8 * (size - 1 - i))) & 0xFF, 1, domain); } private int ReadSigned(long addr, int size, string domain = null) => U2S(ReadUnsigned(addr, size, domain), size); @@ -220,17 +220,17 @@ public string HashRegion(long addr, int count, string domain = null) var d = NamedDomainOrCurrent(domain); if (!0L.RangeToExclusive(d.Size).Contains(addr)) { - var error = $"Address {addr} is outside the bounds of domain {d.Name}"; + string error = $"Address {addr} is outside the bounds of domain {d.Name}"; LogCallback(error); throw new ArgumentOutOfRangeException(error); } if (addr + count > d.Size) { - var error = $"Address {addr} + count {count} is outside the bounds of domain {d.Name}"; + string error = $"Address {addr} + count {count} is outside the bounds of domain {d.Name}"; LogCallback(error); throw new ArgumentOutOfRangeException(error); } - var data = new byte[count]; + byte[] data = new byte[count]; using (d.EnterExit()) { d.BulkPeekByte(addr.RangeToExclusive(addr + count), data); @@ -246,15 +246,15 @@ public IReadOnlyList ReadByteRange(long addr, int length, string domain = { var d = NamedDomainOrCurrent(domain); if (addr < 0) LogCallback($"Warning: Attempted reads on addresses {addr}..-1 outside range of domain {d.Name} in {nameof(ReadByteRange)}()"); - var lastReqAddr = addr + length - 1; - var indexAfterLast = Math.Min(Math.Max(-1L, lastReqAddr), d.Size - 1L) + 1L; - var iSrc = Math.Min(Math.Max(0L, addr), d.Size); - var iDst = iSrc - addr; - var bytes = new byte[indexAfterLast - iSrc]; + long lastReqAddr = addr + length - 1; + long indexAfterLast = Math.Min(Math.Max(-1L, lastReqAddr), d.Size - 1L) + 1L; + long iSrc = Math.Min(Math.Max(0L, addr), d.Size); + long iDst = iSrc - addr; + byte[] bytes = new byte[indexAfterLast - iSrc]; if (iSrc < indexAfterLast) using (d.EnterExit()) d.BulkPeekByte(iSrc.RangeToExclusive(indexAfterLast), bytes); if (lastReqAddr >= d.Size) LogCallback($"Warning: Attempted reads on addresses {d.Size}..{lastReqAddr} outside range of domain {d.Name} in {nameof(ReadByteRange)}()"); if (bytes.Length == length) return bytes; - var newBytes = new byte[length]; + byte[] newBytes = new byte[length]; if (bytes.Length is not 0) Array.Copy(sourceArray: bytes, sourceIndex: 0, destinationArray: newBytes, destinationIndex: iDst, length: bytes.Length); return newBytes; } @@ -268,10 +268,10 @@ public void WriteByteRange(long addr, IReadOnlyList memoryblock, string do return; } if (addr < 0) LogCallback($"Warning: Attempted writes on addresses {addr}..-1 outside range of domain {d.Name} in {nameof(WriteByteRange)}()"); - var lastReqAddr = addr + memoryblock.Count - 1; - var indexAfterLast = Math.Min(Math.Max(-1L, lastReqAddr), d.Size - 1L) + 1L; - var iDst = Math.Min(Math.Max(0L, addr), d.Size); - var iSrc = checked((int) (iDst - addr)); + long lastReqAddr = addr + memoryblock.Count - 1; + long indexAfterLast = Math.Min(Math.Max(-1L, lastReqAddr), d.Size - 1L) + 1L; + long iDst = Math.Min(Math.Max(0L, addr), d.Size); + int iSrc = checked((int) (iDst - addr)); using (d.EnterExit()) { while (iDst < indexAfterLast) d.PokeByte(iDst++, memoryblock[iSrc++]); diff --git a/src/BizHawk.Client.Common/Api/Classes/MemorySaveStateApi.cs b/src/BizHawk.Client.Common/Api/Classes/MemorySaveStateApi.cs index d8a89a29a2d..d117d9a741a 100644 --- a/src/BizHawk.Client.Common/Api/Classes/MemorySaveStateApi.cs +++ b/src/BizHawk.Client.Common/Api/Classes/MemorySaveStateApi.cs @@ -11,20 +11,20 @@ public sealed class MemorySaveStateApi : IMemorySaveStateApi private readonly Action LogCallback; - private readonly Dictionary _memorySavestates = new Dictionary(); + private readonly Dictionary _memorySavestates = new(); public MemorySaveStateApi(Action logCallback) => LogCallback = logCallback; public string SaveCoreStateToMemory() { - var guid = Guid.NewGuid(); + Guid guid = Guid.NewGuid(); _memorySavestates.Add(guid, StatableCore.CloneSavestate()); return guid.ToString(); } public void LoadCoreStateFromMemory(string identifier) { - var guid = new Guid(identifier); + Guid guid = new(identifier); try { StatableCore.LoadStateBinary(_memorySavestates[guid]); diff --git a/src/BizHawk.Client.Common/Api/Classes/SQLiteApi.cs b/src/BizHawk.Client.Common/Api/Classes/SQLiteApi.cs index 2b612af4647..08913ab2900 100644 --- a/src/BizHawk.Client.Common/Api/Classes/SQLiteApi.cs +++ b/src/BizHawk.Client.Common/Api/Classes/SQLiteApi.cs @@ -31,7 +31,7 @@ public string OpenDatabase(string name) _dbConnection?.Dispose(); _dbConnection = new(new SqliteConnectionStringBuilder { DataSource = name }.ToString()); _dbConnection.Open(); - using var initCmds = new SqliteCommand(null, _dbConnection); + using SqliteCommand initCmds = new(null, _dbConnection); // Allows for reads and writes to happen at the same time initCmds.CommandText = "PRAGMA journal_mode = 'wal'"; initCmds.ExecuteNonQuery(); @@ -55,7 +55,7 @@ public string WriteCommand(string query = null) try { _dbConnection.Open(); - using var cmd = new SqliteCommand(query, _dbConnection); + using SqliteCommand cmd = new(query, _dbConnection); cmd.ExecuteNonQuery(); result = "Command ran successfully"; } @@ -75,14 +75,14 @@ public object ReadCommand(string query = null) try { _dbConnection.Open(); - using var command = new SqliteCommand($"PRAGMA read_uncommitted =1;{query}", _dbConnection); + using SqliteCommand command = new($"PRAGMA read_uncommitted =1;{query}", _dbConnection); using var reader = command.ExecuteReader(); if (reader.HasRows) { - var columns = new string[reader.FieldCount]; + string[] columns = new string[reader.FieldCount]; for (int i = 0, l = reader.FieldCount; i < l; i++) columns[i] = reader.GetName(i); long rowCount = 0; - var table = new Dictionary(); + Dictionary table = new(); while (reader.Read()) { for (int i = 0, l = reader.FieldCount; i < l; i++) table[$"{columns[i]} {rowCount}"] = reader.GetValue(i); diff --git a/src/BizHawk.Client.Common/Api/Classes/UserDataApi.cs b/src/BizHawk.Client.Common/Api/Classes/UserDataApi.cs index 91e1d0e45fa..87441f1485a 100644 --- a/src/BizHawk.Client.Common/Api/Classes/UserDataApi.cs +++ b/src/BizHawk.Client.Common/Api/Classes/UserDataApi.cs @@ -29,7 +29,7 @@ public void Set(string name, object value) _movieSession.UserBag[name] = value; } - public object Get(string key) => _movieSession.UserBag.TryGetValue(key, out var value) ? value : null; + public object Get(string key) => _movieSession.UserBag.TryGetValue(key, out object value) ? value : null; public void Clear() => _movieSession.UserBag.Clear(); diff --git a/src/BizHawk.Client.Common/Api/ClientWebSocketWrapper.cs b/src/BizHawk.Client.Common/Api/ClientWebSocketWrapper.cs index 9f754573936..6dd09109752 100644 --- a/src/BizHawk.Client.Common/Api/ClientWebSocketWrapper.cs +++ b/src/BizHawk.Client.Common/Api/ClientWebSocketWrapper.cs @@ -13,7 +13,7 @@ public struct ClientWebSocketWrapper private ClientWebSocket? _w; /// calls getter (unless closed/disposed, then is always returned) - public WebSocketState State => _w?.State ?? WebSocketState.Closed; + public readonly WebSocketState State => _w?.State ?? WebSocketState.Closed; public ClientWebSocketWrapper(Uri uri, CancellationToken? cancellationToken = null) { @@ -33,26 +33,26 @@ public Task Close(WebSocketCloseStatus closeStatus, string statusDescription, Ca } /// calls - public Task Receive(ArraySegment buffer, CancellationToken? cancellationToken = null) + public readonly Task Receive(ArraySegment buffer, CancellationToken? cancellationToken = null) => _w?.ReceiveAsync(buffer, cancellationToken ?? CancellationToken.None) ?? throw new ObjectDisposedException(nameof(_w)); /// calls - public string Receive(int bufferCap, CancellationToken? cancellationToken = null) + public readonly string Receive(int bufferCap, CancellationToken? cancellationToken = null) { if (_w == null) throw new ObjectDisposedException(nameof(_w)); - var buffer = new byte[bufferCap]; + byte[] buffer = new byte[bufferCap]; var result = Receive(new ArraySegment(buffer), cancellationToken ?? CancellationToken.None).Result; return Encoding.UTF8.GetString(buffer, 0, result.Count); } /// calls - public Task Send(ArraySegment buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken? cancellationToken = null) + public readonly Task Send(ArraySegment buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken? cancellationToken = null) => _w?.SendAsync(buffer, messageType, endOfMessage, cancellationToken ?? CancellationToken.None) ?? throw new ObjectDisposedException(nameof(_w)); /// calls - public Task Send(string message, bool endOfMessage, CancellationToken? cancellationToken = null) + public readonly Task Send(string message, bool endOfMessage, CancellationToken? cancellationToken = null) { if (_w == null) throw new ObjectDisposedException(nameof(_w)); return Send( diff --git a/src/BizHawk.Client.Common/Api/HttpCommunication.cs b/src/BizHawk.Client.Common/Api/HttpCommunication.cs index 1270b8d058c..b3d6d0f96e9 100644 --- a/src/BizHawk.Client.Common/Api/HttpCommunication.cs +++ b/src/BizHawk.Client.Common/Api/HttpCommunication.cs @@ -7,7 +7,7 @@ namespace BizHawk.Client.Common { public sealed class HttpCommunication { - private readonly HttpClient _client = new HttpClient(); + private readonly HttpClient _client = new(); private readonly Func _takeScreenshotCallback; @@ -66,10 +66,10 @@ public async Task Post(string url, FormUrlEncodedContent content) public string SendScreenshot(string url = null, string parameter = "screenshot") { - var url1 = url ?? PostUrl; - var content = new FormUrlEncodedContent(new Dictionary { [parameter] = Convert.ToBase64String(_takeScreenshotCallback()) }); + string url1 = url ?? PostUrl; + FormUrlEncodedContent content = new(new Dictionary { [parameter] = Convert.ToBase64String(_takeScreenshotCallback()) }); Task postResponse = null; - var trials = 5; + int trials = 5; while (postResponse == null && trials > 0) { postResponse = Post(url1, content); diff --git a/src/BizHawk.Client.Common/Api/MemoryMappedFiles.cs b/src/BizHawk.Client.Common/Api/MemoryMappedFiles.cs index 669f0ce024f..065bc48ff61 100644 --- a/src/BizHawk.Client.Common/Api/MemoryMappedFiles.cs +++ b/src/BizHawk.Client.Common/Api/MemoryMappedFiles.cs @@ -9,7 +9,7 @@ namespace BizHawk.Client.Common { public sealed class MemoryMappedFiles { - private readonly Dictionary _mmfFiles = new Dictionary(); + private readonly Dictionary _mmfFiles = new(); private readonly Func _takeScreenshotCallback; @@ -23,7 +23,7 @@ public MemoryMappedFiles(Func takeScreenshotCallback, string filename) public string ReadFromFile(string filename, int expectedSize) { - var bytes = ReadBytesFromFile(filename, expectedSize); + byte[] bytes = ReadBytesFromFile(filename, expectedSize); return Encoding.UTF8.GetString(bytes); } @@ -31,7 +31,7 @@ public byte[] ReadBytesFromFile(string filename, int expectedSize) { var mmfFile = _mmfFiles.GetValueOrPut(filename, MemoryMappedFile.OpenExisting); using var viewAccessor = mmfFile.CreateViewAccessor(0, expectedSize, MemoryMappedFileAccess.Read); - var bytes = new byte[expectedSize]; + byte[] bytes = new byte[expectedSize]; viewAccessor.ReadArray(0, bytes, 0, expectedSize); return bytes; } diff --git a/src/BizHawk.Client.Common/Api/SocketServer.cs b/src/BizHawk.Client.Common/Api/SocketServer.cs index ba8e7b7e64c..793aa2db03d 100644 --- a/src/BizHawk.Client.Common/Api/SocketServer.cs +++ b/src/BizHawk.Client.Common/Api/SocketServer.cs @@ -103,7 +103,7 @@ public string ReceiveString(Encoding encoding = null) { //build length of string into a string byte[] oneByte = new byte[1]; - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); for (; ; ) { int recvd = _soc.Receive(oneByte, 1, 0); @@ -150,9 +150,9 @@ public int SendBytes(byte[] sendBytes) public string SendScreenshot(int waitingTime = 0) { - var bmpBytes = PrefixWithLength(_takeScreenshotCallback()); - var sentBytes = 0; - var tries = 0; + byte[] bmpBytes = PrefixWithLength(_takeScreenshotCallback()); + int sentBytes = 0; + int tries = 0; while (sentBytes <= 0 && tries < Retries) { try @@ -176,13 +176,13 @@ public string SendScreenshot(int waitingTime = 0) { return Successful ? "Screenshot was sent" : "Screenshot could not be sent"; } - var resp = ReceiveString(); + string resp = ReceiveString(); return resp == "" ? "Failed to get a response" : resp; } public int SendString(string sendString, Encoding encoding = null) { - var sentBytes = SendBytes(PrefixWithLength((encoding ?? Encoding.UTF8).GetBytes(sendString))); + int sentBytes = SendBytes(PrefixWithLength((encoding ?? Encoding.UTF8).GetBytes(sendString))); Successful = sentBytes > 0; return sentBytes; } diff --git a/src/BizHawk.Client.Common/Api/WebSocketServer.cs b/src/BizHawk.Client.Common/Api/WebSocketServer.cs index da6a34a5100..505cff473d0 100644 --- a/src/BizHawk.Client.Common/Api/WebSocketServer.cs +++ b/src/BizHawk.Client.Common/Api/WebSocketServer.cs @@ -7,6 +7,6 @@ namespace BizHawk.Client.Common { public sealed class WebSocketServer { - public ClientWebSocketWrapper Open(Uri uri, CancellationToken? cancellationToken = null) => new ClientWebSocketWrapper(uri, cancellationToken); + public ClientWebSocketWrapper Open(Uri uri, CancellationToken? cancellationToken = null) => new(uri, cancellationToken); } } diff --git a/src/BizHawk.Client.Common/ArgParser.cs b/src/BizHawk.Client.Common/ArgParser.cs index 0d8350edd3e..3ebfa7a564c 100644 --- a/src/BizHawk.Client.Common/ArgParser.cs +++ b/src/BizHawk.Client.Common/ArgParser.cs @@ -48,19 +48,19 @@ public static void ParseArguments(out ParsedCLIFlags parsed, string[] args) List<(string Key, string Value)>? userdataUnparsedPairs = null; string? cmdRom = null; - for (var i = 0; i < args.Length; i++) + for (int i = 0; i < args.Length; i++) { - var arg = args[i]; + string arg = args[i]; if (arg == ">") { // For some reason sometimes visual studio will pass this to us on the commandline. it makes no sense. - var stdout = args[++i]; + string stdout = args[++i]; Console.SetOut(new StreamWriter(stdout)); continue; } - var argDowncased = arg.ToLowerInvariant(); + string argDowncased = arg.ToLowerInvariant(); if (argDowncased.StartsWithOrdinal("--load-slot=")) { cmdLoadSlot = argDowncased.Substring(argDowncased.IndexOf('=') + 1); @@ -104,7 +104,7 @@ public static void ParseArguments(out ParsedCLIFlags parsed, string[] args) } else if (argDowncased.StartsWithOrdinal("--dump-length=")) { - var len = int.TryParse(argDowncased.Substring(argDowncased.IndexOf('=') + 1), out var i1) ? i1 : default; + int len = int.TryParse(argDowncased.Substring(argDowncased.IndexOf('=') + 1), out int i1) ? i1 : default; autoDumpLength = len; } else if (argDowncased.StartsWithOrdinal("--dump-close")) @@ -131,7 +131,7 @@ public static void ParseArguments(out ParsedCLIFlags parsed, string[] args) } else if (argDowncased.StartsWithOrdinal("--socket_port=")) { - var port = int.TryParse(argDowncased.Substring(argDowncased.IndexOf('=') + 1), out var i1) ? i1 : default; + int port = int.TryParse(argDowncased.Substring(argDowncased.IndexOf('=') + 1), out int i1) ? i1 : default; if (port > 0) socketPort = port; } else if (argDowncased.StartsWithOrdinal("--socket_ip=")) @@ -168,9 +168,9 @@ public static void ParseArguments(out ParsedCLIFlags parsed, string[] args) else if (argDowncased.StartsWithOrdinal("--userdata=")) { userdataUnparsedPairs = new(); - foreach (var s in arg.Substring(11).Split(';')) + foreach (string? s in arg.Substring(11).Split(';')) { - var iColon = s.IndexOf(':'); + int iColon = s.IndexOf(':'); if (iColon is -1) throw new ArgParserException("malformed userdata (';' without ':')"); userdataUnparsedPairs.Add((s.Substring(startIndex: 0, length: iColon), s.Substring(iColon + 1))); } diff --git a/src/BizHawk.Client.Common/BreakpointList.cs b/src/BizHawk.Client.Common/BreakpointList.cs index b43df421ae7..d88b5763a7e 100644 --- a/src/BizHawk.Client.Common/BreakpointList.cs +++ b/src/BizHawk.Client.Common/BreakpointList.cs @@ -9,10 +9,7 @@ public class BreakpointList : List { public MemoryCallbackDelegate Callback { get; set; } - public void Add(IDebuggable core, string scope, uint address, uint mask, MemoryCallbackType type) - { - Add(new Breakpoint(core, scope, Callback, address, mask, type)); - } + public void Add(IDebuggable core, string scope, uint address, uint mask, MemoryCallbackType type) => Add(new Breakpoint(core, scope, Callback, address, mask, type)); public new void Clear() { @@ -50,7 +47,7 @@ public void Add(IDebuggable core, string scope, uint address, uint mask, MemoryC public new int RemoveAll(Predicate match) { - var removeCount = 0; + int removeCount = 0; foreach (var breakpoint in this) { if (match(breakpoint)) @@ -157,15 +154,9 @@ public bool Active } } - private void AddCallback() - { - _core.MemoryCallbacks.Add(new MemoryCallback(Scope, Type, Name, DoCallback, Address, AddressMask)); - } + private void AddCallback() => _core.MemoryCallbacks.Add(new MemoryCallback(Scope, Type, Name, DoCallback, Address, AddressMask)); - private void RemoveCallback() - { - _core.MemoryCallbacks.Remove(DoCallback); - } + private void RemoveCallback() => _core.MemoryCallbacks.Remove(DoCallback); private void DoCallback(uint address, uint value, uint flags) => Callback(address, value, flags); diff --git a/src/BizHawk.Client.Common/Controller.cs b/src/BizHawk.Client.Common/Controller.cs index df66988c532..168f088ae07 100644 --- a/src/BizHawk.Client.Common/Controller.cs +++ b/src/BizHawk.Client.Common/Controller.cs @@ -19,7 +19,7 @@ public Controller(ControllerDefinition definition) _axes[k] = v.Neutral; _axisRanges[k] = v; } - foreach (var channel in Definition.HapticsChannels) _haptics[channel] = 0; + foreach (string channel in Definition.HapticsChannels) _haptics[channel] = 0; } public ControllerDefinition Definition { get; } @@ -33,13 +33,13 @@ public Controller(ControllerDefinition definition) public void SetHapticChannelStrength(string name, int strength) => _haptics[name] = strength; - private readonly WorkingDictionary> _bindings = new WorkingDictionary>(); - private readonly WorkingDictionary _buttons = new WorkingDictionary(); - private readonly WorkingDictionary _axes = new WorkingDictionary(); + private readonly WorkingDictionary> _bindings = new(); + private readonly WorkingDictionary _buttons = new(); + private readonly WorkingDictionary _axes = new(); private readonly Dictionary _axisRanges = new WorkingDictionary(); - private readonly Dictionary _axisBindings = new Dictionary(); + private readonly Dictionary _axisBindings = new(); private readonly Dictionary _haptics = new WorkingDictionary(); - private readonly Dictionary _feedbackBindings = new Dictionary(); + private readonly Dictionary _feedbackBindings = new(); public bool this[string button] => IsPressed(button); @@ -64,7 +64,7 @@ public void LatchFromPhysical(IController finalHostController) foreach (var (k, v) in _bindings) { _buttons[k] = false; - foreach (var button in v) + foreach (string button in v) { if (finalHostController.IsPressed(button)) { @@ -76,10 +76,10 @@ public void LatchFromPhysical(IController finalHostController) foreach (var (k, v) in _axisBindings) { // values from finalHostController are ints in -10000..10000 (or 0..10000), so scale to -1..1, using floats to keep fractional part - var value = finalHostController.AxisValue(v.Value) / 10000.0f; + float value = finalHostController.AxisValue(v.Value) / 10000.0f; // apply deadzone (and scale diminished range back up to -1..1) - var deadzone = v.Deadzone; + float deadzone = v.Deadzone; if (value < -deadzone) value += deadzone; else if (value < deadzone) value = 0.0f; else value -= deadzone; @@ -104,9 +104,9 @@ public void PrepareHapticsForHost(SimpleController finalHostController) { foreach (var (k, v) in _feedbackBindings) { - if (_haptics.TryGetValue(k, out var strength)) + if (_haptics.TryGetValue(k, out int strength)) { - foreach (var hostChannel in v.Channels!.Split('+')) + foreach (string hostChannel in v.Channels!.Split('+')) { finalHostController.SetHapticChannelStrength(v.GamepadPrefix + hostChannel, (int) ((double) strength * v.Prescale)); } @@ -126,7 +126,7 @@ public void OR_FromLogical(IController controller) // foreach (string button in type.BoolButtons) if (controller.Definition != null) { - foreach (var button in controller.Definition.BoolButtons) + foreach (string button in controller.Definition.BoolButtons) { if (controller.IsPressed(button)) { @@ -138,17 +138,17 @@ public void OR_FromLogical(IController controller) public void Overrides(OverrideAdapter controller) { - foreach (var button in controller.Overrides) + foreach (string button in controller.Overrides) { _buttons[button] = controller.IsPressed(button); } - foreach (var button in controller.AxisOverrides) + foreach (string button in controller.AxisOverrides) { _axes[button] = controller.AxisValue(button); } - foreach (var button in controller.InversedButtons) + foreach (string button in controller.InversedButtons) { _buttons[button] ^= true; } @@ -161,17 +161,14 @@ public void BindMulti(string button, string controlString) return; } - var controlBindings = controlString.Split(','); - foreach (var control in controlBindings) + string[] controlBindings = controlString.Split(','); + foreach (string control in controlBindings) { _bindings[button].Add(control.Trim()); } } - public void BindAxis(string button, AnalogBind bind) - { - _axisBindings[button] = bind; - } + public void BindAxis(string button, AnalogBind bind) => _axisBindings[button] = bind; public void BindFeedbackChannel(string channel, FeedbackBind binding) => _feedbackBindings[channel] = binding; diff --git a/src/BizHawk.Client.Common/CoreFileProvider.cs b/src/BizHawk.Client.Common/CoreFileProvider.cs index b1d9e01b754..d67e5879233 100644 --- a/src/BizHawk.Client.Common/CoreFileProvider.cs +++ b/src/BizHawk.Client.Common/CoreFileProvider.cs @@ -40,7 +40,7 @@ public string GetUserPath(string sysID, bool temp) { if (temp) { - var tempUserPath = Path.Combine(Path.GetTempPath(), $"biz-temp{sysID}user"); + string tempUserPath = Path.Combine(Path.GetTempPath(), $"biz-temp{sysID}user"); if (Directory.Exists(tempUserPath)) { Directory.Delete(tempUserPath, true); @@ -54,7 +54,7 @@ public string GetUserPath(string sysID, bool temp) private (byte[] FW, string Path)? GetFirmwareWithPath(FirmwareID id) { - var path = _firmwareManager.Request(_pathEntries, _firmwareUserSpecifications, id); + string? path = _firmwareManager.Request(_pathEntries, _firmwareUserSpecifications, id); try { if (path is not null && File.Exists(path)) return (File.ReadAllBytes(path), path); diff --git a/src/BizHawk.Client.Common/DialogControllerExtensions.cs b/src/BizHawk.Client.Common/DialogControllerExtensions.cs index d6f17dccd3b..473f06cc4f5 100644 --- a/src/BizHawk.Client.Common/DialogControllerExtensions.cs +++ b/src/BizHawk.Client.Common/DialogControllerExtensions.cs @@ -188,7 +188,7 @@ public static bool ShowMessageBox2( string? initFileName = null, bool maySelectMultiple = false) { - var filterIndex = 1; // you'd think the default would be 0, but it's not + int filterIndex = 1; // you'd think the default would be 0, but it's not return dialogParent.DialogController.ShowFileMultiOpenDialog( dialogParent: dialogParent, discardCWDChange: discardCWDChange, diff --git a/src/BizHawk.Client.Common/DisplayManager/DisplayManagerBase.cs b/src/BizHawk.Client.Common/DisplayManager/DisplayManagerBase.cs index 70948564b0a..4c959c48767 100644 --- a/src/BizHawk.Client.Common/DisplayManager/DisplayManagerBase.cs +++ b/src/BizHawk.Client.Common/DisplayManager/DisplayManagerBase.cs @@ -35,10 +35,7 @@ protected class DisplayManagerRenderTargetProvider : IRenderTargetProvider { private readonly Func _callback; - RenderTarget IRenderTargetProvider.Get(Size size) - { - return _callback(size); - } + RenderTarget IRenderTargetProvider.Get(Size size) => _callback(size); public DisplayManagerRenderTargetProvider(Func callback) { @@ -73,7 +70,7 @@ protected DisplayManagerBase( _videoTextureFrugalizer = new(_gl); _shaderChainFrugalizers = new RenderTargetFrugalizer[16]; // hacky hardcoded limit.. need some other way to manage these - for (var i = 0; i < 16; i++) + for (int i = 0; i < 16; i++) { _shaderChainFrugalizers[i] = new(_gl); } @@ -90,20 +87,20 @@ protected DisplayManagerBase( if (dispMethod is EDispMethod.OpenGL or EDispMethod.D3D9) { - var fiHq2x = new FileInfo(Path.Combine(PathUtils.ExeDirectoryPath, "Shaders/BizHawk/hq2x.cgp")); + FileInfo fiHq2x = new(Path.Combine(PathUtils.ExeDirectoryPath, "Shaders/BizHawk/hq2x.cgp")); if (fiHq2x.Exists) { using var stream = fiHq2x.OpenRead(); _shaderChainHq2X = new(_gl, new(stream), Path.Combine(PathUtils.ExeDirectoryPath, "Shaders/BizHawk")); } - var fiScanlines = new FileInfo(Path.Combine(PathUtils.ExeDirectoryPath, "Shaders/BizHawk/BizScanlines.cgp")); + FileInfo fiScanlines = new(Path.Combine(PathUtils.ExeDirectoryPath, "Shaders/BizHawk/BizScanlines.cgp")); if (fiScanlines.Exists) { using var stream = fiScanlines.OpenRead(); _shaderChainScanlines = new(_gl, new(stream), Path.Combine(PathUtils.ExeDirectoryPath, "Shaders/BizHawk")); } - var bicubicPath = dispMethod == EDispMethod.D3D9 ? "Shaders/BizHawk/bicubic-normal.cgp" : "Shaders/BizHawk/bicubic-fast.cgp"; - var fiBicubic = new FileInfo(Path.Combine(PathUtils.ExeDirectoryPath, bicubicPath)); + string bicubicPath = dispMethod == EDispMethod.D3D9 ? "Shaders/BizHawk/bicubic-normal.cgp" : "Shaders/BizHawk/bicubic-fast.cgp"; + FileInfo fiBicubic = new(Path.Combine(PathUtils.ExeDirectoryPath, bicubicPath)); if (fiBicubic.Exists) { using var stream = fiBicubic.Open(FileMode.Open, FileAccess.Read, FileShare.Read); @@ -216,7 +213,7 @@ public void RefreshUserShader() _shaderChainUser?.Dispose(); if (File.Exists(GlobalConfig.DispUserFilterPath)) { - var fi = new FileInfo(GlobalConfig.DispUserFilterPath); + FileInfo fi = new(GlobalConfig.DispUserFilterPath); using var stream = fi.OpenRead(); _shaderChainUser = new(_gl, new(stream), Path.GetDirectoryName(GlobalConfig.DispUserFilterPath)); } @@ -256,14 +253,14 @@ public void RefreshUserShader() private (int Horizontal, int Vertical) CalculateCompleteContentPaddingSum(bool user, bool source) { - var p = CalculateCompleteContentPadding(user: user, source: source); - return (p.Left + p.Right, p.Top + p.Bottom); + var (Left, Top, Right, Bottom) = CalculateCompleteContentPadding(user: user, source: source); + return (Left + Right, Top + Bottom); } private FilterProgram BuildDefaultChain(Size chainInSize, Size chainOutSize, bool includeOSD, bool includeUserFilters) { // select user special FX shader chain - var selectedChainProperties = new Dictionary(); + Dictionary selectedChainProperties = new(); RetroShaderChain selectedChain = null; switch (GlobalConfig.TargetDisplayFilter) { @@ -286,11 +283,11 @@ private FilterProgram BuildDefaultChain(Size chainInSize, Size chainOutSize, boo var fCoreScreenControl = CreateCoreScreenControl(); - var fPresent = new FinalPresentation(chainOutSize); - var fInput = new SourceImage(chainInSize); - var fOSD = new OSD(includeOSD, OSD, _theOneFont); + FinalPresentation fPresent = new(chainOutSize); + SourceImage fInput = new(chainInSize); + OSD fOSD = new(includeOSD, OSD, _theOneFont); - var chain = new FilterProgram(); + FilterProgram chain = new(); //add the first filter, encompassing output from the emulator core chain.AddFilter(fInput, "input"); @@ -317,7 +314,7 @@ private FilterProgram BuildDefaultChain(Size chainInSize, Size chainOutSize, boo if (size.Width < 1) size.Width = 1; if (size.Height < 1) size.Height = 1; - var fPadding = new FinalPresentation(size); + FinalPresentation fPadding = new(size); chain.AddFilter(fPadding, "padding"); fPadding.Config_PadOnly = true; fPadding.Padding = padding; @@ -330,7 +327,7 @@ private FilterProgram BuildDefaultChain(Size chainInSize, Size chainOutSize, boo { if (GlobalConfig.DispPrescale != 1) { - var fPrescale = new PrescaleFilter() { Scale = GlobalConfig.DispPrescale }; + PrescaleFilter fPrescale = new() { Scale = GlobalConfig.DispPrescale }; chain.AddFilter(fPrescale, "user_prescale"); } } @@ -344,7 +341,7 @@ private FilterProgram BuildDefaultChain(Size chainInSize, Size chainOutSize, boo // AutoPrescale makes no sense for a None final filter if (GlobalConfig.DispAutoPrescale && GlobalConfig.DispFinalFilter != (int)FinalPresentation.eFilterOption.None) { - var apf = new AutoPrescaleFilter(); + AutoPrescaleFilter apf = new(); chain.AddFilter(apf, "auto_prescale"); } @@ -392,10 +389,10 @@ private FilterProgram BuildDefaultChain(Size chainInSize, Size chainOutSize, boo private static void AppendRetroShaderChain(FilterProgram program, string name, RetroShaderChain retroChain, Dictionary properties) { - for (var i = 0; i < retroChain.Passes.Length; i++) + for (int i = 0; i < retroChain.Passes.Length; i++) { - var rsp = new RetroShaderPass(retroChain, i); - var fname = $"{name}[{i}]"; + RetroShaderPass rsp = new(retroChain, i); + string fname = $"{name}[{i}]"; program.AddFilter(rsp, fname); rsp.Parameters = properties; } @@ -410,7 +407,7 @@ private void AppendApiHawkLayer(FilterProgram chain, DisplaySurfaceID surfaceID) } var luaNativeTexture = _apiHawkSurfaceFrugalizers[surfaceID].Get(luaNativeSurface); - var fLuaLayer = new LuaLayer(); + LuaLayer fLuaLayer = new(); fLuaLayer.SetTexture(luaNativeTexture); chain.AddFilter(fLuaLayer, surfaceID.GetName()); } @@ -429,7 +426,7 @@ public Point UntransformPoint(Point p) if (_currentFilterProgram == null) return p; // otherwise, have the filter program untransform it - var v = new Vector2(p.X, p.Y); + Vector2 v = new(p.X, p.Y); v = _currentFilterProgram.UntransformPoint("default", v); return new((int)v.X, (int)v.Y); @@ -447,7 +444,7 @@ public Point TransformPoint(Point p) } // otherwise, have the filter program untransform it - var v = new Vector2(p.X, p.Y); + Vector2 v = new(p.X, p.Y); v = _currentFilterProgram.TransformPoint("default", v); return new((int)v.X, (int)v.Y); } @@ -462,8 +459,8 @@ public Point TransformPoint(Point p) /// public void UpdateSource(IVideoProvider videoProvider) { - var displayNothing = GlobalConfig.DispSpeedupFeatures == 0; - var job = new JobInfo + bool displayNothing = GlobalConfig.DispSpeedupFeatures == 0; + JobInfo job = new() { VideoProvider = videoProvider, Simulate = displayNothing, @@ -490,7 +487,7 @@ private BaseFilter CreateCoreScreenControl() /// public BitmapBuffer RenderOffscreen(IVideoProvider videoProvider, bool includeOSD) { - var job = new JobInfo + JobInfo job = new() { VideoProvider = videoProvider, Simulate = false, @@ -508,7 +505,7 @@ public BitmapBuffer RenderOffscreen(IVideoProvider videoProvider, bool includeOS /// public BitmapBuffer RenderOffscreenLua(IVideoProvider videoProvider) { - var job = new JobInfo + JobInfo job = new() { VideoProvider = videoProvider, Simulate = false, @@ -547,7 +544,7 @@ public int[] GetVideoBuffer() private static void FixRatio(float x, float y, int inw, int inh, out int outW, out int outH) { - var ratio = x / y; + float ratio = x / y; if (ratio <= 1) { // taller. weird. expand height. @@ -569,17 +566,17 @@ private static void FixRatio(float x, float y, int inw, int inh, out int outW, o /// public Size CalculateClientSize(IVideoProvider videoProvider, int zoom) { - var arActive = GlobalConfig.DispFixAspectRatio; - var arSystem = GlobalConfig.DispManagerAR == EDispManagerAR.System; - var arCustom = GlobalConfig.DispManagerAR == EDispManagerAR.CustomSize; - var arCustomRatio = GlobalConfig.DispManagerAR == EDispManagerAR.CustomRatio; - var arCorrect = arSystem || arCustom || arCustomRatio; - var arInteger = GlobalConfig.DispFixScaleInteger; - - var bufferWidth = videoProvider.BufferWidth; - var bufferHeight = videoProvider.BufferHeight; - var virtualWidth = videoProvider.VirtualWidth; - var virtualHeight = videoProvider.VirtualHeight; + bool arActive = GlobalConfig.DispFixAspectRatio; + bool arSystem = GlobalConfig.DispManagerAR == EDispManagerAR.System; + bool arCustom = GlobalConfig.DispManagerAR == EDispManagerAR.CustomSize; + bool arCustomRatio = GlobalConfig.DispManagerAR == EDispManagerAR.CustomRatio; + bool arCorrect = arSystem || arCustom || arCustomRatio; + bool arInteger = GlobalConfig.DispFixScaleInteger; + + int bufferWidth = videoProvider.BufferWidth; + int bufferHeight = videoProvider.BufferHeight; + int virtualWidth = videoProvider.VirtualWidth; + int virtualHeight = videoProvider.VirtualHeight; if (arCustom) { @@ -620,7 +617,7 @@ public Size CalculateClientSize(IVideoProvider videoProvider, int zoom) if (bufferHeight < 1) bufferHeight = 1; // old stuff - var fvp = new FakeVideoProvider(bufferWidth, bufferHeight, virtualWidth, virtualHeight); + FakeVideoProvider fvp = new(bufferWidth, bufferHeight, virtualWidth, virtualHeight); Size chainOutsize; if (arActive) @@ -630,8 +627,8 @@ public Size CalculateClientSize(IVideoProvider videoProvider, int zoom) if (arInteger) { // ALERT COPYPASTE LAUNDROMAT - var AR = new Vector2(virtualWidth / (float) bufferWidth, virtualHeight / (float) bufferHeight); - var targetPar = AR.X / AR.Y; + Vector2 AR = new(virtualWidth / (float) bufferWidth, virtualHeight / (float) bufferHeight); + 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 @@ -644,19 +641,19 @@ public Size CalculateClientSize(IVideoProvider videoProvider, int zoom) // TODO - also, this might be messing up zooms and stuff, we might need to run this on the output size of the filter chain Span trials = stackalloc Vector2[3]; - for (var i = 1; i < zoom; i++) + 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. trials[0] = PS + Vector2.UnitX; trials[1] = PS + Vector2.UnitY; trials[2] = PS + Vector2.One; - var bestIndex = -1; - var bestValue = 1000.0f; - for (var t = 0; t < trials.Length; t++) + int bestIndex = -1; + float bestValue = 1000.0f; + for (int t = 0; t < trials.Length; t++) { //I. - var testAr = trials[t].X / trials[t].Y; + float testAr = trials[t].X / trials[t].Y; // II. // var calc = Vector2.Multiply(trials[t], VS); @@ -664,7 +661,7 @@ public Size CalculateClientSize(IVideoProvider videoProvider, int zoom) // not clear which approach is superior - var deviationLinear = Math.Abs(testAr - targetPar); + float deviationLinear = Math.Abs(testAr - targetPar); if (deviationLinear < bestValue) { bestIndex = t; @@ -705,7 +702,7 @@ public Size CalculateClientSize(IVideoProvider videoProvider, int zoom) chainOutsize.Width += ClientExtraPadding.Left + ClientExtraPadding.Right; chainOutsize.Height += ClientExtraPadding.Top + ClientExtraPadding.Bottom; - var job = new JobInfo + JobInfo job = new() { VideoProvider = fvp, Simulate = true, @@ -763,16 +760,16 @@ private FilterProgram UpdateSourceInternal(JobInfo job) } var videoProvider = job.VideoProvider; - var simulate = job.Simulate; + bool simulate = job.Simulate; var chainOutsize = job.ChainOutsize; - var bufferWidth = videoProvider.BufferWidth; - var bufferHeight = videoProvider.BufferHeight; - var presenterTextureWidth = bufferWidth; - var presenterTextureHeight = bufferHeight; + int bufferWidth = videoProvider.BufferWidth; + int bufferHeight = videoProvider.BufferHeight; + int presenterTextureWidth = bufferWidth; + int presenterTextureHeight = bufferHeight; - var vw = videoProvider.VirtualWidth; - var vh = videoProvider.VirtualHeight; + int vw = videoProvider.VirtualWidth; + int vh = videoProvider.VirtualHeight; // TODO: it is bad that this is happening outside the filter chain // the filter chain has the ability to add padding... @@ -811,9 +808,9 @@ private FilterProgram UpdateSourceInternal(JobInfo job) } } - var padding = CalculateCompleteContentPaddingSum(true,false); - vw += padding.Horizontal; - vh += padding.Vertical; + var (Horizontal, Vertical) = CalculateCompleteContentPaddingSum(true,false); + vw += Horizontal; + vh += Vertical; //in case the user requested so much padding that the dimensions are now negative, just turn it to something small. if (vw < 1) vw = 1; @@ -847,18 +844,18 @@ private FilterProgram UpdateSourceInternal(JobInfo job) _currEmuHeight = bufferHeight; //build the default filter chain and set it up with services filters will need - var chainInsize = new Size(bufferWidth, bufferHeight); + Size chainInsize = new(bufferWidth, bufferHeight); var filterProgram = BuildDefaultChain(chainInsize, chainOutsize, job.IncludeOSD, job.IncludeUserFilters); filterProgram.GuiRenderer = _renderer; filterProgram.GL = _gl; //setup the source image filter - var fInput = (SourceImage)filterProgram["input"]; + SourceImage fInput = (SourceImage)filterProgram["input"]; fInput.Texture = videoTexture; //setup the final presentation filter - var fPresent = (FinalPresentation)filterProgram["presentation"]; + FinalPresentation fPresent = (FinalPresentation)filterProgram["presentation"]; if (fPresent != null) { fPresent.VirtualTextureSize = new(vw, vh); @@ -906,7 +903,7 @@ protected virtual void UpdateSourceDrawingWork(JobInfo job) //GraphicsControl.Begin(); // CRITICAL POINT for yabause+GL //TODO - auto-create and age these (and dispose when old) - var rtCounter = 0; + int rtCounter = 0; // ReSharper disable once AccessToModifiedClosure _currentFilterProgram.RenderTargetProvider = new DisplayManagerRenderTargetProvider(size => _shaderChainFrugalizers[rtCounter++].Get(size)); @@ -954,7 +951,7 @@ private void LoadCustomFont(Stream fontStream) var data = Marshal.AllocCoTaskMem((int)fontStream.Length); try { - var fontData = new byte[fontStream.Length]; + byte[] fontData = new byte[fontStream.Length]; fontStream.Read(fontData, 0, (int)fontStream.Length); Marshal.Copy(fontData, 0, data, (int)fontStream.Length); CustomFonts.AddMemoryFont(data, fontData.Length); diff --git a/src/BizHawk.Client.Common/DisplayManager/DisplaySurface.cs b/src/BizHawk.Client.Common/DisplayManager/DisplaySurface.cs index e170efdbf0b..a4f97836101 100644 --- a/src/BizHawk.Client.Common/DisplayManager/DisplaySurface.cs +++ b/src/BizHawk.Client.Common/DisplayManager/DisplaySurface.cs @@ -21,15 +21,9 @@ public void Clear() _bmp.UnlockBits(bmpData); } - public Bitmap PeekBitmap() - { - return _bmp; - } + public Bitmap PeekBitmap() => _bmp; - public Graphics GetGraphics() - { - return Graphics.FromImage(_bmp); - } + public Graphics GetGraphics() => Graphics.FromImage(_bmp); public DisplaySurface(int width, int height) { diff --git a/src/BizHawk.Client.Common/DisplayManager/FilterManager.cs b/src/BizHawk.Client.Common/DisplayManager/FilterManager.cs index 903e1d936a6..16a9c226f1a 100644 --- a/src/BizHawk.Client.Common/DisplayManager/FilterManager.cs +++ b/src/BizHawk.Client.Common/DisplayManager/FilterManager.cs @@ -71,10 +71,7 @@ public enum ProgramStepType public RenderTarget CurrRenderTarget; - public RenderTarget GetTempTarget(int width, int height) - { - return RenderTargetProvider.Get(new(width, height)); - } + public RenderTarget GetTempTarget(int width, int height) => RenderTargetProvider.Get(new(width, height)); public void AddFilter(BaseFilter filter, string name = "") { @@ -87,7 +84,7 @@ public void AddFilter(BaseFilter filter, string name = "") /// public Vector2 UntransformPoint(string channel, Vector2 point) { - for (var i = Filters.Count - 1; i >= 0; i--) + for (int i = Filters.Count - 1; i >= 0; i--) { var filter = Filters[i]; point = filter.UntransformPoint(channel, point); @@ -160,16 +157,16 @@ public void Compile(string channel, Size inSize, Size outsize, bool finalTarget) // propagate output size backwards through filter chain to allow a 'flex' filter to determine its output based on the desired output needs presize = outsize; - for (var i = Filters.Count - 1; i >= 0; i--) + for (int i = Filters.Count - 1; i >= 0; i--) { var filter = Filters[i]; presize = filter.PresizeOutput(channel, presize); } - var obtainedFirstOutput = false; - var currState = new SurfaceState(null); + bool obtainedFirstOutput = false; + SurfaceState currState = new(null); - for (var i = 0; i < Filters.Count; i++) + for (int i = 0; i < Filters.Count; i++) { var f = Filters[i]; @@ -196,7 +193,7 @@ public void Compile(string channel, Size inSize, Size outsize, bool finalTarget) // (if so, insert a render filter) case SurfaceDisposition.RenderTarget when currState.SurfaceDisposition == SurfaceDisposition.Texture: { - var renderer = new Render(); + Render renderer = new(); Filters.Insert(i, renderer); Compile(channel, inSize, outsize, finalTarget); return; @@ -205,7 +202,7 @@ public void Compile(string channel, Size inSize, Size outsize, bool finalTarget) // (if so, the current render target gets resolved, and made no longer current case SurfaceDisposition.Texture when currState.SurfaceDisposition == SurfaceDisposition.RenderTarget: { - var resolver = new Resolve(); + Resolve resolver = new(); Filters.Insert(i, resolver); Compile(channel, inSize, outsize, finalTarget); return; @@ -233,7 +230,7 @@ public void Compile(string channel, Size inSize, Size outsize, bool finalTarget) iosi.SurfaceDisposition = currState.SurfaceDisposition; } - var newTarget = false; + bool newTarget = false; if (iosi.SurfaceFormat.Size != currState.SurfaceFormat.Size) { newTarget = true; @@ -267,7 +264,7 @@ public void Compile(string channel, Size inSize, Size outsize, bool finalTarget) // if the current output disposition is a texture, we need to render it if (currState.SurfaceDisposition == SurfaceDisposition.Texture) { - var renderer = new Render(); + Render renderer = new(); Filters.Insert(Filters.Count, renderer); Compile(channel, inSize, outsize, finalTarget); return; @@ -276,12 +273,12 @@ public void Compile(string channel, Size inSize, Size outsize, bool finalTarget) // patch the program so that the final RenderTarget set operation is the framebuffer instead if (finalTarget) { - for (var i = Program.Count - 1; i >= 0; i--) + for (int i = Program.Count - 1; i >= 0; i--) { var ps = Program[i]; if (ps.Type == ProgramStepType.NewTarget) { - var size = (Size)ps.Args; + Size size = (Size)ps.Args; Debug.Assert(size == outsize); Program[i] = new(ProgramStepType.FinalTarget, size, ps.Comment); break; diff --git a/src/BizHawk.Client.Common/DisplayManager/Filters/BaseFilter.cs b/src/BizHawk.Client.Common/DisplayManager/Filters/BaseFilter.cs index a373513ad3e..afabab3e368 100644 --- a/src/BizHawk.Client.Common/DisplayManager/Filters/BaseFilter.cs +++ b/src/BizHawk.Client.Common/DisplayManager/Filters/BaseFilter.cs @@ -74,10 +74,7 @@ public virtual Vector2 TransformPoint(string channel, Vector2 point) return point; } - public void SetInput(Texture2d tex) - { - InputTexture = tex; - } + public void SetInput(Texture2d tex) => InputTexture = tex; public virtual void Run() { @@ -87,10 +84,7 @@ public Texture2d GetOutput() => _outputTexture; // filter actions - protected void YieldOutput(Texture2d tex) - { - _outputTexture = tex; - } + protected void YieldOutput(Texture2d tex) => _outputTexture = tex; protected FilterProgram FilterProgram; protected Texture2d InputTexture; @@ -100,21 +94,12 @@ protected void YieldOutput(Texture2d tex) /// Indicate a 'RenderTarget' disposition if you want to draw directly to the input /// Indicate a 'Texture' disposition if you want to use it to draw to a newly allocated render target /// - protected IOSurfaceInfo DeclareInput(SurfaceDisposition disposition = SurfaceDisposition.Unspecified, string channel = "default") - { - return DeclareIO(SurfaceDirection.Input, channel, disposition); - } + protected IOSurfaceInfo DeclareInput(SurfaceDisposition disposition = SurfaceDisposition.Unspecified, string channel = "default") => DeclareIO(SurfaceDirection.Input, channel, disposition); - protected IOSurfaceInfo DeclareOutput(SurfaceDisposition disposition = SurfaceDisposition.Unspecified, string channel = "default") - { - return DeclareIO(SurfaceDirection.Output, channel, disposition); - } + protected IOSurfaceInfo DeclareOutput(SurfaceDisposition disposition = SurfaceDisposition.Unspecified, string channel = "default") => DeclareIO(SurfaceDirection.Output, channel, disposition); // TODO - why a different param order than DeclareOutput? - protected RenderTarget GetTempTarget(int width, int height) - { - return FilterProgram.GetTempTarget(width, height); - } + protected RenderTarget GetTempTarget(int width, int height) => FilterProgram.GetTempTarget(width, height); protected IOSurfaceInfo DeclareOutput(SurfaceState state, string channel = "default") { @@ -123,19 +108,13 @@ protected IOSurfaceInfo DeclareOutput(SurfaceState state, string channel = "defa return iosi; } - public IOSurfaceInfo FindInput(string channel = "default") - { - return FindIOSurfaceInfo(channel, SurfaceDirection.Input); - } + public IOSurfaceInfo FindInput(string channel = "default") => FindIOSurfaceInfo(channel, SurfaceDirection.Input); - public IOSurfaceInfo FindOutput(string channel = "default") - { - return FindIOSurfaceInfo(channel, SurfaceDirection.Output); - } + public IOSurfaceInfo FindOutput(string channel = "default") => FindIOSurfaceInfo(channel, SurfaceDirection.Output); private IOSurfaceInfo DeclareIO(SurfaceDirection direction, string channel, SurfaceDisposition disposition) { - var iosi = new IOSurfaceInfo + IOSurfaceInfo iosi = new() { SurfaceDirection = direction, Channel = channel, @@ -149,10 +128,7 @@ private IOSurfaceInfo DeclareIO(SurfaceDirection direction, string channel, Surf private readonly List _ioSurfaceInfos = new(); - private IOSurfaceInfo FindIOSurfaceInfo(string channel, SurfaceDirection direction) - { - return _ioSurfaceInfos.Find(iosi => iosi.Channel == channel && iosi.SurfaceDirection == direction); - } + private IOSurfaceInfo FindIOSurfaceInfo(string channel, SurfaceDirection direction) => _ioSurfaceInfos.Find(iosi => iosi.Channel == channel && iosi.SurfaceDirection == direction); public class IOSurfaceInfo { diff --git a/src/BizHawk.Client.Common/DisplayManager/Filters/Gui.cs b/src/BizHawk.Client.Common/DisplayManager/Filters/Gui.cs index 060ed3a95d4..2e123a43bb0 100644 --- a/src/BizHawk.Client.Common/DisplayManager/Filters/Gui.cs +++ b/src/BizHawk.Client.Common/DisplayManager/Filters/Gui.cs @@ -36,14 +36,14 @@ public LetterboxingLogic() // do maths on the viewport and the native resolution and the user settings to get a display rectangle public LetterboxingLogic(bool maintainAspect, bool maintainInteger, int targetWidth, int targetHeight, int sourceWidth, int sourceHeight, Size textureSize, Size virtualSize) { - var textureWidth = textureSize.Width; - var textureHeight = textureSize.Height; - var virtualWidth = virtualSize.Width; - var virtualHeight = virtualSize.Height; + int textureWidth = textureSize.Width; + int textureHeight = textureSize.Height; + int virtualWidth = virtualSize.Width; + int virtualHeight = virtualSize.Height; // zero 02-jun-2014 - we passed these in, but ignored them. kind of weird.. - var oldSourceWidth = sourceWidth; - var oldSourceHeight = sourceHeight; + int oldSourceWidth = sourceWidth; + int oldSourceHeight = sourceHeight; sourceWidth = virtualWidth; sourceHeight = virtualHeight; @@ -53,8 +53,8 @@ public LetterboxingLogic(bool maintainAspect, bool maintainInteger, int targetWi maintainInteger = false; } - var widthScale = (float)targetWidth / sourceWidth; - var heightScale = (float)targetHeight / sourceHeight; + float widthScale = (float)targetWidth / sourceWidth; + float heightScale = (float)targetHeight / sourceHeight; if (maintainAspect // zero 20-jul-2014 - hacks upon hacks, this function needs rewriting @@ -71,8 +71,8 @@ public LetterboxingLogic(bool maintainAspect, bool maintainInteger, int targetWi // apply the zooming algorithm (pasted and reworked, for now) // ALERT COPYPASTE LAUNDROMAT - var AR = new Vector2(virtualWidth / (float) textureWidth, virtualHeight / (float) textureHeight); - var targetPar = AR.X / AR.Y; + Vector2 AR = new(virtualWidth / (float) textureWidth, virtualHeight / (float) textureHeight); + float targetPar = AR.X / AR.Y; var PS = Vector2.One; // this would malfunction for AR <= 0.5 or AR >= 2.0 Span trials = stackalloc Vector2[3]; @@ -84,21 +84,21 @@ public LetterboxingLogic(bool maintainAspect, bool maintainInteger, int targetWi trials[1] = PS + Vector2.UnitY; trials[2] = PS + Vector2.One; - var bestIndex = -1; - var bestValue = 1000.0f; - for (var t = 0; t < trials.Length; t++) + int bestIndex = -1; + float bestValue = 1000.0f; + for (int t = 0; t < trials.Length; t++) { var vTrial = trials[t]; trialsLimited[t] = false; //check whether this is going to exceed our allotted area - var testVw = (int)(vTrial.X * textureWidth); - var testVh = (int)(vTrial.Y * textureHeight); + int testVw = (int)(vTrial.X * textureWidth); + int testVh = (int)(vTrial.Y * textureHeight); if (testVw > targetWidth) trialsLimited[t] = true; if (testVh > targetHeight) trialsLimited[t] = true; // I. - var testAr = vTrial.X / vTrial.Y; + float testAr = vTrial.X / vTrial.Y; // II. // var calc = Vector2.Multiply(trials[t], VS); @@ -106,7 +106,7 @@ public LetterboxingLogic(bool maintainAspect, bool maintainInteger, int targetWi // not clear which approach is superior - var deviationLinear = Math.Abs(testAr - targetPar); + float deviationLinear = Math.Abs(testAr - targetPar); if (deviationLinear < bestValue) { bestIndex = t; @@ -202,11 +202,9 @@ public ScreenControlNDS(NDS nds) _nds = nds; } - public override void Initialize() - { + public override void Initialize() => //we're going to be blitting the source as pieces to a new render target, so we need our input to be a texture DeclareInput(SurfaceDisposition.Texture); - } private void CrunchNumbers() { @@ -238,7 +236,7 @@ private void CrunchNumbers() // this doesn't make any sense, it's likely to be too much for a monitor to gracefully handle too if (settings.ScreenLayout != NDS.ScreenLayoutKind.Horizontal) { - var rot = settings.ScreenRotation switch + int rot = settings.ScreenRotation switch { NDS.ScreenRotationKind.Rotate90 => 90, NDS.ScreenRotationKind.Rotate180 => 180, @@ -256,14 +254,14 @@ private void CrunchNumbers() matBot = bot.Top; // apply transforms from standard input screen positions to output screen positions - var top_TL = Vector2.Transform(new(0, 0), matTop); - var top_TR = Vector2.Transform(new(256, 0), matTop); - var top_BL = Vector2.Transform(new(0, 192), matTop); - var top_BR = Vector2.Transform(new(256, 192), matTop); - var bot_TL = Vector2.Transform(new(0, 0), matBot); - var bot_TR = Vector2.Transform(new(256, 0), matBot); - var bot_BL = Vector2.Transform(new(0, 192), matBot); - var bot_BR = Vector2.Transform(new(256, 192), matBot); + Vector2 top_TL = Vector2.Transform(new(0, 0), matTop); + Vector2 top_TR = Vector2.Transform(new(256, 0), matTop); + Vector2 top_BL = Vector2.Transform(new(0, 192), matTop); + Vector2 top_BR = Vector2.Transform(new(256, 192), matTop); + Vector2 bot_TL = Vector2.Transform(new(0, 0), matBot); + Vector2 bot_TR = Vector2.Transform(new(256, 0), matBot); + Vector2 bot_BL = Vector2.Transform(new(0, 192), matBot); + Vector2 bot_BR = Vector2.Transform(new(256, 192), matBot); // in case of math errors in the transforms, we'll round this stuff.. although... // we're gonna use matrix transforms for drawing later, so it isn't extremely helpful @@ -315,7 +313,7 @@ private void CrunchNumbers() fixed (Matrix4x4* matTopP = &matTop, matBotP = &matBot) { float* matTopF = (float*)matTopP, matBotF = (float*)matBotP; - for (var i = 0; i < 4 * 4; i++) + for (int i = 0; i < 4 * 4; i++) { if (Math.Abs(matTopF[i]) < 0.0000001f) { @@ -351,14 +349,14 @@ public override Size PresizeOutput(string channel, Size size) public override void SetInputFormat(string channel, SurfaceState state) { CrunchNumbers(); - var ss = new SurfaceState(new(outputSize), SurfaceDisposition.RenderTarget); + SurfaceState ss = new(new(outputSize), SurfaceDisposition.RenderTarget); DeclareOutput(ss, channel); } public override Vector2 UntransformPoint(string channel, Vector2 point) { var settings = _nds.GetSettings(); - var invert = settings.ScreenInvert + bool invert = settings.ScreenInvert && settings.ScreenLayout != NDS.ScreenLayoutKind.Top && settings.ScreenLayout != NDS.ScreenLayoutKind.Bottom; @@ -380,10 +378,7 @@ public override Vector2 UntransformPoint(string channel, Vector2 point) return point; } - public override Vector2 TransformPoint(string channel, Vector2 point) - { - return Vector2.Transform(point, matTop); - } + public override Vector2 TransformPoint(string channel, Vector2 point) => Vector2.Transform(point, matTop); public override void Run() { @@ -406,8 +401,8 @@ public override void Run() InputTexture.SetFilterNearest(); //draw screens - var renderTop = false; - var renderBottom = false; + bool renderTop = false; + bool renderBottom = false; var settings = _nds.GetSettings(); switch (settings.ScreenLayout) { @@ -425,7 +420,7 @@ public override void Run() throw new InvalidOperationException(); } - var invert = settings.ScreenInvert && renderTop && renderBottom; + bool invert = settings.ScreenInvert && renderTop && renderBottom; if (renderTop) { @@ -466,9 +461,9 @@ public override Vector2 UntransformPoint(string channel, Vector2 point) if (_citra.TouchScreenEnabled) { var rect = _citra.TouchScreenRectangle; - var rotated = _citra.TouchScreenRotated; - var bufferWidth = (float)_citra.AsVideoProvider().BufferWidth; - var bufferHeight = (float)_citra.AsVideoProvider().BufferHeight; + bool rotated = _citra.TouchScreenRotated; + float bufferWidth = _citra.AsVideoProvider().BufferWidth; + float bufferHeight = _citra.AsVideoProvider().BufferHeight; // reset the point's origin to the top left of the screen point.X -= rect.X; @@ -498,7 +493,7 @@ public override Vector2 TransformPoint(string channel, Vector2 point) if (_citra.TouchScreenEnabled) { var rect = _citra.TouchScreenRectangle; - var rotated = _citra.TouchScreenRotated; + bool rotated = _citra.TouchScreenRotated; if (rotated) { @@ -588,7 +583,7 @@ public override Size PresizeInput(string channel, Size size) public override void SetInputFormat(string channel, SurfaceState state) { - var need = state.SurfaceFormat.Size != OutputSize || FilterOption != eFilterOption.None; + bool need = state.SurfaceFormat.Size != OutputSize || FilterOption != eFilterOption.None; if (!need) { Nop = true; @@ -611,8 +606,8 @@ public override void SetInputFormat(string channel, SurfaceState state) } else { - var ow = OutputSize.Width; - var oh = OutputSize.Height; + int ow = OutputSize.Width; + int oh = OutputSize.Height; ow -= Padding.Left + Padding.Right; oh -= Padding.Top + Padding.Bottom; LL = new(Config_FixAspectRatio, Config_FixScaleInteger, ow, oh, InputSize.Width, InputSize.Height, TextureSize, VirtualTextureSize); @@ -690,17 +685,14 @@ public class PrescaleFilter : BaseFilter { public int Scale; - public override void Initialize() - { - DeclareInput(SurfaceDisposition.Texture); - } + public override void Initialize() => DeclareInput(SurfaceDisposition.Texture); public override void SetInputFormat(string channel, SurfaceState state) { var outputSize = state.SurfaceFormat.Size; outputSize.Width *= Scale; outputSize.Height *= Scale; - var ss = new SurfaceState(new(outputSize), SurfaceDisposition.RenderTarget); + SurfaceState ss = new(new(outputSize), SurfaceDisposition.RenderTarget); DeclareOutput(ss, channel); } @@ -720,10 +712,7 @@ public class AutoPrescaleFilter : BaseFilter private Size OutputSize; private int XIS, YIS; - public override void Initialize() - { - DeclareInput(SurfaceDisposition.Texture); - } + public override void Initialize() => DeclareInput(SurfaceDisposition.Texture); public override void SetInputFormat(string channel, SurfaceState state) { @@ -755,10 +744,7 @@ public override Size PresizeOutput(string channel, Size size) return base.PresizeOutput(channel, size); } - public override Size PresizeInput(string channel, Size inSize) - { - return inSize; - } + public override Size PresizeInput(string channel, Size inSize) => inSize; public override void Run() { @@ -773,22 +759,13 @@ public override void Run() /// More accurately, ApiHawkLayer, since the gui Lua library is delegated. public class LuaLayer : BaseFilter { - public override void Initialize() - { - DeclareInput(SurfaceDisposition.RenderTarget); - } + public override void Initialize() => DeclareInput(SurfaceDisposition.RenderTarget); - public override void SetInputFormat(string channel, SurfaceState state) - { - DeclareOutput(state); - } + public override void SetInputFormat(string channel, SurfaceState state) => DeclareOutput(state); private Texture2d _texture; - public void SetTexture(Texture2d tex) - { - _texture = tex; - } + public void SetTexture(Texture2d tex) => _texture = tex; public override void Run() { @@ -816,15 +793,9 @@ public OSD(bool drawOsd, OSDManager manager, StringRenderer font) _font = font; } - public override void Initialize() - { - DeclareInput(SurfaceDisposition.RenderTarget); - } + public override void Initialize() => DeclareInput(SurfaceDisposition.RenderTarget); - public override void SetInputFormat(string channel, SurfaceState state) - { - DeclareOutput(state); - } + public override void SetInputFormat(string channel, SurfaceState state) => DeclareOutput(state); public override void Run() { @@ -836,7 +807,7 @@ public override void Run() var size = FindInput().SurfaceFormat.Size; FilterProgram.GuiRenderer.Begin(size.Width, size.Height); - var blitter = new OSDBlitter(_font, FilterProgram.GuiRenderer, new(0, 0, size.Width, size.Height)); + OSDBlitter blitter = new(_font, FilterProgram.GuiRenderer, new(0, 0, size.Width, size.Height)); FilterProgram.GuiRenderer.EnableBlending(); _manager.DrawScreenInfo(blitter); _manager.DrawMessages(blitter); diff --git a/src/BizHawk.Client.Common/DisplayManager/Filters/Retro.cs b/src/BizHawk.Client.Common/DisplayManager/Filters/Retro.cs index 627b29035be..0e49bb7c0b8 100644 --- a/src/BizHawk.Client.Common/DisplayManager/Filters/Retro.cs +++ b/src/BizHawk.Client.Common/DisplayManager/Filters/Retro.cs @@ -32,9 +32,9 @@ private static string ResolveIncludes(string content, string baseDirectory) return content; } - var fname = match.Groups[4].Value; + string fname = match.Groups[4].Value; fname = Path.Combine(baseDirectory,fname); - var includedContent = ResolveIncludes(File.ReadAllText(fname),Path.GetDirectoryName(fname)); + string includedContent = ResolveIncludes(File.ReadAllText(fname),Path.GetDirectoryName(fname)); content = content.Substring(0, match.Index) + includedContent + content.Substring(match.Index + match.Length); } } @@ -52,12 +52,12 @@ public RetroShaderChain(IGL owner, RetroShaderPreset preset, string baseDirector } // load up the shaders - var shaders = new RetroShader[preset.Passes.Count]; - for (var i = 0; i < preset.Passes.Count; i++) + RetroShader[] shaders = new RetroShader[preset.Passes.Count]; + for (int i = 0; i < preset.Passes.Count; i++) { // acquire content. we look for it in any reasonable filename so that one preset can bind to multiple shaders string content; - var path = Path.Combine(baseDirectory, preset.Passes[i].ShaderPath); + string path = Path.Combine(baseDirectory, preset.Passes[i].ShaderPath); if (!File.Exists(path)) { if (!Path.HasExtension(path)) @@ -136,14 +136,14 @@ public class RetroShaderPreset /// public RetroShaderPreset(Stream stream) { - var content = new StreamReader(stream).ReadToEnd(); - var dict = new Dictionary(); + string content = new StreamReader(stream).ReadToEnd(); + Dictionary dict = new(); // parse the key-value-pair format of the file content = content.Replace("\r", ""); - foreach (var splitLine in content.Split('\n')) + foreach (string splitLine in content.Split('\n')) { - var line = splitLine.Trim(); + string line = splitLine.Trim(); if (line.Length is 0) { continue; @@ -154,10 +154,10 @@ public RetroShaderPreset(Stream stream) continue; // comments } - var eq = line.IndexOf('='); - var key = line.Substring(0, eq).Trim(); - var value = line.Substring(eq + 1).Trim(); - var quote = value.IndexOf('\"'); + int eq = line.IndexOf('='); + string key = line.Substring(0, eq).Trim(); + string value = line.Substring(eq + 1).Trim(); + int quote = value.IndexOf('\"'); if (quote != -1) { value = value.Substring(quote + 1, value.IndexOf('\"', quote + 1) - (quote + 1)); @@ -165,7 +165,7 @@ public RetroShaderPreset(Stream stream) else { // remove comments from end of value. exclusive from above condition, since comments after quoted strings would be snipped by the quoted string extraction - var hash = value.IndexOf('#'); + int hash = value.IndexOf('#'); if (hash != -1) { value = value.Substring(0, hash); @@ -177,10 +177,10 @@ public RetroShaderPreset(Stream stream) } // process the keys - var nShaders = FetchInt(dict, "shaders", 0); - for (var i = 0; i < nShaders; i++) + int nShaders = FetchInt(dict, "shaders", 0); + for (int i = 0; i < nShaders; i++) { - var sp = new ShaderPass { Index = i }; + ShaderPass sp = new() { Index = i }; Passes.Add(sp); sp.InputFilterLinear = FetchBool(dict, $"filter_linear{i}", false); // Should this value not be defined, the filtering option is implementation defined. @@ -192,7 +192,7 @@ public RetroShaderPreset(Stream stream) // It is possible to set scale_type_xN and scale_type_yN to specialize the scaling type in either direction. scale_typeN however overrides both of these. sp.ScaleTypeX = (ScaleType)Enum.Parse(typeof(ScaleType), FetchString(dict, $"scale_type_x{i}", "Source"), true); sp.ScaleTypeY = (ScaleType)Enum.Parse(typeof(ScaleType), FetchString(dict, $"scale_type_y{i}", "Source"), true); - var st = (ScaleType)Enum.Parse(typeof(ScaleType), FetchString(dict, $"scale_type{i}", "NotSet"), true); + ScaleType st = (ScaleType)Enum.Parse(typeof(ScaleType), FetchString(dict, $"scale_type{i}", "NotSet"), true); if (st != ScaleType.NotSet) { sp.ScaleTypeX = sp.ScaleTypeY = st; @@ -229,25 +229,13 @@ public class ShaderPass public Vector2 Scale; } - private static string FetchString(IDictionary dict, string key, string @default) - { - return dict.TryGetValue(key, out var str) ? str : @default; - } + private static string FetchString(IDictionary dict, string key, string @default) => dict.TryGetValue(key, out string str) ? str : @default; - private static int FetchInt(IDictionary dict, string key, int @default) - { - return dict.TryGetValue(key, out var str) ? int.Parse(str) : @default; - } + private static int FetchInt(IDictionary dict, string key, int @default) => dict.TryGetValue(key, out string str) ? int.Parse(str) : @default; - private static float FetchFloat(IDictionary dict, string key, float @default) - { - return dict.TryGetValue(key, out var str) ? float.Parse(str, NumberFormatInfo.InvariantInfo) : @default; - } + private static float FetchFloat(IDictionary dict, string key, float @default) => dict.TryGetValue(key, out string str) ? float.Parse(str, NumberFormatInfo.InvariantInfo) : @default; - private static bool FetchBool(IDictionary dict, string key, bool @default) - { - return dict.TryGetValue(key, out var str) ? ParseBool(str) : @default; - } + private static bool FetchBool(IDictionary dict, string key, bool @default) => dict.TryGetValue(key, out string str) ? ParseBool(str) : @default; private static bool ParseBool(string value) { @@ -285,10 +273,7 @@ public RetroShaderPass(RetroShaderChain rsc, int index) _sp = _rsc.Passes[index]; } - public override void Initialize() - { - DeclareInput(SurfaceDisposition.Texture); - } + public override void Initialize() => DeclareInput(SurfaceDisposition.Texture); public override void SetInputFormat(string channel, SurfaceState state) { diff --git a/src/BizHawk.Client.Common/DisplayManager/Filters/Utils.cs b/src/BizHawk.Client.Common/DisplayManager/Filters/Utils.cs index 9dfa70aacb0..e25b037e9bd 100644 --- a/src/BizHawk.Client.Common/DisplayManager/Filters/Utils.cs +++ b/src/BizHawk.Client.Common/DisplayManager/Filters/Utils.cs @@ -16,20 +16,11 @@ public SourceImage(Size size) public Texture2d Texture { get; set; } - public override void Run() - { - YieldOutput(Texture); - } + public override void Run() => YieldOutput(Texture); - public override void Initialize() - { - DeclareOutput(new SurfaceState(new(_size), SurfaceDisposition.Texture)); - } + public override void Initialize() => DeclareOutput(new SurfaceState(new(_size), SurfaceDisposition.Texture)); - public override void SetInputFormat(string channel, SurfaceState format) - { - DeclareOutput(SurfaceDisposition.Texture); - } + public override void SetInputFormat(string channel, SurfaceState format) => DeclareOutput(SurfaceDisposition.Texture); } /// @@ -37,15 +28,9 @@ public override void SetInputFormat(string channel, SurfaceState format) /// public class Render : BaseFilter { - public override void Initialize() - { - DeclareInput(SurfaceDisposition.Texture); - } + public override void Initialize() => DeclareInput(SurfaceDisposition.Texture); - public override void SetInputFormat(string channel, SurfaceState state) - { - DeclareOutput(new SurfaceState(state.SurfaceFormat, SurfaceDisposition.RenderTarget)); - } + public override void SetInputFormat(string channel, SurfaceState state) => DeclareOutput(new SurfaceState(state.SurfaceFormat, SurfaceDisposition.RenderTarget)); public override void Run() { @@ -59,19 +44,10 @@ public override void Run() public class Resolve : BaseFilter { - public override void Initialize() - { - DeclareInput(SurfaceDisposition.RenderTarget); - } + public override void Initialize() => DeclareInput(SurfaceDisposition.RenderTarget); - public override void SetInputFormat(string channel, SurfaceState state) - { - DeclareOutput(new SurfaceState(state.SurfaceFormat, SurfaceDisposition.Texture)); - } + public override void SetInputFormat(string channel, SurfaceState state) => DeclareOutput(new SurfaceState(state.SurfaceFormat, SurfaceDisposition.Texture)); - public override void Run() - { - YieldOutput(FilterProgram.CurrRenderTarget.Texture2d); - } + public override void Run() => YieldOutput(FilterProgram.CurrRenderTarget.Texture2d); } } \ No newline at end of file diff --git a/src/BizHawk.Client.Common/DisplayManager/OSDManager.cs b/src/BizHawk.Client.Common/DisplayManager/OSDManager.cs index 11d930cd4e6..ac519d83ae3 100644 --- a/src/BizHawk.Client.Common/DisplayManager/OSDManager.cs +++ b/src/BizHawk.Client.Common/DisplayManager/OSDManager.cs @@ -55,7 +55,7 @@ private string MakeFrameCounter() { if (_movieSession.Movie.IsFinished()) { - var sb = new StringBuilder(); + StringBuilder sb = new(); sb .Append(_emulator.Frame) .Append('/') @@ -66,7 +66,7 @@ private string MakeFrameCounter() if (_movieSession.Movie.IsPlayingOrFinished()) { - var sb = new StringBuilder(); + StringBuilder sb = new(); sb .Append(_emulator.Frame) .Append('/') @@ -78,9 +78,9 @@ private string MakeFrameCounter() return _emulator.Frame.ToString(); } - private readonly List _messages = new List(5); - private readonly List _guiTextList = new List(); - private readonly List _ramWatchList = new List(); + private readonly List _messages = new(5); + private readonly List _guiTextList = new(); + private readonly List _ramWatchList = new(); public void AddMessage(string message, int? duration = null) => _messages.Add(new() { @@ -88,10 +88,7 @@ public void AddMessage(string message, int? duration = null) ExpireAt = DateTime.Now + TimeSpan.FromSeconds(duration ?? _config.OSDMessageDuration), }); - public void ClearRamWatches() - { - _ramWatchList.Clear(); - } + public void ClearRamWatches() => _ramWatchList.Clear(); public void AddRamWatch(string message, MessagePosition pos, Color backGround, Color foreColor) { @@ -115,15 +112,12 @@ public void AddGuiText(string message, MessagePosition pos, Color backGround, Co }); } - public void ClearGuiText() - { - _guiTextList.Clear(); - } + public void ClearGuiText() => _guiTextList.Clear(); private void DrawMessage(IBlitter g, UIMessage message, int yOffset) { var point = GetCoordinates(g, _config.Messages, message.Message); - var y = point.Y + yOffset; // TODO: clean me up + float y = point.Y + yOffset; // TODO: clean me up g.DrawString(message.Message, FixedMessagesColor, point.X, y); } @@ -174,15 +168,9 @@ public void DrawMessages(IBlitter g) } } - public string InputStrMovie() - { - return MakeStringFor(_movieSession.MovieController, cache: true); - } + public string InputStrMovie() => MakeStringFor(_movieSession.MovieController, cache: true); - public string InputStrImmediate() - { - return MakeStringFor(_inputManager.AutofireStickyXorAdapter, cache: true); - } + public string InputStrImmediate() => MakeStringFor(_inputManager.AutofireStickyXorAdapter, cache: true); public string InputPrevious() { @@ -235,10 +223,7 @@ public string MakeRerecordCount() : ""; } - private void DrawOsdMessage(IBlitter g, string message, Color color, float x, float y) - { - g.DrawString(message, color, x, y); - } + private void DrawOsdMessage(IBlitter g, string message, Color color, float x, float y) => g.DrawString(message, color, x, y); /// /// Display all screen info objects like fps, frame counter, lag counter, and input display @@ -259,12 +244,12 @@ public void DrawScreenInfo(IBlitter g) if (_config.DisplayInput) { - var moviePlaying = _movieSession.Movie.IsPlaying(); + bool moviePlaying = _movieSession.Movie.IsPlaying(); // After the last frame of the movie, we want both the last movie input and the current inputs. - var atMovieEnd = _movieSession.Movie.IsFinished() && _movieSession.Movie.IsAtEnd(); + bool atMovieEnd = _movieSession.Movie.IsFinished() && _movieSession.Movie.IsAtEnd(); if (moviePlaying || atMovieEnd) { - var input = InputStrMovie(); + string input = InputStrMovie(); var point = GetCoordinates(g, _config.InputDisplay, input); Color c = Color.FromArgb(_config.MovieInput); g.DrawString(input, c, point.X, point.Y); @@ -272,27 +257,27 @@ public void DrawScreenInfo(IBlitter g) if (!moviePlaying) // TODO: message config -- allow setting of "mixed", and "auto" { - var previousColor = Color.FromArgb(_config.LastInputColor); + Color previousColor = Color.FromArgb(_config.LastInputColor); Color immediateColor = Color.FromArgb(_config.MessagesColor); var autoColor = Color.Pink; var changedColor = Color.PeachPuff; //we need some kind of string for calculating position when right-anchoring, of something like that - var bgStr = InputStrOrAll(); + string bgStr = InputStrOrAll(); var point = GetCoordinates(g, _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(); + string previousStr = InputPrevious(); g.DrawString(previousStr, 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(); + string immediate = InputStrImmediate(); g.DrawString(immediate, immediateColor, point.X, point.Y); // next draw anything that's pressed because it's sticky. @@ -301,11 +286,11 @@ public void DrawScreenInfo(IBlitter g) // 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 // (adapter creation moved to InputManager) - var autoString = MakeStringFor(_inputManager.WeirdStickyControllerForInputDisplay, cache: true); + string autoString = MakeStringFor(_inputManager.WeirdStickyControllerForInputDisplay, cache: true); g.DrawString(autoString, autoColor, point.X, point.Y); //recolor everything that's changed from the previous input - var immediateOverlay = MakeIntersectImmediatePrevious(); + string immediateOverlay = MakeIntersectImmediatePrevious(); g.DrawString(immediateOverlay, changedColor, point.X, point.Y); } } @@ -318,7 +303,7 @@ public void DrawScreenInfo(IBlitter g) if (_config.DisplayLagCounter && _emulator.CanPollInput()) { - var counter = _emulator.AsInputPollable().LagCount.ToString(); + string counter = _emulator.AsInputPollable().LagCount.ToString(); var point = GetCoordinates(g, _config.LagCounter, counter); DrawOsdMessage(g, counter, FixedAlertMessageColor, point.X, point.Y); } @@ -332,7 +317,7 @@ public void DrawScreenInfo(IBlitter g) if (_inputManager.ClientControls["Autohold"] || _inputManager.ClientControls["Autofire"]) { - var sb = new StringBuilder("Held: "); + StringBuilder sb = new("Held: "); foreach (string sticky in _inputManager.StickyXorAdapter.CurrentStickies) { @@ -347,7 +332,7 @@ public void DrawScreenInfo(IBlitter g) .Append(' '); } - var message = sb.ToString(); + string message = sb.ToString(); var point = GetCoordinates(g, _config.Autohold, message); g.DrawString(message, Color.White, point.X, point.Y); } diff --git a/src/BizHawk.Client.Common/DisplayManager/RenderTargetFrugalizer.cs b/src/BizHawk.Client.Common/DisplayManager/RenderTargetFrugalizer.cs index f824969c568..69e3df93871 100644 --- a/src/BizHawk.Client.Common/DisplayManager/RenderTargetFrugalizer.cs +++ b/src/BizHawk.Client.Common/DisplayManager/RenderTargetFrugalizer.cs @@ -28,23 +28,17 @@ public void Dispose() ResetList(); } - private void ResetList() - { - _currentRenderTargets = new List { null, null }; - } + private void ResetList() => _currentRenderTargets = new List { null, null }; private readonly IGL _gl; private List _currentRenderTargets; - public RenderTarget Get(Size dimensions) - { - return Get(dimensions.Width, dimensions.Height); - } + public RenderTarget Get(Size dimensions) => Get(dimensions.Width, dimensions.Height); public RenderTarget Get(int width, int height) { //get the current entry - RenderTarget currentRenderTarget = _currentRenderTargets[0]; + var currentRenderTarget = _currentRenderTargets[0]; //check if its rotten and needs recreating if (currentRenderTarget == null diff --git a/src/BizHawk.Client.Common/DisplayManager/TextureFrugalizer.cs b/src/BizHawk.Client.Common/DisplayManager/TextureFrugalizer.cs index a084d8f5068..0d908108f8a 100644 --- a/src/BizHawk.Client.Common/DisplayManager/TextureFrugalizer.cs +++ b/src/BizHawk.Client.Common/DisplayManager/TextureFrugalizer.cs @@ -26,23 +26,20 @@ public void Dispose() ResetList(); } - private void ResetList() - { - _currentTextures = new List { null, null }; - } + private void ResetList() => _currentTextures = new List { null, null }; private readonly IGL _gl; private List _currentTextures; public Texture2d Get(IDisplaySurface ds) { - using var bb = new BitmapBuffer(ds.PeekBitmap(), new BitmapLoadOptions()); + using BitmapBuffer bb = new(ds.PeekBitmap(), new BitmapLoadOptions()); return Get(bb); } public Texture2d Get(BitmapBuffer bb) { //get the current entry - Texture2d currentTexture = _currentTextures[0]; + var currentTexture = _currentTextures[0]; // TODO - its a bit cruddy here that we don't respect the current texture HasAlpha condition (in fact, there's no such concept) // we might need to deal with that in the future to fix some bugs. diff --git a/src/BizHawk.Client.Common/FilesystemFilter.cs b/src/BizHawk.Client.Common/FilesystemFilter.cs index e05a06c4c67..b82e17a85e2 100644 --- a/src/BizHawk.Client.Common/FilesystemFilter.cs +++ b/src/BizHawk.Client.Common/FilesystemFilter.cs @@ -55,24 +55,24 @@ public FilesystemFilter( public static readonly IReadOnlyCollection DiscExtensions = new[] { "cue", "ccd", "cdi", "iso", "mds", "m3u", "nrg" }; - public static readonly FilesystemFilter Archives = new FilesystemFilter("Archives", ArchiveExtensions); + public static readonly FilesystemFilter Archives = new("Archives", ArchiveExtensions); - public static readonly FilesystemFilter BizHawkMovies = new FilesystemFilter("Movie Files", new[] { MovieService.StandardMovieExtension }); + public static readonly FilesystemFilter BizHawkMovies = new("Movie Files", new[] { MovieService.StandardMovieExtension }); - public static readonly FilesystemFilter EmuHawkSaveStates = new FilesystemFilter("Save States", new[] { "State" }); + public static readonly FilesystemFilter EmuHawkSaveStates = new("Save States", new[] { "State" }); - public static readonly FilesystemFilter LuaScripts = new FilesystemFilter("Lua Scripts", new[] { "lua" }); + public static readonly FilesystemFilter LuaScripts = new("Lua Scripts", new[] { "lua" }); - public static readonly FilesystemFilter PNGs = new FilesystemFilter("PNG Files", new[] { "png" }); + public static readonly FilesystemFilter PNGs = new("PNG Files", new[] { "png" }); - public static readonly FilesystemFilter TAStudioProjects = new FilesystemFilter("TAS Project Files", new[] { MovieService.TasMovieExtension }); + public static readonly FilesystemFilter TAStudioProjects = new("TAS Project Files", new[] { MovieService.TasMovieExtension }); - public static readonly FilesystemFilter TextFiles = new FilesystemFilter("Text Files", new[] { "txt" }); + public static readonly FilesystemFilter TextFiles = new("Text Files", new[] { "txt" }); /// return value is a valid Filter for Save-/OpenFileDialog public static string SerializeEntry(string desc, IReadOnlyCollection exts) { - var joinedLower = string.Join(";", exts.Select(static ext => $"*.{ext}")); + string joinedLower = string.Join(";", exts.Select(static ext => $"*.{ext}")); return OSTailoredCode.IsUnixHost ? $"{desc} ({joinedLower})|{string.Join(";", exts.Select(static ext => $"*.{ext};*.{ext.ToUpperInvariant()}"))}" : $"{desc} ({joinedLower})|{joinedLower}"; diff --git a/src/BizHawk.Client.Common/FilesystemFilterSet.cs b/src/BizHawk.Client.Common/FilesystemFilterSet.cs index f29314e55c6..5e81f58788c 100644 --- a/src/BizHawk.Client.Common/FilesystemFilterSet.cs +++ b/src/BizHawk.Client.Common/FilesystemFilterSet.cs @@ -27,7 +27,7 @@ public override string ToString() { if (_ser is null) { - var entries = Filters.Select(static filter => filter.ToString()).ToList(); + List entries = Filters.Select(static filter => filter.ToString()).ToList(); if (CombinedEntryDesc is not null) entries.Insert(0, FilesystemFilter.SerializeEntry(CombinedEntryDesc, CombinedExts)); if (AppendAllFilesEntry) entries.Add(FilesystemFilter.AllFilesEntry); _ser = string.Join("|", entries); @@ -37,6 +37,6 @@ public override string ToString() public static readonly FilesystemFilterSet Palettes = new(new FilesystemFilter("Palette Files", new[] { "pal" })); - public static readonly FilesystemFilterSet Screenshots = new FilesystemFilterSet(FilesystemFilter.PNGs, new FilesystemFilter(".bmp Files", new[] { "bmp" })); + public static readonly FilesystemFilterSet Screenshots = new(FilesystemFilter.PNGs, new FilesystemFilter(".bmp Files", new[] { "bmp" })); } } diff --git a/src/BizHawk.Client.Common/OpenAdvanced.cs b/src/BizHawk.Client.Common/OpenAdvanced.cs index 394a100fd17..2d05f95a0f0 100644 --- a/src/BizHawk.Client.Common/OpenAdvanced.cs +++ b/src/BizHawk.Client.Common/OpenAdvanced.cs @@ -60,20 +60,14 @@ private static IOpenAdvanced Deserialize(string text) OpenAdvancedTypes.LibretroNoGame => new OpenAdvanced_LibretroNoGame(), OpenAdvancedTypes.MAME => new OpenAdvanced_MAME(), _ => null - }; - - if (ioa == null) - { - throw new InvalidOperationException($"{nameof(IOpenAdvanced)} deserialization error"); - } - + } ?? throw new InvalidOperationException($"{nameof(IOpenAdvanced)} deserialization error"); ioa.Deserialize(token); return ioa; } public static string Serialize(IOpenAdvanced ioa) { - var sw = new StringWriter(); + StringWriter sw = new(); sw.Write("{0}*", ioa.TypeName); ioa.Serialize(sw); return sw.ToString(); @@ -93,15 +87,9 @@ public struct Token public string DisplayName => $"{Path.GetFileNameWithoutExtension(token.CorePath)}: {token.Path}"; public string SimplePath => token.Path; - public void Deserialize(string str) - { - token = JsonConvert.DeserializeObject(str); - } - - public void Serialize(TextWriter tw) - { - tw.Write(JsonConvert.SerializeObject(token)); - } + public void Deserialize(string str) => token = JsonConvert.DeserializeObject(str); + + public void Serialize(TextWriter tw) => tw.Write(JsonConvert.SerializeObject(token)); public string CorePath { @@ -131,15 +119,9 @@ public OpenAdvanced_LibretroNoGame(string corePath) public string DisplayName => Path.GetFileName(CorePath); // assume we like the filename of the core public string SimplePath => ""; // effectively a signal to not use a game - public void Deserialize(string str) - { - CorePath = str; - } + public void Deserialize(string str) => CorePath = str; - public void Serialize(TextWriter tw) - { - tw.Write(CorePath); - } + public void Serialize(TextWriter tw) => tw.Write(CorePath); public string CorePath { get; set; } } @@ -152,15 +134,9 @@ public class OpenAdvanced_OpenRom : IOpenAdvanced public string DisplayName => Path; public string SimplePath => Path; - public void Deserialize(string str) - { - Path = str; - } + public void Deserialize(string str) => Path = str; - public void Serialize(TextWriter tw) - { - tw.Write(Path); - } + public void Serialize(TextWriter tw) => tw.Write(Path); } public class OpenAdvanced_MAME : IOpenAdvanced @@ -171,14 +147,8 @@ public class OpenAdvanced_MAME : IOpenAdvanced public string DisplayName => $"{TypeName}: {Path}"; public string SimplePath => Path; - public void Deserialize(string str) - { - Path = str; - } + public void Deserialize(string str) => Path = str; - public void Serialize(TextWriter tw) - { - tw.Write(Path); - } + public void Serialize(TextWriter tw) => tw.Write(Path); } } \ No newline at end of file diff --git a/src/BizHawk.Client.Common/QuickBmpFile.cs b/src/BizHawk.Client.Common/QuickBmpFile.cs index 4e7d18136d7..83f0356e5dc 100644 --- a/src/BizHawk.Client.Common/QuickBmpFile.cs +++ b/src/BizHawk.Client.Common/QuickBmpFile.cs @@ -233,8 +233,8 @@ public class LoadedBMP : IVideoProvider public static unsafe bool Load(IVideoProvider v, Stream s) { - var bf = BITMAPFILEHEADER.FromStream(s); - var bi = BITMAPINFOHEADER.FromStream(s); + BITMAPFILEHEADER bf = BITMAPFILEHEADER.FromStream(s); + BITMAPINFOHEADER bi = BITMAPINFOHEADER.FromStream(s); if (bf.bfType != 0x4d42 || bf.bfOffBits != bf.bfSize + bi.biSize || bi.biPlanes != 1 @@ -251,7 +251,7 @@ public static unsafe bool Load(IVideoProvider v, Stream s) s.Read(src, 0, src.Length); if (v is LoadedBMP) { - var l = v as LoadedBMP; + LoadedBMP l = v as LoadedBMP; l.BufferWidth = inW; l.BufferHeight = inH; l.VideoBuffer = new int[inW * inH]; @@ -284,8 +284,8 @@ public static unsafe bool Load(IVideoProvider v, Stream s) public static unsafe void Save(IVideoProvider v, Stream s, int w, int h) { - var bf = new BITMAPFILEHEADER(); - var bi = new BITMAPINFOHEADER(); + BITMAPFILEHEADER bf = new(); + BITMAPINFOHEADER bi = new(); bf.bfType = 0x4d42; bf.bfOffBits = bf.bfSize + bi.biSize; diff --git a/src/BizHawk.Client.Common/RecentFiles.cs b/src/BizHawk.Client.Common/RecentFiles.cs index 041cd971774..1ab262a3d30 100644 --- a/src/BizHawk.Client.Common/RecentFiles.cs +++ b/src/BizHawk.Client.Common/RecentFiles.cs @@ -10,7 +10,7 @@ namespace BizHawk.Client.Common public class RecentFiles : IEnumerable { // ReSharper disable once FieldCanBeMadeReadOnly.Local - private List recentlist; + private readonly List recentlist; public RecentFiles() : this(8) @@ -77,9 +77,6 @@ public bool Remove(string newFile) return false; } - public void ToggleAutoLoad() - { - AutoLoad ^= true; - } + public void ToggleAutoLoad() => AutoLoad ^= true; } } diff --git a/src/BizHawk.Client.Common/RomGame.cs b/src/BizHawk.Client.Common/RomGame.cs index 1b255178096..33f794de926 100644 --- a/src/BizHawk.Client.Common/RomGame.cs +++ b/src/BizHawk.Client.Common/RomGame.cs @@ -105,15 +105,15 @@ public RomGame(HawkFile file, string patch) { RomData = FileData; } - else if (file.Extension == ".dsk" || file.Extension == ".tap" || file.Extension == ".tzx" || - file.Extension == ".pzx" || file.Extension == ".csw" || file.Extension == ".wav" || file.Extension == ".cdt") + else if (file.Extension is ".dsk" or ".tap" or ".tzx" or + ".pzx" or ".csw" or ".wav" or ".cdt") { // these are not roms. unfortunately if treated as such there are certain edge-cases // where a header offset is detected. This should mitigate this issue until a cleaner solution is found // (-Asnivor) RomData = FileData; } - else if (SHA1_check == Flappy_Bird_INTV || SHA1_check == Minehunter_INTV) + else if (SHA1_check is Flappy_Bird_INTV or Minehunter_INTV) { // several INTV games have sizes that are multiples of 512 bytes Console.WriteLine("False positive detected in Header Check, using entire file."); @@ -147,19 +147,19 @@ public RomGame(HawkFile file, string patch) CheckForPatchOptions(); if (patch is null) return; - using var patchFile = new HawkFile(patch); + using HawkFile patchFile = new(patch); patchFile.BindFirstOf(".ips"); if (!patchFile.IsBound) patchFile.BindFirstOf(".bps"); if (!patchFile.IsBound) return; - var patchBytes = patchFile.GetStream().ReadAllBytes(); + byte[] patchBytes = patchFile.GetStream().ReadAllBytes(); if (BPSPatcher.IsIPSFile(patchBytes)) { RomData = BPSPatcher.Patch(RomData, new BPSPatcher.IPSPayload(patchBytes)); } else if (BPSPatcher.IsBPSFile(patchBytes, out var patchStruct)) { - var ignoreBaseChecksum = true; //TODO check base checksum and ask user before continuing - RomData = BPSPatcher.Patch(StripSNESDumpHeader(RomData), patchStruct, out var checksumsMatch); + bool ignoreBaseChecksum = true; //TODO check base checksum and ask user before continuing + RomData = BPSPatcher.Patch(StripSNESDumpHeader(RomData), patchStruct, out bool checksumsMatch); if (!checksumsMatch && !ignoreBaseChecksum) throw new Exception("BPS patch didn't produce the expected output"); } else @@ -183,7 +183,7 @@ private static byte[] DeInterleaveSMD(byte[] source) } int pages = size / 0x4000; - var output = new byte[size]; + byte[] output = new byte[size]; for (int page = 0; page < pages; page++) { @@ -203,10 +203,10 @@ private void CheckForPatchOptions() { if (GameInfo["PatchBytes"]) { - var args = GameInfo.OptionValue("PatchBytes"); - foreach (var val in args.Split(',')) + string args = GameInfo.OptionValue("PatchBytes"); + foreach (string val in args.Split(',')) { - var split = val.Split(':'); + string[] split = val.Split(':'); int offset = int.Parse(split[0], NumberStyles.HexNumber); byte value = byte.Parse(split[1], NumberStyles.HexNumber); RomData[offset] = value; diff --git a/src/BizHawk.Client.Common/RomLoader.cs b/src/BizHawk.Client.Common/RomLoader.cs index d4411bc1bfc..9ecac749a5a 100644 --- a/src/BizHawk.Client.Common/RomLoader.cs +++ b/src/BizHawk.Client.Common/RomLoader.cs @@ -71,20 +71,14 @@ public enum LoadErrorType // helper methods for the settings events private TSetting GetCoreSettings() - where TCore : IEmulator - { - return (TSetting)GetCoreSettings(typeof(TCore), typeof(TSetting)); - } + where TCore : IEmulator => (TSetting)GetCoreSettings(typeof(TCore), typeof(TSetting)); private TSync GetCoreSyncSettings() - where TCore : IEmulator - { - return (TSync)GetCoreSyncSettings(typeof(TCore), typeof(TSync)); - } + where TCore : IEmulator => (TSync)GetCoreSyncSettings(typeof(TCore), typeof(TSync)); private object GetCoreSettings(Type t, Type settingsType) { - var e = new SettingsLoadArgs(t, settingsType); + SettingsLoadArgs e = new(t, settingsType); if (OnLoadSettings == null) throw new InvalidOperationException("Frontend failed to provide a settings getter"); OnLoadSettings(this, e); @@ -95,7 +89,7 @@ private object GetCoreSettings(Type t, Type settingsType) private object GetCoreSyncSettings(Type t, Type syncSettingsType) { - var e = new SettingsLoadArgs(t, syncSettingsType); + SettingsLoadArgs e = new(t, syncSettingsType); if (OnLoadSyncSettings == null) throw new InvalidOperationException("Frontend failed to provide a sync settings getter"); OnLoadSyncSettings(this, e); @@ -183,15 +177,9 @@ public SettingsLoadArgs(Type t, Type s) } // May want to phase out this method in favor of the overload with more parameters - private void DoLoadErrorCallback(string message, string systemId, LoadErrorType type = LoadErrorType.Unknown) - { - OnLoadError?.Invoke(this, new RomErrorArgs(message, systemId, type)); - } + private void DoLoadErrorCallback(string message, string systemId, LoadErrorType type = LoadErrorType.Unknown) => OnLoadError?.Invoke(this, new RomErrorArgs(message, systemId, type)); - private void DoLoadErrorCallback(string message, string systemId, string path, bool det, LoadErrorType type = LoadErrorType.Unknown) - { - OnLoadError?.Invoke(this, new RomErrorArgs(message, systemId, path, det, type)); - } + private void DoLoadErrorCallback(string message, string systemId, string path, bool det, LoadErrorType type = LoadErrorType.Unknown) => OnLoadError?.Invoke(this, new RomErrorArgs(message, systemId, path, det, type)); public IOpenAdvanced OpenAdvanced { get; set; } @@ -205,7 +193,7 @@ private bool HandleArchiveBinding(HawkFile file) // ...including unrecognised extensions that the user has set a platform for if (!file.IsBound) { - var exts = _config.PreferredPlatformsForExtensions.Where(static kvp => !string.IsNullOrEmpty(kvp.Value)) + List exts = _config.PreferredPlatformsForExtensions.Where(static kvp => !string.IsNullOrEmpty(kvp.Value)) .Select(static kvp => kvp.Key) .ToList(); if (exts.Count is not 0) file.BindSoleItemOf(exts); @@ -234,8 +222,8 @@ private GameInfo MakeGameFromDisc(Disc disc, string ext, string name) { // TODO - use more sophisticated IDer var discType = new DiscIdentifier(disc).DetectDiscType(); - var discHasher = new DiscHasher(disc); - var discHash = discType == DiscType.SonyPSX + DiscHasher discHasher = new(disc); + string discHash = discType == DiscType.SonyPSX ? discHasher.Calculate_PSX_BizIDHash() : discHasher.OldHash(); @@ -249,59 +237,27 @@ Exception NoCoreForSystem(string sysID) game.System = sysID; return new NoAvailableCoreException(sysID); } - switch (discType) - { - case DiscType.SegaSaturn: - game.System = VSystemID.Raw.SAT; - break; - case DiscType.MegaCD: - game.System = VSystemID.Raw.GEN; - break; - case DiscType.PCFX: - game.System = VSystemID.Raw.PCFX; - break; - - case DiscType.TurboGECD: - case DiscType.TurboCD: - game.System = VSystemID.Raw.PCE; - break; - - case DiscType.JaguarCD: - game.System = VSystemID.Raw.Jaguar; - break; - - case DiscType.Amiga: - throw NoCoreForSystem(VSystemID.Raw.Amiga); - case DiscType.CDi: - throw NoCoreForSystem(VSystemID.Raw.PhillipsCDi); - case DiscType.Dreamcast: - throw NoCoreForSystem(VSystemID.Raw.Dreamcast); - case DiscType.GameCube: - throw NoCoreForSystem(VSystemID.Raw.GameCube); - case DiscType.NeoGeoCD: - throw NoCoreForSystem(VSystemID.Raw.NeoGeoCD); - case DiscType.Panasonic3DO: - throw NoCoreForSystem(VSystemID.Raw.Panasonic3DO); - case DiscType.Playdia: - throw NoCoreForSystem(VSystemID.Raw.Playdia); - case DiscType.SonyPS2: - throw NoCoreForSystem(VSystemID.Raw.PS2); - case DiscType.SonyPSP: - throw NoCoreForSystem(VSystemID.Raw.PSP); - case DiscType.Wii: - throw NoCoreForSystem(VSystemID.Raw.Wii); - - case DiscType.AudioDisc: - case DiscType.UnknownCDFS: - case DiscType.UnknownFormat: - game.System = _config.TryGetChosenSystemForFileExt(ext, out var sysID) ? sysID : VSystemID.Raw.NULL; - break; - - default: //"for an unknown disc, default to psx instead of pce-cd, since that is far more likely to be what they are attempting to open" [5e07ab3ec3b8b8de9eae71b489b55d23a3909f55, year 2015] - case DiscType.SonyPSX: - game.System = VSystemID.Raw.PSX; - break; - } + game.System = discType switch + { + DiscType.SegaSaturn => VSystemID.Raw.SAT, + DiscType.MegaCD => VSystemID.Raw.GEN, + DiscType.PCFX => VSystemID.Raw.PCFX, + DiscType.TurboGECD or DiscType.TurboCD => VSystemID.Raw.PCE, + DiscType.JaguarCD => VSystemID.Raw.Jaguar, + DiscType.Amiga => throw NoCoreForSystem(VSystemID.Raw.Amiga), + DiscType.CDi => throw NoCoreForSystem(VSystemID.Raw.PhillipsCDi), + DiscType.Dreamcast => throw NoCoreForSystem(VSystemID.Raw.Dreamcast), + DiscType.GameCube => throw NoCoreForSystem(VSystemID.Raw.GameCube), + DiscType.NeoGeoCD => throw NoCoreForSystem(VSystemID.Raw.NeoGeoCD), + DiscType.Panasonic3DO => throw NoCoreForSystem(VSystemID.Raw.Panasonic3DO), + DiscType.Playdia => throw NoCoreForSystem(VSystemID.Raw.Playdia), + DiscType.SonyPS2 => throw NoCoreForSystem(VSystemID.Raw.PS2), + DiscType.SonyPSP => throw NoCoreForSystem(VSystemID.Raw.PSP), + DiscType.Wii => throw NoCoreForSystem(VSystemID.Raw.Wii), + DiscType.AudioDisc or DiscType.UnknownCDFS or DiscType.UnknownFormat => _config.TryGetChosenSystemForFileExt(ext, out string sysID) ? sysID : VSystemID.Raw.NULL, + //"for an unknown disc, default to psx instead of pce-cd, since that is far more likely to be what they are attempting to open" [5e07ab3ec3b8b8de9eae71b489b55d23a3909f55, year 2015] + _ => VSystemID.Raw.PSX, + }; return game; } @@ -317,7 +273,7 @@ private bool LoadDisc(string path, CoreComm nextComm, HawkFile file, string ext, game = MakeGameFromDisc(disc, ext, Path.GetFileNameWithoutExtension(file.Name)); - var cip = new CoreInventoryParameters(this) + CoreInventoryParameters cip = new(this) { Comm = nextComm, Game = game, @@ -338,13 +294,13 @@ private bool LoadDisc(string path, CoreComm nextComm, HawkFile file, string ext, private void LoadM3U(string path, CoreComm nextComm, HawkFile file, string forcedCoreName, out IEmulator nextEmulator, out GameInfo game) { M3U_File m3u; - using (var sr = new StreamReader(path)) + using (StreamReader sr = new(path)) m3u = M3U_File.Read(sr); if (m3u.Entries.Count == 0) throw new InvalidOperationException("Can't load an empty M3U"); m3u.Rebase(Path.GetDirectoryName(path)); - var discs = m3u.Entries + List discs = m3u.Entries .Select(e => e.Path) .Where(p => Disc.IsValidExtension(Path.GetExtension(p))) .Select(path => (p: path, d: DiscExtensions.CreateAnyType(path, str => DoLoadErrorCallback(str, "???", LoadErrorType.DiscError)))) @@ -360,7 +316,7 @@ private void LoadM3U(string path, CoreComm nextComm, HawkFile file, string force throw new InvalidOperationException("Couldn't load any contents of the M3U as discs"); game = MakeGameFromDisc(discs[0].DiscData, Path.GetExtension(m3u.Entries[0].Path), discs[0].DiscName); - var cip = new CoreInventoryParameters(this) + CoreInventoryParameters cip = new(this) { Comm = nextComm, Game = game, @@ -379,8 +335,8 @@ private IEmulator MakeCoreFromCoreInventory(CoreInventoryParameters cip, string } else { - _ = _config.PreferredCores.TryGetValue(cip.Game.System, out var preferredCore); - var dbForcedCoreName = cip.Game.ForcedCore; + _ = _config.PreferredCores.TryGetValue(cip.Game.System, out string preferredCore); + string dbForcedCoreName = cip.Game.ForcedCore; cores = CoreInventory.Instance.GetCores(cip.Game.System) .OrderBy(c => { @@ -399,7 +355,7 @@ private IEmulator MakeCoreFromCoreInventory(CoreInventoryParameters cip, string .ToList(); if (cores.Count == 0) throw new InvalidOperationException("No core was found to try on the game"); } - var exceptions = new List(); + List exceptions = new(); foreach (var core in cores) { try @@ -443,13 +399,13 @@ private void LoadOther( if (string.IsNullOrEmpty(rom.GameInfo.System)) { // Has the user picked a preference for this extension? - if (_config.TryGetChosenSystemForFileExt(rom.Extension.ToLowerInvariant(), out var systemID)) + if (_config.TryGetChosenSystemForFileExt(rom.Extension.ToLowerInvariant(), out string systemID)) { rom.GameInfo.System = systemID; } else if (ChoosePlatform != null) { - var result = ChoosePlatform(rom); + string result = ChoosePlatform(rom); if (!string.IsNullOrEmpty(result)) { rom.GameInfo.System = result; @@ -490,7 +446,7 @@ private void LoadOther( break; case VSystemID.Raw.PSX when ext is ".bin": const string FILE_EXT_CUE = ".cue"; - var cuePath = TempFileManager.GetTempFilename(friendlyName: "syn", dotAndExtension: FILE_EXT_CUE, delete: false); + string cuePath = TempFileManager.GetTempFilename(friendlyName: "syn", dotAndExtension: FILE_EXT_CUE, delete: false); DiscMountJob.CreateSyntheticCue(cueFilePath: cuePath, binFilePath: file.Name); var gameBak = game; var nextEmulatorBak = nextEmulator; @@ -517,7 +473,7 @@ private void LoadOther( nextEmulator = nextEmulatorBak; break; } - var cip = new CoreInventoryParameters(this) + CoreInventoryParameters cip = new(this) { Comm = nextComm, Game = game, @@ -543,7 +499,7 @@ static byte[] CbDeflater(Stream instream, int size) { return new GZipStream(instream, CompressionMode.Decompress).ReadAllBytes(); } - var psf = new PSF(); + PSF psf = new(); psf.Load(path, CbDeflater); nextEmulator = new Octoshock( nextComm, @@ -564,11 +520,11 @@ private bool LoadXML(string path, CoreComm nextComm, HawkFile file, string force game = null; try { - var xmlGame = XmlGame.Create(file); // if load fails, are we supposed to retry as a bsnes XML???????? + XmlGame xmlGame = XmlGame.Create(file); // if load fails, are we supposed to retry as a bsnes XML???????? game = xmlGame.GI; - var system = game.System; - var cip = new CoreInventoryParameters(this) + string system = game.System; + CoreInventoryParameters cip = new(this) { Comm = nextComm, Game = game, @@ -643,7 +599,7 @@ private void LoadMAME( { try { - using var f = new HawkFile(path, allowArchives: true); + using HawkFile f = new(path, allowArchives: true); if (!HandleArchiveBinding(f)) throw; LoadOther(nextComm, f, ext: ext, forcedCoreName: null, out nextEmulator, out rom, out game, out cancel); } @@ -667,7 +623,7 @@ public bool LoadRom(string path, CoreComm nextComm, string launchLibretroCore, s bool allowArchives = true; if (OpenAdvanced is OpenAdvanced_MAME || MAMEMachineDB.IsMAMEMachine(path)) allowArchives = false; - using var file = new HawkFile(path, false, allowArchives); + using HawkFile file = new(path, false, allowArchives); if (!file.Exists && OpenAdvanced is not OpenAdvanced_LibretroNoGame) return false; // if the provided file doesn't even exist, give up! (unless libretro no game is used) CanonicalFullPath = file.CanonicalFullPath; @@ -678,14 +634,14 @@ public bool LoadRom(string path, CoreComm nextComm, string launchLibretroCore, s try { - var cancel = false; + bool cancel = false; if (OpenAdvanced is OpenAdvanced_Libretro or OpenAdvanced_LibretroNoGame) { // must be done before LoadNoGame (which triggers retro_init and the paths to be consumed by the core) // game name == name of core Game = game = new GameInfo { Name = Path.GetFileNameWithoutExtension(launchLibretroCore), System = VSystemID.Raw.Libretro }; - var retro = new LibretroHost(nextComm, game, launchLibretroCore); + LibretroHost retro = new(nextComm, game, launchLibretroCore); nextEmulator = retro; if (retro.Description.SupportsNoGame && string.IsNullOrEmpty(path)) @@ -743,7 +699,7 @@ public bool LoadRom(string path, CoreComm nextComm, string launchLibretroCore, s } // not libretro: do extension checking - var ext = file.Extension; + string ext = file.Extension; switch (ext) { case ".m3u": @@ -800,7 +756,7 @@ public bool LoadRom(string path, CoreComm nextComm, string launchLibretroCore, s } catch (Exception ex) { - var system = game?.System; + string system = game?.System; DispatchErrorMessage(ex, system: system, path: path); return false; @@ -821,7 +777,7 @@ private void DispatchErrorMessage(Exception ex, string system, string path) { DoLoadErrorCallback("Multiple cores failed to load the rom:", system); } - foreach (Exception e in agg.InnerExceptions) + foreach (var e in agg.InnerExceptions) { DispatchErrorMessage(e, system: system, path: path); } diff --git a/src/BizHawk.Client.Common/SaveSlotManager.cs b/src/BizHawk.Client.Common/SaveSlotManager.cs index 96bfa3221ea..6a5609248de 100644 --- a/src/BizHawk.Client.Common/SaveSlotManager.cs +++ b/src/BizHawk.Client.Common/SaveSlotManager.cs @@ -31,7 +31,7 @@ public void Update(IEmulator emulator, IMovie movie, string saveStatePrefix) } else { - var file = new FileInfo($"{saveStatePrefix}.QuickSave{i % 10}.State"); + FileInfo file = new($"{saveStatePrefix}.QuickSave{i % 10}.State"); if (file.Directory != null && file.Directory.Exists == false) { file.Directory.Create(); @@ -77,9 +77,9 @@ public bool IsRedo(IMovie movie, int slot) public void SwapBackupSavestate(IMovie movie, string path, int currentSlot) { // Takes the .state and .bak files and swaps them - var state = new FileInfo(path); - var backup = new FileInfo($"{path}.bak"); - var temp = new FileInfo($"{path}.bak.tmp"); + FileInfo state = new(path); + FileInfo backup = new($"{path}.bak"); + FileInfo temp = new($"{path}.bak.tmp"); if (!state.Exists || !backup.Exists) { diff --git a/src/BizHawk.Client.Common/SharpCompressArchiveFile.cs b/src/BizHawk.Client.Common/SharpCompressArchiveFile.cs index 13f0c4112b2..b7c696df8cf 100644 --- a/src/BizHawk.Client.Common/SharpCompressArchiveFile.cs +++ b/src/BizHawk.Client.Common/SharpCompressArchiveFile.cs @@ -37,7 +37,7 @@ public void Dispose() public void ExtractFile(int index, Stream stream) { var reader = _archive!.ExtractAllEntries(); - for (var i = 0; i <= index; i++) reader.MoveToNextEntry(); + for (int i = 0; i <= index; i++) reader.MoveToNextEntry(); using var entryStream = reader.OpenEntryStream(); entryStream.CopyTo(stream); } @@ -45,8 +45,8 @@ public void ExtractFile(int index, Stream stream) public List? Scan() { List outFiles = new(); - var entries = EnumerateArchiveFiles().ToList(); - for (var i = 0; i < entries.Count; i++) + List<(IArchiveEntry Entry, int ArchiveIndex)> entries = EnumerateArchiveFiles().ToList(); + for (int i = 0; i < entries.Count; i++) { var (entry, archiveIndex) = entries[i]; if (entry.Key is null) return null; // see https://github.com/adamhathcock/sharpcompress/issues/137 diff --git a/src/BizHawk.Client.Common/SharpCompressDearchivalMethod.cs b/src/BizHawk.Client.Common/SharpCompressDearchivalMethod.cs index dd4143bf513..acbb23d7e47 100644 --- a/src/BizHawk.Client.Common/SharpCompressDearchivalMethod.cs +++ b/src/BizHawk.Client.Common/SharpCompressDearchivalMethod.cs @@ -40,10 +40,10 @@ public bool CheckSignature(string fileName, out int offset, out bool isExecutabl // looking for magic bytes fs.Seek(0x101, SeekOrigin.Begin); - var buffer = new byte[8]; + byte[] buffer = new byte[8]; fs.Read(buffer, 0, 8); - var s = buffer.BytesToHexString(); - if (s == "7573746172003030" || s == "7573746172202000") return true; // "ustar\000" (libarchive's bsdtar) or "ustar \0" (GNU Tar) + string s = buffer.BytesToHexString(); + if (s is "7573746172003030" or "7573746172202000") return true; // "ustar\000" (libarchive's bsdtar) or "ustar \0" (GNU Tar) Console.WriteLine($"SharpCompress identified file as original .tar format, probably a false positive, ignoring. Filename: {fileName}"); return false; @@ -67,13 +67,13 @@ public bool CheckSignature(Stream fileStream, string? filenameHint) if (fileStream.Length < 512) return false; // looking for magic bytes - var seekPos = fileStream.Position; + long seekPos = fileStream.Position; fileStream.Seek(0x101, SeekOrigin.Begin); - var buffer = new byte[8]; + byte[] buffer = new byte[8]; fileStream.Read(buffer, 0, 8); fileStream.Seek(seekPos, SeekOrigin.Begin); - var s = buffer.BytesToHexString(); - if (s == "7573746172003030" || s == "7573746172202000") return true; // "ustar\000" (libarchive's bsdtar) or "ustar \0" (GNU Tar) + string s = buffer.BytesToHexString(); + if (s is "7573746172003030" or "7573746172202000") return true; // "ustar\000" (libarchive's bsdtar) or "ustar \0" (GNU Tar) Console.WriteLine($"SharpCompress identified file in stream as original .tar format, probably a false positive, ignoring. Filename hint: {filenameHint}"); return false; diff --git a/src/BizHawk.Client.Common/Sound/HostAudioManagerExtensions.cs b/src/BizHawk.Client.Common/Sound/HostAudioManagerExtensions.cs index 53453c6ac0f..9b10999bc58 100644 --- a/src/BizHawk.Client.Common/Sound/HostAudioManagerExtensions.cs +++ b/src/BizHawk.Client.Common/Sound/HostAudioManagerExtensions.cs @@ -2,14 +2,8 @@ namespace BizHawk.Client.Common { public static class HostAudioManagerExtensions { - public static int MillisecondsToSamples(this IHostAudioManager audioMan, int milliseconds) - { - return milliseconds * audioMan.SampleRate / 1000; - } + public static int MillisecondsToSamples(this IHostAudioManager audioMan, int milliseconds) => milliseconds * audioMan.SampleRate / 1000; - public static double SamplesToMilliseconds(this IHostAudioManager audioMan, int samples) - { - return samples * 1000.0 / audioMan.SampleRate; - } + public static double SamplesToMilliseconds(this IHostAudioManager audioMan, int samples) => samples * 1000.0 / audioMan.SampleRate; } } diff --git a/src/BizHawk.Client.Common/Sound/Output/DummySoundOutput.cs b/src/BizHawk.Client.Common/Sound/Output/DummySoundOutput.cs index 31d5839e551..8e4531afb37 100644 --- a/src/BizHawk.Client.Common/Sound/Output/DummySoundOutput.cs +++ b/src/BizHawk.Client.Common/Sound/Output/DummySoundOutput.cs @@ -34,10 +34,7 @@ public void StartSound() _lastWriteTime = 0; } - public void StopSound() - { - BufferSizeSamples = 0; - } + public void StopSound() => BufferSizeSamples = 0; public int CalculateSamplesNeeded() { diff --git a/src/BizHawk.Client.Common/Sound/Utilities/BufferedAsync.cs b/src/BizHawk.Client.Common/Sound/Utilities/BufferedAsync.cs index 14795ab8978..038b86cf2fc 100644 --- a/src/BizHawk.Client.Common/Sound/Utilities/BufferedAsync.cs +++ b/src/BizHawk.Client.Common/Sound/Utilities/BufferedAsync.cs @@ -34,7 +34,7 @@ public sealed class BufferedAsync : ISoundProvider, IBufferedSoundProvider { public ISoundProvider BaseSoundProvider { get; set; } - private readonly Queue buffer = new Queue(MaxExcessSamples); + private readonly Queue buffer = new(MaxExcessSamples); private int SamplesInOneFrame = 1470; private readonly int TargetExtraSamples = 882; @@ -43,12 +43,9 @@ public sealed class BufferedAsync : ISoundProvider, IBufferedSoundProvider /// /// recalculates some internal parameters based on the IEmulator's framerate /// - public void RecalculateMagic(double framerate) - { + public void RecalculateMagic(double framerate) => // ceiling instead of floor here is very important (magic) - SamplesInOneFrame = 2 * (int)Math.Ceiling((44100.0 / framerate)); - //TargetExtraSamples = ;// complete guess - } + SamplesInOneFrame = 2 * (int)Math.Ceiling((44100.0 / framerate));//TargetExtraSamples = ;// complete guess public void DiscardSamples() { @@ -67,7 +64,7 @@ public void GetSamplesAsync(short[] samples) if (samplesToGenerate + buffer.Count < samples.Length) samplesToGenerate = samples.Length - buffer.Count; - var mySamples = new short[samplesToGenerate]; + short[] mySamples = new short[samplesToGenerate]; if (BaseSoundProvider.SyncMode != SyncSoundMode.Async) { @@ -100,9 +97,6 @@ public void SetSyncMode(SyncSoundMode mode) } /// always - public void GetSamplesSync(out short[] samples, out int nsamp) - { - throw new InvalidOperationException("Sync mode is not supported."); - } + public void GetSamplesSync(out short[] samples, out int nsamp) => throw new InvalidOperationException("Sync mode is not supported."); } } \ No newline at end of file diff --git a/src/BizHawk.Client.Common/Sound/Utilities/SoundOutputProvider.cs b/src/BizHawk.Client.Common/Sound/Utilities/SoundOutputProvider.cs index 7c5b06bd25d..b89d767acf5 100644 --- a/src/BizHawk.Client.Common/Sound/Utilities/SoundOutputProvider.cs +++ b/src/BizHawk.Client.Common/Sound/Utilities/SoundOutputProvider.cs @@ -32,20 +32,20 @@ public class SoundOutputProvider : IBufferedSoundProvider private readonly Func _getCoreVsyncRateCallback; - private readonly Queue _buffer = new Queue(); + private readonly Queue _buffer = new(); private readonly bool _standaloneMode; private readonly int _targetExtraSamples; private int _maxSamplesDeficit; - private readonly Queue _extraCountHistory = new Queue(); - private readonly Queue _outputCountHistory = new Queue(); - private readonly Queue _hardCorrectionHistory = new Queue(); + private readonly Queue _extraCountHistory = new(); + private readonly Queue _outputCountHistory = new(); + private readonly Queue _hardCorrectionHistory = new(); private int _baseConsecutiveEmptyFrames; - private readonly Queue _baseEmptyFrameCorrectionHistory = new Queue(); + private readonly Queue _baseEmptyFrameCorrectionHistory = new(); private double _lastAdvertisedSamplesPerFrame; - private readonly Queue _baseSamplesPerFrame = new Queue(); + private readonly Queue _baseSamplesPerFrame = new(); private short[] _outputBuffer = Array.Empty(); @@ -210,7 +210,7 @@ private void GetSamplesFromBase(ref double scaleFactor) { throw new InvalidOperationException("Base sound provider must be in sync mode."); } - BaseSoundProvider.GetSamplesSync(out var samples, out var count); + BaseSoundProvider.GetSamplesSync(out short[] samples, out int count); bool correctedEmptyFrame = false; if (count == 0) diff --git a/src/BizHawk.Client.Common/Sound/Utilities/SyncToAsyncProvider.cs b/src/BizHawk.Client.Common/Sound/Utilities/SyncToAsyncProvider.cs index bd311de14c3..c55fa10d364 100644 --- a/src/BizHawk.Client.Common/Sound/Utilities/SyncToAsyncProvider.cs +++ b/src/BizHawk.Client.Common/Sound/Utilities/SyncToAsyncProvider.cs @@ -16,10 +16,7 @@ public SyncToAsyncProvider(Func getCoreVsyncRateCallback, ISoundProvider }; } - public void DiscardSamples() - { - _outputProvider.DiscardSamples(); - } + public void DiscardSamples() => _outputProvider.DiscardSamples(); public bool CanProvideAsync => true; @@ -35,14 +32,8 @@ public void SetSyncMode(SyncSoundMode mode) } /// always - public void GetSamplesSync(out short[] samples, out int nsamp) - { - throw new InvalidOperationException("Sync mode is not supported."); - } + public void GetSamplesSync(out short[] samples, out int nsamp) => throw new InvalidOperationException("Sync mode is not supported."); - public void GetSamplesAsync(short[] samples) - { - _outputProvider.GetSamples(samples); - } + public void GetSamplesAsync(short[] samples) => _outputProvider.GetSamples(samples); } } diff --git a/src/BizHawk.Client.Common/XmlGame.cs b/src/BizHawk.Client.Common/XmlGame.cs index 9684da4443e..ea54193c4d3 100644 --- a/src/BizHawk.Client.Common/XmlGame.cs +++ b/src/BizHawk.Client.Common/XmlGame.cs @@ -24,7 +24,7 @@ public static XmlGame Create(HawkFile f) { try { - var x = new XmlDocument(); + XmlDocument x = new(); x.Load(f.GetStream()); var y = x.SelectSingleNode("./BizHawk-XMLGame"); if (y == null) @@ -32,7 +32,7 @@ public static XmlGame Create(HawkFile f) return null; } - var ret = new XmlGame + XmlGame ret = new() { GI = { @@ -42,17 +42,17 @@ public static XmlGame Create(HawkFile f) }, Xml = x }; - var fullPath = ""; + string fullPath = ""; var n = y.SelectSingleNode("./LoadAssets"); if (n != null) { - var hashStream = new MemoryStream(); + MemoryStream hashStream = new(); int? originalIndex = null; foreach (XmlNode a in n.ChildNodes) { - var filename = a.Attributes!["FileName"].Value; + string filename = a.Attributes!["FileName"].Value; byte[] data; if (filename[0] == '|') { @@ -77,7 +77,7 @@ public static XmlGame Create(HawkFile f) fullPath = Path.Combine(fullPath, filename.SubstringBefore('|')); try { - using var hf = new HawkFile(fullPath, allowArchives: !MAMEMachineDB.IsMAMEMachine(fullPath)); + using HawkFile hf = new(fullPath, allowArchives: !MAMEMachineDB.IsMAMEMachine(fullPath)); if (hf.IsArchive) { var archiveItem = hf.ArchiveItems.First(ai => ai.Name == filename.Split('|').Skip(1).First()); @@ -89,7 +89,7 @@ public static XmlGame Create(HawkFile f) } else { - var path = fullPath.SubstringBefore('|'); + string path = fullPath.SubstringBefore('|'); data = RomGame.Is3DSRom(Path.GetExtension(path).ToUpperInvariant()) ? Array.Empty() : File.ReadAllBytes(path); @@ -103,7 +103,7 @@ public static XmlGame Create(HawkFile f) ret.Assets.Add(new(filename, data)); ret.AssetFullPaths.Add(fullPath); - var sha1 = SHA1Checksum.Compute(data); + byte[] sha1 = SHA1Checksum.Compute(data); hashStream.Write(sha1, 0, sha1.Length); } diff --git a/src/BizHawk.Client.Common/cheats/GameSharkDecoder.cs b/src/BizHawk.Client.Common/cheats/GameSharkDecoder.cs index 54ac1058885..c6018abdba9 100644 --- a/src/BizHawk.Client.Common/cheats/GameSharkDecoder.cs +++ b/src/BizHawk.Client.Common/cheats/GameSharkDecoder.cs @@ -34,7 +34,7 @@ public IDecodeResult Decode(string code) public MemoryDomain CheatDomain() { - var domain = CheatDomainName(); + string domain = CheatDomainName(); return domain is null ? _domains.SystemBus : _domains[domain]!; } diff --git a/src/BizHawk.Client.Common/cheats/GbGameSharkDecoder.cs b/src/BizHawk.Client.Common/cheats/GbGameSharkDecoder.cs index 14750d9b17d..1edb77dc2f1 100644 --- a/src/BizHawk.Client.Common/cheats/GbGameSharkDecoder.cs +++ b/src/BizHawk.Client.Common/cheats/GbGameSharkDecoder.cs @@ -22,20 +22,20 @@ public static IDecodeResult Decode(string code) return new InvalidCheatCode("GameShark codes must be 8 characters with no dashes."); } - var test = code.Substring(0, 2); - if (test != "00" && test != "01") + string test = code.Substring(0, 2); + if (test is not "00" and not "01") { return new InvalidCheatCode("All GameShark Codes for GameBoy need to start with 00 or 01"); } - var result = new DecodeResult { Size = WatchSize.Byte }; + DecodeResult result = new() { Size = WatchSize.Byte }; code = code.Remove(0, 2); - var valueStr = code.Remove(2, 4); + string valueStr = code.Remove(2, 4); code = code.Remove(0, 2); - var addrStr = code.Remove(0, 2); + string addrStr = code.Remove(0, 2); addrStr += code.Remove(2, 2); result.Value = int.Parse(valueStr, NumberStyles.HexNumber); diff --git a/src/BizHawk.Client.Common/cheats/GbGgGameGenieDecoder.cs b/src/BizHawk.Client.Common/cheats/GbGgGameGenieDecoder.cs index 849fea2ce37..78501306fe9 100644 --- a/src/BizHawk.Client.Common/cheats/GbGgGameGenieDecoder.cs +++ b/src/BizHawk.Client.Common/cheats/GbGgGameGenieDecoder.cs @@ -8,7 +8,7 @@ namespace BizHawk.Client.Common.cheats /// public static class GbGgGameGenieDecoder { - private static readonly Dictionary _gbGgGameGenieTable = new Dictionary + private static readonly Dictionary _gbGgGameGenieTable = new() { ['0'] = 0, ['1'] = 1, @@ -45,7 +45,7 @@ public static IDecodeResult Decode(string _code) // Bit # |3|2|1|0|3|2|1|0|3|2|1|0|3|2|1|0|3|2|1|0|3|2|1|0|3|2|1|0|3|2|1|0|3|2|1|0| // maps to| Value |A|B|C|D|E|F|G|H|I|J|K|L|XOR 0xF|a|b|c|c|NotUsed|e|f|g|h| // proper | Value |XOR 0xF|A|B|C|D|E|F|G|H|I|J|K|L|g|h|a|b|Nothing|c|d|e|f| - var result = new DecodeResult { Size = WatchSize.Byte }; + DecodeResult result = new() { Size = WatchSize.Byte }; int x; @@ -95,7 +95,7 @@ public static IDecodeResult Decode(string _code) if (_code.Length > 8) { _ = _gbGgGameGenieTable.TryGetValue(_code[6], out x); - var comp = x << 2; + int comp = x << 2; // 8th character ignored _ = _gbGgGameGenieTable.TryGetValue(_code[8], out x); diff --git a/src/BizHawk.Client.Common/cheats/GbaGameSharkDecoder.cs b/src/BizHawk.Client.Common/cheats/GbaGameSharkDecoder.cs index 6b94b732f9b..c4b0d2205aa 100644 --- a/src/BizHawk.Client.Common/cheats/GbaGameSharkDecoder.cs +++ b/src/BizHawk.Client.Common/cheats/GbaGameSharkDecoder.cs @@ -12,8 +12,8 @@ public static class GbaGameSharkDecoder private static string Decrypt(string code) { - var op1 = uint.Parse(code.Remove(8, 9), NumberStyles.HexNumber); - var op2 = uint.Parse(code.Remove(0, 9), NumberStyles.HexNumber); + uint op1 = uint.Parse(code.Remove(8, 9), NumberStyles.HexNumber); + uint op2 = uint.Parse(code.Remove(0, 9), NumberStyles.HexNumber); uint sum = 0xC6EF3720; @@ -28,12 +28,13 @@ private static string Decrypt(string code) return $"{op1:X8} {op2:X8}"; } + #pragma warning disable IDE0051 // TODO: When to use this? private static string DecryptPro(string code) { - var sum = 0xC6EF3720; - var op1 = uint.Parse(code.Remove(8, 9), NumberStyles.HexNumber); - var op2 = uint.Parse(code.Remove(0, 9), NumberStyles.HexNumber); + uint sum = 0xC6EF3720; + uint op1 = uint.Parse(code.Remove(8, 9), NumberStyles.HexNumber); + uint op2 = uint.Parse(code.Remove(0, 9), NumberStyles.HexNumber); for (int j = 0; j < 32; ++j) { @@ -44,6 +45,7 @@ private static string DecryptPro(string code) return $"{op1:X8} {op2:X8}"; } + #pragma warning restore IDE0051 public static IDecodeResult Decode(string code) { @@ -62,7 +64,7 @@ public static IDecodeResult Decode(string code) return new InvalidCheatCode("All GBA GameShark Codes need to be 17 characters in length with a space after the first eight."); } - var result = new DecodeResult + DecodeResult result = new() { Size = code.First() switch { @@ -89,9 +91,6 @@ public static IDecodeResult Decode(string code) return result; } - private static string GetLast(string str, int length) - { - return length >= str.Length ? str : str.Substring(str.Length - length); - } + private static string GetLast(string str, int length) => length >= str.Length ? str : str.Substring(str.Length - length); } } diff --git a/src/BizHawk.Client.Common/cheats/GenesisActionReplayDecoder.cs b/src/BizHawk.Client.Common/cheats/GenesisActionReplayDecoder.cs index ee61b0a9351..2f1e34a8c3b 100644 --- a/src/BizHawk.Client.Common/cheats/GenesisActionReplayDecoder.cs +++ b/src/BizHawk.Client.Common/cheats/GenesisActionReplayDecoder.cs @@ -18,7 +18,7 @@ public static IDecodeResult Decode(string code) return new InvalidCheatCode("Action Replay/Pro Action Replay Codes need to contain a colon after the sixth character."); } - var parseString = code.Remove(0, 2); + string parseString = code.Remove(0, 2); return code.Length switch { 9 => diff --git a/src/BizHawk.Client.Common/cheats/GenesisGameGenieDecoder.cs b/src/BizHawk.Client.Common/cheats/GenesisGameGenieDecoder.cs index 290db9c097c..2e32177ee62 100644 --- a/src/BizHawk.Client.Common/cheats/GenesisGameGenieDecoder.cs +++ b/src/BizHawk.Client.Common/cheats/GenesisGameGenieDecoder.cs @@ -5,7 +5,7 @@ namespace BizHawk.Client.Common.cheats { public static class GenesisGameGenieDecoder { - private static readonly Dictionary GameGenieTable = new Dictionary + private static readonly Dictionary GameGenieTable = new() { ['A'] = 0, ['B'] = 1, @@ -62,10 +62,10 @@ public static IDecodeResult Decode(string code) long hexCode = 0; // convert code to a long binary string - foreach (var t in code) + foreach (char t in code) { hexCode <<= 5; - _ = GameGenieTable.TryGetValue(t, out var y); + _ = GameGenieTable.TryGetValue(t, out long y); hexCode |= y; } diff --git a/src/BizHawk.Client.Common/cheats/IDecodeResult.cs b/src/BizHawk.Client.Common/cheats/IDecodeResult.cs index bbc51f2f28c..c76cfaffed4 100644 --- a/src/BizHawk.Client.Common/cheats/IDecodeResult.cs +++ b/src/BizHawk.Client.Common/cheats/IDecodeResult.cs @@ -39,7 +39,7 @@ public static bool IsValid(this IDecodeResult result, out DecodeResult valid) public static Cheat ToCheat(this DecodeResult result, MemoryDomain domain, string description) { - var watch = Watch.GenerateWatch( + Watch watch = Watch.GenerateWatch( domain, result.Address, result.Size, diff --git a/src/BizHawk.Client.Common/cheats/N64GameSharkDecoder.cs b/src/BizHawk.Client.Common/cheats/N64GameSharkDecoder.cs index 2d42fcc523a..5707629e83b 100644 --- a/src/BizHawk.Client.Common/cheats/N64GameSharkDecoder.cs +++ b/src/BizHawk.Client.Common/cheats/N64GameSharkDecoder.cs @@ -46,7 +46,7 @@ public static IDecodeResult Decode(string code) return new InvalidCheatCode("This code is not needed by Bizhawk."); } - var s = code.Remove(0, 2); + string s = code.Remove(0, 2); return new DecodeResult { diff --git a/src/BizHawk.Client.Common/cheats/NesGameGenieDecoder.cs b/src/BizHawk.Client.Common/cheats/NesGameGenieDecoder.cs index 1f5a25bb4b7..64d6ca84bc7 100644 --- a/src/BizHawk.Client.Common/cheats/NesGameGenieDecoder.cs +++ b/src/BizHawk.Client.Common/cheats/NesGameGenieDecoder.cs @@ -5,7 +5,7 @@ namespace BizHawk.Client.Common.cheats { public static class NesGameGenieDecoder { - private static readonly Dictionary GameGenieTable = new Dictionary + private static readonly Dictionary GameGenieTable = new() { ['A'] = 0, // 0000 ['P'] = 1, // 0001 @@ -32,12 +32,12 @@ public static IDecodeResult Decode(string code) throw new ArgumentNullException(nameof(code)); } - if (code.Length != 6 && code.Length != 8) + if (code.Length is not 6 and not 8) { return new InvalidCheatCode("Game Genie codes need to be six or eight characters in length."); } - var result = new DecodeResult { Size = WatchSize.Byte }; + DecodeResult result = new() { Size = WatchSize.Byte }; // char 3 bit 3 denotes the code length. if (code.Length == 6) { @@ -47,7 +47,7 @@ public static IDecodeResult Decode(string code) result.Value = 0; result.Address = 0x8000; - _ = GameGenieTable.TryGetValue(code[0], out var x); + _ = GameGenieTable.TryGetValue(code[0], out int x); result.Value |= x & 0x07; result.Value |= (x & 0x08) << 4; @@ -79,7 +79,7 @@ public static IDecodeResult Decode(string code) result.Address = 0x8000; result.Compare = 0; - _ = GameGenieTable.TryGetValue(code[0], out var x); + _ = GameGenieTable.TryGetValue(code[0], out int x); result.Value |= x & 0x07; result.Value |= (x & 0x08) << 4; diff --git a/src/BizHawk.Client.Common/cheats/PsxGameSharkDecoder.cs b/src/BizHawk.Client.Common/cheats/PsxGameSharkDecoder.cs index 3298a37227a..206ffe79dd6 100644 --- a/src/BizHawk.Client.Common/cheats/PsxGameSharkDecoder.cs +++ b/src/BizHawk.Client.Common/cheats/PsxGameSharkDecoder.cs @@ -24,9 +24,9 @@ public static IDecodeResult Decode(string code) return new InvalidCheatCode("All PSX GameShark Cheats need to be 13 characters in length."); } - var result = new DecodeResult(); + DecodeResult result = new(); - var type = code.Substring(0, 2); + string type = code.Substring(0, 2); result.Size = type switch { "10" => WatchSize.Word, @@ -49,7 +49,7 @@ public static IDecodeResult Decode(string code) _ => WatchSize.Byte }; - var s = code.Remove(0, 2); + string s = code.Remove(0, 2); result.Address = int.Parse(s.Remove(6, 5), NumberStyles.HexNumber); result.Value = int.Parse(s.Remove(0, 7), NumberStyles.HexNumber); diff --git a/src/BizHawk.Client.Common/cheats/SaturnGameSharkDecoder.cs b/src/BizHawk.Client.Common/cheats/SaturnGameSharkDecoder.cs index 06fd4355471..3d8dbeb353d 100644 --- a/src/BizHawk.Client.Common/cheats/SaturnGameSharkDecoder.cs +++ b/src/BizHawk.Client.Common/cheats/SaturnGameSharkDecoder.cs @@ -28,16 +28,16 @@ public static IDecodeResult Decode(string code) return new InvalidCheatCode("All Saturn GameShark Cheats need to be 13 characters in length."); } - var result = new DecodeResult { Size = WatchSize.Word }; + DecodeResult result = new() { Size = WatchSize.Word }; // Only the first character really matters? 16 or 36? - var test = code.Remove(2, 11).Remove(1, 1); + string test = code.Remove(2, 11).Remove(1, 1); if (test == "3") { result.Size = WatchSize.Byte; } - - var s = code.Remove(0, 2); + + string s = code.Remove(0, 2); result.Address = int.Parse(s.Remove(6, 5), NumberStyles.HexNumber); result.Value = int.Parse(s.Remove(0, 7)); return result; diff --git a/src/BizHawk.Client.Common/cheats/SmsActionReplayDecoder.cs b/src/BizHawk.Client.Common/cheats/SmsActionReplayDecoder.cs index c3ef9867a52..12c5b6fa075 100644 --- a/src/BizHawk.Client.Common/cheats/SmsActionReplayDecoder.cs +++ b/src/BizHawk.Client.Common/cheats/SmsActionReplayDecoder.cs @@ -17,11 +17,11 @@ public static IDecodeResult Decode(string code) return new InvalidCheatCode("Action Replay Codes must be 9 characters with a dash after the third character"); } - var result = new DecodeResult { Size = WatchSize.Byte }; + DecodeResult result = new() { Size = WatchSize.Byte }; - var s = code.Remove(0, 2); - var ramAddress = s.Remove(4, 2).Replace("-", ""); - var ramValue = s.Remove(0, 5); + string s = code.Remove(0, 2); + string ramAddress = s.Remove(4, 2).Replace("-", ""); + string ramValue = s.Remove(0, 5); result.Address = int.Parse(ramAddress, NumberStyles.HexNumber); result.Value = int.Parse(ramValue, NumberStyles.HexNumber); return result; diff --git a/src/BizHawk.Client.Common/cheats/SnesGameGenieDecoder.cs b/src/BizHawk.Client.Common/cheats/SnesGameGenieDecoder.cs index 24e12e8e80f..a11dd208444 100644 --- a/src/BizHawk.Client.Common/cheats/SnesGameGenieDecoder.cs +++ b/src/BizHawk.Client.Common/cheats/SnesGameGenieDecoder.cs @@ -9,7 +9,7 @@ public static class SnesGameGenieDecoder // Code: D F 4 7 0 9 1 5 6 B C 8 A 2 3 E // Hex: 0 1 2 3 4 5 6 7 8 9 A B C D E F // This only applies to the SNES - private static readonly Dictionary SNESGameGenieTable = new Dictionary + private static readonly Dictionary SNESGameGenieTable = new() { ['D'] = 0, // 0000 ['F'] = 1, // 0001 @@ -48,7 +48,7 @@ public static IDecodeResult Decode(string code) // Bit # |3|2|1|0|3|2|1|0|3|2|1|0|3|2|1|0|3|2|1|0|3|2|1|0|3|2|1|0|3|2|1|0| // maps to| Value |i|j|k|l|q|r|s|t|o|p|a|b|c|d|u|v|w|x|e|f|g|h|m|n| // order | Value |a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x| - var result = new DecodeResult { Size = WatchSize.Byte }; + DecodeResult result = new() { Size = WatchSize.Byte }; int x; diff --git a/src/BizHawk.Client.Common/config/Binding.cs b/src/BizHawk.Client.Common/config/Binding.cs index 323e475008d..946e78cb729 100644 --- a/src/BizHawk.Client.Common/config/Binding.cs +++ b/src/BizHawk.Client.Common/config/Binding.cs @@ -14,8 +14,8 @@ public class HotkeyInfo static HotkeyInfo() { - var dict = new Dictionary(); - var i = 0; + Dictionary dict = new(); + int i = 0; #if true void Bind(string tabGroup, string displayName, string defaultBinding = "", string toolTip = "") => dict.Add(displayName, new(tabGroup: tabGroup, i++, displayName: displayName, toolTip: toolTip, defaultBinding: defaultBinding)); diff --git a/src/BizHawk.Client.Common/config/ConfigExtensions.cs b/src/BizHawk.Client.Common/config/ConfigExtensions.cs index db982d0d3aa..7f9da1a4e7f 100644 --- a/src/BizHawk.Client.Common/config/ConfigExtensions.cs +++ b/src/BizHawk.Client.Common/config/ConfigExtensions.cs @@ -17,7 +17,7 @@ private class TypeNameEncapsulator } private static JToken Serialize(object o) { - var tne = new TypeNameEncapsulator { o = o }; + TypeNameEncapsulator tne = new() { o = o }; return JToken.FromObject(tne, ConfigService.Serializer)["o"]; // Maybe todo: This code is identical to the code above, except that it does not emit the legacy "$type" @@ -54,10 +54,7 @@ public static object GetCoreSettings(this Config config, Type coreType, Type set /// /// null if no settings were saved, or there was an error deserializing public static TSetting GetCoreSettings(this Config config) - where TCore : IEmulator - { - return (TSetting)config.GetCoreSettings(typeof(TCore), typeof(TSetting)); - } + where TCore : IEmulator => (TSetting)config.GetCoreSettings(typeof(TCore), typeof(TSetting)); /// /// saves the core settings for a core @@ -94,10 +91,7 @@ public static object GetCoreSyncSettings(this Config config, Type coreType, Type /// /// null if no settings were saved, or there was an error deserializing public static TSync GetCoreSyncSettings(this Config config) - where TCore : IEmulator - { - return (TSync)config.GetCoreSyncSettings(typeof(TCore), typeof(TSync)); - } + where TCore : IEmulator => (TSync)config.GetCoreSyncSettings(typeof(TCore), typeof(TSync)); /// /// saves the core syncsettings for a core @@ -120,11 +114,11 @@ public static void PutCoreSyncSettings(this Config config, object o, Type coreTy public static void ReplaceKeysInBindings(this Config config, IReadOnlyDictionary replMap) { string ReplMulti(string multiBind) - => multiBind.TransformFields(',', bind => bind.TransformFields('+', button => replMap.TryGetValue(button, out var repl) ? repl : button)); - foreach (var k in config.HotkeyBindings.Keys.ToList()) config.HotkeyBindings[k] = ReplMulti(config.HotkeyBindings[k]); + => multiBind.TransformFields(',', bind => bind.TransformFields('+', button => replMap.TryGetValue(button, out string repl) ? repl : button)); + foreach (string k in config.HotkeyBindings.Keys.ToList()) config.HotkeyBindings[k] = ReplMulti(config.HotkeyBindings[k]); foreach (var bindCollection in new[] { config.AllTrollers, config.AllTrollersAutoFire }) // analog and feedback binds can only be bound to (host) gamepads, not keyboard { - foreach (var k in bindCollection.Keys.ToArray()) bindCollection[k] = bindCollection[k].ToDictionary(static kvp => kvp.Key, kvp => ReplMulti(kvp.Value)); + foreach (string k in bindCollection.Keys.ToArray()) bindCollection[k] = bindCollection[k].ToDictionary(static kvp => kvp.Key, kvp => ReplMulti(kvp.Value)); } } @@ -132,7 +126,7 @@ string ReplMulti(string multiBind) /// will be if returned value is public static bool TryGetChosenSystemForFileExt(this Config config, string fileExt, out string systemID) { - var b = config.PreferredPlatformsForExtensions.TryGetValue(fileExt, out var v); + bool b = config.PreferredPlatformsForExtensions.TryGetValue(fileExt, out string v); if (b && !string.IsNullOrEmpty(v)) { systemID = v; diff --git a/src/BizHawk.Client.Common/config/ConfigService.cs b/src/BizHawk.Client.Common/config/ConfigService.cs index 310790ac32c..0394f9d6175 100644 --- a/src/BizHawk.Client.Common/config/ConfigService.cs +++ b/src/BizHawk.Client.Common/config/ConfigService.cs @@ -67,14 +67,14 @@ public static bool IsFromSameVersion(string filepath, out string msg) } else { - var cfgVersion = VersionInfo.VersionStrToInt(cfgVersionStr); + uint cfgVersion = VersionInfo.VersionStrToInt(cfgVersionStr); if (cfgVersion < 0x02050000U) { fmt = MSGFMT_PRE_2_5; } else { - var thisVersion = VersionInfo.VersionStrToInt(VersionInfo.MainVersion); + uint thisVersion = VersionInfo.VersionStrToInt(VersionInfo.MainVersion); fmt = cfgVersion < thisVersion ? MSGFMT_OLDER : MSGFMT_NEWER; } } @@ -85,15 +85,15 @@ public static bool IsFromSameVersion(string filepath, out string msg) /// internal error public static T Load(string filepath) where T : new() { - T config = default(T); + T config = default; try { - var file = new FileInfo(filepath); + FileInfo file = new(filepath); if (file.Exists) { using var reader = file.OpenText(); - var r = new JsonTextReader(reader); + JsonTextReader r = new(reader); config = (T)Serializer.Deserialize(r, typeof(T)); } } @@ -107,11 +107,11 @@ public static bool IsFromSameVersion(string filepath, out string msg) public static void Save(string filepath, object config) { - var file = new FileInfo(filepath); + FileInfo file = new(filepath); try { using var writer = file.CreateText(); - var w = new JsonTextWriter(writer) { Formatting = Formatting.Indented }; + JsonTextWriter w = new(writer) { Formatting = Formatting.Indented }; Serializer.Serialize(w, config); } catch @@ -128,9 +128,9 @@ private class TypeNameEncapsulator public static object LoadWithType(string serialized) { - using var tr = new StringReader(serialized); - using var jr = new JsonTextReader(tr); - var tne = (TypeNameEncapsulator)Serializer.Deserialize(jr, typeof(TypeNameEncapsulator)); + using StringReader tr = new(serialized); + using JsonTextReader jr = new(tr); + TypeNameEncapsulator tne = (TypeNameEncapsulator)Serializer.Deserialize(jr, typeof(TypeNameEncapsulator)); // in the case of trying to deserialize nothing, tne will be nothing // we want to return nothing @@ -139,9 +139,9 @@ public static object LoadWithType(string serialized) public static string SaveWithType(object o) { - using var sw = new StringWriter(); - using var jw = new JsonTextWriter(sw) { Formatting = Formatting.None }; - var tne = new TypeNameEncapsulator { o = o }; + using StringWriter sw = new(); + using JsonTextWriter jw = new(sw) { Formatting = Formatting.None }; + TypeNameEncapsulator tne = new() { o = o }; Serializer.Serialize(jw, tne, typeof(TypeNameEncapsulator)); sw.Flush(); return sw.ToString(); diff --git a/src/BizHawk.Client.Common/config/FeedbackBind.cs b/src/BizHawk.Client.Common/config/FeedbackBind.cs index 207e94d763a..bf322d299cc 100644 --- a/src/BizHawk.Client.Common/config/FeedbackBind.cs +++ b/src/BizHawk.Client.Common/config/FeedbackBind.cs @@ -13,7 +13,7 @@ public struct FeedbackBind public string? GamepadPrefix; [JsonIgnore] - public bool IsZeroed => GamepadPrefix == null; + public readonly bool IsZeroed => GamepadPrefix == null; public float Prescale; diff --git a/src/BizHawk.Client.Common/config/MessagePosition.cs b/src/BizHawk.Client.Common/config/MessagePosition.cs index 039b3f24c78..01f0676fdd5 100644 --- a/src/BizHawk.Client.Common/config/MessagePosition.cs +++ b/src/BizHawk.Client.Common/config/MessagePosition.cs @@ -21,14 +21,14 @@ public static class MessagePositionExtensions { public static bool IsTop(this MessagePosition.AnchorType type) { - return type == MessagePosition.AnchorType.TopLeft - || type == MessagePosition.AnchorType.TopRight; + return type is MessagePosition.AnchorType.TopLeft + or MessagePosition.AnchorType.TopRight; } public static bool IsLeft(this MessagePosition.AnchorType type) { - return type == MessagePosition.AnchorType.TopLeft - || type == MessagePosition.AnchorType.BottomLeft; + return type is MessagePosition.AnchorType.TopLeft + or MessagePosition.AnchorType.BottomLeft; } public static string ToCoordinateStr(this MessagePosition position) => $"{position.X}, {position.Y}"; @@ -36,14 +36,14 @@ public static bool IsLeft(this MessagePosition.AnchorType type) public static class DefaultMessagePositions { - public static readonly MessagePosition Fps = new MessagePosition { X = 0, Y = 0 }; - public static readonly MessagePosition FrameCounter = new MessagePosition { X = 0, Y = 14 }; - public static readonly MessagePosition LagCounter = new MessagePosition { X = 0, Y = 42 }; - public static readonly MessagePosition InputDisplay = new MessagePosition { X = 0, Y = 28 }; - public static readonly MessagePosition ReRecordCounter = new MessagePosition { X = 0, Y = 56 }; - public static readonly MessagePosition Messages = new MessagePosition { X = 0, Y = 0, Anchor = MessagePosition.AnchorType.BottomLeft }; - public static readonly MessagePosition Autohold = new MessagePosition { X = 0, Y = 0, Anchor = MessagePosition.AnchorType.TopRight }; - public static readonly MessagePosition RamWatches = new MessagePosition { X = 0, Y = 70 }; + public static readonly MessagePosition Fps = new() { X = 0, Y = 0 }; + public static readonly MessagePosition FrameCounter = new() { X = 0, Y = 14 }; + public static readonly MessagePosition LagCounter = new() { X = 0, Y = 42 }; + public static readonly MessagePosition InputDisplay = new() { X = 0, Y = 28 }; + public static readonly MessagePosition ReRecordCounter = new() { X = 0, Y = 56 }; + public static readonly MessagePosition Messages = new() { X = 0, Y = 0, Anchor = MessagePosition.AnchorType.BottomLeft }; + public static readonly MessagePosition Autohold = new() { X = 0, Y = 0, Anchor = MessagePosition.AnchorType.TopRight }; + public static readonly MessagePosition RamWatches = new() { X = 0, Y = 70 }; public const int MessagesColor = -1, diff --git a/src/BizHawk.Client.Common/config/PathEntryCollection.cs b/src/BizHawk.Client.Common/config/PathEntryCollection.cs index c2dec1d2c77..4154989b5a8 100644 --- a/src/BizHawk.Client.Common/config/PathEntryCollection.cs +++ b/src/BizHawk.Client.Common/config/PathEntryCollection.cs @@ -148,10 +148,10 @@ public void ResolveWithDefaults() if (!Paths.Exists(p => p.System == defaultPath.System && p.Type == defaultPath.Type)) Paths.Add(defaultPath); } - var entriesToRemove = new List(); + List entriesToRemove = new(); // Remove entries that no longer exist in defaults - foreach (PathEntry pathEntry in Paths) + foreach (var pathEntry in Paths) { var path = Defaults.Value.FirstOrDefault(p => p.System == pathEntry.System && p.Type == pathEntry.Type); if (path == null) @@ -160,7 +160,7 @@ public void ResolveWithDefaults() } } - foreach (PathEntry entry in entriesToRemove) + foreach (var entry in entriesToRemove) { Paths.Remove(entry); } diff --git a/src/BizHawk.Client.Common/config/PathEntryCollectionExtensions.cs b/src/BizHawk.Client.Common/config/PathEntryCollectionExtensions.cs index 9ae93cdf6a9..8798590d898 100644 --- a/src/BizHawk.Client.Common/config/PathEntryCollectionExtensions.cs +++ b/src/BizHawk.Client.Common/config/PathEntryCollectionExtensions.cs @@ -22,7 +22,7 @@ public static string BaseFor(this PathEntryCollection collection, string systemI public static string GlobalBaseAbsolutePath(this PathEntryCollection collection) { - var globalBase = collection[PathEntryCollection.GLOBAL, "Base"].Path; + string globalBase = collection[PathEntryCollection.GLOBAL, "Base"].Path; // if %exe% prefixed then substitute exe path and repeat if (globalBase.StartsWith("%exe%", StringComparison.InvariantCultureIgnoreCase)) @@ -56,7 +56,7 @@ public static PathEntry EntryWithFallback(this PathEntryCollection collection, s public static string AbsolutePathForType(this PathEntryCollection collection, string systemId, string type) { - var path = collection.EntryWithFallback(type, systemId).Path; + string path = collection.EntryWithFallback(type, systemId).Path; return collection.AbsolutePathFor(path, systemId); } @@ -67,12 +67,10 @@ public static string AbsolutePathForType(this PathEntryCollection collection, st /// Logic will fallback until an absolute path is found, /// using Global Base as a last resort /// - public static string AbsolutePathFor(this PathEntryCollection collection, string path, string systemId) - { + public static string AbsolutePathFor(this PathEntryCollection collection, string path, string systemId) => // warning: supposedly Path.GetFullPath accesses directories (and needs permissions) // if this poses a problem, we need to paste code from .net or mono sources and fix them to not pose problems, rather than homebrew stuff - return Path.GetFullPath(collection.AbsolutePathForInner(path, systemId)); - } + Path.GetFullPath(collection.AbsolutePathForInner(path, systemId)); private static string AbsolutePathForInner(this PathEntryCollection collection, string path, string systemId) { @@ -136,54 +134,51 @@ private static string AbsolutePathForInner(this PathEntryCollection collection, public static string MovieAbsolutePath(this PathEntryCollection collection) { - var path = collection[PathEntryCollection.GLOBAL, "Movies"].Path; + string path = collection[PathEntryCollection.GLOBAL, "Movies"].Path; return collection.AbsolutePathFor(path, null); } public static string MovieBackupsAbsolutePath(this PathEntryCollection collection) { - var path = collection[PathEntryCollection.GLOBAL, "Movie backups"].Path; + string path = collection[PathEntryCollection.GLOBAL, "Movie backups"].Path; return collection.AbsolutePathFor(path, null); } public static string AvAbsolutePath(this PathEntryCollection collection) { - var path = collection[PathEntryCollection.GLOBAL, "A/V Dumps"].Path; + string path = collection[PathEntryCollection.GLOBAL, "A/V Dumps"].Path; return collection.AbsolutePathFor(path, null); } public static string LuaAbsolutePath(this PathEntryCollection collection) { - var path = collection[PathEntryCollection.GLOBAL, "Lua"].Path; + string path = collection[PathEntryCollection.GLOBAL, "Lua"].Path; return collection.AbsolutePathFor(path, null); } - public static string FirmwareAbsolutePath(this PathEntryCollection collection) - { - return collection.AbsolutePathFor(collection.FirmwaresPathFragment, null); - } + public static string FirmwareAbsolutePath(this PathEntryCollection collection) => collection.AbsolutePathFor(collection.FirmwaresPathFragment, null); public static string LogAbsolutePath(this PathEntryCollection collection) { - var path = collection.ResolveToolsPath(collection[PathEntryCollection.GLOBAL, "Debug Logs"].Path); + string path = collection.ResolveToolsPath(collection[PathEntryCollection.GLOBAL, "Debug Logs"].Path); return collection.AbsolutePathFor(path, null); } public static string WatchAbsolutePath(this PathEntryCollection collection) { - var path = collection.ResolveToolsPath(collection[PathEntryCollection.GLOBAL, "Watch (.wch)"].Path); + string path = collection.ResolveToolsPath(collection[PathEntryCollection.GLOBAL, "Watch (.wch)"].Path); return collection.AbsolutePathFor(path, null); } public static string ToolsAbsolutePath(this PathEntryCollection collection) { - var path = collection[PathEntryCollection.GLOBAL, "Tools"].Path; + string path = collection[PathEntryCollection.GLOBAL, "Tools"].Path; return collection.AbsolutePathFor(path, null); } public static string MultiDiskAbsolutePath(this PathEntryCollection collection) { - var path = collection.ResolveToolsPath(collection[PathEntryCollection.GLOBAL, "Multi-Disk Bundles"].Path); + string path = collection.ResolveToolsPath(collection[PathEntryCollection.GLOBAL, "Multi-Disk Bundles"].Path); return collection.AbsolutePathFor(path, null); } @@ -213,7 +208,7 @@ public static string RomAbsolutePath(this PathEntryCollection collection, string public static string SaveRamAbsolutePath(this PathEntryCollection collection, IGameInfo game, IMovie movie) { - var name = game.FilesystemSafeName(); + string name = game.FilesystemSafeName(); if (movie.IsActive()) { name += $".{Path.GetFileNameWithoutExtension(movie.Filename)}"; @@ -228,7 +223,7 @@ public static string SaveRamAbsolutePath(this PathEntryCollection collection, IG // Shenanigans public static string RetroSaveRamAbsolutePath(this PathEntryCollection collection, IGameInfo game) { - var name = game.FilesystemSafeName(); + string name = game.FilesystemSafeName(); name = Path.GetDirectoryName(name); if (name == "") { @@ -246,7 +241,7 @@ public static string RetroSaveRamAbsolutePath(this PathEntryCollection collectio // Shenanigans public static string RetroSystemAbsolutePath(this PathEntryCollection collection, IGameInfo game) { - var name = game.FilesystemSafeName(); + string name = game.FilesystemSafeName(); name = Path.GetDirectoryName(name); if (string.IsNullOrEmpty(name)) { @@ -261,7 +256,7 @@ public static string RetroSystemAbsolutePath(this PathEntryCollection collection public static string AutoSaveRamAbsolutePath(this PathEntryCollection collection, IGameInfo game, IMovie movie) { - var path = collection.SaveRamAbsolutePath(game, movie); + string path = collection.SaveRamAbsolutePath(game, movie); return path.Insert(path.Length - 8, ".AutoSaveRAM"); } @@ -289,15 +284,9 @@ public static string ScreenshotAbsolutePathFor(this PathEntryCollection collecti return collection.AbsolutePathFor(entry.Path, systemId); } - public static string PalettesAbsolutePathFor(this PathEntryCollection collection, string systemId) - { - return collection.AbsolutePathFor(collection[systemId, "Palettes"].Path, systemId); - } + public static string PalettesAbsolutePathFor(this PathEntryCollection collection, string systemId) => collection.AbsolutePathFor(collection[systemId, "Palettes"].Path, systemId); - public static string UserAbsolutePathFor(this PathEntryCollection collection, string systemId) - { - return collection.AbsolutePathFor(collection[systemId, "User"].Path, systemId); - } + public static string UserAbsolutePathFor(this PathEntryCollection collection, string systemId) => collection.AbsolutePathFor(collection[systemId, "User"].Path, systemId); /// /// Takes an absolute path and attempts to convert it to a relative, based on the system, @@ -316,7 +305,7 @@ public static void RefreshTempPath(this PathEntryCollection collection) { if (string.IsNullOrWhiteSpace(collection.TempFilesFragment)) return; - var path = collection.AbsolutePathFor(collection.TempFilesFragment, null); + string path = collection.AbsolutePathFor(collection.TempFilesFragment, null); TempFileManager.HelperSetTempPath(path); } @@ -324,7 +313,7 @@ private static string ResolveToolsPath(this PathEntryCollection collection, stri { if (Path.IsPathRooted(subPath) || subPath.StartsWith('%')) return subPath; - var toolsPath = collection[PathEntryCollection.GLOBAL, "Tools"].Path; + string toolsPath = collection[PathEntryCollection.GLOBAL, "Tools"].Path; // Hack for backwards compatibility, prior to 1.11.5, .wch files were in .\Tools, we don't want that to turn into .Tools\Tools if (subPath == "Tools") diff --git a/src/BizHawk.Client.Common/config/ToolDialogSettings.cs b/src/BizHawk.Client.Common/config/ToolDialogSettings.cs index 5c2304af1ba..a92f0f2b424 100644 --- a/src/BizHawk.Client.Common/config/ToolDialogSettings.cs +++ b/src/BizHawk.Client.Common/config/ToolDialogSettings.cs @@ -89,10 +89,10 @@ public Point TopLeft public bool UseWindowSize => SaveWindowPosition && Width.HasValue && Height.HasValue; [JsonIgnore] - public Point WindowPosition => new Point(Wndx ?? 0, Wndy ?? 0); + public Point WindowPosition => new(Wndx ?? 0, Wndy ?? 0); [JsonIgnore] - public Size WindowSize => new Size(Width ?? 0, Height ?? 0); + public Size WindowSize => new(Width ?? 0, Height ?? 0); public class ColumnList : List { diff --git a/src/BizHawk.Client.Common/controllers/AutofireController.cs b/src/BizHawk.Client.Common/controllers/AutofireController.cs index 854562f323d..cea11a2fa06 100644 --- a/src/BizHawk.Client.Common/controllers/AutofireController.cs +++ b/src/BizHawk.Client.Common/controllers/AutofireController.cs @@ -21,9 +21,9 @@ public AutofireController(IEmulator emulator, int on, int off) private readonly IEmulator _emulator; - private readonly WorkingDictionary> _bindings = new WorkingDictionary>(); - private readonly WorkingDictionary _buttons = new WorkingDictionary(); - private readonly WorkingDictionary _buttonStarts = new WorkingDictionary(); + private readonly WorkingDictionary> _bindings = new(); + private readonly WorkingDictionary _buttons = new(); + private readonly WorkingDictionary _buttonStarts = new(); public int On { get; set; } public int Off { get; set; } @@ -34,20 +34,14 @@ public AutofireController(IEmulator emulator, int on, int off) public bool IsPressed(string button) { - var a = (internal_frame - _buttonStarts[button]) % (On + Off); + int a = (internal_frame - _buttonStarts[button]) % (On + Off); return a < On && _buttons[button]; } - public void ClearStarts() - { - _buttonStarts.Clear(); - } + public void ClearStarts() => _buttonStarts.Clear(); /// always - public int AxisValue(string name) - { - throw new NotImplementedException(); - } + public int AxisValue(string name) => throw new NotImplementedException(); public IReadOnlyCollection<(string Name, int Strength)> GetHapticsSnapshot() => Array.Empty<(string, int)>(); @@ -63,7 +57,7 @@ public void LatchFromPhysical(IController controller) foreach (var (k, v) in _bindings) { - foreach (var boundBtn in v) + foreach (string boundBtn in v) { if (_buttons[k] == false && controller.IsPressed(boundBtn)) { @@ -76,7 +70,7 @@ public void LatchFromPhysical(IController controller) foreach (var (k, v) in _bindings) { _buttons[k] = false; - foreach (var button in v) + foreach (string button in v) { if (controller.IsPressed(button)) { @@ -90,8 +84,8 @@ public void BindMulti(string button, string controlString) { if (!string.IsNullOrEmpty(controlString)) { - var controlBindings = controlString.Split(','); - foreach (var control in controlBindings) + string[] controlBindings = controlString.Split(','); + foreach (string control in controlBindings) { _bindings[button].Add(control.Trim()); } @@ -100,7 +94,7 @@ public void BindMulti(string button, string controlString) public void IncrementStarts() { - foreach (var key in _buttonStarts.Keys.ToArray()) + foreach (string key in _buttonStarts.Keys.ToArray()) { _buttonStarts[key]++; } diff --git a/src/BizHawk.Client.Common/controllers/ClickyVirtualPadController.cs b/src/BizHawk.Client.Common/controllers/ClickyVirtualPadController.cs index 2c39ea71228..d048277e697 100644 --- a/src/BizHawk.Client.Common/controllers/ClickyVirtualPadController.cs +++ b/src/BizHawk.Client.Common/controllers/ClickyVirtualPadController.cs @@ -11,7 +11,7 @@ namespace BizHawk.Client.Common /// public class ClickyVirtualPadController : IController { - private readonly HashSet _pressed = new HashSet(); + private readonly HashSet _pressed = new(); public ControllerDefinition Definition { get; set; } diff --git a/src/BizHawk.Client.Common/controllers/SimpleController.cs b/src/BizHawk.Client.Common/controllers/SimpleController.cs index 59542794253..071ab90f7e5 100644 --- a/src/BizHawk.Client.Common/controllers/SimpleController.cs +++ b/src/BizHawk.Client.Common/controllers/SimpleController.cs @@ -48,10 +48,7 @@ public bool this[string button] public IReadOnlyDictionary BoolButtons() => Buttons; - public void AcceptNewAxis(string axisId, int value) - { - Axes[axisId] = value; - } + public void AcceptNewAxis(string axisId, int value) => Axes[axisId] = value; public void AcceptNewAxes(IEnumerable<(string AxisID, int Value)> newValues) { diff --git a/src/BizHawk.Client.Common/display/IInputDisplayGenerator.cs b/src/BizHawk.Client.Common/display/IInputDisplayGenerator.cs index 473cd3d2481..e74cfa80bc7 100644 --- a/src/BizHawk.Client.Common/display/IInputDisplayGenerator.cs +++ b/src/BizHawk.Client.Common/display/IInputDisplayGenerator.cs @@ -31,13 +31,13 @@ public Bk2InputDisplayGenerator(string systemId, IController source) public string Generate() { - var sb = new StringBuilder(); + StringBuilder sb = new(); foreach (var (button, range, mnemonicChar) in _cachedInputSpecs) { if (range is not null) { - var val = _source.AxisValue(button); + int val = _source.AxisValue(button); if (val == range.Value.Neutral) { diff --git a/src/BizHawk.Client.Common/fwmanager/FirmwareManager.cs b/src/BizHawk.Client.Common/fwmanager/FirmwareManager.cs index 1bcd584f870..d5b09f40683 100644 --- a/src/BizHawk.Client.Common/fwmanager/FirmwareManager.cs +++ b/src/BizHawk.Client.Common/fwmanager/FirmwareManager.cs @@ -19,19 +19,19 @@ public sealed class FirmwareManager public static (byte[] Patched, string ActualHash) PerformPatchInMemory(byte[] @base, in FirmwarePatchOption patchOption) { - var patched = patchOption.Patches.Aggregate(seed: @base, (a, fpd) => fpd.ApplyToMutating(a)); + byte[] patched = patchOption.Patches.Aggregate(seed: @base, (a, fpd) => fpd.ApplyToMutating(a)); return (patched, SHA1Checksum.ComputeDigestHex(patched)); } public static (string FilePath, int FileSize, FirmwareFile FF) PerformPatchOnDisk(string baseFilename, in FirmwarePatchOption patchOption, PathEntryCollection pathEntries) { - var @base = File.ReadAllBytes(baseFilename); + byte[] @base = File.ReadAllBytes(baseFilename); var (patched, actualHash) = PerformPatchInMemory(@base, in patchOption); Trace.Assert(actualHash == patchOption.TargetHash); - var patchedParentDir = Path.Combine(pathEntries[PathEntryCollection.GLOBAL, "Temp Files"].Path, "AutopatchedFirmware"); + string patchedParentDir = Path.Combine(pathEntries[PathEntryCollection.GLOBAL, "Temp Files"].Path, "AutopatchedFirmware"); Directory.CreateDirectory(patchedParentDir); var ff = FirmwareDatabase.FirmwareFilesByHash[patchOption.TargetHash]; - var patchedFilePath = Path.Combine(patchedParentDir, ff.RecommendedName); + string patchedFilePath = Path.Combine(patchedParentDir, ff.RecommendedName); File.WriteAllBytes(patchedFilePath, patched); return (patchedFilePath, @base.Length, ff); // patches can't change length with the current implementation } @@ -48,12 +48,12 @@ public static (string FilePath, int FileSize, FirmwareFile FF) PerformPatchOnDis private ResolutionInfo? AttemptPatch(FirmwareRecord requested, PathEntryCollection pathEntries, IDictionary userSpecifications) { // look for patchsets where 1. they produce a file that fulfils the request, and 2. a matching input file is present in the firmware dir - var targetOptionHashes = FirmwareDatabase.FirmwareOptions.Where(fo => fo.ID == requested.ID).Select(fo => fo.Hash).ToList(); - var presentBaseFiles = _resolutionDictionary.Values.Select(ri => ri.Hash).ToList(); //TODO might want to use files which are known (in the database), but not assigned to any record + List targetOptionHashes = FirmwareDatabase.FirmwareOptions.Where(fo => fo.ID == requested.ID).Select(fo => fo.Hash).ToList(); + List presentBaseFiles = _resolutionDictionary.Values.Select(ri => ri.Hash).ToList(); //TODO might want to use files which are known (in the database), but not assigned to any record var patchOption = FirmwareDatabase.AllPatches.FirstOrNull(fpo => targetOptionHashes.Contains(fpo.TargetHash) && presentBaseFiles.Contains(fpo.BaseHash)); if (patchOption is null) return null; // found one, proceed with patching the base file - var baseFilename = _resolutionDictionary.Values.First(ri => ri.Hash == patchOption.Value.BaseHash).FilePath!; + string baseFilename = _resolutionDictionary.Values.First(ri => ri.Hash == patchOption.Value.BaseHash).FilePath!; var (patchedFilePath, patchedFileLength, ff) = PerformPatchOnDisk(baseFilename, patchOption.Value, pathEntries); // cache and return this new file's metadata userSpecifications[requested.ID.ConfigKey] = patchedFilePath; @@ -111,7 +111,7 @@ public RealFirmwareFile Read(FileInfo fi) // we can let it fall through here, as ReadAllBytes just reads all bytes starting from the stream position :) } - var hash = SHA1Checksum.ComputeDigestHex(fs.ReadAllBytes()); + string hash = SHA1Checksum.ComputeDigestHex(fs.ReadAllBytes()); return _dict![hash] = new RealFirmwareFile(fi, hash); } } @@ -123,16 +123,16 @@ public bool CanFileBeImported(string f) { try { - var fi = new FileInfo(f); + FileInfo fi = new(f); if (!fi.Exists) return false; // weed out filesizes first to reduce the unnecessary overhead of a hashing operation if (!_firmwareSizes.Contains(fi.Length)) return false; // check the hash - var reader = new RealFirmwareReader(); + RealFirmwareReader reader = new(); reader.Read(fi); - var hash = reader.Dict.Values.First().Hash; + string hash = reader.Dict.Values.First().Hash; return FirmwareDatabase.FirmwareFiles.Any(a => a.Hash == hash); } catch @@ -143,10 +143,10 @@ public bool CanFileBeImported(string f) public void DoScanAndResolve(PathEntryCollection pathEntries, IDictionary userSpecifications) { - var reader = new RealFirmwareReader(); + RealFirmwareReader reader = new(); // build a list of files under the global firmwares path, and build a hash for each of them (as ResolutionInfo) while we're at it - var todo = new Queue(new[] { new DirectoryInfo(pathEntries.AbsolutePathFor(pathEntries.FirmwaresPathFragment, null)) }); + Queue todo = new(new[] { new DirectoryInfo(pathEntries.AbsolutePathFor(pathEntries.FirmwaresPathFragment, null)) }); while (todo.Count != 0) { var di = todo.Dequeue(); @@ -180,7 +180,7 @@ public void DoScanAndResolve(PathEntryCollection pathEntries, IDictionary + foreach (string? k in Buttons.Keys.Where(k => k.EndsWithOrdinal($"+{ie.LogicalButton.Button}") || k.StartsWithOrdinal($"{ie.LogicalButton.Button}+") || k.Contains($"+{ie.LogicalButton.Button}+")) .ToArray()) Buttons[k] = false; @@ -33,7 +33,7 @@ public sealed class ControllerInputCoalescer : InputCoalescer protected override void ProcessSubsets(string button, bool state) { // For controller input, we want Shift+X to register as both Shift and X (for Keyboard controllers) - foreach (var s in button.Split('+')) Buttons[s] = state; + foreach (string? s in button.Split('+')) Buttons[s] = state; } } } diff --git a/src/BizHawk.Client.Common/input/InputEvent.cs b/src/BizHawk.Client.Common/input/InputEvent.cs index dd7a7d3572d..8f8c0acf60d 100644 --- a/src/BizHawk.Client.Common/input/InputEvent.cs +++ b/src/BizHawk.Client.Common/input/InputEvent.cs @@ -69,9 +69,9 @@ public override readonly string ToString() if (Modifiers is 0U) return Button; var allMods = _getEffectiveModListCallback(); StringBuilder ret = new(); - for (var i = 0; i < allMods.Count; i++) + for (int i = 0; i < allMods.Count; i++) { - var b = 1U << i; + uint b = 1U << i; if ((Modifiers & b) is not 0U) { ret.Append(allMods[i]); diff --git a/src/BizHawk.Client.Common/inputAdapters/AutoPattern.cs b/src/BizHawk.Client.Common/inputAdapters/AutoPattern.cs index b1a832c0c37..76ce40908df 100644 --- a/src/BizHawk.Client.Common/inputAdapters/AutoPattern.cs +++ b/src/BizHawk.Client.Common/inputAdapters/AutoPattern.cs @@ -57,15 +57,9 @@ public bool GetNextValue(bool isLag = false) /// /// Gets the next value without incrementing index. /// - public bool PeekNextValue() - { - return Pattern[_index]; - } + public bool PeekNextValue() => Pattern[_index]; - public void Reset() - { - _index = 0; - } + public void Reset() => _index = 0; } public class AutoPatternAxis @@ -134,14 +128,8 @@ public int GetNextValue(bool isLag = false) /// /// Gets the next value without incrementing index. /// - public int PeekNextValue() - { - return Pattern[_index]; - } + public int PeekNextValue() => Pattern[_index]; - public void Reset() - { - _index = 0; - } + public void Reset() => _index = 0; } } diff --git a/src/BizHawk.Client.Common/inputAdapters/InputManager.cs b/src/BizHawk.Client.Common/inputAdapters/InputManager.cs index edf2174518b..8e1642bfcf8 100644 --- a/src/BizHawk.Client.Common/inputAdapters/InputManager.cs +++ b/src/BizHawk.Client.Common/inputAdapters/InputManager.cs @@ -90,10 +90,7 @@ public void ToggleStickies() AutofireStickyXorAdapter.MassToggleStickyState(AutoFireController.PressedButtons); } - public void ToggleAutoStickies() - { - AutofireStickyXorAdapter.MassToggleStickyState(ActiveController.PressedButtons); - } + public void ToggleAutoStickies() => AutofireStickyXorAdapter.MassToggleStickyState(ActiveController.PressedButtons); private static Controller BindToDefinition( ControllerDefinition def, @@ -101,12 +98,12 @@ private static Controller BindToDefinition( IDictionary> analogBinds, IDictionary> feedbackBinds) { - var ret = new Controller(def); + Controller ret = new(def); if (allBinds.TryGetValue(def.Name, out var binds)) { - foreach (var btn in def.BoolButtons) + foreach (string btn in def.BoolButtons) { - if (binds.TryGetValue(btn, out var bind)) + if (binds.TryGetValue(btn, out string bind)) { ret.BindMulti(btn, bind); } @@ -115,7 +112,7 @@ private static Controller BindToDefinition( if (analogBinds.TryGetValue(def.Name, out var aBinds)) { - foreach (var btn in def.Axes.Keys) + foreach (string btn in def.Axes.Keys) { if (aBinds.TryGetValue(btn, out var bind)) { @@ -126,7 +123,7 @@ private static Controller BindToDefinition( if (feedbackBinds.TryGetValue(def.Name, out var fBinds)) { - foreach (var channel in def.HapticsChannels) + foreach (string channel in def.HapticsChannels) { if (fBinds.TryGetValue(channel, out var bind)) ret.BindFeedbackChannel(channel, bind); } @@ -141,12 +138,12 @@ private static AutofireController BindToDefinitionAF( int on, int off) { - var ret = new AutofireController(emulator, on, off); + AutofireController ret = new(emulator, on, off); if (allBinds.TryGetValue(emulator.ControllerDefinition.Name, out var binds)) { - foreach (var btn in emulator.ControllerDefinition.BoolButtons) + foreach (string btn in emulator.ControllerDefinition.BoolButtons) { - if (binds.TryGetValue(btn, out var bind)) + if (binds.TryGetValue(btn, out string bind)) { ret.BindMulti(btn, bind); } diff --git a/src/BizHawk.Client.Common/inputAdapters/OverrideAdapter.cs b/src/BizHawk.Client.Common/inputAdapters/OverrideAdapter.cs index 9373b86d92c..78918ad9095 100644 --- a/src/BizHawk.Client.Common/inputAdapters/OverrideAdapter.cs +++ b/src/BizHawk.Client.Common/inputAdapters/OverrideAdapter.cs @@ -15,16 +15,16 @@ public class OverrideAdapter : IController public IInputDisplayGenerator InputDisplayGenerator { get; set; } = null; - private readonly Dictionary _overrides = new Dictionary(); - private readonly Dictionary _axisOverrides = new Dictionary(); - private readonly List _inverses = new List(); + private readonly Dictionary _overrides = new(); + private readonly Dictionary _axisOverrides = new(); + private readonly List _inverses = new(); /// not overridden public bool IsPressed(string button) - => _overrides.TryGetValue(button, out var b) ? b : throw new InvalidOperationException(); + => _overrides.TryGetValue(button, out bool b) ? b : throw new InvalidOperationException(); public int AxisValue(string name) - => _axisOverrides.TryGetValue(name, out var i) ? i : 0; + => _axisOverrides.TryGetValue(name, out int i) ? i : 0; public IReadOnlyCollection<(string Name, int Strength)> GetHapticsSnapshot() => throw new NotImplementedException(); // no idea --yoshi @@ -51,10 +51,7 @@ public void UnSet(string button) _inverses.Remove(button); } - public void SetInverse(string button) - { - _inverses.Add(button); - } + public void SetInverse(string button) => _inverses.Add(button); public void FrameTick() { diff --git a/src/BizHawk.Client.Common/inputAdapters/StickyAdapters.cs b/src/BizHawk.Client.Common/inputAdapters/StickyAdapters.cs index 69fbeb89e19..900ac9c68ad 100644 --- a/src/BizHawk.Client.Common/inputAdapters/StickyAdapters.cs +++ b/src/BizHawk.Client.Common/inputAdapters/StickyAdapters.cs @@ -19,14 +19,14 @@ public class StickyXorAdapter : IStickyAdapter public bool IsPressed(string button) { - var source = Source.IsPressed(button); + bool source = Source.IsPressed(button); source ^= CurrentStickies.Contains(button); return source; } public int AxisValue(string name) { - var val = _axisSet[name]; + int? val = _axisSet[name]; if (val.HasValue) { @@ -47,11 +47,11 @@ public int AxisValue(string name) public IController Source { get; set; } - private List _justPressed = new List(); + private List _justPressed = new(); // if SetAxis() is called (typically virtual pads), then that axis will entirely override the Source input // otherwise, the source is passed thru. - private readonly WorkingDictionary _axisSet = new WorkingDictionary(); + private readonly WorkingDictionary _axisSet = new(); public void SetAxis(string name, int? value) { @@ -97,7 +97,7 @@ public void ClearStickies() public void MassToggleStickyState(List buttons) { - foreach (var button in buttons.Where(button => !_justPressed.Contains(button))) + foreach (string button in buttons.Where(button => !_justPressed.Contains(button))) { if (CurrentStickies.Contains(button)) { @@ -121,7 +121,7 @@ public class AutoFireStickyXorAdapter : IStickyAdapter, IInputAdapter public bool IsPressed(string button) { - var source = Source.IsPressed(button); + bool source = Source.IsPressed(button); bool patternValue = false; if (_boolPatterns.TryGetValue(button, out var pattern)) { @@ -154,8 +154,8 @@ public void SetOnOffPatternFromConfig(int on, int off) _off = off < 0 ? 0 : off; } - private readonly WorkingDictionary _boolPatterns = new WorkingDictionary(); - private readonly WorkingDictionary _axisPatterns = new WorkingDictionary(); + private readonly WorkingDictionary _boolPatterns = new(); + private readonly WorkingDictionary _axisPatterns = new(); public AutoFireStickyXorAdapter() { @@ -191,12 +191,9 @@ public void SetSticky(string button, bool isSticky, AutoPatternBool pattern = nu } } - public bool IsSticky(string button) - { - return _boolPatterns.ContainsKey(button) || _axisPatterns.ContainsKey(button); - } + public bool IsSticky(string button) => _boolPatterns.ContainsKey(button) || _axisPatterns.ContainsKey(button); - public HashSet CurrentStickies => new HashSet(_boolPatterns.Keys); + public HashSet CurrentStickies => new(_boolPatterns.Keys); public void ClearStickies() { @@ -217,11 +214,11 @@ public void IncrementLoops(bool lagged) } } - private List _justPressed = new List(); + private List _justPressed = new(); public void MassToggleStickyState(List buttons) { - foreach (var button in buttons.Where(button => !_justPressed.Contains(button))) + foreach (string button in buttons.Where(button => !_justPressed.Contains(button))) { SetSticky(button, !_boolPatterns.ContainsKey(button)); } diff --git a/src/BizHawk.Client.Common/lua/CommonLibs/ClientLuaLibrary.cs b/src/BizHawk.Client.Common/lua/CommonLibs/ClientLuaLibrary.cs index 6619ea5907e..30dcfbc4264 100644 --- a/src/BizHawk.Client.Common/lua/CommonLibs/ClientLuaLibrary.cs +++ b/src/BizHawk.Client.Common/lua/CommonLibs/ClientLuaLibrary.cs @@ -53,17 +53,11 @@ public int BorderWidth() [LuaMethodExample("local inclibuf = client.bufferheight( );")] [LuaMethod("bufferheight", "Gets the visible height of the emu display surface (the core video output). This excludes the gameExtraPadding you've set.")] - public int BufferHeight() - { - return VideoProvider?.BufferHeight ?? NullVideo.Instance.BufferHeight; // TODO: consider exposing the video provider from mainform, so it can decide NullVideo is the correct substitute - } + public int BufferHeight() => VideoProvider?.BufferHeight ?? NullVideo.Instance.BufferHeight; // TODO: consider exposing the video provider from mainform, so it can decide NullVideo is the correct substitute [LuaMethodExample("local inclibuf = client.bufferwidth( );")] [LuaMethod("bufferwidth", "Gets the visible width of the emu display surface (the core video output). This excludes the gameExtraPadding you've set.")] - public int BufferWidth() - { - return VideoProvider?.BufferWidth ?? NullVideo.Instance.BufferWidth; - } + public int BufferWidth() => VideoProvider?.BufferWidth ?? NullVideo.Instance.BufferWidth; [LuaMethodExample("client.clearautohold( );")] [LuaMethod("clearautohold", "Clears all autohold keys")] @@ -201,7 +195,7 @@ public void OpenRamSearch() public bool OpenRom(string path) { _luaLibsImpl.IsRebootingCore = true; - var success = APIs.EmuClient.OpenRom(path); + bool success = APIs.EmuClient.OpenRom(path); _luaLibsImpl.IsRebootingCore = false; return success; } @@ -322,10 +316,7 @@ public int Ypos() [LuaMethodExample("local incbhver = client.getversion( );")] [LuaMethod("getversion", "Returns the current stable BizHawk version")] - public static string GetVersion() - { - return VersionInfo.MainVersion; - } + public static string GetVersion() => VersionInfo.MainVersion; [LuaMethodExample("local nlcliget = client.getavailabletools( );")] [LuaMethod("getavailabletools", "Returns a list of the tools currently open")] @@ -344,7 +335,7 @@ public LuaTable GetTool(string name) [LuaMethod("createinstance", "returns a default instance of the given type of object if it exists (not case sensitive). Note: This will only work on objects which have a parameterless constructor. If no suitable type is found, or the type does not have a parameterless constructor, then nil is returned")] public LuaTable CreateInstance(string name) { - var instance = APIs.Tool.CreateInstance(name); + object instance = APIs.Tool.CreateInstance(name); return instance == null ? null : _th.ObjectToTable(instance); } @@ -360,10 +351,7 @@ public void SaveRam() [LuaMethodExample("client.sleep( 50 );")] [LuaMethod("sleep", "sleeps for n milliseconds")] - public void Sleep(int millis) - { - Thread.Sleep(millis); - } + public void Sleep(int millis) => Thread.Sleep(millis); [LuaMethodExample("client.exactsleep( 50 );")] [LuaMethod("exactsleep", "sleeps exactly for n milliseconds")] @@ -397,8 +385,8 @@ public void AddCheat(string code) Log($"cheat codes not supported by the current system: {MainForm.Emulator.SystemId}"); return; } - - var decoder = new GameSharkDecoder(MainForm.Emulator.AsMemoryDomains(), MainForm.Emulator.SystemId); + + GameSharkDecoder decoder = new(MainForm.Emulator.AsMemoryDomains(), MainForm.Emulator.SystemId); var result = decoder.Decode(code); if (result.IsValid(out var valid)) @@ -427,7 +415,7 @@ public void RemoveCheat(string code) return; } - var decoder = new GameSharkDecoder(MainForm.Emulator.AsMemoryDomains(), MainForm.Emulator.SystemId); + GameSharkDecoder decoder = new(MainForm.Emulator.AsMemoryDomains(), MainForm.Emulator.SystemId); var result = decoder.Decode(code); if (result.IsValid(out var valid)) diff --git a/src/BizHawk.Client.Common/lua/CommonLibs/CommLuaLibrary.cs b/src/BizHawk.Client.Common/lua/CommonLibs/CommLuaLibrary.cs index bc44d08d1cb..62422c2faaf 100644 --- a/src/BizHawk.Client.Common/lua/CommonLibs/CommLuaLibrary.cs +++ b/src/BizHawk.Client.Common/lua/CommonLibs/CommLuaLibrary.cs @@ -22,7 +22,7 @@ public CommLuaLibrary(ILuaLibraries luaLibsImpl, ApiContainer apiContainer, Acti [LuaMethod("getluafunctionslist", "returns a list of implemented functions")] public static string GetLuaFunctionsList() { - var list = new StringBuilder(); + StringBuilder list = new(); foreach (var function in typeof(CommLuaLibrary).GetMethods()) { list.AppendLine(function.ToString()); @@ -73,10 +73,7 @@ public string SocketServerResponse() } [LuaMethod("socketServerSuccessful", "returns the status of the last Socket server action")] - public bool SocketServerSuccessful() - { - return CheckSocketServer() && APIs.Comm.Sockets.Successful; - } + public bool SocketServerSuccessful() => CheckSocketServer() && APIs.Comm.Sockets.Successful; [LuaMethod("socketServerSetTimeout", "sets the timeout in milliseconds for receiving messages")] public void SocketServerSetTimeout(int timeout) @@ -100,16 +97,10 @@ public void SocketServerSetPort(int port) } [LuaMethod("socketServerGetIp", "returns the IP address of the Lua socket server")] - public string SocketServerGetIp() - { - return APIs.Comm.Sockets?.IP; - } + public string SocketServerGetIp() => APIs.Comm.Sockets?.IP; [LuaMethod("socketServerGetPort", "returns the port of the Lua socket server")] - public int? SocketServerGetPort() - { - return APIs.Comm.Sockets?.Port; - } + public int? SocketServerGetPort() => APIs.Comm.Sockets?.Port; [LuaMethod("socketServerGetInfo", "returns the IP and port of the Lua socket server")] public string SocketServerGetInfo() diff --git a/src/BizHawk.Client.Common/lua/CommonLibs/EmulationLuaLibrary.cs b/src/BizHawk.Client.Common/lua/CommonLibs/EmulationLuaLibrary.cs index 879e741a397..8532b867002 100644 --- a/src/BizHawk.Client.Common/lua/CommonLibs/EmulationLuaLibrary.cs +++ b/src/BizHawk.Client.Common/lua/CommonLibs/EmulationLuaLibrary.cs @@ -25,10 +25,7 @@ public void DisplayVsync(bool enabled) [LuaMethodExample("emu.frameadvance( );")] [LuaMethod("frameadvance", "Signals to the emulator to resume emulation. Necessary for any lua script while loop or else the emulator will freeze!")] - public void FrameAdvance() - { - FrameAdvanceCallback(); - } + public void FrameAdvance() => FrameAdvanceCallback(); [LuaMethodExample("local inemufra = emu.framecount( );")] [LuaMethod("framecount", "Returns the current frame count")] @@ -110,10 +107,7 @@ public void SetRenderPlanes(params bool[] luaParam) [LuaMethodExample("emu.yield( );")] [LuaMethod("yield", "allows a script to run while emulation is paused and interact with the gui/main window in realtime ")] - public void Yield() - { - YieldCallback(); - } + public void Yield() => YieldCallback(); [LuaMethodExample("local stemuget = emu.getdisplaytype();")] [LuaMethod("getdisplaytype", "returns the display type (PAL vs NTSC) that the emulator is currently running in")] diff --git a/src/BizHawk.Client.Common/lua/CommonLibs/GuiLuaLibrary.cs b/src/BizHawk.Client.Common/lua/CommonLibs/GuiLuaLibrary.cs index ac7f6a5ba0f..e709a758cf6 100644 --- a/src/BizHawk.Client.Common/lua/CommonLibs/GuiLuaLibrary.cs +++ b/src/BizHawk.Client.Common/lua/CommonLibs/GuiLuaLibrary.cs @@ -76,8 +76,8 @@ public void DrawBezier( { try { - var pointsArr = new Point[4]; - var i = 0; + Point[] pointsArr = new Point[4]; + int i = 0; foreach (var point in _th.EnumerateValues(points) .Select(table => _th.EnumerateValues(table).ToList())) { @@ -217,12 +217,12 @@ public void DrawPolygon( [LuaColorParam] object background = null, string surfaceName = null) { - var pointsList = _th.EnumerateValues(points) + System.Collections.Generic.List> pointsList = _th.EnumerateValues(points) .Select(table => _th.EnumerateValues(table).ToList()).ToList(); try { - var pointsArr = new Point[pointsList.Count]; - var i = 0; + Point[] pointsArr = new Point[pointsList.Count]; + int i = 0; foreach (var point in pointsList) { pointsArr[i] = new Point((int) point[0] + (offsetX ?? 0), (int) point[1] + (offsetY ?? 0)); diff --git a/src/BizHawk.Client.Common/lua/CommonLibs/JoypadLuaLibrary.cs b/src/BizHawk.Client.Common/lua/CommonLibs/JoypadLuaLibrary.cs index 27799327c3d..bc48d834e8a 100644 --- a/src/BizHawk.Client.Common/lua/CommonLibs/JoypadLuaLibrary.cs +++ b/src/BizHawk.Client.Common/lua/CommonLibs/JoypadLuaLibrary.cs @@ -37,7 +37,7 @@ public void SetFromMnemonicStr(string inputLogEntry) [LuaMethod("set", "sets the given buttons to their provided values for the current frame")] public void Set(LuaTable buttons, int? controller = null) { - var dict = new Dictionary(); + Dictionary dict = new(); foreach (var (k, v) in _th.EnumerateEntries(buttons)) { dict[k.ToString()] = Convert.ToBoolean(v); // Accepts 1/0 or true/false @@ -49,10 +49,10 @@ public void Set(LuaTable buttons, int? controller = null) [LuaMethod("setanalog", "sets the given analog controls to their provided values for the current frame. Note that unlike set() there is only the logic of overriding with the given value.")] public void SetAnalog(LuaTable controls, int? controller = null) { - var dict = new Dictionary(); + Dictionary dict = new(); foreach (var (k, v) in _th.EnumerateEntries(controls)) { - dict[k.ToString()] = long.TryParse(v.ToString(), out var d) ? (int) d : null; + dict[k.ToString()] = long.TryParse(v.ToString(), out long d) ? (int) d : null; } APIs.Joypad.SetAnalog(dict, controller); } diff --git a/src/BizHawk.Client.Common/lua/CommonLibs/MemoryLuaLibrary.cs b/src/BizHawk.Client.Common/lua/CommonLibs/MemoryLuaLibrary.cs index 945b378b127..072aacf29a8 100644 --- a/src/BizHawk.Client.Common/lua/CommonLibs/MemoryLuaLibrary.cs +++ b/src/BizHawk.Client.Common/lua/CommonLibs/MemoryLuaLibrary.cs @@ -73,8 +73,7 @@ public LuaTable ReadBytesAsDict(long addr, int length, string domain = null) [LuaDeprecatedMethod] [LuaMethod("writebyterange", "Writes the given values to the given addresses as unsigned bytes")] - public void WriteByteRange(LuaTable memoryblock, string domain = null) - { + public void WriteByteRange(LuaTable memoryblock, string domain = null) => #if true WriteBytesAsDict(memoryblock, domain); #else @@ -98,7 +97,7 @@ public void WriteByteRange(LuaTable memoryblock, string domain = null) Log($"Error: the domain {d.Name} is not writable"); } #endif - } + [LuaMethodExample("memory.write_bytes_as_array(0x100, { 0xAB, 0x12, 0xCD, 0x34 });")] [LuaMethod("write_bytes_as_array", "Writes sequential bytes starting at addr.")] diff --git a/src/BizHawk.Client.Common/lua/CommonLibs/MovieLuaLibrary.cs b/src/BizHawk.Client.Common/lua/CommonLibs/MovieLuaLibrary.cs index c77d116ed99..5918a61acdc 100644 --- a/src/BizHawk.Client.Common/lua/CommonLibs/MovieLuaLibrary.cs +++ b/src/BizHawk.Client.Common/lua/CommonLibs/MovieLuaLibrary.cs @@ -72,7 +72,7 @@ public string Mode() public bool PlayFromStart(string path = "") { _luaLibsImpl.IsRebootingCore = true; - var success = APIs.Movie.PlayFromStart(path); + bool success = APIs.Movie.PlayFromStart(path); _luaLibsImpl.IsRebootingCore = false; return success; } diff --git a/src/BizHawk.Client.Common/lua/CommonLibs/SQLiteLuaLibrary.cs b/src/BizHawk.Client.Common/lua/CommonLibs/SQLiteLuaLibrary.cs index 9ac0170f491..642dc085db7 100644 --- a/src/BizHawk.Client.Common/lua/CommonLibs/SQLiteLuaLibrary.cs +++ b/src/BizHawk.Client.Common/lua/CommonLibs/SQLiteLuaLibrary.cs @@ -34,7 +34,7 @@ public string WriteCommand(string query = "") "Ex: select * from rewards")] public object ReadCommand(string query = "") { - var result = APIs.SQLite.ReadCommand(query); + object result = APIs.SQLite.ReadCommand(query); return result switch { Dictionary dict => _th.DictToTable(dict), diff --git a/src/BizHawk.Client.Common/lua/CommonLibs/SaveStateLuaLibrary.cs b/src/BizHawk.Client.Common/lua/CommonLibs/SaveStateLuaLibrary.cs index 5d9c00e7c62..e04345302e1 100644 --- a/src/BizHawk.Client.Common/lua/CommonLibs/SaveStateLuaLibrary.cs +++ b/src/BizHawk.Client.Common/lua/CommonLibs/SaveStateLuaLibrary.cs @@ -14,7 +14,7 @@ public SaveStateLuaLibrary(ILuaLibraries luaLibsImpl, ApiContainer apiContainer, public bool Load(string path, bool suppressOSD = false) { _luaLibsImpl.IsUpdateSupressed = true; - var success = APIs.SaveState.Load(path, suppressOSD); + bool success = APIs.SaveState.Load(path, suppressOSD); _luaLibsImpl.IsUpdateSupressed = false; return success; } @@ -24,7 +24,7 @@ public bool Load(string path, bool suppressOSD = false) public bool LoadSlot(int slotNum, bool suppressOSD = false) { _luaLibsImpl.IsUpdateSupressed = true; - var success = APIs.SaveState.LoadSlot(slotNum, suppressOSD: suppressOSD); + bool success = APIs.SaveState.LoadSlot(slotNum, suppressOSD: suppressOSD); _luaLibsImpl.IsUpdateSupressed = false; return success; } diff --git a/src/BizHawk.Client.Common/lua/EnvironmentSandbox.cs b/src/BizHawk.Client.Common/lua/EnvironmentSandbox.cs index 3f201935e92..792ea6ed916 100644 --- a/src/BizHawk.Client.Common/lua/EnvironmentSandbox.cs +++ b/src/BizHawk.Client.Common/lua/EnvironmentSandbox.cs @@ -5,10 +5,8 @@ namespace BizHawk.Client.Common { public static class EnvironmentSandbox { - public static void Sandbox(Action callback) - { + public static void Sandbox(Action callback) => // just a stub for right now callback(); - } } } diff --git a/src/BizHawk.Client.Common/lua/LuaDocumentation.cs b/src/BizHawk.Client.Common/lua/LuaDocumentation.cs index fb6d7dd6cd5..ff347599746 100644 --- a/src/BizHawk.Client.Common/lua/LuaDocumentation.cs +++ b/src/BizHawk.Client.Common/lua/LuaDocumentation.cs @@ -10,7 +10,7 @@ public class LuaDocumentation : List { public string ToTASVideosWikiMarkup() { - var sb = new StringBuilder(); + StringBuilder sb = new(); sb.AppendLine("__This is an autogenerated page, do not edit.__ (To update, open the function list dialog on a Debug build and click the wiki button.)") .AppendLine() @@ -76,23 +76,23 @@ public string ToTASVideosWikiMarkup() ** The ''name'' of a callback is an optional parameter in all the event subscription functions. The ''ID'' of a callback is what's returned by the subscription function. Multiple callbacks can share the same name, but IDs are unique. "); - foreach (var library in this.Select(lf => (Name: lf.Library, Description: lf.LibraryDescription)) + foreach (var (Name, Description) in this.Select(lf => (Name: lf.Library, Description: lf.LibraryDescription)) .Distinct() .OrderBy(library => library.Name)) { sb - .AppendFormat("%%TAB {0}%%", library.Name) + .AppendFormat("%%TAB {0}%%", Name) .AppendLine() .AppendLine(); - if (!string.IsNullOrWhiteSpace(library.Description)) + if (!string.IsNullOrWhiteSpace(Description)) { sb - .Append(library.Description) + .Append(Description) .AppendLine() .AppendLine(); } - foreach (var func in this.Where(lf => lf.Library == library.Name).OrderBy(lf => lf.Name)) + foreach (var func in this.Where(lf => lf.Library == Name).OrderBy(lf => lf.Name)) { string deprecated = func.IsDeprecated ? "__[[deprecated]]__ " : ""; sb @@ -135,23 +135,23 @@ public class Completion public string ToSublime2CompletionList() { - var sc = new SublimeCompletions(); + SublimeCompletions sc = new(); foreach (var f in this.OrderBy(lf => lf.Library).ThenBy(lf => lf.Name)) { - var completion = new SublimeCompletions.Completion + SublimeCompletions.Completion completion = new() { Trigger = $"{f.Library}.{f.Name}" }; - var sb = new StringBuilder(); + StringBuilder sb = new(); if (f.ParameterList.Any()) { sb .Append($"{f.Library}.{f.Name}("); - var parameters = f.Method.GetParameters() + List parameters = f.Method.GetParameters() .ToList(); for (int i = 0; i < parameters.Count; i++) @@ -187,10 +187,7 @@ public string ToSublime2CompletionList() return JsonConvert.SerializeObject(sc); } - public string ToNotepadPlusPlusAutoComplete() - { - return ""; // TODO - } + public string ToNotepadPlusPlusAutoComplete() => ""; // TODO } public class LibraryFunction @@ -232,11 +229,11 @@ public string ParameterList { var parameters = Method.GetParameters(); - var list = new StringBuilder(); + StringBuilder list = new(); list.Append('('); - for (var i = 0; i < parameters.Length; i++) + for (int i = 0; i < parameters.Length; i++) { - var p = TypeCleanup(parameters[i].ToString()); + string p = TypeCleanup(parameters[i].ToString()); if (parameters[i].GetCustomAttribute() != null) p = p.Replace("object", "luacolor"); if (parameters[i].IsOptional) { @@ -297,7 +294,7 @@ public string ReturnType { get { - var returnType = Method.ReturnType.ToString(); + string returnType = Method.ReturnType.ToString(); return TypeCleanup(returnType).Trim(); } } diff --git a/src/BizHawk.Client.Common/lua/LuaFileList.cs b/src/BizHawk.Client.Common/lua/LuaFileList.cs index 689a16e88e9..7643480ac28 100644 --- a/src/BizHawk.Client.Common/lua/LuaFileList.cs +++ b/src/BizHawk.Client.Common/lua/LuaFileList.cs @@ -35,10 +35,7 @@ public LuaFileList(IReadOnlyCollection collection, Action onChanged) if (collection != null) AddRange(collection); // doesn't actually trigger callback as the superclass' Add is called; if this class is rewritten without `new` methods, something clever will need to be done, like a bool field _initialised } - public void StopAllScripts() - { - ForEach(lf => lf.State = LuaFile.RunState.Disabled); - } + public void StopAllScripts() => ForEach(lf => lf.State = LuaFile.RunState.Disabled); public new void Clear() { @@ -68,7 +65,7 @@ public void StopAllScripts() public bool Load(string path, bool disableOnLoad) { - var file = new FileInfo(path); + FileInfo file = new(path); if (!file.Exists) { return false; @@ -85,10 +82,10 @@ public bool Load(string path, bool disableOnLoad) } else { - var scriptPath = line.Substring(2, line.Length - 2); + string scriptPath = line.Substring(2, line.Length - 2); if (!Path.IsPathRooted(scriptPath)) { - var directory = Path.GetDirectoryName(path); + string directory = Path.GetDirectoryName(path); scriptPath = Path.GetFullPath(Path.Combine(directory ?? "", scriptPath)); } @@ -107,9 +104,9 @@ public bool Load(string path, bool disableOnLoad) public void Save(string path) { - using var sw = new StreamWriter(path); - var sb = new StringBuilder(); - var saveDirectory = Path.GetDirectoryName(Path.GetFullPath(path)); + using StreamWriter sw = new(path); + StringBuilder sb = new(); + string saveDirectory = Path.GetDirectoryName(Path.GetFullPath(path)); foreach (var file in this) { if (file.IsSeparator) diff --git a/src/BizHawk.Client.Common/lua/LuaFunctionList.cs b/src/BizHawk.Client.Common/lua/LuaFunctionList.cs index 7e20aa4e6ee..6bc86694f2b 100644 --- a/src/BizHawk.Client.Common/lua/LuaFunctionList.cs +++ b/src/BizHawk.Client.Common/lua/LuaFunctionList.cs @@ -9,7 +9,7 @@ namespace BizHawk.Client.Common { public class LuaFunctionList : IEnumerable { - private readonly List _functions = new List(); + private readonly List _functions = new(); private readonly Action Changed; @@ -36,7 +36,7 @@ public bool Remove(NamedLuaFunction function, IEmulator emulator) emulator.AsDebuggable().MemoryCallbacks.Remove(function.MemCallback); } - var result = _functions.Remove(function); + bool result = _functions.Remove(function); if (result) { Changed(); @@ -47,7 +47,7 @@ public bool Remove(NamedLuaFunction function, IEmulator emulator) public void RemoveForFile(LuaFile file, IEmulator emulator) { - var functionsToRemove = _functions.Where(l => l.LuaFile.Path == file.Path || ReferenceEquals(l.LuaFile.Thread, file.Thread)).ToList(); + List functionsToRemove = _functions.Where(l => l.LuaFile.Path == file.Path || ReferenceEquals(l.LuaFile.Thread, file.Thread)).ToList(); foreach (var function in functionsToRemove) { diff --git a/src/BizHawk.Client.Common/lua/LuaHelperLibs/BitLuaLibrary.cs b/src/BizHawk.Client.Common/lua/LuaHelperLibs/BitLuaLibrary.cs index f4620df8b11..fc5cb24cee0 100644 --- a/src/BizHawk.Client.Common/lua/LuaHelperLibs/BitLuaLibrary.cs +++ b/src/BizHawk.Client.Common/lua/LuaHelperLibs/BitLuaLibrary.cs @@ -60,17 +60,11 @@ public uint Lshift(uint val, int amt) [LuaMethodExample("local uibitrol = bit.rol( 1000, 4 );")] [LuaMethod("rol", "Left rotate 'val' by 'amt' bits")] - public static uint Rol(uint val, int amt) - { - return (val << amt) | (val >> (32 - amt)); - } + public static uint Rol(uint val, int amt) => (val << amt) | (val >> (32 - amt)); [LuaMethodExample("local uibitror = bit.ror( 1000, 4 );")] [LuaMethod("ror", "Right rotate 'val' by 'amt' bits")] - public static uint Ror(uint val, int amt) - { - return (val >> amt) | (val << (32 - amt)); - } + public static uint Ror(uint val, int amt) => (val >> amt) | (val << (32 - amt)); [LuaDeprecatedMethod] [LuaMethodExample("local uibitrsh = bit.rshift( 1000, 4 );")] @@ -83,31 +77,19 @@ public uint Rshift(uint val, int amt) [LuaMethodExample("local inbitars = bit.arshift( -1000, 4 );")] [LuaMethod("arshift", "Arithmetic shift right of 'val' by 'amt' bits")] - public static int Arshift(uint val, int amt) - { - return (int)val >> amt; - } + public static int Arshift(uint val, int amt) => (int)val >> amt; [LuaMethodExample("if ( bit.check( -12345, 35 ) ) then\r\n\tconsole.log( \"Returns result of bit 'pos' being set in 'num'\" );\r\nend;")] [LuaMethod("check", "Returns result of bit 'pos' being set in 'num'")] - public static bool Check(long num, int pos) - { - return (num & (1 << pos)) != 0; - } + public static bool Check(long num, int pos) => (num & (1 << pos)) != 0; [LuaMethodExample("local uibitset = bit.set( 25, 35 );")] [LuaMethod("set", "Sets the bit 'pos' in 'num'")] - public static uint Set(uint num, int pos) - { - return num | 1U << pos; - } + public static uint Set(uint num, int pos) => num | 1U << pos; [LuaMethodExample("local lobitcle = bit.clear( 25, 35 );")] [LuaMethod("clear", "Clears the bit 'pos' in 'num'")] - public static long Clear(uint num, int pos) - { - return num & ~(1 << pos); - } + public static long Clear(uint num, int pos) => num & ~(1 << pos); [LuaMethodExample("local usbitbyt = bit.byteswap_16( 100 );")] [LuaMethod("byteswap_16", "Byte swaps 'short', i.e. bit.byteswap_16(0xFF00) would return 0x00FF")] diff --git a/src/BizHawk.Client.Common/lua/LuaHelperLibs/EventsLuaLibrary.cs b/src/BizHawk.Client.Common/lua/LuaHelperLibs/EventsLuaLibrary.cs index 0dc0d636877..9d1b43a6a06 100644 --- a/src/BizHawk.Client.Common/lua/LuaHelperLibs/EventsLuaLibrary.cs +++ b/src/BizHawk.Client.Common/lua/LuaHelperLibs/EventsLuaLibrary.cs @@ -35,10 +35,7 @@ private void LogMemoryCallbacksNotImplemented(bool isWildcard) private void LogMemoryExecuteCallbacksNotImplemented(bool isWildcard) => Log($"{Emulator.Attributes().CoreName} does not implement {(isWildcard ? "wildcard " : string.Empty)}memory execute callbacks"); - private void LogScopeNotAvailable(string scope) - { - Log($"{scope} is not an available scope for {Emulator.Attributes().CoreName}"); - } + private void LogScopeNotAvailable(string scope) => Log($"{scope} is not an available scope for {Emulator.Attributes().CoreName}"); [LuaMethod("can_use_callback_params", "Returns whether EmuHawk will pass arguments to callbacks. The current version passes arguments to \"memory\" callbacks (RAM/ROM/bus R/W), so this function will return true for that input. (It returns false for any other input.) This tells you whether it's necessary to enable workarounds/hacks because a script is running in a version without parameter support.")] [LuaMethodExample("local mem_callback = event.can_use_callback_params(\"memory\") and mem_callback or mem_callback_pre_29;")] @@ -82,10 +79,7 @@ public string OnInputPoll(LuaFunction luaf, string name = null) return Guid.Empty.ToString(); } - private void LogNotImplemented() - { - Log($"Error: {Emulator.Attributes().CoreName} does not yet implement input polling callbacks"); - } + private void LogNotImplemented() => Log($"Error: {Emulator.Attributes().CoreName} does not yet implement input polling callbacks"); [LuaMethodExample("local steveonl = event.onloadstate(\r\n\tfunction()\r\n\tconsole.log( \"Fires after a state is loaded. Receives a lua function name, and registers it to the event immediately following a successful savestate event\" );\r\nend\", \"Frame name\" );")] [LuaMethod("onloadstate", "Fires after a state is loaded. Your callback can have 1 parameter, which will be the name of the loaded state.")] @@ -99,11 +93,9 @@ public string OnMemoryExecute( LuaFunction luaf, uint address, string name = null, - string scope = null) - { -// Log("Deprecated function event.onmemoryexecute() used, replace the call with event.on_bus_exec()."); - return OnBusExec(luaf, address, name: name, scope: scope); - } + string scope = null) => + // Log("Deprecated function event.onmemoryexecute() used, replace the call with event.on_bus_exec()."); + OnBusExec(luaf, address, name: name, scope: scope); [LuaMethodExample("local exec_cb_id = event.on_bus_exec(\r\n\tfunction(addr, val, flags)\r\n\t\tconsole.log( \"Fires immediately before the given address is executed by the core. {{val}} is the value to be executed (or {{0}} always, if this feature is only partially implemented).\" );\r\n\tend\r\n\t, 0x200, \"Frame name\", \"System Bus\" );")] [LuaMethod("on_bus_exec", "Fires immediately before the given address is executed by the core. Your callback can have 3 parameters {{(addr, val, flags)}}. {{val}} is the value to be executed (or {{0}} always, if this feature is only partially implemented).")] @@ -145,11 +137,9 @@ public string OnBusExec( public string OnMemoryExecuteAny( LuaFunction luaf, string name = null, - string scope = null) - { -// Log("Deprecated function event.onmemoryexecuteany(...) used, replace the call with event.on_bus_exec_any(...)."); - return OnBusExecAny(luaf, name: name, scope: scope); - } + string scope = null) => + // Log("Deprecated function event.onmemoryexecuteany(...) used, replace the call with event.on_bus_exec_any(...)."); + OnBusExecAny(luaf, name: name, scope: scope); [LuaMethodExample("local exec_cb_id = event.on_bus_exec_any(\r\n\tfunction(addr, val, flags)\r\n\t\tconsole.log( \"Fires immediately before every instruction executed (in the specified scope) by the core (CPU-intensive). {{val}} is the value to be executed (or {{0}} always, if this feature is only partially implemented).\" );\r\n\tend\r\n\t, \"Frame name\", \"System Bus\" );")] [LuaMethod("on_bus_exec_any", "Fires immediately before every instruction executed (in the specified scope) by the core (CPU-intensive). Your callback can have 3 parameters {{(addr, val, flags)}}. {{val}} is the value to be executed (or {{0}} always, if this feature is only partially implemented).")] @@ -196,11 +186,9 @@ public string OnMemoryRead( LuaFunction luaf, uint? address = null, string name = null, - string scope = null) - { -// Log("Deprecated function event.onmemoryread(...) used, replace the call with event.on_bus_read(...)."); - return OnBusRead(luaf, address, name: name, scope: scope); - } + string scope = null) => + // Log("Deprecated function event.onmemoryread(...) used, replace the call with event.on_bus_read(...)."); + OnBusRead(luaf, address, name: name, scope: scope); [LuaMethodExample("local exec_cb_id = event.on_bus_read(\r\n\tfunction(addr, val, flags)\r\n\t\tconsole.log( \"Fires immediately before the given address is read by the core. {{val}} is the value read. If no address is given, it will fire on every memory read.\" );\r\n\tend\r\n\t, 0x200, \"Frame name\" );")] [LuaMethod("on_bus_read", "Fires immediately before the given address is read by the core. Your callback can have 3 parameters {{(addr, val, flags)}}. {{val}} is the value read. If no address is given, it will fire on every memory read.")] @@ -242,11 +230,9 @@ public string OnMemoryWrite( LuaFunction luaf, uint? address = null, string name = null, - string scope = null) - { -// Log("Deprecated function event.onmemorywrite(...) used, replace the call with event.on_bus_write(...)."); - return OnBusWrite(luaf, address, name: name, scope: scope); - } + string scope = null) => + // Log("Deprecated function event.onmemorywrite(...) used, replace the call with event.on_bus_write(...)."); + OnBusWrite(luaf, address, name: name, scope: scope); [LuaMethodExample("local exec_cb_id = event.on_bus_write(\r\n\tfunction(addr, val, flags)\r\n\t\tconsole.log( \"Fires immediately before the given address is written by the core. {{val}} is the value to be written (or {{0}} always, if this feature is only partially implemented). If no address is given, it will fire on every memory write.\" );\r\n\tend\r\n\t, 0x200, \"Frame name\" );")] [LuaMethod("on_bus_write", "Fires immediately before the given address is written by the core. Your callback can have 3 parameters {{(addr, val, flags)}}. {{val}} is the value to be written (or {{0}} always, if this feature is only partially implemented). If no address is given, it will fire on every memory write.")] @@ -336,9 +322,6 @@ private string ProcessScope(string scope) return scope; } - private bool HasScope(string scope) - { - return string.IsNullOrWhiteSpace(scope) || DebuggableCore.MemoryCallbacks.AvailableScopes.Contains(scope); - } + private bool HasScope(string scope) => string.IsNullOrWhiteSpace(scope) || DebuggableCore.MemoryCallbacks.AvailableScopes.Contains(scope); } } diff --git a/src/BizHawk.Client.Common/lua/LuaHelperLibs/MainMemoryLuaLibrary.cs b/src/BizHawk.Client.Common/lua/LuaHelperLibs/MainMemoryLuaLibrary.cs index 5c012bd8bf2..7ecfc8feb81 100644 --- a/src/BizHawk.Client.Common/lua/LuaHelperLibs/MainMemoryLuaLibrary.cs +++ b/src/BizHawk.Client.Common/lua/LuaHelperLibs/MainMemoryLuaLibrary.cs @@ -38,10 +38,7 @@ public string GetName() [LuaMethodExample("local uimaiget = mainmemory.getcurrentmemorydomainsize( );")] [LuaMethod("getcurrentmemorydomainsize", "Returns the number of bytes of the domain defined as main memory")] - public uint GetSize() - { - return (uint)Domain.Size; - } + public uint GetSize() => (uint)Domain.Size; [LuaMethodExample("local uimairea = mainmemory.readbyte( 0x100 );")] [LuaMethod("readbyte", "gets the value from the given address as an unsigned byte")] @@ -70,8 +67,7 @@ public LuaTable ReadBytesAsDict(long addr, int length) [LuaDeprecatedMethod] [LuaMethod("writebyterange", "Writes the given values to the given addresses as unsigned bytes")] - public void WriteByteRange(LuaTable memoryblock) - { + public void WriteByteRange(LuaTable memoryblock) => #if true WriteBytesAsDict(memoryblock); #else @@ -95,7 +91,7 @@ public void WriteByteRange(LuaTable memoryblock) Log($"Error: the domain {d.Name} is not writable"); } #endif - } + [LuaMethodExample("mainmemory.write_bytes_as_array(0x100, { 0xAB, 0x12, 0xCD, 0x34 });")] [LuaMethod("write_bytes_as_array", "Writes sequential bytes starting at addr.")] diff --git a/src/BizHawk.Client.Common/lua/LuaHelperLibs/SNESLuaLibrary.cs b/src/BizHawk.Client.Common/lua/LuaHelperLibs/SNESLuaLibrary.cs index 139d96f7c9b..1d2e92cea14 100644 --- a/src/BizHawk.Client.Common/lua/LuaHelperLibs/SNESLuaLibrary.cs +++ b/src/BizHawk.Client.Common/lua/LuaHelperLibs/SNESLuaLibrary.cs @@ -23,59 +23,35 @@ private LibsnesCore.SnesSettings Settings [LuaMethodExample("if ( snes.getlayer_bg_1( ) ) then\r\n\tconsole.log( \"Returns whether the bg 1 layer is displayed\" );\r\nend;")] [LuaMethod("getlayer_bg_1", "Returns whether the bg 1 layer is displayed")] - public bool GetLayerBg1() - { - return Settings.ShowBG1_1; - } + public bool GetLayerBg1() => Settings.ShowBG1_1; [LuaMethodExample("if ( snes.getlayer_bg_2( ) ) then\r\n\tconsole.log( \"Returns whether the bg 2 layer is displayed\" );\r\nend;")] [LuaMethod("getlayer_bg_2", "Returns whether the bg 2 layer is displayed")] - public bool GetLayerBg2() - { - return Settings.ShowBG2_1; - } + public bool GetLayerBg2() => Settings.ShowBG2_1; [LuaMethodExample("if ( snes.getlayer_bg_3( ) ) then\r\n\tconsole.log( \"Returns whether the bg 3 layer is displayed\" );\r\nend;")] [LuaMethod("getlayer_bg_3", "Returns whether the bg 3 layer is displayed")] - public bool GetLayerBg3() - { - return Settings.ShowBG3_1; - } + public bool GetLayerBg3() => Settings.ShowBG3_1; [LuaMethodExample("if ( snes.getlayer_bg_4( ) ) then\r\n\tconsole.log( \"Returns whether the bg 4 layer is displayed\" );\r\nend;")] [LuaMethod("getlayer_bg_4", "Returns whether the bg 4 layer is displayed")] - public bool GetLayerBg4() - { - return Settings.ShowBG4_1; - } + public bool GetLayerBg4() => Settings.ShowBG4_1; [LuaMethodExample("if ( snes.getlayer_obj_1( ) ) then\r\n\tconsole.log( \"Returns whether the obj 1 layer is displayed\" );\r\nend;")] [LuaMethod("getlayer_obj_1", "Returns whether the obj 1 layer is displayed")] - public bool GetLayerObj1() - { - return Settings.ShowOBJ_0; - } + public bool GetLayerObj1() => Settings.ShowOBJ_0; [LuaMethodExample("if ( snes.getlayer_obj_2( ) ) then\r\n\tconsole.log( \"Returns whether the obj 2 layer is displayed\" );\r\nend;")] [LuaMethod("getlayer_obj_2", "Returns whether the obj 2 layer is displayed")] - public bool GetLayerObj2() - { - return Settings.ShowOBJ_1; - } + public bool GetLayerObj2() => Settings.ShowOBJ_1; [LuaMethodExample("if ( snes.getlayer_obj_3( ) ) then\r\n\tconsole.log( \"Returns whether the obj 3 layer is displayed\" );\r\nend;")] [LuaMethod("getlayer_obj_3", "Returns whether the obj 3 layer is displayed")] - public bool GetLayerObj3() - { - return Settings.ShowOBJ_2; - } + public bool GetLayerObj3() => Settings.ShowOBJ_2; [LuaMethodExample("if ( snes.getlayer_obj_4( ) ) then\r\n\tconsole.log( \"Returns whether the obj 4 layer is displayed\" );\r\nend;")] [LuaMethod("getlayer_obj_4", "Returns whether the obj 4 layer is displayed")] - public bool GetLayerObj4() - { - return Settings.ShowOBJ_3; - } + public bool GetLayerObj4() => Settings.ShowOBJ_3; [LuaMethodExample("snes.setlayer_bg_1( true );")] [LuaMethod("setlayer_bg_1", "Sets whether the bg 1 layer is displayed")] diff --git a/src/BizHawk.Client.Common/lua/LuaHelperLibs/StringLuaLibrary.cs b/src/BizHawk.Client.Common/lua/LuaHelperLibs/StringLuaLibrary.cs index c70b37a1940..93c3ba29544 100644 --- a/src/BizHawk.Client.Common/lua/LuaHelperLibs/StringLuaLibrary.cs +++ b/src/BizHawk.Client.Common/lua/LuaHelperLibs/StringLuaLibrary.cs @@ -19,7 +19,7 @@ public StringLuaLibrary(ILuaLibraries luaLibsImpl, ApiContainer apiContainer, Ac [LuaMethod("hex", "Converts the number to a string representation of the hexadecimal value of the given number")] public static string Hex(long num) { - var hex = $"{num:X}"; + string hex = $"{num:X}"; if (hex.Length == 1) { hex = $"0{hex}"; @@ -32,7 +32,7 @@ public static string Hex(long num) [LuaMethod("binary", "Converts the number to a string representation of the binary value of the given number")] public static string Binary(long num) { - var binary = Convert.ToString(num, 2); + string binary = Convert.ToString(num, 2); binary = binary.TrimStart('0'); return binary; } @@ -41,7 +41,7 @@ public static string Binary(long num) [LuaMethod("octal", "Converts the number to a string representation of the octal value of the given number")] public static string Octal(long num) { - var octal = Convert.ToString(num, 8); + string octal = Convert.ToString(num, 8); if (octal.Length == 1) { octal = $"0{octal}"; diff --git a/src/BizHawk.Client.Common/lua/LuaSandbox.cs b/src/BizHawk.Client.Common/lua/LuaSandbox.cs index e1f5a203d0a..0c6a62baaeb 100644 --- a/src/BizHawk.Client.Common/lua/LuaSandbox.cs +++ b/src/BizHawk.Client.Common/lua/LuaSandbox.cs @@ -12,10 +12,7 @@ public class LuaSandbox public static Action DefaultLogger { get; set; } - public void SetSandboxCurrentDirectory(string dir) - { - _currentDirectory = dir; - } + public void SetSandboxCurrentDirectory(string dir) => _currentDirectory = dir; private string _currentDirectory; @@ -58,7 +55,7 @@ private void Sandbox(Action callback, Action exceptionCallback) } catch (NLua.Exceptions.LuaException ex) { - var exStr = ex.ToString() + '\n'; + string exStr = ex.ToString() + '\n'; if (ex.InnerException is not null) { exStr += ex.InnerException.ToString() + '\n'; @@ -79,7 +76,7 @@ private void Sandbox(Action callback, Action exceptionCallback) public static LuaSandbox CreateSandbox(LuaThread thread, string initialDirectory) { - var sandbox = new LuaSandbox(); + LuaSandbox sandbox = new(); SandboxForThread.Add(thread, sandbox); sandbox.SetSandboxCurrentDirectory(initialDirectory); return sandbox; @@ -108,9 +105,6 @@ public static LuaSandbox GetSandbox(LuaThread thread) } } - public static void Sandbox(LuaThread thread, Action callback, Action exceptionCallback = null) - { - GetSandbox(thread).Sandbox(callback, exceptionCallback); - } + public static void Sandbox(LuaThread thread, Action callback, Action exceptionCallback = null) => GetSandbox(thread).Sandbox(callback, exceptionCallback); } } diff --git a/src/BizHawk.Client.Common/lua/NLuaTableHelper.cs b/src/BizHawk.Client.Common/lua/NLuaTableHelper.cs index 0ef2ddab795..22a6e9603d1 100644 --- a/src/BizHawk.Client.Common/lua/NLuaTableHelper.cs +++ b/src/BizHawk.Client.Common/lua/NLuaTableHelper.cs @@ -45,10 +45,10 @@ public LuaTable ListToTable(IReadOnlyList list, int indexFrom = 1) public LuaTable MemoryBlockToTable(IReadOnlyList bytes, long startAddr) { - var length = bytes.Count; + int length = bytes.Count; var table = CreateTable(); - var iArray = 0; - var iDict = startAddr; + int iArray = 0; + long iDict = startAddr; while (iArray < length) table[iDict++] = bytes[iArray++]; return table; } @@ -59,7 +59,7 @@ public LuaTable ObjectToTable(object obj) foreach (var method in obj.GetType().GetMethods()) { if (!method.IsPublic) continue; - var foundAttrs = method.GetCustomAttributes(typeof(LuaMethodAttribute), false); + object[] foundAttrs = method.GetCustomAttributes(typeof(LuaMethodAttribute), false); table[method.Name] = _lua.RegisterFunction( foundAttrs.Length == 0 ? string.Empty : ((LuaMethodAttribute) foundAttrs[0]).Name, // empty string will default to the actual method name obj, @@ -90,11 +90,11 @@ public LuaTable ObjectToTable(object obj) case string s: if (s[0] is '#' && (s.Length is 7 or 9)) { - var i1 = uint.Parse(s.Substring(1), NumberStyles.HexNumber); + uint i1 = uint.Parse(s.Substring(1), NumberStyles.HexNumber); if (s.Length is 7) i1 |= 0xFF000000U; return ParseColor(unchecked((int) i1), safe, logCallback); } - var fromName = Color.FromName(s); + Color fromName = Color.FromName(s); if (fromName.IsNamedColor) return fromName; if (safe) logCallback($"ParseColor: not a known color name (\"{s}\")"); return null; diff --git a/src/BizHawk.Client.Common/movie/BasicMovieInfo.cs b/src/BizHawk.Client.Common/movie/BasicMovieInfo.cs index 82361ffc242..e68ada702f6 100644 --- a/src/BizHawk.Client.Common/movie/BasicMovieInfo.cs +++ b/src/BizHawk.Client.Common/movie/BasicMovieInfo.cs @@ -47,15 +47,15 @@ public TimeSpan TimeLength { double numSeconds; - if (Header.TryGetValue(HeaderKeys.CycleCount, out var numCyclesStr) && Header.TryGetValue(HeaderKeys.ClockRate, out var clockRateStr)) + if (Header.TryGetValue(HeaderKeys.CycleCount, out string numCyclesStr) && Header.TryGetValue(HeaderKeys.ClockRate, out string clockRateStr)) { - var numCycles = Convert.ToUInt64(numCyclesStr); - var clockRate = Convert.ToDouble(clockRateStr, CultureInfo.InvariantCulture); + ulong numCycles = Convert.ToUInt64(numCyclesStr); + double clockRate = Convert.ToDouble(clockRateStr, CultureInfo.InvariantCulture); numSeconds = numCycles / clockRate; } else { - var numFrames = (ulong)FrameCount; + ulong numFrames = (ulong)FrameCount; numSeconds = numFrames / FrameRate; } @@ -67,7 +67,7 @@ public double FrameRate { get { - if (SystemID == VSystemID.Raw.Arcade && Header.TryGetValue(HeaderKeys.VsyncAttoseconds, out var vsyncAttoStr)) + if (SystemID == VSystemID.Raw.Arcade && Header.TryGetValue(HeaderKeys.VsyncAttoseconds, out string vsyncAttoStr)) { const decimal attosInSec = 1000000000000000000; return (double)(attosInSec / Convert.ToUInt64(vsyncAttoStr)); @@ -96,7 +96,7 @@ public virtual string SystemID public virtual ulong Rerecords { - get => Header.TryGetValue(HeaderKeys.Rerecords, out var rerecords) ? ulong.Parse(rerecords) : 0; + get => Header.TryGetValue(HeaderKeys.Rerecords, out string rerecords) ? ulong.Parse(rerecords) : 0; set => Header[HeaderKeys.Rerecords] = value.ToString(); } @@ -146,7 +146,7 @@ public virtual string FirmwareHash public bool Load() { - var file = new FileInfo(Filename); + FileInfo file = new(Filename); if (!file.Exists) { return false; @@ -154,7 +154,7 @@ public bool Load() try { - using var bl = ZipStateLoader.LoadAndDetect(Filename, true); + using ZipStateLoader bl = ZipStateLoader.LoadAndDetect(Filename, true); if (bl is null) return false; ClearBeforeLoad(); LoadFields(bl); @@ -187,7 +187,7 @@ protected virtual void LoadFields(ZipStateLoader bl) { if (!string.IsNullOrWhiteSpace(line)) { - var pair = line.Split(new[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries); + string[] pair = line.Split(new[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries); if (pair.Length > 1) { diff --git a/src/BizHawk.Client.Common/movie/MovieConversionExtensions.cs b/src/BizHawk.Client.Common/movie/MovieConversionExtensions.cs index f42c10f0f7e..fd53d0c1dea 100644 --- a/src/BizHawk.Client.Common/movie/MovieConversionExtensions.cs +++ b/src/BizHawk.Client.Common/movie/MovieConversionExtensions.cs @@ -23,7 +23,7 @@ public static class MovieConversionExtensions public static ITasMovie ToTasMovie(this IMovie old) { string newFilename = ConvertFileNameToTasMovie(old.Filename); - var tas = (ITasMovie)old.Session.Get(newFilename); + ITasMovie tas = (ITasMovie)old.Session.Get(newFilename); tas.CopyLog(old.GetLogEntries()); tas.LogKey = old.LogKey; @@ -38,7 +38,7 @@ public static ITasMovie ToTasMovie(this IMovie old) tas.SyncSettingsJson = old.SyncSettingsJson; tas.Comments.Clear(); - foreach (var comment in old.Comments) + foreach (string comment in old.Comments) { tas.Comments.Add(comment); } @@ -72,7 +72,7 @@ public static IMovie ToBk2(this IMovie old) bk2.SyncSettingsJson = old.SyncSettingsJson; bk2.Comments.Clear(); - foreach (var comment in old.Comments) + foreach (string comment in old.Comments) { bk2.Comments.Add(comment); } @@ -94,7 +94,7 @@ public static ITasMovie ConvertToSavestateAnchoredMovie(this ITasMovie old, int { string newFilename = ConvertFileNameToTasMovie(old.Filename); - var tas = (ITasMovie)old.Session.Get(newFilename); + ITasMovie tas = (ITasMovie)old.Session.Get(newFilename); tas.BinarySavestate = savestate; tas.LagLog.Clear(); @@ -126,12 +126,12 @@ public static ITasMovie ConvertToSavestateAnchoredMovie(this ITasMovie old, int } tas.Subtitles.Clear(); - foreach (Subtitle sub in old.Subtitles) + foreach (var sub in old.Subtitles) { tas.Subtitles.Add(sub); } - foreach (TasMovieMarker marker in old.Markers) + foreach (var marker in old.Markers) { if (marker.Frame > frame) { @@ -149,7 +149,7 @@ public static ITasMovie ConvertToSaveRamAnchoredMovie(this ITasMovie old, byte[] { string newFilename = ConvertFileNameToTasMovie(old.Filename); - var tas = (ITasMovie)old.Session.Get(newFilename); + ITasMovie tas = (ITasMovie)old.Session.Get(newFilename); tas.SaveRam = saveRam; tas.TasStateManager.Clear(); tas.LagLog.Clear(); @@ -172,7 +172,7 @@ public static ITasMovie ConvertToSaveRamAnchoredMovie(this ITasMovie old, byte[] } tas.Subtitles.Clear(); - foreach (Subtitle sub in old.Subtitles) + foreach (var sub in old.Subtitles) { tas.Subtitles.Add(sub); } @@ -227,7 +227,7 @@ public static void PopulateWithDefaultHeaderValues( { foreach (var firmware in firmwareManager.RecentlyServed) { - var key = firmware.ID.MovieHeaderKey; + string key = firmware.ID.MovieHeaderKey; if (!movie.HeaderEntries.ContainsKey(key)) { movie.HeaderEntries.Add(key, firmware.Hash); @@ -309,7 +309,7 @@ internal static string ConvertFileNameToTasMovie(string oldFileName) if (oldFileName is null) return null; var (dir, fileNoExt, _) = oldFileName.SplitPathToDirFileAndExt(); if (dir is null) return string.Empty; - var newFileName = Path.Combine(dir, $"{fileNoExt}.{TasMovie.Extension}"); + string newFileName = Path.Combine(dir, $"{fileNoExt}.{TasMovie.Extension}"); int fileSuffix = 0; while (File.Exists(newFileName)) { diff --git a/src/BizHawk.Client.Common/movie/MovieService.cs b/src/BizHawk.Client.Common/movie/MovieService.cs index a7f43490f6c..ebdb6aa8012 100644 --- a/src/BizHawk.Client.Common/movie/MovieService.cs +++ b/src/BizHawk.Client.Common/movie/MovieService.cs @@ -16,14 +16,11 @@ public static class MovieService /// public static IEnumerable MovieExtensions => new[] { Bk2Movie.Extension, TasMovie.Extension }; - public static bool IsValidMovieExtension(string ext) - { - return MovieExtensions.Contains(ext.Replace(".", ""), StringComparer.OrdinalIgnoreCase); - } + public static bool IsValidMovieExtension(string ext) => MovieExtensions.Contains(ext.Replace(".", ""), StringComparer.OrdinalIgnoreCase); public static bool IsCurrentTasVersion(string movieVersion) { - var actual = ParseTasMovieVersion(movieVersion); + double actual = ParseTasMovieVersion(movieVersion); return actual.HawkFloatEquality(TasMovie.CurrentVersion); } @@ -34,7 +31,7 @@ internal static double ParseTasMovieVersion(string movieVersion) return 1.0F; } - var split = movieVersion + string[] split = movieVersion .ToLowerInvariant() .Split(new[] {"tasproj"}, StringSplitOptions.RemoveEmptyEntries); @@ -43,17 +40,17 @@ internal static double ParseTasMovieVersion(string movieVersion) return 1.0F; } - var versionStr = split[1] + string versionStr = split[1] .Trim() .Replace("v", ""); - if (double.TryParse(versionStr, NumberStyles.Float, CultureInfo.InvariantCulture, out var parsedWithPeriod)) + if (double.TryParse(versionStr, NumberStyles.Float, CultureInfo.InvariantCulture, out double parsedWithPeriod)) { return parsedWithPeriod; } // Accept .tasproj files written from <= 2.5 where the host culture settings used ',' - if (double.TryParse(versionStr.Replace(',', '.'), NumberStyles.Float, CultureInfo.InvariantCulture, out var parsedWithComma)) + if (double.TryParse(versionStr.Replace(',', '.'), NumberStyles.Float, CultureInfo.InvariantCulture, out double parsedWithComma)) { return parsedWithComma; } diff --git a/src/BizHawk.Client.Common/movie/MovieSession.cs b/src/BizHawk.Client.Common/movie/MovieSession.cs index 21887e484b3..57f0e81ae00 100644 --- a/src/BizHawk.Client.Common/movie/MovieSession.cs +++ b/src/BizHawk.Client.Common/movie/MovieSession.cs @@ -53,16 +53,11 @@ public MovieSession( public IMovieController MovieController { get; private set; } = new Bk2Controller("", NullController.Instance.Definition); - public IMovieController GenerateMovieController(ControllerDefinition definition = null) - { + public IMovieController GenerateMovieController(ControllerDefinition definition = null) => // TODO: expose Movie.LogKey and pass in here - return new Bk2Controller("", definition ?? MovieController.Definition); - } + new Bk2Controller("", definition ?? MovieController.Definition); - public void SetMovieController(ControllerDefinition definition) - { - MovieController = GenerateMovieController(definition); - } + public void SetMovieController(ControllerDefinition definition) => MovieController = GenerateMovieController(definition); public void HandleFrameBefore() { @@ -128,7 +123,7 @@ public bool CheckSavestateTimeline(TextReader reader) { if (Movie.IsActive() && ReadOnly) { - var result = Movie.CheckTimeLines(reader, out var errorMsg); + bool result = Movie.CheckTimeLines(reader, out string errorMsg); if (!result) { Output(errorMsg); @@ -174,7 +169,7 @@ public bool HandleLoadState(TextReader reader) Movie.SwitchToRecord(); } - var result = Movie.ExtractInputLog(reader, out var errorMsg); + bool result = Movie.ExtractInputLog(reader, out string errorMsg); if (!result) { Output(errorMsg); @@ -210,14 +205,14 @@ public void QueueNewMovie(IMovie movie, bool record, string systemId, IDictionar { if (string.IsNullOrWhiteSpace(movie.Core)) { - PopupMessage(preferredCores.TryGetValue(systemId, out var coreName) + PopupMessage(preferredCores.TryGetValue(systemId, out string coreName) ? $"No core specified in the movie file, using the preferred core {coreName} instead." : "No core specified in the movie file, using the default core instead."); } else { - var keys = preferredCores.Keys.ToList(); - foreach (var k in keys) + List keys = preferredCores.Keys.ToList(); + foreach (string k in keys) { preferredCores[k] = movie.Core; } @@ -267,7 +262,7 @@ public void StopMovie(bool saveChanges = true) { if (Movie.IsActive()) { - var message = "Movie "; + string message = "Movie "; if (Movie.IsRecording()) { message += "recording "; @@ -279,7 +274,7 @@ public void StopMovie(bool saveChanges = true) message += "stopped."; - var result = Movie.Stop(saveChanges); + bool result = Movie.Stop(saveChanges); if (result) { Output($"{Path.GetFileName(Movie.Filename)} written to disk."); @@ -323,10 +318,7 @@ public IMovie Get(string path) private void Output(string message) => _dialogParent.DialogController.AddOnScreenMessage(message); - private void LatchInputToUser() - { - MovieOut.Source = MovieIn; - } + private void LatchInputToUser() => MovieOut.Source = MovieIn; // Latch input from the input log, if available private void LatchInputToLog() @@ -350,11 +342,11 @@ private void HandlePlaybackEnd() bool movieHasValue = Movie.HeaderEntries.TryGetValue(HeaderKeys.CycleCount, out string movieValueStr); long movieValue = movieHasValue ? Convert.ToInt64(movieValueStr) : 0; - var valuesMatch = movieValue == coreValue; + bool valuesMatch = movieValue == coreValue; if (!movieHasValue || !valuesMatch) { - var previousState = !movieHasValue + string previousState = !movieHasValue ? $"The movie is currently missing a cycle count." : $"The cycle count in the movie ({movieValue}) doesn't match the current value."; // TODO: Ideally, this would be a Yes/No MessageBox that saves when "Yes" is pressed. diff --git a/src/BizHawk.Client.Common/movie/PlatformFrameRates.cs b/src/BizHawk.Client.Common/movie/PlatformFrameRates.cs index 773f7d87851..f1b278af60b 100644 --- a/src/BizHawk.Client.Common/movie/PlatformFrameRates.cs +++ b/src/BizHawk.Client.Common/movie/PlatformFrameRates.cs @@ -13,7 +13,7 @@ public static class PlatformFrameRates private static readonly double NTSCCarrier = 4500000 * 227.5 / 286; // 3.579545454... MHz private static readonly double PALNCarrier = (15625 * 229.25) + 25; // 3.58205625 MHz - private static readonly Dictionary Rates = new Dictionary + private static readonly Dictionary Rates = new() { ["NES"] = 60.098813897440515532, // discussion here: http://forums.nesdev.com/viewtopic.php?t=492 ; a rational expression would be (19687500 / 11) / ((341*262-0.529780.5)/3) -> (118125000 / 1965513) -> 60.098813897440515529533511098629 (so our chosen number is very close) ["NES_PAL"] = 50.006977968268290849, @@ -81,6 +81,6 @@ public static class PlatformFrameRates }; public static double GetFrameRate(string systemId, bool pal) - => Rates.TryGetValue(systemId + (pal ? "_PAL" : ""), out var d) ? d : 60.0; + => Rates.TryGetValue(systemId + (pal ? "_PAL" : ""), out double d) ? d : 60.0; } } diff --git a/src/BizHawk.Client.Common/movie/Subtitle.cs b/src/BizHawk.Client.Common/movie/Subtitle.cs index b8e7c2afe06..78bc98a52cb 100644 --- a/src/BizHawk.Client.Common/movie/Subtitle.cs +++ b/src/BizHawk.Client.Common/movie/Subtitle.cs @@ -33,7 +33,7 @@ public Subtitle(Subtitle s) public override string ToString() { - var sb = new StringBuilder("subtitle "); + StringBuilder sb = new("subtitle "); sb .Append(Frame).Append(' ') .Append(X).Append(' ') @@ -47,7 +47,7 @@ public override string ToString() public string ToSubRip(int index, double fps, bool addColorTag) { - var sb = new StringBuilder(); + StringBuilder sb = new(); sb.Append(index); sb.Append("\r\n"); @@ -59,9 +59,9 @@ public string ToSubRip(int index, double fps, bool addColorTag) int startTime = (int)(start * 1000 / fps); int endTime = (int)(end * 1000 / fps); - var startString = $"{startTime / 3600000:d2}:{(startTime / 60000) % 60:d2}:{(startTime / 1000) % 60:d2},{startTime % 1000:d3}"; + string startString = $"{startTime / 3600000:d2}:{(startTime / 60000) % 60:d2}:{(startTime / 1000) % 60:d2},{startTime % 1000:d3}"; - var endString = $"{endTime / 3600000:d2}:{(endTime / 60000) % 60:d2}:{(endTime / 1000) % 60:d2},{endTime % 1000:d3}"; + string endString = $"{endTime / 3600000:d2}:{(endTime / 60000) % 60:d2}:{(endTime / 1000) % 60:d2},{endTime % 1000:d3}"; sb.Append(startString); sb.Append(" --> "); diff --git a/src/BizHawk.Client.Common/movie/SubtitleList.cs b/src/BizHawk.Client.Common/movie/SubtitleList.cs index d2a19bd63e6..7d779955e95 100644 --- a/src/BizHawk.Client.Common/movie/SubtitleList.cs +++ b/src/BizHawk.Client.Common/movie/SubtitleList.cs @@ -22,7 +22,7 @@ public SubtitleList() public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new(); Sort(); ForEach(subtitle => sb.AppendLine(subtitle.ToString())); return sb.ToString(); @@ -34,11 +34,11 @@ public bool AddFromString(string subtitleStr) { try { - var subParts = subtitleStr.Split(' '); + string[] subParts = subtitleStr.Split(' '); // Unfortunately I made the file format space delaminated so this hack is necessary to get the message - var message = ""; - for (var i = 6; i < subParts.Length; i++) + string message = ""; + for (int i = 6; i < subParts.Length; i++) { message += subParts[i] + ' '; } @@ -76,8 +76,8 @@ public bool AddFromString(string subtitleStr) public string ToSubRip(double fps) { int index = 1; - var sb = new StringBuilder(); - var subs = new List(); + StringBuilder sb = new(); + List subs = new(); foreach (var subtitle in this) { subs.Add(new Subtitle(subtitle)); diff --git a/src/BizHawk.Client.Common/movie/bk2/Bk2Controller.cs b/src/BizHawk.Client.Common/movie/bk2/Bk2Controller.cs index e2484906088..65612a0e891 100755 --- a/src/BizHawk.Client.Common/movie/bk2/Bk2Controller.cs +++ b/src/BizHawk.Client.Common/movie/bk2/Bk2Controller.cs @@ -31,7 +31,7 @@ public Bk2Controller(string key, ControllerDefinition definition) : this(definit { if (!string.IsNullOrEmpty(key)) { - var groups = key.Split(new[] { "#" }, StringSplitOptions.RemoveEmptyEntries); + string[] groups = key.Split(new[] { "#" }, StringSplitOptions.RemoveEmptyEntries); _type.ControlsFromLog = groups .Select(group => group.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries).ToList()) @@ -42,7 +42,7 @@ public Bk2Controller(string key, ControllerDefinition definition) : this(definit public Bk2Controller(ControllerDefinition definition) { _type = new Bk2ControllerDefinition(definition); - foreach ((string axisName, AxisSpec range) in definition.Axes) + foreach ((string axisName, var range) in definition.Axes) { _myAxisControls[axisName] = range.Neutral; } @@ -65,7 +65,7 @@ public void SetFrom(IController source) _myBoolButtons[button] = source.IsPressed(button); } - foreach (var name in Definition.Axes.Keys) + foreach (string name in Definition.Axes.Keys) { _myAxisControls[name] = source.AxisValue(name); } @@ -73,7 +73,7 @@ public void SetFrom(IController source) public void SetFromSticky(IStickyAdapter controller) { - foreach (var button in Definition.BoolButtons) + foreach (string button in Definition.BoolButtons) { _myBoolButtons[button] = controller.IsSticky(button); } @@ -86,8 +86,8 @@ public void SetFromMnemonic(string mnemonic) { if (!string.IsNullOrWhiteSpace(mnemonic)) { - var trimmed = mnemonic.Replace("|", ""); - var iterator = 0; + string trimmed = mnemonic.Replace("|", ""); + int iterator = 0; foreach (var key in ControlsOrdered) { @@ -98,9 +98,9 @@ public void SetFromMnemonic(string mnemonic) } else if (key.IsAxis) { - var commaIndex = trimmed.Substring(iterator).IndexOf(','); - var temp = trimmed.Substring(iterator, commaIndex); - var val = int.Parse(temp.Trim()); + int commaIndex = trimmed.Substring(iterator).IndexOf(','); + string temp = trimmed.Substring(iterator, commaIndex); + int val = int.Parse(temp.Trim()); _myAxisControls[key.Name] = val; iterator += commaIndex + 1; @@ -109,15 +109,9 @@ public void SetFromMnemonic(string mnemonic) } } - public void SetBool(string buttonName, bool value) - { - _myBoolButtons[buttonName] = value; - } + public void SetBool(string buttonName, bool value) => _myBoolButtons[buttonName] = value; - public void SetAxis(string buttonName, int value) - { - _myAxisControls[buttonName] = value; - } + public void SetAxis(string buttonName, int value) => _myAxisControls[buttonName] = value; private class ControlMap { diff --git a/src/BizHawk.Client.Common/movie/bk2/Bk2Header.cs b/src/BizHawk.Client.Common/movie/bk2/Bk2Header.cs index 4a6bd55d596..7eb464d8346 100644 --- a/src/BizHawk.Client.Common/movie/bk2/Bk2Header.cs +++ b/src/BizHawk.Client.Common/movie/bk2/Bk2Header.cs @@ -9,13 +9,13 @@ public class Bk2Header : Dictionary { public new string this[string key] { - get => TryGetValue(key, out var s) ? s : string.Empty; + get => TryGetValue(key, out string s) ? s : string.Empty; set => base[key] = value; } public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new(); foreach (var (k, v) in this) sb.Append(k).Append(' ').Append(v).AppendLine(); return sb.ToString(); } diff --git a/src/BizHawk.Client.Common/movie/bk2/Bk2LogEntryGenerator.cs b/src/BizHawk.Client.Common/movie/bk2/Bk2LogEntryGenerator.cs index 7b5d10ea3fe..8d8985e3a8d 100644 --- a/src/BizHawk.Client.Common/movie/bk2/Bk2LogEntryGenerator.cs +++ b/src/BizHawk.Client.Common/movie/bk2/Bk2LogEntryGenerator.cs @@ -22,7 +22,7 @@ public Bk2LogEntryGenerator(string systemId, IController source) _controlsOrdered = _source.Definition.ControlsOrdered.Where(static c => c.Count is not 0).ToList(); foreach (var group in _controlsOrdered) { - foreach (var button in group) + foreach (string button in group) { _mnemonics.Add(button, Bk2MnemonicLookup.Lookup(button, _systemId)); } @@ -47,13 +47,13 @@ public Bk2LogEntryGenerator(string systemId, IController source) /// public string GenerateLogKey() { - var sb = new StringBuilder(); + StringBuilder sb = new(); sb.Append("LogKey:"); foreach (var group in _source.Definition.ControlsOrdered.Where(static c => c.Count is not 0)) { sb.Append('#'); - foreach (var button in group) + foreach (string button in group) { sb.Append(button).Append('|'); } @@ -67,8 +67,8 @@ public string GenerateLogKey() /// public IDictionary Map() { - var dict = new Dictionary(); - foreach (var button in _source.Definition.OrderedControlsFlat) + Dictionary dict = new(); + foreach (string button in _source.Definition.OrderedControlsFlat) { if (_source.Definition.BoolButtons.Contains(button)) { @@ -85,17 +85,17 @@ public IDictionary Map() private string CreateLogEntry(bool createEmpty = false) { - var sb = new StringBuilder(); + StringBuilder sb = new(); sb.Append('|'); foreach (var group in _controlsOrdered) { - foreach (var button in group) + foreach (string button in group) { if (_source.Definition.Axes.TryGetValue(button, out var range)) { - var val = createEmpty ? range.Neutral : _source.AxisValue(button); + int val = createEmpty ? range.Neutral : _source.AxisValue(button); sb.Append(val.ToString().PadLeft(5, ' ')).Append(','); } else diff --git a/src/BizHawk.Client.Common/movie/bk2/Bk2MnemonicLookup.cs b/src/BizHawk.Client.Common/movie/bk2/Bk2MnemonicLookup.cs index ba03a26230b..2872b8de63d 100644 --- a/src/BizHawk.Client.Common/movie/bk2/Bk2MnemonicLookup.cs +++ b/src/BizHawk.Client.Common/movie/bk2/Bk2MnemonicLookup.cs @@ -11,7 +11,7 @@ internal static class Bk2MnemonicLookup { public static char Lookup(string button, string systemId) { - var key = button.Replace("Key ", ""); + string key = button.Replace("Key ", ""); if (key.StartsWith('P')) { if (key.Length > 2 && key[1] == '1' && key[2] >= '0' && key[2] <= '9') // Hack to support 10-20 controllers, TODO: regex this thing instead @@ -25,12 +25,12 @@ public static char Lookup(string button, string systemId) } key = key.RemovePrefix(LibretroHost.LibretroControllerDef.PFX_RETROPAD); - if (SystemOverrides.TryGetValue(systemId, out var overridesForSys) && overridesForSys.TryGetValue(key, out var c)) + if (SystemOverrides.TryGetValue(systemId, out var overridesForSys) && overridesForSys.TryGetValue(key, out char c)) { return c; } - if (BaseMnemonicLookupTable.TryGetValue(key, out var c1)) + if (BaseMnemonicLookupTable.TryGetValue(key, out char c1)) { return c1; } @@ -45,19 +45,19 @@ public static char Lookup(string button, string systemId) public static string LookupAxis(string button, string systemId) { - var key = button + string key = button .Replace("P1 ", "") .Replace("P2 ", "") .Replace("P3 ", "") .Replace("P4 ", "") .Replace("Key ", ""); - if (AxisSystemOverrides.TryGetValue(systemId, out var overridesForSystem) && overridesForSystem.TryGetValue(key, out var s)) + if (AxisSystemOverrides.TryGetValue(systemId, out var overridesForSystem) && overridesForSystem.TryGetValue(key, out string s)) { return s; } - if (BaseAxisLookupTable.TryGetValue(key, out var s1)) + if (BaseAxisLookupTable.TryGetValue(key, out string s1)) { return s1; } @@ -65,7 +65,7 @@ public static string LookupAxis(string button, string systemId) return button; } - private static readonly Dictionary BaseMnemonicLookupTable = new Dictionary + private static readonly Dictionary BaseMnemonicLookupTable = new() { ["Power"] = 'P', ["Reset"] = 'r', @@ -177,7 +177,7 @@ public static string LookupAxis(string button, string systemId) ["F10"] = '0' }; - private static readonly Dictionary> SystemOverrides = new Dictionary> + private static readonly Dictionary> SystemOverrides = new() { [VSystemID.Raw.NES] = new() { @@ -687,7 +687,7 @@ public static string LookupAxis(string button, string systemId) }, }; - private static readonly Dictionary BaseAxisLookupTable = new Dictionary + private static readonly Dictionary BaseAxisLookupTable = new() { ["Zapper X"] = "zapX", ["Zapper Y"] = "zapY", @@ -707,7 +707,7 @@ public static string LookupAxis(string button, string systemId) ["Disk Index"] = "Disk", }; - private static readonly Dictionary> AxisSystemOverrides = new Dictionary> + private static readonly Dictionary> AxisSystemOverrides = new() { [VSystemID.Raw.A78] = new() { diff --git a/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.HeaderApi.cs b/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.HeaderApi.cs index afb9e7dda0c..bcd2152002a 100644 --- a/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.HeaderApi.cs +++ b/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.HeaderApi.cs @@ -34,7 +34,7 @@ public override ulong Rerecords public virtual bool StartsFromSavestate { // ReSharper disable SimplifyConditionalTernaryExpression - get => Header.TryGetValue(HeaderKeys.StartsFromSavestate, out var s) ? bool.Parse(s) : false; + get => Header.TryGetValue(HeaderKeys.StartsFromSavestate, out string s) && bool.Parse(s); // ReSharper restore SimplifyConditionalTernaryExpression set { @@ -52,7 +52,7 @@ public virtual bool StartsFromSavestate public bool StartsFromSaveRam { // ReSharper disable SimplifyConditionalTernaryExpression - get => Header.TryGetValue(HeaderKeys.StartsFromSaveram, out var s) ? bool.Parse(s) : false; + get => Header.TryGetValue(HeaderKeys.StartsFromSaveram, out string s) && bool.Parse(s); // ReSharper restore SimplifyConditionalTernaryExpression set { @@ -180,9 +180,9 @@ public override string FirmwareHash protected string CommentsString() { - var sb = new StringBuilder(); + StringBuilder sb = new(); - foreach (var comment in Comments) + foreach (string comment in Comments) { sb.AppendLine(comment); } diff --git a/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.IO.cs b/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.IO.cs index 3f5d53e0d7b..0bd56671cd0 100644 --- a/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.IO.cs +++ b/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.IO.cs @@ -10,10 +10,7 @@ namespace BizHawk.Client.Common { public partial class Bk2Movie { - public void Save() - { - Write(Filename); - } + public void Save() => Write(Filename); public void SaveBackup() { @@ -22,7 +19,7 @@ public void SaveBackup() return; } - var backupName = Filename; + string backupName = Filename; backupName = backupName.Insert(Filename.LastIndexOf(".", StringComparison.Ordinal), $".{DateTime.Now:yyyy-MM-dd HH.mm.ss}"); backupName = Path.Combine(Session.BackupDirectory, Path.GetFileName(backupName)); @@ -40,7 +37,7 @@ protected virtual void Write(string fn, bool isBackup = false) Header[HeaderKeys.EmulatorVersion] = VersionInfo.GetEmuVersion(); CreateDirectoryIfNotExists(fn); - using var bs = new ZipStateSaver(fn, Session.Settings.MovieCompressionLevel); + using ZipStateSaver bs = new(fn, Session.Settings.MovieCompressionLevel); AddLumps(bs, isBackup); if (!isBackup) @@ -69,17 +66,14 @@ private void SetCycleValues() private static void CreateDirectoryIfNotExists(string fn) { - var file = new FileInfo(fn); + FileInfo file = new(fn); if (file.Directory != null && !file.Directory.Exists) { Directory.CreateDirectory(file.Directory.ToString()); } } - protected virtual void AddLumps(ZipStateSaver bs, bool isBackup = false) - { - AddBk2Lumps(bs); - } + protected virtual void AddLumps(ZipStateSaver bs, bool isBackup = false) => AddBk2Lumps(bs); protected void AddBk2Lumps(ZipStateSaver bs) { @@ -160,7 +154,7 @@ private void LoadBk2Fields(ZipStateLoader bl) bl.GetLump(BinaryStateLump.Framebuffer, false, br => { - var fb = br.ReadAllBytes(); + byte[] fb = br.ReadAllBytes(); SavestateFramebuffer = new int[fb.Length / sizeof(int)]; Buffer.BlockCopy(fb, 0, SavestateFramebuffer, 0, fb.Length); }); diff --git a/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.InputLog.cs b/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.InputLog.cs index 9b407f3d494..660b98124b4 100644 --- a/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.InputLog.cs +++ b/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.InputLog.cs @@ -23,7 +23,7 @@ public void WriteInputLog(TextWriter writer) writer.WriteLine($"LogKey:{LogKey}"); } - foreach (var record in Log) + foreach (string record in Log) { writer.WriteLine(record); } @@ -60,7 +60,7 @@ public virtual bool ExtractInputLog(TextReader reader, out string errorMessage) } else if (line.StartsWithOrdinal("Frame ")) { - var strs = line.Split(' '); + string[] strs = line.Split(' '); try { stateFrame = int.Parse(strs[1]); @@ -82,7 +82,7 @@ public virtual bool ExtractInputLog(TextReader reader, out string errorMessage) errorMessage = "Savestate Frame number failed to parse"; } - var stateFramei = stateFrame ?? 0; + int stateFramei = stateFrame ?? 0; if (stateFramei.StrictlyBoundedBy(0.RangeTo(Log.Count))) { @@ -113,8 +113,8 @@ public bool CheckTimeLines(TextReader reader, out string errorMessage) { // This function will compare the movie data to the savestate movie data to see if they match errorMessage = ""; - var newLog = new List(); - var stateFrame = 0; + List newLog = new(); + int stateFrame = 0; string line; while ((line = reader.ReadLine()) != null) { @@ -124,7 +124,7 @@ public bool CheckTimeLines(TextReader reader, out string errorMessage) } else if (line.StartsWithOrdinal("Frame ")) { - var strs = line.Split(' '); + string[] strs = line.Split(' '); try { stateFrame = int.Parse(strs[1]); @@ -154,7 +154,7 @@ public bool CheckTimeLines(TextReader reader, out string errorMessage) return false; } - for (var i = 0; i < stateFrame; i++) + for (int i = 0; i < stateFrame; i++) { if (Log[i] != newLog[i]) { @@ -166,7 +166,7 @@ public bool CheckTimeLines(TextReader reader, out string errorMessage) if (stateFrame > newLog.Count) // stateFrame is greater than state input log, so movie finished mode { - if (Mode == MovieMode.Play || Mode == MovieMode.Finished) + if (Mode is MovieMode.Play or MovieMode.Finished) { Mode = MovieMode.Finished; return true; diff --git a/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.cs b/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.cs index 84aadc9e5d5..3a67eb6b4f5 100755 --- a/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.cs +++ b/src/BizHawk.Client.Common/movie/bk2/Bk2Movie.cs @@ -13,10 +13,7 @@ public Bk2Movie(IMovieSession session, string filename) : base(filename) Header[HeaderKeys.MovieVersion] = "BizHawk v2.0.0"; } - public virtual void Attach(IEmulator emulator) - { - Emulator = emulator; - } + public virtual void Attach(IEmulator emulator) => Emulator = emulator; protected bool IsAttached() => Emulator != null; @@ -52,7 +49,7 @@ public Bk2LogEntryGenerator LogGeneratorInstance(IController source) public void CopyLog(IEnumerable log) { Log.Clear(); - foreach (var entry in log) + foreach (string entry in log) { Log.Add(entry); } diff --git a/src/BizHawk.Client.Common/movie/bk2/StringLogs.cs b/src/BizHawk.Client.Common/movie/bk2/StringLogs.cs index 3a4cf026725..32c24643775 100644 --- a/src/BizHawk.Client.Common/movie/bk2/StringLogs.cs +++ b/src/BizHawk.Client.Common/movie/bk2/StringLogs.cs @@ -43,8 +43,8 @@ public static IStringLog MakeStringLog() public static string ToInputLog(this IStringLog log) { - var sb = new StringBuilder(); - foreach (var record in log) + StringBuilder sb = new(); + foreach (string record in log) { sb.AppendLine(record); } @@ -72,7 +72,7 @@ internal class ListStringLog : List, IStringLog { public IStringLog Clone() { - var ret = new ListStringLog(); + ListStringLog ret = new(); ret.AddRange(this); return ret; } @@ -89,7 +89,7 @@ public void Dispose() { } internal class StreamStringLog : IStringLog { private readonly Stream _stream; - private readonly List _offsets = new List(); + private readonly List _offsets = new(); private readonly BinaryWriter _bw; private readonly BinaryReader _br; private readonly bool _mDisk; @@ -99,7 +99,7 @@ public StreamStringLog(bool disk) _mDisk = disk; if (disk) { - var path = TempFileManager.GetTempFilename("movieOnDisk"); + string path = TempFileManager.GetTempFilename("movieOnDisk"); _stream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, 4 * 1024, FileOptions.DeleteOnClose); } else @@ -114,7 +114,7 @@ public StreamStringLog(bool disk) public IStringLog Clone() { - var ret = new StreamStringLog(_mDisk); // doesn't necessarily make sense to copy the mDisk value, they could be designated for different targets... + StreamStringLog ret = new(_mDisk); // doesn't necessarily make sense to copy the mDisk value, they could be designated for different targets... for (int i = 0; i < Count; i++) { ret.Add(this[i]); @@ -123,10 +123,7 @@ public IStringLog Clone() return ret; } - public void Dispose() - { - _stream.Dispose(); - } + public void Dispose() => _stream.Dispose(); public int Count => _offsets.Count; @@ -144,11 +141,9 @@ public void Add(string str) _bw.Flush(); } - public void RemoveAt(int index) - { + public void RemoveAt(int index) => // no garbage collection in the disk file... oh well. _offsets.RemoveAt(index); - } public string this[int index] { @@ -177,7 +172,7 @@ public void Insert(int index, string val) public void InsertRange(int index, IEnumerable collection) { - foreach (var item in collection) + foreach (string item in collection) { Insert(index++, item); } @@ -185,7 +180,7 @@ public void InsertRange(int index, IEnumerable collection) public void AddRange(IEnumerable collection) { - foreach (var item in collection) + foreach (string item in collection) { Add(item); } @@ -211,20 +206,14 @@ bool IEnumerator.MoveNext() return true; } - void IEnumerator.Reset() { _index = -1; } - + void IEnumerator.Reset() => _index = -1; + public void Dispose() { } } - IEnumerator IEnumerable.GetEnumerator() - { - return new Enumerator { Log = this }; - } + IEnumerator IEnumerable.GetEnumerator() => new Enumerator { Log = this }; - IEnumerator IEnumerable.GetEnumerator() - { - return new Enumerator { Log = this }; - } + IEnumerator IEnumerable.GetEnumerator() => new Enumerator { Log = this }; public void RemoveRange(int index, int count) { diff --git a/src/BizHawk.Client.Common/movie/import/BkmImport.cs b/src/BizHawk.Client.Common/movie/import/BkmImport.cs index 76996cf838a..cfe00c842c4 100644 --- a/src/BizHawk.Client.Common/movie/import/BkmImport.cs +++ b/src/BizHawk.Client.Common/movie/import/BkmImport.cs @@ -8,10 +8,10 @@ internal class BkmImport : MovieImporter { protected override void RunImport() { - var bkm = new BkmMovie { Filename = SourceFile.FullName }; + BkmMovie bkm = new() { Filename = SourceFile.FullName }; bkm.Load(); - for (var i = 0; i < bkm.InputLogLength; i++) + for (int i = 0; i < bkm.InputLogLength; i++) { var input = bkm.GetInputState(i, Result.Movie.Emulator.ControllerDefinition, bkm.Header[HeaderKeys.Platform]); Result.Movie.AppendFrame(input); @@ -23,7 +23,7 @@ protected override void RunImport() Result.Movie.SyncSettingsJson = bkm.SyncSettingsJson; Result.Movie.Comments.Clear(); - foreach (var comment in bkm.Comments) + foreach (string comment in bkm.Comments) { Result.Movie.Comments.Add(comment); } diff --git a/src/BizHawk.Client.Common/movie/import/DsmImport.cs b/src/BizHawk.Client.Common/movie/import/DsmImport.cs index d2831687dfd..90ba3353a51 100644 --- a/src/BizHawk.Client.Common/movie/import/DsmImport.cs +++ b/src/BizHawk.Client.Common/movie/import/DsmImport.cs @@ -27,7 +27,7 @@ protected override void RunImport() { Result.Movie.HeaderEntries[HeaderKeys.Platform] = VSystemID.Raw.NDS; - var syncSettings = new NDS.NDSSyncSettings(); + NDS.NDSSyncSettings syncSettings = new(); using var sr = SourceFile.OpenText(); string line; @@ -44,7 +44,7 @@ protected override void RunImport() } else if (line.StartsWithOrdinal("rerecordCount")) { - Result.Movie.Rerecords = (ulong) (int.TryParse(ParseHeader(line, "rerecordCount"), out var rerecordCount) ? rerecordCount : default); + Result.Movie.Rerecords = (ulong) (int.TryParse(ParseHeader(line, "rerecordCount"), out int rerecordCount) ? rerecordCount : default); } else if (line.StartsWithOrdinal("firmNickname")) { @@ -108,7 +108,7 @@ private void ImportInputFrame(string line) if (sections.Length > 1) { - var mnemonics = sections[1].Take(_buttons.Length).ToList(); + System.Collections.Generic.List mnemonics = sections[1].Take(_buttons.Length).ToList(); controller["Right"] = mnemonics[0] != '.'; controller["Left"] = mnemonics[1] != '.'; @@ -125,8 +125,8 @@ private void ImportInputFrame(string line) controller["Touch"] = sections[1].Substring(21, 1) != "0"; - var touchX = int.Parse(sections[1].Substring(13, 3)); - var touchY = int.Parse(sections[1].Substring(17, 3)); + int touchX = int.Parse(sections[1].Substring(13, 3)); + int touchY = int.Parse(sections[1].Substring(17, 3)); controller.AcceptNewAxes(new[] { diff --git a/src/BizHawk.Client.Common/movie/import/FcmImport.cs b/src/BizHawk.Client.Common/movie/import/FcmImport.cs index 7e3946c1cf0..e5b99d406b0 100644 --- a/src/BizHawk.Client.Common/movie/import/FcmImport.cs +++ b/src/BizHawk.Client.Common/movie/import/FcmImport.cs @@ -20,8 +20,8 @@ protected override void RunImport() { Result.Movie.HeaderEntries[HeaderKeys.Core] = CoreNames.NesHawk; - using var r = new BinaryReader(SourceFile.Open(FileMode.Open, FileAccess.Read)); - var signature = new string(r.ReadChars(4)); + using BinaryReader r = new(SourceFile.Open(FileMode.Open, FileAccess.Read)); + string signature = new(r.ReadChars(4)); if (signature != "FCM\x1A") { Result.Errors.Add("This is not a valid .FCM file."); @@ -30,9 +30,9 @@ protected override void RunImport() Result.Movie.HeaderEntries[HeaderKeys.Platform] = VSystemID.Raw.NES; - var syncSettings = new NES.NESSyncSettings(); + NES.NESSyncSettings syncSettings = new(); - var controllerSettings = new NESControlSettings + NESControlSettings controllerSettings = new() { NesLeftPort = nameof(ControllerNES), NesRightPort = nameof(ControllerNES) @@ -114,7 +114,7 @@ The savestate offset is . T Result.Movie.Comments.Add($"{EmulationOrigin} FCEU {emuVersion}"); // 034 name of the ROM used - UTF8 encoded nul-terminated string. - var gameBytes = new List(); + List gameBytes = new(); while (r.PeekChar() != 0) { gameBytes.Add(r.ReadByte()); @@ -130,7 +130,7 @@ The savestate offset is . T name and ends at the savestate offset. This string is displayed as "Author Info" in the Windows version of the emulator. */ - var authorBytes = new List(); + List authorBytes = new(); while (r.PeekChar() != 0) { authorBytes.Add(r.ReadByte()); diff --git a/src/BizHawk.Client.Common/movie/import/Fm2Import.cs b/src/BizHawk.Client.Common/movie/import/Fm2Import.cs index 95a7d3d918e..b695f3856da 100644 --- a/src/BizHawk.Client.Common/movie/import/Fm2Import.cs +++ b/src/BizHawk.Client.Common/movie/import/Fm2Import.cs @@ -17,11 +17,11 @@ protected override void RunImport() { Result.Movie.HeaderEntries[HeaderKeys.Core] = CoreNames.NesHawk; const string emulator = "FCEUX"; - var platform = VSystemID.Raw.NES; // TODO: FDS? + string platform = VSystemID.Raw.NES; // TODO: FDS? - var syncSettings = new NES.NESSyncSettings(); + NES.NESSyncSettings syncSettings = new(); - var controllerSettings = new NESControlSettings + NESControlSettings controllerSettings = new() { NesLeftPort = nameof(UnpluggedNES), NesRightPort = nameof(UnpluggedNES) @@ -46,7 +46,7 @@ protected override void RunImport() } else if (line.StartsWith("sub", StringComparison.OrdinalIgnoreCase)) { - var subtitle = ImportTextSubtitle(line); + string subtitle = ImportTextSubtitle(line); if (!string.IsNullOrEmpty(subtitle)) { @@ -97,7 +97,7 @@ protected override void RunImport() } else if (line.StartsWith("rerecordcount", StringComparison.OrdinalIgnoreCase)) { - Result.Movie.Rerecords = (ulong) (int.TryParse(ParseHeader(line, "rerecordCount"), out var rerecordCount) ? rerecordCount : default); + Result.Movie.Rerecords = (ulong) (int.TryParse(ParseHeader(line, "rerecordCount"), out int rerecordCount) ? rerecordCount : default); } else if (line.StartsWith("guid", StringComparison.OrdinalIgnoreCase)) { diff --git a/src/BizHawk.Client.Common/movie/import/FmvImport.cs b/src/BizHawk.Client.Common/movie/import/FmvImport.cs index 1b86bf00d24..9eeff7d87d7 100644 --- a/src/BizHawk.Client.Common/movie/import/FmvImport.cs +++ b/src/BizHawk.Client.Common/movie/import/FmvImport.cs @@ -15,9 +15,9 @@ internal class FmvImport : MovieImporter protected override void RunImport() { using var fs = SourceFile.Open(FileMode.Open, FileAccess.Read); - using var r = new BinaryReader(fs); + using BinaryReader r = new(fs); // 000 4-byte signature: 46 4D 56 1A "FMV\x1A" - var signature = new string(r.ReadChars(4)); + string signature = new(r.ReadChars(4)); if (signature != "FMV\x1A") { Result.Errors.Add("This is not a valid .FMV file."); @@ -35,7 +35,7 @@ protected override void RunImport() } Result.Movie.HeaderEntries[HeaderKeys.Platform] = VSystemID.Raw.NES; - var syncSettings = new NES.NESSyncSettings(); + NES.NESSyncSettings syncSettings = new(); // other bits: unknown, set to 0 // 005 1-byte flags: @@ -89,7 +89,7 @@ the file. Result.Warnings.Add("No input recorded."); } - var controllerSettings = new NESControlSettings + NESControlSettings controllerSettings = new() { NesLeftPort = controller1 ? nameof(ControllerNES) : nameof(UnpluggedNES), NesRightPort = controller2 ? nameof(ControllerNES) : nameof(UnpluggedNES) diff --git a/src/BizHawk.Client.Common/movie/import/GmvImport.cs b/src/BizHawk.Client.Common/movie/import/GmvImport.cs index d05504675cc..dd31d3d94a5 100644 --- a/src/BizHawk.Client.Common/movie/import/GmvImport.cs +++ b/src/BizHawk.Client.Common/movie/import/GmvImport.cs @@ -14,10 +14,10 @@ internal class GmvImport : MovieImporter protected override void RunImport() { using var fs = SourceFile.Open(FileMode.Open, FileAccess.Read); - using var r = new BinaryReader(fs); + using BinaryReader r = new(fs); // 000 16-byte signature and format version: "Gens Movie TEST9" - string signature = new string(r.ReadChars(15)); + string signature = new(r.ReadChars(15)); if (signature != "Gens Movie TEST") { Result.Errors.Add("This is not a valid .GMV file."); @@ -27,7 +27,7 @@ protected override void RunImport() Result.Movie.HeaderEntries[HeaderKeys.Platform] = VSystemID.Raw.GEN; // 00F ASCII-encoded GMV file format version. The most recent is 'A'. (?) - string version = new string(r.ReadChars(1)); + string version = new(r.ReadChars(1)); Result.Movie.Comments.Add($"{MovieOrigin} .GMV version {version}"); Result.Movie.Comments.Add($"{EmulationOrigin} Gens"); @@ -63,7 +63,7 @@ protected override void RunImport() // bit 5: if "1", movie is 3-player movie; if "0", movie is 2-player movie bool threePlayers = ((flags >> 5) & 0x1) != 0; - LibGPGX.InputData input = new LibGPGX.InputData(); + LibGPGX.InputData input = new(); input.dev[0] = player1Config == '6' ? LibGPGX.INPUT_DEVICE.DEVICE_PAD6B : LibGPGX.INPUT_DEVICE.DEVICE_PAD3B; @@ -72,7 +72,7 @@ protected override void RunImport() ? LibGPGX.INPUT_DEVICE.DEVICE_PAD6B : LibGPGX.INPUT_DEVICE.DEVICE_PAD3B; - var ss = new GPGX.GPGXSyncSettings + GPGX.GPGXSyncSettings ss = new() { UseSixButton = player1Config == '6' || player2Config == '6', ControlTypeLeft = GPGX.ControlType.Normal, @@ -88,7 +88,7 @@ protected override void RunImport() : LibGPGX.INPUT_DEVICE.DEVICE_PAD3B; } - var controlConverter = new GPGXControlConverter(input, false); + GPGXControlConverter controlConverter = new(input, false); SimpleController controller = new(controlConverter.ControllerDef); diff --git a/src/BizHawk.Client.Common/movie/import/IMovieImport.cs b/src/BizHawk.Client.Common/movie/import/IMovieImport.cs index b3a5e8576b4..fe78e180cea 100644 --- a/src/BizHawk.Client.Common/movie/import/IMovieImport.cs +++ b/src/BizHawk.Client.Common/movie/import/IMovieImport.cs @@ -40,7 +40,7 @@ public ImportResult Import( return Result; } - var newFileName = $"{SourceFile.FullName}.{Bk2Movie.Extension}"; + string newFileName = $"{SourceFile.FullName}.{Bk2Movie.Extension}"; Result.Movie = session.Get(newFileName); RunImport(); @@ -87,15 +87,15 @@ private string PromptForRom(MatchesMovieHash matchesMovieHash) if (!_dialogParent.ModalMessageBox2(messageBoxText, "ROM required to populate hash", useOKCancel: true)) return null; - var result = _dialogParent.ShowFileOpenDialog( + string result = _dialogParent.ShowFileOpenDialog( filter: RomLoader.RomFilter, initDir: Config.PathEntries.RomAbsolutePath(Result.Movie.SystemID)); if (result is null) return null; // skip hash migration when the dialog was canceled - using var rom = new HawkFile(result); + using HawkFile rom = new(result); if (rom.IsArchive) rom.BindFirst(); - var romData = (ReadOnlySpan) rom.ReadAllBytes(); + ReadOnlySpan romData = (ReadOnlySpan) rom.ReadAllBytes(); if (romData.Length % 1024 == 512) romData = romData.Slice(512, romData.Length - 512); if (matchesMovieHash(romData)) @@ -161,7 +161,7 @@ public class ImportResult public static ImportResult Error(string errorMsg) { - var result = new ImportResult(); + ImportResult result = new(); result.Errors.Add(errorMsg); return result; } diff --git a/src/BizHawk.Client.Common/movie/import/LsmvImport.cs b/src/BizHawk.Client.Common/movie/import/LsmvImport.cs index f05c6099bc5..1e1772ab40b 100644 --- a/src/BizHawk.Client.Common/movie/import/LsmvImport.cs +++ b/src/BizHawk.Client.Common/movie/import/LsmvImport.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; @@ -28,7 +27,7 @@ protected override void RunImport() Result.Movie.HeaderEntries[HeaderKeys.Core] = CoreNames.SubBsnes115; // .LSMV movies are .zip files containing data files. - using var fs = new FileStream(SourceFile.FullName, FileMode.Open, FileAccess.Read); + using FileStream fs = new(SourceFile.FullName, FileMode.Open, FileAccess.Read); { byte[] data = new byte[4]; fs.Read(data, 0, 4); @@ -40,9 +39,9 @@ protected override void RunImport() fs.Position = 0; } - using var zip = new ZipArchive(fs, ZipArchiveMode.Read, true); + using ZipArchive zip = new(fs, ZipArchiveMode.Read, true); - var ss = new BsnesCore.SnesSyncSettings(); + BsnesCore.SnesSyncSettings ss = new(); string platform = VSystemID.Raw.SNES; @@ -92,7 +91,7 @@ protected override void RunImport() string authors = Encoding.UTF8.GetString(stream.ReadAllBytes()); string authorList = ""; string authorLast = ""; - using (var reader = new StringReader(authors)) + using (StringReader reader = new(authors)) { // Each author is on a different line. while (reader.ReadLine() is string line) @@ -156,7 +155,7 @@ protected override void RunImport() break; } - bool pal = gametype == "snes_pal" || gametype == "sgb_pal"; + bool pal = gametype is "snes_pal" or "sgb_pal"; Result.Movie.HeaderEntries[HeaderKeys.Pal] = pal.ToString(); } else if (item.FullName == "input") @@ -167,7 +166,7 @@ protected override void RunImport() // Insert an empty frame in lsmv snes movies // see https://github.com/TASEmulators/BizHawk/issues/721 Result.Movie.AppendFrame(EmptyLmsvFrame()); - using (var reader = new StringReader(input)) + using (StringReader reader = new(input)) { while(reader.ReadLine() is string line) { @@ -229,15 +228,13 @@ protected override void RunImport() { using var stream = item.Open(); string subtitles = Encoding.UTF8.GetString(stream.ReadAllBytes()); - using (var reader = new StringReader(subtitles)) + using StringReader reader = new(subtitles); + while (reader.ReadLine() is string line) { - while (reader.ReadLine() is string line) + string subtitle = ImportTextSubtitle(line); + if (!string.IsNullOrEmpty(subtitle)) { - var subtitle = ImportTextSubtitle(line); - if (!string.IsNullOrEmpty(subtitle)) - { - Result.Movie.Subtitles.AddFromString(subtitle); - } + Result.Movie.Subtitles.AddFromString(subtitle); } } } @@ -269,7 +266,7 @@ private IController EmptyLmsvFrame() { SimpleController emptyController = new(_controllers.Definition); - foreach (var button in emptyController.Definition.BoolButtons) + foreach (string button in emptyController.Definition.BoolButtons) { emptyController[button] = false; } @@ -318,7 +315,7 @@ private void ImportTextFrame(string line) { if (player > _playerCount) break; - IReadOnlyList buttons = controllers.Definition.ControlsOrdered[player]; + var buttons = controllers.Definition.ControlsOrdered[player]; if (buttons[0].EndsWithOrdinal("Up")) // hack to identify gamepad / multitap which have a different button order in bizhawk compared to lsnes { buttons = new[] { "B", "Y", "Select", "Start", "Up", "Down", "Left", "Right", "A", "X", "L", "R" } diff --git a/src/BizHawk.Client.Common/movie/import/Mc2Import.cs b/src/BizHawk.Client.Common/movie/import/Mc2Import.cs index edf9fc3f586..b1843f81016 100644 --- a/src/BizHawk.Client.Common/movie/import/Mc2Import.cs +++ b/src/BizHawk.Client.Common/movie/import/Mc2Import.cs @@ -13,7 +13,7 @@ internal class Mc2Import : MovieImporter protected override void RunImport() { - var ss = new PCEngine.PCESyncSettings + PCEngine.PCESyncSettings ss = new() { Port1 = PceControllerType.Unplugged, Port2 = PceControllerType.Unplugged, @@ -46,7 +46,7 @@ protected override void RunImport() } else if (line.StartsWith("ports", StringComparison.OrdinalIgnoreCase)) { - var portNumStr = ParseHeader(line, "ports"); + string portNumStr = ParseHeader(line, "ports"); if (int.TryParse(portNumStr, out int ports)) { // Ugh @@ -145,7 +145,7 @@ protected override void RunImport() // Import a frame from a text-based format. private void ImportTextFrame(string line) { - var buttons = new[] { "Up", "Down", "Left", "Right", "B1", "B2", "Run", "Select" }; + string[] buttons = new[] { "Up", "Down", "Left", "Right", "B1", "B2", "Run", "Select" }; SimpleController controllers = new(_deck.Definition); diff --git a/src/BizHawk.Client.Common/movie/import/MmvImport.cs b/src/BizHawk.Client.Common/movie/import/MmvImport.cs index 7e05ebb6980..48c11d03536 100644 --- a/src/BizHawk.Client.Common/movie/import/MmvImport.cs +++ b/src/BizHawk.Client.Common/movie/import/MmvImport.cs @@ -13,10 +13,10 @@ internal class MmvImport : MovieImporter protected override void RunImport() { using var fs = SourceFile.Open(FileMode.Open, FileAccess.Read); - using var r = new BinaryReader(fs); + using BinaryReader r = new(fs); // 0000: 4-byte signature: "MMV\0" - string signature = new string(r.ReadChars(4)); + string signature = new(r.ReadChars(4)); if (signature != "MMV\0") { Result.Errors.Add("This is not a valid .MMV file."); @@ -94,8 +94,8 @@ protected override void RunImport() byte[] md5 = r.ReadBytes(16); Result.Movie.HeaderEntries[HeaderKeys.Md5] = md5.BytesToHexString().ToLowerInvariant(); - var ss = new SMS.SmsSyncSettings(); - var cd = new SMSControllerDeck(ss.Port1, ss.Port2, isGameGear, ss.UseKeyboard); + SMS.SmsSyncSettings ss = new(); + SMSControllerDeck cd = new(ss.Port1, ss.Port2, isGameGear, ss.UseKeyboard); SimpleController controllers = new(cd.Definition); /* diff --git a/src/BizHawk.Client.Common/movie/import/MovieImport.cs b/src/BizHawk.Client.Common/movie/import/MovieImport.cs index 72310e478e0..eddea48bda1 100644 --- a/src/BizHawk.Client.Common/movie/import/MovieImport.cs +++ b/src/BizHawk.Client.Common/movie/import/MovieImport.cs @@ -23,7 +23,7 @@ public static bool IsValidMovieExtension(string extension) .Any(e => string.Equals(extension, e.Extension, StringComparison.OrdinalIgnoreCase)); } - public static readonly FilesystemFilterSet AvailableImporters = new FilesystemFilterSet( + public static readonly FilesystemFilterSet AvailableImporters = new( Importers.Values.OrderBy(attr => attr.Emulator) .Select(attr => new FilesystemFilter(attr.Emulator, new[] { attr.Extension.Substring(1) })) // substring removes initial '.' .ToArray()) @@ -53,9 +53,6 @@ public static ImportResult ImportFile( : ImportResult.Error($"No importer found for file type {ext}"); } - private static Type ImporterForExtension(string ext) - { - return Importers.First(i => string.Equals(i.Value.Extension, ext, StringComparison.OrdinalIgnoreCase)).Key; - } + private static Type ImporterForExtension(string ext) => Importers.First(i => string.Equals(i.Value.Extension, ext, StringComparison.OrdinalIgnoreCase)).Key; } } diff --git a/src/BizHawk.Client.Common/movie/import/PjmImport.cs b/src/BizHawk.Client.Common/movie/import/PjmImport.cs index cacff790eaa..f5f962c1728 100644 --- a/src/BizHawk.Client.Common/movie/import/PjmImport.cs +++ b/src/BizHawk.Client.Common/movie/import/PjmImport.cs @@ -14,7 +14,7 @@ protected override void RunImport() Result.Movie.HeaderEntries[HeaderKeys.Platform] = VSystemID.Raw.PSX; using var fs = SourceFile.OpenRead(); - using var br = new BinaryReader(fs); + using BinaryReader br = new(fs); var info = ParseHeader(Result.Movie, "PJM ", br); fs.Seek(info.ControllerDataOffset, SeekOrigin.Begin); @@ -31,9 +31,9 @@ protected override void RunImport() protected MiscHeaderInfo ParseHeader(IMovie movie, string expectedMagic, BinaryReader br) { - var info = new MiscHeaderInfo(); + MiscHeaderInfo info = new(); - string magic = new string(br.ReadChars(4)); + string magic = new(br.ReadChars(4)); if (magic != expectedMagic) { Result.Errors.Add($"Not a {expectedMagic}file: invalid magic number in file header."); @@ -125,7 +125,7 @@ protected MiscHeaderInfo ParseHeader(IMovie movie, string expectedMagic, BinaryR return info; } - var syncSettings = new Octoshock.SyncSettings + Octoshock.SyncSettings syncSettings = new() { FIOConfig = { @@ -172,7 +172,7 @@ protected MiscHeaderInfo ParseHeader(IMovie movie, string expectedMagic, BinaryR protected void ParseBinaryInputLog(BinaryReader br, IMovie movie, MiscHeaderInfo info) { - var settings = new Octoshock.SyncSettings(); + Octoshock.SyncSettings settings = new(); settings.FIOConfig.Devices8 = new[] { info.Player1Type, @@ -282,7 +282,7 @@ protected void ParseBinaryInputLog(BinaryReader br, IMovie movie, MiscHeaderInfo protected void ParseTextInputLog(BinaryReader br, IMovie movie, MiscHeaderInfo info) { - Octoshock.SyncSettings settings = new Octoshock.SyncSettings(); + Octoshock.SyncSettings settings = new(); settings.FIOConfig.Devices8 = new[] { info.Player1Type, @@ -307,7 +307,7 @@ protected void ParseTextInputLog(BinaryReader br, IMovie movie, MiscHeaderInfo i for (int frame = 0; frame < info.FrameCount; ++frame) { - var mnemonicStr = new string(br.ReadChars(strCount)); + string mnemonicStr = new(br.ReadChars(strCount)); // Junk whitespace at the end of a file if (string.IsNullOrWhiteSpace(mnemonicStr)) @@ -321,10 +321,10 @@ protected void ParseTextInputLog(BinaryReader br, IMovie movie, MiscHeaderInfo i Result.Errors.Add("Unable to parse text input, unknown configuration"); } - var split = mnemonicStr.Replace("\r\n", "").Split('|'); - var player1Str = split[0]; - var player2Str = split[1]; - var controlStr = split[2]; + string[] split = mnemonicStr.Replace("\r\n", "").Split('|'); + string player1Str = split[0]; + string player2Str = split[1]; + string controlStr = split[2]; if (info.Player1Type != OctoshockDll.ePeripheralType.None) { // As L3 and R3 don't exist on a standard gamepad, handle them separately later. Unfortunately diff --git a/src/BizHawk.Client.Common/movie/import/PxmImport.cs b/src/BizHawk.Client.Common/movie/import/PxmImport.cs index c2200d7cc6b..3e1b0c27265 100644 --- a/src/BizHawk.Client.Common/movie/import/PxmImport.cs +++ b/src/BizHawk.Client.Common/movie/import/PxmImport.cs @@ -20,7 +20,7 @@ protected override void RunImport() movie.HeaderEntries[HeaderKeys.Platform] = VSystemID.Raw.PSX; using var fs = SourceFile.OpenRead(); - using var br = new BinaryReader(fs); + using BinaryReader br = new(fs); var info = ParseHeader(movie, "PXM ", br); fs.Seek(info.ControllerDataOffset, SeekOrigin.Begin); diff --git a/src/BizHawk.Client.Common/movie/import/SmvImport.cs b/src/BizHawk.Client.Common/movie/import/SmvImport.cs index b6889eb760e..2305ab262a0 100644 --- a/src/BizHawk.Client.Common/movie/import/SmvImport.cs +++ b/src/BizHawk.Client.Common/movie/import/SmvImport.cs @@ -19,10 +19,10 @@ protected override void RunImport() Result.Movie.HeaderEntries[HeaderKeys.Core] = CoreNames.Snes9X; using var fs = SourceFile.Open(FileMode.Open, FileAccess.Read); - using var r = new BinaryReader(fs); + using BinaryReader r = new(fs); // 000 4-byte signature: 53 4D 56 1A "SMV\x1A" - string signature = new string(r.ReadChars(4)); + string signature = new(r.ReadChars(4)); if (signature != "SMV\x1A") { Result.Errors.Add("This is not a valid .SMV file."); @@ -33,7 +33,7 @@ protected override void RunImport() // 004 4-byte little-endian unsigned int: version number uint versionNumber = r.ReadUInt32(); - var version = versionNumber switch + string version = versionNumber switch { 1 => "1.43", 4 => "1.51", @@ -74,7 +74,7 @@ recording time in Unix epoch format } int highestControllerIndex = 1 + Array.LastIndexOf(controllersUsed, true); - var ss = new Snes9x.SyncSettings(); + Snes9x.SyncSettings ss = new(); switch (highestControllerIndex) { @@ -190,7 +190,7 @@ is used (and MOVIE_SYNC_DATA_EXISTS is set), 0 bytes otherwise. Result.Movie.HeaderEntries[HeaderKeys.GameName] = gameName; } - var _controllers = new Snes9xControllers(ss); + Snes9xControllers _controllers = new(ss); Result.Movie.LogKey = new Bk2LogEntryGenerator("SNES", new Bk2Controller(_controllers.ControllerDefinition)).GenerateLogKey(); SimpleController controllers = new(_controllers.ControllerDefinition); @@ -261,7 +261,7 @@ is being recorded. { for (int i = 0; i < 2; i++) { - var peripheral = ""; + string peripheral = ""; switch (controllerTypes[i]) { case 0: // NONE diff --git a/src/BizHawk.Client.Common/movie/import/VbmImport.cs b/src/BizHawk.Client.Common/movie/import/VbmImport.cs index 3226e06a3b9..93f1a541c3a 100644 --- a/src/BizHawk.Client.Common/movie/import/VbmImport.cs +++ b/src/BizHawk.Client.Common/movie/import/VbmImport.cs @@ -16,11 +16,11 @@ internal class VbmImport : MovieImporter protected override void RunImport() { using var fs = SourceFile.Open(FileMode.Open, FileAccess.Read); - using var r = new BinaryReader(fs); + using BinaryReader r = new(fs); bool is_GBC = false; // 000 4-byte signature: 56 42 4D 1A "VBM\x1A" - string signature = new string(r.ReadChars(4)); + string signature = new(r.ReadChars(4)); if (signature != "VBM\x1A") { Result.Errors.Add("This is not a valid .VBM file."); @@ -200,7 +200,7 @@ recording time in Unix epoch format Result.Movie.Comments.Add(movieDescription); r.BaseStream.Position = firstFrameOffset; - SimpleController controllers = isGBA + var controllers = isGBA ? GbaController() : GbController(); diff --git a/src/BizHawk.Client.Common/movie/import/YmvImport.cs b/src/BizHawk.Client.Common/movie/import/YmvImport.cs index 20c1b39b899..617516e60f9 100644 --- a/src/BizHawk.Client.Common/movie/import/YmvImport.cs +++ b/src/BizHawk.Client.Common/movie/import/YmvImport.cs @@ -13,7 +13,7 @@ internal class YmvImport : MovieImporter protected override void RunImport() { Result.Movie.HeaderEntries[HeaderKeys.Platform] = VSystemID.Raw.SAT; - var ss = new Emulation.Cores.Waterbox.NymaCore.NymaSyncSettings + Emulation.Cores.Waterbox.NymaCore.NymaSyncSettings ss = new() { PortDevices = { @@ -109,7 +109,7 @@ private void ImportTextFrame(string line) }.MakeImmutable()); // Split up the sections of the frame. - var sections = line.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries); + string[] sections = line.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries); if (sections.Length != 2) { Result.Errors.Add("Unsupported input configuration"); diff --git a/src/BizHawk.Client.Common/movie/import/bkm/BkmControllerAdapter.cs b/src/BizHawk.Client.Common/movie/import/bkm/BkmControllerAdapter.cs index 6734a7b62e8..e7c9e198135 100644 --- a/src/BizHawk.Client.Common/movie/import/bkm/BkmControllerAdapter.cs +++ b/src/BizHawk.Client.Common/movie/import/bkm/BkmControllerAdapter.cs @@ -14,7 +14,7 @@ public BkmControllerAdapter(ControllerDefinition definition, string systemId) { // We do need to map the definition name to the legacy // controller names that were used back in the bkm days - var name = systemId switch + string name = systemId switch { "Lynx" => "Lynx Controller", "SNES" => "SNES Controller", @@ -39,15 +39,9 @@ public BkmControllerAdapter(ControllerDefinition definition, string systemId) public ControllerDefinition Definition { get; set; } - public bool IsPressed(string button) - { - return _myBoolButtons[button]; - } + public bool IsPressed(string button) => _myBoolButtons[button]; - public int AxisValue(string name) - { - return _myAxisControls[name]; - } + public int AxisValue(string name) => _myAxisControls[name]; public IReadOnlyCollection<(string Name, int Strength)> GetHapticsSnapshot() => throw new NotImplementedException(); // no idea --yoshi @@ -104,7 +98,7 @@ public void SetControllersAsMnemonic(string mnemonic) } } - var c = new MnemonicChecker(mnemonic); + MnemonicChecker c = new(mnemonic); _myBoolButtons.Clear(); @@ -164,7 +158,7 @@ public void SetControllersAsMnemonic(string mnemonic) Force("Power", mnemonic[1] != '.'); } - if (ControlType == "SMS Controller" || ControlType == "TI83 Controller" || ControlType == "ColecoVision Basic Controller") + if (ControlType is "SMS Controller" or "TI83 Controller" or "ColecoVision Basic Controller") { start = 1; } @@ -176,8 +170,8 @@ public void SetControllersAsMnemonic(string mnemonic) return; } - Force("Reset", mnemonic[1] != '.' && mnemonic[1] != '0'); - Force("Select", mnemonic[2] != '.' && mnemonic[2] != '0'); + Force("Reset", mnemonic[1] is not '.' and not '0'); + Force("Select", mnemonic[2] is not '.' and not '0'); start = 4; } @@ -191,7 +185,7 @@ public void SetControllersAsMnemonic(string mnemonic) } string prefix = ""; - if (ControlType != "Gameboy Controller" && ControlType != "TI83 Controller") + if (ControlType is not "Gameboy Controller" and not "TI83 Controller") { prefix = $"P{player} "; } @@ -206,33 +200,27 @@ public void SetControllersAsMnemonic(string mnemonic) { int srcIndex = BkmMnemonicConstants.Players[ControlType] * (BkmMnemonicConstants.Buttons[ControlType].Count + 1); int ctr = start; - foreach (var command in BkmMnemonicConstants.Commands[ControlType].Keys) + foreach (string command in BkmMnemonicConstants.Commands[ControlType].Keys) { Force(command, c[srcIndex + ctr++]); } } } - private readonly WorkingDictionary _myBoolButtons = new WorkingDictionary(); - private readonly WorkingDictionary _myAxisControls = new WorkingDictionary(); + private readonly WorkingDictionary _myBoolButtons = new(); + private readonly WorkingDictionary _myAxisControls = new(); private bool IsGenesis6Button() => Definition.BoolButtons.Contains("P1 X"); - private void Force(string button, bool state) - { - _myBoolButtons[button] = state; - } + private void Force(string button, bool state) => _myBoolButtons[button] = state; - private void Force(string name, int state) - { - _myAxisControls[name] = state; - } + private void Force(string name, int state) => _myAxisControls[name] = state; private string ControlType => Definition.Name; private void SetGBAControllersAsMnemonic(string mnemonic) { - var c = new MnemonicChecker(mnemonic); + MnemonicChecker c = new(mnemonic); _myBoolButtons.Clear(); if (mnemonic.Length < 2) { @@ -253,7 +241,7 @@ private void SetGBAControllersAsMnemonic(string mnemonic) private void SetGenesis6ControllersAsMnemonic(string mnemonic) { - var c = new MnemonicChecker(mnemonic); + MnemonicChecker c = new(mnemonic); _myBoolButtons.Clear(); if (mnemonic.Length < 2) @@ -265,7 +253,7 @@ private void SetGenesis6ControllersAsMnemonic(string mnemonic) { Force("Power", true); } - else if (mnemonic[1] != '.' && mnemonic[1] != '0') + else if (mnemonic[1] is not '.' and not '0') { Force("Reset", true); } @@ -294,7 +282,7 @@ private void SetGenesis6ControllersAsMnemonic(string mnemonic) private void SetGenesis3ControllersAsMnemonic(string mnemonic) { - var c = new MnemonicChecker(mnemonic); + MnemonicChecker c = new(mnemonic); _myBoolButtons.Clear(); if (mnemonic.Length < 2) @@ -306,7 +294,7 @@ private void SetGenesis3ControllersAsMnemonic(string mnemonic) { Force("Power", true); } - else if (mnemonic[1] != '.' && mnemonic[1] != '0') + else if (mnemonic[1] is not '.' and not '0') { Force("Reset", true); } @@ -335,7 +323,7 @@ private void SetGenesis3ControllersAsMnemonic(string mnemonic) private void SetSNESControllersAsMnemonic(string mnemonic) { - var c = new MnemonicChecker(mnemonic); + MnemonicChecker c = new(mnemonic); _myBoolButtons.Clear(); if (mnemonic.Length < 2) @@ -347,7 +335,7 @@ private void SetSNESControllersAsMnemonic(string mnemonic) { Force("Power", true); } - else if (mnemonic[1] != '.' && mnemonic[1] != '0') + else if (mnemonic[1] is not '.' and not '0') { Force("Reset", true); } @@ -362,7 +350,7 @@ private void SetSNESControllersAsMnemonic(string mnemonic) } int start = 3; - foreach (var button in BkmMnemonicConstants.Buttons[ControlType].Keys) + foreach (string button in BkmMnemonicConstants.Buttons[ControlType].Keys) { Force($"P{player} {button}", c[srcIndex + start++]); } @@ -371,7 +359,7 @@ private void SetSNESControllersAsMnemonic(string mnemonic) private void SetLynxControllersAsMnemonic(string mnemonic) { - var c = new MnemonicChecker(mnemonic); + MnemonicChecker c = new(mnemonic); _myBoolButtons.Clear(); if (mnemonic.Length < 2) @@ -394,7 +382,7 @@ private void SetLynxControllersAsMnemonic(string mnemonic) } int start = 3; - foreach (var button in BkmMnemonicConstants.Buttons[ControlType].Keys) + foreach (string button in BkmMnemonicConstants.Buttons[ControlType].Keys) { Force(button, c[srcIndex + start++]); } @@ -403,7 +391,7 @@ private void SetLynxControllersAsMnemonic(string mnemonic) private void SetN64ControllersAsMnemonic(string mnemonic) { - var c = new MnemonicChecker(mnemonic); + MnemonicChecker c = new(mnemonic); _myBoolButtons.Clear(); if (mnemonic.Length < 2) @@ -415,7 +403,7 @@ private void SetN64ControllersAsMnemonic(string mnemonic) { Force("Power", true); } - else if (mnemonic[1] != '.' && mnemonic[1] != '0') + else if (mnemonic[1] is not '.' and not '0') { Force("Reset", true); } @@ -445,7 +433,7 @@ private void SetN64ControllersAsMnemonic(string mnemonic) private void SetSaturnControllersAsMnemonic(string mnemonic) { - var c = new MnemonicChecker(mnemonic); + MnemonicChecker c = new(mnemonic); _myBoolButtons.Clear(); if (mnemonic.Length < 2) @@ -457,7 +445,7 @@ private void SetSaturnControllersAsMnemonic(string mnemonic) { Force("Power", true); } - else if (mnemonic[1] != '.' && mnemonic[1] != '0') + else if (mnemonic[1] is not '.' and not '0') { Force("Reset", true); } @@ -481,7 +469,7 @@ private void SetSaturnControllersAsMnemonic(string mnemonic) private void SetAtari7800AsMnemonic(string mnemonic) { - var c = new MnemonicChecker(mnemonic); + MnemonicChecker c = new(mnemonic); _myBoolButtons.Clear(); if (mnemonic.Length < 5) @@ -527,7 +515,7 @@ private void SetAtari7800AsMnemonic(string mnemonic) private void SetDualGameBoyControllerAsMnemonic(string mnemonic) { - var checker = new MnemonicChecker(mnemonic); + MnemonicChecker checker = new(mnemonic); _myBoolButtons.Clear(); for (int i = 0; i < BkmMnemonicConstants.DgbMnemonic.Length; i++) { @@ -541,7 +529,7 @@ private void SetDualGameBoyControllerAsMnemonic(string mnemonic) private void SetWonderSwanControllerAsMnemonic(string mnemonic) { - var checker = new MnemonicChecker(mnemonic); + MnemonicChecker checker = new(mnemonic); _myBoolButtons.Clear(); for (int i = 0; i < BkmMnemonicConstants.WsMnemonic.Length; i++) { @@ -555,7 +543,7 @@ private void SetWonderSwanControllerAsMnemonic(string mnemonic) private void SetC64ControllersAsMnemonic(string mnemonic) { - var c = new MnemonicChecker(mnemonic); + MnemonicChecker c = new(mnemonic); _myBoolButtons.Clear(); for (int player = 1; player <= BkmMnemonicConstants.Players[ControlType]; player++) @@ -568,7 +556,7 @@ private void SetC64ControllersAsMnemonic(string mnemonic) } int start = 1; - foreach (var button in BkmMnemonicConstants.Buttons[ControlType].Keys) + foreach (string button in BkmMnemonicConstants.Buttons[ControlType].Keys) { Force($"P{player} {button}", c[srcIndex + start++]); } diff --git a/src/BizHawk.Client.Common/movie/import/bkm/BkmHeader.cs b/src/BizHawk.Client.Common/movie/import/bkm/BkmHeader.cs index db21ab74055..fcb20439364 100644 --- a/src/BizHawk.Client.Common/movie/import/bkm/BkmHeader.cs +++ b/src/BizHawk.Client.Common/movie/import/bkm/BkmHeader.cs @@ -19,7 +19,7 @@ public BkmHeader() public string SavestateBinaryBase64Blob { - get => TryGetValue(HeaderKeys.SavestateBinaryBase64Blob, out var s) ? s : null; + get => TryGetValue(HeaderKeys.SavestateBinaryBase64Blob, out string s) ? s : null; set { if (value == null) @@ -35,7 +35,7 @@ public string SavestateBinaryBase64Blob public new string this[string key] { - get => TryGetValue(key, out var s) ? s : string.Empty; + get => TryGetValue(key, out string s) ? s : string.Empty; set => base[key] = value; } @@ -50,7 +50,7 @@ public bool ParseLineFromFile(string line) { if (!string.IsNullOrWhiteSpace(line)) { - var splitLine = line.Split(new[] { ' ' }, 2); + string[] splitLine = line.Split(new[] { ' ' }, 2); if (HeaderKeys.Contains(splitLine[0]) && !ContainsKey(splitLine[0])) { diff --git a/src/BizHawk.Client.Common/movie/import/bkm/BkmMnemonicConstants.cs b/src/BizHawk.Client.Common/movie/import/bkm/BkmMnemonicConstants.cs index 13a56785f1b..6efbde21168 100644 --- a/src/BizHawk.Client.Common/movie/import/bkm/BkmMnemonicConstants.cs +++ b/src/BizHawk.Client.Common/movie/import/bkm/BkmMnemonicConstants.cs @@ -4,7 +4,7 @@ namespace BizHawk.Client.Common { internal static class BkmMnemonicConstants { - public static readonly Dictionary> Buttons = new Dictionary> + public static readonly Dictionary> Buttons = new() { ["Gameboy Controller"] = new Dictionary { @@ -95,12 +95,12 @@ internal static class BkmMnemonicConstants } }; - public static readonly Dictionary> Analogs = new Dictionary> + public static readonly Dictionary> Analogs = new() { ["Nintendo 64 Controller"] = new Dictionary { ["X Axis"] = "X" , ["Y Axis"] = "Y" } }; - public static readonly Dictionary> Commands = new Dictionary> + public static readonly Dictionary> Commands = new() { ["Atari 2600 Basic Controller"] = new Dictionary { ["Reset"] = "r", ["Select"] = "s" }, ["Atari 7800 ProLine Joystick Controller"] = new Dictionary { ["Reset"] = "r", ["Select"] = "s" }, @@ -118,7 +118,7 @@ internal static class BkmMnemonicConstants ["GPGX 3-Button Controller"] = new Dictionary { ["Power"] = "P", ["Reset"] = "r" } }; - public static readonly Dictionary Players = new Dictionary + public static readonly Dictionary Players = new() { ["Gameboy Controller"] = 1, ["GBA Controller"] = 1, diff --git a/src/BizHawk.Client.Common/movie/import/bkm/BkmMovie.cs b/src/BizHawk.Client.Common/movie/import/bkm/BkmMovie.cs index b70c152c265..f59bd08e534 100644 --- a/src/BizHawk.Client.Common/movie/import/bkm/BkmMovie.cs +++ b/src/BizHawk.Client.Common/movie/import/bkm/BkmMovie.cs @@ -9,7 +9,7 @@ namespace BizHawk.Client.Common { internal class BkmMovie { - private readonly List _log = new List(); + private readonly List _log = new(); public BkmHeader Header { get; } = new BkmHeader(); public string Filename { get; set; } = ""; public bool Loaded { get; private set; } @@ -19,7 +19,7 @@ public BkmControllerAdapter GetInputState(int frame, ControllerDefinition defini { if (frame < InputLogLength && frame >= 0) { - var adapter = new BkmControllerAdapter(definition, sytemId); + BkmControllerAdapter adapter = new(definition, sytemId); adapter.SetControllersAsMnemonic(_log[frame]); return adapter; } @@ -41,7 +41,7 @@ public string SyncSettingsJson public bool Load() { - var file = new FileInfo(Filename); + FileInfo file = new(Filename); if (file.Exists == false) { diff --git a/src/BizHawk.Client.Common/movie/interfaces/IMovie.cs b/src/BizHawk.Client.Common/movie/interfaces/IMovie.cs index 3ccefb589be..68f71345338 100644 --- a/src/BizHawk.Client.Common/movie/interfaces/IMovie.cs +++ b/src/BizHawk.Client.Common/movie/interfaces/IMovie.cs @@ -210,8 +210,8 @@ public static FilesystemFilterSet GetFSFilterSet(this IMovie/*?*/ movie) public static bool IsPlaying(this IMovie movie) => movie?.Mode == MovieMode.Play; 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 IsPlayingOrFinished(this IMovie movie) => movie?.Mode == MovieMode.Play || movie?.Mode == MovieMode.Finished; - public static bool IsPlayingOrRecording(this IMovie movie) => movie?.Mode == MovieMode.Play || movie?.Mode == MovieMode.Record; + public static bool IsPlayingOrFinished(this IMovie movie) => movie?.Mode is MovieMode.Play or MovieMode.Finished; + public static bool IsPlayingOrRecording(this IMovie movie) => movie?.Mode is MovieMode.Play or MovieMode.Record; /// /// Emulation is currently right after the movie's last input frame, /// but no further frames have been emulated. diff --git a/src/BizHawk.Client.Common/movie/tasproj/StateDictionary.cs b/src/BizHawk.Client.Common/movie/tasproj/StateDictionary.cs index ffdb67fa1da..747f72c676d 100644 --- a/src/BizHawk.Client.Common/movie/tasproj/StateDictionary.cs +++ b/src/BizHawk.Client.Common/movie/tasproj/StateDictionary.cs @@ -51,15 +51,9 @@ public void SetState(int frame, Stream stream) public bool IsReadOnly => false; - public void Add(int key, byte[] value) - { - this[key] = value; - } + public void Add(int key, byte[] value) => this[key] = value; - public void Add(KeyValuePair item) - { - this[item.Key] = item.Value; - } + public void Add(KeyValuePair item) => this[item.Key] = item.Value; public void Clear() { @@ -69,20 +63,11 @@ public void Clear() _streams.Clear(); } - public bool Contains(KeyValuePair item) - { - throw new NotImplementedException(); - } + public bool Contains(KeyValuePair item) => throw new NotImplementedException(); - public bool ContainsKey(int key) - { - return _streams.ContainsKey(key); - } + public bool ContainsKey(int key) => _streams.ContainsKey(key); - public void CopyTo(KeyValuePair[] array, int arrayIndex) - { - throw new NotImplementedException(); - } + public void CopyTo(KeyValuePair[] array, int arrayIndex) => throw new NotImplementedException(); public IEnumerator> GetEnumerator() { @@ -101,10 +86,7 @@ public bool Remove(int key) return false; } - public bool Remove(KeyValuePair item) - { - throw new NotImplementedException(); - } + public bool Remove(KeyValuePair item) => throw new NotImplementedException(); public bool TryGetValue(int key, out byte[] value) { @@ -122,9 +104,6 @@ public bool TryGetValue(int key, out byte[] value) IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - public void Dispose() - { - Clear(); - } + public void Dispose() => Clear(); } } diff --git a/src/BizHawk.Client.Common/movie/tasproj/TasBranch.cs b/src/BizHawk.Client.Common/movie/tasproj/TasBranch.cs index b4ace9f0c58..ef3c3ecace0 100644 --- a/src/BizHawk.Client.Common/movie/tasproj/TasBranch.cs +++ b/src/BizHawk.Client.Common/movie/tasproj/TasBranch.cs @@ -10,7 +10,7 @@ namespace BizHawk.Client.Common { public class TasBranch { - internal struct ForSerialization + internal readonly struct ForSerialization { public readonly int Frame; @@ -116,7 +116,7 @@ public void Replace(TasBranch old, TasBranch newBranch) public new bool Remove(TasBranch item) { - var result = base.Remove(item); + bool result = base.Remove(item); if (result) { _movie.FlagChanges(); @@ -127,13 +127,13 @@ public void Replace(TasBranch old, TasBranch newBranch) public void Save(ZipStateSaver bs) { - var nheader = new IndexedStateLump(BinaryStateLump.BranchHeader); - var ncore = new IndexedStateLump(BinaryStateLump.BranchCoreData); - var ninput = new IndexedStateLump(BinaryStateLump.BranchInputLog); - var nframebuffer = new IndexedStateLump(BinaryStateLump.BranchFrameBuffer); - var ncoreframebuffer = new IndexedStateLump(BinaryStateLump.BranchCoreFrameBuffer); - var nmarkers = new IndexedStateLump(BinaryStateLump.BranchMarkers); - var nusertext = new IndexedStateLump(BinaryStateLump.BranchUserText); + IndexedStateLump nheader = new(BinaryStateLump.BranchHeader); + IndexedStateLump ncore = new(BinaryStateLump.BranchCoreData); + IndexedStateLump ninput = new(BinaryStateLump.BranchInputLog); + IndexedStateLump nframebuffer = new(BinaryStateLump.BranchFrameBuffer); + IndexedStateLump ncoreframebuffer = new(BinaryStateLump.BranchCoreFrameBuffer); + IndexedStateLump nmarkers = new(BinaryStateLump.BranchMarkers); + IndexedStateLump nusertext = new(BinaryStateLump.BranchUserText); foreach (var b in this) { bs.PutLump(nheader, tw => tw.WriteLine(JsonConvert.SerializeObject(b.ForSerial))); @@ -151,13 +151,13 @@ public void Save(ZipStateSaver bs) bs.PutLump(nframebuffer, s => { - var vp = new BitmapBufferVideoProvider(b.OSDFrameBuffer); + BitmapBufferVideoProvider vp = new(b.OSDFrameBuffer); QuickBmpFile.Save(vp, s, b.OSDFrameBuffer.Width, b.OSDFrameBuffer.Height); }); bs.PutLump(ncoreframebuffer, s => { - var vp = new BitmapBufferVideoProvider(b.CoreFrameBuffer); + BitmapBufferVideoProvider vp = new(b.CoreFrameBuffer); QuickBmpFile.Save(vp, s, b.CoreFrameBuffer.Width, b.CoreFrameBuffer.Height); }); @@ -177,23 +177,23 @@ public void Save(ZipStateSaver bs) public void Load(ZipStateLoader bl, ITasMovie movie) { - var nheader = new IndexedStateLump(BinaryStateLump.BranchHeader); - var ncore = new IndexedStateLump(BinaryStateLump.BranchCoreData); - var ninput = new IndexedStateLump(BinaryStateLump.BranchInputLog); - var nframebuffer = new IndexedStateLump(BinaryStateLump.BranchFrameBuffer); - var ncoreframebuffer = new IndexedStateLump(BinaryStateLump.BranchCoreFrameBuffer); - var nmarkers = new IndexedStateLump(BinaryStateLump.BranchMarkers); - var nusertext = new IndexedStateLump(BinaryStateLump.BranchUserText); + IndexedStateLump nheader = new(BinaryStateLump.BranchHeader); + IndexedStateLump ncore = new(BinaryStateLump.BranchCoreData); + IndexedStateLump ninput = new(BinaryStateLump.BranchInputLog); + IndexedStateLump nframebuffer = new(BinaryStateLump.BranchFrameBuffer); + IndexedStateLump ncoreframebuffer = new(BinaryStateLump.BranchCoreFrameBuffer); + IndexedStateLump nmarkers = new(BinaryStateLump.BranchMarkers); + IndexedStateLump nusertext = new(BinaryStateLump.BranchUserText); Clear(); while (true) { - var b = new TasBranch(); + TasBranch b = new(); if (!bl.GetLump(nheader, abort: false, tr => { - var header = (dynamic)JsonConvert.DeserializeObject(tr.ReadLine()); + dynamic header = JsonConvert.DeserializeObject(tr.ReadLine()); b.Frame = (int)header.Frame; var timestamp = header.TimeStamp; diff --git a/src/BizHawk.Client.Common/movie/tasproj/TasLagLog.cs b/src/BizHawk.Client.Common/movie/tasproj/TasLagLog.cs index 303d7c5a860..6e820025310 100644 --- a/src/BizHawk.Client.Common/movie/tasproj/TasLagLog.cs +++ b/src/BizHawk.Client.Common/movie/tasproj/TasLagLog.cs @@ -7,14 +7,14 @@ namespace BizHawk.Client.Common { public class TasLagLog { - private Dictionary _lagLog = new Dictionary(); - private Dictionary _wasLag = new Dictionary(); + private Dictionary _lagLog = new(); + private Dictionary _wasLag = new(); public bool? this[int frame] { get { - var result = _lagLog.TryGetValue(frame, out var lag); + bool result = _lagLog.TryGetValue(frame, out bool lag); return result ? lag : null; } @@ -38,8 +38,8 @@ public void Clear() public bool RemoveFrom(int frame) { - var frames = _lagLog.Keys.Where(k => k > frame).ToList(); - foreach (var f in frames) + List frames = _lagLog.Keys.Where(k => k > frame).ToList(); + foreach (int f in frames) { RemoveLagEntry(f); } @@ -47,10 +47,7 @@ public bool RemoveFrom(int frame) return frames.Any(); } - public void RemoveHistoryAt(int frame) - { - _wasLag.Remove(frame); - } + public void RemoveHistoryAt(int frame) => _wasLag.Remove(frame); public void InsertHistoryAt(int frame, bool isLag) { @@ -72,7 +69,7 @@ public void Load(TextReader tr) public bool? History(int frame) { - var result = _wasLag.TryGetValue(frame, out var wasLag); + bool result = _wasLag.TryGetValue(frame, out bool wasLag); if (result) { return wasLag; @@ -98,7 +95,7 @@ public void StartFromFrame(int index) private void RemoveLagEntry(int frame) { - var result = _lagLog.TryGetValue(frame, out var lag); + bool result = _lagLog.TryGetValue(frame, out bool lag); if (result) { _wasLag[frame] = lag; diff --git a/src/BizHawk.Client.Common/movie/tasproj/TasMovie.Editing.cs b/src/BizHawk.Client.Common/movie/tasproj/TasMovie.Editing.cs index a4e6d8ef131..9bb05264e0a 100644 --- a/src/BizHawk.Client.Common/movie/tasproj/TasMovie.Editing.cs +++ b/src/BizHawk.Client.Common/movie/tasproj/TasMovie.Editing.cs @@ -105,10 +105,7 @@ private void ShiftBindedMarkers(int frame, int offset) } } - public void RemoveFrame(int frame) - { - RemoveFrames(frame, frame + 1); - } + public void RemoveFrame(int frame) => RemoveFrames(frame, frame + 1); public void RemoveFrames(ICollection frames) { @@ -125,11 +122,11 @@ public void RemoveFrames(ICollection frames) while (numDeleted != framesToDelete.Count) { int startFrame; - var prevFrame = startFrame = framesToDelete[f]; + int prevFrame = startFrame = framesToDelete[f]; f++; for (; f < framesToDelete.Count; f++) { - var frame = framesToDelete[f]; + int frame = framesToDelete[f]; if (frame - 1 != prevFrame) { f--; @@ -156,7 +153,7 @@ public void RemoveFrames(int removeStart, int removeUpTo) Log.CopyTo(removeStart, removedInputs, 0, removedInputs.Length); // Pre-process removed markers for the ChangeLog. - List removedMarkers = new List(); + List removedMarkers = new(); if (BindMarkersToInput) { bool wasRecording = ChangeLog.IsRecording; @@ -190,7 +187,7 @@ public void RemoveFrames(int removeStart, int removeUpTo) public void InsertInput(int frame, string inputState) { - var inputLog = new List { inputState }; + List inputLog = new() { inputState }; InsertInput(frame, inputLog); // ChangeLog handled within } @@ -209,7 +206,7 @@ public void InsertInput(int frame, IEnumerable inputLog) public void InsertInput(int frame, IEnumerable inputStates) { // ChangeLog is done in the InsertInput call. - var inputLog = new List(); + List inputLog = new(); foreach (var input in inputStates) { @@ -224,8 +221,8 @@ public int CopyOverInput(int frame, IEnumerable inputStates) { int firstChangedFrame = -1; ChangeLog.BeginNewBatch($"Copy Over Input: {frame}"); - - var states = inputStates.ToList(); + + List states = inputStates.ToList(); if (Log.Count < states.Count + frame) { @@ -242,7 +239,7 @@ public int CopyOverInput(int frame, IEnumerable inputStates) } var lg = LogGeneratorInstance(states[i]); - var entry = lg.GenerateLogEntry(); + string entry = lg.GenerateLogEntry(); if (firstChangedFrame == -1 && Log[frame + i] != entry) { firstChangedFrame = frame + i; @@ -325,7 +322,7 @@ public void SetBoolState(int frame, string buttonName, bool val) } var adapter = GetInputState(frame); - var old = adapter.IsPressed(buttonName); + bool old = adapter.IsPressed(buttonName); adapter.SetBool(buttonName, val); var lg = LogGeneratorInstance(adapter); @@ -381,7 +378,7 @@ public void SetAxisState(int frame, string buttonName, int val) } var adapter = GetInputState(frame); - var old = adapter.AxisValue(buttonName); + int old = adapter.AxisValue(buttonName); adapter.SetAxis(buttonName, val); var lg = LogGeneratorInstance(adapter); @@ -408,7 +405,7 @@ public void SetAxisStates(int frame, int count, string buttonName, int val) for (int i = 0; i < count; i++) { var adapter = GetInputState(frame + i); - var old = adapter.AxisValue(buttonName); + int old = adapter.AxisValue(buttonName); adapter.SetAxis(buttonName, val); var lg = LogGeneratorInstance(adapter); diff --git a/src/BizHawk.Client.Common/movie/tasproj/TasMovie.History.cs b/src/BizHawk.Client.Common/movie/tasproj/TasMovie.History.cs index bc2401f70f5..42553abb9fa 100644 --- a/src/BizHawk.Client.Common/movie/tasproj/TasMovie.History.cs +++ b/src/BizHawk.Client.Common/movie/tasproj/TasMovie.History.cs @@ -39,7 +39,7 @@ public TasMovieChangeLog(ITasMovie movie) _movie = movie; } - private readonly List> _history = new List>(); + private readonly List> _history = new(); private readonly ITasMovie _movie; private int _maxSteps = 100; @@ -190,7 +190,7 @@ public int Undo() return _movie.InputLogLength; } - List batch = _history[UndoIndex]; + var batch = _history[UndoIndex]; for (int i = batch.Count - 1; i >= 0; i--) { batch[i].Undo(_movie); @@ -214,8 +214,8 @@ public int Redo() } UndoIndex++; - List batch = _history[UndoIndex]; - foreach (IMovieAction b in batch) + var batch = _history[UndoIndex]; + foreach (var b in batch) { b.Redo(_movie); } diff --git a/src/BizHawk.Client.Common/movie/tasproj/TasMovie.IO.cs b/src/BizHawk.Client.Common/movie/tasproj/TasMovie.IO.cs index ee1dc396f32..685865c4fb3 100644 --- a/src/BizHawk.Client.Common/movie/tasproj/TasMovie.IO.cs +++ b/src/BizHawk.Client.Common/movie/tasproj/TasMovie.IO.cs @@ -21,14 +21,14 @@ protected override void AddLumps(ZipStateSaver bs, bool isBackup = false) private void AddTasProjLumps(ZipStateSaver bs, bool isBackup = false) { - var settings = JsonConvert.SerializeObject(TasStateManager.Settings); + string settings = JsonConvert.SerializeObject(TasStateManager.Settings); bs.PutLump(BinaryStateLump.StateHistorySettings, tw => tw.WriteLine(settings)); bs.PutLump(BinaryStateLump.LagLog, tw => LagLog.Save(tw)); bs.PutLump(BinaryStateLump.Markers, tw => tw.WriteLine(Markers.ToString())); if (ClientSettingsForSave != null) { - var clientSettingsJson = ClientSettingsForSave(); + string clientSettingsJson = ClientSettingsForSave(); bs.PutLump(BinaryStateLump.ClientSettings, (TextWriter tw) => tw.Write(clientSettingsJson)); } @@ -121,7 +121,7 @@ private void LoadTasprojExtras(ZipStateLoader bl) VerificationLog.Clear(); while (true) { - var line = tr.ReadLine(); + string line = tr.ReadLine(); if (string.IsNullOrEmpty(line)) { break; @@ -138,7 +138,7 @@ private void LoadTasprojExtras(ZipStateLoader bl) bl.GetLump(BinaryStateLump.Session, abort: false, tr => { - var json = tr.ReadToEnd(); + string json = tr.ReadToEnd(); try { TasSession = JsonConvert.DeserializeObject(json); @@ -149,10 +149,10 @@ private void LoadTasprojExtras(ZipStateLoader bl) } }); - ZwinderStateManagerSettings settings = new ZwinderStateManagerSettings(); + ZwinderStateManagerSettings settings = new(); bl.GetLump(BinaryStateLump.StateHistorySettings, abort: false, tr => { - var json = tr.ReadToEnd(); + string json = tr.ReadToEnd(); try { settings = JsonConvert.DeserializeObject(json); diff --git a/src/BizHawk.Client.Common/movie/tasproj/TasMovie.cs b/src/BizHawk.Client.Common/movie/tasproj/TasMovie.cs index f3101ab9e82..d6fb9d2bc24 100644 --- a/src/BizHawk.Client.Common/movie/tasproj/TasMovie.cs +++ b/src/BizHawk.Client.Common/movie/tasproj/TasMovie.cs @@ -52,7 +52,7 @@ public override void Attach(IEmulator emulator) } else { - var ms = new MemoryStream(); + MemoryStream ms = new(); if (StartsFromSaveRam && emulator.HasSaveRam()) { emulator.AsSaveRam().StoreSaveRam(SaveRam!); @@ -63,13 +63,13 @@ public override void Attach(IEmulator emulator) base.Attach(emulator); - foreach (var button in emulator.ControllerDefinition.BoolButtons) + foreach (string button in emulator.ControllerDefinition.BoolButtons) { _mnemonicCache[button] = Bk2MnemonicLookup.Lookup(button, emulator.SystemId); } } - private readonly Dictionary _mnemonicCache = new Dictionary(); + private readonly Dictionary _mnemonicCache = new(); public override bool StartsFromSavestate { @@ -101,8 +101,8 @@ public ITasMovieRecord this[int index] { get { - var lagIndex = index + 1; - var lagged = LagLog[lagIndex]; + int lagIndex = index + 1; + bool? lagged = LagLog[lagIndex]; if (lagged == null) { if (IsAttached() && Emulator.Frame == lagIndex) @@ -133,8 +133,8 @@ public override void StartNewRecording() // Removes lag log and greenzone after this frame private void InvalidateAfter(int frame) { - var anyLagInvalidated = LagLog.RemoveFrom(frame); - var anyStateInvalidated = TasStateManager.InvalidateAfter(frame); + bool anyLagInvalidated = LagLog.RemoveFrom(frame); + bool anyStateInvalidated = TasStateManager.InvalidateAfter(frame); GreenzoneInvalidated(frame + 1); if (anyLagInvalidated || anyStateInvalidated) { @@ -214,7 +214,7 @@ public override bool ExtractInputLog(TextReader reader, out string errorMessage) errorMessage = ""; int? stateFrame = null; - var newLog = new List(); + List newLog = new(); int? timelineBranchFrame = null; // We are in record mode so replace the movie log with the one from the savestate @@ -240,7 +240,7 @@ public override bool ExtractInputLog(TextReader reader, out string errorMessage) } else if (line.StartsWithOrdinal("Frame ")) { - var split = line.Split(' '); + string[] split = line.Split(' '); try { stateFrame = int.Parse(split[1]); @@ -265,7 +265,7 @@ public override bool ExtractInputLog(TextReader reader, out string errorMessage) errorMessage = "Savestate Frame number failed to parse"; } - var stateFrameValue = stateFrame ?? 0; + int stateFrameValue = stateFrame ?? 0; if (stateFrameValue > 0 && stateFrameValue < Log.Count) { @@ -333,16 +333,11 @@ protected set } // This event is Raised only when Changes is TOGGLED. - private void OnPropertyChanged(string propertyName) - { + private void OnPropertyChanged(string propertyName) => // Raising the event when FirstName or LastName property value changed PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - } - private void Markers_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) - { - Changes = true; - } + private void Markers_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) => Changes = true; public void ClearChanges() => Changes = false; public void FlagChanges() => Changes = true; diff --git a/src/BizHawk.Client.Common/movie/tasproj/TasMovieMarker.cs b/src/BizHawk.Client.Common/movie/tasproj/TasMovieMarker.cs index edc8682b3d2..d50c1d2abc4 100644 --- a/src/BizHawk.Client.Common/movie/tasproj/TasMovieMarker.cs +++ b/src/BizHawk.Client.Common/movie/tasproj/TasMovieMarker.cs @@ -23,7 +23,7 @@ public TasMovieMarker(int frame, string message = "") /// public TasMovieMarker(string line) { - var split = line.Split('\t'); + string[] split = line.Split('\t'); Frame = int.Parse(split[0]); Message = split[1]; } @@ -72,10 +72,7 @@ public override bool Equals(object obj) /// Intended for moving binded markers during frame inserts/deletions. /// /// Amount to shift marker by. - public void ShiftTo(int offset) - { - Frame += offset; - } + public void ShiftTo(int offset) => Frame += offset; } public class TasMovieMarkerList : List @@ -89,7 +86,7 @@ public TasMovieMarkerList(ITasMovie movie) public TasMovieMarkerList DeepClone() { - var ret = new TasMovieMarkerList(_movie); + TasMovieMarkerList ret = new(_movie); for (int i = 0; i < Count; i++) { // used to copy markers between branches @@ -101,15 +98,13 @@ public TasMovieMarkerList DeepClone() public event NotifyCollectionChangedEventHandler CollectionChanged; - private void OnListChanged(NotifyCollectionChangedAction action) - { + private void OnListChanged(NotifyCollectionChangedAction action) => // TODO Allow different types CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); - } public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new(); foreach (var marker in this) { sb.AppendLine(marker.ToString()); @@ -119,10 +114,7 @@ public override string ToString() } // the inherited one - public new void Add(TasMovieMarker item) - { - Add(item, false); - } + public new void Add(TasMovieMarker item) => Add(item, false); public void Add(TasMovieMarker item, bool skipHistory) { @@ -153,15 +145,12 @@ public void Add(TasMovieMarker item, bool skipHistory) } } - public void Add(int frame, string message) - { - Add(new TasMovieMarker(frame, message)); - } + public void Add(int frame, string message) => Add(new TasMovieMarker(frame, message)); public new void AddRange(IEnumerable collection) { bool endBatch = _movie.ChangeLog.BeginNewBatch("Add Markers", true); - foreach (TasMovieMarker m in collection) + foreach (var m in collection) { Add(m); } @@ -184,7 +173,7 @@ public void Add(int frame, string message) public new void InsertRange(int index, IEnumerable collection) { bool endBatch = _movie.ChangeLog.BeginNewBatch("Add Markers", true); - foreach (TasMovieMarker m in collection) + foreach (var m in collection) { _movie.ChangeLog.AddMarkerChange(m); } @@ -216,7 +205,7 @@ public void Add(int frame, string message) public new int RemoveAll(Predicate match) { bool endBatch = _movie.ChangeLog.BeginNewBatch("Remove All Markers", true); - foreach (TasMovieMarker m in this) + foreach (var m in this) { if (match.Invoke(m)) { @@ -246,7 +235,7 @@ public void Move(int fromFrame, int toFrame) return; } - TasMovieMarker m = Get(fromFrame); + var m = Get(fromFrame); if (m == null) // TODO: Don't do this. { return; @@ -318,21 +307,12 @@ public TasMovieMarker Next(int currentFrame) .FirstOrDefault(); } - public int FindIndex(string markerName) - { - return FindIndex(m => m.Message == markerName); - } + public int FindIndex(string markerName) => FindIndex(m => m.Message == markerName); - public bool IsMarker(int frame) - { - return this.Any(m => m == frame); - } + public bool IsMarker(int frame) => this.Any(m => m == frame); + + public TasMovieMarker Get(int frame) => this.FirstOrDefault(m => m == frame); - public TasMovieMarker Get(int frame) - { - return this.FirstOrDefault(m => m == frame); - } - public void ShiftAt(int frame, int offset) { foreach (var marker in this.Where(m => m.Frame >= frame).ToList()) diff --git a/src/BizHawk.Client.Common/movie/tasproj/ZwinderStateManager.cs b/src/BizHawk.Client.Common/movie/tasproj/ZwinderStateManager.cs index 9baa2b97b25..89de1a0dd7d 100644 --- a/src/BizHawk.Client.Common/movie/tasproj/ZwinderStateManager.cs +++ b/src/BizHawk.Client.Common/movie/tasproj/ZwinderStateManager.cs @@ -14,7 +14,7 @@ public class ZwinderStateManager : IStateManager, IDisposable private static readonly byte[] NonState = Array.Empty(); private readonly Func _reserveCallback; - internal readonly SortedList StateCache = new SortedList(); + internal readonly SortedList StateCache = new(); private ZwinderBuffer _current; private ZwinderBuffer _recent; @@ -75,7 +75,7 @@ public byte[] this[int frame] return NonState; } - var data = dataStream.ReadAllBytes(); + byte[] data = dataStream.ReadAllBytes(); dataStream.Dispose(); return data; } @@ -98,7 +98,7 @@ public void UpdateSettings(ZwinderStateManagerSettings settings, bool keepOldSta if (settings.AncientStateInterval > _ancientInterval) { int lastReserved = 0; - List framesToRemove = new List(); + List framesToRemove = new(); foreach (int f in _reserved.Keys) { if (!_reserveCallback(f) && f - lastReserved < settings.AncientStateInterval) @@ -117,7 +117,7 @@ public void UpdateSettings(ZwinderStateManagerSettings settings, bool keepOldSta { if (_reserved != null) { - List framesToRemove = new List(); + List framesToRemove = new(); foreach (int f in _reserved.Keys) { if (f != 0 && !_reserveCallback(f)) @@ -137,18 +137,12 @@ public void UpdateSettings(ZwinderStateManagerSettings settings, bool keepOldSta private void RebuildReserved() { - IDictionary newReserved; - switch (Settings.AncientStoreType) + IDictionary newReserved = Settings.AncientStoreType switch { - case IRewindSettings.BackingStoreType.Memory: - newReserved = new Dictionary(); - break; - case IRewindSettings.BackingStoreType.TempFile: - newReserved = new TempFileStateDictionary(); - break; - default: - throw new InvalidOperationException("Unsupported store type for reserved states."); - } + IRewindSettings.BackingStoreType.Memory => new Dictionary(), + IRewindSettings.BackingStoreType.TempFile => new TempFileStateDictionary(), + _ => throw new InvalidOperationException("Unsupported store type for reserved states."), + }; if (_reserved != null) { foreach (var (f, data) in _reserved) newReserved.Add(f, data); @@ -166,11 +160,11 @@ private ZwinderBuffer UpdateBuffer(ZwinderBuffer buffer, RewindConfig newConfig, if (keepOldStates) { // force capture all the old states, let the buffer handle decay if they don't all fit - ZwinderBuffer old = buffer; + var old = buffer; buffer = new ZwinderBuffer(newConfig); for (int i = 0; i < old.Count; i++) { - ZwinderBuffer.StateInformation si = old.GetState(i); + var si = old.GetState(i); // don't allow states that should be reserved to decay here, where we don't attempt re-capture if (_reserveCallback(si.Frame)) AddToReserved(si); @@ -195,7 +189,7 @@ private ZwinderBuffer UpdateBuffer(ZwinderBuffer buffer, RewindConfig newConfig, private void RebuildStateCache() { StateCache.Clear(); - foreach (StateInfo state in AllStates()) + foreach (var state in AllStates()) { AddStateCache(state.Frame); } @@ -223,11 +217,11 @@ public StateInfo(int frame, byte[] data) // Enumerate all current and recent states in reverse order private IEnumerable CurrentAndRecentStates() { - for (var i = _current.Count - 1; i >= 0; i--) + for (int i = _current.Count - 1; i >= 0; i--) { yield return new StateInfo(_current.GetState(i)); } - for (var i = _recent.Count - 1; i >= 0; i--) + for (int i = _recent.Count - 1; i >= 0; i--) { yield return new StateInfo(_recent.GetState(i)); } @@ -236,7 +230,7 @@ private IEnumerable CurrentAndRecentStates() // Enumerate all gap states in reverse order private IEnumerable GapStates() { - for (var i = _gapFiller.Count - 1; i >= 0; i--) + for (int i = _gapFiller.Count - 1; i >= 0; i--) { yield return new StateInfo(_gapFiller.GetState(i)); } @@ -245,7 +239,7 @@ private IEnumerable GapStates() // Enumerate all reserved states in reverse order private IEnumerable ReservedStates() { - foreach (var key in _reserved.Keys.OrderDescending()) + foreach (int key in _reserved.Keys.OrderDescending()) { yield return new StateInfo(key, _reserved[key]); } @@ -273,7 +267,7 @@ internal void CaptureReserved(int frame, IStatable source) return; } - var ms = new MemoryStream(); + MemoryStream ms = new(); source.SaveStateBinary(new BinaryWriter(ms)); _reserved.Add(frame, ms.ToArray()); AddStateCache(frame); @@ -370,7 +364,7 @@ public void Capture(int frame, IStatable source, bool force = false) var state2 = _recent.GetState(index2); StateCache.Remove(state2.Frame); - var isReserved = _reserveCallback(state2.Frame); + bool isReserved = _reserveCallback(state2.Frame); // Add to reserved if reserved, or if it matches an "ancient" state consideration if (isReserved || !HasNearByReserved(state2.Frame)) @@ -415,7 +409,7 @@ private bool NeedsGap(int frame) // When starting to fill gaps we won't actually know the true frequency, so fall back to current // Current may very well not be the same as gap, but it's a reasonable behavior to have a current sized gap before seeing filler sized gaps - var frequency = _gapFiller.Count == 0 ? _current.RewindFrequency : _gapFiller.RewindFrequency; + int frequency = _gapFiller.Count == 0 ? _current.RewindFrequency : _gapFiller.RewindFrequency; return !StateCache.Any(sc => sc < frame && sc > frame - frequency); } @@ -481,14 +475,11 @@ public KeyValuePair GetStateClosestToFrame(int frame) return new KeyValuePair(si.Frame, si.Read()); } - public bool HasState(int frame) - { - return StateCache.Contains(frame); - } + public bool HasState(int frame) => StateCache.Contains(frame); private bool InvalidateGaps(int frame) { - for (var i = 0; i < _gapFiller.Count; i++) + for (int i = 0; i < _gapFiller.Count; i++) { var state = _gapFiller.GetState(i); if (state.Frame > frame) @@ -502,7 +493,7 @@ private bool InvalidateGaps(int frame) private bool InvalidateNormal(int frame) { - for (var i = 0; i < _recent.Count; i++) + for (int i = 0; i < _recent.Count; i++) { if (_recent.GetState(i).Frame > frame) { @@ -512,7 +503,7 @@ private bool InvalidateNormal(int frame) } } - for (var i = 0; i < _current.Count; i++) + for (int i = 0; i < _current.Count; i++) { if (_current.GetState(i).Frame > frame) { @@ -525,7 +516,7 @@ private bool InvalidateNormal(int frame) private bool InvalidateReserved(int frame) { - var origCount = _reserved.Count; + int origCount = _reserved.Count; _reserved = _reserved .Where(kvp => kvp.Key <= frame) .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); @@ -537,9 +528,9 @@ public bool InvalidateAfter(int frame) { if (frame < 0) throw new ArgumentOutOfRangeException(nameof(frame)); - var b1 = InvalidateNormal(frame); - var b2 = InvalidateGaps(frame); - var b3 = InvalidateReserved(frame); + bool b1 = InvalidateNormal(frame); + bool b2 = InvalidateGaps(frame); + bool b3 = InvalidateReserved(frame); StateCache.RemoveAfter(frame); return b1 || b2 || b3; } @@ -549,21 +540,21 @@ public static ZwinderStateManager Create(BinaryReader br, ZwinderStateManagerSet // Initial format had no version number, but I think it's a safe bet no valid file has buffer size 2^56 or more so this should work. int version = br.ReadByte(); - var current = ZwinderBuffer.Create(br, settings.Current(), version == 0); - var recent = ZwinderBuffer.Create(br, settings.Recent()); - var gaps = ZwinderBuffer.Create(br, settings.GapFiller()); + ZwinderBuffer current = ZwinderBuffer.Create(br, settings.Current(), version == 0); + ZwinderBuffer recent = ZwinderBuffer.Create(br, settings.Recent()); + ZwinderBuffer gaps = ZwinderBuffer.Create(br, settings.GapFiller()); if (version == 0) settings.AncientStateInterval = br.ReadInt32(); - var ret = new ZwinderStateManager(current, recent, gaps, reserveCallback, settings); + ZwinderStateManager ret = new(current, recent, gaps, reserveCallback, settings); - var ancientCount = br.ReadInt32(); - for (var i = 0; i < ancientCount; i++) + int ancientCount = br.ReadInt32(); + for (int i = 0; i < ancientCount; i++) { - var key = br.ReadInt32(); - var length = br.ReadInt32(); - var data = br.ReadBytes(length); + int key = br.ReadInt32(); + int length = br.ReadInt32(); + byte[] data = br.ReadBytes(length); ret._reserved.Add(key, data); } diff --git a/src/BizHawk.Client.Common/rewind/ZeldaWinder.cs b/src/BizHawk.Client.Common/rewind/ZeldaWinder.cs index af6b8db8b24..aba69ec7c47 100644 --- a/src/BizHawk.Client.Common/rewind/ZeldaWinder.cs +++ b/src/BizHawk.Client.Common/rewind/ZeldaWinder.cs @@ -30,10 +30,7 @@ private void Sync() _activeTask?.Wait(); _activeTask = null; } - private void Work(Action work) - { - _activeTask = Task.Run(work); - } + private void Work(Action work) => _activeTask = Task.Run(work); public ZeldaWinder(IStatable stateSource, IRewindSettings settings) { @@ -66,15 +63,9 @@ public bool Active private set { Sync(); _active = value; } } - public void Suspend() - { - Active = false; - } + public void Suspend() => Active = false; - public void Resume() - { - Active = true; - } + public void Resume() => Active = true; public void Dispose() { @@ -97,7 +88,7 @@ public unsafe void Capture(int frame) return; if (_masterFrame == -1) { - var sss = new SaveStateStream(this); + SaveStateStream sss = new(this); _stateSource.SaveStateBinary(new BinaryWriter(sss)); (_master, _scratch) = (_scratch, _master); _masterLength = (int)sss.Position; @@ -109,7 +100,7 @@ public unsafe void Capture(int frame) return; { - var sss = new SaveStateStream(this); + SaveStateStream sss = new(this); _stateSource.SaveStateBinary(new BinaryWriter(sss)); Work(() => @@ -119,13 +110,13 @@ public unsafe void Capture(int frame) var zeldas = SpanStream.GetOrBuild(underlyingStream_); if (_master.Length < _scratch.Length) { - var replacement = new byte[_scratch.Length]; + byte[] replacement = new byte[_scratch.Length]; Array.Copy(_master, replacement, _master.Length); _master = replacement; } - var lengthHolder = _masterLength; - var lengthHolderSpan = new ReadOnlySpan(&lengthHolder, 4); + int lengthHolder = _masterLength; + ReadOnlySpan lengthHolderSpan = new(&lengthHolder, 4); zeldas.Write(lengthHolderSpan); @@ -200,8 +191,8 @@ public unsafe void Capture(int frame) private unsafe void RefillMaster(ZwinderBuffer.StateInformation state) { - var lengthHolder = 0; - var lengthHolderSpan = new Span(&lengthHolder, 4); + int lengthHolder = 0; + Span lengthHolderSpan = new(&lengthHolder, 4); using var rs = state.GetReadStream(); var zeldas = SpanStream.GetOrBuild(rs); zeldas.Read(lengthHolderSpan); @@ -235,7 +226,7 @@ public bool Rewind(int frameToAvoid) { if (_count > 1) { - var index = _buffer.Count - 1; + int index = _buffer.Count - 1; RefillMaster(_buffer.GetState(index)); _buffer.InvalidateEnd(index); _stateSource.LoadStateBinary(new BinaryReader(new MemoryStream(_master, 0, _masterLength, false))); @@ -262,7 +253,7 @@ public SaveStateStream(ZeldaWinder owner) { _owner = owner; } - private ZeldaWinder _owner; + private readonly ZeldaWinder _owner; private byte[] _dest { get => _owner._scratch; @@ -278,29 +269,26 @@ public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) => throw new IOException(); public override long Seek(long offset, SeekOrigin origin) => throw new IOException(); public override void SetLength(long value) => throw new IOException(); - public override void Write(byte[] buffer, int offset, int count) - { - Write(new ReadOnlySpan(buffer, offset, count)); - } + public override void Write(byte[] buffer, int offset, int count) => Write(new ReadOnlySpan(buffer, offset, count)); private void MaybeResize(int requestedSize) { if (requestedSize > _dest.Length) { - var replacement = new byte[(Math.Max(_dest.Length * 2, requestedSize) + 3) & ~3]; + byte[] replacement = new byte[(Math.Max(_dest.Length * 2, requestedSize) + 3) & ~3]; Array.Copy(_dest, replacement, _dest.Length); _dest = replacement; } } public void Write(ReadOnlySpan buffer) { - var requestedSize = _position + buffer.Length; + int requestedSize = _position + buffer.Length; MaybeResize(requestedSize); buffer.CopyTo(new Span(_dest, _position, buffer.Length)); _position = requestedSize; } public override void WriteByte(byte value) { - var requestedSize = _position + 1; + int requestedSize = _position + 1; MaybeResize(requestedSize); _dest[_position] = value; _position = requestedSize; diff --git a/src/BizHawk.Client.Common/rewind/Zwinder.cs b/src/BizHawk.Client.Common/rewind/Zwinder.cs index 056bd60dcce..79836ba3570 100644 --- a/src/BizHawk.Client.Common/rewind/Zwinder.cs +++ b/src/BizHawk.Client.Common/rewind/Zwinder.cs @@ -64,7 +64,7 @@ public bool Rewind(int frameToAvoid) { if (!Active || Count == 0) return false; - var index = Count - 1; + int index = Count - 1; var state = _buffer.GetState(index); if (state.Frame == frameToAvoid) { @@ -72,7 +72,7 @@ public bool Rewind(int frameToAvoid) { state = _buffer.GetState(index - 1); } - using var br = new BinaryReader(state.GetReadStream()); + using BinaryReader br = new(state.GetReadStream()); _stateSource.LoadStateBinary(br); _buffer.InvalidateEnd(index); } @@ -80,30 +80,18 @@ public bool Rewind(int frameToAvoid) { // The emulator will frame advance without giving us a chance to // re-capture this frame, so we shouldn't invalidate this state just yet. - using var br = new BinaryReader(state.GetReadStream()); + using BinaryReader br = new(state.GetReadStream()); _stateSource.LoadStateBinary(br); } return true; } - public void Suspend() - { - Active = false; - } + public void Suspend() => Active = false; - public void Resume() - { - Active = true; - } + public void Resume() => Active = true; - public void Dispose() - { - _buffer.Dispose(); - } + public void Dispose() => _buffer.Dispose(); - public void Clear() - { - _buffer.InvalidateEnd(0); - } + public void Clear() => _buffer.InvalidateEnd(0); } } diff --git a/src/BizHawk.Client.Common/rewind/ZwinderBuffer.cs b/src/BizHawk.Client.Common/rewind/ZwinderBuffer.cs index 09531bb0ec8..277c7c6319b 100644 --- a/src/BizHawk.Client.Common/rewind/ZwinderBuffer.cs +++ b/src/BizHawk.Client.Common/rewind/ZwinderBuffer.cs @@ -33,7 +33,7 @@ public ZwinderBuffer(IRewindSettings settings) { case IRewindSettings.BackingStoreType.Memory: { - var buffer = new MemoryBlock((ulong)Size); + MemoryBlock buffer = new((ulong)Size); buffer.Protect(buffer.Start, buffer.Size, MemoryBlock.Protection.RW); _disposables.Add(buffer); _backingStore = new MemoryViewStream(true, true, (long)buffer.Start, (long)buffer.Size); @@ -42,8 +42,8 @@ public ZwinderBuffer(IRewindSettings settings) } case IRewindSettings.BackingStoreType.TempFile: { - var filename = TempFileManager.GetTempFilename("ZwinderBuffer"); - var filestream = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite, FileShare.None, 4096, FileOptions.DeleteOnClose); + string filename = TempFileManager.GetTempFilename("ZwinderBuffer"); + FileStream filestream = new(filename, FileMode.Create, FileAccess.ReadWrite, FileShare.None, 4096, FileOptions.DeleteOnClose); filestream.SetLength(Size); _backingStore = filestream; _disposables.Add(filestream); @@ -76,7 +76,7 @@ public void Dispose() _zstd.Dispose(); } - private readonly List _disposables = new List(); + private readonly List _disposables = new(); /// /// Number of states that could be in the state ringbuffer, Mask for the state ringbuffer @@ -150,10 +150,10 @@ private int ComputeIdealRewindInterval() } // assume that the most recent state size is representative of stuff - var sizeRatio = Size / (float)_states[HeadStateIndex].Size; - var frameRatio = _targetFrameLength / sizeRatio; + float sizeRatio = Size / (float)_states[HeadStateIndex].Size; + float frameRatio = _targetFrameLength / sizeRatio; - var idealInterval = (int)Math.Round(frameRatio); + int idealInterval = (int)Math.Round(frameRatio); return Math.Max(idealInterval, 1); } @@ -185,7 +185,7 @@ private bool ShouldCaptureForFrameDiff(int frameDiff) private bool ShouldCapture(int frame) { - var frameDiff = frame - _states[HeadStateIndex].Frame; + int frameDiff = frame - _states[HeadStateIndex].Frame; return ShouldCaptureForFrameDiff(frameDiff); } @@ -194,10 +194,7 @@ private bool ShouldCapture(int frame) /// /// The assumed frame delta. Normally this will be equal to `nextStateFrame - GetState(Count - 1).Frame`. /// Whether Capture(nextStateFrame) would actually capture, assuming the frameDelta matched. - public bool WouldCapture(int frameDelta) - { - return ShouldCaptureForFrameDiff(frameDelta); - } + public bool WouldCapture(int frameDelta) => ShouldCaptureForFrameDiff(frameDelta); /// /// Maybe captures a state, if the conditions are favorable @@ -219,11 +216,11 @@ public void Capture(int frame, Action callback, Action indexInvalid _firstStateIndex = (_firstStateIndex + 1) & STATEMASK; } - var start = (_states[HeadStateIndex].Start + _states[HeadStateIndex].Size) & _sizeMask; - var initialMaxSize = Count > 0 + long start = (_states[HeadStateIndex].Start + _states[HeadStateIndex].Size) & _sizeMask; + long initialMaxSize = Count > 0 ? (_states[_firstStateIndex].Start - start) & _sizeMask : Size; - Func notifySizeReached = () => + long notifySizeReached() { if (Count == 0) throw new IOException("A single state must not be larger than the buffer"); @@ -232,8 +229,8 @@ public void Capture(int frame, Action callback, Action indexInvalid return Count > 0 ? (_states[_firstStateIndex].Start - start) & _sizeMask : Size; - }; - var stream = new SaveStateStream(_backingStore, start, _sizeMask, initialMaxSize, notifySizeReached); + } + SaveStateStream stream = new(_backingStore, start, _sizeMask, initialMaxSize, notifySizeReached); if (_useCompression) { @@ -268,10 +265,7 @@ public class StateInformation public int Frame => _parent._states[_index].Frame; public int Size => _parent._states[_index].Size; private readonly ZwinderBuffer _parent; - public Stream GetReadStream() - { - return _parent.MakeLoadStream(_index); - } + public Stream GetReadStream() => _parent.MakeLoadStream(_index); internal StateInformation(ZwinderBuffer parent, int index) { _index = index; @@ -315,15 +309,15 @@ public void SaveStateBinary(BinaryWriter writer) private void SaveStateBodyBinary(BinaryWriter writer) { writer.Write(Count); - for (var i = _firstStateIndex; i != _nextStateIndex; i = (i + 1) & STATEMASK) + for (int i = _firstStateIndex; i != _nextStateIndex; i = (i + 1) & STATEMASK) { writer.Write(_states[i].Frame); writer.Write(_states[i].Size); } if (Count != 0) { - var startByte = _states[_firstStateIndex].Start; - var endByte = (_states[HeadStateIndex].Start + _states[HeadStateIndex].Size) & _sizeMask; + long startByte = _states[_firstStateIndex].Start; + long endByte = (_states[HeadStateIndex].Start + _states[HeadStateIndex].Size) & _sizeMask; var destStream = SpanStream.GetOrBuild(writer.BaseStream); if (startByte > endByte) { @@ -343,7 +337,7 @@ private void LoadStateBodyBinary(BinaryReader reader) _firstStateIndex = 0; _nextStateIndex = reader.ReadInt32(); long nextByte = 0; - for (var i = 0; i < _nextStateIndex; i++) + for (int i = 0; i < _nextStateIndex; i++) { _states[i].Frame = reader.ReadInt32(); _states[i].Size = reader.ReadInt32(); @@ -364,10 +358,10 @@ public static ZwinderBuffer Create(BinaryReader reader, RewindConfig rewindConfi { byte[] sizeArr = new byte[8]; reader.Read(sizeArr, 1, 7); - var size = BitConverter.ToInt64(sizeArr, 0); - var sizeMask = reader.ReadInt64(); - var targetFrameLength = reader.ReadInt32(); - var useCompression = reader.ReadBoolean(); + long size = BitConverter.ToInt64(sizeArr, 0); + long sizeMask = reader.ReadInt64(); + int targetFrameLength = reader.ReadInt32(); + bool useCompression = reader.ReadBoolean(); ret = new ZwinderBuffer(new RewindConfig { BufferSize = (int)(size >> 20), @@ -440,10 +434,7 @@ public override void Flush() {} public override void SetLength(long value) => throw new IOException(); public int Read(Span buffer) => throw new IOException(); - public override void Write(byte[] buffer, int offset, int count) - { - Write(new ReadOnlySpan(buffer, offset, count)); - } + public override void Write(byte[] buffer, int offset, int count) => Write(new ReadOnlySpan(buffer, offset, count)); public void Write(ReadOnlySpan buffer) { @@ -453,8 +444,8 @@ public void Write(ReadOnlySpan buffer) long n = buffer.Length; if (n > 0) { - var start = (_position + _offset) & _mask; - var end = (start + n) & _mask; + long start = (_position + _offset) & _mask; + long end = (start + n) & _mask; _backingStore.Position = start; if (end < start) { @@ -516,10 +507,7 @@ public override long Position } public override void Flush() {} - public override int Read(byte[] buffer, int offset, int count) - { - return Read(new Span(buffer, offset, count)); - } + public override int Read(byte[] buffer, int offset, int count) => Read(new Span(buffer, offset, count)); public int Read(Span buffer) { @@ -527,8 +515,8 @@ public int Read(Span buffer) int ret = (int)n; if (n > 0) { - var start = (_position + _offset) & _mask; - var end = (start + n) & _mask; + long start = (_position + _offset) & _mask; + long end = (start + n) & _mask; if (end < start) { long m = BufferLength - start; @@ -554,7 +542,7 @@ public override int ReadByte() { if (_position < _size) { - var ret = _backingStore.ReadByte(); + int ret = _backingStore.ReadByte(); if (ret == -1) throw new IOException("Unexpected end of underlying buffer"); _position++; diff --git a/src/BizHawk.Client.Common/savestates/IndexedStateLump.cs b/src/BizHawk.Client.Common/savestates/IndexedStateLump.cs index d5ca7b06a37..e1edfbcb263 100644 --- a/src/BizHawk.Client.Common/savestates/IndexedStateLump.cs +++ b/src/BizHawk.Client.Common/savestates/IndexedStateLump.cs @@ -14,10 +14,7 @@ public IndexedStateLump(BinaryStateLump root) Calc(); } - private void Calc() - { - Name = _root.Name + _idx; - } + private void Calc() => Name = _root.Name + _idx; public void Increment() { diff --git a/src/BizHawk.Client.Common/savestates/SavestateFile.cs b/src/BizHawk.Client.Common/savestates/SavestateFile.cs index 36643397bf8..036823636fc 100644 --- a/src/BizHawk.Client.Common/savestates/SavestateFile.cs +++ b/src/BizHawk.Client.Common/savestates/SavestateFile.cs @@ -45,7 +45,7 @@ public void Create(string filename, SaveStateConfig config) { // the old method of text savestate save is now gone. // a text savestate is just like a binary savestate, but with a different core lump - using var bs = new ZipStateSaver(filename, config.CompressionLevelNormal); + using ZipStateSaver bs = new(filename, config.CompressionLevelNormal); using (new SimpleTime("Save Core")) { @@ -61,7 +61,7 @@ public void Create(string filename, SaveStateConfig config) if (config.SaveScreenshot && _videoProvider != null) { - var buff = _videoProvider.GetVideoBuffer(); + int[] buff = _videoProvider.GetVideoBuffer(); if (buff.Length == 1) { // is a hacky opengl texture ID. can't handle this now! @@ -105,7 +105,7 @@ public void Create(string filename, SaveStateConfig config) bs.PutLump(BinaryStateLump.UserData, tw => { - var data = ConfigService.SaveWithType(_userBag); + string data = ConfigService.SaveWithType(_userBag); tw.WriteLine(data); }); } @@ -119,16 +119,16 @@ public void Create(string filename, SaveStateConfig config) public bool Load(string path, IDialogParent dialogParent) { // try to detect binary first - using var bl = ZipStateLoader.LoadAndDetect(path); + using ZipStateLoader bl = ZipStateLoader.LoadAndDetect(path); if (bl is null) return false; - var succeed = false; + bool succeed = false; if (!VersionInfo.DeveloperBuild) { bl.GetLump(BinaryStateLump.BizVersion, true, tr => succeed = tr.ReadLine() == VersionInfo.GetEmuVersion()); if (!succeed) { - var result = dialogParent.ModalMessageBox2( + bool result = dialogParent.ModalMessageBox2( "This savestate was made with a different version, so it's unlikely to work.\nChoose OK to try loading it anyway.", "Savestate version mismatch", EMsgBoxIcon.Question, @@ -182,7 +182,7 @@ public bool Load(string path, IDialogParent dialogParent) if (!string.IsNullOrWhiteSpace(userData)) { - var bag = (Dictionary)ConfigService.LoadWithType(userData); + Dictionary bag = (Dictionary)ConfigService.LoadWithType(userData); _userBag.Clear(); foreach (var (k, v) in bag) _userBag.Add(k, v); } @@ -206,7 +206,7 @@ private static void PopulateFramebuffer(BinaryReader br, IVideoProvider videoPro } catch { - var buff = videoProvider.GetVideoBuffer(); + int[] buff = videoProvider.GetVideoBuffer(); try { for (int i = 0; i < buff.Length; i++) diff --git a/src/BizHawk.Client.Common/savestates/ZipStateLoader.cs b/src/BizHawk.Client.Common/savestates/ZipStateLoader.cs index 74848e3adf2..79bc07290bb 100644 --- a/src/BizHawk.Client.Common/savestates/ZipStateLoader.cs +++ b/src/BizHawk.Client.Common/savestates/ZipStateLoader.cs @@ -21,10 +21,7 @@ private ZipStateLoader() _zstd = new(); } - public void Dispose() - { - Dispose(true); - } + public void Dispose() => Dispose(true); protected virtual void Dispose(bool disposing) { @@ -48,7 +45,7 @@ private void ReadZipVersion(Stream s, long length) } else { - var sr = new StreamReader(s); + StreamReader sr = new(s); _ver = new Version(1, 0, int.Parse(sr.ReadLine())); } @@ -74,9 +71,9 @@ private void PopulateEntries() private static readonly byte[] Zipheader = { 0x50, 0x4b, 0x03, 0x04 }; public static ZipStateLoader LoadAndDetect(string filename, bool isMovieLoad = false) { - var ret = new ZipStateLoader(); + ZipStateLoader ret = new(); - using (var fs = new FileStream(filename, FileMode.Open, FileAccess.Read)) + using (FileStream fs = new(filename, FileMode.Open, FileAccess.Read)) { byte[] data = new byte[4]; fs.Read(data, 0, 4); diff --git a/src/BizHawk.Client.Common/savestates/ZipStateSaver.cs b/src/BizHawk.Client.Common/savestates/ZipStateSaver.cs index a2b05e9e1c4..f2d849ea368 100644 --- a/src/BizHawk.Client.Common/savestates/ZipStateSaver.cs +++ b/src/BizHawk.Client.Common/savestates/ZipStateSaver.cs @@ -12,13 +12,13 @@ public class ZipStateSaver : IDisposable private static void WriteZipVersion(Stream s) { - using var sw = new StreamWriter(s); + using StreamWriter sw = new(s); sw.WriteLine("2"); // version 1.0.2 } private static void WriteEmuVersion(Stream s) { - using var sw = new StreamWriter(s); + using StreamWriter sw = new(s); sw.WriteLine(VersionInfo.GetEmuVersion()); } @@ -32,16 +32,13 @@ public ZipStateSaver(string path, int compressionLevel) PutLump(BinaryStateLump.BizVersion, WriteEmuVersion, false); } - public void PutLump(BinaryStateLump lump, Action callback, bool zstdCompress = true) - { - _zip.WriteItem(lump.WriteName, callback, zstdCompress); - } + public void PutLump(BinaryStateLump lump, Action callback, bool zstdCompress = true) => _zip.WriteItem(lump.WriteName, callback, zstdCompress); public void PutLump(BinaryStateLump lump, Action callback) { PutLump(lump, s => { - var bw = new BinaryWriter(s); + BinaryWriter bw = new(s); callback(bw); bw.Flush(); }); diff --git a/src/BizHawk.Client.Common/tools/Cheat.cs b/src/BizHawk.Client.Common/tools/Cheat.cs index 40f4b6a83b3..ffacb49d07e 100644 --- a/src/BizHawk.Client.Common/tools/Cheat.cs +++ b/src/BizHawk.Client.Common/tools/Cheat.cs @@ -16,7 +16,7 @@ public enum CompareType } private readonly Watch _watch; - private int? _compare; + private readonly int? _compare; private int _val; private bool _enabled; @@ -59,7 +59,7 @@ public Cheat(Cheat cheat) public delegate void CheatEventHandler(object sender); public event CheatEventHandler Changed; - public static Cheat Separator => new Cheat(SeparatorWatch.Instance, 0, null, false); + public static Cheat Separator => new(SeparatorWatch.Instance, 0, null, false); public bool IsSeparator => _watch.IsSeparator; @@ -123,7 +123,7 @@ public void Enable(bool handleChange = true) { if (!IsSeparator) { - var wasEnabled = _enabled; + bool wasEnabled = _enabled; _enabled = true; if (!wasEnabled && handleChange) { @@ -136,7 +136,7 @@ public void Disable(bool handleChange = true) { if (!IsSeparator) { - var wasEnabled = _enabled; + bool wasEnabled = _enabled; _enabled = false; if (wasEnabled && handleChange) { @@ -214,19 +214,14 @@ private bool ShouldPoke() public bool Contains(long addr) { - switch (_watch.Size) + return _watch.Size switch { - default: - case WatchSize.Separator: - return false; - case WatchSize.Byte: - return _watch.Address == addr; - case WatchSize.Word: - return addr == _watch.Address || addr == _watch.Address + 1; - case WatchSize.DWord: - return addr == _watch.Address || addr == _watch.Address + 1 || - addr == _watch.Address + 2 || addr == _watch.Address + 3; - } + WatchSize.Byte => _watch.Address == addr, + WatchSize.Word => addr == _watch.Address || addr == _watch.Address + 1, + WatchSize.DWord => addr == _watch.Address || addr == _watch.Address + 1 || + addr == _watch.Address + 2 || addr == _watch.Address + 3, + _ => false, + }; } public void PokeValue(int val) @@ -276,10 +271,7 @@ public void SetType(WatchDisplayType type) } } - private void Changes() - { - Changed?.Invoke(this); - } + private void Changes() => Changed?.Invoke(this); public override bool Equals(object obj) { @@ -296,10 +288,7 @@ public override bool Equals(object obj) return base.Equals(obj); } - public override int GetHashCode() - { - return Domain.GetHashCode() + (int)(Address ?? 0); - } + public override int GetHashCode() => Domain.GetHashCode() + (int)(Address ?? 0); public static bool operator ==(Cheat a, Cheat b) { diff --git a/src/BizHawk.Client.Common/tools/CheatList.cs b/src/BizHawk.Client.Common/tools/CheatList.cs index 0d92d13823b..641c54126d6 100644 --- a/src/BizHawk.Client.Common/tools/CheatList.cs +++ b/src/BizHawk.Client.Common/tools/CheatList.cs @@ -27,7 +27,7 @@ public class CheatCollection : ICollection private readonly IDialogParent _dialogParent; private readonly ICheatConfig _config; - private List _cheatList = new List(); + private List _cheatList = new(); private string _defaultFileName = ""; private bool _changes; @@ -75,17 +75,14 @@ public bool Changes IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - public void Pulse() - { - _cheatList.ForEach(cheat => cheat.Pulse()); - } + public void Pulse() => _cheatList.ForEach(cheat => cheat.Pulse()); /// /// Looks for a .cht file that matches the ROM loaded based on the default filename for a given ROM /// public bool AttemptToLoadCheatFile(IMemoryDomains domains) { - var file = new FileInfo(_defaultFileName); + FileInfo file = new(_defaultFileName); return file.Exists && Load(domains, file.FullName, false); } @@ -133,7 +130,7 @@ public void Add(Cheat cheat) public void AddRange(IEnumerable cheats) { - var toAdd = cheats.Where(c => !_cheatList.Contains(c)).ToList(); + List toAdd = cheats.Where(c => !_cheatList.Contains(c)).ToList(); if (toAdd.Count is 0) return; const int WARN_WHEN_ADDING_MORE_THAN = 200; if (toAdd.Count > WARN_WHEN_ADDING_MORE_THAN && !_dialogParent.ModalMessageBox2($"Adding {toAdd.Count} freezes/cheats at once is probably a bad idea. Do it anyway?")) return; @@ -172,7 +169,7 @@ public bool Exchange(Cheat oldCheat, Cheat newCheat) public bool Remove(Cheat cheat) { - var result = _cheatList.Remove(cheat); + bool result = _cheatList.Remove(cheat); if (result) { Changes = true; @@ -185,10 +182,7 @@ public bool Remove(Cheat cheat) public bool Contains(Cheat cheat) => _cheatList.Exists(c => c == cheat); - public void CopyTo(Cheat[] array, int arrayIndex) - { - _cheatList.CopyTo(array, arrayIndex); - } + public void CopyTo(Cheat[] array, int arrayIndex) => _cheatList.CopyTo(array, arrayIndex); public void RemoveRange(IEnumerable cheats) { @@ -262,13 +256,13 @@ public bool SaveFile(string path) { try { - var file = new FileInfo(path); + FileInfo file = new(path); if (file.Directory != null && !file.Directory.Exists) { file.Directory.Create(); } - var sb = new StringBuilder(); + StringBuilder sb = new(); foreach (var cheat in _cheatList) { @@ -315,7 +309,7 @@ public bool SaveFile(string path) public bool Load(IMemoryDomains domains, string path, bool append) { - var file = new FileInfo(path); + FileInfo file = new(path); if (file.Exists == false) { return false; @@ -347,7 +341,7 @@ public bool Load(IMemoryDomains domains, string path, bool append) int? compare; var size = WatchSize.Byte; var type = WatchDisplayType.Hex; - var bigEndian = false; + bool bigEndian = false; var comparisonType = Cheat.CompareType.None; if (s.Length < 6) @@ -355,9 +349,9 @@ public bool Load(IMemoryDomains domains, string path, bool append) continue; } - var vals = s.Split('\t'); - var address = int.Parse(vals[0], NumberStyles.HexNumber); - var value = int.Parse(vals[1], NumberStyles.HexNumber); + string[] vals = s.Split('\t'); + int address = int.Parse(vals[0], NumberStyles.HexNumber); + int value = int.Parse(vals[1], NumberStyles.HexNumber); if (vals[2] == "N") { @@ -369,8 +363,8 @@ public bool Load(IMemoryDomains domains, string path, bool append) } var domain = domains[vals[3]]; - var enabled = vals[4] == "1"; - var name = vals[5]; + bool enabled = vals[4] == "1"; + string name = vals[5]; // For backwards compatibility, don't assume these values exist if (vals.Length > 6) @@ -389,7 +383,7 @@ public bool Load(IMemoryDomains domains, string path, bool append) } } - var watch = Watch.GenerateWatch( + Watch watch = Watch.GenerateWatch( domain, address, size, @@ -412,7 +406,7 @@ public bool Load(IMemoryDomains domains, string path, bool append) } private static readonly RigidMultiPredicateSort ColumnSorts - = new RigidMultiPredicateSort(new Dictionary> + = new(new Dictionary> { [NameColumn] = c => c.Name, [AddressColumn] = c => c.Address ?? 0L, @@ -428,10 +422,7 @@ private static readonly RigidMultiPredicateSort ColumnSorts public void Sort(string column, bool reverse) => _cheatList = ColumnSorts.AppliedTo(_cheatList, column, firstIsDesc: reverse); - public void SetDefaultFileName(string defaultFileName) - { - _defaultFileName = defaultFileName; - } + public void SetDefaultFileName(string defaultFileName) => _defaultFileName = defaultFileName; private void CheatChanged(object sender) { diff --git a/src/BizHawk.Client.Common/tools/RamSearchEngine/Extensions.cs b/src/BizHawk.Client.Common/tools/RamSearchEngine/Extensions.cs index fce21969733..7a54e2c1439 100644 --- a/src/BizHawk.Client.Common/tools/RamSearchEngine/Extensions.cs +++ b/src/BizHawk.Client.Common/tools/RamSearchEngine/Extensions.cs @@ -9,7 +9,7 @@ internal static class Extensions { public static float ToFloat(this long val) { - var bytes = BitConverter.GetBytes((int)val); + byte[] bytes = BitConverter.GetBytes((int)val); return BitConverter.ToSingle(bytes, 0); } diff --git a/src/BizHawk.Client.Common/tools/RamSearchEngine/IMiniWatch.cs b/src/BizHawk.Client.Common/tools/RamSearchEngine/IMiniWatch.cs index 1bd7b869669..dd4d8503ccb 100644 --- a/src/BizHawk.Client.Common/tools/RamSearchEngine/IMiniWatch.cs +++ b/src/BizHawk.Client.Common/tools/RamSearchEngine/IMiniWatch.cs @@ -27,20 +27,11 @@ public MiniByteWatch(MemoryDomain domain, long addr) public long Previous => _previous; - public bool IsValid(MemoryDomain domain) - { - return IsValid(Address, domain); - } + public bool IsValid(MemoryDomain domain) => IsValid(Address, domain); - public void SetPreviousToCurrent(MemoryDomain domain, bool bigEndian) - { - _previous = GetByte(Address, domain); - } + public void SetPreviousToCurrent(MemoryDomain domain, bool bigEndian) => _previous = GetByte(Address, domain); - public static bool IsValid(long address, MemoryDomain domain) - { - return address < domain.Size; - } + public static bool IsValid(long address, MemoryDomain domain) => address < domain.Size; public static byte GetByte(long address, MemoryDomain domain) { @@ -66,20 +57,11 @@ public MiniWordWatch(MemoryDomain domain, long addr, bool bigEndian) public long Previous => _previous; - public void SetPreviousToCurrent(MemoryDomain domain, bool bigEndian) - { - _previous = GetUshort(Address, domain, bigEndian); - } + public void SetPreviousToCurrent(MemoryDomain domain, bool bigEndian) => _previous = GetUshort(Address, domain, bigEndian); - public bool IsValid(MemoryDomain domain) - { - return IsValid(Address, domain); - } + public bool IsValid(MemoryDomain domain) => IsValid(Address, domain); - public static bool IsValid(long address, MemoryDomain domain) - { - return address < (domain.Size - 1); - } + public static bool IsValid(long address, MemoryDomain domain) => address < (domain.Size - 1); public static ushort GetUshort(long address, MemoryDomain domain, bool bigEndian) { @@ -105,20 +87,11 @@ public MiniDWordWatch(MemoryDomain domain, long addr, bool bigEndian) public long Previous => _previous; - public void SetPreviousToCurrent(MemoryDomain domain, bool bigEndian) - { - _previous = GetUint(Address, domain, bigEndian); - } + public void SetPreviousToCurrent(MemoryDomain domain, bool bigEndian) => _previous = GetUint(Address, domain, bigEndian); - public bool IsValid(MemoryDomain domain) - { - return IsValid(Address, domain); - } + public bool IsValid(MemoryDomain domain) => IsValid(Address, domain); - public static bool IsValid(long address, MemoryDomain domain) - { - return address < (domain.Size - 3); - } + public static bool IsValid(long address, MemoryDomain domain) => address < (domain.Size - 3); public static uint GetUint(long address, MemoryDomain domain, bool bigEndian) { diff --git a/src/BizHawk.Client.Common/tools/RamSearchEngine/IMiniWatchDetails.cs b/src/BizHawk.Client.Common/tools/RamSearchEngine/IMiniWatchDetails.cs index 024eae8d78a..a55c675e682 100644 --- a/src/BizHawk.Client.Common/tools/RamSearchEngine/IMiniWatchDetails.cs +++ b/src/BizHawk.Client.Common/tools/RamSearchEngine/IMiniWatchDetails.cs @@ -28,10 +28,7 @@ public MiniByteWatchDetailed(MemoryDomain domain, long addr) SetPreviousToCurrent(domain, false); } - public void SetPreviousToCurrent(MemoryDomain domain, bool bigEndian) - { - _previous = _prevFrame = MiniByteWatch.GetByte(Address, domain); - } + public void SetPreviousToCurrent(MemoryDomain domain, bool bigEndian) => _previous = _prevFrame = MiniByteWatch.GetByte(Address, domain); public long Previous => _previous; @@ -39,7 +36,7 @@ public void SetPreviousToCurrent(MemoryDomain domain, bool bigEndian) public void Update(PreviousType type, MemoryDomain domain, bool bigEndian) { - var value = MiniByteWatch.GetByte(Address, domain); + byte value = MiniByteWatch.GetByte(Address, domain); if (value != _prevFrame) { @@ -84,10 +81,7 @@ public MiniWordWatchDetailed(MemoryDomain domain, long addr, bool bigEndian) SetPreviousToCurrent(domain, bigEndian); } - public void SetPreviousToCurrent(MemoryDomain domain, bool bigEndian) - { - _previous = _prevFrame = MiniWordWatch.GetUshort(Address, domain, bigEndian); - } + public void SetPreviousToCurrent(MemoryDomain domain, bool bigEndian) => _previous = _prevFrame = MiniWordWatch.GetUshort(Address, domain, bigEndian); public long Previous => _previous; @@ -95,7 +89,7 @@ public void SetPreviousToCurrent(MemoryDomain domain, bool bigEndian) public void Update(PreviousType type, MemoryDomain domain, bool bigEndian) { - var value = MiniWordWatch.GetUshort(Address, domain, bigEndian); + ushort value = MiniWordWatch.GetUshort(Address, domain, bigEndian); if (value != Previous) { ChangeCount++; @@ -139,10 +133,7 @@ public MiniDWordWatchDetailed(MemoryDomain domain, long addr, bool bigEndian) SetPreviousToCurrent(domain, bigEndian); } - public void SetPreviousToCurrent(MemoryDomain domain, bool bigEndian) - { - _previous = _prevFrame = MiniDWordWatch.GetUint(Address, domain, bigEndian); - } + public void SetPreviousToCurrent(MemoryDomain domain, bool bigEndian) => _previous = _prevFrame = MiniDWordWatch.GetUint(Address, domain, bigEndian); public long Previous => (int)_previous; @@ -150,7 +141,7 @@ public void SetPreviousToCurrent(MemoryDomain domain, bool bigEndian) public void Update(PreviousType type, MemoryDomain domain, bool bigEndian) { - var value = MiniDWordWatch.GetUint(Address, domain, bigEndian); + uint value = MiniDWordWatch.GetUint(Address, domain, bigEndian); if (value != Previous) { ChangeCount++; diff --git a/src/BizHawk.Client.Common/tools/RamSearchEngine/RamSearchEngine.cs b/src/BizHawk.Client.Common/tools/RamSearchEngine/RamSearchEngine.cs index ec6ace12eaf..313789b9d42 100644 --- a/src/BizHawk.Client.Common/tools/RamSearchEngine/RamSearchEngine.cs +++ b/src/BizHawk.Client.Common/tools/RamSearchEngine/RamSearchEngine.cs @@ -16,7 +16,7 @@ public class RamSearchEngine private IMiniWatch[] _watchList = Array.Empty(); private readonly SearchEngineSettings _settings; - private readonly UndoHistory> _history = new UndoHistory>(true, new List()); //TODO use IList instead of IEnumerable and stop calling `.ToArray()` (i.e. cloning) on reads and writes? + private readonly UndoHistory> _history = new(true, new List()); //TODO use IList instead of IEnumerable and stop calling `.ToArray()` (i.e. cloning) on reads and writes? private bool _isSorted = true; // Tracks whether or not the array is sorted by address, if it is, binary search can be used for finding watches public RamSearchEngine(SearchEngineSettings settings, IMemoryDomains memoryDomains) @@ -203,7 +203,7 @@ public void Update() { using (_settings.Domain.EnterExit()) { - foreach (IMiniWatchDetails watch in _watchList) + foreach (var watch in _watchList.Cast()) { watch.Update(_settings.PreviousType, _settings.Domain, _settings.BigEndian); } @@ -226,10 +226,7 @@ public void SetPreviousType(PreviousType type) _settings.PreviousType = type; } - public void SetPreviousToCurrent() - { - Array.ForEach(_watchList, w => w.SetPreviousToCurrent(_settings.Domain, _settings.BigEndian)); - } + public void SetPreviousToCurrent() => Array.ForEach(_watchList, w => w.SetPreviousToCurrent(_settings.Domain, _settings.BigEndian)); public void ClearChangeCounts() { @@ -268,10 +265,7 @@ public void RemoveRange(IEnumerable indices) _watchList = _watchList.Except(removeList).ToArray(); } - public void RemoveAddressRange(IEnumerable addresses) - { - _watchList = _watchList.Where(w => !addresses.Contains(w.Address)).ToArray(); - } + public void RemoveAddressRange(IEnumerable addresses) => _watchList = _watchList.Where(w => !addresses.Contains(w.Address)).ToArray(); public void AddRange(IEnumerable addresses, bool append) { @@ -384,7 +378,7 @@ private IEnumerable ComparePrevious(IEnumerable watchLis case ComparisonOperator.DifferentBy: if (DifferentBy.HasValue) { - var differentBy = DifferentBy.Value; + int differentBy = DifferentBy.Value; if (_settings.Type == WatchDisplayType.Float) { return watchList.Where(w => (GetValue(w.Address).ToFloat() + differentBy).HawkFloatEquality(w.Previous.ToFloat()) @@ -410,7 +404,7 @@ private IEnumerable CompareSpecificValue(IEnumerable wat { if (CompareValue.HasValue) { - var compareValue = CompareValue.Value; + long compareValue = CompareValue.Value; switch (Operator) { default: @@ -443,7 +437,7 @@ private IEnumerable CompareSpecificValue(IEnumerable wat case ComparisonOperator.DifferentBy: if (DifferentBy.HasValue) { - var differentBy = DifferentBy.Value; + int differentBy = DifferentBy.Value; if (_settings.Type == WatchDisplayType.Float) { return watchList.Where(w => (GetValue(w.Address).ToFloat() + differentBy).HawkFloatEquality(compareValue) @@ -466,7 +460,7 @@ private IEnumerable CompareSpecificAddress(IEnumerable w { if (CompareValue.HasValue) { - var compareValue = CompareValue.Value; + long compareValue = CompareValue.Value; switch (Operator) { default: @@ -500,7 +494,7 @@ private IEnumerable CompareChanges(IEnumerable watchList { if (_settings.IsDetailed() && CompareValue.HasValue) { - var compareValue = CompareValue.Value; + long compareValue = CompareValue.Value; switch (Operator) { default: @@ -548,7 +542,7 @@ private IEnumerable CompareDifference(IEnumerable watchL { if (CompareValue.HasValue) { - var compareValue = CompareValue.Value; + long compareValue = CompareValue.Value; switch (Operator) { default: @@ -579,7 +573,7 @@ private IEnumerable CompareDifference(IEnumerable watchL case ComparisonOperator.DifferentBy: if (DifferentBy.HasValue) { - var differentBy = DifferentBy.Value; + int differentBy = DifferentBy.Value; if (_settings.Type == WatchDisplayType.Float) { return watchList.Where(w => (GetValue(w.Address).ToFloat() - w.Previous.ToFloat() + differentBy).HawkFloatEquality(compareValue) diff --git a/src/BizHawk.Client.Common/tools/Watch/ByteWatch.cs b/src/BizHawk.Client.Common/tools/Watch/ByteWatch.cs index d9189bcd200..430d0f71ad8 100644 --- a/src/BizHawk.Client.Common/tools/Watch/ByteWatch.cs +++ b/src/BizHawk.Client.Common/tools/Watch/ByteWatch.cs @@ -51,18 +51,12 @@ public static IEnumerable ValidTypes /// Get a list a that can be used for this /// /// An enumeration that contains all valid - public override IEnumerable AvailableTypes() - { - return ValidTypes; - } + public override IEnumerable AvailableTypes() => ValidTypes; /// /// Reset the previous value; set it to the current one /// - public override void ResetPrevious() - { - _previous = GetByte(); - } + public override void ResetPrevious() => _previous = GetByte(); /// /// Try to sets the value into the @@ -102,7 +96,7 @@ public override void Update(PreviousType previousType) case PreviousType.Original: return; case PreviousType.LastChange: - var temp = _value; + byte temp = _value; _value = GetByte(); if (_value != temp) { diff --git a/src/BizHawk.Client.Common/tools/Watch/DWordWatch.cs b/src/BizHawk.Client.Common/tools/Watch/DWordWatch.cs index 6c9645ba5e2..ae4945adcce 100644 --- a/src/BizHawk.Client.Common/tools/Watch/DWordWatch.cs +++ b/src/BizHawk.Client.Common/tools/Watch/DWordWatch.cs @@ -54,18 +54,12 @@ public static IEnumerable ValidTypes /// Get a list of that can be used for a /// /// An enumeration that contains all valid - public override IEnumerable AvailableTypes() - { - return ValidTypes; - } + public override IEnumerable AvailableTypes() => ValidTypes; /// /// Reset the previous value; set it to the current one /// - public override void ResetPrevious() - { - _previous = GetWord(); - } + public override void ResetPrevious() => _previous = GetWord(); /// /// Try to sets the value into the @@ -107,7 +101,7 @@ public override void Update(PreviousType previousType) case PreviousType.Original: return; case PreviousType.LastChange: - var temp = _value; + uint temp = _value; _value = GetDWord(); if (_value != temp) { @@ -133,15 +127,15 @@ public string FormatValue(uint val) { string FormatFloat() { - var bytes = BitConverter.GetBytes(val); - var _float = BitConverter.ToSingle(bytes, 0); + byte[] bytes = BitConverter.GetBytes(val); + float _float = BitConverter.ToSingle(bytes, 0); return _float.ToString(NumberFormatInfo.InvariantInfo); } string FormatBinary() { - var str = Convert.ToString(val, 2).PadLeft(32, '0'); - for (var i = 28; i > 0; i -= 4) + string str = Convert.ToString(val, 2).PadLeft(32, '0'); + for (int i = 28; i > 0; i -= 4) { str = str.Insert(i, " "); } diff --git a/src/BizHawk.Client.Common/tools/Watch/SeparatorWatch.cs b/src/BizHawk.Client.Common/tools/Watch/SeparatorWatch.cs index 81de10f3817..45737ee060c 100644 --- a/src/BizHawk.Client.Common/tools/Watch/SeparatorWatch.cs +++ b/src/BizHawk.Client.Common/tools/Watch/SeparatorWatch.cs @@ -19,7 +19,7 @@ internal SeparatorWatch() /// /// Gets the separator instance /// - public static SeparatorWatch Instance => new SeparatorWatch(); + public static SeparatorWatch Instance => new(); public static SeparatorWatch NewSeparatorWatch(string description) { @@ -74,10 +74,7 @@ public override string ToDisplayString() /// Transforms the current instance into a string /// /// A representation of the current - public override string ToString() - { - return $"0\tS\t_\t1\t\t{Notes.Trim('\r', '\n')}"; - } + public override string ToString() => $"0\tS\t_\t1\t\t{Notes.Trim('\r', '\n')}"; /// /// Ignore that stuff diff --git a/src/BizHawk.Client.Common/tools/Watch/Watch.cs b/src/BizHawk.Client.Common/tools/Watch/Watch.cs index a823371abb1..faf5b2e0abb 100644 --- a/src/BizHawk.Client.Common/tools/Watch/Watch.cs +++ b/src/BizHawk.Client.Common/tools/Watch/Watch.cs @@ -96,12 +96,12 @@ public static Watch FromString(string line, IMemoryDomains domains) return null; } - if (long.TryParse(parts[0], NumberStyles.HexNumber, CultureInfo.CurrentCulture, out var address)) + if (long.TryParse(parts[0], NumberStyles.HexNumber, CultureInfo.CurrentCulture, out long address)) { - WatchSize size = SizeFromChar(parts[1][0]); - WatchDisplayType type = DisplayTypeFromChar(parts[2][0]); + var size = SizeFromChar(parts[1][0]); + var type = DisplayTypeFromChar(parts[2][0]); bool bigEndian = parts[3] != "0"; - MemoryDomain domain = domains[parts[4]]; + var domain = domains[parts[4]]; string notes = parts[5].Trim('\r', '\n'); return GenerateWatch( @@ -313,10 +313,7 @@ protected void PokeDWord(uint val) /// /// Sets the number of changes to 0 /// - public void ClearChangeCount() - { - ChangeCount = 0; - } + public void ClearChangeCount() => ChangeCount = 0; /// /// Determines if this is equals to another @@ -399,29 +396,20 @@ public override bool Equals(object obj) /// Hash the current watch and gets a unique value /// /// that can serves as a unique representation of current Watch - public override int GetHashCode() - { - return Domain.GetHashCode() + (int)Address; - } + public override int GetHashCode() => Domain.GetHashCode() + (int)Address; /// /// Determines if the specified can be /// used for the current /// /// you want to check - public bool IsDisplayTypeAvailable(WatchDisplayType type) - { - return AvailableTypes().Any(d => d == type); - } + public bool IsDisplayTypeAvailable(WatchDisplayType type) => AvailableTypes().Any(d => d == type); /// /// Transforms the current instance into a string /// /// A representation of the current - public override string ToString() - { - return $"{(Domain == null && Address == 0 ? "0" : Address.ToHexString((Domain?.Size ?? 0xFF - 1).NumHexDigits()))}\t{SizeAsChar}\t{TypeAsChar}\t{Convert.ToInt32(BigEndian)}\t{Domain?.Name}\t{Notes.Trim('\r', '\n')}"; - } + public override string ToString() => $"{(Domain == null && Address == 0 ? "0" : Address.ToHexString((Domain?.Size ?? 0xFF - 1).NumHexDigits()))}\t{SizeAsChar}\t{TypeAsChar}\t{Convert.ToInt32(BigEndian)}\t{Domain?.Name}\t{Notes.Trim('\r', '\n')}"; /// /// Transform the current instance into a displayable (short representation) string diff --git a/src/BizHawk.Client.Common/tools/Watch/WatchList/WatchList.cs b/src/BizHawk.Client.Common/tools/Watch/WatchList/WatchList.cs index ee418b04619..e99121cbb3b 100644 --- a/src/BizHawk.Client.Common/tools/Watch/WatchList/WatchList.cs +++ b/src/BizHawk.Client.Common/tools/Watch/WatchList/WatchList.cs @@ -28,7 +28,7 @@ public sealed partial class WatchList private static readonly Dictionary> WatchComparers; - private readonly List _watchList = new List(0); + private readonly List _watchList = new(0); private readonly string _systemId; private IMemoryDomains _memoryDomains; @@ -89,10 +89,7 @@ public void Clear() /// specified /// /// The object to - public bool Contains(Watch watch) - { - return _watchList.Contains(watch); - } + public bool Contains(Watch watch) => _watchList.Contains(watch); /// /// Copies the elements of the current @@ -100,10 +97,7 @@ public bool Contains(Watch watch) /// /// The one-dimension that will serve as destination to copy /// Zero-based index where the copy should starts - public void CopyTo(Watch[] array, int arrayIndex) - { - _watchList.CopyTo(array, arrayIndex); - } + public void CopyTo(Watch[] array, int arrayIndex) => _watchList.CopyTo(array, arrayIndex); /// /// Removes the first of specified @@ -127,10 +121,7 @@ public bool Remove(Watch watch) /// /// to look for /// Zero-base position if has been found; otherwise -1 - public int IndexOf(Watch watch) - { - return _watchList.IndexOf(watch); - } + public int IndexOf(Watch watch) => _watchList.IndexOf(watch); /// /// Insert a at the specified index @@ -172,19 +163,13 @@ public void RemoveAt(int index) /// Returns an enumerator that iterates through the collection /// /// An for the current collection - public IEnumerator GetEnumerator() - { - return _watchList.GetEnumerator(); - } + public IEnumerator GetEnumerator() => _watchList.GetEnumerator(); /// /// Returns an enumerator that iterates through the collection /// /// An for the current collection - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); /// /// Add an existing collection of into the current one @@ -214,8 +199,8 @@ public void ClearChangeCounts() /// Defines the order of the sort. Ascending (true) or descending (false) public void OrderWatches(string column, bool reverse) { - var separatorIndices = new List(); - for (var i = 0; i < _watchList.Count; i++) + List separatorIndices = new(); + for (int i = 0; i < _watchList.Count; i++) { if (_watchList[i].IsSeparator) { @@ -311,7 +296,7 @@ public Watch this[int index] public bool Load(string path, bool append) { - var result = LoadFile(path, append); + bool result = LoadFile(path, append); if (result) { @@ -345,9 +330,9 @@ public bool Save() return false; } - using (var sw = new StreamWriter(CurrentFileName)) + using (StreamWriter sw = new(CurrentFileName)) { - var sb = new StringBuilder(); + StringBuilder sb = new(); sb.Append("SystemID ").AppendLine(_systemId); foreach (var watch in _watchList) @@ -375,13 +360,13 @@ public bool SaveAs(FileInfo file) private bool LoadFile(string path, bool append) { - var file = new FileInfo(path); + FileInfo file = new(path); if (file.Exists == false) { return false; } - var isBizHawkWatch = true; // Hack to support .wch files from other emulators + bool isBizHawkWatch = true; // Hack to support .wch files from other emulators using var sr = file.OpenText(); string line; @@ -410,7 +395,7 @@ private bool LoadFile(string path, bool append) continue; } - var numColumns = line.Count(c => c == '\t'); + int numColumns = line.Count(c => c == '\t'); int startIndex; if (numColumns == 5) { @@ -434,7 +419,7 @@ private bool LoadFile(string path, bool append) int addr; var memDomain = _memoryDomains.MainMemory; - var temp = line.Substring(0, line.IndexOf('\t')); + string temp = line.Substring(0, line.IndexOf('\t')); try { addr = int.Parse(temp, NumberStyles.HexNumber); @@ -463,7 +448,7 @@ private bool LoadFile(string path, bool append) continue; } - var bigEndian = startIndex != 0; + bool bigEndian = startIndex != 0; if (isBizHawkWatch) { @@ -474,7 +459,7 @@ private bool LoadFile(string path, bool append) } startIndex = line.IndexOf('\t') + 1; - var notes = line.Substring(startIndex, line.Length - startIndex); + string notes = line.Substring(startIndex, line.Length - startIndex); _watchList.Add( Watch.GenerateWatch( diff --git a/src/BizHawk.Client.Common/tools/Watch/WatchList/WatchValueComparer.cs b/src/BizHawk.Client.Common/tools/Watch/WatchList/WatchValueComparer.cs index eeb48e269f7..4d61cf45a05 100644 --- a/src/BizHawk.Client.Common/tools/Watch/WatchList/WatchValueComparer.cs +++ b/src/BizHawk.Client.Common/tools/Watch/WatchList/WatchValueComparer.cs @@ -26,13 +26,13 @@ private sealed class WatchValueComparer /// 0 for equality, 1 if x comes first; -1 if y comes first public int Compare(Watch x, Watch y) { - var xValue = x.Type is not WatchDisplayType.Signed + int xValue = x.Type is not WatchDisplayType.Signed ? x.Value - : int.TryParse(x.ValueString, out var i) ? i : default; + : int.TryParse(x.ValueString, out int i) ? i : default; - var yValue = y.Type is not WatchDisplayType.Signed + int yValue = y.Type is not WatchDisplayType.Signed ? y.Value - : int.TryParse(y.ValueString, out var i1) ? i1 : default; + : int.TryParse(y.ValueString, out int i1) ? i1 : default; if (Equals(x, y)) { diff --git a/src/BizHawk.Client.Common/tools/Watch/WordWatch.cs b/src/BizHawk.Client.Common/tools/Watch/WordWatch.cs index 4317a4436fb..babd857c547 100644 --- a/src/BizHawk.Client.Common/tools/Watch/WordWatch.cs +++ b/src/BizHawk.Client.Common/tools/Watch/WordWatch.cs @@ -57,10 +57,7 @@ public static IEnumerable ValidTypes /// /// Reset the previous value; set it to the current one /// - public override void ResetPrevious() - { - _previous = GetWord(); - } + public override void ResetPrevious() => _previous = GetWord(); /// /// Try to sets the value into the @@ -101,7 +98,7 @@ public override void Update(PreviousType previousType) case PreviousType.Original: return; case PreviousType.LastChange: - var temp = _value; + ushort temp = _value; _value = GetWord(); if (_value != temp) diff --git a/src/BizHawk.Client.DiscoHawk/About.cs b/src/BizHawk.Client.DiscoHawk/About.cs index 38c7a0708a4..df1706e452b 100644 --- a/src/BizHawk.Client.DiscoHawk/About.cs +++ b/src/BizHawk.Client.DiscoHawk/About.cs @@ -11,14 +11,8 @@ public About() lblVersion.Text = $"v{System.Reflection.Assembly.GetExecutingAssembly().GetName().Version}"; } - private void richTextBox1_LinkClicked(object sender, LinkClickedEventArgs e) - { - System.Diagnostics.Process.Start(e.LinkText); - } + private void richTextBox1_LinkClicked(object sender, LinkClickedEventArgs e) => System.Diagnostics.Process.Start(e.LinkText); - private void button1_Click(object sender, EventArgs e) - { - Close(); - } + private void button1_Click(object sender, EventArgs e) => Close(); } } diff --git a/src/BizHawk.Client.DiscoHawk/MainDiscoForm.cs b/src/BizHawk.Client.DiscoHawk/MainDiscoForm.cs index dfad5822a5b..b3367116cd6 100644 --- a/src/BizHawk.Client.DiscoHawk/MainDiscoForm.cs +++ b/src/BizHawk.Client.DiscoHawk/MainDiscoForm.cs @@ -24,15 +24,9 @@ public MainDiscoForm() else Console.WriteLine("couldn't load .ico EmbeddedResource?"); } - private void MainDiscoForm_Load(object sender, EventArgs e) - { - lvCompareTargets.Columns[0].Width = lvCompareTargets.ClientSize.Width; - } + private void MainDiscoForm_Load(object sender, EventArgs e) => lvCompareTargets.Columns[0].Width = lvCompareTargets.ClientSize.Width; - private void ExitButton_Click(object sender, EventArgs e) - { - Close(); - } + private void ExitButton_Click(object sender, EventArgs e) => Close(); private void lblMagicDragArea_DragDrop(object sender, DragEventArgs e) { @@ -40,9 +34,9 @@ private void lblMagicDragArea_DragDrop(object sender, DragEventArgs e) Cursor = Cursors.WaitCursor; try { - foreach (var file in ValidateDrop(e.Data)) + foreach (string file in ValidateDrop(e.Data)) { - var success = DiscoHawkLogic.HawkAndWriteFile( + bool success = DiscoHawkLogic.HawkAndWriteFile( inputPath: file, errorCallback: err => MessageBox.Show(err, "Error loading disc")); if (!success) break; @@ -97,12 +91,12 @@ private void LblMagicDragArea_DragEnter(object sender, DragEventArgs e) private static List ValidateDrop(IDataObject ido) { - var ret = new List(); - var files = (string[])ido.GetData(DataFormats.FileDrop); + List ret = new(); + string[] files = (string[])ido.GetData(DataFormats.FileDrop); if (files == null) return new(); - foreach (var str in files) + foreach (string str in files) { - var ext = Path.GetExtension(str) ?? string.Empty; + string ext = Path.GetExtension(str) ?? string.Empty; if (!Disc.IsValidExtension(ext)) { return new(); @@ -118,9 +112,9 @@ private void LblMp3ExtractMagicArea_DragDrop(object sender, DragEventArgs e) { var files = ValidateDrop(e.Data); if (files.Count == 0) return; - foreach (var file in files) + foreach (string file in files) { - using var disc = Disc.LoadAutomagic(file); + using Disc disc = Disc.LoadAutomagic(file); var (path, filename, _) = file.SplitPathToDirFileAndExt(); static bool? PromptForOverwrite(string mp3Path) => MessageBox.Show( @@ -136,9 +130,6 @@ private void LblMp3ExtractMagicArea_DragDrop(object sender, DragEventArgs e) } } - private void BtnAbout_Click(object sender, EventArgs e) - { - new About().ShowDialog(); - } + private void BtnAbout_Click(object sender, EventArgs e) => new About().ShowDialog(); } } diff --git a/src/BizHawk.Client.DiscoHawk/Program.cs b/src/BizHawk.Client.DiscoHawk/Program.cs index e48e94a96b8..0fa3e816c0f 100644 --- a/src/BizHawk.Client.DiscoHawk/Program.cs +++ b/src/BizHawk.Client.DiscoHawk/Program.cs @@ -32,7 +32,7 @@ static Program() // otherwise, some people will have crashes at boot-up due to .net security disliking MOTW. // some people are getting MOTW through a combination of browser used to download BizHawk, and program used to dearchive it static void RemoveMOTW(string path) => DeleteFileW($"{path}:Zone.Identifier"); - var todo = new Queue(new[] { new DirectoryInfo(dllDir) }); + Queue todo = new(new[] { new DirectoryInfo(dllDir) }); while (todo.Count != 0) { var di = todo.Dequeue(); @@ -43,10 +43,7 @@ static Program() } [STAThread] - private static void Main(string[] args) - { - SubMain(args); - } + private static void Main(string[] args) => SubMain(args); // NoInlining should keep this code from getting jammed into Main() which would create dependencies on types which haven't been setup by the resolver yet... or something like that [DllImport("user32.dll", SetLastError = true)] @@ -60,8 +57,8 @@ private static void SubMain(string[] args) // WELL, OBVIOUSLY IT DOES SOMETIMES. I DON'T REMEMBER THE DETAILS OR WHY WE HAD TO DO THIS SHIT // BUT THE FUNCTION WE NEED DOESN'T EXIST UNTIL WINDOWS 7, CONVENIENTLY // SO CHECK FOR IT - IntPtr lib = OSTC.LinkedLibManager.LoadOrThrow("user32.dll"); - IntPtr proc = OSTC.LinkedLibManager.GetProcAddrOrZero(lib, "ChangeWindowMessageFilterEx"); + var lib = OSTC.LinkedLibManager.LoadOrThrow("user32.dll"); + var proc = OSTC.LinkedLibManager.GetProcAddrOrZero(lib, "ChangeWindowMessageFilterEx"); if (proc != IntPtr.Zero) { ChangeWindowMessageFilter(WM_DROPFILES, ChangeWindowMessageFilterFlags.Add); @@ -73,7 +70,7 @@ private static void SubMain(string[] args) if (args.Length == 0) { - using var dialog = new MainDiscoForm(); + using MainDiscoForm dialog = new(); dialog.ShowDialog(); } else @@ -82,17 +79,14 @@ private static void SubMain(string[] args) args, results => { - using var cr = new ComparisonResults { textBox1 = { Text = results } }; + using ComparisonResults cr = new() { textBox1 = { Text = results } }; cr.ShowDialog(); }); } } - public static string GetExeDirectoryAbsolute() - { - return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); - } + public static string GetExeDirectoryAbsolute() => Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { diff --git a/src/BizHawk.Client.EmuHawk/AVOut/AVSync.cs b/src/BizHawk.Client.EmuHawk/AVOut/AVSync.cs index 51a509095d1..55aee8e6a5f 100644 --- a/src/BizHawk.Client.EmuHawk/AVOut/AVSync.cs +++ b/src/BizHawk.Client.EmuHawk/AVOut/AVSync.cs @@ -192,16 +192,10 @@ public abstract class AVStretcher : VwWrap, IVideoWriter } /// always - public new virtual void AddFrame(IVideoProvider source) - { - throw new InvalidOperationException("Must call AddAV()!"); - } + public new virtual void AddFrame(IVideoProvider source) => throw new InvalidOperationException("Must call AddAV()!"); /// always - public new virtual void AddSamples(short[] samples) - { - throw new InvalidOperationException("Must call AddAV()!"); - } + public new virtual void AddSamples(short[] samples) => throw new InvalidOperationException("Must call AddAV()!"); } public abstract class VwWrap : IVideoWriter @@ -212,74 +206,32 @@ public abstract class VwWrap : IVideoWriter public bool UsesVideo => W.UsesVideo; - public void SetVideoCodecToken(IDisposable token) - { - W.SetVideoCodecToken(token); - } + public void SetVideoCodecToken(IDisposable token) => W.SetVideoCodecToken(token); - public void SetDefaultVideoCodecToken(Config config) - { - W.SetDefaultVideoCodecToken(config); - } + public void SetDefaultVideoCodecToken(Config config) => W.SetDefaultVideoCodecToken(config); - public void OpenFile(string baseName) - { - W.OpenFile(baseName); - } + public void OpenFile(string baseName) => W.OpenFile(baseName); - public void CloseFile() - { - W.CloseFile(); - } + public void CloseFile() => W.CloseFile(); - public void SetFrame(int frame) - { - W.SetFrame(frame); - } + public void SetFrame(int frame) => W.SetFrame(frame); - public void AddFrame(IVideoProvider source) - { - W.AddFrame(source); - } + public void AddFrame(IVideoProvider source) => W.AddFrame(source); - public void AddSamples(short[] samples) - { - W.AddSamples(samples); - } + public void AddSamples(short[] samples) => W.AddSamples(samples); - public IDisposable AcquireVideoCodecToken(Config config) - { - return W.AcquireVideoCodecToken(config); - } + public IDisposable AcquireVideoCodecToken(Config config) => W.AcquireVideoCodecToken(config); - public void SetMovieParameters(int fpsNum, int fpsDen) - { - W.SetMovieParameters(fpsNum, fpsDen); - } + public void SetMovieParameters(int fpsNum, int fpsDen) => W.SetMovieParameters(fpsNum, fpsDen); - public void SetVideoParameters(int width, int height) - { - W.SetVideoParameters(width, height); - } + public void SetVideoParameters(int width, int height) => W.SetVideoParameters(width, height); - public void SetAudioParameters(int sampleRate, int channels, int bits) - { - W.SetAudioParameters(sampleRate, channels, bits); - } + public void SetAudioParameters(int sampleRate, int channels, int bits) => W.SetAudioParameters(sampleRate, channels, bits); - public void SetMetaData(string gameName, string authors, ulong lengthMs, ulong rerecords) - { - W.SetMetaData(gameName, authors, lengthMs, rerecords); - } + public void SetMetaData(string gameName, string authors, ulong lengthMs, ulong rerecords) => W.SetMetaData(gameName, authors, lengthMs, rerecords); - public string DesiredExtension() - { - return W.DesiredExtension(); - } + public string DesiredExtension() => W.DesiredExtension(); - public void Dispose() - { - W.Dispose(); - } + public void Dispose() => W.Dispose(); } } diff --git a/src/BizHawk.Client.EmuHawk/AVOut/AviWriter.cs b/src/BizHawk.Client.EmuHawk/AVOut/AviWriter.cs index 326d52405d6..205e7041830 100644 --- a/src/BizHawk.Client.EmuHawk/AVOut/AviWriter.cs +++ b/src/BizHawk.Client.EmuHawk/AVOut/AviWriter.cs @@ -34,10 +34,7 @@ public void SetFrame(int frame) private bool IsOpen => _nameProvider != null; - public void Dispose() - { - _currSegment?.Dispose(); - } + public void Dispose() => _currSegment?.Dispose(); /// sets the codec token to be used for video compression /// does not inherit @@ -69,10 +66,7 @@ public static IEnumerator CreateBasicNameProvider(string template) /// opens an avi file for recording with names based on the supplied template. /// set a video codec token first. /// - public void OpenFile(string baseName) - { - OpenFile(CreateBasicNameProvider(baseName)); - } + public void OpenFile(string baseName) => OpenFile(CreateBasicNameProvider(baseName)); // thread communication // synchronized queue with custom messages @@ -133,10 +127,7 @@ public VideoCopy(IVideoProvider c) VsyncDenominator = c.VsyncDenominator; } - public int[] GetVideoBuffer() - { - return _vb; - } + public int[] GetVideoBuffer() => _vb; } /// opens an avi file for recording, with being used to name files @@ -268,7 +259,7 @@ private void Segment() /// public IDisposable AcquireVideoCodecToken(Config config) { - var tempParams = new Parameters + Parameters tempParams = new() { height = 256, width = 256, @@ -278,7 +269,7 @@ public IDisposable AcquireVideoCodecToken(Config config) a_samplerate = 44100, a_channels = 2 }; - var temp = new AviWriterSegment(); + AviWriterSegment temp = new(); string tempfile = Path.GetTempFileName(); File.Delete(tempfile); tempfile = Path.ChangeExtension(tempfile, "avi"); @@ -346,7 +337,7 @@ public void PopulateWAVEFORMATEX(ref AVIWriterImports.WAVEFORMATEX wfex) public int fps, fps_scale; } - private readonly Parameters _parameters = new Parameters(); + private readonly Parameters _parameters = new(); /// @@ -436,7 +427,7 @@ private static string Decode_mmioFOURCC(int code) public static CodecToken CreateFromAVICOMPRESSOPTIONS(ref AVIWriterImports.AVICOMPRESSOPTIONS opts) { - var ret = new CodecToken + CodecToken ret = new() { _comprOptions = opts, codec = Decode_mmioFOURCC(opts.fccHandler), @@ -486,8 +477,8 @@ public void AllocateToAVICOMPRESSOPTIONS(ref AVIWriterImports.AVICOMPRESSOPTIONS private byte[] SerializeToByteArray() { - var m = new MemoryStream(); - var b = new BinaryWriter(m); + MemoryStream m = new(); + BinaryWriter b = new(m); b.Write(_comprOptions.fccType); b.Write(_comprOptions.fccHandler); @@ -508,10 +499,10 @@ private byte[] SerializeToByteArray() private static CodecToken DeSerializeFromByteArray(byte[] data) { - var m = new MemoryStream(data, false); - var b = new BinaryReader(m); + MemoryStream m = new(data, false); + BinaryReader b = new(m); - AVIWriterImports.AVICOMPRESSOPTIONS comprOptions = new AVIWriterImports.AVICOMPRESSOPTIONS(); + AVIWriterImports.AVICOMPRESSOPTIONS comprOptions = new(); byte[] format; byte[] parms; @@ -544,7 +535,7 @@ private static CodecToken DeSerializeFromByteArray(byte[] data) b.Close(); } - var ret = new CodecToken + CodecToken ret = new() { _comprOptions = comprOptions, Format = format, @@ -554,15 +545,9 @@ private static CodecToken DeSerializeFromByteArray(byte[] data) return ret; } - public string Serialize() - { - return Convert.ToBase64String(SerializeToByteArray()); - } + public string Serialize() => Convert.ToBase64String(SerializeToByteArray()); - public static CodecToken DeSerialize(string s) - { - return DeSerializeFromByteArray(Convert.FromBase64String(s)); - } + public static CodecToken DeSerialize(string s) => DeSerializeFromByteArray(Convert.FromBase64String(s)); } /// @@ -584,10 +569,7 @@ public AviWriterSegment() { } - public void Dispose() - { - CloseFile(); - } + public void Dispose() => CloseFile(); private CodecToken _currVideoCodecToken; private bool _isOpen; @@ -630,10 +612,7 @@ private class OutputStatus private OutputStatus _outStatus; - public long GetLengthApproximation() - { - return _outStatus.video_bytes + _outStatus.audio_bytes; - } + public long GetLengthApproximation() => _outStatus.video_bytes + _outStatus.audio_bytes; private static bool FAILED(int hr) => hr < 0; @@ -641,9 +620,9 @@ private static int AVISaveOptions(IntPtr stream, ref AVIWriterImports.AVICOMPRES { fixed (AVIWriterImports.AVICOMPRESSOPTIONS* _popts = &opts) { - IntPtr* pStream = &stream; - AVIWriterImports.AVICOMPRESSOPTIONS* popts = _popts; - AVIWriterImports.AVICOMPRESSOPTIONS** ppopts = &popts; + var pStream = &stream; + var popts = _popts; + var ppopts = &popts; return AVIWriterImports.AVISaveOptions(owner, 0, 1, pStream, ppopts); } } @@ -677,8 +656,8 @@ static int mmioFOURCC(string str) => ( } // initialize the video stream - AVIWriterImports.AVISTREAMINFOW vidstream_header = new AVIWriterImports.AVISTREAMINFOW(); - AVIWriterImports.BITMAPINFOHEADER bmih = new AVIWriterImports.BITMAPINFOHEADER(); + AVIWriterImports.AVISTREAMINFOW vidstream_header = new(); + AVIWriterImports.BITMAPINFOHEADER bmih = new(); parameters.PopulateBITMAPINFOHEADER24(ref bmih); vidstream_header.fccType = mmioFOURCC("vids"); vidstream_header.dwRate = parameters.fps; @@ -691,8 +670,8 @@ static int mmioFOURCC(string str) => ( } // initialize audio stream - AVIWriterImports.AVISTREAMINFOW audstream_header = new AVIWriterImports.AVISTREAMINFOW(); - AVIWriterImports.WAVEFORMATEX wfex = new AVIWriterImports.WAVEFORMATEX(); + AVIWriterImports.AVISTREAMINFOW audstream_header = new(); + AVIWriterImports.WAVEFORMATEX wfex = new(); parameters.PopulateWAVEFORMATEX(ref wfex); audstream_header.fccType = mmioFOURCC("auds"); audstream_header.dwQuality = -1; @@ -726,7 +705,7 @@ public IDisposable AcquireVideoCodecToken(IntPtr hwnd, CodecToken lastCodecToken } // encoder params - AVIWriterImports.AVICOMPRESSOPTIONS comprOptions = new AVIWriterImports.AVICOMPRESSOPTIONS(); + AVIWriterImports.AVICOMPRESSOPTIONS comprOptions = new(); _currVideoCodecToken?.AllocateToAVICOMPRESSOPTIONS(ref comprOptions); bool result = AVISaveOptions(_pAviRawVideoStream, ref comprOptions, hwnd) != 0; @@ -759,7 +738,7 @@ public void OpenStreams() } // open compressed video stream - AVIWriterImports.AVICOMPRESSOPTIONS opts = new AVIWriterImports.AVICOMPRESSOPTIONS(); + AVIWriterImports.AVICOMPRESSOPTIONS opts = new(); _currVideoCodecToken.AllocateToAVICOMPRESSOPTIONS(ref opts); bool failed = FAILED(AVIWriterImports.AVIMakeCompressedStream(out _pAviCompressedVideoStream, _pAviRawVideoStream, ref opts, IntPtr.Zero)); CodecToken.DeallocateAVICOMPRESSOPTIONS(ref opts); @@ -771,7 +750,7 @@ public void OpenStreams() } // set the compressed video stream input format - AVIWriterImports.BITMAPINFOHEADER bmih = new AVIWriterImports.BITMAPINFOHEADER(); + AVIWriterImports.BITMAPINFOHEADER bmih = new(); if (_bit32) { _parameters.PopulateBITMAPINFOHEADER32(ref bmih); @@ -789,7 +768,7 @@ public void OpenStreams() } // set audio stream input format - AVIWriterImports.WAVEFORMATEX wfex = new AVIWriterImports.WAVEFORMATEX(); + AVIWriterImports.WAVEFORMATEX wfex = new(); _parameters.PopulateWAVEFORMATEX(ref wfex); if (FAILED(AVIWriterImports.AVIStreamSetFormat(_pAviRawAudioStream, 0, ref wfex, Marshal.SizeOf(wfex)))) { @@ -873,7 +852,7 @@ private void FlushBufferedAudio() { int todo = _outStatus.audio_buffered_shorts; int todo_realsamples = todo / 2; - IntPtr buf = GetStaticGlobalBuf(todo * 2); + var buf = GetStaticGlobalBuf(todo * 2); short* sptr = (short*)buf.ToPointer(); for (int i = 0; i < todo; i++) @@ -882,7 +861,7 @@ private void FlushBufferedAudio() } // (TODO - inefficient- build directly in a buffer) - _ = AVIWriterImports.AVIStreamWrite(_pAviRawAudioStream, _outStatus.audio_samples, todo_realsamples, buf, todo_realsamples * 4, 0, IntPtr.Zero, out var bytes_written); + _ = AVIWriterImports.AVIStreamWrite(_pAviRawAudioStream, _outStatus.audio_samples, todo_realsamples, buf, todo_realsamples * 4, 0, IntPtr.Zero, out int bytes_written); _outStatus.audio_samples += todo_realsamples; _outStatus.audio_bytes += bytes_written; _outStatus.audio_buffered_shorts = 0; @@ -905,7 +884,7 @@ public void AddFrame(IVideoProvider source) if (!_bit32) { - IntPtr buf = GetStaticGlobalBuf(todo); + var buf = GetStaticGlobalBuf(todo); // TODO - would using a byte* be faster? int[] buffer = source.GetVideoBuffer(); @@ -930,7 +909,7 @@ public void AddFrame(IVideoProvider source) bp += pitch_add; } - int ret = AVIWriterImports.AVIStreamWrite(_pAviCompressedVideoStream, _outStatus.video_frames, 1, new IntPtr(bytes_ptr), todo, AVIIF_KEYFRAME, IntPtr.Zero, out var bytes_written); + int ret = AVIWriterImports.AVIStreamWrite(_pAviCompressedVideoStream, _outStatus.video_frames, 1, new IntPtr(bytes_ptr), todo, AVIIF_KEYFRAME, IntPtr.Zero, out int bytes_written); _outStatus.video_bytes += bytes_written; _outStatus.video_frames++; } @@ -938,7 +917,7 @@ public void AddFrame(IVideoProvider source) } else // 32 bit { - IntPtr buf = GetStaticGlobalBuf(todo * 4); + var buf = GetStaticGlobalBuf(todo * 4); int[] buffer = source.GetVideoBuffer(); fixed (int* buffer_ptr = &buffer[0]) { @@ -961,7 +940,7 @@ public void AddFrame(IVideoProvider source) idx -= w * 2; } - int ret = AVIWriterImports.AVIStreamWrite(_pAviCompressedVideoStream, _outStatus.video_frames, 1, new IntPtr(bytes_ptr), todo * 3, AVIIF_KEYFRAME, IntPtr.Zero, out var bytes_written); + int ret = AVIWriterImports.AVIStreamWrite(_pAviCompressedVideoStream, _outStatus.video_frames, 1, new IntPtr(bytes_ptr), todo * 3, AVIIF_KEYFRAME, IntPtr.Zero, out int bytes_written); _outStatus.video_bytes += bytes_written; _outStatus.video_frames++; } @@ -973,14 +952,11 @@ public void AddFrame(IVideoProvider source) /// no default codec token in config public void SetDefaultVideoCodecToken(Config config) { - var ct = CodecToken.DeSerialize(config.AviCodecToken); + CodecToken ct = CodecToken.DeSerialize(config.AviCodecToken); _currVideoCodecToken = ct ?? throw new Exception($"No default {nameof(config.AviCodecToken)} in config!"); } - public string DesiredExtension() - { - return "avi"; - } + public string DesiredExtension() => "avi"; public bool UsesAudio => _parameters.has_audio; diff --git a/src/BizHawk.Client.EmuHawk/AVOut/FFmpegDownloaderForm.cs b/src/BizHawk.Client.EmuHawk/AVOut/FFmpegDownloaderForm.cs index c08b8e24957..cc1db0d280e 100644 --- a/src/BizHawk.Client.EmuHawk/AVOut/FFmpegDownloaderForm.cs +++ b/src/BizHawk.Client.EmuHawk/AVOut/FFmpegDownloaderForm.cs @@ -28,46 +28,41 @@ public FFmpegDownloaderForm() private bool succeeded = false; private bool failed = false; - private void ThreadProc() - { - Download(); - } + private void ThreadProc() => Download(); private void Download() { //the temp file is owned by this thread - var fn = TempFileManager.GetTempFilename("ffmpeg_download", ".7z", false); + string fn = TempFileManager.GetTempFilename("ffmpeg_download", ".7z", false); try { - using (var evt = new ManualResetEvent(false)) + using (ManualResetEvent evt = new(false)) { - using (var client = new System.Net.WebClient()) + using System.Net.WebClient client = new(); + System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; + client.DownloadFileAsync(new Uri(FFmpegService.Url), fn); + client.DownloadProgressChanged += (object sender, System.Net.DownloadProgressChangedEventArgs e) => { - System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; - client.DownloadFileAsync(new Uri(FFmpegService.Url), fn); - client.DownloadProgressChanged += (object sender, System.Net.DownloadProgressChangedEventArgs e) => - { - pct = e.ProgressPercentage; - }; - client.DownloadFileCompleted += (object sender, System.ComponentModel.AsyncCompletedEventArgs e) => - { - //we don't really need a status. we'll just try to unzip it when it's done - evt.Set(); - }; + pct = e.ProgressPercentage; + }; + client.DownloadFileCompleted += (object sender, System.ComponentModel.AsyncCompletedEventArgs e) => + { + //we don't really need a status. we'll just try to unzip it when it's done + evt.Set(); + }; - for (; ; ) + for (; ; ) + { + if (evt.WaitOne(10)) + break; + + //if the gui thread ordered an exit, cancel the download and wait for it to acknowledge + if (exiting) { - if (evt.WaitOne(10)) - break; - - //if the gui thread ordered an exit, cancel the download and wait for it to acknowledge - if (exiting) - { - client.CancelAsync(); - evt.WaitOne(); - break; - } + client.CancelAsync(); + evt.WaitOne(); + break; } } } @@ -79,24 +74,22 @@ private void Download() return; //try acquiring file - using (var hf = new HawkFile(fn)) + using (HawkFile hf = new(fn)) { - using (var exe = OSTailoredCode.IsUnixHost ? hf.BindArchiveMember("ffmpeg") : hf.BindFirstOf(".exe")) - { - var data = exe!.ReadAllBytes(); + using var exe = OSTailoredCode.IsUnixHost ? hf.BindArchiveMember("ffmpeg") : hf.BindFirstOf(".exe"); + byte[] data = exe!.ReadAllBytes(); - //last chance. exiting, don't dump the new ffmpeg file - if (exiting) - return; + //last chance. exiting, don't dump the new ffmpeg file + if (exiting) + return; - DirectoryInfo parentDir = new(Path.GetDirectoryName(FFmpegService.FFmpegPath)!); - if (!parentDir.Exists) parentDir.Create(); - File.WriteAllBytes(FFmpegService.FFmpegPath, data); - if (OSTailoredCode.IsUnixHost) - { - OSTailoredCode.ConstructSubshell("chmod", $"+x {FFmpegService.FFmpegPath}", checkStdout: false).Start(); - Thread.Sleep(50); // Linux I/O flush idk - } + DirectoryInfo parentDir = new(Path.GetDirectoryName(FFmpegService.FFmpegPath)!); + if (!parentDir.Exists) parentDir.Create(); + File.WriteAllBytes(FFmpegService.FFmpegPath, data); + if (OSTailoredCode.IsUnixHost) + { + OSTailoredCode.ConstructSubshell("chmod", $"+x {FFmpegService.FFmpegPath}", checkStdout: false).Start(); + Thread.Sleep(50); // Linux I/O flush idk } } @@ -123,21 +116,16 @@ private void btnDownload_Click(object sender, EventArgs e) failed = false; succeeded = false; pct = 0; - var t = new Thread(ThreadProc); + Thread t = new(ThreadProc); t.Start(); } - private void btnCancel_Click(object sender, EventArgs e) - { - Close(); - } + private void btnCancel_Click(object sender, EventArgs e) => Close(); - protected override void OnClosed(EventArgs e) - { + protected override void OnClosed(EventArgs e) => //inform the worker thread that it needs to try terminating without doing anything else //(it will linger on in background for a bit til it can service this) exiting = true; - } private void timer1_Tick(object sender, EventArgs e) { @@ -154,10 +142,7 @@ private void timer1_Tick(object sender, EventArgs e) progressBar1.Value = pct; } - private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) - { - System.Diagnostics.Process.Start(FFmpegService.Url); - } + private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) => System.Diagnostics.Process.Start(FFmpegService.Url); } } diff --git a/src/BizHawk.Client.EmuHawk/AVOut/FFmpegWriter.cs b/src/BizHawk.Client.EmuHawk/AVOut/FFmpegWriter.cs index 6b5574a0574..2c77a7a28a5 100644 --- a/src/BizHawk.Client.EmuHawk/AVOut/FFmpegWriter.cs +++ b/src/BizHawk.Client.EmuHawk/AVOut/FFmpegWriter.cs @@ -168,12 +168,12 @@ private string FfmpegGetError() _ffmpeg.CancelErrorRead(); } - var s = new StringBuilder(); + StringBuilder s = new(); s.Append(_commandline); s.Append('\n'); while (_stderr.Count > 0) { - var foo = _stderr.Dequeue(); + string foo = _stderr.Dequeue(); s.Append(foo); } @@ -193,7 +193,7 @@ public void AddFrame(IVideoProvider source) throw new Exception($"unexpected ffmpeg death:\n{FfmpegGetError()}"); } - var video = source.GetVideoBuffer(); + int[] video = source.GetVideoBuffer(); try { _muxer.WriteVideoFrame(video); @@ -212,7 +212,7 @@ public IDisposable AcquireVideoCodecToken(Config config) { if (!FFmpegService.QueryServiceAvailable()) { - using var form = new FFmpegDownloaderForm(); + using FFmpegDownloaderForm form = new(); _dialogParent.ShowDialogWithTempMute(form); if (!FFmpegService.QueryServiceAvailable()) return null; } @@ -311,16 +311,11 @@ public void SetAudioParameters(int sampleRate, int channels, int bits) this._channels = channels; } - public string DesiredExtension() - { + public string DesiredExtension() => // this needs to interface with the codec token - return _token.Extension; - } + _token.Extension; - public void SetDefaultVideoCodecToken(Config config) - { - _token = FFmpegWriterForm.FormatPreset.GetDefaultPreset(config); - } + public void SetDefaultVideoCodecToken(Config config) => _token = FFmpegWriterForm.FormatPreset.GetDefaultPreset(config); public bool UsesAudio => true; diff --git a/src/BizHawk.Client.EmuHawk/AVOut/FFmpegWriterForm.cs b/src/BizHawk.Client.EmuHawk/AVOut/FFmpegWriterForm.cs index b5f4b131fa3..6269dc6a5a2 100644 --- a/src/BizHawk.Client.EmuHawk/AVOut/FFmpegWriterForm.cs +++ b/src/BizHawk.Client.EmuHawk/AVOut/FFmpegWriterForm.cs @@ -81,7 +81,7 @@ public static FormatPreset[] GetPresets(string customCommand) /// public static FormatPreset GetDefaultPreset(Config config) { - FormatPreset[] fps = GetPresets(config.FFmpegCustomCommand); + var fps = GetPresets(config.FFmpegCustomCommand); foreach (var fp in fps) { @@ -98,10 +98,7 @@ public static FormatPreset GetDefaultPreset(Config config) return fps[1]; } - public override string ToString() - { - return Name; - } + public override string ToString() => Name; public void Dispose() { @@ -109,7 +106,7 @@ public void Dispose() public void DeduceFormat(string commandline) { - var splitCommandLine = commandline.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); + string[] splitCommandLine = commandline.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); for (int index = 0; index < splitCommandLine.Length - 1; index++) { if (splitCommandLine[index] == "-f") @@ -146,7 +143,7 @@ private void ListBox1_SelectedIndexChanged(object sender, EventArgs e) { if (listBox1.SelectedIndex != -1) { - var f = (FormatPreset)listBox1.SelectedItem; + FormatPreset f = (FormatPreset)listBox1.SelectedItem; label5.Text = $"Extension: {f.Extension}"; label3.Text = f.Desc; textBox1.Text = f.Commandline; @@ -158,7 +155,7 @@ private void ListBox1_SelectedIndexChanged(object sender, EventArgs e) /// public static FormatPreset DoFFmpegWriterDlg(IWin32Window owner, Config config) { - FFmpegWriterForm dlg = new FFmpegWriterForm(); + FFmpegWriterForm dlg = new(); dlg.listBox1.Items.AddRange(FormatPreset.GetPresets(config.FFmpegCustomCommand).Cast().ToArray()); int i = dlg.listBox1.FindStringExact(config.FFmpegFormat); @@ -167,7 +164,7 @@ public static FormatPreset DoFFmpegWriterDlg(IWin32Window owner, Config config) dlg.listBox1.SelectedIndex = i; } - DialogResult result = dlg.ShowDialog(owner); + var result = dlg.ShowDialog(owner); FormatPreset ret; if (result != DialogResult.OK || dlg.listBox1.SelectedIndex == -1) diff --git a/src/BizHawk.Client.EmuHawk/AVOut/GifWriter.cs b/src/BizHawk.Client.EmuHawk/AVOut/GifWriter.cs index e9e97f70b0a..6c0e3a81aa6 100644 --- a/src/BizHawk.Client.EmuHawk/AVOut/GifWriter.cs +++ b/src/BizHawk.Client.EmuHawk/AVOut/GifWriter.cs @@ -168,13 +168,13 @@ public void AddFrame(IVideoProvider source) return; // skip this frame } - using var bmp = new Bitmap(source.BufferWidth, source.BufferHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb); + using Bitmap bmp = new(source.BufferWidth, source.BufferHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb); var data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); System.Runtime.InteropServices.Marshal.Copy(source.GetVideoBuffer(), 0, data.Scan0, bmp.Width * bmp.Height); bmp.UnlockBits(data); using var qBmp = new OctreeQuantizer(255, 8).Quantize(bmp); - MemoryStream ms = new MemoryStream(); + MemoryStream ms = new(); qBmp.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); byte[] b = ms.GetBuffer(); if (!_firstDone) @@ -200,10 +200,7 @@ public void AddSamples(short[] samples) // ignored } - public IDisposable AcquireVideoCodecToken(Config config) - { - return GifWriterForm.DoTokenForm(_dialogParent.AsWinFormsHandle(), config); - } + public IDisposable AcquireVideoCodecToken(Config config) => GifWriterForm.DoTokenForm(_dialogParent.AsWinFormsHandle(), config); private void CalcDelay() { @@ -249,10 +246,7 @@ public void SetMetaData(string gameName, string authors, ulong lengthMS, ulong r } - public string DesiredExtension() - { - return "gif"; - } + public string DesiredExtension() => "gif"; public void Dispose() { diff --git a/src/BizHawk.Client.EmuHawk/AVOut/GifWriterForm.cs b/src/BizHawk.Client.EmuHawk/AVOut/GifWriterForm.cs index 02ae1da861e..87132af371e 100644 --- a/src/BizHawk.Client.EmuHawk/AVOut/GifWriterForm.cs +++ b/src/BizHawk.Client.EmuHawk/AVOut/GifWriterForm.cs @@ -13,7 +13,7 @@ public GifWriterForm() public static GifWriter.GifToken DoTokenForm(IWin32Window parent, Config config) { - using var dlg = new GifWriterForm + using GifWriterForm dlg = new() { numericUpDown1 = { Value = config.GifWriterFrameskip }, numericUpDown2 = { Value = config.GifWriterDelay } diff --git a/src/BizHawk.Client.EmuHawk/AVOut/IVideoWriter.cs b/src/BizHawk.Client.EmuHawk/AVOut/IVideoWriter.cs index 9d964fd0820..cc16804d202 100644 --- a/src/BizHawk.Client.EmuHawk/AVOut/IVideoWriter.cs +++ b/src/BizHawk.Client.EmuHawk/AVOut/IVideoWriter.cs @@ -142,7 +142,7 @@ public IVideoWriter Create(IDialogParent dialogParent) => (IVideoWriter) ( /// public static class VideoWriterInventory { - private static readonly Dictionary VideoWriters = new Dictionary(); + private static readonly Dictionary VideoWriters = new(); static VideoWriterInventory() { diff --git a/src/BizHawk.Client.EmuHawk/AVOut/ImageSequenceWriter.cs b/src/BizHawk.Client.EmuHawk/AVOut/ImageSequenceWriter.cs index 3139a7b802c..2b5b1d76ea7 100644 --- a/src/BizHawk.Client.EmuHawk/AVOut/ImageSequenceWriter.cs +++ b/src/BizHawk.Client.EmuHawk/AVOut/ImageSequenceWriter.cs @@ -30,10 +30,7 @@ public void SetDefaultVideoCodecToken(Config config) public bool UsesVideo => true; - public void OpenFile(string baseName) - { - _baseName = baseName; - } + public void OpenFile(string baseName) => _baseName = baseName; public void CloseFile() { @@ -47,8 +44,8 @@ public void SetFrame(int frame) public void AddFrame(IVideoProvider source) { var (dir, fileNoExt, ext) = _baseName.SplitPathToDirFileAndExt(); - var name = Path.Combine(dir!, $"{fileNoExt}_{_frame}{ext}"); - BitmapBuffer bb = new BitmapBuffer(source.BufferWidth, source.BufferHeight, source.GetVideoBuffer()); + string name = Path.Combine(dir!, $"{fileNoExt}_{_frame}{ext}"); + BitmapBuffer bb = new(source.BufferWidth, source.BufferHeight, source.GetVideoBuffer()); using var bmp = bb.ToSysdrawingBitmap(); if (ext.ToUpperInvariant() == ".PNG") { @@ -73,10 +70,7 @@ public void Dispose() } } - public IDisposable AcquireVideoCodecToken(Config config) - { - return new CodecToken(); - } + public IDisposable AcquireVideoCodecToken(Config config) => new CodecToken(); public void SetMovieParameters(int fpsNum, int fpsDen) { diff --git a/src/BizHawk.Client.EmuHawk/AVOut/JMDForm.cs b/src/BizHawk.Client.EmuHawk/AVOut/JMDForm.cs index 1a0d961044b..cd137ddc0c1 100644 --- a/src/BizHawk.Client.EmuHawk/AVOut/JMDForm.cs +++ b/src/BizHawk.Client.EmuHawk/AVOut/JMDForm.cs @@ -13,10 +13,7 @@ public JmdForm() InitializeComponent(); } - private void ThreadsBar_Scroll(object sender, EventArgs e) - { - threadTop.Text = $"Number of compression threads: {threadsBar.Value}"; - } + private void ThreadsBar_Scroll(object sender, EventArgs e) => threadTop.Text = $"Number of compression threads: {threadsBar.Value}"; private void CompressionBar_Scroll(object sender, EventArgs e) { @@ -38,7 +35,7 @@ private void CompressionBar_Scroll(object sender, EventArgs e) /// false if user canceled; true if user consented public static bool DoCompressionDlg(ref int threads, ref int compLevel, int tMin, int tMax, int cMin, int cMax, IWin32Window hwnd) { - var j = new JmdForm + JmdForm j = new() { threadsBar = { Minimum = tMin, Maximum = tMax }, compressionBar = { Minimum = cMin, Maximum = cMax } @@ -53,7 +50,7 @@ public static bool DoCompressionDlg(ref int threads, ref int compLevel, int tMin j.compressionLeft.Text = $"{cMin}"; j.compressionRight.Text = $"{cMax}"; - DialogResult d = j.ShowDialog(hwnd); + var d = j.ShowDialog(hwnd); threads = j.threadsBar.Value; compLevel = j.compressionBar.Value; diff --git a/src/BizHawk.Client.EmuHawk/AVOut/JMDWriter.cs b/src/BizHawk.Client.EmuHawk/AVOut/JMDWriter.cs index 4ec8f34b8dd..0d82509bd02 100644 --- a/src/BizHawk.Client.EmuHawk/AVOut/JMDWriter.cs +++ b/src/BizHawk.Client.EmuHawk/AVOut/JMDWriter.cs @@ -25,19 +25,18 @@ public class JmdWriter : IVideoWriter private const int NO_COMPRESSION = 0; private const int BEST_COMPRESSION = 9; private const int DEFAULT_COMPRESSION = -1; + #pragma warning disable IDE0051 private const int BEST_SPEED = 1; + #pragma warning restore IDE0051 private static CompressionLevel GetCompressionLevel(int v) { - switch (v) + return v switch { - case NO_COMPRESSION: - return CompressionLevel.NoCompression; - case BEST_COMPRESSION: - return CompressionLevel.Optimal; - default: - return CompressionLevel.Fastest; - } + NO_COMPRESSION => CompressionLevel.NoCompression, + BEST_COMPRESSION => CompressionLevel.Optimal, + _ => CompressionLevel.Fastest, + }; } /// @@ -224,7 +223,7 @@ public void WriteMetadata(MovieMetaData mmd) WriteBe32(0); // timestamp (same time as previous packet) _f.WriteByte(71); // GameName - var temp = Encoding.UTF8.GetBytes(mmd.GameName); + byte[] temp = Encoding.UTF8.GetBytes(mmd.GameName); WriteVar(temp.Length); _f.Write(temp, 0, temp.Length); @@ -354,7 +353,7 @@ private void WriteActual(JmdPacket j) throw new ArithmeticException("JMD Timestamp problem?"); } - var timeStampOut = j.Timestamp - _timestampOff; + ulong timeStampOut = j.Timestamp - _timestampOff; while (timeStampOut > 0xffffffff) { timeStampOut -= 0xffffffff; @@ -376,7 +375,7 @@ private void WriteActual(JmdPacket j) /// zlibed frame with width and height prepended public void AddVideo(byte[] source) { - var j = new JmdPacket + JmdPacket j = new() { Stream = 0, Subtype = 1,// zlib compressed, other possibility is 0 = uncompressed @@ -417,7 +416,7 @@ public void AddSamples(short[] samples) /// right sample private void DoAudioPacket(short l, short r) { - var j = new JmdPacket + JmdPacket j = new() { Stream = 1, Subtype = 1, // raw PCM audio @@ -543,7 +542,7 @@ public void SetVideoCodecToken(IDisposable token) public IDisposable AcquireVideoCodecToken(Config config) { - var ret = new CodecToken(); + CodecToken ret = new(); // load from config and sanitize int t = Math.Min(Math.Max(config.JmdThreads, 1), 6); @@ -713,7 +712,7 @@ public VideoCopy(IVideoProvider c) /// zlib compressed frame, with width and height prepended private byte[] GzipFrame(VideoCopy v) { - var m = new MemoryStream(); + MemoryStream m = new(); // write frame height and width first m.WriteByte((byte)(v.BufferWidth >> 8)); @@ -721,7 +720,7 @@ private byte[] GzipFrame(VideoCopy v) m.WriteByte((byte)(v.BufferHeight >> 8)); m.WriteByte((byte)(v.BufferHeight & 255)); - var g = new GZipStream(m, GetCompressionLevel(_token.CompressionLevel), true); // leave memory stream open so we can pick its contents + GZipStream g = new(m, GetCompressionLevel(_token.CompressionLevel), true); // leave memory stream open so we can pick its contents g.Write(v.VideoBuffer, 0, v.VideoBuffer.Length); g.Flush(); g.Close(); @@ -789,7 +788,7 @@ public void SetMetaData(string gameName, string authors, ulong lengthMs, ulong r public void SetDefaultVideoCodecToken(Config config) { - CodecToken ct = new CodecToken(); + CodecToken ct = new(); // load from config and sanitize int t = Math.Min(Math.Max(config.JmdThreads, 1), 6); diff --git a/src/BizHawk.Client.EmuHawk/AVOut/NutMuxer.cs b/src/BizHawk.Client.EmuHawk/AVOut/NutMuxer.cs index 66a65e220c4..2b20e1ed375 100644 --- a/src/BizHawk.Client.EmuHawk/AVOut/NutMuxer.cs +++ b/src/BizHawk.Client.EmuHawk/AVOut/NutMuxer.cs @@ -16,7 +16,7 @@ public class NutMuxer public class ReusableBufferPool { - private readonly List _available = new List(); + private readonly List _available = new(); private readonly ICollection _inUse = new HashSet(); private readonly int _capacity; @@ -59,15 +59,9 @@ private T[] GetBufferInternal(int length, bool zerofill, Predicate criteria return candidate; } - public T[] GetBuffer(int length, bool zerofill = false) - { - return GetBufferInternal(length, zerofill, a => a.Length == length); - } + public T[] GetBuffer(int length, bool zerofill = false) => GetBufferInternal(length, zerofill, a => a.Length == length); - public T[] GetBufferAtLeast(int length, bool zerofill = false) - { - return GetBufferInternal(length, zerofill, a => a.Length >= length && a.Length / (float)length <= 2.0f); - } + public T[] GetBufferAtLeast(int length, bool zerofill = false) => GetBufferInternal(length, zerofill, a => a.Length >= length && a.Length / (float)length <= 2.0f); /// is not in use public void ReleaseBuffer(T[] buffer) @@ -128,10 +122,7 @@ private static void WriteVarU(long v, Stream stream) /// /// utf-8 string with length prepended /// - private static void WriteString(string s, Stream stream) - { - WriteBytes(Encoding.UTF8.GetBytes(s), stream); - } + private static void WriteString(string s, Stream stream) => WriteBytes(Encoding.UTF8.GetBytes(s), stream); /// /// arbitrary sequence of bytes with length prepended @@ -187,7 +178,7 @@ private static void WriteBe32(uint v, Stream stream) private static uint NutCRC32(byte[] buf) { uint crc = 0; - foreach (var b in buf) + foreach (byte b in buf) { crc ^= (uint)b << 24; crc = (crc << 4) ^ CrcTable[crc >> 28]; @@ -239,7 +230,7 @@ public NutPacket(StartCode startCode, Stream underlying) public override void Flush() { // first, prep header - var header = new MemoryStream(); + MemoryStream header = new(); WriteBe64((ulong)_startCode, header); WriteVarU(_data.Length + 4, header); // +4 for checksum if (_data.Length > 4092) @@ -247,7 +238,7 @@ public override void Flush() WriteBe32(NutCRC32(header.ToArray()), header); } - var tmp = header.ToArray(); + byte[] tmp = header.ToArray(); _underlying.Write(tmp, 0, tmp.Length); tmp = _data.ToArray(); @@ -265,25 +256,13 @@ public override long Position set => throw new NotImplementedException(); } - public override int Read(byte[] buffer, int offset, int count) - { - throw new NotImplementedException(); - } + public override int Read(byte[] buffer, int offset, int count) => throw new NotImplementedException(); - public override long Seek(long offset, SeekOrigin origin) - { - throw new NotImplementedException(); - } + public override long Seek(long offset, SeekOrigin origin) => throw new NotImplementedException(); - public override void SetLength(long value) - { - throw new NotImplementedException(); - } - - public override void Write(byte[] buffer, int offset, int count) - { - _data.Write(buffer, offset, count); - } + public override void SetLength(long value) => throw new NotImplementedException(); + + public override void Write(byte[] buffer, int offset, int count) => _data.Write(buffer, offset, count); } /// @@ -333,7 +312,7 @@ public void Reduce() // audio packets waiting to be written private readonly Queue _audioQueue; - private readonly ReusableBufferPool _bufferPool = new ReusableBufferPool(12); + private readonly ReusableBufferPool _bufferPool = new(12); /// /// write out the main header @@ -341,10 +320,10 @@ public void Reduce() private void WriteMainHeader() { // note: this file starttag not actually part of main headers - var tmp = Encoding.ASCII.GetBytes("nut/multimedia container\0"); + byte[] tmp = Encoding.ASCII.GetBytes("nut/multimedia container\0"); _output.Write(tmp, 0, tmp.Length); - var header = new NutPacket(NutPacket.StartCode.Main, _output); + NutPacket header = new(NutPacket.StartCode.Main, _output); WriteVarU(3, header); // version WriteVarU(2, header); // stream_count @@ -376,7 +355,7 @@ private void WriteMainHeader() // write out the 0th stream header (video) private void WriteVideoHeader() { - var header = new NutPacket(NutPacket.StartCode.Stream, _output); + NutPacket header = new(NutPacket.StartCode.Stream, _output); WriteVarU(0, header); // stream_id WriteVarU(0, header); // stream_class = video WriteString("BGRA", header); // fourcc = "BGRA" @@ -400,7 +379,7 @@ private void WriteVideoHeader() // write out the 1st stream header (audio) private void WriteAudioHeader() { - var header = new NutPacket(NutPacket.StartCode.Stream, _output); + NutPacket header = new(NutPacket.StartCode.Stream, _output); WriteVarU(1, header); // stream_id WriteVarU(1, header); // stream_class = audio WriteString("\x01\x00\x00\x00", header); // fourcc = 01 00 00 00 @@ -466,16 +445,16 @@ public NutFrame(byte[] payload, int payLoadLen, ulong pts, ulong ptsNum, ulong p _pool = pool; _data = pool.GetBufferAtLeast(payLoadLen + 2048); - var frame = new MemoryStream(_data); + MemoryStream frame = new(_data); // create syncpoint - var sync = new NutPacket(NutPacket.StartCode.Syncpoint, frame); + NutPacket sync = new(NutPacket.StartCode.Syncpoint, frame); WriteVarU(pts * 2 + (ulong)ptsIndex, sync); // global_key_pts WriteVarU(1, sync); // back_ptr_div_16, this is wrong sync.Flush(); - var frameHeader = new MemoryStream(); + MemoryStream frameHeader = new(); frameHeader.WriteByte(0); // frame_code // frame_flags = FLAG_CODED, so: @@ -495,7 +474,7 @@ public NutFrame(byte[] payload, int payLoadLen, ulong pts, ulong ptsNum, ulong p WriteVarU(pts + 256, frameHeader); // coded_pts = pts + 1 << msb_pts_shift WriteVarU(payLoadLen, frameHeader); // data_size_msb - var frameHeaderArr = frameHeader.ToArray(); + byte[] frameHeaderArr = frameHeader.ToArray(); frame.Write(frameHeaderArr, 0, frameHeaderArr.Length); WriteBe32(NutCRC32(frameHeaderArr), frame); // checksum frame.Write(payload, 0, payLoadLen); @@ -508,18 +487,18 @@ public NutFrame(byte[] payload, int payLoadLen, ulong pts, ulong ptsNum, ulong p /// public static bool operator <=(NutFrame lhs, NutFrame rhs) { - BigInteger left = new BigInteger(lhs._pts); + BigInteger left = new(lhs._pts); left = left * lhs._ptsNum * rhs._ptsDen; - BigInteger right = new BigInteger(rhs._pts); + BigInteger right = new(rhs._pts); right = right * rhs._ptsNum * lhs._ptsDen; return left <= right; } public static bool operator >=(NutFrame lhs, NutFrame rhs) { - BigInteger left = new BigInteger(lhs._pts); + BigInteger left = new(lhs._pts); left = left * lhs._ptsNum * rhs._ptsDen; - BigInteger right = new BigInteger(rhs._pts); + BigInteger right = new(rhs._pts); right = right * rhs._ptsNum * lhs._ptsDen; return left >= right; @@ -553,7 +532,7 @@ public void WriteVideoFrame(int[] video) _videoDone = true; } - var f = new NutFrame(data, dataLen, _videoOpts, (ulong) _avParams.FpsDen, (ulong) _avParams.FpsNum, 0, _bufferPool); + NutFrame f = new(data, dataLen, _videoOpts, (ulong) _avParams.FpsDen, (ulong) _avParams.FpsNum, 0, _bufferPool); _bufferPool.ReleaseBuffer(data); _videoOpts++; _videoQueue.Enqueue(f); @@ -587,7 +566,7 @@ public void WriteAudioFrame(short[] samples) _audioDone = true; } - var f = new NutFrame(data, dataLen, _audioPts, 1, (ulong)_avParams.Samplerate, 1, _bufferPool); + NutFrame f = new(data, dataLen, _audioPts, 1, (ulong)_avParams.Samplerate, 1, _bufferPool); _bufferPool.ReleaseBuffer(data); _audioPts += (ulong)samples.Length / (ulong)_avParams.Channels; _audioQueue.Enqueue(f); diff --git a/src/BizHawk.Client.EmuHawk/AVOut/NutWriter.cs b/src/BizHawk.Client.EmuHawk/AVOut/NutWriter.cs index 39c8f463702..58d6822ad78 100644 --- a/src/BizHawk.Client.EmuHawk/AVOut/NutWriter.cs +++ b/src/BizHawk.Client.EmuHawk/AVOut/NutWriter.cs @@ -30,10 +30,7 @@ public void SetVideoCodecToken(IDisposable token) { // ignored } - public IDisposable AcquireVideoCodecToken(Config config) - { - return new NutWriterToken(); - } + public IDisposable AcquireVideoCodecToken(Config config) => new NutWriterToken(); // avParams @@ -64,10 +61,7 @@ private void EndSegment() _current = null; } - public void CloseFile() - { - EndSegment(); - } + public void CloseFile() => EndSegment(); public void AddFrame(IVideoProvider source) { @@ -79,10 +73,7 @@ public void AddFrame(IVideoProvider source) _current.WriteVideoFrame(source.GetVideoBuffer()); } - public void AddSamples(short[] samples) - { - _current.WriteAudioFrame(samples); - } + public void AddSamples(short[] samples) => _current.WriteAudioFrame(samples); public void SetMovieParameters(int fpsNum, int fpsDen) { diff --git a/src/BizHawk.Client.EmuHawk/AVOut/SynclessRecorder.cs b/src/BizHawk.Client.EmuHawk/AVOut/SynclessRecorder.cs index 169924ee1e3..90a5a307267 100644 --- a/src/BizHawk.Client.EmuHawk/AVOut/SynclessRecorder.cs +++ b/src/BizHawk.Client.EmuHawk/AVOut/SynclessRecorder.cs @@ -26,10 +26,7 @@ public void SetDefaultVideoCodecToken(Config config) { } - public void SetFrame(int frame) - { - _mCurrFrame = frame; - } + public void SetFrame(int frame) => _mCurrFrame = frame; private int _mCurrFrame; private string _mBaseDirectory, _mFramesDirectory; @@ -40,9 +37,9 @@ public void OpenFile(string projFile) _mProjectFile = projFile; var (dir, fileNoExt, _) = projFile.SplitPathToDirFileAndExt(); _mBaseDirectory = dir ?? string.Empty; - var framesDirFragment = $"{fileNoExt}_frames"; + string framesDirFragment = $"{fileNoExt}_frames"; _mFramesDirectory = Path.Combine(_mBaseDirectory, framesDirFragment); - var sb = new StringBuilder(); + StringBuilder sb = new(); sb.AppendLine("version=1"); sb.AppendLine($"framesdir={framesDirFragment}"); File.WriteAllText(_mProjectFile, sb.ToString()); @@ -54,7 +51,7 @@ public void CloseFile() public void AddFrame(IVideoProvider source) { - using var bb = new BitmapBuffer(source.BufferWidth, source.BufferHeight, source.GetVideoBuffer()); + using BitmapBuffer bb = new(source.BufferWidth, source.BufferHeight, source.GetVideoBuffer()); string subPath = GetAndCreatePathForFrameNum(_mCurrFrame); string path = $"{subPath}.png"; bb.ToSysdrawingBitmap().Save(path, ImageFormat.Png); @@ -64,7 +61,7 @@ public void AddSamples(short[] samples) { string subPath = GetAndCreatePathForFrameNum(_mCurrFrame); string path = $"{subPath}.wav"; - var wwv = new WavWriterV(); + WavWriterV wwv = new(); wwv.SetAudioParameters(_paramSampleRate, _paramChannels, _paramBits); wwv.OpenFile(path); wwv.AddSamples(samples); @@ -83,10 +80,7 @@ public void Dispose() } } - public IDisposable AcquireVideoCodecToken(Config config) - { - return new DummyDisposable(); - } + public IDisposable AcquireVideoCodecToken(Config config) => new DummyDisposable(); public void SetMovieParameters(int fpsNum, int fpsDen) { @@ -114,6 +108,7 @@ public void SetMetaData(string gameName, string authors, ulong lengthMs, ulong r public string DesiredExtension() => "syncless.txt"; + #pragma warning disable IDE0051 /// /// splits the string into chunks of length s /// @@ -125,7 +120,7 @@ private static List StringChunkSplit(string s, int len) } int numChunks = (s.Length + len - 1) / len; - var output = new List(numChunks); + List output = new(numChunks); for (int i = 0, j = 0; i < numChunks; i++, j += len) { int todo = len; @@ -140,6 +135,7 @@ private static List StringChunkSplit(string s, int len) return output; } + #pragma warning restore IDE0051 private string GetAndCreatePathForFrameNum(int index) { @@ -151,15 +147,14 @@ private string GetAndCreatePathForFrameNum(int index) return path; } - public static string GetPathFragmentForFrameNum(int index) - { + public static string GetPathFragmentForFrameNum(int index) => #if true - return index.ToString(); + index.ToString(); #else // not sure of the original purpose here, but the subfolders it makes don't seem to work right, just return frame number for now var chunks = StringChunkSplit(index.ToString(), 2); string subPath = string.Join("/", chunks); return subPath; #endif - } + } } diff --git a/src/BizHawk.Client.EmuHawk/AVOut/SynclessRecordingTools.cs b/src/BizHawk.Client.EmuHawk/AVOut/SynclessRecordingTools.cs index 8945f95b6eb..2d4c6613697 100644 --- a/src/BizHawk.Client.EmuHawk/AVOut/SynclessRecordingTools.cs +++ b/src/BizHawk.Client.EmuHawk/AVOut/SynclessRecordingTools.cs @@ -17,7 +17,7 @@ public partial class SynclessRecordingTools : Form, IDialogParent private readonly IGameInfo _game; #if AVI_SUPPORT - private readonly List _mFrameInfos = new List(); + private readonly List _mFrameInfos = new(); private string _mFramesDirectory; @@ -37,18 +37,18 @@ public SynclessRecordingTools(Config config, IGameInfo game, IDialogController d #if AVI_SUPPORT public void Run() { - var result = this.ShowFileOpenDialog( + string result = this.ShowFileOpenDialog( initDir: _config.PathEntries.AvAbsolutePath(), initFileName: $"{_game.FilesystemSafeName()}.syncless.txt"); if (result is null) return; _mSynclessConfigFile = result; - + //---- this is pretty crappy: - var lines = File.ReadAllLines(_mSynclessConfigFile); + string[] lines = File.ReadAllLines(_mSynclessConfigFile); string framesDir = ""; - foreach (var line in lines) + foreach (string line in lines) { int idx = line.IndexOf('='); string key = line[..idx]; @@ -65,7 +65,7 @@ public void Run() int frame = 1; // hacky! skip frame 0, because we have a problem with dumping that frame somehow for (;;) { - GetPaths(frame, out var png, out var wav); + GetPaths(frame, out string png, out string wav); if (!File.Exists(png) || !File.Exists(wav)) { break; @@ -108,19 +108,19 @@ private void BtnExport_Click(object sender, EventArgs e) } int width, height; - using(var bmp = new Bitmap(_mFrameInfos[0].PngPath)) + using(Bitmap bmp = new(_mFrameInfos[0].PngPath)) { width = bmp.Width; height = bmp.Height; } - var initFileName = Path.ChangeExtension(_mSynclessConfigFile, ".avi"); - var result = this.ShowFileSaveDialog( + string initFileName = Path.ChangeExtension(_mSynclessConfigFile, ".avi"); + string result = this.ShowFileSaveDialog( initDir: Path.GetDirectoryName(initFileName)!, initFileName: initFileName); if (result is null) return; - using var avw = new AviWriter(this); + using AviWriter avw = new(this); avw.SetAudioParameters(44100, 2, 16); // hacky avw.SetMovieParameters(60, 1); // hacky avw.SetVideoParameters(width, height); @@ -129,17 +129,17 @@ private void BtnExport_Click(object sender, EventArgs e) avw.OpenFile(result); foreach (var fi in _mFrameInfos) { - using (var bb = new BitmapBuffer(fi.PngPath, new BitmapLoadOptions())) + using (BitmapBuffer bb = new(fi.PngPath, new BitmapLoadOptions())) { - var bbvp = new BitmapBufferVideoProvider(bb); + BitmapBufferVideoProvider bbvp = new(bb); avw.AddFrame(bbvp); } // offset = 44 dec - var wavBytes = File.ReadAllBytes(fi.WavPath); - var ms = new MemoryStream(wavBytes) { Position = 44 }; - var br = new BinaryReader(ms); - var sampleData = new List(); + byte[] wavBytes = File.ReadAllBytes(fi.WavPath); + MemoryStream ms = new(wavBytes) { Position = 44 }; + BinaryReader br = new(ms); + List sampleData = new(); while (br.BaseStream.Position != br.BaseStream.Length) { sampleData.Add(br.ReadInt16()); diff --git a/src/BizHawk.Client.EmuHawk/AVOut/VideoWriterChooserForm.cs b/src/BizHawk.Client.EmuHawk/AVOut/VideoWriterChooserForm.cs index 587d21854f3..d4e21ddf8d8 100644 --- a/src/BizHawk.Client.EmuHawk/AVOut/VideoWriterChooserForm.cs +++ b/src/BizHawk.Client.EmuHawk/AVOut/VideoWriterChooserForm.cs @@ -64,7 +64,7 @@ public static IVideoWriter DoVideoWriterChooserDlg( Config config) where T : IMainFormForTools, IDialogParent { - var dlg = new VideoWriterChooserForm(owner, emulator, config) + VideoWriterChooserForm dlg = new(owner, emulator, config) { checkBoxASync = { Checked = config.VideoWriterAudioSyncEffective }, checkBoxPad = { Checked = config.AVWriterPad }, @@ -99,7 +99,7 @@ public static IVideoWriter DoVideoWriterChooserDlg( if (owner.ShowDialogAsChild(dlg).IsOk() && dlg.listBox1.SelectedIndex is not -1) { - var vwi = (VideoWriterInfo)dlg.listBox1.SelectedItem; + VideoWriterInfo vwi = (VideoWriterInfo)dlg.listBox1.SelectedItem; ret = vwi.Create(owner); config.VideoWriter = vwi.Attribs.ShortName; } diff --git a/src/BizHawk.Client.EmuHawk/AVOut/WavWriter.cs b/src/BizHawk.Client.EmuHawk/AVOut/WavWriter.cs index beed6ac85b6..4b1d455a63c 100644 --- a/src/BizHawk.Client.EmuHawk/AVOut/WavWriter.cs +++ b/src/BizHawk.Client.EmuHawk/AVOut/WavWriter.cs @@ -135,25 +135,19 @@ public void WriteSamples(short[] samples) } else { - Stream next = _fileChain.Current; + var next = _fileChain.Current; CloseCurrent(); OpenCurrent(next); } } } - public void Dispose() - { - Close(); - } + public void Dispose() => Close(); /// /// finishes writing /// - public void Close() - { - CloseCurrent(); - } + public void Close() => CloseCurrent(); /// /// checks sampling rate, number of channels for validity @@ -229,11 +223,9 @@ private class WavWriterVToken : IDisposable public void Dispose() { } } - public IDisposable AcquireVideoCodecToken(Config config) - { + public IDisposable AcquireVideoCodecToken(Config config) => // don't care - return new WavWriterVToken(); - } + new WavWriterVToken(); /// is not 16 public void SetAudioParameters(int sampleRate, int channels, int bits) @@ -248,10 +240,7 @@ public void SetMetaData(string gameName, string authors, ulong lengthMs, ulong r // not implemented } - public void Dispose() - { - _wavWriter?.Dispose(); - } + public void Dispose() => _wavWriter?.Dispose(); private WavWriter _wavWriter; private int _sampleRate; @@ -272,10 +261,7 @@ private static IEnumerator CreateStreamIterator(string template) } } - public void OpenFile(string baseName) - { - _wavWriter = new WavWriter(CreateStreamIterator(baseName), _sampleRate, _channels); - } + public void OpenFile(string baseName) => _wavWriter = new WavWriter(CreateStreamIterator(baseName), _sampleRate, _channels); public void CloseFile() { @@ -284,10 +270,7 @@ public void CloseFile() _wavWriter = null; } - public void AddSamples(short[] samples) - { - _wavWriter.WriteSamples(samples); - } + public void AddSamples(short[] samples) => _wavWriter.WriteSamples(samples); public string DesiredExtension() => "wav"; diff --git a/src/BizHawk.Client.EmuHawk/Api/ApiManager.cs b/src/BizHawk.Client.EmuHawk/Api/ApiManager.cs index 3eed6c02135..bff9cfb81ac 100644 --- a/src/BizHawk.Client.EmuHawk/Api/ApiManager.cs +++ b/src/BizHawk.Client.EmuHawk/Api/ApiManager.cs @@ -16,7 +16,7 @@ public static class ApiManager static ApiManager() { - var list = new List<(Type, Type, ConstructorInfo, Type[])>(); + List<(Type, Type, ConstructorInfo, Type[])> list = new(); foreach (var implType in Common.ReflectionCache.Types.Concat(ReflectionCache.Types) .Where(t => /*t.IsClass &&*/t.IsSealed)) // small optimisation; api impl. types are all sealed classes { @@ -44,7 +44,7 @@ private static ApiContainer Register( IEmulator emulator, IGameInfo game) { - var avail = new Dictionary + Dictionary avail = new() { [typeof(Action)] = logCallback, [typeof(IMainFormForApi)] = mainForm, @@ -61,7 +61,7 @@ private static ApiContainer Register( tuple => tuple.InterfaceType, tuple => { - var instance = tuple.Ctor.Invoke(tuple.CtorTypes.Select(t => avail[t]).ToArray()); + object instance = tuple.Ctor.Invoke(tuple.CtorTypes.Select(t => avail[t]).ToArray()); if (!ServiceInjector.UpdateServices(serviceProvider, instance, mayCache: true)) throw new Exception("ApiHawk impl. has required service(s) that can't be fulfilled"); return (IExternalApi) instance; })); diff --git a/src/BizHawk.Client.EmuHawk/ArchiveChooser.cs b/src/BizHawk.Client.EmuHawk/ArchiveChooser.cs index 16cda64e098..1e6a9e09fe9 100644 --- a/src/BizHawk.Client.EmuHawk/ArchiveChooser.cs +++ b/src/BizHawk.Client.EmuHawk/ArchiveChooser.cs @@ -12,7 +12,7 @@ namespace BizHawk.Client.EmuHawk public partial class ArchiveChooser : Form { private readonly IList _archiveItems = new List(); - private readonly ToolTip _errorBalloon = new ToolTip(); + private readonly ToolTip _errorBalloon = new(); private static bool _useRegEx; private static bool _matchWhileTyping = true; @@ -30,11 +30,11 @@ public ArchiveChooser(HawkFile hawkFile) for (int i = 0; i < items.Count; i++) { var item = items[i]; - var lvi = new ListViewItem { Tag = i }; + ListViewItem lvi = new() { Tag = i }; lvi.SubItems.Add(new ListViewItem.ListViewSubItem()); lvi.Text = item.Name; long size = item.Size; - var extension = Path.GetExtension(item.Name); + string extension = Path.GetExtension(item.Name); if (extension != null && size % 1024 == 16 && extension.ToUpperInvariant() == ".NES") size -= 16; lvi.SubItems[1].Text = Util.FormatFileSize(size); @@ -50,7 +50,7 @@ private void InitializeFileView() try { lvMembers.Items.Clear(); - foreach (ListViewItem i in _archiveItems.OrderBy(x => x.Name)) + foreach (var i in _archiveItems.OrderBy(x => x.Name)) { lvMembers.Items.Add(i); } @@ -77,10 +77,7 @@ private void btnOK_Click(object sender, EventArgs e) Close(); } - private void btnCancel_Click(object sender, EventArgs e) - { - DialogResult = DialogResult.Cancel; - } + private void btnCancel_Click(object sender, EventArgs e) => DialogResult = DialogResult.Cancel; private void lvMembers_ItemActivate(object sender, EventArgs e) { @@ -94,20 +91,11 @@ private void ArchiveChooser_Load(object sender, EventArgs e) tbFilter.Select(); } - private void btnSearch_Click(object sender, EventArgs e) - { - StartMatching(tbSearch, DoSearch); - } + private void btnSearch_Click(object sender, EventArgs e) => StartMatching(tbSearch, DoSearch); - private void cbInstantFilter_CheckedChanged(object sender, EventArgs e) - { - _matchWhileTyping = cbInstantFilter.Checked; - } + private void cbInstantFilter_CheckedChanged(object sender, EventArgs e) => _matchWhileTyping = cbInstantFilter.Checked; - private void radRegEx_CheckedChanged(object sender, EventArgs e) - { - _useRegEx = radRegEx.Checked; - } + private void radRegEx_CheckedChanged(object sender, EventArgs e) => _useRegEx = radRegEx.Checked; private void tbFilter_TextChanged(object sender, EventArgs e) { @@ -117,10 +105,7 @@ private void tbFilter_TextChanged(object sender, EventArgs e) } } - private void btnFilter_Click(object sender, EventArgs e) - { - StartMatching(tbFilter, DoFilter); - } + private void btnFilter_Click(object sender, EventArgs e) => StartMatching(tbFilter, DoFilter); private void StartMatching(TextBox tb, Action func) { @@ -182,7 +167,7 @@ private void DoFilter(IMatcher searchMatcher) try { lvMembers.Items.Clear(); - foreach (ListViewItem item in _archiveItems) + foreach (var item in _archiveItems) { if (searchMatcher.Matches(item)) { @@ -222,10 +207,7 @@ public bool Matches(ListViewItem value) private class RegExMatcher : IMatcher { public Regex Matcher { get; set; } - public bool Matches(ListViewItem value) - { - return Matcher.IsMatch(value.Text); - } + public bool Matches(ListViewItem value) => Matcher.IsMatch(value.Text); } private IMatcher CreateMatcher(string searchKey) diff --git a/src/BizHawk.Client.EmuHawk/BizBox.cs b/src/BizHawk.Client.EmuHawk/BizBox.cs index d26cb5f6686..60775ca895f 100644 --- a/src/BizHawk.Client.EmuHawk/BizBox.cs +++ b/src/BizHawk.Client.EmuHawk/BizBox.cs @@ -24,10 +24,7 @@ private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs Process.Start(VersionInfo.HomePage); } - private void OK_Click(object sender, EventArgs e) - { - Close(); - } + private void OK_Click(object sender, EventArgs e) => Close(); private void BizBox_Load(object sender, EventArgs e) { @@ -61,19 +58,10 @@ private void BizBox_Load(object sender, EventArgs e) linkLabel2.Text = $"Commit :{VersionInfo.GIT_BRANCH}@{VersionInfo.GIT_SHORTHASH}"; } - private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) - { - Process.Start($"https://github.com/TASEmulators/BizHawk/commit/{VersionInfo.GIT_SHORTHASH}"); - } + private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) => Process.Start($"https://github.com/TASEmulators/BizHawk/commit/{VersionInfo.GIT_SHORTHASH}"); - private void btnCopyHash_Click(object sender, EventArgs e) - { - Clipboard.SetText(VersionInfo.GIT_SHORTHASH); - } + private void btnCopyHash_Click(object sender, EventArgs e) => Clipboard.SetText(VersionInfo.GIT_SHORTHASH); - private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) - { - Process.Start("https://github.com/TASEmulators/BizHawk/graphs/contributors"); - } + private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) => Process.Start("https://github.com/TASEmulators/BizHawk/graphs/contributors"); } } diff --git a/src/BizHawk.Client.EmuHawk/CoreFeatureAnalysis.cs b/src/BizHawk.Client.EmuHawk/CoreFeatureAnalysis.cs index 011bd0228a0..56ddef5b511 100644 --- a/src/BizHawk.Client.EmuHawk/CoreFeatureAnalysis.cs +++ b/src/BizHawk.Client.EmuHawk/CoreFeatureAnalysis.cs @@ -27,13 +27,13 @@ public CoreInfo(IEmulator emu) Released = emu.Attributes().Released; Services = new Dictionary(); var ser = emu.ServiceProvider; - foreach (Type t in ser.AvailableServices.Where(type => type != emu.GetType())) + foreach (var t in ser.AvailableServices.Where(type => type != emu.GetType())) { - var si = new ServiceInfo(t, ser.GetService(t)); + ServiceInfo si = new(t, ser.GetService(t)); Services.Add(si.TypeName, si); } - var notApplicableAttribute = ((ServiceNotApplicableAttribute)Attribute + ServiceNotApplicableAttribute notApplicableAttribute = ((ServiceNotApplicableAttribute)Attribute .GetCustomAttribute(emu.GetType(), typeof(ServiceNotApplicableAttribute))); if (notApplicableAttribute != null) @@ -123,7 +123,7 @@ public CoreFeatureAnalysis() private TreeNode CreateCoreTree(CoreInfo ci) { - var ret = new TreeNode + TreeNode ret = new() { Text = ci.CoreName + (ci.Released ? "" : " (UNRELEASED)"), ForeColor = ci.Released ? Color.Black : Color.DarkGray @@ -132,7 +132,7 @@ private TreeNode CreateCoreTree(CoreInfo ci) foreach (var service in ci.Services.Values) { string img = service.Complete ? "Good" : "Bad"; - var serviceNode = new TreeNode + TreeNode serviceNode = new() { Text = service.TypeName, ForeColor = service.Complete ? Color.Black : Color.Red, @@ -162,7 +162,7 @@ private TreeNode CreateCoreTree(CoreInfo ci) && !ci.Services.ContainsKey(t.ToString()) && !ci.NotApplicableTypes.Contains(t.ToString()))) { string img = "Bad"; - var serviceNode = new TreeNode + TreeNode serviceNode = new() { Text = service.ToString(), ForeColor = Color.Red, @@ -196,7 +196,7 @@ private void DoAllCoresTree(CoreInfo current_ci) CoreTree.ImageList.Images.Add("Bad", Properties.Resources.ExclamationRed); CoreTree.ImageList.Images.Add("Unknown", Properties.Resources.RetroQuestion); - var possibleCoreTypes = CoreInventory.Instance.SystemsFlat + List possibleCoreTypes = CoreInventory.Instance.SystemsFlat .OrderByDescending(core => core.CoreAttr.Released) .ThenBy(core => core.Name) .ToList(); @@ -222,7 +222,7 @@ private void DoAllCoresTree(CoreInfo current_ci) if (!KnownCores.ContainsKey(core.Name)) { string img = "Unknown"; - var coreNode = new TreeNode + TreeNode coreNode = new() { Text = core.Name + (core.CoreAttr.Released ? "" : " (UNRELEASED)"), ForeColor = core.CoreAttr.Released ? Color.Black : Color.DarkGray, @@ -239,7 +239,7 @@ private void DoAllCoresTree(CoreInfo current_ci) public override void Restart() { - var ci = new CoreInfo(Emulator); + CoreInfo ci = new(Emulator); KnownCores[ci.CoreName] = ci; DoCurrentCoreTree(ci); diff --git a/src/BizHawk.Client.EmuHawk/CustomControls/ControlRenderer/GdiPlusRenderer.cs b/src/BizHawk.Client.EmuHawk/CustomControls/ControlRenderer/GdiPlusRenderer.cs index f585ddc41ec..09be62b7ccd 100644 --- a/src/BizHawk.Client.EmuHawk/CustomControls/ControlRenderer/GdiPlusRenderer.cs +++ b/src/BizHawk.Client.EmuHawk/CustomControls/ControlRenderer/GdiPlusRenderer.cs @@ -7,9 +7,9 @@ public class GdiPlusRenderer : IControlRenderer { private Graphics _graphics; - private readonly Pen _currentPen = new Pen(Color.Black); - private readonly SolidBrush _currentBrush = new SolidBrush(Color.Black); - private readonly SolidBrush _currentStringBrush = new SolidBrush(Color.Black); + private readonly Pen _currentPen = new(Color.Black); + private readonly SolidBrush _currentBrush = new(Color.Black); + private readonly SolidBrush _currentStringBrush = new(Color.Black); private Font _currentFont; private bool _rotateString; @@ -35,15 +35,9 @@ public void Dispose() _currentStringBrush.Dispose(); } - public void DrawBitmap(Bitmap bitmap, Point point) - { - _graphics.DrawImage(bitmap, point); - } + public void DrawBitmap(Bitmap bitmap, Point point) => _graphics.DrawImage(bitmap, point); - public void DrawRectangle(Rectangle rect) - { - _graphics.DrawRectangle(_currentPen, rect); - } + public void DrawRectangle(Rectangle rect) => _graphics.DrawRectangle(_currentPen, rect); public void DrawString(string str, Rectangle rect) { @@ -60,15 +54,9 @@ public void DrawString(string str, Rectangle rect) } } - public void FillRectangle(Rectangle rect) - { - _graphics.FillRectangle(_currentBrush, rect); - } + public void FillRectangle(Rectangle rect) => _graphics.FillRectangle(_currentBrush, rect); - public void Line(int x1, int y1, int x2, int y2) - { - _graphics.DrawLine(_currentPen, x1, y1, x2, y2); - } + public void Line(int x1, int y1, int x2, int y2) => _graphics.DrawLine(_currentPen, x1, y1, x2, y2); public IDisposable LockGraphics(Graphics g) { @@ -76,10 +64,7 @@ public IDisposable LockGraphics(Graphics g) return new GdiPlusGraphicsLock(); } - public SizeF MeasureString(string str, Font font) - { - return _graphics.MeasureString(str, font); - } + public SizeF MeasureString(string str, Font font) => _graphics.MeasureString(str, font); public void PrepDrawString(Font font, Color color, bool rotate = false) { @@ -88,14 +73,8 @@ public void PrepDrawString(Font font, Color color, bool rotate = false) _rotateString = rotate; } - public void SetBrush(Color color) - { - _currentBrush.Color = color; - } + public void SetBrush(Color color) => _currentBrush.Color = color; - public void SetSolidPen(Color color) - { - _currentPen.Color = color; - } + public void SetSolidPen(Color color) => _currentPen.Color = color; } } diff --git a/src/BizHawk.Client.EmuHawk/CustomControls/ExceptionBox.cs b/src/BizHawk.Client.EmuHawk/CustomControls/ExceptionBox.cs index 212691c413a..705d2afd7a2 100644 --- a/src/BizHawk.Client.EmuHawk/CustomControls/ExceptionBox.cs +++ b/src/BizHawk.Client.EmuHawk/CustomControls/ExceptionBox.cs @@ -15,10 +15,7 @@ public ExceptionBox(string str) public ExceptionBox(Exception ex): this(ex.ToString()) {} - private void btnCopy_Click(object sender, EventArgs e) - { - DoCopy(); - } + private void btnCopy_Click(object sender, EventArgs e) => DoCopy(); private void DoCopy() { @@ -54,10 +51,7 @@ protected override bool ProcessCmdKey(ref Message msg, Keys keyData) return false; } - private void btnOK_Click(object sender, EventArgs e) - { - Close(); - } + private void btnOK_Click(object sender, EventArgs e) => Close(); private void timer1_Tick(object sender, EventArgs e) { @@ -71,9 +65,9 @@ private class MyLabel : Label { protected override void OnPaint(PaintEventArgs e) { - Rectangle rc = ClientRectangle; - StringFormat fmt = new StringFormat(StringFormat.GenericTypographic); - using var br = new SolidBrush(ForeColor); + var rc = ClientRectangle; + StringFormat fmt = new(StringFormat.GenericTypographic); + using SolidBrush br = new(ForeColor); e.Graphics.DrawString(this.Text, this.Font, br, rc, fmt); } } diff --git a/src/BizHawk.Client.EmuHawk/CustomControls/FolderBrowserDialogEx.cs b/src/BizHawk.Client.EmuHawk/CustomControls/FolderBrowserDialogEx.cs index 9c1f3d45ead..bb2958a0298 100644 --- a/src/BizHawk.Client.EmuHawk/CustomControls/FolderBrowserDialogEx.cs +++ b/src/BizHawk.Client.EmuHawk/CustomControls/FolderBrowserDialogEx.cs @@ -57,7 +57,7 @@ int Callback(IntPtr hwnd, uint uMsg, IntPtr lParam, IntPtr lpData) try { var buffer = Marshal.AllocHGlobal(Win32Imports.MAX_PATH); - var bi = new Win32Imports.BROWSEINFO + Win32Imports.BROWSEINFO bi = new() { hwndOwner = hWndOwner, pidlRoot = pidlRoot, @@ -69,7 +69,7 @@ int Callback(IntPtr hwnd, uint uMsg, IntPtr lParam, IntPtr lpData) pidlRet = Win32Imports.SHBrowseForFolder(ref bi); Marshal.FreeHGlobal(buffer); if (pidlRet == IntPtr.Zero) return DialogResult.Cancel; // user clicked Cancel - var sb = new StringBuilder(Win32Imports.MAX_PATH); + StringBuilder sb = new(Win32Imports.MAX_PATH); if (Win32Imports.SHGetPathFromIDList(pidlRet, sb) == 0) return DialogResult.Cancel; SelectedPath = sb.ToString(); } diff --git a/src/BizHawk.Client.EmuHawk/CustomControls/HexTextBox.cs b/src/BizHawk.Client.EmuHawk/CustomControls/HexTextBox.cs index 8a8d13e5213..f4ecaf4ed56 100644 --- a/src/BizHawk.Client.EmuHawk/CustomControls/HexTextBox.cs +++ b/src/BizHawk.Client.EmuHawk/CustomControls/HexTextBox.cs @@ -62,14 +62,11 @@ public long GetMax() return (1L << (4 * MaxLength)) - 1; } - public override void ResetText() - { - Text = Nullable ? "" : string.Format(_addressFormatStr, 0); - } + public override void ResetText() => Text = Nullable ? "" : string.Format(_addressFormatStr, 0); protected override void OnKeyPress(KeyPressEventArgs e) { - if (e.KeyChar == '\b' || e.KeyChar == 22 || e.KeyChar == 1 || e.KeyChar == 3) + if (e.KeyChar is '\b' or (char)22 or (char)1 or (char)3) { return; } @@ -86,7 +83,7 @@ protected override void OnKeyDown(KeyEventArgs e) { if (Text.IsHex() && !string.IsNullOrEmpty(_addressFormatStr)) { - var val = (uint)ToRawInt(); + uint val = (uint)ToRawInt(); if (val == GetMax()) { @@ -104,7 +101,7 @@ protected override void OnKeyDown(KeyEventArgs e) { if (Text.IsHex() && !string.IsNullOrEmpty(_addressFormatStr)) { - var val = (uint)ToRawInt(); + uint val = (uint)ToRawInt(); if (val == 0) { val = (uint)GetMax(); // int to long todo @@ -150,15 +147,9 @@ protected override void OnTextChanged(EventArgs e) return int.Parse(Text, NumberStyles.HexNumber); } - public void SetFromRawInt(int? val) - { - Text = val.HasValue ? string.Format(_addressFormatStr, val) : ""; - } + public void SetFromRawInt(int? val) => Text = val.HasValue ? string.Format(_addressFormatStr, val) : ""; - public void SetFromLong(long val) - { - Text = string.Format(_addressFormatStr, val); - } + public void SetFromLong(long val) => Text = string.Format(_addressFormatStr, val); public void SetFromU64(ulong? val) => Text = val is null ? string.Empty : string.Format(_addressFormatStr, val.Value); @@ -179,7 +170,7 @@ public void SetFromU64(ulong? val) } public ulong? ToU64() - => ulong.TryParse(Text, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var l) + => ulong.TryParse(Text, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ulong l) ? l : Nullable ? null @@ -197,7 +188,7 @@ public UnsignedIntegerBox() protected override void OnKeyPress(KeyPressEventArgs e) { - if (e.KeyChar == '\b' || e.KeyChar == 22 || e.KeyChar == 1 || e.KeyChar == 3) + if (e.KeyChar is '\b' or (char)22 or (char)1 or (char)3) { return; } @@ -208,10 +199,7 @@ protected override void OnKeyPress(KeyPressEventArgs e) } } - public override void ResetText() - { - Text = Nullable ? "" : "0"; - } + public override void ResetText() => Text = Nullable ? "" : "0"; protected override void OnKeyDown(KeyEventArgs e) { @@ -219,7 +207,7 @@ protected override void OnKeyDown(KeyEventArgs e) { if (Text.IsHex()) { - var val = (uint)ToRawInt(); + uint val = (uint)ToRawInt(); if (val == uint.MaxValue) { val = 0; @@ -236,7 +224,7 @@ protected override void OnKeyDown(KeyEventArgs e) { if (Text.IsHex()) { - var val = (uint)ToRawInt(); + uint val = (uint)ToRawInt(); if (val == 0) { @@ -283,9 +271,6 @@ protected override void OnTextChanged(EventArgs e) return (int)uint.Parse(Text); } - public void SetFromRawInt(int? val) - { - Text = val?.ToString() ?? ""; - } + public void SetFromRawInt(int? val) => Text = val?.ToString() ?? ""; } } diff --git a/src/BizHawk.Client.EmuHawk/CustomControls/InputRoll/Cell.cs b/src/BizHawk.Client.EmuHawk/CustomControls/InputRoll/Cell.cs index ce631c8a30f..b9e3beb533f 100644 --- a/src/BizHawk.Client.EmuHawk/CustomControls/InputRoll/Cell.cs +++ b/src/BizHawk.Client.EmuHawk/CustomControls/InputRoll/Cell.cs @@ -21,7 +21,7 @@ public Cell(Cell cell) public override bool Equals(object obj) { - var cell = obj as Cell; + Cell cell = obj as Cell; if (cell != null) { return Column == cell.Column && RowIndex == cell.RowIndex; @@ -30,10 +30,7 @@ public override bool Equals(object obj) return false; } - public override int GetHashCode() - { - return Column.GetHashCode() + RowIndex.GetHashCode(); - } + public override int GetHashCode() => Column.GetHashCode() + RowIndex.GetHashCode(); public static bool operator ==(Cell a, Cell b) { @@ -89,9 +86,6 @@ int IComparer.Compare(Cell c1, Cell c2) public static class CellExtensions { - public static bool IsDataCell(this Cell cell) - { - return cell != null && cell.RowIndex != null && cell.Column != null; - } + public static bool IsDataCell(this Cell cell) => cell != null && cell.RowIndex != null && cell.Column != null; } } diff --git a/src/BizHawk.Client.EmuHawk/CustomControls/InputRoll/InputRoll.Drawing.cs b/src/BizHawk.Client.EmuHawk/CustomControls/InputRoll/InputRoll.Drawing.cs index bc1a2a484dc..a910ba8796a 100644 --- a/src/BizHawk.Client.EmuHawk/CustomControls/InputRoll/InputRoll.Drawing.cs +++ b/src/BizHawk.Client.EmuHawk/CustomControls/InputRoll/InputRoll.Drawing.cs @@ -32,19 +32,19 @@ protected override void OnPaint(PaintEventArgs e) } else { - visibleColumns = _columns.VisibleColumns + visibleColumns = AllColumns.VisibleColumns .Where(c => c.Right > _hBar.Value && c.Left - _hBar.Value < e.ClipRectangle.Width) .ToList(); } - var firstVisibleRow = Math.Max(FirstVisibleRow, 0); - var visibleRows = HorizontalOrientation + int firstVisibleRow = Math.Max(FirstVisibleRow, 0); + int visibleRows = HorizontalOrientation ? e.ClipRectangle.Width / CellWidth : e.ClipRectangle.Height / CellHeight; - var lastVisibleRow = firstVisibleRow + visibleRows; + int lastVisibleRow = firstVisibleRow + visibleRows; - var needsColumnRedraw = HorizontalOrientation || e.ClipRectangle.Y < ColumnHeight; + bool needsColumnRedraw = HorizontalOrientation || e.ClipRectangle.Y < ColumnHeight; if (visibleColumns.Any() && needsColumnRedraw) { DrawColumnBg(visibleColumns, e.ClipRectangle); @@ -86,7 +86,7 @@ private void CalculateHorizontalColumnPositions(List visibleColumns) int startRow = FirstVisibleRow; for (int j = 0; j < visibleColumns.Count; j++) { - RollColumn col = visibleColumns[j]; + var col = visibleColumns[j]; int height = CellHeight; if (col.Rotatable && col.RotatedHeight != null) { @@ -96,7 +96,7 @@ private void CalculateHorizontalColumnPositions(List visibleColumns) { int strOffsetX = 0; int strOffsetY = 0; - QueryItemText(startRow, col, out var text, ref strOffsetX, ref strOffsetY); + QueryItemText(startRow, col, out string text, ref strOffsetX, ref strOffsetY); int textWidth = (int)_renderer.MeasureString(text, Font).Width; height = Math.Max(height, textWidth + (CellWidthPadding * 2)); } @@ -148,12 +148,12 @@ private void DrawCellDrag(List visibleColumns) && _currentX.HasValue && _currentY.HasValue) { - var text = ""; + string text = ""; int offsetX = 0; int offsetY = 0; QueryItemText?.Invoke(_draggingCell.RowIndex.Value, _draggingCell.Column, out text, ref offsetX, ref offsetY); - Color bgColor = _backColor; + var bgColor = _backColor; QueryItemBkColor?.Invoke(_draggingCell.RowIndex.Value, _draggingCell.Column, ref bgColor); int columnHeight = CellHeight; @@ -184,13 +184,13 @@ private void DrawColumnText(List visibleColumns) for (int j = 0; j < visibleColumns.Count; j++) { var column = visibleColumns[j]; - var w = column.Width; + int w = column.Width; int x, y; if (HorizontalOrientation) { - var columnHeight = GetHColHeight(j); - var textHeight = (int)_renderer.MeasureString(column.Text, Font).Height; + int columnHeight = GetHColHeight(j); + int textHeight = (int)_renderer.MeasureString(column.Text, Font).Height; x = CellWidthPadding; y = yOffset + ((columnHeight - textHeight) / 2); yOffset += columnHeight; @@ -235,7 +235,7 @@ private void DrawData(List visibleColumns, int firstVisibleRow, int { for (int j = 0; j < visibleColumns.Count; j++) { - RollColumn col = visibleColumns[j]; + var col = visibleColumns[j]; int colHeight = GetHColHeight(j); for (int i = 0, f = 0; f < range; i++, f++) @@ -263,7 +263,7 @@ private void DrawData(List visibleColumns, int firstVisibleRow, int int strOffsetX = 0; int strOffsetY = 0; - QueryItemText(f + startRow, col, out var text, ref strOffsetX, ref strOffsetY); + QueryItemText(f + startRow, col, out string text, ref strOffsetX, ref strOffsetY); int textWidth = (int)_renderer.MeasureString(text, Font).Width; if (col.Rotatable) @@ -295,11 +295,11 @@ private void DrawData(List visibleColumns, int firstVisibleRow, int f += _lagFrames[i]; foreach (var column in visibleColumns) { - RollColumn col = column; + var col = column; int strOffsetX = 0; int strOffsetY = 0; - Point point = new Point(col.Left + xPadding, RowsToPixels(i) + CellHeightPadding); + Point point = new(col.Left + xPadding, RowsToPixels(i) + CellHeightPadding); Bitmap image = null; int bitmapOffsetX = 0; @@ -312,7 +312,7 @@ private void DrawData(List visibleColumns, int firstVisibleRow, int _renderer.DrawBitmap(image, new Point(point.X + bitmapOffsetX, point.Y + bitmapOffsetY + CellHeightPadding)); } - QueryItemText(f + startRow, column, out var text, ref strOffsetX, ref strOffsetY); + QueryItemText(f + startRow, column, out string text, ref strOffsetX, ref strOffsetY); bool rePrep = false; if (_selectedItems.Contains(new Cell { Column = column, RowIndex = f + startRow })) @@ -510,17 +510,17 @@ private void DrawBg(List visibleColumns, Rectangle rect, int firstVi private void DoSelectionBG(List visibleColumns, Rectangle rect) { - Color rowColor = Color.White; + var rowColor = Color.White; var visibleRows = FirstVisibleRow.RangeTo(LastVisibleRow); int lastRow = -1; - foreach (Cell cell in _selectedItems) + foreach (var cell in _selectedItems) { if (!cell.RowIndex.HasValue || !visibleRows.Contains(cell.RowIndex.Value) || !VisibleColumns.Contains(cell.Column)) { continue; } - Cell relativeCell = new Cell + Cell relativeCell = new() { RowIndex = cell.RowIndex - visibleRows.Start, Column = cell.Column @@ -533,12 +533,12 @@ private void DoSelectionBG(List visibleColumns, Rectangle rect) lastRow = cell.RowIndex.Value; } - Color cellColor = rowColor; + var cellColor = rowColor; QueryItemBkColor?.Invoke(cell.RowIndex.Value, cell.Column, ref cellColor); // Alpha layering for cell before selection float alpha = (float)cellColor.A / 255; - if (cellColor.A != 255 && cellColor.A != 0) + if (cellColor.A is not 255 and not 0) { cellColor = Color.FromArgb(rowColor.R - (int)((rowColor.R - cellColor.R) * alpha), rowColor.G - (int)((rowColor.G - cellColor.G) * alpha), @@ -603,19 +603,19 @@ private void DoBackGroundCallback(List visibleColumns, Rectangle rec for (int i = 0, f = 0; f < range; i++, f++) { f += _lagFrames[i]; - Color rowColor = Color.White; + var rowColor = Color.White; QueryRowBkColor?.Invoke(f + startIndex, ref rowColor); foreach (var column in visibleColumns) { - Color itemColor = Color.White; + var itemColor = Color.White; QueryItemBkColor?.Invoke(f + startIndex, column, ref itemColor); if (itemColor == Color.White) { itemColor = rowColor; } - else if (itemColor.A != 255 && itemColor.A != 0) + else if (itemColor.A is not 255 and not 0) { float alpha = (float)itemColor.A / 255; itemColor = Color.FromArgb(rowColor.R - (int)((rowColor.R - itemColor.R) * alpha), @@ -625,7 +625,7 @@ private void DoBackGroundCallback(List visibleColumns, Rectangle rec if (itemColor != Color.White) // An easy optimization, don't draw unless the user specified something other than the default { - var cell = new Cell + Cell cell = new() { Column = column, RowIndex = i diff --git a/src/BizHawk.Client.EmuHawk/CustomControls/InputRoll/InputRoll.cs b/src/BizHawk.Client.EmuHawk/CustomControls/InputRoll/InputRoll.cs index 89fc29af2a7..459b1191ba9 100644 --- a/src/BizHawk.Client.EmuHawk/CustomControls/InputRoll/InputRoll.cs +++ b/src/BizHawk.Client.EmuHawk/CustomControls/InputRoll/InputRoll.cs @@ -22,19 +22,17 @@ namespace BizHawk.Client.EmuHawk public partial class InputRoll : Control { private readonly IControlRenderer _renderer; - private readonly SortedSet _selectedItems = new SortedSet(new SortCell()); + private readonly SortedSet _selectedItems = new(new SortCell()); // scrollbar location(s) are calculated later (e.g. on resize) - private readonly VScrollBar _vBar = new VScrollBar { Visible = false }; - private readonly HScrollBar _hBar = new HScrollBar { Visible = false }; + private readonly VScrollBar _vBar = new() { Visible = false }; + private readonly HScrollBar _hBar = new() { Visible = false }; - private readonly Timer _hoverTimer = new Timer(); + private readonly Timer _hoverTimer = new(); private readonly byte[] _lagFrames = new byte[256]; // Large enough value that it shouldn't ever need resizing. // apparently not large enough for 4K private readonly Color _foreColor; private readonly Color _backColor; - - private RollColumns _columns = new RollColumns(); private bool _horizontalOrientation; private bool _programmaticallyUpdatingScrollBarValues; @@ -111,7 +109,7 @@ public InputRoll() _hBar.ValueChanged += HorizontalBar_ValueChanged; RecalculateScrollBars(); - _columns.ChangedCallback = ColumnChangedCallback; + AllColumns.ChangedCallback = ColumnChangedCallback; _hoverTimer.Interval = 750; _hoverTimer.Tick += HoverTimerEventProcessor; @@ -142,7 +140,7 @@ public void ExpandColumnToFitText(string columnName, string text) using var g = CreateGraphics(); using (_renderer.LockGraphics(g)) { - var strLength = (int)_renderer.MeasureString(text, Font).Width + (CellWidthPadding * 2); + int strLength = (int)_renderer.MeasureString(text, Font).Width + (CellWidthPadding * 2); if (column.Width < strLength) { column.Width = strLength; @@ -163,7 +161,7 @@ protected override void OnDoubleClick(EventArgs e) } else { - var maxLength = CurrentCell.Column.Text?.Length ?? 0; + int maxLength = CurrentCell.Column.Text?.Length ?? 0; for (int i = 0; i < RowCount; i++) { @@ -176,9 +174,9 @@ protected override void OnDoubleClick(EventArgs e) } } - var newWidth = (maxLength * _charSize.Width) + (CellWidthPadding * 2); + float newWidth = (maxLength * _charSize.Width) + (CellWidthPadding * 2); CurrentCell.Column.Width = (int)newWidth; - _columns.ColumnsChanged(); + AllColumns.ColumnsChanged(); Refresh(); } @@ -339,7 +337,7 @@ private void FastDraw() /// All visible columns /// [Category("Behavior")] - public IEnumerable VisibleColumns => _columns.VisibleColumns; + public IEnumerable VisibleColumns => AllColumns.VisibleColumns; /// /// Gets or sets how the InputRoll scrolls when calling ScrollToIndex. @@ -373,7 +371,7 @@ private void FastDraw() /// [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public RollColumns AllColumns => _columns; + public RollColumns AllColumns { get; private set; } = new(); [DefaultValue(750)] [Category("Behavior")] @@ -546,20 +544,20 @@ public ColumnReorderedEventArgs(int oldDisplayIndex, int newDisplayIndex, RollCo public void SelectRow(int index, bool val) { - if (_columns.VisibleColumns.Any()) + if (AllColumns.VisibleColumns.Any()) { if (val) { SelectCell(new Cell { RowIndex = index, - Column = _columns[0] + Column = AllColumns[0] }); _lastSelectedRow = index; } else { - IEnumerable items = _selectedItems.Where(cell => cell.RowIndex == index); + var items = _selectedItems.Where(cell => cell.RowIndex == index); _selectedItems.RemoveWhere(items.Contains); _lastSelectedRow = _selectedItems.LastOrDefault()?.RowIndex; } @@ -568,7 +566,7 @@ public void SelectRow(int index, bool val) public void SelectAll() { - var oldFullRowVal = FullRowSelect; + bool oldFullRowVal = FullRowSelect; FullRowSelect = true; for (int i = 0; i < RowCount; i++) { @@ -633,28 +631,28 @@ public int? SelectionEndIndex public string UserSettingsSerialized() { - var settings = ConfigService.SaveWithType(Settings); + string settings = ConfigService.SaveWithType(Settings); return settings; } public void LoadSettingsSerialized(string settingsJson) { - var settings = ConfigService.LoadWithType(settingsJson); + object settings = ConfigService.LoadWithType(settingsJson); // TODO: don't silently fail, inform the user somehow if (settings is InputRollSettings rollSettings) { - _columns = rollSettings.Columns; - _columns.ChangedCallback = ColumnChangedCallback; + AllColumns = rollSettings.Columns; + AllColumns.ChangedCallback = ColumnChangedCallback; HorizontalOrientation = rollSettings.HorizontalOrientation; LagFramesToHide = rollSettings.LagFramesToHide; HideWasLagFrames = rollSettings.HideWasLagFrames; } } - private InputRollSettings Settings => new InputRollSettings + private InputRollSettings Settings => new() { - Columns = _columns, + Columns = AllColumns, HorizontalOrientation = HorizontalOrientation, LagFramesToHide = LagFramesToHide, HideWasLagFrames = HideWasLagFrames @@ -827,17 +825,14 @@ public int VisibleRows return (_drawWidth - MaxColumnWidth) / CellWidth; } - var result = (_drawHeight - ColumnHeight - 3) / CellHeight; // Minus three makes it work + int result = (_drawHeight - ColumnHeight - 3) / CellHeight; // Minus three makes it work return result < 0 ? 0 : result; } } private Cell _draggingCell; - public void DragCurrentCell() - { - _draggingCell = CurrentCell; - } + public void DragCurrentCell() => _draggingCell = CurrentCell; public void ReleaseCurrentCell() { @@ -962,7 +957,7 @@ public IEnumerable GenerateContextMenuItems() { yield return new ToolStripSeparator(); - var rotate = new ToolStripMenuItem + ToolStripMenuItem rotate = new() { Name = "RotateMenuItem", Text = "Rotate", @@ -1025,7 +1020,7 @@ protected override void OnMouseMove(MouseEventArgs e) _columnResizing.Width = 1; } - _columns.ColumnsChanged(); + AllColumns.ColumnsChanged(); Refresh(); } } @@ -1034,7 +1029,7 @@ protected override void OnMouseMove(MouseEventArgs e) _columnDownMoved = true; } - Cell newCell = CalculatePointedCell(_currentX.Value, _currentY.Value); + var newCell = CalculatePointedCell(_currentX.Value, _currentY.Value); // SuuperW: Hide lag frames if (QueryFrameLag != null && newCell.RowIndex.HasValue) @@ -1148,19 +1143,19 @@ protected override void OnMouseDown(MouseEventArgs e) { if (FullRowSelect) { - var selected = _selectedItems.Any(c => c.RowIndex.HasValue && CurrentCell.RowIndex.HasValue && c.RowIndex == CurrentCell.RowIndex); + bool selected = _selectedItems.Any(c => c.RowIndex.HasValue && CurrentCell.RowIndex.HasValue && c.RowIndex == CurrentCell.RowIndex); if (!selected) { - var rowIndices = _selectedItems + List rowIndices = _selectedItems .Where(c => c.RowIndex.HasValue) .Select(c => c.RowIndex ?? -1) .Where(c => c >= 0) // Hack to avoid possible Nullable exceptions .Distinct() .ToList(); - var firstIndex = rowIndices.Min(); - var lastIndex = rowIndices.Max(); + int firstIndex = rowIndices.Min(); + int lastIndex = rowIndices.Max(); if (CurrentCell.RowIndex.Value < firstIndex) { @@ -1186,7 +1181,7 @@ protected override void OnMouseDown(MouseEventArgs e) } else // Somewhere in between, a scenario that can happen with ctrl-clicking, find the previous and highlight from there { - var nearest = rowIndices + int nearest = rowIndices .Where(x => x < CurrentCell.RowIndex.Value) .Max(); @@ -1340,25 +1335,16 @@ protected override void OnMouseWheel(MouseEventArgs e) } } - private void DoRightMouseScroll(object sender, MouseEventArgs e) - { - RightMouseScrolled?.Invoke(sender, e); - } + private void DoRightMouseScroll(object sender, MouseEventArgs e) => RightMouseScrolled?.Invoke(sender, e); - private void ColumnClickEvent(RollColumn column) - { - ColumnClick?.Invoke(this, new ColumnClickEventArgs(column)); - } + private void ColumnClickEvent(RollColumn column) => ColumnClick?.Invoke(this, new ColumnClickEventArgs(column)); - private void ColumnRightClickEvent(RollColumn column) - { - ColumnRightClick?.Invoke(this, new ColumnClickEventArgs(column)); - } + private void ColumnRightClickEvent(RollColumn column) => ColumnRightClick?.Invoke(this, new ColumnClickEventArgs(column)); // This allows arrow keys to be detected by KeyDown. protected override void OnPreviewKeyDown(PreviewKeyDownEventArgs e) { - if (e.KeyCode == Keys.Left || e.KeyCode == Keys.Right || e.KeyCode == Keys.Up || e.KeyCode == Keys.Down) + if (e.KeyCode is Keys.Left or Keys.Right or Keys.Up or Keys.Down) { e.IsInputKey = true; } @@ -1385,9 +1371,9 @@ protected override void OnKeyDown(KeyEventArgs e) { if (ChangeSelectionWhenPaging) { - var selectedRow = AnyRowsSelected ? FirstSelectedRowIndex : FirstVisibleRow; - var increment = LastVisibleRow - FirstVisibleRow; - var newSelectedRow = selectedRow - increment; + int selectedRow = AnyRowsSelected ? FirstSelectedRowIndex : FirstVisibleRow; + int increment = LastVisibleRow - FirstVisibleRow; + int newSelectedRow = selectedRow - increment; if (newSelectedRow < 0) { newSelectedRow = 0; @@ -1407,9 +1393,9 @@ protected override void OnKeyDown(KeyEventArgs e) { if (ChangeSelectionWhenPaging) { - var selectedRow = AnyRowsSelected ? FirstSelectedRowIndex : FirstVisibleRow; - var increment = LastVisibleRow - FirstVisibleRow; - var newSelectedRow = selectedRow + increment; + int selectedRow = AnyRowsSelected ? FirstSelectedRowIndex : FirstVisibleRow; + int increment = LastVisibleRow - FirstVisibleRow; + int newSelectedRow = selectedRow + increment; if (newSelectedRow > RowCount - 1) { newSelectedRow = RowCount - 1; @@ -1443,10 +1429,10 @@ protected override void OnKeyDown(KeyEventArgs e) { if (AnyRowsSelected) { - var selectedRow = FirstSelectedRowIndex; + int selectedRow = FirstSelectedRowIndex; if (selectedRow > 0) { - var targetSelectedRow = selectedRow - 1; + int targetSelectedRow = selectedRow - 1; DeselectAll(); SelectRow(targetSelectedRow, true); ScrollToIndex(targetSelectedRow); @@ -1458,10 +1444,10 @@ protected override void OnKeyDown(KeyEventArgs e) { if (AnyRowsSelected) { - var selectedRow = FirstSelectedRowIndex; + int selectedRow = FirstSelectedRowIndex; if (selectedRow < RowCount - 1) { - var targetSelectedRow = selectedRow + 1; + int targetSelectedRow = selectedRow + 1; DeselectAll(); SelectRow(targetSelectedRow, true); ScrollToIndex(targetSelectedRow); @@ -1493,7 +1479,7 @@ protected override void OnKeyDown(KeyEventArgs e) if (_selectedItems.Any(i => i.RowIndex == _lastSelectedRow.Value) && _selectedItems.Any(i => i.RowIndex == _lastSelectedRow + 1)) // Unhighlight if already highlighted { - var origIndex = _lastSelectedRow.Value; + int origIndex = _lastSelectedRow.Value; SelectRow(origIndex, false); // SelectRow assumed the max row should be selected, but in this edge case it isn't @@ -1513,7 +1499,7 @@ protected override void OnKeyDown(KeyEventArgs e) { if (AnyRowsSelected && LetKeysModifySelection && FirstSelectedRowIndex > 0) { - foreach (var row in SelectedRows.ToList()) // clones SelectedRows + foreach (int row in SelectedRows.ToList()) // clones SelectedRows { SelectRow(row - 1, true); SelectRow(row, false); @@ -1524,7 +1510,7 @@ protected override void OnKeyDown(KeyEventArgs e) { if (AnyRowsSelected && LetKeysModifySelection) { - foreach (var row in SelectedRows.Reverse()) // clones SelectedRows + foreach (int row in SelectedRows.Reverse()) // clones SelectedRows { SelectRow(row + 1, true); SelectRow(row, false); @@ -1655,9 +1641,9 @@ private void HorizontalBar_ValueChanged(object sender, EventArgs e) private void ColumnChangedCallback() { RecalculateScrollBars(); - if (_columns.VisibleColumns.Any()) + if (AllColumns.VisibleColumns.Any()) { - MaxColumnWidth = _columns.VisibleColumns.Max(c => c.Width) + CellWidthPadding * 4; + MaxColumnWidth = AllColumns.VisibleColumns.Max(c => c.Width) + CellWidthPadding * 4; } } @@ -1665,13 +1651,13 @@ private void DoColumnReorder() { if (_columnDown != CurrentCell.Column) { - var oldIndex = _columns.IndexOf(_columnDown); - var newIndex = _columns.IndexOf(CurrentCell.Column); + int oldIndex = AllColumns.IndexOf(_columnDown); + int newIndex = AllColumns.IndexOf(CurrentCell.Column); ColumnReordered?.Invoke(this, new ColumnReorderedEventArgs(oldIndex, newIndex, _columnDown)); - _columns.Remove(_columnDown); - _columns.Insert(newIndex, _columnDown); + AllColumns.Remove(_columnDown); + AllColumns.Insert(newIndex, _columnDown); } } @@ -1681,7 +1667,7 @@ private void RecalculateScrollBars() { UpdateDrawSize(); - var columns = _columns.VisibleColumns.ToList(); + List columns = AllColumns.VisibleColumns.ToList(); int iLastColumn = columns.Count - 1; if (HorizontalOrientation) @@ -1802,7 +1788,7 @@ private void SelectCell(Cell cell, bool toggle = false) } else { - foreach (var column in _columns) + foreach (var column in AllColumns) { _selectedItems.Add(new Cell { @@ -1844,7 +1830,7 @@ private void SelectCell(Cell cell, bool toggle = false) private bool IsPointingOnCellEdge(int? x) => x.HasValue && !HorizontalOrientation //TODO support column resize in horizontal orientation - && _columns.VisibleColumns.Any(column => (column.Left - _hBar.Value + (column.Width - column.Width / 6)).RangeTo(column.Right - _hBar.Value).Contains(x.Value)); + && AllColumns.VisibleColumns.Any(column => (column.Left - _hBar.Value + (column.Width - column.Width / 6)).RangeTo(column.Right - _hBar.Value).Contains(x.Value)); /// /// Finds the specific cell that contains the (x, y) coordinate. @@ -1855,8 +1841,8 @@ private bool IsPointingOnCellEdge(int? x) => x.HasValue /// The cell with row number and RollColumn reference, both of which can be null. private Cell CalculatePointedCell(int x, int y) { - var newCell = new Cell(); - var columns = _columns.VisibleColumns.ToList(); + Cell newCell = new(); + List columns = AllColumns.VisibleColumns.ToList(); // If pointing to a column header if (columns.Any()) @@ -1888,8 +1874,8 @@ private Cell CalculatePointedCell(int x, int y) private bool NeedsHScrollbar { get; set; } // Gets the total width of all the columns by using the last column's Right property. - private int TotalColWidth => _columns.VisibleColumns.Any() - ? _columns.VisibleColumns.Last().Right + private int TotalColWidth => AllColumns.VisibleColumns.Any() + ? AllColumns.VisibleColumns.Last().Right : 0; /// @@ -1901,11 +1887,11 @@ private RollColumn ColumnAtPixel(int pixel) { if (_horizontalOrientation) { - return _columns.VisibleColumns.Select(static (n, i) => (Column: n, Index: i)) + return AllColumns.VisibleColumns.Select(static (n, i) => (Column: n, Index: i)) .FirstOrNull(item => (GetHColTop(item.Index) - _vBar.Value).RangeTo(GetHColBottom(item.Index) - _vBar.Value).Contains(pixel)) ?.Column; } - return _columns.VisibleColumns.FirstOrDefault(column => (column.Left - _hBar.Value).RangeTo(column.Right - _hBar.Value).Contains(pixel)); + return AllColumns.VisibleColumns.FirstOrDefault(column => (column.Left - _hBar.Value).RangeTo(column.Right - _hBar.Value).Contains(pixel)); } /// @@ -1983,16 +1969,13 @@ private void UpdateCellSize() CellHeight = (int)_charSize.Height + (CellHeightPadding * 2); CellWidth = (int)_charSize.Width + (CellWidthPadding * 4); // Double the padding for horizontal because it looks better - if (_columns.VisibleColumns.Any()) + if (AllColumns.VisibleColumns.Any()) { - MaxColumnWidth = _columns.VisibleColumns.Max(c => c.Width) + CellWidthPadding * 4; + MaxColumnWidth = AllColumns.VisibleColumns.Max(c => c.Width) + CellWidthPadding * 4; } } - protected override void OnFontChanged(EventArgs e) - { - UpdateCellSize(); - } + protected override void OnFontChanged(EventArgs e) => UpdateCellSize(); // SuuperW: Count lag frames between FirstDisplayed and given display position private int CountLagFramesDisplay(int relativeIndex) @@ -2111,9 +2094,6 @@ private void SetLagFramesFirst() } // Number of displayed + hidden frames, if fps is as expected - private int ExpectedDisplayRange() - { - return (VisibleRows + 1) * LagFramesToHide; - } + private int ExpectedDisplayRange() => (VisibleRows + 1) * LagFramesToHide; } } diff --git a/src/BizHawk.Client.EmuHawk/CustomControls/InputRoll/RollColumns.cs b/src/BizHawk.Client.EmuHawk/CustomControls/InputRoll/RollColumns.cs index 27b846c1420..d6b7741cca4 100644 --- a/src/BizHawk.Client.EmuHawk/CustomControls/InputRoll/RollColumns.cs +++ b/src/BizHawk.Client.EmuHawk/CustomControls/InputRoll/RollColumns.cs @@ -62,7 +62,7 @@ public void ColumnsChanged() public new void InsertRange(int index, IEnumerable collection) { - var items = collection.ToList(); + List items = collection.ToList(); foreach (var column in items) { if (this.Any(c => c.Name == column.Name)) @@ -77,14 +77,14 @@ public void ColumnsChanged() public new bool Remove(RollColumn column) { - var result = base.Remove(column); + bool result = base.Remove(column); ColumnsChanged(); return result; } public new int RemoveAll(Predicate match) { - var result = base.RemoveAll(match); + int result = base.RemoveAll(match); ColumnsChanged(); return result; } diff --git a/src/BizHawk.Client.EmuHawk/CustomControls/InputWidget.cs b/src/BizHawk.Client.EmuHawk/CustomControls/InputWidget.cs index 47ba9d8d2d8..cbe63c7d791 100644 --- a/src/BizHawk.Client.EmuHawk/CustomControls/InputWidget.cs +++ b/src/BizHawk.Client.EmuHawk/CustomControls/InputWidget.cs @@ -12,8 +12,8 @@ namespace BizHawk.Client.EmuHawk public sealed class InputWidget : TextBox { // TODO: when binding, make sure that the new key combo is not in one of the other bindings - private readonly Timer _timer = new Timer(); - private readonly List _bindings = new List(); + private readonly Timer _timer = new(); + private readonly List _bindings = new(); private InputEvent _lastPress; @@ -55,7 +55,7 @@ public string Bindings set { ClearBindings(); - var newBindings = value.Trim().Split(','); + string[] newBindings = value.Trim().Split(','); _bindings.AddRange(newBindings); UpdateLabel(); } @@ -73,10 +73,7 @@ public void ClearAll() Clear(); } - private void ClearBindings() - { - _bindings.Clear(); - } + private void ClearBindings() => _bindings.Clear(); protected override void OnEnter(EventArgs e) { @@ -100,10 +97,7 @@ protected override void OnHandleDestroyed(EventArgs e) base.OnHandleDestroyed(e); } - private void Timer_Tick(object sender, EventArgs e) - { - ReadKeys(); - } + private void Timer_Tick(object sender, EventArgs e) => ReadKeys(); private void EraseMappings() { @@ -127,7 +121,7 @@ public void SetBinding(string bindingStr) private void ReadKeys() { Input.Instance.Update(); - var bindingStr = Input.Instance.GetNextBindEvent(ref _lastPress); + string bindingStr = Input.Instance.GetNextBindEvent(ref _lastPress); if (bindingStr != null) { @@ -215,10 +209,7 @@ public void UpdateLabel() CompositeWidget.RefreshTooltip(); } - protected override void OnKeyPress(KeyPressEventArgs e) - { - e.Handled = true; - } + protected override void OnKeyPress(KeyPressEventArgs e) => e.Handled = true; protected override void WndProc(ref Message m) { @@ -256,9 +247,6 @@ protected override void OnGotFocus(EventArgs e) if (!OSTailoredCode.IsUnixHost) Win32Imports.HideCaret(Handle); } - protected override bool ProcessCmdKey(ref Message msg, Keys keyData) - { - return !(keyData.ToString() == "F4" || keyData.ToString().Contains("Alt")); - } + protected override bool ProcessCmdKey(ref Message msg, Keys keyData) => !(keyData.ToString() == "F4" || keyData.ToString().Contains("Alt")); } } \ No newline at end of file diff --git a/src/BizHawk.Client.EmuHawk/CustomControls/MenuButton.cs b/src/BizHawk.Client.EmuHawk/CustomControls/MenuButton.cs index 0a96b123edc..9bd3fc1b5bf 100644 --- a/src/BizHawk.Client.EmuHawk/CustomControls/MenuButton.cs +++ b/src/BizHawk.Client.EmuHawk/CustomControls/MenuButton.cs @@ -26,7 +26,7 @@ protected override void OnPaint(PaintEventArgs e) int arrowX = ClientRectangle.Width - 14; int arrowY = ClientRectangle.Height / 2 - 1; - Brush brush = Enabled ? SystemBrushes.ControlText : SystemBrushes.ButtonShadow; + var brush = Enabled ? SystemBrushes.ControlText : SystemBrushes.ButtonShadow; Point[] arrows = { new Point(arrowX, arrowY), new Point(arrowX + 7, arrowY), new Point(arrowX + 3, arrowY + 4) }; e.Graphics.FillPolygon(brush, arrows); } diff --git a/src/BizHawk.Client.EmuHawk/CustomControls/MiscControls.cs b/src/BizHawk.Client.EmuHawk/CustomControls/MiscControls.cs index 994927929f8..36dda079b79 100644 --- a/src/BizHawk.Client.EmuHawk/CustomControls/MiscControls.cs +++ b/src/BizHawk.Client.EmuHawk/CustomControls/MiscControls.cs @@ -5,15 +5,9 @@ namespace BizHawk.Client.EmuHawk { public class HorizontalLine : Control { - protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) - { - base.SetBoundsCore(x, y, width, 2, specified); - } + protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) => base.SetBoundsCore(x, y, width, 2, specified); - protected override void OnPaint(PaintEventArgs e) - { - ControlPaint.DrawBorder3D(e.Graphics, 0, 0, Width, 2, Border3DStyle.Etched); - } + protected override void OnPaint(PaintEventArgs e) => ControlPaint.DrawBorder3D(e.Graphics, 0, 0, Width, 2, Border3DStyle.Etched); } public class CustomCheckBox : CheckBox @@ -35,15 +29,15 @@ public bool? ForceChecked protected override void OnPaint(PaintEventArgs pevent) { // draw text-label part of the control with something so that it isn't hallofmirrorsy - using(var brush = new SolidBrush(Parent.BackColor)) + using(SolidBrush brush = new(Parent.BackColor)) pevent.Graphics.FillRectangle(brush, ClientRectangle); - - var r = new Rectangle(ClientRectangle.Location, SystemInformation.MenuCheckSize); + + Rectangle r = new(ClientRectangle.Location, SystemInformation.MenuCheckSize); var glyphLoc = ClientRectangle; glyphLoc.Size = SystemInformation.MenuCheckSize; // draw the selectedbackdrop color roughly where the glyph belongs - using (var brush = new SolidBrush(_checkBackColor)) + using (SolidBrush brush = new(_checkBackColor)) pevent.Graphics.FillRectangle(brush, glyphLoc); // draw a checkbox menu glyph (we could do this more elegantly with DrawFrameControl) diff --git a/src/BizHawk.Client.EmuHawk/CustomControls/MsgBox.cs b/src/BizHawk.Client.EmuHawk/CustomControls/MsgBox.cs index 1350eaa8923..6df4a811440 100644 --- a/src/BizHawk.Client.EmuHawk/CustomControls/MsgBox.cs +++ b/src/BizHawk.Client.EmuHawk/CustomControls/MsgBox.cs @@ -47,10 +47,7 @@ public MsgBox(string message, string title, MessageBoxIcon boxIcon) /// public DialogBoxResult DialogBoxResult { get; private set; } - public void SetMessageToAutoSize() - { - messageLbl.MaximumSize = new Size(MaximumSize.Width - _msgIcon.Width - UIHelper.ScaleX(25), MaximumSize.Height); - } + public void SetMessageToAutoSize() => messageLbl.MaximumSize = new Size(MaximumSize.Width - _msgIcon.Width - UIHelper.ScaleX(25), MaximumSize.Height); /// /// Create up to 3 buttons with given DialogResult values. diff --git a/src/BizHawk.Client.EmuHawk/CustomControls/ViewportPanel.cs b/src/BizHawk.Client.EmuHawk/CustomControls/ViewportPanel.cs index 1ef784db64b..d9a306d43ea 100644 --- a/src/BizHawk.Client.EmuHawk/CustomControls/ViewportPanel.cs +++ b/src/BizHawk.Client.EmuHawk/CustomControls/ViewportPanel.cs @@ -61,7 +61,7 @@ private void DoPaint() { if (_bmp != null) { - using Graphics g = CreateGraphics(); + using var g = CreateGraphics(); g.PixelOffsetMode = PixelOffsetMode.HighSpeed; g.InterpolationMode = InterpolationMode.NearestNeighbor; g.CompositingMode = CompositingMode.SourceCopy; @@ -74,7 +74,7 @@ private void DoPaint() } else { - using (var sb = new SolidBrush(Color.Black)) + using (SolidBrush sb = new(Color.Black)) { g.FillRectangle(sb, _bmp.Width, 0, Width - _bmp.Width, Height); g.FillRectangle(sb, 0, _bmp.Height, _bmp.Width, Height - _bmp.Height); @@ -116,7 +116,7 @@ private void CleanupDisposeQueue() } } - private readonly Queue _disposeQueue = new Queue(); + private readonly Queue _disposeQueue = new(); private void SignalPaint() { @@ -143,10 +143,7 @@ public void SetBitmap(Bitmap newBmp) /// bit of a hack; use at your own risk /// you probably shouldn't modify this? - public Bitmap GetBitmap() - { - return _bmp; - } + public Bitmap GetBitmap() => _bmp; protected override void OnPaintBackground(PaintEventArgs pevent) { diff --git a/src/BizHawk.Client.EmuHawk/DisplayManager/DisplayManager.cs b/src/BizHawk.Client.EmuHawk/DisplayManager/DisplayManager.cs index 802bc31b0dc..d7c42aa756a 100644 --- a/src/BizHawk.Client.EmuHawk/DisplayManager/DisplayManager.cs +++ b/src/BizHawk.Client.EmuHawk/DisplayManager/DisplayManager.cs @@ -62,7 +62,7 @@ protected override void UpdateSourceDrawingWork(JobInfo job) if (!job.Offscreen) { //apply the vsync setting (should probably try to avoid repeating this) - var vsync = GlobalConfig.VSyncThrottle || GlobalConfig.VSync; + bool vsync = GlobalConfig.VSyncThrottle || GlobalConfig.VSync; //ok, now this is a bit undesirable. //maybe the user wants vsync, but not vsync throttle. @@ -107,7 +107,7 @@ protected override void UpdateSourceDrawingWork(JobInfo job) _currentFilterProgram.RenderTargetProvider = new DisplayManagerRenderTargetProvider(size => _shaderChainFrugalizers[rtCounter++].Get(size)); _gl.BeginScene(); - RunFilterChainSteps(ref rtCounter, out var rtCurr, out var inFinalTarget); + RunFilterChainSteps(ref rtCounter, out var rtCurr, out bool inFinalTarget); _gl.EndScene(); if (job.Offscreen) diff --git a/src/BizHawk.Client.EmuHawk/EmuHawkUtil.cs b/src/BizHawk.Client.EmuHawk/EmuHawkUtil.cs index 9137c484d0f..ae9888a8818 100644 --- a/src/BizHawk.Client.EmuHawk/EmuHawkUtil.cs +++ b/src/BizHawk.Client.EmuHawk/EmuHawkUtil.cs @@ -16,14 +16,14 @@ public static class EmuHawkUtil public static string ResolveShortcut(string filename) { if (filename.Contains("|") || OSTailoredCode.IsUnixHost || !".lnk".Equals(Path.GetExtension(filename), StringComparison.OrdinalIgnoreCase)) return filename; // archive internal files are never shortcuts (and choke when analyzing any further) - var link = new ShellLinkImports.ShellLink(); + ShellLinkImports.ShellLink link = new(); const uint STGM_READ = 0; ((ShellLinkImports.IPersistFile) link).Load(filename, STGM_READ); #if false // TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files. ((ShellLinkImports.IShellLinkW) link).Resolve(hwnd, 0); #endif - var sb = new StringBuilder(Win32Imports.MAX_PATH); + StringBuilder sb = new(Win32Imports.MAX_PATH); ((ShellLinkImports.IShellLinkW) link).GetPath(sb, sb.Capacity, out _, 0); return sb.Length == 0 ? filename : sb.ToString(); // maybe? what if it's invalid? } diff --git a/src/BizHawk.Client.EmuHawk/Extensions/ControlExtensions.cs b/src/BizHawk.Client.EmuHawk/Extensions/ControlExtensions.cs index 5de92d53080..b458970e734 100644 --- a/src/BizHawk.Client.EmuHawk/Extensions/ControlExtensions.cs +++ b/src/BizHawk.Client.EmuHawk/Extensions/ControlExtensions.cs @@ -38,7 +38,7 @@ public static void BeginInvoke(this Control control, Action action) public static ToolStripMenuItem ToColumnsMenu(this InputRoll inputRoll, Action changeCallback) { - var menu = new ToolStripMenuItem + ToolStripMenuItem menu = new() { Name = "GeneratedColumnsSubMenu", Text = "Columns" @@ -48,7 +48,7 @@ public static ToolStripMenuItem ToColumnsMenu(this InputRoll inputRoll, Action c foreach (var column in columns) { - var menuItem = new ToolStripMenuItem + ToolStripMenuItem menuItem = new() { Name = column.Name, Text = $"{column.Text} ({column.Name})", @@ -59,7 +59,7 @@ public static ToolStripMenuItem ToColumnsMenu(this InputRoll inputRoll, Action c menuItem.CheckedChanged += (o, ev) => { - var sender = (ToolStripMenuItem)o; + ToolStripMenuItem sender = (ToolStripMenuItem)o; columns.Find(c => c.Name == (string)sender.Tag).Visible = sender.Checked; columns.ColumnsChanged(); changeCallback(); @@ -72,14 +72,11 @@ public static ToolStripMenuItem ToColumnsMenu(this InputRoll inputRoll, Action c return menu; } - public static Point ChildPointToScreen(this Control control, Control child) - { - return control.PointToScreen(new Point(child.Location.X, child.Location.Y)); - } + public static Point ChildPointToScreen(this Control control, Control child) => control.PointToScreen(new Point(child.Location.X, child.Location.Y)); public static Color Add(this Color color, int val) { - var col = color.ToArgb(); + int col = color.ToArgb(); col += val; return Color.FromArgb(col); } @@ -92,10 +89,10 @@ public static Color Add(this Color color, int val) public static T Clone(this T controlToClone) where T : Control { - PropertyInfo[] controlProperties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); + var controlProperties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); - Type t = controlToClone.GetType(); - var instance = (T) Activator.CreateInstance(t); + var t = controlToClone.GetType(); + T instance = (T) Activator.CreateInstance(t); t.GetProperty("AutoSize")?.SetMethod?.Invoke(instance, new object[] {false}); @@ -108,7 +105,7 @@ public static T Clone(this T controlToClone) continue; } - if (propInfo.Name != "AutoSize" && propInfo.Name != "WindowTarget") + if (propInfo.Name is not "AutoSize" and not "WindowTarget") { propInfo.SetValue(instance, propInfo.GetValue(controlToClone, null), null); } @@ -129,10 +126,7 @@ public static T Clone(this T controlToClone) public static IEnumerable Controls(this Control control) => control.Controls.Cast(); - public static IEnumerable TabPages(this TabControl tabControl) - { - return tabControl.TabPages.Cast(); - } + public static IEnumerable TabPages(this TabControl tabControl) => tabControl.TabPages.Cast(); public static void ReplaceDropDownItems(this ToolStripDropDownItem menu, params ToolStripItem[] items) { @@ -154,7 +148,7 @@ public static string CopyItemsAsText(this ListView listViewControl) return ""; } - var sb = new StringBuilder(); + StringBuilder sb = new(); // walk over each selected item and subitem within it to generate a string from it foreach (int index in indexes) @@ -191,8 +185,8 @@ public static void SetSortIcon(this ListView listViewControl, int columnIndex, S var columnHeader = Win32Imports.SendMessage(listViewControl.Handle, LVM_GETHEADER, IntPtr.Zero, IntPtr.Zero); for (int columnNumber = 0, l = listViewControl.Columns.Count; columnNumber < l; columnNumber++) { - var columnPtr = new IntPtr(columnNumber); - var item = new Win32Imports.HDITEM { mask = Win32Imports.HDITEM.Mask.Format }; + IntPtr columnPtr = new(columnNumber); + Win32Imports.HDITEM item = new() { mask = Win32Imports.HDITEM.Mask.Format }; if (Win32Imports.SendMessage(columnHeader, HDM_GETITEM, columnPtr, ref item) == IntPtr.Zero) throw new Win32Exception(); if (columnNumber != columnIndex || order == SortOrder.None) { @@ -212,10 +206,7 @@ public static void SetSortIcon(this ListView listViewControl, int columnIndex, S } } - public static bool IsOk(this DialogResult dialogResult) - { - return dialogResult == DialogResult.OK; - } + public static bool IsOk(this DialogResult dialogResult) => dialogResult == DialogResult.OK; /// /// Sets the desired effect if data is present, else None @@ -229,8 +220,8 @@ public static void Set(this DragEventArgs e, DragDropEffects effect) public static Bitmap ToBitMap(this Control control) { - var b = new Bitmap(control.Width, control.Height); - var rect = new Rectangle(new Point(0, 0), control.Size); + Bitmap b = new(control.Width, control.Height); + Rectangle rect = new(new Point(0, 0), control.Size); control.DrawToBitmap(b, rect); return b; } @@ -243,7 +234,7 @@ public static void ToClipBoard(this Bitmap bitmap) public static void SaveAsFile(this Bitmap bitmap, IGameInfo game, string suffix, string systemId, PathEntryCollection paths, IDialogParent parent) { - var result = parent.ShowFileSaveDialog( + string? result = parent.ShowFileSaveDialog( discardCWDChange: true, filter: FilesystemFilterSet.Screenshots, initDir: paths.ScreenshotAbsolutePathFor(systemId), @@ -251,7 +242,7 @@ public static void SaveAsFile(this Bitmap bitmap, IGameInfo game, string suffix, if (result is null) return; FileInfo file = new(result); string extension = file.Extension.ToUpperInvariant(); - ImageFormat i = extension switch + var i = extension switch { ".BMP" => ImageFormat.Bmp, _ => ImageFormat.Png, @@ -301,7 +292,7 @@ public static void AdjustDescriptionHeightToFit(this PropertyGrid grid) foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(grid.SelectedObject)) { - var s = property.Description; + string s = property.Description; if (s != null && s.Length > maxLength) { maxLength = s.Length; diff --git a/src/BizHawk.Client.EmuHawk/Extensions/ToolExtensions.cs b/src/BizHawk.Client.EmuHawk/Extensions/ToolExtensions.cs index e394e6940f6..36821884791 100644 --- a/src/BizHawk.Client.EmuHawk/Extensions/ToolExtensions.cs +++ b/src/BizHawk.Client.EmuHawk/Extensions/ToolExtensions.cs @@ -23,16 +23,16 @@ public static ToolStripItem[] RecentMenu( bool noAutoload = false, bool romLoading = false) { - var items = new List(); + List items = new(); if (recent.Empty) { - var none = new ToolStripMenuItem { Enabled = false, Text = "None" }; + ToolStripMenuItem none = new() { Enabled = false, Text = "None" }; items.Add(none); } else { - foreach (var filename in recent) + foreach (string filename in recent) { string caption = filename; string path = filename; @@ -57,7 +57,7 @@ public static ToolStripItem[] RecentMenu( } // TODO - do TSMI and TSDD need disposing? yuck - var item = new ToolStripMenuItem { Text = caption.Replace("&", "&&") }; + ToolStripMenuItem item = new() { Text = caption.Replace("&", "&&") }; items.Add(item); item.Click += (o, ev) => @@ -65,19 +65,19 @@ public static ToolStripItem[] RecentMenu( loadFileCallback(path); }; - var tsdd = new ToolStripDropDownMenu(); + ToolStripDropDownMenu tsdd = new(); if (crazyStuff) { //TODO - use standard methods to split filename (hawkfile acquire?) - var hf = new HawkFile(physicalPath ?? throw new Exception("this will probably never appear but I can't be bothered checking --yoshi"), delayIOAndDearchive: true); + HawkFile hf = new(physicalPath ?? throw new Exception("this will probably never appear but I can't be bothered checking --yoshi"), delayIOAndDearchive: true); bool canExplore = File.Exists(hf.FullPathWithoutMember); if (canExplore) { //make a menuitem to show the last modified timestamp var timestamp = File.GetLastWriteTime(hf.FullPathWithoutMember); - var tsmiTimestamp = new ToolStripLabel { Text = timestamp.ToString(DateTimeFormatInfo.InvariantInfo) }; + ToolStripLabel tsmiTimestamp = new() { Text = timestamp.ToString(DateTimeFormatInfo.InvariantInfo) }; tsdd.Items.Add(tsmiTimestamp); tsdd.Items.Add(new ToolStripSeparator()); @@ -85,22 +85,22 @@ public static ToolStripItem[] RecentMenu( if (hf.IsArchive) { //make a menuitem to let you copy the path - var tsmiCopyCanonicalPath = new ToolStripMenuItem { Text = "&Copy Canonical Path" }; + ToolStripMenuItem tsmiCopyCanonicalPath = new() { Text = "&Copy Canonical Path" }; tsmiCopyCanonicalPath.Click += (o, ev) => { Clipboard.SetText(physicalPath); }; tsdd.Items.Add(tsmiCopyCanonicalPath); - var tsmiCopyArchivePath = new ToolStripMenuItem { Text = "Copy Archive Path" }; + ToolStripMenuItem tsmiCopyArchivePath = new() { Text = "Copy Archive Path" }; tsmiCopyArchivePath.Click += (o, ev) => { Clipboard.SetText(hf.FullPathWithoutMember); }; tsdd.Items.Add(tsmiCopyArchivePath); - var tsmiOpenArchive = new ToolStripMenuItem { Text = "Open &Archive" }; + ToolStripMenuItem tsmiOpenArchive = new() { Text = "Open &Archive" }; tsmiOpenArchive.Click += (o, ev) => { System.Diagnostics.Process.Start(hf.FullPathWithoutMember); }; tsdd.Items.Add(tsmiOpenArchive); } else { // make a menuitem to let you copy the path - var tsmiCopyPath = new ToolStripMenuItem { Text = "&Copy Path" }; + ToolStripMenuItem tsmiCopyPath = new() { Text = "&Copy Path" }; tsmiCopyPath.Click += (o, ev) => { Clipboard.SetText(physicalPath); }; tsdd.Items.Add(tsmiCopyPath); } @@ -108,13 +108,13 @@ public static ToolStripItem[] RecentMenu( tsdd.Items.Add(new ToolStripSeparator()); // make a menuitem to let you explore to it - var tsmiExplore = new ToolStripMenuItem { Text = "&Explore" }; + ToolStripMenuItem tsmiExplore = new() { Text = "&Explore" }; string explorePath = $"\"{hf.FullPathWithoutMember}\""; tsmiExplore.Click += (o, ev) => { System.Diagnostics.Process.Start("explorer.exe", $"/select, {explorePath}"); }; tsdd.Items.Add(tsmiExplore); - var tsmiCopyFile = new ToolStripMenuItem { Text = "Copy &File" }; - var lame = new System.Collections.Specialized.StringCollection + ToolStripMenuItem tsmiCopyFile = new() { Text = "Copy &File" }; + System.Collections.Specialized.StringCollection lame = new() { hf.FullPathWithoutMember }; @@ -124,10 +124,10 @@ public static ToolStripItem[] RecentMenu( if (!OSTailoredCode.IsUnixHost) { - var tsmiTest = new ToolStripMenuItem { Text = "&Shell Context Menu" }; + ToolStripMenuItem tsmiTest = new() { Text = "&Shell Context Menu" }; tsmiTest.Click += (o, ev) => { - var tsddi = (ToolStripDropDownItem)o; + ToolStripDropDownItem tsddi = (ToolStripDropDownItem)o; tsddi.Owner.Update(); Win32ShellContextMenu.ShowContextMenu(hf.FullPathWithoutMember, tsddi.Owner.Handle, tsddi.Owner.Location.X, tsddi.Owner.Location.Y); }; @@ -139,7 +139,7 @@ public static ToolStripItem[] RecentMenu( else { //make a menuitem to show the last modified timestamp - var tsmiMissingFile = new ToolStripLabel { Text = "-Missing-" }; + ToolStripLabel tsmiMissingFile = new() { Text = "-Missing-" }; tsdd.Items.Add(tsmiMissingFile); tsdd.Items.Add(new ToolStripSeparator()); } @@ -147,7 +147,7 @@ public static ToolStripItem[] RecentMenu( } //crazystuff //in any case, make a menuitem to let you remove the item - var tsmiRemovePath = new ToolStripMenuItem { Text = "&Remove" }; + ToolStripMenuItem tsmiRemovePath = new() { Text = "&Remove" }; tsmiRemovePath.Click += (o, ev) => { recent.Remove(path); }; @@ -181,11 +181,11 @@ public static ToolStripItem[] RecentMenu( items.Add(new ToolStripSeparator()); - var clearItem = new ToolStripMenuItem { Text = "&Clear", Enabled = !recent.Frozen }; + ToolStripMenuItem clearItem = new() { Text = "&Clear", Enabled = !recent.Frozen }; clearItem.Click += (o, ev) => recent.Clear(); items.Add(clearItem); - var freezeItem = new ToolStripMenuItem + ToolStripMenuItem freezeItem = new() { Text = recent.Frozen ? "&Unfreeze" : "&Freeze", Image = recent.Frozen ? Properties.Resources.Unfreeze : Properties.Resources.Freeze @@ -195,22 +195,22 @@ public static ToolStripItem[] RecentMenu( if (!noAutoload) { - var auto = new ToolStripMenuItem { Text = $"&Autoload {entrySemantic}", Checked = recent.AutoLoad }; + ToolStripMenuItem auto = new() { Text = $"&Autoload {entrySemantic}", Checked = recent.AutoLoad }; auto.Click += (o, ev) => recent.ToggleAutoLoad(); items.Add(auto); } - var settingsItem = new ToolStripMenuItem { Text = "&Recent Settings..." }; + ToolStripMenuItem settingsItem = new() { Text = "&Recent Settings..." }; settingsItem.Click += (o, ev) => { - using var prompt = new InputPrompt + using InputPrompt prompt = new() { TextInputType = InputPrompt.InputType.Unsigned, Message = "Number of recent files to track", InitialValue = recent.MAX_RECENT_FILES.ToString() }; if (!mainForm.ShowDialogWithTempMute(prompt).IsOk()) return; - var val = int.Parse(prompt.PromptText); + int val = int.Parse(prompt.PromptText); if (val > 0) recent.MAX_RECENT_FILES = val; }; items.Add(settingsItem); @@ -242,8 +242,8 @@ public static IEnumerable MenuItems(this IMemoryDomains domains, { foreach (var domain in domains) { - var name = domain.Name; - var item = new ToolStripMenuItem + string name = domain.Name; + ToolStripMenuItem item = new() { Text = name, Enabled = !(maxSize.HasValue && domain.Size > maxSize.Value), diff --git a/src/BizHawk.Client.EmuHawk/Input/Input.cs b/src/BizHawk.Client.EmuHawk/Input/Input.cs index 7acc6246a77..565ee62b29d 100644 --- a/src/BizHawk.Client.EmuHawk/Input/Input.cs +++ b/src/BizHawk.Client.EmuHawk/Input/Input.cs @@ -25,7 +25,7 @@ public void ControlInputFocus(Control c, ClientInputFocus types, bool wants) if (types.HasFlag(ClientInputFocus.Mouse) && !wants) _wantingMouseFocus.Remove(c); } - private readonly HashSet _wantingMouseFocus = new HashSet(); + private readonly HashSet _wantingMouseFocus = new(); public static Input Instance { get; set; } @@ -63,9 +63,9 @@ internal Input(IntPtr mainFormHandle, Func getConfigCallback, Func _lastState = new WorkingDictionary(); - private readonly WorkingDictionary _axisValues = new WorkingDictionary(); - private readonly WorkingDictionary _axisDeltas = new WorkingDictionary(); + private readonly WorkingDictionary _lastState = new(); + private readonly WorkingDictionary _axisValues = new(); + private readonly WorkingDictionary _axisDeltas = new(); private bool _trackDeltas; private bool _ignoreEventsNextPoll; @@ -100,9 +100,9 @@ public void UpdateModifierKeysEffective() private void HandleButton(string button, bool newState, ClientInputFocus source) { - if (!(_currentConfig.MergeLAndRModifierKeys && ModifierKeyPreMap.TryGetValue(button, out var button1))) button1 = button; - var modIndex = _currentConfig.ModifierKeysEffective.IndexOf(button1); - var currentModifier = modIndex is -1 ? 0U : 1U << modIndex; + if (!(_currentConfig.MergeLAndRModifierKeys && ModifierKeyPreMap.TryGetValue(button, out string button1))) button1 = button; + int modIndex = _currentConfig.ModifierKeysEffective.IndexOf(button1); + uint currentModifier = modIndex is -1 ? 0U : 1U << modIndex; if (EnableIgnoreModifiers && currentModifier is not 0U) return; if (newState == _lastState[button1]) return; @@ -115,18 +115,18 @@ private void HandleButton(string button, bool newState, ClientInputFocus source) } // don't generate events for things like Ctrl+LeftControl - var mods = _modifiers; + uint mods = _modifiers; if (!newState) mods = 0; // don't set mods for release events, handle releasing all corresponding buttons later in InputCoalescer.Receive() else if (currentModifier is not 0U) mods &= ~currentModifier; - var ie = new InputEvent - { - EventType = newState ? InputEventType.Press : InputEventType.Release, - LogicalButton = new(button1, mods, () => _getConfigCallback().ModifierKeysEffective), - Source = source - }; + InputEvent ie = new() + { + EventType = newState ? InputEventType.Press : InputEventType.Release, + LogicalButton = new(button1, mods, () => _getConfigCallback().ModifierKeysEffective), + Source = source + }; _lastState[button1] = newState; if (!_ignoreEventsNextPoll) @@ -142,7 +142,7 @@ private void HandleAxis(string axis, int newValue) } private uint _modifiers; - private readonly List _newEvents = new List(); + private readonly List _newEvents = new(); public void ClearEvents() { @@ -154,7 +154,7 @@ public void ClearEvents() } } - private readonly Queue _inputEvents = new Queue(); + private readonly Queue _inputEvents = new(); public InputEvent DequeueEvent() { lock (this) @@ -250,7 +250,7 @@ private void UpdateThreadProc() if (_newEvents.Count != 0) { //WHAT!? WE SHOULD NOT BE SO NAIVELY TOUCHING MAINFORM FROM THE INPUTTHREAD. ITS BUSY RUNNING. - AllowInput allowInput = MainFormInputAllowedCallback(false); + var allowInput = MainFormInputAllowedCallback(false); foreach (var ie in _newEvents) { @@ -272,10 +272,7 @@ private void UpdateThreadProc() } } - private static bool ShouldSwallow(AllowInput allowInput, InputEvent inputEvent) - { - return allowInput == AllowInput.None || (allowInput == AllowInput.OnlyController && inputEvent.Source != ClientInputFocus.Pad); - } + private static bool ShouldSwallow(AllowInput allowInput, InputEvent inputEvent) => allowInput == AllowInput.None || (allowInput == AllowInput.OnlyController && inputEvent.Source != ClientInputFocus.Pad); public void StartListeningForAxisEvents() { @@ -320,7 +317,7 @@ public string GetNextBindEvent(ref InputEvent lastPress) lock (this) { if (_inputEvents.Count == 0) return null; - AllowInput allowInput = MainFormInputAllowedCallback(false); + var allowInput = MainFormInputAllowedCallback(false); //wait for the first release after a press to complete input binding, because we need to distinguish pure modifierkeys from modified keys //if you just pressed ctrl, wanting to bind ctrl, we'd see: pressed:ctrl, unpressed:ctrl @@ -329,7 +326,7 @@ public string GetNextBindEvent(ref InputEvent lastPress) while (_inputEvents.Count != 0) { - InputEvent ie = DequeueEvent(); + var ie = DequeueEvent(); if (ShouldSwallow(allowInput, ie)) continue; diff --git a/src/BizHawk.Client.EmuHawk/JumpLists.cs b/src/BizHawk.Client.EmuHawk/JumpLists.cs index 8d628c90145..c407c34816d 100644 --- a/src/BizHawk.Client.EmuHawk/JumpLists.cs +++ b/src/BizHawk.Client.EmuHawk/JumpLists.cs @@ -13,13 +13,13 @@ static JumpLists() { try { - var presentationFramework = + Assembly 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); + object app = Activator.CreateInstance(application); dynamic jmp = Activator.CreateInstance(JumpList); jmp.ShowRecentCategory = true; JumpList diff --git a/src/BizHawk.Client.EmuHawk/LogWindow.cs b/src/BizHawk.Client.EmuHawk/LogWindow.cs index 8f417a4c602..3da76dd5fc6 100644 --- a/src/BizHawk.Client.EmuHawk/LogWindow.cs +++ b/src/BizHawk.Client.EmuHawk/LogWindow.cs @@ -21,7 +21,7 @@ public static Icon ToolIcon // TODO: only show add to game db when this is a Rom details dialog // Let user decide what type (instead of always adding it as a good dump) - private readonly List _lines = new List(); + private readonly List _lines = new(); private LogWriter _logWriter; [RequiredService] @@ -65,10 +65,10 @@ private void Detach() public void ShowReport(string title, string report) { - var ss = report.Split('\n'); + string[] ss = report.Split('\n'); lock (_lines) - foreach (var s in ss) + foreach (string s in ss) { _lines.Add(s.TrimEnd('\r')); } @@ -81,8 +81,8 @@ public void ShowReport(string title, string report) private void append(string str, bool invoked) { - var ss = str.Split('\n'); - foreach (var s in ss) + string[] ss = str.Split('\n'); + foreach (string s in ss) { if (!string.IsNullOrWhiteSpace(s)) { @@ -107,10 +107,7 @@ private void doUpdateListSize() virtualListView1.EnsureVisible(_lines.Count - 1); } - private void appendInvoked(string str) - { - append(str, true); - } + private void appendInvoked(string str) => append(str, true); private void BtnClear_Click(object sender, EventArgs e) { @@ -122,25 +119,13 @@ private void BtnClear_Click(object sender, EventArgs e) } } - private void BtnClose_Click(object sender, EventArgs e) - { - Close(); - } + private void BtnClose_Click(object sender, EventArgs e) => Close(); - private void LogWindow_Load(object sender, EventArgs e) - { - HideShowGameDbButton(); - } + private void LogWindow_Load(object sender, EventArgs e) => HideShowGameDbButton(); - private void ListView_QueryItemText(object sender, RetrieveVirtualItemEventArgs e) - { - e.Item = new ListViewItem(_lines[e.ItemIndex]); - } + private void ListView_QueryItemText(object sender, RetrieveVirtualItemEventArgs e) => e.Item = new ListViewItem(_lines[e.ItemIndex]); - private void ListView_ClientSizeChanged(object sender, EventArgs e) - { - virtualListView1.Columns[0].Width = virtualListView1.ClientSize.Width; - } + private void ListView_ClientSizeChanged(object sender, EventArgs e) => virtualListView1.Columns[0].Width = virtualListView1.ClientSize.Width; private void ListView_KeyDown(object sender, KeyEventArgs e) { @@ -178,9 +163,9 @@ private void ButtonCopy_Click(object sender, EventArgs e) private void ButtonCopyAll_Click(object sender, EventArgs e) { - var sb = new StringBuilder(); + StringBuilder sb = new(); lock(_lines) - foreach (var s in _lines) + foreach (string s in _lines) sb.AppendLine(s); if (sb.Length > 0) Clipboard.SetText(sb.ToString(), TextDataFormat.Text); @@ -194,7 +179,7 @@ private void HideShowGameDbButton() private void AddToGameDbBtn_Click(object sender, EventArgs e) { - using var picker = new RomStatusPicker(); + using RomStatusPicker picker = new(); var result = picker.ShowDialog(); if (result.IsOk()) { @@ -208,10 +193,7 @@ private void AddToGameDbBtn_Click(object sender, EventArgs e) private class LogWriter : TextWriter { - public override void Write(char[] buffer, int offset, int count) - { - Emit(new string(buffer, offset, count)); - } + public override void Write(char[] buffer, int offset, int count) => Emit(new string(buffer, offset, count)); public override Encoding Encoding => Encoding.Unicode; diff --git a/src/BizHawk.Client.EmuHawk/MainForm.Debug.cs b/src/BizHawk.Client.EmuHawk/MainForm.Debug.cs index 65726907520..6299138a18f 100644 --- a/src/BizHawk.Client.EmuHawk/MainForm.Debug.cs +++ b/src/BizHawk.Client.EmuHawk/MainForm.Debug.cs @@ -77,11 +77,11 @@ private void AddDebugMenu() }; debugMenu.DropDownOpened += (ddoSender, _) => { - var sysID = Emulator.SystemId; - var coreName = Emulator.Attributes().CoreName; + string sysID = Emulator.SystemId; + string coreName = Emulator.Attributes().CoreName; foreach (var item in ((ToolStripMenuItemEx) ddoSender).DropDownItems.OfType()) { - var groupEnabled = item.SysIDs.Contains(sysID); + bool groupEnabled = item.SysIDs.Contains(sysID); foreach (var child in item.DropDownItems.Cast().Where(static child => child.RequiresLoadedRom)) // RequiresLoadedRom == false => leave Enabled as default true { child.Enabled = groupEnabled && (child.RequiresCore is null || child.RequiresCore == coreName); diff --git a/src/BizHawk.Client.EmuHawk/MainForm.Events.cs b/src/BizHawk.Client.EmuHawk/MainForm.Events.cs index 1d305ffe711..67d63839d19 100644 --- a/src/BizHawk.Client.EmuHawk/MainForm.Events.cs +++ b/src/BizHawk.Client.EmuHawk/MainForm.Events.cs @@ -103,7 +103,7 @@ private void FileSubMenu_DropDownOpened(object sender, EventArgs e) CloseRomMenuItem.Enabled = !Emulator.IsNull(); - var hasSaveRam = Emulator.HasSaveRam(); + bool hasSaveRam = Emulator.HasSaveRam(); bool needBold = hasSaveRam && Emulator.AsSaveRam().SaveRamModified; SaveRAMSubMenu.Enabled = hasSaveRam; @@ -207,10 +207,7 @@ private void SaveSlotSubMenu_DropDownOpened(object sender, EventArgs e) SelectSlot0MenuItem.Checked = Config.SaveSlot is 10; } - private void SaveRamSubMenu_DropDownOpened(object sender, EventArgs e) - { - FlushSaveRAMMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Flush SaveRAM"]; - } + private void SaveRamSubMenu_DropDownOpened(object sender, EventArgs e) => FlushSaveRAMMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Flush SaveRAM"]; private void MovieSubMenu_DropDownOpened(object sender, EventArgs e) { @@ -291,19 +288,16 @@ private void ScreenshotSubMenu_DropDownOpening(object sender, EventArgs e) ScreenshotClientClipboardMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Screen Client to Clipboard"]; } - private void OpenRomMenuItem_Click(object sender, EventArgs e) - { - OpenRom(); - } + private void OpenRomMenuItem_Click(object sender, EventArgs e) => OpenRom(); private void OpenAdvancedMenuItem_Click(object sender, EventArgs e) { - using var oac = new OpenAdvancedChooser(this, Config, CreateCoreComm, Game, RunLibretroCoreChooser); + using OpenAdvancedChooser oac = new(this, Config, CreateCoreComm, Game, RunLibretroCoreChooser); if (this.ShowDialogWithTempMute(oac) == DialogResult.Cancel) return; if (oac.Result == AdvancedRomLoaderType.LibretroLaunchNoGame) { - var argsNoGame = new LoadRomArgs + LoadRomArgs argsNoGame = new() { OpenAdvanced = new OpenAdvanced_LibretroNoGame(Config.LibretroCore) }; @@ -311,7 +305,7 @@ private void OpenAdvancedMenuItem_Click(object sender, EventArgs e) return; } - var args = new LoadRomArgs(); + LoadRomArgs args = new(); var filter = RomLoader.RomFilter; @@ -333,7 +327,7 @@ private void OpenAdvancedMenuItem_Click(object sender, EventArgs e) { throw new InvalidOperationException("Automatic Alpha Sanitizer"); } - var result = this.ShowFileOpenDialog( + string result = this.ShowFileOpenDialog( filter: filter, filterIndex: ref _lastOpenRomFilter, initDir: Config.PathEntries.RomAbsolutePath(Emulator.SystemId), @@ -361,14 +355,8 @@ private void QuickLoadstateMenuItem_Click(object sender, EventArgs e) private void LoadNamedStateMenuItem_Click(object sender, EventArgs e) => LoadStateAs(); - private void AutoloadLastSlotMenuItem_Click(object sender, EventArgs e) - { - Config.AutoLoadLastSaveSlot ^= true; - } - private void AutosaveLastSlotMenuItem_Click(object sender, EventArgs e) - { - Config.AutoSaveLastSaveSlot ^= true; - } + private void AutoloadLastSlotMenuItem_Click(object sender, EventArgs e) => Config.AutoLoadLastSaveSlot ^= true; + private void AutosaveLastSlotMenuItem_Click(object sender, EventArgs e) => Config.AutoSaveLastSaveSlot ^= true; private void SelectSlotMenuItems_Click(object sender, EventArgs e) { @@ -387,15 +375,9 @@ private void SelectSlotMenuItems_Click(object sender, EventArgs e) SaveSlotSelectedMessage(); } - private void PreviousSlotMenuItem_Click(object sender, EventArgs e) - { - PreviousSlot(); - } + private void PreviousSlotMenuItem_Click(object sender, EventArgs e) => PreviousSlot(); - private void NextSlotMenuItem_Click(object sender, EventArgs e) - { - NextSlot(); - } + private void NextSlotMenuItem_Click(object sender, EventArgs e) => NextSlot(); private void SaveToCurrentSlotMenuItem_Click(object sender, EventArgs e) => SavestateCurrentSlot(); @@ -409,22 +391,16 @@ private void LoadCurrentSlotMenuItem_Click(object sender, EventArgs e) private bool LoadstateCurrentSlot() => LoadQuickSave(Config.SaveSlot); - private void FlushSaveRAMMenuItem_Click(object sender, EventArgs e) - { - FlushSaveRAM(); - } + private void FlushSaveRAMMenuItem_Click(object sender, EventArgs e) => FlushSaveRAM(); - private void ReadonlyMenuItem_Click(object sender, EventArgs e) - { - ToggleReadOnly(); - } + private void ReadonlyMenuItem_Click(object sender, EventArgs e) => ToggleReadOnly(); private void RecordMovieMenuItem_Click(object sender, EventArgs e) { if (Game.IsNullInstance()) return; if (!Emulator.Attributes().Released) { - var result = this.ModalMessageBox2( + bool result = this.ModalMessageBox2( "Thanks for using BizHawk! The emulation core you have selected " + "is currently BETA-status. We appreciate your help in testing BizHawk. " + "You can record a movie on this core if you'd like to, but expect to " @@ -440,7 +416,7 @@ private void RecordMovieMenuItem_Click(object sender, EventArgs e) // Nag user to user a more accurate core, but let them continue anyway EnsureCoreIsAccurate(); - using var form = new RecordMovie(this, Config, Game, Emulator, MovieSession, FirmwareManager); + using RecordMovie form = new(this, Config, Game, Emulator, MovieSession, FirmwareManager); this.ShowDialogWithTempMute(form); } @@ -454,14 +430,11 @@ private string CanProvideFirmware(FirmwareID id, string hash) private void PlayMovieMenuItem_Click(object sender, EventArgs e) { - using var form = new PlayMovie(this, Config, Game, Emulator, MovieSession, CanProvideFirmware); + using PlayMovie form = new(this, Config, Game, Emulator, MovieSession, CanProvideFirmware); this.ShowDialogWithTempMute(form); } - private void StopMovieMenuItem_Click(object sender, EventArgs e) - { - StopMovie(); - } + private void StopMovieMenuItem_Click(object sender, EventArgs e) => StopMovie(); private void PlayFromBeginningMenuItem_Click(object sender, EventArgs e) => _ = RestartMovie(); @@ -472,17 +445,14 @@ private void ImportMovieMenuItem_Click(object sender, EventArgs e) discardCWDChange: false, filter: MovieImport.AvailableImporters, initDir: Config.PathEntries.RomAbsolutePath(Emulator.SystemId)); - if (result is not null) foreach (var fn in result) ProcessMovieImport(fn, false); + if (result is not null) foreach (string fn in result) ProcessMovieImport(fn, false); } - private void SaveMovieMenuItem_Click(object sender, EventArgs e) - { - SaveMovie(); - } + private void SaveMovieMenuItem_Click(object sender, EventArgs e) => SaveMovie(); private void SaveMovieAsMenuItem_Click(object sender, EventArgs e) { - var filename = MovieSession.Movie.Filename; + string filename = MovieSession.Movie.Filename; if (string.IsNullOrWhiteSpace(filename)) { filename = Game.FilesystemSafeName(); @@ -512,35 +482,17 @@ private void StopMovieWithoutSavingMenuItem_Click(object sender, EventArgs e) StopMovie(saveChanges: false); } - private void AutomaticMovieBackupMenuItem_Click(object sender, EventArgs e) - { - Config.Movies.EnableBackupMovies ^= true; - } + private void AutomaticMovieBackupMenuItem_Click(object sender, EventArgs e) => Config.Movies.EnableBackupMovies ^= true; - private void FullMovieLoadstatesMenuItem_Click(object sender, EventArgs e) - { - Config.Movies.VBAStyleMovieLoadState ^= true; - } + private void FullMovieLoadstatesMenuItem_Click(object sender, EventArgs e) => Config.Movies.VBAStyleMovieLoadState ^= true; - private void MovieEndFinishMenuItem_Click(object sender, EventArgs e) - { - Config.Movies.MovieEndAction = MovieEndAction.Finish; - } + private void MovieEndFinishMenuItem_Click(object sender, EventArgs e) => Config.Movies.MovieEndAction = MovieEndAction.Finish; - private void MovieEndRecordMenuItem_Click(object sender, EventArgs e) - { - Config.Movies.MovieEndAction = MovieEndAction.Record; - } + private void MovieEndRecordMenuItem_Click(object sender, EventArgs e) => Config.Movies.MovieEndAction = MovieEndAction.Record; - private void MovieEndStopMenuItem_Click(object sender, EventArgs e) - { - Config.Movies.MovieEndAction = MovieEndAction.Stop; - } + private void MovieEndStopMenuItem_Click(object sender, EventArgs e) => Config.Movies.MovieEndAction = MovieEndAction.Stop; - private void MovieEndPauseMenuItem_Click(object sender, EventArgs e) - { - Config.Movies.MovieEndAction = MovieEndAction.Pause; - } + private void MovieEndPauseMenuItem_Click(object sender, EventArgs e) => Config.Movies.MovieEndAction = MovieEndAction.Pause; private void ConfigAndRecordAVMenuItem_Click(object sender, EventArgs e) { @@ -552,15 +504,9 @@ private void ConfigAndRecordAVMenuItem_Click(object sender, EventArgs e) RecordAv(); } - private void RecordAVMenuItem_Click(object sender, EventArgs e) - { - RecordAv(null, null); // force unattended, but allow traditional setup - } + private void RecordAVMenuItem_Click(object sender, EventArgs e) => RecordAv(null, null); // force unattended, but allow traditional setup - private void StopAVMenuItem_Click(object sender, EventArgs e) - { - StopAv(); - } + private void StopAVMenuItem_Click(object sender, EventArgs e) => StopAv(); private void CaptureOSDMenuItem_Click(object sender, EventArgs e) { @@ -578,35 +524,23 @@ private void CaptureLuaMenuItem_Click(object sender, EventArgs e) Config.AviCaptureOsd = false; } - private void ScreenshotMenuItem_Click(object sender, EventArgs e) - { - TakeScreenshot(); - } + private void ScreenshotMenuItem_Click(object sender, EventArgs e) => TakeScreenshot(); private void ScreenshotAsMenuItem_Click(object sender, EventArgs e) { var (dir, file) = $"{ScreenshotPrefix()}.{DateTime.Now:yyyy-MM-dd HH.mm.ss}.png".SplitPathToDirAndFile(); - var result = this.ShowFileSaveDialog( + string result = this.ShowFileSaveDialog( filter: ScreenshotsFSFilterSet, initDir: dir, initFileName: file); if (result is not null) TakeScreenshot(result); } - private void ScreenshotClipboardMenuItem_Click(object sender, EventArgs e) - { - TakeScreenshotToClipboard(); - } + private void ScreenshotClipboardMenuItem_Click(object sender, EventArgs e) => TakeScreenshotToClipboard(); - private void ScreenshotClientClipboardMenuItem_Click(object sender, EventArgs e) - { - TakeScreenshotClientToClipboard(); - } + private void ScreenshotClientClipboardMenuItem_Click(object sender, EventArgs e) => TakeScreenshotClientToClipboard(); - private void ScreenshotCaptureOSDMenuItem_Click(object sender, EventArgs e) - { - Config.ScreenshotCaptureOsd ^= true; - } + private void ScreenshotCaptureOSDMenuItem_Click(object sender, EventArgs e) => Config.ScreenshotCaptureOsd ^= true; private void ExitMenuItem_Click(object sender, EventArgs e) { @@ -652,20 +586,11 @@ private void PauseMenuItem_Click(object sender, EventArgs e) TogglePause(); } - private void PowerMenuItem_Click(object sender, EventArgs e) - { - RebootCore(); - } + private void PowerMenuItem_Click(object sender, EventArgs e) => RebootCore(); - private void SoftResetMenuItem_Click(object sender, EventArgs e) - { - SoftReset(); - } + private void SoftResetMenuItem_Click(object sender, EventArgs e) => SoftReset(); - private void HardResetMenuItem_Click(object sender, EventArgs e) - { - HardReset(); - } + private void HardResetMenuItem_Click(object sender, EventArgs e) => HardReset(); private void ViewSubMenu_DropDownOpened(object sender, EventArgs e) { @@ -733,40 +658,19 @@ private void WindowSize_Click(object sender, EventArgs e) FrameBufferResized(); } - private void SwitchToFullscreenMenuItem_Click(object sender, EventArgs e) - { - ToggleFullscreen(); - } + private void SwitchToFullscreenMenuItem_Click(object sender, EventArgs e) => ToggleFullscreen(); - private void DisplayFpsMenuItem_Click(object sender, EventArgs e) - { - ToggleFps(); - } + private void DisplayFpsMenuItem_Click(object sender, EventArgs e) => ToggleFps(); - private void DisplayFrameCounterMenuItem_Click(object sender, EventArgs e) - { - ToggleFrameCounter(); - } + private void DisplayFrameCounterMenuItem_Click(object sender, EventArgs e) => ToggleFrameCounter(); - private void DisplayLagCounterMenuItem_Click(object sender, EventArgs e) - { - ToggleLagCounter(); - } + private void DisplayLagCounterMenuItem_Click(object sender, EventArgs e) => ToggleLagCounter(); - private void DisplayInputMenuItem_Click(object sender, EventArgs e) - { - ToggleInputDisplay(); - } + private void DisplayInputMenuItem_Click(object sender, EventArgs e) => ToggleInputDisplay(); - private void DisplayRerecordsMenuItem_Click(object sender, EventArgs e) - { - Config.DisplayRerecordCount ^= true; - } + private void DisplayRerecordsMenuItem_Click(object sender, EventArgs e) => Config.DisplayRerecordCount ^= true; - private void DisplaySubtitlesMenuItem_Click(object sender, EventArgs e) - { - Config.DisplaySubtitles ^= true; - } + private void DisplaySubtitlesMenuItem_Click(object sender, EventArgs e) => Config.DisplaySubtitles ^= true; private void DisplayStatusBarMenuItem_Click(object sender, EventArgs e) { @@ -774,15 +678,9 @@ private void DisplayStatusBarMenuItem_Click(object sender, EventArgs e) SetStatusBar(); } - private void DisplayMessagesMenuItem_Click(object sender, EventArgs e) - { - Config.DisplayMessages ^= true; - } + private void DisplayMessagesMenuItem_Click(object sender, EventArgs e) => Config.DisplayMessages ^= true; - private void DisplayLogWindowMenuItem_Click(object sender, EventArgs e) - { - Tools.Load(); - } + private void DisplayLogWindowMenuItem_Click(object sender, EventArgs e) => Tools.Load(); private void ConfigSubMenu_DropDownOpened(object sender, EventArgs e) { @@ -862,7 +760,7 @@ private void KeyPriorityMenuItem_DropDownOpened(object sender, EventArgs e) private void ControllersMenuItem_Click(object sender, EventArgs e) { - using var controller = new ControllerConfig(this, Emulator, Config); + using ControllerConfig controller = new(this, Emulator, Config); if (!this.ShowDialogWithTempMute(controller).IsOk()) return; AddOnScreenMessage("Controller settings saved"); @@ -872,7 +770,7 @@ private void ControllersMenuItem_Click(object sender, EventArgs e) private void HotkeysMenuItem_Click(object sender, EventArgs e) { - using var hotkeyConfig = new HotkeyConfig(Config); + using HotkeyConfig hotkeyConfig = new(Config); if (!this.ShowDialogWithTempMute(hotkeyConfig).IsOk()) return; AddOnScreenMessage("Hotkey settings saved"); @@ -894,19 +792,19 @@ private void OpenFWConfigRomLoadFailed(RomLoader.RomErrorArgs args) private void FirmwaresMenuItem_Click(object sender, EventArgs e) { - using var configForm = new FirmwaresConfig(this, FirmwareManager, Config.FirmwareUserSpecifications, Config.PathEntries); + using FirmwaresConfig configForm = new(this, FirmwareManager, Config.FirmwareUserSpecifications, Config.PathEntries); this.ShowDialogWithTempMute(configForm); } private void MessagesMenuItem_Click(object sender, EventArgs e) { - using var form = new MessageConfig(Config); + using MessageConfig form = new(Config); if (this.ShowDialogWithTempMute(form).IsOk()) AddOnScreenMessage("Message settings saved"); } private void PathsMenuItem_Click(object sender, EventArgs e) { - using var form = new PathConfig(Config.PathEntries, Game.System, newPath => MovieSession.BackupDirectory = newPath); + using PathConfig form = new(Config.PathEntries, Game.System, newPath => MovieSession.BackupDirectory = newPath); if (this.ShowDialogWithTempMute(form).IsOk()) AddOnScreenMessage("Path settings saved"); } @@ -920,8 +818,8 @@ private void SoundMenuItem_Click(object sender, EventArgs e) _ => Enumerable.Empty() }; var oldOutputMethod = Config.SoundOutputMethod; - var oldDevice = Config.SoundDevice; - using var form = new SoundConfig(this, Config, GetDeviceNamesCallback); + string oldDevice = Config.SoundDevice; + using SoundConfig form = new(this, Config, GetDeviceNamesCallback); if (!this.ShowDialogWithTempMute(form).IsOk()) return; AddOnScreenMessage("Sound settings saved"); @@ -940,7 +838,7 @@ private void SoundMenuItem_Click(object sender, EventArgs e) private void AutofireMenuItem_Click(object sender, EventArgs e) { - using var form = new AutofireConfig(Config, InputManager.AutoFireController, InputManager.AutofireStickyXorAdapter); + using AutofireConfig form = new(Config, InputManager.AutoFireController, InputManager.AutofireStickyXorAdapter); if (this.ShowDialogWithTempMute(form).IsOk()) AddOnScreenMessage("Autofire settings saved"); } @@ -958,7 +856,7 @@ private void RewindOptionsMenuItem_Click(object sender, EventArgs e) private void FileExtensionsMenuItem_Click(object sender, EventArgs e) { - using var form = new FileExtensionPreferences(Config.PreferredPlatformsForExtensions); + using FileExtensionPreferences form = new(Config.PreferredPlatformsForExtensions); if (this.ShowDialogWithTempMute(form).IsOk()) AddOnScreenMessage("Rom Extension Preferences changed"); } @@ -972,14 +870,14 @@ private void BumpAutoFlushSaveRamTimer() private void CustomizeMenuItem_Click(object sender, EventArgs e) { - using var form = new EmuHawkOptions(Config, BumpAutoFlushSaveRamTimer); + using EmuHawkOptions form = new(Config, BumpAutoFlushSaveRamTimer); if (!this.ShowDialogWithTempMute(form).IsOk()) return; AddOnScreenMessage("Custom configurations saved."); } private void ProfilesMenuItem_Click(object sender, EventArgs e) { - using var form = new ProfileConfig(Config, this); + using ProfileConfig form = new(Config, this); if (!this.ShowDialogWithTempMute(form).IsOk()) return; AddOnScreenMessage("Profile settings saved"); @@ -994,7 +892,7 @@ private void ClockThrottleMenuItem_Click(object sender, EventArgs e) Config.ClockThrottle ^= true; if (Config.ClockThrottle) { - var old = Config.SoundThrottle; + bool old = Config.SoundThrottle; Config.SoundThrottle = false; if (old) { @@ -1019,7 +917,7 @@ private void AudioThrottleMenuItem_Click(object sender, EventArgs e) if (Config.SoundThrottle) { Config.ClockThrottle = false; - var old = Config.VSyncThrottle; + bool old = Config.VSyncThrottle; Config.VSyncThrottle = false; if (old) { @@ -1037,7 +935,7 @@ private void VsyncThrottleMenuItem_Click(object sender, EventArgs e) if (Config.VSyncThrottle) { Config.ClockThrottle = false; - var old = Config.SoundThrottle; + bool old = Config.SoundThrottle; Config.SoundThrottle = false; if (old) { @@ -1074,10 +972,7 @@ private void ToggleUnthrottled() ThrottleMessage(); } - private void MinimizeSkippingMenuItem_Click(object sender, EventArgs e) - { - Config.AutoMinimizeSkipping ^= true; - } + private void MinimizeSkippingMenuItem_Click(object sender, EventArgs e) => Config.AutoMinimizeSkipping ^= true; private void NeverSkipMenuItem_Click(object sender, EventArgs e) { Config.FrameSkip = 0; FrameSkipMessage(); } private void Frameskip1MenuItem_Click(object sender, EventArgs e) { Config.FrameSkip = 1; FrameSkipMessage(); } @@ -1124,7 +1019,7 @@ private void SaveConfigMenuItem_Click(object sender, EventArgs e) private void SaveConfigAsMenuItem_Click(object sender, EventArgs e) { var (dir, file) = _getConfigPath().SplitPathToDirAndFile(); - var result = this.ShowFileSaveDialog( + string result = this.ShowFileSaveDialog( filter: ConfigFileFSFilterSet, initDir: dir, initFileName: file); @@ -1135,15 +1030,12 @@ private void SaveConfigAsMenuItem_Click(object sender, EventArgs e) } } - private void LoadConfigMenuItem_Click(object sender, EventArgs e) - { - LoadConfigFile(_getConfigPath()); - } + private void LoadConfigMenuItem_Click(object sender, EventArgs e) => LoadConfigFile(_getConfigPath()); private void LoadConfigFromMenuItem_Click(object sender, EventArgs e) { var (dir, file) = _getConfigPath().SplitPathToDirAndFile(); - var result = this.ShowFileOpenDialog(filter: ConfigFileFSFilterSet, initDir: dir!, initFileName: file!); + string result = this.ShowFileOpenDialog(filter: ConfigFileFSFilterSet, initDir: dir!, initFileName: file!); if (result is not null) LoadConfigFile(result); } @@ -1205,22 +1097,13 @@ private void ExternalToolMenuItem_DropDownOpening(object sender, EventArgs e) ExternalToolMenuItem.DropDownItems.Add(forgetTrustedItem); } - private void ToolBoxMenuItem_Click(object sender, EventArgs e) - { - Tools.Load(); - } + private void ToolBoxMenuItem_Click(object sender, EventArgs e) => Tools.Load(); - private void RamWatchMenuItem_Click(object sender, EventArgs e) - { - Tools.LoadRamWatch(true); - } + private void RamWatchMenuItem_Click(object sender, EventArgs e) => Tools.LoadRamWatch(true); private void RamSearchMenuItem_Click(object sender, EventArgs e) => Tools.Load(); - private void LuaConsoleMenuItem_Click(object sender, EventArgs e) - { - OpenLuaConsole(); - } + private void LuaConsoleMenuItem_Click(object sender, EventArgs e) => OpenLuaConsole(); private void TAStudioMenuItem_Click(object sender, EventArgs e) { @@ -1238,70 +1121,37 @@ private void TAStudioMenuItem_Click(object sender, EventArgs e) Tools.Load(); } - private void HexEditorMenuItem_Click(object sender, EventArgs e) - { - Tools.Load(); - } + private void HexEditorMenuItem_Click(object sender, EventArgs e) => Tools.Load(); - private void TraceLoggerMenuItem_Click(object sender, EventArgs e) - { - Tools.Load(); - } + private void TraceLoggerMenuItem_Click(object sender, EventArgs e) => Tools.Load(); - private void DebuggerMenuItem_Click(object sender, EventArgs e) - { - Tools.Load(); - } + private void DebuggerMenuItem_Click(object sender, EventArgs e) => Tools.Load(); - private void CodeDataLoggerMenuItem_Click(object sender, EventArgs e) - { - Tools.Load(); - } + private void CodeDataLoggerMenuItem_Click(object sender, EventArgs e) => Tools.Load(); - private void MacroToolMenuItem_Click(object sender, EventArgs e) - { - Tools.Load(); - } + private void MacroToolMenuItem_Click(object sender, EventArgs e) => Tools.Load(); - private void VirtualPadMenuItem_Click(object sender, EventArgs e) - { - Tools.Load(); - } + private void VirtualPadMenuItem_Click(object sender, EventArgs e) => Tools.Load(); - private void BasicBotMenuItem_Click(object sender, EventArgs e) - { - Tools.Load(); - } + private void BasicBotMenuItem_Click(object sender, EventArgs e) => Tools.Load(); - private void CheatsMenuItem_Click(object sender, EventArgs e) - { - Tools.Load(); - } + private void CheatsMenuItem_Click(object sender, EventArgs e) => Tools.Load(); - private void CheatCodeConverterMenuItem_Click(object sender, EventArgs e) - { - Tools.Load(); - } + private void CheatCodeConverterMenuItem_Click(object sender, EventArgs e) => Tools.Load(); - private void MultidiskBundlerMenuItem_Click(object sender, EventArgs e) - { - Tools.Load(); - } + private void MultidiskBundlerMenuItem_Click(object sender, EventArgs e) => Tools.Load(); private void BatchRunnerMenuItem_Click(object sender, EventArgs e) { - using var form = new BatchRun(this, Config, CreateCoreComm); + using BatchRun form = new(this, Config, CreateCoreComm); this.ShowDialogWithTempMute(form); } - private void StartRetroAchievementsMenuItem_Click(object sender, EventArgs e) - { - OpenRetroAchievements(); - } + private void StartRetroAchievementsMenuItem_Click(object sender, EventArgs e) => OpenRetroAchievements(); private void NesSubMenu_DropDownOpened(object sender, EventArgs e) { - var boardName = Emulator.HasBoardInfo() ? Emulator.AsBoardInfo().BoardName : null; + string boardName = Emulator.HasBoardInfo() ? Emulator.AsBoardInfo().BoardName : null; FDSControlsMenuItem.Enabled = boardName == "FDS"; VSControlsMenuItem.Enabled = @@ -1321,7 +1171,7 @@ private void NesSubMenu_DropDownOpened(object sender, EventArgs e) private void FdsControlsMenuItem_DropDownOpened(object sender, EventArgs e) { - var boardName = Emulator.HasBoardInfo() ? Emulator.AsBoardInfo().BoardName : null; + string boardName = Emulator.HasBoardInfo() ? Emulator.AsBoardInfo().BoardName : null; FdsEjectDiskMenuItem.Enabled = boardName == "FDS"; while (FDSControlsMenuItem.DropDownItems.Count > 1) @@ -1332,25 +1182,16 @@ private void FdsControlsMenuItem_DropDownOpened(object sender, EventArgs e) string button; for (int i = 0; Emulator.ControllerDefinition.BoolButtons.Contains(button = $"FDS Insert {i}"); i++) { - var name = $"Disk {i / 2 + 1} Side {(char)(i % 2 + 'A')}"; + string name = $"Disk {i / 2 + 1} Side {(char)(i % 2 + 'A')}"; FdsInsertDiskMenuAdd($"Insert {name}", button, $"FDS {name} inserted."); } } - private void NesPpuViewerMenuItem_Click(object sender, EventArgs e) - { - Tools.Load(); - } + private void NesPpuViewerMenuItem_Click(object sender, EventArgs e) => Tools.Load(); - private void NesNametableViewerMenuItem_Click(object sender, EventArgs e) - { - Tools.Load(); - } + private void NesNametableViewerMenuItem_Click(object sender, EventArgs e) => Tools.Load(); - private void MusicRipperMenuItem_Click(object sender, EventArgs e) - { - Tools.Load(); - } + private void MusicRipperMenuItem_Click(object sender, EventArgs e) => Tools.Load(); private DialogResult OpenNesHawkGraphicsSettingsDialog(ISettingsAdapter settable) { @@ -1375,10 +1216,7 @@ private void NesGraphicSettingsMenuItem_Click(object sender, EventArgs e) }; } - private void NesSoundChannelsMenuItem_Click(object sender, EventArgs e) - { - Tools.Load(); - } + private void NesSoundChannelsMenuItem_Click(object sender, EventArgs e) => Tools.Load(); private DialogResult OpenNesHawkVSSettingsDialog(ISettingsAdapter settable) { @@ -1485,20 +1323,14 @@ private void MovieSettingsMenuItem_Click(object sender, EventArgs e) }; } - private void BarcodeReaderMenuItem_Click(object sender, EventArgs e) - { - Tools.Load(); - } + private void BarcodeReaderMenuItem_Click(object sender, EventArgs e) => Tools.Load(); - private void Ti83KeypadMenuItem_Click(object sender, EventArgs e) - { - Tools.Load(); - } + private void Ti83KeypadMenuItem_Click(object sender, EventArgs e) => Tools.Load(); private void Ti83LoadTIFileMenuItem_Click(object sender, EventArgs e) { if (Emulator is not TI83 ti83) return; - var result = this.ShowFileOpenDialog( + string result = this.ShowFileOpenDialog( discardCWDChange: true, filter: TI83ProgramFilesFSFilterSet, initDir: Config.PathEntries.RomAbsolutePath(Emulator.SystemId)); @@ -1509,7 +1341,7 @@ private void Ti83LoadTIFileMenuItem_Click(object sender, EventArgs e) } catch (IOException ex) { - var message = + string message = $"Invalid file format. Reason: {ex.Message} \nForce transfer? This may cause the calculator to crash."; if (this.ShowMessageBox3(owner: null, message, "Upload Failed", EMsgBoxIcon.Question) == true) { @@ -1611,20 +1443,11 @@ private void SameboyColorChooserMenuItem_Click(object sender, EventArgs e) }; } - private void GbGpuViewerMenuItem_Click(object sender, EventArgs e) - { - Tools.Load(); - } + private void GbGpuViewerMenuItem_Click(object sender, EventArgs e) => Tools.Load(); - private void GbPrinterViewerMenuItem_Click(object sender, EventArgs e) - { - Tools.Load(); - } + private void GbPrinterViewerMenuItem_Click(object sender, EventArgs e) => Tools.Load(); - private void PsxSubMenu_DropDownOpened(object sender, EventArgs e) - { - PSXControllerSettingsMenuItem.Enabled = MovieSession.Movie.NotActive(); - } + private void PsxSubMenu_DropDownOpened(object sender, EventArgs e) => PSXControllerSettingsMenuItem.Enabled = MovieSession.Movie.NotActive(); private DialogResult OpenOctoshockGamepadSettingsDialog(ISettingsAdapter settable) { @@ -1654,10 +1477,7 @@ private void PsxOptionsMenuItem_Click(object sender, EventArgs e) if (result.IsOk()) FrameBufferResized(); } - private void PsxDiscControlsMenuItem_Click(object sender, EventArgs e) - { - Tools.Load().ScrollToPadSchema("Console"); - } + private void PsxDiscControlsMenuItem_Click(object sender, EventArgs e) => Tools.Load().ScrollToPadSchema("Console"); private void PsxHashDiscsMenuItem_Click(object sender, EventArgs e) { @@ -1666,10 +1486,7 @@ private void PsxHashDiscsMenuItem_Click(object sender, EventArgs e) this.ShowDialogWithTempMute(form); } - private void SnesSubMenu_DropDownOpened(object sender, EventArgs e) - { - SNESControllerConfigurationMenuItem.Enabled = MovieSession.Movie.NotActive(); - } + private void SnesSubMenu_DropDownOpened(object sender, EventArgs e) => SNESControllerConfigurationMenuItem.Enabled = MovieSession.Movie.NotActive(); private DialogResult OpenOldBSNESGamepadSettingsDialog(ISettingsAdapter settable) { @@ -1694,10 +1511,7 @@ private void SNESControllerConfigurationMenuItem_Click(object sender, EventArgs }; } - private void SnesGfxDebuggerMenuItem_Click(object sender, EventArgs e) - { - Tools.Load(); - } + private void SnesGfxDebuggerMenuItem_Click(object sender, EventArgs e) => Tools.Load(); private DialogResult OpenOldBSNESSettingsDialog(ISettingsAdapter settable) => SNESOptions.DoSettingsDialog(this, settable); @@ -1729,7 +1543,7 @@ private void ColecoSubMenu_DropDownOpened(object sender, EventArgs e) private void ColecoHawkSetSkipBIOSIntro(bool newValue, ISettingsAdapter settable) { - var ss = (ColecoVision.ColecoSyncSettings) settable.GetSyncSettings(); + ColecoVision.ColecoSyncSettings ss = (ColecoVision.ColecoSyncSettings) settable.GetSyncSettings(); ss.SkipBiosIntro = newValue; settable.PutCoreSyncSettings(ss); } @@ -1741,7 +1555,7 @@ private void ColecoSkipBiosMenuItem_Click(object sender, EventArgs e) private void ColecoHawkSetSuperGameModule(bool newValue, ISettingsAdapter settable) { - var ss = (ColecoVision.ColecoSyncSettings) settable.GetSyncSettings(); + ColecoVision.ColecoSyncSettings ss = (ColecoVision.ColecoSyncSettings) settable.GetSyncSettings(); ss.UseSGM = newValue; settable.PutCoreSyncSettings(ss); } @@ -1812,14 +1626,11 @@ private void N64ControllerSettingsMenuItem_Click(object sender, EventArgs e) }; } - private void N64CircularAnalogRangeMenuItem_Click(object sender, EventArgs e) - { - Config.N64UseCircularAnalogConstraint ^= true; - } + private void N64CircularAnalogRangeMenuItem_Click(object sender, EventArgs e) => Config.N64UseCircularAnalogConstraint ^= true; private void Mupen64PlusSetNonVILagFrames(bool newValue, ISettingsAdapter settable) { - var s = (N64Settings) settable.GetSettings(); + N64Settings s = (N64Settings) settable.GetSettings(); s.UseMupenStyleLag = newValue; settable.PutCoreSettings(s); } @@ -1829,7 +1640,7 @@ private void MupenStyleLagMenuItem_Click(object sender, EventArgs e) private void Mupen64PlusSetUseExpansionSlot(bool newValue, ISettingsAdapter settable) { - var ss = (N64SyncSettings) settable.GetSyncSettings(); + N64SyncSettings ss = (N64SyncSettings) settable.GetSyncSettings(); ss.DisableExpansionSlot = !newValue; settable.PutCoreSyncSettings(ss); } @@ -1899,7 +1710,7 @@ private void AppleDisksSubMenu_DropDownOpened(object sender, EventArgs e) { for (int i = 0; i < appleII.DiskCount; i++) { - var menuItem = new ToolStripMenuItem + ToolStripMenuItem menuItem = new() { Name = $"Disk{i + 1}", Text = $"Disk{i + 1}", @@ -1933,7 +1744,7 @@ private void C64DisksSubMenu_DropDownOpened(object sender, EventArgs e) { for (int i = 0; i < c64.DiskCount; i++) { - var menuItem = new ToolStripMenuItem + ToolStripMenuItem menuItem = new() { Name = $"Disk{i + 1}", Text = $"Disk{i + 1}", @@ -1963,10 +1774,7 @@ private void C64SettingsMenuItem_Click(object sender, EventArgs e) }; } - private void IntVSubMenu_DropDownOpened(object sender, EventArgs e) - { - IntVControllerSettingsMenuItem.Enabled = MovieSession.Movie.NotActive(); - } + private void IntVSubMenu_DropDownOpened(object sender, EventArgs e) => IntVControllerSettingsMenuItem.Enabled = MovieSession.Movie.NotActive(); private DialogResult OpenIntelliHawkGamepadSettingsDialog(ISettingsAdapter settable) { @@ -2060,13 +1868,13 @@ private void ZXSpectrumTapesSubMenu_DropDownOpened(object sender, EventArgs e) if (Emulator is ZXSpectrum speccy) { - var tapeMediaIndex = speccy._machine.TapeMediaIndex; + int tapeMediaIndex = speccy._machine.TapeMediaIndex; for (int i = 0; i < speccy._tapeInfo.Count; i++) { string name = speccy._tapeInfo[i].Name; - var menuItem = new ToolStripMenuItem + ToolStripMenuItem menuItem = new() { Name = $"{i}_{name}", Text = $"{i}: {name}", @@ -2094,13 +1902,13 @@ private void ZXSpectrumDisksSubMenu_DropDownOpened(object sender, EventArgs e) if (Emulator is ZXSpectrum speccy) { - var diskMediaIndex = speccy._machine.DiskMediaIndex; + int diskMediaIndex = speccy._machine.DiskMediaIndex; for (int i = 0; i < speccy._diskInfo.Count; i++) { string name = speccy._diskInfo[i].Name; - var menuItem = new ToolStripMenuItem + ToolStripMenuItem menuItem = new() { Name = $"{i}_{name}", Text = $"{i}: {name}", @@ -2124,7 +1932,7 @@ private void ZXSpectrumExportSnapshotMenuItemMenuItem_Click(object sender, Event { try { - var result = this.ShowFileSaveDialog( + string result = this.ShowFileSaveDialog( discardCWDChange: true, fileExt: "szx", // SupportMultiDottedExtensions = true, // I think this should be enabled globally if we're going to do it --yoshi @@ -2132,8 +1940,8 @@ private void ZXSpectrumExportSnapshotMenuItemMenuItem_Click(object sender, Event initDir: Config.PathEntries.ToolsAbsolutePath()); if (result is not null) { - var speccy = (ZXSpectrum)Emulator; - var snap = speccy.GetSZXSnapshot(); + ZXSpectrum speccy = (ZXSpectrum)Emulator; + byte[] snap = speccy.GetSZXSnapshot(); File.WriteAllBytes(result, snap); } } @@ -2189,13 +1997,13 @@ private void AmstradCpcTapesSubMenu_DropDownOpened(object sender, EventArgs e) if (Emulator is AmstradCPC ams) { - var tapeMediaIndex = ams._machine.TapeMediaIndex; + int tapeMediaIndex = ams._machine.TapeMediaIndex; for (int i = 0; i < ams._tapeInfo.Count; i++) { string name = ams._tapeInfo[i].Name; - var menuItem = new ToolStripMenuItem + ToolStripMenuItem menuItem = new() { Name = $"{i}_{name}", Text = $"{i}: {name}", @@ -2223,13 +2031,13 @@ private void AmstradCpcDisksSubMenu_DropDownOpened(object sender, EventArgs e) if (Emulator is AmstradCPC ams) { - var diskMediaIndex = ams._machine.DiskMediaIndex; + int diskMediaIndex = ams._machine.DiskMediaIndex; for (int i = 0; i < ams._diskInfo.Count; i++) { string name = ams._diskInfo[i].Name; - var menuItem = new ToolStripMenuItem + ToolStripMenuItem menuItem = new() { Name = $"{i}_{name}", Text = $"{i}: {name}", @@ -2264,29 +2072,17 @@ private void AmstradCpcNonSyncSettingsMenuItem_Click(object sender, EventArgs e) }; } - private void HelpSubMenu_DropDownOpened(object sender, EventArgs e) - { - FeaturesMenuItem.Visible = VersionInfo.DeveloperBuild; - } + private void HelpSubMenu_DropDownOpened(object sender, EventArgs e) => FeaturesMenuItem.Visible = VersionInfo.DeveloperBuild; - private void OnlineHelpMenuItem_Click(object sender, EventArgs e) - { - System.Diagnostics.Process.Start("https://tasvideos.org/BizHawk"); - } + private void OnlineHelpMenuItem_Click(object sender, EventArgs e) => System.Diagnostics.Process.Start("https://tasvideos.org/BizHawk"); - private void ForumsMenuItem_Click(object sender, EventArgs e) - { - System.Diagnostics.Process.Start("https://tasvideos.org/Forum/Subforum/64"); - } + private void ForumsMenuItem_Click(object sender, EventArgs e) => System.Diagnostics.Process.Start("https://tasvideos.org/Forum/Subforum/64"); - private void FeaturesMenuItem_Click(object sender, EventArgs e) - { - Tools.Load(); - } + private void FeaturesMenuItem_Click(object sender, EventArgs e) => Tools.Load(); private void AboutMenuItem_Click(object sender, EventArgs e) { - using var form = new BizBox(); + using BizBox form = new(); this.ShowDialogWithTempMute(form); } @@ -2303,7 +2099,7 @@ private void MainFormContextMenu_Opening(object sender, System.ComponentModel.Ca showMenuVisible = true; // I decided this was always possible in chrome-less mode, we'll see what they think } - var movieIsActive = MovieSession.Movie.IsActive(); + bool movieIsActive = MovieSession.Movie.IsActive(); ShowMenuContextMenuItem.Visible = ShowMenuContextMenuSeparator.Visible = @@ -2362,7 +2158,7 @@ private void MainFormContextMenu_Opening(object sender, System.ComponentModel.Ca } } - var file = new FileInfo($"{SaveStatePrefix()}.QuickSave{Config.SaveSlot % 10}.State.bak"); + FileInfo file = new($"{SaveStatePrefix()}.QuickSave{Config.SaveSlot % 10}.State.bak"); if (file.Exists) { @@ -2409,15 +2205,9 @@ private void DisplayConfigMenuItem_Click(object sender, EventArgs e) private void LoadLastRomContextMenuItem_Click(object sender, EventArgs e) => LoadMostRecentROM(); - private void LoadMostRecentROM() - { - LoadRomFromRecent(Config.RecentRoms.MostRecent); - } + private void LoadMostRecentROM() => LoadRomFromRecent(Config.RecentRoms.MostRecent); - private void LoadLastMovieContextMenuItem_Click(object sender, EventArgs e) - { - LoadMoviesFromRecent(Config.RecentMovies.MostRecent); - } + private void LoadLastMovieContextMenuItem_Click(object sender, EventArgs e) => LoadMoviesFromRecent(Config.RecentMovies.MostRecent); private void BackupMovieContextMenuItem_Click(object sender, EventArgs e) { @@ -2435,11 +2225,11 @@ private void ViewSubtitlesContextMenuItem_Click(object sender, EventArgs e) private void AddSubtitleContextMenuItem_Click(object sender, EventArgs e) { // TODO: rethink this? - var subForm = new SubtitleMaker(); + SubtitleMaker subForm = new(); subForm.DisableFrame(); int index = -1; - var sub = new Subtitle(); + Subtitle sub = new(); for (int i = 0; i < MovieSession.Movie.Subtitles.Count; i++) { sub = MovieSession.Movie.Subtitles[i]; @@ -2475,10 +2265,7 @@ private void UndoSavestateContextMenuItem_Click(object sender, EventArgs e) AddOnScreenMessage($"Save slot {Config.SaveSlot} restored."); } - private void ClearSramContextMenuItem_Click(object sender, EventArgs e) - { - CloseRom(clearSram: true); - } + private void ClearSramContextMenuItem_Click(object sender, EventArgs e) => CloseRom(clearSram: true); private void ShowMenuContextMenuItem_Click(object sender, EventArgs e) { @@ -2503,7 +2290,7 @@ private void DumpStatusButton_Click(object sender, EventArgs e) private void SlotStatusButtons_MouseUp(object sender, MouseEventArgs e) { - var slot = 10; + int slot = 10; if (sender == Slot1StatusButton) slot = 1; if (sender == Slot2StatusButton) slot = 2; if (sender == Slot3StatusButton) slot = 3; @@ -2542,7 +2329,7 @@ private void ProfileFirstBootLabel_Click(object sender, EventArgs e) { // We do not check if the user is actually setting a profile here. // This is intentional. - using var profileForm = new ProfileConfig(Config, this); + using ProfileConfig profileForm = new(Config, this); this.ShowDialogWithTempMute(profileForm); Config.FirstBoot = false; ProfileFirstBootLabel.Visible = false; @@ -2561,7 +2348,7 @@ private void LinkConnectStatusBarButton_Click(object sender, EventArgs e) private void UpdateNotification_Click(object sender, EventArgs e) { Sound.StopSound(); - var result = this.ModalMessageBox3( + bool? result = this.ModalMessageBox3( $"Version {Config.UpdateLatestVersion} is now available. Would you like to open the BizHawk homepage?\r\n\r\nClick \"No\" to hide the update notification for this version.", "New Version Available", EMsgBoxIcon.Question); @@ -2602,15 +2389,9 @@ private void TimerMouseIdle_Tick(object sender, EventArgs e) } } - private void MainForm_Enter(object sender, EventArgs e) - { - AutohideCursor(false); - } + private void MainForm_Enter(object sender, EventArgs e) => AutohideCursor(false); - private void MainForm_Resize(object sender, EventArgs e) - { - _presentationPanel.Resized = true; - } + private void MainForm_Resize(object sender, EventArgs e) => _presentationPanel.Resized = true; private void MainForm_Shown(object sender, EventArgs e) { @@ -2656,10 +2437,7 @@ public void MaybeUnpauseFromMenuClosed() UnpauseEmulator(); } - private static void FormDragEnter(object sender, DragEventArgs e) - { - e.Set(DragDropEffects.Copy); - } + private static void FormDragEnter(object sender, DragEventArgs e) => e.Set(DragDropEffects.Copy); private void FormDragDrop(object sender, DragEventArgs e) => PathsFromDragDrop = (string[]) e.Data.GetData(DataFormats.FileDrop); @@ -2755,7 +2533,7 @@ ToolStripMenuItemEx CreateCoreSubmenu(VSystemCategory cat, string coreName, para var colecoHawkSubmenu = CreateCoreSubmenu(VSystemCategory.Consoles, CoreNames.ColecoHawk, colecoHawkGamepadSettingsItem, colecoHawkSkipBIOSItem, colecoHawkUseSGMItem); colecoHawkSubmenu.DropDownOpened += (_, _) => { - var ss = (ColecoVision.ColecoSyncSettings) GetSettingsAdapterFor().GetSyncSettings(); + ColecoVision.ColecoSyncSettings ss = (ColecoVision.ColecoSyncSettings) GetSettingsAdapterFor().GetSyncSettings(); colecoHawkGamepadSettingsItem.Enabled = MovieSession.Movie.NotActive() || Emulator is not ColecoVision; colecoHawkSkipBIOSItem.Checked = ss.SkipBiosIntro; colecoHawkUseSGMItem.Checked = ss.UseSGM; @@ -2847,10 +2625,10 @@ ToolStripMenuItemEx CreateCoreSubmenu(VSystemCategory cat, string coreName, para mupen64PlusSubmenu.DropDownOpened += (_, _) => { var settable = GetSettingsAdapterFor(); - var s = (N64Settings) settable.GetSettings(); - var isMovieActive = MovieSession.Movie.IsActive(); - var mupen64Plus = Emulator as N64; - var loadedCoreIsMupen64Plus = mupen64Plus is not null; + N64Settings s = (N64Settings) settable.GetSettings(); + bool isMovieActive = MovieSession.Movie.IsActive(); + N64 mupen64Plus = Emulator as N64; + bool loadedCoreIsMupen64Plus = mupen64Plus is not null; mupen64PlusGraphicsSettingsItem.Enabled = !loadedCoreIsMupen64Plus || !isMovieActive; mupen64PlusGamepadSettingsItem.Enabled = !loadedCoreIsMupen64Plus || !isMovieActive; mupen64PlusAnalogConstraintItem.Checked = Config.N64UseCircularAnalogConstraint; @@ -2884,8 +2662,8 @@ ToolStripMenuItemEx CreateCoreSubmenu(VSystemCategory cat, string coreName, para nesHawkAdvancedSettingsItem); nesHawkSubmenu.DropDownOpened += (_, _) => { - var nesHawk = Emulator as NES; - var canEditSyncSettings = nesHawk is null || MovieSession.Movie.NotActive(); + NES nesHawk = Emulator as NES; + bool canEditSyncSettings = nesHawk is null || MovieSession.Movie.NotActive(); nesHawkGamepadSettingsItem.Enabled = canEditSyncSettings && Tools.IsAvailable(); nesHawkVSSettingsItem.Enabled = nesHawk?.IsVS is null or true; nesHawkAdvancedSettingsItem.Enabled = canEditSyncSettings; @@ -2907,7 +2685,7 @@ ToolStripMenuItemEx CreateCoreSubmenu(VSystemCategory cat, string coreName, para var octoshockSubmenu = CreateCoreSubmenu(VSystemCategory.Consoles, CoreNames.Octoshock, octoshockGamepadSettingsItem, octoshockSettingsItem, octoshockNTSCSettingsItem, octoshockPALSettingsItem); octoshockSubmenu.DropDownOpened += (_, _) => { - var loadedCoreIsOctoshock = Emulator is Octoshock; + bool loadedCoreIsOctoshock = Emulator is Octoshock; octoshockGamepadSettingsItem.Enabled = !loadedCoreIsOctoshock || MovieSession.Movie.NotActive(); octoshockSettingsItem.Visible = loadedCoreIsOctoshock; octoshockNTSCSettingsItem.Visible = octoshockPALSettingsItem.Visible = !loadedCoreIsOctoshock; @@ -2963,8 +2741,8 @@ ToolStripMenuItemEx CreateCoreSubmenu(VSystemCategory cat, string coreName, para subNESHawkAdvancedSettingsItem); subNESHawkSubmenu.DropDownOpened += (_, _) => { - var subNESHawk = Emulator as SubNESHawk; - var canEditSyncSettings = subNESHawk is null || MovieSession.Movie.NotActive(); + SubNESHawk subNESHawk = Emulator as SubNESHawk; + bool canEditSyncSettings = subNESHawk is null || MovieSession.Movie.NotActive(); subNESHawkGamepadSettingsItem.Enabled = canEditSyncSettings && Tools.IsAvailable(); subNESHawkVSSettingsItem.Enabled = subNESHawk?.IsVs is null or true; subNESHawkAdvancedSettingsItem.Enabled = canEditSyncSettings; diff --git a/src/BizHawk.Client.EmuHawk/MainForm.FileLoader.cs b/src/BizHawk.Client.EmuHawk/MainForm.FileLoader.cs index 3e094cdbb1b..7596be4e53d 100644 --- a/src/BizHawk.Client.EmuHawk/MainForm.FileLoader.cs +++ b/src/BizHawk.Client.EmuHawk/MainForm.FileLoader.cs @@ -45,7 +45,7 @@ private void LoadCdl(string filename, string archive = null) { if (Tools.IsAvailable()) { - CDL cdl = Tools.Load(); + var cdl = Tools.Load(); cdl.LoadFile(filename); } } @@ -100,7 +100,7 @@ public bool LoadMovie(string filename, string archive = null) private bool LoadRom(string filename, string archive = null) { - var args = new LoadRomArgs + LoadRomArgs args = new() { OpenAdvanced = new OpenAdvanced_OpenRom {Path = filename} }; @@ -120,7 +120,7 @@ private void ProcessFileList(IEnumerable fileList, ref Dictionary> sortedFiles = new Dictionary>(); + Dictionary> sortedFiles = new(); // Initialize the dictionary's lists. foreach (LoadOrdering value in Enum.GetValues(typeof(LoadOrdering))) diff --git a/src/BizHawk.Client.EmuHawk/MainForm.Hotkey.cs b/src/BizHawk.Client.EmuHawk/MainForm.Hotkey.cs index 7986ba1275c..1d91c6282a1 100644 --- a/src/BizHawk.Client.EmuHawk/MainForm.Hotkey.cs +++ b/src/BizHawk.Client.EmuHawk/MainForm.Hotkey.cs @@ -34,7 +34,7 @@ void ToggleGambatteSyncSetting( return; } var ss = gb.GetSyncSettings(); - var newState = !getter(ss); + bool newState = !getter(ss); setter(ss, newState); gb.PutSyncSettings(ss); AddOnScreenMessage($"{name} toggled {(newState ? "on" : "off")}"); @@ -311,10 +311,10 @@ void ToggleGambatteSyncSetting( Tools.Load(); break; case "Toggle All Cheats": - var cheats = CheatList.Where(static c => !c.IsSeparator).ToList(); + System.Collections.Generic.List cheats = CheatList.Where(static c => !c.IsSeparator).ToList(); if (cheats.Count is 0) break; - var firstWasEnabled = cheats[0].Enabled; - var kind = cheats.TrueForAll(c => c.Enabled == firstWasEnabled) + bool firstWasEnabled = cheats[0].Enabled; + string kind = cheats.TrueForAll(c => c.Enabled == firstWasEnabled) ? firstWasEnabled ? "off" : "on" @@ -561,7 +561,7 @@ private void IncrementDSLayout(int delta) if (Emulator is NDS ds) { var settings = ds.GetSettings(); - var num = (int)settings.ScreenLayout; + int num = (int)settings.ScreenLayout; if (decrement) { num--; @@ -571,7 +571,7 @@ private void IncrementDSLayout(int delta) num++; } - var next = (NDS.ScreenLayoutKind)Enum.Parse(typeof(NDS.ScreenLayoutKind), num.ToString()); + NDS.ScreenLayoutKind next = (NDS.ScreenLayoutKind)Enum.Parse(typeof(NDS.ScreenLayoutKind), num.ToString()); if (typeof(NDS.ScreenLayoutKind).IsEnumDefined(next)) { settings.ScreenLayout = next; @@ -586,28 +586,12 @@ private void IncrementDSLayout(int delta) // Determines if the value is a hotkey that would be handled outside of the CheckHotkey method private bool IsInternalHotkey(string trigger) { - switch (trigger) + return trigger switch { - default: - return false; - case "Autohold": - case "Autofire": - case "Frame Advance": - case "Turbo": - case "Rewind": - case "Fast Forward": - case "Open RA Overlay": - return true; - case "RA Up": - case "RA Down": - case "RA Left": - case "RA Right": - case "RA Confirm": - case "RA Cancel": - case "RA Quit": - // don't consider these keys outside of RAIntegration overlay being active - return RA is RAIntegration { OverlayActive: true }; - } + "Autohold" or "Autofire" or "Frame Advance" or "Turbo" or "Rewind" or "Fast Forward" or "Open RA Overlay" => true, + "RA Up" or "RA Down" or "RA Left" or "RA Right" or "RA Confirm" or "RA Cancel" or "RA Quit" => RA is RAIntegration { OverlayActive: true },// don't consider these keys outside of RAIntegration overlay being active + _ => false, + }; } } } diff --git a/src/BizHawk.Client.EmuHawk/MainForm.Movie.cs b/src/BizHawk.Client.EmuHawk/MainForm.Movie.cs index 6412e720124..77bd121ec9d 100644 --- a/src/BizHawk.Client.EmuHawk/MainForm.Movie.cs +++ b/src/BizHawk.Client.EmuHawk/MainForm.Movie.cs @@ -15,14 +15,14 @@ public bool StartNewMovie(IMovie movie, bool record) if (CheatList.AnyActive) { - var result = this.ModalMessageBox3( + bool? result = this.ModalMessageBox3( caption: "Cheats warning", text: "Continue playback with cheats enabled?\nChoosing \"No\" will disable cheats but not remove them.", icon: EMsgBoxIcon.Question); if (result is null) return false; if (result is false) CheatList.DisableAll(); } - var oldPreferredCores = new Dictionary(Config.PreferredCores); + Dictionary oldPreferredCores = new(Config.PreferredCores); try { try @@ -31,14 +31,14 @@ public bool StartNewMovie(IMovie movie, bool record) } catch (MoviePlatformMismatchException ex) { - using var ownerForm = new Form { TopMost = true }; + using Form ownerForm = new() { TopMost = true }; MessageBox.Show(ownerForm, ex.Message, "Movie/Platform Mismatch", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (!_isLoadingRom) { - var rebootSucceeded = RebootCore(); + bool rebootSucceeded = RebootCore(); if (!rebootSucceeded) return false; } @@ -109,7 +109,7 @@ public bool RestartMovie() { if (IsSlave && Master.WantsToControlRestartMovie) return Master.RestartMovie(); if (!MovieSession.Movie.IsActive()) return false; - var success = StartNewMovie(MovieSession.Movie, false); + bool success = StartNewMovie(MovieSession.Movie, false); if (success) AddOnScreenMessage("Replaying movie file in read-only mode"); return success; } diff --git a/src/BizHawk.Client.EmuHawk/MainForm.cs b/src/BizHawk.Client.EmuHawk/MainForm.cs index f6b1ddeabbc..f5a8ca0243f 100644 --- a/src/BizHawk.Client.EmuHawk/MainForm.cs +++ b/src/BizHawk.Client.EmuHawk/MainForm.cs @@ -69,37 +69,37 @@ private void MainForm_Load(object sender, EventArgs e) foreach (var (groupLabel, appliesTo, coreNames) in Config.CorePickerUIData.Select(static tuple => (GroupLabel: tuple.AppliesTo[0], tuple.AppliesTo, tuple.CoreNames)) .OrderBy(static tuple => tuple.GroupLabel)) { - var submenu = new ToolStripMenuItem { Text = groupLabel }; + ToolStripMenuItem submenu = new() { Text = groupLabel }; void ClickHandler(object clickSender, EventArgs clickArgs) { - var coreName = ((ToolStripMenuItem) clickSender).Text; - foreach (var system in appliesTo) + string coreName = ((ToolStripMenuItem) clickSender).Text; + foreach (string system in appliesTo) { if (Emulator.SystemId == system && Emulator.Attributes().CoreName != coreName) FlagNeedsReboot(); Config.PreferredCores[system] = coreName; } } submenu.DropDownItems.AddRange(coreNames.Select(coreName => { - var entry = new ToolStripMenuItem { Text = coreName }; + ToolStripMenuItem entry = new() { Text = coreName }; entry.Click += ClickHandler; return (ToolStripItem) entry; }).ToArray()); submenu.DropDownOpened += (openedSender, _1) => { - _ = Config.PreferredCores.TryGetValue(groupLabel, out var preferred); + _ = Config.PreferredCores.TryGetValue(groupLabel, out string preferred); foreach (ToolStripMenuItem entry in ((ToolStripMenuItem) openedSender).DropDownItems) entry.Checked = entry.Text == preferred; }; CoresSubMenu.DropDownItems.Add(submenu); } CoresSubMenu.DropDownItems.Add(new ToolStripSeparator { AutoSize = true }); - var GBInSGBMenuItem = new ToolStripMenuItem { Text = "GB in SGB" }; + ToolStripMenuItem GBInSGBMenuItem = new() { Text = "GB in SGB" }; GBInSGBMenuItem.Click += (_, _) => { Config.GbAsSgb ^= true; if (Emulator.SystemId is VSystemID.Raw.GB or VSystemID.Raw.GBC or VSystemID.Raw.SGB) FlagNeedsReboot(); }; CoresSubMenu.DropDownItems.Add(GBInSGBMenuItem); - var setLibretroCoreToolStripMenuItem = new ToolStripMenuItem { Text = "Set Libretro Core..." }; + ToolStripMenuItem setLibretroCoreToolStripMenuItem = new() { Text = "Set Libretro Core..." }; setLibretroCoreToolStripMenuItem.Click += (_, _) => RunLibretroCoreChooser(); CoresSubMenu.DropDownItems.Add(setLibretroCoreToolStripMenuItem); CoresSubMenu.DropDownOpened += (_, _) => GBInSGBMenuItem.Checked = Config.GbAsSgb; @@ -188,7 +188,7 @@ void ClickHandler(object clickSender, EventArgs clickArgs) UpdateChecker.BeginCheck(); // Won't actually check unless enabled by user // open requested ext. tool - var requestedExtToolDll = _argParser.openExtToolDll; + string requestedExtToolDll = _argParser.openExtToolDll; if (requestedExtToolDll != null) { var found = ExtToolManager.ToolStripItems.Where(static item => item.Enabled) @@ -213,7 +213,7 @@ static MainForm() public CoreComm CreateCoreComm() { - var cfp = new CoreFileProvider( + CoreFileProvider cfp = new( this, FirmwareManager, Config.PathEntries, @@ -695,8 +695,8 @@ _argParser.SocketAddress is var (socketIP, socketPort) { "true" => true, "false" => false, - _ when int.TryParse(v, out var i) => i, - _ when double.TryParse(v, out var d) => d, + _ when int.TryParse(v, out int i) => i, + _ when double.TryParse(v, out double d) => d, _ => v }; } @@ -742,7 +742,7 @@ _ when double.TryParse(v, out var d) => d, if (!Config.SkipOutdatedOsCheck && OSTailoredCode.HostWindowsVersion is not null) { var (winVersion, win10PlusVersion) = OSTailoredCode.HostWindowsVersion.Value; - var message = winVersion switch + string message = winVersion switch { // OSTailoredCode.WindowsVersion._11 when win10PlusVersion! < new Version(10, 0, 22621) => $"Quick reminder: Your copy of Windows 11 (build {win10PlusVersion.Build}) is no longer supported by Microsoft.\nEmuHawk will probably continue working, but please update to at least 21H2 for increased security.", OSTailoredCode.WindowsVersion._11 => null, @@ -1110,8 +1110,8 @@ private void ProcessInput( { if (ie.LogicalButton.Button.Length == 1) { - var c = ie.LogicalButton.Button.ToLowerInvariant()[0]; - if ((c >= 'a' && c <= 'z') || c == ' ') + char c = ie.LogicalButton.Button.ToLowerInvariant()[0]; + if (c is >= 'a' and <= 'z' or ' ') { SendAltKeyChar(c); } @@ -1271,17 +1271,17 @@ private void TakeScreenshotClientToClipboard() private string ScreenshotPrefix() { - var screenPath = Config.PathEntries.ScreenshotAbsolutePathFor(Game.System); - var name = Game.FilesystemSafeName(); + string screenPath = Config.PathEntries.ScreenshotAbsolutePathFor(Game.System); + string name = Game.FilesystemSafeName(); return Path.Combine(screenPath, name); } public void TakeScreenshot() { - var basename = $"{ScreenshotPrefix()}.{DateTime.Now:yyyy-MM-dd HH.mm.ss}"; + string basename = $"{ScreenshotPrefix()}.{DateTime.Now:yyyy-MM-dd HH.mm.ss}"; - var fnameBare = $"{basename}.png"; - var fname = $"{basename} (0).png"; + string fnameBare = $"{basename}.png"; + string fname = $"{basename} (0).png"; // if the (0) filename exists, do nothing. we'll bump up the number later // if the bare filename exists, move it to (0) @@ -1292,7 +1292,7 @@ public void TakeScreenshot() else fname = fnameBare; } - for (var seq = 0; File.Exists(fname); seq++) + for (int seq = 0; File.Exists(fname); seq++) fname = $"{basename} ({seq}).png"; TakeScreenshot(fname); @@ -1300,7 +1300,7 @@ public void TakeScreenshot() public void TakeScreenshot(string path) { - var fi = new FileInfo(path); + FileInfo fi = new(path); if (fi.Directory != null && !fi.Directory.Exists) { fi.Directory.Create(); @@ -1334,7 +1334,7 @@ public void FrameBufferResized() int borderHeight = Size.Height - _presentationPanel.Control.Size.Height; // start at target zoom and work way down until we find acceptable zoom - Size lastComputedSize = new Size(1, 1); + Size lastComputedSize = new(1, 1); for (; zoom >= 1; zoom--) { lastComputedSize = DisplayManager.CalculateClientSize(_currentVideoProvider, zoom); @@ -1472,10 +1472,7 @@ public void ToggleFullscreen(bool allowSuppress = false) } } - private void OpenLuaConsole() - { - Tools.Load(); - } + private void OpenLuaConsole() => Tools.Load(); public void ClickSpeedItem(int num) { @@ -1489,15 +1486,9 @@ public void ClickSpeedItem(int num) } } - public void Unthrottle() - { - Config.Unthrottled = true; - } + public void Unthrottle() => Config.Unthrottled = true; - public void Throttle() - { - Config.Unthrottled = false; - } + public void Throttle() => Config.Unthrottled = false; private void ThrottleMessage() { @@ -1523,10 +1514,7 @@ private void ThrottleMessage() AddOnScreenMessage(msg); } - public void FrameSkipMessage() - { - AddOnScreenMessage($"Frameskipping set to {Config.FrameSkip}"); - } + public void FrameSkipMessage() => AddOnScreenMessage($"Frameskipping set to {Config.FrameSkip}"); public void UpdateCheatStatus() { @@ -1679,7 +1667,7 @@ public bool RunLibretroCoreChooser() initDir = Config.PathEntries.AbsolutePathForType(VSystemID.Raw.Libretro, "Cores"); Directory.CreateDirectory(initDir); } - var result = this.ShowFileOpenDialog( + string result = this.ShowFileOpenDialog( discardCWDChange: true, filter: LibretroCoresFSFilterSet, initDir: initDir!, @@ -1689,8 +1677,8 @@ public bool RunLibretroCoreChooser() return true; } - private Size _lastVideoSize = new Size(-1, -1), _lastVirtualSize = new Size(-1, -1); - private readonly SaveSlotManager _stateSlots = new SaveSlotManager(); + private Size _lastVideoSize = new(-1, -1), _lastVirtualSize = new(-1, -1); + private readonly SaveSlotManager _stateSlots = new(); // AVI/WAV state private IVideoWriter _currAviWriter; @@ -1748,7 +1736,7 @@ public bool RunLibretroCoreChooser() // input state which has been destined for game controller inputs are coalesced here // public static ControllerInputCoalescer ControllerInputCoalescer = new ControllerInputCoalescer(); // input state which has been destined for client hotkey consumption are colesced here - private readonly InputCoalescer _hotkeyCoalescer = new InputCoalescer(); + private readonly InputCoalescer _hotkeyCoalescer = new(); private readonly PresentationPanel _presentationPanel; @@ -1769,7 +1757,7 @@ protected override string WindowTitle { get { - var sb = new StringBuilder(); + StringBuilder sb = new(); if (_inResizeLoop) { @@ -1805,7 +1793,7 @@ protected override string WindowTitleStatic { get { - var sb = new StringBuilder(); + StringBuilder sb = new(); sb.Append(string.IsNullOrEmpty(VersionInfo.CustomBuildString) ? "BizHawk" : VersionInfo.CustomBuildString); @@ -1925,11 +1913,11 @@ private void LoadSaveRam() { try // zero says: this is sort of sketchy... but this is no time for rearchitecting { - var saveRamPath = Config.PathEntries.SaveRamAbsolutePath(Game, MovieSession.Movie); + string saveRamPath = Config.PathEntries.SaveRamAbsolutePath(Game, MovieSession.Movie); if (Config.AutosaveSaveRAM) { - var saveram = new FileInfo(saveRamPath); - var autosave = new FileInfo(Config.PathEntries.AutoSaveRamAbsolutePath(Game, MovieSession.Movie)); + FileInfo saveram = new(saveRamPath); + FileInfo autosave = new(Config.PathEntries.AutoSaveRamAbsolutePath(Game, MovieSession.Movie)); if (autosave.Exists && autosave.LastWriteTime > saveram.LastWriteTime) { AddOnScreenMessage("AutoSaveRAM is newer than last saved SaveRAM"); @@ -1945,7 +1933,7 @@ private void LoadSaveRam() } else { - var oldRam = Emulator.AsSaveRam().CloneSaveRam(); + byte[] oldRam = Emulator.AsSaveRam().CloneSaveRam(); if (oldRam == null) { // we're eating this one now. The possible negative consequence is that a user could lose @@ -1956,7 +1944,7 @@ private void LoadSaveRam() // why do we silently truncate\pad here instead of warning\erroring? sram = new byte[oldRam.Length]; - using var reader = new BinaryReader(new FileStream(saveRamPath, FileMode.Open, FileAccess.Read)); + using BinaryReader reader = new(new FileStream(saveRamPath, FileMode.Open, FileAccess.Read)); reader.Read(sram, 0, sram.Length); } @@ -1985,11 +1973,11 @@ public bool FlushSaveRAM(bool autosave = false) path = Config.PathEntries.SaveRamAbsolutePath(Game, MovieSession.Movie); } - var file = new FileInfo(path); - var newPath = $"{path}.new"; - var newFile = new FileInfo(newPath); - var backupPath = $"{path}.bak"; - var backupFile = new FileInfo(backupPath); + FileInfo file = new(path); + string newPath = $"{path}.new"; + FileInfo newFile = new(newPath); + string backupPath = $"{path}.bak"; + FileInfo backupFile = new(backupPath); if (file.Directory != null && !file.Directory.Exists) { try @@ -2003,11 +1991,11 @@ public bool FlushSaveRAM(bool autosave = false) } } - var saveram = Emulator.AsSaveRam().CloneSaveRam(); + byte[] saveram = Emulator.AsSaveRam().CloneSaveRam(); if (saveram == null) return true; - using (var writer = new BinaryWriter(new FileStream(newPath, FileMode.Create, FileAccess.Write))) + using (BinaryWriter writer = new(new FileStream(newPath, FileMode.Create, FileAccess.Write))) writer.Write(saveram, 0, saveram.Length); if (file.Exists) @@ -2053,7 +2041,7 @@ private void HandlePlatformMenus() { if (GenericCoreSubMenu.Visible) { - var i = GenericCoreSubMenu.Text.IndexOf('&'); + int i = GenericCoreSubMenu.Text.IndexOf('&'); if (i != -1) AvailableAccelerators.Add(GenericCoreSubMenu.Text[i + 1]); } GenericCoreSubMenu.Visible = false; @@ -2073,7 +2061,7 @@ private void HandlePlatformMenus() zXSpectrumToolStripMenuItem.Visible = false; amstradCPCToolStripMenuItem.Visible = false; - var sysID = Emulator.SystemId; + string sysID = Emulator.SystemId; switch (sysID) { case VSystemID.Raw.NULL: @@ -2152,11 +2140,11 @@ private ISet AvailableAccelerators if (_availableAccelerators == null) { _availableAccelerators = new HashSet(); - for (var c = 'A'; c <= 'Z'; c++) _availableAccelerators.Add(c); + for (char c = 'A'; c <= 'Z'; c++) _availableAccelerators.Add(c); foreach (ToolStripItem item in MainMenuStrip.Items) { if (!item.Visible) continue; - var i = item.Text.IndexOf('&'); + int i = item.Text.IndexOf('&'); if (i == -1 || i == item.Text.Length - 1) continue; _availableAccelerators.Remove(char.ToUpperInvariant(item.Text[i + 1])); } @@ -2168,10 +2156,10 @@ private ISet AvailableAccelerators private void DisplayDefaultCoreMenu() { GenericCoreSubMenu.Visible = true; - var sysID = Emulator.SystemId; - for (var i = 0; i < sysID.Length; i++) + string sysID = Emulator.SystemId; + for (int i = 0; i < sysID.Length; i++) { - var upper = char.ToUpperInvariant(sysID[i]); + char upper = char.ToUpperInvariant(sysID[i]); if (AvailableAccelerators.Contains(upper)) { AvailableAccelerators.Remove(upper); @@ -2182,11 +2170,11 @@ private void DisplayDefaultCoreMenu() GenericCoreSubMenu.Text = sysID; GenericCoreSubMenu.DropDownItems.Clear(); - var settingsMenuItem = new ToolStripMenuItem { Text = "&Settings" }; + ToolStripMenuItem settingsMenuItem = new() { Text = "&Settings" }; settingsMenuItem.Click += GenericCoreSettingsMenuItem_Click; GenericCoreSubMenu.DropDownItems.Add(settingsMenuItem); - var specializedTools = SpecializedTools.Where(Tools.IsAvailable).OrderBy(static t => t.Name).ToList(); + List specializedTools = SpecializedTools.Where(Tools.IsAvailable).OrderBy(static t => t.Name).ToList(); if (specializedTools.Count is 0) return; GenericCoreSubMenu.DropDownItems.Add(new ToolStripSeparator()); @@ -2234,7 +2222,7 @@ private void LoadRomFromRecent(string rom) { var ioa = OpenAdvancedSerializer.ParseWithLegacy(rom); - var args = new LoadRomArgs + LoadRomArgs args = new() { OpenAdvanced = ioa }; @@ -2242,7 +2230,7 @@ private void LoadRomFromRecent(string rom) // if(ioa is this or that) - for more complex behaviour string romPath = ioa.SimplePath; - if (!LoadRom(romPath, args, out var failureIsFromAskSave)) + if (!LoadRom(romPath, args, out bool failureIsFromAskSave)) { if (failureIsFromAskSave) AddOnScreenMessage("ROM loading cancelled; a tool had unsaved changes"); else if (ioa is OpenAdvanced_LibretroNoGame || File.Exists(romPath)) AddOnScreenMessage("ROM loading failed"); @@ -2288,9 +2276,9 @@ private void SyncThrottle() // skips outputting the audio. There's also a third way which is when no throttle // method is selected, but the clock throttle determines that by itself and // everything appears normal here. - var rewind = Rewinder?.Active == true && (InputManager.ClientControls["Rewind"] || PressRewind); - var fastForward = InputManager.ClientControls["Fast Forward"] || FastForward; - var turbo = IsTurboing; + bool rewind = Rewinder?.Active == true && (InputManager.ClientControls["Rewind"] || PressRewind); + bool fastForward = InputManager.ClientControls["Fast Forward"] || FastForward; + bool turbo = IsTurboing; int speedPercent = fastForward ? Config.SpeedPercentAlternate : Config.SpeedPercent; @@ -2364,7 +2352,7 @@ private void CheckMessages() _singleInstanceForwardedArgs.Clear(); } } - foreach (var args in todo) SingleInstanceProcessArgs(args); + foreach (string[] args in todo) SingleInstanceProcessArgs(args); } private void AutohideCursor(bool hide) @@ -2385,7 +2373,7 @@ private void AutohideCursor(bool hide) public BitmapBuffer MakeScreenshotImage() { - var ret = new BitmapBuffer(_currentVideoProvider.BufferWidth, _currentVideoProvider.BufferHeight, _currentVideoProvider.GetVideoBuffer().ToArray()); + BitmapBuffer ret = new(_currentVideoProvider.BufferWidth, _currentVideoProvider.BufferHeight, _currentVideoProvider.GetVideoBuffer().ToArray()); ret.DiscardAlpha(); return ret; } @@ -2406,8 +2394,8 @@ private void SaveSlotSelectedMessage() } var video = _currentVideoProvider; - Size currVideoSize = new Size(video.BufferWidth, video.BufferHeight); - Size currVirtualSize = new Size(video.VirtualWidth, video.VirtualHeight); + Size currVideoSize = new(video.BufferWidth, video.BufferHeight); + Size currVirtualSize = new(video.VirtualWidth, video.VirtualHeight); bool resizeFramebuffer = currVideoSize != _lastVideoSize || currVirtualSize != _lastVirtualSize; @@ -2438,7 +2426,7 @@ private void SaveSlotSelectedMessage() // sends a simulation of a plain alt key keystroke private void SendPlainAltKey(int lparam) { - var m = new Message { WParam = new IntPtr(0xF100), LParam = new IntPtr(lparam), Msg = 0x0112, HWnd = Handle }; + Message m = new() { WParam = new IntPtr(0xF100), LParam = new IntPtr(lparam), Msg = 0x0112, HWnd = Handle }; base.WndProc(ref m); } @@ -2459,12 +2447,12 @@ private void SendAltKeyChar(char c) private void OpenRom() { - var result = this.ShowFileOpenDialog( + string result = this.ShowFileOpenDialog( filter: RomLoader.RomFilter, filterIndex: ref _lastOpenRomFilter, initDir: Config.PathEntries.RomAbsolutePath(Emulator.SystemId)); if (result is null) return; - var filePath = new FileInfo(result).FullName; + string filePath = new FileInfo(result).FullName; _ = LoadRom(filePath, new LoadRomArgs { OpenAdvanced = new OpenAdvanced_OpenRom { Path = filePath } }); } @@ -2497,10 +2485,7 @@ private void CoreSyncSettings(object sender, RomLoader.SettingsLoadArgs e) } } - private void CoreSettings(object sender, RomLoader.SettingsLoadArgs e) - { - e.Settings = Config.GetCoreSettings(e.Core, e.SettingsType); - } + private void CoreSettings(object sender, RomLoader.SettingsLoadArgs e) => e.Settings = Config.GetCoreSettings(e.Core, e.SettingsType); private void HandlePutCoreSettings(PutSettingsDirtyBits dirty) { @@ -2570,25 +2555,13 @@ private void SaveConfig(string path = "") ConfigService.Save(path, Config); } - private void ToggleFps() - { - Config.DisplayFps ^= true; - } + private void ToggleFps() => Config.DisplayFps ^= true; - private void ToggleFrameCounter() - { - Config.DisplayFrameCounter ^= true; - } + private void ToggleFrameCounter() => Config.DisplayFrameCounter ^= true; - private void ToggleLagCounter() - { - Config.DisplayLagCounter ^= true; - } + private void ToggleLagCounter() => Config.DisplayLagCounter ^= true; - private void ToggleInputDisplay() - { - Config.DisplayInput ^= true; - } + private void ToggleInputDisplay() => Config.DisplayInput ^= true; public void ToggleSound() { @@ -2788,7 +2761,7 @@ private void IncreaseSpeed() if (!CheckCanSetSpeed()) return; - var oldPercent = Config.SpeedPercent; + int oldPercent = Config.SpeedPercent; int newPercent; int i = 0; @@ -2807,7 +2780,7 @@ private void DecreaseSpeed() if (!CheckCanSetSpeed()) return; - var oldPercent = Config.SpeedPercent; + int oldPercent = Config.SpeedPercent; int newPercent; int i = SpeedPercents.Length - 1; @@ -2834,7 +2807,7 @@ private void HandleToggleLightAndLink() { if (MainStatusBar.Visible) { - var hasDriveLight = Emulator.HasDriveLight() && Emulator.AsDriveLight().DriveLightEnabled; + bool hasDriveLight = Emulator.HasDriveLight() && Emulator.AsDriveLight().DriveLightEnabled; if (hasDriveLight) { @@ -2904,10 +2877,7 @@ private void ToggleBackgroundInput() AddOnScreenMessage($"Background Input {(Config.AcceptBackgroundInput ? "enabled" : "disabled")}"); } - private void VsyncMessage() - { - AddOnScreenMessage($"Display Vsync set to {(Config.VSync ? "on" : "off")}"); - } + private void VsyncMessage() => AddOnScreenMessage($"Display Vsync set to {(Config.VSync ? "on" : "off")}"); private void FdsInsertDiskMenuAdd(string name, string button, string msg) { @@ -2941,16 +2911,14 @@ protected override void WndProc(ref Message m) base.WndProc(ref m); } - protected override bool ProcessDialogChar(char charCode) - { + protected override bool ProcessDialogChar(char charCode) => // this is necessary to trap alt+char combinations so that only our hotkey system gets them - return (ModifierKeys & Keys.Alt) != 0 || base.ProcessDialogChar(charCode); - } + (ModifierKeys & Keys.Alt) != 0 || base.ProcessDialogChar(charCode); private void UpdateCoreStatusBarButton() { var attributes = Emulator.Attributes(); - var coreDispName = attributes.Released ? attributes.CoreName : $"(Experimental) {attributes.CoreName}"; + string coreDispName = attributes.Released ? attributes.CoreName : $"(Experimental) {attributes.CoreName}"; LoadedCoreNameMenuItem.Text = $"Loaded core: {coreDispName} ({Emulator.SystemId})"; if (Emulator.IsNull()) { @@ -2967,13 +2935,13 @@ private void UpdateCoreStatusBarButton() if (Emulator.SystemId == VSystemID.Raw.ZXSpectrum) { - var core = (Emulation.Cores.Computers.SinclairSpectrum.ZXSpectrum)Emulator; + Emulation.Cores.Computers.SinclairSpectrum.ZXSpectrum core = (Emulation.Cores.Computers.SinclairSpectrum.ZXSpectrum)Emulator; CoreNameStatusBarButton.ToolTipText = core.GetMachineType(); } if (Emulator.SystemId == VSystemID.Raw.AmstradCPC) { - var core = (Emulation.Cores.Computers.AmstradCPC.AmstradCPC)Emulator; + Emulation.Cores.Computers.AmstradCPC.AmstradCPC core = (Emulation.Cores.Computers.AmstradCPC.AmstradCPC)Emulator; CoreNameStatusBarButton.ToolTipText = core.GetMachineType(); } } @@ -3043,9 +3011,9 @@ public void SeekFrameAdvance() private void StepRunLoop_Core(bool force = false) { - var runFrame = false; + bool runFrame = false; _runloopFrameAdvance = false; - var currentTimestamp = Stopwatch.GetTimestamp(); + long currentTimestamp = Stopwatch.GetTimestamp(); double frameAdvanceTimestampDeltaMs = (double)(currentTimestamp - _frameAdvanceTimestamp) / Stopwatch.Frequency * 1000.0; bool frameProgressTimeElapsed = frameAdvanceTimestampDeltaMs >= Config.FrameProgressDelayMs; @@ -3112,15 +3080,15 @@ private void StepRunLoop_Core(bool force = false) runFrame = true; } - bool isRewinding = Rewind(ref runFrame, currentTimestamp, out var returnToRecording); + bool isRewinding = Rewind(ref runFrame, currentTimestamp, out bool returnToRecording); float atten = 0; // BlockFrameAdvance (true when input it being editted in TAStudio) supercedes all other frame advance conditions if ((runFrame || force) && !BlockFrameAdvance) { - var isFastForwarding = InputManager.ClientControls["Fast Forward"] || IsTurboing || InvisibleEmulation; - var isFastForwardingOrRewinding = isFastForwarding || isRewinding || Config.Unthrottled; + bool isFastForwarding = InputManager.ClientControls["Fast Forward"] || IsTurboing || InvisibleEmulation; + bool isFastForwardingOrRewinding = isFastForwarding || isRewinding || Config.Unthrottled; if (isFastForwardingOrRewinding != _lastFastForwardingOrRewinding) { @@ -3306,7 +3274,7 @@ private void CalcFramerateAndUpdateDisplay(long currentTimestamp, bool isRewindi _framesSinceLastFpsUpdate = 0; _timestampLastFpsUpdate = currentTimestamp; - var fpsString = $"{_lastFpsRounded} fps"; + string fpsString = $"{_lastFpsRounded} fps"; if (isRewinding) { fpsString += IsTurboing || isFastForwarding ? @@ -3338,18 +3306,12 @@ private void InitializeFpsData() /// /// match the short name of an /// filename to save to - private void RecordAv(string videoWriterName, string filename) - { - RecordAvBase(videoWriterName, filename, true); - } + private void RecordAv(string videoWriterName, string filename) => RecordAvBase(videoWriterName, filename, true); /// /// start AV recording, asking user for filename and options /// - private void RecordAv() - { - RecordAvBase(null, null, false); - } + private void RecordAv() => RecordAvBase(null, null, false); /// /// start AV recording @@ -3449,7 +3411,7 @@ private void RecordAvBase(string videoWriterName, string filename, bool unattend // handle directories first if (ext == "") { - using var fbd = new FolderBrowserEx(); + using FolderBrowserEx fbd = new(); if (this.ShowDialogWithTempMute(fbd) is DialogResult.Cancel) { aw.Dispose(); @@ -3460,7 +3422,7 @@ private void RecordAvBase(string videoWriterName, string filename, bool unattend } else { - var result = this.ShowFileSaveDialog( + string result = this.ShowFileSaveDialog( filter: new(new FilesystemFilter(ext, new[] { ext })), initDir: Config.PathEntries.AvAbsolutePath(), initFileName: $"{Game.FilesystemSafeName()}.{ext}"); @@ -3578,7 +3540,7 @@ private void AvFrameAdvance() Bitmap bmpOut = new(width: Config.AVWriterResizeWidth, height: Config.AVWriterResizeHeight, PixelFormat.Format32bppArgb); bmpIn = bbIn.ToSysdrawingBitmap(); - using (var g = Graphics.FromImage(bmpOut)) + using (Graphics g = Graphics.FromImage(bmpOut)) { if (Config.AVWriterPad) { @@ -3657,7 +3619,7 @@ private void AvFrameAdvance() private int? LoadArchiveChooser(HawkFile file) { - using var ac = new ArchiveChooser(file); + using ArchiveChooser ac = new(file); if (this.ShowDialogAsChild(ac).IsOk()) { return ac.SelectedMemberIndex; @@ -3668,7 +3630,7 @@ private void AvFrameAdvance() public string SaveStatePrefix() { - var name = Game.FilesystemSafeName(); + string name = Game.FilesystemSafeName(); name += $".{Emulator.Attributes().CoreName}"; // Bsnes profiles have incompatible savestates so save the profile name @@ -3682,7 +3644,7 @@ public string SaveStatePrefix() name += $".{Path.GetFileNameWithoutExtension(MovieSession.Movie.Filename)}"; } - var pathEntry = Config.PathEntries.SaveStateAbsolutePath(Game.System); + string pathEntry = Config.PathEntries.SaveStateAbsolutePath(Game.System); return Path.Combine(pathEntry, name); } @@ -3721,7 +3683,7 @@ private void ShowLoadError(object sender, RomLoader.RomErrorArgs e) private string ChoosePlatformForRom(RomGame rom) { - using var platformChooser = new PlatformChooser(Config) + using PlatformChooser platformChooser = new(Config) { RomGame = rom }; @@ -3742,7 +3704,7 @@ public bool LoadRom(string path, LoadRomArgs args, out bool failureIsFromAskSave // what's the meaning of the last rom path when opening an archive? based on the archive file location if (args.OpenAdvanced is OpenAdvanced_OpenRom) { - var leftPart = path.Split('|')[0]; + string leftPart = path.Split('|')[0]; Config.PathEntries.LastRomPath = Path.GetFullPath(Path.GetDirectoryName(leftPart) ?? ""); } @@ -3786,7 +3748,7 @@ private bool LoadRomInternal(string path, LoadRomArgs args, out bool failureIsFr return false; } - var loader = new RomLoader(Config) + RomLoader loader = new(Config) { ChooseArchive = LoadArchiveChooser, ChoosePlatform = ChoosePlatformForRom, @@ -3808,19 +3770,16 @@ private bool LoadRomInternal(string path, LoadRomArgs args, out bool failureIsFr var nextComm = CreateCoreComm(); - IOpenAdvanced ioa = args.OpenAdvanced; - var oaOpenrom = ioa as OpenAdvanced_OpenRom; - var ioaRetro = ioa as IOpenAdvancedLibretro; + var ioa = args.OpenAdvanced; + OpenAdvanced_OpenRom oaOpenrom = ioa as OpenAdvanced_OpenRom; + IOpenAdvancedLibretro ioaRetro = ioa as IOpenAdvancedLibretro; // we need to inform LoadRom which Libretro core to use... if (ioaRetro != null) { // prepare a core specification // if it wasn't already specified, use the current default - if (ioaRetro.CorePath == null) - { - ioaRetro.CorePath = Config.LibretroCore; - } + ioaRetro.CorePath ??= Config.LibretroCore; if (ioaRetro.CorePath == null) { @@ -3837,7 +3796,7 @@ private bool LoadRomInternal(string path, LoadRomArgs args, out bool failureIsFr DisplayManager.ActivateOpenGLContext(); // required in case the core wants to create a shared OpenGL context - var result = loader.LoadRom(path, nextComm, ioaRetro?.CorePath, forcedCoreName: MovieSession.QueuedCoreName); + bool result = loader.LoadRom(path, nextComm, ioaRetro?.CorePath, forcedCoreName: MovieSession.QueuedCoreName); if (result) Game = loader.Game; @@ -3873,13 +3832,13 @@ private bool LoadRomInternal(string path, LoadRomArgs args, out bool failureIsFr { // this is a multi-disk bundler file // determine the xml assets and create RomStatusDetails for all of them - var xmlGame = XmlGame.Create(new HawkFile(oaOpenrom.Path)); + XmlGame xmlGame = XmlGame.Create(new HawkFile(oaOpenrom.Path)); - using var xSw = new StringWriter(); + using StringWriter xSw = new(); for (int xg = 0; xg < xmlGame.Assets.Count; xg++) { - var ext = Path.GetExtension(xmlGame.AssetFullPaths[xg])?.ToLowerInvariant(); + string ext = Path.GetExtension(xmlGame.AssetFullPaths[xg])?.ToLowerInvariant(); var (filename, data) = xmlGame.Assets[xg]; if (Disc.IsValidExtension(ext)) @@ -3924,7 +3883,7 @@ private bool LoadRomInternal(string path, LoadRomArgs args, out bool failureIsFr } } - var romDetails = Emulator.RomDetails(); + string romDetails = Emulator.RomDetails(); if (string.IsNullOrWhiteSpace(romDetails) && loader.Rom != null) { _defaultRomDetails = $"{loader.Game.Name}\r\n{SHA1Checksum.ComputePrefixedHex(loader.Rom.RomData)}\r\n{MD5Checksum.ComputePrefixedHex(loader.Rom.RomData)}\r\n"; @@ -4069,7 +4028,7 @@ private void CloseGame(bool clearSram = false) GameIsClosing = true; if (clearSram) { - var path = Config.PathEntries.SaveRamAbsolutePath(Game, MovieSession.Movie); + string path = Config.PathEntries.SaveRamAbsolutePath(Game, MovieSession.Movie); if (File.Exists(path)) { File.Delete(path); @@ -4080,7 +4039,7 @@ private void CloseGame(bool clearSram = false) { if (!FlushSaveRAM()) { - var msgRes = ShowMessageBox2( + bool msgRes = ShowMessageBox2( owner: null, "Failed flushing the game's Save RAM to your disk.\nClose without flushing Save RAM?", "Directory IO Error", @@ -4214,20 +4173,11 @@ public void DisableRewind() private bool IsRewindSlave => IsSlave && Master.WantsToControlRewind; - public void RelinquishControl(IControlMainform master) - { - Master = master; - } + public void RelinquishControl(IControlMainform master) => Master = master; - public void TakeBackControl() - { - Master = null; - } + public void TakeBackControl() => Master = null; - private int SlotToInt(string slot) - { - return int.Parse(slot.Substring(slot.Length - 1, 1)); - } + private int SlotToInt(string slot) => int.Parse(slot.Substring(slot.Length - 1, 1)); public bool LoadState(string path, string userFriendlyStateName, bool suppressOSD = false) // Move to client.common { @@ -4273,13 +4223,13 @@ public bool LoadQuickSave(int slot, bool suppressOSD = false) { if (!Emulator.HasSavestates()) return false; - var quickSlotName = $"QuickSave{slot % 10}"; - EmuClient.OnBeforeQuickLoad(this, quickSlotName, out var handled); + string quickSlotName = $"QuickSave{slot % 10}"; + EmuClient.OnBeforeQuickLoad(this, quickSlotName, out bool handled); if (handled) return true; // not sure if (IsSavestateSlave) return Master.LoadQuickSave(SlotToInt(quickSlotName)); - var path = $"{SaveStatePrefix()}.{quickSlotName}.State"; + string path = $"{SaveStatePrefix()}.{quickSlotName}.State"; if (!File.Exists(path)) { AddOnScreenMessage($"Unable to load {quickSlotName}.State"); @@ -4332,8 +4282,8 @@ public void SaveQuickSave(int slot, bool suppressOSD = false, bool fromLua = fal { return; } - var quickSlotName = $"QuickSave{slot % 10}"; - EmuClient.OnBeforeQuickSave(this, quickSlotName, out var handled); + string quickSlotName = $"QuickSave{slot % 10}"; + EmuClient.OnBeforeQuickSave(this, quickSlotName, out bool handled); if (handled) { return; @@ -4345,9 +4295,9 @@ public void SaveQuickSave(int slot, bool suppressOSD = false, bool fromLua = fal return; } - var path = $"{SaveStatePrefix()}.{quickSlotName}.State"; + string path = $"{SaveStatePrefix()}.{quickSlotName}.State"; - var file = new FileInfo(path); + FileInfo file = new(path); if (file.Directory != null && !file.Directory.Exists) { file.Directory.Create(); @@ -4371,7 +4321,7 @@ public bool EnsureCoreIsAccurate() { bool PromptToSwitchCore(string currentCore, string recommendedCore, Action disableCurrentCore) { - using var box = new MsgBox( + using MsgBox box = new( $"While the {currentCore} core is faster, it is not nearly as accurate as {recommendedCore}.{Environment.NewLine}It is recommended that you switch to the {recommendedCore} core for movie recording.{Environment.NewLine}Switch to {recommendedCore}?", "Accuracy Warning", MessageBoxIcon.Warning); @@ -4418,15 +4368,15 @@ private void SaveStateAs() return; } - var path = Config.PathEntries.SaveStateAbsolutePath(Game.System); + string path = Config.PathEntries.SaveStateAbsolutePath(Game.System); - var file = new FileInfo(path); + FileInfo file = new(path); if (file.Directory != null && !file.Directory.Exists) { file.Directory.Create(); } - var result = this.ShowFileSaveDialog( + string result = this.ShowFileSaveDialog( fileExt: "State", filter: EmuHawkSaveStatesFSFilterSet, initDir: path, @@ -4444,7 +4394,7 @@ private bool LoadStateAs() if (!Emulator.HasSavestates()) return false; if (IsSavestateSlave) return Master.LoadStateAs(); - var result = this.ShowFileOpenDialog( + string result = this.ShowFileOpenDialog( discardCWDChange: true, filter: EmuHawkSaveStatesFSFilterSet, initDir: Config.PathEntries.SaveStateAbsolutePath(Game.System)); @@ -4457,7 +4407,7 @@ private void SelectSlot(int slot) if (!Emulator.HasSavestates()) return; if (IsSavestateSlave) { - var handled = Master.SelectSlot(slot); + bool handled = Master.SelectSlot(slot); if (handled) return; } Config.SaveSlot = slot; @@ -4470,7 +4420,7 @@ private void PreviousSlot() if (!Emulator.HasSavestates()) return; if (IsSavestateSlave) { - var handled = Master.PreviousSlot(); + bool handled = Master.PreviousSlot(); if (handled) return; } Config.SaveSlot--; @@ -4484,7 +4434,7 @@ private void NextSlot() if (!Emulator.HasSavestates()) return; if (IsSavestateSlave) { - var handled = Master.NextSlot(); + bool handled = Master.NextSlot(); if (handled) return; } Config.SaveSlot++; @@ -4507,7 +4457,7 @@ private void CaptureRewind(bool suppressCaptureRewind) private bool Rewind(ref bool runFrame, long currentTimestamp, out bool returnToRecording) { - var isRewinding = false; + bool isRewinding = false; returnToRecording = false; @@ -4585,7 +4535,7 @@ private bool Rewind(ref bool runFrame, long currentTimestamp, out bool returnToR { // Try to avoid the previous frame: We want to frame advance right after rewinding so we can give a useful // framebuffer. - var frameToAvoid = Emulator.Frame - 1; + int frameToAvoid = Emulator.Frame - 1; runFrame = Rewinder.Rewind(frameToAvoid); if (Emulator.Frame == frameToAvoid) { @@ -4728,20 +4678,17 @@ private bool SingleInstanceInit(string[] args) } } - private void SingleInstanceDispose() - { - _singleInstanceServer?.Dispose(); - } + private void SingleInstanceDispose() => _singleInstanceServer?.Dispose(); private void ForwardSingleInstanceStartup(string[] args) { - using var namedPipeClientStream = new NamedPipeClientStream(".", "pipe-{84125ACB-F570-4458-9748-321F887FE795}", PipeDirection.Out); + using NamedPipeClientStream namedPipeClientStream = new(".", "pipe-{84125ACB-F570-4458-9748-321F887FE795}", PipeDirection.Out); try { namedPipeClientStream.Connect(0); //do this a bit cryptically to avoid loading up another big assembly (especially ones as frail as http and/or web ones) - var payloadString = string.Join("|", args.Select(a => Encoding.UTF8.GetBytes(a).BytesToHexString())); - var payloadBytes = Encoding.ASCII.GetBytes(payloadString); + string payloadString = string.Join("|", args.Select(a => Encoding.UTF8.GetBytes(a).BytesToHexString())); + byte[] payloadBytes = Encoding.ASCII.GetBytes(payloadString); namedPipeClientStream.Write(payloadBytes, 0, payloadBytes.Length); } catch @@ -4755,13 +4702,13 @@ private void StartSingleInstanceServer() //MIT LICENSE - https://www.autoitconsulting.com/site/development/single-instance-winform-app-csharp-mutex-named-pipes/ // Create a new pipe accessible by local authenticated users, disallow network - var sidNetworkService = new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null); - var sidWorld = new SecurityIdentifier(WellKnownSidType.WorldSid, null); + SecurityIdentifier sidNetworkService = new(WellKnownSidType.NetworkServiceSid, null); + SecurityIdentifier sidWorld = new(WellKnownSidType.WorldSid, null); - var pipeSecurity = new PipeSecurity(); + PipeSecurity pipeSecurity = new(); // Deny network access to the pipe - var accessRule = new PipeAccessRule(sidNetworkService, PipeAccessRights.ReadWrite, AccessControlType.Deny); + PipeAccessRule accessRule = new(sidNetworkService, PipeAccessRights.ReadWrite, AccessControlType.Deny); pipeSecurity.AddAccessRule(accessRule); // Alow Everyone to read/write @@ -4769,7 +4716,7 @@ private void StartSingleInstanceServer() pipeSecurity.AddAccessRule(accessRule); // Current user is the owner - SecurityIdentifier sidOwner = WindowsIdentity.GetCurrent().Owner; + var sidOwner = WindowsIdentity.GetCurrent().Owner; if (sidOwner != null) { accessRule = new PipeAccessRule(sidOwner, PipeAccessRights.FullControl, AccessControlType.Allow); @@ -4802,17 +4749,17 @@ private void SingleInstanceServerPipeCallback(IAsyncResult iAsyncResult) //a bit over-engineered in case someone wants to send a script or a rom or something //buffer size is set to something tiny so that we are continually testing it - var payloadBytes = new MemoryStream(); + MemoryStream payloadBytes = new(); while (true) { - var bytes = new byte[16]; + byte[] bytes = new byte[16]; int did = _singleInstanceServer.Read(bytes, 0, bytes.Length); payloadBytes.Write(bytes, 0, did); if (_singleInstanceServer.IsMessageComplete) break; } - var payloadString = System.Text.Encoding.ASCII.GetString(payloadBytes.GetBuffer(), 0, (int)payloadBytes.Length); - var args = payloadString.Split('|').Select(a => Encoding.UTF8.GetString(a.HexStringToBytes())).ToArray(); + string payloadString = System.Text.Encoding.ASCII.GetString(payloadBytes.GetBuffer(), 0, (int)payloadBytes.Length); + string[] args = payloadString.Split('|').Select(a => Encoding.UTF8.GetString(a.HexStringToBytes())).ToArray(); Console.WriteLine("RECEIVED SINGLE INSTANCE FORWARDED ARGS:"); lock (_singleInstanceForwardedArgs) @@ -4839,8 +4786,7 @@ private void SingleInstanceServerPipeCallback(IAsyncResult iAsyncResult) StartSingleInstanceServer(); } - private void SingleInstanceProcessArgs(string[] args) - { + private void SingleInstanceProcessArgs(string[] args) => //ulp. it's not clear how to handle these. //we only have a legacy case where we can tell the form to load a rom, if it's in a sensible condition for that. //er.. let's assume it's always in a sensible condition @@ -4848,7 +4794,6 @@ private void SingleInstanceProcessArgs(string[] args) //BANZAIIIIIIIIIIIIIIIIIIIIIIIIIII _ = LoadRom(args[0]); - } private IRetroAchievements RA { get; set; } diff --git a/src/BizHawk.Client.EmuHawk/OpenAdvancedChooser.cs b/src/BizHawk.Client.EmuHawk/OpenAdvancedChooser.cs index 99394c69ee1..1b7759d3adf 100644 --- a/src/BizHawk.Client.EmuHawk/OpenAdvancedChooser.cs +++ b/src/BizHawk.Client.EmuHawk/OpenAdvancedChooser.cs @@ -70,7 +70,7 @@ private void RefreshLibretroCore(bool bootstrap) btnLibretroLaunchNoGame.Enabled = false; btnLibretroLaunchGame.Enabled = false; - var core = _config.LibretroCore; + string core = _config.LibretroCore; if (string.IsNullOrEmpty(core)) { return; @@ -83,7 +83,7 @@ private void RefreshLibretroCore(bool bootstrap) try { var coreComm = _createCoreComm(); - using var retro = new LibretroHost(coreComm, _game, core, true); + using LibretroHost retro = new(coreComm, _game, core, true); btnLibretroLaunchGame.Enabled = true; if (retro.Description.SupportsNoGame) btnLibretroLaunchNoGame.Enabled = true; @@ -111,7 +111,7 @@ private void RefreshLibretroCore(bool bootstrap) private void btnLibretroLaunchGame_Click(object sender, EventArgs e) { - var entries = new List { new FilesystemFilter("ROMs", _currentDescription.ValidExtensions.Split('|')) }; + List entries = new() { new FilesystemFilter("ROMs", _currentDescription.ValidExtensions.Split('|')) }; if (!_currentDescription.NeedsArchives) entries.Add(FilesystemFilter.Archives); // "needs archives" means the relevant archive extensions are already in the list, and we shouldn't scan archives for roms SuggestedExtensionFilter = new(entries.ToArray()); Result = AdvancedRomLoaderType.LibretroLaunchGame; @@ -144,8 +144,8 @@ private void txtLibretroCore_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { - var filePaths = (string[])e.Data.GetData(DataFormats.FileDrop); - var ext = Path.GetExtension(filePaths[0]).ToUpperInvariant(); + string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop); + string ext = Path.GetExtension(filePaths[0]).ToUpperInvariant(); if (OSTailoredCode.IsUnixHost ? ext == ".SO" : ext == ".DLL") { e.Effect = DragDropEffects.Copy; @@ -158,7 +158,7 @@ private void txtLibretroCore_DragEnter(object sender, DragEventArgs e) private void txtLibretroCore_DragDrop(object sender, DragEventArgs e) { - var filePaths = (string[])e.Data.GetData(DataFormats.FileDrop); + string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop); _config.LibretroCore = filePaths[0]; RefreshLibretroCore(false); } diff --git a/src/BizHawk.Client.EmuHawk/PlatformChooser.cs b/src/BizHawk.Client.EmuHawk/PlatformChooser.cs index 92aa384cf4f..473c8cd4842 100644 --- a/src/BizHawk.Client.EmuHawk/PlatformChooser.cs +++ b/src/BizHawk.Client.EmuHawk/PlatformChooser.cs @@ -38,7 +38,7 @@ private void PlatformChooser_Load(object sender, EventArgs e) int spacing = 25; foreach (var platform in _availableSystems) { - var radio = new RadioButton + RadioButton radio = new() { Text = platform.FullName, Location = UIHelper.Scale(new Point(15, 15 + (count * spacing))), @@ -55,14 +55,11 @@ private void PlatformChooser_Load(object sender, EventArgs e) .Select(); } - private void CancelButton_Click(object sender, EventArgs e) - { - Close(); - } + private void CancelButton_Click(object sender, EventArgs e) => Close(); private void OkBtn_Click(object sender, EventArgs e) { - var selectedValue = SelectedRadio != null ? SelectedRadio.Text : ""; + string selectedValue = SelectedRadio != null ? SelectedRadio.Text : ""; PlatformChoice = _availableSystems.First(x => x.FullName == selectedValue).SystemId; if (AlwaysCheckbox.Checked) @@ -73,9 +70,6 @@ private void OkBtn_Click(object sender, EventArgs e) Close(); } - private void label4_Click(object sender, EventArgs e) - { - AlwaysCheckbox.Checked ^= true; - } + private void label4_Click(object sender, EventArgs e) => AlwaysCheckbox.Checked ^= true; } } diff --git a/src/BizHawk.Client.EmuHawk/PresentationPanel.cs b/src/BizHawk.Client.EmuHawk/PresentationPanel.cs index 9cd9ba96c8b..5b407bbd4a9 100644 --- a/src/BizHawk.Client.EmuHawk/PresentationPanel.cs +++ b/src/BizHawk.Client.EmuHawk/PresentationPanel.cs @@ -65,7 +65,7 @@ private void HandleFullscreenToggle(object sender, MouseEventArgs e) if (e.Button == MouseButtons.Left) { // allow suppression of the toggle.. but if shift is pressed, always do the toggle - var allowSuppress = Control.ModifierKeys != Keys.Shift; + bool allowSuppress = Control.ModifierKeys != Keys.Shift; if (_config.DispChromeAllowDoubleClickFullscreen || !allowSuppress) { _fullscreenToggleCallback(allowSuppress); diff --git a/src/BizHawk.Client.EmuHawk/Program.cs b/src/BizHawk.Client.EmuHawk/Program.cs index 68c6031fee1..63600c8e7fe 100644 --- a/src/BizHawk.Client.EmuHawk/Program.cs +++ b/src/BizHawk.Client.EmuHawk/Program.cs @@ -29,7 +29,7 @@ static Program() // quickly check if the user is running this as a 32 bit process somehow if (!Environment.Is64BitProcess) { - using (var box = new ExceptionBox($"EmuHawk requires a 64 bit environment in order to run! EmuHawk will now close.")) box.ShowDialog(); + using (ExceptionBox box = new($"EmuHawk requires a 64 bit environment in order to run! EmuHawk will now close.")) box.ShowDialog(); Process.GetCurrentProcess().Kill(); return; } @@ -63,7 +63,7 @@ static Program() } // this will look in subdirectory "dll" to load pinvoked stuff - var dllDir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "dll"); + string dllDir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "dll"); _ = SetDllDirectory(dllDir); //in case assembly resolution fails, such as if we moved them into the dll subdiretory, this event handler can reroute to them @@ -76,7 +76,7 @@ static Program() // some people are getting MOTW through a combination of browser used to download bizhawk, and program used to dearchive it // We need to do it here too... otherwise people get exceptions when externaltools we distribute try to startup static void RemoveMOTW(string path) => DeleteFileW($"{path}:Zone.Identifier"); - var todo = new Queue(new[] { new DirectoryInfo(dllDir) }); + Queue todo = new(new[] { new DirectoryInfo(dllDir) }); while (todo.Count != 0) { var di = todo.Dequeue(); @@ -94,7 +94,7 @@ static Program() [STAThread] private static int Main(string[] args) { - var exitCode = SubMain(args); + int exitCode = SubMain(args); if (OSTC.IsUnixHost) { Console.WriteLine("BizHawk has completed its shutdown routines, killing process..."); @@ -146,12 +146,12 @@ private static int SubMain(string[] args) new ExceptionBox(e.Message).ShowDialog(); } - var configPath = cliFlags.cmdConfigFile ?? Path.Combine(PathUtils.ExeDirectoryPath, "config.ini"); + string configPath = cliFlags.cmdConfigFile ?? Path.Combine(PathUtils.ExeDirectoryPath, "config.ini"); Config initialConfig; try { - if (!VersionInfo.DeveloperBuild && !ConfigService.IsFromSameVersion(configPath, out var msg)) + if (!VersionInfo.DeveloperBuild && !ConfigService.IsFromSameVersion(configPath, out string msg)) { new MsgBox(msg, "Mismatched version in config file", MessageBoxIcon.Warning).ShowDialog(); } @@ -174,7 +174,7 @@ private static int SubMain(string[] args) StringLogUtil.DefaultToDisk = initialConfig.Movies.MoviesOnDisk; - var glInitCount = 0; + int glInitCount = 0; IGL TryInitIGL(EDispMethod dispMethod) { @@ -200,9 +200,9 @@ IGL CheckRenderer(IGL gl) } catch (Exception ex) { - var fallback = ChooseFallback(); - new ExceptionBox(new Exception($"Initialization of Display Method failed; falling back to {fallback.Name}", ex)).ShowDialog(); - return TryInitIGL(initialConfig.DispMethod = fallback.Method); + var (Method, Name) = ChooseFallback(); + new ExceptionBox(new Exception($"Initialization of Display Method failed; falling back to {Name}", ex)).ShowDialog(); + return TryInitIGL(initialConfig.DispMethod = Method); } } @@ -220,19 +220,19 @@ IGL CheckRenderer(IGL gl) } catch (Exception ex) { - var fallback = ChooseFallback(); - new ExceptionBox(new Exception($"Initialization of Direct3D9 Display Method failed; falling back to {fallback.Name}", ex)).ShowDialog(); - return TryInitIGL(initialConfig.DispMethod = fallback.Method); + var (Method, Name) = ChooseFallback(); + new ExceptionBox(new Exception($"Initialization of Direct3D9 Display Method failed; falling back to {Name}", ex)).ShowDialog(); + return TryInitIGL(initialConfig.DispMethod = Method); } case EDispMethod.OpenGL: if (!IGL_OpenGL.Available) { // too old to use, need to fallback to something else - var fallback = ChooseFallback(); - new ExceptionBox(new Exception($"Initialization of OpenGL Display Method failed; falling back to {fallback.Name}")).ShowDialog(); - return TryInitIGL(initialConfig.DispMethod = fallback.Method); + var (Method, Name) = ChooseFallback(); + new ExceptionBox(new Exception($"Initialization of OpenGL Display Method failed; falling back to {Name}")).ShowDialog(); + return TryInitIGL(initialConfig.DispMethod = Method); } - var igl = new IGL_OpenGL(); + IGL_OpenGL igl = new(); // need to have a context active for checking renderer, will be disposed afterwards using (new SDL2OpenGLContext(3, 0, false, false)) { @@ -262,7 +262,7 @@ IGL CheckRenderer(IGL gl) //It isn't clear whether we need the earlier SetDllDirectory(), but I think we do. //note: this is pasted instead of being put in a static method due to this initialization code being sensitive to things like that, and not wanting to cause it to break //pasting should be safe (not affecting the jit order of things) - var dllDir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "dll"); + string dllDir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "dll"); _ = SetDllDirectory(dllDir); } @@ -285,7 +285,7 @@ IGL CheckRenderer(IGL gl) FPCtrl.FixFPCtrl(); - var exitCode = 0; + int exitCode = 0; try { MainForm mf = new( @@ -296,7 +296,7 @@ IGL CheckRenderer(IGL gl) newSound => globalSound = newSound, args, out var movieSession, - out var exitEarly); + out bool exitEarly); if (exitEarly) { //TODO also use this for ArgParser failure @@ -305,7 +305,7 @@ IGL CheckRenderer(IGL gl) } mf.LoadGlobalConfigFromFile = iniPath => { - if (!VersionInfo.DeveloperBuild && !ConfigService.IsFromSameVersion(iniPath, out var msg)) + if (!VersionInfo.DeveloperBuild && !ConfigService.IsFromSameVersion(iniPath, out string msg)) { new MsgBox(msg, "Mismatched version in config file", MessageBoxIcon.Warning).ShowDialog(); } @@ -362,7 +362,7 @@ IGL CheckRenderer(IGL gl) /// http://www.codeproject.com/Articles/310675/AppDomain-AssemblyResolve-Event-Tips private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { - var requested = args.Name; + string requested = args.Name; lock (AppDomain.CurrentDomain) { @@ -370,10 +370,10 @@ private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEven if (firstAsm != null) return firstAsm; //load missing assemblies by trying to find them in the dll directory - var dllname = $"{new AssemblyName(requested).Name}.dll"; - var directory = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "dll"); - var simpleName = new AssemblyName(requested).Name; - var fname = Path.Combine(directory, dllname); + string dllname = $"{new AssemblyName(requested).Name}.dll"; + string directory = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "dll"); + string simpleName = new AssemblyName(requested).Name; + string fname = Path.Combine(directory, dllname); //it is important that we use LoadFile here and not load from a byte array; otherwise mixed (managed/unmanaged) assemblies can't load return File.Exists(fname) ? Assembly.LoadFile(fname) : null; } diff --git a/src/BizHawk.Client.EmuHawk/Properties/Resources.cs b/src/BizHawk.Client.EmuHawk/Properties/Resources.cs index c406b7c0743..0dfc34bfdd9 100644 --- a/src/BizHawk.Client.EmuHawk/Properties/Resources.cs +++ b/src/BizHawk.Client.EmuHawk/Properties/Resources.cs @@ -7,44 +7,44 @@ namespace BizHawk.Client.EmuHawk.Properties internal static class Resources { /// Dir separator is '.'. Filename is relative to <NS>/images and omits .png extension. - private static Bitmap ReadEmbeddedBitmap(string filename) => new Bitmap(EmuHawk.ReflectionCache.EmbeddedResourceStream($"images.{filename}.png")); + private static Bitmap ReadEmbeddedBitmap(string filename) => new(EmuHawk.ReflectionCache.EmbeddedResourceStream($"images.{filename}.png")); /// Dir separator is '.'. Filename is relative to <NS>/images and omits .ico extension. - private static Icon ReadEmbeddedIcon(string filename) => new Icon(EmuHawk.ReflectionCache.EmbeddedResourceStream($"images.{filename}.ico")); + private static Icon ReadEmbeddedIcon(string filename) => new(EmuHawk.ReflectionCache.EmbeddedResourceStream($"images.{filename}.ico")); /// Dir separator is '.'. Filename is relative to <NS>/images and omits .ico extension. - private static Bitmap ReadEmbeddedIconAsBitmap(string filename) => new Bitmap(EmuHawk.ReflectionCache.EmbeddedResourceStream($"images.{filename}.ico")); + private static Bitmap ReadEmbeddedIconAsBitmap(string filename) => new(EmuHawk.ReflectionCache.EmbeddedResourceStream($"images.{filename}.ico")); - internal static readonly Lazy A78Joystick = new Lazy(() => ReadEmbeddedBitmap("ControllerImages.A78Joystick")); - internal static readonly Lazy AppleIIKeyboard = new Lazy(() => ReadEmbeddedBitmap("ControllerImages.AppleIIKeyboard")); - internal static readonly Lazy ArcadeController = new Lazy(() => ReadEmbeddedBitmap("ControllerImages.ArcadeController")); - internal static readonly Lazy C64Joystick = new Lazy(() => ReadEmbeddedBitmap("ControllerImages.C64Joystick")); - internal static readonly Lazy C64Keyboard = new Lazy(() => ReadEmbeddedBitmap("ControllerImages.C64Keyboard")); - internal static readonly Lazy ColecoVisionController = new Lazy(() => ReadEmbeddedBitmap("ControllerImages.colecovisioncontroller")); - internal static readonly Lazy DSController = new Lazy(() => ReadEmbeddedBitmap("ControllerImages.DSController")); - internal static readonly Lazy GbaController = new Lazy(() => ReadEmbeddedBitmap("ControllerImages.GBA_Controller")); - internal static readonly Lazy GbController = new Lazy(() => ReadEmbeddedBitmap("ControllerImages.GBController")); - internal static readonly Lazy GenesisController = new Lazy(() => ReadEmbeddedBitmap("ControllerImages.GENController")); - internal static readonly Lazy IntVController = new Lazy(() => ReadEmbeddedBitmap("ControllerImages.IntVController")); - internal static readonly Lazy Lynx = new Lazy(() => ReadEmbeddedBitmap("ControllerImages.Lynx")); - internal static readonly Lazy N64 = new Lazy(() => ReadEmbeddedBitmap("ControllerImages.N64")); - internal static readonly Lazy NesController = new Lazy(() => ReadEmbeddedBitmap("ControllerImages.NES_Controller")); - internal static readonly Lazy NgpController = new Lazy(() => ReadEmbeddedBitmap("ControllerImages.NGPController")); - internal static readonly Lazy PceController = new Lazy(() => ReadEmbeddedBitmap("ControllerImages.PCEngineController")); - internal static readonly Lazy PsxDualShockController = new Lazy(() => ReadEmbeddedBitmap("ControllerImages.psx_dualshock")); - internal static readonly Lazy SaturnController = new Lazy(() => ReadEmbeddedBitmap("ControllerImages.SaturnController")); - internal static readonly Lazy SmsController = new Lazy(() => ReadEmbeddedBitmap("ControllerImages.SMSController")); - internal static readonly Lazy SnesController = new Lazy(() => ReadEmbeddedBitmap("ControllerImages.SNES_Controller")); - internal static readonly Lazy TI83Controller = new Lazy(() => ReadEmbeddedBitmap("ControllerImages.TI83_Controller")); - internal static readonly Lazy VBoyController = new Lazy(() => ReadEmbeddedBitmap("ControllerImages.VBoyController")); - internal static readonly Lazy WonderSwanColor = new Lazy(() => ReadEmbeddedBitmap("ControllerImages.WonderSwanColor")); - internal static readonly Lazy ZXSpectrumKeyboards = new Lazy(() => ReadEmbeddedBitmap("ControllerImages.ZXSpectrumKeyboards")); + internal static readonly Lazy A78Joystick = new(() => ReadEmbeddedBitmap("ControllerImages.A78Joystick")); + internal static readonly Lazy AppleIIKeyboard = new(() => ReadEmbeddedBitmap("ControllerImages.AppleIIKeyboard")); + internal static readonly Lazy ArcadeController = new(() => ReadEmbeddedBitmap("ControllerImages.ArcadeController")); + internal static readonly Lazy C64Joystick = new(() => ReadEmbeddedBitmap("ControllerImages.C64Joystick")); + internal static readonly Lazy C64Keyboard = new(() => ReadEmbeddedBitmap("ControllerImages.C64Keyboard")); + internal static readonly Lazy ColecoVisionController = new(() => ReadEmbeddedBitmap("ControllerImages.colecovisioncontroller")); + internal static readonly Lazy DSController = new(() => ReadEmbeddedBitmap("ControllerImages.DSController")); + internal static readonly Lazy GbaController = new(() => ReadEmbeddedBitmap("ControllerImages.GBA_Controller")); + internal static readonly Lazy GbController = new(() => ReadEmbeddedBitmap("ControllerImages.GBController")); + internal static readonly Lazy GenesisController = new(() => ReadEmbeddedBitmap("ControllerImages.GENController")); + internal static readonly Lazy IntVController = new(() => ReadEmbeddedBitmap("ControllerImages.IntVController")); + internal static readonly Lazy Lynx = new(() => ReadEmbeddedBitmap("ControllerImages.Lynx")); + internal static readonly Lazy N64 = new(() => ReadEmbeddedBitmap("ControllerImages.N64")); + internal static readonly Lazy NesController = new(() => ReadEmbeddedBitmap("ControllerImages.NES_Controller")); + internal static readonly Lazy NgpController = new(() => ReadEmbeddedBitmap("ControllerImages.NGPController")); + internal static readonly Lazy PceController = new(() => ReadEmbeddedBitmap("ControllerImages.PCEngineController")); + internal static readonly Lazy PsxDualShockController = new(() => ReadEmbeddedBitmap("ControllerImages.psx_dualshock")); + internal static readonly Lazy SaturnController = new(() => ReadEmbeddedBitmap("ControllerImages.SaturnController")); + internal static readonly Lazy SmsController = new(() => ReadEmbeddedBitmap("ControllerImages.SMSController")); + internal static readonly Lazy SnesController = new(() => ReadEmbeddedBitmap("ControllerImages.SNES_Controller")); + internal static readonly Lazy TI83Controller = new(() => ReadEmbeddedBitmap("ControllerImages.TI83_Controller")); + internal static readonly Lazy VBoyController = new(() => ReadEmbeddedBitmap("ControllerImages.VBoyController")); + internal static readonly Lazy WonderSwanColor = new(() => ReadEmbeddedBitmap("ControllerImages.WonderSwanColor")); + internal static readonly Lazy ZXSpectrumKeyboards = new(() => ReadEmbeddedBitmap("ControllerImages.ZXSpectrumKeyboards")); internal static readonly Bitmap Add = ReadEmbeddedBitmap("add"); internal static readonly Bitmap AddEdit = ReadEmbeddedBitmap("AddEdit"); internal static readonly Bitmap AddWatch = ReadEmbeddedIconAsBitmap("addWatch"); internal static readonly Bitmap ArrowBlackDown = ReadEmbeddedBitmap("arrow_black_down"); - internal static readonly Lazy AtariController = new Lazy(() => ReadEmbeddedBitmap("atari_controller")); + internal static readonly Lazy AtariController = new(() => ReadEmbeddedBitmap("atari_controller")); internal static readonly Bitmap Audio = ReadEmbeddedBitmap("AudioHS"); internal static readonly Bitmap AutoSearch = ReadEmbeddedBitmap("AutoSearch"); internal static readonly Bitmap Avi = ReadEmbeddedBitmap("AVI"); @@ -53,7 +53,7 @@ internal static class Resources internal static readonly Icon BasicBot = ReadEmbeddedIcon("basicbot"); internal static readonly Bitmap BasicBotBit = ReadEmbeddedBitmap("basicbotbit"); internal static readonly Bitmap Blank = ReadEmbeddedBitmap("Blank"); - internal static readonly Cursor BlankCursor = new Cursor(EmuHawk.ReflectionCache.EmbeddedResourceStream("images.BlankCursor.cur")); + internal static readonly Cursor BlankCursor = new(EmuHawk.ReflectionCache.EmbeddedResourceStream("images.BlankCursor.cur")); internal static readonly Bitmap BlueDown = ReadEmbeddedBitmap("BlueDown"); internal static readonly Bitmap BlueUp = ReadEmbeddedBitmap("BlueUp"); internal static readonly Bitmap Both = ReadEmbeddedBitmap("Both"); @@ -96,7 +96,7 @@ internal static class Resources internal static readonly Icon GambatteIcon = ReadEmbeddedIcon("gambatte"); internal static readonly Icon GameControllerIcon = ReadEmbeddedIcon("GameController"); internal static readonly Bitmap GameController = ReadEmbeddedBitmap("GameController"); - internal static readonly Lazy GbaIcon = new Lazy(() => ReadEmbeddedIcon("Gameboy Advance (black) icon")); + internal static readonly Lazy GbaIcon = new(() => ReadEmbeddedIcon("Gameboy Advance (black) icon")); internal static readonly Bitmap GenPlus = ReadEmbeddedBitmap("genplus"); internal static readonly Bitmap GreenCheck = ReadEmbeddedBitmap("GreenCheck"); internal static readonly Bitmap Hack = ReadEmbeddedBitmap("Hack"); diff --git a/src/BizHawk.Client.EmuHawk/RetroAchievements/LibRCheevos.cs b/src/BizHawk.Client.EmuHawk/RetroAchievements/LibRCheevos.cs index 87d135ff180..a345e0e5d0b 100644 --- a/src/BizHawk.Client.EmuHawk/RetroAchievements/LibRCheevos.cs +++ b/src/BizHawk.Client.EmuHawk/RetroAchievements/LibRCheevos.cs @@ -104,8 +104,8 @@ public struct rc_api_request_t public IntPtr post_data; public rc_api_buffer_t buffer; - public string URL => Mershul.PtrToStringUtf8(url); - public string PostData => Mershul.PtrToStringUtf8(post_data); + public readonly string URL => Mershul.PtrToStringUtf8(url); + public readonly string PostData => Mershul.PtrToStringUtf8(post_data); } [StructLayout(LayoutKind.Sequential)] @@ -115,7 +115,7 @@ public struct rc_api_response_t public IntPtr error_message; public rc_api_buffer_t buffer; - public string ErrorMessage => Mershul.PtrToStringUtf8(error_message); + public readonly string ErrorMessage => Mershul.PtrToStringUtf8(error_message); } [StructLayout(LayoutKind.Sequential)] @@ -136,9 +136,9 @@ public struct rc_api_login_response_t public IntPtr display_name; public rc_api_response_t response; - public string Username => Mershul.PtrToStringUtf8(username); - public string ApiToken => Mershul.PtrToStringUtf8(api_token); - public string DisplayName => Mershul.PtrToStringUtf8(display_name); + public readonly string Username => Mershul.PtrToStringUtf8(username); + public readonly string ApiToken => Mershul.PtrToStringUtf8(api_token); + public readonly string DisplayName => Mershul.PtrToStringUtf8(display_name); } [StructLayout(LayoutKind.Sequential)] @@ -225,11 +225,11 @@ public struct rc_api_achievement_definition_t public long created; // time_t? public long updated; // time_t? - public string Title => Mershul.PtrToStringUtf8(title); - public string Description => Mershul.PtrToStringUtf8(description); - public string Definition => Mershul.PtrToStringUtf8(definition); - public string Author => Mershul.PtrToStringUtf8(author); - public string BadgeName => Mershul.PtrToStringUtf8(badge_name); + public readonly string Title => Mershul.PtrToStringUtf8(title); + public readonly string Description => Mershul.PtrToStringUtf8(description); + public readonly string Definition => Mershul.PtrToStringUtf8(definition); + public readonly string Author => Mershul.PtrToStringUtf8(author); + public readonly string BadgeName => Mershul.PtrToStringUtf8(badge_name); } [StructLayout(LayoutKind.Sequential)] @@ -243,9 +243,9 @@ public struct rc_api_leaderboard_definition_t public int lower_is_better; public int hidden; - public string Title => Mershul.PtrToStringUtf8(title); - public string Description => Mershul.PtrToStringUtf8(description); - public string Definition => Mershul.PtrToStringUtf8(definition); + public readonly string Title => Mershul.PtrToStringUtf8(title); + public readonly string Description => Mershul.PtrToStringUtf8(description); + public readonly string Definition => Mershul.PtrToStringUtf8(definition); } [StructLayout(LayoutKind.Sequential)] @@ -262,9 +262,9 @@ public struct rc_api_fetch_game_data_response_t public int num_leaderboards; public rc_api_response_t response; - public string Title => Mershul.PtrToStringUtf8(title); - public string ImageName => Mershul.PtrToStringUtf8(image_name); - public string RichPresenceScript => Mershul.PtrToStringUtf8(rich_presence_script); + public readonly string Title => Mershul.PtrToStringUtf8(title); + public readonly string ImageName => Mershul.PtrToStringUtf8(image_name); + public readonly string RichPresenceScript => Mershul.PtrToStringUtf8(rich_presence_script); } [StructLayout(LayoutKind.Sequential)] @@ -443,9 +443,9 @@ public struct rc_api_fetch_leaderboard_info_response_t public int num_entries; public rc_api_response_t response; - public string Title => Mershul.PtrToStringUtf8(title); - public string Description => Mershul.PtrToStringUtf8(description); - public string Definition => Mershul.PtrToStringUtf8(definition); + public readonly string Title => Mershul.PtrToStringUtf8(title); + public readonly string Description => Mershul.PtrToStringUtf8(description); + public readonly string Definition => Mershul.PtrToStringUtf8(definition); } [StructLayout(LayoutKind.Sequential)] diff --git a/src/BizHawk.Client.EmuHawk/RetroAchievements/RAIntegration.Update.cs b/src/BizHawk.Client.EmuHawk/RetroAchievements/RAIntegration.Update.cs index 79fc6dfd3be..4c1e7045bde 100644 --- a/src/BizHawk.Client.EmuHawk/RetroAchievements/RAIntegration.Update.cs +++ b/src/BizHawk.Client.EmuHawk/RetroAchievements/RAIntegration.Update.cs @@ -53,7 +53,7 @@ private static bool DownloadDll(string url) url = url.Replace("http:", "https:"); } - using var downloadForm = new RAIntegrationDownloaderForm(url); + using RAIntegrationDownloaderForm downloadForm = new(url); downloadForm.ShowDialog(); return downloadForm.DownloadSucceeded(); } @@ -62,12 +62,12 @@ public static bool CheckUpdateRA(IMainFormForRetroAchievements mainForm) { try { - var http = new HttpCommunication(null, "https://retroachievements.org/dorequest.php?r=latestintegration", null); + HttpCommunication http = new(null, "https://retroachievements.org/dorequest.php?r=latestintegration", null); var info = JsonConvert.DeserializeObject>(http.ExecGet()); - if (info.TryGetValue("Success", out var success) && (bool)success) + if (info.TryGetValue("Success", out object success) && (bool)success) { - var lastestVer = new Version((string)info["LatestVersion"]); - var minVer = new Version((string)info["MinimumVersion"]); + Version lastestVer = new((string)info["LatestVersion"]); + Version minVer = new((string)info["MinimumVersion"]); if (_version < minVer) { @@ -79,7 +79,7 @@ public static bool CheckUpdateRA(IMainFormForRetroAchievements mainForm) icon: EMsgBoxIcon.Question, useOKCancel: false)) return false; DetachDll(); - var ret = DownloadDll((string)info["LatestVersionUrlX64"]); + bool ret = DownloadDll((string)info["LatestVersionUrlX64"]); AttachDll(); return ret; } diff --git a/src/BizHawk.Client.EmuHawk/RetroAchievements/RAIntegration.cs b/src/BizHawk.Client.EmuHawk/RetroAchievements/RAIntegration.cs index ffcc0e6f33b..7c7c7b10311 100644 --- a/src/BizHawk.Client.EmuHawk/RetroAchievements/RAIntegration.cs +++ b/src/BizHawk.Client.EmuHawk/RetroAchievements/RAIntegration.cs @@ -55,11 +55,11 @@ static RAIntegration() private void RebuildMenu() { - var numItems = RA.GetPopupMenuItems(_menuItems); + int numItems = RA.GetPopupMenuItems(_menuItems); var tsmiddi = _raDropDownItems; tsmiddi.Clear(); { - var tsi = new ToolStripMenuItem("Shutdown RetroAchievements"); + ToolStripMenuItem tsi = new("Shutdown RetroAchievements"); tsi.Click += (_, _) => _shutdownRACallback(); tsmiddi.Add(tsi); @@ -71,14 +71,14 @@ private void RebuildMenu() tsi.CheckedChanged += (_, _) => _getConfig().RAAutostart ^= true; tsmiddi.Add(tsi); - var tss = new ToolStripSeparator(); + ToolStripSeparator tss = new(); tsmiddi.Add(tss); } for (int i = 0; i < numItems; i++) { if (_menuItems[i].Label != IntPtr.Zero) { - var tsi = new ToolStripMenuItem(Marshal.PtrToStringUni(_menuItems[i].Label)) + ToolStripMenuItem tsi = new(Marshal.PtrToStringUni(_menuItems[i].Label)) { Checked = _menuItems[i].Checked != 0, }; @@ -92,7 +92,7 @@ private void RebuildMenu() } else { - var tss = new ToolStripSeparator(); + ToolStripSeparator tss = new(); tsmiddi.Add(tss); } } @@ -127,7 +127,7 @@ public RAIntegration(IMainFormForRetroAchievements mainForm, InputManager inputM _rebuildMenu = RebuildMenu; _estimateTitle = buffer => { - var name = Encoding.UTF8.GetBytes(Game?.Name ?? "No Game Info Available"); + byte[] name = Encoding.UTF8.GetBytes(Game?.Name ?? "No Game Info Available"); Marshal.Copy(name, 0, buffer, Math.Min(name.Length, 256)); }; _resetEmulator = () => _mainForm.RebootCore(); @@ -202,7 +202,7 @@ public override void Restart() { _memFunctions = CreateMemoryBanks(consoleId, Domains, Emu.CanDebug() ? Emu.AsDebuggable() : null); - for (var i = 0; i < _memFunctions.Count; i++) + for (int i = 0; i < _memFunctions.Count; i++) { _memFunctions[i].MemGuard = _memGuard; RA.InstallMemoryBank(i, _memFunctions[i].ReadFunc, _memFunctions[i].WriteFunc, _memFunctions[i].BankSize); @@ -251,7 +251,7 @@ public override void Update() if (!OverlayActive) return; - var ci = new RAInterface.ControllerInput + RAInterface.ControllerInput ci = new() { UpPressed = _inputManager.ClientControls["RA Up"], DownPressed = _inputManager.ClientControls["RA Down"], diff --git a/src/BizHawk.Client.EmuHawk/RetroAchievements/RAIntegrationDownloaderForm.cs b/src/BizHawk.Client.EmuHawk/RetroAchievements/RAIntegrationDownloaderForm.cs index cbe3e517b87..ca577cd5995 100644 --- a/src/BizHawk.Client.EmuHawk/RetroAchievements/RAIntegrationDownloaderForm.cs +++ b/src/BizHawk.Client.EmuHawk/RetroAchievements/RAIntegrationDownloaderForm.cs @@ -44,21 +44,18 @@ public bool DownloadSucceeded() return _succeeded; } - private void ThreadProc() - { - Download(); - } + private void ThreadProc() => Download(); private void Download() { //the temp file is owned by this thread - var fn = TempFileManager.GetTempFilename("RAIntegration_download", ".dll", false); + string fn = TempFileManager.GetTempFilename("RAIntegration_download", ".dll", false); try { - using (var evt = new ManualResetEvent(false)) + using (ManualResetEvent evt = new(false)) { - using var client = new System.Net.WebClient(); + using System.Net.WebClient client = new(); System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; client.DownloadFileAsync(new Uri(_url), fn); client.DownloadProgressChanged += (object sender, System.Net.DownloadProgressChangedEventArgs e) => @@ -93,9 +90,9 @@ private void Download() return; //try acquiring file - using (var dll = new HawkFile(fn)) + using (HawkFile dll = new(fn)) { - var data = dll!.ReadAllBytes(); + byte[] data = dll!.ReadAllBytes(); //last chance. exiting, don't dump the new RAIntegration file if (_exiting) @@ -131,17 +128,12 @@ private void btnDownload_Click(object sender, EventArgs e) _thread.Start(); } - private void btnCancel_Click(object sender, EventArgs e) - { - Close(); - } + private void btnCancel_Click(object sender, EventArgs e) => Close(); - protected override void OnClosed(EventArgs e) - { + protected override void OnClosed(EventArgs e) => //inform the worker thread that it needs to try terminating without doing anything else //(it will linger on in background for a bit til it can service this) _exiting = true; - } private void timer1_Tick(object sender, EventArgs e) { @@ -158,10 +150,7 @@ private void timer1_Tick(object sender, EventArgs e) progressBar1.Value = _pct; } - private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) - { - System.Diagnostics.Process.Start(_url); - } + private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) => System.Diagnostics.Process.Start(_url); } } diff --git a/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.Achievements.cs b/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.Achievements.cs index 0539e2fdc74..29884b04862 100644 --- a/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.Achievements.cs +++ b/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.Achievements.cs @@ -131,7 +131,7 @@ public Cheevo(in Cheevo cheevo, Func allowUnofficialCheevos) private string GetCheevoProgress(int id) { - var len = _lib.rc_runtime_format_achievement_measured(_runtime, id, _cheevoFormatBuffer, _cheevoFormatBuffer.Length); + int len = _lib.rc_runtime_format_achievement_measured(_runtime, id, _cheevoFormatBuffer, _cheevoFormatBuffer.Length); return Encoding.ASCII.GetString(_cheevoFormatBuffer, 0, len); } diff --git a/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.Debug.cs b/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.Debug.cs index fb3260419d2..4542c456f5a 100644 --- a/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.Debug.cs +++ b/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.Debug.cs @@ -28,7 +28,7 @@ private static void VerboseMessageCallback(string message) private static IntPtr OpenFileCallback(string utf8_path) { - var file = new HawkFile(utf8_path); + HawkFile file = new(utf8_path); // this probably shouldn't ever happen if (!file.Exists || !file.IsBound || !file.GetStream().CanSeek || !file.GetStream().CanRead) @@ -37,37 +37,37 @@ private static IntPtr OpenFileCallback(string utf8_path) return IntPtr.Zero; } - var handle = GCHandle.Alloc(file, GCHandleType.Normal); + GCHandle handle = GCHandle.Alloc(file, GCHandleType.Normal); return GCHandle.ToIntPtr(handle); } private static void SeekFileCallback(IntPtr file_handle, long offset, SeekOrigin origin) { - var handle = GCHandle.FromIntPtr(file_handle); - var file = (HawkFile)handle.Target; + GCHandle handle = GCHandle.FromIntPtr(file_handle); + HawkFile file = (HawkFile)handle.Target; file.GetStream().Seek(offset, origin); } private static long TellFileCallback(IntPtr file_handle) { - var handle = GCHandle.FromIntPtr(file_handle); - var file = (HawkFile)handle.Target; + GCHandle handle = GCHandle.FromIntPtr(file_handle); + HawkFile file = (HawkFile)handle.Target; return file.GetStream().Position; } private static UIntPtr ReadFileCallback(IntPtr file_handle, IntPtr buffer, UIntPtr requested_bytes) { - var handle = GCHandle.FromIntPtr(file_handle); - var file = (HawkFile)handle.Target; + GCHandle handle = GCHandle.FromIntPtr(file_handle); + HawkFile file = (HawkFile)handle.Target; // this is poop without spans const int TMP_BUFFER_LEN = 65536; - var tmp = new byte[TMP_BUFFER_LEN]; + byte[] tmp = new byte[TMP_BUFFER_LEN]; var stream = file.GetStream(); - var remainingBytes = (ulong)requested_bytes; + ulong remainingBytes = (ulong)requested_bytes; while (remainingBytes != 0) { - var numRead = stream.Read(tmp, 0, (int)Math.Min(remainingBytes, TMP_BUFFER_LEN)); + int numRead = stream.Read(tmp, 0, (int)Math.Min(remainingBytes, TMP_BUFFER_LEN)); if (numRead == 0) // reached end of stream { break; @@ -83,8 +83,8 @@ private static UIntPtr ReadFileCallback(IntPtr file_handle, IntPtr buffer, UIntP private static void CloseFileCallback(IntPtr file_handle) { - var handle = GCHandle.FromIntPtr(file_handle); - var file = (HawkFile)handle.Target; + GCHandle handle = GCHandle.FromIntPtr(file_handle); + HawkFile file = (HawkFile)handle.Target; file.Dispose(); handle.Free(); } @@ -119,7 +119,7 @@ public RCTrack(string path, int tracknum) switch (tracknum) // implicitly, this checks the first session only, except for RC_HASH_CDTRACK_FIRST_OF_SECOND_SESSION { case RC_HASH_CDTRACK_FIRST_DATA: - for (var i = 1; i <= _disc.Session1.InformationTrackCount; i++) + for (int i = 1; i <= _disc.Session1.InformationTrackCount; i++) { var track = _disc.Session1.Tracks[i]; if (track.IsData) @@ -130,7 +130,7 @@ public RCTrack(string path, int tracknum) } break; case RC_HASH_CDTRACK_LAST: - for (var i = _disc.Session1.InformationTrackCount; i >= 1; i--) + for (int i = _disc.Session1.InformationTrackCount; i >= 1; i--) { var track = _disc.Session1.Tracks[i]; if (track.IsData) @@ -141,7 +141,7 @@ public RCTrack(string path, int tracknum) } break; case RC_HASH_CDTRACK_LARGEST or 0: // 0 is same meaning - for (var i = 1; i <= _disc.Session1.InformationTrackCount; i++) + for (int i = 1; i <= _disc.Session1.InformationTrackCount; i++) { var track = _disc.Session1.Tracks[i]; if (track.IsData) @@ -152,8 +152,8 @@ public RCTrack(string path, int tracknum) } else { - var curTrackLen = _track.NextTrack.LBA - _track.LBA; - var nextTrackLen = track.NextTrack.LBA - track.LBA; + int curTrackLen = _track.NextTrack.LBA - _track.LBA; + int nextTrackLen = track.NextTrack.LBA - track.LBA; if (nextTrackLen > curTrackLen) { _track = track; @@ -196,50 +196,47 @@ public int ReadSector(int lba, IntPtr buffer, ulong requestedBytes) return 0; } - var numRead = _dsr.ReadLBA_2448(lba, _buf2448, 0); - var numCopied = (int)Math.Min((ulong)numRead, requestedBytes); + int numRead = _dsr.ReadLBA_2448(lba, _buf2448, 0); + int numCopied = (int)Math.Min((ulong)numRead, requestedBytes); Marshal.Copy(_buf2448, 0, buffer, numCopied); return numCopied; } - public void Dispose() - { - _disc.Dispose(); - } + public void Dispose() => _disc.Dispose(); } private static IntPtr OpenTrackCallback(string path, int tracknum) { - var track = new RCTrack(path, tracknum); + RCTrack track = new(path, tracknum); if (!track.IsAvailable) { return IntPtr.Zero; } - var handle = GCHandle.Alloc(track, GCHandleType.Normal); + GCHandle handle = GCHandle.Alloc(track, GCHandleType.Normal); return GCHandle.ToIntPtr(handle); } private static UIntPtr ReadSectorCallback(IntPtr track_handle, uint sector, IntPtr buffer, UIntPtr requested_bytes) { - var handle = GCHandle.FromIntPtr(track_handle); - var track = (RCTrack)handle.Target; + GCHandle handle = GCHandle.FromIntPtr(track_handle); + RCTrack track = (RCTrack)handle.Target; return new((uint)track.ReadSector((int)sector, buffer, (ulong)requested_bytes)); } private static void CloseTrackCallback(IntPtr track_handle) { - var handle = GCHandle.FromIntPtr(track_handle); - var track = (RCTrack)handle.Target; + GCHandle handle = GCHandle.FromIntPtr(track_handle); + RCTrack track = (RCTrack)handle.Target; track.Dispose(); handle.Free(); } private static uint FirstTrackSectorCallback(IntPtr track_handle) { - var handle = GCHandle.FromIntPtr(track_handle); - var track = (RCTrack)handle.Target; + GCHandle handle = GCHandle.FromIntPtr(track_handle); + RCTrack track = (RCTrack)handle.Target; return (uint)track.LBA; } @@ -247,7 +244,7 @@ private static uint FirstTrackSectorCallback(IntPtr track_handle) // outputs results in the console public static void DebugHash() { - using var ofd = new OpenFileDialog + using OpenFileDialog ofd = new() { CheckFileExists = true, CheckPathExists = true, @@ -266,15 +263,15 @@ public static void DebugHash() return; } - var ext = Path.GetExtension(Path.GetExtension(path.Replace("|", "")).ToLowerInvariant()); + string ext = Path.GetExtension(Path.GetExtension(path.Replace("|", "")).ToLowerInvariant()); switch (ext) { case ".m3u": { - using var file = new HawkFile(path); - using var sr = new StreamReader(file.GetStream()); - var m3u = M3U_File.Read(sr); + using HawkFile file = new(path); + using StreamReader sr = new(file.GetStream()); + M3U_File m3u = M3U_File.Read(sr); m3u.Rebase(Path.GetDirectoryName(path)); foreach (var entry in m3u.Entries) { @@ -285,7 +282,7 @@ public static void DebugHash() } case ".xml": { - var xml = XmlGame.Create(new(path)); + XmlGame xml = XmlGame.Create(new(path)); foreach (var kvp in xml.Assets) { InternalDebugHash(kvp.Key); @@ -315,10 +312,10 @@ static string ResolvePath(string path) return Path.GetFileName(path).ToLowerInvariant(); } - using var file = new HawkFile(path); + using HawkFile file = new(path); if (file.IsArchive && !file.IsBound) { - using var ac = new ArchiveChooser(file); + using ArchiveChooser ac = new(file); if (ac.ShowDialog().IsOk()) { file.BindArchiveMember(ac.SelectedMemberIndex); @@ -374,8 +371,8 @@ static ConsoleID IdentifyConsole(string path) return ConsoleID.Arcade; } - using var file = new HawkFile(path); - var rom = new RomGame(file); + using HawkFile file = new(path); + RomGame rom = new(file); return rom.GameInfo.System switch { VSystemID.Raw.A26 => ConsoleID.Atari2600, @@ -441,8 +438,8 @@ VSystemID.Raw.GEN when rom.GameInfo.GetBool("32X", false) => ConsoleID.Sega32X, path = ResolvePath(path); var consoleID = IdentifyConsole(path); - var hash = new byte[33]; - var success = _lib.rc_hash_generate_from_file(hash, consoleID, path); + byte[] hash = new byte[33]; + bool success = _lib.rc_hash_generate_from_file(hash, consoleID, path); Console.WriteLine(path); Console.WriteLine(success ? $"Generated RC Hash: {Encoding.ASCII.GetString(hash, 0, 32)}" diff --git a/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.GameInfo.cs b/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.GameInfo.cs index 07f3fb3b526..0fb04bb7413 100644 --- a/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.GameInfo.cs +++ b/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.GameInfo.cs @@ -33,8 +33,8 @@ protected override void ResponseCallback(byte[] serv_resp) { unsafe { - var unlocks = (int*)resp.achievement_ids; - for (var i = 0; i < resp.num_achievement_ids; i++) + int* unlocks = (int*)resp.achievement_ids; + for (int i = 0; i < resp.num_achievement_ids; i++) { if (_cheevos.TryGetValue(unlocks![i], out var cheevo)) { @@ -114,7 +114,7 @@ protected override void ResponseCallback(byte[] serv_resp) { try { - var image = new Bitmap(new MemoryStream(serv_resp)); + Bitmap image = new(new MemoryStream(serv_resp)); Image = image; } catch @@ -162,14 +162,11 @@ public class GameData public Cheevo GetCheevoById(int i) => _cheevos[i]; public LBoard GetLboardById(int i) => _lboards[i]; - public UserUnlocksRequest InitUnlocks(string username, string api_token, bool hardcore) - { - return new(username, api_token, GameID, hardcore, _cheevos); - } + public UserUnlocksRequest InitUnlocks(string username, string api_token, bool hardcore) => new(username, api_token, GameID, hardcore, _cheevos); public IEnumerable LoadImages() { - var requests = new List(1 + (_cheevos?.Count ?? 0) * 2); + List requests = new(1 + (_cheevos?.Count ?? 0) * 2); _gameBadgeImageRequest = new(ImageName, LibRCheevos.rc_api_image_type_t.RC_IMAGE_TYPE_GAME); requests.Add(_gameBadgeImageRequest); @@ -195,18 +192,18 @@ public unsafe GameData(in LibRCheevos.rc_api_fetch_game_data_response_t resp, Fu ImageName = resp.ImageName; RichPresenseScript = resp.RichPresenceScript; - var cheevos = new Dictionary(); - var cptr = (LibRCheevos.rc_api_achievement_definition_t*)resp.achievements; - for (var i = 0; i < resp.num_achievements; i++) + Dictionary cheevos = new(); + LibRCheevos.rc_api_achievement_definition_t* cptr = (LibRCheevos.rc_api_achievement_definition_t*)resp.achievements; + for (int i = 0; i < resp.num_achievements; i++) { cheevos.Add(cptr![i].id, new(in cptr[i], allowUnofficialCheevos)); } _cheevos = cheevos; - var lboards = new Dictionary(); - var lptr = (LibRCheevos.rc_api_leaderboard_definition_t*)resp.leaderboards; - for (var i = 0; i < resp.num_leaderboards; i++) + Dictionary lboards = new(); + LibRCheevos.rc_api_leaderboard_definition_t* lptr = (LibRCheevos.rc_api_leaderboard_definition_t*)resp.leaderboards; + for (int i = 0; i < resp.num_leaderboards; i++) { lboards.Add(lptr![i].id, new(in lptr[i])); } @@ -270,7 +267,7 @@ public ResolveHashRequest(string hash) private int SendHash(string hash) { - var resolveHashRequest = new ResolveHashRequest(hash); + ResolveHashRequest resolveHashRequest = new(hash); PushRequest(resolveHashRequest); resolveHashRequest.Wait(); // currently, this is done synchronously return resolveHashRequest.GameID; @@ -284,7 +281,7 @@ protected override int IdentifyHash(string hash) protected override int IdentifyRom(byte[] rom) { - var hash = new byte[33]; + byte[] hash = new byte[33]; if (_lib.rc_hash_generate_from_buffer(hash, _consoleId, rom, rom.Length)) { return IdentifyHash(Encoding.ASCII.GetString(hash, 0, 32)); @@ -317,7 +314,7 @@ private void InitGameData() private GameData GetGameData(int id) { - var gameDataRequest = new GameDataRequest(Username, ApiToken, id, () => AllowUnofficialCheevos); + GameDataRequest gameDataRequest = new(Username, ApiToken, id, () => AllowUnofficialCheevos); PushRequest(gameDataRequest); gameDataRequest.Wait(); return gameDataRequest.GameData; diff --git a/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.Http.cs b/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.Http.cs index d37b4415a1c..0c9953385bd 100644 --- a/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.Http.cs +++ b/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.Http.cs @@ -114,7 +114,7 @@ protected void InternalDoRequest(LibRCheevos.rc_error_t apiParamsResult, ref Lib apiTask.ContinueWith(async t => { - var result = await t; + byte[] result = await t; if (result is null) // likely a timeout { ShouldRetry = true; @@ -196,7 +196,7 @@ private void HttpRequestThreadProc() _activeHttpRequests.RemoveAll(activeRequest => { - var shouldRemove = activeRequest.IsCompleted && !activeRequest.ShouldRetry; + bool shouldRemove = activeRequest.IsCompleted && !activeRequest.ShouldRetry; if (shouldRemove) { activeRequest.Dispose(); @@ -247,7 +247,7 @@ private static async Task HttpPost(string url, string post) { try { - using var content = new StringContent(post, Encoding.UTF8, "application/x-www-form-urlencoded"); + using StringContent content = new(post, Encoding.UTF8, "application/x-www-form-urlencoded"); using var response = await _http.PostAsync(url, content).ConfigureAwait(false); return response.IsSuccessStatusCode ? await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false) diff --git a/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.Leaderboards.cs b/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.Leaderboards.cs index 9cfcd248890..84ae69c1f04 100644 --- a/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.Leaderboards.cs +++ b/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.Leaderboards.cs @@ -54,7 +54,7 @@ public class LBoard public void SetScore(int val) { - var len = _lib.rc_runtime_format_lboard_value(_scoreFormatBuffer, _scoreFormatBuffer.Length, val, Format); + int len = _lib.rc_runtime_format_lboard_value(_scoreFormatBuffer, _scoreFormatBuffer.Length, val, Format); Score = Encoding.ASCII.GetString(_scoreFormatBuffer, 0, len); } diff --git a/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.Login.cs b/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.Login.cs index 345f02bd181..8415a1e769d 100644 --- a/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.Login.cs +++ b/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.Login.cs @@ -45,7 +45,7 @@ protected override void ResponseCallback(byte[] serv_resp) private bool DoLogin(string username, string apiToken = null, string password = null) { - var loginRequest = new LoginRequest(username, apiToken, password); + LoginRequest loginRequest = new(username, apiToken, password); PushRequest(loginRequest); loginRequest.Wait(); @@ -73,7 +73,7 @@ private void Login() } } - using var loginForm = new RCheevosLoginForm((username, password) => DoLogin(username, password: password)); + using RCheevosLoginForm loginForm = new((username, password) => DoLogin(username, password: password)); loginForm.ShowDialog(); config.RAUsername = Username; diff --git a/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.Ping.cs b/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.Ping.cs index e0b373bfa9f..732f56393fa 100644 --- a/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.Ping.cs +++ b/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.Ping.cs @@ -34,10 +34,7 @@ protected override void ResponseCallback(byte[] serv_resp) } } - private void StartGameSession() - { - PushRequest(new StartGameSessionRequest(Username, ApiToken, _gameData.GameID)); - } + private void StartGameSession() => PushRequest(new StartGameSessionRequest(Username, ApiToken, _gameData.GameID)); private sealed class PingRequest : RCheevoHttpRequest { @@ -65,10 +62,7 @@ protected override void ResponseCallback(byte[] serv_resp) } } - private void SendPing() - { - PushRequest(new PingRequest(Username, ApiToken, _gameData.GameID, CurrentRichPresence)); - } + private void SendPing() => PushRequest(new PingRequest(Username, ApiToken, _gameData.GameID, CurrentRichPresence)); private readonly byte[] _richPresenceBuffer = new byte[1024]; @@ -79,7 +73,7 @@ private void CheckPing() { if (RichPresenceActive) { - var len = _lib.rc_runtime_get_richpresence(_runtime, _richPresenceBuffer, _richPresenceBuffer.Length, _peekcb, IntPtr.Zero, IntPtr.Zero); + int len = _lib.rc_runtime_get_richpresence(_runtime, _richPresenceBuffer, _richPresenceBuffer.Length, _peekcb, IntPtr.Zero, IntPtr.Zero); CurrentRichPresence = Encoding.UTF8.GetString(_richPresenceBuffer, 0, len); } else diff --git a/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.cs b/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.cs index 4743b427056..1697bc18c07 100644 --- a/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.cs +++ b/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevos.cs @@ -19,7 +19,7 @@ public partial class RCheevos : RetroAchievements static RCheevos() { - var resolver = new DynamicLibraryImportResolver( + DynamicLibraryImportResolver resolver = new( OSTailoredCode.IsUnixHost ? "librcheevos.so" : "librcheevos.dll", hasLimitedLifetime: false); _lib = BizInvoker.GetInvoker(resolver, CallingConventionAdapters.Native); @@ -58,11 +58,11 @@ private void BuildMenu(ToolStripItemCollection raDropDownItems) { raDropDownItems.Clear(); - var shutDownRAItem = new ToolStripMenuItem("Shutdown RetroAchievements"); + ToolStripMenuItem shutDownRAItem = new("Shutdown RetroAchievements"); shutDownRAItem.Click += (_, _) => _shutdownRACallback(); raDropDownItems.Add(shutDownRAItem); - var autoStartRAItem = new ToolStripMenuItem("Autostart RetroAchievements") + ToolStripMenuItem autoStartRAItem = new("Autostart RetroAchievements") { Checked = _getConfig().RAAutostart, CheckOnClick = true, @@ -70,7 +70,7 @@ private void BuildMenu(ToolStripItemCollection raDropDownItems) autoStartRAItem.CheckedChanged += (_, _) => _getConfig().RAAutostart ^= true; raDropDownItems.Add(autoStartRAItem); - var loginItem = new ToolStripMenuItem("Login") + ToolStripMenuItem loginItem = new("Login") { Visible = !LoggedIn }; @@ -83,7 +83,7 @@ private void BuildMenu(ToolStripItemCollection raDropDownItems) }; raDropDownItems.Add(loginItem); - var logoutItem = new ToolStripMenuItem("Logout") + ToolStripMenuItem logoutItem = new("Logout") { Visible = LoggedIn }; @@ -97,10 +97,10 @@ private void BuildMenu(ToolStripItemCollection raDropDownItems) LoginStatusChanged += () => loginItem.Visible = !LoggedIn; LoginStatusChanged += () => logoutItem.Visible = LoggedIn; - var tss = new ToolStripSeparator(); + ToolStripSeparator tss = new(); raDropDownItems.Add(tss); - var enableCheevosItem = new ToolStripMenuItem("Enable Achievements") + ToolStripMenuItem enableCheevosItem = new("Enable Achievements") { Checked = CheevosActive, CheckOnClick = true @@ -108,7 +108,7 @@ private void BuildMenu(ToolStripItemCollection raDropDownItems) enableCheevosItem.CheckedChanged += (_, _) => CheevosActive ^= true; raDropDownItems.Add(enableCheevosItem); - var enableLboardsItem = new ToolStripMenuItem("Enable Leaderboards") + ToolStripMenuItem enableLboardsItem = new("Enable Leaderboards") { Checked = LBoardsActive, CheckOnClick = true, @@ -117,7 +117,7 @@ private void BuildMenu(ToolStripItemCollection raDropDownItems) enableLboardsItem.CheckedChanged += (_, _) => LBoardsActive ^= true; raDropDownItems.Add(enableLboardsItem); - var enableRichPresenceItem = new ToolStripMenuItem("Enable Rich Presence") + ToolStripMenuItem enableRichPresenceItem = new("Enable Rich Presence") { Checked = RichPresenceActive, CheckOnClick = true @@ -125,7 +125,7 @@ private void BuildMenu(ToolStripItemCollection raDropDownItems) enableRichPresenceItem.CheckedChanged += (_, _) => RichPresenceActive ^= true; raDropDownItems.Add(enableRichPresenceItem); - var enableHardcoreItem = new ToolStripMenuItem("Enable Hardcore Mode") + ToolStripMenuItem enableHardcoreItem = new("Enable Hardcore Mode") { Checked = HardcoreMode, CheckOnClick = true @@ -149,7 +149,7 @@ private void BuildMenu(ToolStripItemCollection raDropDownItems) _hardcoreModeMenuItem = enableHardcoreItem; - var enableSoundEffectsItem = new ToolStripMenuItem("Enable Sound Effects") + ToolStripMenuItem enableSoundEffectsItem = new("Enable Sound Effects") { Checked = EnableSoundEffects, CheckOnClick = true @@ -157,7 +157,7 @@ private void BuildMenu(ToolStripItemCollection raDropDownItems) enableSoundEffectsItem.CheckedChanged += (_, _) => EnableSoundEffects ^= true; raDropDownItems.Add(enableSoundEffectsItem); - var enableUnofficialCheevosItem = new ToolStripMenuItem("Test Unofficial Achievements") + ToolStripMenuItem enableUnofficialCheevosItem = new("Test Unofficial Achievements") { Checked = AllowUnofficialCheevos, CheckOnClick = true @@ -168,7 +168,7 @@ private void BuildMenu(ToolStripItemCollection raDropDownItems) tss = new ToolStripSeparator(); raDropDownItems.Add(tss); - var viewGameInfoItem = new ToolStripMenuItem("View Game Info"); + ToolStripMenuItem viewGameInfoItem = new("View Game Info"); viewGameInfoItem.Click += (_, _) => { _gameInfoForm.OnFrameAdvance(_gameData.GameBadge, _gameData.TotalCheevoPoints(HardcoreMode), @@ -179,7 +179,7 @@ private void BuildMenu(ToolStripItemCollection raDropDownItems) }; raDropDownItems.Add(viewGameInfoItem); - var viewCheevoListItem = new ToolStripMenuItem("View Achievement List"); + ToolStripMenuItem viewCheevoListItem = new("View Achievement List"); viewCheevoListItem.Click += (_, _) => { _cheevoListForm.OnFrameAdvance(HardcoreMode, true); @@ -263,7 +263,7 @@ public override void OnSaveState(string path) var size = _lib.rc_runtime_progress_size(_runtime, IntPtr.Zero); if (size > 0) { - var buffer = new byte[(int)size]; + byte[] buffer = new byte[(int)size]; _lib.rc_runtime_serialize_progress(buffer, _runtime, IntPtr.Zero); using var file = File.OpenWrite(path + ".rap"); file.Write(buffer, 0, buffer.Length); @@ -289,7 +289,7 @@ public override void OnLoadState(string path) if (!File.Exists(path + ".rap")) return; using var file = File.OpenRead(path + ".rap"); - var buffer = file.ReadAllBytes(); + byte[] buffer = file.ReadAllBytes(); _lib.rc_runtime_deserialize_progress(_runtime, buffer, IntPtr.Zero); } @@ -356,12 +356,12 @@ public override void Restart() { _memFunctions = CreateMemoryBanks(_consoleId, Domains, Emu.CanDebug() ? Emu.AsDebuggable() : null); - var addr = 0; + int addr = 0; foreach (var memFunctions in _memFunctions) { if (memFunctions.ReadFunc is not null) { - for (var i = 0; i < memFunctions.BankSize; i++) + for (int i = 0; i < memFunctions.BankSize; i++) { _readMap.Add(addr + i, (memFunctions.ReadFunc, addr)); } @@ -381,7 +381,7 @@ public override void Restart() AllGamesVerified = !ids.Contains(0); - var gameId = ids.Count > 0 ? ids[0] : 0; + int gameId = ids.Count > 0 ? ids[0] : 0; _gameData = new(); if (gameId != 0) @@ -415,6 +415,7 @@ public override void Restart() // validate addresses now that we have cheevos init // ReSharper disable once ConvertToLocalFunction LibRCheevos.rc_runtime_validate_address_t peekcb = address => _readMap.ContainsKey(address); + _lib.rc_runtime_validate_addresses(_runtime, _eventcb, peekcb); _gameInfoForm.Restart(_gameData.Title, _gameData.TotalCheevoPoints(HardcoreMode), CurrentRichPresence ?? "N/A"); @@ -449,7 +450,7 @@ public override void Update() private unsafe void EventHandlerCallback(IntPtr runtime_event) { - var evt = (LibRCheevos.rc_runtime_event_t*)runtime_event; + LibRCheevos.rc_runtime_event_t* evt = (LibRCheevos.rc_runtime_event_t*)runtime_event; switch (evt->type) { case LibRCheevos.rc_runtime_event_type_t.RC_RUNTIME_EVENT_ACHIEVEMENT_TRIGGERED: @@ -462,7 +463,7 @@ private unsafe void EventHandlerCallback(IntPtr runtime_event) _lib.rc_runtime_deactivate_achievement(_runtime, evt->id); cheevo.SetUnlocked(HardcoreMode, true); - var prefix = HardcoreMode ? "[HARDCORE] " : ""; + string prefix = HardcoreMode ? "[HARDCORE] " : ""; _mainForm.AddOnScreenMessage($"{prefix}Achievement Unlocked!"); _mainForm.AddOnScreenMessage(cheevo.Description); if (EnableSoundEffects) _unlockSound.PlayNoExceptions(); @@ -483,7 +484,7 @@ private unsafe void EventHandlerCallback(IntPtr runtime_event) if (cheevo.IsEnabled) { cheevo.IsPrimed = true; - var prefix = HardcoreMode ? "[HARDCORE] " : ""; + string prefix = HardcoreMode ? "[HARDCORE] " : ""; _mainForm.AddOnScreenMessage($"{prefix}Achievement Primed!"); _mainForm.AddOnScreenMessage(cheevo.Description); if (EnableSoundEffects) _infoSound.PlayNoExceptions(); @@ -589,7 +590,7 @@ private unsafe void EventHandlerCallback(IntPtr runtime_event) if (cheevo.IsEnabled) { cheevo.IsPrimed = false; - var prefix = HardcoreMode ? "[HARDCORE] " : ""; + string prefix = HardcoreMode ? "[HARDCORE] " : ""; _mainForm.AddOnScreenMessage($"{prefix}Achievement Unprimed!"); _mainForm.AddOnScreenMessage(cheevo.Description); if (EnableSoundEffects) _infoSound.PlayNoExceptions(); diff --git a/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevosAchievementForm.cs b/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevosAchievementForm.cs index db753ffbeff..f5cf87a2953 100644 --- a/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevosAchievementForm.cs +++ b/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevosAchievementForm.cs @@ -12,7 +12,7 @@ public partial class RCheevosAchievementForm : Form { public int OrderByKey() { - var ret = 0; + int ret = 0; ret += hcUnlockedCheckBox.Checked ? 3 : 0; ret += scUnlockedCheckBox.Checked ? 2 : 0; ret += primedCheckBox.Checked ? 1 : 0; @@ -44,8 +44,8 @@ public RCheevosAchievementForm(RCheevos.Cheevo cheevo, Func getChee private static Bitmap UpscaleBadge(Bitmap src) { - var ret = new Bitmap(120, 120); - using var g = Graphics.FromImage(ret); + Bitmap ret = new(120, 120); + using Graphics g = Graphics.FromImage(ret); g.InterpolationMode = InterpolationMode.NearestNeighbor; g.PixelOffsetMode = PixelOffsetMode.Half; g.DrawImage(src, 0, 0, 120, 120); diff --git a/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevosAchievementListForm.cs b/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevosAchievementListForm.cs index 0d5d9467532..c055931d39d 100644 --- a/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevosAchievementListForm.cs +++ b/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevosAchievementListForm.cs @@ -36,7 +36,7 @@ public void Restart(IEnumerable cheevos, Func getC { flowLayoutPanel1.Controls.Clear(); DisposeCheevoForms(); - var cheevoForms = new List(); + List cheevoForms = new(); foreach (var cheevo in cheevos) { cheevoForms.Add(new(cheevo, getCheevoProgress)); diff --git a/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevosLeaderboardForm.cs b/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevosLeaderboardForm.cs index ff963d6bc13..c63a7f073d1 100644 --- a/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevosLeaderboardForm.cs +++ b/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevosLeaderboardForm.cs @@ -21,10 +21,7 @@ public RCheevosLeaderboardForm(RCheevos.LBoard lboard) Show(); } - public void OnFrameAdvance() - { - scoreBox.Text = _lboard.Score; - } + public void OnFrameAdvance() => scoreBox.Text = _lboard.Score; } } diff --git a/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevosLoginForm.cs b/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevosLoginForm.cs index c9c061ca96a..b6adb5af900 100644 --- a/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevosLoginForm.cs +++ b/src/BizHawk.Client.EmuHawk/RetroAchievements/RCheevosLoginForm.cs @@ -19,7 +19,7 @@ public RCheevosLoginForm(Func loginCallback) private void btnLogin_Click(object sender, EventArgs e) { - var res = _loginCallback(txtUsername.Text, txtPassword.Text); + bool res = _loginCallback(txtUsername.Text, txtPassword.Text); if (res) { MessageBox.Show("Login successful"); @@ -31,10 +31,7 @@ private void btnLogin_Click(object sender, EventArgs e) } } - private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) - { - Process.Start("https://retroachievements.org/createaccount.php"); - } + private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) => Process.Start("https://retroachievements.org/createaccount.php"); } } diff --git a/src/BizHawk.Client.EmuHawk/RetroAchievements/RetroAchievements.ConsoleID.cs b/src/BizHawk.Client.EmuHawk/RetroAchievements/RetroAchievements.ConsoleID.cs index c7b8bf72769..3215b94b2bb 100644 --- a/src/BizHawk.Client.EmuHawk/RetroAchievements/RetroAchievements.ConsoleID.cs +++ b/src/BizHawk.Client.EmuHawk/RetroAchievements/RetroAchievements.ConsoleID.cs @@ -117,7 +117,7 @@ protected ConsoleID SystemIdToConsoleId() VSystemID.Raw.GB => ConsoleID.GB, VSystemID.Raw.GBA => ConsoleID.GBA, VSystemID.Raw.GBC => ConsoleID.GBC, // Not actually used - VSystemID.Raw.GBL when Emu is ILinkedGameBoyCommon { First: { IsCGBMode: true } } => ConsoleID.GBC, + VSystemID.Raw.GBL when Emu is ILinkedGameBoyCommon { First.IsCGBMode: true } => ConsoleID.GBC, VSystemID.Raw.GBL => ConsoleID.GB, // actually can be a mix of GB and GBC VSystemID.Raw.GEN when Emu is GPGX { IsMegaCD: true } => ConsoleID.SegaCD, VSystemID.Raw.GEN when Emu is PicoDrive { Is32XActive: true } => ConsoleID.Sega32X, diff --git a/src/BizHawk.Client.EmuHawk/RetroAchievements/RetroAchievements.GameVerification.cs b/src/BizHawk.Client.EmuHawk/RetroAchievements/RetroAchievements.GameVerification.cs index 2a619a59dc6..048ef7ca6a5 100644 --- a/src/BizHawk.Client.EmuHawk/RetroAchievements/RetroAchievements.GameVerification.cs +++ b/src/BizHawk.Client.EmuHawk/RetroAchievements/RetroAchievements.GameVerification.cs @@ -20,18 +20,18 @@ private int HashDisc(string path, ConsoleID consoleID) { // this shouldn't throw in practice, this is only called when loading was successful! using var disc = DiscExtensions.CreateAnyType(path, e => throw new(e)); - var dsr = new DiscSectorReader(disc) + DiscSectorReader dsr = new(disc) { Policy = { DeterministicClearBuffer = false } // let's make this a little faster }; - var buf2048 = new byte[2048]; - var buffer = new List(); + byte[] buf2048 = new byte[2048]; + List buffer = new(); int FirstDataTrackLBA() { var toc = disc.TOC; - for (var t = toc.FirstRecordedTrackNumber; t <= toc.LastRecordedTrackNumber; t++) + for (int t = toc.FirstRecordedTrackNumber; t <= toc.LastRecordedTrackNumber; t++) { if (toc.TOCItems[t] .IsData) return toc.TOCItems[t].LBA; @@ -44,12 +44,12 @@ int FirstDataTrackLBA() { case ConsoleID.PCEngineCD: { - var slba = FirstDataTrackLBA(); + int slba = FirstDataTrackLBA(); dsr.ReadLBA_2048(slba + 1, buf2048, 0); buffer.AddRange(new ArraySegment(buf2048, 128 - 22, 22)); - var bootSector = (buf2048[0] << 16) | (buf2048[1] << 8) | buf2048[2]; - var numSectors = buf2048[3]; - for (var i = 0; i < numSectors; i++) + int bootSector = (buf2048[0] << 16) | (buf2048[1] << 8) | buf2048[2]; + byte numSectors = buf2048[3]; + for (int i = 0; i < numSectors; i++) { dsr.ReadLBA_2048(slba + bootSector + i, buf2048, 0); buffer.AddRange(buf2048); @@ -58,12 +58,12 @@ int FirstDataTrackLBA() } case ConsoleID.PCFX: { - var slba = FirstDataTrackLBA(); + int slba = FirstDataTrackLBA(); dsr.ReadLBA_2048(slba + 1, buf2048, 0); buffer.AddRange(new ArraySegment(buf2048, 0, 128)); - var bootSector = (buf2048[35] << 24) | (buf2048[34] << 16) | (buf2048[33] << 8) | buf2048[32]; - var numSectors = (buf2048[39] << 24) | (buf2048[38] << 16) | (buf2048[37] << 8) | buf2048[36]; - for (var i = 0; i < numSectors; i++) + int bootSector = (buf2048[35] << 24) | (buf2048[34] << 16) | (buf2048[33] << 8) | buf2048[32]; + int numSectors = (buf2048[39] << 24) | (buf2048[38] << 16) | (buf2048[37] << 8) | buf2048[36]; + for (int i = 0; i < numSectors; i++) { dsr.ReadLBA_2048(slba + bootSector + i, buf2048, 0); buffer.AddRange(buf2048); @@ -75,15 +75,15 @@ int FirstDataTrackLBA() int GetFileSector(string filename, out int filesize) { dsr.ReadLBA_2048(16, buf2048, 0); - var sector = (buf2048[160] << 16) | (buf2048[159] << 8) | buf2048[158]; + int sector = (buf2048[160] << 16) | (buf2048[159] << 8) | buf2048[158]; dsr.ReadLBA_2048(sector, buf2048, 0); - var index = 0; + int index = 0; while (index + 33 + filename.Length < 2048) { - var term = buf2048[index + 33 + filename.Length]; - if (term == ';' || term == '\0') + byte term = buf2048[index + 33 + filename.Length]; + if (term is (byte)';' or (byte)'\0') { - var fn = Encoding.ASCII.GetString(buf2048, index + 33, filename.Length); + string fn = Encoding.ASCII.GetString(buf2048, index + 33, filename.Length); if (filename.Equals(fn, StringComparison.OrdinalIgnoreCase)) { filesize = (buf2048[index + 13] << 24) | (buf2048[index + 12] << 16) | (buf2048[index + 11] << 8) | buf2048[index + 10]; @@ -97,10 +97,10 @@ int GetFileSector(string filename, out int filesize) return -1; } - var exePath = "PSX.EXE"; + string exePath = "PSX.EXE"; // find SYSTEM.CNF sector - var sector = GetFileSector("SYSTEM.CNF", out _); + int sector = GetFileSector("SYSTEM.CNF", out _); if (sector > 0) { // read SYSTEM.CNF sector @@ -108,7 +108,7 @@ int GetFileSector(string filename, out int filesize) exePath = Encoding.ASCII.GetString(buf2048); // "BOOT = cdrom:" precedes the path - var index = exePath.IndexOf("BOOT = cdrom:", StringComparison.Ordinal); + int index = exePath.IndexOf("BOOT = cdrom:", StringComparison.Ordinal); if (index < -1) break; exePath = exePath.Remove(0, index + 13); @@ -117,7 +117,7 @@ int GetFileSector(string filename, out int filesize) while (index < exePath.Length && exePath[index] is '\\') index++; // end of the path has ; - var end = exePath.IndexOf(';'); + int end = exePath.IndexOf(';'); if (end < 0) break; exePath = exePath[index..end]; } @@ -126,14 +126,14 @@ int GetFileSector(string filename, out int filesize) // get the filename // valid too if -1, as that means we already have the filename - var start = exePath.LastIndexOf('\\'); + int start = exePath.LastIndexOf('\\'); if (start > 0) { exePath = exePath.Remove(0, start + 1); } // get sector for exe - sector = GetFileSector(exePath, out var exeSize); + sector = GetFileSector(exePath, out int exeSize); if (sector < 0) break; dsr.ReadLBA_2048(sector++, buf2048, 0); @@ -168,21 +168,21 @@ static string HashJaguar(DiscTrack bootTrack, DiscSectorReader dsr, bool commonH { const string _jaguarHeader = "ATARI APPROVED DATA HEADER ATRI"; const string _jaguarBSHeader = "TARA IPARPVODED TA AEHDAREA RT"; - var buffer = new List(); - var buf2352 = new byte[2352]; + List buffer = new(); + byte[] buf2352 = new byte[2352]; // find the boot track header // see https://github.com/TASEmulators/BizHawk/blob/f29113287e88c6a644dbff30f92a9833307aad20/waterbox/virtualjaguar/src/cdhle.cpp#L109-L145 - var startLba = bootTrack.LBA; - var numLbas = bootTrack.NextTrack.LBA - bootTrack.LBA; + int startLba = bootTrack.LBA; + int numLbas = bootTrack.NextTrack.LBA - bootTrack.LBA; int bootLen = 0, bootLba = 0, bootOff = 0; bool byteswapped = false, foundHeader = false; - var bootLenOffset = (commonHomebrewHash ? 0x40 : 0) + 32 + 4; - for (var i = 0; i < numLbas; i++) + int bootLenOffset = (commonHomebrewHash ? 0x40 : 0) + 32 + 4; + for (int i = 0; i < numLbas; i++) { dsr.ReadLBA_2352(startLba + i, buf2352, 0); - for (var j = 0; j < 2352 - bootLenOffset - 4; j++) + for (int j = 0; j < 2352 - bootLenOffset - 4; j++) { if (buf2352[j] == _jaguarHeader[0]) { @@ -249,7 +249,7 @@ static string HashJaguar(DiscTrack bootTrack, DiscSectorReader dsr, bool commonH return MD5Checksum.ComputeDigestHex(buffer.ToArray()); } - var jaguarHash = HashJaguar(disc.Sessions[2].Tracks[1], dsr, false); + string jaguarHash = HashJaguar(disc.Sessions[2].Tracks[1], dsr, false); switch (jaguarHash) { case null: @@ -272,46 +272,46 @@ static string HashJaguar(DiscTrack bootTrack, DiscSectorReader dsr, bool commonH return 0; } - var hash = MD5Checksum.ComputeDigestHex(buffer.ToArray()); + string hash = MD5Checksum.ComputeDigestHex(buffer.ToArray()); return IdentifyHash(hash); } private int HashArcade(string path) { // Arcade wants to just hash the filename (with no extension) - var name = Encoding.UTF8.GetBytes(Path.GetFileNameWithoutExtension(path)); - var hash = MD5Checksum.ComputeDigestHex(name); + byte[] name = Encoding.UTF8.GetBytes(Path.GetFileNameWithoutExtension(path)); + string hash = MD5Checksum.ComputeDigestHex(name); return IdentifyHash(hash); } private int Hash3DS(string path) { // 3DS is too big to hash as a byte array... - var hash = new byte[33]; + byte[] hash = new byte[33]; return RCheevos._lib.rc_hash_generate_from_file(hash, ConsoleID.Nintendo3DS, path) ? IdentifyHash(Encoding.ASCII.GetString(hash, 0, 32)) : 0; } protected IReadOnlyList GetRAGameIds(IOpenAdvanced ioa, ConsoleID consoleID) { - var ret = new List(); + List ret = new(); switch (ioa.TypeName) { case OpenAdvancedTypes.OpenRom: { - var ext = Path.GetExtension(Path.GetExtension(ioa.SimplePath.Replace("|", "")).ToLowerInvariant()); + string ext = Path.GetExtension(Path.GetExtension(ioa.SimplePath.Replace("|", "")).ToLowerInvariant()); if (ext == ".m3u") { - using var file = new HawkFile(ioa.SimplePath); - using var sr = new StreamReader(file.GetStream()); - var m3u = M3U_File.Read(sr); + using HawkFile file = new(ioa.SimplePath); + using StreamReader sr = new(file.GetStream()); + M3U_File m3u = M3U_File.Read(sr); m3u.Rebase(Path.GetDirectoryName(ioa.SimplePath)); ret.AddRange(m3u.Entries.Select(entry => HashDisc(entry.Path, consoleID))); } else if (ext == ".xml") { - var xml = XmlGame.Create(new(ioa.SimplePath)); + XmlGame xml = XmlGame.Create(new(ioa.SimplePath)); foreach (var kvp in xml.Assets) { if (consoleID is ConsoleID.Arcade) @@ -351,8 +351,8 @@ protected IReadOnlyList GetRAGameIds(IOpenAdvanced ioa, ConsoleID consoleID } else { - using var file = new HawkFile(ioa.SimplePath); - var rom = file.ReadAllBytes(); + using HawkFile file = new(ioa.SimplePath); + byte[] rom = file.ReadAllBytes(); ret.Add(IdentifyRom(rom)); } } @@ -369,8 +369,8 @@ protected IReadOnlyList GetRAGameIds(IOpenAdvanced ioa, ConsoleID consoleID case OpenAdvancedTypes.Libretro: { // can't know what's here exactly, so we'll just hash the entire thing - using var file = new HawkFile(ioa.SimplePath); - var rom = file.ReadAllBytes(); + using HawkFile file = new(ioa.SimplePath); + byte[] rom = file.ReadAllBytes(); ret.Add(IdentifyRom(rom)); break; } diff --git a/src/BizHawk.Client.EmuHawk/RetroAchievements/RetroAchievements.Hardcore.cs b/src/BizHawk.Client.EmuHawk/RetroAchievements/RetroAchievements.Hardcore.cs index f32e07e4e3e..c40e53776c8 100644 --- a/src/BizHawk.Client.EmuHawk/RetroAchievements/RetroAchievements.Hardcore.cs +++ b/src/BizHawk.Client.EmuHawk/RetroAchievements/RetroAchievements.Hardcore.cs @@ -84,8 +84,8 @@ protected void CheckHardcoreModeConditions() _inputManager.ClientControls.Overrides(_hardcoreHotkeyOverrides); _mainForm.FrameInch = false; - var fastForward = _inputManager.ClientControls["Fast Forward"] || _mainForm.FastForward; - var speedPercent = fastForward ? _getConfig().SpeedPercentAlternate : _getConfig().SpeedPercent; + bool fastForward = _inputManager.ClientControls["Fast Forward"] || _mainForm.FastForward; + int speedPercent = fastForward ? _getConfig().SpeedPercentAlternate : _getConfig().SpeedPercent; if (speedPercent < 100) { HandleHardcoreModeDisable("Slow motion in hardcore mode is not allowed."); @@ -147,11 +147,11 @@ protected void CheckHardcoreModeConditions() break; } default: - if (CoreGraphicsLayers.TryGetValue(Emu.GetType(), out var layers)) + if (CoreGraphicsLayers.TryGetValue(Emu.GetType(), out string[] layers)) { - var s = _mainForm.GetSettingsAdapterForLoadedCoreUntyped().GetSettings(); + object s = _mainForm.GetSettingsAdapterForLoadedCoreUntyped().GetSettings(); var t = s.GetType(); - foreach (var layer in layers) + foreach (string layer in layers) { // annoyingly NES has fields instead of properties for layers if ((bool)(t.GetProperty(layer) diff --git a/src/BizHawk.Client.EmuHawk/RetroAchievements/RetroAchievements.Memory.cs b/src/BizHawk.Client.EmuHawk/RetroAchievements/RetroAchievements.Memory.cs index 9859312234f..1cc055eda7a 100644 --- a/src/BizHawk.Client.EmuHawk/RetroAchievements/RetroAchievements.Memory.cs +++ b/src/BizHawk.Client.EmuHawk/RetroAchievements/RetroAchievements.Memory.cs @@ -33,10 +33,7 @@ public void Enter() } } - public void Exit() - { - _memSema.Release(); - } + public void Exit() => _memSema.Release(); public void Dispose() { @@ -146,12 +143,12 @@ protected virtual int ReadMemBlock(int addr, IntPtr buffer, int bytes) using (MemGuard.EnterExit()) { - var end = Math.Min(addr + bytes, _domainAddrStart + BankSize); - var length = end - addr; + int end = Math.Min(addr + bytes, _domainAddrStart + BankSize); + int length = end - addr; if (_addressMangler == 0) { - var ret = new byte[length]; + byte[] ret = new byte[length]; _domain.BulkPeekByte(((long)addr).RangeToExclusive(end), ret); Marshal.Copy(ret, 0, buffer, length); } @@ -159,7 +156,7 @@ protected virtual int ReadMemBlock(int addr, IntPtr buffer, int bytes) { unsafe { - for (var i = addr; i < end; i++) + for (int i = addr; i < end; i++) { ((byte*)buffer)![i - addr] = _domain.PeekByte(i ^ _addressMangler); } @@ -235,12 +232,12 @@ protected override int ReadMemBlock(int addr, IntPtr buffer, int bytes) using (MemGuard.EnterExit()) { - var end = Math.Min(addr + bytes, BankSize); - var length = end - addr; + int end = Math.Min(addr + bytes, BankSize); + int length = end - addr; unsafe { - for (var i = addr; i < end; i++) + for (int i = addr; i < end; i++) { if ((i & 2) != 0) { @@ -320,8 +317,8 @@ protected override int ReadMemBlock(int addr, IntPtr buffer, int bytes) using (MemGuard.EnterExit()) { var regs = _debuggable.GetCpuFlagsAndRegisters(); - var end = Math.Min(addr + bytes, BankSize); - for (var i = addr; i < end; i++) + int end = Math.Min(addr + bytes, BankSize); + for (int i = addr; i < end; i++) { byte val; if (i < 0x40) @@ -380,7 +377,7 @@ public ChanFMemFunctions(IDebuggable debuggable, MemoryDomain vram) protected static IReadOnlyList CreateMemoryBanks(ConsoleID consoleId, IMemoryDomains domains, IDebuggable debuggable) { - var mfs = new List(); + List mfs = new(); void TryAddDomain(string domain, int? size = null, int addressMangler = 0) { diff --git a/src/BizHawk.Client.EmuHawk/ScreenSaver.cs b/src/BizHawk.Client.EmuHawk/ScreenSaver.cs index 906dc025d13..b35803fd654 100644 --- a/src/BizHawk.Client.EmuHawk/ScreenSaver.cs +++ b/src/BizHawk.Client.EmuHawk/ScreenSaver.cs @@ -45,10 +45,7 @@ private class UnixScreenBlankTimer : IScreenBlankTimer private static int ctr; - public static void ResetTimerImmediate() - { - _screenBlankTimer.Duration = _screenBlankTimer.Duration; - } + public static void ResetTimerImmediate() => _screenBlankTimer.Duration = _screenBlankTimer.Duration; public static void ResetTimerPeriodically() { diff --git a/src/BizHawk.Client.EmuHawk/Sound/Sound.cs b/src/BizHawk.Client.EmuHawk/Sound/Sound.cs index 782d8f2b92d..667ff7f62b3 100644 --- a/src/BizHawk.Client.EmuHawk/Sound/Sound.cs +++ b/src/BizHawk.Client.EmuHawk/Sound/Sound.cs @@ -24,7 +24,7 @@ public class Sound : IHostAudioManager, IDisposable private bool _disposed; private readonly ISoundOutput _outputDevice; private readonly SoundOutputProvider _outputProvider; // Buffer for Sync sources - private readonly BufferedAsync _bufferedAsync = new BufferedAsync(); // Buffer for Async sources + private readonly BufferedAsync _bufferedAsync = new(); // Buffer for Async sources private IBufferedSoundProvider _bufferedProvider; // One of the preceding buffers, or null if no source is set public Config Config; diff --git a/src/BizHawk.Client.EmuHawk/Throttle.cs b/src/BizHawk.Client.EmuHawk/Throttle.cs index a686550bf57..65dc963032d 100644 --- a/src/BizHawk.Client.EmuHawk/Throttle.cs +++ b/src/BizHawk.Client.EmuHawk/Throttle.cs @@ -205,10 +205,7 @@ public void AutoFrameSkip_IgnorePreviousDelay() fSkipFrames *= 0.5f; } - private void AutoFrameSkip_BeforeThrottle() - { - preThrottleEndticks = GetCurTime(); - } + private void AutoFrameSkip_BeforeThrottle() => preThrottleEndticks = GetCurTime(); private void AutoFrameSkip_NextFrame() { diff --git a/src/BizHawk.Client.EmuHawk/UIHelper.cs b/src/BizHawk.Client.EmuHawk/UIHelper.cs index 72e851b3fdc..e55a73bec64 100644 --- a/src/BizHawk.Client.EmuHawk/UIHelper.cs +++ b/src/BizHawk.Client.EmuHawk/UIHelper.cs @@ -18,29 +18,17 @@ public static class UIHelper public static SizeF AutoScaleFactor { get; } = new SizeF(AutoScaleFactorX, AutoScaleFactorY); - public static int ScaleX(int size) - { - return (int)Math.Round(size * AutoScaleFactorX); - } + public static int ScaleX(int size) => (int)Math.Round(size * AutoScaleFactorX); - public static int ScaleY(int size) - { - return (int)Math.Round(size * AutoScaleFactorY); - } + public static int ScaleY(int size) => (int)Math.Round(size * AutoScaleFactorY); - public static Point Scale(Point p) - { - return new Point(ScaleX(p.X), ScaleY(p.Y)); - } + public static Point Scale(Point p) => new(ScaleX(p.X), ScaleY(p.Y)); - public static Size Scale(Size s) - { - return new Size(ScaleX(s.Width), ScaleY(s.Height)); - } + public static Size Scale(Size s) => new(ScaleX(s.Width), ScaleY(s.Height)); private static SizeF GetCurrentAutoScaleSize(AutoScaleMode autoScaleMode) { - using var form = new Form { AutoScaleMode = autoScaleMode }; + using Form form = new() { AutoScaleMode = autoScaleMode }; return form.CurrentAutoScaleDimensions; } diff --git a/src/BizHawk.Client.EmuHawk/UpdateChecker.cs b/src/BizHawk.Client.EmuHawk/UpdateChecker.cs index 045682a2c84..5f6efe202c0 100644 --- a/src/BizHawk.Client.EmuHawk/UpdateChecker.cs +++ b/src/BizHawk.Client.EmuHawk/UpdateChecker.cs @@ -58,10 +58,7 @@ public static void BeginCheck(bool skipCheck = false) && VersionInfo.VersionStrToInt(VersionInfo.MainVersion) != 0U // Avoid notifying if current version string is invalid && VersionInfo.VersionStrToInt(LatestVersion) > VersionInfo.VersionStrToInt(VersionInfo.MainVersion); - public static void IgnoreNewVersion() - { - IgnoreVersion = LatestVersion; - } + public static void IgnoreNewVersion() => IgnoreVersion = LatestVersion; public static void ResetHistory() { @@ -90,23 +87,17 @@ private static void CheckInternal() private static string DownloadURLAsString(string url) { - var request = (HttpWebRequest)WebRequest.Create(url); + HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.UserAgent = "BizHawk"; request.KeepAlive = false; - using var response = (HttpWebResponse)request.GetResponse(); - using var responseStream = new StreamReader(response.GetResponseStream()); + using HttpWebResponse response = (HttpWebResponse)request.GetResponse(); + using StreamReader responseStream = new(response.GetResponseStream()); return responseStream.ReadToEnd(); } - private static string ValidateVersionNumberString(string versionNumber) - { - return versionNumber != null && VersionInfo.VersionStrToInt(versionNumber) != 0U ? versionNumber : ""; - } + private static string ValidateVersionNumberString(string versionNumber) => versionNumber != null && VersionInfo.VersionStrToInt(versionNumber) != 0U ? versionNumber : ""; - private static void OnCheckComplete() - { - CheckComplete?.Invoke(null, EventArgs.Empty); - } + private static void OnCheckComplete() => CheckComplete?.Invoke(null, EventArgs.Empty); public static event EventHandler CheckComplete; } diff --git a/src/BizHawk.Client.EmuHawk/config/A7800/A7800ControllerSettings.cs b/src/BizHawk.Client.EmuHawk/config/A7800/A7800ControllerSettings.cs index 9e473f089ac..e5d98cdca7d 100644 --- a/src/BizHawk.Client.EmuHawk/config/A7800/A7800ControllerSettings.cs +++ b/src/BizHawk.Client.EmuHawk/config/A7800/A7800ControllerSettings.cs @@ -22,7 +22,7 @@ public A7800ControllerSettings(ISettingsAdapter settable) private void IntvControllerSettings_Load(object sender, EventArgs e) { - foreach (var val in A7800HawkControllerDeck.ControllerCtors.Keys) + foreach (string val in A7800HawkControllerDeck.ControllerCtors.Keys) { Port1ComboBox.Items.Add(val); Port2ComboBox.Items.Add(val); diff --git a/src/BizHawk.Client.EmuHawk/config/A7800/A7800FilterSettings.cs b/src/BizHawk.Client.EmuHawk/config/A7800/A7800FilterSettings.cs index 7386432e56a..f9e68e110bf 100644 --- a/src/BizHawk.Client.EmuHawk/config/A7800/A7800FilterSettings.cs +++ b/src/BizHawk.Client.EmuHawk/config/A7800/A7800FilterSettings.cs @@ -25,7 +25,7 @@ private void A7800FilterSettings_Load(object sender, EventArgs e) { var possibleFilters = A7800Hawk.ValidFilterTypes.Select(t => t.Key); - foreach (var val in possibleFilters) + foreach (string val in possibleFilters) { Port1ComboBox.Items.Add(val); } diff --git a/src/BizHawk.Client.EmuHawk/config/AmstradCPC/AmstradCPCAudioSettings.cs b/src/BizHawk.Client.EmuHawk/config/AmstradCPC/AmstradCPCAudioSettings.cs index 5e95e7f5c49..30f11aa7f54 100644 --- a/src/BizHawk.Client.EmuHawk/config/AmstradCPC/AmstradCPCAudioSettings.cs +++ b/src/BizHawk.Client.EmuHawk/config/AmstradCPC/AmstradCPCAudioSettings.cs @@ -24,8 +24,8 @@ public AmstradCpcAudioSettings(ISettingsAdapter settable) private void IntvControllerSettings_Load(object sender, EventArgs e) { // AY panning config - var panTypes = Enum.GetNames(typeof(AY38912.AYPanConfig)); - foreach (var val in panTypes) + string[] panTypes = Enum.GetNames(typeof(AY38912.AYPanConfig)); + foreach (string val in panTypes) { panTypecomboBox1.Items.Add(val); } diff --git a/src/BizHawk.Client.EmuHawk/config/AmstradCPC/AmstradCPCCoreEmulationSettings.cs b/src/BizHawk.Client.EmuHawk/config/AmstradCPC/AmstradCPCCoreEmulationSettings.cs index 179c0146571..f0c8e23783d 100644 --- a/src/BizHawk.Client.EmuHawk/config/AmstradCPC/AmstradCPCCoreEmulationSettings.cs +++ b/src/BizHawk.Client.EmuHawk/config/AmstradCPC/AmstradCPCCoreEmulationSettings.cs @@ -22,8 +22,8 @@ public AmstradCpcCoreEmulationSettings(ISettingsAdapter settable) private void IntvControllerSettings_Load(object sender, EventArgs e) { // machine selection - var machineTypes = Enum.GetNames(typeof(MachineType)); - foreach (var val in machineTypes) + string[] machineTypes = Enum.GetNames(typeof(MachineType)); + foreach (string val in machineTypes) { MachineSelectionComboBox.Items.Add(val); } @@ -31,8 +31,8 @@ private void IntvControllerSettings_Load(object sender, EventArgs e) UpdateMachineNotes((MachineType)Enum.Parse(typeof(MachineType), MachineSelectionComboBox.SelectedItem.ToString())); // border selection - var borderTypes = Enum.GetNames(typeof(AmstradCPC.BorderType)); - foreach (var val in borderTypes) + string[] borderTypes = Enum.GetNames(typeof(AmstradCPC.BorderType)); + foreach (string val in borderTypes) { borderTypecomboBox1.Items.Add(val); } @@ -81,18 +81,15 @@ private void CancelBtn_Click(object sender, EventArgs e) private void MachineSelectionComboBox_SelectionChangeCommitted(object sender, EventArgs e) { - var cb = (ComboBox)sender; + ComboBox cb = (ComboBox)sender; UpdateMachineNotes((MachineType)Enum.Parse(typeof(MachineType), cb.SelectedItem.ToString())); } - private void UpdateMachineNotes(MachineType type) - { - textBoxMachineNotes.Text = AmstradCPC.CPCMachineMetaData.GetMetaString(type); - } + private void UpdateMachineNotes(MachineType type) => textBoxMachineNotes.Text = AmstradCPC.CPCMachineMetaData.GetMetaString(type); private void BorderTypeComboBox_SelectedIndexChanged(object sender, EventArgs e) { - var cb = (ComboBox)sender; + ComboBox cb = (ComboBox)sender; UpdateBorderNotes((AmstradCPC.BorderType)Enum.Parse(typeof(AmstradCPC.BorderType), cb.SelectedItem.ToString())); } diff --git a/src/BizHawk.Client.EmuHawk/config/AmstradCPC/AmstradCPCNonSyncSettings.cs b/src/BizHawk.Client.EmuHawk/config/AmstradCPC/AmstradCPCNonSyncSettings.cs index 644093431a9..7dd818440c8 100644 --- a/src/BizHawk.Client.EmuHawk/config/AmstradCPC/AmstradCPCNonSyncSettings.cs +++ b/src/BizHawk.Client.EmuHawk/config/AmstradCPC/AmstradCPCNonSyncSettings.cs @@ -23,8 +23,8 @@ public AmstradCpcNonSyncSettings(ISettingsAdapter settable) private void IntvControllerSettings_Load(object sender, EventArgs e) { // OSD Message Verbosity - var osdTypes = Enum.GetNames(typeof(AmstradCPC.OSDVerbosity)); - foreach (var val in osdTypes) + string[] osdTypes = Enum.GetNames(typeof(AmstradCPC.OSDVerbosity)); + foreach (string val in osdTypes) { osdMessageVerbositycomboBox1.Items.Add(val); } @@ -77,7 +77,7 @@ private void UpdateOSDNotes(AmstradCPC.OSDVerbosity type) private void OSDComboBox_SelectionChangeCommitted(object sender, EventArgs e) { - var cb = (ComboBox)sender; + ComboBox cb = (ComboBox)sender; UpdateOSDNotes((AmstradCPC.OSDVerbosity)Enum.Parse(typeof(AmstradCPC.OSDVerbosity), cb.SelectedItem.ToString())); } } diff --git a/src/BizHawk.Client.EmuHawk/config/AnalogRangeConfig.cs b/src/BizHawk.Client.EmuHawk/config/AnalogRangeConfig.cs index 1f4033ba8a7..490b19734ee 100644 --- a/src/BizHawk.Client.EmuHawk/config/AnalogRangeConfig.cs +++ b/src/BizHawk.Client.EmuHawk/config/AnalogRangeConfig.cs @@ -57,8 +57,8 @@ private Point TopLeft { get { - var centerX = Size.Width / 2; - var centerY = Size.Height / 2; + int centerX = Size.Width / 2; + int centerY = Size.Height / 2; return new Point(centerX - ScaledX, centerY - ScaledY); } @@ -142,11 +142,11 @@ private void DoDrag(int x, int y) { if (_isDragging) { - var centerX = Size.Width / 2; - var centerY = Size.Height / 2; + int centerX = Size.Width / 2; + int centerY = Size.Height / 2; - var offsetX = Math.Abs(centerX - x) * ScaleFactor; - var offsetY = Math.Abs(centerY - y) * ScaleFactor; + int offsetX = Math.Abs(centerX - x) * ScaleFactor; + int offsetY = Math.Abs(centerY - y) * ScaleFactor; MaxX = Math.Min(offsetX, sbyte.MaxValue); MaxY = Math.Min(offsetY, sbyte.MaxValue); @@ -161,9 +161,6 @@ protected override void OnMouseMove(MouseEventArgs e) public Action ChangeCallback { get; set; } - private void Changed() - { - ChangeCallback?.Invoke(); - } + private void Changed() => ChangeCallback?.Invoke(); } } diff --git a/src/BizHawk.Client.EmuHawk/config/AnalogRangeConfigControl.cs b/src/BizHawk.Client.EmuHawk/config/AnalogRangeConfigControl.cs index 2f2b0ee7c03..a0c14f2c7a0 100644 --- a/src/BizHawk.Client.EmuHawk/config/AnalogRangeConfigControl.cs +++ b/src/BizHawk.Client.EmuHawk/config/AnalogRangeConfigControl.cs @@ -12,10 +12,7 @@ public AnalogRangeConfigControl() InitializeComponent(); } - private void AnalogRangeConfigControl_Load(object sender, EventArgs e) - { - AnalogRange.ChangeCallback = AnalogControlChanged; - } + private void AnalogRangeConfigControl_Load(object sender, EventArgs e) => AnalogRange.ChangeCallback = AnalogControlChanged; private void XNumeric_ValueChanged(object sender, EventArgs e) { diff --git a/src/BizHawk.Client.EmuHawk/config/ColecoVision/ColecoControllerSettings.cs b/src/BizHawk.Client.EmuHawk/config/ColecoVision/ColecoControllerSettings.cs index bf7f4a2577b..62a6d49c52e 100644 --- a/src/BizHawk.Client.EmuHawk/config/ColecoVision/ColecoControllerSettings.cs +++ b/src/BizHawk.Client.EmuHawk/config/ColecoVision/ColecoControllerSettings.cs @@ -22,7 +22,7 @@ public ColecoControllerSettings(ISettingsAdapter settable) private void ColecoControllerSettings_Load(object sender, EventArgs e) { - foreach (var val in ColecoVisionControllerDeck.ControllerCtors.Keys) + foreach (string val in ColecoVisionControllerDeck.ControllerCtors.Keys) { Port1ComboBox.Items.Add(val); Port2ComboBox.Items.Add(val); diff --git a/src/BizHawk.Client.EmuHawk/config/ControllerConfig.cs b/src/BizHawk.Client.EmuHawk/config/ControllerConfig.cs index 50641fb9ec0..06b573cfbf7 100644 --- a/src/BizHawk.Client.EmuHawk/config/ControllerConfig.cs +++ b/src/BizHawk.Client.EmuHawk/config/ControllerConfig.cs @@ -15,7 +15,7 @@ namespace BizHawk.Client.EmuHawk { public partial class ControllerConfig : Form, IDialogParent { - private static readonly Dictionary> ControllerImages = new Dictionary>(); + private static readonly Dictionary> ControllerImages = new(); private readonly IEmulator _emulator; private readonly Config _config; @@ -73,10 +73,7 @@ private void ControllerConfig_Load(object sender, EventArgs e) Text = $"{_emulator.ControllerDefinition.Name} Configuration"; } - private void ControllerConfig_FormClosed(object sender, FormClosedEventArgs e) - { - Input.Instance.ClearEvents(); - } + private void ControllerConfig_FormClosed(object sender, FormClosedEventArgs e) => Input.Instance.ClearEvents(); private delegate Control PanelCreator(Dictionary settings, List buttons, Size size); @@ -87,17 +84,11 @@ private Control CreateNormalPanel(Dictionary settings, List settings, List buttons, Size size) - { - return new AnalogBindPanel(settings, buttons) { Dock = DockStyle.Fill, AutoScroll = true }; - } + private static Control CreateAnalogPanel(Dictionary settings, List buttons, Size size) => new AnalogBindPanel(settings, buttons) { Dock = DockStyle.Fill, AutoScroll = true }; - private static Control CreateFeedbacksPanel(Dictionary settings, List buttons, Size size) - { - return new FeedbacksBindPanel(settings, buttons) { Dock = DockStyle.Fill, AutoScroll = true }; - } + private static Control CreateFeedbacksPanel(Dictionary settings, List buttons, Size size) => new FeedbacksBindPanel(settings, buttons) { Dock = DockStyle.Fill, AutoScroll = true }; - private static readonly Regex ButtonMatchesPlayer = new Regex("^P(\\d+)\\s"); + private static readonly Regex ButtonMatchesPlayer = new("^P(\\d+)\\s"); private void LoadToPanel( Control dest, @@ -112,7 +103,7 @@ PanelCreator createPanel var settings = settingsBlock.GetValueOrPutNew(controllerName); // check to make sure that the settings object has all of the appropriate bool buttons - foreach (var button in controllerButtons) + foreach (string button in controllerButtons) { if (!settings.ContainsKey(button)) { @@ -127,15 +118,15 @@ PanelCreator createPanel // split the list of all settings into buckets by player number, or supplied category // the order that buttons appeared in determines the order of the tabs - var orderedBuckets = new List>>(); - var buckets = new Dictionary>(); + List>> orderedBuckets = new(); + Dictionary> buckets = new(); // by iterating through only the controller's active buttons, we're silently // discarding anything that's not on the controller right now. due to the way // saving works, those entries will still be preserved in the config file, tho - foreach (var button in controllerButtons) + foreach (string button in controllerButtons) { - if (!categoryLabels.TryGetValue(button, out var categoryLabel)) + if (!categoryLabels.TryGetValue(button, out string categoryLabel)) { var m = ButtonMatchesPlayer.Match(button); categoryLabel = m.Success @@ -145,7 +136,7 @@ PanelCreator createPanel if (!buckets.ContainsKey(categoryLabel)) { - var l = new List(); + List l = new(); buckets.Add(categoryLabel, l); orderedBuckets.Add(new KeyValuePair>(categoryLabel, l)); } @@ -161,7 +152,7 @@ PanelCreator createPanel else { // create multiple tabs - var tt = new TabControl { Dock = DockStyle.Fill }; + TabControl tt = new() { Dock = DockStyle.Fill }; dest.Controls.Add(tt); int pageIdx = 0; foreach (var (tabName, buttons) in orderedBuckets) @@ -255,15 +246,9 @@ private void LoadPanels( if (FeedbacksTab.Controls.Count == 0) tabControl1.TabPages.Remove(FeedbacksTab); } - private void LoadPanels(DefaultControls cd) - { - LoadPanels(cd.AllTrollers, cd.AllTrollersAutoFire, cd.AllTrollersAnalog, cd.AllTrollersFeedbacks); - } + private void LoadPanels(DefaultControls cd) => LoadPanels(cd.AllTrollers, cd.AllTrollersAutoFire, cd.AllTrollersAnalog, cd.AllTrollersFeedbacks); - private void LoadPanels(Config c) - { - LoadPanels(c.AllTrollers, c.AllTrollersAutoFire, c.AllTrollersAnalog, c.AllTrollersFeedbacks); - } + private void LoadPanels(Config c) => LoadPanels(c.AllTrollers, c.AllTrollersAutoFire, c.AllTrollersAnalog, c.AllTrollersFeedbacks); private void SetControllerPicture(string controlName) { @@ -283,11 +268,11 @@ private void SetControllerPicture(string controlName) // Uberhack if (controlName == "Commodore 64 Controller") { - var pictureBox2 = new PictureBox - { - Image = Properties.Resources.C64Keyboard.Value, - Size = Properties.Resources.C64Keyboard.Value.Size - }; + PictureBox pictureBox2 = new() + { + Image = Properties.Resources.C64Keyboard.Value, + Size = Properties.Resources.C64Keyboard.Value.Size + }; tableLayoutPanel1.ColumnStyles[1].Width = Properties.Resources.C64Keyboard.Value.Width; pictureBox1.Height /= 2; pictureBox1.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; @@ -373,10 +358,7 @@ private static void ActOnControlCollection(Control c, Action proc) } } - private void CheckBoxAutoTab_CheckedChanged(object sender, EventArgs e) - { - SetAutoTab(this, checkBoxAutoTab.Checked); - } + private void CheckBoxAutoTab_CheckedChanged(object sender, EventArgs e) => SetAutoTab(this, checkBoxAutoTab.Checked); private void ButtonOk_Click(object sender, EventArgs e) { @@ -391,10 +373,7 @@ private void ButtonOk_Click(object sender, EventArgs e) Close(); } - private void ButtonCancel_Click(object sender, EventArgs e) - { - Close(); - } + private void ButtonCancel_Click(object sender, EventArgs e) => Close(); private static TabControl GetTabControl(IEnumerable controls) { @@ -407,7 +386,7 @@ private void ButtonLoadDefaults_Click(object sender, EventArgs e) { tabControl1.SuspendLayout(); - var wasTabbedMain = tabControl1.SelectedTab.Name; + string wasTabbedMain = tabControl1.SelectedTab.Name; var tb1 = GetTabControl(NormalControlsTab.Controls); var tb2 = GetTabControl(AutofireControlsTab.Controls); var tb3 = GetTabControl(AnalogControlsTab.Controls); @@ -466,7 +445,7 @@ private void ButtonSaveDefaults_Click(object sender, EventArgs e) { // this doesn't work anymore, as it stomps out any defaults for buttons that aren't currently active on the console // there are various ways to fix it, each with its own semantic problems - var result = this.ModalMessageBox2("OK to overwrite defaults for current control scheme?", "Save Defaults"); + bool result = this.ModalMessageBox2("OK to overwrite defaults for current control scheme?", "Save Defaults"); if (result) { var cd = ConfigService.Load(Config.ControlDefaultPath); @@ -495,7 +474,7 @@ private void ClearWidgetAndChildren(Control c) break; } - var children = c.Controls().ToList(); + List children = c.Controls().ToList(); if (children.Count != 0) { foreach (var child in children) ClearWidgetAndChildren(child); diff --git a/src/BizHawk.Client.EmuHawk/config/ControllerConfig/AnalogBindControl.cs b/src/BizHawk.Client.EmuHawk/config/ControllerConfig/AnalogBindControl.cs index d0d200456da..4aae4ac6af6 100644 --- a/src/BizHawk.Client.EmuHawk/config/ControllerConfig/AnalogBindControl.cs +++ b/src/BizHawk.Client.EmuHawk/config/ControllerConfig/AnalogBindControl.cs @@ -75,10 +75,7 @@ private void TrackBarDeadzone_ValueChanged(object sender, EventArgs e) labelDeadzone.Text = $"Deadzone: {_bind.Deadzone:P0}"; } - private void ButtonFlip_Click(object sender, EventArgs e) - { - trackBarSensitivity.Value *= -1; - } + private void ButtonFlip_Click(object sender, EventArgs e) => trackBarSensitivity.Value *= -1; public void Unbind_Click(object sender, EventArgs e) { diff --git a/src/BizHawk.Client.EmuHawk/config/ControllerConfig/AnalogBindPanel.cs b/src/BizHawk.Client.EmuHawk/config/ControllerConfig/AnalogBindPanel.cs index adfaf329314..89a616cb300 100644 --- a/src/BizHawk.Client.EmuHawk/config/ControllerConfig/AnalogBindPanel.cs +++ b/src/BizHawk.Client.EmuHawk/config/ControllerConfig/AnalogBindPanel.cs @@ -23,7 +23,7 @@ private void LoadSettings(IEnumerable buttonList) int y = 4; foreach (string buttonName in buttonList) { - var ctrl = new AnalogBindControl(buttonName, _realConfigObject[buttonName]) + AnalogBindControl ctrl = new(buttonName, _realConfigObject[buttonName]) { Location = new Point(x, y) }; @@ -44,7 +44,7 @@ public void Save(Dictionary saveConfigObject = null) var saveTo = saveConfigObject ?? _realConfigObject; foreach (Control c in Controls) { - var abc = (AnalogBindControl)c; + AnalogBindControl abc = (AnalogBindControl)c; saveTo[abc.ButtonName] = abc.Bind; } } diff --git a/src/BizHawk.Client.EmuHawk/config/ControllerConfig/ControllerConfigPanel.cs b/src/BizHawk.Client.EmuHawk/config/ControllerConfig/ControllerConfigPanel.cs index 7398d888455..ce0ff9c31a8 100644 --- a/src/BizHawk.Client.EmuHawk/config/ControllerConfig/ControllerConfigPanel.cs +++ b/src/BizHawk.Client.EmuHawk/config/ControllerConfig/ControllerConfigPanel.cs @@ -16,7 +16,7 @@ public partial class ControllerConfigPanel : UserControl // for instance, to show only a single player private List _realConfigButtons; - private readonly List _buttons = new List(); + private readonly List _buttons = new(); private readonly int _inputMarginLeft = UIHelper.ScaleX(0); private readonly int _labelPadding = UIHelper.ScaleX(5); @@ -27,9 +27,9 @@ public partial class ControllerConfigPanel : UserControl public ToolTip Tooltip { get; set; } - private readonly List _inputs = new List(); + private readonly List _inputs = new(); - private Size _panelSize = new Size(0, 0); + private Size _panelSize = new(0, 0); private bool _autoTab; @@ -41,10 +41,7 @@ public ControllerConfigPanel(IReadOnlyList effectiveModList) InitializeComponent(); } - private void ClearAll() - { - _inputs.ForEach(x => x.Clear()); - } + private void ClearAll() => _inputs.ForEach(x => x.Clear()); /// /// save to config @@ -55,7 +52,7 @@ public void Save(Dictionary saveConfigObject = null) var saveTo = saveConfigObject ?? _realConfigObject; for (int button = 0; button < _buttons.Count; button++) { - var bindings = _inputs[button].Bindings; + string bindings = _inputs[button].Bindings; if (!string.IsNullOrWhiteSpace(bindings)) { saveTo[_buttons[button]] = bindings; @@ -89,7 +86,7 @@ public void LoadSettings(Dictionary config, bool autoTab, List bl = _realConfigButtons ?? (IEnumerable)_realConfigObject.Keys; + var bl = _realConfigButtons ?? (IEnumerable)_realConfigObject.Keys; foreach (string s in bl) { _buttons.Add(s); @@ -100,7 +97,7 @@ private void SetWidgetStrings() { for (int button = 0; button < _buttons.Count; button++) { - if (!_realConfigObject.TryGetValue(_buttons[button], out var s)) + if (!_realConfigObject.TryGetValue(_buttons[button], out string s)) { s = ""; } @@ -111,8 +108,8 @@ private void SetWidgetStrings() private void Startup() { - var labelWidth = _buttons.Max(b => b.Length) * _charWidth; - var columnWidth = _inputSize + (_labelPadding * 2) + labelWidth; + int labelWidth = _buttons.Max(b => b.Length) * _charWidth; + int columnWidth = _inputSize + (_labelPadding * 2) + labelWidth; int x = _inputMarginLeft; int y = _marginTop - _ySpacing; for (int i = 0; i < _buttons.Count; i++) @@ -124,7 +121,7 @@ private void Startup() x += columnWidth; } - var iw = new InputCompositeWidget(_effectiveModList) + InputCompositeWidget iw = new(_effectiveModList) { Location = new Point(x, y), Size = new Size(_inputSize, UIHelper.ScaleY(23)), @@ -137,7 +134,7 @@ private void Startup() iw.BringToFront(); Controls.Add(iw); _inputs.Add(iw); - var label = new Label + Label label = new() { Location = new Point(x + _inputSize + _labelPadding, y + UIHelper.ScaleY(3)), Size = new Size(labelWidth, UIHelper.ScaleY(15)), @@ -150,14 +147,8 @@ private void Startup() } } - public void SetAutoTab(bool value) - { - _inputs.ForEach(x => x.AutoTab = value); - } + public void SetAutoTab(bool value) => _inputs.ForEach(x => x.AutoTab = value); - private void ClearToolStripMenuItem_Click(object sender, EventArgs e) - { - ClearAll(); - } + private void ClearToolStripMenuItem_Click(object sender, EventArgs e) => ClearAll(); } } diff --git a/src/BizHawk.Client.EmuHawk/config/ControllerConfig/FeedbackBindControl.cs b/src/BizHawk.Client.EmuHawk/config/ControllerConfig/FeedbackBindControl.cs index 7d896bff987..e3944ea8827 100644 --- a/src/BizHawk.Client.EmuHawk/config/ControllerConfig/FeedbackBindControl.cs +++ b/src/BizHawk.Client.EmuHawk/config/ControllerConfig/FeedbackBindControl.cs @@ -34,15 +34,15 @@ public FeedbackBindControl(string vChannel, FeedbackBind existingBind, IHostInpu void UpdateDropdownAndLabel(string newPrefix) { txtBoundPrefix.Text = newPrefix; - var wasSelected = (string) cbBoundChannel.SelectedItem; + string wasSelected = (string) cbBoundChannel.SelectedItem; cbBoundChannel.Enabled = false; cbBoundChannel.SelectedIndex = -1; cbBoundChannel.Items.Clear(); if (hostInputAdapter.GetHapticsChannels().TryGetValue(newPrefix, out var channels) && channels.Count != 0) { - var hasLeft = false; - var hasRight = false; - foreach (var hostChannel in channels) + bool hasLeft = false; + bool hasRight = false; + foreach (string hostChannel in channels) { cbBoundChannel.Items.Add(hostChannel); if (hostChannel == "Left") hasLeft = true; @@ -80,10 +80,10 @@ void UpdateListeningState(bool newState) btnBind.Text = "Bind!"; } } - var isListening = false; + bool isListening = false; timer.Tick += (_, _) => { - var bindValue = Input.Instance.GetNextAxisEvent(); + string bindValue = Input.Instance.GetNextAxisEvent(); if (bindValue == null) return; UpdateListeningState(isListening = false); UpdateDropdownAndLabel(BoundGamepadPrefix = bindValue.SubstringBefore(' ') + ' '); diff --git a/src/BizHawk.Client.EmuHawk/config/ControllerConfig/FeedbacksBindPanel.cs b/src/BizHawk.Client.EmuHawk/config/ControllerConfig/FeedbacksBindPanel.cs index bcf7b28ff83..211a6304dbb 100644 --- a/src/BizHawk.Client.EmuHawk/config/ControllerConfig/FeedbacksBindPanel.cs +++ b/src/BizHawk.Client.EmuHawk/config/ControllerConfig/FeedbacksBindPanel.cs @@ -20,7 +20,7 @@ public FeedbacksBindPanel(IDictionary realConfigObject, IC _realConfigObject = realConfigObject; _flpMain.Controls.Add(new LabelEx { Text = "To bind, click \"Bind!\", move an axis (e.g. analog stick) on the desired gamepad, and choose from the dropdown.\nNote: haptic feedback won't work if your input method is DirectInput+XInput and your gamepad is shown as \"J#\"." }); var adapter = Input.Instance.Adapter; - foreach (var buttonName in realConfigButtons ?? realConfigObject.Keys) + foreach (string buttonName in realConfigButtons ?? realConfigObject.Keys) { _flpMain.Controls.Add(new FeedbackBindControl(buttonName, _realConfigObject[buttonName], adapter)); } diff --git a/src/BizHawk.Client.EmuHawk/config/DisplayConfig.cs b/src/BizHawk.Client.EmuHawk/config/DisplayConfig.cs index 556b574dab7..08b95c7fa30 100755 --- a/src/BizHawk.Client.EmuHawk/config/DisplayConfig.cs +++ b/src/BizHawk.Client.EmuHawk/config/DisplayConfig.cs @@ -262,14 +262,11 @@ private void BtnOk_Click(object sender, EventArgs e) Close(); } - private void RefreshState() - { - lblUserFilterName.Text = Path.GetFileNameWithoutExtension(_pathSelection); - } + private void RefreshState() => lblUserFilterName.Text = Path.GetFileNameWithoutExtension(_pathSelection); private void BtnSelectUserFilter_Click(object sender, EventArgs e) { - var result = this.ShowFileOpenDialog( + string result = this.ShowFileOpenDialog( filter: CgShaderPresetsFSFilterSet, initDir: string.IsNullOrWhiteSpace(_pathSelection) ? string.Empty : Path.GetDirectoryName(_pathSelection)!, @@ -277,26 +274,26 @@ private void BtnSelectUserFilter_Click(object sender, EventArgs e) if (result is null) return; rbUser.Checked = true; - var choice = Path.GetFullPath(result); + string choice = Path.GetFullPath(result); //test the preset using (var stream = File.OpenRead(choice)) { - var cgp = new RetroShaderPreset(stream); + RetroShaderPreset cgp = new(stream); // try compiling it bool ok = false; string errors = ""; try { - var filter = new RetroShaderChain(_gl, cgp, Path.GetDirectoryName(choice)); + RetroShaderChain filter = new(_gl, cgp, Path.GetDirectoryName(choice)); ok = filter.Available; errors = filter.Errors; } catch {} if (!ok) { - using var errorForm = new ExceptionBox(errors); + using ExceptionBox errorForm = new(errors); this.ShowDialogAsChild(errorForm); return; } @@ -306,25 +303,13 @@ private void BtnSelectUserFilter_Click(object sender, EventArgs e) RefreshState(); } - private void CheckLetterbox_CheckedChanged(object sender, EventArgs e) - { - RefreshAspectRatioOptions(); - } + private void CheckLetterbox_CheckedChanged(object sender, EventArgs e) => RefreshAspectRatioOptions(); - private void CheckPadInteger_CheckedChanged(object sender, EventArgs e) - { - RefreshAspectRatioOptions(); - } + private void CheckPadInteger_CheckedChanged(object sender, EventArgs e) => RefreshAspectRatioOptions(); - private void RbUseRaw_CheckedChanged(object sender, EventArgs e) - { - RefreshAspectRatioOptions(); - } + private void RbUseRaw_CheckedChanged(object sender, EventArgs e) => RefreshAspectRatioOptions(); - private void RbUseSystem_CheckedChanged(object sender, EventArgs e) - { - RefreshAspectRatioOptions(); - } + private void RbUseSystem_CheckedChanged(object sender, EventArgs e) => RefreshAspectRatioOptions(); private void RefreshAspectRatioOptions() { @@ -338,10 +323,7 @@ public void TbScanlineIntensity_Scroll(object sender, EventArgs e) lblScanlines.Text = $"{_config.TargetScanlineFilterIntensity / 256.0:P2}"; } - private void TrackBarFrameSizeWindowed_ValueChanged(object sender, EventArgs e) - { - SyncTrackBar(); - } + private void TrackBarFrameSizeWindowed_ValueChanged(object sender, EventArgs e) => SyncTrackBar(); private void SyncTrackBar() { @@ -361,15 +343,9 @@ private void SyncTrackBar() } } - private void LinkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) - { - System.Diagnostics.Process.Start("https://tasvideos.org/Bizhawk/DisplayConfig"); - } + private void LinkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) => System.Diagnostics.Process.Start("https://tasvideos.org/Bizhawk/DisplayConfig"); - private void Label13_Click(object sender, EventArgs e) - { - cbAlternateVsync.Checked ^= true; - } + private void Label13_Click(object sender, EventArgs e) => cbAlternateVsync.Checked ^= true; private void BtnDefaults_Click(object sender, EventArgs e) { diff --git a/src/BizHawk.Client.EmuHawk/config/EmuHawkOptions.cs b/src/BizHawk.Client.EmuHawk/config/EmuHawkOptions.cs index 6a8a67db3ea..32b6a04f5cd 100755 --- a/src/BizHawk.Client.EmuHawk/config/EmuHawkOptions.cs +++ b/src/BizHawk.Client.EmuHawk/config/EmuHawkOptions.cs @@ -100,7 +100,7 @@ private void OkBtn_Click(object sender, EventArgs e) { if (cbMergeLAndRModifierKeys.Checked != _config.MergeLAndRModifierKeys) { - var merging = cbMergeLAndRModifierKeys.Checked; + bool merging = cbMergeLAndRModifierKeys.Checked; var result = MessageBox.Show( this, text: $"Would you like to replace {(merging ? "LShift and RShift with Shift" : "Shift with LShift")},\nand the same for the other modifier keys,\nin existing keybinds for hotkeys and all systems' gamepads?", @@ -146,19 +146,10 @@ private void CancelBtn_Click(object sender, EventArgs e) DialogResult = DialogResult.Cancel; } - private void AcceptBackgroundInputCheckbox_CheckedChanged(object sender, EventArgs e) - { - AcceptBackgroundInputControllerOnlyCheckBox.Enabled = AcceptBackgroundInputCheckbox.Checked; - } + private void AcceptBackgroundInputCheckbox_CheckedChanged(object sender, EventArgs e) => AcceptBackgroundInputControllerOnlyCheckBox.Enabled = AcceptBackgroundInputCheckbox.Checked; - private void AutosaveSRAMCheckbox_CheckedChanged(object sender, EventArgs e) - { - groupBox2.Enabled = AutosaveSRAMCheckbox.Checked; - } + private void AutosaveSRAMCheckbox_CheckedChanged(object sender, EventArgs e) => groupBox2.Enabled = AutosaveSRAMCheckbox.Checked; - private void AutosaveSRAMRadioButton3_CheckedChanged(object sender, EventArgs e) - { - AutosaveSRAMtextBox.Enabled = AutosaveSRAMradioButton3.Checked; - } + private void AutosaveSRAMRadioButton3_CheckedChanged(object sender, EventArgs e) => AutosaveSRAMtextBox.Enabled = AutosaveSRAMradioButton3.Checked; } } diff --git a/src/BizHawk.Client.EmuHawk/config/FileExtensionPreferences.cs b/src/BizHawk.Client.EmuHawk/config/FileExtensionPreferences.cs index 6246efb6b8a..8d4f0e3434d 100644 --- a/src/BizHawk.Client.EmuHawk/config/FileExtensionPreferences.cs +++ b/src/BizHawk.Client.EmuHawk/config/FileExtensionPreferences.cs @@ -24,7 +24,7 @@ private void FileExtensionPreferences_Load(object sender, EventArgs e) int count = 0; foreach (var (fileExt, sysID) in _preferredPlatformsForExtensions) { - var picker = new FileExtensionPreferencesPicker(_preferredPlatformsForExtensions) + FileExtensionPreferencesPicker picker = new(_preferredPlatformsForExtensions) { FileExtension = fileExt, OriginalPreference = sysID, @@ -47,9 +47,6 @@ private void OkBtn_Click(object sender, EventArgs e) Close(); } - private void CancelBtn_Click(object sender, EventArgs e) - { - Close(); - } + private void CancelBtn_Click(object sender, EventArgs e) => Close(); } } diff --git a/src/BizHawk.Client.EmuHawk/config/FileExtensionPreferencesPicker.cs b/src/BizHawk.Client.EmuHawk/config/FileExtensionPreferencesPicker.cs index e35051e7637..8bf3e71d906 100644 --- a/src/BizHawk.Client.EmuHawk/config/FileExtensionPreferencesPicker.cs +++ b/src/BizHawk.Client.EmuHawk/config/FileExtensionPreferencesPicker.cs @@ -50,10 +50,10 @@ private void FileExtensionPreferencesPicker_Load(object sender, EventArgs e) { PopulatePlatforms(); - var selectedSystemId = _preferredPlatformsForExtensions[FileExtension]; + string selectedSystemId = _preferredPlatformsForExtensions[FileExtension]; if (!string.IsNullOrEmpty(selectedSystemId)) { - var selectedSystem = _availableSystems.Find(s => s.SystemId == selectedSystemId)?.FullName ?? string.Empty; + string selectedSystem = _availableSystems.Find(s => s.SystemId == selectedSystemId)?.FullName ?? string.Empty; if (PlatformDropdown.Items.Contains(selectedSystem)) { PlatformDropdown.SelectedItem = selectedSystem; diff --git a/src/BizHawk.Client.EmuHawk/config/FirmwaresConfig.cs b/src/BizHawk.Client.EmuHawk/config/FirmwaresConfig.cs index bc08aed90fc..2832165cce3 100644 --- a/src/BizHawk.Client.EmuHawk/config/FirmwaresConfig.cs +++ b/src/BizHawk.Client.EmuHawk/config/FirmwaresConfig.cs @@ -60,7 +60,7 @@ public partial class FirmwaresConfig : Form, IDialogParent // friendlier names than the system Ids // Redundant with SystemLookup? Not so fast. That data drives things. This is one step abstracted. Don't be such a smart guy. Keep this redundant list up to date. - private static readonly Dictionary SystemGroupNames = new Dictionary + private static readonly Dictionary SystemGroupNames = new() { ["NES"] = "NES", ["SNES"] = "SNES", @@ -111,8 +111,8 @@ public ListViewSorter(int column) public int Compare(object a, object b) { - var lva = (ListViewItem)a; - var lvb = (ListViewItem)b; + ListViewItem lva = (ListViewItem)a; + ListViewItem lvb = (ListViewItem)b; return Sign * string.CompareOrdinal(lva.SubItems[Column].Text, lvb.SubItems[Column].Text); } } @@ -182,7 +182,7 @@ ListViewGroup AddGroup(string sysID) { lvFirmwares.Groups.Add( key: sysID, - headerText: SystemGroupNames.TryGetValue(sysID, out var name) ? name : "FIX ME (FirmwaresConfig.cs)"); + headerText: SystemGroupNames.TryGetValue(sysID, out string name) ? name : "FIX ME (FirmwaresConfig.cs)"); return lvFirmwares.Groups[^1]; } @@ -192,11 +192,11 @@ ListViewGroup AddGroup(string sysID) _boldFixedFont = new Font(_fixedFont, FontStyle.Bold); // populate ListView from firmware DB - var groups = new Dictionary(); + Dictionary groups = new(); foreach (var fr in FirmwareDatabase.FirmwareRecords) { - var sysID = fr.ID.System; - var lvi = new ListViewItem + string sysID = fr.ID.System; + ListViewItem lvi = new() { Tag = fr, UseItemStyleForSubItems = false, @@ -228,7 +228,7 @@ ListViewGroup AddGroup(string sysID) WarpToSystemId(TargetSystem); } - var oldBasePath = _currSelectorDir; + string oldBasePath = _currSelectorDir; linkBasePath.Text = _currSelectorDir = _pathEntries.FirmwareAbsolutePath(); if (_currSelectorDir != oldBasePath) DoScan(); } @@ -252,11 +252,9 @@ private void FirmwaresConfig_FormClosed(object sender, FormClosedEventArgs e) _boldFixedFont.Dispose(); } - private void TbbGroup_Click(object sender, EventArgs e) - { + private void TbbGroup_Click(object sender, EventArgs e) => // toggle the grouping state lvFirmwares.ShowGroups = !lvFirmwares.ShowGroups; - } private void LvFirmwares_ColumnClick(object sender, ColumnClickEventArgs e) { @@ -271,11 +269,9 @@ private void LvFirmwares_ColumnClick(object sender, ColumnClickEventArgs e) lvFirmwares.Sort(); } - private void TbbScan_Click(object sender, EventArgs e) - { + private void TbbScan_Click(object sender, EventArgs e) => // user-initiated scan DoScan(); - } private void DoScan() { @@ -287,7 +283,7 @@ private void DoScan() // for each type of firmware, try resolving and record the result foreach (ListViewItem lvi in lvFirmwares.Items) { - var fr = (FirmwareRecord) lvi.Tag; + FirmwareRecord fr = (FirmwareRecord) lvi.Tag; var ri = Manager.Resolve( _pathEntries, _firmwareUserSpecifications, @@ -307,15 +303,15 @@ private void DoScan() else { // lazy substring extraction. really should do a better job - var basePath = _pathEntries.FirmwareAbsolutePath() + Path.DirectorySeparatorChar; - - var path = ri.FilePath.Replace(basePath, ""); + string basePath = _pathEntries.FirmwareAbsolutePath() + Path.DirectorySeparatorChar; + + string path = ri.FilePath.Replace(basePath, ""); // bolden the item if the user has specified a path for it bool bolden = ri.UserSpecified; // set columns based on whether it was a known file - var hash = ri.KnownFirmwareFile?.Hash; + string hash = ri.KnownFirmwareFile?.Hash; if (hash == null) { lvi.ImageIndex = (int) FirmwareOptionStatus.Unknown; @@ -387,7 +383,7 @@ private void TbbOrganize_Click(object sender, EventArgs e) if (ri?.KnownFirmwareFile == null) continue; if (ri.UserSpecified) continue; - var fpTarget = Path.Combine(_pathEntries.FirmwareAbsolutePath(), ri.KnownFirmwareFile.Value.RecommendedName); + string fpTarget = Path.Combine(_pathEntries.FirmwareAbsolutePath(), ri.KnownFirmwareFile.Value.RecommendedName); string fpSource = ri.FilePath; try @@ -406,7 +402,7 @@ private void TbbOrganize_Click(object sender, EventArgs e) private void TbbOpenFolder_Click(object sender, EventArgs e) { - var frmWares = _pathEntries.FirmwareAbsolutePath(); + string frmWares = _pathEntries.FirmwareAbsolutePath(); Directory.CreateDirectory(frmWares); System.Diagnostics.Process.Start(frmWares); } @@ -421,7 +417,7 @@ private void LvFirmwares_KeyDown(object sender, KeyEventArgs e) private void PerformListCopy() { - var str = lvFirmwares.CopyItemsAsText(); + string str = lvFirmwares.CopyItemsAsText(); if (str.Length > 0) Clipboard.SetDataObject(str); } @@ -433,7 +429,7 @@ private void LvFirmwares_MouseClick(object sender, MouseEventArgs e) private void TsmiSetCustomization_Click(object sender, EventArgs e) { - var result = this.ShowFileOpenDialog( + string result = this.ShowFileOpenDialog( discardCWDChange: true, initDir: _currSelectorDir); if (result is null) return; @@ -449,18 +445,18 @@ private void TsmiSetCustomization_Click(object sender, EventArgs e) // for each selected item, set the user choice (even though multiple selection for this operation is no longer allowed) foreach (ListViewItem lvi in lvFirmwares.SelectedItems) { - var fr = (FirmwareRecord) lvi.Tag; - var filePath = result; + FirmwareRecord fr = (FirmwareRecord) lvi.Tag; + string filePath = result; // if the selected file is an archive, allow the user to pick the inside file // to always be copied to the global firmwares directory if (hf.IsArchive) { - var ac = new ArchiveChooser(new HawkFile(filePath)); + ArchiveChooser ac = new(new HawkFile(filePath)); if (!ac.ShowDialog(this).IsOk()) return; var insideFile = hf.BindArchiveMember(ac.SelectedMemberIndex); - var fileData = insideFile.ReadAllBytes(); + byte[] fileData = insideFile.ReadAllBytes(); // write to file in the firmwares folder File.WriteAllBytes(Path.Combine(firmwarePath, insideFile.Name), fileData); @@ -472,12 +468,12 @@ private void TsmiSetCustomization_Click(object sender, EventArgs e) // check whether this file is currently outside of the global firmware directory if (_currSelectorDir != firmwarePath) { - var askMoveResult = this.ModalMessageBox2("The selected custom firmware does not reside in the root of the global firmware directory.\nDo you want to copy it there?", "Import Custom Firmware"); + bool askMoveResult = this.ModalMessageBox2("The selected custom firmware does not reside in the root of the global firmware directory.\nDo you want to copy it there?", "Import Custom Firmware"); if (askMoveResult) { try { - var fi = new FileInfo(filePath); + FileInfo fi = new(filePath); filePath = Path.Combine(firmwarePath, fi.Name); File.Copy(result, filePath); } @@ -507,7 +503,7 @@ private void TsmiClearCustomization_Click(object sender, EventArgs e) // for each selected item, clear the user choice foreach (ListViewItem lvi in lvFirmwares.SelectedItems) { - var fr = (FirmwareRecord) lvi.Tag; + FirmwareRecord fr = (FirmwareRecord) lvi.Tag; _firmwareUserSpecifications.Remove(fr.ID.ConfigKey); } @@ -517,12 +513,12 @@ private void TsmiClearCustomization_Click(object sender, EventArgs e) private void TsmiInfo_Click(object sender, EventArgs e) { var lvi = lvFirmwares.SelectedItems[0]; - var fr = (FirmwareRecord) lvi.Tag; + FirmwareRecord fr = (FirmwareRecord) lvi.Tag; // get all options for this firmware (in order) var options = FirmwareDatabase.FirmwareOptions.Where(fo => fo.ID == fr.ID); - var fciDialog = new FirmwaresConfigInfo + FirmwaresConfigInfo fciDialog = new() { lblFirmware = { @@ -532,7 +528,7 @@ private void TsmiInfo_Click(object sender, EventArgs e) foreach (var o in options) { - ListViewItem olvi = new ListViewItem(); + ListViewItem olvi = new(); olvi.SubItems.Add(new ListViewItem.ListViewSubItem()); olvi.SubItems.Add(new ListViewItem.ListViewSubItem()); olvi.SubItems.Add(new ListViewItem.ListViewSubItem()); @@ -568,10 +564,7 @@ private void LvFirmwaresContextMenuStrip_Opening(object sender, CancelEventArgs tsmiInfo.Visible = lvFirmwares.SelectedItems.Count == 1; } - private void TsmiCopy_Click(object sender, EventArgs e) - { - PerformListCopy(); - } + private void TsmiCopy_Click(object sender, EventArgs e) => PerformListCopy(); private void TbbImport_Click(object sender, EventArgs e) { @@ -583,7 +576,7 @@ private bool RunImportJobSingle(string basePath, string f, ref string errors) { try { - var fi = new FileInfo(f); + FileInfo fi = new(f); if (!fi.Exists) { return false; @@ -622,11 +615,11 @@ private bool RunImportJobSingle(string basePath, string f, ref string errors) private void RunImportJob(IEnumerable files) { bool didSomething = false; - var basePath = _pathEntries.FirmwareAbsolutePath(); + string basePath = _pathEntries.FirmwareAbsolutePath(); string errors = ""; - foreach(var f in files) + foreach(string f in files) { - using var hf = new HawkFile(f); + using HawkFile hf = new(f); if (hf.IsArchive) { // blech. the worst extraction code in the universe. @@ -686,10 +679,7 @@ protected override bool ProcessCmdKey(ref Message msg, Keys keyData) return base.ProcessCmdKey(ref msg, keyData); } - private void LvFirmwares_DragEnter(object sender, DragEventArgs e) - { - e.Set(DragDropEffects.Copy); - } + private void LvFirmwares_DragEnter(object sender, DragEventArgs e) => e.Set(DragDropEffects.Copy); private void LvFirmwares_DragDrop(object sender, DragEventArgs e) { diff --git a/src/BizHawk.Client.EmuHawk/config/FirmwaresConfigInfo.cs b/src/BizHawk.Client.EmuHawk/config/FirmwaresConfigInfo.cs index 12708df3325..8585acdd207 100644 --- a/src/BizHawk.Client.EmuHawk/config/FirmwaresConfigInfo.cs +++ b/src/BizHawk.Client.EmuHawk/config/FirmwaresConfigInfo.cs @@ -27,14 +27,11 @@ private void LvOptions_KeyDown(object sender, KeyEventArgs e) private void PerformListCopy() { - var str = lvOptions.CopyItemsAsText(); + string str = lvOptions.CopyItemsAsText(); if (str.Length > 0) Clipboard.SetDataObject(str); } - private void TsmiOptionsCopy_Click(object sender, EventArgs e) - { - PerformListCopy(); - } + private void TsmiOptionsCopy_Click(object sender, EventArgs e) => PerformListCopy(); private void LvOptions_MouseClick(object sender, MouseEventArgs e) { diff --git a/src/BizHawk.Client.EmuHawk/config/GB/BmpView.cs b/src/BizHawk.Client.EmuHawk/config/GB/BmpView.cs index 5abe2db2665..056b9bfb02f 100644 --- a/src/BizHawk.Client.EmuHawk/config/GB/BmpView.cs +++ b/src/BizHawk.Client.EmuHawk/config/GB/BmpView.cs @@ -23,7 +23,7 @@ protected override void ScaleControl(SizeF factor, BoundsSpecified specified) x = (int)(x * factor.Width); if (specified.HasFlag(BoundsSpecified.Y)) y = (int)(y * factor.Height); - var pt = new Point(x, y); + Point pt = new(x, y); if (pt != Location) Location = pt; } @@ -48,10 +48,7 @@ public BmpView() } } - private void BmpView_SizeChanged(object sender, EventArgs e) - { - _scaled = !(Bmp.Width == Width && Bmp.Height == Height); - } + private void BmpView_SizeChanged(object sender, EventArgs e) => _scaled = !(Bmp.Width == Width && Bmp.Height == Height); private void BmpView_Paint(object sender, PaintEventArgs e) { diff --git a/src/BizHawk.Client.EmuHawk/config/GB/CGBColorChooserForm.cs b/src/BizHawk.Client.EmuHawk/config/GB/CGBColorChooserForm.cs index 58fba344835..58d986031a5 100644 --- a/src/BizHawk.Client.EmuHawk/config/GB/CGBColorChooserForm.cs +++ b/src/BizHawk.Client.EmuHawk/config/GB/CGBColorChooserForm.cs @@ -127,7 +127,7 @@ private void RadioButton1_CheckedChanged(object sender, EventArgs e) public static void DoCGBColorChooserFormDialog(IDialogParent parent, Gameboy.GambatteSettings s) { - using var dlg = new CGBColorChooserForm(); + using CGBColorChooserForm dlg = new(); dlg.LoadType(s); if (!parent.ShowDialogAsChild(dlg).IsOk()) return; s.CGBColors = dlg._type; diff --git a/src/BizHawk.Client.EmuHawk/config/GB/ColorChooserForm.cs b/src/BizHawk.Client.EmuHawk/config/GB/ColorChooserForm.cs index 4be0c56dd7a..3719c905eeb 100644 --- a/src/BizHawk.Client.EmuHawk/config/GB/ColorChooserForm.cs +++ b/src/BizHawk.Client.EmuHawk/config/GB/ColorChooserForm.cs @@ -81,20 +81,11 @@ private void InterpolateColors(int firstIndex, int lastIndex) RefreshAllBackdrops(); } - private void Button3_Click(object sender, EventArgs e) - { - InterpolateColors(0, 3); - } + private void Button3_Click(object sender, EventArgs e) => InterpolateColors(0, 3); - private void Button4_Click(object sender, EventArgs e) - { - InterpolateColors(4, 7); - } + private void Button4_Click(object sender, EventArgs e) => InterpolateColors(4, 7); - private void Button5_Click(object sender, EventArgs e) - { - InterpolateColors(8, 11); - } + private void Button5_Click(object sender, EventArgs e) => InterpolateColors(8, 11); private void Panel12_DoubleClick(object sender, EventArgs e) { @@ -128,7 +119,7 @@ private void Panel12_DoubleClick(object sender, EventArgs e) else return; // i = -1; - using var dlg = new ColorDialog + using ColorDialog dlg = new() { AllowFullOpen = true, AnyColor = true, @@ -179,7 +170,7 @@ private void Panel12_DoubleClick(object sender, EventArgs e) /// null on failure public static int[] LoadPalFile(TextReader f) { - var lines = new Dictionary(); + Dictionary lines = new(); string line; while ((line = f.ReadLine()) != null) @@ -238,7 +229,7 @@ private void SetAllColors(int[] colors) public static void DoColorChooserFormDialog(IDialogParent parent, Config config, IGameInfo game, Gameboy.GambatteSettings s) { - using var dlg = new ColorChooserForm(parent.DialogController, config, game); + using ColorChooserForm dlg = new(parent.DialogController, config, game); dlg.SetAllColors(s.GBPalette); @@ -259,13 +250,8 @@ private void LoadColorFile(string filename, bool alert) { try { - using var f = new StreamReader(filename); - int[] newColors = LoadPalFile(f); - if (newColors == null) - { - throw new Exception(); - } - + using StreamReader f = new(filename); + int[] newColors = LoadPalFile(f) ?? throw new Exception(); SetAllColors(newColors); } catch @@ -281,7 +267,7 @@ private void SaveColorFile(string filename) { try { - using var f = new StreamWriter(filename); + using StreamWriter f = new(filename); int[] saveColors = new int[12]; for (int i = 0; i < 12; i++) { @@ -299,7 +285,7 @@ private void SaveColorFile(string filename) private void Button6_Click(object sender, EventArgs e) { - var result = this.ShowFileOpenDialog( + string result = this.ShowFileOpenDialog( discardCWDChange: true, filter: FilesystemFilterSet.Palettes, initDir: _config.PathEntries.ScreenshotAbsolutePathFor(VSystemID.Raw.GB)); @@ -310,7 +296,7 @@ private void ColorChooserForm_DragDrop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { - var files = (string[])e.Data.GetData(DataFormats.FileDrop); + string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); if (files.Length > 1) { @@ -321,14 +307,11 @@ private void ColorChooserForm_DragDrop(object sender, DragEventArgs e) } } - private void ColorChooserForm_DragEnter(object sender, DragEventArgs e) - { - e.Set(DragDropEffects.Move); - } + private void ColorChooserForm_DragEnter(object sender, DragEventArgs e) => e.Set(DragDropEffects.Move); private void Button7_Click(object sender, EventArgs e) { - var result = this.ShowFileSaveDialog( + string result = this.ShowFileSaveDialog( discardCWDChange: true, filter: FilesystemFilterSet.Palettes, initDir: _config.PathEntries.PalettesAbsolutePathFor(VSystemID.Raw.GB), @@ -336,14 +319,8 @@ private void Button7_Click(object sender, EventArgs e) if (result is not null) SaveColorFile(result); } - private void DefaultButton_Click(object sender, EventArgs e) - { - SetAllColors(DefaultDMGColors); - } + private void DefaultButton_Click(object sender, EventArgs e) => SetAllColors(DefaultDMGColors); - private void DefaultButtonCGB_Click(object sender, EventArgs e) - { - SetAllColors(DefaultCGBColors); - } + private void DefaultButtonCGB_Click(object sender, EventArgs e) => SetAllColors(DefaultCGBColors); } } diff --git a/src/BizHawk.Client.EmuHawk/config/GB/GBLPrefs.cs b/src/BizHawk.Client.EmuHawk/config/GB/GBLPrefs.cs index 6fc315e3bbe..66aa15ca5bd 100644 --- a/src/BizHawk.Client.EmuHawk/config/GB/GBLPrefs.cs +++ b/src/BizHawk.Client.EmuHawk/config/GB/GBLPrefs.cs @@ -55,10 +55,10 @@ public static DialogResult DoGBLPrefsDialog( IMovieSession movieSession, ISettingsAdapter settable) { - var s = (GambatteLink.GambatteLinkSettings) settable.GetSettings(); - var ss = (GambatteLink.GambatteLinkSyncSettings) settable.GetSyncSettings(); + GambatteLink.GambatteLinkSettings s = (GambatteLink.GambatteLinkSettings) settable.GetSettings(); + GambatteLink.GambatteLinkSyncSettings ss = (GambatteLink.GambatteLinkSyncSettings) settable.GetSyncSettings(); - using var dlg = new GBLPrefs(dialogParent.DialogController, config, game, movieSession); + using GBLPrefs dlg = new(dialogParent.DialogController, config, game, movieSession); dlg.PutSettings(s, ss); var result = dialogParent.ShowDialogAsChild(dlg); diff --git a/src/BizHawk.Client.EmuHawk/config/GB/GBPrefControl.cs b/src/BizHawk.Client.EmuHawk/config/GB/GBPrefControl.cs index e0989109ffa..9997dd5730e 100644 --- a/src/BizHawk.Client.EmuHawk/config/GB/GBPrefControl.cs +++ b/src/BizHawk.Client.EmuHawk/config/GB/GBPrefControl.cs @@ -58,34 +58,16 @@ private void ButtonDefaults_Click(object sender, EventArgs e) } } - private void ButtonGbPalette_Click(object sender, EventArgs e) - { - ColorChooserForm.DoColorChooserFormDialog(DialogParent, _config, _game, _s); - } + private void ButtonGbPalette_Click(object sender, EventArgs e) => ColorChooserForm.DoColorChooserFormDialog(DialogParent, _config, _game, _s); - private void ButtonGbcPalette_Click(object sender, EventArgs e) - { - CGBColorChooserForm.DoCGBColorChooserFormDialog(DialogParent, _s); - } + private void ButtonGbcPalette_Click(object sender, EventArgs e) => CGBColorChooserForm.DoCGBColorChooserFormDialog(DialogParent, _s); - private void PropertyGrid1_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) - { - SyncSettingsChanged = true; - } + private void PropertyGrid1_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) => SyncSettingsChanged = true; - private void CheckBoxMuted_CheckedChanged(object sender, EventArgs e) - { - _s.Muted = ((CheckBox)sender).Checked; - } - - private void CbRgbdsSyntax_CheckedChanged(object sender, EventArgs e) - { - _s.RgbdsSyntax = ((CheckBox)sender).Checked; - } + private void CheckBoxMuted_CheckedChanged(object sender, EventArgs e) => _s.Muted = ((CheckBox)sender).Checked; - private void CbShowBorder_CheckedChanged(object sender, EventArgs e) - { - _s.ShowBorder = ((CheckBox)sender).Checked; - } + private void CbRgbdsSyntax_CheckedChanged(object sender, EventArgs e) => _s.RgbdsSyntax = ((CheckBox)sender).Checked; + + private void CbShowBorder_CheckedChanged(object sender, EventArgs e) => _s.ShowBorder = ((CheckBox)sender).Checked; } } diff --git a/src/BizHawk.Client.EmuHawk/config/GB/GBPrefs.cs b/src/BizHawk.Client.EmuHawk/config/GB/GBPrefs.cs index d29ffd71b8f..6f24ad860ab 100644 --- a/src/BizHawk.Client.EmuHawk/config/GB/GBPrefs.cs +++ b/src/BizHawk.Client.EmuHawk/config/GB/GBPrefs.cs @@ -24,10 +24,10 @@ public static DialogResult DoGBPrefsDialog( IMovieSession movieSession, ISettingsAdapter settable) { - var s = (Gameboy.GambatteSettings) settable.GetSettings(); - var ss = (Gameboy.GambatteSyncSettings) settable.GetSyncSettings(); + Gameboy.GambatteSettings s = (Gameboy.GambatteSettings) settable.GetSettings(); + Gameboy.GambatteSyncSettings ss = (Gameboy.GambatteSyncSettings) settable.GetSyncSettings(); - using var dlg = new GBPrefs(dialogParent.DialogController); + using GBPrefs dlg = new(dialogParent.DialogController); dlg.gbPrefControl1.PutSettings(config, game, movieSession, s, ss); var result = dialogParent.ShowDialogAsChild(dlg); if (result.IsOk()) diff --git a/src/BizHawk.Client.EmuHawk/config/GB/SameBoyColorChooserForm.cs b/src/BizHawk.Client.EmuHawk/config/GB/SameBoyColorChooserForm.cs index 7f9c775af98..20a0140e52a 100644 --- a/src/BizHawk.Client.EmuHawk/config/GB/SameBoyColorChooserForm.cs +++ b/src/BizHawk.Client.EmuHawk/config/GB/SameBoyColorChooserForm.cs @@ -68,10 +68,7 @@ private void InterpolateColors(int firstIndex, int lastIndex) RefreshAllBackdrops(); } - private void Button3_Click(object sender, EventArgs e) - { - InterpolateColors(0, 3); // todo: interpolate disabled color - } + private void Button3_Click(object sender, EventArgs e) => InterpolateColors(0, 3); // todo: interpolate disabled color private void Panel12_DoubleClick(object sender, EventArgs e) { @@ -91,7 +88,7 @@ private void Panel12_DoubleClick(object sender, EventArgs e) else return; // i = -1; - using var dlg = new ColorDialog + using ColorDialog dlg = new() { AllowFullOpen = true, AnyColor = true, @@ -149,7 +146,7 @@ private void Panel12_DoubleClick(object sender, EventArgs e) /// null on failure public static int[] LoadPalFile(TextReader f) { - var lines = new Dictionary(); + Dictionary lines = new(); string line; while ((line = f.ReadLine()) != null) @@ -221,13 +218,8 @@ private void LoadColorFile(string filename, bool alert) { try { - using var f = new StreamReader(filename); - int[] newColors = LoadPalFile(f); - if (newColors == null) - { - throw new Exception(); - } - + using StreamReader f = new(filename); + int[] newColors = LoadPalFile(f) ?? throw new Exception(); SetAllColors(newColors); } catch @@ -243,7 +235,7 @@ private void SaveColorFile(string filename) { try { - using var f = new StreamWriter(filename); + using StreamWriter f = new(filename); int[] saveColors = new int[5]; for (int i = 0; i < 5; i++) { @@ -261,7 +253,7 @@ private void SaveColorFile(string filename) private void Button6_Click(object sender, EventArgs e) { - var result = this.ShowFileOpenDialog( + string result = this.ShowFileOpenDialog( discardCWDChange: true, filter: FilesystemFilterSet.Palettes, initDir: _config.PathEntries.ScreenshotAbsolutePathFor(VSystemID.Raw.GB)); @@ -272,7 +264,7 @@ private void ColorChooserForm_DragDrop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { - var files = (string[])e.Data.GetData(DataFormats.FileDrop); + string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); if (files.Length > 1) { @@ -283,14 +275,11 @@ private void ColorChooserForm_DragDrop(object sender, DragEventArgs e) } } - private void ColorChooserForm_DragEnter(object sender, DragEventArgs e) - { - e.Set(DragDropEffects.Move); - } + private void ColorChooserForm_DragEnter(object sender, DragEventArgs e) => e.Set(DragDropEffects.Move); private void Button7_Click(object sender, EventArgs e) { - var result = this.ShowFileSaveDialog( + string result = this.ShowFileSaveDialog( discardCWDChange: true, filter: FilesystemFilterSet.Palettes, initDir: _config.PathEntries.PalettesAbsolutePathFor(VSystemID.Raw.GB), diff --git a/src/BizHawk.Client.EmuHawk/config/GenericCoreConfig.cs b/src/BizHawk.Client.EmuHawk/config/GenericCoreConfig.cs index e86eb9f7f83..181c41a3036 100644 --- a/src/BizHawk.Client.EmuHawk/config/GenericCoreConfig.cs +++ b/src/BizHawk.Client.EmuHawk/config/GenericCoreConfig.cs @@ -75,7 +75,7 @@ public static DialogResult DoNymaDialogFor( public static void DoDialog(IEmulator emulator, IDialogParent owner, bool isMovieActive) { var settable = ((MainForm) owner).GetSettingsAdapterForLoadedCoreUntyped(); //HACK - var title = $"{emulator.Attributes().CoreName} Settings"; + string title = $"{emulator.Attributes().CoreName} Settings"; _ = emulator switch { MAME mame => DoMAMEDialog(owner, settable, mame.CurrentDriverSettings, isMovieActive: isMovieActive), @@ -147,10 +147,7 @@ private void OkBtn_Click(object sender, EventArgs e) Close(); } - private void PropertyGrid2_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) - { - _syncSettingsChanged = true; - } + private void PropertyGrid2_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) => _syncSettingsChanged = true; private void DefaultsBtn_Click(object sender, EventArgs e) { @@ -170,9 +167,6 @@ private void DefaultsBtn_Click(object sender, EventArgs e) } } - private void propertyGrid1_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) - { - _settingsChanged = true; - } + private void propertyGrid1_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) => _settingsChanged = true; } } diff --git a/src/BizHawk.Client.EmuHawk/config/HotkeyConfig.cs b/src/BizHawk.Client.EmuHawk/config/HotkeyConfig.cs index 3ea5af69f53..a2b3fb7676d 100644 --- a/src/BizHawk.Client.EmuHawk/config/HotkeyConfig.cs +++ b/src/BizHawk.Client.EmuHawk/config/HotkeyConfig.cs @@ -36,7 +36,7 @@ protected override void OnDeactivate(EventArgs e) private void HotkeyConfig_Load(object sender, EventArgs e) { - var source = new AutoCompleteStringCollection(); + AutoCompleteStringCollection source = new(); source.AddRange(HotkeyInfo.AllHotkeys.Keys.ToArray()); SearchBox.AutoCompleteCustomSource = source; @@ -47,15 +47,9 @@ private void HotkeyConfig_Load(object sender, EventArgs e) DoFocus(); } - private void HotkeyConfig_FormClosed(object sender, FormClosedEventArgs e) - { - Input.Instance.ClearEvents(); - } + private void HotkeyConfig_FormClosed(object sender, FormClosedEventArgs e) => Input.Instance.ClearEvents(); - private void IDB_CANCEL_Click(object sender, EventArgs e) - { - Close(); - } + private void IDB_CANCEL_Click(object sender, EventArgs e) => Close(); private void IDB_SAVE_Click(object sender, EventArgs e) { @@ -64,10 +58,7 @@ private void IDB_SAVE_Click(object sender, EventArgs e) Close(); } - private void AutoTabCheckBox_CheckedChanged(object sender, EventArgs e) - { - SetAutoTab(); - } + private void AutoTabCheckBox_CheckedChanged(object sender, EventArgs e) => SetAutoTab(); private void Save() { @@ -83,14 +74,14 @@ private void DoTabs() HotkeyTabControl.SuspendLayout(); HotkeyTabControl.TabPages.Clear(); - foreach (var tab in HotkeyInfo.Groupings) + foreach (string tab in HotkeyInfo.Groupings) { if (tab == "RAIntegration" && !RAIntegration.IsAvailable) { continue; // skip RA hotkeys if it can't be used } - var tb = new TabPage { Name = tab, Text = tab }; + TabPage tb = new() { Name = tab, Text = tab }; var bindings = HotkeyInfo.AllHotkeys.Where(kvp => kvp.Value.TabGroup == tab) .OrderBy(static kvp => kvp.Value.Ordinal).ThenBy(static kvp => kvp.Value.DisplayName); int x = UIHelper.ScaleX(6); @@ -103,14 +94,14 @@ private void DoTabs() foreach (var (k, b) in bindings) { - var l = new Label + Label l = new() { Text = b.DisplayName, Location = new Point(x, y), Size = new Size(iwOffsetX - UIHelper.ScaleX(2), UIHelper.ScaleY(15)) }; - var w = new InputCompositeWidget(_config.ModifierKeysEffective) + InputCompositeWidget w = new(_config.ModifierKeysEffective) { Location = new Point(x + iwOffsetX, y + iwOffsetY), AutoTab = AutoTabCheckBox.Checked, @@ -182,10 +173,7 @@ private void SetAutoTab() } } - private void HotkeyTabControl_SelectedIndexChanged(object sender, EventArgs e) - { - DoFocus(); - } + private void HotkeyTabControl_SelectedIndexChanged(object sender, EventArgs e) => DoFocus(); private void DoFocus() { @@ -203,7 +191,7 @@ private void SearchBox_KeyDown(object sender, KeyEventArgs e) { if (e.IsPressed(Keys.Enter) || e.IsPressed(Keys.Tab)) { - var k = HotkeyInfo.AllHotkeys.FirstOrNull(kvp => string.Compare(kvp.Value.DisplayName, SearchBox.Text, StringComparison.OrdinalIgnoreCase) is 0)?.Key; + string k = HotkeyInfo.AllHotkeys.FirstOrNull(kvp => string.Compare(kvp.Value.DisplayName, SearchBox.Text, StringComparison.OrdinalIgnoreCase) is 0)?.Key; // Found if (k is not null) @@ -220,19 +208,10 @@ private void SearchBox_KeyDown(object sender, KeyEventArgs e) } } - private void ClearAllToolStripMenuItem_Click(object sender, EventArgs e) - { - ClearAll(true); - } + private void ClearAllToolStripMenuItem_Click(object sender, EventArgs e) => ClearAll(true); - private void ClearCurrentTabToolStripMenuItem_Click(object sender, EventArgs e) - { - ClearAll(false); - } + private void ClearCurrentTabToolStripMenuItem_Click(object sender, EventArgs e) => ClearAll(false); - private void RestoreDefaultsToolStripMenuItem_Click(object sender, EventArgs e) - { - Defaults(); - } + private void RestoreDefaultsToolStripMenuItem_Click(object sender, EventArgs e) => Defaults(); } } diff --git a/src/BizHawk.Client.EmuHawk/config/INTV/IntvControllerSettings.cs b/src/BizHawk.Client.EmuHawk/config/INTV/IntvControllerSettings.cs index 33053418385..c6708ccc340 100644 --- a/src/BizHawk.Client.EmuHawk/config/INTV/IntvControllerSettings.cs +++ b/src/BizHawk.Client.EmuHawk/config/INTV/IntvControllerSettings.cs @@ -22,7 +22,7 @@ public IntvControllerSettings(ISettingsAdapter settable) private void IntvControllerSettings_Load(object sender, EventArgs e) { - foreach (var val in IntellivisionControllerDeck.ControllerCtors.Keys) + foreach (string val in IntellivisionControllerDeck.ControllerCtors.Keys) { Port1ComboBox.Items.Add(val); Port2ComboBox.Items.Add(val); diff --git a/src/BizHawk.Client.EmuHawk/config/InputCompositeWidget.cs b/src/BizHawk.Client.EmuHawk/config/InputCompositeWidget.cs index 0da03d1a3f9..ebdfb958dcd 100644 --- a/src/BizHawk.Client.EmuHawk/config/InputCompositeWidget.cs +++ b/src/BizHawk.Client.EmuHawk/config/InputCompositeWidget.cs @@ -22,7 +22,7 @@ public InputCompositeWidget(IReadOnlyList effectiveModList) _dropdownMenu.PreviewKeyDown += DropdownMenu_PreviewKeyDown; foreach (var spec in InputWidget.SpecialBindings) { - var tsi = new ToolStripMenuItem(spec.BindingName) { ToolTipText = spec.TooltipText }; + ToolStripMenuItem tsi = new(spec.BindingName) { ToolTipText = spec.TooltipText }; _dropdownMenu.Items.Add(tsi); } @@ -64,10 +64,7 @@ private void DropdownMenu_PreviewKeyDown(object sender, PreviewKeyDownEventArgs } } - public void TabNext() - { - Parent.SelectNextControl(btnSpecial, true, true, true, true); - } + public void TabNext() => Parent.SelectNextControl(btnSpecial, true, true, true, true); private readonly ContextMenuStrip _dropdownMenu; @@ -75,19 +72,13 @@ public void TabNext() public string WidgetName { get => widget.WidgetName; set => widget.WidgetName = value; } public string Bindings { get => widget.Bindings; set => widget.Bindings = value; } - public void Clear() - { - widget.ClearAll(); - } + public void Clear() => widget.ClearAll(); - private void BtnSpecial_Click(object sender, EventArgs e) - { - _dropdownMenu.Show(MousePosition); - } + private void BtnSpecial_Click(object sender, EventArgs e) => _dropdownMenu.Show(MousePosition); private void DropdownMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { - var mods = 0U; + uint mods = 0U; if ((ModifierKeys & Keys.Shift) != 0) { diff --git a/src/BizHawk.Client.EmuHawk/config/Messages/ColorRow.cs b/src/BizHawk.Client.EmuHawk/config/Messages/ColorRow.cs index cb393343f13..1a27d498429 100644 --- a/src/BizHawk.Client.EmuHawk/config/Messages/ColorRow.cs +++ b/src/BizHawk.Client.EmuHawk/config/Messages/ColorRow.cs @@ -36,7 +36,7 @@ private void SetColor() private void ColorPanel_Click(object sender, EventArgs e) { - using var colorPicker = new ColorDialog + using ColorDialog colorPicker = new() { FullOpen = true, Color = Color.FromArgb(_selectedColor) }; diff --git a/src/BizHawk.Client.EmuHawk/config/Messages/MessageConfig.cs b/src/BizHawk.Client.EmuHawk/config/Messages/MessageConfig.cs index 73324f0b1cf..740ecc4fed9 100644 --- a/src/BizHawk.Client.EmuHawk/config/Messages/MessageConfig.cs +++ b/src/BizHawk.Client.EmuHawk/config/Messages/MessageConfig.cs @@ -24,7 +24,7 @@ public partial class MessageConfig : Form private readonly SzNUDEx _nudDuration; - private Dictionary Positions => new Dictionary + private Dictionary Positions => new() { ["Fps"] = _fps, ["Frame Counter"] = _frameCounter, @@ -36,7 +36,7 @@ public partial class MessageConfig : Form ["Autohold"] = _autohold }; - private Dictionary Colors => new Dictionary + private Dictionary Colors => new() { ["Main Messages"] = _config.MessagesColor, ["Alert Messages"] = _config.AlertMessageColor, @@ -104,7 +104,7 @@ void SetMessagePosition(MessageRow row, MessagePosition position) int y = 12; foreach (var (name, pos) in Positions) { - var row = new MessageRow + MessageRow row = new() { Name = name, Location = new Point(10, y) @@ -128,7 +128,7 @@ private void CreateColorBoxes() int y = 20; foreach (var (name, argb) in Colors) { - var row = new ColorRow + ColorRow row = new() { Name = name, Location = new Point(10, y), @@ -162,10 +162,7 @@ private void Ok_Click(object sender, EventArgs e) Close(); } - private void Cancel_Click(object sender, EventArgs e) - { - Close(); - } + private void Cancel_Click(object sender, EventArgs e) => Close(); private void ResetDefaultsButton_Click(object sender, EventArgs e) { diff --git a/src/BizHawk.Client.EmuHawk/config/Messages/MessageEdit.cs b/src/BizHawk.Client.EmuHawk/config/Messages/MessageEdit.cs index fc3b868b4c7..9d46bb21431 100644 --- a/src/BizHawk.Client.EmuHawk/config/Messages/MessageEdit.cs +++ b/src/BizHawk.Client.EmuHawk/config/Messages/MessageEdit.cs @@ -8,7 +8,7 @@ namespace BizHawk.Client.EmuHawk { public partial class MessageEdit : UserControl { - private MessagePosition _messagePosition = new MessagePosition(); + private MessagePosition _messagePosition = new(); private Action _changeCallback; private bool _programmaticallyChangingValues; private bool _mousedown; @@ -113,15 +113,9 @@ private void PositionPanel_MouseDown(object sender, MouseEventArgs e) SetPosition(e.X, e.Y); } - private void PositionPanel_MouseEnter(object sender, EventArgs e) - { - Cursor = Cursors.Hand; - } + private void PositionPanel_MouseEnter(object sender, EventArgs e) => Cursor = Cursors.Hand; - private void PositionPanel_MouseLeave(object sender, EventArgs e) - { - Cursor = Cursors.Default; - } + private void PositionPanel_MouseLeave(object sender, EventArgs e) => Cursor = Cursors.Default; private void PositionPanel_MouseMove(object sender, MouseEventArgs e) { @@ -162,7 +156,7 @@ private void PositionPanel_Paint(object sender, PaintEventArgs e) break; } - using var p = new Pen(Color.Black); + using Pen p = new(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)); diff --git a/src/BizHawk.Client.EmuHawk/config/Messages/MessageRow.cs b/src/BizHawk.Client.EmuHawk/config/Messages/MessageRow.cs index 907f6398495..c62182be542 100644 --- a/src/BizHawk.Client.EmuHawk/config/Messages/MessageRow.cs +++ b/src/BizHawk.Client.EmuHawk/config/Messages/MessageRow.cs @@ -39,10 +39,7 @@ public bool Checked } } - public void SetText() - { - LocationLabel.Text = MessagePosition.ToCoordinateStr(); - } + public void SetText() => LocationLabel.Text = MessagePosition.ToCoordinateStr(); private void RowRadio_CheckedChanged(object sender, EventArgs e) { diff --git a/src/BizHawk.Client.EmuHawk/config/N64/N64ControllerSettingControl.cs b/src/BizHawk.Client.EmuHawk/config/N64/N64ControllerSettingControl.cs index c2badf6a94a..75c8b6024b2 100644 --- a/src/BizHawk.Client.EmuHawk/config/N64/N64ControllerSettingControl.cs +++ b/src/BizHawk.Client.EmuHawk/config/N64/N64ControllerSettingControl.cs @@ -48,7 +48,7 @@ public N64SyncSettings.N64ControllerSettings.N64ControllerPakType PakType { if (PakTypeDropdown.Items.Count > 0) // Null check for designer { - var toSelect = PakTypeDropdown.Items + object toSelect = PakTypeDropdown.Items .OfType() .FirstOrDefault(item => item.ToString() == value.GetDescription()); PakTypeDropdown.SelectedItem = toSelect; @@ -64,9 +64,6 @@ public override void Refresh() base.Refresh(); } - private void EnabledCheckbox_CheckedChanged(object sender, EventArgs e) - { - PakTypeDropdown.Enabled = EnabledCheckbox.Checked; - } + private void EnabledCheckbox_CheckedChanged(object sender, EventArgs e) => PakTypeDropdown.Enabled = EnabledCheckbox.Checked; } } diff --git a/src/BizHawk.Client.EmuHawk/config/N64/N64VideoPluginconfig.cs b/src/BizHawk.Client.EmuHawk/config/N64/N64VideoPluginconfig.cs index 60b4626a227..203c5b0ef8f 100644 --- a/src/BizHawk.Client.EmuHawk/config/N64/N64VideoPluginconfig.cs +++ b/src/BizHawk.Client.EmuHawk/config/N64/N64VideoPluginconfig.cs @@ -69,8 +69,8 @@ private void SaveSettings() // Global if (VideoResolutionComboBox.Text != CustomResItemName) { - var videoSettings = VideoResolutionComboBox.SelectedItem.ToString(); - var strArr = videoSettings.Split('x'); + string videoSettings = VideoResolutionComboBox.SelectedItem.ToString(); + string[] strArr = videoSettings.Split('x'); _s.VideoSizeX = int.Parse(strArr[0].Trim()); _s.VideoSizeY = int.Parse(strArr[1].Trim()); } @@ -134,9 +134,9 @@ private void N64VideoPluginConfig_Load(object sender, EventArgs e) VideoResolutionXTextBox.Text = _s.VideoSizeX.ToString(); VideoResolutionYTextBox.Text = _s.VideoSizeY.ToString(); - var videoSetting = $"{_s.VideoSizeX} x {_s.VideoSizeY}"; + string videoSetting = $"{_s.VideoSizeX} x {_s.VideoSizeY}"; - var index = VideoResolutionComboBox.Items.IndexOf(videoSetting); + int index = VideoResolutionComboBox.Items.IndexOf(videoSetting); if (index >= 0) { VideoResolutionComboBox.SelectedIndex = index; @@ -170,7 +170,7 @@ private void PluginComboBox_SelectedIndexChanged(object sender, EventArgs e) string[] strArr; int oldSizeX, oldSizeY; - var oldResolution = VideoResolutionComboBox.SelectedItem?.ToString() ?? ""; + string oldResolution = VideoResolutionComboBox.SelectedItem?.ToString() ?? ""; if (oldResolution != CustomResItemName) { strArr = oldResolution.Split('x'); @@ -189,7 +189,7 @@ private void PluginComboBox_SelectedIndexChanged(object sender, EventArgs e) // If the given resolution is in the table, pick it. // Otherwise find a best fit - var index = VideoResolutionComboBox.Items.IndexOf(oldResolution); + int index = VideoResolutionComboBox.Items.IndexOf(oldResolution); if (index >= 0) { VideoResolutionComboBox.SelectedIndex = index; @@ -239,8 +239,8 @@ private void VideoResolutionComboBox_SelectedIndexChanged(object sender, EventAr else { HideCustomVideoResolutionControls(); - var newResolution = VideoResolutionComboBox.SelectedItem.ToString(); - var strArr = newResolution.Split('x'); + string newResolution = VideoResolutionComboBox.SelectedItem.ToString(); + string[] strArr = newResolution.Split('x'); VideoResolutionXTextBox.Text = strArr[0].Trim(); VideoResolutionYTextBox.Text = strArr[1].Trim(); } diff --git a/src/BizHawk.Client.EmuHawk/config/NES/DataTableDictionaryBind.cs b/src/BizHawk.Client.EmuHawk/config/NES/DataTableDictionaryBind.cs index 6439914eae4..66a5cdc7e92 100644 --- a/src/BizHawk.Client.EmuHawk/config/NES/DataTableDictionaryBind.cs +++ b/src/BizHawk.Client.EmuHawk/config/NES/DataTableDictionaryBind.cs @@ -32,8 +32,8 @@ private void CreateTable() private void Table_RowChanged(object sender, DataRowChangeEventArgs e) { - var key = (TKey)e.Row[0]; - var value = (TValue)e.Row[1]; + TKey key = (TKey)e.Row[0]; + TValue value = (TValue)e.Row[1]; switch (e.Action) { diff --git a/src/BizHawk.Client.EmuHawk/config/NES/NESGraphicsConfig.cs b/src/BizHawk.Client.EmuHawk/config/NES/NESGraphicsConfig.cs index 42f31ebdd64..68b69a0d391 100644 --- a/src/BizHawk.Client.EmuHawk/config/NES/NESGraphicsConfig.cs +++ b/src/BizHawk.Client.EmuHawk/config/NES/NESGraphicsConfig.cs @@ -36,10 +36,7 @@ public NESGraphicsConfig( InitializeComponent(); } - private void NESGraphicsConfig_Load(object sender, EventArgs e) - { - LoadStuff(); - } + private void NESGraphicsConfig_Load(object sender, EventArgs e) => LoadStuff(); private void LoadStuff() { @@ -59,7 +56,7 @@ private void LoadStuff() private void BrowsePalette_Click(object sender, EventArgs e) { - var result = this.ShowFileOpenDialog( + string result = this.ShowFileOpenDialog( discardCWDChange: true, filter: FilesystemFilterSet.Palettes, initDir: _config.PathEntries.PalettesAbsolutePathFor(VSystemID.Raw.NES)); @@ -71,12 +68,12 @@ private void BrowsePalette_Click(object sender, EventArgs e) private void SetPaletteImage() { - var pal = ResolvePalette(); + byte[,] pal = ResolvePalette(); int w = pictureBoxPalette.Size.Width; int h = pictureBoxPalette.Size.Height; - var bmp = new Bitmap(w, h); + Bitmap bmp = new(w, h); for (int j = 0; j < h; j++) { int cy = j * 4 / h; @@ -98,11 +95,11 @@ private void SetPaletteImage() { if (PalettePath.Text.Length > 0) { - var palette = new HawkFile(PalettePath.Text); + HawkFile palette = new(PalettePath.Text); if (palette.Exists) { - var data = Palettes.Load_FCEUX_Palette(palette.ReadAllBytes()); + byte[,] data = Palettes.Load_FCEUX_Palette(palette.ReadAllBytes()); if (showMsg) { DialogController.AddOnScreenMessage($"Palette file loaded: {palette.Name}"); @@ -157,10 +154,7 @@ private void SetColorBox() BackgroundColorPanel.BackColor = BGColorDialog.Color; } - private void ChangeBGColor_Click(object sender, EventArgs e) - { - ChangeBG(); - } + private void ChangeBGColor_Click(object sender, EventArgs e) => ChangeBG(); private void ChangeBG() { @@ -182,10 +176,7 @@ private void BtnAreaFull_Click(object sender, EventArgs e) NTSC_LastLineNumeric.Value = 239; } - private void BackgroundColorPanel_DoubleClick(object sender, EventArgs e) - { - ChangeBG(); - } + private void BackgroundColorPanel_DoubleClick(object sender, EventArgs e) => ChangeBG(); private void RestoreDefaultsButton_Click(object sender, EventArgs e) { @@ -193,9 +184,6 @@ private void RestoreDefaultsButton_Click(object sender, EventArgs e) LoadStuff(); } - private void AutoLoadPalette_Click(object sender, EventArgs e) - { - SetPaletteImage(); - } + private void AutoLoadPalette_Click(object sender, EventArgs e) => SetPaletteImage(); } } diff --git a/src/BizHawk.Client.EmuHawk/config/NES/NESSoundConfig.cs b/src/BizHawk.Client.EmuHawk/config/NES/NESSoundConfig.cs index a0a08fe5c04..6307715f1d5 100644 --- a/src/BizHawk.Client.EmuHawk/config/NES/NESSoundConfig.cs +++ b/src/BizHawk.Client.EmuHawk/config/NES/NESSoundConfig.cs @@ -12,10 +12,7 @@ public partial class NESSoundConfig : ToolFormBase private NES.NESSettings _oldSettings; private NES.NESSettings _settings; - public override void Restart() - { - NESSoundConfig_Load(null, null); - } + public override void Restart() => NESSoundConfig_Load(null, null); protected override string WindowTitleStatic => "NES Sound Channels"; @@ -24,7 +21,7 @@ public NESSoundConfig() InitializeComponent(); // get baseline maxes from a default config object - var d = new NES.NESSettings(); + NES.NESSettings d = new(); trackBar1.Minimum = d.APU_vol; } @@ -36,10 +33,7 @@ private void NESSoundConfig_Load(object sender, EventArgs e) trackBar1.Value = _settings.APU_vol; } - private void Ok_Click(object sender, EventArgs e) - { - Close(); - } + private void Ok_Click(object sender, EventArgs e) => Close(); private void Cancel_Click(object sender, EventArgs e) { diff --git a/src/BizHawk.Client.EmuHawk/config/NES/NESSyncSettingsForm.cs b/src/BizHawk.Client.EmuHawk/config/NES/NESSyncSettingsForm.cs index 87653e1210d..568492a2ee7 100644 --- a/src/BizHawk.Client.EmuHawk/config/NES/NESSyncSettingsForm.cs +++ b/src/BizHawk.Client.EmuHawk/config/NES/NESSyncSettingsForm.cs @@ -50,8 +50,8 @@ public NESSyncSettingsForm( if (_syncSettings.InitialWRamStatePattern != null && _syncSettings.InitialWRamStatePattern.Any()) { - var sb = new StringBuilder(); - foreach (var b in _syncSettings.InitialWRamStatePattern) + StringBuilder sb = new(); + foreach (byte b in _syncSettings.InitialWRamStatePattern) { sb.Append($"{b:X2}"); } diff --git a/src/BizHawk.Client.EmuHawk/config/NES/NESVSSettings.cs b/src/BizHawk.Client.EmuHawk/config/NES/NESVSSettings.cs index f640e4359a9..02c34dec5a1 100644 --- a/src/BizHawk.Client.EmuHawk/config/NES/NESVSSettings.cs +++ b/src/BizHawk.Client.EmuHawk/config/NES/NESVSSettings.cs @@ -46,9 +46,6 @@ private void OkBtn_Click(object sender, EventArgs e) Close(); } - private void CancelBtn_Click(object sender, EventArgs e) - { - Close(); - } + private void CancelBtn_Click(object sender, EventArgs e) => Close(); } } diff --git a/src/BizHawk.Client.EmuHawk/config/NES/NesControllerSettings.cs b/src/BizHawk.Client.EmuHawk/config/NES/NesControllerSettings.cs index b14c2e2661b..d70ff15252c 100644 --- a/src/BizHawk.Client.EmuHawk/config/NES/NesControllerSettings.cs +++ b/src/BizHawk.Client.EmuHawk/config/NES/NesControllerSettings.cs @@ -40,7 +40,7 @@ private void CheckBoxFamicom_CheckedChanged(object sender, EventArgs e) private void OkBtn_Click(object sender, EventArgs e) { - var controls = new NESControlSettings + NESControlSettings controls = new() { Famicom = checkBoxFamicom.Checked, FamicomExpPort = (string)comboBoxFamicom.SelectedItem, diff --git a/src/BizHawk.Client.EmuHawk/config/NES/QuickNesConfig.cs b/src/BizHawk.Client.EmuHawk/config/NES/QuickNesConfig.cs index 63880cfeb29..24996c28117 100644 --- a/src/BizHawk.Client.EmuHawk/config/NES/QuickNesConfig.cs +++ b/src/BizHawk.Client.EmuHawk/config/NES/QuickNesConfig.cs @@ -39,8 +39,8 @@ private void SetPaletteImage() { int w = pictureBox1.Size.Width; int h = pictureBox1.Size.Height; - var bmp = new Bitmap(w, h); - var pal = _settings.Palette; + Bitmap bmp = new(w, h); + byte[] pal = _settings.Palette; for (int j = 0; j < h; j++) { @@ -83,7 +83,7 @@ protected override void OnClosed(EventArgs e) private void ButtonPal_Click(object sender, EventArgs e) { - var result = this.ShowFileOpenDialog( + string result = this.ShowFileOpenDialog( discardCWDChange: true, filter: FilesystemFilterSet.Palettes, initDir: _config.PathEntries.PalettesAbsolutePathFor(VSystemID.Raw.NES)); @@ -92,7 +92,7 @@ private void ButtonPal_Click(object sender, EventArgs e) if (palette.Exists) { - var data = Emulation.Cores.Nintendo.NES.Palettes.Load_FCEUX_Palette(palette.ReadAllBytes()); + byte[,] data = Emulation.Cores.Nintendo.NES.Palettes.Load_FCEUX_Palette(palette.ReadAllBytes()); _settings.SetNesHawkPalette(data); SetPaletteImage(); } diff --git a/src/BizHawk.Client.EmuHawk/config/PSX/PSXControllerConfig.cs b/src/BizHawk.Client.EmuHawk/config/PSX/PSXControllerConfig.cs index ae182414846..da98eccb7cf 100644 --- a/src/BizHawk.Client.EmuHawk/config/PSX/PSXControllerConfig.cs +++ b/src/BizHawk.Client.EmuHawk/config/PSX/PSXControllerConfig.cs @@ -58,7 +58,7 @@ private void GuiFromUserConfig(OctoshockFIOConfigUser user) private OctoshockFIOConfigUser UserConfigFromGui() { - var uc = new OctoshockFIOConfigUser + OctoshockFIOConfigUser uc = new() { Memcards = { [0] = cbMemcard_1.Checked, [1] = cbMemcard_2.Checked }, Multitaps = { [0] = cbMultitap_1.Checked, [1] = cbMultitap_2.Checked } @@ -128,15 +128,9 @@ private void RefreshLabels() } } - private void Cb_Changed(object sender, EventArgs e) - { - RefreshLabels(); - } + private void Cb_Changed(object sender, EventArgs e) => RefreshLabels(); - private void Combo_SelectedIndexChanged(object sender, EventArgs e) - { - RefreshLabels(); - } + private void Combo_SelectedIndexChanged(object sender, EventArgs e) => RefreshLabels(); private void BtnOk_Click(object sender, EventArgs e) { diff --git a/src/BizHawk.Client.EmuHawk/config/PSX/PSXOptions.cs b/src/BizHawk.Client.EmuHawk/config/PSX/PSXOptions.cs index 0d14187246b..7d19cf61978 100644 --- a/src/BizHawk.Client.EmuHawk/config/PSX/PSXOptions.cs +++ b/src/BizHawk.Client.EmuHawk/config/PSX/PSXOptions.cs @@ -177,25 +177,13 @@ private void SyncLabels() lblTweakedMednafen.Text = _lblTweakedMednafenText.Replace("400x300", $"{ri.Resolution.Width}x{ri.Resolution.Height}"); } - private void DrawingArea_ValueChanged(object sender, EventArgs e) - { - SyncLabels(); - } + private void DrawingArea_ValueChanged(object sender, EventArgs e) => SyncLabels(); - private void RbClipHorizontal_CheckedChanged(object sender, EventArgs e) - { - SyncLabels(); - } + private void RbClipHorizontal_CheckedChanged(object sender, EventArgs e) => SyncLabels(); - private void RbClipToFramebuffer_CheckedChanged(object sender, EventArgs e) - { - SyncLabels(); - } + private void RbClipToFramebuffer_CheckedChanged(object sender, EventArgs e) => SyncLabels(); - private void RbClipNone_CheckedChanged(object sender, EventArgs e) - { - SyncLabels(); - } + private void RbClipNone_CheckedChanged(object sender, EventArgs e) => SyncLabels(); private void LinkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { diff --git a/src/BizHawk.Client.EmuHawk/config/PathConfig.cs b/src/BizHawk.Client.EmuHawk/config/PathConfig.cs index 5681de66021..2f2af311d54 100644 --- a/src/BizHawk.Client.EmuHawk/config/PathConfig.cs +++ b/src/BizHawk.Client.EmuHawk/config/PathConfig.cs @@ -19,7 +19,7 @@ public partial class PathConfig : Form private readonly string _sysID; - private static AutoCompleteStringCollection AutoCompleteOptions => new AutoCompleteStringCollection + private static AutoCompleteStringCollection AutoCompleteOptions => new() { "%recent%", "%exe%", @@ -66,10 +66,10 @@ void PopulateTabPage(Control t, string system) .OrderBy(p => p.Ordinal) .ThenBy(p => p.Type); - var y = UIHelper.ScaleY(14); + int y = UIHelper.ScaleY(14); foreach (var path in paths) { - var box = new TextBox + TextBox box = new() { Text = path.Path, Location = new Point(x, y), @@ -82,7 +82,7 @@ void PopulateTabPage(Control t, string system) AutoCompleteSource = AutoCompleteSource.CustomSource }; - var btn = new Button + Button btn = new() { Text = "", Image = Properties.Resources.OpenFile, @@ -93,11 +93,11 @@ void PopulateTabPage(Control t, string system) }; var tempBox = box; - var tempPath = path.Type; - var tempSystem = path.System; + string tempPath = path.Type; + string tempSystem = path.System; btn.Click += (sender, args) => BrowseFolder(tempBox, tempPath, tempSystem); - var label = new Label + Label label = new() { Text = path.Type, Location = new Point(widgetOffset + buttonWidth + padding, y + UIHelper.ScaleY(4)), @@ -115,7 +115,7 @@ void PopulateTabPage(Control t, string system) } void AddTabPageForSystem(string system, string systemDisplayName) { - var t = new TabPage + TabPage t = new() { Name = system, Text = systemDisplayName, @@ -135,7 +135,7 @@ void AddTabPageForSystem(string system, string systemDisplayName) tcMain.Visible = false; PathTabControl.TabPages.Clear(); - var systems = _pathEntries.Select(e => e.System).Distinct() // group entries by "system" (intentionally using instance field here, not parameter) + List<(string SysGroup, string DisplayName)> systems = _pathEntries.Select(e => e.System).Distinct() // group entries by "system" (intentionally using instance field here, not parameter) .Select(sys => (SysGroup: sys, DisplayName: PathEntryCollection.GetDisplayNameFor(sys))) .OrderBy(tuple => tuple.DisplayName) .ToList(); @@ -143,7 +143,7 @@ void AddTabPageForSystem(string system, string systemDisplayName) // add the Global tab first... tpGlobal.Name = PathEntryCollection.GLOBAL; // required for SaveSettings systems.RemoveAll(tuple => tuple.SysGroup == PathEntryCollection.GLOBAL); - var hack = tpGlobal.Size.Width - UIHelper.ScaleX(220); // whyyyyyyyyyy + int hack = tpGlobal.Size.Width - UIHelper.ScaleX(220); // whyyyyyyyyyy textBoxWidth += hack; widgetOffset += hack; Size hack1 = new(17, 0); // also whyyyyyyyyyy @@ -156,7 +156,7 @@ void AddTabPageForSystem(string system, string systemDisplayName) // ...then continue with the others (after removing unreleased systems in Release builds) if (!VersionInfo.DeveloperBuild) { - var releasedCoreSysIDs = CoreInventory.Instance.AllCores.SelectMany(kvp => kvp.Value.Select(coreInfo => (SysID: kvp.Key, CoreInfo: coreInfo))) + List releasedCoreSysIDs = CoreInventory.Instance.AllCores.SelectMany(kvp => kvp.Value.Select(coreInfo => (SysID: kvp.Key, CoreInfo: coreInfo))) .Where(tuple => tuple.CoreInfo.CoreAttr.Released) .Select(tuple => tuple.SysID) .Distinct().ToList(); @@ -188,7 +188,7 @@ private void BrowseFolder(TextBox box, string name, string system) if (OSTailoredCode.IsUnixHost) { // FolderBrowserEx doesn't work in Mono for obvious reasons - using var f = new FolderBrowserDialog + using FolderBrowserDialog f = new() { Description = $"Set the directory for {name}", SelectedPath = _pathEntries.AbsolutePathFor(box.Text, system) @@ -198,7 +198,7 @@ private void BrowseFolder(TextBox box, string name, string system) } else { - using var f = new FolderBrowserEx + using FolderBrowserEx f = new() { Description = $"Set the directory for {name}", SelectedPath = _pathEntries.AbsolutePathFor(box.Text, system) @@ -236,25 +236,13 @@ private void DoRomToggle() private IEnumerable AllPathControls => new[] { tpGlobal }.Concat(PathTabControl.TabPages.Cast()).SelectMany(tp => tp.Controls()); - private void NewPathConfig_Load(object sender, EventArgs e) - { - LoadSettings(); - } + private void NewPathConfig_Load(object sender, EventArgs e) => LoadSettings(); - private void RecentForRoms_CheckedChanged(object sender, EventArgs e) - { - DoRomToggle(); - } + private void RecentForRoms_CheckedChanged(object sender, EventArgs e) => DoRomToggle(); - private void SpecialCommandsBtn_Click(object sender, EventArgs e) - { - new PathInfo().Show(); - } + private void SpecialCommandsBtn_Click(object sender, EventArgs e) => new PathInfo().Show(); - private void SaveBtn_Click(object sender, EventArgs e) - { - SaveSettings(); - } + private void SaveBtn_Click(object sender, EventArgs e) => SaveSettings(); private void DefaultsBtn_Click(object sender, EventArgs e) => DoTabs(PathEntryCollection.Defaults.Value, PathEntryCollection.GLOBAL); @@ -267,14 +255,8 @@ private void Ok_Click(object sender, EventArgs e) Close(); } - private void Cancel_Click(object sender, EventArgs e) - { - Close(); - } + private void Cancel_Click(object sender, EventArgs e) => Close(); - private void comboSystem_SelectedIndexChanged(object sender, EventArgs e) - { - PathTabControl.SelectTab(((ComboBox) sender).SelectedIndex); - } + private void comboSystem_SelectedIndexChanged(object sender, EventArgs e) => PathTabControl.SelectTab(((ComboBox)sender).SelectedIndex); } } diff --git a/src/BizHawk.Client.EmuHawk/config/PathInfo.cs b/src/BizHawk.Client.EmuHawk/config/PathInfo.cs index a09e5987ea0..9850cec85b3 100644 --- a/src/BizHawk.Client.EmuHawk/config/PathInfo.cs +++ b/src/BizHawk.Client.EmuHawk/config/PathInfo.cs @@ -10,9 +10,6 @@ public PathInfo() InitializeComponent(); } - private void Ok_Click(object sender, EventArgs e) - { - Close(); - } + private void Ok_Click(object sender, EventArgs e) => Close(); } } diff --git a/src/BizHawk.Client.EmuHawk/config/RewindConfig.cs b/src/BizHawk.Client.EmuHawk/config/RewindConfig.cs index cf292a97602..f895475499b 100755 --- a/src/BizHawk.Client.EmuHawk/config/RewindConfig.cs +++ b/src/BizHawk.Client.EmuHawk/config/RewindConfig.cs @@ -42,9 +42,9 @@ private void RewindConfig_Load(object sender, EventArgs e) var rewinder = _getRewinder(); if (rewinder?.Active == true) { - var fullnessRatio = rewinder.FullnessRatio; + float fullnessRatio = rewinder.FullnessRatio; FullnessLabel.Text = $"{fullnessRatio:P2}"; - var stateCount = rewinder.Count; + int stateCount = rewinder.Count; RewindFramesUsedLabel.Text = stateCount.ToString(); _avgStateSize = stateCount is 0 ? 0UL : (ulong) Math.Round(rewinder.Size * fullnessRatio / stateCount); } @@ -100,10 +100,7 @@ private string FormatKB(ulong n) return $"{num:0.00} KB"; } - private void Cancel_Click(object sender, EventArgs e) - { - Close(); - } + private void Cancel_Click(object sender, EventArgs e) => Close(); private bool TriggerRewindSettingsReload { get; set; } @@ -152,7 +149,7 @@ private void CalculateEstimates() double estFrames = 0.0; if (_avgStateSize is not 0UL) { - var bufferSize = 1L << (int) BufferSizeUpDown.Value; + long bufferSize = 1L << (int) BufferSizeUpDown.Value; labelEx1.Text = bufferSize.ToString(); bufferSize *= 1024 * 1024; estFrames = bufferSize / (double) _avgStateSize; @@ -161,30 +158,16 @@ private void CalculateEstimates() EstTimeLabel.Text = $"{estFrames / _framerate / 60.0:n} minutes"; } - private void BufferSizeUpDown_ValueChanged(object sender, EventArgs e) - { - CalculateEstimates(); - } + private void BufferSizeUpDown_ValueChanged(object sender, EventArgs e) => CalculateEstimates(); - private void UseCompression_CheckedChanged(object sender, EventArgs e) - { - CalculateEstimates(); - } + private void UseCompression_CheckedChanged(object sender, EventArgs e) => CalculateEstimates(); - private void NudCompression_ValueChanged(object sender, EventArgs e) - { - trackBarCompression.Value = (int)((NumericUpDown)sender).Value; - } + private void NudCompression_ValueChanged(object sender, EventArgs e) => trackBarCompression.Value = (int)((NumericUpDown)sender).Value; - private void TrackBarCompression_ValueChanged(object sender, EventArgs e) - { + private void TrackBarCompression_ValueChanged(object sender, EventArgs e) => // TODO - make a UserControl which is TrackBar and NUD combined nudCompression.Value = ((TrackBar)sender).Value; - } - private void BtnResetCompression_Click(object sender, EventArgs e) - { - nudCompression.Value = SaveStateConfig.DefaultCompressionLevelNormal; - } + private void BtnResetCompression_Click(object sender, EventArgs e) => nudCompression.Value = SaveStateConfig.DefaultCompressionLevelNormal; } } diff --git a/src/BizHawk.Client.EmuHawk/config/SNES/BSNESControllerConfig.cs b/src/BizHawk.Client.EmuHawk/config/SNES/BSNESControllerConfig.cs index 3c3f55f54b7..647bfa20b81 100644 --- a/src/BizHawk.Client.EmuHawk/config/SNES/BSNESControllerConfig.cs +++ b/src/BizHawk.Client.EmuHawk/config/SNES/BSNESControllerConfig.cs @@ -56,8 +56,8 @@ private void CancelBtn_Click(object sender, EventArgs e) private void PortComboBox_SelectedIndexChanged(object sender, EventArgs e) { - var leftPort = (BsnesApi.BSNES_INPUT_DEVICE) Port1ComboBox.SelectedIndex; - var rightPort = (BsnesApi.BSNES_INPUT_DEVICE) Port2ComboBox.SelectedIndex; + BsnesApi.BSNES_INPUT_DEVICE leftPort = (BsnesApi.BSNES_INPUT_DEVICE) Port1ComboBox.SelectedIndex; + BsnesApi.BSNES_INPUT_DEVICE rightPort = (BsnesApi.BSNES_INPUT_DEVICE) Port2ComboBox.SelectedIndex; ToggleMouseSection(leftPort == BsnesApi.BSNES_INPUT_DEVICE.Mouse || rightPort == BsnesApi.BSNES_INPUT_DEVICE.Mouse); } diff --git a/src/BizHawk.Client.EmuHawk/config/SNES/BSNESOptions.cs b/src/BizHawk.Client.EmuHawk/config/SNES/BSNESOptions.cs index b130ab9b94e..0362de9e473 100644 --- a/src/BizHawk.Client.EmuHawk/config/SNES/BSNESOptions.cs +++ b/src/BizHawk.Client.EmuHawk/config/SNES/BSNESOptions.cs @@ -29,9 +29,9 @@ private void OnLoad(object sender, EventArgs e) public static DialogResult DoSettingsDialog(IDialogParent dialogParent, ISettingsAdapter settable) { - var s = (BsnesCore.SnesSettings) settable.GetSettings(); - var ss = (BsnesCore.SnesSyncSettings) settable.GetSyncSettings(); - using var dlg = new BSNESOptions(s, ss) + BsnesCore.SnesSettings s = (BsnesCore.SnesSettings) settable.GetSettings(); + BsnesCore.SnesSyncSettings ss = (BsnesCore.SnesSyncSettings) settable.GetSyncSettings(); + using BSNESOptions dlg = new(s, ss) { AlwaysDoubleSize = s.AlwaysDoubleSize, CropSGBFrame = s.CropSGBFrame, @@ -201,9 +201,6 @@ private void BtnCancel_Click(object sender, EventArgs e) Close(); } - private void FastPPU_CheckedChanged(object sender, EventArgs e) - { - cbDoubleSize.Enabled = cbNoPPUSpriteLimit.Enabled = cbFastPPU.Checked; - } + private void FastPPU_CheckedChanged(object sender, EventArgs e) => cbDoubleSize.Enabled = cbNoPPUSpriteLimit.Enabled = cbFastPPU.Checked; } } diff --git a/src/BizHawk.Client.EmuHawk/config/SNES/SNESControllerConfig.cs b/src/BizHawk.Client.EmuHawk/config/SNES/SNESControllerConfig.cs index 5401ff2e2dc..dea895dc312 100644 --- a/src/BizHawk.Client.EmuHawk/config/SNES/SNESControllerConfig.cs +++ b/src/BizHawk.Client.EmuHawk/config/SNES/SNESControllerConfig.cs @@ -61,8 +61,8 @@ private void PortComboBox_SelectedIndexChanged(object sender, EventArgs e) { if (!_suppressDropdownChangeEvents) { - var leftPort = (LibsnesControllerDeck.ControllerType)Enum.Parse(typeof(LibsnesControllerDeck.ControllerType), Port1ComboBox.SelectedItem.ToString()); - var rightPort = (LibsnesControllerDeck.ControllerType)Enum.Parse(typeof(LibsnesControllerDeck.ControllerType), Port2ComboBox.SelectedItem.ToString()); + LibsnesControllerDeck.ControllerType leftPort = (LibsnesControllerDeck.ControllerType)Enum.Parse(typeof(LibsnesControllerDeck.ControllerType), Port1ComboBox.SelectedItem.ToString()); + LibsnesControllerDeck.ControllerType rightPort = (LibsnesControllerDeck.ControllerType)Enum.Parse(typeof(LibsnesControllerDeck.ControllerType), Port2ComboBox.SelectedItem.ToString()); ToggleMouseSection(leftPort == LibsnesControllerDeck.ControllerType.Mouse || rightPort == LibsnesControllerDeck.ControllerType.Mouse); } diff --git a/src/BizHawk.Client.EmuHawk/config/SNES/SNESOptions.cs b/src/BizHawk.Client.EmuHawk/config/SNES/SNESOptions.cs index c430972c077..40b0a8da675 100644 --- a/src/BizHawk.Client.EmuHawk/config/SNES/SNESOptions.cs +++ b/src/BizHawk.Client.EmuHawk/config/SNES/SNESOptions.cs @@ -19,9 +19,9 @@ private SNESOptions() public static DialogResult DoSettingsDialog(IDialogParent dialogParent, ISettingsAdapter settable) { - var s = (LibsnesCore.SnesSettings) settable.GetSettings(); - var ss = (LibsnesCore.SnesSyncSettings) settable.GetSyncSettings(); - using var dlg = new SNESOptions + LibsnesCore.SnesSettings s = (LibsnesCore.SnesSettings) settable.GetSettings(); + LibsnesCore.SnesSyncSettings ss = (LibsnesCore.SnesSyncSettings) settable.GetSyncSettings(); + using SNESOptions dlg = new() { RandomizedInitialState = ss.RandomizedInitialState, AlwaysDoubleSize = s.AlwaysDoubleSize, diff --git a/src/BizHawk.Client.EmuHawk/config/SoundConfig.cs b/src/BizHawk.Client.EmuHawk/config/SoundConfig.cs index 093a3d94c78..b5549ee3dcb 100644 --- a/src/BizHawk.Client.EmuHawk/config/SoundConfig.cs +++ b/src/BizHawk.Client.EmuHawk/config/SoundConfig.cs @@ -79,17 +79,14 @@ private void Ok_Click(object sender, EventArgs e) DialogResult = DialogResult.OK; } - private void Cancel_Click(object sender, EventArgs e) - { - Close(); - } + private void Cancel_Click(object sender, EventArgs e) => Close(); private void PopulateDeviceList() { listBoxSoundDevices.Items.Clear(); listBoxSoundDevices.Items.Add(""); listBoxSoundDevices.SelectedIndex = 0; - foreach (var name in _getDeviceNamesCallback(GetSelectedOutputMethod())) + foreach (string name in _getDeviceNamesCallback(GetSelectedOutputMethod())) { listBoxSoundDevices.Items.Add(name); if (name == _config.SoundDevice) @@ -109,15 +106,9 @@ private void OutputMethodRadioButtons_CheckedChanged(object sender, EventArgs e) PopulateDeviceList(); } - private void TrackBar1_Scroll(object sender, EventArgs e) - { - nudNormal.Value = tbNormal.Value; - } + private void TrackBar1_Scroll(object sender, EventArgs e) => nudNormal.Value = tbNormal.Value; - private void TbRwff_Scroll(object sender, EventArgs e) - { - nudRWFF.Value = tbRWFF.Value; - } + private void TbRwff_Scroll(object sender, EventArgs e) => nudRWFF.Value = tbRWFF.Value; private void SoundVolNumeric_ValueChanged(object sender, EventArgs e) { @@ -136,14 +127,8 @@ private void UpdateSoundDialog() grpSoundVol.Enabled = cbEnableMaster.Checked; } - private void UpdateSoundDialog(object sender, EventArgs e) - { - UpdateSoundDialog(); - } + private void UpdateSoundDialog(object sender, EventArgs e) => UpdateSoundDialog(); - private void nudRWFF_ValueChanged(object sender, EventArgs e) - { - tbRWFF.Value = (int)nudRWFF.Value; - } + private void nudRWFF_ValueChanged(object sender, EventArgs e) => tbRWFF.Value = (int)nudRWFF.Value; } } diff --git a/src/BizHawk.Client.EmuHawk/config/TI83/TI83PaletteConfig.cs b/src/BizHawk.Client.EmuHawk/config/TI83/TI83PaletteConfig.cs index 559e0a55eb9..77b53dc79ba 100644 --- a/src/BizHawk.Client.EmuHawk/config/TI83/TI83PaletteConfig.cs +++ b/src/BizHawk.Client.EmuHawk/config/TI83/TI83PaletteConfig.cs @@ -52,7 +52,7 @@ private void BackgroundPanel_Click(object sender, EventArgs e) // and the rgb order is switched int customColor = BackgroundPanel.BackColor.R | BackgroundPanel.BackColor.G << 8 | BackgroundPanel.BackColor.B << 16; - using var dlg = new ColorDialog + using ColorDialog dlg = new() { AllowFullOpen = true, AnyColor = true, @@ -73,7 +73,7 @@ private void ForeGroundPanel_Click(object sender, EventArgs e) // and the rgb order is switched int customColor = ForeGroundPanel.BackColor.R | ForeGroundPanel.BackColor.G << 8 | ForeGroundPanel.BackColor.B << 16; - using var dlg = new ColorDialog + using ColorDialog dlg = new() { AllowFullOpen = true, AnyColor = true, @@ -89,7 +89,7 @@ private void ForeGroundPanel_Click(object sender, EventArgs e) private void DefaultsBtn_Click(object sender, EventArgs e) { - var s = new TI83Common.TI83CommonSettings(); + TI83Common.TI83CommonSettings s = new(); BackgroundPanel.BackColor = Color.FromArgb((int)s.BGColor); ForeGroundPanel.BackColor = Color.FromArgb((int)s.ForeColor); } diff --git a/src/BizHawk.Client.EmuHawk/config/ZXSpectrum/ZXSpectrumAudioSettings.cs b/src/BizHawk.Client.EmuHawk/config/ZXSpectrum/ZXSpectrumAudioSettings.cs index ad5e108ed4a..1149594177c 100644 --- a/src/BizHawk.Client.EmuHawk/config/ZXSpectrum/ZXSpectrumAudioSettings.cs +++ b/src/BizHawk.Client.EmuHawk/config/ZXSpectrum/ZXSpectrumAudioSettings.cs @@ -23,8 +23,8 @@ public ZxSpectrumAudioSettings(ISettingsAdapter settable) private void IntvControllerSettings_Load(object sender, EventArgs e) { // AY panning config - var panTypes = Enum.GetNames(typeof(AY38912.AYPanConfig)); - foreach (var val in panTypes) + string[] panTypes = Enum.GetNames(typeof(AY38912.AYPanConfig)); + foreach (string val in panTypes) { panTypecomboBox1.Items.Add(val); } diff --git a/src/BizHawk.Client.EmuHawk/config/ZXSpectrum/ZXSpectrumCoreEmulationSettings.cs b/src/BizHawk.Client.EmuHawk/config/ZXSpectrum/ZXSpectrumCoreEmulationSettings.cs index 026e5cf9e2a..7dbdd125456 100644 --- a/src/BizHawk.Client.EmuHawk/config/ZXSpectrum/ZXSpectrumCoreEmulationSettings.cs +++ b/src/BizHawk.Client.EmuHawk/config/ZXSpectrum/ZXSpectrumCoreEmulationSettings.cs @@ -23,8 +23,8 @@ public ZxSpectrumCoreEmulationSettings(ISettingsAdapter settable) private void IntvControllerSettings_Load(object sender, EventArgs e) { // machine selection - var machineTypes = Enum.GetNames(typeof(MachineType)); - foreach (var val in machineTypes) + string[] machineTypes = Enum.GetNames(typeof(MachineType)); + foreach (string val in machineTypes) { MachineSelectionComboBox.Items.Add(val); } @@ -32,8 +32,8 @@ private void IntvControllerSettings_Load(object sender, EventArgs e) UpdateMachineNotes((MachineType)Enum.Parse(typeof(MachineType), MachineSelectionComboBox.SelectedItem.ToString())); // border selection - var borderTypes = Enum.GetNames(typeof(ZXSpectrum.BorderType)); - foreach (var val in borderTypes) + string[] borderTypes = Enum.GetNames(typeof(ZXSpectrum.BorderType)); + foreach (string val in borderTypes) { borderTypecomboBox1.Items.Add(val); } @@ -76,18 +76,15 @@ private void CancelBtn_Click(object sender, EventArgs e) private void MachineSelectionComboBox_SelectionChangeCommitted(object sender, EventArgs e) { - var cb = (ComboBox)sender; + ComboBox cb = (ComboBox)sender; UpdateMachineNotes((MachineType)Enum.Parse(typeof(MachineType), cb.SelectedItem.ToString())); } - private void UpdateMachineNotes(MachineType type) - { - textBoxCoreDetails.Text = ZXMachineMetaData.GetMetaString(type); - } + private void UpdateMachineNotes(MachineType type) => textBoxCoreDetails.Text = ZXMachineMetaData.GetMetaString(type); private void BorderTypeComboBox_SelectedIndexChanged(object sender, EventArgs e) { - var cb = (ComboBox)sender; + ComboBox cb = (ComboBox)sender; UpdateBorderNotes((ZXSpectrum.BorderType)Enum.Parse(typeof(ZXSpectrum.BorderType), cb.SelectedItem.ToString())); } diff --git a/src/BizHawk.Client.EmuHawk/config/ZXSpectrum/ZXSpectrumJoystickSettings.cs b/src/BizHawk.Client.EmuHawk/config/ZXSpectrum/ZXSpectrumJoystickSettings.cs index 2acc1ab7eff..63b5cf50de4 100644 --- a/src/BizHawk.Client.EmuHawk/config/ZXSpectrum/ZXSpectrumJoystickSettings.cs +++ b/src/BizHawk.Client.EmuHawk/config/ZXSpectrum/ZXSpectrumJoystickSettings.cs @@ -29,7 +29,7 @@ private void IntvControllerSettings_Load(object sender, EventArgs e) { _possibleControllers = Enum.GetNames(typeof(JoystickType)); - foreach (var val in _possibleControllers) + foreach (string val in _possibleControllers) { Port1ComboBox.Items.Add(val); Port2ComboBox.Items.Add(val); @@ -54,7 +54,7 @@ private void OkBtn_Click(object sender, EventArgs e) bool selectionValid = true; - var j1 = Port1ComboBox.SelectedItem.ToString(); + string j1 = Port1ComboBox.SelectedItem.ToString(); if (j1 != _possibleControllers[0]) { if (j1 == Port2ComboBox.SelectedItem.ToString()) @@ -69,7 +69,7 @@ private void OkBtn_Click(object sender, EventArgs e) } } - var j2 = Port2ComboBox.SelectedItem.ToString(); + string j2 = Port2ComboBox.SelectedItem.ToString(); if (j2 != _possibleControllers[0]) { if (j2 == Port1ComboBox.SelectedItem.ToString()) @@ -84,7 +84,7 @@ private void OkBtn_Click(object sender, EventArgs e) } } - var j3 = Port3ComboBox.SelectedItem.ToString(); + string j3 = Port3ComboBox.SelectedItem.ToString(); if (j3 != _possibleControllers[0]) { if (j3 == Port1ComboBox.SelectedItem.ToString()) diff --git a/src/BizHawk.Client.EmuHawk/config/ZXSpectrum/ZXSpectrumNonSyncSettings.cs b/src/BizHawk.Client.EmuHawk/config/ZXSpectrum/ZXSpectrumNonSyncSettings.cs index 98d005297da..46197bd69e4 100644 --- a/src/BizHawk.Client.EmuHawk/config/ZXSpectrum/ZXSpectrumNonSyncSettings.cs +++ b/src/BizHawk.Client.EmuHawk/config/ZXSpectrum/ZXSpectrumNonSyncSettings.cs @@ -30,8 +30,8 @@ private void IntvControllerSettings_Load(object sender, EventArgs e) checkBoxShowCoreBrdColor.Checked = _settings.UseCoreBorderForBackground; // OSD Message Verbosity - var osdTypes = Enum.GetNames(typeof(ZXSpectrum.OSDVerbosity)); - foreach (var val in osdTypes) + string[] osdTypes = Enum.GetNames(typeof(ZXSpectrum.OSDVerbosity)); + foreach (string val in osdTypes) { osdMessageVerbositycomboBox1.Items.Add(val); } @@ -41,7 +41,7 @@ private void IntvControllerSettings_Load(object sender, EventArgs e) private void SetBtnColor() { - var c = System.Drawing.Color.FromArgb(_bgColor); + System.Drawing.Color c = System.Drawing.Color.FromArgb(_bgColor); buttonChooseBGColor.ForeColor = c; buttonChooseBGColor.BackColor = c; } @@ -95,15 +95,15 @@ private void UpdateOSDNotes(ZXSpectrum.OSDVerbosity type) private void OSDComboBox_SelectionChangeCommitted(object sender, EventArgs e) { - var cb = (ComboBox)sender; + ComboBox cb = (ComboBox)sender; UpdateOSDNotes((ZXSpectrum.OSDVerbosity)Enum.Parse(typeof(ZXSpectrum.OSDVerbosity), cb.SelectedItem.ToString())); } private void buttonChooseBGColor_Click(object sender, EventArgs e) { - var currColor = _settings.BackgroundColor; + int currColor = _settings.BackgroundColor; System.Drawing.Color c = System.Drawing.Color.FromArgb(currColor); - using var cd = new ColorDialog(); + using ColorDialog cd = new(); System.Drawing.Color[] colors = { diff --git a/src/BizHawk.Client.EmuHawk/debug/FirmwareAutopatchDebugToolForm.cs b/src/BizHawk.Client.EmuHawk/debug/FirmwareAutopatchDebugToolForm.cs index 3768ab1f408..e4f981266b0 100644 --- a/src/BizHawk.Client.EmuHawk/debug/FirmwareAutopatchDebugToolForm.cs +++ b/src/BizHawk.Client.EmuHawk/debug/FirmwareAutopatchDebugToolForm.cs @@ -32,7 +32,7 @@ static string LabelFragment(string hash) SzTextBoxEx txtBaseFile = new() { Size = new(224, 23) }; void ShowBaseFilePicker() { - var filename = this.ShowFileSaveDialog(initDir: Config!.PathEntries.FirmwareAbsolutePath()); + string? filename = this.ShowFileSaveDialog(initDir: Config!.PathEntries.FirmwareAbsolutePath()); if (filename is not null) txtBaseFile.Text = filename; } CheckBoxEx cbDryRun = new() { Checked = true, Text = "dry run (skip writing to disk)" }; @@ -48,7 +48,7 @@ void DoPatch() this.ModalMessageBox($"wrote {filePath}"); return; } - var @base = File.ReadAllBytes(txtBaseFile.Text); + byte[] @base = File.ReadAllBytes(txtBaseFile.Text); var (_, actualHash) = FirmwareManager.PerformPatchInMemory(@base, in fpo); if (actualHash == fpo.TargetHash) { @@ -56,7 +56,7 @@ void DoPatch() return; } // else something happened, figure out what it was - var baseHash = SHA1Checksum.ComputeDigestHex(@base); + string baseHash = SHA1Checksum.ComputeDigestHex(@base); this.ModalMessageBox(baseHash == fpo.BaseHash ? $"patchset declared with target\nSHA1:{fpo.TargetHash}\nbut produced\nSHA1:{actualHash}\n(is the patch wrong, or the hash?)" : $"patchset declared for base\nSHA1:{fpo.BaseHash}\nbut\nSHA1:{baseHash}\nwas provided"); diff --git a/src/BizHawk.Client.EmuHawk/debug/N64RomByteswapToolForm.cs b/src/BizHawk.Client.EmuHawk/debug/N64RomByteswapToolForm.cs index 5154b2ba896..c73a553aac4 100644 --- a/src/BizHawk.Client.EmuHawk/debug/N64RomByteswapToolForm.cs +++ b/src/BizHawk.Client.EmuHawk/debug/N64RomByteswapToolForm.cs @@ -23,7 +23,7 @@ public N64RomByteswapToolForm() SzTextBoxEx txtBaseFile = new() { Size = new(224, 23) }; void ChooseBaseFile() { - var filename = this.ShowFileOpenDialog(initDir: Config!.PathEntries.RomAbsolutePath()); + string? filename = this.ShowFileOpenDialog(initDir: Config!.PathEntries.RomAbsolutePath()); if (filename is not null) txtBaseFile.Text = filename; } ComboBox comboFormats = new() @@ -35,7 +35,7 @@ void ChooseBaseFile() SzTextBoxEx txtTargetFile = new() { Size = new(224, 23) }; void ChooseTargetFile() { - var filename = this.ShowFileSaveDialog( + string? filename = this.ShowFileSaveDialog( fileExt: comboFormats.SelectedIndex switch { 0 => "n64", @@ -50,7 +50,7 @@ void DoConvert() { try { - var rom = File.ReadAllBytes(txtBaseFile.Text); + byte[] rom = File.ReadAllBytes(txtBaseFile.Text); _ = comboFormats.SelectedIndex switch { 0 => N64RomByteswapper.ToN64LittleEndian(rom), diff --git a/src/BizHawk.Client.EmuHawk/debug/N64VideoSettingsFuzzToolForm.cs b/src/BizHawk.Client.EmuHawk/debug/N64VideoSettingsFuzzToolForm.cs index 5de980f9ab4..9fa8c9ce04d 100644 --- a/src/BizHawk.Client.EmuHawk/debug/N64VideoSettingsFuzzToolForm.cs +++ b/src/BizHawk.Client.EmuHawk/debug/N64VideoSettingsFuzzToolForm.cs @@ -45,11 +45,11 @@ public N64VideoSettingsFuzzToolForm() Random rng = new(); void Fuzz(bool limit) { - var props = propDict.Keys.ToList(); + List props = propDict.Keys.ToList(); if (limit) { props.Sort((_, _) => rng.Next(2)); - var l = props.Count / 10; + int l = props.Count / 10; while (l < props.Count) props.RemoveAt(l); } var ss = Emulator.GetSyncSettings(); diff --git a/src/BizHawk.Client.EmuHawk/movie/EditCommentsForm.cs b/src/BizHawk.Client.EmuHawk/movie/EditCommentsForm.cs index 40107cfca99..b14303c7f42 100644 --- a/src/BizHawk.Client.EmuHawk/movie/EditCommentsForm.cs +++ b/src/BizHawk.Client.EmuHawk/movie/EditCommentsForm.cs @@ -44,7 +44,7 @@ private void EditCommentsForm_Load(object sender, EventArgs e) if (CommentGrid.Rows.Count > 8) { - var x = Height + ((CommentGrid.Rows.Count - 8) * 21); + int x = Height + ((CommentGrid.Rows.Count - 8) * 21); Height = x < 600 ? x : 600; } } @@ -61,10 +61,7 @@ private void Save() _movie.Save(); } - private void Cancel_Click(object sender, EventArgs e) - { - Close(); - } + private void Cancel_Click(object sender, EventArgs e) => Close(); private void Ok_Click(object sender, EventArgs e) { @@ -72,19 +69,13 @@ private void Ok_Click(object sender, EventArgs e) Close(); } - private void SaveBtn_Click(object sender, EventArgs e) - { - Save(); - } + private void SaveBtn_Click(object sender, EventArgs e) => Save(); - private void OnColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) - { - SortColumn(CommentGrid.Columns[e.ColumnIndex]); - } + private void OnColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) => SortColumn(CommentGrid.Columns[e.ColumnIndex]); private void SortColumn(DataGridViewColumn e) { - DataGridViewColumn column = e; + var column = e; if (_lastHeaderClicked != column.Name) { _sortReverse = false; diff --git a/src/BizHawk.Client.EmuHawk/movie/EditSubtitlesForm.cs b/src/BizHawk.Client.EmuHawk/movie/EditSubtitlesForm.cs index 17c351be9ef..edb1b897e45 100644 --- a/src/BizHawk.Client.EmuHawk/movie/EditSubtitlesForm.cs +++ b/src/BizHawk.Client.EmuHawk/movie/EditSubtitlesForm.cs @@ -32,7 +32,7 @@ public EditSubtitlesForm(IDialogController dialogController, IMovie movie, PathE private void EditSubtitlesForm_Load(object sender, EventArgs e) { - var subs = new SubtitleList(); + SubtitleList subs = new(); subs.AddRange(_selectedMovie.Subtitles); for (int x = 0; x < subs.Count; x++) @@ -67,21 +67,18 @@ private void EditSubtitlesForm_Load(object sender, EventArgs e) if (SubGrid.Rows.Count > 8) { - var x = Height + ((SubGrid.Rows.Count - 8) * 21); + int x = Height + ((SubGrid.Rows.Count - 8) * 21); Height = x < 600 ? x : 600; } } - private void Cancel_Click(object sender, EventArgs e) - { - Close(); - } + private void Cancel_Click(object sender, EventArgs e) => Close(); private void ShowError(int row, int column) { var c = SubGrid.Rows[row].Cells[column]; - var error = $"Unable to parse value: {c.Value}"; - var caption = $"Parse Error Row {row} Column {column}"; + string error = $"Unable to parse value: {c.Value}"; + string caption = $"Parse Error Row {row} Column {column}"; DialogController.ShowMessageBox(error, caption, EMsgBoxIcon.Error); } @@ -92,7 +89,7 @@ private void Ok_Click(object sender, EventArgs e) _selectedMovie.Subtitles.Clear(); for (int i = 0; i < SubGrid.Rows.Count - 1; i++) { - var sub = new Subtitle(); + Subtitle sub = new(); var c = SubGrid.Rows[i].Cells[0]; try { sub.Frame = int.Parse(c.Value.ToString()); } @@ -148,8 +145,8 @@ private Subtitle GetRow(int index) { return new Subtitle(); } - - var sub = new Subtitle(); + + Subtitle sub = new(); if (int.TryParse(SubGrid.Rows[index].Cells[0].Value.ToString(), out int frame)) { @@ -195,7 +192,7 @@ private void SubGrid_MouseDoubleClick(object sender, MouseEventArgs e) return; } - using var s = new SubtitleMaker { Sub = GetRow(c[0].Index) }; + using SubtitleMaker s = new() { Sub = GetRow(c[0].Index) }; if (s.ShowDialog().IsOk()) { ChangeRow(s.Sub, SubGrid.SelectedRows[0].Index); @@ -205,7 +202,7 @@ private void SubGrid_MouseDoubleClick(object sender, MouseEventArgs e) private void Export_Click(object sender, EventArgs e) { // Get file to save as - var fileName = this.ShowFileSaveDialog( + string fileName = this.ShowFileSaveDialog( filter: SubRipFilesFSFilterSet, initDir: _pathEntries.MovieAbsolutePath()); if (fileName is null) return; @@ -224,7 +221,7 @@ private void Export_Click(object sender, EventArgs e) } // Create string and write to file - var str = _selectedMovie.Subtitles.ToSubRip(fps); + string str = _selectedMovie.Subtitles.ToSubRip(fps); File.WriteAllText(fileName, str); // Display success @@ -240,29 +237,23 @@ private void SubGrid_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e.Row.Cells["DispColor"].Value = "FFFFFFFF"; } - private void ConcatMultilines_CheckedChanged(object sender, EventArgs e) - { - _selectedMovie.Subtitles.ConcatMultilines = ConcatMultilines.Checked; - } + private void ConcatMultilines_CheckedChanged(object sender, EventArgs e) => _selectedMovie.Subtitles.ConcatMultilines = ConcatMultilines.Checked; - private void AddColorTag_CheckedChanged(object sender, EventArgs e) - { - _selectedMovie.Subtitles.AddColorTag = AddColorTag.Checked; - } + private void AddColorTag_CheckedChanged(object sender, EventArgs e) => _selectedMovie.Subtitles.AddColorTag = AddColorTag.Checked; private void SubGrid_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (!_readOnly && e.ColumnIndex == 4) { var color = Color.White; - var val = SubGrid[e.ColumnIndex, e.RowIndex].Value; + object val = SubGrid[e.ColumnIndex, e.RowIndex].Value; if (val != null) { - var hex = int.Parse(val.ToString(), NumberStyles.HexNumber); + int hex = int.Parse(val.ToString(), NumberStyles.HexNumber); color = Color.FromArgb(hex); } - using var picker = new ColorDialog { AllowFullOpen = true, AnyColor = true, Color = color }; + using ColorDialog picker = new() { AllowFullOpen = true, AnyColor = true, Color = color }; if (picker.ShowDialog().IsOk()) { SubGrid[e.ColumnIndex, e.RowIndex].Value = picker.Color.ToArgb().ToHexString(8); diff --git a/src/BizHawk.Client.EmuHawk/movie/PlayMovie.cs b/src/BizHawk.Client.EmuHawk/movie/PlayMovie.cs index dbca1eee1d0..209d540b0d9 100644 --- a/src/BizHawk.Client.EmuHawk/movie/PlayMovie.cs +++ b/src/BizHawk.Client.EmuHawk/movie/PlayMovie.cs @@ -107,7 +107,7 @@ private void Run() private int? AddMovieToList(string filename, bool force) { - using var file = new HawkFile(filename); + using HawkFile file = new(filename); if (!file.Exists) { return null; @@ -141,7 +141,7 @@ private void Run() private int? IsDuplicateOf(string filename) { - for (var i = 0; i < _movieList.Count; i++) + for (int i = 0; i < _movieList.Count; i++) { if (_movieList[i].Filename == filename) { @@ -189,10 +189,10 @@ private void PreHighlightMovie() return; } - var indices = new List(); + List indices = new(); // Pull out matching names - for (var i = 0; i < _movieList.Count; i++) + for (int i = 0; i < _movieList.Count; i++) { if (_game.FilesystemSafeName() == _movieList[i].GameName) { @@ -213,10 +213,10 @@ private void PreHighlightMovie() // Prefer tas files // but `_movieList` should only contain `.bk2` and `.tasproj` so... isn't that all of them? or, it is now I've fixed the case-sensitivity bug --yoshi - var tas = new List(); - for (var i = 0; i < indices.Count; i++) + List tas = new(); + for (int i = 0; i < indices.Count; i++) { - foreach (var ext in MovieService.MovieExtensions) + foreach (string ext in MovieService.MovieExtensions) { if ($".{ext}".Equals(Path.GetExtension(_movieList[indices[i]].Filename), StringComparison.OrdinalIgnoreCase)) { @@ -255,12 +255,12 @@ private void ScanFiles() MovieView.VirtualListSize = 0; MovieView.Update(); - var directory = _config.PathEntries.MovieAbsolutePath(); + string directory = _config.PathEntries.MovieAbsolutePath(); Directory.CreateDirectory(directory); - var dpTodo = new Queue(); - var fpTodo = new List(); + Queue dpTodo = new(); + List fpTodo = new(); dpTodo.Enqueue(directory); - var ordinals = new Dictionary(); + Dictionary ordinals = new(); while (dpTodo.Count > 0) { @@ -269,14 +269,14 @@ private void ScanFiles() // enqueue subdirectories if appropriate if (_config.PlayMovieIncludeSubDir) { - foreach (var subDir in Directory.GetDirectories(dp)) + foreach (string subDir in Directory.GetDirectories(dp)) { dpTodo.Enqueue(subDir); } } // add movies - foreach (var extension in MovieService.MovieExtensions) + foreach (string extension in MovieService.MovieExtensions) { fpTodo.AddRange(Directory.GetFiles(dp, $"*.{extension}")); } @@ -285,7 +285,7 @@ private void ScanFiles() // in parallel, scan each movie Parallel.For(0, fpTodo.Count, i => { - var file = fpTodo[i]; + string file = fpTodo[i]; lock (ordinals) { ordinals[file] = i; @@ -306,16 +306,13 @@ private void RefreshMovieList() UpdateList(); } - private void MovieView_DragEnter(object sender, DragEventArgs e) - { - e.Set(DragDropEffects.Copy); - } + private void MovieView_DragEnter(object sender, DragEventArgs e) => e.Set(DragDropEffects.Copy); private void MovieView_DragDrop(object sender, DragEventArgs e) { - var filePaths = (string[])e.Data.GetData(DataFormats.FileDrop); + string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop); - foreach (var path in filePaths.Where(path => MovieService.MovieExtensions.Contains(Path.GetExtension(path)?.Replace(".", "")))) + foreach (string path in filePaths.Where(path => MovieService.MovieExtensions.Contains(Path.GetExtension(path)?.Replace(".", "")))) { AddMovieToList(path, force: true); } @@ -330,7 +327,7 @@ private void MovieView_KeyDown(object sender, KeyEventArgs e) var indexes = MovieView.SelectedIndices; if (indexes.Count > 0) { - var copyStr = new StringBuilder(); + StringBuilder copyStr = new(); foreach (int index in indexes) { copyStr @@ -363,7 +360,7 @@ private static readonly RigidMultiPredicateSort ColumnSorts private void MovieView_ColumnClick(object sender, ColumnClickEventArgs e) { - var columnName = MovieView.Columns[e.Column].Text; + string columnName = MovieView.Columns[e.Column].Text; _movieList = ColumnSorts.AppliedTo(_movieList, columnName); if (_sortedCol == columnName && _sortReverse) { @@ -389,12 +386,12 @@ private void MovieView_SelectedIndexChanged(object sender, EventArgs e) OK.Enabled = true; - var firstIndex = MovieView.SelectedIndices[0]; + int firstIndex = MovieView.SelectedIndices[0]; MovieView.EnsureVisible(firstIndex); foreach (var (k, v) in _movieList[firstIndex].HeaderEntries) { - var item = new ListViewItem(k); + ListViewItem item = new(k); item.SubItems.Add(v); item.ToolTipText = v; switch (k) @@ -430,8 +427,8 @@ private void MovieView_SelectedIndexChanged(object sender, EventArgs e) default: if (k.Contains("_Firmware_")) { - var split = k.Split(new[] { "_Firmware_" }, StringSplitOptions.None); - var actualHash = _canProvideFirmware(new(split[0], split[1]), v); + string[] split = k.Split(new[] { "_Firmware_" }, StringSplitOptions.None); + string actualHash = _canProvideFirmware(new(split[0], split[1]), v); if (actualHash != v) { item.BackColor = Color.Yellow; @@ -444,11 +441,11 @@ private void MovieView_SelectedIndexChanged(object sender, EventArgs e) DetailsView.Items.Add(item); } - var fpsItem = new ListViewItem("Fps"); + ListViewItem fpsItem = new("Fps"); fpsItem.SubItems.Add($"{_movieList[firstIndex].FrameRate:0.#######}"); DetailsView.Items.Add(fpsItem); - var framesItem = new ListViewItem("Frames"); + ListViewItem framesItem = new("Frames"); framesItem.SubItems.Add(_movieList[firstIndex].FrameCount.ToString()); DetailsView.Items.Add(framesItem); CommentsBtn.Enabled = _movieList[firstIndex].Comments.Any(); @@ -466,8 +463,8 @@ private void EditMenuItem_Click(object sender, EventArgs e) private void DetailsView_ColumnClick(object sender, ColumnClickEventArgs e) { - var detailsList = new List(); - for (var i = 0; i < DetailsView.Items.Count; i++) + List detailsList = new(); + for (int i = 0; i < DetailsView.Items.Count; i++) { detailsList.Add(new MovieDetails { @@ -477,7 +474,7 @@ private void DetailsView_ColumnClick(object sender, ColumnClickEventArgs e) }); } - var columnName = DetailsView.Columns[e.Column].Text; + string columnName = DetailsView.Columns[e.Column].Text; if (_sortedDetailsCol != columnName) { _sortDetailsReverse = false; @@ -499,7 +496,7 @@ private void DetailsView_ColumnClick(object sender, ColumnClickEventArgs e) DetailsView.Items.Clear(); foreach (var detail in detailsList) { - var item = new ListViewItem { Text = detail.Keys, BackColor = detail.BackgroundColor }; + ListViewItem item = new() { Text = detail.Keys, BackColor = detail.BackgroundColor }; item.SubItems.Add(detail.Values); DetailsView.Items.Add(item); } @@ -517,7 +514,7 @@ private void CommentsBtn_Click(object sender, EventArgs e) var movie = _movieSession.Get(_movieList[MovieView.SelectedIndices[0]].Filename); movie.Load(); // TODO movie should be disposed if movie is ITasMovie - var form = new EditCommentsForm(movie, _movieSession.ReadOnly); + EditCommentsForm form = new(movie, _movieSession.ReadOnly); form.Show(); } } @@ -538,7 +535,7 @@ private void SubtitlesBtn_Click(object sender, EventArgs e) private void BrowseMovies_Click(object sender, EventArgs e) { - var result = this.ShowFileOpenDialog( + string result = this.ShowFileOpenDialog( filter: MoviesFSFilterSet, initDir: _config.PathEntries.MovieAbsolutePath()); if (result is null) return; @@ -598,10 +595,7 @@ private void Ok_Click(object sender, EventArgs e) Close(); } - private void Cancel_Click(object sender, EventArgs e) - { - Close(); - } + private void Cancel_Click(object sender, EventArgs e) => Close(); private bool _programmaticallyChangingStopFrameCheckbox; private bool _suppressCheckedChanged; diff --git a/src/BizHawk.Client.EmuHawk/movie/RecordMovie.cs b/src/BizHawk.Client.EmuHawk/movie/RecordMovie.cs index 467a048a430..8c236394815 100644 --- a/src/BizHawk.Client.EmuHawk/movie/RecordMovie.cs +++ b/src/BizHawk.Client.EmuHawk/movie/RecordMovie.cs @@ -183,7 +183,7 @@ public RecordMovie( private string MakePath() { - var path = RecordBox.Text; + string path = RecordBox.Text; if (!string.IsNullOrWhiteSpace(path)) { @@ -209,13 +209,13 @@ private string MakePath() private void Ok_Click(object sender, EventArgs e) { - var path = MakePath(); + string path = MakePath(); if (!string.IsNullOrWhiteSpace(path)) { - var test = new FileInfo(path); + FileInfo test = new(path); if (test.Exists) { - var result = DialogController.ShowMessageBox2($"{path} already exists, overwrite?", "Confirm overwrite", EMsgBoxIcon.Warning, useOKCancel: true); + bool result = DialogController.ShowMessageBox2($"{path} already exists, overwrite?", "Confirm overwrite", EMsgBoxIcon.Warning, useOKCancel: true); if (!result) { return; @@ -224,7 +224,7 @@ private void Ok_Click(object sender, EventArgs e) var movieToRecord = _movieSession.Get(path); - var fileInfo = new FileInfo(path); + FileInfo fileInfo = new(path); if (!fileInfo.Exists) { Directory.CreateDirectory(fileInfo.DirectoryName); @@ -242,7 +242,7 @@ private void Ok_Click(object sender, EventArgs e) } else { - using var sw = new StringWriter(); + using StringWriter sw = new(); core.SaveStateText(sw); movieToRecord.TextSavestate = sw.ToString(); } @@ -284,10 +284,7 @@ private void Ok_Click(object sender, EventArgs e) } } - private void Cancel_Click(object sender, EventArgs e) - { - Close(); - } + private void Cancel_Click(object sender, EventArgs e) => Close(); private void BrowseBtn_Click(object sender, EventArgs e) { @@ -301,7 +298,7 @@ private void BrowseBtn_Click(object sender, EventArgs e) catch (Exception movieDirException) { if (movieDirException is IOException - || movieDirException is UnauthorizedAccessException) + or UnauthorizedAccessException) { //TO DO : Pass error to user? } @@ -309,7 +306,7 @@ private void BrowseBtn_Click(object sender, EventArgs e) } var filterset = _movieSession.Movie.GetFSFilterSet(); - var result = this.ShowFileSaveDialog( + string result = this.ShowFileSaveDialog( fileExt: $".{filterset.Filters[0].Extensions.First()}", filter: filterset, initDir: movieFolderPath, @@ -329,14 +326,11 @@ private void RecordMovie_Load(object sender, EventArgs e) } } - private void RecordBox_DragEnter(object sender, DragEventArgs e) - { - e.Set(DragDropEffects.Copy); - } + private void RecordBox_DragEnter(object sender, DragEventArgs e) => e.Set(DragDropEffects.Copy); private void RecordBox_DragDrop(object sender, DragEventArgs e) { - var filePaths = (string[])e.Data.GetData(DataFormats.FileDrop); + string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop); RecordBox.Text = filePaths[0]; } } diff --git a/src/BizHawk.Client.EmuHawk/movie/SubtitleMaker.cs b/src/BizHawk.Client.EmuHawk/movie/SubtitleMaker.cs index 621b808f527..d0d8aa84185 100644 --- a/src/BizHawk.Client.EmuHawk/movie/SubtitleMaker.cs +++ b/src/BizHawk.Client.EmuHawk/movie/SubtitleMaker.cs @@ -16,15 +16,9 @@ public SubtitleMaker() Icon = Properties.Resources.TAStudioIcon; } - public void DisableFrame() - { - FrameNumeric.Enabled = false; - } + public void DisableFrame() => FrameNumeric.Enabled = false; - private void Cancel_Click(object sender, EventArgs e) - { - Close(); - } + private void Cancel_Click(object sender, EventArgs e) => Close(); private void Ok_Click(object sender, EventArgs e) { diff --git a/src/BizHawk.Client.EmuHawk/tools/BasicBot/BasicBot.cs b/src/BizHawk.Client.EmuHawk/tools/BasicBot/BasicBot.cs index fd4b67794d9..ec75551c5ff 100644 --- a/src/BizHawk.Client.EmuHawk/tools/BasicBot/BasicBot.cs +++ b/src/BizHawk.Client.EmuHawk/tools/BasicBot/BasicBot.cs @@ -44,8 +44,8 @@ private string CurrentFileName private long _frames; private int _targetFrame; private bool _oldCountingSetting; - private BotAttempt _currentBotAttempt; - private BotAttempt _bestBotAttempt; + private readonly BotAttempt _currentBotAttempt; + private readonly BotAttempt _bestBotAttempt; private readonly BotAttempt _comparisonBotAttempt; private bool _replayMode; private int _startFrame; @@ -252,7 +252,7 @@ public string FromSlot set { - var item = StartFromSlotBox.Items + object item = StartFromSlotBox.Items .OfType() .FirstOrDefault(o => o.ToString() == value); @@ -295,10 +295,7 @@ public override void Restart() } } - private void FileSubMenu_DropDownOpened(object sender, EventArgs e) - { - SaveMenuItem.Enabled = !string.IsNullOrWhiteSpace(CurrentFileName); - } + private void FileSubMenu_DropDownOpened(object sender, EventArgs e) => SaveMenuItem.Enabled = !string.IsNullOrWhiteSpace(CurrentFileName); private void RecentSubMenu_DropDownOpened(object sender, EventArgs e) => RecentSubMenu.ReplaceDropDownItems(Settings.RecentBotFiles.RecentMenu(this, LoadFileFromRecent, "Bot Parameters")); @@ -359,7 +356,7 @@ private void SaveMenuItem_Click(object sender, EventArgs e) private void SaveAsMenuItem_Click(object sender, EventArgs e) { - var fileName = CurrentFileName; + string fileName = CurrentFileName; if (string.IsNullOrWhiteSpace(fileName)) { fileName = Game.FilesystemSafeName(); @@ -387,10 +384,7 @@ private void OptionsSubMenu_DropDownOpened(object sender, EventArgs e) private void MemoryDomainsMenuItem_DropDownOpened(object sender, EventArgs e) => MemoryDomainsMenuItem.ReplaceDropDownItems(MemoryDomains.MenuItems(SetMemoryDomain, _currentDomain.Name).ToArray()); - private void BigEndianMenuItem_Click(object sender, EventArgs e) - { - _bigEndian ^= true; - } + private void BigEndianMenuItem_Click(object sender, EventArgs e) => _bigEndian ^= true; private void DataSizeMenuItem_DropDownOpened(object sender, EventArgs e) { @@ -399,35 +393,17 @@ private void DataSizeMenuItem_DropDownOpened(object sender, EventArgs e) _4ByteMenuItem.Checked = _dataSize == 4; } - private void OneByteMenuItem_Click(object sender, EventArgs e) - { - _dataSize = 1; - } + private void OneByteMenuItem_Click(object sender, EventArgs e) => _dataSize = 1; - private void TwoByteMenuItem_Click(object sender, EventArgs e) - { - _dataSize = 2; - } + private void TwoByteMenuItem_Click(object sender, EventArgs e) => _dataSize = 2; - private void FourByteMenuItem_Click(object sender, EventArgs e) - { - _dataSize = 4; - } + private void FourByteMenuItem_Click(object sender, EventArgs e) => _dataSize = 4; - private void TurboWhileBottingMenuItem_Click(object sender, EventArgs e) - { - Settings.TurboWhenBotting ^= true; - } + private void TurboWhileBottingMenuItem_Click(object sender, EventArgs e) => Settings.TurboWhenBotting ^= true; - private void RunBtn_Click(object sender, EventArgs e) - { - StartBot(); - } + private void RunBtn_Click(object sender, EventArgs e) => StartBot(); - private void StopBtn_Click(object sender, EventArgs e) - { - StopBot(); - } + private void StopBtn_Click(object sender, EventArgs e) => StopBot(); private void ClearBestButton_Click(object sender, EventArgs e) { @@ -445,10 +421,10 @@ private void PlayBestButton_Click(object sender, EventArgs e) _doNotUpdateValues = true; // here we need to apply the initial frame's input from the best attempt - var logEntry = _bestBotAttempt.Log[0]; + string logEntry = _bestBotAttempt.Log[0]; var controller = MovieSession.GenerateMovieController(); controller.SetFromMnemonic(logEntry); - foreach (var button in controller.Definition.BoolButtons) + foreach (string button in controller.Definition.BoolButtons) { // TODO: make an input adapter specifically for the bot? InputManager.ButtonOverrideAdapter.SetButton(button, controller.IsPressed(button)); @@ -466,10 +442,7 @@ private void PlayBestButton_Click(object sender, EventArgs e) MainForm.UnpauseEmulator(); } - private void FrameLengthNumeric_ValueChanged(object sender, EventArgs e) - { - AssessRunButtonStatus(); - } + private void FrameLengthNumeric_ValueChanged(object sender, EventArgs e) => AssessRunButtonStatus(); private void ClearStatsContextMenuItem_Click(object sender, EventArgs e) { @@ -566,7 +539,7 @@ private class BotData private void LoadFileFromRecent(string path) { - var result = LoadBotFile(path); + bool result = LoadBotFile(path); if (!result && !File.Exists(path)) { Settings.RecentBotFiles.HandleLoadError(MainForm, path); @@ -593,12 +566,12 @@ private bool LoadBotFile(string path) // else grandfathered (made with old version, sysID unknowable), user has been warned } // if something else is off, though, let the user decide - var hawkVersionMatches = VersionInfo.DeveloperBuild || botData.HawkVersion == VersionInfo.GetEmuVersion(); - var coreNameMatches = botData.CoreName == Emulator.Attributes().CoreName; - var gameNameMatches = botData.GameName == Game.Name; + bool hawkVersionMatches = VersionInfo.DeveloperBuild || botData.HawkVersion == VersionInfo.GetEmuVersion(); + bool coreNameMatches = botData.CoreName == Emulator.Attributes().CoreName; + bool gameNameMatches = botData.GameName == Game.Name; if (!(hawkVersionMatches && coreNameMatches && gameNameMatches)) { - var s = hawkVersionMatches + string s = hawkVersionMatches ? coreNameMatches ? string.Empty : $" with a different core ({botData.CoreName ?? "unknown"})" @@ -646,7 +619,7 @@ private void LoadBotFileInner(BotData botData, string path) _bestBotAttempt.is_Reset = false; - var probabilityControls = ControlProbabilityPanel.Controls + List probabilityControls = ControlProbabilityPanel.Controls .OfType() .ToList(); @@ -731,7 +704,7 @@ private void LoadBotFileInner(BotData botData, string path) private void SaveBotFile(string path) { - var data = new BotData + BotData data = new() { Best = _bestBotAttempt, ControlProbabilities = ControlProbabilities, @@ -764,7 +737,7 @@ private void SaveBotFile(string path) GameName = Game.Name, }; - var json = ConfigService.SaveWithType(data); + string json = ConfigService.SaveWithType(data); File.WriteAllText(path, json); CurrentFileName = path; @@ -772,12 +745,10 @@ private void SaveBotFile(string path) MessageLabel.Text = $"{Path.GetFileName(CurrentFileName)} saved"; } - public bool HasFrameAdvanced() - { + public bool HasFrameAdvanced() => // If the emulator frame is different from the last time it tried calling // the function then we can continue, otherwise we need to stop. - return _lastFrameAdvanced != Emulator.Frame; - } + _lastFrameAdvanced != Emulator.Frame; private void SetupControlsAndProperties() { MaximizeAddressBox.SetHexProperties(_currentDomain.Size); @@ -795,9 +766,9 @@ private void SetupControlsAndProperties() ControlProbabilityPanel.SuspendLayout(); ControlProbabilityPanel.Controls.Clear(); - foreach (var button in Emulator.ControllerDefinition.BoolButtons) + foreach (string button in Emulator.ControllerDefinition.BoolButtons) { - var control = new BotControlsRow + BotControlsRow control = new() { ButtonName = button, Probability = 0.0, @@ -836,8 +807,8 @@ private void SetMemoryDomain(string name) private int GetRamValue(ulong? address) { if (address is null) return 0; - var addr = checked((long) address); //TODO MemoryDomain needs converting one day - var val = _dataSize switch + long addr = checked((long) address); //TODO MemoryDomain needs converting one day + int val = _dataSize switch { 1 => _currentDomain.PeekByte(addr), 2 => _currentDomain.PeekUshort(addr, _bigEndian), @@ -866,10 +837,10 @@ private void Update(bool fast) if (index < _bestBotAttempt.Log.Count) { - var logEntry = _bestBotAttempt.Log[index]; + string logEntry = _bestBotAttempt.Log[index]; var controller = MovieSession.GenerateMovieController(); controller.SetFromMnemonic(logEntry); - foreach (var button in controller.Definition.BoolButtons) + foreach (string button in controller.Definition.BoolButtons) { // TODO: make an input adapter specifically for the bot? InputManager.ButtonOverrideAdapter.SetButton(button, controller.IsPressed(button)); @@ -969,8 +940,8 @@ private void UpdateBestAttempt() BestTieBreak2Box.Text = _bestBotAttempt.TieBreak2.ToString(); BestTieBreak3Box.Text = _bestBotAttempt.TieBreak3.ToString(); - var sb = new StringBuilder(); - foreach (var logEntry in _bestBotAttempt.Log) + StringBuilder sb = new(); + foreach (string logEntry in _bestBotAttempt.Log) { sb.AppendLine(logEntry); } @@ -994,9 +965,9 @@ private void UpdateBestAttempt() private void PressButtons(bool clear_log) { - var rand = new Random((int)DateTime.Now.Ticks); + Random rand = new((int)DateTime.Now.Ticks); - foreach (var button in Emulator.ControllerDefinition.BoolButtons) + foreach (string button in Emulator.ControllerDefinition.BoolButtons) { double probability = _cachedControlProbabilities[button]; bool pressed = !(rand.Next(100) < probability); @@ -1011,7 +982,7 @@ private void PressButtons(bool clear_log) private void StartBot() { - var message = CanStart(); + string message = CanStart(); if (!string.IsNullOrWhiteSpace(message)) { DialogController.ShowMessageBox(message); @@ -1124,15 +1095,9 @@ private void UpdateBotStatusIcon() } } - private void SetMaxSpeed() - { - MainForm.Unthrottle(); - } + private void SetMaxSpeed() => MainForm.Unthrottle(); - private void SetNormalSpeed() - { - MainForm.Throttle(); - } + private void SetNormalSpeed() => MainForm.Throttle(); private void AssessRunButtonStatus() { @@ -1290,24 +1255,12 @@ private void TieBreak3Numeric_ValueChanged(object sender, EventArgs e) } // Copy to Clipboard - private void BtnCopyBestInput_Click(object sender, EventArgs e) - { - Clipboard.SetText(BestAttemptLogLabel.Text); - } + private void BtnCopyBestInput_Click(object sender, EventArgs e) => Clipboard.SetText(BestAttemptLogLabel.Text); - private void HelpToolStripMenuItem_Click(object sender, EventArgs e) - { - Process.Start("https://tasvideos.org/Bizhawk/BasicBot"); - } + private void HelpToolStripMenuItem_Click(object sender, EventArgs e) => Process.Start("https://tasvideos.org/Bizhawk/BasicBot"); - private void InvisibleEmulationCheckBox_CheckedChanged(object sender, EventArgs e) - { - Settings.InvisibleEmulation ^= true; - } + private void InvisibleEmulationCheckBox_CheckedChanged(object sender, EventArgs e) => Settings.InvisibleEmulation ^= true; - private void MaximizeAddressBox_TextChanged(object sender, EventArgs e) - { - AssessRunButtonStatus(); - } + private void MaximizeAddressBox_TextChanged(object sender, EventArgs e) => AssessRunButtonStatus(); } } diff --git a/src/BizHawk.Client.EmuHawk/tools/BatchRun.cs b/src/BizHawk.Client.EmuHawk/tools/BatchRun.cs index bef6713fb2f..db39361797e 100644 --- a/src/BizHawk.Client.EmuHawk/tools/BatchRun.cs +++ b/src/BizHawk.Client.EmuHawk/tools/BatchRun.cs @@ -30,15 +30,9 @@ public BatchRun(IDialogController dialogController, Config config, Func e.Set(DragDropEffects.Link); - private void SetCount() - { - label2.Text = $"Number of files: {listBox1.Items.Count}"; - } + private void SetCount() => label2.Text = $"Number of files: {listBox1.Items.Count}"; private void ListBox1_DragDrop(object sender, DragEventArgs e) { @@ -72,7 +66,7 @@ private void ButtonGo_Click(object sender, EventArgs e) { label3.Text = "Status: Running..."; int numFrames = (int)numericUpDownFrames.Value; - var files = new List(listBox1.Items.Count); + List files = new(listBox1.Items.Count); foreach (string s in listBox1.Items) { files.Add(s); @@ -94,8 +88,8 @@ private void ThreadProc(object o) { try { - var pp = (Tuple>)o; - BatchRunner br = new BatchRunner(_config, _createCoreComm(), pp.Item2, pp.Item1); + Tuple> pp = (Tuple>)o; + BatchRunner br = new(_config, _createCoreComm(), pp.Item2, pp.Item1); br.OnProgress += BrOnProgress; var results = br.Run(); this.Invoke(() => { label3.Text = "Status: Finished!"; _mostRecentResults = results; }); @@ -130,7 +124,7 @@ private void ButtonDump_Click(object sender, EventArgs e) DialogController.ShowMessageBox("No results to save!"); return; } - var result = this.ShowFileSaveDialog(initDir: _config.PathEntries.ToolsAbsolutePath()); + string result = this.ShowFileSaveDialog(initDir: _config.PathEntries.ToolsAbsolutePath()); if (result is null) return; using TextWriter tw = new StreamWriter(result); foreach (var r in _mostRecentResults) diff --git a/src/BizHawk.Client.EmuHawk/tools/BatchRunner.cs b/src/BizHawk.Client.EmuHawk/tools/BatchRunner.cs index 5e5e8f89aa5..ec569176fb8 100644 --- a/src/BizHawk.Client.EmuHawk/tools/BatchRunner.cs +++ b/src/BizHawk.Client.EmuHawk/tools/BatchRunner.cs @@ -25,7 +25,7 @@ public ProgressEventArgs(int completed, int total) public event ProgressEventHandler OnProgress; private readonly List _files; - private readonly List _results = new List(); + private readonly List _results = new(); private readonly RomLoader _ldr; private readonly CoreComm _comm; private readonly int _numFrames; @@ -58,10 +58,7 @@ public enum EStatus public string BoardName { get; set; } // IEmulator's board name return (could be null!) - public void DumpTo(TextWriter tw) - { - tw.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}", Filename, Fullname, CoreType, Status, Frames, LaggedFrames, Game.Hash, BoardName); - } + public void DumpTo(TextWriter tw) => tw.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}", Filename, Fullname, CoreType, Status, Frames, LaggedFrames, Game.Hash, BoardName); } public BatchRunner(Config config, CoreComm comm, IEnumerable files, int numFrames) @@ -110,7 +107,7 @@ private void RunInternal() } while (_multiHasNext); if (OnProgress != null) { - var e = new ProgressEventArgs(i + 1, _files.Count); + ProgressEventArgs e = new(i + 1, _files.Count); OnProgress(this, e); if (e.ShouldCancel) { @@ -153,11 +150,11 @@ private void LoadOne(string f) return; } - using (IEmulator emu = _ldr.LoadedEmulator) + using (var emu = _ldr.LoadedEmulator) { _current.Game = _ldr.Game; _current.CoreType = emu.GetType(); - var controller = new Controller(emu.ControllerDefinition); + Controller controller = new(emu.ControllerDefinition); _current.BoardName = emu.HasBoardInfo() ? emu.AsBoardInfo().BoardName : null; _current.Frames = 0; diff --git a/src/BizHawk.Client.EmuHawk/tools/CDL.cs b/src/BizHawk.Client.EmuHawk/tools/CDL.cs index 49f1af4a16e..7182b37dcbd 100644 --- a/src/BizHawk.Client.EmuHawk/tools/CDL.cs +++ b/src/BizHawk.Client.EmuHawk/tools/CDL.cs @@ -26,14 +26,8 @@ public partial class CDL : ToolFormBase, IToolFormAutoConfig public static Icon ToolIcon => Resources.CdLoggerIcon; - private RecentFiles _recentFld = new RecentFiles(); - [ConfigPersist] - private RecentFiles _recent - { - get => _recentFld; - set => _recentFld = value; - } + private RecentFiles _recent { get; set; } = new(); [ConfigPersist] private bool CDLAutoSave { get; set; } = true; @@ -117,10 +111,7 @@ public override void Restart() UpdateDisplay(true); } - private void SetLoggingActiveCheck(bool value) - { - tsbLoggingActive.Checked = value; - } + private void SetLoggingActiveCheck(bool value) => tsbLoggingActive.Checked = value; private string[][] _listContents = Array.Empty(); @@ -175,7 +166,7 @@ private unsafe void UpdateDisplay(bool force) var bm = _cdl.GetBlockMap(); long addr = bm[scope]; - var lvi = _listContents[idx++] = new string[13]; + string[] lvi = _listContents[idx++] = new string[13]; lvi[0] = $"{addr:X8}"; lvi[1] = scope; lvi[2] = $"{total / (float) dataA.Length:P2}"; @@ -223,7 +214,7 @@ public override bool AskSaveChanges() } // 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 = DialogController.ShowMessageBox2("Save changes to CDL session?", "CDL Auto Save", EMsgBoxIcon.Question); + bool result = DialogController.ShowMessageBox2("Save changes to CDL session?", "CDL Auto Save", EMsgBoxIcon.Question); if (!result) { ShutdownCDL(); @@ -250,13 +241,13 @@ public override bool AskSaveChanges() private bool _autoloading; public void LoadFile(string path) { - using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read)) + using (FileStream fs = new(path, FileMode.Open, FileAccess.Read)) { - var newCDL = new CodeDataLog(); + CodeDataLog newCDL = new(); newCDL.Load(fs); //have the core create a CodeDataLog to check mapping information against - var testCDL = new CodeDataLog(); + CodeDataLog testCDL = new(); CodeDataLogger.NewCDL(testCDL); if (!newCDL.Check(testCDL)) { @@ -316,7 +307,7 @@ private void NewMenuItem_Click(object sender, EventArgs e) //take care not to clobber an existing CDL if (_cdl != null) { - var result = this.ModalMessageBox2("OK to create new CDL?", "Query"); + bool result = this.ModalMessageBox2("OK to create new CDL?", "Query"); if (!result) return; } @@ -336,7 +327,7 @@ private void OpenMenuItem_Click(object sender, EventArgs e) //take care not to clobber an existing CDL if (_cdl != null) { - var result = this.ModalMessageBox2("OK to load new CDL?", "Query"); + bool result = this.ModalMessageBox2("OK to load new CDL?", "Query"); if (!result) return; } @@ -346,7 +337,7 @@ private void OpenMenuItem_Click(object sender, EventArgs e) private void RunSave() { _recent.Add(_currentFilename); - using var fs = new FileStream(_currentFilename, FileMode.Create, FileAccess.Write); + using FileStream fs = new(_currentFilename, FileMode.Create, FileAccess.Write); _cdl.Save(fs); } @@ -372,7 +363,7 @@ private void SaveMenuItem_Click(object sender, EventArgs e) /// private bool RunSaveAs() { - var fileName = _currentFilename; + string fileName = _currentFilename; if (string.IsNullOrWhiteSpace(fileName)) { fileName = Game.FilesystemSafeName(); @@ -392,10 +383,7 @@ private bool RunSaveAs() return true; } - private void SaveAsMenuItem_Click(object sender, EventArgs e) - { - RunSaveAs(); - } + private void SaveAsMenuItem_Click(object sender, EventArgs e) => RunSaveAs(); private void AppendMenuItem_Click(object sender, EventArgs e) { @@ -412,8 +400,8 @@ private void AppendMenuItem_Click(object sender, EventArgs e) if (file != null) { - using var fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read); - var newCDL = new CodeDataLog(); + using FileStream fs = new(file.FullName, FileMode.Open, FileAccess.Read); + CodeDataLog newCDL = new(); newCDL.Load(fs); if (!_cdl.Check(newCDL)) { @@ -434,7 +422,7 @@ private void ClearMenuItem_Click(object sender, EventArgs e) } else { - var result = this.ModalMessageBox2("OK to clear CDL?", "Query"); + bool result = this.ModalMessageBox2("OK to clear CDL?", "Query"); if (result) { _cdl.ClearData(); @@ -450,10 +438,10 @@ private void DisassembleMenuItem_Click(object sender, EventArgs e) this.ModalMessageBox("Cannot disassemble with no CDL loaded!", "Alert"); return; } - var result = this.ShowFileSaveDialog(initDir: Config!.PathEntries.ToolsAbsolutePath()); + string result = this.ShowFileSaveDialog(initDir: Config!.PathEntries.ToolsAbsolutePath()); if (result is not null) { - using var fs = new FileStream(result, FileMode.Create, FileAccess.Write); + using FileStream fs = new(result, FileMode.Create, FileAccess.Write); CodeDataLogger.DisassembleCDL(fs, _cdl); } } @@ -492,9 +480,9 @@ private void CDL_Load(object sender, EventArgs e) try { _autoloading = true; - var autoResumeFile = $"{Game.FilesystemSafeName()}.cdl"; - var autoResumeDir = Config.PathEntries.LogAbsolutePath(); - var autoResumePath = Path.Combine(autoResumeDir, autoResumeFile); + string autoResumeFile = $"{Game.FilesystemSafeName()}.cdl"; + string autoResumeDir = Config.PathEntries.LogAbsolutePath(); + string autoResumePath = Path.Combine(autoResumeDir, autoResumeFile); if (File.Exists(autoResumePath)) { LoadFile(autoResumePath); @@ -506,7 +494,7 @@ private void CDL_Load(object sender, EventArgs e) } } - if (_recentFld.AutoLoad && !_recentFld.Empty) + if (_recent.AutoLoad && !_recent.Empty) { if (File.Exists(_recent.MostRecent)) { @@ -524,24 +512,18 @@ private void CDL_Load(object sender, EventArgs e) } } - private void CDL_DragEnter(object sender, DragEventArgs e) - { - e.Set(DragDropEffects.Copy); - } + private void CDL_DragEnter(object sender, DragEventArgs e) => e.Set(DragDropEffects.Copy); private void CDL_DragDrop(object sender, DragEventArgs e) { - var filePaths = (string[])e.Data.GetData(DataFormats.FileDrop); + string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop); if (Path.GetExtension(filePaths[0]) == ".cdl") { LoadFile(filePaths[0]); } } - private void TsbViewStyle_SelectedIndexChanged(object sender, EventArgs e) - { - UpdateDisplay(true); - } + private void TsbViewStyle_SelectedIndexChanged(object sender, EventArgs e) => UpdateDisplay(true); private void TsbLoggingActive_CheckedChanged(object sender, EventArgs e) { @@ -559,35 +541,26 @@ private void TsbLoggingActive_CheckedChanged(object sender, EventArgs e) private void LvCDL_QueryItemText(int index, RollColumn column, out string text, ref int offsetX, ref int offsetY) { - var subItem = lvCDL.AllColumns.IndexOf(column); + int subItem = lvCDL.AllColumns.IndexOf(column); text = _listContents[index][subItem]; } private void TsbExportText_Click(object sender, EventArgs e) { - using var sw = new StringWriter(); - foreach(var line in _listContents) + using StringWriter sw = new(); + foreach(string[] line in _listContents) { - foreach (var entry in line) + foreach (string entry in line) sw.Write("{0} |", entry); sw.WriteLine(); } Clipboard.SetText(sw.ToString()); } - private void MiAutoSave_Click(object sender, EventArgs e) - { - CDLAutoSave ^= true; - } + private void MiAutoSave_Click(object sender, EventArgs e) => CDLAutoSave ^= true; - private void MiAutoStart_Click(object sender, EventArgs e) - { - CDLAutoStart ^= true; - } + private void MiAutoStart_Click(object sender, EventArgs e) => CDLAutoStart ^= true; - private void MiAutoResume_Click(object sender, EventArgs e) - { - CDLAutoResume ^= true; - } + private void MiAutoResume_Click(object sender, EventArgs e) => CDLAutoResume ^= true; } } diff --git a/src/BizHawk.Client.EmuHawk/tools/Cheats/CheatEdit.cs b/src/BizHawk.Client.EmuHawk/tools/Cheats/CheatEdit.cs index 2ab34a1048b..63b47efd5f8 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Cheats/CheatEdit.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Cheats/CheatEdit.cs @@ -20,18 +20,13 @@ public CheatEdit() } private const string HexInd = "0x"; - - private Cheat _cheat; private bool _loading; private bool _editMode; private Action _addCallback; private Action _editCallback; - private void CheatEdit_Load(object sender, EventArgs e) - { - Restart(); - } + private void CheatEdit_Load(object sender, EventArgs e) => Restart(); public void Restart() { @@ -56,43 +51,43 @@ public void Restart() private void SetFormToCheat() { _loading = true; - SetSizeSelected(_cheat.Size); + SetSizeSelected(OriginalCheat.Size); PopulateTypeDropdown(); - SetTypeSelected(_cheat.Type); - SetDomainSelected(_cheat.Domain); + SetTypeSelected(OriginalCheat.Type); + SetDomainSelected(OriginalCheat.Domain); - AddressBox.SetHexProperties(_cheat.Domain.Size); + AddressBox.SetHexProperties(OriginalCheat.Domain.Size); ValueBox.ByteSize = CompareBox.ByteSize = - _cheat.Size; + OriginalCheat.Size; ValueBox.Type = CompareBox.Type = - _cheat.Type; + OriginalCheat.Type; ValueHexIndLabel.Text = CompareHexIndLabel.Text = - _cheat.Type == WatchDisplayType.Hex ? HexInd : ""; + OriginalCheat.Type == WatchDisplayType.Hex ? HexInd : ""; - BigEndianCheckBox.Checked = _cheat.BigEndian ?? false; + BigEndianCheckBox.Checked = OriginalCheat.BigEndian ?? false; - NameBox.Text = _cheat.Name; - AddressBox.Text = _cheat.AddressStr; - ValueBox.Text = _cheat.ValueStr; - CompareBox.Text = _cheat.Compare.HasValue ? _cheat.CompareStr : ""; + NameBox.Text = OriginalCheat.Name; + AddressBox.Text = OriginalCheat.AddressStr; + ValueBox.Text = OriginalCheat.ValueStr; + CompareBox.Text = OriginalCheat.Compare.HasValue ? OriginalCheat.CompareStr : ""; - if (_cheat.ComparisonType.Equals(Cheat.CompareType.None)) + if (OriginalCheat.ComparisonType.Equals(Cheat.CompareType.None)) { CompareTypeDropDown.SelectedIndex = 0; } else { - CompareTypeDropDown.SelectedIndex = (int)_cheat.ComparisonType - 1; + CompareTypeDropDown.SelectedIndex = (int)OriginalCheat.ComparisonType - 1; } CheckFormState(); - if (!_cheat.Compare.HasValue) + if (!OriginalCheat.Compare.HasValue) { CompareBox.Text = ""; // Necessary hack until WatchValueBox.ToRawInt() becomes nullable } @@ -139,24 +134,17 @@ private void SetFormToDefault() private void SetSizeSelected(WatchSize size) { - switch (size) + SizeDropDown.SelectedIndex = size switch { - default: - case WatchSize.Byte: - SizeDropDown.SelectedIndex = 0; - break; - case WatchSize.Word: - SizeDropDown.SelectedIndex = 1; - break; - case WatchSize.DWord: - SizeDropDown.SelectedIndex = 2; - break; - } + WatchSize.Word => 1, + WatchSize.DWord => 2, + _ => 0, + }; } private void SetTypeSelected(WatchDisplayType type) { - foreach (var item in DisplayTypeDropDown.Items) + foreach (object item in DisplayTypeDropDown.Items) { if (item.ToString() == Watch.DisplayTypeToString(type)) { @@ -168,7 +156,7 @@ private void SetTypeSelected(WatchDisplayType type) private void SetDomainSelected(Emu.MemoryDomain domain) { - foreach (var item in DomainDropDown.Items) + foreach (object item in DomainDropDown.Items) { if (item.ToString() == domain.Name) { @@ -185,21 +173,21 @@ private void PopulateTypeDropdown() { default: case 0: - foreach (WatchDisplayType t in ByteWatch.ValidTypes) + foreach (var t in ByteWatch.ValidTypes) { DisplayTypeDropDown.Items.Add(Watch.DisplayTypeToString(t)); } break; case 1: - foreach (WatchDisplayType t in WordWatch.ValidTypes) + foreach (var t in WordWatch.ValidTypes) { DisplayTypeDropDown.Items.Add(Watch.DisplayTypeToString(t)); } break; case 2: - foreach (WatchDisplayType t in DWordWatch.ValidTypes) + foreach (var t in DWordWatch.ValidTypes) { DisplayTypeDropDown.Items.Add(Watch.DisplayTypeToString(t)); } @@ -212,7 +200,7 @@ private void PopulateTypeDropdown() private void CheckFormState() { - var valid = !string.IsNullOrWhiteSpace(AddressBox.Text) && !string.IsNullOrWhiteSpace(ValueBox.Text); + bool valid = !string.IsNullOrWhiteSpace(AddressBox.Text) && !string.IsNullOrWhiteSpace(ValueBox.Text); AddButton.Enabled = valid; EditButton.Enabled = _editMode && valid; } @@ -240,16 +228,12 @@ private void DomainDropDown_SelectedIndexChanged(object sender, EventArgs e) private WatchSize GetCurrentSize() { - switch (SizeDropDown.SelectedIndex) + return SizeDropDown.SelectedIndex switch { - default: - case 0: - return WatchSize.Byte; - case 1: - return WatchSize.Word; - case 2: - return WatchSize.DWord; - } + 1 => WatchSize.Word, + 2 => WatchSize.DWord, + _ => WatchSize.Byte, + }; } private void DisplayTypeDropDown_SelectedIndexChanged(object sender, EventArgs e) @@ -259,20 +243,14 @@ private void DisplayTypeDropDown_SelectedIndexChanged(object sender, EventArgs e Watch.StringToDisplayType(DisplayTypeDropDown.SelectedItem.ToString()); } - private void AddButton_Click(object sender, EventArgs e) - { - _addCallback?.Invoke(); - } + private void AddButton_Click(object sender, EventArgs e) => _addCallback?.Invoke(); - private void EditButton_Click(object sender, EventArgs e) - { - _editCallback?.Invoke(); - } + private void EditButton_Click(object sender, EventArgs e) => _editCallback?.Invoke(); public void SetCheat(Cheat cheat) { _editMode = true; - _cheat = cheat; + OriginalCheat = cheat; if (cheat.IsSeparator) { SetFormToDefault(); @@ -285,20 +263,20 @@ public void SetCheat(Cheat cheat) public void ClearForm() { - _cheat = Cheat.Separator; + OriginalCheat = Cheat.Separator; _editMode = false; SetFormToDefault(); } - public Cheat OriginalCheat => _cheat; + public Cheat OriginalCheat { get; private set; } public Cheat GetCheat() { var domain = MemoryDomains[DomainDropDown.SelectedItem.ToString()]!; - var address = AddressBox.ToRawInt().Value; + int address = AddressBox.ToRawInt().Value; if (address < domain.Size) { - var watch = Watch.GenerateWatch( + Watch watch = Watch.GenerateWatch( domain, address: address, GetCurrentSize(), @@ -318,7 +296,7 @@ public Cheat GetCheat() _ => Cheat.CompareType.None }; - var compare = CompareBox.ToRawInt(); + int? compare = CompareBox.ToRawInt(); return new Cheat( watch, value: ValueBox.ToRawInt().Value, @@ -331,19 +309,13 @@ public Cheat GetCheat() return Cheat.Separator; } - public void SetAddEvent(Action addCallback) - { - _addCallback = addCallback; - } + public void SetAddEvent(Action addCallback) => _addCallback = addCallback; - public void SetEditEvent(Action editCallback) - { - _editCallback = editCallback; - } + public void SetEditEvent(Action editCallback) => _editCallback = editCallback; private void CompareBox_TextChanged(object sender, EventArgs e) { - var compareBox = (WatchValueBox)sender; + WatchValueBox compareBox = (WatchValueBox)sender; PopulateComparisonTypeBox(string.IsNullOrWhiteSpace(compareBox.Text)); } diff --git a/src/BizHawk.Client.EmuHawk/tools/Cheats/Cheats.cs b/src/BizHawk.Client.EmuHawk/tools/Cheats/Cheats.cs index a4d06c5a038..a351646f8fd 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Cheats/Cheats.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Cheats/Cheats.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; @@ -99,10 +99,10 @@ protected override void GeneralUpdate() private void LoadFileFromRecent(string path) { - var askResult = !MainForm.CheatList.Changes || AskSaveChanges(); + bool askResult = !MainForm.CheatList.Changes || AskSaveChanges(); if (askResult) { - var loadResult = MainForm.CheatList.Load(Core, path, append: false); + bool loadResult = MainForm.CheatList.Load(Core, path, append: false); if (!loadResult) { Config.Cheats.Recent.HandleLoadError(MainForm, path); @@ -128,7 +128,7 @@ private void LoadFile(FileSystemInfo file, bool append) { if (file != null) { - var result = true; + bool result = true; if (MainForm.CheatList.Changes) { result = AskSaveChanges(); @@ -145,7 +145,7 @@ private void LoadFile(FileSystemInfo file, bool append) private bool SaveAs() { - var fileName = MainForm.CheatList.CurrentFileName; + string fileName = MainForm.CheatList.CurrentFileName; if (string.IsNullOrWhiteSpace(fileName)) { fileName = Game.FilesystemSafeName(); @@ -178,10 +178,7 @@ private void SetColumns() CheatListView.Refresh(); } - private void ColumnToggleCallback() - { - Settings.Columns = CheatListView.AllColumns; - } + private void ColumnToggleCallback() => Settings.Columns = CheatListView.AllColumns; private void ToggleGameGenieButton() { @@ -223,7 +220,7 @@ private void CheatListView_QueryItemText(int index, RollColumn column, out strin return; } - var columnName = column.Name; + string columnName = column.Name; switch (columnName) { @@ -294,7 +291,7 @@ private void CheatListView_QueryItemBkColor(int index, RollColumn column, ref Co private void DoSelectedIndexChange() { - var selected = SelectedCheats.Take(2).ToList(); // is this saving that much overhead by not enumerating the whole selection? could display the row count if we did + List selected = SelectedCheats.Take(2).ToList(); // is this saving that much overhead by not enumerating the whole selection? could display the row count if we did if (selected.Count is 0) { CheatEditor.ClearForm(); @@ -317,7 +314,7 @@ private void DoSelectedIndexChange() private void StartNewList() { - var result = !MainForm.CheatList.Changes || AskSaveChanges(); + bool result = !MainForm.CheatList.Changes || AskSaveChanges(); if (result) { MainForm.CheatList.NewList(Tools.GenerateDefaultCheatFilename()); @@ -329,25 +326,19 @@ private void StartNewList() private void NewList() { - var result = !MainForm.CheatList.Changes || AskSaveChanges(); + bool result = !MainForm.CheatList.Changes || AskSaveChanges(); if (result) { StartNewList(); } } - private void FileSubMenu_DropDownOpened(object sender, EventArgs e) - { - SaveMenuItem.Enabled = MainForm.CheatList.Changes; - } + private void FileSubMenu_DropDownOpened(object sender, EventArgs e) => SaveMenuItem.Enabled = MainForm.CheatList.Changes; private void RecentSubMenu_DropDownOpened(object sender, EventArgs e) => RecentSubMenu.ReplaceDropDownItems(Config!.Cheats.Recent.RecentMenu(this, LoadFileFromRecent, "Cheats")); - private void NewMenuItem_Click(object sender, EventArgs e) - { - NewList(); - } + private void NewMenuItem_Click(object sender, EventArgs e) => NewList(); private void OpenMenuItem_Click(object sender, EventArgs e) { @@ -401,7 +392,7 @@ private void CheatsSubMenu_DropDownOpened(object sender, EventArgs e) private void RemoveCheatMenuItem_Click(object sender, EventArgs e) { - var items = SelectedItems.ToList(); + List items = SelectedItems.ToList(); if (items.Any()) { foreach (var item in items) @@ -423,13 +414,13 @@ private void InsertSeparatorMenuItem_Click(object sender, EventArgs e) private void MoveUpMenuItem_Click(object sender, EventArgs e) { - var indices = SelectedIndices.ToList(); + List indices = SelectedIndices.ToList(); if (indices.Count == 0 || indices[0] == 0) { return; } - foreach (var index in indices) + foreach (int index in indices) { var cheat = MainForm.CheatList[index]; MainForm.CheatList.Remove(cheat); @@ -439,7 +430,7 @@ private void MoveUpMenuItem_Click(object sender, EventArgs e) var newIndices = indices.Select(t => t - 1); CheatListView.DeselectAll(); - foreach (var index in newIndices) + foreach (int index in newIndices) { CheatListView.SelectRow(index, true); } @@ -450,14 +441,14 @@ private void MoveUpMenuItem_Click(object sender, EventArgs e) private void MoveDownMenuItem_Click(object sender, EventArgs e) { - var indices = SelectedIndices.ToList(); + List indices = SelectedIndices.ToList(); if (indices.Count == 0 || indices[^1] == MainForm.CheatList.Count - 1) // at end already { return; } - for (var i = indices.Count - 1; i >= 0; i--) + for (int i = indices.Count - 1; i >= 0; i--) { var cheat = MainForm.CheatList[indices[i]]; MainForm.CheatList.Remove(cheat); @@ -469,7 +460,7 @@ private void MoveDownMenuItem_Click(object sender, EventArgs e) var newIndices = indices.Select(t => t + 1); CheatListView.DeselectAll(); - foreach (var index in newIndices) + foreach (int index in newIndices) { CheatListView.SelectRow(index, true); } @@ -489,15 +480,9 @@ private void ToggleMenuItem_Click(object sender, EventArgs e) CheatListView.Refresh(); } - private void DisableAllCheatsMenuItem_Click(object sender, EventArgs e) - { - MainForm.CheatList.DisableAll(); - } + private void DisableAllCheatsMenuItem_Click(object sender, EventArgs e) => MainForm.CheatList.DisableAll(); - private void OpenGameGenieEncoderDecoderMenuItem_Click(object sender, EventArgs e) - { - Tools.Load(); - } + private void OpenGameGenieEncoderDecoderMenuItem_Click(object sender, EventArgs e) => Tools.Load(); private void SettingsSubMenu_DropDownOpened(object sender, EventArgs e) { @@ -506,21 +491,13 @@ private void SettingsSubMenu_DropDownOpened(object sender, EventArgs e) DisableCheatsOnLoadMenuItem.Checked = Config.Cheats.DisableOnLoad; } - private void AlwaysLoadCheatsMenuItem_Click(object sender, EventArgs e) - { - Config.Cheats.LoadFileByGame ^= true; - } + private void AlwaysLoadCheatsMenuItem_Click(object sender, EventArgs e) => Config.Cheats.LoadFileByGame ^= true; - private void AutoSaveCheatsMenuItem_Click(object sender, EventArgs e) - { - Config.Cheats.AutoSaveOnClose ^= true; - } + private void AutoSaveCheatsMenuItem_Click(object sender, EventArgs e) => Config.Cheats.AutoSaveOnClose ^= true; - private void CheatsOnOffLoadMenuItem_Click(object sender, EventArgs e) - { - Config.Cheats.DisableOnLoad ^= true; - } + private void CheatsOnOffLoadMenuItem_Click(object sender, EventArgs e) => Config.Cheats.DisableOnLoad ^= true; +#pragma warning disable IDE0051 [RestoreDefaults] private void RestoreDefaults() { @@ -540,11 +517,9 @@ private void RestoreDefaults() CheatListView.AllColumns.Clear(); SetColumns(); } +#pragma warning restore IDE0051 - private void CheatListView_DoubleClick(object sender, EventArgs e) - { - ToggleMenuItem_Click(sender, e); - } + private void CheatListView_DoubleClick(object sender, EventArgs e) => ToggleMenuItem_Click(sender, e); private void CheatListView_KeyDown(object sender, KeyEventArgs e) { @@ -560,10 +535,7 @@ private void CheatListView_KeyDown(object sender, KeyEventArgs e) DoSelectedIndexChange(); } - private void CheatListView_SelectedIndexChanged(object sender, EventArgs e) - { - DoSelectedIndexChange(); - } + private void CheatListView_SelectedIndexChanged(object sender, EventArgs e) => DoSelectedIndexChange(); private void CheatListView_ColumnClick(object sender, InputRoll.ColumnClickEventArgs e) { @@ -582,7 +554,7 @@ private void CheatListView_ColumnClick(object sender, InputRoll.ColumnClickEvent private void NewCheatForm_DragDrop(object sender, DragEventArgs e) { - var filePaths = (string[])e.Data.GetData(DataFormats.FileDrop); + string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop); if (Path.GetExtension(filePaths[0]) == ".cht") { LoadFile(new FileInfo(filePaths[0]), append: false); @@ -591,10 +563,7 @@ private void NewCheatForm_DragDrop(object sender, DragEventArgs e) } } - private void NewCheatForm_DragEnter(object sender, DragEventArgs e) - { - e.Set(DragDropEffects.Copy); - } + private void NewCheatForm_DragEnter(object sender, DragEventArgs e) => e.Set(DragDropEffects.Copy); private void CheatsContextMenu_Opening(object sender, CancelEventArgs e) { @@ -607,7 +576,7 @@ private void CheatsContextMenu_Opening(object sender, CancelEventArgs e) private void ViewInHexEditorContextMenuItem_Click(object sender, EventArgs e) { - var selected = SelectedCheats.ToList(); + List selected = SelectedCheats.ToList(); if (selected.Any()) { Tools.Load(); diff --git a/src/BizHawk.Client.EmuHawk/tools/Debugger/BreakpointControl.cs b/src/BizHawk.Client.EmuHawk/tools/Debugger/BreakpointControl.cs index 89d1f6b666e..7f74874cd6e 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Debugger/BreakpointControl.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Debugger/BreakpointControl.cs @@ -19,7 +19,7 @@ public partial class BreakpointControl : UserControl, IDialogParent public GenericDebugger ParentDebugger { get; set; } public IMemoryDomains MemoryDomains { get; set; } - private readonly BreakpointList _breakpoints = new BreakpointList(); + private readonly BreakpointList _breakpoints = new(); public IDialogController DialogController => MainForm; @@ -36,10 +36,7 @@ public BreakpointControl() _breakpoints.Callback = BreakpointCallback; } - private void BreakpointControl_Load(object sender, EventArgs e) - { - UpdateStatsLabel(); - } + private void BreakpointControl_Load(object sender, EventArgs e) => UpdateStatsLabel(); private void BreakPointView_QueryItemText(object sender, RetrieveVirtualItemEventArgs e) { @@ -161,7 +158,7 @@ private void AddBreakpointButton_Click(object sender, EventArgs e) public void AddSeekBreakpoint(uint pcVal, int pcBitSize) { - var name = SeekName + pcVal.ToHexString(pcBitSize / 4); + string name = SeekName + pcVal.ToHexString(pcBitSize / 4); _breakpoints.Add(new Breakpoint(name, true, Core, MemoryDomains.SystemBus.Name, SeekCallback, pcVal, 0xFFFFFFFF, MemoryCallbackType.Execute)); } @@ -186,7 +183,7 @@ private void RemoveBreakpointButton_Click(object sender, EventArgs e) { if (EditableItems.Any()) { - var items = EditableItems.ToList(); + List items = EditableItems.ToList(); if (items.Any()) { foreach (var item in items) @@ -203,21 +200,18 @@ private void RemoveBreakpointButton_Click(object sender, EventArgs e) private void UpdateBreakpointRemoveButton() { - var editableCount = EditableItems.Count(); + int editableCount = EditableItems.Count(); ToggleButton.Enabled = RemoveBreakpointButton.Enabled = editableCount > 0; DuplicateBreakpointButton.Enabled = EditBreakpointButton.Enabled = editableCount == 1; } - private void BreakpointView_SelectedIndexChanged(object sender, EventArgs e) - { - UpdateBreakpointRemoveButton(); - } + private void BreakpointView_SelectedIndexChanged(object sender, EventArgs e) => UpdateBreakpointRemoveButton(); private void BreakpointView_ItemActivate(object sender, EventArgs e) { if (EditableItems.Any()) { - var items = EditableItems.ToList(); + List items = EditableItems.ToList(); if (items.Any()) { foreach (var item in items) @@ -240,10 +234,7 @@ private void BreakpointView_KeyDown(object sender, KeyEventArgs e) } } - private void UpdateStatsLabel() - { - BreakpointStatsLabel.Text = $"{_breakpoints.Count} Total / {_breakpoints.Count(b => b.Active)} Active"; - } + private void UpdateStatsLabel() => BreakpointStatsLabel.Text = $"{_breakpoints.Count} Total / {_breakpoints.Count(b => b.Active)} Active"; private void ToggleButton_Click(object sender, EventArgs e) { @@ -299,9 +290,9 @@ private void EditBreakpointButton_Click(object sender, EventArgs e) private AddBreakpointDialog CreateAddBreakpointDialog(BreakpointOperation op, MemoryCallbackType? type = null, uint? address = null, uint? mask = null) { - var operation = (AddBreakpointDialog.BreakpointOperation)op; + AddBreakpointDialog.BreakpointOperation operation = (AddBreakpointDialog.BreakpointOperation)op; - var b = new AddBreakpointDialog(operation) + AddBreakpointDialog b = new(operation) { MaxAddressSize = MemoryDomains.SystemBus.Size - 1 }; diff --git a/src/BizHawk.Client.EmuHawk/tools/Debugger/GenericDebugger.Disassembler.cs b/src/BizHawk.Client.EmuHawk/tools/Debugger/GenericDebugger.Disassembler.cs index 0841ce7b4fd..db0cb359e2d 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Debugger/GenericDebugger.Disassembler.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Debugger/GenericDebugger.Disassembler.cs @@ -11,7 +11,7 @@ namespace BizHawk.Client.EmuHawk { public partial class GenericDebugger { - private readonly List _disassemblyLines = new List(); + private readonly List _disassemblyLines = new(); private int _pcRegisterSize = 4; private uint _currentDisassemblerAddress; @@ -61,7 +61,7 @@ private void Disassemble() uint a = _currentDisassemblerAddress; for (int i = 0; i <= lineCount; ++i) { - string line = Disassembler.Disassemble(MemoryDomains.SystemBus, a, out var advance); + string line = Disassembler.Disassemble(MemoryDomains.SystemBus, a, out int advance); _disassemblyLines.Add(new DisasmOp(a, advance, line)); a += (uint)advance; if (a > BusMaxValue) @@ -111,7 +111,7 @@ private void DecrementCurrentAddress() while (true) { - Disassembler.Disassemble(MemoryDomains.SystemBus, newaddress, out var bytestoadvance); + Disassembler.Disassemble(MemoryDomains.SystemBus, newaddress, out int bytestoadvance); if (newaddress + bytestoadvance == _currentDisassemblerAddress) { break; @@ -220,10 +220,7 @@ private void OnPauseChanged(bool isPaused) if (isPaused) FullUpdate(); } - private void DisassemblerContextMenu_Opening(object sender, EventArgs e) - { - AddBreakpointContextMenuItem.Enabled = DisassemblerView.AnyRowsSelected; - } + private void DisassemblerContextMenu_Opening(object sender, EventArgs e) => AddBreakpointContextMenuItem.Enabled = DisassemblerView.AnyRowsSelected; private void AddBreakpointContextMenuItem_Click(object sender, EventArgs e) { diff --git a/src/BizHawk.Client.EmuHawk/tools/Debugger/GenericDebugger.cs b/src/BizHawk.Client.EmuHawk/tools/Debugger/GenericDebugger.cs index 65278a27211..9772afdfaf7 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Debugger/GenericDebugger.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Debugger/GenericDebugger.cs @@ -186,15 +186,9 @@ public void EnabledBreakpointBox() toolTip1.SetToolTip(BreakpointsGroupBox, ""); } - private void OnCpuDropDownIndexChanged(object sender, EventArgs e) - { - Disassembler.Cpu = ((ComboBox) sender).SelectedItem.ToString(); - } + private void OnCpuDropDownIndexChanged(object sender, EventArgs e) => Disassembler.Cpu = ((ComboBox)sender).SelectedItem.ToString(); - private void RunBtn_Click(object sender, EventArgs e) - { - MainForm.UnpauseEmulator(); - } + private void RunBtn_Click(object sender, EventArgs e) => MainForm.UnpauseEmulator(); private void StepIntoMenuItem_Click(object sender, EventArgs e) { @@ -271,16 +265,13 @@ private void GenericDebugger_MouseMove(object sender, MouseEventArgs e) } } - public void DisableCancelSeekBtn() - { - CancelSeekBtn.Enabled = false; - } + public void DisableCancelSeekBtn() => CancelSeekBtn.Enabled = false; private void SeekToBtn_Click(object sender, EventArgs e) { CancelSeekBtn.Enabled = true; - var pcVal = (uint)(SeekToBox.ToRawInt() ?? 0); - var pcBitSize = PCRegister.BitSize; + uint pcVal = (uint)(SeekToBox.ToRawInt() ?? 0); + byte pcBitSize = PCRegister.BitSize; BreakPointControl1.RemoveCurrentSeek(); BreakPointControl1.AddSeekBreakpoint(pcVal, pcBitSize); @@ -300,14 +291,8 @@ private void ToPCBtn_Click(object sender, EventArgs e) DisassemblerView.Refresh(); } - private void RefreshMenuItem_Click(object sender, EventArgs e) - { - FullUpdate(); - } + private void RefreshMenuItem_Click(object sender, EventArgs e) => FullUpdate(); - public void AddBreakpoint(uint address, uint mask, MemoryCallbackType type) - { - this.BreakPointControl1.AddBreakpoint(address, mask, type); - } + public void AddBreakpoint(uint address, uint mask, MemoryCallbackType type) => this.BreakPointControl1.AddBreakpoint(address, mask, type); } } diff --git a/src/BizHawk.Client.EmuHawk/tools/Debugger/RegisterBoxControl.cs b/src/BizHawk.Client.EmuHawk/tools/Debugger/RegisterBoxControl.cs index 79e3e77a714..5a974995d64 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Debugger/RegisterBoxControl.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Debugger/RegisterBoxControl.cs @@ -126,8 +126,8 @@ public void GenerateUI() int y = UIHelper.ScaleY(0); - var maxCharSize = registers.Where(r => r.Value.BitSize != 1).Max(r => r.Key.Length); - var width = maxCharSize * (int)Font.Size; + int maxCharSize = registers.Where(r => r.Value.BitSize != 1).Max(r => r.Key.Length); + int width = maxCharSize * (int)Font.Size; if (width < 20) { width = 20; @@ -144,7 +144,7 @@ public void GenerateUI() if (_canSetCpuRegisters) { - var t = new TextBox + TextBox t = new() { Name = name, Text = rv.Value.ToHexString(rv.BitSize / 4), @@ -195,7 +195,7 @@ public void GenerateUI() if (flags.Any()) { - var p = new Panel + Panel p = new() { Name = "FlagPanel", Location = new Point(UIHelper.ScaleX(5), y), @@ -206,7 +206,7 @@ public void GenerateUI() foreach (var (name, rv) in registers.Where(r => r.Value.BitSize == 1).OrderByDescending(x => x.Key)) { - var c = new CheckBox + CheckBox c = new() { Appearance = Appearance.Button, Name = name, diff --git a/src/BizHawk.Client.EmuHawk/tools/ExternalToolManager.cs b/src/BizHawk.Client.EmuHawk/tools/ExternalToolManager.cs index 4e4a5e88449..35ce845e647 100644 --- a/src/BizHawk.Client.EmuHawk/tools/ExternalToolManager.cs +++ b/src/BizHawk.Client.EmuHawk/tools/ExternalToolManager.cs @@ -35,13 +35,13 @@ public MenuItemInfo( _asmChecksum = asmChecksum; _entryPointTypeName = entryPointTypeName; _extToolMan = extToolMan; - _skipExtToolWarning = _extToolMan._config.TrustedExtTools.TryGetValue(asmFilename, out var s) && s == _asmChecksum; + _skipExtToolWarning = _extToolMan._config.TrustedExtTools.TryGetValue(asmFilename, out string s) && s == _asmChecksum; AsmFilename = asmFilename; } public void TryLoad() { - var success = _extToolMan._loadCallback( + bool success = _extToolMan._loadCallback( /*toolPath:*/ AsmFilename, /*customFormTypeName:*/ _entryPointTypeName, /*skipExtToolWarning:*/ _skipExtToolWarning); @@ -59,7 +59,7 @@ public void TryLoad() private FileSystemWatcher DirectoryMonitor; - private readonly List MenuItems = new List(); + private readonly List MenuItems = new(); internal readonly IList PossibleExtToolTypeNames = new List(); @@ -81,7 +81,7 @@ public void Restart(Config config) DirectoryMonitor.Created -= DirectoryMonitor_Created; DirectoryMonitor.Dispose(); } - var path = _config.PathEntries[PathEntryCollection.GLOBAL, "External Tools"].Path; + string path = _config.PathEntries[PathEntryCollection.GLOBAL, "External Tools"].Path; if (Directory.Exists(path)) { DirectoryMonitor = new FileSystemWatcher(path, "*.dll") @@ -111,7 +111,7 @@ internal void BuildToolStrip() private ToolStripMenuItem GenerateToolTipFromFileName(string fileName) { if (fileName == null) throw new Exception(); - var item = new ToolStripMenuItem(Path.GetFileName(fileName)) + ToolStripMenuItem item = new(Path.GetFileName(fileName)) { Enabled = false, Image = Properties.Resources.ExclamationRed, @@ -119,20 +119,18 @@ private ToolStripMenuItem GenerateToolTipFromFileName(string fileName) try { if (!OSTailoredCode.IsUnixHost) MotWHack.RemoveMOTW(fileName); - var asmBytes = File.ReadAllBytes(fileName); - var externalToolFile = Assembly.Load(asmBytes); + byte[] asmBytes = File.ReadAllBytes(fileName); + Assembly externalToolFile = Assembly.Load(asmBytes); var entryPoint = externalToolFile.GetTypes() - .SingleOrDefault(t => typeof(IExternalToolForm).IsAssignableFrom(t) && t.GetCustomAttributes().OfType().Any()); - if (entryPoint == null) throw new ExternalToolAttribute.MissingException(); - - var allAttrs = entryPoint.GetCustomAttributes().ToList(); - var applicabilityAttrs = allAttrs.OfType().ToList(); + .SingleOrDefault(t => typeof(IExternalToolForm).IsAssignableFrom(t) && t.GetCustomAttributes().OfType().Any()) ?? throw new ExternalToolAttribute.MissingException(); + List allAttrs = entryPoint.GetCustomAttributes().ToList(); + List applicabilityAttrs = allAttrs.OfType().ToList(); if (applicabilityAttrs.Count > 1) throw new ExternalToolApplicabilityAttributeBase.DuplicateException(); var toolAttribute = allAttrs.OfType().First(); if (toolAttribute.LoadAssemblyFiles != null) { - foreach (var depFilename in toolAttribute.LoadAssemblyFiles) Assembly.LoadFrom($"{_config.PathEntries[PathEntryCollection.GLOBAL, "External Tools"].Path}/{depFilename}"); + foreach (string depFilename in toolAttribute.LoadAssemblyFiles) Assembly.LoadFrom($"{_config.PathEntries[PathEntryCollection.GLOBAL, "External Tools"].Path}/{depFilename}"); } item.Image = null; // no errors, remove error icon @@ -199,10 +197,7 @@ private ToolStripMenuItem GenerateToolTipFromFileName(string fileName) /// /// Object that raised the event /// Event arguments - private void DirectoryMonitor_Created(object sender, FileSystemEventArgs e) - { - MenuItems.Add(GenerateToolTipFromFileName(e.FullPath)); - } + private void DirectoryMonitor_Created(object sender, FileSystemEventArgs e) => MenuItems.Add(GenerateToolTipFromFileName(e.FullPath)); public IReadOnlyCollection ToolStripItems => MenuItems; diff --git a/src/BizHawk.Client.EmuHawk/tools/GB/GBGPUView.cs b/src/BizHawk.Client.EmuHawk/tools/GB/GBGPUView.cs index 0bbc3578229..4110c14bf4f 100644 --- a/src/BizHawk.Client.EmuHawk/tools/GB/GBGPUView.cs +++ b/src/BizHawk.Client.EmuHawk/tools/GB/GBGPUView.cs @@ -558,16 +558,16 @@ private void ScanlineCallback(byte lcdc) } // try to run the current mouseover, to refresh if the mouse is being held over a pane while the emulator runs // this doesn't really work well; the update rate seems to be throttled - var e = new MouseEventArgs(MouseButtons.None, 0, Cursor.Position.X, Cursor.Position.Y, 0); + MouseEventArgs e = new(MouseButtons.None, 0, Cursor.Position.X, Cursor.Position.Y, 0); OnMouseMove(e); } private void GbGpuView_FormClosed(object sender, FormClosedEventArgs e) => _gbCore?.SetScanlineCallback(null, 0); - private void radioButtonRefreshFrame_CheckedChanged(object sender, EventArgs e) { ComputeRefreshValues(); } - private void radioButtonRefreshScanline_CheckedChanged(object sender, EventArgs e) { ComputeRefreshValues(); } - private void radioButtonRefreshManual_CheckedChanged(object sender, EventArgs e) { ComputeRefreshValues(); } + private void radioButtonRefreshFrame_CheckedChanged(object sender, EventArgs e) => ComputeRefreshValues(); + private void radioButtonRefreshScanline_CheckedChanged(object sender, EventArgs e) => ComputeRefreshValues(); + private void radioButtonRefreshManual_CheckedChanged(object sender, EventArgs e) => ComputeRefreshValues(); private void ComputeRefreshValues() { @@ -650,7 +650,7 @@ private void LoadDetails() groupBoxDetails.Text = _freezeLabel; bmpViewDetails.Height = _freezeBmp.Height * 8; bmpViewDetails.ChangeBitmapSize(_freezeBmp.Size); - using (var g = Graphics.FromImage(bmpViewDetails.Bmp)) + using (Graphics g = Graphics.FromImage(bmpViewDetails.Bmp)) g.DrawImageUnscaled(_freezeBmp, 0, 0); labelDetails.Text = _freezeDetails; bmpViewDetails.Refresh(); @@ -661,7 +661,7 @@ private void SetFreeze() groupBoxMemory.Text = groupBoxDetails.Text; bmpViewMemory.Size = bmpViewDetails.Size; bmpViewMemory.ChangeBitmapSize(bmpViewDetails.Bmp.Size); - using (var g = Graphics.FromImage(bmpViewMemory.Bmp)) + using (Graphics g = Graphics.FromImage(bmpViewMemory.Bmp)) g.DrawImageUnscaled(bmpViewDetails.Bmp, 0, 0); labelMemory.Text = labelDetails.Text; bmpViewMemory.Refresh(); @@ -669,176 +669,168 @@ private void SetFreeze() private unsafe void PaletteMouseover(int x, int y, bool sprite) { - using (var memory = Gb.LockGPU()) - { - var bgPal = memory.Bgpal; - var spPal = memory.Sppal; + using var memory = Gb.LockGPU(); + var bgPal = memory.Bgpal; + var spPal = memory.Sppal; - bmpViewDetails.ChangeBitmapSize(8, 10); - if (bmpViewDetails.Height != 80) - bmpViewDetails.Height = 80; - var sb = new StringBuilder(); - x /= 16; - y /= 16; - int* pal = (int*)(sprite ? spPal : bgPal) + x * 4; - int color = pal[y]; + bmpViewDetails.ChangeBitmapSize(8, 10); + if (bmpViewDetails.Height != 80) + bmpViewDetails.Height = 80; + StringBuilder sb = new(); + x /= 16; + y /= 16; + int* pal = (int*)(sprite ? spPal : bgPal) + x * 4; + int color = pal[y]; - sb.AppendLine($"Palette {x}"); - sb.AppendLine($"Color {y}"); - sb.AppendLine($"(R,G,B) = ({color >> 16 & 255},{color >> 8 & 255},{color & 255})"); + sb.AppendLine($"Palette {x}"); + sb.AppendLine($"Color {y}"); + sb.AppendLine($"(R,G,B) = ({color >> 16 & 255},{color >> 8 & 255},{color & 255})"); - var lockData = bmpViewDetails.Bmp.LockBits(new Rectangle(0, 0, 8, 10), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); - int* dest = (int*)lockData.Scan0; - int pitch = lockData.Stride / sizeof(int); + var lockData = bmpViewDetails.Bmp.LockBits(new Rectangle(0, 0, 8, 10), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); + int* dest = (int*)lockData.Scan0; + int pitch = lockData.Stride / sizeof(int); - for (int py = 0; py < 10; py++) + for (int py = 0; py < 10; py++) + { + for (int px = 0; px < 8; px++) { - for (int px = 0; px < 8; px++) + if (py < 8) { - if (py < 8) - { - *dest++ = color; - } - else - { - *dest++ = pal[px / 2]; - } + *dest++ = color; + } + else + { + *dest++ = pal[px / 2]; } - dest -= 8; - dest += pitch; } - bmpViewDetails.Bmp.UnlockBits(lockData); - labelDetails.Text = sb.ToString(); - bmpViewDetails.Refresh(); + dest -= 8; + dest += pitch; } + bmpViewDetails.Bmp.UnlockBits(lockData); + labelDetails.Text = sb.ToString(); + bmpViewDetails.Refresh(); } private unsafe void TileMouseover(int x, int y, bool secondBank) { - using (var memory = Gb.LockGPU()) - { - var vram = memory.Vram; - var tilesPal = ComputeTilesPalFromMemory(memory); - - // todo: draw with a specific palette - bmpViewDetails.ChangeBitmapSize(8, 8); - if (bmpViewDetails.Height != 64) - bmpViewDetails.Height = 64; - var sb = new StringBuilder(); - x /= 8; - y /= 8; - int tileIndex = y * 16 + x; - int tileOffset = tileIndex * 16; - sb.AppendLine(_cgb - ? $"Tile #{tileIndex} @{(secondBank ? 1 : 0)}:{tileOffset + 0x8000:x4}" - : $"Tile #{tileIndex} @{tileOffset + 0x8000:x4}"); - - var lockData = bmpViewDetails.Bmp.LockBits(new Rectangle(0, 0, 8, 8), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); - DrawTile((byte*)vram + tileOffset + (secondBank ? 8192 : 0), (int*)lockData.Scan0, lockData.Stride / sizeof(int), (int*)tilesPal); - bmpViewDetails.Bmp.UnlockBits(lockData); - labelDetails.Text = sb.ToString(); - bmpViewDetails.Refresh(); - } + using var memory = Gb.LockGPU(); + var vram = memory.Vram; + var tilesPal = ComputeTilesPalFromMemory(memory); + + // todo: draw with a specific palette + bmpViewDetails.ChangeBitmapSize(8, 8); + if (bmpViewDetails.Height != 64) + bmpViewDetails.Height = 64; + StringBuilder sb = new(); + x /= 8; + y /= 8; + int tileIndex = y * 16 + x; + int tileOffset = tileIndex * 16; + sb.AppendLine(_cgb + ? $"Tile #{tileIndex} @{(secondBank ? 1 : 0)}:{tileOffset + 0x8000:x4}" + : $"Tile #{tileIndex} @{tileOffset + 0x8000:x4}"); + + var lockData = bmpViewDetails.Bmp.LockBits(new Rectangle(0, 0, 8, 8), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); + DrawTile((byte*)vram + tileOffset + (secondBank ? 8192 : 0), (int*)lockData.Scan0, lockData.Stride / sizeof(int), (int*)tilesPal); + bmpViewDetails.Bmp.UnlockBits(lockData); + labelDetails.Text = sb.ToString(); + bmpViewDetails.Refresh(); } private unsafe void TileMapMouseover(int x, int y, bool win) { - using (var memory = Gb.LockGPU()) + using var memory = Gb.LockGPU(); + var _bgpal = memory.Bgpal; + var _vram = memory.Vram; + + bmpViewDetails.ChangeBitmapSize(8, 8); + if (bmpViewDetails.Height != 64) + bmpViewDetails.Height = 64; + StringBuilder sb = new(); + bool secondMap = win ? _lcdc.Bit(6) : _lcdc.Bit(3); + int mapOffset = secondMap ? 0x1c00 : 0x1800; + x /= 8; + y /= 8; + mapOffset += y * 32 + x; + byte* mapBase = (byte*)_vram + mapOffset; + int tileIndex = mapBase[0]; + if (win || !_lcdc.Bit(4)) // 0x9000 base + if (tileIndex < 128) + tileIndex += 256; // compute all if from 0x8000 base + int tileOffset = tileIndex * 16; + var lockData = bmpViewDetails.Bmp.LockBits(new Rectangle(0, 0, 8, 8), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); + if (!_cgb) { - var _bgpal = memory.Bgpal; - var _vram = memory.Vram; - - bmpViewDetails.ChangeBitmapSize(8, 8); - if (bmpViewDetails.Height != 64) - bmpViewDetails.Height = 64; - var sb = new StringBuilder(); - bool secondMap = win ? _lcdc.Bit(6) : _lcdc.Bit(3); - int mapOffset = secondMap ? 0x1c00 : 0x1800; - x /= 8; - y /= 8; - mapOffset += y * 32 + x; - byte* mapBase = (byte*)_vram + mapOffset; - int tileIndex = mapBase[0]; - if (win || !_lcdc.Bit(4)) // 0x9000 base - if (tileIndex < 128) - tileIndex += 256; // compute all if from 0x8000 base - int tileOffset = tileIndex * 16; - var lockData = bmpViewDetails.Bmp.LockBits(new Rectangle(0, 0, 8, 8), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); - if (!_cgb) - { - sb.AppendLine($"{(win ? "Win" : "BG")} Map ({x},{y}) @{mapOffset + 0x8000:x4}"); - sb.AppendLine($" Tile #{tileIndex} @{tileOffset + 0x8000:x4}"); - DrawTile((byte*)_vram + tileOffset, (int*)lockData.Scan0, lockData.Stride / sizeof(int), (int*)_bgpal); - } - else - { - int tileExt = mapBase[8192]; + sb.AppendLine($"{(win ? "Win" : "BG")} Map ({x},{y}) @{mapOffset + 0x8000:x4}"); + sb.AppendLine($" Tile #{tileIndex} @{tileOffset + 0x8000:x4}"); + DrawTile((byte*)_vram + tileOffset, (int*)lockData.Scan0, lockData.Stride / sizeof(int), (int*)_bgpal); + } + else + { + int tileExt = mapBase[8192]; - sb.AppendLine($"{(win ? "Win" : "BG")} Map ({x},{y}) @{mapOffset + 0x8000:x4}"); - sb.AppendLine($" Tile #{tileIndex} @{(tileExt.Bit(3) ? 1 : 0)}:{tileOffset + 0x8000:x4}"); - sb.AppendLine($" Palette {tileExt & 7}"); - sb.AppendLine($" Flags {(tileExt.Bit(5) ? 'H' : ' ')}{(tileExt.Bit(6) ? 'V' : ' ')}{(tileExt.Bit(7) ? 'P' : ' ')}"); - DrawTileHv((byte*)_vram + tileOffset + (tileExt.Bit(3) ? 8192 : 0), (int*)lockData.Scan0, lockData.Stride / sizeof(int), (int*)_bgpal + 4 * (tileExt & 7), tileExt.Bit(5), tileExt.Bit(6)); - } - bmpViewDetails.Bmp.UnlockBits(lockData); - labelDetails.Text = sb.ToString(); - bmpViewDetails.Refresh(); + sb.AppendLine($"{(win ? "Win" : "BG")} Map ({x},{y}) @{mapOffset + 0x8000:x4}"); + sb.AppendLine($" Tile #{tileIndex} @{(tileExt.Bit(3) ? 1 : 0)}:{tileOffset + 0x8000:x4}"); + sb.AppendLine($" Palette {tileExt & 7}"); + sb.AppendLine($" Flags {(tileExt.Bit(5) ? 'H' : ' ')}{(tileExt.Bit(6) ? 'V' : ' ')}{(tileExt.Bit(7) ? 'P' : ' ')}"); + DrawTileHv((byte*)_vram + tileOffset + (tileExt.Bit(3) ? 8192 : 0), (int*)lockData.Scan0, lockData.Stride / sizeof(int), (int*)_bgpal + 4 * (tileExt & 7), tileExt.Bit(5), tileExt.Bit(6)); } + bmpViewDetails.Bmp.UnlockBits(lockData); + labelDetails.Text = sb.ToString(); + bmpViewDetails.Refresh(); } private unsafe void SpriteMouseover(int x, int y) { - using (var memory = Gb.LockGPU()) + using var memory = Gb.LockGPU(); + var spPal = memory.Sppal; + var oam = memory.Oam; + var vram = memory.Vram; + + bool tall = _lcdc.Bit(2); + x /= 8; + y /= 8; + bmpViewDetails.ChangeBitmapSize(8, tall ? 16 : 8); + if (bmpViewDetails.Height != bmpViewDetails.Bmp.Height * 8) + bmpViewDetails.Height = bmpViewDetails.Bmp.Height * 8; + StringBuilder sb = new(); + + byte* oament = (byte*)oam + 4 * x; + int sy = oament[0]; + int sx = oament[1]; + int tileNum = oament[2]; + int flags = oament[3]; + bool hFlip = flags.Bit(5); + bool vFlip = flags.Bit(6); + if (tall) { - var spPal = memory.Sppal; - var oam = memory.Oam; - var vram = memory.Vram; + tileNum = vFlip ? tileNum | 1 : tileNum & ~1; + } - bool tall = _lcdc.Bit(2); - x /= 8; - y /= 8; - bmpViewDetails.ChangeBitmapSize(8, tall ? 16 : 8); - if (bmpViewDetails.Height != bmpViewDetails.Bmp.Height * 8) - bmpViewDetails.Height = bmpViewDetails.Bmp.Height * 8; - var sb = new StringBuilder(); - - byte* oament = (byte*)oam + 4 * x; - int sy = oament[0]; - int sx = oament[1]; - int tileNum = oament[2]; - int flags = oament[3]; - bool hFlip = flags.Bit(5); - bool vFlip = flags.Bit(6); + int tileOffset = tileNum * 16; + sb.AppendLine($"Sprite #{x} @{4 * x + 0xfe00:x4}"); + sb.AppendLine($" (x,y) = ({sx},{sy})"); + var lockData = bmpViewDetails.Bmp.LockBits(new Rectangle(0, 0, 8, tall ? 16 : 8), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); + if (_cgb) + { + sb.AppendLine($" Tile #{(y == 1 ? tileNum ^ 1 : tileNum)} @{(flags.Bit(3) ? 1 : 0)}:{tileOffset + 0x8000:x4}"); + sb.AppendLine($" Palette {flags & 7}"); + DrawTileHv((byte*)vram + tileOffset + (flags.Bit(3) ? 8192 : 0), (int*)lockData.Scan0, lockData.Stride / sizeof(int), (int*)spPal + 4 * (flags & 7), hFlip, vFlip); if (tall) - { - tileNum = vFlip ? tileNum | 1 : tileNum & ~1; - } - - int tileOffset = tileNum * 16; - sb.AppendLine($"Sprite #{x} @{4 * x + 0xfe00:x4}"); - sb.AppendLine($" (x,y) = ({sx},{sy})"); - var lockData = bmpViewDetails.Bmp.LockBits(new Rectangle(0, 0, 8, tall ? 16 : 8), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); - if (_cgb) - { - sb.AppendLine($" Tile #{(y == 1 ? tileNum ^ 1 : tileNum)} @{(flags.Bit(3) ? 1 : 0)}:{tileOffset + 0x8000:x4}"); - sb.AppendLine($" Palette {flags & 7}"); - DrawTileHv((byte*)vram + tileOffset + (flags.Bit(3) ? 8192 : 0), (int*)lockData.Scan0, lockData.Stride / sizeof(int), (int*)spPal + 4 * (flags & 7), hFlip, vFlip); - if (tall) - DrawTileHv((byte*)vram + (tileOffset ^ 16) + (flags.Bit(3) ? 8192 : 0), (int*)(lockData.Scan0 + lockData.Stride * 8), lockData.Stride / sizeof(int), (int*)spPal + 4 * (flags & 7), hFlip, vFlip); - } - else - { - sb.AppendLine($" Tile #{(y == 1 ? tileNum ^ 1 : tileNum)} @{tileOffset + 0x8000:x4}"); - sb.AppendLine($" Palette {(flags.Bit(4) ? 1 : 0)}"); - DrawTileHv((byte*)vram + tileOffset, (int*)lockData.Scan0, lockData.Stride / sizeof(int), (int*)spPal + (flags.Bit(4) ? 4 : 0), hFlip, vFlip); - if (tall) - DrawTileHv((byte*)vram + (tileOffset ^ 16), (int*)(lockData.Scan0 + lockData.Stride * 8), lockData.Stride / sizeof(int), (int*)spPal + 4 * (flags.Bit(4) ? 4 : 0), hFlip, vFlip); - } - sb.AppendLine($" Flags {(hFlip ? 'H' : ' ')}{(vFlip ? 'V' : ' ')}{(flags.Bit(7) ? 'P' : ' ')}"); - bmpViewDetails.Bmp.UnlockBits(lockData); - labelDetails.Text = sb.ToString(); - bmpViewDetails.Refresh(); + DrawTileHv((byte*)vram + (tileOffset ^ 16) + (flags.Bit(3) ? 8192 : 0), (int*)(lockData.Scan0 + lockData.Stride * 8), lockData.Stride / sizeof(int), (int*)spPal + 4 * (flags & 7), hFlip, vFlip); } + else + { + sb.AppendLine($" Tile #{(y == 1 ? tileNum ^ 1 : tileNum)} @{tileOffset + 0x8000:x4}"); + sb.AppendLine($" Palette {(flags.Bit(4) ? 1 : 0)}"); + DrawTileHv((byte*)vram + tileOffset, (int*)lockData.Scan0, lockData.Stride / sizeof(int), (int*)spPal + (flags.Bit(4) ? 4 : 0), hFlip, vFlip); + if (tall) + DrawTileHv((byte*)vram + (tileOffset ^ 16), (int*)(lockData.Scan0 + lockData.Stride * 8), lockData.Stride / sizeof(int), (int*)spPal + 4 * (flags.Bit(4) ? 4 : 0), hFlip, vFlip); + } + sb.AppendLine($" Flags {(hFlip ? 'H' : ' ')}{(vFlip ? 'V' : ' ')}{(flags.Bit(7) ? 'P' : ' ')}"); + bmpViewDetails.Bmp.UnlockBits(lockData); + labelDetails.Text = sb.ToString(); + bmpViewDetails.Refresh(); } private void bmpViewBG_MouseEnter(object sender, EventArgs e) @@ -847,15 +839,9 @@ private void bmpViewBG_MouseEnter(object sender, EventArgs e) groupBoxDetails.Text = "Details - Background"; } - private void bmpViewBG_MouseLeave(object sender, EventArgs e) - { - LoadDetails(); - } + private void bmpViewBG_MouseLeave(object sender, EventArgs e) => LoadDetails(); - private void bmpViewBG_MouseMove(object sender, MouseEventArgs e) - { - TileMapMouseover(e.X, e.Y, false); - } + private void bmpViewBG_MouseMove(object sender, MouseEventArgs e) => TileMapMouseover(e.X, e.Y, false); private void bmpViewWin_MouseEnter(object sender, EventArgs e) { @@ -863,15 +849,9 @@ private void bmpViewWin_MouseEnter(object sender, EventArgs e) groupBoxDetails.Text = "Details - Window"; } - private void bmpViewWin_MouseLeave(object sender, EventArgs e) - { - LoadDetails(); - } + private void bmpViewWin_MouseLeave(object sender, EventArgs e) => LoadDetails(); - private void bmpViewWin_MouseMove(object sender, MouseEventArgs e) - { - TileMapMouseover(e.X, e.Y, true); - } + private void bmpViewWin_MouseMove(object sender, MouseEventArgs e) => TileMapMouseover(e.X, e.Y, true); private void bmpViewTiles1_MouseEnter(object sender, EventArgs e) { @@ -879,15 +859,9 @@ private void bmpViewTiles1_MouseEnter(object sender, EventArgs e) groupBoxDetails.Text = "Details - Tiles"; } - private void bmpViewTiles1_MouseLeave(object sender, EventArgs e) - { - LoadDetails(); - } + private void bmpViewTiles1_MouseLeave(object sender, EventArgs e) => LoadDetails(); - private void bmpViewTiles1_MouseMove(object sender, MouseEventArgs e) - { - TileMouseover(e.X, e.Y, false); - } + private void bmpViewTiles1_MouseMove(object sender, MouseEventArgs e) => TileMouseover(e.X, e.Y, false); private void bmpViewTiles2_MouseEnter(object sender, EventArgs e) { @@ -917,15 +891,9 @@ private void bmpViewBGPal_MouseEnter(object sender, EventArgs e) groupBoxDetails.Text = "Details - Palette"; } - private void bmpViewBGPal_MouseLeave(object sender, EventArgs e) - { - LoadDetails(); - } + private void bmpViewBGPal_MouseLeave(object sender, EventArgs e) => LoadDetails(); - private void bmpViewBGPal_MouseMove(object sender, MouseEventArgs e) - { - PaletteMouseover(e.X, e.Y, false); - } + private void bmpViewBGPal_MouseMove(object sender, MouseEventArgs e) => PaletteMouseover(e.X, e.Y, false); private void bmpViewSPPal_MouseEnter(object sender, EventArgs e) { @@ -933,15 +901,9 @@ private void bmpViewSPPal_MouseEnter(object sender, EventArgs e) groupBoxDetails.Text = "Details - Palette"; } - private void bmpViewSPPal_MouseLeave(object sender, EventArgs e) - { - LoadDetails(); - } + private void bmpViewSPPal_MouseLeave(object sender, EventArgs e) => LoadDetails(); - private void bmpViewSPPal_MouseMove(object sender, MouseEventArgs e) - { - PaletteMouseover(e.X, e.Y, true); - } + private void bmpViewSPPal_MouseMove(object sender, MouseEventArgs e) => PaletteMouseover(e.X, e.Y, true); private void bmpViewOAM_MouseEnter(object sender, EventArgs e) { @@ -949,15 +911,9 @@ private void bmpViewOAM_MouseEnter(object sender, EventArgs e) groupBoxDetails.Text = "Details - Sprite"; } - private void bmpViewOAM_MouseLeave(object sender, EventArgs e) - { - LoadDetails(); - } + private void bmpViewOAM_MouseLeave(object sender, EventArgs e) => LoadDetails(); - private void bmpViewOAM_MouseMove(object sender, MouseEventArgs e) - { - SpriteMouseover(e.X, e.Y); - } + private void bmpViewOAM_MouseMove(object sender, MouseEventArgs e) => SpriteMouseover(e.X, e.Y); private void bmpViewOBJ_MouseEnter(object sender, EventArgs e) { @@ -965,10 +921,7 @@ private void bmpViewOBJ_MouseEnter(object sender, EventArgs e) groupBoxDetails.Text = "Details - Objects"; } - private void bmpViewOBJ_MouseLeave(object sender, EventArgs e) - { - LoadDetails(); - } + private void bmpViewOBJ_MouseLeave(object sender, EventArgs e) => LoadDetails(); private void bmpViewOBJ_MouseMove(object sender, MouseEventArgs e) { @@ -996,14 +949,14 @@ private void bmpView_MouseClick(object sender, MouseEventArgs e) } } - private readonly Timer _messageTimer = new Timer(); + private readonly Timer _messageTimer = new(); private void GbGpuView_KeyDown(object sender, KeyEventArgs e) { if (ModifierKeys.HasFlag(Keys.Control) && e.KeyCode == Keys.C) { // find the control under the mouse - Point m = Cursor.Position; + var m = Cursor.Position; Control top = this; Control found; do @@ -1030,7 +983,7 @@ private void MessageTimer_Tick(object sender, EventArgs e) private void ButtonChangeColor_Click(object sender, EventArgs e) { - using var dlg = new ColorDialog + using ColorDialog dlg = new() { AllowFullOpen = true, AnyColor = true, diff --git a/src/BizHawk.Client.EmuHawk/tools/GB/GBPrinterView.cs b/src/BizHawk.Client.EmuHawk/tools/GB/GBPrinterView.cs index fb28f76afd4..1dd72bd2f40 100644 --- a/src/BizHawk.Client.EmuHawk/tools/GB/GBPrinterView.cs +++ b/src/BizHawk.Client.EmuHawk/tools/GB/GBPrinterView.cs @@ -89,7 +89,7 @@ private void OnPrint(IntPtr image, byte height, byte topMargin, byte bottomMargi // exposure is ignored // The page received image - var page = new Bitmap(PaperWidth, height); + Bitmap page = new(PaperWidth, height); var bmp = page.LockBits(new Rectangle(0, 0, PaperWidth, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); @@ -113,10 +113,10 @@ private void OnPrint(IntPtr image, byte height, byte topMargin, byte bottomMargi // add it to the bottom of the history int oldHeight = _printerHistory.Height; ResizeHistory(_printerHistory.Height + page.Height + topMargin + bottomMargin); - using (var g = Graphics.FromImage(_printerHistory)) + using (Graphics g = Graphics.FromImage(_printerHistory)) { // Make it brown - var a = new ImageAttributes(); + ImageAttributes a = new(); a.SetColorMatrix(_paperAdjustment); g.DrawImage(page, new Rectangle(0, oldHeight + topMargin, page.Width, page.Height), 0F, 0F, page.Width, page.Height, GraphicsUnit.Pixel, a); @@ -148,8 +148,8 @@ private void ClearPaper() private void ResizeHistory(int height) { // copy to a new image of height - var newHistory = new Bitmap(PaperWidth, height); - using (var g = Graphics.FromImage(newHistory)) + Bitmap newHistory = new(PaperWidth, height); + using (Graphics g = Graphics.FromImage(newHistory)) { g.Clear(Color.FromArgb((int)PaperColor)); if (_printerHistory != null) @@ -169,7 +169,7 @@ private void ResizeHistory(int height) private void RefreshView() { - using (var g = Graphics.FromImage(paperView.Bmp)) + using (Graphics g = Graphics.FromImage(paperView.Bmp)) { g.Clear(Color.FromArgb((int)PaperColor)); g.DrawImage(_printerHistory, new Point(0, -paperScroll.Value)); @@ -183,9 +183,9 @@ private void SaveImageToolStripMenuItem_Click(object sender, EventArgs e) { // slight hack to use the nice SaveFile() feature of a BmpView - BmpView toSave = new BmpView(); + BmpView toSave = new(); toSave.ChangeBitmapSize(_printerHistory.Size); - using (var g = Graphics.FromImage(toSave.Bmp)) + using (Graphics g = Graphics.FromImage(toSave.Bmp)) { g.DrawImage(_printerHistory, Point.Empty); g.Flush(); @@ -194,14 +194,8 @@ private void SaveImageToolStripMenuItem_Click(object sender, EventArgs e) toSave.Bmp.SaveAsFile(Game, "Print", Emulator.SystemId, Config.PathEntries, this); } - private void CopyToolStripMenuItem_Click(object sender, EventArgs e) - { - Clipboard.SetImage(_printerHistory); - } + private void CopyToolStripMenuItem_Click(object sender, EventArgs e) => Clipboard.SetImage(_printerHistory); - private void PaperScroll_ValueChanged(object sender, EventArgs e) - { - RefreshView(); - } + private void PaperScroll_ValueChanged(object sender, EventArgs e) => RefreshView(); } } diff --git a/src/BizHawk.Client.EmuHawk/tools/GBA/GBAGPUView.cs b/src/BizHawk.Client.EmuHawk/tools/GBA/GBAGPUView.cs index baa9643efd7..1c8702fca95 100644 --- a/src/BizHawk.Client.EmuHawk/tools/GBA/GBAGPUView.cs +++ b/src/BizHawk.Client.EmuHawk/tools/GBA/GBAGPUView.cs @@ -175,7 +175,7 @@ private unsafe void DrawTextBG(int n, MobileBmpView mbv) case 2: mbv.ChangeAllSizes(256, 512); break; case 3: mbv.ChangeAllSizes(512, 512); break; } - Bitmap bmp = mbv.BmpView.Bmp; + var bmp = mbv.BmpView.Bmp; var lockData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); int* pixels = (int*)lockData.Scan0; @@ -234,7 +234,7 @@ private unsafe void DrawAffineBG(int n, MobileBmpView mbv) case 2: mbv.ChangeAllSizes(512, 512); break; case 3: mbv.ChangeAllSizes(1024, 1024); break; } - Bitmap bmp = mbv.BmpView.Bmp; + var bmp = mbv.BmpView.Bmp; var lockData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); int* pixels = (int*)lockData.Scan0; @@ -262,7 +262,7 @@ private unsafe void DrawAffineBG(int n, MobileBmpView mbv) private unsafe void DrawM3BG(MobileBmpView mbv) { mbv.ChangeAllSizes(240, 160); - Bitmap bmp = mbv.BmpView.Bmp; + var bmp = mbv.BmpView.Bmp; var lockData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); int* pixels = (int*)lockData.Scan0; @@ -288,7 +288,7 @@ private unsafe void DrawM3BG(MobileBmpView mbv) private unsafe void DrawM4BG(MobileBmpView mbv, bool secondFrame) { mbv.ChangeAllSizes(240, 160); - Bitmap bmp = mbv.BmpView.Bmp; + var bmp = mbv.BmpView.Bmp; var lockData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); int* pixels = (int*)lockData.Scan0; @@ -315,7 +315,7 @@ private unsafe void DrawM4BG(MobileBmpView mbv, bool secondFrame) private unsafe void DrawM5BG(MobileBmpView mbv, bool secondFrame) { mbv.ChangeAllSizes(160, 128); - Bitmap bmp = mbv.BmpView.Bmp; + var bmp = mbv.BmpView.Bmp; var lockData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); int* pixels = (int*)lockData.Scan0; @@ -417,7 +417,7 @@ private unsafe void DrawSprite(int* dest, int pitch, ushort* sprite, byte* tiles private unsafe void DrawSprites(MobileBmpView mbv) { mbv.BmpView.ChangeBitmapSize(1024, 512); - Bitmap bmp = mbv.BmpView.Bmp; + var bmp = mbv.BmpView.Bmp; var lockData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); BmpView.Clear_Selected_Region((byte*)lockData.Scan0, (uint)(lockData.Height * lockData.Stride)); @@ -450,7 +450,7 @@ private unsafe void DrawSprites(MobileBmpView mbv) private unsafe void DrawPalette(MobileBmpView mbv, bool sprite) { mbv.BmpView.ChangeBitmapSize(16, 16); - Bitmap bmp = mbv.BmpView.Bmp; + var bmp = mbv.BmpView.Bmp; var lockData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); int* pixels = (int*)lockData.Scan0; @@ -500,7 +500,7 @@ private unsafe void DrawSpriteTiles(MobileBmpView mbv, bool tophalfonly, bool ei int th = tophalfonly ? 16 : 32; mbv.BmpView.ChangeBitmapSize(tw * 8, 256); - Bitmap bmp = mbv.BmpView.Bmp; + var bmp = mbv.BmpView.Bmp; var lockData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); int* pixels = (int*)lockData.Scan0; @@ -528,7 +528,7 @@ private unsafe void DrawBGTiles(MobileBmpView mbv, bool eightbit) int th = 32; mbv.BmpView.ChangeBitmapSize(tw * 8, th * 8); - Bitmap bmp = mbv.BmpView.Bmp; + var bmp = mbv.BmpView.Bmp; var lockData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); int* pixels = (int*)lockData.Scan0; @@ -635,7 +635,7 @@ private unsafe void DrawEverything() private MobileBmpView MakeMBVWidget(string text, int w, int h) { - var mbv = new MobileBmpView { Text = text }; + MobileBmpView mbv = new() { Text = text }; mbv.BmpView.Text = text; mbv.TopLevel = false; mbv.ChangeViewSize(w, h); @@ -647,7 +647,7 @@ private MobileBmpView MakeMBVWidget(string text, int w, int h) private MobileDetailView MakeMDVWidget(string text, int w, int h) { - var mdv = new MobileDetailView { Text = text }; + MobileDetailView mdv = new() { Text = text }; mdv.BmpView.Text = text; mdv.TopLevel = false; mdv.ClientSize = new Size(w, h); @@ -676,7 +676,7 @@ private void GenerateWidgets() // memory = MakeMDVWidget("Details - Memory", 128, 192); listBoxWidgets.EndUpdate(); - foreach (var f in listBoxWidgets.Items) + foreach (object f in listBoxWidgets.Items) { Form form = (Form)f; // close becomes hide @@ -742,22 +742,16 @@ private void ShowSelectedWidget() { if (listBoxWidgets.SelectedItem != null) { - var form = listBoxWidgets.SelectedItem as Form; + Form form = listBoxWidgets.SelectedItem as Form; form.Show(); form.BringToFront(); listBoxWidgets.Items.RemoveAt(listBoxWidgets.SelectedIndex); } } - private void buttonShowWidget_Click(object sender, EventArgs e) - { - ShowSelectedWidget(); - } + private void buttonShowWidget_Click(object sender, EventArgs e) => ShowSelectedWidget(); - private void listBoxWidgets_DoubleClick(object sender, EventArgs e) - { - ShowSelectedWidget(); - } + private void listBoxWidgets_DoubleClick(object sender, EventArgs e) => ShowSelectedWidget(); private int? _cbScanline; private int? _cbScanlineEmu = 500; @@ -778,10 +772,7 @@ private void RecomputeRefresh() } } - private void radioButtonScanline_CheckedChanged(object sender, EventArgs e) - { - RecomputeRefresh(); - } + private void radioButtonScanline_CheckedChanged(object sender, EventArgs e) => RecomputeRefresh(); private void hScrollBar1_ValueChanged(object sender, EventArgs e) { @@ -789,15 +780,9 @@ private void hScrollBar1_ValueChanged(object sender, EventArgs e) radioButtonScanline.Text = $"Scanline {_cbScanline}"; } - private void radioButtonManual_CheckedChanged(object sender, EventArgs e) - { - RecomputeRefresh(); - } + private void radioButtonManual_CheckedChanged(object sender, EventArgs e) => RecomputeRefresh(); - private void buttonRefresh_Click(object sender, EventArgs e) - { - DrawEverything(); - } + private void buttonRefresh_Click(object sender, EventArgs e) => DrawEverything(); private void GbaGpuView_FormClosed(object sender, FormClosedEventArgs e) => GBA.SetScanlineCallback(null, 0); @@ -813,7 +798,7 @@ private void GbaGpuView_KeyDown(object sender, KeyEventArgs e) if (ModifierKeys.HasFlag(Keys.Control) && e.KeyCode == Keys.C) { // find the control under the mouse - Point m = Cursor.Position; + var m = Cursor.Position; Control top = this; Control found; do diff --git a/src/BizHawk.Client.EmuHawk/tools/GBA/MobileBmpView.Designer.cs b/src/BizHawk.Client.EmuHawk/tools/GBA/MobileBmpView.Designer.cs index e33564fd34e..b1c4b0d6343 100644 --- a/src/BizHawk.Client.EmuHawk/tools/GBA/MobileBmpView.Designer.cs +++ b/src/BizHawk.Client.EmuHawk/tools/GBA/MobileBmpView.Designer.cs @@ -28,23 +28,23 @@ protected override void Dispose(bool disposing) /// private void InitializeComponent() { - this.bmpView1 = new BizHawk.Client.EmuHawk.BmpView(); + this.BmpView = new BizHawk.Client.EmuHawk.BmpView(); this.SuspendLayout(); // // bmpView1 // - this.bmpView1.Location = new System.Drawing.Point(0, 0); - this.bmpView1.Name = "bmpView1"; - this.bmpView1.Size = new System.Drawing.Size(64, 64); - this.bmpView1.TabIndex = 0; - this.bmpView1.Text = "bmpView1"; + this.BmpView.Location = new System.Drawing.Point(0, 0); + this.BmpView.Name = "bmpView1"; + this.BmpView.Size = new System.Drawing.Size(64, 64); + this.BmpView.TabIndex = 0; + this.BmpView.Text = "bmpView1"; // // MobileBmpView // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(292, 273); - this.Controls.Add(this.bmpView1); + this.Controls.Add(this.BmpView); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.MaximizeBox = false; this.MinimizeBox = false; @@ -57,6 +57,5 @@ private void InitializeComponent() #endregion - private BmpView bmpView1; } } \ No newline at end of file diff --git a/src/BizHawk.Client.EmuHawk/tools/GBA/MobileBmpView.cs b/src/BizHawk.Client.EmuHawk/tools/GBA/MobileBmpView.cs index 89dab7d613c..ad59d056f3d 100644 --- a/src/BizHawk.Client.EmuHawk/tools/GBA/MobileBmpView.cs +++ b/src/BizHawk.Client.EmuHawk/tools/GBA/MobileBmpView.cs @@ -11,7 +11,7 @@ public MobileBmpView() InitializeComponent(); } - public BmpView BmpView => bmpView1; + public BmpView BmpView { get; private set; } [Browsable(false)] public bool ShouldDraw => Visible; @@ -20,19 +20,16 @@ public MobileBmpView() public void ChangeViewSize(Size size) { - bmpView1.Size = size; + BmpView.Size = size; this.ClientSize = size; } - public void ChangeViewSize(int w, int h) - { - ChangeViewSize(new Size(w, h)); - } + public void ChangeViewSize(int w, int h) => ChangeViewSize(new Size(w, h)); public void ChangeAllSizes(int w, int h) { ChangeViewSize(w, h); - bmpView1.ChangeBitmapSize(w, h); + BmpView.ChangeBitmapSize(w, h); } } } diff --git a/src/BizHawk.Client.EmuHawk/tools/GBA/MobileDetailView.Designer.cs b/src/BizHawk.Client.EmuHawk/tools/GBA/MobileDetailView.Designer.cs index 29da7361ee8..00f0db07c4c 100644 --- a/src/BizHawk.Client.EmuHawk/tools/GBA/MobileDetailView.Designer.cs +++ b/src/BizHawk.Client.EmuHawk/tools/GBA/MobileDetailView.Designer.cs @@ -29,7 +29,7 @@ protected override void Dispose(bool disposing) private void InitializeComponent() { this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); - this.bmpView1 = new BizHawk.Client.EmuHawk.BmpView(); + this.BmpView = new BizHawk.Client.EmuHawk.BmpView(); this.listView1 = new System.Windows.Forms.ListView(); this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); @@ -40,7 +40,7 @@ private void InitializeComponent() // this.tableLayoutPanel1.ColumnCount = 1; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); - this.tableLayoutPanel1.Controls.Add(this.bmpView1, 0, 0); + this.tableLayoutPanel1.Controls.Add(this.BmpView, 0, 0); this.tableLayoutPanel1.Controls.Add(this.listView1, 0, 1); this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0); @@ -53,12 +53,12 @@ private void InitializeComponent() // // bmpView1 // - this.bmpView1.Dock = System.Windows.Forms.DockStyle.Fill; - this.bmpView1.Location = new System.Drawing.Point(3, 3); - this.bmpView1.Name = "bmpView1"; - this.bmpView1.Size = new System.Drawing.Size(136, 134); - this.bmpView1.TabIndex = 0; - this.bmpView1.Text = "bmpView1"; + this.BmpView.Dock = System.Windows.Forms.DockStyle.Fill; + this.BmpView.Location = new System.Drawing.Point(3, 3); + this.BmpView.Name = "bmpView1"; + this.BmpView.Size = new System.Drawing.Size(136, 134); + this.BmpView.TabIndex = 0; + this.BmpView.Text = "bmpView1"; // // listView1 // @@ -96,7 +96,6 @@ private void InitializeComponent() #endregion private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; - private BmpView bmpView1; private System.Windows.Forms.ListView listView1; private System.Windows.Forms.ColumnHeader columnHeader1; private System.Windows.Forms.ColumnHeader columnHeader2; diff --git a/src/BizHawk.Client.EmuHawk/tools/GBA/MobileDetailView.cs b/src/BizHawk.Client.EmuHawk/tools/GBA/MobileDetailView.cs index 740f1b9bc84..6a5e67b92b1 100644 --- a/src/BizHawk.Client.EmuHawk/tools/GBA/MobileDetailView.cs +++ b/src/BizHawk.Client.EmuHawk/tools/GBA/MobileDetailView.cs @@ -10,15 +10,13 @@ public MobileDetailView() InitializeComponent(); } - public BmpView BmpView => bmpView1; + public BmpView BmpView { get; private set; } public override string ToString() => Text; - private void MobileDetailView_SizeChanged(object sender, EventArgs e) - { + private void MobileDetailView_SizeChanged(object sender, EventArgs e) => // bmp view is always square tableLayoutPanel1.RowStyles[0].Height = ClientSize.Width; - } private void listView1_SizeChanged(object sender, EventArgs e) { diff --git a/src/BizHawk.Client.EmuHawk/tools/GameShark.cs b/src/BizHawk.Client.EmuHawk/tools/GameShark.cs index 85053377279..8c6aee9a119 100644 --- a/src/BizHawk.Client.EmuHawk/tools/GameShark.cs +++ b/src/BizHawk.Client.EmuHawk/tools/GameShark.cs @@ -40,18 +40,18 @@ public GameShark() private void Go_Click(object sender, EventArgs e) { - foreach (var l in txtCheat.Lines) + foreach (string l in txtCheat.Lines) { try { - var code = l.ToUpperInvariant().Trim(); - var decoder = new GameSharkDecoder(MemoryDomains, Emulator.SystemId); + string code = l.ToUpperInvariant().Trim(); + GameSharkDecoder decoder = new(MemoryDomains, Emulator.SystemId); var result = decoder.Decode(code); var domain = decoder.CheatDomain(); if (result.IsValid(out var valid)) { - var description = !string.IsNullOrWhiteSpace(txtDescription.Text) + string description = !string.IsNullOrWhiteSpace(txtDescription.Text) ? txtDescription.Text : code; MainForm.CheatList.Add(valid.ToCheat(domain, description)); @@ -74,7 +74,7 @@ private void Go_Click(object sender, EventArgs e) private void BtnClear_Click(object sender, EventArgs e) { // Clear old Inputs - var result = DialogController.ShowMessageBox2("Are you sure you want to clear this form?", "Clear Form", EMsgBoxIcon.Question); + bool result = DialogController.ShowMessageBox2("Are you sure you want to clear this form?", "Clear Form", EMsgBoxIcon.Question); if (result) { txtDescription.Clear(); diff --git a/src/BizHawk.Client.EmuHawk/tools/Genesis/VDPViewer.cs b/src/BizHawk.Client.EmuHawk/tools/Genesis/VDPViewer.cs index e1dfa026e5b..d3543ba925f 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Genesis/VDPViewer.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Genesis/VDPViewer.cs @@ -20,11 +20,9 @@ public partial class GenVdpViewer : ToolFormBase, IToolFormAutoConfig private int _palIndex; - protected override Point ScrollToControl(Control activeControl) - { + protected override Point ScrollToControl(Control activeControl) => // Returning the current location prevents the panel from scrolling to the active control when the panel loses and regains focus - return DisplayRectangle.Location; - } + DisplayRectangle.Location; protected override string WindowTitleStatic => "VDP Viewer"; @@ -57,7 +55,7 @@ private static unsafe void DrawNameTable(LibGPGX.VDPNameTable nt, ushort* vram, int tileW = nt.Width; int tileH = nt.Height; - Size pixSize = new Size(tileW * 8, tileH * 8); + Size pixSize = new(tileW * 8, tileH * 8); bv.Size = pixSize; bv.ChangeBitmapSize(pixSize); @@ -143,10 +141,7 @@ protected override unsafe void UpdateBefore() } } - public override void Restart() - { - GeneralUpdate(); - } + public override void Restart() => GeneralUpdate(); private void BmpViewPal_MouseClick(object sender, MouseEventArgs e) { @@ -161,7 +156,7 @@ private void VDPViewer_KeyDown(object sender, KeyEventArgs e) if (ModifierKeys.HasFlag(Keys.Control) && e.KeyCode == Keys.C) { // find the control under the mouse - Point m = Cursor.Position; + var m = Cursor.Position; Control top = this; Control found; do @@ -177,34 +172,16 @@ private void VDPViewer_KeyDown(object sender, KeyEventArgs e) } } - private void SaveAsFile(Bitmap bitmap, string suffix) - { - bitmap.SaveAsFile(Game, suffix, Emu.SystemId, Config.PathEntries, this); - } + private void SaveAsFile(Bitmap bitmap, string suffix) => bitmap.SaveAsFile(Game, suffix, Emu.SystemId, Config.PathEntries, this); - private void SaveBGAScreenshotToolStripMenuItem_Click(object sender, EventArgs e) - { - SaveAsFile(bmpViewNTA.Bmp, "NTA"); - } + private void SaveBGAScreenshotToolStripMenuItem_Click(object sender, EventArgs e) => SaveAsFile(bmpViewNTA.Bmp, "NTA"); - private void SaveBGBScreenshotToolStripMenuItem_Click(object sender, EventArgs e) - { - SaveAsFile(bmpViewNTB.Bmp, "NTB"); - } + private void SaveBGBScreenshotToolStripMenuItem_Click(object sender, EventArgs e) => SaveAsFile(bmpViewNTB.Bmp, "NTB"); - private void SaveTilesScreenshotToolStripMenuItem_Click(object sender, EventArgs e) - { - SaveAsFile(bmpViewTiles.Bmp, "Tiles"); - } + private void SaveTilesScreenshotToolStripMenuItem_Click(object sender, EventArgs e) => SaveAsFile(bmpViewTiles.Bmp, "Tiles"); - private void SaveWindowScreenshotToolStripMenuItem_Click(object sender, EventArgs e) - { - SaveAsFile(bmpViewNTW.Bmp, "Window"); - } + private void SaveWindowScreenshotToolStripMenuItem_Click(object sender, EventArgs e) => SaveAsFile(bmpViewNTW.Bmp, "Window"); - private void SavePaletteScreenshotToolStripMenuItem_Click(object sender, EventArgs e) - { - SaveAsFile(bmpViewPal.Bmp, "Palettes"); - } + private void SavePaletteScreenshotToolStripMenuItem_Click(object sender, EventArgs e) => SaveAsFile(bmpViewPal.Bmp, "Palettes"); } } diff --git a/src/BizHawk.Client.EmuHawk/tools/HexEditor/HexEditor.cs b/src/BizHawk.Client.EmuHawk/tools/HexEditor/HexEditor.cs index 93107424638..7201f6e9a44 100644 --- a/src/BizHawk.Client.EmuHawk/tools/HexEditor/HexEditor.cs +++ b/src/BizHawk.Client.EmuHawk/tools/HexEditor/HexEditor.cs @@ -68,12 +68,12 @@ private static FilesystemFilterSet CreateBinaryDumpFSFilterSet(string ext) private readonly int _fontWidth; private readonly int _fontHeight; - private readonly List _nibbles = new List(); + private readonly List _nibbles = new(); private long? _highlightedAddress; - private readonly List _secondaryHighlightedAddresses = new List(); + private readonly List _secondaryHighlightedAddresses = new(); - private readonly Dictionary _textTable = new Dictionary(); + private readonly Dictionary _textTable = new(); private int _rowsVisible; private int _numDigits = 4; @@ -119,7 +119,7 @@ internal class ColorConfig private WatchSize WatchSize => (WatchSize)DataSize; - private readonly Pen _blackPen = new Pen(Color.Black); + private readonly Pen _blackPen = new(Color.Black); private SolidBrush _freezeBrush; private SolidBrush _freezeHighlightBrush; private SolidBrush _highlightBrush; @@ -195,10 +195,7 @@ private void HexEditor_Load(object sender, EventArgs e) GeneralUpdate(); } - protected override void UpdateAfter() - { - AddressesLabel.Text = GenerateMemoryViewString(true); - } + protected override void UpdateAfter() => AddressesLabel.Text = GenerateMemoryViewString(true); protected override void GeneralUpdate() { @@ -248,7 +245,7 @@ public void SetToAddresses(IEnumerable addresses, MemoryDomain domain, Wat { DataSize = (int)size; SetDataSize(DataSize); - var addrList = addresses.ToList(); + List addrList = addresses.ToList(); if (addrList.Any()) { SetMemoryDomain(domain.Name); @@ -265,10 +262,10 @@ public byte[] ConvertTextToBytes(string str) { if (_textTable.Any()) { - var byteArr = new byte[str.Length]; - for (var i = 0; i < str.Length; i++) + byte[] byteArr = new byte[str.Length]; + for (int i = 0; i < str.Length; i++) { - var c = str[i]; + char c = str[i]; byteArr[i] = (byte) (_textTable.FirstOrNull(kvp => kvp.Value == c)?.Key ?? 0); } return byteArr; @@ -281,13 +278,13 @@ public void FindNext(string value, bool wrap) { long found = -1; - var search = value.Replace(" ", "").ToUpperInvariant(); + string search = value.Replace(" ", "").ToUpperInvariant(); if (string.IsNullOrEmpty(search)) { return; } - var numByte = search.Length / 2; + int numByte = search.Length / 2; long startByte; if (_highlightedAddress == null) @@ -304,10 +301,10 @@ public void FindNext(string value, bool wrap) } byte[] searchBytes = ConvertHexStringToByteArray(search); - for (var i = startByte; i < (_domain.Size - numByte); i++) + for (long i = startByte; i < (_domain.Size - numByte); i++) { bool differenceFound = false; - for (var j = 0; j < numByte; j++) + for (int j = 0; j < numByte; j++) { if (_domain.PeekByte(i + j) != searchBytes[j]) { @@ -341,21 +338,21 @@ public void FindPrev(string value, bool wrap) { long found = -1; - var search = value.Replace(" ", "").ToUpperInvariant(); + string search = value.Replace(" ", "").ToUpperInvariant(); if (string.IsNullOrEmpty(search)) { return; } - var numByte = search.Length / 2; + int numByte = search.Length / 2; long startByte = _highlightedAddress - 1 ?? _domain.Size - DataSize - numByte; byte[] searchBytes = ConvertHexStringToByteArray(search); - for (var i = startByte; i >= 0; i--) + for (long i = startByte; i >= 0; i--) { bool differenceFound = false; - for (var j = 0; j < numByte; j++) + for (int j = 0; j < numByte; j++) { if (_domain.PeekByte(i + j) != searchBytes[j]) { differenceFound = true; @@ -406,9 +403,9 @@ private byte[] ConvertHexStringToByteArray(string str) private char Remap(byte val) { - if (_textTable.Count != 0) return _textTable.TryGetValue(val, out var c) ? c : '?'; + if (_textTable.Count != 0) return _textTable.TryGetValue(val, out char c) ? c : '?'; - if (val < ' ' || val >= 0x7F) + if (val is < (byte)' ' or >= 0x7F) { return '.'; } @@ -418,26 +415,26 @@ private char Remap(byte val) private bool CurrentRomIsArchive() { - var path = MainForm.CurrentlyOpenRom; + string path = MainForm.CurrentlyOpenRom; if (path == null) { return false; } - using var file = new HawkFile(path); + using HawkFile file = new(path); return file.Exists && file.IsArchive; } private byte[] GetRomBytes() { - var path = MainForm.CurrentlyOpenRomArgs.OpenAdvanced.SimplePath; + string path = MainForm.CurrentlyOpenRomArgs.OpenAdvanced.SimplePath; if (string.IsNullOrEmpty(path)) { return new byte[] { 0xFF }; } - using var file = new HawkFile(path); + using HawkFile file = new(path); if (!file.Exists) { @@ -465,17 +462,17 @@ private static int GetNumDigits(long i) private static bool IsHexKeyCode(char key) { - if (key >= '0' && key <= '9') // 0-9 + if (key is >= '0' and <= '9') // 0-9 { return true; } - if (key >= 'a' && key <= 'f') // A-F + if (key is >= 'a' and <= 'f') // A-F { return true; } - if (key >= 'A' && key <= 'F') // A-F + if (key is >= 'A' and <= 'F') // A-F { return true; } @@ -507,9 +504,9 @@ private void CloseHexFind() private string GenerateAddressString() { - var addrStr = new StringBuilder(); + StringBuilder addrStr = new(); - for (var i = 0; i < _rowsVisible; i++) + for (int i = 0; i < _rowsVisible; i++) { long row = i + HexScrollBar.Value; long addr = row << 4; @@ -535,10 +532,10 @@ private string GenerateAddressString() private string GenerateMemoryViewString(bool forWindow) { - var rowStr = new StringBuilder(); + StringBuilder rowStr = new(); var hexValues = MakeValues(DataSize); var charValues = MakeValues(1); - for (var i = 0; i < _rowsVisible; i++) + for (int i = 0; i < _rowsVisible; i++) { long row = i + HexScrollBar.Value; long addr = row << 4; @@ -547,16 +544,16 @@ private string GenerateMemoryViewString(bool forWindow) break; } - for (var j = 0; j < 16; j += DataSize) + for (int j = 0; j < 16; j += DataSize) { if (addr + j + DataSize <= _domain.Size) { - var addressVal = hexValues[addr + j]; + long addressVal = hexValues[addr + j]; rowStr.AppendFormat(_digitFormatString, addressVal); } else { - for (var t = 0; t < DataSize; t++) + for (int t = 0; t < DataSize; t++) { rowStr.Append(" "); } @@ -566,7 +563,7 @@ private string GenerateMemoryViewString(bool forWindow) } rowStr.Append("| "); - for (var k = 0; k < 16; k++) + for (int k = 0; k < 16; k++) { if (addr + k < _domain.Size) { @@ -594,7 +591,7 @@ private Dictionary MakeValues(int dataSize) end = Math.Min(end, _domain.Size); end &= -(long)dataSize; - var dict = new Dictionary(); + Dictionary dict = new(); if (end <= start) return dict; @@ -606,28 +603,28 @@ private Dictionary MakeValues(int dataSize) default: case 1: { - var vals = new byte[end - start]; + byte[] vals = new byte[end - start]; _domain.BulkPeekByte(range, vals); int i = 0; - for (var addr = start; addr < end; addr += dataSize) + for (long addr = start; addr < end; addr += dataSize) dict.Add(addr, vals[i++]); break; } case 2: { - var vals = new ushort[(end - start) >> 1]; + ushort[] vals = new ushort[(end - start) >> 1]; _domain.BulkPeekUshort(range, BigEndian, vals); int i = 0; - for (var addr = start; addr < end; addr += dataSize) + for (long addr = start; addr < end; addr += dataSize) dict.Add(addr, vals[i++]); break; } case 4: { - var vals = new uint[(end - start) >> 2]; + uint[] vals = new uint[(end - start) >> 2]; _domain.BulkPeekUint(range, BigEndian, vals); int i = 0; - for (var addr = start; addr < end; addr += dataSize) + for (long addr = start; addr < end; addr += dataSize) dict.Add(addr, vals[i++]); break; } @@ -638,16 +635,12 @@ private Dictionary MakeValues(int dataSize) private int MakeValue(int dataSize, long address) { - switch (dataSize) + return dataSize switch { - default: - case 1: - return _domain.PeekByte(address); - case 2: - return _domain.PeekUshort(address, BigEndian); - case 4: - return (int)_domain.PeekUint(address, BigEndian); - } + 2 => _domain.PeekUshort(address, BigEndian), + 4 => (int)_domain.PeekUint(address, BigEndian), + _ => _domain.PeekByte(address), + }; } private void SetMemoryDomain(string name) @@ -688,8 +681,8 @@ private void SetMemoryDomain(string name) private void UpdateGroupBoxTitle() { - var addressesString = "0x" + $"{_domain.Size / DataSize:X8}".TrimStart('0'); - var viewerText = $"{Emulator.SystemId} {_domain}{(_domain.Writable ? string.Empty : " (READ-ONLY)")} - {addressesString} addresses"; + string addressesString = "0x" + $"{_domain.Size / DataSize:X8}".TrimStart('0'); + string viewerText = $"{Emulator.SystemId} {_domain}{(_domain.Writable ? string.Empty : " (READ-ONLY)")} - {addressesString} addresses"; if (_nibbles.Any()) { viewerText += $" Typing: ({MakeNibbles()})"; @@ -736,7 +729,7 @@ private void SetHighlighted(long address) if (!IsVisible(address)) { - var value = (address / 16) - _rowsVisible + 1; + long value = (address / 16) - _rowsVisible + 1; if (value < 0) { value = 0; @@ -759,7 +752,7 @@ private void UpdateFormText() } else { - var newTitle = "Hex Editor"; + string newTitle = "Hex Editor"; newTitle += " - Editing Address 0x" + string.Format(_numDigitsStr, _highlightedAddress); if (_secondaryHighlightedAddresses.Any()) { @@ -793,7 +786,7 @@ private void SetHeader() private void SetDataSize(int size) { - if (size == 1 || size == 2 || size == 4) + if (size is 1 or 2 or 4) { DataSize = size; _digitFormatString = $"{{0:X{DataSize * 2}}} "; @@ -806,22 +799,15 @@ private void SetDataSize(int size) private Watch MakeWatch(long address) { - switch (DataSize) + return DataSize switch { - default: - case 1: - return Watch.GenerateWatch(_domain, address, WatchSize.Byte, Common.WatchDisplayType.Hex, BigEndian); - case 2: - return Watch.GenerateWatch(_domain, address, WatchSize.Word, Common.WatchDisplayType.Hex, BigEndian); - case 4: - return Watch.GenerateWatch(_domain, address, WatchSize.DWord, Common.WatchDisplayType.Hex, BigEndian); - } + 2 => Watch.GenerateWatch(_domain, address, WatchSize.Word, Common.WatchDisplayType.Hex, BigEndian), + 4 => Watch.GenerateWatch(_domain, address, WatchSize.DWord, Common.WatchDisplayType.Hex, BigEndian), + _ => Watch.GenerateWatch(_domain, address, WatchSize.Byte, Common.WatchDisplayType.Hex, BigEndian), + }; } - private bool IsFrozen(long address) - { - return MainForm.CheatList.IsActive(_domain, address); - } + private bool IsFrozen(long address) => MainForm.CheatList.IsActive(_domain, address); private void FreezeHighlighted() { @@ -832,7 +818,7 @@ private void FreezeHighlighted() if (_highlightedAddress >= 0) { - var watch = Watch.GenerateWatch( + Watch watch = Watch.GenerateWatch( _domain, _highlightedAddress.Value, WatchSize, @@ -846,10 +832,10 @@ private void FreezeHighlighted() if (_secondaryHighlightedAddresses.Any()) { - var cheats = new List(); - foreach (var address in _secondaryHighlightedAddresses) + List cheats = new(); + foreach (long address in _secondaryHighlightedAddresses) { - var watch = Watch.GenerateWatch( + Watch watch = Watch.GenerateWatch( _domain, address, WatchSize, @@ -892,9 +878,9 @@ private void UnfreezeHighlighted() private void SaveFileBinary(string path) { - var file = new FileInfo(path); - using var binWriter = new BinaryWriter(File.Open(file.FullName, FileMode.Create)); - for (var i = 0; i < _domain.Size; i++) + FileInfo file = new(path); + using BinaryWriter binWriter = new(File.Open(file.FullName, FileMode.Create)); + for (int i = 0; i < _domain.Size; i++) { binWriter.Write(_domain.PeekByte(i)); } @@ -958,7 +944,7 @@ private void ResetScrollBar() private void SetUpScrollBar() { _rowsVisible = (MemoryViewerBox.Height - (_fontHeight * 2) - (_fontHeight / 2)) / _fontHeight; - var totalRows = (int)((_domain.Size + 15) / 16); + int totalRows = (int)((_domain.Size + 15) / 16); if (totalRows < _rowsVisible) { @@ -976,14 +962,14 @@ private long GetPointedAddress(int x, int y) { // Scroll value determines the first row long i = HexScrollBar.Value; - var rowOffset = y / _fontHeight; + int rowOffset = y / _fontHeight; i += rowOffset; int colWidth = DataSize * 2 + 1; - var column = x / (_fontWidth * colWidth); + int column = x / (_fontWidth * colWidth); - var innerOffset = AddressesLabel.Location.X - AddressLabel.Location.X + AddressesLabel.Margin.Left; - var start = GetTextOffset() - innerOffset; + int innerOffset = AddressesLabel.Location.X - AddressLabel.Location.X + AddressesLabel.Margin.Left; + int start = GetTextOffset() - innerOffset; if (x > start) { column = (x - start) / (_fontWidth * DataSize); @@ -1001,14 +987,14 @@ private void DoShiftClick() _secondaryHighlightedAddresses.Clear(); if (_addressOver < _highlightedAddress) { - for (var x = _addressOver; x < _highlightedAddress; x += DataSize) + for (long x = _addressOver; x < _highlightedAddress; x += DataSize) { _secondaryHighlightedAddresses.Add(x); } } else if (_addressOver > _highlightedAddress) { - for (var x = _highlightedAddress.Value + DataSize; x <= _addressOver; x += DataSize) + for (long x = _highlightedAddress.Value + DataSize; x <= _addressOver; x += DataSize) { _secondaryHighlightedAddresses.Add(x); } @@ -1016,7 +1002,7 @@ private void DoShiftClick() if (!IsVisible(_addressOver)) { - var value = (_addressOver / 16) + 1 - ((_addressOver / 16) < HexScrollBar.Value ? 1 : _rowsVisible); + long value = (_addressOver / 16) + 1 - ((_addressOver / 16) < HexScrollBar.Value ? 1 : _rowsVisible); if (value < 0) { value = 0; @@ -1035,9 +1021,9 @@ private void ClearHighlighted() private Point GetAddressCoordinates(long address) { - var extra = (address % DataSize) * _fontWidth * 2; - var xOffset = AddressesLabel.Location.X + _fontWidth / 2 - 2; - var yOffset = AddressesLabel.Location.Y; + long extra = (address % DataSize) * _fontWidth * 2; + int xOffset = AddressesLabel.Location.X + _fontWidth / 2 - 2; + int yOffset = AddressesLabel.Location.Y; if (OSTailoredCode.IsUnixHost) { // don't wanna know @@ -1053,10 +1039,7 @@ private Point GetAddressCoordinates(long address) } // TODO: rename this, but it is a hack work around for highlighting misaligned addresses that result from highlighting on in a smaller data size and switching size - private bool NeedsExtra(long val) - { - return val % DataSize > 0; - } + private bool NeedsExtra(long val) => val % DataSize > 0; private int GetTextOffset() { @@ -1068,15 +1051,12 @@ private int GetTextOffset() return start; } - private long GetTextX(long address) - { - return GetTextOffset() + ((address % 16) * _fontWidth); - } + private long GetTextX(long address) => GetTextOffset() + ((address % 16) * _fontWidth); private string MakeNibbles() { - var str = ""; - foreach (var c in _nibbles) + string str = ""; + foreach (char c in _nibbles) { str += c; } @@ -1172,7 +1152,7 @@ private string GetFindValues() { if (_highlightedAddress.HasValue) { - var values = ValueString(_highlightedAddress.Value); + string values = ValueString(_highlightedAddress.Value); return _secondaryHighlightedAddresses.Aggregate(values, (current, x) => current + ValueString(x)); } @@ -1184,15 +1164,15 @@ private void HighlightSecondaries(string value, long found) // This function assumes that the primary highlighted value has been set and sets the remaining characters in this string _secondaryHighlightedAddresses.Clear(); - var addrLength = DataSize * 2; + int addrLength = DataSize * 2; if (value.Length <= addrLength) { return; } - var numToHighlight = (value.Length / addrLength) - 1; + int numToHighlight = (value.Length / addrLength) - 1; - for (var i = 0; i < numToHighlight; i += DataSize) + for (int i = 0; i < numToHighlight; i += DataSize) { _secondaryHighlightedAddresses.Add(found + DataSize + i); } @@ -1206,7 +1186,7 @@ private bool LoadTable(string path) } _textTable.Clear(); - var file = new FileInfo(path); + FileInfo file = new(path); if (!file.Exists) { return false; @@ -1221,7 +1201,7 @@ private bool LoadTable(string path) continue; } - var parts = line.Split('='); + string[] parts = line.Split('='); _textTable.Add(int.Parse(parts[0], NumberStyles.HexNumber), parts[1].First()); } @@ -1254,7 +1234,7 @@ private void SaveMenuItem_Click(object sender, EventArgs e) private void SaveAsBinaryMenuItem_Click(object sender, EventArgs e) { - var path = GetBinarySaveFileFromUser(); + string path = GetBinarySaveFileFromUser(); if (!string.IsNullOrEmpty(path)) { SaveFileBinary(path); @@ -1269,7 +1249,7 @@ private void importAsBinaryToolStripMenuItem_Click(object sender, EventArgs e) return; } - var path = this.ShowFileOpenDialog( + string path = this.ShowFileOpenDialog( discardCWDChange: true, filter: ImportableFSFilterSet, initDir: Config!.PathEntries.ToolsAbsolutePath()); @@ -1285,16 +1265,16 @@ private void importAsBinaryToolStripMenuItem_Click(object sender, EventArgs e) private void SaveAsTextMenuItem_Click(object sender, EventArgs e) { - var path = GetSaveFileFromUser(); + string path = GetSaveFileFromUser(); if (!string.IsNullOrWhiteSpace(path)) { - var file = new FileInfo(path); - using var sw = new StreamWriter(file.FullName); - var sb = new StringBuilder(); + FileInfo file = new(path); + using StreamWriter sw = new(file.FullName); + StringBuilder sb = new(); - for (var i = 0; i < _domain.Size / 16; i++) + for (int i = 0; i < _domain.Size / 16; i++) { - for (var j = 0; j < 16; j++) + for (int j = 0; j < 16; j++) { sb.Append($"{_domain.PeekByte((i * 16) + j):X2} "); } @@ -1308,7 +1288,7 @@ private void SaveAsTextMenuItem_Click(object sender, EventArgs e) private void LoadTableFileMenuItem_Click(object sender, EventArgs e) { - var result = this.ShowFileOpenDialog( + string result = this.ShowFileOpenDialog( discardCWDChange: false, filter: TextTablesFSFilterSet, initDir: Config!.PathEntries.ToolsAbsolutePath(), @@ -1319,15 +1299,12 @@ private void LoadTableFileMenuItem_Click(object sender, EventArgs e) GeneralUpdate(); } - private void CloseTableFileMenuItem_Click(object sender, EventArgs e) - { - _textTable.Clear(); - } + private void CloseTableFileMenuItem_Click(object sender, EventArgs e) => _textTable.Clear(); public void LoadFileFromRecent(string path) { - var result = LoadTable(path); + bool result = LoadTable(path); if (!result) { RecentTables.HandleLoadError(MainForm, path); @@ -1382,7 +1359,7 @@ private string MakeCopyExportString(bool export) // find the maximum length of the exported string int maximumLength = addresses.Length * (export ? 3 : 2) + 8; - var sb = new StringBuilder(maximumLength); + StringBuilder sb = new(maximumLength); // generate it differently for export (as you see it) or copy (raw bytes) if (export) @@ -1396,7 +1373,7 @@ private string MakeCopyExportString(bool export) } else { - foreach (var addr in addresses) + foreach (long addr in addresses) { long start = addr; long end = addr + DataSize -1 ; @@ -1413,7 +1390,7 @@ private string MakeCopyExportString(bool export) private void ExportMenuItem_Click(object sender, EventArgs e) { - var value = MakeCopyExportString(true); + string value = MakeCopyExportString(true); if (!string.IsNullOrEmpty(value)) { Clipboard.SetDataObject(value); @@ -1422,7 +1399,7 @@ private void ExportMenuItem_Click(object sender, EventArgs e) private void CopyMenuItem_Click(object sender, EventArgs e) { - var value = MakeCopyExportString(false); + string value = MakeCopyExportString(false); if (!string.IsNullOrEmpty(value)) { Clipboard.SetDataObject(value); @@ -1437,15 +1414,15 @@ private void PasteMenuItem_Click(object sender, EventArgs e) { return; } - - var clipboardRaw = (string)data.GetData(DataFormats.Text); - var hex = clipboardRaw.OnlyHex(); - var numBytes = hex.Length / 2; - for (var i = 0; i < numBytes; i++) + string clipboardRaw = (string)data.GetData(DataFormats.Text); + string hex = clipboardRaw.OnlyHex(); + + int numBytes = hex.Length / 2; + for (int i = 0; i < numBytes; i++) { - var value = int.Parse(hex.Substring(i * 2, 2), NumberStyles.HexNumber); - var address = (_highlightedAddress ?? 0) + i; + int value = int.Parse(hex.Substring(i * 2, 2), NumberStyles.HexNumber); + long address = (_highlightedAddress ?? 0) + i; if (address < _domain.Size) { @@ -1457,10 +1434,7 @@ private void PasteMenuItem_Click(object sender, EventArgs e) } private bool _lastSearchWasText; - private void SearchTypeChanged(bool isText) - { - _lastSearchWasText = isText; - } + private void SearchTypeChanged(bool isText) => _lastSearchWasText = isText; private void FindMenuItem_Click(object sender, EventArgs e) { @@ -1484,15 +1458,9 @@ private void FindMenuItem_Click(object sender, EventArgs e) } } - private void FindNextMenuItem_Click(object sender, EventArgs e) - { - FindNext(_findStr, false); - } + private void FindNextMenuItem_Click(object sender, EventArgs e) => FindNext(_findStr, false); - private void FindPrevMenuItem_Click(object sender, EventArgs e) - { - FindPrev(_findStr, false); - } + private void FindPrevMenuItem_Click(object sender, EventArgs e) => FindPrev(_findStr, false); private void OptionsSubMenu_DropDownOpened(object sender, EventArgs e) { @@ -1527,7 +1495,7 @@ private void MemoryDomainsMenuItem_DropDownOpened(object sender, EventArgs e) if (_romDomain != null) { - var romMenuItem = new ToolStripMenuItem + ToolStripMenuItem romMenuItem = new() { Text = _romDomain.Name, Checked = _domain.Name == _romDomain.Name @@ -1540,20 +1508,11 @@ private void MemoryDomainsMenuItem_DropDownOpened(object sender, EventArgs e) } } - private void DataSizeByteMenuItem_Click(object sender, EventArgs e) - { - SetDataSize(1); - } + private void DataSizeByteMenuItem_Click(object sender, EventArgs e) => SetDataSize(1); - private void DataSizeWordMenuItem_Click(object sender, EventArgs e) - { - SetDataSize(2); - } + private void DataSizeWordMenuItem_Click(object sender, EventArgs e) => SetDataSize(2); - private void DataSizeDWordMenuItem_Click(object sender, EventArgs e) - { - SetDataSize(4); - } + private void DataSizeDWordMenuItem_Click(object sender, EventArgs e) => SetDataSize(4); private void BigEndianMenuItem_Click(object sender, EventArgs e) { @@ -1563,7 +1522,7 @@ private void BigEndianMenuItem_Click(object sender, EventArgs e) private void GoToAddressMenuItem_Click(object sender, EventArgs e) { - using var inputPrompt = new InputPrompt + using InputPrompt inputPrompt = new() { Text = "Go to Address", StartLocation = this.ChildPointToScreen(MemoryViewerBox), @@ -1603,7 +1562,7 @@ private void FreezeAddressMenuItem_Click(object sender, EventArgs e) if (_highlightedAddress.HasValue) { - var highlighted = _highlightedAddress.Value; + long highlighted = _highlightedAddress.Value; if (IsFrozen(highlighted)) { UnfreezeHighlighted(); @@ -1618,10 +1577,7 @@ private void FreezeAddressMenuItem_Click(object sender, EventArgs e) MemoryViewerBox.Refresh(); } - private void UnfreezeAllMenuItem_Click(object sender, EventArgs e) - { - MainForm.CheatList.RemoveAll(); - } + private void UnfreezeAllMenuItem_Click(object sender, EventArgs e) => MainForm.CheatList.RemoveAll(); private void PokeAddressMenuItem_Click(object sender, EventArgs e) { @@ -1630,7 +1586,7 @@ private void PokeAddressMenuItem_Click(object sender, EventArgs e) return; } - var addresses = new List(); + List addresses = new(); if (_highlightedAddress.HasValue) { addresses.Add(_highlightedAddress.Value); @@ -1651,7 +1607,7 @@ private void PokeAddressMenuItem_Click(object sender, EventArgs e) Common.WatchDisplayType.Hex, BigEndian)); - using var poke = new RamPoke(DialogController, watches, MainForm.CheatList) + using RamPoke poke = new(DialogController, watches, MainForm.CheatList) { InitialLocation = this.ChildPointToScreen(AddressLabel), ParentTool = this @@ -1664,7 +1620,7 @@ private void PokeAddressMenuItem_Click(object sender, EventArgs e) private void SetColorsMenuItem_Click(object sender, EventArgs e) { - using var form = new HexColorsForm(this); + using HexColorsForm form = new(this); this.ShowDialogWithTempMute(form); } @@ -1684,10 +1640,7 @@ private void HexEditor_Resize(object sender, EventArgs e) GeneralUpdate(); } - private void HexEditor_ResizeEnd(object sender, EventArgs e) - { - SetUpScrollBar(); - } + private void HexEditor_ResizeEnd(object sender, EventArgs e) => SetUpScrollBar(); private void HexEditor_KeyDown(object sender, KeyEventArgs e) { @@ -1711,7 +1664,7 @@ private void HexEditor_KeyDown(object sender, KeyEventArgs e) newHighlighted = currentAddress - 16; if (e.Modifiers == Keys.Shift) { - for (var i = newHighlighted + DataSize; i <= currentAddress; i += DataSize) + for (long i = newHighlighted + DataSize; i <= currentAddress; i += DataSize) { AddToSecondaryHighlights(i); } @@ -1729,7 +1682,7 @@ private void HexEditor_KeyDown(object sender, KeyEventArgs e) newHighlighted = currentAddress + 16; if (e.Modifiers == Keys.Shift) { - for (var i = currentAddress; i < newHighlighted; i += DataSize) + for (long i = currentAddress; i < newHighlighted; i += DataSize) { AddToSecondaryHighlights(i); } @@ -1775,7 +1728,7 @@ private void HexEditor_KeyDown(object sender, KeyEventArgs e) newHighlighted = currentAddress - (_rowsVisible * 16); if (e.Modifiers == Keys.Shift) { - for (var i = newHighlighted + 1; i <= currentAddress; i += DataSize) + for (long i = newHighlighted + 1; i <= currentAddress; i += DataSize) { AddToSecondaryHighlights(i); } @@ -1793,7 +1746,7 @@ private void HexEditor_KeyDown(object sender, KeyEventArgs e) newHighlighted = currentAddress + (_rowsVisible * 16); if (e.Modifiers == Keys.Shift) { - for (var i = currentAddress + 1; i < newHighlighted; i += DataSize) + for (long i = currentAddress + 1; i < newHighlighted; i += DataSize) { AddToSecondaryHighlights(i); } @@ -1822,7 +1775,7 @@ private void HexEditor_KeyDown(object sender, KeyEventArgs e) case Keys.Home: if (e.Modifiers == Keys.Shift) { - for (var i = 1; i <= currentAddress; i += DataSize) + for (int i = 1; i <= currentAddress; i += DataSize) { AddToSecondaryHighlights(i); } @@ -1840,7 +1793,7 @@ private void HexEditor_KeyDown(object sender, KeyEventArgs e) newHighlighted = _domain.Size - DataSize; if (e.Modifiers == Keys.Shift) { - for (var i = currentAddress; i < newHighlighted; i += DataSize) + for (long i = currentAddress; i < newHighlighted; i += DataSize) { AddToSecondaryHighlights(i); } @@ -1906,24 +1859,24 @@ private void HexEditor_KeyPress(object sender, KeyPressEventArgs e) return; } - var currentAddress = _highlightedAddress ?? 0; + long currentAddress = _highlightedAddress ?? 0; _nibbles.Add(e.KeyChar); if (_nibbles.Count == DataSize * 2) { - var nibbleStr = MakeNibbles(); + string nibbleStr = MakeNibbles(); switch (DataSize) { default: case 1: - var byteVal = byte.Parse(nibbleStr, NumberStyles.HexNumber); + byte byteVal = byte.Parse(nibbleStr, NumberStyles.HexNumber); _domain.PokeByte(currentAddress, byteVal); break; case 2: - var ushortVal = ushort.Parse(nibbleStr, NumberStyles.HexNumber); + ushort ushortVal = ushort.Parse(nibbleStr, NumberStyles.HexNumber); _domain.PokeUshort(currentAddress, ushortVal, BigEndian); break; case 4: - var uintVal = uint.Parse(nibbleStr, NumberStyles.HexNumber); + uint uintVal = uint.Parse(nibbleStr, NumberStyles.HexNumber); _domain.PokeUint(currentAddress, uintVal, BigEndian); break; } @@ -2013,7 +1966,7 @@ private void DecrementContextItem_Click(object sender, EventArgs e) private void HexEditor_MouseWheel(object sender, MouseEventArgs e) { - var delta = 0; + int delta = 0; if (e.Delta > 0) { delta = -1; @@ -2023,7 +1976,7 @@ private void HexEditor_MouseWheel(object sender, MouseEventArgs e) delta = 1; } - var newValue = HexScrollBar.Value + delta; + int newValue = HexScrollBar.Value + delta; if (newValue < HexScrollBar.Minimum) { newValue = HexScrollBar.Minimum; @@ -2050,7 +2003,7 @@ private void MemoryViewerBox_Paint(object sender, PaintEventArgs e) { if (_domain.ToString() == cheat.Domain.Name) { - var gaps = (int)cheat.Size - DataSize; + int gaps = (int)cheat.Size - DataSize; if (cheat.Size == WatchSize.DWord && DataSize == 2) { @@ -2058,10 +2011,10 @@ private void MemoryViewerBox_Paint(object sender, PaintEventArgs e) } if (gaps < 0) { gaps = 0; } - - var width = (_fontWidth * 2 * (int)cheat.Size) + (gaps * _fontWidth); - var rect = new Rectangle(GetAddressCoordinates(cheat.Address ?? 0), new Size(width, _fontHeight)); + int width = (_fontWidth * 2 * (int)cheat.Size) + (gaps * _fontWidth); + + Rectangle rect = new(GetAddressCoordinates(cheat.Address ?? 0), new Size(width, _fontHeight)); e.Graphics.DrawRectangle(_blackPen, rect); _freezeBrush.Color = Colors.Freeze; e.Graphics.FillRectangle(_freezeBrush, rect); @@ -2075,13 +2028,13 @@ private void MemoryViewerBox_Paint(object sender, PaintEventArgs e) // Create a slight offset to increase rectangle sizes var point = GetAddressCoordinates(addressHighlighted); - var textX = (int)GetTextX(addressHighlighted); - var textPoint = new Point(textX, point.Y); + int textX = (int)GetTextX(addressHighlighted); + Point textPoint = new(textX, point.Y); - var rect = new Rectangle(point, new Size(_fontWidth * 2 * DataSize + (NeedsExtra(addressHighlighted) ? _fontWidth : 0) + 2, _fontHeight)); + Rectangle rect = new(point, new Size(_fontWidth * 2 * DataSize + (NeedsExtra(addressHighlighted) ? _fontWidth : 0) + 2, _fontHeight)); e.Graphics.DrawRectangle(_blackPen, rect); - var textRect = new Rectangle(textPoint, new Size(_fontWidth * DataSize, _fontHeight)); + Rectangle textRect = new(textPoint, new Size(_fontWidth * DataSize, _fontHeight)); if (MainForm.CheatList.IsActive(_domain, addressHighlighted)) { @@ -2097,18 +2050,18 @@ private void MemoryViewerBox_Paint(object sender, PaintEventArgs e) } } - foreach (var address in _secondaryHighlightedAddresses) + foreach (long address in _secondaryHighlightedAddresses) { if (IsVisible(address)) { var point = GetAddressCoordinates(address); - var textX = (int)GetTextX(address); - var textPoint = new Point(textX, point.Y); + int textX = (int)GetTextX(address); + Point textPoint = new(textX, point.Y); - var rect = new Rectangle(point, new Size(_fontWidth * 2 * DataSize + 2, _fontHeight)); + Rectangle rect = new(point, new Size(_fontWidth * 2 * DataSize + 2, _fontHeight)); e.Graphics.DrawRectangle(_blackPen, rect); - var textRect = new Rectangle(textPoint, new Size(_fontWidth * DataSize, _fontHeight)); + Rectangle textRect = new(textPoint, new Size(_fontWidth * DataSize, _fontHeight)); if (MainForm.CheatList.IsActive(_domain, address)) { @@ -2126,10 +2079,7 @@ private void MemoryViewerBox_Paint(object sender, PaintEventArgs e) } } - private void AddressesLabel_MouseUp(object sender, MouseEventArgs e) - { - _mouseIsDown = false; - } + private void AddressesLabel_MouseUp(object sender, MouseEventArgs e) => _mouseIsDown = false; private void AddressesLabel_MouseMove(object sender, MouseEventArgs e) { @@ -2153,7 +2103,7 @@ private void AddressesLabel_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { - var pointedAddress = GetPointedAddress(e.X, e.Y); + long pointedAddress = GetPointedAddress(e.X, e.Y); if (pointedAddress >= 0) { if ((ModifierKeys & Keys.Control) == Keys.Control) @@ -2237,13 +2187,13 @@ private void viewN64MatrixToolStripMenuItem_Click(object sender, EventArgs e) }.ToString()); #endif - using var sw = new StringWriter(); + using StringWriter sw = new(); for (int i = 0; i < 4; i++) { sw.WriteLine("{0,18:0.00000} {1,18:0.00000} {2,18:0.00000} {3,18:0.00000}", matVals[i, 0], matVals[i, 1], matVals[i, 2], matVals[i, 3]); } - var str = sw.ToString(); + string str = sw.ToString(); DialogController.ShowMessageBox(str); } } diff --git a/src/BizHawk.Client.EmuHawk/tools/HexEditor/HexFind.cs b/src/BizHawk.Client.EmuHawk/tools/HexEditor/HexFind.cs index 2ef951eb13a..eb51b803bde 100644 --- a/src/BizHawk.Client.EmuHawk/tools/HexEditor/HexFind.cs +++ b/src/BizHawk.Client.EmuHawk/tools/HexEditor/HexFind.cs @@ -57,10 +57,10 @@ private string GetFindBoxChars() return FindBox.Text; } - var bytes = _hexEditor.ConvertTextToBytes(FindBox.Text); + byte[] bytes = _hexEditor.ConvertTextToBytes(FindBox.Text); - var byteString = new StringBuilder(); - foreach (var b in bytes) + StringBuilder byteString = new(); + foreach (byte b in bytes) { byteString.Append($"{b:X2}"); } @@ -68,19 +68,13 @@ private string GetFindBoxChars() return byteString.ToString(); } - private void Find_Prev_Click(object sender, EventArgs e) - { - _hexEditor.FindPrev(GetFindBoxChars(), false); - } + private void Find_Prev_Click(object sender, EventArgs e) => _hexEditor.FindPrev(GetFindBoxChars(), false); - private void Find_Next_Click(object sender, EventArgs e) - { - _hexEditor.FindNext(GetFindBoxChars(), false); - } + private void Find_Next_Click(object sender, EventArgs e) => _hexEditor.FindNext(GetFindBoxChars(), false); private void ChangeCasing() { - var text = FindBox.Text; + string text = FindBox.Text; var location = FindBox.Location; var size = FindBox.Size; diff --git a/src/BizHawk.Client.EmuHawk/tools/InputPrompt.cs b/src/BizHawk.Client.EmuHawk/tools/InputPrompt.cs index 595e5c7b3c9..5081ff595d7 100644 --- a/src/BizHawk.Client.EmuHawk/tools/InputPrompt.cs +++ b/src/BizHawk.Client.EmuHawk/tools/InputPrompt.cs @@ -70,7 +70,7 @@ private void PromptBox_KeyPress(object sender, KeyPressEventArgs e) case InputType.Text: break; case InputType.Hex: - if (e.KeyChar == '\b' || e.KeyChar == 22 || e.KeyChar == 1 || e.KeyChar == 3) + if (e.KeyChar is '\b' or (char)22 or (char)1 or (char)3) { return; } @@ -82,7 +82,7 @@ private void PromptBox_KeyPress(object sender, KeyPressEventArgs e) break; case InputType.Signed: - if (e.KeyChar == '\b' || e.KeyChar == 22 || e.KeyChar == 1 || e.KeyChar == 3) + if (e.KeyChar is '\b' or (char)22 or (char)1 or (char)3) { return; } @@ -94,7 +94,7 @@ private void PromptBox_KeyPress(object sender, KeyPressEventArgs e) break; case InputType.Unsigned: - if (e.KeyChar == '\b' || e.KeyChar == 22 || e.KeyChar == 1 || e.KeyChar == 3) + if (e.KeyChar is '\b' or (char)22 or (char)1 or (char)3) { return; } diff --git a/src/BizHawk.Client.EmuHawk/tools/Lua/Libraries/ConsoleLuaLibrary.cs b/src/BizHawk.Client.EmuHawk/tools/Lua/Libraries/ConsoleLuaLibrary.cs index 7feef97accc..5cc3a622270 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Lua/Libraries/ConsoleLuaLibrary.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Lua/Libraries/ConsoleLuaLibrary.cs @@ -32,7 +32,7 @@ public void Clear() [LuaMethod("getluafunctionslist", "returns a list of implemented functions")] public string GetLuaFunctionsList() { - var list = new StringBuilder(); + StringBuilder list = new(); foreach (var function in _luaLibsImpl.Docs) { list.AppendLine(function.Name); @@ -43,24 +43,15 @@ public string GetLuaFunctionsList() [LuaMethodExample("console.log( \"New log.\" );")] [LuaMethod("log", "Outputs the given object to the output box on the Lua Console dialog. Note: Can accept a LuaTable")] - public void Log(params object[] outputs) - { - LogWithSeparator("\t", "\n", outputs); - } + public void Log(params object[] outputs) => LogWithSeparator("\t", "\n", outputs); [LuaMethodExample("console.writeline( \"New log line.\" );")] [LuaMethod("writeline", "Outputs the given object to the output box on the Lua Console dialog. Note: Can accept a LuaTable")] - public void WriteLine(params object[] outputs) - { - LogWithSeparator("\n", "\n", outputs); - } + public void WriteLine(params object[] outputs) => LogWithSeparator("\n", "\n", outputs); [LuaMethodExample("console.write( \"New log message.\" );")] [LuaMethod("write", "Outputs the given object to the output box on the Lua Console dialog. Note: Can accept a LuaTable")] - public void Write(params object[] outputs) - { - LogWithSeparator("", "", outputs); - } + public void Write(params object[] outputs) => LogWithSeparator("", "", outputs); // Outputs the given object to the output box on the Lua Console dialog. Note: Can accept a LuaTable private void LogWithSeparator(string separator, string terminator, params object[] outputs) @@ -74,9 +65,9 @@ static string SerializeTable(LuaTable lti) throw new ArgumentException(message: "each value must be paired with one key, they differ in number", paramName: nameof(lti)); } - var values = new object[keyObjs.Count]; - var kvpIndex = 0; - foreach (var valueObj in valueObjs) + object[] values = new object[keyObjs.Count]; + int kvpIndex = 0; + foreach (object valueObj in valueObjs) { values[kvpIndex++] = valueObj; } @@ -91,7 +82,7 @@ static string SerializeTable(LuaTable lti) return; } - var sb = new StringBuilder(); + StringBuilder sb = new(); void SerializeAndWrite(object output) => sb.Append(output switch diff --git a/src/BizHawk.Client.EmuHawk/tools/Lua/Libraries/FormsLuaLibrary.cs b/src/BizHawk.Client.EmuHawk/tools/Lua/Libraries/FormsLuaLibrary.cs index 2e44ba11246..e589c4f1b1c 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Lua/Libraries/FormsLuaLibrary.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Lua/Libraries/FormsLuaLibrary.cs @@ -24,17 +24,17 @@ public FormsLuaLibrary(ILuaLibraries luaLibsImpl, ApiContainer apiContainer, Act public override string Name => "forms"; - private readonly List _luaForms = new List(); + private readonly List _luaForms = new(); public void WindowClosed(IntPtr handle) { - var i = _luaForms.FindIndex(form => form.Handle == handle); + int i = _luaForms.FindIndex(form => form.Handle == handle); if (i is not -1) _luaForms.RemoveAt(i); } private LuaWinform GetForm(long formHandle) { - var ptr = new IntPtr(formHandle); + IntPtr ptr = new(formHandle); return _luaForms.Find(form => form.Handle == ptr); } @@ -55,7 +55,7 @@ private static void SetText(Control control, string caption) [LuaMethod("addclick", "adds the given lua function as a click event to the given control")] public void AddClick(long handle, LuaFunction clickEvent) { - var ptr = new IntPtr(handle); + IntPtr ptr = new(handle); foreach (var form in _luaForms) { foreach (Control control in form.Controls) @@ -86,7 +86,7 @@ public long Button( return 0; } - var button = new LuaButton(); + LuaButton button = new(); SetText(button, caption); form.Controls.Add(button); form.ControlEvents.Add(new LuaWinform.LuaEvent(button.Handle, clickEvent)); @@ -115,7 +115,7 @@ public long Checkbox(long formHandle, string caption, int? x = null, int? y = nu return 0; } - var checkbox = new LuaCheckbox(); + LuaCheckbox checkbox = new(); form.Controls.Add(checkbox); SetText(checkbox, caption); @@ -131,7 +131,7 @@ public long Checkbox(long formHandle, string caption, int? x = null, int? y = nu [LuaMethod("clearclicks", "Removes all click events from the given widget at the specified handle")] public void ClearClicks(long handle) { - var ptr = new IntPtr(handle); + IntPtr ptr = new(handle); foreach (var form in _luaForms) { foreach (Control control in form.Controls) @@ -148,7 +148,7 @@ public void ClearClicks(long handle) [LuaMethod("destroy", "Closes and removes a Lua created form with the specified handle. If a dialog was found and removed true is returned, else false")] public bool Destroy(long handle) { - var ptr = new IntPtr(handle); + IntPtr ptr = new(handle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -166,7 +166,7 @@ public bool Destroy(long handle) [LuaMethod("destroyall", "Closes and removes all Lua created dialogs")] public void DestroyAll() { - for (var i = _luaForms.Count - 1; i >= 0; i--) + for (int i = _luaForms.Count - 1; i >= 0; i--) { _luaForms[i].Close(); } @@ -189,10 +189,10 @@ public long Dropdown( return 0; } - var dropdownItems = _th.EnumerateValues(items).ToList(); + List dropdownItems = _th.EnumerateValues(items).ToList(); dropdownItems.Sort(); - var dropdown = new LuaDropDown(dropdownItems); + LuaDropDown dropdown = new(dropdownItems); form.Controls.Add(dropdown); if (x.HasValue && y.HasValue) @@ -214,7 +214,7 @@ public string GetProperty(long handle, string property) { try { - var ptr = new IntPtr(handle); + IntPtr ptr = new(handle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -245,7 +245,7 @@ public string GetText(long handle) { try { - var ptr = new IntPtr(handle); + IntPtr ptr = new(handle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -274,7 +274,7 @@ public string GetText(long handle) [LuaMethod("ischecked", "Returns the given checkbox's checked property")] public bool IsChecked(long handle) { - var ptr = new IntPtr(handle); + IntPtr ptr = new(handle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -317,7 +317,7 @@ public long Label( return 0; } - var label = new Label(); + Label label = new(); if (fixedWidth) { label.Font = new Font("Courier New", 8); @@ -348,7 +348,7 @@ public long NewForm( string title = null, LuaFunction onClose = null) { - var form = new LuaWinform(CurrentFile, WindowClosed); + LuaWinform form = new(CurrentFile, WindowClosed); _luaForms.Add(form); if (width.HasValue && height.HasValue) { @@ -389,7 +389,7 @@ public string OpenFile( string filter = null) { if (initialDirectory is null && fileName is not null) initialDirectory = Path.GetDirectoryName(fileName); - var result = ((IDialogParent) MainForm).ShowFileOpenDialog( + string result = ((IDialogParent) MainForm).ShowFileOpenDialog( filterStr: filter ?? FilesystemFilter.AllFilesEntry, initDir: initialDirectory ?? PathEntries.LuaAbsolutePath(), initFileName: fileName); @@ -408,7 +408,7 @@ public long PictureBox(long formHandle, int? x = null, int? y = null, int? width return 0; } - var pictureBox = new LuaPictureBox { TableHelper = _th }; + LuaPictureBox pictureBox = new() { TableHelper = _th }; form.Controls.Add(pictureBox); if (x.HasValue && y.HasValue) @@ -434,7 +434,7 @@ public void Clear(long componentHandle, [LuaColorParam] object color) try { var color1 = _th.ParseColor(color); - var ptr = new IntPtr(componentHandle); + IntPtr ptr = new(componentHandle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -465,7 +465,7 @@ public void Refresh(long componentHandle) { try { - var ptr = new IntPtr(componentHandle); + IntPtr ptr = new(componentHandle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -497,7 +497,7 @@ public void SetDefaultForegroundColor(long componentHandle, [LuaColorParam] obje try { var color1 = _th.ParseColor(color); - var ptr = new IntPtr(componentHandle); + IntPtr ptr = new(componentHandle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -529,7 +529,7 @@ public void SetDefaultBackgroundColor(long componentHandle, [LuaColorParam] obje try { var color1 = _th.ParseColor(color); - var ptr = new IntPtr(componentHandle); + IntPtr ptr = new(componentHandle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -561,7 +561,7 @@ public void SetDefaultTextBackground(long componentHandle, [LuaColorParam] objec try { var color1 = _th.ParseColor(color); - var ptr = new IntPtr(componentHandle); + IntPtr ptr = new(componentHandle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -593,7 +593,7 @@ public void DrawBezier(long componentHandle, LuaTable points, [LuaColorParam] ob try { var color1 = _th.ParseColor(color); - var ptr = new IntPtr(componentHandle); + IntPtr ptr = new(componentHandle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -633,7 +633,7 @@ public void DrawBox( { var strokeColor = _th.SafeParseColor(line); var fillColor = _th.SafeParseColor(background); - var ptr = new IntPtr(componentHandle); + IntPtr ptr = new(componentHandle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -673,7 +673,7 @@ public void DrawEllipse( { var strokeColor = _th.SafeParseColor(line); var fillColor = _th.SafeParseColor(background); - var ptr = new IntPtr(componentHandle); + IntPtr ptr = new(componentHandle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -715,7 +715,7 @@ public void DrawIcon( } try { - var ptr = new IntPtr(componentHandle); + IntPtr ptr = new(componentHandle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -758,7 +758,7 @@ public void DrawImage( } try { - var ptr = new IntPtr(componentHandle); + IntPtr ptr = new(componentHandle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -789,7 +789,7 @@ public void ClearImageCache(long componentHandle) { try { - var ptr = new IntPtr(componentHandle); + IntPtr ptr = new(componentHandle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -835,7 +835,7 @@ public void DrawImageRegion( } try { - var ptr = new IntPtr(componentHandle); + IntPtr ptr = new(componentHandle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -867,7 +867,7 @@ public void DrawLine(long componentHandle, int x1, int y1, int x2, int y2, [LuaC try { var color1 = _th.SafeParseColor(color); - var ptr = new IntPtr(componentHandle); + IntPtr ptr = new(componentHandle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -899,7 +899,7 @@ public void DrawAxis(long componentHandle, int x, int y, int size, [LuaColorPara try { var color1 = _th.SafeParseColor(color); - var ptr = new IntPtr(componentHandle); + IntPtr ptr = new(componentHandle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -940,7 +940,7 @@ public void DrawArc( try { var strokeColor = _th.SafeParseColor(line); - var ptr = new IntPtr(componentHandle); + IntPtr ptr = new(componentHandle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -982,7 +982,7 @@ public void DrawPie( { var strokeColor = _th.SafeParseColor(line); var fillColor = _th.SafeParseColor(background); - var ptr = new IntPtr(componentHandle); + IntPtr ptr = new(componentHandle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -1014,7 +1014,7 @@ public void DrawPixel(long componentHandle, int x, int y, [LuaColorParam] object try { var color1 = _th.SafeParseColor(color); - var ptr = new IntPtr(componentHandle); + IntPtr ptr = new(componentHandle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -1053,7 +1053,7 @@ public void DrawPolygon( { var strokeColor = _th.SafeParseColor(line); var fillColor = _th.SafeParseColor(background); - var ptr = new IntPtr(componentHandle); + IntPtr ptr = new(componentHandle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -1094,7 +1094,7 @@ public void DrawRectangle( { var strokeColor = _th.SafeParseColor(line); var fillColor = _th.SafeParseColor(background); - var ptr = new IntPtr(componentHandle); + IntPtr ptr = new(componentHandle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -1138,7 +1138,7 @@ public void DrawString( { var fgColor = _th.SafeParseColor(forecolor); var bgColor = _th.SafeParseColor(backcolor); - var ptr = new IntPtr(componentHandle); + IntPtr ptr = new(componentHandle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -1182,7 +1182,7 @@ public void DrawText( { var fgColor = _th.SafeParseColor(forecolor); var bgColor = _th.SafeParseColor(backcolor); - var ptr = new IntPtr(componentHandle); + IntPtr ptr = new(componentHandle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -1214,7 +1214,7 @@ public int GetMouseX(long componentHandle) { try { - var ptr = new IntPtr(componentHandle); + IntPtr ptr = new(componentHandle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -1247,7 +1247,7 @@ public int GetMouseY(long componentHandle) { try { - var ptr = new IntPtr(componentHandle); + IntPtr ptr = new(componentHandle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -1278,7 +1278,7 @@ public void SetDropdownItems(long handle, LuaTable items, bool alphabetize = tru { try { - var ptr = new IntPtr(handle); + IntPtr ptr = new(handle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -1292,7 +1292,7 @@ public void SetDropdownItems(long handle, LuaTable items, bool alphabetize = tru { if (control is LuaDropDown ldd) { - var dropdownItems = _th.EnumerateValues(items).ToList(); + List dropdownItems = _th.EnumerateValues(items).ToList(); if (alphabetize) dropdownItems.Sort(); ldd.SetItems(dropdownItems); } @@ -1311,7 +1311,7 @@ public void SetDropdownItems(long handle, LuaTable items, bool alphabetize = tru [LuaMethod("setlocation", "Sets the location of a control or form by passing in the handle of the created object")] public void SetLocation(long handle, int x, int y) { - var ptr = new IntPtr(handle); + IntPtr ptr = new(handle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -1344,7 +1344,7 @@ void ParseAndSet(Control c) { var pi = c.GetType().GetProperty(property) ?? throw new Exception($"no property with the identifier {property}"); var pt = pi.PropertyType; - var o = pt.IsEnum + object o = pt.IsEnum ? Enum.Parse(pt, value.ToString(), true) : pt == typeof(Color) ? _th.ParseColor(value) @@ -1352,7 +1352,7 @@ void ParseAndSet(Control c) pi.SetValue(c, o, null); } - var ptr = new IntPtr(handle); + IntPtr ptr = new(handle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -1373,16 +1373,13 @@ void ParseAndSet(Control c) [LuaMethodExample("local coforcre = forms.createcolor( 0x7F, 0x3F, 0x1F, 0xCF );")] [LuaMethod("createcolor", "Creates a color object useful with setproperty")] - public Color CreateColor(int r, int g, int b, int a) - { - return Color.FromArgb(a, r, g, b); - } + public Color CreateColor(int r, int g, int b, int a) => Color.FromArgb(a, r, g, b); [LuaMethodExample("forms.setsize( 332, 77, 99 );")] [LuaMethod("setsize", "TODO")] public void SetSize(long handle, int width, int height) { - var ptr = new IntPtr(handle); + IntPtr ptr = new(handle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -1406,7 +1403,7 @@ public void SetSize(long handle, int width, int height) [LuaMethod("settext", "Sets the text property of a control or form by passing in the handle of the created object")] public void Settext(long handle, string caption) { - var ptr = new IntPtr(handle); + IntPtr ptr = new(handle); foreach (var form in _luaForms) { if (form.Handle == ptr) @@ -1447,7 +1444,7 @@ public long Textbox( return 0; } - var textbox = new LuaTextBox(); + LuaTextBox textbox = new(); if (fixedWidth) { textbox.Font = new Font("Courier New", 8); diff --git a/src/BizHawk.Client.EmuHawk/tools/Lua/Libraries/TAStudioLuaLibrary.cs b/src/BizHawk.Client.EmuHawk/tools/Lua/Libraries/TAStudioLuaLibrary.cs index 739ad363701..fd35c50da3c 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Lua/Libraries/TAStudioLuaLibrary.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Lua/Libraries/TAStudioLuaLibrary.cs @@ -60,21 +60,15 @@ public class TastudioBranchInfo public string Text { get; set; } } - private readonly List _changeList = new List(); //TODO: Initialize it to empty list on a script reload, and have each script have it's own list + private readonly List _changeList = new(); //TODO: Initialize it to empty list on a script reload, and have each script have it's own list [LuaMethodExample("if ( tastudio.engaged( ) ) then\r\n\tconsole.log( \"returns whether or not tastudio is currently engaged ( active )\" );\r\nend;")] [LuaMethod("engaged", "returns whether or not tastudio is currently engaged (active)")] - public bool Engaged() - { - return Tools.Has(); // TODO: eventually tastudio should have an engaged flag - } + public bool Engaged() => Tools.Has(); // TODO: eventually tastudio should have an engaged flag [LuaMethodExample("if ( tastudio.getrecording( ) ) then\r\n\tconsole.log( \"returns whether or not TAStudio is in recording mode\" );\r\nend;")] [LuaMethod("getrecording", "returns whether or not TAStudio is in recording mode")] - public bool GetRecording() - { - return Tastudio.TasPlaybackBox.RecordingMode; - } + public bool GetRecording() => Tastudio.TasPlaybackBox.RecordingMode; [LuaMethodExample("tastudio.setrecording( true );")] [LuaMethod("setrecording", "sets the recording mode on/off depending on the parameter")] @@ -88,10 +82,7 @@ public void SetRecording(bool val) [LuaMethodExample("tastudio.togglerecording( );")] [LuaMethod("togglerecording", "toggles tastudio recording mode on/off depending on its current state")] - public void SetRecording() - { - Tastudio.ToggleReadOnly(); - } + public void SetRecording() => Tastudio.ToggleReadOnly(); [LuaMethodExample("local botasisl = tastudio.islag( 500 );")] [LuaMethod("islag", "Returns whether or not the given frame was a lag frame, null if unknown")] @@ -363,7 +354,7 @@ public void AddColumn(string name, string text, int width) [LuaMethod("setbranchtext", "adds the given message to the existing branch, or to the branch that will be created next if branch index is not specified")] public void SetBranchText(string text, int? index = null) { - var text1 = text; + string text1 = text; if (index != null) { var branch = Tastudio.CurrentTasMovie.Branches[index.Value]; @@ -405,12 +396,12 @@ public LuaTable GetBranchInput(string branchId, int frame) var controller = Tastudio.GetBranchInput(branchId, frame); if (controller == null) return table; - foreach (var button in controller.Definition.BoolButtons) + foreach (string button in controller.Definition.BoolButtons) { table[button] = controller.IsPressed(button); } - foreach (var button in controller.Definition.Axes.Keys) + foreach (string button in controller.Definition.Axes.Keys) { table[button] = controller.AxisValue(button); } @@ -469,7 +460,7 @@ public void SetMarker(int frame, string message = null) { if (Engaged()) { - var message1 = message; + string message1 = message; var marker = Tastudio.CurrentTasMovie.Markers.Get(frame); if (marker != null) { @@ -501,7 +492,7 @@ public void OnQueryItemText(LuaFunction luaf) { Tastudio.QueryItemTextCallback = (index, name) => { - var result = luaf.Call(index, name); + object[] result = luaf.Call(index, name); return result?[0]?.ToString(); }; } @@ -515,7 +506,7 @@ public void OnQueryItemIcon(LuaFunction luaf) { Tastudio.QueryItemIconCallback = (index, name) => { - var result = luaf.Call(index, name); + object[] result = luaf.Call(index, name); if (result?[0] != null) { return _iconCache.GetValueOrPutNew1(result[0].ToString()).ToBitmap(); diff --git a/src/BizHawk.Client.EmuHawk/tools/Lua/LuaAutocompleteInstaller.cs b/src/BizHawk.Client.EmuHawk/tools/Lua/LuaAutocompleteInstaller.cs index 95df15dd123..a68b6b74e43 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Lua/LuaAutocompleteInstaller.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Lua/LuaAutocompleteInstaller.cs @@ -62,7 +62,7 @@ private bool IsNotepadInstalled() private bool IsBizLuaSublimeInstalled() { - var bizCompletions = Path.Combine(AppDataFolder, SublimeLuaPath, SublimeCompletionsFilename); + string bizCompletions = Path.Combine(AppDataFolder, SublimeLuaPath, SublimeCompletionsFilename); return File.Exists(bizCompletions); } @@ -71,23 +71,23 @@ private bool IsBizLuaSublimeInstalled() private bool IsBizLuaNotepadInstalled() { - var bizCompletions = Path.Combine(AppDataFolder, NotepadPath, NotepadAutoCompleteFileName); + string bizCompletions = Path.Combine(AppDataFolder, NotepadPath, NotepadAutoCompleteFileName); return File.Exists(bizCompletions); } private void InstallBizLuaToSublime2(LuaDocumentation docs) { - var bizCompletions = Path.Combine(AppDataFolder, SublimeLuaPath, SublimeCompletionsFilename); + string bizCompletions = Path.Combine(AppDataFolder, SublimeLuaPath, SublimeCompletionsFilename); - var text = docs.ToSublime2CompletionList(); + string text = docs.ToSublime2CompletionList(); File.WriteAllText(bizCompletions, text); } private void InstallBizLuaToNotepad(LuaDocumentation docs) { - var bizAutocomplete = Path.Combine(AppDataFolder, NotepadPath, NotepadAutoCompleteFileName); + string bizAutocomplete = Path.Combine(AppDataFolder, NotepadPath, NotepadAutoCompleteFileName); - var text = docs.ToNotepadPlusPlusAutoComplete(); + string text = docs.ToNotepadPlusPlusAutoComplete(); // TODO //File.WriteAllText(bizCompletions, text); diff --git a/src/BizHawk.Client.EmuHawk/tools/Lua/LuaCanvas.cs b/src/BizHawk.Client.EmuHawk/tools/Lua/LuaCanvas.cs index 6da3fcc0d5c..01d7c97b89a 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Lua/LuaCanvas.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Lua/LuaCanvas.cs @@ -105,50 +105,35 @@ public void SetLocation(int x, int y) [LuaMethod( "Clear", "Clears the canvas")] - public void Clear([LuaColorParam] object color) - { - luaPictureBox.Clear(_th.ParseColor(color)); - } + public void Clear([LuaColorParam] object color) => luaPictureBox.Clear(_th.ParseColor(color)); [LuaMethodExample( "LuaCanvas.Refresh( );")] [LuaMethod( "Refresh", "Redraws the canvas")] - public new void Refresh() - { - luaPictureBox.Refresh(); - } + public new void Refresh() => luaPictureBox.Refresh(); [LuaMethodExample( "LuaCanvas.SetDefaultForegroundColor( 0x000000FF );")] [LuaMethod( "SetDefaultForegroundColor", "Sets the default foreground color to use in drawing methods, white by default")] - public void SetDefaultForegroundColor([LuaColorParam] object color) - { - luaPictureBox.SetDefaultForegroundColor(_th.ParseColor(color)); - } + public void SetDefaultForegroundColor([LuaColorParam] object color) => luaPictureBox.SetDefaultForegroundColor(_th.ParseColor(color)); [LuaMethodExample( "LuaCanvas.SetDefaultBackgroundColor( 0x000000FF );")] [LuaMethod( "SetDefaultBackgroundColor", "Sets the default background color to use in drawing methods, transparent by default")] - public void SetDefaultBackgroundColor([LuaColorParam] object color) - { - luaPictureBox.SetDefaultBackgroundColor(_th.ParseColor(color)); - } + public void SetDefaultBackgroundColor([LuaColorParam] object color) => luaPictureBox.SetDefaultBackgroundColor(_th.ParseColor(color)); [LuaMethodExample( "LuaCanvas.SetDefaultTextBackground( 0x000000FF );")] [LuaMethod( "SetDefaultTextBackground", "Sets the default background color to use in text drawing methods, half-transparent black by default")] - public void SetDefaultTextBackground([LuaColorParam] object color) - { - luaPictureBox.SetDefaultTextBackground(_th.ParseColor(color)); - } + public void SetDefaultTextBackground([LuaColorParam] object color) => luaPictureBox.SetDefaultTextBackground(_th.ParseColor(color)); [LuaMethodExample( "LuaCanvas.DrawBezier( { { 5, 10 }, { 10, 10 }, { 10, 20 }, { 5, 20 } }, 0x000000FF );")] @@ -243,7 +228,7 @@ public void DrawImage( int? height = null, bool cache = true) { - var path1 = path; + string path1 = path; if (!File.Exists(path1)) { LogOutputCallback($"File not found: {path1}\nScript Terminated"); @@ -257,10 +242,7 @@ public void DrawImage( [LuaMethod( "ClearImageCache", "clears the image cache that is built up by using gui.drawImage, also releases the file handle for cached images")] - public void ClearImageCache() - { - luaPictureBox.ClearImageCache(); - } + public void ClearImageCache() => luaPictureBox.ClearImageCache(); [LuaMethodExample( "LuaCanvas.DrawImageRegion( \"C:\\image.png\", 11, 22, 33, 44, 21, 43, 34, 45 );")] @@ -278,7 +260,7 @@ public void DrawImageRegion( int? destWidth = null, int? destHeight = null) { - var path1 = path; + string path1 = path; if (!File.Exists(path1)) { LogOutputCallback($"File not found: {path1}\nScript Terminated"); @@ -292,20 +274,14 @@ public void DrawImageRegion( [LuaMethod( "DrawLine", "Draws a line from the first coordinate pair to the 2nd. Color is optional (if not specified it will be drawn black)")] - public void DrawLine(int x1, int y1, int x2, int y2, [LuaColorParam] object color = null) - { - luaPictureBox.DrawLine(x1, y1, x2, y2, _th.SafeParseColor(color)); - } + public void DrawLine(int x1, int y1, int x2, int y2, [LuaColorParam] object color = null) => luaPictureBox.DrawLine(x1, y1, x2, y2, _th.SafeParseColor(color)); [LuaMethodExample( "LuaCanvas.DrawAxis( 16, 32, int size, 0xFFFFFFFF );")] [LuaMethod( "DrawAxis", "Draws an axis of the specified size at the coordinate pair.)")] - public void DrawAxis(int x, int y, int size, [LuaColorParam] object color = null) - { - luaPictureBox.DrawAxis(x, y, size, _th.SafeParseColor(color)); - } + public void DrawAxis(int x, int y, int size, [LuaColorParam] object color = null) => luaPictureBox.DrawAxis(x, y, size, _th.SafeParseColor(color)); [LuaMethodExample( "LuaCanvas.DrawArc( 16, 32, 77, 99, 180, 90, 0x007F00FF );")] @@ -320,10 +296,7 @@ public void DrawArc( int height, int startAngle, int sweepAngle, - [LuaColorParam] object line = null) - { - luaPictureBox.DrawArc(x, y, width, height, startAngle, sweepAngle, _th.SafeParseColor(line)); - } + [LuaColorParam] object line = null) => luaPictureBox.DrawArc(x, y, width, height, startAngle, sweepAngle, _th.SafeParseColor(line)); [LuaMethodExample( "LuaCanvas.DrawPie( 16, 32, 77, 99, 180, 90, 0x007F00FF, 0x7F7F7FFF );")] @@ -338,10 +311,7 @@ public void DrawPie( int startAngle, int sweepAngle, [LuaColorParam] object line = null, - [LuaColorParam] object background = null) - { - luaPictureBox.DrawPie(x, y, width, height, startAngle, sweepAngle, _th.SafeParseColor(line), _th.SafeParseColor(background)); - } + [LuaColorParam] object background = null) => luaPictureBox.DrawPie(x, y, width, height, startAngle, sweepAngle, _th.SafeParseColor(line), _th.SafeParseColor(background)); [LuaMethodExample( "LuaCanvas.DrawPixel( 16, 32, 0xFFFFFFFF );")] @@ -394,10 +364,7 @@ public void DrawRectangle( int width, int height, [LuaColorParam] object line = null, - [LuaColorParam] object background = null) - { - luaPictureBox.DrawRectangle(x, y, width, height, _th.SafeParseColor(line), _th.SafeParseColor(background)); - } + [LuaColorParam] object background = null) => luaPictureBox.DrawRectangle(x, y, width, height, _th.SafeParseColor(line), _th.SafeParseColor(background)); [LuaMethodExample( "LuaCanvas.DrawString( 16, 32, \"Some message\", 0x7F0000FF, 0x00007FFF, 8, \"Arial Narrow\", \"bold\", \"center\", \"middle\" );")] @@ -414,10 +381,7 @@ public void DrawString( string fontFamily = null, string fontStyle = null, string horizontalAlign = null, - string verticalAlign = null) - { - luaPictureBox.DrawText(x, y, message, _th.SafeParseColor(foreColor), _th.SafeParseColor(backColor), fontSize, fontFamily, fontStyle, horizontalAlign, verticalAlign); - } + string verticalAlign = null) => luaPictureBox.DrawText(x, y, message, _th.SafeParseColor(foreColor), _th.SafeParseColor(backColor), fontSize, fontFamily, fontStyle, horizontalAlign, verticalAlign); [LuaMethodExample( "LuaCanvas.DrawText( 16, 32, \"Some message\", 0x7F0000FF, 0x00007FFF, 8, \"Arial Narrow\", \"bold\", \"center\", \"middle\" );")] @@ -434,10 +398,7 @@ public void DrawText( string fontFamily = null, string fontStyle = null, string horizontalAlign = null, - string verticalAlign = null) - { - luaPictureBox.DrawText(x, y, message, _th.SafeParseColor(foreColor), _th.SafeParseColor(backColor), fontSize, fontFamily, fontStyle, horizontalAlign, verticalAlign); - } + string verticalAlign = null) => luaPictureBox.DrawText(x, y, message, _th.SafeParseColor(foreColor), _th.SafeParseColor(backColor), fontSize, fontFamily, fontStyle, horizontalAlign, verticalAlign); // It'd be great if these were simplified into 1 function, but I cannot figure out how to return a LuaTable from this class @@ -464,9 +425,6 @@ public int GetMouseY() } [LuaMethod("save_image_to_disk", "Saves everything that's been drawn to a .png file at the given path. Relative paths are relative to the path set for \"Screenshots\" for the current system.")] - public void SaveImageToDisk(string path) - { - luaPictureBox.Image.Save(path.MakeAbsolute(_emuLib.PathEntries.ScreenshotAbsolutePathFor(_emuLib.GetSystemId()))); - } + public void SaveImageToDisk(string path) => luaPictureBox.Image.Save(path.MakeAbsolute(_emuLib.PathEntries.ScreenshotAbsolutePathFor(_emuLib.GetSystemId()))); } } diff --git a/src/BizHawk.Client.EmuHawk/tools/Lua/LuaCheckbox.cs b/src/BizHawk.Client.EmuHawk/tools/Lua/LuaCheckbox.cs index 5f61da99931..16d1aaef205 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Lua/LuaCheckbox.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Lua/LuaCheckbox.cs @@ -7,7 +7,7 @@ public class LuaCheckbox : CheckBox { private void DoLuaClick(object sender, EventArgs e) { - var parent = Parent as LuaWinform; + LuaWinform parent = Parent as LuaWinform; parent?.DoLuaEvent(Handle); } diff --git a/src/BizHawk.Client.EmuHawk/tools/Lua/LuaConsole.cs b/src/BizHawk.Client.EmuHawk/tools/Lua/LuaConsole.cs index f0c0196d3ea..95a8dd0846a 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Lua/LuaConsole.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Lua/LuaConsole.cs @@ -29,12 +29,12 @@ public partial class LuaConsole : ToolFormBase, IToolFormAutoConfig private static readonly FilesystemFilterSet ScriptsAndTextFilesFSFilterSet = new(FilesystemFilter.LuaScripts, FilesystemFilter.TextFiles); - private static readonly FilesystemFilterSet SessionsFSFilterSet = new FilesystemFilterSet(new FilesystemFilter("Lua Session Files", new[] { "luases" })); + private static readonly FilesystemFilterSet SessionsFSFilterSet = new(new FilesystemFilter("Lua Session Files", new[] { "luases" })); public static Icon ToolIcon => Resources.TextDocIcon; - private readonly LuaAutocompleteInstaller _luaAutoInstaller = new LuaAutocompleteInstaller(); + private readonly LuaAutocompleteInstaller _luaAutoInstaller = new(); private readonly Dictionary _watches = new(); private readonly int _defaultSplitDistance; @@ -45,7 +45,7 @@ public static Icon ToolIcon private bool _sortReverse; private string _lastColumnSorted; - private readonly List _consoleCommandHistory = new List(); + private readonly List _consoleCommandHistory = new(); private int _consoleCommandHistoryIndex = -1; public ToolDialogSettings.ColumnList Columns { get; set; } @@ -180,10 +180,7 @@ private void LuaConsole_Load(object sender, EventArgs e) splitContainer1.SetDistanceOrDefault(Settings.SplitDistance, _defaultSplitDistance); } - private void BranchesMarkersSplit_SplitterMoved(object sender, SplitterEventArgs e) - { - Settings.SplitDistance = splitContainer1.SplitterDistance; - } + private void BranchesMarkersSplit_SplitterMoved(object sender, SplitterEventArgs e) => Settings.SplitDistance = splitContainer1.SplitterDistance; public override void Restart() { @@ -283,7 +280,7 @@ private void CreateFileWatcher(LuaFile item) if (!Directory.Exists(dir)) return; - var watcher = new FileSystemWatcher + FileSystemWatcher watcher = new() { Path = dir, Filter = file, @@ -317,7 +314,7 @@ private void OnLuaFileChanged(LuaFile item) public void LoadLuaFile(string path) { - var absolutePath = Path.GetFullPath(path); + string absolutePath = Path.GetFullPath(path); var alreadyLoadedFile = LuaImp.ScriptList.FirstOrDefault(t => absolutePath == t.Path); if (alreadyLoadedFile is not null) @@ -329,7 +326,7 @@ public void LoadLuaFile(string path) } else { - var luaFile = new LuaFile("", absolutePath); + LuaFile luaFile = new("", absolutePath); LuaImp.ScriptList.Add(luaFile); LuaListView.RowCount = LuaImp.ScriptList.Count; @@ -356,7 +353,7 @@ public void LoadLuaFile(string path) public void RemoveLuaFile(string path) { - var absolutePath = Path.GetFullPath(path); + string absolutePath = Path.GetFullPath(path); var luaFile = LuaImp.ScriptList.FirstOrDefault(t => absolutePath == t.Path); if (luaFile is not null) @@ -445,17 +442,14 @@ private void LuaListView_QueryItemText(int index, RollColumn column, out string } } - private string DressUpRelative(string path) - { - return path.StartsWithOrdinal(".\\") ? path.Replace(".\\", "") : path; - } + private string DressUpRelative(string path) => path.StartsWithOrdinal(".\\") ? path.Replace(".\\", "") : path; private void UpdateNumberOfScripts() { - var message = ""; - var total = LuaImp.ScriptList.Count(file => !file.IsSeparator); - var active = LuaImp.ScriptList.Count(file => !file.IsSeparator && file.Enabled); - var paused = LuaImp.ScriptList.Count(static lf => !lf.IsSeparator && lf.Paused); + string message = ""; + int total = LuaImp.ScriptList.Count(file => !file.IsSeparator); + int active = LuaImp.ScriptList.Count(file => !file.IsSeparator && file.Enabled); + int paused = LuaImp.ScriptList.Count(static lf => !lf.IsSeparator && lf.Paused); if (total == 1) { @@ -514,7 +508,7 @@ public bool LoadLuaSession(string path) { RemoveAllLuaFiles(); - var result = LuaImp.ScriptList.Load(path, Settings.DisableLuaScriptsOnLoad); + bool result = LuaImp.ScriptList.Load(path, Settings.DisableLuaScriptsOnLoad); foreach (var script in LuaImp.ScriptList) { @@ -577,7 +571,7 @@ protected override void FastUpdateAfter() private void ResetDrawSurfacePadding() { - var resized = false; + bool resized = false; if (DisplayManager.ClientExtraPadding != (0, 0, 0, 0)) { DisplayManager.ClientExtraPadding = (0, 0, 0, 0); @@ -610,7 +604,7 @@ public void ResumeScripts(bool includeFrameWaiters) { LuaSandbox.Sandbox(lf.Thread, () => { - var prohibit = lf.FrameWaiting && !includeFrameWaiters; + bool prohibit = lf.FrameWaiting && !includeFrameWaiters; if (!prohibit) { var (waitForFrame, terminated) = LuaImp.ResumeScript(lf); @@ -662,7 +656,7 @@ private FileInfo GetSaveFileFromUser() initDir = Config!.PathEntries.LuaAbsolutePath(); initFileName = Game.IsNullInstance() ? "NULL" : Game.FilesystemSafeName(); } - var result = this.ShowFileSaveDialog( + string result = this.ShowFileSaveDialog( discardCWDChange: true, filter: SessionsFSFilterSet, initDir: initDir, @@ -683,7 +677,7 @@ private void SaveSessionAs() private void LoadSessionFromRecent(string path) { - var load = true; + bool load = true; if (LuaImp.ScriptList.Changes) { load = AskSaveChanges(); @@ -748,10 +742,7 @@ private void SaveOrSaveAs() } } - private void FileSubMenu_DropDownOpened(object sender, EventArgs e) - { - SaveSessionMenuItem.Enabled = LuaImp.ScriptList.Changes; - } + private void FileSubMenu_DropDownOpened(object sender, EventArgs e) => SaveSessionMenuItem.Enabled = LuaImp.ScriptList.Changes; private void RecentSessionsSubMenu_DropDownOpened(object sender, EventArgs e) => RecentSessionsSubMenu.ReplaceDropDownItems(Config!.RecentLuaSession.RecentMenu(this, LoadSessionFromRecent, "Session")); @@ -761,7 +752,7 @@ private void RecentScriptsSubMenu_DropDownOpened(object sender, EventArgs e) private void NewSessionMenuItem_Click(object sender, EventArgs e) { - var result = !LuaImp.ScriptList.Changes || AskSaveChanges(); + bool result = !LuaImp.ScriptList.Changes || AskSaveChanges(); if (result) { @@ -774,9 +765,9 @@ private void NewSessionMenuItem_Click(object sender, EventArgs e) private void OpenSessionMenuItem_Click(object sender, EventArgs e) { - var initDir = Config!.PathEntries.LuaAbsolutePath(); + string initDir = Config!.PathEntries.LuaAbsolutePath(); Directory.CreateDirectory(initDir); - var result = this.ShowFileOpenDialog( + string result = this.ShowFileOpenDialog( discardCWDChange: true, filter: SessionsFSFilterSet, initDir: initDir); @@ -792,10 +783,7 @@ private void SaveSessionMenuItem_Click(object sender, EventArgs e) } } - private void SaveSessionAsMenuItem_Click(object sender, EventArgs e) - { - SaveSessionAs(); - } + private void SaveSessionAsMenuItem_Click(object sender, EventArgs e) => SaveSessionAs(); private void ScriptSubMenu_DropDownOpened(object sender, EventArgs e) { @@ -817,7 +805,7 @@ private void ScriptSubMenu_DropDownOpened(object sender, EventArgs e) private void NewScriptMenuItem_Click(object sender, EventArgs e) { - var luaDir = Config!.PathEntries.LuaAbsolutePath(); + string luaDir = Config!.PathEntries.LuaAbsolutePath(); string initDir; string ext; if (!string.IsNullOrWhiteSpace(LuaImp.ScriptList.Filename)) @@ -829,14 +817,14 @@ private void NewScriptMenuItem_Click(object sender, EventArgs e) initDir = luaDir; ext = Path.GetFileNameWithoutExtension(Game.Name); } - var result = this.ShowFileSaveDialog( + string result = this.ShowFileSaveDialog( fileExt: ".lua", filter: JustScriptsFSFilterSet, initDir: initDir, initFileName: ext); if (string.IsNullOrWhiteSpace(result)) return; const string TEMPLATE_FILENAME = ".template.lua"; - var templatePath = Path.Combine(luaDir, TEMPLATE_FILENAME); + string templatePath = Path.Combine(luaDir, TEMPLATE_FILENAME); const string DEF_TEMPLATE_CONTENTS = "-- This template lives at `.../Lua/.template.lua`.\nwhile true do\n\t-- Code here will run once when the script is loaded, then after each emulated frame.\n\temu.frameadvance();\nend\n"; if (!File.Exists(templatePath)) File.WriteAllText(path: templatePath, contents: DEF_TEMPLATE_CONTENTS); if (!Settings.WarnedOnceOnOverwrite && File.Exists(result)) @@ -868,14 +856,14 @@ private void NewScriptMenuItem_Click(object sender, EventArgs e) private void OpenScriptMenuItem_Click(object sender, EventArgs e) { - var initDir = Config!.PathEntries.LuaAbsolutePath(); + string initDir = Config!.PathEntries.LuaAbsolutePath(); Directory.CreateDirectory(initDir); var result = this.ShowFileMultiOpenDialog( discardCWDChange: true, filter: ScriptsAndTextFilesFSFilterSet, initDir: initDir); if (result is null) return; - foreach (var file in result) + foreach (string file in result) { LoadLuaFile(file); Config.RecentLua.Add(file); @@ -947,7 +935,7 @@ private void EditScriptMenuItem_Click(object sender, EventArgs e) private void RemoveScriptMenuItem_Click(object sender, EventArgs e) { - var items = SelectedItems.ToList(); + List items = SelectedItems.ToList(); if (items.Any()) { foreach (var item in items) @@ -976,7 +964,7 @@ private void DuplicateScriptMenuItem_Click(object sender, EventArgs e) } var (dir, fileNoExt, _) = script.Path.SplitPathToDirFileAndExt(); - var result = this.ShowFileSaveDialog( + string result = this.ShowFileSaveDialog( fileExt: ".lua", filter: JustScriptsFSFilterSet, initDir: dir, @@ -995,10 +983,7 @@ private void DuplicateScriptMenuItem_Click(object sender, EventArgs e) } } - private void ClearConsoleMenuItem_Click(object sender, EventArgs e) - { - ClearOutputWindow(); - } + private void ClearConsoleMenuItem_Click(object sender, EventArgs e) => ClearOutputWindow(); private void InsertSeparatorMenuItem_Click(object sender, EventArgs e) { @@ -1008,13 +993,13 @@ private void InsertSeparatorMenuItem_Click(object sender, EventArgs e) private void MoveUpMenuItem_Click(object sender, EventArgs e) { - var indices = LuaListView.SelectedRows.ToList(); + List indices = LuaListView.SelectedRows.ToList(); if (indices.Count == 0 || indices[0] == 0) { return; } - foreach (var index in indices) + foreach (int index in indices) { var file = LuaImp.ScriptList[index]; LuaImp.ScriptList.Remove(file); @@ -1024,7 +1009,7 @@ private void MoveUpMenuItem_Click(object sender, EventArgs e) var newIndices = indices.Select(t => t - 1); LuaListView.DeselectAll(); - foreach (var i in newIndices) + foreach (int i in newIndices) { LuaListView.SelectRow(i, true); } @@ -1034,14 +1019,14 @@ private void MoveUpMenuItem_Click(object sender, EventArgs e) private void MoveDownMenuItem_Click(object sender, EventArgs e) { - var indices = LuaListView.SelectedRows.ToList(); + List indices = LuaListView.SelectedRows.ToList(); if (indices.Count == 0 || indices[^1] == LuaImp.ScriptList.Count - 1) // at end already { return; } - for (var i = indices.Count - 1; i >= 0; i--) + for (int i = indices.Count - 1; i >= 0; i--) { var file = LuaImp.ScriptList[indices[i]]; LuaImp.ScriptList.Remove(file); @@ -1051,7 +1036,7 @@ private void MoveDownMenuItem_Click(object sender, EventArgs e) var newIndices = indices.Select(t => t + 1); LuaListView.DeselectAll(); - foreach (var i in newIndices) + foreach (int i in newIndices) { LuaListView.SelectRow(i, true); } @@ -1075,7 +1060,7 @@ private void RegisteredFunctionsMenuItem_Click(object sender, EventArgs e) { if (LuaImp.RegisteredFunctions.Any()) { - var alreadyOpen = false; + bool alreadyOpen = false; foreach (Form form in Application.OpenForms) { if (form is LuaRegisteredFunctionsList) @@ -1102,15 +1087,9 @@ private void OptionsSubMenu_DropDownOpened(object sender, EventArgs e) ReloadWhenScriptFileChangesMenuItem.Checked = Settings.ReloadOnScriptFileChange; } - private void DisableScriptsOnLoadMenuItem_Click(object sender, EventArgs e) - { - Settings.DisableLuaScriptsOnLoad ^= true; - } + private void DisableScriptsOnLoadMenuItem_Click(object sender, EventArgs e) => Settings.DisableLuaScriptsOnLoad ^= true; - private void ToggleAllIfNoneSelectedMenuItem_Click(object sender, EventArgs e) - { - Settings.ToggleAllIfNoneSelected ^= true; - } + private void ToggleAllIfNoneSelectedMenuItem_Click(object sender, EventArgs e) => Settings.ToggleAllIfNoneSelected ^= true; private void ReloadWhenScriptFileChangesMenuItem_Click(object sender, EventArgs e) { @@ -1176,25 +1155,13 @@ private void RegisterToTextEditorsSubMenu_DropDownOpened(object sender, EventArg } } - private void RegisterSublimeText2MenuItem_Click(object sender, EventArgs e) - { - _luaAutoInstaller.InstallBizLua(LuaAutocompleteInstaller.TextEditors.Sublime2, LuaImp.Docs); - } + private void RegisterSublimeText2MenuItem_Click(object sender, EventArgs e) => _luaAutoInstaller.InstallBizLua(LuaAutocompleteInstaller.TextEditors.Sublime2, LuaImp.Docs); - private void RegisterNotePadMenuItem_Click(object sender, EventArgs e) - { - _luaAutoInstaller.InstallBizLua(LuaAutocompleteInstaller.TextEditors.NotePad, LuaImp.Docs); - } + private void RegisterNotePadMenuItem_Click(object sender, EventArgs e) => _luaAutoInstaller.InstallBizLua(LuaAutocompleteInstaller.TextEditors.NotePad, LuaImp.Docs); - private void FunctionsListMenuItem_Click(object sender, EventArgs e) - { - new LuaFunctionsForm(LuaImp.Docs).Show(); - } + private void FunctionsListMenuItem_Click(object sender, EventArgs e) => new LuaFunctionsForm(LuaImp.Docs).Show(); - private void OnlineDocsMenuItem_Click(object sender, EventArgs e) - { - Process.Start("https://tasvideos.org/BizHawk/LuaFunctions"); - } + private void OnlineDocsMenuItem_Click(object sender, EventArgs e) => Process.Start("https://tasvideos.org/BizHawk/LuaFunctions"); private void ScriptListContextMenu_Opening(object sender, CancelEventArgs e) { @@ -1223,10 +1190,7 @@ private void ConsoleContextMenu_Opening(object sender, CancelEventArgs e) LuaImp.RegisteredFunctions.Any(); } - private void ClearConsoleContextItem_Click(object sender, EventArgs e) - { - ClearOutputWindow(); - } + private void ClearConsoleContextItem_Click(object sender, EventArgs e) => ClearOutputWindow(); private void SelectAllContextItem_Click(object sender, EventArgs e) { @@ -1256,19 +1220,16 @@ private void CopyContextItem_Click(object sender, EventArgs e) }); } - private void ClearRegisteredFunctionsContextMenuItem_Click(object sender, EventArgs e) - { - LuaImp.RegisteredFunctions.Clear(Emulator); - } + private void ClearRegisteredFunctionsContextMenuItem_Click(object sender, EventArgs e) => LuaImp.RegisteredFunctions.Clear(Emulator); private void LuaConsole_DragDrop(object sender, DragEventArgs e) { - var filePaths = (string[])e.Data.GetData(DataFormats.FileDrop); + string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop); try { - foreach (var path in filePaths) + foreach (string path in filePaths) { - if (Path.GetExtension(path)?.ToLowerInvariant() == ".lua" || Path.GetExtension(path)?.ToLowerInvariant() == ".txt") + if (Path.GetExtension(path)?.ToLowerInvariant() is ".lua" or ".txt") { LoadLuaFile(path); UpdateDialog(); @@ -1315,8 +1276,8 @@ private void OutputBox_KeyDown(object sender, KeyEventArgs e) /// private void LuaListView_ColumnClick(object sender, InputRoll.ColumnClickEventArgs e) { - var columnToSort = e.Column.Name; - var luaListTemp = new List(); + string columnToSort = e.Column.Name; + List luaListTemp = new(); if (columnToSort != _lastColumnSorted) { _sortReverse = false; @@ -1324,10 +1285,10 @@ private void LuaListView_ColumnClick(object sender, InputRoll.ColumnClickEventAr // For getting the name of the .lua file, for some reason this field is kept blank in LuaFile.cs? // The Name variable gets emptied again near the end just in case it would break something. - for (var i = 0; i < LuaImp.ScriptList.Count; i++) + for (int i = 0; i < LuaImp.ScriptList.Count; i++) { - var words = Regex.Split(LuaImp.ScriptList[i].Path, ".lua"); - var split = words[0].Split(Path.DirectorySeparatorChar); + string[] words = Regex.Split(LuaImp.ScriptList[i].Path, ".lua"); + string[] split = words[0].Split(Path.DirectorySeparatorChar); luaListTemp.Add(LuaImp.ScriptList[i]); luaListTemp[i].Name = split[^1]; @@ -1350,7 +1311,7 @@ private void LuaListView_ColumnClick(object sender, InputRoll.ColumnClickEventAr break; } - for (var i = 0; i < LuaImp.ScriptList.Count; i++) + for (int i = 0; i < LuaImp.ScriptList.Count; i++) { LuaImp.ScriptList[i] = luaListTemp[i]; LuaImp.ScriptList[i].Name = ""; @@ -1455,26 +1416,18 @@ protected override bool ProcessCmdKey(ref Message msg, Keys keyData) return base.ProcessCmdKey(ref msg, keyData); } - protected override bool ProcessTabKey(bool forward) - { + protected override bool ProcessTabKey(bool forward) => // TODO: Make me less dirty (please) - return false; - } + false; - private void EraseToolbarItem_Click(object sender, EventArgs e) - { - DisplayManager.ClearApiHawkSurfaces(); - } + private void EraseToolbarItem_Click(object sender, EventArgs e) => DisplayManager.ClearApiHawkSurfaces(); // Stupid designer - protected void DragEnterWrapper(object sender, DragEventArgs e) - { - GenericDragEnter(sender, e); - } + protected void DragEnterWrapper(object sender, DragEventArgs e) => GenericDragEnter(sender, e); private void LuaListView_DoubleClick(object sender, EventArgs e) { - var index = LuaListView.CurrentCell?.RowIndex; + int? index = LuaListView.CurrentCell?.RowIndex; if (index < LuaImp.ScriptList.Count) { var file = LuaImp.ScriptList[index.Value]; @@ -1524,6 +1477,7 @@ private void RefreshLuaScript(LuaFile file) ToggleLuaScript(file); } + #pragma warning disable IDE0051 [RestoreDefaults] private void RestoreDefaults() { @@ -1533,5 +1487,6 @@ private void RestoreDefaults() splitContainer1.SplitterDistance = _defaultSplitDistance; UpdateDialog(); } + #pragma warning restore IDE0051 } } diff --git a/src/BizHawk.Client.EmuHawk/tools/Lua/LuaFunctionsForm.cs b/src/BizHawk.Client.EmuHawk/tools/Lua/LuaFunctionsForm.cs index 877135034df..0c5b10f7dc4 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Lua/LuaFunctionsForm.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Lua/LuaFunctionsForm.cs @@ -13,10 +13,10 @@ namespace BizHawk.Client.EmuHawk public partial class LuaFunctionsForm : Form { private readonly LuaDocumentation _docs; - private readonly Sorting _columnSort = new Sorting(); + private readonly Sorting _columnSort = new(); - private List _functionList = new List(); - private List _filteredList = new List(); + private List _functionList = new(); + private List _filteredList = new(); public LuaFunctionsForm(LuaDocumentation docs) { @@ -58,7 +58,7 @@ private void FunctionView_QueryItemText(object sender, RetrieveVirtualItemEventA e.Item = new ListViewItem(entry.ReturnType); e.Item.SubItems.Add(entry.Library); - var deprecated = entry.IsDeprecated ? "[Deprecated] " : ""; + string deprecated = entry.IsDeprecated ? "[Deprecated] " : ""; e.Item.SubItems.Add(deprecated + entry.Name); e.Item.SubItems.Add(entry.ParameterList); e.Item.SubItems.Add(entry.Description); @@ -81,15 +81,9 @@ private void OrderColumn(int column) UpdateList(); } - private void Ok_Click(object sender, EventArgs e) - { - Close(); - } + private void Ok_Click(object sender, EventArgs e) => Close(); - private void FunctionView_ColumnClick(object sender, ColumnClickEventArgs e) - { - OrderColumn(e.Column); - } + private void FunctionView_ColumnClick(object sender, ColumnClickEventArgs e) => OrderColumn(e.Column); private class Sorting { @@ -127,7 +121,7 @@ private void FunctionView_Copy(object sender, EventArgs e) return; } - var sb = new StringBuilder(); + StringBuilder sb = new(); foreach (int index in FunctionView.SelectedIndices) { var itm = _filteredList[index]; @@ -152,14 +146,8 @@ private void UpdateList() FunctionView.Refresh(); } - private void FilterBox_KeyUp(object sender, KeyEventArgs e) - { - UpdateList(); - } + private void FilterBox_KeyUp(object sender, KeyEventArgs e) => UpdateList(); - private void ToWikiMarkupButton_Click(object sender, EventArgs e) - { - Clipboard.SetDataObject(_docs.ToTASVideosWikiMarkup()); - } + private void ToWikiMarkupButton_Click(object sender, EventArgs e) => Clipboard.SetDataObject(_docs.ToTASVideosWikiMarkup()); } } diff --git a/src/BizHawk.Client.EmuHawk/tools/Lua/LuaLibraries.cs b/src/BizHawk.Client.EmuHawk/tools/Lua/LuaLibraries.cs index 38b53b33f63..b9fb78ab592 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Lua/LuaLibraries.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Lua/LuaLibraries.cs @@ -33,7 +33,7 @@ void EnumerateLuaFunctions(string name, Type type, LuaLibraryBase instance) if (instance != null) _lua.NewTable(name); foreach (var method in type.GetMethods()) { - var foundAttrs = method.GetCustomAttributes(typeof(LuaMethodAttribute), false); + object[] foundAttrs = method.GetCustomAttributes(typeof(LuaMethodAttribute), false); if (foundAttrs.Length == 0) continue; if (instance != null) _lua.RegisterFunction($"{name}.{((LuaMethodAttribute)foundAttrs[0]).Name}", instance, method); LibraryFunction libFunc = new( @@ -64,7 +64,7 @@ void EnumerateLuaFunctions(string name, Type type, LuaLibraryBase instance) if (VersionInfo.DeveloperBuild || lib.GetCustomAttribute(inherit: false)?.Released is not false) { - var instance = (LuaLibraryBase)Activator.CreateInstance(lib, this, _apiContainer, (Action)LogToLuaConsole); + LuaLibraryBase instance = (LuaLibraryBase)Activator.CreateInstance(lib, this, _apiContainer, (Action)LogToLuaConsole); if (!ServiceInjector.UpdateServices(serviceProvider, instance, mayCache: true)) throw new Exception("Lua lib has required service(s) that can't be fulfilled"); // TODO: make EmuHawk libraries have a base class with common properties such as this @@ -87,7 +87,7 @@ void EnumerateLuaFunctions(string name, Type type, LuaLibraryBase instance) // emu lib may be null now, depending on order of ReflectionCache.Types, but definitely won't be null when this is called guiLib.CreateLuaCanvasCallback = (width, height, x, y) => { - var canvas = new LuaCanvas(EmulationLuaLibrary, width, height, x, y, _th, LogToLuaConsole); + LuaCanvas canvas = new(EmulationLuaLibrary, width, height, x, y, _th, LogToLuaConsole); canvas.Show(); return _th.ObjectToTable(canvas); }; @@ -104,8 +104,8 @@ void EnumerateLuaFunctions(string name, Type type, LuaLibraryBase instance) _lua.RegisterFunction("print", this, typeof(LuaLibraries).GetMethod(nameof(Print))); - var packageTable = (LuaTable) _lua["package"]; - var luaPath = PathEntries.LuaAbsolutePath(); + LuaTable packageTable = (LuaTable) _lua["package"]; + string luaPath = PathEntries.LuaAbsolutePath(); if (OSTailoredCode.IsUnixHost) { // add %exe%/Lua to library resolution pathset (LUA_PATH) @@ -160,7 +160,7 @@ void EnumerateLuaFunctions(string name, Type type, LuaLibraryBase instance) private readonly IDictionary Libraries = new Dictionary(); - private EventWaitHandle LuaWait; + private readonly EventWaitHandle LuaWait; public PathEntryCollection PathEntries { get; private set; } @@ -298,7 +298,7 @@ public INamedLuaFunction CreateAndRegisterNamedFunction( LuaFile luaFile, string name = null) { - var nlf = new NamedLuaFunction(function, theEvent, logCallback, luaFile, + NamedLuaFunction nlf = new(function, theEvent, logCallback, luaFile, () => { _lua.NewThread(out var thread); return thread; }, name); RegisteredFunctions.Add(nlf); return nlf; @@ -306,7 +306,7 @@ public INamedLuaFunction CreateAndRegisterNamedFunction( public bool RemoveNamedFunctionMatching(Func predicate) { - var nlf = (NamedLuaFunction)RegisteredFunctions.FirstOrDefault(predicate); + NamedLuaFunction nlf = (NamedLuaFunction)RegisteredFunctions.FirstOrDefault(predicate); if (nlf == null) return false; RegisteredFunctions.Remove(nlf, _mainForm.Emulator); return true; @@ -314,7 +314,7 @@ public bool RemoveNamedFunctionMatching(Func predicate) public LuaThread SpawnCoroutine(string file) { - var content = File.ReadAllText(file); + string content = File.ReadAllText(file); var main = _lua.LoadString(content, "main"); _lua.NewThread(main, out var ret); return ret; @@ -354,10 +354,7 @@ public void ExecuteString(string command) } } - public static void Print(params object[] outputs) - { - _logToLuaConsoleCallback(outputs); - } + public static void Print(params object[] outputs) => _logToLuaConsoleCallback(outputs); private void FrameAdvance() { @@ -365,9 +362,6 @@ private void FrameAdvance() _currThread.Yield(); } - private void EmuYield() - { - _currThread.Yield(); - } + private void EmuYield() => _currThread.Yield(); } } diff --git a/src/BizHawk.Client.EmuHawk/tools/Lua/LuaPictureBox.cs b/src/BizHawk.Client.EmuHawk/tools/Lua/LuaPictureBox.cs index 91e7118690c..22cf3177514 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Lua/LuaPictureBox.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Lua/LuaPictureBox.cs @@ -13,10 +13,10 @@ namespace BizHawk.Client.EmuHawk { public class LuaPictureBox : PictureBox { - private readonly Dictionary _imageCache = new Dictionary(); + private readonly Dictionary _imageCache = new(); - private readonly Dictionary _solidBrushes = new Dictionary(); - private readonly Dictionary _pens = new Dictionary(); + private readonly Dictionary _solidBrushes = new(); + private readonly Dictionary _pens = new(); internal NLuaTableHelper TableHelper { get; set; } @@ -44,30 +44,21 @@ public void LuaResize(int width, int height) public void Clear([LuaColorParam] object color) { - var boxBackground = Graphics.FromImage(Image); + Graphics boxBackground = Graphics.FromImage(Image); boxBackground.Clear(TableHelper.ParseColor(color)); } - public void SetDefaultForegroundColor([LuaColorParam] object color) - { - _defaultForeground = TableHelper.ParseColor(color); - } + public void SetDefaultForegroundColor([LuaColorParam] object color) => _defaultForeground = TableHelper.ParseColor(color); - public void SetDefaultBackgroundColor([LuaColorParam] object color) - { - _defaultBackground = TableHelper.ParseColor(color); - } + public void SetDefaultBackgroundColor([LuaColorParam] object color) => _defaultBackground = TableHelper.ParseColor(color); - public void SetDefaultTextBackground([LuaColorParam] object color) - { - _defaultTextBackground = TableHelper.ParseColor(color); - } + public void SetDefaultTextBackground([LuaColorParam] object color) => _defaultTextBackground = TableHelper.ParseColor(color); public void DrawBezier(LuaTable points, [LuaColorParam] object color) { - var pointsArr = new Point[4]; + Point[] pointsArr = new Point[4]; - var i = 0; + int i = 0; foreach (var point in TableHelper.EnumerateValues(points) .Select(table => TableHelper.EnumerateValues(table).ToList())) { @@ -79,7 +70,7 @@ public void DrawBezier(LuaTable points, [LuaColorParam] object color) } } - var boxBackground = Graphics.FromImage(Image); + Graphics boxBackground = Graphics.FromImage(Image); boxBackground.DrawBezier(GetPen(TableHelper.ParseColor(color)), pointsArr[0], pointsArr[1], pointsArr[2], pointsArr[3]); } @@ -105,7 +96,7 @@ public void DrawBox(int x, int y, int x2, int y2, [LuaColorParam] object line = y -= y2; } - var boxBackground = Graphics.FromImage(Image); + Graphics boxBackground = Graphics.FromImage(Image); boxBackground.DrawRectangle(GetPen(TableHelper.SafeParseColor(line) ?? _defaultForeground), x, y, x2, y2); var bg = TableHelper.SafeParseColor(background) ?? _defaultBackground; @@ -119,7 +110,7 @@ public void DrawBox(int x, int y, int x2, int y2, [LuaColorParam] object line = public void DrawEllipse(int x, int y, int width, int height, [LuaColorParam] object line = null, [LuaColorParam] object background = null) { var bg = TableHelper.SafeParseColor(background) ?? _defaultBackground; - var boxBackground = Graphics.FromImage(Image); + Graphics boxBackground = Graphics.FromImage(Image); if (bg.HasValue) { var brush = GetBrush(bg.Value); @@ -142,7 +133,7 @@ public void DrawIcon(string path, int x, int y, int? width = null, int? height = icon = new Icon(path); } - var boxBackground = Graphics.FromImage(Image); + Graphics boxBackground = Graphics.FromImage(Image); boxBackground.DrawIcon(icon, x, y); } @@ -157,7 +148,7 @@ public void DrawImage(string path, int x, int y, int? width = null, int? height } } - var boxBackground = Graphics.FromImage(Image); + Graphics boxBackground = Graphics.FromImage(Image); boxBackground.DrawImage(img, x, y, width ?? img.Width, height ?? img.Height); } @@ -174,15 +165,15 @@ public void ClearImageCache() public void DrawImageRegion(string path, int sourceX, int sourceY, int sourceWidth, int sourceHeight, int destX, int destY, int? destWidth = null, int? destHeight = null) { var img = _imageCache.GetValueOrPut(path, Image.FromFile); - var destRect = new Rectangle(destX, destY, destWidth ?? sourceWidth, destHeight ?? sourceHeight); + Rectangle destRect = new(destX, destY, destWidth ?? sourceWidth, destHeight ?? sourceHeight); - var boxBackground = Graphics.FromImage(Image); + Graphics boxBackground = Graphics.FromImage(Image); boxBackground.DrawImage(img, destRect, sourceX, sourceY, sourceWidth, sourceHeight, GraphicsUnit.Pixel); } public void DrawLine(int x1, int y1, int x2, int y2, [LuaColorParam] object color = null) { - var boxBackground = Graphics.FromImage(Image); + Graphics boxBackground = Graphics.FromImage(Image); boxBackground.DrawLine(GetPen(TableHelper.SafeParseColor(color) ?? _defaultForeground), x1, y1, x2, y2); } @@ -195,7 +186,7 @@ public void DrawAxis(int x, int y, int size, [LuaColorParam] object color = null public void DrawArc(int x, int y, int width, int height, int startAngle, int sweepAngle, [LuaColorParam] object line = null) { - var boxBackground = Graphics.FromImage(Image); + Graphics boxBackground = Graphics.FromImage(Image); boxBackground.DrawArc(GetPen(TableHelper.SafeParseColor(line) ?? _defaultForeground), x, y, width, height, startAngle, sweepAngle); } @@ -210,7 +201,7 @@ public void DrawPie( [LuaColorParam] object background = null) { var bg = TableHelper.SafeParseColor(background) ?? _defaultBackground; - var boxBackground = Graphics.FromImage(Image); + Graphics boxBackground = Graphics.FromImage(Image); if (bg.HasValue) { var brush = GetBrush(bg.Value); @@ -223,23 +214,23 @@ public void DrawPie( public void DrawPixel(int x, int y, [LuaColorParam] object color = null) { - var boxBackground = Graphics.FromImage(Image); + Graphics boxBackground = Graphics.FromImage(Image); boxBackground.DrawLine(GetPen(TableHelper.SafeParseColor(color) ?? _defaultForeground), x, y, x + 0.1F, y); } public void DrawPolygon(LuaTable points, int? x = null, int? y = null, [LuaColorParam] object line = null, [LuaColorParam] object background = null) { - var pointsList = TableHelper.EnumerateValues(points) + List> pointsList = TableHelper.EnumerateValues(points) .Select(table => TableHelper.EnumerateValues(table).ToList()).ToList(); - var pointsArr = new Point[pointsList.Count]; - var i = 0; + Point[] pointsArr = new Point[pointsList.Count]; + int i = 0; foreach (var point in pointsList) { pointsArr[i] = new Point((int) point[0] + x ?? 0, (int) point[1] + y ?? 0); i++; } - var boxBackground = Graphics.FromImage(Image); + Graphics boxBackground = Graphics.FromImage(Image); boxBackground.DrawPolygon(GetPen(TableHelper.SafeParseColor(line) ?? _defaultForeground), pointsArr); var bg = TableHelper.SafeParseColor(background) ?? _defaultBackground; if (bg.HasValue) @@ -252,7 +243,7 @@ public void DrawPolygon(LuaTable points, int? x = null, int? y = null, [LuaColor public void DrawRectangle(int x, int y, int width, int height, [LuaColorParam] object line = null, [LuaColorParam] object background = null) { var bg = TableHelper.SafeParseColor(background) ?? _defaultBackground; - var boxBackground = Graphics.FromImage(Image); + Graphics boxBackground = Graphics.FromImage(Image); if (bg.HasValue) { boxBackground.FillRectangle(GetBrush(bg.Value), x, y, width, height); @@ -303,9 +294,9 @@ public void DrawText( } } - var f = new StringFormat(StringFormat.GenericDefault); - var font = new Font(family, fontSize ?? 12, fStyle, GraphicsUnit.Pixel); - var boxBackground = Graphics.FromImage(Image); + StringFormat f = new(StringFormat.GenericDefault); + Font font = new(family, fontSize ?? 12, fStyle, GraphicsUnit.Pixel); + Graphics boxBackground = Graphics.FromImage(Image); Size sizeOfText = boxBackground.MeasureString(message, font, 0, f).ToSize(); @@ -342,7 +333,7 @@ public void DrawText( break; } } - Rectangle rect = new Rectangle(new Point(x, y), sizeOfText); + Rectangle rect = new(new Point(x, y), sizeOfText); boxBackground = Graphics.FromImage(Image); boxBackground.FillRectangle(GetBrush(TableHelper.SafeParseColor(backColor) ?? _defaultTextBackground.Value), rect); boxBackground = Graphics.FromImage(Image); diff --git a/src/BizHawk.Client.EmuHawk/tools/Lua/LuaRegisteredFunctionsList.cs b/src/BizHawk.Client.EmuHawk/tools/Lua/LuaRegisteredFunctionsList.cs index 844c5fb4d13..e7d448e95ec 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Lua/LuaRegisteredFunctionsList.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Lua/LuaRegisteredFunctionsList.cs @@ -38,10 +38,7 @@ private void LuaRegisteredFunctionsList_Load(object sender, EventArgs e) PopulateListView(); } - private void OK_Click(object sender, EventArgs e) - { - Close(); - } + private void OK_Click(object sender, EventArgs e) => Close(); private void PopulateListView() { @@ -52,7 +49,7 @@ private void PopulateListView() .ThenBy(f => f.Name); foreach (var nlf in functions) { - var item = new ListViewItem { Text = nlf.Event }; + ListViewItem item = new() { Text = nlf.Event }; item.SubItems.Add(nlf.Name); item.SubItems.Add(nlf.Guid.ToString()); FunctionView.Items.Add(item); @@ -61,15 +58,9 @@ private void PopulateListView() DoButtonsStatus(); } - private void CallButton_Click(object sender, EventArgs e) - { - CallFunction(); - } + private void CallButton_Click(object sender, EventArgs e) => CallFunction(); - private void RemoveButton_Click(object sender, EventArgs e) - { - RemoveFunctionButton(); - } + private void RemoveButton_Click(object sender, EventArgs e) => RemoveFunctionButton(); private void CallFunction() { @@ -78,7 +69,7 @@ private void CallFunction() { foreach (int index in indices) { - var guid = FunctionView.Items[index].SubItems[2].Text; + string guid = FunctionView.Items[index].SubItems[2].Text; _registeredFunctions[guid].Call(); } } @@ -91,7 +82,7 @@ private void RemoveFunctionButton() { foreach (int index in indices) { - var guid = FunctionView.Items[index].SubItems[2].Text; + string guid = FunctionView.Items[index].SubItems[2].Text; var nlf = _registeredFunctions[guid]; _registeredFunctions.Remove(nlf, _mainForm.Emulator); } @@ -100,15 +91,9 @@ private void RemoveFunctionButton() } } - private void FunctionView_SelectedIndexChanged(object sender, EventArgs e) - { - DoButtonsStatus(); - } + private void FunctionView_SelectedIndexChanged(object sender, EventArgs e) => DoButtonsStatus(); - private void FunctionView_DoubleClick(object sender, EventArgs e) - { - CallFunction(); - } + private void FunctionView_DoubleClick(object sender, EventArgs e) => CallFunction(); private void RemoveAllBtn_Click(object sender, EventArgs e) { diff --git a/src/BizHawk.Client.EmuHawk/tools/Lua/LuaTextBox.cs b/src/BizHawk.Client.EmuHawk/tools/Lua/LuaTextBox.cs index d67658db6de..3cded75dbcc 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Lua/LuaTextBox.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Lua/LuaTextBox.cs @@ -76,7 +76,7 @@ private void Increment() switch (_boxType) { case BoxType.Hex: - var hVal = uint.Parse(text, NumberStyles.HexNumber); + uint hVal = uint.Parse(text, NumberStyles.HexNumber); if (hVal < uint.MaxValue) { hVal++; @@ -89,7 +89,7 @@ private void Increment() break; case BoxType.Signed: - var sval = int.Parse(text); + int sval = int.Parse(text); if (sval < int.MaxValue) { sval++; @@ -102,7 +102,7 @@ private void Increment() break; case BoxType.Unsigned: - var uval = uint.Parse(text); + uint uval = uint.Parse(text); if (uval < uint.MaxValue) { uval++; @@ -123,7 +123,7 @@ private void Decrement() switch (_boxType) { case BoxType.Hex: - var hVal = uint.Parse(text, NumberStyles.HexNumber); + uint hVal = uint.Parse(text, NumberStyles.HexNumber); if (hVal > 0) { hVal--; @@ -132,12 +132,12 @@ private void Decrement() break; case BoxType.Signed: - var sval = int.Parse(text); + int sval = int.Parse(text); sval--; Text = sval.ToString(); break; case BoxType.Unsigned: - var uval = uint.Parse(text); + uint uval = uint.Parse(text); if (uval > 0) { uval--; diff --git a/src/BizHawk.Client.EmuHawk/tools/Lua/LuaWinform.cs b/src/BizHawk.Client.EmuHawk/tools/Lua/LuaWinform.cs index 91647177054..1f3313d594a 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Lua/LuaWinform.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Lua/LuaWinform.cs @@ -30,7 +30,7 @@ public void DoLuaEvent(IntPtr handle) LuaSandbox.Sandbox(_ownerFile?.Thread, () => { Environment.CurrentDirectory = _currentDirectory; - foreach (LuaEvent luaEvent in ControlEvents) + foreach (var luaEvent in ControlEvents) { if (luaEvent.Control == handle) { diff --git a/src/BizHawk.Client.EmuHawk/tools/Macros/MacroInput.ButtonSelect.cs b/src/BizHawk.Client.EmuHawk/tools/Macros/MacroInput.ButtonSelect.cs index dc5beeaabdc..44a6fe1f0ca 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Macros/MacroInput.ButtonSelect.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Macros/MacroInput.ButtonSelect.cs @@ -15,12 +15,12 @@ private void SetUpButtonBoxes() for (int i = 0; i < def.Axes.Count; i++) { - var box = new CheckBox { Text = def.Axes[i] }; + CheckBox box = new() { Text = def.Axes[i] }; _buttonBoxes[i] = box; } for (int i = 0; i < def.BoolButtons.Count; i++) { - var box = new CheckBox { Text = def.BoolButtons[i] }; + CheckBox box = new() { Text = def.BoolButtons[i] }; _buttonBoxes[i + def.Axes.Count] = box; } diff --git a/src/BizHawk.Client.EmuHawk/tools/Macros/MacroInput.cs b/src/BizHawk.Client.EmuHawk/tools/Macros/MacroInput.cs index 3823a2d81b7..27ed16f12f9 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Macros/MacroInput.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Macros/MacroInput.cs @@ -16,13 +16,13 @@ public partial class MacroInputTool : ToolFormBase, IToolFormAutoConfig [RequiredService] private IEmulator Emulator { get; set; } - public static readonly FilesystemFilterSet MacrosFSFilterSet = new FilesystemFilterSet(new FilesystemFilter("Movie Macros", new[] { "bk2m" })); + public static readonly FilesystemFilterSet MacrosFSFilterSet = new(new FilesystemFilter("Movie Macros", new[] { "bk2m" })); public static Icon ToolIcon => Properties.Resources.TAStudioIcon; - private readonly List _zones = new List(); - private readonly List _unsavedZones = new List(); + private readonly List _zones = new(); + private readonly List _unsavedZones = new(); private bool _selecting; private IMovie CurrentMovie => MovieSession.Movie; @@ -55,7 +55,7 @@ private void MacroInputTool_Load(object sender, EventArgs e) ReplaceBox.Enabled = OverlayBox.Enabled = PlaceNum.Enabled = CurrentMovie is ITasMovie; - var main = new MovieZone(Emulator, Tools, MovieSession, 0, CurrentMovie.InputLogLength) + MovieZone main = new(Emulator, Tools, MovieSession, 0, CurrentMovie.InputLogLength) { Name = "Entire Movie" }; @@ -102,7 +102,7 @@ public override bool AskSaveChanges() return true; } - var result = DialogController.ShowMessageBox3("You have unsaved macro(s). Do you wish to save them?", "Save?"); + bool? result = DialogController.ShowMessageBox3("You have unsaved macro(s). Do you wish to save them?", "Save?"); if (result == null) { return false; @@ -113,7 +113,7 @@ public override bool AskSaveChanges() return true; } - foreach (var zone in _unsavedZones) + foreach (int zone in _unsavedZones) { SaveMacroAs(_zones[zone]); } @@ -129,7 +129,7 @@ private void SetZoneButton_Click(object sender, EventArgs e) return; } - var newZone = new MovieZone(Emulator, Tools, MovieSession, (int) StartNum.Value, (int) (EndNum.Value - StartNum.Value + 1)) + MovieZone newZone = new(Emulator, Tools, MovieSession, (int) StartNum.Value, (int) (EndNum.Value - StartNum.Value + 1)) { Name = $"Zone {_zones.Count}" }; @@ -197,10 +197,7 @@ private void OverlayBox_CheckedChanged(object sender, EventArgs e) SelectedZone.Overlay = OverlayBox.Checked; } - private void CurrentButton_Click(object sender, EventArgs e) - { - PlaceNum.Value = Emulator.Frame; - } + private void CurrentButton_Click(object sender, EventArgs e) => PlaceNum.Value = Emulator.Frame; private void PlaceZoneButton_Click(object sender, EventArgs e) { @@ -231,7 +228,7 @@ private void SaveAsToolStripMenuItem_Click(object sender, EventArgs e) private void LoadMacroToolStripMenuItem_Click(object sender, EventArgs e) { - MovieZone loadZone = LoadMacro(); + var loadZone = LoadMacro(); if (loadZone != null) { _zones.Add(loadZone); @@ -251,7 +248,7 @@ private void RecentToolStripMenuItem_DropDownOpened(object sender, EventArgs e) private void DummyLoadMacro(string path) { - MovieZone loadZone = new MovieZone(path, MainForm, Emulator, MovieSession, Tools); + MovieZone loadZone = new(path, MainForm, Emulator, MovieSession, Tools); _zones.Add(loadZone); ZonesList.Items.Add($"{loadZone.Name} - length: {loadZone.Length}"); } @@ -275,7 +272,7 @@ private bool SaveMacroAs(MovieZone macro) create = true; } - var result = this.ShowFileSaveDialog( + string result = this.ShowFileSaveDialog( filter: MacrosFSFilterSet, initDir: suggestedFolder, initFileName: macro.Name); @@ -297,7 +294,7 @@ private bool SaveMacroAs(MovieZone macro) private MovieZone LoadMacro(IEmulator emulator = null, ToolManager tools = null) { - var result = this.ShowFileOpenDialog( + string result = this.ShowFileOpenDialog( filter: MacrosFSFilterSet, initDir: SuggestedFolder(Config, Game)); if (result is null) return null; diff --git a/src/BizHawk.Client.EmuHawk/tools/Macros/MovieZone.cs b/src/BizHawk.Client.EmuHawk/tools/Macros/MovieZone.cs index 6dc2f0b5814..7874b689f20 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Macros/MovieZone.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Macros/MovieZone.cs @@ -73,7 +73,7 @@ private void InitController(string key) { string[] keys = key.Split('|'); ControllerDefinition d = new(_emulator.ControllerDefinition.Name); - foreach (var k in keys) + foreach (string k in keys) { if (_emulator.ControllerDefinition.BoolButtons.Contains(k)) { @@ -106,7 +106,7 @@ private void ReSetLog() // Get a IController that only contains buttons in key. string[] keys = _inputKey.Split('|'); ControllerDefinition d = new(_emulator.ControllerDefinition.Name); - foreach (var key in keys) + foreach (string key in keys) { if (_emulator.ControllerDefinition.BoolButtons.Contains(key)) { @@ -242,7 +242,7 @@ public MovieZone(string fileName, IDialogController dialogController, IEmulator key = key[..^1]; string[] emuKeys = key.Split('|'); string[] macroKeys = _inputKey.Split('|'); - foreach (var macro in macroKeys) + foreach (string macro in macroKeys) { if (!emuKeys.Contains(macro)) { @@ -289,7 +289,7 @@ private void ORLatchFromSource(IMovieController latching, IController source) foreach (string name in latching.Definition.Axes.Keys) { - var axisValue = source.AxisValue(name); + int axisValue = source.AxisValue(name); if (axisValue == source.Definition.Axes[name].Neutral) { latching.SetAxis(name, axisValue); diff --git a/src/BizHawk.Client.EmuHawk/tools/MultiDiskBundler/MultiDiskBundler.cs b/src/BizHawk.Client.EmuHawk/tools/MultiDiskBundler/MultiDiskBundler.cs index 4842cc1f865..35234fda0a9 100644 --- a/src/BizHawk.Client.EmuHawk/tools/MultiDiskBundler/MultiDiskBundler.cs +++ b/src/BizHawk.Client.EmuHawk/tools/MultiDiskBundler/MultiDiskBundler.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Drawing; using System.IO; @@ -64,10 +64,10 @@ public override void Restart() { if (MainForm.CurrentlyOpenRom.Contains("|")) { - var pieces = MainForm.CurrentlyOpenRom.Split('|'); + string[] pieces = MainForm.CurrentlyOpenRom.Split('|'); - var directory = Path.GetDirectoryName(pieces[0]) ?? ""; - var filename = Path.ChangeExtension(pieces[1], ".xml"); + string directory = Path.GetDirectoryName(pieces[0]) ?? ""; + string filename = Path.ChangeExtension(pieces[1], ".xml"); NameBox.Text = Path.Combine(directory, filename); } @@ -106,7 +106,7 @@ private bool DoSave(out FileInfo fileInfo) fileInfo = new FileInfo(NameBox.Text); if (fileInfo.Exists) { - var result = this.ModalMessageBox2("File already exists, overwrite?", "File exists", EMsgBoxIcon.Warning, useOKCancel: true); + bool result = this.ModalMessageBox2("File already exists, overwrite?", "File exists", EMsgBoxIcon.Warning, useOKCancel: true); if (!result) { return false; @@ -117,10 +117,7 @@ private bool DoSave(out FileInfo fileInfo) return true; } - private void SaveButton_Click(object sender, EventArgs e) - { - DoSave(out var dummy); - } + private void SaveButton_Click(object sender, EventArgs e) => DoSave(out var dummy); private void SaveRunButton_Click(object sender, EventArgs e) { @@ -131,7 +128,7 @@ private void SaveRunButton_Click(object sender, EventArgs e) DialogResult = DialogResult.OK; Close(); - var lra = new LoadRomArgs { OpenAdvanced = new OpenAdvanced_OpenRom { Path = fileInfo.FullName } }; + LoadRomArgs lra = new() { OpenAdvanced = new OpenAdvanced_OpenRom { Path = fileInfo.FullName } }; _ = MainForm.LoadRom(fileInfo.FullName, lra); } @@ -139,7 +136,7 @@ private void AddButton_Click(object sender, EventArgs e) { int start = 3 + (FileSelectorPanel.Controls.Count * 43); - var groupBox = new GroupBox + GroupBox groupBox = new() { Text = "", Location = UIHelper.Scale(new Point(6, start)), @@ -147,7 +144,7 @@ private void AddButton_Click(object sender, EventArgs e) Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top }; - var mdf = new MultiDiskFileSelector(MainForm, Config.PathEntries, + MultiDiskFileSelector mdf = new(MainForm, Config.PathEntries, () => MainForm.CurrentlyOpenRom, () => SystemDropDown.SelectedItem?.ToString()) { Location = UIHelper.Scale(new Point(7, 12)), @@ -166,7 +163,7 @@ private void btnRemove_Click(object sender, EventArgs e) //ToDo: //Make this better? //We need to have i at 1 and not zero because Controls Count doesn't start at zero (sort of) - var i = 1; + int i = 1; //For Each Control box we have, loop foreach (Control ctrl in FileSelectorPanel.Controls) { @@ -182,10 +179,7 @@ private void btnRemove_Click(object sender, EventArgs e) Recalculate(); } - private void FileSelector_NameChanged(object sender, EventArgs e) - { - Recalculate(); - } + private void FileSelector_NameChanged(object sender, EventArgs e) => Recalculate(); private IEnumerable FileSelectors => FileSelectorPanel.Controls @@ -196,11 +190,11 @@ private bool Recalculate() { try { - var names = FileSelectors.Select(f => f.Path).ToList(); + List names = FileSelectors.Select(f => f.Path).ToList(); if (names.Count != 0) { - var name = NameBox.Text; + string name = NameBox.Text; if (string.IsNullOrWhiteSpace(name)) { @@ -209,17 +203,17 @@ private bool Recalculate() if (names.Exists(string.IsNullOrWhiteSpace)) throw new Exception("Rom Names can not be blank"); - var system = SystemDropDown.SelectedItem?.ToString(); + string system = SystemDropDown.SelectedItem?.ToString(); if (string.IsNullOrWhiteSpace(system)) { throw new Exception("System Id can not be blank"); } - var basePath = Path.GetDirectoryName(name.SubstringBefore('|')); + string basePath = Path.GetDirectoryName(name.SubstringBefore('|')); if (string.IsNullOrEmpty(basePath)) { - var fileInfo = new FileInfo(name); + FileInfo fileInfo = new(name); basePath = Path.GetDirectoryName(fileInfo.FullName); } @@ -250,10 +244,7 @@ private bool Recalculate() return false; } - private void NameBox_TextChanged(object sender, EventArgs e) - { - Recalculate(); - } + private void NameBox_TextChanged(object sender, EventArgs e) => Recalculate(); private void BrowseBtn_Click(object sender, EventArgs e) { @@ -273,16 +264,13 @@ private void BrowseBtn_Click(object sender, EventArgs e) initialDirectory = Path.GetDirectoryName(filename) ?? string.Empty; } - var result = this.ShowFileSaveDialog( + string result = this.ShowFileSaveDialog( filter: BundlesFSFilterSet, initDir: initialDirectory, initFileName: filename); if (result is not null) NameBox.Text = result; } - private void SystemDropDown_SelectedIndexChanged(object sender, EventArgs e) - { - Recalculate(); - } + private void SystemDropDown_SelectedIndexChanged(object sender, EventArgs e) => Recalculate(); } } diff --git a/src/BizHawk.Client.EmuHawk/tools/MultiDiskBundler/MultiDiskFileSelector.cs b/src/BizHawk.Client.EmuHawk/tools/MultiDiskBundler/MultiDiskFileSelector.cs index 8a1eff5755b..d43446aa6b9 100644 --- a/src/BizHawk.Client.EmuHawk/tools/MultiDiskBundler/MultiDiskFileSelector.cs +++ b/src/BizHawk.Client.EmuHawk/tools/MultiDiskBundler/MultiDiskFileSelector.cs @@ -27,10 +27,7 @@ public string Path public event EventHandler NameChanged; - private void HandleLabelTextChanged(object sender, EventArgs e) - { - OnNameChanged(EventArgs.Empty); - } + private void HandleLabelTextChanged(object sender, EventArgs e) => OnNameChanged(EventArgs.Empty); public MultiDiskFileSelector(IDialogController dialogController, PathEntryCollection pathEntries, Func getLoadedRomNameCallback, Func getSystemNameCallback) @@ -43,10 +40,7 @@ public MultiDiskFileSelector(IDialogController dialogController, PathEntryCollec PathBox.TextChanged += HandleLabelTextChanged; } - protected virtual void OnNameChanged(EventArgs e) - { - NameChanged?.Invoke(this, e); - } + protected virtual void OnNameChanged(EventArgs e) => NameChanged?.Invoke(this, e); private void PathBox_DragEnter(object sender, DragEventArgs e) { @@ -65,7 +59,7 @@ private void PathBox_DragDrop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { - var ff = (string[])e.Data.GetData(DataFormats.FileDrop); + string[] ff = (string[])e.Data.GetData(DataFormats.FileDrop); if (ff.Length == 1) { PathBox.Text = ff[0]; @@ -75,8 +69,8 @@ private void PathBox_DragDrop(object sender, DragEventArgs e) private void BrowseButton_Click(object sender, EventArgs e) { - var systemName = _getSystemNameCallback(); - var hawkPath = this.ShowFileOpenDialog( + string systemName = _getSystemNameCallback(); + string hawkPath = this.ShowFileOpenDialog( discardCWDChange: true, filter: RomLoader.RomFilter, initDir: _pathEntries.UseRecentForRoms ? string.Empty : _pathEntries.RomAbsolutePath(systemName)); @@ -84,7 +78,7 @@ private void BrowseButton_Click(object sender, EventArgs e) try { FileInfo file = new(hawkPath); - var path = EmuHawkUtil.ResolveShortcut(file.FullName); + string path = EmuHawkUtil.ResolveShortcut(file.FullName); using HawkFile hf = new(path, allowArchives: !MAMEMachineDB.IsMAMEMachine(hawkPath)); if (!hf.IsArchive) @@ -116,27 +110,18 @@ private void BrowseButton_Click(object sender, EventArgs e) } } - private void UseCurrentRomButton_Click(object sender, EventArgs e) - { - PathBox.Text = _getLoadedRomNameCallback(); - } + private void UseCurrentRomButton_Click(object sender, EventArgs e) => PathBox.Text = _getLoadedRomNameCallback(); - private void DualGBFileSelector_Load(object sender, EventArgs e) - { - UpdateValues(); - } + private void DualGBFileSelector_Load(object sender, EventArgs e) => UpdateValues(); public void UpdateValues() { - var loadedRomName = _getLoadedRomNameCallback(); + string loadedRomName = _getLoadedRomNameCallback(); UseCurrentRomButton.Enabled = !string.IsNullOrEmpty(loadedRomName) && !loadedRomName.Contains(".xml"); // Can't already be an xml } - private void PathBox_TextChanged(object sender, EventArgs e) - { - OnNameChanged(e); - } + private void PathBox_TextChanged(object sender, EventArgs e) => OnNameChanged(e); } } diff --git a/src/BizHawk.Client.EmuHawk/tools/NES/BarcodeEntry.cs b/src/BizHawk.Client.EmuHawk/tools/NES/BarcodeEntry.cs index e58ede885ac..150ea57e529 100644 --- a/src/BizHawk.Client.EmuHawk/tools/NES/BarcodeEntry.cs +++ b/src/BizHawk.Client.EmuHawk/tools/NES/BarcodeEntry.cs @@ -21,14 +21,11 @@ public BarcodeEntry() Icon = ToolIcon; } - public override void Restart() - { - textBox1_TextChanged(null, null); - } + public override void Restart() => textBox1_TextChanged(null, null); private void textBox1_TextChanged(object sender, EventArgs e) { - if (!DatachBarcode.ValidString(textBox1.Text, out var why)) + if (!DatachBarcode.ValidString(textBox1.Text, out string why)) { label3.Text = $"Invalid: {why}"; label3.Visible = true; @@ -41,9 +38,6 @@ private void textBox1_TextChanged(object sender, EventArgs e) } } - private void button1_Click(object sender, EventArgs e) - { - Reader.Transfer(textBox1.Text); - } + private void button1_Click(object sender, EventArgs e) => Reader.Transfer(textBox1.Text); } } diff --git a/src/BizHawk.Client.EmuHawk/tools/NES/NESMusicRipper.cs b/src/BizHawk.Client.EmuHawk/tools/NES/NESMusicRipper.cs index c3e84c8d4e7..b0e9e63f326 100644 --- a/src/BizHawk.Client.EmuHawk/tools/NES/NESMusicRipper.cs +++ b/src/BizHawk.Client.EmuHawk/tools/NES/NESMusicRipper.cs @@ -106,7 +106,7 @@ private class ApuState private void Export_Click(object sender, EventArgs e) { //acquire target - var outPath = this.ShowFileSaveDialog( + string outPath = this.ShowFileSaveDialog( filter: RenoiseFilesFSFilterSet, initDir: Config!.PathEntries.ToolsAbsolutePath()); if (outPath is null) return; @@ -118,7 +118,7 @@ private void Export_Click(object sender, EventArgs e) // load template XElement templateRoot; - using (var zfTemplate = new ZipArchive(new FileStream(templatePath, FileMode.Open, FileAccess.Read), ZipArchiveMode.Read)) + using (ZipArchive zfTemplate = new(new FileStream(templatePath, FileMode.Open, FileAccess.Read), ZipArchiveMode.Read)) { var entry = zfTemplate.Entries.Single(entry => entry.FullName == "Song.xml"); using var stream = entry.Open(); @@ -130,7 +130,7 @@ private void Export_Click(object sender, EventArgs e) var xPatternPool = xPatterns.Parent; xPatterns.Remove(); - var writer = new StringWriter(); + StringWriter writer = new(); writer.WriteLine(""); @@ -258,7 +258,7 @@ private void Export_Click(object sender, EventArgs e) var rec = _log[index]; - TriangleState tri = rec.Triangle; + var tri = rec.Triangle; { bool keyOff = false, keyOn = false; @@ -314,7 +314,7 @@ private void Export_Click(object sender, EventArgs e) var rec = _log[index]; - NoiseState noise = rec.Noise; + var noise = rec.Noise; // transform quieted notes to dead notes // blech its buggy, im tired @@ -388,7 +388,7 @@ private void Export_Click(object sender, EventArgs e) writer.WriteLine(""); writer.Flush(); - var xNewPatternList = XElement.Parse(writer.ToString()); + XElement xNewPatternList = XElement.Parse(writer.ToString()); xPatternPool.Add(xNewPatternList); //write pattern sequence @@ -411,14 +411,14 @@ private void Export_Click(object sender, EventArgs e) File.Delete(outPath); File.Copy(templatePath, outPath); - using var zfOutput = new ZipArchive(new FileStream(outPath, FileMode.Create, FileAccess.Write), ZipArchiveMode.Create); + using ZipArchive zfOutput = new(new FileStream(outPath, FileMode.Create, FileAccess.Write), ZipArchiveMode.Create); using (var stream = zfOutput.CreateEntry("Song.xml").Open()) { templateRoot.Save(stream); } } - private readonly List _log = new List(); + private readonly List _log = new(); private void DebugCallback() { @@ -446,7 +446,7 @@ private void DebugCallback() int noiseNote = FindNearestNote(noiseFreq); // create the record - var rec = new ApuState + ApuState rec = new() { Pulse0 = { @@ -479,10 +479,7 @@ private void DebugCallback() SyncContents(); } - private void SyncContents() - { - lblContents.Text = $"{_log.Count} Rows"; - } + private void SyncContents() => lblContents.Text = $"{_log.Count} Rows"; private void BtnControl_Click(object sender, EventArgs e) { diff --git a/src/BizHawk.Client.EmuHawk/tools/NES/NESNameTableViewer.cs b/src/BizHawk.Client.EmuHawk/tools/NES/NESNameTableViewer.cs index 10077e0ec66..7f9961a5ec2 100644 --- a/src/BizHawk.Client.EmuHawk/tools/NES/NESNameTableViewer.cs +++ b/src/BizHawk.Client.EmuHawk/tools/NES/NESNameTableViewer.cs @@ -46,20 +46,11 @@ public NESNameTableViewer() Icon = ToolIcon; } - private void NESNameTableViewer_Load(object sender, EventArgs e) - { - Generate(true); - } + private void NESNameTableViewer_Load(object sender, EventArgs e) => Generate(true); - public override void Restart() - { - Generate(true); - } + public override void Restart() => Generate(true); - protected override void UpdateBefore() - { - _ppu.InstallCallback1(() => Generate(), _scanline); - } + protected override void UpdateBefore() => _ppu.InstallCallback1(() => Generate(), _scanline); protected override void GeneralUpdate() => UpdateBefore(); @@ -173,13 +164,13 @@ private unsafe void Generate(bool now = false) ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); - var dPtr = (int*)bmpData.Scan0.ToPointer(); - var pitch = bmpData.Stride / 4; + int* dPtr = (int*)bmpData.Scan0.ToPointer(); + int pitch = bmpData.Stride / 4; // Buffer all the data from the ppu, because it will be read multiple times and that is slow - var ppuBuffer = _ppu.GetPPUBus(); + byte[] ppuBuffer = _ppu.GetPPUBus(); - var palRam = _ppu.GetPalRam(); + byte[] palRam = _ppu.GetPalRam(); if (_ppu.ExActive) { @@ -202,10 +193,7 @@ private void ScreenshotMenuItem_Click(object sender, EventArgs e) .SaveAsFile(Game, "Nametables", VSystemID.Raw.NES, Config.PathEntries, this); } - private void ScreenshotToClipboardMenuItem_Click(object sender, EventArgs e) - { - NameTableView.ToBitMap().ToClipBoard(); - } + private void ScreenshotToClipboardMenuItem_Click(object sender, EventArgs e) => NameTableView.ToBitMap().ToClipBoard(); private void RefreshImageContextMenuItem_Click(object sender, EventArgs e) { diff --git a/src/BizHawk.Client.EmuHawk/tools/NES/NESPPU.cs b/src/BizHawk.Client.EmuHawk/tools/NES/NESPPU.cs index 871e025ed32..45b62d6fcfc 100644 --- a/src/BizHawk.Client.EmuHawk/tools/NES/NESPPU.cs +++ b/src/BizHawk.Client.EmuHawk/tools/NES/NESPPU.cs @@ -25,7 +25,7 @@ public static Icon ToolIcon private int _scanline; - private Bitmap _zoomBoxDefaultImage = new Bitmap(64, 64); + private Bitmap _zoomBoxDefaultImage = new(64, 64); private bool _forceChange; [RequiredService] @@ -71,10 +71,7 @@ private void NesPPU_Load(object sender, EventArgs e) ChrRomViewReload(); } - protected override void UpdateBefore() - { - _ppu.InstallCallback2(() => Generate(), _scanline); - } + protected override void UpdateBefore() => _ppu.InstallCallback2(() => Generate(), _scanline); public override void Restart() { @@ -82,10 +79,7 @@ public override void Restart() ChrRomViewReload(); } - private byte GetBit(byte[] ppuBus, int address, int bit) - { - return (byte)((ppuBus[address] >> (7 - bit)) & 1); - } + private byte GetBit(byte[] ppuBus, int address, int bit) => (byte)((ppuBus[address] >> (7 - bit)) & 1); private bool CheckChange(byte[] palRam, byte[] ppuBus) { @@ -191,7 +185,7 @@ private unsafe void Generate(bool now = false) _forceChange = false; // Pattern Viewer - for (var i = 0; i < 16; i++) + for (int i = 0; i < 16; i++) { PaletteView.BgPalettesPrev[i].Value = PaletteView.BgPalettes[i].Value; PaletteView.SpritePalettesPrev[i].Value = PaletteView.SpritePalettes[i].Value; @@ -208,7 +202,7 @@ private unsafe void Generate(bool now = false) } var bmpData2 = SpriteView.Sprites.LockBits(new Rectangle(new Point(0, 0), SpriteView.Sprites.Size), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); - var frameBuf2 = (int*)bmpData2.Scan0.ToPointer(); + int* frameBuf2 = (int*)bmpData2.Scan0.ToPointer(); int ptAdd = _ppu.SPBaseHigh ? 0x1000 : 0; bool is8x16 = _ppu.SPTall; @@ -301,8 +295,8 @@ private void UpdatePaletteSelection() private static Bitmap Section(Image srcBitmap, Rectangle section, bool is8x16) { // Create the new bitmap and associated graphics object - var bmp = new Bitmap(64, 64); - var g = Graphics.FromImage(bmp); + Bitmap bmp = new(64, 64); + Graphics g = Graphics.FromImage(bmp); // Draw the specified section of the source bitmap to the new one g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor; @@ -323,40 +317,19 @@ private void HandleDefaultImage() } } - private void Screenshot(Bitmap b, string suffix) - { - b.SaveAsFile(Game, suffix, VSystemID.Raw.NES, Config.PathEntries, this); - } + private void Screenshot(Bitmap b, string suffix) => b.SaveAsFile(Game, suffix, VSystemID.Raw.NES, Config.PathEntries, this); - private void SavePaletteScreenshotMenuItem_Click(object sender, EventArgs e) - { - Screenshot(PaletteView.ToBitMap(), "Palettes"); - } + private void SavePaletteScreenshotMenuItem_Click(object sender, EventArgs e) => Screenshot(PaletteView.ToBitMap(), "Palettes"); - private void SavePatternScreenshotMenuItem_Click(object sender, EventArgs e) - { - Screenshot(PatternView.ToBitMap(), "Patterns"); - } + private void SavePatternScreenshotMenuItem_Click(object sender, EventArgs e) => Screenshot(PatternView.ToBitMap(), "Patterns"); - private void SaveSpriteScreenshotMenuItem_Click(object sender, EventArgs e) - { - Screenshot(SpriteView.ToBitMap(), "Sprites"); - } + private void SaveSpriteScreenshotMenuItem_Click(object sender, EventArgs e) => Screenshot(SpriteView.ToBitMap(), "Sprites"); - private void CopyPaletteToClipboardMenuItem_Click(object sender, EventArgs e) - { - PaletteView.ToBitMap().ToClipBoard(); - } + private void CopyPaletteToClipboardMenuItem_Click(object sender, EventArgs e) => PaletteView.ToBitMap().ToClipBoard(); - private void CopyPatternToClipboardMenuItem_Click(object sender, EventArgs e) - { - PatternView.ToBitMap().ToClipBoard(); - } + private void CopyPatternToClipboardMenuItem_Click(object sender, EventArgs e) => PatternView.ToBitMap().ToClipBoard(); - private void CopySpriteToClipboardMenuItem_Click(object sender, EventArgs e) - { - SpriteView.ToBitMap().ToClipBoard(); - } + private void CopySpriteToClipboardMenuItem_Click(object sender, EventArgs e) => SpriteView.ToBitMap().ToClipBoard(); private void Table0PaletteSubMenu_DropDownOpened(object sender, EventArgs e) { @@ -452,30 +425,15 @@ private void Palette_Click(object sender, EventArgs e) UpdatePaletteSelection(); } - private void SettingsSubMenu_DropDownOpened(object sender, EventArgs e) - { - cHRROMTileViewerToolStripMenuItem.Checked = ChrRomView; - } + private void SettingsSubMenu_DropDownOpened(object sender, EventArgs e) => cHRROMTileViewerToolStripMenuItem.Checked = ChrRomView; - private void PaletteRefreshMenuItem_Click(object sender, EventArgs e) - { - PaletteView.Refresh(); - } + private void PaletteRefreshMenuItem_Click(object sender, EventArgs e) => PaletteView.Refresh(); - private void PatternRefreshMenuItem_Click(object sender, EventArgs e) - { - PatternView.Refresh(); - } + private void PatternRefreshMenuItem_Click(object sender, EventArgs e) => PatternView.Refresh(); - private void SpriteRefreshMenuItem_Click(object sender, EventArgs e) - { - SpriteView.Refresh(); - } + private void SpriteRefreshMenuItem_Click(object sender, EventArgs e) => SpriteView.Refresh(); - private void NesPPU_MouseClick(object sender, MouseEventArgs e) - { - ZoomBox.Image = new Bitmap(64, 64); - } + private void NesPPU_MouseClick(object sender, MouseEventArgs e) => ZoomBox.Image = new Bitmap(64, 64); private void NesPPU_KeyDown(object sender, KeyEventArgs e) { @@ -522,30 +480,15 @@ private void MessageTimer_Tick(object sender, EventArgs e) toolStripStatusLabel1.Text = "Use CTRL+C to copy the pane under the mouse to the clipboard."; } - private void PaletteView_MouseClick(object sender, MouseEventArgs e) - { - HandleDefaultImage(); - } + private void PaletteView_MouseClick(object sender, MouseEventArgs e) => HandleDefaultImage(); - private void SpriteView_MouseClick(object sender, MouseEventArgs e) - { - HandleDefaultImage(); - } + private void SpriteView_MouseClick(object sender, MouseEventArgs e) => HandleDefaultImage(); - private void SpriteView_MouseEnter(object sender, EventArgs e) - { - DetailsBox.Text = "Details - Sprites"; - } + private void SpriteView_MouseEnter(object sender, EventArgs e) => DetailsBox.Text = "Details - Sprites"; - private void SpriteView_MouseLeave(object sender, EventArgs e) - { - ClearDetails(); - } - - private void SpriteView_MouseMove(object sender, MouseEventArgs e) - { - HandleSpriteViewMouseMove(e.Location); - } + private void SpriteView_MouseLeave(object sender, EventArgs e) => ClearDetails(); + + private void SpriteView_MouseMove(object sender, MouseEventArgs e) => HandleSpriteViewMouseMove(e.Location); private void HandleSpriteViewMouseMove(Point e) { @@ -584,21 +527,21 @@ private void HandleSpriteViewMouseMove(Point e) spriteSlotY /= 3; //if these were utterly senseless slots (so far out of range) then bail - if (spriteSlotX < 0 || spriteSlotX >= 16) + if (spriteSlotX is < 0 or >= 16) return; - if (spriteSlotY < 0 || spriteSlotY >= 4) + if (spriteSlotY is < 0 or >= 4) return; //find the final sprite number that's being hovered - var spriteNumber = spriteSlotY * 16 + spriteSlotX; + int spriteNumber = spriteSlotY * 16 + spriteSlotX; int x = oam[(spriteNumber * 4) + 3]; int y = oam[spriteNumber * 4]; - var color = oam[(spriteNumber * 4) + 2] & 0x03; - var attributes = oam[(spriteNumber * 4) + 2]; + int color = oam[(spriteNumber * 4) + 2] & 0x03; + byte attributes = oam[(spriteNumber * 4) + 2]; - var flags = "Flags: "; + string flags = "Flags: "; int h = GetBit(ppuBus, attributes, 6); int v = GetBit(ppuBus, attributes, 7); int priority = GetBit(ppuBus, attributes, 5); @@ -648,20 +591,11 @@ private void HandleSpriteViewMouseMove(Point e) } } - private void PaletteView_MouseLeave(object sender, EventArgs e) - { - ClearDetails(); - } + private void PaletteView_MouseLeave(object sender, EventArgs e) => ClearDetails(); - private void PaletteView_MouseEnter(object sender, EventArgs e) - { - DetailsBox.Text = "Details - Palettes"; - } + private void PaletteView_MouseEnter(object sender, EventArgs e) => DetailsBox.Text = "Details - Palettes"; - private void PaletteView_MouseMove(object sender, MouseEventArgs e) - { - HandlePaletteViewMouseMove(e.Location); - } + private void PaletteView_MouseMove(object sender, MouseEventArgs e) => HandlePaletteViewMouseMove(e.Location); private void HandlePaletteViewMouseMove(Point e) { @@ -681,8 +615,8 @@ private void HandlePaletteViewMouseMove(Point e) AddressLabel.Text = $"Address: 0x{addr:X4}"; int val; - var bmp = new Bitmap(64, 64); - var g = Graphics.FromImage(bmp); + Bitmap bmp = new(64, 64); + Graphics g = Graphics.FromImage(bmp); byte[] palRam = _ppu.GetPalRam(); @@ -733,15 +667,9 @@ private void PatternView_Click(object sender, MouseEventArgs e) HandleDefaultImage(); } - private void PatternView_MouseEnter(object sender, EventArgs e) - { - DetailsBox.Text = "Details - Patterns"; - } + private void PatternView_MouseEnter(object sender, EventArgs e) => DetailsBox.Text = "Details - Patterns"; - private void PatternView_MouseLeave(object sender, EventArgs e) - { - ClearDetails(); - } + private void PatternView_MouseLeave(object sender, EventArgs e) => ClearDetails(); private void PatternView_MouseMove(object sender, MouseEventArgs e) { @@ -766,7 +694,7 @@ private void PatternView_MouseMove(object sender, MouseEventArgs e) address += (e.Y / 8) * 256; tile += (e.Y / 8) * 16; - var usage = "Usage: "; + string usage = "Usage: "; if (_ppu.BGBaseHigh == address >= 0x1000) // bghigh { @@ -804,15 +732,9 @@ private void NesPPU_FormClosed(object sender, FormClosedEventArgs e) private MemoryDomain _chrRom; private readonly byte[] _chrRomCache = new byte[8192]; - private void ChrROMTileViewerToolStripMenuItem_Click(object sender, EventArgs e) - { - ChrRomView ^= true; - } + private void ChrROMTileViewerToolStripMenuItem_Click(object sender, EventArgs e) => ChrRomView ^= true; - private void CalculateFormSize() - { - Width = ChrRomView ? 861 : 580; - } + private void CalculateFormSize() => Width = ChrRomView ? 861 : 580; private void ChrRomViewReload() { @@ -844,9 +766,6 @@ private void ChrRomViewRefresh() } } - private void NumericUpDownChrRomBank_ValueChanged(object sender, EventArgs e) - { - ChrRomViewRefresh(); - } + private void NumericUpDownChrRomBank_ValueChanged(object sender, EventArgs e) => ChrRomViewRefresh(); } } diff --git a/src/BizHawk.Client.EmuHawk/tools/NES/NameTableViewer.cs b/src/BizHawk.Client.EmuHawk/tools/NES/NameTableViewer.cs index f94d73bba37..a09da46b3fe 100644 --- a/src/BizHawk.Client.EmuHawk/tools/NES/NameTableViewer.cs +++ b/src/BizHawk.Client.EmuHawk/tools/NES/NameTableViewer.cs @@ -9,7 +9,7 @@ public sealed class NameTableViewer : Control public NameTableViewer() { - var pSize = new Size(512, 480); + Size pSize = new(512, 480); Nametables = new Bitmap(pSize.Width, pSize.Height); SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.UserPaint, true); @@ -64,8 +64,8 @@ private void NameTableViewer_Paint(object sender, PaintEventArgs e) public void ScreenshotToClipboard() { - using var b = new Bitmap(Width, Height); - var rect = new Rectangle(new Point(0, 0), Size); + using Bitmap b = new(Width, Height); + Rectangle rect = new(new Point(0, 0), Size); DrawToBitmap(b, rect); Clipboard.SetImage(b); } diff --git a/src/BizHawk.Client.EmuHawk/tools/NES/PaletteViewer.cs b/src/BizHawk.Client.EmuHawk/tools/NES/PaletteViewer.cs index e7a2408ede9..002b180d3aa 100644 --- a/src/BizHawk.Client.EmuHawk/tools/NES/PaletteViewer.cs +++ b/src/BizHawk.Client.EmuHawk/tools/NES/PaletteViewer.cs @@ -5,8 +5,8 @@ namespace BizHawk.Client.EmuHawk { public sealed class PaletteViewer : Control { - private readonly SolidBrush BgPalettesBrush = new SolidBrush(Color.Black); - private readonly SolidBrush SpritePalettesBrush = new SolidBrush(Color.Black); + private readonly SolidBrush BgPalettesBrush = new(Color.Black); + private readonly SolidBrush SpritePalettesBrush = new(Color.Black); public class Palette { @@ -73,8 +73,8 @@ public bool HasChanged() public void ScreenshotToClipboard() { - var b = new Bitmap(Width, Height); - var rect = new Rectangle(new Point(0, 0), Size); + Bitmap b = new(Width, Height); + Rectangle rect = new(new Point(0, 0), Size); DrawToBitmap(b, rect); using var img = b; diff --git a/src/BizHawk.Client.EmuHawk/tools/NES/PatternViewer.cs b/src/BizHawk.Client.EmuHawk/tools/NES/PatternViewer.cs index 78b6645c73b..9d294ddf278 100644 --- a/src/BizHawk.Client.EmuHawk/tools/NES/PatternViewer.cs +++ b/src/BizHawk.Client.EmuHawk/tools/NES/PatternViewer.cs @@ -11,7 +11,7 @@ public sealed class PatternViewer : Control public PatternViewer() { - var pSize = new Size(256, 128); + Size pSize = new(256, 128); Pattern = new Bitmap(pSize.Width, pSize.Height); SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.UserPaint, true); @@ -32,8 +32,8 @@ private void PatternViewer_Paint(object sender, PaintEventArgs e) public void ScreenshotToClipboard() { - var b = new Bitmap(Width, Height); - var rect = new Rectangle(new Point(0, 0), Size); + Bitmap b = new(Width, Height); + Rectangle rect = new(new Point(0, 0), Size); DrawToBitmap(b, rect); using var img = b; diff --git a/src/BizHawk.Client.EmuHawk/tools/NES/SpriteViewer.cs b/src/BizHawk.Client.EmuHawk/tools/NES/SpriteViewer.cs index f61c65e0226..59b3247388b 100644 --- a/src/BizHawk.Client.EmuHawk/tools/NES/SpriteViewer.cs +++ b/src/BizHawk.Client.EmuHawk/tools/NES/SpriteViewer.cs @@ -10,7 +10,7 @@ public sealed class SpriteViewer : Control public SpriteViewer() { SetStyle(ControlStyles.SupportsTransparentBackColor, true); - var pSize = new Size(256, 96); + Size pSize = new(256, 96); Sprites = new Bitmap(pSize.Width, pSize.Height); SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.UserPaint, true); @@ -27,15 +27,12 @@ private void Display(Graphics g) g.DrawImageUnscaled(Sprites, 1, 1); } - private void SpriteViewer_Paint(object sender, PaintEventArgs e) - { - Display(e.Graphics); - } + private void SpriteViewer_Paint(object sender, PaintEventArgs e) => Display(e.Graphics); public void ScreenshotToClipboard() { - var b = new Bitmap(Width, Height); - var rect = new Rectangle(new Point(0, 0), Size); + Bitmap b = new(Width, Height); + Rectangle rect = new(new Point(0, 0), Size); DrawToBitmap(b, rect); using var img = b; diff --git a/src/BizHawk.Client.EmuHawk/tools/PCE/PCEBGCanvas.cs b/src/BizHawk.Client.EmuHawk/tools/PCE/PCEBGCanvas.cs index 9481b1c302d..4b2e7d33743 100644 --- a/src/BizHawk.Client.EmuHawk/tools/PCE/PCEBGCanvas.cs +++ b/src/BizHawk.Client.EmuHawk/tools/PCE/PCEBGCanvas.cs @@ -21,9 +21,6 @@ public PceBgCanvas() Paint += BGViewer_Paint; } - private void BGViewer_Paint(object sender, PaintEventArgs e) - { - e.Graphics.DrawImageUnscaled(Bat, 0, 0); - } + private void BGViewer_Paint(object sender, PaintEventArgs e) => e.Graphics.DrawImageUnscaled(Bat, 0, 0); } } diff --git a/src/BizHawk.Client.EmuHawk/tools/PCE/PCEBGViewer.cs b/src/BizHawk.Client.EmuHawk/tools/PCE/PCEBGViewer.cs index e0e2ba993f2..49fb13ff542 100644 --- a/src/BizHawk.Client.EmuHawk/tools/PCE/PCEBGViewer.cs +++ b/src/BizHawk.Client.EmuHawk/tools/PCE/PCEBGViewer.cs @@ -48,14 +48,14 @@ public unsafe void Generate() Viewer.GetGpuData(_vdcType, view => { - var width = 8 * view.BatWidth; - var height = 8 * view.BatHeight; + int width = 8 * view.BatWidth; + int height = 8 * view.BatHeight; var buf = canvas.Bat.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, canvas.Bat.PixelFormat); - var pitch = buf.Stride / 4; - var begin = (int*)buf.Scan0.ToPointer(); - var vram = view.Vram; - var patternBuffer = view.BackgroundCache; - var palette = view.PaletteCache; + int pitch = buf.Stride / 4; + int* begin = (int*)buf.Scan0.ToPointer(); + ushort* vram = view.Vram; + byte* patternBuffer = view.BackgroundCache; + int* palette = view.PaletteCache; int* p = begin; for (int y = 0; y < height; ++y) @@ -99,26 +99,17 @@ private void FileSubMenu_DropDownOpened(object sender, EventArgs e) VDC2MenuItem.Checked = _vdcType == 1; } - private void VDC1MenuItem_Click(object sender, EventArgs e) - { - _vdcType = 0; - } + private void VDC1MenuItem_Click(object sender, EventArgs e) => _vdcType = 0; - private void VDC2MenuItem_Click(object sender, EventArgs e) - { - _vdcType = 1; - } + private void VDC2MenuItem_Click(object sender, EventArgs e) => _vdcType = 1; - private void ExitMenuItem_Click(object sender, EventArgs e) - { - Close(); - } + private void ExitMenuItem_Click(object sender, EventArgs e) => Close(); private unsafe void Canvas_MouseMove(object sender, MouseEventArgs e) { Viewer.GetGpuData(_vdcType, view => { - var vram = view.Vram; + ushort* vram = view.Vram; int xTile = e.X / 8; int yTile = e.Y / 8; int tileNo = vram[(ushort)((yTile * view.BatWidth) + xTile)] & 0x07FF; diff --git a/src/BizHawk.Client.EmuHawk/tools/PCE/PCESoundDebugger.cs b/src/BizHawk.Client.EmuHawk/tools/PCE/PCESoundDebugger.cs index b880c6aa5e0..203d3da7df4 100644 --- a/src/BizHawk.Client.EmuHawk/tools/PCE/PCESoundDebugger.cs +++ b/src/BizHawk.Client.EmuHawk/tools/PCE/PCESoundDebugger.cs @@ -99,15 +99,15 @@ protected override void UpdateAfter() short[] waveform = (short[])ch.Wave.Clone(); // hash it - var ms = new MemoryStream(_waveformTemp); - var bw = new BinaryWriter(ms); - foreach (var s in waveform) + MemoryStream ms = new(_waveformTemp); + BinaryWriter bw = new(ms); + foreach (short s in waveform) { bw.Write(s); } bw.Flush(); - var md5 = MD5Checksum.ComputeDigestHex(_waveformTemp); + string md5 = MD5Checksum.ComputeDigestHex(_waveformTemp); if (!_psgEntryTable.TryGetValue(md5, out var entry)) { @@ -164,8 +164,8 @@ private class PsgEntry } private readonly PsgEntry[] _lastSamples = new PsgEntry[8]; - private readonly List _psgEntries = new List(); - private readonly Dictionary _psgEntryTable = new Dictionary(); + private readonly List _psgEntries = new(); + private readonly Dictionary _psgEntryTable = new(); // 32*16 samples, 16bit, mono, 8khz (but we'll change the sample rate) private static readonly byte[] EmptyWav = { @@ -178,14 +178,14 @@ private class PsgEntry private void BtnExport_Click(object sender, EventArgs e) { string tmpFilename = $"{Path.GetTempFileName()}.zip"; - using (var stream = new FileStream(tmpFilename, FileMode.Create, FileAccess.Write, FileShare.Read)) + using (FileStream stream = new(tmpFilename, FileMode.Create, FileAccess.Write, FileShare.Read)) { - using var zip = new ZipArchive(stream, ZipArchiveMode.Create); + using ZipArchive zip = new(stream, ZipArchiveMode.Create); foreach (var entry in _psgEntries) { - var ms = new MemoryStream(); - var bw = new BinaryWriter(ms); + MemoryStream ms = new(); + BinaryWriter bw = new(ms); bw.Write(EmptyWav, 0, EmptyWav.Length); ms.Position = 0x18; // samplerate and avgbytespersecond bw.Write(20000); @@ -201,7 +201,7 @@ private void BtnExport_Click(object sender, EventArgs e) } bw.Flush(); - var buf = ms.GetBuffer(); + byte[] buf = ms.GetBuffer(); var ze = zip.CreateEntry($"{entry.Name}.wav", CompressionLevel.Fastest); using var zipstream = ze.Open(); @@ -224,7 +224,7 @@ private void SyncLists() lvPsgWaveforms.Items.Clear(); foreach (var entry in _psgEntries) { - var lvi = new ListViewItem(entry.Name); + ListViewItem lvi = new(entry.Name); lvi.SubItems.Add(entry.HitCount.ToString()); lvPsgWaveforms.Items.Add(lvi); } diff --git a/src/BizHawk.Client.EmuHawk/tools/PCE/PCETileViewer.cs b/src/BizHawk.Client.EmuHawk/tools/PCE/PCETileViewer.cs index ef69543b23f..3384f0a232e 100644 --- a/src/BizHawk.Client.EmuHawk/tools/PCE/PCETileViewer.cs +++ b/src/BizHawk.Client.EmuHawk/tools/PCE/PCETileViewer.cs @@ -163,10 +163,7 @@ public override void Restart() CheckBoxVDC2_CheckedChanged(null, null); } - private void CheckBoxVDC2_CheckedChanged(object sender, EventArgs e) - { - GeneralUpdate(); - } + private void CheckBoxVDC2_CheckedChanged(object sender, EventArgs e) => GeneralUpdate(); private void BmpViewBGPal_MouseClick(object sender, MouseEventArgs e) { @@ -189,7 +186,7 @@ private void PceTileViewer_KeyDown(object sender, KeyEventArgs e) if (ModifierKeys.HasFlag(Keys.Control) && e.KeyCode == Keys.C) { // find the control under the mouse - Point m = Cursor.Position; + var m = Cursor.Position; Control top = this; Control found; do @@ -205,19 +202,10 @@ private void PceTileViewer_KeyDown(object sender, KeyEventArgs e) } } - private void SaveAsFile(Bitmap bmp, string suffix) - { - bmp.SaveAsFile(Game, suffix, Emulator.SystemId, Config.PathEntries, this); - } + private void SaveAsFile(Bitmap bmp, string suffix) => bmp.SaveAsFile(Game, suffix, Emulator.SystemId, Config.PathEntries, this); - private void SaveBackgroundScreenshotMenuItem_Click(object sender, EventArgs e) - { - SaveAsFile(bmpViewBG.Bmp, "BG"); - } + private void SaveBackgroundScreenshotMenuItem_Click(object sender, EventArgs e) => SaveAsFile(bmpViewBG.Bmp, "BG"); - private void SaveSpriteScreenshotMenuItem_Click(object sender, EventArgs e) - { - SaveAsFile(bmpViewBG.Bmp, "Sprites"); - } + private void SaveSpriteScreenshotMenuItem_Click(object sender, EventArgs e) => SaveAsFile(bmpViewBG.Bmp, "Sprites"); } } diff --git a/src/BizHawk.Client.EmuHawk/tools/SMS/VDPViewer.cs b/src/BizHawk.Client.EmuHawk/tools/SMS/VDPViewer.cs index c35b2b20c56..ab485a26940 100644 --- a/src/BizHawk.Client.EmuHawk/tools/SMS/VDPViewer.cs +++ b/src/BizHawk.Client.EmuHawk/tools/SMS/VDPViewer.cs @@ -159,10 +159,7 @@ protected override void UpdateBefore() } } - public override void Restart() - { - GeneralUpdate(); - } + public override void Restart() => GeneralUpdate(); private void BmpViewPalette_MouseClick(object sender, MouseEventArgs e) { @@ -182,7 +179,7 @@ private void VDPViewer_KeyDown(object sender, KeyEventArgs e) if (ModifierKeys.HasFlag(Keys.Control) && e.KeyCode == Keys.C) { // find the control under the mouse - Point m = Cursor.Position; + var m = Cursor.Position; Control top = this; Control found; do @@ -198,24 +195,12 @@ private void VDPViewer_KeyDown(object sender, KeyEventArgs e) } } - private void SaveAsFile(Bitmap bmp, string suffix) - { - bmp.SaveAsFile(Game, suffix, Emulator.SystemId, Config.PathEntries, this); - } + private void SaveAsFile(Bitmap bmp, string suffix) => bmp.SaveAsFile(Game, suffix, Emulator.SystemId, Config.PathEntries, this); - private void SaveTilesScreenshotToolStripMenuItem_Click(object sender, EventArgs e) - { - SaveAsFile(bmpViewTiles.Bmp, "Tiles"); - } + private void SaveTilesScreenshotToolStripMenuItem_Click(object sender, EventArgs e) => SaveAsFile(bmpViewTiles.Bmp, "Tiles"); - private void SavePalettesScreenshotMenuItem_Click(object sender, EventArgs e) - { - SaveAsFile(bmpViewPalette.Bmp, "Palette"); - } + private void SavePalettesScreenshotMenuItem_Click(object sender, EventArgs e) => SaveAsFile(bmpViewPalette.Bmp, "Palette"); - private void SaveBgScreenshotMenuItem_Click(object sender, EventArgs e) - { - SaveAsFile(bmpViewBG.Bmp, "BG"); - } + private void SaveBgScreenshotMenuItem_Click(object sender, EventArgs e) => SaveAsFile(bmpViewBG.Bmp, "BG"); } } diff --git a/src/BizHawk.Client.EmuHawk/tools/SNES/SNESGraphicsDebugger.cs b/src/BizHawk.Client.EmuHawk/tools/SNES/SNESGraphicsDebugger.cs index 19f81b86f72..98c622927db 100644 --- a/src/BizHawk.Client.EmuHawk/tools/SNES/SNESGraphicsDebugger.cs +++ b/src/BizHawk.Client.EmuHawk/tools/SNES/SNESGraphicsDebugger.cs @@ -38,7 +38,7 @@ namespace BizHawk.Client.EmuHawk { public unsafe partial class SNESGraphicsDebugger : ToolFormBase, IToolFormAutoConfig { - private readonly List displayTypeItems = new List(); + private readonly List displayTypeItems = new(); [RequiredService] private IBSNESForGfxDebugger Emulator { get; set; } @@ -83,7 +83,7 @@ public SNESGraphicsDebugger() comboDisplayType.DataSource = displayTypeItems; comboDisplayType.SelectedIndex = 2; - var paletteTypeItems = new List + List paletteTypeItems = new() { // must be in same order as enum new PaletteTypeItem("BizHawk", SnesColors.ColorType.BizHawk), @@ -115,10 +115,7 @@ protected override void OnClosed(EventArgs e) gd = null; } - private string FormatBpp(int bpp) - { - return bpp == 0 ? "---" : bpp.ToString(); - } + private string FormatBpp(int bpp) => bpp == 0 ? "---" : bpp.ToString(); private string FormatVramAddress(int address) { @@ -344,13 +341,13 @@ private void RenderView() int* pixelptr = null; int stride = 0; - Action allocate = (w, h) => + void allocate(int w, int h) { bmp = new Bitmap(w, h); bmpdata = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); pixelptr = (int*)bmpdata.Scan0.ToPointer(); stride = bmpdata.Stride; - }; + } var selection = CurrDisplaySelection; if (selection == eDisplayType.OBJ) @@ -379,7 +376,7 @@ private void RenderView() gd.RenderSpriteToScreen(pixelptr, stride / 4, oam.X, oam.Y, si, i, oam, 256, 224, spriteMap); } } - if (selection == eDisplayType.OBJTiles0 || selection == eDisplayType.OBJTiles1) + if (selection is eDisplayType.OBJTiles0 or eDisplayType.OBJTiles1) { allocate(128, 256); int startTile; @@ -485,24 +482,24 @@ private enum eDisplayType BG1Screen = 101, BG2Screen = 102, BG3Screen = 103, BG4Screen = 104 } - private static bool IsDisplayTypeBG(eDisplayType type) { return type == eDisplayType.BG1 || type == eDisplayType.BG2 || type == eDisplayType.BG3 || type == eDisplayType.BG4; } - private static bool IsDisplayTypeOBJ(eDisplayType type) { return type == eDisplayType.OBJTiles0 || type == eDisplayType.OBJTiles1; } + private static bool IsDisplayTypeBG(eDisplayType type) => type is eDisplayType.BG1 or eDisplayType.BG2 or eDisplayType.BG3 or eDisplayType.BG4; + private static bool IsDisplayTypeOBJ(eDisplayType type) => type is eDisplayType.OBJTiles0 or eDisplayType.OBJTiles1; private static int DisplayTypeBGNum(eDisplayType type) { if(IsDisplayTypeBG(type)) return (int)type; else return -1; } private static SNESGraphicsDecoder.BGMode BGModeForDisplayType(eDisplayType type) { - switch (type) + return type switch { - case eDisplayType.Tiles2bpp: return SNESGraphicsDecoder.BGMode.Text; - case eDisplayType.Tiles4bpp: return SNESGraphicsDecoder.BGMode.Text; - case eDisplayType.Tiles8bpp: return SNESGraphicsDecoder.BGMode.Text; - case eDisplayType.TilesMode7: return SNESGraphicsDecoder.BGMode.Mode7; - case eDisplayType.TilesMode7Ext: return SNESGraphicsDecoder.BGMode.Mode7Ext; - case eDisplayType.TilesMode7DC: return SNESGraphicsDecoder.BGMode.Mode7DC; - case eDisplayType.OBJTiles0: return SNESGraphicsDecoder.BGMode.OBJ; - case eDisplayType.OBJTiles1: return SNESGraphicsDecoder.BGMode.OBJ; - default: throw new InvalidOperationException(); - } + eDisplayType.Tiles2bpp => SNESGraphicsDecoder.BGMode.Text, + eDisplayType.Tiles4bpp => SNESGraphicsDecoder.BGMode.Text, + eDisplayType.Tiles8bpp => SNESGraphicsDecoder.BGMode.Text, + eDisplayType.TilesMode7 => SNESGraphicsDecoder.BGMode.Mode7, + eDisplayType.TilesMode7Ext => SNESGraphicsDecoder.BGMode.Mode7Ext, + eDisplayType.TilesMode7DC => SNESGraphicsDecoder.BGMode.Mode7DC, + eDisplayType.OBJTiles0 => SNESGraphicsDecoder.BGMode.OBJ, + eDisplayType.OBJTiles1 => SNESGraphicsDecoder.BGMode.OBJ, + _ => throw new InvalidOperationException(), + }; } private class DisplayTypeItem @@ -592,7 +589,7 @@ private void comboBGProps_SelectedIndexChanged(object sender, EventArgs e) private Rectangle GetPaletteRegion(int start, int num) { - var ret = new Rectangle + Rectangle ret = new() { X = start % 16, Y = start / 16, @@ -620,8 +617,8 @@ private void DrawPaletteRegion(Graphics g, Color color, Rectangle region) int width = cellTotalSize * region.Width; int height = cellTotalSize * region.Height; - var rect = new Rectangle(x, y, width, height); - using var pen = new Pen(color); + Rectangle rect = new(x, y, width, height); + using Pen pen = new(color); g.DrawRectangle(pen, rect); } @@ -638,7 +635,7 @@ private SNESGraphicsDecoder.PaletteSelection GetPaletteSelectionForTileDisplay(i if (selection == eDisplayType.OBJTiles0) bpp = 4; if (selection == eDisplayType.OBJTiles1) bpp = 4; - var ret = new SNESGraphicsDecoder.PaletteSelection(); + SNESGraphicsDecoder.PaletteSelection ret = new(); if(bpp == 0) return ret; //mode7 ext is fixed to use the top 128 colors @@ -664,8 +661,8 @@ private void RenderPalette() int pixsize = paletteCellSize * 16 + paletteCellSpacing * 17; int cellTotalSize = (paletteCellSize + paletteCellSpacing); - var bmp = new Bitmap(pixsize, pixsize, PixelFormat.Format32bppArgb); - using (var g = Graphics.FromImage(bmp)) + Bitmap bmp = new(pixsize, pixsize, PixelFormat.Format32bppArgb); + using (Graphics g = Graphics.FromImage(bmp)) { for (int y = 0; y < 16; y++) { @@ -673,7 +670,7 @@ private void RenderPalette() { int rgb555 = lastPalette[y * 16 + x]; int color = gd.Colorize(rgb555); - using var brush = new SolidBrush(Color.FromArgb(color)); + using SolidBrush brush = new(Color.FromArgb(color)); g.FillRectangle(brush, new Rectangle(paletteCellSpacing + x * cellTotalSize, paletteCellSpacing + y * cellTotalSize, paletteCellSize, paletteCellSize)); } } @@ -691,7 +688,7 @@ private void RenderPalette() } if (IsDisplayTypeOBJ(CurrDisplaySelection)) { - var ps = new SNESGraphicsDecoder.PaletteSelection(128, 128); + SNESGraphicsDecoder.PaletteSelection ps = new(128, 128); region = GetPaletteRegion(ps); DrawPaletteRegion(g, Color.FromArgb(192, 128, 255, 255), region); } @@ -820,10 +817,7 @@ private void paletteViewer_MouseClick(object sender, MouseEventArgs e) InternalUpdateValues(); } - private void SyncColorSelection() - { - currPaletteSelection = GetPaletteSelectionForTileDisplay(selectedColorNum); - } + private void SyncColorSelection() => currPaletteSelection = GetPaletteSelectionForTileDisplay(selectedColorNum); private void pnDetailsPaletteColor_DoubleClick(object sender, EventArgs e) { @@ -833,20 +827,11 @@ private void pnDetailsPaletteColor_DoubleClick(object sender, EventArgs e) //cd.ShowDialog(this); } - private void SyncViewerSize() - { - viewer.Size = check2x.Checked ? new Size(1024, 1024) : new Size(512, 512); - } + private void SyncViewerSize() => viewer.Size = check2x.Checked ? new Size(1024, 1024) : new Size(512, 512); - private void checkScanlineControl_CheckedChanged(object sender, EventArgs e) - { - SyncCore(); - } + private void checkScanlineControl_CheckedChanged(object sender, EventArgs e) => SyncCore(); - private void check2x_CheckedChanged(object sender, EventArgs e) - { - SyncViewerSize(); - } + private void check2x_CheckedChanged(object sender, EventArgs e) => SyncViewerSize(); private bool viewerPan; private Point panStartLocation; @@ -873,7 +858,7 @@ private void Freeze() var tp = tabctrlDetails.SelectedTab; //clone the currently selected tab page into the destination - var oldControls = new ArrayList(pnGroupFreeze.Controls); + ArrayList oldControls = new(pnGroupFreeze.Controls); pnGroupFreeze.Controls.Clear(); foreach (Control control in tp.Controls) pnGroupFreeze.Controls.Add(control.Clone()); foreach (Control control in oldControls) control.Dispose(); @@ -954,7 +939,7 @@ private void RenderTileView() int tileSize = si.BG[bgs.bgnum].TileSize; int pixels = tileSize * tileSize; - var bmp = new Bitmap(tileSize, tileSize, PixelFormat.Format32bppArgb); + Bitmap bmp = new(tileSize, tileSize, PixelFormat.Format32bppArgb); var bmpData = bmp.LockBits(new Rectangle(0, 0, tileSize, tileSize), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); if (viewBgMode == SNESGraphicsDecoder.BGMode.Mode7) @@ -978,7 +963,7 @@ private void RenderTileView() //view a tileset tile int bpp = currTileDataState.Bpp; - var bmp = new Bitmap(8, 8, PixelFormat.Format32bppArgb); + Bitmap bmp = new(8, 8, PixelFormat.Format32bppArgb); var bmpdata = bmp.LockBits(new Rectangle(0, 0, 8, 8), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); if (currTileDataState.Type == eDisplayType.TilesMode7) gd.RenderMode7TilesToScreen((int*)bmpdata.Scan0, bmpdata.Stride / 4, false, false, 1, currTileDataState.Tile, 1); @@ -986,7 +971,7 @@ private void RenderTileView() gd.RenderMode7TilesToScreen((int*)bmpdata.Scan0, bmpdata.Stride / 4, true, false, 1, currTileDataState.Tile, 1); else if (currTileDataState.Type == eDisplayType.TilesMode7DC) gd.RenderMode7TilesToScreen((int*)bmpdata.Scan0, bmpdata.Stride / 4, false, true, 1, currTileDataState.Tile, 1); - else if (currTileDataState.Type == eDisplayType.OBJTiles0 || currTileDataState.Type == eDisplayType.OBJTiles1) + else if (currTileDataState.Type is eDisplayType.OBJTiles0 or eDisplayType.OBJTiles1) { //render an obj tile int tile = currTileDataState.Address / 32; @@ -1002,7 +987,7 @@ private void RenderTileView() var bounds = si.ObjSizeBoundsSquare; int width = bounds.Width; int height = bounds.Height; - var bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb); + Bitmap bmp = new(width, height, PixelFormat.Format32bppArgb); var bmpData = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); gd.RenderSpriteToScreen((int*)bmpData.Scan0, bmpData.Stride / 4, 0, 0, si, currObjDataState.Number); bmp.UnlockBits(bmpData); @@ -1010,7 +995,7 @@ private void RenderTileView() } else { - var bmp = new Bitmap(8, 8, PixelFormat.Format32bppArgb); + Bitmap bmp = new(8, 8, PixelFormat.Format32bppArgb); viewerTile.SetBitmap(bmp); } } @@ -1033,7 +1018,7 @@ private void HandleTileViewMouseOver(int pxacross, int pxtall, int bpp, int tx, }; currTileDataState.Address = (bpp == 7 ? 8 : bpp) * 8 * currTileDataState.Tile; currTileDataState.Palette = currPaletteSelection.start; - if (CurrDisplaySelection == eDisplayType.OBJTiles0 || CurrDisplaySelection == eDisplayType.OBJTiles1) + if (CurrDisplaySelection is eDisplayType.OBJTiles0 or eDisplayType.OBJTiles1) { if (tileNum < 256) currTileDataState.Address += si.OBJTable0Addr; @@ -1213,7 +1198,7 @@ private void checkBackdropColor_CheckedChanged(object sender, EventArgs e) private void pnBackdropColor_MouseDoubleClick(object sender, MouseEventArgs e) { - var cd = new ColorDialog + ColorDialog cd = new() { Color = pnBackdropColor.BackColor }; @@ -1231,7 +1216,7 @@ protected override bool ProcessCmdKey(ref Message msg, Keys keyData) if (keyData == (Keys.C | Keys.Control)) { // find the control under the mouse - Point m = Cursor.Position; + var m = Cursor.Position; Control top = this; Control found = null; do @@ -1276,7 +1261,7 @@ private void MessageTimer_Tick(object sender, EventArgs e) private void comboPalette_SelectedIndexChanged(object sender, EventArgs e) { if (suppression) return; - var pal = (SnesColors.ColorType)comboPalette.SelectedValue; + SnesColors.ColorType pal = (SnesColors.ColorType)comboPalette.SelectedValue; Console.WriteLine("set {0}", pal); try { @@ -1354,7 +1339,7 @@ private void checkEN_CheckedChanged(object sender, EventArgs e) private void lblEnPrio0_Click(object sender, EventArgs e) { bool all = checkEN0_OBJ.Checked && checkEN0_BG1.Checked && checkEN0_BG2.Checked && checkEN0_BG3.Checked && checkEN0_BG4.Checked; - var newVal = !all; + bool newVal = !all; checkEN0_OBJ.Checked = checkEN0_BG1.Checked = checkEN0_BG2.Checked = checkEN0_BG3.Checked = checkEN0_BG4.Checked = newVal; } @@ -1362,20 +1347,14 @@ private void lblEnPrio0_Click(object sender, EventArgs e) private void lblEnPrio1_Click(object sender, EventArgs e) { bool all = checkEN1_OBJ.Checked && checkEN1_BG1.Checked && checkEN1_BG2.Checked && checkEN1_BG3.Checked && checkEN1_BG4.Checked; - var newVal = !all; + bool newVal = !all; checkEN1_OBJ.Checked = checkEN1_BG1.Checked = checkEN1_BG2.Checked = checkEN1_BG3.Checked = checkEN1_BG4.Checked = newVal; } - private void lblEnPrio2_Click(object sender, EventArgs e) - { - checkEN2_OBJ.Checked ^= true; - } + private void lblEnPrio2_Click(object sender, EventArgs e) => checkEN2_OBJ.Checked ^= true; - private void lblEnPrio3_Click(object sender, EventArgs e) - { - checkEN3_OBJ.Checked ^= true; - } + private void lblEnPrio3_Click(object sender, EventArgs e) => checkEN3_OBJ.Checked ^= true; } //class SNESGraphicsDebugger } //namespace BizHawk.Client.EmuHawk diff --git a/src/BizHawk.Client.EmuHawk/tools/SNES/SNESGraphicsViewer.cs b/src/BizHawk.Client.EmuHawk/tools/SNES/SNESGraphicsViewer.cs index 64687346413..9939b90c086 100644 --- a/src/BizHawk.Client.EmuHawk/tools/SNES/SNESGraphicsViewer.cs +++ b/src/BizHawk.Client.EmuHawk/tools/SNES/SNESGraphicsViewer.cs @@ -13,7 +13,7 @@ protected override void ScaleControl(SizeF factor, BoundsSpecified specified) x = (int)(x * factor.Width); if (specified.HasFlag(BoundsSpecified.Y)) y = (int)(y * factor.Height); - var pt = new Point(x, y); + Point pt = new(x, y); if (pt != Location) Location = pt; } diff --git a/src/BizHawk.Client.EmuHawk/tools/TAStudio/BookmarksBranchesBox.cs b/src/BizHawk.Client.EmuHawk/tools/TAStudio/BookmarksBranchesBox.cs index fc31e2a4456..60225042fa8 100644 --- a/src/BizHawk.Client.EmuHawk/tools/TAStudio/BookmarksBranchesBox.cs +++ b/src/BizHawk.Client.EmuHawk/tools/TAStudio/BookmarksBranchesBox.cs @@ -17,7 +17,7 @@ public partial class BookmarksBranchesBox : UserControl, IDialogParent private const string FrameColumnName = "FrameColumn"; private const string UserTextColumnName = "TextColumn"; - private readonly ScreenshotForm _screenshot = new ScreenshotForm(); + private readonly ScreenshotForm _screenshot = new(); private ITasMovie Movie => Tastudio.CurrentTasMovie; private ITasBranchCollection Branches => Movie.Branches; @@ -272,7 +272,7 @@ private bool PrepareHistoryAndLoadSelectedBranch() { _backupBranch = CreateBranch(); - var currentHashes = Branches.Select(b => b.Uuid.GetHashCode()).ToList(); + System.Collections.Generic.List currentHashes = Branches.Select(b => b.Uuid.GetHashCode()).ToList(); do { _backupBranch.Uuid = Guid.NewGuid(); @@ -286,7 +286,7 @@ private bool PrepareHistoryAndLoadSelectedBranch() if (!BranchView.AnyRowsSelected) return false; // why'd we do all that then - var success = LoadSelectedBranch(); + bool success = LoadSelectedBranch(); LoadedCallback?.Invoke(BranchView.FirstSelectedRowIndex); return success; } @@ -325,7 +325,7 @@ private void EditBranchTextToolStripMenuItem_Click(object sender, EventArgs e) return; } - var index = BranchView.FirstSelectedRowIndex; + int index = BranchView.FirstSelectedRowIndex; string oldText = SelectedBranch.UserText; if (EditBranchTextPopUp(index)) @@ -353,9 +353,9 @@ private void RemoveBranchToolStripMenuItem_Click(object sender, EventArgs e) return; } - var indices = BranchView.SelectedRows.ToList(); - var branches = Branches.ToList(); - foreach (var index in indices) + System.Collections.Generic.List indices = BranchView.SelectedRows.ToList(); + System.Collections.Generic.List branches = Branches.ToList(); + foreach (int index in indices) { _backupBranch = branches[index].Clone(); Branches.Remove(branches[index]); @@ -423,10 +423,7 @@ private void UndoBranchToolStripMenuItem_Click(object sender, EventArgs e) Tastudio.RefreshDialog(); } - public void AddBranchExternal() - { - AddBranchToolStripMenuItem_Click(null, null); - } + public void AddBranchExternal() => AddBranchToolStripMenuItem_Click(null, null); public bool LoadBranchExternal(int slot = -1) { @@ -477,10 +474,7 @@ public void UpdateBranchExternal(int slot = -1) UpdateBranchToolStripMenuItem_Click(null, null); } - public void RemoveBranchExternal() - { - RemoveBranchToolStripMenuItem_Click(null, null); - } + public void RemoveBranchExternal() => RemoveBranchToolStripMenuItem_Click(null, null); public void SelectBranchExternal(int slot) { @@ -509,7 +503,7 @@ public void SelectBranchExternal(bool next) return; } - var sel = BranchView.FirstSelectedRowIndex; + int sel = BranchView.FirstSelectedRowIndex; if (next) { if (Branches[sel + 1] != null) @@ -550,10 +544,7 @@ public void NonExistentBranchMessage(int slot) Tastudio.MainForm.AddOnScreenMessage($"Use {Tastudio.Config!.HotkeyBindings["Add Branch"]} to add branches"); } - public void UpdateValues() - { - BranchView.RowCount = Branches.Count; - } + public void UpdateValues() => BranchView.RowCount = Branches.Count; public void Restart() { @@ -571,7 +562,7 @@ public void UpdateTextColumnWidth() { if (Branches.Any()) { - var longestBranchText = Branches + string longestBranchText = Branches .OrderBy(b => b.UserText?.Length ?? 0) .Last() .UserText; @@ -588,7 +579,7 @@ public bool EditBranchTextPopUp(int index) return false; } - var i = new InputPrompt + InputPrompt i = new() { Text = $"Text for branch {index + 1}", TextInputType = InputPrompt.InputType.Text, @@ -652,10 +643,7 @@ private void BranchView_MouseMove(object sender, MouseEventArgs e) } } - private void BranchView_MouseLeave(object sender, EventArgs e) - { - _screenshot.FadeOut(); - } + private void BranchView_MouseLeave(object sender, EventArgs e) => _screenshot.FadeOut(); private void BranchView_CellDropped(object sender, InputRoll.CellEventArgs e) { @@ -681,7 +669,7 @@ private void BranchView_PointedCellChanged(object sender, InputRoll.CellEventArg BranchView.CurrentCell.RowIndex < Branches.Count) { var branch = Branches[BranchView.CurrentCell.RowIndex.Value]; - Point location = PointToScreen(Location); + var location = PointToScreen(Location); int width = branch.OSDFrameBuffer.Width; int height = branch.OSDFrameBuffer.Height; location.Offset(-width, 0); @@ -708,9 +696,6 @@ private void BranchView_PointedCellChanged(object sender, InputRoll.CellEventArg } } - private void BranchView_SelectedIndexChanged(object sender, EventArgs e) - { - UpdateButtons(); - } + private void BranchView_SelectedIndexChanged(object sender, EventArgs e) => UpdateButtons(); } } diff --git a/src/BizHawk.Client.EmuHawk/tools/TAStudio/FramesPrompt.cs b/src/BizHawk.Client.EmuHawk/tools/TAStudio/FramesPrompt.cs index 25127ef6d06..23df120926f 100644 --- a/src/BizHawk.Client.EmuHawk/tools/TAStudio/FramesPrompt.cs +++ b/src/BizHawk.Client.EmuHawk/tools/TAStudio/FramesPrompt.cs @@ -20,10 +20,7 @@ public FramesPrompt(string headMessage, string bodyMessage) public int Frames => NumFramesBox.ToRawInt() ?? 0; - private void FramesPrompt_Load(object sender, EventArgs e) - { - NumFramesBox.Select(); - } + private void FramesPrompt_Load(object sender, EventArgs e) => NumFramesBox.Select(); private void OkBtn_Click(object sender, EventArgs e) { diff --git a/src/BizHawk.Client.EmuHawk/tools/TAStudio/GreenzoneSettings.cs b/src/BizHawk.Client.EmuHawk/tools/TAStudio/GreenzoneSettings.cs index e23c7b61465..8bab2f74c2a 100644 --- a/src/BizHawk.Client.EmuHawk/tools/TAStudio/GreenzoneSettings.cs +++ b/src/BizHawk.Client.EmuHawk/tools/TAStudio/GreenzoneSettings.cs @@ -27,22 +27,16 @@ public GreenzoneSettings(IDialogController dialogController, ZwinderStateManager SettingsPropertyGrid.SelectedObject = _settings; } - private void GreenzoneSettings_Load(object sender, EventArgs e) - { - SettingsPropertyGrid.AdjustDescriptionHeightToFit(); - } + private void GreenzoneSettings_Load(object sender, EventArgs e) => SettingsPropertyGrid.AdjustDescriptionHeightToFit(); private void OkBtn_Click(object sender, EventArgs e) { - var keep = !_isDefault && DialogController.ShowMessageBox2("Attempt to keep old states?", "Keep old states?"); + bool keep = !_isDefault && DialogController.ShowMessageBox2("Attempt to keep old states?", "Keep old states?"); _saveSettings(_settings, keep); Close(); } - private void CancelBtn_Click(object sender, EventArgs e) - { - Close(); - } + private void CancelBtn_Click(object sender, EventArgs e) => Close(); private void DefaultsButton_Click(object sender, EventArgs e) { diff --git a/src/BizHawk.Client.EmuHawk/tools/TAStudio/HeaderEditor.cs b/src/BizHawk.Client.EmuHawk/tools/TAStudio/HeaderEditor.cs index 9952d940136..81af18fe2e2 100644 --- a/src/BizHawk.Client.EmuHawk/tools/TAStudio/HeaderEditor.cs +++ b/src/BizHawk.Client.EmuHawk/tools/TAStudio/HeaderEditor.cs @@ -50,9 +50,6 @@ private void CancelBtn_Click(object sender, EventArgs e) Close(); } - private void DefaultAuthorButton_Click(object sender, EventArgs e) - { - AuthorTextBox.Text = _config.DefaultAuthor; - } + private void DefaultAuthorButton_Click(object sender, EventArgs e) => AuthorTextBox.Text = _config.DefaultAuthor; } } diff --git a/src/BizHawk.Client.EmuHawk/tools/TAStudio/MarkerControl.Designer.cs b/src/BizHawk.Client.EmuHawk/tools/TAStudio/MarkerControl.Designer.cs index a141eecbd77..2bc4114a668 100644 --- a/src/BizHawk.Client.EmuHawk/tools/TAStudio/MarkerControl.Designer.cs +++ b/src/BizHawk.Client.EmuHawk/tools/TAStudio/MarkerControl.Designer.cs @@ -45,7 +45,7 @@ private void InitializeComponent() this.RemoveMarkerButton = new System.Windows.Forms.Button(); this.ScrollToMarkerButton = new System.Windows.Forms.Button(); this.AddMarkerWithTextButton = new System.Windows.Forms.Button(); - this.MarkerView = new BizHawk.Client.EmuHawk.InputRoll(); + this.MarkerInputRoll = new BizHawk.Client.EmuHawk.InputRoll(); this.MarkersGroupBox = new System.Windows.Forms.GroupBox(); this.MarkerContextMenu.SuspendLayout(); this.MarkersGroupBox.SuspendLayout(); @@ -179,35 +179,35 @@ private void InitializeComponent() // // MarkerView // - this.MarkerView.AllowColumnReorder = false; - this.MarkerView.AllowColumnResize = false; - this.MarkerView.AllowMassNavigationShortcuts = true; - this.MarkerView.AllowRightClickSelection = true; - this.MarkerView.AlwaysScroll = false; - this.MarkerView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + this.MarkerInputRoll.AllowColumnReorder = false; + this.MarkerInputRoll.AllowColumnResize = false; + this.MarkerInputRoll.AllowMassNavigationShortcuts = true; + this.MarkerInputRoll.AllowRightClickSelection = true; + this.MarkerInputRoll.AlwaysScroll = false; + this.MarkerInputRoll.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); - this.MarkerView.CellHeightPadding = 0; - this.MarkerView.ChangeSelectionWhenPaging = true; - this.MarkerView.ContextMenuStrip = this.MarkerContextMenu; - this.MarkerView.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); - this.MarkerView.FullRowSelect = true; - this.MarkerView.HorizontalOrientation = false; - this.MarkerView.LetKeysModifySelection = false; - this.MarkerView.Location = new System.Drawing.Point(6, 19); - this.MarkerView.Name = "MarkerView"; - this.MarkerView.RowCount = 0; - this.MarkerView.ScrollSpeed = 1; - this.MarkerView.SeekingCutoffInterval = 0; - this.MarkerView.Size = new System.Drawing.Size(186, 224); - this.MarkerView.TabIndex = 0; - this.MarkerView.TabStop = false; - this.MarkerView.SelectedIndexChanged += new System.EventHandler(this.MarkerView_SelectedIndexChanged); - this.MarkerView.DoubleClick += new System.EventHandler(this.MarkerView_MouseDoubleClick); + this.MarkerInputRoll.CellHeightPadding = 0; + this.MarkerInputRoll.ChangeSelectionWhenPaging = true; + this.MarkerInputRoll.ContextMenuStrip = this.MarkerContextMenu; + this.MarkerInputRoll.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.MarkerInputRoll.FullRowSelect = true; + this.MarkerInputRoll.HorizontalOrientation = false; + this.MarkerInputRoll.LetKeysModifySelection = false; + this.MarkerInputRoll.Location = new System.Drawing.Point(6, 19); + this.MarkerInputRoll.Name = "MarkerView"; + this.MarkerInputRoll.RowCount = 0; + this.MarkerInputRoll.ScrollSpeed = 1; + this.MarkerInputRoll.SeekingCutoffInterval = 0; + this.MarkerInputRoll.Size = new System.Drawing.Size(186, 224); + this.MarkerInputRoll.TabIndex = 0; + this.MarkerInputRoll.TabStop = false; + this.MarkerInputRoll.SelectedIndexChanged += new System.EventHandler(this.MarkerView_SelectedIndexChanged); + this.MarkerInputRoll.DoubleClick += new System.EventHandler(this.MarkerView_MouseDoubleClick); // // MarkersGroupBox // - this.MarkersGroupBox.Controls.Add(this.MarkerView); + this.MarkersGroupBox.Controls.Add(this.MarkerInputRoll); this.MarkersGroupBox.Controls.Add(this.AddMarkerButton); this.MarkersGroupBox.Controls.Add(this.AddMarkerWithTextButton); this.MarkersGroupBox.Controls.Add(this.RemoveMarkerButton); @@ -237,7 +237,6 @@ private void InitializeComponent() #endregion - private InputRoll MarkerView; private System.Windows.Forms.Button AddMarkerButton; private System.Windows.Forms.Button RemoveMarkerButton; private System.Windows.Forms.Button JumpToMarkerButton; diff --git a/src/BizHawk.Client.EmuHawk/tools/TAStudio/MarkerControl.cs b/src/BizHawk.Client.EmuHawk/tools/TAStudio/MarkerControl.cs index e388e4f1fd7..8598f3fcc11 100644 --- a/src/BizHawk.Client.EmuHawk/tools/TAStudio/MarkerControl.cs +++ b/src/BizHawk.Client.EmuHawk/tools/TAStudio/MarkerControl.cs @@ -17,7 +17,7 @@ public partial class MarkerControl : UserControl, IDialogParent public IDialogController DialogController => Tastudio.MainForm; private TasMovieMarker FirstSelectedMarker - => Markers[MarkerView.FirstSelectedRowIndex]; + => Markers[MarkerInputRoll.FirstSelectedRowIndex]; public MarkerControl() { @@ -36,14 +36,14 @@ public MarkerControl() ScrollToMarkerButton.Image = Resources.ScrollTo; AddMarkerWithTextButton.Image = Resources.AddEdit; SetupColumns(); - MarkerView.QueryItemBkColor += MarkerView_QueryItemBkColor; - MarkerView.QueryItemText += MarkerView_QueryItemText; + MarkerInputRoll.QueryItemBkColor += MarkerView_QueryItemBkColor; + MarkerInputRoll.QueryItemText += MarkerView_QueryItemText; } private void SetupColumns() { - MarkerView.AllColumns.Clear(); - MarkerView.AllColumns.AddRange(new[] + MarkerInputRoll.AllColumns.Clear(); + MarkerInputRoll.AllColumns.AddRange(new[] { new RollColumn { @@ -62,7 +62,7 @@ private void SetupColumns() }); } - public InputRoll MarkerInputRoll => MarkerView; + public InputRoll MarkerInputRoll { get; private set; } private void MarkerView_QueryItemBkColor(int index, RollColumn column, ref Color color) { @@ -127,7 +127,7 @@ private void MarkerContextMenu_Opening(object sender, CancelEventArgs e) EditMarkerToolStripMenuItem.Enabled = EditMarkerFrameToolStripMenuItem.Enabled = RemoveMarkerToolStripMenuItem.Enabled = - MarkerInputRoll.AnyRowsSelected && MarkerView.FirstSelectedRowIndex is not 0; + MarkerInputRoll.AnyRowsSelected && MarkerInputRoll.FirstSelectedRowIndex is not 0; JumpToMarkerToolStripMenuItem.Enabled = ScrollToMarkerToolStripMenuItem.Enabled = @@ -136,7 +136,7 @@ private void MarkerContextMenu_Opening(object sender, CancelEventArgs e) private void ScrollToMarkerToolStripMenuItem_Click(object sender, EventArgs e) { - if (MarkerView.AnyRowsSelected) + if (MarkerInputRoll.AnyRowsSelected) { Tastudio.SetVisibleFrame(FirstSelectedMarker.Frame); Tastudio.RefreshDialog(); @@ -145,48 +145,39 @@ private void ScrollToMarkerToolStripMenuItem_Click(object sender, EventArgs e) private void JumpToMarkerToolStripMenuItem_Click(object sender, EventArgs e) { - if (MarkerView.AnyRowsSelected) Tastudio.GoToFrame(FirstSelectedMarker.Frame); + if (MarkerInputRoll.AnyRowsSelected) Tastudio.GoToFrame(FirstSelectedMarker.Frame); } private void EditMarkerToolStripMenuItem_Click(object sender, EventArgs e) { - if (MarkerView.AnyRowsSelected) EditMarkerPopUp(FirstSelectedMarker); + if (MarkerInputRoll.AnyRowsSelected) EditMarkerPopUp(FirstSelectedMarker); } private void EditMarkerFrameToolStripMenuItem_Click(object sender, EventArgs e) { - if (MarkerView.AnyRowsSelected) EditMarkerFramePopUp(FirstSelectedMarker); + if (MarkerInputRoll.AnyRowsSelected) EditMarkerFramePopUp(FirstSelectedMarker); } - private void AddMarkerToolStripMenuItem_Click(object sender, EventArgs e) - { - AddMarker(Tastudio.Emulator.Frame); - } + private void AddMarkerToolStripMenuItem_Click(object sender, EventArgs e) => AddMarker(Tastudio.Emulator.Frame); - private void AddMarkerWithTextToolStripMenuItem_Click(object sender, EventArgs e) - { - AddMarker(Tastudio.Emulator.Frame, true); - } + private void AddMarkerWithTextToolStripMenuItem_Click(object sender, EventArgs e) => AddMarker(Tastudio.Emulator.Frame, true); private void RemoveMarkerToolStripMenuItem_Click(object sender, EventArgs e) { - if (!MarkerView.AnyRowsSelected) return; - foreach (var i in MarkerView.SelectedRows.Select(index => Markers[index]).ToList()) Markers.Remove(i); - MarkerView.RowCount = Markers.Count; + if (!MarkerInputRoll.AnyRowsSelected) return; + foreach (var i in MarkerInputRoll.SelectedRows.Select(index => Markers[index]).ToList()) Markers.Remove(i); + MarkerInputRoll.RowCount = Markers.Count; Tastudio.RefreshDialog(); } - public void UpdateMarkerCount() - { - MarkerView.RowCount = Markers.Count; - } + public void UpdateMarkerCount() => MarkerInputRoll.RowCount = Markers.Count; public void AddMarker(int frame, bool editText = false) { TasMovieMarker marker; if (editText) { - var i = new InputPrompt + InputPrompt i = new() { Text = $"Marker for frame {frame}", TextInputType = InputPrompt.InputType.Text, @@ -214,8 +205,8 @@ public void AddMarker(int frame, bool editText = false) UpdateValues(); Markers.Add(marker); - var index = Markers.IndexOf(marker); - MarkerView.MakeIndexVisible(index); + int index = Markers.IndexOf(marker); + MarkerInputRoll.MakeIndexVisible(index); Tastudio.RefreshDialog(); } @@ -223,19 +214,19 @@ public void UpdateTextColumnWidth() { if (Markers.Any()) { - var longestBranchText = Markers + string longestBranchText = Markers .OrderBy(b => b.Message?.Length ?? 0) .Last() .Message; - MarkerView.ExpandColumnToFitText("LabelColumn", longestBranchText); + MarkerInputRoll.ExpandColumnToFitText("LabelColumn", longestBranchText); } } public void EditMarkerPopUp(TasMovieMarker marker, bool followCursor = false) { - var markerFrame = marker.Frame; - var i = new InputPrompt + int markerFrame = marker.Frame; + InputPrompt i = new() { Text = $"Marker for frame {markerFrame}", TextInputType = InputPrompt.InputType.Text, @@ -263,8 +254,8 @@ public void EditMarkerPopUp(TasMovieMarker marker, bool followCursor = false) public void EditMarkerFramePopUp(TasMovieMarker marker) { - var markerFrame = marker.Frame; - var i = new InputPrompt + int markerFrame = marker.Frame; + InputPrompt i = new() { Text = $"Marker for frame {markerFrame}", TextInputType = InputPrompt.InputType.Unsigned, @@ -275,7 +266,7 @@ public void EditMarkerFramePopUp(TasMovieMarker marker) }; if (!this.ShowDialogWithTempMute(i).IsOk() - || !int.TryParse(i.PromptText, out var promptValue) + || !int.TryParse(i.PromptText, out int promptValue) || Markers.IsMarker(promptValue)) // don't move to frame with an existing marker { return; @@ -288,17 +279,17 @@ public void EditMarkerFramePopUp(TasMovieMarker marker) public void UpdateValues() { - if (MarkerView != null && Tastudio?.CurrentTasMovie != null && Markers != null) + if (MarkerInputRoll != null && Tastudio?.CurrentTasMovie != null && Markers != null) { - MarkerView.RowCount = Markers.Count; + MarkerInputRoll.RowCount = Markers.Count; } } public void Restart() { SetupColumns(); - MarkerView.RowCount = Markers.Count; - MarkerView.Refresh(); + MarkerInputRoll.RowCount = Markers.Count; + MarkerInputRoll.Refresh(); } private void MarkerView_SelectedIndexChanged(object sender, EventArgs e) @@ -306,7 +297,7 @@ private void MarkerView_SelectedIndexChanged(object sender, EventArgs e) EditMarkerButton.Enabled = EditMarkerFrameButton.Enabled = RemoveMarkerButton.Enabled = - MarkerInputRoll.AnyRowsSelected && MarkerView.FirstSelectedRowIndex is not 0; + MarkerInputRoll.AnyRowsSelected && MarkerInputRoll.FirstSelectedRowIndex is not 0; JumpToMarkerButton.Enabled = ScrollToMarkerButton.Enabled = @@ -317,7 +308,7 @@ private void MarkerView_SelectedIndexChanged(object sender, EventArgs e) // A much more useful feature would be to easily jump to it. private void MarkerView_MouseDoubleClick(object sender, EventArgs e) { - if (MarkerView.AnyRowsSelected) Tastudio.GoToFrame(FirstSelectedMarker.Frame); + if (MarkerInputRoll.AnyRowsSelected) Tastudio.GoToFrame(FirstSelectedMarker.Frame); } } } diff --git a/src/BizHawk.Client.EmuHawk/tools/TAStudio/PatternsForm.cs b/src/BizHawk.Client.EmuHawk/tools/TAStudio/PatternsForm.cs index 3d992848ceb..1c15cb36a8d 100644 --- a/src/BizHawk.Client.EmuHawk/tools/TAStudio/PatternsForm.cs +++ b/src/BizHawk.Client.EmuHawk/tools/TAStudio/PatternsForm.cs @@ -11,8 +11,8 @@ public partial class PatternsForm : Form { private readonly TAStudio _tastudio; - private readonly List _counts = new List(); - private readonly List _values = new List(); + private readonly List _counts = new(); + private readonly List _values = new(); private int _loopAt; private bool _updating; @@ -26,12 +26,12 @@ public PatternsForm(TAStudio owner) _tastudio = owner; - foreach (var button in _tastudio.MovieSession.MovieController.Definition.BoolButtons) + foreach (string button in _tastudio.MovieSession.MovieController.Definition.BoolButtons) { ButtonBox.Items.Add(button); } - foreach (var button in _tastudio.MovieSession.MovieController.Definition.Axes.Keys) + foreach (string button in _tastudio.MovieSession.MovieController.Definition.Axes.Keys) { ButtonBox.Items.Add(button); } @@ -40,10 +40,7 @@ public PatternsForm(TAStudio owner) ButtonBox.Items.Add("Default float Auto-Fire"); } - private void PatternsForm_Load(object sender, EventArgs e) - { - ButtonBox.SelectedIndex = 0; - } + private void PatternsForm_Load(object sender, EventArgs e) => ButtonBox.SelectedIndex = 0; private void ButtonBox_SelectedIndexChanged(object sender, EventArgs e) { @@ -99,10 +96,7 @@ private void DeleteButton_Click(object sender, EventArgs e) UpdateDisplay(); } - private void LagBox_CheckedChanged(object sender, EventArgs e) - { - UpdatePattern(); - } + private void LagBox_CheckedChanged(object sender, EventArgs e) => UpdatePattern(); private void ValueNum_ValueChanged(object sender, EventArgs e) { @@ -241,7 +235,7 @@ private void UpdatePattern() if (index != -1) { - var p = new List(); + List p = new(); for (int i = 0; i < _counts.Count; i++) { for (int c = 0; c < _counts[i]; c++) @@ -263,7 +257,7 @@ private void UpdatePattern() index = _tastudio.MovieSession.MovieController.Definition.Axes.IndexOf(SelectedButton); } - var p = new List(); + List p = new(); for (int i = 0; i < _counts.Count; i++) { for (int c = 0; c < _counts[i]; c++) @@ -275,7 +269,7 @@ private void UpdatePattern() _tastudio.AxisPatterns[index] = new AutoPatternAxis(p.ToArray(), LagBox.Checked, 0, _loopAt); } - if ((SelectedButton != "Default float Auto-Fire") && (SelectedButton != "Default bool Auto-Fire")) + if (SelectedButton is not "Default float Auto-Fire" and not "Default bool Auto-Fire") { _tastudio.UpdateAutoFire(SelectedButton, null); } @@ -325,8 +319,8 @@ private void GetPattern() index = _tastudio.MovieSession.MovieController.Definition.Axes.IndexOf(SelectedButton); } - var p = _tastudio.AxisPatterns[index].Pattern; - var lastValue = p[0]; + int[] p = _tastudio.AxisPatterns[index].Pattern; + int lastValue = p[0]; _counts.Clear(); _values.Clear(); _counts.Add(1); diff --git a/src/BizHawk.Client.EmuHawk/tools/TAStudio/PlaybackBox.cs b/src/BizHawk.Client.EmuHawk/tools/TAStudio/PlaybackBox.cs index b5c2f4f30b4..6c39fb0d183 100644 --- a/src/BizHawk.Client.EmuHawk/tools/TAStudio/PlaybackBox.cs +++ b/src/BizHawk.Client.EmuHawk/tools/TAStudio/PlaybackBox.cs @@ -79,20 +79,11 @@ protected override void OnLoad(EventArgs e) _loading = false; } - private void PreviousMarkerButton_Click(object sender, EventArgs e) - { - Tastudio.GoToPreviousMarker(); - } + private void PreviousMarkerButton_Click(object sender, EventArgs e) => Tastudio.GoToPreviousMarker(); - private void PauseButton_Click(object sender, EventArgs e) - { - Tastudio.TogglePause(); - } + private void PauseButton_Click(object sender, EventArgs e) => Tastudio.TogglePause(); - private void NextMarkerButton_Click(object sender, EventArgs e) - { - Tastudio.GoToNextMarker(); - } + private void NextMarkerButton_Click(object sender, EventArgs e) => Tastudio.GoToNextMarker(); private void TurboSeekCheckbox_CheckedChanged(object sender, EventArgs e) { @@ -130,34 +121,16 @@ private void RecordingModeCheckbox_MouseClick(object sender, MouseEventArgs e) Tastudio.WasRecording = RecordingMode; // hard reset at manual click } - private void RewindButton_MouseDown(object sender, MouseEventArgs e) - { - Tastudio.MainForm.PressRewind = true; - } + private void RewindButton_MouseDown(object sender, MouseEventArgs e) => Tastudio.MainForm.PressRewind = true; - private void RewindButton_MouseUp(object sender, MouseEventArgs e) - { - Tastudio.MainForm.PressRewind = false; - } + private void RewindButton_MouseUp(object sender, MouseEventArgs e) => Tastudio.MainForm.PressRewind = false; - private void RewindButton_MouseLeave(object sender, EventArgs e) - { - Tastudio.MainForm.PressRewind = false; - } + private void RewindButton_MouseLeave(object sender, EventArgs e) => Tastudio.MainForm.PressRewind = false; - private void FrameAdvanceButton_MouseDown(object sender, MouseEventArgs e) - { - Tastudio.MainForm.HoldFrameAdvance = true; - } + private void FrameAdvanceButton_MouseDown(object sender, MouseEventArgs e) => Tastudio.MainForm.HoldFrameAdvance = true; - private void FrameAdvanceButton_MouseLeave(object sender, EventArgs e) - { - Tastudio.MainForm.HoldFrameAdvance = false; - } + private void FrameAdvanceButton_MouseLeave(object sender, EventArgs e) => Tastudio.MainForm.HoldFrameAdvance = false; - private void FrameAdvanceButton_MouseUp(object sender, MouseEventArgs e) - { - Tastudio.MainForm.HoldFrameAdvance = false; - } + private void FrameAdvanceButton_MouseUp(object sender, MouseEventArgs e) => Tastudio.MainForm.HoldFrameAdvance = false; } } diff --git a/src/BizHawk.Client.EmuHawk/tools/TAStudio/ScreenshotForm.cs b/src/BizHawk.Client.EmuHawk/tools/TAStudio/ScreenshotForm.cs index ce8fc52cca3..e3205040b4f 100644 --- a/src/BizHawk.Client.EmuHawk/tools/TAStudio/ScreenshotForm.cs +++ b/src/BizHawk.Client.EmuHawk/tools/TAStudio/ScreenshotForm.cs @@ -16,8 +16,8 @@ public partial class ScreenshotForm : Form private const int Interval = 40; private const double AlphaStep = 0.125; - private readonly Timer _showTimer = new Timer(); - private readonly Timer _hideTimer = new Timer(); + private readonly Timer _showTimer = new(); + private readonly Timer _hideTimer = new(); private TasBranch _branch; private int _drawingHeight; @@ -29,8 +29,8 @@ public partial class ScreenshotForm : Form public ScreenshotForm() { InitializeComponent(); - - var fontSize = 10; + + int fontSize = 10; var fontStyle = FontStyle.Regular; Font = new Font(FontFamily.GenericMonospace, fontSize, fontStyle); _drawingHeight = 0; @@ -111,7 +111,7 @@ protected override CreateParams CreateParams { get { - CreateParams createParams = base.CreateParams; + var createParams = base.CreateParams; createParams.ExStyle |= WS_EX_TOPMOST; return createParams; } diff --git a/src/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.Callbacks.cs b/src/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.Callbacks.cs index a9dff4b5ec4..b292a230e94 100644 --- a/src/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.Callbacks.cs +++ b/src/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.Callbacks.cs @@ -15,24 +15,12 @@ public partial class TAStudio public Action BranchSavedCallback { get; set; } public Action BranchRemovedCallback { get; set; } - private void GreenzoneInvalidated(int index) - { - GreenzoneInvalidatedCallback?.Invoke(index); - } + private void GreenzoneInvalidated(int index) => GreenzoneInvalidatedCallback?.Invoke(index); - private void BranchLoaded(int index) - { - BranchLoadedCallback?.Invoke(index); - } + private void BranchLoaded(int index) => BranchLoadedCallback?.Invoke(index); - private void BranchSaved(int index) - { - BranchSavedCallback?.Invoke(index); - } + private void BranchSaved(int index) => BranchSavedCallback?.Invoke(index); - private void BranchRemoved(int index) - { - BranchRemovedCallback?.Invoke(index); - } + private void BranchRemoved(int index) => BranchRemovedCallback?.Invoke(index); } } diff --git a/src/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.IControlMainForm.cs b/src/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.IControlMainForm.cs index a3d0582d508..c27912e65d7 100644 --- a/src/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.IControlMainForm.cs +++ b/src/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.IControlMainForm.cs @@ -10,10 +10,7 @@ public partial class TAStudio : IControlMainform public bool WantsToControlSavestates => !NamedStatePending; - public void SaveState() - { - BookMarkControl.UpdateBranchExternal(); - } + public void SaveState() => BookMarkControl.UpdateBranchExternal(); public bool LoadState() => BookMarkControl.LoadBranchExternal(); @@ -116,7 +113,7 @@ public bool RestartMovie() { if (!AskSaveChanges()) return false; WantsToControlStopMovie = false; - var success = StartNewMovieWrapper(CurrentTasMovie); + bool success = StartNewMovieWrapper(CurrentTasMovie); WantsToControlStopMovie = true; RefreshDialog(); return success; diff --git a/src/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.IToolForm.cs b/src/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.IToolForm.cs index 772b08c1308..2a8af0dcd93 100644 --- a/src/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.IToolForm.cs +++ b/src/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.IToolForm.cs @@ -54,10 +54,7 @@ private void UpdateProgressBar() } } - protected override void GeneralUpdate() - { - RefreshDialog(); - } + protected override void GeneralUpdate() => RefreshDialog(); protected override void UpdateAfter() { @@ -71,7 +68,7 @@ protected override void UpdateAfter() return; } - var refreshNeeded = false; + bool refreshNeeded = false; if (AutoadjustInputMenuItem.Checked) { refreshNeeded = AutoAdjustInput(); @@ -89,10 +86,7 @@ protected override void UpdateAfter() UpdateProgressBar(); } - protected override void FastUpdateAfter() - { - UpdateProgressBar(); - } + protected override void FastUpdateAfter() => UpdateProgressBar(); public override void Restart() { diff --git a/src/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.ListView.cs b/src/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.ListView.cs index 135b5709a92..29562dc86dd 100644 --- a/src/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.ListView.cs +++ b/src/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.ListView.cs @@ -47,7 +47,7 @@ private int AxisEditRow public bool AxisEditingMode => _axisEditRow != -1; - private readonly List _extraAxisRows = new List(); + private readonly List _extraAxisRows = new(); // Right-click dragging private string[] _rightClickInput; @@ -158,7 +158,7 @@ private void TasView_QueryItemIcon(int index, RollColumn column, ref Bitmap bitm return; } - var columnName = column.Name; + string columnName = column.Name; if (columnName == CursorColumnName) { @@ -218,7 +218,7 @@ private void TasView_QueryItemBkColor(int index, RollColumn column, ref Color co return; } - Color? overrideColor = QueryItemBgColorCallback?.Invoke(index, column.Name); + var overrideColor = QueryItemBgColorCallback?.Invoke(index, column.Name); if (overrideColor.HasValue) { @@ -254,7 +254,7 @@ private void TasView_QueryItemBkColor(int index, RollColumn column, ref Color co if (_alternateRowColor.GetValueOrPut( columnName, columnName1 => { - var playerNumber = ControllerDefinition.PlayerNumber(columnName1); + int playerNumber = ControllerDefinition.PlayerNumber(columnName1); return playerNumber % 2 is 0 && playerNumber is not 0; })) { @@ -318,7 +318,7 @@ private void TasView_QueryItemText(int index, RollColumn column, out string text return; } - var overrideText = QueryItemTextCallback?.Invoke(index, column.Name); + string overrideText = QueryItemTextCallback?.Invoke(index, column.Name); if (overrideText != null) { text = overrideText; @@ -328,7 +328,7 @@ private void TasView_QueryItemText(int index, RollColumn column, out string text try { text = ""; - var columnName = column.Name; + string columnName = column.Name; if (columnName == CursorColumnName) { @@ -381,7 +381,7 @@ private void TasView_ColumnClick(object sender, InputRoll.ColumnClickEventArgs e { if (TasView.AnyRowsSelected) { - var columnName = e.Column.Name; + string columnName = e.Column.Name; if (columnName == FrameColumnName) { @@ -389,7 +389,7 @@ private void TasView_ColumnClick(object sender, InputRoll.ColumnClickEventArgs e } else if (columnName != CursorColumnName) { - var frame = TasView.AnyRowsSelected ? TasView.FirstSelectedRowIndex : 0; + int frame = TasView.AnyRowsSelected ? TasView.FirstSelectedRowIndex : 0; string buttonName = TasView.CurrentCell.Column.Name; if (ControllerType.BoolButtons.Contains(buttonName)) @@ -398,7 +398,7 @@ private void TasView_ColumnClick(object sender, InputRoll.ColumnClickEventArgs e { // nifty taseditor logic bool allPressed = true; - foreach (var index in TasView.SelectedRows) + foreach (int index in TasView.SelectedRows) { if (index == CurrentTasMovie.FrameCount // last movie frame can't have input, but can be selected || !CurrentTasMovie.BoolIsPressed(index, buttonName)) @@ -412,7 +412,7 @@ private void TasView_ColumnClick(object sender, InputRoll.ColumnClickEventArgs e else { BoolPatterns[ControllerType.BoolButtons.IndexOf(buttonName)].Reset(); - foreach (var index in TasView.SelectedRows) + foreach (int index in TasView.SelectedRows) { CurrentTasMovie.SetBoolState(index, buttonName, BoolPatterns[ControllerType.BoolButtons.IndexOf(buttonName)].GetNextValue()); } @@ -480,7 +480,7 @@ public void UpdateAutoFire(string button, bool? isOn) // This is a sign of a deeper problem, but this fixes some basic functionality at least if (index < BoolPatterns.Length) { - AutoPatternBool p = BoolPatterns[index]; + var p = BoolPatterns[index]; InputManager.AutofireStickyXorAdapter.SetSticky(button, isOn.Value, p); } } @@ -505,16 +505,13 @@ public void UpdateAutoFire(string button, bool? isOn) // This is a sign of a deeper problem, but this fixes some basic functionality at least if (index < AxisPatterns.Length) { - AutoPatternAxis p = AxisPatterns[index]; + var p = AxisPatterns[index]; InputManager.AutofireStickyXorAdapter.SetAxis(button, value, p); } } } - private void TasView_ColumnReordered(object sender, InputRoll.ColumnReorderedEventArgs e) - { - CurrentTasMovie.FlagChanges(); - } + private void TasView_ColumnReordered(object sender, InputRoll.ColumnReorderedEventArgs e) => CurrentTasMovie.FlagChanges(); private void TasView_MouseEnter(object sender, EventArgs e) { @@ -569,7 +566,7 @@ private void TasView_MouseDown(object sender, MouseEventArgs e) // SuuperW: Exit axis editing mode, or re-enter mouse editing if (AxisEditingMode) { - if (ModifierKeys == Keys.Control || ModifierKeys == Keys.Shift) + if (ModifierKeys is Keys.Control or Keys.Shift) { _extraAxisRows.Clear(); _extraAxisRows.AddRange(TasView.SelectedRows); @@ -648,13 +645,13 @@ private void TasView_MouseDown(object sender, MouseEventArgs e) { if (!TasView.AnyRowsSelected) return; - var iFirstSelectedRow = TasView.FirstSelectedRowIndex; + int iFirstSelectedRow = TasView.FirstSelectedRowIndex; var (firstSel, lastSel) = frame <= iFirstSelectedRow ? (frame, iFirstSelectedRow) : (iFirstSelectedRow, frame); bool allPressed = true; - for (var i = firstSel; i <= lastSel; i++) + for (int i = firstSel; i <= lastSel; i++) { if (i == CurrentTasMovie.FrameCount // last movie frame can't have input, but can be selected || !CurrentTasMovie.BoolIsPressed(i, buttonName)) @@ -1000,7 +997,7 @@ private void TasView_PointedCellChanged(object sender, InputRoll.CellEventArgs e } else if (_startSelectionDrag) { - for (var i = startVal; i <= endVal; i++) + for (int i = startVal; i <= endVal; i++) { TasView.SelectRow(i, _selectionDragState); if (AxisEditingMode && (ModifierKeys == Keys.Control || ModifierKeys == Keys.Shift)) @@ -1163,7 +1160,7 @@ private void TasView_PointedCellChanged(object sender, InputRoll.CellEventArgs e for (int i = startVal; i <= endVal; i++) // Inclusive on both ends (drawing up or down) { - var setVal = _axisPaintState; + int setVal = _axisPaintState; if (_patternPaint) { if (CurrentTasMovie[frame].Lagged.HasValue && CurrentTasMovie[frame].Lagged.Value) @@ -1203,17 +1200,14 @@ private void TasView_MouseMove(object sender, MouseEventArgs e) return; } - var value = (_axisPaintState + increment).ConstrainWithin(ControllerType.Axes[_axisEditColumn].Range); + int value = (_axisPaintState + increment).ConstrainWithin(ControllerType.Axes[_axisEditColumn].Range); CurrentTasMovie.SetAxisState(_axisEditRow, _axisEditColumn, value); _axisTypedValue = value.ToString(); RefreshDialog(); } } - private void TasView_SelectedIndexChanged(object sender, EventArgs e) - { - SetSplicer(); - } + private void TasView_SelectedIndexChanged(object sender, EventArgs e) => SetSplicer(); public void AnalogIncrementByOne() { @@ -1304,7 +1298,7 @@ public void EditAnalogProgrammatically(KeyEventArgs e) value = rMin; _axisTypedValue = value.ToString(NumberFormatInfo.InvariantInfo); } - else if (e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9) + else if (e.KeyCode is >= Keys.D0 and <= Keys.D9) { if (curDigits >= maxDigits) { @@ -1313,7 +1307,7 @@ public void EditAnalogProgrammatically(KeyEventArgs e) _axisTypedValue += e.KeyCode - Keys.D0; } - else if (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9) + else if (e.KeyCode is >= Keys.NumPad0 and <= Keys.NumPad9) { if (curDigits >= maxDigits) { @@ -1322,7 +1316,7 @@ public void EditAnalogProgrammatically(KeyEventArgs e) _axisTypedValue += e.KeyCode - Keys.NumPad0; } - else if (e.KeyCode == Keys.OemMinus || e.KeyCode == Keys.Subtract) + else if (e.KeyCode is Keys.OemMinus or Keys.Subtract) { _axisTypedValue = _axisTypedValue.StartsWith('-') ? _axisTypedValue[1..] @@ -1336,7 +1330,7 @@ public void EditAnalogProgrammatically(KeyEventArgs e) } _axisTypedValue = _axisTypedValue[..^1]; - if (_axisTypedValue == "" || _axisTypedValue == "-") + if (_axisTypedValue is "" or "-") { value = 0f; } diff --git a/src/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.MenuItems.cs b/src/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.MenuItems.cs index c519f1d7f21..18c78f386bf 100644 --- a/src/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.MenuItems.cs +++ b/src/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.MenuItems.cs @@ -59,7 +59,7 @@ private void StartANewProjectFromSaveRamMenuItem_Click(object sender, EventArgs { if (AskSaveChanges()) { - var saveRam = SaveRamEmulator?.CloneSaveRam() ?? throw new Exception("No SaveRam"); + byte[] saveRam = SaveRamEmulator?.CloneSaveRam() ?? throw new Exception("No SaveRam"); GoToFrame(TasView.AnyRowsSelected ? TasView.FirstSelectedRowIndex : 0); var newProject = CurrentTasMovie.ConvertToSaveRamAnchoredMovie(saveRam); MainForm.PauseEmulator(); @@ -72,7 +72,7 @@ private void RecentSubMenu_DropDownOpened(object sender, EventArgs e) private void NewTasMenuItem_Click(object sender, EventArgs e) { - var prev = WantsToControlReboot; + bool prev = WantsToControlReboot; WantsToControlReboot = false; StartNewTasMovie(); WantsToControlReboot = prev; @@ -81,12 +81,12 @@ private void NewTasMenuItem_Click(object sender, EventArgs e) private void OpenTasMenuItem_Click(object sender, EventArgs e) { if (!AskSaveChanges()) return; - var filename = CurrentTasMovie.Filename; + string filename = CurrentTasMovie.Filename; if (string.IsNullOrWhiteSpace(filename) || filename == DefaultTasProjName()) { filename = ""; } - var result = this.ShowFileOpenDialog( + string result = this.ShowFileOpenDialog( filter: MoviesFSFilterSet, initDir: Config!.PathEntries.MovieAbsolutePath(), initFileName: filename); @@ -120,7 +120,7 @@ public bool LoadMovieFile(string filename, bool askToSave = true) MainForm.StartNewMovie(MovieSession.Get(filename), false); ConvertCurrentMovieToTasproj(); _initializing = false; - var success = StartNewMovieWrapper(CurrentTasMovie); + bool success = StartNewMovieWrapper(CurrentTasMovie); _engaged = true; WantsToControlReboot = true; SetUpColumns(); @@ -218,7 +218,7 @@ private void SaveSelectionToMacroMenuItem_Click(object sender, EventArgs e) if (file != null) { - var selectionStart = TasView.SelectionStartIndex!.Value; + int selectionStart = TasView.SelectionStartIndex!.Value; new MovieZone( Emulator, Tools, @@ -259,8 +259,8 @@ private void ToBk2MenuItem_Click(object sender, EventArgs e) _autosaveTimer.Stop(); if (Emulator is Emulation.Cores.Nintendo.SubNESHawk.SubNESHawk - || Emulator is Emulation.Cores.Nintendo.Gameboy.Gameboy - || Emulator is Emulation.Cores.Nintendo.SubGBHawk.SubGBHawk) + or Emulation.Cores.Nintendo.Gameboy.Gameboy + or Emulation.Cores.Nintendo.SubGBHawk.SubGBHawk) { DialogController.ShowMessageBox("This core requires emulation to be on the last frame when writing the movie, otherwise movie length will appear incorrect.\nTAStudio can't handle this, so Export BK2, play it to the end, and then Save Movie.", "Warning", EMsgBoxIcon.Warning); } @@ -270,7 +270,7 @@ private void ToBk2MenuItem_Click(object sender, EventArgs e) Cursor = Cursors.WaitCursor; Update(); string exportResult = " not exported."; - var file = new FileInfo(bk2.Filename); + FileInfo file = new(bk2.Filename); if (file.Exists) { var result = MainForm.DoWithTempMute(() => MessageBox.Show( @@ -395,7 +395,7 @@ private void SelectBetweenMarkersMenuItem_Click(object sender, EventArgs e) { if (TasView.Focused && TasView.AnyRowsSelected) { - var selectionEnd = TasView.SelectionEndIndex ?? 0; + int selectionEnd = TasView.SelectionEndIndex ?? 0; var prevMarker = CurrentTasMovie.Markers.PreviousOrCurrent(selectionEnd); var nextMarker = CurrentTasMovie.Markers.Next(selectionEnd); @@ -429,10 +429,10 @@ private void CopyMenuItem_Click(object sender, EventArgs e) if (TasView.Focused && TasView.AnyRowsSelected) { _tasClipboard.Clear(); - var list = TasView.SelectedRows.ToArray(); - var sb = new StringBuilder(); + int[] list = TasView.SelectedRows.ToArray(); + StringBuilder sb = new(); - foreach (var index in list) + foreach (int index in list) { var input = CurrentTasMovie.GetInputState(index); if (input == null) @@ -441,7 +441,7 @@ private void CopyMenuItem_Click(object sender, EventArgs e) } _tasClipboard.Add(new TasClipboardEntry(index, input)); - var logEntry = CurrentTasMovie.LogGeneratorInstance(input).GenerateLogEntry(); + string logEntry = CurrentTasMovie.LogGeneratorInstance(input).GenerateLogEntry(); sb.AppendLine(Settings.CopyIncludesFrameNo ? $"{FrameToStringPadded(index)} {logEntry}" : logEntry); } @@ -458,7 +458,7 @@ private void PasteMenuItem_Click(object sender, EventArgs e) // FCEUX Taseditor doesn't do this, but I think it is the expected behavior in editor programs // TODO: copy paste from PasteInsertMenuItem_Click! - IDataObject data = Clipboard.GetDataObject(); + var data = Clipboard.GetDataObject(); if (data != null && data.GetDataPresent(DataFormats.StringFormat)) { string input = (string)data.GetData(DataFormats.StringFormat); @@ -481,7 +481,7 @@ private void PasteMenuItem_Click(object sender, EventArgs e) _tasClipboard.Add(new TasClipboardEntry(i, line)); } - var rollbackFrame = CurrentTasMovie.CopyOverInput(TasView.SelectionStartIndex ?? 0, _tasClipboard.Select(static x => x.ControllerState)); + int rollbackFrame = CurrentTasMovie.CopyOverInput(TasView.SelectionStartIndex ?? 0, _tasClipboard.Select(static x => x.ControllerState)); if (rollbackFrame > 0) { GoToLastEmulatedFrameIfNecessary(rollbackFrame); @@ -500,7 +500,7 @@ private void PasteInsertMenuItem_Click(object sender, EventArgs e) if (TasView.Focused && TasView.AnyRowsSelected) { // copy paste from PasteMenuItem_Click! - IDataObject data = Clipboard.GetDataObject(); + var data = Clipboard.GetDataObject(); if (data != null && data.GetDataPresent(DataFormats.StringFormat)) { string input = (string)data.GetData(DataFormats.StringFormat); @@ -523,8 +523,8 @@ private void PasteInsertMenuItem_Click(object sender, EventArgs e) _tasClipboard.Add(new TasClipboardEntry(i, line)); } - var selectionStart = TasView.SelectionStartIndex; - var needsToRollback = selectionStart < Emulator.Frame; + int? selectionStart = TasView.SelectionStartIndex; + bool needsToRollback = selectionStart < Emulator.Frame; CurrentTasMovie.InsertInput(selectionStart ?? 0, _tasClipboard.Select(static x => x.ControllerState)); if (needsToRollback) { @@ -543,15 +543,15 @@ private void CutMenuItem_Click(object sender, EventArgs e) { if (TasView.Focused && TasView.AnyRowsSelected) { - var selectionStart = TasView.SelectionStartIndex; - var needsToRollback = selectionStart < Emulator.Frame; - var rollBackFrame = selectionStart ?? 0; + int? selectionStart = TasView.SelectionStartIndex; + bool needsToRollback = selectionStart < Emulator.Frame; + int rollBackFrame = selectionStart ?? 0; _tasClipboard.Clear(); - var list = TasView.SelectedRows.ToArray(); - var sb = new StringBuilder(); + int[] list = TasView.SelectedRows.ToArray(); + StringBuilder sb = new(); - foreach (var index in list) // copy of CopyMenuItem_Click() + foreach (int index in list) // copy of CopyMenuItem_Click() { var input = CurrentTasMovie.GetInputState(index); if (input == null) @@ -582,9 +582,9 @@ private void ClearFramesMenuItem_Click(object sender, EventArgs e) { if (TasView.Focused && TasView.AnyRowsSelected) { - var firstWithInput = FirstNonEmptySelectedFrame; + int? firstWithInput = FirstNonEmptySelectedFrame; bool needsToRollback = firstWithInput.HasValue && firstWithInput < Emulator.Frame; - var rollBackFrame = TasView.SelectionStartIndex ?? 0; + int rollBackFrame = TasView.SelectionStartIndex ?? 0; CurrentTasMovie.ChangeLog.BeginNewBatch($"Clear frames {TasView.SelectionStartIndex}-{TasView.SelectionEndIndex}"); foreach (int frame in TasView.SelectedRows) @@ -608,9 +608,9 @@ private void DeleteFramesMenuItem_Click(object sender, EventArgs e) { if (TasView.Focused && TasView.AnyRowsSelected) { - var selectionStart = TasView.SelectionStartIndex; - var needsToRollback = selectionStart < Emulator.Frame; - var rollBackFrame = selectionStart ?? 0; + int? selectionStart = TasView.SelectionStartIndex; + bool needsToRollback = selectionStart < Emulator.Frame; + int rollBackFrame = selectionStart ?? 0; if (rollBackFrame >= CurrentTasMovie.InputLogLength) { // Cannot delete non-existent frames @@ -631,14 +631,11 @@ private void DeleteFramesMenuItem_Click(object sender, EventArgs e) } } - private void CloneFramesMenuItem_Click(object sender, EventArgs e) - { - CloneFramesXTimes(1); - } + private void CloneFramesMenuItem_Click(object sender, EventArgs e) => CloneFramesXTimes(1); private void CloneFramesXTimesMenuItem_Click(object sender, EventArgs e) { - using var framesPrompt = new FramesPrompt("Clone # Times", "Insert times to clone:"); + using FramesPrompt framesPrompt = new("Clone # Times", "Insert times to clone:"); if (framesPrompt.ShowDialog().IsOk()) { CloneFramesXTimes(framesPrompt.Frames); @@ -652,10 +649,10 @@ private void CloneFramesXTimes(int timesToClone) if (TasView.Focused && TasView.AnyRowsSelected) { var framesToInsert = TasView.SelectedRows; - var insertionFrame = Math.Min((TasView.SelectionEndIndex ?? 0) + 1, CurrentTasMovie.InputLogLength); - var needsToRollback = TasView.SelectionStartIndex < Emulator.Frame; + int insertionFrame = Math.Min((TasView.SelectionEndIndex ?? 0) + 1, CurrentTasMovie.InputLogLength); + bool needsToRollback = TasView.SelectionStartIndex < Emulator.Frame; - var inputLog = framesToInsert + System.Collections.Generic.List inputLog = framesToInsert .Select(frame => CurrentTasMovie.GetInputLogEntry(frame)) .ToList(); @@ -676,9 +673,9 @@ private void InsertFrameMenuItem_Click(object sender, EventArgs e) { if (TasView.Focused && TasView.AnyRowsSelected) { - var selectionStart = TasView.SelectionStartIndex; - var insertionFrame = selectionStart ?? 0; - var needsToRollback = selectionStart < Emulator.Frame; + int? selectionStart = TasView.SelectionStartIndex; + int insertionFrame = selectionStart ?? 0; + bool needsToRollback = selectionStart < Emulator.Frame; CurrentTasMovie.InsertEmptyFrame(insertionFrame); @@ -696,8 +693,8 @@ private void InsertNumFramesMenuItem_Click(object sender, EventArgs e) { if (TasView.Focused && TasView.AnyRowsSelected) { - var insertionFrame = TasView.SelectionStartIndex ?? 0; - using var framesPrompt = new FramesPrompt(); + int insertionFrame = TasView.SelectionStartIndex ?? 0; + using FramesPrompt framesPrompt = new(); if (framesPrompt.ShowDialog().IsOk()) { InsertNumFrames(insertionFrame, framesPrompt.Frames); @@ -709,8 +706,8 @@ private void TruncateMenuItem_Click(object sender, EventArgs e) { if (TasView.Focused && TasView.AnyRowsSelected) { - var rollbackFrame = TasView.SelectionEndIndex ?? 0; - var needsToRollback = TasView.SelectionStartIndex < Emulator.Frame; + int rollbackFrame = TasView.SelectionEndIndex ?? 0; + bool needsToRollback = TasView.SelectionStartIndex < Emulator.Frame; CurrentTasMovie.Truncate(rollbackFrame); MarkerControl.MarkerInputRoll.TruncateSelection(CurrentTasMovie.Markers.Count - 1); @@ -726,26 +723,23 @@ private void TruncateMenuItem_Click(object sender, EventArgs e) private void SetMarkersMenuItem_Click(object sender, EventArgs e) { - var selectedRows = TasView.SelectedRows.ToList(); + System.Collections.Generic.List selectedRows = TasView.SelectedRows.ToList(); if (selectedRows.Count > 50) { - var result = DialogController.ShowMessageBox2("Are you sure you want to add more than 50 markers?", "Add markers", EMsgBoxIcon.Question, useOKCancel: true); + bool result = DialogController.ShowMessageBox2("Are you sure you want to add more than 50 markers?", "Add markers", EMsgBoxIcon.Question, useOKCancel: true); if (!result) { return; } } - foreach (var index in selectedRows) + foreach (int index in selectedRows) { MarkerControl.AddMarker(index, false); } } - private void SetMarkerWithTextMenuItem_Click(object sender, EventArgs e) - { - MarkerControl.AddMarker(TasView.AnyRowsSelected ? TasView.FirstSelectedRowIndex : 0, true); - } + private void SetMarkerWithTextMenuItem_Click(object sender, EventArgs e) => MarkerControl.AddMarker(TasView.AnyRowsSelected ? TasView.FirstSelectedRowIndex : 0, true); private void RemoveMarkersMenuItem_Click(object sender, EventArgs e) { @@ -786,11 +780,11 @@ private void StateHistoryIntegrityCheckMenuItem_Click(object sender, EventArgs e { if (DialogController.ShowMessageBox2($"Bad data between frames {lastState} and {Emulator.Frame}. Save the relevant state (raw data)?", "Integrity Failed!")) { - var result = this.ShowFileSaveDialog(initDir: Config!.PathEntries.ToolsAbsolutePath(), initFileName: "integrity.fresh"); + string result = this.ShowFileSaveDialog(initDir: Config!.PathEntries.ToolsAbsolutePath(), initFileName: "integrity.fresh"); if (result is not null) { File.WriteAllBytes(result, state); - var path = Path.ChangeExtension(result, ".greenzoned"); + string path = Path.ChangeExtension(result, ".greenzoned"); File.WriteAllBytes(path, greenZone); } } @@ -822,7 +816,7 @@ private void ConfigSubMenu_DropDownOpened(object sender, EventArgs e) private void SetMaxUndoLevelsMenuItem_Click(object sender, EventArgs e) { - using var prompt = new InputPrompt + using InputPrompt prompt = new() { TextInputType = InputPrompt.InputType.Unsigned, Message = "Number of Undo Levels to keep", @@ -851,7 +845,7 @@ private void SetMaxUndoLevelsMenuItem_Click(object sender, EventArgs e) private void SetBranchCellHoverIntervalMenuItem_Click(object sender, EventArgs e) { - using var prompt = new InputPrompt + using InputPrompt prompt = new() { TextInputType = InputPrompt.InputType.Unsigned, Message = "ScreenshotPopUp Delay", @@ -872,7 +866,7 @@ private void SetBranchCellHoverIntervalMenuItem_Click(object sender, EventArgs e private void SetSeekingCutoffIntervalMenuItem_Click(object sender, EventArgs e) { - using var prompt = new InputPrompt + using InputPrompt prompt = new() { TextInputType = InputPrompt.InputType.Unsigned, Message = "Seeking Cutoff Interval", @@ -891,14 +885,11 @@ private void SetSeekingCutoffIntervalMenuItem_Click(object sender, EventArgs e) } } - private void CopyIncludesFrameNoMenuItem_Click(object sender, EventArgs e) - { - Settings.CopyIncludesFrameNo ^= true; - } + private void CopyIncludesFrameNoMenuItem_Click(object sender, EventArgs e) => Settings.CopyIncludesFrameNo ^= true; private void SetAutosaveIntervalMenuItem_Click(object sender, EventArgs e) { - using var prompt = new InputPrompt + using InputPrompt prompt = new() { TextInputType = InputPrompt.InputType.Unsigned, Message = "Autosave Interval in seconds\nSet to 0 to disable", @@ -918,45 +909,21 @@ private void SetAutosaveIntervalMenuItem_Click(object sender, EventArgs e) } } - private void AutosaveAsBk2MenuItem_Click(object sender, EventArgs e) - { - Settings.AutosaveAsBk2 ^= true; - } + private void AutosaveAsBk2MenuItem_Click(object sender, EventArgs e) => Settings.AutosaveAsBk2 ^= true; - private void AutosaveAsBackupFileMenuItem_Click(object sender, EventArgs e) - { - Settings.AutosaveAsBackupFile ^= true; - } + private void AutosaveAsBackupFileMenuItem_Click(object sender, EventArgs e) => Settings.AutosaveAsBackupFile ^= true; - private void BackupPerFileSaveMenuItem_Click(object sender, EventArgs e) - { - Settings.BackupPerFileSave ^= true; - } + private void BackupPerFileSaveMenuItem_Click(object sender, EventArgs e) => Settings.BackupPerFileSave ^= true; - private void ApplyPatternToPaintedInputMenuItem_CheckedChanged(object sender, EventArgs e) - { - onlyOnAutoFireColumnsToolStripMenuItem.Enabled = applyPatternToPaintedInputToolStripMenuItem.Checked; - } + private void ApplyPatternToPaintedInputMenuItem_CheckedChanged(object sender, EventArgs e) => onlyOnAutoFireColumnsToolStripMenuItem.Enabled = applyPatternToPaintedInputToolStripMenuItem.Checked; - private void SingleClickAxisEditMenuItem_Click(object sender, EventArgs e) - { - Settings.SingleClickAxisEdit ^= true; - } + private void SingleClickAxisEditMenuItem_Click(object sender, EventArgs e) => Settings.SingleClickAxisEdit ^= true; - private void BindMarkersToInputMenuItem_Click(object sender, EventArgs e) - { - Settings.BindMarkersToInput = CurrentTasMovie.BindMarkersToInput = BindMarkersToInputMenuItem.Checked; - } + private void BindMarkersToInputMenuItem_Click(object sender, EventArgs e) => Settings.BindMarkersToInput = CurrentTasMovie.BindMarkersToInput = BindMarkersToInputMenuItem.Checked; - private void EmptyNewMarkerNotesMenuItem_Click(object sender, EventArgs e) - { - Settings.EmptyMarkers ^= true; - } + private void EmptyNewMarkerNotesMenuItem_Click(object sender, EventArgs e) => Settings.EmptyMarkers ^= true; - private void AutoPauseAtEndMenuItem_Click(object sender, EventArgs e) - { - Settings.AutoPause ^= true; - } + private void AutoPauseAtEndMenuItem_Click(object sender, EventArgs e) => Settings.AutoPause ^= true; private void AutoHoldMenuItem_CheckedChanged(object sender, EventArgs e) { @@ -1004,19 +971,13 @@ private void SetCustomsMenuItem_Click(object sender, EventArgs e) { // Exceptions in PatternsForm are not caught by the debugger, I have no idea why. // Exceptions in UndoForm are caught, which makes it weirder. - var pForm = new PatternsForm(this) { Owner = this }; + PatternsForm pForm = new(this) { Owner = this }; pForm.Show(); } - private void OldControlSchemeForBranchesMenuItem_Click(object sender, EventArgs e) - { - Settings.OldControlSchemeForBranches ^= true; - } + private void OldControlSchemeForBranchesMenuItem_Click(object sender, EventArgs e) => Settings.OldControlSchemeForBranches ^= true; - private void LoadBranchOnDoubleClickMenuItem_Click(object sender, EventArgs e) - { - Settings.LoadBranchOnDoubleClick ^= true; - } + private void LoadBranchOnDoubleClickMenuItem_Click(object sender, EventArgs e) => Settings.LoadBranchOnDoubleClick ^= true; private void HeaderMenuItem_Click(object sender, EventArgs e) { @@ -1042,7 +1003,7 @@ private void StateHistorySettingsMenuItem_Click(object sender, EventArgs e) private void CommentsMenuItem_Click(object sender, EventArgs e) { - var form = new EditCommentsForm(CurrentTasMovie, false); + EditCommentsForm form = new(CurrentTasMovie, false); form.Show(); } @@ -1065,10 +1026,7 @@ private void DefaultStateSettingsMenuItem_Click(object sender, EventArgs e) }.ShowDialog(); } - private void SettingsSubMenu_DropDownOpened(object sender, EventArgs e) - { - RotateMenuItem.ShortcutKeyDisplayString = TasView.RotateHotkeyStr; - } + private void SettingsSubMenu_DropDownOpened(object sender, EventArgs e) => RotateMenuItem.ShortcutKeyDisplayString = TasView.RotateHotkeyStr; private void HideLagFramesSubMenu_DropDownOpened(object sender, EventArgs e) { @@ -1125,35 +1083,17 @@ private void HideLagFramesX_Click(object sender, EventArgs e) RefreshDialog(); } - private void HideWasLagFramesMenuItem_Click(object sender, EventArgs e) - { - TasView.HideWasLagFrames ^= true; - } - - private void AlwaysScrollMenuItem_Click(object sender, EventArgs e) - { - TasView.AlwaysScroll = Settings.FollowCursorAlwaysScroll = alwaysScrollToolStripMenuItem.Checked; - } - - private void ScrollToViewMenuItem_Click(object sender, EventArgs e) - { - TasView.ScrollMethod = Settings.FollowCursorScrollMethod = "near"; - } - - private void ScrollToTopMenuItem_Click(object sender, EventArgs e) - { - TasView.ScrollMethod = Settings.FollowCursorScrollMethod = "top"; - } + private void HideWasLagFramesMenuItem_Click(object sender, EventArgs e) => TasView.HideWasLagFrames ^= true; - private void ScrollToBottomMenuItem_Click(object sender, EventArgs e) - { - TasView.ScrollMethod = Settings.FollowCursorScrollMethod = "bottom"; - } + private void AlwaysScrollMenuItem_Click(object sender, EventArgs e) => TasView.AlwaysScroll = Settings.FollowCursorAlwaysScroll = alwaysScrollToolStripMenuItem.Checked; - private void ScrollToCenterMenuItem_Click(object sender, EventArgs e) - { - TasView.ScrollMethod = Settings.FollowCursorScrollMethod = "center"; - } + private void ScrollToViewMenuItem_Click(object sender, EventArgs e) => TasView.ScrollMethod = Settings.FollowCursorScrollMethod = "near"; + + private void ScrollToTopMenuItem_Click(object sender, EventArgs e) => TasView.ScrollMethod = Settings.FollowCursorScrollMethod = "top"; + + private void ScrollToBottomMenuItem_Click(object sender, EventArgs e) => TasView.ScrollMethod = Settings.FollowCursorScrollMethod = "bottom"; + + private void ScrollToCenterMenuItem_Click(object sender, EventArgs e) => TasView.ScrollMethod = Settings.FollowCursorScrollMethod = "center"; private void DenoteStatesWithIconsToolStripMenuItem_Click(object sender, EventArgs e) { @@ -1181,13 +1121,13 @@ private void DenoteMarkersWithBGColorToolStripMenuItem_Click(object sender, Even private void ColorSettingsMenuItem_Click(object sender, EventArgs e) { - using var colorSettings = new TAStudioColorSettingsForm(Palette, p => Settings.Palette = p); + using TAStudioColorSettingsForm colorSettings = new(Palette, p => Settings.Palette = p); this.ShowDialogAsChild(colorSettings); } private void WheelScrollSpeedMenuItem_Click(object sender, EventArgs e) { - var inputPrompt = new InputPrompt + InputPrompt inputPrompt = new() { TextInputType = InputPrompt.InputType.Unsigned, Message = "Frames per tick:", @@ -1202,7 +1142,7 @@ private void SetUpToolStripColumns() { ColumnsSubMenu.DropDownItems.Clear(); - var columns = TasView.AllColumns + System.Collections.Generic.List columns = TasView.AllColumns .Where(static c => !string.IsNullOrWhiteSpace(c.Text) && c.Name is not "FrameColumn") .ToList(); @@ -1212,14 +1152,14 @@ private void SetUpToolStripColumns() int keyCount = columns.Count(c => c.Name.StartsWithOrdinal("Key ")); int keysMenusCount = (int)Math.Ceiling((double)keyCount / maxRows); - var keysMenus = new ToolStripMenuItem[keysMenusCount]; + ToolStripMenuItem[] keysMenus = new ToolStripMenuItem[keysMenusCount]; for (int i = 0; i < keysMenus.Length; i++) { keysMenus[i] = new ToolStripMenuItem(); } - var playerMenus = new ToolStripMenuItem[Emulator.ControllerDefinition.PlayerCount + 1]; + ToolStripMenuItem[] playerMenus = new ToolStripMenuItem[Emulator.ControllerDefinition.PlayerCount + 1]; playerMenus[0] = ColumnsSubMenu; for (int i = 1; i < playerMenus.Length; i++) @@ -1229,7 +1169,7 @@ private void SetUpToolStripColumns() foreach (var column in columns) { - var menuItem = new ToolStripMenuItem + ToolStripMenuItem menuItem = new() { Text = $"{column.Text} ({column.Name})", Checked = column.Visible, @@ -1298,7 +1238,7 @@ private void SetUpToolStripColumns() if (keysMenus.Length > 0) { - var item = new ToolStripMenuItem("Show Keys") + ToolStripMenuItem item = new("Show Keys") { CheckOnClick = true, Checked = false @@ -1327,13 +1267,13 @@ private void SetUpToolStripColumns() { if (playerMenus[i].HasDropDownItems) { - var item = new ToolStripMenuItem($"Show Player {i}") + ToolStripMenuItem item = new($"Show Player {i}") { CheckOnClick = true, Checked = playerMenus[i].DropDownItems.OfType().Any(mi => mi.Checked) }; - ToolStripMenuItem dummyObject = playerMenus[i]; + var dummyObject = playerMenus[i]; item.CheckedChanged += (o, ev) => { // TODO: preserve underlying button checked state and make this a master visibility control @@ -1355,6 +1295,7 @@ private void SetUpToolStripColumns() TasView.AllColumns.ColumnsChanged(); } + #pragma warning disable IDE0051 // ReSharper disable once UnusedMember.Local [RestoreDefaults] private void RestoreDefaults() @@ -1367,6 +1308,7 @@ private void RestoreDefaults() MainVertialSplit.SplitterDistance = _defaultMainSplitDistance; BranchesMarkersSplit.SplitterDistance = _defaultBranchMarkerSplitDistance; } + #pragma warning restore IDE0051 private void RightClickMenu_Opened(object sender, EventArgs e) { @@ -1388,7 +1330,7 @@ private void RightClickMenu_Opened(object sender, EventArgs e) (Clipboard.GetDataObject()?.GetDataPresent(DataFormats.StringFormat) ?? false) && TasView.AnyRowsSelected; - var selectionIsSingleRow = TasView.SelectedRows.CountIsExactly(1); + bool selectionIsSingleRow = TasView.SelectedRows.CountIsExactly(1); StartNewProjectFromNowMenuItem.Visible = selectionIsSingleRow && TasView.IsRowSelected(Emulator.Frame) @@ -1418,19 +1360,10 @@ private void CancelSeekContextMenuItem_Click(object sender, EventArgs e) TasView.Refresh(); } - private void BranchContextMenuItem_Click(object sender, EventArgs e) - { - BookMarkControl.Branch(); - } + private void BranchContextMenuItem_Click(object sender, EventArgs e) => BookMarkControl.Branch(); - private void TASEditorManualOnlineMenuItem_Click(object sender, EventArgs e) - { - System.Diagnostics.Process.Start("http://www.fceux.com/web/help/taseditor/"); - } + private void TASEditorManualOnlineMenuItem_Click(object sender, EventArgs e) => System.Diagnostics.Process.Start("http://www.fceux.com/web/help/taseditor/"); - private void ForumThreadMenuItem_Click(object sender, EventArgs e) - { - System.Diagnostics.Process.Start("https://tasvideos.org/Forum/Topics/13505"); - } + private void ForumThreadMenuItem_Click(object sender, EventArgs e) => System.Diagnostics.Process.Start("https://tasvideos.org/Forum/Topics/13505"); } } diff --git a/src/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.Navigation.cs b/src/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.Navigation.cs index ac0cf5d8a8d..69315d72a15 100644 --- a/src/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.Navigation.cs +++ b/src/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.Navigation.cs @@ -80,7 +80,7 @@ public void GoToPreviousMarker() if (Emulator.Frame > 0) { var prevMarker = CurrentTasMovie.Markers.Previous(Emulator.Frame); - var prev = prevMarker?.Frame ?? 0; + int prev = prevMarker?.Frame ?? 0; GoToFrame(prev); } } @@ -88,7 +88,7 @@ public void GoToPreviousMarker() public void GoToNextMarker() { var nextMarker = CurrentTasMovie.Markers.Next(Emulator.Frame); - var next = nextMarker?.Frame ?? CurrentTasMovie.InputLogLength - 1; + int next = nextMarker?.Frame ?? CurrentTasMovie.InputLogLength - 1; GoToFrame(next); } diff --git a/src/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.cs b/src/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.cs index 1463aaab5d6..5cdbfd6e7c1 100644 --- a/src/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.cs +++ b/src/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.cs @@ -32,7 +32,7 @@ public static Icon ToolIcon public bool IsInMenuLoop { get; private set; } - private readonly List _tasClipboard = new List(); + private readonly List _tasClipboard = new(); private const string CursorColumnName = "CursorColumn"; private const string FrameColumnName = "FrameColumn"; private MovieEndAction _originalEndAction; // The movie end behavior selected by the user (that is overridden by TAStudio) @@ -229,12 +229,12 @@ private bool Engage() // Start Scenario 1: A regular movie is active if (MovieSession.Movie.IsActive() && MovieSession.Movie is not ITasMovie) { - var changesString = "Would you like to save the current movie before closing it?"; + string changesString = "Would you like to save the current movie before closing it?"; if (MovieSession.Movie.Changes) { changesString = "The current movie has unsaved changes. Would you like to save before closing it?"; } - var result = DialogController.ShowMessageBox3( + bool? result = DialogController.ShowMessageBox3( "TAStudio will create a new project file from the current movie.\n\n" + changesString, "Convert movie", EMsgBoxIcon.Question); @@ -507,8 +507,8 @@ private int? FirstNonEmptySelectedFrame get { var lg = CurrentTasMovie.LogGeneratorInstance(MovieSession.MovieController); - var empty = lg.EmptyEntry; - foreach (var row in TasView.SelectedRows) + string empty = lg.EmptyEntry; + foreach (int row in TasView.SelectedRows) { if (CurrentTasMovie[row].LogEntry != empty) { @@ -538,7 +538,7 @@ private bool LoadFile(FileInfo file, bool startsFromSavestate = false, int gotoF } _engaged = false; - var newMovie = (ITasMovie)MovieSession.Get(file.FullName); + ITasMovie newMovie = (ITasMovie)MovieSession.Get(file.FullName); newMovie.BindMarkersToInput = Settings.BindMarkersToInput; newMovie.GreenzoneInvalidated = GreenzoneInvalidated; @@ -595,8 +595,8 @@ private void StartNewTasMovie() if (Game.IsNullInstance()) throw new InvalidOperationException("how is TAStudio open with no game loaded? please report this including as much detail as possible"); - var filename = DefaultTasProjName(); // TODO don't do this, take over any mainform actions that can crash without a filename - var tasMovie = (ITasMovie)MovieSession.Get(filename); + string filename = DefaultTasProjName(); // TODO don't do this, take over any mainform actions that can crash without a filename + ITasMovie tasMovie = (ITasMovie)MovieSession.Get(filename); tasMovie.BindMarkersToInput = Settings.BindMarkersToInput; @@ -633,7 +633,7 @@ private bool HandleMovieLoadStuff(ITasMovie movie) { WantsToControlStopMovie = false; WantsToControlReboot = false; - var result = StartNewMovieWrapper(movie); + bool result = StartNewMovieWrapper(movie); if (!result) { @@ -683,7 +683,7 @@ private void DummyLoadProject(string path) private void LoadFileWithFallback(string path) { - var result = LoadFile(new FileInfo(path)); + bool result = LoadFile(new FileInfo(path)); if (!result) { TasView.AllColumns.Clear(); @@ -700,22 +700,16 @@ private void DummyLoadMacro(string path) return; } - var loadZone = new MovieZone(path, MainForm, Emulator, MovieSession, Tools) + MovieZone loadZone = new(path, MainForm, Emulator, MovieSession, Tools) { Start = TasView.SelectionStartIndex!.Value, }; loadZone.PlaceZone(CurrentTasMovie, Config); } - private void TastudioPlayMode() - { - TasPlaybackBox.RecordingMode = false; - } + private void TastudioPlayMode() => TasPlaybackBox.RecordingMode = false; - private void TastudioRecordMode() - { - TasPlaybackBox.RecordingMode = true; - } + private void TastudioRecordMode() => TasPlaybackBox.RecordingMode = true; private void TastudioStopMovie() { @@ -786,7 +780,7 @@ private void SaveAsTas() MainForm.DoWithTempMute(() => { ClearLeftMouseStates(); - var filename = CurrentTasMovie.Filename; + string filename = CurrentTasMovie.Filename; if (string.IsNullOrWhiteSpace(filename) || filename == DefaultTasProjName()) { filename = SuggestedTasProjName(); @@ -907,10 +901,7 @@ public void DoAutoRestore() /// Get a savestate prior to the previous frame so code following the call can frame advance and have a framebuffer. /// If frame is 0, return the initial state. /// - private KeyValuePair GetPriorStateForFramebuffer(int frame) - { - return CurrentTasMovie.TasStateManager.GetStateClosestToFrame(frame > 0 ? frame - 1 : 0); - } + private KeyValuePair GetPriorStateForFramebuffer(int frame) => CurrentTasMovie.TasStateManager.GetStateClosestToFrame(frame > 0 ? frame - 1 : 0); private void StartAtNearestFrameAndEmulate(int frame, bool fromLua, bool fromRewinding) { @@ -993,16 +984,13 @@ private void UpdateTools() Tools.UpdateToolsAfter(); } - public void TogglePause() - { - MainForm.TogglePause(); - } + public void TogglePause() => MainForm.TogglePause(); private void SetSplicer() { // TODO: columns selected? - var selectedRowCount = TasView.SelectedRows.Count(); - var temp = $"Selected: {selectedRowCount} {(selectedRowCount == 1 ? "frame" : "frames")}, States: {CurrentTasMovie.TasStateManager.Count}"; + int selectedRowCount = TasView.SelectedRows.Count(); + string temp = $"Selected: {selectedRowCount} {(selectedRowCount == 1 ? "frame" : "frames")}, States: {CurrentTasMovie.TasStateManager.Count}"; if (_tasClipboard.Any()) temp += $", Clipboard: {_tasClipboard.Count} {(_tasClipboard.Count == 1 ? "frame" : "frames")}"; SplicerStatusLabel.Text = temp; } @@ -1035,7 +1023,7 @@ public void InsertNumFrames(int insertionFrame, int numberOfFrames) { if (insertionFrame <= CurrentTasMovie.InputLogLength) { - var needsToRollback = TasView.SelectionStartIndex < Emulator.Frame; + bool needsToRollback = TasView.SelectionStartIndex < Emulator.Frame; CurrentTasMovie.InsertEmptyFrame(insertionFrame, numberOfFrames); @@ -1059,7 +1047,7 @@ public void DeleteFrames(int beginningFrame, int numberOfFrames) CurrentTasMovie.RemoveFrames(framesToRemove); SetSplicer(); - var needsToRollback = beginningFrame < Emulator.Frame; + bool needsToRollback = beginningFrame < Emulator.Frame; if (needsToRollback) { GoToLastEmulatedFrameIfNecessary(beginningFrame); @@ -1076,7 +1064,7 @@ public void ClearFrames(int beginningFrame, int numberOfFrames) { if (beginningFrame < CurrentTasMovie.InputLogLength) { - var needsToRollback = TasView.SelectionStartIndex < Emulator.Frame; + bool needsToRollback = TasView.SelectionStartIndex < Emulator.Frame; int last = Math.Min(beginningFrame + numberOfFrames, CurrentTasMovie.InputLogLength); for (int i = beginningFrame; i < last; i++) { @@ -1122,30 +1110,23 @@ private void Tastudio_Closing(object sender, FormClosingEventArgs e) /// /// This method is called every time the Changes property is toggled on a instance. /// - private void TasMovie_OnPropertyChanged(object sender, PropertyChangedEventArgs e) - { - UpdateWindowTitle(); - } + private void TasMovie_OnPropertyChanged(object sender, PropertyChangedEventArgs e) => UpdateWindowTitle(); private void TAStudio_DragDrop(object sender, DragEventArgs e) { // TODO: Maybe this should call Mainform's DragDrop method, // since that can file types that are not movies, // and it can process multiple files sequentially - var filePaths = (string[])e.Data.GetData(DataFormats.FileDrop); + string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop); LoadMovieFile(filePaths[0]); } - private void TAStudio_MouseLeave(object sender, EventArgs e) - { - DoTriggeredAutoRestoreIfNeeded(); - } + private void TAStudio_MouseLeave(object sender, EventArgs e) => DoTriggeredAutoRestoreIfNeeded(); protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { - if (keyData == Keys.Tab - || keyData == (Keys.Shift | Keys.Tab) - || keyData == Keys.Space) + if (keyData is Keys.Tab + or (Keys.Shift | Keys.Tab) or Keys.Space) { return true; } @@ -1193,15 +1174,9 @@ private bool AutoAdjustInput() return false; } - private void MainVerticalSplit_SplitterMoved(object sender, SplitterEventArgs e) - { - Settings.MainVerticalSplitDistance = MainVertialSplit.SplitterDistance; - } + private void MainVerticalSplit_SplitterMoved(object sender, SplitterEventArgs e) => Settings.MainVerticalSplitDistance = MainVertialSplit.SplitterDistance; - private void BranchesMarkersSplit_SplitterMoved(object sender, SplitterEventArgs e) - { - Settings.BranchMarkerSplitDistance = BranchesMarkersSplit.SplitterDistance; - } + private void BranchesMarkersSplit_SplitterMoved(object sender, SplitterEventArgs e) => Settings.BranchMarkerSplitDistance = BranchesMarkersSplit.SplitterDistance; private void TasView_CellDropped(object sender, InputRoll.CellEventArgs e) { @@ -1209,32 +1184,23 @@ private void TasView_CellDropped(object sender, InputRoll.CellEventArgs e) { var currentMarker = CurrentTasMovie.Markers.Single(m => m.Frame == e.OldCell.RowIndex.Value); int newFrame = e.NewCell.RowIndex.Value; - var newMarker = new TasMovieMarker(newFrame, currentMarker.Message); + TasMovieMarker newMarker = new(newFrame, currentMarker.Message); CurrentTasMovie.Markers.Remove(currentMarker); CurrentTasMovie.Markers.Add(newMarker); RefreshDialog(); } } - private void TASMenu_MenuActivate(object sender, EventArgs e) - { - IsInMenuLoop = true; - } + private void TASMenu_MenuActivate(object sender, EventArgs e) => IsInMenuLoop = true; - private void TASMenu_MenuDeactivate(object sender, EventArgs e) - { - IsInMenuLoop = false; - } + private void TASMenu_MenuDeactivate(object sender, EventArgs e) => IsInMenuLoop = false; // Stupid designer - protected void DragEnterWrapper(object sender, DragEventArgs e) - { - GenericDragEnter(sender, e); - } + protected void DragEnterWrapper(object sender, DragEventArgs e) => GenericDragEnter(sender, e); private void SetFontMenuItem_Click(object sender, EventArgs e) { - using var fontDialog = new FontDialog + using FontDialog fontDialog = new() { ShowColor = false, Font = TasView.Font diff --git a/src/BizHawk.Client.EmuHawk/tools/TAStudio/UndoHistoryForm.cs b/src/BizHawk.Client.EmuHawk/tools/TAStudio/UndoHistoryForm.cs index bf41f39b6ba..2c933654224 100644 --- a/src/BizHawk.Client.EmuHawk/tools/TAStudio/UndoHistoryForm.cs +++ b/src/BizHawk.Client.EmuHawk/tools/TAStudio/UndoHistoryForm.cs @@ -105,10 +105,7 @@ private void UndoToHere(int index) _tastudio.RefreshDialog(); } - private void HistoryView_DoubleClick(object sender, EventArgs e) - { - UndoToHere(SelectedItem); - } + private void HistoryView_DoubleClick(object sender, EventArgs e) => UndoToHere(SelectedItem); private void HistoryView_MouseUp(object sender, MouseEventArgs e) { @@ -128,15 +125,9 @@ private void HistoryView_MouseUp(object sender, MouseEventArgs e) // Hacky way to select a row by clicking the names row private int _hackSelect = -1; - private void HistoryView_MouseDown(object sender, MouseEventArgs e) - { - _hackSelect = SelectedItem; - } + private void HistoryView_MouseDown(object sender, MouseEventArgs e) => _hackSelect = SelectedItem; - private void UndoHereMenuItem_Click(object sender, EventArgs e) - { - UndoToHere(SelectedItem); - } + private void UndoHereMenuItem_Click(object sender, EventArgs e) => UndoToHere(SelectedItem); private void RedoHereMenuItem_Click(object sender, EventArgs e) { @@ -166,9 +157,6 @@ private void ClearHistoryToHereMenuItem_Click(object sender, EventArgs e) UpdateValues(); } - private void MaxStepsNum_ValueChanged(object sender, EventArgs e) - { - Log.MaxSteps = (int)MaxStepsNum.Value; - } + private void MaxStepsNum_ValueChanged(object sender, EventArgs e) => Log.MaxSteps = (int)MaxStepsNum.Value; } } diff --git a/src/BizHawk.Client.EmuHawk/tools/TI83/TI83KeyPad.cs b/src/BizHawk.Client.EmuHawk/tools/TI83/TI83KeyPad.cs index abde7acedd0..09b7e940c71 100644 --- a/src/BizHawk.Client.EmuHawk/tools/TI83/TI83KeyPad.cs +++ b/src/BizHawk.Client.EmuHawk/tools/TI83/TI83KeyPad.cs @@ -42,10 +42,7 @@ private void TI83KeyPad_Load(object sender, EventArgs e) } } - private void KeyClick(string name) - { - InputManager.ClickyVirtualPadController.Click(name); - } + private void KeyClick(string name) => InputManager.ClickyVirtualPadController.Click(name); private void SetToolTips() { @@ -103,15 +100,9 @@ private void SetToolTips() KeyPadToolTips.SetToolTip(SinButton, mappings["SIN"]); } - private void StopToolTips() - { - KeyPadToolTips.RemoveAll(); - } + private void StopToolTips() => KeyPadToolTips.RemoveAll(); - private void OptionsSubMenu_DropDownOpened(object sender, EventArgs e) - { - ShowHotkeysMenuItem.Checked = TI83ToolTips; - } + private void OptionsSubMenu_DropDownOpened(object sender, EventArgs e) => ShowHotkeysMenuItem.Checked = TI83ToolTips; private void ShowHotkeysMenuItem_Click(object sender, EventArgs e) { diff --git a/src/BizHawk.Client.EmuHawk/tools/ToolBox.cs b/src/BizHawk.Client.EmuHawk/tools/ToolBox.cs index ebdb1452023..5fbebacbdc5 100644 --- a/src/BizHawk.Client.EmuHawk/tools/ToolBox.cs +++ b/src/BizHawk.Client.EmuHawk/tools/ToolBox.cs @@ -77,7 +77,7 @@ private void SetTools() Image = tsi.Image ?? IconMissingIcon.Value, Text = tsi.Text, }; - var info = (ExternalToolManager.MenuItemInfo) tsi.Tag; + ExternalToolManager.MenuItemInfo info = (ExternalToolManager.MenuItemInfo) tsi.Tag; tsb.Click += (_, _) => info.TryLoad(); ToolBoxStrip.Items.Add(tsb); } @@ -85,7 +85,7 @@ private void SetTools() private void SetSize() { - var rows = (int)Math.Ceiling(ToolBoxItems.Count() / 4.0); + int rows = (int)Math.Ceiling(ToolBoxItems.Count() / 4.0); Height = 30 + (rows * 30); } diff --git a/src/BizHawk.Client.EmuHawk/tools/ToolFormBase.cs b/src/BizHawk.Client.EmuHawk/tools/ToolFormBase.cs index 5916ae9ec75..0e75d063c30 100644 --- a/src/BizHawk.Client.EmuHawk/tools/ToolFormBase.cs +++ b/src/BizHawk.Client.EmuHawk/tools/ToolFormBase.cs @@ -81,7 +81,7 @@ protected virtual void FastUpdateAfter() { } public FileInfo OpenFileDialog(string currentFile, string path, FilesystemFilterSet filterSet) { Directory.CreateDirectory(path); - var result = this.ShowFileOpenDialog( + string result = this.ShowFileOpenDialog( discardCWDChange: true, filter: filterSet, initDir: path, @@ -94,7 +94,7 @@ public FileInfo OpenFileDialog(string currentFile, string path, FilesystemFilter public static FileInfo SaveFileDialog(string currentFile, string path, FilesystemFilterSet filterSet, IDialogParent parent) { Directory.CreateDirectory(path); - var result = parent.ShowFileSaveDialog( + string result = parent.ShowFileSaveDialog( discardCWDChange: true, filter: filterSet, initDir: path, @@ -121,10 +121,7 @@ public void ViewInHexEditor(MemoryDomain domain, IEnumerable addresses, Wa Tools.HexEditor.SetToAddresses(addresses, domain, size); } - protected void GenericDragEnter(object sender, DragEventArgs e) - { - e.Set(DragDropEffects.Copy); - } + protected void GenericDragEnter(object sender, DragEventArgs e) => e.Set(DragDropEffects.Copy); protected override void OnLoad(EventArgs e) { diff --git a/src/BizHawk.Client.EmuHawk/tools/ToolManager.cs b/src/BizHawk.Client.EmuHawk/tools/ToolManager.cs index b2c55fed729..a9e34a97a96 100644 --- a/src/BizHawk.Client.EmuHawk/tools/ToolManager.cs +++ b/src/BizHawk.Client.EmuHawk/tools/ToolManager.cs @@ -32,7 +32,7 @@ public class ToolManager // 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 // Also a UsesRam, and similar method - private readonly List _tools = new List(); + private readonly List _tools = new(); private IExternalApiProvider ApiProvider { @@ -126,7 +126,7 @@ public T Load(bool focus = true, string toolPath = "") if (newTool is Form form) form.Owner = _owner; if (!ServiceInjector.UpdateServices(_emulator.ServiceProvider, newTool)) return null; //TODO pass `true` for `mayCache` when from EmuHawk assembly SetBaseProperties(newTool); - var toolTypeName = typeof(T).FullName!; + string toolTypeName = typeof(T).FullName!; // auto settings if (newTool is IToolFormAutoConfig autoConfigTool) { @@ -162,7 +162,7 @@ public IExternalToolForm LoadExternalToolForm(string toolPath, string customForm _tools.Remove(existingTool); } - var newTool = (IExternalToolForm) CreateInstance(typeof(IExternalToolForm), toolPath, customFormTypeName, skipExtToolWarning: skipExtToolWarning); + IExternalToolForm newTool = (IExternalToolForm) CreateInstance(typeof(IExternalToolForm), toolPath, customFormTypeName, skipExtToolWarning: skipExtToolWarning); if (newTool == null) return null; if (newTool is Form form) form.Owner = _owner; if (!(ServiceInjector.UpdateServices(_emulator.ServiceProvider, newTool) && ApiInjector.UpdateApis(ApiProvider, newTool))) return null; @@ -195,7 +195,7 @@ public void AutoLoad() var typeNames = genericSettings.Concat(customSettings); - foreach (var typename in typeNames) + foreach (string typename in typeNames) { // this type resolution might not be sufficient. more investigation is needed Type t = Type.GetType(typename); @@ -216,7 +216,7 @@ public void AutoLoad() private void RefreshSettings(Form form, ToolStripItemCollection menu, ToolDialogSettings settings, int idx) { ((ToolStripMenuItem)menu[idx + 0]).Checked = settings.SaveWindowPosition; - var stayOnTopItem = (ToolStripMenuItem)menu[idx + 1]; + ToolStripMenuItem stayOnTopItem = (ToolStripMenuItem)menu[idx + 1]; stayOnTopItem.Checked = settings.TopMost; if (OSTailoredCode.IsUnixHost) { @@ -242,7 +242,7 @@ private void AddCloseButton(ToolStripMenuItem subMenu, Form form) subMenu.DropDownItems.Add(new ToolStripSeparatorEx()); } - var closeMenuItem = new ToolStripMenuItem + ToolStripMenuItem closeMenuItem = new() { Name = "CloseBtn", Text = "&Close", @@ -255,7 +255,7 @@ private void AddCloseButton(ToolStripMenuItem subMenu, Form form) private void AttachSettingHooks(IToolFormAutoConfig tool, ToolDialogSettings settings) { - var form = (Form)tool; + Form form = (Form)tool; ToolStripItemCollection dest = null; var oldSize = form.Size; // this should be the right time to grab this size foreach (Control c in form.Controls) @@ -277,7 +277,7 @@ private void AttachSettingHooks(IToolFormAutoConfig tool, ToolDialogSettings set if (dest == null) { - var submenu = new ToolStripMenuItem("&Settings"); + ToolStripMenuItem submenu = new("&Settings"); ms.Items.Add(submenu); dest = submenu.DropDownItems; } @@ -309,7 +309,7 @@ private void AttachSettingHooks(IToolFormAutoConfig tool, ToolDialogSettings set if (settings.UseWindowSize) { - if (form.FormBorderStyle == FormBorderStyle.Sizable || form.FormBorderStyle == FormBorderStyle.SizableToolWindow) + if (form.FormBorderStyle is FormBorderStyle.Sizable or FormBorderStyle.SizableToolWindow) { form.Size = settings.WindowSize; } @@ -373,15 +373,12 @@ private void AttachSettingHooks(IToolFormAutoConfig tool, ToolDialogSettings set }; } - private static bool HasCustomConfig(IToolForm tool) - { - return tool.GetType().GetPropertiesWithAttrib(typeof(ConfigPersistAttribute)).Any(); - } + private static bool HasCustomConfig(IToolForm tool) => tool.GetType().GetPropertiesWithAttrib(typeof(ConfigPersistAttribute)).Any(); private static void InstallCustomConfig(IToolForm tool, Dictionary data) { - Type type = tool.GetType(); - var props = type.GetPropertiesWithAttrib(typeof(ConfigPersistAttribute)).ToList(); + var type = tool.GetType(); + List props = type.GetPropertiesWithAttrib(typeof(ConfigPersistAttribute)).ToList(); if (props.Count == 0) { return; @@ -389,7 +386,7 @@ private static void InstallCustomConfig(IToolForm tool, Dictionary /// Type of tool to get - public IToolForm Get() where T : class, IToolForm - { - return Load(false); - } + public IToolForm Get() where T : class, IToolForm => Load(false); /// /// returns the instance of , regardless of whether it's loaded,
@@ -524,7 +518,7 @@ private static void CaptureIconAndName(object tool, Type toolType) { if (IconAndNameCache.TryGetValue(toolType, out var tuple)) return tuple; Image/*?*/ icon = null; - var name = toolType.GetCustomAttribute()?.DisplayName; //TODO codegen ToolIcon and WindowTitleStatic from [Tool] or some new attribute -- Bitmap..ctor(Type, string) + string name = toolType.GetCustomAttribute()?.DisplayName; //TODO codegen ToolIcon and WindowTitleStatic from [Tool] or some new attribute -- Bitmap..ctor(Type, string) var instance = LazyGet(toolType); if (instance is not null) { @@ -564,7 +558,7 @@ public void Restart(Config config, IEmulator emulator, IGameInfo game) _owner.CheatList.NewList(GenerateDefaultCheatFilename(), autosave: true); } - var unavailable = new List(); + List unavailable = new(); foreach (var tool in _tools) { @@ -647,10 +641,7 @@ public void Close() /// Path .dll for an external tool /// New instance of an IToolForm private IToolForm CreateInstance(string dllPath) - where T : IToolForm - { - return CreateInstance(typeof(T), dllPath); - } + where T : IToolForm => CreateInstance(typeof(T), dllPath); /// /// Create a new instance of an IToolForm and return it @@ -761,7 +752,7 @@ public bool IsAvailable(Type tool) if (typeof(IExternalToolForm).IsAssignableFrom(tool) && !ApiInjector.IsAvailable(ApiProvider, tool)) return false; if (!PossibleToolTypeNames.Contains(tool.AssemblyQualifiedName) && !_extToolManager.PossibleExtToolTypeNames.Contains(tool.AssemblyQualifiedName)) return false; // not a tool - ToolAttribute attr = tool.GetCustomAttributes(false).OfType().SingleOrDefault(); + var attr = tool.GetCustomAttributes(false).OfType().SingleOrDefault(); if (attr == null) { return true; // no ToolAttribute on given type -> assumed all supported @@ -777,7 +768,7 @@ public bool IsAvailable(Type tool) private T GetTool() where T : class, IToolForm, new() { - T tool = _tools.OfType().FirstOrDefault(); + var tool = _tools.OfType().FirstOrDefault(); if (tool != null) { if (tool.IsActive) @@ -832,9 +823,9 @@ public void LoadRamWatch(bool loadDialog) public string GenerateDefaultCheatFilename() { - var path = _config.PathEntries.CheatsAbsolutePath(_game.System); + string path = _config.PathEntries.CheatsAbsolutePath(_game.System); - var f = new FileInfo(path); + FileInfo f = new(path); if (f.Directory != null && f.Directory.Exists == false) { f.Directory.Create(); diff --git a/src/BizHawk.Client.EmuHawk/tools/TraceLogger.cs b/src/BizHawk.Client.EmuHawk/tools/TraceLogger.cs index bdb8edf4d58..b2e3f75f3f6 100644 --- a/src/BizHawk.Client.EmuHawk/tools/TraceLogger.cs +++ b/src/BizHawk.Client.EmuHawk/tools/TraceLogger.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; @@ -33,6 +33,7 @@ private ITraceable Tracer [ConfigPersist] private int FileSizeCap { get; set; } + #pragma warning disable IDE0051 [ConfigPersist] private List Columns { @@ -48,6 +49,7 @@ private List Columns TraceView.AllColumns.ColumnsChanged(); } } + #pragma warning restore IDE0051 private FileInfo _logFile; private FileInfo LogFile @@ -61,7 +63,7 @@ private FileInfo LogFile } } - private readonly List _instructions = new List(); + private readonly List _instructions = new(); private StreamWriter _streamWriter; private bool _splitFile; private string _baseName; @@ -140,10 +142,7 @@ private void TraceLogger_Load(object sender, EventArgs e) private class CallbackSink : ITraceSink { - public void Put(TraceInfo info) - { - Putter(info); - } + public void Put(TraceInfo info) => Putter(info); public Action Putter { get; set; } } @@ -192,7 +191,7 @@ public override void UpdateValues(ToolFormUpdateType type) Putter = (info) => { //no padding supported. core should be doing this! - var data = $"{info.Disassembly} {info.RegisterInfo}"; + string data = $"{info.Disassembly} {info.RegisterInfo}"; _streamWriter.WriteLine(data); _currentSize += (ulong)data.Length; if (_splitFile) @@ -229,7 +228,7 @@ private void DumpToDisk() foreach (var instruction in _instructions) { //no padding supported. core should be doing this! - var data = $"{instruction.Disassembly} {instruction.RegisterInfo}"; + string data = $"{instruction.Disassembly} {instruction.RegisterInfo}"; _streamWriter.WriteLine(data); _currentSize += (ulong)data.Length; if (_splitFile) @@ -237,6 +236,7 @@ private void DumpToDisk() } } + #pragma warning disable IDE0051 private void LogToWindow() { if (_instructions.Count >= MaxLines) @@ -245,6 +245,7 @@ private void LogToWindow() } TraceView.RowCount = _instructions.Count; } + #pragma warning restore IDE0051 private void SetTracerBoxTitle() { @@ -305,7 +306,7 @@ private FileInfo GetFileFromUser() initFileName = Path.GetFileNameWithoutExtension(LogFile.FullName); initDir = Config!.PathEntries.LogAbsolutePath(); } - var result = this.ShowFileSaveDialog( + string result = this.ShowFileSaveDialog( discardCWDChange: true, filter: LogFilesFSFilterSet, initDir: initDir, @@ -338,7 +339,7 @@ private void CopyMenuItem_Click(object sender, EventArgs e) private void SelectAllMenuItem_Click(object sender, EventArgs e) { - for (var i = 0; i < _instructions.Count; i++) + for (int i = 0; i < _instructions.Count; i++) { TraceView.SelectRow(i, true); } @@ -346,7 +347,7 @@ private void SelectAllMenuItem_Click(object sender, EventArgs e) private void MaxLinesMenuItem_Click(object sender, EventArgs e) { - using var prompt = new InputPrompt + using InputPrompt prompt = new() { StartLocation = this.ChildPointToScreen(TraceView), TextInputType = InputPrompt.InputType.Unsigned, @@ -354,13 +355,13 @@ private void MaxLinesMenuItem_Click(object sender, EventArgs e) InitialValue = MaxLines.ToString() }; if (!this.ShowDialogWithTempMute(prompt).IsOk()) return; - var max = int.Parse(prompt.PromptText); + int max = int.Parse(prompt.PromptText); if (max > 0) MaxLines = max; } private void SegmentSizeMenuItem_Click(object sender, EventArgs e) { - using var prompt = new InputPrompt + using InputPrompt prompt = new() { StartLocation = this.ChildPointToScreen(TraceView), TextInputType = InputPrompt.InputType.Unsigned, @@ -393,7 +394,7 @@ private void LoggingEnabled_CheckedChanged(object sender, EventArgs e) private void StartLogFile(bool append = false) { - var data = Tracer.Header; + string data = Tracer.Header; _streamWriter = new StreamWriter( string.Concat(_baseName, _segmentCount == 0 ? string.Empty : $"_{_segmentCount}", _extension), append); @@ -435,8 +436,8 @@ private void ToFileRadio_CheckedChanged(object sender, EventArgs e) { FileBox.Visible = true; BrowseBox.Visible = true; - var name = Game.FilesystemSafeName(); - var filename = Path.Combine(Config.PathEntries.LogAbsolutePath(), name) + _extension; + string name = Game.FilesystemSafeName(); + string filename = Path.Combine(Config.PathEntries.LogAbsolutePath(), name) + _extension; LogFile = new FileInfo(filename); if (LogFile.Directory != null && !LogFile.Directory.Exists) { @@ -473,10 +474,7 @@ private void ToFileRadio_CheckedChanged(object sender, EventArgs e) SetTracerBoxTitle(); } - private void ClearMenuItem_Click(object sender, EventArgs e) - { - ClearList(); - } + private void ClearMenuItem_Click(object sender, EventArgs e) => ClearList(); private void OpenLogFile_Click(object sender, EventArgs e) { diff --git a/src/BizHawk.Client.EmuHawk/tools/VirtualPads/VirtualPad.cs b/src/BizHawk.Client.EmuHawk/tools/VirtualPads/VirtualPad.cs index 3104ab2cf44..ae2a6c710a6 100644 --- a/src/BizHawk.Client.EmuHawk/tools/VirtualPads/VirtualPad.cs +++ b/src/BizHawk.Client.EmuHawk/tools/VirtualPads/VirtualPad.cs @@ -48,10 +48,7 @@ public partial class VirtualPad : UserControl private readonly EventHandler _setLastFocusedNUD; private bool _readOnly; - public void UpdateValues() - { - PadControls.ForEach(c => c.UpdateValues()); - } + public void UpdateValues() => PadControls.ForEach(c => c.UpdateValues()); private List PadControls => PadBox.Controls @@ -88,7 +85,7 @@ private void VirtualPadControl_Load(object sender, EventArgs e) static VirtualPadButton GenVirtualPadButton(InputManager inputManager, ButtonSchema button) { var icon = button.Icon == null ? null : _buttonImages[button.Icon.Value]; - var buttonControl = new VirtualPadButton + VirtualPadButton buttonControl = new() { InputManager = inputManager, Name = button.Name, @@ -170,10 +167,7 @@ static VirtualPadButton GenVirtualPadButton(InputManager inputManager, ButtonSch } } - public void Clear() - { - PadControls.ForEach(p => p.Clear()); - } + public void Clear() => PadControls.ForEach(p => p.Clear()); public void ClearBoolean() { @@ -183,10 +177,7 @@ public void ClearBoolean() } } - public void Set(IController controller) - { - PadControls.ForEach(c => c.Set(controller)); - } + public void Set(IController controller) => PadControls.ForEach(c => c.Set(controller)); public void SetPrevious(IController previous) { diff --git a/src/BizHawk.Client.EmuHawk/tools/VirtualPads/VirtualpadsTool.cs b/src/BizHawk.Client.EmuHawk/tools/VirtualPads/VirtualpadsTool.cs index d4969112b6c..4c71847ed15 100644 --- a/src/BizHawk.Client.EmuHawk/tools/VirtualPads/VirtualpadsTool.cs +++ b/src/BizHawk.Client.EmuHawk/tools/VirtualPads/VirtualpadsTool.cs @@ -54,10 +54,7 @@ public VirtualpadTool() Icon = ToolIcon; } - private void VirtualpadTool_Load(object sender, EventArgs e) - { - CreatePads(); - } + private void VirtualpadTool_Load(object sender, EventArgs e) => CreatePads(); public void ClearVirtualPadHolds() { @@ -72,9 +69,7 @@ public void ClearVirtualPadHolds() } public void BumpAnalogValue(int? x, int? y) // TODO: multi-player - { - Pads.ForEach(pad => pad.BumpAnalog(x, y)); - } +=> Pads.ForEach(pad => pad.BumpAnalog(x, y)); private void SetLastFocusedNUD(object sender, EventArgs args) => _lastFocusedNUD = (Control) sender; @@ -96,7 +91,7 @@ private void CreatePads() return; } - var padSchemata = ((IVirtualPadSchema) Activator.CreateInstance(schemaType)) + List padSchemata = ((IVirtualPadSchema) Activator.CreateInstance(schemaType)) .GetPadSchemas(Emulator, s => DialogController.ShowMessageBox(s)) .ToList(); @@ -126,7 +121,7 @@ private void CreatePads() public void ScrollToPadSchema(string padSchemaName) { - foreach (var control in ControllerPanel.Controls) + foreach (object control in ControllerPanel.Controls) { if (control is not VirtualPad vp) { @@ -214,39 +209,18 @@ protected override void FastUpdateAfter() } } - private void PadsSubMenu_DropDownOpened(object sender, EventArgs e) - { - StickyMenuItem.Checked = StickyPads; - } + private void PadsSubMenu_DropDownOpened(object sender, EventArgs e) => StickyMenuItem.Checked = StickyPads; - private void ClearAllMenuItem_Click(object sender, EventArgs e) - { - ClearVirtualPadHolds(); - } + private void ClearAllMenuItem_Click(object sender, EventArgs e) => ClearVirtualPadHolds(); - private void StickyMenuItem_Click(object sender, EventArgs e) - { - StickyPads ^= true; - } + private void StickyMenuItem_Click(object sender, EventArgs e) => StickyPads ^= true; - private void PadBoxContextMenu_Opening(object sender, System.ComponentModel.CancelEventArgs e) - { - StickyContextMenuItem.Checked = StickyPads; - } + private void PadBoxContextMenu_Opening(object sender, System.ComponentModel.CancelEventArgs e) => StickyContextMenuItem.Checked = StickyPads; - private void ExitMenuItem_Click(object sender, EventArgs e) - { - Close(); - } + private void ExitMenuItem_Click(object sender, EventArgs e) => Close(); - private void OptionsSubMenu_DropDownOpened(object sender, EventArgs e) - { - ClearClearsAnalogInputMenuItem.Checked = ClearAlsoClearsAnalog; - } + private void OptionsSubMenu_DropDownOpened(object sender, EventArgs e) => ClearClearsAnalogInputMenuItem.Checked = ClearAlsoClearsAnalog; - private void ClearClearsAnalogInputMenuItem_Click(object sender, EventArgs e) - { - ClearAlsoClearsAnalog ^= true; - } + private void ClearClearsAnalogInputMenuItem_Click(object sender, EventArgs e) => ClearAlsoClearsAnalog ^= true; } } diff --git a/src/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/VirtualPadAnalogButton.cs b/src/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/VirtualPadAnalogButton.cs index 36e2e7fab5e..6407609fe3b 100644 --- a/src/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/VirtualPadAnalogButton.cs +++ b/src/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/VirtualPadAnalogButton.cs @@ -38,7 +38,7 @@ public VirtualPadAnalogButton( // Name, AnalogTrackBar, DisplayNameLabel, and ValueLabel are now assigned Name = name; - var trackbarWidth = Size.Width - 15; + int trackbarWidth = Size.Width - 15; int trackbarHeight; if ((AnalogTrackBar.Orientation = orientation) == Orientation.Vertical) { @@ -58,8 +58,8 @@ public VirtualPadAnalogButton( // try to base it on the width, lets make a tick every 10 pixels at the minimum // yo none of this makes any sense --yoshi - var range = maxValue - minValue + 1; - var canDoTicks = Math.Min(Math.Max(2, trackbarWidth / 10), range); + int range = maxValue - minValue + 1; + int canDoTicks = Math.Min(Math.Max(2, trackbarWidth / 10), range); AnalogTrackBar.TickFrequency = range / Math.Max(1, canDoTicks); DisplayNameLabel.Text = displayName ?? string.Empty; @@ -82,8 +82,8 @@ public void Clear() public void Set(IController controller) { - var newVal = controller.AxisValue(Name); - var changed = AnalogTrackBar.Value != newVal; + int newVal = controller.AxisValue(Name); + bool changed = AnalogTrackBar.Value != newVal; if (changed) { CurrentValue = newVal; diff --git a/src/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/VirtualPadAnalogStick.cs b/src/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/VirtualPadAnalogStick.cs index 76baba50fb5..c63133ec336 100644 --- a/src/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/VirtualPadAnalogStick.cs +++ b/src/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/VirtualPadAnalogStick.cs @@ -43,8 +43,8 @@ public VirtualPadAnalogStick( PolarToRectHelper = (r, θ) => { var (x, y) = PolarRectConversion.PolarToRectLookup((ushort) r, (ushort) θ); - var x1 = (RangeX.IsReversed ? RangeX.Neutral - x : RangeX.Neutral + x).ConstrainWithin(RangeX.Range); - var y1 = (RangeY.IsReversed ? RangeY.Neutral - y : RangeY.Neutral + y).ConstrainWithin(RangeY.Range); + int x1 = (RangeX.IsReversed ? RangeX.Neutral - x : RangeX.Neutral + x).ConstrainWithin(RangeX.Range); + int y1 = (RangeY.IsReversed ? RangeY.Neutral - y : RangeY.Neutral + y).ConstrainWithin(RangeY.Range); return ((short) x1, (short) y1); }; RectToPolarHelper = (x, y) => PolarRectConversion.RectToPolarLookup( @@ -59,17 +59,17 @@ public VirtualPadAnalogStick( const double RAD_TO_DEG_FACTOR = 180 / Math.PI; PolarToRectHelper = (r, θ) => { - var x = (short) (r * Math.Cos(θ * DEG_TO_RAD_FACTOR)); - var y = (short) (r * Math.Sin(θ * DEG_TO_RAD_FACTOR)); - var x1 = (RangeX.IsReversed ? RangeX.Neutral - x : RangeX.Neutral + x).ConstrainWithin(RangeX.Range); - var y1 = (RangeY.IsReversed ? RangeY.Neutral - y : RangeY.Neutral + y).ConstrainWithin(RangeY.Range); + short x = (short) (r * Math.Cos(θ * DEG_TO_RAD_FACTOR)); + short y = (short) (r * Math.Sin(θ * DEG_TO_RAD_FACTOR)); + int x1 = (RangeX.IsReversed ? RangeX.Neutral - x : RangeX.Neutral + x).ConstrainWithin(RangeX.Range); + int y1 = (RangeY.IsReversed ? RangeY.Neutral - y : RangeY.Neutral + y).ConstrainWithin(RangeY.Range); return ((short) x1, (short) y1); }; RectToPolarHelper = (x, y) => { double x1 = RangeX.IsReversed ? RangeX.Neutral - x : x - RangeX.Neutral; double y1 = RangeY.IsReversed ? RangeY.Neutral - y : y - RangeY.Neutral; - var θ = Math.Atan2(y1, x1) * RAD_TO_DEG_FACTOR; + double θ = Math.Atan2(y1, x1) * RAD_TO_DEG_FACTOR; return ((uint) Math.Sqrt(x1 * x1 + y1 * y1), (uint) (θ < 0 ? 360.0 + θ : θ)); }; } @@ -196,8 +196,8 @@ private void ManualXY_ValueChanged(object sender, EventArgs e) if (_updatingFromAnalog || _updatingFromPolar) return; _updatingFromXY = true; - var x = (int) ManualX.Value; - var y = (int) ManualY.Value; + int x = (int) ManualX.Value; + int y = (int) ManualY.Value; var (r, θ) = RectToPolarHelper(x, y); SetAnalog(x, y); SetPolar(r, θ); @@ -248,8 +248,8 @@ private void SetNumericsFromAnalog() if (AnalogStick.HasValue) { - var x = AnalogStick.X; - var y = AnalogStick.Y; + int x = AnalogStick.X; + int y = AnalogStick.Y; var (r, θ) = RectToPolarHelper(x, y); SetPolar(r, θ); SetXY(x, y); diff --git a/src/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/VirtualPadButton.cs b/src/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/VirtualPadButton.cs index 72c7eced5fe..6192d343bce 100644 --- a/src/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/VirtualPadButton.cs +++ b/src/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/VirtualPadButton.cs @@ -45,8 +45,8 @@ public void UpdateValues() public void Set(IController controller) { - var newVal = controller.IsPressed(Name); - var changed = newVal != Checked; + bool newVal = controller.IsPressed(Name); + bool changed = newVal != Checked; Checked = newVal; if (changed) diff --git a/src/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/VirtualPadDiscManager.cs b/src/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/VirtualPadDiscManager.cs index 13516d0fd4e..e8c912dadbf 100644 --- a/src/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/VirtualPadDiscManager.cs +++ b/src/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/VirtualPadDiscManager.cs @@ -42,15 +42,15 @@ private void UpdateCoreAssociation() return; } - var buttons = new List { "- NONE -" }; + List buttons = new() { "- NONE -" }; buttons.AddRange(psx.HackyDiscButtons); lvDiscs.Items.Clear(); int idx = 0; - foreach (var button in buttons) + foreach (string button in buttons) { - var lvi = new ListViewItem { Text = idx.ToString() }; + ListViewItem lvi = new() { Text = idx.ToString() }; lvi.SubItems.Add(button); lvDiscs.Items.Add(lvi); idx++; @@ -123,11 +123,9 @@ public void Set(IController controller) public bool ReadOnly { get; set; } - private void lvDiscs_SelectedIndexChanged(object sender, EventArgs e) - { + private void lvDiscs_SelectedIndexChanged(object sender, EventArgs e) => // emergency measure: if no selection, set no disc _inputManager.StickyXorAdapter.SetAxis(_discSelectName, lvDiscs.SelectedIndices.Count == 0 ? 0 : lvDiscs.SelectedIndices[0]); - } private void btnClose_Click(object sender, EventArgs e) { diff --git a/src/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/VirtualPadTargetScreen.cs b/src/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/VirtualPadTargetScreen.cs index 6f29e3ee88f..e6d395d955e 100644 --- a/src/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/VirtualPadTargetScreen.cs +++ b/src/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/VirtualPadTargetScreen.cs @@ -9,9 +9,9 @@ namespace BizHawk.Client.EmuHawk public partial class VirtualPadTargetScreen : UserControl, IVirtualPadControl { private readonly StickyXorAdapter _stickyXorAdapter; - private readonly Pen BlackPen = new Pen(Brushes.Black, 2); - private readonly Pen GrayPen = new Pen(Brushes.Gray, 2); - private readonly Pen RedPen = new Pen(Brushes.Red, 2); + private readonly Pen BlackPen = new(Brushes.Black, 2); + private readonly Pen GrayPen = new(Brushes.Gray, 2); + private readonly Pen RedPen = new(Brushes.Red, 2); private bool _isProgrammicallyChangingNumerics; private bool _isDragging; @@ -51,10 +51,7 @@ private void VirtualPadTargetScreen_Load(object sender, EventArgs e) YNumeric.Maximum = TargetPanel.Height - 1; } - public void UpdateValues() - { - TargetPanel.Refresh(); - } + public void UpdateValues() => TargetPanel.Refresh(); public void Clear() { @@ -68,13 +65,13 @@ public void Clear() public void Set(IController controller) { - var newX = controller.AxisValue(XName) / MultiplierX; - var newY = controller.AxisValue(YName) / MultiplierY; + float newX = controller.AxisValue(XName) / MultiplierX; + float newY = controller.AxisValue(YName) / MultiplierY; - var oldX = X / MultiplierX; - var oldY = Y / MultiplierY; + float oldX = X / MultiplierX; + float oldY = Y / MultiplierY; - var changed = newX != oldX && newY != oldY; + bool changed = newX != oldX && newY != oldY; XNumeric.Value = (int)newX; YNumeric.Value = (int)newY; @@ -117,7 +114,7 @@ public bool ReadOnly } // Size of the extra controls to the right / bottom of the target panel at 96 DPI - private Size PaddingSize => new Size(0, 30); + private Size PaddingSize => new(0, 30); public Size TargetSize { @@ -255,25 +252,13 @@ private void TargetPanel_Paint(object sender, PaintEventArgs e) new Rectangle(X - 2, Y - 2, 4, 4)); } - private void XNumeric_ValueChanged(object sender, EventArgs e) - { - UpdatePanelFromNumeric(); - } + private void XNumeric_ValueChanged(object sender, EventArgs e) => UpdatePanelFromNumeric(); - private void XNumeric_KeyUp(object sender, KeyEventArgs e) - { - UpdatePanelFromNumeric(); - } + private void XNumeric_KeyUp(object sender, KeyEventArgs e) => UpdatePanelFromNumeric(); - private void YNumeric_ValueChanged(object sender, EventArgs e) - { - UpdatePanelFromNumeric(); - } + private void YNumeric_ValueChanged(object sender, EventArgs e) => UpdatePanelFromNumeric(); - private void YNumeric_KeyUp(object sender, KeyEventArgs e) - { - UpdatePanelFromNumeric(); - } + private void YNumeric_KeyUp(object sender, KeyEventArgs e) => UpdatePanelFromNumeric(); private void TargetPanel_MouseDown(object sender, MouseEventArgs e) { diff --git a/src/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/components/AnalogStickPanel.cs b/src/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/components/AnalogStickPanel.cs index 40d6d1d638e..3a2a172455c 100644 --- a/src/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/components/AnalogStickPanel.cs +++ b/src/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/components/AnalogStickPanel.cs @@ -64,7 +64,7 @@ public void Init(StickyXorAdapter stickyXorAdapter, string nameX, AxisSpec range { _stickyXorAdapter = stickyXorAdapter; - var scaleBase = Math.Min(Size.Width, Size.Height) - 10.0; // be circular when control is stretched + double scaleBase = Math.Min(Size.Width, Size.Height) - 10.0; // be circular when control is stretched XName = nameX; _fullRangeX = rangeX; @@ -132,12 +132,12 @@ private int GfxToRealX(int val) => private int GfxToRealY(int val) => MaybeReversedInY((_rangeY.Start + ((val - PixelMinY) / ScaleY).RoundToInt()).ConstrainWithin(_rangeY)); - private readonly Pen _blackPen = new Pen(Brushes.Black); - private readonly Pen _bluePen = new Pen(Brushes.Blue, 2); - private readonly Pen _grayPen = new Pen(Brushes.Gray, 2); + private readonly Pen _blackPen = new(Brushes.Black); + private readonly Pen _bluePen = new(Brushes.Blue, 2); + private readonly Pen _grayPen = new(Brushes.Gray, 2); - private readonly Bitmap _dot = new Bitmap(7, 7); - private readonly Bitmap _grayDot = new Bitmap(7, 7); + private readonly Bitmap _dot = new(7, 7); + private readonly Bitmap _grayDot = new(7, 7); [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Action ClearCallback { get; set; } @@ -154,14 +154,14 @@ public AnalogStickPanel() BorderStyle = BorderStyle.Fixed3D; // Draw the dot into a bitmap - using var g = Graphics.FromImage(_dot); + using Graphics g = Graphics.FromImage(_dot); g.Clear(Color.Transparent); var redBrush = Brushes.Red; g.FillRectangle(redBrush, 2, 0, 3, 7); g.FillRectangle(redBrush, 1, 1, 5, 5); g.FillRectangle(redBrush, 0, 2, 7, 3); - using var gg = Graphics.FromImage(_grayDot); + using Graphics gg = Graphics.FromImage(_grayDot); gg.Clear(Color.Transparent); gg.FillRectangle(Brushes.Gray, 2, 0, 3, 7); gg.FillRectangle(Brushes.Gray, 1, 1, 5, 5); @@ -191,8 +191,8 @@ private void AnalogControlPanel_Paint(object sender, PaintEventArgs e) // Previous frame if (_previous != null) { - var pX = _previous.AxisValue(XName); - var pY = _previous.AxisValue(YName); + int pX = _previous.AxisValue(XName); + int pY = _previous.AxisValue(YName); e.Graphics.DrawLine(_grayPen, PixelMidX, PixelMidY, RealToGfxX(pX), RealToGfxY(pY)); e.Graphics.DrawImage(_grayDot, RealToGfxX(pX) - 3, RealToGfxY(_rangeY.EndInclusive) - RealToGfxY(pY) - 3); } @@ -268,15 +268,12 @@ public void Clear(bool fromCallback = false) public void Set(IController controller) { - var newX = controller.AxisValue(XName); - var newY = controller.AxisValue(YName); + int newX = controller.AxisValue(XName); + int newY = controller.AxisValue(YName); if (newX != X || newY != Y) SetPosition(newX, newY); } - public void SetPrevious(IController previous) - { - _previous = previous; - } + public void SetPrevious(IController previous) => _previous = previous; private void SetPosition(int xval, int yval) { diff --git a/src/BizHawk.Client.EmuHawk/tools/Watch/RamPoke.cs b/src/BizHawk.Client.EmuHawk/tools/Watch/RamPoke.cs index eebd9a43472..b94e556936e 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Watch/RamPoke.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Watch/RamPoke.cs @@ -77,10 +77,7 @@ private void RamPoke_Load(object sender, EventArgs e) SetTitle(); } - private void SetTitle() - { - Text = $"RAM Poke - {_watchList[0].Domain.Name}"; - } + private void SetTitle() => Text = $"RAM Poke - {_watchList[0].Domain.Name}"; private void Cancel_Click(object sender, EventArgs e) { @@ -90,10 +87,10 @@ private void Cancel_Click(object sender, EventArgs e) private void Ok_Click(object sender, EventArgs e) { - var success = true; + bool success = true; foreach (var watch in _watchList) { - var result = watch.Poke(ValueBox.Text); + bool result = watch.Poke(ValueBox.Text); if (result) { var cheat = _cheats.FirstOrDefault(c => c.Address == watch.Address && c.Domain == watch.Domain); diff --git a/src/BizHawk.Client.EmuHawk/tools/Watch/RamSearch.cs b/src/BizHawk.Client.EmuHawk/tools/Watch/RamSearch.cs index 9dbd06d11c9..455a677cbb2 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Watch/RamSearch.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Watch/RamSearch.cs @@ -112,7 +112,7 @@ public RamSearch() private void HardSetDisplayTypeDropDown(Common.WatchDisplayType type) { - foreach (var item in DisplayTypeDropdown.Items) + foreach (object item in DisplayTypeDropdown.Items) { if (Watch.DisplayTypeToString(type) == item.ToString()) { @@ -132,10 +132,7 @@ private void HardSetSizeDropDown(WatchSize size) }; } - private void ColumnToggleCallback() - { - Settings.Columns = WatchListView.AllColumns; - } + private void ColumnToggleCallback() => Settings.Columns = WatchListView.AllColumns; private void RamSearch_Load(object sender, EventArgs e) { @@ -179,10 +176,7 @@ private void RamSearch_Load(object sender, EventArgs e) NewSearch(); } - private void OutOfRangeCheck() - { - ErrorIconButton.Visible = _searches.OutOfRangeAddress.Any(); - } + private void OutOfRangeCheck() => ErrorIconButton.Visible = _searches.OutOfRangeAddress.Any(); private void ListView_QueryItemBkColor(int index, RollColumn column, ref Color color) { @@ -190,8 +184,8 @@ private void ListView_QueryItemBkColor(int index, RollColumn column, ref Color c { var nextColor = Color.White; var search = _searches[index]; - var isCheat = MainForm.CheatList.IsActive(_settings.Domain, search.Address); - var isWeeded = Settings.PreviewMode && !_forcePreviewClear && _searches.Preview(search.Address); + bool isCheat = MainForm.CheatList.IsActive(_settings.Domain, search.Address); + bool isWeeded = Settings.PreviewMode && !_forcePreviewClear && _searches.Preview(search.Address); if (!search.IsValid) { @@ -222,7 +216,7 @@ private void ListView_QueryItemText(int index, RollColumn column, out string tex return; } - var columnName = column.Name; + string columnName = column.Name; text = columnName switch { WatchList.Address => _searches[index].AddressString, @@ -320,8 +314,8 @@ public override void Restart() public void NewSearch() { var compareTo = _searches.CompareTo; - var compareVal = _searches.CompareValue; - var differentBy = _searches.DifferentBy; + long? compareVal = _searches.CompareValue; + int? differentBy = _searches.DifferentBy; _searches = new RamSearchEngine(_settings, MemoryDomains, compareTo, compareVal, differentBy); _searches.Start(); @@ -339,13 +333,13 @@ public void NewSearch() public void NextCompareTo(bool reverse = false) { - var radios = CompareToBox.Controls + List radios = CompareToBox.Controls .OfType() .Select(control => control) .OrderBy(x => x.TabIndex) .ToList(); - var index = radios.FindIndex(static x => x.Checked); + int index = radios.FindIndex(static x => x.Checked); if (reverse) { @@ -374,13 +368,13 @@ public void NextCompareTo(bool reverse = false) public void NextOperator(bool reverse = false) { - var radios = ComparisonBox.Controls + List radios = ComparisonBox.Controls .OfType() .Select(control => control) .OrderBy(x => x.TabIndex) .ToList(); - var index = radios.FindIndex(static x => x.Checked); + int index = radios.FindIndex(static x => x.Checked); if (reverse) { @@ -529,7 +523,7 @@ public void DoSearch() _searches.Operator = Operator; _searches.CompareTo = Compare; - var removed = _searches.DoSearch(); + int removed = _searches.DoSearch(); UpdateList(); SetRemovedMessage(removed); ToggleSearchDependentToolBarItems(); @@ -545,24 +539,15 @@ public void DoSearch() private bool MayPokeAllSelected => WatchListView.AnyRowsSelected && SelectedWatches.All(static w => w.Domain.Writable); - private void SetRemovedMessage(int val) - { - MessageLabel.Text = $"{val} {(val == 1 ? "address" : "addresses")} removed"; - } + private void SetRemovedMessage(int val) => MessageLabel.Text = $"{val} {(val == 1 ? "address" : "addresses")} removed"; - private void SetTotal() - { - TotalSearchLabel.Text = $"{_searches.Count:n0} addresses"; - } + private void SetTotal() => TotalSearchLabel.Text = $"{_searches.Count:n0} addresses"; - private void SetDomainLabel() - { - MemDomainLabel.Text = _searches.Domain.Name; - } + private void SetDomainLabel() => MemDomainLabel.Text = _searches.Domain.Name; private void LoadFileFromRecent(string path) { - var file = new FileInfo(path); + FileInfo file = new(path); if (!file.Exists) { @@ -693,8 +678,8 @@ private void SetSize(WatchSize size) private void PopulateTypeDropDown() { - var previous = DisplayTypeDropdown.SelectedItem?.ToString() ?? ""; - var next = ""; + string previous = DisplayTypeDropdown.SelectedItem?.ToString() ?? ""; + string next = ""; DisplayTypeDropdown.Items.Clear(); @@ -708,7 +693,7 @@ private void PopulateTypeDropDown() foreach (var type in types) { - var typeStr = Watch.DisplayTypeToString(type); + string typeStr = Watch.DisplayTypeToString(type); DisplayTypeDropdown.Items.Add(typeStr); if (previous == typeStr) { @@ -771,7 +756,7 @@ private ToolStripMenuItem ChangesMenuItem { get { - var subMenu = (ToolStripMenuItem)RamSearchMenu.Items + ToolStripMenuItem subMenu = (ToolStripMenuItem)RamSearchMenu.Items .Cast() .Single(t => t.Name == "GeneratedColumnsSubMenu"); // TODO - make name a constant return subMenu.DropDownItems @@ -784,7 +769,7 @@ private void SetToFastMode() { _settings.Mode = SearchMode.Fast; - if (_settings.PreviousType == PreviousType.LastFrame || _settings.PreviousType == PreviousType.LastChange) + if (_settings.PreviousType is PreviousType.LastFrame or PreviousType.LastChange) { SetPreviousType(PreviousType.LastSearch); } @@ -808,7 +793,7 @@ private void SetToFastMode() private void RemoveAddresses() { - var indices = SelectedIndices.ToList(); + List indices = SelectedIndices.ToList(); if (indices.Any()) { SetRemovedMessage(indices.Count); @@ -829,12 +814,12 @@ private void LoadWatchFile(FileInfo file, bool append, bool truncate = false) _currentFileName = file.FullName; } - var watches = new WatchList(MemoryDomains, Emu.SystemId); + WatchList watches = new(MemoryDomains, Emu.SystemId); watches.Load(file.FullName, append); Settings.RecentSearches.Add(watches.CurrentFileName); - var watchList = watches.Where(x => !x.IsSeparator).ToList(); - var addresses = watchList.Select(x => x.Address).ToList(); + List watchList = watches.Where(x => !x.IsSeparator).ToList(); + List addresses = watchList.Select(x => x.Address).ToList(); if (truncate) { @@ -861,7 +846,7 @@ private void LoadWatchFile(FileInfo file, bool append, bool truncate = false) private void AddToRamWatch() { - var watches = SelectedWatches.ToList(); + List watches = SelectedWatches.ToList(); if (watches.Any()) { Tools.LoadRamWatch(true); @@ -899,7 +884,7 @@ private void UpdateUndoToolBarButtons() private void GoToSpecifiedAddress() { WatchListView.DeselectAll(); - var prompt = new InputPrompt + InputPrompt prompt = new() { Text = "Go to Address", StartLocation = this.ChildPointToScreen(WatchListView), @@ -910,7 +895,7 @@ private void GoToSpecifiedAddress() { try { - var addr = int.Parse(prompt.PromptText, NumberStyles.HexNumber); + int addr = int.Parse(prompt.PromptText, NumberStyles.HexNumber); for (int index = 0; index < _searches.Count; index++) { if (_searches[index].Address == addr) @@ -964,10 +949,7 @@ public RamSearchSettings() public RecentFiles RecentSearches { get; set; } } - private void FileSubMenu_DropDownOpened(object sender, EventArgs e) - { - SaveMenuItem.Enabled = !string.IsNullOrWhiteSpace(_currentFileName); - } + private void FileSubMenu_DropDownOpened(object sender, EventArgs e) => SaveMenuItem.Enabled = !string.IsNullOrWhiteSpace(_currentFileName); private void RecentSubMenu_DropDownOpened(object sender, EventArgs e) => RecentSubMenu.ReplaceDropDownItems(Settings.RecentSearches.RecentMenu(this, LoadFileFromRecent, "Search", noAutoload: true)); @@ -991,8 +973,8 @@ private void SaveMenuItem_Click(object sender, EventArgs e) { if (!string.IsNullOrWhiteSpace(_currentFileName)) { - var watches = new WatchList(MemoryDomains, Emu.SystemId) { CurrentFileName = _currentFileName }; - for (var i = 0; i < _searches.Count; i++) + WatchList watches = new(MemoryDomains, Emu.SystemId) { CurrentFileName = _currentFileName }; + for (int i = 0; i < _searches.Count; i++) { watches.Add(_searches[i]); } @@ -1008,7 +990,7 @@ private void SaveMenuItem_Click(object sender, EventArgs e) } else { - var result = watches.SaveAs(GetWatchSaveFileFromUser(CurrentFileName())); + bool result = watches.SaveAs(GetWatchSaveFileFromUser(CurrentFileName())); if (result) { MessageLabel.Text = $"{Path.GetFileName(_currentFileName)} saved"; @@ -1020,8 +1002,8 @@ private void SaveMenuItem_Click(object sender, EventArgs e) private void SaveAsMenuItem_Click(object sender, EventArgs e) { - var watches = new WatchList(MemoryDomains, Emu.SystemId) { CurrentFileName = _currentFileName }; - for (var i = 0; i < _searches.Count; i++) + WatchList watches = new(MemoryDomains, Emu.SystemId) { CurrentFileName = _currentFileName }; + for (int i = 0; i < _searches.Count; i++) { watches.Add(_searches[i]); } @@ -1070,12 +1052,12 @@ private void DisplayTypeSubMenu_DropDownOpened(object sender, EventArgs e) foreach (var type in types) { - var item = new ToolStripMenuItem - { - Name = $"{type}ToolStripMenuItem", - Text = Watch.DisplayTypeToString(type), - Checked = _settings.Type == type - }; + ToolStripMenuItem item = new() + { + Name = $"{type}ToolStripMenuItem", + Text = Watch.DisplayTypeToString(type), + Checked = _settings.Type == type + }; var type1 = type; item.Click += (o, ev) => DoDisplayTypeClick(type1); @@ -1111,30 +1093,15 @@ private void DefinePreviousValueSubMenu_DropDownOpened(object sender, EventArgs Previous_LastChangeMenuItem.Enabled = _settings.IsDetailed(); } - private void DetailedMenuItem_Click(object sender, EventArgs e) - { - SetToDetailedMode(); - } + private void DetailedMenuItem_Click(object sender, EventArgs e) => SetToDetailedMode(); - private void FastMenuItem_Click(object sender, EventArgs e) - { - SetToFastMode(); - } + private void FastMenuItem_Click(object sender, EventArgs e) => SetToFastMode(); - private void ByteMenuItem_Click(object sender, EventArgs e) - { - HandleWatchSizeSelected(WatchSize.Byte); - } + private void ByteMenuItem_Click(object sender, EventArgs e) => HandleWatchSizeSelected(WatchSize.Byte); - private void WordMenuItem_Click(object sender, EventArgs e) - { - HandleWatchSizeSelected(WatchSize.Word); - } + private void WordMenuItem_Click(object sender, EventArgs e) => HandleWatchSizeSelected(WatchSize.Word); - private void DWordMenuItem_Click_Click(object sender, EventArgs e) - { - HandleWatchSizeSelected(WatchSize.DWord); - } + private void DWordMenuItem_Click_Click(object sender, EventArgs e) => HandleWatchSizeSelected(WatchSize.DWord); private void CheckMisalignedMenuItem_Click(object sender, EventArgs e) { @@ -1142,25 +1109,13 @@ private void CheckMisalignedMenuItem_Click(object sender, EventArgs e) SetReboot(true); } - private void Previous_LastFrameMenuItem_Click(object sender, EventArgs e) - { - SetPreviousType(PreviousType.LastFrame); - } + private void Previous_LastFrameMenuItem_Click(object sender, EventArgs e) => SetPreviousType(PreviousType.LastFrame); - private void Previous_LastSearchMenuItem_Click(object sender, EventArgs e) - { - SetPreviousType(PreviousType.LastSearch); - } + private void Previous_LastSearchMenuItem_Click(object sender, EventArgs e) => SetPreviousType(PreviousType.LastSearch); - private void Previous_OriginalMenuItem_Click(object sender, EventArgs e) - { - SetPreviousType(PreviousType.Original); - } + private void Previous_OriginalMenuItem_Click(object sender, EventArgs e) => SetPreviousType(PreviousType.Original); - private void Previous_LastChangeMenuItem_Click(object sender, EventArgs e) - { - SetPreviousType(PreviousType.LastChange); - } + private void Previous_LastChangeMenuItem_Click(object sender, EventArgs e) => SetPreviousType(PreviousType.LastChange); private void BigEndianMenuItem_Click(object sender, EventArgs e) { @@ -1187,15 +1142,9 @@ private void SearchSubMenu_DropDownOpened(object sender, EventArgs e) RedoMenuItem.Enabled = _searches.CanRedo; } - private void NewSearchMenuMenuItem_Click(object sender, EventArgs e) - { - NewSearch(); - } + private void NewSearchMenuMenuItem_Click(object sender, EventArgs e) => NewSearch(); - private void SearchMenuItem_Click(object sender, EventArgs e) - { - DoSearch(); - } + private void SearchMenuItem_Click(object sender, EventArgs e) => DoSearch(); private void UndoMenuItem_Click(object sender, EventArgs e) { @@ -1235,29 +1184,17 @@ private void ClearChangeCountsMenuItem_Click(object sender, EventArgs e) WatchListView.Refresh(); } - private void RemoveMenuItem_Click(object sender, EventArgs e) - { - RemoveAddresses(); - } + private void RemoveMenuItem_Click(object sender, EventArgs e) => RemoveAddresses(); - private void GoToAddressMenuItem_Click(object sender, EventArgs e) - { - GoToSpecifiedAddress(); - } + private void GoToAddressMenuItem_Click(object sender, EventArgs e) => GoToSpecifiedAddress(); - private void AddToRamWatchMenuItem_Click(object sender, EventArgs e) - { - AddToRamWatch(); - } + private void AddToRamWatchMenuItem_Click(object sender, EventArgs e) => AddToRamWatch(); - private void PokeAddressMenuItem_Click(object sender, EventArgs e) - { - PokeAddress(); - } + private void PokeAddressMenuItem_Click(object sender, EventArgs e) => PokeAddress(); private void FreezeAddressMenuItem_Click(object sender, EventArgs e) { - var allCheats = SelectedWatches.All(x => MainForm.CheatList.IsActive(x.Domain, x.Address)); + bool allCheats = SelectedWatches.All(x => MainForm.CheatList.IsActive(x.Domain, x.Address)); if (allCheats) { MainForm.CheatList.RemoveRange(SelectedWatches); @@ -1287,10 +1224,7 @@ private void SettingsSubMenu_DropDownOpened(object sender, EventArgs e) AutoSearchAccountForLagMenuItem.Checked = Settings.AutoSearchTakeLagFramesIntoAccount; } - private void PreviewModeMenuItem_Click(object sender, EventArgs e) - { - Settings.PreviewMode ^= true; - } + private void PreviewModeMenuItem_Click(object sender, EventArgs e) => Settings.PreviewMode ^= true; private void AutoSearchMenuItem_Click(object sender, EventArgs e) { @@ -1301,10 +1235,7 @@ private void AutoSearchMenuItem_Click(object sender, EventArgs e) !_autoSearch; } - private void AutoSearchAccountForLagMenuItem_Click(object sender, EventArgs e) - { - Settings.AutoSearchTakeLagFramesIntoAccount ^= true; - } + private void AutoSearchAccountForLagMenuItem_Click(object sender, EventArgs e) => Settings.AutoSearchTakeLagFramesIntoAccount ^= true; private void ExcludeRamWatchMenuItem_Click(object sender, EventArgs e) { @@ -1321,6 +1252,7 @@ private void UseUndoHistoryMenuItem_Click(object sender, EventArgs e) Settings.UseUndoHistory = _searches.UndoEnabled; } + #pragma warning disable IDE0051 [RestoreDefaults] private void RestoreDefaultsMenuItem() { @@ -1344,6 +1276,7 @@ private void RestoreDefaultsMenuItem() WatchListView.AllColumns.Clear(); SetColumns(); } + #pragma warning restore IDE0051 private void ListViewContextMenu_Opening(object sender, CancelEventArgs e) { @@ -1376,10 +1309,7 @@ private void ListViewContextMenu_Opening(object sender, CancelEventArgs e) } } - private void UnfreezeAllContextMenuItem_Click(object sender, EventArgs e) - { - MainForm.CheatList.RemoveAll(); - } + private void UnfreezeAllContextMenuItem_Click(object sender, EventArgs e) => MainForm.CheatList.RemoveAll(); private void ViewInHexEditorContextMenuItem_Click(object sender, EventArgs e) { @@ -1423,7 +1353,7 @@ private void DisplayTypeDropdown_SelectedIndexChanged(object sender, EventArgs e private void ErrorIconButton_Click(object sender, EventArgs e) { - var outOfRangeAddresses = _searches.OutOfRangeAddress.ToList(); + List outOfRangeAddresses = _searches.OutOfRangeAddress.ToList(); _searches.RemoveAddressRange(outOfRangeAddresses); SetRemovedMessage(outOfRangeAddresses.Count); @@ -1435,7 +1365,7 @@ private void CopyWatchesToClipBoard() { if (SelectedItems.Any()) { - var sb = new StringBuilder(); + StringBuilder sb = new(); foreach (var watch in SelectedItems) { sb.AppendLine(watch.ToString()); @@ -1541,10 +1471,7 @@ private void DifferenceRadio_Click(object sender, EventArgs e) SetCompareTo(Compare.Difference); } - private void CompareToValue_TextChanged(object sender, EventArgs e) - { - SetCompareValue(((INumberBox)sender).ToRawInt()); - } + private void CompareToValue_TextChanged(object sender, EventArgs e) => SetCompareValue(((INumberBox)sender).ToRawInt()); private void EqualToRadio_Click(object sender, EventArgs e) { @@ -1630,10 +1557,7 @@ private void WatchListView_SelectedIndexChanged(object sender, EventArgs e) WatchListView.AnyRowsSelected && _searches.Domain.Writable; } - private void WatchListView_Enter(object sender, EventArgs e) - { - WatchListView.Refresh(); - } + private void WatchListView_Enter(object sender, EventArgs e) => WatchListView.Refresh(); private void WatchListView_ColumnClick(object sender, InputRoll.ColumnClickEventArgs e) { @@ -1658,17 +1582,14 @@ private void WatchListView_MouseDoubleClick(object sender, MouseEventArgs e) } } - private void NewRamSearch_Activated(object sender, EventArgs e) - { - WatchListView.Refresh(); - } + private void NewRamSearch_Activated(object sender, EventArgs e) => WatchListView.Refresh(); private void NewRamSearch_DragDrop(object sender, DragEventArgs e) { - var filePaths = (string[])e.Data.GetData(DataFormats.FileDrop); + string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop); if (Path.GetExtension(filePaths[0]) == ".wch") { - var file = new FileInfo(filePaths[0]); + FileInfo file = new(filePaths[0]); if (file.Exists) { LoadWatchFile(file, false); @@ -1677,9 +1598,6 @@ private void NewRamSearch_DragDrop(object sender, DragEventArgs e) } // Stupid designer - protected void DragEnterWrapper(object sender, DragEventArgs e) - { - GenericDragEnter(sender, e); - } + protected void DragEnterWrapper(object sender, DragEventArgs e) => GenericDragEnter(sender, e); } } diff --git a/src/BizHawk.Client.EmuHawk/tools/Watch/RamWatch.cs b/src/BizHawk.Client.EmuHawk/tools/Watch/RamWatch.cs index d2f6370e9c6..9e7e77193fd 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Watch/RamWatch.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Watch/RamWatch.cs @@ -101,9 +101,9 @@ public RamWatch() { return; } - var seen = new SortedList<(string Domain, long Addr)>[] { null, new(), new(), null, new() }; + SortedList<(string Domain, long Addr)>[] seen = new SortedList<(string Domain, long Addr)>[] { null, new(), new(), null, new() }; //TODO check if it's faster to build up a toRemove list and then batch Remove (by ref) at end - var i = 0; + int i = 0; Watch w; while (i < _watches.Count) { @@ -235,7 +235,7 @@ public override bool AskSaveChanges() public void LoadFileFromRecent(string path) { - var askResult = true; + bool askResult = true; if (_watches.Changes) { askResult = AskSaveChanges(); @@ -243,7 +243,7 @@ public void LoadFileFromRecent(string path) if (askResult) { - var loadResult = _watches.Load(path, append: false); + bool loadResult = _watches.Load(path, append: false); if (!loadResult) { Config.RecentWatches.HandleLoadError(MainForm, path); @@ -264,7 +264,7 @@ public void LoadWatchFile(FileInfo file, bool append) { if (file != null) { - var result = true; + bool result = true; if (_watches.Changes) { result = AskSaveChanges(); @@ -364,9 +364,9 @@ private void DisplayOnScreenWatches() if (Config.DisplayRamWatch) { DisplayManager.OSD.ClearRamWatches(); - for (var i = 0; i < _watches.Count; i++) + for (int i = 0; i < _watches.Count; i++) { - var frozen = !_watches[i].IsSeparator && MainForm.CheatList.IsActive(_watches[i].Domain, _watches[i].Address); + bool frozen = !_watches[i].IsSeparator && MainForm.CheatList.IsActive(_watches[i].Domain, _watches[i].Address); DisplayManager.OSD.AddRamWatch( _watches[i].ToDisplayString(), new MessagePosition @@ -391,7 +391,7 @@ private void CopyWatchesToClipBoard() { if (SelectedItems.Any()) { - var sb = new StringBuilder(); + StringBuilder sb = new(); foreach (var watch in SelectedItems) { sb.AppendLine(watch.ToString()); @@ -410,11 +410,11 @@ private void PasteWatchesFromClipBoard() if (data != null && data.GetDataPresent(DataFormats.Text)) { - var clipboardRows = ((string)data.GetData(DataFormats.Text)).Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); + string[] clipboardRows = ((string)data.GetData(DataFormats.Text)).Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); - foreach (var row in clipboardRows) + foreach (string row in clipboardRows) { - var watch = Watch.FromString(row, MemoryDomains); + Watch watch = Watch.FromString(row, MemoryDomains); if (watch is not null) { _watches.Add(watch); @@ -435,11 +435,11 @@ private void FullyUpdateWatchList() private void EditWatch(bool duplicate = false) { - var indexes = SelectedIndices.ToList(); + List indexes = SelectedIndices.ToList(); if (SelectedWatches.Any()) { - var we = new WatchEditor + WatchEditor we = new() { InitialLocation = this.ChildPointToScreen(WatchListView), MemoryDomains = MemoryDomains @@ -457,7 +457,7 @@ private void EditWatch(bool duplicate = false) } else { - for (var i = 0; i < we.Watches.Count; i++) + for (int i = 0; i < we.Watches.Count; i++) { _watches[indexes[i]] = we.Watches[i]; } @@ -469,7 +469,7 @@ private void EditWatch(bool duplicate = false) } else if (SelectedSeparators.Any() && !duplicate) { - var inputPrompt = new InputPrompt + InputPrompt inputPrompt = new() { Text = "Edit Separator", StartLocation = this.ChildPointToScreen(WatchListView), @@ -481,8 +481,8 @@ private void EditWatch(bool duplicate = false) { Changes(); - var selection = SelectedSeparators.ToList(); - for (var i = 0; i < selection.Count; i++) + List selection = SelectedSeparators.ToList(); + for (int i = 0; i < selection.Count; i++) { var sep = selection[i]; sep.Notes = inputPrompt.PromptText; @@ -536,7 +536,7 @@ private void LoadConfigSettings() private void NewWatchList(bool suppressAsk) { - var result = true; + bool result = true; if (_watches.Changes) { result = AskSaveChanges(); @@ -581,7 +581,7 @@ private string CurrentFileName() private void SaveAs() { - var result = _watches.SaveAs(GetWatchSaveFileFromUser(CurrentFileName())); + bool result = _watches.SaveAs(GetWatchSaveFileFromUser(CurrentFileName())); if (result) { UpdateStatusBar(saved: true); @@ -589,10 +589,7 @@ private void SaveAs() } } - private void SaveConfigSettings() - { - Settings.Columns = WatchListView.AllColumns; - } + private void SaveConfigSettings() => Settings.Columns = WatchListView.AllColumns; private void SetMemoryDomain(string name) { @@ -602,7 +599,7 @@ private void SetMemoryDomain(string name) private void UpdateStatusBar(bool saved = false) { - var message = ""; + string message = ""; if (!string.IsNullOrWhiteSpace(_watches.CurrentFileName)) { if (saved) @@ -620,10 +617,7 @@ private void UpdateStatusBar(bool saved = false) MessageLabel.Text = message; } - private void UpdateWatchCount() - { - WatchCountLabel.Text = _watches.WatchCount + (_watches.WatchCount == 1 ? " watch" : " watches"); - } + private void UpdateWatchCount() => WatchCountLabel.Text = _watches.WatchCount + (_watches.WatchCount == 1 ? " watch" : " watches"); private void WatchListView_QueryItemBkColor(int index, RollColumn column, ref Color color) { @@ -697,19 +691,13 @@ private void WatchListView_QueryItemText(int index, RollColumn column, out strin } } - private void FileSubMenu_DropDownOpened(object sender, EventArgs e) - { - SaveMenuItem.Enabled = _watches.Changes; - } + private void FileSubMenu_DropDownOpened(object sender, EventArgs e) => SaveMenuItem.Enabled = _watches.Changes; - private void NewListMenuItem_Click(object sender, EventArgs e) - { - NewWatchList(false); - } + private void NewListMenuItem_Click(object sender, EventArgs e) => NewWatchList(false); private void OpenMenuItem_Click(object sender, EventArgs e) { - var append = sender == AppendMenuItem; + bool append = sender == AppendMenuItem; LoadWatchFile(GetWatchFileFromUser(_watches.CurrentFileName), append); } @@ -729,10 +717,7 @@ private void SaveMenuItem_Click(object sender, EventArgs e) } } - private void SaveAsMenuItem_Click(object sender, EventArgs e) - { - SaveAs(); - } + private void SaveAsMenuItem_Click(object sender, EventArgs e) => SaveAs(); private void RecentSubMenu_DropDownOpened(object sender, EventArgs e) => RecentSubMenu.ReplaceDropDownItems(Config!.RecentWatches.RecentMenu(this, LoadFileFromRecent, "Watches")); @@ -769,7 +754,7 @@ private void MemoryDomainsSubMenu_DropDownOpened(object sender, EventArgs e) private void NewWatchMenuItem_Click(object sender, EventArgs e) { - var we = new WatchEditor + WatchEditor we = new() { InitialLocation = this.ChildPointToScreen(WatchListView), MemoryDomains = MemoryDomains @@ -783,24 +768,18 @@ private void NewWatchMenuItem_Click(object sender, EventArgs e) GeneralUpdate(); } - private void EditWatchMenuItem_Click(object sender, EventArgs e) - { - EditWatch(); - } + private void EditWatchMenuItem_Click(object sender, EventArgs e) => EditWatch(); private void RemoveWatchMenuItem_Click(object sender, EventArgs e) { if (!WatchListView.AnyRowsSelected) return; - foreach (var index in SelectedIndices.OrderDescending().ToList()) _watches.RemoveAt(index); + foreach (int index in SelectedIndices.OrderDescending().ToList()) _watches.RemoveAt(index); WatchListView.RowCount = _watches.Count; GeneralUpdate(); UpdateWatchCount(); } - private void DuplicateWatchMenuItem_Click(object sender, EventArgs e) - { - EditWatch(duplicate: true); - } + private void DuplicateWatchMenuItem_Click(object sender, EventArgs e) => EditWatch(duplicate: true); private static (Watch A, Watch B) SplitWatch(Watch ab) { @@ -810,8 +789,8 @@ private static (Watch A, Watch B) SplitWatch(Watch ab) WatchSize.Word => WatchSize.Byte, _ => throw new InvalidOperationException() }; - var a = Watch.GenerateWatch(ab.Domain, ab.Address, newSize, ab.Type, ab.BigEndian, ab.Notes); - var b = Watch.GenerateWatch(ab.Domain, ab.Address + (int) newSize, newSize, ab.Type, ab.BigEndian, ab.Notes); + Watch a = Watch.GenerateWatch(ab.Domain, ab.Address, newSize, ab.Type, ab.BigEndian, ab.Notes); + Watch b = Watch.GenerateWatch(ab.Domain, ab.Address + (int) newSize, newSize, ab.Type, ab.BigEndian, ab.Notes); return ab.BigEndian ? (a, b) : (b, a); } @@ -826,8 +805,8 @@ private void SplitWatchAt(int index) private void SplitWatchMenuItem_Click(object sender, EventArgs e) { - var indices = SelectedIndices.ToList(); - for (var indexIndex = indices.Count - 1; indexIndex >= 0; indexIndex--) SplitWatchAt(indices[indexIndex]); + List indices = SelectedIndices.ToList(); + for (int indexIndex = indices.Count - 1; indexIndex >= 0; indexIndex--) SplitWatchAt(indices[indexIndex]); Changes(); UpdateWatchCount(); WatchListView.RowCount = _watches.Count; @@ -838,7 +817,7 @@ private void PokeAddressMenuItem_Click(object sender, EventArgs e) { if (SelectedWatches.Any()) { - var poke = new RamPoke(DialogController, SelectedWatches, MainForm.CheatList) + RamPoke poke = new(DialogController, SelectedWatches, MainForm.CheatList) { InitialLocation = this.ChildPointToScreen(WatchListView) }; @@ -852,7 +831,7 @@ private void PokeAddressMenuItem_Click(object sender, EventArgs e) private void FreezeAddressMenuItem_Click(object sender, EventArgs e) { - var allCheats = SelectedWatches.All(x => MainForm.CheatList.IsActive(x.Domain, x.Address)); + bool allCheats = SelectedWatches.All(x => MainForm.CheatList.IsActive(x.Domain, x.Address)); if (allCheats) { MainForm.CheatList.RemoveRange(SelectedWatches); @@ -880,13 +859,13 @@ private void ClearChangeCountsMenuItem_Click(object sender, EventArgs e) private void MoveUpMenuItem_Click(object sender, EventArgs e) { - var indexes = SelectedIndices.ToList(); + List indexes = SelectedIndices.ToList(); if (!indexes.Any() || indexes[0] == 0) { return; } - foreach (var index in indexes) + foreach (int index in indexes) { var watch = _watches[index]; _watches.RemoveAt(index); @@ -898,7 +877,7 @@ private void MoveUpMenuItem_Click(object sender, EventArgs e) var indices = indexes.Select(t => t - 1); WatchListView.DeselectAll(); - foreach (var t in indices) + foreach (int t in indices) { WatchListView.SelectRow(t, true); } @@ -908,14 +887,14 @@ private void MoveUpMenuItem_Click(object sender, EventArgs e) private void MoveDownMenuItem_Click(object sender, EventArgs e) { - var indices = SelectedIndices.ToList(); + List indices = SelectedIndices.ToList(); if (indices.Count == 0 || indices[^1] == _watches.Count - 1) // at end already { return; } - for (var i = indices.Count - 1; i >= 0; i--) + for (int i = indices.Count - 1; i >= 0; i--) { var watch = _watches[indices[i]]; _watches.RemoveAt(indices[i]); @@ -925,7 +904,7 @@ private void MoveDownMenuItem_Click(object sender, EventArgs e) var newIndices = indices.Select(t => t + 1); WatchListView.DeselectAll(); - foreach (var t in newIndices) + foreach (int t in newIndices) { WatchListView.SelectRow(t, true); } @@ -936,7 +915,7 @@ private void MoveDownMenuItem_Click(object sender, EventArgs e) private void MoveTopMenuItem_Click(object sender, EventArgs e) { - var indexes = SelectedIndices.ToList(); + List indexes = SelectedIndices.ToList(); if (!indexes.Any()) { return; @@ -953,7 +932,7 @@ private void MoveTopMenuItem_Click(object sender, EventArgs e) Changes(); WatchListView.DeselectAll(); - foreach (var t in indexes) + foreach (int t in indexes) { WatchListView.SelectRow(t, true); } @@ -963,27 +942,27 @@ private void MoveTopMenuItem_Click(object sender, EventArgs e) private void MoveBottomMenuItem_Click(object sender, EventArgs e) { - var indices = SelectedIndices.ToList(); + List indices = SelectedIndices.ToList(); if (indices.Count == 0) { return; } - for (var i = 0; i < indices.Count; i++) + for (int i = 0; i < indices.Count; i++) { var watch = _watches[indices[i] - i]; _watches.RemoveAt(indices[i] - i); _watches.Insert(_watches.Count, watch); } - var newInd = new List(); + List newInd = new(); for (int i = 0, x = _watches.Count - indices.Count; i < indices.Count; i++, x++) { newInd.Add(x); } WatchListView.DeselectAll(); - foreach (var t in newInd) + foreach (int t in newInd) { WatchListView.SelectRow(t, true); } @@ -995,10 +974,7 @@ private void MoveBottomMenuItem_Click(object sender, EventArgs e) private void SelectAllMenuItem_Click(object sender, EventArgs e) => WatchListView.ToggleSelectAll(); - private void SettingsSubMenu_DropDownOpened(object sender, EventArgs e) - { - WatchesOnScreenMenuItem.Checked = Config.DisplayRamWatch; - } + private void SettingsSubMenu_DropDownOpened(object sender, EventArgs e) => WatchesOnScreenMenuItem.Checked = Config.DisplayRamWatch; private void DefinePreviousValueSubMenu_DropDownOpened(object sender, EventArgs e) { @@ -1007,20 +983,11 @@ private void DefinePreviousValueSubMenu_DropDownOpened(object sender, EventArgs OriginalMenuItem.Checked = Config.RamWatchDefinePrevious == PreviousType.Original; } - private void PreviousFrameMenuItem_Click(object sender, EventArgs e) - { - Config.RamWatchDefinePrevious = PreviousType.LastFrame; - } + private void PreviousFrameMenuItem_Click(object sender, EventArgs e) => Config.RamWatchDefinePrevious = PreviousType.LastFrame; - private void LastChangeMenuItem_Click(object sender, EventArgs e) - { - Config.RamWatchDefinePrevious = PreviousType.LastChange; - } + private void LastChangeMenuItem_Click(object sender, EventArgs e) => Config.RamWatchDefinePrevious = PreviousType.LastChange; - private void OriginalMenuItem_Click(object sender, EventArgs e) - { - Config.RamWatchDefinePrevious = PreviousType.Original; - } + private void OriginalMenuItem_Click(object sender, EventArgs e) => Config.RamWatchDefinePrevious = PreviousType.Original; private void WatchesOnScreenMenuItem_Click(object sender, EventArgs e) { @@ -1036,6 +1003,7 @@ private void WatchesOnScreenMenuItem_Click(object sender, EventArgs e) } } + #pragma warning disable IDE0051 [RestoreDefaults] private void RestoreDefaultsMenuItem() { @@ -1052,6 +1020,7 @@ private void RestoreDefaultsMenuItem() SetColumns(); WatchListView.Refresh(); } + #pragma warning restore IDE0051 private void RamWatch_Load(object sender, EventArgs e) { @@ -1065,14 +1034,11 @@ private void RamWatch_Load(object sender, EventArgs e) MayPokeAllSelected; } - private void ColumnToggleCallback() - { - Settings.Columns = WatchListView.AllColumns; - } + private void ColumnToggleCallback() => Settings.Columns = WatchListView.AllColumns; private void RamWatch_DragDrop(object sender, DragEventArgs e) { - var filePaths = (string[])e.Data.GetData(DataFormats.FileDrop); + string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop); if (Path.GetExtension(filePaths[0]) == ".wch") { _watches.Load(filePaths[0], append: false); @@ -1118,7 +1084,7 @@ private void ListViewContextMenu_Opening(object sender, CancelEventArgs e) FreezeContextMenuItem.Visible = MayPokeAllSelected; - var allCheats = SelectedWatches.All(x => MainForm.CheatList.IsActive(x.Domain, x.Address)); + bool allCheats = SelectedWatches.All(x => MainForm.CheatList.IsActive(x.Domain, x.Address)); if (allCheats) { @@ -1138,14 +1104,11 @@ private void ListViewContextMenu_Opening(object sender, CancelEventArgs e) newToolStripMenuItem.Visible = !WatchListView.AnyRowsSelected; } - private void UnfreezeAllContextMenuItem_Click(object sender, EventArgs e) - { - MainForm.CheatList.RemoveAll(); - } + private void UnfreezeAllContextMenuItem_Click(object sender, EventArgs e) => MainForm.CheatList.RemoveAll(); private void ViewInHexEditorContextMenuItem_Click(object sender, EventArgs e) { - var selected = SelectedWatches.ToList(); + List selected = SelectedWatches.ToList(); if (selected.Any()) { Tools.Load(); @@ -1160,7 +1123,7 @@ private void ViewInHexEditorContextMenuItem_Click(object sender, EventArgs e) private void ReadBreakpointContextMenuItem_Click(object sender, EventArgs e) { - var selected = SelectedWatches.ToList(); + List selected = SelectedWatches.ToList(); if (selected.Any()) { @@ -1175,7 +1138,7 @@ private void ReadBreakpointContextMenuItem_Click(object sender, EventArgs e) private void WriteBreakpointContextMenuItem_Click(object sender, EventArgs e) { - var selected = SelectedWatches.ToList(); + List selected = SelectedWatches.ToList(); if (selected.Any()) { @@ -1215,19 +1178,13 @@ private void WatchListView_SelectedIndexChanged(object sender, EventArgs e) MayPokeAllSelected; } - private void WatchListView_MouseDoubleClick(object sender, MouseEventArgs e) - { - EditWatch(); - } + private void WatchListView_MouseDoubleClick(object sender, MouseEventArgs e) => EditWatch(); - private void WatchListView_ColumnClick(object sender, InputRoll.ColumnClickEventArgs e) - { - OrderColumn(e.Column); - } + private void WatchListView_ColumnClick(object sender, InputRoll.ColumnClickEventArgs e) => OrderColumn(e.Column); private void ErrorIconButton_Click(object sender, EventArgs e) { - var items = _watches + List items = _watches .Where(watch => !watch.IsValid) .ToList(); // enumerate because _watches is about to be changed @@ -1243,9 +1200,6 @@ private void ErrorIconButton_Click(object sender, EventArgs e) } // Stupid designer - protected void DragEnterWrapper(object sender, DragEventArgs e) - { - GenericDragEnter(sender, e); - } + protected void DragEnterWrapper(object sender, DragEventArgs e) => GenericDragEnter(sender, e); } } diff --git a/src/BizHawk.Client.EmuHawk/tools/Watch/WatchEditor.cs b/src/BizHawk.Client.EmuHawk/tools/Watch/WatchEditor.cs index 7b20ab3490d..6de11bf076a 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Watch/WatchEditor.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Watch/WatchEditor.cs @@ -65,7 +65,7 @@ private void RamWatchNewWatch_Load(object sender, EventArgs e) _ => SizeDropDown.SelectedItem }; - var index = DisplayTypeDropDown.Items.IndexOf(Watch.DisplayTypeToString(Watches[0].Type)); + int index = DisplayTypeDropDown.Items.IndexOf(Watch.DisplayTypeToString(Watches[0].Type)); DisplayTypeDropDown.SelectedItem = DisplayTypeDropDown.Items[index]; if (Watches.Count > 1) @@ -146,19 +146,19 @@ private void SetDisplayTypes() { default: case 0: - foreach (WatchDisplayType t in ByteWatch.ValidTypes) + foreach (var t in ByteWatch.ValidTypes) { DisplayTypeDropDown.Items.Add(Watch.DisplayTypeToString(t)); } break; case 1: - foreach (WatchDisplayType t in WordWatch.ValidTypes) + foreach (var t in WordWatch.ValidTypes) { DisplayTypeDropDown.Items.Add(Watch.DisplayTypeToString(t)); } break; case 2: - foreach (WatchDisplayType t in DWordWatch.ValidTypes) + foreach (var t in DWordWatch.ValidTypes) { DisplayTypeDropDown.Items.Add(Watch.DisplayTypeToString(t)); } @@ -174,7 +174,7 @@ private void SetBigEndianCheckBox() { if (Watches.Count > 1) { - var firstWasBE = Watches[0].BigEndian; + bool firstWasBE = Watches[0].BigEndian; if (Watches.TrueForAll(w => w.BigEndian == firstWasBE)) { BigEndianCheckBox.Checked = firstWasBE; @@ -211,10 +211,10 @@ private void Ok_Click(object sender, EventArgs e) default: case Mode.New: var domain = MemoryDomains.FirstOrDefault(d => d.Name == DomainDropDown.SelectedItem.ToString()); - var address = AddressBox.ToLong() ?? 0; - var notes = NotesBox.Text; + long address = AddressBox.ToLong() ?? 0; + string notes = NotesBox.Text; var type = Watch.StringToDisplayType(DisplayTypeDropDown.SelectedItem.ToString()); - var bigEndian = BigEndianCheckBox.Checked; + bool bigEndian = BigEndianCheckBox.Checked; switch (SizeDropDown.SelectedIndex) { case 0: @@ -233,7 +233,7 @@ private void Ok_Click(object sender, EventArgs e) DoEdit(); break; case Mode.Duplicate: - var tempWatchList = new List(); + List tempWatchList = new(); tempWatchList.AddRange(Watches); Watches.Clear(); foreach (var watch in tempWatchList) @@ -263,7 +263,7 @@ private void DoEdit() if (_changedSize) { - for (var i = 0; i < Watches.Count; i++) + for (int i = 0; i < Watches.Count; i++) { var size = SizeDropDown.SelectedIndex switch { @@ -310,9 +310,6 @@ private void SizeDropDown_SelectedIndexChanged(object sender, EventArgs e) } } - private void DisplayTypeDropDown_SelectedIndexChanged(object sender, EventArgs e) - { - _changedDisplayType = true; - } + private void DisplayTypeDropDown_SelectedIndexChanged(object sender, EventArgs e) => _changedDisplayType = true; } } diff --git a/src/BizHawk.Client.EmuHawk/tools/Watch/WatchValueBox.cs b/src/BizHawk.Client.EmuHawk/tools/Watch/WatchValueBox.cs index 08875e8cd3f..41d7768f388 100644 --- a/src/BizHawk.Client.EmuHawk/tools/Watch/WatchValueBox.cs +++ b/src/BizHawk.Client.EmuHawk/tools/Watch/WatchValueBox.cs @@ -24,14 +24,14 @@ public WatchSize ByteSize get => _size; set { - var changed = _size != value; + bool changed = _size != value; _size = value; if (changed) { SetMaxLength(); - var isTypeCompatible = value switch + bool isTypeCompatible = value switch { WatchSize.Byte => ByteWatch.ValidTypes.Any(t => t == _type), WatchSize.Word => WordWatch.ValidTypes.Any(t => t == _type), @@ -54,7 +54,7 @@ public WatchDisplayType Type get => _type; set { - var val = ToRawInt(); + int? val = ToRawInt(); _type = value; SetMaxLength(); SetFromRawInt(val); @@ -108,87 +108,57 @@ public override void ResetText() } else { - switch (Type) + Text = Type switch { - default: - case WatchDisplayType.Signed: - case WatchDisplayType.Unsigned: - Text = "0"; - break; - case WatchDisplayType.Hex: - Text = 0.ToHexString(MaxLength); - break; - case WatchDisplayType.FixedPoint_12_4: - case WatchDisplayType.FixedPoint_20_12: - case WatchDisplayType.FixedPoint_16_16: - case WatchDisplayType.Float: - Text = "0.0"; - break; - case WatchDisplayType.Binary: - Text = "0".PadLeft(((int)_size) * 8); - break; - } + WatchDisplayType.Hex => 0.ToHexString(MaxLength), + WatchDisplayType.FixedPoint_12_4 or WatchDisplayType.FixedPoint_20_12 or WatchDisplayType.FixedPoint_16_16 or WatchDisplayType.Float => "0.0", + WatchDisplayType.Binary => "0".PadLeft(((int)_size) * 8), + _ => "0", + }; } } private void SetMaxLength() { - switch (_type) + MaxLength = _type switch { - default: - MaxLength = 8; - break; - case WatchDisplayType.Binary: - MaxLength = _size switch - { - WatchSize.Byte => 8, - WatchSize.Word => 16, - _ => 8 - }; - break; - case WatchDisplayType.Hex: - MaxLength = _size switch - { - WatchSize.Byte => 2, - WatchSize.Word => 4, - WatchSize.DWord => 8, - _ => 2 - }; - break; - case WatchDisplayType.Signed: - MaxLength = _size switch - { - WatchSize.Byte => 4, - WatchSize.Word => 6, - WatchSize.DWord => 11, - _ => 4 - }; - break; - case WatchDisplayType.Unsigned: - MaxLength = _size switch - { - WatchSize.Byte => 3, - WatchSize.Word => 5, - WatchSize.DWord => 10, - _ => 3 - }; - break; - case WatchDisplayType.FixedPoint_12_4: - MaxLength = 10; - break; - case WatchDisplayType.Float: - MaxLength = 40; - break; - case WatchDisplayType.FixedPoint_20_12: - case WatchDisplayType.FixedPoint_16_16: - MaxLength = 24; - break; - } + WatchDisplayType.Binary => _size switch + { + WatchSize.Byte => 8, + WatchSize.Word => 16, + _ => 8 + }, + WatchDisplayType.Hex => _size switch + { + WatchSize.Byte => 2, + WatchSize.Word => 4, + WatchSize.DWord => 8, + _ => 2 + }, + WatchDisplayType.Signed => _size switch + { + WatchSize.Byte => 4, + WatchSize.Word => 6, + WatchSize.DWord => 11, + _ => 4 + }, + WatchDisplayType.Unsigned => _size switch + { + WatchSize.Byte => 3, + WatchSize.Word => 5, + WatchSize.DWord => 10, + _ => 3 + }, + WatchDisplayType.FixedPoint_12_4 => 10, + WatchDisplayType.Float => 40, + WatchDisplayType.FixedPoint_20_12 or WatchDisplayType.FixedPoint_16_16 => 24, + _ => 8, + }; } protected override void OnKeyDown(KeyEventArgs e) { - var text = string.IsNullOrWhiteSpace(Text) ? "0" : Text; + string text = string.IsNullOrWhiteSpace(Text) ? "0" : Text; if (e.KeyCode == Keys.Up) { switch (_type) @@ -208,7 +178,7 @@ protected override void OnKeyDown(KeyEventArgs e) Text = val.ToString(); break; case WatchDisplayType.Unsigned: - var uval = (uint)(ToRawInt() ?? 0); + uint uval = (uint)(ToRawInt() ?? 0); if (uval == MaxUnsignedInt) { uval = 0; @@ -221,7 +191,7 @@ protected override void OnKeyDown(KeyEventArgs e) Text = uval.ToString(); break; case WatchDisplayType.Binary: - var bVal = (uint)(ToRawInt() ?? 0); + uint bVal = (uint)(ToRawInt() ?? 0); if (bVal == MaxUnsignedInt) { bVal = 0; @@ -231,11 +201,11 @@ protected override void OnKeyDown(KeyEventArgs e) bVal++; } - var numBits = ((int)ByteSize) * 8; + int numBits = ((int)ByteSize) * 8; Text = Convert.ToString(bVal, 2).PadLeft(numBits, '0'); break; case WatchDisplayType.Hex: - var hexVal = (uint)(ToRawInt() ?? 0); + uint hexVal = (uint)(ToRawInt() ?? 0); if (hexVal == MaxUnsignedInt) { hexVal = 0; @@ -248,7 +218,7 @@ protected override void OnKeyDown(KeyEventArgs e) Text = hexVal.ToHexString(MaxLength); break; case WatchDisplayType.FixedPoint_12_4: - var f12val = double.Parse(text, NumberFormatInfo.InvariantInfo); + double f12val = double.Parse(text, NumberFormatInfo.InvariantInfo); if (f12val > Max12_4 - _12_4_Unit) { f12val = Min12_4; @@ -261,7 +231,7 @@ protected override void OnKeyDown(KeyEventArgs e) Text = f12val.ToString(NumberFormatInfo.InvariantInfo); break; case WatchDisplayType.FixedPoint_20_12: - var f20val = double.Parse(text, NumberFormatInfo.InvariantInfo); + double f20val = double.Parse(text, NumberFormatInfo.InvariantInfo); if (f20val > Max20_12 - _20_12_Unit) { f20val = Min20_12; @@ -274,7 +244,7 @@ protected override void OnKeyDown(KeyEventArgs e) Text = f20val.ToString(NumberFormatInfo.InvariantInfo); break; case WatchDisplayType.FixedPoint_16_16: - var f16val = double.Parse(text, NumberFormatInfo.InvariantInfo); + double f16val = double.Parse(text, NumberFormatInfo.InvariantInfo); if (f16val > Max16_16 - _16_16_Unit) { f16val = Min16_16; @@ -287,7 +257,7 @@ protected override void OnKeyDown(KeyEventArgs e) Text = f16val.ToString(NumberFormatInfo.InvariantInfo); break; case WatchDisplayType.Float: - var dVal = double.Parse(text, NumberFormatInfo.InvariantInfo); + double dVal = double.Parse(text, NumberFormatInfo.InvariantInfo); if (dVal > float.MaxValue - 1) { dVal = 0; @@ -320,7 +290,7 @@ protected override void OnKeyDown(KeyEventArgs e) Text = val.ToString(); break; case WatchDisplayType.Unsigned: - var uval = (uint)(ToRawInt() ?? 0); + uint uval = (uint)(ToRawInt() ?? 0); if (uval == 0) { uval = MaxUnsignedInt; @@ -333,7 +303,7 @@ protected override void OnKeyDown(KeyEventArgs e) Text = uval.ToString(); break; case WatchDisplayType.Binary: - var bVal = (uint)(ToRawInt() ?? 0); + uint bVal = (uint)(ToRawInt() ?? 0); if (bVal == 0) { bVal = MaxUnsignedInt; @@ -343,11 +313,11 @@ protected override void OnKeyDown(KeyEventArgs e) bVal--; } - var numBits = ((int)ByteSize) * 8; + int numBits = ((int)ByteSize) * 8; Text = Convert.ToString(bVal, 2).PadLeft(numBits, '0'); break; case WatchDisplayType.Hex: - var hexVal = (uint)(ToRawInt() ?? 0); + uint hexVal = (uint)(ToRawInt() ?? 0); if (hexVal == 0) { hexVal = MaxUnsignedInt; @@ -360,7 +330,7 @@ protected override void OnKeyDown(KeyEventArgs e) Text = hexVal.ToHexString(MaxLength); break; case WatchDisplayType.FixedPoint_12_4: - var f12val = double.Parse(text, NumberFormatInfo.InvariantInfo); + double f12val = double.Parse(text, NumberFormatInfo.InvariantInfo); if (f12val < Min12_4 + _12_4_Unit) { f12val = Max12_4; @@ -373,7 +343,7 @@ protected override void OnKeyDown(KeyEventArgs e) Text = f12val.ToString(NumberFormatInfo.InvariantInfo); break; case WatchDisplayType.FixedPoint_20_12: - var f20val = double.Parse(text, NumberFormatInfo.InvariantInfo); + double f20val = double.Parse(text, NumberFormatInfo.InvariantInfo); if (f20val < Min20_12 + _20_12_Unit) { f20val = Max20_12; @@ -386,7 +356,7 @@ protected override void OnKeyDown(KeyEventArgs e) Text = f20val.ToString(NumberFormatInfo.InvariantInfo); break; case WatchDisplayType.FixedPoint_16_16: - var f16val = double.Parse(text, NumberFormatInfo.InvariantInfo); + double f16val = double.Parse(text, NumberFormatInfo.InvariantInfo); if (f16val < Min16_16 + _16_16_Unit) { f16val = Max16_16; @@ -399,7 +369,7 @@ protected override void OnKeyDown(KeyEventArgs e) Text = f16val.ToString(NumberFormatInfo.InvariantInfo); break; case WatchDisplayType.Float: - var dval = double.Parse(text, NumberFormatInfo.InvariantInfo); + double dval = double.Parse(text, NumberFormatInfo.InvariantInfo); if (dval < float.MinValue + 1) { dval = 0; @@ -467,12 +437,12 @@ public void SetFromRawInt(int? val) Text = val.Value.ToString(); break; case WatchDisplayType.Unsigned: - var uval = (uint)val.Value; + uint uval = (uint)val.Value; Text = uval.ToString(); break; case WatchDisplayType.Binary: - var bVal = (uint)val.Value; - var numBits = ((int)ByteSize) * 8; + uint bVal = (uint)val.Value; + int numBits = ((int)ByteSize) * 8; Text = Convert.ToString(bVal, 2).PadLeft(numBits, '0'); break; case WatchDisplayType.Hex: @@ -488,7 +458,7 @@ public void SetFromRawInt(int? val) Text = (val.Value / 65536.0).ToString("F5", NumberFormatInfo.InvariantInfo); break; case WatchDisplayType.Float: - var bytes = BitConverter.GetBytes(val.Value); + byte[] bytes = BitConverter.GetBytes(val.Value); float _float = BitConverter.ToSingle(bytes, 0); Text = _float.ToString("F6", NumberFormatInfo.InvariantInfo); break; diff --git a/src/BizHawk.Common/BPSPatcher.cs b/src/BizHawk.Common/BPSPatcher.cs index 3b6bc1e5f6f..b4e52bab163 100644 --- a/src/BizHawk.Common/BPSPatcher.cs +++ b/src/BizHawk.Common/BPSPatcher.cs @@ -24,7 +24,7 @@ public static int DecodeVarInt(ReadOnlySpan data, ref int i) ulong num = 0, mul = 1; while (true) { - var x = data[i++]; + byte x = data[i++]; num += (x & 0b0111_1111UL) * mul; if ((x & 0b1000_0000UL) is not 0UL) break; mul <<= 7; @@ -52,10 +52,10 @@ public static int DecodeVarInt(ReadOnlySpan data, ref int i) public BPSPayload(ReadOnlySpan dataWithHeader) { _isValid = true; - var i = 4; + int i = 4; _sourceSize = DecodeVarInt(dataWithHeader, ref i); TargetSize = DecodeVarInt(dataWithHeader, ref i); - var metadataSize = DecodeVarInt(dataWithHeader, ref i); + int metadataSize = DecodeVarInt(dataWithHeader, ref i); if (metadataSize is not 0) { Console.WriteLine($"ignoring {metadataSize} bytes of .bps metadata"); @@ -73,15 +73,15 @@ public bool DoPatch(ReadOnlySpan baseRom, Span target) if (!_isValid) throw new InvalidOperationException(ERR_MSG_UNINIT); if (target.Length != TargetSize) throw new ArgumentException(message: $"target buffer too {(target.Length < TargetSize ? "small" : "large")}", paramName: nameof(target)); if (baseRom.Length != _sourceSize) throw new ArgumentException(message: $"target buffer too {(baseRom.Length < _sourceSize ? "small" : "large")}", paramName: nameof(baseRom)); - var checksumsMatch = CheckCRC(data: baseRom, reversedChecksum: _sourceChecksum); - var outputOffset = 0; - var sourceRelOffset = 0; - var targetRelOffset = 0; - var i = 0; + bool checksumsMatch = CheckCRC(data: baseRom, reversedChecksum: _sourceChecksum); + int outputOffset = 0; + int sourceRelOffset = 0; + int targetRelOffset = 0; + int i = 0; while (i < _data.Length) { - var actionAndLength = DecodeVarInt(_data, ref i); - var length = (actionAndLength >> 2) + 1; + int actionAndLength = DecodeVarInt(_data, ref i); + int length = (actionAndLength >> 2) + 1; switch (actionAndLength & 0b11) { case 0b00: // SourceRead @@ -95,13 +95,13 @@ public bool DoPatch(ReadOnlySpan baseRom, Span target) while (length-- is not 0) target[outputOffset++] = _data[i++]; break; case 0b10: // SourceCopy - var offset = DecodeVarInt(_data, ref i); + int offset = DecodeVarInt(_data, ref i); if ((offset & 1) is 0) sourceRelOffset += offset >> 1; else sourceRelOffset -= offset >> 1; while (length-- is not 0) target[outputOffset++] = baseRom[sourceRelOffset++]; break; case 0b11: // TargetCopy - var offset1 = DecodeVarInt(_data, ref i); + int offset1 = DecodeVarInt(_data, ref i); if ((offset1 & 1) is 0) targetRelOffset += offset1 >> 1; else targetRelOffset -= offset1 >> 1; while (length-- is not 0) target[outputOffset++] = target[targetRelOffset++]; @@ -141,14 +141,14 @@ internal static void CheckRomSize(ReadOnlySpan rom) List<(int PatchOffset, int TargetOffset, int Size, bool IsRLE)> records = new(); try { - var i = 0; + int i = 0; while (i != data.Length) { - var targetOffset = (data[i++] * 0x10000) | (data[i++] * 0x100) | data[i++]; - var size = (data[i++] * 0x100) | data[i++]; + int targetOffset = (data[i++] * 0x10000) | (data[i++] * 0x100) | data[i++]; + int size = (data[i++] * 0x100) | data[i++]; if (size is 0) { - var rleSize = (data[i++] * 0x100) | data[i++]; + int rleSize = (data[i++] * 0x100) | data[i++]; Debug.Assert(rleSize is not 0); records.Add((i, targetOffset, rleSize, true)); i++; @@ -192,12 +192,12 @@ internal void DoPatch(Span rom) { if (isRLE) { - var value = _data[patchOffset]; + byte value = _data[patchOffset]; for (int j = targetOffset, endExclusive = j + size; j < endExclusive; j++) rom[j] = value; } else { - for (var j = 0; j < size; j++) rom[targetOffset + j] = _data[patchOffset + j]; + for (int j = 0; j < size; j++) rom[targetOffset + j] = _data[patchOffset + j]; } } } @@ -232,7 +232,7 @@ public static bool IsIPSFile(ReadOnlySpan dataWithHeader) /// always allocates a new array public static byte[] Patch(ReadOnlySpan baseRom, BPSPayload patch, out bool checksumsMatch) { - var target = new byte[patch.TargetSize]; + byte[] target = new byte[patch.TargetSize]; checksumsMatch = patch.DoPatch(baseRom: baseRom, target: target); return target; } @@ -240,9 +240,9 @@ public static byte[] Patch(ReadOnlySpan baseRom, BPSPayload patch, out boo /// may patch in place, returning , or allocate a new array public static byte[] Patch(byte[] baseRom, IPSPayload patch) { - var rom = baseRom; - var last = patch.Records[patch.Records.Count - 1]; - var reqSize = last.TargetOffset + last.Size; + byte[] rom = baseRom; + var (PatchOffset, TargetOffset, Size, IsRLE) = patch.Records[patch.Records.Count - 1]; + int reqSize = TargetOffset + Size; if (baseRom.Length < reqSize) { rom = new byte[reqSize]; @@ -257,8 +257,8 @@ public static byte[] Patch(byte[] baseRom, IPSPayload patch) public static bool TryPatchInPlace(Span rom, IPSPayload patch) { IPSPayload.CheckRomSize(rom); - var last = patch.Records[patch.Records.Count - 1]; - if (rom.Length < last.TargetOffset + last.Size) return false; + var (PatchOffset, TargetOffset, Size, IsRLE) = patch.Records[patch.Records.Count - 1]; + if (rom.Length < TargetOffset + Size) return false; patch.DoPatch(rom); return true; } diff --git a/src/BizHawk.Common/BinaryQuickSerializer.cs b/src/BizHawk.Common/BinaryQuickSerializer.cs index fcb487708d0..f37a5653094 100644 --- a/src/BizHawk.Common/BinaryQuickSerializer.cs +++ b/src/BizHawk.Common/BinaryQuickSerializer.cs @@ -21,13 +21,10 @@ private static MethodInfo FromExpression(Expression e) ? caller.Method : throw new ArgumentException(message: "Expression must be a method call", paramName: nameof(e)); - private static MethodInfo Method(Expression> f) - { - return FromExpression(f.Body); - } + private static MethodInfo Method(Expression> f) => FromExpression(f.Body); - private static readonly Dictionary Readhandlers = new Dictionary(); - private static readonly Dictionary Writehandlers = new Dictionary(); + private static readonly Dictionary Readhandlers = new(); + private static readonly Dictionary Writehandlers = new(); private static void AddR(Expression> f) { @@ -100,13 +97,13 @@ public SerializationFactory(Type type, Reader read, Writer write) private static SerializationFactory CreateFactory(Type t) { - var fields = DeepEquality.GetAllFields(t) + List fields = DeepEquality.GetAllFields(t) ////.OrderBy(fi => (int)fi.GetManagedOffset()) // [StructLayout.Sequential] doesn't work with this .OrderBy(fi => (int)Marshal.OffsetOf(t, fi.Name)) .ToList(); - var rmeth = new DynamicMethod($"{t.Name}_r", null, new[] { typeof(object), typeof(BinaryReader) }, true); - var wmeth = new DynamicMethod($"{t.Name}_w", null, new[] { typeof(object), typeof(BinaryWriter) }, true); + DynamicMethod rmeth = new($"{t.Name}_r", null, new[] { typeof(object), typeof(BinaryReader) }, true); + DynamicMethod wmeth = new($"{t.Name}_w", null, new[] { typeof(object), typeof(BinaryWriter) }, true); { var il = rmeth.GetILGenerator(); @@ -169,7 +166,7 @@ private static SerializationFactory GetFactory(Type t) public static T Create(BinaryReader r) where T : new() { - T target = new T(); + T target = new(); Read(target, r); return target; } @@ -181,14 +178,8 @@ public static object Create(Type t, BinaryReader r) return target; } - public static void Read(object target, BinaryReader r) - { - GetFactory(target.GetType()).Read(target, r); - } + public static void Read(object target, BinaryReader r) => GetFactory(target.GetType()).Read(target, r); - public static void Write(object target, BinaryWriter w) - { - GetFactory(target.GetType()).Write(target, w); - } + public static void Write(object target, BinaryWriter w) => GetFactory(target.GetType()).Write(target, w); } } diff --git a/src/BizHawk.Common/Bit.cs b/src/BizHawk.Common/Bit.cs index fb1aff55ef0..b3d4d7c5606 100644 --- a/src/BizHawk.Common/Bit.cs +++ b/src/BizHawk.Common/Bit.cs @@ -60,10 +60,7 @@ public static implicit operator bool(Bit rhs) return rhs._val != 0; } - public override string ToString() - { - return _val.ToString(); - } + public override string ToString() => _val.ToString(); public static bool operator ==(Bit lhs, Bit rhs) { @@ -75,14 +72,8 @@ public override string ToString() return lhs._val != rhs._val; } - public override int GetHashCode() - { - return _val.GetHashCode(); - } + public override int GetHashCode() => _val.GetHashCode(); - public override bool Equals(object? obj) - { - return obj is Bit b && this == b; - } + public override bool Equals(object? obj) => obj is Bit b && this == b; } } diff --git a/src/BizHawk.Common/CustomCollections.cs b/src/BizHawk.Common/CustomCollections.cs index c89a4e540c0..dc042395246 100644 --- a/src/BizHawk.Common/CustomCollections.cs +++ b/src/BizHawk.Common/CustomCollections.cs @@ -13,7 +13,7 @@ namespace BizHawk.Common [Serializable] public class Bag : IEnumerable where TKey : notnull { - private readonly WorkingDictionary> dictionary = new WorkingDictionary>(); + private readonly WorkingDictionary> dictionary = new(); public IList Keys => dictionary.Keys.ToList(); @@ -59,7 +59,7 @@ public SortedList(IEnumerable collection) public virtual void Add(T item) { - var i = _list.BinarySearch(item); + int i = _list.BinarySearch(item); _list.Insert(i < 0 ? ~i : i, item); } @@ -75,14 +75,14 @@ public virtual void Add(T item) public virtual int IndexOf(T item) { - var i = _list.BinarySearch(item); + int i = _list.BinarySearch(item); return i < 0 ? -1 : i; } public virtual bool Remove(T item) { #if true - var i = _list.BinarySearch(item); + int i = _list.BinarySearch(item); if (i < 0) return false; _list.RemoveAt(i); return true; @@ -99,7 +99,7 @@ public virtual bool Remove(T item) /// Remove all items after the specific item (but not the given item). public virtual void RemoveAfter(T item) { - var startIndex = _list.BinarySearch(item); + int startIndex = _list.BinarySearch(item); if (startIndex < 0) { // If BinarySearch doesn't find the item, diff --git a/src/BizHawk.Common/DeepEquality.cs b/src/BizHawk.Common/DeepEquality.cs index c02de6f381f..2595eb3186e 100644 --- a/src/BizHawk.Common/DeepEquality.cs +++ b/src/BizHawk.Common/DeepEquality.cs @@ -81,8 +81,8 @@ public static bool DeepEquals(object? o1, object? o2) } if (o1 == null || o2 == null) return false; // not equal (above) and one is null - Type t1 = o1.GetType(); - Type t2 = o2.GetType(); + var t1 = o1.GetType(); + var t2 = o2.GetType(); if (t1 != t2) { return false; diff --git a/src/BizHawk.Common/DeltaSerializer.cs b/src/BizHawk.Common/DeltaSerializer.cs index c69d0fed54a..24d614f7775 100644 --- a/src/BizHawk.Common/DeltaSerializer.cs +++ b/src/BizHawk.Common/DeltaSerializer.cs @@ -32,24 +32,24 @@ public static ReadOnlySpan GetDelta(ReadOnlySpan original, ReadOnlyS throw new InvalidOperationException($"{nameof(orignalAsBytes.Length)} must equal {nameof(currentAsBytes.Length)}"); } - var index = 0; - var end = currentAsBytes.Length; + int index = 0; + int end = currentAsBytes.Length; var ret = new byte[end + 4].AsSpan(); // worst case scenario size (i.e. everything is different) - var retSize = 0; + int retSize = 0; while (index < end) { - var blockStart = index; + int blockStart = index; while (index < end && orignalAsBytes[index] == currentAsBytes[index]) { index++; } - var same = index - blockStart; + int same = index - blockStart; if (same < 4) // something changed, or we hit end of spans, count how many different bytes come after { - var different = 0; + int different = 0; while (index < end && same < 8) // in case we hit end of span before, this does nothing and different is 0 { if (orignalAsBytes[index] != currentAsBytes[index]) @@ -80,7 +80,7 @@ public static ReadOnlySpan GetDelta(ReadOnlySpan original, ReadOnlyS different = -different; // negative is a signal that these are different bytes MemoryMarshal.Write(ret.Slice(retSize, 4), ref different); retSize += 4; - for (var i = blockStart; i < index - same; i++) + for (int i = blockStart; i < index - same; i++) { ret[retSize++] = (byte)(orignalAsBytes[i] ^ currentAsBytes[i]); } @@ -124,10 +124,10 @@ public static void ApplyDelta(ReadOnlySpan original, Span current, Read throw new InvalidOperationException($"{nameof(orignalAsBytes.Length)} must equal {nameof(currentAsBytes.Length)}"); } - var dataPos = 0; - var dataEnd = currentAsBytes.Length; - var deltaPos = 0; - var deltaEnd = delta.Length; + int dataPos = 0; + int dataEnd = currentAsBytes.Length; + int deltaPos = 0; + int deltaEnd = delta.Length; while (deltaPos < deltaEnd) { @@ -136,7 +136,7 @@ public static void ApplyDelta(ReadOnlySpan original, Span current, Read throw new InvalidOperationException("Hit end of delta unexpectingly!"); } - var header = MemoryMarshal.Read(delta.Slice(deltaPos, 4)); + int header = MemoryMarshal.Read(delta.Slice(deltaPos, 4)); deltaPos += 4; if (header < 0) // difference block { @@ -147,7 +147,7 @@ public static void ApplyDelta(ReadOnlySpan original, Span current, Read throw new InvalidOperationException("Corrupt delta header!"); } - for (var i = 0; i < header; i++) + for (int i = 0; i < header; i++) { currentAsBytes[dataPos + i] = (byte)(orignalAsBytes[dataPos + i] ^ delta[deltaPos + i]); } diff --git a/src/BizHawk.Common/EndiannessUtils.cs b/src/BizHawk.Common/EndiannessUtils.cs index cb00446bb0d..39870643a5d 100644 --- a/src/BizHawk.Common/EndiannessUtils.cs +++ b/src/BizHawk.Common/EndiannessUtils.cs @@ -9,14 +9,12 @@ public static unsafe class EndiannessUtils public static void MutatingByteSwap16(Span a) { #if true //TODO benchmark (both methods work correctly); also there is another method involving shifting the (output copy of the) array over by 1 byte then manually writing every second byte - var l = a.Length; + int l = a.Length; Debug.Assert(l % 2 == 0); - fixed (byte* p = &a[0]) for (var i = 0; i < l; i += 2) + fixed (byte* p = &a[0]) for (int i = 0; i < l; i += 2) { - var b = p[i]; - p[i] = p[i + 1]; - p[i + 1] = b; - } + (p[i + 1], p[i]) = (p[i], p[i + 1]); + } #else Debug.Assert(a.Length % 2 == 0); var shorts = MemoryMarshal.Cast(a); @@ -28,17 +26,13 @@ public static void MutatingByteSwap16(Span a) public static void MutatingByteSwap32(Span a) { #if true //TODO benchmark (both methods work correctly) - var l = a.Length; + int l = a.Length; Debug.Assert(l % 4 == 0); - fixed (byte* p = &a[0]) for (var i = 0; i < l; i += 4) + fixed (byte* p = &a[0]) for (int i = 0; i < l; i += 4) { - var b = p[i]; - p[i] = p[i + 3]; - p[i + 3] = b; - b = p[i + 1]; - p[i + 1] = p[i + 2]; - p[i + 2] = b; - } + (p[i + 3], p[i]) = (p[i], p[i + 3]); + (p[i + 2], p[i + 1]) = (p[i + 1], p[i + 2]); + } #else Debug.Assert(a.Length % 4 == 0); var ints = MemoryMarshal.Cast(a); diff --git a/src/BizHawk.Common/Extensions/BufferExtensions.cs b/src/BizHawk.Common/Extensions/BufferExtensions.cs index b0a0c2b1f17..83b7d7bca52 100644 --- a/src/BizHawk.Common/Extensions/BufferExtensions.cs +++ b/src/BizHawk.Common/Extensions/BufferExtensions.cs @@ -55,8 +55,8 @@ public static unsafe void ReadFromHexFast(this byte[] buffer, string hex) /// public static string BytesToHexString(this byte[] bytes) { - var sb = new StringBuilder(); - foreach (var b in bytes) + StringBuilder sb = new(); + foreach (byte b in bytes) { sb.AppendFormat("{0:X2}", b); } @@ -66,7 +66,7 @@ public static string BytesToHexString(this byte[] bytes) public static bool FindBytes(this byte[] array, byte[] pattern) { - var fidx = 0; + int fidx = 0; int result = Array.FindIndex(array, 0, array.Length, (byte b) => { fidx = b == pattern[fidx] ? fidx + 1 : 0; diff --git a/src/BizHawk.Common/Extensions/CollectionExtensions.cs b/src/BizHawk.Common/Extensions/CollectionExtensions.cs index 8918099cccd..521c97f7f15 100644 --- a/src/BizHawk.Common/Extensions/CollectionExtensions.cs +++ b/src/BizHawk.Common/Extensions/CollectionExtensions.cs @@ -12,10 +12,7 @@ public static class CollectionExtensions public static IOrderedEnumerable OrderBy( this IEnumerable source, Func keySelector, - bool desc) - { - return desc ? source.OrderByDescending(keySelector) : source.OrderBy(keySelector); - } + bool desc) => desc ? source.OrderByDescending(keySelector) : source.OrderBy(keySelector); public static int LowerBoundBinarySearch(this IList list, Func keySelector, TKey key) where TKey : IComparable @@ -27,7 +24,7 @@ public static int LowerBoundBinarySearch(this IList list, Func(this IList list, Func keySelec while (min < max) { int mid = (max + min) / 2; - T midItem = list[mid]; - TKey midKey = keySelector(midItem); + var midItem = list[mid]; + var midKey = keySelector(midItem); int comp = midKey.CompareTo(key); if (comp < 0) { @@ -132,7 +129,7 @@ public static ReadOnlySpan ConcatArray(this ReadOnlySpan a, ReadOnlySpa { if (b.Length is 0) return a; if (a.Length is 0) return b; - var combinedLen = a.Length + b.Length; + int combinedLen = a.Length + b.Length; if (combinedLen < dest.Length) return Span.Empty; a.CopyTo(dest); b.CopyTo(dest.Slice(start: a.Length)); @@ -144,7 +141,7 @@ public static T[] ConcatArray(this T[] a, T[] b) { if (b.Length is 0) return a; if (a.Length is 0) return b; - var combined = new T[a.Length + b.Length]; + T[] combined = new T[a.Length + b.Length]; var returned = ((ReadOnlySpan) a).ConcatArray(b, combined); Debug.Assert(returned == combined); return combined; @@ -245,10 +242,10 @@ public static IOrderedEnumerable OrderDescending(this IEnumerable sourc public static int RemoveAll(this ICollection list, Predicate match) { if (list is List listImpl) return listImpl.RemoveAll(match); - var c = list.Count; + int c = list.Count; if (list is IList iList) { - for (var i = 0; i < iList.Count; i++) + for (int i = 0; i < iList.Count; i++) { if (match(iList[i])) iList.RemoveAt(i--); } @@ -271,10 +268,10 @@ private static T ReturnSelf(this T self) public static bool ReversedSequenceEqual(this ReadOnlySpan a, ReadOnlySpan b) where T : IEquatable { - var len = a.Length; + int len = a.Length; if (len != b.Length) return false; if (len is 0) return true; - var i = 0; + int i = 0; while (i < len) { if (!a[i].Equals(b[len - 1 - i])) return false; diff --git a/src/BizHawk.Common/Extensions/IOExtensions.cs b/src/BizHawk.Common/Extensions/IOExtensions.cs index 956b2747257..c3a0486e592 100644 --- a/src/BizHawk.Common/Extensions/IOExtensions.cs +++ b/src/BizHawk.Common/Extensions/IOExtensions.cs @@ -18,7 +18,7 @@ public static unsafe string GetString(this Encoding encoding, ReadOnlySpan public static byte[] ReadAllBytes(this Stream stream) { - var outStream = new MemoryStream(); + MemoryStream outStream = new(); stream.CopyTo(outStream); return outStream.ToArray(); @@ -27,10 +27,10 @@ public static byte[] ReadAllBytes(this Stream stream) public static byte[] ReadAllBytes(this BinaryReader br) { const int BUFF_SIZE = 4096; - var buffer = new byte[BUFF_SIZE]; + byte[] buffer = new byte[BUFF_SIZE]; int bytesRead; - var outStream = new MemoryStream(); + MemoryStream outStream = new(); while ((bytesRead = br.Read(buffer, 0, BUFF_SIZE)) > 0) { @@ -48,7 +48,7 @@ public static byte[] ReadAllBytes(this BinaryReader br) /// public static string ReadStringFixedUtf8(this BinaryReader r, int bytes) { - var read = new byte[bytes]; + byte[] read = new byte[bytes]; r.Read(read, 0, bytes); return Encoding.UTF8.GetString(read); } @@ -60,10 +60,10 @@ public static string ReadStringFixedUtf8(this BinaryReader r, int bytes) /// public static string ReadStringUtf8NullTerminated(this BinaryReader br) { - using var ms = new MemoryStream(); + using MemoryStream ms = new(); for (;;) { - var b = br.ReadByte(); + byte b = br.ReadByte(); if (b == 0) { return Encoding.UTF8.GetString(ms.ToArray()); @@ -105,14 +105,8 @@ public static void Write(this BinaryWriter bw, ushort[] buffer) } } - public static void WriteBit(this BinaryWriter bw, Bit bit) - { - bw.Write((bool)bit); - } + public static void WriteBit(this BinaryWriter bw, Bit bit) => bw.Write((bool)bit); - public static Bit ReadBit(this BinaryReader br) - { - return br.ReadBoolean(); - } + public static Bit ReadBit(this BinaryReader br) => br.ReadBoolean(); } } diff --git a/src/BizHawk.Common/Extensions/NumberExtensions.cs b/src/BizHawk.Common/Extensions/NumberExtensions.cs index 5a59b746798..a98b56df202 100644 --- a/src/BizHawk.Common/Extensions/NumberExtensions.cs +++ b/src/BizHawk.Common/Extensions/NumberExtensions.cs @@ -5,55 +5,25 @@ namespace BizHawk.Common.NumberExtensions { public static class NumberExtensions { - public static string ToHexString(this int n, int numDigits) - { - return string.Format($"{{0:X{numDigits}}}", n); - } + public static string ToHexString(this int n, int numDigits) => string.Format($"{{0:X{numDigits}}}", n); - public static string ToHexString(this uint n, int numDigits) - { - return string.Format($"{{0:X{numDigits}}}", n); - } + public static string ToHexString(this uint n, int numDigits) => string.Format($"{{0:X{numDigits}}}", n); - public static string ToHexString(this long n, int numDigits) - { - return string.Format($"{{0:X{numDigits}}}", n); - } + public static string ToHexString(this long n, int numDigits) => string.Format($"{{0:X{numDigits}}}", n); - public static string ToHexString(this ulong n, int numDigits) - { - return string.Format($"{{0:X{numDigits}}}", n); - } + public static string ToHexString(this ulong n, int numDigits) => string.Format($"{{0:X{numDigits}}}", n); - public static bool Bit(this byte b, int index) - { - return (b & (1 << index)) != 0; - } + public static bool Bit(this byte b, int index) => (b & (1 << index)) != 0; - public static bool Bit(this int b, int index) - { - return (b & (1 << index)) != 0; - } + public static bool Bit(this int b, int index) => (b & (1 << index)) != 0; - public static bool Bit(this ushort b, int index) - { - return (b & (1 << index)) != 0; - } + public static bool Bit(this ushort b, int index) => (b & (1 << index)) != 0; - public static bool In(this int i, params int[] options) - { - return options.Any(j => i == j); - } + public static bool In(this int i, params int[] options) => options.Any(j => i == j); - public static byte BinToBCD(this byte v) - { - return (byte)(((v / 10) * 16) + (v % 10)); - } + public static byte BinToBCD(this byte v) => (byte)(((v / 10) * 16) + (v % 10)); - public static byte BCDtoBin(this byte v) - { - return (byte)(((v / 16) * 10) + (v % 16)); - } + public static byte BCDtoBin(this byte v) => (byte)(((v / 16) * 10) + (v % 16)); /// /// Receives a number and returns the number of hexadecimal digits it is @@ -93,10 +63,7 @@ public static int NumHexDigits(this long i) /// /// The % operator is a remainder operator. (e.g. -1 mod 4 returns -1, not 3.) /// - public static int Mod(this int a, int b) - { - return a - (b * (int)Math.Floor((float)a / b)); - } + public static int Mod(this int a, int b) => a - (b * (int)Math.Floor((float)a / b)); /// /// Force the value to be strictly between min and max (both excluded) diff --git a/src/BizHawk.Common/Extensions/NumericStringExtensions.cs b/src/BizHawk.Common/Extensions/NumericStringExtensions.cs index 7db7040c3c5..4866430bb16 100644 --- a/src/BizHawk.Common/Extensions/NumericStringExtensions.cs +++ b/src/BizHawk.Common/Extensions/NumericStringExtensions.cs @@ -6,7 +6,7 @@ namespace BizHawk.Common.StringExtensions public static class NumericStringExtensions { /// iff is either '0' or '1' - public static bool IsBinary(this char c) => c == '0' || c == '1'; + public static bool IsBinary(this char c) => c is '0' or '1'; /// iff is not and all chars of are either '0' or '1' /// should exclude the prefix 0b diff --git a/src/BizHawk.Common/Extensions/PathExtensions.cs b/src/BizHawk.Common/Extensions/PathExtensions.cs index c00bcbef2d8..9f9c27c9ea8 100644 --- a/src/BizHawk.Common/Extensions/PathExtensions.cs +++ b/src/BizHawk.Common/Extensions/PathExtensions.cs @@ -19,8 +19,8 @@ public static bool IsSubfolderOf(this string? childPath, string? parentPath) if (OSTailoredCode.IsUnixHost) { #if true - var c = OSTailoredCode.SimpleSubshell("realpath", $"-Lm \"{childPath}\"", $"invalid path {childPath} or missing realpath binary"); - var p = OSTailoredCode.SimpleSubshell("realpath", $"-Lm \"{parentPath}\"", $"invalid path {parentPath} or missing realpath binary"); + string c = OSTailoredCode.SimpleSubshell("realpath", $"-Lm \"{childPath}\"", $"invalid path {childPath} or missing realpath binary"); + string p = OSTailoredCode.SimpleSubshell("realpath", $"-Lm \"{parentPath}\"", $"invalid path {parentPath} or missing realpath binary"); return c == p || c.StartsWithOrdinal($"{p}/"); #else // written for Unix port but may be useful for Windows when moving to .NET Core var parentUriPath = new Uri(parentPath.TrimEnd('.')).AbsolutePath.TrimEnd('/'); @@ -39,8 +39,8 @@ public static bool IsSubfolderOf(this string? childPath, string? parentPath) #endif } - var parentUri = new Uri(parentPath.RemoveSuffix(Path.DirectorySeparatorChar)); - for (var childUri = new DirectoryInfo(childPath); childUri != null; childUri = childUri.Parent) + Uri parentUri = new(parentPath.RemoveSuffix(Path.DirectorySeparatorChar)); + for (DirectoryInfo childUri = new(childPath); childUri != null; childUri = childUri.Parent) { if (new Uri(childUri.FullName) == parentUri) return true; } @@ -49,10 +49,7 @@ public static bool IsSubfolderOf(this string? childPath, string? parentPath) /// iff absolute (OS-dependent) /// - public static bool IsAbsolute(this string path) - { - return PathInternal.IsPathFullyQualified(path); - } + public static bool IsAbsolute(this string path) => PathInternal.IsPathFullyQualified(path); /// iff absolute (OS-dependent) /// that means it may return for invalid paths @@ -71,7 +68,7 @@ public static bool IsAbsolute(this string path) if (fromPath == null || toPath == null) return null; if (OSTailoredCode.IsUnixHost) { - var realpathOutput = OSTailoredCode.SimpleSubshell("realpath", $"--relative-to=\"{fromPath}\" \"{toPath}\"", $"invalid path {toPath}, invalid path {fromPath}, or missing realpath binary"); + string realpathOutput = OSTailoredCode.SimpleSubshell("realpath", $"--relative-to=\"{fromPath}\" \"{toPath}\"", $"invalid path {toPath}, invalid path {fromPath}, or missing realpath binary"); return !realpathOutput.StartsWithOrdinal("../") && realpathOutput != "." && realpathOutput != ".." ? $"./{realpathOutput}" : realpathOutput; } @@ -82,7 +79,7 @@ static FileAttributes GetPathAttribute(string path1) if (File.Exists(path1.SubstringBefore('|'))) return FileAttributes.Normal; throw new FileNotFoundException(); } - var path = new StringBuilder(260 /* = MAX_PATH */); + StringBuilder path = new(260 /* = MAX_PATH */); return Win32Imports.PathRelativePathTo(path, fromPath, GetPathAttribute(fromPath), toPath, GetPathAttribute(toPath)) ? path.ToString() : throw new ArgumentException(message: "Paths must have a common prefix", paramName: nameof(toPath)); @@ -100,9 +97,9 @@ public static string MakeAbsolute(this string path, string? cwd = null) else { // FileInfo for normalisation ("C:\a\b\..\c" => "C:\a\c") - var mycwd = cwd ?? (OSTailoredCode.IsUnixHost ? Environment.CurrentDirectory : CWDHacks.Get()); - var finalpath = $"{mycwd}/{path}"; - var fi = new FileInfo(finalpath); + string mycwd = cwd ?? (OSTailoredCode.IsUnixHost ? Environment.CurrentDirectory : CWDHacks.Get()); + string finalpath = $"{mycwd}/{path}"; + FileInfo fi = new(finalpath); return fi.FullName; } } @@ -125,7 +122,7 @@ public static string MakeAbsolute(this string path, string? cwd = null) if (!absolutePath.IsSubfolderOf(basePath)) return absolutePath; if (!OSTailoredCode.IsUnixHost) return absolutePath.Replace(basePath, ".").RemoveSuffix(Path.DirectorySeparatorChar); #if true // Unix implementation using realpath - var realpathOutput = OSTailoredCode.SimpleSubshell("realpath", $"--relative-base=\"{basePath}\" \"{absolutePath}\"", $"invalid path {absolutePath}, invalid path {basePath}, or missing realpath binary"); + string realpathOutput = OSTailoredCode.SimpleSubshell("realpath", $"--relative-base=\"{basePath}\" \"{absolutePath}\"", $"invalid path {absolutePath}, invalid path {basePath}, or missing realpath binary"); return !realpathOutput.StartsWithOrdinal("../") && realpathOutput != "." && realpathOutput != ".." ? $"./{realpathOutput}" : realpathOutput; #else // for some reason there were two Unix implementations in the codebase before me? --yoshi // alt. #1 @@ -185,7 +182,7 @@ public static string SpecialRecentsDir static PathUtils() { - var dirPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location); + string dirPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location); ExeDirectoryPath = OSTailoredCode.IsUnixHost ? string.IsNullOrEmpty(dirPath) || dirPath == "/" ? string.Empty : dirPath : string.IsNullOrEmpty(dirPath) ? throw new Exception("failed to get location of executable, very bad things must have happened") : dirPath.RemoveSuffix('\\'); @@ -194,7 +191,7 @@ static PathUtils() DataDirectoryPath = ExeDirectoryPath; if (OSTailoredCode.IsUnixHost) { - var envVar = Environment.GetEnvironmentVariable("BIZHAWK_DATA_HOME"); + string envVar = Environment.GetEnvironmentVariable("BIZHAWK_DATA_HOME"); try { envVar = envVar?.MakeAbsolute() ?? string.Empty; diff --git a/src/BizHawk.Common/Extensions/ReflectionExtensions.cs b/src/BizHawk.Common/Extensions/ReflectionExtensions.cs index 94ea1ee6501..8f1adaccab5 100644 --- a/src/BizHawk.Common/Extensions/ReflectionExtensions.cs +++ b/src/BizHawk.Common/Extensions/ReflectionExtensions.cs @@ -37,7 +37,7 @@ public static string GetDescription(this object obj) if (memInfo.Length > 0) { - var attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false); + object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false); if (attrs.Length > 0) { @@ -53,7 +53,7 @@ public static string GetDescription(this object obj) /// public static string DisplayName(this Type type) { - var attr = type.GetCustomAttributes(typeof(DisplayNameAttribute), false).FirstOrDefault(); + object attr = type.GetCustomAttributes(typeof(DisplayNameAttribute), false).FirstOrDefault(); return attr is DisplayNameAttribute displayName ? displayName.DisplayName : type.Name; } @@ -88,7 +88,7 @@ public static T GetEnumFromDescription(this string description) } } - return default(T); + return default; } /// @@ -98,15 +98,12 @@ public static IEnumerable GetEnumDescriptions(this Type type) { var vals = Enum.GetValues(type); - foreach (var v in vals) + foreach (object? v in vals) { yield return v.GetDescription(); } } - public static T GetAttribute(this object o) - { - return (T)o.GetType().GetCustomAttributes(typeof(T), false)[0]; - } + public static T GetAttribute(this object o) => (T)o.GetType().GetCustomAttributes(typeof(T), false)[0]; } } diff --git a/src/BizHawk.Common/Extensions/StringExtensions.cs b/src/BizHawk.Common/Extensions/StringExtensions.cs index 4a15b1b6a24..fd62fe8d02a 100644 --- a/src/BizHawk.Common/Extensions/StringExtensions.cs +++ b/src/BizHawk.Common/Extensions/StringExtensions.cs @@ -8,8 +8,8 @@ public static class StringExtensions { public static string CharCodepointsToString(byte[] array) { - var a = new char[array.Length]; - for (var i = 0; i < array.Length; i++) a[i] = char.ConvertFromUtf32(array[i])[0]; + char[] a = new char[array.Length]; + for (int i = 0; i < array.Length; i++) a[i] = char.ConvertFromUtf32(array[i])[0]; return new(a); } @@ -88,7 +88,7 @@ public static bool StartsWith(this string str, char c) /// public static string SubstringAfter(this string str, string delimiter, string notFoundValue) { - var index = str.IndexOf(delimiter, StringComparison.Ordinal); + int index = str.IndexOf(delimiter, StringComparison.Ordinal); return index < 0 ? notFoundValue : str.Substring(index + delimiter.Length, str.Length - index - delimiter.Length); } @@ -105,7 +105,7 @@ public static string SubstringAfterLast(this string str, char delimiter) /// public static string SubstringAfterLast(this string str, char delimiter, string notFoundValue) { - var index = str.LastIndexOf(delimiter); + int index = str.LastIndexOf(delimiter); return index < 0 ? notFoundValue : str.Substring(index + 1, str.Length - index - 1); } @@ -121,7 +121,7 @@ public static string SubstringAfterLast(this string str, char delimiter, string /// public static string SubstringBefore(this string str, char delimiter, string notFoundValue) { - var index = str.IndexOf(delimiter); + int index = str.IndexOf(delimiter); return index < 0 ? notFoundValue : str.Substring(0, index); } @@ -137,7 +137,7 @@ public static string SubstringBefore(this string str, char delimiter, string not /// public static string SubstringBeforeLast(this string str, char delimiter, string notFoundValue) { - var index = str.LastIndexOf(delimiter); + int index = str.LastIndexOf(delimiter); return index < 0 ? notFoundValue : str.Substring(0, index); } @@ -147,14 +147,14 @@ public static string SubstringBeforeLast(this string str, char delimiter, string /// public static string? SubstringBeforeOrNull(this string str, string delimiter) { - var index = str.IndexOf(delimiter, StringComparison.Ordinal); + int index = str.IndexOf(delimiter, StringComparison.Ordinal); return index < 0 ? null : str.Substring(0, index); } public static byte[] ToCharCodepointArray(this string str) { - var a = new byte[str.Length]; - for (var i = 0; i < str.Length; i++) a[i] = (byte) char.ConvertToUtf32(str, i); + byte[] a = new byte[str.Length]; + for (int i = 0; i < str.Length; i++) a[i] = (byte) char.ConvertToUtf32(str, i); return a; } diff --git a/src/BizHawk.Common/FFmpegService.cs b/src/BizHawk.Common/FFmpegService.cs index 87e0568e655..37abdaadc5e 100644 --- a/src/BizHawk.Common/FFmpegService.cs +++ b/src/BizHawk.Common/FFmpegService.cs @@ -28,17 +28,14 @@ public class AudioQueryResult public bool IsAudio; } - private static string[] Escape(IEnumerable args) - { - return args.Select(s => s.Contains(" ") ? $"\"{s}\"" : s).ToArray(); - } + private static string[] Escape(IEnumerable args) => args.Select(s => s.Contains(" ") ? $"\"{s}\"" : s).ToArray(); //note: accepts . or : in the stream stream/substream separator in the stream ID format, since that changed at some point in FFMPEG history //if someone has a better idea how to make the determination of whether an audio stream is available, I'm all ears - private static readonly Regex rxHasAudio = new Regex(@"Stream \#(\d*(\.|\:)\d*)\: Audio", RegexOptions.Compiled); + private static readonly Regex rxHasAudio = new(@"Stream \#(\d*(\.|\:)\d*)\: Audio", RegexOptions.Compiled); public static AudioQueryResult QueryAudio(string path) { - var ret = new AudioQueryResult(); + AudioQueryResult ret = new(); string stdout = Run("-i", path).Text; ret.IsAudio = rxHasAudio.Matches(stdout).Count > 0; return ret; @@ -68,14 +65,14 @@ public struct RunResults public static RunResults Run(params string[] args) { args = Escape(args); - StringBuilder sbCmdline = new StringBuilder(); + StringBuilder sbCmdline = new(); for (int i = 0; i < args.Length; i++) { sbCmdline.Append(args[i]); if (i != args.Length - 1) sbCmdline.Append(' '); } - ProcessStartInfo oInfo = new ProcessStartInfo(FFmpegPath, sbCmdline.ToString()) + ProcessStartInfo oInfo = new(FFmpegPath, sbCmdline.ToString()) { UseShellExecute = false, CreateNoWindow = true, @@ -83,13 +80,15 @@ public static RunResults Run(params string[] args) RedirectStandardError = true }; - Process proc = new Process(); - proc.StartInfo = oInfo; - Mutex m = new Mutex(); + Process proc = new() + { + StartInfo = oInfo + }; + Mutex m = new(); - var outputBuilder = new StringBuilder(); - var outputCloseEvent = new TaskCompletionSource(); - var errorCloseEvent = new TaskCompletionSource(); + StringBuilder outputBuilder = new(); + TaskCompletionSource outputCloseEvent = new(); + TaskCompletionSource errorCloseEvent = new(); proc.OutputDataReceived += (s, e) => { diff --git a/src/BizHawk.Common/HawkFile/HawkFile.cs b/src/BizHawk.Common/HawkFile/HawkFile.cs index ac544d53311..cb44a4e21b7 100644 --- a/src/BizHawk.Common/HawkFile/HawkFile.cs +++ b/src/BizHawk.Common/HawkFile/HawkFile.cs @@ -95,7 +95,7 @@ public HawkFile([HawkFilePath] string path, bool delayIOAndDearchive = false, bo if (DearchivalMethod != null && allowArchives) { - var ext = Path.GetExtension(path).ToLowerInvariant(); + string ext = Path.GetExtension(path).ToLowerInvariant(); if (DearchivalMethod.AllowedArchiveExtensions.Contains(ext)) { if (DearchivalMethod.CheckSignature(path, out _, out _)) @@ -165,7 +165,7 @@ public HawkFile BindArchiveMember(int index) if (_boundStream != null) throw new InvalidOperationException("stream already bound!"); if (_archiveItems == null || _extractor == null) throw new InvalidOperationException("not an archive"); - var archiveIndex = _archiveItems[index].ArchiveIndex; + int archiveIndex = _archiveItems[index].ArchiveIndex; _boundStream = new MemoryStream(); _extractor.ExtractFile(archiveIndex, _boundStream); _boundStream.Position = 0; @@ -194,7 +194,7 @@ private HawkFile BindByExtensionCore(IReadOnlyCollection extensions, boo { if (extensions.Count != 0) { - var candidates = _archiveItems.Where(item => extensions.Contains(Path.GetExtension(item.Name).ToLowerInvariant())).ToList(); + List candidates = _archiveItems.Where(item => extensions.Contains(Path.GetExtension(item.Name).ToLowerInvariant())).ToList(); if (onlyBindSingle ? candidates.Count == 1 : candidates.Count != 0) BindArchiveMember(candidates[0].Index); return this; } @@ -270,7 +270,7 @@ public void Dispose() public byte[] ReadAllBytes() { using var stream = GetStream(); - using var ms = new MemoryStream((int) stream.Length); + using MemoryStream ms = new((int) stream.Length); stream.CopyTo(ms); return ms.GetBuffer(); } @@ -293,7 +293,7 @@ public void Unbind() /// path / member path pair iff contains '|', otherwise private static (string, string)? SplitArchiveMemberPath([HawkFilePath] string path) { - var i = path.LastIndexOf('|'); + int i = path.LastIndexOf('|'); #if DEBUG if (path.IndexOf('|') != i) Console.WriteLine($"{nameof(HawkFile)} path contains multiple '|'"); #endif diff --git a/src/BizHawk.Common/IImportResolver.cs b/src/BizHawk.Common/IImportResolver.cs index 6cf628d1003..19f0dd73bac 100644 --- a/src/BizHawk.Common/IImportResolver.cs +++ b/src/BizHawk.Common/IImportResolver.cs @@ -25,8 +25,8 @@ public class DynamicLibraryImportResolver : IDisposable, IImportResolver static DynamicLibraryImportResolver() { - var currDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase)?.Replace("file:", "") ?? string.Empty; - var sysLibDir = Environment.GetEnvironmentVariable("BIZHAWK_INT_SYSLIB_PATH") ?? "/usr/lib"; + string currDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase)?.Replace("file:", "") ?? string.Empty; + string sysLibDir = Environment.GetEnvironmentVariable("BIZHAWK_INT_SYSLIB_PATH") ?? "/usr/lib"; UnixSearchPaths = new[] { $"{currDir}/", $"{currDir}/dll/", @@ -39,7 +39,7 @@ private static string UnixResolveFilePath(string orig) => orig.IsAbsolute() : UnixSearchPaths.Select(dir => dir + orig) .FirstOrDefault(s => { - var fi = new FileInfo(s); + FileInfo fi = new(s); return fi.Exists && (fi.Attributes & FileAttributes.Directory) != FileAttributes.Directory; }) ?? orig; // don't MakeAbsolute, just pass through and hope something lower-level magically makes it work @@ -107,19 +107,19 @@ public class InstanceDll : IDisposable, IImportResolver public InstanceDll(string dllPath) { // copy the dll to a temp directory - var path = TempFileManager.GetTempFilename(Path.GetFileNameWithoutExtension(dllPath), ".dll", false); + string path = TempFileManager.GetTempFilename(Path.GetFileNameWithoutExtension(dllPath), ".dll", false); File.Copy(dllPath, path, true); // try to locate dlls in the current directory (for libretro cores) // this isn't foolproof but it's a little better than nothing // setting PWD temporarily doesn't work. that'd be ideal since it supposedly gets searched early on, // but i guess not with SetDllDirectory in effect - var envpath = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Process); + string envpath = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Process); try { - var envpath_new = $"{Path.GetDirectoryName(path)};{envpath}"; + string envpath_new = $"{Path.GetDirectoryName(path)};{envpath}"; Environment.SetEnvironmentVariable("PATH", envpath_new, EnvironmentVariableTarget.Process); HModule = OSTailoredCode.LinkedLibManager.LoadOrThrow(path); // consider using LoadLibraryEx instead of shenanigans? - var newfname = TempFileManager.RenameTempFilenameForDelete(path); + string newfname = TempFileManager.RenameTempFilenameForDelete(path); File.Move(path, newfname); } catch @@ -153,7 +153,7 @@ public PatchImportResolver(params IImportResolver[] resolvers) public IntPtr GetProcAddrOrZero(string entryPoint) { - for (var i = _resolvers.Count - 1; i != 0; i--) + for (int i = _resolvers.Count - 1; i != 0; i--) { var ret = _resolvers[i].GetProcAddrOrZero(entryPoint); if (ret != IntPtr.Zero) return ret; diff --git a/src/BizHawk.Common/Log.cs b/src/BizHawk.Common/Log.cs index 4b73db550fb..b45aec5c9d1 100644 --- a/src/BizHawk.Common/Log.cs +++ b/src/BizHawk.Common/Log.cs @@ -20,7 +20,7 @@ static Log() } // -------------- Logging Domain Configuration -------------- - private static readonly List EnabledLogDomains = new List(); + private static readonly List EnabledLogDomains = new(); public static void EnableDomain(string domain) { @@ -52,10 +52,7 @@ public static void Note(string domain, string msg, params object[] vals) } } - public static void Error(string domain, string msg, params object[] vals) - { - LogAction(string.Format(msg, vals)); - } + public static void Error(string domain, string msg, params object[] vals) => LogAction(string.Format(msg, vals)); // -------------- Default Logger Action -------------- private static readonly bool LogToConsole = false; diff --git a/src/BizHawk.Common/OSTailoredCode.cs b/src/BizHawk.Common/OSTailoredCode.cs index 638d96df740..570d01f693b 100644 --- a/src/BizHawk.Common/OSTailoredCode.cs +++ b/src/BizHawk.Common/OSTailoredCode.cs @@ -47,7 +47,7 @@ public static class OSTailoredCode { // Win11 has ProductName == "Windows 10 Pro" MICROSOFT WHY https://stackoverflow.com/a/69922526 https://stackoverflow.com/a/70456554 // Version win10PlusVer = new(FileVersionInfo.GetVersionInfo(@"C:\Windows\System32\kernel32.dll").FileVersion.SubstringBefore(' ')); // bonus why: this doesn't work because the file's metadata wasn't updated - Version win10PlusVer = new(10, 0, int.TryParse(GetRegValue("CurrentBuild") ?? "19044", out var i) ? i : 19044); // still, leaving the Version wrapper here for when they inevitably do something stupid like decide to call Win11 11.0.x (or 10.1.x because they're incapable of doing anything sensible) + Version win10PlusVer = new(10, 0, int.TryParse(GetRegValue("CurrentBuild") ?? "19044", out int i) ? i : 19044); // still, leaving the Version wrapper here for when they inevitably do something stupid like decide to call Win11 11.0.x (or 10.1.x because they're incapable of doing anything sensible) return (win10PlusVer < new Version(10, 0, 22000) ? WindowsVersion._10 : WindowsVersion._11, win10PlusVer); } // ...else we're on 8.1. Can't be bothered writing code for KB installed check, not that I have a Win8.1 machine to test on anyway, so it gets a free pass (though I suspect `CurrentBuild` would work here too). --yoshi @@ -82,14 +82,14 @@ public static class OSTailoredCode return false; } - var isWine = LinkedLibManager.GetProcAddrOrZero(ntdll, "wine_get_version") != IntPtr.Zero; + bool isWine = LinkedLibManager.GetProcAddrOrZero(ntdll, "wine_get_version") != IntPtr.Zero; LinkedLibManager.FreeByPtr(ntdll); return isWine; }); public static bool IsWine => _isWine.Value; - private static readonly Lazy _LinkedLibManager = new Lazy(() => CurrentOS switch + private static readonly Lazy _LinkedLibManager = new(() => CurrentOS switch { DistinctOS.Linux => new UnixMonoLLManager(), DistinctOS.macOS => new UnixMonoLLManager(), @@ -210,10 +210,10 @@ public IntPtr LoadOrThrow(string dllToLoad) public string GetErrorMessage() { - var errCode = GetLastError(); - var sz = FormatMessageA(FORMAT_MESSAGE.ALLOCATE_BUFFER | FORMAT_MESSAGE.FROM_SYSTEM | FORMAT_MESSAGE.IGNORE_INSERTS, + uint errCode = GetLastError(); + int sz = FormatMessageA(FORMAT_MESSAGE.ALLOCATE_BUFFER | FORMAT_MESSAGE.FROM_SYSTEM | FORMAT_MESSAGE.IGNORE_INSERTS, IntPtr.Zero, errCode, 0, out var buffer, 1024, IntPtr.Zero); - var ret = Marshal.PtrToStringAnsi(buffer, sz); + string ret = Marshal.PtrToStringAnsi(buffer, sz); _ = LocalFree(buffer); return ret; } @@ -243,7 +243,8 @@ public enum WindowsVersion /// stderr is discarded if false /// OS is implicit and needs to be checked at callsite. Returned has not been started. public static Process ConstructSubshell(string cmd, string args, bool checkStdout = true, bool checkStderr = false) - => new Process { + => new() + { StartInfo = new ProcessStartInfo { Arguments = args, CreateNoWindow = true, diff --git a/src/BizHawk.Common/PropertyGridConverters/ConstrainedFloatConverter.cs b/src/BizHawk.Common/PropertyGridConverters/ConstrainedFloatConverter.cs index 0f004e793a2..131e0a6200d 100644 --- a/src/BizHawk.Common/PropertyGridConverters/ConstrainedFloatConverter.cs +++ b/src/BizHawk.Common/PropertyGridConverters/ConstrainedFloatConverter.cs @@ -12,14 +12,11 @@ namespace BizHawk.Common /// public class ConstrainedFloatConverter : TypeConverter { - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) - { - return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); - } + public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) => sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { - var range = (RangeAttribute)context.Instance + RangeAttribute range = (RangeAttribute)context.Instance .GetType() .GetProperty(context.PropertyDescriptor!.Name)! .GetCustomAttributes() @@ -32,7 +29,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c throw new FormatException($"{context.PropertyDescriptor.Name} can not be null"); } - if (float.TryParse(value.ToString(), out var floatVal)) + if (float.TryParse(value.ToString(), out float floatVal)) { return floatVal; } @@ -49,7 +46,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul if (destinationType == typeof(string)) { - var num = Convert.ToSingle(value); + float num = Convert.ToSingle(value); return num.ToString(NumberFormatInfo.InvariantInfo); } diff --git a/src/BizHawk.Common/PropertyGridConverters/ConstrainedIntConverter.cs b/src/BizHawk.Common/PropertyGridConverters/ConstrainedIntConverter.cs index 5dfe2053f19..4838ffc8445 100644 --- a/src/BizHawk.Common/PropertyGridConverters/ConstrainedIntConverter.cs +++ b/src/BizHawk.Common/PropertyGridConverters/ConstrainedIntConverter.cs @@ -12,14 +12,11 @@ namespace BizHawk.Common /// public class ConstrainedIntConverter : TypeConverter { - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) - { - return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); - } + public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) => sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { - var range = (RangeAttribute)context.Instance + RangeAttribute range = (RangeAttribute)context.Instance .GetType() .GetProperty(context.PropertyDescriptor!.Name)! .GetCustomAttributes() @@ -32,7 +29,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c throw new FormatException($"{context.PropertyDescriptor.Name} can not be null"); } - if (int.TryParse(value.ToString(), out var intVal)) + if (int.TryParse(value.ToString(), out int intVal)) { return intVal; } @@ -49,7 +46,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul if (destinationType == typeof(string)) { - var num = Convert.ToInt32(value); + int num = Convert.ToInt32(value); return num.ToString(); } diff --git a/src/BizHawk.Common/PropertyGridConverters/ConstrainedStringConverter.cs b/src/BizHawk.Common/PropertyGridConverters/ConstrainedStringConverter.cs index f355f1f0d37..b4d5dbc454b 100644 --- a/src/BizHawk.Common/PropertyGridConverters/ConstrainedStringConverter.cs +++ b/src/BizHawk.Common/PropertyGridConverters/ConstrainedStringConverter.cs @@ -12,14 +12,11 @@ namespace BizHawk.Common ///
public class ConstrainedStringConverter : TypeConverter { - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) - { - return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); - } + public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) => sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { - var maxLength = (MaxLengthAttribute)context.Instance + MaxLengthAttribute maxLength = (MaxLengthAttribute)context.Instance .GetType() .GetProperty(context.PropertyDescriptor!.Name)! .GetCustomAttributes() diff --git a/src/BizHawk.Common/PropertyGridConverters/DescribableEnumConverter.cs b/src/BizHawk.Common/PropertyGridConverters/DescribableEnumConverter.cs index 463e4d63851..bca4c8c1d73 100644 --- a/src/BizHawk.Common/PropertyGridConverters/DescribableEnumConverter.cs +++ b/src/BizHawk.Common/PropertyGridConverters/DescribableEnumConverter.cs @@ -22,7 +22,7 @@ public DescribableEnumConverter(Type type) : base(type) public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { - var valueStr = value?.ToString() ?? throw new ArgumentNullException(paramName: nameof(value)); + string valueStr = value?.ToString() ?? throw new ArgumentNullException(paramName: nameof(value)); return Enum.Parse( enumType, enumType.GetFields(BindingFlags.Public | BindingFlags.Static) @@ -33,7 +33,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destType) { - var fieldName = Enum.GetName(enumType, value ?? throw new ArgumentNullException(paramName: nameof(value))); + string fieldName = Enum.GetName(enumType, value ?? throw new ArgumentNullException(paramName: nameof(value))); if (fieldName != null) { var fieldInfo = enumType.GetField(fieldName); diff --git a/src/BizHawk.Common/Ranges.cs b/src/BizHawk.Common/Ranges.cs index cf95b170df3..4b5cd5ebf46 100644 --- a/src/BizHawk.Common/Ranges.cs +++ b/src/BizHawk.Common/Ranges.cs @@ -68,7 +68,7 @@ public static class RangeExtensions { private const ulong MIN_LONG_NEGATION_AS_ULONG = 9223372036854775808UL; - private static readonly ArithmeticException ExclusiveRangeMinValExc = new ArithmeticException("exclusive range end is min value of integral type"); + private static readonly ArithmeticException ExclusiveRangeMinValExc = new("exclusive range end is min value of integral type"); /// if it's contained in , or else whichever bound of is closest to public static T ConstrainWithin(this T value, Range range) where T : unmanaged, IComparable => value.CompareTo(range.Start) < 0 @@ -115,7 +115,7 @@ public static void Deconstruct(this Range range, out T start, out T endInc /// public static IEnumerable Enumerate(this Range range, double step) { - var d = range.Start; + double d = range.Start; while (d < range.EndInclusive) { yield return d; @@ -127,7 +127,7 @@ public static IEnumerable Enumerate(this Range range, double ste /// beware precision errors public static IEnumerable Enumerate(this Range range, float step) { - var f = range.Start; + float f = range.Start; while (f < range.EndInclusive) { yield return f; @@ -138,14 +138,14 @@ public static IEnumerable Enumerate(this Range range, float step) public static IEnumerable Enumerate(this Range range) { - var i = range.Start; + int i = range.Start; while (i < range.EndInclusive) yield return i++; yield return i; } public static IEnumerable Enumerate(this Range range) { - var l = range.Start; + long l = range.Start; while (l < range.EndInclusive) yield return l++; yield return l; } @@ -156,14 +156,14 @@ public static IEnumerable Enumerate(this Range range) public static IEnumerable Enumerate(this Range range) { - var i = range.Start; + uint i = range.Start; while (i < range.EndInclusive) yield return i++; yield return i; } public static IEnumerable Enumerate(this Range range) { - var l = range.Start; + ulong l = range.Start; while (l < range.EndInclusive) yield return l++; yield return l; } @@ -172,10 +172,10 @@ public static IEnumerable Enumerate(this Range range) public static Range GetImmutableCopy(this Range range) where T : unmanaged, IComparable => GetMutableCopy(range); - public static MutableRange GetMutableCopy(this Range range) where T : unmanaged, IComparable => new MutableRange(range.Start, range.EndInclusive); + public static MutableRange GetMutableCopy(this Range range) where T : unmanaged, IComparable => new(range.Start, range.EndInclusive); /// - public static MutableRange MutableRangeTo(this T start, T endInclusive) where T : unmanaged, IComparable => new MutableRange(start, endInclusive); + public static MutableRange MutableRangeTo(this T start, T endInclusive) where T : unmanaged, IComparable => new(start, endInclusive); /// public static MutableRange MutableRangeToExclusive(this byte start, byte endExclusive) => endExclusive == byte.MinValue diff --git a/src/BizHawk.Common/Serializer.cs b/src/BizHawk.Common/Serializer.cs index 9190eb916a0..b83060967bf 100644 --- a/src/BizHawk.Common/Serializer.cs +++ b/src/BizHawk.Common/Serializer.cs @@ -14,19 +14,19 @@ public unsafe class Serializer { public Serializer() { } - public bool IsReader => _isReader; + public bool IsReader { get; private set; } public bool IsWriter => !IsReader; - public bool IsText => _isText; + public bool IsText { get; private set; } - public BinaryReader BinaryReader => _br; + public BinaryReader BinaryReader { get; private set; } - public BinaryWriter BinaryWriter => _bw; + public BinaryWriter BinaryWriter { get; private set; } - public TextReader TextReader => _tr; + public TextReader TextReader { get; private set; } - public TextWriter TextWriter => _tw; + public TextWriter TextWriter { get; private set; } public Serializer(BinaryWriter bw) { @@ -48,50 +48,38 @@ public Serializer(TextReader tr) StartRead(tr); } - public static Serializer CreateBinaryWriter(BinaryWriter bw) - { - return new Serializer(bw); - } + public static Serializer CreateBinaryWriter(BinaryWriter bw) => new(bw); - public static Serializer CreateBinaryReader(BinaryReader br) - { - return new Serializer(br); - } + public static Serializer CreateBinaryReader(BinaryReader br) => new(br); - public static Serializer CreateTextWriter(TextWriter tw) - { - return new Serializer(tw); - } + public static Serializer CreateTextWriter(TextWriter tw) => new(tw); - public static Serializer CreateTextReader(TextReader tr) - { - return new Serializer(tr); - } + public static Serializer CreateTextReader(TextReader tr) => new(tr); public void StartWrite(BinaryWriter bw) { - _bw = bw; - _isReader = false; + BinaryWriter = bw; + IsReader = false; } public void StartRead(BinaryReader br) { - _br = br; - _isReader = true; + BinaryReader = br; + IsReader = true; } public void StartWrite(TextWriter tw) { - _tw = tw; - _isReader = false; - _isText = true; + TextWriter = tw; + IsReader = false; + IsText = true; } public void StartRead(TextReader tr) { - _tr = tr; - _isReader = true; - _isText = true; + TextReader = tr; + IsReader = true; + IsText = true; BeginTextBlock(); } @@ -102,7 +90,7 @@ public void BeginSection(string name) { if (IsWriter) { - _tw.WriteLine("[{0}]", name); + TextWriter.WriteLine("[{0}]", name); } else { @@ -114,12 +102,12 @@ public void BeginSection(string name) public void EndSection() { - var name = _sections.Pop(); + string name = _sections.Pop(); if (IsText) { if (IsWriter) { - _tw.WriteLine("[/{0}]", name); + TextWriter.WriteLine("[/{0}]", name); } else { @@ -136,17 +124,17 @@ public void SyncEnum(string name, ref T val) where T : struct throw new InvalidOperationException(); } - if (_isText) + if (IsText) { SyncEnumText(name, ref val); } else if (IsReader) { - val = (T)Enum.ToObject(typeof(T), _br.ReadInt32()); + val = (T)Enum.ToObject(typeof(T), BinaryReader.ReadInt32()); } else { - _bw.Write(Convert.ToInt32(val)); + BinaryWriter.Write(Convert.ToInt32(val)); } } @@ -161,7 +149,7 @@ public void SyncEnumText(string name, ref T val) where T : struct } else { - _tw.WriteLine("{0} {1}", name, val); + TextWriter.WriteLine("{0} {1}", name, val); } } @@ -173,11 +161,11 @@ public void Sync(string name, ref byte[] val, bool useNull) } else if (IsReader) { - val = _br.ReadByteBuffer(useNull); + val = BinaryReader.ReadByteBuffer(useNull); } else { - _bw.WriteByteBuffer(val); + BinaryWriter.WriteByteBuffer(val); } } @@ -197,8 +185,8 @@ public void SyncText(string name, ref byte[] val, bool useNull) } else { - var temp = val ?? Array.Empty(); - _tw.WriteLine("{0} {1}", name, temp.BytesToHexString()); + byte[] temp = val ?? Array.Empty(); + TextWriter.WriteLine("{0} {1}", name, temp.BytesToHexString()); } } @@ -210,7 +198,7 @@ public void Sync(string name, ref bool[] val, bool useNull) } else if (IsReader) { - val = _br.ReadByteBuffer(false).ToBoolBuffer(); + val = BinaryReader.ReadByteBuffer(false).ToBoolBuffer(); if (val == null && !useNull) { val = Array.Empty(); @@ -218,7 +206,7 @@ public void Sync(string name, ref bool[] val, bool useNull) } else { - _bw.WriteByteBuffer(val.ToUByteBuffer()); + BinaryWriter.WriteByteBuffer(val.ToUByteBuffer()); } } @@ -228,7 +216,7 @@ public void SyncText(string name, ref bool[] val, bool useNull) { if (Present(name)) { - var bytes = Item(name).HexStringToBytes(); + byte[] bytes = Item(name).HexStringToBytes(); val = bytes.ToBoolBuffer(); } @@ -239,8 +227,8 @@ public void SyncText(string name, ref bool[] val, bool useNull) } else { - var temp = val ?? Array.Empty(); - _tw.WriteLine("{0} {1}", name, temp.ToUByteBuffer().BytesToHexString()); + bool[] temp = val ?? Array.Empty(); + TextWriter.WriteLine("{0} {1}", name, temp.ToUByteBuffer().BytesToHexString()); } } public void Sync(string name, ref short[] val, bool useNull) @@ -251,7 +239,7 @@ public void Sync(string name, ref short[] val, bool useNull) } else if (IsReader) { - val = _br.ReadByteBuffer(false).ToShortBuffer(); + val = BinaryReader.ReadByteBuffer(false).ToShortBuffer(); if (val == null && !useNull) { val = Array.Empty(); @@ -259,7 +247,7 @@ public void Sync(string name, ref short[] val, bool useNull) } else { - _bw.WriteByteBuffer(val.ToUByteBuffer()); + BinaryWriter.WriteByteBuffer(val.ToUByteBuffer()); } } @@ -271,7 +259,7 @@ public void Sync(string name, ref ushort[] val, bool useNull) } else if (IsReader) { - val = _br.ReadByteBuffer(false).ToUShortBuffer(); + val = BinaryReader.ReadByteBuffer(false).ToUShortBuffer(); if (val == null && !useNull) { val = Array.Empty(); @@ -279,7 +267,7 @@ public void Sync(string name, ref ushort[] val, bool useNull) } else { - _bw.WriteByteBuffer(val.ToUByteBuffer()); + BinaryWriter.WriteByteBuffer(val.ToUByteBuffer()); } } @@ -289,7 +277,7 @@ public void SyncText(string name, ref short[] val, bool useNull) { if (Present(name)) { - var bytes = Item(name).HexStringToBytes(); + byte[] bytes = Item(name).HexStringToBytes(); val = bytes.ToShortBuffer(); } @@ -300,8 +288,8 @@ public void SyncText(string name, ref short[] val, bool useNull) } else { - var temp = val ?? Array.Empty(); - _tw.WriteLine("{0} {1}", name, temp.ToUByteBuffer().BytesToHexString()); + short[] temp = val ?? Array.Empty(); + TextWriter.WriteLine("{0} {1}", name, temp.ToUByteBuffer().BytesToHexString()); } } @@ -311,7 +299,7 @@ public void SyncText(string name, ref ushort[] val, bool useNull) { if (Present(name)) { - var bytes = Item(name).HexStringToBytes(); + byte[] bytes = Item(name).HexStringToBytes(); val = bytes.ToUShortBuffer(); } @@ -322,8 +310,8 @@ public void SyncText(string name, ref ushort[] val, bool useNull) } else { - var temp = val ?? Array.Empty(); - _tw.WriteLine("{0} {1}", name, temp.ToUByteBuffer().BytesToHexString()); + ushort[] temp = val ?? Array.Empty(); + TextWriter.WriteLine("{0} {1}", name, temp.ToUByteBuffer().BytesToHexString()); } } @@ -335,7 +323,7 @@ public void Sync(string name, ref int[] val, bool useNull) } else if (IsReader) { - val = _br.ReadByteBuffer(false).ToIntBuffer(); + val = BinaryReader.ReadByteBuffer(false).ToIntBuffer(); if (val == null && !useNull) { val = Array.Empty(); @@ -343,7 +331,7 @@ public void Sync(string name, ref int[] val, bool useNull) } else { - _bw.WriteByteBuffer(val.ToUByteBuffer()); + BinaryWriter.WriteByteBuffer(val.ToUByteBuffer()); } } @@ -353,7 +341,7 @@ public void SyncText(string name, ref int[] val, bool useNull) { if (Present(name)) { - var bytes = Item(name).HexStringToBytes(); + byte[] bytes = Item(name).HexStringToBytes(); val = bytes.ToIntBuffer(); } @@ -364,8 +352,8 @@ public void SyncText(string name, ref int[] val, bool useNull) } else { - var temp = val ?? Array.Empty(); - _tw.WriteLine("{0} {1}", name, temp.ToUByteBuffer().BytesToHexString()); + int[] temp = val ?? Array.Empty(); + TextWriter.WriteLine("{0} {1}", name, temp.ToUByteBuffer().BytesToHexString()); } } @@ -377,7 +365,7 @@ public void Sync(string name, ref uint[] val, bool useNull) } else if (IsReader) { - val = _br.ReadByteBuffer(false).ToUIntBuffer(); + val = BinaryReader.ReadByteBuffer(false).ToUIntBuffer(); if (val == null && !useNull) { val = Array.Empty(); @@ -385,7 +373,7 @@ public void Sync(string name, ref uint[] val, bool useNull) } else { - _bw.WriteByteBuffer(val.ToUByteBuffer()); + BinaryWriter.WriteByteBuffer(val.ToUByteBuffer()); } } @@ -395,7 +383,7 @@ public void SyncText(string name, ref uint[] val, bool useNull) { if (Present(name)) { - var bytes = Item(name).HexStringToBytes(); + byte[] bytes = Item(name).HexStringToBytes(); val = bytes.ToUIntBuffer(); } @@ -406,8 +394,8 @@ public void SyncText(string name, ref uint[] val, bool useNull) } else { - var temp = val ?? Array.Empty(); - _tw.WriteLine("{0} {1}", name, temp.ToUByteBuffer().BytesToHexString()); + uint[] temp = val ?? Array.Empty(); + TextWriter.WriteLine("{0} {1}", name, temp.ToUByteBuffer().BytesToHexString()); } } @@ -419,7 +407,7 @@ public void Sync(string name, ref float[] val, bool useNull) } else if (IsReader) { - val = _br.ReadByteBuffer(false).ToFloatBuffer(); + val = BinaryReader.ReadByteBuffer(false).ToFloatBuffer(); if (val == null && !useNull) { val = Array.Empty(); @@ -427,7 +415,7 @@ public void Sync(string name, ref float[] val, bool useNull) } else { - _bw.WriteByteBuffer(val.ToUByteBuffer()); + BinaryWriter.WriteByteBuffer(val.ToUByteBuffer()); } } @@ -437,7 +425,7 @@ public void SyncText(string name, ref float[] val, bool useNull) { if (Present(name)) { - var bytes = Item(name).HexStringToBytes(); + byte[] bytes = Item(name).HexStringToBytes(); val = bytes.ToFloatBuffer(); } @@ -448,8 +436,8 @@ public void SyncText(string name, ref float[] val, bool useNull) } else { - var temp = val ?? Array.Empty(); - _tw.WriteLine("{0} {1}", name, temp.ToUByteBuffer().BytesToHexString()); + float[] temp = val ?? Array.Empty(); + TextWriter.WriteLine("{0} {1}", name, temp.ToUByteBuffer().BytesToHexString()); } } @@ -461,7 +449,7 @@ public void Sync(string name, ref double[] val, bool useNull) } else if (IsReader) { - val = _br.ReadByteBuffer(false).ToDoubleBuffer(); + val = BinaryReader.ReadByteBuffer(false).ToDoubleBuffer(); if (val == null && !useNull) { val = Array.Empty(); @@ -469,7 +457,7 @@ public void Sync(string name, ref double[] val, bool useNull) } else { - _bw.WriteByteBuffer(val.ToUByteBuffer()); + BinaryWriter.WriteByteBuffer(val.ToUByteBuffer()); } } @@ -479,7 +467,7 @@ public void SyncText(string name, ref double[] val, bool useNull) { if (Present(name)) { - var bytes = Item(name).HexStringToBytes(); + byte[] bytes = Item(name).HexStringToBytes(); val = bytes.ToDoubleBuffer(); } @@ -490,8 +478,8 @@ public void SyncText(string name, ref double[] val, bool useNull) } else { - var temp = val ?? Array.Empty(); - _tw.WriteLine("{0} {1}", name, temp.ToUByteBuffer().BytesToHexString()); + double[] temp = val ?? Array.Empty(); + TextWriter.WriteLine("{0} {1}", name, temp.ToUByteBuffer().BytesToHexString()); } } @@ -705,17 +693,17 @@ public void SyncFixedString(string name, ref string val, int length) // TODO - this could be made more efficient perhaps just by writing values right out of the string.. if (IsReader) { - var buf = new char[length]; - if (_isText) + char[] buf = new char[length]; + if (IsText) { - _tr.Read(buf, 0, length); + TextReader.Read(buf, 0, length); } else { - _br.Read(buf, 0, length); + BinaryReader.Read(buf, 0, length); } - var len = 0; + int len = 0; for (; len < length; len++) { if (buf[len] == 0) @@ -733,17 +721,17 @@ public void SyncFixedString(string name, ref string val, int length) throw new InvalidOperationException($"{nameof(SyncFixedString)} too long"); } - var buf = val.ToCharArray(); - var remainder = new char[length - buf.Length]; + char[] buf = val.ToCharArray(); + char[] remainder = new char[length - buf.Length]; if (IsText) { - _tw.Write(buf); - _tw.Write(remainder); + TextWriter.Write(buf); + TextWriter.Write(remainder); } else { - _bw.Write(buf); - _bw.Write(remainder); + BinaryWriter.Write(buf); + BinaryWriter.Write(remainder); } } } @@ -753,27 +741,20 @@ public void SyncDelta(string name, T[] original, T[] current) { if (IsReader) { - var delta = Array.Empty(); + byte[] delta = Array.Empty(); Sync(name, ref delta, useNull: false); DeltaSerializer.ApplyDelta(original, current, delta); } else { - var delta = DeltaSerializer.GetDelta(original, current).ToArray(); // TODO: don't create array here (need .net update to write span to binary writer) + byte[] delta = DeltaSerializer.GetDelta(original, current).ToArray(); // TODO: don't create array here (need .net update to write span to binary writer) Sync(name, ref delta, useNull: false); } } - private BinaryReader _br; - private BinaryWriter _bw; - private TextReader _tr; - private TextWriter _tw; - - private bool _isText; - private bool _isReader; - private readonly Stack _sections = new Stack(); + private readonly Stack _sections = new(); private Section _readerSection, _currSection; - private readonly Stack
_sectionStack = new Stack
(); + private readonly Stack
_sectionStack = new(); private void BeginTextBlock() { @@ -783,22 +764,22 @@ private void BeginTextBlock() } _readerSection = new Section(); - var ss = new Stack
(); + Stack
ss = new(); ss.Push(_readerSection); var curs = _readerSection; - var rxEnd = new System.Text.RegularExpressions.Regex(@"\[/(.*?)\]", System.Text.RegularExpressions.RegexOptions.Compiled); - var rxBegin = new System.Text.RegularExpressions.Regex(@"\[(.*?)\]", System.Text.RegularExpressions.RegexOptions.Compiled); + System.Text.RegularExpressions.Regex rxEnd = new(@"\[/(.*?)\]", System.Text.RegularExpressions.RegexOptions.Compiled); + System.Text.RegularExpressions.Regex rxBegin = new(@"\[(.*?)\]", System.Text.RegularExpressions.RegexOptions.Compiled); // read the entire file into a data structure for flexi-parsing string str; - while ((str = _tr.ReadLine()) != null) + while ((str = TextReader.ReadLine()) != null) { var end = rxEnd.Match(str); var begin = rxBegin.Match(str); if (end.Success) { - var name = end.Groups[1].Value; + string name = end.Groups[1].Value; if (name != curs.Name) { throw new InvalidOperationException("Mis-formed savestate blob"); @@ -815,9 +796,9 @@ private void BeginTextBlock() } else if (begin.Success) { - var name = begin.Groups[1].Value; + string name = begin.Groups[1].Value; ss.Push(curs); - var news = new Section { Name = name }; + Section news = new() { Name = name }; curs.Add(name, news); curs = news; } @@ -829,8 +810,8 @@ private void BeginTextBlock() continue; } - var parts = str.Split(' '); - var key = parts[0]; + string[] parts = str.Split(' '); + string key = parts[0]; // UGLY: adds whole string instead of splitting the key. later, split the key, and have the individual Sync methods give up that responsibility curs.Items.Add(key, parts[1]); @@ -840,15 +821,9 @@ private void BeginTextBlock() _currSection = _readerSection; } - private string Item(string key) - { - return _currSection.Items[key]; - } + private string Item(string key) => _currSection.Items[key]; - private bool Present(string key) - { - return _currSection.Items.ContainsKey(key); - } + private bool Present(string key) => _currSection.Items.ContainsKey(key); private void SyncBuffer(string name, int elemsize, int len, void* ptr) { @@ -862,7 +837,7 @@ private void SyncBuffer(string name, int elemsize, int len, void* ptr) else { int todo = len * elemsize; - var temp = new byte[todo]; + byte[] temp = new byte[todo]; System.Runtime.InteropServices.Marshal.Copy(new IntPtr(ptr), temp, 0, todo); Sync(name, ref temp, false); } @@ -1000,15 +975,9 @@ private void SyncText(string name, ref bool val) } } - private void Read(ref Bit val) - { - val = _br.ReadBit(); - } + private void Read(ref Bit val) => val = BinaryReader.ReadBit(); - private void Write(ref Bit val) - { - _bw.WriteBit(val); - } + private void Write(ref Bit val) => BinaryWriter.WriteBit(val); private void ReadText(string name, ref Bit val) { @@ -1018,20 +987,11 @@ private void ReadText(string name, ref Bit val) } } - private void WriteText(string name, ref Bit val) - { - _tw.WriteLine("{0} {1}", name, (int)val); - } + private void WriteText(string name, ref Bit val) => TextWriter.WriteLine("{0} {1}", name, (int)val); - private void Read(ref byte val) - { - val = _br.ReadByte(); - } + private void Read(ref byte val) => val = BinaryReader.ReadByte(); - private void Write(ref byte val) - { - _bw.Write(val); - } + private void Write(ref byte val) => BinaryWriter.Write(val); private void ReadText(string name, ref byte val) { @@ -1040,20 +1000,11 @@ private void ReadText(string name, ref byte val) val = byte.Parse(Item(name).Replace("0x", ""), NumberStyles.HexNumber); } } - private void WriteText(string name, ref byte val) - { - _tw.WriteLine("{0} 0x{1:X2}", name, val); - } + private void WriteText(string name, ref byte val) => TextWriter.WriteLine("{0} 0x{1:X2}", name, val); - private void Read(ref ushort val) - { - val = _br.ReadUInt16(); - } + private void Read(ref ushort val) => val = BinaryReader.ReadUInt16(); - private void Write(ref ushort val) - { - _bw.Write(val); - } + private void Write(ref ushort val) => BinaryWriter.Write(val); private void ReadText(string name, ref ushort val) { @@ -1063,20 +1014,14 @@ private void ReadText(string name, ref ushort val) } } - private void WriteText(string name, ref ushort val) - { - _tw.WriteLine("{0} 0x{1:X4}", name, val); - } + private void WriteText(string name, ref ushort val) => TextWriter.WriteLine("{0} 0x{1:X4}", name, val); private void Read(ref uint val) { - { val = _br.ReadUInt32(); } + { val = BinaryReader.ReadUInt32(); } } - private void Write(ref uint val) - { - _bw.Write(val); - } + private void Write(ref uint val) => BinaryWriter.Write(val); private void ReadText(string name, ref uint val) { @@ -1086,20 +1031,11 @@ private void ReadText(string name, ref uint val) } } - private void WriteText(string name, ref uint val) - { - _tw.WriteLine("{0} 0x{1:X8}", name, val); - } + private void WriteText(string name, ref uint val) => TextWriter.WriteLine("{0} 0x{1:X8}", name, val); - private void Read(ref sbyte val) - { - val = _br.ReadSByte(); - } + private void Read(ref sbyte val) => val = BinaryReader.ReadSByte(); - private void Write(ref sbyte val) - { - _bw.Write(val); - } + private void Write(ref sbyte val) => BinaryWriter.Write(val); private void ReadText(string name, ref sbyte val) { @@ -1109,20 +1045,11 @@ private void ReadText(string name, ref sbyte val) } } - private void WriteText(string name, ref sbyte val) - { - _tw.WriteLine("{0} 0x{1:X2}", name, val); - } + private void WriteText(string name, ref sbyte val) => TextWriter.WriteLine("{0} 0x{1:X2}", name, val); - private void Read(ref short val) - { - val = _br.ReadInt16(); - } + private void Read(ref short val) => val = BinaryReader.ReadInt16(); - private void Write(ref short val) - { - _bw.Write(val); - } + private void Write(ref short val) => BinaryWriter.Write(val); private void ReadText(string name, ref short val) { @@ -1132,20 +1059,11 @@ private void ReadText(string name, ref short val) } } - private void WriteText(string name, ref short val) - { - _tw.WriteLine("{0} 0x{1:X4}", name, val); - } + private void WriteText(string name, ref short val) => TextWriter.WriteLine("{0} 0x{1:X4}", name, val); - private void Read(ref int val) - { - val = _br.ReadInt32(); - } + private void Read(ref int val) => val = BinaryReader.ReadInt32(); - private void Write(ref int val) - { - _bw.Write(val); - } + private void Write(ref int val) => BinaryWriter.Write(val); private void ReadText(string name, ref int val) { @@ -1155,30 +1073,15 @@ private void ReadText(string name, ref int val) } } - private void WriteText(string name, ref int val) - { - _tw.WriteLine("{0} 0x{1:X8}", name, val); - } + private void WriteText(string name, ref int val) => TextWriter.WriteLine("{0} 0x{1:X8}", name, val); - private void Read(ref long val) - { - val = _br.ReadInt64(); - } + private void Read(ref long val) => val = BinaryReader.ReadInt64(); - private void Write(ref long val) - { - _bw.Write(val); - } + private void Write(ref long val) => BinaryWriter.Write(val); - private void Read(ref ulong val) - { - val = _br.ReadUInt64(); - } + private void Read(ref ulong val) => val = BinaryReader.ReadUInt64(); - private void Write(ref ulong val) - { - _bw.Write(val); - } + private void Write(ref ulong val) => BinaryWriter.Write(val); private void ReadText(string name, ref long val) { @@ -1188,10 +1091,7 @@ private void ReadText(string name, ref long val) } } - private void WriteText(string name, ref long val) - { - _tw.WriteLine("{0} 0x{1:X16}", name, val); - } + private void WriteText(string name, ref long val) => TextWriter.WriteLine("{0} 0x{1:X16}", name, val); private void ReadText(string name, ref ulong val) { @@ -1201,30 +1101,15 @@ private void ReadText(string name, ref ulong val) } } - private void WriteText(string name, ref ulong val) - { - _tw.WriteLine("{0} 0x{1:X16}", name, val); - } + private void WriteText(string name, ref ulong val) => TextWriter.WriteLine("{0} 0x{1:X16}", name, val); - private void Read(ref float val) - { - val = _br.ReadSingle(); - } + private void Read(ref float val) => val = BinaryReader.ReadSingle(); - private void Write(ref float val) - { - _bw.Write(val); - } + private void Write(ref float val) => BinaryWriter.Write(val); - private void Read(ref double val) - { - val = _br.ReadDouble(); - } + private void Read(ref double val) => val = BinaryReader.ReadDouble(); - private void Write(ref double val) - { - _bw.Write(val); - } + private void Write(ref double val) => BinaryWriter.Write(val); private void ReadText(string name, ref float val) { @@ -1234,10 +1119,7 @@ private void ReadText(string name, ref float val) } } - private void WriteText(string name, ref float val) - { - _tw.WriteLine("{0} {1}", name, val); - } + private void WriteText(string name, ref float val) => TextWriter.WriteLine("{0} {1}", name, val); private void ReadText(string name, ref double val) { @@ -1247,20 +1129,11 @@ private void ReadText(string name, ref double val) } } - private void WriteText(string name, ref double val) - { - _tw.WriteLine("{0} {1}", name, val); - } + private void WriteText(string name, ref double val) => TextWriter.WriteLine("{0} {1}", name, val); - private void Read(ref bool val) - { - val = _br.ReadBoolean(); - } + private void Read(ref bool val) => val = BinaryReader.ReadBoolean(); - private void Write(ref bool val) - { - _bw.Write(val); - } + private void Write(ref bool val) => BinaryWriter.Write(val); private void ReadText(string name, ref bool val) { @@ -1269,15 +1142,12 @@ private void ReadText(string name, ref bool val) val = bool.Parse(Item(name)); } } - private void WriteText(string name, ref bool val) - { - _tw.WriteLine("{0} {1}", name, val); - } + private void WriteText(string name, ref bool val) => TextWriter.WriteLine("{0} {1}", name, val); private sealed class Section : Dictionary { public string Name = ""; - public readonly Dictionary Items = new Dictionary(); + public readonly Dictionary Items = new(); } } } diff --git a/src/BizHawk.Common/SettingsUtil.cs b/src/BizHawk.Common/SettingsUtil.cs index 25176ac7619..3a47c806ba2 100644 --- a/src/BizHawk.Common/SettingsUtil.cs +++ b/src/BizHawk.Common/SettingsUtil.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Reflection; using System.Reflection.Emit; using System.Collections.Concurrent; using System.ComponentModel; @@ -38,7 +37,7 @@ public static void SetDefaultValues(T obj) f.SetDefaultValues(obj, f.DefaultValues); } - private static readonly Dictionary IntTypes = new Dictionary + private static readonly Dictionary IntTypes = new() { { typeof(byte), OpCodes.Conv_U1 }, { typeof(sbyte), OpCodes.Conv_I1 }, @@ -54,9 +53,9 @@ public static void SetDefaultValues(T obj) private static DefaultValueSetter CreateSetter(Type t) { - var dyn = new DynamicMethod($"SetDefaultValues_{t.Name}", null, new[] { typeof(object), typeof(object[]) }, false); + DynamicMethod dyn = new($"SetDefaultValues_{t.Name}", null, new[] { typeof(object), typeof(object[]) }, false); var il = dyn.GetILGenerator(); - List DefaultValues = new List(); + List DefaultValues = new(); il.Emit(OpCodes.Ldarg_0); // arg0: object to set properties of il.Emit(OpCodes.Castclass, t); // cast to appropriate type @@ -65,14 +64,14 @@ private static DefaultValueSetter CreateSetter(Type t) { if (!prop.CanWrite) continue; - MethodInfo method = prop.GetSetMethod(true); + var method = prop.GetSetMethod(true); foreach (object attr in prop.GetCustomAttributes(true)) { if (attr is DefaultValueAttribute dvAttr) { - var value = dvAttr.Value; - Type desiredType = method.GetParameters()[0].ParameterType; - Type sourceType = value.GetType(); + object value = dvAttr.Value; + var desiredType = method.GetParameters()[0].ParameterType; + var sourceType = value.GetType(); int idx = DefaultValues.Count; DefaultValues.Add(value); diff --git a/src/BizHawk.Common/SimpleTime.cs b/src/BizHawk.Common/SimpleTime.cs index 74132174832..85588bf3b8e 100644 --- a/src/BizHawk.Common/SimpleTime.cs +++ b/src/BizHawk.Common/SimpleTime.cs @@ -8,7 +8,7 @@ public class SimpleTime : IDisposable { private readonly Action _callback; - private readonly Stopwatch _stopwatch = new Stopwatch(); + private readonly Stopwatch _stopwatch = new(); public SimpleTime(Action callback) { diff --git a/src/BizHawk.Common/SpanStream.cs b/src/BizHawk.Common/SpanStream.cs index 8052ea3a957..63e784d7e10 100644 --- a/src/BizHawk.Common/SpanStream.cs +++ b/src/BizHawk.Common/SpanStream.cs @@ -41,7 +41,7 @@ public unsafe int Read(Span buffer) { _buffer = new byte[buffer.Length]; } - var n = _stream.Read(_buffer, 0, buffer.Length); + int n = _stream.Read(_buffer, 0, buffer.Length); fixed(byte* p = buffer) { Marshal.Copy(_buffer, 0, (IntPtr)p, n); diff --git a/src/BizHawk.Common/TempFileManager.cs b/src/BizHawk.Common/TempFileManager.cs index 2beb37408aa..782386b65df 100644 --- a/src/BizHawk.Common/TempFileManager.cs +++ b/src/BizHawk.Common/TempFileManager.cs @@ -20,7 +20,7 @@ public static class TempFileManager public static string GetTempFilename(string friendlyName, string? dotAndExtension = null, bool delete = true) { string guidPart = Guid.NewGuid().ToString(); - var fname = $"biz-{System.Diagnostics.Process.GetCurrentProcess().Id}-{friendlyName}-{guidPart}{dotAndExtension ?? ""}"; + string fname = $"biz-{System.Diagnostics.Process.GetCurrentProcess().Id}-{friendlyName}-{guidPart}{dotAndExtension ?? ""}"; if (delete) { fname = RenameTempFilenameForDelete(fname); @@ -64,8 +64,8 @@ public static void Start() private static void ThreadProc() { // squirrely logic, trying not to create garbage - var knownTempDirs = new HashSet(); - var dis = new List(); + HashSet knownTempDirs = new(); + List dis = new(); for (;;) { lock (typeof(TempFileManager)) diff --git a/src/BizHawk.Common/Util.cs b/src/BizHawk.Common/Util.cs index 39b8a2f9a65..08456eaa3f6 100644 --- a/src/BizHawk.Common/Util.cs +++ b/src/BizHawk.Common/Util.cs @@ -20,10 +20,10 @@ public static void BreakDebuggerIfAttached() public static void CopyStream(Stream src, Stream dest, long len) { const int size = 0x2000; - var buffer = new byte[size]; + byte[] buffer = new byte[size]; while (len > 0) { - var n = src.Read(buffer, 0, (int) Math.Min(len, size)); + int n = src.Read(buffer, 0, (int) Math.Min(len, size)); dest.Write(buffer, 0, n); len -= n; } @@ -49,15 +49,15 @@ public static void CopyStream(Stream src, Stream dest, long len) /// TODO use and instead of using and keeping a reference to the array? --yoshi public static byte[] DecompressGzipFile(Stream src) { - var tmp = new byte[4]; + byte[] tmp = new byte[4]; if (src.Read(tmp, 0, 2) != 2) throw new InvalidOperationException("Unexpected end of stream"); if (tmp[0] != 0x1F || tmp[1] != 0x8B) throw new InvalidOperationException("GZIP header not present"); src.Seek(-4, SeekOrigin.End); src.Read(tmp, 0, 4); src.Seek(0, SeekOrigin.Begin); - using var gs = new GZipStream(src, CompressionMode.Decompress, true); - var data = new byte[BitConverter.ToInt32(tmp, 0)]; - using var ms = new MemoryStream(data); + using GZipStream gs = new(src, CompressionMode.Decompress, true); + byte[] data = new byte[BitConverter.ToInt32(tmp, 0)]; + using MemoryStream ms = new(data); gs.CopyTo(ms); return data; } @@ -129,25 +129,25 @@ public static byte[] HexStringToBytes(this string str) if (str.Length % 2 is not 0) throw new ArgumentException(message: "string length must be even (add 0 padding if necessary)", paramName: nameof(str)); static int CharToNybble(char c) { - if ('0' <= c && c <= '9') return c - 0x30; - if ('A' <= c && c <= 'F') return c - 0x37; - if ('a' <= c && c <= 'f') return c - 0x57; + if (c is >= '0' and <= '9') return c - 0x30; + if (c is >= 'A' and <= 'F') return c - 0x37; + if (c is >= 'a' and <= 'f') return c - 0x57; throw new ArgumentException(message: "not a hex digit", paramName: nameof(c)); } - using var ms = new MemoryStream(); + using MemoryStream ms = new(); for (int i = 0, l = str.Length / 2; i != l; i++) ms.WriteByte((byte) ((CharToNybble(str[2 * i]) << 4) + CharToNybble(str[2 * i + 1]))); return ms.ToArray(); } public static int Memcmp(void* a, void* b, int len) { - var ba = (byte*) a; - var bb = (byte*) b; - for (var i = 0; i != len; i++) + byte* ba = (byte*) a; + byte* bb = (byte*) b; + for (int i = 0; i != len; i++) { - var _a = ba[i]; - var _b = bb[i]; - var c = _a - _b; + byte _a = ba[i]; + byte _b = bb[i]; + int c = _a - _b; if (c != 0) return c; } return 0; @@ -155,19 +155,19 @@ public static int Memcmp(void* a, void* b, int len) public static void Memset(void* ptr, int val, int len) { - var bptr = (byte*) ptr; - for (var i = 0; i != len; i++) bptr[i] = (byte) val; + byte* bptr = (byte*) ptr; + for (int i = 0; i != len; i++) bptr[i] = (byte) val; } public static byte[]? ReadByteBuffer(this BinaryReader br, bool returnNull) { - var len = br.ReadInt32(); + int len = br.ReadInt32(); if (len == 0 && returnNull) return null; - var ret = new byte[len]; - var ofs = 0; + byte[] ret = new byte[len]; + int ofs = 0; while (len > 0) { - var done = br.Read(ret, ofs, len); + int done = br.Read(ret, ofs, len); ofs += done; len -= done; } @@ -177,23 +177,23 @@ public static void Memset(void* ptr, int val, int len) /// Any non-zero element is interpreted as . public static bool[] ToBoolBuffer(this byte[] buf) { - var ret = new bool[buf.Length]; + bool[] ret = new bool[buf.Length]; for (int i = 0, len = buf.Length; i != len; i++) ret[i] = buf[i] != 0; return ret; } public static double[] ToDoubleBuffer(this byte[] buf) { - var len = buf.Length; - var ret = new double[len / 8]; + int len = buf.Length; + double[] ret = new double[len / 8]; Buffer.BlockCopy(buf, 0, ret, 0, len); return ret; } public static float[] ToFloatBuffer(this byte[] buf) { - var len = buf.Length; - var ret = new float[len / 4]; + int len = buf.Length; + float[] ret = new float[len / 4]; Buffer.BlockCopy(buf, 0, ret, 0, len); return ret; } @@ -201,11 +201,11 @@ public static float[] ToFloatBuffer(this byte[] buf) /// Each set of 4 elements in becomes 1 element in the returned buffer. The first of each set is interpreted as the LSB, with the 4th being the MSB. Elements are used as raw bits without regard for sign. public static int[] ToIntBuffer(this byte[] buf) { - var len = buf.Length / 4; - var ret = new int[len]; + int len = buf.Length / 4; + int[] ret = new int[len]; unchecked { - for (var i = 0; i != len; i++) ret[i] = (buf[4 * i + 3] << 24) | (buf[4 * i + 2] << 16) | (buf[4 * i + 1] << 8) | buf[4 * i]; + for (int i = 0; i != len; i++) ret[i] = (buf[4 * i + 3] << 24) | (buf[4 * i + 2] << 16) | (buf[4 * i + 1] << 8) | buf[4 * i]; } return ret; } @@ -213,34 +213,34 @@ public static int[] ToIntBuffer(this byte[] buf) /// Each pair of elements in becomes 1 element in the returned buffer. The first of each pair is interpreted as the LSB. Elements are used as raw bits without regard for sign. public static short[] ToShortBuffer(this byte[] buf) { - var len = buf.Length / 2; - var ret = new short[len]; + int len = buf.Length / 2; + short[] ret = new short[len]; unchecked { - for (var i = 0; i != len; i++) ret[i] = (short) ((buf[2 * i + 1] << 8) | buf[2 * i]); + for (int i = 0; i != len; i++) ret[i] = (short) ((buf[2 * i + 1] << 8) | buf[2 * i]); } return ret; } public static byte[] ToUByteBuffer(this bool[] buf) { - var ret = new byte[buf.Length]; + byte[] ret = new byte[buf.Length]; for (int i = 0, len = buf.Length; i != len; i++) ret[i] = buf[i] ? (byte) 1 : (byte) 0; return ret; } public static byte[] ToUByteBuffer(this double[] buf) { - var len = buf.Length * 8; - var ret = new byte[len]; + int len = buf.Length * 8; + byte[] ret = new byte[len]; Buffer.BlockCopy(buf, 0, ret, 0, len); return ret; } public static byte[] ToUByteBuffer(this float[] buf) { - var len = buf.Length * 4; - var ret = new byte[len]; + int len = buf.Length * 4; + byte[] ret = new byte[len]; Buffer.BlockCopy(buf, 0, ret, 0, len); return ret; } @@ -248,11 +248,11 @@ public static byte[] ToUByteBuffer(this float[] buf) /// Each element of becomes 4 elements in the returned buffer, with the LSB coming first. Elements are used as raw bits without regard for sign. public static byte[] ToUByteBuffer(this int[] buf) { - var len = buf.Length; - var ret = new byte[4 * len]; + int len = buf.Length; + byte[] ret = new byte[4 * len]; unchecked { - for (var i = 0; i != len; i++) + for (int i = 0; i != len; i++) { ret[4 * i] = (byte) buf[i]; ret[4 * i + 1] = (byte) (buf[i] >> 8); @@ -266,11 +266,11 @@ public static byte[] ToUByteBuffer(this int[] buf) /// Each element of becomes 2 elements in the returned buffer, with the LSB coming first. Elements are used as raw bits without regard for sign. public static byte[] ToUByteBuffer(this short[] buf) { - var len = buf.Length; - var ret = new byte[2 * len]; + int len = buf.Length; + byte[] ret = new byte[2 * len]; unchecked { - for (var i = 0; i != len; i++) + for (int i = 0; i != len; i++) { ret[2 * i] = (byte) buf[i]; ret[2 * i + 1] = (byte) (buf[i] >> 8); @@ -282,11 +282,11 @@ public static byte[] ToUByteBuffer(this short[] buf) /// public static byte[] ToUByteBuffer(this uint[] buf) { - var len = buf.Length; - var ret = new byte[4 * len]; + int len = buf.Length; + byte[] ret = new byte[4 * len]; unchecked { - for (var i = 0; i != len; i++) + for (int i = 0; i != len; i++) { ret[4 * i] = (byte) buf[i]; ret[4 * i + 1] = (byte) (buf[i] >> 8); @@ -300,11 +300,11 @@ public static byte[] ToUByteBuffer(this uint[] buf) /// public static byte[] ToUByteBuffer(this ushort[] buf) { - var len = buf.Length; - var ret = new byte[2 * len]; + int len = buf.Length; + byte[] ret = new byte[2 * len]; unchecked { - for (var i = 0; i != len; i++) + for (int i = 0; i != len; i++) { ret[2 * i] = (byte) buf[i]; ret[2 * i + 1] = (byte) (buf[i] >> 8); @@ -316,11 +316,11 @@ public static byte[] ToUByteBuffer(this ushort[] buf) /// public static uint[] ToUIntBuffer(this byte[] buf) { - var len = buf.Length / 4; - var ret = new uint[len]; + int len = buf.Length / 4; + uint[] ret = new uint[len]; unchecked { - for (var i = 0; i != len; i++) ret[i] = (uint) ((buf[4 * i + 3] << 24) | (buf[4 * i + 2] << 16) | (buf[4 * i + 1] << 8) | buf[4 * i]); + for (int i = 0; i != len; i++) ret[i] = (uint) ((buf[4 * i + 3] << 24) | (buf[4 * i + 2] << 16) | (buf[4 * i + 1] << 8) | buf[4 * i]); } return ret; } @@ -328,11 +328,11 @@ public static uint[] ToUIntBuffer(this byte[] buf) /// public static ushort[] ToUShortBuffer(this byte[] buf) { - var len = buf.Length / 2; - var ret = new ushort[len]; + int len = buf.Length / 2; + ushort[] ret = new ushort[len]; unchecked { - for (var i = 0; i != len; i++) ret[i] = (ushort) ((buf[2 * i + 1] << 8) | buf[2 * i]); + for (int i = 0; i != len; i++) ret[i] = (ushort) ((buf[2 * i + 1] << 8) | buf[2 * i]); } return ret; } @@ -356,7 +356,7 @@ public static bool TryMoveBackupFile(string desiredPath, string backupPath) // deletions are asynchronous, so wait for a while and then give up static bool TryWaitForFileToVanish(string path) { - for (var i = 25; i != 0; i--) + for (int i = 25; i != 0; i--) { if (!File.Exists(path)) return true; Thread.Sleep(10); diff --git a/src/BizHawk.Common/VersionInfo.cs b/src/BizHawk.Common/VersionInfo.cs index cde5abeabb4..6f6a67618ce 100644 --- a/src/BizHawk.Common/VersionInfo.cs +++ b/src/BizHawk.Common/VersionInfo.cs @@ -23,14 +23,14 @@ public static partial class VersionInfo static VersionInfo() { - var path = Path.Combine( + string path = Path.Combine( Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location)?.RemoveSuffix(Path.DirectorySeparatorChar) ?? string.Empty, "dll", "custombuild.txt" ); if (File.Exists(path)) { - var lines = File.ReadAllLines(path); + string[] lines = File.ReadAllLines(path); if (lines.Length > 0) { CustomBuildString = lines[0]; @@ -44,13 +44,13 @@ public static string GetEmuVersion() /// "2.5.1" => 0x02050100 public static uint VersionStrToInt(string s) { - var a = s.Split('.'); - var v = 0U; - var i = 0; + string[] a = s.Split('.'); + uint v = 0U; + int i = 0; while (i < 4) { v <<= 8; - v += i < a.Length && byte.TryParse(a[i], out var b) ? b : 0U; + v += i < a.Length && byte.TryParse(a[i], out byte b) ? b : 0U; i++; } return v; diff --git a/src/BizHawk.Common/Win32/AVIWriterImports.cs b/src/BizHawk.Common/Win32/AVIWriterImports.cs index a81316faaee..5c0bb461c4e 100644 --- a/src/BizHawk.Common/Win32/AVIWriterImports.cs +++ b/src/BizHawk.Common/Win32/AVIWriterImports.cs @@ -62,10 +62,7 @@ public struct BITMAPINFOHEADER public uint biClrUsed; public uint biClrImportant; - public void Init() - { - biSize = (uint)Marshal.SizeOf(this); - } + public void Init() => biSize = (uint)Marshal.SizeOf(this); } [StructLayout(LayoutKind.Sequential)] @@ -95,10 +92,7 @@ public struct WAVEFORMATEX public ushort wBitsPerSample; public ushort cbSize; - public void Init() - { - cbSize = (ushort)Marshal.SizeOf(this); - } + public void Init() => cbSize = (ushort)Marshal.SizeOf(this); } /// Create a new stream in an existing file and creates an interface to the new stream diff --git a/src/BizHawk.Common/Win32/CWDHacks.cs b/src/BizHawk.Common/Win32/CWDHacks.cs index a6f14fd7df8..d0c640fb73c 100644 --- a/src/BizHawk.Common/Win32/CWDHacks.cs +++ b/src/BizHawk.Common/Win32/CWDHacks.cs @@ -27,8 +27,8 @@ public static string Get() { uint result; fixed (byte* pBuf = &BUFFER[0]) result = GetCurrentDirectoryW(BUFFER_LEN, pBuf); - if (result <= BUFFER_LEN && result is not 0U) return Encoding.Unicode.GetString(BUFFER, 0, (int) (2U * result)); - var buf = new byte[result]; + if (result is <= BUFFER_LEN and not 0U) return Encoding.Unicode.GetString(BUFFER, 0, (int) (2U * result)); + byte[] buf = new byte[result]; uint result1; fixed (byte* pBuf = &buf[0]) result1 = GetCurrentDirectoryW(BUFFER_LEN, pBuf); if (result1 == result) return Encoding.Unicode.GetString(buf, 0, (int) (2U * result)); diff --git a/src/BizHawk.Common/Win32/Win32ShellContextMenu.cs b/src/BizHawk.Common/Win32/Win32ShellContextMenu.cs index 8f3279c0256..c4d4a1c7fd7 100644 --- a/src/BizHawk.Common/Win32/Win32ShellContextMenu.cs +++ b/src/BizHawk.Common/Win32/Win32ShellContextMenu.cs @@ -241,7 +241,7 @@ public static extern IShellItem SHCreateItemFromParsingName( private Win32ShellContextMenu(string path) { - var uri = new Uri(path); + Uri uri = new(path); // this should be the only scheme used in practice if (uri.Scheme != "file") @@ -251,13 +251,13 @@ private Win32ShellContextMenu(string path) var shellItem = SHCreateItemFromParsingName(uri.LocalPath, IntPtr.Zero, typeof(IShellItem).GUID); - var pidls = new IntPtr[1]; + IntPtr[] pidls = new IntPtr[1]; pidls[0] = ILFindLastID(SHGetIDListFromObject(shellItem)); shellItem.GetParent(out var parent); var result = parent.BindToHandler(IntPtr.Zero, SFObject, typeof(IShellFolder).GUID); - var shellFolder = (IShellFolder)Marshal.GetObjectForIUnknown(result); + IShellFolder shellFolder = (IShellFolder)Marshal.GetObjectForIUnknown(result); shellFolder.GetUIObjectOf(IntPtr.Zero, 1, pidls, typeof(IContextMenu).GUID, 0, out result); ComInterface = (IContextMenu)Marshal.GetObjectForIUnknown(result); @@ -295,11 +295,11 @@ public void Dispose() public static void ShowContextMenu(string path, IntPtr parentWindow, int x, int y) { - var ctxMenu = new Win32ShellContextMenu(path); - using var menu = new TempMenu(); + Win32ShellContextMenu ctxMenu = new(path); + using TempMenu menu = new(); const int CmdFirst = 0x8000; ctxMenu.ComInterface.QueryContextMenu(menu.Handle, 0, CmdFirst, int.MaxValue, CMF.EXPLORE); - var command = TrackPopupMenuEx(menu.Handle, TPM.TPM_RETURNCMD, x, y, parentWindow, IntPtr.Zero); + int command = TrackPopupMenuEx(menu.Handle, TPM.TPM_RETURNCMD, x, y, parentWindow, IntPtr.Zero); if (command > 0) { const int SW_SHOWNORMAL = 1; diff --git a/src/BizHawk.Common/checksums/CRC32.cs b/src/BizHawk.Common/checksums/CRC32.cs index afe8b65d943..a62549e8a12 100644 --- a/src/BizHawk.Common/checksums/CRC32.cs +++ b/src/BizHawk.Common/checksums/CRC32.cs @@ -29,7 +29,7 @@ static CRC32() // put operator for one zero bit in odd odd[0] = POLYNOMIAL_CONST; var oddTail = odd.Slice(1); - for (var n = 0; n < oddTail.Length; n++) oddTail[n] = 1U << n; + for (int n = 0; n < oddTail.Length; n++) oddTail[n] = 1U << n; // put operator for two zero bits in even gf2_matrix_square(even, odd); // put operator for four zero bits in odd @@ -46,12 +46,12 @@ public static uint Calculate(ReadOnlySpan data) private static void gf2_matrix_square(Span square, ReadOnlySpan mat) { if (mat.Length != square.Length) throw new ArgumentException(message: "must be same length as " + nameof(square), paramName: nameof(mat)); - for (var n = 0; n < square.Length; n++) square[n] = gf2_matrix_times(mat, mat[n]); + for (int n = 0; n < square.Length; n++) square[n] = gf2_matrix_times(mat, mat[n]); } private static uint gf2_matrix_times(ReadOnlySpan mat, uint vec) { - var matIdx = 0; + int matIdx = 0; uint sum = 0U; while (vec != 0U) { @@ -62,23 +62,17 @@ private static uint gf2_matrix_times(ReadOnlySpan mat, uint vec) return sum; } - private uint _current = 0xFFFFFFFFU; - /// The raw non-negated output - public uint Current - { - get => _current; - set => _current = value; - } + public uint Current { get; set; } = 0xFFFFFFFFU; /// The negated output (the typical result of the CRC calculation) - public uint Result => ~_current; + public uint Result => ~Current; public unsafe void Add(ReadOnlySpan data) { fixed (byte* d = &data.GetPinnableReference()) { - _current = _calcCRC(_current, (IntPtr) d, data.Length); + Current = _calcCRC(Current, (IntPtr) d, data.Length); } } @@ -101,7 +95,7 @@ public void Incorporate(uint crc, int len) { // apply zeros operator for this bit of len gf2_matrix_square(even, odd); - if ((len & 1U) != 0U) _current = gf2_matrix_times(even, _current); + if ((len & 1U) != 0U) Current = gf2_matrix_times(even, Current); len >>= 1; // if no more bits set, then done @@ -109,14 +103,14 @@ public void Incorporate(uint crc, int len) // another iteration of the loop with odd and even swapped gf2_matrix_square(odd, even); - if ((len & 1U) != 0U) _current = gf2_matrix_times(odd, _current); + if ((len & 1U) != 0U) Current = gf2_matrix_times(odd, Current); len >>= 1; // if no more bits set, then done } while (len != 0U); // finally, combine and return - _current ^= crc; + Current ^= crc; } } } diff --git a/src/BizHawk.Common/checksums/CRC32Checksum.cs b/src/BizHawk.Common/checksums/CRC32Checksum.cs index a988b4b8035..8c134e58239 100644 --- a/src/BizHawk.Common/checksums/CRC32Checksum.cs +++ b/src/BizHawk.Common/checksums/CRC32Checksum.cs @@ -17,7 +17,7 @@ public static class CRC32Checksum public static byte[] BytesAsDigest(uint digest) { - var a = BitConverter.GetBytes(digest); + byte[] a = BitConverter.GetBytes(digest); return new[] { a[3], a[2], a[1], a[0] }; } diff --git a/src/BizHawk.Common/checksums/SHA1Checksum.cs b/src/BizHawk.Common/checksums/SHA1Checksum.cs index 471bc5f67f3..19239a96965 100644 --- a/src/BizHawk.Common/checksums/SHA1Checksum.cs +++ b/src/BizHawk.Common/checksums/SHA1Checksum.cs @@ -40,11 +40,11 @@ public static byte[] ComputeConcat(ReadOnlySpan dataA, ReadOnlySpan private static unsafe byte[] UnmanagedImpl(byte[] buffer) { // Set SHA1 start state - var state = stackalloc uint[] { 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0 }; + uint* state = stackalloc uint[] { 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0 }; // This will use dedicated SHA instructions, which perform 4x faster than a generic implementation LibBizHash.BizCalcSha1((IntPtr) state, buffer, buffer.Length); // The copy seems wasteful, but pinning the state down actually has a bigger performance impact - var ret = new byte[20]; + byte[] ret = new byte[20]; Marshal.Copy((IntPtr) state, ret, 0, 20); return ret; } @@ -72,7 +72,7 @@ public static byte[] Compute(byte[] data) public static byte[] ComputeConcat(byte[] dataA, byte[] dataB) { if (LibBizHash.BizSupportsShaInstructions()) return UnmanagedImpl(dataA.ConcatArray(dataB)); - using var impl = IncrementalHash.CreateHash(HashAlgorithmName.SHA1); + using IncrementalHash impl = IncrementalHash.CreateHash(HashAlgorithmName.SHA1); impl.AppendData(dataA); impl.AppendData(dataB); return impl.GetHashAndReset(); diff --git a/src/BizHawk.Emulation.Common/Base Implementations/Axes/AxisDict.cs b/src/BizHawk.Emulation.Common/Base Implementations/Axes/AxisDict.cs index 0973c5852a8..0f5992cfa56 100644 --- a/src/BizHawk.Emulation.Common/Base Implementations/Axes/AxisDict.cs +++ b/src/BizHawk.Emulation.Common/Base Implementations/Axes/AxisDict.cs @@ -61,7 +61,7 @@ public void Clear() public IEnumerator> GetEnumerator() { - foreach (var key in _keys) + foreach (string key in _keys) { yield return new(key, _specs[key]); } diff --git a/src/BizHawk.Emulation.Common/Base Implementations/Axes/CircularAxisConstraint.cs b/src/BizHawk.Emulation.Common/Base Implementations/Axes/CircularAxisConstraint.cs index c56dc67ea98..7f8f96aabfb 100644 --- a/src/BizHawk.Emulation.Common/Base Implementations/Axes/CircularAxisConstraint.cs +++ b/src/BizHawk.Emulation.Common/Base Implementations/Axes/CircularAxisConstraint.cs @@ -19,10 +19,10 @@ public CircularAxisConstraint(string @class, string pairedAxis, float magnitude) public (int X, int Y) ApplyTo(int rawX, int rawY) { - var xVal = (double) rawX; - var yVal = (double) rawY; - var length = Math.Sqrt(xVal * xVal + yVal * yVal); - var ratio = Magnitude / length; + double xVal = rawX; + double yVal = rawY; + double length = Math.Sqrt(xVal * xVal + yVal * yVal); + double ratio = Magnitude / length; return ratio < 1.0 ? ((int) (xVal * ratio), (int) (yVal * ratio)) : ((int) xVal, (int) yVal); diff --git a/src/BizHawk.Emulation.Common/Base Implementations/BasicServiceProvider.cs b/src/BizHawk.Emulation.Common/Base Implementations/BasicServiceProvider.cs index 462582d82a9..f8e7a116810 100644 --- a/src/BizHawk.Emulation.Common/Base Implementations/BasicServiceProvider.cs +++ b/src/BizHawk.Emulation.Common/Base Implementations/BasicServiceProvider.cs @@ -14,7 +14,7 @@ namespace BizHawk.Emulation.Common /// public class BasicServiceProvider : IEmulatorServiceProvider { - private readonly Dictionary _services = new Dictionary(); + private readonly Dictionary _services = new(); public BasicServiceProvider(IEmulator core) { @@ -23,7 +23,7 @@ public BasicServiceProvider(IEmulator core) // find the field), but we're going to keep such logic out of the basic provider. anything the passed // core doesn't implement directly needs to be added with Register() // this also fully allows services that are not IEmulatorService - Type coreType = core.GetType(); + var coreType = core.GetType(); foreach (var service in coreType.GetInterfaces().Where(static t => typeof(IEmulatorService).IsAssignableFrom(t) && t != typeof(IEmulatorService) && t != typeof(ISpecializedEmulatorService))) @@ -44,30 +44,18 @@ public BasicServiceProvider(IEmulator core) /// The to register /// is null public void Register(T provider) - where T : class, IEmulatorService - { - _services[typeof(T)] = provider; - } + where T : class, IEmulatorService => _services[typeof(T)] = provider; public T GetService() where T : IEmulatorService => (T) GetService(typeof(T))!; - public object? GetService(Type t) - { - return _services.TryGetValue(t, out var service) ? service : null; - } + public object? GetService(Type t) => _services.TryGetValue(t, out object? service) ? service : null; public bool HasService() - where T : IEmulatorService - { - return HasService(typeof(T)); - } + where T : IEmulatorService => HasService(typeof(T)); - public bool HasService(Type t) - { - return _services.ContainsKey(t); - } + public bool HasService(Type t) => _services.ContainsKey(t); public IEnumerable AvailableServices =>_services.Select(d => d.Key); } diff --git a/src/BizHawk.Emulation.Common/Base Implementations/CallbackBasedTraceBuffer.cs b/src/BizHawk.Emulation.Common/Base Implementations/CallbackBasedTraceBuffer.cs index 7f65081db9c..338d4a7e295 100644 --- a/src/BizHawk.Emulation.Common/Base Implementations/CallbackBasedTraceBuffer.cs +++ b/src/BizHawk.Emulation.Common/Base Implementations/CallbackBasedTraceBuffer.cs @@ -41,7 +41,7 @@ protected CallbackBasedTraceBuffer(IDebuggable debuggableCore, IMemoryDomains me protected readonly IDisassemblable Disassembler; protected readonly IDebuggable DebuggableCore; - protected readonly List Buffer = new List(); + protected readonly List Buffer = new(); protected abstract void TraceFromCallback(uint addr, uint value, uint flags); @@ -57,7 +57,7 @@ public ITraceSink? Sink if (_sink != null) { - var scope = DebuggableCore.MemoryCallbacks.AvailableScopes[0]; // This will be an issue when cores use this trace buffer and utilize multiple scopes + string scope = DebuggableCore.MemoryCallbacks.AvailableScopes[0]; // This will be an issue when cores use this trace buffer and utilize multiple scopes DebuggableCore.MemoryCallbacks.Add(new TracingMemoryCallback(TraceFromCallback, scope)); } } diff --git a/src/BizHawk.Emulation.Common/Base Implementations/CodeDataLog.cs b/src/BizHawk.Emulation.Common/Base Implementations/CodeDataLog.cs index cb28e261ac1..35da300ffd5 100644 --- a/src/BizHawk.Emulation.Common/Base Implementations/CodeDataLog.cs +++ b/src/BizHawk.Emulation.Common/Base Implementations/CodeDataLog.cs @@ -47,15 +47,12 @@ public void Unpin() /// /// Retrieves the pointer to a managed array /// - public IntPtr GetPin(string key) - { - return _pins[key].AddrOfPinnedObject(); - } + public IntPtr GetPin(string key) => _pins[key].AddrOfPinnedObject(); /// /// Pinned managed arrays /// - private readonly Dictionary _pins = new Dictionary(); + private readonly Dictionary _pins = new(); /// /// Whether the CDL is tracking a block with the given name @@ -92,7 +89,7 @@ public bool Check(ICodeDataLog other) foreach (var (scope, data) in this) { - if (!other.TryGetValue(scope, out var oval) || oval.Length != data.Length) return false; + if (!other.TryGetValue(scope, out byte[]? oval) || oval.Length != data.Length) return false; } // don't need to check keys present in other but not in this -- `Count` would differ @@ -112,7 +109,7 @@ public void LogicalOrFrom(ICodeDataLog other) foreach (var (scope, fromData) in other) { - var toData = this[scope]; + byte[] toData = this[scope]; if (fromData.Length != toData.Length) { @@ -134,15 +131,12 @@ public void ClearData() } } - public void Save(Stream s) - { - SaveInternal(s, true); - } - + public void Save(Stream s) => SaveInternal(s, true); + private Dictionary SaveInternal(Stream s, bool forReal) { - var ret = new Dictionary(); - var w = new BinaryWriter(s); + Dictionary ret = new(); + BinaryWriter w = new(s); w.Write("BIZHAWK-CDL-2"); w.Write(SubType!.PadRight(15)); w.Write(Count); @@ -172,15 +166,12 @@ private Dictionary SaveInternal(Stream s, bool forReal) return ret; } - public Dictionary GetBlockMap() - { - return SaveInternal(new MemoryStream(), false); - } + public Dictionary GetBlockMap() => SaveInternal(new MemoryStream(), false); /// contents of do not begin with valid file header public void Load(Stream s) { - var br = new BinaryReader(s); + BinaryReader br = new(s); string id = br.ReadString(); SubType = id switch { diff --git a/src/BizHawk.Emulation.Common/Base Implementations/ControllerDefinition.cs b/src/BizHawk.Emulation.Common/Base Implementations/ControllerDefinition.cs index c69a735fe80..01ebdbed107 100644 --- a/src/BizHawk.Emulation.Common/Base Implementations/ControllerDefinition.cs +++ b/src/BizHawk.Emulation.Common/Base Implementations/ControllerDefinition.cs @@ -69,7 +69,7 @@ public IList BoolButtons } } - public readonly AxisDict Axes = new AxisDict(); + public readonly AxisDict Axes = new(); /// Contains names of virtual haptic feedback channels, e.g. { "P1 Mono" }, { "P2 Left", "P2 Right" }. public IList HapticsChannels { get; private set; } = new List(); @@ -89,8 +89,8 @@ public void ApplyAxisConstraints(string constraintClass, IDictionary> GenOrderedControls() { - var ret = new List[PlayerCount + 1]; - for (var i = 0; i < ret.Length; i++) ret[i] = new(); - foreach (var btn in Axes.Keys.Concat(BoolButtons)) ret[PlayerNumber(btn)].Add(btn); + List[] ret = new List[PlayerCount + 1]; + for (int i = 0; i < ret.Length; i++) ret[i] = new(); + foreach (string btn in Axes.Keys.Concat(BoolButtons)) ret[PlayerNumber(btn)].Add(btn); return ret; } @@ -130,14 +130,14 @@ public static int PlayerNumber(string buttonName) : 0; } - private static readonly Regex PlayerRegex = new Regex("^P(\\d+) "); + private static readonly Regex PlayerRegex = new("^P(\\d+) "); public int PlayerCount { get { - var allNames = Axes.Keys.Concat(BoolButtons).ToList(); - var player = allNames + List allNames = Axes.Keys.Concat(BoolButtons).ToList(); + int player = allNames .Select(PlayerNumber) .DefaultIfEmpty(0) .Max(); @@ -152,9 +152,6 @@ public int PlayerCount } } - public bool Any() - { - return BoolButtons.Any() || Axes.Any(); - } + public bool Any() => BoolButtons.Any() || Axes.Any(); } } diff --git a/src/BizHawk.Emulation.Common/Base Implementations/InputCallbackSystem.cs b/src/BizHawk.Emulation.Common/Base Implementations/InputCallbackSystem.cs index ed67e782b08..52c002b82f8 100644 --- a/src/BizHawk.Emulation.Common/Base Implementations/InputCallbackSystem.cs +++ b/src/BizHawk.Emulation.Common/Base Implementations/InputCallbackSystem.cs @@ -22,32 +22,32 @@ public void Call() // TODO: these just happen to be all the add/remove methods the client uses, to be thorough the others should be overriden as well public void RemoveAll(IEnumerable actions) { - var hadAny = this.Any(); + bool hadAny = this.Any(); foreach (var action in actions) { Remove(action); } - var hasAny = this.Any(); + bool hasAny = this.Any(); Changes(hadAny, hasAny); } public new void Add(Action item) { - var hadAny = this.Any(); + bool hadAny = this.Any(); base.Add(item); - var hasAny = this.Any(); + bool hasAny = this.Any(); Changes(hadAny, hasAny); } public new bool Remove(Action item) { - var hadAny = this.Any(); - var result = base.Remove(item); - var hasAny = this.Any(); + bool hadAny = this.Any(); + bool result = base.Remove(item); + bool hasAny = this.Any(); Changes(hadAny, hasAny); diff --git a/src/BizHawk.Emulation.Common/Base Implementations/LinkedDebuggable.cs b/src/BizHawk.Emulation.Common/Base Implementations/LinkedDebuggable.cs index 8182008bceb..dd1f90ff491 100644 --- a/src/BizHawk.Emulation.Common/Base Implementations/LinkedDebuggable.cs +++ b/src/BizHawk.Emulation.Common/Base Implementations/LinkedDebuggable.cs @@ -23,7 +23,7 @@ public LinkedDebuggable(IEmulator[] linkedCores, int numCores, MemoryCallbackSys public IDictionary GetCpuFlagsAndRegisters() { - var ret = new List>(); + List> ret = new(); for (int i = 0; i < _numCores; i++) { diff --git a/src/BizHawk.Emulation.Common/Base Implementations/LinkedMemoryDomains.cs b/src/BizHawk.Emulation.Common/Base Implementations/LinkedMemoryDomains.cs index 4670c57c0b9..96ef75e63ef 100644 --- a/src/BizHawk.Emulation.Common/Base Implementations/LinkedMemoryDomains.cs +++ b/src/BizHawk.Emulation.Common/Base Implementations/LinkedMemoryDomains.cs @@ -22,7 +22,7 @@ public LinkedMemoryDomains(IEmulator[] linkedCores, int numCores, LinkedDisassem private static List LinkMemoryDomains(IEmulator[] linkedCores, int numCores) { - var mm = new List(); + List mm = new(); for (int i = 0; i < numCores; i++) { diff --git a/src/BizHawk.Emulation.Common/Base Implementations/LinkedSaveRam.cs b/src/BizHawk.Emulation.Common/Base Implementations/LinkedSaveRam.cs index c2d344ef350..1e88b8f0a5e 100644 --- a/src/BizHawk.Emulation.Common/Base Implementations/LinkedSaveRam.cs +++ b/src/BizHawk.Emulation.Common/Base Implementations/LinkedSaveRam.cs @@ -34,7 +34,7 @@ private bool LinkedSaveRamModified() public byte[] CloneSaveRam() { - var linkedBuffers = new List(); + List linkedBuffers = new(); int len = 0; for (int i = 0; i < _numCores; i++) { @@ -56,7 +56,7 @@ public void StoreSaveRam(byte[] data) int pos = 0; for (int i = 0; i < _numCores; i++) { - var b = new byte[_linkedCores[i].AsSaveRam().CloneSaveRam()!.Length]; + byte[] b = new byte[_linkedCores[i].AsSaveRam().CloneSaveRam()!.Length]; Buffer.BlockCopy(data, pos, b, 0, b.Length); pos += b.Length; _linkedCores[i].AsSaveRam().StoreSaveRam(b); diff --git a/src/BizHawk.Emulation.Common/Base Implementations/MemoryBasedInputCallbackSystem.cs b/src/BizHawk.Emulation.Common/Base Implementations/MemoryBasedInputCallbackSystem.cs index df0f7598441..26bc49cde31 100644 --- a/src/BizHawk.Emulation.Common/Base Implementations/MemoryBasedInputCallbackSystem.cs +++ b/src/BizHawk.Emulation.Common/Base Implementations/MemoryBasedInputCallbackSystem.cs @@ -12,7 +12,7 @@ namespace BizHawk.Emulation.Common /// public class MemoryBasedInputCallbackSystem : IInputCallbackSystem { - private readonly List _inputCallbacks = new List(); + private readonly List _inputCallbacks = new(); public MemoryBasedInputCallbackSystem(IDebuggable debuggableCore, string scope, IEnumerable addresses) { @@ -21,9 +21,9 @@ public MemoryBasedInputCallbackSystem(IDebuggable debuggableCore, string scope, throw new InvalidOperationException("Memory callbacks are required"); } - foreach (var address in addresses) + foreach (uint address in addresses) { - var callback = new MemoryCallback( + MemoryCallback callback = new( scope, MemoryCallbackType.Read, "InputCallback" + address, @@ -49,10 +49,7 @@ private void MemoryCallback(uint address, uint value, uint flags) public void Add(Action item) => _inputCallbacks.Add(item); - public void Clear() - { - _inputCallbacks.Clear(); - } + public void Clear() => _inputCallbacks.Clear(); public bool Contains(Action item) => _inputCallbacks.Contains(item); @@ -63,10 +60,7 @@ public void Clear() public int Count => _inputCallbacks.Count; public bool IsReadOnly => false; - public void Call() - { - throw new InvalidOperationException("This implementation does not require being called directly"); - } + public void Call() => throw new InvalidOperationException("This implementation does not require being called directly"); public void RemoveAll(IEnumerable actions) { diff --git a/src/BizHawk.Emulation.Common/Base Implementations/MemoryCallbackSystem.cs b/src/BizHawk.Emulation.Common/Base Implementations/MemoryCallbackSystem.cs index 3a14bc67867..28cca000c1e 100644 --- a/src/BizHawk.Emulation.Common/Base Implementations/MemoryCallbackSystem.cs +++ b/src/BizHawk.Emulation.Common/Base Implementations/MemoryCallbackSystem.cs @@ -116,20 +116,11 @@ public void CallMemoryCallbacks(uint addr, uint value, uint flags, string scope) public bool HasExecutes { get; private set; } - public bool HasReadsForScope(string scope) - { - return _reads.Any(e => e.Scope == scope); - } + public bool HasReadsForScope(string scope) => _reads.Any(e => e.Scope == scope); - public bool HasWritesForScope(string scope) - { - return _writes.Any(e => e.Scope == scope); - } + public bool HasWritesForScope(string scope) => _writes.Any(e => e.Scope == scope); - public bool HasExecutesForScope(string scope) - { - return _execs.Any(e => e.Scope == scope); - } + public bool HasExecutesForScope(string scope) => _execs.Any(e => e.Scope == scope); private bool UpdateHasVariables() { @@ -203,20 +194,11 @@ public void Clear() public delegate void CallbackRemovedEventHandler(IMemoryCallback callback); public event CallbackRemovedEventHandler CallbackRemoved; - private void Changes() - { - ActiveChanged?.Invoke(); - } + private void Changes() => ActiveChanged?.Invoke(); - private void OnCallbackAdded(object sender, IMemoryCallback callback) - { - CallbackAdded?.Invoke(callback); - } + private void OnCallbackAdded(object sender, IMemoryCallback callback) => CallbackAdded?.Invoke(callback); - private void OnCallbackRemoved(object sender, IMemoryCallback callback) - { - CallbackRemoved?.Invoke(callback); - } + private void OnCallbackRemoved(object sender, IMemoryCallback callback) => CallbackRemoved?.Invoke(callback); public IEnumerator GetEnumerator() { @@ -375,15 +357,9 @@ private void BeginModify() _modifyInProgress = true; } - private void EndModify() - { - _modifyInProgress = false; - } + private void EndModify() => _modifyInProgress = false; - private void BeginCopyOnWrite() - { - _copyOnWriteRequired++; - } + private void BeginCopyOnWrite() => _copyOnWriteRequired++; private void EndCopyOnWrite() { @@ -424,8 +400,8 @@ public Enumerator(MemoryCallbackCollection collection) } public readonly IMemoryCallback Current => _items[_position]; - - object IEnumerator.Current => Current; + + readonly object IEnumerator.Current => Current; public bool MoveNext() => ++_position < _items.Count; diff --git a/src/BizHawk.Emulation.Common/Base Implementations/MemoryDomain.cs b/src/BizHawk.Emulation.Common/Base Implementations/MemoryDomain.cs index 2f89aed99fa..3a00147815d 100644 --- a/src/BizHawk.Emulation.Common/Base Implementations/MemoryDomain.cs +++ b/src/BizHawk.Emulation.Common/Base Implementations/MemoryDomain.cs @@ -35,39 +35,33 @@ public enum Endian public virtual ushort PeekUshort(long addr, bool bigEndian) { - Endian endian = bigEndian ? Endian.Big : Endian.Little; - switch (endian) + var endian = bigEndian ? Endian.Big : Endian.Little; + return endian switch { - default: - case Endian.Big: - return (ushort)((PeekByte(addr) << 8) | PeekByte(addr + 1)); - case Endian.Little: - return (ushort)(PeekByte(addr) | (PeekByte(addr + 1) << 8)); - } + Endian.Little => (ushort)(PeekByte(addr) | (PeekByte(addr + 1) << 8)), + _ => (ushort)((PeekByte(addr) << 8) | PeekByte(addr + 1)), + }; } public virtual uint PeekUint(long addr, bool bigEndian) { - Endian endian = bigEndian ? Endian.Big : Endian.Little; - switch (endian) + var endian = bigEndian ? Endian.Big : Endian.Little; + return endian switch { - default: - case Endian.Big: - return (uint)((PeekByte(addr) << 24) - | (PeekByte(addr + 1) << 16) - | (PeekByte(addr + 2) << 8) - | (PeekByte(addr + 3) << 0)); - case Endian.Little: - return (uint)((PeekByte(addr) << 0) - | (PeekByte(addr + 1) << 8) - | (PeekByte(addr + 2) << 16) - | (PeekByte(addr + 3) << 24)); - } + Endian.Little => (uint)((PeekByte(addr) << 0) + | (PeekByte(addr + 1) << 8) + | (PeekByte(addr + 2) << 16) + | (PeekByte(addr + 3) << 24)), + _ => (uint)((PeekByte(addr) << 24) + | (PeekByte(addr + 1) << 16) + | (PeekByte(addr + 2) << 8) + | (PeekByte(addr + 3) << 0)), + }; } public virtual void PokeUshort(long addr, ushort val, bool bigEndian) { - Endian endian = bigEndian ? Endian.Big : Endian.Little; + var endian = bigEndian ? Endian.Big : Endian.Little; switch (endian) { default: @@ -84,7 +78,7 @@ public virtual void PokeUshort(long addr, ushort val, bool bigEndian) public virtual void PokeUint(long addr, uint val, bool bigEndian) { - Endian endian = bigEndian ? Endian.Big : Endian.Little; + var endian = bigEndian ? Endian.Big : Endian.Little; switch (endian) { default: @@ -115,7 +109,7 @@ public virtual void BulkPeekByte(Range addresses, byte[] values) using (this.EnterExit()) { - for (var i = addresses.Start; i <= addresses.EndInclusive; i++) + for (long i = addresses.Start; i <= addresses.EndInclusive; i++) { values[i - addresses.Start] = PeekByte(i); } @@ -127,8 +121,8 @@ public virtual void BulkPeekUshort(Range addresses, bool bigEndian, ushor if (addresses is null) throw new ArgumentNullException(paramName: nameof(addresses)); if (values is null) throw new ArgumentNullException(paramName: nameof(values)); - var start = addresses.Start; - var end = addresses.EndInclusive + 1; + long start = addresses.Start; + long end = addresses.EndInclusive + 1; if ((start & 1) != 0 || (end & 1) != 0) throw new InvalidOperationException("The API contract doesn't define what to do for unaligned reads and writes!"); @@ -141,7 +135,7 @@ public virtual void BulkPeekUshort(Range addresses, bool bigEndian, ushor using (this.EnterExit()) { - for (var i = 0; i < values.Length; i++, start += 2) + for (int i = 0; i < values.Length; i++, start += 2) values[i] = PeekUshort(start, bigEndian); } } @@ -151,8 +145,8 @@ public virtual void BulkPeekUint(Range addresses, bool bigEndian, uint[] v if (addresses is null) throw new ArgumentNullException(paramName: nameof(addresses)); if (values is null) throw new ArgumentNullException(paramName: nameof(values)); - var start = addresses.Start; - var end = addresses.EndInclusive + 1; + long start = addresses.Start; + long end = addresses.EndInclusive + 1; if ((start & 3) != 0 || (end & 3) != 0) throw new InvalidOperationException("The API contract doesn't define what to do for unaligned reads and writes!"); @@ -165,7 +159,7 @@ public virtual void BulkPeekUint(Range addresses, bool bigEndian, uint[] v using (this.EnterExit()) { - for (var i = 0; i < values.Length; i++, start += 4) + for (int i = 0; i < values.Length; i++, start += 4) values[i] = PeekUint(start, bigEndian); } } diff --git a/src/BizHawk.Emulation.Common/Base Implementations/MemoryDomainImpls.cs b/src/BizHawk.Emulation.Common/Base Implementations/MemoryDomainImpls.cs index 6393101dd3c..0f8e3c1aac2 100644 --- a/src/BizHawk.Emulation.Common/Base Implementations/MemoryDomainImpls.cs +++ b/src/BizHawk.Emulation.Common/Base Implementations/MemoryDomainImpls.cs @@ -28,15 +28,9 @@ public Action Poke } } - public override byte PeekByte(long addr) - { - return Peek(addr); - } + public override byte PeekByte(long addr) => Peek(addr); - public override void PokeByte(long addr, byte val) - { - _poke?.Invoke(addr, val); - } + public override void PokeByte(long addr, byte val) => _poke?.Invoke(addr, val); public override void BulkPeekByte(Range addresses, byte[] values) { @@ -112,10 +106,7 @@ public byte[] Data } } - public override byte PeekByte(long addr) - { - return Data[addr]; - } + public override byte PeekByte(long addr) => Data[addr]; public override void PokeByte(long addr, byte val) { @@ -213,8 +204,8 @@ public override void PokeByte(long addr, byte val) public override void BulkPeekByte(Range addresses, byte[] values) { - var start = (ulong)addresses.Start; - var count = addresses.Count(); + ulong start = (ulong)addresses.Start; + ulong count = addresses.Count(); if (start < (ulong)Size && (start + count) <= (ulong)Size) { @@ -226,10 +217,7 @@ public override void BulkPeekByte(Range addresses, byte[] values) } } - public void SetSize(long size) - { - Size = size; - } + public void SetSize(long size) => Size = size; public MemoryDomainIntPtr(string name, Endian endian, IntPtr data, long size, bool writable, int wordSize) { @@ -278,10 +266,7 @@ public override void PokeByte(long addr, byte val) } } - public void SetSize(long size) - { - Size = size; - } + public void SetSize(long size) => Size = size; public MemoryDomainIntPtrMonitor(string name, Endian endian, IntPtr data, long size, bool writable, int wordSize, IMonitor monitor) diff --git a/src/BizHawk.Emulation.Common/Base Implementations/MemoryDomainList.cs b/src/BizHawk.Emulation.Common/Base Implementations/MemoryDomainList.cs index 2261f44272d..1ff1f2f2dff 100644 --- a/src/BizHawk.Emulation.Common/Base Implementations/MemoryDomainList.cs +++ b/src/BizHawk.Emulation.Common/Base Implementations/MemoryDomainList.cs @@ -16,10 +16,7 @@ public class MemoryDomainList : ReadOnlyCollection, IMemoryDomains private MemoryDomain _mainMemory; private MemoryDomain _systemBus; - public bool Has(string name) - { - return this.Any(md => md.Name == name); - } + public bool Has(string name) => this.Any(md => md.Name == name); public MemoryDomainList(IList domains) : base(domains) @@ -56,7 +53,7 @@ public MemoryDomain SystemBus /// public void MergeList(MemoryDomainList other) { - var domains = this.ToDictionary(m => m.Name); + Dictionary domains = this.ToDictionary(m => m.Name); foreach (var src in other) { if (domains.TryGetValue(src.Name, out var dst)) diff --git a/src/BizHawk.Emulation.Common/Base Implementations/MemoryDomainStream.cs b/src/BizHawk.Emulation.Common/Base Implementations/MemoryDomainStream.cs index 795d4ddb135..e8de9773a71 100644 --- a/src/BizHawk.Emulation.Common/Base Implementations/MemoryDomainStream.cs +++ b/src/BizHawk.Emulation.Common/Base Implementations/MemoryDomainStream.cs @@ -60,7 +60,7 @@ public override int Read(byte[] buffer, int offset, int count) if (count == 0) return 0; // TODO: Memory domain doesn't have the overload we need :( - var poop = new byte[count]; + byte[] poop = new byte[count]; // TODO: Range has the wrong end value _d.BulkPeekByte(Position.RangeToExclusive(Position + count), poop); Array.Copy(poop, 0, buffer, offset, count); @@ -72,7 +72,7 @@ public override void Write(byte[] buffer, int offset, int count) { if (offset < 0 || offset + count > buffer.Length) throw new ArgumentException("start or end not within bounds of buffer", nameof(offset)); - for (var i = offset; i < offset + count; i++) + for (int i = offset; i < offset + count; i++) _d.PokeByte(Position++, buffer[i]); } @@ -95,9 +95,6 @@ public override long Seek(long offset, SeekOrigin origin) return Position; } - public override void SetLength(long value) - { - throw new NotSupportedException("Stream cannot be resized"); - } + public override void SetLength(long value) => throw new NotSupportedException("Stream cannot be resized"); } } diff --git a/src/BizHawk.Emulation.Common/Base Implementations/NullController.cs b/src/BizHawk.Emulation.Common/Base Implementations/NullController.cs index 3017554fe58..f2285ed33e9 100644 --- a/src/BizHawk.Emulation.Common/Base Implementations/NullController.cs +++ b/src/BizHawk.Emulation.Common/Base Implementations/NullController.cs @@ -24,6 +24,6 @@ public class NullController : IController public void SetHapticChannelStrength(string name, int strength) {} - public static readonly NullController Instance = new NullController(); + public static readonly NullController Instance = new(); } } \ No newline at end of file diff --git a/src/BizHawk.Emulation.Common/Base Implementations/NullSound.cs b/src/BizHawk.Emulation.Common/Base Implementations/NullSound.cs index dfc8c57181d..595f41ad226 100644 --- a/src/BizHawk.Emulation.Common/Base Implementations/NullSound.cs +++ b/src/BizHawk.Emulation.Common/Base Implementations/NullSound.cs @@ -68,10 +68,7 @@ public void DiscardSamples() { } - public void SetSyncMode(SyncSoundMode mode) - { - SyncMode = mode; - } + public void SetSyncMode(SyncSoundMode mode) => SyncMode = mode; /// is not (call ) public void GetSamplesAsync(short[] samples) diff --git a/src/BizHawk.Emulation.Common/Base Implementations/SimpleSyncSoundProvider.cs b/src/BizHawk.Emulation.Common/Base Implementations/SimpleSyncSoundProvider.cs index 037b1ddce5b..6db431dd484 100644 --- a/src/BizHawk.Emulation.Common/Base Implementations/SimpleSyncSoundProvider.cs +++ b/src/BizHawk.Emulation.Common/Base Implementations/SimpleSyncSoundProvider.cs @@ -47,14 +47,8 @@ public void GetSamplesSync(out short[] samples, out int nsamp) } /// always - public void GetSamplesAsync(short[] samples) - { - throw new NotImplementedException(); - } + public void GetSamplesAsync(short[] samples) => throw new NotImplementedException(); - public void DiscardSamples() - { - _nsamp = 0; - } + public void DiscardSamples() => _nsamp = 0; } } diff --git a/src/BizHawk.Emulation.Common/Base Implementations/StateSerializer.cs b/src/BizHawk.Emulation.Common/Base Implementations/StateSerializer.cs index b864951020c..57aef2ca731 100644 --- a/src/BizHawk.Emulation.Common/Base Implementations/StateSerializer.cs +++ b/src/BizHawk.Emulation.Common/Base Implementations/StateSerializer.cs @@ -30,10 +30,7 @@ public StateSerializer(Action syncState) public bool AvoidRewind => false; - public void SaveStateText(TextWriter writer) - { - _syncState(Serializer.CreateTextWriter(writer)); - } + public void SaveStateText(TextWriter writer) => _syncState(Serializer.CreateTextWriter(writer)); public void LoadStateText(TextReader reader) { @@ -41,10 +38,7 @@ public void LoadStateText(TextReader reader) LoadStateCallback?.Invoke(); } - public void SaveStateBinary(BinaryWriter bw) - { - _syncState(Serializer.CreateBinaryWriter(bw)); - } + public void SaveStateBinary(BinaryWriter bw) => _syncState(Serializer.CreateBinaryWriter(bw)); public void LoadStateBinary(BinaryReader br) { diff --git a/src/BizHawk.Emulation.Common/ControllerDefinitionMerger.cs b/src/BizHawk.Emulation.Common/ControllerDefinitionMerger.cs index 4d7fa28b820..f300662cb55 100644 --- a/src/BizHawk.Emulation.Common/ControllerDefinitionMerger.cs +++ b/src/BizHawk.Emulation.Common/ControllerDefinitionMerger.cs @@ -49,7 +49,7 @@ public static ControllerDefinition GetMerged( foreach (var (k, v) in def.Axes) { - var r = Allocate(k, ref plr, ref playerNext); + string r = Allocate(k, ref plr, ref playerNext); ret.Axes.Add(r, v); buttonAxisRemaps[k] = r; } @@ -83,15 +83,9 @@ public DummyController( /// always public ControllerDefinition Definition => throw new NotImplementedException(); - public bool IsPressed(string button) - { - return _src.IsPressed(_buttonAxisRemaps[button]); - } + public bool IsPressed(string button) => _src.IsPressed(_buttonAxisRemaps[button]); - public int AxisValue(string name) - { - return _src.AxisValue(_buttonAxisRemaps[name]); - } + public int AxisValue(string name) => _src.AxisValue(_buttonAxisRemaps[name]); public IReadOnlyCollection<(string Name, int Strength)> GetHapticsSnapshot() => Array.Empty<(string, int)>(); diff --git a/src/BizHawk.Emulation.Common/Database/Database.cs b/src/BizHawk.Emulation.Common/Database/Database.cs index 585c30a05e5..86320958bfb 100644 --- a/src/BizHawk.Emulation.Common/Database/Database.cs +++ b/src/BizHawk.Emulation.Common/Database/Database.cs @@ -40,10 +40,10 @@ private static void LoadDatabase_Escape(string line, bool inUser, bool silent) { if (!line.StartsWith("#include", StringComparison.InvariantCultureIgnoreCase)) return; - var isUserInclude = line.StartsWith("#includeuser", StringComparison.InvariantCultureIgnoreCase); - var searchUser = inUser || isUserInclude; + bool isUserInclude = line.StartsWith("#includeuser", StringComparison.InvariantCultureIgnoreCase); + bool searchUser = inUser || isUserInclude; line = line.Substring(isUserInclude ? 12 : 8).TrimStart(); - var filename = Path.Combine(searchUser ? _userRoot : _bundledRoot, line); + string filename = Path.Combine(searchUser ? _userRoot : _bundledRoot, line); if (File.Exists(filename)) { if (!silent) Util.DebugWriteLine($"loading external game database {line} ({(searchUser ? "user" : "bundled")})"); @@ -61,7 +61,7 @@ private static void LoadDatabase_Escape(string line, bool inUser, bool silent) public static void SaveDatabaseEntry(CompactGameInfo gameInfo, string filename = "gamedb_user.txt") { - var sb = new StringBuilder(); + StringBuilder sb = new(); sb .Append("sha1:") // TODO: how do we know it is sha1? .Append(gameInfo.Hash) @@ -99,10 +99,10 @@ private static void InitializeWork(string path, bool inUser, bool silent) { if (!inUser) _expected.Remove(Path.GetFileName(path)); //reminder: this COULD be done on several threads, if it takes even longer - using var reader = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)); + using StreamReader reader = new(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)); while (reader.EndOfStream == false) { - var line = reader.ReadLine() ?? ""; + string line = reader.ReadLine() ?? ""; try { if (line.StartsWith(';')) continue; // comment @@ -118,9 +118,9 @@ private static void InitializeWork(string path, bool inUser, bool silent) continue; } - var items = line.Split('\t'); + string[] items = line.Split('\t'); - var game = new CompactGameInfo + CompactGameInfo game = new() { Hash = FormatHash(items[0]), Status = items[1].Trim() @@ -178,7 +178,7 @@ public static void InitializeDatabase(string bundledRoot, string userRoot, bool _expected = new DirectoryInfo(_bundledRoot!).EnumerateFiles("*.txt").Select(static fi => fi.Name).ToList(); - var stopwatch = Stopwatch.StartNew(); + Stopwatch stopwatch = Stopwatch.StartNew(); ThreadPool.QueueUserWorkItem(_ => { InitializeWork(Path.Combine(bundledRoot, "gamedb.txt"), inUser: false, silent: silent); if (_expected.Count is not 0) Util.DebugWriteLine($"extra bundled gamedb files were not #included: {string.Join(", ", _expected)}"); @@ -191,7 +191,7 @@ public static GameInfo CheckDatabase(string hash) { _acquire.WaitOne(); - var hashFormatted = FormatHash(hash); + string hashFormatted = FormatHash(hash); _ = DB.TryGetValue(hashFormatted, out var cgi); if (cgi == null) { @@ -206,26 +206,26 @@ public static GameInfo GetGameInfo(byte[] romData, string fileName) { _acquire.WaitOne(); - var hashSHA1 = SHA1Checksum.ComputeDigestHex(romData); + string hashSHA1 = SHA1Checksum.ComputeDigestHex(romData); if (DB.TryGetValue(hashSHA1, out var cgi)) { return new GameInfo(cgi); } - var hashMD5 = MD5Checksum.ComputeDigestHex(romData); + string hashMD5 = MD5Checksum.ComputeDigestHex(romData); if (DB.TryGetValue(hashMD5, out cgi)) { return new GameInfo(cgi); } - var hashCRC32 = CRC32Checksum.ComputeDigestHex(romData); + string hashCRC32 = CRC32Checksum.ComputeDigestHex(romData); if (DB.TryGetValue(hashCRC32, out cgi)) { return new GameInfo(cgi); } // rom is not in database. make some best-guesses - var game = new GameInfo + GameInfo game = new() { Hash = hashSHA1, Status = RomStatus.NotInDatabase, @@ -234,7 +234,7 @@ public static GameInfo GetGameInfo(byte[] romData, string fileName) Console.WriteLine($"Game was not in DB. CRC: {hashCRC32} MD5: {hashMD5}"); - var ext = Path.GetExtension(fileName)?.ToUpperInvariant(); + string ext = Path.GetExtension(fileName)?.ToUpperInvariant(); switch (ext) { @@ -250,7 +250,7 @@ public static GameInfo GetGameInfo(byte[] romData, string fileName) if (SatellaviewFileTypeDetector.IsSatellaviewRom(romData, out var warnings)) { game.System = VSystemID.Raw.Satellaview; - foreach (var s in warnings) Console.WriteLine(s); + foreach (string s in warnings) Console.WriteLine(s); } else { @@ -371,7 +371,7 @@ public static GameInfo GetGameInfo(byte[] romData, string fileName) break; case ".DSK": - var dId = new DskIdentifier(romData); + DskIdentifier dId = new(romData); game.System = dId.IdentifiedSystem; break; diff --git a/src/BizHawk.Emulation.Common/Database/FirmwareDatabase.cs b/src/BizHawk.Emulation.Common/Database/FirmwareDatabase.cs index 5f65ab4d0a4..09e391197c0 100644 --- a/src/BizHawk.Emulation.Common/Database/FirmwareDatabase.cs +++ b/src/BizHawk.Emulation.Common/Database/FirmwareDatabase.cs @@ -49,7 +49,7 @@ FirmwareFile File( void Option(string systemId, string id, in FirmwareFile ff, FirmwareOptionStatus status = FirmwareOptionStatus.Acceptable) { - var option = new FirmwareOption(new(systemId, id), ff.Hash, ff.Size, ff.IsBad ? FirmwareOptionStatus.Bad : status); + FirmwareOption option = new(new(systemId, id), ff.Hash, ff.Size, ff.IsBad ? FirmwareOptionStatus.Bad : status); options.Add(option); filesByOption[option] = ff; } diff --git a/src/BizHawk.Emulation.Common/Database/FirmwareOption.cs b/src/BizHawk.Emulation.Common/Database/FirmwareOption.cs index fa5ec1dc1ed..3bd6e2c5bc1 100644 --- a/src/BizHawk.Emulation.Common/Database/FirmwareOption.cs +++ b/src/BizHawk.Emulation.Common/Database/FirmwareOption.cs @@ -14,7 +14,7 @@ namespace BizHawk.Emulation.Common public readonly FirmwareID ID; - public bool IsAcceptableOrIdeal => Status == FirmwareOptionStatus.Ideal || Status == FirmwareOptionStatus.Acceptable; + public bool IsAcceptableOrIdeal => Status is FirmwareOptionStatus.Ideal or FirmwareOptionStatus.Acceptable; public readonly long Size; diff --git a/src/BizHawk.Emulation.Common/Database/FirmwarePatchData.cs b/src/BizHawk.Emulation.Common/Database/FirmwarePatchData.cs index 371ffe88511..cb6f0f2f9c0 100644 --- a/src/BizHawk.Emulation.Common/Database/FirmwarePatchData.cs +++ b/src/BizHawk.Emulation.Common/Database/FirmwarePatchData.cs @@ -35,9 +35,9 @@ public readonly byte[] ApplyToMutating(byte[] @base) } else { - var iBase = Offset; - var iPatch = 0; - var l = Contents.Length; + int iBase = Offset; + int iPatch = 0; + int l = Contents.Length; while (iPatch < l) @base[iBase++] ^= Contents[iPatch++]; } return @base; diff --git a/src/BizHawk.Emulation.Common/Database/GameInfo.cs b/src/BizHawk.Emulation.Common/Database/GameInfo.cs index 9cc80b935f2..81af57f447c 100644 --- a/src/BizHawk.Emulation.Common/Database/GameInfo.cs +++ b/src/BizHawk.Emulation.Common/Database/GameInfo.cs @@ -41,7 +41,7 @@ public GameInfo() public GameInfo Clone() { - var ret = (GameInfo)MemberwiseClone(); + GameInfo ret = (GameInfo)MemberwiseClone(); ret.Options = new Dictionary(Options); return ret; } @@ -69,42 +69,21 @@ internal GameInfo(CompactGameInfo cgi) ParseOptionsDictionary(cgi.MetaData); } - public void AddOption(string option, string param) - { - Options[option] = param; - } + public void AddOption(string option, string param) => Options[option] = param; - public void RemoveOption(string option) - { - Options.Remove(option); - } + public void RemoveOption(string option) => Options.Remove(option); public bool this[string option] => Options.ContainsKey(option); - public bool OptionPresent(string option) - { - return Options.ContainsKey(option); - } + public bool OptionPresent(string option) => Options.ContainsKey(option); - public string OptionValue(string option) - { - return Options.TryGetValue(option, out var s) ? s : null; - } + public string OptionValue(string option) => Options.TryGetValue(option, out string s) ? s : null; - public int GetIntValue(string option) - { - return int.Parse(Options[option]); - } + public int GetIntValue(string option) => int.Parse(Options[option]); - public string GetStringValue(string option) - { - return Options[option]; - } + public string GetStringValue(string option) => Options[option]; - public int GetHexValue(string option) - { - return int.Parse(Options[option], NumberStyles.HexNumber); - } + public int GetHexValue(string option) => int.Parse(Options[option], NumberStyles.HexNumber); /// /// /// Gets a boolean value from the database @@ -150,10 +129,7 @@ public int GetInt(string parameter, int defaultVal) return defaultVal; } - public IReadOnlyDictionary GetOptions() - { - return new ReadOnlyDictionary(Options); - } + public IReadOnlyDictionary GetOptions() => new ReadOnlyDictionary(Options); private void ParseOptionsDictionary(string metaData) { @@ -162,13 +138,13 @@ private void ParseOptionsDictionary(string metaData) return; } - var options = metaData.Split(';').Where(opt => string.IsNullOrEmpty(opt) == false).ToArray(); + string[] options = metaData.Split(';').Where(opt => string.IsNullOrEmpty(opt) == false).ToArray(); - foreach (var opt in options) + foreach (string opt in options) { - var parts = opt.Split('='); - var key = parts[0]; - var value = parts.Length > 1 ? parts[1] : ""; + string[] parts = opt.Split('='); + string key = parts[0]; + string value = parts.Length > 1 ? parts[1] : ""; Options[key] = value; } } @@ -176,14 +152,8 @@ private void ParseOptionsDictionary(string metaData) public static class GameInfoExtensions { - public static bool IsNullInstance(this IGameInfo game) - { - return game == null || game.System == VSystemID.Raw.NULL; - } + public static bool IsNullInstance(this IGameInfo game) => game == null || game.System == VSystemID.Raw.NULL; - public static bool IsRomStatusBad(this IGameInfo game) - { - return game.Status == RomStatus.BadDump || game.Status == RomStatus.Overdump; - } + public static bool IsRomStatusBad(this IGameInfo game) => game.Status is RomStatus.BadDump or RomStatus.Overdump; } } diff --git a/src/BizHawk.Emulation.Common/Extensions.cs b/src/BizHawk.Emulation.Common/Extensions.cs index d3e83b7d855..92598d9b2a5 100644 --- a/src/BizHawk.Emulation.Common/Extensions.cs +++ b/src/BizHawk.Emulation.Common/Extensions.cs @@ -68,26 +68,14 @@ public static class EmulatorExtensions [VSystemID.Raw.ZXSpectrum] = "ZX Spectrum", }; - public static CoreAttribute Attributes(this IEmulator core) - { - return (CoreAttribute)Attribute.GetCustomAttribute(core.GetType(), typeof(CoreAttribute)); - } + public static CoreAttribute Attributes(this IEmulator core) => (CoreAttribute)Attribute.GetCustomAttribute(core.GetType(), typeof(CoreAttribute)); // todo: most of the special cases involving the NullEmulator should probably go away - public static bool IsNull(this IEmulator core) - { - return core == null || core is NullEmulator; - } + public static bool IsNull(this IEmulator core) => core is null or NullEmulator; - public static bool HasVideoProvider(this IEmulator core) - { - return core != null && core.ServiceProvider.HasService(); - } + public static bool HasVideoProvider(this IEmulator core) => core != null && core.ServiceProvider.HasService(); - public static IVideoProvider AsVideoProvider(this IEmulator core) - { - return core.ServiceProvider.GetService(); - } + public static IVideoProvider AsVideoProvider(this IEmulator core) => core.ServiceProvider.GetService(); /// /// Returns the core's VideoProvider, or a suitable dummy provider @@ -98,17 +86,11 @@ public static IVideoProvider AsVideoProviderOrDefault(this IEmulator core) ?? NullVideo.Instance; } - public static bool HasSoundProvider(this IEmulator core) - { - return core != null && core.ServiceProvider.HasService(); - } + public static bool HasSoundProvider(this IEmulator core) => core != null && core.ServiceProvider.HasService(); - public static ISoundProvider AsSoundProvider(this IEmulator core) - { - return core.ServiceProvider.GetService(); - } + public static ISoundProvider AsSoundProvider(this IEmulator core) => core.ServiceProvider.GetService(); - private static readonly ConditionalWeakTable CachedNullSoundProviders = new ConditionalWeakTable(); + private static readonly ConditionalWeakTable CachedNullSoundProviders = new(); /// /// returns the core's SoundProvider, or a suitable dummy provider @@ -119,45 +101,21 @@ public static ISoundProvider AsSoundProviderOrDefault(this IEmulator core) ?? CachedNullSoundProviders.GetValue(core, e => new NullSound(core.VsyncNumerator(), core.VsyncDenominator())); } - public static bool HasMemoryDomains(this IEmulator core) - { - return core != null && core.ServiceProvider.HasService(); - } + public static bool HasMemoryDomains(this IEmulator core) => core != null && core.ServiceProvider.HasService(); - public static IMemoryDomains AsMemoryDomains(this IEmulator core) - { - return core.ServiceProvider.GetService(); - } + public static IMemoryDomains AsMemoryDomains(this IEmulator core) => core.ServiceProvider.GetService(); - public static bool HasSaveRam(this IEmulator core) - { - return core != null && core.ServiceProvider.HasService(); - } + public static bool HasSaveRam(this IEmulator core) => core != null && core.ServiceProvider.HasService(); - public static ISaveRam AsSaveRam(this IEmulator core) - { - return core.ServiceProvider.GetService(); - } + public static ISaveRam AsSaveRam(this IEmulator core) => core.ServiceProvider.GetService(); - public static bool HasSavestates(this IEmulator core) - { - return core != null && core.ServiceProvider.HasService(); - } + public static bool HasSavestates(this IEmulator core) => core != null && core.ServiceProvider.HasService(); - public static IStatable AsStatable(this IEmulator core) - { - return core.ServiceProvider.GetService(); - } + public static IStatable AsStatable(this IEmulator core) => core.ServiceProvider.GetService(); - public static bool CanPollInput(this IEmulator core) - { - return core != null && core.ServiceProvider.HasService(); - } + public static bool CanPollInput(this IEmulator core) => core != null && core.ServiceProvider.HasService(); - public static IInputPollable AsInputPollable(this IEmulator core) - { - return core.ServiceProvider.GetService(); - } + public static IInputPollable AsInputPollable(this IEmulator core) => core.ServiceProvider.GetService(); public static bool InputCallbacksAvailable(this IEmulator core) { @@ -179,35 +137,17 @@ public static bool InputCallbacksAvailable(this IEmulator core) return false; } - public static bool HasDriveLight(this IEmulator core) - { - return core != null && core.ServiceProvider.HasService(); - } + public static bool HasDriveLight(this IEmulator core) => core != null && core.ServiceProvider.HasService(); - public static IDriveLight AsDriveLight(this IEmulator core) - { - return core.ServiceProvider.GetService(); - } + public static IDriveLight AsDriveLight(this IEmulator core) => core.ServiceProvider.GetService(); - public static bool CanDebug(this IEmulator core) - { - return core != null && core.ServiceProvider.HasService(); - } + public static bool CanDebug(this IEmulator core) => core != null && core.ServiceProvider.HasService(); - public static IDebuggable AsDebuggable(this IEmulator core) - { - return core.ServiceProvider.GetService(); - } + public static IDebuggable AsDebuggable(this IEmulator core) => core.ServiceProvider.GetService(); - public static bool CpuTraceAvailable(this IEmulator core) - { - return core != null && core.ServiceProvider.HasService(); - } + public static bool CpuTraceAvailable(this IEmulator core) => core != null && core.ServiceProvider.HasService(); - public static ITraceable AsTracer(this IEmulator core) - { - return core.ServiceProvider.GetService(); - } + public static ITraceable AsTracer(this IEmulator core) => core.ServiceProvider.GetService(); public static bool MemoryCallbacksAvailable(this IEmulator core) { @@ -247,65 +187,29 @@ public static bool MemoryCallbacksAvailable(this IDebuggable core) } } - public static bool CanDisassemble(this IEmulator core) - { - return core != null && core.ServiceProvider.HasService(); - } + public static bool CanDisassemble(this IEmulator core) => core != null && core.ServiceProvider.HasService(); - public static IDisassemblable AsDisassembler(this IEmulator core) - { - return core.ServiceProvider.GetService(); - } + public static IDisassemblable AsDisassembler(this IEmulator core) => core.ServiceProvider.GetService(); - public static bool HasRegions(this IEmulator core) - { - return core != null && core.ServiceProvider.HasService(); - } + public static bool HasRegions(this IEmulator core) => core != null && core.ServiceProvider.HasService(); - public static IRegionable AsRegionable(this IEmulator core) - { - return core.ServiceProvider.GetService(); - } + public static IRegionable AsRegionable(this IEmulator core) => core.ServiceProvider.GetService(); - public static bool CanCDLog(this IEmulator core) - { - return core != null && core.ServiceProvider.HasService(); - } + public static bool CanCDLog(this IEmulator core) => core != null && core.ServiceProvider.HasService(); - public static ICodeDataLogger AsCodeDataLogger(this IEmulator core) - { - return core.ServiceProvider.GetService(); - } + public static ICodeDataLogger AsCodeDataLogger(this IEmulator core) => core.ServiceProvider.GetService(); - public static ILinkable AsLinkable(this IEmulator core) - { - return core.ServiceProvider.GetService(); - } + public static ILinkable AsLinkable(this IEmulator core) => core.ServiceProvider.GetService(); - public static bool UsesLinkCable(this IEmulator core) - { - return core != null && core.ServiceProvider.HasService(); - } + public static bool UsesLinkCable(this IEmulator core) => core != null && core.ServiceProvider.HasService(); - public static bool CanGenerateGameDBEntries(this IEmulator core) - { - return core != null && core.ServiceProvider.HasService(); - } + public static bool CanGenerateGameDBEntries(this IEmulator core) => core != null && core.ServiceProvider.HasService(); - public static ICreateGameDBEntries AsGameDBEntryGenerator(this IEmulator core) - { - return core.ServiceProvider.GetService(); - } + public static ICreateGameDBEntries AsGameDBEntryGenerator(this IEmulator core) => core.ServiceProvider.GetService(); - public static bool HasBoardInfo(this IEmulator core) - { - return core != null && core.ServiceProvider.HasService(); - } + public static bool HasBoardInfo(this IEmulator core) => core != null && core.ServiceProvider.HasService(); - public static IBoardInfo AsBoardInfo(this IEmulator core) - { - return core.ServiceProvider.GetService(); - } + public static IBoardInfo AsBoardInfo(this IEmulator core) => core.ServiceProvider.GetService(); public static (int X, int Y) ScreenLogicalOffsets(this IEmulator core) { @@ -348,15 +252,9 @@ public static int VsyncDenominator(this IEmulator core) return 1; } - public static double VsyncRate(this IEmulator core) - { - return core.VsyncNumerator() / (double)core.VsyncDenominator(); - } + public static double VsyncRate(this IEmulator core) => core.VsyncNumerator() / (double)core.VsyncDenominator(); - public static bool IsImplemented(this MethodInfo info) - { - return !info.GetCustomAttributes(false).Any(a => a is FeatureNotImplementedAttribute); - } + public static bool IsImplemented(this MethodInfo info) => !info.GetCustomAttributes(false).Any(a => a is FeatureNotImplementedAttribute); /// /// Gets a list of boolean button names. If a controller number is specified, only returns button names @@ -368,27 +266,21 @@ public static bool IsImplemented(this MethodInfo info) /// - ToBoolButtonNameList(controller, 2) -> [A, B] /// - ToBoolButtonNameList(controller, null) -> [P1 A, P1 B, P2 A, P2 B] /// - public static List ToBoolButtonNameList(this IController controller, int? controllerNum = null) - { - return ToControlNameList(controller.Definition.BoolButtons, controllerNum); - } + public static List ToBoolButtonNameList(this IController controller, int? controllerNum = null) => ToControlNameList(controller.Definition.BoolButtons, controllerNum); /// /// See ToBoolButtonNameList(). Works the same except with axes /// - public static List ToAxisControlNameList(this IController controller, int? controllerNum = null) - { - return ToControlNameList(controller.Definition.Axes.Keys, controllerNum); - } + public static List ToAxisControlNameList(this IController controller, int? controllerNum = null) => ToControlNameList(controller.Definition.Axes.Keys, controllerNum); private static List ToControlNameList(IEnumerable buttonList, int? controllerNum = null) { - var buttons = new List(); - foreach (var button in buttonList) + List buttons = new(); + foreach (string button in buttonList) { if (controllerNum != null && button.Length > 2 && button.Substring(0, 2) == $"P{controllerNum}") { - var sub = button.Substring(3); + string sub = button.Substring(3); buttons.Add(sub); } else if (controllerNum == null) @@ -401,23 +293,23 @@ private static List ToControlNameList(IEnumerable buttonList, in public static IReadOnlyDictionary ToDictionary(this IController controller, int? controllerNum = null) { - var dict = new Dictionary(); + Dictionary dict = new(); if (controllerNum == null) { - foreach (var buttonName in controller.Definition.BoolButtons) dict[buttonName] = controller.IsPressed(buttonName); - foreach (var axisName in controller.Definition.Axes.Keys) dict[axisName] = controller.AxisValue(axisName); + foreach (string buttonName in controller.Definition.BoolButtons) dict[buttonName] = controller.IsPressed(buttonName); + foreach (string axisName in controller.Definition.Axes.Keys) dict[axisName] = controller.AxisValue(axisName); return dict; } - var prefix = $"P{controllerNum} "; - foreach (var buttonName in controller.Definition.BoolButtons) + string prefix = $"P{controllerNum} "; + foreach (string buttonName in controller.Definition.BoolButtons) { - var s = buttonName.RemovePrefix(prefix); + string s = buttonName.RemovePrefix(prefix); if (ReferenceEquals(s, buttonName)) continue; // did not start with prefix dict[s] = controller.IsPressed(buttonName); } - foreach (var axisName in controller.Definition.Axes.Keys) + foreach (string axisName in controller.Definition.Axes.Keys) { - var s = axisName.RemovePrefix(prefix); + string s = axisName.RemovePrefix(prefix); if (ReferenceEquals(s, axisName)) continue; // did not start with prefix dict[s] = controller.AxisValue(axisName); } @@ -452,7 +344,7 @@ public static ControllerDefinition AddAxis(this ControllerDefinition def, string /// identical reference to ; the object is mutated public static ControllerDefinition AddXYPair(this ControllerDefinition def, string nameFormat, AxisPairOrientation pDir, Range rangeX, int neutralX, Range rangeY, int neutralY, AxisConstraint constraint = null) { - var yAxisName = string.Format(nameFormat, "Y"); + string yAxisName = string.Format(nameFormat, "Y"); var finalConstraint = constraint ?? new NoOpAxisConstraint(yAxisName); return def.AddAxis(string.Format(nameFormat, "X"), rangeX, neutralX, ((byte) pDir & 2) != 0, finalConstraint) .AddAxis(yAxisName, rangeY, neutralY, ((byte) pDir & 1) != 0); @@ -478,10 +370,10 @@ public static ControllerDefinition AddXYZTriple(this ControllerDefinition def, s .AddAxis(string.Format(nameFormat, "Y"), rangeAll, neutralAll) .AddAxis(string.Format(nameFormat, "Z"), rangeAll, neutralAll); - public static AxisSpec With(this in AxisSpec spec, Range range, int neutral) => new AxisSpec(range, neutral, spec.IsReversed, spec.Constraint); + public static AxisSpec With(this in AxisSpec spec, Range range, int neutral) => new(range, neutral, spec.IsReversed, spec.Constraint); public static string SystemIDToDisplayName(string sysID) - => SystemIDDisplayNames.TryGetValue(sysID, out var dispName) ? dispName : string.Empty; + => SystemIDDisplayNames.TryGetValue(sysID, out string dispName) ? dispName : string.Empty; public static bool IsEnabled(this ITraceable core) => core.Sink is not null; diff --git a/src/BizHawk.Emulation.Common/Interfaces/Services/IDebuggable.cs b/src/BizHawk.Emulation.Common/Interfaces/Services/IDebuggable.cs index 54d52b19bb0..1a00e706d48 100644 --- a/src/BizHawk.Emulation.Common/Interfaces/Services/IDebuggable.cs +++ b/src/BizHawk.Emulation.Common/Interfaces/Services/IDebuggable.cs @@ -58,7 +58,7 @@ public RegisterValue(ulong val, byte bitSize) { Value = val; } - else if (bitSize > 64 || bitSize == 0) + else if (bitSize is > 64 or 0) { throw new ArgumentOutOfRangeException(nameof(bitSize), $"{nameof(BitSize)} must be in 1..64"); } @@ -124,14 +124,14 @@ public RegisterValue(long val) BitSize = 64; } - public static implicit operator RegisterValue(bool val) => new RegisterValue(val); - public static implicit operator RegisterValue(byte val) => new RegisterValue(val); - public static implicit operator RegisterValue(sbyte val) => new RegisterValue(val); - public static implicit operator RegisterValue(ushort val) => new RegisterValue(val); - public static implicit operator RegisterValue(short val) => new RegisterValue(val); - public static implicit operator RegisterValue(uint val) => new RegisterValue(val); - public static implicit operator RegisterValue(int val) => new RegisterValue(val); - public static implicit operator RegisterValue(ulong val) => new RegisterValue(val); - public static implicit operator RegisterValue(long val) => new RegisterValue(val); + public static implicit operator RegisterValue(bool val) => new(val); + public static implicit operator RegisterValue(byte val) => new(val); + public static implicit operator RegisterValue(sbyte val) => new(val); + public static implicit operator RegisterValue(ushort val) => new(val); + public static implicit operator RegisterValue(short val) => new(val); + public static implicit operator RegisterValue(uint val) => new(val); + public static implicit operator RegisterValue(int val) => new(val); + public static implicit operator RegisterValue(ulong val) => new(val); + public static implicit operator RegisterValue(long val) => new(val); } } diff --git a/src/BizHawk.Emulation.Common/Interfaces/Services/IStatable.cs b/src/BizHawk.Emulation.Common/Interfaces/Services/IStatable.cs index 2e5e380d1be..34520226714 100644 --- a/src/BizHawk.Emulation.Common/Interfaces/Services/IStatable.cs +++ b/src/BizHawk.Emulation.Common/Interfaces/Services/IStatable.cs @@ -39,7 +39,7 @@ public static void SaveStateText(this IStatable core, TextWriter writer) textCore.SaveStateText(writer); } - var temp = core.CloneSavestate(); + byte[] temp = core.CloneSavestate(); temp.SaveAsHexFast(writer); } @@ -53,26 +53,23 @@ public static void LoadStateText(this IStatable core, TextReader reader) string hex = reader.ReadLine(); if (hex != null) { - var state = new byte[hex.Length / 2]; + byte[] state = new byte[hex.Length / 2]; state.ReadFromHexFast(hex); - using var ms = new MemoryStream(state); - using var br = new BinaryReader(ms); + using MemoryStream ms = new(state); + using BinaryReader br = new(ms); core.LoadStateBinary(br); } } - public static void LoadStateText(this IStatable core, string textState) - { - core.LoadStateText(new StringReader(textState)); - } + public static void LoadStateText(this IStatable core, string textState) => core.LoadStateText(new StringReader(textState)); /// /// Loads a state directly from a byte array /// public static void LoadStateBinary(this IStatable core, byte[] state) { - using var ms = new MemoryStream(state, false); - using var br = new BinaryReader(ms); + using MemoryStream ms = new(state, false); + using BinaryReader br = new(ms); core.LoadStateBinary(br); } @@ -82,11 +79,11 @@ public static void LoadStateBinary(this IStatable core, byte[] state) /// public static byte[] CloneSavestate(this IStatable core) { - using var ms = new MemoryStream(); - using var bw = new BinaryWriter(ms); + using MemoryStream ms = new(); + using BinaryWriter bw = new(ms); core.SaveStateBinary(bw); bw.Flush(); - var stateBuffer = ms.ToArray(); + byte[] stateBuffer = ms.ToArray(); bw.Close(); return stateBuffer; } diff --git a/src/BizHawk.Emulation.Common/Interfaces/Services/IVideoProvider.cs b/src/BizHawk.Emulation.Common/Interfaces/Services/IVideoProvider.cs index 20abcc9ebb6..e7c117bafe3 100644 --- a/src/BizHawk.Emulation.Common/Interfaces/Services/IVideoProvider.cs +++ b/src/BizHawk.Emulation.Common/Interfaces/Services/IVideoProvider.cs @@ -75,8 +75,8 @@ public static class VideoProviderExtensions /// public static void PopulateFromBuffer(this IVideoProvider videoProvider, int[] frameBuffer) { - var b1 = frameBuffer; - var b2 = videoProvider.GetVideoBuffer(); + int[] b1 = frameBuffer; + int[] b2 = videoProvider.GetVideoBuffer(); int len = Math.Min(b1.Length, b2.Length); for (int i = 0; i < len; i++) { diff --git a/src/BizHawk.Emulation.Common/SaveController.cs b/src/BizHawk.Emulation.Common/SaveController.cs index 079710f5146..06f59a76c28 100644 --- a/src/BizHawk.Emulation.Common/SaveController.cs +++ b/src/BizHawk.Emulation.Common/SaveController.cs @@ -13,7 +13,7 @@ namespace BizHawk.Emulation.Common /// public class SaveController : IController { - private readonly WorkingDictionary _buttons = new WorkingDictionary(); + private readonly WorkingDictionary _buttons = new(); public IInputDisplayGenerator InputDisplayGenerator { get; set; } = null; @@ -36,7 +36,7 @@ public SaveController(ControllerDefinition def) public void Serialize(BinaryWriter b) { b.Write(_buttons.Keys.Count); - foreach (var k in _buttons.Keys) + foreach (string k in _buttons.Keys) { b.Write(k); b.Write(_buttons[k]); @@ -64,12 +64,12 @@ public void CopyFrom(IController source) { Definition = source.Definition; _buttons.Clear(); - foreach (var k in Definition.BoolButtons) + foreach (string k in Definition.BoolButtons) { _buttons.Add(k, source.IsPressed(k) ? 1 : 0); } - foreach (var k in Definition.Axes.Keys) + foreach (string k in Definition.Axes.Keys) { if (_buttons.ContainsKey(k)) { @@ -80,25 +80,13 @@ public void CopyFrom(IController source) } } - public void Clear() - { - _buttons.Clear(); - } + public void Clear() => _buttons.Clear(); - public void Set(string button) - { - _buttons[button] = 1; - } + public void Set(string button) => _buttons[button] = 1; - public bool IsPressed(string button) - { - return _buttons[button] != 0; - } + public bool IsPressed(string button) => _buttons[button] != 0; - public int AxisValue(string name) - { - return _buttons[name]; - } + public int AxisValue(string name) => _buttons[name]; public IReadOnlyCollection<(string Name, int Strength)> GetHapticsSnapshot() => Array.Empty<(string, int)>(); diff --git a/src/BizHawk.Emulation.Common/ServiceInjector.cs b/src/BizHawk.Emulation.Common/ServiceInjector.cs index 38f84169197..2fb3048b829 100644 --- a/src/BizHawk.Emulation.Common/ServiceInjector.cs +++ b/src/BizHawk.Emulation.Common/ServiceInjector.cs @@ -60,7 +60,7 @@ private static (List Req, List Opt) GetService /// don't think having a genericised overload would be helpful, but TODO pass in type to save target.GetType() call public static bool UpdateServices(IEmulatorServiceProvider source, object target, bool mayCache = false) { - Type targetType = target.GetType(); + var targetType = target.GetType(); object?[] tmp = new object?[1]; var (req, opt) = GetServicePropsFor(targetType, mayCache: mayCache); foreach (var info in req) diff --git a/src/BizHawk.Emulation.Common/Sound/BlipBuffer.cs b/src/BizHawk.Emulation.Common/Sound/BlipBuffer.cs index 432fafcf888..ea0f4af3434 100644 --- a/src/BizHawk.Emulation.Common/Sound/BlipBuffer.cs +++ b/src/BizHawk.Emulation.Common/Sound/BlipBuffer.cs @@ -104,44 +104,23 @@ public void Dispose() } } - public void SetRates(double clockRate, double sampleRate) - { - BlipBufDll.blip_set_rates(_context, clockRate, sampleRate); - } + public void SetRates(double clockRate, double sampleRate) => BlipBufDll.blip_set_rates(_context, clockRate, sampleRate); public const int MaxRatio = BlipBufDll.BlipMaxRatio; - public void Clear() - { - BlipBufDll.blip_clear(_context); - } + public void Clear() => BlipBufDll.blip_clear(_context); - public void AddDelta(uint clockTime, int delta) - { - BlipBufDll.blip_add_delta(_context, clockTime, delta); - } + public void AddDelta(uint clockTime, int delta) => BlipBufDll.blip_add_delta(_context, clockTime, delta); - public void AddDeltaFast(uint clockTime, int delta) - { - BlipBufDll.blip_add_delta_fast(_context, clockTime, delta); - } + public void AddDeltaFast(uint clockTime, int delta) => BlipBufDll.blip_add_delta_fast(_context, clockTime, delta); - public int ClocksNeeded(int sampleCount) - { - return BlipBufDll.blip_clocks_needed(_context, sampleCount); - } + public int ClocksNeeded(int sampleCount) => BlipBufDll.blip_clocks_needed(_context, sampleCount); public const int MaxFrame = BlipBufDll.BlipMaxFrame; - public void EndFrame(uint clockDuration) - { - BlipBufDll.blip_end_frame(_context, clockDuration); - } + public void EndFrame(uint clockDuration) => BlipBufDll.blip_end_frame(_context, clockDuration); - public int SamplesAvailable() - { - return BlipBufDll.blip_samples_avail(_context); - } + public int SamplesAvailable() => BlipBufDll.blip_samples_avail(_context); /// can't hold samples (or twice that if is ) public int ReadSamples(short[] output, int count, bool stereo) diff --git a/src/BizHawk.Emulation.Common/Sound/DCFilter.cs b/src/BizHawk.Emulation.Common/Sound/DCFilter.cs index 6e6f737daea..2e2d81d7019 100644 --- a/src/BizHawk.Emulation.Common/Sound/DCFilter.cs +++ b/src/BizHawk.Emulation.Common/Sound/DCFilter.cs @@ -46,10 +46,7 @@ public DCFilter(ISoundProvider input, int filterWidth) /// /// sample buffer to modify /// number of samples (not pairs). stereo - public void PushThroughSamples(short[] samples, int length) - { - PushThroughSamples(samples, samples, length); - } + public void PushThroughSamples(short[] samples, int length) => PushThroughSamples(samples, samples, length); private void PushThroughSamples(short[] samplesIn, short[] samplesOut, int length) { @@ -102,14 +99,11 @@ public void GetSamplesAsync(short[] samples) PushThroughSamples(samples, samples.Length); } - public void DiscardSamples() - { - _soundProvider.DiscardSamples(); - } + public void DiscardSamples() => _soundProvider.DiscardSamples(); public void GetSamplesSync(out short[] samples, out int nsamp) { - _soundProvider.GetSamplesSync(out var sampIn, out var nsampIn); + _soundProvider.GetSamplesSync(out short[] sampIn, out int nsampIn); short[] ret = new short[nsampIn * 2]; PushThroughSamples(sampIn, ret, nsampIn * 2); @@ -121,9 +115,6 @@ public void GetSamplesSync(out short[] samples, out int nsamp) public bool CanProvideAsync => _soundProvider.CanProvideAsync; - public void SetSyncMode(SyncSoundMode mode) - { - _soundProvider.SetSyncMode(mode); - } + public void SetSyncMode(SyncSoundMode mode) => _soundProvider.SetSyncMode(mode); } } diff --git a/src/BizHawk.Emulation.Common/Sound/SpeexResampler.cs b/src/BizHawk.Emulation.Common/Sound/SpeexResampler.cs index 3d15421fb48..2c8d7ad113e 100644 --- a/src/BizHawk.Emulation.Common/Sound/SpeexResampler.cs +++ b/src/BizHawk.Emulation.Common/Sound/SpeexResampler.cs @@ -19,7 +19,7 @@ public class SpeexResampler : IDisposable, ISoundProvider private static readonly LibSpeexDSP NativeDSP; static SpeexResampler() { - var resolver = new DynamicLibraryImportResolver( + DynamicLibraryImportResolver resolver = new( OSTailoredCode.IsUnixHost ? "libspeexdsp.so.1" : "libspeexdsp.dll", hasLimitedLifetime: false); NativeDSP = BizInvoker.GetInvoker(resolver, CallingConventionAdapters.Native); } @@ -208,7 +208,7 @@ public void GetSamplesSync(out short[] samples, out int nsamp) { if (_input != null) { - _input.GetSamplesSync(out var sampin, out int nsampin); + _input.GetSamplesSync(out short[] sampin, out int nsampin); EnqueueSamples(sampin, nsampin); } @@ -218,20 +218,14 @@ public void GetSamplesSync(out short[] samples, out int nsamp) _outbuf2pos = 0; } - public void DiscardSamples() - { - _outbuf2pos = 0; - } + public void DiscardSamples() => _outbuf2pos = 0; public bool CanProvideAsync => false; public SyncSoundMode SyncMode => SyncSoundMode.Sync; /// always - public void GetSamplesAsync(short[] samples) - { - throw new InvalidOperationException("Async mode is not supported."); - } + public void GetSamplesAsync(short[] samples) => throw new InvalidOperationException("Async mode is not supported."); /// is public void SetSyncMode(SyncSoundMode mode) diff --git a/src/BizHawk.Emulation.Common/Sound/Waves.cs b/src/BizHawk.Emulation.Common/Sound/Waves.cs index b708846efa5..24e94787386 100644 --- a/src/BizHawk.Emulation.Common/Sound/Waves.cs +++ b/src/BizHawk.Emulation.Common/Sound/Waves.cs @@ -26,7 +26,7 @@ public static void InitWaves() PeriodicWave16 = new short[] { 32767, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; NoiseWave = new short[0x1000]; - var rnd = new System.Random(unchecked((int)0xDEADBEEF)); + System.Random rnd = new(unchecked((int)0xDEADBEEF)); for (int i = 0; i < NoiseWave.Length; i++) { int r = rnd.Next(); diff --git a/src/BizHawk.Emulation.Common/SystemLookup.cs b/src/BizHawk.Emulation.Common/SystemLookup.cs index 5332a73c3df..a858b2e1488 100644 --- a/src/BizHawk.Emulation.Common/SystemLookup.cs +++ b/src/BizHawk.Emulation.Common/SystemLookup.cs @@ -5,7 +5,7 @@ namespace BizHawk.Emulation.Common // TODO: This should build itself from the Cores assembly, we don't want to maintain this public class SystemLookup { - private readonly List _systems = new List + private readonly List _systems = new() { new(VSystemID.Raw.A26, "Atari 2600"), new(VSystemID.Raw.A78, "Atari 7800"), diff --git a/src/BizHawk.Emulation.Common/TextState.cs b/src/BizHawk.Emulation.Common/TextState.cs index 2500b79b312..af98122f579 100644 --- a/src/BizHawk.Emulation.Common/TextState.cs +++ b/src/BizHawk.Emulation.Common/TextState.cs @@ -23,25 +23,19 @@ public TextState() public class Node { - public readonly Dictionary Data = new Dictionary(); - public readonly Dictionary Objects = new Dictionary(); + public readonly Dictionary Data = new(); + public readonly Dictionary Objects = new(); // methods named "ShouldSerialize*" are detected and dynamically invoked by JSON.NET // if they return false during serialization, the field/prop is omitted from the created json // ReSharper disable once UnusedMember.Global - public bool ShouldSerializeData() - { - return Data.Count > 0; - } + public bool ShouldSerializeData() => Data.Count > 0; // ReSharper disable once UnusedMember.Global - public bool ShouldSerializeObjects() - { - return Objects.Count > 0; - } + public bool ShouldSerializeObjects() => Objects.Count > 0; } - public readonly Node Root = new Node(); + public readonly Node Root = new(); [JsonIgnore] private Stack Nodes; @@ -76,28 +70,26 @@ public void Load(IntPtr data, int length, string name) public void EnterSectionSave(string name) { - Node next = new Node(); + Node next = new(); Current.Objects.Add(name, next); Nodes.Push(next); } public void EnterSectionLoad(string name) { - Node next = Current.Objects[name]; + var next = Current.Objects[name]; Nodes.Push(next); } - public void EnterSection(string name) - { + public void EnterSection(string name) => // works for either save or load, but as a consequence cannot report intelligent // errors about section name mismatches Nodes.Push(Current.Objects.GetValueOrPutNew(name)); - } /// doesn't match the section being closed public void ExitSection(string name) { - Node last = Nodes.Pop(); + var last = Nodes.Pop(); if (Current.Objects[name] != last) { throw new InvalidOperationException(); diff --git a/src/BizHawk.Emulation.Common/filetype_detectors/SatellaviewFileTypeDetector.cs b/src/BizHawk.Emulation.Common/filetype_detectors/SatellaviewFileTypeDetector.cs index 7ce8f343168..ea5f98c55af 100644 --- a/src/BizHawk.Emulation.Common/filetype_detectors/SatellaviewFileTypeDetector.cs +++ b/src/BizHawk.Emulation.Common/filetype_detectors/SatellaviewFileTypeDetector.cs @@ -14,6 +14,7 @@ public static class SatellaviewFileTypeDetector /// public readonly ref struct SatellaviewHeader { + #pragma warning disable IDE0051 private const byte LIMITED_0_PLAYS_LEFT = 0b10000000; private const byte LIMITED_1_PLAYS_LEFT = 0b10000100; @@ -43,6 +44,7 @@ public readonly ref struct SatellaviewHeader private const int OFFSET_SPEED = 0x28; // 1 octet private const int OFFSET_TITLE = 0x10; // 16 octets + #pragma warning restore IDE0051 internal const byte UNLIMITED_PLAYS_LEFT = 0b00000000; @@ -103,7 +105,7 @@ public bool VerifyChecksum(ReadOnlySpan rom) private static bool CheckHeaderHeuristics(bool checkHiROM, ReadOnlySpan rom, IList warnings) { SatellaviewHeader header = new(rom.Slice(start: checkHiROM ? 0xFFB0 : 0x7FB0, length: HEADER_LENGTH)); - var corruption = 0; + int corruption = 0; // "invalid" states were assigned a higher value if the wiki page was less vague if (header.Title.Length is 0) corruption++; @@ -126,14 +128,14 @@ private static bool CheckHeaderHeuristics(bool checkHiROM, ReadOnlySpan ro if (header.MagicDRMByte is not 0x33) corruption += 3; // just this would probably have sufficed - var checksumMatches = header.VerifyChecksum(rom); + bool checksumMatches = header.VerifyChecksum(rom); if (!checksumMatches) { corruption++; warnings.Add("mismatch with rom's internal checksum"); } - var detected = corruption <= THRESHOLD; + bool detected = corruption <= THRESHOLD; if (detected) Util.DebugWriteLine($"heuristic match for Satellaview game/content ({(checkHiROM ? "HiROM" : "LoROM")}, -{corruption} pts.): {header.ToString()}"); else { @@ -153,7 +155,7 @@ public static bool IsSatellaviewRom(ReadOnlySpan rom, out IReadOnlyList warnings1 = new(); //TODO which should we check first? - var detected = CheckHeaderHeuristics(checkHiROM: false, rom, warnings1) + bool detected = CheckHeaderHeuristics(checkHiROM: false, rom, warnings1) || CheckHeaderHeuristics(checkHiROM: true, rom, warnings1); warnings = warnings1; return detected; diff --git a/src/BizHawk.Emulation.Common/vpads_schemata/PadSchemaControl.cs b/src/BizHawk.Emulation.Common/vpads_schemata/PadSchemaControl.cs index b7f1c357a4e..b0c6bff23cc 100644 --- a/src/BizHawk.Emulation.Common/vpads_schemata/PadSchemaControl.cs +++ b/src/BizHawk.Emulation.Common/vpads_schemata/PadSchemaControl.cs @@ -35,28 +35,28 @@ public ButtonSchema(int x, int y, int controller, string name, string displayNam => DisplayName = displayName; public static ButtonSchema Up(int x, int y, string? name = null) - => new ButtonSchema(x, y, name ?? "Up") { Icon = VGamepadButtonImage.BlueArrN }; + => new(x, y, name ?? "Up") { Icon = VGamepadButtonImage.BlueArrN }; public static ButtonSchema Up(int x, int y, int controller) - => new ButtonSchema(x, y, controller, "Up") { Icon = VGamepadButtonImage.BlueArrN }; + => new(x, y, controller, "Up") { Icon = VGamepadButtonImage.BlueArrN }; public static ButtonSchema Down(int x, int y, string? name = null) - => new ButtonSchema(x, y, name ?? "Down") { Icon = VGamepadButtonImage.BlueArrS }; + => new(x, y, name ?? "Down") { Icon = VGamepadButtonImage.BlueArrS }; public static ButtonSchema Down(int x, int y, int controller) - => new ButtonSchema(x, y, controller, "Down") { Icon = VGamepadButtonImage.BlueArrS }; + => new(x, y, controller, "Down") { Icon = VGamepadButtonImage.BlueArrS }; public static ButtonSchema Left(int x, int y, string? name = null) - => new ButtonSchema(x, y, name ?? "Left") { Icon = VGamepadButtonImage.BlueArrW }; + => new(x, y, name ?? "Left") { Icon = VGamepadButtonImage.BlueArrW }; public static ButtonSchema Left(int x, int y, int controller) - => new ButtonSchema(x, y, controller, "Left") { Icon = VGamepadButtonImage.BlueArrW }; + => new(x, y, controller, "Left") { Icon = VGamepadButtonImage.BlueArrW }; public static ButtonSchema Right(int x, int y, string? name = null) - => new ButtonSchema(x, y, name ?? "Right") { Icon = VGamepadButtonImage.BlueArrE }; + => new(x, y, name ?? "Right") { Icon = VGamepadButtonImage.BlueArrE }; public static ButtonSchema Right(int x, int y, int controller) - => new ButtonSchema(x, y, controller, "Right") { Icon = VGamepadButtonImage.BlueArrE }; + => new(x, y, controller, "Right") { Icon = VGamepadButtonImage.BlueArrE }; } /// A single analog control (e.g. pressure sensitive button) diff --git a/src/BizHawk.Emulation.Common/zstd/Zstd.cs b/src/BizHawk.Emulation.Common/zstd/Zstd.cs index ea7932ad53c..798b96c59d8 100644 --- a/src/BizHawk.Emulation.Common/zstd/Zstd.cs +++ b/src/BizHawk.Emulation.Common/zstd/Zstd.cs @@ -103,7 +103,7 @@ protected override void Dispose(bool disposing) Flush(); while (true) { - var n = _lib.ZSTD_endStream(_ctx.Zcs, ref _ctx.Output); + ulong n = _lib.ZSTD_endStream(_ctx.Zcs, ref _ctx.Output); CheckError(n); InternalFlush(); if (n == 0) @@ -154,7 +154,7 @@ public override void Flush() InternalFlush(); } - var n = _lib.ZSTD_flushStream(_ctx.Zcs, ref _ctx.Output); + ulong n = _lib.ZSTD_flushStream(_ctx.Zcs, ref _ctx.Output); CheckError(n); if (n == 0) { @@ -185,7 +185,7 @@ public override void Write(byte[] buffer, int offset, int count) Flush(); } - var n = Math.Min(count, (int)(ZstdCompressionStreamContext.INPUT_BUFFER_SIZE - _ctx.Input.Size)); + int n = Math.Min(count, (int)(ZstdCompressionStreamContext.INPUT_BUFFER_SIZE - _ctx.Input.Size)); Marshal.Copy(buffer, offset, _ctx.Input.Ptr + (int)_ctx.Input.Size, n); offset += n; _ctx.Input.Size += (ulong)n; @@ -317,10 +317,10 @@ public override void Flush() public override int Read(byte[] buffer, int offset, int count) { - var n = count; + int n = count; while (n > 0) { - var inputConsumed = _baseStream.Read(_ctx.InputBuffer, + int inputConsumed = _baseStream.Read(_ctx.InputBuffer, (int)_ctx.Input.Size, (int)(ZstdDecompressionStreamContext.INPUT_BUFFER_SIZE - _ctx.Input.Size)); _ctx.Input.Size += (ulong)inputConsumed; // avoid interop in case compression cannot be done @@ -329,7 +329,7 @@ public override int Read(byte[] buffer, int offset, int count) { CheckError(_lib.ZSTD_decompressStream(_ctx.Zds, ref _ctx.Output, ref _ctx.Input)); } - var outputToConsume = Math.Min(n, (int)(_ctx.Output.Pos - _outputConsumed)); + int outputToConsume = Math.Min(n, (int)(_ctx.Output.Pos - _outputConsumed)); Marshal.Copy(_ctx.Output.Ptr + (int)_outputConsumed, buffer, offset, outputToConsume); _outputConsumed += (ulong)outputToConsume; offset += outputToConsume; @@ -376,7 +376,7 @@ public override void Write(byte[] buffer, int offset, int count) static Zstd() { - var resolver = new DynamicLibraryImportResolver( + DynamicLibraryImportResolver resolver = new( OSTailoredCode.IsUnixHost ? "libzstd.so.1" : "libzstd.dll", hasLimitedLifetime: false); _lib = BizInvoker.GetInvoker(resolver, CallingConventionAdapters.Native); @@ -462,7 +462,7 @@ public Stream CreateZstdDecompressionStream(Stream stream) public static MemoryStream DecompressZstdStream(Stream src) { // check for ZSTD header - var tmp = new byte[4]; + byte[] tmp = new byte[4]; if (src.Read(tmp, 0, 4) != 4) { throw new InvalidOperationException("Unexpected end of stream"); @@ -473,10 +473,10 @@ public static MemoryStream DecompressZstdStream(Stream src) } src.Seek(0, SeekOrigin.Begin); - using var dctx = new ZstdDecompressionStreamContext(); + using ZstdDecompressionStreamContext dctx = new(); dctx.InitContext(); - using var dstream = new ZstdDecompressionStream(src, dctx); - var ret = new MemoryStream(); + using ZstdDecompressionStream dstream = new(src, dctx); + MemoryStream ret = new(); dstream.CopyTo(ret); return ret; } diff --git a/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.IEmulator.cs b/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.IEmulator.cs index 7ad918af801..2bdb273965c 100644 --- a/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.IEmulator.cs +++ b/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.IEmulator.cs @@ -9,7 +9,7 @@ public partial class MAME : IEmulator public bool DeterministicEmulation { get; } public int Frame { get; private set; } public IEmulatorServiceProvider ServiceProvider { get; } - public ControllerDefinition ControllerDefinition => MAMEController; + public ControllerDefinition ControllerDefinition { get; } = new("MAME Controller"); /// /// MAME fires the periodic callback on every video and debugger update, diff --git a/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.IInputPollable.cs b/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.IInputPollable.cs index 5967bf43f3f..09023dc1a6a 100644 --- a/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.IInputPollable.cs +++ b/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.IInputPollable.cs @@ -14,8 +14,6 @@ public partial class MAME : IInputPollable public bool IsLagFrame { get; set; } = false; public IInputCallbackSystem InputCallbacks { get; } = new InputCallbackSystem(); - private readonly ControllerDefinition MAMEController = new("MAME Controller"); - private string[] _buttonFields; private string[] _analogFields; private IntPtr[] _fieldPtrs; @@ -23,12 +21,12 @@ public partial class MAME : IInputPollable private void GetInputFields() { - var buttonFields = MameGetString(MAMELuaCommand.GetButtonFields).Split(';'); - var analogFields = MameGetString(MAMELuaCommand.GetAnalogFields).Split(';'); + string[] buttonFields = MameGetString(MAMELuaCommand.GetButtonFields).Split(';'); + string[] analogFields = MameGetString(MAMELuaCommand.GetAnalogFields).Split(';'); - var buttonFieldList = new List(); - var analogFieldList = new List(); - var fieldPtrList = new List(); + List buttonFieldList = new(); + List analogFieldList = new(); + List fieldPtrList = new(); void AddFieldPtr(string tag, string field) { @@ -43,31 +41,31 @@ void AddFieldPtr(string tag, string field) fieldPtrList.Add(ptr); } - foreach (var buttonField in buttonFields) + foreach (string buttonField in buttonFields) { if (buttonField != string.Empty && !buttonField.Contains('%')) { - var tag = buttonField.SubstringBefore(','); - var field = buttonField.SubstringAfterLast(','); + string tag = buttonField.SubstringBefore(','); + string field = buttonField.SubstringAfterLast(','); buttonFieldList.Add(field); AddFieldPtr(tag, field); - MAMEController.BoolButtons.Add(field); + ControllerDefinition.BoolButtons.Add(field); } } - foreach (var analogField in analogFields) + foreach (string analogField in analogFields) { if (analogField != string.Empty && !analogField.Contains('%')) { - var keys = analogField.Split(','); - var tag = keys[0]; - var field = keys[1]; + string[] keys = analogField.Split(','); + string tag = keys[0]; + string field = keys[1]; analogFieldList.Add(field); AddFieldPtr(tag, field); - var def = int.Parse(keys[2]); - var min = int.Parse(keys[3]); - var max = int.Parse(keys[4]); - MAMEController.AddAxis(field, min.RangeTo(max), def); + int def = int.Parse(keys[2]); + int min = int.Parse(keys[3]); + int max = int.Parse(keys[4]); + ControllerDefinition.AddAxis(field, min.RangeTo(max), def); } } @@ -76,17 +74,17 @@ void AddFieldPtr(string tag, string field) _fieldPtrs = fieldPtrList.ToArray(); _fieldInputs = new int[_fieldPtrs.Length]; - MAMEController.MakeImmutable(); + ControllerDefinition.MakeImmutable(); } private void SendInput(IController controller) { - for (var i = 0; i < _buttonFields.Length; i++) + for (int i = 0; i < _buttonFields.Length; i++) { _fieldInputs[i] = controller.IsPressed(_buttonFields[i]) ? 1 : 0; } - for (var i = 0; i < _analogFields.Length; i++) + for (int i = 0; i < _analogFields.Length; i++) { _fieldInputs[_buttonFields.Length + i] = controller.AxisValue(_analogFields[i]); } diff --git a/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.ISaveRam.cs b/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.ISaveRam.cs index 02e5b697ac3..7e0927318d4 100644 --- a/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.ISaveRam.cs +++ b/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.ISaveRam.cs @@ -12,10 +12,7 @@ public partial class MAME : ISaveRam private readonly List _nvramFilenames = new(); private const string NVRAM_MAGIC = "MAMEHAWK_NVRAM"; - private void GetNVRAMFilenames() - { - _core.mame_nvram_get_filenames(_filenameCallback); - } + private void GetNVRAMFilenames() => _core.mame_nvram_get_filenames(_filenameCallback); public bool SaveRamModified => _nvramFilenames.Count > 0; @@ -33,15 +30,15 @@ public byte[] CloneSaveRam() _core.mame_nvram_save(); - using var ms = new MemoryStream(); - using var writer = new BinaryWriter(ms); + using MemoryStream ms = new(); + using BinaryWriter writer = new(ms); writer.Write(NVRAM_MAGIC); writer.Write(_nvramFilenames.Count); - for (var i = 0; i < _nvramFilenames.Count; i++) + for (int i = 0; i < _nvramFilenames.Count; i++) { - var res = _exe.RemoveTransientFile(_nvramFilenames[i]); + byte[] res = _exe.RemoveTransientFile(_nvramFilenames[i]); writer.Write(_nvramFilenames[i]); writer.Write(res.Length); writer.Write(res); @@ -57,24 +54,24 @@ public void StoreSaveRam(byte[] data) return; } - using var ms = new MemoryStream(data, false); - using var reader = new BinaryReader(ms); + using MemoryStream ms = new(data, false); + using BinaryReader reader = new(ms); if (reader.ReadString() != NVRAM_MAGIC) { throw new InvalidOperationException("Bad NVRAM magic!"); } - var cnt = reader.ReadInt32(); + int cnt = reader.ReadInt32(); if (cnt != _nvramFilenames.Count) { throw new InvalidOperationException($"Wrong NVRAM file count! (got {cnt}, expected {_nvramFilenames.Count})"); } - var nvramFilesToClose = new List(); + List nvramFilesToClose = new(); void RemoveFiles() { - foreach (var nvramFileToClose in nvramFilesToClose) + foreach (string nvramFileToClose in nvramFilesToClose) { _exe.RemoveReadonlyFile(nvramFileToClose); } @@ -82,16 +79,16 @@ void RemoveFiles() try { - for (var i = 0; i < cnt; i++) + for (int i = 0; i < cnt; i++) { - var name = reader.ReadString(); + string name = reader.ReadString(); if (name != _nvramFilenames[i]) { throw new InvalidOperationException($"Wrong NVRAM filename! (got {name}, expected {_nvramFilenames[i]})"); } - var len = reader.ReadInt32(); - var buf = reader.ReadBytes(len); + int len = reader.ReadInt32(); + byte[] buf = reader.ReadBytes(len); if (len != buf.Length) { diff --git a/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.ISettable.ComponentModel.cs b/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.ISettable.ComponentModel.cs index fc506c69ffe..28cae685232 100644 --- a/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.ISettable.ComponentModel.cs +++ b/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.ISettable.ComponentModel.cs @@ -113,20 +113,17 @@ public override bool ShouldSerializeValue(object component) public override object GetValue(object component) { - var ss = (MAMESyncSettings)component; - if (!ss.DriverSettings.TryGetValue(Setting.LookupKey, out var val)) + MAMESyncSettings ss = (MAMESyncSettings)component; + if (!ss.DriverSettings.TryGetValue(Setting.LookupKey, out string val)) val = Setting.DefaultValue; return ConvertFromString(val); } - public override void ResetValue(object component) - { - ((MAMESyncSettings)component).DriverSettings.Remove(Setting.LookupKey); - } + public override void ResetValue(object component) => ((MAMESyncSettings)component).DriverSettings.Remove(Setting.LookupKey); public override void SetValue(object component, object value) { - var s = ConvertToString(value); + string s = ConvertToString(value); if (s == null || s == Setting.DefaultValue) { ResetValue(component); diff --git a/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.ISettable.cs b/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.ISettable.cs index 36b76190ecd..01511a42121 100644 --- a/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.ISettable.cs @@ -16,10 +16,7 @@ public partial class MAME : ISettable public List CurrentDriverSettings = new(); private MAMESyncSettings _syncSettings; - public MAMESyncSettings GetSyncSettings() - { - return _syncSettings.Clone(); - } + public MAMESyncSettings GetSyncSettings() => _syncSettings.Clone(); public PutSettingsDirtyBits PutSyncSettings(MAMESyncSettings o) { @@ -72,17 +69,17 @@ public MAMESyncSettings Clone() public void FetchDefaultGameSettings() { - var DIPSwitchTags = MameGetString(MAMELuaCommand.GetDIPSwitchTags); - var tags = DIPSwitchTags.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); + string DIPSwitchTags = MameGetString(MAMELuaCommand.GetDIPSwitchTags); + string[] tags = DIPSwitchTags.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); - foreach (var tag in tags) + foreach (string tag in tags) { - var DIPSwitchFields = MameGetString(MAMELuaCommand.GetDIPSwitchFields(tag)); - var fieldNames = DIPSwitchFields.Split(new[] { '^' }, StringSplitOptions.RemoveEmptyEntries); + string DIPSwitchFields = MameGetString(MAMELuaCommand.GetDIPSwitchFields(tag)); + string[] fieldNames = DIPSwitchFields.Split(new[] { '^' }, StringSplitOptions.RemoveEmptyEntries); - foreach (var fieldName in fieldNames) + foreach (string fieldName in fieldNames) { - var setting = new DriverSetting + DriverSetting setting = new() { Name = fieldName, GameName = _gameShortName, @@ -92,12 +89,12 @@ public void FetchDefaultGameSettings() $"return { MAMELuaCommand.InputField(tag, fieldName) }.defvalue").ToString() }; - var DIPSwitchOptions = MameGetString(MAMELuaCommand.GetDIPSwitchOptions(tag, fieldName)); - var options = DIPSwitchOptions.Split(new[] { '@' }, StringSplitOptions.RemoveEmptyEntries); + string DIPSwitchOptions = MameGetString(MAMELuaCommand.GetDIPSwitchOptions(tag, fieldName)); + string[] options = DIPSwitchOptions.Split(new[] { '@' }, StringSplitOptions.RemoveEmptyEntries); - foreach (var option in options) + foreach (string option in options) { - var opt = option.Split(new[] { '~' }, StringSplitOptions.RemoveEmptyEntries); + string[] opt = option.Split(new[] { '~' }, StringSplitOptions.RemoveEmptyEntries); setting.Options.Add(opt[0], opt[1]); } @@ -124,11 +121,11 @@ public void OverrideGameSettings() private void GetROMsInfo() { - var ROMsInfo = MameGetString(MAMELuaCommand.GetROMsInfo); - var ROMs = ROMsInfo.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); - var tempDefault = string.Empty; + string ROMsInfo = MameGetString(MAMELuaCommand.GetROMsInfo); + string[] ROMs = ROMsInfo.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); + string tempDefault = string.Empty; - var setting = new DriverSetting + DriverSetting setting = new() { Name = "BIOS", GameName = _gameShortName, @@ -136,17 +133,17 @@ private void GetROMsInfo() Type = SettingType.BIOS }; - foreach (var ROM in ROMs) + foreach (string ROM in ROMs) { if (ROM != string.Empty) { - var substrings = ROM.Split('~'); - var name = substrings[0]; - var hashdata = substrings[1]; - var flags = long.Parse(substrings[2]); + string[] substrings = ROM.Split('~'); + string name = substrings[0]; + string hashdata = substrings[1]; + long flags = long.Parse(substrings[2]); - if ((flags & LibMAME.ROMENTRY_TYPEMASK) == LibMAME.ROMENTRYTYPE_SYSTEM_BIOS - || (flags & LibMAME.ROMENTRY_TYPEMASK) == LibMAME.ROMENTRYTYPE_DEFAULT_BIOS) + if ((flags & LibMAME.ROMENTRY_TYPEMASK) is LibMAME.ROMENTRYTYPE_SYSTEM_BIOS + or LibMAME.ROMENTRYTYPE_DEFAULT_BIOS) { setting.Options.Add(name, hashdata); @@ -179,10 +176,7 @@ private void GetROMsInfo() if (setting.Options.Count > 0) { - if (setting.DefaultValue == null) - { - setting.DefaultValue = tempDefault; - } + setting.DefaultValue ??= tempDefault; CurrentDriverSettings.Add(setting); } diff --git a/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.ISoundProvider.cs b/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.ISoundProvider.cs index 5caabf0290b..e01b408d750 100644 --- a/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.ISoundProvider.cs +++ b/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.ISoundProvider.cs @@ -21,10 +21,7 @@ public void SetSyncMode(SyncSoundMode mode) } } - private void UpdateSound() - { - _nsamps = _core.mame_sound_get_samples(_sampleBuffer); - } + private void UpdateSound() => _nsamps = _core.mame_sound_get_samples(_sampleBuffer); public void GetSamplesSync(out short[] samples, out int nsamp) { @@ -32,14 +29,8 @@ public void GetSamplesSync(out short[] samples, out int nsamp) nsamp = _nsamps; } - public void GetSamplesAsync(short[] samples) - { - throw new InvalidOperationException("Async mode is not supported."); - } + public void GetSamplesAsync(short[] samples) => throw new InvalidOperationException("Async mode is not supported."); - public void DiscardSamples() - { - _nsamps = 0; - } + public void DiscardSamples() => _nsamps = 0; } } \ No newline at end of file diff --git a/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.IVideoProvider.cs b/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.IVideoProvider.cs index 92ec289baa4..091b0f71387 100644 --- a/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.IVideoProvider.cs +++ b/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.IVideoProvider.cs @@ -44,11 +44,11 @@ private void UpdateAspect() private void UpdateVideo() { - _core.mame_video_get_dimensions(out var width, out var height); + _core.mame_video_get_dimensions(out int width, out int height); BufferWidth = width; BufferHeight = height; - var numPixels = width * height; + int numPixels = width * height; if (_frameBuffer.Length < numPixels) { diff --git a/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.MemoryDomains.cs b/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.MemoryDomains.cs index fc7dbbda94b..a4dbd64db2d 100644 --- a/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.MemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.MemoryDomains.cs @@ -59,13 +59,13 @@ public override void Exit() private void InitMemoryDomains() { - var domains = new List(); + List domains = new(); - var systemBusAddressShift = _core.mame_lua_get_int(MAMELuaCommand.GetSpaceAddressShift); - var dataWidth = _core.mame_lua_get_int(MAMELuaCommand.GetSpaceDataWidth) >> 3; // mame returns in bits - var size = _core.mame_lua_get_long(MAMELuaCommand.GetSpaceAddressMask) + dataWidth; - var endianString = MameGetString(MAMELuaCommand.GetSpaceEndianness); - var deviceName = MameGetString(MAMELuaCommand.GetMainCPUName); + int systemBusAddressShift = _core.mame_lua_get_int(MAMELuaCommand.GetSpaceAddressShift); + int dataWidth = _core.mame_lua_get_int(MAMELuaCommand.GetSpaceDataWidth) >> 3; // mame returns in bits + long size = _core.mame_lua_get_long(MAMELuaCommand.GetSpaceAddressMask) + dataWidth; + string endianString = MameGetString(MAMELuaCommand.GetSpaceEndianness); + string deviceName = MameGetString(MAMELuaCommand.GetMainCPUName); //var addrSize = (size * 2).ToString(); var endian = MemoryDomain.Endian.Unknown; @@ -79,18 +79,18 @@ private void InitMemoryDomains() endian = MemoryDomain.Endian.Big; } - var mapCount = _core.mame_lua_get_int(MAMELuaCommand.GetSpaceMapCount); + int mapCount = _core.mame_lua_get_int(MAMELuaCommand.GetSpaceMapCount); - for (var i = 1; i <= mapCount; i++) + for (int i = 1; i <= mapCount; i++) { - var read = MameGetString($"return { MAMELuaCommand.SpaceMap }[{ i }].read.handlertype"); - var write = MameGetString($"return { MAMELuaCommand.SpaceMap }[{ i }].write.handlertype"); + string read = MameGetString($"return { MAMELuaCommand.SpaceMap }[{ i }].read.handlertype"); + string write = MameGetString($"return { MAMELuaCommand.SpaceMap }[{ i }].write.handlertype"); if (read == "ram" && write == "ram" || read == "rom") { - var firstOffset = _core.mame_lua_get_int($"return { MAMELuaCommand.SpaceMap }[{ i }].address_start"); - var lastOffset = _core.mame_lua_get_int($"return { MAMELuaCommand.SpaceMap }[{ i }].address_end"); - var name = $"{ deviceName } : { read } : 0x{ firstOffset:X}-0x{ lastOffset:X}"; + int firstOffset = _core.mame_lua_get_int($"return { MAMELuaCommand.SpaceMap }[{ i }].address_start"); + int lastOffset = _core.mame_lua_get_int($"return { MAMELuaCommand.SpaceMap }[{ i }].address_end"); + string name = $"{ deviceName } : { read } : 0x{ firstOffset:X}-0x{ lastOffset:X}"; domains.Add(new MAMEMemoryDomain(name, lastOffset - firstOffset + 1, endian, dataWidth, read != "rom", _core, _exe, firstOffset, systemBusAddressShift, size)); diff --git a/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.cs b/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.cs index 52e2ad6dcb1..c246792717d 100644 --- a/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.cs +++ b/src/BizHawk.Emulation.Cores/Arcades/MAME/MAME.cs @@ -35,7 +35,7 @@ public MAME(CoreLoadParameters lp) _filenameCallback = name => _nvramFilenames.Add(name); _infoCallback = info => { - var text = info.Replace(". ", "\n").Replace("\n\n", "\n"); + string text = info.Replace(". ", "\n").Replace("\n\n", "\n"); lp.Comm.Notify(text, 4 * Regex.Matches(text, "\n").Count); RomDetails = $"Full Name: { _gameFullName }\r\n" + @@ -91,7 +91,7 @@ public MAME(CoreLoadParameters lp) } // concat all SHA1 hashes together (unprefixed), then hash that - var hashes = string.Concat(_romHashes.Values + string hashes = string.Concat(_romHashes.Values .Where(static s => s.Contains("SHA:")) .Select(static s => s.Split(' ') .First(static s => s.StartsWithOrdinal("SHA:")) @@ -141,7 +141,7 @@ private void StartMAME(List roms) _core.mame_set_log_callback(_logCallback); _core.mame_set_base_time_callback(_baseTimeCallback); - var gameName = _gameFileName.Split('.')[0]; + string gameName = _gameFileName.Split('.')[0]; static byte[] MakeRomData(IRomAsset rom) { @@ -149,17 +149,17 @@ static byte[] MakeRomData(IRomAsset rom) { // if this is deflate, unzip the zip, and rezip it without compression // this is to get around some zlib bug? - using var ret = new MemoryStream(); + using MemoryStream ret = new(); ret.Write(rom.FileData, 0, rom.FileData.Length); - using (var zip = new ZipArchive(ret, ZipArchiveMode.Update, leaveOpen: true)) + using (ZipArchive zip = new(ret, ZipArchiveMode.Update, leaveOpen: true)) { - foreach (var entryName in zip.Entries.Select(e => e.FullName).ToList()) + foreach (string entryName in zip.Entries.Select(e => e.FullName).ToList()) { try // TODO: this is a bad way to detect deflate (although it works I guess) { var oldEntry = zip.GetEntry(entryName)!; using var oldEntryStream = oldEntry.Open(); // if this isn't deflate, this throws InvalidDataException - var contents = oldEntryStream.ReadAllBytes(); + byte[] contents = oldEntryStream.ReadAllBytes(); oldEntryStream.Dispose(); oldEntry.Delete(); var newEntry = zip.CreateEntry(entryName, CompressionLevel.NoCompression); @@ -192,7 +192,7 @@ string MakeFileName(IRomAsset rom) } // https://docs.mamedev.org/commandline/commandline-index.html - var args = new List + List args = new() { "mame" // dummy, internally discarded by index, so has to go first , _gameFileName // no dash for rom names @@ -221,7 +221,7 @@ string MakeFileName(IRomAsset rom) if (_syncSettings.DriverSettings.TryGetValue( MAMELuaCommand.MakeLookupKey(gameName, LibMAME.BIOS_LUA_CODE), - out var value)) + out string value)) { args.AddRange(new[] { "-bios", value }); } @@ -262,7 +262,7 @@ string MakeFileName(IRomAsset rom) private string MameGetString(string command) { - var ptr = _core.mame_lua_get_string(command, out var lengthInBytes); + var ptr = _core.mame_lua_get_string(command, out int lengthInBytes); if (ptr == IntPtr.Zero) { @@ -270,7 +270,7 @@ private string MameGetString(string command) return string.Empty; } - var ret = Marshal.PtrToStringAnsi(ptr, lengthInBytes); + string ret = Marshal.PtrToStringAnsi(ptr, lengthInBytes); _core.mame_lua_free_string(ptr); return ret; } @@ -283,8 +283,8 @@ private void UpdateGameName() private void CheckVersions() { - var mameVersion = MameGetString(MAMELuaCommand.GetVersion); - var version = ((PortedCoreAttribute) this.Attributes()).PortedVersion; + string mameVersion = MameGetString(MAMELuaCommand.GetVersion); + string version = ((PortedCoreAttribute) this.Attributes()).PortedVersion; Debug.Assert(version == mameVersion, "MAME versions desync!\n\n" + $"MAME is { mameVersion }\n" + diff --git a/src/BizHawk.Emulation.Cores/Arcades/MAME/MAMEMachineDB.cs b/src/BizHawk.Emulation.Cores/Arcades/MAME/MAMEMachineDB.cs index dae31e314d1..07dc4407c00 100644 --- a/src/BizHawk.Emulation.Cores/Arcades/MAME/MAMEMachineDB.cs +++ b/src/BizHawk.Emulation.Cores/Arcades/MAME/MAMEMachineDB.cs @@ -25,7 +25,7 @@ public static void Initialize(string basePath) if (_acquire != null) throw new InvalidOperationException("MAME Machine DB multiply initialized"); _acquire = new(false); - var sw = Stopwatch.StartNew(); + Stopwatch sw = Stopwatch.StartNew(); ThreadPool.QueueUserWorkItem(_ => { Instance = new(basePath); @@ -36,11 +36,11 @@ public static void Initialize(string basePath) private MAMEMachineDB(string basePath) { - using var mameMachineFile = new HawkFile(Path.Combine(basePath, "mame_machines.txt")); - using var sr = new StreamReader(mameMachineFile.GetStream()); + using HawkFile mameMachineFile = new(Path.Combine(basePath, "mame_machines.txt")); + using StreamReader sr = new(mameMachineFile.GetStream()); while (true) { - var line = sr.ReadLine(); + string line = sr.ReadLine(); if (string.IsNullOrEmpty(line)) { diff --git a/src/BizHawk.Emulation.Cores/CPUs/68000/Diassembler.cs b/src/BizHawk.Emulation.Cores/CPUs/68000/Diassembler.cs index 9b5ff406e80..ffea3fa583b 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/68000/Diassembler.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/68000/Diassembler.cs @@ -17,7 +17,7 @@ partial class MC68000 { public DisassemblyInfo Disassemble(int pc) { - var info = new DisassemblyInfo { Mnemonic = "UNKNOWN", PC = pc, Length = 2 }; + DisassemblyInfo info = new() { Mnemonic = "UNKNOWN", PC = pc, Length = 2 }; op = (ushort)ReadWord(pc); if (Opcodes[op] == MOVE) MOVE_Disasm(info); @@ -102,7 +102,7 @@ public DisassemblyInfo Disassemble(int pc) else if (Opcodes[op] == MOVECCR) MOVECCR_Disasm(info); else if (Opcodes[op] == TRAP) TRAP_Disasm(info); - var sb = new StringBuilder(); + StringBuilder sb = new(); for (int p = info.PC; p < info.PC + info.Length; p++) sb.AppendFormat("{0:X2}", ReadByte(p)); info.RawBytes = sb.ToString(); diff --git a/src/BizHawk.Emulation.Cores/CPUs/68000/Instructions/DataMovement.cs b/src/BizHawk.Emulation.Cores/CPUs/68000/Instructions/DataMovement.cs index 57c02a77a81..3c57595c05c 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/68000/Instructions/DataMovement.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/68000/Instructions/DataMovement.cs @@ -92,15 +92,15 @@ private void MOVEA() case 5: PendingCycles -= 12; break; case 6: PendingCycles -= 14; break; case 7: - switch (srcReg) + PendingCycles -= srcReg switch { - case 0: PendingCycles -= 12; break; - case 1: PendingCycles -= 16; break; - case 2: PendingCycles -= 12; break; - case 3: PendingCycles -= 14; break; - case 4: PendingCycles -= 8; break; - default: throw new InvalidOperationException(); - } + 0 => 12, + 1 => 16, + 2 => 12, + 3 => 14, + 4 => 8, + _ => throw new InvalidOperationException(), + }; break; } } @@ -117,15 +117,15 @@ private void MOVEA() case 5: PendingCycles -= 16; break; case 6: PendingCycles -= 18; break; case 7: - switch (srcReg) + PendingCycles -= srcReg switch { - case 0: PendingCycles -= 16; break; - case 1: PendingCycles -= 20; break; - case 2: PendingCycles -= 16; break; - case 3: PendingCycles -= 18; break; - case 4: PendingCycles -= 12; break; - default: throw new InvalidOperationException(); - } + 0 => 16, + 1 => 20, + 2 => 16, + 3 => 18, + 4 => 12, + _ => throw new InvalidOperationException(), + }; break; } } @@ -389,7 +389,7 @@ private void MOVEM1() private static string DisassembleRegisterList0(uint registers) { - var str = new StringBuilder(); + StringBuilder str = new(); int count = 0; bool snip = false; for (int i = 0; i < 8; i++) @@ -444,7 +444,7 @@ private static string DisassembleRegisterList0(uint registers) private static string DisassembleRegisterList1(uint registers) { - var str = new StringBuilder(); + StringBuilder str = new(); int count = 0; bool snip = false; for (int i = 0; i < 8; i++) diff --git a/src/BizHawk.Emulation.Cores/CPUs/68000/Instructions/IntegerMath.cs b/src/BizHawk.Emulation.Cores/CPUs/68000/Instructions/IntegerMath.cs index 77b03704354..d0cc3cdc048 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/68000/Instructions/IntegerMath.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/68000/Instructions/IntegerMath.cs @@ -19,7 +19,7 @@ private void ADD0() int result = D[Dreg].s8 + value; int uresult = D[Dreg].u8 + (byte)value; X = C = (uresult & 0x100) != 0; - V = result > sbyte.MaxValue || result < sbyte.MinValue; + V = result is > sbyte.MaxValue or < sbyte.MinValue; N = (result & 0x80) != 0; Z = result == 0; D[Dreg].s8 = (sbyte)result; @@ -32,7 +32,7 @@ private void ADD0() int result = D[Dreg].s16 + value; int uresult = D[Dreg].u16 + (ushort)value; X = C = (uresult & 0x10000) != 0; - V = result > short.MaxValue || result < short.MinValue; + V = result is > short.MaxValue or < short.MinValue; N = (result & 0x8000) != 0; Z = result == 0; D[Dreg].s16 = (short)result; @@ -45,7 +45,7 @@ private void ADD0() long result = D[Dreg].s32 + value; long uresult = D[Dreg].u32 + (uint)value; X = C = (uresult & 0x100000000) != 0; - V = result > int.MaxValue || result < int.MinValue; + V = result is > int.MaxValue or < int.MinValue; N = (result & 0x80000000) != 0; Z = result == 0; D[Dreg].s32 = (int)result; @@ -70,7 +70,7 @@ private void ADD1() int result = value + D[Dreg].s8; int uresult = (byte)value + D[Dreg].u8; X = C = (uresult & 0x100) != 0; - V = result > sbyte.MaxValue || result < sbyte.MinValue; + V = result is > sbyte.MaxValue or < sbyte.MinValue; N = (result & 0x80) != 0; Z = result == 0; WriteValueB(mode, reg, (sbyte)result); @@ -83,7 +83,7 @@ private void ADD1() int result = value + D[Dreg].s16; int uresult = (ushort)value + D[Dreg].u16; X = C = (uresult & 0x10000) != 0; - V = result > short.MaxValue || result < short.MinValue; + V = result is > short.MaxValue or < short.MinValue; N = (result & 0x8000) != 0; Z = result == 0; WriteValueW(mode, reg, (short)result); @@ -96,7 +96,7 @@ private void ADD1() long result = value + D[Dreg].s32; long uresult = (uint)value + D[Dreg].u32; X = C = (uresult & 0x100000000) != 0; - V = result > int.MaxValue || result < int.MinValue; + V = result is > int.MaxValue or < int.MinValue; N = (result & 0x80000000) != 0; Z = result == 0; WriteValueL(mode, reg, (int)result); @@ -143,7 +143,7 @@ private void ADDI() int result = value + immed; int uresult = (byte)value + (byte)immed; X = C = (uresult & 0x100) != 0; - V = result > sbyte.MaxValue || result < sbyte.MinValue; + V = result is > sbyte.MaxValue or < sbyte.MinValue; N = (result & 0x80) != 0; Z = result == 0; WriteValueB(mode, reg, (sbyte)result); @@ -158,7 +158,7 @@ private void ADDI() int result = value + immed; int uresult = (ushort)value + (ushort)immed; X = C = (uresult & 0x10000) != 0; - V = result > short.MaxValue || result < short.MinValue; + V = result is > short.MaxValue or < short.MinValue; N = (result & 0x8000) != 0; Z = result == 0; WriteValueW(mode, reg, (short)result); @@ -173,7 +173,7 @@ private void ADDI() long result = value + immed; long uresult = (uint)value + (uint)immed; X = C = (uresult & 0x100000000) != 0; - V = result > int.MaxValue || result < int.MinValue; + V = result is > int.MaxValue or < int.MinValue; N = (result & 0x80000000) != 0; Z = result == 0; WriteValueL(mode, reg, (int)result); @@ -228,7 +228,7 @@ private void ADDQ() int uresult = (byte)value + data; N = (result & 0x80) != 0; Z = result == 0; - V = result > sbyte.MaxValue || result < sbyte.MinValue; + V = result is > sbyte.MaxValue or < sbyte.MinValue; C = X = (uresult & 0x100) != 0; WriteValueB(mode, reg, (sbyte)result); if (mode == 0) PendingCycles -= 4; @@ -249,7 +249,7 @@ private void ADDQ() int uresult = (ushort)value + data; N = (result & 0x8000) != 0; Z = result == 0; - V = result > short.MaxValue || result < short.MinValue; + V = result is > short.MaxValue or < short.MinValue; C = X = (uresult & 0x10000) != 0; WriteValueW(mode, reg, (short)result); } @@ -266,7 +266,7 @@ private void ADDQ() { N = (result & 0x80000000) != 0; Z = result == 0; - V = result > int.MaxValue || result < int.MinValue; + V = result is > int.MaxValue or < int.MinValue; C = X = (uresult & 0x100000000) != 0; } WriteValueL(mode, reg, (int)result); @@ -349,7 +349,7 @@ private void SUB0() sbyte b = ReadValueB(mode, reg); int result = a - b; X = C = ((a < b) ^ ((a ^ b) >= 0) == false); - V = result > sbyte.MaxValue || result < sbyte.MinValue; + V = result is > sbyte.MaxValue or < sbyte.MinValue; N = (result & 0x80) != 0; Z = result == 0; D[dReg].s8 = (sbyte)result; @@ -362,7 +362,7 @@ private void SUB0() short b = ReadValueW(mode, reg); int result = a - b; X = C = ((a < b) ^ ((a ^ b) >= 0) == false); - V = result > short.MaxValue || result < short.MinValue; + V = result is > short.MaxValue or < short.MinValue; N = (result & 0x8000) != 0; Z = result == 0; D[dReg].s16 = (short)result; @@ -375,7 +375,7 @@ private void SUB0() int b = ReadValueL(mode, reg); long result = a - b; X = C = ((a < b) ^ ((a ^ b) >= 0) == false); - V = result > int.MaxValue || result < int.MinValue; + V = result is > int.MaxValue or < int.MinValue; N = (result & 0x80000000) != 0; Z = result == 0; D[dReg].s32 = (int)result; @@ -400,7 +400,7 @@ private void SUB1() sbyte b = D[dReg].s8; int result = a - b; X = C = ((a < b) ^ ((a ^ b) >= 0) == false); - V = result > sbyte.MaxValue || result < sbyte.MinValue; + V = result is > sbyte.MaxValue or < sbyte.MinValue; N = (result & 0x80) != 0; Z = result == 0; WriteValueB(mode, reg, (sbyte)result); @@ -413,7 +413,7 @@ private void SUB1() short b = D[dReg].s16; int result = a - b; X = C = ((a < b) ^ ((a ^ b) >= 0) == false); - V = result > short.MaxValue || result < short.MinValue; + V = result is > short.MaxValue or < short.MinValue; N = (result & 0x8000) != 0; Z = result == 0; WriteValueW(mode, reg, (short)result); @@ -426,7 +426,7 @@ private void SUB1() int b = D[dReg].s32; long result = a - b; X = C = ((a < b) ^ ((a ^ b) >= 0) == false); - V = result > int.MaxValue || result < int.MinValue; + V = result is > int.MaxValue or < int.MinValue; N = (result & 0x80000000) != 0; Z = result == 0; WriteValueL(mode, reg, (int)result); @@ -472,7 +472,7 @@ private void SUBI() sbyte a = PeekValueB(mode, reg); int result = a - b; X = C = ((a < b) ^ ((a ^ b) >= 0) == false); - V = result > sbyte.MaxValue || result < sbyte.MinValue; + V = result is > sbyte.MaxValue or < sbyte.MinValue; N = (result & 0x80) != 0; Z = result == 0; WriteValueB(mode, reg, (sbyte)result); @@ -486,7 +486,7 @@ private void SUBI() short a = PeekValueW(mode, reg); int result = a - b; X = C = ((a < b) ^ ((a ^ b) >= 0) == false); - V = result > short.MaxValue || result < short.MinValue; + V = result is > short.MaxValue or < short.MinValue; N = (result & 0x8000) != 0; Z = result == 0; WriteValueW(mode, reg, (short)result); @@ -500,7 +500,7 @@ private void SUBI() int a = PeekValueL(mode, reg); long result = a - b; X = C = ((a < b) ^ ((a ^ b) >= 0) == false); - V = result > int.MaxValue || result < int.MinValue; + V = result is > int.MaxValue or < int.MinValue; N = (result & 0x80000000) != 0; Z = result == 0; WriteValueL(mode, reg, (int)result); @@ -554,7 +554,7 @@ private void SUBQ() int result = value - data; N = (result & 0x80) != 0; Z = result == 0; - V = result > sbyte.MaxValue || result < sbyte.MinValue; + V = result is > sbyte.MaxValue or < sbyte.MinValue; C = X = ((value < data) ^ ((value ^ data) >= 0) == false); WriteValueB(mode, reg, (sbyte)result); if (mode == 0) PendingCycles -= 4; @@ -574,7 +574,7 @@ private void SUBQ() int result = value - data; N = (result & 0x8000) != 0; Z = result == 0; - V = result > short.MaxValue || result < short.MinValue; + V = result is > short.MaxValue or < short.MinValue; C = X = ((value < data) ^ ((value ^ data) >= 0) == false); WriteValueW(mode, reg, (short)result); } @@ -590,7 +590,7 @@ private void SUBQ() { N = (result & 0x80000000) != 0; Z = result == 0; - V = result > int.MaxValue || result < int.MinValue; + V = result is > int.MaxValue or < int.MinValue; C = X = ((value < data) ^ ((value ^ data) >= 0) == false); } WriteValueL(mode, reg, (int)result); @@ -675,7 +675,7 @@ private void NEG() int result = 0 - value; N = (result & 0x80) != 0; Z = result == 0; - V = result > sbyte.MaxValue || result < sbyte.MinValue; + V = result is > sbyte.MaxValue or < sbyte.MinValue; C = X = ((0 < value) ^ ((0 ^ value) >= 0) == false); WriteValueB(mode, reg, (sbyte)result); if (mode == 0) PendingCycles -= 4; @@ -688,7 +688,7 @@ private void NEG() int result = 0 - value; N = (result & 0x8000) != 0; Z = result == 0; - V = result > short.MaxValue || result < short.MinValue; + V = result is > short.MaxValue or < short.MinValue; C = X = ((0 < value) ^ ((0 ^ value) >= 0) == false); WriteValueW(mode, reg, (short)result); if (mode == 0) PendingCycles -= 4; @@ -701,7 +701,7 @@ private void NEG() long result = 0 - value; N = (result & 0x80000000) != 0; Z = result == 0; - V = result > int.MaxValue || result < int.MinValue; + V = result is > int.MaxValue or < int.MinValue; C = X = ((0 < value) ^ ((0 ^ value) >= 0) == false); WriteValueL(mode, reg, (int)result); if (mode == 0) PendingCycles -= 8; @@ -754,7 +754,7 @@ private void CMP() int result = a - b; N = (result & 0x80) != 0; Z = result == 0; - V = result > sbyte.MaxValue || result < sbyte.MinValue; + V = result is > sbyte.MaxValue or < sbyte.MinValue; C = ((a < b) ^ ((a ^ b) >= 0) == false); if (mode == 0) PendingCycles -= 8; PendingCycles -= 4 + EACyclesBW[mode, reg]; @@ -767,7 +767,7 @@ private void CMP() int result = a - b; N = (result & 0x8000) != 0; Z = result == 0; - V = result > short.MaxValue || result < short.MinValue; + V = result is > short.MaxValue or < short.MinValue; C = ((a < b) ^ ((a ^ b) >= 0) == false); if (mode == 0) PendingCycles -= 8; PendingCycles -= 4 + EACyclesBW[mode, reg]; @@ -780,7 +780,7 @@ private void CMP() long result = a - b; N = (result & 0x80000000) != 0; Z = result == 0; - V = result > int.MaxValue || result < int.MinValue; + V = result is > int.MaxValue or < int.MinValue; C = ((a < b) ^ ((a ^ b) >= 0) == false); PendingCycles -= 6 + EACyclesL[mode, reg]; return; @@ -831,7 +831,7 @@ private void CMPA() int result = a - b; N = (result & 0x8000) != 0; Z = result == 0; - V = result > short.MaxValue || result < short.MinValue; + V = result is > short.MaxValue or < short.MinValue; C = ((a < b) ^ ((a ^ b) >= 0) == false); PendingCycles -= 6 + EACyclesBW[mode, reg]; return; @@ -843,7 +843,7 @@ private void CMPA() long result = a - b; N = (result & 0x80000000) != 0; Z = result == 0; - V = result > int.MaxValue || result < int.MinValue; + V = result is > int.MaxValue or < int.MinValue; C = ((a < b) ^ ((a ^ b) >= 0) == false); PendingCycles -= 6 + EACyclesL[mode, reg]; return; @@ -889,7 +889,7 @@ private void CMPM() int result = a - b; N = (result & 0x80) != 0; Z = result == 0; - V = result > sbyte.MaxValue || result < sbyte.MinValue; + V = result is > sbyte.MaxValue or < sbyte.MinValue; C = ((a < b) ^ ((a ^ b) >= 0) == false); PendingCycles -= 12; return; @@ -901,7 +901,7 @@ private void CMPM() int result = a - b; N = (result & 0x8000) != 0; Z = result == 0; - V = result > short.MaxValue || result < short.MinValue; + V = result is > short.MaxValue or < short.MinValue; C = ((a < b) ^ ((a ^ b) >= 0) == false); PendingCycles -= 12; return; @@ -913,7 +913,7 @@ private void CMPM() long result = a - b; N = (result & 0x80000000) != 0; Z = result == 0; - V = result > int.MaxValue || result < int.MinValue; + V = result is > int.MaxValue or < int.MinValue; C = ((a < b) ^ ((a ^ b) >= 0) == false); PendingCycles -= 20; return; @@ -953,7 +953,7 @@ private void CMPI() int result = a - b; N = (result & 0x80) != 0; Z = result == 0; - V = result > sbyte.MaxValue || result < sbyte.MinValue; + V = result is > sbyte.MaxValue or < sbyte.MinValue; C = ((a < b) ^ ((a ^ b) >= 0) == false); if (mode == 0) PendingCycles -= 8; else PendingCycles -= 8 + EACyclesBW[mode, reg]; @@ -966,7 +966,7 @@ private void CMPI() int result = a - b; N = (result & 0x8000) != 0; Z = result == 0; - V = result > short.MaxValue || result < short.MinValue; + V = result is > short.MaxValue or < short.MinValue; C = ((a < b) ^ ((a ^ b) >= 0) == false); if (mode == 0) PendingCycles -= 8; else PendingCycles -= 8 + EACyclesBW[mode, reg]; @@ -979,7 +979,7 @@ private void CMPI() long result = a - b; N = (result & 0x80000000) != 0; Z = result == 0; - V = result > int.MaxValue || result < int.MinValue; + V = result is > int.MaxValue or < int.MinValue; C = ((a < b) ^ ((a ^ b) >= 0) == false); if (mode == 0) PendingCycles -= 14; else PendingCycles -= 12 + EACyclesL[mode, reg]; @@ -1090,7 +1090,7 @@ private void DIVU() uint quotient = dest / source; uint remainder = dest % source; - V = ((int)quotient < short.MinValue || (int)quotient > short.MaxValue); + V = ((int)quotient is < short.MinValue or > short.MaxValue); N = (quotient & 0x8000) != 0; Z = quotient == 0; C = false; @@ -1126,7 +1126,7 @@ private void DIVS() int quotient = dest / source; int remainder = dest % source; - V = (quotient < short.MinValue || quotient > short.MaxValue); + V = (quotient is < short.MinValue or > short.MaxValue); N = (quotient & 0x8000) != 0; Z = quotient == 0; C = false; diff --git a/src/BizHawk.Emulation.Cores/CPUs/68000/Instructions/ProgramFlow.cs b/src/BizHawk.Emulation.Cores/CPUs/68000/Instructions/ProgramFlow.cs index 9aa956a982f..058c332d684 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/68000/Instructions/ProgramFlow.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/68000/Instructions/ProgramFlow.cs @@ -6,51 +6,50 @@ partial class MC68000 { private bool TestCondition(int condition) { - switch (condition) - { - case 0x00: return true; // True - case 0x01: return false; // False - case 0x02: return !C && !Z; // High (Unsigned) - case 0x03: return C || Z; // Less or Same (Unsigned) - case 0x04: return !C; // Carry Clear (High or Same) - case 0x05: return C; // Carry Set (Lower) - case 0x06: return !Z; // Not Equal - case 0x07: return Z; // Equal - case 0x08: return !V; // Overflow Clear - case 0x09: return V; // Overflow Set - case 0x0A: return !N; // Plus (Positive) - case 0x0B: return N; // Minus (Negative) - case 0x0C: return N && V || !N && !V; // Greater or Equal - case 0x0D: return N && !V || !N && V; // Less Than - case 0x0E: return N && V && !Z || !N && !V && !Z; // Greater Than - case 0x0F: return Z || N && !V || !N && V; // Less or Equal - default: - throw new Exception("Invalid condition " + condition); - } + return condition switch + { + 0x00 => true,// True + 0x01 => false,// False + 0x02 => !C && !Z,// High (Unsigned) + 0x03 => C || Z,// Less or Same (Unsigned) + 0x04 => !C,// Carry Clear (High or Same) + 0x05 => C,// Carry Set (Lower) + 0x06 => !Z,// Not Equal + 0x07 => Z,// Equal + 0x08 => !V,// Overflow Clear + 0x09 => V,// Overflow Set + 0x0A => !N,// Plus (Positive) + 0x0B => N,// Minus (Negative) + 0x0C => N && V || !N && !V,// Greater or Equal + 0x0D => N && !V || !N && V,// Less Than + 0x0E => N && V && !Z || !N && !V && !Z,// Greater Than + 0x0F => Z || N && !V || !N && V,// Less or Equal + _ => throw new Exception("Invalid condition " + condition), + }; } private string DisassembleCondition(int condition) { - switch (condition) - { - case 0x00: return "t"; // True - case 0x01: return "f"; // False - case 0x02: return "hi"; // High (Unsigned) - case 0x03: return "ls"; // Less or Same (Unsigned) - case 0x04: return "cc"; // Carry Clear (High or Same) - case 0x05: return "cs"; // Carry Set (Lower) - case 0x06: return "ne"; // Not Equal - case 0x07: return "eq"; // Equal - case 0x08: return "vc"; // Overflow Clear - case 0x09: return "vs"; // Overflow Set - case 0x0A: return "pl"; // Plus (Positive) - case 0x0B: return "mi"; // Minus (Negative) - case 0x0C: return "ge"; // Greater or Equal - case 0x0D: return "lt"; // Less Than - case 0x0E: return "gt"; // Greater Than - case 0x0F: return "le"; // Less or Equal - default: return "??"; // Invalid condition - } + return condition switch + { + 0x00 => "t",// True + 0x01 => "f",// False + 0x02 => "hi",// High (Unsigned) + 0x03 => "ls",// Less or Same (Unsigned) + 0x04 => "cc",// Carry Clear (High or Same) + 0x05 => "cs",// Carry Set (Lower) + 0x06 => "ne",// Not Equal + 0x07 => "eq",// Equal + 0x08 => "vc",// Overflow Clear + 0x09 => "vs",// Overflow Set + 0x0A => "pl",// Plus (Positive) + 0x0B => "mi",// Minus (Negative) + 0x0C => "ge",// Greater or Equal + 0x0D => "lt",// Less Than + 0x0E => "gt",// Greater Than + 0x0F => "le",// Less or Equal + _ => "??",// Invalid condition + }; } private void Bcc() // Branch on condition @@ -696,15 +695,9 @@ private void UNLK_Disasm(DisassemblyInfo info) info.Length = 2; } - private void NOP() - { - PendingCycles -= 4; - } + private void NOP() => PendingCycles -= 4; - private void NOP_Disasm(DisassemblyInfo info) - { - info.Mnemonic = "nop"; - } + private void NOP_Disasm(DisassemblyInfo info) => info.Mnemonic = "nop"; private void Scc() // Set on condition { diff --git a/src/BizHawk.Emulation.Cores/CPUs/68000/MC68000.cs b/src/BizHawk.Emulation.Cores/CPUs/68000/MC68000.cs index ec0ff467236..2dabff50b0d 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/68000/MC68000.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/68000/MC68000.cs @@ -18,16 +18,12 @@ public sealed partial class MC68000 // Status Registers private int InterruptMaskLevel; - private bool s, m; + private bool s; private int usp, ssp; /// Machine/Interrupt mode /// TODO probably have some switch logic maybe - public bool M - { - get => m; - set => m = value; - } + public bool M { get; set; } /// Supervisor/User mode public bool S @@ -208,7 +204,7 @@ public void SaveStateText(TextWriter writer, string id) writer.WriteLine("USP {0:X8}", usp); writer.WriteLine("SSP {0:X8}", ssp); writer.WriteLine("S {0}", s); - writer.WriteLine("M {0}", m); + writer.WriteLine("M {0}", M); writer.WriteLine(); writer.WriteLine($"{nameof(TotalExecutedCycles)} {TotalExecutedCycles}"); @@ -247,7 +243,7 @@ public void LoadStateText(TextReader reader, string id) else if (args[0] == "USP") usp = int.Parse(args[1], NumberStyles.HexNumber); else if (args[0] == "SSP") ssp = int.Parse(args[1], NumberStyles.HexNumber); else if (args[0] == "S") s = bool.Parse(args[1]); - else if (args[0] == "M") m = bool.Parse(args[1]); + else if (args[0] == "M") M = bool.Parse(args[1]); else if (args[0] == nameof(TotalExecutedCycles)) TotalExecutedCycles = int.Parse(args[1]); else if (args[0] == nameof(PendingCycles)) PendingCycles = int.Parse(args[1]); @@ -276,6 +272,6 @@ public struct Register [FieldOffset(0)] public sbyte s8; - public override string ToString() => $"{u32:X8}"; + public override readonly string ToString() => $"{u32:X8}"; } } diff --git a/src/BizHawk.Emulation.Cores/CPUs/68000/Memory.cs b/src/BizHawk.Emulation.Cores/CPUs/68000/Memory.cs index d456c4c5d49..be794a67daf 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/68000/Memory.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/68000/Memory.cs @@ -556,15 +556,13 @@ private int GetIndex() int size = (extension >> 11) & 0x1; int scale = (extension >> 9) & 0x3; sbyte displacement = (sbyte)extension; - - int indexReg; - switch (scale) + int indexReg = scale switch { - case 0: indexReg = 1; break; - case 1: indexReg = 2; break; - case 2: indexReg = 4; break; - default: indexReg = 8; break; - } + 0 => 1, + 1 => 2, + 2 => 4, + _ => 8, + }; if (da == 0) indexReg *= size == 0 ? D[reg].s16 : D[reg].s32; else @@ -584,15 +582,13 @@ private int PeekIndex() int size = (extension >> 11) & 0x1; int scale = (extension >> 9) & 0x3; sbyte displacement = (sbyte)extension; - - int indexReg; - switch (scale) + int indexReg = scale switch { - case 0: indexReg = 1; break; - case 1: indexReg = 2; break; - case 2: indexReg = 4; break; - default: indexReg = 8; break; - } + 0 => 1, + 1 => 2, + 2 => 4, + _ => 8, + }; if (da == 0) indexReg *= size == 0 ? D[reg].s16 : D[reg].s32; else @@ -608,16 +604,13 @@ private string DisassembleIndex(string baseRegister, short extension) int size = (extension >> 11) & 0x1; int scale = (extension >> 9) & 0x3; sbyte displacement = (sbyte)extension; - - string scaleFactor; - switch (scale) + string scaleFactor = scale switch { - case 0: scaleFactor = ""; break; - case 1: scaleFactor = "2"; break; - case 2: scaleFactor = "4"; break; - default: scaleFactor = "8"; break; - } - + 0 => "", + 1 => "2", + 2 => "4", + _ => "8", + }; string offsetRegister = (d_a == 0) ? "D" : "A"; string sizeStr = size == 0 ? ".w" : ".l"; string displacementStr = displacement == 0 ? "" : ("," + displacement); diff --git a/src/BizHawk.Emulation.Cores/CPUs/68000/OpcodeTable.cs b/src/BizHawk.Emulation.Cores/CPUs/68000/OpcodeTable.cs index e6fc59cccf5..2429096187d 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/68000/OpcodeTable.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/68000/OpcodeTable.cs @@ -98,10 +98,12 @@ private void BuildOpcodeTable() private void Assign(string instr, Action exec, string root, params string[] bitfield) { - List opList = new List(); - opList.Add(root); + List opList = new() + { + root + }; - foreach (var component in bitfield) + foreach (string component in bitfield) { if (component.IsBinary()) AppendConstant(opList, component); else if (component == "Size1") opList = AppendPermutations(opList, Size1); @@ -118,7 +120,7 @@ private void Assign(string instr, Action exec, string root, params string[] bitf else if (component == "Data8") opList = AppendData(opList, 8); } - foreach (var opcode in opList) + foreach (string opcode in opList) { int opc = Convert.ToInt32(opcode, 2); if (Opcodes[opc] != null && !instr.In("movea", "andi2sr", "eori2sr", "ori2sr", "ext", "dbcc", "swap", "cmpm")) @@ -135,10 +137,10 @@ private void AppendConstant(List ops, string constant) private List AppendPermutations(List ops, string[] permutations) { - List output = new List(); + List output = new(); - foreach (var input in ops) - foreach (var perm in permutations) + foreach (string input in ops) + foreach (string perm in permutations) output.Add(input + perm); return output; @@ -146,9 +148,9 @@ private List AppendPermutations(List ops, string[] permutations) private List AppendData(List ops, int bits) { - List output = new List(); + List output = new(); - foreach (var input in ops) + foreach (string input in ops) for (int i = 0; i < BinaryExp(bits); i++) output.Add(input + Convert.ToString(i, 2).PadLeft(bits, '0')); diff --git a/src/BizHawk.Emulation.Cores/CPUs/ARM/Darm.cs b/src/BizHawk.Emulation.Cores/CPUs/ARM/Darm.cs index 2f51213b6bd..de763e6e38a 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/ARM/Darm.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/ARM/Darm.cs @@ -92,8 +92,8 @@ public class Darm_Str_T public string DisassembleStuff(uint addr, uint opcode) { - var d = new Darm_T(); - var s = new Darm_Str_T(); + Darm_T d = new(); + Darm_Str_T s = new(); if (!Disassemble(d, (ushort)opcode, (ushort)(opcode >> 16), addr)) return null; if (Str(d, s, false)) diff --git a/src/BizHawk.Emulation.Cores/CPUs/CP1610/CP1610.Execute.cs b/src/BizHawk.Emulation.Cores/CPUs/CP1610/CP1610.Execute.cs index 1b663b78950..64350006f27 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/CP1610/CP1610.Execute.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/CP1610/CP1610.Execute.cs @@ -34,10 +34,7 @@ public TraceInfo CP1610State(bool disassemble = true) FlagD ? "D" : "d") }.Concat(Register.Select((r, i) => $"R{i}:{r:X4}")))); - private void Calc_FlagC(int result) - { - FlagC = ((result & 0x10000) != 0); - } + private void Calc_FlagC(int result) => FlagC = ((result & 0x10000) != 0); private void Calc_FlagO_Add(int op1, int op2, int result) { @@ -61,20 +58,11 @@ private void Calc_FlagO_Sub(int op1, int op2, int result) ); } - private void Calc_FlagS(int result) - { - FlagS = ((result & 0x8000) != 0); - } + private void Calc_FlagS(int result) => FlagS = ((result & 0x8000) != 0); - private void Calc_FlagS_7(int result) - { - FlagS = ((result & 0x80) != 0); - } + private void Calc_FlagS_7(int result) => FlagS = ((result & 0x80) != 0); - private void Calc_FlagZ(int result) - { - FlagZ = (result == 0); - } + private void Calc_FlagZ(int result) => FlagZ = (result == 0); private ushort Indirect_Get(byte mem) { @@ -97,7 +85,7 @@ private ushort Indirect_Get(byte mem) value |= (ushort)(ReadMemoryWrapper(Register[mem], false) << 8); } // Auto-increment the memory register if it does so on write. - if (mem >= 0x4 && mem != 0x6) + if (mem is >= 0x4 and not 0x6) { Register[mem]++; } @@ -307,7 +295,7 @@ falling edge. case 0x027: dest = (byte)(opcode & 0x7); dest_value = Register[dest]; - var ones = (dest_value ^ 0xFFFF); + int ones = (dest_value ^ 0xFFFF); result = ones + 1; Calc_FlagC(result); Calc_FlagO_Sub(dest_value, 0, result); @@ -329,7 +317,7 @@ falling edge. case 0x02F: dest = (byte)(opcode & 0x7); dest_value = Register[dest]; - var carry = FlagC ? 1 : 0; + int carry = FlagC ? 1 : 0; result = dest_value + carry; Calc_FlagC(result); Calc_FlagO_Add(dest_value, carry, result); @@ -694,7 +682,7 @@ falling edge. Calc_FlagS(result); Calc_FlagZ(result); Register[dest] = (ushort)result; - if (dest == 0x6 || dest == 0x7) + if (dest is 0x6 or 0x7) { cycles = 7; } diff --git a/src/BizHawk.Emulation.Cores/CPUs/CP1610/CP1610.cs b/src/BizHawk.Emulation.Cores/CPUs/CP1610/CP1610.cs index 34d2d7828e0..f9da485fe70 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/CP1610/CP1610.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/CP1610/CP1610.cs @@ -98,10 +98,7 @@ public void Reset() PendingCycles = 0; } - public bool GetBusAk() - { - return BusAk; - } + public bool GetBusAk() => BusAk; public void SetIntRM(bool value) { @@ -112,20 +109,11 @@ public void SetIntRM(bool value) } } - public void SetBusRq(bool value) - { - BusRq = !value; - } + public void SetBusRq(bool value) => BusRq = !value; - public int GetPendingCycles() - { - return PendingCycles; - } + public int GetPendingCycles() => PendingCycles; - public void AddPendingCycles(int cycles) - { - PendingCycles += cycles; - } + public void AddPendingCycles(int cycles) => PendingCycles += cycles; public IDictionary GetCpuFlagsAndRegisters() { diff --git a/src/BizHawk.Emulation.Cores/CPUs/FairchildF8/F3850.Disassembler.cs b/src/BizHawk.Emulation.Cores/CPUs/FairchildF8/F3850.Disassembler.cs index 8b4ad69ed77..d15f7c0ae7f 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/FairchildF8/F3850.Disassembler.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/FairchildF8/F3850.Disassembler.cs @@ -27,7 +27,7 @@ private static string Result(string format, Func read, ref ushort if (format.IndexOf("+d", StringComparison.Ordinal) != -1) format = format.Replace("+d", "d"); if (format.IndexOf("d", StringComparison.Ordinal) != -1) { - var b = unchecked((sbyte)read(addr++)); + sbyte b = unchecked((sbyte)read(addr++)); format = format.Replace("d", $"{(b < 0 ? '-' : '+')}{(b < 0 ? -b : b):X2}h"); } diff --git a/src/BizHawk.Emulation.Cores/CPUs/FairchildF8/F3850.Execute.cs b/src/BizHawk.Emulation.Cores/CPUs/FairchildF8/F3850.Execute.cs index eec20ccda79..8e84df5909e 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/FairchildF8/F3850.Execute.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/FairchildF8/F3850.Execute.cs @@ -17,7 +17,7 @@ public sealed partial class F3850 private string debug = ""; private void UpdateDebug() { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); for (int i = 0; i < 255; i++) { if (dLog[i] > 0) diff --git a/src/BizHawk.Emulation.Cores/CPUs/FairchildF8/F3850.Operations.cs b/src/BizHawk.Emulation.Cores/CPUs/FairchildF8/F3850.Operations.cs index 21f503bbe7b..5dddbf3be10 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/FairchildF8/F3850.Operations.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/FairchildF8/F3850.Operations.cs @@ -7,20 +7,11 @@ namespace BizHawk.Emulation.Cores.Components.FairchildF8 /// public sealed partial class F3850 { - public void Read_Func(byte dest, byte src_l, byte src_h) - { - Regs[dest] = ReadMemory((ushort)(Regs[src_l] | (Regs[src_h]) << 8)); - } + public void Read_Func(byte dest, byte src_l, byte src_h) => Regs[dest] = ReadMemory((ushort)(Regs[src_l] | (Regs[src_h]) << 8)); - public void Write_Func(byte dest_l, byte dest_h, byte src) - { - WriteMemory((ushort)(Regs[dest_l] | (Regs[dest_h] << 8)), Regs[src]); - } + public void Write_Func(byte dest_l, byte dest_h, byte src) => WriteMemory((ushort)(Regs[dest_l] | (Regs[dest_h] << 8)), Regs[src]); - public void IN_Func(byte dest, byte src) - { - Regs[dest] = ReadHardware(Regs[src]); - } + public void IN_Func(byte dest, byte src) => Regs[dest] = ReadHardware(Regs[src]); /// /// Helper method moving from IO pins to accumulator @@ -48,12 +39,10 @@ public void LR_A_IO_Func(byte dest, byte src) /// /// /// - public void OUT_Func(byte dest, byte src) - { + public void OUT_Func(byte dest, byte src) => // data is complemented between accumulator and I/O pins (because PINs are active-low) // however for ease here we will make them active-high WriteHardware(Regs[dest], Regs[src]); - } public void ClearFlags_Func() { @@ -173,9 +162,9 @@ public void ADDD_Func(byte dest, byte src) // STEP 1: Binary add H'66' to the augend. (this should happen before this function is called) // STEP 2: Binary add the addend to the sum from Step 1. Record the status of the carry (C) and intermediate carry (IC). - var augend = Regs[dest]; - var addend = Regs[src]; - var working = (byte)(augend + addend); + byte augend = Regs[dest]; + byte addend = Regs[src]; + byte working = (byte)(augend + addend); bool highCarry; bool lowCarry; @@ -183,7 +172,7 @@ public void ADDD_Func(byte dest, byte src) highCarry = ((augend + addend) & 0xFF0) > 0xF0; lowCarry = (augend & 0x0F) + (addend & 0x0F) > 0x0F; - var res = augend + addend; + int res = augend + addend; FlagC = res.Bit(8); FlagO = (Regs[dest].Bit(7) == Regs[src].Bit(7)) && (Regs[dest].Bit(7) != res.Bit(7)); FlagS = !working.Bit(7); @@ -227,7 +216,7 @@ public void ADDD_Func(byte dest, byte src) public void CI_Func() { //var twosComp = (byte)((Regs[A] ^ 0xFF) + 1); - var twosComp = (byte)(~Regs[A]); + byte twosComp = (byte)(~Regs[A]); Regs[ALU0] = twosComp; Regs[ALU1] = Regs[DB]; ADD_Func(ALU0, ALU1, ONE); diff --git a/src/BizHawk.Emulation.Cores/CPUs/FairchildF8/F3850.Registers.cs b/src/BizHawk.Emulation.Cores/CPUs/FairchildF8/F3850.Registers.cs index 2981c7ebe1a..7b4759f58b7 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/FairchildF8/F3850.Registers.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/FairchildF8/F3850.Registers.cs @@ -244,7 +244,7 @@ public ushort RegIRQV public IDictionary GetCpuFlagsAndRegisters() { - var res = new Dictionary + Dictionary res = new() { ["A"] = Regs[A], ["W"] = Regs[W], @@ -277,7 +277,7 @@ public void SetCpuRegister(string register, int value) { if (register.StartsWithOrdinal("SPR")) { - var reg = Convert.ToInt32(register.Replace("SPR", "")); + int reg = Convert.ToInt32(register.Replace("SPR", "")); if (reg > 63) { @@ -340,7 +340,7 @@ public void SetCpuRegister(string register, int value) private void ResetRegisters() { - for (var i = 0; i < Regs.Length; i++) + for (int i = 0; i < Regs.Length; i++) { Regs[i] = 0; } diff --git a/src/BizHawk.Emulation.Cores/CPUs/FairchildF8/F3850.Tables.cs b/src/BizHawk.Emulation.Cores/CPUs/FairchildF8/F3850.Tables.cs index 61c12ca6ba2..3f9f8f67381 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/FairchildF8/F3850.Tables.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/FairchildF8/F3850.Tables.cs @@ -766,10 +766,7 @@ private void CI() /// /// Illegal Opcode - just do a short cycle NOP /// - private void ILLEGAL() - { - NOP(); - } + private void ILLEGAL() => NOP(); /// /// IN - INPUT LONG ADDRESS diff --git a/src/BizHawk.Emulation.Cores/CPUs/FairchildF8/F3850.cs b/src/BizHawk.Emulation.Cores/CPUs/FairchildF8/F3850.cs index 5d031e83595..5d5dc982bad 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/FairchildF8/F3850.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/FairchildF8/F3850.cs @@ -757,9 +757,7 @@ public void ExecuteOne() // Devices with DC0 and DC1 registers must switch registers. Devices without a DC1 register perform no operation // CYCLE LENGTH: S case ROMC_1D: - ushort temp = RegDC0; - RegDC0 = RegDC1; - RegDC1 = temp; + (RegDC1, RegDC0) = (RegDC0, RegDC1); break; // The device whose address space includes the contents of PC0 must place the low order byte of PC0 onto the data bus diff --git a/src/BizHawk.Emulation.Cores/CPUs/HuC6280/HuC6280.cs b/src/BizHawk.Emulation.Cores/CPUs/HuC6280/HuC6280.cs index f17360fa68e..0de2683043b 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/HuC6280/HuC6280.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/HuC6280/HuC6280.cs @@ -28,10 +28,7 @@ public void Reset() LowSpeed = true; } - public void ResetPC() - { - PC = ReadWord(ResetVector); - } + public void ResetPC() => PC = ReadWord(ResetVector); // ==== CPU State ==== @@ -214,10 +211,7 @@ public void WriteIrqControl(byte value) IRQNextControlByte = value; } - public void WriteIrqStatus() - { - TimerAssert = false; - } + public void WriteIrqStatus() => TimerAssert = false; public byte ReadIrqStatus() { diff --git a/src/BizHawk.Emulation.Cores/CPUs/HuC6280/HuC6280_CDL.cs b/src/BizHawk.Emulation.Cores/CPUs/HuC6280/HuC6280_CDL.cs index 98601be50b4..55599f97211 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/HuC6280/HuC6280_CDL.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/HuC6280/HuC6280_CDL.cs @@ -8,7 +8,7 @@ public partial class HuC6280 { public void DisassembleCDL(Stream s, ICodeDataLog cdl, IMemoryDomains mem) { - var w = new StreamWriter(s); + StreamWriter w = new(s); w.WriteLine("; Bizhawk CDL Disassembly"); w.WriteLine(); foreach (var kvp in cdl) @@ -44,7 +44,7 @@ public struct MemMapping public string Name; public int Offs; public int VOffs; // if non-zero, specifies a larger potential offset - public int MaxOffs => Math.Max(Offs, VOffs); + public readonly int MaxOffs => Math.Max(Offs, VOffs); } public MemMapping[] Mappings; // = new MemMapping[256]; diff --git a/src/BizHawk.Emulation.Cores/CPUs/Intel8048/Disassembler.cs b/src/BizHawk.Emulation.Cores/CPUs/Intel8048/Disassembler.cs index ae81dd1f92b..5fbcb93cab3 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/Intel8048/Disassembler.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/Intel8048/Disassembler.cs @@ -269,8 +269,10 @@ public sealed partial class I8048 public static string Disassemble(ushort addr, Func reader, out ushort size) { ushort origaddr = addr; - List bytes = new List(); - bytes.Add(reader(addr++)); + List bytes = new() + { + reader(addr++) + }; string result = table[bytes[0]]; @@ -281,9 +283,9 @@ public static string Disassemble(ushort addr, Func reader, out ush result = result.Replace("i8", string.Format("#{0:X2}h", d)); } - StringBuilder ret = new StringBuilder(); + StringBuilder ret = new(); ret.Append(string.Format("{0:X4}: ", origaddr)); - foreach (var b in bytes) + foreach (byte b in bytes) ret.Append(string.Format("{0:X2} ", b)); while (ret.Length < 22) ret.Append(' '); diff --git a/src/BizHawk.Emulation.Cores/CPUs/Intel8048/Operations.cs b/src/BizHawk.Emulation.Cores/CPUs/Intel8048/Operations.cs index 021304dc626..c32e02ea23a 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/Intel8048/Operations.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/Intel8048/Operations.cs @@ -20,10 +20,7 @@ public void Write_Func(ushort dest, ushort src) WriteMemory(Regs[dest], (byte)Regs[src]); } - public void TR_Func(ushort dest, ushort src) - { - Regs[dest] = Regs[src]; - } + public void TR_Func(ushort dest, ushort src) => Regs[dest] = Regs[src]; public void ADD8_Func(ushort dest, ushort src) { @@ -43,20 +40,11 @@ public void ADD8_Func(ushort dest, ushort src) Regs[dest] = ans; } - public void AND8_Func(ushort dest, ushort src) - { - Regs[dest] = (ushort)(Regs[dest] & Regs[src]); - } + public void AND8_Func(ushort dest, ushort src) => Regs[dest] = (ushort)(Regs[dest] & Regs[src]); - public void OR8_Func(ushort dest, ushort src) - { - Regs[dest] = (ushort)(Regs[dest] | Regs[src]); - } + public void OR8_Func(ushort dest, ushort src) => Regs[dest] = (ushort)(Regs[dest] | Regs[src]); - public void XOR8_Func(ushort dest, ushort src) - { - Regs[dest] = (ushort)(Regs[dest] ^ Regs[src]); - } + public void XOR8_Func(ushort dest, ushort src) => Regs[dest] = (ushort)(Regs[dest] ^ Regs[src]); public void ROR_Func(ushort src) { @@ -89,15 +77,9 @@ public void RLC_Func(ushort src) Regs[src] = (ushort)(((Regs[src] << 1) & 0xFF) | c); } - public void INC8_Func(ushort src) - { - Regs[src] = (ushort)((Regs[src] + 1) & 0xFF); - } + public void INC8_Func(ushort src) => Regs[src] = (ushort)((Regs[src] + 1) & 0xFF); - public void DEC8_Func(ushort src) - { - Regs[src] = (ushort)((Regs[src] - 1) & 0xFF); - } + public void DEC8_Func(ushort src) => Regs[src] = (ushort)((Regs[src] - 1) & 0xFF); public void ADC8_Func(ushort dest, ushort src) { diff --git a/src/BizHawk.Emulation.Cores/CPUs/LR35902/NewDisassembler.cs b/src/BizHawk.Emulation.Cores/CPUs/LR35902/NewDisassembler.cs index 840294ffd25..fcb62ae92b9 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/LR35902/NewDisassembler.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/LR35902/NewDisassembler.cs @@ -1043,7 +1043,7 @@ public sealed partial class LR35902 public static string Disassemble(ushort addr, Func reader, bool rgbds, out ushort size) { ushort origaddr = addr; - var bytes = new List + List bytes = new() { reader(addr++) }; @@ -1090,7 +1090,7 @@ public static string Disassemble(ushort addr, Func reader, bool rg int offs = d; if (offs >= 128) offs -= 256; - var u = (ushort) (addr + offs); + ushort u = (ushort) (addr + offs); result = result.Replace("r8", rgbds ? $"${u:X4}" : $"{u:X4}h"); } else if (result.Contains("e8")) @@ -1101,9 +1101,9 @@ public static string Disassemble(ushort addr, Func reader, bool rg string sign = (d >= 128) ? "-" : ""; result = result.Replace("e8", rgbds ? sign + $"${offs:X2}" : sign + $"{offs:X2}h"); } - var ret = new StringBuilder(); + StringBuilder ret = new(); ret.Append($"{origaddr:X4}: "); - foreach (var b in bytes) + foreach (byte b in bytes) ret.Append($"{b:X2} "); while (ret.Length < 17) ret.Append(' '); diff --git a/src/BizHawk.Emulation.Cores/CPUs/LR35902/Operations.cs b/src/BizHawk.Emulation.Cores/CPUs/LR35902/Operations.cs index 60e28cfe253..17661528791 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/LR35902/Operations.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/LR35902/Operations.cs @@ -22,10 +22,7 @@ public void Read_Func(ushort dest, ushort src_l, ushort src_h) } // special read for POP AF that always clears the lower 4 bits of F - public void Read_Func_F(ushort dest, ushort src_l, ushort src_h) - { - Regs[dest] = (byte)(ReadMemory((ushort)(Regs[src_l] | (Regs[src_h]) << 8)) & 0xF0); - } + public void Read_Func_F(ushort dest, ushort src_l, ushort src_h) => Regs[dest] = (byte)(ReadMemory((ushort)(Regs[src_l] | (Regs[src_h]) << 8)) & 0xF0); public void Write_Func(ushort dest_l, ushort dest_h, ushort src) { @@ -34,10 +31,7 @@ public void Write_Func(ushort dest_l, ushort dest_h, ushort src) WriteMemory(addr, (byte)Regs[src]); } - public void TR_Func(ushort dest, ushort src) - { - Regs[dest] = Regs[src]; - } + public void TR_Func(ushort dest, ushort src) => Regs[dest] = Regs[src]; public void ADD16_Func(ushort dest_l, ushort dest_h, ushort src_l, ushort src_h) { @@ -112,20 +106,11 @@ public void BIT_Func(ushort bit, ushort src) FlagN = false; } - public void SET_Func(ushort bit, ushort src) - { - Regs[src] |= (ushort)(1 << bit); - } + public void SET_Func(ushort bit, ushort src) => Regs[src] |= (ushort)(1 << bit); - public void RES_Func(ushort bit, ushort src) - { - Regs[src] &= (ushort)(0xFF - (1 << bit)); - } + public void RES_Func(ushort bit, ushort src) => Regs[src] &= (ushort)(0xFF - (1 << bit)); - public void ASGN_Func(ushort src, ushort val) - { - Regs[src] = val; - } + public void ASGN_Func(ushort src, ushort val) => Regs[src] = val; public void SWAP_Func(ushort src) { @@ -251,7 +236,7 @@ public void RRC_Func(ushort src) Regs[src] = (ushort)((FlagC ? 0x80 : 0) | (Regs[src] >> 1)); - FlagZ = imm ? false : (Regs[src] == 0); + FlagZ = !imm && (Regs[src] == 0); FlagH = false; FlagN = false; } @@ -267,7 +252,7 @@ public void RR_Func(ushort src) Regs[src] = (ushort)(c | (Regs[src] >> 1)); - FlagZ = imm ? false : (Regs[src] == 0); + FlagZ = !imm && (Regs[src] == 0); FlagH = false; FlagN = false; } @@ -282,7 +267,7 @@ public void RLC_Func(ushort src) Regs[src] = (ushort)(((Regs[src] << 1) & 0xFF) | c); - FlagZ = imm ? false : (Regs[src] == 0); + FlagZ = !imm && (Regs[src] == 0); FlagH = false; FlagN = false; } @@ -297,7 +282,7 @@ public void RL_Func(ushort src) Regs[src] = (ushort)(((Regs[src] << 1) & 0xFF) | c); - FlagZ = imm ? false : (Regs[src] == 0); + FlagZ = !imm && (Regs[src] == 0); FlagH = false; FlagN = false; } diff --git a/src/BizHawk.Emulation.Cores/CPUs/MC6800/Disassembler.cs b/src/BizHawk.Emulation.Cores/CPUs/MC6800/Disassembler.cs index d5b41fe0265..82d6eaaf120 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/MC6800/Disassembler.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/MC6800/Disassembler.cs @@ -269,8 +269,10 @@ public sealed partial class MC6800 public static string Disassemble(ushort addr, Func reader, out ushort size) { ushort origaddr = addr; - List bytes = new List(); - bytes.Add(reader(addr++)); + List bytes = new() + { + reader(addr++) + }; string result = table[bytes[0]]; @@ -305,9 +307,9 @@ public static string Disassemble(ushort addr, Func reader, out ush result = result.Replace("ea", string.Format("{0:N}h", d)); } - StringBuilder ret = new StringBuilder(); + StringBuilder ret = new(); ret.Append(string.Format("{0:X4}: ", origaddr)); - foreach (var b in bytes) + foreach (byte b in bytes) ret.Append(string.Format("{0:X2} ", b)); while (ret.Length < 22) ret.Append(' '); diff --git a/src/BizHawk.Emulation.Cores/CPUs/MC6800/Indexed_Modes.cs b/src/BizHawk.Emulation.Cores/CPUs/MC6800/Indexed_Modes.cs index 91892ef5f53..448693ade0a 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/MC6800/Indexed_Modes.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/MC6800/Indexed_Modes.cs @@ -90,6 +90,7 @@ private void INDEX_OP_ST() IRQS = 3; } + #pragma warning disable IDE0051 private void INDEX_OP_LDD() { PopulateCURINSTR(IDLE, @@ -107,6 +108,7 @@ private void INDEX_OP_STD() IRQS = 3; } + #pragma warning restore IDE0051 private void INDEX_OP_EX4(ushort oper) { @@ -134,6 +136,7 @@ private void INDEX_OP_EX6(ushort oper) IRQS = 4; } + #pragma warning disable IDE0051 private void INDEX_OP_EX6D(ushort oper) { PopulateCURINSTR(IDLE, @@ -143,6 +146,7 @@ private void INDEX_OP_EX6D(ushort oper) IRQS = 4; } + #pragma warning restore IDE0051 private void INDEX_CMP_EX6(ushort oper) { diff --git a/src/BizHawk.Emulation.Cores/CPUs/MC6800/OP_Tables.cs b/src/BizHawk.Emulation.Cores/CPUs/MC6800/OP_Tables.cs index 177e8a72579..fea20a3d612 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/MC6800/OP_Tables.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/MC6800/OP_Tables.cs @@ -36,6 +36,7 @@ private void REG_OP_16(ushort oper, ushort src) IRQS = 3; } + #pragma warning disable IDE0051 private void DIRECT_MEM(ushort oper) { PopulateCURINSTR(RD_INC, ALU, PC, @@ -46,6 +47,7 @@ private void DIRECT_MEM(ushort oper) IRQS = 5; } + #pragma warning restore IDE0051 private void DIRECT_ST_4(ushort dest) { diff --git a/src/BizHawk.Emulation.Cores/CPUs/MC6800/Operations.cs b/src/BizHawk.Emulation.Cores/CPUs/MC6800/Operations.cs index eab346e9e61..d42f5dbdb1d 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/MC6800/Operations.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/MC6800/Operations.cs @@ -79,10 +79,7 @@ public void NEG_8_Func(ushort src) Regs[src] = ans; } - public void TR_Func(ushort dest, ushort src) - { - Regs[dest] = Regs[src]; - } + public void TR_Func(ushort dest, ushort src) => Regs[dest] = Regs[src]; public void LD_8_Func(ushort dest, ushort src) { @@ -315,15 +312,9 @@ public void DEC8_Func(ushort src) FlagN = (Regs[src] & 0xFF) > 127; } - public void INC16_Func(ushort src) - { - Regs[src] += 1; - } + public void INC16_Func(ushort src) => Regs[src] += 1; - public void DEC16_Func(ushort src) - { - Regs[src] -= 1; - } + public void DEC16_Func(ushort src) => Regs[src] -= 1; public void ADC8_Func(ushort dest, ushort src) { diff --git a/src/BizHawk.Emulation.Cores/CPUs/MC6809/Disassembler.cs b/src/BizHawk.Emulation.Cores/CPUs/MC6809/Disassembler.cs index 6df0489009f..87239336c25 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/MC6809/Disassembler.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/MC6809/Disassembler.cs @@ -789,8 +789,10 @@ public sealed partial class MC6809 public static string Disassemble(ushort addr, Func reader, out ushort size) { ushort origaddr = addr; - List bytes = new List(); - bytes.Add(reader(addr++)); + List bytes = new() + { + reader(addr++) + }; string result = table[bytes[0]]; if (bytes[0] == 0x10) @@ -1011,9 +1013,9 @@ public static string Disassemble(ushort addr, Func reader, out ush } } - StringBuilder ret = new StringBuilder(); + StringBuilder ret = new(); ret.Append(string.Format("{0:X4}: ", origaddr)); - foreach (var b in bytes) + foreach (byte b in bytes) ret.Append(string.Format("{0:X2} ", b)); while (ret.Length < 22) ret.Append(' '); diff --git a/src/BizHawk.Emulation.Cores/CPUs/MC6809/Interrupts.cs b/src/BizHawk.Emulation.Cores/CPUs/MC6809/Interrupts.cs index 094463cbd94..48912d0d470 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/MC6809/Interrupts.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/MC6809/Interrupts.cs @@ -82,9 +82,6 @@ private void NMI_() public Action FIRQCallback = () => {}; public Action NMICallback = () => {}; - private void ResetInterrupts() - { - IN_SYNC = false; - } + private void ResetInterrupts() => IN_SYNC = false; } } \ No newline at end of file diff --git a/src/BizHawk.Emulation.Cores/CPUs/MC6809/Operations.cs b/src/BizHawk.Emulation.Cores/CPUs/MC6809/Operations.cs index 6259dd99464..99413cafe62 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/MC6809/Operations.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/MC6809/Operations.cs @@ -86,10 +86,7 @@ public void NEG_8_Func(ushort src) Regs[src] = ans; } - public void TR_Func(ushort dest, ushort src) - { - Regs[dest] = Regs[src]; - } + public void TR_Func(ushort dest, ushort src) => Regs[dest] = Regs[src]; public void LD_8_Func(ushort dest, ushort src) { @@ -133,7 +130,7 @@ public void LEA_Func(ushort dest, ushort src) { Regs[dest] = Regs[src]; - if (dest == X || dest == Y) + if (dest is X or Y) { FlagZ = Regs[dest] == 0; } @@ -158,10 +155,7 @@ public void CLR_Func(ushort src) // source is considered a 16 bit signed value, used for long relative branch // no flags used - public void ADD16BR_Func(ushort dest, ushort src) - { - Regs[dest] = (ushort)(Regs[dest] + (short)Regs[src]); - } + public void ADD16BR_Func(ushort dest, ushort src) => Regs[dest] = (ushort)(Regs[dest] + (short)Regs[src]); public void ADD8BR_Func(ushort dest, ushort src) { @@ -381,15 +375,9 @@ public void DEC8_Func(ushort src) FlagN = (Regs[src] & 0xFF) > 127; } - public void INC16_Func(ushort src) - { - Regs[src] += 1; - } + public void INC16_Func(ushort src) => Regs[src] += 1; - public void DEC16_Func(ushort src) - { - Regs[src] -= 1; - } + public void DEC16_Func(ushort src) => Regs[src] -= 1; public void ADC8_Func(ushort dest, ushort src) { @@ -557,18 +545,18 @@ public void EXG_Func(ushort sel) case 7: src = 0xFF; break; } - switch ((Regs[sel] >> 4) & 0xF) + dest = ((Regs[sel] >> 4) & 0xF) switch { - case 0: dest = Dr; break; - case 1: dest = X; break; - case 2: dest = Y; break; - case 3: dest = US; break; - case 4: dest = SP; break; - case 5: dest = PC; break; - case 6: dest = 0xFF; break; - case 7: dest = 0xFF; break; - default: dest = 0xFF; break; - } + 0 => Dr, + 1 => X, + 2 => Y, + 3 => US, + 4 => SP, + 5 => PC, + 6 => 0xFF, + 7 => 0xFF, + _ => 0xFF, + }; } else { @@ -584,18 +572,18 @@ public void EXG_Func(ushort sel) case 15: src = 0xFF; break; } - switch ((Regs[sel] >> 4) & 0xF) + dest = ((Regs[sel] >> 4) & 0xF) switch { - case 8: dest = A; break; - case 9: dest = B; break; - case 10: dest = CC; break; - case 11: dest = DP; break; - case 12: dest = 0xFF; break; - case 13: dest = 0xFF; break; - case 14: dest = 0xFF; break; - case 15: dest = 0xFF; break; - default: dest = 0xFF; break; - } + 8 => A, + 9 => B, + 10 => CC, + 11 => DP, + 12 => 0xFF, + 13 => 0xFF, + 14 => 0xFF, + 15 => 0xFF, + _ => 0xFF, + }; } if ((src != 0xFF) && (dest != 0xFF)) @@ -640,18 +628,18 @@ public void TFR_Func(ushort sel) case 7: dest = 0xFF; break; } - switch ((Regs[sel] >> 4) & 0xF) + src = ((Regs[sel] >> 4) & 0xF) switch { - case 0: src = Dr; break; - case 1: src = X; break; - case 2: src = Y; break; - case 3: src = US; break; - case 4: src = SP; break; - case 5: src = PC; break; - case 6: src = 0xFF; break; - case 7: src = 0xFF; break; - default: src = 0xFF; break; - } + 0 => Dr, + 1 => X, + 2 => Y, + 3 => US, + 4 => SP, + 5 => PC, + 6 => 0xFF, + 7 => 0xFF, + _ => 0xFF, + }; } else { @@ -667,18 +655,18 @@ public void TFR_Func(ushort sel) case 15: dest = 0xFF; break; } - switch ((Regs[sel] >> 4) & 0xF) + src = ((Regs[sel] >> 4) & 0xF) switch { - case 8: src = A; break; - case 9: src = B; break; - case 10: src = CC; break; - case 11: src = DP; break; - case 12: src = 0xFF; break; - case 13: src = 0xFF; break; - case 14: src = 0xFF; break; - case 15: src = 0xFF; break; - default: src = 0xFF; break; - } + 8 => A, + 9 => B, + 10 => CC, + 11 => DP, + 12 => 0xFF, + 13 => 0xFF, + 14 => 0xFF, + 15 => 0xFF, + _ => 0xFF, + }; } if ((src != 0xFF) && (dest != 0xFF)) diff --git a/src/BizHawk.Emulation.Cores/CPUs/MOS 6502X/Disassembler.cs b/src/BizHawk.Emulation.Cores/CPUs/MOS 6502X/Disassembler.cs index d88c7491ffd..5df931e8924 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/MOS 6502X/Disassembler.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/MOS 6502X/Disassembler.cs @@ -6,10 +6,7 @@ namespace BizHawk.Emulation.Cores.Components.M6502 { public partial class MOS6502X : IDisassemblable { - public string Disassemble(ushort pc, out int bytesToAdvance) - { - return MOS6502X.Disassemble(pc, out bytesToAdvance, _link.PeekMemory); - } + public string Disassemble(ushort pc, out int bytesToAdvance) => MOS6502X.Disassemble(pc, out bytesToAdvance, _link.PeekMemory); public string Cpu { @@ -26,10 +23,7 @@ public IEnumerable AvailableCpus get { yield return "6502"; } } - public string Disassemble(MemoryDomain m, uint addr, out int length) - { - return MOS6502X.Disassemble((ushort)addr, out length, a => m.PeekByte(a)); - } + public string Disassemble(MemoryDomain m, uint addr, out int length) => MOS6502X.Disassemble((ushort)addr, out length, a => m.PeekByte(a)); } public static class MOS6502X diff --git a/src/BizHawk.Emulation.Cores/CPUs/MOS 6502X/Execute.cs b/src/BizHawk.Emulation.Cores/CPUs/MOS 6502X/Execute.cs index 56bdb7e6317..abca9351fdf 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/MOS 6502X/Execute.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/MOS 6502X/Execute.cs @@ -618,15 +618,9 @@ private void Fetch3() } } - private void PushPCH() - { - _link.WriteMemory((ushort)(S-- + 0x100), (byte)(PC >> 8)); - } + private void PushPCH() => _link.WriteMemory((ushort)(S-- + 0x100), (byte)(PC >> 8)); - private void PushPCL() - { - _link.WriteMemory((ushort)(S-- + 0x100), (byte)PC); - } + private void PushPCL() => _link.WriteMemory((ushort)(S-- + 0x100), (byte)PC); private void PushP_BRK() { @@ -737,21 +731,11 @@ private void Imp_DEX() } } - private void NZ_A() - { - P = (byte)((P & 0x7D) | TableNZ[A]); - } - - private void NZ_X() - { - P = (byte)((P & 0x7D) | TableNZ[X]); - } + private void NZ_A() => P = (byte)((P & 0x7D) | TableNZ[A]); - private void NZ_Y() - { - P = (byte)((P & 0x7D) | TableNZ[Y]); + private void NZ_X() => P = (byte)((P & 0x7D) | TableNZ[X]); - } + private void NZ_Y() => P = (byte)((P & 0x7D) | TableNZ[Y]); private void Imp_TSX() { @@ -876,46 +860,21 @@ private void Imp_CLV() } } - private void Abs_WRITE_STA() - { - _link.WriteMemory((ushort)((opcode3 << 8) + opcode2), A); - } + private void Abs_WRITE_STA() => _link.WriteMemory((ushort)((opcode3 << 8) + opcode2), A); - private void Abs_WRITE_STX() - { - _link.WriteMemory((ushort)((opcode3 << 8) + opcode2), X); - } + private void Abs_WRITE_STX() => _link.WriteMemory((ushort)((opcode3 << 8) + opcode2), X); - private void Abs_WRITE_STY() - { - _link.WriteMemory((ushort)((opcode3 << 8) + opcode2), Y); - } + private void Abs_WRITE_STY() => _link.WriteMemory((ushort)((opcode3 << 8) + opcode2), Y); - private void Abs_WRITE_SAX() - { - _link.WriteMemory((ushort)((opcode3 << 8) + opcode2), (byte)(X & A)); + private void Abs_WRITE_SAX() => _link.WriteMemory((ushort)((opcode3 << 8) + opcode2), (byte)(X & A)); - } + private void ZP_WRITE_STA() => _link.WriteMemory(opcode2, A); - private void ZP_WRITE_STA() - { - _link.WriteMemory(opcode2, A); - } + private void ZP_WRITE_STY() => _link.WriteMemory(opcode2, Y); - private void ZP_WRITE_STY() - { - _link.WriteMemory(opcode2, Y); - } + private void ZP_WRITE_STX() => _link.WriteMemory(opcode2, X); - private void ZP_WRITE_STX() - { - _link.WriteMemory(opcode2, X); - } - - private void ZP_WRITE_SAX() - { - _link.WriteMemory(opcode2, (byte)(X & A)); - } + private void ZP_WRITE_SAX() => _link.WriteMemory(opcode2, (byte)(X & A)); private void IndIdx_Stage3() { @@ -978,15 +937,9 @@ private void IndIdx_RMW_Stage5() } } - private void IndIdx_WRITE_Stage6_STA() - { - _link.WriteMemory((ushort)ea, A); - } + private void IndIdx_WRITE_Stage6_STA() => _link.WriteMemory((ushort)ea, A); - private void IndIdx_WRITE_Stage6_SHA() - { - _link.WriteMemory((ushort)ea, (byte)(A & X & 7)); - } + private void IndIdx_WRITE_Stage6_SHA() => _link.WriteMemory((ushort)ea, (byte)(A & X & 7)); private void IndIdx_READ_Stage6_LDA() { @@ -1133,10 +1086,7 @@ private void IndIdx_RMW_Stage7_RLA() NZ_A(); } - private void IndIdx_RMW_Stage8() - { - _link.WriteMemory((ushort)ea, (byte)alu_temp); - } + private void IndIdx_RMW_Stage8() => _link.WriteMemory((ushort)ea, (byte)alu_temp); private void RelBranch_Stage2_BVS() { @@ -1477,10 +1427,7 @@ private void ZpIdx_RMW_Stage4() } } - private void ZpIdx_RMW_Stage6() - { - _link.WriteMemory(opcode2, (byte)alu_temp); - } + private void ZpIdx_RMW_Stage6() => _link.WriteMemory(opcode2, (byte)alu_temp); private void ZP_READ_EOR() { @@ -2060,10 +2007,7 @@ private void IdxInd_Stage6_READ_SBC() } } - private void IdxInd_Stage6_WRITE_STA() - { - _link.WriteMemory((ushort)ea, A); - } + private void IdxInd_Stage6_WRITE_STA() => _link.WriteMemory((ushort)ea, A); private void IdxInd_Stage6_WRITE_SAX() { @@ -2138,10 +2082,7 @@ private void IdxInd_Stage7_RMW_RLA() NZ_A(); } - private void IdxInd_Stage8_RMW() - { - _link.WriteMemory((ushort)ea, (byte)alu_temp); - } + private void IdxInd_Stage8_RMW() => _link.WriteMemory((ushort)ea, (byte)alu_temp); private void PushP() { @@ -2149,10 +2090,7 @@ private void PushP() _link.WriteMemory((ushort)(S-- + 0x100), P); } - private void PushA() - { - _link.WriteMemory((ushort)(S-- + 0x100), A); - } + private void PushA() => _link.WriteMemory((ushort)(S-- + 0x100), A); private void PullA_NoInc() { @@ -2255,10 +2193,7 @@ private void ZP_RMW_Stage3() } } - private void ZP_RMW_Stage5() - { - _link.WriteMemory(opcode2, (byte)alu_temp); - } + private void ZP_RMW_Stage5() => _link.WriteMemory(opcode2, (byte)alu_temp); private void ZP_RMW_INC() { @@ -2425,10 +2360,7 @@ private void AbsIdx_Stage4() } } - private void AbsIdx_WRITE_Stage5_STA() - { - _link.WriteMemory((ushort)ea, A); - } + private void AbsIdx_WRITE_Stage5_STA() => _link.WriteMemory((ushort)ea, A); private void AbsIdx_WRITE_Stage5_SHY() { @@ -2459,10 +2391,7 @@ private void AbsIdx_RMW_Stage5() } } - private void AbsIdx_RMW_Stage7() - { - _link.WriteMemory((ushort)ea, (byte)alu_temp); - } + private void AbsIdx_RMW_Stage7() => _link.WriteMemory((ushort)ea, (byte)alu_temp); private void AbsIdx_RMW_Stage6_DEC() { @@ -2829,10 +2758,7 @@ private void Abs_RMW_Stage5_LSR() P = (byte)((P & 0x7D) | TableNZ[value8]); } - private void Abs_RMW_Stage6() - { - _link.WriteMemory((ushort)ea, (byte)alu_temp); - } + private void Abs_RMW_Stage6() => _link.WriteMemory((ushort)ea, (byte)alu_temp); private void End_ISpecial() { @@ -2858,22 +2784,16 @@ private void End() ExecuteOneRetry(); } - private void End_BranchSpecial() - { - End(); - } + private void End_BranchSpecial() => End(); - private void Jam() - { - rdy_freeze = true; - } + private void Jam() => rdy_freeze = true; [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ExecuteOneRetry() { //don't know whether this system is any faster. hard to get benchmarks someone else try it? //Uop uop = (Uop)CompiledMicrocode[MicrocodeIndex[opcode] + mi]; - Uop uop = Microcode[opcode][mi]; + var uop = Microcode[opcode][mi]; switch (uop) { default: throw new InvalidOperationException(); @@ -3140,9 +3060,6 @@ public void ExecuteOne() mi++; } - public bool AtInstructionStart() - { - return Microcode[opcode][mi] >= Uop.End; - } + public bool AtInstructionStart() => Microcode[opcode][mi] >= Uop.End; } } diff --git a/src/BizHawk.Emulation.Cores/CPUs/MOS 6502X/MOS6502X.cs b/src/BizHawk.Emulation.Cores/CPUs/MOS 6502X/MOS6502X.cs index 5f58193b058..51371ee9c7b 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/MOS 6502X/MOS6502X.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/MOS 6502X/MOS6502X.cs @@ -97,7 +97,7 @@ public TraceInfo State(bool disassemble = true) if (!disassemble) return new(disassembly: string.Empty, registerInfo: string.Empty); string rawbytes = ""; - string disasm = Disassemble(PC, out var length); + string disasm = Disassemble(PC, out int length); for (int i = 0; i < length; i++) { @@ -129,11 +129,9 @@ public TraceInfo State(bool disassemble = true) public bool AtStart => opcode == VOP_Fetch1 || Microcode[opcode][mi] >= Uop.End; - public TraceInfo TraceState() - { + public TraceInfo TraceState() => // only disassemble when we're at the beginning of an opcode - return State(AtStart); - } + State(AtStart); public const ushort NMIVector = 0xFFFA; public const ushort ResetVector = 0xFFFC; @@ -244,10 +242,7 @@ public bool FlagN public long TotalExecutedCycles; // SO pin - public void SetOverflow() - { - FlagV = true; - } + public void SetOverflow() => FlagV = true; private static readonly byte[] TableNZ = { diff --git a/src/BizHawk.Emulation.Cores/CPUs/W65816/Disassembler.cs b/src/BizHawk.Emulation.Cores/CPUs/W65816/Disassembler.cs index 0f66bc23bcc..dd2662c2a71 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/W65816/Disassembler.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/W65816/Disassembler.cs @@ -10,7 +10,7 @@ internal class W65816_DisassemblerService : IDisassemblable { public string Cpu { get; set; } - private readonly W65816 disassemblerCpu = new W65816(); + private readonly W65816 disassemblerCpu = new(); public IEnumerable AvailableCpus { @@ -468,7 +468,7 @@ public string Disassemble(uint addr, Func peek, ref byte P, out int break; } - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); bool print_addr = false; bool print_hex = false; diff --git a/src/BizHawk.Emulation.Cores/CPUs/Z80A/NewDisassembler.cs b/src/BizHawk.Emulation.Cores/CPUs/Z80A/NewDisassembler.cs index 56b9416026c..0165a1c844f 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/Z80A/NewDisassembler.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/Z80A/NewDisassembler.cs @@ -19,7 +19,7 @@ private static string Result(string format, Func read, ref ushort if (format.IndexOf("+d", StringComparison.Ordinal) != -1) format = format.Replace("+d", "d"); if (format.IndexOf("d", StringComparison.Ordinal) != -1) { - var b = unchecked ((sbyte) read(addr++)); + sbyte b = unchecked ((sbyte) read(addr++)); format = format.Replace("d", $"{(b < 0 ? '-' : '+')}{(b < 0 ? -b : b):X2}h"); } diff --git a/src/BizHawk.Emulation.Cores/CPUs/Z80A/Operations.cs b/src/BizHawk.Emulation.Cores/CPUs/Z80A/Operations.cs index f4b0752520e..70b232129e4 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/Z80A/Operations.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/Z80A/Operations.cs @@ -102,10 +102,7 @@ public void IN_A_N_INC_Func(ushort dest, ushort src_l, ushort src_h) INC16_Func(src_l, src_h); } - public void TR_Func(ushort dest, ushort src) - { - Regs[dest] = Regs[src]; - } + public void TR_Func(ushort dest, ushort src) => Regs[dest] = Regs[src]; public void TR16_Func(ushort dest_l, ushort dest_h, ushort src_l, ushort src_h) { @@ -202,20 +199,11 @@ public void I_BIT_Func(ushort bit, ushort src) Flag3 = Regs[W].Bit(3); } - public void SET_Func(ushort bit, ushort src) - { - Regs[src] |= (ushort)(1 << bit); - } + public void SET_Func(ushort bit, ushort src) => Regs[src] |= (ushort)(1 << bit); - public void RES_Func(ushort bit, ushort src) - { - Regs[src] &= (ushort)(0xFF - (1 << bit)); - } + public void RES_Func(ushort bit, ushort src) => Regs[src] &= (ushort)(0xFF - (1 << bit)); - public void ASGN_Func(ushort src, ushort val) - { - Regs[src] = val; - } + public void ASGN_Func(ushort src, ushort val) => Regs[src] = val; public void SLL_Func(ushort src) { @@ -650,13 +638,8 @@ public void ADDS_Func(ushort dest_l, ushort dest_h, ushort src_l, ushort src_h) public void EXCH_16_Func(ushort dest_l, ushort dest_h, ushort src_l, ushort src_h) { - ushort temp = Regs[dest_l]; - Regs[dest_l] = Regs[src_l]; - Regs[src_l] = temp; - - temp = Regs[dest_h]; - Regs[dest_h] = Regs[src_h]; - Regs[src_h] = temp; + (Regs[src_l], Regs[dest_l]) = (Regs[dest_l], Regs[src_l]); + (Regs[src_h], Regs[dest_h]) = (Regs[dest_h], Regs[src_h]); } public void SBC_16_Func(ushort dest_l, ushort dest_h, ushort src_l, ushort src_h) @@ -806,9 +789,6 @@ public void SET_FL_IR_Func(ushort dest) } } - public void FTCH_DB_Func() - { - Regs[DB] = FetchDB(); - } + public void FTCH_DB_Func() => Regs[DB] = FetchDB(); } } diff --git a/src/BizHawk.Emulation.Cores/CPUs/Z80A/Z80A.cs b/src/BizHawk.Emulation.Cores/CPUs/Z80A/Z80A.cs index 75181abe6d1..ab199f55c13 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/Z80A/Z80A.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/Z80A/Z80A.cs @@ -528,7 +528,7 @@ public void ExecuteOne() I_skip = true; // for prefetched case, the PC stays on the BUS one cycle longer - if ((src_t == IXCBpre) || (src_t == IYCBpre)) { BUSRQ[0] = PCh; } + if (src_t is IXCBpre or IYCBpre) { BUSRQ[0] = PCh; } break; case ASGN: @@ -868,7 +868,7 @@ public TraceInfo State(bool disassemble = true) } return new( - disassembly: $"{RegPC:X4}: {byte_code.PadRight(12)} {disasm.PadRight(26)}", + disassembly: $"{RegPC:X4}: {byte_code,-12} {disasm,-26}", registerInfo: string.Join(" ", $"AF:{(Regs[A] << 8) + Regs[F]:X4}", $"BC:{(Regs[B] << 8) + Regs[C]:X4}", diff --git a/src/BizHawk.Emulation.Cores/CPUs/x86/Disassembler.cs b/src/BizHawk.Emulation.Cores/CPUs/x86/Disassembler.cs index 8e8b4507e21..098d419679c 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/x86/Disassembler.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/x86/Disassembler.cs @@ -15,10 +15,7 @@ public class DisassemblyInfo public partial class x86 where TCpu : struct, x86CpuType { - private ushort ReadWord(int addr) - { - return (ushort)(ReadMemory(addr++) + (ReadMemory(addr) << 8)); - } + private ushort ReadWord(int addr) => (ushort)(ReadMemory(addr++) + (ReadMemory(addr) << 8)); private string DisassembleRM8(ref int addr) { @@ -26,20 +23,18 @@ private string DisassembleRM8(ref int addr) int mod = (ModRM >> 6) & 3; int r = (ModRM >> 3) & 7; int m = ModRM & 7; - - string reg; - switch (r) + string reg = r switch { - case 0: reg = "AL"; break; - case 1: reg = "CL"; break; - case 2: reg = "DL"; break; - case 3: reg = "BL"; break; - case 4: reg = "AH"; break; - case 5: reg = "CH"; break; - case 6: reg = "DH"; break; - case 7: reg = "BH"; break; - default: reg = "UNKNOWN"; break; - } + 0 => "AL", + 1 => "CL", + 2 => "DL", + 3 => "BL", + 4 => "AH", + 5 => "CH", + 6 => "DH", + 7 => "BH", + _ => "UNKNOWN", + }; return reg + ", " + DisassembleMod(ref addr, mod, m, 1); } @@ -106,7 +101,7 @@ private string DisassembleMod(ref int addr, int mod, int m, int size) public DisassemblyInfo Disassemble(int addr) { - var info = new DisassemblyInfo { Addr = addr }; + DisassemblyInfo info = new() { Addr = addr }; byte op1 = ReadMemory(addr++); switch (op1) { @@ -185,7 +180,7 @@ public DisassemblyInfo Disassemble(int addr) } info.Length = addr - info.Addr; - var sb = new StringBuilder(); + StringBuilder sb = new(); for (int p = info.Addr; p < info.Addr + info.Length; p++) sb.AppendFormat("{0:X2}", ReadMemory(p)); info.RawBytes = sb.ToString(); diff --git a/src/BizHawk.Emulation.Cores/CPUs/x86/x86.cs b/src/BizHawk.Emulation.Cores/CPUs/x86/x86.cs index a5dcfa685f4..59f0e72b6ce 100644 --- a/src/BizHawk.Emulation.Cores/CPUs/x86/x86.cs +++ b/src/BizHawk.Emulation.Cores/CPUs/x86/x86.cs @@ -140,6 +140,6 @@ public struct Register16 [FieldOffset(1)] public byte High; - public override string ToString() => $"{Word:X4}"; + public override readonly string ToString() => $"{Word:X4}"; } } \ No newline at end of file diff --git a/src/BizHawk.Emulation.Cores/Calculators/Emu83/Emu83.IDebuggable.cs b/src/BizHawk.Emulation.Cores/Calculators/Emu83/Emu83.IDebuggable.cs index a62c5fc1f86..a023f6caacc 100644 --- a/src/BizHawk.Emulation.Cores/Calculators/Emu83/Emu83.IDebuggable.cs +++ b/src/BizHawk.Emulation.Cores/Calculators/Emu83/Emu83.IDebuggable.cs @@ -50,7 +50,7 @@ private void InitMemoryCallbacks() { LibEmu83.MemoryCallback CreateCallback(MemoryCallbackFlags flags, Func getHasCBOfType) { - var rawFlags = (uint)flags; + uint rawFlags = (uint)flags; return (address, cycleCount) => { _callbackCycleCount = cycleCount; diff --git a/src/BizHawk.Emulation.Cores/Calculators/Emu83/Emu83.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Calculators/Emu83/Emu83.IMemoryDomains.cs index 0d1c9da77f0..86901a2725b 100644 --- a/src/BizHawk.Emulation.Cores/Calculators/Emu83/Emu83.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Calculators/Emu83/Emu83.IMemoryDomains.cs @@ -12,7 +12,7 @@ public partial class Emu83 private void CreateMemoryDomain(LibEmu83.MemoryArea_t which, string name) { - IntPtr data = IntPtr.Zero; + var data = IntPtr.Zero; int length = 0; if (!LibEmu83.TI83_GetMemoryArea(Context, which, ref data, ref length)) diff --git a/src/BizHawk.Emulation.Cores/Calculators/Emu83/Emu83.cs b/src/BizHawk.Emulation.Cores/Calculators/Emu83/Emu83.cs index 5000f61e320..0bb77ad0cc4 100644 --- a/src/BizHawk.Emulation.Cores/Calculators/Emu83/Emu83.cs +++ b/src/BizHawk.Emulation.Cores/Calculators/Emu83/Emu83.cs @@ -16,7 +16,7 @@ public partial class Emu83 : TI83Common static Emu83() { - var resolver = new DynamicLibraryImportResolver( + DynamicLibraryImportResolver resolver = new( OSTailoredCode.IsUnixHost ? "libemu83.so" : "libemu83.dll", hasLimitedLifetime: false); LibEmu83 = BizInvoker.GetInvoker(resolver, CallingConventionAdapters.Native); } @@ -34,14 +34,14 @@ public Emu83(CoreLoadParameters lp) { _serviceProvider = new BasicServiceProvider(this); PutSettings(lp.Settings ?? new TI83CommonSettings()); - var rom = lp.Comm.CoreFileProvider.GetFirmwareOrThrow(new("TI83", "Rom")); + byte[] rom = lp.Comm.CoreFileProvider.GetFirmwareOrThrow(new("TI83", "Rom")); Context = LibEmu83.TI83_CreateContext(rom, rom.Length); if (Context == IntPtr.Zero) { throw new Exception("Core returned null! Bad ROM?"); } - var linkFiles = lp.Roms.Select(r => r.RomData).ToList(); - foreach (var linkFile in linkFiles) + System.Collections.Generic.List linkFiles = lp.Roms.Select(r => r.RomData).ToList(); + foreach (byte[] linkFile in linkFiles) { if (!LibEmu83.TI83_LoadLinkFile(Context, linkFile, linkFile.Length)) { diff --git a/src/BizHawk.Emulation.Cores/Calculators/Emu83/TI83Disassembler.cs b/src/BizHawk.Emulation.Cores/Calculators/Emu83/TI83Disassembler.cs index 80ea48a2f87..f144a896cbd 100644 --- a/src/BizHawk.Emulation.Cores/Calculators/Emu83/TI83Disassembler.cs +++ b/src/BizHawk.Emulation.Cores/Calculators/Emu83/TI83Disassembler.cs @@ -13,7 +13,7 @@ public class TI83Disassembler : VerifiedDisassembler public override string Disassemble(MemoryDomain m, uint addr, out int length) { - var ret = Z80A.Disassemble((ushort) addr, a => m.PeekByte(a), out var tmp); + string ret = Z80A.Disassemble((ushort) addr, a => m.PeekByte(a), out int tmp); length = tmp; return ret; } diff --git a/src/BizHawk.Emulation.Cores/Calculators/TI83/TI83.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Calculators/TI83/TI83.IMemoryDomains.cs index d5faf559493..c6b2e2ceb40 100644 --- a/src/BizHawk.Emulation.Cores/Calculators/TI83/TI83.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Calculators/TI83/TI83.IMemoryDomains.cs @@ -8,15 +8,15 @@ namespace BizHawk.Emulation.Cores.Calculators.TI83 { public partial class TI83 { - private readonly Dictionary _byteArrayDomains = new Dictionary(); + private readonly Dictionary _byteArrayDomains = new(); private IMemoryDomains _memoryDomains; private bool _memoryDomainsInit; private void SetupMemoryDomains() { - var domains = new List(); + List domains = new(); - var systemBusDomain = new MemoryDomainDelegate("System Bus", 0x10000, MemoryDomain.Endian.Little, + MemoryDomainDelegate systemBusDomain = new("System Bus", 0x10000, MemoryDomain.Endian.Little, (addr) => { if (addr is < 0 or > 0xFFFF) throw new ArgumentOutOfRangeException(paramName: nameof(addr), addr, message: "address out of range"); @@ -38,10 +38,7 @@ private void SetupMemoryDomains() _memoryDomainsInit = true; } - private void SyncAllByteArrayDomains() - { - SyncByteArrayDomain("Main RAM", _ram); - } + private void SyncAllByteArrayDomains() => SyncByteArrayDomain("Main RAM", _ram); private void SyncByteArrayDomain(string name, byte[] data) { @@ -52,7 +49,7 @@ private void SyncByteArrayDomain(string name, byte[] data) } else { - var m = new MemoryDomainByteArray(name, MemoryDomain.Endian.Little, data, true, 1); + MemoryDomainByteArray m = new(name, MemoryDomain.Endian.Little, data, true, 1); _byteArrayDomains.Add(name, m); } } diff --git a/src/BizHawk.Emulation.Cores/Calculators/TI83/TI83.IStatable.cs b/src/BizHawk.Emulation.Cores/Calculators/TI83/TI83.IStatable.cs index 99f5c354e8f..c05f2b4edb0 100644 --- a/src/BizHawk.Emulation.Cores/Calculators/TI83/TI83.IStatable.cs +++ b/src/BizHawk.Emulation.Cores/Calculators/TI83/TI83.IStatable.cs @@ -10,7 +10,7 @@ private void SyncState(Serializer ser) { if (ser.IsWriter) { - var ms = new MemoryStream(); + MemoryStream ms = new(); ms.Close(); ms.ToArray(); } diff --git a/src/BizHawk.Emulation.Cores/Calculators/TI83/TI83.cs b/src/BizHawk.Emulation.Cores/Calculators/TI83/TI83.cs index 8b3a5fac227..27681ad33e7 100644 --- a/src/BizHawk.Emulation.Cores/Calculators/TI83/TI83.cs +++ b/src/BizHawk.Emulation.Cores/Calculators/TI83/TI83.cs @@ -13,7 +13,7 @@ public partial class TI83 : TI83Common, IEmulator, IVideoProvider, IDebuggable, [CoreConstructor(VSystemID.Raw.TI83)] public TI83(CoreLoadParameters lp) { - var ser = new BasicServiceProvider(this); + BasicServiceProvider ser = new(this); ServiceProvider = ser; PutSettings(lp.Settings ?? new TI83CommonSettings()); @@ -42,7 +42,7 @@ public TI83(CoreLoadParameters lp) private readonly TraceBuffer _tracer; - private readonly Z80A _cpu = new Z80A(); + private readonly Z80A _cpu = new(); private readonly byte[] _rom; // configuration @@ -441,7 +441,7 @@ private void WriteDispCtrl(byte value) { _displayMode = value; } - else if (value >= 4 && value <= 7) + else if (value is >= 4 and <= 7) { _displayMove = value - 4; } @@ -471,17 +471,13 @@ private void WriteDispCtrl(byte value) } } - private void IRQCallback() - { + private void IRQCallback() => //Console.WriteLine("IRQ with vec {0} and cpu.InterruptMode {1}", _cpu.Regs[_cpu.I], _cpu.InterruptMode); _cpu.FlagI = false; - } - private void NMICallback() - { + private void NMICallback() => //Console.WriteLine("NMI"); _cpu.NonMaskableInterrupt = false; - } private void HardReset() { diff --git a/src/BizHawk.Emulation.Cores/Calculators/TI83/TI83LinkPort.cs b/src/BizHawk.Emulation.Cores/Calculators/TI83/TI83LinkPort.cs index e2cabbfeb0e..9224cbad35a 100644 --- a/src/BizHawk.Emulation.Cores/Calculators/TI83/TI83LinkPort.cs +++ b/src/BizHawk.Emulation.Cores/Calculators/TI83/TI83LinkPort.cs @@ -11,7 +11,7 @@ public class TI83LinkPort // Note: Each hardware read/write to the link port calls tthe update method. private readonly TI83 Parent; - private readonly Queue CurrentData = new Queue(); + private readonly Queue CurrentData = new(); private Stream _currentFile; private byte[] _variableData; diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.Controllers.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.Controllers.cs index ef3ce3749e3..c2088ee6b58 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.Controllers.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.Controllers.cs @@ -19,32 +19,32 @@ public ControllerDefinition AmstradCPCControllerDefinition ControllerDefinition definition = new("AmstradCPC Controller"); // joysticks - var joys1 = new List + List joys1 = new() { // P1 Joystick "P1 Up", "P1 Down", "P1 Left", "P1 Right", "P1 Fire1", "P1 Fire2", "P1 Fire3" }; - foreach (var s in joys1) + foreach (string s in joys1) { definition.BoolButtons.Add(s); definition.CategoryLabels[s] = "J1"; } - var joys2 = new List + List joys2 = new() { // P2 Joystick "P2 Up", "P2 Down", "P2 Left", "P2 Right", "P2 Fire", }; - foreach (var s in joys2) + foreach (string s in joys2) { definition.BoolButtons.Add(s); definition.CategoryLabels[s] = "J2"; } // keyboard - var keys = new List + List keys = new() { // http://www.cpcwiki.eu/index.php/Programming:Keyboard_scanning // http://www.cpcwiki.eu/index.php/File:Grimware_cpc464_version3_case_top.jpg @@ -65,47 +65,47 @@ public ControllerDefinition AmstradCPCControllerDefinition "Key NUM0", "Key NUM1", "Key NUM2", "Key NUM3", "Key NUM4", "Key NUM5", "Key NUM6", "Key NUM7", "Key NUM8", "Key NUM9", "Key NUMPERIOD", "KEY ENTER" }; - foreach (var s in keys) + foreach (string s in keys) { definition.BoolButtons.Add(s); definition.CategoryLabels[s] = "Keyboard"; } // Power functions - var power = new List + List power = new() { // Power functions "Reset", "Power" }; - foreach (var s in power) + foreach (string s in power) { definition.BoolButtons.Add(s); definition.CategoryLabels[s] = "Power"; } // Datacorder (tape device) - var tape = new List + List tape = new() { // Tape functions "Play Tape", "Stop Tape", "RTZ Tape", "Record Tape", "Insert Next Tape", "Insert Previous Tape", "Next Tape Block", "Prev Tape Block", "Get Tape Status" }; - foreach (var s in tape) + foreach (string s in tape) { definition.BoolButtons.Add(s); definition.CategoryLabels[s] = "Datacorder"; } // Datacorder (tape device) - var disk = new List + List disk = new() { // Tape functions "Insert Next Disk", "Insert Previous Disk", /*"Eject Current Disk",*/ "Get Disk Status" }; - foreach (var s in disk) + foreach (string s in disk) { definition.BoolButtons.Add(s); definition.CategoryLabels[s] = "Amstrad Disk Drive"; diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.IEmulator.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.IEmulator.cs index d4b93e58b5d..45f96c62415 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.IEmulator.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.IEmulator.cs @@ -59,9 +59,6 @@ public void ResetCounters() _isLag = false; } - public void Dispose() - { - _machine = null; - } + public void Dispose() => _machine = null; } } diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.IMemoryDomains.cs index 9d21bada1be..176ca45165d 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.IMemoryDomains.cs @@ -12,12 +12,12 @@ namespace BizHawk.Emulation.Cores.Computers.AmstradCPC public partial class AmstradCPC { internal IMemoryDomains memoryDomains; - private readonly Dictionary _byteArrayDomains = new Dictionary(); + private readonly Dictionary _byteArrayDomains = new(); private bool _memoryDomainsInit = false; private void SetupMemoryDomains() { - var domains = new List + List domains = new() { new MemoryDomainDelegate("System Bus", 0x10000, MemoryDomain.Endian.Little, (addr) => @@ -65,7 +65,7 @@ private void SyncByteArrayDomain(string name, byte[] data) } else { - var m = new MemoryDomainByteArray(name, MemoryDomain.Endian.Little, data, true, 1); + MemoryDomainByteArray m = new(name, MemoryDomain.Endian.Little, data, true, 1); _byteArrayDomains.Add(name, m); } #pragma warning restore MEN014 diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.ISettable.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.ISettable.cs index 0d50bdd4b0c..0c577ad8b34 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.ISettable.cs @@ -12,18 +12,12 @@ namespace BizHawk.Emulation.Cores.Computers.AmstradCPC /// public partial class AmstradCPC : ISettable { - internal AmstradCPCSettings Settings = new AmstradCPCSettings(); - internal AmstradCPCSyncSettings SyncSettings = new AmstradCPCSyncSettings(); + internal AmstradCPCSettings Settings = new(); + internal AmstradCPCSyncSettings SyncSettings = new(); - public AmstradCPCSettings GetSettings() - { - return Settings.Clone(); - } + public AmstradCPCSettings GetSettings() => Settings.Clone(); - public AmstradCPCSyncSettings GetSyncSettings() - { - return SyncSettings.Clone(); - } + public AmstradCPCSyncSettings GetSyncSettings() => SyncSettings.Clone(); public PutSettingsDirtyBits PutSettings(AmstradCPCSettings o) { @@ -74,10 +68,7 @@ public class AmstradCPCSettings [DefaultValue(50)] public int TapeVolume { get; set; } - public AmstradCPCSettings Clone() - { - return (AmstradCPCSettings)MemberwiseClone(); - } + public AmstradCPCSettings Clone() => (AmstradCPCSettings)MemberwiseClone(); public AmstradCPCSettings() { @@ -107,20 +98,14 @@ public class AmstradCPCSyncSettings [DefaultValue(BorderType.Uniform)] public BorderType BorderType { get; set; } - public AmstradCPCSyncSettings Clone() - { - return (AmstradCPCSyncSettings)MemberwiseClone(); - } + public AmstradCPCSyncSettings Clone() => (AmstradCPCSyncSettings)MemberwiseClone(); public AmstradCPCSyncSettings() { SettingsUtil.SetDefaultValues(this); } - public static bool NeedsReboot(AmstradCPCSyncSettings x, AmstradCPCSyncSettings y) - { - return !DeepEquality.DeepEquals(x, y); - } + public static bool NeedsReboot(AmstradCPCSyncSettings x, AmstradCPCSyncSettings y) => !DeepEquality.DeepEquals(x, y); } /// @@ -158,11 +143,11 @@ public class CPCMachineMetaData public string Media { get; set; } public string OtherMisc { get; set; } - private readonly Dictionary Data = new Dictionary(); + private readonly Dictionary Data = new(); public static CPCMachineMetaData GetMetaObject(MachineType type) { - var m = new CPCMachineMetaData { MachineType = type }; + CPCMachineMetaData m = new() { MachineType = type }; switch (type) { @@ -205,7 +190,7 @@ public static CPCMachineMetaData GetMetaObject(MachineType type) public static string GetMetaString(MachineType type) { var m = GetMetaObject(type); - var sb = new StringBuilder(); + StringBuilder sb = new(); // get longest title int titleLen = 0; @@ -215,13 +200,13 @@ public static string GetMetaString(MachineType type) titleLen = d.Key.Length; } - var maxDataLineLen = 40; + int maxDataLineLen = 40; // generate layout foreach (var d in m.Data) { - var tLen = d.Key.Length; - var makeup = (titleLen - tLen) / 4; + int tLen = d.Key.Length; + int makeup = (titleLen - tLen) / 4; sb.Append(d.Key + ":\t"); for (int i = 0; i < makeup; i++) { @@ -235,13 +220,13 @@ public static string GetMetaString(MachineType type) } // output the data splitting and tabbing as neccessary - var arr = d.Value.Split(' '); + string[] arr = d.Value.Split(' '); - List builder = new List(); + List builder = new(); string working = ""; - foreach (var s in arr) + foreach (string s in arr) { - var len = s.Length; + int len = s.Length; if (working.Length + 1 + len > maxDataLineLen) { // new line needed @@ -276,7 +261,7 @@ public static string GetMetaStringOld(MachineType type) { var m = GetMetaObject(type); - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); sb.Append(m.Name); sb.AppendLine(); diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.IStatable.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.IStatable.cs index a676469a48e..6349fa4513f 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.IStatable.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.IStatable.cs @@ -14,7 +14,7 @@ private void SyncState(Serializer ser) byte[] core = null; if (ser.IsWriter) { - var ms = new MemoryStream(); + MemoryStream ms = new(); ms.Close(); core = ms.ToArray(); } diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.Messaging.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.Messaging.cs index 3e3b0294d4b..b653597e71a 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.Messaging.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.Messaging.cs @@ -17,7 +17,7 @@ public void SendMessage(string message, MessageCategory category) if (!CheckMessageSettings(category)) return; - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); switch (category) { @@ -48,7 +48,7 @@ public void SendMessage(string message, MessageCategory category) /// public void OSD_FireInputMessage(string input) { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); sb.Append(input); SendMessage(sb.ToString().TrimEnd('\n'), MessageCategory.Input); } @@ -58,7 +58,7 @@ public void OSD_FireInputMessage(string input) /// public void OSD_DiskInit() { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); if (_machine.diskImages != null && _machine.UPDDiskDevice != null) { sb.Append("Disk Media Imported (count: " + _machine.diskImages.Count + ")"); @@ -71,7 +71,7 @@ public void OSD_DiskInit() /// public void OSD_DiskInserted() { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); if (_machine.UPDDiskDevice == null) { @@ -89,7 +89,7 @@ public void OSD_DiskInserted() /// public void OSD_ShowDiskStatus() { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); if (_machine.UPDDiskDevice == null) { @@ -148,7 +148,7 @@ public void OSD_TapeInit() if (_tapeInfo.Count == 0) return; - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); sb.Append("Tape Media Imported (count: " + _tapeInfo.Count + ")"); SendMessage(sb.ToString().TrimEnd('\n'), MessageCategory.Emulator); } @@ -161,7 +161,7 @@ public void OSD_TapeMotorActive() if (_tapeInfo.Count == 0) return; - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); sb.Append("MOTOR ON (" + _machine.TapeMediaIndex + ": " + _tapeInfo[_machine.TapeMediaIndex].Name + ")"); SendMessage(sb.ToString().TrimEnd('\n'), MessageCategory.Tape); @@ -175,7 +175,7 @@ public void OSD_TapeMotorInactive() if (_tapeInfo.Count == 0) return; - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); sb.Append("MOTOR OFF (" + _machine.TapeMediaIndex + ": " + _tapeInfo[_machine.TapeMediaIndex].Name + ")"); SendMessage(sb.ToString().TrimEnd('\n'), MessageCategory.Tape); @@ -189,7 +189,7 @@ public void OSD_TapePlaying() if (_tapeInfo.Count == 0) return; - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); sb.Append("PLAYING MANUAL (" + _machine.TapeMediaIndex + ": " + _tapeInfo[_machine.TapeMediaIndex].Name + ")"); SendMessage(sb.ToString().TrimEnd('\n'), MessageCategory.Tape); @@ -203,7 +203,7 @@ public void OSD_TapeStopped() if (_tapeInfo.Count == 0) return; - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); sb.Append("STOPPED MANUAL (" + _machine.TapeMediaIndex + ": " + _tapeInfo[_machine.TapeMediaIndex].Name + ")"); SendMessage(sb.ToString().TrimEnd('\n'), MessageCategory.Tape); @@ -217,7 +217,7 @@ public void OSD_TapeRTZ() if (_tapeInfo.Count == 0) return; - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); sb.Append("REWOUND (" + _machine.TapeMediaIndex + ": " + _tapeInfo[_machine.TapeMediaIndex].Name + ")"); SendMessage(sb.ToString().TrimEnd('\n'), MessageCategory.Tape); @@ -231,7 +231,7 @@ public void OSD_TapeInserted() if (_tapeInfo.Count == 0) return; - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); sb.Append("TAPE INSERTED (" + _machine.TapeMediaIndex + ": " + _tapeInfo[_machine.TapeMediaIndex].Name + ")"); SendMessage(sb.ToString().TrimEnd('\n'), MessageCategory.Tape); @@ -243,7 +243,7 @@ public void OSD_TapeInserted() /// public void OSD_TapeStoppedAuto() { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); if (_tapeInfo.Count == 0) { @@ -263,7 +263,7 @@ public void OSD_TapeStoppedAuto() /// public void OSD_TapePlayingAuto() { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); if (_tapeInfo.Count == 0) { @@ -283,7 +283,7 @@ public void OSD_TapePlayingAuto() /// public void OSD_TapePlayingBlockInfo(string blockinfo) { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); if (_tapeInfo.Count == 0) { @@ -303,7 +303,7 @@ public void OSD_TapePlayingBlockInfo(string blockinfo) /// public void OSD_TapePlayingSkipBlockInfo(string blockinfo) { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); if (_tapeInfo.Count == 0) { @@ -323,7 +323,7 @@ public void OSD_TapePlayingSkipBlockInfo(string blockinfo) /// public void OSD_TapeEndDetected(string blockinfo) { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); if (_tapeInfo.Count == 0) { @@ -343,7 +343,7 @@ public void OSD_TapeEndDetected(string blockinfo) /// public void OSD_TapeNextBlock(string blockinfo) { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); if (_tapeInfo.Count == 0) { @@ -363,7 +363,7 @@ public void OSD_TapeNextBlock(string blockinfo) /// public void OSD_TapePrevBlock(string blockinfo) { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); if (_tapeInfo.Count == 0) { @@ -383,7 +383,7 @@ public void OSD_TapePrevBlock(string blockinfo) /// public void OSD_ShowTapeStatus() { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); if (_tapeInfo.Count == 0) { @@ -427,7 +427,7 @@ public void OSD_ShowTapeStatus() // get position within the tape itself sb.Append("Tape Pos: "); - var ind = _machine.TapeDevice.CurrentDataBlockIndex; + int ind = _machine.TapeDevice.CurrentDataBlockIndex; int cnt = 0; for (int i = 0; i < ind; i++) { @@ -453,26 +453,17 @@ public void OSD_ShowTapeStatus() /// public bool CheckMessageSettings(MessageCategory category) { - switch (Settings.OSDMessageVerbosity) + return Settings.OSDMessageVerbosity switch { - case OSDVerbosity.Full: - return true; - case OSDVerbosity.None: - return false; - case OSDVerbosity.Medium: - switch (category) - { - case MessageCategory.Disk: - case MessageCategory.Emulator: - case MessageCategory.Tape: - case MessageCategory.Misc: - return true; - default: - return false; - } - default: - return true; - } + OSDVerbosity.Full => true, + OSDVerbosity.None => false, + OSDVerbosity.Medium => category switch + { + MessageCategory.Disk or MessageCategory.Emulator or MessageCategory.Tape or MessageCategory.Misc => true, + _ => false, + }, + _ => true, + }; } /// diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.Util.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.Util.cs index 61d92baf094..f670ff1f181 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.Util.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.Util.cs @@ -24,10 +24,7 @@ public static int GetIntFromBitArray(BitArray bitArray) /// /// POKEs a memory bus address /// - public void PokeMemory(ushort addr, byte value) - { - _machine.WriteBus(addr, value); - } + public void PokeMemory(ushort addr, byte value) => _machine.WriteBus(addr, value); public string GetMachineType() { @@ -45,9 +42,6 @@ public string GetMachineType() return m; } - public static string GetMemberName(Expression> memberAccess) - { - return ((MemberExpression)memberAccess.Body).Member.Name; - } + public static string GetMemberName(Expression> memberAccess) => ((MemberExpression)memberAccess.Body).Member.Name; } } diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.cs index 760bb98a7c5..5a147bdeb17 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/AmstradCPC.cs @@ -18,7 +18,7 @@ public partial class AmstradCPC : IRegionable, IDriveLight [CoreConstructor(VSystemID.Raw.AmstradCPC)] public AmstradCPC(CoreLoadParameters lp) { - var ser = new BasicServiceProvider(this); + BasicServiceProvider ser = new(this); ServiceProvider = ser; CoreComm = lp.Comm; _gameInfo = lp.Roms.Select(r => r.Game).ToList(); @@ -105,7 +105,7 @@ public AmstradCPC(CoreLoadParameters public readonly IList _tapeInfo = new List(); public readonly IList _diskInfo = new List(); - private SoundProviderMixer SoundMixer; + private readonly SoundProviderMixer SoundMixer; private readonly List _files; @@ -143,12 +143,7 @@ private byte[] GetFirmware(int length, params string[] names) return embeddedRom; // Embedded ROM not found, maybe this is a peripheral ROM? - var result = names.Select(n => CoreComm.CoreFileProvider.GetFirmware(new("AmstradCPC", n))).FirstOrDefault(b => b != null && b.Length == length); - if (result == null) - { - throw new MissingFirmwareException($"At least one of these firmwares is required: {string.Join(", ", names)}"); - } - + byte[] result = names.Select(n => CoreComm.CoreFileProvider.GetFirmware(new("AmstradCPC", n))).FirstOrDefault(b => b != null && b.Length == length) ?? throw new MissingFirmwareException($"At least one of these firmwares is required: {string.Join(", ", names)}"); return result; } @@ -163,18 +158,22 @@ private void Init(MachineType machineType, List files, bool autoTape, Bo { case MachineType.CPC464: _machine = new CPC464(this, _cpu, files, autoTape, bType); - var roms64 = new List(); - roms64.Add(RomData.InitROM(MachineType.CPC464, GetFirmware(0x4000, "OS464ROM"), RomData.ROMChipType.Lower)); - roms64.Add(RomData.InitROM(MachineType.CPC464, GetFirmware(0x4000, "BASIC1-0ROM"), RomData.ROMChipType.Upper, 0)); + List roms64 = new() + { + RomData.InitROM(MachineType.CPC464, GetFirmware(0x4000, "OS464ROM"), RomData.ROMChipType.Lower), + RomData.InitROM(MachineType.CPC464, GetFirmware(0x4000, "BASIC1-0ROM"), RomData.ROMChipType.Upper, 0) + }; _machine.InitROM(roms64.ToArray()); break; case MachineType.CPC6128: _machine = new CPC6128(this, _cpu, files, autoTape, bType); - var roms128 = new List(); - roms128.Add(RomData.InitROM(MachineType.CPC6128, GetFirmware(0x4000, "OS6128ROM"), RomData.ROMChipType.Lower)); - roms128.Add(RomData.InitROM(MachineType.CPC6128, GetFirmware(0x4000, "BASIC1-1ROM"), RomData.ROMChipType.Upper, 0)); - roms128.Add(RomData.InitROM(MachineType.CPC6128, GetFirmware(0x4000, "AMSDOS0-5ROM"), RomData.ROMChipType.Upper, 7)); + List roms128 = new() + { + RomData.InitROM(MachineType.CPC6128, GetFirmware(0x4000, "OS6128ROM"), RomData.ROMChipType.Lower), + RomData.InitROM(MachineType.CPC6128, GetFirmware(0x4000, "BASIC1-1ROM"), RomData.ROMChipType.Upper, 0), + RomData.InitROM(MachineType.CPC6128, GetFirmware(0x4000, "AMSDOS0-5ROM"), RomData.ROMChipType.Upper, 7) + }; _machine.InitROM(roms128.ToArray()); break; } diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Datacorder/DatacorderDevice.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Datacorder/DatacorderDevice.cs index 5670a8547dd..5a2150ec4a7 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Datacorder/DatacorderDevice.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Datacorder/DatacorderDevice.cs @@ -27,10 +27,7 @@ public DatacorderDevice(bool autoTape) /// /// Initializes the datacorder device /// - public void Init(CPCBase machine) - { - _machine = machine; - } + public void Init(CPCBase machine) => _machine = machine; /// /// Signs whether the tape motor is running @@ -81,7 +78,7 @@ public int CurrentDataBlockIndex { get { - if (_dataBlocks.Any()) + if (DataBlocks.Any()) { return _currentDataBlockIndex; } @@ -91,7 +88,7 @@ public int CurrentDataBlockIndex set { if (value == _currentDataBlockIndex) { return; } - if (value < _dataBlocks.Count && value >= 0) + if (value < DataBlocks.Count && value >= 0) { _currentDataBlockIndex = value; _position = 0; @@ -103,7 +100,7 @@ public int CurrentDataBlockIndex /// The current position within the current data block /// private int _position = 0; - public int Position => _position >= _dataBlocks[_currentDataBlockIndex].DataPeriods.Count ? 0 : _position; + public int Position => _position >= DataBlocks[_currentDataBlockIndex].DataPeriods.Count ? 0 : _position; /// /// Signs whether the tape is currently playing or not @@ -111,15 +108,7 @@ public int CurrentDataBlockIndex private bool _tapeIsPlaying = false; public bool TapeIsPlaying => _tapeIsPlaying; - /// - /// A list of the currently loaded data blocks - /// - private List _dataBlocks = new List(); - public List DataBlocks - { - get => _dataBlocks; - set => _dataBlocks = value; - } + public List DataBlocks { get; set; } = new(); /// /// Stores the last CPU t-state value @@ -140,7 +129,7 @@ public List DataBlocks /// Signs whether the device should autodetect when the Z80 has entered into /// 'load' mode and auto-play the tape if neccesary /// - private bool _autoPlay; + private readonly bool _autoPlay; /// /// Should be fired at the end of every frame @@ -177,25 +166,25 @@ public void Play() _position = 0; if ( - _dataBlocks.Count > 0 && // data blocks are present && + DataBlocks.Count > 0 && // data blocks are present && _currentDataBlockIndex >= 0 // the current data block index is 1 or greater ) { - while (_position >= _dataBlocks[_currentDataBlockIndex].DataPeriods.Count) + while (_position >= DataBlocks[_currentDataBlockIndex].DataPeriods.Count) { // we are at the end of a data block - move to the next _position = 0; _currentDataBlockIndex++; // are we at the end of the tape? - if (_currentDataBlockIndex >= _dataBlocks.Count) + if (_currentDataBlockIndex >= DataBlocks.Count) { break; } } // check for end of tape - if (_currentDataBlockIndex >= _dataBlocks.Count) + if (_currentDataBlockIndex >= DataBlocks.Count) { // end of tape reached. Rewind to beginning AutoStopTape(); @@ -204,7 +193,7 @@ public void Play() } // update waitEdge with the current position in the current block - _waitEdge = _dataBlocks[_currentDataBlockIndex].DataPeriods[_position]; + _waitEdge = DataBlocks[_currentDataBlockIndex].DataPeriods[_position]; // sign that the tape is now playing _tapeIsPlaying = true; @@ -227,13 +216,13 @@ public void Stop() if ( _currentDataBlockIndex >= 0 && // we are at datablock 1 or above - _position >= _dataBlocks[_currentDataBlockIndex].DataPeriods.Count - 1 // the block is still playing back + _position >= DataBlocks[_currentDataBlockIndex].DataPeriods.Count - 1 // the block is still playing back ) { // move to the next block _currentDataBlockIndex++; - if (_currentDataBlockIndex >= _dataBlocks.Count) + if (_currentDataBlockIndex >= DataBlocks.Count) { _currentDataBlockIndex = -1; } @@ -244,7 +233,7 @@ public void Stop() if ( _currentDataBlockIndex < 0 && // block index is -1 - _dataBlocks.Count > 0 // number of blocks is greater than 0 + DataBlocks.Count > 0 // number of blocks is greater than 0 ) { // move the index on to 0 @@ -273,7 +262,7 @@ public void RTZ() /// public void SkipBlock(bool skipForward) { - int blockCount = _dataBlocks.Count; + int blockCount = DataBlocks.Count; int targetBlockId = _currentDataBlockIndex; if (skipForward) @@ -301,11 +290,11 @@ public void SkipBlock(bool skipForward) } } - var bl = _dataBlocks[targetBlockId]; + var bl = DataBlocks[targetBlockId]; - StringBuilder sbd = new StringBuilder(); + StringBuilder sbd = new(); sbd.Append('('); - sbd.Append((targetBlockId + 1) + " of " + _dataBlocks.Count); + sbd.Append((targetBlockId + 1) + " of " + DataBlocks.Count); sbd.Append(") : "); //sbd.Append("ID" + bl.BlockID.ToString("X2") + " - "); sbd.Append(bl.BlockDescription); @@ -331,7 +320,7 @@ public void SkipBlock(bool skipForward) public void LoadTape(byte[] tapeData) { // instantiate converters - CdtConverter cdtSer = new CdtConverter(this); + CdtConverter cdtSer = new(this); // CDT if (cdtSer.CheckType(tapeData)) @@ -355,10 +344,7 @@ public void LoadTape(byte[] tapeData) /// /// Resets the tape /// - public void Reset() - { - RTZ(); - } + public void Reset() => RTZ(); /// /// Is called every cpu cycle but runs every 50 t-states @@ -413,7 +399,7 @@ public bool GetEarBit(long cpuCycle) if (_position == 0 && tapeMotor) { // start of block - take care of initial pulse level for PZX - switch (_dataBlocks[_currentDataBlockIndex].BlockDescription) + switch (DataBlocks[_currentDataBlockIndex].BlockDescription) { case BlockType.PULS: // initial pulse level is always low @@ -422,19 +408,19 @@ public bool GetEarBit(long cpuCycle) break; case BlockType.DATA: // initial pulse level is stored in block - if (currentState != _dataBlocks[_currentDataBlockIndex].InitialPulseLevel) + if (currentState != DataBlocks[_currentDataBlockIndex].InitialPulseLevel) FlipTapeState(); break; case BlockType.PAUS: // initial pulse level is stored in block - if (currentState != _dataBlocks[_currentDataBlockIndex].InitialPulseLevel) + if (currentState != DataBlocks[_currentDataBlockIndex].InitialPulseLevel) FlipTapeState(); break; } // most of these amstrad tapes appear to have a pause block at the start // skip this if it is the first block - switch (_dataBlocks[_currentDataBlockIndex].BlockDescription) + switch (DataBlocks[_currentDataBlockIndex].BlockDescription) { case BlockType.PAUS: case BlockType.PAUSE_BLOCK: @@ -450,7 +436,7 @@ public bool GetEarBit(long cpuCycle) bool okToSkipPause = true; for (int i = _currentDataBlockIndex; i >= 0; i--) { - switch (_dataBlocks[i].BlockDescription) + switch (DataBlocks[i].BlockDescription) { case BlockType.Archive_Info: case BlockType.BRWS: @@ -480,11 +466,11 @@ public bool GetEarBit(long cpuCycle) } // notify about the current block - var bl = _dataBlocks[_currentDataBlockIndex]; + var bl = DataBlocks[_currentDataBlockIndex]; - StringBuilder sbd = new StringBuilder(); + StringBuilder sbd = new(); sbd.Append('('); - sbd.Append((_currentDataBlockIndex + 1) + " of " + _dataBlocks.Count); + sbd.Append((_currentDataBlockIndex + 1) + " of " + DataBlocks.Count); sbd.Append(") : "); //sbd.Append("ID" + bl.BlockID.ToString("X2") + " - "); sbd.Append(bl.BlockDescription); @@ -500,17 +486,17 @@ public bool GetEarBit(long cpuCycle) // increment the current period position _position++; - if (_position >= _dataBlocks[_currentDataBlockIndex].DataPeriods.Count) + if (_position >= DataBlocks[_currentDataBlockIndex].DataPeriods.Count) { // we have reached the end of the current block - if (_dataBlocks[_currentDataBlockIndex].DataPeriods.Count == 0) + if (DataBlocks[_currentDataBlockIndex].DataPeriods.Count == 0) { // notify about the current block (we are skipping it because its empty) - var bl = _dataBlocks[_currentDataBlockIndex]; - StringBuilder sbd = new StringBuilder(); + var bl = DataBlocks[_currentDataBlockIndex]; + StringBuilder sbd = new(); sbd.Append('('); - sbd.Append((_currentDataBlockIndex + 1) + " of " + _dataBlocks.Count); + sbd.Append((_currentDataBlockIndex + 1) + " of " + DataBlocks.Count); sbd.Append(") : "); //sbd.Append("ID" + bl.BlockID.ToString("X2") + " - "); sbd.Append(bl.BlockDescription); @@ -524,11 +510,11 @@ public bool GetEarBit(long cpuCycle) } // skip any empty blocks (and process any command blocks) - while (_position >= _dataBlocks[_currentDataBlockIndex].DataPeriods.Count) + while (_position >= DataBlocks[_currentDataBlockIndex].DataPeriods.Count) { // check for any commands - var command = _dataBlocks[_currentDataBlockIndex].Command; - var block = _dataBlocks[_currentDataBlockIndex]; + var command = DataBlocks[_currentDataBlockIndex].Command; + var block = DataBlocks[_currentDataBlockIndex]; bool shouldStop = false; switch (command) { @@ -581,14 +567,14 @@ public bool GetEarBit(long cpuCycle) _position = 0; _currentDataBlockIndex++; - if (_currentDataBlockIndex >= _dataBlocks.Count) + if (_currentDataBlockIndex >= DataBlocks.Count) { break; } } // check for end of tape - if (_currentDataBlockIndex >= _dataBlocks.Count) + if (_currentDataBlockIndex >= DataBlocks.Count) { _currentDataBlockIndex = -1; RTZ(); @@ -597,7 +583,7 @@ public bool GetEarBit(long cpuCycle) } // update waitEdge with current position within the current block - _waitEdge = _dataBlocks[_currentDataBlockIndex].DataPeriods[_position]; + _waitEdge = DataBlocks[_currentDataBlockIndex].DataPeriods[_position]; // flip the current state FlipTapeState(); @@ -613,10 +599,7 @@ public bool GetEarBit(long cpuCycle) return currentState; } - private void FlipTapeState() - { - currentState = !currentState; - } + private void FlipTapeState() => currentState = !currentState; public void AutoStopTape() diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Disk/NECUPD765.FDC.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Disk/NECUPD765.FDC.cs index ebef7e3f149..d2b3877b14a 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Disk/NECUPD765.FDC.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Disk/NECUPD765.FDC.cs @@ -29,7 +29,7 @@ public partial class NECUPD765 /// /// State parameters relating to the Active command /// - public CommandParameters ActiveCommandParams = new CommandParameters(); + public CommandParameters ActiveCommandParams = new(); /// /// The current active phase of the controller @@ -375,7 +375,7 @@ private void UPD_ReadData() sectorSize = 0x80 << ActiveCommandParams.SectorSize; } - var mtc = maxTransferCap; + int mtc = maxTransferCap; // get the current track var track = ActiveDrive.Disk.DiskTracks.FirstOrDefault(a => a.TrackNumber == ActiveDrive.CurrentTrackID); @@ -558,7 +558,7 @@ private void UPD_ReadData() //---------------------------------------- case Phase.Execution: - var index = ExecLength - ExecCounter; + int index = ExecLength - ExecCounter; LastSectorDataReadByte = ExecBuffer[index]; @@ -872,7 +872,7 @@ private void UPD_ReadDeletedData() // FDC in execution phase reading/writing bytes //---------------------------------------- case Phase.Execution: - var index = ExecLength - ExecCounter; + int index = ExecLength - ExecCounter; LastSectorDataReadByte = ExecBuffer[index]; @@ -1100,7 +1100,7 @@ private void UPD_ReadDiagnostic() //---------------------------------------- case Phase.Execution: - var index = ExecLength - ExecCounter; + int index = ExecLength - ExecCounter; LastSectorDataReadByte = ExecBuffer[index]; @@ -1380,7 +1380,7 @@ private void UPD_WriteData() //---------------------------------------- case Phase.Execution: - var index = ExecLength - ExecCounter; + int index = ExecLength - ExecCounter; ExecBuffer[index] = LastSectorDataWriteByte; @@ -1673,7 +1673,7 @@ private void UPD_WriteDeletedData() //---------------------------------------- case Phase.Execution: - var index = ExecLength - ExecCounter; + int index = ExecLength - ExecCounter; ExecBuffer[index] = LastSectorDataWriteByte; @@ -1866,7 +1866,7 @@ private void UPD_Specify() // process parameter byte byte currByte = CommBuffer[CommCounter]; - BitArray bi = new BitArray(new byte[] { currByte }); + BitArray bi = new(new byte[] { currByte }); switch (CommCounter) { @@ -2112,8 +2112,8 @@ private void UPD_SenseInterruptStatus() // for now I will assume that the first call is aimed at DriveA, the second at DriveB (which we are NOT implementing) // check active drive first - if (ActiveDrive.SeekStatus == SEEK_RECALIBRATE || - ActiveDrive.SeekStatus == SEEK_SEEK) + if (ActiveDrive.SeekStatus is SEEK_RECALIBRATE or + SEEK_SEEK) { // interrupt has been raised for this drive // acknowledge @@ -2495,7 +2495,7 @@ private bool ParseCommandByte(byte cmdByte) cmdByte = cByte; // lookup the command - var i = CommandList.FindIndex(a => a.CommandCode == cmdByte); + int i = CommandList.FindIndex(a => a.CommandCode == cmdByte); if (i is -1) { // no command found - use invalid @@ -2572,7 +2572,7 @@ private bool ParseCommandByte(byte cmdByte) private void ParseParamByteStandard(int index) { byte currByte = CommBuffer[index]; - BitArray bi = new BitArray(new byte[] { currByte }); + BitArray bi = new(new byte[] { currByte }); switch (index) { diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Disk/NECUPD765.FDD.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Disk/NECUPD765.FDD.cs index 52744f750c7..ee5148c25ad 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Disk/NECUPD765.FDD.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Disk/NECUPD765.FDD.cs @@ -52,7 +52,7 @@ private void FDD_Init() { for (int i = 0; i < 4; i++) { - DriveState ds = new DriveState(i, this); + DriveState ds = new(i, this); DriveStates[i] = ds; } } @@ -141,19 +141,14 @@ private FloppyDisk.Sector GetSector() /// /// Parses a new disk image and loads it into this floppy drive /// - public void FDD_LoadDisk(byte[] diskData) - { + public void FDD_LoadDisk(byte[] diskData) => // we are only going to load into the first drive DriveStates[0].FDD_LoadDisk(diskData); - } /// /// Ejects the current disk /// - public void FDD_EjectDisk() - { - DriveStates[0].FDD_EjectDisk(); - } + public void FDD_EjectDisk() => DriveStates[0].FDD_EjectDisk(); /// /// Signs whether the current active drive has a disk inserted @@ -782,11 +777,7 @@ public void FDD_LoadDisk(byte[] diskData) /// /// Ejects the current disk /// - public void FDD_EjectDisk() - { - Disk = null; - //FLAG_READY = false; - } + public void FDD_EjectDisk() => Disk = null;//FLAG_READY = false; /// /// Signs whether the current active drive has a disk inserted diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Disk/NECUPD765.IPortIODevice.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Disk/NECUPD765.IPortIODevice.cs index 763080209c7..f11bebbc3e5 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Disk/NECUPD765.IPortIODevice.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Disk/NECUPD765.IPortIODevice.cs @@ -21,7 +21,7 @@ public partial class NECUPD765 : IPortIODevice public string outputString = "STATUS,WRITE,READ,CODE,MT,MF,SK,CMDCNT,RESCNT,EXECCNT,EXECLEN\r\n"; public bool writeDebug = false; - public List dLog = new List + public List dLog = new() { "STATUS,WRITE,READ,CODE,MT,MF,SK,CMDCNT,RESCNT,EXECCNT,EXECLEN" }; @@ -41,7 +41,7 @@ public partial class NECUPD765 : IPortIODevice private void BuildCSVLine() { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); for (int i = 0; i < 3; i++) { sb.Append(workingArr[i]); @@ -119,7 +119,7 @@ public void Motor(int data) /// public bool ReadPort(ushort port, ref int data) { - BitArray bits = new BitArray(new byte[] { (byte)data }); + BitArray bits = new(new byte[] { (byte)data }); if (port == 0x3ffd) { @@ -159,7 +159,7 @@ public bool ReadPort(ushort port, ref int data) /// public bool WritePort(ushort port, int data) { - BitArray bits = new BitArray(new byte[] { (byte)data }); + BitArray bits = new(new byte[] { (byte)data }); if (port == 0x3ffd) { diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Disk/NECUPD765.Timing.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Disk/NECUPD765.Timing.cs index f269e7a3c64..94120a7854c 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Disk/NECUPD765.Timing.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Disk/NECUPD765.Timing.cs @@ -1,4 +1,4 @@ - + namespace BizHawk.Emulation.Cores.Computers.AmstradCPC { /// @@ -12,6 +12,7 @@ namespace BizHawk.Emulation.Cores.Computers.AmstradCPC */ public partial class NECUPD765 { + #pragma warning disable IDE0051 /// /// The current Z80 cycle /// @@ -25,6 +26,7 @@ private long CurrentCPUCycle return _machine.CPU.TotalExecutedCycles; } } + #pragma warning restore IDE0051 /// /// The last CPU cycle when the FDC accepted an IO read/write @@ -89,6 +91,7 @@ private void TimingInit() } + #pragma warning disable IDE0051 /// /// Called by reads to the main status register /// Returns true if there is no delay @@ -114,5 +117,6 @@ private bool CheckTiming() return true; } } + #pragma warning restore IDE0051 } } diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Disk/NECUPS765.Static.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Disk/NECUPS765.Static.cs index ae70ad7a2ff..40b89616268 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Disk/NECUPS765.Static.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Disk/NECUPS765.Static.cs @@ -18,10 +18,10 @@ public partial class NECUPD765 /// public static bool GetBit(int bitNumber, byte dataByte) { - if (bitNumber < 0 || bitNumber > 7) + if (bitNumber is < 0 or > 7) return false; - BitArray bi = new BitArray(new byte[] { dataByte }); + BitArray bi = new(new byte[] { dataByte }); return bi[bitNumber]; } @@ -31,7 +31,7 @@ public static bool GetBit(int bitNumber, byte dataByte) /// public static void SetBit(int bitNumber, ref byte dataByte) { - if (bitNumber < 0 || bitNumber > 7) + if (bitNumber is < 0 or > 7) return; int db = dataByte; @@ -46,7 +46,7 @@ public static void SetBit(int bitNumber, ref byte dataByte) /// public static void UnSetBit(int bitNumber, ref byte dataByte) { - if (bitNumber < 0 || bitNumber > 7) + if (bitNumber is < 0 or > 7) return; int db = dataByte; diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Display/AmstradGateArray.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Display/AmstradGateArray.cs index 7384e398f03..8440c93d6ba 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Display/AmstradGateArray.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Display/AmstradGateArray.cs @@ -1,4 +1,4 @@ -using BizHawk.Common; +using BizHawk.Common; using BizHawk.Common.NumberExtensions; using BizHawk.Emulation.Common; using BizHawk.Emulation.Cores.Components.Z80A; @@ -19,10 +19,12 @@ public class AmstradGateArray : IPortIODevice, IVideoProvider private readonly CPCBase _machine; private Z80A CPU => _machine.CPU; private CRCT_6845 CRCT => _machine.CRCT; + #pragma warning disable IDE0051 //private CRTDevice CRT => _machine.CRT; private IPSG PSG => _machine.AYDevice; private NECUPD765 FDC => _machine.UPDDiskDevice; private DatacorderDevice DATACORDER => _machine.TapeDevice; + #pragma warning disable IDE0051 private ushort BUSRQ => CPU.MEMRQ[CPU.bus_pntr]; public const ushort PCh = 1; @@ -233,7 +235,7 @@ public byte RMR { _RMR = value; //ScreenMode = _RMR & 0x03; - var sm = _RMR & 0x03; + int sm = _RMR & 0x03; if (sm != 1) { @@ -338,6 +340,7 @@ public int InterruptCounter /// 16-bit address - read from the CRCT /// private short _MA; + #pragma warning disable IDE0051 private short MA { get @@ -346,6 +349,7 @@ private short MA return _MA; } } + #pragma warning restore IDE0051 /// /// Set when the HSYNC signal is detected from the CRCT @@ -527,6 +531,7 @@ private void DoConditionalCPUCycle() } } + #pragma warning disable IDE0051 /// /// The CRCT builds the picture in a strange way, so that the top left of the display area is the first pixel from /// video RAM. The borders come either side of the HSYNC and VSYNCs later on: @@ -573,6 +578,7 @@ private void FrameDetector() IsNewFrame = false; } } + #pragma warning restore IDE0051 /// /// Handles interrupt generation @@ -684,7 +690,7 @@ private void GACharacterCycle() /// /// List of screen lines as they are built up /// - private readonly List ScreenLines = new List(); + private readonly List ScreenLines = new(); /// /// Pixel value lookups for every scanline byte value @@ -751,13 +757,13 @@ private void InitByteLookup() /// private void CalculateNextScreenMemory() { - var verCharCount = CRCT.VCC; - var verRasCount = CRCT.VLC; + int verCharCount = CRCT.VCC; + int verRasCount = CRCT.VLC; - var screenWidthByteCount = CRCT.DisplayWidth * 2; + int screenWidthByteCount = CRCT.DisplayWidth * 2; NextVidRamLine = new ushort[screenWidthByteCount * 2]; - var screenHeightCharCount = CRCT.DisplayHeightInChars; - var screenAddress = CRCT.MA; + int screenHeightCharCount = CRCT.DisplayHeightInChars; + short screenAddress = CRCT.MA; int baseAddress = ((screenAddress << 2) & 0xf000); int offset = (screenAddress * 2) & 0x7ff; @@ -783,14 +789,14 @@ private void RenderScanline() int cRas = CRCT.VLC; int screenByteWidth = CRCT.DisplayWidth * 2; - var screenHeightCharCount = CRCT.DisplayHeightInChars; + int screenHeightCharCount = CRCT.DisplayHeightInChars; //CalculateNextScreenMemory(); - var crctAddr = CRCT.DStartHigh << 8; + int crctAddr = CRCT.DStartHigh << 8; crctAddr |= CRCT.DStartLow; - var baseAddr = ((crctAddr << 2) & (0xF000)); //CRCT.VideoPageBase;// - var baseOffset = (crctAddr * 2) & 0x7FF; //CRCT.VideoRAMOffset * 2; // - var xA = baseOffset + ((cRow * screenByteWidth) & 0x7ff); - var yA = baseAddr + (cRas * 2048); + int baseAddr = ((crctAddr << 2) & (0xF000)); //CRCT.VideoPageBase;// + int baseOffset = (crctAddr * 2) & 0x7FF; //CRCT.VideoRAMOffset * 2; // + int xA = baseOffset + ((cRow * screenByteWidth) & 0x7ff); + int yA = baseAddr + (cRas * 2048); // border and display int pix = 0; @@ -896,11 +902,9 @@ private void RenderScanline() /// /// Called when the Z80 acknowledges an interrupt /// - public void IORQA() - { + public void IORQA() => // bit 5 of the interrupt counter is reset InterruptCounter &= ~(1 << 5); - } private int slCounter = 0; private int slBackup = 0; @@ -941,36 +945,15 @@ public void OnVSYNC() public int[] ScreenBuffer; - private int _virtualWidth; - private int _virtualHeight; - private int _bufferWidth; - private int _bufferHeight; - public int BackgroundColor => CPCHardwarePalette[0]; - public int VirtualWidth - { - get => _virtualWidth; - set => _virtualWidth = value; - } + public int VirtualWidth { get; set; } - public int VirtualHeight - { - get => _virtualHeight; - set => _virtualHeight = value; - } + public int VirtualHeight { get; set; } - public int BufferWidth - { - get => _bufferWidth; - set => _bufferWidth = value; - } + public int BufferWidth { get; set; } - public int BufferHeight - { - get => _bufferHeight; - set => _bufferHeight = value; - } + public int BufferHeight { get; set; } public int SysBufferWidth; public int SysBufferHeight; @@ -992,27 +975,27 @@ public int[] GetVideoBuffer() int lCount = 0; foreach (var l in lines) { - var lCop = l.Pixels.ToList(); - var len = l.Pixels.Count; + List lCop = l.Pixels.ToList(); + int len = l.Pixels.Count; if (l.Phases.Contains(Phase.VSYNC) && l.Phases.Contains(Phase.BORDER)) continue; if (len < 320) continue; - var pad = BufferWidth - len; + int pad = BufferWidth - len; if (pad < 0) { // trim the left and right - var padPos = pad * -1; - var excessL = padPos / 2; - var excessR = excessL + (padPos % 2); - for (var i = 0; i < excessL; i++) lCop.RemoveAt(0); - for (var i = 0; i < excessL; i++) lCop.RemoveAt(lCop.Count - 1); //TODO should be using excessR? + int padPos = pad * -1; + int excessL = padPos / 2; + int excessR = excessL + (padPos % 2); + for (int i = 0; i < excessL; i++) lCop.RemoveAt(0); + for (int i = 0; i < excessL; i++) lCop.RemoveAt(lCop.Count - 1); //TODO should be using excessR? } - var lPad = pad / 2; - var rPad = lPad + (pad % 2); + int lPad = pad / 2; + int rPad = lPad + (pad % 2); for (int i = 0; i < 2; i++) { @@ -1122,30 +1105,22 @@ public void SetupScreenSize() protected int[] croppedBuffer; - private AmstradCPC.BorderType _borderType; - - public AmstradCPC.BorderType borderType - { - get => _borderType; - set => _borderType = value; - } + public AmstradCPC.BorderType borderType { get; set; } /// /// Device responds to an IN instruction /// - public bool ReadPort(ushort port, ref int result) - { + public bool ReadPort(ushort port, ref int result) => // gate array is OUT only - return false; - } + false; /// /// Device responds to an OUT instruction /// public bool WritePort(ushort port, int result) { - BitArray portBits = new BitArray(BitConverter.GetBytes(port)); - BitArray dataBits = new BitArray(BitConverter.GetBytes((byte)result)); + BitArray portBits = new(BitConverter.GetBytes(port)); + BitArray dataBits = new(BitConverter.GetBytes((byte)result)); byte portUpper = (byte)(port >> 8); byte portLower = (byte)(port & 0xff); @@ -1234,16 +1209,13 @@ public class CharacterLine //} public int ScreenMode = 1; - public List Phases = new List(); - public List Pixels = new List(); + public List Phases = new(); + public List Pixels = new(); /// /// Adds a new horizontal character to the list /// - public void AddCharacter(Phase phase) - { - Phases.Add(phase); - } + public void AddCharacter(Phase phase) => Phases.Add(phase); public int PhaseCount => Phases.Count; diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Display/CRCT_6845.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Display/CRCT_6845.cs index d1f6d33d9be..fa8b126b21e 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Display/CRCT_6845.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Display/CRCT_6845.cs @@ -1,4 +1,4 @@ -using BizHawk.Common; +using BizHawk.Common; using BizHawk.Common.NumberExtensions; namespace BizHawk.Emulation.Cores.Computers.AmstradCPC @@ -18,15 +18,9 @@ public class CRCT_6845 : IPortIODevice private CallBack HSYNC_Callbacks; private CallBack VSYNC_Callbacks; - public void AttachVSYNCCallback(CallBack vCall) - { - VSYNC_Callbacks += vCall; - } + public void AttachVSYNCCallback(CallBack vCall) => VSYNC_Callbacks += vCall; - public void AttachHSYNCCallback(CallBack hCall) - { - HSYNC_Callbacks += hCall; - } + public void AttachHSYNCCallback(CallBack hCall) => HSYNC_Callbacks += hCall; public CRCT_6845(CRCTType chipType, CPCBase machine) { @@ -35,8 +29,10 @@ public CRCT_6845(CRCTType chipType, CPCBase machine) Reset(); } + #pragma warning disable IDE0051 private const int WRITE = 0; private const int READ = 1; + #pragma warning restore IDE0051 /// /// Denotes that HSYNC is active @@ -469,12 +465,12 @@ public void ClockCycle() { DISPTMG = true; - var line = VCC; - var row = VLC; - var addrX = (LatchedRAMOffset * 2) + ((VCC * LatchedScreenWidthBytes) & 0x7ff) + ByteCounter; + int line = VCC; + int row = VLC; + int addrX = (LatchedRAMOffset * 2) + ((VCC * LatchedScreenWidthBytes) & 0x7ff) + ByteCounter; // remove artifacts caused by certain hardware scrolling addresses addrX &= 0x7ff; - var addrY = LatchedRAMStartAddress + (2048 * VLC); + int addrY = LatchedRAMStartAddress + (2048 * VLC); //var addr = VideoPageBase + (line * (0x50)) + (row * 0x800) + (ByteCounter); CurrentByteAddress = (ushort)(addrX + addrY); @@ -538,12 +534,12 @@ public void ClockCycle2() { DISPTMG = true; - var line = VCC; - var row = VLC; - var addrX = (LatchedRAMOffset * 2) + ((VCC * LatchedScreenWidthBytes) & 0x7ff) + ByteCounter; + int line = VCC; + int row = VLC; + int addrX = (LatchedRAMOffset * 2) + ((VCC * LatchedScreenWidthBytes) & 0x7ff) + ByteCounter; // remove artifacts caused by certain hardware scrolling addresses addrX &= 0x7ff; - var addrY = LatchedRAMStartAddress + (2048 * VLC); + int addrY = LatchedRAMStartAddress + (2048 * VLC); //var addr = VideoPageBase + (line * (0x50)) + (row * 0x800) + (ByteCounter); CurrentByteAddress = (ushort)(addrX + addrY); @@ -773,10 +769,7 @@ public void Reset() /// /// Selects a register /// - private void RegisterSelect(int data) - { - SelectedRegister = data & 0x1F; - } + private void RegisterSelect(int data) => SelectedRegister = data & 0x1F; /* RegIdx Register Name Type @@ -811,7 +804,7 @@ 17 Light Pen Address (Low) Read Only Read Only Read Only private void WriteRegister(int data) { // 16 and 17 are read only registers on all types - if (SelectedRegister == 16 || SelectedRegister == 17) + if (SelectedRegister is 16 or 17) return; // non existing registers @@ -837,7 +830,7 @@ private void WriteRegister(int data) if (SelectedRegister == 1) { - var d = data; + int d = data; } Regs[SelectedRegister] = (byte)(data & CPCMask[SelectedRegister]); @@ -892,7 +885,7 @@ private bool ReadRegister(ref int data) default: // registers 18-31 read as 0, on type 0 and 2. registers 18-30 read as 0 on type1, register 31 reads as 0x0ff. - if (SelectedRegister >= 18 && SelectedRegister <= 30) + if (SelectedRegister is >= 18 and <= 30) { switch ((int)ChipType) { @@ -1042,7 +1035,7 @@ public bool WritePort(ushort port, int result) if (portUpper.Bit(6)) return accessed; - var func = portUpper & 3; + int func = portUpper & 3; switch (func) { diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Display/CRTC6845.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Display/CRTC6845.cs index 1ded8d72986..d7ada73123c 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Display/CRTC6845.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Display/CRTC6845.cs @@ -1,4 +1,4 @@ -using System.Collections; +using System.Collections; using BizHawk.Common; using BizHawk.Common.NumberExtensions; @@ -166,7 +166,7 @@ public ushort AddressLineCPC { get { - BitArray MA = new BitArray(16); + BitArray MA = new(16); MA[0] = _CLK; MA[1] = MA0; MA[2] = MA1; @@ -390,7 +390,7 @@ public virtual bool WritePort(ushort port, int value) if (portUpper.Bit(6)) return accessed; - var func = portUpper & 3; + int func = portUpper & 3; switch (func) { @@ -438,14 +438,11 @@ private int HSYNCWidth { get { - switch ((int)ChipType) + return (int)ChipType switch { - case 0: - case 1: - return HSYNCWidth_Type0_1; - default: - return HSYNCWidth_Type2_3_4; - } + 0 or 1 => HSYNCWidth_Type0_1, + _ => HSYNCWidth_Type2_3_4, + }; } } @@ -457,14 +454,11 @@ private int VSYNCWidth { get { - switch ((int)ChipType) + return (int)ChipType switch { - case 1: - case 2: - return VSYNCWidth_Type1_2; - default: - return VSYNCWidth_Type0_3_4; - } + 1 or 2 => VSYNCWidth_Type1_2, + _ => VSYNCWidth_Type0_3_4, + }; } } @@ -473,8 +467,8 @@ private int VSYNCWidth /// private void SelectRegister(int value) { - var v = (byte)((byte)value & 0x1F); - if (v > 0 && v < 18) + byte v = (byte)((byte)value & 0x1F); + if (v is > 0 and < 18) { AddressRegister = v; } @@ -485,15 +479,14 @@ private void SelectRegister(int value) /// private bool ReadRegister(ref int data) { - switch ((int)ChipType) - { - case 0: return ReadRegister_Type0(ref data); - case 1: return ReadRegister_Type1(ref data); - case 2: return ReadRegister_Type2(ref data); - case 3: - case 4: return ReadRegister_Type3_4(ref data); - default: return false; - } + return (int)ChipType switch + { + 0 => ReadRegister_Type0(ref data), + 1 => ReadRegister_Type1(ref data), + 2 => ReadRegister_Type2(ref data), + 3 or 4 => ReadRegister_Type3_4(ref data), + _ => false, + }; } /// @@ -516,13 +509,12 @@ private void WriteRegister(int data) /// private bool ReadStatus(ref int data) { - switch ((int)ChipType) + return (int)ChipType switch { - case 1: return ReadStatus_Type1(ref data); - case 3: - case 4: return ReadStatus_Type3_4(ref data); - default: return false; - } + 1 => ReadStatus_Type1(ref data), + 3 or 4 => ReadStatus_Type3_4(ref data), + _ => false, + }; } /// @@ -532,7 +524,7 @@ private int DISPTMGSkew { get { - var val = Register[INTERLACE_MODE]; + byte val = Register[INTERLACE_MODE]; int res = 0; switch ((int)ChipType) { @@ -569,7 +561,7 @@ private int CUDISPSkew { get { - var val = Register[INTERLACE_MODE]; + byte val = Register[INTERLACE_MODE]; int res = 0; switch ((int)ChipType) { @@ -599,6 +591,7 @@ private int CUDISPSkew } } + #pragma warning disable IDE0051 /// /// The currently selected Interlace Mode (based on R8) /// Looks to be the same for all chip types @@ -626,6 +619,7 @@ private InterlaceMode CurrentInterlaceMode return InterlaceMode.NormalSyncMode; } } + #pragma warning restore IDE0051 /// /// Gets the combined value of R12 & R13 @@ -634,8 +628,8 @@ private int StartAddressRegisterValue { get { - var Reg13 = Register[START_ADDR_L]; - var Reg12 = (byte)(Register[START_ADDR_H] & 0x3f); + byte Reg13 = Register[START_ADDR_L]; + byte Reg12 = (byte)(Register[START_ADDR_H] & 0x3f); return (Reg12 << 8) + Reg13; } } @@ -647,8 +641,8 @@ private int CursorAddressRegisterValue { get { - var reg15 = Register[CURSOR_L]; - var reg14 = (byte)(Register[CURSOR_H] & 0x3f); + byte reg15 = Register[CURSOR_L]; + byte reg14 = (byte)(Register[CURSOR_H] & 0x3f); return (reg14 << 8) + reg15; } } @@ -669,7 +663,7 @@ private int HSYNCWidth_Type2_3_4 { // Bits 3..0 define Horizontal Sync Width. // If 0 is programmed this gives a HSYNC width of 16 - var width = (Register[SYNC_WIDTHS] >> 0) & 0x0F; + int width = (Register[SYNC_WIDTHS] >> 0) & 0x0F; if (width == 0) width = 16; return width; @@ -685,7 +679,7 @@ private int VSYNCWidth_Type0_3_4 { // Bits 7..4 define Vertical Sync Width // If 0 is programmed this gives 16 lines of VSYNC - var width = (Register[SYNC_WIDTHS] >> 4) & 0x0F; + int width = (Register[SYNC_WIDTHS] >> 4) & 0x0F; if (width == 0) width = 16; return width; @@ -733,7 +727,7 @@ private bool ReadRegister_Type0(ref int data) data = Register[AddressRegister]; break; default: - if (AddressRegister > 17 && AddressRegister < 32) + if (AddressRegister is > 17 and < 32) { data = 0; } @@ -791,7 +785,7 @@ private bool ReadRegister_Type1(ref int data) data = 0xff; break; default: - if (AddressRegister > 17 && AddressRegister < 31) + if (AddressRegister is > 17 and < 31) { data = 0; } @@ -840,7 +834,7 @@ private bool ReadRegister_Type2(ref int data) data = Register[AddressRegister]; break; default: - if (AddressRegister > 17 && AddressRegister < 32) + if (AddressRegister is > 17 and < 32) { data = 0; } @@ -1079,19 +1073,15 @@ private bool ReadStatus_Type1(ref int data) /// Status Register is unavailable but attempts to read will return the currently /// selected register data instead /// - private bool ReadStatus_Type3_4(ref int data) - { - return ReadRegister(ref data); - } + private bool ReadStatus_Type3_4(ref int data) => ReadRegister(ref data); +#pragma warning disable IDE0051 /// /// Read Status Register (HD6845S & UM6845) /// No status register available /// - private bool ReadStatus_Unavailable(ref int data) - { - return false; - } + private bool ReadStatus_Unavailable(ref int data) => false; +#pragma warning restore IDE0051 /* persistent switch signals */ private bool s_VS; @@ -1404,9 +1394,9 @@ private void ClockCycle_Type0() bool curOutput = false; // info from registers - var curStartRaster = Register[CURSOR_START] & 0x1f; - var curEndRaster = Register[CURSOR_END] & 0x1f; - var curDisplayMode = (Register[CURSOR_START] & 0x60) >> 5; + int curStartRaster = Register[CURSOR_START] & 0x1f; + int curEndRaster = Register[CURSOR_END] & 0x1f; + int curDisplayMode = (Register[CURSOR_START] & 0x60) >> 5; switch (curDisplayMode) { @@ -1516,6 +1506,7 @@ private void ClockCycle_Type0() } } + #pragma warning disable IDE0051 /// /// Runs a Type1 Clock Cycle /// There doesnt seem to be a block diagram in the datasheets for this, so will use the type0 @@ -1750,9 +1741,9 @@ private void ClockCycle_Type1() bool curOutput = false; // info from registers - var curStartRaster = Register[CURSOR_START] & 0x1f; - var curEndRaster = Register[CURSOR_END] & 0x1f; - var curDisplayMode = (Register[CURSOR_START] & 0x60) >> 5; + int curStartRaster = Register[CURSOR_START] & 0x1f; + int curEndRaster = Register[CURSOR_END] & 0x1f; + int curDisplayMode = (Register[CURSOR_START] & 0x60) >> 5; switch (curDisplayMode) { @@ -1808,6 +1799,7 @@ private void ClockCycle_Type1() _LPSTB = false; } } + #pragma warning restore IDE0051 /// /// Runs a Type2 Clock Cycle @@ -2041,9 +2033,9 @@ private void ClockCycle_Type2() bool curOutput = false; // info from registers - var curStartRaster = Register[CURSOR_START] & 0x1f; - var curEndRaster = Register[CURSOR_END] & 0x1f; - var curDisplayMode = (Register[CURSOR_START] & 0x60) >> 5; + int curStartRaster = Register[CURSOR_START] & 0x1f; + int curEndRaster = Register[CURSOR_END] & 0x1f; + int curDisplayMode = (Register[CURSOR_START] & 0x60) >> 5; switch (curDisplayMode) { @@ -2097,6 +2089,7 @@ private void ClockCycle_Type2() } } + #pragma warning disable IDE0051 /// /// Runs a Type3or4 Clock Cycle /// @@ -2104,6 +2097,7 @@ private void ClockCycle_Type3_4() { } + #pragma warning restore IDE0051 /* Horizontal Timing Register Constants */ /// diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Display/CRTDevice.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Display/CRTDevice.cs index 06461dadcb0..9b7a8d50a3f 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Display/CRTDevice.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Display/CRTDevice.cs @@ -118,10 +118,7 @@ public CRTDevice(CPCBase machine) /// /// Video buffer processing /// - public int[] ProcessVideoBuffer() - { - return ScreenBuffer; - } + public int[] ProcessVideoBuffer() => ScreenBuffer; /// /// Sets up buffers and the like at the start of a frame diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Input/StandardKeyboard.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Input/StandardKeyboard.cs index 5c3eb8a24d2..e4714fb2c2f 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Input/StandardKeyboard.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/Input/StandardKeyboard.cs @@ -20,7 +20,7 @@ public int CurrentLine set { // bits 0-3 contain the line - var line = value & 0x0f; + int line = value & 0x0f; if (line > 0) { @@ -37,20 +37,8 @@ public bool[] KeyStatus get => _keyStatus; set => _keyStatus = value; } - - private string[] _keyboardMatrix; - public string[] KeyboardMatrix - { - get => _keyboardMatrix; - set => _keyboardMatrix = value; - } - - private string[] _nonMatrixKeys; - public string[] NonMatrixKeys - { - get => _nonMatrixKeys; - set => _nonMatrixKeys = value; - } + public string[] KeyboardMatrix { get; set; } + public string[] NonMatrixKeys { get; set; } public StandardKeyboard(CPCBase machine) { @@ -88,9 +76,9 @@ public StandardKeyboard(CPCBase machine) KeyStatus = new bool[8 * 10]; // nonmatrix keys (anything that hasnt already been taken) - var nonMatrix = new List(); + List nonMatrix = new(); - foreach (var key in _machine.CPC.AmstradCPCControllerDefinition.BoolButtons) + foreach (string key in _machine.CPC.AmstradCPCControllerDefinition.BoolButtons) { if (!KeyboardMatrix.Any(s => s == key)) nonMatrix.Add(key); @@ -104,10 +92,10 @@ public StandardKeyboard(CPCBase machine) /// public byte ReadCurrentLine() { - var lin = _currentLine; // - 0x40; - var pos = lin * 8; - var l = KeyStatus.Skip(pos).Take(8).ToArray(); - BitArray bi = new BitArray(l); + int lin = _currentLine; // - 0x40; + int pos = lin * 8; + bool[] l = KeyStatus.Skip(pos).Take(8).ToArray(); + BitArray bi = new(l); byte[] bytes = new byte[1]; bi.CopyTo(bytes, 0); byte inv = (byte)(~bytes[0]); diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/PPI/PPI_8255.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/PPI/PPI_8255.cs index 535c111003b..edccb6987a6 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/PPI/PPI_8255.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/PPI/PPI_8255.cs @@ -1,4 +1,4 @@ -using System.Collections; +using System.Collections; using BizHawk.Common; using BizHawk.Common.NumberExtensions; @@ -13,7 +13,9 @@ public class PPI_8255 : IPortIODevice { private readonly CPCBase _machine; private CRCT_6845 CRTC => _machine.CRCT; + #pragma warning disable IDE0051 private AmstradGateArray GateArray => _machine.GateArray; + #pragma warning restore IDE0051 private IPSG PSG => _machine.AYDevice; private DatacorderDevice Tape => _machine.TapeDevice; private IKeyboard Keyboard => _machine.KeyboardDevice; @@ -83,12 +85,10 @@ private void OUTPortA(int data) /// /// Writes to Port B /// - private void OUTPortB(int data) - { + private void OUTPortB(int data) => // PortB is read only // just latch the data Regs[PORT_B] = (byte)data; - } /// /// Writes to Port C @@ -141,7 +141,7 @@ private void OUTControl(int data) bool isSet = data.Bit(0); // get the bit in PortC that we wish to change - var bit = (data >> 1) & 7; + int bit = (data >> 1) & 7; // modify this bit if (isSet) @@ -202,7 +202,7 @@ private int INPortB() { // build the PortB output // start with every bit reset - BitArray rBits = new BitArray(8); + BitArray rBits = new(8); // Bit0 - Vertical Sync ("1"=VSYNC active, "0"=VSYNC inactive) if (CRTC.VSYNC) @@ -253,7 +253,7 @@ private int INPortC() val &= 0x0f; // isolate control bits - var v = Regs[PORT_C] & 0xc0; + int v = Regs[PORT_C] & 0xc0; if (v == 0xc0) { @@ -309,7 +309,7 @@ public bool ReadPort(ushort port, ref int result) //if (portUpper.Bit(3)) //return false; - var PPIFunc = (port & 0x0300) >> 8; // portUpper & 3; + int PPIFunc = (port & 0x0300) >> 8; // portUpper & 3; switch (PPIFunc) { @@ -353,7 +353,7 @@ public bool WritePort(ushort port, int result) if (portUpper.Bit(3)) return false; - var PPIFunc = portUpper & 3; + int PPIFunc = portUpper & 3; switch (PPIFunc) { diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/SoundOutput/AY38912.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/SoundOutput/AY38912.cs index 0e2134c332a..e3ee09f13d2 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/SoundOutput/AY38912.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/SoundOutput/AY38912.cs @@ -1,4 +1,4 @@ -using BizHawk.Common; +using BizHawk.Common; using BizHawk.Emulation.Common; using System; using System.Collections.Generic; @@ -328,19 +328,14 @@ public void StartFrame() /// /// End of frame /// - public void EndFrame() - { - BufferUpdate(_tStatesPerFrame); - } + public void EndFrame() => BufferUpdate(_tStatesPerFrame); /// /// Updates the audiobuffer based on the current frame t-state /// - public void UpdateSound(int frameCycle) - { - BufferUpdate(frameCycle); - } + public void UpdateSound(int frameCycle) => BufferUpdate(frameCycle); +#pragma warning disable IDE0051 /// /// Register indicies /// @@ -360,6 +355,7 @@ public void UpdateSound(int frameCycle) private const int AY_E_SHAPE = 13; private const int AY_PORT_A = 14; private const int AY_PORT_B = 15; + #pragma warning restore IDE0051 /// /// The register array @@ -414,7 +410,7 @@ The AY-3-8912 ignores bit 7 of this register. /// /// The rendering resolution of the chip /// - private double _resolution = 50D * 8D / _chipFrequency; + private readonly double _resolution = 50D * 8D / _chipFrequency; /// /// Channel generator state @@ -504,7 +500,7 @@ The AY-3-8912 ignores bit 7 of this register. /// /// Panning table list /// - private static readonly List PanTabs = new List + private static readonly List PanTabs = new() { // MONO new uint[] { 50,50, 50,50, 50,50 }, @@ -554,9 +550,9 @@ The AY-3-8912 ignores bit 7 of this register. private void UpdateVolume() { int upperFloor = 40000; - var inc = (0xFFFF - upperFloor) / 100; + int inc = (0xFFFF - upperFloor) / 100; - var vol = inc * _volume; // ((ulong)0xFFFF * (ulong)_volume / 100UL) - 20000 ; + int vol = inc * _volume; // ((ulong)0xFFFF * (ulong)_volume / 100UL) - 20000 ; _volumeTables = new uint[6][]; // parent array @@ -653,7 +649,7 @@ private void BufferUpdate(int cycle) if ((_eState & ~31) != 0) { - var mask = (1 << _registers[AY_E_SHAPE]); + int mask = (1 << _registers[AY_E_SHAPE]); if ((mask & ((1 << 0) | (1 << 1) | (1 << 2) | (1 << 3) | (1 << 4) | (1 << 5) | (1 << 6) | @@ -681,12 +677,12 @@ private void BufferUpdate(int cycle) } // mix the sample - var mixA = ((_eMaskA & _eState) | _vA) & ((_bitA | _bit0) & (_bitN | _bit3)); - var mixB = ((_eMaskB & _eState) | _vB) & ((_bitB | _bit1) & (_bitN | _bit4)); - var mixC = ((_eMaskC & _eState) | _vC) & ((_bitC | _bit2) & (_bitN | _bit5)); + int mixA = ((_eMaskA & _eState) | _vA) & ((_bitA | _bit0) & (_bitN | _bit3)); + int mixB = ((_eMaskB & _eState) | _vB) & ((_bitB | _bit1) & (_bitN | _bit4)); + int mixC = ((_eMaskC & _eState) | _vC) & ((_bitC | _bit2) & (_bitN | _bit5)); - var l = _volumeTables[0][mixA]; - var r = _volumeTables[1][mixA]; + uint l = _volumeTables[0][mixA]; + uint r = _volumeTables[1][mixA]; l += _volumeTables[2][mixB]; r += _volumeTables[3][mixB]; @@ -712,17 +708,9 @@ public void SetSyncMode(SyncSoundMode mode) throw new InvalidOperationException("Only Sync mode is supported."); } - public void GetSamplesAsync(short[] samples) - { - throw new NotSupportedException("Async is not available"); - } + public void GetSamplesAsync(short[] samples) => throw new NotSupportedException("Async is not available"); - public void DiscardSamples() - { - _audioBuffer = new short[_samplesPerFrame * 2]; - //_blipL.Clear(); - //_blipR.Clear(); - } + public void DiscardSamples() => _audioBuffer = new short[_samplesPerFrame * 2];//_blipL.Clear();//_blipR.Clear(); public void GetSamplesSync(out short[] samples, out int nsamp) { diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/SoundOutput/Beeper.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/SoundOutput/Beeper.cs index 204a2a21e8f..40f5e59f130 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/SoundOutput/Beeper.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Hardware/SoundOutput/Beeper.cs @@ -33,7 +33,7 @@ public int Volume get => VolumeConverterOut(_volume); set { - var newVol = VolumeConverterIn(value); + int newVol = VolumeConverterIn(value); if (newVol != _volume) blip.Clear(); _volume = VolumeConverterIn(value); @@ -68,7 +68,7 @@ public int Volume /// /// Device blipbuffer /// - private readonly BlipBuffer blip = new BlipBuffer(883); + private readonly BlipBuffer blip = new(883); /// /// Takes an int 0-100 and returns the relevant short volume to output @@ -147,15 +147,9 @@ public void SetSyncMode(SyncSoundMode mode) throw new InvalidOperationException("Only Sync mode is supported."); } - public void GetSamplesAsync(short[] samples) - { - throw new NotSupportedException("Async is not available"); - } + public void GetSamplesAsync(short[] samples) => throw new NotSupportedException("Async is not available"); - public void DiscardSamples() - { - blip.Clear(); - } + public void DiscardSamples() => blip.Clear(); public void GetSamplesSync(out short[] samples, out int nsamp) { diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPC464/CPC464.Memory.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPC464/CPC464.Memory.cs index d15d22e3a56..cceafbd04f4 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPC464/CPC464.Memory.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPC464/CPC464.Memory.cs @@ -88,7 +88,7 @@ public override void WriteBus(ushort addr, byte value) /// public override byte ReadMemory(ushort addr) { - var data = ReadBus(addr); + byte data = ReadBus(addr); return data; } @@ -96,10 +96,7 @@ public override byte ReadMemory(ushort addr) /// Writes a byte of data to a specified memory address /// (with memory contention if appropriate) /// - public override void WriteMemory(ushort addr, byte value) - { - WriteBus(addr, value); - } + public override void WriteMemory(ushort addr, byte value) => WriteBus(addr, value); /// diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPC464/CPC464.Port.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPC464/CPC464.Port.cs index 9d2d10e321f..66fb0affab3 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPC464/CPC464.Port.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPC464/CPC464.Port.cs @@ -14,7 +14,7 @@ public partial class CPC464 : CPCBase /// public override byte ReadPort(ushort port) { - BitArray portBits = new BitArray(BitConverter.GetBytes(port)); + BitArray portBits = new(BitConverter.GetBytes(port)); byte portUpper = (byte)(port >> 8); byte portLower = (byte)(port & 0xff); @@ -54,8 +54,8 @@ public override byte ReadPort(ushort port) /// public override void WritePort(ushort port, byte value) { - BitArray portBits = new BitArray(BitConverter.GetBytes(port)); - BitArray dataBits = new BitArray(BitConverter.GetBytes(value)); + BitArray portBits = new(BitConverter.GetBytes(port)); + BitArray dataBits = new(BitConverter.GetBytes(value)); byte portUpper = (byte)(port >> 8); byte portLower = (byte)(port & 0xff); diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPC6128/CPC6128.Memory.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPC6128/CPC6128.Memory.cs index e64b0621ea0..3d685dd40fb 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPC6128/CPC6128.Memory.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPC6128/CPC6128.Memory.cs @@ -25,15 +25,11 @@ public override byte ReadBus(ushort addr) } else { - switch (RAMConfig) + result = RAMConfig switch { - case 2: - result = RAM4[addr % 0x4000]; - break; - default: - result = RAM0[addr % 0x4000]; - break; - } + 2 => RAM4[addr % 0x4000], + _ => RAM0[addr % 0x4000], + }; } break; @@ -67,45 +63,30 @@ public override byte ReadBus(ushort addr) // RAM 0x8000 case 2: - switch (RAMConfig) + result = RAMConfig switch { - case 2: - result = RAM6[addr % 0x4000]; - break; - default: - result = RAM2[addr % 0x4000]; - break; - } + 2 => RAM6[addr % 0x4000], + _ => RAM2[addr % 0x4000], + }; break; // RAM 0xc000 case 3: if (UpperROMPaged) { - switch (UpperROMPosition) + result = UpperROMPosition switch { - case 7: - result = ROM7[addr % 0x4000]; - break; - case 0: - default: - result = ROM0[addr % 0x4000]; - break; - } + 7 => ROM7[addr % 0x4000], + _ => ROM0[addr % 0x4000], + }; } else { - switch (RAMConfig) + result = RAMConfig switch { - case 1: - case 2: - case 3: - result = RAM7[addr % 0x4000]; - break; - default: - result = RAM3[addr % 0x4000]; - break; - } + 1 or 2 or 3 => RAM7[addr % 0x4000], + _ => RAM3[addr % 0x4000], + }; } break; default: @@ -203,7 +184,7 @@ public override void WriteBus(ushort addr, byte value) /// public override byte ReadMemory(ushort addr) { - var data = ReadBus(addr); + byte data = ReadBus(addr); return data; } @@ -211,10 +192,7 @@ public override byte ReadMemory(ushort addr) /// Writes a byte of data to a specified memory address /// (with memory contention if appropriate) /// - public override void WriteMemory(ushort addr, byte value) - { - WriteBus(addr, value); - } + public override void WriteMemory(ushort addr, byte value) => WriteBus(addr, value); /// diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPC6128/CPC6128.Port.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPC6128/CPC6128.Port.cs index 6cd4c5706c9..42651a13af4 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPC6128/CPC6128.Port.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPC6128/CPC6128.Port.cs @@ -15,7 +15,7 @@ public partial class CPC6128 : CPCBase /// public override byte ReadPort(ushort port) { - BitArray portBits = new BitArray(BitConverter.GetBytes(port)); + BitArray portBits = new(BitConverter.GetBytes(port)); byte portUpper = (byte)(port >> 8); byte portLower = (byte)(port & 0xff); @@ -68,8 +68,8 @@ public override byte ReadPort(ushort port) /// public override void WritePort(ushort port, byte value) { - BitArray portBits = new BitArray(BitConverter.GetBytes(port)); - BitArray dataBits = new BitArray(BitConverter.GetBytes(value)); + BitArray portBits = new(BitConverter.GetBytes(port)); + BitArray dataBits = new(BitConverter.GetBytes(value)); byte portUpper = (byte)(port >> 8); byte portLower = (byte)(port & 0xff); @@ -88,7 +88,7 @@ public override void WritePort(ushort port, byte value) RAMConfig = value & 0x07; // additional 64K bank index - var b64 = value & 0x38; + int b64 = value & 0x38; } } else if (d == PortDevice.CRCT) diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPCBase.Input.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPCBase.Input.cs index d947398c1f5..d1f83e1d046 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPCBase.Input.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPCBase.Input.cs @@ -53,7 +53,7 @@ public void PollInput() { // parse single keyboard matrix keys. // J1 and J2 are scanned as part of the keyboard - for (var i = 0; i < KeyboardDevice.KeyboardMatrix.Length; i++) + for (int i = 0; i < KeyboardDevice.KeyboardMatrix.Length; i++) { string key = KeyboardDevice.KeyboardMatrix[i]; bool prevState = KeyboardDevice.GetKeyStatus(key); diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPCBase.Media.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPCBase.Media.cs index 02dc1620eb3..04bfa10f776 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPCBase.Media.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPCBase.Media.cs @@ -121,7 +121,7 @@ protected void LoadAllMedia() diskImages = new List(); int cnt = 0; - foreach (var m in mediaImages) + foreach (byte[] m in mediaImages) { switch (IdentifyMedia(m)) { @@ -136,7 +136,7 @@ protected void LoadAllMedia() case CPCMediaType.DiskDoubleSided: // this is a bit tricky. we will attempt to parse the double sided disk image byte array, // then output two separate image byte arrays - List working = new List(); + List working = new(); foreach (DiskType type in Enum.GetValues(typeof(DiskType))) { bool found = false; @@ -158,12 +158,12 @@ protected void LoadAllMedia() // add side 2 diskImages.Add(working[1]); - Common.GameInfo one = new Common.GameInfo(); - Common.GameInfo two = new Common.GameInfo(); + Common.GameInfo one = new(); + Common.GameInfo two = new(); var gi = CPC._gameInfo[cnt]; for (int i = 0; i < 2; i++) { - Common.GameInfo work = new Common.GameInfo(); + Common.GameInfo work = new(); if (i == 0) { work = one; @@ -205,10 +205,7 @@ protected void LoadAllMedia() /// /// Attempts to load a tape into the tape device based on tapeMediaIndex /// - protected void LoadTapeMedia() - { - TapeDevice.LoadTape(tapeImages[tapeMediaIndex]); - } + protected void LoadTapeMedia() => TapeDevice.LoadTape(tapeImages[tapeMediaIndex]); /// /// Attempts to load a disk into the disk device based on diskMediaIndex @@ -237,7 +234,7 @@ private CPCMediaType IdentifyMedia(byte[] data) { // amstrad .dsk disk file // check for number of sides - var sides = data[0x31]; + byte sides = data[0x31]; if (sides == 1) return CPCMediaType.Disk; else diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPCBase.Memory.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPCBase.Memory.cs index 80cb7bcd9fb..099e62e7b42 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPCBase.Memory.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPCBase.Memory.cs @@ -67,10 +67,7 @@ public abstract partial class CPCBase /// /// Pushes a value onto the data bus that should be valid as long as the interrupt is true /// - public virtual byte PushBus() - { - return 0xFF; - } + public virtual byte PushBus() => 0xFF; /// /// Simulates writing to the bus diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPCBase.Port.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPCBase.Port.cs index d70afd91019..20012e87919 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPCBase.Port.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/CPCBase.Port.cs @@ -28,7 +28,7 @@ public abstract partial class CPCBase /// protected virtual PortDevice DecodeINPort(ushort port) { - PortDevice dev = PortDevice.Unknown; + var dev = PortDevice.Unknown; if (!port.Bit(15) && port.Bit(14)) dev = PortDevice.GateArray; @@ -62,7 +62,7 @@ protected virtual PortDevice DecodeINPort(ushort port) /// protected virtual List DecodeOUTPort(ushort port) { - List devs = new List(); + List devs = new(); if (!port.Bit(15) && port.Bit(14)) devs.Add(PortDevice.GateArray); diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/GateArrayBase.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/GateArrayBase.cs index 71cf090839d..c6789668547 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/GateArrayBase.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Machine/GateArrayBase.cs @@ -1,4 +1,4 @@ -using BizHawk.Common; +using BizHawk.Common; using BizHawk.Emulation.Common; using BizHawk.Emulation.Cores.Components.Z80A; using System; @@ -19,7 +19,9 @@ public abstract class GateArrayBase : IVideoProvider private readonly CPCBase _machine; private Z80A CPU => _machine.CPU; private CRCT_6845 CRCT => _machine.CRCT; + #pragma warning disable IDE0051 private IPSG PSG => _machine.AYDevice; + #pragma warning restore IDE0051 /// /// CRTC Register constants @@ -269,17 +271,14 @@ public virtual void SetPenColour(BitArray bi) { byte[] b = new byte[1]; bi.CopyTo(b, 0); - var colour = b[0] & 0x1f; + int colour = b[0] & 0x1f; PenColours[CurrentPen] = colour; } /// /// Returns the actual ARGB pen colour value /// - public virtual int GetPenColour(int idx) - { - return CPCHardwarePalette[PenColours[idx]]; - } + public virtual int GetPenColour(int idx) => CPCHardwarePalette[PenColours[idx]]; /// /// Screen mode and ROM config @@ -290,7 +289,7 @@ public virtual void SetReg2(BitArray bi) bi.CopyTo(b, 0); // screen mode - var mode = b[0] & 0x03; + int mode = b[0] & 0x03; ScreenMode = mode; // ROM @@ -331,10 +330,7 @@ public virtual void SetRAM(BitArray bi) return; } - public void InterruptACK() - { - INTScanlineCnt &= 0x01f; - } + public void InterruptACK() => INTScanlineCnt &= 0x01f; public void Reset() @@ -350,19 +346,17 @@ public void Reset() /// /// Device responds to an IN instruction /// - public bool ReadPort(ushort port, ref int result) - { + public bool ReadPort(ushort port, ref int result) => // gate array is OUT only - return false; - } + false; /// /// Device responds to an OUT instruction /// public bool WritePort(ushort port, int result) { - BitArray portBits = new BitArray(BitConverter.GetBytes(port)); - BitArray dataBits = new BitArray(BitConverter.GetBytes((byte)result)); + BitArray portBits = new(BitConverter.GetBytes(port)); + BitArray dataBits = new(BitConverter.GetBytes((byte)result)); // The gate array responds to port 0x7F bool accessed = !portBits[15]; @@ -402,36 +396,15 @@ public bool WritePort(ushort port, int result) /// public int[] ScreenBuffer; - private int _virtualWidth; - private int _virtualHeight; - private int _bufferWidth; - private int _bufferHeight; - public int BackgroundColor => CPCHardwarePalette[16]; - public int VirtualWidth - { - get => _virtualWidth; - set => _virtualWidth = value; - } + public int VirtualWidth { get; set; } - public int VirtualHeight - { - get => _virtualHeight; - set => _virtualHeight = value; - } + public int VirtualHeight { get; set; } - public int BufferWidth - { - get => _bufferWidth; - set => _bufferWidth = value; - } + public int BufferWidth { get; set; } - public int BufferHeight - { - get => _bufferHeight; - set => _bufferHeight = value; - } + public int BufferHeight { get; set; } public int VsyncNumerator { diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Media/Disk/CPCExtendedFloppyDisk.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Media/Disk/CPCExtendedFloppyDisk.cs index 3193db72be0..926d1dbb7df 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Media/Disk/CPCExtendedFloppyDisk.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Media/Disk/CPCExtendedFloppyDisk.cs @@ -46,7 +46,7 @@ public override bool ParseDisk(byte[] data) if (DiskHeader.NumberOfSides > 1) { - StringBuilder sbm = new StringBuilder(); + StringBuilder sbm = new(); sbm.AppendLine(); sbm.AppendLine(); sbm.AppendLine("The detected disk image contains multiple sides."); @@ -74,10 +74,11 @@ public override bool ParseDisk(byte[] data) } int p = pos; - DiskTracks[i] = new Track(); - - // track info block - DiskTracks[i].TrackIdent = Encoding.ASCII.GetString(data, p, 12); + DiskTracks[i] = new Track + { + // track info block + TrackIdent = Encoding.ASCII.GetString(data, p, 12) + }; p += 16; DiskTracks[i].TrackNumber = data[p++]; DiskTracks[i].SideNumber = data[p++]; @@ -193,7 +194,7 @@ public static bool SplitDoubleSided(byte[] data, List results) while (tCount < data[0x30] * data[0x31]) { // which side is this? - var side = data[mPos + 0x11]; + byte side = data[mPos + 0x11]; if (side == 0) { // side 1 diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Media/Disk/CPCFloppyDisk.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Media/Disk/CPCFloppyDisk.cs index 43029789b4b..4a8b4f4dfcc 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Media/Disk/CPCFloppyDisk.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Media/Disk/CPCFloppyDisk.cs @@ -46,7 +46,7 @@ public override bool ParseDisk(byte[] data) if (DiskHeader.NumberOfSides > 1) { - StringBuilder sbm = new StringBuilder(); + StringBuilder sbm = new(); sbm.AppendLine(); sbm.AppendLine(); sbm.AppendLine("The detected disk image contains multiple sides."); @@ -75,10 +75,11 @@ public override bool ParseDisk(byte[] data) } int p = pos; - DiskTracks[i] = new Track(); - - // track info block - DiskTracks[i].TrackIdent = Encoding.ASCII.GetString(data, p, 12); + DiskTracks[i] = new Track + { + // track info block + TrackIdent = Encoding.ASCII.GetString(data, p, 12) + }; p += 16; DiskTracks[i].TrackNumber = data[p++]; DiskTracks[i].SideNumber = data[p++]; @@ -185,7 +186,7 @@ public static bool SplitDoubleSided(byte[] data, List results) while (mPos < trkSize * data[0x30] * data[0x31]) { // which side is this? - var side = data[mPos + 0x11]; + byte side = data[mPos + 0x11]; if (side == 0) { // side 1 diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Media/Disk/FloppyDisk.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Media/Disk/FloppyDisk.cs index 8b77b899b32..c974931f10d 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Media/Disk/FloppyDisk.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Media/Disk/FloppyDisk.cs @@ -20,7 +20,7 @@ public abstract class FloppyDisk /// /// Disk information header /// - public Header DiskHeader = new Header(); + public Header DiskHeader = new(); /// /// Track array @@ -93,12 +93,10 @@ public int RandomCounter /// TRUE: disk parsed /// FALSE: unable to parse disk /// - public virtual bool ParseDisk(byte[] diskData) - { + public virtual bool ParseDisk(byte[] diskData) => // default result // override in inheriting class - return false; - } + false; /// /// Examines the floppydisk data to work out what protection (if any) is present @@ -114,11 +112,11 @@ public virtual void ParseProtection() { Protection = ProtectionType.Speedlock; - Sector sec = DiskTracks[0].Sectors[1]; + var sec = DiskTracks[0].Sectors[1]; if (!sec.ContainsMultipleWeakSectors) { byte[] origData = sec.SectorData.ToArray(); - List data = new List(); + List data = new(); for (int m = 0; m < 3; m++) { for (int i = 0; i < 512; i++) @@ -245,7 +243,7 @@ public bool DetectSpeedlock(ref int[] weak) return false; // sector[1] (SectorID 2) contains the weak sectors - Sector sec = DiskTracks[0].Sectors[1]; + var sec = DiskTracks[0].Sectors[1]; // check for correct sector 1 lengths if (sec.SectorSize != 2 || @@ -288,8 +286,8 @@ public bool DetectAlkatraz(ref int[] weak) { try { - var data1 = DiskTracks[0].Sectors[0].SectorData; - var data2 = DiskTracks[0].Sectors[0].SectorData.Length; + byte[] data1 = DiskTracks[0].Sectors[0].SectorData; + int data2 = DiskTracks[0].Sectors[0].SectorData.Length; } catch (Exception) { @@ -329,8 +327,8 @@ public bool DetectPaulOwens(ref int[] weak) { try { - var data1 = DiskTracks[0].Sectors[2].SectorData; - var data2 = DiskTracks[0].Sectors[2].SectorData.Length; + byte[] data1 = DiskTracks[0].Sectors[2].SectorData; + int data2 = DiskTracks[0].Sectors[2].SectorData.Length; } catch (Exception) { @@ -365,10 +363,10 @@ public bool DetectHexagon(ref int[] weak) { try { - var data1 = DiskTracks[0].Sectors.Length; - var data2 = DiskTracks[0].Sectors[8].ActualDataByteLength; - var data3 = DiskTracks[0].Sectors[8].SectorData; - var data4 = DiskTracks[0].Sectors[8].SectorData.Length; + int data1 = DiskTracks[0].Sectors.Length; + int data2 = DiskTracks[0].Sectors[8].ActualDataByteLength; + byte[] data3 = DiskTracks[0].Sectors[8].SectorData; + int data4 = DiskTracks[0].Sectors[8].SectorData.Length; var data5 = DiskTracks[1].Sectors[0]; } catch (Exception) @@ -505,10 +503,7 @@ protected virtual void SpeedlockDetection() /// /// Returns the track count for the disk /// - public virtual int GetTrackCount() - { - return DiskHeader.NumberOfTracks * DiskHeader.NumberOfSides; - } + public virtual int GetTrackCount() => DiskHeader.NumberOfTracks * DiskHeader.NumberOfSides; /// /// Reads the current sector ID info @@ -534,11 +529,12 @@ public virtual CHRN ReadID(byte trackIndex, byte side, int sectorIndex) var sector = track.Sectors[sectorIndex]; - CHRN chrn = new CHRN(); - - chrn.C = sector.TrackNumber; - chrn.H = sector.SideNumber; - chrn.R = sector.SectorID; + CHRN chrn = new() + { + C = sector.TrackNumber, + H = sector.SideNumber, + R = sector.SectorID + }; // wrap around for N > 7 if (sector.SectorSize > 7) @@ -598,7 +594,7 @@ public byte[] TrackSectorData { get { - List list = new List(); + List list = new(); foreach (var sec in Sectors) { @@ -658,7 +654,7 @@ public byte[] ActualData int size = 0x80 << SectorSize; if (size > ActualDataByteLength) { - List l = new List(); + List l = new(); l.AddRange(SectorData); for (int i = 0; i < size - ActualDataByteLength; i++) { @@ -702,7 +698,7 @@ public byte[] ActualData } public CHRN SectorIDInfo => - new CHRN + new() { C = TrackNumber, H = SideNumber, diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Media/MediaConverter.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Media/MediaConverter.cs index 954f76c2ded..ed8c5429e20 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Media/MediaConverter.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Media/MediaConverter.cs @@ -60,18 +60,12 @@ public static byte[] GetBytes(int value) /// /// Returns an int32 from a byte array based on offset /// - public static int GetInt32(byte[] buf, int offsetIndex) - { - return buf[offsetIndex] | buf[offsetIndex + 1] << 8 | buf[offsetIndex + 2] << 16 | buf[offsetIndex + 3] << 24; - } + public static int GetInt32(byte[] buf, int offsetIndex) => buf[offsetIndex] | buf[offsetIndex + 1] << 8 | buf[offsetIndex + 2] << 16 | buf[offsetIndex + 3] << 24; /// /// Returns an uint16 from a byte array based on offset /// - public static ushort GetWordValue(byte[] buf, int offsetIndex) - { - return (ushort)(buf[offsetIndex] | buf[offsetIndex + 1] << 8); - } + public static ushort GetWordValue(byte[] buf, int offsetIndex) => (ushort)(buf[offsetIndex] | buf[offsetIndex + 1] << 8); /// /// Updates a byte array with a uint16 value based on offset @@ -88,7 +82,7 @@ public static void SetWordValue(byte[] buf, int offsetIndex, ushort value) public static int TranslatePause(int pauseInMS) { // t-states per millisecond - var tspms = (69888 * 50) / 1000; + int tspms = (69888 * 50) / 1000; // get value int res = pauseInMS * tspms; @@ -100,12 +94,12 @@ public static int TranslatePause(int pauseInMS) /// public static void DecompressZRLE(byte[] sourceBuffer, ref byte[] destBuffer) { - MemoryStream stream = new MemoryStream(); + MemoryStream stream = new(); stream.Write(sourceBuffer, 0, sourceBuffer.Length); stream.Position = 0; stream.ReadByte(); stream.ReadByte(); - DeflateStream ds = new DeflateStream(stream, CompressionMode.Decompress, false); + DeflateStream ds = new(stream, CompressionMode.Decompress, false); ds.Read(destBuffer, 0, destBuffer.Length); } } diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Media/Tape/CDT/CdtConverter.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Media/Tape/CDT/CdtConverter.cs index 8591e2f0008..ac956a6ae97 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Media/Tape/CDT/CdtConverter.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Media/Tape/CDT/CdtConverter.cs @@ -42,7 +42,7 @@ protected override string SelfTypeName /// /// Object to keep track of loops - this assumes there is only one loop at a time /// - private readonly List> _loopCounter = new List>(); + private readonly List> _loopCounter = new(); private readonly DatacorderDevice _datacorder; @@ -58,7 +58,7 @@ public CdtConverter(DatacorderDevice _tapeDevice) /// private TapeDataBlock ConvertClock(TapeDataBlock db) { - var tb = new TapeDataBlock + TapeDataBlock tb = new() { BlockDescription = db.BlockDescription, BlockID = db.BlockID, @@ -93,10 +93,7 @@ private int ClockAdjust(int val) private int Scale => ((40 << 16) / 35); - private int Adjust(int val) - { - return (int)((val * CLOCK_MULTIPLIER)); - } + private int Adjust(int val) => (int)((val * CLOCK_MULTIPLIER)); private const double CLOCK_MULTIPLIER = 1.142857; @@ -338,7 +335,7 @@ This block must be replayed with the standard Spectrum ROM timing values - see t for custom loading routines that use the same timings as ROM ones do. */ private void ProcessBlockID10(byte[] data) { - var t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x10, BlockDescription = BlockType.Standard_Speed_Data_Block, @@ -390,7 +387,7 @@ This block is very similar to the normal TAP block but with some additional info sync or pilot tones (i.e. all sorts of protection schemes) then use the next three blocks to describe it.*/ private void ProcessBlockID11(byte[] data) { - var t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x11, BlockDescription = BlockType.Turbo_Speed_Data_Block, @@ -441,7 +438,7 @@ private void ProcessBlockID12(byte[] data) { int blockLen = 4; - var t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x12, BlockDescription = BlockType.Pure_Tone, @@ -477,7 +474,7 @@ 0x00 N BYTE Number of pulses sync tones used by some protection schemes. */ private void ProcessBlockID13(byte[] data) { - TapeDataBlock t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x13, BlockDescription = BlockType.Pulse_Sequence, @@ -517,7 +514,7 @@ 0x07 N BYTE[3] Length of data that follow This is the same as in the turbo loading data block, except that it has no pilot or sync pulses. */ private void ProcessBlockID14(byte[] data) { - TapeDataBlock t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x14, BlockDescription = BlockType.Pure_Data_Block, @@ -572,7 +569,7 @@ The preferred sampling frequencies are 22050 or 44100 Hz (158 or 79 T-states/sam Please use this block only if you cannot use any other block. */ private void ProcessBlockID15(byte[] data) { - var t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x15, BlockDescription = BlockType.Direct_Recording, @@ -674,7 +671,7 @@ Offset Value Type Description This block contains a sequence of raw pulses encoded in CSW format v2 (Compressed Square Wave). */ private void ProcessBlockID18(byte[] data) { - TapeDataBlock t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x18, BlockDescription = BlockType.CSW_Recording, @@ -704,7 +701,7 @@ private void ProcessBlockID18(byte[] data) SinclairSpectrum.CswConverter.ProcessCSWV2(src, ref dest, compType, pulses); // create the periods - var rate = (69888 * 50) / sampleRate; + int rate = (69888 * 50) / sampleRate; for (int i = 0; i < dest.Length;) { @@ -793,7 +790,7 @@ the symbol and the number of times it must be repeated. private void ProcessBlockID19(byte[] data) { // not currently implemented properly - var t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x19, BlockDescription = BlockType.Generalized_Data_Block, @@ -835,7 +832,7 @@ Offset Value Type Description emulator or utility should (in effect) STOP THE TAPE, i.e. should not continue loading until the user or emulator requests it. */ private void ProcessBlockID20(byte[] data) { - TapeDataBlock t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x20, DataPeriods = new List(), @@ -895,7 +892,7 @@ You can also give the group a name (example 'Bleepload Block 1'). For each group start block, there must be a group end block. Nesting of groups is not allowed. */ private void ProcessBlockID21(byte[] data) { - var t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x21, DataPeriods = new List(), @@ -923,7 +920,7 @@ private void ProcessBlockID21(byte[] data) This indicates the end of a group. This block has no body. */ private void ProcessBlockID22(byte[] data) { - TapeDataBlock t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x22, DataPeriods = new List(), @@ -950,7 +947,7 @@ All blocks are included in the block count!. */ private void ProcessBlockID23(byte[] data) { // not implemented properly - var t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x23, DataPeriods = new List(), @@ -996,7 +993,7 @@ be repeated. This block is the same as the FOR statement in BASIC. For simplicity reasons don't nest loop blocks! */ private void ProcessBlockID24(byte[] data) { - var t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x24, DataPeriods = new List(), @@ -1033,7 +1030,7 @@ private void ProcessBlockID24(byte[] data) This block has no body. */ private void ProcessBlockID25(byte[] data) { - var t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x25, DataPeriods = new List(), @@ -1057,9 +1054,11 @@ private void ProcessBlockID25(byte[] data) // loop through each group to repeat for (int b = 0; b < numberOfRepetitions; b++) { - TapeDataBlock repeater = new TapeDataBlock(); - //repeater.BlockDescription = "[LOOP REPEAT - " + (b + 1) + "]"; - repeater.DataPeriods = new List(); + TapeDataBlock repeater = new() + { + //repeater.BlockDescription = "[LOOP REPEAT - " + (b + 1) + "]"; + DataPeriods = new List() + }; // add the repeat block _datacorder.DataBlocks.Add(repeater); @@ -1086,7 +1085,7 @@ then goes back to the next block. Because more than one call can be normally use private void ProcessBlockID26(byte[] data) { // block processing not implemented for this - just gets added for informational purposes only - var t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x26, DataPeriods = new List(), @@ -1112,7 +1111,7 @@ This block indicates the end of the Called Sequence. The next block played will private void ProcessBlockID27(byte[] data) { // block processing not implemented for this - just gets added for informational purposes only - var t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x27, DataPeriods = new List(), @@ -1145,7 +1144,7 @@ selections when it encounters such a block. All offsets are relative signed word private void ProcessBlockID28(byte[] data) { // block processing not implemented for this - just gets added for informational purposes only - var t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x28, DataPeriods = new List(), @@ -1172,7 +1171,7 @@ 0x00 0 DWORD Length of the block without these four bytes (0) This block has no body of its own, but follows the extension rule. */ private void ProcessBlockID2A(byte[] data) { - var t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x2A, DataPeriods = new List(), @@ -1200,7 +1199,7 @@ This block sets the current signal level to the specified value (high or low). I ambiguities, e.g. with custom loaders which are level-sensitive. */ private void ProcessBlockID2B(byte[] data) { - var t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x2B, DataPeriods = new List(), @@ -1228,7 +1227,7 @@ The description can be up to 255 characters long but please keep it down to abou Please use 'Archive Info' block for title, authors, publisher, etc. */ private void ProcessBlockID30(byte[] data) { - var t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x30, DataPeriods = new List(), @@ -1267,7 +1266,7 @@ stick to a maximum of 8 lines. private void ProcessBlockID31(byte[] data) { // currently not implemented properly in CPCHawk - var t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x31, DataPeriods = new List(), @@ -1327,7 +1326,7 @@ If all texts on the tape are in English language then you don't have to supply t The information about what hardware the tape uses is in the 'Hardware Type' block, so no need for it here. */ private void ProcessBlockID32(byte[] data) { - var t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x32, DataPeriods = new List(), @@ -1432,7 +1431,7 @@ private void ProcessBlockID33(byte[] data) { // currently not implemented properly in CPCHawk - TapeDataBlock t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x33, DataPeriods = new List(), @@ -1465,7 +1464,7 @@ 0x10 L DWORD Length of the custom info extra settings required by a particular emulator, or even poke data. */ private void ProcessBlockID35(byte[] data) { - var t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x35, DataPeriods = new List(), @@ -1499,7 +1498,7 @@ This block is generated when you merge two ZX Tape files together. It is here so ensure that they are both of the higher version number. */ private void ProcessBlockID5A(byte[] data) { - var t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x5A, DataPeriods = new List(), @@ -1516,7 +1515,7 @@ private void ProcessBlockID5A(byte[] data) private void ProcessUnidentifiedBlock(byte[] data) { - var t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = -2, DataPeriods = new List(), @@ -1538,7 +1537,7 @@ private void ProcessUnidentifiedBlock(byte[] data) private void ProcessBlockID16(byte[] data) { // CPCHawk will not implement this block. it will however handle it so subsequent blocks can be parsed - TapeDataBlock t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x16, DataPeriods = new List(), @@ -1557,7 +1556,7 @@ private void ProcessBlockID16(byte[] data) private void ProcessBlockID17(byte[] data) { // CPCHawk will not implement this block. it will however handle it so subsequent blocks can be parsed - var t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x17, DataPeriods = new List(), @@ -1576,7 +1575,7 @@ private void ProcessBlockID17(byte[] data) private void ProcessBlockID34(byte[] data) { // currently not implemented properly in CPCHawk - var t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x34, DataPeriods = new List(), @@ -1606,7 +1605,7 @@ private void ProcessBlockID40(byte[] data) { // currently not implemented properly in CPCHawk - TapeDataBlock t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x40, DataPeriods = new List(), @@ -1666,10 +1665,10 @@ A SCREEN$ file is regarded as a Code file with start address 16384 and length 69 { string fileName = Encoding.ASCII.GetString(blockdata.Skip(2).Take(10).ToArray()).Trim(); string type = "Unknown Type"; - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); - var param1 = GetWordValue(blockdata, 12); - var param2 = GetWordValue(blockdata, 14); + ushort param1 = GetWordValue(blockdata, 12); + ushort param2 = GetWordValue(blockdata, 14); // header block - examine first byte of header if (blockdata[1] == 0) @@ -1706,7 +1705,7 @@ A SCREEN$ file is regarded as a Code file with start address 16384 and length 69 else { // some other type (turbo data etc..) - description = $"#{blockdata[0].ToString("X2")} block, {blockSize} bytes"; + description = $"#{blockdata[0]:X2} block, {blockSize} bytes"; //description += (crc != 0) ? $", crc bad (#{crcFile:X2}!=#{crcValue:X2})" : ", crc ok"; block.AddMetaData(BlockDescriptorTitle.Undefined, description); } @@ -1785,7 +1784,7 @@ A SCREEN$ file is regarded as a Code file with start address 16384 and length 69 block.AddMetaData(BlockDescriptorTitle.Pause_After_Data, pauseAfterBlock + " ms"); // calculate period information - List dataPeriods = new List(); + List dataPeriods = new(); // generate pilot pulses @@ -1905,13 +1904,13 @@ private void CreatePauseBlock(TapeDataBlock original) { if (original.PauseInMS > 0) { - var pBlock = new TapeDataBlock + TapeDataBlock pBlock = new() { DataPeriods = new List(), BlockDescription = BlockType.PAUSE_BLOCK, PauseInMS = 0 }; - var pauseInTStates = TranslatePause(original.PauseInMS); + int pauseInTStates = TranslatePause(original.PauseInMS); pBlock.AddMetaData(BlockDescriptorTitle.Block_ID, pauseInTStates + " cycles"); diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Media/Tape/TapeDataBlock.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Media/Tape/TapeDataBlock.cs index 5ba41f11da0..3391ac6bfa4 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Media/Tape/TapeDataBlock.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/Media/Tape/TapeDataBlock.cs @@ -20,8 +20,7 @@ public int BlockID { _blockID = value; - if (MetaData == null) - MetaData = new Dictionary(); + MetaData ??= new Dictionary(); AddMetaData(BlockDescriptorTitle.Block_ID, value.ToString()); } @@ -37,8 +36,7 @@ public BlockType BlockDescription set { _blockType = value; - if (MetaData == null) - MetaData = new Dictionary(); + MetaData ??= new Dictionary(); } } @@ -93,7 +91,7 @@ public void AddMetaData(BlockDescriptorTitle descriptor, string data) /// /// List containing the pulse timing values /// - public List DataPeriods = new List(); + public List DataPeriods = new(); public bool InitialPulseLevel; @@ -107,35 +105,20 @@ public TapeCommand Command get => _command; set => _command = value; } - - /// - /// The defined post-block pause - /// - private int _pauseInMS; - public int PauseInMS - { - get => _pauseInMS; - set => _pauseInMS = value; - } + public int PauseInMS { get; set; } /// /// Returns the data periods as an array /// (primarily to aid in bizhawk state serialization) /// - public int[] GetDataPeriodsArray() - { - return DataPeriods.ToArray(); - } + public int[] GetDataPeriodsArray() => DataPeriods.ToArray(); /// /// Accepts an array of data periods and updates the DataPeriods list accordingly /// (primarily to aid in bizhawk state serialization) /// - public void SetDataPeriodsArray(int[] periodArray) - { - DataPeriods = periodArray?.ToList() ?? new List(); - } + public void SetDataPeriodsArray(int[] periodArray) => DataPeriods = periodArray?.ToList() ?? new List(); /// /// Bizhawk state serialization diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/ROM/RomData.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/ROM/RomData.cs index 62ffb71c30c..5875cabbd3f 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/ROM/RomData.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/ROM/RomData.cs @@ -9,12 +9,7 @@ public class RomData /// /// ROM Contents /// - public byte[] RomBytes - { - get => _romBytes; - set => _romBytes = value; - } - private byte[] _romBytes; + public byte[] RomBytes { get; set; } public enum ROMChipType { @@ -37,7 +32,7 @@ public enum ROMChipType /// public static RomData InitROM(MachineType machineType, byte[] rom, ROMChipType type, int romPosition = 0) { - RomData RD = new RomData { RomBytes = new byte[rom.Length] }; + RomData RD = new() { RomBytes = new byte[rom.Length] }; RD.RomBytes = rom; RD.ROMType = type; diff --git a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/SoundProviderMixer.cs b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/SoundProviderMixer.cs index 9bc3ec6539e..b6bed4de4d6 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/SoundProviderMixer.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AmstradCPC/SoundProviderMixer.cs @@ -21,12 +21,7 @@ private class Provider public int NSamp { get; set; } } - private bool _stereo = true; - public bool Stereo - { - get => _stereo; - set => _stereo = value; - } + public bool Stereo { get; set; } = true; private readonly List SoundProviders; @@ -114,10 +109,7 @@ public void SetSyncMode(SyncSoundMode mode) throw new InvalidOperationException("Only Sync mode is supported."); } - public void GetSamplesAsync(short[] samples) - { - throw new NotSupportedException("Async is not available"); - } + public void GetSamplesAsync(short[] samples) => throw new NotSupportedException("Async is not available"); public void DiscardSamples() { @@ -135,14 +127,14 @@ public void GetSamplesSync(out short[] samples, out int nsamp) // get samples from all the providers foreach (var sp in SoundProviders) { - sp.SoundProvider.GetSamplesSync(out var samp, out var sampCount); + sp.SoundProvider.GetSamplesSync(out short[] samp, out int sampCount); sp.NSamp = sampCount; sp.Buffer = samp; } // are all the sample lengths the same? - var firstEntry = SoundProviders[0].NSamp; - var sameCount = SoundProviders.TrueForAll(s => s.NSamp == firstEntry); + int firstEntry = SoundProviders[0].NSamp; + bool sameCount = SoundProviders.TrueForAll(s => s.NSamp == firstEntry); if (!sameCount) { diff --git a/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.IDebuggable.cs b/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.IDebuggable.cs index 9566f1b14a2..cdb29b197a8 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.IDebuggable.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.IDebuggable.cs @@ -9,7 +9,7 @@ public partial class AppleII : IDebuggable { public IDictionary GetCpuFlagsAndRegisters() { - var regs = new Dictionary + Dictionary regs = new() { ["A"] = _machine.Cpu.RA, ["X"] = _machine.Cpu.RX, @@ -26,7 +26,7 @@ public IDictionary GetCpuFlagsAndRegisters() ["Flag T"] = _machine.Cpu.FlagT ? 1 : 0 }; - var dic = new Dictionary(); + Dictionary dic = new(); foreach (var reg in regs) { @@ -92,15 +92,11 @@ public void SetCpuRegister(string register, int value) public bool CanStep(StepType type) { - switch (type) + return type switch { - case StepType.Into: - case StepType.Over: - case StepType.Out: - return true; - default: - return false; - } + StepType.Into or StepType.Over or StepType.Out => true, + _ => false, + }; } public void Step(StepType type) @@ -123,18 +119,12 @@ public void Step(StepType type) private RegisterValue GetRegisterValue(KeyValuePair reg) { - switch (reg.Key) + return reg.Key switch { - case "A": - case "X": - case "Y": - case "S": - return (byte)reg.Value; - case "PC": - return (ushort)reg.Value; - default: - return reg.Value; - } + "A" or "X" or "Y" or "S" => (RegisterValue)(byte)reg.Value, + "PC" => (RegisterValue)(ushort)reg.Value, + _ => (RegisterValue)reg.Value, + }; } private void StepInto() @@ -148,7 +138,7 @@ private void StepInto() _machine.Cpu.TraceCallback = null; } - var machineInVblank = _machine.Video.IsVBlank; + bool machineInVblank = _machine.Video.IsVBlank; _machine.Events.HandleEvents(_machine.Cpu.Execute()); @@ -168,11 +158,11 @@ private void StepInto() private void StepOver() { - var instruction = _machine.Memory.Read(_machine.Cpu.RPC); + int instruction = _machine.Memory.Read(_machine.Cpu.RPC); if (instruction == Jsr) { - var destination = _machine.Cpu.RPC + JsrSize; + int destination = _machine.Cpu.RPC + JsrSize; while (_machine.Cpu.RPC != destination) { StepInto(); @@ -186,11 +176,11 @@ private void StepOver() private void StepOut() { - var instr = _machine.Memory.Read(_machine.Cpu.RPC); + int instr = _machine.Memory.Read(_machine.Cpu.RPC); _jsrCount = instr == Jsr ? 1 : 0; - var bailOutFrame = Frame + 1; + int bailOutFrame = Frame + 1; while (true) { diff --git a/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.IDisassembler.cs b/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.IDisassembler.cs index 4ae4f1a1072..74abbe4b74d 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.IDisassembler.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.IDisassembler.cs @@ -22,9 +22,6 @@ public IEnumerable AvailableCpus get { yield return "6502"; } } - public string Disassemble(MemoryDomain m, uint addr, out int length) - { - return MOS6502X.Disassemble((ushort)addr, out length, a => m.PeekByte(a)); - } + public string Disassemble(MemoryDomain m, uint addr, out int length) => MOS6502X.Disassemble((ushort)addr, out length, a => m.PeekByte(a)); } } diff --git a/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.IMemoryDomains.cs index 6d7932bb5e3..6602197b009 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.IMemoryDomains.cs @@ -9,9 +9,9 @@ public partial class AppleII { private void SetupMemoryDomains() { - var domains = new List(); + List domains = new(); - var mainRamDomain = new MemoryDomainDelegate("Main RAM", 0x10000, MemoryDomain.Endian.Little, + MemoryDomainDelegate mainRamDomain = new("Main RAM", 0x10000, MemoryDomain.Endian.Little, addr => { if (addr is < 0 or > 0x10000) throw new ArgumentOutOfRangeException(paramName: nameof(addr), addr, message: "address out of range"); @@ -25,7 +25,7 @@ private void SetupMemoryDomains() domains.Add(mainRamDomain); - var auxRamDomain = new MemoryDomainDelegate("Auxiliary RAM", 0x10000, MemoryDomain.Endian.Little, + MemoryDomainDelegate auxRamDomain = new("Auxiliary RAM", 0x10000, MemoryDomain.Endian.Little, addr => { if (addr is < 0 or > 0x10000) throw new ArgumentOutOfRangeException(paramName: nameof(addr), addr, message: "address out of range"); @@ -39,7 +39,7 @@ private void SetupMemoryDomains() domains.Add(auxRamDomain); - var systemBusDomain = new MemoryDomainDelegate("System Bus", 0x10000, MemoryDomain.Endian.Little, + MemoryDomainDelegate systemBusDomain = new("System Bus", 0x10000, MemoryDomain.Endian.Little, addr => { if (addr is < 0 or > 0xFFFF) throw new ArgumentOutOfRangeException(paramName: nameof(addr), addr, message: "address out of range"); diff --git a/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.ISaveRam.cs b/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.ISaveRam.cs index 332dda89e35..7bf973863d7 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.ISaveRam.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.ISaveRam.cs @@ -10,21 +10,18 @@ public partial class AppleII : ISaveRam { private byte[][] _diskDeltas; - private void InitSaveRam() - { - _diskDeltas = new byte[DiskCount][]; - } + private void InitSaveRam() => _diskDeltas = new byte[DiskCount][]; public bool SaveRamModified => true; public byte[] CloneSaveRam() { - using var ms = new MemoryStream(); - using var bw = new BinaryWriter(ms); + using MemoryStream ms = new(); + using BinaryWriter bw = new(ms); SaveDelta(); bw.Write(DiskCount); - for (var i = 0; i < DiskCount; i++) + for (int i = 0; i < DiskCount; i++) { bw.WriteByteBuffer(_diskDeltas[i]); } @@ -34,17 +31,17 @@ public byte[] CloneSaveRam() public void StoreSaveRam(byte[] data) { - using var ms = new MemoryStream(data, false); - using var br = new BinaryReader(ms); + using MemoryStream ms = new(data, false); + using BinaryReader br = new(ms); - var ndisks = br.ReadInt32(); + int ndisks = br.ReadInt32(); if (ndisks != DiskCount) { throw new InvalidOperationException("Disk count mismatch!"); } - for (var i = 0; i < DiskCount; i++) + for (int i = 0; i < DiskCount; i++) { _diskDeltas[i] = br.ReadByteBuffer(returnNull: true); } diff --git a/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.ISettable.cs b/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.ISettable.cs index ffa5a4a42ad..bbc3001f9e3 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.ISettable.cs @@ -66,7 +66,7 @@ public PutSettingsDirtyBits PutSettings(Settings o) public PutSettingsDirtyBits PutSyncSettings(SyncSettings o) { - var ret = SyncSettings.NeedsReboot(_syncSettings, o); + bool ret = SyncSettings.NeedsReboot(_syncSettings, o); _syncSettings = o; return ret ? PutSettingsDirtyBits.RebootCore : PutSettingsDirtyBits.None; } diff --git a/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.ISoundProvider.cs b/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.ISoundProvider.cs index a655d5247b6..692cb9a7eb8 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.ISoundProvider.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.ISoundProvider.cs @@ -7,15 +7,9 @@ public partial class AppleII : ISoundProvider { public bool CanProvideAsync => false; - public void GetSamplesSync(out short[] samples, out int nsamp) - { - _machine.Memory.Speaker.GetSamples(out samples, out nsamp); - } + public void GetSamplesSync(out short[] samples, out int nsamp) => _machine.Memory.Speaker.GetSamples(out samples, out nsamp); - public void DiscardSamples() - { - _machine.Memory.Speaker.Clear(); - } + public void DiscardSamples() => _machine.Memory.Speaker.Clear(); public SyncSoundMode SyncMode => SyncSoundMode.Sync; @@ -27,9 +21,6 @@ public void SetSyncMode(SyncSoundMode mode) } } - public void GetSamplesAsync(short[] samples) - { - throw new InvalidOperationException("Async mode is not supported."); - } + public void GetSamplesAsync(short[] samples) => throw new InvalidOperationException("Async mode is not supported."); } } diff --git a/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.IStatable.cs b/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.IStatable.cs index 5ad404baed1..01938484dae 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.IStatable.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.IStatable.cs @@ -9,30 +9,18 @@ public partial class AppleII : ITextStatable { public bool AvoidRewind => false; - public void SaveStateText(TextWriter writer) - { - SyncState(new AppleSerializer(writer)); - } + public void SaveStateText(TextWriter writer) => SyncState(new AppleSerializer(writer)); - public void LoadStateText(TextReader reader) - { - SyncState(new AppleSerializer(reader)); - } + public void LoadStateText(TextReader reader) => SyncState(new AppleSerializer(reader)); - public void SaveStateBinary(BinaryWriter writer) - { - SyncState(new AppleSerializer(writer)); - } + public void SaveStateBinary(BinaryWriter writer) => SyncState(new AppleSerializer(writer)); - public void LoadStateBinary(BinaryReader reader) - { - SyncState(new AppleSerializer(reader)); - } + public void LoadStateBinary(BinaryReader reader) => SyncState(new AppleSerializer(reader)); private void SyncState(AppleSerializer ser) { int version = 2; - var oldCurrentDisk = CurrentDisk; + int oldCurrentDisk = CurrentDisk; ser.BeginSection(nameof(AppleII)); ser.Sync(nameof(version), ref version); ser.Sync("Frame", ref _frame); @@ -80,7 +68,7 @@ private void SyncState(AppleSerializer ser) ser.EndSection(); ser.BeginSection("InactiveDisks"); - for (var i = 0; i < DiskCount; i++) + for (int i = 0; i < DiskCount; i++) { // the current disk is handled in DiskIIController if (i != CurrentDisk) diff --git a/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.cs b/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.cs index dfd2082afb3..998f1a15aca 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AppleII/AppleII.cs @@ -25,7 +25,7 @@ public AppleII(CoreLoadParameters lp) { static (byte[], string) GetRomAndExt(IRomAsset romAssert) { - var ext = romAssert.Extension.ToUpperInvariant(); + string ext = romAssert.Extension.ToUpperInvariant(); return ext switch { ".DSK" or ".PO" or ".DO" or ".NIB" => (romAssert.FileData, ext), @@ -35,7 +35,7 @@ public AppleII(CoreLoadParameters lp) } _romSet = lp.Roms.Select(GetRomAndExt).ToList(); - var ser = new BasicServiceProvider(this); + BasicServiceProvider ser = new(this); ServiceProvider = ser; const string TRACE_HEADER = "6502: PC, opcode, register (A, X, Y, P, SP, Cy), flags (NVTBDIZC)"; @@ -119,10 +119,10 @@ private void InitDisk() LoadDelta(false); } - private static readonly List RealButtons = new List(Keyboard.GetKeyNames() + private static readonly List RealButtons = new(Keyboard.GetKeyNames() .Where(k => k != "Reset")); - private static readonly List ExtraButtons = new List + private static readonly List ExtraButtons = new() { "Previous Disk", "Next Disk", diff --git a/src/BizHawk.Emulation.Cores/Computers/AppleII/Components.cs b/src/BizHawk.Emulation.Cores/Computers/AppleII/Components.cs index 48217ba0818..aa001173222 100644 --- a/src/BizHawk.Emulation.Cores/Computers/AppleII/Components.cs +++ b/src/BizHawk.Emulation.Cores/Computers/AppleII/Components.cs @@ -17,7 +17,7 @@ public Components(byte[] appleIIe, byte[] diskIIRom) NoSlotClock = new NoSlotClock(Video); DiskIIController = new DiskIIController(Video, diskIIRom); - var emptySlot = new EmptyPeripheralCard(Video); + EmptyPeripheralCard emptySlot = new(Video); // Necessary because of tangling dependencies between memory and video classes Memory.Initialize( diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.IDebuggable.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.IDebuggable.cs index dca7310fb5b..d7dd220ba93 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.IDebuggable.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.IDebuggable.cs @@ -18,10 +18,7 @@ private IEnumerable GetAvailableDebuggables() } } - private void SetDefaultDebuggable() - { - _selectedDebuggable = GetAvailableDebuggables().First(); - } + private void SetDefaultDebuggable() => _selectedDebuggable = GetAvailableDebuggables().First(); public IDictionary GetCpuFlagsAndRegisters() { diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.IDisassemblable.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.IDisassemblable.cs index 944c24bcb9e..39004256f40 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.IDisassemblable.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.IDisassemblable.cs @@ -18,10 +18,7 @@ private IEnumerable GetAvailableDisassemblables() } } - private void SetDefaultDisassemblable() - { - _selectedDisassemblable = GetAvailableDisassemblables().First(); - } + private void SetDefaultDisassemblable() => _selectedDisassemblable = GetAvailableDisassemblables().First(); public string Cpu { @@ -59,10 +56,7 @@ public string PCRegisterName } } - public IEnumerable AvailableCpus - { - get { return GetAvailableDisassemblables().SelectMany(d => d.AvailableCpus); } - } + public IEnumerable AvailableCpus => GetAvailableDisassemblables().SelectMany(d => d.AvailableCpus); public string Disassemble(MemoryDomain m, uint addr, out int length) { diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.IMemoryDomains.cs index b89b26709ba..38ac232d8e1 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.IMemoryDomains.cs @@ -13,7 +13,7 @@ private void SetupMemoryDomains() bool diskDriveEnabled = _board.DiskDrive != null; bool tapeDriveEnabled = _board.TapeDrive != null; - var domains = new List + List domains = new() { C64MemoryDomainFactory.Create("System Bus", 0x10000, a => _board.Cpu.Peek(a), (a, v) => _board.Cpu.Poke(a, v)), C64MemoryDomainFactory.Create("RAM", 0x10000, a => _board.Ram.Peek(a), (a, v) => _board.Ram.Poke(a, v)), @@ -48,10 +48,7 @@ private void SetupMemoryDomains() private static class C64MemoryDomainFactory { - public static MemoryDomain Create(string name, int size, Func peekByte, Action pokeByte) - { - return new MemoryDomainDelegate(name, size, MemoryDomain.Endian.Little, addr => unchecked((byte)peekByte((int)addr)), (addr, val) => pokeByte(unchecked((int)addr), val), 1); - } + public static MemoryDomain Create(string name, int size, Func peekByte, Action pokeByte) => new MemoryDomainDelegate(name, size, MemoryDomain.Endian.Little, addr => unchecked((byte)peekByte((int)addr)), (addr, val) => pokeByte(unchecked((int)addr), val), 1); } } } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.ISettable.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.ISettable.cs index 4c9342c8489..c182ab80ed6 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.ISettable.cs @@ -6,15 +6,9 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64 // adelikat: changing settings to default object until there are actually settings, as the ui depends on it to know if there are any settings available public partial class C64 : ISettable { - public C64Settings GetSettings() - { - return Settings.Clone(); - } + public C64Settings GetSettings() => Settings.Clone(); - public C64SyncSettings GetSyncSettings() - { - return SyncSettings.Clone(); - } + public C64SyncSettings GetSyncSettings() => SyncSettings.Clone(); public PutSettingsDirtyBits PutSettings(C64Settings o) { @@ -43,10 +37,7 @@ public class C64Settings [DefaultValue(BorderType.SmallProportional)] public BorderType BorderType { get; set; } - public C64Settings Clone() - { - return (C64Settings)MemberwiseClone(); - } + public C64Settings Clone() => (C64Settings)MemberwiseClone(); public C64Settings() { @@ -86,10 +77,7 @@ public class C64SyncSettings [DefaultValue(DiskDriveType.None)] public DiskDriveType DiskDriveType { get; set; } - public C64SyncSettings Clone() - { - return (C64SyncSettings)MemberwiseClone(); - } + public C64SyncSettings Clone() => (C64SyncSettings)MemberwiseClone(); public C64SyncSettings() { diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.IStatable.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.IStatable.cs index 51a61d24b82..253303d658b 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.IStatable.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.IStatable.cs @@ -11,7 +11,7 @@ private void SyncState(Serializer ser) ser.Sync(nameof(Frame), ref _frame); ser.Sync(nameof(IsLagFrame), ref _isLagFrame); ser.Sync(nameof(LagCount), ref _lagCount); - var oldDisk = _currentDisk; + int oldDisk = _currentDisk; ser.Sync(nameof(CurrentDisk), ref _currentDisk); if (oldDisk != _currentDisk) { diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.Motherboard.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.Motherboard.cs index 2f0001e7e48..881ccb79655 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.Motherboard.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.Motherboard.cs @@ -172,10 +172,7 @@ public void Execute() Vic.ExecutePhase2(); } - public void Flush() - { - Sid.Flush(false); - } + public void Flush() => Sid.Flush(false); // ----------------------------------------- public void HardReset() diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.MotherboardInput.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.MotherboardInput.cs index 572e027ceb5..a1e6e98b7f0 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.MotherboardInput.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.MotherboardInput.cs @@ -32,9 +32,9 @@ public void PollInput() // scan joysticks _pollIndex = 0; - for (var j = 0; j < 2; j++) + for (int j = 0; j < 2; j++) { - for (var i = 0; i < 5; i++) + for (int i = 0; i < 5; i++) { _joystickPressed[_pollIndex] = Controller.IsPressed(JoystickMatrix[j][i]); _pollIndex++; @@ -43,9 +43,9 @@ public void PollInput() // scan keyboard _pollIndex = 0; - for (var i = 0; i < 8; i++) + for (int i = 0; i < 8; i++) { - for (var j = 0; j < 8; j++) + for (int j = 0; j < 8; j++) { _keyboardPressed[_pollIndex++] = Controller.IsPressed(KeyboardMatrix[i][j]); } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.MotherboardInterface.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.MotherboardInterface.cs index 6db624e968f..2e481194ace 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.MotherboardInterface.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.MotherboardInterface.cs @@ -1,4 +1,4 @@ -namespace BizHawk.Emulation.Cores.Computers.Commodore64 +namespace BizHawk.Emulation.Cores.Computers.Commodore64 { public sealed partial class Motherboard { @@ -6,15 +6,9 @@ public sealed partial class Motherboard private int _lastReadVicData = 0xFF; private int _vicBank = 0xC000; - private bool CassPort_ReadDataOutput() - { - return (Cpu.PortData & 0x08) != 0; - } + private bool CassPort_ReadDataOutput() => (Cpu.PortData & 0x08) != 0; - private bool CassPort_ReadMotor() - { - return (Cpu.PortData & 0x20) != 0; - } + private bool CassPort_ReadMotor() => (Cpu.PortData & 0x20) != 0; private int Cia1_ReadPortA() { @@ -24,15 +18,15 @@ private int Cia1_ReadPortA() 0x3F; } - private int Cia1_ReadPortB() - { +#pragma warning disable IDE0051 + private int Cia1_ReadPortB() => // Ordinarily these are connected to the userport. - return 0x00; - } + 0x00; +#pragma warning restore IDE0051 private int Cpu_ReadPort() { - var data = 0x1F; + int data = 0x1F; if (!Cassette.ReadSenseBuffer()) { data &= 0xEF; @@ -41,39 +35,21 @@ private int Cpu_ReadPort() return data; } - private void Cpu_WriteMemoryPort(int addr) - { - Pla.WriteMemory(addr, ReadOpenBus()); - } + private void Cpu_WriteMemoryPort(int addr) => Pla.WriteMemory(addr, ReadOpenBus()); - private bool Glue_ReadIRQ() - { - return Cia0.ReadIrq() && Vic.ReadIrq() && CartPort.ReadIrq(); - } + private bool Glue_ReadIRQ() => Cia0.ReadIrq() && Vic.ReadIrq() && CartPort.ReadIrq(); - private bool Glue_ReadNMI() - { - return !_restorePressed && Cia1.ReadIrq() && CartPort.ReadNmi(); - } + private bool Glue_ReadNMI() => !_restorePressed && Cia1.ReadIrq() && CartPort.ReadNmi(); - private bool[] Input_ReadJoysticks() - { - return _joystickPressed; - } + private bool[] Input_ReadJoysticks() => _joystickPressed; - private bool[] Input_ReadKeyboard() - { - return _keyboardPressed; - } + private bool[] Input_ReadKeyboard() => _keyboardPressed; - private bool Pla_ReadCharen() - { - return (Cpu.PortData & 0x04) != 0; - } + private bool Pla_ReadCharen() => (Cpu.PortData & 0x04) != 0; private int Pla_ReadCia0(int addr) { - if (addr == 0xDC00 || addr == 0xDC01) + if (addr is 0xDC00 or 0xDC01) { InputRead = true; } @@ -82,59 +58,35 @@ private int Pla_ReadCia0(int addr) private int Pla_ReadColorRam(int addr) { - var result = ReadOpenBus(); + int result = ReadOpenBus(); result &= 0xF0; result |= ColorRam.Read(addr); return result; } - private bool Pla_ReadHiRam() - { - return (Cpu.PortData & 0x02) != 0; - } + private bool Pla_ReadHiRam() => (Cpu.PortData & 0x02) != 0; - private bool Pla_ReadLoRam() - { - return (Cpu.PortData & 0x01) != 0; - } + private bool Pla_ReadLoRam() => (Cpu.PortData & 0x01) != 0; - private int Pla_ReadExpansion0(int addr) - { - return CartPort.IsConnected ? CartPort.ReadLoExp(addr) : _lastReadVicData; - } + private int Pla_ReadExpansion0(int addr) => CartPort.IsConnected ? CartPort.ReadLoExp(addr) : _lastReadVicData; - private int Pla_ReadExpansion1(int addr) - { - return CartPort.IsConnected ? CartPort.ReadHiExp(addr) : _lastReadVicData; - } + private int Pla_ReadExpansion1(int addr) => CartPort.IsConnected ? CartPort.ReadHiExp(addr) : _lastReadVicData; - private bool SerPort_ReadAtnOut() - { + private bool SerPort_ReadAtnOut() => // inverted PA3 (input NOT pulled up) - return !((Cia1.DdrA & 0x08) != 0 && (Cia1.PrA & 0x08) != 0); - } + !((Cia1.DdrA & 0x08) != 0 && (Cia1.PrA & 0x08) != 0); - private bool SerPort_ReadClockOut() - { + private bool SerPort_ReadClockOut() => // inverted PA4 (input NOT pulled up) - return !((Cia1.DdrA & 0x10) != 0 && (Cia1.PrA & 0x10) != 0); - } + !((Cia1.DdrA & 0x10) != 0 && (Cia1.PrA & 0x10) != 0); - private bool SerPort_ReadDataOut() - { + private bool SerPort_ReadDataOut() => // inverted PA5 (input NOT pulled up) - return !((Cia1.DdrA & 0x20) != 0 && (Cia1.PrA & 0x20) != 0); - } + !((Cia1.DdrA & 0x20) != 0 && (Cia1.PrA & 0x20) != 0); - private int Sid_ReadPotX() - { - return 255; - } + private int Sid_ReadPotX() => 255; - private int Sid_ReadPotY() - { - return 255; - } + private int Sid_ReadPotY() => 255; private int Vic_ReadMemory(int addr) { @@ -144,9 +96,6 @@ private int Vic_ReadMemory(int addr) return _lastReadVicData; } - private int ReadOpenBus() - { - return _lastReadVicData; - } + private int ReadOpenBus() => _lastReadVicData; } } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.cs index 9cb55e5548f..a4d9fd81a73 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64.cs @@ -18,7 +18,7 @@ public C64(CoreLoadParameters lp) PutSyncSettings(lp.SyncSettings ?? new C64SyncSettings()); PutSettings(lp.Settings ?? new C64Settings()); - var ser = new BasicServiceProvider(this); + BasicServiceProvider ser = new(this); ServiceProvider = ser; CoreComm = lp.Comm; @@ -66,7 +66,7 @@ public C64(CoreLoadParameters lp) if (_board.CartPort.IsConnected) { - var first = _roms[0]; // There are no multi-cart cart games, so just hardcode first + byte[] first = _roms[0]; // There are no multi-cart cart games, so just hardcode first RomDetails = $"{lp.Game.Name}\r\n{SHA1Checksum.ComputePrefixedHex(first)}\r\n{MD5Checksum.ComputePrefixedHex(first)}\r\nMapper Impl \"{_board.CartPort.CartridgeType}\""; } @@ -97,7 +97,7 @@ private void RomSanityCheck() var formats = _roms.Select(C64FormatFinder.GetFormat); - HashSet uniqueFormats = new HashSet(); + HashSet uniqueFormats = new(); foreach (var format in formats) { @@ -218,7 +218,7 @@ public void SetDisk(int discNum) /**********************************************/ - private ISoundProvider _soundProvider; + private readonly ISoundProvider _soundProvider; private void DoCycle() { @@ -250,19 +250,14 @@ private void DoCycle() private byte[] GetFirmware(int length, params string[] names) { - var result = names.Select(n => CoreComm.CoreFileProvider.GetFirmware(new("C64", n))).FirstOrDefault(b => b != null && b.Length == length); - if (result == null) - { - throw new MissingFirmwareException($"At least one of these firmwares is required: {string.Join(", ", names)}"); - } - + byte[] result = names.Select(n => CoreComm.CoreFileProvider.GetFirmware(new("C64", n))).FirstOrDefault(b => b != null && b.Length == length) ?? throw new MissingFirmwareException($"At least one of these firmwares is required: {string.Join(", ", names)}"); return result; } private void Init(VicType initRegion, BorderType borderType, SidType sidType, TapeDriveType tapeDriveType, DiskDriveType diskDriveType) { // Force certain drive types to be available depending on ROM type - var rom = _roms[0]; + byte[] rom = _roms[0]; switch (C64FormatFinder.GetFormat(rom)) { @@ -326,14 +321,14 @@ private void InitMedia(byte[] rom) } break; case C64Format.CRT: - var cart = CartridgeDevice.Load(rom); + CartridgeDevice cart = CartridgeDevice.Load(rom); if (cart != null) { _board.CartPort.Connect(cart); } break; case C64Format.TAP: - var tape = Tape.Load(rom); + Tape tape = Tape.Load(rom); if (tape != null) { _board.TapeDrive.Insert(tape); @@ -380,14 +375,8 @@ private void InitRoms(DiskDriveType diskDriveType) } } - private void HardReset() - { - _board.HardReset(); - } + private void HardReset() => _board.HardReset(); - private void SoftReset() - { - _board.SoftReset(); - } + private void SoftReset() => _board.SoftReset(); } } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64FormatFinder.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64FormatFinder.cs index 9573e873713..6a19b023634 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64FormatFinder.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/C64FormatFinder.cs @@ -13,69 +13,67 @@ public static C64Format GetFormat(byte[] data) return C64Format.Unknown; } - using (var reader = new BinaryReader(new MemoryStream(data))) - { - var header = Encoding.GetEncoding(437).GetString(reader.ReadBytes(0x10)); + using BinaryReader reader = new(new MemoryStream(data)); + string header = Encoding.GetEncoding(437).GetString(reader.ReadBytes(0x10)); - if (header.StartsWithOrdinal("C64 CARTRIDGE ")) - { - return C64Format.CRT; - } + if (header.StartsWithOrdinal("C64 CARTRIDGE ")) + { + return C64Format.CRT; + } - if (header.StartsWithOrdinal("GCR-1541")) - { - return C64Format.G64; - } + if (header.StartsWithOrdinal("GCR-1541")) + { + return C64Format.G64; + } - if (header.StartsWithOrdinal("C64S tape image ") || header.StartsWithOrdinal("C64 tape image f")) - { - return C64Format.T64; - } + if (header.StartsWithOrdinal("C64S tape image ") || header.StartsWithOrdinal("C64 tape image f")) + { + return C64Format.T64; + } - if (header.StartsWithOrdinal("C64-TAPE-RAW")) - { - return C64Format.TAP; - } + if (header.StartsWithOrdinal("C64-TAPE-RAW")) + { + return C64Format.TAP; + } - if (header.StartsWithOrdinal("C64File")) - { - return C64Format.P00; // poo :) - } + if (header.StartsWithOrdinal("C64File")) + { + return C64Format.P00; // poo :) + } - if (header.StartsWithOrdinal("P64-1541")) - { - return C64Format.P64; - } + if (header.StartsWithOrdinal("P64-1541")) + { + return C64Format.P64; + } - if (data[0] == 0x43 && data[1] == 0x15 && data[2] == 0x41 && data[3] == 0x64) - { - return C64Format.X64; - } + if (data[0] == 0x43 && data[1] == 0x15 && data[2] == 0x41 && data[3] == 0x64) + { + return C64Format.X64; + } - if (data.Length == 174848 || data.Length == 175531 || data.Length == 196608 || data.Length == 197376) - { - return C64Format.D64; - } + if (data.Length is 174848 or 175531 or 196608 or 197376) + { + return C64Format.D64; + } - if (data.Length == 349696 || data.Length == 351062) - { - return C64Format.D71; - } + if (data.Length is 349696 or 351062) + { + return C64Format.D71; + } - if (data.Length == 533248) - { - return C64Format.D80; - } + if (data.Length == 533248) + { + return C64Format.D80; + } - if (data.Length == 819200 || data.Length == 822400) - { - return C64Format.D81; - } + if (data.Length is 819200 or 822400) + { + return C64Format.D81; + } - if (data.Length == 1066496) - { - return C64Format.D82; - } + if (data.Length == 1066496) + { + return C64Format.D82; } return C64Format.Unknown; diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/CartridgeDevice.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/CartridgeDevice.cs index 8590a1e4975..12817a715ef 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/CartridgeDevice.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/CartridgeDevice.cs @@ -13,24 +13,24 @@ public abstract class CartridgeDevice : IDriveLight public static CartridgeDevice Load(byte[] crtFile) { - using var mem = new MemoryStream(crtFile); - var reader = new BinaryReader(mem); + using MemoryStream mem = new(crtFile); + BinaryReader reader = new(mem); if (new string(reader.ReadChars(16)) != "C64 CARTRIDGE ") { return null; } - var chipAddress = new List(); - var chipBank = new List(); - var chipData = new List(); - var chipType = new List(); + List chipAddress = new(); + List chipBank = new(); + List chipData = new(); + List chipType = new(); - var headerLength = ReadCRTInt(reader); - var version = ReadCRTShort(reader); - var mapper = ReadCRTShort(reader); - var exrom = reader.ReadByte() != 0; - var game = reader.ReadByte() != 0; + int headerLength = ReadCRTInt(reader); + int version = ReadCRTShort(reader); + int mapper = ReadCRTShort(reader); + bool exrom = reader.ReadByte() != 0; + bool game = reader.ReadByte() != 0; // reserved reader.ReadBytes(6); @@ -52,11 +52,11 @@ public static CartridgeDevice Load(byte[] crtFile) break; } - var chipLength = ReadCRTInt(reader); + int chipLength = ReadCRTInt(reader); chipType.Add(ReadCRTShort(reader)); chipBank.Add(ReadCRTShort(reader)); chipAddress.Add(ReadCRTShort(reader)); - var chipDataLength = ReadCRTShort(reader); + int chipDataLength = ReadCRTShort(reader); chipData.Add(reader.ReadBytes(chipDataLength).Select(x => (int)x).ToArray()); chipLength -= chipDataLength + 0x10; if (chipLength > 0) @@ -70,51 +70,36 @@ public static CartridgeDevice Load(byte[] crtFile) return null; } - CartridgeDevice result; - switch (mapper) + CartridgeDevice result = mapper switch { - case 0x0000: // Standard Cartridge - result = new Mapper0000(chipAddress, chipData, game, exrom); - break; - case 0x0001: // Action Replay (4.2 and up) - result = new Mapper0001(chipAddress, chipBank, chipData); - break; - case 0x0005: // Ocean - result = new Mapper0005(chipAddress, chipBank, chipData); - break; - case 0x0007: // Fun Play - result = new Mapper0007(chipData, game, exrom); - break; - case 0x0008: // SuperGame - result = new Mapper0008(chipData); - break; - case 0x000A: // Epyx FastLoad - result = new Mapper000A(chipData); - break; - case 0x000B: // Westermann Learning - result = new Mapper000B(chipAddress, chipData); - break; - case 0x000F: // C64 Game System / System 3 - result = new Mapper000F(chipAddress, chipBank, chipData); - break; - case 0x0011: // Dinamic - result = new Mapper0011(chipAddress, chipBank, chipData); - break; - case 0x0012: // Zaxxon / Super Zaxxon - result = new Mapper0012(chipAddress, chipBank, chipData); - break; - case 0x0013: // Domark - result = new Mapper0013(chipAddress, chipBank, chipData); - break; - case 0x0020: // EasyFlash - result = new Mapper0020(chipAddress, chipBank, chipData); - break; - case 0x002B: // Prophet 64 - result = new Mapper002B(chipAddress, chipBank, chipData); - break; - default: - throw new Exception("This cartridge file uses an unrecognized mapper: " + mapper); - } + // Standard Cartridge + 0x0000 => new Mapper0000(chipAddress, chipData, game, exrom), + // Action Replay (4.2 and up) + 0x0001 => new Mapper0001(chipAddress, chipBank, chipData), + // Ocean + 0x0005 => new Mapper0005(chipAddress, chipBank, chipData), + // Fun Play + 0x0007 => new Mapper0007(chipData, game, exrom), + // SuperGame + 0x0008 => new Mapper0008(chipData), + // Epyx FastLoad + 0x000A => new Mapper000A(chipData), + // Westermann Learning + 0x000B => new Mapper000B(chipAddress, chipData), + // C64 Game System / System 3 + 0x000F => new Mapper000F(chipAddress, chipBank, chipData), + // Dinamic + 0x0011 => new Mapper0011(chipAddress, chipBank, chipData), + // Zaxxon / Super Zaxxon + 0x0012 => new Mapper0012(chipAddress, chipBank, chipData), + // Domark + 0x0013 => new Mapper0013(chipAddress, chipBank, chipData), + // EasyFlash + 0x0020 => new Mapper0020(chipAddress, chipBank, chipData), + // Prophet 64 + 0x002B => new Mapper002B(chipAddress, chipBank, chipData), + _ => throw new Exception("This cartridge file uses an unrecognized mapper: " + mapper), + }; result.HardReset(); return result; @@ -165,25 +150,13 @@ public virtual void HardReset() public bool NMI => pinNMI; - public virtual int Peek8000(int addr) - { - return ReadOpenBus(); - } + public virtual int Peek8000(int addr) => ReadOpenBus(); - public virtual int PeekA000(int addr) - { - return ReadOpenBus(); - } + public virtual int PeekA000(int addr) => ReadOpenBus(); - public virtual int PeekDE00(int addr) - { - return ReadOpenBus(); - } + public virtual int PeekDE00(int addr) => ReadOpenBus(); - public virtual int PeekDF00(int addr) - { - return ReadOpenBus(); - } + public virtual int PeekDF00(int addr) => ReadOpenBus(); public virtual void Poke8000(int addr, int val) { @@ -201,25 +174,13 @@ public virtual void PokeDF00(int addr, int val) { } - public virtual int Read8000(int addr) - { - return ReadOpenBus(); - } + public virtual int Read8000(int addr) => ReadOpenBus(); - public virtual int ReadA000(int addr) - { - return ReadOpenBus(); - } + public virtual int ReadA000(int addr) => ReadOpenBus(); - public virtual int ReadDE00(int addr) - { - return ReadOpenBus(); - } + public virtual int ReadDE00(int addr) => ReadOpenBus(); - public virtual int ReadDF00(int addr) - { - return ReadOpenBus(); - } + public virtual int ReadDF00(int addr) => ReadOpenBus(); public bool Reset => pinReset; diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/CartridgePort.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/CartridgePort.cs index 055f1fe0afd..57ddd537f42 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/CartridgePort.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/CartridgePort.cs @@ -21,60 +21,30 @@ public CartridgePort() // ------------------------------------------ - public int PeekHiExp(int addr) - { - return _connected ? _cartridgeDevice.PeekDF00(addr & 0x00FF) : 0xFF; - } + public int PeekHiExp(int addr) => _connected ? _cartridgeDevice.PeekDF00(addr & 0x00FF) : 0xFF; - public int PeekHiRom(int addr) - { - return _connected ? _cartridgeDevice.PeekA000(addr & 0x1FFF) : 0xFF; - } + public int PeekHiRom(int addr) => _connected ? _cartridgeDevice.PeekA000(addr & 0x1FFF) : 0xFF; - public int PeekLoExp(int addr) - { - return _connected ? _cartridgeDevice.PeekDE00(addr & 0x00FF) : 0xFF; - } + public int PeekLoExp(int addr) => _connected ? _cartridgeDevice.PeekDE00(addr & 0x00FF) : 0xFF; - public int PeekLoRom(int addr) - { - return _connected ? _cartridgeDevice.Peek8000(addr & 0x1FFF) : 0xFF; - } + public int PeekLoRom(int addr) => _connected ? _cartridgeDevice.Peek8000(addr & 0x1FFF) : 0xFF; public void PokeHiExp(int addr, int val) { if (_connected) { _cartridgeDevice.PokeDF00(addr & 0x00FF, val); } } public void PokeHiRom(int addr, int val) { if (_connected) { _cartridgeDevice.PokeA000(addr & 0x1FFF, val); } } public void PokeLoExp(int addr, int val) { if (_connected) { _cartridgeDevice.PokeDE00(addr & 0x00FF, val); } } public void PokeLoRom(int addr, int val) { if (_connected) { _cartridgeDevice.Poke8000(addr & 0x1FFF, val); } } - public bool ReadExRom() - { - return !_connected || _cartridgeDevice.ExRom; - } + public bool ReadExRom() => !_connected || _cartridgeDevice.ExRom; - public bool ReadGame() - { - return !_connected || _cartridgeDevice.Game; - } + public bool ReadGame() => !_connected || _cartridgeDevice.Game; - public int ReadHiExp(int addr) - { - return _connected ? _cartridgeDevice.ReadDF00(addr & 0x00FF) : 0xFF; - } + public int ReadHiExp(int addr) => _connected ? _cartridgeDevice.ReadDF00(addr & 0x00FF) : 0xFF; - public int ReadHiRom(int addr) - { - return _connected ? _cartridgeDevice.ReadA000(addr & 0x1FFF) : 0xFF; - } + public int ReadHiRom(int addr) => _connected ? _cartridgeDevice.ReadA000(addr & 0x1FFF) : 0xFF; - public int ReadLoExp(int addr) - { - return _connected ? _cartridgeDevice.ReadDE00(addr & 0x00FF) : 0xFF; - } + public int ReadLoExp(int addr) => _connected ? _cartridgeDevice.ReadDE00(addr & 0x00FF) : 0xFF; - public int ReadLoRom(int addr) - { - return _connected ? _cartridgeDevice.Read8000(addr & 0x1FFF) : 0xFF; - } + public int ReadLoRom(int addr) => _connected ? _cartridgeDevice.Read8000(addr & 0x1FFF) : 0xFF; public void WriteHiExp(int addr, int val) { if (_connected) { _cartridgeDevice.WriteDF00(addr & 0x00FF, val); } } public void WriteHiRom(int addr, int val) { if (_connected) { _cartridgeDevice.WriteA000(addr & 0x1FFF, val); } } @@ -115,15 +85,9 @@ public void HardReset() public bool IsConnected => _connected; - public bool ReadIrq() - { - return !_connected || _cartridgeDevice.IRQ; - } + public bool ReadIrq() => !_connected || _cartridgeDevice.IRQ; - public bool ReadNmi() - { - return !_connected || _cartridgeDevice.NMI; - } + public bool ReadNmi() => !_connected || _cartridgeDevice.NMI; public void SyncState(Serializer ser) { diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0000.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0000.cs index 8954ace31d3..271d13e2c3e 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0000.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0000.cs @@ -27,7 +27,7 @@ public Mapper0000(IList newAddresses, IList newData, bool game, bool _romA[0] = 0xFF; _romB[0] = 0xFF; - for (var i = 0; i < newAddresses.Count; i++) + for (int i = 0; i < newAddresses.Count; i++) { if (newAddresses[i] == 0x8000) { @@ -56,7 +56,7 @@ public Mapper0000(IList newAddresses, IList newData, bool game, bool return; } } - else if (newAddresses[i] == 0xA000 || newAddresses[i] == 0xE000) + else if (newAddresses[i] is 0xA000 or 0xE000) { switch (newData[i].Length) { @@ -82,24 +82,12 @@ protected override void SyncStateInternal(Serializer ser) ser.Sync("RomMaskB", ref _romBMask); } - public override int Peek8000(int addr) - { - return _romA[addr & _romAMask]; - } + public override int Peek8000(int addr) => _romA[addr & _romAMask]; - public override int PeekA000(int addr) - { - return _romB[addr & _romBMask]; - } + public override int PeekA000(int addr) => _romB[addr & _romBMask]; - public override int Read8000(int addr) - { - return _romA[addr & _romAMask]; - } + public override int Read8000(int addr) => _romA[addr & _romAMask]; - public override int ReadA000(int addr) - { - return _romB[addr & _romBMask]; - } + public override int ReadA000(int addr) => _romB[addr & _romBMask]; } } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0001.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0001.cs index a7d662796fb..e9b17c1ba32 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0001.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0001.cs @@ -19,7 +19,7 @@ public Mapper0001(IList newAddresses, IList newBanks, IList new { pinExRom = false; pinGame = false; - for (var i = 0; i < newData.Count; i++) + for (int i = 0; i < newData.Count; i++) { if (newAddresses[i] == 0x8000) { @@ -44,7 +44,7 @@ public override void HardReset() base.HardReset(); pinExRom = false; pinGame = false; - for (var i = 0; i < 0x2000; i++) + for (int i = 0; i < 0x2000; i++) { _ram[i] = 0x00; } @@ -53,75 +53,33 @@ public override void HardReset() _cartEnabled = true; } - public override int Peek8000(int addr) - { - return GetLoRom(addr); - } + public override int Peek8000(int addr) => GetLoRom(addr); - public override int PeekA000(int addr) - { - return Peek8000(addr); - } + public override int PeekA000(int addr) => Peek8000(addr); - public override int PeekDF00(int addr) - { - return GetIo2(addr); - } + public override int PeekDF00(int addr) => GetIo2(addr); - public override void Poke8000(int addr, int val) - { - SetLoRom(addr, val); - } + public override void Poke8000(int addr, int val) => SetLoRom(addr, val); - public override void PokeA000(int addr, int val) - { - Poke8000(addr, val); - } + public override void PokeA000(int addr, int val) => Poke8000(addr, val); - public override void PokeDE00(int addr, int val) - { - SetState(val); - } + public override void PokeDE00(int addr, int val) => SetState(val); - public override void PokeDF00(int addr, int val) - { - SetIo2(addr, val); - } + public override void PokeDF00(int addr, int val) => SetIo2(addr, val); - public override int Read8000(int addr) - { - return GetLoRom(addr); - } + public override int Read8000(int addr) => GetLoRom(addr); - public override int ReadA000(int addr) - { - return GetHiRom(addr); - } + public override int ReadA000(int addr) => GetHiRom(addr); - public override int ReadDF00(int addr) - { - return GetIo2(addr); - } + public override int ReadDF00(int addr) => GetIo2(addr); - public override void Write8000(int addr, int val) - { - SetLoRom(addr, val); - } + public override void Write8000(int addr, int val) => SetLoRom(addr, val); - public override void WriteA000(int addr, int val) - { - SetLoRom(addr, val); - } + public override void WriteA000(int addr, int val) => SetLoRom(addr, val); - public override void WriteDE00(int addr, int val) - { - SetState(val); - } + public override void WriteDE00(int addr, int val) => SetState(val); - public override void WriteDF00(int addr, int val) - { - SetIo2(addr, val); - } + public override void WriteDF00(int addr, int val) => SetIo2(addr, val); private void SetState(int val) { @@ -139,15 +97,9 @@ private int GetLoRom(int addr) : _rom[(addr & 0x1FFF) | _romOffset]; } - private int GetHiRom(int addr) - { - return _rom[(addr & 0x1FFF) | _romOffset]; - } + private int GetHiRom(int addr) => _rom[(addr & 0x1FFF) | _romOffset]; - private void SetLoRom(int addr, int val) - { - _ram[addr & 0x1FFF] = val; - } + private void SetLoRom(int addr, int val) => _ram[addr & 0x1FFF] = val; private int GetIo2(int addr) { @@ -161,9 +113,6 @@ private int GetIo2(int addr) : _rom[(addr & 0xFF) | _romOffset | 0x1F00]; } - private void SetIo2(int addr, int val) - { - _ram[addr & 0x1FFF] = val & 0xFF; - } + private void SetIo2(int addr, int val) => _ram[addr & 0x1FFF] = val & 0xFF; } } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0005.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0005.cs index 1fa7e798769..7ac0e848985 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0005.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0005.cs @@ -23,11 +23,11 @@ internal sealed class Mapper0005 : CartridgeDevice public Mapper0005(IList newAddresses, IList newBanks, IList newData) { - var count = newAddresses.Count; + int count = newAddresses.Count; // build dummy bank _dummyBank = new int[0x2000]; - for (var i = 0; i < 0x2000; i++) + for (int i = 0; i < 0x2000; i++) { _dummyBank[i] = 0xFF; // todo: determine if this is correct } @@ -83,18 +83,18 @@ public Mapper0005(IList newAddresses, IList newBanks, IList new } // for safety, initialize all banks to dummy - for (var i = 0; i < _banksA.Length; i++) + for (int i = 0; i < _banksA.Length; i++) { _banksA[i] = _dummyBank; } - for (var i = 0; i < _banksB.Length; i++) + for (int i = 0; i < _banksB.Length; i++) { _banksB[i] = _dummyBank; } // now load in the banks - for (var i = 0; i < count; i++) + for (int i = 0; i < count; i++) { switch (newAddresses[i]) { @@ -129,15 +129,9 @@ private void BankSet(int index) _currentBankB = !pinGame ? _banksB[_bankNumber] : _dummyBank; } - public override int Peek8000(int addr) - { - return _currentBankA[addr]; - } + public override int Peek8000(int addr) => _currentBankA[addr]; - public override int PeekA000(int addr) - { - return _currentBankB[addr]; - } + public override int PeekA000(int addr) => _currentBankB[addr]; public override void PokeDE00(int addr, int val) { @@ -147,15 +141,9 @@ public override void PokeDE00(int addr, int val) } } - public override int Read8000(int addr) - { - return _currentBankA[addr]; - } + public override int Read8000(int addr) => _currentBankA[addr]; - public override int ReadA000(int addr) - { - return _currentBankB[addr]; - } + public override int ReadA000(int addr) => _currentBankB[addr]; public override void WriteDE00(int addr, int val) { diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0007.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0007.cs index 69281d9a480..6a90f34c83f 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0007.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0007.cs @@ -20,9 +20,9 @@ public Mapper0007(IList newData, bool game, bool exrom) _disabled = false; // load data into the banks from the list - for (var j = 0; j < 16; j++) + for (int j = 0; j < 16; j++) { - for (var i = 0; i < 0x2000; i++) + for (int i = 0; i < 0x2000; i++) { _banks[j, i] = newData[j][i]; } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0008.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0008.cs index 299d73d5c36..49fa4b1f7fb 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0008.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0008.cs @@ -24,9 +24,9 @@ public Mapper0008(IList newData) _latchedval = 0; // load data into the banks from the list - for (var j = 0; j < 4; j++) + for (int j = 0; j < 4; j++) { - for (var i = 0; i < 0x4000; i++) + for (int i = 0; i < 0x4000; i++) { _banks[j, i] = newData[j][i]; } @@ -60,15 +60,9 @@ private void BankSet(int index) } } - public override int Peek8000(int addr) - { - return _banks[_bankNumber, addr]; - } + public override int Peek8000(int addr) => _banks[_bankNumber, addr]; - public override int PeekA000(int addr) - { - return _banks[_bankNumber, addr + 0x2000]; - } + public override int PeekA000(int addr) => _banks[_bankNumber, addr + 0x2000]; public override void PokeDF00(int addr, int val) { @@ -78,15 +72,9 @@ public override void PokeDF00(int addr, int val) } } - public override int Read8000(int addr) - { - return _banks[_bankNumber, addr]; - } + public override int Read8000(int addr) => _banks[_bankNumber, addr]; - public override int ReadA000(int addr) - { - return _banks[_bankNumber, addr + 0x2000]; - } + public override int ReadA000(int addr) => _banks[_bankNumber, addr + 0x2000]; public override void WriteDF00(int addr, int val) { @@ -96,9 +84,6 @@ public override void WriteDF00(int addr, int val) } } - public override int ReadDF00(int addr) - { - return _latchedval; - } + public override int ReadDF00(int addr) => _latchedval; } } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper000A.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper000A.cs index 7916a457654..6d693ce0dd6 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper000A.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper000A.cs @@ -26,10 +26,7 @@ public Mapper000A(IList newData) pinGame = true; } - protected override void SyncStateInternal(Serializer ser) - { - ser.Sync("CapacitorCycles", ref _capacitorCycles); - } + protected override void SyncStateInternal(Serializer ser) => ser.Sync("CapacitorCycles", ref _capacitorCycles); public override void ExecutePhase() { @@ -46,20 +43,11 @@ public override void HardReset() base.HardReset(); } - public override int Peek8000(int addr) - { - return _rom[addr & 0x1FFF]; - } + public override int Peek8000(int addr) => _rom[addr & 0x1FFF]; - public override int PeekDE00(int addr) - { - return 0x00; - } + public override int PeekDE00(int addr) => 0x00; - public override int PeekDF00(int addr) - { - return _rom[(addr & 0xFF) | 0x1F00]; - } + public override int PeekDF00(int addr) => _rom[(addr & 0xFF) | 0x1F00]; public override int Read8000(int addr) { @@ -73,9 +61,6 @@ public override int ReadDE00(int addr) return 0x00; } - public override int ReadDF00(int addr) - { - return _rom[(addr & 0xFF) | 0x1F00]; - } + public override int ReadDF00(int addr) => _rom[(addr & 0xFF) | 0x1F00]; } } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper000B.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper000B.cs index 9adbd5406d2..84e194a1fa2 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper000B.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper000B.cs @@ -19,7 +19,7 @@ public Mapper000B(IList newAddresses, IList newData) { validCartridge = false; - for (var i = 0; i < 0x4000; i++) + for (int i = 0; i < 0x4000; i++) { _rom[i] = 0xFF; } @@ -38,25 +38,13 @@ protected override void SyncStateInternal(Serializer ser) // Nothing to save } - public override int Peek8000(int addr) - { - return _rom[addr]; - } + public override int Peek8000(int addr) => _rom[addr]; - public override int PeekA000(int addr) - { - return _rom[addr | 0x2000]; - } + public override int PeekA000(int addr) => _rom[addr | 0x2000]; - public override int Read8000(int addr) - { - return _rom[addr]; - } + public override int Read8000(int addr) => _rom[addr]; - public override int ReadA000(int addr) - { - return _rom[addr | 0x2000]; - } + public override int ReadA000(int addr) => _rom[addr | 0x2000]; public override int ReadDF00(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper000F.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper000F.cs index 2d8090a96f8..c84086bf4dd 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper000F.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper000F.cs @@ -22,14 +22,14 @@ internal class Mapper000F : CartridgeDevice public Mapper000F(IList newAddresses, IList newBanks, IList newData) { - var count = newAddresses.Count; + int count = newAddresses.Count; pinGame = true; pinExRom = false; // build dummy bank - var dummyBank = new int[0x2000]; - for (var i = 0; i < 0x2000; i++) + int[] dummyBank = new int[0x2000]; + for (int i = 0; i < 0x2000; i++) { dummyBank[i] = 0xFF; // todo: determine if this is correct } @@ -69,13 +69,13 @@ public Mapper000F(IList newAddresses, IList newBanks, IList new } // for safety, initialize all banks to dummy - for (var i = 0; i < _banks.Length; i++) + for (int i = 0; i < _banks.Length; i++) { _banks[i] = dummyBank; } // now load in the banks - for (var i = 0; i < count; i++) + for (int i = 0; i < count; i++) { if (newAddresses[i] == 0x8000) { @@ -103,25 +103,13 @@ protected void BankSet(int index) UpdateState(); } - public override int Peek8000(int addr) - { - return _currentBank[addr]; - } + public override int Peek8000(int addr) => _currentBank[addr]; - public override void PokeDE00(int addr, int val) - { - BankSet(addr); - } + public override void PokeDE00(int addr, int val) => BankSet(addr); - public override int Read8000(int addr) - { - return _currentBank[addr]; - } + public override int Read8000(int addr) => _currentBank[addr]; - private void UpdateState() - { - _currentBank = _banks[_bankNumber]; - } + private void UpdateState() => _currentBank = _banks[_bankNumber]; public override int ReadDE00(int addr) { @@ -130,9 +118,6 @@ public override int ReadDE00(int addr) return 0; } - public override void WriteDE00(int addr, int val) - { - BankSet(addr); - } + public override void WriteDE00(int addr, int val) => BankSet(addr); } } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0012.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0012.cs index 22783696fa4..12d8bd54e68 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0012.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0012.cs @@ -22,10 +22,10 @@ public Mapper0012(IList newAddresses, IList newBanks, IList new { _bankMain = new int[0x2000]; _bankHigh = new int[2][]; - var dummyBank = new int[0x2000]; + int[] dummyBank = new int[0x2000]; // create dummy bank just in case - for (var i = 0; i < 0x2000; i++) + for (int i = 0; i < 0x2000; i++) { dummyBank[i] = 0xFF; } @@ -34,7 +34,7 @@ public Mapper0012(IList newAddresses, IList newBanks, IList new _bankHigh[1] = dummyBank; // load in the banks - for (var i = 0; i < newAddresses.Count; i++) + for (int i = 0; i < newAddresses.Count; i++) { if (newAddresses[i] == 0x8000) { @@ -63,15 +63,9 @@ protected override void SyncStateInternal(Serializer ser) } } - public override int Peek8000(int addr) - { - return _bankMain[addr]; - } + public override int Peek8000(int addr) => _bankMain[addr]; - public override int PeekA000(int addr) - { - return _bankHighSelected[addr]; - } + public override int PeekA000(int addr) => _bankHighSelected[addr]; public override int Read8000(int addr) { @@ -80,9 +74,6 @@ public override int Read8000(int addr) return _bankMain[addr]; } - public override int ReadA000(int addr) - { - return _bankHighSelected[addr]; - } + public override int ReadA000(int addr) => _bankHighSelected[addr]; } } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0013.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0013.cs index 19fce67c3e5..57b846f0fb0 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0013.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0013.cs @@ -25,15 +25,15 @@ internal sealed class Mapper0013 : CartridgeDevice public Mapper0013(IList newAddresses, IList newBanks, IList newData) { - var count = newAddresses.Count; + int count = newAddresses.Count; pinGame = true; pinExRom = false; _romEnable = true; // build dummy bank - var dummyBank = new int[0x2000]; - for (var i = 0; i < 0x2000; i++) + int[] dummyBank = new int[0x2000]; + for (int i = 0; i < 0x2000; i++) { dummyBank[i] = 0xFF; // todo: determine if this is correct } @@ -57,13 +57,13 @@ public Mapper0013(IList newAddresses, IList newBanks, IList new } // for safety, initialize all banks to dummy - for (var i = 0; i < _banks.Length; i++) + for (int i = 0; i < _banks.Length; i++) { _banks[i] = dummyBank; } // now load in the banks - for (var i = 0; i < count; i++) + for (int i = 0; i < count; i++) { if (newAddresses[i] == 0x8000) { @@ -93,10 +93,7 @@ private void BankSet(int index) UpdateState(); } - public override int Peek8000(int addr) - { - return _currentBank[addr]; - } + public override int Peek8000(int addr) => _currentBank[addr]; public override void PokeDE00(int addr, int val) { @@ -106,10 +103,7 @@ public override void PokeDE00(int addr, int val) } } - public override int Read8000(int addr) - { - return _currentBank[addr]; - } + public override int Read8000(int addr) => _currentBank[addr]; private void UpdateState() { diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0020.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0020.cs index 2ff0806bfec..5267c576721 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0020.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper0020.cs @@ -26,8 +26,8 @@ internal sealed class Mapper0020 : CartridgeDevice { private int _bankOffset = 63 << 13; - private int[] _banksA = new int[64 << 13]; // 8000 - private int[] _banksB = new int[64 << 13]; // A000 + private readonly int[] _banksA = new int[64 << 13]; // 8000 + private readonly int[] _banksB = new int[64 << 13]; // A000 private readonly int[] _originalMediaA; // 8000 private readonly int[] _originalMediaB; // A000 @@ -48,7 +48,7 @@ internal sealed class Mapper0020 : CartridgeDevice public Mapper0020(IList newAddresses, IList newBanks, IList newData) { DriveLightEnabled = true; - var count = newAddresses.Count; + int count = newAddresses.Count; // force ultimax mode (the cart SHOULD set this // otherwise on load, according to the docs) @@ -56,14 +56,14 @@ public Mapper0020(IList newAddresses, IList newBanks, IList new pinExRom = true; // for safety, initialize all banks to dummy - for (var i = 0; i < 64 * 0x2000; i++) + for (int i = 0; i < 64 * 0x2000; i++) { _banksA[i] = 0xFF; _banksB[i] = 0xFF; } // load in all banks - for (var i = 0; i < count; i++) + for (int i = 0; i < count; i++) { switch (newAddresses[i]) { @@ -105,10 +105,7 @@ protected override void SyncStateInternal(Serializer ser) DriveLightOn = _boardLed; } - private void BankSet(int index) - { - _bankOffset = (index & 0x3F) << 13; - } + private void BankSet(int index) => _bankOffset = (index & 0x3F) << 13; public override int Peek8000(int addr) { @@ -156,15 +153,9 @@ public override void PokeDF00(int addr, int val) _ram[addr] = val & 0xFF; } - public override int Read8000(int addr) - { - return ReadInternal(addr & 0x1FFF, _banksA); - } + public override int Read8000(int addr) => ReadInternal(addr & 0x1FFF, _banksA); - public override int ReadA000(int addr) - { - return ReadInternal(addr & 0x1FFF, _banksB); - } + public override int ReadA000(int addr) => ReadInternal(addr & 0x1FFF, _banksB); public override int ReadDF00(int addr) { @@ -217,15 +208,9 @@ private void StateSet(int val) DriveLightOn = _boardLed; } - public override void Write8000(int addr, int val) - { - WriteInternal(addr, val); - } + public override void Write8000(int addr, int val) => WriteInternal(addr, val); - public override void WriteA000(int addr, int val) - { - WriteInternal(addr | 0x2000, val); - } + public override void WriteA000(int addr, int val) => WriteInternal(addr | 0x2000, val); private void WriteInternal(int addr, int val) { @@ -240,7 +225,7 @@ private void WriteInternal(int addr, int val) _commandLatch55 = false; _commandLatchAa = false; } - else if (_internalRomState != 0x00 && _internalRomState != 0xF0) + else if (_internalRomState is not 0x00 and not 0xF0) { switch (_internalRomState) { @@ -305,9 +290,6 @@ public override void WriteDE00(int addr, int val) } } - public override void WriteDF00(int addr, int val) - { - _ram[addr] = val & 0xFF; - } + public override void WriteDF00(int addr, int val) => _ram[addr] = val & 0xFF; } } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper002B.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper002B.cs index 8d733d9fcca..0ec613f1412 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper002B.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cartridge/Mapper002B.cs @@ -24,7 +24,7 @@ public Mapper002B(IList newAddresses, IList newBanks, IList new _rom = new int[0x40000]; Array.Copy(newData.First(), _rom, 0x2000); pinGame = true; - for (var i = 0; i < newData.Count; i++) + for (int i = 0; i < newData.Count; i++) { if (newAddresses[i] == 0x8000) { @@ -45,16 +45,11 @@ public override void HardReset() _romOffset = 0; } - public override int Peek8000(int addr) - { - return _romOffset | (addr & 0x1FFF); - } + public override int Peek8000(int addr) => _romOffset | (addr & 0x1FFF); - public override int PeekDF00(int addr) - { + public override int PeekDF00(int addr) => // For debugging only. The processor does not see this. - return ((_romOffset >> 13) & 0x1F) | (_romEnabled ? 0x20 : 0x00); - } + ((_romOffset >> 13) & 0x1F) | (_romEnabled ? 0x20 : 0x00); public override void PokeDF00(int addr, int val) { @@ -62,15 +57,9 @@ public override void PokeDF00(int addr, int val) _romEnabled = (val & 0x20) != 0; } - public override int Read8000(int addr) - { - return _romOffset | (addr & 0x1FFF); - } + public override int Read8000(int addr) => _romOffset | (addr & 0x1FFF); - public override int ReadDF00(int addr) - { - return 0x00; - } + public override int ReadDF00(int addr) => 0x00; public override void WriteDF00(int addr, int val) { diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cassette/CassettePort.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cassette/CassettePort.cs index 9e7be9a88fa..e0caf91f704 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cassette/CassettePort.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cassette/CassettePort.cs @@ -28,15 +28,9 @@ public void ExecutePhase() } } - public bool ReadDataInputBuffer() - { - return !_connected || _device.ReadDataInputBuffer(); - } + public bool ReadDataInputBuffer() => !_connected || _device.ReadDataInputBuffer(); - public bool ReadSenseBuffer() - { - return !_connected || _device.ReadSenseBuffer(); - } + public bool ReadSenseBuffer() => !_connected || _device.ReadSenseBuffer(); public void SyncState(Serializer ser) { diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cassette/CassettePortDevice.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cassette/CassettePortDevice.cs index 4039e5c9132..1eff82421fb 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cassette/CassettePortDevice.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cassette/CassettePortDevice.cs @@ -16,15 +16,9 @@ public virtual void HardReset() { } - public virtual bool ReadDataInputBuffer() - { - return true; - } + public virtual bool ReadDataInputBuffer() => true; - public virtual bool ReadSenseBuffer() - { - return true; - } + public virtual bool ReadSenseBuffer() => true; public abstract void SyncState(Serializer ser); diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cassette/TapeDrive.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cassette/TapeDrive.cs index 97c30f9fe07..47b516a1de7 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cassette/TapeDrive.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Cassette/TapeDrive.cs @@ -15,35 +15,17 @@ public override void ExecutePhase2() } } - public override void HardReset() - { - _tape?.Rewind(); - } + public override void HardReset() => _tape?.Rewind(); - public override bool ReadDataInputBuffer() - { - return _tape == null || _tape.Read(); - } + public override bool ReadDataInputBuffer() => _tape == null || _tape.Read(); - public override bool ReadSenseBuffer() - { - return _tape == null; - } + public override bool ReadSenseBuffer() => _tape == null; - public override void SyncState(Serializer ser) - { - _tape?.SyncState(ser); - } + public override void SyncState(Serializer ser) => _tape?.SyncState(ser); - public void Insert(Tape tape) - { - _tape = tape; - } + public void Insert(Tape tape) => _tape = tape; - public void RemoveMedia() - { - _tape = null; - } + public void RemoveMedia() => _tape = null; // Exposed for memory domains, should not be used for actual emulation implementation public override byte[] TapeDataDomain => _tape?.TapeDataDomain; diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/FFT.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/FFT.cs index b87c8f5b384..020691e5429 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/FFT.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/FFT.cs @@ -32,15 +32,9 @@ public RealFFT(int length) CorrectionScaleFactor = 1.0 / (ForwardScaleFactor * ReverseScaleFactor); } - public void ComputeForward(double[] buff) - { - Compute(buff, false); - } + public void ComputeForward(double[] buff) => Compute(buff, false); - public void ComputeReverse(double[] buff) - { - Compute(buff, true); - } + public void ComputeReverse(double[] buff) => Compute(buff, true); private void Compute(double[] buff, bool reverse) { diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip2114.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip2114.cs index 82ed244d69e..13a6180f3d7 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip2114.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip2114.cs @@ -14,40 +14,22 @@ public Chip2114() public void HardReset() { - for (var i = 0; i < 0x400; i++) + for (int i = 0; i < 0x400; i++) { _ram[i] = 0x0; } } - public int Peek(int addr) - { - return _ram[addr & 0x3FF]; - } + public int Peek(int addr) => _ram[addr & 0x3FF]; - public void Poke(int addr, int val) - { - _ram[addr & 0x3FF] = val & 0xF; - } + public void Poke(int addr, int val) => _ram[addr & 0x3FF] = val & 0xF; - public int Read(int addr) - { - return _ram[addr & 0x3FF]; - } + public int Read(int addr) => _ram[addr & 0x3FF]; - public int ReadInt(int addr) - { - return _ram[addr & 0x3FF]; - } + public int ReadInt(int addr) => _ram[addr & 0x3FF]; - public void SyncState(Serializer ser) - { - ser.Sync(nameof(_ram), ref _ram, useNull: false); - } + public void SyncState(Serializer ser) => ser.Sync(nameof(_ram), ref _ram, useNull: false); - public void Write(int addr, int val) - { - _ram[addr & 0x3FF] = val & 0xF; - } + public void Write(int addr, int val) => _ram[addr & 0x3FF] = val & 0xF; } } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip23128.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip23128.cs index 5772386af1e..203f7912acb 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip23128.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip23128.cs @@ -20,20 +20,14 @@ public Chip23128(byte[] data) : this() public void Flash(byte[] data) { // ensures ROM is mirrored - for (var i = 0; i < _rom.Length; i += data.Length) + for (int i = 0; i < _rom.Length; i += data.Length) { Array.Copy(data, 0, _rom, i, data.Length); } } - public int Peek(int addr) - { - return _rom[addr & 0x3FFF]; - } + public int Peek(int addr) => _rom[addr & 0x3FFF]; - public int Read(int addr) - { - return _rom[addr & 0x3FFF]; - } + public int Read(int addr) => _rom[addr & 0x3FFF]; } } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip4864.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip4864.cs index 78367804a77..41ccc5b5539 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip4864.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip4864.cs @@ -25,35 +25,20 @@ public Chip4864() public void HardReset() { // stripe the ram - for (var i = 0; i < 10000; i++) + for (int i = 0; i < 10000; i++) { _ram[i] = (i & 0x40) != 0 ? 0xFF : 0x00; } } - public int Peek(int addr) - { - return _ram[addr]; - } + public int Peek(int addr) => _ram[addr]; - public void Poke(int addr, int val) - { - _ram[addr] = val; - } + public void Poke(int addr, int val) => _ram[addr] = val; - public int Read(int addr) - { - return _ram[addr]; - } + public int Read(int addr) => _ram[addr]; - public void SyncState(Serializer ser) - { - ser.Sync(nameof(_ram), ref _ram, useNull: false); - } + public void SyncState(Serializer ser) => ser.Sync(nameof(_ram), ref _ram, useNull: false); - public void Write(int addr, int val) - { - _ram[addr] = val; - } + public void Write(int addr, int val) => _ram[addr] = val; } } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6510.IDebuggable.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6510.IDebuggable.cs index a35ee6f9961..7d190c12480 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6510.IDebuggable.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6510.IDebuggable.cs @@ -11,15 +11,11 @@ public sealed partial class Chip6510 : IDebuggable bool IDebuggable.CanStep(StepType type) { - switch (type) + return type switch { - case StepType.Into: - case StepType.Over: - case StepType.Out: - return DebuggerStep != null; - default: - return false; - } + StepType.Into or StepType.Over or StepType.Out => DebuggerStep != null, + _ => false, + }; } void IDebuggable.Step(StepType type) @@ -55,11 +51,11 @@ private void StepInto() private void StepOver() { - var instruction = Peek(_cpu.PC); + int instruction = Peek(_cpu.PC); if (instruction == Jsr) { - var destination = _cpu.PC + JsrSize; + int destination = _cpu.PC + JsrSize; while (_cpu.PC != destination) { StepInto(); @@ -73,8 +69,8 @@ private void StepOver() private void StepOut() { - var instructionsBeforeBailout = 1000000; - var instr = Peek(_cpu.PC); + int instructionsBeforeBailout = 1000000; + int instr = Peek(_cpu.PC); _jsrCount = instr == Jsr ? 1 : 0; while (--instructionsBeforeBailout > 0) @@ -91,7 +87,7 @@ private void StepOut() _jsrCount = 0; break; } - else if (instr == Rts || instr == Rti) + else if (instr is Rts or Rti) { _jsrCount--; } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6510.IDisassemblable.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6510.IDisassemblable.cs index 6ccfc9f3f7e..9246d185438 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6510.IDisassemblable.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6510.IDisassemblable.cs @@ -21,9 +21,6 @@ public string Cpu public string PCRegisterName => "PC"; - public string Disassemble(MemoryDomain m, uint addr, out int length) - { - return MOS6502X.Disassemble((ushort) addr, out length, a => unchecked((byte) Peek(a))); - } + public string Disassemble(MemoryDomain m, uint addr, out int length) => MOS6502X.Disassemble((ushort)addr, out length, a => unchecked((byte)Peek(a))); } } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6510.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6510.cs index b2b342c286b..3991b73b728 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6510.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6510.cs @@ -16,7 +16,7 @@ public sealed partial class Chip6510 private int _nmiDelay; public C64 c64; - private struct CpuLink : IMOS6502XLink + private readonly struct CpuLink : IMOS6502XLink { private readonly Chip6510 _chip; @@ -25,15 +25,15 @@ public CpuLink(Chip6510 chip) _chip = chip; } - public byte DummyReadMemory(ushort address) => unchecked((byte)_chip.Read(address)); + public readonly byte DummyReadMemory(ushort address) => unchecked((byte)_chip.Read(address)); - public void OnExecFetch(ushort address) => _chip.c64.ExecFetch(address); + public readonly void OnExecFetch(ushort address) => _chip.c64.ExecFetch(address); - public byte PeekMemory(ushort address) => unchecked((byte)_chip.Peek(address)); + public readonly byte PeekMemory(ushort address) => unchecked((byte)_chip.Peek(address)); - public byte ReadMemory(ushort address) => unchecked((byte)_chip.Read(address)); + public readonly byte ReadMemory(ushort address) => unchecked((byte)_chip.Read(address)); - public void WriteMemory(ushort address, byte value) => _chip.Write(address, value); + public readonly void WriteMemory(ushort address, byte value) => _chip.Write(address, value); } public Func PeekMemory; @@ -98,15 +98,12 @@ public void ExecutePhase() public int Peek(int addr) { - switch (addr) + return addr switch { - case 0x0000: - return _port.Direction; - case 0x0001: - return PortData; - default: - return PeekMemory(addr); - } + 0x0000 => _port.Direction, + 0x0001 => PortData, + _ => PeekMemory(addr), + }; } public void Poke(int addr, int val) diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6522.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6522.cs index d54e3c2e1af..074a387306c 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6522.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6522.cs @@ -4,14 +4,8 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64.MOS { public static class Chip6522 { - public static Via Create(Func readPrA, Func readPrB) - { - return new Via(readPrA, readPrB); - } + public static Via Create(Func readPrA, Func readPrB) => new(readPrA, readPrB); - public static Via Create(Func readClock, Func readData, Func readAtn, int driveNumber) - { - return new Via(readClock, readData, readAtn, driveNumber); - } + public static Via Create(Func readClock, Func readData, Func readAtn, int driveNumber) => new(readClock, readData, readAtn, driveNumber); } } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6526.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6526.cs index f7fb0665f13..6ed167c492f 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6526.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6526.cs @@ -11,60 +11,50 @@ public static class Chip6526 { public static Cia CreateCia1(C64.CiaType type, Func readIec, Func readUserPort) { - switch (type) + return type switch { - case C64.CiaType.Ntsc: - return new Cia(14318181, 14 * 60, readIec, readUserPort) - { - DelayedInterrupts = true - }; - case C64.CiaType.NtscRevA: - return new Cia(14318181, 14 * 60, readIec, readUserPort) - { - DelayedInterrupts = false - }; - case C64.CiaType.Pal: - return new Cia(17734472, 18 * 50, readIec, readUserPort) - { - DelayedInterrupts = true - }; - case C64.CiaType.PalRevA: - return new Cia(17734472, 18 * 50, readIec, readUserPort) - { - DelayedInterrupts = false - }; - default: - throw new Exception("Unrecognized CIA timer type."); - } + C64.CiaType.Ntsc => new Cia(14318181, 14 * 60, readIec, readUserPort) + { + DelayedInterrupts = true + }, + C64.CiaType.NtscRevA => new Cia(14318181, 14 * 60, readIec, readUserPort) + { + DelayedInterrupts = false + }, + C64.CiaType.Pal => new Cia(17734472, 18 * 50, readIec, readUserPort) + { + DelayedInterrupts = true + }, + C64.CiaType.PalRevA => new Cia(17734472, 18 * 50, readIec, readUserPort) + { + DelayedInterrupts = false + }, + _ => throw new Exception("Unrecognized CIA timer type."), + }; } public static Cia CreateCia0(C64.CiaType type, Func keyboard, Func joysticks) { - switch (type) + return type switch { - case C64.CiaType.Ntsc: - return new Cia(14318181, 14 * 60, keyboard, joysticks) - { - DelayedInterrupts = true - }; - case C64.CiaType.NtscRevA: - return new Cia(14318181, 14 * 60, keyboard, joysticks) - { - DelayedInterrupts = false - }; - case C64.CiaType.Pal: - return new Cia(17734472, 18 * 50, keyboard, joysticks) - { - DelayedInterrupts = true - }; - case C64.CiaType.PalRevA: - return new Cia(17734472, 18 * 50, keyboard, joysticks) - { - DelayedInterrupts = false - }; - default: - throw new Exception("Unrecognized CIA timer type."); - } + C64.CiaType.Ntsc => new Cia(14318181, 14 * 60, keyboard, joysticks) + { + DelayedInterrupts = true + }, + C64.CiaType.NtscRevA => new Cia(14318181, 14 * 60, keyboard, joysticks) + { + DelayedInterrupts = false + }, + C64.CiaType.Pal => new Cia(17734472, 18 * 50, keyboard, joysticks) + { + DelayedInterrupts = true + }, + C64.CiaType.PalRevA => new Cia(17734472, 18 * 50, keyboard, joysticks) + { + DelayedInterrupts = false + }, + _ => throw new Exception("Unrecognized CIA timer type."), + }; } } } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6581R2.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6581R2.cs index 8f3d04b64e8..287c4787647 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6581R2.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6581R2.cs @@ -15,9 +15,6 @@ public static class Chip6581R2 new[] { 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x014, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x001, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x025, 0x015, 0x028, 0x074, 0x196, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x014, 0x05c, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x014, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x089, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x080, 0x0c4, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x02a, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x02a, 0x000, 0x095, 0x095, 0x135, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x095, 0x000, 0x000, 0x000, 0x095, 0x095, 0x095, 0x0e0, 0x1c5, 0x02a, 0x095, 0x095, 0x0e0, 0x0a0, 0x0e0, 0x13a, 0x28d, 0x0e5, 0x145, 0x148, 0x2d9, 0x239, 0x3cc, 0x632, 0x89a, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x014, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x001, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x025, 0x015, 0x028, 0x074, 0x196, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x014, 0x05c, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x014, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x089, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x080, 0x0c4, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x02a, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x02a, 0x000, 0x095, 0x095, 0x135, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x095, 0x000, 0x000, 0x000, 0x095, 0x095, 0x095, 0x0e0, 0x1c5, 0x02a, 0x095, 0x095, 0x0e0, 0x0a0, 0x0e0, 0x13a, 0x28d, 0x0e5, 0x145, 0x148, 0x2d9, 0x239, 0x3cc, 0x632, 0x89a } }; - public static Sid Create(int newSampleRate, int clockFrqNum, int clockFrqDen) - { - return new Sid(WaveTable, newSampleRate, clockFrqNum, clockFrqDen); - } + public static Sid Create(int newSampleRate, int clockFrqNum, int clockFrqDen) => new(WaveTable, newSampleRate, clockFrqNum, clockFrqDen); } } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6581R3.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6581R3.cs index a777cb6d39e..e697025ae64 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6581R3.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6581R3.cs @@ -15,9 +15,6 @@ public static class Chip6581R3 new[] { 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x345, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x050, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x100, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x100, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x280, 0x000, 0x000, 0x000, 0x4ea, 0x22a, 0x7ca, 0x7f0, 0x7f0, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x345, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x050, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x100, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x100, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x32a, 0x000, 0x000, 0x000, 0x4ea, 0x22a, 0x7d0, 0x7f0, 0x7f0 } }; - public static Sid Create(int newSampleRate, int clockFrqNum, int clockFrqDen) - { - return new Sid(WaveTable, newSampleRate, clockFrqNum, clockFrqDen); - } + public static Sid Create(int newSampleRate, int clockFrqNum, int clockFrqDen) => new(WaveTable, newSampleRate, clockFrqNum, clockFrqDen); } } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6581R4AR.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6581R4AR.cs index 14ebea10267..cabd99c20e6 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6581R4AR.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6581R4AR.cs @@ -15,9 +15,6 @@ public static class Chip6581R4AR new[] { 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x070, 0x274, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x03c, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x01c, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x080, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x240, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x080, 0x2a0, 0x000, 0x000, 0x000, 0x080, 0x000, 0x080, 0x0c0, 0x3d0, 0x080, 0x1e0, 0x260, 0x4a8, 0x458, 0x6a4, 0x7ec, 0x7f0, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x070, 0x274, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x03c, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x01c, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x080, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x240, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x080, 0x2a0, 0x000, 0x000, 0x000, 0x080, 0x000, 0x080, 0x0c0, 0x3d0, 0x080, 0x1e0, 0x260, 0x4a8, 0x458, 0x6a4, 0x7ec, 0x7f0 } }; - public static Sid Create(int newSampleRate, int clockFrqNum, int clockFrqDen) - { - return new Sid(WaveTable, newSampleRate, clockFrqNum, clockFrqDen); - } + public static Sid Create(int newSampleRate, int clockFrqNum, int clockFrqDen) => new(WaveTable, newSampleRate, clockFrqNum, clockFrqDen); } } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip8580R5.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip8580R5.cs index eae6476e863..4ae5d655424 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip8580R5.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip8580R5.cs @@ -15,9 +15,6 @@ public static class Chip8580R5 new[] { 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x078, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x100, 0x000, 0x000, 0x000, 0x100, 0x100, 0x100, 0x380, 0x3c0, 0x3c0, 0x3c0, 0x4c0, 0x760, 0x760, 0x7d0, 0x7e8, 0x7f0, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x0f0, 0x2f0, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x800, 0x918, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x400, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x400, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x800, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x400, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x000, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x000, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x800, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x800, 0x800, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x400, 0x800, 0x400, 0x400, 0x400, 0x800, 0x800, 0x800, 0x800, 0x800, 0x800, 0x800, 0x800, 0x800, 0x800, 0x800, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xc00, 0xc38, 0x800, 0x800, 0x800, 0x800, 0x800, 0x800, 0x800, 0x800, 0x800, 0x800, 0x800, 0x800, 0x800, 0x800, 0x800, 0xa00, 0x800, 0x800, 0x800, 0x800, 0x800, 0x800, 0x800, 0x800, 0x800, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0x800, 0x800, 0x800, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xc00, 0xc00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xc00, 0xa00, 0xa00, 0xc00, 0xc00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xa00, 0xc00, 0xc00, 0xc00, 0xc00, 0xc00, 0xc00, 0xc00, 0xc00, 0xc00, 0xc00, 0xc00, 0xc00, 0xc00, 0xc00, 0xc00, 0xc00, 0xc00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xe00, 0xe00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xe00, 0xe00, 0xe00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xd00, 0xe00, 0xd00, 0xe00, 0xd00, 0xd00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe00, 0xe80, 0xe80, 0xe80, 0xe80, 0xf00, 0xf00, 0xe80, 0xe80, 0xe80, 0xe80, 0xe80, 0xe80, 0xe80, 0xe80, 0xe80, 0xe80, 0xe80, 0xe80, 0xe80, 0xf00, 0xf00, 0xf00, 0xe80, 0xe80, 0xf00, 0xf00, 0xf00, 0xf00, 0xf00, 0xf00, 0xf00, 0xf00, 0xf00, 0xf40, 0xf40, 0xf40, 0xf40, 0xf80, 0xf40, 0xf40, 0xf40, 0xf40, 0xf40, 0xf40, 0xf80, 0xf80, 0xf80, 0xf80, 0xf80, 0xf80, 0xf80, 0xfa0, 0xfa0, 0xfc0, 0xfa0, 0xfc0, 0xfc0, 0xfc0, 0xfc0, 0xfc0, 0xfd0, 0xfe0, 0xfe0, 0xfe0, 0xfe0, 0xff0, 0xff0, 0xff0, 0xff0, 0xff0 } }; - public static Sid Create(int newSampleRate, int clockFrqNum, int clockFrqDen) - { - return new Sid(WaveTable, newSampleRate, clockFrqNum, clockFrqDen); - } + public static Sid Create(int newSampleRate, int clockFrqNum, int clockFrqDen) => new(WaveTable, newSampleRate, clockFrqNum, clockFrqDen); } } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip90611401.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip90611401.cs index 75af8f84ac4..af68ba11644 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip90611401.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip90611401.cs @@ -198,37 +198,23 @@ private PlaBank Bank(int addr, bool read) public int Peek(int addr) { - switch (Bank(addr, true)) + return Bank(addr, true) switch { - case PlaBank.BasicRom: - return PeekBasicRom(addr); - case PlaBank.CartridgeHi: - return PeekCartridgeHi(addr); - case PlaBank.CartridgeLo: - return PeekCartridgeLo(addr); - case PlaBank.CharRom: - return PeekCharRom(addr); - case PlaBank.Cia0: - return PeekCia0(addr); - case PlaBank.Cia1: - return PeekCia1(addr); - case PlaBank.ColorRam: - return PeekColorRam(addr); - case PlaBank.Expansion0: - return PeekExpansionLo(addr); - case PlaBank.Expansion1: - return PeekExpansionHi(addr); - case PlaBank.KernalRom: - return PeekKernalRom(addr); - case PlaBank.Ram: - return PeekMemory(addr); - case PlaBank.Sid: - return PeekSid(addr); - case PlaBank.Vic: - return PeekVic(addr); - } - - return 0xFF; + PlaBank.BasicRom => PeekBasicRom(addr), + PlaBank.CartridgeHi => PeekCartridgeHi(addr), + PlaBank.CartridgeLo => PeekCartridgeLo(addr), + PlaBank.CharRom => PeekCharRom(addr), + PlaBank.Cia0 => PeekCia0(addr), + PlaBank.Cia1 => PeekCia1(addr), + PlaBank.ColorRam => PeekColorRam(addr), + PlaBank.Expansion0 => PeekExpansionLo(addr), + PlaBank.Expansion1 => PeekExpansionHi(addr), + PlaBank.KernalRom => PeekKernalRom(addr), + PlaBank.Ram => PeekMemory(addr), + PlaBank.Sid => PeekSid(addr), + PlaBank.Vic => PeekVic(addr), + _ => 0xFF, + }; } public void Poke(int addr, int val) @@ -270,37 +256,23 @@ public void Poke(int addr, int val) public int Read(int addr) { - switch (Bank(addr, true)) + return Bank(addr, true) switch { - case PlaBank.BasicRom: - return ReadBasicRom(addr); - case PlaBank.CartridgeHi: - return ReadCartridgeHi(addr); - case PlaBank.CartridgeLo: - return ReadCartridgeLo(addr); - case PlaBank.CharRom: - return ReadCharRom(addr); - case PlaBank.Cia0: - return ReadCia0(addr); - case PlaBank.Cia1: - return ReadCia1(addr); - case PlaBank.ColorRam: - return ReadColorRam(addr); - case PlaBank.Expansion0: - return ReadExpansionLo(addr); - case PlaBank.Expansion1: - return ReadExpansionHi(addr); - case PlaBank.KernalRom: - return ReadKernalRom(addr); - case PlaBank.Ram: - return ReadMemory(addr); - case PlaBank.Sid: - return ReadSid(addr); - case PlaBank.Vic: - return ReadVic(addr); - } - - return 0xFF; + PlaBank.BasicRom => ReadBasicRom(addr), + PlaBank.CartridgeHi => ReadCartridgeHi(addr), + PlaBank.CartridgeLo => ReadCartridgeLo(addr), + PlaBank.CharRom => ReadCharRom(addr), + PlaBank.Cia0 => ReadCia0(addr), + PlaBank.Cia1 => ReadCia1(addr), + PlaBank.ColorRam => ReadColorRam(addr), + PlaBank.Expansion0 => ReadExpansionLo(addr), + PlaBank.Expansion1 => ReadExpansionHi(addr), + PlaBank.KernalRom => ReadKernalRom(addr), + PlaBank.Ram => ReadMemory(addr), + PlaBank.Sid => ReadSid(addr), + PlaBank.Vic => ReadVic(addr), + _ => 0xFF, + }; } public void SyncState(Serializer ser) diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Cia.Port.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Cia.Port.cs index f4af0f5146c..07b75d0c5f5 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Cia.Port.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Cia.Port.cs @@ -15,15 +15,9 @@ private interface IPort private sealed class DisconnectedPort : IPort { - public int ReadPra(int pra, int ddra, int prb, int ddrb) - { - return (pra | ~ddra) & 0xFF; - } + public int ReadPra(int pra, int ddra, int prb, int ddrb) => (pra | ~ddra) & 0xFF; - public int ReadPrb(int pra, int ddra, int prb, int ddrb) - { - return (prb | ~ddrb) & 0xFF; - } + public int ReadPrb(int pra, int ddra, int prb, int ddrb) => (prb | ~ddrb) & 0xFF; } private sealed class JoystickKeyboardPort : IPort @@ -41,7 +35,7 @@ public JoystickKeyboardPort(Func readJoyData, Func readKeyData) private int GetJoystick1() { - var joyData = _readJoyData(); + bool[] joyData = _readJoyData(); return 0xE0 | (joyData[0] ? 0x00 : 0x01) | (joyData[1] ? 0x00 : 0x02) | @@ -52,7 +46,7 @@ private int GetJoystick1() private int GetJoystick2() { - var joyData = _readJoyData(); + bool[] joyData = _readJoyData(); return 0xE0 | (joyData[5] ? 0x00 : 0x01) | (joyData[6] ? 0x00 : 0x02) | @@ -63,14 +57,14 @@ private int GetJoystick2() private int GetKeyboardRows(int activeColumns) { - var keyData = _readKeyData(); - var result = 0xFF; - for (var r = 0; r < 8; r++) + bool[] keyData = _readKeyData(); + int result = 0xFF; + for (int r = 0; r < 8; r++) { if ((activeColumns & 0x1) == 0) { - var i = r << 3; - for (var c = 0; c < 8; c++) + int i = r << 3; + for (int c = 0; c < 8; c++) { if (keyData[i++]) { @@ -87,14 +81,14 @@ private int GetKeyboardRows(int activeColumns) private int GetKeyboardColumns(int activeRows) { - var keyData = _readKeyData(); - var result = 0xFF; - for (var c = 0; c < 8; c++) + bool[] keyData = _readKeyData(); + int result = 0xFF; + for (int c = 0; c < 8; c++) { if ((activeRows & 0x1) == 0) { - var i = c; - for (var r = 0; r < 8; r++) + int i = c; + for (int r = 0; r < 8; r++) { if (keyData[i]) { @@ -139,15 +133,9 @@ public IecPort(Func readIec, Func readUserPort) _readUserPort = readUserPort; } - public int ReadPra(int pra, int ddra, int prb, int ddrb) - { - return (pra & ddra) | (~ddra & _readIec()); - } + public int ReadPra(int pra, int ddra, int prb, int ddrb) => (pra & ddra) | (~ddra & _readIec()); - public int ReadPrb(int pra, int ddra, int prb, int ddrb) - { - return (prb | ~ddrb) | (~ddrb & _readUserPort()); - } + public int ReadPrb(int pra, int ddra, int prb, int ddrb) => (prb | ~ddrb) | (~ddrb & _readUserPort()); } } } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Cia.Registers.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Cia.Registers.cs index 8d435bfdf2c..2a4bdfa3c16 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Cia.Registers.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Cia.Registers.cs @@ -2,20 +2,11 @@ { public sealed partial class Cia { - public int Peek(int addr) - { - return ReadRegister(addr & 0xF); - } + public int Peek(int addr) => ReadRegister(addr & 0xF); - public bool ReadIrq() - { - return (_icr & 0x80) == 0; - } + public bool ReadIrq() => (_icr & 0x80) == 0; - public int ReadPortA() - { - return (_pra | ~_ddra) & 0xFF; - } + public int ReadPortA() => (_pra | ~_ddra) & 0xFF; public int Read(int addr) { @@ -33,7 +24,7 @@ public int Read(int addr) _todLatch = true; return _latchHr; case 0xD: - var icrTemp = _icr; + int icrTemp = _icr; _icr = 0; return icrTemp; } @@ -43,49 +34,29 @@ public int Read(int addr) private int ReadRegister(int addr) { - switch (addr) + return addr switch { - case 0x0: - return _port.ReadPra(_pra, _ddra, _prb, _ddrb); - case 0x1: - return _port.ReadPrb(_pra, _ddra, _prb, _ddrb); - case 0x2: - return _ddra; - case 0x3: - return _ddrb; - case 0x4: - return _ta & 0xFF; - case 0x5: - return (_ta >> 8) & 0xFF; - case 0x6: - return _tb & 0xFF; - case 0x7: - return (_tb >> 8) & 0xFF; - case 0x8: - return _tod10Ths; - case 0x9: - return _todSec; - case 0xA: - return _todMin; - case 0xB: - return _todHr; - case 0xC: - return _sdr; - case 0xD: - return _icr; - case 0xE: - return _cra; - case 0xF: - return _crb; - } - - return 0; + 0x0 => _port.ReadPra(_pra, _ddra, _prb, _ddrb), + 0x1 => _port.ReadPrb(_pra, _ddra, _prb, _ddrb), + 0x2 => _ddra, + 0x3 => _ddrb, + 0x4 => _ta & 0xFF, + 0x5 => (_ta >> 8) & 0xFF, + 0x6 => _tb & 0xFF, + 0x7 => (_tb >> 8) & 0xFF, + 0x8 => _tod10Ths, + 0x9 => _todSec, + 0xA => _todMin, + 0xB => _todHr, + 0xC => _sdr, + 0xD => _icr, + 0xE => _cra, + 0xF => _crb, + _ => 0, + }; } - public void Poke(int addr, int val) - { - WriteRegister(addr, val); - } + public void Poke(int addr, int val) => WriteRegister(addr, val); public void Write(int addr, int val) { @@ -171,7 +142,7 @@ public void Write(int addr, int val) } break; case 0xE: - var oldCra = _cra; + int oldCra = _cra; WriteRegister(addr, val); // Toggle output begins high when timer starts. @@ -181,7 +152,7 @@ public void Write(int addr, int val) } break; case 0xF: - var oldCrb = _crb; + int oldCrb = _crb; WriteRegister(addr, val); // Toggle output begins high when timer starts. diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/LatchedPort.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/LatchedPort.cs index 13d2e9a3874..1e1ae4cc1e4 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/LatchedPort.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/LatchedPort.cs @@ -25,15 +25,9 @@ public LatchedPort() // cause the pull-up resistors not to be enough to keep the bus bit set to 1 when // both the direction and latch are 1 (the keyboard and joystick port 2 can do this.) // the class does not handle this case as it must be handled differently in every occurrence. - public int ReadInput(int bus) - { - return (Latch & Direction) | ((Direction ^ 0xFF) & bus); - } + public int ReadInput(int bus) => (Latch & Direction) | ((Direction ^ 0xFF) & bus); - public int ReadOutput() - { - return (Latch & Direction) | (Direction ^ 0xFF); - } + public int ReadOutput() => (Latch & Direction) | (Direction ^ 0xFF); public void SyncState(Serializer ser) { @@ -66,15 +60,9 @@ public LatchedBooleanPort() // 1 1 0 1 // 1 1 1 1 - public bool ReadInput(bool bus) - { - return (Direction && Latch) || (!Direction && bus); - } + public bool ReadInput(bool bus) => (Direction && Latch) || (!Direction && bus); - public bool ReadOutput() - { - return Latch || !Direction; - } + public bool ReadOutput() => Latch || !Direction; public void SyncState(Serializer ser) { diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Sid.Envelope.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Sid.Envelope.cs index fc6d9ee5aa8..a9759cd08ec 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Sid.Envelope.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Sid.Envelope.cs @@ -60,7 +60,7 @@ public void ExecutePhase2() if (_lfsr != _rate) { - var feedback = ((_lfsr >> 14) ^ (_lfsr >> 13)) & 0x1; + int feedback = ((_lfsr >> 14) ^ (_lfsr >> 13)) & 0x1; _lfsr = ((_lfsr << 1) & 0x7FFF) | feedback; return; } @@ -132,7 +132,7 @@ private void UpdateExpCounter() { { - for (var i = 0; i < 7; i++) + for (int i = 0; i < 7; i++) { if (_envCounter == ExpCounterTable[i]) _expPeriod = ExpPeriodTable[i]; @@ -171,7 +171,7 @@ public bool Gate get => _gate; set { - var nextGate = value; + bool nextGate = value; if (nextGate && !_gate) { _state = StateAttack; diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Sid.Registers.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Sid.Registers.cs index 3140be4fef5..ea0c44653e7 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Sid.Registers.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Sid.Registers.cs @@ -2,20 +2,14 @@ { public sealed partial class Sid { - public int Peek(int addr) - { - return ReadRegister(addr & 0x1F); - } + public int Peek(int addr) => ReadRegister(addr & 0x1F); - public void Poke(int addr, int val) - { - WriteRegister(addr & 0x1F, val); - } + public void Poke(int addr, int val) => WriteRegister(addr & 0x1F, val); public int Read(int addr) { addr &= 0x1F; - var result = _databus; + int result = _databus; switch (addr) { @@ -33,7 +27,7 @@ public int Read(int addr) private int ReadRegister(int addr) { - var result = 0x00; + int result = 0x00; switch (addr) { @@ -145,7 +139,7 @@ public void Write(int addr, int val) // we want to only flush the filter when the filter is actually changed, that way // the FFT will not be impacted by small sample sizes from other changes - if ((addr == 0x15) || (addr == 0x16) || (addr == 0x17)) + if (addr is 0x15 or 0x16 or 0x17) { Flush(true); } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Sid.SoundProvider.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Sid.SoundProvider.cs index cff7a41f8c0..551ccc86583 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Sid.SoundProvider.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Sid.SoundProvider.cs @@ -1,4 +1,4 @@ -using System; +using System; using BizHawk.Emulation.Common; namespace BizHawk.Emulation.Cores.Computers.Commodore64.MOS @@ -17,28 +17,24 @@ public void SetSyncMode(SyncSoundMode mode) } } - public void GetSamplesAsync(short[] samples) - { - throw new NotSupportedException("Async is not available"); - } + public void GetSamplesAsync(short[] samples) => throw new NotSupportedException("Async is not available"); - public void DiscardSamples() - { - _outputBufferIndex = 0; - } + public void DiscardSamples() => _outputBufferIndex = 0; +#pragma warning disable IDE0051 // Expose this as GetSamplesAsync to support async sound // There's not need to do this though unless this core wants to handle async in its own way (the client can handle these situations if not available from the core) private void GetSamples(short[] samples) { Flush(true); - var length = Math.Min(samples.Length, _outputBufferIndex); - for (var i = 0; i < length; i++) + int length = Math.Min(samples.Length, _outputBufferIndex); + for (int i = 0; i < length; i++) { samples[i] = _outputBuffer[i]; } _outputBufferIndex = 0; } + #pragma warning restore IDE0051 public void GetSamplesSync(out short[] samples, out int nsamp) { diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Sid.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Sid.cs index f3f3a56e5cb..659a54cf1ce 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Sid.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Sid.cs @@ -76,21 +76,21 @@ public Sid(int[][] newWaveformTable, int sampleRate, int cyclesNum, int cyclesDe _sampleCyclesDen = cyclesDen * sampleRate; _envelopes = new Envelope[3]; - for (var i = 0; i < 3; i++) + for (int i = 0; i < 3; i++) _envelopes[i] = new Envelope(); _envelope0 = _envelopes[0]; _envelope1 = _envelopes[1]; _envelope2 = _envelopes[2]; _voices = new Voice[3]; - for (var i = 0; i < 3; i++) + for (int i = 0; i < 3; i++) _voices[i] = new Voice(newWaveformTable); _voice0 = _voices[0]; _voice1 = _voices[1]; _voice2 = _voices[2]; _filterEnable = new bool[3]; - for (var i = 0; i < 3; i++) + for (int i = 0; i < 3; i++) _filterEnable[i] = false; _outputBufferFiltered = new int[sampleRate]; @@ -102,7 +102,7 @@ public Sid(int[][] newWaveformTable, int sampleRate, int cyclesNum, int cyclesDe public void HardReset() { - for (var i = 0; i < 3; i++) + for (int i = 0; i < 3; i++) { _envelopes[i].HardReset(); _voices[i].HardReset(); @@ -283,7 +283,7 @@ public void filter_operator() // add resonance effect // let's assume that frequencies near the peak are doubled in strength at max resonance - if ((1.2 > freq / loc_filterFrequency) && (freq / loc_filterFrequency > 0.8 )) + if (freq / loc_filterFrequency is < 1.2 and > 0.8) { _fftBuffer[i] = _fftBuffer[i] * (1 + (double)_filterResonance/15); } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Via.Port.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Via.Port.cs index 14d89e0c438..30c4fa04b02 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Via.Port.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Via.Port.cs @@ -17,25 +17,13 @@ private interface IPort private sealed class DisconnectedPort : IPort { - public int ReadPra(int pra, int ddra) - { - return (pra | ~ddra) & 0xFF; - } + public int ReadPra(int pra, int ddra) => (pra | ~ddra) & 0xFF; - public int ReadPrb(int prb, int ddrb) - { - return (prb | ~ddrb) & 0xFF; - } + public int ReadPrb(int prb, int ddrb) => (prb | ~ddrb) & 0xFF; - public int ReadExternalPra() - { - return 0xFF; - } + public int ReadExternalPra() => 0xFF; - public int ReadExternalPrb() - { - return 0xFF; - } + public int ReadExternalPrb() => 0xFF; public void SyncState(Serializer ser) { @@ -54,25 +42,13 @@ public DriverPort(Func readPrA, Func readPrB) _readPrB = readPrB; } - public int ReadPra(int pra, int ddra) - { - return (pra | ~ddra) & ReadExternalPra(); - } + public int ReadPra(int pra, int ddra) => (pra | ~ddra) & ReadExternalPra(); - public int ReadPrb(int prb, int ddrb) - { - return (prb & ddrb) | (_readPrB() & ~ddrb); - } + public int ReadPrb(int prb, int ddrb) => (prb & ddrb) | (_readPrB() & ~ddrb); - public int ReadExternalPra() - { - return _readPrA(); - } + public int ReadExternalPra() => _readPrA(); - public int ReadExternalPrb() - { - return _readPrB(); - } + public int ReadExternalPrb() => _readPrB(); public void SyncState(Serializer ser) { @@ -96,10 +72,7 @@ public IecPort(Func readClock, Func readData, Func readAtn, in _driveNumber = (driveNumber & 0x3) << 5; } - public int ReadPra(int pra, int ddra) - { - return (pra | ~ddra) & ReadExternalPra(); - } + public int ReadPra(int pra, int ddra) => (pra | ~ddra) & ReadExternalPra(); public int ReadPrb(int prb, int ddrb) { @@ -111,10 +84,7 @@ public int ReadPrb(int prb, int ddrb) _driveNumber)); } - public int ReadExternalPra() - { - return 0xFF; - } + public int ReadExternalPra() => 0xFF; public int ReadExternalPrb() { @@ -125,10 +95,7 @@ public int ReadExternalPrb() _driveNumber; } - public void SyncState(Serializer ser) - { - ser.Sync(nameof(_driveNumber), ref _driveNumber); - } + public void SyncState(Serializer ser) => ser.Sync(nameof(_driveNumber), ref _driveNumber); } } } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Via.Registers.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Via.Registers.cs index a5b122724be..0b1ef076be5 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Via.Registers.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Via.Registers.cs @@ -2,15 +2,9 @@ { public sealed partial class Via { - public int Peek(int addr) - { - return ReadRegister(addr & 0xF); - } + public int Peek(int addr) => ReadRegister(addr & 0xF); - public void Poke(int addr, int val) - { - WriteRegister(addr & 0xF, val); - } + public void Poke(int addr, int val) => WriteRegister(addr & 0xF, val); public int Read(int addr) { @@ -18,13 +12,13 @@ public int Read(int addr) switch (addr) { case 0x0: - if (_pcrCb2Control != PCR_CONTROL_INDEPENDENT_INTERRUPT_INPUT_NEGATIVE_EDGE && _pcrCb2Control != PCR_CONTROL_INDEPENDENT_INTERRUPT_INPUT_POSITIVE_EDGE) + if (_pcrCb2Control is not PCR_CONTROL_INDEPENDENT_INTERRUPT_INPUT_NEGATIVE_EDGE and not PCR_CONTROL_INDEPENDENT_INTERRUPT_INPUT_POSITIVE_EDGE) _ifr &= 0xE7; if (_acrPbLatchEnable) return _pbLatch; break; case 0x1: - if (_pcrCa2Control != PCR_CONTROL_INDEPENDENT_INTERRUPT_INPUT_NEGATIVE_EDGE && _pcrCa2Control != PCR_CONTROL_INDEPENDENT_INTERRUPT_INPUT_POSITIVE_EDGE) + if (_pcrCa2Control is not PCR_CONTROL_INDEPENDENT_INTERRUPT_INPUT_NEGATIVE_EDGE and not PCR_CONTROL_INDEPENDENT_INTERRUPT_INPUT_POSITIVE_EDGE) _ifr &= 0xFC; if (_acrPaLatchEnable) return _paLatch; @@ -52,42 +46,25 @@ public int Read(int addr) private int ReadRegister(int addr) { - switch (addr) + return addr switch { - case 0x0: - return _port.ReadPrb(_prb, _ddrb); - case 0x1: - case 0xF: - return _port.ReadExternalPra(); - case 0x2: - return _ddrb; - case 0x3: - return _ddra; - case 0x4: - return _t1C & 0xFF; - case 0x5: - return (_t1C >> 8) & 0xFF; - case 0x6: - return _t1L & 0xFF; - case 0x7: - return (_t1L >> 8) & 0xFF; - case 0x8: - return _t2C & 0xFF; - case 0x9: - return (_t2C >> 8) & 0xFF; - case 0xA: - return _sr; - case 0xB: - return _acr; - case 0xC: - return _pcr; - case 0xD: - return _ifr; - case 0xE: - return _ier | 0x80; - } - - return 0xFF; + 0x0 => _port.ReadPrb(_prb, _ddrb), + 0x1 or 0xF => _port.ReadExternalPra(), + 0x2 => _ddrb, + 0x3 => _ddra, + 0x4 => _t1C & 0xFF, + 0x5 => (_t1C >> 8) & 0xFF, + 0x6 => _t1L & 0xFF, + 0x7 => (_t1L >> 8) & 0xFF, + 0x8 => _t2C & 0xFF, + 0x9 => (_t2C >> 8) & 0xFF, + 0xA => _sr, + 0xB => _acr, + 0xC => _pcr, + 0xD => _ifr, + 0xE => _ier | 0x80, + _ => 0xFF, + }; } public void Write(int addr, int val) @@ -96,14 +73,14 @@ public void Write(int addr, int val) switch (addr) { case 0x0: - if (_pcrCb2Control != PCR_CONTROL_INDEPENDENT_INTERRUPT_INPUT_NEGATIVE_EDGE && _pcrCb2Control != PCR_CONTROL_INDEPENDENT_INTERRUPT_INPUT_POSITIVE_EDGE) + if (_pcrCb2Control is not PCR_CONTROL_INDEPENDENT_INTERRUPT_INPUT_NEGATIVE_EDGE and not PCR_CONTROL_INDEPENDENT_INTERRUPT_INPUT_POSITIVE_EDGE) _ifr &= 0xE7; if (_pcrCb2Control == PCR_CONTROL_PULSE_OUTPUT) _handshakeCb2NextClock = true; WriteRegister(addr, val); break; case 0x1: - if (_pcrCa2Control != PCR_CONTROL_INDEPENDENT_INTERRUPT_INPUT_NEGATIVE_EDGE && _pcrCa2Control != PCR_CONTROL_INDEPENDENT_INTERRUPT_INPUT_POSITIVE_EDGE) + if (_pcrCa2Control is not PCR_CONTROL_INDEPENDENT_INTERRUPT_INPUT_NEGATIVE_EDGE and not PCR_CONTROL_INDEPENDENT_INTERRUPT_INPUT_POSITIVE_EDGE) _ifr &= 0xFC; if (_pcrCa2Control == PCR_CONTROL_PULSE_OUTPUT) _handshakeCa2NextClock = true; diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Via.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Via.cs index 6bf5aac492e..06a0917057b 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Via.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Via.cs @@ -1,10 +1,11 @@ -using System; +using System; using BizHawk.Common; namespace BizHawk.Emulation.Cores.Computers.Commodore64.MOS { public sealed partial class Via { + #pragma warning disable IDE0051 private const int PCR_INT_CONTROL_NEGATIVE_EDGE = 0x00; private const int PCR_INT_CONTROL_POSITIVE_EDGE = 0x01; private const int PCR_CONTROL_INPUT_NEGATIVE_ACTIVE_EDGE = 0x00; @@ -30,6 +31,7 @@ public sealed partial class Via private const int ACR_T1_CONTROL_INTERRUPT_ON_LOAD_AND_ONESHOT_PB7 = 0x80; private const int ACR_T1_CONTROL_CONTINUOUS_INTERRUPTS_AND_OUTPUT_ON_PB7 = 0xC0; private const int ACR_T1_CONTROL_INTERRUPT_ON_LOAD_AND_PULSE_PB7 = 0x80; + #pragma warning restore IDE0051 private int _pra; private int _ddra; @@ -153,7 +155,7 @@ public void HardReset() public void ExecutePhase() { - var shiftIn = false; + bool shiftIn = false; // TODO: use this or delete ////var shiftOut = false; diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.Parse.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.Parse.cs index d514c320a81..1fa08dab145 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.Parse.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.Parse.cs @@ -152,21 +152,13 @@ private void ParseCycle() case VideoMode010: case VideoMode011: _parseSrColorEnable = _parsePixelData != 0; - switch (_parsePixelData) + _pixel = _parsePixelData switch { - case 0: - _pixel = 0; - break; - case 1: - _pixel = _idle ? 0 : _dataC >> 4; - break; - case 2: - _pixel = _idle ? 0 : _dataC; - break; - default: - _pixel = _idle ? 0 : _dataC >> 8; - break; - } + 0 => 0, + 1 => _idle ? 0 : _dataC >> 4, + 2 => _idle ? 0 : _dataC, + _ => _idle ? 0 : _dataC >> 8, + }; break; case VideoMode100: if (_parsePixelData != 0) diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.Registers.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.Registers.cs index d6de85ab6ad..d3feebbcf0f 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.Registers.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.Registers.cs @@ -2,15 +2,9 @@ { public sealed partial class Vic { - public int Peek(int addr) - { - return ReadRegister(addr & 0x3F); - } + public int Peek(int addr) => ReadRegister(addr & 0x3F); - public void Poke(int addr, int val) - { - WriteRegister(addr & 0x3F, val); - } + public void Poke(int addr, int val) => WriteRegister(addr & 0x3F, val); public int Read(int addr) { @@ -31,155 +25,107 @@ public int Read(int addr) private int ReadRegister(int addr) { - switch (addr) + return addr switch { - case 0x00: - case 0x02: - case 0x04: - case 0x06: - case 0x08: - case 0x0A: - case 0x0C: - case 0x0E: - return _sprites[addr >> 1].X & 0xFF; - case 0x01: - case 0x03: - case 0x05: - case 0x07: - case 0x09: - case 0x0B: - case 0x0D: - case 0x0F: - return _sprites[addr >> 1].Y & 0xFF; - case 0x10: - return ((_sprite0.X >> 8) & 0x01) | - ((_sprite1.X >> 7) & 0x02) | - ((_sprite2.X >> 6) & 0x04) | - ((_sprite3.X >> 5) & 0x08) | - ((_sprite4.X >> 4) & 0x10) | - ((_sprite5.X >> 3) & 0x20) | - ((_sprite6.X >> 2) & 0x40) | - ((_sprite7.X >> 1) & 0x80); - case 0x11: - return (_yScroll & 0x7) | - (_rowSelect ? 0x08 : 0x00) | - (_displayEnable ? 0x10 : 0x00) | - (_bitmapMode ? 0x20 : 0x00) | - (_extraColorMode ? 0x40 : 0x00) | - ((_rasterLine & 0x100) >> 1); - case 0x12: - return _rasterLine & 0xFF; - case 0x13: - return _lightPenX & 0xFF; - case 0x14: - return _lightPenY & 0xFF; - case 0x15: - return (_sprite0.Enable ? 0x01 : 0x00) | - (_sprite1.Enable ? 0x02 : 0x00) | - (_sprite2.Enable ? 0x04 : 0x00) | - (_sprite3.Enable ? 0x08 : 0x00) | - (_sprite4.Enable ? 0x10 : 0x00) | - (_sprite5.Enable ? 0x20 : 0x00) | - (_sprite6.Enable ? 0x40 : 0x00) | - (_sprite7.Enable ? 0x80 : 0x00); - case 0x16: - return 0xC0 | (_xScroll & 0x7) | - (_columnSelect ? 0x08 : 0x00) | - (_multicolorMode ? 0x10 : 0x00); - case 0x17: - return (_sprite0.YExpand ? 0x01 : 0x00) | - (_sprite1.YExpand ? 0x02 : 0x00) | - (_sprite2.YExpand ? 0x04 : 0x00) | - (_sprite3.YExpand ? 0x08 : 0x00) | - (_sprite4.YExpand ? 0x10 : 0x00) | - (_sprite5.YExpand ? 0x20 : 0x00) | - (_sprite6.YExpand ? 0x40 : 0x00) | - (_sprite7.YExpand ? 0x80 : 0x00); - case 0x18: - return 0x01 | ((_pointerVm & 0x3C00) >> 6) | - ((_pointerCb & 0x7) << 1); - case 0x19: - return 0x70 | (_intRaster ? 0x01 : 0x00) | - (_intSpriteDataCollision ? 0x02 : 0x00) | - (_intSpriteCollision ? 0x04 : 0x00) | - (_intLightPen ? 0x08 : 0x00) | - ((_irqBuffer & 1) << 7); - case 0x1A: - return 0xF0 | (_enableIntRaster ? 0x01 : 0x00) | - (_enableIntSpriteDataCollision ? 0x02 : 0x00) | - (_enableIntSpriteCollision ? 0x04 : 0x00) | - (_enableIntLightPen ? 0x08 : 0x00); - case 0x1B: - return (_sprite0.Priority ? 0x01 : 0x00) | - (_sprite1.Priority ? 0x02 : 0x00) | - (_sprite2.Priority ? 0x04 : 0x00) | - (_sprite3.Priority ? 0x08 : 0x00) | - (_sprite4.Priority ? 0x10 : 0x00) | - (_sprite5.Priority ? 0x20 : 0x00) | - (_sprite6.Priority ? 0x40 : 0x00) | - (_sprite7.Priority ? 0x80 : 0x00); - case 0x1C: - return (_sprite0.Multicolor ? 0x01 : 0x00) | - (_sprite1.Multicolor ? 0x02 : 0x00) | - (_sprite2.Multicolor ? 0x04 : 0x00) | - (_sprite3.Multicolor ? 0x08 : 0x00) | - (_sprite4.Multicolor ? 0x10 : 0x00) | - (_sprite5.Multicolor ? 0x20 : 0x00) | - (_sprite6.Multicolor ? 0x40 : 0x00) | - (_sprite7.Multicolor ? 0x80 : 0x00); - case 0x1D: - return (_sprite0.XExpand ? 0x01 : 0x00) | - (_sprite1.XExpand ? 0x02 : 0x00) | - (_sprite2.XExpand ? 0x04 : 0x00) | - (_sprite3.XExpand ? 0x08 : 0x00) | - (_sprite4.XExpand ? 0x10 : 0x00) | - (_sprite5.XExpand ? 0x20 : 0x00) | - (_sprite6.XExpand ? 0x40 : 0x00) | - (_sprite7.XExpand ? 0x80 : 0x00); - case 0x1E: - return (_sprite0.CollideSprite ? 0x01 : 0x00) | - (_sprite1.CollideSprite ? 0x02 : 0x00) | - (_sprite2.CollideSprite ? 0x04 : 0x00) | - (_sprite3.CollideSprite ? 0x08 : 0x00) | - (_sprite4.CollideSprite ? 0x10 : 0x00) | - (_sprite5.CollideSprite ? 0x20 : 0x00) | - (_sprite6.CollideSprite ? 0x40 : 0x00) | - (_sprite7.CollideSprite ? 0x80 : 0x00); - case 0x1F: - return (_sprite0.CollideData ? 0x01 : 0x00) | - (_sprite1.CollideData ? 0x02 : 0x00) | - (_sprite2.CollideData ? 0x04 : 0x00) | - (_sprite3.CollideData ? 0x08 : 0x00) | - (_sprite4.CollideData ? 0x10 : 0x00) | - (_sprite5.CollideData ? 0x20 : 0x00) | - (_sprite6.CollideData ? 0x40 : 0x00) | - (_sprite7.CollideData ? 0x80 : 0x00); - case 0x20: - return 0xF0 | _borderColor & 0x0F; - case 0x21: - return 0xF0 | _backgroundColor0 & 0x0F; - case 0x22: - return 0xF0 | _backgroundColor1 & 0x0F; - case 0x23: - return 0xF0 | _backgroundColor2 & 0x0F; - case 0x24: - return 0xF0 | _backgroundColor3 & 0x0F; - case 0x25: - return 0xF0 | _spriteMulticolor0 & 0x0F; - case 0x26: - return 0xF0 | _spriteMulticolor1 & 0x0F; - case 0x27: - case 0x28: - case 0x29: - case 0x2A: - case 0x2B: - case 0x2C: - case 0x2D: - case 0x2E: - return 0xF0 | _sprites[addr - 0x27].Color & 0xF; - default: - return 0xFF; - } + 0x00 or 0x02 or 0x04 or 0x06 or 0x08 or 0x0A or 0x0C or 0x0E => _sprites[addr >> 1].X & 0xFF, + 0x01 or 0x03 or 0x05 or 0x07 or 0x09 or 0x0B or 0x0D or 0x0F => _sprites[addr >> 1].Y & 0xFF, + 0x10 => ((_sprite0.X >> 8) & 0x01) | + ((_sprite1.X >> 7) & 0x02) | + ((_sprite2.X >> 6) & 0x04) | + ((_sprite3.X >> 5) & 0x08) | + ((_sprite4.X >> 4) & 0x10) | + ((_sprite5.X >> 3) & 0x20) | + ((_sprite6.X >> 2) & 0x40) | + ((_sprite7.X >> 1) & 0x80), + 0x11 => (_yScroll & 0x7) | + (_rowSelect ? 0x08 : 0x00) | + (_displayEnable ? 0x10 : 0x00) | + (_bitmapMode ? 0x20 : 0x00) | + (_extraColorMode ? 0x40 : 0x00) | + ((_rasterLine & 0x100) >> 1), + 0x12 => _rasterLine & 0xFF, + 0x13 => _lightPenX & 0xFF, + 0x14 => _lightPenY & 0xFF, + 0x15 => (_sprite0.Enable ? 0x01 : 0x00) | + (_sprite1.Enable ? 0x02 : 0x00) | + (_sprite2.Enable ? 0x04 : 0x00) | + (_sprite3.Enable ? 0x08 : 0x00) | + (_sprite4.Enable ? 0x10 : 0x00) | + (_sprite5.Enable ? 0x20 : 0x00) | + (_sprite6.Enable ? 0x40 : 0x00) | + (_sprite7.Enable ? 0x80 : 0x00), + 0x16 => 0xC0 | (_xScroll & 0x7) | + (_columnSelect ? 0x08 : 0x00) | + (_multicolorMode ? 0x10 : 0x00), + 0x17 => (_sprite0.YExpand ? 0x01 : 0x00) | + (_sprite1.YExpand ? 0x02 : 0x00) | + (_sprite2.YExpand ? 0x04 : 0x00) | + (_sprite3.YExpand ? 0x08 : 0x00) | + (_sprite4.YExpand ? 0x10 : 0x00) | + (_sprite5.YExpand ? 0x20 : 0x00) | + (_sprite6.YExpand ? 0x40 : 0x00) | + (_sprite7.YExpand ? 0x80 : 0x00), + 0x18 => 0x01 | ((_pointerVm & 0x3C00) >> 6) | + ((_pointerCb & 0x7) << 1), + 0x19 => 0x70 | (_intRaster ? 0x01 : 0x00) | + (_intSpriteDataCollision ? 0x02 : 0x00) | + (_intSpriteCollision ? 0x04 : 0x00) | + (_intLightPen ? 0x08 : 0x00) | + ((_irqBuffer & 1) << 7), + 0x1A => 0xF0 | (_enableIntRaster ? 0x01 : 0x00) | + (_enableIntSpriteDataCollision ? 0x02 : 0x00) | + (_enableIntSpriteCollision ? 0x04 : 0x00) | + (_enableIntLightPen ? 0x08 : 0x00), + 0x1B => (_sprite0.Priority ? 0x01 : 0x00) | + (_sprite1.Priority ? 0x02 : 0x00) | + (_sprite2.Priority ? 0x04 : 0x00) | + (_sprite3.Priority ? 0x08 : 0x00) | + (_sprite4.Priority ? 0x10 : 0x00) | + (_sprite5.Priority ? 0x20 : 0x00) | + (_sprite6.Priority ? 0x40 : 0x00) | + (_sprite7.Priority ? 0x80 : 0x00), + 0x1C => (_sprite0.Multicolor ? 0x01 : 0x00) | + (_sprite1.Multicolor ? 0x02 : 0x00) | + (_sprite2.Multicolor ? 0x04 : 0x00) | + (_sprite3.Multicolor ? 0x08 : 0x00) | + (_sprite4.Multicolor ? 0x10 : 0x00) | + (_sprite5.Multicolor ? 0x20 : 0x00) | + (_sprite6.Multicolor ? 0x40 : 0x00) | + (_sprite7.Multicolor ? 0x80 : 0x00), + 0x1D => (_sprite0.XExpand ? 0x01 : 0x00) | + (_sprite1.XExpand ? 0x02 : 0x00) | + (_sprite2.XExpand ? 0x04 : 0x00) | + (_sprite3.XExpand ? 0x08 : 0x00) | + (_sprite4.XExpand ? 0x10 : 0x00) | + (_sprite5.XExpand ? 0x20 : 0x00) | + (_sprite6.XExpand ? 0x40 : 0x00) | + (_sprite7.XExpand ? 0x80 : 0x00), + 0x1E => (_sprite0.CollideSprite ? 0x01 : 0x00) | + (_sprite1.CollideSprite ? 0x02 : 0x00) | + (_sprite2.CollideSprite ? 0x04 : 0x00) | + (_sprite3.CollideSprite ? 0x08 : 0x00) | + (_sprite4.CollideSprite ? 0x10 : 0x00) | + (_sprite5.CollideSprite ? 0x20 : 0x00) | + (_sprite6.CollideSprite ? 0x40 : 0x00) | + (_sprite7.CollideSprite ? 0x80 : 0x00), + 0x1F => (_sprite0.CollideData ? 0x01 : 0x00) | + (_sprite1.CollideData ? 0x02 : 0x00) | + (_sprite2.CollideData ? 0x04 : 0x00) | + (_sprite3.CollideData ? 0x08 : 0x00) | + (_sprite4.CollideData ? 0x10 : 0x00) | + (_sprite5.CollideData ? 0x20 : 0x00) | + (_sprite6.CollideData ? 0x40 : 0x00) | + (_sprite7.CollideData ? 0x80 : 0x00), + 0x20 => 0xF0 | _borderColor & 0x0F, + 0x21 => 0xF0 | _backgroundColor0 & 0x0F, + 0x22 => 0xF0 | _backgroundColor1 & 0x0F, + 0x23 => 0xF0 | _backgroundColor2 & 0x0F, + 0x24 => 0xF0 | _backgroundColor3 & 0x0F, + 0x25 => 0xF0 | _spriteMulticolor0 & 0x0F, + 0x26 => 0xF0 | _spriteMulticolor1 & 0x0F, + 0x27 or 0x28 or 0x29 or 0x2A or 0x2B or 0x2C or 0x2D or 0x2E => 0xF0 | _sprites[addr - 0x27].Color & 0xF, + _ => 0xFF, + }; } public void Write(int addr, int val) diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.Render.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.Render.cs index ee9173cf551..e83a2b8af6b 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.Render.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.Render.cs @@ -82,21 +82,13 @@ void PostRenderBorder() } else { - switch (((_srColor0 & SrMask1) >> 18) | ((_srColor1 & SrMask1) >> 17)) + _pixel = (((_srColor0 & SrMask1) >> 18) | ((_srColor1 & SrMask1) >> 17)) switch { - case 1: - _pixel = _idle ? 0 : _backgroundColor1; - break; - case 2: - _pixel = _idle ? 0 : _backgroundColor2; - break; - case 3: - _pixel = _idle ? 0 : _backgroundColor3; - break; - default: - _pixel = _backgroundColor0; - break; - } + 1 => _idle ? 0 : _backgroundColor1, + 2 => _idle ? 0 : _backgroundColor2, + 3 => _idle ? 0 : _backgroundColor3, + _ => _backgroundColor0, + }; } // render sprites diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.State.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.State.cs index da5b50f4059..369fdfc847f 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.State.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.State.cs @@ -138,13 +138,13 @@ public void HardReset() _yScroll = 0; // reset sprites - for (var i = 0; i < 8; i++) + for (int i = 0; i < 8; i++) { _sprites[i].HardReset(); } // clear C buffer - for (var i = 0; i < 40; i++) + for (int i = 0; i < 40; i++) { _bufferC[i] = 0; } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.TimingBuilder.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.TimingBuilder.cs index 9a3109db89c..4168ef6fa84 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.TimingBuilder.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.TimingBuilder.cs @@ -28,10 +28,10 @@ public sealed partial class Vic // pre-display operations happen, and Cycle55 is the X-raster position where post-display operations happen. public static int[] TimingBuilder_Act(int[] timing, int cycle14, int sprite0Ba, int sprDisp) { - var result = new List(); + List result = new(); - var length = timing.Length; - for (var i = 0; i < length; i++) + int length = timing.Length; + for (int i = 0; i < length; i++) { while (i < result.Count) i++; @@ -40,7 +40,7 @@ public static int[] TimingBuilder_Act(int[] timing, int cycle14, int sprite0Ba, else result.Add(0); } - for (var i = 0; i < length; i++) + for (int i = 0; i < length; i++) { // pipeline raster X delay if (timing[(i + 1) % length] == timing[i]) @@ -75,11 +75,11 @@ public static int[] TimingBuilder_Act(int[] timing, int cycle14, int sprite0Ba, public static int[] TimingBuilder_BA(int[] fetch) { const int baRestart = 7; - var start = 0; - var length = fetch.Length; - var result = new int[length]; - var spriteBa = new int[8]; - var charBa = 0; + int start = 0; + int length = fetch.Length; + int[] result = new int[length]; + int[] spriteBa = new int[8]; + int charBa = 0; while (true) { @@ -97,18 +97,18 @@ public static int[] TimingBuilder_BA(int[] fetch) if (start < 0) start += length; - var offset = start; + int offset = start; while (true) { - var ba = BaTypeNone; + int ba = BaTypeNone; if (fetch[offset] == FetchTypeColor) charBa = baRestart; else if ((fetch[offset] & 0xFF00) == FetchTypeSprite) spriteBa[fetch[offset] & 0x007] = baRestart; - for (var i = 0; i < 8; i++) + for (int i = 0; i < 8; i++) { if (spriteBa[i] > 0) { @@ -135,7 +135,7 @@ public static int[] TimingBuilder_BA(int[] fetch) break; } - for (var i = 0; i < length; i += 2) + for (int i = 0; i < length; i += 2) { result[i] = result[i + 1]; } @@ -146,16 +146,16 @@ public static int[] TimingBuilder_BA(int[] fetch) // This builds a table of the fetch operations to take on each half-cycle. public static int[] TimingBuilder_Fetch(int[] timing, int sprite) { - var length = timing.Length; - var result = new int[length]; - var index = -1; - var refreshCounter = 0; - var spriteActive = false; - var spriteIndex = 0; - var spritePhase = 0; - var charCounter = 0; - - for (var i = 0; i < length; i++) + int length = timing.Length; + int[] result = new int[length]; + int index = -1; + int refreshCounter = 0; + bool spriteActive = false; + int spriteIndex = 0; + int spritePhase = 0; + int charCounter = 0; + + for (int i = 0; i < length; i++) { result[i++] = FetchTypeIdle; result[i] = FetchTypeNone; @@ -166,7 +166,7 @@ public static int[] TimingBuilder_Fetch(int[] timing, int sprite) index++; if (index >= length) index -= length; - var offset = timing[index]; + int offset = timing[index]; if (charCounter > 0) { @@ -217,8 +217,8 @@ private static int TimingBuilder_ScreenHeight(int vblankStart, int vblankEnd, in return lines; } - var offset = vblankEnd; - var result = 0; + int offset = vblankEnd; + int result = 0; while (true) { if (offset >= lines) @@ -238,9 +238,9 @@ private static int TimingBuilder_ScreenWidth(IList timing, int hblankStart, return timing.Count * 4; } - var length = timing.Count; - var result = 0; - var offset = 0; + int length = timing.Count; + int result = 0; + int offset = 0; while (timing[offset] != hblankEnd) { offset = (offset + 1) % length; } while (timing[offset] != hblankStart) { offset = (offset + 1) % length; result++; } @@ -254,13 +254,13 @@ private static int TimingBuilder_ScreenWidth(IList timing, int hblankStart, // (specifically on an NTSC 6567R8) and DelayAmount is the number of positions to lag. public static int[] TimingBuilder_XRaster(int start, int width, int count, int delayOffset, int delayAmount) { - var result = new List(); - var rasterX = start; - var delayed = false; + List result = new(); + int rasterX = start; + bool delayed = false; count >>= 2; delayAmount >>= 2; - for (var i = 0; i < count; i++) + for (int i = 0; i < count; i++) { result.Add(rasterX); diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.VideoProvider.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.VideoProvider.cs index 3adf339c765..8d8c333c54c 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.VideoProvider.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.VideoProvider.cs @@ -7,11 +7,8 @@ public sealed partial class Vic : IVideoProvider { private static readonly int BgColor = Colors.ARGB(0, 0, 0); private int[] _buf; - private int _bufHeight; private int _bufLength; private int _bufOffset; - private int _bufWidth; - private const int PixBufferSize = 24; private const int PixBorderBufferSize = 12; @@ -47,14 +44,11 @@ public sealed partial class Vic : IVideoProvider public int BackgroundColor => BgColor; - public int BufferHeight => _bufHeight; + public int BufferHeight { get; private set; } - public int BufferWidth => _bufWidth; + public int BufferWidth { get; private set; } - public int[] GetVideoBuffer() - { - return _buf; - } + public int[] GetVideoBuffer() => _buf; public int VirtualWidth { get; private set; } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.cs index b1159ee6431..1eeb69eed3e 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Vic.cs @@ -25,11 +25,10 @@ Commodore VIC-II 6567/6569/6572 core. public Func ReadColorRam; public Func ReadMemory; - public bool ReadAec() { return _pinAec; } - public bool ReadBa() { return _pinBa; } - public bool ReadIrq() { return (_irqBuffer & 1) == 0; } + public bool ReadAec() => _pinAec; + public bool ReadBa() => _pinBa; + public bool ReadIrq() => (_irqBuffer & 1) == 0; - private readonly int _cyclesPerSec; private readonly int[] _rasterXPipeline; private readonly int[] _fetchPipeline; private readonly int[] _baPipeline; @@ -48,7 +47,7 @@ public Vic(int newCycles, int newLines, IList newPipeline, int newCyclesP { Util.DebugWriteLine("C64 VIC timings:"); Util.DebugWriteLine("RX FTCH BA ACT"); - for (var i = 0; i < newPipeline[0].Length; i++) + for (int i = 0; i < newPipeline[0].Length; i++) { Util.DebugWriteLine("{0:x4} {1:x4} {2:x4} {3:x8}", newPipeline[0][i], newPipeline[1][i], newPipeline[2][i], newPipeline[3][i]); } @@ -62,12 +61,12 @@ public Vic(int newCycles, int newLines, IList newPipeline, int newCyclesP _actPipeline = newPipeline[3]; _totalCycles = newCycles; _totalLines = newLines; - _cyclesPerSec = newCyclesPerSec; + CyclesPerSecond = newCyclesPerSec; ConfigureBlanking(newLines, hblankStart, hblankEnd, vblankStart, vblankEnd, borderType); _sprites = new Sprite[8]; - for (var i = 0; i < 8; i++) + for (int i = 0; i < 8; i++) _sprites[i] = new Sprite(i); _sprite0 = _sprites[0]; @@ -86,13 +85,13 @@ public Vic(int newCycles, int newLines, IList newPipeline, int newCyclesP private void ConfigureBlanking(int lines, int hblankStart, int hblankEnd, int vblankStart, int vblankEnd, C64.BorderType borderType) { - var newHblankStart = hblankStart; - var newHblankEnd = hblankEnd; - var newVblankStart = vblankStart; - var newVblankEnd = vblankEnd; - var hBorderSize = 16; // must be a multiple of 4 - var vBorderSize = hBorderSize * _pixelRatioNum / _pixelRatioDen; // to keep top and bottom in proportion - var maxWidth = _rasterXPipeline.Max(); + int newHblankStart = hblankStart; + int newHblankEnd = hblankEnd; + int newVblankStart = vblankStart; + int newVblankEnd = vblankEnd; + int hBorderSize = 16; // must be a multiple of 4 + int vBorderSize = hBorderSize * _pixelRatioNum / _pixelRatioDen; // to keep top and bottom in proportion + int maxWidth = _rasterXPipeline.Max(); switch (borderType) { @@ -156,12 +155,12 @@ private void ConfigureBlanking(int lines, int hblankStart, int hblankEnd, int vb _hblankEndCheckXRaster = newHblankEnd & 0xFFC; _vblankStart = newVblankStart; _vblankEnd = newVblankEnd; - _bufWidth = TimingBuilder_ScreenWidth(_rasterXPipeline, newHblankStart, newHblankEnd); - _bufHeight = TimingBuilder_ScreenHeight(newVblankStart, newVblankEnd, lines); - _buf = new int[_bufWidth * _bufHeight]; + BufferWidth = TimingBuilder_ScreenWidth(_rasterXPipeline, newHblankStart, newHblankEnd); + BufferHeight = TimingBuilder_ScreenHeight(newVblankStart, newVblankEnd, lines); + _buf = new int[BufferWidth * BufferHeight]; _bufLength = _buf.Length; - VirtualWidth = _bufWidth * _pixelRatioNum / _pixelRatioDen; - VirtualHeight = _bufHeight; + VirtualWidth = BufferWidth * _pixelRatioNum / _pixelRatioDen; + VirtualHeight = BufferHeight; } private int WrapValue(int min, int max, int val) @@ -171,7 +170,7 @@ private int WrapValue(int min, int max, int val) return min; } - var width = Math.Abs(min - max); + int width = Math.Abs(min - max); while (val > max) { val -= width; @@ -187,7 +186,7 @@ private int WrapValue(int min, int max, int val) public int CyclesPerFrame => _totalCycles * _totalLines; - public int CyclesPerSecond => _cyclesPerSec; + public int CyclesPerSecond { get; } public void ExecutePhase1() { @@ -336,10 +335,10 @@ private void UpdatePins() { // IRQ is treated as a delay line - var intIrq = (_enableIntRaster && _intRaster) ? 0x0002 : 0x0000; - var sdIrq = (_enableIntSpriteDataCollision & _intSpriteDataCollision) ? 0x0001 : 0x0000; - var ssIrq = (_enableIntSpriteCollision & _intSpriteCollision) ? 0x0001 : 0x0000; - var lpIrq = (_enableIntLightPen & _intLightPen) ? 0x0001 : 0x0000; + int intIrq = (_enableIntRaster && _intRaster) ? 0x0002 : 0x0000; + int sdIrq = (_enableIntSpriteDataCollision & _intSpriteDataCollision) ? 0x0001 : 0x0000; + int ssIrq = (_enableIntSpriteCollision & _intSpriteCollision) ? 0x0001 : 0x0000; + int lpIrq = (_enableIntLightPen & _intLightPen) ? 0x0001 : 0x0000; _irqBuffer >>= 1; _irqBuffer |= intIrq | sdIrq | ssIrq | lpIrq; diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Media/D64.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Media/D64.cs index 98ef0649cf1..0b81b543f43 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Media/D64.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Media/D64.cs @@ -89,10 +89,10 @@ private enum ErrorType private static byte Checksum(byte[] source) { - var count = source.Length; + int count = source.Length; byte result = 0; - for (var i = 0; i < count; i++) + for (int i = 0; i < count; i++) { result ^= source[i]; } @@ -102,8 +102,8 @@ private static byte Checksum(byte[] source) private static byte[] ConvertSectorToGcr(byte[] source, byte sectorNo, byte trackNo, byte formatA, byte formatB, int gapLength, ErrorType errorType, out int bitsWritten) { - using var mem = new MemoryStream(); - using var writer = new BinaryWriter(mem); + using MemoryStream mem = new(); + using BinaryWriter writer = new(mem); if (errorType == ErrorType.IdMismatch) { @@ -111,11 +111,11 @@ private static byte[] ConvertSectorToGcr(byte[] source, byte sectorNo, byte trac formatB ^= 0xFF; } - var headerChecksum = (byte)(sectorNo ^ trackNo ^ formatA ^ formatB ^ (errorType == ErrorType.HeaderChecksumError ? 0xFF : 0x00)); + byte headerChecksum = (byte)(sectorNo ^ trackNo ^ formatA ^ formatB ^ (errorType == ErrorType.HeaderChecksumError ? 0xFF : 0x00)); // assemble written data for GCR encoding - var writtenData = new byte[260]; - var syncBytes40 = Enumerable.Repeat((byte) (errorType == ErrorType.NoSyncSequence ? 0x00 : 0xFF), 5).ToArray(); + byte[] writtenData = new byte[260]; + byte[] syncBytes40 = Enumerable.Repeat((byte) (errorType == ErrorType.NoSyncSequence ? 0x00 : 0xFF), 5).ToArray(); Array.Copy(source, 0, writtenData, 1, 256); writtenData[0] = (byte)(errorType == ErrorType.HeaderNotFound ? 0x00 : 0x07); @@ -139,13 +139,13 @@ private static byte[] ConvertSectorToGcr(byte[] source, byte sectorNo, byte trac private static byte[] EncodeGcr(byte[] source) { // 4 bytes -> 5 GCR encoded bytes - var gcr = new int[8]; - var data = new byte[4]; - var count = source.Length; - using var mem = new MemoryStream(); - var writer = new BinaryWriter(mem); + int[] gcr = new int[8]; + byte[] data = new byte[4]; + int count = source.Length; + using MemoryStream mem = new(); + BinaryWriter writer = new(mem); - for (var i = 0; i < count; i += 4) + for (int i = 0; i < count; i += 4) { Array.Copy(source, i, data, 0, 4); gcr[0] = GcrEncodeTable[data[0] >> 4]; @@ -160,7 +160,7 @@ private static byte[] EncodeGcr(byte[] source) // -------- -------- -------- -------- -------- // 00000111 11222223 33334444 45555566 66677777 - var outputValue = (gcr[0] << 3) | (gcr[1] >> 2); + int outputValue = (gcr[0] << 3) | (gcr[1] >> 2); writer.Write((byte)(outputValue & 0xFF)); outputValue = (gcr[1] << 6) | (gcr[2] << 1) | (gcr[3] >> 4); writer.Write((byte)(outputValue & 0xFF)); @@ -177,15 +177,15 @@ private static byte[] EncodeGcr(byte[] source) public static Disk Read(byte[] source) { - var formatB = source[D64_DISK_ID_OFFSET + 0x00]; - var formatA = source[D64_DISK_ID_OFFSET + 0x01]; - - using var mem = new MemoryStream(source); - var reader = new BinaryReader(mem); - var trackDatas = new List(); - var trackLengths = new List(); - var trackNumbers = new List(); - var trackDensities = new List(); + byte formatB = source[D64_DISK_ID_OFFSET + 0x00]; + byte formatA = source[D64_DISK_ID_OFFSET + 0x01]; + + using MemoryStream mem = new(source); + BinaryReader reader = new(mem); + List trackDatas = new(); + List trackLengths = new(); + List trackNumbers = new(); + List trackDensities = new(); var errorType = ErrorType.NoError; int trackCount; int errorOffset = -1; @@ -210,24 +210,24 @@ public static Disk Read(byte[] source) throw new Exception("Not able to identify capacity of the D64 file."); } - for (var i = 0; i < trackCount; i++) + for (int i = 0; i < trackCount; i++) { if (errorOffset >= 0) { errorType = (ErrorType) source[errorOffset]; errorOffset++; } - var sectors = SectorsPerTrack[i]; - var trackLengthBits = 0; - using var trackMem = new MemoryStream(); - for (var j = 0; j < sectors; j++) + int sectors = SectorsPerTrack[i]; + int trackLengthBits = 0; + using MemoryStream trackMem = new(); + for (int j = 0; j < sectors; j++) { - var sectorData = reader.ReadBytes(256); - var diskData = ConvertSectorToGcr(sectorData, (byte)j, (byte)(i + 1), formatA, formatB, StandardSectorGapLength[DensityTable[i]], errorType, out var bitsWritten); + byte[] sectorData = reader.ReadBytes(256); + byte[] diskData = ConvertSectorToGcr(sectorData, (byte)j, (byte)(i + 1), formatA, formatB, StandardSectorGapLength[DensityTable[i]], errorType, out int bitsWritten); trackMem.Write(diskData, 0, diskData.Length); trackLengthBits += bitsWritten; } - var density = DensityTable[i]; + int density = DensityTable[i]; // we pad the tracks with extra gap bytes to meet MNIB standards while (trackMem.Length < StandardTrackLengthBytes[density]) diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Media/Disk.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Media/Disk.cs index 3ff51cd7703..98e4a6c9d04 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Media/Disk.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Media/Disk.cs @@ -39,7 +39,7 @@ public Disk(IList trackData, IList trackNumbers, IList trackDe { WriteProtected = true; _tracks = new int[trackCapacity][]; - for (var i = 0; i < trackData.Count; i++) + for (int i = 0; i < trackData.Count; i++) { _tracks[trackNumbers[i]] = ConvertToFluxTransitions(trackDensities[i], trackData[i], 0); } @@ -51,7 +51,7 @@ public Disk(IList trackData, IList trackNumbers, IList trackDe private int[] ConvertToFluxTransitions(int density, byte[] bytes, int fluxBitOffset) { - var paddedLength = bytes.Length; + int paddedLength = bytes.Length; switch (density) { case 3: @@ -69,28 +69,28 @@ private int[] ConvertToFluxTransitions(int density, byte[] bytes, int fluxBitOff } paddedLength++; - var paddedBytes = new byte[paddedLength]; + byte[] paddedBytes = new byte[paddedLength]; Array.Copy(bytes, paddedBytes, bytes.Length); - for (var i = bytes.Length; i < paddedLength; i++) + for (int i = bytes.Length; i < paddedLength; i++) { paddedBytes[i] = 0xAA; } - var result = new int[FluxEntriesPerTrack]; - var lengthBits = (paddedLength * 8) - 7; - var offsets = new List(); - var remainingBits = lengthBits; + int[] result = new int[FluxEntriesPerTrack]; + int lengthBits = (paddedLength * 8) - 7; + List offsets = new(); + int remainingBits = lengthBits; const long bitsNum = FluxEntriesPerTrack * FluxBitsPerEntry; long bitsDen = lengthBits; - for (var i = 0; i < paddedLength; i++) + for (int i = 0; i < paddedLength; i++) { - var byteData = paddedBytes[i]; - for (var j = 0; j < 8; j++) + byte byteData = paddedBytes[i]; + for (int j = 0; j < 8; j++) { - var offset = fluxBitOffset + ((i * 8 + j) * bitsNum / bitsDen); - var byteOffset = (int)(offset / FluxBitsPerEntry); - var bitOffset = (int)(offset % FluxBitsPerEntry); + long offset = fluxBitOffset + ((i * 8 + j) * bitsNum / bitsDen); + int byteOffset = (int)(offset / FluxBitsPerEntry); + int bitOffset = (int)(offset % FluxBitsPerEntry); offsets.Add(offset); result[byteOffset] |= ((byteData & 0x80) != 0 ? 1 : 0) << bitOffset; byteData <<= 1; @@ -113,7 +113,7 @@ private int[] ConvertToFluxTransitions(int density, byte[] bytes, int fluxBitOff private void FillMissingTracks() { // Fill half tracks (should assist with EA "fat-track" protections) - for (var i = 1; i < _tracks.Length; i += 2) + for (int i = 1; i < _tracks.Length; i += 2) { if (_tracks[i] == null && _tracks[i - 1] != null) { @@ -123,7 +123,7 @@ private void FillMissingTracks() } // Fill vacant tracks - for (var i = 0; i < _tracks.Length; i++) + for (int i = 0; i < _tracks.Length; i++) { if (_tracks[i] == null) { @@ -149,7 +149,7 @@ public void AttachTracker(bool[] usedTracks) /// callback public void DeltaUpdate(Action deltaUpdateCallback) { - for (var i = 0; i < _tracks.Length; i++) + for (int i = 0; i < _tracks.Length; i++) { if (_usedTracks[i]) { @@ -164,9 +164,6 @@ public int[] GetDataForTrack(int halftrack) return _tracks[halftrack]; } - public void SyncState(Serializer ser) - { - ser.Sync(nameof(WriteProtected), ref WriteProtected); - } + public void SyncState(Serializer ser) => ser.Sync(nameof(WriteProtected), ref WriteProtected); } } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Media/DiskBuilder.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Media/DiskBuilder.cs index 778670a31f8..fb603031008 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Media/DiskBuilder.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Media/DiskBuilder.cs @@ -24,7 +24,7 @@ protected class BamEntry public BamEntry(int sectors) { Data = 0; - for (var i = 0; i < sectors; i++) + for (int i = 0; i < sectors; i++) { Data >>= 1; Data |= 0x800000; @@ -45,7 +45,7 @@ private int GetBit(int sector) public void Allocate(int sector) { - var bit = GetBit(sector); + int bit = GetBit(sector); if (bit != 0 && (Data & bit) != 0) { Data &= ~bit; @@ -55,7 +55,7 @@ public void Allocate(int sector) public void Free(int sector) { - var bit = GetBit(sector); + int bit = GetBit(sector); if (bit != 0 && (Data & bit) == 0) { Data |= bit; @@ -81,10 +81,7 @@ public bool this[int sector] } } - public byte[] GetBytes() - { - return GetBytesEnumerable().ToArray(); - } + public byte[] GetBytes() => GetBytesEnumerable().ToArray(); private IEnumerable GetBytesEnumerable() { @@ -98,8 +95,8 @@ public IEnumerable Entries { get { - var d = Data; - for (var i = 0; i < Sectors; i++) + int d = Data; + for (int i = 0; i < Sectors; i++) { d <<= 1; yield return (d & 0x1000000) != 0; @@ -155,11 +152,11 @@ public DiskBuilder() public Disk Build() { const int tracks = 35; - var trackByteOffsets = new int[tracks]; - var bam = new BamEntry[tracks]; - var diskFull = false; + int[] trackByteOffsets = new int[tracks]; + BamEntry[] bam = new BamEntry[tracks]; + bool diskFull = false; - for (var i = 0; i < tracks; i++) + for (int i = 0; i < tracks; i++) { bam[i] = new BamEntry(SectorsPerTrack[i]); if (i > 0) @@ -167,23 +164,23 @@ public Disk Build() trackByteOffsets[i] = trackByteOffsets[i - 1] + (SectorsPerTrack[i - 1] * 256); } } - var bytes = new byte[trackByteOffsets[tracks - 1] + (SectorsPerTrack[tracks - 1] * 256)]; + byte[] bytes = new byte[trackByteOffsets[tracks - 1] + (SectorsPerTrack[tracks - 1] * 256)]; - var currentTrack = 16; - var currentSector = 0; - var interleaveStart = 0; - var sectorInterleave = 3; - var directory = new List(); + int currentTrack = 16; + int currentSector = 0; + int interleaveStart = 0; + int sectorInterleave = 3; + List directory = new(); - Func GetOutputOffset = (t, s) => trackByteOffsets[t] + (s * 256); + int GetOutputOffset(int t, int s) => trackByteOffsets[t] + (s * 256); foreach (var entry in Entries) { - var sourceOffset = 0; - var dataLength = entry.Data == null ? 0 : entry.Data.Length; - var lengthInSectors = dataLength / 254; - var dataRemaining = dataLength; - var directoryEntry = new LocatedEntry + int sourceOffset = 0; + int dataLength = entry.Data == null ? 0 : entry.Data.Length; + int lengthInSectors = dataLength / 254; + int dataRemaining = dataLength; + LocatedEntry directoryEntry = new() { Entry = entry, LengthInSectors = lengthInSectors + 1, @@ -194,7 +191,7 @@ public Disk Build() while (!diskFull) { - var outputOffset = GetOutputOffset(currentTrack, currentSector); + int outputOffset = GetOutputOffset(currentTrack, currentSector); if (dataRemaining > 254) { @@ -256,11 +253,11 @@ public Disk Build() } // write Directory - var directoryOffset = -(0x20); + int directoryOffset = -(0x20); currentTrack = 17; currentSector = 1; - var directoryOutputOffset = GetOutputOffset(currentTrack, currentSector); - var fileIndex = 0; + int directoryOutputOffset = GetOutputOffset(currentTrack, currentSector); + int fileIndex = 0; bam[currentTrack].Allocate(currentSector); foreach (var entry in directory) { @@ -279,12 +276,12 @@ public Disk Build() bytes[directoryOutputOffset + directoryOffset + 0x02] = (byte)((int)entry.Entry.Type | (entry.Entry.Locked ? 0x40 : 0x00) | (entry.Entry.Closed ? 0x80 : 0x00)); bytes[directoryOutputOffset + directoryOffset + 0x03] = (byte)(entry.Track + 1); bytes[directoryOutputOffset + directoryOffset + 0x04] = (byte)entry.Sector; - for (var i = 0x05; i <= 0x14; i++) + for (int i = 0x05; i <= 0x14; i++) { bytes[directoryOutputOffset + directoryOffset + i] = 0xA0; } - var fileNameBytes = Encoding.ASCII.GetBytes(entry.Entry.Name ?? $"FILE{fileIndex:D3}"); + byte[] fileNameBytes = Encoding.ASCII.GetBytes(entry.Entry.Name ?? $"FILE{fileIndex:D3}"); Array.Copy(fileNameBytes, 0, bytes, directoryOutputOffset + directoryOffset + 0x05, Math.Min(fileNameBytes.Length, 0x10)); bytes[directoryOutputOffset + directoryOffset + 0x1E] = (byte)(entry.LengthInSectors & 0xFF); bytes[directoryOutputOffset + directoryOffset + 0x1F] = (byte)((entry.LengthInSectors >> 8) & 0xFF); @@ -294,21 +291,21 @@ public Disk Build() bytes[directoryOutputOffset + 0x01] = 0xFF; // write BAM - var bamOutputOffset = GetOutputOffset(17, 0); + int bamOutputOffset = GetOutputOffset(17, 0); bytes[bamOutputOffset + 0x00] = 18; bytes[bamOutputOffset + 0x01] = 1; bytes[bamOutputOffset + 0x02] = (byte)VersionType; - for (var i = 0; i < 35; i++) + for (int i = 0; i < 35; i++) { Array.Copy(bam[i].GetBytes(), 0, bytes, bamOutputOffset + 4 + (i * 4), 4); } - for (var i = 0x90; i <= 0xAA; i++) + for (int i = 0x90; i <= 0xAA; i++) { bytes[bamOutputOffset + i] = 0xA0; } - var titleBytes = Encoding.ASCII.GetBytes(Title ?? "UNTITLED"); + byte[] titleBytes = Encoding.ASCII.GetBytes(Title ?? "UNTITLED"); Array.Copy(titleBytes, 0, bytes, bamOutputOffset + 0x90, Math.Min(titleBytes.Length, 0x10)); return D64.Read(bytes); diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Media/G64.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Media/G64.cs index ae875049ab4..70937fd7b21 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Media/G64.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Media/G64.cs @@ -9,13 +9,13 @@ public static class G64 { public static Disk Read(byte[] source) { - using var mem = new MemoryStream(source); - using var reader = new BinaryReader(mem); - var id = new string(reader.ReadChars(8)); - var trackDatas = new List(); - var trackLengths = new List(); - var trackNumbers = new List(); - var trackDensities = new List(); + using MemoryStream mem = new(source); + using BinaryReader reader = new(mem); + string id = new(reader.ReadChars(8)); + List trackDatas = new(); + List trackLengths = new(); + List trackNumbers = new(); + List trackDensities = new(); if (id == @"GCR-1541") { @@ -23,26 +23,26 @@ public static Disk Read(byte[] source) int trackCount = reader.ReadByte(); reader.ReadInt16(); // max track size in bytes - var trackOffsetTable = new int[trackCount]; - var trackSpeedTable = new int[trackCount]; + int[] trackOffsetTable = new int[trackCount]; + int[] trackSpeedTable = new int[trackCount]; - for (var i = 0; i < trackCount; i++) + for (int i = 0; i < trackCount; i++) { trackOffsetTable[i] = reader.ReadInt32(); } - for (var i = 0; i < trackCount; i++) + for (int i = 0; i < trackCount; i++) { trackSpeedTable[i] = reader.ReadInt32(); } - for (var i = 0; i < trackCount; i++) + for (int i = 0; i < trackCount; i++) { if (trackOffsetTable[i] > 0) { mem.Position = trackOffsetTable[i]; int trackLength = reader.ReadInt16(); - var trackData = reader.ReadBytes(trackLength); + byte[] trackData = reader.ReadBytes(trackLength); trackDatas.Add(trackData); trackLengths.Add(trackLength * 8); @@ -51,7 +51,7 @@ public static Disk Read(byte[] source) } } - if (trackSpeedTable.Any(ts => ts > 3 || ts < 0)) + if (trackSpeedTable.Any(ts => ts is > 3 or < 0)) { throw new Exception("Byte-level speeds are not yet supported in the G64 loader."); } @@ -69,10 +69,10 @@ public static byte[] Write(IList trackData, IList trackNumbers, ILi const int headerLength = 0xC; const byte dataFillerValue = 0xFF; - var trackMaxLength = (ushort)Math.Max(7928, trackData.Max(d => d.Length)); + ushort trackMaxLength = (ushort)Math.Max(7928, trackData.Max(d => d.Length)); - using var mem = new MemoryStream(); - using var writer = new BinaryWriter(mem); + using MemoryStream mem = new(); + using BinaryWriter writer = new(mem); // header ID writer.Write("GCR-1541".ToCharArray()); @@ -87,22 +87,22 @@ public static byte[] Write(IList trackData, IList trackNumbers, ILi writer.Write(trackMaxLength); // combine track data - var offsets = new List(); - var densities = new List(); - using (var trackMem = new MemoryStream()) + List offsets = new(); + List densities = new(); + using (MemoryStream trackMem = new()) { - var trackMemWriter = new BinaryWriter(trackMem); - for (var i = 0; i < trackCount; i++) + BinaryWriter trackMemWriter = new(trackMem); + for (int i = 0; i < trackCount; i++) { if (trackNumbers.Contains(i)) { - var trackIndex = trackNumbers.IndexOf(i); + int trackIndex = trackNumbers.IndexOf(i); offsets.Add((int)trackMem.Length); densities.Add(trackDensities[trackIndex]); - var data = trackData[trackIndex]; - var buffer = Enumerable.Repeat(dataFillerValue, trackMaxLength).ToArray(); - var dataBytes = data.Select(d => unchecked(d)).ToArray(); + byte[] data = trackData[trackIndex]; + byte[] buffer = Enumerable.Repeat(dataFillerValue, trackMaxLength).ToArray(); + byte[] dataBytes = data.Select(d => unchecked(d)).ToArray(); Array.Copy(dataBytes, buffer, dataBytes.Length); trackMemWriter.Write((ushort)dataBytes.Length); trackMemWriter.Write(buffer); @@ -116,13 +116,13 @@ public static byte[] Write(IList trackData, IList trackNumbers, ILi trackMemWriter.Flush(); // offset table - foreach (var offset in offsets.Select(o => o >= 0 ? o + headerLength + trackCount * 8 : 0)) + foreach (int offset in offsets.Select(o => o >= 0 ? o + headerLength + trackCount * 8 : 0)) { writer.Write(offset); } // speed zone data - foreach (var density in densities) + foreach (int density in densities) { writer.Write(density); } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Media/PRG.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Media/PRG.cs index a3d5806af89..a1cf74ff412 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Media/PRG.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Media/PRG.cs @@ -6,14 +6,14 @@ public static class Prg { public static void Load(Chip90611401 pla, byte[] prgFile) { - var length = prgFile.Length; + int length = prgFile.Length; if (length <= 2) { return; } - var addr = prgFile[0] | (prgFile[1] << 8); - var offset = 2; + int addr = prgFile[0] | (prgFile[1] << 8); + int offset = 2; unchecked { while (offset < length) diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Media/Tape.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Media/Tape.cs index 529b893b09a..eb2f4dc62f3 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Media/Tape.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Media/Tape.cs @@ -6,7 +6,6 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64.Media { public class Tape { - private readonly byte[] _tapeData; private readonly byte _version; private readonly int _start; private readonly int _end; @@ -20,7 +19,7 @@ public class Tape public Tape(byte version, byte[] tapeData, int start, int end) { _version = version; - _tapeData = tapeData; + TapeDataDomain = tapeData; _start = start; _end = end; Rewind(); @@ -36,7 +35,7 @@ public void ExecuteCycle() return; } - _cycle = _tapeData[_pos++] * 8; + _cycle = TapeDataDomain[_pos++] * 8; if (_cycle == 0) { if (_version == 0) @@ -45,7 +44,7 @@ public void ExecuteCycle() } else { - _cycle = (int)(BitConverter.ToUInt32(_tapeData, _pos - 1) >> 8); + _cycle = (int)(BitConverter.ToUInt32(TapeDataDomain, _pos - 1) >> 8); _pos += 3; if (_cycle == 0) { @@ -69,10 +68,7 @@ public void Rewind() } // Reads from tape, this will tell the caller if the flag pin should be raised - public bool Read() - { - return _data; - } + public bool Read() => _data; // Try to construct a tape file from file data. Returns null if not a tape file, throws exceptions for bad tape files. // (Note that some error conditions aren't caught right here.) @@ -82,13 +78,13 @@ public static Tape Load(byte[] tapeFile) if (Encoding.ASCII.GetString(tapeFile, 0, 12) == "C64-TAPE-RAW") { - var version = tapeFile[12]; + byte version = tapeFile[12]; if (version > 1) { throw new Exception("This tape has an unsupported version"); } - var size = BitConverter.ToUInt32(tapeFile, 16); + uint size = BitConverter.ToUInt32(tapeFile, 16); if (size + 20 != tapeFile.Length) { throw new Exception("Tape file header specifies a length that doesn't match the file size"); @@ -113,6 +109,6 @@ public void SyncState(Serializer ser) } // Exposed for memory domains, should not be used for actual emulation implementation - public byte[] TapeDataDomain => _tapeData; + public byte[] TapeDataDomain { get; } } } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Serial/Drive1541.IDebuggable.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Serial/Drive1541.IDebuggable.cs index 534b86217e8..7fb21056878 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Serial/Drive1541.IDebuggable.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Serial/Drive1541.IDebuggable.cs @@ -53,15 +53,11 @@ void IDebuggable.SetCpuRegister(string register, int value) bool IDebuggable.CanStep(StepType type) { - switch (type) + return type switch { - case StepType.Into: - case StepType.Over: - case StepType.Out: - return DebuggerStep != null; - default: - return false; - } + StepType.Into or StepType.Over or StepType.Out => DebuggerStep != null, + _ => false, + }; } void IDebuggable.Step(StepType type) @@ -97,11 +93,11 @@ private void StepInto() private void StepOver() { - var instruction = CpuPeek(_cpu.PC); + byte instruction = CpuPeek(_cpu.PC); if (instruction == Jsr) { - var destination = _cpu.PC + JsrSize; + int destination = _cpu.PC + JsrSize; while (_cpu.PC != destination) { StepInto(); @@ -115,8 +111,8 @@ private void StepOver() private void StepOut() { - var instructionsBeforeBailout = 1000000; - var instr = CpuPeek(_cpu.PC); + int instructionsBeforeBailout = 1000000; + byte instr = CpuPeek(_cpu.PC); _jsrCount = instr == Jsr ? 1 : 0; while (--instructionsBeforeBailout > 0) @@ -133,7 +129,7 @@ private void StepOut() _jsrCount = 0; break; } - else if (instr == Rts || instr == Rti) + else if (instr is Rts or Rti) { _jsrCount--; } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Serial/Drive1541.IDisassemblable.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Serial/Drive1541.IDisassemblable.cs index c8c159933e1..861810a2a05 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Serial/Drive1541.IDisassemblable.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Serial/Drive1541.IDisassemblable.cs @@ -21,9 +21,6 @@ string IDisassemblable.Cpu string IDisassemblable.PCRegisterName => "PC"; - string IDisassemblable.Disassemble(MemoryDomain m, uint addr, out int length) - { - return Components.M6502.MOS6502X.Disassemble((ushort)addr, out length, CpuPeek); - } + string IDisassemblable.Disassemble(MemoryDomain m, uint addr, out int length) => Components.M6502.MOS6502X.Disassemble((ushort)addr, out length, CpuPeek); } } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Serial/Drive1541.Registers.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Serial/Drive1541.Registers.cs index 44259d3899d..2a2b18b822f 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Serial/Drive1541.Registers.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Serial/Drive1541.Registers.cs @@ -1,53 +1,40 @@ -namespace BizHawk.Emulation.Cores.Computers.Commodore64.Serial +namespace BizHawk.Emulation.Cores.Computers.Commodore64.Serial { public sealed partial class Drive1541 { private int _overflowFlagDelaySr; - private byte CpuPeek(ushort addr) - { - return unchecked((byte)Peek(addr)); - } + private byte CpuPeek(ushort addr) => unchecked((byte)Peek(addr)); - private byte CpuRead(ushort addr) - { - return unchecked((byte)Read(addr)); - } +#pragma warning disable IDE0051 + private byte CpuRead(ushort addr) => unchecked((byte)Read(addr)); - private void CpuWrite(ushort addr, byte val) - { - Write(addr, val); - } + private void CpuWrite(ushort addr, byte val) => Write(addr, val); +#pragma warning restore IDE0051 private bool ViaReadClock() { - var inputClock = ReadMasterClk(); - var outputClock = ReadDeviceClk(); + bool inputClock = ReadMasterClk(); + bool outputClock = ReadDeviceClk(); return !(inputClock && outputClock); } private bool ViaReadData() { - var inputData = ReadMasterData(); - var outputData = ReadDeviceData(); + bool inputData = ReadMasterData(); + bool outputData = ReadDeviceData(); return !(inputData && outputData); } private bool ViaReadAtn() { - var inputAtn = ReadMasterAtn(); + bool inputAtn = ReadMasterAtn(); return !inputAtn; } - private int ReadVia1PrA() - { - return _bitHistory & 0xFF; - } + private int ReadVia1PrA() => _bitHistory & 0xFF; - private int ReadVia1PrB() - { - return (_motorStep & 0x03) | (_motorEnabled ? 0x04 : 0x00) | (_sync ? 0x00 : 0x80) | (_diskWriteProtected ? 0x00 : 0x10); - } + private int ReadVia1PrB() => (_motorStep & 0x03) | (_motorEnabled ? 0x04 : 0x00) | (_sync ? 0x00 : 0x80) | (_diskWriteProtected ? 0x00 : 0x10); public int Peek(int addr) { @@ -72,15 +59,9 @@ public int Peek(int addr) return (addr >> 8) & 0xFF; } - public int PeekVia0(int addr) - { - return Via0.Peek(addr); - } + public int PeekVia0(int addr) => Via0.Peek(addr); - public int PeekVia1(int addr) - { - return Via1.Peek(addr); - } + public int PeekVia1(int addr) => Via1.Peek(addr); public void Poke(int addr, int val) { @@ -102,15 +83,9 @@ public void Poke(int addr, int val) } } - public void PokeVia0(int addr, int val) - { - Via0.Poke(addr, val); - } + public void PokeVia0(int addr, int val) => Via0.Poke(addr, val); - public void PokeVia1(int addr, int val) - { - Via1.Poke(addr, val); - } + public void PokeVia1(int addr, int val) => Via1.Poke(addr, val); public int Read(int addr) { @@ -157,25 +132,22 @@ public void Write(int addr, int val) public override bool ReadDeviceClk() { - var viaOutputClock = (Via0.DdrB & 0x08) != 0 && (Via0.PrB & 0x08) != 0; + bool viaOutputClock = (Via0.DdrB & 0x08) != 0 && (Via0.PrB & 0x08) != 0; return !viaOutputClock; } public override bool ReadDeviceData() { // PB1 (input not pulled up) - var viaOutputData = (Via0.DdrB & 0x02) != 0 && (Via0.PrB & 0x02) != 0; + bool viaOutputData = (Via0.DdrB & 0x02) != 0 && (Via0.PrB & 0x02) != 0; // inverted from c64, input, not pulled up to PB7/CA1 - var viaInputAtn = ViaReadAtn(); + bool viaInputAtn = ViaReadAtn(); // PB4 (input not pulled up) - var viaOutputAtna = (Via0.DdrB & 0x10) != 0 && (Via0.PrB & 0x10) != 0; + bool viaOutputAtna = (Via0.DdrB & 0x10) != 0 && (Via0.PrB & 0x10) != 0; return !(viaOutputAtna ^ viaInputAtn) && !viaOutputData; } - public override bool ReadDeviceLight() - { - return _driveLightOffTime > 0; - } + public override bool ReadDeviceLight() => _driveLightOffTime > 0; } } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Serial/Drive1541.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Serial/Drive1541.cs index 22fd03870af..8baad7f160f 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Serial/Drive1541.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Serial/Drive1541.cs @@ -33,7 +33,7 @@ public sealed partial class Drive1541 : SerialPortDevice, ISaveRam public Action DebuggerStep; public readonly Chip23128 DriveRom; - private struct CpuLink : IMOS6502XLink + private readonly struct CpuLink : IMOS6502XLink { private readonly Drive1541 _drive; @@ -42,15 +42,15 @@ public CpuLink(Drive1541 drive) _drive = drive; } - public byte DummyReadMemory(ushort address) => unchecked((byte)_drive.Read(address)); + public readonly byte DummyReadMemory(ushort address) => unchecked((byte)_drive.Read(address)); - public void OnExecFetch(ushort address) { } + public readonly void OnExecFetch(ushort address) { } - public byte PeekMemory(ushort address) => unchecked((byte)_drive.Peek(address)); + public readonly byte PeekMemory(ushort address) => unchecked((byte)_drive.Peek(address)); - public byte ReadMemory(ushort address) => unchecked((byte)_drive.Read(address)); + public readonly byte ReadMemory(ushort address) => unchecked((byte)_drive.Read(address)); - public void WriteMemory(ushort address, byte value) => _drive.Write(address, value); + public readonly void WriteMemory(ushort address, byte value) => _drive.Write(address, value); } public Drive1541(int clockNum, int clockDen, Func getCurrentDiskNumber) @@ -133,10 +133,10 @@ public override void SyncState(Serializer ser) SaveDeltas(); } - for (var i = 0; i < _usedDiskTracks.Length; i++) + for (int i = 0; i < _usedDiskTracks.Length; i++) { ser.Sync($"_usedDiskTracks{i}", ref _usedDiskTracks[i], useNull: false); - for (var j = 0; j < 84; j++) + for (int j = 0; j < 84; j++) { ser.Sync($"DiskDeltas{i},{j}", ref _diskDeltas[i, j], useNull: true); } @@ -204,7 +204,7 @@ public override void HardReset() Via0.HardReset(); Via1.HardReset(); _trackNumber = 34; - for (var i = 0; i < _ram.Length; i++) + for (int i = 0; i < _ram.Length; i++) { _ram[i] = 0x00; } @@ -272,7 +272,7 @@ public void InitSaveRam(int diskCount) { _usedDiskTracks = new bool[diskCount][]; _diskDeltas = new byte[diskCount, 84][]; - for (var i = 0; i < diskCount; i++) + for (int i = 0; i < diskCount; i++) { _usedDiskTracks[i] = new bool[84]; } @@ -284,13 +284,13 @@ public byte[] CloneSaveRam() { SaveDeltas(); // update the current deltas - using var ms = new MemoryStream(); - using var bw = new BinaryWriter(ms); + using MemoryStream ms = new(); + using BinaryWriter bw = new(ms); bw.Write(_usedDiskTracks.Length); - for (var i = 0; i < _usedDiskTracks.Length; i++) + for (int i = 0; i < _usedDiskTracks.Length; i++) { bw.WriteByteBuffer(_usedDiskTracks[i].ToUByteBuffer()); - for (var j = 0; j < 84; j++) + for (int j = 0; j < 84; j++) { bw.WriteByteBuffer(_diskDeltas[i, j]); } @@ -301,10 +301,10 @@ public byte[] CloneSaveRam() public void StoreSaveRam(byte[] data) { - using var ms = new MemoryStream(data, false); - using var br = new BinaryReader(ms); + using MemoryStream ms = new(data, false); + using BinaryReader br = new(ms); - var ndisks = br.ReadInt32(); + int ndisks = br.ReadInt32(); if (ndisks != _usedDiskTracks.Length) { throw new InvalidOperationException("Disk count mismatch!"); @@ -312,10 +312,10 @@ public void StoreSaveRam(byte[] data) ResetDeltas(); - for (var i = 0; i < _usedDiskTracks.Length; i++) + for (int i = 0; i < _usedDiskTracks.Length; i++) { _usedDiskTracks[i] = br.ReadByteBuffer(returnNull: false)!.ToBoolBuffer(); - for (var j = 0; j < 84; j++) + for (int j = 0; j < 84; j++) { _diskDeltas[i, j] = br.ReadByteBuffer(returnNull: true); } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Serial/SerialPort.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Serial/SerialPort.cs index 725d7111056..1f35db82def 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Serial/SerialPort.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Serial/SerialPort.cs @@ -39,20 +39,11 @@ public void ExecuteDeferred(int cycles) } } - public bool ReadDeviceClock() - { - return !_connected || _device.ReadDeviceClk(); - } + public bool ReadDeviceClock() => !_connected || _device.ReadDeviceClk(); - public bool ReadDeviceData() - { - return !_connected || _device.ReadDeviceData(); - } + public bool ReadDeviceData() => !_connected || _device.ReadDeviceData(); - public bool ReadDeviceLight() - { - return _connected && _device.ReadDeviceLight(); - } + public bool ReadDeviceLight() => _connected && _device.ReadDeviceLight(); public void SyncState(Serializer ser) { diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Serial/SerialPortDevice.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Serial/SerialPortDevice.cs index 657519f580f..af8659d475f 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/Serial/SerialPortDevice.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/Serial/SerialPortDevice.cs @@ -21,20 +21,11 @@ public virtual void HardReset() { } - public virtual bool ReadDeviceClk() - { - return true; - } + public virtual bool ReadDeviceClk() => true; - public virtual bool ReadDeviceData() - { - return true; - } + public virtual bool ReadDeviceData() => true; - public virtual bool ReadDeviceLight() - { - return false; - } + public virtual bool ReadDeviceLight() => false; public abstract void SyncState(Serializer ser); } diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/User/UserPort.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/User/UserPort.cs index e92642d09cf..6661d9bb40e 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/User/UserPort.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/User/UserPort.cs @@ -42,30 +42,15 @@ public void HardReset() } } - public bool ReadAtn() - { - return !_connected || _device.ReadAtn(); - } + public bool ReadAtn() => !_connected || _device.ReadAtn(); - public int ReadData() - { - return !_connected ? 0xFF : _device.ReadData(); - } + public int ReadData() => !_connected ? 0xFF : _device.ReadData(); - public bool ReadFlag2() - { - return !_connected || _device.ReadFlag2(); - } + public bool ReadFlag2() => !_connected || _device.ReadFlag2(); - public bool ReadPa2() - { - return !_connected || _device.ReadPa2(); - } + public bool ReadPa2() => !_connected || _device.ReadPa2(); - public bool ReadReset() - { - return !_connected || _device.ReadReset(); - } + public bool ReadReset() => !_connected || _device.ReadReset(); public void SyncState(Serializer ser) { diff --git a/src/BizHawk.Emulation.Cores/Computers/Commodore64/User/UserPortDevice.cs b/src/BizHawk.Emulation.Cores/Computers/Commodore64/User/UserPortDevice.cs index c47b13d5048..a10521694a9 100644 --- a/src/BizHawk.Emulation.Cores/Computers/Commodore64/User/UserPortDevice.cs +++ b/src/BizHawk.Emulation.Cores/Computers/Commodore64/User/UserPortDevice.cs @@ -16,30 +16,15 @@ public virtual void HardReset() // note: this will not disconnect any attached media } - public virtual bool ReadAtn() - { - return true; - } + public virtual bool ReadAtn() => true; - public virtual int ReadData() - { - return 0xFF; - } + public virtual int ReadData() => 0xFF; - public virtual bool ReadFlag2() - { - return true; - } + public virtual bool ReadFlag2() => true; - public virtual bool ReadPa2() - { - return true; - } + public virtual bool ReadPa2() => true; - public virtual bool ReadReset() - { - return true; - } + public virtual bool ReadReset() => true; public abstract void SyncState(Serializer ser); } diff --git a/src/BizHawk.Emulation.Cores/Computers/MSX/MSX.IEmulator.cs b/src/BizHawk.Emulation.Cores/Computers/MSX/MSX.IEmulator.cs index a7d147424bf..cb49cdc1bac 100644 --- a/src/BizHawk.Emulation.Cores/Computers/MSX/MSX.IEmulator.cs +++ b/src/BizHawk.Emulation.Cores/Computers/MSX/MSX.IEmulator.cs @@ -1,4 +1,4 @@ -using BizHawk.Emulation.Common; +using BizHawk.Emulation.Common; using System; namespace BizHawk.Emulation.Cores.Computers.MSX @@ -7,7 +7,7 @@ public partial class MSX : IEmulator, ISoundProvider, IVideoProvider { public IEmulatorServiceProvider ServiceProvider { get; } - public ControllerDefinition ControllerDefinition => current_controller; + public ControllerDefinition ControllerDefinition { get; } = null; public bool FrameAdvance(IController controller, bool render, bool rendersound) { @@ -29,7 +29,7 @@ public bool FrameAdvance(IController controller, bool render, bool rendersound) if (_controller.IsPressed("P2 B1")) ctrl2_byte -= 0x10; if (_controller.IsPressed("P2 B2")) ctrl2_byte -= 0x20; - if (current_controller == MSXControllerKB) { kb_rows_check(controller); } + if (ControllerDefinition == MSXControllerKB) { kb_rows_check(controller); } if (Tracer.IsEnabled()) { @@ -174,12 +174,14 @@ public void Dispose() } } - public BlipBuffer blip = new BlipBuffer(4500); + public BlipBuffer blip = new(4500); public int[] Aud = new int [9000]; public uint num_samp; + #pragma warning disable IDE0051 private const int blipbuffsize = 4500; + #pragma warning restore IDE0051 public bool CanProvideAsync => false; @@ -191,10 +193,7 @@ public void SetSyncMode(SyncSoundMode mode) } } - public void GetSamplesAsync(short[] samples) - { - throw new NotSupportedException("Async not supported"); - } + public void GetSamplesAsync(short[] samples) => throw new NotSupportedException("Async not supported"); public SyncSoundMode SyncMode => SyncSoundMode.Sync; @@ -220,19 +219,13 @@ public void GetSamplesSync(out short[] samples, out int nsamp) } } - public void DiscardSamples() - { - blip.Clear(); - } + public void DiscardSamples() => blip.Clear(); public int _frameHz = 60; public int[] _vidbuffer = new int[192 * 256]; - public int[] GetVideoBuffer() - { - return _vidbuffer; - } + public int[] GetVideoBuffer() => _vidbuffer; public int VirtualWidth => 256; public int VirtualHeight => 192; diff --git a/src/BizHawk.Emulation.Cores/Computers/MSX/MSX.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Computers/MSX/MSX.IMemoryDomains.cs index 1d9d6e69ab3..6ac8f87093a 100644 --- a/src/BizHawk.Emulation.Cores/Computers/MSX/MSX.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Computers/MSX/MSX.IMemoryDomains.cs @@ -8,12 +8,12 @@ namespace BizHawk.Emulation.Cores.Computers.MSX public partial class MSX { private MemoryDomainList MemoryDomains; - private readonly Dictionary _byteArrayDomains = new Dictionary(); + private readonly Dictionary _byteArrayDomains = new(); private bool _memoryDomainsInit = false; private void SetupMemoryDomains() { - var domains = new List + List domains = new() { new MemoryDomainDelegate( "System Bus", @@ -40,7 +40,7 @@ private void SetupMemoryDomains() if (SaveRAM != null) { - var saveRamDomain = new MemoryDomainDelegate("Save RAM", SaveRAM.Length, MemoryDomain.Endian.Little, + MemoryDomainDelegate saveRamDomain = new("Save RAM", SaveRAM.Length, MemoryDomain.Endian.Little, addr => SaveRAM[addr], (addr, value) => { SaveRAM[addr] = value; SaveRamModified = true; }, 1); domains.Add(saveRamDomain); @@ -54,10 +54,7 @@ private void SetupMemoryDomains() _memoryDomainsInit = true; } - private void SyncAllByteArrayDomains() - { - SyncByteArrayDomain("ROM", RomData); - } + private void SyncAllByteArrayDomains() => SyncByteArrayDomain("ROM", RomData); private void SyncByteArrayDomain(string name, byte[] data) { @@ -68,7 +65,7 @@ private void SyncByteArrayDomain(string name, byte[] data) } else { - var m = new MemoryDomainByteArray(name, MemoryDomain.Endian.Little, data, true, 1); + MemoryDomainByteArray m = new(name, MemoryDomain.Endian.Little, data, true, 1); _byteArrayDomains.Add(name, m); } } diff --git a/src/BizHawk.Emulation.Cores/Computers/MSX/MSX.ISaveRam.cs b/src/BizHawk.Emulation.Cores/Computers/MSX/MSX.ISaveRam.cs index e9f89ac306d..f5b40c25f04 100644 --- a/src/BizHawk.Emulation.Cores/Computers/MSX/MSX.ISaveRam.cs +++ b/src/BizHawk.Emulation.Cores/Computers/MSX/MSX.ISaveRam.cs @@ -6,10 +6,7 @@ namespace BizHawk.Emulation.Cores.Computers.MSX { public partial class MSX : ISaveRam { - public byte[] CloneSaveRam() - { - return (byte[]) SaveRAM?.Clone(); - } + public byte[] CloneSaveRam() => (byte[])SaveRAM?.Clone(); public void StoreSaveRam(byte[] data) { diff --git a/src/BizHawk.Emulation.Cores/Computers/MSX/MSX.ISettable.cs b/src/BizHawk.Emulation.Cores/Computers/MSX/MSX.ISettable.cs index 3a2983a1ac3..385cd2b9c1f 100644 --- a/src/BizHawk.Emulation.Cores/Computers/MSX/MSX.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Computers/MSX/MSX.ISettable.cs @@ -6,15 +6,9 @@ namespace BizHawk.Emulation.Cores.Computers.MSX { public partial class MSX : ISettable { - public MSXSettings GetSettings() - { - return Settings.Clone(); - } + public MSXSettings GetSettings() => Settings.Clone(); - public MSXSyncSettings GetSyncSettings() - { - return SyncSettings.Clone(); - } + public MSXSyncSettings GetSyncSettings() => SyncSettings.Clone(); public PutSettingsDirtyBits PutSettings(MSXSettings o) { @@ -46,20 +40,14 @@ public class MSXSettings [DefaultValue(true)] public bool DispOBJ { get; set; } - public MSXSettings Clone() - { - return (MSXSettings)MemberwiseClone(); - } + public MSXSettings Clone() => (MSXSettings)MemberwiseClone(); public MSXSettings() { SettingsUtil.SetDefaultValues(this); } - public static bool RebootNeeded(MSXSettings x, MSXSettings y) - { - return false; - } + public static bool RebootNeeded(MSXSettings x, MSXSettings y) => false; } public class MSXSyncSettings @@ -87,20 +75,14 @@ public enum RegionType public RegionType Region_Setting { get; set; } - public MSXSyncSettings Clone() - { - return (MSXSyncSettings)MemberwiseClone(); - } + public MSXSyncSettings Clone() => (MSXSyncSettings)MemberwiseClone(); public MSXSyncSettings() { SettingsUtil.SetDefaultValues(this); } - public static bool RebootNeeded(MSXSyncSettings x, MSXSyncSettings y) - { - return true; - } + public static bool RebootNeeded(MSXSyncSettings x, MSXSyncSettings y) => true; } } } diff --git a/src/BizHawk.Emulation.Cores/Computers/MSX/MSX.cs b/src/BizHawk.Emulation.Cores/Computers/MSX/MSX.cs index ad78413d0bf..e8da8a80dcc 100644 --- a/src/BizHawk.Emulation.Cores/Computers/MSX/MSX.cs +++ b/src/BizHawk.Emulation.Cores/Computers/MSX/MSX.cs @@ -24,10 +24,10 @@ public MSX(CoreLoadParameters lp) throw new NotSupportedException("Only MSX .rom files are supported!"); } - RomData = new byte[rom.RomData.Length]; - - // look up game in db before transforming ROM - var hash_md5 = MD5Checksum.ComputePrefixedHex(rom.RomData); + RomData = new byte[rom.RomData.Length]; + + // look up game in db before transforming ROM + string hash_md5 = MD5Checksum.ComputePrefixedHex(rom.RomData); var gi = Database.CheckDatabase(hash_md5); var dict = gi?.GetOptions(); @@ -149,18 +149,18 @@ public MSX(CoreLoadParameters lp) Disasm_Length = LibMSX.MSX_getdisasmlength(MSX_Pntr); Reg_String_Length = LibMSX.MSX_getregstringlength(MSX_Pntr); - var newHeader = new StringBuilder(Header_Length); + StringBuilder newHeader = new(Header_Length); LibMSX.MSX_getheader(MSX_Pntr, newHeader, Header_Length); Console.WriteLine(Header_Length + " " + Disasm_Length + " " + Reg_String_Length); Tracer = new TraceBuffer(newHeader.ToString()); - var serviceProvider = ServiceProvider as BasicServiceProvider; + BasicServiceProvider serviceProvider = ServiceProvider as BasicServiceProvider; serviceProvider.Register(Tracer); serviceProvider.Register(new StateSerializer(SyncState)); - current_controller = SyncSettings.Contr_Setting == MSXSyncSettings.ContrType.Keyboard ? MSXControllerKB : MSXControllerJS; + ControllerDefinition = SyncSettings.Contr_Setting == MSXSyncSettings.ContrType.Keyboard ? MSXControllerKB : MSXControllerJS; } public void HardReset() @@ -181,10 +181,7 @@ public void HardReset() private static byte[] RomData2; // Machine resources - private IController _controller = NullController.Instance; - - private readonly ControllerDefinition current_controller = null; - + private IController _controller = NullController.Instance; private int _frame = 0; public DisplayType Region => DisplayType.NTSC; @@ -194,14 +191,14 @@ public void HardReset() private LibMSX.TraceCallback tracecb; // these will be constant values assigned during core construction - private int Header_Length; + private readonly int Header_Length; private readonly int Disasm_Length; private readonly int Reg_String_Length; private void MakeTrace(int t) { - StringBuilder new_d = new StringBuilder(Disasm_Length); - StringBuilder new_r = new StringBuilder(Reg_String_Length); + StringBuilder new_d = new(Disasm_Length); + StringBuilder new_r = new(Reg_String_Length); LibMSX.MSX_getdisassembly(MSX_Pntr, new_d, t, Disasm_Length); LibMSX.MSX_getregisterstate(MSX_Pntr, new_r, t, Reg_String_Length); @@ -209,7 +206,7 @@ private void MakeTrace(int t) Tracer.Put(new(disassembly: new_d.ToString().PadRight(36), registerInfo: new_r.ToString())); } - private readonly MemoryCallbackSystem _memorycallbacks = new MemoryCallbackSystem(new[] { "System Bus" }); + private readonly MemoryCallbackSystem _memorycallbacks = new(new[] { "System Bus" }); public IMemoryCallbackSystem MemoryCallbacks => _memorycallbacks; } } diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Datacorder/DatacorderDevice.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Datacorder/DatacorderDevice.cs index eddac7f77a8..ba2b2411f05 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Datacorder/DatacorderDevice.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Datacorder/DatacorderDevice.cs @@ -48,13 +48,13 @@ public int CurrentDataBlockIndex { get { - if (_dataBlocks.Count > 0) { return _currentDataBlockIndex; } + if (DataBlocks.Count > 0) { return _currentDataBlockIndex; } else { return -1; } } set { if (value == _currentDataBlockIndex) { return; } - if (value < _dataBlocks.Count && value >= 0) + if (value < DataBlocks.Count && value >= 0) { _currentDataBlockIndex = value; _position = 0; @@ -70,7 +70,7 @@ public int Position { get { - if (_position >= _dataBlocks[_currentDataBlockIndex].DataPeriods.Count) { return 0; } + if (_position >= DataBlocks[_currentDataBlockIndex].DataPeriods.Count) { return 0; } return _position; } @@ -82,15 +82,7 @@ public int Position private bool _tapeIsPlaying = false; public bool TapeIsPlaying => _tapeIsPlaying; - /// - /// A list of the currently loaded data blocks - /// - private List _dataBlocks = new List(); - public List DataBlocks - { - get => _dataBlocks; - set => _dataBlocks = value; - } + public List DataBlocks { get; set; } = new(); /// /// Stores the last CPU t-state value @@ -111,16 +103,13 @@ public List DataBlocks /// Signs whether the device should autodetect when the Z80 has entered into /// 'load' mode and auto-play the tape if neccesary /// - private bool _autoPlay; + private readonly bool _autoPlay; /// /// Should be fired at the end of every frame /// Primary purpose is to detect tape traps and manage auto play /// - public void EndFrame() - { - MonitorFrame(); - } + public void EndFrame() => MonitorFrame(); /// /// Starts the tape playing from the beginning of the current block @@ -140,25 +129,25 @@ public void Play() _position = 0; if ( - _dataBlocks.Count > 0 && // data blocks are present && + DataBlocks.Count > 0 && // data blocks are present && _currentDataBlockIndex >= 0 // the current data block index is 1 or greater ) { - while (_position >= _dataBlocks[_currentDataBlockIndex].DataPeriods.Count) + while (_position >= DataBlocks[_currentDataBlockIndex].DataPeriods.Count) { // we are at the end of a data block - move to the next _position = 0; _currentDataBlockIndex++; // are we at the end of the tape? - if (_currentDataBlockIndex >= _dataBlocks.Count) + if (_currentDataBlockIndex >= DataBlocks.Count) { break; } } // check for end of tape - if (_currentDataBlockIndex >= _dataBlocks.Count) + if (_currentDataBlockIndex >= DataBlocks.Count) { // end of tape reached. Rewind to beginning AutoStopTape(); @@ -167,7 +156,7 @@ public void Play() } // update waitEdge with the current position in the current block - _waitEdge = _dataBlocks[_currentDataBlockIndex].DataPeriods[_position]; + _waitEdge = DataBlocks[_currentDataBlockIndex].DataPeriods[_position]; // sign that the tape is now playing _tapeIsPlaying = true; @@ -190,13 +179,13 @@ public void Stop() if ( _currentDataBlockIndex >= 0 && // we are at datablock 1 or above - _position >= _dataBlocks[_currentDataBlockIndex].DataPeriods.Count - 1 // the block is still playing back + _position >= DataBlocks[_currentDataBlockIndex].DataPeriods.Count - 1 // the block is still playing back ) { // move to the next block _currentDataBlockIndex++; - if (_currentDataBlockIndex >= _dataBlocks.Count) + if (_currentDataBlockIndex >= DataBlocks.Count) { _currentDataBlockIndex = -1; } @@ -207,7 +196,7 @@ public void Stop() if ( _currentDataBlockIndex < 0 && // block index is -1 - _dataBlocks.Count > 0 // number of blocks is greater than 0 + DataBlocks.Count > 0 // number of blocks is greater than 0 ) { // move the index on to 0 @@ -236,7 +225,7 @@ public void RTZ() /// public void SkipBlock(bool skipForward) { - int blockCount = _dataBlocks.Count; + int blockCount = DataBlocks.Count; int targetBlockId = _currentDataBlockIndex; if (skipForward) @@ -264,11 +253,11 @@ public void SkipBlock(bool skipForward) } } - var bl = _dataBlocks[targetBlockId]; + var bl = DataBlocks[targetBlockId]; - StringBuilder sbd = new StringBuilder(); + StringBuilder sbd = new(); sbd.Append('('); - sbd.Append((targetBlockId + 1) + " of " + _dataBlocks.Count); + sbd.Append((targetBlockId + 1) + " of " + DataBlocks.Count); sbd.Append(") : "); sbd.Append(bl.BlockDescription); if (bl.MetaData.Count > 0) @@ -291,11 +280,11 @@ public void SkipBlock(bool skipForward) public void LoadTape(byte[] tapeData) { // instantiate converters - TzxConverter tzxSer = new TzxConverter(this); - TapConverter tapSer = new TapConverter(this); - PzxConverter pzxSer = new PzxConverter(this); - CswConverter cswSer = new CswConverter(this); - WavConverter wavSer = new WavConverter(this); + TzxConverter tzxSer = new(this); + TapConverter tapSer = new(this); + PzxConverter pzxSer = new(this); + CswConverter cswSer = new(this); + WavConverter wavSer = new(this); // TZX if (tzxSer.CheckType(tapeData)) @@ -390,10 +379,7 @@ public void LoadTape(byte[] tapeData) /// /// Resets the tape /// - public void Reset() - { - RTZ(); - } + public void Reset() => RTZ(); /// /// Is called every cpu cycle but runs every 50 t-states @@ -450,11 +436,11 @@ public bool GetEarBit(long cpuCycle) if (_position == 0 && _tapeIsPlaying) { // notify about the current block - var bl = _dataBlocks[_currentDataBlockIndex]; + var bl = DataBlocks[_currentDataBlockIndex]; - StringBuilder sbd = new StringBuilder(); + StringBuilder sbd = new(); sbd.Append('('); - sbd.Append((_currentDataBlockIndex + 1) + " of " + _dataBlocks.Count); + sbd.Append((_currentDataBlockIndex + 1) + " of " + DataBlocks.Count); sbd.Append(") : "); sbd.Append(bl.BlockDescription); if (bl.MetaData.Count > 0) @@ -468,16 +454,16 @@ public bool GetEarBit(long cpuCycle) // increment the current period position _position++; - if (_position >= _dataBlocks[_currentDataBlockIndex].DataPeriods.Count) + if (_position >= DataBlocks[_currentDataBlockIndex].DataPeriods.Count) { // we have reached the end of the current block - if (_dataBlocks[_currentDataBlockIndex].DataPeriods.Count == 0) + if (DataBlocks[_currentDataBlockIndex].DataPeriods.Count == 0) { // notify about the current block (we are skipping it because its empty) - var bl = _dataBlocks[_currentDataBlockIndex]; - StringBuilder sbd = new StringBuilder(); + var bl = DataBlocks[_currentDataBlockIndex]; + StringBuilder sbd = new(); sbd.Append('('); - sbd.Append((_currentDataBlockIndex + 1) + " of " + _dataBlocks.Count); + sbd.Append((_currentDataBlockIndex + 1) + " of " + DataBlocks.Count); sbd.Append(") : "); sbd.Append(bl.BlockDescription); if (bl.MetaData.Count > 0) @@ -490,11 +476,11 @@ public bool GetEarBit(long cpuCycle) } // skip any empty blocks (and process any command blocks) - while (_position >= _dataBlocks[_currentDataBlockIndex].DataPeriods.Count) + while (_position >= DataBlocks[_currentDataBlockIndex].DataPeriods.Count) { // check for any commands - var command = _dataBlocks[_currentDataBlockIndex].Command; - var block = _dataBlocks[_currentDataBlockIndex]; + var command = DataBlocks[_currentDataBlockIndex].Command; + var block = DataBlocks[_currentDataBlockIndex]; bool shouldStop = false; switch (command) { @@ -505,7 +491,7 @@ public bool GetEarBit(long cpuCycle) _machine.Spectrum.OSD_TapeStoppedAuto(); shouldStop = true; - if (_currentDataBlockIndex >= _dataBlocks.Count) + if (_currentDataBlockIndex >= DataBlocks.Count) RTZ(); else { @@ -520,7 +506,7 @@ public bool GetEarBit(long cpuCycle) _machine.Spectrum.OSD_TapeStoppedAuto(); shouldStop = true; - if (_currentDataBlockIndex >= _dataBlocks.Count) + if (_currentDataBlockIndex >= DataBlocks.Count) RTZ(); else { @@ -538,14 +524,14 @@ public bool GetEarBit(long cpuCycle) _position = 0; _currentDataBlockIndex++; - if (_currentDataBlockIndex >= _dataBlocks.Count) + if (_currentDataBlockIndex >= DataBlocks.Count) { break; } } // check for end of tape - if (_currentDataBlockIndex >= _dataBlocks.Count) + if (_currentDataBlockIndex >= DataBlocks.Count) { _currentDataBlockIndex = -1; RTZ(); @@ -554,11 +540,11 @@ public bool GetEarBit(long cpuCycle) } // update waitEdge with current position within the current block - _waitEdge = _dataBlocks[_currentDataBlockIndex].DataPeriods.Count > 0 ? _dataBlocks[_currentDataBlockIndex].DataPeriods[_position] : 0; + _waitEdge = DataBlocks[_currentDataBlockIndex].DataPeriods.Count > 0 ? DataBlocks[_currentDataBlockIndex].DataPeriods[_position] : 0; // flip the current state //FlipTapeState(); - currentState = _dataBlocks[_currentDataBlockIndex].DataLevels[_position]; + currentState = DataBlocks[_currentDataBlockIndex].DataLevels[_position]; } // update lastCycle and return currentstate @@ -567,10 +553,7 @@ public bool GetEarBit(long cpuCycle) return currentState; } - private void FlipTapeState() - { - currentState = !currentState; - } + private void FlipTapeState() => currentState = !currentState; /// /// Flash loading implementation @@ -602,7 +585,7 @@ private bool FlashLoad() } var tb = DataBlocks[_currentDataBlockIndex]; - var tData = tb.BlockData; + byte[] tData = tb.BlockData; if (tData == null || tData.Length < 2) { @@ -610,7 +593,7 @@ private bool FlashLoad() return false; } - var toRead = tData.Length - 1; + int toRead = tData.Length - 1; if (toRead < _cpu.Regs[_cpu.E] + (_cpu.Regs[_cpu.D] << 8)) { @@ -624,27 +607,27 @@ private bool FlashLoad() if (toRead <= 0) return false; - var parity = tData[0]; + byte parity = tData[0]; if (parity != _cpu.Regs[_cpu.F_s] + (_cpu.Regs[_cpu.A_s] << 8) >> 8) return false; util.SetCpuRegister("Shadow AF", 0x0145); - for (var i = 0; i < toRead; i++) + for (int i = 0; i < toRead; i++) { - var v = tData[i + 1]; + byte v = tData[i + 1]; _cpu.Regs[_cpu.L] = v; parity ^= v; - var d = (ushort)(_cpu.Regs[_cpu.Ixl] + (_cpu.Regs[_cpu.Ixh] << 8) + 1); + ushort d = (ushort)(_cpu.Regs[_cpu.Ixl] + (_cpu.Regs[_cpu.Ixh] << 8) + 1); _machine.WriteBus(d, v); } - var pc = (ushort)0x05DF; + ushort pc = 0x05DF; if (_cpu.Regs[_cpu.E] + (_cpu.Regs[_cpu.D] << 8) == toRead && toRead + 1 < tData.Length) { - var v = tData[toRead + 1]; + byte v = tData[toRead + 1]; _cpu.Regs[_cpu.L] = v; parity ^= v; _cpu.Regs[_cpu.B] = 0xB0; @@ -659,9 +642,9 @@ private bool FlashLoad() } _cpu.Regs[_cpu.H] = parity; - var de = _cpu.Regs[_cpu.E] + (_cpu.Regs[_cpu.D] << 8); + int de = _cpu.Regs[_cpu.E] + (_cpu.Regs[_cpu.D] << 8); util.SetCpuRegister("DE", de - toRead); - var ix = _cpu.Regs[_cpu.Ixl] + (_cpu.Regs[_cpu.Ixh] << 8); + int ix = _cpu.Regs[_cpu.Ixl] + (_cpu.Regs[_cpu.Ixh] << 8); util.SetCpuRegister("IX", ix + toRead); util.SetCpuRegister("PC", pc); @@ -698,7 +681,7 @@ public void MonitorRead() int delta = (int)(cpuCycle - _lastINCycle); _lastINCycle = cpuCycle; - var nRegs = new ushort[] + ushort[] nRegs = new ushort[] { _cpu.Regs[_cpu.A], _cpu.Regs[_cpu.B], @@ -783,8 +766,8 @@ private void MonitorFrame() if (_tapeIsPlaying && _autoPlay) { if (DataBlocks.Count > 1 || - (_dataBlocks[_currentDataBlockIndex].BlockDescription != BlockType.CSW_Recording && - _dataBlocks[_currentDataBlockIndex].BlockDescription != BlockType.WAV_Recording)) + (DataBlocks[_currentDataBlockIndex].BlockDescription != BlockType.CSW_Recording && + DataBlocks[_currentDataBlockIndex].BlockDescription != BlockType.WAV_Recording)) { // we should only stop the tape when there are multiple blocks // if we just have one big block (maybe a CSW or WAV) then auto stopping will cock things up @@ -793,8 +776,8 @@ private void MonitorFrame() if (_monitorTimeOut < 0) { - if (_dataBlocks[_currentDataBlockIndex].BlockDescription != BlockType.PAUSE_BLOCK && - _dataBlocks[_currentDataBlockIndex].BlockDescription != BlockType.PAUS) + if (DataBlocks[_currentDataBlockIndex].BlockDescription is not BlockType.PAUSE_BLOCK and + not BlockType.PAUS) { AutoStopTape(); } @@ -811,7 +794,7 @@ private void MonitorFrame() var block = DataBlocks[_currentDataBlockIndex]; // is this a pause block? - if (block.BlockDescription == BlockType.PAUS || block.BlockDescription == BlockType.PAUSE_BLOCK) + if (block.BlockDescription is BlockType.PAUS or BlockType.PAUSE_BLOCK) { // don't autostop the tape here return; @@ -828,8 +811,8 @@ private void MonitorFrame() return; // don't autostop if there is only 1 block - if (DataBlocks.Count == 1 || _dataBlocks[_currentDataBlockIndex].BlockDescription == BlockType.CSW_Recording || - _dataBlocks[_currentDataBlockIndex].BlockDescription == BlockType.WAV_Recording + if (DataBlocks.Count == 1 || DataBlocks[_currentDataBlockIndex].BlockDescription == BlockType.CSW_Recording || + DataBlocks[_currentDataBlockIndex].BlockDescription == BlockType.WAV_Recording ) { return; diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Disk/NECUPD765.FDC.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Disk/NECUPD765.FDC.cs index 4cc6c9e04a2..a29f60338bf 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Disk/NECUPD765.FDC.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Disk/NECUPD765.FDC.cs @@ -29,7 +29,7 @@ public partial class NECUPD765 /// /// State parameters relating to the Active command /// - public CommandParameters ActiveCommandParams = new CommandParameters(); + public CommandParameters ActiveCommandParams = new(); /// /// The current active phase of the controller @@ -569,7 +569,7 @@ private void UPD_ReadData() //---------------------------------------- case Phase.Execution: - var index = ExecLength - ExecCounter; + int index = ExecLength - ExecCounter; LastSectorDataReadByte = ExecBuffer[index]; @@ -883,7 +883,7 @@ private void UPD_ReadDeletedData() // FDC in execution phase reading/writing bytes //---------------------------------------- case Phase.Execution: - var index = ExecLength - ExecCounter; + int index = ExecLength - ExecCounter; LastSectorDataReadByte = ExecBuffer[index]; @@ -1122,7 +1122,7 @@ private void UPD_ReadDiagnostic() //---------------------------------------- case Phase.Execution: - var index = ExecLength - ExecCounter; + int index = ExecLength - ExecCounter; LastSectorDataReadByte = ExecBuffer[index]; @@ -1402,7 +1402,7 @@ private void UPD_WriteData() //---------------------------------------- case Phase.Execution: - var index = ExecLength - ExecCounter; + int index = ExecLength - ExecCounter; ExecBuffer[index] = LastSectorDataWriteByte; @@ -1695,7 +1695,7 @@ private void UPD_WriteDeletedData() //---------------------------------------- case Phase.Execution: - var index = ExecLength - ExecCounter; + int index = ExecLength - ExecCounter; ExecBuffer[index] = LastSectorDataWriteByte; @@ -1888,7 +1888,7 @@ private void UPD_Specify() // process parameter byte byte currByte = CommBuffer[CommCounter]; - BitArray bi = new BitArray(new byte[] { currByte }); + BitArray bi = new(new byte[] { currByte }); switch (CommCounter) { @@ -2134,8 +2134,8 @@ private void UPD_SenseInterruptStatus() // for now I will assume that the first call is aimed at DriveA, the second at DriveB (which we are NOT implementing) // check active drive first - if (ActiveDrive.SeekStatus == SEEK_RECALIBRATE || - ActiveDrive.SeekStatus == SEEK_SEEK) + if (ActiveDrive.SeekStatus is SEEK_RECALIBRATE or + SEEK_SEEK) { // interrupt has been raised for this drive // acknowledge @@ -2523,7 +2523,7 @@ private bool ParseCommandByte(byte cmdByte) cmdByte = cByte; // lookup the command - var i = CommandList.FindIndex(a => a.CommandCode == cmdByte); + int i = CommandList.FindIndex(a => a.CommandCode == cmdByte); if (i is -1) { // no command found - use invalid @@ -2600,7 +2600,7 @@ private bool ParseCommandByte(byte cmdByte) private void ParseParamByteStandard(int index) { byte currByte = CommBuffer[index]; - BitArray bi = new BitArray(new byte[] { currByte }); + BitArray bi = new(new byte[] { currByte }); switch (index) { diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Disk/NECUPD765.FDD.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Disk/NECUPD765.FDD.cs index 8911b943d03..bf9eae08310 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Disk/NECUPD765.FDD.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Disk/NECUPD765.FDD.cs @@ -52,7 +52,7 @@ private void FDD_Init() { for (int i = 0; i < 4; i++) { - DriveState ds = new DriveState(i, this); + DriveState ds = new(i, this); DriveStates[i] = ds; } } @@ -141,19 +141,14 @@ private FloppyDisk.Sector GetSector() /// /// Parses a new disk image and loads it into this floppy drive /// - public void FDD_LoadDisk(byte[] diskData) - { + public void FDD_LoadDisk(byte[] diskData) => // we are only going to load into the first drive DriveStates[0].FDD_LoadDisk(diskData); - } /// /// Ejects the current disk /// - public void FDD_EjectDisk() - { - DriveStates[0].FDD_EjectDisk(); - } + public void FDD_EjectDisk() => DriveStates[0].FDD_EjectDisk(); /// /// Signs whether the current active drive has a disk inserted @@ -783,11 +778,7 @@ public void FDD_LoadDisk(byte[] diskData) /// /// Ejects the current disk /// - public void FDD_EjectDisk() - { - Disk = null; - //FLAG_READY = false; - } + public void FDD_EjectDisk() => Disk = null;//FLAG_READY = false; /// /// Signs whether the current active drive has a disk inserted diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Disk/NECUPD765.IPortIODevice.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Disk/NECUPD765.IPortIODevice.cs index 4bb412a50a8..a707dd96bb2 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Disk/NECUPD765.IPortIODevice.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Disk/NECUPD765.IPortIODevice.cs @@ -21,8 +21,8 @@ public partial class NECUPD765 : IPortIODevice public string outputString = "STATUS,WRITE,READ,CODE,MT,MF,SK,CMDCNT,RESCNT,EXECCNT,EXECLEN\r\n"; public bool writeDebug = false; - public List dLog = new List - { + public List dLog = new() + { "STATUS,WRITE,READ,CODE,MT,MF,SK,CMDCNT,RESCNT,EXECCNT,EXECLEN" }; @@ -41,7 +41,7 @@ public partial class NECUPD765 : IPortIODevice private void BuildCSVLine() { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); for (int i = 0; i < 3; i++) { sb.Append(workingArr[i]); @@ -71,7 +71,7 @@ private void BuildCSVLine() /// public bool ReadPort(ushort port, ref int data) { - BitArray bits = new BitArray(new byte[] { (byte)data }); + BitArray bits = new(new byte[] { (byte)data }); if (port == 0x3ffd) { @@ -111,7 +111,7 @@ public bool ReadPort(ushort port, ref int data) /// public bool WritePort(ushort port, int data) { - BitArray bits = new BitArray(new byte[] { (byte)data }); + BitArray bits = new(new byte[] { (byte)data }); if (port == 0x3ffd) { diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Disk/NECUPD765.Timing.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Disk/NECUPD765.Timing.cs index 04304bd0564..ed6c8e60614 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Disk/NECUPD765.Timing.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Disk/NECUPD765.Timing.cs @@ -1,4 +1,4 @@ - + namespace BizHawk.Emulation.Cores.Computers.SinclairSpectrum { /// @@ -12,6 +12,7 @@ namespace BizHawk.Emulation.Cores.Computers.SinclairSpectrum */ public partial class NECUPD765 { + #pragma warning disable IDE0051 /// /// The current Z80 cycle /// @@ -25,11 +26,12 @@ private long CurrentCPUCycle return _machine.CPU.TotalExecutedCycles; } } + #pragma warning restore IDE0051 - /// - /// The last CPU cycle when the FDC accepted an IO read/write - /// - private long LastCPUCycle; + /// + /// The last CPU cycle when the FDC accepted an IO read/write + /// + private long LastCPUCycle; /// /// The current delay figure (in Z80 t-states) @@ -89,6 +91,7 @@ private void TimingInit() } + #pragma warning disable IDE0051 /// /// Called by reads to the main status register /// Returns true if there is no delay @@ -114,5 +117,6 @@ private bool CheckTiming() return true; } } + #pragma warning restore IDE0051 } } diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Disk/NECUPS765.Static.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Disk/NECUPS765.Static.cs index 1d638fc8d21..64cf16d2005 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Disk/NECUPS765.Static.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Disk/NECUPS765.Static.cs @@ -18,10 +18,10 @@ public partial class NECUPD765 /// public static bool GetBit(int bitNumber, byte dataByte) { - if (bitNumber < 0 || bitNumber > 7) + if (bitNumber is < 0 or > 7) return false; - BitArray bi = new BitArray(new byte[] { dataByte }); + BitArray bi = new(new byte[] { dataByte }); return bi[bitNumber]; } @@ -31,7 +31,7 @@ public static bool GetBit(int bitNumber, byte dataByte) /// public static void SetBit(int bitNumber, ref byte dataByte) { - if (bitNumber < 0 || bitNumber > 7) + if (bitNumber is < 0 or > 7) return; int db = dataByte; @@ -46,7 +46,7 @@ public static void SetBit(int bitNumber, ref byte dataByte) /// public static void UnSetBit(int bitNumber, ref byte dataByte) { - if (bitNumber < 0 || bitNumber > 7) + if (bitNumber is < 0 or > 7) return; int db = dataByte; diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Input/CursorJoystick.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Input/CursorJoystick.cs index 66c70788965..2cb732572a0 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Input/CursorJoystick.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Input/CursorJoystick.cs @@ -16,19 +16,19 @@ public CursorJoystick(SpectrumBase machine, int playerNumber) { _machine = machine; //_joyLine = 0; - _playerNumber = playerNumber; + PlayerNumber = playerNumber; ButtonCollection = new List { - "P" + _playerNumber + " Left", - "P" + _playerNumber + " Right", - "P" + _playerNumber + " Down", - "P" + _playerNumber + " Up", - "P" + _playerNumber + " Button", + "P" + PlayerNumber + " Left", + "P" + PlayerNumber + " Right", + "P" + PlayerNumber + " Down", + "P" + PlayerNumber + " Up", + "P" + PlayerNumber + " Button", }.ToArray(); } - private readonly List btnLookups = new List + private readonly List btnLookups = new() { "Key 5", // left "Key 8", // right @@ -40,20 +40,14 @@ public CursorJoystick(SpectrumBase machine, int playerNumber) public JoystickType JoyType => JoystickType.Cursor; public string[] ButtonCollection { get; set; } - - private int _playerNumber; - public int PlayerNumber - { - get => _playerNumber; - set => _playerNumber = value; - } + public int PlayerNumber { get; set; } /// /// Sets the joystick line based on key pressed /// public void SetJoyInput(string key, bool isPressed) { - var pos = GetBitPos(key); + int pos = GetBitPos(key); if (isPressed) { @@ -78,11 +72,11 @@ public void SetJoyInput(string key, bool isPressed) /// public bool GetJoyInput(string key) { - var pos = GetBitPos(key); + int pos = GetBitPos(key); if (_machine == null) return false; - var l = _machine.KeyboardDevice.GetKeyStatus(btnLookups[pos]); + bool l = _machine.KeyboardDevice.GetKeyStatus(btnLookups[pos]); return l; } diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Input/KempstonJoystick.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Input/KempstonJoystick.cs index 5e2d710f7ee..619634ab7dd 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Input/KempstonJoystick.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Input/KempstonJoystick.cs @@ -5,46 +5,39 @@ namespace BizHawk.Emulation.Cores.Computers.SinclairSpectrum { public class KempstonJoystick : IJoystick { - private int _joyLine; - private SpectrumBase _machine; + private readonly SpectrumBase _machine; public KempstonJoystick(SpectrumBase machine, int playerNumber) { _machine = machine; - _joyLine = 0; - _playerNumber = playerNumber; + JoyLine = 0; + PlayerNumber = playerNumber; ButtonCollection = new List { - "P" + _playerNumber + " Right", - "P" + _playerNumber + " Left", - "P" + _playerNumber + " Down", - "P" + _playerNumber + " Up", - "P" + _playerNumber + " Button", + "P" + PlayerNumber + " Right", + "P" + PlayerNumber + " Left", + "P" + PlayerNumber + " Down", + "P" + PlayerNumber + " Up", + "P" + PlayerNumber + " Button", }.ToArray(); } public JoystickType JoyType => JoystickType.Kempston; public string[] ButtonCollection { get; set; } - - private int _playerNumber; - public int PlayerNumber - { - get => _playerNumber; - set => _playerNumber = value; - } + public int PlayerNumber { get; set; } /// /// Sets the joystick line based on key pressed /// public void SetJoyInput(string key, bool isPressed) { - var pos = GetBitPos(key); + int pos = GetBitPos(key); if (isPressed) - _joyLine |= (1 << pos); + JoyLine |= (1 << pos); else - _joyLine &= ~(1 << pos); + JoyLine &= ~(1 << pos); } /// @@ -52,19 +45,15 @@ public void SetJoyInput(string key, bool isPressed) /// public bool GetJoyInput(string key) { - var pos = GetBitPos(key); - return (_joyLine & (1 << pos)) != 0; + int pos = GetBitPos(key); + return (JoyLine & (1 << pos)) != 0; } /// /// Active bits high /// 0 0 0 F U D L R /// - public int JoyLine - { - get => _joyLine; - set => _joyLine = value; - } + public int JoyLine { get; set; } /// /// Gets the bit position of a particular joystick binding from the matrix diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Input/NullJoystick.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Input/NullJoystick.cs index f2b52a3d628..7f8a19d24cc 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Input/NullJoystick.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Input/NullJoystick.cs @@ -8,14 +8,13 @@ namespace BizHawk.Emulation.Cores.Computers.SinclairSpectrum /// public class NullJoystick : IJoystick { - private int _joyLine; - private SpectrumBase _machine; + private readonly SpectrumBase _machine; public NullJoystick(SpectrumBase machine, int playerNumber) { _machine = machine; - _joyLine = 0; - _playerNumber = playerNumber; + JoyLine = 0; + PlayerNumber = playerNumber; ButtonCollection = new List { @@ -26,24 +25,18 @@ public NullJoystick(SpectrumBase machine, int playerNumber) public JoystickType JoyType => JoystickType.NULL; public string[] ButtonCollection { get; set; } - - private int _playerNumber; - public int PlayerNumber - { - get => _playerNumber; - set => _playerNumber = value; - } + public int PlayerNumber { get; set; } /// /// Sets the joystick line based on key pressed /// public void SetJoyInput(string key, bool isPressed) { - var pos = GetBitPos(key); + int pos = GetBitPos(key); if (isPressed) - _joyLine |= (1 << pos); + JoyLine |= (1 << pos); else - _joyLine &= ~(1 << pos); + JoyLine &= ~(1 << pos); } /// @@ -51,19 +44,15 @@ public void SetJoyInput(string key, bool isPressed) /// public bool GetJoyInput(string key) { - var pos = GetBitPos(key); - return (_joyLine & (1 << pos)) != 0; + int pos = GetBitPos(key); + return (JoyLine & (1 << pos)) != 0; } /// /// Active bits high /// 0 0 0 F U D L R /// - public int JoyLine - { - get => _joyLine; - set => _joyLine = value; - } + public int JoyLine { get; set; } /// /// Gets the bit position of a particular joystick binding from the matrix diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Input/SinclairJoystick1.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Input/SinclairJoystick1.cs index b16d024075d..8a5b7dc1368 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Input/SinclairJoystick1.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Input/SinclairJoystick1.cs @@ -16,19 +16,19 @@ public SinclairJoystick1(SpectrumBase machine, int playerNumber) { _machine = machine; //_joyLine = 0; - _playerNumber = playerNumber; + PlayerNumber = playerNumber; ButtonCollection = new List { - "P" + _playerNumber + " Left", - "P" + _playerNumber + " Right", - "P" + _playerNumber + " Down", - "P" + _playerNumber + " Up", - "P" + _playerNumber + " Button", + "P" + PlayerNumber + " Left", + "P" + PlayerNumber + " Right", + "P" + PlayerNumber + " Down", + "P" + PlayerNumber + " Up", + "P" + PlayerNumber + " Button", }.ToArray(); } - private readonly List btnLookups = new List + private readonly List btnLookups = new() { "Key 1", // left "Key 2", // right @@ -40,20 +40,14 @@ public SinclairJoystick1(SpectrumBase machine, int playerNumber) public JoystickType JoyType => JoystickType.SinclairLEFT; public string[] ButtonCollection { get; set; } - - private int _playerNumber; - public int PlayerNumber - { - get => _playerNumber; - set => _playerNumber = value; - } + public int PlayerNumber { get; set; } /// /// Sets the joystick line based on key pressed /// public void SetJoyInput(string key, bool isPressed) { - var pos = GetBitPos(key); + int pos = GetBitPos(key); if (isPressed) { @@ -78,7 +72,7 @@ public void SetJoyInput(string key, bool isPressed) /// public bool GetJoyInput(string key) { - var pos = GetBitPos(key); + int pos = GetBitPos(key); if (_machine == null) return false; diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Input/SinclairJoystick2.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Input/SinclairJoystick2.cs index d35504e9b07..e9818bc98d0 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Input/SinclairJoystick2.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Input/SinclairJoystick2.cs @@ -16,19 +16,19 @@ public SinclairJoystick2(SpectrumBase machine, int playerNumber) { _machine = machine; //_joyLine = 0; - _playerNumber = playerNumber; + PlayerNumber = playerNumber; ButtonCollection = new List { - "P" + _playerNumber + " Left", - "P" + _playerNumber + " Right", - "P" + _playerNumber + " Down", - "P" + _playerNumber + " Up", - "P" + _playerNumber + " Button", + "P" + PlayerNumber + " Left", + "P" + PlayerNumber + " Right", + "P" + PlayerNumber + " Down", + "P" + PlayerNumber + " Up", + "P" + PlayerNumber + " Button", }.ToArray(); } - private readonly List btnLookups = new List + private readonly List btnLookups = new() { "Key 6", // left "Key 7", // right @@ -40,20 +40,14 @@ public SinclairJoystick2(SpectrumBase machine, int playerNumber) public JoystickType JoyType => JoystickType.SinclairRIGHT; public string[] ButtonCollection { get; set; } - - private int _playerNumber; - public int PlayerNumber - { - get => _playerNumber; - set => _playerNumber = value; - } + public int PlayerNumber { get; set; } /// /// Sets the joystick line based on key pressed /// public void SetJoyInput(string key, bool isPressed) { - var pos = GetBitPos(key); + int pos = GetBitPos(key); if (isPressed) { @@ -78,7 +72,7 @@ public void SetJoyInput(string key, bool isPressed) /// public bool GetJoyInput(string key) { - var pos = GetBitPos(key); + int pos = GetBitPos(key); if (_machine == null) return false; diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Input/StandardKeyboard.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Input/StandardKeyboard.cs index b799a6f6200..6055272dc1e 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Input/StandardKeyboard.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Input/StandardKeyboard.cs @@ -12,16 +12,9 @@ public class StandardKeyboard : IKeyboard { public SpectrumBase _machine { get; set; } private byte[] LineStatus; - private string[] _keyboardMatrix; private int[] _keyLine; - private bool _isIssue2Keyboard; - private string[] _nonMatrixKeys; - public bool IsIssue2Keyboard - { - get => _isIssue2Keyboard; - set => _isIssue2Keyboard = value; - } + public bool IsIssue2Keyboard { get; set; } public int[] KeyLine { @@ -29,17 +22,9 @@ public int[] KeyLine set => _keyLine = value; } - public string[] KeyboardMatrix - { - get => _keyboardMatrix; - set => _keyboardMatrix = value; - } + public string[] KeyboardMatrix { get; set; } - public string[] NonMatrixKeys - { - get => _nonMatrixKeys; - set => _nonMatrixKeys = value; - } + public string[] NonMatrixKeys { get; set; } public StandardKeyboard(SpectrumBase machine) { @@ -65,9 +50,9 @@ public StandardKeyboard(SpectrumBase machine) "Key Space", "Key Symbol Shift", "Key M", "Key N", "Key B" }; - var nonMatrix = new List(); + List nonMatrix = new(); - foreach (var key in _machine.Spectrum.ZXSpectrumControllerDefinition.BoolButtons) + foreach (string key in _machine.Spectrum.ZXSpectrumControllerDefinition.BoolButtons) { if (!KeyboardMatrix.Any(s => s == key)) nonMatrix.Add(key); @@ -86,8 +71,8 @@ public void SetKeyStatus(string key, bool isPressed) if (k != 255) { - var lineIndex = k / 5; - var lineMask = 1 << k % 5; + int lineIndex = k / 5; + int lineMask = 1 << k % 5; _keyLine[lineIndex] = isPressed ? (byte)(_keyLine[lineIndex] & ~lineMask) @@ -137,8 +122,8 @@ public void SetKeyStatus(string key, bool isPressed) public bool GetKeyStatus(string key) { byte keyByte = GetByteFromKeyMatrix(key); - var lineIndex = keyByte / 5; - var lineMask = 1 << keyByte % 5; + int lineIndex = keyByte / 5; + int lineMask = 1 << keyByte % 5; return (_keyLine[lineIndex] & lineMask) == 0; } @@ -158,7 +143,7 @@ public byte GetLineStatus(byte lines) { byte status = 0; lines = (byte)~lines; - var lineIndex = 0; + int lineIndex = 0; while (lines > 0) { if ((lines & 0x01) != 0) @@ -166,16 +151,13 @@ public byte GetLineStatus(byte lines) lineIndex++; lines >>= 1; } - var result = status; + byte result = status; return result; } } - public byte ReadKeyboardByte(ushort addr) - { - return GetLineStatus((byte)(addr >> 8)); - } + public byte ReadKeyboardByte(ushort addr) => GetLineStatus((byte)(addr >> 8)); public byte GetByteFromKeyMatrix(string key) { @@ -259,11 +241,9 @@ A zero in one of the five lowest bits means that the corresponding key is presse /// /// Device responds to an OUT instruction /// - public bool WritePort(ushort port, int result) - { + public bool WritePort(ushort port, int result) => // not implemented - return false; - } + false; public void SyncState(Serializer ser) { diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Rom/RomData.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Rom/RomData.cs index 2f5da5e94d1..771ca46b349 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Rom/RomData.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/Rom/RomData.cs @@ -9,51 +9,20 @@ public class RomData /// /// ROM Contents /// - public byte[] RomBytes - { - get => _romBytes; - set => _romBytes = value; - } + public byte[] RomBytes { get; set; } /// /// Useful ROM addresses that are needed during tape operations /// - public ushort SaveBytesRoutineAddress - { - get => _saveBytesRoutineAddress; - set => _saveBytesRoutineAddress = value; - } - public ushort LoadBytesRoutineAddress - { - get => _loadBytesRoutineAddress; - set => _loadBytesRoutineAddress = value; - } - public ushort SaveBytesResumeAddress - { - get => _saveBytesResumeAddress; - set => _saveBytesResumeAddress = value; - } - public ushort LoadBytesResumeAddress - { - get => _loadBytesResumeAddress; - set => _loadBytesResumeAddress = value; - } - public ushort LoadBytesInvalidHeaderAddress - { - get => _loadBytesInvalidHeaderAddress; - set => _loadBytesInvalidHeaderAddress = value; - } - - private byte[] _romBytes; - private ushort _saveBytesRoutineAddress; - private ushort _loadBytesRoutineAddress; - private ushort _saveBytesResumeAddress; - private ushort _loadBytesResumeAddress; - private ushort _loadBytesInvalidHeaderAddress; + public ushort SaveBytesRoutineAddress { get; set; } + public ushort LoadBytesRoutineAddress { get; set; } + public ushort SaveBytesResumeAddress { get; set; } + public ushort LoadBytesResumeAddress { get; set; } + public ushort LoadBytesInvalidHeaderAddress { get; set; } public static RomData InitROM(MachineType machineType, byte[] rom) { - RomData RD = new RomData { RomBytes = new byte[rom.Length] }; + RomData RD = new() { RomBytes = new byte[rom.Length] }; RD.RomBytes = rom; switch (machineType) diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/SoundOuput/AY38912.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/SoundOuput/AY38912.cs index 17e34ae24ac..c40b778fd2b 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/SoundOuput/AY38912.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Hardware/SoundOuput/AY38912.cs @@ -1,4 +1,4 @@ -using BizHawk.Common; +using BizHawk.Common; using BizHawk.Common.NumberExtensions; using BizHawk.Emulation.Common; using System; @@ -162,10 +162,7 @@ public int SelectedRegister /// /// Used for snapshot generation /// - public int[] ExportRegisters() - { - return _registers; - } + public int[] ExportRegisters() => _registers; /// /// Resets the PSG @@ -210,10 +207,7 @@ public void Reset() /// /// Reads the value from the currently selected register /// - public int PortRead() - { - return _registers[_activeRegister]; - } + public int PortRead() => _registers[_activeRegister]; /// /// Writes to the currently selected register @@ -324,19 +318,14 @@ public void StartFrame() /// /// End of frame /// - public void EndFrame() - { - BufferUpdate(_tStatesPerFrame); - } + public void EndFrame() => BufferUpdate(_tStatesPerFrame); /// /// Updates the audiobuffer based on the current frame t-state /// - public void UpdateSound(int frameCycle) - { - BufferUpdate(frameCycle); - } + public void UpdateSound(int frameCycle) => BufferUpdate(frameCycle); +#pragma warning disable IDE0051 /// /// Register indicies /// @@ -356,6 +345,7 @@ public void UpdateSound(int frameCycle) private const int AY_E_SHAPE = 13; private const int AY_PORT_A = 14; private const int AY_PORT_B = 15; + #pragma warning restore IDE0051 /// /// The register array @@ -406,7 +396,7 @@ The AY-3-8912 ignores bit 7 of this register. /// /// The rendering resolution of the chip /// - private double _resolution = 50D * 8D / _chipFrequency; + private readonly double _resolution = 50D * 8D / _chipFrequency; /// /// Channel generator state @@ -496,7 +486,7 @@ The AY-3-8912 ignores bit 7 of this register. /// /// Panning table list /// - private static readonly List PanTabs = new List + private static readonly List PanTabs = new() { // MONO new uint[] { 50,50, 50,50, 50,50 }, @@ -546,9 +536,9 @@ The AY-3-8912 ignores bit 7 of this register. private void UpdateVolume() { int upperFloor = 40000; - var inc = (0xFFFF - upperFloor) / 100; + int inc = (0xFFFF - upperFloor) / 100; - var vol = inc * _volume; // ((ulong)0xFFFF * (ulong)_volume / 100UL) - 20000 ; + int vol = inc * _volume; // ((ulong)0xFFFF * (ulong)_volume / 100UL) - 20000 ; _volumeTables = new uint[6][]; // parent array @@ -587,7 +577,7 @@ private void InitTiming(int sampleRate, int frameTactCount) mult_const = ((_chipFrequency / 8) << 14) / _machine.ULADevice.ClockSpeed; - var aytickspercputick = _machine.ULADevice.ClockSpeed / (double)_chipFrequency; + double aytickspercputick = _machine.ULADevice.ClockSpeed / (double)_chipFrequency; int ayCyclesPerSample = (int)(_tStatesPerSample * (double)aytickspercputick); } @@ -645,7 +635,7 @@ private void BufferUpdate(int cycle) if ((_eState & ~31) != 0) { - var mask = (1 << _registers[AY_E_SHAPE]); + int mask = (1 << _registers[AY_E_SHAPE]); if ((mask & ((1 << 0) | (1 << 1) | (1 << 2) | (1 << 3) | (1 << 4) | (1 << 5) | (1 << 6) | @@ -673,12 +663,12 @@ private void BufferUpdate(int cycle) } // mix the sample - var mixA = ((_eMaskA & _eState) | _vA) & ((_bitA | _bit0) & (_bitN | _bit3)); - var mixB = ((_eMaskB & _eState) | _vB) & ((_bitB | _bit1) & (_bitN | _bit4)); - var mixC = ((_eMaskC & _eState) | _vC) & ((_bitC | _bit2) & (_bitN | _bit5)); + int mixA = ((_eMaskA & _eState) | _vA) & ((_bitA | _bit0) & (_bitN | _bit3)); + int mixB = ((_eMaskB & _eState) | _vB) & ((_bitB | _bit1) & (_bitN | _bit4)); + int mixC = ((_eMaskC & _eState) | _vC) & ((_bitC | _bit2) & (_bitN | _bit5)); - var l = _volumeTables[0][mixA]; - var r = _volumeTables[1][mixA]; + uint l = _volumeTables[0][mixA]; + uint r = _volumeTables[1][mixA]; l += _volumeTables[2][mixB]; r += _volumeTables[3][mixB]; @@ -704,15 +694,9 @@ public void SetSyncMode(SyncSoundMode mode) throw new InvalidOperationException("Only Sync mode is supported."); } - public void GetSamplesAsync(short[] samples) - { - throw new NotSupportedException("Async is not available"); - } + public void GetSamplesAsync(short[] samples) => throw new NotSupportedException("Async is not available"); - public void DiscardSamples() - { - _audioBuffer = new short[_samplesPerFrame * 2]; - } + public void DiscardSamples() => _audioBuffer = new short[_samplesPerFrame * 2]; public void GetSamplesSync(out short[] samples, out int nsamp) { diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/CPUMonitor.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/CPUMonitor.cs index 2458eef3fd5..064e2250040 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/CPUMonitor.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/CPUMonitor.cs @@ -25,14 +25,11 @@ public ushort BUSRQ { get { - switch (machineType) + return machineType switch { - case MachineType.ZXSpectrum128Plus2a: - case MachineType.ZXSpectrum128Plus3: - return _cpu.MEMRQ[_cpu.bus_pntr]; - default: - return _cpu.BUSRQ[_cpu.mem_pntr]; - } + MachineType.ZXSpectrum128Plus2a or MachineType.ZXSpectrum128Plus3 => _cpu.MEMRQ[_cpu.bus_pntr], + _ => _cpu.BUSRQ[_cpu.mem_pntr], + }; } } @@ -69,7 +66,7 @@ public void ExecuteCycle() // is the memory address of the BUSRQ potentially contended? if (_machine.IsContended(AscertainBUSRQAddress())) { - var cont = _machine.ULADevice.GetContentionValue((int)_machine.CurrentFrameCycle); + int cont = _machine.ULADevice.GetContentionValue((int)_machine.CurrentFrameCycle); if (cont > 0) { _cpu.TotalExecutedCycles += cont; diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/Pentagon128K/Pentagon128.Memory.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/Pentagon128K/Pentagon128.Memory.cs index 327e90619b4..323a300c3e1 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/Pentagon128K/Pentagon128.Memory.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/Pentagon128K/Pentagon128.Memory.cs @@ -179,7 +179,7 @@ public override void WriteBus(ushort addr, byte value) /// public override byte ReadMemory(ushort addr) { - var data = ReadBus(addr); + byte data = ReadBus(addr); return data; } @@ -188,7 +188,7 @@ public override byte ReadMemory(ushort addr) /// public override ZXSpectrum.CDLResult ReadCDL(ushort addr) { - var result = new ZXSpectrum.CDLResult(); + ZXSpectrum.CDLResult result = new(); int divisor = addr / 0x4000; result.Address = addr % 0x4000; @@ -250,21 +250,18 @@ public override ZXSpectrum.CDLResult ReadCDL(ushort addr) return result; } - /// - /// Writes a byte of data to a specified memory address - /// (with memory contention if appropriate) - /// - public override void WriteMemory(ushort addr, byte value) - { - WriteBus(addr, value); - } + /// + /// Writes a byte of data to a specified memory address + /// (with memory contention if appropriate) + /// + public override void WriteMemory(ushort addr, byte value) => WriteBus(addr, value); - /// - /// Checks whether supplied address is in a potentially contended bank - /// - public override bool IsContended(ushort addr) + /// + /// Checks whether supplied address is in a potentially contended bank + /// + public override bool IsContended(ushort addr) { - var a = addr & 0xc000; + int a = addr & 0xc000; if (a == 0x4000) { @@ -293,17 +290,12 @@ public override bool IsContended(ushort addr) /// public override bool ContendedBankPaged() { - switch (RAMPaged) - { - case 1: - case 3: - case 5: - case 7: - return true; - } - - return false; - } + return RAMPaged switch + { + 1 or 3 or 5 or 7 => true, + _ => false, + }; + } /// /// ULA reads the memory at the specified address @@ -312,7 +304,7 @@ public override bool ContendedBankPaged() /// public override byte FetchScreenMemory(ushort addr) { - byte value = new byte(); + byte value = new(); if (SHADOWPaged && !PagingDisabled) { diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/Pentagon128K/Pentagon128.Port.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/Pentagon128K/Pentagon128.Port.cs index 72889d1b0d5..88a681984fe 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/Pentagon128K/Pentagon128.Port.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/Pentagon128K/Pentagon128.Port.cs @@ -19,7 +19,7 @@ public override byte ReadPort(ushort port) // ports 0x3ffd & 0x7ffd // traditionally thought to be write-only - if (port == 0x3ffd || port == 0x7ffd) + if (port is 0x3ffd or 0x7ffd) { // https://faqwiki.zxnet.co.uk/wiki/ZX_Spectrum_128 // HAL bugs @@ -80,9 +80,9 @@ public override byte ReadPort(ushort port) public override void WritePort(ushort port, byte value) { // get a BitArray of the port - BitArray portBits = new BitArray(BitConverter.GetBytes(port)); + BitArray portBits = new(BitConverter.GetBytes(port)); // get a BitArray of the value byte - BitArray bits = new BitArray(new byte[] { value }); + BitArray bits = new(new byte[] { value }); // handle AY port writes AYDevice.WritePort(port, value); @@ -97,8 +97,8 @@ public override void WritePort(ushort port, byte value) // if paging is disabled then all writes to this port are ignored until the next reboot if (!PagingDisabled) { - // Bits 0, 1, 2 select the RAM page - var rp = value & 0x07; + // Bits 0, 1, 2 select the RAM page + int rp = value & 0x07; if (RAMPaged != rp && rp < 8) RAMPaged = rp; diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/SpectrumBase.Input.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/SpectrumBase.Input.cs index 60a1730e8cc..17b5974aa59 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/SpectrumBase.Input.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/SpectrumBase.Input.cs @@ -54,7 +54,7 @@ public void PollInput() lock (this) { // parse single keyboard matrix keys - for (var i = 0; i < KeyboardDevice.KeyboardMatrix.Length; i++) + for (int i = 0; i < KeyboardDevice.KeyboardMatrix.Length; i++) { string key = KeyboardDevice.KeyboardMatrix[i]; bool prevState = KeyboardDevice.GetKeyStatus(key); @@ -281,7 +281,7 @@ public void PollInput() /// protected void InitJoysticks(List joys) { - var jCollection = new List(); + List jCollection = new(); for (int i = 0; i < joys.Count; i++) { @@ -301,30 +301,21 @@ protected void InitJoysticks(List joys) /// public IJoystick InstantiateJoystick(JoystickType type, int playerNumber) { - switch (type) + return type switch { - case JoystickType.Kempston: - return new KempstonJoystick(this, playerNumber); - case JoystickType.Cursor: - return new CursorJoystick(this, playerNumber); - case JoystickType.SinclairLEFT: - return new SinclairJoystick1(this, playerNumber); - case JoystickType.SinclairRIGHT: - return new SinclairJoystick2(this, playerNumber); - case JoystickType.NULL: - return new NullJoystick(this, playerNumber); - } - - return null; + JoystickType.Kempston => new KempstonJoystick(this, playerNumber), + JoystickType.Cursor => new CursorJoystick(this, playerNumber), + JoystickType.SinclairLEFT => new SinclairJoystick1(this, playerNumber), + JoystickType.SinclairRIGHT => new SinclairJoystick2(this, playerNumber), + JoystickType.NULL => new NullJoystick(this, playerNumber), + _ => null, + }; } /// /// Returns a IJoystick object depending on the type (or null if not found) /// - protected IJoystick LocateUniqueJoystick(JoystickType type) - { - return JoystickCollection.FirstOrDefault(a => a.JoyType == type); - } + protected IJoystick LocateUniqueJoystick(JoystickType type) => JoystickCollection.FirstOrDefault(a => a.JoyType == type); /// /// Signs whether input read has been requested diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/SpectrumBase.Media.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/SpectrumBase.Media.cs index 61cfe4295f1..bb200a21f7e 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/SpectrumBase.Media.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/SpectrumBase.Media.cs @@ -131,7 +131,7 @@ protected void LoadAllMedia() diskImages = new List(); int cnt = 0; - foreach (var m in mediaImages) + foreach (byte[] m in mediaImages) { switch (IdentifyMedia(m)) { @@ -146,7 +146,7 @@ protected void LoadAllMedia() case SpectrumMediaType.DiskDoubleSided: // this is a bit tricky. we will attempt to parse the double sided disk image byte array, // then output two separate image byte arrays - List working = new List(); + List working = new(); foreach (DiskType type in Enum.GetValues(typeof(DiskType))) { bool found = false; @@ -171,12 +171,12 @@ protected void LoadAllMedia() // add side 2 diskImages.Add(working[1]); - Common.GameInfo one = new Common.GameInfo(); - Common.GameInfo two = new Common.GameInfo(); + Common.GameInfo one = new(); + Common.GameInfo two = new(); var gi = Spectrum._gameInfo[cnt]; for (int i = 0; i < 2; i++) { - Common.GameInfo work = new Common.GameInfo(); + Common.GameInfo work = new(); if (i == 0) { work = one; @@ -215,18 +215,15 @@ protected void LoadAllMedia() LoadDiskMedia(); } - /// - /// Attempts to load a tape into the tape device based on tapeMediaIndex - /// - protected void LoadTapeMedia() - { - TapeDevice.LoadTape(tapeImages[tapeMediaIndex]); - } + /// + /// Attempts to load a tape into the tape device based on tapeMediaIndex + /// + protected void LoadTapeMedia() => TapeDevice.LoadTape(tapeImages[tapeMediaIndex]); - /// - /// Attempts to load a disk into the disk device based on diskMediaIndex - /// - protected void LoadDiskMedia() + /// + /// Attempts to load a disk into the disk device based on diskMediaIndex + /// + protected void LoadDiskMedia() { if (this is not ZX128Plus3) { @@ -248,9 +245,9 @@ private SpectrumMediaType IdentifyMedia(byte[] data) // disk checking first if (hdr.Contains("EXTENDED CPC DSK", StringComparison.OrdinalIgnoreCase) || hdr.Contains("MV - CPC", StringComparison.OrdinalIgnoreCase)) { - // spectrum .dsk disk file - // check for number of sides - var sides = data[0x31]; + // spectrum .dsk disk file + // check for number of sides + byte sides = data[0x31]; if (sides == 1) return SpectrumMediaType.Disk; else diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/SpectrumBase.Memory.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/SpectrumBase.Memory.cs index 1e00b123937..80305ff1ad3 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/SpectrumBase.Memory.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/SpectrumBase.Memory.cs @@ -92,28 +92,22 @@ public virtual int _ROMpaged /// public abstract byte ReadBus(ushort addr); - /// - /// Pushes a value onto the data bus that should be valid as long as the interrupt is true - /// - public virtual byte PushBus() - { - return 0xFF; - } + /// + /// Pushes a value onto the data bus that should be valid as long as the interrupt is true + /// + public virtual byte PushBus() => 0xFF; - /// - /// Simulates writing to the bus - /// Paging should be handled here - /// - public virtual void WriteBus(ushort addr, byte value) - { - throw new NotImplementedException("Must be overriden"); - } + /// + /// Simulates writing to the bus + /// Paging should be handled here + /// + public virtual void WriteBus(ushort addr, byte value) => throw new NotImplementedException("Must be overriden"); - /// - /// Reads a byte of data from a specified memory address - /// (with memory contention if appropriate) - /// - public abstract byte ReadMemory(ushort addr); + /// + /// Reads a byte of data from a specified memory address + /// (with memory contention if appropriate) + /// + public abstract byte ReadMemory(ushort addr); /// /// Returns the ROM/RAM enum that relates to this particular memory read operation @@ -137,7 +131,7 @@ public virtual void WriteBus(ushort addr, byte value) /// public virtual byte FetchScreenMemory(ushort addr) { - var value = ReadBus((ushort)((addr & 0x3FFF) + 0x4000)); + byte value = ReadBus((ushort)((addr & 0x3FFF) + 0x4000)); //var value = ReadBus(addr); return value; } diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/SpectrumBase.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/SpectrumBase.cs index fe654b1516c..5a2973cfb7e 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/SpectrumBase.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/SpectrumBase.cs @@ -238,7 +238,7 @@ public virtual void HardReset() RAM7 }; - foreach (var r in rams) + foreach (byte[] r in rams) { for (int i = 0; i < r.Length; i++) { @@ -289,7 +289,7 @@ public virtual void SoftReset() RAM7 }; - foreach (var r in rams) + foreach (byte[] r in rams) { for (int i = 0; i < r.Length; i++) { diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ULA.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ULA.cs index 2d3c7a9a304..798351c3b17 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ULA.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ULA.cs @@ -127,7 +127,7 @@ public virtual void CycleClock(long totalCycles) // has more than one cycle past since this last ran // (this can be true if contention has taken place) - var ticksToProcess = totalCycles - LastULATick; + long ticksToProcess = totalCycles - LastULATick; // store the current cycle LastULATick = totalCycles; @@ -284,9 +284,9 @@ public RenderTable(ULA ula, MachineType machineType) /// private void InitRenderer(MachineType machineType) { - for (var t = 0; t < _ula.FrameCycleLength; t++) + for (int t = 0; t < _ula.FrameCycleLength; t++) { - var tStateScreen = t + _ula.RenderTableOffset;// + _ula.InterruptStartTime; + int tStateScreen = t + _ula.RenderTableOffset;// + _ula.InterruptStartTime; if (tStateScreen < 0) tStateScreen += _ula.FrameCycleLength; @@ -301,9 +301,10 @@ private void InitRenderer(MachineType machineType) private void CalculateRenderItem(int item, int line, int pix) { - Renderer[item] = new RenderCycle(); - - Renderer[item].RAction = RenderAction.None; + Renderer[item] = new RenderCycle + { + RAction = RenderAction.None + }; int pitchWidth = _ula.ScreenWidth + _ula.BorderRightWidth + _ula.BorderLeftWidth; int scrPix = pix - _ula.FirstPaperTState; @@ -432,7 +433,7 @@ private void CreateContention(MachineType machineType) continue; } int scrPix = pix - _ula.FirstPaperTState; - if (scrPix < 0 || scrPix >= 128) + if (scrPix is < 0 or >= 128) { Renderer[t].ContentionValue = 0; continue; @@ -446,14 +447,14 @@ private void CreateContention(MachineType machineType) private ushort CalculateByteAddress(int x, int y) { x >>= 2; - var vp = x | (y << 5); + int vp = x | (y << 5); return (ushort)((vp & 0x181F) | ((vp & 0x0700) >> 3) | ((vp & 0x00E0) << 3)); } private ushort CalculateAttributeAddress(int x, int y) { x >>= 2; - var ap = x | ((y >> 3) << 5); + int ap = x | ((y >> 3) << 5); return (ushort)(6144 + ap); } @@ -620,9 +621,7 @@ private void ProcessInkPaper(byte attrData) // swap paper and ink when flash is on if (flashOn && (flash != 0)) { - int temp = palInk; - palInk = palPaper; - palPaper = temp; + (palPaper, palInk) = (palInk, palPaper); } } @@ -631,7 +630,7 @@ private void ProcessInkPaper(byte attrData) /// public void GenerateP3PortTable() { - List table = new List(); + List table = new(); for (int i = 0; i < 0x1000; i++) { ushort r = (ushort)(1 + (4 * i)); @@ -701,23 +700,12 @@ public void ReadFloatingBus(int tstate, ref int result, ushort port) } // floating bus on +2a/+3 always returns a byte with Bit0 set - switch (item.RAction) + result = item.RAction switch { - case RenderTable.RenderAction.BorderAndFetchByte1: - case RenderTable.RenderAction.Shift1AndFetchByte2: - case RenderTable.RenderAction.Shift2AndFetchByte1: - result = (byte)(_machine.FetchScreenMemory(item.ByteAddress) | 0x01); - break; - case RenderTable.RenderAction.BorderAndFetchAttribute1: - case RenderTable.RenderAction.Shift1AndFetchAttribute2: - case RenderTable.RenderAction.Shift2AndFetchAttribute1: - result = (byte)(_machine.FetchScreenMemory(item.AttributeAddress) | 0x01); - break; - default: - result = (byte)(_machine.LastContendedReadByte | 0x01); - break; - } - + RenderTable.RenderAction.BorderAndFetchByte1 or RenderTable.RenderAction.Shift1AndFetchByte2 or RenderTable.RenderAction.Shift2AndFetchByte1 => (byte)(_machine.FetchScreenMemory(item.ByteAddress) | 0x01), + RenderTable.RenderAction.BorderAndFetchAttribute1 or RenderTable.RenderAction.Shift1AndFetchAttribute2 or RenderTable.RenderAction.Shift2AndFetchAttribute1 => (byte)(_machine.FetchScreenMemory(item.AttributeAddress) | 0x01), + _ => (int)(byte)(_machine.LastContendedReadByte | 0x01), + }; break; } } @@ -725,10 +713,7 @@ public void ReadFloatingBus(int tstate, ref int result, ushort port) /// /// Returns the contention value for the current t-state /// - public int GetContentionValue() - { - return GetContentionValue((int)_machine.CurrentFrameCycle); - } + public int GetContentionValue() => GetContentionValue((int)_machine.CurrentFrameCycle); /// /// Returns the contention value for the supplied t-state @@ -763,17 +748,12 @@ public int GetPortContentionValue(int tstate) /// public int[] ScreenBuffer; - private int _virtualWidth; - private int _virtualHeight; - private int _bufferWidth; - private int _bufferHeight; - public int BackgroundColor { get { var settings = _machine.Spectrum.GetSettings(); - var color = settings.BackgroundColor; + int color = settings.BackgroundColor; if (!settings.UseCoreBorderForBackground) return color; else @@ -781,29 +761,13 @@ public int BackgroundColor } } - public int VirtualWidth - { - get => _virtualWidth; - set => _virtualWidth = value; - } + public int VirtualWidth { get; set; } - public int VirtualHeight - { - get => _virtualHeight; - set => _virtualHeight = value; - } + public int VirtualHeight { get; set; } - public int BufferWidth - { - get => _bufferWidth; - set => _bufferWidth = value; - } + public int BufferWidth { get; set; } - public int BufferHeight - { - get => _bufferHeight; - set => _bufferHeight = value; - } + public int BufferHeight { get; set; } public int VsyncNumerator { @@ -820,8 +784,8 @@ public int[] GetVideoBuffer() // Full side borders, no top or bottom border (giving *almost* 16:9 output) case ZXSpectrum.BorderType.Widescreen: // we are cropping out the top and bottom borders - var startPixelsToCrop = ScanLineWidth * BorderTopHeight; - var endPixelsToCrop = ScanLineWidth * BorderBottomHeight; + int startPixelsToCrop = ScanLineWidth * BorderTopHeight; + int endPixelsToCrop = ScanLineWidth * BorderBottomHeight; int index = 0; for (int i = startPixelsToCrop; i < ScreenBuffer.Length - endPixelsToCrop; i++) { @@ -835,12 +799,12 @@ public int[] GetVideoBuffer() case ZXSpectrum.BorderType.Medium: // all border sizes now 24 - var lR = BorderLeftWidth - 24; - var rR = BorderRightWidth - 24; - var tR = BorderTopHeight - 24; - var bR = BorderBottomHeight - 24; - var startP = ScanLineWidth * tR; - var endP = ScanLineWidth * bR; + int lR = BorderLeftWidth - 24; + int rR = BorderRightWidth - 24; + int tR = BorderTopHeight - 24; + int bR = BorderBottomHeight - 24; + int startP = ScanLineWidth * tR; + int endP = ScanLineWidth * bR; int index2 = 0; // line by line @@ -859,12 +823,12 @@ public int[] GetVideoBuffer() case ZXSpectrum.BorderType.Small: // all border sizes now 24 - var lR_ = BorderLeftWidth - 10; - var rR_ = BorderRightWidth - 10; - var tR_ = BorderTopHeight - 10; - var bR_ = BorderBottomHeight - 10; - var startP_ = ScanLineWidth * tR_; - var endP_ = ScanLineWidth * bR_; + int lR_ = BorderLeftWidth - 10; + int rR_ = BorderRightWidth - 10; + int tR_ = BorderTopHeight - 10; + int bR_ = BorderBottomHeight - 10; + int startP_ = ScanLineWidth * tR_; + int endP_ = ScanLineWidth * bR_; int index2_ = 0; // line by line @@ -883,12 +847,12 @@ public int[] GetVideoBuffer() case ZXSpectrum.BorderType.None: // all border sizes now 0 - var lR__ = BorderLeftWidth; - var rR__ = BorderRightWidth; - var tR__ = BorderTopHeight; - var bR__ = BorderBottomHeight; - var startP__ = ScanLineWidth * tR__; - var endP__ = ScanLineWidth * bR__; + int lR__ = BorderLeftWidth; + int rR__ = BorderRightWidth; + int tR__ = BorderTopHeight; + int bR__ = BorderBottomHeight; + int startP__ = ScanLineWidth * tR__; + int endP__ = ScanLineWidth * bR__; int index2__ = 0; // line by line @@ -963,13 +927,7 @@ protected void SetupScreenSize() protected int[] croppedBuffer; - private ZXSpectrum.BorderType _borderType; - - public ZXSpectrum.BorderType borderType - { - get => _borderType; - set => _borderType = value; - } + public ZXSpectrum.BorderType borderType { get; set; } public void SyncState(Serializer ser) { diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum128K/ZX128.Memory.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum128K/ZX128.Memory.cs index 8bb3a0b215f..98e339431f4 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum128K/ZX128.Memory.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum128K/ZX128.Memory.cs @@ -179,7 +179,7 @@ public override void WriteBus(ushort addr, byte value) /// public override byte ReadMemory(ushort addr) { - var data = ReadBus(addr); + byte data = ReadBus(addr); return data; } @@ -188,7 +188,7 @@ public override byte ReadMemory(ushort addr) /// public override ZXSpectrum.CDLResult ReadCDL(ushort addr) { - var result = new ZXSpectrum.CDLResult(); + ZXSpectrum.CDLResult result = new(); int divisor = addr / 0x4000; result.Address = addr % 0x4000; @@ -250,21 +250,18 @@ public override ZXSpectrum.CDLResult ReadCDL(ushort addr) return result; } - /// - /// Writes a byte of data to a specified memory address - /// (with memory contention if appropriate) - /// - public override void WriteMemory(ushort addr, byte value) - { - WriteBus(addr, value); - } + /// + /// Writes a byte of data to a specified memory address + /// (with memory contention if appropriate) + /// + public override void WriteMemory(ushort addr, byte value) => WriteBus(addr, value); - /// - /// Checks whether supplied address is in a potentially contended bank - /// - public override bool IsContended(ushort addr) + /// + /// Checks whether supplied address is in a potentially contended bank + /// + public override bool IsContended(ushort addr) { - var a = addr & 0xc000; + int a = addr & 0xc000; if (a == 0x4000) { @@ -293,17 +290,12 @@ public override bool IsContended(ushort addr) /// public override bool ContendedBankPaged() { - switch (RAMPaged) - { - case 1: - case 3: - case 5: - case 7: - return true; - } - - return false; - } + return RAMPaged switch + { + 1 or 3 or 5 or 7 => true, + _ => false, + }; + } /// /// ULA reads the memory at the specified address @@ -312,7 +304,7 @@ public override bool ContendedBankPaged() /// public override byte FetchScreenMemory(ushort addr) { - byte value = new byte(); + byte value = new(); if (SHADOWPaged && !PagingDisabled) { diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum128K/ZX128.Port.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum128K/ZX128.Port.cs index 5aee11266a2..f720f58e428 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum128K/ZX128.Port.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum128K/ZX128.Port.cs @@ -19,7 +19,7 @@ public override byte ReadPort(ushort port) // ports 0x3ffd & 0x7ffd // traditionally thought to be write-only - if (port == 0x3ffd || port == 0x7ffd) + if (port is 0x3ffd or 0x7ffd) { // https://faqwiki.zxnet.co.uk/wiki/ZX_Spectrum_128 // HAL bugs @@ -83,9 +83,9 @@ public override byte ReadPort(ushort port) public override void WritePort(ushort port, byte value) { // get a BitArray of the port - BitArray portBits = new BitArray(BitConverter.GetBytes(port)); + BitArray portBits = new(BitConverter.GetBytes(port)); // get a BitArray of the value byte - BitArray bits = new BitArray(new byte[] { value }); + BitArray bits = new(new byte[] { value }); // handle AY port writes AYDevice.WritePort(port, value); @@ -100,8 +100,8 @@ public override void WritePort(ushort port, byte value) // if paging is disabled then all writes to this port are ignored until the next reboot if (!PagingDisabled) { - // Bits 0, 1, 2 select the RAM page - var rp = value & 0x07; + // Bits 0, 1, 2 select the RAM page + int rp = value & 0x07; if (RAMPaged != rp && rp < 8) RAMPaged = rp; diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum128KPlus2a/ZX128Plus2a.Memory.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum128KPlus2a/ZX128Plus2a.Memory.cs index 243581e569e..0767bd7c75d 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum128KPlus2a/ZX128Plus2a.Memory.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum128KPlus2a/ZX128Plus2a.Memory.cs @@ -349,7 +349,7 @@ public override void WriteBus(ushort addr, byte value) /// public override byte ReadMemory(ushort addr) { - var data = ReadBus(addr); + byte data = ReadBus(addr); if (CPUMon.NextMemReadContended) { LastContendedReadByte = data; @@ -364,7 +364,7 @@ public override byte ReadMemory(ushort addr) /// public override ZXSpectrum.CDLResult ReadCDL(ushort addr) { - var result = new ZXSpectrum.CDLResult(); + ZXSpectrum.CDLResult result = new(); int divisor = addr / 0x4000; result.Address = addr % 0x4000; @@ -501,14 +501,13 @@ public override ZXSpectrum.CDLResult ReadCDL(ushort addr) return result; } - /// - /// Writes a byte of data to a specified memory address - /// (with memory contention if appropriate) - /// - public override void WriteMemory(ushort addr, byte value) - { - // update ULA screen buffer if necessary BEFORE T1 write - /* + /// + /// Writes a byte of data to a specified memory address + /// (with memory contention if appropriate) + /// + public override void WriteMemory(ushort addr, byte value) => + // update ULA screen buffer if necessary BEFORE T1 write + /* if (!SpecialPagingMode) { if (((addr & 49152) == 16384 || ((addr & 0xc000) == 0xc000) && (RAMPaged == 5 || RAMPaged == 7)) && _render) @@ -530,15 +529,14 @@ public override void WriteMemory(ushort addr, byte value) } } */ - WriteBus(addr, value); - } + WriteBus(addr, value); - /// - /// Checks whether supplied address is in a potentially contended bank - /// - public override bool IsContended(ushort addr) + /// + /// Checks whether supplied address is in a potentially contended bank + /// + public override bool IsContended(ushort addr) { - var a = addr & 0xc000; + int a = addr & 0xc000; if (a == 0x4000) { @@ -567,17 +565,12 @@ public override bool IsContended(ushort addr) /// public override bool ContendedBankPaged() { - switch (RAMPaged) - { - case 4: - case 5: - case 6: - case 7: - return true; - } - - return false; - } + return RAMPaged switch + { + 4 or 5 or 6 or 7 => true, + _ => false, + }; + } /// /// ULA reads the memory at the specified address @@ -586,7 +579,7 @@ public override bool ContendedBankPaged() /// public override byte FetchScreenMemory(ushort addr) { - byte value = new byte(); + byte value = new(); if (SHADOWPaged && !PagingDisabled) { diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum128KPlus2a/ZX128Plus2a.Port.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum128KPlus2a/ZX128Plus2a.Port.cs index 6301e8ee434..4624c59342c 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum128KPlus2a/ZX128Plus2a.Port.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum128KPlus2a/ZX128Plus2a.Port.cs @@ -64,9 +64,9 @@ public override byte ReadPort(ushort port) public override void WritePort(ushort port, byte value) { // get a BitArray of the port - BitArray portBits = new BitArray(BitConverter.GetBytes(port)); + BitArray portBits = new(BitConverter.GetBytes(port)); // get a BitArray of the value byte - BitArray bits = new BitArray(new byte[] { value }); + BitArray bits = new(new byte[] { value }); // Check whether the low bit is reset bool lowBitReset = !portBits[0]; // (port & 0x01) == 0; @@ -80,8 +80,8 @@ public override void WritePort(ushort port, byte value) if (!PagingDisabled) { - // bits 0, 1, 2 select the RAM page - var rp = value & 0x07; + // bits 0, 1, 2 select the RAM page + int rp = value & 0x07; if (rp < 8) RAMPaged = rp; @@ -118,7 +118,7 @@ public override void WritePort(ushort port, byte value) // Config 1 = Bit1-1 Bit2-0 // Config 2 = Bit1-0 Bit2-1 // Config 3 = Bit1-1 Bit2-1 - BitArray confHalfNibble = new BitArray(2); + BitArray confHalfNibble = new(2); confHalfNibble[0] = bits[1]; confHalfNibble[1] = bits[2]; @@ -177,8 +177,8 @@ public override int _ROMpaged { get { - // calculate the ROMpage from the high and low bits - var rp = ZXSpectrum.GetIntFromBitArray(new BitArray(new bool[] { ROMlow, ROMhigh })); + // calculate the ROMpage from the high and low bits + int rp = ZXSpectrum.GetIntFromBitArray(new BitArray(new bool[] { ROMlow, ROMhigh })); if (rp != 0) { diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum128KPlus3/ZX128Plus3.Memory.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum128KPlus3/ZX128Plus3.Memory.cs index ca174ac9036..6f716403958 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum128KPlus3/ZX128Plus3.Memory.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum128KPlus3/ZX128Plus3.Memory.cs @@ -349,7 +349,7 @@ public override void WriteBus(ushort addr, byte value) /// public override byte ReadMemory(ushort addr) { - var data = ReadBus(addr); + byte data = ReadBus(addr); if (CPUMon.NextMemReadContended) { LastContendedReadByte = data; @@ -364,7 +364,7 @@ public override byte ReadMemory(ushort addr) /// public override ZXSpectrum.CDLResult ReadCDL(ushort addr) { - var result = new ZXSpectrum.CDLResult(); + ZXSpectrum.CDLResult result = new(); int divisor = addr / 0x4000; result.Address = addr % 0x4000; @@ -501,45 +501,43 @@ public override ZXSpectrum.CDLResult ReadCDL(ushort addr) return result; } - /// - /// Writes a byte of data to a specified memory address - /// (with memory contention if appropriate) - /// - public override void WriteMemory(ushort addr, byte value) - { - /* - // update ULA screen buffer if necessary BEFORE T1 write - if (!SpecialPagingMode) - { - if (((addr & 49152) == 16384 || ((addr & 0xc000) == 0xc000) && (RAMPaged == 5 || RAMPaged == 7)) && _render) - ULADevice.RenderScreen((int)CurrentFrameCycle); - } - else - { - switch (PagingConfiguration) - { - case 2: - case 3: - if ((addr & 49152) == 16384) - ULADevice.RenderScreen((int)CurrentFrameCycle); - break; - case 1: - if ((addr & 49152) == 16384 || addr >= 0xc000) - ULADevice.RenderScreen((int)CurrentFrameCycle); - break; - } - } - */ - - WriteBus(addr, value); - } + /// + /// Writes a byte of data to a specified memory address + /// (with memory contention if appropriate) + /// + public override void WriteMemory(ushort addr, byte value) => + /* +// update ULA screen buffer if necessary BEFORE T1 write +if (!SpecialPagingMode) +{ +if (((addr & 49152) == 16384 || ((addr & 0xc000) == 0xc000) && (RAMPaged == 5 || RAMPaged == 7)) && _render) +ULADevice.RenderScreen((int)CurrentFrameCycle); +} +else +{ +switch (PagingConfiguration) +{ +case 2: +case 3: +if ((addr & 49152) == 16384) +ULADevice.RenderScreen((int)CurrentFrameCycle); +break; +case 1: +if ((addr & 49152) == 16384 || addr >= 0xc000) +ULADevice.RenderScreen((int)CurrentFrameCycle); +break; +} +} +*/ - /// - /// Checks whether supplied address is in a potentially contended bank - /// - public override bool IsContended(ushort addr) + WriteBus(addr, value); + + /// + /// Checks whether supplied address is in a potentially contended bank + /// + public override bool IsContended(ushort addr) { - var a = addr & 0xc000; + int a = addr & 0xc000; if (a == 0x4000) { @@ -568,17 +566,12 @@ public override bool IsContended(ushort addr) /// public override bool ContendedBankPaged() { - switch (RAMPaged) - { - case 4: - case 5: - case 6: - case 7: - return true; - } - - return false; - } + return RAMPaged switch + { + 4 or 5 or 6 or 7 => true, + _ => false, + }; + } /// /// ULA reads the memory at the specified address @@ -587,7 +580,7 @@ public override bool ContendedBankPaged() /// public override byte FetchScreenMemory(ushort addr) { - byte value = new byte(); + byte value = new(); if (SHADOWPaged && !PagingDisabled) { diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum128KPlus3/ZX128Plus3.Port.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum128KPlus3/ZX128Plus3.Port.cs index 1c1a94ccf02..a5a5d40068e 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum128KPlus3/ZX128Plus3.Port.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum128KPlus3/ZX128Plus3.Port.cs @@ -75,9 +75,9 @@ public override void WritePort(ushort port, byte value) LastFe = value; // get a BitArray of the port - BitArray portBits = new BitArray(BitConverter.GetBytes(port)); + BitArray portBits = new(BitConverter.GetBytes(port)); // get a BitArray of the value byte - BitArray bits = new BitArray(new byte[] { value }); + BitArray bits = new(new byte[] { value }); // Check whether the low bit is reset bool lowBitReset = !portBits[0]; // (port & 0x01) == 0; @@ -91,8 +91,8 @@ public override void WritePort(ushort port, byte value) { if (!PagingDisabled) { - // bits 0, 1, 2 select the RAM page - var rp = value & 0x07; + // bits 0, 1, 2 select the RAM page + int rp = value & 0x07; if (rp < 8) RAMPaged = rp; @@ -127,7 +127,7 @@ public override void WritePort(ushort port, byte value) // Config 1 = Bit1-1 Bit2-0 // Config 2 = Bit1-0 Bit2-1 // Config 3 = Bit1-1 Bit2-1 - BitArray confHalfNibble = new BitArray(2); + BitArray confHalfNibble = new(2); confHalfNibble[0] = bits[1]; confHalfNibble[1] = bits[2]; @@ -184,8 +184,8 @@ public override int _ROMpaged { get { - // calculate the ROMpage from the high and low bits - var rp = ZXSpectrum.GetIntFromBitArray(new BitArray(new bool[] { ROMlow, ROMhigh })); + // calculate the ROMpage from the high and low bits + int rp = ZXSpectrum.GetIntFromBitArray(new BitArray(new bool[] { ROMlow, ROMhigh })); if (rp != 0) { diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum16K/ZX16.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum16K/ZX16.cs index 0a3eaf4d281..c142e61c68e 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum16K/ZX16.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum16K/ZX16.cs @@ -39,7 +39,7 @@ public ZX16(ZXSpectrum spectrum, Z80A cpu, ZXSpectrum.BorderType borderType, Lis public override byte ReadBus(ushort addr) { int divisor = addr / 0x4000; - var index = addr % 0x4000; + int index = addr % 0x4000; // paging logic goes here @@ -62,7 +62,7 @@ public override byte ReadBus(ushort addr) public override void WriteBus(ushort addr, byte value) { int divisor = addr / 0x4000; - var index = addr % 0x4000; + int index = addr % 0x4000; // paging logic goes here @@ -84,7 +84,7 @@ public override void WriteBus(ushort addr, byte value) /// public override byte ReadMemory(ushort addr) { - var data = ReadBus(addr); + byte data = ReadBus(addr); return data; } @@ -93,7 +93,7 @@ public override byte ReadMemory(ushort addr) /// public override ZXSpectrum.CDLResult ReadCDL(ushort addr) { - var res = new ZXSpectrum.CDLResult(); + ZXSpectrum.CDLResult res = new(); int divisor = addr / 0x4000; res.Address = addr % 0x4000; @@ -112,10 +112,7 @@ public override ZXSpectrum.CDLResult ReadCDL(ushort addr) /// Writes a byte of data to a specified memory address /// (with memory contention if appropriate) /// - public override void WriteMemory(ushort addr, byte value) - { - WriteBus(addr, value); - } + public override void WriteMemory(ushort addr, byte value) => WriteBus(addr, value); /// /// Sets up the ROM diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum48K/ZX48.Memory.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum48K/ZX48.Memory.cs index 279a9b3a085..59aaebd6d15 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum48K/ZX48.Memory.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum48K/ZX48.Memory.cs @@ -37,7 +37,7 @@ public partial class ZX48 : SpectrumBase public override byte ReadBus(ushort addr) { int divisor = addr / 0x4000; - var index = addr % 0x4000; + int index = addr % 0x4000; // paging logic goes here @@ -60,7 +60,7 @@ public override byte ReadBus(ushort addr) public override void WriteBus(ushort addr, byte value) { int divisor = addr / 0x4000; - var index = addr % 0x4000; + int index = addr % 0x4000; // paging logic goes here @@ -88,7 +88,7 @@ public override void WriteBus(ushort addr, byte value) /// public override byte ReadMemory(ushort addr) { - var data = ReadBus(addr); + byte data = ReadBus(addr); return data; } @@ -97,7 +97,7 @@ public override byte ReadMemory(ushort addr) /// public override ZXSpectrum.CDLResult ReadCDL(ushort addr) { - var res = new ZXSpectrum.CDLResult(); + ZXSpectrum.CDLResult res = new(); int divisor = addr / 0x4000; res.Address = addr % 0x4000; @@ -114,37 +114,31 @@ public override ZXSpectrum.CDLResult ReadCDL(ushort addr) return res; } - /// - /// Writes a byte of data to a specified memory address - /// (with memory contention if appropriate) - /// - public override void WriteMemory(ushort addr, byte value) - { - WriteBus(addr, value); - } + /// + /// Writes a byte of data to a specified memory address + /// (with memory contention if appropriate) + /// + public override void WriteMemory(ushort addr, byte value) => WriteBus(addr, value); - /// - /// Checks whether supplied address is in a potentially contended bank - /// - public override bool IsContended(ushort addr) + /// + /// Checks whether supplied address is in a potentially contended bank + /// + public override bool IsContended(ushort addr) { if ((addr & 49152) == 16384) return true; return false; } - /// - /// Returns TRUE if there is a contended bank paged in - /// - public override bool ContendedBankPaged() - { - return false; - } + /// + /// Returns TRUE if there is a contended bank paged in + /// + public override bool ContendedBankPaged() => false; - /// - /// Sets up the ROM - /// - public override void InitROM(RomData romData) + /// + /// Sets up the ROM + /// + public override void InitROM(RomData romData) { RomData = romData; // for 16/48k machines only ROM0 is used (no paging) diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum48K/ZX48.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum48K/ZX48.cs index eba23b3b599..9524fe9f8c2 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum48K/ZX48.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Machine/ZXSpectrum48K/ZX48.cs @@ -39,7 +39,7 @@ public override void HardReset() { base.HardReset(); - Random rn = new Random(); + Random rn = new(); for (int d = 0; d < 6912; d++) { RAM0[d] = (byte)rn.Next(255); diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Disk/CPCFormat/CPCExtendedFloppyDisk.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Disk/CPCFormat/CPCExtendedFloppyDisk.cs index da3b4446b78..1f0a869cb9d 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Disk/CPCFormat/CPCExtendedFloppyDisk.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Disk/CPCFormat/CPCExtendedFloppyDisk.cs @@ -46,7 +46,7 @@ public override bool ParseDisk(byte[] data) if (DiskHeader.NumberOfSides > 1) { - StringBuilder sbm = new StringBuilder(); + StringBuilder sbm = new(); sbm.AppendLine(); sbm.AppendLine(); sbm.AppendLine("The detected disk image contains multiple sides."); @@ -57,7 +57,7 @@ public override bool ParseDisk(byte[] data) if (DiskHeader.NumberOfTracks > 42) { - StringBuilder sbm = new StringBuilder(); + StringBuilder sbm = new(); sbm.AppendLine(); sbm.AppendLine(); sbm.AppendLine("The detected disk is an " + DiskHeader.NumberOfTracks + " track disk image."); @@ -80,16 +80,19 @@ public override bool ParseDisk(byte[] data) // check for unformatted track if (DiskHeader.TrackSizes[i] == 0) { - DiskTracks[i] = new Track(); - DiskTracks[i].Sectors = new Sector[0]; + DiskTracks[i] = new Track + { + Sectors = new Sector[0] + }; continue; } int p = pos; - DiskTracks[i] = new Track(); - - // track info block - DiskTracks[i].TrackIdent = Encoding.ASCII.GetString(data, p, 12); + DiskTracks[i] = new Track + { + // track info block + TrackIdent = Encoding.ASCII.GetString(data, p, 12) + }; p += 16; DiskTracks[i].TrackNumber = data[p++]; DiskTracks[i].SideNumber = data[p++]; @@ -106,15 +109,16 @@ public override bool ParseDisk(byte[] data) DiskTracks[i].Sectors = new Sector[DiskTracks[i].NumberOfSectors]; for (int s = 0; s < DiskTracks[i].NumberOfSectors; s++) { - DiskTracks[i].Sectors[s] = new Sector(); - - DiskTracks[i].Sectors[s].TrackNumber = data[p++]; - DiskTracks[i].Sectors[s].SideNumber = data[p++]; - DiskTracks[i].Sectors[s].SectorID = data[p++]; - DiskTracks[i].Sectors[s].SectorSize = data[p++]; - DiskTracks[i].Sectors[s].Status1 = data[p++]; - DiskTracks[i].Sectors[s].Status2 = data[p++]; - DiskTracks[i].Sectors[s].ActualDataByteLength = MediaConverter.GetWordValue(data, p); + DiskTracks[i].Sectors[s] = new Sector + { + TrackNumber = data[p++], + SideNumber = data[p++], + SectorID = data[p++], + SectorSize = data[p++], + Status1 = data[p++], + Status2 = data[p++], + ActualDataByteLength = MediaConverter.GetWordValue(data, p) + }; p += 2; // sector data - begins at 0x100 offset from the start of the track info block (in this case dpos) @@ -204,7 +208,7 @@ public static bool SplitDoubleSided(byte[] data, List results) while (tCount < data[0x30] * data[0x31]) { // which side is this? - var side = data[mPos + 0x11]; + byte side = data[mPos + 0x11]; if (side == 0) { // side 1 diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Disk/CPCFormat/CPCFloppyDisk.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Disk/CPCFormat/CPCFloppyDisk.cs index a78ed1515f2..037ae82cb7d 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Disk/CPCFormat/CPCFloppyDisk.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Disk/CPCFormat/CPCFloppyDisk.cs @@ -46,7 +46,7 @@ public override bool ParseDisk(byte[] data) if (DiskHeader.NumberOfSides > 1) { - StringBuilder sbm = new StringBuilder(); + StringBuilder sbm = new(); sbm.AppendLine(); sbm.AppendLine(); sbm.AppendLine("The detected disk image contains multiple sides."); @@ -57,7 +57,7 @@ public override bool ParseDisk(byte[] data) if (DiskHeader.NumberOfTracks > 42) { - StringBuilder sbm = new StringBuilder(); + StringBuilder sbm = new(); sbm.AppendLine(); sbm.AppendLine(); sbm.AppendLine("The detected disk is an " + DiskHeader.NumberOfTracks + " track disk image."); @@ -81,16 +81,19 @@ public override bool ParseDisk(byte[] data) // check for unformatted track if (DiskHeader.TrackSizes[i] == 0) { - DiskTracks[i] = new Track(); - DiskTracks[i].Sectors = new Sector[0]; + DiskTracks[i] = new Track + { + Sectors = new Sector[0] + }; continue; } int p = pos; - DiskTracks[i] = new Track(); - - // track info block - DiskTracks[i].TrackIdent = Encoding.ASCII.GetString(data, p, 12); + DiskTracks[i] = new Track + { + // track info block + TrackIdent = Encoding.ASCII.GetString(data, p, 12) + }; p += 16; DiskTracks[i].TrackNumber = data[p++]; DiskTracks[i].SideNumber = data[p++]; @@ -106,15 +109,16 @@ public override bool ParseDisk(byte[] data) DiskTracks[i].Sectors = new Sector[DiskTracks[i].NumberOfSectors]; for (int s = 0; s < DiskTracks[i].NumberOfSectors; s++) { - DiskTracks[i].Sectors[s] = new Sector(); - - DiskTracks[i].Sectors[s].TrackNumber = data[p++]; - DiskTracks[i].Sectors[s].SideNumber = data[p++]; - DiskTracks[i].Sectors[s].SectorID = data[p++]; - DiskTracks[i].Sectors[s].SectorSize = data[p++]; - DiskTracks[i].Sectors[s].Status1 = data[p++]; - DiskTracks[i].Sectors[s].Status2 = data[p++]; - DiskTracks[i].Sectors[s].ActualDataByteLength = MediaConverter.GetWordValue(data, p); + DiskTracks[i].Sectors[s] = new Sector + { + TrackNumber = data[p++], + SideNumber = data[p++], + SectorID = data[p++], + SectorSize = data[p++], + Status1 = data[p++], + Status2 = data[p++], + ActualDataByteLength = MediaConverter.GetWordValue(data, p) + }; p += 2; // actualdatabytelength value is calculated now @@ -185,20 +189,20 @@ public static bool SplitDoubleSided(byte[] data, List results) S0[0x31] = 1; S1[0x31] = 1; - var trkSize = MediaConverter.GetWordValue(data, 0x32); + ushort trkSize = MediaConverter.GetWordValue(data, 0x32); // start at track info blocks int mPos = 0x100; int s0Pos = 0x100; int s1Pos = 0x100; - var numTrks = data[0x30]; - var numSides = data[0x31]; + byte numTrks = data[0x30]; + byte numSides = data[0x31]; while (mPos < trkSize * data[0x30] * data[0x31]) { // which side is this? - var side = data[mPos + 0x11]; + byte side = data[mPos + 0x11]; if (side == 0) { // side 1 diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Disk/FloppyDisk.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Disk/FloppyDisk.cs index 760a0507ed7..0e9222228be 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Disk/FloppyDisk.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Disk/FloppyDisk.cs @@ -20,7 +20,7 @@ public abstract class FloppyDisk /// /// Disk information header /// - public Header DiskHeader = new Header(); + public Header DiskHeader = new(); /// /// Track array @@ -93,12 +93,10 @@ public int RandomCounter /// TRUE: disk parsed /// FALSE: unable to parse disk /// - public virtual bool ParseDisk(byte[] diskData) - { + public virtual bool ParseDisk(byte[] diskData) => // default result // override in inheriting class - return false; - } + false; /// /// Examines the floppydisk data to work out what protection (if any) is present @@ -114,11 +112,11 @@ public virtual void ParseProtection() { Protection = ProtectionType.Speedlock; - Sector sec = DiskTracks[0].Sectors[1]; + var sec = DiskTracks[0].Sectors[1]; if (!sec.ContainsMultipleWeakSectors) { byte[] origData = sec.SectorData.ToArray(); - List data = new List(); + List data = new(); for (int m = 0; m < 3; m++) { for (int i = 0; i < 512; i++) @@ -245,7 +243,7 @@ public bool DetectSpeedlock(ref int[] weak) return false; // sector[1] (SectorID 2) contains the weak sectors - Sector sec = DiskTracks[0].Sectors[1]; + var sec = DiskTracks[0].Sectors[1]; // check for correct sector 1 lengths if (sec.SectorSize != 2 || @@ -288,8 +286,8 @@ public bool DetectAlkatraz(ref int[] weak) { try { - var data1 = DiskTracks[0].Sectors[0].SectorData; - var data2 = DiskTracks[0].Sectors[0].SectorData.Length; + byte[] data1 = DiskTracks[0].Sectors[0].SectorData; + int data2 = DiskTracks[0].Sectors[0].SectorData.Length; } catch (Exception) { @@ -329,8 +327,8 @@ public bool DetectPaulOwens(ref int[] weak) { try { - var data1 = DiskTracks[0].Sectors[2].SectorData; - var data2 = DiskTracks[0].Sectors[2].SectorData.Length; + byte[] data1 = DiskTracks[0].Sectors[2].SectorData; + int data2 = DiskTracks[0].Sectors[2].SectorData.Length; } catch (Exception) { @@ -365,10 +363,10 @@ public bool DetectHexagon(ref int[] weak) { try { - var data1 = DiskTracks[0].Sectors.Length; - var data2 = DiskTracks[0].Sectors[8].ActualDataByteLength; - var data3 = DiskTracks[0].Sectors[8].SectorData; - var data4 = DiskTracks[0].Sectors[8].SectorData.Length; + int data1 = DiskTracks[0].Sectors.Length; + int data2 = DiskTracks[0].Sectors[8].ActualDataByteLength; + byte[] data3 = DiskTracks[0].Sectors[8].SectorData; + int data4 = DiskTracks[0].Sectors[8].SectorData.Length; var data5 = DiskTracks[1].Sectors[0]; } catch (Exception) @@ -505,10 +503,7 @@ protected virtual void SpeedlockDetection() /// /// Returns the track count for the disk /// - public virtual int GetTrackCount() - { - return DiskHeader.NumberOfTracks * DiskHeader.NumberOfSides; - } + public virtual int GetTrackCount() => DiskHeader.NumberOfTracks * DiskHeader.NumberOfSides; /// /// Reads the current sector ID info @@ -534,11 +529,12 @@ public virtual CHRN ReadID(byte trackIndex, byte side, int sectorIndex) var sector = track.Sectors[sectorIndex]; - CHRN chrn = new CHRN(); - - chrn.C = sector.TrackNumber; - chrn.H = sector.SideNumber; - chrn.R = sector.SectorID; + CHRN chrn = new() + { + C = sector.TrackNumber, + H = sector.SideNumber, + R = sector.SectorID + }; // wrap around for N > 7 if (sector.SectorSize > 7) @@ -603,7 +599,7 @@ public virtual byte[] TrackSectorData { get { - List list = new List(); + List list = new(); foreach (var sec in Sectors) { @@ -661,7 +657,7 @@ public byte[] ActualData int size = 0x80 << SectorSize; if (size > ActualDataByteLength) { - List l = new List(); + List l = new(); l.AddRange(SectorData); for (int i = 0; i < size - ActualDataByteLength; i++) { @@ -703,7 +699,7 @@ public byte[] ActualData } public CHRN SectorIDInfo => - new CHRN + new() { C = TrackNumber, H = SideNumber, diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Disk/IPFFormat/IPFFloppyDisk.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Disk/IPFFormat/IPFFloppyDisk.cs index 4bd90bd4374..75b512574ee 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Disk/IPFFormat/IPFFloppyDisk.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Disk/IPFFormat/IPFFloppyDisk.cs @@ -35,13 +35,13 @@ public override bool ParseDisk(byte[] data) int pos = 0; - List blocks = new List(); + List blocks = new(); while (pos < data.Length) { try { - var block = IPFBlock.ParseNextBlock(ref pos, this, data, blocks); + IPFBlock block = IPFBlock.ParseNextBlock(ref pos, this, data, blocks); if (block == null) { @@ -58,13 +58,13 @@ public override bool ParseDisk(byte[] data) } catch (Exception ex) { - var e = ex.ToString(); + string e = ex.ToString(); } } // now process the blocks var infoBlock = blocks.Find(static a => a.RecordType == RecordHeaderType.INFO); - var IMGEblocks = blocks.Where(a => a.RecordType == RecordHeaderType.IMGE).ToList(); + List IMGEblocks = blocks.Where(a => a.RecordType == RecordHeaderType.IMGE).ToList(); var DATAblocks = blocks.Where(a => a.RecordType == RecordHeaderType.DATA); DiskHeader.NumberOfTracks = (byte)(IMGEblocks.Count); @@ -78,7 +78,7 @@ public override bool ParseDisk(byte[] data) DiskTracks[t] = new Track(); var trk = DiskTracks[t]; - var blockCount = img.IMGEblockCount; + int blockCount = img.IMGEblockCount; var dataBlock = DATAblocks.FirstOrDefault(a => a.DATAdataKey == img.IMGEdataKey); trk.SideNumber = (byte)img.IMGEside; @@ -90,7 +90,7 @@ public override bool ParseDisk(byte[] data) int p = 0; for (int d = 0; d < blockCount; d++) { - var extraDataAreaStart = 32 * blockCount; + int extraDataAreaStart = 32 * blockCount; trk.Sectors[d] = new Sector(); var sector = trk.Sectors[d]; @@ -145,7 +145,7 @@ public override bool ParseDisk(byte[] data) // data stream elements if (dataBits != 0) { - var dsLocation = dataOffset; + int dsLocation = dataOffset; for (; ; ) { @@ -156,11 +156,11 @@ public override bool ParseDisk(byte[] data) break; } - var sampleSize = ((dataHead & 0xE0) >> 5); - var dataType = dataHead & 0x1F; + int sampleSize = ((dataHead & 0xE0) >> 5); + int dataType = dataHead & 0x1F; byte[] dSize = new byte[sampleSize]; Array.Copy(dataBlock.DATAextraDataRaw, dsLocation, dSize, 0, sampleSize); - var dataSize = MediaConverter.GetBEInt32FromByteArray(dSize); + int dataSize = MediaConverter.GetBEInt32FromByteArray(dSize); dsLocation += dSize.Length; int dataLen; byte[] dataStream = new byte[0]; @@ -292,8 +292,10 @@ public class IPFBlock public static IPFBlock ParseNextBlock(ref int startPos, FloppyDisk disk, byte[] data, List blockCollection) { - IPFBlock ipf = new IPFBlock(); - ipf.StartPos = startPos; + IPFBlock ipf = new() + { + StartPos = startPos + }; if (startPos >= data.Length) { diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Disk/UDIFormat/UDI1_0FloppyDisk.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Disk/UDIFormat/UDI1_0FloppyDisk.cs index 232435898b5..cab1d223e05 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Disk/UDIFormat/UDI1_0FloppyDisk.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Disk/UDIFormat/UDI1_0FloppyDisk.cs @@ -54,7 +54,7 @@ public override bool ParseDisk(byte[] data) int fileSize = MediaConverter.GetInt32(data, 4); // not including the final 4-byte checksum // ignore extended header - var extHdrSize = MediaConverter.GetInt32(data, 0x0C); + int extHdrSize = MediaConverter.GetInt32(data, 0x0C); int pos = 0x10 + extHdrSize; // process track information @@ -106,7 +106,7 @@ public static bool SplitDoubleSided(byte[] data, List results) byte[] S1 = new byte[data.Length]; // header - var extHdr = MediaConverter.GetInt32(data, 0x0C); + int extHdr = MediaConverter.GetInt32(data, 0x0C); Array.Copy(data, 0, S0, 0, 0x10 + extHdr); Array.Copy(data, 0, S1, 0, 0x10 + extHdr); // change side number @@ -122,9 +122,9 @@ public static bool SplitDoubleSided(byte[] data, List results) // process track information for (int t = 0; t < (data[0x09] + 1) * 2; t++) { - var TLEN = MediaConverter.GetWordValue(data, pos + 1); - var CLEN = TLEN / 8 + (TLEN % 8 / 7) / 8; - var blockSize = TLEN + CLEN + 3; + ushort TLEN = MediaConverter.GetWordValue(data, pos + 1); + int CLEN = TLEN / 8 + (TLEN % 8 / 7) / 8; + int blockSize = TLEN + CLEN + 3; // 2 sided image: side 0 tracks will all have t as an even number try @@ -172,8 +172,8 @@ public override Sector[] Sectors get { List secs = new(); - var datas = TrackData.Skip(3).Take(TLEN).ToArray(); - var clocks = new BitArray(TrackData.Skip(3 + TLEN).Take(CLEN).ToArray()); + byte[] datas = TrackData.Skip(3).Take(TLEN).ToArray(); + BitArray clocks = new(TrackData.Skip(3 + TLEN).Take(CLEN).ToArray()); return secs.ToArray(); } diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/MediaConverter.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/MediaConverter.cs index 16061604282..8654fcbb35a 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/MediaConverter.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/MediaConverter.cs @@ -62,10 +62,7 @@ public static byte[] GetBytes(int value) /// /// Returns an int32 from a byte array based on offset /// - public static int GetInt32(byte[] buf, int offsetIndex) - { - return buf[offsetIndex] | buf[offsetIndex + 1] << 8 | buf[offsetIndex + 2] << 16 | buf[offsetIndex + 3] << 24; - } + public static int GetInt32(byte[] buf, int offsetIndex) => buf[offsetIndex] | buf[offsetIndex + 1] << 8 | buf[offsetIndex + 2] << 16 | buf[offsetIndex + 3] << 24; /// /// Returns an int32 from a byte array based on offset (in BIG ENDIAN format) @@ -89,41 +86,27 @@ public static int GetBEInt32FromByteArray(byte[] buf) return 0; int res = b[0]; int pos = 1; - switch (b.Length) + return b.Length switch { - case 1: - default: - return res; - case 2: - return res | b[pos] << (8 * pos++); - case 3: - return res | b[pos] << (8 * pos++) | b[pos] << (8 * pos++); - case 4: - return res | b[pos] << (8 * pos++) | b[pos] << (8 * pos++) | b[pos] << (8 * pos++); - case 5: - return res | b[pos] << (8 * pos++) | b[pos] << (8 * pos++) | b[pos] << (8 * pos++) | b[pos] << (8 * pos++); - case 6: - return res | b[pos] << (8 * pos++) | b[pos] << (8 * pos++) | b[pos] << (8 * pos++) | b[pos] << (8 * pos++) | b[pos] << (8 * pos++); - case 7: - return res | b[pos] << (8 * pos++) | b[pos] << (8 * pos++) | b[pos] << (8 * pos++) | b[pos] << (8 * pos++) | b[pos] << (8 * pos++) | b[pos] << (8 * pos++); - } + 2 => res | b[pos] << (8 * pos++), + 3 => res | b[pos] << (8 * pos++) | b[pos] << (8 * pos++), + 4 => res | b[pos] << (8 * pos++) | b[pos] << (8 * pos++) | b[pos] << (8 * pos++), + 5 => res | b[pos] << (8 * pos++) | b[pos] << (8 * pos++) | b[pos] << (8 * pos++) | b[pos] << (8 * pos++), + 6 => res | b[pos] << (8 * pos++) | b[pos] << (8 * pos++) | b[pos] << (8 * pos++) | b[pos] << (8 * pos++) | b[pos] << (8 * pos++), + 7 => res | b[pos] << (8 * pos++) | b[pos] << (8 * pos++) | b[pos] << (8 * pos++) | b[pos] << (8 * pos++) | b[pos] << (8 * pos++) | b[pos] << (8 * pos++), + _ => res, + }; } /// /// Returns an int32 from a byte array based on offset /// - public static uint GetUInt32(byte[] buf, int offsetIndex) - { - return (uint)(buf[offsetIndex] | buf[offsetIndex + 1] << 8 | buf[offsetIndex + 2] << 16 | buf[offsetIndex + 3] << 24); - } + public static uint GetUInt32(byte[] buf, int offsetIndex) => (uint)(buf[offsetIndex] | buf[offsetIndex + 1] << 8 | buf[offsetIndex + 2] << 16 | buf[offsetIndex + 3] << 24); /// /// Returns an uint16 from a byte array based on offset /// - public static ushort GetWordValue(byte[] buf, int offsetIndex) - { - return (ushort)(buf[offsetIndex] | buf[offsetIndex + 1] << 8); - } + public static ushort GetWordValue(byte[] buf, int offsetIndex) => (ushort)(buf[offsetIndex] | buf[offsetIndex + 1] << 8); /// /// Updates a byte array with a uint16 value based on offset @@ -172,12 +155,12 @@ public static bool CheckChecksum(byte[] buf, int len) /// public static void DecompressZRLE(byte[] sourceBuffer, ref byte[] destBuffer) { - MemoryStream stream = new MemoryStream(); + MemoryStream stream = new(); stream.Write(sourceBuffer, 0, sourceBuffer.Length); stream.Position = 0; stream.ReadByte(); stream.ReadByte(); - DeflateStream ds = new DeflateStream(stream, CompressionMode.Decompress, false); + DeflateStream ds = new(stream, CompressionMode.Decompress, false); ds.Read(destBuffer, 0, destBuffer.Length); } @@ -185,7 +168,7 @@ public static void DecompressZRLE(byte[] sourceBuffer, ref byte[] destBuffer) public static byte[] SerializeRaw(object obj) { int rSize = Marshal.SizeOf(obj); - IntPtr buff = Marshal.AllocHGlobal(rSize); + var buff = Marshal.AllocHGlobal(rSize); Marshal.StructureToPtr(obj, buff, false); byte[] rData = new byte[rSize]; Marshal.Copy(buff, rData, 0, rSize); @@ -197,7 +180,7 @@ public static T DeserializeRaw(byte[] rData, int pos) int rSize = Marshal.SizeOf(typeof(T)); if (rSize > rData.Length - pos) throw new Exception(); - IntPtr buff = Marshal.AllocHGlobal(rSize); + var buff = Marshal.AllocHGlobal(rSize); Marshal.Copy(rData, pos, buff, rSize); T rObj = (T)Marshal.PtrToStructure(buff, typeof(T)); Marshal.FreeHGlobal(buff); diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Snapshot/SZX/SZX.Methods.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Snapshot/SZX/SZX.Methods.cs index 0be68276de6..c8e5ead6b0b 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Snapshot/SZX/SZX.Methods.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Snapshot/SZX/SZX.Methods.cs @@ -1,4 +1,4 @@ -using BizHawk.Emulation.Cores.Components.Z80A; +using BizHawk.Emulation.Cores.Components.Z80A; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; @@ -14,7 +14,9 @@ public partial class SZX { private readonly SpectrumBase _machine; + #pragma warning disable IDE0051 private Z80A _cpu => _machine.CPU; + #pragma warning restore IDE0051 private SZX(SpectrumBase machine) { @@ -26,21 +28,21 @@ private SZX(SpectrumBase machine) /// public static byte[] ExportSZX(SpectrumBase machine) { - var s = new SZX(machine); + SZX s = new(machine); byte[] result = null; - using (var ms = new MemoryStream()) + using (MemoryStream ms = new()) { - using (var r = new BinaryWriter(ms)) + using (BinaryWriter r = new(ms)) { // temp buffer byte[] buff; // working block - ZXSTBLOCK block = new ZXSTBLOCK(); + ZXSTBLOCK block = new(); // header - ZXSTHEADER header = new ZXSTHEADER + ZXSTHEADER header = new() { dwMagic = MediaConverter.GetUInt32(Encoding.UTF8.GetBytes("ZXST"), 0), chMajorVersion = 1, @@ -106,7 +108,7 @@ public static byte[] ExportSZX(SpectrumBase machine) // ZXSTAYBLOCK - if (s._machine.Spectrum.MachineType != MachineType.ZXSpectrum16 && s._machine.Spectrum.MachineType != MachineType.ZXSpectrum48) + if (s._machine.Spectrum.MachineType is not MachineType.ZXSpectrum16 and not MachineType.ZXSpectrum48) { var gStruct = s.GetZXSTAYBLOCK(); block.dwId = MediaConverter.GetUInt32(Encoding.UTF8.GetBytes("AY\0\0"), 0); @@ -161,7 +163,7 @@ public static byte[] ExportSZX(SpectrumBase machine) case MachineType.ZXSpectrum128Plus2: case MachineType.ZXSpectrum128Plus2a: case MachineType.ZXSpectrum128Plus3: - List rams = new List + List rams = new() { s._machine.RAM0, s._machine.RAM1, s._machine.RAM2, s._machine.RAM3, s._machine.RAM4, s._machine.RAM5, s._machine.RAM6, s._machine.RAM7 @@ -231,17 +233,19 @@ public static byte[] ExportSZX(SpectrumBase machine) private ZXSTRAMPAGE GetZXSTRAMPAGE(byte page, byte[] RAM) { - var s = new ZXSTRAMPAGE(); - s.wFlags = 0; // uncompressed only at the moment - s.chPageNo = page; - s.ramPage = RAM; + ZXSTRAMPAGE s = new() + { + wFlags = 0, // uncompressed only at the moment + chPageNo = page, + ramPage = RAM + }; return s; } private ZXSTCREATOR GetZXSTCREATOR() { - var s = new ZXSTCREATOR(); - var str = "BIZHAWK EMULATOR".ToCharArray(); + ZXSTCREATOR s = new(); + char[] str = "BIZHAWK EMULATOR".ToCharArray(); s.szCreator = new char[32]; for (int i = 0; i < str.Length; i++) s.szCreator[i] = str[i]; @@ -253,7 +257,7 @@ private ZXSTCREATOR GetZXSTCREATOR() private ZXSTZ80REGS GetZXSTZ80REGS() { - var s = new ZXSTZ80REGS + ZXSTZ80REGS s = new() { AF = (ushort) _machine.Spectrum.GetCpuFlagsAndRegisters()["AF"].Value, BC = (ushort) _machine.Spectrum.GetCpuFlagsAndRegisters()["BC"].Value, @@ -291,9 +295,11 @@ private ZXSTZ80REGS GetZXSTZ80REGS() private ZXSTSPECREGS GetZXSTSPECREGS() { - var s = new ZXSTSPECREGS(); - s.chBorder = _machine.ULADevice.BorderColor > 7 ? (byte)0 : (byte)_machine.ULADevice.BorderColor; - s.chFe = _machine.LastFe; + ZXSTSPECREGS s = new() + { + chBorder = _machine.ULADevice.BorderColor > 7 ? (byte)0 : (byte)_machine.ULADevice.BorderColor, + chFe = _machine.LastFe + }; byte x7ffd = (byte)_machine.RAMPaged; byte x1ffd = 0; switch (_machine.Spectrum.MachineType) @@ -357,16 +363,20 @@ private ZXSTSPECREGS GetZXSTSPECREGS() private ZXSTKEYBOARD GetZXSTKEYBOARD() { - var s = new ZXSTKEYBOARD(); - s.dwFlags = 0; //no issue 2 emulation + ZXSTKEYBOARD s = new() + { + dwFlags = 0 //no issue 2 emulation + }; s.chKeyboardJoystick |= (byte)JoystickTypes.ZXSTKJT_NONE; return s; } private ZXSTJOYSTICK GetZXSTJOYSTICK() { - var s = new ZXSTJOYSTICK(); - s.dwFlags = 0; //depreciated + ZXSTJOYSTICK s = new() + { + dwFlags = 0 //depreciated + }; s.chTypePlayer1 |= (byte)JoystickTypes.ZXSTKJT_KEMPSTON; s.chTypePlayer2 |= (byte)JoystickTypes.ZXSTKJT_SINCLAIR1; return s; @@ -374,10 +384,12 @@ private ZXSTJOYSTICK GetZXSTJOYSTICK() private ZXSTAYBLOCK GetZXSTAYBLOCK() { - var s = new ZXSTAYBLOCK(); - s.cFlags = 0; // no external units - s.chCurrentRegister = (byte)_machine.AYDevice.SelectedRegister; - var regs = _machine.AYDevice.ExportRegisters(); + ZXSTAYBLOCK s = new() + { + cFlags = 0, // no external units + chCurrentRegister = (byte)_machine.AYDevice.SelectedRegister + }; + int[] regs = _machine.AYDevice.ExportRegisters(); s.chAyRegs = new byte[16]; for (int i = 0; i < 16; i++) { @@ -386,9 +398,10 @@ private ZXSTAYBLOCK GetZXSTAYBLOCK() return s; } + #pragma warning disable IDE0051 private ZXSTTAPE GetZXSTTAPE() { - var s = new ZXSTTAPE(); + ZXSTTAPE s = new(); s.wFlags |= (int)CassetteRecorderState.ZXSTTP_EMBEDDED; s.wCurrentBlockNo = (ushort)_machine.TapeDevice.CurrentDataBlockIndex; s.dwCompressedSize = _machine.tapeImages[_machine.TapeDevice.CurrentDataBlockIndex].Length; @@ -404,19 +417,24 @@ private ZXSTTAPE GetZXSTTAPE() private ZXSTPLUS3 GetZXSTPLUS3() { - var s = new ZXSTPLUS3(); - s.chNumDrives = 1; - s.fMotorOn = _machine.UPDDiskDevice.FDD_FLAG_MOTOR ? (byte)1 : (byte)0; + ZXSTPLUS3 s = new() + { + chNumDrives = 1, + fMotorOn = _machine.UPDDiskDevice.FDD_FLAG_MOTOR ? (byte)1 : (byte)0 + }; return s; } private ZXSTDSKFILE GetZXSTDSKFILE() { - var s = new ZXSTDSKFILE(); - s.wFlags = 0; - s.chDriveNum = 0; - s.dwUncompressedSize = 0; + ZXSTDSKFILE s = new() + { + wFlags = 0, + chDriveNum = 0, + dwUncompressedSize = 0 + }; return s; } + #pragma warning restore IDE0051 } } diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/CSW/CswConverter.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/CSW/CswConverter.cs index 86c0643e2ad..1f31949adc8 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/CSW/CswConverter.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/CSW/CswConverter.cs @@ -192,11 +192,13 @@ 0x1D 0x00 BYTE[3] Reserved. // create the single tape block // (use DATA block for now so initial signal level is handled correctly by the datacorder device) - TapeDataBlock t = new TapeDataBlock(); - t.BlockDescription = BlockType.CSW_Recording; - t.BlockID = 0x18; - t.DataPeriods = new List(); - t.DataLevels = new List(); + TapeDataBlock t = new() + { + BlockDescription = BlockType.CSW_Recording, + BlockID = 0x18, + DataPeriods = new List(), + DataLevels = new List() + }; if (flags.Bit(0)) t.InitialPulseLevel = true; @@ -205,7 +207,7 @@ 0x1D 0x00 BYTE[3] Reserved. bool currLevel = !t.InitialPulseLevel; - var rate = (69888 * 50) / sampleRate; + int rate = (69888 * 50) / sampleRate; for (int i = 0; i < cswDataUncompressed.Length;) { diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/PZX/PzxConverter.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/PZX/PzxConverter.cs index aa487e45e44..6396dc91e67 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/PZX/PzxConverter.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/PZX/PzxConverter.cs @@ -105,7 +105,7 @@ 8 u8[size] data arbitrary amount of block data. _position = 0; // parse all blocks out into seperate byte arrays first - List bDatas = new List(); + List bDatas = new(); while (_position < data.Length) { @@ -125,13 +125,13 @@ 8 u8[size] data arbitrary amount of block data. } // process the blocks - foreach (var b in bDatas) + foreach (byte[] b in bDatas) { int pos = 8; string blockId = Encoding.ASCII.GetString(b, 0, 4); int blockSize = GetInt32(b, 4); - TapeDataBlock t = new TapeDataBlock(); + TapeDataBlock t = new(); switch (blockId) { @@ -165,7 +165,7 @@ 6 ... ... ditto repeated until the end of the block t.InitialPulseLevel = false; bool pLevel = !t.InitialPulseLevel; - List pulses = new List(); + List pulses = new(); while (pos < blockSize + 8) { @@ -196,7 +196,7 @@ 6 ... ... ditto repeated until the end of the block t.BlockDescription = BlockType.PULS; t.PauseInMS = 0; - foreach (var x in pulses) + foreach (ushort[] x in pulses) { for (int i = 0; i < x[0]; i++) { @@ -228,9 +228,9 @@ 8 u16[p0] s0 sequence of pulse durations encoding bit equa t.DataPeriods = new List(); t.DataLevels = new List(); - List s0 = new List(); - List s1 = new List(); - List dData = new List(); + List s0 = new(); + List s1 = new(); + List dData = new(); uint initPulseLevel = 1; int dCount = 1; @@ -250,36 +250,36 @@ 8 u16[p0] s0 sequence of pulse durations encoding bit equa tail = GetWordValue(b, pos); pos += 2; - var p0 = b[pos++]; - var p1 = b[pos++]; + byte p0 = b[pos++]; + byte p1 = b[pos++]; for (int i = 0; i < p1; i++) { - var s = GetWordValue(b, pos); + ushort s = GetWordValue(b, pos); pos += 2; s0.Add(s); } for (int i = 0; i < p1; i++) { - var s = GetWordValue(b, pos); + ushort s = GetWordValue(b, pos); pos += 2; s1.Add(s); } for (int i = 0; i < Math.Ceiling((decimal)dCount / 8); i++) { - var buff = b[pos++]; + byte buff = b[pos++]; dData.Add(buff); } - foreach (var by in dData) + foreach (byte by in dData) { for (int i = 7; i >= 0; i--) { if (by.Bit(i)) { - foreach (var pu in s1) + foreach (ushort pu in s1) { t.DataPeriods.Add(pu); bLevel = !bLevel; @@ -289,7 +289,7 @@ 8 u16[p0] s0 sequence of pulse durations encoding bit equa } else { - foreach (var pu in s0) + foreach (ushort pu in s0) { t.DataPeriods.Add(pu); bLevel = !bLevel; @@ -334,7 +334,7 @@ 0 u32 duration bits 0-30 duration of the pause int iniPulseLevel = 1; int pCount = 0; - var d = GetInt32(b, pos); + int d = GetInt32(b, pos); iniPulseLevel = ((d & 0x80000000) == 0 ? 0 : 1); t.InitialPulseLevel = iniPulseLevel == 1; bool paLevel = !t.InitialPulseLevel; @@ -390,7 +390,7 @@ 0 u16 flags when exactly to stop the tape (1 48k only, other always). t.BlockID = GetInt32(b, 0); t.DataPeriods = new List(); - var flags = GetWordValue(b, pos); + ushort flags = GetWordValue(b, pos); if (flags == 1) { t.BlockDescription = BlockType.Stop_the_Tape_48K; diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/TAP/TapConverter.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/TAP/TapConverter.cs index 1abb0e77ee6..62406170cf7 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/TAP/TapConverter.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/TAP/TapConverter.cs @@ -116,7 +116,7 @@ first two bytes of rom .................................^^^^^ _datacorder.DataBlocks.Clear(); // convert bytearray to memory stream - MemoryStream stream = new MemoryStream(data); + MemoryStream stream = new(data); // the first 2 bytes of the TAP file designate the length of the first data block // this (I think) should always be 17 bytes (as this is the tape header) @@ -139,7 +139,7 @@ first two bytes of rom .................................^^^^^ stream.Read(blockdata, 0, blockSize); // create and populate a new tapedatablock object - TapeDataBlock tdb = new TapeDataBlock(); + TapeDataBlock tdb = new(); // ascertain the block description string description = string.Empty; @@ -176,10 +176,10 @@ A SCREEN$ file is regarded as a Code file with start address 16384 and length 69 { string fileName = Encoding.ASCII.GetString(blockdata.Skip(2).Take(10).ToArray()).Trim(); string type = "Unknown Type"; - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); - var param1 = GetWordValue(blockdata, 12); - var param2 = GetWordValue(blockdata, 14); + ushort param1 = GetWordValue(blockdata, 12); + ushort param2 = GetWordValue(blockdata, 14); // header block - examine first byte of header if (blockdata[1] == 0) @@ -216,7 +216,7 @@ A SCREEN$ file is regarded as a Code file with start address 16384 and length 69 else { // some other type (turbo data etc..) - description = $"#{blockdata[0].ToString("X2")} block, {blockSize} bytes"; + description = $"#{blockdata[0]:X2} block, {blockSize} bytes"; //description += (crc != 0) ? $", crc bad (#{crcFile:X2}!=#{crcValue:X2})" : ", crc ok"; tdb.AddMetaData(BlockDescriptorTitle.Undefined, description); } @@ -279,8 +279,8 @@ A SCREEN$ file is regarded as a Code file with start address 16384 and length 69 } // create a list to hold the data periods - List dataPeriods = new List(); - List dataLevels = new List(); + List dataPeriods = new(); + List dataLevels = new(); bool currLevel = false; diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/TZX/TzxConverter.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/TZX/TzxConverter.cs index 9da1fd9a242..37c77007f3b 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/TZX/TzxConverter.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/TZX/TzxConverter.cs @@ -42,7 +42,7 @@ protected override string SelfTypeName /// /// Object to keep track of loops - this assumes there is only one loop at a time /// - private readonly List> _loopCounter = new List>(); + private readonly List> _loopCounter = new(); /// /// The virtual cassette deck @@ -249,10 +249,7 @@ 0x09 20 BYTE TZX minor revision number /// /// Inverts the audio signal /// - private void ToggleSignal() - { - signal = !signal; - } + private void ToggleSignal() => signal = !signal; /// /// Processes a TZX block @@ -442,10 +439,10 @@ This block must be replayed with the standard Spectrum ROM timing values - see t { string fileName = Encoding.ASCII.GetString(blockdata.Skip(2).Take(10).ToArray()).Trim(); string type = "Unknown Type"; - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); - var param1 = GetWordValue(blockdata, 12); - var param2 = GetWordValue(blockdata, 14); + ushort param1 = GetWordValue(blockdata, 12); + ushort param2 = GetWordValue(blockdata, 14); // header block - examine first byte of header if (blockdata[1] == 0) @@ -482,7 +479,7 @@ This block must be replayed with the standard Spectrum ROM timing values - see t else { // some other type (turbo data etc..) - description = $"#{blockdata[0].ToString("X2")} block, {blockLen} bytes"; + description = $"#{blockdata[0]:X2} block, {blockLen} bytes"; //description += (crc != 0) ? $", crc bad (#{crcFile:X2}!=#{crcValue:X2})" : ", crc ok"; t.AddMetaData(BlockDescriptorTitle.Undefined, description); } @@ -566,10 +563,10 @@ sync or pilot tones (i.e. all sorts of protection schemes) then use the next thr { string fileName = Encoding.ASCII.GetString(blockdata.Skip(2).Take(10).ToArray()).Trim(); string type = "Unknown Type"; - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); - var param1 = GetWordValue(blockdata, 12); - var param2 = GetWordValue(blockdata, 14); + ushort param1 = GetWordValue(blockdata, 12); + ushort param2 = GetWordValue(blockdata, 14); // header block - examine first byte of header if (blockdata[1] == 0) @@ -606,7 +603,7 @@ sync or pilot tones (i.e. all sorts of protection schemes) then use the next thr else { // some other type (turbo data etc..) - description = $"#{blockdata[0].ToString("X2")} block, {blockLen} bytes"; + description = $"#{blockdata[0]:X2} block, {blockLen} bytes"; //description += (crc != 0) ? $", crc bad (#{crcFile:X2}!=#{crcValue:X2})" : ", crc ok"; t.AddMetaData(BlockDescriptorTitle.Undefined, description); } @@ -823,7 +820,7 @@ The preferred sampling frequencies are 22050 or 44100 Hz (158 or 79 T-states/sam Please, if you can, don't use other sampling frequencies. Please use this block only if you cannot use any other block. */ - TapeDataBlock t = new TapeDataBlock + TapeDataBlock t = new() { BlockID = 0x15, BlockDescription = BlockType.Direct_Recording @@ -859,7 +856,7 @@ The preferred sampling frequencies are 22050 or 44100 Hz (158 or 79 T-states/sam } // get the byte to be processed - var currByte = data[_position++]; + byte currByte = data[_position++]; // do the bits while (bitCount > 0) @@ -946,7 +943,7 @@ This block contains a sequence of raw pulses encoded in CSW format v2 (Compresse CswConverter.ProcessCSWV2(src, ref dest, compType, pulses); // create the periods - var rate = (69888 * 50) / sampleRate; + int rate = (69888 * 50) / sampleRate; for (int i = 0; i < dest.Length;) { @@ -987,10 +984,12 @@ Offset Value Type Description This will make a silence (low amplitude level (0)) for a given time in milliseconds. If the value is 0 then the emulator or utility should (in effect) STOP THE TAPE, i.e. should not continue loading until the user or emulator requests it. */ - t = new TapeDataBlock(); - t.BlockID = 0x20; - t.DataPeriods = new List(); - t.BlockDescription = BlockType.Pause_or_Stop_the_Tape; + t = new TapeDataBlock + { + BlockID = 0x20, + DataPeriods = new List(), + BlockDescription = BlockType.Pause_or_Stop_the_Tape + }; pauseLen = GetWordValue(data, _position); @@ -1033,10 +1032,12 @@ This block marks the start of a group of blocks which are to be treated as one s You can also give the group a name (example 'Bleepload Block 1'). For each group start block, there must be a group end block. Nesting of groups is not allowed. */ - t = new TapeDataBlock(); - t.BlockID = 0x21; - t.DataPeriods = new List(); - t.BlockDescription = BlockType.Group_Start; + t = new TapeDataBlock + { + BlockID = 0x21, + DataPeriods = new List(), + BlockDescription = BlockType.Group_Start + }; int nameLength = data[_position]; _position++; @@ -1067,14 +1068,16 @@ private void ProcessBlockID22() This indicates the end of a group. This block has no body. */ - t = new TapeDataBlock(); - t.BlockID = 0x22; - t.DataPeriods = new List(); - t.BlockDescription = BlockType.Group_End; - t.Command = TapeCommand.END_GROUP; + t = new TapeDataBlock + { + BlockID = 0x22, + DataPeriods = new List(), + BlockDescription = BlockType.Group_End, + Command = TapeCommand.END_GROUP, - t.PauseInMS = 0; - t.PauseInTStates = 0; + PauseInMS = 0, + PauseInTStates = 0 + }; // add to tape _datacorder.DataBlocks.Add(t); @@ -1097,9 +1100,11 @@ Offset Value Type Description be repeated. This block is the same as the FOR statement in BASIC. For simplicity reasons don't nest loop blocks! */ - t = new TapeDataBlock(); - t.BlockID = 0x24; - t.BlockDescription = BlockType.Loop_Start; + t = new TapeDataBlock + { + BlockID = 0x24, + BlockDescription = BlockType.Loop_Start + }; // loop should start from the next block int loopStart = _datacorder.DataBlocks.Count + 1; @@ -1139,10 +1144,12 @@ private void ProcessBlockID25() been run for the specified number of times. This block has no body. */ - t = new TapeDataBlock(); - t.BlockID = 0x25; - t.DataPeriods = new List(); - t.BlockDescription = BlockType.Loop_End; + t = new TapeDataBlock + { + BlockID = 0x25, + DataPeriods = new List(), + BlockDescription = BlockType.Loop_End + }; // get the most recent loop info var loop = _loopCounter.LastOrDefault(); @@ -1161,9 +1168,11 @@ This block has no body. */ // loop through each group to repeat for (int b = 0; b < numberOfRepetitions; b++) { - TapeDataBlock repeater = new TapeDataBlock(); - //repeater.BlockDescription = "[LOOP REPEAT - " + (b + 1) + "]"; - repeater.DataPeriods = new List(); + TapeDataBlock repeater = new() + { + //repeater.BlockDescription = "[LOOP REPEAT - " + (b + 1) + "]"; + DataPeriods = new List() + }; // add the repeat block _datacorder.DataBlocks.Add(repeater); @@ -1194,11 +1203,13 @@ 0x00 0 DWORD Length of the block without these four bytes (0) multiloading games that load one level at a time in 48K mode, but load the entire tape at once if in 128K mode. This block has no body of its own, but follows the extension rule. */ - t = new TapeDataBlock(); - t.BlockID = 0x2A; - t.DataPeriods = new List(); - t.BlockDescription = BlockType.Stop_the_Tape_48K; - t.Command = TapeCommand.STOP_THE_TAPE_48K; + t = new TapeDataBlock + { + BlockID = 0x2A, + DataPeriods = new List(), + BlockDescription = BlockType.Stop_the_Tape_48K, + Command = TapeCommand.STOP_THE_TAPE_48K + }; int blockSize = 4 + GetWordValue(data, _position); @@ -1229,13 +1240,15 @@ 0x00 1 DWORD Block length (without these four bytes) This block sets the current signal level to the specified value (high or low). It should be used whenever it is necessary to avoid any ambiguities, e.g. with custom loaders which are level-sensitive. */ - t = new TapeDataBlock(); - t.BlockID = 0x2B; - t.DataPeriods = new List(); - t.BlockDescription = BlockType.Set_Signal_Level; + t = new TapeDataBlock + { + BlockID = 0x2B, + DataPeriods = new List(), + BlockDescription = BlockType.Set_Signal_Level, - t.PauseInMS = 0; - t.PauseInTStates = 0; + PauseInMS = 0, + PauseInTStates = 0 + }; // we already flip the signal *before* adding to the buffer elsewhere // so set the opposite level specified in this block @@ -1273,10 +1286,12 @@ The description can be up to 255 characters long but please keep it down to abou (where this is appropriate). Please use 'Archive Info' block for title, authors, publisher, etc. */ - t = new TapeDataBlock(); - t.BlockID = 0x30; - t.DataPeriods = new List(); - t.BlockDescription = BlockType.Text_Description; + t = new TapeDataBlock + { + BlockID = 0x30, + DataPeriods = new List(), + BlockDescription = BlockType.Text_Description + }; int textLen = data[_position]; _position++; @@ -1336,9 +1351,11 @@ The block consists of a series of text strings. Each text has its identification If all texts on the tape are in English language then you don't have to supply the 'Language' field The information about what hardware the tape uses is in the 'Hardware Type' block, so no need for it here. */ - t = new TapeDataBlock(); - t.BlockID = 0x32; - t.BlockDescription = BlockType.Archive_Info; + t = new TapeDataBlock + { + BlockID = 0x32, + BlockDescription = BlockType.Archive_Info + }; blockLen = GetWordValue(data, _position); _position += 2; @@ -1425,12 +1442,14 @@ 0x10 L DWORD Length of the custom info This block can be used to save any information you want. For example, it might contain some information written by a utility, extra settings required by a particular emulator, or even poke data. */ - t = new TapeDataBlock(); - t.BlockID = 0x35; - t.BlockDescription = BlockType.Custom_Info_Block; + t = new TapeDataBlock + { + BlockID = 0x35, + BlockDescription = BlockType.Custom_Info_Block, - t.PauseInMS = 0; - t.PauseInTStates = 0; + PauseInMS = 0, + PauseInTStates = 0 + }; string info = Encoding.ASCII.GetString(data, _position, 0x10); t.AddMetaData(BlockDescriptorTitle.Custom_Info, info); @@ -1464,14 +1483,16 @@ This block is generated when you merge two ZX Tape files together. It is here so them. Of course, this means that resulting file would be 10 bytes longer than if this block was not used. All you have to do if you encounter this block ID is to skip next 9 bytes. If you can avoid using this block for this purpose, then do so; it is preferable to use a utility to join the two files and - ensure that they are both of the higher version number. */ + ensure that they are both of the higher version number. */ - t = new TapeDataBlock(); - t.BlockID = 0x5A; - t.DataPeriods = new List(); - t.BlockDescription = BlockType.Glue_Block; + t = new TapeDataBlock + { + BlockID = 0x5A, + DataPeriods = new List(), + BlockDescription = BlockType.Glue_Block, - t.PauseInMS = 0; + PauseInMS = 0 + }; // add to tape _datacorder.DataBlocks.Add(t); @@ -1488,10 +1509,12 @@ ensure that they are both of the higher version number. */ /// private void ProcessUnidentifiedBlock() { - TapeDataBlock t = new TapeDataBlock(); - t.BlockID = -2; - t.DataPeriods = new List(); - t.BlockDescription = BlockType.Unsupported; + TapeDataBlock t = new() + { + BlockID = -2, + DataPeriods = new List(), + BlockDescription = BlockType.Unsupported + }; //t.BlockDescription = "[UNSUPPORTED - 0x" + data[_position - 1] + "]"; _position += GetInt32(data, _position) & 0xFFFFFF; @@ -1541,13 +1564,15 @@ need to list this information. // currently not implemented properly in ZXHawk - t = new TapeDataBlock(); - t.BlockID = 0x33; - t.DataPeriods = new List(); - t.BlockDescription = BlockType.Hardware_Type; + t = new TapeDataBlock + { + BlockID = 0x33, + DataPeriods = new List(), + BlockDescription = BlockType.Hardware_Type, - t.PauseInMS = 0; - t.PauseInTStates = 0; + PauseInMS = 0, + PauseInTStates = 0 + }; // first byte contains number of HWINFOs int infos = data[_position]; @@ -1589,10 +1614,12 @@ stick to a maximum of 8 lines. // currently not implemented properly in ZXHawk - t = new TapeDataBlock(); - t.BlockID = 0x31; - t.DataPeriods = new List(); - t.BlockDescription = BlockType.Message_Block; + t = new TapeDataBlock + { + BlockID = 0x31, + DataPeriods = new List(), + BlockDescription = BlockType.Message_Block + }; _position++; @@ -1633,10 +1660,12 @@ then goes back to the next block. Because more than one call can be normally use file without disturbing the call values. Please take a look at 'Jump To Block' for reference on the values. */ // block processing not implemented for this - just gets added for informational purposes only - t = new TapeDataBlock(); - t.BlockID = 0x26; - t.DataPeriods = new List(); - t.BlockDescription = BlockType.Call_Sequence; + t = new TapeDataBlock + { + BlockID = 0x26, + DataPeriods = new List(), + BlockDescription = BlockType.Call_Sequence + }; int blockSize = 2 + 2 * GetWordValue(data, _position); @@ -1665,11 +1694,13 @@ This block indicates the end of the Called Sequence. The next block played will Again, this block has no body. */ // block processing not implemented for this - just gets added for informational purposes only - t = new TapeDataBlock(); - t.BlockID = 0x27; - t.BlockDescription = BlockType.Return_From_Sequence; - t.PauseInMS = 0; - t.PauseInTStates = 0; + t = new TapeDataBlock + { + BlockID = 0x27, + BlockDescription = BlockType.Return_From_Sequence, + PauseInMS = 0, + PauseInTStates = 0 + }; // add to tape _datacorder.DataBlocks.Add(t); @@ -1704,10 +1735,12 @@ one of the parts and the utility/emulator will start loading from that block. Fo selections when it encounters such a block. All offsets are relative signed words. */ // block processing not implemented for this - just gets added for informational purposes only - t = new TapeDataBlock(); - t.BlockID = 0x28; - t.DataPeriods = new List(); - t.BlockDescription = BlockType.Select_Block; + t = new TapeDataBlock + { + BlockID = 0x28, + DataPeriods = new List(), + BlockDescription = BlockType.Select_Block + }; int blockSize = 2 + GetWordValue(data, _position); @@ -1745,10 +1778,12 @@ All blocks are included in the block count!. */ // not implemented properly - t = new TapeDataBlock(); - t.BlockID = 0x23; - t.DataPeriods = new List(); - t.BlockDescription = BlockType.Jump_to_Block; + t = new TapeDataBlock + { + BlockID = 0x23, + DataPeriods = new List(), + BlockDescription = BlockType.Jump_to_Block + }; int relativeJumpValue = GetWordValue(data, _position); string result = string.Empty; @@ -1852,10 +1887,12 @@ the symbol and the number of times it must be repeated. // not currently implemented properly - TapeDataBlock t = new TapeDataBlock(); - t.BlockID = 0x19; - t.BlockDescription = BlockType.Generalized_Data_Block; - t.DataPeriods = new List(); + TapeDataBlock t = new() + { + BlockID = 0x19, + BlockDescription = BlockType.Generalized_Data_Block, + DataPeriods = new List() + }; int blockLen = GetInt32(data, _position); _position += 4; @@ -1893,12 +1930,14 @@ the symbol and the number of times it must be repeated. private void ProcessBlockID16() { // zxhawk will not implement this block. it will however handle it so subsequent blocks can be parsed - TapeDataBlock t = new TapeDataBlock(); - t.BlockID = 0x16; - t.DataPeriods = new List(); - t.BlockDescription = BlockType.C64_ROM_Type_Data_Block; + TapeDataBlock t = new() + { + BlockID = 0x16, + DataPeriods = new List(), + BlockDescription = BlockType.C64_ROM_Type_Data_Block, - t.PauseInMS = 0; + PauseInMS = 0 + }; // add to tape _datacorder.DataBlocks.Add(t); @@ -1911,12 +1950,14 @@ private void ProcessBlockID16() private void ProcessBlockID17() { // zxhawk will not implement this block. it will however handle it so subsequent blocks can be parsed - TapeDataBlock t = new TapeDataBlock(); - t.BlockID = 0x17; - t.DataPeriods = new List(); - t.BlockDescription = BlockType.C64_Turbo_Tape_Data_Block; + TapeDataBlock t = new() + { + BlockID = 0x17, + DataPeriods = new List(), + BlockDescription = BlockType.C64_Turbo_Tape_Data_Block, - t.PauseInMS = 0; + PauseInMS = 0 + }; // add to tape _datacorder.DataBlocks.Add(t); @@ -1930,10 +1971,12 @@ private void ProcessBlockID34() { // currently not implemented properly in ZXHawk - TapeDataBlock t = new TapeDataBlock(); - t.BlockID = 0x34; - t.DataPeriods = new List(); - t.BlockDescription = BlockType.Emulation_Info; + TapeDataBlock t = new() + { + BlockID = 0x34, + DataPeriods = new List(), + BlockDescription = BlockType.Emulation_Info + }; // add to tape _datacorder.DataBlocks.Add(t); @@ -1958,10 +2001,12 @@ private void ProcessBlockID40() { // currently not implemented properly in ZXHawk - TapeDataBlock t = new TapeDataBlock(); - t.BlockID = 0x40; - t.DataPeriods = new List(); - t.BlockDescription = BlockType.Snapshot_Block; + TapeDataBlock t = new() + { + BlockID = 0x40, + DataPeriods = new List(), + BlockDescription = BlockType.Snapshot_Block + }; _position++; @@ -2044,7 +2089,7 @@ private void DecodeData() } // get the byte to be processed - var currByte = data[_position]; + byte currByte = data[_position]; // do the bits int currBitLength = 0; diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/TapeDataBlock.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/TapeDataBlock.cs index 293732f6c38..c9db7c2061b 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/TapeDataBlock.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/TapeDataBlock.cs @@ -68,14 +68,14 @@ public void AddMetaData(BlockDescriptorTitle descriptor, string data) /// /// List containing the pulse timing values /// - public List DataPeriods = new List(); + public List DataPeriods = new(); /// /// List containing the pulse levels (in relation to the pulse timing values) /// - public List DataLevels = new List(); + public List DataLevels = new(); - public List PulseDescription = new List(); + public List PulseDescription = new(); public bool InitialPulseLevel; @@ -89,44 +89,20 @@ public TapeCommand Command get => _command; set => _command = value; } - - /// - /// The defined post-block pause in MS - /// - private int _pauseInMS; - public int PauseInMS - { - get => _pauseInMS; - set => _pauseInMS = value; - } - - /// - /// The defined post-block pause in T-States - /// - private int _pauseInTStates; - public int PauseInTStates - { - get { return _pauseInTStates; } - set { _pauseInTStates = value; } - } + public int PauseInMS { get; set; } + public int PauseInTStates { get; set; } /// /// Returns the data periods as an array /// (primarily to aid in bizhawk state serialization) /// - public int[] GetDataPeriodsArray() - { - return DataPeriods.ToArray(); - } + public int[] GetDataPeriodsArray() => DataPeriods.ToArray(); /// /// Accepts an array of data periods and updates the DataPeriods list accordingly /// (primarily to aid in bizhawk state serialization) /// - public void SetDataPeriodsArray(int[] periodArray) - { - DataPeriods = periodArray?.ToList() ?? new List(); - } + public void SetDataPeriodsArray(int[] periodArray) => DataPeriods = periodArray?.ToList() ?? new List(); /// /// Bizhawk state serialization diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/WAV/StreamHelper.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/WAV/StreamHelper.cs index 1c1669e3d91..2d98b3acf98 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/WAV/StreamHelper.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/WAV/StreamHelper.cs @@ -46,10 +46,7 @@ public static void Write(Stream stream, sbyte value) stream.Write(data, 0, data.Length); } - public static void Write(Stream stream, byte[] value) - { - stream.Write(value, 0, value.Length); - } + public static void Write(Stream stream, byte[] value) => stream.Write(value, 0, value.Length); public static void Read(Stream stream, out int value) @@ -96,9 +93,6 @@ public static void Read(Stream stream, out sbyte value) value = (sbyte)data[0]; } - public static void Read(Stream stream, byte[] value) - { - stream.Read(value, 0, value.Length); - } + public static void Read(Stream stream, byte[] value) => stream.Read(value, 0, value.Length); } } diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/WAV/WavConverter.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/WAV/WavConverter.cs index cf498216cb5..7a5d02670bc 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/WAV/WavConverter.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/WAV/WavConverter.cs @@ -81,11 +81,11 @@ public override void Read(byte[] data) //_position = 0; - MemoryStream stream = new MemoryStream(); + MemoryStream stream = new(); stream.Write(data, 0, data.Length); stream.Position = 0; - WavStreamReader reader = new WavStreamReader(stream); + WavStreamReader reader = new(stream); const double d = /*69888.0*/70000.0 * 50.0; int rate = (int) (d / reader.Header.sampleRate); @@ -93,11 +93,13 @@ public override void Read(byte[] data) int state = reader.ReadNext(); // create the single tape block - TapeDataBlock t = new TapeDataBlock(); - t.BlockDescription = BlockType.WAV_Recording; - t.BlockID = 0; - t.DataPeriods = new List(); - t.DataLevels = new List(); + TapeDataBlock t = new() + { + BlockDescription = BlockType.WAV_Recording, + BlockID = 0, + DataPeriods = new List(), + DataLevels = new List() + }; bool currLevel = false; diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/WAV/WavStreamReader.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/WAV/WavStreamReader.cs index 2565bafdd94..d44676bc178 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/WAV/WavStreamReader.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/Media/Tape/WAV/WavStreamReader.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; namespace BizHawk.Emulation.Cores.Computers.SinclairSpectrum @@ -9,60 +9,53 @@ namespace BizHawk.Emulation.Cores.Computers.SinclairSpectrum public class WavStreamReader { private readonly Stream m_stream; - private readonly WavHeader m_header = new WavHeader(); public WavStreamReader(Stream stream) { m_stream = stream; - m_header.Deserialize(stream); + Header.Deserialize(stream); } - public WavHeader Header => m_header; + public WavHeader Header { get; } = new(); - public int Count => m_header.dataSize / m_header.fmtBlockAlign; + public int Count => Header.dataSize / Header.fmtBlockAlign; public int ReadNext() { // check - sample should be in PCM format - if (m_header.fmtCode != WAVE_FORMAT_PCM && - m_header.fmtCode != WAVE_FORMAT_IEEE_FLOAT) + if (Header.fmtCode is not WAVE_FORMAT_PCM and + not WAVE_FORMAT_IEEE_FLOAT) { - throw new FormatException($"Not supported audio format: fmtCode={m_header.fmtCode}, bitDepth={m_header.bitDepth}"); + throw new FormatException($"Not supported audio format: fmtCode={Header.fmtCode}, bitDepth={Header.bitDepth}"); } - byte[] data = new byte[m_header.fmtBlockAlign]; + byte[] data = new byte[Header.fmtBlockAlign]; m_stream.Read(data, 0, data.Length); - if (m_header.fmtCode == WAVE_FORMAT_PCM) + if (Header.fmtCode == WAVE_FORMAT_PCM) { // use first channel only - if (m_header.bitDepth == 8) + if (Header.bitDepth == 8) return getSamplePcm8(data, 0, 0); - if (m_header.bitDepth == 16) + if (Header.bitDepth == 16) return getSamplePcm16(data, 0, 0); - if (m_header.bitDepth == 24) + if (Header.bitDepth == 24) return getSamplePcm24(data, 0, 0); - if (m_header.bitDepth == 32) + if (Header.bitDepth == 32) return getSamplePcm32(data, 0, 0); } - else if (m_header.fmtCode == WAVE_FORMAT_IEEE_FLOAT) + else if (Header.fmtCode == WAVE_FORMAT_IEEE_FLOAT) { // use first channel only - if (m_header.bitDepth == 32) + if (Header.bitDepth == 32) return getSampleFloat32(data, 0, 0); - if (m_header.bitDepth == 64) + if (Header.bitDepth == 64) return getSampleFloat64(data, 0, 0); } - throw new NotSupportedException($"Not supported audio format ({(m_header.fmtCode == WAVE_FORMAT_PCM ? "PCM" : "FLOAT")}/{m_header.bitDepth} bit)"); + throw new NotSupportedException($"Not supported audio format ({(Header.fmtCode == WAVE_FORMAT_PCM ? "PCM" : "FLOAT")}/{Header.bitDepth} bit)"); } - private int getSamplePcm8(byte[] bufferRaw, int offset, int channel) - { - return bufferRaw[offset + channel] - 128; - } + private int getSamplePcm8(byte[] bufferRaw, int offset, int channel) => bufferRaw[offset + channel] - 128; - private int getSamplePcm16(byte[] bufferRaw, int offset, int channel) - { - return BitConverter.ToInt16(bufferRaw, offset + 2 * channel); - } + private int getSamplePcm16(byte[] bufferRaw, int offset, int channel) => BitConverter.ToInt16(bufferRaw, offset + 2 * channel); private int getSamplePcm24(byte[] bufferRaw, int offset, int channel) { @@ -83,10 +76,7 @@ private int getSamplePcm24(byte[] bufferRaw, int offset, int channel) return result; } - private int getSamplePcm32(byte[] bufferRaw, int offset, int channel) - { - return BitConverter.ToInt32(bufferRaw, offset + 4 * channel); - } + private int getSamplePcm32(byte[] bufferRaw, int offset, int channel) => BitConverter.ToInt32(bufferRaw, offset + 4 * channel); private int getSampleFloat32(byte[] data, int offset, int channel) { @@ -102,10 +92,12 @@ private int getSampleFloat64(byte[] data, int offset, int channel) return (int) (fSample * int.MaxValue); } + #pragma warning disable IDE0051 private const int WAVE_FORMAT_PCM = 1; /* PCM */ private const int WAVE_FORMAT_IEEE_FLOAT = 3; /* IEEE float */ private const int WAVE_FORMAT_ALAW = 6; /* 8-bit ITU-T G.711 A-law */ private const int WAVE_FORMAT_MULAW = 7; /* 8-bit ITU-T G.711 µ-law */ private const int WAVE_FORMAT_EXTENSIBLE = 0xFFFE; /* Determined by SubFormat */ + #pragma warning restore IDE0051 } } diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.Controllers.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.Controllers.cs index a9453c2c2bc..815cb05349c 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.Controllers.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.Controllers.cs @@ -19,44 +19,44 @@ public ControllerDefinition ZXSpectrumControllerDefinition ControllerDefinition definition = new("ZXSpectrum Controller"); // joysticks - var joys1 = new List + List joys1 = new() { // P1 Joystick "P1 Up", "P1 Down", "P1 Left", "P1 Right", "P1 Button", }; - foreach (var s in joys1) + foreach (string s in joys1) { definition.BoolButtons.Add(s); definition.CategoryLabels[s] = "J1 (" + SyncSettings.JoystickType1 + ")"; } - var joys2 = new List + List joys2 = new() { // P2 Joystick "P2 Up", "P2 Down", "P2 Left", "P2 Right", "P2 Button", }; - foreach (var s in joys2) + foreach (string s in joys2) { definition.BoolButtons.Add(s); definition.CategoryLabels[s] = "J2 (" + SyncSettings.JoystickType2 + ")"; } - var joys3 = new List + List joys3 = new() { // P3 Joystick "P3 Up", "P3 Down", "P3 Left", "P3 Right", "P3 Button", }; - foreach (var s in joys3) + foreach (string s in joys3) { definition.BoolButtons.Add(s); definition.CategoryLabels[s] = "J3 (" + SyncSettings.JoystickType3 + ")"; } // keyboard - var keys = new List + List keys = new() { // Controller mapping includes all keyboard keys from the following models: // https://upload.wikimedia.org/wikipedia/commons/thumb/3/33/ZXSpectrum48k.jpg/1200px-ZXSpectrum48k.jpg @@ -74,47 +74,47 @@ public ControllerDefinition ZXSpectrumControllerDefinition "Key Symbol Shift", "Key Semi-Colon", "Key Quote", "Key Left Cursor", "Key Right Cursor", "Key Space", "Key Up Cursor", "Key Down Cursor", "Key Comma", }; - foreach (var s in keys) + foreach (string s in keys) { definition.BoolButtons.Add(s); definition.CategoryLabels[s] = "Keyboard"; } // Power functions - var power = new List + List power = new() { // Power functions "Reset", "Power" }; - foreach (var s in power) + foreach (string s in power) { definition.BoolButtons.Add(s); definition.CategoryLabels[s] = "Power"; } // Datacorder (tape device) - var tape = new List + List tape = new() { // Tape functions "Play Tape", "Stop Tape", "RTZ Tape", "Record Tape", "Insert Next Tape", "Insert Previous Tape", "Next Tape Block", "Prev Tape Block", "Get Tape Status" }; - foreach (var s in tape) + foreach (string s in tape) { definition.BoolButtons.Add(s); definition.CategoryLabels[s] = "Datacorder"; } // Datacorder (tape device) - var disk = new List + List disk = new() { // Tape functions "Insert Next Disk", "Insert Previous Disk", /*"Eject Current Disk",*/ "Get Disk Status" }; - foreach (var s in disk) + foreach (string s in disk) { definition.BoolButtons.Add(s); definition.CategoryLabels[s] = "+3 Disk Drive"; diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.ICodeDataLog.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.ICodeDataLog.cs index cef7ea749ce..37fbfe4a210 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.ICodeDataLog.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.ICodeDataLog.cs @@ -42,7 +42,7 @@ void AddIfExists(string name) AddIfExists("ROM - 48K BASIC"); // different RAM bank ordering for < 128k models - if (_machineType == MachineType.ZXSpectrum16 || _machineType == MachineType.ZXSpectrum48) + if (_machineType is MachineType.ZXSpectrum16 or MachineType.ZXSpectrum48) { AddIfExists("RAM - BANK 0 (Screen)"); AddIfExists("RAM - BANK 1"); @@ -86,7 +86,7 @@ private byte ReadMemory_CDL(ushort addr) { var mapping = _machine.ReadCDL(addr); var res = mapping.Type; - var address = mapping.Address; + int address = mapping.Address; byte data = _machine.ReadMemory(addr); diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.IEmulator.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.IEmulator.cs index c06b3c0d555..4e6d2e577af 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.IEmulator.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.IEmulator.cs @@ -59,9 +59,6 @@ public void ResetCounters() _isLag = false; } - public void Dispose() - { - _machine = null; - } + public void Dispose() => _machine = null; } } diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.IMemoryDomains.cs index a76ae31d0e6..91ffa343c3c 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.IMemoryDomains.cs @@ -12,12 +12,12 @@ namespace BizHawk.Emulation.Cores.Computers.SinclairSpectrum public partial class ZXSpectrum { internal IMemoryDomains memoryDomains; - private readonly Dictionary _byteArrayDomains = new Dictionary(); + private readonly Dictionary _byteArrayDomains = new(); private bool _memoryDomainsInit = false; private void SetupMemoryDomains() { - var domains = new List + List domains = new() { new MemoryDomainDelegate("System Bus", 0x10000, MemoryDomain.Endian.Little, (addr) => @@ -97,7 +97,7 @@ private void SyncByteArrayDomain(string name, byte[] data) } else { - var m = new MemoryDomainByteArray(name, MemoryDomain.Endian.Little, data, true, 1); + MemoryDomainByteArray m = new(name, MemoryDomain.Endian.Little, data, true, 1); _byteArrayDomains.Add(name, m); } #pragma warning restore MEN014 diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.ISettable.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.ISettable.cs index 9abfb46c295..90cafea6ce7 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.ISettable.cs @@ -13,8 +13,8 @@ namespace BizHawk.Emulation.Cores.Computers.SinclairSpectrum /// public partial class ZXSpectrum : ISettable { - internal ZXSpectrumSettings Settings = new ZXSpectrumSettings(); - internal ZXSpectrumSyncSettings SyncSettings = new ZXSpectrumSyncSettings(); + internal ZXSpectrumSettings Settings = new(); + internal ZXSpectrumSyncSettings SyncSettings = new(); public ZXSpectrumSettings GetSettings() => Settings.Clone(); @@ -86,10 +86,7 @@ public class ZXSpectrumSettings [DefaultValue(false)] public bool UseCoreBorderForBackground { get; set; } - public ZXSpectrumSettings Clone() - { - return (ZXSpectrumSettings)MemberwiseClone(); - } + public ZXSpectrumSettings Clone() => (ZXSpectrumSettings)MemberwiseClone(); public ZXSpectrumSettings() { @@ -140,20 +137,14 @@ public class ZXSpectrumSyncSettings public bool AutoLoadTape { get; set; } - public ZXSpectrumSyncSettings Clone() - { - return (ZXSpectrumSyncSettings)MemberwiseClone(); - } + public ZXSpectrumSyncSettings Clone() => (ZXSpectrumSyncSettings)MemberwiseClone(); public ZXSpectrumSyncSettings() { SettingsUtil.SetDefaultValues(this); } - public static bool NeedsReboot(ZXSpectrumSyncSettings x, ZXSpectrumSyncSettings y) - { - return !DeepEquality.DeepEquals(x, y); - } + public static bool NeedsReboot(ZXSpectrumSyncSettings x, ZXSpectrumSyncSettings y) => !DeepEquality.DeepEquals(x, y); } /// @@ -234,14 +225,14 @@ public class ZXMachineMetaData public string Media { get; set; } public string OtherMisc { get; set; } - private readonly Dictionary Data = new Dictionary(); + private readonly Dictionary Data = new(); /// /// Detailed info to be displayed within the settings UIs /// public static ZXMachineMetaData GetMetaObject(MachineType type) { - ZXMachineMetaData m = new ZXMachineMetaData { MachineType = type }; + ZXMachineMetaData m = new() { MachineType = type }; switch (type) { @@ -348,7 +339,7 @@ public static string GetMetaString(MachineType type) { var m = GetMetaObject(type); - var sb = new StringBuilder(); + StringBuilder sb = new(); // get longest title int titleLen = 0; @@ -358,13 +349,13 @@ public static string GetMetaString(MachineType type) titleLen = d.Key.Length; } - var maxDataLineLen = 40; + int maxDataLineLen = 40; // generate layout foreach (var d in m.Data) { - var tLen = d.Key.Length; - var makeup = (titleLen - tLen) / 4; + int tLen = d.Key.Length; + int makeup = (titleLen - tLen) / 4; sb.Append(d.Key + ":\t"); for (int i = 0; i < makeup; i++) { @@ -378,14 +369,14 @@ public static string GetMetaString(MachineType type) } // output the data splitting and tabbing as necessary - var arr = d.Value.Split(' '); + string[] arr = d.Value.Split(' '); //int cnt = 0; - var builder = new List(); + List builder = new(); string working = ""; - foreach (var s in arr) + foreach (string s in arr) { - var len = s.Length; + int len = s.Length; if (working.Length + 1 + len > maxDataLineLen) { // new line needed diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.IStatable.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.IStatable.cs index 65bf11630cc..3689ffb4a23 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.IStatable.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.IStatable.cs @@ -14,7 +14,7 @@ private void SyncState(Serializer ser) byte[] core = null; if (ser.IsWriter) { - var ms = new MemoryStream(); + MemoryStream ms = new(); ms.Close(); core = ms.ToArray(); } diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.Messaging.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.Messaging.cs index cc560ad1843..1bfa9aee0bc 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.Messaging.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.Messaging.cs @@ -18,7 +18,7 @@ public void SendMessage(string message, MessageCategory category) if (!CheckMessageSettings(category)) return; - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); switch (category) { @@ -49,7 +49,7 @@ public void SendMessage(string message, MessageCategory category) /// public void OSD_FireInputMessage(string input) { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); sb.Append(input); SendMessage(sb.ToString().TrimEnd('\n'), MessageCategory.Input); } @@ -59,7 +59,7 @@ public void OSD_FireInputMessage(string input) /// public void OSD_DiskInit() { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); if (_machine.diskImages != null && _machine.UPDDiskDevice != null) { sb.Append("Disk Media Imported (count: " + _machine.diskImages.Count + ")"); @@ -72,7 +72,7 @@ public void OSD_DiskInit() /// public void OSD_DiskInserted() { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); if (_machine.UPDDiskDevice == null) { @@ -90,7 +90,7 @@ public void OSD_DiskInserted() /// public void OSD_ShowDiskStatus() { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); if (_machine.UPDDiskDevice == null) { @@ -148,7 +148,7 @@ public void OSD_TapeInit() if (_tapeInfo.Count == 0) return; - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); sb.Append("Tape Media Imported (count: " + _tapeInfo.Count + ")"); SendMessage(sb.ToString().TrimEnd('\n'), MessageCategory.Emulator); } @@ -161,7 +161,7 @@ public void OSD_TapePlaying() if (_tapeInfo.Count == 0) return; - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); sb.Append("PLAYING (" + _machine.TapeMediaIndex + ": " + _tapeInfo[_machine.TapeMediaIndex].Name + ")"); SendMessage(sb.ToString().TrimEnd('\n'), MessageCategory.Tape); @@ -175,7 +175,7 @@ public void OSD_TapeStopped() if (_tapeInfo.Count == 0) return; - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); sb.Append("STOPPED (" + _machine.TapeMediaIndex + ": " + _tapeInfo[_machine.TapeMediaIndex].Name + ")"); SendMessage(sb.ToString().TrimEnd('\n'), MessageCategory.Tape); @@ -189,7 +189,7 @@ public void OSD_TapeRTZ() if (_tapeInfo.Count == 0) return; - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); sb.Append("REWOUND (" + _machine.TapeMediaIndex + ": " + _tapeInfo[_machine.TapeMediaIndex].Name + ")"); SendMessage(sb.ToString().TrimEnd('\n'), MessageCategory.Tape); @@ -203,7 +203,7 @@ public void OSD_TapeInserted() if (_tapeInfo.Count == 0) return; - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); sb.Append("TAPE INSERTED (" + _machine.TapeMediaIndex + ": " + _tapeInfo[_machine.TapeMediaIndex].Name + ")"); SendMessage(sb.ToString().TrimEnd('\n'), MessageCategory.Tape); @@ -215,7 +215,7 @@ public void OSD_TapeInserted() /// public void OSD_TapeStoppedAuto() { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); if (_tapeInfo.Count == 0) { @@ -235,7 +235,7 @@ public void OSD_TapeStoppedAuto() /// public void OSD_TapePlayingAuto() { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); if (_tapeInfo.Count == 0) { @@ -255,7 +255,7 @@ public void OSD_TapePlayingAuto() /// public void OSD_TapePlayingBlockInfo(string blockinfo) { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); if (_tapeInfo.Count == 0) { @@ -275,7 +275,7 @@ public void OSD_TapePlayingBlockInfo(string blockinfo) /// public void OSD_TapePlayingSkipBlockInfo(string blockinfo) { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); if (_tapeInfo.Count == 0) { @@ -295,7 +295,7 @@ public void OSD_TapePlayingSkipBlockInfo(string blockinfo) /// public void OSD_TapeEndDetected(string blockinfo) { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); if (_tapeInfo.Count == 0) { @@ -315,7 +315,7 @@ public void OSD_TapeEndDetected(string blockinfo) /// public void OSD_TapeNextBlock(string blockinfo) { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); if (_tapeInfo.Count == 0) { @@ -335,7 +335,7 @@ public void OSD_TapeNextBlock(string blockinfo) /// public void OSD_TapePrevBlock(string blockinfo) { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); if (_tapeInfo.Count == 0) { @@ -355,7 +355,7 @@ public void OSD_TapePrevBlock(string blockinfo) /// public void OSD_ShowTapeStatus() { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); if (_tapeInfo.Count == 0) { @@ -399,7 +399,7 @@ public void OSD_ShowTapeStatus() // get position within the tape itself sb.Append("Tape Pos: "); - var ind = _machine.TapeDevice.CurrentDataBlockIndex; + int ind = _machine.TapeDevice.CurrentDataBlockIndex; int cnt = 0; for (int i = 0; i < ind; i++) { @@ -425,26 +425,17 @@ public void OSD_ShowTapeStatus() /// public bool CheckMessageSettings(MessageCategory category) { - switch (Settings.OSDMessageVerbosity) + return Settings.OSDMessageVerbosity switch { - case OSDVerbosity.Full: - return true; - case OSDVerbosity.None: - return false; - case OSDVerbosity.Medium: - switch (category) - { - case MessageCategory.Disk: - case MessageCategory.Emulator: - case MessageCategory.Tape: - case MessageCategory.Misc: - return true; - default: - return false; - } - default: - return true; - } + OSDVerbosity.Full => true, + OSDVerbosity.None => false, + OSDVerbosity.Medium => category switch + { + MessageCategory.Disk or MessageCategory.Emulator or MessageCategory.Tape or MessageCategory.Misc => true, + _ => false, + }, + _ => true, + }; } /// diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.Util.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.Util.cs index 058aa948aef..6a830edffd1 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.Util.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.Util.cs @@ -24,10 +24,7 @@ public static int GetIntFromBitArray(BitArray bitArray) /// /// POKEs a memory bus address /// - public void PokeMemory(ushort addr, byte value) - { - _machine.WriteBus(addr, value); - } + public void PokeMemory(ushort addr, byte value) => _machine.WriteBus(addr, value); /// /// Called by MainForm so that the core label can display a more detailed tooltip about the emulated spectrum model @@ -67,17 +64,11 @@ public string GetMachineType() /// Called by MainForm - dumps a close approximation of the Spectaculator SZX snapshot format /// DEV use only - this is nowhere near accurate /// - public byte[] GetSZXSnapshot() - { - return SZX.ExportSZX(_machine); - } + public byte[] GetSZXSnapshot() => SZX.ExportSZX(_machine); /// /// Utility method to get MemberName from an object /// - public static string GetMemberName(Expression> memberAccess) - { - return ((MemberExpression)memberAccess.Body).Member.Name; - } + public static string GetMemberName(Expression> memberAccess) => ((MemberExpression)memberAccess.Body).Member.Name; } } diff --git a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.cs b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.cs index d4460aa83a5..754a0fc5ce0 100644 --- a/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.cs +++ b/src/BizHawk.Emulation.Cores/Computers/SinclairSpectrum/ZXSpectrum.cs @@ -20,7 +20,7 @@ public partial class ZXSpectrum : IRegionable, IDriveLight public ZXSpectrum( CoreLoadParameters lp) { - var ser = new BasicServiceProvider(this); + BasicServiceProvider ser = new(this); ServiceProvider = ser; CoreComm = lp.Comm; @@ -38,7 +38,7 @@ public ZXSpectrum( PutSyncSettings(syncSettings); PutSettings(settings); - var joysticks = new List + List joysticks = new() { syncSettings.JoystickType1, syncSettings.JoystickType2, @@ -136,7 +136,7 @@ public ZXSpectrum( _machine.TapeBuzzer.Volume = settings.TapeVolume; } - DCFilter dc = new DCFilter(SoundMixer, 512); + DCFilter dc = new(SoundMixer, 512); ser.Register(dc); ser.Register(new StateSerializer(SyncState)); HardReset(); @@ -157,13 +157,13 @@ public ZXSpectrum( public readonly IList _tapeInfo = new List(); public readonly IList _diskInfo = new List(); - private SyncSoundMixer SoundMixer; + private readonly SyncSoundMixer SoundMixer; private readonly List _files; public bool DiagRom = false; - private readonly List diagRoms = new List + private readonly List diagRoms = new() { @"\DiagROM.v28", @"\zx-diagnostics\testrom.bin" @@ -176,7 +176,7 @@ private byte[] GetFirmware(int length, params string[] names) { if (DiagRom & File.Exists(Directory.GetCurrentDirectory() + diagRoms[diagIndex])) { - var rom = File.ReadAllBytes(Directory.GetCurrentDirectory() + diagRoms[diagIndex]); + byte[] rom = File.ReadAllBytes(Directory.GetCurrentDirectory() + diagRoms[diagIndex]); return rom; } @@ -207,12 +207,7 @@ private byte[] GetFirmware(int length, params string[] names) return embeddedRom; // Embedded ROM not found, maybe this is a peripheral ROM? - var result = names.Select(n => CoreComm.CoreFileProvider.GetFirmware(new("ZXSpectrum", n))).FirstOrDefault(b => b != null && b.Length == length); - if (result == null) - { - throw new MissingFirmwareException($"At least one of these firmwares is required: {string.Join(", ", names)}"); - } - + byte[] result = names.Select(n => CoreComm.CoreFileProvider.GetFirmware(new("ZXSpectrum", n))).FirstOrDefault(b => b != null && b.Length == length) ?? throw new MissingFirmwareException($"At least one of these firmwares is required: {string.Join(", ", names)}"); return result; } @@ -227,46 +222,46 @@ private void Init(MachineType machineType, BorderType borderType, TapeLoadSpeed { case MachineType.ZXSpectrum16: _machine = new ZX16(this, _cpu, borderType, files, joys); - var _systemRom16 = GetFirmware(0x4000, "48ROM"); - var romData16 = RomData.InitROM(machineType, _systemRom16); + byte[] _systemRom16 = GetFirmware(0x4000, "48ROM"); + RomData romData16 = RomData.InitROM(machineType, _systemRom16); _machine.InitROM(romData16); break; case MachineType.ZXSpectrum48: _machine = new ZX48(this, _cpu, borderType, files, joys); - var _systemRom = GetFirmware(0x4000, "48ROM"); - var romData = RomData.InitROM(machineType, _systemRom); + byte[] _systemRom = GetFirmware(0x4000, "48ROM"); + RomData romData = RomData.InitROM(machineType, _systemRom); _machine.InitROM(romData); break; case MachineType.ZXSpectrum128: _machine = new ZX128(this, _cpu, borderType, files, joys); - var _systemRom128 = GetFirmware(0x8000, "128ROM"); - var romData128 = RomData.InitROM(machineType, _systemRom128); + byte[] _systemRom128 = GetFirmware(0x8000, "128ROM"); + RomData romData128 = RomData.InitROM(machineType, _systemRom128); _machine.InitROM(romData128); break; case MachineType.ZXSpectrum128Plus2: _machine = new ZX128Plus2(this, _cpu, borderType, files, joys); - var _systemRomP2 = GetFirmware(0x8000, "PLUS2ROM"); - var romDataP2 = RomData.InitROM(machineType, _systemRomP2); + byte[] _systemRomP2 = GetFirmware(0x8000, "PLUS2ROM"); + RomData romDataP2 = RomData.InitROM(machineType, _systemRomP2); _machine.InitROM(romDataP2); break; case MachineType.ZXSpectrum128Plus2a: _machine = new ZX128Plus2a(this, _cpu, borderType, files, joys); - var _systemRomP4 = GetFirmware(0x10000, "PLUS2AROM"); - var romDataP4 = RomData.InitROM(machineType, _systemRomP4); + byte[] _systemRomP4 = GetFirmware(0x10000, "PLUS2AROM"); + RomData romDataP4 = RomData.InitROM(machineType, _systemRomP4); _machine.InitROM(romDataP4); break; case MachineType.ZXSpectrum128Plus3: _machine = new ZX128Plus3(this, _cpu, borderType, files, joys); - var _systemRomP3 = GetFirmware(0x10000, "PLUS3ROM"); - var romDataP3 = RomData.InitROM(machineType, _systemRomP3); + byte[] _systemRomP3 = GetFirmware(0x10000, "PLUS3ROM"); + RomData romDataP3 = RomData.InitROM(machineType, _systemRomP3); _machine.InitROM(romDataP3); break; case MachineType.Pentagon128: _machine = new Pentagon128(this, _cpu, borderType, files, joys); - var _systemRomPen128 = GetFirmware(0x8000, "PentagonROM"); - var _systemRomTrdos = GetFirmware(0x4000, "TRDOSROM"); - var conc = _systemRomPen128.Concat(_systemRomTrdos).ToArray(); - var romDataPen128 = RomData.InitROM(machineType, conc); + byte[] _systemRomPen128 = GetFirmware(0x8000, "PentagonROM"); + byte[] _systemRomTrdos = GetFirmware(0x4000, "TRDOSROM"); + byte[] conc = _systemRomPen128.Concat(_systemRomTrdos).ToArray(); + RomData romDataPen128 = RomData.InitROM(machineType, conc); _machine.InitROM(romDataPen128); break; } diff --git a/src/BizHawk.Emulation.Cores/Computers/TIC80/TIC80.ISettable.cs b/src/BizHawk.Emulation.Cores/Computers/TIC80/TIC80.ISettable.cs index 2f224e51b7b..65e2b07619f 100644 --- a/src/BizHawk.Emulation.Cores/Computers/TIC80/TIC80.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Computers/TIC80/TIC80.ISettable.cs @@ -25,7 +25,7 @@ public PutSettingsDirtyBits PutSettings(TIC80Settings o) public PutSettingsDirtyBits PutSyncSettings(TIC80SyncSettings o) { - var ret = TIC80SyncSettings.NeedsReboot(_syncSettings, o); + bool ret = TIC80SyncSettings.NeedsReboot(_syncSettings, o); _syncSettings = o; return ret ? PutSettingsDirtyBits.RebootCore : PutSettingsDirtyBits.None; } diff --git a/src/BizHawk.Emulation.Cores/Computers/TIC80/TIC80.cs b/src/BizHawk.Emulation.Cores/Computers/TIC80/TIC80.cs index 8bd68433350..d1458080e1a 100644 --- a/src/BizHawk.Emulation.Cores/Computers/TIC80/TIC80.cs +++ b/src/BizHawk.Emulation.Cores/Computers/TIC80/TIC80.cs @@ -50,8 +50,8 @@ public TIC80(CoreLoadParameters lp) SkipMemoryConsistencyCheck = CoreComm.CorePreferences.HasFlag(CoreComm.CorePreferencesFlags.WaterboxMemoryConsistencyCheck), }); - var rom = lp.Roms[0].FileData; - var inputsActive = new bool[6] + byte[] rom = lp.Roms[0].FileData; + bool[] inputsActive = new bool[6] { _syncSettings.Gamepad1, _syncSettings.Gamepad2, @@ -83,11 +83,11 @@ public TIC80(CoreLoadParameters lp) private static IReadOnlyCollection> MakeKeyMap() { var enumValues = Enum.GetValues(typeof(LibTIC80.TIC80Keys)); - var ret = new KeyValuePair[enumValues.Length - 1]; + KeyValuePair[] ret = new KeyValuePair[enumValues.Length - 1]; for (int i = 0; i < ret.Length; i++) { - var val = enumValues.GetValue(i + 1); - var name = Enum.GetName(typeof(LibTIC80.TIC80Keys), val).TrimStart('_').Replace('_', ' '); + object val = enumValues.GetValue(i + 1); + string name = Enum.GetName(typeof(LibTIC80.TIC80Keys), val).TrimStart('_').Replace('_', ' '); ret[i] = new(name, (LibTIC80.TIC80Keys)val); } @@ -96,13 +96,13 @@ public TIC80(CoreLoadParameters lp) private static ControllerDefinition CreateControllerDefinition(bool[] inputsActive) { - var ret = new ControllerDefinition("TIC-80 Controller"); + ControllerDefinition ret = new("TIC-80 Controller"); for (int i = 0; i < 4; i++) { if (inputsActive[i]) { - foreach (var b in Enum.GetValues(typeof(LibTIC80.TIC80Gamepad))) + foreach (object b in Enum.GetValues(typeof(LibTIC80.TIC80Gamepad))) { ret.BoolButtons.Add($"P{i + 1} {Enum.GetName(typeof(LibTIC80.TIC80Gamepad), b)}"); } @@ -118,7 +118,7 @@ private static ControllerDefinition CreateControllerDefinition(bool[] inputsActi ret.AddXYPair("Mouse Scroll {0}", AxisPairOrientation.RightAndUp, (-32).RangeTo(31), 0); ret.BoolButtons.Add("Mouse Relative Toggle"); - foreach (var n in ret.BoolButtons) + foreach (string n in ret.BoolButtons) { if (n.StartsWithOrdinal("Mouse")) { @@ -126,7 +126,7 @@ private static ControllerDefinition CreateControllerDefinition(bool[] inputsActi } } - foreach (var n in ret.Axes.Keys) + foreach (string n in ret.Axes.Keys) { if (n.StartsWithOrdinal("Mouse")) { @@ -137,9 +137,9 @@ private static ControllerDefinition CreateControllerDefinition(bool[] inputsActi if (inputsActive[5]) { - foreach (var k in Enum.GetValues(typeof(LibTIC80.TIC80Keys))) + foreach (object k in Enum.GetValues(typeof(LibTIC80.TIC80Keys))) { - var name = Enum.GetName(typeof(LibTIC80.TIC80Keys), k).TrimStart('_').Replace('_', ' '); + string name = Enum.GetName(typeof(LibTIC80.TIC80Keys), k).TrimStart('_').Replace('_', ' '); if (name is "Unknown") continue; ret.BoolButtons.Add(name); ret.CategoryLabels[name] = "Keyboard"; @@ -153,11 +153,11 @@ private static ControllerDefinition CreateControllerDefinition(bool[] inputsActi private static void GetGamepads(IController controller, ref LibTIC80.TIC80Inputs inputs) { - var gamepads = new LibTIC80.TIC80Gamepad[4]; + LibTIC80.TIC80Gamepad[] gamepads = new LibTIC80.TIC80Gamepad[4]; for (int i = 0; i < 4; i++) { gamepads[i] = 0; - foreach (var b in Enum.GetValues(typeof(LibTIC80.TIC80Gamepad))) + foreach (object b in Enum.GetValues(typeof(LibTIC80.TIC80Gamepad))) { if (controller.IsPressed($"P{i + 1} {Enum.GetName(typeof(LibTIC80.TIC80Gamepad), b)}")) { @@ -187,9 +187,9 @@ private static ushort GetMouseButtons(IController controller) { ret |= 0x2000; } - var x = (ushort)((sbyte)controller.AxisValue("Mouse Scroll X") + 32); + ushort x = (ushort)((sbyte)controller.AxisValue("Mouse Scroll X") + 32); ret |= (ushort)(x << 7); - var y = (ushort)((sbyte)controller.AxisValue("Mouse Scroll Y") + 32); + ushort y = (ushort)((sbyte)controller.AxisValue("Mouse Scroll Y") + 32); ret |= (ushort)(y << 1); if (controller.IsPressed("Mouse Relative Toggle")) { @@ -200,7 +200,7 @@ private static ushort GetMouseButtons(IController controller) private static void GetKeys(IController controller, ref LibTIC80.TIC80Inputs inputs) { - var keys = new LibTIC80.TIC80Keys[4]; + LibTIC80.TIC80Keys[] keys = new LibTIC80.TIC80Keys[4]; int i = 0; foreach (var kvp in KeyMap) { @@ -222,7 +222,7 @@ private static void GetKeys(IController controller, ref LibTIC80.TIC80Inputs inp protected override LibWaterboxCore.FrameInfo FrameAdvancePrep(IController controller, bool render, bool rendersound) { - var inputs = new LibTIC80.TIC80Inputs + LibTIC80.TIC80Inputs inputs = new() { MouseX = (sbyte)controller.AxisValue("Mouse Position X"), MouseY = (sbyte)controller.AxisValue("Mouse Position Y"), diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600.Core.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600.Core.cs index c1ae0606569..50bb43b22f7 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600.Core.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600.Core.cs @@ -40,7 +40,7 @@ public partial class Atari2600 public bool unselect_reset; public bool unselect_select; - internal struct CpuLink : IMOS6502XLink + internal readonly struct CpuLink : IMOS6502XLink { private readonly Atari2600 _atari2600; @@ -49,15 +49,15 @@ public CpuLink(Atari2600 atari2600) _atari2600 = atari2600; } - public byte DummyReadMemory(ushort address) => _atari2600.ReadMemory(address); + public readonly byte DummyReadMemory(ushort address) => _atari2600.ReadMemory(address); - public void OnExecFetch(ushort address) => _atari2600.ExecFetch(address); + public readonly void OnExecFetch(ushort address) => _atari2600.ExecFetch(address); - public byte PeekMemory(ushort address) => _atari2600.ReadMemory(address); + public readonly byte PeekMemory(ushort address) => _atari2600.ReadMemory(address); - public byte ReadMemory(ushort address) => _atari2600.ReadMemory(address); + public readonly byte ReadMemory(ushort address) => _atari2600.ReadMemory(address); - public void WriteMemory(ushort address, byte value) => _atari2600.WriteMemory(address, value); + public readonly void WriteMemory(ushort address, byte value) => _atari2600.WriteMemory(address, value); } // keeps track of tia cycles, 3 cycles per CPU cycle @@ -148,12 +148,12 @@ private byte ReadMemory(ushort addr) } _mapper.Bit13 = addr.Bit(13); - var temp = _mapper.ReadMemory((ushort)(addr & 0x1FFF)); + byte temp = _mapper.ReadMemory((ushort)(addr & 0x1FFF)); _tia.BusState = temp; if (MemoryCallbacks.HasReads) { - var flags = (uint)(MemoryCallbackFlags.AccessRead); + uint flags = (uint)(MemoryCallbackFlags.AccessRead); MemoryCallbacks.CallMemoryCallbacks(addr, 0, flags, "System Bus"); } @@ -173,22 +173,19 @@ private void WriteMemory(ushort addr, byte value) if (MemoryCallbacks.HasWrites) { - var flags = (uint)(MemoryCallbackFlags.AccessWrite); + uint flags = (uint)(MemoryCallbackFlags.AccessWrite); MemoryCallbacks.CallMemoryCallbacks(addr, value, flags, "System Bus"); } } - internal void PokeMemory(ushort addr, byte value) - { - _mapper.PokeMemory((ushort)(addr & 0x1FFF), value); - } + internal void PokeMemory(ushort addr, byte value) => _mapper.PokeMemory((ushort)(addr & 0x1FFF), value); [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ExecFetch(ushort addr) { if (MemoryCallbacks.HasExecutes) { - var flags = (uint)(MemoryCallbackFlags.AccessExecute); + uint flags = (uint)(MemoryCallbackFlags.AccessExecute); MemoryCallbacks.CallMemoryCallbacks(addr, 0, flags, "System Bus"); } } @@ -225,17 +222,17 @@ private void RebootCore() RomDetails = $"{_game.Name}\r\n{SHA1Checksum.ComputePrefixedHex(Rom)}\r\n{MD5Checksum.ComputePrefixedHex(Rom)}\r\nMapper Impl \"{_mapper.GetType()}\""; // Some games (ex. 3D tic tac toe), turn off the screen for extended periods, so we need to allow for this here. - if (_game.GetOptions().TryGetValue("SP_FRAME", out var spFrameStr) && spFrameStr == "true") + if (_game.GetOptions().TryGetValue("SP_FRAME", out string spFrameStr) && spFrameStr == "true") { SP_FRAME = true; } // Some games wait for reset to be unpressed before turning the screen back on, hack unset it if needed - if (_game.GetOptions().TryGetValue("SP_RESET", out var spResetStr) && spResetStr == "true") + if (_game.GetOptions().TryGetValue("SP_RESET", out string spResetStr) && spResetStr == "true") { SP_RESET = true; } // Ditto select (ex. Karate) - if (_game.GetOptions().TryGetValue("SP_SELECT", out var spSelectStr) && spSelectStr == "true") + if (_game.GetOptions().TryGetValue("SP_SELECT", out string spSelectStr) && spSelectStr == "true") { SP_SELECT = true; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600.IMemoryDomains.cs index 8c3459bab59..648e40ec4d9 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600.IMemoryDomains.cs @@ -8,12 +8,12 @@ namespace BizHawk.Emulation.Cores.Atari.Atari2600 public partial class Atari2600 { internal IMemoryDomains MemoryDomains; - private readonly Dictionary _byteArrayDomains = new Dictionary(); + private readonly Dictionary _byteArrayDomains = new(); private bool _memoryDomainsInit; private void SetupMemoryDomains() { - var domains = new List + List domains = new() { new MemoryDomainDelegate( "TIA", @@ -72,7 +72,7 @@ private void SyncByteArrayDomain(string name, byte[] data) } else { - var m = new MemoryDomainByteArray(name, MemoryDomain.Endian.Little, data, true, 1); + MemoryDomainByteArray m = new(name, MemoryDomain.Endian.Little, data, true, 1); _byteArrayDomains.Add(name, m); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600.ISettable.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600.ISettable.cs index 73d14250712..240a214d8b8 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600.ISettable.cs @@ -11,15 +11,9 @@ namespace BizHawk.Emulation.Cores.Atari.Atari2600 { public partial class Atari2600 : ISettable { - public A2600Settings GetSettings() - { - return Settings.Clone(); - } + public A2600Settings GetSettings() => Settings.Clone(); - public A2600SyncSettings GetSyncSettings() - { - return SyncSettings.Clone(); - } + public A2600SyncSettings GetSyncSettings() => SyncSettings.Clone(); public PutSettingsDirtyBits PutSettings(A2600Settings o) { @@ -136,10 +130,7 @@ public int PALBottomLine [DefaultValue(typeof(Color), "Black")] public Color BackgroundColor { get; set; } - public A2600Settings Clone() - { - return (A2600Settings)MemberwiseClone(); - } + public A2600Settings Clone() => (A2600Settings)MemberwiseClone(); public A2600Settings() { @@ -181,20 +172,14 @@ public class A2600SyncSettings [DefaultValue(false)] public bool FastScBios { get; set; } - public A2600SyncSettings Clone() - { - return (A2600SyncSettings)MemberwiseClone(); - } + public A2600SyncSettings Clone() => (A2600SyncSettings)MemberwiseClone(); public A2600SyncSettings() { SettingsUtil.SetDefaultValues(this); } - public static bool NeedsReboot(A2600SyncSettings x, A2600SyncSettings y) - { - return !DeepEquality.DeepEquals(x, y); - } + public static bool NeedsReboot(A2600SyncSettings x, A2600SyncSettings y) => !DeepEquality.DeepEquals(x, y); } } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600.RomHeuristics.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600.RomHeuristics.cs index 928596d20bf..55efc9bc4a4 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600.RomHeuristics.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600.RomHeuristics.cs @@ -77,7 +77,7 @@ private static string DetectMapper(byte[] rom) return "F8"; } - if (rom.Length >= 10240 && rom.Length <= 10496) // ~10K - Pitfall2 + if (rom.Length is >= 10240 and <= 10496) // ~10K - Pitfall2 { return "DPC"; } @@ -112,7 +112,7 @@ private static string DetectMapper(byte[] rom) return "F6"; } - if (rom.Length == 24 * 1024 || rom.Length == 28 * 1024) // 24K & 28K + if (rom.Length is (24 * 1024) or (28 * 1024)) // 24K & 28K { return "FA2"; } @@ -236,11 +236,11 @@ private static bool IsProbablySC(IList rom) // We assume a Superchip cart contains the same bytes for its entire // RAM area; obviously this test will fail if it doesn't // The RAM area will be the first 256 bytes of each 4K bank - var numBanks = rom.Count / 4096; - for (var i = 0; i < numBanks; i++) + int numBanks = rom.Count / 4096; + for (int i = 0; i < numBanks; i++) { - var first = rom[i * 4096]; - for (var j = 0; j < 256; j++) + byte first = rom[i * 4096]; + for (int j = 0; j < 256; j++) { if (rom[(i * 4096) + j] != first) { @@ -252,13 +252,11 @@ private static bool IsProbablySC(IList rom) return false; } - private static bool IsProbably3E(byte[] rom) - { + private static bool IsProbably3E(byte[] rom) => // 3E cart bankswitching is triggered by storing the bank number // in address 3E using 'STA $3E', commonly followed by an // immediate mode LDA - return rom.FindBytes(new byte[] { 0x85, 0x3E, 0xA9, 0x00 }); // STA $3E; LDA #$00 - } + rom.FindBytes(new byte[] { 0x85, 0x3E, 0xA9, 0x00 }); // STA $3E; LDA #$00 private static bool IsProbably3F(byte[] rom) { @@ -441,14 +439,8 @@ private static bool IsProbablySB(byte[] rom) }); } - private static bool ContainsAny(byte[] rom, IEnumerable signatures) - { - return signatures.Any(rom.FindBytes); - } + private static bool ContainsAny(byte[] rom, IEnumerable signatures) => signatures.Any(rom.FindBytes); - private static bool ContainsAll(byte[] rom, IEnumerable signatures) - { - return signatures.All(rom.FindBytes); - } + private static bool ContainsAll(byte[] rom, IEnumerable signatures) => signatures.All(rom.FindBytes); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600.cs index babcfed61b8..b41b107b2e2 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600.cs @@ -23,7 +23,7 @@ internal static class RomChecksums [CoreConstructor(VSystemID.Raw.A26)] public Atari2600(GameInfo game, byte[] rom, Atari2600.A2600Settings settings, Atari2600.A2600SyncSettings syncSettings) { - var ser = new BasicServiceProvider(this); + BasicServiceProvider ser = new(this); ServiceProvider = ser; _ram = new byte[128]; @@ -44,7 +44,7 @@ public Atari2600(GameInfo game, byte[] rom, Atari2600.A2600Settings settings, At game.AddOption("m", DetectMapper(rom)); } - var romHashSHA1 = SHA1Checksum.ComputePrefixedHex(Rom); + string romHashSHA1 = SHA1Checksum.ComputePrefixedHex(Rom); if (romHashSHA1 is RomChecksums.CongoBongo or RomChecksums.Tapper or RomChecksums.KangarooNotInGameDB) { game.RemoveOption("m"); @@ -110,7 +110,7 @@ private static bool DetectPal(GameInfo game, byte[] rom) // here we advance past start up irregularities to see how long a frame is based on calls to Vsync // we run 72 frames, then run 270 scanlines worth of cycles. // if we don't hit a new frame, we can be pretty confident we are in PAL - using var emu = new Atari2600(newGame, rom, null, null); + using Atari2600 emu = new(newGame, rom, null, null); for (int i = 0; i < 72; i++) { emu.FrameAdvance(NullController.Instance, false, false); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600ControllerDeck.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600ControllerDeck.cs index 6558d8328df..69e38ee8707 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600ControllerDeck.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600ControllerDeck.cs @@ -32,25 +32,13 @@ public Atari2600ControllerDeck(Atari2600ControllerTypes controller1, Atari2600Co Definition.MakeImmutable(); } - public byte ReadPort1(IController c) - { - return Port1.Read(c); - } + public byte ReadPort1(IController c) => Port1.Read(c); - public byte ReadPort2(IController c) - { - return Port2.Read(c); - } + public byte ReadPort2(IController c) => Port2.Read(c); - public int ReadPot1(IController c, int pot) - { - return Port1.Read_Pot(c, pot); - } + public int ReadPot1(IController c, int pot) => Port1.Read_Pot(c, pot); - public int ReadPot2(IController c, int pot) - { - return Port2.Read_Pot(c, pot); - } + public int ReadPot2(IController c, int pot) => Port2.Read_Pot(c, pot); public ControllerDefinition Definition { get; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600Controllers.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600Controllers.cs index 47cc13cfb81..1c82625eb5b 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600Controllers.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Atari2600Controllers.cs @@ -40,15 +40,9 @@ public UnpluggedController(int portNum) Definition = new("(Atari 2600 Basic Controller fragment)"); } - public byte Read(IController c) - { - return 0xFF; - } + public byte Read(IController c) => 0xFF; - public int Read_Pot(IController c, int pot) - { - return -1; // indicates not applicable - } + public int Read_Pot(IController c, int pot) => -1; // indicates not applicable public ControllerDefinition Definition { get; } @@ -95,10 +89,7 @@ public byte Read(IController c) return result; } - public int Read_Pot(IController c, int pot) - { - return -1; // indicates not applicable - } + public int Read_Pot(IController c, int pot) => -1; // indicates not applicable private static readonly string[] BaseDefinition = { @@ -294,10 +285,7 @@ public byte Read(IController c) return result; } - public int Read_Pot(IController c, int pot) - { - return -1; // indicates not applicable - } + public int Read_Pot(IController c, int pot) => -1; // indicates not applicable private static float CalcDirection(float x, float y) { @@ -360,10 +348,7 @@ public byte Read(IController c) return result; } - public int Read_Pot(IController c, int pot) - { - return -2; // indicates keyboard - } + public int Read_Pot(IController c, int pot) => -2; // indicates keyboard private static readonly string[] BaseDefinition = { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/M6532.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/M6532.cs index 9ac41313769..ed152917a3a 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/M6532.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/M6532.cs @@ -31,13 +31,13 @@ public byte ReadMemory(ushort addr, bool peek) return _core.Ram[(ushort)(addr & 0x007f)]; } - var registerAddr = (ushort)(addr & 0x0007); + ushort registerAddr = (ushort)(addr & 0x0007); if (registerAddr == 0x00) { // Read Output reg A // Combine readings from player 1 and player 2 // actually depends on setting in SWCHCNTA (aka DDRa) - var temp = (byte)(_core.ReadControls1(peek) & 0xF0 | ((_core.ReadControls2(peek) >> 4) & 0x0F)); + byte temp = (byte)(_core.ReadControls1(peek) & 0xF0 | ((_core.ReadControls2(peek) >> 4) & 0x0F)); temp = (byte)(temp & ~_ddRa); temp = (byte)(temp + (_outputA & _ddRa)); return temp; @@ -52,7 +52,7 @@ public byte ReadMemory(ushort addr, bool peek) if (registerAddr == 0x02) { // Read Output reg B - var temp = _core.ReadConsoleSwitches(peek); + byte temp = _core.ReadConsoleSwitches(peek); temp = (byte)(temp & ~_ddRb); return temp; } @@ -112,7 +112,7 @@ public void WriteMemory(ushort addr, byte value) { Timer.Overflowed = false; - var registerAddr = (ushort)(addr & 0x0007); + ushort registerAddr = (ushort)(addr & 0x0007); // Bit 0x0080 contains interrupt enable/disable Timer.InterruptEnabled = (addr & 0x0080) != 0; @@ -157,7 +157,7 @@ public void WriteMemory(ushort addr, byte value) // these are register writes else if ((addr & 0x0004) == 0) { - var registerAddr = (ushort)(addr & 0x0007); + ushort registerAddr = (ushort)(addr & 0x0007); if (registerAddr == 0x00) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/Multicart2K.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/Multicart2K.cs index c81c2450407..92469d4c3e0 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/Multicart2K.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/Multicart2K.cs @@ -21,10 +21,7 @@ public override void SyncState(Serializer ser) base.SyncState(ser); } - public override void HardReset() - { - IncrementGame(); - } + public override void HardReset() => IncrementGame(); public override byte ReadMemory(ushort addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/Multicart4K.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/Multicart4K.cs index 62b8bcf019b..dc163ba51dc 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/Multicart4K.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/Multicart4K.cs @@ -21,10 +21,7 @@ public override void SyncState(Serializer ser) base.SyncState(ser); } - public override void HardReset() - { - IncrementGame(); - } + public override void HardReset() => IncrementGame(); public override byte ReadMemory(ushort addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/m0840.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/m0840.cs index abf14152859..9a3f97bea11 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/m0840.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/m0840.cs @@ -35,10 +35,7 @@ public override void SyncState(Serializer ser) ser.Sync("bank_4k", ref _bank4K); } - public override void HardReset() - { - _bank4K = 0; - } + public override void HardReset() => _bank4K = 0; public override byte ReadMemory(ushort addr) => ReadMem(addr, false); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/m3F.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/m3F.cs index ea08534a23d..9bb17bb1c4a 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/m3F.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/m3F.cs @@ -34,10 +34,7 @@ public override void SyncState(Serializer ser) ser.Sync("lowbank_2k", ref _lowBank2K); } - public override void HardReset() - { - _lowBank2K = 0; - } + public override void HardReset() => _lowBank2K = 0; public override byte ReadMemory(ushort addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mAR.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mAR.cs index 4a1da154c57..2494113a57b 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mAR.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mAR.cs @@ -175,10 +175,7 @@ public override void SyncState(Serializer ser) base.SyncState(ser); } - public override void ClockCpu() - { - _elapsedCycles++; - } + public override void ClockCpu() => _elapsedCycles++; public override byte ReadMemory(ushort addr) => ReadMem(addr, false); @@ -453,7 +450,7 @@ private void LoadIntoRam(byte load) { int bank = _header[16 + j] & 0x03; int page = (_header[16 + j] >> 2) & 0x07; - var src = _loadedImages + byte[] src = _loadedImages .Skip((image * 8448) + (j * 256)) .Take(256) .ToArray(); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mCM.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mCM.cs index 95b750b67f2..8bf1e41a661 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mCM.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mCM.cs @@ -304,11 +304,11 @@ private void WriteMem(ushort addr, byte value, bool poke) // these are register writes else if ((addr & 0x0004) == 0) { - var registerAddr = (ushort)(addr & 0x0007); + ushort registerAddr = (ushort)(addr & 0x0007); if (registerAddr == 0x00) { - if (addr != 640 && addr >= 0x280) // register addresses are only above 0x280 + if (addr is not 640 and >= 0x280) // register addresses are only above 0x280 { // Write Output reg A ////isPortA = true; @@ -320,8 +320,8 @@ private void WriteMem(ushort addr, byte value, bool poke) if (addr == 0x280 && !poke) // Stella uses only 280 ////if (isPortA && !poke) { - var bit5 = value.Bit(5); - var bit4 = value.Bit(4); + bool bit5 = value.Bit(5); + bool bit4 = value.Bit(4); // D5 RAM direction. (high = write, low = read) // 0 -> enable RAM writing (if D4 = 1) diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mCV.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mCV.cs index 9ccd8d96e48..83c2e6c757a 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mCV.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mCV.cs @@ -31,10 +31,7 @@ public override void SyncState(Serializer ser) ser.Sync("aux_ram", ref _ram, false); } - public override void HardReset() - { - _ram = new byte[1024]; - } + public override void HardReset() => _ram = new byte[1024]; public override byte ReadMemory(ushort addr) { @@ -48,7 +45,7 @@ public override byte ReadMemory(ushort addr) return _ram[(addr & 0x3FF)]; } - if (addr >= 0x1800 && addr < 0x2000) + if (addr is >= 0x1800 and < 0x2000) { return Core.Rom[addr & 0x7FF]; } @@ -70,7 +67,7 @@ private void WriteMem(ushort addr, byte value, bool poke) { base.WriteMemory(addr, value); } - else if (addr >= 0x1400 && addr < 0x1800) + else if (addr is >= 0x1400 and < 0x1800) { _ram[addr & 0x3FF] = value; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mDPC.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mDPC.cs index 33272a7ea5f..f6af827fd08 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mDPC.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mDPC.cs @@ -278,10 +278,7 @@ public override void HardReset() _fractionalClocks = 0; } - public override void ClockCpu() - { - _elapsedCycles++; - } + public override void ClockCpu() => _elapsedCycles++; public override byte ReadMemory(ushort addr) => ReadMem(addr, false); @@ -311,8 +308,8 @@ private byte ReadMem(ushort addr, bool peek) byte result; // Get the index of the data fetcher that's being accessed - var index = addr & 0x07; - var function = (addr >> 3) & 0x07; + int index = addr & 0x07; + int function = (addr >> 3) & 0x07; // Update flag register for selected data fetcher if ((_counters[index] & 0x00ff) == _tops[index]) @@ -333,7 +330,7 @@ private byte ReadMem(ushort addr, bool peek) } else // No, it's a music read { - var musicAmplitudes = new byte[] { + byte[] musicAmplitudes = new byte[] { 0x00, 0x04, 0x05, 0x09, 0x06, 0x0a, 0x0b, 0x0f }; @@ -406,10 +403,10 @@ private void WriteMem(ushort addr, byte value, bool poke) return; } - if (addr >= 0x1040 && addr < 0x1080) + if (addr is >= 0x1040 and < 0x1080) { - var index = addr & 0x07; - var function = (addr >> 3) & 0x07; + int index = addr & 0x07; + int function = (addr >> 3) & 0x07; switch (function) { @@ -484,7 +481,7 @@ private void ClockRandomNumberGenerator() { // Using bits 7, 5, 4, & 3 of the shift register compute the input // bit for the shift register - var bit = _randomInputBits[((_currentRandomVal >> 3) & 0x07) + byte bit = _randomInputBits[((_currentRandomVal >> 3) & 0x07) | ((_currentRandomVal & 0x80) > 0 ? 0x08 : 0x00)]; // Update the shift register @@ -494,12 +491,12 @@ private void ClockRandomNumberGenerator() private void UpdateMusicModeDataFetchers() { // Calculate the number of cycles since the last update - var cycles = _elapsedCycles; + int cycles = _elapsedCycles; _elapsedCycles = 0; // Calculate the number of DPC OSC clocks since the last update - var clocks = ((20000.0 * cycles) / 1193191.66666667) + _fractionalClocks; - var wholeClocks = (int)clocks; + double clocks = ((20000.0 * cycles) / 1193191.66666667) + _fractionalClocks; + int wholeClocks = (int)clocks; _fractionalClocks = (float)(clocks - wholeClocks); if (wholeClocks <= 0) @@ -508,13 +505,13 @@ private void UpdateMusicModeDataFetchers() } // Let's update counters and flags of the music mode data fetchers - for (var x = 5; x <= 7; ++x) + for (int x = 5; x <= 7; ++x) { // Update only if the data fetcher is in music mode if (_musicModes[x - 5]) { - var top = _tops[x] + 1; - var newLow = _counters[x] & 0x00ff; + int top = _tops[x] + 1; + int newLow = _counters[x] & 0x00ff; if (_tops[x] != 0) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mDPCPlus.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mDPCPlus.cs index 57a4b1fb635..bdad91c62cc 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mDPCPlus.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mDPCPlus.cs @@ -67,10 +67,7 @@ public override void HardReset() _fractionalClocks = 0; } - public override void ClockCpu() - { - _elapsedCycles++; - } + public override void ClockCpu() => _elapsedCycles++; public override byte ReadMemory(ushort addr) => ReadMem(addr, false); @@ -87,10 +84,10 @@ public override void WriteMemory(ushort addr, byte value) Address(addr); ClockRandomNumberGenerator(); - if (addr >= 0x1040 && addr < 0x1080) + if (addr is >= 0x1040 and < 0x1080) { - var index = addr & 0x07; - var function = (addr >> 3) & 0x07; + int index = addr & 0x07; + int function = (addr >> 3) & 0x07; switch (function) { @@ -167,8 +164,8 @@ private byte ReadMem(ushort addr, bool peek) byte result; // Get the index of the data fetcher that's being accessed - var index = addr & 0x07; - var function = (addr >> 3) & 0x07; + int index = addr & 0x07; + int function = (addr >> 3) & 0x07; // Update flag register for selected data fetcher if ((_counters[index] & 0x00ff) == _tops[index]) @@ -189,7 +186,7 @@ private byte ReadMem(ushort addr, bool peek) } else // No, it's a music read { - var musicAmplitudes = new byte[] { + byte[] musicAmplitudes = new byte[] { 0x00, 0x04, 0x05, 0x09, 0x06, 0x0a, 0x0b, 0x0f }; @@ -281,7 +278,7 @@ private void ClockRandomNumberGenerator() { // Using bits 7, 5, 4, & 3 of the shift register compute the input // bit for the shift register - var bit = _randomInputBits[((_currentRandomVal >> 3) & 0x07) | + byte bit = _randomInputBits[((_currentRandomVal >> 3) & 0x07) | (((_currentRandomVal & 0x80) > 0) ? 0x08 : 0x00)]; // Update the shift register @@ -291,12 +288,12 @@ private void ClockRandomNumberGenerator() private void UpdateMusicModeDataFetchers() { // Calculate the number of cycles since the last update - var cycles = _elapsedCycles; + int cycles = _elapsedCycles; _elapsedCycles = 0; // Calculate the number of DPC OSC clocks since the last update - var clocks = ((20000.0 * cycles) / 1193191.66666667) + _fractionalClocks; - var wholeClocks = (int)clocks; + double clocks = ((20000.0 * cycles) / 1193191.66666667) + _fractionalClocks; + int wholeClocks = (int)clocks; _fractionalClocks = (float)(clocks - wholeClocks); if (wholeClocks <= 0) @@ -305,13 +302,13 @@ private void UpdateMusicModeDataFetchers() } // Let's update counters and flags of the music mode data fetchers - for (var x = 5; x <= 7; ++x) + for (int x = 5; x <= 7; ++x) { // Update only if the data fetcher is in music mode if (_musicModes[x - 5]) { - var top = _tops[x] + 1; - var newLow = _counters[x] & 0x00ff; + int top = _tops[x] + 1; + int newLow = _counters[x] & 0x00ff; if (_tops[x] != 0) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mE7.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mE7.cs index 683ae5ed6d6..c1e4388aaf3 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mE7.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mE7.cs @@ -131,7 +131,7 @@ private void WriteMem(ushort addr, byte value, bool poke) { _ram[addr & 0x3FF] = value; } - else if (addr >= 0x1800 && addr < 0x1900) + else if (addr is >= 0x1800 and < 0x1900) { _ram[RamBank1Offset + (addr & 0xFF) + (_ramBank1Toggle * 0x100)] = value; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mEF.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mEF.cs index 76adc926697..56d18b1c2d8 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mEF.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mEF.cs @@ -25,10 +25,7 @@ public override void SyncState(Serializer ser) ser.Sync("toggle", ref _toggle); } - public override void HardReset() - { - _toggle = 0; - } + public override void HardReset() => _toggle = 0; public override byte ReadMemory(ushort addr) => ReadMem(addr, false); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mF0.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mF0.cs index a6488979721..b0df5d0435b 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mF0.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mF0.cs @@ -31,10 +31,7 @@ public override void SyncState(Serializer ser) ser.Sync("bank", ref _bank); } - public override void HardReset() - { - _bank = 0; - } + public override void HardReset() => _bank = 0; public override byte ReadMemory(ushort addr) => ReadMem(addr, false); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mF4.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mF4.cs index acbd350207b..035bc73b5f9 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mF4.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mF4.cs @@ -23,10 +23,7 @@ public override void SyncState(Serializer ser) ser.Sync("toggle", ref _toggle); } - public override void HardReset() - { - _toggle = 0; - } + public override void HardReset() => _toggle = 0; public override byte ReadMemory(ushort addr) => ReadMem(addr, false); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mF6.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mF6.cs index 69b9ab83eff..7b7c112d27f 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mF6.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mF6.cs @@ -25,10 +25,7 @@ public override void SyncState(Serializer ser) ser.Sync("toggle", ref _toggle); } - public override void HardReset() - { - _toggle = 0; - } + public override void HardReset() => _toggle = 0; private byte ReadMem(ushort addr, bool peek) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mF8.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mF8.cs index 2a870efbfee..dcca64f8bc5 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mF8.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mF8.cs @@ -33,10 +33,7 @@ public override void SyncState(Serializer ser) ser.Sync("bank_4k", ref _bank4K); } - public override void HardReset() - { - _bank4K = 0; - } + public override void HardReset() => _bank4K = 0; public override byte ReadMemory(ushort addr) => ReadMem(addr, false); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mF8_sega.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mF8_sega.cs index 0904fc759bf..14c65c25bd4 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mF8_sega.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mF8_sega.cs @@ -22,10 +22,7 @@ public override void SyncState(Serializer ser) ser.Sync("bank_4k", ref _bank4K); } - public override void HardReset() - { - _bank4K = 1; - } + public override void HardReset() => _bank4K = 1; public override byte ReadMemory(ushort addr) => ReadMem(addr, false); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mSB.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mSB.cs index 92f387d19bc..cda0f9a3ba7 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mSB.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mSB.cs @@ -22,10 +22,7 @@ public override void SyncState(Serializer ser) ser.Sync("bank_4k", ref _bank4K); } - public override void HardReset() - { - _bank4K = 0; - } + public override void HardReset() => _bank4K = 0; public override byte ReadMemory(ushort addr) => ReadMem(addr, false); @@ -69,7 +66,7 @@ private void WriteMem(ushort addr, byte value, bool poke) private void Address(ushort addr) { - var temp = addr & (0x17FF + (Core.Rom.Length >> 12)); + int temp = addr & (0x17FF + (Core.Rom.Length >> 12)); if ((temp & 0x1800) == 0x800) { _bank4K = temp & MyStartBank; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mUA.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mUA.cs index 9be82a33e71..e6d977bd605 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mUA.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mUA.cs @@ -25,10 +25,7 @@ public override void SyncState(Serializer ser) ser.Sync("toggle", ref _toggle); } - public override void HardReset() - { - _toggle = 0; - } + public override void HardReset() => _toggle = 0; public override byte ReadMemory(ushort addr) => ReadMem(addr, false); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mX07.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mX07.cs index 4e24601cddb..32114e143f5 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mX07.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Mappers/mX07.cs @@ -47,10 +47,7 @@ public override void SyncState(Serializer ser) ser.Sync("rombank_2k", ref _romBank2K); } - public override void HardReset() - { - _romBank2K = 0; - } + public override void HardReset() => _romBank2K = 0; public override byte ReadMemory(ushort addr) => ReadMem(addr, false); @@ -105,9 +102,6 @@ private void Address(ushort addr) } } - private void Bank(int bank) - { - _romBank2K = bank & 0x0F; - } + private void Bank(int bank) => _romBank2K = bank & 0x0F; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Tia/TIA.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Tia/TIA.cs index 7282feeb78c..ef09b4325b1 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Tia/TIA.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Tia/TIA.cs @@ -32,7 +32,7 @@ public TIA(Atari2600 core, bool pal, bool secam) SetSecam(secam); CalcFrameRate(); - _spf = _vsyncNum / (double)_vsyncDen > 55.0 ? 735 : 882; + _spf = VsyncNumerator / (double)VsyncDenominator > 55.0 ? 735 : 882; } // indicates to the core where a new frame is starting @@ -142,7 +142,7 @@ public TIA(Atari2600 core, bool pal, bool secam) private HMoveData _hmove; private BallData _ball; - private readonly Audio AUD =new Audio(); + private readonly Audio AUD =new(); // current audio register state used to sample correct positions in the scanline (clrclk 0 and 114) public readonly short[] LocalAudioCycles = new short[2000]; @@ -166,14 +166,11 @@ private void CalcFrameRate() int clockrate = _pal ? 3546895 : 3579545; int clocksperframe = 228 * NominalNumScanlines; int gcd = (int)BigInteger.GreatestCommonDivisor(clockrate, clocksperframe); - _vsyncNum = clockrate / gcd; - _vsyncDen = clocksperframe / gcd; + VsyncNumerator = clockrate / gcd; + VsyncDenominator = clocksperframe / gcd; } - public void SetSecam(bool secam) - { - _palette = _pal ? secam ? SecamPalette : PALPalette : NTSCPalette; - } + public void SetSecam(bool secam) => _palette = _pal ? secam ? SecamPalette : PALPalette : NTSCPalette; public int CurrentScanLine => _currentScanLine; @@ -471,7 +468,7 @@ public void Execute() } // Assume we're on the left side of the screen for now - var rightSide = false; + bool rightSide = false; // ---- Things that happen only in the drawing section ---- // TODO: Remove this magic number (17). It depends on the HMOVE @@ -612,7 +609,7 @@ public void Execute() if (y < MaxScreenHeight) { int x = _hsyncCnt - 68; - if (x < 0 || x > 159) // this can't happen, right? + if (x is < 0 or > 159) // this can't happen, right? { throw new Exception(); // TODO } @@ -639,7 +636,7 @@ public void Execute() if (y < MaxScreenHeight) { int x = _hsyncCnt - 68; - if (x < 0 || x > 159) // this can't happen, right? + if (x is < 0 or > 159) // this can't happen, right? { throw new Exception(); // TODO } @@ -881,7 +878,7 @@ public void Execute() } // do the audio sampling - if (_hsyncCnt == 36 || _hsyncCnt == 148) + if (_hsyncCnt is 36 or 148) { if (AudioClocks < 2000) { @@ -933,7 +930,7 @@ private void OutputFrame(int validlines) public byte ReadMemory(ushort addr, bool peek) { - var maskedAddr = (ushort)(addr & 0x000F); + ushort maskedAddr = (ushort)(addr & 0x000F); byte coll = 0; int mask = 0xFF; @@ -1199,7 +1196,7 @@ public byte ReadMemory(ushort addr, bool peek) public void WriteMemory(ushort addr, byte value, bool poke) { - var maskedAddr = (ushort)(addr & 0x3f); + ushort maskedAddr = (ushort)(addr & 0x3f); if (!poke) { BusState = value; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Tia/Tia.Audio.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Tia/Tia.Audio.cs index ef4cfb364ef..5ea01c51d41 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Tia/Tia.Audio.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Tia/Tia.Audio.cs @@ -125,7 +125,7 @@ public short Cycle_L() Run5_L(); break; case 0x02: - if ((sr5_L == 31) || (sr5_L == 16)) + if (sr5_L is 31 or 16) { on_L = Run4_L(); } @@ -276,7 +276,7 @@ public short Cycle_R() Run5_R(); break; case 0x02: - if ((sr5_R == 31) || (sr5_R == 16)) + if (sr5_R is 31 or 16) { on_R = Run4_R(); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Tia/Tia.ISoundProvider.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Tia/Tia.ISoundProvider.cs index 95a73b0e56b..c1dab5d7f9f 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Tia/Tia.ISoundProvider.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Tia/Tia.ISoundProvider.cs @@ -25,15 +25,9 @@ public void GetSamplesSync(out short[] samples, out int nsamp) nsamp = _spf; } - public void GetSamplesAsync(short[] samples) - { - throw new NotSupportedException("Async is not available"); - } + public void GetSamplesAsync(short[] samples) => throw new NotSupportedException("Async is not available"); - public void DiscardSamples() - { - AudioClocks = 0; - } + public void DiscardSamples() => AudioClocks = 0; private readonly int _spf; @@ -43,7 +37,7 @@ private void GetSamples(short[] samples) { if (AudioClocks > 0) { - var samples31Khz = new short[AudioClocks]; // mono + short[] samples31Khz = new short[AudioClocks]; // mono for (int i = 0; i < AudioClocks; i++) { @@ -52,7 +46,7 @@ private void GetSamples(short[] samples) } // convert from 31khz to 44khz - for (var i = 0; i < samples.Length / 2; i++) + for (int i = 0; i < samples.Length / 2; i++) { samples[i * 2] = samples31Khz[(int)((samples31Khz.Length / (double)(samples.Length / 2)) * i)]; samples[(i * 2) + 1] = samples[i * 2]; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Tia/Tia.IVideoProvider.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Tia/Tia.IVideoProvider.cs index 9af6c5f9c12..07fdf69e992 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Tia/Tia.IVideoProvider.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Tia/Tia.IVideoProvider.cs @@ -4,10 +4,7 @@ namespace BizHawk.Emulation.Cores.Atari.Atari2600 { public partial class TIA : IVideoProvider { - public int[] GetVideoBuffer() - { - return _frameBuffer; - } + public int[] GetVideoBuffer() => _frameBuffer; public int VirtualWidth { @@ -39,13 +36,12 @@ public int BufferHeight } } - public int VsyncNumerator => _vsyncNum; + public int VsyncNumerator { get; private set; } - public int VsyncDenominator => _vsyncDen; + public int VsyncDenominator { get; private set; } public int BackgroundColor => _core.Settings.BackgroundColor.ToArgb(); private readonly int[] _frameBuffer = new int[ScreenWidth * MaxScreenHeight]; - private int _vsyncNum, _vsyncDen; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Tia/Tia.MissleData.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Tia/Tia.MissleData.cs index 2c9234be7f1..c6e617bed07 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Tia/Tia.MissleData.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Tia/Tia.MissleData.cs @@ -24,7 +24,7 @@ private struct MissileData public bool Tick() { - var result = false; + bool result = false; if (_scanCntInit) { @@ -78,7 +78,7 @@ public bool Tick() // our goal here is to send a start signal 4 clocks before drawing begins. The properly emulates // drawing on a real TIA - if (HPosCnt == 156 || HPosCnt == 12 || HPosCnt == 28 || HPosCnt == 60) + if (HPosCnt is 156 or 12 or 28 or 60) { _startSignal = HPosCnt; _signalReached = HPosCnt + 5; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Tia/Tia.PlayerData.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Tia/Tia.PlayerData.cs index 3d33f1426e9..a1a3a0dc37b 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Tia/Tia.PlayerData.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/2600/Tia/Tia.PlayerData.cs @@ -31,7 +31,7 @@ private struct PlayerData public bool Tick() { - var result = false; + bool result = false; if (ScanCnt < 8) { if (!ScanCntInit) @@ -168,7 +168,7 @@ public bool Tick() // our goal here is to send a start signal 4 clocks before drawing begins. This properly emulates // drawing on a real TIA - if (HPosCnt == 156 || HPosCnt == 12 || HPosCnt == 28 || HPosCnt == 60) + if (HPosCnt is 156 or 12 or 28 or 60) { _startSignal = HPosCnt - 1; _signalReached = HPosCnt + 5; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.IEmulator.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.IEmulator.cs index 80e0ba0a9bf..c43b9d4ab63 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.IEmulator.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.IEmulator.cs @@ -164,7 +164,7 @@ public void RunCPUCycle() tia._hsyncCnt++; tia._hsyncCnt %= 454; // do the audio sampling of TIA audio - if (tia._hsyncCnt == 113 || tia._hsyncCnt == 340) + if (tia._hsyncCnt is 113 or 340) { temp_s_tia = tia.Execute(); } @@ -364,14 +364,14 @@ public void apply_filter() } - public static readonly Dictionary ValidFilterTypes = new Dictionary + public static readonly Dictionary ValidFilterTypes = new() { { "None", "None"}, { "NTSC", "NTSC"}, { "Pal", "Pal"} }; - private BlipBuffer _blip = new BlipBuffer(4096); + private BlipBuffer _blip = new(4096); public bool CanProvideAsync => false; @@ -404,10 +404,7 @@ public void GetSamplesSync(out short[] samples, out int nsamp) temp = 0; } - public void GetSamplesAsync(short[] samples) - { - throw new NotSupportedException("Async is not available"); - } + public void GetSamplesAsync(short[] samples) => throw new NotSupportedException("Async is not available"); public void DiscardSamples() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.IMemoryDomains.cs index 42369d2cc8b..dc0388fd230 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.IMemoryDomains.cs @@ -9,7 +9,7 @@ public partial class A7800Hawk public void SetupMemoryDomains() { - var domains = new List + List domains = new() { new MemoryDomainDelegate( "Main RAM", diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.ISaveRam.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.ISaveRam.cs index 875dbcf8d3e..82a061c16fd 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.ISaveRam.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.ISaveRam.cs @@ -5,15 +5,9 @@ namespace BizHawk.Emulation.Cores.Atari.A7800Hawk { public partial class A7800Hawk : ISaveRam { - public byte[] CloneSaveRam() - { - return (byte[])_hsram.Clone(); - } + public byte[] CloneSaveRam() => (byte[])_hsram.Clone(); - public void StoreSaveRam(byte[] data) - { - Buffer.BlockCopy(data, 0, _hsram, 0, data.Length); - } + public void StoreSaveRam(byte[] data) => Buffer.BlockCopy(data, 0, _hsram, 0, data.Length); public bool SaveRamModified => (_hsbios != null); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.ISettable.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.ISettable.cs index 9ae394fe542..97f5f4acc67 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.ISettable.cs @@ -8,15 +8,9 @@ namespace BizHawk.Emulation.Cores.Atari.A7800Hawk { public partial class A7800Hawk : IEmulator, ISettable { - public A7800Settings GetSettings() - { - return _settings.Clone(); - } + public A7800Settings GetSettings() => _settings.Clone(); - public A7800SyncSettings GetSyncSettings() - { - return _syncSettings.Clone(); - } + public A7800SyncSettings GetSyncSettings() => _syncSettings.Clone(); public PutSettingsDirtyBits PutSettings(A7800Settings o) { @@ -31,15 +25,12 @@ public PutSettingsDirtyBits PutSyncSettings(A7800SyncSettings o) return ret ? PutSettingsDirtyBits.RebootCore : PutSettingsDirtyBits.None; } - private A7800Settings _settings = new A7800Settings(); - public A7800SyncSettings _syncSettings = new A7800SyncSettings(); + private A7800Settings _settings = new(); + public A7800SyncSettings _syncSettings = new(); public class A7800Settings { - public A7800Settings Clone() - { - return (A7800Settings)MemberwiseClone(); - } + public A7800Settings Clone() => (A7800Settings)MemberwiseClone(); public A7800Settings() { @@ -51,14 +42,9 @@ public class A7800SyncSettings { private string _port1 = A7800HawkControllerDeck.DefaultControllerName; private string _port2 = A7800HawkControllerDeck.DefaultControllerName; - private string _Filter = "None"; [JsonIgnore] - public string Filter - { - get => _Filter; - set => _Filter = value; - } + public string Filter { get; set; } = "None"; [JsonIgnore] public string Port1 @@ -90,20 +76,14 @@ public string Port2 } } - public A7800SyncSettings Clone() - { - return (A7800SyncSettings)MemberwiseClone(); - } + public A7800SyncSettings Clone() => (A7800SyncSettings)MemberwiseClone(); public A7800SyncSettings() { SettingsUtil.SetDefaultValues(this); } - public static bool NeedsReboot(A7800SyncSettings x, A7800SyncSettings y) - { - return !DeepEquality.DeepEquals(x, y); - } + public static bool NeedsReboot(A7800SyncSettings x, A7800SyncSettings y) => !DeepEquality.DeepEquals(x, y); } } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.cs index 38eca519572..d4118baaa30 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.cs @@ -55,7 +55,7 @@ internal static class RomChecksums public TIA tia; public Pokey pokey; - public struct CpuLink : IMOS6502XLink + public readonly struct CpuLink : IMOS6502XLink { private readonly A7800Hawk _a7800; @@ -64,21 +64,21 @@ public CpuLink(A7800Hawk a7800) _a7800 = a7800; } - public byte DummyReadMemory(ushort address) => _a7800.ReadMemory(address); + public readonly byte DummyReadMemory(ushort address) => _a7800.ReadMemory(address); - public void OnExecFetch(ushort address) => _a7800.ExecFetch(address); + public readonly void OnExecFetch(ushort address) => _a7800.ExecFetch(address); - public byte PeekMemory(ushort address) => _a7800.ReadMemory(address); + public readonly byte PeekMemory(ushort address) => _a7800.ReadMemory(address); - public byte ReadMemory(ushort address) => _a7800.ReadMemory(address); + public readonly byte ReadMemory(ushort address) => _a7800.ReadMemory(address); - public void WriteMemory(ushort address, byte value) => _a7800.WriteMemory(address, value); + public readonly void WriteMemory(ushort address, byte value) => _a7800.WriteMemory(address, value); } [CoreConstructor(VSystemID.Raw.A78)] public A7800Hawk(CoreComm comm, byte[] rom, A7800Hawk.A7800Settings settings, A7800Hawk.A7800SyncSettings syncSettings) { - var ser = new BasicServiceProvider(this); + BasicServiceProvider ser = new(this); maria = new Maria(); tia = new TIA(); @@ -98,9 +98,9 @@ public A7800Hawk(CoreComm comm, byte[] rom, A7800Hawk.A7800Settings settings, A7 _syncSettings = syncSettings ?? new A7800SyncSettings(); _controllerDeck = new A7800HawkControllerDeck(_syncSettings.Port1, _syncSettings.Port2); - var highscoreBios = comm.CoreFileProvider.GetFirmware(new("A78", "Bios_HSC"), "Some functions may not work without the high score BIOS."); - var palBios = comm.CoreFileProvider.GetFirmware(new("A78", "Bios_PAL"), "The game will not run if the correct region BIOS is not available."); - var ntscBios = comm.CoreFileProvider.GetFirmware(new("A78", "Bios_NTSC"), "The game will not run if the correct region BIOS is not available."); + byte[] highscoreBios = comm.CoreFileProvider.GetFirmware(new("A78", "Bios_HSC"), "Some functions may not work without the high score BIOS."); + byte[] palBios = comm.CoreFileProvider.GetFirmware(new("A78", "Bios_PAL"), "The game will not run if the correct region BIOS is not available."); + byte[] ntscBios = comm.CoreFileProvider.GetFirmware(new("A78", "Bios_NTSC"), "The game will not run if the correct region BIOS is not available."); byte[] header = new byte[128]; bool is_header = false; @@ -121,7 +121,7 @@ public A7800Hawk(CoreComm comm, byte[] rom, A7800Hawk.A7800Settings settings, A7 // if none found default is zero // also check for PAL region s_mapper = null; - var hash_md5 = MD5Checksum.ComputePrefixedHex(rom); + string hash_md5 = MD5Checksum.ComputePrefixedHex(rom); var gi = Database.CheckDatabase(hash_md5); @@ -136,26 +136,26 @@ public A7800Hawk(CoreComm comm, byte[] rom, A7800Hawk.A7800Settings settings, A7 if (!dict.TryGetValue("board", out s_mapper)) throw new Exception("No Board selected for this game"); // check if the game uses pokey or RAM - if (dict.TryGetValue("RAM", out var cartRAMStr)) + if (dict.TryGetValue("RAM", out string cartRAMStr)) { int.TryParse(cartRAMStr, out cart_RAM); } - if (dict.TryGetValue("Pokey", out var pokeyStr)) + if (dict.TryGetValue("Pokey", out string pokeyStr)) { bool.TryParse(pokeyStr, out is_pokey); } - if (dict.TryGetValue("Pokey_450", out var pokey450Str)) + if (dict.TryGetValue("Pokey_450", out string pokey450Str)) { bool.TryParse(pokey450Str, out is_pokey_450); } // some games will not function with the high score bios // if such a game is being played, tell the user and disable it - if (dict.TryGetValue("No_HS", out var noHSStr)) + if (dict.TryGetValue("No_HS", out string noHSStr)) { - bool.TryParse(noHSStr, out var no_hs); + bool.TryParse(noHSStr, out bool no_hs); if (no_hs) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800HawkControllerDeck.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800HawkControllerDeck.cs index c1303b569e4..b257f1e553c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800HawkControllerDeck.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800HawkControllerDeck.cs @@ -42,55 +42,25 @@ public A7800HawkControllerDeck(string controller1Name, string controller2Name) Definition.MakeImmutable(); } - public byte ReadPort1(IController c) - { - return Port1.Read(c); - } + public byte ReadPort1(IController c) => Port1.Read(c); - public byte ReadPort2(IController c) - { - return Port2.Read(c); - } + public byte ReadPort2(IController c) => Port2.Read(c); - public byte ReadFire1(IController c) - { - return Port1.ReadFire(c); - } + public byte ReadFire1(IController c) => Port1.ReadFire(c); - public byte ReadFire2(IController c) - { - return Port2.ReadFire(c); - } + public byte ReadFire2(IController c) => Port2.ReadFire(c); - public byte ReadFire1_2x(IController c) - { - return Port1.ReadFire2x(c); - } + public byte ReadFire1_2x(IController c) => Port1.ReadFire2x(c); - public byte ReadFire2_2x(IController c) - { - return Port2.ReadFire2x(c); - } + public byte ReadFire2_2x(IController c) => Port2.ReadFire2x(c); - public bool Is_2_button1(IController c) - { - return Port1.Is_2_button(c); - } + public bool Is_2_button1(IController c) => Port1.Is_2_button(c); - public bool Is_2_button2(IController c) - { - return Port2.Is_2_button(c); - } + public bool Is_2_button2(IController c) => Port2.Is_2_button(c); - public bool Is_LightGun1(IController c, out float lightgun_x, out float lightgun_y) - { - return Port1.Is_LightGun(c, out lightgun_x, out lightgun_y); - } + public bool Is_LightGun1(IController c, out float lightgun_x, out float lightgun_y) => Port1.Is_LightGun(c, out lightgun_x, out lightgun_y); - public bool Is_LightGun2(IController c, out float lightgun_x, out float lightgun_y) - { - return Port2.Is_LightGun(c, out lightgun_x, out lightgun_y); - } + public bool Is_LightGun2(IController c, out float lightgun_x, out float lightgun_y) => Port2.Is_LightGun(c, out lightgun_x, out lightgun_y); public ControllerDefinition Definition { get; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800HawkControllers.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800HawkControllers.cs index d1d63cc1bab..ad2281be76d 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800HawkControllers.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800HawkControllers.cs @@ -54,20 +54,11 @@ public byte Read(IController c) return result; } - public byte ReadFire(IController c) - { - return 0x80; - } + public byte ReadFire(IController c) => 0x80; - public byte ReadFire2x(IController c) - { - return 0; - } + public byte ReadFire2x(IController c) => 0; - public bool Is_2_button(IController c) - { - return false; - } + public bool Is_2_button(IController c) => false; public bool Is_LightGun(IController c, out float x, out float y) { @@ -136,15 +127,9 @@ public byte ReadFire(IController c) return result; } - public byte ReadFire2x(IController c) - { - return 0; // only applicable for 2 button mode - } + public byte ReadFire2x(IController c) => 0; // only applicable for 2 button mode - public bool Is_2_button(IController c) - { - return false; - } + public bool Is_2_button(IController c) => false; public bool Is_LightGun(IController c, out float x, out float y) { @@ -165,7 +150,7 @@ public void SyncState(Serializer ser) "Up", "Down", "Left", "Right", "Button" }; - private static byte[] HandControllerButtons = + private static readonly byte[] HandControllerButtons = { 0x0, // UP 0x0, // Down @@ -233,10 +218,7 @@ public byte ReadFire2x(IController c) return result; } - public bool Is_2_button(IController c) - { - return true; - } + public bool Is_2_button(IController c) => true; public bool Is_LightGun(IController c, out float x, out float y) { @@ -257,7 +239,7 @@ public void SyncState(Serializer ser) "Up", "Down", "Left", "Right", "Trigger", "Trigger 2" }; - private static byte[] HandControllerButtons = + private static readonly byte[] HandControllerButtons = { 0x0, // UP 0x0, // Down @@ -297,20 +279,11 @@ public byte Read(IController c) return result; } - public byte ReadFire(IController c) - { - return 0x80; - } + public byte ReadFire(IController c) => 0x80; - public byte ReadFire2x(IController c) - { - return 0; // only applicable for 2 button mode - } + public byte ReadFire2x(IController c) => 0; // only applicable for 2 button mode - public bool Is_2_button(IController c) - { - return false; - } + public bool Is_2_button(IController c) => false; public bool Is_LightGun(IController c, out float x, out float y) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/M6532.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/M6532.cs index 99aff809a2b..56bafb8e3fc 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/M6532.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/M6532.cs @@ -30,7 +30,7 @@ public byte ReadMemory(ushort addr, bool peek) return 0; } - var registerAddr = (ushort)(addr & 0x0007); + ushort registerAddr = (ushort)(addr & 0x0007); if (registerAddr == 0x00) { Core._isLag = false; @@ -114,7 +114,7 @@ public void WriteMemory(ushort addr, byte value) // If bit 0x0010 is set, and bit 0x0004 is set, this is a timer write if ((addr & 0x0014) == 0x0014) { - var registerAddr = (ushort)(addr & 0x0007); + ushort registerAddr = (ushort)(addr & 0x0007); // Bit 0x0080 contains interrupt enable/disable Timer.InterruptEnabled = (addr & 0x0080) != 0; @@ -159,7 +159,7 @@ public void WriteMemory(ushort addr, byte value) // these are register writes else if ((addr & 0x0004) == 0) { - var registerAddr = (ushort)(addr & 0x0007); + ushort registerAddr = (ushort)(addr & 0x0007); if (registerAddr == 0x00) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Mappers/MapperDefault.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Mappers/MapperDefault.cs index ff1a8897653..f48cbc0f40c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Mappers/MapperDefault.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Mappers/MapperDefault.cs @@ -8,7 +8,7 @@ public sealed class MapperDefault : MapperBase { public override byte ReadMemory(ushort addr) { - if (addr >=0x1000 && addr < 0x1800) + if (addr is >= 0x1000 and < 0x1800) { //could be hsbios RAM here if (Core._hsbios != null) @@ -53,7 +53,7 @@ public override byte ReadMemory(ushort addr) public override void WriteMemory(ushort addr, byte value) { - if (addr >= 0x1000 && addr < 0x1800) + if (addr is >= 0x1000 and < 0x1800) { //could be hsbios RAM here if (Core._hsbios != null) diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Mappers/MapperF18.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Mappers/MapperF18.cs index 07c6d81a44a..43ae3f2254b 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Mappers/MapperF18.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Mappers/MapperF18.cs @@ -10,7 +10,7 @@ public sealed class MapperF18 : MapperBase public override byte ReadMemory(ushort addr) { - if (addr >= 0x1000 && addr < 0x1800) + if (addr is >= 0x1000 and < 0x1800) { //could be hsbios RAM here if (Core._hsbios != null) @@ -53,7 +53,7 @@ public override byte ReadMemory(ushort addr) public override void WriteMemory(ushort addr, byte value) { - if (addr >= 0x1000 && addr < 0x1800) + if (addr is >= 0x1000 and < 0x1800) { //could be hsbios RAM here if (Core._hsbios != null) @@ -84,9 +84,6 @@ public override void WriteMemory(ushort addr, byte value) } } - public override void SyncState(Serializer ser) - { - ser.Sync("Bank", ref _bank); - } + public override void SyncState(Serializer ser) => ser.Sync("Bank", ref _bank); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Mappers/MapperFractalus.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Mappers/MapperFractalus.cs index ac374b13362..45fe2c8f37f 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Mappers/MapperFractalus.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Mappers/MapperFractalus.cs @@ -10,7 +10,7 @@ public sealed class MapperFractalus : MapperBase public override byte ReadMemory(ushort addr) { - if (addr >= 0x1000 && addr < 0x1800) + if (addr is >= 0x1000 and < 0x1800) { //could be hsbios RAM here if (Core._hsbios != null) @@ -45,7 +45,7 @@ public override byte ReadMemory(ushort addr) return Core._bios[addr - (0x10000 - Core._bios.Length)]; } - if (addr >= 0x4000 && addr <0x5000) + if (addr is >= 0x4000 and < 0x5000) { int tempRet1 = ((addr >> 8) & 0xE) >> 1; int tempRet2 = addr & 0xFF; @@ -58,7 +58,7 @@ public override byte ReadMemory(ushort addr) public override void WriteMemory(ushort addr, byte value) { - if (addr >= 0x1000 && addr < 0x1800) + if (addr is >= 0x1000 and < 0x1800) { //could be hsbios RAM here if (Core._hsbios != null) @@ -80,7 +80,7 @@ public override void WriteMemory(ushort addr, byte value) } else { - if (addr >= 0x4000 && addr < 0x5000) + if (addr is >= 0x4000 and < 0x5000) { int tempRet1 = ((addr >> 8) & 0xE) >> 1; int tempRet2 = addr & 0xFF; @@ -90,9 +90,6 @@ public override void WriteMemory(ushort addr, byte value) } } - public override void SyncState(Serializer ser) - { - ser.Sync(nameof(RAM), ref RAM, false); - } + public override void SyncState(Serializer ser) => ser.Sync(nameof(RAM), ref RAM, false); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Mappers/MapperRampage.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Mappers/MapperRampage.cs index 1d32848f816..9e710829218 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Mappers/MapperRampage.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Mappers/MapperRampage.cs @@ -10,7 +10,7 @@ public sealed class MapperRampage : MapperBase public override byte ReadMemory(ushort addr) { - if (addr >= 0x1000 && addr < 0x1800) + if (addr is >= 0x1000 and < 0x1800) { // could be hsbios RAM here if (Core._hsbios != null) @@ -48,25 +48,25 @@ public override byte ReadMemory(ushort addr) $a000-$dfff Banked */ int tempAddr; - if (addr >= 0x4000 && addr < 0x6000) + if (addr is >= 0x4000 and < 0x6000) { tempAddr = addr - 0x4000; return Core._rom[6 * 0x4000 + 0x2000 + tempAddr]; } - if (addr >= 0x6000 && addr < 0x8000) + if (addr is >= 0x6000 and < 0x8000) { tempAddr = addr - 0x6000; return Core._rom[6 * 0x4000 + tempAddr]; } - if (addr >= 0x8000 && addr < 0xA000) + if (addr is >= 0x8000 and < 0xA000) { tempAddr = addr - 0x8000; return Core._rom[7 * 0x4000 + 0x2000 + tempAddr]; } - if (addr >= 0xA000 && addr < 0xE000) + if (addr is >= 0xA000 and < 0xE000) { tempAddr = addr - 0xA000; return Core._rom[_bank * 0x4000 + tempAddr]; @@ -78,7 +78,7 @@ public override byte ReadMemory(ushort addr) public override void WriteMemory(ushort addr, byte value) { - if (addr >= 0x1000 && addr < 0x1800) + if (addr is >= 0x1000 and < 0x1800) { //could be hsbios RAM here if (Core._hsbios != null) @@ -101,16 +101,13 @@ public override void WriteMemory(ushort addr, byte value) else { // cartridge and other OPSYS - if (addr >= 0xFF80 && addr < 0xFF88) // might be other addresses, but only these are used + if (addr is >= 0xFF80 and < 0xFF88) // might be other addresses, but only these are used { _bank = (byte)(addr & 7); } } } - public override void SyncState(Serializer ser) - { - ser.Sync("Bank", ref _bank); - } + public override void SyncState(Serializer ser) => ser.Sync("Bank", ref _bank); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Mappers/MapperSG.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Mappers/MapperSG.cs index 231dc9d5c1b..57b194479ec 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Mappers/MapperSG.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Mappers/MapperSG.cs @@ -11,7 +11,7 @@ public sealed class MapperSG : MapperBase public override byte ReadMemory(ushort addr) { - if (addr >= 0x1000 && addr < 0x1800) + if (addr is >= 0x1000 and < 0x1800) { //could be hsbios RAM here if (Core._hsbios != null) @@ -108,7 +108,7 @@ public override byte ReadMemory(ushort addr) public override void WriteMemory(ushort addr, byte value) { - if (addr >= 0x1000 && addr < 0x1800) + if (addr is >= 0x1000 and < 0x1800) { //could be hsbios RAM here if (Core._hsbios != null) diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Mappers/MapperSGE.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Mappers/MapperSGE.cs index 5faa93f80f0..900635fb006 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Mappers/MapperSGE.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Mappers/MapperSGE.cs @@ -11,7 +11,7 @@ public sealed class MapperSGE : MapperBase public override byte ReadMemory(ushort addr) { - if (addr >= 0x1000 && addr < 0x1800) + if (addr is >= 0x1000 and < 0x1800) { //could be hsbios RAM here if (Core._hsbios != null) @@ -73,7 +73,7 @@ public override byte ReadMemory(ushort addr) public override void WriteMemory(ushort addr, byte value) { - if (addr >= 0x1000 && addr < 0x1800) + if (addr is >= 0x1000 and < 0x1800) { //could be hsbios RAM here if (Core._hsbios != null) @@ -111,9 +111,6 @@ public override void WriteMemory(ushort addr, byte value) } } - public override void SyncState(Serializer ser) - { - ser.Sync("Bank", ref _bank); - } + public override void SyncState(Serializer ser) => ser.Sync("Bank", ref _bank); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/MemoryMap.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/MemoryMap.cs index ce6a6cb15f5..6e243ec9d09 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/MemoryMap.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/MemoryMap.cs @@ -61,43 +61,43 @@ public byte ReadMemory(ushort addr) return RAM_6532[addr & 0x7F]; } - if ((addr >= 0x1800) && (addr < 0x2800)) + if (addr is >= 0x1800 and < 0x2800) { return RAM[addr -0x1800]; } - if ((addr >= 0x40) && (addr < 0x100)) + if (addr is >= 0x40 and < 0x100) { // RAM block 0 return RAM[addr - 0x40 + 0x840]; } - if ((addr >= 0x140) && (addr < 0x200)) + if (addr is >= 0x140 and < 0x200) { // RAM block 1 return RAM[addr - 0x140 + 0x940]; } - if ((addr >= 0x2800) && (addr < 0x3000)) + if (addr is >= 0x2800 and < 0x3000) { // this mirror evidently does not exist on hardware despite being in the documentation // must return 0 or Summer Games will deadlock at event start screen return 0x0;// RAM[(addr & 0x7FF) + 0x800]; } - if ((addr >= 0x3000) && (addr < 0x4000)) + if (addr is >= 0x3000 and < 0x4000) { // could be either RAM mirror or ROM return mapper.ReadMemory(addr); } - if ((addr >= 0x400) && (addr < 0x480)) + if (addr is >= 0x400 and < 0x480) { // cartridge space available return mapper.ReadMemory(addr); } - if ((addr >= 0x500) && (addr < 0x1800)) + if (addr is >= 0x500 and < 0x1800) { // cartridge space available return mapper.ReadMemory(addr); @@ -132,7 +132,7 @@ public void WriteMemory(ushort addr, byte value) if ((A7800_control_register & 0x2) > 0) { // register 8 is read only and controlled by Maria - var temp = addr & 0x1F; + int temp = addr & 0x1F; if (temp != 8) Maria_regs[temp] = value; @@ -163,36 +163,36 @@ public void WriteMemory(ushort addr, byte value) slow_access = true; RAM_6532[addr & 0x7F] = value; } - else if ((addr >= 0x1800) && (addr < 0x2800)) + else if (addr is >= 0x1800 and < 0x2800) { RAM[addr - 0x1800] = value; } - else if ((addr >= 0x40) && (addr < 0x100)) + else if (addr is >= 0x40 and < 0x100) { // RAM block 0 RAM[addr - 0x40 + 0x840] = value; } - else if ((addr >= 0x140) && (addr < 0x200)) + else if (addr is >= 0x140 and < 0x200) { // RAM block 1 RAM[addr - 0x140 + 0x940] = value; } - else if ((addr >= 0x2800) && (addr < 0x3000)) + else if (addr is >= 0x2800 and < 0x3000) { // this mirror evidently does not exist on hardware despite being in the documentation //RAM[(addr & 0x7FF) + 0x800] = value; } - else if ((addr >= 0x3000) && (addr < 0x4000)) + else if (addr is >= 0x3000 and < 0x4000) { // could be either RAM mirror or ROM mapper.WriteMemory(addr, value); } - else if ((addr >= 0x400) && (addr < 0x480)) + else if (addr is >= 0x400 and < 0x480) { // cartridge space available mapper.WriteMemory(addr, value); } - else if ((addr >= 0x500) && (addr < 0x1800)) + else if (addr is >= 0x500 and < 0x1800) { // cartridge space available mapper.WriteMemory(addr, value); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Pokey.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Pokey.cs index c60fef40c05..bc7f5d0ec19 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Pokey.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Pokey.cs @@ -224,7 +224,7 @@ public void Tick() ch_out[i] = poly5.Bit(16); } } - else if (((Regs[i * 2 + 1] & 0xF0) == 0x20) || ((Regs[i * 2 + 1] & 0xF0) == 0x60)) + else if ((Regs[i * 2 + 1] & 0xF0) is 0x20 or 0x60) { // 5 bit poly //if (ch_src[i]) diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/TIA_Sound/TIA.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/TIA_Sound/TIA.cs index 9fbd6aff076..1ab82b27b73 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/TIA_Sound/TIA.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/TIA_Sound/TIA.cs @@ -43,7 +43,7 @@ public int Execute() public byte ReadMemory(ushort addr, bool peek) { - var maskedAddr = (ushort)(addr & 0x000F); + ushort maskedAddr = (ushort)(addr & 0x000F); if (maskedAddr == 0x00) // CXM0P { @@ -196,7 +196,7 @@ public byte ReadMemory(ushort addr, bool peek) public void WriteMemory(ushort addr, byte value, bool poke) { - var maskedAddr = (ushort)(addr & 0x3f); + ushort maskedAddr = (ushort)(addr & 0x3f); if (!poke) { BusState = value; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/TIA_Sound/Tia.Audio.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/TIA_Sound/Tia.Audio.cs index e060c0ac1e4..0fde310f433 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/TIA_Sound/Tia.Audio.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/TIA_Sound/Tia.Audio.cs @@ -120,7 +120,7 @@ public short Cycle() Run5(); break; case 0x02: - if ((sr5 == 31) || (sr5 == 16)) + if (sr5 is 31 or 16) { on = Run4(); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/jaguar/JaguarDisassembler.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/jaguar/JaguarDisassembler.cs index 73b68a44ea2..fab1f3bdaaa 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/jaguar/JaguarDisassembler.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/jaguar/JaguarDisassembler.cs @@ -24,9 +24,9 @@ public string DisassembleM68K(MemoryDomain m, uint addr, out int length) // most of this is taken from virtualjaguar's dasmjag function public string DisassembleRISC(bool gpu, MemoryDomain m, uint addr, out int length) { - var opcode = m.PeekUshort(addr & 0xFFFFFF, true); - var arg1 = (opcode >> 5) & 0x1F; - var arg2 = opcode & 0x1F; + ushort opcode = m.PeekUshort(addr & 0xFFFFFF, true); + int arg1 = (opcode >> 5) & 0x1F; + int arg2 = opcode & 0x1F; length = (opcode >> 10) == 0x26 ? 6 : 2; string argRR() => $"r{arg1}, r{arg2}"; @@ -35,7 +35,7 @@ public string DisassembleRISC(bool gpu, MemoryDomain m, uint addr, out int lengt string argR2() => $"r{arg2}"; string argSR() { - var s1 = (short)(arg1 << 11) >> 11; + int s1 = (short)(arg1 << 11) >> 11; if (s1 < 0) { return $"-${-s1:X02}, r{arg2}"; @@ -75,7 +75,7 @@ string argCC() }; } - var disasm = (opcode >> 10) switch + string disasm = (opcode >> 10) switch { 0x00 => $"add {argRR()}", 0x01 => $"addc {argRR()}", diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/jaguar/VirtualJaguar.IDebuggable.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/jaguar/VirtualJaguar.IDebuggable.cs index 3b80276e415..215f1686a5b 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/jaguar/VirtualJaguar.IDebuggable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/jaguar/VirtualJaguar.IDebuggable.cs @@ -14,7 +14,7 @@ public unsafe IDictionary GetCpuFlagsAndRegisters() uint* regs = stackalloc uint[18 + 32 + 32 + 32 + 32 + 2]; _core.GetRegisters((IntPtr)regs); - var ret = new Dictionary(); + Dictionary ret = new(); // M68K data regs for (int i = 0; i < 8; i++) { @@ -47,13 +47,13 @@ public void SetCpuRegister(string register, int value) register = register.ToUpperInvariant(); if (register.StartsWithOrdinal("M68K ")) { - var reg = Enum.Parse(typeof(LibVirtualJaguar.M68KRegisters), register.Remove(0, 5)); + object reg = Enum.Parse(typeof(LibVirtualJaguar.M68KRegisters), register.Remove(0, 5)); _core.SetRegister((int)reg, value); } else if (register.StartsWithOrdinal("GPU ") || register.StartsWithOrdinal("DSP ")) { bool gpu = register.StartsWithOrdinal("GPU "); - var regName = register.Remove(0, 4); + string regName = register.Remove(0, 4); if (regName == "PC") { @@ -61,8 +61,8 @@ public void SetCpuRegister(string register, int value) } else if (regName.StartsWith('R')) { - var offset = gpu ? 18 : 82; - var reg = int.Parse(regName.Remove(0, 1)); + int offset = gpu ? 18 : 82; + int reg = int.Parse(regName.Remove(0, 1)); if (reg > 63) { throw new ArgumentException("Invalid register", nameof(register)); @@ -103,7 +103,7 @@ private void InitMemoryCallbacks() { LibVirtualJaguar.MemoryCallback CreateCallback(MemoryCallbackFlags flags, Func getHasCBOfType) { - var rawFlags = (uint)flags; + uint rawFlags = (uint)flags; return address => { if (getHasCBOfType()) diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/jaguar/VirtualJaguar.ISettable.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/jaguar/VirtualJaguar.ISettable.cs index cffcd096ec0..0889dbefbba 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/jaguar/VirtualJaguar.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/jaguar/VirtualJaguar.ISettable.cs @@ -25,7 +25,7 @@ public VirtualJaguarSyncSettings GetSyncSettings() public PutSettingsDirtyBits PutSyncSettings(VirtualJaguarSyncSettings o) { - var ret = VirtualJaguarSyncSettings.NeedsReboot(_syncSettings, o); + bool ret = VirtualJaguarSyncSettings.NeedsReboot(_syncSettings, o); _syncSettings = o; return ret ? PutSettingsDirtyBits.RebootCore : PutSettingsDirtyBits.None; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/jaguar/VirtualJaguar.ITraceable.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/jaguar/VirtualJaguar.ITraceable.cs index a713d025e5a..131069d2c22 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/jaguar/VirtualJaguar.ITraceable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/jaguar/VirtualJaguar.ITraceable.cs @@ -13,20 +13,20 @@ public partial class VirtualJaguar private unsafe void MakeCPUTrace(IntPtr r) { - var regs = (uint*)r; - var pc = regs![16] & 0xFFFFFF; - var disasm = _disassembler.DisassembleM68K(this.AsMemoryDomains().SystemBus, pc, out _); - var regInfo = new StringBuilder(216); - for (var i = 0; i < 8; i++) + uint* regs = (uint*)r; + uint pc = regs![16] & 0xFFFFFF; + string disasm = _disassembler.DisassembleM68K(this.AsMemoryDomains().SystemBus, pc, out _); + StringBuilder regInfo = new(216); + for (int i = 0; i < 8; i++) { regInfo.Append($"D{i}:{regs[i]:X8} "); } - for (var i = 0; i < 8; i++) + for (int i = 0; i < 8; i++) { regInfo.Append($"A{i}:{regs[i + 8]:X8} "); } regInfo.Append($"SR:{regs[17]:X8} "); - var sr = regs[17]; + uint sr = regs[17]; regInfo.Append(string.Concat( (sr & 16) > 0 ? "X" : "x", (sr & 8) > 0 ? "N" : "n", @@ -40,11 +40,11 @@ private unsafe void MakeCPUTrace(IntPtr r) private unsafe void MakeGPUTrace(uint pc, IntPtr r) { - var regs = (uint*)r; + uint* regs = (uint*)r; pc &= 0xFFFFFF; - var disasm = _disassembler.DisassembleRISC(true, this.AsMemoryDomains().SystemBus, pc, out _); - var regInfo = new StringBuilder(411); - for (var i = 0; i < 32; i++) + string disasm = _disassembler.DisassembleRISC(true, this.AsMemoryDomains().SystemBus, pc, out _); + StringBuilder regInfo = new(411); + for (int i = 0; i < 32; i++) { regInfo.Append($"r{i}:{regs![i]:X8} "); } @@ -55,11 +55,11 @@ private unsafe void MakeGPUTrace(uint pc, IntPtr r) private unsafe void MakeDSPTrace(uint pc, IntPtr r) { - var regs = (uint*)r; + uint* regs = (uint*)r; pc &= 0xFFFFFF; - var disasm = _disassembler.DisassembleRISC(false, this.AsMemoryDomains().SystemBus, pc, out _); - var regInfo = new StringBuilder(411); - for (var i = 0; i < 32; i++) + string disasm = _disassembler.DisassembleRISC(false, this.AsMemoryDomains().SystemBus, pc, out _); + StringBuilder regInfo = new(411); + for (int i = 0; i < 32; i++) { regInfo.Append($"r{i}:{regs![i]:X8} "); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/jaguar/VirtualJaguar.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/jaguar/VirtualJaguar.cs index 77fb6dbd874..724b4b77239 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/jaguar/VirtualJaguar.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/jaguar/VirtualJaguar.cs @@ -67,9 +67,9 @@ public VirtualJaguar(CoreLoadParameters throw new InvalidOperationException(), }; - var bios = Zstd.DecompressZstdStream(new MemoryStream(brev.Value)).ToArray(); + byte[] bios = Zstd.DecompressZstdStream(new MemoryStream(brev.Value)).ToArray(); - var settings = new LibVirtualJaguar.Settings + LibVirtualJaguar.Settings settings = new() { NTSC = _syncSettings.NTSC, UseBIOS = !_syncSettings.SkipBIOS, @@ -84,7 +84,7 @@ public VirtualJaguar(CoreLoadParameters + List mms = new() { new MemoryDomainIntPtr("RAM", MemoryDomain.Endian.Little, LibLynx.GetRamPointer(Core), 65536, true, 2) }; - if (LibLynx.GetSaveRamPtr(Core, out var s, out var p)) + if (LibLynx.GetSaveRamPtr(Core, out int s, out var p)) { mms.Add(new MemoryDomainIntPtr("Save RAM", MemoryDomain.Endian.Little, p, s, true, 2)); } - LibLynx.GetReadOnlyCartPtrs(Core, out var s0, out var p0, out var s1, out var p1); + LibLynx.GetReadOnlyCartPtrs(Core, out int s0, out var p0, out int s1, out var p1); if (s0 > 0 && p0 != IntPtr.Zero) { mms.Add(new MemoryDomainIntPtr("Cart A", MemoryDomain.Endian.Little, p0, s0, false, 2)); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/lynx/Lynx.ISaveRam.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/lynx/Lynx.ISaveRam.cs index 3cbb9d79755..eac9a58f6a1 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/lynx/Lynx.ISaveRam.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/lynx/Lynx.ISaveRam.cs @@ -9,7 +9,7 @@ public partial class Lynx : ISaveRam { public byte[] CloneSaveRam() { - if (!LibLynx.GetSaveRamPtr(Core, out var size, out var data)) + if (!LibLynx.GetSaveRamPtr(Core, out int size, out var data)) { return null; } @@ -21,7 +21,7 @@ public byte[] CloneSaveRam() public void StoreSaveRam(byte[] srcData) { - if (!LibLynx.GetSaveRamPtr(Core, out var size, out var data)) + if (!LibLynx.GetSaveRamPtr(Core, out int size, out var data)) { throw new InvalidOperationException(); } @@ -31,6 +31,6 @@ public void StoreSaveRam(byte[] srcData) Marshal.Copy(srcData, 0, data, size); } - public bool SaveRamModified => LibLynx.GetSaveRamPtr(Core, out int unused, out IntPtr unused2); + public bool SaveRamModified => LibLynx.GetSaveRamPtr(Core, out int unused, out var unused2); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/lynx/Lynx.ISoundProvider.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/lynx/Lynx.ISoundProvider.cs index dcae3ea27fb..182b793ff5c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/lynx/Lynx.ISoundProvider.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/lynx/Lynx.ISoundProvider.cs @@ -31,9 +31,6 @@ public void SetSyncMode(SyncSoundMode mode) public SyncSoundMode SyncMode => SyncSoundMode.Sync; - public void GetSamplesAsync(short[] samples) - { - throw new InvalidOperationException("Async mode is not supported."); - } + public void GetSamplesAsync(short[] samples) => throw new InvalidOperationException("Async mode is not supported."); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/lynx/Lynx.IStatable.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/lynx/Lynx.IStatable.cs index adfff454786..4a43a63ca2c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/lynx/Lynx.IStatable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/lynx/Lynx.IStatable.cs @@ -12,7 +12,7 @@ public partial class Lynx : ITextStatable public void SaveStateText(TextWriter writer) { - var s = new TextState(); + TextState s = new(); s.Prepare(); var ff = s.GetFunctionPointersSave(); LibLynx.TxtStateSave(Core, ref ff); @@ -25,7 +25,7 @@ public void SaveStateText(TextWriter writer) public void LoadStateText(TextReader reader) { - var s = (TextState)_ser.Deserialize(reader, typeof(TextState)); + TextState s = (TextState)_ser.Deserialize(reader, typeof(TextState)); s.Prepare(); var ff = s.GetFunctionPointersLoad(); LibLynx.TxtStateLoad(Core, ref ff); @@ -70,7 +70,7 @@ public void LoadStateBinary(BinaryReader reader) Frame = reader.ReadInt32(); } - private readonly JsonSerializer _ser = new JsonSerializer { Formatting = Formatting.Indented }; + private readonly JsonSerializer _ser = new() { Formatting = Formatting.Indented }; private readonly byte[] _saveBuff; private class TextStateData diff --git a/src/BizHawk.Emulation.Cores/Consoles/Atari/lynx/Lynx.cs b/src/BizHawk.Emulation.Cores/Consoles/Atari/lynx/Lynx.cs index efc725ef3dc..18995721891 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Atari/lynx/Lynx.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Atari/lynx/Lynx.cs @@ -17,7 +17,7 @@ public partial class Lynx : IEmulator, IVideoProvider, ISoundProvider, ISaveRam, static Lynx() { - var resolver = new DynamicLibraryImportResolver( + DynamicLibraryImportResolver resolver = new( OSTailoredCode.IsUnixHost ? "libbizlynx.dll.so" : "bizlynx.dll", hasLimitedLifetime: false); LibLynx = BizInvoker.GetInvoker(resolver, CallingConventionAdapters.Native); } @@ -27,7 +27,7 @@ public Lynx(byte[] file, GameInfo game, CoreComm comm) { ServiceProvider = new BasicServiceProvider(this); - var bios = comm.CoreFileProvider.GetFirmwareOrThrow(new("Lynx", "Boot"), "Boot rom is required"); + byte[] bios = comm.CoreFileProvider.GetFirmwareOrThrow(new("Lynx", "Boot"), "Boot rom is required"); if (bios.Length != 512) { throw new MissingFirmwareException("Lynx Bootrom must be 512 bytes!"); @@ -38,8 +38,8 @@ public Lynx(byte[] file, GameInfo game, CoreComm comm) byte[] realfile = null; { - using var ms = new MemoryStream(file, false); - using var br = new BinaryReader(ms); + using MemoryStream ms = new(file, false); + using BinaryReader br = new(ms); string header = Encoding.ASCII.GetString(br.ReadBytes(4)); int p0 = br.ReadUInt16(); int p1 = br.ReadUInt16(); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Belogic/Uzem.cs b/src/BizHawk.Emulation.Cores/Consoles/Belogic/Uzem.cs index a5fa6049cff..2ea174450c0 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Belogic/Uzem.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Belogic/Uzem.cs @@ -9,7 +9,7 @@ namespace BizHawk.Emulation.Cores.Consoles.Belogic [PortedCore(CoreNames.Uzem, "David Etherton")] public class Uzem : WaterboxCore { - private LibUzem _uze; + private readonly LibUzem _uze; private readonly bool _mouseEnabled; [CoreConstructor(VSystemID.Raw.UZE)] @@ -73,7 +73,7 @@ private static int EncodePad(IController c, int p) int ret = unchecked((int)0xffff0000); int val = 1; int idx = 0; - foreach (var s in PadBits) + foreach (string s in PadBits) { if (c.IsPressed("P" + p + " " + PadBits[idx++])) ret |= val; @@ -113,7 +113,7 @@ private static int EncodeDelta(float value) protected override LibWaterboxCore.FrameInfo FrameAdvancePrep(IController controller, bool render, bool rendersound) { - var ret = new LibUzem.FrameInfo(); + LibUzem.FrameInfo ret = new(); if (_mouseEnabled) { ret.ButtonsP1 = EncodeDelta(controller.AxisValue("P1 Mouse X")) << 24 diff --git a/src/BizHawk.Emulation.Cores/Consoles/Coleco/AY_3_8910_SGM.cs b/src/BizHawk.Emulation.Cores/Consoles/Coleco/AY_3_8910_SGM.cs index 92bafc6595b..9568b25a051 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Coleco/AY_3_8910_SGM.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Coleco/AY_3_8910_SGM.cs @@ -29,10 +29,7 @@ public void Reset() sync_psg_state(); } - public short Sample() - { - return current_sample; - } + public short Sample() => current_sample; private static readonly int[] VolumeTable = { @@ -84,10 +81,7 @@ public void SyncState(Serializer ser) ser.EndSection(); } - public byte ReadReg() - { - return Register[port_sel]; - } + public byte ReadReg() => Register[port_sel]; private void sync_psg_state() { @@ -130,7 +124,7 @@ private void sync_psg_state() noise_per = 0x20; } - var shape_select = Register[13] & 0xF; + int shape_select = Register[13] & 0xF; if (shape_select < 4) env_shape = 0; @@ -161,7 +155,7 @@ public void WriteReg(byte value) { env_clock = env_per; - if (env_shape == 0 || env_shape == 2 || env_shape == 3 || env_shape == 4 || env_shape == 5) + if (env_shape is 0 or 2 or 3 or 4 or 5) { env_E = 15; E_up_down = -1; @@ -209,21 +203,21 @@ public void generate_sound(int cycles_to_do) env_E += E_up_down; - if (env_E == 16 || env_E == -1) + if (env_E is 16 or (-1)) { // we just completed a period of the envelope, determine what to do now based on the envelope shape - if (env_shape == 0 || env_shape == 1 || env_shape == 3 || env_shape == 9) + if (env_shape is 0 or 1 or 3 or 9) { E_up_down = 0; env_E = 0; } - else if (env_shape == 5 || env_shape == 7) + else if (env_shape is 5 or 7) { E_up_down = 0; env_E = 15; } - else if (env_shape == 4 || env_shape == 8) + else if (env_shape is 4 or 8) { if (env_E == 16) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Coleco/ColecoControllers.cs b/src/BizHawk.Emulation.Cores/Consoles/Coleco/ColecoControllers.cs index 76fe74d9e67..2b41436918c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Coleco/ColecoControllers.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Coleco/ColecoControllers.cs @@ -32,10 +32,7 @@ public UnpluggedController(int portNum) Definition = new("(ColecoVision Basic Controller fragment)"); } - public byte Read(IController c, bool leftMode, bool updateWheel, float wheelAngle) - { - return 0x7F; // needs checking - } + public byte Read(IController c, bool leftMode, bool updateWheel, float wheelAngle) => 0x7F; // needs checking public ControllerDefinition Definition { get; } @@ -145,7 +142,7 @@ public byte Read(IController c, bool leftMode, bool updateWheel, float wheelAngl float x = c.AxisValue(Definition.Axes[0]); float y = c.AxisValue(Definition.Axes[1]); - var angle = updateWheel ? wheelAngle : CalcDirection(x, y); + float angle = updateWheel ? wheelAngle : CalcDirection(x, y); byte temp2 = 0; @@ -247,7 +244,7 @@ public byte Read(IController c, bool left_mode, bool updateWheel, float wheelAng float x = c.AxisValue(Definition.Axes[0]); float y = c.AxisValue(Definition.Axes[1]); - var angle = updateWheel ? wheelAngle : CalcDirection(x, y); + float angle = updateWheel ? wheelAngle : CalcDirection(x, y); byte temp2 = 0; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Coleco/ColecoVision.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Consoles/Coleco/ColecoVision.IMemoryDomains.cs index 3ded4d582b5..71e0f0327d2 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Coleco/ColecoVision.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Coleco/ColecoVision.IMemoryDomains.cs @@ -9,12 +9,12 @@ namespace BizHawk.Emulation.Cores.ColecoVision public partial class ColecoVision { private MemoryDomainList _memoryDomains; - private readonly Dictionary _byteArrayDomains = new Dictionary(); + private readonly Dictionary _byteArrayDomains = new(); private bool _memoryDomainsInit = false; private void SetupMemoryDomains() { - var domains = new List + List domains = new() { new MemoryDomainDelegate("System Bus", 0x10000, MemoryDomain.Endian.Little, addr => @@ -31,10 +31,10 @@ private void SetupMemoryDomains() if (use_SGM) { - var SGMLRam = new MemoryDomainByteArray("SGM Low RAM", MemoryDomain.Endian.Little, SGM_low_RAM, true, 1); + MemoryDomainByteArray SGMLRam = new("SGM Low RAM", MemoryDomain.Endian.Little, SGM_low_RAM, true, 1); domains.Add(SGMLRam); - var SGMHRam = new MemoryDomainByteArray("SGM High RAM", MemoryDomain.Endian.Little, SGM_high_RAM, true, 1); + MemoryDomainByteArray SGMHRam = new("SGM High RAM", MemoryDomain.Endian.Little, SGM_high_RAM, true, 1); domains.Add(SGMHRam); } @@ -61,7 +61,7 @@ private void SyncByteArrayDomain(string name, byte[] data) } else { - var m = new MemoryDomainByteArray(name, MemoryDomain.Endian.Little, data, true, 1); + MemoryDomainByteArray m = new(name, MemoryDomain.Endian.Little, data, true, 1); _byteArrayDomains.Add(name, m); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Coleco/ColecoVision.ISettable.cs b/src/BizHawk.Emulation.Cores/Consoles/Coleco/ColecoVision.ISettable.cs index 83d7352afe6..5ea1353dbb1 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Coleco/ColecoVision.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Coleco/ColecoVision.ISettable.cs @@ -8,15 +8,9 @@ namespace BizHawk.Emulation.Cores.ColecoVision { public partial class ColecoVision : IEmulator, ISettable { - public ColecoSettings GetSettings() - { - return _settings.Clone(); - } + public ColecoSettings GetSettings() => _settings.Clone(); - public ColecoSyncSettings GetSyncSettings() - { - return _syncSettings.Clone(); - } + public ColecoSyncSettings GetSyncSettings() => _syncSettings.Clone(); public PutSettingsDirtyBits PutSettings(ColecoSettings o) { @@ -34,14 +28,11 @@ public PutSettingsDirtyBits PutSyncSettings(ColecoSyncSettings o) public class ColecoSettings { - public ColecoSettings Clone() - { - return (ColecoSettings)MemberwiseClone(); - } + public ColecoSettings Clone() => (ColecoSettings)MemberwiseClone(); } - private ColecoSettings _settings = new ColecoSettings(); - private ColecoSyncSettings _syncSettings = new ColecoSyncSettings(); + private ColecoSettings _settings = new(); + private ColecoSyncSettings _syncSettings = new(); public class ColecoSyncSettings { @@ -81,15 +72,9 @@ public string Port2 } } - public ColecoSyncSettings Clone() - { - return (ColecoSyncSettings)MemberwiseClone(); - } + public ColecoSyncSettings Clone() => (ColecoSyncSettings)MemberwiseClone(); - public static bool NeedsReboot(ColecoSyncSettings x, ColecoSyncSettings y) - { - return !DeepEquality.DeepEquals(x, y); - } + public static bool NeedsReboot(ColecoSyncSettings x, ColecoSyncSettings y) => !DeepEquality.DeepEquals(x, y); } } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Coleco/ColecoVision.ISoundProvider.cs b/src/BizHawk.Emulation.Cores/Consoles/Coleco/ColecoVision.ISoundProvider.cs index 9d906296a29..03c1e906cf2 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Coleco/ColecoVision.ISoundProvider.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Coleco/ColecoVision.ISoundProvider.cs @@ -9,7 +9,7 @@ public partial class ColecoVision : ISoundProvider private readonly SN76489col PSG; private readonly AY_3_8910_SGM SGM_sound; - private readonly BlipBuffer _blip = new BlipBuffer(4096); + private readonly BlipBuffer _blip = new(4096); public void DiscardSamples() { @@ -17,10 +17,7 @@ public void DiscardSamples() _sampleClock = 0; } - public void GetSamplesAsync(short[] samples) - { - throw new NotSupportedException("Async is not available"); - } + public void GetSamplesAsync(short[] samples) => throw new NotSupportedException("Async is not available"); public bool CanProvideAsync => false; @@ -50,10 +47,7 @@ public void GetSamplesSync(out short[] samples, out int nsamp) } } - public void GetSamples(short[] samples) - { - throw new Exception(); - } + public void GetSamples(short[] samples) => throw new Exception(); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Coleco/ColecoVision.IStatable.cs b/src/BizHawk.Emulation.Cores/Consoles/Coleco/ColecoVision.IStatable.cs index 1bf5876a357..62cce269b16 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Coleco/ColecoVision.IStatable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Coleco/ColecoVision.IStatable.cs @@ -11,7 +11,7 @@ private void SyncState(Serializer ser) byte[] core = null; if (ser.IsWriter) { - using var ms = new MemoryStream(); + using MemoryStream ms = new(); ms.Close(); core = ms.ToArray(); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Coleco/ColecoVision.cs b/src/BizHawk.Emulation.Cores/Consoles/Coleco/ColecoVision.cs index 232400c1783..3c1de0039ba 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Coleco/ColecoVision.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Coleco/ColecoVision.cs @@ -13,7 +13,7 @@ public ColecoVision(CoreComm comm, GameInfo game, byte[] rom, ColecoSettings settings, ColecoSyncSettings syncSettings) { - var ser = new BasicServiceProvider(this); + BasicServiceProvider ser = new(this); ServiceProvider = ser; _syncSettings = syncSettings ?? new ColecoSyncSettings(); bool skipBios = _syncSettings.SkipBiosIntro; @@ -116,7 +116,7 @@ private byte ReadPort(ushort port) { port &= 0xFF; - if (port >= 0xA0 && port < 0xC0) + if (port is >= 0xA0 and < 0xC0) { if ((port & 1) == 0) { @@ -166,7 +166,7 @@ private void WritePort(ushort port, byte value) { port &= 0xFF; - if (port >= 0xA0 && port <= 0xBF) + if (port is >= 0xA0 and <= 0xBF) { if ((port & 1) == 0) { @@ -180,13 +180,13 @@ private void WritePort(ushort port, byte value) return; } - if (port >= 0x80 && port <= 0x9F) + if (port is >= 0x80 and <= 0x9F) { _inputPortSelection = InputPortMode.Right; return; } - if (port >= 0xC0 && port <= 0xDF) + if (port is >= 0xC0 and <= 0xDF) { _inputPortSelection = InputPortMode.Left; return; @@ -343,14 +343,14 @@ private void WriteMemory(ushort addr, byte value) { if (!enable_SGM_high) { - if (addr >= 0x6000 && addr < 0x8000) + if (addr is >= 0x6000 and < 0x8000) { _ram[addr & 1023] = value; } } else { - if (addr >= 0x2000 && addr < 0x8000) + if (addr is >= 0x2000 and < 0x8000) { SGM_high_RAM[addr - 0x2000] = value; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Coleco/SN76489col.cs b/src/BizHawk.Emulation.Cores/Consoles/Coleco/SN76489col.cs index fa6238f0e8c..faea40e2b40 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Coleco/SN76489col.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Coleco/SN76489col.cs @@ -42,10 +42,7 @@ public void Reset() noise = 0x40000; } - public int Sample() - { - return current_sample; - } + public int Sample() => current_sample; public void SyncState(Serializer ser) { @@ -77,11 +74,9 @@ public void SyncState(Serializer ser) ser.EndSection(); } - public byte ReadReg() - { + public byte ReadReg() => // not used, reading not allowed, just return 0xFF - return 0xFF; - } + 0xFF; public void WriteReg(byte value) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Coleco/TMS9918A.cs b/src/BizHawk.Emulation.Cores/Consoles/Coleco/TMS9918A.cs index b6c3b14e368..51de25df8f8 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Coleco/TMS9918A.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Coleco/TMS9918A.cs @@ -1,4 +1,4 @@ -using System; +using System; using BizHawk.Common; using BizHawk.Emulation.Common; @@ -25,7 +25,9 @@ public sealed class TMS9918A : IVideoProvider private bool EnableLargeSprites => (Registers[1] & 2) > 0; public bool EnableInterrupts => (Registers[1] & 32) > 0; private bool DisplayOn => (Registers[1] & 64) > 0; + #pragma warning disable IDE0051 private bool Mode16k => (Registers[1] & 128) > 0; + #pragma warning restore IDE0051 public bool InterruptPending { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Audio.cs b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Audio.cs index 39ec65e9aa2..57cea863c1f 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Audio.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Audio.cs @@ -1,4 +1,4 @@ -using System; +using System; using BizHawk.Emulation.Common; namespace BizHawk.Emulation.Cores.Consoles.ChannelF @@ -17,13 +17,13 @@ public partial class ChannelF : ISoundProvider private int tone = 0; private readonly double[] tone_freqs = { 0, 1000, 500, 120 }; -#pragma warning disable CS0414 +#pragma warning disable CS0414,IDE0051 private double amplitude = 0; - private double decay = 0.998; + private readonly double decay = 0.998; private double time = 0; - private double cycles = 0; + private readonly double cycles = 0; private int samplePos = 0; -#pragma warning restore CS0414 +#pragma warning restore CS0414,IDE0051 private int lastCycle = 0; private BlipBuffer _blip; @@ -75,10 +75,7 @@ public void SetSyncMode(SyncSoundMode mode) throw new InvalidOperationException("Only Sync mode is supported."); } - public void GetSamplesAsync(short[] samples) - { - throw new NotSupportedException("Async is not available"); - } + public void GetSamplesAsync(short[] samples) => throw new NotSupportedException("Async is not available"); public void DiscardSamples() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Cart/VesCartBase.cs b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Cart/VesCartBase.cs index 402673173a2..f6dcac74a73 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Cart/VesCartBase.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Cart/VesCartBase.cs @@ -7,24 +7,21 @@ namespace BizHawk.Emulation.Cores.Consoles.ChannelF { public abstract class VesCartBase { - public abstract string BoardType { get; } + public abstract string BoardType { get; } - public virtual void SyncByteArrayDomain(ChannelF sys) - { - sys.SyncByteArrayDomain("ROM", _rom); - } + public virtual void SyncByteArrayDomain(ChannelF sys) => sys.SyncByteArrayDomain("ROM", _rom); public virtual byte[] ROM { - get { return _rom; } - protected set { _rom = value; } + get => _rom; + protected set => _rom = value; } protected byte[] _rom; public virtual byte[] RAM { - get { return _ram; } - protected set { _ram = value; } + get => _ram; + protected set => _ram = value; } protected byte[] _ram; @@ -49,27 +46,16 @@ public static VesCartBase Configure(GameInfo gi, byte[] rom) // get board type string boardStr = gi.OptionPresent("board") ? gi.GetStringValue("board") : "STD"; - switch (boardStr) + return boardStr switch { // standard cart layout - case "STD": - // any number of F3851 Program Storage Units (1KB ROM each) or F3856 Program Storage Unit (2KB ROM) - // no on-pcb RAM and no extra IO - return new mapper_STD(rom); - - case "MAZE": - return new mapper_MAZE(rom); - - case "SCHACH": - default: - // F3853 Memory Interface Chip, 6KB of ROM and 2KB of RAM - // - default to this - return new mapper_SCHACH(rom); - - case "HANG": - - return new mapper_HANG(rom); - } + "STD" => new mapper_STD(rom),// any number of F3851 Program Storage Units (1KB ROM each) or F3856 Program Storage Unit (2KB ROM) + // no on-pcb RAM and no extra IO + "MAZE" => new mapper_MAZE(rom), + "HANG" => new mapper_HANG(rom), + _ => new mapper_SCHACH(rom),// F3853 Memory Interface Chip, 6KB of ROM and 2KB of RAM + // - default to this + }; } /// @@ -130,7 +116,7 @@ public void SRAM2102_Write(int index, byte data) // notice that data is 8bits, so when swapping bit8 & bit9 are always 0! //m_addr_latch = (m_addr_latch & 0x0c) | (bitswap < 16 > ((uint16_t)data, 15, 14, 13, 12, 11, 10, 7, 6, 5, 3, 2, 1, 9, 8, 4, 0)); - BitArray b = new BitArray(16); + BitArray b = new(16); b[3] = false;// data.Bit(3); b[2] = false; // data.Bit(2); @@ -146,7 +132,7 @@ public void SRAM2102_Write(int index, byte data) b[0] = data.Bit(0); - var resBytes = new byte[4]; + byte[] resBytes = new byte[4]; b.CopyTo(resBytes, 0); m_addr_latch = (ushort)(resBytes[0] | resBytes[1] << 8); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Cart/mapper_HANG.cs b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Cart/mapper_HANG.cs index 15816c65c79..d14ba2e6c0f 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Cart/mapper_HANG.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Cart/mapper_HANG.cs @@ -16,7 +16,7 @@ public mapper_HANG(byte[] rom) ROM[i] = rom[i]; if (i > 3000) { - var test = rom[i]; + byte test = rom[i]; } } @@ -25,7 +25,7 @@ public mapper_HANG(byte[] rom) public override byte ReadBus(ushort addr) { - var off = addr - 0x800; + int off = addr - 0x800; return ROM[off]; } @@ -36,13 +36,13 @@ public override void WriteBus(ushort addr, byte value) public override byte ReadPort(ushort addr) { - var index = addr - 0x20; + int index = addr - 0x20; return SRAM2102_Read(index); } public override void WritePort(ushort addr, byte data) { - var index = addr - 0x20; + int index = addr - 0x20; SRAM2102_Write(index, data); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Cart/mapper_MAZE.cs b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Cart/mapper_MAZE.cs index 391a84cc1ce..58e8420011c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Cart/mapper_MAZE.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Cart/mapper_MAZE.cs @@ -20,7 +20,7 @@ public mapper_MAZE(byte[] rom) public override byte ReadBus(ushort addr) { - var off = addr - 0x800; + int off = addr - 0x800; return ROM[off]; } @@ -31,13 +31,13 @@ public override void WriteBus(ushort addr, byte value) public override byte ReadPort(ushort addr) { - var index = addr - 0x24; + int index = addr - 0x24; return SRAM2102_Read(index); } public override void WritePort(ushort addr, byte data) { - var index = addr - 0x24; + int index = addr - 0x24; SRAM2102_Write(index, data); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Cart/mapper_SCHACH.cs b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Cart/mapper_SCHACH.cs index 35a527d44ff..02067341c27 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Cart/mapper_SCHACH.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Cart/mapper_SCHACH.cs @@ -22,10 +22,10 @@ public mapper_SCHACH(byte[] rom) public override byte ReadBus(ushort addr) { - var result = 0xFF; - var off = addr - 0x800; + int result = 0xFF; + int off = addr - 0x800; - if (addr >= 0x2800 && addr < 0x3000) + if (addr is >= 0x2800 and < 0x3000) { // 2KB RAM result = RAM[addr - 0x2800]; @@ -42,7 +42,7 @@ public override byte ReadBus(ushort addr) public override void WriteBus(ushort addr, byte value) { // 2KB writeable memory at 0x2800; - if (addr >= 0x2800 && addr < 0x3000) + if (addr is >= 0x2800 and < 0x3000) { RAM[addr - 0x2800] = value; } @@ -57,10 +57,7 @@ public override void WriteBus(ushort addr, byte value) } } - public override byte ReadPort(ushort addr) - { - return 0xFF; - } + public override byte ReadPort(ushort addr) => 0xFF; public override void WritePort(ushort addr, byte data) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Cart/mapper_STD.cs b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Cart/mapper_STD.cs index 93ddc4d7869..ed67961fc7c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Cart/mapper_STD.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Cart/mapper_STD.cs @@ -21,7 +21,7 @@ public mapper_STD(byte[] rom) public override byte ReadBus(ushort addr) { - var off = addr - 0x800; + int off = addr - 0x800; if (off < ROM.Length) return ROM[off]; else @@ -33,10 +33,7 @@ public override void WriteBus(ushort addr, byte value) // no writeable memory } - public override byte ReadPort(ushort addr) - { - return 0xFF; - } + public override byte ReadPort(ushort addr) => 0xFF; public override void WritePort(ushort addr, byte data) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/ChannelF.Controllers.cs b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/ChannelF.Controllers.cs index b546b3f7f86..7b4d8931559 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/ChannelF.Controllers.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/ChannelF.Controllers.cs @@ -14,13 +14,13 @@ public ControllerDefinition ChannelFControllerDefinition string pre = "P1 "; // sticks - var stickR = new List + List stickR = new() { // P1 (right) stick pre + "Forward", pre + "Back", pre + "Left", pre + "Right", pre + "CCW", pre + "CW", pre + "Pull", pre + "Push" }; - foreach (var s in stickR) + foreach (string s in stickR) { definition.BoolButtons.Add(s); definition.CategoryLabels[s] = "Right Controller"; @@ -28,25 +28,25 @@ public ControllerDefinition ChannelFControllerDefinition pre = "P2 "; - var stickL = new List + List stickL = new() { // P2 (left) stick pre + "Forward", pre + "Back", pre + "Left", pre + "Right", pre + "CCW", pre + "CW", pre + "Pull", pre + "Push" }; - foreach (var s in stickL) + foreach (string s in stickL) { definition.BoolButtons.Add(s); definition.CategoryLabels[s] = "Left Controller"; } // console - var consoleButtons = new List + List consoleButtons = new() { "TIME", "MODE", "HOLD", "START", "RESET" }; - foreach (var s in consoleButtons) + foreach (string s in consoleButtons) { definition.BoolButtons.Add(s); definition.CategoryLabels[s] = "Console"; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/ChannelF.IEmulator.cs b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/ChannelF.IEmulator.cs index 1eeaa8fa1a3..121dae66f9d 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/ChannelF.IEmulator.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/ChannelF.IEmulator.cs @@ -20,7 +20,7 @@ public partial class ChannelF : IEmulator private void CalcClock() { - var c = ((cpuFreq * 1000000) / refreshRate); + double c = ((cpuFreq * 1000000) / refreshRate); ClockPerFrame = (int) c; SetupAudio(); @@ -29,7 +29,7 @@ private void CalcClock() public bool FrameAdvance(IController controller, bool render, bool renderSound) { _controller = controller; - _isLag = true; + IsLagFrame = true; if (_tracer.IsEnabled()) { @@ -48,15 +48,13 @@ public bool FrameAdvance(IController controller, bool render, bool renderSound) PollInput(); FrameClock = 0; - _frame++; + Frame++; - if (_isLag) - _lagCount++; + if (IsLagFrame) + LagCount++; return true; } - - private int _frame; #pragma warning disable CS0414 //private int _lagcount; //private bool _islag; @@ -64,12 +62,12 @@ public bool FrameAdvance(IController controller, bool render, bool renderSound) public void ResetCounters() { - _frame = 0; - _lagCount = 0; - _isLag = false; + Frame = 0; + LagCount = 0; + IsLagFrame = false; } - public int Frame => _frame; + public int Frame { get; private set; } public void Dispose() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/ChannelF.ISettable.cs b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/ChannelF.ISettable.cs index cbb0ff2eedb..5de2d028016 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/ChannelF.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/ChannelF.ISettable.cs @@ -6,18 +6,12 @@ namespace BizHawk.Emulation.Cores.Consoles.ChannelF { public partial class ChannelF : ISettable { - internal ChannelFSettings Settings = new ChannelFSettings(); - internal ChannelFSyncSettings SyncSettings = new ChannelFSyncSettings(); + internal ChannelFSettings Settings = new(); + internal ChannelFSyncSettings SyncSettings = new(); - public ChannelFSettings GetSettings() - { - return Settings.Clone(); - } + public ChannelFSettings GetSettings() => Settings.Clone(); - public ChannelFSyncSettings GetSyncSettings() - { - return SyncSettings.Clone(); - } + public ChannelFSyncSettings GetSyncSettings() => SyncSettings.Clone(); public PutSettingsDirtyBits PutSettings(ChannelFSettings o) { @@ -39,10 +33,7 @@ public class ChannelFSettings [DefaultValue(0)] public int BackgroundColor { get; set; } - public ChannelFSettings Clone() - { - return (ChannelFSettings)MemberwiseClone(); - } + public ChannelFSettings Clone() => (ChannelFSettings)MemberwiseClone(); public ChannelFSettings() { @@ -61,20 +52,14 @@ public class ChannelFSyncSettings [DefaultValue(RegionType.NTSC)] public RegionType Region { get; set; } - public ChannelFSyncSettings Clone() - { - return (ChannelFSyncSettings) MemberwiseClone(); - } + public ChannelFSyncSettings Clone() => (ChannelFSyncSettings)MemberwiseClone(); public ChannelFSyncSettings() { SettingsUtil.SetDefaultValues(this); } - public static bool NeedsReboot(ChannelFSyncSettings x, ChannelFSyncSettings y) - { - return !DeepEquality.DeepEquals(x, y); - } + public static bool NeedsReboot(ChannelFSyncSettings x, ChannelFSyncSettings y) => !DeepEquality.DeepEquals(x, y); } public enum RegionType diff --git a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/ChannelF.IVideoProvider.cs b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/ChannelF.IVideoProvider.cs index 630e86d2e0d..9b4e11ed5dc 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/ChannelF.IVideoProvider.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/ChannelF.IVideoProvider.cs @@ -46,14 +46,14 @@ private void BuildFrame() for (int r = 0; r < 64; r++) { // lines - var p1 = (VRAM[(r * 0x80) + 125]) & 0x03; - var p2 = (VRAM[(r * 0x80) + 126]) & 0x03; - var pOffset = ((p2 & 0x02) | (p1 >> 1)) << 2; + int p1 = (VRAM[(r * 0x80) + 125]) & 0x03; + int p2 = (VRAM[(r * 0x80) + 126]) & 0x03; + int pOffset = ((p2 & 0x02) | (p1 >> 1)) << 2; for (int c = 0; c < 128; c++) { // columns - var colourIndex = pOffset + (VRAM[c | (r << 7)] & 0x03); + int colourIndex = pOffset + (VRAM[c | (r << 7)] & 0x03); frameBuffer[(r << 7) + c] = CMap[colourIndex]; } } @@ -74,12 +74,12 @@ public int[] GetVideoBuffer() { BuildFrame(); - var lBorderWidth = 4; - var rBorderWidth = 128 - 102 - lBorderWidth; - var tBorderHeight = 4; - var bBorderHeight = 64 - 58 - tBorderHeight; - var startP = 128 * tBorderHeight; - var endP = 128 * bBorderHeight; + int lBorderWidth = 4; + int rBorderWidth = 128 - 102 - lBorderWidth; + int tBorderHeight = 4; + int bBorderHeight = 64 - 58 - tBorderHeight; + int startP = 128 * tBorderHeight; + int endP = 128 * bBorderHeight; int index = 0; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/ChannelF.InputPollable.cs b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/ChannelF.InputPollable.cs index e4ce1a40f34..9368adf3c65 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/ChannelF.InputPollable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/ChannelF.InputPollable.cs @@ -4,23 +4,12 @@ namespace BizHawk.Emulation.Cores.Consoles.ChannelF { public partial class ChannelF : IInputPollable { - public int LagCount - { - get => _lagCount; - set => _lagCount = value; - } + public int LagCount { get; set; } = 0; - public bool IsLagFrame - { - get => _isLag; - set => _isLag = value; - } + public bool IsLagFrame { get; set; } = false; public IInputCallbackSystem InputCallbacks { get; } = new InputCallbackSystem(); - private int _lagCount = 0; - private bool _isLag = false; - /// /// Cycles through all the input callbacks /// This should be done once per frame @@ -35,7 +24,7 @@ public bool PollInput() { for (int i = 0; i < ButtonsConsole.Length; i++) { - var key = ButtonsConsole[i]; + string key = ButtonsConsole[i]; bool prevState = StateConsole[i]; // CTRLConsole.Bit(i); bool currState = _controller.IsPressed(key); if (currState != prevState) @@ -57,7 +46,7 @@ public bool PollInput() for (int i = 0; i < ButtonsRight.Length; i++) { - var key = "P1 " + ButtonsRight[i]; + string key = "P1 " + ButtonsRight[i]; bool prevState = StateRight[i]; bool currState = _controller.IsPressed(key); if (currState != prevState) @@ -69,7 +58,7 @@ public bool PollInput() for (int i = 0; i < ButtonsLeft.Length; i++) { - var key = "P2 " + ButtonsLeft[i]; + string key = "P2 " + ButtonsLeft[i]; bool prevState = StateLeft[i]; bool currState = _controller.IsPressed(key); if (currState != prevState) diff --git a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/ChannelF.MemoryDomains.cs b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/ChannelF.MemoryDomains.cs index f77585ee8e0..b7a6043c1cd 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/ChannelF.MemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/ChannelF.MemoryDomains.cs @@ -8,12 +8,12 @@ namespace BizHawk.Emulation.Cores.Consoles.ChannelF public partial class ChannelF { internal IMemoryDomains memoryDomains; - private readonly Dictionary _byteArrayDomains = new Dictionary(); + private readonly Dictionary _byteArrayDomains = new(); private bool _memoryDomainsInit = false; private void SetupMemoryDomains() { - var domains = new List + List domains = new() { new MemoryDomainDelegate("System Bus", 0x10000, MemoryDomain.Endian.Big, (addr) => @@ -55,7 +55,7 @@ public void SyncByteArrayDomain(string name, byte[] data) } else { - var m = new MemoryDomainByteArray(name, MemoryDomain.Endian.Big, data, false, 1); + MemoryDomainByteArray m = new(name, MemoryDomain.Endian.Big, data, false, 1); _byteArrayDomains.Add(name, m); } #pragma warning restore MEN014 diff --git a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/ChannelF.cs b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/ChannelF.cs index ddc8206bdde..b5ecbaa4aaa 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/ChannelF.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/ChannelF.cs @@ -11,7 +11,7 @@ public partial class ChannelF : IDriveLight [CoreConstructor(VSystemID.Raw.ChannelF)] public ChannelF(CoreLoadParameters lp) { - var ser = new BasicServiceProvider(this); + BasicServiceProvider ser = new(this); ServiceProvider = ser; CoreComm = lp.Comm; _gameInfo = lp.Roms.Select(r => r.Game).ToList(); @@ -28,8 +28,8 @@ public ChannelF(CoreLoadParameters lp) ControllerDefinition = ChannelFControllerDefinition; - var bios01 = CoreComm.CoreFileProvider.GetFirmwareOrThrow(new("ChannelF", "ChannelF_sl131253")); - var bios02 = CoreComm.CoreFileProvider.GetFirmwareOrThrow(new("ChannelF", "ChannelF_sl131254")); + byte[] bios01 = CoreComm.CoreFileProvider.GetFirmwareOrThrow(new("ChannelF", "ChannelF_sl131253")); + byte[] bios02 = CoreComm.CoreFileProvider.GetFirmwareOrThrow(new("ChannelF", "ChannelF_sl131254")); //var bios02 = CoreComm.CoreFileProvider.GetFirmwareOrThrow(new("ChannelF", "ChannelF_sl90025")); Cartridge = VesCartBase.Configure(_gameInfo[0], _files[0]); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Memory.cs b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Memory.cs index 2025dd96923..cbe609815a1 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Memory.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Memory.cs @@ -37,9 +37,6 @@ public byte ReadBus(ushort addr) /// Channel F addressable through the address space) /// /// - public void WriteBus(ushort addr, byte value) - { - Cartridge.WriteBus(addr, value); - } + public void WriteBus(ushort addr, byte value) => Cartridge.WriteBus(addr, value); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Ports.cs b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Ports.cs index de6c30f28d8..55b80788b0b 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Ports.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Ports.cs @@ -27,7 +27,7 @@ public partial class ChannelF /// public byte ReadPort(ushort addr) { - var result = 0xFF; + int result = 0xFF; switch (addr) { @@ -39,7 +39,7 @@ public byte ReadPort(ushort addr) // b3: START // RESET button is connected directly to the RST pin on the CPU (this is handled here in the PollInput() method) result = (~DataConsole & 0x0F) | OutputLatch[addr]; - _isLag = false; + IsLagFrame = false; break; case 1: @@ -51,9 +51,9 @@ public byte ReadPort(ushort addr) // b3: FORWARD // b4: CCW // b5: CW - var v1 = LS368Enable ? DataRight : DataRight | 0xC0; + int v1 = LS368Enable ? DataRight : DataRight | 0xC0; result = (~v1) | OutputLatch[addr]; - _isLag = false; + IsLagFrame = false; break; case 4: @@ -68,10 +68,10 @@ public byte ReadPort(ushort addr) // b5: CW // b6: PULL // b7: PUSH - var v2 = LS368Enable ? DataLeft : 0xFF; + int v2 = LS368Enable ? DataLeft : 0xFF; result = (~v2) | OutputLatch[addr]; if (LS368Enable) - _isLag = false; + IsLagFrame = false; break; case 5: @@ -119,7 +119,7 @@ public void WritePort(ushort addr, byte value) case 5: OutputLatch[addr] = value; latch_y = (value | 0xC0) ^ 0xFF; - var audio = ((value ^ 0xFF) >> 6) & 0x03; + int audio = ((value ^ 0xFF) >> 6) & 0x03; if (audio != tone) { tone = audio; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Video.cs b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Video.cs index 33bbce1a1f9..2147bef5b51 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Video.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Fairchild/ChannelF/Video.cs @@ -1,10 +1,11 @@ -namespace BizHawk.Emulation.Cores.Consoles.ChannelF +namespace BizHawk.Emulation.Cores.Consoles.ChannelF { /// /// Video related functions /// public partial class ChannelF { + #pragma warning disable IDE0051 private void BuildFrame1() { // rows @@ -12,10 +13,10 @@ private void BuildFrame1() for (int row = 0; row < 64; row++) { // columns 125 and 126 hold the palette index modifier for the entire row - var rIndex = 128 * row; - var c125 = (VRAM[rIndex + 125] & 0x03); - var c126 = (VRAM[rIndex + 126] & 0x03); - var pModifier = (((c126 & 0x02) | c125 >> 1) << 2); + int rIndex = 128 * row; + int c125 = (VRAM[rIndex + 125] & 0x03); + int c126 = (VRAM[rIndex + 126] & 0x03); + int pModifier = (((c126 & 0x02) | c125 >> 1) << 2); pModifier = ((VRAM[(row << 7) + 125] & 2) >> 1) | (VRAM[(row << 7) + 126] & 3); pModifier = (pModifier << 2) & 0xc; @@ -30,5 +31,6 @@ private void BuildFrame1() } } } + #pragma warning restore IDE0051 } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/Audio.cs b/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/Audio.cs index 5eaf9b2e2ee..d9500c5b3fa 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/Audio.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/Audio.cs @@ -1,4 +1,4 @@ -using System; +using System; using BizHawk.Common; using BizHawk.Emulation.Common; @@ -11,7 +11,7 @@ public class Audio : ISoundProvider { public VectrexHawk Core { get; set; } - private BlipBuffer _blip = new BlipBuffer(15000); + private BlipBuffer _blip = new(15000); public uint master_audio_clock; @@ -24,10 +24,7 @@ public class Audio : ISoundProvider public byte port_sel; - public short Sample() - { - return current_sample; - } + public short Sample() => current_sample; private static readonly int[] VolumeTable = { @@ -85,10 +82,7 @@ public void SyncState(Serializer ser) ser.EndSection(); } - public byte ReadReg(int addr) - { - return Register[port_sel]; - } + public byte ReadReg(int addr) => Register[port_sel]; private void sync_psg_state() { @@ -131,7 +125,7 @@ private void sync_psg_state() noise_per = 0x20; } - var shape_select = Register[13] & 0xF; + int shape_select = Register[13] & 0xF; if (shape_select < 4) env_shape = 0; @@ -165,7 +159,7 @@ public void WriteReg(int addr, byte value) { env_clock = env_per; - if (env_shape == 0 || env_shape == 2 || env_shape == 3 || env_shape == 4 || env_shape == 5) + if (env_shape is 0 or 2 or 3 or 4 or 5) { env_E = 15; E_up_down = -1; @@ -212,21 +206,21 @@ public void tick() env_E += E_up_down; - if (env_E == 16 || env_E == -1) + if (env_E is 16 or (-1)) { // we just completed a period of the envelope, determine what to do now based on the envelope shape - if (env_shape == 0 || env_shape == 1 || env_shape == 3 || env_shape == 9) + if (env_shape is 0 or 1 or 3 or 9) { E_up_down = 0; env_E = 0; } - else if (env_shape == 5 || env_shape == 7) + else if (env_shape is 5 or 7) { E_up_down = 0; env_E = 15; } - else if (env_shape == 4 || env_shape == 8) + else if (env_shape is 4 or 8) { if (env_E == 16) { @@ -361,10 +355,7 @@ public void GetSamplesSync(out short[] samples, out int nsamp) master_audio_clock = 0; } - public void GetSamplesAsync(short[] samples) - { - throw new NotSupportedException("Async is not available"); - } + public void GetSamplesAsync(short[] samples) => throw new NotSupportedException("Async is not available"); public void DiscardSamples() { @@ -372,10 +363,12 @@ public void DiscardSamples() master_audio_clock = 0; } + #pragma warning disable IDE0051 private void GetSamples(short[] samples) { } + #pragma warning restore IDE0051 public void DisposeSound() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/Mappers/MapperBase.cs b/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/Mappers/MapperBase.cs index 3ed82196834..b41ad84e345 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/Mappers/MapperBase.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/Mappers/MapperBase.cs @@ -9,15 +9,9 @@ public class MapperBase public int bank; - public virtual byte ReadMemory(ushort addr) - { - return 0; - } + public virtual byte ReadMemory(ushort addr) => 0; - public virtual byte PeekMemory(ushort addr) - { - return 0; - } + public virtual byte PeekMemory(ushort addr) => 0; public virtual void WriteMemory(ushort addr, byte value) { @@ -27,10 +21,7 @@ public virtual void PokeMemory(ushort addr, byte value) { } - public virtual void SyncState(Serializer ser) - { - ser.Sync(nameof(bank), ref bank); - } + public virtual void SyncState(Serializer ser) => ser.Sync(nameof(bank), ref bank); public virtual void Dispose() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/Mappers/Mapper_64K.cs b/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/Mappers/Mapper_64K.cs index 9ecc5efcbeb..b2a26fedd8e 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/Mappers/Mapper_64K.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/Mappers/Mapper_64K.cs @@ -4,29 +4,17 @@ // make sure peekmemory and poke memory don't effect the rest of the system! public class Mapper_64K : MapperBase { - public override void Initialize() - { - bank = 0; - } + public override void Initialize() => bank = 0; - public override byte ReadMemory(ushort addr) - { - return Core._rom[addr + bank * 0x8000]; - } + public override byte ReadMemory(ushort addr) => Core._rom[addr + bank * 0x8000]; - public override byte PeekMemory(ushort addr) - { - return ReadMemory(addr); - } + public override byte PeekMemory(ushort addr) => ReadMemory(addr); public override void WriteMemory(ushort addr, byte value) { } - public override void PokeMemory(ushort addr, byte value) - { - WriteMemory(addr, value); - } + public override void PokeMemory(ushort addr, byte value) => WriteMemory(addr, value); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/Mappers/Mapper_Default.cs b/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/Mappers/Mapper_Default.cs index 9203ad35afa..0cee7543cec 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/Mappers/Mapper_Default.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/Mappers/Mapper_Default.cs @@ -9,24 +9,15 @@ public override void Initialize() // nothing to initialize } - public override byte ReadMemory(ushort addr) - { - return Core._rom[addr]; - } + public override byte ReadMemory(ushort addr) => Core._rom[addr]; - public override byte PeekMemory(ushort addr) - { - return ReadMemory(addr); - } + public override byte PeekMemory(ushort addr) => ReadMemory(addr); public override void WriteMemory(ushort addr, byte value) { } - public override void PokeMemory(ushort addr, byte value) - { - WriteMemory(addr, value); - } + public override void PokeMemory(ushort addr, byte value) => WriteMemory(addr, value); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/SerialPort.cs b/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/SerialPort.cs index 45169eb2896..36c4ec4cc9c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/SerialPort.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/SerialPort.cs @@ -6,10 +6,7 @@ public class SerialPort { public VectrexHawk Core { get; set; } - public byte ReadReg(int addr) - { - return 0xFF; - } + public byte ReadReg(int addr) => 0xFF; public void WriteReg(int addr, byte value) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/VectrexHawk.ICodeDataLog.cs b/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/VectrexHawk.ICodeDataLog.cs index f8670541312..f08d0ac6057 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/VectrexHawk.ICodeDataLog.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/VectrexHawk.ICodeDataLog.cs @@ -7,10 +7,7 @@ namespace BizHawk.Emulation.Cores.Consoles.Vectrex { public sealed partial class VectrexHawk : ICodeDataLogger { - public void SetCDL(ICodeDataLog cdl) - { - CDL = cdl; - } + public void SetCDL(ICodeDataLog cdl) => CDL = cdl; public void NewCDL(ICodeDataLog cdl) { @@ -40,7 +37,7 @@ private enum CDLog_Flags Data = 0x04 } -#pragma warning disable CS0649 +#pragma warning disable CS0649,IDE0051 private struct CDLog_MapResults { public CDLog_AddrType Type; @@ -48,15 +45,14 @@ private struct CDLog_MapResults } private delegate CDLog_MapResults MapMemoryDelegate(ushort addr, bool write); - private MapMemoryDelegate MapMemory; -#pragma warning restore CS0649 + private readonly MapMemoryDelegate MapMemory; private ICodeDataLog CDL; private void RunCDL(ushort address, CDLog_Flags flags) { if (MapMemory != null) { - CDLog_MapResults results = MapMemory(address, false); + var results = MapMemory(address, false); switch (results.Type) { case CDLog_AddrType.None: break; @@ -84,4 +80,5 @@ private byte ReadMemory_CDL(ushort address) return ReadMemory(address); } } +#pragma warning restore CS0649,IDE0051 } \ No newline at end of file diff --git a/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/VectrexHawk.IEmulator.cs b/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/VectrexHawk.IEmulator.cs index cd7936b0ebe..56e300d64ef 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/VectrexHawk.IEmulator.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/VectrexHawk.IEmulator.cs @@ -108,20 +108,14 @@ public void ResetCounters() _islag = false; } - public void Dispose() - { - audio.DisposeSound(); - } + public void Dispose() => audio.DisposeSound(); public int _frameHz = 50; public int[] _vidbuffer; public int[] _framebuffer; - public int[] GetVideoBuffer() - { - return _framebuffer; - } + public int[] GetVideoBuffer() => _framebuffer; public void get_video_frame() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/VectrexHawk.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/VectrexHawk.IMemoryDomains.cs index 3606d69e0a2..bceedcff745 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/VectrexHawk.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/VectrexHawk.IMemoryDomains.cs @@ -10,7 +10,7 @@ public partial class VectrexHawk public void SetupMemoryDomains() { - var domains = new List + List domains = new() { new MemoryDomainDelegate( "Main RAM", diff --git a/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/VectrexHawk.ISaveRam.cs b/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/VectrexHawk.ISaveRam.cs index aec02239739..7f07ccc9305 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/VectrexHawk.ISaveRam.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/VectrexHawk.ISaveRam.cs @@ -4,10 +4,7 @@ namespace BizHawk.Emulation.Cores.Consoles.Vectrex { public partial class VectrexHawk : ISaveRam { - public byte[] CloneSaveRam() - { - return null; - } + public byte[] CloneSaveRam() => null; public void StoreSaveRam(byte[] data) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/VectrexHawk.ISettable.cs b/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/VectrexHawk.ISettable.cs index d99bef72d92..fb291933b30 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/VectrexHawk.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/VectrexHawk.ISettable.cs @@ -11,10 +11,7 @@ public partial class VectrexHawk : IEmulator, ISettable _settings; - public VectrexSyncSettings GetSyncSettings() - { - return _syncSettings.Clone(); - } + public VectrexSyncSettings GetSyncSettings() => _syncSettings.Clone(); public PutSettingsDirtyBits PutSettings(object o) { @@ -29,8 +26,8 @@ public PutSettingsDirtyBits PutSyncSettings(VectrexSyncSettings o) return ret ? PutSettingsDirtyBits.RebootCore : PutSettingsDirtyBits.None; } - private object _settings = new object(); - public VectrexSyncSettings _syncSettings = new VectrexSyncSettings(); + private object _settings = new(); + public VectrexSyncSettings _syncSettings = new(); public class VectrexSyncSettings { @@ -78,20 +75,14 @@ public ControllerType VectrexController2 } } - public VectrexSyncSettings Clone() - { - return (VectrexSyncSettings)MemberwiseClone(); - } + public VectrexSyncSettings Clone() => (VectrexSyncSettings)MemberwiseClone(); public VectrexSyncSettings() { SettingsUtil.SetDefaultValues(this); } - public static bool NeedsReboot(VectrexSyncSettings x, VectrexSyncSettings y) - { - return !DeepEquality.DeepEquals(x, y); - } + public static bool NeedsReboot(VectrexSyncSettings x, VectrexSyncSettings y) => !DeepEquality.DeepEquals(x, y); } } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/VectrexHawk.cs b/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/VectrexHawk.cs index 1142efd5258..5fe6cba5fcd 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/VectrexHawk.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/VectrexHawk.cs @@ -35,7 +35,7 @@ internal static class RomChecksums [CoreConstructor(VSystemID.Raw.VEC)] public VectrexHawk(CoreComm comm, byte[] rom, VectrexHawk.VectrexSyncSettings syncSettings) { - var ser = new BasicServiceProvider(this); + BasicServiceProvider ser = new(this); cpu = new MC6809 { @@ -57,7 +57,7 @@ public VectrexHawk(CoreComm comm, byte[] rom, VectrexHawk.VectrexSyncSettings sy /*var Bios =*/ _bios = comm.CoreFileProvider.GetFirmwareOrThrow(new("VEC", "Bios"), "BIOS Not Found, Cannot Load"); /*var Mine =*/ minestorm = comm.CoreFileProvider.GetFirmwareOrThrow(new("VEC", "Minestorm"), "Minestorm Not Found, Cannot Load"); - var romHashSHA1 = SHA1Checksum.ComputePrefixedHex(rom); + string romHashSHA1 = SHA1Checksum.ComputePrefixedHex(rom); Console.WriteLine(romHashSHA1); _rom = rom; diff --git a/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/VectrexHawkControllerDeck.cs b/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/VectrexHawkControllerDeck.cs index 71d05d1377f..97de8811470 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/VectrexHawkControllerDeck.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/GCE/Vectrex/VectrexHawkControllerDeck.cs @@ -37,15 +37,9 @@ public VectrexHawkControllerDeck(string controller1Name, string controller2Name) Definition.MakeImmutable(); } - public byte ReadPort1(IController c) - { - return Port1.Read(c); - } + public byte ReadPort1(IController c) => Port1.Read(c); - public byte ReadPort2(IController c) - { - return Port2.Read(c); - } + public byte ReadPort2(IController c) => Port2.Read(c); public ControllerDefinition Definition { get; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Cartridge.cs b/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Cartridge.cs index 393c5af0aa3..09c6742f532 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Cartridge.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Cartridge.cs @@ -54,172 +54,172 @@ public int Parse(byte[] rom) switch (_mapper) { case 0: - if (addr >= 0x5000 && addr <= 0x6FFF) + if (addr is >= 0x5000 and <= 0x6FFF) { return Data[addr - 0x5000]; } - if (addr >= 0xD000 && addr <= 0xDFFF) + if (addr is >= 0xD000 and <= 0xDFFF) { return Data[addr - 0xB000]; } - if (addr >= 0xF000 && addr <= 0xFFFF) + if (addr is >= 0xF000 and <= 0xFFFF) { return Data[addr - 0xC000]; } break; case 1: - if (addr >= 0x5000 && addr <= 0x6FFF) + if (addr is >= 0x5000 and <= 0x6FFF) { return Data[addr - 0x5000]; } - if (addr >= 0xD000 && addr <= 0xFFFF) + if (addr is >= 0xD000 and <= 0xFFFF) { return Data[addr - 0xB000]; } break; case 2: - if (addr >= 0x5000 && addr <= 0x6FFF) + if (addr is >= 0x5000 and <= 0x6FFF) { return Data[addr - 0x5000]; } - if (addr >= 0x9000 && addr <= 0xBFFF) + if (addr is >= 0x9000 and <= 0xBFFF) { return Data[addr - 0x7000]; } - if (addr >= 0xD000 && addr <= 0xDFFF) + if (addr is >= 0xD000 and <= 0xDFFF) { return Data[addr - 0x8000]; } break; case 3: - if (addr >= 0x5000 && addr <= 0x6FFF) + if (addr is >= 0x5000 and <= 0x6FFF) { return Data[addr - 0x5000]; } - if (addr >= 0x9000 && addr <= 0xAFFF) + if (addr is >= 0x9000 and <= 0xAFFF) { return Data[addr - 0x7000]; } - if (addr >= 0xD000 && addr <= 0xDFFF) + if (addr is >= 0xD000 and <= 0xDFFF) { return Data[addr - 0x9000]; } - if (addr >= 0xF000 && addr <= 0xFFFF) + if (addr is >= 0xF000 and <= 0xFFFF) { return Data[addr - 0xA000]; } break; case 4: - if (addr >= 0x5000 && addr <= 0x6FFF) + if (addr is >= 0x5000 and <= 0x6FFF) { return Data[addr - 0x5000]; } - if (addr >= 0xD000 && addr <= 0xD3FF) + if (addr is >= 0xD000 and <= 0xD3FF) { return Cart_Ram[addr - 0xD000]; } break; case 5: - if (addr >= 0x5000 && addr <= 0x7FFF) + if (addr is >= 0x5000 and <= 0x7FFF) { return Data[addr - 0x5000]; } - if (addr >= 0x9000 && addr <= 0xBFFF) + if (addr is >= 0x9000 and <= 0xBFFF) { return Data[addr - 0x6000]; } break; case 6: - if (addr >= 0x6000 && addr <= 0x7FFF) + if (addr is >= 0x6000 and <= 0x7FFF) { return Data[addr - 0x6000]; } break; case 7: - if (addr >= 0x4800 && addr <= 0x67FF) + if (addr is >= 0x4800 and <= 0x67FF) { return Data[addr - 0x4800]; } break; case 8: - if (addr >= 0x5000 && addr <= 0x5FFF) + if (addr is >= 0x5000 and <= 0x5FFF) { return Data[addr - 0x5000]; } - else if (addr >= 0x7000 && addr <= 0x7FFF) + else if (addr is >= 0x7000 and <= 0x7FFF) { return Data[addr - 0x6000]; } break; case 9: - if (addr >= 0x5000 && addr <= 0x6FFF) + if (addr is >= 0x5000 and <= 0x6FFF) { return Data[addr - 0x5000]; } - if (addr >= 0x9000 && addr <= 0xAFFF) + if (addr is >= 0x9000 and <= 0xAFFF) { return Data[addr - 0x7000]; } - if (addr >= 0xD000 && addr <= 0xDFFF) + if (addr is >= 0xD000 and <= 0xDFFF) { return Data[addr - 0x9000]; } - if (addr >= 0xF000 && addr <= 0xFFFF) + if (addr is >= 0xF000 and <= 0xFFFF) { return Data[addr - 0xA000]; } - if (addr >= 0x8800 && addr <= 0x8FFF) + if (addr is >= 0x8800 and <= 0x8FFF) { return Cart_Ram[addr - 0x8800]; } break; case 10: - if (addr >= 0x5000 && addr <= 0x6FFF) + if (addr is >= 0x5000 and <= 0x6FFF) { return Data[addr - 0x5000]; } - if (addr >= 0x8800 && addr <= 0xB7FF) + if (addr is >= 0x8800 and <= 0xB7FF) { return Data[addr - 0x6800]; } - if (addr >= 0xD000 && addr <= 0xFFFF) + if (addr is >= 0xD000 and <= 0xFFFF) { return Data[addr - 0x8000]; } break; case 11: - if (addr >= 0x5000 && addr <= 0x5FFF) + if (addr is >= 0x5000 and <= 0x5FFF) { return Data[addr - 0x5000]; } - if (addr >= 0xD000 && addr <= 0xDFFF) + if (addr is >= 0xD000 and <= 0xDFFF) { return Data[addr - 0xC000]; } @@ -234,14 +234,14 @@ public bool WriteCart(ushort addr, ushort value, bool poke) switch (_mapper) { case 4: - if (addr >= 0xD000 && addr <= 0xD3FF) + if (addr is >= 0xD000 and <= 0xD3FF) { Cart_Ram[addr - 0xD000] = value; return true; } break; case 9: - if (addr >= 0x8800 && addr <= 0x8FFF) + if (addr is >= 0x8800 and <= 0x8FFF) { Cart_Ram[addr - 0x8800] = value; return true; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Controllers/IntellivisionControllerDeck.cs b/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Controllers/IntellivisionControllerDeck.cs index 26b3cc892c3..276c18bf1b5 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Controllers/IntellivisionControllerDeck.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Controllers/IntellivisionControllerDeck.cs @@ -37,15 +37,9 @@ public IntellivisionControllerDeck(string controller1Name, string controller2Nam Definition.MakeImmutable(); } - public byte ReadPort1(IController c) - { - return Port1.Read(c); - } + public byte ReadPort1(IController c) => Port1.Read(c); - public byte ReadPort2(IController c) - { - return Port2.Read(c); - } + public byte ReadPort2(IController c) => Port2.Read(c); public ControllerDefinition Definition { get; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Controllers/IntellivisionControllers.cs b/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Controllers/IntellivisionControllers.cs index 376b35cdd8c..ed7af3e289b 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Controllers/IntellivisionControllers.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Controllers/IntellivisionControllers.cs @@ -30,10 +30,7 @@ public UnpluggedController(int portNum) Definition = new("(Intellivision Controller fragment)"); } - public byte Read(IController c) - { - return 0; - } + public byte Read(IController c) => 0; public ControllerDefinition Definition { get; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Intellicart.cs b/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Intellicart.cs index e2e4d7c7d0b..ef569f8652d 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Intellicart.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Intellicart.cs @@ -56,10 +56,7 @@ public void SyncState(Serializer ser) 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0 }; - private ushort UpdateCRC16(ushort crc, byte data) - { - return (ushort)((crc << 8) ^ CRC16_table[(crc >> 8) ^ data]); - } + private ushort UpdateCRC16(ushort crc, byte data) => (ushort)((crc << 8) ^ CRC16_table[(crc >> 8) ^ data]); public int Parse(byte[] Rom) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Intellivision.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Intellivision.IMemoryDomains.cs index 8668bca6f6b..da0c3dfcdbc 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Intellivision.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Intellivision.IMemoryDomains.cs @@ -11,7 +11,7 @@ private void SetupMemoryDomains() { // TODO: is 8bit for byte arrays and 16bit for ushort correct here? // If ushort is correct, how about little endian? - var domains = new List + List domains = new() { new MemoryDomainDelegate( "Main RAM", diff --git a/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Intellivision.ISettable.cs b/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Intellivision.ISettable.cs index 999929b2f3a..eb5a08f22cc 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Intellivision.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Intellivision.ISettable.cs @@ -8,15 +8,9 @@ namespace BizHawk.Emulation.Cores.Intellivision { public partial class Intellivision : IEmulator, ISettable { - public IntvSettings GetSettings() - { - return _settings.Clone(); - } + public IntvSettings GetSettings() => _settings.Clone(); - public IntvSyncSettings GetSyncSettings() - { - return _syncSettings.Clone(); - } + public IntvSyncSettings GetSyncSettings() => _syncSettings.Clone(); public PutSettingsDirtyBits PutSettings(IntvSettings o) { @@ -31,15 +25,12 @@ public PutSettingsDirtyBits PutSyncSettings(IntvSyncSettings o) return ret ? PutSettingsDirtyBits.RebootCore : PutSettingsDirtyBits.None; } - private IntvSettings _settings = new IntvSettings(); - private IntvSyncSettings _syncSettings = new IntvSyncSettings(); + private IntvSettings _settings = new(); + private IntvSyncSettings _syncSettings = new(); public class IntvSettings { - public IntvSettings Clone() - { - return (IntvSettings)MemberwiseClone(); - } + public IntvSettings Clone() => (IntvSettings)MemberwiseClone(); } public class IntvSyncSettings @@ -77,15 +68,9 @@ public string Port2 } } - public IntvSyncSettings Clone() - { - return (IntvSyncSettings)MemberwiseClone(); - } + public IntvSyncSettings Clone() => (IntvSyncSettings)MemberwiseClone(); - public static bool NeedsReboot(IntvSyncSettings x, IntvSyncSettings y) - { - return !DeepEquality.DeepEquals(x, y); - } + public static bool NeedsReboot(IntvSyncSettings x, IntvSyncSettings y) => !DeepEquality.DeepEquals(x, y); } } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Intellivision.cs b/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Intellivision.cs index 4c9de475613..945c668d065 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Intellivision.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Intellivision/Intellivision.cs @@ -13,7 +13,7 @@ public sealed partial class Intellivision : IEmulator, IInputPollable, IDisassem [CoreConstructor(VSystemID.Raw.INTV)] public Intellivision(CoreComm comm, byte[] rom, Intellivision.IntvSettings settings, Intellivision.IntvSyncSettings syncSettings) { - var ser = new BasicServiceProvider(this); + BasicServiceProvider ser = new(this); ServiceProvider = ser; _rom = rom; _settings = settings ?? new IntvSettings(); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Intellivision/PSG.cs b/src/BizHawk.Emulation.Cores/Consoles/Intellivision/PSG.cs index 3f3c24bcf8e..762d860fd4e 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Intellivision/PSG.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Intellivision/PSG.cs @@ -8,7 +8,7 @@ namespace BizHawk.Emulation.Cores.Intellivision { public sealed class PSG : ISoundProvider { - private readonly BlipBuffer _blip = new BlipBuffer(4096); + private readonly BlipBuffer _blip = new(4096); private short[] _sampleBuffer = new short[0]; @@ -40,10 +40,7 @@ public void DiscardSamples() _sampleClock = 0; } - public void GetSamplesAsync(short[] samples) - { - throw new NotSupportedException("Async is not available"); - } + public void GetSamplesAsync(short[] samples) => throw new NotSupportedException("Async is not available"); public bool CanProvideAsync => false; @@ -78,10 +75,7 @@ public void GetSamplesSync(out short[] samples, out int nsamp) samples = _sampleBuffer; } - public void GetSamples(short[] samples) - { - throw new Exception(); - } + public void GetSamples(short[] samples) => throw new Exception(); private static readonly int[] VolumeTable = { @@ -144,7 +138,7 @@ public void SyncState(Serializer ser) public ushort? ReadPSG(ushort addr, bool peek) { - if (addr >= 0x01F0 && addr <= 0x01FF) + if (addr is >= 0x01F0 and <= 0x01FF) { return Register[addr - 0x01F0]; } @@ -193,7 +187,7 @@ private void sync_psg_state() noise_per = 0x20; } - var shape_select = Register[10] & 0xF; + int shape_select = Register[10] & 0xF; if (shape_select < 4) env_shape = 0; @@ -214,19 +208,19 @@ private void sync_psg_state() public bool WritePSG(ushort addr, ushort value, bool poke) { - if (addr >= 0x01F0 && addr <= 0x01FF) + if (addr is >= 0x01F0 and <= 0x01FF) { - var reg = addr - 0x01F0; + int reg = addr - 0x01F0; value &= 0xFF; - if (reg == 4 || reg == 5 || reg == 6 || reg == 10) + if (reg is 4 or 5 or 6 or 10) value &= 0xF; if (reg == 9) value &= 0x1F; - if (reg == 11 || reg == 12 || reg == 13) + if (reg is 11 or 12 or 13) value &= 0x3F; Register[addr - 0x01F0] = value; @@ -237,7 +231,7 @@ public bool WritePSG(ushort addr, ushort value, bool poke) { env_clock = env_per; - if (env_shape == 0 || env_shape == 2 || env_shape == 3 || env_shape == 4 || env_shape == 5) + if (env_shape is 0 or 2 or 3 or 4 or 5) { env_E = 15; E_up_down = -1; @@ -292,21 +286,21 @@ public void generate_sound(int cycles_to_do) env_E += E_up_down; - if (env_E == 16 || env_E == -1) + if (env_E is 16 or (-1)) { // we just completed a period of the envelope, determine what to do now based on the envelope shape - if (env_shape == 0 || env_shape == 1 || env_shape == 3 || env_shape == 9) + if (env_shape is 0 or 1 or 3 or 9) { E_up_down = 0; env_E = 0; } - else if (env_shape == 5 || env_shape == 7) + else if (env_shape is 5 or 7) { E_up_down = 0; env_E = 15; } - else if (env_shape == 4 || env_shape == 8) + else if (env_shape is 4 or 8) { if (env_E == 16) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Intellivision/STIC.cs b/src/BizHawk.Emulation.Cores/Consoles/Intellivision/STIC.cs index ec49aa5d55e..5b62be065b5 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Intellivision/STIC.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Intellivision/STIC.cs @@ -48,11 +48,7 @@ public void SyncState(Serializer ser) ser.EndSection(); } - public int[] GetVideoBuffer() - { - - return FrameBuffer; - } + public int[] GetVideoBuffer() => FrameBuffer; // gets called when a new border color is chosen private void Update_Border() @@ -105,15 +101,9 @@ public void Reset() public bool GetSr1() => Sr1; public bool GetSr2() => Sr2; - public void ToggleSr2() - { - Sr2 = !Sr2; - } + public void ToggleSr2() => Sr2 = !Sr2; - public void SetSst(bool value) - { - Sst = value; - } + public void SetSst(bool value) => Sst = value; // mask off appropriate STIC bits and write to register private void write_reg(int reg, ushort value, bool poke) @@ -273,43 +263,26 @@ public bool WriteSTIC(ushort addr, ushort value, bool poke) private int ColorToRGBA(int color) { - switch (color) + return color switch { - case 0: - return 0x000000; - case 1: - return 0x002DFF; - case 2: - return 0xFF3D10; - case 3: - return 0xC9CFAB; - case 4: - return 0x386B3F; - case 5: - return 0x00A756; - case 6: - return 0xFAEA50; - case 7: - return 0xFFFCFF; - case 8: - return 0xBDACC8; - case 9: - return 0x24B8FF; - case 10: - return 0xFFB41F; - case 11: - return 0x546E00; - case 12: - return 0xFF4E57; - case 13: - return 0xA496FF; - case 14: - return 0x75CC80; - case 15: - return 0xB51A58; - default: - throw new ArgumentOutOfRangeException(paramName: nameof(color), color, message: "Specified color does not exist."); - } + 0 => 0x000000, + 1 => 0x002DFF, + 2 => 0xFF3D10, + 3 => 0xC9CFAB, + 4 => 0x386B3F, + 5 => 0x00A756, + 6 => 0xFAEA50, + 7 => 0xFFFCFF, + 8 => 0xBDACC8, + 9 => 0x24B8FF, + 10 => 0xFFB41F, + 11 => 0x546E00, + 12 => 0xFF4E57, + 13 => 0xA496FF, + 14 => 0x75CC80, + 15 => 0xB51A58, + _ => throw new ArgumentOutOfRangeException(paramName: nameof(color), color, message: "Specified color does not exist."), + }; } public void Background(int input_row) @@ -856,7 +829,7 @@ public void Mobs() } // the extra condition here is to ignore only border/BG collsion bit set - if (Collision[i, j] != 0 && Collision[i,j] != (1 << 9) && Collision[i,j] != (1 << 8)) + if (Collision[i, j] is not 0 and not (1 << 9) and not (1 << 8)) { for (int k = 0; k < 8; k++) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/Mappers/MapperBase.cs b/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/Mappers/MapperBase.cs index e9b7c5594f7..fe31a1890ae 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/Mappers/MapperBase.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/Mappers/MapperBase.cs @@ -35,14 +35,8 @@ public virtual void MapCDL(ushort addr, I8048.eCDLogMemFlags flags) { } - protected void SetCDLROM(I8048.eCDLogMemFlags flags, int cdladdr) - { - Core.SetCDL(flags, "ROM", cdladdr); - } + protected void SetCDLROM(I8048.eCDLogMemFlags flags, int cdladdr) => Core.SetCDL(flags, "ROM", cdladdr); - protected void SetCDLRAM(I8048.eCDLogMemFlags flags, int cdladdr) - { - Core.SetCDL(flags, "CartRAM", cdladdr); - } + protected void SetCDLRAM(I8048.eCDLogMemFlags flags, int cdladdr) => Core.SetCDL(flags, "CartRAM", cdladdr); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/Mappers/Mapper_Default.cs b/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/Mappers/Mapper_Default.cs index af5b0599b44..1fa932cebeb 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/Mappers/Mapper_Default.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/Mappers/Mapper_Default.cs @@ -21,24 +21,15 @@ public override void Initialize() } } - public override byte ReadMemory(ushort addr) - { - return Core._rom[addr & ROM_mask]; - } + public override byte ReadMemory(ushort addr) => Core._rom[addr & ROM_mask]; - public override void MapCDL(ushort addr, I8048.eCDLogMemFlags flags) - { - SetCDLROM(flags, addr); - } + public override void MapCDL(ushort addr, I8048.eCDLogMemFlags flags) => SetCDLROM(flags, addr); public override void WriteMemory(ushort addr, byte value) { // no mapping hardware available } - public override void SyncState(Serializer ser) - { - ser.Sync(nameof(ROM_mask), ref ROM_mask); - } + public override void SyncState(Serializer ser) => ser.Sync(nameof(ROM_mask), ref ROM_mask); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/Mappers/Mapper_XROM.cs b/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/Mappers/Mapper_XROM.cs index 512d03e65a3..7d62c7ce413 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/Mappers/Mapper_XROM.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/Mappers/Mapper_XROM.cs @@ -7,31 +7,20 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk public class MapperXROM : MapperBase { public int ROM_mask; - - public override void Initialize() - { + + public override void Initialize() => // XROM has data instructions from 0x400-0xFFF ROM_mask = 0xFFF; - } - public override byte ReadMemory(ushort addr) - { - return Core._rom[(addr + 0x400) & ROM_mask]; - } + public override byte ReadMemory(ushort addr) => Core._rom[(addr + 0x400) & ROM_mask]; - public override void MapCDL(ushort addr, I8048.eCDLogMemFlags flags) - { - SetCDLROM(flags, addr); - } + public override void MapCDL(ushort addr, I8048.eCDLogMemFlags flags) => SetCDLROM(flags, addr); public override void WriteMemory(ushort addr, byte value) { // no mapping hardware available } - public override void SyncState(Serializer ser) - { - ser.Sync(nameof(ROM_mask), ref ROM_mask); - } + public override void SyncState(Serializer ser) => ser.Sync(nameof(ROM_mask), ref ROM_mask); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.IEmulator.cs b/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.IEmulator.cs index f21dae03892..68f9997a7b4 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.IEmulator.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.IEmulator.cs @@ -203,10 +203,7 @@ public void ResetCounters() _islag = false; } - public void Dispose() - { - ppu.DisposeSound(); - } + public void Dispose() => ppu.DisposeSound(); public int _frameHz = 60; @@ -214,10 +211,7 @@ public void Dispose() public int[] frame_buffer; - public int[] GetVideoBuffer() - { - return frame_buffer; - } + public int[] GetVideoBuffer() => frame_buffer; public void SendVideoBuffer() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.IMemoryDomains.cs index af966bf76db..0025a975442 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.IMemoryDomains.cs @@ -9,7 +9,7 @@ public partial class O2Hawk public void SetupMemoryDomains() { - var domains = new List + List domains = new() { new MemoryDomainDelegate( "Main RAM", @@ -50,7 +50,7 @@ public void SetupMemoryDomains() if (cart_RAM != null) { - var CartRam = new MemoryDomainByteArray("Cart RAM", MemoryDomain.Endian.Little, cart_RAM, true, 1); + MemoryDomainByteArray CartRam = new("Cart RAM", MemoryDomain.Endian.Little, cart_RAM, true, 1); domains.Add(CartRam); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.ISaveRam.cs b/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.ISaveRam.cs index efa4a2cd83b..dc36d4893d3 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.ISaveRam.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.ISaveRam.cs @@ -5,10 +5,7 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk { public partial class O2Hawk : ISaveRam { - public byte[] CloneSaveRam() - { - return (byte[])cart_RAM?.Clone(); - } + public byte[] CloneSaveRam() => (byte[])cart_RAM?.Clone(); public void StoreSaveRam(byte[] data) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.ISettable.cs b/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.ISettable.cs index 51326205d10..aaa7023394c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.ISettable.cs @@ -6,15 +6,9 @@ namespace BizHawk.Emulation.Cores.Consoles.O2Hawk { public partial class O2Hawk : IEmulator, ISettable { - public O2Settings GetSettings() - { - return _settings.Clone(); - } + public O2Settings GetSettings() => _settings.Clone(); - public O2SyncSettings GetSyncSettings() - { - return _syncSettings.Clone(); - } + public O2SyncSettings GetSyncSettings() => _syncSettings.Clone(); public PutSettingsDirtyBits PutSettings(O2Settings o) { @@ -29,8 +23,8 @@ public PutSettingsDirtyBits PutSyncSettings(O2SyncSettings o) return ret ? PutSettingsDirtyBits.RebootCore : PutSettingsDirtyBits.None; } - public O2Settings _settings = new O2Settings(); - public O2SyncSettings _syncSettings = new O2SyncSettings(); + public O2Settings _settings = new(); + public O2SyncSettings _syncSettings = new(); public class O2Settings { @@ -59,10 +53,7 @@ public class O2Settings [DefaultValue(true)] public bool Show_G7400_BG { get; set; } - public O2Settings Clone() - { - return (O2Settings)MemberwiseClone(); - } + public O2Settings Clone() => (O2Settings)MemberwiseClone(); public O2Settings() { @@ -82,20 +73,14 @@ public class O2SyncSettings [DefaultValue(true)] public bool Use_SRAM { get; set; } - public O2SyncSettings Clone() - { - return (O2SyncSettings)MemberwiseClone(); - } + public O2SyncSettings Clone() => (O2SyncSettings)MemberwiseClone(); public O2SyncSettings() { SettingsUtil.SetDefaultValues(this); } - public static bool NeedsReboot(O2SyncSettings x, O2SyncSettings y) - { - return !DeepEquality.DeepEquals(x, y); - } + public static bool NeedsReboot(O2SyncSettings x, O2SyncSettings y) => !DeepEquality.DeepEquals(x, y); } } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.cs b/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.cs index ee389b83b3b..ca772b9a114 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2Hawk.cs @@ -43,7 +43,7 @@ public partial class O2Hawk : IEmulator, ISaveRam, IDebuggable, IInputPollable, [CoreConstructor(VSystemID.Raw.O2)] public O2Hawk(CoreComm comm, GameInfo game, byte[] rom, O2Settings settings, O2SyncSettings syncSettings) { - var ser = new BasicServiceProvider(this); + BasicServiceProvider ser = new(this); cpu = new I8048 { @@ -138,10 +138,7 @@ public void HardReset() WritePort(2, 0xFF); } - public void SoftReset() - { - cpu.Reset(); - } + public void SoftReset() => cpu.Reset(); public string BoardName => mapper.GetType().Name; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2HawkControllerDeck.cs b/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2HawkControllerDeck.cs index ac8dedf1cb5..e0d95a999d5 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2HawkControllerDeck.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/O2HawkControllerDeck.cs @@ -64,15 +64,9 @@ public O2HawkControllerDeck(string controller1Name, string controller2Name, bool Definition.MakeImmutable(); } - public byte ReadPort1(IController c) - { - return Port1.Read(c); - } + public byte ReadPort1(IController c) => Port1.Read(c); - public byte ReadPort2(IController c) - { - return Port2.Read(c); - } + public byte ReadPort2(IController c) => Port2.Read(c); public ControllerDefinition Definition { get; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/PPU.cs b/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/PPU.cs index 13b4274582b..d9916d15cc6 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/PPU.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Magnavox/Odyssey2/PPU.cs @@ -1,4 +1,4 @@ -using System; +using System; using BizHawk.Common; using BizHawk.Common.NumberExtensions; using BizHawk.Emulation.Common; @@ -125,15 +125,15 @@ public virtual byte ReadReg(int addr) { ret = AudioReadReg(addr); } - else if ((addr >= 0xC0) && (addr <= 0xC8)) + else if (addr is >= 0xC0 and <= 0xC8) { ret = Grid_H[addr - 0xC0]; } - else if ((addr >= 0xD0) && (addr <= 0xD8)) + else if (addr is >= 0xD0 and <= 0xD8) { ret = Grid_H[addr - 0xD0 + 9]; } - else if ((addr >= 0xE0) && (addr <= 0xE9)) + else if (addr is >= 0xE0 and <= 0xE9) { ret = Grid_V[addr - 0xE0]; } @@ -175,9 +175,9 @@ public virtual byte PeekReg(int addr) else { ret = (byte)(cycle); } } else if (addr <= 0xAA) { ret = AudioReadReg(addr); } - else if ((addr >= 0xC0) && (addr <= 0xC8)) { ret = Grid_H[addr - 0xC0]; } - else if ((addr >= 0xD0) && (addr <= 0xD8)) { ret = Grid_H[addr - 0xD0 + 9]; } - else if ((addr >= 0xE0) && (addr <= 0xE9)) { ret = Grid_V[addr - 0xE0]; } + else if (addr is >= 0xC0 and <= 0xC8) { ret = Grid_H[addr - 0xC0]; } + else if (addr is >= 0xD0 and <= 0xD8) { ret = Grid_H[addr - 0xD0 + 9]; } + else if (addr is >= 0xE0 and <= 0xE9) { ret = Grid_V[addr - 0xE0]; } return ret; } @@ -271,25 +271,22 @@ public void WriteReg(int addr, byte value) { AudioWriteReg(addr, value); } - else if ((addr >= 0xC0) && (addr <= 0xC8)) + else if (addr is >= 0xC0 and <= 0xC8) { if (!VDC_ctrl.Bit(3)) { Grid_H[addr - 0xC0] = value; } else { Console.WriteLine("blocked"); } } - else if ((addr >= 0xD0) && (addr <= 0xD8)) + else if (addr is >= 0xD0 and <= 0xD8) { if (!VDC_ctrl.Bit(3)) { Grid_H[addr - 0xD0 + 9] = value; } else { Console.WriteLine("blocked"); } } - else if ((addr >= 0xE0) && (addr <= 0xE9)) + else if (addr is >= 0xE0 and <= 0xE9) { if (!VDC_ctrl.Bit(3)) { Grid_V[addr - 0xE0] = value; } else { Console.WriteLine("blocked"); } } //Console.WriteLine(addr + " " + value + " " + LY + " " + Core.cpu.TotalExecutedCycles); } - public byte ReadRegVPP(int addr) - { - return 0; - } + public byte ReadRegVPP(int addr) => 0; public void WriteRegVPP(int addr, byte value) { @@ -481,7 +478,7 @@ public virtual void process_pixel() if (VDC_ctrl.Bit(6) && ((LY - GRID_OFST) >= 0) && (((LY - GRID_OFST) % GRID_OFST) < 3) && VDC_ctrl.Bit(3)) { - if (((cycle % 16) == 8) || ((cycle % 16) == 9)) + if (cycle % 16 is 8 or 9) { int k = (int)Math.Floor(cycle / 16.0); int j = (int)Math.Floor((LY - GRID_OFST) / 24.0); @@ -1329,7 +1326,7 @@ public void SyncState(Serializer ser) AudioSyncState(ser); } - private BlipBuffer _blip_C = new BlipBuffer(15000); + private BlipBuffer _blip_C = new(15000); public byte sample; @@ -1502,10 +1499,7 @@ public void GetSamplesSync(out short[] samples, out int nsamp) master_audio_clock = 0; } - public void GetSamplesAsync(short[] samples) - { - throw new NotSupportedException("Async is not available"); - } + public void GetSamplesAsync(short[] samples) => throw new NotSupportedException("Async is not available"); public void DiscardSamples() { @@ -1513,10 +1507,12 @@ public void DiscardSamples() master_audio_clock = 0; } + #pragma warning disable IDE0051 private void GetSamples(short[] samples) { } + #pragma warning restore IDE0051 public void DisposeSound() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/NEC/PCE/HyperNyma.cs b/src/BizHawk.Emulation.Cores/Consoles/NEC/PCE/HyperNyma.cs index db4e95d88c9..23a73f93eac 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/NEC/PCE/HyperNyma.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/NEC/PCE/HyperNyma.cs @@ -24,7 +24,7 @@ public static NymaSettingsInfo CachedSettingsInfo(CoreComm comm) { if (_cachedSettingsInfo is null) { - using var n = new HyperNyma(comm); + using HyperNyma n = new(comm); n.InitForSettingsInfo("hyper.wbx"); _cachedSettingsInfo = n.SettingsInfo.Clone(); } @@ -42,7 +42,7 @@ public static NymaSettingsInfo CachedSettingsInfo(CoreComm comm) public HyperNyma(CoreLoadParameters lp) : base(lp.Comm, VSystemID.Raw.PCE, "PC Engine Controller", lp.Settings, lp.SyncSettings) { - var firmwares = new Dictionary(); + Dictionary firmwares = new(); if (lp.Discs.Count > 0) { _hasCds = true; @@ -79,12 +79,12 @@ public unsafe void GetGpuData(int vdc, Action callback) { using(_exe.EnterExit()) { - var palScratch = new int[512]; - var v = new PceGpuData(); + int[] palScratch = new int[512]; + PceGpuData v = new(); _hyperNyma.GetVramInfo(v, vdc); fixed(int* p = palScratch) { - for (var i = 0; i < 512; i++) + for (int i = 0; i < 512; i++) p[i] = v.PaletteCache[i] | unchecked((int)0xff000000); v.PaletteCache = p; callback(v); diff --git a/src/BizHawk.Emulation.Cores/Consoles/NEC/PCE/TurboNyma.cs b/src/BizHawk.Emulation.Cores/Consoles/NEC/PCE/TurboNyma.cs index 60978421dda..b079c8806f6 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/NEC/PCE/TurboNyma.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/NEC/PCE/TurboNyma.cs @@ -26,7 +26,7 @@ public static NymaSettingsInfo CachedSettingsInfo(CoreComm comm) { if (_cachedSettingsInfo is null) { - using var n = new TurboNyma(comm); + using TurboNyma n = new(comm); n.InitForSettingsInfo("turbo.wbx"); _cachedSettingsInfo = n.SettingsInfo.Clone(); } @@ -44,11 +44,11 @@ public static NymaSettingsInfo CachedSettingsInfo(CoreComm comm) public TurboNyma(CoreLoadParameters lp) : base(lp.Comm, VSystemID.Raw.PCE, "PC Engine Controller", lp.Settings, lp.SyncSettings) { - var firmwares = new Dictionary(); + Dictionary firmwares = new(); if (lp.Discs.Count > 0) { _hasCds = true; - var ids = lp.Discs.Select(dg => dg.DiscType).ToList(); + List ids = lp.Discs.Select(dg => dg.DiscType).ToList(); if (ids.Contains(DiscType.TurboCD)) firmwares.Add("FIRMWARE:syscard3.pce", new("PCECD", "Bios")); if (ids.Contains(DiscType.TurboGECD)) @@ -117,12 +117,12 @@ public unsafe void GetGpuData(int vdc, Action callback) { using(_exe.EnterExit()) { - var palScratch = new int[512]; - var v = new PceGpuData(); + int[] palScratch = new int[512]; + PceGpuData v = new(); _turboNyma.GetVramInfo(v, vdc); fixed(int* p = palScratch) { - for (var i = 0; i < 512; i++) + for (int i = 0; i < 512; i++) p[i] = v.PaletteCache[i] | unchecked((int)0xff000000); v.PaletteCache = p; callback(v); diff --git a/src/BizHawk.Emulation.Cores/Consoles/NEC/PCFX/Tst.cs b/src/BizHawk.Emulation.Cores/Consoles/NEC/PCFX/Tst.cs index 643bc2c91f0..238e52fef4c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/NEC/PCFX/Tst.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/NEC/PCFX/Tst.cs @@ -20,7 +20,7 @@ public static NymaSettingsInfo CachedSettingsInfo(CoreComm comm) { if (_cachedSettingsInfo is null) { - using var n = new Tst(comm); + using Tst n = new(comm); n.InitForSettingsInfo("pcfx.wbx"); _cachedSettingsInfo = n.SettingsInfo.Clone(); } @@ -34,7 +34,7 @@ public Tst(CoreLoadParameters lp) { if (lp.Roms.Count > 0) throw new InvalidOperationException("To load a PC-FX game, please load the CUE file and not the BIN file."); - var firmwares = new Dictionary + Dictionary firmwares = new() { { "FIRMWARE:pcfx.rom", new("PCFX", "BIOS") }, }; @@ -71,13 +71,13 @@ public Tst(CoreLoadParameters lp) protected override HashSet ComputeHiddenPorts() { // NB: Since we're hiding these settings up above, this will always trim us down to 2 ports - var devCount = 8; + int devCount = 8; if (SettingsQuery("pcfx.input.port1.multitap") != "1") devCount -= 3; if (SettingsQuery("pcfx.input.port2.multitap") != "1") devCount -= 3; - var ret = new HashSet(); - for (var i = 1; i <= 8; i++) + HashSet ret = new(); + for (int i = 1; i <= 8; i++) { if (i > devCount) ret.Add($"port{i}"); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/3DS/3DSMotionEmu.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/3DS/3DSMotionEmu.cs index a2001e34ec8..f53296ba472 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/3DS/3DSMotionEmu.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/3DS/3DSMotionEmu.cs @@ -31,7 +31,7 @@ public void Update(bool tilting, int x, int y) else { TiltDirection = tiltMove; - var tiltMoveNormalized = tiltMove.Length(); + float tiltMoveNormalized = tiltMove.Length(); TiltDirection /= tiltMoveNormalized; TiltAngle = tiltMoveNormalized * SENSITIVITY; TiltAngle = Math.Max(TiltAngle, 0.0f); @@ -43,8 +43,8 @@ public void Update(bool tilting, int x, int y) TiltAngle = 0; } - var tiltQ = Quaternion.CreateFromAxisAngle(new(-TiltDirection.Y, 0.0f, TiltDirection.X), TiltAngle); - var conTiltQ = Quaternion.Conjugate(tiltQ); + Quaternion tiltQ = Quaternion.CreateFromAxisAngle(new(-TiltDirection.Y, 0.0f, TiltDirection.X), TiltAngle); + Quaternion conTiltQ = Quaternion.Conjugate(tiltQ); var angularRateQ = (tiltQ - PrevTiltQuaternion) * conTiltQ; var angularRate = new Vector3(angularRateQ.X, angularRateQ.Y, angularRateQ.Z) * 2; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/3DS/Citra.IEmulator.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/3DS/Citra.IEmulator.cs index d37da9486eb..1a9826e341d 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/3DS/Citra.IEmulator.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/3DS/Citra.IEmulator.cs @@ -56,7 +56,7 @@ private void OnVideoRefresh() _core.Citra_GetVideoDimensions(_context, out _citraVideoProvider.Width, out _citraVideoProvider.Height); _citraVideoProvider.VideoDirty = true; - _core.Citra_GetTouchScreenLayout(_context, out var x, out var y, out var width, out var height, out var rotated, out var enabled); + _core.Citra_GetTouchScreenLayout(_context, out int x, out int y, out int width, out int height, out bool rotated, out bool enabled); TouchScreenRectangle = new(x, y, width, height); TouchScreenRotated = rotated; TouchScreenEnabled = enabled; @@ -80,7 +80,7 @@ public void Dispose() _core.Citra_DestroyContext(_context); - foreach (var glContext in _glContexts) + foreach (object glContext in _glContexts) { _openGLProvider.ReleaseGLContext(glContext); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/3DS/Citra.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/3DS/Citra.IMemoryDomains.cs index e98b51a1df5..edb49895669 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/3DS/Citra.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/3DS/Citra.IMemoryDomains.cs @@ -16,7 +16,7 @@ public partial class Citra private void InitMemoryDomains() { - var domains = new List() + List domains = new() { (_fcram = new("FCRAM", MemoryDomain.Endian.Little, IntPtr.Zero, 0, true, 4)), (_vram = new("VRAM", MemoryDomain.Endian.Little, IntPtr.Zero, 0, true, 4)), @@ -38,7 +38,7 @@ private void WireMemoryDomains() { void WireDomain(LibCitra.MemoryRegion region, MemoryDomainIntPtr domain) { - _core.Citra_GetMemoryRegion(_context, region, out var ptr, out var size); + _core.Citra_GetMemoryRegion(_context, region, out var ptr, out int size); domain.Data = ptr; domain.SetSize(size); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/3DS/Citra.ISettable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/3DS/Citra.ISettable.cs index 633f6229d28..3da0c71a6d3 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/3DS/Citra.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/3DS/Citra.ISettable.cs @@ -76,15 +76,15 @@ public partial class Citra : ISettable _userPath, "username" => _syncSettings.CFGUsername, _ => throw new InvalidOperationException() }; - var bytes = Encoding.UTF8.GetBytes(ret); - var numToCopy = Math.Min(bytes.Length, bufferSize - 1); + byte[] bytes = Encoding.UTF8.GetBytes(ret); + int numToCopy = Math.Min(bytes.Length, bufferSize - 1); Marshal.Copy(bytes, 0, buffer, numToCopy); Marshal.WriteByte(buffer, numToCopy, 0); } @@ -104,7 +104,7 @@ public PutSettingsDirtyBits PutSettings(CitraSettings o) public PutSettingsDirtyBits PutSyncSettings(CitraSyncSettings o) { - var ret = CitraSyncSettings.NeedsReboot(_syncSettings, o); + bool ret = CitraSyncSettings.NeedsReboot(_syncSettings, o); _syncSettings = o; return ret ? PutSettingsDirtyBits.RebootCore : PutSettingsDirtyBits.None; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/3DS/Citra.ISoundProvider.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/3DS/Citra.ISoundProvider.cs index 53e2bdfd648..8578acb2fd2 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/3DS/Citra.ISoundProvider.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/3DS/Citra.ISoundProvider.cs @@ -12,7 +12,7 @@ public partial class Citra : ISoundProvider private void ProcessSound() { - _core.Citra_GetAudio(_context, out var buffer, out var frames); + _core.Citra_GetAudio(_context, out var buffer, out int frames); if (frames > _sampleBuf.Length) { _sampleBuf = new short[frames]; @@ -26,15 +26,9 @@ private void ProcessSound() public SyncSoundMode SyncMode => SyncSoundMode.Sync; - public void DiscardSamples() - { - _nsamps = 0; - } + public void DiscardSamples() => _nsamps = 0; - public void GetSamplesAsync(short[] samples) - { - throw new NotSupportedException("Aync mode is not supported"); - } + public void GetSamplesAsync(short[] samples) => throw new NotSupportedException("Aync mode is not supported"); public void GetSamplesSync(out short[] samples, out int nsamp) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/3DS/Citra.IStatable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/3DS/Citra.IStatable.cs index b3561e37075..e5fcf4cbc10 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/3DS/Citra.IStatable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/3DS/Citra.IStatable.cs @@ -13,7 +13,7 @@ public partial class Citra : IStatable public void SaveStateBinary(BinaryWriter writer) { - var stateLen = _core.Citra_StartSaveState(_context); + int stateLen = _core.Citra_StartSaveState(_context); writer.Write(stateLen); if (stateLen > _stateBuf.Length) @@ -49,7 +49,7 @@ public void SaveStateBinary(BinaryWriter writer) public void LoadStateBinary(BinaryReader reader) { - var stateLen = reader.ReadInt32(); + int stateLen = reader.ReadInt32(); if (stateLen > _stateBuf.Length) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/3DS/Citra.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/3DS/Citra.cs index 5b06c4eb335..c18310f0caf 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/3DS/Citra.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/3DS/Citra.cs @@ -19,7 +19,7 @@ public partial class Citra static Citra() { - var resolver = new DynamicLibraryImportResolver( + DynamicLibraryImportResolver resolver = new( OSTailoredCode.IsUnixHost ? "libcitra-headless.so" : "citra-headless.dll", hasLimitedLifetime: false); _core = BizInvoker.GetInvoker(resolver, CallingConventionAdapters.Native); } @@ -67,8 +67,8 @@ public Citra(CoreLoadParameters lp) _supportsOpenGL43 = _openGLProvider.SupportsGLVersion(4, 3); if (!_supportsOpenGL43/* && _syncSettings.GraphicsApi == CitraSyncSettings.EGraphicsApi.OpenGL*/) { + lp.Comm.Notify("OpenGL 4.3 is not supported on this machine, falling back to software renderer", null); throw new("OpenGL 4.3 is required, but it is not supported on this machine"); -// lp.Comm.Notify("OpenGL 4.3 is not supported on this machine, falling back to software renderer", null); } _glCallbackInterface.RequestGLContext = RequestGLContextCallback; @@ -94,30 +94,30 @@ public Citra(CoreLoadParameters lp) _serviceProvider.Register(_citraVideoProvider); - var sysDataDir = Path.Combine(_userPath, "sysdata"); + string sysDataDir = Path.Combine(_userPath, "sysdata"); if (!Directory.Exists(sysDataDir)) { Directory.CreateDirectory(sysDataDir); } - var aesKeys = lp.Comm.CoreFileProvider.GetFirmware(new("3DS", "aes_keys")); + byte[] aesKeys = lp.Comm.CoreFileProvider.GetFirmware(new("3DS", "aes_keys")); if (aesKeys is not null) { File.WriteAllBytes(Path.Combine(sysDataDir, "aes_keys.txt"), aesKeys); } - var seeddb = lp.Comm.CoreFileProvider.GetFirmware(new("3DS", "seeddb")); + byte[] seeddb = lp.Comm.CoreFileProvider.GetFirmware(new("3DS", "seeddb")); if (seeddb is not null) { File.WriteAllBytes(Path.Combine(sysDataDir, "seeddb.bin"), seeddb); } - var romPath = lp.Roms[0].RomPath; + string romPath = lp.Roms[0].RomPath; if (lp.Roms[0].Extension.ToLowerInvariant() == ".cia") { - var message = new byte[1024]; - var res = _core.Citra_InstallCIA(_context, romPath, message, message.Length); - var outMsg = Encoding.UTF8.GetString(message).TrimEnd(); + byte[] message = new byte[1024]; + bool res = _core.Citra_InstallCIA(_context, romPath, message, message.Length); + string outMsg = Encoding.UTF8.GetString(message).TrimEnd(); if (res) { romPath = outMsg; @@ -132,8 +132,8 @@ public Citra(CoreLoadParameters lp) // user could have other CIAs after the first ROM (e.g. DLCs, updates) // they need to installed at once in the case of recording // as the temp folder is cleaned for each session - var dummyBuffer = new byte[1]; - for (var i = 1; i < lp.Roms.Count; i++) + byte[] dummyBuffer = new byte[1]; + for (int i = 1; i < lp.Roms.Count; i++) { // doesn't make sense if not a CIA if (lp.Roms[i].Extension.ToLowerInvariant() != ".cia") @@ -145,7 +145,7 @@ public Citra(CoreLoadParameters lp) _core.Citra_InstallCIA(_context, lp.Roms[i].RomPath, dummyBuffer, dummyBuffer.Length); } - var errorMessage = new byte[1024]; + byte[] errorMessage = new byte[1024]; if (!_core.Citra_LoadROM(_context, romPath, errorMessage, errorMessage.Length)) { Dispose(); @@ -161,15 +161,15 @@ public Citra(CoreLoadParameters lp) private IntPtr RequestGLContextCallback() { - var context = _openGLProvider.RequestGLContext(4, 3, true, false); + object context = _openGLProvider.RequestGLContext(4, 3, true, false); _glContexts.Add(context); - var handle = GCHandle.Alloc(context, GCHandleType.Weak); + GCHandle handle = GCHandle.Alloc(context, GCHandleType.Weak); return GCHandle.ToIntPtr(handle); } private void ReleaseGLContextCallback(IntPtr context) { - var handle = GCHandle.FromIntPtr(context); + GCHandle handle = GCHandle.FromIntPtr(context); _openGLProvider.ReleaseGLContext(handle.Target); _glContexts.Remove(handle.Target); handle.Free(); @@ -177,7 +177,7 @@ private void ReleaseGLContextCallback(IntPtr context) private void ActivateGLContextCallback(IntPtr context) { - var handle = GCHandle.FromIntPtr(context); + GCHandle handle = GCHandle.FromIntPtr(context); _openGLProvider.ActivateGLContext(handle.Target); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Ares64/Ares64.IDebuggable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Ares64/Ares64.IDebuggable.cs index 028037eb2a0..731881da141 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Ares64/Ares64.IDebuggable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Ares64/Ares64.IDebuggable.cs @@ -9,8 +9,8 @@ public partial class Ares64 : IDebuggable { public IDictionary GetCpuFlagsAndRegisters() { - var ret = new Dictionary(); - var data = new ulong[32 + 3]; // GPRs, lo, hi, pc (todo: other regs) + Dictionary ret = new(); + ulong[] data = new ulong[32 + 3]; // GPRs, lo, hi, pc (todo: other regs) _core.GetRegisters(data); for (int i = 0; i < 32; i++) diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Ares64/Ares64.IDisassemblable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Ares64/Ares64.IDisassemblable.cs index d4410da7778..aa198789483 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Ares64/Ares64.IDisassemblable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Ares64/Ares64.IDisassemblable.cs @@ -25,8 +25,8 @@ public override string Disassemble(MemoryDomain m, uint addr, out int length) // FIXME: the PC register is actually 64-bits (although in practice it will only ever be 32-bits) _core.GetDisassembly(addr, m.PeekUint(addr, true), _disasmbuf); length = 4; - var ret = Encoding.UTF8.GetString(_disasmbuf); - var z = ret.IndexOf('\0'); + string ret = Encoding.UTF8.GetString(_disasmbuf); + int z = ret.IndexOf('\0'); if (z > -1) { ret = ret.Substring(0, z); // remove garbage past null terminator diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Ares64/Ares64.ISettable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Ares64/Ares64.ISettable.cs index 5b1dba6b9d3..7b984441f70 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Ares64/Ares64.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Ares64/Ares64.ISettable.cs @@ -25,7 +25,7 @@ public PutSettingsDirtyBits PutSettings(Ares64Settings o) public PutSettingsDirtyBits PutSyncSettings(Ares64SyncSettings o) { - var ret = Ares64SyncSettings.NeedsReboot(_syncSettings, o); + bool ret = Ares64SyncSettings.NeedsReboot(_syncSettings, o); _syncSettings = o; return ret ? PutSettingsDirtyBits.RebootCore : PutSettingsDirtyBits.None; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Ares64/Ares64.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Ares64/Ares64.cs index d0f9ef0c414..39e3fa99c9c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Ares64/Ares64.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Ares64/Ares64.cs @@ -45,7 +45,7 @@ public Ares64(CoreLoadParameters lp) }; N64Controller = CreateControllerDefinition(ControllerSettings); - var interpreter = lp.Game.GetBool("ares_force_cpu_interpreter", false) || _syncSettings.CPUEmulation == LibAres64.CpuType.Interpreter; + bool interpreter = lp.Game.GetBool("ares_force_cpu_interpreter", false) || _syncSettings.CPUEmulation == LibAres64.CpuType.Interpreter; _core = PreInit(new() { @@ -71,8 +71,8 @@ static bool IsGBRom(byte[] rom) // (probably should, but needs refactoring) foreach (var r in lp.Roms) _ = N64RomByteswapper.ToZ64Native(r.RomData); // no-op if N64 magic bytes not present - var gbRoms = lp.Roms.FindAll(r => IsGBRom(r.FileData)).Select(r => r.FileData).ToArray(); - var rom = lp.Roms.Find(r => !gbRoms.Contains(r.FileData) && (char)r.RomData[0x3B] is 'N' or 'C')?.RomData; + byte[][] gbRoms = lp.Roms.FindAll(r => IsGBRom(r.FileData)).Select(r => r.FileData).ToArray(); + byte[] rom = lp.Roms.Find(r => !gbRoms.Contains(r.FileData) && (char)r.RomData[0x3B] is 'N' or 'C')?.RomData; var (disk, error) = TransformDisk(lp.Roms.Find(r => !gbRoms.Contains(r.FileData) && r.RomData != rom)?.FileData); if (rom is null && disk is null) @@ -87,14 +87,14 @@ static bool IsGBRom(byte[] rom) } } - var regionByte = rom is null ? 0 : rom[0x3E]; + int regionByte = rom is null ? 0 : rom[0x3E]; Region = regionByte switch { 0x44 or 0x46 or 0x49 or 0x50 or 0x53 or 0x55 or 0x58 or 0x59 => DisplayType.PAL, _ => DisplayType.NTSC, // note that N64DD is only valid as NTSC }; - var pal = Region == DisplayType.PAL; + bool pal = Region == DisplayType.PAL; if (pal) { @@ -102,7 +102,7 @@ static bool IsGBRom(byte[] rom) VsyncDenominator = 1; } - var pif = Zstd.DecompressZstdStream(new MemoryStream(pal ? Resources.PIF_PAL_ROM.Value : Resources.PIF_NTSC_ROM.Value)).ToArray(); + byte[] pif = Zstd.DecompressZstdStream(new MemoryStream(pal ? Resources.PIF_PAL_ROM.Value : Resources.PIF_NTSC_ROM.Value)).ToArray(); IsDD = disk is not null; byte[] ipl = null; @@ -133,7 +133,7 @@ byte[] GetGBRomOrNull(int n) gb3RomPtr = GetGBRomOrNull(2), gb4RomPtr = GetGBRomOrNull(3)) { - var loadData = new LibAres64.LoadData + LibAres64.LoadData loadData = new() { PifData = (IntPtr)pifPtr, PifLen = pif.Length, @@ -179,7 +179,7 @@ byte[] GetGBRomOrNull(int n) private static ControllerDefinition CreateControllerDefinition(LibAres64.ControllerType[] controllerSettings) { - var ret = new ControllerDefinition("Nintendo 64 Controller"); + ControllerDefinition ret = new("Nintendo 64 Controller"); for (int i = 0; i < 4; i++) { if (controllerSettings[i] == LibAres64.ControllerType.Mouse) @@ -315,13 +315,13 @@ static bool RepeatCheck(ReadOnlySpan slice, int size, int repeat) return true; } - var ret = new byte[1175 * 2 * 2]; + byte[] ret = new byte[1175 * 2 * 2]; ret[12] = 0; - var systemBlocks = new[] { 0, 1, 8, 9 }; + int[] systemBlocks = new[] { 0, 1, 8, 9 }; for (int i = 0; i < 4; i++) { - var systemOffset = systemBlocks[i] * 0x4D08; + int systemOffset = systemBlocks[i] * 0x4D08; if (disk[systemOffset + 0x00] is not 0xE8 and not 0x22) continue; if (disk[systemOffset + 0x01] is not 0x48 and not 0x63) continue; if (disk[systemOffset + 0x02] is not 0xD3 and not 0xEE) continue; @@ -343,8 +343,8 @@ static bool RepeatCheck(ReadOnlySpan slice, int size, int repeat) { for (int i = 0; i < 4; i++) { - var systemBlock = disk.Length == 0x3DEC800 ? (systemBlocks[i] + 2) ^ 1 : (systemBlocks[i] + 2); - var systemOffset = systemBlock * 0x4D08; + int systemBlock = disk.Length == 0x3DEC800 ? (systemBlocks[i] + 2) ^ 1 : (systemBlocks[i] + 2); + int systemOffset = systemBlock * 0x4D08; ret[systemBlocks[i] + 2] = 1; if (disk[systemOffset + 0x00] != 0x00) continue; if (disk[systemOffset + 0x01] != 0x00) continue; @@ -365,7 +365,7 @@ static bool RepeatCheck(ReadOnlySpan slice, int size, int repeat) for (int i = 0; i < 2; i++) { - var diskIdOffset = (14 + i) * 0x4D08; + int diskIdOffset = (14 + i) * 0x4D08; ret[14 + i] = 1; if (!RepeatCheck(new(disk, diskIdOffset, 0xE8 * 0x55), 0xE8, 0x55)) continue; ret[14 + i] = 0; @@ -411,17 +411,17 @@ private static (byte[] Disk, byte[] Error) TransformDisk(byte[] disk) if (disk.Length != 0x3DEC800) return default; // need the error table for this - var errorTable = CreateErrorTable(disk); + byte[] errorTable = CreateErrorTable(disk); // "system area check" - var systemCheck = false; - var systemBlocks = new[] { 9, 8, 1, 0 }; - var systemOffset = 0; + bool systemCheck = false; + int[] systemBlocks = new[] { 9, 8, 1, 0 }; + int systemOffset = 0; for (int i = 0; i < 4; i++) { if (errorTable[12] == 0) { - var systemBlock = systemBlocks[i] + 2; + int systemBlock = systemBlocks[i] + 2; if (errorTable[systemBlock] == 0) { systemCheck = true; @@ -430,7 +430,7 @@ private static (byte[] Disk, byte[] Error) TransformDisk(byte[] disk) } else { - var systemBlock = systemBlocks[i]; + int systemBlock = systemBlocks[i]; if (errorTable[systemBlock] == 0) { systemCheck = true; @@ -441,31 +441,31 @@ private static (byte[] Disk, byte[] Error) TransformDisk(byte[] disk) if (!systemCheck) return default; - var dataFormat = new ReadOnlySpan(disk, systemOffset, 0xE8); + ReadOnlySpan dataFormat = new(disk, systemOffset, 0xE8); - var diskIndex = 0; - var ret = new byte[0x435B0C0]; + int diskIndex = 0; + byte[] ret = new byte[0x435B0C0]; - var type = dataFormat[5] & 0xF; - var vzone = 0; + int type = dataFormat[5] & 0xF; + int vzone = 0; for (int lba = 0; lba < 0x10DC; lba++) { if (lba >= _vzoneLbaTable[type, vzone]) vzone++; - var pzoneCalc = _vzone2pzoneTable[type, vzone]; - var headCalc = pzoneCalc > 7; + int pzoneCalc = _vzone2pzoneTable[type, vzone]; + bool headCalc = pzoneCalc > 7; - var lba_vzone = lba; + int lba_vzone = lba; if (vzone > 0) lba_vzone -= _vzoneLbaTable[type, vzone - 1]; - var trackStart = _trackPhysicalTable[headCalc ? pzoneCalc - 8 : pzoneCalc]; - var trackCalc = _trackPhysicalTable[pzoneCalc]; + int trackStart = _trackPhysicalTable[headCalc ? pzoneCalc - 8 : pzoneCalc]; + int trackCalc = _trackPhysicalTable[pzoneCalc]; if (headCalc) trackCalc -= (lba_vzone >> 1); else trackCalc += (lba_vzone >> 1); - var defectOffset = 0; + int defectOffset = 0; if (pzoneCalc > 0) defectOffset = dataFormat[8 + pzoneCalc - 1]; - var defectAmount = dataFormat[8 + pzoneCalc] - defectOffset; + int defectAmount = dataFormat[8 + pzoneCalc] - defectOffset; while ((defectAmount != 0) && ((dataFormat[0x20 + defectOffset] + trackStart) <= trackCalc)) { @@ -474,13 +474,13 @@ private static (byte[] Disk, byte[] Error) TransformDisk(byte[] disk) defectAmount--; } - var blockCalc = ((lba & 3) == 0 || (lba & 3) == 3) ? 0 : 1; + int blockCalc = ((lba & 3) is 0 or 3) ? 0 : 1; - var offsetCalc = _startOffsetTable[pzoneCalc]; + int offsetCalc = _startOffsetTable[pzoneCalc]; offsetCalc += (trackCalc - trackStart) * _blockSizeTable[headCalc ? pzoneCalc - 7 : pzoneCalc] * 2; offsetCalc += _blockSizeTable[headCalc ? pzoneCalc - 7 : pzoneCalc] * blockCalc; - var blockSize = _blockSizeTable[headCalc ? pzoneCalc - 7 : pzoneCalc]; + int blockSize = _blockSizeTable[headCalc ? pzoneCalc - 7 : pzoneCalc]; for (int i = 0; i < blockSize; i++) { ret[offsetCalc + i] = disk[diskIndex++]; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/BsnesApi.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/BsnesApi.cs index 20e40fb15fd..f95c67a3bae 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/BsnesApi.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/BsnesApi.cs @@ -107,15 +107,9 @@ public partial class BsnesApi : IDisposable, IMonitor, IStatable private readonly ICallingConventionAdapter _adapter; private bool _disposed; - public void Enter() - { - exe.Enter(); - } + public void Enter() => exe.Enter(); - public void Exit() - { - exe.Exit(); - } + public void Exit() => exe.Exit(); private readonly List _readonlyFiles = new(); @@ -297,8 +291,7 @@ public void Seal() public bool AvoidRewind => false; - public void SaveStateBinary(BinaryWriter writer) - { + public void SaveStateBinary(BinaryWriter writer) => // commented code left for debug purposes; created savestates are native bsnes savestates // and therefor compatible across minor core updates @@ -307,7 +300,6 @@ public void SaveStateBinary(BinaryWriter writer) // core.snes_serialize(serializedData, serializedSize); // writer.Write(serializedData); exe.SaveStateBinary(writer); - } public void LoadStateBinary(BinaryReader reader) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/BsnesControllers.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/BsnesControllers.cs index c2b785b1781..3a92a1b7592 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/BsnesControllers.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/BsnesControllers.cs @@ -64,10 +64,7 @@ public BsnesControllers(BsnesCore.SnesSyncSettings ss, bool subframe = false) Definition.MakeImmutable(); } - public short CoreInputPoll(IController controller, int port, int index, int id) - { - return _ports[port].GetState(_mergers[port].UnMerge(controller), index, id); - } + public short CoreInputPoll(IController controller, int port, int index, int id) => _ports[port].GetState(_mergers[port].UnMerge(controller), index, id); } public interface IBsnesController diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/BsnesCore.IDebuggable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/BsnesCore.IDebuggable.cs index 07ae55aadcf..a06b3921338 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/BsnesCore.IDebuggable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/BsnesCore.IDebuggable.cs @@ -13,7 +13,7 @@ public IDictionary GetCpuFlagsAndRegisters() CpuRegisters registers = default; Api.core.snes_get_cpu_registers(ref registers); - var flags = (RegisterFlags) registers.p; + RegisterFlags flags = (RegisterFlags) registers.p; bool fc = (flags & RegisterFlags.C) != 0; bool fz = (flags & RegisterFlags.Z) != 0; @@ -50,24 +50,17 @@ public IDictionary GetCpuFlagsAndRegisters() }; } - public void SetCpuRegister(string register, int value) - { - Api.core.snes_set_cpu_register(register, (uint) value); - } + public void SetCpuRegister(string register, int value) => Api.core.snes_set_cpu_register(register, (uint)value); public IMemoryCallbackSystem MemoryCallbacks { get; } = new MemoryCallbackSystem(null); public bool CanStep(StepType type) { - switch (type) + return type switch { - case StepType.Into: - case StepType.Over: - case StepType.Out: - return true; - default: - return false; - } + StepType.Into or StepType.Over or StepType.Out => true, + _ => false, + }; } public void Step(StepType type) diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/BsnesCore.IEmulator.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/BsnesCore.IEmulator.cs index 02668bd7d03..d0e6a903f03 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/BsnesCore.IEmulator.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/BsnesCore.IEmulator.cs @@ -65,7 +65,7 @@ internal void FrameAdvancePost() private int UpdateAudioBuffer() { - var rawAudioBuffer = Api.core.snes_get_audiobuffer_and_size(out var size); + var rawAudioBuffer = Api.core.snes_get_audiobuffer_and_size(out int size); if (size == 0) return 0; if (size > _audioBuffer.Length) _audioBuffer = new short[size]; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/BsnesCore.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/BsnesCore.IMemoryDomains.cs index 363fa9b1d95..ef5c11f83ba 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/BsnesCore.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/BsnesCore.IMemoryDomains.cs @@ -13,7 +13,7 @@ private void SetMemoryDomains() List mm = new(); foreach (int i in Enum.GetValues(typeof(BsnesApi.SNES_MEMORY))) { - var data = Api.core.snes_get_memory_region(i, out var size, out var wordSize); + var data = Api.core.snes_get_memory_region(i, out int size, out int wordSize); if (data == IntPtr.Zero) continue; if (i == (int) BsnesApi.SNES_MEMORY.CARTRAM) { @@ -34,7 +34,7 @@ private void SetMemoryDomains() { foreach (int i in Enum.GetValues(typeof(BsnesApi.SGB_MEMORY))) { - var data = Api.core.snes_get_sgb_memory_region(i, out var size); + var data = Api.core.snes_get_sgb_memory_region(i, out int size); if (data == IntPtr.Zero || size == 0) continue; mm.Add(new MemoryDomainIntPtrMonitor("SGB " + Enum.GetName(typeof(BsnesApi.SGB_MEMORY), i), MemoryDomain.Endian.Little, data, size, true, 1, Api)); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/BsnesCore.ISettable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/BsnesCore.ISettable.cs index c82aac4d190..719d1c20934 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/BsnesCore.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/BsnesCore.ISettable.cs @@ -20,24 +20,18 @@ public enum SATELLAVIEW_CARTRIDGE Rom_Tsuri } - public SnesSettings GetSettings() - { - return _settings with {}; - } + public SnesSettings GetSettings() => _settings with { }; SNES.IBSNESForGfxDebugger.SettingsObj SNES.IBSNESForGfxDebugger.GetSettings() => GetSettings(); - public SnesSyncSettings GetSyncSettings() - { - return _syncSettings with {}; - } + public SnesSyncSettings GetSyncSettings() => _syncSettings with { }; public PutSettingsDirtyBits PutSettings(SnesSettings o) { if (o != _settings) { - var enables = new BsnesApi.LayerEnables + BsnesApi.LayerEnables enables = new() { BG1_Prio0 = o.ShowBG1_0, BG1_Prio1 = o.ShowBG1_1, diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/BsnesCore.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/BsnesCore.cs index 4e4c748aea4..3b2b8315125 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/BsnesCore.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/BsnesCore.cs @@ -21,7 +21,7 @@ public partial class BsnesCore : IEmulator, IDebuggable, IVideoProvider, ISaveRa public BsnesCore(CoreLoadParameters loadParameters) : this(loadParameters, false) { } public BsnesCore(CoreLoadParameters loadParameters, bool subframe = false) { - var ser = new BasicServiceProvider(this); + BasicServiceProvider ser = new(this); ServiceProvider = ser; this._romPath = Path.ChangeExtension(loadParameters.Roms[0].RomPath, null); @@ -97,7 +97,7 @@ public BsnesCore(CoreLoadParameters loadParamete } else if (SystemId is VSystemID.Raw.Satellaview) { - SATELLAVIEW_CARTRIDGE slottedCartridge = _syncSettings.SatellaviewCartridge; + var slottedCartridge = _syncSettings.SatellaviewCartridge; if (slottedCartridge == SATELLAVIEW_CARTRIDGE.Autodetect) { if (loadParameters.Game.NotInDatabase) @@ -219,10 +219,7 @@ private string snes_path_request(int slot, string hint, bool required) /// meaningless for most controllers. for multitap, 0-3 for which multitap controller /// button ID enum; in the case of a regular controller, this corresponds to shift register position /// for regular controllers, one bit D0 of button status. for other controls, varying ranges depending on id - private short snes_input_poll(int port, int index, int id) - { - return _controllers.CoreInputPoll(_controller, port, index, id); - } + private short snes_input_poll(int port, int index, int id) => _controllers.CoreInputPoll(_controller, port, index, id); private void snes_no_lag(bool sgbPoll) { @@ -233,10 +230,7 @@ private void snes_no_lag(bool sgbPoll) } } - private void snes_controller_latch() - { - InputCallbacks.Call(); - } + private void snes_controller_latch() => InputCallbacks.Call(); private readonly int[] palette = new int[0x8000]; @@ -312,10 +306,7 @@ private unsafe void snes_video_refresh(IntPtr data, int width, int height, int p } } - private void InitAudio() - { - _soundProvider = new SimpleSyncSoundProvider(); - } + private void InitAudio() => _soundProvider = new SimpleSyncSoundProvider(); private void snes_trace(string disassembly, string registerInfo) => _tracer.Put(new(disassembly: disassembly, registerInfo: registerInfo)); @@ -366,14 +357,8 @@ private long snes_time() private FileStream _currentMsuTrack; - private void msu_seek(long offset, bool relative) - { - _currentMsuTrack?.Seek(offset, relative ? SeekOrigin.Current : SeekOrigin.Begin); - } - private byte msu_read() - { - return (byte) (_currentMsuTrack?.ReadByte() ?? 0); - } + private void msu_seek(long offset, bool relative) => _currentMsuTrack?.Seek(offset, relative ? SeekOrigin.Current : SeekOrigin.Begin); + private byte msu_read() => (byte)(_currentMsuTrack?.ReadByte() ?? 0); private void msu_open(ushort trackId) { @@ -387,9 +372,6 @@ private void msu_open(ushort trackId) _currentMsuTrack = null; } } - private bool msu_end() - { - return _currentMsuTrack.Position == _currentMsuTrack.Length; - } + private bool msu_end() => _currentMsuTrack.Position == _currentMsuTrack.Length; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/SNESGraphicsDecoder.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/SNESGraphicsDecoder.cs index 2eec906e1d1..3f9680b7081 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/SNESGraphicsDecoder.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/SNESGraphicsDecoder.cs @@ -10,7 +10,7 @@ namespace BizHawk.Emulation.Cores.Nintendo.BSNES public sealed unsafe class SNESGraphicsDecoder : ISNESGraphicsDecoder { [StructLayout(LayoutKind.Sequential)] - public struct Object // size: 10 bytes; equivalent to the c++ version + public readonly struct Object // size: 10 bytes; equivalent to the c++ version { public readonly ushort x; public readonly byte y; @@ -144,10 +144,7 @@ private void CacheTilesMode7ExtBg() cachedTiles[4][i] = (byte)(cachedTiles[3][i] & 0x7F); } - public int Colorize(int rgb555) - { - return palette[rgb555]; - } + public int Colorize(int rgb555) => palette[rgb555]; public void Colorize(int* buf, int offset, int numpixels) { @@ -255,7 +252,7 @@ public void Exit() public TileEntry[] FetchMode7Tilemap() { - var buf = new TileEntry[128*128]; + TileEntry[] buf = new TileEntry[128*128]; for (int tidx = 0; tidx < 128 * 128; tidx++) { buf[tidx].address = tidx * 2; @@ -267,7 +264,7 @@ public TileEntry[] FetchMode7Tilemap() public TileEntry[] FetchTilemap(int addr, ScreenSize size) { - Dimensions blockDimensions = SizeInBlocksForBGSize(size); + var blockDimensions = SizeInBlocksForBGSize(size); int realWidth = blockDimensions.Width * 32; int realHeight = blockDimensions.Height * 32; TileEntry[] buf = new TileEntry[realWidth*realHeight]; @@ -349,7 +346,7 @@ public void RenderSpriteToScreen( byte[,] spriteMap) { oam ??= new OAMInfo(objects, si, spritenum); - Size dim = ObjSizes[si.OBSEL_Size, oam.Size ? 1 : 0]; + var dim = ObjSizes[si.OBSEL_Size, oam.Size ? 1 : 0]; byte[] cachedTileBuffer = cachedTiles[bppArrayIndex[4]]; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/SubBsnesCore.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/SubBsnesCore.cs index f84cf5c905e..6edf6240a42 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/SubBsnesCore.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/BSNES/SubBsnesCore.cs @@ -94,15 +94,9 @@ public bool FrameAdvance(IController controller, bool render, bool renderSound = public bool DeterministicEmulation => _bsnesCore.DeterministicEmulation; - public void ResetCounters() - { - _bsnesCore.ResetCounters(); - } + public void ResetCounters() => _bsnesCore.ResetCounters(); - public void Dispose() - { - _bsnesCore.Dispose(); - } + public void Dispose() => _bsnesCore.Dispose(); public long CycleCount => _bsnesCore.Api.core.snes_get_executed_cycles(); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Faust/Faust.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Faust/Faust.cs index 1eb073a93cd..9a1c0515c41 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Faust/Faust.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Faust/Faust.cs @@ -18,7 +18,7 @@ public static NymaSettingsInfo CachedSettingsInfo(CoreComm comm) { if (_cachedSettingsInfo is null) { - using var n = new Faust(comm); + using Faust n = new(comm); n.InitForSettingsInfo("faust.wbx"); _cachedSettingsInfo = n.SettingsInfo.Clone(); } @@ -42,13 +42,13 @@ public Faust(GameInfo game, byte[] rom, CoreComm comm, string extension, protected override HashSet ComputeHiddenPorts() { - var devCount = 8; + int devCount = 8; if (SettingsQuery("snes_faust.input.sport1.multitap") != "1") devCount -= 3; if (SettingsQuery("snes_faust.input.sport2.multitap") != "1") devCount -= 3; - var ret = new HashSet(); - for (var i = 1; i <= 8; i++) + HashSet ret = new(); + for (int i = 1; i <= 8; i++) { if (i > devCount) ret.Add($"port{i}"); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.IDebuggable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.IDebuggable.cs index f09a6eb44ca..8413c145065 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.IDebuggable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.IDebuggable.cs @@ -9,10 +9,10 @@ public partial class MGBAHawk : IDebuggable { public IDictionary GetCpuFlagsAndRegisters() { - var values = new int[RegisterNames.Length]; + int[] values = new int[RegisterNames.Length]; LibmGBA.BizGetRegisters(Core, values); - var ret = new Dictionary(); - for (var i = 0; i < RegisterNames.Length; i++) + Dictionary ret = new(); + for (int i = 0; i < RegisterNames.Length; i++) { ret[RegisterNames[i]] = new(values[i]); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.IMemoryDomains.cs index 3c1dcdd0f59..db9c314ef78 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.IMemoryDomains.cs @@ -23,7 +23,7 @@ private void CreateMemoryDomains(int romsize) { const MemoryDomain.Endian le = MemoryDomain.Endian.Little; - var mm = new List + List mm = new() { (_iwram = new MemoryDomainIntPtr("IWRAM", le, IntPtr.Zero, 32 * 1024, true, 4)), (_ewram = new MemoryDomainIntPtr("EWRAM", le, IntPtr.Zero, 256 * 1024, true, 4)), @@ -41,13 +41,13 @@ private void CreateMemoryDomains(int romsize) new MemoryDomainDelegate("System Bus", 0x10000000, le, addr => { - var a = (uint)addr; + uint a = (uint)addr; if (a >= 0x10000000) throw new ArgumentOutOfRangeException(paramName: nameof(addr), a, message: "address out of range"); return LibmGBA.BizReadBus(Core, a); }, (addr, val) => { - var a = (uint)addr; + uint a = (uint)addr; if (a >= 0x10000000) throw new ArgumentOutOfRangeException(paramName: nameof(addr), a, message: "address out of range"); LibmGBA.BizWriteBus(Core, a, val); }, 4) @@ -106,14 +106,8 @@ private void WireMemoryDomainPointers() }; } - private unsafe byte PeekWRAM(IntPtr xwram, long addr) - { - return ((byte*)xwram)[addr]; - } + private unsafe byte PeekWRAM(IntPtr xwram, long addr) => ((byte*)xwram)[addr]; - private unsafe void PokeWRAM(IntPtr xwram, long addr, byte value) - { - ((byte*)xwram)[addr] = value; - } + private unsafe void PokeWRAM(IntPtr xwram, long addr, byte value) => ((byte*)xwram)[addr] = value; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.ISaveRam.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.ISaveRam.cs index bd9decc3153..1142522c14e 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.ISaveRam.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.ISaveRam.cs @@ -25,7 +25,7 @@ public byte[] CloneSaveRam() return null; } - var ret = new byte[len]; + byte[] ret = new byte[len]; Array.Copy(_saveScratch, ret, len); return ret; } @@ -47,7 +47,7 @@ public void StoreSaveRam(byte[] data) private static byte[] LegacyFix(byte[] saveram) { // at one point vbanext-hawk had a special saveram format which we want to load. - var br = new BinaryReader(new MemoryStream(saveram, false)); + BinaryReader br = new(new MemoryStream(saveram, false)); br.ReadBytes(8); // header; int flashSize = br.ReadInt32(); int eepromsize = br.ReadInt32(); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.ISettable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.ISettable.cs index 50743453177..8afa734bf04 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.ISettable.cs @@ -32,7 +32,7 @@ public PutSettingsDirtyBits PutSettings(Settings o) if (o.PlayChB) smask |= LibmGBA.Sounds.CHB; LibmGBA.BizSetSoundMask(Core, smask); - var palette = new int[65536]; + int[] palette = new int[65536]; var c = o.ColorType switch { Settings.ColorTypes.SameBoy => GBColors.ColorType.sameboy, @@ -45,7 +45,7 @@ public PutSettingsDirtyBits PutSettings(Settings o) _ => GBColors.ColorType.vivid, }; GBColors.GetLut(c, palette, agb: true); - for (var i = 32768; i < 65536; i++) + for (int i = 32768; i < 65536; i++) palette[i] = palette[i - 32768]; LibmGBA.BizSetPalette(Core, palette); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.ISoundProvider.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.ISoundProvider.cs index 2981dc7e086..5fd0012ee56 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.ISoundProvider.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.ISoundProvider.cs @@ -29,14 +29,8 @@ public void GetSamplesSync(out short[] samples, out int nsamp) DiscardSamples(); } - public void GetSamplesAsync(short[] samples) - { - throw new InvalidOperationException("Async mode is not supported."); - } + public void GetSamplesAsync(short[] samples) => throw new InvalidOperationException("Async mode is not supported."); - public void DiscardSamples() - { - _nsamp = 0; - } + public void DiscardSamples() => _nsamp = 0; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.IStatable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.IStatable.cs index 8257bdfe78e..ebc5cb44557 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.IStatable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.IStatable.cs @@ -13,7 +13,7 @@ public partial class MGBAHawk : IStatable public void SaveStateBinary(BinaryWriter writer) { - if (!LibmGBA.BizStartGetState(Core, out var p, out var size)) + if (!LibmGBA.BizStartGetState(Core, out var p, out int size)) { throw new InvalidOperationException("Core failed to save!"); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.ITraceable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.ITraceable.cs index 4e9b624e1df..ae947548450 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.ITraceable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.ITraceable.cs @@ -12,16 +12,16 @@ public partial class MGBAHawk private void MakeTrace(string msg) { - var disasm = msg.Split('|')[1]; - var split = disasm.Split(':'); - var machineCode = split[0].PadLeft(8); - var instruction = split[1].Trim(); + string disasm = msg.Split('|')[1]; + string[] split = disasm.Split(':'); + string machineCode = split[0].PadLeft(8); + string instruction = split[1].Trim(); var regs = GetCpuFlagsAndRegisters(); - var wordSize = (regs["CPSR"].Value & 32) == 0 ? 4UL : 2UL; - var pc = regs["R15"].Value - wordSize * 2; - var sb = new StringBuilder(); + ulong wordSize = (regs["CPSR"].Value & 32) == 0 ? 4UL : 2UL; + ulong pc = regs["R15"].Value - wordSize * 2; + StringBuilder sb = new(); - for (var i = 0; i < RegisterNames.Length; i++) + for (int i = 0; i < RegisterNames.Length; i++) { sb.Append($" { RegisterNames[i] }:{ regs[RegisterNames[i]].Value:X8}"); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.cs index a13a85fa0ab..cb57095ccbe 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAHawk.cs @@ -14,7 +14,7 @@ public partial class MGBAHawk static MGBAHawk() { - var resolver = new DynamicLibraryImportResolver( + DynamicLibraryImportResolver resolver = new( OSTailoredCode.IsUnixHost ? "libmgba.dll.so" : "mgba.dll", hasLimitedLifetime: false); LibmGBA = BizInvoker.GetInvoker(resolver, CallingConventionAdapters.Native); } @@ -27,12 +27,12 @@ public MGBAHawk(CoreLoadParameters lp) _syncSettings = lp.SyncSettings ?? new(); _settings = lp.Settings ?? new(); - var bios = lp.Comm.CoreFileProvider.GetFirmware(new("GBA", "Bios")); + byte[] bios = lp.Comm.CoreFileProvider.GetFirmware(new("GBA", "Bios")); if (bios is { Length: not 0x4000 }) throw new InvalidOperationException("BIOS must be exactly 16384 bytes!"); if (lp.DeterministicEmulationRequested && bios is null) throw new MissingFirmwareException("A BIOS is required for deterministic recordings!"); DeterministicEmulation = lp.DeterministicEmulationRequested || (bios is not null && !_syncSettings.RTCUseRealTime); // in this case, the core is deterministic even though it wasn't asked to be - var rom = lp.Roms[0].FileData; + byte[] rom = lp.Roms[0].FileData; var overrides = GetOverrideInfo(_syncSettings); Core = LibmGBA.BizCreate( @@ -52,7 +52,7 @@ public MGBAHawk(CoreLoadParameters lp) try { CreateMemoryDomains(rom.Length); - var ser = new BasicServiceProvider(this); + BasicServiceProvider ser = new(this); ser.Register(new ArmV4Disassembler()); ser.Register(_memoryDomains); @@ -78,7 +78,7 @@ public MGBAHawk(CoreLoadParameters lp) private static LibmGBA.OverrideInfo GetOverrideInfo(SyncSettings syncSettings) { - var ret = new LibmGBA.OverrideInfo + LibmGBA.OverrideInfo ret = new() { Savetype = syncSettings.OverrideSaveType, Hardware = LibmGBA.Hardware.None, diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAMemoryCallbackSystem.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAMemoryCallbackSystem.cs index 9e536250995..05b08928181 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAMemoryCallbackSystem.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBA/MGBAMemoryCallbackSystem.cs @@ -64,7 +64,7 @@ public void Add(IMemoryCallback callback) throw new NotImplementedException("Non 0xFFFFFFFF address masks are not currently implemented."); } - var container = new CallbackContainer(callback); + CallbackContainer container = new(callback); if (container.Callback.Type == MemoryCallbackType.Execute) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Audio.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Audio.cs index aef73aec305..dfb9d1e6507 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Audio.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Audio.cs @@ -12,8 +12,8 @@ public class Audio : ISoundProvider { public GBHawk Core { get; set; } - private BlipBuffer _blip_L = new BlipBuffer(15000); - private BlipBuffer _blip_R = new BlipBuffer(15000); + private BlipBuffer _blip_L = new(15000); + private BlipBuffer _blip_R = new(15000); public static readonly bool[] DUTY_CYCLES = { false, false, false, false, false, false, false, true, true, false, false, false, false, false, false, true, @@ -772,7 +772,7 @@ public void tick() } // clock the sweep - if ((sequencer_swp == 0) || (sequencer_swp == 4)) + if (sequencer_swp is 0 or 4) { SQ1_intl_swp_cnt--; if ((SQ1_intl_swp_cnt == 0) && SQ1_swp_enable) @@ -1222,10 +1222,7 @@ public void GetSamplesSync(out short[] samples, out int nsamp) master_audio_clock = 0; } - public void GetSamplesAsync(short[] samples) - { - throw new NotSupportedException("Async is not available"); - } + public void GetSamplesAsync(short[] samples) => throw new NotSupportedException("Async is not available"); public void DiscardSamples() { @@ -1234,10 +1231,12 @@ public void DiscardSamples() master_audio_clock = 0; } + #pragma warning disable IDE0051 private void GetSamples(short[] samples) { } + #pragma warning restore IDE0051 public void DisposeSound() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBA_Init_State.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBA_Init_State.cs index baafbf52aea..eec1b0be2aa 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBA_Init_State.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBA_Init_State.cs @@ -4,7 +4,7 @@ namespace BizHawk.Emulation.Cores.Nintendo.GBHawk { public partial class GBHawk { - static byte[] GBA_Init_RAM = + static readonly byte[] GBA_Init_RAM = { 0xCA, 0x2F, 0x9B, 0xEE, 0x95, 0xCF, 0x1E, 0x5F, 0xE2, 0x7D, 0x59, 0xFE, 0xBE, 0x5D, 0xFA, 0x9D, 0x6A, 0x85, 0xA7, 0x33, 0x33, 0x5C, 0x4F, 0x7D, 0x7F, 0xEC, 0xBF, 0x6E, 0xFF, 0xE1, 0xC2, 0x7D, diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBC_GB_PPU.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBC_GB_PPU.cs index 85581c19b76..e2ed9ecb4b7 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBC_GB_PPU.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBC_GB_PPU.cs @@ -528,10 +528,7 @@ public override void tick() // scanline callback if ((LY + LY_inc) == Core._scanlineCallbackLine) { - if (Core._scanlineCallback != null) - { - Core._scanlineCallback(LCDC); - } + Core._scanlineCallback?.Invoke(LCDC); } cycle = 0; @@ -613,7 +610,7 @@ public override void tick() if (!STAT.Bit(5)) { VBL_INT = false; } } - if ((cycle >= 2) && (cycle < 4)) + if (cycle is >= 2 and < 4) { // there is an edge case where a VBL INT is triggered if STAT bit 5 is set if (STAT.Bit(5)) { VBL_INT = true; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBC_PPU.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBC_PPU.cs index 84d8bb7562d..c6ef86ae875 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBC_PPU.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBC_PPU.cs @@ -529,10 +529,7 @@ public override void tick() // scanline callback if ((LY + LY_inc) == Core._scanlineCallbackLine) { - if (Core._scanlineCallback != null) - { - Core._scanlineCallback(LCDC); - } + Core._scanlineCallback?.Invoke(LCDC); } cycle = 0; @@ -616,7 +613,7 @@ public override void tick() if (!STAT.Bit(5)) { VBL_INT = false; } } - if ((cycle >= 2) && (cycle < 4)) + if (cycle is >= 2 and < 4) { // there is an edge case where a VBL INT is triggered if STAT bit 5 is set if (STAT.Bit(5)) { VBL_INT = true; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawk.ICodeDataLog.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawk.ICodeDataLog.cs index f55e94cd005..2c0e5bab871 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawk.ICodeDataLog.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawk.ICodeDataLog.cs @@ -66,11 +66,11 @@ private void CDLCpuCallback(ushort addr, LR35902.eCDLogMemFlags flags) return; } } - else if ((addr >= 0xE000) && (addr < 0xF000)) + else if (addr is >= 0xE000 and < 0xF000) { SetCDL(flags, "WRAM", addr - 0xE000); } - else if ((addr >= 0xF000) && (addr < 0xFE00)) + else if (addr is >= 0xF000 and < 0xFE00) { SetCDL(flags, "WRAM", (RAM_Bank * 0x1000) + (addr - 0xF000)); } @@ -78,7 +78,7 @@ private void CDLCpuCallback(ushort addr, LR35902.eCDLogMemFlags flags) { return; } - else if ((addr >= 0xFF00) && (addr < 0xFF80)) // The game GOAL! Requires Hardware Regs to be accessible + else if (addr is >= 0xFF00 and < 0xFF80) // The game GOAL! Requires Hardware Regs to be accessible { return; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawk.IEmulator.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawk.IEmulator.cs index 49eeb27e633..73cee601cac 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawk.IEmulator.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawk.IEmulator.cs @@ -360,10 +360,7 @@ public void GetControllerState(IController controller) (Acc_X_state, Acc_Y_state) = _controllerDeck.ReadAcc1(controller); } - public byte GetButtons(ushort r) - { - return input_register; - } + public byte GetButtons(ushort r) => input_register; public byte GetIntRegs(ushort r) { @@ -419,10 +416,7 @@ public void ResetCounters() _islag = false; } - public void Dispose() - { - audio.DisposeSound(); - } + public void Dispose() => audio.DisposeSound(); public int[] frame_buffer; @@ -430,10 +424,7 @@ public void Dispose() public uint[] vid_buffer; - public int[] GetVideoBuffer() - { - return frame_buffer; - } + public int[] GetVideoBuffer() => frame_buffer; public void SendVideoBuffer() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawk.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawk.IMemoryDomains.cs index ec26712605d..0a5434908e4 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawk.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawk.IMemoryDomains.cs @@ -9,7 +9,7 @@ public partial class GBHawk public void SetupMemoryDomains() { - var domains = new List + List domains = new() { new MemoryDomainDelegate( "WRAM", @@ -57,7 +57,7 @@ public void SetupMemoryDomains() if (cart_RAM != null) { - var CartRam = new MemoryDomainDelegate( + MemoryDomainDelegate CartRam = new( "CartRAM", cart_RAM.Length, MemoryDomain.Endian.Little, diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawk.ISaveRam.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawk.ISaveRam.cs index d77ee0d3173..165c5be78fe 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawk.ISaveRam.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawk.ISaveRam.cs @@ -5,10 +5,7 @@ namespace BizHawk.Emulation.Cores.Nintendo.GBHawk { public partial class GBHawk : ISaveRam { - public byte[] CloneSaveRam() - { - return (byte[])cart_RAM?.Clone(); - } + public byte[] CloneSaveRam() => (byte[])cart_RAM?.Clone(); public void StoreSaveRam(byte[] data) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawk.ISettable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawk.ISettable.cs index 93956de7a6b..7aaf20ec603 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawk.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawk.ISettable.cs @@ -10,15 +10,9 @@ namespace BizHawk.Emulation.Cores.Nintendo.GBHawk { public partial class GBHawk : IEmulator, ISettable { - public GBSettings GetSettings() - { - return _settings.Clone(); - } + public GBSettings GetSettings() => _settings.Clone(); - public GBSyncSettings GetSyncSettings() - { - return _syncSettings.Clone(); - } + public GBSyncSettings GetSyncSettings() => _syncSettings.Clone(); public PutSettingsDirtyBits PutSettings(GBSettings o) { @@ -34,8 +28,8 @@ public PutSettingsDirtyBits PutSyncSettings(GBSyncSettings o) return ret ? PutSettingsDirtyBits.RebootCore : PutSettingsDirtyBits.None; } - public GBSettings _settings = new GBSettings(); - public GBSyncSettings _syncSettings = new GBSyncSettings(); + public GBSettings _settings = new(); + public GBSyncSettings _syncSettings = new(); public class GBSettings { @@ -71,10 +65,7 @@ public enum Cycle_Return [DefaultValue(true)] public bool UseRGBDSSyntax { get; set; } - public GBSettings Clone() - { - return (GBSettings)MemberwiseClone(); - } + public GBSettings Clone() => (GBSettings)MemberwiseClone(); public GBSettings() { @@ -131,20 +122,14 @@ public int RTCOffset [JsonIgnore] public ushort _DivInitialTime = 8; - public GBSyncSettings Clone() - { - return (GBSyncSettings)MemberwiseClone(); - } + public GBSyncSettings Clone() => (GBSyncSettings)MemberwiseClone(); public GBSyncSettings() { SettingsUtil.SetDefaultValues(this); } - public static bool NeedsReboot(GBSyncSettings x, GBSyncSettings y) - { - return !DeepEquality.DeepEquals(x, y); - } + public static bool NeedsReboot(GBSyncSettings x, GBSyncSettings y) => !DeepEquality.DeepEquals(x, y); } } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawk.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawk.cs index b3c68f1da41..f4c0ccd7d03 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawk.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawk.cs @@ -132,7 +132,7 @@ internal static class RomChecksums [CoreConstructor(VSystemID.Raw.GBC)] public GBHawk(CoreComm comm, GameInfo game, byte[] rom, /*string gameDbFn,*/ GBSettings settings, GBSyncSettings syncSettings, bool subframe = false) { - var ser = new BasicServiceProvider(this); + BasicServiceProvider ser = new(this); cpu = new LR35902 { @@ -188,13 +188,13 @@ public GBHawk(CoreComm comm, GameInfo game, byte[] rom, /*string gameDbFn,*/ GBS is_GB_in_GBC = true; // for movie files } - var romHashMD5 = MD5Checksum.ComputePrefixedHex(rom); + string romHashMD5 = MD5Checksum.ComputePrefixedHex(rom); Console.WriteLine(romHashMD5); - var romHashSHA1 = SHA1Checksum.ComputePrefixedHex(rom); + string romHashSHA1 = SHA1Checksum.ComputePrefixedHex(rom); Console.WriteLine(romHashSHA1); _rom = rom; - var mppr = Setup_Mapper(romHashMD5, romHashSHA1); + string mppr = Setup_Mapper(romHashMD5, romHashSHA1); if (cart_RAM != null) { cart_RAM_vbls = new byte[cart_RAM.Length]; } _controllerDeck = new(mppr is "MBC7" @@ -244,7 +244,7 @@ private uint[] SynthesizeFrontendBGPal() } else { - var scratch = new uint[4]; + uint[] scratch = new uint[4]; for (int i = 0; i < 4; i++) { scratch[i] = ppu.color_palette[(ppu.BGP >> (i * 2)) & 3]; @@ -265,7 +265,7 @@ private uint[] SynthesizeFrontendSPPal() } else { - var scratch = new uint[8]; + uint[] scratch = new uint[8]; for (int i = 0; i < 4; i++) { scratch[i] = ppu.color_palette[(ppu.obj_pal_0 >> (i * 2)) & 3]; @@ -307,7 +307,7 @@ public GPUMemoryAreas(byte[] vram, byte[] oam, uint[] sppal, uint[] bgpal) private IntPtr AddHandle(object target) { - var handle = GCHandle.Alloc(target, GCHandleType.Pinned); + GCHandle handle = GCHandle.Alloc(target, GCHandleType.Pinned); _handles.Add(handle); return handle.AddrOfPinnedObject(); } @@ -338,10 +338,7 @@ public void SetScanlineCallback(ScanlineCallback callback, int line) private PrinterCallback _printerCallback = null; #pragma warning restore CS0414 - public void SetPrinterCallback(PrinterCallback callback) - { - _printerCallback = null; - } + public void SetPrinterCallback(PrinterCallback callback) => _printerCallback = null; public DisplayType Region => DisplayType.NTSC; @@ -626,7 +623,7 @@ public string Setup_Mapper(string romHashMD5, string romHashSHA1) } // Sachen maper not known to have RAM - if ((mppr == "Schn1") || (mppr == "Schn2")) + if (mppr is "Schn1" or "Schn2") { cart_RAM = null; Use_MT = true; @@ -741,7 +738,7 @@ public class GBHawkDisassembler : VerifiedDisassembler public override string Disassemble(MemoryDomain m, uint addr, out int length) { - var ret = LR35902.Disassemble((ushort) addr, a => m.PeekByte(a), UseRGBDSSyntax, out var tmp); + string ret = LR35902.Disassemble((ushort) addr, a => m.PeekByte(a), UseRGBDSSyntax, out ushort tmp); length = tmp; return ret; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawkControllerDeck.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawkControllerDeck.cs index 7353fb98970..4f1f2c95ab4 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawkControllerDeck.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawkControllerDeck.cs @@ -32,10 +32,7 @@ public GBHawkControllerDeck(string controller1Name, bool subframe) Definition.MakeImmutable(); } - public byte ReadPort1(IController c) - { - return Port1.Read(c); - } + public byte ReadPort1(IController c) => Port1.Read(c); public (ushort X, ushort Y) ReadAcc1(IController c) => Port1.ReadAcc(c); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawkControllers.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawkControllers.cs index cb11d4de95e..14853092edd 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawkControllers.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GBHawkControllers.cs @@ -164,19 +164,19 @@ public byte Read(IController c) // acc x is the result of rotating around body y AFTER rotating around body x // therefore this control scheme gives decreasing sensitivity in X as Y rotation increases - var temp = (float) (Math.Cos(theta) * Math.Sin(phi)); + float temp = (float) (Math.Cos(theta) * Math.Sin(phi)); // additional acceleration components are dominated by axial components due to off axis rotation. // They vary widely based on physical hand movements, but this roughly matches what I observe in a real GBP - var temp2 = (float) ((phi - 2 * phi_prev + phi_prev_2) * 59.7275 * 59.7275 * 0.1); - var accX = (ushort) (0x8370 - Math.Floor(temp * 216) - temp2); + float temp2 = (float) ((phi - 2 * phi_prev + phi_prev_2) * 59.7275 * 59.7275 * 0.1); + ushort accX = (ushort) (0x8370 - Math.Floor(temp * 216) - temp2); // acc y is just the sine of the angle - var temp3 = (float) Math.Sin(theta); + float temp3 = (float) Math.Sin(theta); // here we add in the acceleration generated by the point of rotation being far away from the accelerometer // this term dominates other facators due to the cartridge being far from the players hands in whatever system is being used. // It roughly matches what I observe in a real GBP - var temp4 = (float) (Math.Pow((theta - theta_prev) * 59.7275, 2) * 0.15); - var accY = (ushort) (0x8370 - Math.Floor(temp3 * 216) + temp4); + float temp4 = (float) (Math.Pow((theta - theta_prev) * 59.7275, 2) * 0.15); + ushort accY = (ushort) (0x8370 - Math.Floor(temp3 * 216) + temp4); return (accX, accY); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GB_PPU.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GB_PPU.cs index de9635e99d2..dedd4463fa7 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GB_PPU.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/GB_PPU.cs @@ -61,7 +61,7 @@ public override void WriteReg(int addr, byte value) if (LCDC.Bit(7)) { - if (((STAT & 3) == 0) || ((STAT & 3) == 1)) + if ((STAT & 3) is 0 or 1) { LYC_INT = true; //if (Core.REG_FFFF.Bit(1)) { Core.cpu.FlagI = true; } @@ -151,10 +151,7 @@ public override void tick() // scanline callback if ((LY + LY_inc) == Core._scanlineCallbackLine) { - if (Core._scanlineCallback != null) - { - Core._scanlineCallback(LCDC); - } + Core._scanlineCallback?.Invoke(LCDC); } cycle = 0; @@ -227,7 +224,7 @@ public override void tick() if (!STAT.Bit(5)) { VBL_INT = false; } } - if ((cycle >= 2) && (cycle < 4)) + if (cycle is >= 2 and < 4) { // there is an edge case where a VBL INT is triggered if STAT bit 5 is set if (STAT.Bit(5)) { VBL_INT = true; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/HW_Registers.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/HW_Registers.cs index 9879b918835..4a8de758347 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/HW_Registers.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/HW_Registers.cs @@ -213,10 +213,10 @@ public byte Read_Registers(int addr) break; case 0xFF76: - var ret1 = audio.SQ1_output >= Audio.DAC_OFST + byte ret1 = audio.SQ1_output >= Audio.DAC_OFST ? (byte) (audio.SQ1_output - Audio.DAC_OFST) : (byte) 0; - var ret2 = audio.SQ2_output >= Audio.DAC_OFST + byte ret2 = audio.SQ2_output >= Audio.DAC_OFST ? (byte) (audio.SQ2_output - Audio.DAC_OFST) : (byte) 0; if (is_GBC) { ret = (byte)(ret1 | (ret2 << 4)); } @@ -224,10 +224,10 @@ public byte Read_Registers(int addr) break; case 0xFF77: - var retN = audio.NOISE_output >= Audio.DAC_OFST + byte retN = audio.NOISE_output >= Audio.DAC_OFST ? (byte) (audio.NOISE_output - Audio.DAC_OFST) : (byte) 0; - var retW = audio.WAVE_output >= Audio.DAC_OFST + byte retW = audio.WAVE_output >= Audio.DAC_OFST ? (byte) (audio.WAVE_output - Audio.DAC_OFST) : (byte) 0; if (is_GBC) { ret = (byte)(retN | (retW << 4)); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/MapperBase.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/MapperBase.cs index 12da082b14a..06add1986e8 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/MapperBase.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/MapperBase.cs @@ -7,25 +7,13 @@ public class MapperBase { public GBHawk Core { get; set; } - public virtual byte ReadMemoryLow(ushort addr) - { - return 0; - } + public virtual byte ReadMemoryLow(ushort addr) => 0; - public virtual byte ReadMemoryHigh(ushort addr) - { - return 0; - } + public virtual byte ReadMemoryHigh(ushort addr) => 0; - public virtual byte PeekMemoryLow(ushort addr) - { - return 0; - } + public virtual byte PeekMemoryLow(ushort addr) => 0; - public virtual byte PeekMemoryHigh(ushort addr) - { - return 0; - } + public virtual byte PeekMemoryHigh(ushort addr) => 0; public virtual void WriteMemory(ushort addr, byte value) { @@ -59,14 +47,8 @@ public virtual void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags) { } - protected void SetCDLROM(LR35902.eCDLogMemFlags flags, int cdladdr) - { - Core.SetCDL(flags, "ROM", cdladdr); - } + protected void SetCDLROM(LR35902.eCDLogMemFlags flags, int cdladdr) => Core.SetCDL(flags, "ROM", cdladdr); - protected void SetCDLRAM(LR35902.eCDLogMemFlags flags, int cdladdr) - { - Core.SetCDL(flags, "CartRAM", cdladdr); - } + protected void SetCDLRAM(LR35902.eCDLogMemFlags flags, int cdladdr) => Core.SetCDL(flags, "CartRAM", cdladdr); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_Camera.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_Camera.cs index ef49ffb4d25..c8703a3f373 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_Camera.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_Camera.cs @@ -84,10 +84,7 @@ public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags) } } - public override byte PeekMemoryLow(ushort addr) - { - return ReadMemoryLow(addr); - } + public override byte PeekMemoryLow(ushort addr) => ReadMemoryLow(addr); public override void WriteMemory(ushort addr, byte value) { @@ -132,10 +129,7 @@ public override void WriteMemory(ushort addr, byte value) } } - public override void PokeMemory(ushort addr, byte value) - { - WriteMemory(addr, value); - } + public override void PokeMemory(ushort addr, byte value) => WriteMemory(addr, value); public override void SyncState(Serializer ser) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_Default.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_Default.cs index 8f6560219bd..1f045eb6f35 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_Default.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_Default.cs @@ -10,10 +10,7 @@ public override void Reset() // nothing to initialize } - public override byte ReadMemoryLow(ushort addr) - { - return Core._rom[addr]; - } + public override byte ReadMemoryLow(ushort addr) => Core._rom[addr]; public override byte ReadMemoryHigh(ushort addr) { @@ -48,15 +45,9 @@ public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags) } } - public override byte PeekMemoryLow(ushort addr) - { - return ReadMemoryLow(addr); - } + public override byte PeekMemoryLow(ushort addr) => ReadMemoryLow(addr); - public override byte PeekMemoryHigh(ushort addr) - { - return ReadMemoryHigh(addr); - } + public override byte PeekMemoryHigh(ushort addr) => ReadMemoryHigh(addr); public override void WriteMemory(ushort addr, byte value) { @@ -73,9 +64,6 @@ public override void WriteMemory(ushort addr, byte value) } } - public override void PokeMemory(ushort addr, byte value) - { - WriteMemory(addr, value); - } + public override void PokeMemory(ushort addr, byte value) => WriteMemory(addr, value); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_HuC1.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_HuC1.cs index febbccf996e..157848a58a2 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_HuC1.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_HuC1.cs @@ -45,7 +45,7 @@ public override byte ReadMemoryLow(ushort addr) public override byte ReadMemoryHigh(ushort addr) { - if ((addr >= 0xA000) && (addr < 0xC000)) + if (addr is >= 0xA000 and < 0xC000) { if (RAM_enable) { @@ -88,7 +88,7 @@ public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags) { SetCDLROM(flags, (addr - 0x4000) + ROM_bank * 0x4000); } - else if ((addr >= 0xA000) && (addr < 0xC000)) + else if (addr is >= 0xA000 and < 0xC000) { if (RAM_enable) { @@ -119,10 +119,7 @@ public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags) } } - public override byte PeekMemoryLow(ushort addr) - { - return ReadMemoryLow(addr); - } + public override byte PeekMemoryLow(ushort addr) => ReadMemoryLow(addr); public override void WriteMemory(ushort addr, byte value) { @@ -173,10 +170,7 @@ public override void WriteMemory(ushort addr, byte value) } } - public override void PokeMemory(ushort addr, byte value) - { - WriteMemory(addr, value); - } + public override void PokeMemory(ushort addr, byte value) => WriteMemory(addr, value); public override void SyncState(Serializer ser) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_HuC3.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_HuC3.cs index de5d5d21328..ea7e6179919 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_HuC3.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_HuC3.cs @@ -58,7 +58,7 @@ public override byte ReadMemoryLow(ushort addr) public override byte ReadMemoryHigh(ushort addr) { - if ((control >= 0xB) && (control < 0xE)) + if (control is >= 0xB and < 0xE) { if (control == 0xD) { @@ -94,7 +94,7 @@ public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags) { SetCDLROM(flags, (addr - 0x4000) + ROM_bank * 0x4000); } - else if ((addr >= 0xA000) && (addr < 0xC000)) + else if (addr is >= 0xA000 and < 0xC000) { if (RAM_enable) { @@ -125,10 +125,7 @@ public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags) } } - public override byte PeekMemoryLow(ushort addr) - { - return ReadMemoryLow(addr); - } + public override byte PeekMemoryLow(ushort addr) => ReadMemoryLow(addr); public override void WriteMemory(ushort addr, byte value) { @@ -155,7 +152,7 @@ public override void WriteMemory(ushort addr, byte value) } else { - if ((control < 0xB) || (control > 0xE)) + if (control is < 0xB or > 0xE) { if (!RAM_enable) { @@ -247,10 +244,7 @@ public override void WriteMemory(ushort addr, byte value) } } - public override void RTC_Get(int value, int index) - { - time |= (uint)((value & 0xFF) << index); - } + public override void RTC_Get(int value, int index) => time |= (uint)((value & 0xFF) << index); public override void Mapper_Tick() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC1.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC1.cs index 6c42583d689..0ee13c8080c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC1.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC1.cs @@ -109,10 +109,7 @@ public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags) } } - public override byte PeekMemoryLow(ushort addr) - { - return ReadMemoryLow(addr); - } + public override byte PeekMemoryLow(ushort addr) => ReadMemoryLow(addr); public override void WriteMemory(ushort addr, byte value) { @@ -174,10 +171,7 @@ public override void WriteMemory(ushort addr, byte value) } } - public override void PokeMemory(ushort addr, byte value) - { - WriteMemory(addr, value); - } + public override void PokeMemory(ushort addr, byte value) => WriteMemory(addr, value); public override void SyncState(Serializer ser) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC1_Multi.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC1_Multi.cs index 3530095c705..f427b102d9f 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC1_Multi.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC1_Multi.cs @@ -111,10 +111,7 @@ public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags) } } - public override byte PeekMemoryLow(ushort addr) - { - return ReadMemoryLow(addr); - } + public override byte PeekMemoryLow(ushort addr) => ReadMemoryLow(addr); public override void WriteMemory(ushort addr, byte value) { @@ -176,10 +173,7 @@ public override void WriteMemory(ushort addr, byte value) } } - public override void PokeMemory(ushort addr, byte value) - { - WriteMemory(addr, value); - } + public override void PokeMemory(ushort addr, byte value) => WriteMemory(addr, value); public override void SyncState(Serializer ser) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC2.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC2.cs index 7d5649dd8a8..bcf5329acbb 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC2.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC2.cs @@ -33,7 +33,7 @@ public override byte ReadMemoryLow(ushort addr) public override byte ReadMemoryHigh(ushort addr) { - if ((addr >= 0xA000) && (addr < 0xA200)) + if (addr is >= 0xA000 and < 0xA200) { if (RAM_enable) { @@ -57,7 +57,7 @@ public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags) { SetCDLROM(flags, (addr - 0x4000) + ROM_bank * 0x4000); } - else if ((addr >= 0xA000) && (addr < 0xA200)) + else if (addr is >= 0xA000 and < 0xA200) { if (RAM_enable) { @@ -71,10 +71,7 @@ public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags) } } - public override byte PeekMemoryLow(ushort addr) - { - return ReadMemoryLow(addr); - } + public override byte PeekMemoryLow(ushort addr) => ReadMemoryLow(addr); public override void WriteMemory(ushort addr, byte value) { @@ -93,7 +90,7 @@ public override void WriteMemory(ushort addr, byte value) if (ROM_bank==0) { ROM_bank = 1; } } } - else if ((addr >= 0xA000) && (addr < 0xA200)) + else if (addr is >= 0xA000 and < 0xA200) { if (RAM_enable) { @@ -102,10 +99,7 @@ public override void WriteMemory(ushort addr, byte value) } } - public override void PokeMemory(ushort addr, byte value) - { - WriteMemory(addr, value); - } + public override void PokeMemory(ushort addr, byte value) => WriteMemory(addr, value); public override void SyncState(Serializer ser) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC3.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC3.cs index 75aaa686979..49581c21289 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC3.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC3.cs @@ -75,7 +75,7 @@ public override byte ReadMemoryHigh(ushort addr) } } - if ((RAM_bank >= 8) && (RAM_bank <= 0xC)) + if (RAM_bank is >= 8 and <= 0xC) { //Console.WriteLine("reg: " + (RAM_bank - 8) + " value: " + RTC_regs_latch[RAM_bank - 8] + " cpu: " + Core.cpu.TotalExecutedCycles); return RTC_regs_latch[RAM_bank - 8]; @@ -119,7 +119,7 @@ public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags) } } - if ((RAM_bank >= 8) && (RAM_bank <= 0xC)) + if (RAM_bank is >= 8 and <= 0xC) { return; } @@ -135,10 +135,7 @@ public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags) } } - public override byte PeekMemoryLow(ushort addr) - { - return ReadMemoryLow(addr); - } + public override byte PeekMemoryLow(ushort addr) => ReadMemoryLow(addr); public override byte PeekMemoryHigh(ushort addr) { @@ -155,7 +152,7 @@ public override byte PeekMemoryHigh(ushort addr) } } - if ((RAM_bank >= 8) && (RAM_bank <= 0xC)) + if (RAM_bank is >= 8 and <= 0xC) { //Console.WriteLine("reg: " + (RAM_bank - 8) + " value: " + RTC_regs_latch[RAM_bank - 8] + " cpu: " + Core.cpu.TotalExecutedCycles); return RTC_regs_latch[RAM_bank - 8]; @@ -212,7 +209,7 @@ public override void WriteMemory(ushort addr, byte value) Core.cart_RAM[(addr - 0xA000) + RAM_bank * 0x2000] = value; } } - else if ((RAM_bank >= 8) && (RAM_bank <= 0xC)) + else if (RAM_bank is >= 8 and <= 0xC) { // not all bits are writable switch (RAM_bank - 8) @@ -234,10 +231,7 @@ public override void WriteMemory(ushort addr, byte value) } } - public override void PokeMemory(ushort addr, byte value) - { - WriteMemory(addr, value); - } + public override void PokeMemory(ushort addr, byte value) => WriteMemory(addr, value); public override void RTC_Get(int value, int index) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC5.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC5.cs index 6b67f6c02d8..f4645142781 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC5.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC5.cs @@ -94,10 +94,7 @@ public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags) } } - public override byte PeekMemoryLow(ushort addr) - { - return ReadMemoryLow(addr); - } + public override byte PeekMemoryLow(ushort addr) => ReadMemoryLow(addr); public override void WriteMemory(ushort addr, byte value) { @@ -141,10 +138,7 @@ public override void WriteMemory(ushort addr, byte value) } } - public override void PokeMemory(ushort addr, byte value) - { - WriteMemory(addr, value); - } + public override void PokeMemory(ushort addr, byte value) => WriteMemory(addr, value); public override void SyncState(Serializer ser) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC6.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC6.cs index 3611dd14138..e731a47815a 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC6.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC6.cs @@ -60,10 +60,7 @@ public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags) } } - public override byte PeekMemoryLow(ushort addr) - { - return ReadMemoryLow(addr); - } + public override byte PeekMemoryLow(ushort addr) => ReadMemoryLow(addr); public override void WriteMemory(ushort addr, byte value) { @@ -80,9 +77,6 @@ public override void WriteMemory(ushort addr, byte value) } } - public override void PokeMemory(ushort addr, byte value) - { - WriteMemory(addr, value); - } + public override void PokeMemory(ushort addr, byte value) => WriteMemory(addr, value); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC7.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC7.cs index 69204039f84..734a433ee7b 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC7.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC7.cs @@ -123,10 +123,7 @@ public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags) } } - public override byte PeekMemoryLow(ushort addr) - { - return ReadMemoryLow(addr); - } + public override byte PeekMemoryLow(ushort addr) => ReadMemoryLow(addr); public override void WriteMemory(ushort addr, byte value) { @@ -161,10 +158,7 @@ public override void WriteMemory(ushort addr, byte value) } } - public override void PokeMemory(ushort addr, byte value) - { - WriteMemory(addr, value); - } + public override void PokeMemory(ushort addr, byte value) => WriteMemory(addr, value); public override void SyncState(Serializer ser) { @@ -426,11 +420,11 @@ private void EEPROM_write(byte value) break; case 5: - if ((instr_clocks >= 0) && (instr_clocks <= 7)) + if (instr_clocks is >= 0 and <= 7) { DO = ((Core.cart_RAM[EE_addr * 2 + 1] >> (7 - instr_clocks)) & 1) == 1; } - else if ((instr_clocks >= 8) && (instr_clocks <= 15)) + else if (instr_clocks is >= 8 and <= 15) { DO = ((Core.cart_RAM[EE_addr * 2] >> (15 - instr_clocks)) & 1) == 1; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MMM01.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MMM01.cs index d8047525605..a5b0a40642a 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MMM01.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MMM01.cs @@ -60,10 +60,7 @@ public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags) } } - public override byte PeekMemoryLow(ushort addr) - { - return ReadMemoryLow(addr); - } + public override byte PeekMemoryLow(ushort addr) => ReadMemoryLow(addr); public override void WriteMemory(ushort addr, byte value) { @@ -80,9 +77,6 @@ public override void WriteMemory(ushort addr, byte value) } } - public override void PokeMemory(ushort addr, byte value) - { - WriteMemory(addr, value); - } + public override void PokeMemory(ushort addr, byte value) => WriteMemory(addr, value); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_RockMan8.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_RockMan8.cs index 2cd2a9c92d5..ebfe95b2f11 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_RockMan8.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_RockMan8.cs @@ -32,10 +32,7 @@ public override byte ReadMemoryLow(ushort addr) } } - public override byte ReadMemoryHigh(ushort addr) - { - return 0xFF; - } + public override byte ReadMemoryHigh(ushort addr) => 0xFF; public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags) { @@ -55,14 +52,11 @@ public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags) } } - public override byte PeekMemoryLow(ushort addr) - { - return ReadMemoryLow(addr); - } + public override byte PeekMemoryLow(ushort addr) => ReadMemoryLow(addr); public override void WriteMemory(ushort addr, byte value) { - if ((addr >= 0x2000) && (addr < 0x4000)) + if (addr is >= 0x2000 and < 0x4000) { value &= 0x1F; @@ -73,10 +67,7 @@ public override void WriteMemory(ushort addr, byte value) } } - public override void PokeMemory(ushort addr, byte value) - { - WriteMemory(addr, value); - } + public override void PokeMemory(ushort addr, byte value) => WriteMemory(addr, value); public override void SyncState(Serializer ser) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_Sachen_MMC1.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_Sachen_MMC1.cs index c25e688cacd..c6d0d8edeb2 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_Sachen_MMC1.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_Sachen_MMC1.cs @@ -40,7 +40,7 @@ public override byte ReadMemoryLow(ushort addr) if (locked) { // header is scrambled - if ((addr >= 0x100) && (addr < 0x200)) + if (addr is >= 0x100 and < 0x200) { int temp0 = (addr & 1); int temp1 = (addr & 2); @@ -66,10 +66,7 @@ public override byte ReadMemoryLow(ushort addr) } } - public override byte ReadMemoryHigh(ushort addr) - { - return 0xFF; - } + public override byte ReadMemoryHigh(ushort addr) => 0xFF; public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags) { @@ -78,7 +75,7 @@ public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags) if (locked) { // header is scrambled - if ((addr >= 0x100) && (addr < 0x200)) + if (addr is >= 0x100 and < 0x200) { int temp0 = (addr & 1); int temp1 = (addr & 2); @@ -108,10 +105,7 @@ public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags) } } - public override byte PeekMemoryLow(ushort addr) - { - return ReadMemoryLow(addr); - } + public override byte PeekMemoryLow(ushort addr) => ReadMemoryLow(addr); public override void WriteMemory(ushort addr, byte value) { @@ -144,10 +138,7 @@ public override void WriteMemory(ushort addr, byte value) } } - public override void PokeMemory(ushort addr, byte value) - { - WriteMemory(addr, value); - } + public override void PokeMemory(ushort addr, byte value) => WriteMemory(addr, value); public override void Mapper_Tick() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_Sachen_MMC2.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_Sachen_MMC2.cs index f326dd172ae..29aa5e9a037 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_Sachen_MMC2.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_Sachen_MMC2.cs @@ -40,7 +40,7 @@ public override byte ReadMemoryLow(ushort addr) if (addr < 0x4000) { // header is scrambled - if ((addr >= 0x100) && (addr < 0x200)) + if (addr is >= 0x100 and < 0x200) { int temp0 = (addr & 1); int temp1 = (addr & 2); @@ -69,17 +69,14 @@ public override byte ReadMemoryLow(ushort addr) } } - public override byte ReadMemoryHigh(ushort addr) - { - return 0xFF; - } + public override byte ReadMemoryHigh(ushort addr) => 0xFF; public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags) { if (addr < 0x4000) { // header is scrambled - if ((addr >= 0x100) && (addr < 0x200)) + if (addr is >= 0x100 and < 0x200) { int temp0 = (addr & 1); int temp1 = (addr & 2); @@ -112,10 +109,7 @@ public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags) } } - public override byte PeekMemoryLow(ushort addr) - { - return ReadMemoryLow(addr); - } + public override byte PeekMemoryLow(ushort addr) => ReadMemoryLow(addr); public override void WriteMemory(ushort addr, byte value) { @@ -148,10 +142,7 @@ public override void WriteMemory(ushort addr, byte value) } } - public override void PokeMemory(ushort addr, byte value) - { - WriteMemory(addr, value); - } + public override void PokeMemory(ushort addr, byte value) => WriteMemory(addr, value); public override void Mapper_Tick() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_TAMA5.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_TAMA5.cs index 5566a5370c4..5692d132d88 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_TAMA5.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_TAMA5.cs @@ -60,21 +60,14 @@ public override byte ReadMemoryLow(ushort addr) public override byte ReadMemoryHigh(ushort addr) { - switch (ctrl) + return ctrl switch { - case 0xA: - // The game won't proceed unless this value (anded with 3) is 1 - // see bank 0: 0x1A7D to 0x1A89 - return 1; - case 0xC: - //Console.WriteLine("read low: " + Chip_return_low); - return Chip_return_low; - case 0xD: - //Console.WriteLine("read high: " + Chip_return_high); - return Chip_return_high; - } - - return 0x0; + 0xA => 1,// The game won't proceed unless this value (anded with 3) is 1 + // see bank 0: 0x1A7D to 0x1A89 + 0xC => Chip_return_low,//Console.WriteLine("read low: " + Chip_return_low); + 0xD => Chip_return_high,//Console.WriteLine("read high: " + Chip_return_high); + _ => 0x0, + }; } public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags) @@ -93,10 +86,7 @@ public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags) } } - public override byte PeekMemoryLow(ushort addr) - { - return ReadMemoryLow(addr); - } + public override byte PeekMemoryLow(ushort addr) => ReadMemoryLow(addr); public override void WriteMemory(ushort addr, byte value) { @@ -189,10 +179,7 @@ public override void WriteMemory(ushort addr, byte value) } } - public override void PokeMemory(ushort addr, byte value) - { - WriteMemory(addr, value); - } + public override void PokeMemory(ushort addr, byte value) => WriteMemory(addr, value); public override void RTC_Get(int value, int index) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_WisdomTree.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_WisdomTree.cs index 59a9c669cfd..827ed0bd9c4 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_WisdomTree.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_WisdomTree.cs @@ -19,15 +19,9 @@ public override void Reset() if (ROM_mask > 0x100) { ROM_mask |= 0xFF; } } - public override byte ReadMemoryLow(ushort addr) - { - return Core._rom[ROM_bank * 0x8000 + addr]; - } + public override byte ReadMemoryLow(ushort addr) => Core._rom[ROM_bank * 0x8000 + addr]; - public override byte ReadMemoryHigh(ushort addr) - { - return 0xFF; - } + public override byte ReadMemoryHigh(ushort addr) => 0xFF; public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags) { @@ -41,15 +35,9 @@ public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags) } } - public override byte PeekMemoryLow(ushort addr) - { - return ReadMemoryLow(addr); - } + public override byte PeekMemoryLow(ushort addr) => ReadMemoryLow(addr); - public override byte PeekMemoryHigh(ushort addr) - { - return ReadMemoryHigh(addr); - } + public override byte PeekMemoryHigh(ushort addr) => ReadMemoryHigh(addr); public override void WriteMemory(ushort addr, byte value) { @@ -60,10 +48,7 @@ public override void WriteMemory(ushort addr, byte value) } } - public override void PokeMemory(ushort addr, byte value) - { - WriteMemory(addr, value); - } + public override void PokeMemory(ushort addr, byte value) => WriteMemory(addr, value); public override void SyncState(Serializer ser) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/MemoryMap.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/MemoryMap.cs index 95adf2bb57b..831c5db4d63 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/MemoryMap.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/MemoryMap.cs @@ -60,18 +60,18 @@ public byte ReadMemory(ushort addr) return bus_value; } - if (addr >= 0xE000 && addr < 0xF000) + if (addr is >= 0xE000 and < 0xF000) { return RAM[addr - 0xE000]; } - if (addr >= 0xF000 && addr < 0xFE00) + if (addr is >= 0xF000 and < 0xFE00) { //if (RAM_read[(RAM_Bank * 0x1000) + (addr - 0xF000)] == 0) { Console.WriteLine("RAM: " + addr + " " + cpu.TotalExecutedCycles); } return RAM[(RAM_Bank * 0x1000) + (addr - 0xF000)]; } - if (addr >= 0xFE00 && addr < 0xFEA0) + if (addr is >= 0xFE00 and < 0xFEA0) { if (ppu.DMA_OAM_access) { @@ -83,7 +83,7 @@ public byte ReadMemory(ushort addr) } } - if (addr >= 0xFF00 && addr < 0xFF80) // The game GOAL! Requires Hardware Regs to be accessible + if (addr is >= 0xFF00 and < 0xFF80) // The game GOAL! Requires Hardware Regs to be accessible { return Read_Registers(addr); } @@ -280,12 +280,12 @@ public void WriteMemory(ushort addr, byte value) mapper.WriteMemory(addr, value); } - if (addr >= 0xE000 && addr < 0xF000) + if (addr is >= 0xE000 and < 0xF000) { //RAM_read[addr - 0xE000] = 1; RAM[addr - 0xE000] = value; } - else if (addr >= 0xF000 && addr < 0xFE00) + else if (addr is >= 0xF000 and < 0xFE00) { //RAM_read[RAM_Bank * 0x1000 + (addr - 0xF000)] = 1; RAM[RAM_Bank * 0x1000 + (addr - 0xF000)] = value; @@ -294,7 +294,7 @@ public void WriteMemory(ushort addr, byte value) { OAM[addr - 0xFE00] = value; } - else if (addr >= 0xFF00 && addr < 0xFF80) // The game GOAL! Requires Hardware Regs to be accessible + else if (addr is >= 0xFF00 and < 0xFF80) // The game GOAL! Requires Hardware Regs to be accessible { Write_Registers(addr, value); } @@ -443,17 +443,17 @@ public byte PeekMemory(ushort addr) return mapper.PeekMemoryHigh(addr); } - if (addr >= 0xE000 && addr < 0xF000) + if (addr is >= 0xE000 and < 0xF000) { return RAM[addr - 0xE000]; } - if (addr >= 0xF000 && addr < 0xFE00) + if (addr is >= 0xF000 and < 0xFE00) { return RAM[(RAM_Bank * 0x1000) + (addr - 0xF000)]; } - if (addr >= 0xFE00 && addr < 0xFEA0) + if (addr is >= 0xFE00 and < 0xFEA0) { if (ppu.DMA_OAM_access) { @@ -465,7 +465,7 @@ public byte PeekMemory(ushort addr) } } - if (addr >= 0xFF00 && addr < 0xFF80) // The game GOAL! Requires Hardware Regs to be accessible + if (addr is >= 0xFF00 and < 0xFF80) // The game GOAL! Requires Hardware Regs to be accessible { return Read_Registers(addr); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/PPU.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/PPU.cs index 7a9b254ff59..e98eba72277 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/PPU.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/PPU.cs @@ -127,10 +127,7 @@ public class PPU public int total_counter; public uint[] color_palette = new uint[4]; - public virtual byte ReadReg(int addr) - { - return 0; - } + public virtual byte ReadReg(int addr) => 0; public virtual void WriteReg(int addr, byte value) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/SerialPort.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/SerialPort.cs index d2cf7c08239..284c63f252c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/SerialPort.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/SerialPort.cs @@ -19,15 +19,12 @@ public class SerialPort public byte ReadReg(int addr) { - switch (addr) + return addr switch { - case 0xFF01: - return serial_data; - case 0xFF02: - return serial_control; - } - - return 0xFF; + 0xFF01 => serial_data, + 0xFF02 => serial_control, + _ => 0xFF, + }; } public void WriteReg(int addr, byte value) diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink/GBHawkLink.ICodeDataLog.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink/GBHawkLink.ICodeDataLog.cs index 9151badcbc9..01ec3b52edd 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink/GBHawkLink.ICodeDataLog.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink/GBHawkLink.ICodeDataLog.cs @@ -67,11 +67,11 @@ private void CDLCpuCallback(ushort addr, LR35902.eCDLogMemFlags flags) return; } } - else if ((addr >= 0xE000) && (addr < 0xF000)) + else if (addr is >= 0xE000 and < 0xF000) { SetCDL(flags, "WRAM", addr - 0xE000); } - else if ((addr >= 0xF000) && (addr < 0xFE00)) + else if (addr is >= 0xF000 and < 0xFE00) { SetCDL(flags, "WRAM", (L.RAM_Bank * 0x1000) + (addr - 0xF000)); } @@ -79,7 +79,7 @@ private void CDLCpuCallback(ushort addr, LR35902.eCDLogMemFlags flags) { return; } - else if ((addr >= 0xFF00) && (addr < 0xFF80)) // The game GOAL! Requires Hardware Regs to be accessible + else if (addr is >= 0xFF00 and < 0xFF80) // The game GOAL! Requires Hardware Regs to be accessible { return; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink/GBHawkLink.IEmulator.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink/GBHawkLink.IEmulator.cs index 46f2e497931..57634ecfe2c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink/GBHawkLink.IEmulator.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink/GBHawkLink.IEmulator.cs @@ -312,8 +312,8 @@ public void SetSyncMode(SyncSoundMode mode) public void GetSamplesSync(out short[] samples, out int nsamp) { - L.audio.GetSamplesSync(out var tempSampL, out var nsampL); - R.audio.GetSamplesSync(out var tempSampR, out var nsampR); + L.audio.GetSamplesSync(out short[] tempSampL, out int nsampL); + R.audio.GetSamplesSync(out short[] tempSampR, out int nsampR); if (linkSettings.AudioSet == GBLinkSettings.AudioSrc.Left) { @@ -332,10 +332,7 @@ public void GetSamplesSync(out short[] samples, out int nsamp) } } - public void GetSamplesAsync(short[] samples) - { - throw new NotSupportedException("Async is not available"); - } + public void GetSamplesAsync(short[] samples) => throw new NotSupportedException("Async is not available"); public void DiscardSamples() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink/GBHawkLink.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink/GBHawkLink.IMemoryDomains.cs index 19dfb15e990..1ab4527d245 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink/GBHawkLink.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink/GBHawkLink.IMemoryDomains.cs @@ -10,7 +10,7 @@ public partial class GBHawkLink public void SetupMemoryDomains() { - var domains = new List + List domains = new() { new MemoryDomainDelegate( "Main RAM L", @@ -86,13 +86,13 @@ public void SetupMemoryDomains() if (L.cart_RAM != null) { - var cartRamL = new MemoryDomainByteArray("Cart RAM L", MemoryDomain.Endian.Little, L.cart_RAM, true, 1); + MemoryDomainByteArray cartRamL = new("Cart RAM L", MemoryDomain.Endian.Little, L.cart_RAM, true, 1); domains.Add(cartRamL); } if (R.cart_RAM != null) { - var cartRamR = new MemoryDomainByteArray("Cart RAM R", MemoryDomain.Endian.Little, R.cart_RAM, true, 1); + MemoryDomainByteArray cartRamR = new("Cart RAM R", MemoryDomain.Endian.Little, R.cart_RAM, true, 1); domains.Add(cartRamR); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink/GBHawkLink.ISettable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink/GBHawkLink.ISettable.cs index 2841f97cd2d..dfeb80686dd 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink/GBHawkLink.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink/GBHawkLink.ISettable.cs @@ -27,8 +27,8 @@ public PutSettingsDirtyBits PutSyncSettings(GBLinkSyncSettings o) return ret ? PutSettingsDirtyBits.RebootCore : PutSettingsDirtyBits.None; } - private GBLinkSettings linkSettings = new GBLinkSettings(); - public GBLinkSyncSettings linkSyncSettings = new GBLinkSyncSettings(); + private GBLinkSettings linkSettings = new(); + public GBLinkSyncSettings linkSyncSettings = new(); public class GBLinkSettings { @@ -146,10 +146,7 @@ public int RTCOffset_R public GBLinkSyncSettings() => SettingsUtil.SetDefaultValues(this); - public static bool NeedsReboot(GBLinkSyncSettings x, GBLinkSyncSettings y) - { - return !DeepEquality.DeepEquals(x, y); - } + public static bool NeedsReboot(GBLinkSyncSettings x, GBLinkSyncSettings y) => !DeepEquality.DeepEquals(x, y); } } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink/GBHawkLink.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink/GBHawkLink.cs index 825b2ea42eb..c0936b3e3fe 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink/GBHawkLink.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink/GBHawkLink.cs @@ -37,7 +37,7 @@ public GBHawkLink(CoreLoadParameters _cableconnected = value; } + #pragma warning disable IDE0051 private void ExecFetch(ushort addr) { uint flags = (uint)(MemoryCallbackFlags.AccessExecute); MemoryCallbacks.CallMemoryCallbacks(addr, 0, flags, "System Bus"); } + #pragma warning restore IDE0051 } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink/GBHawkLinkControllerDeck.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink/GBHawkLinkControllerDeck.cs index 74a3f497bc2..bc7e9d68423 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink/GBHawkLinkControllerDeck.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink/GBHawkLinkControllerDeck.cs @@ -27,15 +27,9 @@ public GBHawkLinkControllerDeck(string controller1Name, string controller2Name) }.MakeImmutable(); } - public byte ReadPort1(IController c) - { - return Port1.Read(c); - } + public byte ReadPort1(IController c) => Port1.Read(c); - public byte ReadPort2(IController c) - { - return Port2.Read(c); - } + public byte ReadPort2(IController c) => Port2.Read(c); public ControllerDefinition Definition { get; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink3x/GBHawkLink3x.ICodeDataLog.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink3x/GBHawkLink3x.ICodeDataLog.cs index 6f9bdd900bc..e51e7dead1c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink3x/GBHawkLink3x.ICodeDataLog.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink3x/GBHawkLink3x.ICodeDataLog.cs @@ -67,11 +67,11 @@ private void CDLCpuCallback(ushort addr, LR35902.eCDLogMemFlags flags) return; } } - else if ((addr >= 0xE000) && (addr < 0xF000)) + else if (addr is >= 0xE000 and < 0xF000) { SetCDL(flags, "WRAM", addr - 0xE000); } - else if ((addr >= 0xF000) && (addr < 0xFE00)) + else if (addr is >= 0xF000 and < 0xFE00) { SetCDL(flags, "WRAM", (L.RAM_Bank * 0x1000) + (addr - 0xF000)); } @@ -79,7 +79,7 @@ private void CDLCpuCallback(ushort addr, LR35902.eCDLogMemFlags flags) { return; } - else if ((addr >= 0xFF00) && (addr < 0xFF80)) // The game GOAL! Requires Hardware Regs to be accessible + else if (addr is >= 0xFF00 and < 0xFF80) // The game GOAL! Requires Hardware Regs to be accessible { return; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink3x/GBHawkLink3x.IEmulator.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink3x/GBHawkLink3x.IEmulator.cs index d77e1e9e201..aafe5189a1e 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink3x/GBHawkLink3x.IEmulator.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink3x/GBHawkLink3x.IEmulator.cs @@ -481,9 +481,9 @@ public void SetSyncMode(SyncSoundMode mode) public void GetSamplesSync(out short[] samples, out int nsamp) { - L.audio.GetSamplesSync(out var tempSampL, out var nsampL); - C.audio.GetSamplesSync(out var tempSampC, out var nsampC); - R.audio.GetSamplesSync(out var tempSampR, out var nsampR); + L.audio.GetSamplesSync(out short[] tempSampL, out int nsampL); + C.audio.GetSamplesSync(out short[] tempSampC, out int nsampC); + R.audio.GetSamplesSync(out short[] tempSampR, out int nsampR); if (Link3xSettings.AudioSet == GBLink3xSettings.AudioSrc.Left) { @@ -507,10 +507,7 @@ public void GetSamplesSync(out short[] samples, out int nsamp) } } - public void GetSamplesAsync(short[] samples) - { - throw new NotSupportedException("Async is not available"); - } + public void GetSamplesAsync(short[] samples) => throw new NotSupportedException("Async is not available"); public void DiscardSamples() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink3x/GBHawkLink3x.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink3x/GBHawkLink3x.IMemoryDomains.cs index 7441f030971..d92b76d6212 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink3x/GBHawkLink3x.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink3x/GBHawkLink3x.IMemoryDomains.cs @@ -10,7 +10,7 @@ public partial class GBHawkLink3x public void SetupMemoryDomains() { - var domains = new List + List domains = new() { new MemoryDomainDelegate( "Main RAM L", @@ -121,19 +121,19 @@ public void SetupMemoryDomains() if (L.cart_RAM != null) { - var cartRamL = new MemoryDomainByteArray("Cart RAM L", MemoryDomain.Endian.Little, L.cart_RAM, true, 1); + MemoryDomainByteArray cartRamL = new("Cart RAM L", MemoryDomain.Endian.Little, L.cart_RAM, true, 1); domains.Add(cartRamL); } if (C.cart_RAM != null) { - var cartRamC = new MemoryDomainByteArray("Cart RAM C", MemoryDomain.Endian.Little, C.cart_RAM, true, 1); + MemoryDomainByteArray cartRamC = new("Cart RAM C", MemoryDomain.Endian.Little, C.cart_RAM, true, 1); domains.Add(cartRamC); } if (R.cart_RAM != null) { - var cartRamR = new MemoryDomainByteArray("Cart RAM R", MemoryDomain.Endian.Little, R.cart_RAM, true, 1); + MemoryDomainByteArray cartRamR = new("Cart RAM R", MemoryDomain.Endian.Little, R.cart_RAM, true, 1); domains.Add(cartRamR); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink3x/GBHawkLink3x.ISettable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink3x/GBHawkLink3x.ISettable.cs index 08713f3a97b..0a04821805c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink3x/GBHawkLink3x.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink3x/GBHawkLink3x.ISettable.cs @@ -27,8 +27,8 @@ public PutSettingsDirtyBits PutSyncSettings(GBLink3xSyncSettings o) return ret ? PutSettingsDirtyBits.RebootCore : PutSettingsDirtyBits.None; } - private GBLink3xSettings Link3xSettings = new GBLink3xSettings(); - private GBLink3xSyncSettings Link3xSyncSettings = new GBLink3xSyncSettings(); + private GBLink3xSettings Link3xSettings = new(); + private GBLink3xSyncSettings Link3xSyncSettings = new(); public class GBLink3xSettings { @@ -169,10 +169,7 @@ public int RTCOffset_R public GBLink3xSyncSettings() => SettingsUtil.SetDefaultValues(this); - public static bool NeedsReboot(GBLink3xSyncSettings x, GBLink3xSyncSettings y) - { - return !DeepEquality.DeepEquals(x, y); - } + public static bool NeedsReboot(GBLink3xSyncSettings x, GBLink3xSyncSettings y) => !DeepEquality.DeepEquals(x, y); } } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink3x/GBHawkLink3x.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink3x/GBHawkLink3x.cs index b3ac4a216b4..87d4b8a50b9 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink3x/GBHawkLink3x.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink3x/GBHawkLink3x.cs @@ -37,7 +37,7 @@ public GBHawkLink3x(CoreLoadParameters l if (lp.Roms.Count != 3) throw new InvalidOperationException("Wrong number of roms"); - var ser = new BasicServiceProvider(this); + BasicServiceProvider ser = new(this); ServiceProvider = ser; Link3xSettings = lp.Settings ?? new GBLink3xSettings(); @@ -47,13 +47,13 @@ public GBHawkLink3x(CoreLoadParameters l GBHawkControllerDeck.DefaultControllerName, GBHawkControllerDeck.DefaultControllerName); - var tempSetL = new GBHawk.GBHawk.GBSettings(); - var tempSetC = new GBHawk.GBHawk.GBSettings(); - var tempSetR = new GBHawk.GBHawk.GBSettings(); + GBHawk.GBHawk.GBSettings tempSetL = new(); + GBHawk.GBHawk.GBSettings tempSetC = new(); + GBHawk.GBHawk.GBSettings tempSetR = new(); - var tempSyncL = new GBHawk.GBHawk.GBSyncSettings(); - var tempSyncC = new GBHawk.GBHawk.GBSyncSettings(); - var tempSyncR = new GBHawk.GBHawk.GBSyncSettings(); + GBHawk.GBHawk.GBSyncSettings tempSyncL = new(); + GBHawk.GBHawk.GBSyncSettings tempSyncC = new(); + GBHawk.GBHawk.GBSyncSettings tempSyncR = new(); tempSyncL.ConsoleMode = Link3xSyncSettings.ConsoleMode_L; tempSyncC.ConsoleMode = Link3xSyncSettings.ConsoleMode_C; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink3x/GBHawkLink3xControllerDeck.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink3x/GBHawkLink3xControllerDeck.cs index 65b6399ecc3..f2e5b58bb7b 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink3x/GBHawkLink3xControllerDeck.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink3x/GBHawkLink3xControllerDeck.cs @@ -33,20 +33,11 @@ public GBHawkLink3xControllerDeck(string controller1Name, string controller2Name }.MakeImmutable(); } - public byte ReadPort1(IController c) - { - return Port1.Read(c); - } + public byte ReadPort1(IController c) => Port1.Read(c); - public byte ReadPort2(IController c) - { - return Port2.Read(c); - } + public byte ReadPort2(IController c) => Port2.Read(c); - public byte ReadPort3(IController c) - { - return Port3.Read(c); - } + public byte ReadPort3(IController c) => Port3.Read(c); public ControllerDefinition Definition { get; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink4x/GBHawkLink4x.ICodeDataLog.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink4x/GBHawkLink4x.ICodeDataLog.cs index d7698af937e..cc7b734a012 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink4x/GBHawkLink4x.ICodeDataLog.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink4x/GBHawkLink4x.ICodeDataLog.cs @@ -67,11 +67,11 @@ private void CDLCpuCallback(ushort addr, LR35902.eCDLogMemFlags flags) return; } } - else if ((addr >= 0xE000) && (addr < 0xF000)) + else if (addr is >= 0xE000 and < 0xF000) { SetCDL(flags, "WRAM", addr - 0xE000); } - else if ((addr >= 0xF000) && (addr < 0xFE00)) + else if (addr is >= 0xF000 and < 0xFE00) { SetCDL(flags, "WRAM", (A.RAM_Bank * 0x1000) + (addr - 0xF000)); } @@ -79,7 +79,7 @@ private void CDLCpuCallback(ushort addr, LR35902.eCDLogMemFlags flags) { return; } - else if ((addr >= 0xFF00) && (addr < 0xFF80)) // The game GOAL! Requires Hardware Regs to be accessible + else if (addr is >= 0xFF00 and < 0xFF80) // The game GOAL! Requires Hardware Regs to be accessible { return; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink4x/GBHawkLink4x.IEmulator.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink4x/GBHawkLink4x.IEmulator.cs index 335dbe81cfa..96507f77f0c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink4x/GBHawkLink4x.IEmulator.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink4x/GBHawkLink4x.IEmulator.cs @@ -1020,10 +1020,7 @@ public void Dispose() public int[] _vidbuffer = new int[160 * 2 * 144 * 2]; - public int[] GetVideoBuffer() - { - return _vidbuffer; - } + public int[] GetVideoBuffer() => _vidbuffer; public void FillVideoBuffer() { @@ -1067,10 +1064,10 @@ public void SetSyncMode(SyncSoundMode mode) public void GetSamplesSync(out short[] samples, out int nsamp) { - A.audio.GetSamplesSync(out var temp_samp_A, out var nsamp_A); - B.audio.GetSamplesSync(out var temp_samp_B, out var nsamp_B); - C.audio.GetSamplesSync(out var temp_samp_C, out var nsamp_C); - D.audio.GetSamplesSync(out var temp_samp_D, out var nsamp_D); + A.audio.GetSamplesSync(out short[] temp_samp_A, out int nsamp_A); + B.audio.GetSamplesSync(out short[] temp_samp_B, out int nsamp_B); + C.audio.GetSamplesSync(out short[] temp_samp_C, out int nsamp_C); + D.audio.GetSamplesSync(out short[] temp_samp_D, out int nsamp_D); if (Link4xSettings.AudioSet == GBLink4xSettings.AudioSrc.A) { @@ -1099,10 +1096,7 @@ public void GetSamplesSync(out short[] samples, out int nsamp) } } - public void GetSamplesAsync(short[] samples) - { - throw new NotSupportedException("Async is not available"); - } + public void GetSamplesAsync(short[] samples) => throw new NotSupportedException("Async is not available"); public void DiscardSamples() { @@ -1112,10 +1106,12 @@ public void DiscardSamples() D.audio.DiscardSamples(); } + #pragma warning disable IDE0051 private void GetSamples(short[] samples) { } + #pragma warning restore IDE0051 public void DisposeSound() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink4x/GBHawkLink4x.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink4x/GBHawkLink4x.IMemoryDomains.cs index b0eb4dda3cd..19b2c3ad6ca 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink4x/GBHawkLink4x.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink4x/GBHawkLink4x.IMemoryDomains.cs @@ -10,7 +10,7 @@ public partial class GBHawkLink4x public void SetupMemoryDomains() { - var domains = new List + List domains = new() { new MemoryDomainDelegate( "Main RAM A", @@ -156,25 +156,25 @@ public void SetupMemoryDomains() if (A.cart_RAM != null) { - var cartRamA = new MemoryDomainByteArray("Cart RAM L", MemoryDomain.Endian.Little, A.cart_RAM, true, 1); + MemoryDomainByteArray cartRamA = new("Cart RAM L", MemoryDomain.Endian.Little, A.cart_RAM, true, 1); domains.Add(cartRamA); } if (B.cart_RAM != null) { - var cartRamB = new MemoryDomainByteArray("Cart RAM B", MemoryDomain.Endian.Little, B.cart_RAM, true, 1); + MemoryDomainByteArray cartRamB = new("Cart RAM B", MemoryDomain.Endian.Little, B.cart_RAM, true, 1); domains.Add(cartRamB); } if (C.cart_RAM != null) { - var cartRamC = new MemoryDomainByteArray("Cart RAM C", MemoryDomain.Endian.Little, C.cart_RAM, true, 1); + MemoryDomainByteArray cartRamC = new("Cart RAM C", MemoryDomain.Endian.Little, C.cart_RAM, true, 1); domains.Add(cartRamC); } if (D.cart_RAM != null) { - var cartRamD = new MemoryDomainByteArray("Cart RAM D", MemoryDomain.Endian.Little, D.cart_RAM, true, 1); + MemoryDomainByteArray cartRamD = new("Cart RAM D", MemoryDomain.Endian.Little, D.cart_RAM, true, 1); domains.Add(cartRamD); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink4x/GBHawkLink4x.ISettable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink4x/GBHawkLink4x.ISettable.cs index 344ac2f324c..9cf30259995 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink4x/GBHawkLink4x.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink4x/GBHawkLink4x.ISettable.cs @@ -27,8 +27,8 @@ public PutSettingsDirtyBits PutSyncSettings(GBLink4xSyncSettings o) return ret ? PutSettingsDirtyBits.RebootCore : PutSettingsDirtyBits.None; } - private GBLink4xSettings Link4xSettings = new GBLink4xSettings(); - public GBLink4xSyncSettings Link4xSyncSettings = new GBLink4xSyncSettings(); + private GBLink4xSettings Link4xSettings = new(); + public GBLink4xSyncSettings Link4xSyncSettings = new(); public class GBLink4xSettings { @@ -203,10 +203,7 @@ public int RTCOffset_D public GBLink4xSyncSettings Clone() => (GBLink4xSyncSettings)MemberwiseClone(); public GBLink4xSyncSettings() => SettingsUtil.SetDefaultValues(this); - public static bool NeedsReboot(GBLink4xSyncSettings x, GBLink4xSyncSettings y) - { - return !DeepEquality.DeepEquals(x, y); - } + public static bool NeedsReboot(GBLink4xSyncSettings x, GBLink4xSyncSettings y) => !DeepEquality.DeepEquals(x, y); } } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink4x/GBHawkLink4x.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink4x/GBHawkLink4x.cs index cc33f7f5769..c8e629fada0 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink4x/GBHawkLink4x.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink4x/GBHawkLink4x.cs @@ -58,7 +58,7 @@ public GBHawkLink4x(CoreLoadParameters l if (lp.Roms.Count != 4) throw new InvalidOperationException("Wrong number of roms"); - var ser = new BasicServiceProvider(this); + BasicServiceProvider ser = new(this); Link4xSettings = lp.Settings ?? new GBLink4xSettings(); Link4xSyncSettings = lp.SyncSettings ?? new GBLink4xSyncSettings(); @@ -68,15 +68,15 @@ public GBHawkLink4x(CoreLoadParameters l GBHawkControllerDeck.DefaultControllerName, GBHawkControllerDeck.DefaultControllerName); - var tempSetA = new GBHawk.GBHawk.GBSettings(); - var tempSetB = new GBHawk.GBHawk.GBSettings(); - var tempSetC = new GBHawk.GBHawk.GBSettings(); - var tempSetD = new GBHawk.GBHawk.GBSettings(); + GBHawk.GBHawk.GBSettings tempSetA = new(); + GBHawk.GBHawk.GBSettings tempSetB = new(); + GBHawk.GBHawk.GBSettings tempSetC = new(); + GBHawk.GBHawk.GBSettings tempSetD = new(); - var tempSyncA = new GBHawk.GBHawk.GBSyncSettings(); - var tempSyncB = new GBHawk.GBHawk.GBSyncSettings(); - var tempSyncC = new GBHawk.GBHawk.GBSyncSettings(); - var tempSyncD = new GBHawk.GBHawk.GBSyncSettings(); + GBHawk.GBHawk.GBSyncSettings tempSyncA = new(); + GBHawk.GBHawk.GBSyncSettings tempSyncB = new(); + GBHawk.GBHawk.GBSyncSettings tempSyncC = new(); + GBHawk.GBHawk.GBSyncSettings tempSyncD = new(); tempSyncA.ConsoleMode = Link4xSyncSettings.ConsoleMode_A; tempSyncB.ConsoleMode = Link4xSyncSettings.ConsoleMode_B; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink4x/GBHawkLink4xControllerDeck.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink4x/GBHawkLink4xControllerDeck.cs index d0f4aa29a48..59238e3ffc5 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink4x/GBHawkLink4xControllerDeck.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink4x/GBHawkLink4xControllerDeck.cs @@ -38,25 +38,13 @@ public GBHawkLink4xControllerDeck(string controller1Name, string controller2Name }.MakeImmutable(); } - public byte ReadPort1(IController c) - { - return Port1.Read(c); - } + public byte ReadPort1(IController c) => Port1.Read(c); - public byte ReadPort2(IController c) - { - return Port2.Read(c); - } + public byte ReadPort2(IController c) => Port2.Read(c); - public byte ReadPort3(IController c) - { - return Port3.Read(c); - } + public byte ReadPort3(IController c) => Port3.Read(c); - public byte ReadPort4(IController c) - { - return Port4.Read(c); - } + public byte ReadPort4(IController c) => Port4.Read(c); public ControllerDefinition Definition { get; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GBColors.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GBColors.cs index 49d86db34dd..66a9fe343d8 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GBColors.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GBColors.cs @@ -23,7 +23,7 @@ public Triple(int r, int g, int b) this.b = b; } - public Triple Bit5to8Bad() + public readonly Triple Bit5to8Bad() { Triple ret; ret.r = r * 8; @@ -32,7 +32,7 @@ public Triple Bit5to8Bad() return ret; } - public Triple Bit5to8Good() + public readonly Triple Bit5to8Good() { Triple ret; ret.r = (r * 255 + 15) / 31; @@ -45,7 +45,7 @@ public Triple Bit5to8Good() private static readonly int[] sameboy_agb_color_curve = new int[32] { 0, 3, 8, 14, 20, 26, 33, 40, 47, 54, 62, 70, 78, 86, 94, 103, 112, 120, 129, 138, 147, 157, 166, 176, 185, 195, 205, 215, 225, 235, 245, 255 }; private static readonly int[] sameboy_sgb_color_curve = new int[32] { 0, 2, 5, 9, 15, 20, 27, 34, 42, 50, 58, 67, 76, 85, 94, 104, 114, 123, 133, 143, 153, 163, 173, 182, 192, 202, 211, 220, 229, 238, 247, 255 }; - public Triple Bit5to8SameBoy(bool sgb, bool agb) + public readonly Triple Bit5to8SameBoy(bool sgb, bool agb) { Triple ret; if (sgb) @@ -70,10 +70,7 @@ public Triple Bit5to8SameBoy(bool sgb, bool agb) return ret; } - public int ToARGB32() - { - return b | g << 8 | r << 16 | 255 << 24; - } + public readonly int ToARGB32() => b | g << 8 | r << 16 | 255 << 24; } // sameboy's "emulate hardware" color conversion @@ -82,7 +79,7 @@ public int ToARGB32() // todo: maybe add in its "harsh reality" too? (""accuracy"") public static Triple SameBoyColor(Triple c, bool sgb, bool agb) { - Triple ret = c.Bit5to8SameBoy(sgb, agb); + var ret = c.Bit5to8SameBoy(sgb, agb); if (!sgb) { if (agb) @@ -124,16 +121,10 @@ public static Triple LibretroGBCColor(Triple c, bool sgb, bool agb) } // vba's default mode - public static Triple VividVBAColor(Triple c, bool sgb, bool agb) - { - return c.Bit5to8Bad(); - } + public static Triple VividVBAColor(Triple c, bool sgb, bool agb) => c.Bit5to8Bad(); // "gameboy colors" mode on older versions of VBA - private static int gbGetValue(int min, int max, int v) - { - return (int)(min + (max - min) * (2.0 * (v / 31.0) - (v / 31.0) * (v / 31.0))); - } + private static int gbGetValue(int min, int max, int v) => (int)(min + (max - min) * (2.0 * (v / 31.0) - (v / 31.0) * (v / 31.0))); public static Triple OldVBAColor(Triple c, bool sgb, bool agb) { @@ -162,17 +153,11 @@ public static Triple NewVBAColor(Triple c, bool sgb, bool agb) } // as vivid as possible - public static Triple UltraVividColor(Triple c, bool sgb, bool agb) - { - return c.Bit5to8Good(); - } + public static Triple UltraVividColor(Triple c, bool sgb, bool agb) => c.Bit5to8Good(); // possibly represents a GBA screen, more or less // but probably not (black point?) - private static int GBAGamma(int input) - { - return (int)Math.Round(Math.Pow(input / 31.0, 3.5 / 2.2) * 255.0); - } + private static int GBAGamma(int input) => (int)Math.Round(Math.Pow(input / 31.0, 3.5 / 2.2) * 255.0); public static Triple GBAColor(Triple c, bool sgb, bool agb) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GBDisassembler.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GBDisassembler.cs index c5e801d3769..18f572e6efa 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GBDisassembler.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GBDisassembler.cs @@ -15,7 +15,7 @@ public class GBDisassembler : VerifiedDisassembler public override string Disassemble(MemoryDomain m, uint addr, out int length) { - var ret = LR35902.Disassemble((ushort) addr, a => m.PeekByte(a), UseRGBDSSyntax, out var tmp); + string ret = LR35902.Disassemble((ushort) addr, a => m.PeekByte(a), UseRGBDSSyntax, out ushort tmp); length = tmp; return ret; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/Gambatte.IDebuggable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/Gambatte.IDebuggable.cs index 78be84d283f..77e62a27621 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/Gambatte.IDebuggable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/Gambatte.IDebuggable.cs @@ -58,7 +58,7 @@ public void SetCpuRegister(string register, int value) public long TotalExecutedCycles => Math.Max((long)_cycleCount, (long)callbackCycleCount); - private MemoryCallbackSystem _memorycallbacks = new MemoryCallbackSystem(new[] { "System Bus", "ROM", "VRAM", "SRAM", "WRAM", "OAM", "HRAM" }); + private MemoryCallbackSystem _memorycallbacks = new(new[] { "System Bus", "ROM", "VRAM", "SRAM", "WRAM", "OAM", "HRAM" }); public IMemoryCallbackSystem MemoryCallbacks => _memorycallbacks; private LibGambatte.MemoryCallback _readcb; @@ -79,14 +79,14 @@ internal void ConnectMemoryCallbackSystem(MemoryCallbackSystem mcs, int which) private LibGambatte.MemoryCallback CreateCallback(MemoryCallbackFlags flags, Func getHasCBOfType, string which = "") { - var rawFlags = (uint)flags; + uint rawFlags = (uint)flags; return (address, cycleOffset) => { callbackCycleCount = _cycleCount + cycleOffset; if (getHasCBOfType()) { MemoryCallbacks.CallMemoryCallbacks(address, 0, rawFlags, which + "System Bus"); - var bank = LibGambatte.gambatte_getaddrbank(GambatteState, (ushort)address); + int bank = LibGambatte.gambatte_getaddrbank(GambatteState, (ushort)address); if (address < 0x4000u) // usually rom bank 0 for most mbcs, some mbcs might have this at a different rom bank { address += (uint)(bank * 0x4000); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/Gambatte.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/Gambatte.IMemoryDomains.cs index 30684ca990b..30e2665ef0c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/Gambatte.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/Gambatte.IMemoryDomains.cs @@ -7,12 +7,12 @@ namespace BizHawk.Emulation.Cores.Nintendo.Gameboy { public partial class Gameboy { - private readonly List _memoryDomains = new List(); + private readonly List _memoryDomains = new(); internal IMemoryDomains MemoryDomains { get; private set; } private void CreateMemoryDomain(LibGambatte.MemoryAreas which, string name) { - IntPtr data = IntPtr.Zero; + var data = IntPtr.Zero; int length = 0; if (!LibGambatte.gambatte_getmemoryarea(GambatteState, which, ref data, ref length)) diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/Gambatte.ISettable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/Gambatte.ISettable.cs index a4f7f5c4b93..b894fd3560a 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/Gambatte.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/Gambatte.ISettable.cs @@ -8,10 +8,7 @@ namespace BizHawk.Emulation.Cores.Nintendo.Gameboy { public partial class Gameboy : ISettable { - public GambatteSettings GetSettings() - { - return _settings.Clone(); - } + public GambatteSettings GetSettings() => _settings.Clone(); public PutSettingsDirtyBits PutSettings(GambatteSettings o) { @@ -29,10 +26,7 @@ public PutSettingsDirtyBits PutSettings(GambatteSettings o) return PutSettingsDirtyBits.None; } - public GambatteSyncSettings GetSyncSettings() - { - return _syncSettings.Clone(); - } + public GambatteSyncSettings GetSyncSettings() => _syncSettings.Clone(); public PutSettingsDirtyBits PutSyncSettings(GambatteSyncSettings o) { @@ -91,7 +85,7 @@ public GambatteSettings() public GambatteSettings Clone() { - var ret = (GambatteSettings)MemberwiseClone(); + GambatteSettings ret = (GambatteSettings)MemberwiseClone(); ret.GBPalette = (int[])GBPalette.Clone(); return ret; } @@ -178,15 +172,9 @@ public GambatteSyncSettings() SettingsUtil.SetDefaultValues(this); } - public GambatteSyncSettings Clone() - { - return (GambatteSyncSettings)MemberwiseClone(); - } + public GambatteSyncSettings Clone() => (GambatteSyncSettings)MemberwiseClone(); - public static bool NeedsReboot(GambatteSyncSettings x, GambatteSyncSettings y) - { - return !DeepEquality.DeepEquals(x, y); - } + public static bool NeedsReboot(GambatteSyncSettings x, GambatteSyncSettings y) => !DeepEquality.DeepEquals(x, y); } } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/Gambatte.ISoundProvider.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/Gambatte.ISoundProvider.cs index 67999fa373d..1e64a372ed8 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/Gambatte.ISoundProvider.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/Gambatte.ISoundProvider.cs @@ -8,10 +8,7 @@ public partial class Gameboy : ISoundProvider { public bool CanProvideAsync => false; - public void DiscardSamples() - { - _soundoutbuffcontains = 0; - } + public void DiscardSamples() => _soundoutbuffcontains = 0; public void GetSamplesSync(out short[] samples, out int nsamp) { @@ -29,10 +26,7 @@ public void SetSyncMode(SyncSoundMode mode) public SyncSoundMode SyncMode => SyncSoundMode.Sync; - public void GetSamplesAsync(short[] samples) - { - throw new InvalidOperationException("Async mode is not supported."); - } + public void GetSamplesAsync(short[] samples) => throw new InvalidOperationException("Async mode is not supported."); internal bool Muted => _settings.Muted; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/Gambatte.IStatable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/Gambatte.IStatable.cs index 9b08cfdc95e..6726234463f 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/Gambatte.IStatable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/Gambatte.IStatable.cs @@ -21,7 +21,7 @@ public void SaveStateText(TextWriter writer) public void LoadStateText(TextReader reader) { - var s = (TextState)ser.Deserialize(reader, typeof(TextState)); + TextState s = (TextState)ser.Deserialize(reader, typeof(TextState)); LoadState(s); reader.ReadToEnd(); } @@ -88,16 +88,15 @@ public void LoadStateBinary(BinaryReader reader) private byte[] _stateBuf; - private void NewSaveCoreSetBuff() - { + private void NewSaveCoreSetBuff() => #if USE_UPSTREAM_STATES _stateBuf = new byte[LibGambatte.gambatte_savestate(GambatteState, null, 160, null)]; #else _stateBuf = new byte[LibGambatte.gambatte_newstatelen(GambatteState)]; #endif - } - private readonly JsonSerializer ser = new JsonSerializer { Formatting = Formatting.Indented }; + + private readonly JsonSerializer ser = new() { Formatting = Formatting.Indented }; // other data in the text state besides core internal class TextStateData @@ -113,7 +112,7 @@ internal class TextStateData internal TextState SaveState() { - var s = new TextState(); + TextState s = new(); s.Prepare(); var ff = s.GetFunctionPointersSave(); LibGambatte.gambatte_newstatesave_ex(GambatteState, ref ff); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/Gambatte.IVideoProvider.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/Gambatte.IVideoProvider.cs index d35a96eae1a..02fe9f283d4 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/Gambatte.IVideoProvider.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/Gambatte.IVideoProvider.cs @@ -21,7 +21,7 @@ public partial class Gameboy : IVideoProvider private static int[] CreateVideoBuffer() { - var b = new int[160 * 144]; + int[] b = new int[160 * 144]; for (int i = 0; i < (160 * 144); i++) { b[i] = -1; // GB/C screen is disabled on bootup, so it always starts as white, not black @@ -29,10 +29,7 @@ private static int[] CreateVideoBuffer() return b; } - public int[] GetVideoBuffer() - { - return (IsSgb && _settings.ShowBorder) ? SgbVideoBuffer : VideoBuffer; - } + public int[] GetVideoBuffer() => (IsSgb && _settings.ShowBorder) ? SgbVideoBuffer : VideoBuffer; public int VirtualWidth => (IsSgb && _settings.ShowBorder) ? 256 : 160; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/Gambatte.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/Gambatte.cs index 473b46e7407..67ff915e63c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/Gambatte.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/Gambatte.cs @@ -22,7 +22,7 @@ public partial class Gameboy : IInputPollable, IRomInfo, IGameboyCommon, ICycleT [CoreConstructor(VSystemID.Raw.SGB)] public Gameboy(CoreComm comm, GameInfo game, byte[] file, GambatteSettings settings, GambatteSyncSettings syncSettings, bool deterministic) { - var ser = new BasicServiceProvider(this); + BasicServiceProvider ser = new(this); ser.Register(_disassembler); ServiceProvider = ser; const string TRACE_HEADER = "LR35902: PC, opcode, registers (A, F, B, C, D, E, H, L, LY, SP, CY)"; @@ -45,7 +45,7 @@ public Gameboy(CoreComm comm, GameInfo game, byte[] file, GambatteSettings setti { _syncSettings = syncSettings ?? new GambatteSyncSettings(); - LibGambatte.LoadFlags flags = LibGambatte.LoadFlags.READONLY_SAV; + var flags = LibGambatte.LoadFlags.READONLY_SAV; switch (_syncSettings.ConsoleMode) { @@ -80,7 +80,7 @@ public Gameboy(CoreComm comm, GameInfo game, byte[] file, GambatteSettings setti : _syncSettings.ConsoleMode is GambatteSyncSettings.ConsoleModeType.GBA ? "AGB" : "World"); - var bios = comm.CoreFileProvider.GetFirmwareOrThrow(fwid, "BIOS Not Found, Cannot Load. Change SyncSettings to run without BIOS."); // https://github.com/TASEmulators/BizHawk/issues/2832 tho + byte[] bios = comm.CoreFileProvider.GetFirmwareOrThrow(fwid, "BIOS Not Found, Cannot Load. Change SyncSettings to run without BIOS."); // https://github.com/TASEmulators/BizHawk/issues/2832 tho if (LibGambatte.gambatte_loadbiosbuf(GambatteState, bios, (uint)bios.Length) != 0) { throw new InvalidOperationException($"{nameof(LibGambatte.gambatte_loadbiosbuf)}() returned non-zero (bios error)"); @@ -271,7 +271,7 @@ public Gameboy(CoreComm comm, GameInfo game, byte[] file, GambatteSettings setti public static ControllerDefinition CreateControllerDefinition(bool sgb, bool sub, bool tilt, bool rumble, bool remote) { - var ret = new ControllerDefinition((sub ? "Subframe " : "") + "Gameboy Controller" + (tilt ? " + Tilt" : "")); + ControllerDefinition ret = new((sub ? "Subframe " : "") + "Gameboy Controller" + (tilt ? " + Tilt" : "")); if (sub) { ret.AddAxis("Input Length", 0.RangeTo(35112), 35112); @@ -348,7 +348,7 @@ public bool IsCGBMode public bool IsCGBDMGMode => LibGambatte.gambatte_iscgbdmg(GambatteState); - private InputCallbackSystem _inputCallbacks = new InputCallbackSystem(); + private InputCallbackSystem _inputCallbacks = new(); // low priority TODO: due to certain aspects of the core implementation, // we don't smartly use the ActiveChanged event here. @@ -357,10 +357,7 @@ public bool IsCGBDMGMode /// /// for use in dual core /// - public void ConnectInputCallbackSystem(InputCallbackSystem ics) - { - _inputCallbacks = ics; - } + public void ConnectInputCallbackSystem(InputCallbackSystem ics) => _inputCallbacks = ics; // needs to match the reverse order of Libgambatte's button enum private static readonly IReadOnlyList GB_BUTTON_ORDER_IN_BITMASK = new[] { "Down", "Up", "Left", "Right", "Start", "Select", "B", "A" }; @@ -378,7 +375,7 @@ internal void FrameAdvancePrep(IController controller) uint b = 0; if (IsSgb) { - for (var i = 0; i < 32; i++) + for (int i = 0; i < 32; i++) { b <<= 1; if (controller.IsPressed(SGB_BUTTON_ORDER_IN_BITMASK[i])) b |= 1; @@ -386,7 +383,7 @@ internal void FrameAdvancePrep(IController controller) } else { - for (var i = 0; i < 8; i++) + for (int i = 0; i < 8; i++) { b <<= 1; if (controller.IsPressed(GB_BUTTON_ORDER_IN_BITMASK[i])) b |= 1; @@ -622,7 +619,7 @@ public void SetScanlineCallback(ScanlineCallback callback, int line) callback(LibGambatte.gambatte_cpuread(GambatteState, 0xFF40)); } } - else if (line >= 0 && line <= 153) + else if (line is >= 0 and <= 153) { scanlinecb = () => callback(LibGambatte.gambatte_cpuread(GambatteState, 0xFF40)); LibGambatte.gambatte_setscanlinecallback(GambatteState, scanlinecb, line); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.ICodeDataLog.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.ICodeDataLog.cs index 60972c86de2..71b96586883 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.ICodeDataLog.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.ICodeDataLog.cs @@ -24,16 +24,6 @@ void ICodeDataLogger.NewCDL(ICodeDataLog cdl) } [FeatureNotImplemented] - public void DisassembleCDL(Stream s, ICodeDataLog cdl) - { - throw new NotImplementedException(); - // this doesn't actually do anything - /* - for (int i = 0; i < _numCores; i++) - { - _linkedCores[i].DisassembleCDL(s, cdl); - } - */ - } + public void DisassembleCDL(Stream s, ICodeDataLog cdl) => throw new NotImplementedException();// this doesn't actually do anything } } \ No newline at end of file diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.IEmulator.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.IEmulator.cs index 861bd1d5364..ccfd1cad3fa 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.IEmulator.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.IEmulator.cs @@ -17,7 +17,7 @@ public bool FrameAdvance(IController controller, bool render, bool rendersound = _linkedConts[i].Clear(); } - foreach (var s in GBLinkController.BoolButtons) + foreach (string s in GBLinkController.BoolButtons) { if (controller.IsPressed(s)) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.IInputPollable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.IInputPollable.cs index 2be0cf877f1..f84bc0845a2 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.IInputPollable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.IInputPollable.cs @@ -10,6 +10,6 @@ public partial class GambatteLink : IInputPollable public IInputCallbackSystem InputCallbacks => _inputCallbacks; - private readonly InputCallbackSystem _inputCallbacks = new InputCallbackSystem(); + private readonly InputCallbackSystem _inputCallbacks = new(); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.ISettable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.ISettable.cs index 3fbd3ada1d1..a35d58b0ffe 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.ISettable.cs @@ -8,15 +8,9 @@ public partial class GambatteLink : ISettable _settings.Clone(); - public GambatteLinkSyncSettings GetSyncSettings() - { - return _syncSettings.Clone(); - } + public GambatteLinkSyncSettings GetSyncSettings() => _syncSettings.Clone(); public PutSettingsDirtyBits PutSettings(GambatteLinkSettings o) { @@ -56,10 +50,7 @@ public GambatteLinkSettings(Gameboy.GambatteSettings one, Gameboy.GambatteSettin _linkedSettings = new Gameboy.GambatteSettings[MAX_PLAYERS] { one, two, three, four }; } - public GambatteLinkSettings Clone() - { - return new GambatteLinkSettings(_linkedSettings[P1].Clone(), _linkedSettings[P2].Clone(), _linkedSettings[P3].Clone(), _linkedSettings[P4].Clone()); - } + public GambatteLinkSettings Clone() => new(_linkedSettings[P1].Clone(), _linkedSettings[P2].Clone(), _linkedSettings[P3].Clone(), _linkedSettings[P4].Clone()); } public class GambatteLinkSyncSettings @@ -76,10 +67,7 @@ public GambatteLinkSyncSettings(Gameboy.GambatteSyncSettings one, Gameboy.Gambat _linkedSyncSettings = new Gameboy.GambatteSyncSettings[MAX_PLAYERS] { one, two, three, four }; } - public GambatteLinkSyncSettings Clone() - { - return new GambatteLinkSyncSettings(_linkedSyncSettings[P1].Clone(), _linkedSyncSettings[P2].Clone(), _linkedSyncSettings[P3].Clone(), _linkedSyncSettings[P4].Clone()); - } + public GambatteLinkSyncSettings Clone() => new(_linkedSyncSettings[P1].Clone(), _linkedSyncSettings[P2].Clone(), _linkedSyncSettings[P3].Clone(), _linkedSyncSettings[P4].Clone()); } } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.ISoundProvider.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.ISoundProvider.cs index 7e9ca7b22d0..e97b89b9d61 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.ISoundProvider.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.ISoundProvider.cs @@ -24,15 +24,9 @@ public void GetSamplesSync(out short[] samples, out int nsamp) samples = SampleBuffer; } - public void GetSamplesAsync(short[] samples) - { - throw new InvalidOperationException("Async mode is not supported."); - } + public void GetSamplesAsync(short[] samples) => throw new InvalidOperationException("Async mode is not supported."); - public void DiscardSamples() - { - _sampleBufferContains = 0; - } + public void DiscardSamples() => _sampleBufferContains = 0; // i tried using the left and right buffers and then mixing them together... it was kind of a mess of code, and slow private readonly BlipBuffer[] _linkedBlips; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.IStatable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.IStatable.cs index 437370815d1..febdb397e33 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.IStatable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.IStatable.cs @@ -13,8 +13,8 @@ public bool AvoidRewind { get { - var ret = false; - for (var i = 0; i < _numCores; i++) + bool ret = false; + for (int i = 0; i < _numCores; i++) { ret |= _linkedCores[i].AvoidRewind; } @@ -23,14 +23,11 @@ public bool AvoidRewind } } - public void SaveStateText(TextWriter writer) - { - ser.Serialize(writer, new GBLSerialized(this)); - } + public void SaveStateText(TextWriter writer) => ser.Serialize(writer, new GBLSerialized(this)); public void LoadStateText(TextReader reader) { - var s = (GBLSerialized)ser.Deserialize(reader, typeof(GBLSerialized)); + GBLSerialized s = (GBLSerialized)ser.Deserialize(reader, typeof(GBLSerialized)); if (s.NumCores != _numCores) { throw new InvalidOperationException("Core number mismatch!"); @@ -98,7 +95,7 @@ public void LoadStateBinary(BinaryReader reader) _linkSpaceSignal = reader.ReadBoolean(); } - private readonly JsonSerializer ser = new JsonSerializer { Formatting = Formatting.Indented }; + private readonly JsonSerializer ser = new() { Formatting = Formatting.Indented }; private class GBLSerialized { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.IVideoProvider.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.IVideoProvider.cs index 178f0f70f44..40c651ee222 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.IVideoProvider.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.IVideoProvider.cs @@ -23,7 +23,7 @@ public partial class GambatteLink : IVideoProvider private int[] CreateVideoBuffer() { - var b = new int[BufferWidth * BufferHeight]; + int[] b = new int[BufferWidth * BufferHeight]; for (int i = 0; i < b.Length; i++) { b[i] = -1; // GB/C screen is disabled on bootup, so it always starts as white, not black diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.cs index cf5d337b9bd..5f273ea8adf 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/Gameboy/GambatteLink.cs @@ -14,7 +14,7 @@ public partial class GambatteLink : ILinkable, ILinkedGameBoyCommon, IRomInfo [CoreConstructor(VSystemID.Raw.GBL)] public GambatteLink(CoreLoadParameters lp) { - if (lp.Roms.Count < MIN_PLAYERS || lp.Roms.Count > MAX_PLAYERS) + if (lp.Roms.Count is < MIN_PLAYERS or > MAX_PLAYERS) throw new InvalidOperationException("Wrong number of roms"); _numCores = lp.Roms.Count; @@ -31,7 +31,7 @@ public GambatteLink(CoreLoadParameters= CommandState.GB_PRINTER_COMMAND_ID && command_state < CommandState.GB_PRINTER_COMMAND_CHECKSUM_LOW) + if (command_state is >= CommandState.GB_PRINTER_COMMAND_ID and < CommandState.GB_PRINTER_COMMAND_CHECKSUM_LOW) { checksum += byte_received; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64.IDebuggable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64.IDebuggable.cs index 3658e6a7cb8..f634b098b0c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64.IDebuggable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64.IDebuggable.cs @@ -12,27 +12,27 @@ public IDictionary GetCpuFlagsAndRegisters() { // note: the approach this code takes is highly bug-prone // warning: tracer magically relies on these register names! - var ret = new Dictionary(); - var data = new byte[32 * 8 + 4 + 4 + 8 + 8 + 4 + 4 + 32 * 4 + 32 * 8]; + Dictionary ret = new(); + byte[] data = new byte[32 * 8 + 4 + 4 + 8 + 8 + 4 + 4 + 32 * 4 + 32 * 8]; api.getRegisters(data); for (int i = 0; i < 32; i++) { - var reg = BitConverter.ToInt64(data, i * 8); + long reg = BitConverter.ToInt64(data, i * 8); ret.Add(GPRnames[i] + "_lo", (int)(reg)); ret.Add(GPRnames[i] + "_hi", (int)(reg >> 32)); } - var PC = BitConverter.ToUInt32(data, 32 * 8); + uint PC = BitConverter.ToUInt32(data, 32 * 8); ret.Add("PC", (int)PC); ret.Add("LL", BitConverter.ToInt32(data, 32 * 8 + 4)); - var Lo = BitConverter.ToInt64(data, 32 * 8 + 4 + 4); + long Lo = BitConverter.ToInt64(data, 32 * 8 + 4 + 4); ret.Add("LO_lo", (int)Lo); ret.Add("LO_hi", (int)(Lo >> 32)); - var Hi = BitConverter.ToInt64(data, 32 * 8 + 4 + 4 + 8); + long Hi = BitConverter.ToInt64(data, 32 * 8 + 4 + 4 + 8); ret.Add("HI_lo", (int)Hi); ret.Add("HI_hi", (int)(Hi >> 32)); @@ -41,13 +41,13 @@ public IDictionary GetCpuFlagsAndRegisters() for (int i = 0; i < 32; i++) { - var reg_cop0 = BitConverter.ToUInt32(data, 32 * 8 + 4 + 4 + 8 + 8 + 4 + 4 + i * 4); + uint reg_cop0 = BitConverter.ToUInt32(data, 32 * 8 + 4 + 4 + 8 + 8 + 4 + 4 + i * 4); ret.Add("CP0 REG" + i, (int)reg_cop0); } for (int i = 0; i < 32; i++) { - var reg_cop1_fgr_64 = BitConverter.ToInt64(data, 32 * 8 + 4 + 4 + 8 + 8 + 4 + 4 + 32 * 4 + i * 8); + long reg_cop1_fgr_64 = BitConverter.ToInt64(data, 32 * 8 + 4 + 4 + 8 + 8 + 4 + 4 + 32 * 4 + i * 8); ret.Add("CP1 FGR REG" + i + "_lo", (int)reg_cop1_fgr_64); ret.Add("CP1 FGR REG" + i + "_hi", (int)(reg_cop1_fgr_64 >> 32)); } @@ -72,28 +72,21 @@ public IDictionary GetCpuFlagsAndRegisters() }; [FeatureNotImplemented] - public void SetCpuRegister(string register, int value) - { - throw new NotImplementedException(); - } + public void SetCpuRegister(string register, int value) => throw new NotImplementedException(); public IMemoryCallbackSystem MemoryCallbacks => _memoryCallbacks; - private readonly MemoryCallbackSystem _memoryCallbacks = new MemoryCallbackSystem(new[] { "System Bus" }); + private readonly MemoryCallbackSystem _memoryCallbacks = new(new[] { "System Bus" }); public bool CanStep(StepType type) { - switch(type) + return type switch { - case StepType.Into: - return false; // Implemented but disabled for now. Should be re-enabled once BizHawk supports mid-frame pausing. - case StepType.Out: - return false; - case StepType.Over: - return false; - } - - return false; + StepType.Into => false,// Implemented but disabled for now. Should be re-enabled once BizHawk supports mid-frame pausing. + StepType.Out => false, + StepType.Over => false, + _ => false, + }; } [FeatureNotImplemented] diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64.IDisassemblable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64.IDisassemblable.cs index 3e1a4a6ae84..8f109bf5948 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64.IDisassemblable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64.IDisassemblable.cs @@ -26,7 +26,7 @@ public IEnumerable AvailableCpus public string Disassemble(MemoryDomain m, uint addr, out int length) { length = 4; // TODO: is this right? - var instruction = m.PeekUint(addr, true); + uint instruction = m.PeekUint(addr, true); //TODO - reserve buffer here for disassembling into. allocating repeatedly will be slower var result = api.m64p_decode_op(instruction, addr); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64.IMemoryDomains.cs index 0bbfd0aaa87..bcf55d8db40 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64.IMemoryDomains.cs @@ -9,7 +9,7 @@ namespace BizHawk.Emulation.Cores.Nintendo.N64 { public partial class N64 { - private readonly List _memoryDomains = new List(); + private readonly List _memoryDomains = new(); private IMemoryDomains MemoryDomains; @@ -23,7 +23,7 @@ private void MakeMemoryDomain(string name, mupen64plusApi.N64_MEMORY id, MemoryD return; } - IntPtr memPtr = api.get_memory_ptr(id); + var memPtr = api.get_memory_ptr(id); Func peekByte; Action pokeByte; @@ -55,7 +55,7 @@ private void MakeMemoryDomain(string name, mupen64plusApi.N64_MEMORY id, MemoryD }; } - var md = new MemoryDomainDelegate(name, size, endian, peekByte, pokeByte, 4); + MemoryDomainDelegate md = new(name, size, endian, peekByte, pokeByte, 4); _memoryDomains.Add(md); } @@ -101,8 +101,8 @@ private void InitMemoryDomains() } - Func peekByte = addr => api.m64p_read_memory_8((uint) addr); - Action pokeByte = (addr, val) => api.m64p_write_memory_8((uint) addr, val); + byte peekByte(long addr) => api.m64p_read_memory_8((uint)addr); + void pokeByte(long addr, byte val) => api.m64p_write_memory_8((uint)addr, val); _memoryDomains.Add(new MemoryDomainDelegate ( diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64.ISaveRam.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64.ISaveRam.cs index 347dc9e819c..693732c468f 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64.ISaveRam.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64.ISaveRam.cs @@ -4,15 +4,9 @@ namespace BizHawk.Emulation.Cores.Nintendo.N64 { public partial class N64 : ISaveRam { - public byte[] CloneSaveRam() - { - return api.SaveSaveram(); - } + public byte[] CloneSaveRam() => api.SaveSaveram(); - public void StoreSaveRam(byte[] data) - { - api.LoadSaveram(data); - } + public void StoreSaveRam(byte[] data) => api.LoadSaveram(data); public bool SaveRamModified => true; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64.ISettable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64.ISettable.cs index 921fac29474..43316944c3f 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64.ISettable.cs @@ -6,15 +6,9 @@ namespace BizHawk.Emulation.Cores.Nintendo.N64 { public partial class N64 : ISettable { - public N64Settings GetSettings() - { - return _settings.Clone(); - } + public N64Settings GetSettings() => _settings.Clone(); - public N64SyncSettings GetSyncSettings() - { - return _syncSettings.Clone(); - } + public N64SyncSettings GetSyncSettings() => _syncSettings.Clone(); public PutSettingsDirtyBits PutSettings(N64Settings o) { @@ -45,7 +39,7 @@ static void AddN64StandardController(ControllerDefinition def, int player, bool ControllerDefinition = new("Nintendo 64 Controller"); ControllerDefinition.BoolButtons.AddRange(new[] { "Reset", "Power" }); - for (var i = 0; i < 4; i++) + for (int i = 0; i < 4; i++) { if (_syncSettings.Controllers[i].IsConnected) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64.ITraceable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64.ITraceable.cs index 1332210c252..e0955326762 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64.ITraceable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64.ITraceable.cs @@ -14,13 +14,13 @@ public void MakeTrace() { var regs = GetCpuFlagsAndRegisters(); uint pc = (uint)regs["PC"].Value; - var disasm = Disassemble(MemoryDomains.SystemBus, pc, out int length); + string disasm = Disassemble(MemoryDomains.SystemBus, pc, out int length); - var sb = new StringBuilder(); + StringBuilder sb = new(); for (int i = 1; i < 32; i++) // r0 is always zero { - var val = (regs[GPRnames[i] + "_hi"].Value << 32) | regs[GPRnames[i] + "_lo"].Value; + ulong val = (regs[GPRnames[i] + "_hi"].Value << 32) | regs[GPRnames[i] + "_lo"].Value; string name = GPRnames[i]; sb.Append($"{name}:{val:X16} "); } @@ -33,13 +33,13 @@ public void MakeTrace() for (int i = 0; i < 32; i++) // r0 is always zero { - var val = (regs["CP1 FGR REG" + i + "_hi"].Value << 32) | regs["CP1 FGR REG" + i + "_lo"].Value; + ulong val = (regs["CP1 FGR REG" + i + "_hi"].Value << 32) | regs["CP1 FGR REG" + i + "_lo"].Value; sb.Append($"f{i}:{val:X16} "); } // drop MMU co-processor regs for now - Tracer.Put(new(disassembly: $"{pc:X}: {disasm.PadRight(32)}", registerInfo: sb.ToString().Trim())); + Tracer.Put(new(disassembly: $"{pc:X}: {disasm,-32}", registerInfo: sb.ToString().Trim())); } private const string TraceHeader = "r3400: PC, mnemonic, operands, registers (GPRs, Load/Link Bit, MultHI, MultLO, Implementation/Revision, Control/Status, FGRs)"; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64.cs index 1f2974cafde..841a83837dc 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64.cs @@ -42,37 +42,20 @@ public N64(GameInfo game, byte[] file, byte[] rom, N64Settings settings, N64Sync _disableExpansionSlot = _syncSettings.DisableExpansionSlot; // Override the user's expansion slot setting if it is mentioned in the gamedb (it is mentioned but the game MUST have this setting or else not work - if (game.OptionValue("expansionpak") != null && game.OptionValue("expansionpak") == "1") + if (game.OptionValue("expansionpak") is not null and "1") { _disableExpansionSlot = false; IsOverridingUserExpansionSlotSetting = true; } byte country_code = rom[0x3E]; - switch (country_code) + Region = country_code switch { // PAL codes - case 0x44: - case 0x46: - case 0x49: - case 0x50: - case 0x53: - case 0x55: - case 0x58: - case 0x59: - _display_type = DisplayType.PAL; - break; - + 0x44 or 0x46 or 0x49 or 0x50 or 0x53 or 0x55 or 0x58 or 0x59 => DisplayType.PAL, // NTSC codes - case 0x37: - case 0x41: - case 0x45: - case 0x4a: - default: // Fallback for unknown codes - _display_type = DisplayType.NTSC; - break; - } - + _ => DisplayType.NTSC, + }; StartThreadLoop(); var videosettings = _syncSettings.GetVPS(game, _settings.VideoSizeX, _settings.VideoSizeY); @@ -147,8 +130,8 @@ public N64(GameInfo game, byte[] file, byte[] rom, N64Settings settings, N64Sync private readonly N64VideoProvider _videoProvider; private readonly N64Audio _audioProvider; - private readonly EventWaitHandle _pendingThreadEvent = new EventWaitHandle(false, EventResetMode.AutoReset); - private readonly EventWaitHandle _completeThreadEvent = new EventWaitHandle(false, EventResetMode.AutoReset); + private readonly EventWaitHandle _pendingThreadEvent = new(false, EventResetMode.AutoReset); + private readonly EventWaitHandle _completeThreadEvent = new(false, EventResetMode.AutoReset); private mupen64plusApi api; // mupen64plus DLL Api @@ -156,9 +139,6 @@ public N64(GameInfo game, byte[] file, byte[] rom, N64Settings settings, N64Sync private N64Settings _settings; private bool _pendingThreadTerminate; - - private readonly DisplayType _display_type = DisplayType.NTSC; - private Action _pendingThreadAction; private readonly bool _disableExpansionSlot = true; @@ -208,14 +188,11 @@ private void RunThreadAction(Action action) private void StartThreadLoop() { - var thread = new Thread(ThreadLoop) { IsBackground = true }; + Thread thread = new(ThreadLoop) { IsBackground = true }; thread.Start(); // will this solve the hanging process problem? } - private void EndThreadLoop() - { - RunThreadAction(() => { _pendingThreadTerminate = true; }); - } + private void EndThreadLoop() => RunThreadAction(() => { _pendingThreadTerminate = true; }); public bool FrameAdvance(IController controller, bool render, bool rendersound) { @@ -253,7 +230,7 @@ public bool FrameAdvance(IController controller, bool render, bool rendersound) public string SystemId => VSystemID.Raw.N64; - public DisplayType Region => _display_type; + public DisplayType Region { get; } = DisplayType.NTSC; public ControllerDefinition ControllerDefinition { get; private set; } = new("Nintendo 64 Controller"); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64Input.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64Input.cs index e40b8719634..407de4dba3c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64Input.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64Input.cs @@ -122,19 +122,13 @@ public int ReadController(int num) /// /// Id of the controller /// Type to which the controller pak is set. Currently only NO_PAK and MEMORY_CARD are supported - public void SetControllerPakType(int controller, N64SyncSettings.N64ControllerSettings.N64ControllerPakType type) - { - _api.SetM64PControllerPakType(controller, type); - } + public void SetControllerPakType(int controller, N64SyncSettings.N64ControllerSettings.N64ControllerPakType type) => _api.SetM64PControllerPakType(controller, type); /// /// Sets the connection status of the controller /// /// Id of the controller to connect or disconnect /// New status of the controller connection - public void SetControllerConnected(int controller, bool connectionStatus) - { - _api.SetM64PControllerConnected(controller, connectionStatus); - } + public void SetControllerConnected(int controller, bool connectionStatus) => _api.SetM64PControllerConnected(controller, connectionStatus); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64SyncSettings.Angrylion.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64SyncSettings.Angrylion.cs index 7cb38167431..b0b9b636f42 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64SyncSettings.Angrylion.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64SyncSettings.Angrylion.cs @@ -18,19 +18,13 @@ public N64AngrylionPluginSettings() [Category("Video")] public bool BobDeinterlacer { get; set; } - public N64AngrylionPluginSettings Clone() - { - return (N64AngrylionPluginSettings)MemberwiseClone(); - } + public N64AngrylionPluginSettings Clone() => (N64AngrylionPluginSettings)MemberwiseClone(); public void FillPerGameHacks(GameInfo game) { } - public PluginType GetPluginType() - { - return PluginType.Angrylion; - } + public PluginType GetPluginType() => PluginType.Angrylion; } } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64SyncSettings.GLideN64.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64SyncSettings.GLideN64.cs index a0231513bd7..9de681b3926 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64SyncSettings.GLideN64.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64SyncSettings.GLideN64.cs @@ -601,10 +601,7 @@ public enum BlendMode [Category("Emulation")] public float GammaCorrectionLevel { get; set; } - public N64GLideN64PluginSettings Clone() - { - return (N64GLideN64PluginSettings)MemberwiseClone(); - } + public N64GLideN64PluginSettings Clone() => (N64GLideN64PluginSettings)MemberwiseClone(); public void FillPerGameHacks(GameInfo game) { @@ -618,10 +615,7 @@ public void FillPerGameHacks(GameInfo game) } } - public PluginType GetPluginType() - { - return PluginType.GLideN64; - } + public PluginType GetPluginType() => PluginType.GLideN64; } } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64SyncSettings.Glide.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64SyncSettings.Glide.cs index fe8afe087fd..cd8d5df56b1 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64SyncSettings.Glide.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64SyncSettings.Glide.cs @@ -341,10 +341,7 @@ public N64GlidePluginSettings() [Category("More Per Game Settings")] public int depth_bias { get; set; } - public N64GlidePluginSettings Clone() - { - return (N64GlidePluginSettings)MemberwiseClone(); - } + public N64GlidePluginSettings Clone() => (N64GlidePluginSettings)MemberwiseClone(); public void FillPerGameHacks(GameInfo game) { @@ -386,10 +383,7 @@ public void FillPerGameHacks(GameInfo game) } } - public PluginType GetPluginType() - { - return PluginType.Glide; - } + public PluginType GetPluginType() => PluginType.Glide; } } } \ No newline at end of file diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64SyncSettings.GlideMk2.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64SyncSettings.GlideMk2.cs index a91e1902152..cd70b8762a8 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64SyncSettings.GlideMk2.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64SyncSettings.GlideMk2.cs @@ -271,10 +271,7 @@ public N64Glide64mk2PluginSettings() [Category("More Per Game Settings")] public int read_back_to_screen { get; set; } - public N64Glide64mk2PluginSettings Clone() - { - return (N64Glide64mk2PluginSettings)MemberwiseClone(); - } + public N64Glide64mk2PluginSettings Clone() => (N64Glide64mk2PluginSettings)MemberwiseClone(); public void FillPerGameHacks(GameInfo game) { @@ -320,10 +317,7 @@ public void FillPerGameHacks(GameInfo game) } } - public PluginType GetPluginType() - { - return PluginType.GlideMk2; - } + public PluginType GetPluginType() => PluginType.GlideMk2; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64SyncSettings.Rice.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64SyncSettings.Rice.cs index b544c8aafc6..10e5e06349b 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64SyncSettings.Rice.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64SyncSettings.Rice.cs @@ -417,10 +417,7 @@ public N64RicePluginSettings() [Category("Per-Game Hacks")] public int EnableHacksForGame { get; set; } - public N64RicePluginSettings Clone() - { - return (N64RicePluginSettings)MemberwiseClone(); - } + public N64RicePluginSettings Clone() => (N64RicePluginSettings)MemberwiseClone(); public void FillPerGameHacks(GameInfo game) { @@ -456,10 +453,7 @@ public void FillPerGameHacks(GameInfo game) } } - public PluginType GetPluginType() - { - return PluginType.Rice; - } + public PluginType GetPluginType() => PluginType.Rice; } } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64SyncSettings.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64SyncSettings.cs index bdbada90cb7..295e918a856 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64SyncSettings.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/N64SyncSettings.cs @@ -64,7 +64,7 @@ public N64SyncSettings Clone() // get mupenapi internal object public VideoPluginSettings GetVPS(GameInfo game, int videoSizeX, int videoSizeY) { - var ret = new VideoPluginSettings(VideoPlugin, videoSizeX, videoSizeY); + VideoPluginSettings ret = new(VideoPlugin, videoSizeX, videoSizeY); IPluginSettings ips = null; switch (VideoPlugin) { @@ -136,13 +136,13 @@ public static class PluginExtensions public static Dictionary GetPluginSettings(this IPluginSettings plugin) { // TODO: deal witn the game depedent settings - var dictionary = new Dictionary(); + Dictionary dictionary = new(); var members = plugin.GetType().GetMembers(); foreach (var member in members) { if (member.MemberType == MemberTypes.Property) { - var field = plugin.GetType().GetProperty(member.Name).GetValue(plugin, null); + object field = plugin.GetType().GetProperty(member.Name).GetValue(plugin, null); dictionary.Add(member.Name, field); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/NativeApi/mupen64plusAudioApi.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/NativeApi/mupen64plusAudioApi.cs index 9e2caaee4b0..4b36037ac57 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/NativeApi/mupen64plusAudioApi.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/NativeApi/mupen64plusAudioApi.cs @@ -8,7 +8,7 @@ internal class mupen64plusAudioApi /// /// Handle to native audio plugin /// - private IntPtr AudDll; + private readonly IntPtr AudDll; /// /// Gets the size of the mupen64plus audio buffer @@ -57,27 +57,18 @@ public mupen64plusAudioApi(mupen64plusApi core) /// /// Returns currently used sampling rate /// - public uint GetSamplingRate() - { - return (uint)dllGetAudioRate(); - } + public uint GetSamplingRate() => (uint)dllGetAudioRate(); /// /// Returns size of bytes currently in the audio buffer /// - public int GetAudioBufferSize() - { - return dllGetBufferSize(); - } + public int GetAudioBufferSize() => dllGetBufferSize(); /// /// Returns bytes currently in the audiobuffer /// Afterwards audio buffer is cleared /// buffer.Length must be greater than GetAudioBufferSize() /// - public void GetAudioBuffer(short[] buffer) - { - dllReadAudioBuffer(buffer); - } + public void GetAudioBuffer(short[] buffer) => dllReadAudioBuffer(buffer); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/NativeApi/mupen64plusCoreApi.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/NativeApi/mupen64plusCoreApi.cs index cce4af97067..4eaa4c7bb90 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/NativeApi/mupen64plusCoreApi.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/NativeApi/mupen64plusCoreApi.cs @@ -21,9 +21,9 @@ public class mupen64plusApi : IDisposable private readonly Thread m64pEmulator; - private readonly AutoResetEvent m64pEvent = new AutoResetEvent(false); - private AutoResetEvent m64pContinueEvent = new AutoResetEvent(false); - private readonly ManualResetEvent m64pStartupComplete = new ManualResetEvent(false); + private readonly AutoResetEvent m64pEvent = new(false); + private readonly AutoResetEvent m64pContinueEvent = new(false); + private readonly ManualResetEvent m64pStartupComplete = new(false); private bool event_frameend = false; private bool event_breakpoint = false; @@ -387,7 +387,7 @@ public struct m64p_breakpoint [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void FrameCallback(); - private FrameCallback m64pFrameCallback; + private readonly FrameCallback m64pFrameCallback; /// /// This will be called every time a VI occurs @@ -395,7 +395,7 @@ public struct m64p_breakpoint [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void VICallback(); - private VICallback m64pVICallback; + private readonly VICallback m64pVICallback; /// /// This will be called every time before the screen is drawn @@ -403,7 +403,7 @@ public struct m64p_breakpoint [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void RenderCallback(); - private RenderCallback m64pRenderCallback; + private readonly RenderCallback m64pRenderCallback; /// /// This will be called after the emulator is setup and is ready to be used @@ -439,7 +439,7 @@ public struct m64p_breakpoint [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void DebugInitCallback(); - private DebugInitCallback m64pDebugInitCallback; + private readonly DebugInitCallback m64pDebugInitCallback; /// /// This will be called when the debugger hits a breakpoint or executes one instruction in stepping mode @@ -447,7 +447,7 @@ public struct m64p_breakpoint [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void DebugUpdateCallback(int bpt); - private DebugUpdateCallback m64pDebugUpdateCallback; + private readonly DebugUpdateCallback m64pDebugUpdateCallback; /// /// This will be called during each vertical interrupt @@ -503,7 +503,7 @@ public struct m64p_breakpoint private DebugStep m64pDebugStep; - private readonly DynamicLibraryImportResolver Library = new DynamicLibraryImportResolver(OSTailoredCode.IsUnixHost ? "libmupen64plus.so.2" : "mupen64plus.dll"); + private readonly DynamicLibraryImportResolver Library = new(OSTailoredCode.IsUnixHost ? "libmupen64plus.so.2" : "mupen64plus.dll"); public mupen64plusApi(N64 bizhawkCore, byte[] rom, VideoPluginSettings video_settings, int SaveType, int CoreType, bool DisableExpansionSlot) { @@ -518,11 +518,11 @@ public mupen64plusApi(N64 bizhawkCore, byte[] rom, VideoPluginSettings video_set connectFunctionPointers(); // Start up the core - m64p_error result = m64pCoreStartup(0x20001, "", "", "Core", + var result = m64pCoreStartup(0x20001, "", "", "Core", null, "", IntPtr.Zero); // Open the core settings section in the config system - IntPtr core_section = IntPtr.Zero; + var core_section = IntPtr.Zero; m64pConfigOpenSection("Core", ref core_section); // Set the savetype if needed @@ -547,7 +547,7 @@ public mupen64plusApi(N64 bizhawkCore, byte[] rom, VideoPluginSettings video_set result = m64pCoreDoCommandByteArray(m64p_command.M64CMD_ROM_OPEN, rom.Length, rom); // Open the general video settings section in the config system - IntPtr video_section = IntPtr.Zero; + var video_section = IntPtr.Zero; m64pConfigOpenSection("Video-General", ref video_section); // Set the desired width and height for mupen64plus @@ -598,7 +598,7 @@ public void AsyncExecuteEmulator() private void ExecuteEmulatorThread() { emulator_running = true; - var cb = new StartupCallback(() => m64pStartupComplete.Set()); + StartupCallback cb = new(() => m64pStartupComplete.Set()); m64pCoreDoCommandPtr(m64p_command.M64CMD_EXECUTE, 0, Marshal.GetFunctionPointerForDelegate(cb)); emulator_running = false; @@ -657,7 +657,7 @@ private void connectFunctionPointers() /// Settings to put into mupen64plus public void set_video_parameters(VideoPluginSettings video_settings) { - IntPtr video_plugin_section = IntPtr.Zero; + var video_plugin_section = IntPtr.Zero; if (video_settings.Plugin == PluginType.Rice) { m64pConfigOpenSection("Video-Rice", ref video_plugin_section); @@ -688,7 +688,7 @@ public void set_video_parameters(VideoPluginSettings video_settings) if (video_settings.Parameters[Parameter].GetType() == typeof(string)) { string value = ((string)video_settings.Parameters[Parameter]); - StringBuilder sb = new StringBuilder(value); + StringBuilder sb = new(value); m64pConfigSetParameterStr(video_plugin_section, Parameter, m64p_type.M64TYPE_STRING, sb); } else @@ -712,25 +712,13 @@ public void set_video_parameters(VideoPluginSettings video_settings) } } - public int get_memory_size(N64_MEMORY id) - { - return m64pMemGetSize(id); - } + public int get_memory_size(N64_MEMORY id) => m64pMemGetSize(id); - public IntPtr get_memory_ptr(N64_MEMORY id) - { - return m64pDebugMemGetPointer(id); - } + public IntPtr get_memory_ptr(N64_MEMORY id) => m64pDebugMemGetPointer(id); - public void soft_reset() - { - m64pCoreDoCommandPtr(m64p_command.M64CMD_RESET, 0, IntPtr.Zero); - } + public void soft_reset() => m64pCoreDoCommandPtr(m64p_command.M64CMD_RESET, 0, IntPtr.Zero); - public void hard_reset() - { - m64pCoreDoCommandPtr(m64p_command.M64CMD_RESET, 1, IntPtr.Zero); - } + public void hard_reset() => m64pCoreDoCommandPtr(m64p_command.M64CMD_RESET, 1, IntPtr.Zero); public enum BreakType { @@ -862,22 +850,13 @@ public void OnBreakpoint(BreakParams breakparams) m64pEvent.Set(); //order important } - public int SaveState(byte[] buffer) - { - return m64pCoreSaveState(buffer); - } + public int SaveState(byte[] buffer) => m64pCoreSaveState(buffer); - public void LoadState(byte[] buffer) - { - m64pCoreLoadState(buffer); - } + public void LoadState(byte[] buffer) => m64pCoreLoadState(buffer); private byte[] saveram_backup; - public void InitSaveram() - { - m64pinit_saveram(); - } + public void InitSaveram() => m64pinit_saveram(); public const int kSaveramSize = 0x800 + 4 * 0x8000 + 0x20000 + 0x8000; @@ -903,15 +882,12 @@ public byte[] SaveSaveram() } } - public void LoadSaveram(byte[] src) - { - m64pload_saveram(src); - } + public void LoadSaveram(byte[] src) => m64pload_saveram(src); /* TODO: Support address masks */ public void SetBreakpoint(BreakType type, uint? address) { - m64p_breakpoint breakpoint = address is null + var breakpoint = address is null ? new m64p_breakpoint() { // For null address, specify max address range to match any address @@ -967,25 +943,16 @@ public void RemoveBreakpoint(BreakType type, uint? address) break; } - m64p_breakpoint unused = new m64p_breakpoint(); + m64p_breakpoint unused = new(); m64pDebugBreakpointCommand(m64p_dbg_bkp_command.M64P_BKP_CMD_REMOVE_IDX, (uint)index, ref unused); } - public void setTraceCallback(TraceCallback callback) - { - m64pSetTraceCallback(callback); - } + public void setTraceCallback(TraceCallback callback) => m64pSetTraceCallback(callback); - public void getRegisters(byte[] dest) - { - m64pGetRegisters(dest); - } + public void getRegisters(byte[] dest) => m64pGetRegisters(dest); - public void Step() - { - m64pDebugStep(); - } + public void Step() => m64pDebugStep(); public void Resume() { @@ -1028,13 +995,13 @@ private struct AttachedPlugin public PluginShutdown dllShutdown; } - private readonly Dictionary plugins = new Dictionary(); + private readonly Dictionary plugins = new(); public IntPtr AttachPlugin(m64p_plugin_type type, string PluginName) { static IntPtr GetDLIRPtrByRefl(DynamicLibraryImportResolver dlir) => (IntPtr) fiDLIRInternalPtr.GetValue(dlir); if (plugins.ContainsKey(type)) DetachPlugin(type); - var lib = new DynamicLibraryImportResolver(PluginName); + DynamicLibraryImportResolver lib = new(PluginName); var libPtr = GetDLIRPtrByRefl(lib); GetTypedDelegate(libPtr, "PluginStartup")(GetDLIRPtrByRefl(Library), null, null); if (m64pCoreAttachPlugin(type, libPtr) != m64p_error.M64ERR_SUCCESS) @@ -1064,11 +1031,9 @@ public void DetachPlugin(m64p_plugin_type type) public delegate void BreakpointHitCallback(uint address, BreakType type); public event BreakpointHitCallback BreakpointHit; - private void FireFrameFinishedEvent() - { + private void FireFrameFinishedEvent() => // Execute Frame Callback functions FrameFinished?.Invoke(); - } private void FireVIEvent() { @@ -1078,15 +1043,9 @@ private void FireVIEvent() m64pEvent.Set(); //order important } - private void FireRenderEvent() - { - BeforeRender?.Invoke(); - } + private void FireRenderEvent() => BeforeRender?.Invoke(); - private bool CheckBreakpointFlag(ref m64p_breakpoint bkp, m64p_dbg_bkp_flags flag) - { - return ((bkp.flags & (uint)flag) != 0); - } + private bool CheckBreakpointFlag(ref m64p_breakpoint bkp, m64p_dbg_bkp_flags flag) => ((bkp.flags & (uint)flag) != 0); private void FireBreakpointEvent(int bpt) { @@ -1096,11 +1055,11 @@ private void FireBreakpointEvent(int bpt) return; } - m64p_breakpoint breakpoint = new m64p_breakpoint(); + m64p_breakpoint breakpoint = new(); m64pDebugBreakpointCommand(m64p_dbg_bkp_command.M64P_BKP_CMD_GET_STRUCT, (uint)bpt, ref breakpoint); - BreakType type = BreakType.Execute; + var type = BreakType.Execute; if(CheckBreakpointFlag(ref breakpoint, m64p_dbg_bkp_flags.M64P_BPT_FLAG_READ)) { @@ -1114,15 +1073,12 @@ private void FireBreakpointEvent(int bpt) BreakpointHit(breakpoint.address, type); } - private void OnDebuggerInitialized() - { + private void OnDebuggerInitialized() => // Default value is M64P_DBG_RUNSTATE_PAUSED m64pDebugSetRunState(m64p_dbg_runstate.M64P_DBG_RUNSTATE_RUNNING); - } - private void CompletedFrameCallback() - { - m64pEvent.Set(); - } +#pragma warning disable IDE0051 + private void CompletedFrameCallback() => m64pEvent.Set(); +#pragma warning restore IDE0051 } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/NativeApi/mupen64plusInputApi.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/NativeApi/mupen64plusInputApi.cs index 259220cc705..dcf5850f2f2 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/NativeApi/mupen64plusInputApi.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/NativeApi/mupen64plusInputApi.cs @@ -5,7 +5,7 @@ namespace BizHawk.Emulation.Cores.Nintendo.N64.NativeApi { internal class mupen64plusInputApi { - private IntPtr InpDll; + private readonly IntPtr InpDll; /// /// Sets a callback to use when the mupen core wants controller buttons @@ -27,7 +27,7 @@ internal class mupen64plusInputApi [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate mupen64plusApi.m64p_error SetRumbleCallback(RumbleCallback ParamPtr); - private SetRumbleCallback InpSetRumbleCallback; + private readonly SetRumbleCallback InpSetRumbleCallback; /// /// This will be called every time the N64 changes @@ -77,14 +77,8 @@ public void SetM64PInputCallbacks(InputCallback inputCallback, RumbleCallback ru _ = InpSetRumbleCallback(m64pRumbleCallback = rumbleCallback); } - public void SetM64PControllerPakType(int controller, N64SyncSettings.N64ControllerSettings.N64ControllerPakType type) - { - InpSetControllerPakType(controller, (int)type); - } + public void SetM64PControllerPakType(int controller, N64SyncSettings.N64ControllerSettings.N64ControllerPakType type) => InpSetControllerPakType(controller, (int)type); - public void SetM64PControllerConnected(int controller, bool connected) - { - InpSetControllerConnected(controller, connected?1:0); - } + public void SetM64PControllerConnected(int controller, bool connected) => InpSetControllerConnected(controller, connected ? 1 : 0); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/NativeApi/mupen64plusVideoApi.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/NativeApi/mupen64plusVideoApi.cs index 3f6d073d852..0b077827561 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/NativeApi/mupen64plusVideoApi.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/N64/NativeApi/mupen64plusVideoApi.cs @@ -7,7 +7,7 @@ namespace BizHawk.Emulation.Cores.Nintendo.N64.NativeApi { internal class mupen64plusVideoApi { - private IntPtr GfxDll; + private readonly IntPtr GfxDll; /// /// Fills a provided buffer with the mupen64plus framebuffer @@ -36,31 +36,18 @@ internal class mupen64plusVideoApi [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int GetScreenTextureID(); - private GetScreenTextureID GFXGetScreenTextureID; + private readonly GetScreenTextureID GFXGetScreenTextureID; public mupen64plusVideoApi(mupen64plusApi core, VideoPluginSettings settings) { - string videoplugin; - switch (settings.Plugin) + string videoplugin = settings.Plugin switch { - default: - case PluginType.Rice: - videoplugin = "mupen64plus-video-rice.dll"; - break; - case PluginType.Glide: - videoplugin = "mupen64plus-video-glide64.dll"; - break; - case PluginType.GlideMk2: - videoplugin = "mupen64plus-video-glide64mk2.dll"; - break; - case PluginType.GLideN64: - videoplugin = "mupen64plus-video-GLideN64.dll"; - break; - case PluginType.Angrylion: - videoplugin = "mupen64plus-video-angrylion-rdp.dll"; - break; - } - + PluginType.Glide => "mupen64plus-video-glide64.dll", + PluginType.GlideMk2 => "mupen64plus-video-glide64mk2.dll", + PluginType.GLideN64 => "mupen64plus-video-GLideN64.dll", + PluginType.Angrylion => "mupen64plus-video-angrylion-rdp.dll", + _ => "mupen64plus-video-rice.dll", + }; GfxDll = core.AttachPlugin(mupen64plusApi.m64p_plugin_type.M64PLUGIN_GFX, videoplugin); GFXReadScreen2 = mupen64plusApi.GetTypedDelegate(GfxDll, "ReadScreen2"); @@ -69,10 +56,7 @@ public mupen64plusVideoApi(mupen64plusApi core, VideoPluginSettings settings) if (funcPtr != IntPtr.Zero) GFXGetScreenTextureID = (GetScreenTextureID) Marshal.GetDelegateForFunctionPointer(funcPtr, typeof(GetScreenTextureID)); } - public void GetScreenDimensions(ref int width, ref int height) - { - GFXReadScreen2Res(IntPtr.Zero, ref width, ref height, 0); - } + public void GetScreenDimensions(ref int width, ref int height) => GFXReadScreen2Res(IntPtr.Zero, ref width, ref height, 0); private int[] m64pBuffer = new int[0]; /// @@ -118,7 +102,7 @@ public class VideoPluginSettings //public Dictionary IntParameters = new Dictionary(); //public Dictionary StringParameters = new Dictionary(); - public Dictionary Parameters = new Dictionary(); + public Dictionary Parameters = new(); public int Height; public int Width; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NDS/MelonDS.IDebuggable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NDS/MelonDS.IDebuggable.cs index f186b20fbbb..2419293c387 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NDS/MelonDS.IDebuggable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NDS/MelonDS.IDebuggable.cs @@ -9,14 +9,14 @@ public partial class NDS : IDebuggable { public IDictionary GetCpuFlagsAndRegisters() { - var regs = new uint[2 * 16]; + uint[] regs = new uint[2 * 16]; _core.GetRegs(regs); - var ret = new Dictionary(); - for (var i = 0; i < 2; i++) + Dictionary ret = new(); + for (int i = 0; i < 2; i++) { - var ncpu = i == 0 ? 9 : 7; - for (var j = 0; j < 16; j++) + int ncpu = i == 0 ? 9 : 7; + for (int j = 0; j < 16; j++) { ret["ARM" + ncpu + " r" + j] = regs[i * 16 + j]; } @@ -26,16 +26,16 @@ public IDictionary GetCpuFlagsAndRegisters() public void SetCpuRegister(string register, int value) { - if (register.Length != 7 && register.Length != 8) + if (register.Length is not 7 and not 8) { throw new InvalidOperationException("Wrong String Length???"); } - var ncpu = int.Parse(register.Substring(3, 1)); + int ncpu = int.Parse(register.Substring(3, 1)); if (ncpu is not (9 or 7)) { throw new InvalidOperationException("Invalid CPU???"); } - var index = int.Parse(register.Substring(6, register.Length - 6)); + int index = int.Parse(register.Substring(6, register.Length - 6)); if (index is < 0 or > 15) { throw new InvalidOperationException("Invalid Reg Index???"); @@ -62,7 +62,7 @@ private void InitMemoryCallbacks() { LibMelonDS.MemoryCallback CreateCallback(MemoryCallbackFlags flags, Func getHasCBOfType) { - var rawFlags = (uint)flags; + uint rawFlags = (uint)flags; return address => { if (getHasCBOfType()) diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NDS/MelonDS.ISaveRam.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NDS/MelonDS.ISaveRam.cs index 573a19a6c04..21d5919bb44 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NDS/MelonDS.ISaveRam.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NDS/MelonDS.ISaveRam.cs @@ -11,32 +11,32 @@ public partial class NDS : ISaveRam { if (IsDSiWare) { - _core.DSiWareSavsLength(DSiTitleId.Lower, out var publicSavSize, out var privateSavSize, out var bannerSavSize); + _core.DSiWareSavsLength(DSiTitleId.Lower, out int publicSavSize, out int privateSavSize, out int bannerSavSize); if (publicSavSize + privateSavSize + bannerSavSize == 0) return null; _exe.AddTransientFile(Array.Empty(), "public.sav"); _exe.AddTransientFile(Array.Empty(), "private.sav"); _exe.AddTransientFile(Array.Empty(), "banner.sav"); _core.ExportDSiWareSavs(DSiTitleId.Lower); - var publicSav = _exe.RemoveTransientFile("public.sav"); - var privateSav = _exe.RemoveTransientFile("private.sav"); - var bannerSav = _exe.RemoveTransientFile("banner.sav"); + byte[] publicSav = _exe.RemoveTransientFile("public.sav"); + byte[] privateSav = _exe.RemoveTransientFile("private.sav"); + byte[] bannerSav = _exe.RemoveTransientFile("banner.sav"); if (publicSav.Length != publicSavSize || privateSav.Length != privateSavSize || bannerSav.Length != bannerSavSize) { throw new InvalidOperationException("Unexpected size difference in DSiWare sav files!"); } - var ret = new byte[publicSavSize + privateSavSize + bannerSavSize]; + byte[] ret = new byte[publicSavSize + privateSavSize + bannerSavSize]; publicSav.AsSpan().CopyTo(ret.AsSpan().Slice(0, publicSavSize)); privateSav.AsSpan().CopyTo(ret.AsSpan().Slice(publicSavSize, privateSavSize)); bannerSav.AsSpan().CopyTo(ret.AsSpan().Slice(publicSavSize + privateSavSize, bannerSavSize)); return ret; } - var length = _core.GetSaveRamLength(); + int length = _core.GetSaveRamLength(); if (length > 0) { - var ret = new byte[length]; + byte[] ret = new byte[length]; _core.GetSaveRam(ret); return ret; } @@ -48,7 +48,7 @@ public partial class NDS : ISaveRam { if (IsDSiWare) { - _core.DSiWareSavsLength(DSiTitleId.Lower, out var publicSavSize, out var privateSavSize, out var bannerSavSize); + _core.DSiWareSavsLength(DSiTitleId.Lower, out int publicSavSize, out int privateSavSize, out int bannerSavSize); if (data.Length == publicSavSize + privateSavSize + bannerSavSize) { if (publicSavSize > 0) _exe.AddReadonlyFile(data.AsSpan().Slice(0, publicSavSize).ToArray(), "public.sav"); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NDS/MelonDS.ISettable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NDS/MelonDS.ISettable.cs index 74dc095f1fc..dcf0fdd607e 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NDS/MelonDS.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NDS/MelonDS.ISettable.cs @@ -322,14 +322,14 @@ public string FirmwareMessage public PutSettingsDirtyBits PutSettings(NDSSettings o) { - var ret = NDSSettings.NeedsScreenResize(_settings, o); + bool ret = NDSSettings.NeedsScreenResize(_settings, o); _settings = o; return ret ? PutSettingsDirtyBits.ScreenLayoutChanged : PutSettingsDirtyBits.None; } public PutSettingsDirtyBits PutSyncSettings(NDSSyncSettings o) { - var ret = NDSSyncSettings.NeedsReboot(_syncSettings, o); + bool ret = NDSSyncSettings.NeedsReboot(_syncSettings, o); _syncSettings = o; return ret ? PutSettingsDirtyBits.RebootCore : PutSettingsDirtyBits.None; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NDS/MelonDS.ITraceable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NDS/MelonDS.ITraceable.cs index d0a0f1f40cc..7d6646765b4 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NDS/MelonDS.ITraceable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NDS/MelonDS.ITraceable.cs @@ -12,7 +12,7 @@ public partial class NDS private unsafe void MakeTrace(LibMelonDS.TraceMask type, uint opcode, IntPtr r, IntPtr disasm, uint cyclesOff) { - var cpu = type switch + string cpu = type switch { LibMelonDS.TraceMask.ARM7_THUMB => "ARM7 (Thumb)", LibMelonDS.TraceMask.ARM7_ARM => "ARM7", @@ -21,10 +21,10 @@ private unsafe void MakeTrace(LibMelonDS.TraceMask type, uint opcode, IntPtr r, _ => throw new InvalidOperationException("Invalid CPU Mode???"), }; - var regs = (uint*)r; + uint* regs = (uint*)r; - var isthumb = type is LibMelonDS.TraceMask.ARM7_THUMB or LibMelonDS.TraceMask.ARM9_THUMB; - var opaddr = regs![15] - (isthumb ? 4u : 8u); // handle prefetch + bool isthumb = type is LibMelonDS.TraceMask.ARM7_THUMB or LibMelonDS.TraceMask.ARM9_THUMB; + uint opaddr = regs![15] - (isthumb ? 4u : 8u); // handle prefetch Tracer.Put(new( disassembly: $"{opaddr:x8}: {opcode:x8} ".PadRight(12) + Marshal.PtrToStringAnsi(disasm)!.PadRight(36), diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NDS/MelonDS.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NDS/MelonDS.cs index 6e6d77f2515..d7b1854063a 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NDS/MelonDS.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NDS/MelonDS.cs @@ -42,7 +42,7 @@ public NDS(CoreLoadParameters lp) IsDSi = _syncSettings.UseDSi; - var roms = lp.Roms.Select(r => r.RomData).ToList(); + List roms = lp.Roms.Select(r => r.RomData).ToList(); DSiTitleId = GetDSiTitleId(roms[0]); IsDSi |= IsDSiWare; @@ -52,8 +52,8 @@ public NDS(CoreLoadParameters lp) throw new InvalidOperationException("Wrong number of ROMs!"); } - var gbacartpresent = roms.Count > 1; - var gbasrampresent = roms.Count == 3; + bool gbacartpresent = roms.Count > 1; + bool gbasrampresent = roms.Count == 3; InitMemoryCallbacks(); _tracecb = MakeTrace; @@ -71,35 +71,35 @@ public NDS(CoreLoadParameters lp) SkipMemoryConsistencyCheck = CoreComm.CorePreferences.HasFlag(CoreComm.CorePreferencesFlags.WaterboxMemoryConsistencyCheck), }, new Delegate[] { _readcb, _writecb, _execcb, _tracecb, _threadstartcb }); - var bios7 = IsDSi || _syncSettings.UseRealBIOS + byte[] bios7 = IsDSi || _syncSettings.UseRealBIOS ? CoreComm.CoreFileProvider.GetFirmwareOrThrow(new("NDS", "bios7")) : null; - var bios9 = IsDSi || _syncSettings.UseRealBIOS + byte[] bios9 = IsDSi || _syncSettings.UseRealBIOS ? CoreComm.CoreFileProvider.GetFirmwareOrThrow(new("NDS", "bios9")) : null; - var bios7i = IsDSi + byte[] bios7i = IsDSi ? CoreComm.CoreFileProvider.GetFirmwareOrThrow(new("NDS", "bios7i")) : null; - var bios9i = IsDSi + byte[] bios9i = IsDSi ? CoreComm.CoreFileProvider.GetFirmwareOrThrow(new("NDS", "bios9i")) : null; - var nand = IsDSi + byte[] nand = IsDSi ? DecideNAND(CoreComm.CoreFileProvider, (DSiTitleId.Upper & ~0xFF) == 0x00030000, roms[0][0x1B0]) : null; - var fw = IsDSi + byte[] fw = IsDSi ? CoreComm.CoreFileProvider.GetFirmwareOrThrow(new("NDS", "firmwarei")) : CoreComm.CoreFileProvider.GetFirmware(new("NDS", "firmware")); - var tmd = IsDSiWare + byte[] tmd = IsDSiWare ? GetTMDData(DSiTitleId.Full) : null; - var skipfw = _syncSettings.SkipFirmware || !_syncSettings.UseRealBIOS || fw == null; + bool skipfw = _syncSettings.SkipFirmware || !_syncSettings.UseRealBIOS || fw == null; var loadFlags = LibMelonDS.LoadFlags.NONE; @@ -120,18 +120,18 @@ public NDS(CoreLoadParameters lp) if (_syncSettings.ThreadedRendering) loadFlags |= LibMelonDS.LoadFlags.THREADED_RENDERING; - var fwSettings = new LibMelonDS.FirmwareSettings(); - var name = Encoding.UTF8.GetBytes(_syncSettings.FirmwareUsername); + LibMelonDS.FirmwareSettings fwSettings = new(); + byte[] name = Encoding.UTF8.GetBytes(_syncSettings.FirmwareUsername); fwSettings.FirmwareUsernameLength = name.Length; fwSettings.FirmwareLanguage = _syncSettings.FirmwareLanguage; if (!IsDSi && _syncSettings.FirmwareStartUp == NDSSyncSettings.StartUp.AutoBoot) fwSettings.FirmwareLanguage |= (NDSSyncSettings.Language)0x40; fwSettings.FirmwareBirthdayMonth = _syncSettings.FirmwareBirthdayMonth; fwSettings.FirmwareBirthdayDay = _syncSettings.FirmwareBirthdayDay; fwSettings.FirmwareFavouriteColour = _syncSettings.FirmwareFavouriteColour; - var message = _syncSettings.FirmwareMessage.Length != 0 ? Encoding.UTF8.GetBytes(_syncSettings.FirmwareMessage) : new byte[1]; + byte[] message = _syncSettings.FirmwareMessage.Length != 0 ? Encoding.UTF8.GetBytes(_syncSettings.FirmwareMessage) : new byte[1]; fwSettings.FirmwareMessageLength = message.Length; - var loadData = new LibMelonDS.LoadData + LibMelonDS.LoadData loadData = new() { DsRomLength = roms[0].Length, GbaRomLength = gbacartpresent ? roms[1].Length : 0, @@ -228,7 +228,7 @@ public NDS(CoreLoadParameters lp) private static (ulong Full, uint Upper, uint Lower) GetDSiTitleId(IReadOnlyList file) { ulong titleId = 0; - for (var i = 0; i < 8; i++) + for (int i = 0; i < 8; i++) { titleId <<= 8; titleId |= file[0x237 - i]; @@ -239,7 +239,7 @@ private static (ulong Full, uint Upper, uint Lower) GetDSiTitleId(IReadOnlyList< private static byte[] DecideNAND(ICoreFileProvider cfp, bool isDSiEnhanced, byte regionFlags) { // TODO: priority settings? - var nandOptions = new List { "NAND (JPN)", "NAND (USA)", "NAND (EUR)", "NAND (AUS)", "NAND (CHN)", "NAND (KOR)" }; + List nandOptions = new() { "NAND (JPN)", "NAND (USA)", "NAND (EUR)", "NAND (AUS)", "NAND (CHN)", "NAND (KOR)" }; if (isDSiEnhanced) // NB: Core makes cartridges region free regardless, DSiWare must follow DSi region locking however (we'll enforce it regardless) { nandOptions.Clear(); @@ -251,9 +251,9 @@ private static byte[] DecideNAND(ICoreFileProvider cfp, bool isDSiEnhanced, byte if (regionFlags.Bit(5)) nandOptions.Add("NAND (KOR)"); } - foreach (var option in nandOptions) + foreach (string option in nandOptions) { - var ret = cfp.GetFirmware(new("NDS", option)); + byte[] ret = cfp.GetFirmware(new("NDS", option)); if (ret is not null) return ret; } @@ -262,7 +262,7 @@ private static byte[] DecideNAND(ICoreFileProvider cfp, bool isDSiEnhanced, byte private static byte[] GetTMDData(ulong titleId) { - using var zip = new ZipArchive(Zstd.DecompressZstdStream(new MemoryStream(Resources.TMDS.Value)), ZipArchiveMode.Read, false); + using ZipArchive zip = new(Zstd.DecompressZstdStream(new MemoryStream(Resources.TMDS.Value)), ZipArchiveMode.Read, false); using var tmd = zip.GetEntry($"{titleId:x16}.tmd")?.Open() ?? throw new($"Cannot find TMD for title ID {titleId:x16}, please report"); return tmd.ReadAllBytes(); } @@ -270,11 +270,11 @@ private static byte[] GetTMDData(ulong titleId) // todo: wire this up w/ frontend public byte[] GetNAND() { - var length = _core.GetNANDSize(); + int length = _core.GetNANDSize(); if (length > 0) { - var ret = new byte[length]; + byte[] ret = new byte[length]; _core.GetNANDData(ret); return ret; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NDS/NDSDisassembler.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NDS/NDSDisassembler.cs index 111f26932cb..516baff3997 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NDS/NDSDisassembler.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NDS/NDSDisassembler.cs @@ -30,7 +30,7 @@ public override string Disassemble(MemoryDomain m, uint addr, out int length) NdsSysBus.UseArm9 = int.Parse(Cpu.Substring(5, 1)) == 5; } - var ret = new byte[80]; + byte[] ret = new byte[80]; var type = Cpu switch { "ARM v5" => LibMelonDS.TraceMask.ARM9_ARM, @@ -43,14 +43,14 @@ public override string Disassemble(MemoryDomain m, uint addr, out int length) if (Cpu.Length == 14) { addr &= ~1u; - var op = m.PeekByte(addr) | (uint)m.PeekByte(addr + 1) << 8; + uint op = m.PeekByte(addr) | (uint)m.PeekByte(addr + 1) << 8; _core.GetDisassembly(type, op, ret); length = 2; } else { addr &= ~3u; - var op = m.PeekByte(addr) + uint op = m.PeekByte(addr) | (uint)m.PeekByte(addr + 1) << 8 | (uint)m.PeekByte(addr + 2) << 16 | (uint)m.PeekByte(addr + 3) << 24; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NDS/NDSFirmware.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NDS/NDSFirmware.cs index c3fe952c57a..ad1a12e10fd 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NDS/NDSFirmware.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NDS/NDSFirmware.cs @@ -11,7 +11,7 @@ public class NDSFirmware { public static bool MaybeWarnIfBadFw(byte[] fw, CoreComm comm) { - if (fw.Length != 0x20000 && fw.Length != 0x40000 && fw.Length != 0x80000) + if (fw.Length is not 0x20000 and not 0x40000 and not 0x80000) { comm.ShowMessage("Bad firmware length detected! Firmware might not work!"); return false; @@ -21,8 +21,8 @@ public static bool MaybeWarnIfBadFw(byte[] fw, CoreComm comm) comm.ShowMessage("Hacked firmware detected! Firmware might not work!"); return false; } - var fwMask = fw.Length - 1; - var badCrc16s = string.Empty; + int fwMask = fw.Length - 1; + string badCrc16s = string.Empty; if (!VerifyCrc16(fw, 0x2C, (fw[0x2C + 1] << 8) | fw[0x2C], 0x0000, 0x2A)) { badCrc16s += " Wifi "; @@ -58,12 +58,12 @@ public static bool MaybeWarnIfBadFw(byte[] fw, CoreComm comm) public static void SanitizeFw(byte[] fw) { - var fwMask = fw.Length - 1; - var apstart = new int[3] { 0x07FA00 & fwMask, 0x07FB00 & fwMask, 0x07FC00 & fwMask }; + int fwMask = fw.Length - 1; + int[] apstart = new int[3] { 0x07FA00 & fwMask, 0x07FB00 & fwMask, 0x07FC00 & fwMask }; - for (var i = 0; i < 3; i++) + for (int i = 0; i < 3; i++) { - for (var j = 0; j < 0x100; j++) + for (int j = 0; j < 0x100; j++) { fw[apstart[i] + j] = 0; } @@ -78,21 +78,21 @@ public static void SanitizeFw(byte[] fw) // F8 98 C1 E6 CC 5D 92 E1 85 8C 96 // different mac address // 18 90 15 E9 7C 1D F1 E1 85 74 02 - var macdependentbytes = new byte[11] { 0xF8, 0x98, 0xC1, 0xE6, 0xCC, 0x9D, 0xBE, 0xE1, 0x85, 0x71, 0x5F }; + byte[] macdependentbytes = new byte[11] { 0xF8, 0x98, 0xC1, 0xE6, 0xCC, 0x9D, 0xBE, 0xE1, 0x85, 0x71, 0x5F }; - var apoffset = 0xF5; + int apoffset = 0xF5; - for (var i = 0; i < 2; i++) + for (int i = 0; i < 2; i++) { - for (var j = 0; j < 11; j++) + for (int j = 0; j < 11; j++) { fw[apstart[i] + apoffset + j] = macdependentbytes[j]; } } - var ffoffset = 0xE7; + int ffoffset = 0xE7; - for (var i = 0; i < 3; i++) + for (int i = 0; i < 3; i++) { fw[apstart[i] + ffoffset] = 0xFF; } @@ -101,9 +101,9 @@ public static void SanitizeFw(byte[] fw) fw[apstart[2] + 0xFE] = 0x0A; fw[apstart[2] + 0xFF] = 0xF0; - var usersettings = new int[2] { 0x7FE00 & fwMask, 0x7FF00 & fwMask }; + int[] usersettings = new int[2] { 0x7FE00 & fwMask, 0x7FF00 & fwMask }; - for (var i = 0; i < 2; i++) + for (int i = 0; i < 2; i++) { unsafe { @@ -134,13 +134,13 @@ public static void SanitizeFw(byte[] fw) private static unsafe ushort Crc16(byte* data, int len, int seed) { - var poly = new ushort[8] { 0xC0C1, 0xC181, 0xC301, 0xC601, 0xCC01, 0xD801, 0xF001, 0xA001 }; + ushort[] poly = new ushort[8] { 0xC0C1, 0xC181, 0xC301, 0xC601, 0xCC01, 0xD801, 0xF001, 0xA001 }; - for (var i = 0; i < len; i++) + for (int i = 0; i < len; i++) { seed ^= data[i]; - for (var j = 0; j < 8; j++) + for (int j = 0; j < 8; j++) { if ((seed & 0x1) != 0) { @@ -159,10 +159,10 @@ private static unsafe ushort Crc16(byte* data, int len, int seed) private static unsafe bool VerifyCrc16(byte[] fw, int startaddr, int len, int seed, int crcaddr) { - var storedCrc16 = (ushort)((fw[crcaddr + 1] << 8) | fw[crcaddr]); + ushort storedCrc16 = (ushort)((fw[crcaddr + 1] << 8) | fw[crcaddr]); fixed (byte* start = &fw[startaddr]) { - var actualCrc16 = Crc16(start, len, seed); + ushort actualCrc16 = Crc16(start, len, seed); return storedCrc16 == actualCrc16; } } @@ -182,16 +182,16 @@ private static unsafe bool VerifyCrc16(byte[] fw, int startaddr, int len, int se private static bool CheckDecryptedCodeChecksum(byte[] fw, CoreComm comm) { - if (!GetDecryptedFirmware(fw, fw.Length, out var decryptedfw, out var decrypedfwlen)) + if (!GetDecryptedFirmware(fw, fw.Length, out var decryptedfw, out int decrypedfwlen)) { comm.ShowMessage("Firmware could not be decryped for verification! This firmware might be not work!"); return false; } - var DecryptedFirmware = new byte[decrypedfwlen]; + byte[] DecryptedFirmware = new byte[decrypedfwlen]; Marshal.Copy(decryptedfw, DecryptedFirmware, 0, decrypedfwlen); FreeDecryptedFirmware(decryptedfw); - var hash = SHA1Checksum.ComputeDigestHex(DecryptedFirmware); + string hash = SHA1Checksum.ComputeDigestHex(DecryptedFirmware); if (hash != goodhashes[0] && hash != goodhashes[1] && hash != goodhashes[2]) { comm.ShowMessage("Potentially bad firmware dump! Decrypted hash " + hash + " does not match known good dumps."); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/APU.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/APU.cs index 337ad9c43dc..e4fb08201c9 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/APU.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/APU.cs @@ -126,7 +126,7 @@ public void SyncState(Serializer ser) ser.EndSection(); } - public bool IsLenCntNonZero() { return len_cnt > 0; } + public bool IsLenCntNonZero() => len_cnt > 0; public void WriteReg(int addr, byte val) { @@ -535,7 +535,7 @@ public void SyncState(Serializer ser) ser.EndSection(); } - public bool IsLenCntNonZero() { return len_cnt > 0; } + public bool IsLenCntNonZero() => len_cnt > 0; public void set_lenctr_en(int value) { @@ -917,10 +917,7 @@ public void set_lenctr_en(bool en) apu.SyncIRQ(); } - public bool IsLenCntNonZero() - { - return sample_length != 0; - } + public bool IsLenCntNonZero() => sample_length != 0; public void WriteReg(int addr, byte val) { @@ -1028,10 +1025,7 @@ public void SyncState(Serializer ser) private int sequencer_counter, sequencer_step, sequencer_mode, sequencer_irq_inhibit, sequencer_irq_assert; private bool sequencer_irq, sequence_reset_pending, sequencer_irq_clear_pending, sequencer_irq_flag; - public void RunDMCFetch() - { - dmc.Fetch(); - } + public void RunDMCFetch() => dmc.Fetch(); private readonly int[][] sequencer_lut = new int[2][]; @@ -1110,10 +1104,7 @@ private void sequencer_tick() sequencer_check(); } - public void SyncIRQ() - { - irq_pending = sequencer_irq | dmc_irq; - } + public void SyncIRQ() => irq_pending = sequencer_irq | dmc_irq; private void sequencer_check() { @@ -1373,7 +1364,7 @@ public void RunOneLast() // the current code simply matches known behaviour if (pending_reg != -1) { - if ( pending_reg == 0x4003 || pending_reg == 0x4007 || pending_reg == 0x4010 || pending_reg == 0x4015 || pending_reg == 0x4017) + if ( pending_reg is 0x4003 or 0x4007 or 0x4010 or 0x4015 or 0x4017) { _WriteReg(pending_reg, pending_val); pending_reg = -1; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/BANDAI_74_161_161_32.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/BANDAI_74_161_161_32.cs index c58537ec625..ae1920d115d 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/BANDAI_74_161_161_32.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/BANDAI_74_161_161_32.cs @@ -43,10 +43,7 @@ public override void SyncState(Serializer ser) ser.Sync(nameof(prg_banks_16k), ref prg_banks_16k, false); } - private void SyncPRG() - { - prg_banks_16k[0] = prg_bank_16k; - } + private void SyncPRG() => prg_banks_16k[0] = prg_bank_16k; public override void WritePrg(int addr, byte value) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Bonza.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Bonza.cs index deaa1e5580d..d1bde235124 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Bonza.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Bonza.cs @@ -49,10 +49,7 @@ public override byte ReadExp(int addr) return base.ReadExp(addr); } - public override byte ReadPrg(int addr) - { - return Rom[(_prgReg * 0x8000) + (addr & 0x7FFF)]; - } + public override byte ReadPrg(int addr) => Rom[(_prgReg * 0x8000) + (addr & 0x7FFF)]; public override byte ReadPpu(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/CNROM.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/CNROM.cs index 85c83aaa74b..8c98328af55 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/CNROM.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/CNROM.cs @@ -158,9 +158,6 @@ public override void SyncState(Serializer ser) ser.Sync(nameof(chr_enabled), ref chr_enabled); } - public override byte ReadPrg(int addr) - { - return Rom[addr & prg_byte_mask]; - } + public override byte ReadPrg(int addr) => Rom[addr & prg_byte_mask]; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Cony.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Cony.cs index 2d1abb76c19..cd285d1ddf8 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Cony.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Cony.cs @@ -178,7 +178,7 @@ public override void ClockCpu() public override void WriteExp(int addr, byte value) { - if (addr >= 0x1100 && addr <= 0x1103) + if (addr is >= 0x1100 and <= 0x1103) _low[addr & 0x3] = value; else base.WriteExp(addr, value); @@ -188,7 +188,7 @@ public override byte ReadExp(int addr) { if (addr == 0x1000) return (byte)((NES.DB & 0xFC) | 0); - else if (addr >= 0x1100 && addr <= 0x1103) + else if (addr is >= 0x1100 and <= 0x1103) return _low[addr & 0x3]; else return base.ReadExp(addr); @@ -368,7 +368,7 @@ public override void ClockCpu() public override void WriteExp(int addr, byte value) { - if (addr >= 0x1100 && addr <= 0x1103) + if (addr is >= 0x1100 and <= 0x1103) _low[addr & 0x3] = value; else base.WriteExp(addr, value); @@ -378,7 +378,7 @@ public override byte ReadExp(int addr) { if (addr == 0x1000) return (byte)((NES.DB & 0xFC) | 0); - else if (addr >= 0x1100 && addr <= 0x1103) + else if (addr is >= 0x1100 and <= 0x1103) return _low[addr & 0x3]; else return base.ReadExp(addr); @@ -401,7 +401,7 @@ public override bool Configure(EDetectionOrigin origin) { case "MAPPER083": // We need one of the Cony boards to throw an error on an unexpected cart size, so we picked this one - if (Cart.PrgSize != 128 && Cart.PrgSize != 256 && Cart.PrgSize != 1024) + if (Cart.PrgSize is not 128 and not 256 and not 1024) { throw new InvalidOperationException("Unexpected prg size of " + Cart.PrgSize + " for Mapper 83"); } @@ -436,7 +436,7 @@ public override void WritePrg(int addr, byte value) prg_regs[0] = (byte)(value & prg_bank_mask_16k); } - else if (addr >= 0x310 && addr < 0x318) + else if (addr is >= 0x310 and < 0x318) { chr_regs[addr & 0x7] = value; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/CoolBoy.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/CoolBoy.cs index 9009b742d47..84e443d9e08 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/CoolBoy.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/CoolBoy.cs @@ -120,9 +120,6 @@ public override void SyncState(Serializer ser) ser.Sync(nameof(exp), ref exp, false); } - public override void NesSoftReset() - { - Array.Clear(exp, 0, 4); - } + public override void NesSoftReset() => Array.Clear(exp, 0, 4); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/DatachBarcode.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/DatachBarcode.cs index 8e2d9f12e21..590a17ea66f 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/DatachBarcode.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/DatachBarcode.cs @@ -75,14 +75,8 @@ public void Reset() data = new byte[0]; } - public bool IsTransferring() - { - return stream_idx < data.Length; - } - private static bool IsDigtsSupported(int count) - { - return count.In(MIN_DIGITS, MAX_DIGITS); - } + public bool IsTransferring() => stream_idx < data.Length; + private static bool IsDigtsSupported(int count) => count.In(MIN_DIGITS, MAX_DIGITS); public static bool ValidString(string s, out string why) { @@ -95,7 +89,7 @@ public static bool ValidString(string s, out string why) } foreach (char c in s) { - if (c < '0' || c > '9') + if (c is < '0' or > '9') { why = "String must be numeric only!"; return false; @@ -107,7 +101,7 @@ public static bool ValidString(string s, out string why) public void Transfer(string s) { - if (!ValidString(s, out var why)) + if (!ValidString(s, out string why)) throw new InvalidOperationException(why); Reset(); @@ -116,13 +110,13 @@ public void Transfer(string s) for (int i = 0; i < s.Length; i++) { - if (s[i] >= '0' && s[i] <= '9') + if (s[i] is >= '0' and <= '9') code[i] = (byte)(s[i] - '0'); else throw new InvalidOperationException("s must be numeric only"); } - var result = new System.IO.MemoryStream(); + System.IO.MemoryStream result = new(); for (int i = 0; i < 33; i++) result.WriteByte(8); @@ -223,9 +217,6 @@ public void Clock() /// /// d3 /// - public bool GetOutput() - { - return output == 8; - } + public bool GetOutput() => output == 8; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/ExROM.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/ExROM.cs index 3302df54040..b480f2f375d 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/ExROM.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/ExROM.cs @@ -44,10 +44,7 @@ internal sealed class ExROM : NesBoardBase private int last_nt_read; private bool irq_audio; - public MemoryDomain GetExRAM() - { - return new MemoryDomainByteArray("ExRAM", MemoryDomain.Endian.Little, EXRAM, true, 1); - } + public MemoryDomain GetExRAM() => new MemoryDomainByteArray("ExRAM", MemoryDomain.Endian.Little, EXRAM, true, 1); /// /// use with caution @@ -430,7 +427,7 @@ public override byte ReadPrg(int addr) { byte ret; int offs = addr & 0x1fff; - int bank = PRGGetBank(addr, out var ram); + int bank = PRGGetBank(addr, out bool ram); if (ram) ret = ReadWRAMActual(bank, offs); @@ -454,7 +451,7 @@ public byte PeekPRG(int addr) { byte ret; int offs = addr & 0x1fff; - int bank = PRGGetBank(addr, out var ram); + int bank = PRGGetBank(addr, out bool ram); if (ram) ret = ReadWRAMActual(bank, offs); @@ -467,7 +464,7 @@ public byte PeekPRG(int addr) public override void WritePrg(int addr, byte value) { - int bank = PRGGetBank(addr, out var ram); + int bank = PRGGetBank(addr, out bool ram); if (ram) WriteWRAMActual(bank, addr & 0x1fff, value); } @@ -475,7 +472,7 @@ public override void WritePrg(int addr, byte value) public override void WriteExp(int addr, byte value) { //NES.LogLine("MMC5 WriteEXP: ${0:x4} = ${1:x2}", addr, value); - if (addr >= 0x1000 && addr <= 0x1015) + if (addr is >= 0x1000 and <= 0x1015) { audio.WriteExp(addr + 0x4000, value); return; @@ -662,10 +659,7 @@ public byte PeekEXP(int addr) return ret; } - private void SyncIRQ() - { - IrqSignal = (irq_pending && irq_enabled) || irq_audio; - } + private void SyncIRQ() => IrqSignal = (irq_pending && irq_enabled) || irq_audio; public override void ClockPpu() { @@ -704,10 +698,7 @@ public override void ClockPpu() } - public override void ClockCpu() - { - audio.Clock(); - } + public override void ClockCpu() => audio.Clock(); private void SetBank(int[] target, int offset, int size, int value) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/FFE/Mapper006.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/FFE/Mapper006.cs index 085ef54ab52..0f06e4148c0 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/FFE/Mapper006.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/FFE/Mapper006.cs @@ -43,7 +43,7 @@ public override void SyncState(Serializer ser) public override void WriteExp(int addr, byte value) { // Mirroring - if (addr == 0x2FE || addr == 0x2FF) + if (addr is 0x2FE or 0x2FF) { int mirr = ((addr << 1) & 2) | ((value >> 4) & 1); switch (mirr) @@ -64,7 +64,7 @@ public override void WriteExp(int addr, byte value) } // IRQ - else if (addr >= 0x500 && addr <= 0x503) + else if (addr is >= 0x500 and <= 0x503) { switch (addr) { @@ -87,10 +87,7 @@ public override void WriteExp(int addr, byte value) } } - public override void WritePrg(int addr, byte value) - { - _reg = value; - } + public override void WritePrg(int addr, byte value) => _reg = value; public override byte ReadPrg(int addr) { @@ -144,9 +141,6 @@ private void ClockIRQ() SyncIRQ(); } - private void SyncIRQ() - { - SyncIRQ(_irqPending); - } + private void SyncIRQ() => SyncIRQ(_irqPending); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/FFE/Mapper017.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/FFE/Mapper017.cs index feb2cbfeb87..41ccc0006b4 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/FFE/Mapper017.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/FFE/Mapper017.cs @@ -161,9 +161,6 @@ private void ClockIRQ() SyncIRQ(); } - private void SyncIRQ() - { - SyncIRQ(irq_pending); - } + private void SyncIRQ() => SyncIRQ(irq_pending); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/FS304.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/FS304.cs index 33569dc6f20..6e6107c88c1 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/FS304.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/FS304.cs @@ -47,9 +47,6 @@ public override void WriteExp(int addr, byte value) prg &= prg_mask_32k; } - public override byte ReadPrg(int addr) - { - return Rom[addr | prg << 15]; - } + public override byte ReadPrg(int addr) => Rom[addr | prg << 15]; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/GameGenie.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/GameGenie.cs index 8c21eb78bc8..99dfbbacd05 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/GameGenie.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/GameGenie.cs @@ -65,9 +65,6 @@ public override byte ReadPpu(int addr) return PatternTables[addr & 0xff]; } - public override void WritePrg(int addr, byte value) - { - NES.LogLine("{0:x4}<={1:x2}", addr + 0x8000, value); - } + public override void WritePrg(int addr, byte value) => NES.LogLine("{0:x4}<={1:x2}", addr + 0x8000, value); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/GxROM.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/GxROM.cs index 337ff4955ba..a634bc1334f 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/GxROM.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/GxROM.cs @@ -55,10 +55,7 @@ public override bool Configure(EDetectionOrigin origin) return true; } - public override byte ReadPrg(int addr) - { - return Rom[addr + (prg<<15)]; - } + public override byte ReadPrg(int addr) => Rom[addr + (prg << 15)]; public override byte ReadPpu(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/IC_74x377.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/IC_74x377.cs index 143b2802dc5..6a3e754dace 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/IC_74x377.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/IC_74x377.cs @@ -53,10 +53,7 @@ public override bool Configure(EDetectionOrigin origin) return true; } - public override byte ReadPrg(int addr) - { - return Rom[addr + (prg_bank_32k << 15)]; - } + public override byte ReadPrg(int addr) => Rom[addr + (prg_bank_32k << 15)]; public override byte ReadPpu(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/IREM_TAM_S1.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/IREM_TAM_S1.cs index 306ef7189a3..685ebc04366 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/IREM_TAM_S1.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/IREM_TAM_S1.cs @@ -36,10 +36,7 @@ public override void SyncState(Serializer ser) ser.Sync(nameof(prg_banks_16k), ref prg_banks_16k, false); } - private void SyncPRG() - { - prg_banks_16k[1] = prg_bank_16k; - } + private void SyncPRG() => prg_banks_16k[1] = prg_bank_16k; public override void WritePrg(int addr, byte value) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Irem_H3001.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Irem_H3001.cs index 929a0b2515e..5fd2400b170 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Irem_H3001.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Irem_H3001.cs @@ -79,10 +79,7 @@ public override void ClockCpu() SyncIRQ(); } - private void SyncIRQ() - { - IrqSignal = irq_asserted; - } + private void SyncIRQ() => IrqSignal = irq_asserted; public override byte ReadPrg(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/JALECO_JF_05_06_07.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/JALECO_JF_05_06_07.cs index 2488793a33c..cc3660e36e1 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/JALECO_JF_05_06_07.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/JALECO_JF_05_06_07.cs @@ -71,9 +71,6 @@ public override byte ReadPpu(int addr) return base.ReadPpu(addr); } - public override byte ReadPrg(int addr) - { - return Rom[addr & prg_byte_mask]; - } + public override byte ReadPrg(int addr) => Rom[addr & prg_byte_mask]; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/MMC3.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/MMC3.cs index 214fb46aaa3..f0817352dd5 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/MMC3.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/MMC3.cs @@ -49,7 +49,7 @@ public EMMC3Type MMC3Type set { _mmc3type = value; - oldIrqType = (_mmc3type == EMMC3Type.MMC3A || _mmc3type == EMMC3Type.MMC3BNonSharp || _mmc3type == EMMC3Type.MMC6); + oldIrqType = (_mmc3type is EMMC3Type.MMC3A or EMMC3Type.MMC3BNonSharp or EMMC3Type.MMC6); } } @@ -161,10 +161,7 @@ public virtual void SyncState(Serializer ser) //some MMC3 variants pass along the irq signal differently (primarily different delay) //this is overrideable so that those boards can get signals whenever this mmc3 base class code manipulates the irq line - public virtual void SyncIRQ() - { - board.SyncIRQ(irq_pending); - } + public virtual void SyncIRQ() => board.SyncIRQ(irq_pending); public byte cmd; @@ -325,15 +322,9 @@ internal abstract class MMC3Board_Base : NesBoardBase public MMC3 mmc3; public int extra_vrom; - public override void AddressPpu(int addr) - { - mmc3.AddressPPU(addr); - } + public override void AddressPpu(int addr) => mmc3.AddressPPU(addr); - public override void ClockPpu() - { - mmc3.ClockPPU(); - } + public override void ClockPpu() => mmc3.ClockPPU(); //configuration protected int prg_mask, chr_mask; @@ -345,15 +336,9 @@ public override void SyncState(Serializer ser) ser.Sync(nameof(extra_vrom), ref extra_vrom); } - protected virtual int Get_CHRBank_1K(int addr) - { - return mmc3.Get_CHRBank_1K(addr); - } + protected virtual int Get_CHRBank_1K(int addr) => mmc3.Get_CHRBank_1K(addr); - protected virtual int Get_PRGBank_8K(int addr) - { - return mmc3.Get_PRGBank_8K(addr); - } + protected virtual int Get_PRGBank_8K(int addr) => mmc3.Get_PRGBank_8K(addr); protected virtual int MapCHR(int addr) { @@ -389,10 +374,7 @@ public override void WritePpu(int addr, byte value) } - public override void WritePrg(int addr, byte value) - { - mmc3.WritePRG(addr, value); - } + public override void WritePrg(int addr, byte value) => mmc3.WritePRG(addr, value); public override byte ReadPrg(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper037.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper037.cs index 4e1e12c4971..fcac88a466c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper037.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper037.cs @@ -39,14 +39,8 @@ public override void WriteWram(int addr, byte value) mmc3.Sync(); // unneeded? } - protected override int Get_CHRBank_1K(int addr) - { - return base.Get_CHRBank_1K(addr) | (exreg << 5 & 0x80); - } + protected override int Get_CHRBank_1K(int addr) => base.Get_CHRBank_1K(addr) | (exreg << 5 & 0x80); - protected override int Get_PRGBank_8K(int addr) - { - return (exreg << 2 & 0x10) | ((exreg & 3) == 3 ? 8 : 0) | (base.Get_PRGBank_8K(addr) & (exreg << 1 | 7)); - } + protected override int Get_PRGBank_8K(int addr) => (exreg << 2 & 0x10) | ((exreg & 3) == 3 ? 8 : 0) | (base.Get_PRGBank_8K(addr) & (exreg << 1 | 7)); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper049.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper049.cs index 0490302fc75..76f719788c8 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper049.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper049.cs @@ -53,9 +53,6 @@ protected override int Get_PRGBank_8K(int addr) return prg * 4 + block_offset; } - protected override int Get_CHRBank_1K(int addr) - { - return (base.Get_CHRBank_1K(addr)&0x7F) + block * 128; - } + protected override int Get_CHRBank_1K(int addr) => (base.Get_CHRBank_1K(addr) & 0x7F) + block * 128; } } \ No newline at end of file diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper114.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper114.cs index 5ba203ef6d1..affd857557d 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper114.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper114.cs @@ -88,7 +88,7 @@ public override byte ReadPrg(int addr) { if ((EXPREGS[0] & 0x80) > 0) { - var bank = EXPREGS[0] & 0x1F & prg_mask_16; + int bank = EXPREGS[0] & 0x1F & prg_mask_16; return Rom[(bank << 14) + (addr & 0x3FFF)]; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper123.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper123.cs index 0d2b8f49ecd..a059b26c70f 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper123.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper123.cs @@ -72,7 +72,7 @@ public override byte ReadPrg(int addr) { if ((EXPREGS[0] & 0x40) > 0) { - var bank = (EXPREGS[0] & 5) | ((EXPREGS[0] & 8) >> 2) | ((EXPREGS[0] & 0x20) >> 2); + int bank = (EXPREGS[0] & 5) | ((EXPREGS[0] & 8) >> 2) | ((EXPREGS[0] & 0x20) >> 2); if ((EXPREGS[0] & 2) > 0) { return Rom[((bank >> 1) << 15) + (addr & 0x7FFF)]; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper134.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper134.cs index 00f21102cbb..08e4fd455e4 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper134.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper134.cs @@ -36,14 +36,8 @@ public override void WriteWram(int addr, byte value) base.WriteWram(addr, value); } - protected override int Get_PRGBank_8K(int addr) - { - return (base.Get_PRGBank_8K(addr) &0x1F) | ((reg & 0x2) << 4); - } + protected override int Get_PRGBank_8K(int addr) => (base.Get_PRGBank_8K(addr) & 0x1F) | ((reg & 0x2) << 4); - protected override int Get_CHRBank_1K(int addr) - { - return base.Get_CHRBank_1K(addr) | (reg <<3 & 0x100); - } + protected override int Get_CHRBank_1K(int addr) => base.Get_CHRBank_1K(addr) | (reg << 3 & 0x100); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper182.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper182.cs index b6df8d8f1bb..f83e4cf39ed 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper182.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper182.cs @@ -43,9 +43,6 @@ public override void WritePrg(int addr, byte value) private static readonly byte[] scramble_table = { 0, 3, 1, 5, 6, 7, 2, 4 }; - private static int scramble_A000(byte val) - { - return (val & ~0x7) | scramble_table[val & 0x7]; - } + private static int scramble_A000(byte val) => (val & ~0x7) | scramble_table[val & 0x7]; } } \ No newline at end of file diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper187.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper187.cs index 57d0ba64e07..da27787d9f4 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper187.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper187.cs @@ -90,7 +90,7 @@ public override byte ReadPrg(int addr) { if ((exRegs[0] & 0x80) > 0) { - var bank = exRegs[0] & 0x1F; + int bank = exRegs[0] & 0x1F; if ((exRegs[0] & 0x20) > 0) { if ((exRegs[0] & 0x40) > 0) diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper189.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper189.cs index d2985e69a8f..8c6fcc93885 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper189.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper189.cs @@ -44,10 +44,7 @@ public override void SyncState(Serializer ser) ser.Sync(nameof(prg), ref prg); } - public override void WriteExp(int addr, byte value) - { - WriteWram(addr, value); - } + public override void WriteExp(int addr, byte value) => WriteWram(addr, value); } } \ No newline at end of file diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper197.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper197.cs index d8a7f6210bb..a2164466074 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper197.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper197.cs @@ -43,12 +43,12 @@ public override void Sync() int chr_right_upper = regs[2] << 1; int chr_right_lower = regs[3] << 1; - for (var i = 0; i < 4; i++) + for (int i = 0; i < 4; i++) { chr_regs_1k_512[i] = chr_left | i; } - for (var i = 0; i < 2; i++) + for (int i = 0; i < 2; i++) { chr_regs_1k_512[4 | i] = chr_right_upper | i; chr_regs_1k_512[6 | i] = chr_right_lower | i; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper198.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper198.cs index a6031fdb23c..82de3894609 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper198.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper198.cs @@ -19,7 +19,7 @@ public override bool Configure(EDetectionOrigin origin) protected override int Get_PRGBank_8K(int addr) { - var val = base.Get_PRGBank_8K(addr); + int val = base.Get_PRGBank_8K(addr); if (val >= 0x50) { return val & 0x4F; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper199.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper199.cs index 7322c611007..0e63db0a83e 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper199.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper199.cs @@ -169,7 +169,7 @@ public override void WritePpu(int addr, byte value) protected override int Get_PRGBank_8K(int addr) { - if (addr >= 0x4000 && addr < 0x6000) + if (addr is >= 0x4000 and < 0x6000) { return exRegs[0]; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper205.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper205.cs index 26ffbeb0f75..e9c955295da 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper205.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper205.cs @@ -31,10 +31,7 @@ public override void SyncState(Serializer ser) base.SyncState(ser); } - public override void WriteWram(int addr, byte value) - { - block = value & 0x03; - } + public override void WriteWram(int addr, byte value) => block = value & 0x03; public override byte ReadPrg(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper208.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper208.cs index c88421f2727..07f99301d92 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper208.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper208.cs @@ -45,10 +45,7 @@ public override void SyncState(Serializer ser) ser.Sync("expregs", ref exRegs, false); } - public override byte ReadPrg(int addr) - { - return Rom[(exRegs[5] << 15) + addr]; - } + public override byte ReadPrg(int addr) => Rom[(exRegs[5] << 15) + addr]; public override byte ReadExp(int addr) { @@ -62,7 +59,7 @@ public override byte ReadExp(int addr) public override void WriteExp(int addr, byte value) { - if (addr >= 0x800 && addr < 0x1000) // 0x4800-0x4FFF + if (addr is >= 0x800 and < 0x1000) // 0x4800-0x4FFF { WriteReg(addr, value); } @@ -88,7 +85,7 @@ public override void WriteExp(int addr, byte value) public override void WriteWram(int addr, byte value) { - if (addr >= 0x800 && addr < 0x1000) // 0x6800 - 0x6FFF + if (addr is >= 0x800 and < 0x1000) // 0x6800 - 0x6FFF { WriteReg(addr, value); } @@ -98,9 +95,6 @@ public override void WriteWram(int addr, byte value) } } - private void WriteReg(int addr, byte value) - { - exRegs[5] = (byte)((value & 1) | ((value >> 3) & 2)); - } + private void WriteReg(int addr, byte value) => exRegs[5] = (byte)((value & 1) | ((value >> 3) & 2)); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper238.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper238.cs index 7ffa4b660ec..63ce062367a 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper238.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper238.cs @@ -39,10 +39,7 @@ public override byte ReadExp(int addr) return reg; } - public override byte ReadWram(int addr) - { - return reg; - } + public override byte ReadWram(int addr) => reg; public override void WriteExp(int addr, byte value) { @@ -54,9 +51,6 @@ public override void WriteExp(int addr, byte value) reg = (byte)lut[value & 3]; } - public override void WriteWram(int addr, byte value) - { - reg = (byte)lut[value & 3]; - } + public override void WriteWram(int addr, byte value) => reg = (byte)lut[value & 3]; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper249.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper249.cs index 8061b97d623..80b05e5070c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper249.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper249.cs @@ -30,10 +30,7 @@ public override void SyncState(Serializer ser) ser.Sync(nameof(piratecrap), ref piratecrap); } - public override void WriteExp(int addr, byte value) - { - piratecrap = value.Bit(1); - } + public override void WriteExp(int addr, byte value) => piratecrap = value.Bit(1); protected override int Get_CHRBank_1K(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper250.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper250.cs index 2efbaac2231..81a283c4c77 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper250.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/Mapper250.cs @@ -18,9 +18,6 @@ public override bool Configure(EDetectionOrigin origin) return true; } - public override void WritePrg(int addr, byte value) - { - base.WritePrg(addr & 0x6000 | addr >> 10 & 1, (byte)(addr & 0xff)); - } + public override void WritePrg(int addr, byte value) => base.WritePrg(addr & 0x6000 | addr >> 10 & 1, (byte)(addr & 0xff)); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/NES-QJ.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/NES-QJ.cs index 0fa3e03db55..af50603f8b1 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/NES-QJ.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/NES-QJ.cs @@ -39,22 +39,15 @@ public override bool Configure(EDetectionOrigin origin) return true; } - protected override int Get_PRGBank_8K(int addr) - { + protected override int Get_PRGBank_8K(int addr) => //base logic will return the mmc reg, which needs to be masked without awareness of the extra block - return (base.Get_PRGBank_8K(addr) & 0xF) + block * 16; - } + (base.Get_PRGBank_8K(addr) & 0xF) + block * 16; - protected override int Get_CHRBank_1K(int addr) - { + protected override int Get_CHRBank_1K(int addr) => //base logic will return the mmc reg, which needs to be masked without awareness of the extra block - return (base.Get_CHRBank_1K(addr) & 0x7F) + block * 128; - } + (base.Get_CHRBank_1K(addr) & 0x7F) + block * 128; - public override byte ReadWram(int addr) - { - return (byte)block; - } + public override byte ReadWram(int addr) => (byte)block; public override void WriteWram(int addr, byte value) { if (mmc3.wram_enable && !mmc3.wram_write_protect) diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/RexSoftSL1632.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/RexSoftSL1632.cs index d086dd97cd3..2439597d4c9 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/RexSoftSL1632.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/RexSoftSL1632.cs @@ -114,7 +114,7 @@ public override void WritePrg(int addr, byte value) } } - else if (addr >= 0x3000 && addr <= 0x6003) + else if (addr is >= 0x3000 and <= 0x6003) { int offset = addr << 2 & 0x4; addr = ((((addr & 0x2) | addr >> 10) >> 1) + 2) & 0x7; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper028.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper028.cs index e29b8a5343b..2db8203254f 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper028.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper028.cs @@ -178,10 +178,7 @@ public override void WritePpu(int addr, byte value) base.WritePpu(addr, value); } - public override byte ReadPrg(int addr) - { - return Rom[(addr & 0x3fff) | (addr < 0x4000 ? prglo : prghi) << 14]; - } + public override byte ReadPrg(int addr) => Rom[(addr & 0x3fff) | (addr < 0x4000 ? prglo : prghi) << 14]; public override void SyncState(Serializer ser) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper030.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper030.cs index f6b50c273f5..c97457f0be3 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper030.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper030.cs @@ -87,11 +87,8 @@ public override bool Configure(EDetectionOrigin origin) { flash_state = 0; flash_mode = flashmode.fm_default; - if (flash_rom == null) - { - // extra space is used to hold information about what sectors have been flashed - flash_rom = new byte[Cart.PrgSize * 1024 + Cart.PrgSize]; - } + // extra space is used to hold information about what sectors have been flashed + flash_rom ??= new byte[Cart.PrgSize * 1024 + Cart.PrgSize]; } SetMirrorType(CalculateMirrorType(Cart.PadH, Cart.PadV)); AssertChr(0); @@ -192,24 +189,18 @@ public override byte ReadPrg(int addr) { if (flash_mode == flashmode.fm_id) { - switch (addr & 0x1FF) + return (addr & 0x1FF) switch { - case 0: - return 0xBF; - case 1: - switch (Cart.PrgSize) - { - case 128: - return 0xB5; - case 256: - return 0xB6; - case 512: - return 0xB7; - } - return 0xFF; //Shouldn't ever reach here, as the size was asserted earlier. - default: - return 0xFF; //Other unknown data is returned from addresses 2-511, in software ID mode, mostly 0xFF. - } + 0 => 0xBF, + 1 => Cart.PrgSize switch + { + 128 => 0xB5, + 256 => 0xB6, + 512 => 0xB7, + _ => 0xFF,//Shouldn't ever reach here, as the size was asserted earlier. + }, + _ => 0xFF,//Other unknown data is returned from addresses 2-511, in software ID mode, mostly 0xFF. + }; } if (get_flash_write_count(addr) > 0) return flash_rom[Cart.PrgSize + (bank << 14 | addr & 0x3fff)]; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper034.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper034.cs index d2283a20e3b..5ae4a500a96 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper034.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper034.cs @@ -43,15 +43,9 @@ public override byte ReadPpu(int addr) return base.ReadPpu(addr); } - public override byte ReadPrg(int addr) - { - return Rom[addr | prg << 15]; - } + public override byte ReadPrg(int addr) => Rom[addr | prg << 15]; - public override void WritePrg(int addr, byte value) - { - prg = value & prg_bank_mask_32k; - } + public override void WritePrg(int addr, byte value) => prg = value & prg_bank_mask_32k; public override void WriteWram(int addr, byte value) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper036.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper036.cs index 03f3280b0b3..eefa32e3948 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper036.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper036.cs @@ -41,21 +41,13 @@ public override byte ReadPpu(int addr) return base.ReadPpu(addr); } - public override byte ReadPrg(int addr) - { - return Rom[addr | prg << 15]; - } + public override byte ReadPrg(int addr) => Rom[addr | prg << 15]; - public override void WritePrg(int addr, byte value) - { + public override void WritePrg(int addr, byte value) => // either hack emulation of a weird bus conflict, or crappy pirate safeguard prg = (R >> 4) & prg_mask; - } - public override byte ReadExp(int addr) - { - return (byte)(R | (NES.DB & 0xCF)); - } + public override byte ReadExp(int addr) => (byte)(R | (NES.DB & 0xCF)); public override void WriteExp(int addr, byte value) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper038.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper038.cs index 59282777fed..d7dfba6ba5f 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper038.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper038.cs @@ -29,10 +29,7 @@ public override bool Configure(EDetectionOrigin origin) return true; } - public override byte ReadPrg(int addr) - { - return Rom[addr + (prg << 15)]; - } + public override byte ReadPrg(int addr) => Rom[addr + (prg << 15)]; public override byte ReadPpu(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper040.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper040.cs index 9e7c0a2064e..dc6d9c32750 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper040.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper040.cs @@ -23,11 +23,9 @@ public override bool Configure(EDetectionOrigin origin) return true; } - public override byte ReadWram(int addr) - { + public override byte ReadWram(int addr) => // bank 6 fixed - return Rom[addr + 0xc000]; - } + Rom[addr + 0xc000]; public override byte ReadPrg(int addr) { if ((addr & 0x6000) == 0x4000) diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper041.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper041.cs index 23d0d2ae14e..92740f97856 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper041.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper041.cs @@ -54,10 +54,7 @@ public override byte ReadPpu(int addr) return base.ReadPpu(addr); } - public override byte ReadPrg(int addr) - { - return Rom[addr | prg << 15]; - } + public override byte ReadPrg(int addr) => Rom[addr | prg << 15]; public override void SyncState(Serializer ser) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper042.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper042.cs index 72bdf388559..c45d6c745d2 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper042.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper042.cs @@ -68,14 +68,8 @@ public override void WritePrg(int addr, byte value) } } - public override byte ReadPrg(int addr) - { - return Rom[addr | 0x18000]; - } - public override byte ReadWram(int addr) - { - return Rom[addr | prg << 13]; - } + public override byte ReadPrg(int addr) => Rom[addr | 0x18000]; + public override byte ReadWram(int addr) => Rom[addr | prg << 13]; public override void ClockCpu() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper045.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper045.cs index 055d13ae123..5375b5dc0c0 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper045.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper045.cs @@ -51,10 +51,7 @@ public override void WriteWram(int addr, byte value) } } - private void Sync45() - { - lock_regs = regs[3].Bit(6); - } + private void Sync45() => lock_regs = regs[3].Bit(6); private void IncrementCounter() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper053.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper053.cs index b32752eac01..0ccbf7ae604 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper053.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper053.cs @@ -52,10 +52,7 @@ public override void WriteWram(int addr, byte value) } } - public override void WritePrg(int addr, byte value) - { - _reg1 = value; - } + public override void WritePrg(int addr, byte value) => _reg1 = value; public override byte ReadPrg(int addr) { @@ -131,10 +128,7 @@ public override void WriteWram(int addr, byte value) } } - public override void WritePrg(int addr, byte value) - { - _reg1 = value; - } + public override void WritePrg(int addr, byte value) => _reg1 = value; public override byte ReadPrg(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper057.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper057.cs index 3bcb8749598..8343218707b 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper057.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper057.cs @@ -93,9 +93,6 @@ public override byte ReadPpu(int addr) return base.ReadPpu(addr); } - public override byte ReadWram(int addr) - { - return (byte)(Mapper57_DipSwitch & 3); - } + public override byte ReadWram(int addr) => (byte)(Mapper57_DipSwitch & 3); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper069.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper069.cs index 63201010ef5..880647b0b97 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper069.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper069.cs @@ -194,10 +194,7 @@ public override void WritePrg(int addr, byte value) } } - private void SyncIrq() - { - IrqSignal = irq_asserted; - } + private void SyncIrq() => IrqSignal = irq_asserted; public override void ClockCpu() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper078.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper078.cs index a6cb9cce095..82c6920d083 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper078.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper078.cs @@ -44,10 +44,7 @@ public override void SyncState(Serializer ser) ser.Sync(nameof(holydiver), ref holydiver); } - private void SyncPRG() - { - prg_banks_16k[0] = prg_bank_16k; - } + private void SyncPRG() => prg_banks_16k[0] = prg_bank_16k; public override void WritePrg(int addr, byte value) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper090.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper090.cs index 34589eb75f4..d0cf29770ec 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper090.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper090.cs @@ -291,8 +291,8 @@ private void SyncCHRBanks() SetBank(chr_banks, 0, 8, ((chr_regs[0] & mask) | block) << 3); break; case 1: - var reg_0 = mapper_090 ? chr_regs[0] : chr_regs[chr_latches[0]]; - var reg_1 = mapper_090 ? chr_regs[4] : chr_regs[chr_latches[1]]; + int reg_0 = mapper_090 ? chr_regs[0] : chr_regs[chr_latches[0]]; + int reg_1 = mapper_090 ? chr_regs[4] : chr_regs[chr_latches[1]]; SetBank(chr_banks, 0, 4, ((reg_0 & mask) | block) << 2); SetBank(chr_banks, 4, 4, ((reg_1 & mask) | block) << 2); @@ -321,7 +321,7 @@ private void SyncNametables() if (nt_advanced_control) { int[] m = new int[4]; - for (var i = 0; i < 4; i++) + for (int i = 0; i < 4; i++) { m[i] = nt_regs[i] & 0x01; } @@ -503,10 +503,7 @@ public override byte ReadPrg(int addr) return Rom[bank << 13 | offset]; } - public override byte ReadWram(int addr) - { - return sram_prg ? Rom[ram_bank << 13 | addr & 0x1FFF] : base.ReadWram(addr); - } + public override byte ReadWram(int addr) => sram_prg ? Rom[ram_bank << 13 | addr & 0x1FFF] : base.ReadWram(addr); public override byte ReadExp(int addr) { @@ -596,10 +593,7 @@ public void ClockIRQ() SyncIRQ(); } - public void SyncIRQ() - { - SyncIRQ(irq_pending); - } + public void SyncIRQ() => SyncIRQ(irq_pending); public override void AddressPpu(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper091.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper091.cs index 111b09c93e3..094909e82bf 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper091.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper091.cs @@ -84,15 +84,9 @@ public override void WriteWram(int addr, byte value) } } - public override void ClockPpu() - { - mmc3.ClockPPU(); - } + public override void ClockPpu() => mmc3.ClockPPU(); - public override void AddressPpu(int addr) - { - mmc3.AddressPPU(addr); - } + public override void AddressPpu(int addr) => mmc3.AddressPPU(addr); public override byte ReadPpu(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper101.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper101.cs index 8eb4346964b..26da8b61128 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper101.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper101.cs @@ -54,9 +54,6 @@ public override byte ReadPpu(int addr) else return base.ReadPpu(addr); } - public override void WriteWram(int addr, byte value) - { - chr_bank_8k = value & chr_bank_mask_8k; - } + public override void WriteWram(int addr, byte value) => chr_bank_8k = value & chr_bank_mask_8k; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper103.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper103.cs index a777d2da95f..c75305a0ff3 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper103.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper103.cs @@ -27,11 +27,9 @@ public override bool Configure(EDetectionOrigin origin) return true; } - public override void WriteWram(int addr, byte value) - { + public override void WriteWram(int addr, byte value) => // writes always go to wram, even if rom is mapped in for read Wram[addr] = value; - } public override byte ReadWram(int addr) { @@ -51,7 +49,7 @@ public override byte ReadPrg(int addr) public override void WritePrg(int addr, byte value) { - if (addr >= 0x3800 && addr < 0x5800) + if (addr is >= 0x3800 and < 0x5800) Wram[addr - 0x1800] = value; else { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper106.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper106.cs index 98b5cd4c415..a2ac316e429 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper106.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper106.cs @@ -68,10 +68,7 @@ public override void WritePrg(int addr, byte value) } } - private void SetMirror() - { - SetMirrorType(regs[0xC].Bit(0) ? EMirrorType.Horizontal : EMirrorType.Vertical); - } + private void SetMirror() => SetMirrorType(regs[0xC].Bit(0) ? EMirrorType.Horizontal : EMirrorType.Vertical); public override byte ReadPpu(int addr) { @@ -126,10 +123,7 @@ public override byte ReadPrg(int addr) return Rom[(bank << 13) + (addr & 0x1FFF)]; } - public override void ClockCpu() - { - IrqHook(1); - } + public override void ClockCpu() => IrqHook(1); private void IrqHook(int a) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper108.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper108.cs index beeeec0660a..97405ccf0b5 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper108.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper108.cs @@ -27,22 +27,16 @@ public override bool Configure(EDetectionOrigin origin) public override void WritePrg(int addr, byte value) { - if (addr < 0xFFF - || addr >= 0x7000) // hack ported from FCEUX to support Bubble Bobble (FDS Conversion, Kaiser Hacked) (Unl) [p1][!] + if (addr is < 0xFFF + or >= 0x7000) // hack ported from FCEUX to support Bubble Bobble (FDS Conversion, Kaiser Hacked) (Unl) [p1][!] { prg = value & 15; } } - public override byte ReadPrg(int addr) - { - return Rom[addr | 0x18000]; - } + public override byte ReadPrg(int addr) => Rom[addr | 0x18000]; - public override byte ReadWram(int addr) - { - return Rom[addr | prg << 13]; - } + public override byte ReadWram(int addr) => Rom[addr | prg << 13]; public override void SyncState(Serializer ser) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper116.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper116.cs index f84dd9703c6..2572b06b554 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper116.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper116.cs @@ -28,10 +28,7 @@ public MMC3_CustomBoard(Mapper116 master) this.master = master; } - public override void SyncIRQ(bool flag) - { - master.SyncIRQ(flag); - } + public override void SyncIRQ(bool flag) => master.SyncIRQ(flag); private readonly Mapper116 master; @@ -139,10 +136,7 @@ private void Sync() { } - private void mmc1_reset() - { - mmc1.mmc1.StandardReset(); - } + private void mmc1_reset() => mmc1.mmc1.StandardReset(); private void WriteModeControl(int addr, byte value) { @@ -167,10 +161,7 @@ private void WriteModeControl(int addr, byte value) if (mode == 3) Console.WriteLine("(mmc1)"); } - public override void WriteExp(int addr, byte value) - { - WriteModeControl(addr + 0x4000, value); - } + public override void WriteExp(int addr, byte value) => WriteModeControl(addr + 0x4000, value); public override void WritePpu(int addr, byte value) { @@ -185,15 +176,13 @@ public override void WritePpu(int addr, byte value) public override byte ReadPpu(int addr) { - switch (mode) + return mode switch { - case 0: return vrc2.ReadPpu(addr); - case 1: return mmc3.ReadPpu(addr); - case 2: - case 3: return mmc1.ReadPpu(addr); - - } - return 0; + 0 => vrc2.ReadPpu(addr), + 1 => mmc3.ReadPpu(addr), + 2 or 3 => mmc1.ReadPpu(addr), + _ => 0, + }; } public override void WritePrg(int addr, byte value) @@ -216,20 +205,16 @@ public override void WritePrg(int addr, byte value) public override byte ReadPrg(int addr) { - switch (mode) + return mode switch { - case 0: return vrc2.ReadPrg(addr); - case 1: return mmc3.ReadPrg(addr); - case 2: - case 3: return mmc1.ReadPrg(addr); - } - return 0; + 0 => vrc2.ReadPrg(addr), + 1 => mmc3.ReadPrg(addr), + 2 or 3 => mmc1.ReadPrg(addr), + _ => 0, + }; } - public override void AddressPpu(int addr) - { - mmc3.AddressPpu(addr); - } + public override void AddressPpu(int addr) => mmc3.AddressPpu(addr); public override void ClockPpu() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper120.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper120.cs index 9b768bf5099..5ec1683d7a9 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper120.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper120.cs @@ -35,14 +35,8 @@ public override void WriteExp(int addr, byte value) } } - public override byte ReadWram(int addr) - { - return Rom[((prg_reg & 7) * 0x2000) + (addr & 0x1FFF)]; - } + public override byte ReadWram(int addr) => Rom[((prg_reg & 7) * 0x2000) + (addr & 0x1FFF)]; - public override byte ReadPrg(int addr) - { - return Rom[0x10000 + addr]; - } + public override byte ReadPrg(int addr) => Rom[0x10000 + addr]; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper125.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper125.cs index eb22671972a..faf132756aa 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper125.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper125.cs @@ -42,7 +42,7 @@ public override void WriteWram(int addr, byte value) public override void WritePrg(int addr, byte value) { - if ((addr >= 0x4000) && (addr < 0x6000)) + if (addr is >= 0x4000 and < 0x6000) Wram[addr - 0x4000] = value; else base.WritePrg(addr, value); @@ -64,9 +64,6 @@ public override byte ReadPrg(int addr) return Rom[(bank << 13) + (addr & 0x1FFF)]; } - public override byte ReadWram(int addr) - { - return Rom[((reg & prg_bank_mask_8k) << 13) + addr]; - } + public override byte ReadWram(int addr) => Rom[((reg & prg_bank_mask_8k) << 13) + addr]; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper132.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper132.cs index b07cbcac747..561b8225132 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper132.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper132.cs @@ -56,14 +56,11 @@ public void sync(byte value) chr &= chr_mask; } - public override void WritePrg(int addr, byte value) - { - sync(value); - } + public override void WritePrg(int addr, byte value) => sync(value); public override void WriteExp(int addr, byte value) { - if (addr <= 0x103 && addr >= 0x100) + if (addr is <= 0x103 and >= 0x100) reg[addr & 0x03] = value; //reg[addr&0x03] = (byte)(value & 0x0f); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper142.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper142.cs index f3f15ce374d..3727fea2d2d 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper142.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper142.cs @@ -40,10 +40,7 @@ public override void SyncState(Serializer ser) ser.Sync(nameof(_irqCount), ref _irqCount); } - public override byte ReadWram(int addr) - { - return Rom[(_reg[4] << 13) + (addr & 0x1FFF)]; - } + public override byte ReadWram(int addr) => Rom[(_reg[4] << 13) + (addr & 0x1FFF)]; public override byte ReadPrg(int addr) { @@ -55,20 +52,11 @@ public override byte ReadPrg(int addr) return Rom[(_lastBank << 13) + (addr & 0x1FFF)]; } - public override void WriteExp(int addr, byte value) - { - Write(addr + 0x4000, value); - } + public override void WriteExp(int addr, byte value) => Write(addr + 0x4000, value); - public override void WriteWram(int addr, byte value) - { - Write(addr + 0x6000, value); - } + public override void WriteWram(int addr, byte value) => Write(addr + 0x6000, value); - public override void WritePrg(int addr, byte value) - { - Write(addr + 0x8000, value); - } + public override void WritePrg(int addr, byte value) => Write(addr + 0x8000, value); private void IRQHook(int a) { @@ -85,10 +73,7 @@ private void IRQHook(int a) } } - public override void ClockPpu() - { - IRQHook(1); - } + public override void ClockPpu() => IRQHook(1); private void Write(int addr, byte value) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper150.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper150.cs index 85f19ef1c10..28d82b80f8a 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper150.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper150.cs @@ -114,10 +114,7 @@ public override byte ReadExp(int addr) return ret; } - public override byte ReadPrg(int addr) - { - return Rom[((latch[0] & prg_mask) << 15) + addr]; - } + public override byte ReadPrg(int addr) => Rom[((latch[0] & prg_mask) << 15) + addr]; public override byte ReadPpu(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper168.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper168.cs index 5cf304a3019..5949f3a0999 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper168.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper168.cs @@ -43,10 +43,7 @@ public override byte ReadPrg(int addr) // the chr reg on hardware is supposedly bitscrambled and then inverted from // what would be expected. since it doesn't make a difference and i don't know // of any clear source on what it's actually supposed to be, ignore. - private int Scramble(int chr) - { - return chr; - } + private int Scramble(int chr) => chr; public override void WritePrg(int addr, byte value) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper170.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper170.cs index 87e21ee818b..9ca377597eb 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper170.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper170.cs @@ -38,7 +38,7 @@ public override byte ReadPrg(int addr) public override void WriteWram(int addr, byte value) { - if (addr == 0x502 || addr == 0x1000) + if (addr is 0x502 or 0x1000) { reg = (byte)(value << 1 & 0x80); } @@ -49,7 +49,7 @@ public override void WriteWram(int addr, byte value) public override byte ReadWram(int addr) { - if (addr == 0x1001 || addr == 0x1777) + if (addr is 0x1001 or 0x1777) { return (byte)(reg | NES.DB & 0x7F); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper176.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper176.cs index bd253236cbb..cf100e93148 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper176.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper176.cs @@ -48,10 +48,7 @@ public override bool Configure(EDetectionOrigin origin) private static readonly EMirrorType[] kMirrorTypes = {EMirrorType.Vertical,EMirrorType.Horizontal,EMirrorType.OneScreenA,EMirrorType.OneScreenB}; - private void SyncMirror() - { - SetMirrorType(kMirrorTypes[mirror]); - } + private void SyncMirror() => SetMirrorType(kMirrorTypes[mirror]); public override byte ReadPrg(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper177.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper177.cs index 290a0813a5f..0b4be3a990d 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper177.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper177.cs @@ -32,10 +32,7 @@ public override void WritePrg(int addr, byte value) SetMirrorType(EMirrorType.Vertical); } - public override byte ReadPrg(int addr) - { - return Rom[addr | prg << 15]; - } + public override byte ReadPrg(int addr) => Rom[addr | prg << 15]; public override void SyncState(Serializer ser) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper180.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper180.cs index 0cd8e07bb86..18c37a10355 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper180.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper180.cs @@ -36,10 +36,7 @@ public override void SyncState(Serializer ser) ser.Sync(nameof(prg_banks_16k), ref prg_banks_16k, false); } - private void SyncPRG() - { - prg_banks_16k[1] = prg_bank_16k; - } + private void SyncPRG() => prg_banks_16k[1] = prg_bank_16k; public override void WritePrg(int addr, byte value) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper183.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper183.cs index 964e7c9bbdb..a640175af34 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper183.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper183.cs @@ -82,15 +82,9 @@ public override void ClockCpu() } } - public override void WriteWram(int addr, byte value) - { - WriteReg(addr + 0x6000, value); - } + public override void WriteWram(int addr, byte value) => WriteReg(addr + 0x6000, value); - public override void WritePrg(int addr, byte value) - { - WriteReg(addr + 0x8000, value); - } + public override void WritePrg(int addr, byte value) => WriteReg(addr + 0x8000, value); private void WriteReg(int addr, byte value) { @@ -98,7 +92,7 @@ private void WriteReg(int addr, byte value) { prg[3] = (byte)(addr & 0x3F); } - else if ((addr & 0xF80C) >= 0xB000 && (addr & 0xF80C) <= 0xE00C) + else if ((addr & 0xF80C) is >= 0xB000 and <= 0xE00C) { int index = (((addr >> 11) - 6) | (addr >> 3)) & 7; chr[index] = (byte)((chr[index] & (0xF0 >> (addr & 4))) | ((value & 0x0F) << (addr & 4))); @@ -143,10 +137,7 @@ public override byte ReadPpu(int addr) return base.ReadPpu(addr); } - public override byte ReadWram(int addr) - { - return Rom[(((prg[3] & prg_bank_mask_8k)) << 13) + (addr & 0x1FFF)]; - } + public override byte ReadWram(int addr) => Rom[(((prg[3] & prg_bank_mask_8k)) << 13) + (addr & 0x1FFF)]; public override byte ReadPrg(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper186.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper186.cs index b6bee772654..c40c15cb895 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper186.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper186.cs @@ -38,14 +38,11 @@ public override byte ReadPrg(int addr) return Rom[addr & 0x3FFF]; } - public override byte ReadWram(int addr) - { - return Rom[(regs[0] >> 6) + addr]; - } + public override byte ReadWram(int addr) => Rom[(regs[0] >> 6) + addr]; public override void WriteExp(int addr, byte value) { - if (addr >= 0x200 && addr < 0x400) + if (addr is >= 0x200 and < 0x400) { if (((addr + 0x4000) & 0x4203) > 0) { @@ -64,7 +61,7 @@ public override void WriteExp(int addr, byte value) public override byte ReadExp(int addr) { - if (addr >= 0x200 && addr < 0x400) + if (addr is >= 0x200 and < 0x400) { switch (addr + 0x4000) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper188.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper188.cs index c95132ec24f..f67e70ecf57 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper188.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper188.cs @@ -28,10 +28,7 @@ public override bool Configure(EDetectionOrigin origin) return true; } - public override void WritePrg(int addr, byte value) - { - prg = value; - } + public override void WritePrg(int addr, byte value) => prg = value; public override void SyncState(Serializer ser) { @@ -49,9 +46,6 @@ public override byte ReadPrg(int addr) return Rom[addr & 0x3fff | bank << 14]; } - public override byte ReadWram(int addr) - { - return 3; - } + public override byte ReadWram(int addr) => 3; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper201.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper201.cs index 3a6419e3026..5f98243abc2 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper201.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper201.cs @@ -42,10 +42,7 @@ public override void WritePrg(int addr, byte value) } } - public override byte ReadPrg(int addr) - { - return Rom[((reg & prg_bank_mask_32k) * 0x8000) + addr]; - } + public override byte ReadPrg(int addr) => Rom[((reg & prg_bank_mask_32k) * 0x8000) + addr]; public override byte ReadPpu(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper203.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper203.cs index 0a7171ab291..8b0747501d7 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper203.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper203.cs @@ -38,10 +38,7 @@ public override void WritePrg(int addr, byte value) chr_reg_8k = (value & 0x03) & chr_bank_mask_8k; } - public override byte ReadPrg(int addr) - { - return Rom[(prg_reg_16k * 0x4000) + (addr & 0x3FFF)]; - } + public override byte ReadPrg(int addr) => Rom[(prg_reg_16k * 0x4000) + (addr & 0x3FFF)]; public override byte ReadPpu(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper214.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper214.cs index a5b12ad2b7c..beca24952cf 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper214.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper214.cs @@ -35,10 +35,7 @@ public override void WritePrg(int addr, byte value) _prgReg = (addr >> 2) & 3; } - public override byte ReadPrg(int addr) - { - return Rom[(_prgReg * 0x4000) + (addr & 0x3FFF)]; - } + public override byte ReadPrg(int addr) => Rom[(_prgReg * 0x4000) + (addr & 0x3FFF)]; public override byte ReadPpu(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper218.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper218.cs index d6ae6bbdcca..3fe770763a9 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper218.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper218.cs @@ -62,15 +62,9 @@ private int TransformPPU(int addr) return addr; } - public override byte ReadPpu(int addr) - { - return NES.CIRAM[TransformPPU(addr)]; - } + public override byte ReadPpu(int addr) => NES.CIRAM[TransformPPU(addr)]; - public override void WritePpu(int addr, byte value) - { - NES.CIRAM[TransformPPU(addr)] = value; - } + public override void WritePpu(int addr, byte value) => NES.CIRAM[TransformPPU(addr)] = value; public override byte ReadPrg(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper222.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper222.cs index 28ae4dd63f8..89359c579f0 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper222.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper222.cs @@ -87,10 +87,7 @@ public override void WritePrg(int addr, byte value) }*/ } - public override byte ReadPrg(int addr) - { - return Rom[addr & 0x1fff | prg[addr >> 13] << 13]; - } + public override byte ReadPrg(int addr) => Rom[addr & 0x1fff | prg[addr >> 13] << 13]; public override byte ReadPpu(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper236.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper236.cs index b7d6b8755fe..5eba71a57a6 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper236.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper236.cs @@ -60,7 +60,7 @@ public override void WritePrg(int addr, byte value) } else { - var mirroring = ((addr & 0x20) >> 5) ^ 1; + int mirroring = ((addr & 0x20) >> 5) ^ 1; SetMirrorType(mirroring > 0 ? EMirrorType.Vertical : EMirrorType.Horizontal); if (isLargeBanks) diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper240.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper240.cs index fa69a78a463..6dbe98451b6 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper240.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper240.cs @@ -51,10 +51,7 @@ public override byte ReadPpu(int addr) else return base.ReadPpu(addr); } - public override byte ReadPrg(int addr) - { - return Rom[addr + (prg_bank_32k * 0x8000)]; - } + public override byte ReadPrg(int addr) => Rom[addr + (prg_bank_32k * 0x8000)]; public override void WriteExp(int addr, byte value) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper241.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper241.cs index a95464f1544..5f6efd5dea1 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper241.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper241.cs @@ -31,11 +31,9 @@ public override bool Configure(EDetectionOrigin origin) return true; } - public override byte ReadExp(int addr) - { + public override byte ReadExp(int addr) => //some kind of magic number.. - return 0x50; - } + 0x50; public override void WritePrg(int addr, byte value) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper242.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper242.cs index cfb87140b42..bda26bcda0e 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper242.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper242.cs @@ -35,10 +35,7 @@ public override bool Configure(EDetectionOrigin origin) return true; } - public override byte ReadPrg(int addr) - { - return Rom[addr + (prg * 0x8000)]; - } + public override byte ReadPrg(int addr) => Rom[addr + (prg * 0x8000)]; public override void WritePrg(int addr, byte value) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper243.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper243.cs index 5e758113068..e2ae2c3f7a2 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper243.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper243.cs @@ -153,9 +153,6 @@ public override byte ReadPpu(int addr) } } - public override byte ReadPrg(int addr) - { - return Rom[((regs[5] & prg_bank_mask_32k) * 0x8000) + addr]; - } + public override byte ReadPrg(int addr) => Rom[((regs[5] & prg_bank_mask_32k) * 0x8000) + addr]; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper244.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper244.cs index 146f87e4412..fd5992c7764 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper244.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper244.cs @@ -18,7 +18,7 @@ public override bool Configure(EDetectionOrigin origin) return true; } - private readonly List> prg_perm = new List> + private readonly List> prg_perm = new() { new List { 0, 1, 2, 3, }, new List { 3, 2, 1, 0, }, @@ -26,7 +26,7 @@ public override bool Configure(EDetectionOrigin origin) new List { 3, 1, 2, 0, }, }; - private readonly List> chr_perm = new List> + private readonly List> chr_perm = new() { new List { 0, 1, 2, 3, 4, 5, 6, 7, }, new List { 0, 2, 1, 3, 4, 6, 5, 7, }, @@ -58,10 +58,7 @@ public override byte ReadPpu(int addr) return base.ReadPpu(addr); } - public override byte ReadPrg(int addr) - { - return Rom[(_prgRegister * 0x8000) + (addr & 0x7FFF)]; - } + public override byte ReadPrg(int addr) => Rom[(_prgRegister * 0x8000) + (addr & 0x7FFF)]; public override void WritePrg(int addr, byte value) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper252.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper252.cs index 845fc9ae34b..91dac2f2f5a 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper252.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper252.cs @@ -62,17 +62,14 @@ public override void ClockCpu() } } - public override void WritePrg(int addr, byte value) - { - WriteReg((addr + 0x8000), value); - } + public override void WritePrg(int addr, byte value) => WriteReg((addr + 0x8000), value); public void WriteReg(int addr, byte value) { - if (addr >= 0xB000 && addr < 0xF000) + if (addr is >= 0xB000 and < 0xF000) { - var ind = ((((addr & 8) | (addr >> 8)) >> 3) + 2) & 7; - var sar = addr & 4; + int ind = ((((addr & 8) | (addr >> 8)) >> 3) + 2) & 7; + int sar = addr & 4; creg[ind] = (byte)((creg[ind] & (0xF0 >> sar)) | ((value & 0x0F) << sar)); } else @@ -133,7 +130,7 @@ public override byte ReadPpu(int addr) int x = (addr >> 10) & 7; int bank; - if (creg[x] == 6 || creg[x] == 7) + if (creg[x] is 6 or 7) { bank = creg[x] & 1; return Vram[(bank << 10) + (addr & 0x3FF)]; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper253.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper253.cs index 68d9af674f1..7ea1046fc34 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper253.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper253.cs @@ -60,11 +60,11 @@ public override void ClockCpu() public override void WritePrg(int addr, byte value) { addr += 0x8000; - if ((addr >= 0xB000) && (addr <= 0xE00C)) + if (addr is >= 0xB000 and <= 0xE00C) { - var ind = ((((addr & 8) | (addr >> 8)) >> 3) + 2) & 7; - var sar = addr & 4; - var clo = (chrlo[ind] & (0xF0 >> sar)) | ((value & 0x0F) << sar); + int ind = ((((addr & 8) | (addr >> 8)) >> 3) + 2) & 7; + int sar = addr & 4; + int clo = (chrlo[ind] & (0xF0 >> sar)) | ((value & 0x0F) << sar); chrlo[ind] = (byte)clo; if (ind == 0) { @@ -133,7 +133,7 @@ public override byte ReadPpu(int addr) if (addr < 0x2000) { int x = (addr >> 10) & 7; - var chr = chrlo[x] | (chrhi[x] << 8); + int chr = chrlo[x] | (chrhi[x] << 8); int bank = (chr & _chrBankMask1k) << 10; if ((chrlo[x] == 4 || chrlo[x] == 5) && !_vLock) @@ -158,7 +158,7 @@ public override void WritePpu(int addr, byte value) if (Vram != null) { int x = (addr >> 10) & 7; - var chr = chrlo[x] | (chrhi[x] << 8); + int chr = chrlo[x] | (chrhi[x] << 8); int bank = (chr & _chrBankMask1k) << 10; if ((chrlo[x] == 4 || chrlo[x] == 5) && !_vLock) diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper50.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper50.cs index 167bd74b974..328cb1befd5 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper50.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper50.cs @@ -78,15 +78,11 @@ public override byte ReadPrg(int addr) } } - public override byte ReadWram(int addr) - { - return Rom[(0x0F * 0x2000) + (addr & 0x1FFF)]; - } + public override byte ReadWram(int addr) => Rom[(0x0F * 0x2000) + (addr & 0x1FFF)]; - private void IRQ_Ready() - { - base.SyncIRQ(irq_ready); - } +#pragma warning disable IDE0051 + private void IRQ_Ready() => base.SyncIRQ(irq_ready); +#pragma warning restore IDE0051 public override void ClockCpu() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper60.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper60.cs index 66fb941156a..8448240b216 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper60.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Mapper60.cs @@ -118,10 +118,7 @@ public override void NesSoftReset() base.NesSoftReset(); } - public override byte ReadPrg(int addr) - { - return Rom[(resetSwitch << 14) + (addr & 0x3FFF)]; - } + public override byte ReadPrg(int addr) => Rom[(resetSwitch << 14) + (addr & 0x3FFF)]; public override byte ReadPpu(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MapperPropAttribute.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MapperPropAttribute.cs index dc73bfec26c..ebd293fdc7d 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MapperPropAttribute.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MapperPropAttribute.cs @@ -34,20 +34,20 @@ public static void Apply(INesBoard board) var fields = board.GetType().GetFields(); foreach (var field in fields) { - var attribs = field.GetCustomAttributes(false); - foreach (var attrib in attribs) + object[] attribs = field.GetCustomAttributes(false); + foreach (object attrib in attribs) { if (attrib is MapperPropAttribute) { string name = field.Name; - if (board.InitialRegisterValues.TryGetValue(name, out var value)) + if (board.InitialRegisterValues.TryGetValue(name, out string value)) { try { field.SetValue(board, Convert.ChangeType(value, field.FieldType)); } - catch (Exception e) when (e is InvalidCastException || e is FormatException || e is OverflowException) + catch (Exception e) when (e is InvalidCastException or FormatException or OverflowException) { throw new InvalidOperationException("Auto Mapper Properties were in a bad format!", e); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/NES-EVENT.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/NES-EVENT.cs index f3a5fb2578b..a3386e30413 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/NES-EVENT.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/NES-EVENT.cs @@ -40,7 +40,7 @@ internal sealed class NES_EVENT : NesBoardBase public bool Dipswitch4 = false; private List Switches => - new List + new() { { Dipswitch1 }, { Dipswitch2 }, @@ -239,10 +239,7 @@ public override void WriteWram(int addr, byte value) } } - public override byte ReadWram(int addr) - { - return wram_disable ? NES.DB : base.ReadWram(addr); - } + public override byte ReadWram(int addr) => wram_disable ? NES.DB : base.ReadWram(addr); public override void NesSoftReset() { @@ -261,10 +258,7 @@ private void InitValues() Sync(); } - public override void WritePrg(int addr, byte value) - { - scnt.Write(addr, value); - } + public override void WritePrg(int addr, byte value) => scnt.Write(addr, value); public override byte ReadPrg(int addr) @@ -296,9 +290,6 @@ private void ClockIRQ() SyncIRQ(); } - private void SyncIRQ() - { - SyncIRQ(irq_pending); - } + private void SyncIRQ() => SyncIRQ(irq_pending); } } \ No newline at end of file diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/NSFBoard.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/NSFBoard.cs index cfca9a6d681..f2fd662f607 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/NSFBoard.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/NSFBoard.cs @@ -130,10 +130,7 @@ private void ReplayInit() Patch_Vectors = true; } - public override void NesSoftReset() - { - ReplayInit(); - } + public override void NesSoftReset() => ReplayInit(); public override void WriteExp(int addr, byte value) { @@ -199,8 +196,8 @@ public override byte ReadReg2xxx(int addr) //NES.WriteMemory(0x4017, 0x40); //important to NSF standard for ram to be cleared, otherwise replayers are confused on account of not initializing memory themselves - var ram = NES.ram; - var wram = this.Wram; + byte[] ram = NES.ram; + byte[] wram = this.Wram; int wram_size = wram.Length; for (int i = 0; i < 0x800; i++) ram[i] = 0; @@ -349,10 +346,7 @@ public override void AtVsyncNmi() } } - public override byte ReadPpu(int addr) - { - return 0; - } + public override byte ReadPpu(int addr) => 0; public override byte ReadPrg(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Namcot129_163.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Namcot129_163.cs index 7fc4c892207..f17ae73f7ce 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Namcot129_163.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Namcot129_163.cs @@ -94,16 +94,13 @@ public override bool Configure(EDetectionOrigin origin) public override byte ReadExp(int addr) { addr &= 0xF800; - switch (addr) + return addr switch { - case 0x0800: - return audio.ReadData(); - case 0x1000: - return (byte)(irq_counter & 0xFF); - case 0x1800: - return (byte)((irq_counter >> 8) | (irq_enabled ? 0x8000 : 0)); - } - return base.ReadExp(addr); + 0x0800 => audio.ReadData(), + 0x1000 => (byte)(irq_counter & 0xFF), + 0x1800 => (byte)((irq_counter >> 8) | (irq_enabled ? 0x8000 : 0)), + _ => base.ReadExp(addr), + }; } public override void WriteExp(int addr, byte value) @@ -218,10 +215,7 @@ public override byte ReadPpu(int addr) } } - private void SyncIRQ() - { - IrqSignal = (irq_pending && irq_enabled); - } + private void SyncIRQ() => IrqSignal = (irq_pending && irq_enabled); private void TriggerIRQ() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Namcot175_340.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Namcot175_340.cs index 7772852f52f..4edf0369791 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Namcot175_340.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Namcot175_340.cs @@ -122,10 +122,7 @@ public override byte ReadPpu(int addr) } } - public override byte ReadPrg(int addr) - { - return Rom[addr & 0x1fff | prg[addr >> 13] << 13]; - } + public override byte ReadPrg(int addr) => Rom[addr & 0x1fff | prg[addr >> 13] << 13]; public override void WriteWram(int addr, byte value) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Namcot1xx/Mapper076.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Namcot1xx/Mapper076.cs index de1d4cb29aa..e4e3b3c32e1 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Namcot1xx/Mapper076.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Namcot1xx/Mapper076.cs @@ -61,10 +61,7 @@ public override void WritePrg(int addr, byte value) } } - public override byte ReadPrg(int addr) - { - return Rom[addr & 0x1fff | prg[addr >> 13] << 13]; - } + public override byte ReadPrg(int addr) => Rom[addr & 0x1fff | prg[addr >> 13] << 13]; public override byte ReadPpu(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Namcot1xx/Namco163Audio.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Namcot1xx/Namco163Audio.cs index 3f45aff95c3..c53ba299c44 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Namcot1xx/Namco163Audio.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Namcot1xx/Namco163Audio.cs @@ -111,9 +111,6 @@ public Namco163Audio(Action enqueuer) // the sound ram can be uesd for arbitrary load\store of data, // and can be batteryed, and some games actually did this - public byte[] GetSaveRam() - { - return ram; - } + public byte[] GetSaveRam() => ram; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Namcot1xx/Namcot1xx.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Namcot1xx/Namcot1xx.cs index 6233c0e4a85..1e1dd38691a 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Namcot1xx/Namcot1xx.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Namcot1xx/Namcot1xx.cs @@ -110,15 +110,9 @@ public override void SyncState(Serializer ser) mapper.SyncState(ser); } - public int Get_CHRBank_1K(int addr) - { - return mapper.Get_CHRBank_1K(addr); - } + public int Get_CHRBank_1K(int addr) => mapper.Get_CHRBank_1K(addr); - public int Get_PRGBank_8K(int addr) - { - return mapper.Get_PRGBank_8K(addr); - } + public int Get_PRGBank_8K(int addr) => mapper.Get_PRGBank_8K(addr); protected int MapCHR(int addr) { @@ -183,10 +177,7 @@ public override void WritePpu(int addr, byte value) base.WritePpu(addr, value); } - public override void WritePrg(int addr, byte value) - { - mapper.WritePRG(addr, value); - } + public override void WritePrg(int addr, byte value) => mapper.WritePRG(addr, value); public override byte ReadPrg(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/NanJing.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/NanJing.cs index d60d34165ab..8d8dc91933c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/NanJing.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/NanJing.cs @@ -44,11 +44,8 @@ public override bool Configure(EDetectionOrigin origin) return true; } - public override byte ReadPrg(int addr) - { - return Rom[(prg << 15) | addr]; - } - + public override byte ReadPrg(int addr) => Rom[(prg << 15) | addr]; + /* public override void WritePRG(int addr, byte value) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/NesBoardBase.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/NesBoardBase.cs index b432621f7f0..d0f2f078403 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/NesBoardBase.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/NesBoardBase.cs @@ -16,10 +16,7 @@ internal enum EMirrorType [NesBoardImpl] internal abstract class NesBoardBase : INesBoard { - public virtual void Create(NES nes) - { - NES = nes; - } + public virtual void Create(NES nes) => NES = nes; public virtual void NesSoftReset() { @@ -40,8 +37,10 @@ public virtual void AtVsyncNmi() { } public virtual NES.CDLog_MapResults MapMemory(ushort addr, bool write) { - NES.CDLog_MapResults ret = new NES.CDLog_MapResults(); - ret.Type = NES.CDLog_AddrType.None; + NES.CDLog_MapResults ret = new() + { + Type = NES.CDLog_AddrType.None + }; if (addr < 0x2000) { @@ -61,10 +60,7 @@ public virtual void SyncState(Serializer ser) SyncStateFlag = true; } - public virtual void SyncIRQ(bool flag) - { - IrqSignal = flag; - } + public virtual void SyncIRQ(bool flag) => IrqSignal = flag; private bool _irqSignal; public bool IrqSignal @@ -118,10 +114,7 @@ public static EMirrorType CalculateMirrorType(int pad_h, int pad_v) return EMirrorType.OneScreenB; } - protected void SetMirrorType(int pad_h, int pad_v) - { - SetMirrorType(CalculateMirrorType(pad_h, pad_v)); - } + protected void SetMirrorType(int pad_h, int pad_v) => SetMirrorType(CalculateMirrorType(pad_h, pad_v)); public void SetMirrorType(EMirrorType mirrorType) { @@ -167,39 +160,21 @@ public virtual void WriteWram(int addr, byte value) } private int _wramMask; - public virtual void PostConfigure() - { - _wramMask = (Cart.WramSize * 1024) - 1; - } + public virtual void PostConfigure() => _wramMask = (Cart.WramSize * 1024) - 1; - public virtual byte ReadWram(int addr) - { - return _wram?[addr & _wramMask] ?? NES.DB; - } + public virtual byte ReadWram(int addr) => _wram?[addr & _wramMask] ?? NES.DB; public virtual void WriteExp(int addr, byte value) { } - public virtual byte ReadExp(int addr) - { - return NES.DB; - } + public virtual byte ReadExp(int addr) => NES.DB; - public virtual byte ReadReg2xxx(int addr) - { - return NES.ppu.ReadReg(addr & 7); - } + public virtual byte ReadReg2xxx(int addr) => NES.ppu.ReadReg(addr & 7); - public virtual byte PeekReg2xxx(int addr) - { - return NES.ppu.PeekReg(addr & 7); - } + public virtual byte PeekReg2xxx(int addr) => NES.ppu.PeekReg(addr & 7); - public virtual void WriteReg2xxx(int addr, byte value) - { - NES.ppu.WriteReg(addr, value); - } + public virtual void WriteReg2xxx(int addr, byte value) => NES.ppu.WriteReg(addr, value); public virtual void WritePpu(int addr, byte value) { @@ -222,10 +197,7 @@ public virtual void AddressPpu(int addr) public virtual byte PeekPPU(int addr) => ReadPpu(addr); - protected virtual byte ReadPPUChr(int addr) - { - return Vrom?[addr] ?? Vram[addr]; - } + protected virtual byte ReadPPUChr(int addr) => Vrom?[addr] ?? Vram[addr]; public virtual byte ReadPpu(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/NovelDiamond.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/NovelDiamond.cs index 06018b2f743..66485088165 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/NovelDiamond.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/NovelDiamond.cs @@ -30,10 +30,7 @@ public override byte ReadPpu(int addr) return base.ReadPpu(addr); } - public override byte ReadPrg(int addr) - { - return Rom[addr | prg << 15]; - } + public override byte ReadPrg(int addr) => Rom[addr | prg << 15]; public override void WritePrg(int addr, byte value) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/SEEPROM.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/SEEPROM.cs index 90c412b6be8..58f3bf5066f 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/SEEPROM.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/SEEPROM.cs @@ -233,7 +233,7 @@ public bool ReadBit(bool deadbit) return !PullDown; } - public byte[] GetSaveRAM() { return rom; } + public byte[] GetSaveRAM() => rom; /// 256 byte instead of 128 byte public SEEPROM(bool Big) diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Sachen8259.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Sachen8259.cs index e034a97cfa4..41f65e8b310 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Sachen8259.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Sachen8259.cs @@ -60,14 +60,8 @@ public override bool Configure(EDetectionOrigin origin) return true; } - public override void WriteExp(int addr, byte value) - { - Write(addr, value); - } - public override void WriteWram(int addr, byte value) - { - Write(addr, value); - } + public override void WriteExp(int addr, byte value) => Write(addr, value); + public override void WriteWram(int addr, byte value) => Write(addr, value); private void Write(int addr, byte value) { @@ -212,14 +206,8 @@ public override bool Configure(EDetectionOrigin origin) return true; } - public override void WriteExp(int addr, byte value) - { - Write(addr, value); - } - public override void WriteWram(int addr, byte value) - { - Write(addr, value); - } + public override void WriteExp(int addr, byte value) => Write(addr, value); + public override void WriteWram(int addr, byte value) => Write(addr, value); private void Write(int addr, byte value) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/SachenSimple.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/SachenSimple.cs index ff2d18b3186..d54cb2e3cbe 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/SachenSimple.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/SachenSimple.cs @@ -68,15 +68,9 @@ private void SA0161M_Write(byte value) chr = value & 7 & chr_mask; } - private void SA72007_Write(byte value) - { - chr = (value >> 7) & 1 & chr_mask; - } + private void SA72007_Write(byte value) => chr = (value >> 7) & 1 & chr_mask; - private void SA009_Write(byte value) - { - chr = value & 1 & chr_mask; - } + private void SA009_Write(byte value) => chr = value & 1 & chr_mask; private void SA72008_Write(byte value) { @@ -90,15 +84,9 @@ public override void WriteExp(int addr, byte value) ExpWrite(value); } - public override void WritePrg(int addr, byte value) - { - PrgWrite?.Invoke(value); - } + public override void WritePrg(int addr, byte value) => PrgWrite?.Invoke(value); - public override byte ReadPrg(int addr) - { - return Rom[(addr & prg_addr_mask) + (prg << 15)]; - } + public override byte ReadPrg(int addr) => Rom[(addr & prg_addr_mask) + (prg << 15)]; public override byte ReadPpu(int addr) { if (addr < 0x2000) diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Subor.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Subor.cs index 523cb8c670e..48daff51065 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Subor.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Subor.cs @@ -30,10 +30,7 @@ public override void SyncState(Serializer ser) ser.Sync(nameof(is167), ref is167); } - public override void WritePrg(int addr, byte value) - { - regs[(addr >> 13) & 0x03] = value; - } + public override void WritePrg(int addr, byte value) => regs[(addr >> 13) & 0x03] = value; public override byte ReadPrg(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Sunsoft1_Alt.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Sunsoft1_Alt.cs index 9094750f55a..b4d1596914d 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Sunsoft1_Alt.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Sunsoft1_Alt.cs @@ -25,10 +25,7 @@ public override bool Configure(EDetectionOrigin origin) return true; } - public override void WriteWram(int addr, byte value) - { - prg = value & 7; - } + public override void WriteWram(int addr, byte value) => prg = value & 7; public override byte ReadPrg(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Sunsoft2_m89.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Sunsoft2_m89.cs index fc034208115..a3f99a86239 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Sunsoft2_m89.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Sunsoft2_m89.cs @@ -41,10 +41,7 @@ public override void SyncState(Serializer ser) ser.Sync(nameof(prg_banks_16k), ref prg_banks_16k, false); } - private void SyncPRG() - { - prg_banks_16k[0] = prg_bank_16k; - } + private void SyncPRG() => prg_banks_16k[0] = prg_bank_16k; public override void WritePrg(int addr, byte value) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Sunsoft2_m93.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Sunsoft2_m93.cs index 3327bc5dc1c..be0ecc4ee90 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Sunsoft2_m93.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Sunsoft2_m93.cs @@ -40,10 +40,7 @@ public override void SyncState(Serializer ser) ser.Sync(nameof(prg_banks_16k), ref prg_banks_16k, false); } - private void SyncPRG() - { - prg_banks_16k[0] = prg_bank_16k; - } + private void SyncPRG() => prg_banks_16k[0] = prg_bank_16k; public override void WritePrg(int addr, byte value) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Sunsoft3.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Sunsoft3.cs index 731f27057f6..5709573b316 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Sunsoft3.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Sunsoft3.cs @@ -85,10 +85,7 @@ private void SetCHR(int block, byte value) ApplyMemoryMapMask(chr_bank_mask_2k, chr_banks_2k); } - private void SyncIRQ() - { - IrqSignal = irq_asserted; - } + private void SyncIRQ() => IrqSignal = irq_asserted; public override void WritePrg(int addr, byte value) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/SxROM.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/SxROM.cs index f0d74c00909..501cda3ed50 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/SxROM.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/SxROM.cs @@ -29,7 +29,7 @@ namespace BizHawk.Emulation.Cores.Nintendo.NES internal sealed class MMC1 { - public MMC1_SerialController scnt = new MMC1_SerialController(); + public MMC1_SerialController scnt = new(); public MMC1() { @@ -105,10 +105,7 @@ public void SyncState(Serializer ser) public Action Reset; public Action WriteRegister; - public void ResetShift() - { - shift_count = shift_val = 0; - } + public void ResetShift() => shift_count = shift_val = 0; public void Write(int addr, byte value) { @@ -225,15 +222,9 @@ private void SyncPRG() } } - public int Get_PRGBank(int addr) - { - return prg_banks_16k[addr >> 14]; - } + public int Get_PRGBank(int addr) => prg_banks_16k[addr >> 14]; - public int Get_CHRBank_4K(int addr) - { - return chr_banks_4k[addr >> 12]; - } + public int Get_CHRBank_4K(int addr) => chr_banks_4k[addr >> 12]; } [NesBoardImplPriority] @@ -570,15 +561,9 @@ private int Map_WRAM(int addr) return (wram_bank_8k << 13) | ofs; } - public override void WriteWram(int addr, byte value) - { - base.WriteWram(Map_WRAM(addr), value); - } + public override void WriteWram(int addr, byte value) => base.WriteWram(Map_WRAM(addr), value); - public override byte ReadWram(int addr) - { - return base.ReadWram(Map_WRAM(addr)); - } + public override byte ReadWram(int addr) => base.ReadWram(Map_WRAM(addr)); } internal class SXROM : SuROM @@ -615,15 +600,9 @@ private int Map_WRAM(int addr) return (wram_bank_8k << 13) | ofs; } - public override void WriteWram(int addr, byte value) - { - base.WriteWram(Map_WRAM(addr), value); - } + public override void WriteWram(int addr, byte value) => base.WriteWram(Map_WRAM(addr), value); - public override byte ReadWram(int addr) - { - return base.ReadWram(Map_WRAM(addr)); - } + public override byte ReadWram(int addr) => base.ReadWram(Map_WRAM(addr)); } internal class SuROM : SxROM diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/TAITO_74_161_161_32.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/TAITO_74_161_161_32.cs index 69ceee2e4e1..057de80a968 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/TAITO_74_161_161_32.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/TAITO_74_161_161_32.cs @@ -40,10 +40,7 @@ public override void SyncState(Serializer ser) ser.Sync(nameof(prg_banks_16k), ref prg_banks_16k, false); } - private void SyncPRG() - { - prg_banks_16k[0] = prg_bank_16k; - } + private void SyncPRG() => prg_banks_16k[0] = prg_bank_16k; public override void WritePrg(int addr, byte value) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/TENGEN-800032.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/TENGEN-800032.cs index 344e85e50ac..f003885f258 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/TENGEN-800032.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/TENGEN-800032.cs @@ -207,10 +207,7 @@ public override byte ReadPpu(int addr) return base.ReadPpu(addr); } - private void SyncIRQ() - { - IrqSignal = irq_pending; - } + private void SyncIRQ() => IrqSignal = irq_pending; private void ClockIRQ() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/TENGEN_800008.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/TENGEN_800008.cs index 1e0b28e0be2..7fb9190421c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/TENGEN_800008.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/TENGEN_800008.cs @@ -39,10 +39,7 @@ public override void WritePrg(int addr, byte value) chr = value & chr_mask; } - public override byte ReadPrg(int addr) - { - return Rom[addr | prg << 15]; - } + public override byte ReadPrg(int addr) => Rom[addr | prg << 15]; public override byte ReadPpu(int addr) { if (addr < 0x2000) diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Taito_TC0190FMC.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Taito_TC0190FMC.cs index 08e9713e39a..51257f907bb 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Taito_TC0190FMC.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/Taito_TC0190FMC.cs @@ -121,10 +121,7 @@ public override bool Configure(EDetectionOrigin origin) return true; } - private void SyncMirror() - { - SetMirrorType(mirror_mode == 0 ? EMirrorType.Vertical : EMirrorType.Horizontal); - } + private void SyncMirror() => SetMirrorType(mirror_mode == 0 ? EMirrorType.Vertical : EMirrorType.Horizontal); public override void WritePrg(int addr, byte value) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-12-IN-1.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-12-IN-1.cs index b23efb8e084..9c3d4563b5c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-12-IN-1.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-12-IN-1.cs @@ -48,10 +48,7 @@ public override void WritePrg(int addr, byte value) } } - private void SetMirroring(bool horizontal) - { - SetMirrorType(horizontal ? EMirrorType.Horizontal : EMirrorType.Vertical); - } + private void SetMirroring(bool horizontal) => SetMirrorType(horizontal ? EMirrorType.Horizontal : EMirrorType.Vertical); public override byte ReadPpu(int addr) { @@ -76,7 +73,7 @@ public override byte ReadPpu(int addr) public override byte ReadPrg(int addr) { - var basebank = (ctrl & 3) << 3; + int basebank = (ctrl & 3) << 3; int bank = 0; if (ctrl.Bit(3)) diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-190in1.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-190in1.cs index 5f21029b702..c1b602d8870 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-190in1.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-190in1.cs @@ -43,9 +43,6 @@ public override byte ReadPpu(int addr) return base.ReadPpu(addr); } - public override byte ReadPrg(int addr) - { - return Rom[(_reg * 0x4000) + (addr & 0x3FFF)]; - } + public override byte ReadPrg(int addr) => Rom[(_reg * 0x4000) + (addr & 0x3FFF)]; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-64in1-NR.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-64in1-NR.cs index feba7a51526..e4ad5e06227 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-64in1-NR.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-64in1-NR.cs @@ -27,7 +27,7 @@ public override bool Configure(EDetectionOrigin origin) public override void WriteExp(int addr, byte value) { - if (addr >= 0x1000 && addr <= 0x1003) + if (addr is >= 0x1000 and <= 0x1003) { regs[addr & 3] = value; SetMirrorType((regs[0] & 0x20) > 0 ? EMirrorType.Horizontal : EMirrorType.Vertical); @@ -36,10 +36,7 @@ public override void WriteExp(int addr, byte value) base.WriteExp(addr, value); } - public override void WritePrg(int addr, byte value) - { - regs[3] = value; - } + public override void WritePrg(int addr, byte value) => regs[3] = value; public override byte ReadPrg(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-BS-5.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-BS-5.cs index abf2de9e3e7..45398a109c0 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-BS-5.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-BS-5.cs @@ -13,7 +13,9 @@ internal sealed class UNIF_BMC_BS_5 : NesBoardBase private int _prgMask8k; private int _chrMask2k; + #pragma warning disable IDE0051 private const int DipSwitchMask = 3; + #pragma warning restore IDE0051 public override bool Configure(EDetectionOrigin origin) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-GS-2004.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-GS-2004.cs index 561dabed23e..f3dc885b9c0 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-GS-2004.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-GS-2004.cs @@ -44,19 +44,10 @@ public override void SyncState(Serializer ser) } - public override void WritePrg(int addr, byte value) - { - _reg = value; - } + public override void WritePrg(int addr, byte value) => _reg = value; - public override byte ReadWram(int addr) - { - return Rom[_wramOffset + (addr & 0x1FFF)]; - } + public override byte ReadWram(int addr) => Rom[_wramOffset + (addr & 0x1FFF)]; - public override byte ReadPrg(int addr) - { - return Rom[((_reg & _prgMask32k) * 0x8000) + (addr & 0x7FFF)]; - } + public override byte ReadPrg(int addr) => Rom[((_reg & _prgMask32k) * 0x8000) + (addr & 0x7FFF)]; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-GS-2013.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-GS-2013.cs index a2a533df522..f3d1a52ede8 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-GS-2013.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-GS-2013.cs @@ -53,10 +53,7 @@ public override void WritePrg(int addr, byte value) _reg = value; } - public override byte ReadWram(int addr) - { - return Rom[_wramPage + (addr & 0x1FFF)]; - } + public override byte ReadWram(int addr) => Rom[_wramPage + (addr & 0x1FFF)]; public override byte ReadPrg(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-Ghostbusters63in1.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-Ghostbusters63in1.cs index d5b3ab3f711..222dfa5df4a 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-Ghostbusters63in1.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-Ghostbusters63in1.cs @@ -60,7 +60,7 @@ public override byte ReadPrg(int addr) if (reg[0].Bit(5)) { - var offset=0; + int offset =0; if (Ghostbusters63in1_63set) offset = banks[bank]; else @@ -71,7 +71,7 @@ public override byte ReadPrg(int addr) } else { - var offset = 0; + int offset = 0; if (Ghostbusters63in1_63set) offset = banks[bank]; else diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-T-262.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-T-262.cs index c736a0e1f53..75e7f1ee136 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-T-262.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMC-T-262.cs @@ -66,9 +66,6 @@ public override void WritePrg(int addr, byte value) SetMirroring(); } - private void SetMirroring() - { - SetMirrorType(_verticalMirror ? EMirrorType.Vertical : EMirrorType.Horizontal); - } + private void SetMirroring() => SetMirrorType(_verticalMirror ? EMirrorType.Vertical : EMirrorType.Horizontal); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-43272.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-43272.cs index 076c1989e04..bb2894d95e0 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-43272.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-43272.cs @@ -25,10 +25,7 @@ public override void SyncState(Serializer ser) base.SyncState(ser); } - public override void WritePrg(int addr, byte value) - { - latche = addr & 65535; - } + public override void WritePrg(int addr, byte value) => latche = addr & 65535; public override byte ReadPrg(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-AC08.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-AC08.cs index e91884eed1b..a7d757ac4c8 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-AC08.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-AC08.cs @@ -48,14 +48,8 @@ public override void WritePrg(int addr, byte value) } } - public override byte ReadWram(int addr) - { - return Rom[(reg << 13) + addr]; - } + public override byte ReadWram(int addr) => Rom[(reg << 13) + addr]; - public override byte ReadPrg(int addr) - { - return Rom[0x20000 + addr]; - } + public override byte ReadPrg(int addr) => Rom[0x20000 + addr]; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-BB.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-BB.cs index 32b048bdf4b..5c536e96d2b 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-BB.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-BB.cs @@ -44,15 +44,9 @@ public override void WritePrg(int addr, byte value) } } - public override byte ReadWram(int addr) - { - return Rom[((reg & 3) << 13) + addr]; - } + public override byte ReadWram(int addr) => Rom[((reg & 3) << 13) + addr]; - public override byte ReadPrg(int addr) - { - return Rom[(prg_mask_32k << 15) + addr]; - } + public override byte ReadPrg(int addr) => Rom[(prg_mask_32k << 15) + addr]; public override byte ReadPpu(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-EDU2000.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-EDU2000.cs index a2e408a527d..ee46aa537c0 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-EDU2000.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-EDU2000.cs @@ -28,14 +28,8 @@ public override void SyncState(Serializer ser) ser.Sync("reg", ref _reg); } - public override void WritePrg(int addr, byte value) - { - _reg = value; - } + public override void WritePrg(int addr, byte value) => _reg = value; - public override byte ReadPrg(int addr) - { - return Rom[((_reg & _prgMask32) * 0x8000) + (addr & 0x7FFF)]; - } + public override byte ReadPrg(int addr) => Rom[((_reg & _prgMask32) * 0x8000) + (addr & 0x7FFF)]; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-KS7012.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-KS7012.cs index 3165f9a1f0b..18955d1f197 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-KS7012.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-KS7012.cs @@ -41,9 +41,6 @@ public override void WritePrg(int addr, byte value) } } - public override byte ReadPrg(int addr) - { - return Rom[((reg & 1) << 15) + addr]; - } + public override byte ReadPrg(int addr) => Rom[((reg & 1) << 15) + addr]; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-KS7013B.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-KS7013B.cs index 5b2412cd52b..c34ef9a7ad1 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-KS7013B.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-KS7013B.cs @@ -29,15 +29,9 @@ public override void SyncState(Serializer ser) base.SyncState(ser); } - public override void WriteWram(int addr, byte value) - { - reg = value; - } + public override void WriteWram(int addr, byte value) => reg = value; - public override void WritePrg(int addr, byte value) - { - SetMirrorType(value.Bit(0) ? EMirrorType.Horizontal : EMirrorType.Vertical); - } + public override void WritePrg(int addr, byte value) => SetMirrorType(value.Bit(0) ? EMirrorType.Horizontal : EMirrorType.Vertical); public override byte ReadPrg(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-LH10.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-LH10.cs index ba43d4b3948..c1f10803206 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-LH10.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-LH10.cs @@ -37,7 +37,7 @@ public override void SyncState(Serializer ser) public override void WritePrg(int addr, byte value) { - if (addr>=0x4000 && addr<0x6000) + if (addr is >= 0x4000 and < 0x6000) { Wram[addr - 0x4000] = value; return; @@ -54,10 +54,7 @@ public override void WritePrg(int addr, byte value) } - public override byte ReadWram(int addr) - { - return Rom[Rom.Length - 0x4000 + addr]; - } + public override byte ReadWram(int addr) => Rom[Rom.Length - 0x4000 + addr]; public override byte ReadPrg(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-TF1201.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-TF1201.cs index 10fe87bedf1..695c03c614d 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-TF1201.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL-TF1201.cs @@ -47,7 +47,7 @@ public override void WritePrg(int addr, byte value) { addr += 0x8000; addr = (addr & 0xF003) | ((addr & 0xC) >> 2); - if ((addr >= 0xB000) && (addr <= 0xE003)) + if (addr is >= 0xB000 and <= 0xE003) { int ind = (((addr >> 11) - 6) | (addr & 1)) & 7; int sar = ((addr & 2) << 1); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL_DripGame.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL_DripGame.cs index 99105137d34..03c62644076 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL_DripGame.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL_DripGame.cs @@ -219,10 +219,7 @@ public override void WritePrg(int addr, byte value) } } - public override byte ReadPrg(int addr) - { - return Rom[addr & 0x3fff | prg[addr >> 14] << 14]; - } + public override byte ReadPrg(int addr) => Rom[addr & 0x3fff | prg[addr >> 14] << 14]; public override byte ReadPpu(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL_SMB2J.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL_SMB2J.cs index d29a7927466..94d2449225c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL_SMB2J.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_UNL_SMB2J.cs @@ -55,15 +55,9 @@ public override byte ReadExp(int addr) else return base.ReadExp(addr); } - public override byte ReadWram(int addr) - { - return Rom[addr + (prg_count - 2) * 0x1000]; - } + public override byte ReadWram(int addr) => Rom[addr + (prg_count - 2) * 0x1000]; - public override byte ReadPrg(int addr) - { - return Rom[(addr + prg * 01000)]; - } + public override byte ReadPrg(int addr) => Rom[(addr + prg * 01000)]; public override void ClockCpu() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UxROM.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UxROM.cs index 45c68de8d6b..6dc300147a7 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UxROM.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UxROM.cs @@ -102,10 +102,7 @@ public override byte ReadPrg(int addr) int ofs = addr & 0x3FFF; return Rom[(page << 14) | ofs]; } - public override void WritePrg(int addr, byte value) - { - prg = adjust_prg(value) & prg_mask; - } + public override void WritePrg(int addr, byte value) => prg = adjust_prg(value) & prg_mask; public override byte ReadPpu(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/VRC2_4.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/VRC2_4.cs index 7ce93f85702..af2a0a31c4c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/VRC2_4.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/VRC2_4.cs @@ -15,50 +15,23 @@ internal sealed class VRC2_4 : NesBoardBase // in addition, each variety has two other bits; a "low bit" and a "high bit" // for vrc2b, low bit is A0 and high bit is A1, so it's represented by AddrA0A1 // other remaps are named similarly - private int AddrA1A0(int addr) - { - return addr & 0x7000 | (addr >> 1) & 1 | (addr << 1) & 2; - } + private int AddrA1A0(int addr) => addr & 0x7000 | (addr >> 1) & 1 | (addr << 1) & 2; - private int AddrA0A1(int addr) - { - return addr & 0x7003; - } + private int AddrA0A1(int addr) => addr & 0x7003; - private int AddrA1A2(int addr) - { - return addr & 0x7000 | (addr >> 1) & 3; - } + private int AddrA1A2(int addr) => addr & 0x7000 | (addr >> 1) & 3; - private int AddrA6A7(int addr) - { - return addr & 0x7000 | (addr >> 6) & 3; - } + private int AddrA6A7(int addr) => addr & 0x7000 | (addr >> 6) & 3; - private int AddrA2A3(int addr) - { - return addr & 0x7000 | (addr >> 2) & 3; - } + private int AddrA2A3(int addr) => addr & 0x7000 | (addr >> 2) & 3; - private int AddrA3A2(int addr) - { - return addr & 0x7000 | (addr >> 3) & 1 | (addr >> 1) & 2; - } + private int AddrA3A2(int addr) => addr & 0x7000 | (addr >> 3) & 1 | (addr >> 1) & 2; // these composite mappings are what's needed for ines mappers - private int AddrA1A2_A6A7(int addr) - { - return addr & 0x7000 | (addr >> 1) & 3 | (addr >> 6) & 3; - } + private int AddrA1A2_A6A7(int addr) => addr & 0x7000 | (addr >> 1) & 3 | (addr >> 6) & 3; - private int AddrA0A1_A2A3(int addr) - { - return addr & 0x7003 | (addr >> 2) & 3; - } + private int AddrA0A1_A2A3(int addr) => addr & 0x7003 | (addr >> 2) & 3; - private int AddrA3A2_A1A0(int addr) - { - return addr & 0x7000 | (addr >> 3) & 1 | (addr >> 1) & 3 | (addr << 1) & 2; - } + private int AddrA3A2_A1A0(int addr) => addr & 0x7000 | (addr >> 3) & 1 | (addr >> 1) & 3 | (addr << 1) & 2; private int prg_bank_mask_8k, chr_bank_mask_1k; private int prg_reg_mask_8k; @@ -150,10 +123,7 @@ public void SyncCHR() } } - private void SyncIRQ() - { - IrqSignal = (irq_pending && irq_enabled); - } + private void SyncIRQ() => IrqSignal = (irq_pending && irq_enabled); public override bool Configure(EDetectionOrigin origin) { @@ -210,21 +180,20 @@ public override bool Configure(EDetectionOrigin origin) case "KONAMI-VRC-4": AssertPrg(128, 256); AssertChr(128, 256); AssertVram(0); AssertWram(0, 2, 8); type = 4; - switch (Cart.Pcb) + remap = Cart.Pcb switch { - case "352398": // vrc4a A1 A2 - remap = AddrA1A2; break; - case "351406": // vrc4b A1 A0 - remap = AddrA1A0; break; - case "352889": // vrc4c A6 A7 - remap = AddrA6A7; break; - case "352400": // vrc4d A3 A2 - remap = AddrA3A2; break; - case "352396": // vrc4e A2 A3 - remap = AddrA2A3; break; - default: - throw new Exception("Unknown PCB type for VRC4"); - } + // vrc4a A1 A2 + "352398" => AddrA1A2, + // vrc4b A1 A0 + "351406" => AddrA1A0, + // vrc4c A6 A7 + "352889" => AddrA6A7, + // vrc4d A3 A2 + "352400" => AddrA3A2, + // vrc4e A2 A3 + "352396" => AddrA2A3, + _ => throw new Exception("Unknown PCB type for VRC4"), + }; break; case "KONAMI-VRC-2": AssertPrg(128, 256); AssertChr(128, 256); AssertVram(0); AssertWram(0, 8); @@ -316,12 +285,12 @@ public override void WritePrg(int addr, byte value) prg_banks_8k[_prgMode?1:0] = (byte)((prg_banks_8k[0] & 0x20) | (value & 0x1F)); return; } - else if (addr >= 0x2000 && addr < 0x3000) + else if (addr is >= 0x2000 and < 0x3000) { prg_banks_8k[1] = (byte)((prg_banks_8k[0] & 0x20) | (value & 0x1F)); return; } - else if (addr >= 0x3000 && addr < 0x7000) + else if (addr is >= 0x3000 and < 0x7000) { value = (byte)(value << 2 & 0x20); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/VRC3.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/VRC3.cs index 0e03e9e12b6..0359ba07946 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/VRC3.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/VRC3.cs @@ -32,10 +32,7 @@ public override void SyncState(Serializer ser) SyncIRQ(); } - private void SyncIRQ() - { - IrqSignal = (irq_pending && irq_enabled); - } + private void SyncIRQ() => IrqSignal = (irq_pending && irq_enabled); public override bool Configure(EDetectionOrigin origin) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/VRC6.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/VRC6.cs index 6ebbe1476ce..54bf6412006 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/VRC6.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/VRC6.cs @@ -39,24 +39,12 @@ private static void GetBankByte(int b003, int banknum, out byte bank, out byte m else // nametables { banknum &= 3; - switch (b003 & 7) + bank = (b003 & 7) switch { - case 0: - case 6: - case 7: // H-mirror, 6677 - bank = (byte)(banknum >> 1 | 6); - break; - case 2: - case 3: - case 4: // V-mirror, 6767 - bank = (byte)(banknum | 6); - break; - case 1: - case 5: // 4 screen, 4567 - default: - bank = (byte)(banknum | 4); - break; - } + 0 or 6 or 7 => (byte)(banknum >> 1 | 6), + 2 or 3 or 4 => (byte)(banknum | 6), + _ => (byte)(banknum | 4), + }; switch (b003) { case 0: @@ -155,10 +143,7 @@ private void SyncPRG() prg_banks_8k[3] = 0xFF; } - private void SyncIRQ() - { - IrqSignal = (irq_pending && irq_enabled); - } + private void SyncIRQ() => IrqSignal = (irq_pending && irq_enabled); public override bool Configure(EDetectionOrigin origin) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/VRC7.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/VRC7.cs index a95c9101b38..bd1418695bc 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/VRC7.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/VRC7.cs @@ -40,42 +40,38 @@ public override void SyncState(Serializer ser) SyncIRQ(); } - private void SyncIRQ() - { - IrqSignal = (irq_pending && irq_enabled); - } + private void SyncIRQ() => IrqSignal = (irq_pending && irq_enabled); private static int RemapM117(int addr) { //addr &= 0x7007; // i don't know all of which bits are decoded, but this breaks stuff - switch (addr) + return addr switch { //prg - case 0x0000: return 0x0000; - case 0x0001: return 0x0001; - case 0x0002: return 0x1000; + 0x0000 => 0x0000, + 0x0001 => 0x0001, + 0x0002 => 0x1000, //chr - case 0x2000: return 0x2000; - case 0x2001: return 0x2001; - case 0x2002: return 0x3000; - case 0x2003: return 0x3001; - case 0x2004: return 0x4000; - case 0x2005: return 0x4001; - case 0x2006: return 0x5000; - case 0x2007: return 0x5001; + 0x2000 => 0x2000, + 0x2001 => 0x2001, + 0x2002 => 0x3000, + 0x2003 => 0x3001, + 0x2004 => 0x4000, + 0x2005 => 0x4001, + 0x2006 => 0x5000, + 0x2007 => 0x5001, //irq // fake addressees to activate different irq handling logic - case 0x4001: return 0x10001; - case 0x4002: return 0x10002; - case 0x4003: return 0x10003; - case 0x6000: return 0x10004; + 0x4001 => 0x10001, + 0x4002 => 0x10002, + 0x4003 => 0x10003, + 0x6000 => 0x10004, //mir - case 0x5000: return 0x6000; - + 0x5000 => 0x6000, //probably nothing at all - default: return 0xffff; - } + _ => 0xffff, + }; } public override bool Configure(EDetectionOrigin origin) diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/VS_M99.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/VS_M99.cs index 85ac8a353bf..b9f63c9e958 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/VS_M99.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/VS_M99.cs @@ -52,11 +52,9 @@ public override void WriteExp(int addr, byte value) //but we don't actually need to do anything yet } - public override byte ReadExp(int addr) - { + public override byte ReadExp(int addr) => //what are we reading? - return 0; - } + 0; public override byte ReadPpu(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/inlnsf.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/inlnsf.cs index 50fbae5cb42..2be24b8f457 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/inlnsf.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/inlnsf.cs @@ -48,9 +48,6 @@ public override void WriteExp(int addr, byte value) base.WriteExp(addr, value); } - public override byte ReadPrg(int addr) - { - return Rom[prg[(addr & 0x7000) >> 12] << 12 | addr & 0x0fff]; - } + public override byte ReadPrg(int addr) => Rom[prg[(addr & 0x7000) >> 12] << 12 | addr & 0x0fff]; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/BootGodDB.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/BootGodDB.cs index d1b772f8eab..b19be2875a1 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/BootGodDB.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/BootGodDB.cs @@ -18,7 +18,7 @@ public class BootGodDb private readonly bool validate = true; - private readonly Bag _sha1Table = new Bag(); + private readonly Bag _sha1Table = new(); private static BootGodDb instance; @@ -27,7 +27,7 @@ public static void Initialize(string basePath) if (acquire != null) throw new InvalidOperationException("Bootgod DB multiply initialized"); acquire = new EventWaitHandle(false, EventResetMode.ManualReset); - var stopwatch = Stopwatch.StartNew(); + Stopwatch stopwatch = Stopwatch.StartNew(); ThreadPool.QueueUserWorkItem(_ => { instance = new BootGodDb(basePath); @@ -62,7 +62,7 @@ public BootGodDb(string basePath) // in anticipation of any slowness annoying people, and just for shits and giggles, i made a super fast parser int state=0; - var xmlReader = XmlReader.Create(stream); + XmlReader xmlReader = XmlReader.Create(stream); CartInfo currCart = null; string currName = null; while (xmlReader.Read()) @@ -134,10 +134,12 @@ public BootGodDb(string basePath) case 1: if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.Name == "cartridge") { - currCart = new CartInfo(); - currCart.System = xmlReader.GetAttribute("system"); - currCart.Sha1 = $"SHA1:{xmlReader.GetAttribute("sha1")}"; - currCart.Name = currName; + currCart = new CartInfo + { + System = xmlReader.GetAttribute("system"), + Sha1 = $"SHA1:{xmlReader.GetAttribute("sha1")}", + Name = currName + }; state = 2; } if (xmlReader.NodeType == XmlNodeType.EndElement && xmlReader.Name == "game") diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/FDS/FDS.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/FDS/FDS.cs index fe9f778c0cd..ed8978aeae2 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/FDS/FDS.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/FDS/FDS.cs @@ -79,10 +79,7 @@ public override void SyncState(Serializer ser) SetIRQ(); } - public void SetDriveLightCallback(Action callback) - { - diskdrive.DriveLightCallback = callback; - } + public void SetDriveLightCallback(Action callback) => diskdrive.DriveLightCallback = callback; /// /// should only be called once, before emulation begins @@ -94,7 +91,7 @@ public void SetDiskImage(byte[] diskimage) { int nsides = diskimage.Length / 65500; - MemoryStream ms = new MemoryStream(); + MemoryStream ms = new(); ms.Write(Encoding.ASCII.GetBytes("FDS\x1A"), 0, 4); ms.WriteByte((byte)nsides); byte[] nulls = new byte[11]; @@ -167,8 +164,8 @@ public byte[] ReadSaveRam() // update diff for currently loaded disk first! if (currentside != null) diskdiffs[(int)currentside] = diskdrive.MakeDiff(); - MemoryStream ms = new MemoryStream(); - BinaryWriter bw = new BinaryWriter(ms); + MemoryStream ms = new(); + BinaryWriter bw = new(ms); bw.Write(Encoding.ASCII.GetBytes("FDSS")); bw.Write(NumSides); for (int i = 0; i < NumSides; i++) @@ -193,8 +190,8 @@ public void StoreSaveRam(byte[] data) // but in fact, StoreSaveRam() is only called once right at startup, so this is no big deal //if (currentside != null) // throw new Exception("FDS Saveram: Can't load when a disk is active!"); - MemoryStream ms = new MemoryStream(data, false); - BinaryReader br = new BinaryReader(ms); + MemoryStream ms = new(data, false); + BinaryReader br = new(ms); byte[] cmp = Encoding.ASCII.GetBytes("FDSS"); byte[] tmp = br.ReadBytes(cmp.Length); if (!cmp.SequenceEqual(tmp)) @@ -217,15 +214,9 @@ public void StoreSaveRam(byte[] data) public override byte[] SaveRam => throw new Exception("FDS Saveram: Must access with method api!"); - public MemoryDomain GetDiskPeeker() - { - return new MemoryDomainDelegate("FDS Side", diskdrive.NumBytes, MemoryDomain.Endian.Little, diskdrive.PeekData, null, 1); - } + public MemoryDomain GetDiskPeeker() => new MemoryDomainDelegate("FDS Side", diskdrive.NumBytes, MemoryDomain.Endian.Little, diskdrive.PeekData, null, 1); - private void SetIRQ() - { - IrqSignal = _diskirq || _timerirq; - } + private void SetIRQ() => IrqSignal = _diskirq || _timerirq; private bool diskirq { @@ -406,15 +397,9 @@ public override void ClockPpu() diskirq = diskdrive.irq; } - public override byte ReadWram(int addr) - { - return Wram[addr & 0x1fff]; - } + public override byte ReadWram(int addr) => Wram[addr & 0x1fff]; - public override void WriteWram(int addr, byte value) - { - Wram[addr & 0x1fff] = value; - } + public override void WriteWram(int addr, byte value) => Wram[addr & 0x1fff] = value; public override byte ReadPrg(int addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/FDS/FDSInspector.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/FDS/FDSInspector.cs index 884e65fed22..47a4bfe104b 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/FDS/FDSInspector.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/FDS/FDSInspector.cs @@ -100,7 +100,7 @@ public FDSDisk(BinaryReader r) { try { - var chunk = new FDSChunk(r) { Hidden = true }; + FDSChunk chunk = new(r) { Hidden = true }; if (r.BaseStream.Position <= endpos) { Chunks.Add(chunk); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/FDS/RamAdapter.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/FDS/RamAdapter.cs index a6eb72c53fe..dc4ca8dc0d0 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/FDS/RamAdapter.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/FDS/RamAdapter.cs @@ -32,10 +32,10 @@ private static byte[] FixFDSSide(byte[] inputdisk) // todo: implement CRC. since the RamAdapter itself doesn't implement it, broken is not a problem // since its not contained in dumps, no way to be sure that the implementation is right - MemoryStream inp = new MemoryStream(inputdisk, false); - BinaryReader br = new BinaryReader(inp); + MemoryStream inp = new(inputdisk, false); + BinaryReader br = new(inp); - MemoryStream ret = new MemoryStream(); + MemoryStream ret = new(); // block 1: header byte[] header = br.ReadBytes(56); @@ -616,7 +616,7 @@ private void Write() } } - var tmp = disk[diskpos >> 3]; + byte tmp = disk[diskpos >> 3]; tmp &= unchecked((byte)~(1 << (diskpos & 7))); if (bittowrite) tmp |= (byte)(1 << (diskpos & 7)); @@ -624,12 +624,10 @@ private void Write() diskpos++; } - private void MoveDummy() - { + private void MoveDummy() => // It seems that the real disk doesn't keep on running at normal speed to the end while restting // Whoever told me that was mistaken... diskpos += 5000; - } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.BoardSystem.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.BoardSystem.cs index f4f486a5c83..27ce509a353 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.BoardSystem.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.BoardSystem.cs @@ -7,11 +7,11 @@ namespace BizHawk.Emulation.Cores.Nintendo.NES { partial class NES { - private static readonly List INESBoardImplementors = new List(); + private static readonly List INESBoardImplementors = new(); private static INesBoard CreateBoardInstance(Type boardType) { - var board = (INesBoard)Activator.CreateInstance(boardType); + INesBoard board = (INesBoard)Activator.CreateInstance(boardType); lock (INESBoardImplementors) { //put the one we chose at the top of the list, for quicker access in the future @@ -32,16 +32,16 @@ private void BoardSystemHardReset() // FDS and NSF have a unique activation setup if (Board is FDS) { - var newfds = new FDS(); - var oldfds = Board as FDS; + FDS newfds = new(); + FDS oldfds = Board as FDS; newfds.biosrom = oldfds.biosrom; newfds.SetDiskImage(oldfds.GetDiskImage()); newboard = newfds; } else if (Board is NSFBoard) { - var newnsf = new NSFBoard(); - var oldnsf = Board as NSFBoard; + NSFBoard newnsf = new(); + NSFBoard oldnsf = Board as NSFBoard; newnsf.InitNSF(oldnsf.nsf); newboard = newnsf; } @@ -65,8 +65,8 @@ private void BoardSystemHardReset() // the old board's sram must be restored if (newboard is FDS) { - var newfds = newboard as FDS; - var oldfds = Board as FDS; + FDS newfds = newboard as FDS; + FDS oldfds = Board as FDS; newfds.StoreSaveRam(oldfds.ReadSaveRam()); } else if (Board.SaveRam != null) @@ -81,18 +81,18 @@ private void BoardSystemHardReset() static NES() { - var highPriority = new List(); - var normalPriority = new List(); + List highPriority = new(); + List normalPriority = new(); //scan types in this assembly to find ones that implement boards to add them to the list foreach (var type in Emulation.Cores.ReflectionCache.Types) { - var attrs = type.GetCustomAttributes(typeof(NesBoardImplAttribute), true); + object[] attrs = type.GetCustomAttributes(typeof(NesBoardImplAttribute), true); if (attrs.Length == 0) continue; if (type.IsAbstract) continue; - var cancelAttrs = type.GetCustomAttributes(typeof(NesBoardImplCancelAttribute), true); + object[] cancelAttrs = type.GetCustomAttributes(typeof(NesBoardImplCancelAttribute), true); if (cancelAttrs.Length != 0) continue; - var priorityAttrs = type.GetCustomAttributes(typeof(NesBoardImplPriorityAttribute), true); + object[] priorityAttrs = type.GetCustomAttributes(typeof(NesBoardImplPriorityAttribute), true); if (priorityAttrs.Length != 0) highPriority.Add(type); else normalPriority.Add(type); @@ -107,7 +107,7 @@ static NES() /// private static Type FindBoard(CartInfo cart, EDetectionOrigin origin, Dictionary properties) { - NES nes = new NES { cart = cart }; + NES nes = new() { cart = cart }; Type ret = null; lock(INESBoardImplementors) foreach (var type in INESBoardImplementors) @@ -140,9 +140,9 @@ private static Type FindBoard(CartInfo cart, EDetectionOrigin origin, Dictionary /// private CartInfo IdentifyFromBootGodDB(IEnumerable hash_sha1) { - foreach (var hash in hash_sha1) + foreach (string hash in hash_sha1) { - List choices = BootGodDb.Identify(hash); + var choices = BootGodDb.Identify(hash); //pick the first board for this hash arbitrarily. it probably doesn't make a difference if (choices.Count != 0) return choices[0]; @@ -158,23 +158,23 @@ private CartInfo IdentifyFromGameDB(string hash) var gi = Database.CheckDatabase(hash); if (gi == null) return null; - CartInfo cart = new CartInfo(); + CartInfo cart = new(); //try generating a bootgod cart descriptor from the game database var dict = gi.GetOptions(); cart.GameInfo = gi; - if (!dict.TryGetValue("board", out var board)) throw new Exception("NES gamedb entries must have a board identifier!"); + if (!dict.TryGetValue("board", out string board)) throw new Exception("NES gamedb entries must have a board identifier!"); cart.BoardType = board; - if (dict.TryGetValue("system", out var system)) cart.System = system; + if (dict.TryGetValue("system", out string system)) cart.System = system; - cart.PrgSize = dict.TryGetValue("PRG", out var prgSizeStr) ? short.Parse(prgSizeStr) : -1; - cart.ChrSize = dict.TryGetValue("CHR", out var chrSizeStr) ? short.Parse(chrSizeStr) : -1; - cart.VramSize = dict.TryGetValue("VRAM", out var vramSizeStr) ? short.Parse(vramSizeStr) : -1; - cart.WramSize = dict.TryGetValue("WRAM", out var wramSizeStr) ? short.Parse(wramSizeStr) : -1; + cart.PrgSize = dict.TryGetValue("PRG", out string prgSizeStr) ? short.Parse(prgSizeStr) : -1; + cart.ChrSize = dict.TryGetValue("CHR", out string chrSizeStr) ? short.Parse(chrSizeStr) : -1; + cart.VramSize = dict.TryGetValue("VRAM", out string vramSizeStr) ? short.Parse(vramSizeStr) : -1; + cart.WramSize = dict.TryGetValue("WRAM", out string wramSizeStr) ? short.Parse(wramSizeStr) : -1; - if (dict.TryGetValue("PAD_H", out var padHStr)) cart.PadH = byte.Parse(padHStr); - if (dict.TryGetValue("PAD_V", out var padVStr)) cart.PadV = byte.Parse(padVStr); - if (dict.TryGetValue("MIR", out var mirStr)) + if (dict.TryGetValue("PAD_H", out string padHStr)) cart.PadH = byte.Parse(padHStr); + if (dict.TryGetValue("PAD_V", out string padVStr)) cart.PadV = byte.Parse(padVStr); + if (dict.TryGetValue("MIR", out string mirStr)) { if (mirStr == "H") { @@ -187,11 +187,11 @@ private CartInfo IdentifyFromGameDB(string hash) } if (dict.ContainsKey("BAD")) cart.Bad = true; - if (dict.TryGetValue("MMC3", out var mmc3)) cart.Chips.Add(mmc3); - if (dict.TryGetValue("PCB", out var pcb)) cart.Pcb = pcb; - if (dict.TryGetValue("BATT", out var batteryStr)) cart.WramBattery = bool.Parse(batteryStr); - if (dict.TryGetValue("palette", out var palette)) cart.Palette = palette; - if (dict.TryGetValue("vs_security", out var vsSecurityStr)) cart.VsSecurity = byte.Parse(vsSecurityStr); + if (dict.TryGetValue("MMC3", out string mmc3)) cart.Chips.Add(mmc3); + if (dict.TryGetValue("PCB", out string pcb)) cart.Pcb = pcb; + if (dict.TryGetValue("BATT", out string batteryStr)) cart.WramBattery = bool.Parse(batteryStr); + if (dict.TryGetValue("palette", out string palette)) cart.Palette = palette; + if (dict.TryGetValue("vs_security", out string vsSecurityStr)) cart.VsSecurity = byte.Parse(vsSecurityStr); return cart; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.Core.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.Core.cs index 522a8385a6a..ddcc53e3fa9 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.Core.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.Core.cs @@ -36,7 +36,6 @@ internal static class RomChecksums public APU apu; public byte[] ram; public byte[] CIRAM; //AKA nametables - private string game_name = ""; //friendly name exposed to user and used as filename base internal CartInfo cart; //the current cart prototype. should be moved into the board, perhaps internal INesBoard Board; //the board hardware that is currently driving things private EDetectionOrigin origin = EDetectionOrigin.None; @@ -78,10 +77,7 @@ internal static class RomChecksums private readonly NESControlSettings ControllerSettings; // this is stored internally so that a new change of settings won't replace private IControllerDeck ControllerDeck; private byte latched4016; - - private DisplayType _display_type = DisplayType.NTSC; - - private BlipBuffer blip = new BlipBuffer(4096); + private BlipBuffer blip = new(4096); private const int blipbuffsize = 4096; public int old_s = 0; @@ -131,10 +127,7 @@ public void SetSyncMode(SyncSoundMode mode) } } - public void GetSamplesAsync(short[] samples) - { - throw new NotSupportedException("Async not supported"); - } + public void GetSamplesAsync(short[] samples) => throw new NotSupportedException("Async not supported"); public SyncSoundMode SyncMode => SyncSoundMode.Sync; @@ -184,7 +177,7 @@ public void HardReset() // if (magicSoundProvider != null) magicSoundProvider.Dispose(); // set up region - switch (_display_type) + switch (Region) { case DisplayType.PAL: apu = new APU(this, apu, true); @@ -193,7 +186,7 @@ public void HardReset() VsyncNum = cpuclockrate * 2; VsyncDen = 66495; cpu_sequence = cpu_sequence_PAL; - _display_type = DisplayType.PAL; + Region = DisplayType.PAL; ClockRate = 5320342.5; break; case DisplayType.NTSC: @@ -213,7 +206,7 @@ public void HardReset() VsyncNum = cpuclockrate; VsyncDen = 35464; cpu_sequence = cpu_sequence_NTSC; - _display_type = DisplayType.Dendy; + Region = DisplayType.Dendy; ClockRate = 5320342.5; break; default: @@ -256,7 +249,7 @@ public void HardReset() // some boards cannot have specific values in RAM upon initialization // Let's hard code those cases here // these will be defined through the gameDB exclusively for now. - var hash = cart.GameInfo?.Hash; // SHA1 or MD5 (see NES.IdentifyFromGameDB) + string hash = cart.GameInfo?.Hash; // SHA1 or MD5 (see NES.IdentifyFromGameDB) if (hash is null) { // short-circuit @@ -270,7 +263,7 @@ public void HardReset() ram[0xEC] = 0; ram[0xED] = 0; } - else if (hash == RomChecksums.SilvaSaga || hash == RomChecksums.Fam_Jump_II) + else if (hash is RomChecksums.SilvaSaga or RomChecksums.Fam_Jump_II) { for (int i = 0; i < Board.Wram.Length; i++) { @@ -319,7 +312,7 @@ public bool FrameAdvance(IController controller, bool render, bool rendersound) if (Board is FDS) { - var b = Board as FDS; + FDS b = Board as FDS; if (controller.IsPressed("FDS Eject")) b.Eject(); for (int i = 0; i < b.NumSides; i++) @@ -841,8 +834,8 @@ private void WriteReg(int addr, byte val) private void write_joyport(byte value) { //Console.WriteLine("cont " + value + " frame " + Frame); - - var si = new StrobeInfo(latched4016, value); + + StrobeInfo si = new(latched4016, value); ControllerDeck.Strobe(si, _controller); latched4016 = value; new_strobe = (value & 1) > 0; @@ -873,11 +866,9 @@ private byte read_joyport(int addr) return ret; } - private byte peek_joyport(int addr) - { + private byte peek_joyport(int addr) => // at the moment, the new system doesn't support peeks - return 0; - } + 0; /// /// Sets the provided palette as current. @@ -918,12 +909,9 @@ public void SetPalette(byte[,] pal) /// /// looks up an internal NES pixel value to an rgb int (applying the core's current palette and assuming no deemph) /// - public int LookupColor(int pixel) - { - return palette_compiled[pixel]; - } + public int LookupColor(int pixel) => palette_compiled[pixel]; - public byte DummyReadMemory(ushort addr) { return 0; } + public byte DummyReadMemory(ushort addr) => 0; public void ApplySystemBusPoke(int addr, byte value) { @@ -1043,7 +1031,7 @@ public byte ReadMemory(ushort addr) // this means that OAM DMA can actually access memory that the cpu cannot if (oam_dma_exec) { - if ((cpu.PC >= 0x4000) && (cpu.PC < 0x4020)) + if (cpu.PC is >= 0x4000 and < 0x4020) { ret = ReadReg(addr); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.CpuLink.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.CpuLink.cs index daccb94f1df..ba2198b27b0 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.CpuLink.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.CpuLink.cs @@ -4,7 +4,7 @@ namespace BizHawk.Emulation.Cores.Nintendo.NES { public partial class NES { - public struct CpuLink : IMOS6502XLink + public readonly struct CpuLink : IMOS6502XLink { private readonly NES _nes; @@ -13,15 +13,15 @@ public CpuLink(NES nes) _nes = nes; } - public byte DummyReadMemory(ushort address) => _nes.ReadMemory(address); + public readonly byte DummyReadMemory(ushort address) => _nes.ReadMemory(address); - public void OnExecFetch(ushort address) => _nes.ExecFetch(address); + public readonly void OnExecFetch(ushort address) => _nes.ExecFetch(address); - public byte PeekMemory(ushort address) => _nes.CDL == null ? _nes.PeekMemory(address) : _nes.FetchMemory_CDL(address); + public readonly byte PeekMemory(ushort address) => _nes.CDL == null ? _nes.PeekMemory(address) : _nes.FetchMemory_CDL(address); - public byte ReadMemory(ushort address) => _nes.CDL == null ? _nes.ReadMemory(address) : _nes.ReadMemory_CDL(address); + public readonly byte ReadMemory(ushort address) => _nes.CDL == null ? _nes.ReadMemory(address) : _nes.ReadMemory_CDL(address); - public void WriteMemory(ushort address, byte value) => _nes.WriteMemory(address, value); + public readonly void WriteMemory(ushort address, byte value) => _nes.WriteMemory(address, value); } } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.ICodeDataLogger.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.ICodeDataLogger.cs index dfaef1ad0b3..167e0b18e32 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.ICodeDataLogger.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.ICodeDataLogger.cs @@ -6,10 +6,7 @@ namespace BizHawk.Emulation.Cores.Nintendo.NES { public sealed partial class NES : ICodeDataLogger { - public void SetCDL(ICodeDataLog cdl) - { - CDL = cdl; - } + public void SetCDL(ICodeDataLog cdl) => CDL = cdl; public void NewCDL(ICodeDataLog cdl) { @@ -60,7 +57,7 @@ public struct CDLog_MapResults private void RunCDL(ushort address, CDLog_Flags flags) { - CDLog_MapResults results = Board.MapMemory(address, false); + var results = Board.MapMemory(address, false); switch (results.Type) { case CDLog_AddrType.None: break; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.IInputPollable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.IInputPollable.cs index 4f02071ec9e..803d8f77613 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.IInputPollable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.IInputPollable.cs @@ -22,6 +22,6 @@ public bool IsLagFrame internal bool lagged = true; private bool islag = false; - private readonly InputCallbackSystem _inputCallbacks = new InputCallbackSystem(); + private readonly InputCallbackSystem _inputCallbacks = new(); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.IMemoryDomains.cs index faf3f19f46d..397196e555b 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.IMemoryDomains.cs @@ -10,18 +10,18 @@ public partial class NES private void SetupMemoryDomains() { - var domains = new List(); - var RAM = new MemoryDomainByteArray("RAM", MemoryDomain.Endian.Little, ram, true, 1); + List domains = new(); + MemoryDomainByteArray RAM = new("RAM", MemoryDomain.Endian.Little, ram, true, 1); // System bus gets it's own class in order to send compare values to cheats - var SystemBus = new MemoryDomainDelegateSysBusNES("System Bus", 0x10000, MemoryDomain.Endian.Little, + MemoryDomainDelegateSysBusNES SystemBus = new("System Bus", 0x10000, MemoryDomain.Endian.Little, addr => PeekMemory((ushort)addr), (addr, value) => ApplySystemBusPoke((int)addr, value), 1, (addr, value, compare, comparetype) => ApplyCompareCheat(addr, value, compare, comparetype)); - var PPUBus = new MemoryDomainDelegate("PPU Bus", 0x4000, MemoryDomain.Endian.Little, + MemoryDomainDelegate PPUBus = new("PPU Bus", 0x4000, MemoryDomain.Endian.Little, addr => ppu.ppubus_peek((int)addr), (addr, value) => ppu.ppubus_write((int)addr, value), 1); - var CIRAMdomain = new MemoryDomainByteArray("CIRAM (nametables)", MemoryDomain.Endian.Little, CIRAM, true, 1); - var OAMdoman = new MemoryDomainByteArray("OAM", MemoryDomain.Endian.Unknown, ppu.OAM, true, 1); + MemoryDomainByteArray CIRAMdomain = new("CIRAM (nametables)", MemoryDomain.Endian.Little, CIRAM, true, 1); + MemoryDomainByteArray OAMdoman = new("OAM", MemoryDomain.Endian.Unknown, ppu.OAM, true, 1); domains.Add(RAM); domains.Add(SystemBus); @@ -31,31 +31,31 @@ private void SetupMemoryDomains() if (Board is not FDS && Board.SaveRam != null) { - var BatteryRam = new MemoryDomainByteArray("Battery RAM", MemoryDomain.Endian.Little, Board.SaveRam, true, 1); + MemoryDomainByteArray BatteryRam = new("Battery RAM", MemoryDomain.Endian.Little, Board.SaveRam, true, 1); domains.Add(BatteryRam); } if (Board.Rom != null) { - var PRGROM = new MemoryDomainByteArray("PRG ROM", MemoryDomain.Endian.Little, Board.Rom, true, 1); + MemoryDomainByteArray PRGROM = new("PRG ROM", MemoryDomain.Endian.Little, Board.Rom, true, 1); domains.Add(PRGROM); } if (Board.Vrom != null) { - var CHRROM = new MemoryDomainByteArray("CHR VROM", MemoryDomain.Endian.Little, Board.Vrom, true, 1); + MemoryDomainByteArray CHRROM = new("CHR VROM", MemoryDomain.Endian.Little, Board.Vrom, true, 1); domains.Add(CHRROM); } if (Board.Vram != null) { - var VRAM = new MemoryDomainByteArray("VRAM", MemoryDomain.Endian.Little, Board.Vram, true, 1); + MemoryDomainByteArray VRAM = new("VRAM", MemoryDomain.Endian.Little, Board.Vram, true, 1); domains.Add(VRAM); } if (Board.Wram != null) { - var WRAM = new MemoryDomainByteArray("WRAM", MemoryDomain.Endian.Little, Board.Wram, true, 1); + MemoryDomainByteArray WRAM = new("WRAM", MemoryDomain.Endian.Little, Board.Wram, true, 1); domains.Add(WRAM); } @@ -77,7 +77,7 @@ private void SetupMemoryDomains() } else { - var src = new MemoryDomainList(domains); + MemoryDomainList src = new(domains); _memoryDomains.MergeList(src); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.INESPPUViewable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.INESPPUViewable.cs index 4906a3469d2..e4146cbea14 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.INESPPUViewable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.INESPPUViewable.cs @@ -56,24 +56,12 @@ public byte[] GetExRam() public MemoryDomain GetCHRROM() => _memoryDomains["CHR VROM"]; - public void InstallCallback1(Action cb, int sl) - { - ppu.NTViewCallback = new PPU.DebugCallback { Callback = cb, Scanline = sl }; - } + public void InstallCallback1(Action cb, int sl) => ppu.NTViewCallback = new PPU.DebugCallback { Callback = cb, Scanline = sl }; - public void InstallCallback2(Action cb, int sl) - { - ppu.PPUViewCallback = new PPU.DebugCallback { Callback = cb, Scanline = sl }; - } + public void InstallCallback2(Action cb, int sl) => ppu.PPUViewCallback = new PPU.DebugCallback { Callback = cb, Scanline = sl }; - public void RemoveCallback1() - { - ppu.NTViewCallback = null; - } + public void RemoveCallback1() => ppu.NTViewCallback = null; - public void RemoveCallback2() - { - ppu.PPUViewCallback = null; - } + public void RemoveCallback2() => ppu.PPUViewCallback = null; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.ISettable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.ISettable.cs index 937f39b5907..59783d4d160 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.ISettable.cs @@ -40,12 +40,12 @@ public PutSettingsDirtyBits PutSyncSettings(NESSyncSettings o) return ret ? PutSettingsDirtyBits.RebootCore : PutSettingsDirtyBits.None; } - internal NESSettings Settings = new NESSettings(); - internal NESSyncSettings SyncSettings = new NESSyncSettings(); + internal NESSettings Settings = new(); + internal NESSyncSettings SyncSettings = new(); public class NESSyncSettings { - public Dictionary BoardProperties = new Dictionary(); + public Dictionary BoardProperties = new(); public enum Region { @@ -57,13 +57,13 @@ public enum Region public Region RegionOverride = Region.Default; - public NESControlSettings Controls = new NESControlSettings(); + public NESControlSettings Controls = new(); public List InitialWRamStatePattern = null; public NESSyncSettings Clone() { - var ret = (NESSyncSettings)MemberwiseClone(); + NESSyncSettings ret = (NESSyncSettings)MemberwiseClone(); ret.BoardProperties = new Dictionary(BoardProperties); ret.Controls = Controls.Clone(); ret.VSDipswitches = VSDipswitches.Clone(); @@ -90,10 +90,7 @@ public class VSDipswitchSettings public bool Dip_Switch_7 { get; set; } public bool Dip_Switch_8 { get; set; } - public VSDipswitchSettings Clone() - { - return (VSDipswitchSettings)MemberwiseClone(); - } + public VSDipswitchSettings Clone() => (VSDipswitchSettings)MemberwiseClone(); public override bool Equals(object obj) { @@ -104,7 +101,7 @@ public override bool Equals(object obj) if (obj is VSDipswitchSettings) { - var settings = obj as VSDipswitchSettings; + VSDipswitchSettings settings = obj as VSDipswitchSettings; return Dip_Switch_1 == settings.Dip_Switch_1 && Dip_Switch_2 == settings.Dip_Switch_2 && Dip_Switch_3 == settings.Dip_Switch_3 @@ -118,13 +115,10 @@ public override bool Equals(object obj) return base.Equals(obj); } - public override int GetHashCode() - { - return base.GetHashCode(); - } + public override int GetHashCode() => base.GetHashCode(); } - public VSDipswitchSettings VSDipswitches = new VSDipswitchSettings(); + public VSDipswitchSettings VSDipswitches = new(); } public class NESSettings @@ -146,7 +140,7 @@ public class NESSettings public NESSettings Clone() { - var ret = (NESSettings)MemberwiseClone(); + NESSettings ret = (NESSettings)MemberwiseClone(); ret.Palette = (byte[,])ret.Palette.Clone(); return ret; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.cs index 4a952d00c6a..eddf8199847 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NES.cs @@ -16,14 +16,14 @@ public partial class NES : IEmulator, ISaveRam, IDebuggable, IInputPollable, IRe [CoreConstructor(VSystemID.Raw.NES)] public NES(CoreComm comm, GameInfo game, byte[] rom, NESSettings settings, NESSyncSettings syncSettings, bool subframe = false) { - var ser = new BasicServiceProvider(this); + BasicServiceProvider ser = new(this); ServiceProvider = ser; - var fdsBios = comm.CoreFileProvider.GetFirmware(new("NES", "Bios_FDS")); + byte[] fdsBios = comm.CoreFileProvider.GetFirmware(new("NES", "Bios_FDS")); if (fdsBios != null && fdsBios.Length == 40976) { comm.ShowMessage("Your FDS BIOS is a bad dump. BizHawk will attempt to use it, but no guarantees! You should find a new one."); - var tmp = new byte[8192]; + byte[] tmp = new byte[8192]; Buffer.BlockCopy(fdsBios, 16 + 8192 * 3, tmp, 0, 8192); fdsBios = tmp; } @@ -118,7 +118,7 @@ public bool HasMapperProperties public bool IsFDS => Board is FDS; - public DisplayType Region => _display_type; + public DisplayType Region { get; private set; } = DisplayType.NTSC; int IVideoLogicalOffsets.ScreenX => Settings.ClipLeftAndRight ? 8 @@ -143,10 +143,7 @@ public MyVideoProvider(NES emu) } private readonly int[] pixels = new int[256 * 240]; - public int[] GetVideoBuffer() - { - return pixels; - } + public int[] GetVideoBuffer() => pixels; public void FillFrameBuffer() { @@ -282,7 +279,7 @@ public void ResetCounters() public string SystemId => VSystemID.Raw.NES; - public string GameName => game_name; + public string GameName { get; private set; } = ""; private StringWriter LoadReport; @@ -292,7 +289,7 @@ private void LoadWriteLine(string format, params object[] arg) LoadReport.WriteLine(format, arg); } - private void LoadWriteLine(object arg) { LoadWriteLine("{0}", arg); } + private void LoadWriteLine(object arg) => LoadWriteLine("{0}", arg); private class MyWriter : StringWriter { @@ -325,11 +322,11 @@ public void Init(GameInfo gameInfo, byte[] rom, byte[] fdsbios = null) CartInfo choice = null; CartInfo iNesHeaderInfo = null; CartInfo iNesHeaderInfoV2 = null; - List hash_sha1_several = new List(); + List hash_sha1_several = new(); string hash_sha1 = null, hash_md5 = null; Unif unif = null; - Dictionary InitialMapperRegisterValues = new Dictionary(SyncSettings.BoardProperties); + Dictionary InitialMapperRegisterValues = new(SyncSettings.BoardProperties); origin = EDetectionOrigin.None; @@ -348,11 +345,11 @@ public void Init(GameInfo gameInfo, byte[] rom, byte[] fdsbios = null) { origin = EDetectionOrigin.NSF; LoadWriteLine("Loading as NSF"); - var nsf = new NSFFormat(); + NSFFormat nsf = new(); nsf.WrapByteArray(file); cart = new CartInfo(); - var nsfboard = new NSFBoard(); + NSFBoard nsfboard = new(); nsfboard.Create(this); nsfboard.Rom = rom; nsfboard.InitNSF( nsf); @@ -364,7 +361,7 @@ public void Init(GameInfo gameInfo, byte[] rom, byte[] fdsbios = null) AutoMapperProps.Populate(Board, SyncSettings); Console.WriteLine("Using NTSC display type for NSF for now"); - _display_type = DisplayType.NTSC; + Region = DisplayType.NTSC; HardReset(); @@ -382,8 +379,10 @@ public void Init(GameInfo gameInfo, byte[] rom, byte[] fdsbios = null) if (fdsbios == null) throw new MissingFirmwareException("Missing FDS Bios"); cart = new CartInfo(); - var fdsboard = new FDS(); - fdsboard.biosrom = fdsbios; + FDS fdsboard = new() + { + biosrom = fdsbios + }; fdsboard.SetDiskImage(rom); fdsboard.Create(this); // at the moment, FDS doesn't use the IRVs, but it could at some point in the future @@ -402,7 +401,7 @@ public void Init(GameInfo gameInfo, byte[] rom, byte[] fdsbios = null) AutoMapperProps.Populate(Board, SyncSettings); Console.WriteLine("Using NTSC display type for FDS disk image"); - _display_type = DisplayType.NTSC; + Region = DisplayType.NTSC; HardReset(); @@ -466,7 +465,7 @@ public void Init(GameInfo gameInfo, byte[] rom, byte[] fdsbios = null) //8KB prg can't be stored in iNES format, which counts 16KB prg banks. //so a correct hash will include only 8KB. LoadWriteLine("Since this rom has a 16 KB PRG, we'll hash it as 8KB too for bootgod's DB:"); - var msTemp = new MemoryStream(); + MemoryStream msTemp = new(); msTemp.Write(file, 16, 8 * 1024); //add prg if (file.Length >= (16 * 1024 + iNesHeaderInfo.ChrSize * 1024 + 16)) { @@ -486,8 +485,8 @@ public void Init(GameInfo gameInfo, byte[] rom, byte[] fdsbios = null) Console.WriteLine("WARNING: 16kb PRG iNES header but unable to parse"); } msTemp.Flush(); - var bytes = msTemp.ToArray(); - var hash = SHA1Checksum.ComputePrefixedHex(bytes); + byte[] bytes = msTemp.ToArray(); + string hash = SHA1Checksum.ComputePrefixedHex(bytes); LoadWriteLine(" PRG (8KB) + CHR hash: {0}", hash); hash_sha1_several.Add(hash); hash = MD5Checksum.ComputePrefixedHex(bytes); @@ -499,8 +498,7 @@ public void Init(GameInfo gameInfo, byte[] rom, byte[] fdsbios = null) if (USE_DATABASE) { if (hash_md5 != null) choice = IdentifyFromGameDB(hash_md5); - if (choice == null) - choice = IdentifyFromGameDB(hash_sha1); + choice ??= IdentifyFromGameDB(hash_sha1); if (choice == null) LoadWriteLine("Could not locate game in bizhawk gamedb"); else @@ -595,7 +593,7 @@ public void Init(GameInfo gameInfo, byte[] rom, byte[] fdsbios = null) } } - game_name = choice.Name; + GameName = choice.Name; //find a INESBoard to handle this if (choice != null) @@ -610,7 +608,7 @@ public void Init(GameInfo gameInfo, byte[] rom, byte[] fdsbios = null) LoadWriteLine("Final game detection results:"); LoadWriteLine(choice); - LoadWriteLine("\"" + game_name + "\""); + LoadWriteLine("\"" + GameName + "\""); LoadWriteLine("Implemented by: class " + boardType.Name); if (choice.Bad) { @@ -657,7 +655,7 @@ public void Init(GameInfo gameInfo, byte[] rom, byte[] fdsbios = null) //create the board's rom and vrom if (iNesHeaderInfo != null) { - using var ms = new MemoryStream(file, false); + using MemoryStream ms = new(file, false); ms.Seek(16, SeekOrigin.Begin); // ines header //pluck the necessary bytes out of the file if (iNesHeaderInfo.TrainerSize != 0) @@ -688,7 +686,7 @@ public void Init(GameInfo gameInfo, byte[] rom, byte[] fdsbios = null) else { // we should only get here for boards with no header - var ms = new MemoryStream(file, false); + MemoryStream ms = new(file, false); ms.Seek(0, SeekOrigin.Begin); Board.Rom = new byte[choice.PrgSize * 1024]; @@ -720,8 +718,8 @@ public void Init(GameInfo gameInfo, byte[] rom, byte[] fdsbios = null) // set up display type - NESSyncSettings.Region fromrom = DetectRegion(cart.System); - NESSyncSettings.Region fromsettings = SyncSettings.RegionOverride; + var fromrom = DetectRegion(cart.System); + var fromsettings = SyncSettings.RegionOverride; if (fromsettings != NESSyncSettings.Region.Default) { @@ -729,14 +727,14 @@ public void Init(GameInfo gameInfo, byte[] rom, byte[] fdsbios = null) fromrom = fromsettings; } - _display_type = fromrom switch + Region = fromrom switch { NESSyncSettings.Region.Dendy => DisplayType.Dendy, NESSyncSettings.Region.NTSC => DisplayType.NTSC, NESSyncSettings.Region.PAL => DisplayType.PAL, _ => DisplayType.NTSC }; - Console.WriteLine("Using NES system region of {0}", _display_type); + Console.WriteLine("Using NES system region of {0}", Region); HardReset(); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NESControllers.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NESControllers.cs index 1a6870de566..4a28963e7d6 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NESControllers.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NESControllers.cs @@ -25,7 +25,7 @@ namespace BizHawk.Emulation.Cores.Nintendo.NES /// /// stores information about the strobe lines controlled by $4016 /// - public struct StrobeInfo + public readonly struct StrobeInfo { /// /// the current value of $4016.0; strobes regular controller ports @@ -171,15 +171,9 @@ public void Strobe(StrobeInfo s, IController c) _right.Strobe(s, _rightU.UnMerge(c)); } - public byte ReadA(IController c) - { - return (byte)(_left.Read(_leftU.UnMerge(c)) & 0x19); - } + public byte ReadA(IController c) => (byte)(_left.Read(_leftU.UnMerge(c)) & 0x19); - public byte ReadB(IController c) - { - return (byte)(_right.Read(_rightU.UnMerge(c)) & 0x19); - } + public byte ReadB(IController c) => (byte)(_right.Read(_rightU.UnMerge(c)) & 0x19); public void SyncState(Serializer ser) { @@ -200,10 +194,7 @@ public void Strobe(StrobeInfo s, IController c) { } - public byte Read(IController c) - { - return 0; - } + public byte Read(IController c) => 0; public void SyncState(Serializer ser) { @@ -238,7 +229,7 @@ public ControllerNES() } - private readonly Dictionary _buttonOrdinals = new Dictionary + private readonly Dictionary _buttonOrdinals = new() { { "0Up", 1 }, { "0Down", 2 }, @@ -269,10 +260,7 @@ public ControllerNES(bool famicomP2) // 1. when OUT0 goes low, to get the last set // 2. when even reading with OUT0 high, since new data for controller is always loading - private void Latch(IController c) - { - _latchedValue = SerialUtil.Latch(_famicomP2Hack ? FamicomP2Buttons : Buttons, c); - } + private void Latch(IController c) => _latchedValue = SerialUtil.Latch(_famicomP2Hack ? FamicomP2Buttons : Buttons, c); public void Strobe(StrobeInfo s, IController c) { @@ -320,10 +308,7 @@ public class ControllerSNES : INesPort // 1. when OUT0 goes low, to get the last set // 2. when even reading with OUT0 high, since new data for controller is always loading - private void Latch(IController c) - { - _latchedValue = SerialUtil.Latch(Buttons, c); - } + private void Latch(IController c) => _latchedValue = SerialUtil.Latch(Buttons, c); public void Strobe(StrobeInfo s, IController c) { @@ -539,15 +524,9 @@ public void SyncState(Serializer ser) } // famicom expansion hookups - public byte ReadA(IController c) - { - return 0; - } + public byte ReadA(IController c) => 0; - public byte ReadB(IController c) - { - return Read(c); - } + public byte ReadB(IController c) => Read(c); } public class VSZapper : INesPort, IZapper @@ -602,15 +581,9 @@ public void SyncState(Serializer ser) } // famicom expansion hookups - public byte ReadA(IController c) - { - return 0; - } + public byte ReadA(IController c) => 0; - public byte ReadB(IController c) - { - return Read(c); - } + public byte ReadB(IController c) => Read(c); } public class FamicomDeck : IControllerDeck @@ -707,10 +680,7 @@ public void Strobe(StrobeInfo s, IController c) } } - public byte ReadA(IController c) - { - return c.IsPressed("0Fire") ? (byte)0x02 : (byte)0x00; - } + public byte ReadA(IController c) => c.IsPressed("0Fire") ? (byte)0x02 : (byte)0x00; public byte ReadB(IController c) { @@ -841,10 +811,7 @@ public void Strobe(StrobeInfo s, IController c) _row = 0; } - public byte ReadA(IController c) - { - return 0; - } + public byte ReadA(IController c) => 0; public byte ReadB(IController c) { @@ -970,10 +937,7 @@ public void Strobe(StrobeInfo s, IController c) _shiftidx++; } - public byte ReadA(IController c) - { - return 0; - } + public byte ReadA(IController c) => 0; public byte ReadB(IController c) { @@ -1005,15 +969,9 @@ public void Strobe(StrobeInfo s, IController c) { } - public byte ReadA(IController c) - { - return 0; - } + public byte ReadA(IController c) => 0; - public byte ReadB(IController c) - { - return 0; - } + public byte ReadB(IController c) => 0; public void SyncState(Serializer ser) { @@ -1057,14 +1015,8 @@ static NESControlSettings() NesPortDevices = Implementors(); } - public static IList GetFamicomExpansionValues() - { - return new List(FamicomExpansions.Keys).AsReadOnly(); - } - public static IList GetNesPortValues() - { - return new List(NesPortDevices.Keys).AsReadOnly(); - } + public static IList GetFamicomExpansionValues() => new List(FamicomExpansions.Keys).AsReadOnly(); + public static IList GetNesPortValues() => new List(NesPortDevices.Keys).AsReadOnly(); [JsonIgnore] private bool _Famicom; @@ -1121,15 +1073,9 @@ public NESControlSettings() NesRightPort = nameof(UnpluggedNES); } - public static bool NeedsReboot(NESControlSettings x, NESControlSettings y) - { - return !DeepEquality.DeepEquals(x, y); - } + public static bool NeedsReboot(NESControlSettings x, NESControlSettings y) => !DeepEquality.DeepEquals(x, y); - public NESControlSettings Clone() - { - return (NESControlSettings)MemberwiseClone(); - } + public NESControlSettings Clone() => (NESControlSettings)MemberwiseClone(); public IControllerDeck Instantiate(LightgunDelegate ppuCallback) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NSFFormat.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NSFFormat.cs index b975a2b3f8f..5f0043804a4 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NSFFormat.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NSFFormat.cs @@ -52,8 +52,8 @@ public void WrapByteArray(byte[] data) { NSFData = data; - var ms = new MemoryStream(data); - var br = new BinaryReader(ms); + MemoryStream ms = new(data); + BinaryReader br = new(ms); br.BaseStream.Position += 5; Version = br.ReadByte(); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/PPU.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/PPU.cs index d70f517d6b8..291c1dabf23 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/PPU.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/PPU.cs @@ -97,13 +97,7 @@ public class DebugCallback 50, 63, 18, 13, 52, 52, 63, 50, 0, 45, 35, 52, 44, 48, 49, 14, }; - private int[] _currentLuma = PaletteLumaNES; - - public int[] CurrentLuma - { - get => _currentLuma; - set => _currentLuma = value; - } + public int[] CurrentLuma { get; set; } = PaletteLumaNES; // true = light sensed public bool LightGunCallback(int x, int y) @@ -139,7 +133,7 @@ public bool LightGunCallback(int x, int y) palcolor = (short)(s & 0x3F); intensity = (short)((s >> 6) & 0x7); - sum += _currentLuma[palcolor]; + sum += CurrentLuma[palcolor]; i++; if (i > xmax) @@ -182,10 +176,7 @@ public byte ppubus_read(int addr, bool ppu, bool addr_ppu) } //debug tools peek into the ppu through this - public byte ppubus_peek(int addr) - { - return nes.Board.PeekPPU(addr); - } + public byte ppubus_peek(int addr) => nes.Board.PeekPPU(addr); public const int PPU_PHASE_VBL = 0; public const int PPU_PHASE_BG = 1; @@ -213,12 +204,10 @@ public PPU(NES nes) Reset(); } - public void NESSoftReset() - { + public void NESSoftReset() => //this hasn't been brought up to date since NEShawk was first made. //in particular http://wiki.nesdev.com/w/index.php/PPU_power_up_state should be studied, but theres no use til theres test cases Reset(); - } //state public int ppudead; //measured in frames diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/PPU.regs.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/PPU.regs.cs index b27632148ea..2ea427c84e4 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/PPU.regs.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/PPU.regs.cs @@ -58,7 +58,7 @@ public byte Value public struct PPUSTATUS { public int sl; - public bool rendering => sl >= 0 && sl < 241; + public readonly bool rendering => sl is >= 0 and < 241; public int cycle; } @@ -103,7 +103,7 @@ public void SyncState(Serializer ser) //cached state data. these are always reset at the beginning of a frame and don't need saving //but just to be safe, we're gonna save it - public PPUSTATUS status = new PPUSTATUS(); + public PPUSTATUS status = new(); //public int ComputeIndex() //{ @@ -186,16 +186,10 @@ public void increment_vs() } [MethodImpl(MethodImplOptions.AggressiveInlining)] - public int get_ntread() - { - return 0x2000 | (v << 0xB) | (h << 0xA) | (vt << 5) | ht; - } + public int get_ntread() => 0x2000 | (v << 0xB) | (h << 0xA) | (vt << 5) | ht; [MethodImpl(MethodImplOptions.AggressiveInlining)] - public int get_2007access() - { - return ((fv & 3) << 0xC) | (v << 0xB) | (h << 0xA) | (vt << 5) | ht; - } + public int get_2007access() => ((fv & 3) << 0xC) | (v << 0xB) | (h << 0xA) | (vt << 5) | ht; //The PPU has an internal 4-position, 2-bit shifter, which it uses for //obtaining the 2-bit palette select data during an attribute table byte @@ -204,10 +198,7 @@ public int get_2007access() //apply to the data read from the attribute data (a is always 0). This is why //you only see bits 0 and 1 used off the read attribute data in the diagram. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public int get_atread() - { - return 0x2000 | (v << 0xB) | (h << 0xA) | 0x3C0 | ((vt & 0x1C) << 1) | ((ht & 0x1C) >> 2); - } + public int get_atread() => 0x2000 | (v << 0xB) | (h << 0xA) | 0x3C0 | ((vt & 0x1C) << 1) | ((ht & 0x1C) >> 2); public void increment2007(bool rendering, bool by32) { @@ -325,8 +316,8 @@ private void write_2000(byte value) reg_2000.Value = value; } - private byte read_2000() { return ppu_open_bus; } - private byte peek_2000() { return ppu_open_bus; } + private byte read_2000() => ppu_open_bus; + private byte peek_2000() => ppu_open_bus; //PPU MASK (write) private void write_2001(byte value) @@ -336,8 +327,8 @@ private void write_2001(byte value) install_2001 = 2; } - private byte read_2001() {return ppu_open_bus; } - private byte peek_2001() {return ppu_open_bus; } + private byte read_2001() => ppu_open_bus; + private byte peek_2001() => ppu_open_bus; //PPU STATUS (read) private void write_2002(byte value) { } @@ -424,8 +415,8 @@ private void write_2003(int addr, byte value) } } - private byte read_2003() { return ppu_open_bus; } - private byte peek_2003() { return ppu_open_bus; } + private byte read_2003() => ppu_open_bus; + private byte peek_2003() => ppu_open_bus; //OAM DATA (write) private void write_2004(byte value) @@ -499,7 +490,7 @@ private byte read_2004() return ret; } - private byte peek_2004() { return OAM[reg_2003]; } + private byte peek_2004() => OAM[reg_2003]; //SCROLL (write) private void write_2005(byte value) @@ -519,8 +510,8 @@ private void write_2005(byte value) vtoggle ^= true; } - private byte read_2005() { return ppu_open_bus; } - private byte peek_2005() { return ppu_open_bus; } + private byte read_2005() => ppu_open_bus; + private byte peek_2005() => ppu_open_bus; //VRAM address register (write) private void write_2006(byte value) @@ -550,8 +541,8 @@ private void write_2006(byte value) vtoggle ^= true; } - private byte read_2006() { return ppu_open_bus; } - private byte peek_2006() { return ppu_open_bus; } + private byte read_2006() => ppu_open_bus; + private byte peek_2006() => ppu_open_bus; //VRAM data register (r/w) private void write_2007(byte value) @@ -706,12 +697,18 @@ public byte ReadReg(int addr) public byte PeekReg(int addr) { - switch (addr) - { - case 0: return peek_2000(); case 1: return peek_2001(); case 2: return peek_2002(); case 3: return peek_2003(); - case 4: return peek_2004(); case 5: return peek_2005(); case 6: return peek_2006(); case 7: return peek_2007(); - default: throw new InvalidOperationException(); - } + return addr switch + { + 0 => peek_2000(), + 1 => peek_2001(), + 2 => peek_2002(), + 3 => peek_2003(), + 4 => peek_2004(), + 5 => peek_2005(), + 6 => peek_2006(), + 7 => peek_2007(), + _ => throw new InvalidOperationException(), + }; } public void WriteReg(int addr, byte value) diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/PPU.run.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/PPU.run.cs index 5505ef1a7df..020060c149d 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/PPU.run.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/PPU.run.cs @@ -320,7 +320,7 @@ public void TickPPU_active() spr_true_count++; soam_m_index++; } - else if (spr_true_count > 0 && spr_true_count < 4) + else if (spr_true_count is > 0 and < 4) { soam[soam_index * 4 + soam_m_index] = read_value; @@ -359,7 +359,7 @@ public void TickPPU_active() spr_true_count++; soam_m_index++; } - else if (spr_true_count > 0 && spr_true_count < 4) + else if (spr_true_count is > 0 and < 4) { soam_m_index++; @@ -907,7 +907,7 @@ public void TickPPU_active() } int temp_x = t_oam[s].oam_x; - if ((ppur.status.sl != 0) && (ppur.status.sl != 240)) + if (ppur.status.sl is not 0 and not 240) { for (int i = 0; (temp_x + i) < 256 && i < 8; i++) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Unif.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Unif.cs index a4e14129d57..1196dfda3ba 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Unif.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Unif.cs @@ -20,7 +20,7 @@ public class Unif private void TryAdd(Stream s, string key) { - if (!Chunks.TryGetValue(key, out var data)) + if (!Chunks.TryGetValue(key, out byte[] data)) { return; } @@ -30,7 +30,7 @@ private void TryAdd(Stream s, string key) public Unif(Stream s) { - var br = new BinaryReader(s, Encoding.ASCII); + BinaryReader br = new(s, Encoding.ASCII); if (!Encoding.ASCII.GetBytes("UNIF") .SequenceEqual(br.ReadBytes(4))) @@ -51,8 +51,8 @@ public Unif(Stream s) Chunks.Add(chunkId, chunkData); } - var prgs = new MemoryStream(); - var chrs = new MemoryStream(); + MemoryStream prgs = new(); + MemoryStream chrs = new(); for (int i = 0; i < 16; i++) { TryAdd(prgs, $"PRG{i:X1}"); @@ -67,7 +67,7 @@ public Unif(Stream s) Cart.PrgSize = (short)(Prg.Length / 1024); Cart.ChrSize = (short)(Chr.Length / 1024); - if (Chunks.TryGetValue("MIRR", out var tmp)) + if (Chunks.TryGetValue("MIRR", out byte[] tmp)) { switch (tmp[0]) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/LibQuickNES.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/LibQuickNES.cs index f673ed5d45c..74b26da753a 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/LibQuickNES.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/LibQuickNES.cs @@ -234,9 +234,9 @@ public static void ThrowStringError(IntPtr p) if (p == IntPtr.Zero) return; string s = Marshal.PtrToStringAnsi(p); - if (s == "Unsupported mapper" - || s == "Not an iNES file" // Not worth making a new exception for the iNES error, they ultimately are the same problem - || s == " truncated file" // This is a garbage rom not worth anyone's time but at least NesHawk handles these better, and these occur before the core has a chance to assess an unsupported mapper + if (s is "Unsupported mapper" + or "Not an iNES file" // Not worth making a new exception for the iNES error, they ultimately are the same problem + or " truncated file" // This is a garbage rom not worth anyone's time but at least NesHawk handles these better, and these occur before the core has a chance to assess an unsupported mapper ) { throw new Common.UnsupportedGameException("Quicknes unsupported mapper"); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/Nes_NTSC_Colors.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/Nes_NTSC_Colors.cs index c84eec5eee4..384c3de11c1 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/Nes_NTSC_Colors.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/Nes_NTSC_Colors.cs @@ -55,7 +55,7 @@ public static void Emphasis(byte[] inp, byte[] outp, int entrynum) float g = to_float * inp[1]; float b = to_float * inp[2]; - RGB_TO_YIQ(r, g, b, out float y, out var i, out var q); + RGB_TO_YIQ(r, g, b, out float y, out float i, out float q); if (tint > 0 && color < 0x0d) { @@ -71,7 +71,7 @@ public static void Emphasis(byte[] inp, byte[] outp, int entrynum) int tint_color = tints[tint]; float sat = hi * (0.5f - atten_mul * 0.5f) + atten_sub * 0.5f; y -= sat * 0.5f; - if (tint >= 3 && tint != 4) + if (tint is >= 3 and not 4) { /* combined tint bits */ sat *= 0.6f; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.IDebuggable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.IDebuggable.cs index c102a3b1145..2724f3cac7d 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.IDebuggable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.IDebuggable.cs @@ -10,7 +10,7 @@ public partial class QuickNES : IDebuggable public IDictionary GetCpuFlagsAndRegisters() { int[] regs = new int[6]; - var ret = new Dictionary(); + Dictionary ret = new(); QN.qn_get_cpuregs(Context, regs); ret["A"] = (byte)regs[0]; ret["X"] = (byte)regs[1]; @@ -22,15 +22,12 @@ public IDictionary GetCpuFlagsAndRegisters() } [FeatureNotImplemented] - public void SetCpuRegister(string register, int value) - { - throw new NotImplementedException(); - } + public void SetCpuRegister(string register, int value) => throw new NotImplementedException(); - public bool CanStep(StepType type) { return false; } + public bool CanStep(StepType type) => false; [FeatureNotImplemented] - public void Step(StepType type) { throw new NotImplementedException(); } + public void Step(StepType type) => throw new NotImplementedException(); public IMemoryCallbackSystem MemoryCallbacks { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.IDisassembler.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.IDisassembler.cs index 5599675375a..f789560b4a8 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.IDisassembler.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.IDisassembler.cs @@ -21,9 +21,6 @@ public IEnumerable AvailableCpus get { yield return "6502"; } } - public string Disassemble(MemoryDomain m, uint addr, out int length) - { - return MOS6502X.Disassemble((ushort)addr, out length, (a) => m.PeekByte(a)); - } + public string Disassemble(MemoryDomain m, uint addr, out int length) => MOS6502X.Disassemble((ushort)addr, out length, (a) => m.PeekByte(a)); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.IMemoryDomains.cs index 8f1fa83be7d..61b0e28aee3 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.IMemoryDomains.cs @@ -10,13 +10,13 @@ public partial class QuickNES { private void InitMemoryDomains() { - List mm = new List(); + List mm = new(); for (int i = 0; ; i++) { - IntPtr data = IntPtr.Zero; + var data = IntPtr.Zero; int size = 0; bool writable = false; - IntPtr name = IntPtr.Zero; + var name = IntPtr.Zero; if (!QN.qn_get_memory_area(Context, i, ref data, ref size, ref writable, ref name)) break; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.INESPPUViewable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.INESPPUViewable.cs index f81083570f3..6d9312fa475 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.INESPPUViewable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.INESPPUViewable.cs @@ -42,47 +42,23 @@ public byte[] GetOam() return oambuf; } - public byte PeekPPU(int addr) - { - return QN.qn_peek_ppu(Context, addr); - } + public byte PeekPPU(int addr) => QN.qn_peek_ppu(Context, addr); // we don't use quicknes's MMC5 at all, so these three methods are just stubs - public byte[] GetExTiles() - { - throw new InvalidOperationException(); - } + public byte[] GetExTiles() => throw new InvalidOperationException(); public bool ExActive => false; - public byte[] GetExRam() - { - throw new InvalidOperationException(); - } + public byte[] GetExRam() => throw new InvalidOperationException(); - public MemoryDomain GetCHRROM() - { - return _memoryDomains["CHR VROM"]; - } + public MemoryDomain GetCHRROM() => _memoryDomains["CHR VROM"]; - public void InstallCallback1(Action cb, int sl) - { - _callBack1 = cb; - } + public void InstallCallback1(Action cb, int sl) => _callBack1 = cb; - public void InstallCallback2(Action cb, int sl) - { - _callBack2 = cb; - } + public void InstallCallback2(Action cb, int sl) => _callBack2 = cb; - public void RemoveCallback1() - { - _callBack1 = null; - } + public void RemoveCallback1() => _callBack1 = null; - public void RemoveCallback2() - { - _callBack2 = null; - } + public void RemoveCallback2() => _callBack2 = null; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.ISaveRam.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.ISaveRam.cs index d312ca84565..eae8bbcfaf2 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.ISaveRam.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.ISaveRam.cs @@ -10,10 +10,7 @@ public byte[] CloneSaveRam() return (byte[])_saveRamBuff.Clone(); } - public void StoreSaveRam(byte[] data) - { - LibQuickNES.ThrowStringError(QN.qn_battery_ram_load(Context, data, data.Length)); - } + public void StoreSaveRam(byte[] data) => LibQuickNES.ThrowStringError(QN.qn_battery_ram_load(Context, data, data.Length)); public bool SaveRamModified => QN.qn_has_battery_ram(Context); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.ISettable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.ISettable.cs index 8e617aaaba2..a19e04bf7ed 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.ISettable.cs @@ -11,15 +11,9 @@ namespace BizHawk.Emulation.Cores.Consoles.Nintendo.QuickNES { public partial class QuickNES : ISettable { - public QuickNESSettings GetSettings() - { - return _settings.Clone(); - } + public QuickNESSettings GetSettings() => _settings.Clone(); - public QuickNESSyncSettings GetSyncSettings() - { - return _syncSettingsNext.Clone(); - } + public QuickNESSyncSettings GetSyncSettings() => _syncSettingsNext.Clone(); public PutSettingsDirtyBits PutSettings(QuickNESSettings o) { @@ -92,7 +86,7 @@ public byte[] Palette public QuickNESSettings Clone() { - var ret = (QuickNESSettings)MemberwiseClone(); + QuickNESSettings ret = (QuickNESSettings)MemberwiseClone(); ret._Palette = (byte[])_Palette.Clone(); return ret; } @@ -138,16 +132,13 @@ public void SetNesHawkPalette(byte[,] pal) private static byte[] GetDefaultColors() { - IntPtr src = QN.qn_get_default_colors(); + var src = QN.qn_get_default_colors(); byte[] ret = new byte[1536]; Marshal.Copy(src, ret, 0, 1536); return ret; } - public void SetDefaultColors() - { - _Palette = GetDefaultColors(); - } + public void SetDefaultColors() => _Palette = GetDefaultColors(); } public class QuickNESSyncSettings @@ -167,17 +158,12 @@ public QuickNESSyncSettings() SettingsUtil.SetDefaultValues(this); } - public QuickNESSyncSettings Clone() - { - return (QuickNESSyncSettings)MemberwiseClone(); - } + public QuickNESSyncSettings Clone() => (QuickNESSyncSettings)MemberwiseClone(); - public static bool NeedsReboot(QuickNESSyncSettings x, QuickNESSyncSettings y) - { + public static bool NeedsReboot(QuickNESSyncSettings x, QuickNESSyncSettings y) => // the core can handle dynamic plugging and unplugging, but that changes // the ControllerDefinition, and we're not ready for that - return !DeepEquality.DeepEquals(x, y); - } + !DeepEquality.DeepEquals(x, y); } } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.ISoundProvider.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.ISoundProvider.cs index 643fe0e7c6a..30662920fcc 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.ISoundProvider.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.ISoundProvider.cs @@ -32,15 +32,9 @@ public void SetSyncMode(SyncSoundMode mode) public SyncSoundMode SyncMode => SyncSoundMode.Sync; - public void GetSamplesAsync(short[] samples) - { - throw new InvalidOperationException("Async mode is not supported."); - } + public void GetSamplesAsync(short[] samples) => throw new InvalidOperationException("Async mode is not supported."); - private void InitAudio() - { - LibQuickNES.ThrowStringError(QN.qn_set_sample_rate(Context, 44100)); - } + private void InitAudio() => LibQuickNES.ThrowStringError(QN.qn_set_sample_rate(Context, 44100)); private void DrainAudio() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.IVideoProvider.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.IVideoProvider.cs index 768011802dc..03e2d738f30 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.IVideoProvider.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.IVideoProvider.cs @@ -42,9 +42,6 @@ private void CalculatePalette() } } - private void Blit() - { - QN.qn_blit(Context, _videoOutput, _videoPalette, _cropLeft, _cropTop, _cropRight, _cropBottom); - } + private void Blit() => QN.qn_blit(Context, _videoOutput, _videoPalette, _cropLeft, _cropTop, _cropRight, _cropBottom); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.cs index c75bd9348f5..d859bf5bdd7 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/QuickNES/QuickNES.cs @@ -20,7 +20,7 @@ public sealed partial class QuickNES : IEmulator, IVideoProvider, ISoundProvider { static QuickNES() { - var resolver = new DynamicLibraryImportResolver( + DynamicLibraryImportResolver resolver = new( $"libquicknes{(OSTailoredCode.IsUnixHost ? ".dll.so.0.7.0" : ".dll")}", hasLimitedLifetime: false); QN = BizInvoker.GetInvoker(resolver, CallingConventionAdapters.Native); QN.qn_setup_mappers(); @@ -88,7 +88,7 @@ private void SetControllerDefinition() ControllerDefinition = def.MakeImmutable(); } - private struct PadEnt + private readonly struct PadEnt { public readonly string Name; public readonly int Mask; @@ -149,7 +149,7 @@ public bool FrameAdvance(IController controller, bool render, bool rendersound = if (controller.IsPressed("Reset")) QN.qn_reset(Context, false); - SetPads(controller, out var j1, out var j2); + SetPads(controller, out int j1, out int j2); QN.qn_set_tracecb(Context, Tracer.IsEnabled() ? _traceCb : null); @@ -194,14 +194,14 @@ private void ComputeBootGod() var chrrom = _memoryDomains["CHR VROM"]; var prgrom = _memoryDomains["PRG ROM"]!; - var ms = new MemoryStream(); + MemoryStream ms = new(); for (int i = 0; i < prgrom.Size; i++) ms.WriteByte(prgrom.PeekByte(i)); if (chrrom != null) for (int i = 0; i < chrrom.Size; i++) ms.WriteByte(chrrom.PeekByte(i)); - var sha1 = SHA1Checksum.ComputeDigestHex(ms.ToArray()); + string sha1 = SHA1Checksum.ComputeDigestHex(ms.ToArray()); Console.WriteLine("Hash for BootGod: {0}", sha1); // Bail out on ROM's known to not be playable by this core @@ -256,7 +256,7 @@ private void CheckDisposed() // we need to do this from the raw file since QuickNES hasn't had time to process it yet. private byte[] FixInesHeader(byte[] file) { - var sha1 = SHA1Checksum.ComputeDigestHex(file); + string sha1 = SHA1Checksum.ComputeDigestHex(file); bool didSomething = false; Console.WriteLine(sha1); @@ -276,7 +276,7 @@ private byte[] FixInesHeader(byte[] file) } // These games are known to not work in quicknes but quicknes thinks it can run them, bail out if one of these is loaded - private static readonly HashSet HashBlackList = new HashSet + private static readonly HashSet HashBlackList = new() { "E39CA4477D3B96E1CE3A1C61D8055187EA5F1784", // Bill and Ted's Excellent Adventure "E8BC7E6BAE7032D571152F6834516535C34C68F0", // Bill and Ted's Excellent Adventure bad dump diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesApi.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesApi.cs index 5d1cdd0d3e0..a1ec07967bb 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesApi.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesApi.cs @@ -38,20 +38,14 @@ static LibsnesApi() private CoreImpl _core; private bool _disposed; private CommStruct* _comm; - private readonly Dictionary _sharedMemoryBlocks = new Dictionary(); + private readonly Dictionary _sharedMemoryBlocks = new(); private bool _sealed = false; - public void Enter() - { - _exe.Enter(); - } + public void Enter() => _exe.Enter(); - public void Exit() - { - _exe.Exit(); - } + public void Exit() => _exe.Exit(); - private readonly List _readonlyFiles = new List(); + private readonly List _readonlyFiles = new(); public void AddReadonlyFile(byte[] data, string name) { @@ -187,12 +181,12 @@ public enum eCDLog_Flags private snes_path_request_t pathRequest; private snes_trace_t traceCallback; - public void QUERY_set_video_refresh(snes_video_refresh_t video_refresh) { this.video_refresh = video_refresh; } + public void QUERY_set_video_refresh(snes_video_refresh_t video_refresh) => this.video_refresh = video_refresh; // not used?? - public void QUERY_set_input_poll(snes_input_poll_t input_poll) { this.input_poll = input_poll; } - public void QUERY_set_input_state(snes_input_state_t input_state) { this.input_state = input_state; } - public void QUERY_set_input_notify(snes_input_notify_t input_notify) { this.input_notify = input_notify; } - public void QUERY_set_path_request(snes_path_request_t pathRequest) { this.pathRequest = pathRequest; } + public void QUERY_set_input_poll(snes_input_poll_t input_poll) => this.input_poll = input_poll; + public void QUERY_set_input_state(snes_input_state_t input_state) => this.input_state = input_state; + public void QUERY_set_input_notify(snes_input_notify_t input_notify) => this.input_notify = input_notify; + public void QUERY_set_path_request(snes_path_request_t pathRequest) => this.pathRequest = pathRequest; public delegate void snes_video_refresh_t(int* data, int width, int height); public delegate void snes_input_poll_t(); @@ -223,64 +217,52 @@ public struct LayerEnables private byte _Obj_Prio0, _Obj_Prio1, _Obj_Prio2, _Obj_Prio3; public bool BG1_Prio0 - { - get => _BG1_Prio0 != 0; + { readonly get => _BG1_Prio0 != 0; set => _BG1_Prio0 = (byte)(value ? 1 : 0); } public bool BG1_Prio1 - { - get => _BG1_Prio1 != 0; + { readonly get => _BG1_Prio1 != 0; set => _BG1_Prio1 = (byte)(value ? 1 : 0); } public bool BG2_Prio0 - { - get => _BG2_Prio0 != 0; + { readonly get => _BG2_Prio0 != 0; set => _BG2_Prio0 = (byte)(value ? 1 : 0); } public bool BG2_Prio1 - { - get => _BG2_Prio1 != 0; + { readonly get => _BG2_Prio1 != 0; set => _BG2_Prio1 = (byte)(value ? 1 : 0); } public bool BG3_Prio0 - { - get => _BG3_Prio0 != 0; + { readonly get => _BG3_Prio0 != 0; set => _BG3_Prio0 = (byte)(value ? 1 : 0); } public bool BG3_Prio1 - { - get => _BG3_Prio1 != 0; + { readonly get => _BG3_Prio1 != 0; set => _BG3_Prio1 = (byte)(value ? 1 : 0); } public bool BG4_Prio0 - { - get => _BG4_Prio0 != 0; + { readonly get => _BG4_Prio0 != 0; set => _BG4_Prio0 = (byte)(value ? 1 : 0); } public bool BG4_Prio1 - { - get => _BG4_Prio1 != 0; + { readonly get => _BG4_Prio1 != 0; set => _BG4_Prio1 = (byte)(value ? 1 : 0); } public bool Obj_Prio0 - { - get => _Obj_Prio0 != 0; + { readonly get => _Obj_Prio0 != 0; set => _Obj_Prio0 = (byte)(value ? 1 : 0); } public bool Obj_Prio1 - { - get => _Obj_Prio1 != 0; + { readonly get => _Obj_Prio1 != 0; set => _Obj_Prio1 = (byte)(value ? 1 : 0); } public bool Obj_Prio2 - { - get => _Obj_Prio2 != 0; + { readonly get => _Obj_Prio2 != 0; set => _Obj_Prio2 = (byte)(value ? 1 : 0); } public bool Obj_Prio3 - { - get => _Obj_Prio3 != 0; + { readonly get => _Obj_Prio3 != 0; set => _Obj_Prio3 = (byte)(value ? 1 : 0); } } @@ -353,15 +335,15 @@ private struct CommStruct [FieldOffset(360)] public SNES_MAPPER mapper; - [FieldOffset(364)] private uint BLANK0; + [FieldOffset(364)] private readonly uint BLANK0; //utilities //TODO: make internal, wrap on the API instead of the comm - public string GetAscii() => _getAscii(str); - public bool GetBool() { return value != 0; } + public readonly string GetAscii() => _getAscii(str); + public readonly bool GetBool() => value != 0; - private string _getAscii(sbyte* ptr) + private readonly string _getAscii(sbyte* ptr) { int len = 0; sbyte* junko = ptr; @@ -421,7 +403,7 @@ public void Seal() _core.DllInit(); _exe.Seal(); _sealed = true; - foreach (var s in _readonlyFiles) + foreach (string s in _readonlyFiles) { _exe.RemoveReadonlyFile(s); } @@ -430,10 +412,7 @@ public void Seal() public bool AvoidRewind => false; - public void SaveStateBinary(BinaryWriter writer) - { - _exe.SaveStateBinary(writer); - } + public void SaveStateBinary(BinaryWriter writer) => _exe.SaveStateBinary(writer); public void LoadStateBinary(BinaryReader reader) { @@ -441,9 +420,6 @@ public void LoadStateBinary(BinaryReader reader) _core.PostLoadState(); } - public MemoryDomain GetPagesDomain() - { - return _exe.GetPagesDomain(); - } + public MemoryDomain GetPagesDomain() => _exe.GetPagesDomain(); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesApi_QUERY.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesApi_QUERY.cs index d5f70386ba9..478f80284e6 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesApi_QUERY.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesApi_QUERY.cs @@ -118,10 +118,7 @@ public void QUERY_set_audio_sample(snes_audio_sample_t audio_sample) } } - public void QUERY_set_layer_enable() - { - _core.Message(eMessage.eMessage_QUERY_set_layer_enable); - } + public void QUERY_set_layer_enable() => _core.Message(eMessage.eMessage_QUERY_set_layer_enable); public void QUERY_set_backdropColor(int backdropColor) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesApi_SIG.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesApi_SIG.cs index 41c1918b8bc..5ca522e6445 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesApi_SIG.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesApi_SIG.cs @@ -45,11 +45,11 @@ private bool Handle_SIG(eMessage msg) if (audio_sample != null) { - var audiobuffer = (short*)_comm->ptr; + short* audiobuffer = (short*)_comm->ptr; for (uint i = 0; i < nsamples;) { - var left = audiobuffer[i++]; - var right = audiobuffer[i++]; + short left = audiobuffer[i++]; + short right = audiobuffer[i++]; audio_sample(left, right); } } @@ -74,9 +74,9 @@ private bool Handle_SIG(eMessage msg) case eMessage.eMessage_SIG_allocSharedMemory: { // NB: shared memory blocks are allocated on the unmanaged side - var name = _comm->GetAscii(); - var size = _comm->size; - var ptr = _comm->ptr; + string name = _comm->GetAscii(); + uint size = _comm->size; + void* ptr = _comm->ptr; if (_sharedMemoryBlocks.ContainsKey(name)) throw new InvalidOperationException("Re-defined a shared memory block. Check bsnes init/shutdown code. Block name: " + name); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesControllerDeck.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesControllerDeck.cs index 0c82bbb75df..9449f649eaa 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesControllerDeck.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesControllerDeck.cs @@ -23,28 +23,20 @@ public enum ControllerType private static ILibsnesController Factory(ControllerType t, LibsnesCore.SnesSyncSettings ss) { - switch (t) + return t switch { - case ControllerType.Unplugged: - return new SnesUnpluggedController(); - case ControllerType.Gamepad: - return new SnesController(); - case ControllerType.Multitap: - return new SnesMultitapController(); - case ControllerType.Payload: - return new SnesPayloadController(); - case ControllerType.Mouse: - return new SnesMouseController - { - LimitAnalogChangeSensitivity = ss.LimitAnalogChangeSensitivity - }; - case ControllerType.SuperScope: - return new SnesSuperScopeController(); - case ControllerType.Justifier: - return new SnesJustifierController(); - default: - throw new InvalidOperationException(); - } + ControllerType.Unplugged => new SnesUnpluggedController(), + ControllerType.Gamepad => new SnesController(), + ControllerType.Multitap => new SnesMultitapController(), + ControllerType.Payload => new SnesPayloadController(), + ControllerType.Mouse => new SnesMouseController + { + LimitAnalogChangeSensitivity = ss.LimitAnalogChangeSensitivity + }, + ControllerType.SuperScope => new SnesSuperScopeController(), + ControllerType.Justifier => new SnesJustifierController(), + _ => throw new InvalidOperationException(), + }; } private readonly ILibsnesController[] _ports; @@ -81,10 +73,7 @@ public void NativeInit(LibsnesApi api) } } - public short CoreInputState(IController controller, int port, int device, int index, int id) - { - return _ports[port].GetState(_mergers[port].UnMerge(controller), index, id); - } + public short CoreInputState(IController controller, int port, int device, int index, int id) => _ports[port].GetState(_mergers[port].UnMerge(controller), index, id); } internal static class SNESControllerDefExtensions @@ -142,7 +131,7 @@ public class SnesController : ILibsnesController private static int ButtonOrder(string btn) { - var order = new Dictionary + Dictionary order = new() { ["0Up"] = 0, ["0Down"] = 1, @@ -204,7 +193,7 @@ public class SnesMultitapController : ILibsnesController private static int ButtonOrder(string btn) { - var order = new Dictionary + Dictionary order = new() { ["Up"] = 0, ["Down"] = 1, @@ -264,10 +253,7 @@ public class SnesPayloadController : ILibsnesController public ControllerDefinition Definition { get; } = _definition; - public short GetState(IController controller, int index, int id) - { - return (short)(controller.IsPressed("0B" + (index << 4 & 16 | id)) ? 1 : 0); - } + public short GetState(IController controller, int index, int id) => (short)(controller.IsPressed("0B" + (index << 4 & 16 | id)) ? 1 : 0); } public class SnesUnpluggedController : ILibsnesController @@ -278,10 +264,7 @@ public class SnesUnpluggedController : ILibsnesController public ControllerDefinition Definition { get; } = _definition; - public short GetState(IController controller, int index, int id) - { - return 0; - } + public short GetState(IController controller, int index, int id) => 0; } public class SnesMouseController : ILibsnesController @@ -303,7 +286,7 @@ public short GetState(IController controller, int index, int id) default: return 0; case 0: - var x = controller.AxisValue("0Mouse X"); + int x = controller.AxisValue("0Mouse X"); if (LimitAnalogChangeSensitivity) { x = x.Clamp(-10, 10); @@ -311,7 +294,7 @@ public short GetState(IController controller, int index, int id) return (short)x; case 1: - var y = controller.AxisValue("0Mouse Y"); + int y = controller.AxisValue("0Mouse Y"); if (LimitAnalogChangeSensitivity) { y = y.Clamp(-10, 10); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.IDebuggable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.IDebuggable.cs index 6f95426cd23..60612dca21f 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.IDebuggable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.IDebuggable.cs @@ -44,23 +44,14 @@ public IDictionary GetCpuFlagsAndRegisters() } [FeatureNotImplemented] - public void SetCpuRegister(string register, int value) - { - throw new NotImplementedException(); - } + public void SetCpuRegister(string register, int value) => throw new NotImplementedException(); public IMemoryCallbackSystem MemoryCallbacks { get; } = new MemoryCallbackSystem(new[] { "System Bus" }); - public bool CanStep(StepType type) - { - return false; - } + public bool CanStep(StepType type) => false; [FeatureNotImplemented] - public void Step(StepType type) - { - throw new NotImplementedException(); - } + public void Step(StepType type) => throw new NotImplementedException(); [FeatureNotImplemented] public long TotalExecutedCycles => throw new NotImplementedException(); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.IEmulator.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.IEmulator.cs index 1e5c22a6558..35e9a228aaa 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.IEmulator.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.IEmulator.cs @@ -49,7 +49,7 @@ public bool FrameAdvance(IController controller, bool render, bool renderSound) Api.CMD_power(); } - var enables = new LibsnesApi.LayerEnables + LibsnesApi.LayerEnables enables = new() { BG1_Prio0 = _settings.ShowBG1_0, BG1_Prio1 = _settings.ShowBG1_1, @@ -71,7 +71,7 @@ public bool FrameAdvance(IController controller, bool render, bool renderSound) // apparently this is one frame? Api.CMD_run(); - _timeFrameCounter++; + Frame++; // once upon a time we forwarded messages from bsnes here, by checking for queued text messages, but I don't think it's needed any longer if (IsLagFrame) @@ -87,18 +87,14 @@ public bool FrameAdvance(IController controller, bool render, bool renderSound) return true; } - public int Frame - { - get => _timeFrameCounter; - private set => _timeFrameCounter = value; - } + public int Frame { get; private set; } public string SystemId { get; } public bool DeterministicEmulation => true; public void ResetCounters() { - _timeFrameCounter = 0; + Frame = 0; LagCount = 0; IsLagFrame = false; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.IMemoryDomains.cs index 52964b8af6e..03188514d83 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.IMemoryDomains.cs @@ -8,7 +8,7 @@ namespace BizHawk.Emulation.Cores.Nintendo.SNES { public partial class LibsnesCore { - private readonly List _memoryDomainList = new List(); + private readonly List _memoryDomainList = new(); private IMemoryDomains _memoryDomains; private LibsnesApi.SNES_MAPPER? _mapper; private LibsnesApi.SNES_REGION? _region; @@ -18,7 +18,7 @@ public partial class LibsnesCore { addr &= 0xffffff; int bank = addr >> 16; - if (bank == 0x7e || bank == 0x7f) + if (bank is 0x7e or 0x7f) { return addr & 0x1ffff; } @@ -65,7 +65,7 @@ private void SetupMemoryDomains(byte[] romData, byte[] sgbRomData) MakeMemoryDomain("SGB WRAM", LibsnesApi.SNES_MEMORY.SGB_WRAM, MemoryDomain.Endian.Little); //uhhh why can't this be done with MakeMemoryDomain? improve that. - var romDomain = new MemoryDomainByteArray("SGB CARTROM", MemoryDomain.Endian.Little, romData, true, 1); + MemoryDomainByteArray romDomain = new("SGB CARTROM", MemoryDomain.Endian.Little, romData, true, 1); _memoryDomainList.Add(romDomain); // the last 1 byte of this is special.. its an interrupt enable register, instead of ram. weird. maybe its actually ram and just getting specially used? @@ -92,7 +92,7 @@ private unsafe void MakeMemoryDomain(string name, LibsnesApi.SNES_MEMORY id, Mem byte* blockPtr = Api.QUERY_get_memory_data(id); - var md = new MemoryDomainIntPtrMonitor(name, MemoryDomain.Endian.Little, (IntPtr)blockPtr, size, + MemoryDomainIntPtrMonitor md = new(name, MemoryDomain.Endian.Little, (IntPtr)blockPtr, size, true, byteSize, Api); @@ -109,12 +109,12 @@ private unsafe void MakeFakeBus() byte* blockPtr = Api.QUERY_get_memory_data(LibsnesApi.SNES_MEMORY.WRAM); - var md = new MemoryDomainDelegate("System Bus", 0x1000000, MemoryDomain.Endian.Little, + MemoryDomainDelegate md = new("System Bus", 0x1000000, MemoryDomain.Endian.Little, addr => { using (Api.EnterExit()) { - var a = FakeBusMap((int)addr); + int? a = FakeBusMap((int)addr); if (a.HasValue) { return blockPtr[a.Value]; @@ -127,7 +127,7 @@ private unsafe void MakeFakeBus() { using (Api.EnterExit()) { - var a = FakeBusMap((int)addr); + int? a = FakeBusMap((int)addr); if (a.HasValue) blockPtr[a.Value] = val; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.ISaveRam.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.ISaveRam.cs index 3f89c642f0c..f1b34b4bc58 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.ISaveRam.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.ISaveRam.cs @@ -17,7 +17,7 @@ public byte[] CloneSaveRam() using (Api.EnterExit()) { byte* buf = Api.QUERY_get_memory_data(LibsnesApi.SNES_MEMORY.CARTRIDGE_RAM); - var size = Api.QUERY_get_memory_size(LibsnesApi.SNES_MEMORY.CARTRIDGE_RAM); + int size = Api.QUERY_get_memory_size(LibsnesApi.SNES_MEMORY.CARTRIDGE_RAM); if (buf == null && Api.QUERY_get_memory_size(LibsnesApi.SNES_MEMORY.SGB_CARTRAM) > 0) { buf = Api.QUERY_get_memory_data(LibsnesApi.SNES_MEMORY.SGB_CARTRAM); @@ -29,7 +29,7 @@ public byte[] CloneSaveRam() return null; } - var ret = new byte[size]; + byte[] ret = new byte[size]; Marshal.Copy((IntPtr)buf, ret, 0, size); return ret; } @@ -40,7 +40,7 @@ public void StoreSaveRam(byte[] data) using (Api.EnterExit()) { byte* buf = Api.QUERY_get_memory_data(LibsnesApi.SNES_MEMORY.CARTRIDGE_RAM); - var size = Api.QUERY_get_memory_size(LibsnesApi.SNES_MEMORY.CARTRIDGE_RAM); + int size = Api.QUERY_get_memory_size(LibsnesApi.SNES_MEMORY.CARTRIDGE_RAM); if (buf == null) { buf = Api.QUERY_get_memory_data(LibsnesApi.SNES_MEMORY.SGB_CARTRAM); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.ISettable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.ISettable.cs index 55544c18ab8..5a43cb4ee7f 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.ISettable.cs @@ -4,18 +4,12 @@ namespace BizHawk.Emulation.Cores.Nintendo.SNES { public partial class LibsnesCore : ISettable { - public SnesSettings GetSettings() - { - return _settings.Clone(); - } + public SnesSettings GetSettings() => _settings.Clone(); IBSNESForGfxDebugger.SettingsObj IBSNESForGfxDebugger.GetSettings() => GetSettings(); - public SnesSyncSettings GetSyncSettings() - { - return _syncSettings.Clone(); - } + public SnesSyncSettings GetSyncSettings() => _syncSettings.Clone(); public PutSettingsDirtyBits PutSettings(SnesSettings o) { @@ -65,10 +59,7 @@ public class SnesSettings : IBSNESForGfxDebugger.SettingsObj public bool AlwaysDoubleSize { get; set; } = false; public string Palette { get; set; } = "BizHawk"; - public SnesSettings Clone() - { - return (SnesSettings)MemberwiseClone(); - } + public SnesSettings Clone() => (SnesSettings)MemberwiseClone(); } public class SnesSyncSettings @@ -80,10 +71,7 @@ public class SnesSyncSettings public bool RandomizedInitialState { get; set; } = true; - public SnesSyncSettings Clone() - { - return (SnesSyncSettings)MemberwiseClone(); - } + public SnesSyncSettings Clone() => (SnesSyncSettings)MemberwiseClone(); } } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.ISoundProvider.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.ISoundProvider.cs index f03e13fbc42..396ebc7b745 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.ISoundProvider.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.ISoundProvider.cs @@ -12,10 +12,7 @@ public partial class LibsnesCore : ISoundProvider private uint _inSamps; private int _outSamps; - public void DiscardSamples() - { - _outSamps = 0; - } + public void DiscardSamples() => _outSamps = 0; public void GetSamplesSync(out short[] samples, out int nsamp) { @@ -65,10 +62,7 @@ private void ProcessSoundEnd() public bool CanProvideAsync => false; - public void GetSamplesAsync(short[] samples) - { - throw new InvalidOperationException("Async mode is not supported."); - } + public void GetSamplesAsync(short[] samples) => throw new InvalidOperationException("Async mode is not supported."); public SyncSoundMode SyncMode => SyncSoundMode.Sync; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.IVideoProvider.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.IVideoProvider.cs index f5be5617def..53173aaf676 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.IVideoProvider.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.IVideoProvider.cs @@ -8,10 +8,9 @@ public partial class LibsnesCore : IVideoProvider public int VirtualHeight { get; private set; } = 224; - public int BufferWidth => _videoWidth; - - public int BufferHeight => _videoHeight; + public int BufferWidth { get; private set; } = 256; + public int BufferHeight { get; private set; } = 224; public int BackgroundColor => 0; public int[] GetVideoBuffer() => _videoBuffer; @@ -20,7 +19,5 @@ public partial class LibsnesCore : IVideoProvider public int VsyncDenominator { get; } private int[] _videoBuffer = new int[256 * 224]; - private int _videoWidth = 256; - private int _videoHeight = 224; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.cs index f8cb97d7108..deff2cc48d4 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.cs @@ -33,7 +33,7 @@ public LibsnesCore(GameInfo game, byte[] romData, byte[] xmlData, string baseRom LibsnesCore.SnesSettings settings, LibsnesCore.SnesSyncSettings syncSettings) { _baseRomPath = baseRomPath; - var ser = new BasicServiceProvider(this); + BasicServiceProvider ser = new(this); ServiceProvider = ser; const string TRACE_HEADER = "65816: PC, mnemonic, operands, registers (A, X, Y, S, D, DB, flags (NVMXDIZC), V, H)"; @@ -104,7 +104,7 @@ public LibsnesCore(GameInfo game, byte[] romData, byte[] xmlData, string baseRom // strip header if ((romData?.Length & 0x7FFF) == 512) { - var newData = new byte[romData.Length - 512]; + byte[] newData = new byte[romData.Length - 512]; Array.Copy(romData, 512, newData, 0, newData.Length); romData = newData; } @@ -217,7 +217,6 @@ public LibsnesCore(GameInfo game, byte[] romData, byte[] xmlData, string baseRom private IController _controller; private readonly LoadParams _currLoadParams; - private int _timeFrameCounter; private bool _disposed; public bool IsSGB { get; } @@ -254,10 +253,7 @@ public MyScanlineHookManager(LibsnesCore core) _core = core; } - protected override void OnHooksChanged() - { - _core.OnScanlineHooksChanged(); - } + protected override void OnHooksChanged() => _core.OnScanlineHooksChanged(); } private void OnScanlineHooksChanged() @@ -270,10 +266,7 @@ private void OnScanlineHooksChanged() Api.QUERY_set_scanlineStart(ScanlineHookManager.HookCount == 0 ? null : _scanlineStartCb); } - private void snes_scanlineStart(int line) - { - ScanlineHookManager.HandleScanline(line); - } + private void snes_scanlineStart(int line) => ScanlineHookManager.HandleScanline(line); private string snes_path_request(int slot, string hint) { @@ -333,7 +326,7 @@ private string snes_path_request(int slot, string hint) } string ret; - var data = CoreComm.CoreFileProvider.GetFirmware(new("SNES", firmwareId), "Game may function incorrectly without the requested firmware."); + byte[] data = CoreComm.CoreFileProvider.GetFirmware(new("SNES", firmwareId), "Game may function incorrectly without the requested firmware."); if (data != null) { ret = hint; @@ -357,7 +350,7 @@ private void snes_trace(uint which, string msg) if (which == (uint)LibsnesApi.eTRACE.CPU) { - var split = msg.Split(new[] { splitStr }, 2, StringSplitOptions.None); + string[] split = msg.Split(new[] { splitStr }, 2, StringSplitOptions.None); _tracer.Put(new(disassembly: split[0].PadRight(34), registerInfo: splitStr + split[1])); } else if (which == (uint)LibsnesApi.eTRACE.SMP) @@ -468,10 +461,7 @@ private bool LoadCurrent() /// meaningless for most controllers. for multitap, 0-3 for which multitap controller /// button ID enum; in the case of a regular controller, this corresponds to shift register position /// for regular controllers, one bit D0 of button status. for other controls, varying ranges depending on id - private short snes_input_state(int port, int device, int index, int id) - { - return _controllerDeck.CoreInputState(_controller, port, device, index, id); - } + private short snes_input_state(int port, int device, int index, int id) => _controllerDeck.CoreInputState(_controller, port, device, index, id); private void snes_input_poll() { @@ -496,15 +486,15 @@ private void snes_video_refresh(int* data, int width, int height) bool doubleSize = _settings.AlwaysDoubleSize; bool lineDouble = doubleSize, dotDouble = doubleSize; - _videoWidth = width; - _videoHeight = height; + BufferWidth = width; + BufferHeight = height; int yskip = 1, xskip = 1; // if we are in high-res mode, we get double width. so, lets double the height here to keep it square. if (width == 512) { - _videoHeight *= 2; + BufferHeight *= 2; yskip = 2; lineDouble = true; @@ -514,14 +504,14 @@ private void snes_video_refresh(int* data, int width, int height) } else if (lineDouble) { - _videoHeight *= 2; + BufferHeight *= 2; yskip = 2; } int srcPitch = 1024; int srcStart = 0; - bool interlaced = height == 478 || height == 448; + bool interlaced = height is 478 or 448; if (interlaced) { // from bsnes in interlaced mode we have each field side by side @@ -533,22 +523,22 @@ private void snes_video_refresh(int* data, int width, int height) lineDouble = false; srcPitch = 512; yskip = 1; - _videoHeight = height; + BufferHeight = height; } if (dotDouble) { - _videoWidth *= 2; + BufferWidth *= 2; xskip = 2; } if (_settings.CropSGBFrame && IsSGB) { - _videoWidth = 160; - _videoHeight = 144; + BufferWidth = 160; + BufferHeight = 144; } - int size = _videoWidth * _videoHeight; + int size = BufferWidth * BufferHeight; if (_videoBuffer.Length != size) { _videoBuffer = new int[size]; @@ -582,13 +572,13 @@ private void snes_video_refresh(int* data, int width, int height) break; } - int bonus = (i * _videoWidth) + xbonus; + int bonus = (i * BufferWidth) + xbonus; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int si = (y * srcPitch) + x + srcStart; - int di = y * _videoWidth * yskip + x * xskip + bonus; + int di = y * BufferWidth * yskip + x * xskip + bonus; int rgb = data[si]; _videoBuffer[di] = rgb; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/SNESGraphicsDecoder.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/SNESGraphicsDecoder.cs index 02c0e4e5fba..ea3d6cf1edc 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/SNESGraphicsDecoder.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/SNESGraphicsDecoder.cs @@ -120,7 +120,7 @@ public struct Dimensions { public Dimensions(int w, int h) { Width = w; Height = h; } public int Width, Height; - public override string ToString() => $"{Width}x{Height}"; + public override readonly string ToString() => $"{Width}x{Height}"; } public enum ScreenSize @@ -170,7 +170,7 @@ public enum BGMode /// /// is a BGMode a mode7 type (mode7, mode7ext, mode7DC) /// - public static bool BGModeIsMode7Type(BGMode bgMode) => bgMode == BGMode.Mode7 || bgMode == BGMode.Mode7DC || bgMode == BGMode.Mode7Ext; + public static bool BGModeIsMode7Type(BGMode bgMode) => bgMode is BGMode.Mode7 or BGMode.Mode7DC or BGMode.Mode7Ext; /// /// this class is not 'smart' - it wont recompute values for you. it's meant to be read only (we should find some way to protect write access to make that clear) @@ -271,7 +271,7 @@ public BGInfo(int num) /// /// The size of the layer, in pixels. This has factored in the selection of 8x8 or 16x16 tiles /// - public Dimensions ScreenSizeInPixels => new Dimensions(ScreenSizeInTiles.Width * TileSize, ScreenSizeInTiles.Height * TileSize); + public Dimensions ScreenSizeInPixels => new(ScreenSizeInTiles.Width * TileSize, ScreenSizeInTiles.Height * TileSize); /// /// returns information about what colors could possibly be used for this bg @@ -347,7 +347,7 @@ public class ScreenInfo public Size ObjSizeBounds; public Size ObjSizeBoundsSquare; - public BGInfos BG = new BGInfos(); + public BGInfos BG = new(); public int Mode { get; init; } public bool Mode1_BG3_Priority { get; init; } @@ -408,7 +408,7 @@ public ScreenInfo ScanScreenInfo() int OBSEL_NameSel = api.QUERY_peek_logical_register(LibsnesApi.SNES_REG.OBSEL_NAMESEL); int OBSEL_NameBase = api.QUERY_peek_logical_register(LibsnesApi.SNES_REG.OBSEL_NAMEBASE); - var si = new ScreenInfo + ScreenInfo si = new() { Mode = api.QUERY_peek_logical_register(LibsnesApi.SNES_REG.BG_MODE), Mode1_BG3_Priority = api.QUERY_peek_logical_register(LibsnesApi.SNES_REG.BG3_PRIORITY) == 1, @@ -1073,18 +1073,16 @@ public void RenderSpriteToScreen(int* screen, int stride, int destx, int desty, } } - public int Colorize(int rgb555) - { + public int Colorize(int rgb555) => //skip to max luminance in the palette table - return colortable[491520 + rgb555]; - } + colortable[491520 + rgb555]; /// /// returns the current palette, transformed into an int array, for more convenience /// public int[] GetPalette() { - var ret = new int[256]; + int[] ret = new int[256]; for (int i = 0; i < 256; i++) ret[i] = cgram[i] & 0x7FFF; return ret; @@ -1097,14 +1095,8 @@ public void DirectColorify(int* screen, int numPixels) } - public void Enter() - { - ((IMonitor)api).Enter(); - } + public void Enter() => ((IMonitor)api).Enter(); - public void Exit() - { - ((IMonitor)api).Exit(); - } + public void Exit() => ((IMonitor)api).Exit(); } //class SNESGraphicsDecoder } //namespace diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/ScanlineHookManager.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/ScanlineHookManager.cs index cf91b7e18d4..7676a78fb42 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/ScanlineHookManager.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/ScanlineHookManager.cs @@ -6,7 +6,7 @@ namespace BizHawk.Emulation.Cores.Nintendo.SNES // TODO: This class is specifically for the SNES Graphics Debugger, but written generally, perhaps it could be moved to a more generic place public class ScanlineHookManager { - private readonly List _records = new List(); + private readonly List _records = new(); public void Register(object tag, Action callback) { @@ -27,10 +27,7 @@ protected virtual void OnHooksChanged() { } - public void Unregister(object tag) - { - _records.RemoveAll(r => r.Tag == tag); - } + public void Unregister(object tag) => _records.RemoveAll(r => r.Tag == tag); public void HandleScanline(int scanline) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES9X/Snes9x.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES9X/Snes9x.cs index ebaee20a3d8..7aa561d7553 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES9X/Snes9x.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES9X/Snes9x.cs @@ -95,23 +95,14 @@ protected override LibWaterboxCore.FrameInfo FrameAdvancePrep(IController contro public override int VirtualWidth => BufferWidth == 256 && BufferHeight <= 240 ? 293 : 587; public override int VirtualHeight => BufferHeight <= 240 && BufferWidth == 512 ? BufferHeight * 2 : BufferHeight; - protected override void LoadStateBinaryInternal(BinaryReader reader) - { - _core.biz_post_load_state(); - } + protected override void LoadStateBinaryInternal(BinaryReader reader) => _core.biz_post_load_state(); private Settings _settings; private SyncSettings _syncSettings; - public Settings GetSettings() - { - return _settings.Clone(); - } + public Settings GetSettings() => _settings.Clone(); - public SyncSettings GetSyncSettings() - { - return _syncSettings.Clone(); - } + public SyncSettings GetSyncSettings() => _syncSettings.Clone(); public PutSettingsDirtyBits PutSettings(Settings o) { @@ -144,7 +135,7 @@ public PutSettingsDirtyBits PutSettings(Settings o) public PutSettingsDirtyBits PutSyncSettings(SyncSettings o) { - var ret = SyncSettings.NeedsReboot(_syncSettings, o); + bool ret = SyncSettings.NeedsReboot(_syncSettings, o); _syncSettings = o; return ret ? PutSettingsDirtyBits.RebootCore : PutSettingsDirtyBits.None; } @@ -228,10 +219,7 @@ public Settings() SettingsUtil.SetDefaultValues(this); } - public Settings Clone() - { - return (Settings)MemberwiseClone(); - } + public Settings Clone() => (Settings)MemberwiseClone(); } public class SyncSettings @@ -251,17 +239,12 @@ public SyncSettings() SettingsUtil.SetDefaultValues(this); } - public SyncSettings Clone() - { - return (SyncSettings)MemberwiseClone(); - } + public SyncSettings Clone() => (SyncSettings)MemberwiseClone(); - public static bool NeedsReboot(SyncSettings x, SyncSettings y) - { + public static bool NeedsReboot(SyncSettings x, SyncSettings y) => // the core can handle dynamic plugging and unplugging, but that changes // the controllerdefinition, and we're not ready for that - return !DeepEquality.DeepEquals(x, y); - } + !DeepEquality.DeepEquals(x, y); } } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES9X/Snes9xControllers.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES9X/Snes9xControllers.cs index 23a7bc14452..2d8078b5283 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES9X/Snes9xControllers.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES9X/Snes9xControllers.cs @@ -91,7 +91,7 @@ private class Joypad : IControlDevice private static int ButtonOrder(string btn) { - var order = new Dictionary + Dictionary order = new() { ["0Up"] = 0, ["0Down"] = 1, ["0Left"] = 2, ["0Right"] = 3, ["0Select"] = 4, ["0Start"] = 5, ["0Y"] = 6, ["0B"] = 7, ["0X"] = 8, ["0A"] = 9 , ["0L"] = 10, ["0R"] = 11 @@ -121,9 +121,9 @@ private abstract class Analog : IControlDevice public void ApplyState(IController controller, short[] input, int offset) { - foreach (var s in Definition.Axes.Keys) + foreach (string s in Definition.Axes.Keys) input[offset++] = (short)controller.AxisValue(s); - foreach (var s in Definition.BoolButtons) + foreach (string s in Definition.BoolButtons) input[offset++] = (short)(controller.IsPressed(s) ? 1 : 0); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SameBoy/SameBoy.IDebuggable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SameBoy/SameBoy.IDebuggable.cs index 17fa17a5c19..cb89c3705e4 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SameBoy/SameBoy.IDebuggable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SameBoy/SameBoy.IDebuggable.cs @@ -55,7 +55,7 @@ public void SetCpuRegister(string register, int value) private const string systemBusScope = "System Bus"; - private readonly MemoryCallbackSystem _memorycallbacks = new MemoryCallbackSystem(new[] { systemBusScope }); + private readonly MemoryCallbackSystem _memorycallbacks = new(new[] { systemBusScope }); public IMemoryCallbackSystem MemoryCallbacks => _memorycallbacks; @@ -67,7 +67,7 @@ private void InitMemoryCallbacks() { LibSameboy.MemoryCallback CreateCallback(MemoryCallbackFlags flags, Func getHasCBOfType) { - var rawFlags = (uint)flags; + uint rawFlags = (uint)flags; return (address) => { if (getHasCBOfType()) diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SameBoy/SameBoy.IEmulator.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SameBoy/SameBoy.IEmulator.cs index ccc1722a5bd..08079055d4e 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SameBoy/SameBoy.IEmulator.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SameBoy/SameBoy.IEmulator.cs @@ -25,7 +25,7 @@ private LibSameboy.Buttons FrameAdvancePrep(IController controller) _controller = controller; uint b = 0; - for (var i = 0; i < 8; i++) + for (int i = 0; i < 8; i++) { b <<= 1; if (controller.IsPressed(GB_BUTTON_ORDER_IN_BITMASK[i])) b |= 1; @@ -36,8 +36,8 @@ private LibSameboy.Buttons FrameAdvancePrep(IController controller) LibSameboy.sameboy_reset(SameboyState); } - var prevTrack = controller.IsPressed("Previous Track"); - var nextTrack = controller.IsPressed("Next Track"); + bool prevTrack = controller.IsPressed("Previous Track"); + bool nextTrack = controller.IsPressed("Next Track"); if (!_switchingTrack) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SameBoy/SameBoy.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SameBoy/SameBoy.IMemoryDomains.cs index 99748ec8dec..605e8fa3bd5 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SameBoy/SameBoy.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SameBoy/SameBoy.IMemoryDomains.cs @@ -13,7 +13,7 @@ public partial class Sameboy private void CreateMemoryDomain(LibSameboy.MemoryAreas which, string name) { - IntPtr data = IntPtr.Zero; + var data = IntPtr.Zero; long length = 0; if (!LibSameboy.sameboy_getmemoryarea(SameboyState, which, ref data, ref length)) diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SameBoy/SameBoy.ISettable.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SameBoy/SameBoy.ISettable.cs index 952701aec0f..03ea4d7afd2 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SameBoy/SameBoy.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SameBoy/SameBoy.ISettable.cs @@ -18,7 +18,7 @@ public partial class Sameboy : ISettable false; - public void DiscardSamples() - { - _soundoutbuffcontains = 0; - } + public void DiscardSamples() => _soundoutbuffcontains = 0; public void GetSamplesSync(out short[] samples, out int nsamp) { @@ -30,10 +27,7 @@ public void SetSyncMode(SyncSoundMode mode) public SyncSoundMode SyncMode => SyncSoundMode.Sync; - public void GetSamplesAsync(short[] samples) - { - throw new InvalidOperationException("Async mode is not supported."); - } + public void GetSamplesAsync(short[] samples) => throw new InvalidOperationException("Async mode is not supported."); private int _soundoutbuffcontains = 0; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SameBoy/SameBoy.IVideoProvider.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SameBoy/SameBoy.IVideoProvider.cs index 7b11766f21f..c36c6b672de 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SameBoy/SameBoy.IVideoProvider.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SameBoy/SameBoy.IVideoProvider.cs @@ -8,7 +8,7 @@ public partial class Sameboy : IVideoProvider private static int[] CreateVideoBuffer() { - var b = new int[256 * 224]; + int[] b = new int[256 * 224]; for (int i = 0; i < (256 * 224); i++) { b[i] = -1; @@ -16,10 +16,7 @@ private static int[] CreateVideoBuffer() return b; } - public int[] GetVideoBuffer() - { - return VideoBuffer; - } + public int[] GetVideoBuffer() => VideoBuffer; public int VirtualWidth => _settings.ShowBorder ? 256 : 160; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SameBoy/SameBoy.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SameBoy/SameBoy.cs index 2c6840f8712..6236558a3df 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SameBoy/SameBoy.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SameBoy/SameBoy.cs @@ -21,7 +21,7 @@ public partial class Sameboy : ICycleTiming, IInputPollable, ILinkable, IRomInfo static Sameboy() { - var resolver = new DynamicLibraryImportResolver( + DynamicLibraryImportResolver resolver = new( OSTailoredCode.IsUnixHost ? "libsameboy.so" : "libsameboy.dll", hasLimitedLifetime: false); LibSameboy = BizInvoker.GetInvoker(resolver, CallingConventionAdapters.Native); } @@ -49,7 +49,7 @@ public bool IsCGBDMGMode public Sameboy(CoreComm comm, GameInfo game, byte[] gbs, SameboySettings settings, SameboySyncSettings syncSettings) : this(comm, game, null, settings, syncSettings, false) { - var gbsInfo = new LibSameboy.GBSInfo + LibSameboy.GBSInfo gbsInfo = new() { TrackCount = 0, FirstTrack = 0, @@ -91,7 +91,7 @@ public Sameboy(CoreComm comm, GameInfo game, byte[] gbs, SameboySettings setting public Sameboy(CoreLoadParameters lp) : this(lp.Comm, lp.Game, lp.Roms[0].FileData, lp.Settings, lp.SyncSettings, lp.DeterministicEmulationRequested) { - var file = lp.Roms[0].FileData; + byte[] file = lp.Roms[0].FileData; RomDetails = $"{lp.Game.Name}\r\n{SHA1Checksum.ComputePrefixedHex(file)}\r\n{MD5Checksum.ComputePrefixedHex(file)}\r\n"; @@ -202,10 +202,7 @@ private void InputCallback() _inputCallbacks.Call(); } - private void RumbleCallback(int amplitude) - { - _controller.SetHapticChannelStrength("Rumble", amplitude); - } + private void RumbleCallback(int amplitude) => _controller.SetHapticChannelStrength("Rumble", amplitude); public bool LinkConnected { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SubGBHawk/SubGBHawk.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SubGBHawk/SubGBHawk.cs index 32914f6b8f9..ff5f5e10155 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SubGBHawk/SubGBHawk.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SubGBHawk/SubGBHawk.cs @@ -26,7 +26,7 @@ public SubGBHawk(CoreComm comm, GameInfo game, byte[] rom, /*string gameDbFn,*/ _GBStatable = _GBCore.ServiceProvider.GetService(); - var ser = new BasicServiceProvider(this); + BasicServiceProvider ser = new(this); ServiceProvider = ser; ser.Register(_GBCore.ServiceProvider.GetService()); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SubNESHawk/SubNESHawk.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SubNESHawk/SubNESHawk.cs index 67990a2acee..83e924fad86 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SubNESHawk/SubNESHawk.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/SubNESHawk/SubNESHawk.cs @@ -22,7 +22,7 @@ public SubNESHawk(CoreComm comm, GameInfo game, byte[] rom, /*string gameDbFn,*/ _nesStatable = _nesCore.ServiceProvider.GetService(); - var ser = new BasicServiceProvider(this); + BasicServiceProvider ser = new(this); ServiceProvider = ser; ser.Register(_nesCore.ServiceProvider.GetService()); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/VB/VirtualBoyee.cs b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/VB/VirtualBoyee.cs index 9d11ff9cf08..42d100756ff 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Nintendo/VB/VirtualBoyee.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Nintendo/VB/VirtualBoyee.cs @@ -19,7 +19,7 @@ public static NymaSettingsInfo CachedSettingsInfo(CoreComm comm) { if (_cachedSettingsInfo is null) { - using var n = new VirtualBoyee(comm); + using VirtualBoyee n = new(comm); n.InitForSettingsInfo("vb.wbx"); _cachedSettingsInfo = n.SettingsInfo.Clone(); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/ADPCM.cs b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/ADPCM.cs index 6e61a6400b8..4e1da182ffd 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/ADPCM.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/ADPCM.cs @@ -10,7 +10,7 @@ public sealed class ADPCM : IMixedSoundProvider { private readonly ScsiCDBus _scsi; private readonly PCEngine _pce; - private readonly VecnaSynchronizer _synchronizer = new VecnaSynchronizer(); + private readonly VecnaSynchronizer _synchronizer = new(); // *************************************************************************** @@ -306,15 +306,9 @@ private void AdpcmEmitSample() } } - public void GetSamplesAsync(short[] samples) - { - _synchronizer.OutputSamples(samples, samples.Length / 2); - } + public void GetSamplesAsync(short[] samples) => _synchronizer.OutputSamples(samples, samples.Length / 2); - public void DiscardSamples() - { - _synchronizer.Clear(); - } + public void DiscardSamples() => _synchronizer.Clear(); public int MaxVolume { get; set; } public bool CanProvideAsync => true; @@ -329,10 +323,7 @@ public void SetSyncMode(SyncSoundMode mode) public SyncSoundMode SyncMode => SyncSoundMode.Async; - public void GetSamplesSync(out short[] samples, out int nsamp) - { - throw new NotImplementedException("Sync sound not yet supported"); - } + public void GetSamplesSync(out short[] samples, out int nsamp) => throw new NotImplementedException("Sync sound not yet supported"); // *************************************************************************** diff --git a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/MemoryMap.Populous.cs b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/MemoryMap.Populous.cs index 6cee45d5feb..f739fb9a06f 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/MemoryMap.Populous.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/MemoryMap.Populous.cs @@ -11,13 +11,13 @@ public partial class PCEngine private byte ReadMemoryPopulous(int addr) { - if (addr >= 0x80000 && addr < 0x88000) + if (addr is >= 0x80000 and < 0x88000) return PopulousRAM[addr & 0x7FFF]; if (addr < 0xFFFFF) // read ROM return RomData[addr % RomLength]; - if (addr >= 0x1F0000 && addr < 0x1F8000) // read RAM + if (addr is >= 0x1F0000 and < 0x1F8000) // read RAM return Ram[addr & 0x1FFF]; if (addr >= 0x1FE000) // hardware page. @@ -26,8 +26,8 @@ private byte ReadMemoryPopulous(int addr) if (addr < 0x1FE800) { Cpu.PendingCycles--; return VCE.ReadVCE(addr); } if (addr < 0x1FEC00) return IOBuffer; if (addr < 0x1FF000) { IOBuffer = (byte)(Cpu.ReadTimerValue() | (IOBuffer & 0x80)); return IOBuffer; } - if (addr >= 0x1FF000 && - addr < 0x1FF400) { IOBuffer = ReadInput(); return IOBuffer; } + if (addr is >= 0x1FF000 and + < 0x1FF400) { IOBuffer = ReadInput(); return IOBuffer; } if ((addr & ~1) == 0x1FF400) return IOBuffer; if (addr == 0x1FF402) { IOBuffer = Cpu.IRQControlByte; return IOBuffer; } if (addr == 0x1FF403) { IOBuffer = (byte)(Cpu.ReadIrqStatus() | (IOBuffer & 0xF8)); return IOBuffer; } @@ -39,7 +39,7 @@ private byte ReadMemoryPopulous(int addr) private void WriteMemoryPopulous(int addr, byte value) { - if (addr >= 0x1F0000 && addr < 0x1F8000) // write RAM. + if (addr is >= 0x1F0000 and < 0x1F8000) // write RAM. Ram[addr & 0x1FFF] = value; else if (addr >= 0x1FE000) // hardware page. @@ -49,13 +49,13 @@ private void WriteMemoryPopulous(int addr, byte value) else if (addr < 0x1FEC00) { IOBuffer = value; PSG.WritePSG((byte)addr, value, Cpu.TotalExecutedCycles); } else if (addr == 0x1FEC00) { IOBuffer = value; Cpu.WriteTimer(value); } else if (addr == 0x1FEC01) { IOBuffer = value; Cpu.WriteTimerEnable(value); } - else if (addr >= 0x1FF000 && - addr < 0x1FF400) { IOBuffer = value; WriteInput(value); } + else if (addr is >= 0x1FF000 and + < 0x1FF400) { IOBuffer = value; WriteInput(value); } else if (addr == 0x1FF402) { IOBuffer = value; Cpu.WriteIrqControl(value); } else if (addr == 0x1FF403) { IOBuffer = value; Cpu.WriteIrqStatus(); } else Log.Error("MEM", "unhandled hardware write [{0:X6}] : {1:X2}", addr, value); } - else if (addr >= 0x80000 && addr < 0x88000) + else if (addr is >= 0x80000 and < 0x88000) PopulousRAM[addr & 0x7FFF] = value; else Log.Error("MEM", "UNHANDLED WRITE: {0:X6}:{1:X2}", addr, value); diff --git a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/MemoryMap.SF2.cs b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/MemoryMap.SF2.cs index 253129ecb44..42af318b05b 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/MemoryMap.SF2.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/MemoryMap.SF2.cs @@ -19,7 +19,7 @@ private byte ReadMemorySF2(int addr) if (addr < 0xFFFFF) // read ROM return RomData[(addr & 0x7FFFF) + ((SF2MapperLatch + 1) * 0x80000)]; - if (addr >= 0x1F0000 && addr < 0x1F8000) // read RAM + if (addr is >= 0x1F0000 and < 0x1F8000) // read RAM return Ram[addr & 0x1FFF]; if (addr >= 0x1FE000) // hardware page. @@ -28,8 +28,8 @@ private byte ReadMemorySF2(int addr) if (addr < 0x1FE800) { Cpu.PendingCycles--; return VCE.ReadVCE(addr); } if (addr < 0x1FEC00) return IOBuffer; if (addr < 0x1FF000) { IOBuffer = (byte)(Cpu.ReadTimerValue() | (IOBuffer & 0x80)); return IOBuffer; } - if (addr >= 0x1FF000 && - addr < 0x1FF400) { IOBuffer = ReadInput(); return IOBuffer; } + if (addr is >= 0x1FF000 and + < 0x1FF400) { IOBuffer = ReadInput(); return IOBuffer; } if ((addr & ~1) == 0x1FF400) return IOBuffer; if (addr == 0x1FF402) { IOBuffer = Cpu.IRQControlByte; return IOBuffer; } if (addr == 0x1FF403) { IOBuffer = (byte)(Cpu.ReadIrqStatus() | (IOBuffer & 0xF8)); return IOBuffer; } @@ -54,7 +54,7 @@ private void WriteMemorySF2(int addr, byte value) return; } - if (addr >= 0x1F0000 && addr < 0x1F8000) // write RAM. + if (addr is >= 0x1F0000 and < 0x1F8000) // write RAM. Ram[addr & 0x1FFF] = value; else if (addr >= 0x1FE000) // hardware page. @@ -64,8 +64,8 @@ private void WriteMemorySF2(int addr, byte value) else if (addr < 0x1FEC00) { IOBuffer = value; PSG.WritePSG((byte)addr, value, Cpu.TotalExecutedCycles); } else if (addr == 0x1FEC00) { IOBuffer = value; Cpu.WriteTimer(value); } else if (addr == 0x1FEC01) { IOBuffer = value; Cpu.WriteTimerEnable(value); } - else if (addr >= 0x1FF000 && - addr < 0x1FF400) { IOBuffer = value; WriteInput(value); } + else if (addr is >= 0x1FF000 and + < 0x1FF400) { IOBuffer = value; WriteInput(value); } else if (addr == 0x1FF402) { IOBuffer = value; Cpu.WriteIrqControl(value); } else if (addr == 0x1FF403) { IOBuffer = value; Cpu.WriteIrqStatus(); } else Log.Error("MEM", "unhandled hardware write [{0:X6}] : {1:X2}", addr, value); diff --git a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/MemoryMap.SuperGrafx.cs b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/MemoryMap.SuperGrafx.cs index 984d5636982..abb00def4bc 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/MemoryMap.SuperGrafx.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/MemoryMap.SuperGrafx.cs @@ -12,7 +12,7 @@ private byte ReadMemorySGX(int addr) if (addr < 0xFFFFF) // read ROM return RomData[addr % RomLength]; - if (addr >= 0x1F0000 && addr < 0x1F8000) // read RAM + if (addr is >= 0x1F0000 and < 0x1F8000) // read RAM return Ram[addr & 0x7FFF]; if (addr >= 0x1FE000) // hardware page. @@ -29,8 +29,8 @@ private byte ReadMemorySGX(int addr) if (addr < 0x1FE800) { Cpu.PendingCycles--; return VCE.ReadVCE(addr); } if (addr < 0x1FEC00) return IOBuffer; if (addr < 0x1FF000) { IOBuffer = (byte)(Cpu.ReadTimerValue() | (IOBuffer & 0x80)); return IOBuffer; } - if (addr >= 0x1FF000 && - addr < 0x1FF400) { IOBuffer = ReadInput(); return IOBuffer; } + if (addr is >= 0x1FF000 and + < 0x1FF400) { IOBuffer = ReadInput(); return IOBuffer; } if ((addr & ~1) == 0x1FF400) return IOBuffer; if (addr == 0x1FF402) { IOBuffer = Cpu.IRQControlByte; return IOBuffer; } if (addr == 0x1FF403) { IOBuffer = (byte)(Cpu.ReadIrqStatus() | (IOBuffer & 0xF8)); return IOBuffer; } @@ -42,7 +42,7 @@ private byte ReadMemorySGX(int addr) private void WriteMemorySGX(int addr, byte value) { - if (addr >= 0x1F0000 && addr < 0x1F8000) // write RAM. + if (addr is >= 0x1F0000 and < 0x1F8000) // write RAM. Ram[addr & 0x7FFF] = value; else if (addr >= 0x1FE000) // hardware page. @@ -58,8 +58,8 @@ private void WriteMemorySGX(int addr, byte value) else if (addr < 0x1FEC00) { IOBuffer = value; PSG.WritePSG((byte)addr, value, Cpu.TotalExecutedCycles); } else if (addr == 0x1FEC00) { IOBuffer = value; Cpu.WriteTimer(value); } else if (addr == 0x1FEC01) { IOBuffer = value; Cpu.WriteTimerEnable(value); } - else if (addr >= 0x1FF000 && - addr < 0x1FF400) { IOBuffer = value; WriteInput(value); } + else if (addr is >= 0x1FF000 and + < 0x1FF400) { IOBuffer = value; WriteInput(value); } else if (addr == 0x1FF402) { IOBuffer = value; Cpu.WriteIrqControl(value); } else if (addr == 0x1FF403) { IOBuffer = value; Cpu.WriteIrqStatus(); } else Log.Error("MEM", "unhandled hardware write [{0:X6}] : {1:X2}", addr, value); diff --git a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/MemoryMap.TurboCD.cs b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/MemoryMap.TurboCD.cs index 99beefb15ab..6ba4066b69f 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/MemoryMap.TurboCD.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/MemoryMap.TurboCD.cs @@ -9,10 +9,10 @@ private byte ReadMemoryCD(int addr) if (addr < 0x80000) // read ROM return RomData[addr % RomLength]; - if (addr >= 0x1F0000 && addr < 0x1F8000) // read RAM + if (addr is >= 0x1F0000 and < 0x1F8000) // read RAM return Ram[addr & 0x1FFF]; - if (addr >= 0x100000 && addr < 0x110000) // read CD RAM + if (addr is >= 0x100000 and < 0x110000) // read CD RAM return CDRam[addr & 0xFFFF]; if (addr >= 0xD0000 && addr < 0x100000 && SuperRam != null) // Super SysCard RAM @@ -24,8 +24,8 @@ private byte ReadMemoryCD(int addr) if (addr < 0x1FE800) { Cpu.PendingCycles--; return VCE.ReadVCE(addr); } if (addr < 0x1FEC00) return IOBuffer; if (addr < 0x1FF000) { IOBuffer = (byte)(Cpu.ReadTimerValue() | (IOBuffer & 0x80)); return IOBuffer; } - if (addr >= 0x1FF000 && - addr < 0x1FF400) { IOBuffer = ReadInput(); return IOBuffer; } + if (addr is >= 0x1FF000 and + < 0x1FF400) { IOBuffer = ReadInput(); return IOBuffer; } if ((addr & ~1) == 0x1FF400) return IOBuffer; if (addr == 0x1FF402) { IOBuffer = Cpu.IRQControlByte; return IOBuffer; } if (addr == 0x1FF403) { IOBuffer = (byte)(Cpu.ReadIrqStatus() | (IOBuffer & 0xF8)); return IOBuffer; } @@ -40,7 +40,7 @@ private byte ReadMemoryCD(int addr) return value; } - if (addr >= 0x1EE000 && addr <= 0x1EE7FF) // BRAM + if (addr is >= 0x1EE000 and <= 0x1EE7FF) // BRAM { if (BramEnabled && BramLocked == false) return BRAM[addr & 0x7FF]; @@ -53,10 +53,10 @@ private byte ReadMemoryCD(int addr) private void WriteMemoryCD(int addr, byte value) { - if (addr >= 0x1F0000 && addr < 0x1F8000) // write RAM. + if (addr is >= 0x1F0000 and < 0x1F8000) // write RAM. Ram[addr & 0x1FFF] = value; - else if (addr >= 0x100000 && addr < 0x110000) // write CD-RAM + else if (addr is >= 0x100000 and < 0x110000) // write CD-RAM CDRam[addr & 0xFFFF] = value; else if (addr >= 0xD0000 && addr < 0x100000 && SuperRam != null) // Super SysCard RAM @@ -69,8 +69,8 @@ private void WriteMemoryCD(int addr, byte value) else if (addr < 0x1FEC00) { IOBuffer = value; PSG.WritePSG((byte)addr, value, Cpu.TotalExecutedCycles); } else if (addr == 0x1FEC00) { IOBuffer = value; Cpu.WriteTimer(value); } else if (addr == 0x1FEC01) { IOBuffer = value; Cpu.WriteTimerEnable(value); } - else if (addr >= 0x1FF000 && - addr < 0x1FF400) { IOBuffer = value; WriteInput(value); } + else if (addr is >= 0x1FF000 and + < 0x1FF400) { IOBuffer = value; WriteInput(value); } else if (addr == 0x1FF402) { IOBuffer = value; Cpu.WriteIrqControl(value); } else if (addr == 0x1FF403) { IOBuffer = value; Cpu.WriteIrqStatus(); } else if (addr >= 0x1FF800) { WriteCD(addr, value); } @@ -84,7 +84,7 @@ private void WriteMemoryCD(int addr, byte value) page.Increment(); } - else if (addr >= 0x1EE000 && addr <= 0x1EE7FF) // BRAM + else if (addr is >= 0x1EE000 and <= 0x1EE7FF) // BRAM { if (BramEnabled && BramLocked == false) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/MemoryMap.cs b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/MemoryMap.cs index 1917adb0a68..31c945d07bd 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/MemoryMap.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/MemoryMap.cs @@ -11,7 +11,7 @@ private byte ReadMemory(int addr) if (addr < 0xFFFFF) // read ROM return RomData[addr % RomLength]; - if (addr >= 0x1F0000 && addr < 0x1F8000) // read RAM + if (addr is >= 0x1F0000 and < 0x1F8000) // read RAM return Ram[addr & 0x1FFF]; if (addr >= 0x1FE000) // hardware page. @@ -20,15 +20,15 @@ private byte ReadMemory(int addr) if (addr < 0x1FE800) { Cpu.PendingCycles--; return VCE.ReadVCE(addr); } if (addr < 0x1FEC00) return IOBuffer; if (addr < 0x1FF000) { IOBuffer = (byte)(Cpu.ReadTimerValue() | (IOBuffer & 0x80)); return IOBuffer; } - if (addr >= 0x1FF000 && - addr < 0x1FF400) { IOBuffer = ReadInput(); return IOBuffer; } + if (addr is >= 0x1FF000 and + < 0x1FF400) { IOBuffer = ReadInput(); return IOBuffer; } if ((addr & ~1) == 0x1FF400) return IOBuffer; if (addr == 0x1FF402) { IOBuffer = Cpu.IRQControlByte; return IOBuffer; } if (addr == 0x1FF403) { IOBuffer = (byte)(Cpu.ReadIrqStatus() | (IOBuffer & 0xF8)); return IOBuffer; } if (addr >= 0x1FF800) return ReadCD(addr); } - if (addr >= 0x1EE000 && addr <= 0x1EE7FF) // BRAM + if (addr is >= 0x1EE000 and <= 0x1EE7FF) // BRAM { if (BramEnabled && BramLocked == false) return BRAM[addr & 0x7FF]; @@ -43,7 +43,7 @@ private byte ReadMemory(int addr) private void WriteMemory(int addr, byte value) { - if (addr >= 0x1F0000 && addr < 0x1F8000) // write RAM. + if (addr is >= 0x1F0000 and < 0x1F8000) // write RAM. { Ram[addr & 0x1FFF] = value; } @@ -54,14 +54,14 @@ private void WriteMemory(int addr, byte value) else if (addr < 0x1FEC00) { IOBuffer = value; PSG.WritePSG((byte)addr, value, Cpu.TotalExecutedCycles); } else if (addr == 0x1FEC00) { IOBuffer = value; Cpu.WriteTimer(value); } else if (addr == 0x1FEC01) { IOBuffer = value; Cpu.WriteTimerEnable(value); } - else if (addr >= 0x1FF000 && - addr < 0x1FF400) { IOBuffer = value; WriteInput(value); } + else if (addr is >= 0x1FF000 and + < 0x1FF400) { IOBuffer = value; WriteInput(value); } else if (addr == 0x1FF402) { IOBuffer = value; Cpu.WriteIrqControl(value); } else if (addr == 0x1FF403) { IOBuffer = value; Cpu.WriteIrqStatus(); } else if (addr >= 0x1FF800) { WriteCD(addr, value); } else Log.Error("MEM", "unhandled hardware write [{0:X6}] : {1:X2}", addr, value); } - else if (addr >= 0x1EE000 && addr <= 0x1EE7FF) // BRAM + else if (addr is >= 0x1EE000 and <= 0x1EE7FF) // BRAM { if (BramEnabled && BramLocked == false) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.ICodeDataLogger.cs b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.ICodeDataLogger.cs index b30f8490d75..2692a8108e4 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.ICodeDataLogger.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.ICodeDataLogger.cs @@ -8,10 +8,7 @@ namespace BizHawk.Emulation.Cores.PCEngine { public sealed partial class PCEngine : ICodeDataLogger { - public void SetCDL(ICodeDataLog cdl) - { - Cpu.CDL = cdl; - } + public void SetCDL(ICodeDataLog cdl) => Cpu.CDL = cdl; public void NewCDL(ICodeDataLog cdl) { @@ -26,10 +23,7 @@ public void NewCDL(ICodeDataLog cdl) cdl.SubVer = 0; } - public void DisassembleCDL(Stream s, ICodeDataLog cdl) - { - Cpu.DisassembleCDL(s, cdl, _memoryDomains); - } + public void DisassembleCDL(Stream s, ICodeDataLog cdl) => Cpu.DisassembleCDL(s, cdl, _memoryDomains); private static void CDLMappingApplyRange(HuC6280.MemMapping[] mm, string name, int block, int len, int initialoffs = 0) { @@ -52,7 +46,7 @@ private void InitCDLMappings() SF2UpdateCDLMappings = true; - var mm = new HuC6280.MemMapping[256]; + HuC6280.MemMapping[] mm = new HuC6280.MemMapping[256]; CDLMappingApplyRange(mm, "ROM", 0x00, Math.Min(RomLength, 1024 * 1024)); if (PopulousRAM != null) @@ -102,7 +96,7 @@ private void InitCDLMappings() CDLMappingApplyRange(mm, "Battery RAM", 0xf7, BRAM.Length); } - var ramMirrors = new HuC6280.MemMapping { Name = "Main Memory", Offs = 0 }; + HuC6280.MemMapping ramMirrors = new() { Name = "Main Memory", Offs = 0 }; mm[0xf9] = mm[0xfa] = mm[0xfb] = ramMirrors; CDLMappingApplyRange(mm, "Main Memory", 0xf8, Ram.Length); diff --git a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.IEmulator.cs b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.IEmulator.cs index 7c1ce7c52f0..cd01e323fbf 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.IEmulator.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.IEmulator.cs @@ -62,9 +62,6 @@ public void ResetCounters() _isLag = false; } - public void Dispose() - { - disc?.Dispose(); - } + public void Dispose() => disc?.Dispose(); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.IInputPollable.cs b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.IInputPollable.cs index bb22491ee78..26e3943edcf 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.IInputPollable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.IInputPollable.cs @@ -18,7 +18,7 @@ public bool IsLagFrame public IInputCallbackSystem InputCallbacks => _inputCallbacks; - private readonly InputCallbackSystem _inputCallbacks = new InputCallbackSystem(); + private readonly InputCallbackSystem _inputCallbacks = new(); private int _lagCount; private bool _lagged = true; private bool _isLag = false; diff --git a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.IMemoryDomains.cs index 59a1075653e..e63e0777adf 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.IMemoryDomains.cs @@ -7,16 +7,16 @@ namespace BizHawk.Emulation.Cores.PCEngine { public sealed partial class PCEngine { - private readonly Dictionary _byteArrayDomains = new Dictionary(); - private readonly Dictionary _ushortArrayDomains = new Dictionary(); + private readonly Dictionary _byteArrayDomains = new(); + private readonly Dictionary _ushortArrayDomains = new(); private bool _memoryDomainsInit; private MemoryDomainList _memoryDomains; private void SetupMemoryDomains() { - var domains = new List(); + List domains = new(); - var systemBusDomain = new MemoryDomainDelegate("System Bus (21 bit)", 0x200000, MemoryDomain.Endian.Little, + MemoryDomainDelegate systemBusDomain = new("System Bus (21 bit)", 0x200000, MemoryDomain.Endian.Little, (addr) => { if (addr is < 0 or > 0x1FFFFF) throw new ArgumentOutOfRangeException(paramName: nameof(addr), addr, message: "address out of range"); @@ -30,7 +30,7 @@ private void SetupMemoryDomains() wordSize: 2); domains.Add(systemBusDomain); - var cpuBusDomain = new MemoryDomainDelegate("System Bus", 0x10000, MemoryDomain.Endian.Little, + MemoryDomainDelegate cpuBusDomain = new("System Bus", 0x10000, MemoryDomain.Endian.Little, (addr) => { if (addr is < 0 or > 0xFFFF) throw new ArgumentOutOfRangeException(paramName: nameof(addr), addr, message: "address out of range"); @@ -49,9 +49,11 @@ private void SetupMemoryDomains() domains.AddRange(_byteArrayDomains.Values); domains.AddRange(_ushortArrayDomains.Values); - _memoryDomains = new MemoryDomainList(domains); - _memoryDomains.SystemBus = cpuBusDomain; - _memoryDomains.MainMemory = _byteArrayDomains["Main Memory"]; + _memoryDomains = new MemoryDomainList(domains) + { + SystemBus = cpuBusDomain, + MainMemory = _byteArrayDomains["Main Memory"] + }; ((BasicServiceProvider) ServiceProvider).Register(_memoryDomains); _memoryDomainsInit = true; @@ -99,7 +101,7 @@ private void SyncByteArrayDomain(string name, byte[] data) } else { - var m = new MemoryDomainByteArray(name, MemoryDomain.Endian.Little, data, true, 1); + MemoryDomainByteArray m = new(name, MemoryDomain.Endian.Little, data, true, 1); _byteArrayDomains.Add(name, m); } } @@ -113,7 +115,7 @@ private void SyncUshortArrayDomain(string name, ushort[] data) } else { - var m = new MemoryDomainUshortArray(name, MemoryDomain.Endian.Big, data, true); + MemoryDomainUshortArray m = new(name, MemoryDomain.Endian.Big, data, true); _ushortArrayDomains.Add(name, m); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.ISaveRam.cs b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.ISaveRam.cs index 0a4b50e6970..7c8f2562b76 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.ISaveRam.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.ISaveRam.cs @@ -7,10 +7,7 @@ public sealed partial class PCEngine : ISaveRam { public bool SaveRamModified { get; private set; } - public byte[] CloneSaveRam() - { - return (byte[]) BRAM?.Clone(); - } + public byte[] CloneSaveRam() => (byte[])BRAM?.Clone(); public void StoreSaveRam(byte[] data) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.ISettable.cs b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.ISettable.cs index 65310a0b259..07e6b5cfdeb 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.ISettable.cs @@ -7,15 +7,9 @@ namespace BizHawk.Emulation.Cores.PCEngine { public sealed partial class PCEngine : ISettable { - public PCESettings GetSettings() - { - return Settings.Clone(); - } + public PCESettings GetSettings() => Settings.Clone(); - public PCESyncSettings GetSyncSettings() - { - return _syncSettings.Clone(); - } + public PCESyncSettings GetSyncSettings() => _syncSettings.Clone(); public PutSettingsDirtyBits PutSettings(PCESettings o) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.TurboCD.cs b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.TurboCD.cs index 809338cb608..2416c8268c2 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.TurboCD.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.TurboCD.cs @@ -185,7 +185,7 @@ private void WriteCD(int addr, byte value) break; default: - if (addr >= 0x1FFA00 && addr < 0x1FFA40) + if (addr is >= 0x1FFA00 and < 0x1FFA40) WriteArcadeCard(addr & 0x1FFF, value); else Log.Error("CD", "unknown write to {0:X4}:{1:X2} pc={2:X4}", addr, value, Cpu.PC); @@ -300,7 +300,7 @@ public byte ReadCD(int addr) case 0x1AFF: return ArcadeCard ? (byte)0x51 : (byte)0xFF; default: - if (addr >= 0x1FFA00 && addr < 0x1FFA40) + if (addr is >= 0x1FFA00 and < 0x1FFA40) return ReadArcadeCard(addr & 0x1FFF); else Log.Error("CD", "unknown read to {0:X4}", addr); diff --git a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.cs b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.cs index 504e57fd515..a04699763ee 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using BizHawk.Common; @@ -85,16 +85,11 @@ public PCEngine(CoreLoadParameters lp) } else if (lp.Discs.Count == 0 && lp.Roms.Count == 1) { - switch (SystemId = lp.Game.System) + Type = (SystemId = lp.Game.System) switch { - default: - case VSystemID.Raw.PCE: - Type = NecSystemType.TurboGrafx; - break; - case VSystemID.Raw.SGX: - Type = NecSystemType.SuperGrafx; - break; - } + VSystemID.Raw.PCE => NecSystemType.TurboGrafx, + _ => NecSystemType.SuperGrafx, + }; Settings = lp.Settings ?? new PCESettings(); _syncSettings = lp.SyncSettings ?? new PCESyncSettings(); @@ -208,7 +203,7 @@ private void Init(GameInfo game, byte[] rom) // 384k roms require special loading code. Why ;_; // In memory, 384k roms look like [1st 256k][Then full 384k] RomData = new byte[0xA0000]; - var origRom = rom; + byte[] origRom = rom; for (int i = 0; i < 0x40000; i++) RomData[i] = origRom[i]; for (int i = 0; i < 0x60000; i++) @@ -316,7 +311,7 @@ private void Init(GameInfo game, byte[] rom) Cpu.ResetPC(); Tracer = new TraceBuffer(Cpu.TraceHeader); - var ser = new BasicServiceProvider(this); + BasicServiceProvider ser = new(this); ServiceProvider = ser; ser.Register(Tracer); ser.Register(Cpu); @@ -330,14 +325,14 @@ private void Init(GameInfo game, byte[] rom) private static Dictionary SizesFromHuMap(IEnumerable mm) { - Dictionary sizes = new Dictionary(); + Dictionary sizes = new(); foreach (var m in mm) { - if (!sizes.TryGetValue(m.Name, out var size) || size <= m.MaxOffs) sizes[m.Name] = m.MaxOffs; + if (!sizes.TryGetValue(m.Name, out int size) || size <= m.MaxOffs) sizes[m.Name] = m.MaxOffs; } - var keys = new List(sizes.Keys); - foreach (var key in keys) + List keys = new(sizes.Keys); + foreach (string key in keys) { // becase we were looking at offsets, and each bank is 8192 big, we need to add that size sizes[key] += 8192; diff --git a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PceControllerDeck.cs b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PceControllerDeck.cs index 674f850bd53..0808478bd56 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PceControllerDeck.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/PceControllerDeck.cs @@ -57,21 +57,15 @@ public PceControllerDeck( public byte Read(int portNum, IController c, bool sel) { - switch (portNum) + return portNum switch { - default: - throw new ArgumentOutOfRangeException(paramName: nameof(portNum), portNum, "port index out of range"); - case 1: - return _port1.Read(c, sel); - case 2: - return _port2.Read(c, sel); - case 3: - return _port3.Read(c, sel); - case 4: - return _port4.Read(c, sel); - case 5: - return _port5.Read(c, sel); - } + 1 => _port1.Read(c, sel), + 2 => _port2.Read(c, sel), + 3 => _port3.Read(c, sel), + 4 => _port4.Read(c, sel), + 5 => _port5.Read(c, sel), + _ => throw new ArgumentOutOfRangeException(paramName: nameof(portNum), portNum, "port index out of range"), + }; } public ControllerDefinition Definition { get; } @@ -94,10 +88,7 @@ public UnpluggedController(int portNum) Definition = new("(PC Engine Controller fragment)"); } - public byte Read(IController c, bool sel) - { - return 0x3F; - } + public byte Read(IController c, bool sel) => 0x3F; public ControllerDefinition Definition { get; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/QuickCollections.cs b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/QuickCollections.cs index 228f18f437b..be374c9f1d4 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/QuickCollections.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/QuickCollections.cs @@ -24,15 +24,9 @@ public T this[int index] public int Count => Position; - public void Add(T item) - { - buffer[Position++] = item; - } + public void Add(T item) => buffer[Position++] = item; - public void Clear() - { - Position = 0; - } + public void Clear() => Position = 0; } // and the point of this one is to be easier to serialize quickly. AND fast to clear. @@ -82,7 +76,7 @@ public T Dequeue() if (size == 0) throw new Exception($"{nameof(QuickQueue)} is empty!"); - T item = buffer[head]; + var item = buffer[head]; head = (head + 1) % buffer.Length; size--; return item; @@ -95,10 +89,7 @@ public void Clear() size = 0; } - public T[] GetBuffer() - { - return buffer; - } + public T[] GetBuffer() => buffer; public void SignalBufferFilled(int count) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/ScsiCDBus.cs b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/ScsiCDBus.cs index 35aa6986434..2b9bc8cd139 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/ScsiCDBus.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/ScsiCDBus.cs @@ -1,4 +1,4 @@ -using System; +using System; using BizHawk.Common; using BizHawk.Common.NumberExtensions; @@ -12,6 +12,7 @@ namespace BizHawk.Emulation.Cores.PCEngine // which incidentally would allow us to put it back to an int from a long if we wanted to public sealed class ScsiCDBus { + #pragma warning disable IDE0051 private const int STATUS_GOOD = 0; private const int STATUS_CHECK_CONDITION = 1; private const int STATUS_CONDITION_MET = 2; @@ -26,6 +27,7 @@ public sealed class ScsiCDBus private const int SCSI_PAUSE = 0xDA; private const int SCSI_READ_SUBCODE_Q = 0xDD; private const int SCSI_READ_TOC = 0xDE; + #pragma warning restore IDE0051 private bool bsy, sel, cd, io, msg, req, ack, atn, rst; private bool signalsChanged; @@ -137,8 +139,8 @@ public bool RST private bool StatusCompleted; private byte MessageValue; - private readonly QuickList CommandBuffer = new QuickList(10); // 10 = biggest command - public QuickQueue DataIn = new QuickQueue(2048); // one data sector + private readonly QuickList CommandBuffer = new(10); // 10 = biggest command + public QuickQueue DataIn = new(2048); // one data sector // ******** Data Transfer / READ command support ******** @@ -181,7 +183,7 @@ public void Think() if (DataIn.Count == 0) { // read in a sector and shove it in the queue - var dsr = new DiscSectorReader(disc); // TODO - cache reader + DiscSectorReader dsr = new(disc); // TODO - cache reader dsr.ReadLBA_2048(CurrentReadingSector, DataIn.GetBuffer(), 0); DataIn.SignalBufferFilled(2048); CurrentReadingSector++; @@ -552,7 +554,7 @@ private void CommandReadTOC() // zero 07-jul-2015 - I may have broken this int totalLbaLength = disc.Session1.LeadoutLBA; - DiscUtils.Convert_LBA_To_AMSF(totalLbaLength + 150, out var m, out var s, out var f); + DiscUtils.Convert_LBA_To_AMSF(totalLbaLength + 150, out byte m, out byte s, out byte f); DataIn.Clear(); DataIn.Enqueue(m.BinToBCD()); @@ -576,7 +578,7 @@ private void CommandReadTOC() else lbaPos = tracks[track].LBA; - DiscUtils.Convert_LBA_To_AMSF(lbaPos, out var m, out var s, out var f); + DiscUtils.Convert_LBA_To_AMSF(lbaPos, out byte m, out byte s, out byte f); DataIn.Clear(); DataIn.Enqueue(m.BinToBCD()); diff --git a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/VDC.Render.cs b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/VDC.Render.cs index afceafc44e0..50542719b17 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/VDC.Render.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/VDC.Render.cs @@ -126,7 +126,7 @@ private unsafe void RenderBackgroundScanlineUnsafe(bool show) int p = vce.Palette[256]; fixed (int* FBptr = FrameBuffer) { - int* dst = FBptr + (ActiveLine + ViewStartLine - pce.Settings.TopLine) * FramePitch; + int* dst = FBptr + (ActiveLine + ViewStartLine - pce.Settings.TopLine) * VirtualWidth; for (int i = 0; i < FrameWidth; i++) *dst++ = p; } @@ -150,7 +150,7 @@ private unsafe void RenderBackgroundScanlineUnsafe(bool show) { // pointer to the BAT and the framebuffer for this line ushort* BatRow = VRAMptr + yTile * BatWidth; - int* dst = FBptr + (ActiveLine + ViewStartLine - pce.Settings.TopLine) * FramePitch; + int* dst = FBptr + (ActiveLine + ViewStartLine - pce.Settings.TopLine) * VirtualWidth; // parameters that change per tile ushort BatEnt; @@ -204,7 +204,7 @@ private void RenderBackgroundScanlineSafe(bool show) if (BackgroundEnabled == false) { for (int i = 0; i < FrameWidth; i++) - FrameBuffer[((ActiveLine + ViewStartLine - pce.Settings.TopLine) * FramePitch) + i] = vce.Palette[256]; + FrameBuffer[((ActiveLine + ViewStartLine - pce.Settings.TopLine) * VirtualWidth) + i] = vce.Palette[256]; return; } @@ -228,10 +228,10 @@ private void RenderBackgroundScanlineSafe(bool show) byte c = PatternBuffer[(tileNo * 64) + (yOfs * 8) + xOfs]; if (c == 0) - FrameBuffer[((ActiveLine + ViewStartLine - pce.Settings.TopLine) * FramePitch) + x] = vce.Palette[0]; + FrameBuffer[((ActiveLine + ViewStartLine - pce.Settings.TopLine) * VirtualWidth) + x] = vce.Palette[0]; else { - FrameBuffer[((ActiveLine + ViewStartLine - pce.Settings.TopLine) * FramePitch) + x] = show ? vce.Palette[paletteBase + c] : vce.Palette[0]; + FrameBuffer[((ActiveLine + ViewStartLine - pce.Settings.TopLine) * VirtualWidth) + x] = show ? vce.Palette[paletteBase + c] : vce.Palette[0]; PriorityBuffer[x] = 1; } } @@ -363,7 +363,7 @@ public void RenderSpritesScanline(bool show) { InterSpritePriorityBuffer[xs] = 1; if ((priority || PriorityBuffer[xs] == 0) && show) - FrameBuffer[((ActiveLine + ViewStartLine - pce.Settings.TopLine) * FramePitch) + xs] = vce.Palette[paletteBase + pixel]; + FrameBuffer[((ActiveLine + ViewStartLine - pce.Settings.TopLine) * VirtualWidth) + xs] = vce.Palette[paletteBase + pixel]; } } } @@ -380,7 +380,7 @@ public void RenderSpritesScanline(bool show) { InterSpritePriorityBuffer[xs] = 1; if ((priority || PriorityBuffer[xs] == 0) && show) - FrameBuffer[((ActiveLine + ViewStartLine - pce.Settings.TopLine) * FramePitch) + xs] = vce.Palette[paletteBase + pixel]; + FrameBuffer[((ActiveLine + ViewStartLine - pce.Settings.TopLine) * VirtualWidth) + xs] = vce.Palette[paletteBase + pixel]; } } @@ -401,7 +401,7 @@ public void RenderSpritesScanline(bool show) { InterSpritePriorityBuffer[xs] = 1; if ((priority || PriorityBuffer[xs] == 0) && show) - FrameBuffer[((ActiveLine + ViewStartLine - pce.Settings.TopLine) * FramePitch) + xs] = vce.Palette[paletteBase + pixel]; + FrameBuffer[((ActiveLine + ViewStartLine - pce.Settings.TopLine) * VirtualWidth) + xs] = vce.Palette[paletteBase + pixel]; } } if (width == 32) @@ -417,7 +417,7 @@ public void RenderSpritesScanline(bool show) { InterSpritePriorityBuffer[xs] = 1; if ((priority || PriorityBuffer[xs] == 0) && show) - FrameBuffer[((ActiveLine + ViewStartLine - pce.Settings.TopLine) * FramePitch) + xs] = vce.Palette[paletteBase + pixel]; + FrameBuffer[((ActiveLine + ViewStartLine - pce.Settings.TopLine) * VirtualWidth) + xs] = vce.Palette[paletteBase + pixel]; } } } @@ -426,21 +426,17 @@ public void RenderSpritesScanline(bool show) } } - private int FramePitch = 320; private int FrameWidth = 320; private int[] FrameBuffer = new int[320 * 262]; - public void Resize_Frame_Buffer_MultiResHack() - { - FrameBuffer = new int[MultiResHack * 262]; - } + public void Resize_Frame_Buffer_MultiResHack() => FrameBuffer = new int[MultiResHack * 262]; // IVideoProvider implementation public int[] GetVideoBuffer() => FrameBuffer; - public int VirtualWidth => FramePitch; + public int VirtualWidth { get; private set; } = 320; public int VirtualHeight => BufferHeight; - public int BufferWidth => FramePitch; + public int BufferWidth => VirtualWidth; public int BufferHeight => (pce.Settings.BottomLine - pce.Settings.TopLine); public int BackgroundColor => vce.Palette[256]; diff --git a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/VDC.cs b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/VDC.cs index 7da92b0ace5..69a84abc02d 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/VDC.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/VDC.cs @@ -23,15 +23,14 @@ public ushort IncrementWidth { get { - switch ((Registers[5] >> 11) & 3) + return ((Registers[5] >> 11) & 3) switch { - case 0: return 1; - case 1: return 32; - case 2: return 64; - case 3: return 128; - } - - return 1; + 0 => 1, + 1 => 32, + 2 => 64, + 3 => 128, + _ => 1, + }; } } @@ -43,7 +42,7 @@ public ushort IncrementWidth public bool SpriteCollisionInterruptEnabled => (Registers[CR] & 0x01) != 0; public bool Sprite4ColorModeEnabled => (Registers[MWR] & 0x0C) == 4; - public int BatWidth { get { switch ((Registers[MWR] >> 4) & 3) { case 0: return 32; case 1: return 64; default: return 128; } } } + public int BatWidth => ((Registers[MWR] >> 4) & 3) switch { 0 => 32, 1 => 64, _ => 128, }; public int BatHeight => (Registers[MWR] & 0x40) == 0 ? 32 : 64; public int RequestedFrameWidth => ((Registers[HDR] & 0x3F) + 1) * 8; @@ -158,7 +157,7 @@ private void RegisterCommit(int register, bool msbComplete) break; case HDR: // Horizontal Display Register - update framebuffer size FrameWidth = RequestedFrameWidth; - FramePitch = MultiResHack == 0 ? FrameWidth : MultiResHack; + VirtualWidth = MultiResHack == 0 ? FrameWidth : MultiResHack; //if (FrameBuffer.Length != FramePitch * FrameHeight) //FrameBuffer = new int[FramePitch * FrameHeight]; break; @@ -168,7 +167,7 @@ private void RegisterCommit(int register, bool msbComplete) //if (FrameHeight > 242) //FrameHeight = 242; if (MultiResHack != 0) - FramePitch = MultiResHack; + VirtualWidth = MultiResHack; //if (FrameBuffer.Length != FramePitch * FrameHeight) //FrameBuffer = new int[FramePitch * FrameHeight]; break; diff --git a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/VPC.cs b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/VPC.cs index 602253077c7..fdb10ca784f 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/VPC.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/VPC.cs @@ -39,25 +39,25 @@ public VPC(PCEngine pce, VDC vdc1, VDC vdc2, VCE vce, HuC6280 cpu) // latch initial video buffer FrameBuffer = vdc1.GetVideoBuffer(); - FrameWidth = vdc1.BufferWidth; - FrameHeight = vdc1.BufferHeight; + BufferWidth = vdc1.BufferWidth; + BufferHeight = vdc1.BufferHeight; } public byte ReadVPC(int port) { port &= 0x0F; - switch (port) + return port switch { - case 0x08: return Registers[0]; - case 0x09: return Registers[1]; - case 0x0A: return Registers[2]; - case 0x0B: return Registers[3]; - case 0x0C: return Registers[4]; - case 0x0D: return Registers[5]; - case 0x0E: return Registers[6]; - case 0x0F: return 0; - default: return 0xFF; - } + 0x08 => Registers[0], + 0x09 => Registers[1], + 0x0A => Registers[2], + 0x0B => Registers[3], + 0x0C => Registers[4], + 0x0D => Registers[5], + 0x0E => Registers[6], + 0x0F => 0, + _ => 0xFF, + }; } public void WriteVPC(int port, byte value) @@ -101,9 +101,6 @@ public void SyncState(Serializer ser) private const int DCR = 15; private int EffectivePriorityMode = 0; - - private int FrameHeight; - private int FrameWidth; private int[] FrameBuffer; private readonly byte[] PriorityBuffer = new byte[512]; @@ -123,8 +120,8 @@ public void ExecFrame(bool render) } // Latch frame dimensions and framebuffer, for purely dumb reasons - FrameWidth = VDC1.BufferWidth; - FrameHeight = VDC1.BufferHeight; + BufferWidth = VDC1.BufferWidth; + BufferHeight = VDC1.BufferHeight; FrameBuffer = VDC1.GetVideoBuffer(); int ScanLine = 0; @@ -272,10 +269,10 @@ private void RenderScanLine() private void InitializeScanLine(int scanline) { // Clear priority buffer - Array.Clear(PriorityBuffer, 0, FrameWidth); + Array.Clear(PriorityBuffer, 0, BufferWidth); // Initialize scanline to background color - for (int i = 0; i < FrameWidth; i++) - FrameBuffer[((scanline + VDC1.ViewStartLine) * FrameWidth) + i] = VCE.Palette[256]; + for (int i = 0; i < BufferWidth; i++) + FrameBuffer[((scanline + VDC1.ViewStartLine) * BufferWidth) + i] = VCE.Palette[256]; } private unsafe void RenderBackgroundScanline(VDC vdc, byte priority, bool show) @@ -299,7 +296,7 @@ private unsafe void RenderBackgroundScanline(VDC vdc, byte priority, bool show) { // pointer to the BAT and the framebuffer for this line ushort* BatRow = VRAMptr + yTile * vdc.BatWidth; - int* dst = FBptr + (vdc.ActiveLine + vdc.ViewStartLine - PCE.Settings.TopLine) * FrameWidth; + int* dst = FBptr + (vdc.ActiveLine + vdc.ViewStartLine - PCE.Settings.TopLine) * BufferWidth; // parameters that change per tile ushort BatEnt; @@ -317,7 +314,7 @@ private unsafe void RenderBackgroundScanline(VDC vdc, byte priority, bool show) paletteBase = paletteNo * 16; src = Patternptr + (tileNo << 6 | yOfs << 3 | xOfs); - for (int x = 0; x < FrameWidth; x++) + for (int x = 0; x < BufferWidth; x++) { if (Priortyptr[x] < priority) { @@ -355,7 +352,7 @@ private void RenderSpritesScanline(VDC vdc, byte lowPriority, byte highPriority, return; // clear inter-sprite priority buffer - Array.Clear(InterSpritePriorityBuffer, 0, FrameWidth); + Array.Clear(InterSpritePriorityBuffer, 0, BufferWidth); var testRange = 0.MutableRangeTo(vdc.ActiveLine + 1); for (int i = 0; i < 64; i++) @@ -446,7 +443,7 @@ private void RenderSpritesScanline(VDC vdc, byte lowPriority, byte highPriority, { if (x + width > 0 && y + height > 0) { - for (int xs = x >= 0 ? x : 0; xs < x + 16 && xs >= 0 && xs < FrameWidth; xs++) + for (int xs = x >= 0 ? x : 0; xs < x + 16 && xs >= 0 && xs < BufferWidth; xs++) { byte pixel = vdc.SpriteBuffer[(patternNo * 256) + (yofs * 16) + (xs - x)]; if (pixel != 0 && InterSpritePriorityBuffer[xs] == 0) @@ -455,7 +452,7 @@ private void RenderSpritesScanline(VDC vdc, byte lowPriority, byte highPriority, byte myPriority = priority ? highPriority : lowPriority; if (PriorityBuffer[xs] < myPriority) { - if (show) FrameBuffer[((vdc.ActiveLine + vdc.ViewStartLine - PCE.Settings.TopLine) * FrameWidth) + xs] = VCE.Palette[paletteBase + pixel]; + if (show) FrameBuffer[((vdc.ActiveLine + vdc.ViewStartLine - PCE.Settings.TopLine) * BufferWidth) + xs] = VCE.Palette[paletteBase + pixel]; PriorityBuffer[xs] = myPriority; } } @@ -465,7 +462,7 @@ private void RenderSpritesScanline(VDC vdc, byte lowPriority, byte highPriority, { patternNo++; x += 16; - for (int xs = x >= 0 ? x : 0; xs < x + 16 && xs >= 0 && xs < FrameWidth; xs++) + for (int xs = x >= 0 ? x : 0; xs < x + 16 && xs >= 0 && xs < BufferWidth; xs++) { byte pixel = vdc.SpriteBuffer[(patternNo * 256) + (yofs * 16) + (xs - x)]; if (pixel != 0 && InterSpritePriorityBuffer[xs] == 0) @@ -474,7 +471,7 @@ private void RenderSpritesScanline(VDC vdc, byte lowPriority, byte highPriority, byte myPriority = priority ? highPriority : lowPriority; if (PriorityBuffer[xs] < myPriority) { - if (show) FrameBuffer[((vdc.ActiveLine + vdc.ViewStartLine - PCE.Settings.TopLine) * FrameWidth) + xs] = VCE.Palette[paletteBase + pixel]; + if (show) FrameBuffer[((vdc.ActiveLine + vdc.ViewStartLine - PCE.Settings.TopLine) * BufferWidth) + xs] = VCE.Palette[paletteBase + pixel]; PriorityBuffer[xs] = myPriority; } } @@ -487,7 +484,7 @@ private void RenderSpritesScanline(VDC vdc, byte lowPriority, byte highPriority, { if (width == 32) patternNo++; - for (int xs = x >= 0 ? x : 0; xs < x + 16 && xs >= 0 && xs < FrameWidth; xs++) + for (int xs = x >= 0 ? x : 0; xs < x + 16 && xs >= 0 && xs < BufferWidth; xs++) { byte pixel = vdc.SpriteBuffer[(patternNo * 256) + (yofs * 16) + 15 - (xs - x)]; if (pixel != 0 && InterSpritePriorityBuffer[xs] == 0) @@ -496,7 +493,7 @@ private void RenderSpritesScanline(VDC vdc, byte lowPriority, byte highPriority, byte myPriority = priority ? highPriority : lowPriority; if (PriorityBuffer[xs] < myPriority) { - if (show) FrameBuffer[((vdc.ActiveLine + vdc.ViewStartLine - PCE.Settings.TopLine) * FrameWidth) + xs] = VCE.Palette[paletteBase + pixel]; + if (show) FrameBuffer[((vdc.ActiveLine + vdc.ViewStartLine - PCE.Settings.TopLine) * BufferWidth) + xs] = VCE.Palette[paletteBase + pixel]; PriorityBuffer[xs] = myPriority; } } @@ -505,7 +502,7 @@ private void RenderSpritesScanline(VDC vdc, byte lowPriority, byte highPriority, { patternNo--; x += 16; - for (int xs = x >= 0 ? x : 0; xs < x + 16 && xs >= 0 && xs < FrameWidth; xs++) + for (int xs = x >= 0 ? x : 0; xs < x + 16 && xs >= 0 && xs < BufferWidth; xs++) { byte pixel = vdc.SpriteBuffer[(patternNo * 256) + (yofs * 16) + 15 - (xs - x)]; if (pixel != 0 && InterSpritePriorityBuffer[xs] == 0) @@ -514,7 +511,7 @@ private void RenderSpritesScanline(VDC vdc, byte lowPriority, byte highPriority, byte myPriority = priority ? highPriority : lowPriority; if (PriorityBuffer[xs] < myPriority) { - if (show) FrameBuffer[((vdc.ActiveLine + vdc.ViewStartLine - PCE.Settings.TopLine) * FrameWidth) + xs] = VCE.Palette[paletteBase + pixel]; + if (show) FrameBuffer[((vdc.ActiveLine + vdc.ViewStartLine - PCE.Settings.TopLine) * BufferWidth) + xs] = VCE.Palette[paletteBase + pixel]; PriorityBuffer[xs] = myPriority; } } @@ -527,10 +524,10 @@ private void RenderSpritesScanline(VDC vdc, byte lowPriority, byte highPriority, // IVideoProvider implementation public int[] GetVideoBuffer() => FrameBuffer; - public int VirtualWidth => FrameWidth; - public int VirtualHeight => FrameHeight; - public int BufferWidth => FrameWidth; - public int BufferHeight => FrameHeight; + public int VirtualWidth => BufferWidth; + public int VirtualHeight => BufferHeight; + public int BufferWidth { get; private set; } + public int BufferHeight { get; private set; } public int BackgroundColor => VCE.Palette[0]; public int VsyncNumerator diff --git a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/VecnaSynchronizer.cs b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/VecnaSynchronizer.cs index 262e53abecb..31e48f64703 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/PC Engine/VecnaSynchronizer.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/PC Engine/VecnaSynchronizer.cs @@ -22,7 +22,7 @@ public class VecnaSynchronizer // If it underflows beyond that threshold, it will give up and output silence. // Since it has done this, it will go ahead and generate some excess silence in order // to restock its excess buffer. - private struct Sample + private readonly struct Sample { public readonly short Left; public readonly short Right; @@ -62,10 +62,7 @@ public void EnqueueSample(short left, short right) _buffer.Enqueue(new Sample(left, right)); } - public void Clear() - { - _buffer.Clear(); - } + public void Clear() => _buffer.Clear(); public int OutputSamples(short[] buf, int samplesRequested) { @@ -85,7 +82,7 @@ public int OutputSamples(short[] buf, int samplesRequested) int index = 0; for (int i = 0; i < samplesRequested; i++) { - Sample sample = _resampleBuffer[i * samplesAvailable / samplesRequested]; + var sample = _resampleBuffer[i * samplesAvailable / samplesRequested]; buf[index++] += sample.Left; buf[index++] += sample.Right; } @@ -102,7 +99,7 @@ public int OutputSamples(short[] buf, int samplesRequested) int index = 0; for (int i = 0; i < samplesRequested && _buffer.Count > 0; i++) { - Sample sample = _buffer.Dequeue(); + var sample = _buffer.Dequeue(); buf[index++] += sample.Left; buf[index++] += sample.Right; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/SNK/NeoGeoPort.cs b/src/BizHawk.Emulation.Cores/Consoles/SNK/NeoGeoPort.cs index 68dd08e2f48..ea17afac65e 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/SNK/NeoGeoPort.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/SNK/NeoGeoPort.cs @@ -21,7 +21,7 @@ public static NymaSettingsInfo CachedSettingsInfo(CoreComm comm) { if (_cachedSettingsInfo is null) { - using var n = new NeoGeoPort(comm); + using NeoGeoPort n = new(comm); n.InitForSettingsInfo("ngp.wbx"); _cachedSettingsInfo = n.SettingsInfo.Clone(); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/GGHawkLink/GGHawkLink.ICodeDataLog.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/GGHawkLink/GGHawkLink.ICodeDataLog.cs index c40d3c73804..4956aa2f3c2 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/GGHawkLink/GGHawkLink.ICodeDataLog.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/GGHawkLink/GGHawkLink.ICodeDataLog.cs @@ -67,7 +67,7 @@ private void RunCDL(ushort address, CDLog_Flags flags) { if (L.MapMemory != null) { - SMS.CDLog_MapResults results = L.MapMemory(address, false); + var results = L.MapMemory(address, false); switch (results.Type) { case SMS.CDLog_AddrType.None: break; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/GGHawkLink/GGHawkLink.IDebuggable.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/GGHawkLink/GGHawkLink.IDebuggable.cs index d6a2348f829..c713e65acfc 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/GGHawkLink/GGHawkLink.IDebuggable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/GGHawkLink/GGHawkLink.IDebuggable.cs @@ -133,16 +133,10 @@ public void SetCpuRegister(string register, int value) public IMemoryCallbackSystem MemoryCallbacks { get; } = new MemoryCallbackSystem(new[] { "System Bus" }); - public bool CanStep(StepType type) - { - return false; - } + public bool CanStep(StepType type) => false; [FeatureNotImplemented] - public void Step(StepType type) - { - throw new NotImplementedException(); - } + public void Step(StepType type) => throw new NotImplementedException(); public long TotalExecutedCycles => L.Cpu.TotalExecutedCycles; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/GGHawkLink/GGHawkLink.IEmulator.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/GGHawkLink/GGHawkLink.IEmulator.cs index 8b6d4c9797d..05a5343cd49 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/GGHawkLink/GGHawkLink.IEmulator.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/GGHawkLink/GGHawkLink.IEmulator.cs @@ -296,10 +296,7 @@ public void Dispose() public int[] buff_L = new int[160 * 144]; public int[] buff_R = new int[160 * 144]; - public int[] GetVideoBuffer() - { - return _vidbuffer; - } + public int[] GetVideoBuffer() => _vidbuffer; public void FillVideoBuffer() { @@ -364,10 +361,7 @@ public void GetSamplesSync(out short[] samples, out int nsamp) } } - public void GetSamplesAsync(short[] samples) - { - throw new NotSupportedException("Async is not available"); - } + public void GetSamplesAsync(short[] samples) => throw new NotSupportedException("Async is not available"); public void DiscardSamples() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/GGHawkLink/GGHawkLink.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/GGHawkLink/GGHawkLink.IMemoryDomains.cs index a13885a9308..3302ab493bd 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/GGHawkLink/GGHawkLink.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/GGHawkLink/GGHawkLink.IMemoryDomains.cs @@ -9,7 +9,7 @@ public partial class GGHawkLink public void SetupMemoryDomains() { - var domains = new List + List domains = new() { new MemoryDomainDelegate( "Main RAM L", @@ -71,13 +71,13 @@ public void SetupMemoryDomains() if (L.SaveRAM != null) { - var cartRamL = new MemoryDomainByteArray("Cart RAM L", MemoryDomain.Endian.Little, L.SaveRAM, true, 1); + MemoryDomainByteArray cartRamL = new("Cart RAM L", MemoryDomain.Endian.Little, L.SaveRAM, true, 1); domains.Add(cartRamL); } if (R.SaveRAM != null) { - var cartRamR = new MemoryDomainByteArray("Cart RAM R", MemoryDomain.Endian.Little, R.SaveRAM, true, 1); + MemoryDomainByteArray cartRamR = new("Cart RAM R", MemoryDomain.Endian.Little, R.SaveRAM, true, 1); domains.Add(cartRamR); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/GGHawkLink/GGHawkLink.ISettable.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/GGHawkLink/GGHawkLink.ISettable.cs index ef73861f284..c74daa63af7 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/GGHawkLink/GGHawkLink.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/GGHawkLink/GGHawkLink.ISettable.cs @@ -6,15 +6,9 @@ namespace BizHawk.Emulation.Cores.Sega.GGHawkLink { public partial class GGHawkLink : IEmulator, IStatable, ISettable { - public GGLinkSettings GetSettings() - { - return linkSettings.Clone(); - } + public GGLinkSettings GetSettings() => linkSettings.Clone(); - public GGLinkSyncSettings GetSyncSettings() - { - return linkSyncSettings.Clone(); - } + public GGLinkSyncSettings GetSyncSettings() => linkSyncSettings.Clone(); public PutSettingsDirtyBits PutSettings(GGLinkSettings o) { @@ -29,8 +23,8 @@ public PutSettingsDirtyBits PutSyncSettings(GGLinkSyncSettings o) return ret ? PutSettingsDirtyBits.RebootCore : PutSettingsDirtyBits.None; } - private GGLinkSettings linkSettings = new GGLinkSettings(); - public GGLinkSyncSettings linkSyncSettings = new GGLinkSyncSettings(); + private GGLinkSettings linkSettings = new(); + public GGLinkSyncSettings linkSyncSettings = new(); public class GGLinkSettings { @@ -46,10 +40,7 @@ public enum AudioSrc [DefaultValue(AudioSrc.Left)] public AudioSrc AudioSet { get; set; } - public GGLinkSettings Clone() - { - return (GGLinkSettings)MemberwiseClone(); - } + public GGLinkSettings Clone() => (GGLinkSettings)MemberwiseClone(); } public class GGLinkSyncSettings @@ -60,15 +51,9 @@ public class GGLinkSyncSettings [DefaultValue(true)] public bool Use_SRAM { get; set; } - public GGLinkSyncSettings Clone() - { - return (GGLinkSyncSettings)MemberwiseClone(); - } + public GGLinkSyncSettings Clone() => (GGLinkSyncSettings)MemberwiseClone(); - public static bool NeedsReboot(GGLinkSyncSettings x, GGLinkSyncSettings y) - { - return !DeepEquality.DeepEquals(x, y); - } + public static bool NeedsReboot(GGLinkSyncSettings x, GGLinkSyncSettings y) => !DeepEquality.DeepEquals(x, y); } } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/GGHawkLink/GGHawkLink.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/GGHawkLink/GGHawkLink.cs index 529d460f7bc..22093e8ba4e 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/GGHawkLink/GGHawkLink.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/GGHawkLink/GGHawkLink.cs @@ -27,17 +27,17 @@ public GGHawkLink(CoreLoadParameters lp) if (lp.Roms.Count != 2) throw new InvalidOperationException("Wrong number of roms"); - var ser = new BasicServiceProvider(this); + BasicServiceProvider ser = new(this); linkSettings = lp.Settings ?? new GGLinkSettings(); linkSyncSettings = lp.SyncSettings ?? new GGLinkSyncSettings(); _controllerDeck = new GGHawkLinkControllerDeck(GGHawkLinkControllerDeck.DefaultControllerName, GGHawkLinkControllerDeck.DefaultControllerName); - var temp_set_L = new SMS.SmsSettings(); - var temp_set_R = new SMS.SmsSettings(); + SMS.SmsSettings temp_set_L = new(); + SMS.SmsSettings temp_set_R = new(); - var temp_sync_L = new SMS.SmsSyncSettings(); - var temp_sync_R = new SMS.SmsSyncSettings(); + SMS.SmsSyncSettings temp_sync_L = new(); + SMS.SmsSyncSettings temp_sync_R = new(); L = new SMS(lp.Comm, lp.Roms[0].Game, lp.Roms[0].RomData, temp_set_L, temp_sync_L); R = new SMS(lp.Comm, lp.Roms[1].Game, lp.Roms[1].RomData, temp_set_R, temp_sync_R); @@ -81,10 +81,12 @@ public bool LinkConnected set => _cableconnected = value; } + #pragma warning disable IDE0051 private void ExecFetch(ushort addr) { uint flags = (uint)MemoryCallbackFlags.AccessExecute; MemoryCallbacks.CallMemoryCallbacks(addr, 0, flags, "System Bus"); } + #pragma warning restore IDE0051 } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/GGHawkLink/GGHawkLinkControllerDeck.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/GGHawkLink/GGHawkLinkControllerDeck.cs index 6c29341cf65..505d65717f3 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/GGHawkLink/GGHawkLinkControllerDeck.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/GGHawkLink/GGHawkLinkControllerDeck.cs @@ -28,15 +28,9 @@ public GGHawkLinkControllerDeck(string controller1Name, string controller2Name) }.MakeImmutable(); } - public byte ReadPort1(IController c) - { - return Port1.Read(c); - } + public byte ReadPort1(IController c) => Port1.Read(c); - public byte ReadPort2(IController c) - { - return Port2.Read(c); - } + public byte ReadPort2(IController c) => Port2.Read(c); public ControllerDefinition Definition { get; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/PicoDrive/PicoDrive.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/PicoDrive/PicoDrive.cs index d768bd9f01f..95450ffbec0 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/PicoDrive/PicoDrive.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/PicoDrive/PicoDrive.cs @@ -35,10 +35,10 @@ private PicoDrive(CoreComm comm, GameInfo game, byte[] rom, Disc cd, bool determ SystemId = VSystemID.Raw.GEN, }) { - var biosg = comm.CoreFileProvider.GetFirmware(new("32X", "G")); - var biosm = comm.CoreFileProvider.GetFirmware(new("32X", "M")); - var bioss = comm.CoreFileProvider.GetFirmware(new("32X", "S")); - var has32xBios = biosg != null && biosm != null && bioss != null; + byte[] biosg = comm.CoreFileProvider.GetFirmware(new("32X", "G")); + byte[] biosm = comm.CoreFileProvider.GetFirmware(new("32X", "M")); + byte[] bioss = comm.CoreFileProvider.GetFirmware(new("32X", "S")); + bool has32xBios = biosg != null && biosm != null && bioss != null; if (deterministic && !has32xBios) throw new InvalidOperationException("32X BIOS files are required for deterministic mode"); deterministic |= has32xBios; @@ -82,7 +82,7 @@ private PicoDrive(CoreComm comm, GameInfo game, byte[] rom, Disc cd, bool determ _exe.AddReadonlyFile(rom, "romfile.md"); } - var regionAutoOrder = (LibPicoDrive.Region)( + LibPicoDrive.Region regionAutoOrder = (LibPicoDrive.Region)( (int)_syncSettings.FirstChoice | (int)_syncSettings.SecondChoice << 4 | (int)_syncSettings.ThirdChoice << 8); @@ -142,9 +142,9 @@ private PicoDrive(CoreComm comm, GameInfo game, byte[] rom, Disc cd, bool determ protected override LibWaterboxCore.FrameInfo FrameAdvancePrep(IController controller, bool render, bool rendersound) { - var b = 0; - var v = 1; - foreach (var s in ButtonOrders) + int b = 0; + int v = 1; + foreach (string s in ButtonOrders) { if (controller.IsPressed(s)) b |= v; @@ -174,10 +174,7 @@ private void CDRead(int lba, IntPtr dest, bool audio) } } - protected override void LoadStateBinaryInternal(BinaryReader reader) - { - _core.SetCDReadCallback(_cdcallback); - } + protected override void LoadStateBinaryInternal(BinaryReader reader) => _core.SetCDReadCallback(_cdcallback); public class SyncSettings { @@ -197,15 +194,9 @@ public class SyncSettings [Description("When region is set to automatic, lowest priority region to use if the game supports multiple regions")] public LibPicoDrive.Region ThirdChoice { get; set; } - public SyncSettings Clone() - { - return (SyncSettings)MemberwiseClone(); - } + public SyncSettings Clone() => (SyncSettings)MemberwiseClone(); - public static bool NeedsReboot(SyncSettings x, SyncSettings y) - { - return !DeepEquality.DeepEquals(x, y); - } + public static bool NeedsReboot(SyncSettings x, SyncSettings y) => !DeepEquality.DeepEquals(x, y); public SyncSettings() { @@ -215,24 +206,15 @@ public SyncSettings() private SyncSettings _syncSettings; - public object GetSettings() - { - return new object(); - } + public object GetSettings() => new(); - public SyncSettings GetSyncSettings() - { - return _syncSettings.Clone(); - } + public SyncSettings GetSyncSettings() => _syncSettings.Clone(); - public PutSettingsDirtyBits PutSettings(object o) - { - return PutSettingsDirtyBits.None; - } + public PutSettingsDirtyBits PutSettings(object o) => PutSettingsDirtyBits.None; public PutSettingsDirtyBits PutSyncSettings(SyncSettings o) { - var ret = SyncSettings.NeedsReboot(_syncSettings, o); + bool ret = SyncSettings.NeedsReboot(_syncSettings, o); _syncSettings = o; return ret ? PutSettingsDirtyBits.RebootCore : PutSettingsDirtyBits.None; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/MemoryMap.EEPROM.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/MemoryMap.EEPROM.cs index 267c0b2d30f..080d7de9e57 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/MemoryMap.EEPROM.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/MemoryMap.EEPROM.cs @@ -69,14 +69,13 @@ private CDLog_MapResults MapMemoryEEPROM(ushort address, bool write) return new CDLog_MapResults { Type = CDLog_AddrType.ROM, Address = (RomBank0 * BankSize) + address }; if (address < 0x8000) return new CDLog_MapResults { Type = CDLog_AddrType.ROM, Address = (RomBank1 * BankSize) + (address & BankSizeMask) }; - switch (SaveRamBank) + return SaveRamBank switch { - case 0: return new CDLog_MapResults { Type = CDLog_AddrType.ROM, Address = (RomBank2 * BankSize) + (address & BankSizeMask) }; - case 1: return new CDLog_MapResults(); // a serial IO port - case 2: return new CDLog_MapResults(); // a serial IO port - default: - return new CDLog_MapResults { Type = CDLog_AddrType.MainRAM, Address = address & RamSizeMask }; - } + 0 => new CDLog_MapResults { Type = CDLog_AddrType.ROM, Address = (RomBank2 * BankSize) + (address & BankSizeMask) }, + 1 => new CDLog_MapResults(),// a serial IO port + 2 => new CDLog_MapResults(),// a serial IO port + _ => new CDLog_MapResults { Type = CDLog_AddrType.MainRAM, Address = address & RamSizeMask }, + }; } return new CDLog_MapResults { Type = CDLog_AddrType.MainRAM, Address = address & RamSizeMask }; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/MemoryMap.ExtRam.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/MemoryMap.ExtRam.cs index 2d37ecb6f85..96eaf27d3bc 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/MemoryMap.ExtRam.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/MemoryMap.ExtRam.cs @@ -28,7 +28,7 @@ private CDLog_MapResults MapMemoryExt(ushort address, bool write) private void WriteMemoryExt(ushort address, byte value) { - if (address < 0xC000 && address >= 0x8000) + if (address is < 0xC000 and >= 0x8000) ExtRam[address & ExtRamMask] = value; else if (address >= 0xC000) SystemRam[address & RamSizeMask] = value; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/MemoryMap.SG_EX_A.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/MemoryMap.SG_EX_A.cs index 7cd44c6b4ad..f6f3e57b74d 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/MemoryMap.SG_EX_A.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/MemoryMap.SG_EX_A.cs @@ -28,7 +28,7 @@ private CDLog_MapResults MapMemorySG_EX_A(ushort address, bool write) private void WriteMemorySG_EX_A(ushort address, byte value) { - if (address < 0x4000 && address >= 0x2000) + if (address is < 0x4000 and >= 0x2000) ExtRam[address & ExtRamMask] = value; else if (address >= 0xC000) SystemRam[address & 0x3FF] = value; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMS.ICodeDataLogger.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMS.ICodeDataLogger.cs index 477fbfdaa31..7e68c1dbbe8 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMS.ICodeDataLogger.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMS.ICodeDataLogger.cs @@ -73,7 +73,7 @@ public void RunCDL(ushort address, CDLog_Flags flags) { if (MapMemory != null) { - CDLog_MapResults results = MapMemory(address, false); + var results = MapMemory(address, false); switch (results.Type) { case CDLog_AddrType.None: break; diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMS.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMS.IMemoryDomains.cs index 3801f193e69..99789c77002 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMS.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMS.IMemoryDomains.cs @@ -9,12 +9,12 @@ namespace BizHawk.Emulation.Cores.Sega.MasterSystem public partial class SMS { private MemoryDomainList MemoryDomains; - private readonly Dictionary _byteArrayDomains = new Dictionary(); + private readonly Dictionary _byteArrayDomains = new(); private bool _memoryDomainsInit = false; private void SetupMemoryDomains() { - var domains = new List + List domains = new() { new MemoryDomainDelegate("System Bus", 0x10000, MemoryDomain.Endian.Little, (addr) => @@ -31,7 +31,7 @@ private void SetupMemoryDomains() if (SaveRAM != null) { - var saveRamDomain = new MemoryDomainDelegate("Save RAM", SaveRAM.Length, MemoryDomain.Endian.Little, + MemoryDomainDelegate saveRamDomain = new("Save RAM", SaveRAM.Length, MemoryDomain.Endian.Little, addr => SaveRAM[addr], (addr, value) => { SaveRAM[addr] = value; SaveRamModified = true; }, 1); domains.Add(saveRamDomain); @@ -66,7 +66,7 @@ private void SyncByteArrayDomain(string name, byte[] data) } else { - var m = new MemoryDomainByteArray(name, MemoryDomain.Endian.Little, data, true, 1); + MemoryDomainByteArray m = new(name, MemoryDomain.Endian.Little, data, true, 1); _byteArrayDomains.Add(name, m); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMS.ISaveRam.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMS.ISaveRam.cs index 20ab96123a6..0b85a2bd1e1 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMS.ISaveRam.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMS.ISaveRam.cs @@ -6,10 +6,7 @@ namespace BizHawk.Emulation.Cores.Sega.MasterSystem { public partial class SMS : ISaveRam { - public byte[] CloneSaveRam() - { - return (byte[]) SaveRAM?.Clone(); - } + public byte[] CloneSaveRam() => (byte[])SaveRAM?.Clone(); public void StoreSaveRam(byte[] data) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMS.ISoundProvider.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMS.ISoundProvider.cs index f97b5bf2f90..f3d44bbeec6 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMS.ISoundProvider.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMS.ISoundProvider.cs @@ -50,10 +50,7 @@ public void GetSamplesSync(out short[] samples, out int nsamp) SampleClock = 0; } - public void GetSamplesAsync(short[] samples) - { - throw new NotSupportedException("Async not supported"); - } + public void GetSamplesAsync(short[] samples) => throw new NotSupportedException("Async not supported"); public void DiscardSamples() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMS.IStatable.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMS.IStatable.cs index ba0d11071b0..df2818574f0 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMS.IStatable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMS.IStatable.cs @@ -10,7 +10,7 @@ private void SyncState(Serializer ser) byte[] core = null; if (ser.IsWriter) { - using var ms = new MemoryStream(); + using MemoryStream ms = new(); ms.Close(); core = ms.ToArray(); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMS.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMS.cs index 3d281368297..1bd13556520 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMS.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMS.cs @@ -24,7 +24,7 @@ public partial class SMS : IEmulator, ISoundProvider, ISaveRam, IInputPollable, [CoreConstructor(VSystemID.Raw.GG)] public SMS(CoreComm comm, GameInfo game, byte[] rom, SmsSettings settings, SmsSyncSettings syncSettings) { - var ser = new BasicServiceProvider(this); + BasicServiceProvider ser = new(this); ServiceProvider = ser; Settings = settings ?? new SmsSettings(); SyncSettings = syncSettings ?? new SmsSyncSettings(); @@ -259,7 +259,7 @@ public void HardReset() private readonly bool HasYM2413 = false; private bool disablePSG = false; - private bool PortDEEnabled = false; + private readonly bool PortDEEnabled = false; private IController _controller = NullController.Instance; private int _frame = 0; @@ -312,7 +312,7 @@ private DisplayType DetermineDisplayType(SmsSyncSettings.DisplayTypes display, s { if (display == SmsSyncSettings.DisplayTypes.Ntsc) return DisplayType.NTSC; if (display == SmsSyncSettings.DisplayTypes.Pal) return DisplayType.PAL; - if (region != null && region == "Europe") return DisplayType.PAL; + if (region is not null and "Europe") return DisplayType.PAL; return DisplayType.NTSC; } @@ -338,10 +338,7 @@ public void WriteMemory(ushort addr, byte value) } } - public byte FetchMemory(ushort addr) - { - return ReadMemoryMapper(addr); - } + public byte FetchMemory(ushort addr) => ReadMemoryMapper(addr); private void OnExecMemory(ushort addr) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMSControllerDeck.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMSControllerDeck.cs index ac46a247a0a..0693886204b 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMSControllerDeck.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMSControllerDeck.cs @@ -58,55 +58,25 @@ public SMSControllerDeck(SMSControllerTypes controller1, SMSControllerTypes cont Definition.MakeImmutable(); } - public byte ReadPort1_c1(IController c) - { - return Port1.Read_p1_c1(c); - } + public byte ReadPort1_c1(IController c) => Port1.Read_p1_c1(c); - public byte ReadPort1_c2(IController c) - { - return Port2.Read_p1_c2(c); - } + public byte ReadPort1_c2(IController c) => Port2.Read_p1_c2(c); - public byte ReadPort2_c1(IController c) - { - return Port1.Read_p2_c1(c); - } + public byte ReadPort2_c1(IController c) => Port1.Read_p2_c1(c); - public byte ReadPort2_c2(IController c) - { - return Port2.Read_p2_c2(c); - } + public byte ReadPort2_c2(IController c) => Port2.Read_p2_c2(c); - public bool GetPin_c1(IController c) - { - return Port1.PinStateGet(c); - } + public bool GetPin_c1(IController c) => Port1.PinStateGet(c); - public bool GetPin_c2(IController c) - { - return Port2.PinStateGet(c); - } + public bool GetPin_c2(IController c) => Port2.PinStateGet(c); - public void SetPin_c1(IController c, bool val) - { - Port1.PinStateSet(c, val); - } + public void SetPin_c1(IController c, bool val) => Port1.PinStateSet(c, val); - public void SetPin_c2(IController c, bool val) - { - Port2.PinStateSet(c, val); - } + public void SetPin_c2(IController c, bool val) => Port2.PinStateSet(c, val); - public void SetCounter_c1(IController c, int val) - { - Port1.CounterSet(c, val); - } + public void SetCounter_c1(IController c, int val) => Port1.CounterSet(c, val); - public void SetCounter_c2(IController c, int val) - { - Port2.CounterSet(c, val); - } + public void SetCounter_c2(IController c, int val) => Port2.CounterSet(c, val); public void SetRegion(IController c, bool val) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMSControllers.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMSControllers.cs index e2b9596099b..8515da43917 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMSControllers.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/SMSControllers.cs @@ -103,7 +103,7 @@ public byte Read_p2_c2(IController c) return result; } - public bool PinStateGet(IController c) { return false; } + public bool PinStateGet(IController c) => false; public void PinStateSet(IController c, bool val) { } @@ -175,7 +175,7 @@ public byte Read_p2_c2(IController c) return result; } - public bool PinStateGet(IController c) { return false; } + public bool PinStateGet(IController c) => false; public void PinStateSet(IController c, bool val) { } @@ -307,9 +307,9 @@ public byte Read_p2_c2(IController c) return result; } - public bool PinStateGet(IController c) { return pin; } + public bool PinStateGet(IController c) => pin; - public void PinStateSet(IController c, bool val) { pin = val;} + public void PinStateSet(IController c, bool val) => pin = val; public void CounterSet(IController c, int val) { } @@ -320,10 +320,7 @@ public void RegionSet(IController c, bool val) { } "Left", "Right", "B1" }; - public void SyncState(Serializer ser) - { - ser.Sync(nameof(pin), ref pin); - } + public void SyncState(Serializer ser) => ser.Sync(nameof(pin), ref pin); } [DisplayName("SMS Sports Pad Controller")] @@ -594,13 +591,13 @@ public byte Read_p2_c2(IController c) return result; } - public bool PinStateGet(IController c) { return pin; } + public bool PinStateGet(IController c) => pin; - public void PinStateSet(IController c, bool val) { pin = val; } + public void PinStateSet(IController c, bool val) => pin = val; - public void CounterSet(IController c, int val) { ControllerCounter = val; } + public void CounterSet(IController c, int val) => ControllerCounter = val; - public void RegionSet(IController c, bool val) { is_JPN = val; } + public void RegionSet(IController c, bool val) => is_JPN = val; private static readonly string[] BaseDefinition = { @@ -663,7 +660,7 @@ public byte Read_p2_c2(IController c) return result; } - public bool PinStateGet(IController c) { return false; } + public bool PinStateGet(IController c) => false; public void PinStateSet(IController c, bool val) { } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/VDP.Mode4.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/VDP.Mode4.cs index 623a70c60b8..4688ca325ef 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/VDP.Mode4.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/VDP.Mode4.cs @@ -343,7 +343,7 @@ internal void ProcessOverscan() // Handles GG clipping or highlighting internal void ProcessGGScreen() { - if (mode != VdpMode.GameGear) + if (VdpMode != VdpMode.GameGear) return; if (Sms.Settings.ShowClippedRegions == false) diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/VDP.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/VDP.cs index cc497188452..8eb4fa55705 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/VDP.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/SMS/VDP.cs @@ -32,13 +32,12 @@ public partial class VDP : IVideoProvider private int lineIntLinesRemaining; private readonly SMS Sms; - private readonly VdpMode mode; public DisplayType DisplayType = DisplayType.NTSC; private readonly Z80A Cpu; public bool SpriteLimit; public int IPeriod = 228; - public VdpMode VdpMode => mode; + public VdpMode VdpMode { get; } public int FrameHeight = 192; public int ScanLine; @@ -75,11 +74,11 @@ public partial class VDP : IVideoProvider // older versions fo the SMS VDP have a masking bit in register two that effects mirroring. // This is needed for Ys (JPN) in the status bar private int NameTableMaskBit; - private bool JPN_Compat =false; + private readonly bool JPN_Compat =false; // For SMS, the last 8 x-tiles are fixed if vertscroll (reg[0].bit(7)) is set, but on GG it must be // only the last 7 or Fray displays incorrectly - private int lock_tile_start; + private readonly int lock_tile_start; // preprocessed state assist stuff. public int[] Palette = new int[32]; @@ -95,7 +94,7 @@ public VDP(SMS sms, Z80A cpu, VdpMode mode, DisplayType displayType, bool region { Sms = sms; Cpu = cpu; - this.mode = mode; + this.VdpMode = mode; if (mode == VdpMode.SMS) CRAM = new byte[32]; if (mode == VdpMode.GameGear) CRAM = new byte[64]; DisplayType = displayType; @@ -145,10 +144,7 @@ public byte ReadVLineCounter() } } - public byte ReadHLineCounter() - { - return HCounter; - } + public byte ReadHLineCounter() => HCounter; public void WriteVdpControl(byte value) { @@ -205,7 +201,7 @@ public void WriteVdpData(byte value) public void UpdatePrecomputedPalette() { - if (mode == VdpMode.SMS) + if (VdpMode == VdpMode.SMS) { for (int i = 0; i < 32; i++) { @@ -443,13 +439,13 @@ public void SyncState(Serializer ser) public int[] GetVideoBuffer() { - if (mode == VdpMode.SMS && Sms.Settings.DisplayOverscan) + if (VdpMode == VdpMode.SMS && Sms.Settings.DisplayOverscan) { if (OverscanFrameBuffer == null) ProcessOverscan(); return OverscanFrameBuffer; } - if (mode == VdpMode.SMS || Sms.Settings.ShowClippedRegions) + if (VdpMode == VdpMode.SMS || Sms.Settings.ShowClippedRegions) return FrameBuffer; return GameGearFrameBuffer; } @@ -458,9 +454,9 @@ public int VirtualWidth { get { - if (mode == VdpMode.SMS && Sms.Settings.DisplayOverscan) + if (VdpMode == VdpMode.SMS && Sms.Settings.DisplayOverscan) return OverscanFrameWidth; - if (mode == VdpMode.SMS) + if (VdpMode == VdpMode.SMS) return 293; if (Sms.Settings.ShowClippedRegions) return 256; @@ -473,9 +469,9 @@ public int BufferWidth { get { - if (mode == VdpMode.SMS && Sms.Settings.DisplayOverscan) + if (VdpMode == VdpMode.SMS && Sms.Settings.DisplayOverscan) return OverscanFrameWidth; - if (mode == VdpMode.SMS || Sms.Settings.ShowClippedRegions) + if (VdpMode == VdpMode.SMS || Sms.Settings.ShowClippedRegions) return 256; return 160; // GameGear } @@ -485,9 +481,9 @@ public int BufferHeight { get { - if (mode == VdpMode.SMS && Sms.Settings.DisplayOverscan) + if (VdpMode == VdpMode.SMS && Sms.Settings.DisplayOverscan) return OverscanFrameHeight; - if (mode == VdpMode.SMS || Sms.Settings.ShowClippedRegions) + if (VdpMode == VdpMode.SMS || Sms.Settings.ShowClippedRegions) return FrameHeight; return 144; // GameGear } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/Saturn/Saturnus.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/Saturn/Saturnus.cs index 88cb73249d4..96fc3fb35e0 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/Saturn/Saturnus.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/Saturn/Saturnus.cs @@ -20,7 +20,7 @@ public static NymaSettingsInfo CachedSettingsInfo(CoreComm comm) { if (_cachedSettingsInfo is null) { - using var n = new Saturnus(comm); + using Saturnus n = new(comm); n.InitForSettingsInfo("ss.wbx"); _cachedSettingsInfo = n.SettingsInfo.Clone(); } @@ -34,7 +34,7 @@ public Saturnus(CoreLoadParameters lp) { if (lp.Roms.Count > 0) throw new InvalidOperationException("To load a Saturn game, please load the CUE file and not the BIN file."); - var firmwares = new Dictionary + Dictionary firmwares = new() { { "FIRMWARE:$J", new("SAT", "J") }, { "FIRMWARE:$U", new("SAT", "U") }, @@ -86,13 +86,13 @@ public Saturnus(CoreLoadParameters lp) protected override HashSet ComputeHiddenPorts() { - var devCount = 12; + int devCount = 12; if (SettingsQuery("ss.input.sport1.multitap") != "1") devCount -= 5; if (SettingsQuery("ss.input.sport2.multitap") != "1") devCount -= 5; - var ret = new HashSet(); - for (var i = 1; i <= 12; i++) + HashSet ret = new(); + for (int i = 1; i <= 12; i++) { if (i > devCount) ret.Add($"port{i}"); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.ICodeDataLogger.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.ICodeDataLogger.cs index d2f992cb9f3..dd78b9994be 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.ICodeDataLogger.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.ICodeDataLogger.cs @@ -38,15 +38,14 @@ private void CDCallbackProc(int addr, LibGPGX.CDLog_AddrType addrtype, LibGPGX.C if (CDL == null) return; if (!CDL.Active) return; - string key; - switch (addrtype) + string key = addrtype switch { - case LibGPGX.CDLog_AddrType.MDCART: key = "MD CART"; break; - case LibGPGX.CDLog_AddrType.RAM68k: key = "68K RAM"; break; - case LibGPGX.CDLog_AddrType.RAMZ80: key = "Z80 RAM"; break; - case LibGPGX.CDLog_AddrType.SRAM: key = "SRAM"; break; - default: throw new InvalidOperationException("Lagrangian earwax incident"); - } + LibGPGX.CDLog_AddrType.MDCART => "MD CART", + LibGPGX.CDLog_AddrType.RAM68k => "68K RAM", + LibGPGX.CDLog_AddrType.RAMZ80 => "Z80 RAM", + LibGPGX.CDLog_AddrType.SRAM => "SRAM", + _ => throw new InvalidOperationException("Lagrangian earwax incident"), + }; CDL[key][addr] |= (byte)flags; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.IDebuggable.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.IDebuggable.cs index 6647386c465..2e6f5abf9bb 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.IDebuggable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.IDebuggable.cs @@ -16,7 +16,7 @@ public IDictionary GetCpuFlagsAndRegisters() int n = Core.gpgx_getregs(regs); if (n > regs.Length) throw new InvalidOperationException("A buffer overrun has occured!"); - var ret = new Dictionary(); + Dictionary ret = new(); using (_elf.EnterExit()) { for (int i = 0; i < n; i++) @@ -35,22 +35,19 @@ public IDictionary GetCpuFlagsAndRegisters() } [FeatureNotImplemented] - public void SetCpuRegister(string register, int value) - { - throw new NotImplementedException(); - } + public void SetCpuRegister(string register, int value) => throw new NotImplementedException(); public IMemoryCallbackSystem MemoryCallbacks => _memoryCallbacks; - public bool CanStep(StepType type) { return false; } + public bool CanStep(StepType type) => false; [FeatureNotImplemented] - public void Step(StepType type) { throw new NotImplementedException(); } + public void Step(StepType type) => throw new NotImplementedException(); [FeatureNotImplemented] public long TotalExecutedCycles => throw new NotImplementedException(); - private readonly MemoryCallbackSystem _memoryCallbacks = new MemoryCallbackSystem(new[] { "M68K BUS" }); + private readonly MemoryCallbackSystem _memoryCallbacks = new(new[] { "M68K BUS" }); private LibGPGX.mem_cb ExecCallback; private LibGPGX.mem_cb ReadCallback; @@ -94,9 +91,6 @@ private void RefreshMemCallbacks() MemoryCallbacks.HasExecutes ? ExecCallback : null); } - private void KillMemCallbacks() - { - Core.gpgx_set_mem_callback(null, null, null); - } + private void KillMemCallbacks() => Core.gpgx_set_mem_callback(null, null, null); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.IDisassembler.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.IDisassembler.cs index ebf79160186..8906f8d989a 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.IDisassembler.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.IDisassembler.cs @@ -34,6 +34,6 @@ public string Disassemble(MemoryDomain m, uint addr, out int length) } // TODO: refactor MC6800's disassembler to be a static call - private readonly MC68000 _disassemblerInstance = new MC68000(); + private readonly MC68000 _disassemblerInstance = new(); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.IEmulator.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.IEmulator.cs index 4b6ef954b12..465fd945503 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.IEmulator.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.IEmulator.cs @@ -17,8 +17,8 @@ public bool FrameAdvance(IController controller, bool render, bool renderSound = Core.gpgx_reset(true); if (_cds != null) { - var prev = controller.IsPressed("Previous Disk"); - var next = controller.IsPressed("Next Disk"); + bool prev = controller.IsPressed("Previous Disk"); + bool next = controller.IsPressed("Next Disk"); int newDisk = _discIndex; if (prev && !_prevDiskPressed) newDisk--; @@ -45,8 +45,8 @@ public bool FrameAdvance(IController controller, bool render, bool renderSound = // if (!Core.gpgx_get_control(input, inputsize)) // throw new Exception("gpgx_get_control() failed!"); - ControlConverter.ScreenWidth = _vwidth; - ControlConverter.ScreenHeight = _vheight; + ControlConverter.ScreenWidth = BufferWidth; + ControlConverter.ScreenHeight = BufferHeight; ControlConverter.Convert(controller, input); if (!Core.gpgx_put_control(input, inputsize)) diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.IInputPollable.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.IInputPollable.cs index 008b1ab06ac..0dd170c5500 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.IInputPollable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.IInputPollable.cs @@ -12,7 +12,7 @@ public partial class GPGX : IInputPollable private readonly LibGPGX.input_cb _inputCallback; - private readonly InputCallbackSystem _inputCallbacks = new InputCallbackSystem(); + private readonly InputCallbackSystem _inputCallbacks = new(); private void input_callback() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.IMemoryDomains.cs index 49f16344e8c..30308aaeab1 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.IMemoryDomains.cs @@ -15,15 +15,15 @@ private unsafe void SetMemoryDomains() { using (_elf.EnterExit()) { - var mm = new List(); - for (var i = LibGPGX.MIN_MEM_DOMAIN; i <= LibGPGX.MAX_MEM_DOMAIN; i++) + List mm = new(); + for (int i = LibGPGX.MIN_MEM_DOMAIN; i <= LibGPGX.MAX_MEM_DOMAIN; i++) { var area = IntPtr.Zero; - var size = 0; + int size = 0; var pName = Core.gpgx_get_memdom(i, ref area, ref size); if (area == IntPtr.Zero || pName == IntPtr.Zero || size == 0) continue; - var name = Marshal.PtrToStringAnsi(pName)!; + string name = Marshal.PtrToStringAnsi(pName)!; var endian = name == "Z80 RAM" ? MemoryDomain.Endian.Little @@ -32,7 +32,7 @@ private unsafe void SetMemoryDomains() if (name == "VRAM") { // vram pokes need to go through hook which invalidates cached tiles - var p = (byte*)area; + byte* p = (byte*)area; mm.Add(new MemoryDomainDelegate(name, size, MemoryDomain.Endian.Big, addr => { @@ -51,14 +51,14 @@ private unsafe void SetMemoryDomains() { // CRAM in the core is internally a different format than what it is natively // this internal format isn't really useful, so let's convert it back - var p = (byte*)area; + byte* p = (byte*)area; mm.Add(new MemoryDomainDelegate(name, size, MemoryDomain.Endian.Big, addr => { if (addr is < 0 or > 0x7F) throw new ArgumentOutOfRangeException(paramName: nameof(addr), addr, message: "address out of range"); using (_elf.EnterExit()) { - var c = *(ushort*)&p![addr & ~1]; + ushort c = *(ushort*)&p![addr & ~1]; c = (ushort)(((c & 0x1C0) << 3) | ((c & 0x038) << 2) | ((c & 0x007) << 1)); return (byte)((addr & 1) != 0 ? c & 0xFF : c >> 8); } @@ -79,16 +79,16 @@ private unsafe void SetMemoryDomains() mm.Add(new MemoryDomainIntPtrSwap16Monitor(name, endian, area, size, true, _elf)); } } - var m68Bus = new MemoryDomainDelegate("M68K BUS", 0x1000000, MemoryDomain.Endian.Big, + MemoryDomainDelegate m68Bus = new("M68K BUS", 0x1000000, MemoryDomain.Endian.Big, addr => { - var a = (uint)addr; + uint a = (uint)addr; if (a > 0xFFFFFF) throw new ArgumentOutOfRangeException(paramName: nameof(addr), a, message: "address out of range"); return Core.gpgx_peek_m68k_bus(a); }, (addr, val) => { - var a = (uint)addr; + uint a = (uint)addr; if (a > 0xFFFFFF) throw new ArgumentOutOfRangeException(paramName: nameof(addr), a, message: "address out of range"); Core.gpgx_write_m68k_bus(a, val); }, 2); @@ -97,16 +97,16 @@ private unsafe void SetMemoryDomains() if (IsMegaCD) { - var s68Bus = new MemoryDomainDelegate("S68K BUS", 0x1000000, MemoryDomain.Endian.Big, + MemoryDomainDelegate s68Bus = new("S68K BUS", 0x1000000, MemoryDomain.Endian.Big, addr => { - var a = (uint)addr; + uint a = (uint)addr; if (a > 0xFFFFFF) throw new ArgumentOutOfRangeException(paramName: nameof(addr), a, message: "address out of range"); return Core.gpgx_peek_s68k_bus(a); }, (addr, val) => { - var a = (uint)addr; + uint a = (uint)addr; if (a > 0xFFFFFF) throw new ArgumentOutOfRangeException(paramName: nameof(addr), a, message: "address out of range"); Core.gpgx_write_s68k_bus(a, val); }, 2); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.ISaveRam.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.ISaveRam.cs index 2a28bed9c39..89a110c2ad4 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.ISaveRam.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.ISaveRam.cs @@ -10,7 +10,7 @@ public partial class GPGX : ISaveRam public byte[] CloneSaveRam() { int size = 0; - IntPtr area = Core.gpgx_get_sram(ref size); + var area = Core.gpgx_get_sram(ref size); if (size == 0 || area == IntPtr.Zero) return null; @@ -38,7 +38,7 @@ public bool SaveRamModified get { int size = 0; - IntPtr area = Core.gpgx_get_sram(ref size); + var area = Core.gpgx_get_sram(ref size); return size > 0 && area != IntPtr.Zero; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.ISettable.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.ISettable.cs index da2c9cded49..98dcbb8454d 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.ISettable.cs @@ -11,15 +11,9 @@ namespace BizHawk.Emulation.Cores.Consoles.Sega.gpgx { public partial class GPGX : ISettable { - public GPGXSettings GetSettings() - { - return _settings.Clone(); - } + public GPGXSettings GetSettings() => _settings.Clone(); - public GPGXSyncSettings GetSyncSettings() - { - return _syncSettings.Clone(); - } + public GPGXSyncSettings GetSyncSettings() => _syncSettings.Clone(); public PutSettingsDirtyBits PutSettings(GPGXSettings o) { @@ -39,15 +33,9 @@ public PutSettingsDirtyBits PutSyncSettings(GPGXSyncSettings o) private class UintToHexConverter : TypeConverter { - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) - { - return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); - } + public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) => sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) - { - return destinationType == typeof(string) || base.CanConvertTo(context, destinationType); - } + public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) => destinationType == typeof(string) || base.CanConvertTo(context, destinationType); public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { @@ -77,15 +65,9 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c private class UshortToHexConverter : TypeConverter { - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) - { - return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); - } + public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) => sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) - { - return destinationType == typeof(string) || base.CanConvertTo(context, destinationType); - } + public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) => destinationType == typeof(string) || base.CanConvertTo(context, destinationType); public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { @@ -215,10 +197,7 @@ public GPGXSettings() SettingsUtil.SetDefaultValues(this); } - public GPGXSettings Clone() - { - return (GPGXSettings)MemberwiseClone(); - } + public GPGXSettings Clone() => (GPGXSettings)MemberwiseClone(); public LibGPGX.DrawMask GetDrawMask() { @@ -231,12 +210,9 @@ public LibGPGX.DrawMask GetDrawMask() return ret; } - public static bool NeedsReboot(GPGXSettings x, GPGXSettings y) - { - return !DeepEquality.DeepEquals(x, y); - } + public static bool NeedsReboot(GPGXSettings x, GPGXSettings y) => !DeepEquality.DeepEquals(x, y); + - } public class GPGXSyncSettings @@ -326,15 +302,9 @@ public GPGXSyncSettings() SettingsUtil.SetDefaultValues(this); } - public GPGXSyncSettings Clone() - { - return (GPGXSyncSettings)MemberwiseClone(); - } + public GPGXSyncSettings Clone() => (GPGXSyncSettings)MemberwiseClone(); - public static bool NeedsReboot(GPGXSyncSettings x, GPGXSyncSettings y) - { - return !DeepEquality.DeepEquals(x, y); - } + public static bool NeedsReboot(GPGXSyncSettings x, GPGXSyncSettings y) => !DeepEquality.DeepEquals(x, y); } } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.ISoundProvider.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.ISoundProvider.cs index 7e66fd11a7a..ca13c6bdc7b 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.ISoundProvider.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.ISoundProvider.cs @@ -19,10 +19,7 @@ public void GetSamplesSync(out short[] samples, out int nsamp) _nsamp = 0; } - public void DiscardSamples() - { - _nsamp = 0; - } + public void DiscardSamples() => _nsamp = 0; public void SetSyncMode(SyncSoundMode mode) { @@ -34,14 +31,11 @@ public void SetSyncMode(SyncSoundMode mode) } public SyncSoundMode SyncMode => SyncSoundMode.Sync; - public void GetSamplesAsync(short[] samples) - { - throw new InvalidOperationException("Async mode is not supported."); - } + public void GetSamplesAsync(short[] samples) => throw new InvalidOperationException("Async mode is not supported."); private void update_audio() { - IntPtr src = IntPtr.Zero; + var src = IntPtr.Zero; Core.gpgx_get_audio(ref _nsamp, ref src); if (src != IntPtr.Zero) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.ITraceable.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.ITraceable.cs index 3b87df99150..00217c361ec 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.ITraceable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.ITraceable.cs @@ -20,23 +20,23 @@ protected override void TraceFromCallback(uint addr, uint value, uint flags) { var regs = DebuggableCore.GetCpuFlagsAndRegisters(); uint pc = (uint)regs["M68K PC"].Value; - var disasm = Disassembler.Disassemble(MemoryDomains.SystemBus, pc & 0xFFFFFF, out _); + string disasm = Disassembler.Disassemble(MemoryDomains.SystemBus, pc & 0xFFFFFF, out _); - var sb = new StringBuilder(); + StringBuilder sb = new(); foreach (var r in regs) { if (r.Key.StartsWithOrdinal("M68K")) // drop Z80 regs until it has its own debugger/tracer { - if (r.Key != "M68K SP" && r.Key != "M68K ISP" && // copies of a7 - r.Key != "M68K PC" && // already present in every line start - r.Key != "M68K IR") // copy of last opcode, already shown in raw bytes + if (r.Key is not "M68K SP" and not "M68K ISP" and // copies of a7 + not "M68K PC" and // already present in every line start + not "M68K IR") // copy of last opcode, already shown in raw bytes { sb.Append($"{r.Key.Replace("M68K", "").Trim()}:{r.Value.Value.ToHexString(r.Value.BitSize / 4)} "); } } } - var sr = regs["M68K SR"].Value; + ulong sr = regs["M68K SR"].Value; sb.Append(string.Concat( (sr & 16) > 0 ? "X" : "x", (sr & 8) > 0 ? "N" : "n", diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.IVideoProvider.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.IVideoProvider.cs index 1ce55c98ee3..c9cf280accd 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.IVideoProvider.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.IVideoProvider.cs @@ -12,9 +12,9 @@ public partial class GPGX : IVideoProvider public int VirtualHeight => 224; - public int BufferWidth => _vwidth; + public int BufferWidth { get; private set; } - public int BufferHeight => _vheight; + public int BufferHeight { get; private set; } public int BackgroundColor => unchecked((int)0xff000000); @@ -23,8 +23,6 @@ public partial class GPGX : IVideoProvider public int VsyncDenominator { get; } private int[] _vidBuff = new int[0]; - private int _vwidth; - private int _vheight; private void UpdateVideoInitial() { @@ -33,9 +31,9 @@ private void UpdateVideoInitial() // so instead, just assume a 320x224 size now; if that happens to be wrong, it'll be fixed soon enough. - _vwidth = 320; - _vheight = 224; - _vidBuff = new int[_vwidth * _vheight]; + BufferWidth = 320; + BufferHeight = 224; + _vidBuff = new int[BufferWidth * BufferHeight]; for (int i = 0; i < _vidBuff.Length; i++) { _vidBuff[i] = unchecked((int)0xff000000); @@ -52,21 +50,21 @@ private unsafe void UpdateVideo() using (_elf.EnterExit()) { - IntPtr src = IntPtr.Zero; + var src = IntPtr.Zero; - Core.gpgx_get_video(out var gpwidth, out var gpheight, out var gppitch, ref src); + Core.gpgx_get_video(out int gpwidth, out int gpheight, out int gppitch, ref src); - _vwidth = gpwidth; - _vheight = gpheight; + BufferWidth = gpwidth; + BufferHeight = gpheight; - if (_settings.PadScreen320 && _vwidth == 256) - _vwidth = 320; + if (_settings.PadScreen320 && BufferWidth == 256) + BufferWidth = 320; - int xpad = (_vwidth - gpwidth) / 2; - int xpad2 = _vwidth - gpwidth - xpad; + int xpad = (BufferWidth - gpwidth) / 2; + int xpad2 = BufferWidth - gpwidth - xpad; - if (_vidBuff.Length < _vwidth * _vheight) - _vidBuff = new int[_vwidth * _vheight]; + if (_vidBuff.Length < BufferWidth * BufferHeight) + _vidBuff = new int[BufferWidth * BufferHeight]; int rinc = (gppitch / 4) - gpwidth; fixed (int* pdst_ = _vidBuff) diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.cs index 54ec5f45611..9eef37d9041 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGX.cs @@ -73,10 +73,10 @@ public GPGX(CoreLoadParameters lp) DriveLightEnabled = true; } - LibGPGX.INPUT_SYSTEM system_a = SystemForSystem(_syncSettings.ControlTypeLeft); - LibGPGX.INPUT_SYSTEM system_b = SystemForSystem(_syncSettings.ControlTypeRight); + var system_a = SystemForSystem(_syncSettings.ControlTypeLeft); + var system_b = SystemForSystem(_syncSettings.ControlTypeRight); - var initResult = Core.gpgx_init(romextension, LoadCallback, _syncSettings.GetNativeSettings(lp.Game)); + bool initResult = Core.gpgx_init(romextension, LoadCallback, _syncSettings.GetNativeSettings(lp.Game)); if (!initResult) throw new Exception($"{nameof(Core.gpgx_init)}() failed"); @@ -121,24 +121,16 @@ public GPGX(CoreLoadParameters lp) private static LibGPGX.INPUT_SYSTEM SystemForSystem(ControlType c) { - switch (c) + return c switch { - default: - case ControlType.None: - return LibGPGX.INPUT_SYSTEM.SYSTEM_NONE; - case ControlType.Normal: - return LibGPGX.INPUT_SYSTEM.SYSTEM_MD_GAMEPAD; - case ControlType.Xea1p: - return LibGPGX.INPUT_SYSTEM.SYSTEM_XE_A1P; - case ControlType.Activator: - return LibGPGX.INPUT_SYSTEM.SYSTEM_ACTIVATOR; - case ControlType.Teamplayer: - return LibGPGX.INPUT_SYSTEM.SYSTEM_TEAMPLAYER; - case ControlType.Wayplay: - return LibGPGX.INPUT_SYSTEM.SYSTEM_WAYPLAY; - case ControlType.Mouse: - return LibGPGX.INPUT_SYSTEM.SYSTEM_MOUSE; - } + ControlType.Normal => LibGPGX.INPUT_SYSTEM.SYSTEM_MD_GAMEPAD, + ControlType.Xea1p => LibGPGX.INPUT_SYSTEM.SYSTEM_XE_A1P, + ControlType.Activator => LibGPGX.INPUT_SYSTEM.SYSTEM_ACTIVATOR, + ControlType.Teamplayer => LibGPGX.INPUT_SYSTEM.SYSTEM_TEAMPLAYER, + ControlType.Wayplay => LibGPGX.INPUT_SYSTEM.SYSTEM_WAYPLAY, + ControlType.Mouse => LibGPGX.INPUT_SYSTEM.SYSTEM_MOUSE, + _ => LibGPGX.INPUT_SYSTEM.SYSTEM_NONE, + }; } private readonly LibGPGX Core; @@ -154,9 +146,9 @@ private static LibGPGX.INPUT_SYSTEM SystemForSystem(ControlType c) private bool _disposed = false; - private LibGPGX.load_archive_cb LoadCallback; + private readonly LibGPGX.load_archive_cb LoadCallback; - private readonly LibGPGX.InputData input = new LibGPGX.InputData(); + private readonly LibGPGX.InputData input = new(); public enum ControlType { @@ -196,7 +188,7 @@ private int load_archive(string filename, IntPtr buffer, int maxsize) } srcdata = _romfile; } - else if (filename == "PRIMARY_CD" || filename == "SECONDARY_CD") + else if (filename is "PRIMARY_CD" or "SECONDARY_CD") { if (filename == "PRIMARY_CD" && _romfile != null) { @@ -304,7 +296,7 @@ private void CDRead(int lba, IntPtr dest, bool audio) public static LibGPGX.CDData GetCDDataStruct(Disc cd) { - var ret = new LibGPGX.CDData(); + LibGPGX.CDData ret = new(); var ses = cd.Session1; int ntrack = ses.InformationTrackCount; @@ -363,10 +355,7 @@ private void SetControllerDefinition() ControllerDefinition = ControlConverter.ControllerDef; } - public LibGPGX.INPUT_DEVICE[] GetDevices() - { - return (LibGPGX.INPUT_DEVICE[])input.dev.Clone(); - } + public LibGPGX.INPUT_DEVICE[] GetDevices() => (LibGPGX.INPUT_DEVICE[])input.dev.Clone(); public bool IsMegaCD => _cds != null; @@ -393,20 +382,14 @@ public VDPView(LibGPGX.VDPView v, IMonitor m) public LibGPGX.VDPNameTable NTW; - public void Enter() - { - _m.Enter(); - } + public void Enter() => _m.Enter(); - public void Exit() - { - _m.Exit(); - } + public void Exit() => _m.Exit(); } public VDPView UpdateVDPViewContext() { - var v = new LibGPGX.VDPView(); + LibGPGX.VDPView v = new(); Core.gpgx_get_vdp_view(v); Core.gpgx_flush_vram(); // fully regenerate internal caches as needed return new VDPView(v, _elf); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGXControlConverter.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGXControlConverter.cs index 4c4c32706b3..b1caa0aec20 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGXControlConverter.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GPGXControlConverter.cs @@ -10,7 +10,7 @@ public class GPGXControlConverter { // this isn't all done - private struct CName + private readonly struct CName { public readonly string Name; public readonly LibGPGX.INPUT_KEYS Key; @@ -100,7 +100,7 @@ public CName(string name, LibGPGX.INPUT_KEYS key) private LibGPGX.InputData _target; private IController _source; - private readonly List _converts = new List(); + private readonly List _converts = new(); public ControllerDefinition ControllerDef { get; } @@ -131,8 +131,8 @@ private void DoMouseAnalog(int idx, int player) // The game in question is Eye of the Beholder, you can FFW to the main menu and get a cursor right away. // --yoshi ControllerDef.AddXYPair($"P{player} Mouse {{0}}", AxisPairOrientation.RightAndUp, (-256).RangeTo(256), 0); - var nx = $"P{player} Mouse X"; - var ny = $"P{player} Mouse Y"; + string nx = $"P{player} Mouse X"; + string ny = $"P{player} Mouse Y"; _converts.Add(() => { _target.analog[(2 * idx) + 0] = (short)_source.AxisValue(nx); @@ -144,8 +144,8 @@ private void DoLightgunAnalog(int idx, int player) { // lightgun needs to be transformed to match the current screen resolution ControllerDef.AddXYPair($"P{player} Lightgun {{0}}", AxisPairOrientation.RightAndUp, 0.RangeTo(10000), 5000); //TODO verify direction against hardware - var nx = $"P{player} Lightgun X"; - var ny = $"P{player} Lightgun Y"; + string nx = $"P{player} Lightgun X"; + string ny = $"P{player} Lightgun Y"; _converts.Add(() => { _target.analog[(2 * idx) + 0] = (short)(_source.AxisValue(nx) / 10000.0f * (ScreenWidth - 1)); @@ -156,9 +156,9 @@ private void DoLightgunAnalog(int idx, int player) private void DoXea1PAnalog(int idx, int player) { ControllerDef.AddXYZTriple($"P{player} Stick {{0}}", (-128).RangeTo(127), 0); - var nx = $"P{player} Stick X"; - var ny = $"P{player} Stick Y"; - var nz = $"P{player} Stick Z"; + string nx = $"P{player} Stick X"; + string ny = $"P{player} Stick Y"; + string nz = $"P{player} Stick Z"; _converts.Add(() => { _target.analog[(2 * idx) + 0] = (short)_source.AxisValue(nx); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GenDbgHlp.cs b/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GenDbgHlp.cs index cfeec6d2519..a6c54e0bc19 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GenDbgHlp.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sega/gpgx64/GenDbgHlp.cs @@ -43,7 +43,7 @@ public void Dispose() private IntPtr DllBase; - private readonly List SymbolsByAddr = new List(); + private readonly List SymbolsByAddr = new(); private readonly IDictionary SymbolsByName = new Dictionary(); private readonly byte[][] data = new byte[10][]; @@ -62,7 +62,7 @@ public void SaveState(int statenum) public unsafe void Cmp(int statex, int statey) { if (disposed) throw new ObjectDisposedException(nameof(GenDbgHlp)); - List> bads = new List>(); + List> bads = new(); byte[] x = data[statex]; byte[] y = data[statey]; @@ -119,7 +119,7 @@ public unsafe void Cmp(int statex, int statey) public GenDbgHlp() { - using (StreamReader sr = new StreamReader(symbolname)) + using (StreamReader sr = new(symbolname)) { string line; while ((line = sr.ReadLine()) != null) @@ -136,8 +136,8 @@ public GenDbgHlp() public List Find(IntPtr addr, int length) { if (disposed) throw new ObjectDisposedException(nameof(GenDbgHlp)); - Symbol min = new Symbol { addr = addr }; - Symbol max = new Symbol { addr = addr + length }; + Symbol min = new() { addr = addr }; + Symbol max = new() { addr = addr + length }; int minidx = SymbolsByAddr.BinarySearch(min); if (minidx < 0) @@ -170,7 +170,7 @@ public static Symbol FromString(string s) throw new Exception(); if (!ss[1].StartsWithOrdinal("0x")) throw new Exception(); - Symbol ret = new Symbol + Symbol ret = new() { addr = (IntPtr)int.Parse(ss[1].Substring(2), System.Globalization.NumberStyles.AllowHexSpecifier), section = ss[3], @@ -179,12 +179,9 @@ public static Symbol FromString(string s) return ret; } - public int CompareTo(Symbol other) - { - return (int)this.addr - (int)other.addr; - } + public readonly int CompareTo(Symbol other) => (int)this.addr - (int)other.addr; - public override string ToString() => $"0x{(int)addr:X8} {name} ({section})"; + public override readonly string ToString() => $"0x{(int)addr:X8} {name} ({section})"; } } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/Nymashock.cs b/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/Nymashock.cs index a83c3a41558..d4362fea75d 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/Nymashock.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/Nymashock.cs @@ -45,7 +45,7 @@ public static NymaSettingsInfo CachedSettingsInfo(CoreComm comm) { if (_cachedSettingsInfo is null) { - using var n = new Nymashock(comm); + using Nymashock n = new(comm); n.InitForSettingsInfo("shock.wbx"); _cachedSettingsInfo = n.SettingsInfo.Clone(); } @@ -59,7 +59,7 @@ public Nymashock(CoreLoadParameters lp) { if (lp.Roms.Count > 0) throw new InvalidOperationException("To load a PSX game, please load the CUE file and not the BIN file."); - var firmwares = new Dictionary + Dictionary firmwares = new() { { "FIRMWARE:$J", new("PSX", "J") }, { "FIRMWARE:$U", new("PSX", "U") }, diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/Octoshock.IDebuggable.cs b/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/Octoshock.IDebuggable.cs index 2d901ab2e53..4da665db704 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/Octoshock.IDebuggable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/Octoshock.IDebuggable.cs @@ -9,8 +9,8 @@ public unsafe partial class Octoshock : IDebuggable // TODO: don't cast to int, and are any of these not 32 bit? public IDictionary GetCpuFlagsAndRegisters() { - Dictionary ret = new Dictionary(); - var regs = new OctoshockDll.ShockRegisters_CPU(); + Dictionary ret = new(); + OctoshockDll.ShockRegisters_CPU regs = new(); OctoshockDll.shock_GetRegisters_CPU(psx, ref regs); @@ -47,7 +47,7 @@ public IDictionary GetCpuFlagsAndRegisters() return ret; } - private static readonly Dictionary CpuRegisterIndices = new Dictionary() { + private static readonly Dictionary CpuRegisterIndices = new() { { "r1", 1 }, { "r2", 2 }, { "r3", 3 }, { "r4", 4 }, { "r5", 5 }, { "r6", 6 }, { "r7", 7 }, { "r8", 8 }, { "r9", 9 }, { "r10", 10 }, { "r11", 11 }, { "r12", 12 }, { "r13", 13 }, { "r14", 14 }, { "r15", 15 }, { "r16", 16 }, { "r17", 17 }, { "r18", 18 }, { "r19", 19 }, { "r20", 20 }, { "r21", 21 }, { "r22", 22 }, { "r23", 23 }, @@ -77,7 +77,7 @@ public void SetCpuRegister(string register, int value) OctoshockDll.shock_SetRegister_CPU(psx, index, (uint)value); } - private readonly MemoryCallbackSystem _memoryCallbacks = new MemoryCallbackSystem(new[] { "System Bus" }); // Note: there is no system bus memory domain, but there's also no hard rule that the memory callback system domains have to correspond to actual domains in MemoryDomains, that could be good, or bad, but something to be careful about + private readonly MemoryCallbackSystem _memoryCallbacks = new(new[] { "System Bus" }); // Note: there is no system bus memory domain, but there's also no hard rule that the memory callback system domains have to correspond to actual domains in MemoryDomains, that could be good, or bad, but something to be careful about public IMemoryCallbackSystem MemoryCallbacks => _memoryCallbacks; public bool CanStep(StepType type) => false; @@ -117,7 +117,7 @@ private void InitMemCallbacks() private void RefreshMemCallbacks() { - OctoshockDll.eShockMemCb mask = OctoshockDll.eShockMemCb.None; + var mask = OctoshockDll.eShockMemCb.None; if (MemoryCallbacks.HasReads) mask |= OctoshockDll.eShockMemCb.Read; if (MemoryCallbacks.HasWrites) mask |= OctoshockDll.eShockMemCb.Write; if (MemoryCallbacks.HasExecutes) mask |= OctoshockDll.eShockMemCb.Execute; @@ -126,9 +126,9 @@ private void RefreshMemCallbacks() private void SetMemoryDomains() { - var mmd = new List(); + List mmd = new(); - OctoshockDll.shock_GetMemData(psx, out var ptr, out var size, OctoshockDll.eMemType.MainRAM); + OctoshockDll.shock_GetMemData(psx, out var ptr, out int size, OctoshockDll.eMemType.MainRAM); mmd.Add(new MemoryDomainIntPtr("MainRAM", MemoryDomain.Endian.Little, ptr, size, true, 4)); OctoshockDll.shock_GetMemData(psx, out ptr, out size, OctoshockDll.eMemType.GPURAM); diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/Octoshock.IDisassemblable.cs b/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/Octoshock.IDisassemblable.cs index cfeb69304ca..96e9d88b942 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/Octoshock.IDisassemblable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/Octoshock.IDisassemblable.cs @@ -25,8 +25,8 @@ public IEnumerable AvailableCpus public string Disassemble(MemoryDomain m, uint addr, out int length) { length = 4; - var buf = new StringBuilder(32); - var result = OctoshockDll.shock_Util_DisassembleMIPS(addr, m.PeekUint(addr, false), buf, buf.Capacity); + StringBuilder buf = new(32); + int result = OctoshockDll.shock_Util_DisassembleMIPS(addr, m.PeekUint(addr, false), buf, buf.Capacity); return result==0?buf.ToString():""; } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/Octoshock.ITraceable.cs b/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/Octoshock.ITraceable.cs index f93a71b5ca8..9e33393263c 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/Octoshock.ITraceable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/Octoshock.ITraceable.cs @@ -17,7 +17,7 @@ public partial class Octoshock public void ShockTraceCallback(IntPtr opaque, uint PC, uint inst, string dis) { var regs = GetCpuFlagsAndRegisters(); - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); foreach (var r in regs) { @@ -25,7 +25,7 @@ public void ShockTraceCallback(IntPtr opaque, uint PC, uint inst, string dis) sb.Append($"{r.Key}:{r.Value.Value.ToHexString(r.Value.BitSize / 4)} "); } - Tracer.Put(new(disassembly: $"{PC:X8}: {inst:X8} {dis.PadRight(30)}", registerInfo: sb.ToString().Trim())); + Tracer.Put(new(disassembly: $"{PC:X8}: {inst:X8} {dis,-30}", registerInfo: sb.ToString().Trim())); } private void ConnectTracer() diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/Octoshock.cs b/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/Octoshock.cs index daa47e8d35d..6f95d6edb3e 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/Octoshock.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/Octoshock.cs @@ -47,7 +47,7 @@ public Octoshock(CoreLoadParameters string romDetails; if (lp.Discs.Count > 0) { - string DiscHashWarningText(GameInfo game, string discHash) + static string DiscHashWarningText(GameInfo game, string discHash) { if (game == null || game.IsRomStatusBad() || game.Status == RomStatus.NotInDatabase) { @@ -63,10 +63,10 @@ string DiscHashWarningText(GameInfo game, string discHash) } } - var sw = new StringWriter(); + StringWriter sw = new(); foreach (var d in lp.Discs) { - var discHash = new DiscHasher(d.DiscData).Calculate_PSX_BizIDHash(); + string discHash = new DiscHasher(d.DiscData).Calculate_PSX_BizIDHash(); sw.WriteLine(Path.GetFileName(d.DiscName)); sw.WriteLine(DiscHashWarningText(Database.CheckDatabase(discHash), discHash)); sw.WriteLine("-------------------------"); @@ -111,7 +111,7 @@ private void Load( foreach (var disc in discs) { - var discInterface = new DiscInterface(disc, + DiscInterface discInterface = new(disc, di => { //if current disc this delegate disc, activity is happening @@ -182,7 +182,7 @@ private void Load( } //TODO - known bad firmwares are a no-go. we should refuse to boot them. (that's the mednafen policy) - var firmware = comm.CoreFileProvider.GetFirmwareOrThrow(new("PSX", firmwareRegion), $"A PSX `{firmwareRegion}` region bios file is required"); + byte[] firmware = comm.CoreFileProvider.GetFirmwareOrThrow(new("PSX", firmwareRegion), $"A PSX `{firmwareRegion}` region bios file is required"); //create the instance fixed (byte* pFirmware = firmware) @@ -268,7 +268,7 @@ private void Load( else OctoshockDll.shock_Peripheral_Connect(psx, 0x02, fioCfg.Devices8[4]); - var memcardTransaction = new OctoshockDll.ShockMemcardTransaction() + OctoshockDll.ShockMemcardTransaction memcardTransaction = new() { transaction = OctoshockDll.eShockMemcardTransaction.Connect }; @@ -308,7 +308,7 @@ public static ControllerDefinition CreateControllerDefinition(SyncSettings syncS "P" + pnum + " A", }); - foreach (var axisName in new[] { $"P{pnum} Twist", $"P{pnum} 1", $"P{pnum} 2", $"P{pnum} L" }) + foreach (string axisName in new[] { $"P{pnum} Twist", $"P{pnum} 1", $"P{pnum} 2", $"P{pnum} L" }) { definition.AddAxis(axisName, 0.RangeTo(255), 128); } @@ -334,7 +334,7 @@ public static ControllerDefinition CreateControllerDefinition(SyncSettings syncS }); - if (type == OctoshockDll.ePeripheralType.DualShock || type == OctoshockDll.ePeripheralType.DualAnalog) + if (type is OctoshockDll.ePeripheralType.DualShock or OctoshockDll.ePeripheralType.DualAnalog) { definition.BoolButtons.Add("P" + pnum + " L3"); definition.BoolButtons.Add("P" + pnum + " R3"); @@ -357,13 +357,10 @@ public static ControllerDefinition CreateControllerDefinition(SyncSettings syncS return definition.MakeImmutable(); } - private void SetControllerButtons() - { - ControllerDefinition = CreateControllerDefinition(_SyncSettings); - } + private void SetControllerButtons() => ControllerDefinition = CreateControllerDefinition(_SyncSettings); private int[] frameBuffer = new int[0]; - private Random rand = new Random(); + private readonly Random rand = new(); //we can only have one active core at a time, due to the lib being so static. //so we'll track the current one here and detach the previous one whenever a new one is booted up. @@ -405,8 +402,8 @@ public DiscInterface(Disc disc, Action cbActivity) OctoshockDll.shock_CreateDisc(out OctoshockHandle, IntPtr.Zero, disc.Session1.LeadoutLBA, cbReadTOC, cbReadLBA, true); } - private OctoshockDll.ShockDisc_ReadTOC cbReadTOC; - private OctoshockDll.ShockDisc_ReadLBA cbReadLBA; + private readonly OctoshockDll.ShockDisc_ReadTOC cbReadTOC; + private readonly OctoshockDll.ShockDisc_ReadLBA cbReadLBA; private readonly Action cbActivity; public readonly Disc Disc; @@ -452,7 +449,7 @@ private int ShockDisc_ReadLBA2448(IntPtr opaque, int lba, void* dst) cbActivity(this); //todo - cache reader - var dsr = new DiscSectorReader(Disc); + DiscSectorReader dsr = new(Disc); int readed = dsr.ReadLBA_2448(lba, SectorBuffer, 0); if (readed == 2448) { @@ -465,7 +462,7 @@ private int ShockDisc_ReadLBA2448(IntPtr opaque, int lba, void* dst) } public List Discs; - private readonly List discInterfaces = new List(); + private readonly List discInterfaces = new(); private DiscInterface currentDiscInterface; public DisplayType Region => SystemVidStandard == OctoshockDll.eVidStandard.PAL ? DisplayType.PAL : DisplayType.NTSC; @@ -499,7 +496,7 @@ static Octoshock() public string CalculateDiscHashes() { - var sb = new StringBuilder(); + StringBuilder sb = new(); try { foreach (var disc in Discs) @@ -584,7 +581,7 @@ private void SetInput() if (_controller.IsPressed(pstring + "Square")) buttons |= 32768; byte left_x = 0, left_y = 0, right_x = 0, right_y = 0; - if (fioCfg.Devices8[slot] == OctoshockDll.ePeripheralType.DualShock || fioCfg.Devices8[slot] == OctoshockDll.ePeripheralType.DualAnalog) + if (fioCfg.Devices8[slot] is OctoshockDll.ePeripheralType.DualShock or OctoshockDll.ePeripheralType.DualAnalog) { if (_controller.IsPressed(pstring + "L3")) buttons |= 2; if (_controller.IsPressed(pstring + "R3")) buttons |= 4; @@ -613,7 +610,7 @@ public class ResolutionInfo /// public static ResolutionInfo CalculateResolution(OctoshockDll.eVidStandard standard, Settings settings, int w, int h) { - ResolutionInfo ret = new ResolutionInfo(); + ResolutionInfo ret = new(); //some of this logic is duplicated in the c++ side, be sure to check there //TODO - scanline control + framebuffer mode is majorly broken @@ -812,7 +809,7 @@ public bool FrameAdvance(IController controller, bool render, bool rendersound) OctoshockDll.shock_SetLEC(psx, _SyncSettings.EnableLEC); - var ropts = new OctoshockDll.ShockRenderOptions() + OctoshockDll.ShockRenderOptions ropts = new() { scanline_start = SystemVidStandard == OctoshockDll.eVidStandard.NTSC ? _Settings.ScanlineStart_NTSC : _Settings.ScanlineStart_PAL, scanline_end = SystemVidStandard == OctoshockDll.eVidStandard.NTSC ? _Settings.ScanlineEnd_NTSC : _Settings.ScanlineEnd_PAL, @@ -860,7 +857,7 @@ public bool FrameAdvance(IController controller, bool render, bool rendersound) return true; } - OctoshockDll.ShockFramebufferInfo fb = new OctoshockDll.ShockFramebufferInfo(); + OctoshockDll.ShockFramebufferInfo fb = new(); //run this once to get current logical size OctoshockDll.shock_GetFramebuffer(psx, ref fb); @@ -941,10 +938,7 @@ public void GetSamplesSync(out short[] samples, out int nsamp) nsamp = sbuffcontains; } - public void DiscardSamples() - { - sbuffcontains = 0; - } + public void DiscardSamples() => sbuffcontains = 0; public bool CanProvideAsync => false; @@ -958,25 +952,24 @@ public void SetSyncMode(SyncSoundMode mode) public SyncSoundMode SyncMode => SyncSoundMode.Sync; - public void GetSamplesAsync(short[] samples) - { - throw new InvalidOperationException("Async mode is not supported."); - } + public void GetSamplesAsync(short[] samples) => throw new InvalidOperationException("Async mode is not supported."); public byte[] CloneSaveRam() { var cfg = _SyncSettings.FIOConfig.ToLogical(); int nMemcards = cfg.NumMemcards; - var buf = new byte[128 * 1024 * nMemcards]; + byte[] buf = new byte[128 * 1024 * nMemcards]; for (int i = 0, idx = 0, addr=0x01; i < 2; i++, addr<<=1) { if (cfg.Memcards[i]) { fixed (byte* pbuf = buf) { - var transaction = new OctoshockDll.ShockMemcardTransaction(); - transaction.buffer128k = pbuf + idx * 128 * 1024; - transaction.transaction = OctoshockDll.eShockMemcardTransaction.Read; + OctoshockDll.ShockMemcardTransaction transaction = new() + { + buffer128k = pbuf + idx * 128 * 1024, + transaction = OctoshockDll.eShockMemcardTransaction.Read + }; OctoshockDll.shock_Peripheral_MemcardTransact(psx, addr, ref transaction); idx++; } @@ -994,9 +987,11 @@ public void StoreSaveRam(byte[] data) { fixed (byte* pbuf = data) { - var transaction = new OctoshockDll.ShockMemcardTransaction(); - transaction.buffer128k = pbuf + idx * 128 * 1024; - transaction.transaction = OctoshockDll.eShockMemcardTransaction.Write; + OctoshockDll.ShockMemcardTransaction transaction = new() + { + buffer128k = pbuf + idx * 128 * 1024, + transaction = OctoshockDll.eShockMemcardTransaction.Write + }; OctoshockDll.shock_Peripheral_MemcardTransact(psx, addr, ref transaction); idx++; } @@ -1013,8 +1008,10 @@ public bool SaveRamModified { if (cfg.Memcards[i]) { - var transaction = new OctoshockDll.ShockMemcardTransaction(); - transaction.transaction = OctoshockDll.eShockMemcardTransaction.CheckDirty; + OctoshockDll.ShockMemcardTransaction transaction = new() + { + transaction = OctoshockDll.eShockMemcardTransaction.CheckDirty + }; OctoshockDll.shock_Peripheral_MemcardTransact(psx, addr, ref transaction); if (OctoshockDll.shock_Peripheral_MemcardTransact(psx, addr, ref transaction) == OctoshockDll.SHOCK_TRUE) return true; @@ -1032,8 +1029,10 @@ public bool SaveRamModified private void StudySaveBufferSize() { - var transaction = new OctoshockDll.ShockStateTransaction(); - transaction.transaction = OctoshockDll.eShockStateTransaction.BinarySize; + OctoshockDll.ShockStateTransaction transaction = new() + { + transaction = OctoshockDll.eShockStateTransaction.BinarySize + }; int size = OctoshockDll.shock_StateTransaction(psx, ref transaction); savebuff = new byte[size]; } @@ -1044,7 +1043,7 @@ public void SaveStateBinary(BinaryWriter writer) { fixed (byte* psavebuff = savebuff) { - var transaction = new OctoshockDll.ShockStateTransaction() + OctoshockDll.ShockStateTransaction transaction = new() { transaction = OctoshockDll.eShockStateTransaction.BinarySave, buffer = psavebuff, @@ -1070,7 +1069,7 @@ public void LoadStateBinary(BinaryReader reader) { fixed (byte* psavebuff = savebuff) { - var transaction = new OctoshockDll.ShockStateTransaction() + OctoshockDll.ShockStateTransaction transaction = new() { transaction = OctoshockDll.eShockStateTransaction.BinaryLoad, buffer = psavebuff, @@ -1095,7 +1094,7 @@ public void LoadStateBinary(BinaryReader reader) } } - private Settings _Settings = new Settings(); + private Settings _Settings = new(); private SyncSettings _SyncSettings; public enum eResolutionMode @@ -1106,17 +1105,14 @@ public enum eResolutionMode public class SyncSettings { - public SyncSettings Clone() - { - return JsonConvert.DeserializeObject(JsonConvert.SerializeObject(this)); - } + public SyncSettings Clone() => JsonConvert.DeserializeObject(JsonConvert.SerializeObject(this)); public bool EnableLEC; public SyncSettings() { //initialize with single controller and memcard - var user = new OctoshockFIOConfigUser(); + OctoshockFIOConfigUser user = new(); user.Memcards[0] = true; user.Memcards[1] = false; user.Multitaps[0] = user.Multitaps[0] = false; @@ -1186,15 +1182,11 @@ public void Validate() //make sure theyre not in the wrong order if (ScanlineEnd_NTSC < ScanlineStart_NTSC) { - int temp = ScanlineEnd_NTSC; - ScanlineEnd_NTSC = ScanlineStart_NTSC; - ScanlineStart_NTSC = temp; + (ScanlineStart_NTSC, ScanlineEnd_NTSC) = (ScanlineEnd_NTSC, ScanlineStart_NTSC); } if (ScanlineEnd_PAL < ScanlineStart_PAL) { - int temp = ScanlineEnd_PAL; - ScanlineEnd_PAL = ScanlineStart_PAL; - ScanlineStart_PAL = temp; + (ScanlineStart_PAL, ScanlineEnd_PAL) = (ScanlineEnd_PAL, ScanlineStart_PAL); } } @@ -1203,21 +1195,12 @@ public Settings() SettingsUtil.SetDefaultValues(this); } - public Settings Clone() - { - return (Settings)MemberwiseClone(); - } + public Settings Clone() => (Settings)MemberwiseClone(); } - public Settings GetSettings() - { - return _Settings.Clone(); - } + public Settings GetSettings() => _Settings.Clone(); - public SyncSettings GetSyncSettings() - { - return _SyncSettings.Clone(); - } + public SyncSettings GetSyncSettings() => _SyncSettings.Clone(); public PutSettingsDirtyBits PutSettings(Settings o) { diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/OctoshockFIOConfig.cs b/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/OctoshockFIOConfig.cs index bc0ee54f2ab..4ad3f029184 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/OctoshockFIOConfig.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/OctoshockFIOConfig.cs @@ -11,7 +11,7 @@ public class OctoshockFIOConfigUser public OctoshockFIOConfigLogical ToLogical() { - var lc = new OctoshockFIOConfigLogical(); + OctoshockFIOConfigLogical lc = new(); lc.PopulateFrom(this); return lc; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/PSF.cs b/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/PSF.cs index 4ec469872b5..b1a397b844a 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/PSF.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/Sony/PSX/PSF.cs @@ -16,58 +16,56 @@ public class PSF public bool Load(string fpPSF, Func cbDeflater) { - using(var fs = File.OpenRead(fpPSF)) - { - //not endian safe - var br = new BinaryReader(fs); - var sig = br.ReadStringFixedUtf8(4); - if (sig != "PSF\x1") - return false; + using var fs = File.OpenRead(fpPSF); + //not endian safe + BinaryReader br = new(fs); + string sig = br.ReadStringFixedUtf8(4); + if (sig != "PSF\x1") + return false; - int reserved_size = br.ReadInt32(); - int compressed_size = br.ReadInt32(); - int compressed_crc32 = br.ReadInt32(); - - //load tags - //tags run until the end of the file - fs.Position = 16 + reserved_size + compressed_size; - if (fs.Position + 5 > fs.Length) - { - //theres no space for tags, probably just no tags in the file - } - else + int reserved_size = br.ReadInt32(); + int compressed_size = br.ReadInt32(); + int compressed_crc32 = br.ReadInt32(); + + //load tags + //tags run until the end of the file + fs.Position = 16 + reserved_size + compressed_size; + if (fs.Position + 5 > fs.Length) + { + //theres no space for tags, probably just no tags in the file + } + else + { + if (br.ReadStringFixedUtf8(5) == "[TAG]") { - if (br.ReadStringFixedUtf8(5) == "[TAG]") + string tagstring = br.ReadStringFixedUtf8((int)(fs.Length - fs.Position)).Replace("\r\n", "\n"); + foreach (string tag in tagstring.Split('\n', '\x0')) { - var tagstring = br.ReadStringFixedUtf8((int)(fs.Length - fs.Position)).Replace("\r\n", "\n"); - foreach (var tag in tagstring.Split('\n', '\x0')) - { - if (tag.Trim() == "") - continue; - int eq = tag.IndexOf('='); - if (eq != -1) - TagsDictionary[tag.Substring(0, eq)] = tag.Substring(eq + 1); - else - LooseTags.Add(tag); - } + if (tag.Trim() == "") + continue; + int eq = tag.IndexOf('='); + if (eq != -1) + TagsDictionary[tag.Substring(0, eq)] = tag.Substring(eq + 1); + else + LooseTags.Add(tag); } } + } - //load compressed section buffer - fs.Position = 16 + reserved_size; - Data = cbDeflater(fs, compressed_size); + //load compressed section buffer + fs.Position = 16 + reserved_size; + Data = cbDeflater(fs, compressed_size); - //load lib if needed - if (TagsDictionary.TryGetValue("_lib", out var relPath)) - { - var fpLib = Path.Combine(Path.GetDirectoryName(fpPSF), relPath); - if (!File.Exists(fpLib)) - return false; - PSF lib = new PSF(); - if (!lib.Load(fpLib,cbDeflater)) - return false; - LibData = lib.Data; - } + //load lib if needed + if (TagsDictionary.TryGetValue("_lib", out string relPath)) + { + string fpLib = Path.Combine(Path.GetDirectoryName(fpPSF), relPath); + if (!File.Exists(fpLib)) + return false; + PSF lib = new(); + if (!lib.Load(fpLib, cbDeflater)) + return false; + LibData = lib.Data; } return true; diff --git a/src/BizHawk.Emulation.Cores/Consoles/WonderSwan/WonderSwan.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Consoles/WonderSwan/WonderSwan.IMemoryDomains.cs index c888bd3bccb..e69d198f016 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/WonderSwan/WonderSwan.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/WonderSwan/WonderSwan.IMemoryDomains.cs @@ -9,10 +9,10 @@ public partial class WonderSwan { private void InitIMemoryDomains() { - var mmd = new List(); + List mmd = new(); for (int i = 0;; i++) { - if (!BizSwan.bizswan_getmemoryarea(Core, i, out var name, out var size, out var data)) + if (!BizSwan.bizswan_getmemoryarea(Core, i, out var name, out int size, out var data)) { break; } diff --git a/src/BizHawk.Emulation.Cores/Consoles/WonderSwan/WonderSwan.ISaveRam.cs b/src/BizHawk.Emulation.Cores/Consoles/WonderSwan/WonderSwan.ISaveRam.cs index cb775adc3ab..1c94caca111 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/WonderSwan/WonderSwan.ISaveRam.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/WonderSwan/WonderSwan.ISaveRam.cs @@ -7,10 +7,7 @@ partial class WonderSwan : ISaveRam { private byte[] _saveramBuff; - private void InitISaveRam() - { - _saveramBuff = new byte[BizSwan.bizswan_saveramsize(Core)]; - } + private void InitISaveRam() => _saveramBuff = new byte[BizSwan.bizswan_saveramsize(Core)]; public byte[] CloneSaveRam() { diff --git a/src/BizHawk.Emulation.Cores/Consoles/WonderSwan/WonderSwan.ISettable.cs b/src/BizHawk.Emulation.Cores/Consoles/WonderSwan/WonderSwan.ISettable.cs index a7da8d07977..c11763876ae 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/WonderSwan/WonderSwan.ISettable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/WonderSwan/WonderSwan.ISettable.cs @@ -34,7 +34,7 @@ public class Settings public BizSwan.Settings GetNativeSettings() { - var ret = new BizSwan.Settings(); + BizSwan.Settings ret = new(); if (EnableBG) ret.LayerMask |= BizSwan.LayerFlags.BG; if (EnableFG) ret.LayerMask |= BizSwan.LayerFlags.FG; if (EnableSprites) ret.LayerMask |= BizSwan.LayerFlags.Sprite; @@ -54,9 +54,9 @@ public BizSwan.Settings GetNativeSettings() { for (int b = 0; b < 16; b++) { - var neoR = (uint)r * 17; - var neoG = (uint)g * 17; - var neoB = (uint)b * 17; + uint neoR = (uint)r * 17; + uint neoG = (uint)g * 17; + uint neoB = (uint)b * 17; ret.ColorPalette[r << 8 | g << 4 | b] = 0xff000000 | neoR << 16 | neoG << 8 | neoB << 0; } } @@ -77,7 +77,7 @@ public Settings() public Settings Clone() { - var ret = (Settings)MemberwiseClone(); + Settings ret = (Settings)MemberwiseClone(); ret.BWPalette = (Color[])BWPalette.Clone(); return ret; } @@ -124,7 +124,7 @@ public class SyncSettings public BizSwan.SyncSettings GetNativeSettings() { - var ret = new BizSwan.SyncSettings + BizSwan.SyncSettings ret = new() { color = Color, userealtime = UseRealTime, @@ -145,15 +145,9 @@ public SyncSettings() SettingsUtil.SetDefaultValues(this); } - public SyncSettings Clone() - { - return (SyncSettings)MemberwiseClone(); - } + public SyncSettings Clone() => (SyncSettings)MemberwiseClone(); - public static bool NeedsReboot(SyncSettings x, SyncSettings y) - { - return !DeepEquality.DeepEquals(x, y); - } + public static bool NeedsReboot(SyncSettings x, SyncSettings y) => !DeepEquality.DeepEquals(x, y); } public Settings GetSettings() => _settings.Clone(); diff --git a/src/BizHawk.Emulation.Cores/Consoles/WonderSwan/WonderSwan.ISoundProvider.cs b/src/BizHawk.Emulation.Cores/Consoles/WonderSwan/WonderSwan.ISoundProvider.cs index fe8983b1c9d..8cfeeff1972 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/WonderSwan/WonderSwan.ISoundProvider.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/WonderSwan/WonderSwan.ISoundProvider.cs @@ -16,10 +16,7 @@ public void GetSamplesSync(out short[] samples, out int nsamp) nsamp = sbuffcontains; } - public void DiscardSamples() - { - sbuffcontains = 0; - } + public void DiscardSamples() => sbuffcontains = 0; public void SetSyncMode(SyncSoundMode mode) { @@ -31,9 +28,6 @@ public void SetSyncMode(SyncSoundMode mode) public SyncSoundMode SyncMode => SyncSoundMode.Sync; - public void GetSamplesAsync(short[] samples) - { - throw new InvalidOperationException("Async mode is not supported."); - } + public void GetSamplesAsync(short[] samples) => throw new InvalidOperationException("Async mode is not supported."); } } diff --git a/src/BizHawk.Emulation.Cores/Consoles/WonderSwan/WonderSwan.IStatable.cs b/src/BizHawk.Emulation.Cores/Consoles/WonderSwan/WonderSwan.IStatable.cs index 377491cb642..dd6710602eb 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/WonderSwan/WonderSwan.IStatable.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/WonderSwan/WonderSwan.IStatable.cs @@ -10,12 +10,9 @@ namespace BizHawk.Emulation.Cores.WonderSwan { partial class WonderSwan: ITextStatable { - private void InitIStatable() - { - savebuff = new byte[BizSwan.bizswan_binstatesize(Core)]; - } + private void InitIStatable() => savebuff = new byte[BizSwan.bizswan_binstatesize(Core)]; - private readonly JsonSerializer ser = new JsonSerializer { Formatting = Formatting.Indented }; + private readonly JsonSerializer ser = new() { Formatting = Formatting.Indented }; [StructLayout(LayoutKind.Sequential)] private class TextStateData @@ -40,7 +37,7 @@ private void SaveTextStateData(TextStateData d) public void SaveStateText(TextWriter writer) { - var s = new TextState(); + TextState s = new(); s.Prepare(); var ff = s.GetFunctionPointersSave(); BizSwan.bizswan_txtstatesave(Core, ref ff); @@ -50,7 +47,7 @@ public void SaveStateText(TextWriter writer) public void LoadStateText(TextReader reader) { - var s = (TextState)ser.Deserialize(reader, typeof(TextState)); + TextState s = (TextState)ser.Deserialize(reader, typeof(TextState)); s.Prepare(); var ff = s.GetFunctionPointersLoad(); BizSwan.bizswan_txtstateload(Core, ref ff); @@ -68,7 +65,7 @@ public void SaveStateBinary(BinaryWriter writer) writer.Write(savebuff.Length); writer.Write(savebuff); - var d = new TextStateData(); + TextStateData d = new(); SaveTextStateData(d); BinaryQuickSerializer.Write(d, writer); } diff --git a/src/BizHawk.Emulation.Cores/Consoles/WonderSwan/WonderSwan.cs b/src/BizHawk.Emulation.Cores/Consoles/WonderSwan/WonderSwan.cs index 044b411809d..aee43a249a6 100644 --- a/src/BizHawk.Emulation.Cores/Consoles/WonderSwan/WonderSwan.cs +++ b/src/BizHawk.Emulation.Cores/Consoles/WonderSwan/WonderSwan.cs @@ -99,15 +99,15 @@ public void ResetCounters() public string SystemId => VSystemID.Raw.WSWAN; public bool DeterministicEmulation { get; } - private readonly InputCallbackSystem _inputCallbacks = new InputCallbackSystem(); + private readonly InputCallbackSystem _inputCallbacks = new(); public IInputCallbackSystem InputCallbacks => _inputCallbacks; - private readonly MemoryCallbackSystem _memorycallbacks = new MemoryCallbackSystem(new[] { "System Bus" }); // This isn't an actual memory domain in this core (yet), but there's nothing that enforces that it has to be + private readonly MemoryCallbackSystem _memorycallbacks = new(new[] { "System Bus" }); // This isn't an actual memory domain in this core (yet), but there's nothing that enforces that it has to be public IMemoryCallbackSystem MemoryCallbacks => _memorycallbacks; public IDictionary GetCpuFlagsAndRegisters() { - var ret = new Dictionary(); + Dictionary ret = new(); for (int i = (int)BizSwan.NecRegsMin; i <= (int)BizSwan.NecRegsMax; i++) { BizSwan.NecRegs en = (BizSwan.NecRegs)i; @@ -118,10 +118,7 @@ public IDictionary GetCpuFlagsAndRegisters() } [FeatureNotImplemented] - public void SetCpuRegister(string register, int value) - { - throw new NotImplementedException(); - } + public void SetCpuRegister(string register, int value) => throw new NotImplementedException(); public bool CanStep(StepType type) => false; @@ -163,10 +160,7 @@ private void ExecCallback(uint addr) } } - private void ButtonCallback() - { - InputCallbacks.Call(); - } + private void ButtonCallback() => InputCallbacks.Call(); private void InitDebugCallbacks() { @@ -178,10 +172,7 @@ private void InitDebugCallbacks() _memorycallbacks.ActiveChanged += SetMemoryCallbacks; } - private void SetInputCallback() - { - BizSwan.bizswan_setbuttoncallback(Core, InputCallbacks.Any() ? ButtonCallbackD : null); - } + private void SetInputCallback() => BizSwan.bizswan_setbuttoncallback(Core, InputCallbacks.Any() ? ButtonCallbackD : null); private void SetMemoryCallbacks() { diff --git a/src/BizHawk.Emulation.Cores/CoreInventory.cs b/src/BizHawk.Emulation.Cores/CoreInventory.cs index 6573150a4d7..a824aa0a22d 100644 --- a/src/BizHawk.Emulation.Cores/CoreInventory.cs +++ b/src/BizHawk.Emulation.Cores/CoreInventory.cs @@ -14,7 +14,7 @@ namespace BizHawk.Emulation.Cores /// public class CoreInventory { - private readonly Dictionary> _systems = new Dictionary>(); + private readonly Dictionary> _systems = new(); /// keys are system IDs; values are core/ctor info for all that system's cores public IReadOnlyDictionary> AllCores => _systems; @@ -33,7 +33,7 @@ private class RomGameFake : IRomAsset } // map parameter names to locations in the constructor - private readonly Dictionary _paramMap = new Dictionary(); + private readonly Dictionary _paramMap = new(); // If true, this is a new style constructor that takes a CoreLoadParameters object private readonly bool _useCoreLoadParameters; @@ -90,7 +90,7 @@ public Core(Type type, CoreConstructorAttribute consAttr, CoreAttribute coreAttr private void Bp(object[] parameters, string name, object value) { - if (_paramMap.TryGetValue(name, out var i)) + if (_paramMap.TryGetValue(name, out int i)) { parameters[i] = value; } @@ -160,10 +160,10 @@ public IEnumerable GetCores(string system) /// public CoreInventory(IEnumerable> assys) { - var systemsFlat = new Dictionary(); + Dictionary systemsFlat = new(); void ProcessConstructor(Type type, CoreConstructorAttribute consAttr, CoreAttribute coreAttr, ConstructorInfo cons) { - var core = new Core(type, consAttr, coreAttr, cons); + Core core = new(type, consAttr, coreAttr, cons); _systems.GetValueOrPutNew(consAttr.System).Add(core); systemsFlat[type] = core; } @@ -173,7 +173,7 @@ void ProcessConstructor(Type type, CoreConstructorAttribute consAttr, CoreAttrib { if (!typ.IsAbstract && typ.GetInterfaces().Contains(typeof(IEmulator))) { - var coreAttr = typ.GetCustomAttributes(typeof(CoreAttribute), false); + object[] coreAttr = typ.GetCustomAttributes(typeof(CoreAttribute), false); if (coreAttr.Length != 1) throw new InvalidOperationException($"{nameof(IEmulator)} {typ} without {nameof(CoreAttribute)}s!"); var cons = typ.GetConstructors(BindingFlags.Public | BindingFlags.Instance) @@ -191,7 +191,7 @@ void ProcessConstructor(Type type, CoreConstructorAttribute consAttr, CoreAttrib SystemsFlat = systemsFlat.Values; } - public static readonly CoreInventory Instance = new CoreInventory(new[] { Emulation.Cores.ReflectionCache.Types }); + public static readonly CoreInventory Instance = new(new[] { Emulation.Cores.ReflectionCache.Types }); } public enum CorePriority diff --git a/src/BizHawk.Emulation.Cores/FileID.cs b/src/BizHawk.Emulation.Cores/FileID.cs index 59a77464674..1e6b299bfc8 100644 --- a/src/BizHawk.Emulation.Cores/FileID.cs +++ b/src/BizHawk.Emulation.Cores/FileID.cs @@ -93,10 +93,7 @@ public FileIDResults(FileIDResult item) { base.Add(item); } - public new void Sort() - { - base.Sort((x, y) => x.Confidence.CompareTo(y.Confidence)); - } + public new void Sort() => base.Sort((x, y) => x.Confidence.CompareTo(y.Confidence)); /// /// indicates whether the client should try again after mounting the disc image for further inspection @@ -140,7 +137,7 @@ private class IdentifyJob /// public FileIDResults Identify(IdentifyParams p) { - IdentifyJob job = new IdentifyJob() { + IdentifyJob job = new() { Stream = p.SeekableStream, Disc = p.Disc }; @@ -149,7 +146,7 @@ public FileIDResults Identify(IdentifyParams p) if (job.Disc != null) return IdentifyDisc(job); - FileIDResults ret = new FileIDResults(); + FileIDResults ret = new(); string ext = p.Extension; if(ext != null) @@ -182,7 +179,7 @@ public FileIDResults Identify(IdentifyParams p) //add a low confidence result just based on extension, if it doesnt exist if(ret.Find( (x) => x.FileIDType == handler.DefaultForExtension) == null) { - var fidr = new FileIDResult(handler.DefaultForExtension, 5); + FileIDResult fidr = new(handler.DefaultForExtension, 5); ret.Add(fidr); } } @@ -214,30 +211,17 @@ public FileIDType IdentifySimple(IdentifyParams p) private FileIDResults IdentifyDisc(IdentifyJob job) { - var discIdentifier = new DiscSystem.DiscIdentifier(job.Disc); + DiscSystem.DiscIdentifier discIdentifier = new(job.Disc); //DiscSystem could use some newer approaches from this file (instead of parsing ISO filesystem... maybe?) - switch (discIdentifier.DetectDiscType()) + return discIdentifier.DetectDiscType() switch { - case DiscSystem.DiscType.SegaSaturn: - return new FileIDResults(new FileIDResult(FileIDType.Saturn, 100)); - - case DiscSystem.DiscType.SonyPSP: - return new FileIDResults(new FileIDResult(FileIDType.PSP, 100)); - - case DiscSystem.DiscType.SonyPSX: - return new FileIDResults(new FileIDResult(FileIDType.PSX, 100)); - - case DiscSystem.DiscType.MegaCD: - return new FileIDResults(new FileIDResult(FileIDType.MegaCD, 100)); - - case DiscSystem.DiscType.TurboCD: - return new FileIDResults(new FileIDResult(FileIDType.TurboCD, 5)); - - case DiscSystem.DiscType.UnknownCDFS: - case DiscSystem.DiscType.UnknownFormat: - default: - return new FileIDResults(new FileIDResult()); - } + DiscSystem.DiscType.SegaSaturn => new FileIDResults(new FileIDResult(FileIDType.Saturn, 100)), + DiscSystem.DiscType.SonyPSP => new FileIDResults(new FileIDResult(FileIDType.PSP, 100)), + DiscSystem.DiscType.SonyPSX => new FileIDResults(new FileIDResult(FileIDType.PSX, 100)), + DiscSystem.DiscType.MegaCD => new FileIDResults(new FileIDResult(FileIDType.MegaCD, 100)), + DiscSystem.DiscType.TurboCD => new FileIDResults(new FileIDResult(FileIDType.TurboCD, 5)), + _ => new FileIDResults(new FileIDResult()), + }; } private class SimpleMagicRecord @@ -252,45 +236,45 @@ private class SimpleMagicRecord //if you change some of the Length arguments for longer keys, please make notes about why private static class SimpleMagics { - public static readonly SimpleMagicRecord INES = new SimpleMagicRecord { Offset = 0, Key = "NES" }; - public static readonly SimpleMagicRecord UNIF = new SimpleMagicRecord { Offset = 0, Key = "UNIF" }; - public static SimpleMagicRecord NSF = new SimpleMagicRecord { Offset = 0, Key = "NESM\x1A" }; + public static readonly SimpleMagicRecord INES = new() { Offset = 0, Key = "NES" }; + public static readonly SimpleMagicRecord UNIF = new() { Offset = 0, Key = "UNIF" }; + public static SimpleMagicRecord NSF = new() { Offset = 0, Key = "NESM\x1A" }; - public static readonly SimpleMagicRecord FDS_HEADERLESS = new SimpleMagicRecord { Offset = 0, Key = "\x01*NINTENDO-HVC*" }; - public static readonly SimpleMagicRecord FDS_HEADER = new SimpleMagicRecord { Offset = 0, Key = "FDS\x1A" }; + public static readonly SimpleMagicRecord FDS_HEADERLESS = new() { Offset = 0, Key = "\x01*NINTENDO-HVC*" }; + public static readonly SimpleMagicRecord FDS_HEADER = new() { Offset = 0, Key = "FDS\x1A" }; //the GBA nintendo logo.. we'll only use 16 bytes of it but theyre all here, for reference //we cant expect these roms to be normally sized, but we may be able to find other features of the header to use for extra checks - public static readonly SimpleMagicRecord GBA = new SimpleMagicRecord { Offset = 4, Length = 16, Key = "\x24\xFF\xAE\x51\x69\x9A\xA2\x21\x3D\x84\x82\x0A\x84\xE4\x09\xAD\x11\x24\x8B\x98\xC0\x81\x7F\x21\xA3\x52\xBE\x19\x93\x09\xCE\x20\x10\x46\x4A\x4A\xF8\x27\x31\xEC\x58\xC7\xE8\x33\x82\xE3\xCE\xBF\x85\xF4\xDF\x94\xCE\x4B\x09\xC1\x94\x56\x8A\xC0\x13\x72\xA7\xFC\x9F\x84\x4D\x73\xA3\xCA\x9A\x61\x58\x97\xA3\x27\xFC\x03\x98\x76\x23\x1D\xC7\x61\x03\x04\xAE\x56\xBF\x38\x84\x00\x40\xA7\x0E\xFD\xFF\x52\xFE\x03\x6F\x95\x30\xF1\x97\xFB\xC0\x85\x60\xD6\x80\x25\xA9\x63\xBE\x03\x01\x4E\x38\xE2\xF9\xA2\x34\xFF\xBB\x3E\x03\x44\x78\x00\x90\xCB\x88\x11\x3A\x94\x65\xC0\x7C\x63\x87\xF0\x3C\xAF\xD6\x25\xE4\x8B\x38\x0A\xAC\x72\x21\xD4\xF8\x07" }; - public static readonly SimpleMagicRecord NDS = new SimpleMagicRecord { Offset = 0xC0, Length = 16, Key = "\x24\xFF\xAE\x51\x69\x9A\xA2\x21\x3D\x84\x82\x0A\x84\xE4\x09\xAD\x11\x24\x8B\x98\xC0\x81\x7F\x21\xA3\x52\xBE\x19\x93\x09\xCE\x20\x10\x46\x4A\x4A\xF8\x27\x31\xEC\x58\xC7\xE8\x33\x82\xE3\xCE\xBF\x85\xF4\xDF\x94\xCE\x4B\x09\xC1\x94\x56\x8A\xC0\x13\x72\xA7\xFC\x9F\x84\x4D\x73\xA3\xCA\x9A\x61\x58\x97\xA3\x27\xFC\x03\x98\x76\x23\x1D\xC7\x61\x03\x04\xAE\x56\xBF\x38\x84\x00\x40\xA7\x0E\xFD\xFF\x52\xFE\x03\x6F\x95\x30\xF1\x97\xFB\xC0\x85\x60\xD6\x80\x25\xA9\x63\xBE\x03\x01\x4E\x38\xE2\xF9\xA2\x34\xFF\xBB\x3E\x03\x44\x78\x00\x90\xCB\x88\x11\x3A\x94\x65\xC0\x7C\x63\x87\xF0\x3C\xAF\xD6\x25\xE4\x8B\x38\x0A\xAC\x72\x21\xD4\xF8\x07" }; + public static readonly SimpleMagicRecord GBA = new() { Offset = 4, Length = 16, Key = "\x24\xFF\xAE\x51\x69\x9A\xA2\x21\x3D\x84\x82\x0A\x84\xE4\x09\xAD\x11\x24\x8B\x98\xC0\x81\x7F\x21\xA3\x52\xBE\x19\x93\x09\xCE\x20\x10\x46\x4A\x4A\xF8\x27\x31\xEC\x58\xC7\xE8\x33\x82\xE3\xCE\xBF\x85\xF4\xDF\x94\xCE\x4B\x09\xC1\x94\x56\x8A\xC0\x13\x72\xA7\xFC\x9F\x84\x4D\x73\xA3\xCA\x9A\x61\x58\x97\xA3\x27\xFC\x03\x98\x76\x23\x1D\xC7\x61\x03\x04\xAE\x56\xBF\x38\x84\x00\x40\xA7\x0E\xFD\xFF\x52\xFE\x03\x6F\x95\x30\xF1\x97\xFB\xC0\x85\x60\xD6\x80\x25\xA9\x63\xBE\x03\x01\x4E\x38\xE2\xF9\xA2\x34\xFF\xBB\x3E\x03\x44\x78\x00\x90\xCB\x88\x11\x3A\x94\x65\xC0\x7C\x63\x87\xF0\x3C\xAF\xD6\x25\xE4\x8B\x38\x0A\xAC\x72\x21\xD4\xF8\x07" }; + public static readonly SimpleMagicRecord NDS = new() { Offset = 0xC0, Length = 16, Key = "\x24\xFF\xAE\x51\x69\x9A\xA2\x21\x3D\x84\x82\x0A\x84\xE4\x09\xAD\x11\x24\x8B\x98\xC0\x81\x7F\x21\xA3\x52\xBE\x19\x93\x09\xCE\x20\x10\x46\x4A\x4A\xF8\x27\x31\xEC\x58\xC7\xE8\x33\x82\xE3\xCE\xBF\x85\xF4\xDF\x94\xCE\x4B\x09\xC1\x94\x56\x8A\xC0\x13\x72\xA7\xFC\x9F\x84\x4D\x73\xA3\xCA\x9A\x61\x58\x97\xA3\x27\xFC\x03\x98\x76\x23\x1D\xC7\x61\x03\x04\xAE\x56\xBF\x38\x84\x00\x40\xA7\x0E\xFD\xFF\x52\xFE\x03\x6F\x95\x30\xF1\x97\xFB\xC0\x85\x60\xD6\x80\x25\xA9\x63\xBE\x03\x01\x4E\x38\xE2\xF9\xA2\x34\xFF\xBB\x3E\x03\x44\x78\x00\x90\xCB\x88\x11\x3A\x94\x65\xC0\x7C\x63\x87\xF0\x3C\xAF\xD6\x25\xE4\x8B\x38\x0A\xAC\x72\x21\xD4\xF8\x07" }; - public static readonly SimpleMagicRecord GB = new SimpleMagicRecord { Offset=0x104, Length = 16, Key = "\xCE\xED\x66\x66\xCC\x0D\x00\x0B\x03\x73\x00\x83\x00\x0C\x00\x0D\x00\x08\x11\x1F\x88\x89\x00\x0E\xDC\xCC\x6E\xE6\xDD\xDD\xD9\x99\xBB\xBB\x67\x63\x6E\x0E\xEC\xCC\xDD\xDC\x99\x9F\xBB\xB9\x33\x3E" }; + public static readonly SimpleMagicRecord GB = new() { Offset=0x104, Length = 16, Key = "\xCE\xED\x66\x66\xCC\x0D\x00\x0B\x03\x73\x00\x83\x00\x0C\x00\x0D\x00\x08\x11\x1F\x88\x89\x00\x0E\xDC\xCC\x6E\xE6\xDD\xDD\xD9\x99\xBB\xBB\x67\x63\x6E\x0E\xEC\xCC\xDD\xDC\x99\x9F\xBB\xB9\x33\x3E" }; - public static readonly SimpleMagicRecord S32X = new SimpleMagicRecord { Offset = 0x100, Key = "SEGA 32X" }; + public static readonly SimpleMagicRecord S32X = new() { Offset = 0x100, Key = "SEGA 32X" }; - public static readonly SimpleMagicRecord SEGAGENESIS = new SimpleMagicRecord { Offset = 0x100, Key = "SEGA GENESIS" }; - public static readonly SimpleMagicRecord SEGAMEGADRIVE = new SimpleMagicRecord { Offset = 0x100, Key = "SEGA MEGA DRIVE" }; - public static readonly SimpleMagicRecord SEGASATURN = new SimpleMagicRecord { Offset = 0, Key = "SEGA SEGASATURN" }; - public static readonly SimpleMagicRecord SEGADISCSYSTEM = new SimpleMagicRecord { Offset = 0, Key = "SEGADISCSYSTEM" }; + public static readonly SimpleMagicRecord SEGAGENESIS = new() { Offset = 0x100, Key = "SEGA GENESIS" }; + public static readonly SimpleMagicRecord SEGAMEGADRIVE = new() { Offset = 0x100, Key = "SEGA MEGA DRIVE" }; + public static readonly SimpleMagicRecord SEGASATURN = new() { Offset = 0, Key = "SEGA SEGASATURN" }; + public static readonly SimpleMagicRecord SEGADISCSYSTEM = new() { Offset = 0, Key = "SEGADISCSYSTEM" }; - public static readonly SimpleMagicRecord PSX = new SimpleMagicRecord { Offset = 0x24E0, Key = " Licensed by Sony Computer Entertainment" }; //there might be other ideas for checking in mednafen sources, if we need them - public static readonly SimpleMagicRecord PSX_EXE = new SimpleMagicRecord { Key = "PS-X EXE\0" }; - public static readonly SimpleMagicRecord PSP = new SimpleMagicRecord { Offset = 0x8000, Key = "\x01CD001\x01\0x00PSP GAME" }; - public static readonly SimpleMagicRecord PSF = new SimpleMagicRecord { Offset = 0, Key = "PSF\x1" }; + public static readonly SimpleMagicRecord PSX = new() { Offset = 0x24E0, Key = " Licensed by Sony Computer Entertainment" }; //there might be other ideas for checking in mednafen sources, if we need them + public static readonly SimpleMagicRecord PSX_EXE = new() { Key = "PS-X EXE\0" }; + public static readonly SimpleMagicRecord PSP = new() { Offset = 0x8000, Key = "\x01CD001\x01\0x00PSP GAME" }; + public static readonly SimpleMagicRecord PSF = new() { Offset = 0, Key = "PSF\x1" }; //https://sites.google.com/site/atari7800wiki/a78-header - public static readonly SimpleMagicRecord A78 = new SimpleMagicRecord { Offset = 0, Key = "\x01ATARI7800" }; + public static readonly SimpleMagicRecord A78 = new() { Offset = 0, Key = "\x01ATARI7800" }; //could be at various offsets? - public static SimpleMagicRecord TMR_SEGA = new SimpleMagicRecord { Offset = 0x7FF0, Key = "TMR SEGA" }; + public static SimpleMagicRecord TMR_SEGA = new() { Offset = 0x7FF0, Key = "TMR SEGA" }; - public static readonly SimpleMagicRecord SBI = new SimpleMagicRecord { Key = "SBI\0" }; - public static readonly SimpleMagicRecord M3U = new SimpleMagicRecord { Key = "#EXTM3U" }; //note: M3U may not have this. EXTM3U only has it. We'll still catch it by extension though. + public static readonly SimpleMagicRecord SBI = new() { Key = "SBI\0" }; + public static readonly SimpleMagicRecord M3U = new() { Key = "#EXTM3U" }; //note: M3U may not have this. EXTM3U only has it. We'll still catch it by extension though. - public static readonly SimpleMagicRecord ECM = new SimpleMagicRecord { Key = "ECM\0" }; - public static readonly SimpleMagicRecord FLAC = new SimpleMagicRecord { Key = "fLaC" }; - public static readonly SimpleMagicRecord MPC = new SimpleMagicRecord { Key = "MP+", ExtraCheck = (s) => { s.Position += 3; return s.ReadByte() >= 7; } }; - public static readonly SimpleMagicRecord APE = new SimpleMagicRecord { Key = "MAC " }; + public static readonly SimpleMagicRecord ECM = new() { Key = "ECM\0" }; + public static readonly SimpleMagicRecord FLAC = new() { Key = "fLaC" }; + public static readonly SimpleMagicRecord MPC = new() { Key = "MP+", ExtraCheck = (s) => { s.Position += 3; return s.ReadByte() >= 7; } }; + public static readonly SimpleMagicRecord APE = new() { Key = "MAC " }; public static readonly SimpleMagicRecord[] WAV = { new SimpleMagicRecord { Offset = 0, Key = "RIFF" }, new SimpleMagicRecord { Offset = 8, Key = "WAVEfmt " } @@ -314,7 +298,8 @@ public ExtensionInfo(FileIDType defaultForExtension, FormatTester tester) /// /// testers to try for each extension, along with a default for the extension /// - private static readonly Dictionary ExtensionHandlers = new Dictionary { + private static readonly Dictionary ExtensionHandlers = new() + { { "NES", new ExtensionInfo(FileIDType.INES, Test_INES ) }, { "FDS", new ExtensionInfo(FileIDType.FDS, Test_FDS ) }, { "GBA", new ExtensionInfo(FileIDType.GBA, (j)=>Test_Simple(j,FileIDType.GBA,SimpleMagics.GBA) ) }, @@ -410,10 +395,7 @@ private static bool CheckMagic(Stream stream, IEnumerable rec return false; } - private static bool CheckMagic(Stream stream, SimpleMagicRecord rec, params int[] offsets) - { - return CheckMagic(stream, new SimpleMagicRecord[] { rec }, offsets); - } + private static bool CheckMagic(Stream stream, SimpleMagicRecord rec, params int[] offsets) => CheckMagic(stream, new SimpleMagicRecord[] { rec }, offsets); private static bool CheckMagicOne(Stream stream, SimpleMagicRecord rec, int offset) { @@ -448,7 +430,7 @@ private static FileIDResult Test_INES(IdentifyJob job) if (!CheckMagic(job.Stream, SimpleMagics.INES)) return new FileIDResult(); - var ret = new FileIDResult(FileIDType.INES, 100); + FileIDResult ret = new(FileIDType.INES, 100); //an INES file should be a multiple of 8k, with the 16 byte header. //if it isnt.. this is fishy. @@ -473,7 +455,7 @@ private static FileIDResult Test_FDS(IdentifyJob job) /// private static FileIDResult Test_Simple(IdentifyJob job, FileIDType type, SimpleMagicRecord[] magics) { - var ret = new FileIDResult(type); + FileIDResult ret = new(type); if (CheckMagic(job.Stream, magics)) return new FileIDResult(type, 100); @@ -483,7 +465,7 @@ private static FileIDResult Test_Simple(IdentifyJob job, FileIDType type, Simple private static FileIDResult Test_Simple(IdentifyJob job, FileIDType type, SimpleMagicRecord magic) { - var ret = new FileIDResult(type); + FileIDResult ret = new(type); if (CheckMagic(job.Stream, magic)) return new FileIDResult(type, 100); @@ -498,7 +480,7 @@ private static FileIDResult Test_UNIF(IdentifyJob job) //TODO - simple parser (for starters, check for a known chunk being next, see http://wiki.nesdev.com/w/index.php/UNIF) - var ret = new FileIDResult(FileIDType.UNIF, 100); + FileIDResult ret = new(FileIDType.UNIF, 100); return ret; } @@ -508,7 +490,7 @@ private static FileIDResult Test_GB_GBC(IdentifyJob job) if (!CheckMagic(job.Stream, SimpleMagics.GB)) return new FileIDResult(); - var ret = new FileIDResult(FileIDType.GB, 100); + FileIDResult ret = new(FileIDType.GB, 100); int type = ReadByte(job.Stream, 0x143); if ((type & 0x80) != 0) ret.FileIDType = FileIDType.GBC; @@ -518,13 +500,11 @@ private static FileIDResult Test_GB_GBC(IdentifyJob job) return ret; } - private static FileIDResult Test_SMS(IdentifyJob job) - { + private static FileIDResult Test_SMS(IdentifyJob job) => //http://www.smspower.org/Development/ROMHeader //actually, not sure how to handle this yet - return new FileIDResult(); - } + new(); private static FileIDResult Test_N64(IdentifyJob job) { @@ -533,7 +513,7 @@ private static FileIDResult Test_N64(IdentifyJob job) // .V64 = Byte Swapped //not sure how to check for these yet... - var ret = new FileIDResult(FileIDType.N64, 5); + FileIDResult ret = new(FileIDType.N64, 5); if (job.Extension == "V64") ret.ExtraInfo["byteswap"] = true; if (job.Extension == "N64") ret.ExtraInfo["wordswap"] = true; return ret; @@ -588,7 +568,7 @@ private static FileIDResult Test_BIN_ISO(IdentifyJob job) //so, I think it's possible that every valid PSX disc is mode2 in the track 1 if (CheckMagic(job.Stream, SimpleMagics.PSX)) { - var ret = new FileIDResult(FileIDType.PSX, 95); + FileIDResult ret = new(FileIDType.PSX, 95); //this is an unreliable way to get a PSX game! ret.ExtraInfo["unreliable"] = true; return ret; @@ -616,12 +596,10 @@ private static FileIDResult Test_BIN_ISO(IdentifyJob job) return new FileIDResult(FileIDType.Multiple, 1); } - private static FileIDResult Test_JAD_JAC(IdentifyJob job) - { + private static FileIDResult Test_JAD_JAC(IdentifyJob job) => //TBD //just mount it as a disc and send it through the disc checker? - return null; - } + null; } } diff --git a/src/BizHawk.Emulation.Cores/Libretro/Libretro.IEmulator.cs b/src/BizHawk.Emulation.Cores/Libretro/Libretro.IEmulator.cs index e559b302222..f4e0c79391a 100644 --- a/src/BizHawk.Emulation.Cores/Libretro/Libretro.IEmulator.cs +++ b/src/BizHawk.Emulation.Cores/Libretro/Libretro.IEmulator.cs @@ -80,7 +80,7 @@ public class LibretroControllerDef : ControllerDefinition public LibretroControllerDef() : base(name: "LibRetro Controls"/*for compatibility*/) { - for (var player = 1; player <= 2; player++) foreach (var button in new[] { "Up", "Down", "Left", "Right", "Select", "Start", "Y", "B", "X", "A", "L", "R", "L2", "R2", "L3", "R3", }) + for (int player = 1; player <= 2; player++) foreach (string button in new[] { "Up", "Down", "Left", "Right", "Select", "Start", "Y", "B", "X", "A", "L", "R", "L2", "R2", "L3", "R3", }) { BoolButtons.Add($"P{player} {PFX_RETROPAD}{button}"); } @@ -88,7 +88,7 @@ public LibretroControllerDef() BoolButtons.Add("Pointer Pressed"); this.AddXYPair("Pointer {0}", AxisPairOrientation.RightAndUp, (-32767).RangeTo(32767), 0); - foreach (var s in new[] { + foreach (string s in new[] { "Backspace", "Tab", "Clear", "Return", "Pause", "Escape", "Space", "Exclaim", "QuoteDbl", "Hash", "Dollar", "Ampersand", "Quote", "LeftParen", "RightParen", "Asterisk", "Plus", "Comma", "Minus", "Period", "Slash", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", @@ -103,7 +103,7 @@ public LibretroControllerDef() "Help", "Print", "SysReq", "Break", "Menu", "Power", "Euro", "Undo" }) { - var buttonName = $"Key {s}"; + string buttonName = $"Key {s}"; BoolButtons.Add(buttonName); CategoryLabels[buttonName] = CAT_KEYBOARD; } @@ -116,13 +116,13 @@ public LibretroControllerDef() protected override IReadOnlyList> GenOrderedControls() { // all this is to remove the keyboard buttons from P0 and put them in P3 so they appear at the end of the input display - var players = base.GenOrderedControls().ToList(); + List> players = base.GenOrderedControls().ToList(); List retroKeyboard = new(); - var p0 = (List) players[0]; - for (var i = 0; i < p0.Count; /* incremented in body */) + List p0 = (List) players[0]; + for (int i = 0; i < p0.Count; /* incremented in body */) { - var buttonName = p0[i]; - if (CategoryLabels.TryGetValue(buttonName, out var v) && v is CAT_KEYBOARD) + string buttonName = p0[i]; + if (CategoryLabels.TryGetValue(buttonName, out string v) && v is CAT_KEYBOARD) { retroKeyboard.Add(buttonName); p0.RemoveAt(i); diff --git a/src/BizHawk.Emulation.Cores/Libretro/Libretro.IInputPollable.cs b/src/BizHawk.Emulation.Cores/Libretro/Libretro.IInputPollable.cs index 4602b3c836f..af7e435baef 100644 --- a/src/BizHawk.Emulation.Cores/Libretro/Libretro.IInputPollable.cs +++ b/src/BizHawk.Emulation.Cores/Libretro/Libretro.IInputPollable.cs @@ -67,7 +67,7 @@ private static short InputState(IController controller, int port, RETRO_DEVICE d case RETRO_DEVICE.KEYBOARD: { - var button = (RETRO_KEY)id switch + string button = (RETRO_KEY)id switch { RETRO_KEY.BACKSPACE => "Backspace", RETRO_KEY.TAB => "Tab", @@ -212,7 +212,7 @@ private static short InputState(IController controller, int port, RETRO_DEVICE d case RETRO_DEVICE.JOYPAD: { - var button = (RETRO_DEVICE_ID_JOYPAD)id switch + string button = (RETRO_DEVICE_ID_JOYPAD)id switch { RETRO_DEVICE_ID_JOYPAD.A => "A", RETRO_DEVICE_ID_JOYPAD.B => "B", @@ -242,7 +242,7 @@ private static short InputState(IController controller, int port, RETRO_DEVICE d private static bool GetButton(IController controller, int pnum, string type, string button) { - var key = $"P{pnum} {type} {button}"; + string key = $"P{pnum} {type} {button}"; return controller.IsPressed(key); } } diff --git a/src/BizHawk.Emulation.Cores/Libretro/Libretro.IMemoryDomains.cs b/src/BizHawk.Emulation.Cores/Libretro/Libretro.IMemoryDomains.cs index 1f26a620546..4fe7c972126 100644 --- a/src/BizHawk.Emulation.Cores/Libretro/Libretro.IMemoryDomains.cs +++ b/src/BizHawk.Emulation.Cores/Libretro/Libretro.IMemoryDomains.cs @@ -25,7 +25,7 @@ private void InitMemoryDomains() foreach (LibretroApi.RETRO_MEMORY m in Enum.GetValues(typeof(LibretroApi.RETRO_MEMORY))) { var mem = api.retro_get_memory_data(m); - var sz = api.retro_get_memory_size(m); + long sz = api.retro_get_memory_size(m); if (mem != IntPtr.Zero && sz > 0) { MemoryDomainIntPtr d = new(_domainNames[m], MemoryDomain.Endian.Unknown, mem, sz, true, 1); diff --git a/src/BizHawk.Emulation.Cores/Libretro/Libretro.ISaveRam.cs b/src/BizHawk.Emulation.Cores/Libretro/Libretro.ISaveRam.cs index f72e54b3b96..6d6c7ff0673 100644 --- a/src/BizHawk.Emulation.Cores/Libretro/Libretro.ISaveRam.cs +++ b/src/BizHawk.Emulation.Cores/Libretro/Libretro.ISaveRam.cs @@ -16,7 +16,7 @@ public byte[] CloneSaveRam() { if (_saveramSize > 0) { - var buf = new byte[_saveramSize]; + byte[] buf = new byte[_saveramSize]; int index = 0; foreach (var m in _saveramAreas) { diff --git a/src/BizHawk.Emulation.Cores/Libretro/Libretro.ISoundProvider.cs b/src/BizHawk.Emulation.Cores/Libretro/Libretro.ISoundProvider.cs index e2557be88dd..389fcd89408 100644 --- a/src/BizHawk.Emulation.Cores/Libretro/Libretro.ISoundProvider.cs +++ b/src/BizHawk.Emulation.Cores/Libretro/Libretro.ISoundProvider.cs @@ -26,7 +26,7 @@ private void SetupResampler(double sps) private void ProcessSound() { - var len = bridge.LibretroBridge_GetAudioSize(cbHandler); + uint len = bridge.LibretroBridge_GetAudioSize(cbHandler); if (len == 0) // no audio? { return; @@ -50,7 +50,7 @@ private void ProcessSound() _inSampBuf = new short[len]; } - bridge.LibretroBridge_GetAudio(cbHandler, out var ns, _inSampBuf); + bridge.LibretroBridge_GetAudio(cbHandler, out int ns, _inSampBuf); for (uint i = 0; i < ns; i++) { @@ -105,14 +105,8 @@ public void GetSamplesSync(out short[] samples, out int nsamp) DiscardSamples(); } - public void GetSamplesAsync(short[] samples) - { - throw new InvalidOperationException("Async mode is not supported."); - } + public void GetSamplesAsync(short[] samples) => throw new InvalidOperationException("Async mode is not supported."); - public void DiscardSamples() - { - _outSamps = 0; - } + public void DiscardSamples() => _outSamps = 0; } } diff --git a/src/BizHawk.Emulation.Cores/Libretro/Libretro.IStatable.cs b/src/BizHawk.Emulation.Cores/Libretro/Libretro.IStatable.cs index eb19dfe6c9c..4c170c83ad2 100644 --- a/src/BizHawk.Emulation.Cores/Libretro/Libretro.IStatable.cs +++ b/src/BizHawk.Emulation.Cores/Libretro/Libretro.IStatable.cs @@ -25,7 +25,7 @@ public StatableLibretro(LibretroHost host, LibretroApi api, int maxSize) public void SaveStateBinary(BinaryWriter writer) { - var len = checked((int)_api.retro_serialize_size()); + int len = checked((int)_api.retro_serialize_size()); if (len > _stateBuf.Length) { throw new Exception("Core attempted to grow state size. This is not allowed per the libretro API."); @@ -43,7 +43,7 @@ public void SaveStateBinary(BinaryWriter writer) public void LoadStateBinary(BinaryReader reader) { - var len = reader.ReadInt32(); + int len = reader.ReadInt32(); if (len > _stateBuf.Length) { throw new Exception("State buffer size exceeded the core's maximum state size!"); diff --git a/src/BizHawk.Emulation.Cores/Libretro/Libretro.IVideoProvider.cs b/src/BizHawk.Emulation.Cores/Libretro/Libretro.IVideoProvider.cs index 4fc76ac3f0d..72a6375b3e3 100644 --- a/src/BizHawk.Emulation.Cores/Libretro/Libretro.IVideoProvider.cs +++ b/src/BizHawk.Emulation.Cores/Libretro/Libretro.IVideoProvider.cs @@ -15,10 +15,7 @@ private void InitVideoBuffer(int width, int height, int maxSize) bridge.LibretroBridge_SetVideoSize(cbHandler, maxSize); } - private void UpdateVideoBuffer() - { - bridge.LibretroBridge_GetVideo(cbHandler, out _vidWidth, out _vidHeight, _vidBuffer); - } + private void UpdateVideoBuffer() => bridge.LibretroBridge_GetVideo(cbHandler, out _vidWidth, out _vidHeight, _vidBuffer); public int BackgroundColor => 0; public int[] GetVideoBuffer() => _vidBuffer; @@ -27,7 +24,7 @@ public int VirtualWidth { get { - var dar = av_info.geometry.aspect_ratio; + float dar = av_info.geometry.aspect_ratio; if (dar <= 0) { return _vidWidth; @@ -44,7 +41,7 @@ public int VirtualHeight { get { - var dar = av_info.geometry.aspect_ratio; + float dar = av_info.geometry.aspect_ratio; if (dar <= 0) { return _vidHeight; diff --git a/src/BizHawk.Emulation.Cores/Libretro/Libretro.cs b/src/BizHawk.Emulation.Cores/Libretro/Libretro.cs index a6d163e5d0f..68ab047f052 100644 --- a/src/BizHawk.Emulation.Cores/Libretro/Libretro.cs +++ b/src/BizHawk.Emulation.Cores/Libretro/Libretro.cs @@ -20,7 +20,7 @@ public partial class LibretroHost static LibretroHost() { - var resolver = new DynamicLibraryImportResolver( + DynamicLibraryImportResolver resolver = new( OSTailoredCode.IsUnixHost ? "libLibretroBridge.so" : "libLibretroBridge.dll", hasLimitedLifetime: false); bridge = BizInvoker.GetInvoker(resolver, CallingConventionAdapters.Native); @@ -158,7 +158,7 @@ public RetroData(object o, long len = 0) private byte[] RetroString(string managedString) { - var ret = Encoding.UTF8.GetBytes(managedString); + byte[] ret = Encoding.UTF8.GetBytes(managedString); Array.Resize(ref ret, ret.Length + 1); return ret; } @@ -234,7 +234,7 @@ private bool LoadHandler(RETRO_LOAD which, RetroData path = null, RetroData data api.retro_set_input_poll(cb_procs.retro_input_poll_proc); api.retro_set_input_state(cb_procs.retro_input_state_proc); - var len = checked((int)api.retro_serialize_size()); + int len = checked((int)api.retro_serialize_size()); if (len > 0) { _stateWrapper = new StatableLibretro(this, api, len); @@ -264,7 +264,7 @@ private bool LoadHandler(RETRO_LOAD which, RetroData path = null, RetroData data public RetroDescription CalculateDescription() { - var descr = new RetroDescription(); + RetroDescription descr = new(); api.retro_get_system_info(out var sys_info); descr.LibraryName = Mershul.PtrToStringUtf8(sys_info.library_name); descr.LibraryVersion = Mershul.PtrToStringUtf8(sys_info.library_version); diff --git a/src/BizHawk.Emulation.Cores/Sound/CDAudio.cs b/src/BizHawk.Emulation.Cores/Sound/CDAudio.cs index 6a51a20da9c..3556f6e8f4e 100644 --- a/src/BizHawk.Emulation.Cores/Sound/CDAudio.cs +++ b/src/BizHawk.Emulation.Cores/Sound/CDAudio.cs @@ -151,10 +151,7 @@ public void SetSyncMode(SyncSoundMode mode) public SyncSoundMode SyncMode => SyncSoundMode.Async; - public void GetSamplesSync(out short[] samples, out int nsamp) - { - throw new NotImplementedException("Sync sound not yet supported"); - } + public void GetSamplesSync(out short[] samples, out int nsamp) => throw new NotImplementedException("Sync sound not yet supported"); public void GetSamplesAsync(short[] samples) { diff --git a/src/BizHawk.Emulation.Cores/Sound/DualSyncSound.cs b/src/BizHawk.Emulation.Cores/Sound/DualSyncSound.cs index 5974f33a872..55c2ee47238 100644 --- a/src/BizHawk.Emulation.Cores/Sound/DualSyncSound.cs +++ b/src/BizHawk.Emulation.Cores/Sound/DualSyncSound.cs @@ -37,8 +37,8 @@ private static short Mix(short[] buff, int idx) public void Fetch() { - _left.GetSamplesSync(out var sampl, out int nsampl); - _right.GetSamplesSync(out var sampr, out var nsampr); + _left.GetSamplesSync(out short[] sampl, out int nsampl); + _right.GetSamplesSync(out short[] sampr, out int nsampr); int n = Math.Min(nsampl + _leftOverflowCount, nsampr + _rightOverflowCount); @@ -70,10 +70,7 @@ public void DiscardSamples() { } - public void GetSamplesAsync(short[] samples) - { - throw new InvalidOperationException(); - } + public void GetSamplesAsync(short[] samples) => throw new InvalidOperationException(); public void GetSamplesSync(out short[] samples, out int nsamp) { diff --git a/src/BizHawk.Emulation.Cores/Sound/HuC6280PSG.cs b/src/BizHawk.Emulation.Cores/Sound/HuC6280PSG.cs index 4a7cf528b31..ceb78e4761c 100644 --- a/src/BizHawk.Emulation.Cores/Sound/HuC6280PSG.cs +++ b/src/BizHawk.Emulation.Cores/Sound/HuC6280PSG.cs @@ -36,7 +36,7 @@ public class PSGChannel public byte VoiceLatch; private byte WaveTableWriteOffset; - private readonly Queue commands = new Queue(256); + private readonly Queue commands = new(256); private long frameStartTime, frameStopTime; private const int SampleRate = 44100; @@ -69,15 +69,9 @@ internal void BeginFrame(long cycles) frameStartTime = cycles; } - internal void EndFrame(long cycles) - { - frameStopTime = cycles; - } + internal void EndFrame(long cycles) => frameStopTime = cycles; - internal void WritePSG(byte register, byte value, long cycles) - { - commands.Enqueue(new QueuedCommand { Register = register, Value = value, Time = cycles - frameStartTime }); - } + internal void WritePSG(byte register, byte value, long cycles) => commands.Enqueue(new QueuedCommand { Register = register, Value = value, Time = cycles - frameStartTime }); private void WritePSGImmediate(int register, byte value) { diff --git a/src/BizHawk.Emulation.Cores/Sound/MMC5Audio.cs b/src/BizHawk.Emulation.Cores/Sound/MMC5Audio.cs index 48bb0e9fcaf..d7a0c7b98fc 100644 --- a/src/BizHawk.Emulation.Cores/Sound/MMC5Audio.cs +++ b/src/BizHawk.Emulation.Cores/Sound/MMC5Audio.cs @@ -95,10 +95,7 @@ public void SetEnable(bool val) if (!Enable) length = 0; } - public bool ReadLength() - { - return length > 0; - } + public bool ReadLength() => length > 0; public void ClockFrame() { @@ -299,11 +296,7 @@ public void Clock() private readonly Action enqueuer; - private void PulseAddDiff(int value) - { - enqueuer(value * 370); - //Console.WriteLine(value); - } + private void PulseAddDiff(int value) => enqueuer(value * 370);//Console.WriteLine(value); public MMC5Audio(Action enqueuer, Action RaiseIRQ) { diff --git a/src/BizHawk.Emulation.Cores/Sound/OneBitBeeper.cs b/src/BizHawk.Emulation.Cores/Sound/OneBitBeeper.cs index a70d7e9d8be..35d69adb08b 100644 --- a/src/BizHawk.Emulation.Cores/Sound/OneBitBeeper.cs +++ b/src/BizHawk.Emulation.Cores/Sound/OneBitBeeper.cs @@ -39,18 +39,12 @@ public OneBitBeeper(int blipSampleRate, int clocksPerFrame, int framesPerSecond, /// /// Option to clock the beeper every CPU clock /// - public void Clock(int clocksToAdd = 1) - { - clockCounter += clocksToAdd; - } + public void Clock(int clocksToAdd = 1) => clockCounter += clocksToAdd; /// /// Option to directly set the current clock position within the frame /// - public void SetClock(int currentFrameClock) - { - clockCounter = currentFrameClock; - } + public void SetClock(int currentFrameClock) => clockCounter = currentFrameClock; private bool lastPulse; @@ -90,7 +84,7 @@ public int Volume get => VolumeConverterOut(_volume); set { - var newVol = VolumeConverterIn(value); + int newVol = VolumeConverterIn(value); if (newVol != _volume) _blip.Clear(); _volume = VolumeConverterIn(value); @@ -139,15 +133,9 @@ public void SetSyncMode(SyncSoundMode mode) throw new InvalidOperationException("Only Sync mode is supported."); } - public void GetSamplesAsync(short[] samples) - { - throw new NotSupportedException("Async is not available"); - } + public void GetSamplesAsync(short[] samples) => throw new NotSupportedException("Async is not available"); - public void DiscardSamples() - { - _blip.Clear(); - } + public void DiscardSamples() => _blip.Clear(); public void GetSamplesSync(out short[] samples, out int nsamp) { diff --git a/src/BizHawk.Emulation.Cores/Sound/SN76489sms.cs b/src/BizHawk.Emulation.Cores/Sound/SN76489sms.cs index d7512925946..3f9298b4530 100644 --- a/src/BizHawk.Emulation.Cores/Sound/SN76489sms.cs +++ b/src/BizHawk.Emulation.Cores/Sound/SN76489sms.cs @@ -8,7 +8,7 @@ public sealed class SN76489sms public int current_sample_L; public int current_sample_R; - int aud_scale = 21; + readonly int aud_scale = 21; public SN76489sms() { @@ -111,11 +111,9 @@ public void SyncState(Serializer ser) ser.EndSection(); } - public byte ReadReg() - { + public byte ReadReg() => // not used, reading not allowed, just return 0xFF - return 0xFF; - } + 0xFF; public void WriteReg(byte value) { diff --git a/src/BizHawk.Emulation.Cores/Sound/SoundMixer.cs b/src/BizHawk.Emulation.Cores/Sound/SoundMixer.cs index 7754ac651e4..8fb3489a8ce 100644 --- a/src/BizHawk.Emulation.Cores/Sound/SoundMixer.cs +++ b/src/BizHawk.Emulation.Cores/Sound/SoundMixer.cs @@ -32,10 +32,7 @@ public SoundMixer(int spf, params IMixedSoundProvider[] soundProviders) _spf = spf; } - public void DisableSource(IMixedSoundProvider source) - { - _soundProviders.Remove(source); - } + public void DisableSource(IMixedSoundProvider source) => _soundProviders.Remove(source); public void DiscardSamples() { diff --git a/src/BizHawk.Emulation.Cores/Sound/Sunsoft5BAudio.cs b/src/BizHawk.Emulation.Cores/Sound/Sunsoft5BAudio.cs index 8f79032eb90..aaf7b2490b6 100644 --- a/src/BizHawk.Emulation.Cores/Sound/Sunsoft5BAudio.cs +++ b/src/BizHawk.Emulation.Cores/Sound/Sunsoft5BAudio.cs @@ -90,10 +90,7 @@ public void SetVolume(byte val) private int RegNum; private readonly Pulse[] pulse = new Pulse[3]; - public void RegSelect(byte val) - { - RegNum = val & 15; - } + public void RegSelect(byte val) => RegNum = val & 15; public void RegWrite(byte val) { switch (RegNum) @@ -134,10 +131,7 @@ public void SyncState(Serializer ser) } private readonly Action enqueuer; - private void PulseAddDiff(int val) - { - enqueuer(val * 250); - } + private void PulseAddDiff(int val) => enqueuer(val * 250); public Sunsoft5BAudio(Action enqueuer) { @@ -150,7 +144,7 @@ public Sunsoft5BAudio(Action enqueuer) public void Clock() { - foreach (Pulse p in pulse) + foreach (var p in pulse) { p.Clock(); } diff --git a/src/BizHawk.Emulation.Cores/Sound/SyncSoundMixer.cs b/src/BizHawk.Emulation.Cores/Sound/SyncSoundMixer.cs index 333f250407c..b3e889fddcd 100644 --- a/src/BizHawk.Emulation.Cores/Sound/SyncSoundMixer.cs +++ b/src/BizHawk.Emulation.Cores/Sound/SyncSoundMixer.cs @@ -19,7 +19,7 @@ public sealed class SyncSoundMixer : ISoundProvider /// /// Currently attached ChildProviders /// - private readonly List _soundProviders = new List(); + private readonly List _soundProviders = new(); /// /// The final output max volume @@ -81,10 +81,7 @@ public SyncSoundMixer(SoundMixBalance mixBalanceMethod = SoundMixBalance.Equaliz /// /// The source ISoundProvider /// An ident string for the ISoundProvider (useful when debugging) - public void PinSource(ISoundProvider source, string sourceDescription) - { - PinSource(source, sourceDescription, FinalMaxVolume); - } + public void PinSource(ISoundProvider source, string sourceDescription) => PinSource(source, sourceDescription, FinalMaxVolume); /// /// Adds an ISoundProvider to the SyncSoundMixer @@ -124,7 +121,7 @@ public void EqualizeVolumes() switch (MixBalanceMethod) { case SoundMixBalance.Equalize: - var eachVolume = FinalMaxVolume / _soundProviders.Count; + int eachVolume = FinalMaxVolume / _soundProviders.Count; foreach (var source in _soundProviders) { source.MaxVolume = eachVolume; @@ -167,10 +164,7 @@ public void SetSyncMode(SyncSoundMode mode) throw new InvalidOperationException("Only Sync mode is supported."); } - public void GetSamplesAsync(short[] samples) - { - throw new NotSupportedException("Async is not available"); - } + public void GetSamplesAsync(short[] samples) => throw new NotSupportedException("Async is not available"); public void DiscardSamples() { @@ -266,10 +260,7 @@ private class ChildProvider /// /// Fetches sample data from the child ISoundProvider /// - public void GetSamples() - { - SoundProvider.GetSamplesSync(out InputBuffer, out InputNSamp); - } + public void GetSamples() => SoundProvider.GetSamplesSync(out InputBuffer, out InputNSamp); /// /// Ensures the output buffer is ready for mixing based on the supplied nsamp value @@ -278,13 +269,13 @@ public void GetSamples() public void PrepareOutput(int nsamp) { OutputNSamp = nsamp; - var outputBuffSize = OutputNSamp * 2; + int outputBuffSize = OutputNSamp * 2; if (OutputNSamp != InputNSamp || InputBuffer.Length != outputBuffSize) { OutputBuffer = new short[outputBuffSize]; - var i = 0; + int i = 0; while (i < InputBuffer.Length && i < outputBuffSize) { OutputBuffer[i] = InputBuffer[i]; diff --git a/src/BizHawk.Emulation.Cores/Sound/VRC6Alt.cs b/src/BizHawk.Emulation.Cores/Sound/VRC6Alt.cs index e95f4bf75d7..bec2d84ec03 100644 --- a/src/BizHawk.Emulation.Cores/Sound/VRC6Alt.cs +++ b/src/BizHawk.Emulation.Cores/Sound/VRC6Alt.cs @@ -25,15 +25,9 @@ public VRC6Alt(Action enqueuer) // the two pulse channels are about the same volume as 2a03 pulse channels. // everything is flipped, though; but that's taken care of in the classes - private void PulseAddDiff(int value) - { - enqueuer(value * 360); - } + private void PulseAddDiff(int value) => enqueuer(value * 360); // saw ends up being not that loud because of differences in implementation - private void SawAddDiff(int value) - { - enqueuer(value * 360); - } + private void SawAddDiff(int value) => enqueuer(value * 360); // state private bool masterenable; @@ -54,9 +48,9 @@ public void SyncState(Serializer ser) ser.EndSection(); } - public void Write9000(byte value) { pulse1.Write0(value); } - public void Write9001(byte value) { pulse1.Write1(value); } - public void Write9002(byte value) { pulse1.Write2(value); } + public void Write9000(byte value) => pulse1.Write0(value); + public void Write9001(byte value) => pulse1.Write1(value); + public void Write9002(byte value) => pulse1.Write2(value); public void Write9003(byte value) { @@ -71,13 +65,13 @@ public void Write9003(byte value) saw.SetRSHIFT(RSHIFT); } - public void WriteA000(byte value) { pulse2.Write0(value); } - public void WriteA001(byte value) { pulse2.Write1(value); } - public void WriteA002(byte value) { pulse2.Write2(value); } + public void WriteA000(byte value) => pulse2.Write0(value); + public void WriteA001(byte value) => pulse2.Write1(value); + public void WriteA002(byte value) => pulse2.Write2(value); - public void WriteB000(byte value) { saw.Write0(value); } - public void WriteB001(byte value) { saw.Write1(value); } - public void WriteB002(byte value) { saw.Write2(value); } + public void WriteB000(byte value) => saw.Write0(value); + public void WriteB001(byte value) => saw.Write1(value); + public void WriteB002(byte value) => saw.Write2(value); public void Clock() { @@ -114,10 +108,7 @@ private class Saw /// latched output, 0..31 private int output; - public void SetRSHIFT(int RSHIFT) - { - this.RSHIFT = RSHIFT; - } + public void SetRSHIFT(int RSHIFT) => this.RSHIFT = RSHIFT; private void SendNew() { @@ -141,10 +132,7 @@ public void SyncState(Serializer ser) ser.Sync(nameof(output), ref output); } - public void Write0(byte value) - { - A = (byte)(value & 63); - } + public void Write0(byte value) => A = (byte)(value & 63); public void Write1(byte value) { F &= 0xf00; @@ -213,10 +201,7 @@ private class Pulse /// latched output, 0..15 private int output; - public void SetRSHIFT(int RSHIFT) - { - this.RSHIFT = RSHIFT; - } + public void SetRSHIFT(int RSHIFT) => this.RSHIFT = RSHIFT; private void SendNew() { diff --git a/src/BizHawk.Emulation.Cores/Sound/YM2413.cs b/src/BizHawk.Emulation.Cores/Sound/YM2413.cs index 843cd71e422..6a8f324fb25 100644 --- a/src/BizHawk.Emulation.Cores/Sound/YM2413.cs +++ b/src/BizHawk.Emulation.Cores/Sound/YM2413.cs @@ -52,15 +52,9 @@ public void Reset() RegisterLatch = 0; } - public void Write(byte value) - { - OPLL_writeReg(opll, RegisterLatch, value); - } + public void Write(byte value) => OPLL_writeReg(opll, RegisterLatch, value); - public void Write(byte register, byte value) - { - OPLL_writeReg(opll, register, value); - } + public void Write(byte register, byte value) => OPLL_writeReg(opll, register, value); public void GetSamples(short[] samples) { @@ -73,7 +67,7 @@ public void GetSamples(short[] samples) } /* Mask */ - private static int OPLL_MASK_CH(int x) { return (1 << (x)); } + private static int OPLL_MASK_CH(int x) => (1 << (x)); private const int OPLL_MASK_HH = (1 << (9)); private const int OPLL_MASK_CYM = (1 << (10)); private const int OPLL_MASK_TOM = (1 << (11)); @@ -205,12 +199,12 @@ public void GetSamples(short[] samples) private const int SL_BITS = 4; private const int SL_MUTE = (1 << SL_BITS); - private static uint EG2DB(uint d) { return ((d) * unchecked((int)(EG_STEP / DB_STEP))); } - private static uint TL2EG(uint d) { return ((d) * unchecked((int)(TL_STEP / EG_STEP))); } - private static uint SL2EG(uint d) { return ((d) * unchecked((int)(SL_STEP / EG_STEP))); } + private static uint EG2DB(uint d) => ((d) * unchecked((int)(EG_STEP / DB_STEP))); + private static uint TL2EG(uint d) => ((d) * unchecked((int)(TL_STEP / EG_STEP))); + private static uint SL2EG(uint d) => ((d) * unchecked((int)(SL_STEP / EG_STEP))); - private static uint DB_POS(double x) { return (uint)((x) / DB_STEP); } - private static uint DB_NEG(double x) { return (uint)(DB_MUTE + DB_MUTE + (x) / DB_STEP); } + private static uint DB_POS(double x) => (uint)((x) / DB_STEP); + private static uint DB_NEG(double x) => (uint)(DB_MUTE + DB_MUTE + (x) / DB_STEP); /* Bits for liner value */ private const int DB2LIN_AMP_BITS = 8; @@ -243,25 +237,25 @@ public void GetSamples(short[] samples) private const double AM_DEPTH = 4.875; /* Cut the lower b bit(s) off. */ - private static uint HIGHBITS(uint c, int b) { return ((c) >> (b)); } + private static uint HIGHBITS(uint c, int b) => ((c) >> (b)); /* Leave the lower b bit(s). */ - private static int LOWBITS(int c, int b) { return ((c) & ((1 << (b)) - 1)); } + private static int LOWBITS(int c, int b) => ((c) & ((1 << (b)) - 1)); /* Expand x which is s bits to d bits. */ - private static int EXPAND_BITS(int x, int s, int d) { return ((x) << ((d) - (s))); } + private static int EXPAND_BITS(int x, int s, int d) => ((x) << ((d) - (s))); /* Expand x which is s bits to d bits and fill expanded bits '1' */ - private static int EXPAND_BITS_X(int x, int s, int d) { return (((x) << ((d) - (s))) | ((1 << ((d) - (s))) - 1)); } + private static int EXPAND_BITS_X(int x, int s, int d) => (((x) << ((d) - (s))) | ((1 << ((d) - (s))) - 1)); /* Adjust envelope speed which depends on sampling rate. */ - private static uint RATE_ADJUST(double x) { return (rate == 49716 ? (uint)x : (uint)((double)(x) * clk / 72 / rate + 0.5)); } /* added 0.5 to round the value*/ + private static uint RATE_ADJUST(double x) => (rate == 49716 ? (uint)x : (uint)((double)(x) * clk / 72 / rate + 0.5)); /* added 0.5 to round the value*/ - private static OPLL_SLOT MOD(OPLL o, int x) { return ((o).slot[(x) << 1]); } - private static OPLL_SLOT CAR(OPLL o, int x) { return ((o).slot[((x) << 1) | 1]); } + private static OPLL_SLOT MOD(OPLL o, int x) => ((o).slot[(x) << 1]); + private static OPLL_SLOT CAR(OPLL o, int x) => ((o).slot[((x) << 1) | 1]); - private static bool BIT(uint s, int b) { return (((s) >> (b)) & 1) != 0; } - private static bool BIT(int s, int b) { return (((s) >> (b)) & 1) != 0; } + private static bool BIT(uint s, int b) => (((s) >> (b)) & 1) != 0; + private static bool BIT(int s, int b) => (((s) >> (b)) & 1) != 0; /* Input clock */ private static uint clk = 844451141; @@ -457,18 +451,12 @@ private static void makeDphaseARTable() RL = Rks & 3; if (RM > 15) RM = 15; - switch (AR) + dphaseARTable[AR, Rks] = AR switch { - case 0: - dphaseARTable[AR, Rks] = 0; - break; - case 15: - dphaseARTable[AR, Rks] = 0;/*EG_DP_WIDTH;*/ - break; - default: - dphaseARTable[AR, Rks] = RATE_ADJUST((uint)((3 * (RL + 4) << (RM + 1)))); - break; - } + 0 => 0, + 15 => 0,/*EG_DP_WIDTH;*/ + _ => RATE_ADJUST((uint)((3 * (RL + 4) << (RM + 1)))), + }; } } @@ -484,15 +472,11 @@ private static void makeDphaseDRTable() RL = Rks & 3; if (RM > 15) RM = 15; - switch (DR) + dphaseDRTable[DR, Rks] = DR switch { - case 0: - dphaseDRTable[DR, Rks] = 0; - break; - default: - dphaseDRTable[DR, Rks] = RATE_ADJUST((uint)((RL + 4) << (RM - 1))); - break; - } + 0 => 0, + _ => RATE_ADJUST((uint)((RL + 4) << (RM - 1))), + }; } } @@ -614,7 +598,7 @@ OPLL public interfaces private const int SLOT_TOM = 16; private const int SLOT_CYM = 17; - private static void UPDATE_PG(OPLL_SLOT S) { (S).dphase = dphaseTable[(S).fnum, (S).block, (S).patch.ml]; } + private static void UPDATE_PG(OPLL_SLOT S) => (S).dphase = dphaseTable[(S).fnum, (S).block, (S).patch.ml]; private static void UPDATE_TLL(OPLL_SLOT S) { @@ -628,9 +612,9 @@ private static void UPDATE_TLL(OPLL_SLOT S) } } - private static void UPDATE_RKS(OPLL_SLOT S) { (S).rks = (uint)rksTable[((S).fnum) >> 8, (S).block, (S).patch.kr]; } - private static void UPDATE_WF(OPLL_SLOT S) { (S).sintbl = (S).patch.wf == 0 ? fullsintable : halfsintable; } - private static void UPDATE_EG(OPLL_SLOT S) { (S).eg_dphase = calc_eg_dphase(S); } + private static void UPDATE_RKS(OPLL_SLOT S) => (S).rks = (uint)rksTable[((S).fnum) >> 8, (S).block, (S).patch.kr]; + private static void UPDATE_WF(OPLL_SLOT S) => (S).sintbl = (S).patch.wf == 0 ? fullsintable : halfsintable; + private static void UPDATE_EG(OPLL_SLOT S) => (S).eg_dphase = calc_eg_dphase(S); private static void UPDATE_ALL(OPLL_SLOT S) { @@ -685,10 +669,7 @@ private static void keyOff(OPLL opll, int i) opll.key_status[i] = 0; } - private static void keyOn_BD(OPLL opll) - { - keyOn(opll, 6); - } + private static void keyOn_BD(OPLL opll) => keyOn(opll, 6); private static void keyOn_SD(OPLL opll) { @@ -715,10 +696,7 @@ private static void keyOn_CYM(OPLL opll) } /* Drum key off */ - private static void keyOff_BD(OPLL opll) - { - keyOff(opll, 6); - } + private static void keyOff_BD(OPLL opll) => keyOff(opll, 6); private static void keyOff_SD(OPLL opll) { @@ -753,10 +731,7 @@ private static void setPatch(OPLL opll, int i, int num) } /* Change a rhythm voice */ - private static void setSlotPatch(OPLL_SLOT slot, OPLL_PATCH patch) - { - slot.patch = patch; - } + private static void setSlotPatch(OPLL_SLOT slot, OPLL_PATCH patch) => slot.patch = patch; /* Set sustine parameter */ private static void setSustine(OPLL opll, int c, int sustine) @@ -767,15 +742,9 @@ private static void setSustine(OPLL opll, int c, int sustine) } /* Volume : 6bit ( Volume register << 2 ) */ - private static void setVolume(OPLL opll, int c, int volume) - { - CAR(opll, c).volume = volume; - } + private static void setVolume(OPLL opll, int c, int volume) => CAR(opll, c).volume = volume; - private static void setSlotVolume(OPLL_SLOT slot, int volume) - { - slot.volume = volume; - } + private static void setSlotVolume(OPLL_SLOT slot, int volume) => slot.volume = volume; /* Set F-Number ( fnum : 9bit ) */ private static void setFnumber(OPLL opll, int c, int fnum) @@ -871,10 +840,7 @@ private static void update_key_status(OPLL opll) } } - private void OPLL_copyPatch(OPLL opll, int num, OPLL_PATCH patch) - { - opll.patch[num] = (OPLL_PATCH)patch.Clone(); - } + private void OPLL_copyPatch(OPLL opll, int num, OPLL_PATCH patch) => opll.patch[num] = (OPLL_PATCH)patch.Clone(); /*********************************************************** @@ -938,7 +904,7 @@ private static void maketables(uint c, uint r) private OPLL OPLL_new(uint clk, uint rate, int type) { - OPLL opll = new OPLL(); + OPLL opll = new(); int i; maketables(clk, rate); @@ -1051,22 +1017,15 @@ private static int wave2_2pi(int e) } /* Convert Amp(0 to EG_HEIGHT) to Phase(0 to 4PI). */ - private static int wave2_4pi(int e) - { - return ((e) << (1 + PG_BITS - SLOT_AMP_BITS)); - /*if ((SLOT_AMP_BITS - PG_BITS - 1) == 0) { + private static int wave2_4pi(int e) => ((e) << (1 + PG_BITS - SLOT_AMP_BITS));/*if ((SLOT_AMP_BITS - PG_BITS - 1) == 0) { return (e); } else if ((SLOT_AMP_BITS - PG_BITS - 1) > 0) { return ((e) >> (SLOT_AMP_BITS - PG_BITS - 1)); } else { return ((e) << (1 + PG_BITS - SLOT_AMP_BITS)); }*/ - } /* Convert Amp(0 to EG_HEIGHT) to Phase(0 to 8PI). */ - private static int wave2_8pi(int e) - { - return ((e) << (2 + PG_BITS - SLOT_AMP_BITS)); - /* + private static int wave2_8pi(int e) => ((e) << (2 + PG_BITS - SLOT_AMP_BITS));/* if ((SLOT_AMP_BITS - PG_BITS - 2) == 0) { return (e); } else if ((SLOT_AMP_BITS - PG_BITS - 2) > 0) { @@ -1075,7 +1034,6 @@ private static int wave2_8pi(int e) return ((e) << (2 + PG_BITS - SLOT_AMP_BITS)); } */ - } /* Update AM, PM unit */ private static void update_ampm(OPLL opll) { @@ -1106,7 +1064,7 @@ private static void update_noise(OPLL opll) } /* EG */ - private static uint S2E(double x) { return (SL2EG((uint)(x / SL_STEP)) << (EG_DP_BITS - EG_BITS)); } + private static uint S2E(double x) => (SL2EG((uint)(x / SL_STEP)) << (EG_DP_BITS - EG_BITS)); private static readonly uint[] SL = { @@ -1677,10 +1635,7 @@ private void OPLL_writeIO(OPLL opll, uint adr, uint val) } /* STEREO MODE (OPT) */ - private void OPLL_set_pan(OPLL opll, uint ch, uint pan) - { - opll.pan[ch & 15] = pan & 3; - } + private void OPLL_set_pan(OPLL opll, uint ch, uint pan) => opll.pan[ch & 15] = pan & 3; private static void calc_stereo(OPLL opll, int[] output) { @@ -1773,8 +1728,22 @@ public sealed class OPLL_PATCH : ICloneable public object Clone() { - OPLL_PATCH o = new OPLL_PATCH(); - o.tl = this.tl; o.fb = this.fb; o.eg = this.eg; o.ml = this.ml; o.ar = this.ar; o.dr = this.dr; o.sl = this.sl; o.rr = this.rr; o.kr = this.kr; o.kl = this.kl; o.am = this.am; o.pm = this.pm; o.wf = this.wf; + OPLL_PATCH o = new() + { + tl = this.tl, + fb = this.fb, + eg = this.eg, + ml = this.ml, + ar = this.ar, + dr = this.dr, + sl = this.sl, + rr = this.rr, + kr = this.kr, + kl = this.kl, + am = this.am, + pm = this.pm, + wf = this.wf + }; return o; } } diff --git a/src/BizHawk.Emulation.Cores/Waterbox/NymaCore.Cd.cs b/src/BizHawk.Emulation.Cores/Waterbox/NymaCore.Cd.cs index 42c15e084f1..ccbf08a05d8 100644 --- a/src/BizHawk.Emulation.Cores/Waterbox/NymaCore.Cd.cs +++ b/src/BizHawk.Emulation.Cores/Waterbox/NymaCore.Cd.cs @@ -8,7 +8,7 @@ namespace BizHawk.Emulation.Cores.Waterbox abstract partial class NymaCore : IDriveLight { // this code was mostly copied from Saturnus, which it will replace soon(R) - private static readonly DiscSectorReaderPolicy _diskPolicy = new DiscSectorReaderPolicy + private static readonly DiscSectorReaderPolicy _diskPolicy = new() { DeinterleavedSubcode = false }; @@ -34,13 +34,13 @@ private static void SetupTOC(LibNymaCore.TOC t, DiscTOC tin) private void CDTOCCallback(int disk, IntPtr dest) { - var toc = new LibNymaCore.TOC { Tracks = new LibNymaCore.TOC.Track[101] }; + LibNymaCore.TOC toc = new() { Tracks = new LibNymaCore.TOC.Track[101] }; SetupTOC(toc, _disks[disk].TOC); Marshal.StructureToPtr(toc, dest, false); } private void CDSectorCallback(int disk, int lba, IntPtr dest) { - var buff = new byte[2448]; + byte[] buff = new byte[2448]; _diskReaders[disk].ReadLBA_2448(lba, buff, 0); Marshal.Copy(buff, 0, dest, 2448); DriveLightOn = true; diff --git a/src/BizHawk.Emulation.Cores/Waterbox/NymaCore.Controller.ButtonNameOverrides.cs b/src/BizHawk.Emulation.Cores/Waterbox/NymaCore.Controller.ButtonNameOverrides.cs index a6a8f210b0c..1c7f9e328f4 100644 --- a/src/BizHawk.Emulation.Cores/Waterbox/NymaCore.Controller.ButtonNameOverrides.cs +++ b/src/BizHawk.Emulation.Cores/Waterbox/NymaCore.Controller.ButtonNameOverrides.cs @@ -10,7 +10,7 @@ partial class NymaCore private static bool IsRomanNumeral(string str) => new[] {"I", "II", "III", "IV", "V", "VI"}.Contains(str); - private static readonly Dictionary ButtonNameOverrides = new Dictionary + private static readonly Dictionary ButtonNameOverrides = new() { ["Left Shoulder"] = "L", ["Right Shoulder"] = "R", diff --git a/src/BizHawk.Emulation.Cores/Waterbox/NymaCore.Controller.cs b/src/BizHawk.Emulation.Cores/Waterbox/NymaCore.Controller.cs index 3feaf614548..f673eeeb98d 100644 --- a/src/BizHawk.Emulation.Cores/Waterbox/NymaCore.Controller.cs +++ b/src/BizHawk.Emulation.Cores/Waterbox/NymaCore.Controller.cs @@ -82,13 +82,13 @@ public ControllerAdapter( } }; - var finalDevices = new List(); + List finalDevices = new(); - var switchPreviousFrame = new List(); + List switchPreviousFrame = new(); for (int port = 0, devByteStart = 0; port < allPorts.Count; port++) { var portInfo = allPorts[port]; - if (!config.TryGetValue(port, out var deviceName)) deviceName = portInfo.DefaultDeviceShortName; + if (!config.TryGetValue(port, out string deviceName)) deviceName = portInfo.DefaultDeviceShortName; finalDevices.Add(deviceName); if (hiddenPorts.Contains(portInfo.ShortName)) @@ -111,7 +111,7 @@ public ControllerAdapter( }); var deviceInfo = device; - var category = portInfo.FullName + " - " + deviceInfo.FullName; + string category = portInfo.FullName + " - " + deviceInfo.FullName; var inputs = deviceInfo.Inputs .OrderBy(a => a.ConfigOrder); @@ -121,14 +121,14 @@ public ControllerAdapter( if (input.Type == InputType.Padding) continue; - var bitSize = (int)input.BitSize; - var bitOffset = (int)input.BitOffset; - var byteStart = devByteStart + bitOffset / 8; + int bitSize = input.BitSize; + int bitOffset = input.BitOffset; + int byteStart = devByteStart + bitOffset / 8; bitOffset %= 8; - var baseName = input.Name; + string baseName = input.Name; if (baseName != null) baseName = overrideName(baseName); - var name = input.Type == InputType.ResetButton ? "Reset" : $"P{port + 1} {baseName}"; + string name = input.Type == InputType.ResetButton ? "Reset" : $"P{port + 1} {baseName}"; switch (input.Type) { @@ -156,19 +156,19 @@ public ControllerAdapter( if (data.Positions.Count > 8) throw new NotImplementedException("Need code changes to support Mdfn switch with more than 8 positions"); - // fake switches as a series of push downs that select each state - // imagine the "gear" selector on a Toyota Prius + // fake switches as a series of push downs that select each state + // imagine the "gear" selector on a Toyota Prius - var si = switchPreviousFrame.Count; + int si = switchPreviousFrame.Count; // [si]: position of this switch on the previous frame switchPreviousFrame.Add((byte)data.DefaultPosition); // [si + 1]: bit array of the previous state of each selector button switchPreviousFrame.Add(0); - var names = data.Positions.Select(p => $"{name}: Set {p.Name}").ToArray(); + string[] names = data.Positions.Select(p => $"{name}: Set {p.Name}").ToArray(); if (!input.Name.StartsWithOrdinal("AF ") && !input.Name.EndsWithOrdinal(" AF") && !input.Name.StartsWithOrdinal("Autofire ")) // hack: don't support some devices { - foreach (var n in names) + foreach (string n in names) { { ret.BoolButtons.Add(n); @@ -179,14 +179,14 @@ public ControllerAdapter( _thunks.Add((c, b) => { - var val = _switchPreviousFrame[si]; - var allOldPressed = _switchPreviousFrame[si + 1]; + byte val = _switchPreviousFrame[si]; + byte allOldPressed = _switchPreviousFrame[si + 1]; byte allNewPressed = 0; - for (var i = 0; i < names.Length; i++) + for (int i = 0; i < names.Length; i++) { - var mask = (byte)(1 << i); - var oldPressed = allOldPressed & mask; - var newPressed = c.IsPressed(names[i]) ? mask : (byte)0; + byte mask = (byte)(1 << i); + int oldPressed = allOldPressed & mask; + byte newPressed = c.IsPressed(names[i]) ? mask : (byte)0; if (newPressed > oldPressed) val = (byte)i; allNewPressed |= newPressed; @@ -200,10 +200,10 @@ public ControllerAdapter( case InputType.Axis: { var data = input.Extra.AsAxis(); - var fullName = $"{name} {overrideName(data.NameNeg)} / {overrideName(data.NamePos)}"; + string fullName = $"{name} {overrideName(data.NameNeg)} / {overrideName(data.NamePos)}"; ControllerThunk thunk = (c, b) => { - var val = c.AxisValue(fullName); + int val = c.AxisValue(fullName); b[byteStart] = (byte)val; b[byteStart + 1] = (byte)(val >> 8); }; @@ -215,7 +215,7 @@ public ControllerAdapter( case InputType.AxisRel: { var data = input.Extra.AsAxis(); - var fullName = $"{name} {input.Extra.AsAxis().NameNeg} / {input.Extra.AsAxis().NamePos}"; + string fullName = $"{name} {input.Extra.AsAxis().NameNeg} / {input.Extra.AsAxis().NamePos}"; // TODO: Mednafen docs say this range should be [-32768, 32767], and inspecting the code // reveals that a 16 bit value is read, but using anywhere near this full range makes @@ -225,7 +225,7 @@ public ControllerAdapter( ret.CategoryLabels[fullName] = category; _thunks.Add((c, b) => { - var val = c.AxisValue(fullName); + int val = c.AxisValue(fullName); b[byteStart] = (byte)val; b[byteStart + 1] = (byte)(val >> 8); }); @@ -233,13 +233,13 @@ public ControllerAdapter( } case InputType.PointerX: { - // I think the core expects to be sent some sort of 16 bit integer, but haven't investigated much - var minX = systemInfo.PointerOffsetX; - var maxX = systemInfo.PointerOffsetX + systemInfo.PointerScaleX; + // I think the core expects to be sent some sort of 16 bit integer, but haven't investigated much + int minX = systemInfo.PointerOffsetX; + int maxX = systemInfo.PointerOffsetX + systemInfo.PointerScaleX; ret.AddAxis(name, minX.RangeTo(maxX), (minX + maxX) / 2); _thunks.Add((c, b) => { - var val = c.AxisValue(name); + int val = c.AxisValue(name); b[byteStart] = (byte)val; b[byteStart + 1] = (byte)(val >> 8); }); @@ -247,13 +247,13 @@ public ControllerAdapter( } case InputType.PointerY: { - // I think the core expects to be sent some sort of 16 bit integer, but haven't investigated much - var minY = systemInfo.PointerOffsetY; - var maxY = systemInfo.PointerOffsetY + systemInfo.PointerScaleY; + // I think the core expects to be sent some sort of 16 bit integer, but haven't investigated much + int minY = systemInfo.PointerOffsetY; + int maxY = systemInfo.PointerOffsetY + systemInfo.PointerScaleY; ret.AddAxis(name, minY.RangeTo(maxY), (minY + maxY) / 2); _thunks.Add((c, b) => { - var val = c.AxisValue(name); + int val = c.AxisValue(name); b[byteStart] = (byte)val; b[byteStart + 1] = (byte)(val >> 8); }); @@ -265,7 +265,7 @@ public ControllerAdapter( ret.CategoryLabels[name] = category; _thunks.Add((c, b) => { - var val = c.AxisValue(name); + int val = c.AxisValue(name); b[byteStart] = (byte)val; b[byteStart + 1] = (byte)(val >> 8); }); @@ -281,7 +281,7 @@ public ControllerAdapter( _rumblers.Add((c, b) => { // TODO: not entirely sure this is correct... - var val = b[byteStart] | (b[byteStart + 1] << 8); + int val = b[byteStart] | (b[byteStart + 1] << 8); c.SetHapticChannelStrength(name, val << 7); }); break; @@ -350,10 +350,7 @@ public void LoadStateBinary(BinaryReader reader) /// On some cores, some controller ports are not relevant when certain settings are off (like multitap). /// Override this if your core has such an issue /// - protected virtual HashSet ComputeHiddenPorts() - { - return new HashSet(); - } + protected virtual HashSet ComputeHiddenPorts() => new(); public class PortResult { diff --git a/src/BizHawk.Emulation.Cores/Waterbox/NymaCore.Settings.ComponentModel.cs b/src/BizHawk.Emulation.Cores/Waterbox/NymaCore.Settings.ComponentModel.cs index be7b0379cb0..796c9a52393 100644 --- a/src/BizHawk.Emulation.Cores/Waterbox/NymaCore.Settings.ComponentModel.cs +++ b/src/BizHawk.Emulation.Cores/Waterbox/NymaCore.Settings.ComponentModel.cs @@ -26,10 +26,7 @@ public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object return null; //? } - public override bool IsSupportedType(Type type) - { - return type == typeof(NymaSyncSettings) || type == typeof(NymaSettings); - } + public override bool IsSupportedType(Type type) => type == typeof(NymaSyncSettings) || type == typeof(NymaSettings); } public class SyncSettingsCustomTypeDescriptor : CustomTypeDescriptor @@ -119,21 +116,18 @@ public MednaPropertyDescriptor(SettingT setting, bool isSyncSetting) public override object GetValue(object component) { - var ss = (INymaDictionarySettings)component; - if (!ss.MednafenValues.TryGetValue(Setting.SettingsKey, out var val)) + INymaDictionarySettings ss = (INymaDictionarySettings)component; + if (!ss.MednafenValues.TryGetValue(Setting.SettingsKey, out string val)) val = Setting.DefaultValue; - var ret = ConvertFromString(val); + object ret = ConvertFromString(val); return ret; } - public override void ResetValue(object component) - { - ((INymaDictionarySettings)component).MednafenValues.Remove(Setting.SettingsKey); - } + public override void ResetValue(object component) => ((INymaDictionarySettings)component).MednafenValues.Remove(Setting.SettingsKey); public override void SetValue(object component, object value) { - var s = ConvertToString(value); + string s = ConvertToString(value); if (s == null || s == Setting.DefaultValue) { ResetValue(component); @@ -142,30 +136,20 @@ public override void SetValue(object component, object value) ((INymaDictionarySettings)component).MednafenValues[Setting.SettingsKey] = s; } - public override bool ShouldSerializeValue(object component) - { - return ((INymaDictionarySettings)component).MednafenValues.ContainsKey(Setting.SettingsKey); - } + public override bool ShouldSerializeValue(object component) => ((INymaDictionarySettings)component).MednafenValues.ContainsKey(Setting.SettingsKey); public static MednaPropertyDescriptor Create(SettingT s, bool isSyncSetting) { - switch (s.Type) + return s.Type switch { - case SettingType.Int: - return new MednaLongDescriptor(s, isSyncSetting); - case SettingType.Uint: - return new MednaUlongDescriptor(s, isSyncSetting); - case SettingType.Bool: - return new MednaBoolDescriptor(s, isSyncSetting); - case SettingType.Float: - return new MednaDoubleDescriptor(s, isSyncSetting); - case SettingType.String: - return new MednaStringDescriptor(s, isSyncSetting); - case SettingType.Enum: - return new MednaEnumDescriptor(s, isSyncSetting); - default: - throw new NotImplementedException($"Unexpected SettingType {s.Type}"); - } + SettingType.Int => new MednaLongDescriptor(s, isSyncSetting), + SettingType.Uint => new MednaUlongDescriptor(s, isSyncSetting), + SettingType.Bool => new MednaBoolDescriptor(s, isSyncSetting), + SettingType.Float => new MednaDoubleDescriptor(s, isSyncSetting), + SettingType.String => new MednaStringDescriptor(s, isSyncSetting), + SettingType.Enum => new MednaEnumDescriptor(s, isSyncSetting), + _ => throw new NotImplementedException($"Unexpected SettingType {s.Type}"), + }; } } @@ -173,14 +157,8 @@ public class MednaEnumDescriptor : MednaPropertyDescriptor { public MednaEnumDescriptor(SettingT s, bool isSyncSetting) : base(s, isSyncSetting) {} public override Type PropertyType => typeof(string); - protected override object ConvertFromString(string s) - { - return s; - } - protected override string ConvertToString(object o) - { - return (string)o; - } + protected override object ConvertFromString(string s) => s; + protected override string ConvertToString(object o) => (string)o; public override TypeConverter Converter => new MyTypeConverter { Setting = Setting }; private class MyTypeConverter : TypeConverter @@ -211,7 +189,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul .Name; } - public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) => new StandardValuesCollection( + public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) => new( ValidSettingEnums.Select(e => e.Value).ToList() ); @@ -224,27 +202,15 @@ public class MednaStringDescriptor : MednaPropertyDescriptor { public MednaStringDescriptor(SettingT s, bool isSyncSetting) : base(s, isSyncSetting) {} public override Type PropertyType => typeof(string); - protected override object ConvertFromString(string s) - { - return s; - } - protected override string ConvertToString(object o) - { - return (string)o; - } + protected override object ConvertFromString(string s) => s; + protected override string ConvertToString(object o) => (string)o; } public class MednaBoolDescriptor : MednaPropertyDescriptor { public MednaBoolDescriptor(SettingT s, bool isSyncSetting) : base(s, isSyncSetting) {} public override Type PropertyType => typeof(bool); - protected override object ConvertFromString(string s) - { - return int.Parse(s) != 0; - } - protected override string ConvertToString(object o) - { - return (bool)o ? "1" : "0"; - } + protected override object ConvertFromString(string s) => int.Parse(s) != 0; + protected override string ConvertToString(object o) => (bool)o ? "1" : "0"; } public class MednaLongDescriptor : MednaPropertyDescriptor { @@ -252,15 +218,12 @@ public MednaLongDescriptor(SettingT s, bool isSyncSetting) : base(s, isSyncSetti public override Type PropertyType => typeof(long); protected override object ConvertFromString(string s) { - var ret = long.Parse(s); + long ret = long.Parse(s); if (Setting.Min != null && ret < long.Parse(Setting.Min) || Setting.Max != null && ret > long.Parse(Setting.Max)) ret = long.Parse(Setting.DefaultValue); return ret; } - protected override string ConvertToString(object o) - { - return o.ToString(); - } + protected override string ConvertToString(object o) => o.ToString(); } public class MednaUlongDescriptor : MednaPropertyDescriptor { @@ -268,15 +231,12 @@ public MednaUlongDescriptor(SettingT s, bool isSyncSetting) : base(s, isSyncSett public override Type PropertyType => typeof(ulong); protected override object ConvertFromString(string s) { - var ret = Parse(s); + ulong ret = Parse(s); if (Setting.Min != null && ret < Parse(Setting.Min) || Setting.Max != null && ret > Parse(Setting.Max)) ret = Parse(Setting.DefaultValue); return ret; } - protected override string ConvertToString(object o) - { - return o.ToString(); - } + protected override string ConvertToString(object o) => o.ToString(); private static ulong Parse(string s) { if (s.StartsWith("0x", StringComparison.Ordinal)) @@ -295,15 +255,12 @@ public MednaDoubleDescriptor(SettingT s, bool isSyncSetting) : base(s, isSyncSet public override Type PropertyType => typeof(double); protected override object ConvertFromString(string s) { - var ret = double.Parse(s, NumberFormatInfo.InvariantInfo); + double ret = double.Parse(s, NumberFormatInfo.InvariantInfo); if (Setting.Min != null && ret < double.Parse(Setting.Min, NumberFormatInfo.InvariantInfo) || Setting.Max != null && ret > double.Parse(Setting.Max, NumberFormatInfo.InvariantInfo)) ret = double.Parse(Setting.DefaultValue, NumberFormatInfo.InvariantInfo); return ret; } - protected override string ConvertToString(object o) - { - return o.ToString(); - } + protected override string ConvertToString(object o) => o.ToString(); } public class PortPropertyDescriptor : PropertyDescriptor @@ -329,29 +286,23 @@ public PortPropertyDescriptor(Port port, int index) public override object GetValue(object component) { - var ss = (NymaSyncSettings)component; - if (!ss.PortDevices.TryGetValue(PortIndex, out var val)) + NymaSyncSettings ss = (NymaSyncSettings)component; + if (!ss.PortDevices.TryGetValue(PortIndex, out string val)) val = Port.DefaultSettingsValue; return val; } - public override void ResetValue(object component) - { - ((NymaSyncSettings)component).PortDevices.Remove(PortIndex); - } + public override void ResetValue(object component) => ((NymaSyncSettings)component).PortDevices.Remove(PortIndex); public override void SetValue(object component, object value) { - var str = (string) value; + string str = (string) value; if (str == Port.DefaultSettingsValue) ResetValue(component); else if (Port.AllowedDevices.Exists(d => d.SettingValue == str)) ((NymaSyncSettings) component).PortDevices[PortIndex] = str; // else does not validate } - public override bool ShouldSerializeValue(object component) - { - return ((NymaSyncSettings)component).PortDevices.ContainsKey(PortIndex); - } + public override bool ShouldSerializeValue(object component) => ((NymaSyncSettings)component).PortDevices.ContainsKey(PortIndex); public override TypeConverter Converter => new MyTypeConverter { Port = Port }; @@ -379,7 +330,7 @@ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo cul .Name; } - public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) => new StandardValuesCollection( + public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) => new( Port.AllowedDevices.Select(d => d.SettingValue).ToList() ); @@ -408,15 +359,9 @@ public LayerPropertyDescriptor(string layerName) public override Type PropertyType => typeof(bool); public override bool CanResetValue(object component) => true; - public override object GetValue(object component) - { - return !((NymaSettings)component).DisabledLayers.Contains(LayerName); - } + public override object GetValue(object component) => !((NymaSettings)component).DisabledLayers.Contains(LayerName); - public override void ResetValue(object component) - { - ((NymaSettings)component).DisabledLayers.Remove(LayerName); - } + public override void ResetValue(object component) => ((NymaSettings)component).DisabledLayers.Remove(LayerName); public override void SetValue(object component, object value) { @@ -426,9 +371,6 @@ public override void SetValue(object component, object value) ((NymaSettings)component).DisabledLayers.Add(LayerName); } - public override bool ShouldSerializeValue(object component) - { - return ((NymaSettings)component).DisabledLayers.Contains(LayerName); - } + public override bool ShouldSerializeValue(object component) => ((NymaSettings)component).DisabledLayers.Contains(LayerName); } } diff --git a/src/BizHawk.Emulation.Cores/Waterbox/NymaCore.Settings.cs b/src/BizHawk.Emulation.Cores/Waterbox/NymaCore.Settings.cs index 44297aa50e4..360e4b0d66d 100644 --- a/src/BizHawk.Emulation.Cores/Waterbox/NymaCore.Settings.cs +++ b/src/BizHawk.Emulation.Cores/Waterbox/NymaCore.Settings.cs @@ -34,7 +34,7 @@ public PutSettingsDirtyBits PutSettings(NymaSettings o) var n = o.Clone(); n.Normalize(SettingsInfo); var ret = NymaSettings.Reboot(_settings, n, SettingsInfo); - var notifies = NymaSettings.ChangedKeys(_settings, n, SettingsInfo).ToList(); + List notifies = NymaSettings.ChangedKeys(_settings, n, SettingsInfo).ToList(); _settings = n; if (SettingsInfo.LayerNames.Count > 0) @@ -47,7 +47,7 @@ public PutSettingsDirtyBits PutSettings(NymaSettings o) } _nyma.SetLayers(layers); } - foreach (var key in notifies) + foreach (string key in notifies) { _nyma.NotifySettingChanged(key); } @@ -87,7 +87,7 @@ public NymaSettings Clone() /// public void Normalize(NymaSettingsInfo info) { - var toRemove = new List(); + List toRemove = new(); foreach (var kvp in MednafenValues) { if (!info.AllSettingsByKey.ContainsKey(kvp.Key)) @@ -101,7 +101,7 @@ public void Normalize(NymaSettingsInfo info) toRemove.Add(kvp.Key); } } - foreach (var key in toRemove) + foreach (string key in toRemove) { MednafenValues.Remove(key); } @@ -113,8 +113,8 @@ public static IEnumerable ChangedKeys(NymaSettings x, NymaSettings y, Ny var possible = info.AllOverrides.Where(kvp => kvp.Value.NonSync && kvp.Value.NoRestart).Select(kvp => kvp.Key); return possible.Where(key => { - _ = x.MednafenValues.TryGetValue(key, out var xx); - _ = y.MednafenValues.TryGetValue(key, out var yy); + _ = x.MednafenValues.TryGetValue(key, out string xx); + _ = y.MednafenValues.TryGetValue(key, out string yy); return xx != yy; }); } @@ -122,10 +122,10 @@ public static IEnumerable ChangedKeys(NymaSettings x, NymaSettings y, Ny public static PutSettingsDirtyBits Reboot(NymaSettings x, NymaSettings y, NymaSettingsInfo info) { var restarters = info.AllOverrides.Where(kvp => kvp.Value.NonSync && !kvp.Value.NoRestart).Select(kvp => kvp.Key); - foreach (var key in restarters) + foreach (string key in restarters) { - _ = x.MednafenValues.TryGetValue(key, out var xx); - _ = y.MednafenValues.TryGetValue(key, out var yy); + _ = x.MednafenValues.TryGetValue(key, out string xx); + _ = y.MednafenValues.TryGetValue(key, out string yy); if (xx != yy) return PutSettingsDirtyBits.RebootCore; } @@ -151,7 +151,7 @@ public NymaSyncSettings Clone() /// public void Normalize(NymaSettingsInfo info) { - var toRemove = new List(); + List toRemove = new(); foreach (var kvp in MednafenValues) { if (!info.AllSettingsByKey.ContainsKey(kvp.Key)) @@ -165,17 +165,17 @@ public void Normalize(NymaSettingsInfo info) toRemove.Add(kvp.Key); } } - foreach (var key in toRemove) + foreach (string key in toRemove) { MednafenValues.Remove(key); } - var toRemovePort = new List(); + List toRemovePort = new(); foreach (var kvp in PortDevices) { if (info.Ports.Count <= kvp.Key || info.Ports[kvp.Key].DefaultSettingsValue == kvp.Value) toRemovePort.Add(kvp.Key); } - foreach (var key in toRemovePort) + foreach (int key in toRemovePort) { PortDevices.Remove(key); } @@ -184,10 +184,10 @@ public void Normalize(NymaSettingsInfo info) public static PutSettingsDirtyBits Reboot(NymaSyncSettings x, NymaSyncSettings y, NymaSettingsInfo info) { var restarters = info.AllOverrides.Where(kvp => !kvp.Value.NonSync && !kvp.Value.NoRestart).Select(kvp => kvp.Key); - foreach (var key in restarters) + foreach (string key in restarters) { - _ = x.MednafenValues.TryGetValue(key, out var xx); - _ = y.MednafenValues.TryGetValue(key, out var yy); + _ = x.MednafenValues.TryGetValue(key, out string xx); + _ = y.MednafenValues.TryGetValue(key, out string yy); if (xx != yy) return PutSettingsDirtyBits.RebootCore; } @@ -208,18 +208,15 @@ protected string SettingsQuery(string name) var dict = ovr.NonSync ? _settings.MednafenValues : _syncSettingsActual.MednafenValues; _ = dict.TryGetValue(name, out val); } - if (val == null) - { - // get default - val = ovr.Default ?? SettingsInfo.AllSettingsByKey[name].DefaultValue; - } + // get default + val ??= ovr.Default ?? SettingsInfo.AllSettingsByKey[name].DefaultValue; return val; } private void SettingsQuery(string name, IntPtr dest) { - var val = SettingsQuery(name); - var bytes = Encoding.UTF8.GetBytes(val); + string val = SettingsQuery(name); + byte[] bytes = Encoding.UTF8.GetBytes(val); if (bytes.Length > 255) throw new InvalidOperationException($"Value {val} for setting {name} was too long"); WaterboxUtils.ZeroMemory(dest, 256); @@ -278,7 +275,7 @@ public NymaSettingsInfo Clone() } private void InitAllSettingsInfo(List allPorts) { - var s = new NymaSettingsInfo(); + NymaSettingsInfo s = new(); foreach (var kvp in ExtraOverrides.Concat(SettingOverrides)) { diff --git a/src/BizHawk.Emulation.Cores/Waterbox/NymaCore.cs b/src/BizHawk.Emulation.Cores/Waterbox/NymaCore.cs index 474a1561f3b..3fc2088740a 100644 --- a/src/BizHawk.Emulation.Cores/Waterbox/NymaCore.cs +++ b/src/BizHawk.Emulation.Cores/Waterbox/NymaCore.cs @@ -71,13 +71,13 @@ protected T DoInit(GameInfo game, byte[] rom, Disc[] discs, string wbxFilenam _cdTocCallback = CDTOCCallback; _cdSectorCallback = CDSectorCallback; - var filesToRemove = new List(); + List filesToRemove = new(); - var firmwareDelegate = new LibNymaCore.FrontendFirmwareNotify((name) => + LibNymaCore.FrontendFirmwareNotify firmwareDelegate = new((name) => { if (firmwares != null && firmwares.TryGetValue(name, out var id)) { - var data = CoreComm.CoreFileProvider.GetFirmwareOrThrow(id, "Firmware files are usually required and may stop your game from loading"); + byte[] data = CoreComm.CoreFileProvider.GetFirmwareOrThrow(id, "Firmware files are usually required and may stop your game from loading"); _exe.AddReadonlyFile(data, name); filesToRemove.Add(name); } @@ -103,16 +103,16 @@ protected T DoInit(GameInfo game, byte[] rom, Disc[] discs, string wbxFilenam _disks = discs; _diskReaders = _disks.Select(d => new DiscSectorReader(d) { Policy = _diskPolicy }).ToArray(); _nyma.SetCDCallbacks(_cdTocCallback, _cdSectorCallback); - var didInit = _nyma.InitCd(_disks.Length); + bool didInit = _nyma.InitCd(_disks.Length); if (!didInit) throw new InvalidOperationException("Core rejected the CDs!"); } else { - var fn = game.FilesystemSafeName(); + string fn = game.FilesystemSafeName(); _exe.AddReadonlyFile(rom, fn); - var didInit = _nyma.InitRom(new LibNymaCore.InitData + bool didInit = _nyma.InitRom(new LibNymaCore.InitData { // TODO: Set these as some cores need them FileNameBase = "", @@ -126,7 +126,7 @@ protected T DoInit(GameInfo game, byte[] rom, Disc[] discs, string wbxFilenam _exe.RemoveReadonlyFile(fn); } - foreach (var s in filesToRemove) + foreach (string s in filesToRemove) { _exe.RemoveReadonlyFile(s); } @@ -139,20 +139,13 @@ protected T DoInit(GameInfo game, byte[] rom, Disc[] discs, string wbxFilenam BufferHeight = info.NominalHeight; _mdfnNominalWidth = info.NominalWidth; _mdfnNominalHeight = info.NominalHeight; - switch (info.VideoSystem) + Region = info.VideoSystem switch { // TODO: There seriously isn't any region besides these? - case LibNymaCore.VideoSystem.PAL: - case LibNymaCore.VideoSystem.SECAM: - Region = DisplayType.PAL; - break; - case LibNymaCore.VideoSystem.PAL_M: - Region = DisplayType.Dendy; // sort of... - break; - default: - Region = DisplayType.NTSC; - break; - } + LibNymaCore.VideoSystem.PAL or LibNymaCore.VideoSystem.SECAM => DisplayType.PAL, + LibNymaCore.VideoSystem.PAL_M => DisplayType.Dendy,// sort of... + _ => DisplayType.NTSC, + }; VsyncNumerator = info.FpsFixed; VsyncDenominator = 1 << 24; ClockRate = info.MasterClock / (double)0x100000000; @@ -207,10 +200,7 @@ protected void InitForSettingsInfo(string wbxFilename) } } - protected override void SaveStateBinaryInternal(BinaryWriter writer) - { - _controllerAdapter.SaveStateBinary(writer); - } + protected override void SaveStateBinaryInternal(BinaryWriter writer) => _controllerAdapter.SaveStateBinary(writer); protected override void LoadStateBinaryInternal(BinaryReader reader) { @@ -247,7 +237,7 @@ protected override LibWaterboxCore.FrameInfo FrameAdvancePrep(IController contro if (controller.IsPressed("Close Tray")) flags |= LibNymaCore.BizhawkFlags.CloseTray; - var ret = new LibNymaCore.FrameInfo + LibNymaCore.FrameInfo ret = new() { Flags = flags, Command = controller.IsPressed("Power") @@ -296,11 +286,11 @@ protected override void FrameAdvancePost() /// private List GetLayerData() { - var ret = new List(); - var p = _nyma.GetLayerData(); + List ret = new(); + byte* p = _nyma.GetLayerData(); if (p == null) return ret; - var q = p; + byte* q = p; while (true) { if (*q == 0) @@ -320,7 +310,7 @@ private List GetSettingsData() { _exe.AddTransientFile(new byte[0], "settings"); _nyma.DumpSettings(); - var settingsBuff = _exe.RemoveTransientFile("settings"); + byte[] settingsBuff = _exe.RemoveTransientFile("settings"); return NymaTypes.Settings.GetRootAsSettings(new ByteBuffer(settingsBuff)).UnPack().Values; } @@ -328,7 +318,7 @@ private List GetInputPortsData() { _exe.AddTransientFile(new byte[0], "inputs"); _nyma.DumpInputs(); - var settingsBuff = _exe.RemoveTransientFile("inputs"); + byte[] settingsBuff = _exe.RemoveTransientFile("inputs"); return NymaTypes.NPorts.GetRootAsNPorts(new ByteBuffer(settingsBuff)).UnPack().Values; } diff --git a/src/BizHawk.Emulation.Cores/Waterbox/WaterboxCore.cs b/src/BizHawk.Emulation.Cores/Waterbox/WaterboxCore.cs index 63c16fb3f5f..0718b40ad6d 100644 --- a/src/BizHawk.Emulation.Cores/Waterbox/WaterboxCore.cs +++ b/src/BizHawk.Emulation.Cores/Waterbox/WaterboxCore.cs @@ -63,20 +63,22 @@ protected void PostInit() { using (_exe.EnterExit()) { - var areas = new LibWaterboxCore.MemoryArea[256]; + LibWaterboxCore.MemoryArea[] areas = new LibWaterboxCore.MemoryArea[256]; _core.GetMemoryAreas(areas); _memoryAreas = areas.Where(a => a.Data != IntPtr.Zero && a.Size != 0) .ToArray(); - var memoryDomains = _memoryAreas.Select(a => WaterboxMemoryDomain.Create(a, _exe)).ToList(); + List memoryDomains = _memoryAreas.Select(a => WaterboxMemoryDomain.Create(a, _exe)).ToList(); var primaryDomain = memoryDomains.Single(static md => md.Definition.Flags.HasFlag(LibWaterboxCore.MemoryDomainFlags.Primary)); - var mdl = new MemoryDomainList( + MemoryDomainList mdl = new( memoryDomains.Cast() .Concat(new[] { _exe.GetPagesDomain() }) .ToList() - ); - mdl.MainMemory = primaryDomain; + ) + { + MainMemory = primaryDomain + }; _serviceProvider.Register(mdl); _saveramAreas = memoryDomains @@ -88,14 +90,11 @@ protected void PostInit() } } - private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0); + private static readonly DateTime Epoch = new(1970, 1, 1, 0, 0, 0); private long _clockTime; private int _clockRemainder; - protected void InitializeRtc(DateTime start) - { - _clockTime = (long)(start - Epoch).TotalSeconds; - } + protected void InitializeRtc(DateTime start) => _clockTime = (long)(start - Epoch).TotalSeconds; protected long GetRtcTime(bool realTime) { @@ -123,14 +122,14 @@ public unsafe bool SaveRamModified { if (_saveramSize == 0) return false; - var buff = new byte[4096]; + byte[] buff = new byte[4096]; using (_exe.EnterExit()) { fixed(byte* bp = buff) { foreach (var area in _saveramAreas) { - var stream = new MemoryDomainStream(area); + MemoryDomainStream stream = new(area); int cmp = (area.Definition.Flags & LibWaterboxCore.MemoryDomainFlags.OneFilled) != 0 ? -1 : 0; while (true) { @@ -159,8 +158,8 @@ public byte[] CloneSaveRam() return null; using (_exe.EnterExit()) { - var ret = new byte[_saveramSize]; - var dest = new MemoryStream(ret, true); + byte[] ret = new byte[_saveramSize]; + MemoryStream dest = new(ret, true); foreach (var area in _saveramAreas) { new MemoryDomainStream(area).CopyTo(dest); @@ -177,7 +176,7 @@ public void StoreSaveRam(byte[] data) throw new InvalidOperationException("Saveram size mismatch"); using (_exe.EnterExit()) { - var source = new MemoryStream(data, false); + MemoryStream source = new(data, false); foreach (var area in _saveramAreas) { WaterboxUtils.CopySome(source, new MemoryDomainStream(area), area.Size); @@ -338,10 +337,7 @@ public void GetSamplesSync(out short[] samples, out int nsamp) nsamp = _numSamples; } - public void GetSamplesAsync(short[] samples) - { - throw new InvalidOperationException("Async mode is not supported."); - } + public void GetSamplesAsync(short[] samples) => throw new InvalidOperationException("Async mode is not supported."); public void DiscardSamples() { @@ -352,10 +348,7 @@ public void DiscardSamples() public bool CanProvideAsync => false; public SyncSoundMode SyncMode => SyncSoundMode.Sync; - public virtual int[] GetVideoBuffer() - { - return _videoBuffer; - } + public virtual int[] GetVideoBuffer() => _videoBuffer; protected int[] _videoBuffer; public virtual int VirtualWidth => BufferWidth; diff --git a/src/BizHawk.Emulation.Cores/Waterbox/WaterboxHost.cs b/src/BizHawk.Emulation.Cores/Waterbox/WaterboxHost.cs index 956c86da758..edac484ad80 100644 --- a/src/BizHawk.Emulation.Cores/Waterbox/WaterboxHost.cs +++ b/src/BizHawk.Emulation.Cores/Waterbox/WaterboxHost.cs @@ -103,8 +103,8 @@ public unsafe IntPtr Read(IntPtr data, UIntPtr size) { try { - var count = (int)size; - var n = _backingSpanStream.Read(new((void*)data, count)); + int count = (int)size; + int n = _backingSpanStream.Read(new((void*)data, count)); return Z.SS(n); } catch @@ -117,7 +117,7 @@ public unsafe int Write(IntPtr data, UIntPtr size) { try { - var count = (int)size; + int count = (int)size; _backingSpanStream.Write(new((void*)data, count)); return 0; } @@ -136,15 +136,15 @@ public void Dispose() private static IntPtr ReadCallback(IntPtr userdata, IntPtr data, UIntPtr size) { - var handle = GCHandle.FromIntPtr(userdata); - var reader = (ReadWriteWrapper)handle.Target; + GCHandle handle = GCHandle.FromIntPtr(userdata); + ReadWriteWrapper reader = (ReadWriteWrapper)handle.Target; return reader.Read(data, size); } private static int WriteCallback(IntPtr userdata, IntPtr data, UIntPtr size) { - var handle = GCHandle.FromIntPtr(userdata); - var writer = (ReadWriteWrapper)handle.Target; + GCHandle handle = GCHandle.FromIntPtr(userdata); + ReadWriteWrapper writer = (ReadWriteWrapper)handle.Target; return writer.Write(data, size); } @@ -154,7 +154,7 @@ private static int WriteCallback(IntPtr userdata, IntPtr data, UIntPtr size) public WaterboxHost(WaterboxOptions opt) { - var nativeOpts = new MemoryLayoutTemplate + MemoryLayoutTemplate nativeOpts = new() { sbrk_size = Z.UU(opt.SbrkHeapSizeKB * 1024), sealed_size = Z.UU(opt.SealedHeapSizeKB * 1024), @@ -163,21 +163,21 @@ public WaterboxHost(WaterboxOptions opt) mmap_size = Z.UU(opt.MmapHeapSizeKB * 1024), }; - var moduleName = opt.Filename; + string moduleName = opt.Filename; - var path = Path.Combine(opt.Path, moduleName); - var zstpath = path + ".zst"; + string path = Path.Combine(opt.Path, moduleName); + string zstpath = path + ".zst"; if (File.Exists(zstpath)) { - using var zstd = new Zstd(); - using var fs = new FileStream(zstpath, FileMode.Open, FileAccess.Read); - using var reader = new ReadWriteWrapper(zstd.CreateZstdDecompressionStream(fs)); + using Zstd zstd = new(); + using FileStream fs = new(zstpath, FileMode.Open, FileAccess.Read); + using ReadWriteWrapper reader = new(zstd.CreateZstdDecompressionStream(fs)); NativeImpl.wbx_create_host(nativeOpts, opt.Filename, _readCallback, reader.WaterboxHandle, out var retobj); _nativeHost = retobj.GetDataOrThrow(); } else { - using var reader = new ReadWriteWrapper(new FileStream(path, FileMode.Open, FileAccess.Read)); + using ReadWriteWrapper reader = new(new FileStream(path, FileMode.Open, FileAccess.Read)); NativeImpl.wbx_create_host(nativeOpts, opt.Filename, _readCallback, reader.WaterboxHandle, out var retobj); _nativeHost = retobj.GetDataOrThrow(); } @@ -228,7 +228,7 @@ public void Seal() /// the filename that the unmanaged core will access the file by public void AddReadonlyFile(byte[] data, string name) { - using var reader = new ReadWriteWrapper(new MemoryStream(data, false)); + using ReadWriteWrapper reader = new(new MemoryStream(data, false)); NativeImpl.wbx_mount_file(_nativeHost, name, _readCallback, reader.WaterboxHandle, false, out var retobj); retobj.GetDataOrThrow(); } @@ -249,7 +249,7 @@ public void RemoveReadonlyFile(string name) /// public void AddTransientFile(byte[] data, string name) { - using var reader = new ReadWriteWrapper(new MemoryStream(data, false)); + using ReadWriteWrapper reader = new(new MemoryStream(data, false)); NativeImpl.wbx_mount_file(_nativeHost, name, _readCallback, reader.WaterboxHandle, true, out var retobj); retobj.GetDataOrThrow(); } @@ -260,8 +260,8 @@ public void AddTransientFile(byte[] data, string name) /// The state of the file when it was removed public byte[] RemoveTransientFile(string name) { - var ms = new MemoryStream(); - using var writer = new ReadWriteWrapper(ms); + MemoryStream ms = new(); + using ReadWriteWrapper writer = new(ms); NativeImpl.wbx_unmount_file(_nativeHost, name, _writeCallback, writer.WaterboxHandle, out var retobj); retobj.GetDataOrThrow(); return ms.ToArray(); @@ -308,10 +308,7 @@ public Func MissingFileCallback } #endif - public MemoryDomain GetPagesDomain() - { - return new WaterboxPagesDomain(this); - } + public MemoryDomain GetPagesDomain() => new WaterboxPagesDomain(this); private class WaterboxPagesDomain : MemoryDomain { @@ -336,24 +333,21 @@ public override byte PeekByte(long addr) return (byte)retobj.GetDataOrThrow(); } - public override void PokeByte(long addr, byte val) - { - throw new InvalidOperationException(); - } + public override void PokeByte(long addr, byte val) => throw new InvalidOperationException(); } public bool AvoidRewind => false; public void SaveStateBinary(BinaryWriter bw) { - using var writer = new ReadWriteWrapper(bw.BaseStream, false); + using ReadWriteWrapper writer = new(bw.BaseStream, false); NativeImpl.wbx_save_state(_nativeHost, _writeCallback, writer.WaterboxHandle, out var retobj); retobj.GetDataOrThrow(); } public void LoadStateBinary(BinaryReader br) { - using var reader = new ReadWriteWrapper(br.BaseStream, false); + using ReadWriteWrapper reader = new(br.BaseStream, false); NativeImpl.wbx_load_state(_nativeHost, _readCallback, reader.WaterboxHandle, out var retobj); retobj.GetDataOrThrow(); } diff --git a/src/BizHawk.Emulation.Cores/Waterbox/WaterboxMemoryDomain.cs b/src/BizHawk.Emulation.Cores/Waterbox/WaterboxMemoryDomain.cs index 63840d3a0ef..390c100b5ca 100644 --- a/src/BizHawk.Emulation.Cores/Waterbox/WaterboxMemoryDomain.cs +++ b/src/BizHawk.Emulation.Cores/Waterbox/WaterboxMemoryDomain.cs @@ -108,8 +108,8 @@ public override void BulkPeekByte(Range addresses, byte[] values) return; } - var start = (ulong)addresses.Start; - var count = addresses.Count(); + ulong start = (ulong)addresses.Start; + ulong count = addresses.Count(); if (start < (ulong)Size && (start + count) <= (ulong)Size) { @@ -198,8 +198,8 @@ public override void BulkPeekByte(Range addresses, byte[] values) return; } - var start = (ulong)addresses.Start; - var count = addresses.Count(); + ulong start = (ulong)addresses.Start; + ulong count = addresses.Count(); if (start < (ulong)Size && (start + count) <= (ulong)Size) { diff --git a/src/BizHawk.Emulation.Cores/vpads_schemata/C64Schema.cs b/src/BizHawk.Emulation.Cores/vpads_schemata/C64Schema.cs index e350af63f02..cf26c6646af 100644 --- a/src/BizHawk.Emulation.Cores/vpads_schemata/C64Schema.cs +++ b/src/BizHawk.Emulation.Cores/vpads_schemata/C64Schema.cs @@ -112,7 +112,7 @@ private static PadSchema Keyboard() } private static ButtonSchema Key(int x, int y, string name, string displayName = null) - => new ButtonSchema(x, y, "Key " + name) + => new(x, y, "Key " + name) { DisplayName = displayName ?? name }; diff --git a/src/BizHawk.Emulation.Cores/vpads_schemata/GBASchema.cs b/src/BizHawk.Emulation.Cores/vpads_schemata/GBASchema.cs index 0b1373c792c..18c06f9ff9d 100644 --- a/src/BizHawk.Emulation.Cores/vpads_schemata/GBASchema.cs +++ b/src/BizHawk.Emulation.Cores/vpads_schemata/GBASchema.cs @@ -42,7 +42,7 @@ private static PadSchema TiltControls() } private static SingleAxisSchema Tilt(int x, int y, string direction) - => new SingleAxisSchema(x, y, "Tilt " + direction) + => new(x, y, "Tilt " + direction) { TargetSize = new Size(226, 69), MinValue = short.MinValue, diff --git a/src/BizHawk.Emulation.Cores/vpads_schemata/IntvSchema.cs b/src/BizHawk.Emulation.Cores/vpads_schemata/IntvSchema.cs index c128f4e0f93..36f644b6c6c 100644 --- a/src/BizHawk.Emulation.Cores/vpads_schemata/IntvSchema.cs +++ b/src/BizHawk.Emulation.Cores/vpads_schemata/IntvSchema.cs @@ -18,8 +18,8 @@ public class IntvSchema : IVirtualPadSchema public IEnumerable GetPadSchemas(IEmulator core, Action showMessageBox) { var intvSyncSettings = ((Intellivision.Intellivision) core).GetSyncSettings().Clone(); - var port1 = intvSyncSettings.Port1; - var port2 = intvSyncSettings.Port2; + string port1 = intvSyncSettings.Port1; + string port2 = intvSyncSettings.Port2; if (port1 == StandardControllerName) { diff --git a/src/BizHawk.Emulation.Cores/vpads_schemata/N64Schema.cs b/src/BizHawk.Emulation.Cores/vpads_schemata/N64Schema.cs index 481573139b7..fbeea53e05f 100644 --- a/src/BizHawk.Emulation.Cores/vpads_schemata/N64Schema.cs +++ b/src/BizHawk.Emulation.Cores/vpads_schemata/N64Schema.cs @@ -17,7 +17,7 @@ public IEnumerable GetPadSchemas(IEmulator core, Action showM if (core is N64 n64) { var ss = n64.GetSyncSettings(); - for (var i = 0; i < 4; i++) + for (int i = 0; i < 4; i++) { if (ss.Controllers[i].IsConnected) { @@ -27,7 +27,7 @@ public IEnumerable GetPadSchemas(IEmulator core, Action showM } else if (core is Ares64 ares64) { - for (var i = 0; i < 4; i++) + for (int i = 0; i < 4; i++) { if (ares64.ControllerSettings[i] != LibAres64.ControllerType.Unplugged) { diff --git a/src/BizHawk.Emulation.Cores/vpads_schemata/NesSchema.cs b/src/BizHawk.Emulation.Cores/vpads_schemata/NesSchema.cs index 0673f65b8f5..69242c4d81b 100644 --- a/src/BizHawk.Emulation.Cores/vpads_schemata/NesSchema.cs +++ b/src/BizHawk.Emulation.Cores/vpads_schemata/NesSchema.cs @@ -16,7 +16,7 @@ public class NesSchema : IVirtualPadSchema /// found ControllerSNES public IEnumerable GetPadSchemas(IEmulator core, Action showMessageBox) { - if (core is NES || core is SubNESHawk) + if (core is NES or SubNESHawk) { NES.NESSyncSettings ss = null; bool isFds = false; @@ -64,7 +64,7 @@ public IEnumerable GetPadSchemas(IEmulator core, Action showM } else { - var currentControllerNo = 1; + int currentControllerNo = 1; switch (ss.Controls.NesLeftPort) { default: @@ -174,7 +174,7 @@ private static PadSchema NesConsoleButtons() private static PadSchema FdsConsoleButtons(int diskSize) { - var buttons = new List + List buttons = new() { new ButtonSchema(10, 15, "Reset"), new ButtonSchema(58, 15, "Power"), @@ -184,7 +184,7 @@ private static PadSchema FdsConsoleButtons(int diskSize) } }; - for (var i = 0; i < diskSize; i++) + for (int i = 0; i < diskSize; i++) { buttons.Add(new ButtonSchema(10 + (i * 58), 50, $"FDS Insert {i}") { @@ -192,7 +192,7 @@ private static PadSchema FdsConsoleButtons(int diskSize) }); } - var width = 20 + (diskSize * 58); + int width = 20 + (diskSize * 58); if (width < 160) { width = 160; @@ -227,7 +227,7 @@ private static PadSchema StandardController(int controller) private static PadSchema Famicom2ndController() { - var controller = 2; + int controller = 2; return new PadSchema { DisplayName = "Player 2", diff --git a/src/BizHawk.Emulation.Cores/vpads_schemata/PSXSchema.cs b/src/BizHawk.Emulation.Cores/vpads_schemata/PSXSchema.cs index f2eb13e5d75..58ff6d07663 100644 --- a/src/BizHawk.Emulation.Cores/vpads_schemata/PSXSchema.cs +++ b/src/BizHawk.Emulation.Cores/vpads_schemata/PSXSchema.cs @@ -27,7 +27,7 @@ public IEnumerable GetPadSchemas(IEmulator core, Action showM } int pNum = i + 1; - if (fioConfig.DevicesPlayer[i] == OctoshockDll.ePeripheralType.DualAnalog || fioConfig.DevicesPlayer[i] == OctoshockDll.ePeripheralType.DualShock) + if (fioConfig.DevicesPlayer[i] is OctoshockDll.ePeripheralType.DualAnalog or OctoshockDll.ePeripheralType.DualShock) { yield return DualShockController(pNum); } @@ -49,8 +49,8 @@ public IEnumerable GetPadSchemas(IEmulator core, Action showM { foreach (var result in nyma.ActualPortData) { - var num = int.Parse(result.Port.ShortName.Last().ToString()); - var device = result.Device.ShortName; + int num = int.Parse(result.Port.ShortName.Last().ToString()); + string device = result.Device.ShortName; if (device is "none") continue; yield return device switch { diff --git a/src/BizHawk.Emulation.Cores/vpads_schemata/PceSchema.cs b/src/BizHawk.Emulation.Cores/vpads_schemata/PceSchema.cs index d9dbff0623a..da762e9410c 100644 --- a/src/BizHawk.Emulation.Cores/vpads_schemata/PceSchema.cs +++ b/src/BizHawk.Emulation.Cores/vpads_schemata/PceSchema.cs @@ -86,10 +86,10 @@ private static PadSchema StandardHawkController(int controller) private static IEnumerable NymaSchemas(NymaCore nyma, Action showMessageBox) { - foreach (NymaCore.PortResult result in nyma.ActualPortData) + foreach (var result in nyma.ActualPortData) { - var num = int.Parse(result.Port.ShortName.Last().ToString()); - var device = result.Device.ShortName; + int num = int.Parse(result.Port.ShortName.Last().ToString()); + string device = result.Device.ShortName; if (device == "gamepad") { yield return StandardController(num); @@ -134,7 +134,7 @@ private static PadSchema StandardController(int controller) private static PadSchema Mouse(int controller) { - var range = new AxisSpec((-127).RangeTo(127), 0); + AxisSpec range = new((-127).RangeTo(127), 0); return new PadSchema { Size = new Size(345, 225), diff --git a/src/BizHawk.Emulation.Cores/vpads_schemata/PcfxSchema.cs b/src/BizHawk.Emulation.Cores/vpads_schemata/PcfxSchema.cs index f561ec063ad..c3287b64a76 100644 --- a/src/BizHawk.Emulation.Cores/vpads_schemata/PcfxSchema.cs +++ b/src/BizHawk.Emulation.Cores/vpads_schemata/PcfxSchema.cs @@ -14,16 +14,16 @@ public class PcfxSchema : IVirtualPadSchema { public IEnumerable GetPadSchemas(IEmulator core, Action showMessageBox) { - var nyma = (NymaCore) core; + NymaCore nyma = (NymaCore) core; return NymaSchemas(nyma, showMessageBox); } private static IEnumerable NymaSchemas(NymaCore nyma, Action showMessageBox) { - foreach (NymaCore.PortResult result in nyma.ActualPortData) + foreach (var result in nyma.ActualPortData) { - var num = int.Parse(result.Port.ShortName.Last().ToString()); - var device = result.Device.ShortName; + int num = int.Parse(result.Port.ShortName.Last().ToString()); + string device = result.Device.ShortName; if (device == "gamepad") { yield return StandardController(num); @@ -70,7 +70,7 @@ private static PadSchema StandardController(int controller) private static PadSchema Mouse(int controller) { - var range = new AxisSpec((-127).RangeTo(127), 0); + AxisSpec range = new((-127).RangeTo(127), 0); return new PadSchema { Size = new Size(345, 225), diff --git a/src/BizHawk.Emulation.Cores/vpads_schemata/SaturnSchema.cs b/src/BizHawk.Emulation.Cores/vpads_schemata/SaturnSchema.cs index 68a61b75094..f5d3cfff84d 100644 --- a/src/BizHawk.Emulation.Cores/vpads_schemata/SaturnSchema.cs +++ b/src/BizHawk.Emulation.Cores/vpads_schemata/SaturnSchema.cs @@ -12,16 +12,16 @@ namespace BizHawk.Emulation.Cores [Schema(VSystemID.Raw.SAT)] public class SaturnSchema : IVirtualPadSchema { - private static readonly AxisSpec AxisRange = new AxisSpec(0.RangeTo(0xffff), 0x8000); + private static readonly AxisSpec AxisRange = new(0.RangeTo(0xffff), 0x8000); public IEnumerable GetPadSchemas(IEmulator core, Action showMessageBox) { - var nyma = (NymaCore)core; + NymaCore nyma = (NymaCore)core; foreach (var result in nyma.ActualPortData .Where(r => r.Port.ShortName != "builtin")) { - var num = int.Parse(result.Port.ShortName.Last().ToString()); - var device = result.Device.ShortName; + int num = int.Parse(result.Port.ShortName.Last().ToString()); + string device = result.Device.ShortName; var schema = GenerateSchemaForPort(device, num, showMessageBox); if (schema != null) { diff --git a/src/BizHawk.Emulation.Cores/vpads_schemata/SmsSchema.cs b/src/BizHawk.Emulation.Cores/vpads_schemata/SmsSchema.cs index 8753ab62942..3d07d47c767 100644 --- a/src/BizHawk.Emulation.Cores/vpads_schemata/SmsSchema.cs +++ b/src/BizHawk.Emulation.Cores/vpads_schemata/SmsSchema.cs @@ -63,10 +63,12 @@ public class SG1000Schema : SMSSchema { } // are these really the same controlle [Schema(VSystemID.Raw.SMS)] public class SMSSchema : IVirtualPadSchema { + #pragma warning disable IDE0051 private static string StandardControllerName => typeof(SmsController).DisplayName(); private static string PaddleControllerName => typeof(SMSPaddleController).DisplayName(); private static string SportControllerName => typeof(SMSSportsPadController).DisplayName(); private static string LightGunControllerName => typeof(SMSLightPhaserController).DisplayName(); + #pragma warning restore IDE0051 public IEnumerable GetPadSchemas(IEmulator core, Action showMessageBox) { diff --git a/src/BizHawk.Emulation.Cores/vpads_schemata/SnesSchema.cs b/src/BizHawk.Emulation.Cores/vpads_schemata/SnesSchema.cs index bf6cca9dd88..e4d6804ffb5 100644 --- a/src/BizHawk.Emulation.Cores/vpads_schemata/SnesSchema.cs +++ b/src/BizHawk.Emulation.Cores/vpads_schemata/SnesSchema.cs @@ -29,8 +29,8 @@ private IEnumerable GetSnes9xPadSchemas(Snes9x core) // Only standard controller is supported on the left port yield return StandardController(1); - Snes9x.SyncSettings syncSettings = core.GetSyncSettings(); - LibSnes9x.RightPortDevice rightPort = syncSettings.RightPort; + var syncSettings = core.GetSyncSettings(); + var rightPort = syncSettings.RightPort; switch (rightPort) { @@ -175,10 +175,10 @@ private IEnumerable GetBsnesPadSchemas(ISettable GetFaustSchemas(NymaCore nyma, Action showMessageBox) { - foreach (NymaCore.PortResult result in nyma.ActualPortData) + foreach (var result in nyma.ActualPortData) { - var num = int.Parse(result.Port.ShortName.Last().ToString()); - var device = result.Device.ShortName; + int num = int.Parse(result.Port.ShortName.Last().ToString()); + string device = result.Device.ShortName; if (device == "gamepad") { yield return StandardController(num); @@ -217,8 +217,8 @@ private static PadSchema StandardController(int controller) private static PadSchema ExtendedStandardController(int controller) { - PadSchema standardController = StandardController(controller); - var newButtons = standardController.Buttons.ToList(); + var standardController = StandardController(controller); + List newButtons = standardController.Buttons.ToList(); newButtons.AddRange(new[] { new ButtonSchema(60, 65, controller, "Extra1", "1"), diff --git a/src/BizHawk.Emulation.Cores/vpads_schemata/TIC80Schema.cs b/src/BizHawk.Emulation.Cores/vpads_schemata/TIC80Schema.cs index 647e801d19e..ffc73643e09 100644 --- a/src/BizHawk.Emulation.Cores/vpads_schemata/TIC80Schema.cs +++ b/src/BizHawk.Emulation.Cores/vpads_schemata/TIC80Schema.cs @@ -44,8 +44,8 @@ private static PadSchema StandardController(int controller) private static PadSchema Mouse() { - var posRange = new AxisSpec((-128).RangeTo(127), 0); - var scrollRange = new AxisSpec((-32).RangeTo(31), 0); + AxisSpec posRange = new((-128).RangeTo(127), 0); + AxisSpec scrollRange = new((-32).RangeTo(31), 0); return new PadSchema { Size = new Size(375, 395), diff --git a/src/BizHawk.Emulation.Cores/vpads_schemata/VECSchema.cs b/src/BizHawk.Emulation.Cores/vpads_schemata/VECSchema.cs index dfeabd79c0b..e1142e4269b 100644 --- a/src/BizHawk.Emulation.Cores/vpads_schemata/VECSchema.cs +++ b/src/BizHawk.Emulation.Cores/vpads_schemata/VECSchema.cs @@ -13,8 +13,8 @@ public class VecSchema : IVirtualPadSchema public IEnumerable GetPadSchemas(IEmulator core, Action showMessageBox) { var vecSyncSettings = ((VectrexHawk)core).GetSyncSettings().Clone(); - var port1 = vecSyncSettings.Port1; - var port2 = vecSyncSettings.Port2; + string port1 = vecSyncSettings.Port1; + string port2 = vecSyncSettings.Port2; switch (port1) { @@ -79,10 +79,7 @@ private static PadSchema AnalogController(int controller) }; } - private static ButtonSchema Button(int x, int y, int controller, int button) - { - return new ButtonSchema(x, y, controller, $"Button {button}", button.ToString()); - } + private static ButtonSchema Button(int x, int y, int controller, int button) => new(x, y, controller, $"Button {button}", button.ToString()); private static PadSchema ConsoleButtons() { diff --git a/src/BizHawk.Emulation.Cores/vpads_schemata/ZXSpectrumSchema.cs b/src/BizHawk.Emulation.Cores/vpads_schemata/ZXSpectrumSchema.cs index 42eaeb8767e..1f384e5adaf 100644 --- a/src/BizHawk.Emulation.Cores/vpads_schemata/ZXSpectrumSchema.cs +++ b/src/BizHawk.Emulation.Cores/vpads_schemata/ZXSpectrumSchema.cs @@ -46,7 +46,7 @@ private class ButtonLayout private static PadSchema Keyboard() { - var bls = new List + List bls = new() { new ButtonLayout { Name = "Key True Video", DisName = "TV", Row = 0, WidthFactor = 1 }, new ButtonLayout { Name = "Key Inv Video", DisName = "IV", Row = 0, WidthFactor = 1 }, @@ -112,13 +112,13 @@ private static PadSchema Keyboard() new ButtonLayout { Name = "Key Symbol Shift", DisName = "SS", Row = 4, WidthFactor = 1 } }; - var ps = new PadSchema + PadSchema ps = new() { DisplayName = "Keyboard", Size = new Size(500, 170) }; - var btns = new List(); + List btns = new(); int rowHeight = 29; //24 int stdButtonWidth = 29; //24 @@ -153,7 +153,7 @@ private static PadSchema Keyboard() if (b.IsActive) { - var btn = new ButtonSchema(xPos, yPos, b.Name) + ButtonSchema btn = new(xPos, yPos, b.Name) { DisplayName = disp }; @@ -167,6 +167,7 @@ private static PadSchema Keyboard() return ps; } + #pragma warning disable IDE0051 private static PadSchema TapeDevice() { return new PadSchema @@ -189,5 +190,6 @@ private static PadSchema TapeDevice() } }; } + #pragma warning restore IDE0051 } } diff --git a/src/BizHawk.Emulation.DiscSystem/API_MednaDisc.cs b/src/BizHawk.Emulation.DiscSystem/API_MednaDisc.cs index 4ada99f9b27..5f78d51462b 100644 --- a/src/BizHawk.Emulation.DiscSystem/API_MednaDisc.cs +++ b/src/BizHawk.Emulation.DiscSystem/API_MednaDisc.cs @@ -94,7 +94,7 @@ public void Read_2048(int LBA, byte[] buffer, int offset) private static void CheckLibrary() { var lib = OSTailoredCode.LinkedLibManager.LoadOrZero("mednadisc.dll"); - _IsLibraryAvailable = lib != IntPtr.Zero + IsLibraryAvailable = lib != IntPtr.Zero && OSTailoredCode.LinkedLibManager.GetProcAddrOrZero(lib, "mednadisc_LoadCD") != IntPtr.Zero; if (lib != IntPtr.Zero) OSTailoredCode.LinkedLibManager.FreeByPtr(lib); } @@ -104,8 +104,7 @@ static MednaDisc() CheckLibrary(); } - private static bool _IsLibraryAvailable; - public static bool IsLibraryAvailable => _IsLibraryAvailable; + public static bool IsLibraryAvailable { get; private set; } public void Dispose() { @@ -131,7 +130,7 @@ public struct MednadiscTOCTrack //can't be a bool due to marshalling... [FieldOffset(8)] public byte _validByte; - public bool Valid => _validByte != 0; + public readonly bool Valid => _validByte != 0; } [DllImport("mednadisc.dll", CallingConvention = CallingConvention.Cdecl)] diff --git a/src/BizHawk.Emulation.DiscSystem/Disc.cs b/src/BizHawk.Emulation.DiscSystem/Disc.cs index 1fbd3b9b306..124356d56f9 100644 --- a/src/BizHawk.Emulation.DiscSystem/Disc.cs +++ b/src/BizHawk.Emulation.DiscSystem/Disc.cs @@ -23,7 +23,7 @@ public sealed class Disc : IDisposable /// public static Disc LoadAutomagic(string path) { - var job = new DiscMountJob(fromPath: path/*, discInterface: DiscInterface.MednaDisc <-- TEST*/); + DiscMountJob job = new(fromPath: path/*, discInterface: DiscInterface.MednaDisc <-- TEST*/); job.Run(); return job.OUT_Disc; } @@ -70,7 +70,7 @@ public byte[] Easy_Extract_Mode1(int lba_start, int lba_count, int byteLength = { int totsize = lba_count * 2048; byte[] ret = new byte[totsize]; - var dsr = new DiscSectorReader(this) { Policy = { DeterministicClearBuffer = false } }; + DiscSectorReader dsr = new(this) { Policy = { DeterministicClearBuffer = false } }; for (int i = 0; i < lba_count; i++) { dsr.ReadLBA_2048(lba_start + i, ret, i*2048); diff --git a/src/BizHawk.Emulation.DiscSystem/DiscExtensions.cs b/src/BizHawk.Emulation.DiscSystem/DiscExtensions.cs index b8b1166723f..6ce422584e1 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscExtensions.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscExtensions.cs @@ -4,19 +4,13 @@ namespace BizHawk.Emulation.DiscSystem { public static class DiscExtensions { - public static Disc CreateAnyType(string path, Action errorCallback) - { - return CreateImpl(null, path, errorCallback); - } - public static Disc Create(this DiscType type, string path, Action errorCallback) - { - return CreateImpl(type, path, errorCallback); - } + public static Disc CreateAnyType(string path, Action errorCallback) => CreateImpl(null, path, errorCallback); + public static Disc Create(this DiscType type, string path, Action errorCallback) => CreateImpl(type, path, errorCallback); private static Disc CreateImpl(DiscType? type, string path, Action errorCallback) { //--- load the disc in a context which will let us abort if it's going to take too long - var discMountJob = new DiscMountJob(fromPath: path, slowLoadAbortThreshold: 8); + DiscMountJob discMountJob = new(fromPath: path, slowLoadAbortThreshold: 8); discMountJob.Run(); if (discMountJob.OUT_SlowLoadAborted) diff --git a/src/BizHawk.Emulation.DiscSystem/DiscFormats/Blobs/Blob_ECM.cs b/src/BizHawk.Emulation.DiscSystem/DiscFormats/Blobs/Blob_ECM.cs index 0b9b32c2cbe..6c61c89b27b 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscFormats/Blobs/Blob_ECM.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscFormats/Blobs/Blob_ECM.cs @@ -65,12 +65,12 @@ public void Load(string path) while (true) { //read block count. this format is really stupid. maybe its good for detecting non-ecm files or something. - var b = stream.ReadByte(); + int b = stream.ReadByte(); if (b == -1) MisformedException(); - var bytes = 1; - var T = b & 3; + int bytes = 1; + int T = b & 3; long N = (b >> 2) & 0x1F; - var nbits = 5; + int nbits = 5; while (b.Bit(7)) { if (bytes == 5) MisformedException(); //if we're gonna need a 6th byte, this file is broken @@ -89,7 +89,7 @@ public void Load(string path) if (N >= 0x100000000) MisformedException(); - var todo = (uint)N + 1; + uint todo = (uint)N + 1; Index.Add(new IndexEntry(type: T, number: todo, ecmOffset: stream.Position, logicalOffset: logOffset)); @@ -119,24 +119,21 @@ public void Load(string path) //TODO - endian bug. need an endian-independent binary reader with good license (miscutils is apache license) //extension methods on binary reader wont suffice, we need something that lets you control the endianness used for reading. a complete replacement. - var br = new BinaryReader(stream); + BinaryReader br = new(stream); EDC = br.ReadInt32(); Length = logOffset; } - private static void MisformedException() - { - throw new InvalidOperationException("Mis-formed ECM file"); - } + private static void MisformedException() => throw new InvalidOperationException("Mis-formed ECM file"); public static bool IsECM(string path) { - using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); - var e = fs.ReadByte(); - var c = fs.ReadByte(); - var m = fs.ReadByte(); - var o = fs.ReadByte(); + using FileStream fs = new(path, FileMode.Open, FileAccess.Read, FileShare.Read); + int e = fs.ReadByte(); + int c = fs.ReadByte(); + int m = fs.ReadByte(); + int o = fs.ReadByte(); return e == 'E' && c == 'C' && m == 'M' && o == 0; } @@ -146,7 +143,7 @@ public static bool IsECM(string path) private int FindInIndex(long offset, int LastReadIndex) { //try to avoid searching the index. check the last index we we used. - for (var i = 0; i < 2; i++) //try 2 times + for (int i = 0; i < 2; i++) //try 2 times { var last = Index[LastReadIndex]; if (LastReadIndex == Index.Count - 1) @@ -171,7 +168,7 @@ private int FindInIndex(long offset, int LastReadIndex) } //Console.WriteLine("binary searched"); //use this to check for mistaken LastReadIndex logic resulting in binary searches during sequential access - var listIndex = Index.LowerBoundBinarySearch(idx => idx.LogicalOffset, offset); + int listIndex = Index.LowerBoundBinarySearch(idx => idx.LogicalOffset, offset); System.Diagnostics.Debug.Assert(listIndex < Index.Count); //Console.WriteLine("byte_pos {0:X8} using index #{1} at offset {2:X8}", offset, listIndex, Index[listIndex].LogicalOffset); @@ -182,7 +179,7 @@ private static void Reconstruct(byte[] secbuf, int type) { //sync secbuf[0] = 0; - for (var i = 1; i <= 10; i++) + for (int i = 1; i <= 10; i++) secbuf[i] = 0xFF; secbuf[11] = 0x00; @@ -193,7 +190,7 @@ private static void Reconstruct(byte[] secbuf, int type) //mode 1 secbuf[15] = 0x01; //reserved - for (var i = 0x814; i <= 0x81B; i++) + for (int i = 0x814; i <= 0x81B; i++) secbuf[i] = 0x00; break; @@ -233,7 +230,7 @@ private static void Reconstruct(byte[] secbuf, int type) public int Read(long byte_pos, byte[] buffer, int offset, int _count) { long remain = _count; - var completed = 0; + int completed = 0; //we take advantage of the fact that we pretty much always read one sector at a time. //this would be really inefficient if we only read one byte at a time. @@ -241,7 +238,7 @@ public int Read(long byte_pos, byte[] buffer, int offset, int _count) while (remain > 0) { - var listIndex = FindInIndex(byte_pos, Read_LastIndex); + int listIndex = FindInIndex(byte_pos, Read_LastIndex); var ie = Index[listIndex]; Read_LastIndex = listIndex; @@ -249,10 +246,10 @@ public int Read(long byte_pos, byte[] buffer, int offset, int _count) if (ie.Type == 0) { //type 0 is special: its just a raw blob. so all we need to do is read straight out of the stream - var blockOffset = byte_pos - ie.LogicalOffset; - var bytesRemainInBlock = ie.Number - blockOffset; + long blockOffset = byte_pos - ie.LogicalOffset; + long bytesRemainInBlock = ie.Number - blockOffset; - var todo = remain; + long todo = remain; if (bytesRemainInBlock < todo) todo = bytesRemainInBlock; @@ -264,7 +261,7 @@ public int Read(long byte_pos, byte[] buffer, int offset, int _count) toRead = int.MaxValue; else toRead = (int)todo; - var done = stream.Read(buffer, offset, toRead); + int done = stream.Read(buffer, offset, toRead); if (done != toRead) return completed; @@ -279,7 +276,7 @@ public int Read(long byte_pos, byte[] buffer, int offset, int _count) { //these are sector-based types. they have similar handling. - var blockOffset = byte_pos - ie.LogicalOffset; + long blockOffset = byte_pos - ie.LogicalOffset; //figure out which sector within the block we're in int outSecSize; @@ -300,12 +297,12 @@ public int Read(long byte_pos, byte[] buffer, int offset, int _count) throw new InvalidOperationException(); } - var secNumberInBlock = blockOffset / outSecSize; - var secOffsetInEcm = secNumberInBlock * outSecSize; - var bytesAskedIntoSector = blockOffset % outSecSize; - var bytesRemainInSector = outSecSize - bytesAskedIntoSector; + long secNumberInBlock = blockOffset / outSecSize; + long secOffsetInEcm = secNumberInBlock * outSecSize; + long bytesAskedIntoSector = blockOffset % outSecSize; + long bytesRemainInSector = outSecSize - bytesAskedIntoSector; - var todo = remain; + long todo = remain; if (bytesRemainInSector < todo) todo = bytesRemainInSector; @@ -336,7 +333,7 @@ public int Read(long byte_pos, byte[] buffer, int offset, int _count) //sector is decoded to 2352 bytes. Handling doesnt depend much on type from here Array.Copy(Read_SectorBuf, (int)bytesAskedIntoSector + outSecOffset, buffer, offset, todo); - var done = (int)todo; + int done = (int)todo; offset += done; completed += done; diff --git a/src/BizHawk.Emulation.DiscSystem/DiscFormats/Blobs/Blob_RawFile.cs b/src/BizHawk.Emulation.DiscSystem/DiscFormats/Blobs/Blob_RawFile.cs index 8d56d051c38..2b65760bed3 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscFormats/Blobs/Blob_RawFile.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscFormats/Blobs/Blob_RawFile.cs @@ -36,7 +36,7 @@ public int Read(long byte_pos, byte[] buffer, int offset, int count) const int buffersize = 2352 * 75 * 2; fs ??= new(new FileStream(physicalPath, FileMode.Open, FileAccess.Read, FileShare.Read), buffersize); - var target = byte_pos + Offset; + long target = byte_pos + Offset; if (fs.Position != target) fs.Position = target; return fs.Read(buffer, offset, count); diff --git a/src/BizHawk.Emulation.DiscSystem/DiscFormats/Blobs/Blob_WaveFile.cs b/src/BizHawk.Emulation.DiscSystem/DiscFormats/Blobs/Blob_WaveFile.cs index 9f28c2ed324..82443f1bbdd 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscFormats/Blobs/Blob_WaveFile.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscFormats/Blobs/Blob_WaveFile.cs @@ -29,7 +29,7 @@ public void Load(byte[] waveData) public void Load(string wavePath) { - var stream = new FileStream(wavePath, FileMode.Open, FileAccess.Read, FileShare.Read); + FileStream stream = new(wavePath, FileMode.Open, FileAccess.Read, FileShare.Read); Load(stream); } @@ -39,7 +39,7 @@ public void Load(Stream stream) try { RiffSource = null; - var rm = new RiffMaster(); + RiffMaster rm = new(); rm.LoadStream(stream); RiffSource = rm; @@ -55,7 +55,7 @@ public void Load(Stream stream) throw new Blob_WaveFile_Exception("Not a valid RIFF WAVE file (missing fmt chunk"); } - var dataChunks = rm.riff.subchunks.Where(chunk => chunk.tag == "data").ToList(); + System.Collections.Generic.List dataChunks = rm.riff.subchunks.Where(chunk => chunk.tag == "data").ToList(); if (dataChunks.Count != 1) { //later, we could make a Stream which would make an index of data chunks and walk around them @@ -73,7 +73,7 @@ public void Load(Stream stream) } //acquire the start of the data chunk - var dataChunk = (RiffMaster.RiffSubchunk) dataChunks[0]; + RiffMaster.RiffSubchunk dataChunk = (RiffMaster.RiffSubchunk) dataChunks[0]; waveDataStreamPos = dataChunk.Position; Length = dataChunk.Length; } diff --git a/src/BizHawk.Emulation.DiscSystem/DiscFormats/Blobs/Blob_ZeroPadAdapter.cs b/src/BizHawk.Emulation.DiscSystem/DiscFormats/Blobs/Blob_ZeroPadAdapter.cs index 16b3847c59c..18b81d9ee3c 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscFormats/Blobs/Blob_ZeroPadAdapter.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscFormats/Blobs/Blob_ZeroPadAdapter.cs @@ -17,8 +17,8 @@ public Blob_ZeroPadAdapter(IBlob srcBlob, long srcBlobLength) public int Read(long byte_pos, byte[] buffer, int offset, int count) { - var todo = count; - var end = byte_pos + todo; + int todo = count; + long end = byte_pos + todo; if (end > srcBlobLength) { todo = checked((int)(srcBlobLength - byte_pos)); diff --git a/src/BizHawk.Emulation.DiscSystem/DiscFormats/Blobs/RiffMaster.cs b/src/BizHawk.Emulation.DiscSystem/DiscFormats/Blobs/RiffMaster.cs index 56201fee4f0..96d9c446017 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscFormats/Blobs/RiffMaster.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscFormats/Blobs/RiffMaster.cs @@ -43,7 +43,7 @@ private static string ReadTag(BinaryReader br) => protected static void WriteTag(BinaryWriter bw, string tag) { - for (var i = 0; i < 4; i++) + for (int i = 0; i < 4; i++) bw.Write(tag[i]); bw.Flush(); } @@ -99,7 +99,7 @@ public override long GetVolume() public byte[] ReadAll() { - var msSize = (int)Math.Min((long)int.MaxValue, Length); + int msSize = (int)Math.Min((long)int.MaxValue, Length); MemoryStream ms = new(msSize); Source.Position = Position; Util.CopyStream(Source, ms, Length); @@ -108,11 +108,11 @@ public byte[] ReadAll() public override RiffChunk Morph() { - switch (tag) + return tag switch { - case "fmt ": return new RiffSubchunk_fmt(this); - } - return this; + "fmt " => new RiffSubchunk_fmt(this), + _ => this, + }; } } @@ -206,7 +206,7 @@ public override void WriteStream(Stream s) { BinaryWriter bw = new(s); WriteTag(bw, tag); - var size = GetVolume(); + long size = GetVolume(); if (size > uint.MaxValue) throw new FormatException("File too big to write out"); bw.Write((uint)size); WriteTag(bw, type); @@ -217,18 +217,15 @@ public override void WriteStream(Stream s) s.WriteByte(0); } - public override long GetVolume() - { - return 4 + subchunks.Sum(rc => rc.GetVolume() + 8); - } + public override long GetVolume() => 4 + subchunks.Sum(rc => rc.GetVolume() + 8); public override RiffChunk Morph() { - switch (type) + return type switch { - case "INFO": return new RiffContainer_INFO(this); - } - return this; + "INFO" => new RiffContainer_INFO(this), + _ => this, + }; } } @@ -254,7 +251,7 @@ private void Flush() subchunks.Clear(); foreach (var (subchunkTag, s) in dictionary) { - var rs = new RiffSubchunk + RiffSubchunk rs = new() { tag = subchunkTag, Source = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(s)), @@ -284,27 +281,27 @@ public override void WriteStream(Stream s) private RiffChunk ReadChunk(BinaryReader br) { RiffChunk ret; - var tag = ReadTag(br); readCounter += 4; - var size = br.ReadUInt32(); readCounter += 4; + string tag = ReadTag(br); readCounter += 4; + uint size = br.ReadUInt32(); readCounter += 4; if (size > int.MaxValue) throw new FormatException("chunk too big"); if (tag is "RIFF" or "LIST") { - var rc = new RiffContainer + RiffContainer rc = new() { tag = tag, type = ReadTag(br) }; readCounter += 4; - var readEnd = readCounter - 4 + size; + long readEnd = readCounter - 4 + size; while (readEnd > readCounter) rc.subchunks.Add(ReadChunk(br)); ret = rc.Morph(); } else { - var rsc = new RiffSubchunk + RiffSubchunk rsc = new() { tag = tag, Source = br.BaseStream, @@ -324,10 +321,7 @@ private RiffChunk ReadChunk(BinaryReader br) return ret; } - public void WriteStream(Stream s) - { - riff.WriteStream(s); - } + public void WriteStream(Stream s) => riff.WriteStream(s); /// takes posession of the supplied stream /// does not contain a riff chunk diff --git a/src/BizHawk.Emulation.DiscSystem/DiscFormats/CCD_format.cs b/src/BizHawk.Emulation.DiscSystem/DiscFormats/CCD_format.cs index b947327d2f6..5707f107a4e 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscFormats/CCD_format.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscFormats/CCD_format.cs @@ -165,12 +165,12 @@ private class CCDSection : Dictionary public string Name; public int FetchOrDefault(int def, string key) - => TryGetValue(key, out var val) ? val : def; + => TryGetValue(key, out int val) ? val : def; /// not found in public int FetchOrFail(string key) { - if (!TryGetValue(key, out var ret)) + if (!TryGetValue(key, out int ret)) throw new CCDParseException($"Malformed or unexpected CCD format: missing required [Entry] key: {key}"); return ret; } @@ -178,16 +178,16 @@ public int FetchOrFail(string key) private static List ParseSections(Stream stream) { - var sections = new List(); + List sections = new(); //TODO - do we need to attempt to parse out the version tag in a first pass? //im doing this from a version 3 example - var sr = new StreamReader(stream); + StreamReader sr = new(stream); CCDSection currSection = null; while (true) { - var line = sr.ReadLine(); + string line = sr.ReadLine(); if (line is null) break; if (line == string.Empty) continue; if (line.StartsWith('[')) @@ -202,7 +202,7 @@ private static List ParseSections(Stream stream) { if (currSection is null) throw new CCDParseException("Malformed or unexpected CCD format: started without ["); - var parts = line.Split('='); + string[] parts = line.Split('='); if (parts.Length != 2) throw new CCDParseException("Malformed or unexpected CCD format: parsing item into two parts"); if (parts[0].ToUpperInvariant() == "FLAGS") @@ -239,7 +239,7 @@ private static int PreParseIntegrityCheck(IReadOnlyList sections) if (ccdSection.Name != "CLONECD") throw new CCDParseException("Malformed CCD format: confusing first section name"); - if (!ccdSection.TryGetValue("VERSION", out var version)) + if (!ccdSection.TryGetValue("VERSION", out int version)) throw new CCDParseException("Malformed CCD format: missing version in CloneCD section"); if (sections[1].Name != "DISC") @@ -251,27 +251,27 @@ private static int PreParseIntegrityCheck(IReadOnlyList sections) /// parsed is 1, parsed session number is not 1, or malformed entry public static CCDFile ParseFrom(Stream stream) { - var ccdf = new CCDFile(); + CCDFile ccdf = new(); var sections = ParseSections(stream); ccdf.Version = PreParseIntegrityCheck(sections); var discSection = sections[1]; - var nTocEntries = discSection["TOCENTRIES"]; //its conceivable that this could be missing - var nSessions = discSection["SESSIONS"]; //its conceivable that this could be missing + int nTocEntries = discSection["TOCENTRIES"]; //its conceivable that this could be missing + int nSessions = discSection["SESSIONS"]; //its conceivable that this could be missing ccdf.DataTracksScrambled = discSection.FetchOrDefault(0, "DATATRACKSSCRAMBLED"); ccdf.CDTextLength = discSection.FetchOrDefault(0, "CDTEXTLENGTH"); if (ccdf.DataTracksScrambled == 1) throw new CCDParseException($"Malformed CCD format: {nameof(ccdf.DataTracksScrambled)}=1 not supported. Please report this, so we can understand what it means."); - for (var i = 2; i < sections.Count; i++) + for (int i = 2; i < sections.Count; i++) { var section = sections[i]; if (section.Name.StartsWithOrdinal("SESSION")) { - var sesnum = int.Parse(section.Name.Split(' ')[1]); - var session = new CCDSession(sesnum); + int sesnum = int.Parse(section.Name.Split(' ')[1]); + CCDSession session = new(sesnum); ccdf.Sessions.Add(session); if (sesnum != ccdf.Sessions.Count) throw new CCDParseException("Malformed CCD format: wrong session number in sequence"); @@ -280,8 +280,8 @@ public static CCDFile ParseFrom(Stream stream) } else if (section.Name.StartsWithOrdinal("ENTRY")) { - var entryNum = int.Parse(section.Name.Split(' ')[1]); - var entry = new CCDTocEntry(entryNum); + int entryNum = int.Parse(section.Name.Split(' ')[1]); + CCDTocEntry entry = new(entryNum); ccdf.TOCEntries.Add(entry); entry.Session = section.FetchOrFail("SESSION"); @@ -307,8 +307,8 @@ public static CCDFile ParseFrom(Stream stream) } else if (section.Name.StartsWithOrdinal("TRACK")) { - var entryNum = int.Parse(section.Name.Split(' ')[1]); - var track = new CCDTrack(entryNum); + int entryNum = int.Parse(section.Name.Split(' ')[1]); + CCDTrack track = new(entryNum); ccdf.Tracks.Add(track); ccdf.TracksByNumber[entryNum] = track; foreach (var (k, v) in section) @@ -335,7 +335,7 @@ public class LoadResults public static LoadResults LoadCCDPath(string path) { - var ret = new LoadResults + LoadResults ret = new() { CcdPath = path, ImgPath = Path.ChangeExtension(path, ".img"), @@ -346,7 +346,7 @@ public static LoadResults LoadCCDPath(string path) if (!File.Exists(path)) throw new CCDParseException("Malformed CCD format: nonexistent CCD file!"); CCDFile ccdf; - using (var infCCD = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) + using (FileStream infCCD = new(path, FileMode.Open, FileAccess.Read, FileShare.Read)) ccdf = ParseFrom(infCCD); ret.ParsedCCDFile = ccdf; @@ -363,7 +363,7 @@ public static LoadResults LoadCCDPath(string path) public static void Dump(Disc disc, string path) { - using (var sw = new StreamWriter(path)) + using (StreamWriter sw = new(path)) { //NOTE: IsoBuster requires the A0,A1,A2 RawTocEntries to be first or else it can't do anything with the tracks //if we ever get them in a different order, we'll have to re-order them here @@ -377,7 +377,7 @@ public static void Dump(Disc disc, string path) sw.WriteLine("DataTracksScrambled=0"); sw.WriteLine("CDTextLength=0"); //not supported anyway sw.WriteLine(); - for (var i = 1; i < disc.Sessions.Count; i++) + for (int i = 1; i < disc.Sessions.Count; i++) { var session = disc.Sessions[i]; @@ -386,12 +386,12 @@ public static void Dump(Disc disc, string path) sw.WriteLine("PreGapSubC=1"); sw.WriteLine(); - for (var j = 0; j < session.RawTOCEntries.Count; j++) + for (int j = 0; j < session.RawTOCEntries.Count; j++) { var entry = session.RawTOCEntries[j]; //ehhh something's wrong with how I track these - var point = entry.QData.q_index.DecimalValue; + int point = entry.QData.q_index.DecimalValue; if (point == 100) point = 0xA0; if (point == 101) point = 0xA1; if (point == 102) point = 0xA2; @@ -418,7 +418,7 @@ public static void Dump(Disc disc, string path) //but in order to make a high quality CCD which can be inspected by various other tools, we need it //now, regarding the indexes.. theyre truly useless. having indexes written out with the tracks is bad news. //index information is only truly stored in subQ - for (var tnum = 1; tnum <= session.InformationTrackCount; tnum++) + for (int tnum = 1; tnum <= session.InformationTrackCount; tnum++) { var track = session.Tracks[tnum]; sw.WriteLine("[TRACK {0}]", track.Number); @@ -433,15 +433,15 @@ public static void Dump(Disc disc, string path) //TODO - actually re-add //dump the img and sub //TODO - acquire disk size first - var imgPath = Path.ChangeExtension(path, ".img"); - var subPath = Path.ChangeExtension(path, ".sub"); - var buf2448 = new byte[2448]; - var dsr = new DiscSectorReader(disc); + string imgPath = Path.ChangeExtension(path, ".img"); + string subPath = Path.ChangeExtension(path, ".sub"); + byte[] buf2448 = new byte[2448]; + DiscSectorReader dsr = new(disc); using var imgFile = File.OpenWrite(imgPath); using var subFile = File.OpenWrite(subPath); - var nLBA = disc.Sessions[disc.Sessions.Count - 1].LeadoutLBA; - for (var lba = 0; lba < nLBA; lba++) + int nLBA = disc.Sessions[disc.Sessions.Count - 1].LeadoutLBA; + for (int lba = 0; lba < nLBA; lba++) { dsr.ReadLBA_2448(lba, buf2448, 0); imgFile.Write(buf2448, 0, 2352); @@ -454,8 +454,8 @@ private class SS_CCD : ISectorSynthJob2448 public void Synth(SectorSynthJob job) { //CCD is always containing everything we'd need (unless a .sub is missing?) so don't worry about flags - var imgBlob = (IBlob) job.Disc.DisposableResources[0]; - var subBlob = (IBlob) job.Disc.DisposableResources[1]; + IBlob imgBlob = (IBlob) job.Disc.DisposableResources[0]; + IBlob subBlob = (IBlob) job.Disc.DisposableResources[1]; //Read_2442(job.LBA, job.DestBuffer2448, job.DestOffset); //read the IMG data if needed @@ -487,22 +487,22 @@ public static Disc LoadCCDToDisc(string ccdPath, DiscMountPolicy IN_DiscMountPol if (!loadResults.Valid) throw loadResults.FailureException; - var disc = new Disc(); + Disc disc = new(); IBlob imgBlob = null; long imgLen = -1; //mount the IMG file //first check for a .ecm in place of the img - var imgPath = loadResults.ImgPath; + string imgPath = loadResults.ImgPath; if (!File.Exists(imgPath)) { - var ecmPath = Path.ChangeExtension(imgPath, ".img.ecm"); + string ecmPath = Path.ChangeExtension(imgPath, ".img.ecm"); if (File.Exists(ecmPath)) { if (Blob_ECM.IsECM(ecmPath)) { - var ecm = new Blob_ECM(); + Blob_ECM ecm = new(); ecm.Load(ecmPath); imgBlob = ecm; imgLen = ecm.Length; @@ -512,7 +512,7 @@ public static Disc LoadCCDToDisc(string ccdPath, DiscMountPolicy IN_DiscMountPol if (imgBlob == null) { if (!File.Exists(loadResults.ImgPath)) throw new CCDParseException("Malformed CCD format: nonexistent IMG file!"); - var imgFile = new Blob_RawFile() { PhysicalPath = loadResults.ImgPath }; + Blob_RawFile imgFile = new() { PhysicalPath = loadResults.ImgPath }; imgLen = imgFile.Length; imgBlob = imgFile; } @@ -520,22 +520,22 @@ public static Disc LoadCCDToDisc(string ccdPath, DiscMountPolicy IN_DiscMountPol //mount the SUB file if (!File.Exists(loadResults.SubPath)) throw new CCDParseException("Malformed CCD format: nonexistent SUB file!"); - var subFile = new Blob_RawFile { PhysicalPath = loadResults.SubPath }; + Blob_RawFile subFile = new() { PhysicalPath = loadResults.SubPath }; disc.DisposableResources.Add(subFile); - var subLen = subFile.Length; + long subLen = subFile.Length; //quick integrity check of file sizes if (imgLen % 2352 != 0) throw new CCDParseException("Malformed CCD format: IMG file length not multiple of 2352"); - var NumImgSectors = (int)(imgLen / 2352); + int NumImgSectors = (int)(imgLen / 2352); if (subLen != NumImgSectors * 96) throw new CCDParseException("Malformed CCD format: SUB file length not matching IMG"); var ccdf = loadResults.ParsedCCDFile; //the only instance of a sector synthesizer we'll need - var synth = new SS_CCD(); + SS_CCD synth = new(); // create the initial session - var curSession = 1; + int curSession = 1; disc.Sessions.Add(new() { Number = curSession }); //generate DiscTOCRaw items from the ones specified in the CCD file @@ -551,20 +551,20 @@ public static Disc LoadCCDToDisc(string ccdPath, DiscMountPolicy IN_DiscMountPol } //this should actually be zero. im not sure if this is stored as BCD2 or not - var tno = BCD2.FromDecimal(entry.TrackNo); + BCD2 tno = BCD2.FromDecimal(entry.TrackNo); //these are special values.. I think, taken from this: //http://www.staff.uni-mainz.de/tacke/scsi/SCSI2-14.html //the CCD will contain Points as decimal values except for these specially converted decimal values which should stay as BCD. //Why couldn't they all be BCD? I don't know. I guess because BCD is inconvenient, but only A0 and friends have special meaning. It's confusing. - var ino = BCD2.FromDecimal(entry.Point); + BCD2 ino = BCD2.FromDecimal(entry.Point); ino.BCDValue = entry.Point switch { 0xA0 or 0xA1 or 0xA2 => (byte)entry.Point, _ => ino.BCDValue }; - var q = new SubchannelQ + SubchannelQ q = new() { q_status = SubchannelQ.ComputeStatus(entry.ADR, (EControlQ)(entry.Control & 0xF)), q_tno = tno, @@ -583,7 +583,7 @@ public static Disc LoadCCDToDisc(string ccdPath, DiscMountPolicy IN_DiscMountPol } //analyze the RAWTocEntries to figure out what type of track track 1 is - var tocSynth = new Synthesize_DiscTOC_From_RawTOCEntries_Job(disc.Session1.RawTOCEntries); + Synthesize_DiscTOC_From_RawTOCEntries_Job tocSynth = new(disc.Session1.RawTOCEntries); tocSynth.Run(); //Add sectors for the mandatory track 1 pregap, which isn't stored in the CCD file @@ -602,16 +602,16 @@ public static Disc LoadCCDToDisc(string ccdPath, DiscMountPolicy IN_DiscMountPol }; } - for (var i = 0; i < 150; i++) + for (int i = 0; i < 150; i++) { - var ss_gap = new CUE.SS_Gap() + CUE.SS_Gap ss_gap = new() { Policy = IN_DiscMountPolicy, TrackType = pregapTrackType }; disc._Sectors.Add(ss_gap); - var qRelMSF = i - 150; + int qRelMSF = i - 150; //tweak relMSF due to ambiguity/contradiction in yellowbook docs if (!IN_DiscMountPolicy.CUE_PregapContradictionModeA) @@ -632,7 +632,7 @@ public static Disc LoadCCDToDisc(string ccdPath, DiscMountPolicy IN_DiscMountPol //build the sectors: //set up as many sectors as we have img/sub for, even if the TOC doesnt reference them //(the TOC is unreliable, and the Track records are redundant) - for (var i = 0; i < NumImgSectors; i++) + for (int i = 0; i < NumImgSectors; i++) { disc._Sectors.Add(synth); } diff --git a/src/BizHawk.Emulation.DiscSystem/DiscFormats/CDI_format.cs b/src/BizHawk.Emulation.DiscSystem/DiscFormats/CDI_format.cs index 76af9ce656a..bb5b0b23253 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscFormats/CDI_format.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscFormats/CDI_format.cs @@ -193,8 +193,8 @@ public CDIParseException(string message) : base(message) { } /// malformed cdi format public static CDIFile ParseFrom(Stream stream) { - var cdif = new CDIFile(); - using var br = new BinaryReader(stream); + CDIFile cdif = new(); + using BinaryReader br = new(stream); try { @@ -213,7 +213,7 @@ void ParseTrackHeader(CDITrackHeader header) { stream.Seek(15, SeekOrigin.Current); // unknown bytes header.NumTracks = br.ReadByte(); - var pathLen = br.ReadByte(); + byte pathLen = br.ReadByte(); header.Path = br.ReadStringFixedUtf8(pathLen); stream.Seek(29, SeekOrigin.Current); // unknown bytes header.MediumType = br.ReadUInt16(); @@ -228,9 +228,9 @@ void ParseTrackHeader(CDITrackHeader header) } } - for (var i = 0; i <= cdif.NumSessions; i++) + for (int i = 0; i <= cdif.NumSessions; i++) { - var session = new CDISession(); + CDISession session = new(); stream.Seek(1, SeekOrigin.Current); // unknown byte session.NumTracks = br.ReadByte(); stream.Seek(13, SeekOrigin.Current); // unknown bytes @@ -247,28 +247,28 @@ void ParseTrackHeader(CDITrackHeader header) throw new CDIParseException("Malformed CDI format: More than 99 tracks on disc!"); } - for (var j = 0; j < session.NumTracks; j++) + for (int j = 0; j < session.NumTracks; j++) { - var track = new CDITrack(); + CDITrack track = new(); ParseTrackHeader(track); - var indexes = br.ReadUInt16(); + ushort indexes = br.ReadUInt16(); if (indexes < 2) // We should have at least 2 indexes (one pre-gap, and one "real" one) { throw new CDIParseException("Malformed CDI format: Less than 2 indexes in track!"); } - for (var k = 0; k < indexes; k++) + for (int k = 0; k < indexes; k++) { track.IndexSectorCounts.Add(br.ReadUInt32()); } - var numCdTextBlocks = br.ReadUInt32(); - for (var k = 0; k < numCdTextBlocks; k++) + uint numCdTextBlocks = br.ReadUInt32(); + for (int k = 0; k < numCdTextBlocks; k++) { - var cdTextBlock = new CDICDText(); - for (var l = 0; l < 18; l++) + CDICDText cdTextBlock = new(); + for (int l = 0; l < 18; l++) { - var cdTextLen = br.ReadByte(); + byte cdTextLen = br.ReadByte(); if (cdTextLen > 0) { cdTextBlock.CdTexts.Add(br.ReadStringFixedUtf8(cdTextLen)); @@ -314,7 +314,7 @@ void ParseTrackHeader(CDITrackHeader header) } stream.Seek(1, SeekOrigin.Current); // unknown byte - var redundantTrackLen = br.ReadUInt32(); + uint redundantTrackLen = br.ReadUInt32(); if (track.TrackLength != redundantTrackLen) { throw new CDIParseException("Malformed CDI format: Track length mismatch!"); @@ -339,7 +339,7 @@ void ParseTrackHeader(CDITrackHeader header) } stream.Seek(5, SeekOrigin.Current); // unknown bytes - var notLastTrackInSession = br.ReadByte(); + byte notLastTrackInSession = br.ReadByte(); switch (notLastTrackInSession) { case 0 when j != session.NumTracks - 1: @@ -367,7 +367,7 @@ void ParseTrackHeader(CDITrackHeader header) //Seems the blob doesn't include leadin and leadout directly anyways } - var volumeIdLen = br.ReadByte(); + byte volumeIdLen = br.ReadByte(); cdif.DiscInfo.VolumeId = br.ReadStringFixedUtf8(volumeIdLen); stream.Seek(9, SeekOrigin.Current); // unknown bytes @@ -378,7 +378,7 @@ void ParseTrackHeader(CDITrackHeader header) cdif.DiscInfo.Ean13Code = string.Empty; } - var cdTextLengh = br.ReadUInt32(); + uint cdTextLengh = br.ReadUInt32(); if (cdTextLengh > int.MaxValue) { // suppose technically this might not be considered too large purely going off the format @@ -418,7 +418,7 @@ public class LoadResults public static LoadResults LoadCDIPath(string path) { - var ret = new LoadResults + LoadResults ret = new() { CdiPath = path }; @@ -427,7 +427,7 @@ public static LoadResults LoadCDIPath(string path) if (!File.Exists(path)) throw new CDIParseException("Malformed CDI format: nonexistent CDI file!"); CDIFile cdif; - using (var infCDI = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) + using (FileStream infCDI = new(path, FileMode.Open, FileAccess.Read, FileShare.Read)) cdif = ParseFrom(infCDI); ret.ParsedCDIFile = cdif; @@ -448,22 +448,22 @@ public static Disc LoadCDIToDisc(string cdiPath, DiscMountPolicy IN_DiscMountPol if (!loadResults.Valid) throw loadResults.FailureException; - var disc = new Disc(); + Disc disc = new(); var cdif = loadResults.ParsedCDIFile; IBlob cdiBlob = new Blob_RawFile { PhysicalPath = cdiPath }; disc.DisposableResources.Add(cdiBlob); - var trackOffset = 0; - var blobOffset = 0; - for (var i = 0; i < cdif.NumSessions; i++) + int trackOffset = 0; + int blobOffset = 0; + for (int i = 0; i < cdif.NumSessions; i++) { - var session = new DiscSession { Number = i + 1 }; + DiscSession session = new() { Number = i + 1 }; // leadin track // we create this only for session 2+, not session 1 - var leadinSize = i == 0 ? 0 : 4500; - for (var j = 0; j < leadinSize; j++) + int leadinSize = i == 0 ? 0 : 4500; + for (int j = 0; j < leadinSize; j++) { // this is most certainly wrong // nothing relies on the exact contents for now (only multisession core is VirtualJaguar which doesn't touch leadin) @@ -486,13 +486,13 @@ public static Disc LoadCDIToDisc(string cdiPath, DiscMountPolicy IN_DiscMountPol }); } - for (var j = 0; j < cdif.Sessions[i].NumTracks; j++) + for (int j = 0; j < cdif.Sessions[i].NumTracks; j++) { var track = cdif.Tracks[trackOffset + j]; RawTOCEntry EmitRawTOCEntry() { - var q = default(SubchannelQ); + SubchannelQ q = default; //absent some kind of policy for how to set it, this is a safe assumption const byte kADR = 1; q.SetStatus(kADR, (EControlQ)track.Control); @@ -505,7 +505,7 @@ RawTOCEntry EmitRawTOCEntry() return new() { QData = q }; } - var sectorSize = track.ReadMode switch + int sectorSize = track.ReadMode switch { 0 => 2048, 1 => 2336, @@ -514,10 +514,10 @@ RawTOCEntry EmitRawTOCEntry() 4 => 2448, _ => throw new InvalidOperationException() }; - var curIndex = 0; - var relMSF = -track.IndexSectorCounts[0]; - var indexSectorOffset = 0U; - for (var k = 0; k < track.TrackLength; k++) + int curIndex = 0; + long relMSF = -track.IndexSectorCounts[0]; + uint indexSectorOffset = 0U; + for (int k = 0; k < track.TrackLength; k++) { if (track.IndexSectorCounts[curIndex] == k - indexSectorOffset) { @@ -565,8 +565,8 @@ RawTOCEntry EmitRawTOCEntry() // leadout track // first leadout is 6750 sectors, later ones are 2250 sectors - var leadoutSize = i == 0 ? 6750 : 2250; - for (var j = 0; j < leadoutSize; j++) + int leadoutSize = i == 0 ? 6750 : 2250; + for (int j = 0; j < leadoutSize; j++) { disc._Sectors.Add(new SS_Leadout { @@ -575,7 +575,7 @@ RawTOCEntry EmitRawTOCEntry() }); } - var TOCMiscInfo = new Synthesize_A0A1A2_Job( + Synthesize_A0A1A2_Job TOCMiscInfo = new( firstRecordedTrackNumber: trackOffset + 1, lastRecordedTrackNumber: trackOffset + cdif.Sessions[i].NumTracks, sessionFormat: (SessionFormat)(cdif.Tracks[trackOffset + cdif.Sessions[i].NumTracks - 1].SessionType * 0x10), diff --git a/src/BizHawk.Emulation.DiscSystem/DiscFormats/CUE/CUE_Compile.cs b/src/BizHawk.Emulation.DiscSystem/DiscFormats/CUE/CUE_Compile.cs index 451a0a8b60f..0fbc721474c 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscFormats/CUE/CUE_Compile.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscFormats/CUE/CUE_Compile.cs @@ -73,10 +73,7 @@ internal class CompiledCueFile { public string FullPath; public CompiledCueFileType Type; - public override string ToString() - { - return $"{Type}: {Path.GetFileName(FullPath)}"; - } + public override string ToString() => $"{Type}: {Path.GetFileName(FullPath)}"; } internal class CompiledSessionInfo @@ -113,7 +110,7 @@ public override string ToString() { var idx = Indexes.FirstOrNull(static cci => cci.Number is 1); if (idx is null) return $"T#{Number:D2} NO INDEX 1"; - var indexlist = string.Join("|", Indexes); + string indexlist = string.Join("|", Indexes); return $"T#{Number:D2} {BlobIndex}:{idx.Value.FileMSF} ({indexlist})"; } } @@ -225,11 +222,11 @@ private void OpenFile(CUE_File.Command.FILE f) return; } - var choice = options[0]; + string choice = options[0]; if (options.Count > 1) Warn($"Multiple options resolving referenced cue file; choosing: {Path.GetFileName(choice)}"); - var cfi = new CompiledCueFile(); + CompiledCueFile cfi = new(); curr_file = cfi; OUT_CompiledCueFiles.Add(cfi); @@ -238,7 +235,7 @@ private void OpenFile(CUE_File.Command.FILE f) //determine the CueFileInfo's type, based on extension and extra checking //TODO - once we reorganize the file ID stuff, do legit checks here (this is completely redundant with the fileID system //TODO - decode vs stream vs unpossible policies in input policies object (including ffmpeg availability-checking callback (results can be cached)) - var blobPathExt = Path.GetExtension(choice).ToUpperInvariant(); + string blobPathExt = Path.GetExtension(choice).ToUpperInvariant(); switch (blobPathExt) { case ".BIN" or ".IMG" or ".RAW": @@ -251,7 +248,7 @@ private void OpenFile(CUE_File.Command.FILE f) //TODO - fix exception-throwing inside //TODO - verify stream-disposing semantics var fs = File.OpenRead(choice); - using var blob = new Blob_WaveFile(); + using Blob_WaveFile blob = new(); try { blob.Load(fs); @@ -308,7 +305,7 @@ private void FinalAnalysis() //we could check the format of the wav file here, though //score the cost of loading the file - var needsCodec = false; + bool needsCodec = false; OUT_LoadTime = 0; foreach (var cfi in OUT_CompiledCueFiles.Where(cfi => cfi is not null)) { @@ -387,10 +384,7 @@ private void OpenTrack(CUE_File.Command.TRACK trackCommand) UpdateDiscInfo(trackCommand); } - private void AddIndex(CUE_File.Command.INDEX indexCommand) - { - curr_track.Indexes.Add(new(indexCommand.Number, indexCommand.Timestamp)); - } + private void AddIndex(CUE_File.Command.INDEX indexCommand) => curr_track.Indexes.Add(new(indexCommand.Number, indexCommand.Timestamp)); public override void Run() { @@ -401,7 +395,7 @@ public override void Run() //add a track 0, for addressing convenience. //note: for future work, track 0 may need emulation (accessible by very negative LBA--the TOC is stored there) - var track0 = new CompiledCueTrack + CompiledCueTrack track0 = new() { Number = 0, }; diff --git a/src/BizHawk.Emulation.DiscSystem/DiscFormats/CUE/CUE_Load.cs b/src/BizHawk.Emulation.DiscSystem/DiscFormats/CUE/CUE_Load.cs index b3c489a8706..6122e765973 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscFormats/CUE/CUE_Load.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscFormats/CUE/CUE_Load.cs @@ -78,7 +78,7 @@ private void MountBlobs() BlobInfos = new(); foreach (var ccf in IN_CompileJob.OUT_CompiledCueFiles) { - var bi = new BlobInfo(); + BlobInfo bi = new(); BlobInfos.Add(bi); IBlob file_blob; @@ -88,14 +88,14 @@ private void MountBlobs() case CompiledCueFileType.Unknown: { //raw files: - var blob = new Blob_RawFile { PhysicalPath = ccf.FullPath }; + Blob_RawFile blob = new() { PhysicalPath = ccf.FullPath }; OUT_Disc.DisposableResources.Add(file_blob = blob); bi.Length = blob.Length; break; } case CompiledCueFileType.ECM: { - var blob = new Blob_ECM(); + Blob_ECM blob = new(); OUT_Disc.DisposableResources.Add(file_blob = blob); blob.Load(ccf.FullPath); bi.Length = blob.Length; @@ -103,7 +103,7 @@ private void MountBlobs() } case CompiledCueFileType.WAVE: { - var blob = new Blob_WaveFile(); + Blob_WaveFile blob = new(); OUT_Disc.DisposableResources.Add(file_blob = blob); blob.Load(ccf.FullPath); bi.Length = blob.Length; @@ -116,8 +116,8 @@ private void MountBlobs() throw new DiscReferenceException(ccf.FullPath, "No decoding service was available (make sure ffmpeg.exe is available. Even though this may be a wav, ffmpeg is used to load oddly formatted wave files. If you object to this, please send us a note and we'll see what we can do. It shouldn't be too hard.)"); } AudioDecoder dec = new(); - var buf = dec.AcquireWaveData(ccf.FullPath); - var blob = new Blob_WaveFile(); + byte[] buf = dec.AcquireWaveData(ccf.FullPath); + Blob_WaveFile blob = new(); OUT_Disc.DisposableResources.Add(file_blob = blob); blob.Load(new MemoryStream(buf)); bi.Length = buf.Length; @@ -174,7 +174,7 @@ private void CloseSession() { //add RawTOCEntries A0 A1 A2 to round out the TOC var sessionInfo = IN_CompileJob.OUT_CompiledSessionInfo[CurrentSession.Number]; - var TOCMiscInfo = new Synthesize_A0A1A2_Job( + Synthesize_A0A1A2_Job TOCMiscInfo = new( firstRecordedTrackNumber: sessionInfo.FirstRecordedTrackNumber, lastRecordedTrackNumber: sessionInfo.LastRecordedTrackNumber, sessionFormat: sessionInfo.SessionFormat, @@ -192,8 +192,8 @@ public override void Run() OUT_Disc = new(); //generation state - var curr_blobIndex = -1; - var curr_blobMSF = -1; + int curr_blobIndex = -1; + int curr_blobMSF = -1; BlobInfo curr_blobInfo = null; long curr_blobOffset = -1; @@ -206,7 +206,7 @@ public override void Run() //loop from track 1 to 99 //(track 0 isnt handled yet, that's way distant work) - for (var t = 1; t < TrackInfos.Count; t++) + for (int t = 1; t < TrackInfos.Count; t++) { var ti = TrackInfos[t]; var cct = ti.CompiledCueTrack; @@ -232,12 +232,12 @@ public override void Run() //--------------------------------- //setup track pregap processing //per "Example 05" on digitalx.org, pregap can come from index specification and pregap command - var specifiedPregapLength = cct.PregapLength.Sector; - var impliedPregapLength = cct.Indexes[1].FileMSF.Sector - cct.Indexes[0].FileMSF.Sector; - var totalPregapLength = specifiedPregapLength + impliedPregapLength; + int specifiedPregapLength = cct.PregapLength.Sector; + int impliedPregapLength = cct.Indexes[1].FileMSF.Sector - cct.Indexes[0].FileMSF.Sector; + int totalPregapLength = specifiedPregapLength + impliedPregapLength; //from now on we'll track relative timestamp and increment it continually - var relMSF = -totalPregapLength; + int relMSF = -totalPregapLength; //read more at policies declaration //if (!context.DiscMountPolicy.CUE_PauseContradictionModeA) @@ -258,11 +258,11 @@ public override void Run() } //work until the next track is reached, or the end of the current file is reached, depending on the track type - var curr_index = 0; + int curr_index = 0; while (true) { - var trackDone = false; - var generateGap = false; + bool trackDone = false; + bool generateGap = false; if (specifiedPregapLength > 0) { @@ -293,7 +293,7 @@ public override void Run() //select the track type for the subQ //it's obviously the same as the main track type usually, but during a pregap it can be different var qTrack = ti; - var qRelMSF = relMSF; + int qRelMSF = relMSF; if (curr_index == 0) { //tweak relMSF due to ambiguity/contradiction in yellowbook docs @@ -390,10 +390,10 @@ public override void Run() //--------------------------------- //gen postgap sectors - var specifiedPostgapLength = cct.PostgapLength.Sector; - for (var s = 0; s < specifiedPostgapLength; s++) + int specifiedPostgapLength = cct.PostgapLength.Sector; + for (int s = 0; s < specifiedPostgapLength; s++) { - var ss = new SS_Gap + SS_Gap ss = new() { TrackType = cct.TrackType // TODO - old track type in some < -150 cases? }; diff --git a/src/BizHawk.Emulation.DiscSystem/DiscFormats/CUE/CUE_Parse.cs b/src/BizHawk.Emulation.DiscSystem/DiscFormats/CUE/CUE_Parse.cs index 6831187ed24..048643a8d1c 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscFormats/CUE/CUE_Parse.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscFormats/CUE/CUE_Parse.cs @@ -44,12 +44,12 @@ public CueLineParser(string line) str = line; } - public string ReadPath() { return ReadToken(Mode.Quotable); } - public string ReadToken() { return ReadToken(Mode.Normal); } + public string ReadPath() => ReadToken(Mode.Quotable); + public string ReadToken() => ReadToken(Mode.Normal); public string ReadLine() { - var len = str.Length; - var ret = str.Substring(index, len - index); + int len = str.Length; + string ret = str.Substring(index, len - index); index = len; EOF = true; return ret; @@ -64,16 +64,16 @@ private string ReadToken(Mode mode) { if (EOF) return null; - var isPath = mode == Mode.Quotable; + bool isPath = mode == Mode.Quotable; - var startIndex = index; - var inToken = false; - var inQuote = false; + int startIndex = index; + bool inToken = false; + bool inQuote = false; for (; ; ) { - var done = false; - var c = str[index]; - var isWhiteSpace = c is ' ' or '\t'; + bool done = false; + char c = str[index]; + bool isWhiteSpace = c is ' ' or '\t'; if (isWhiteSpace) { @@ -89,7 +89,7 @@ private string ReadToken(Mode mode) } else { - var startedQuote = false; + bool startedQuote = false; if (!inToken) { startIndex = index; @@ -123,7 +123,7 @@ private string ReadToken(Mode mode) if (done) break; } - var ret = str.Substring(startIndex, index - startIndex); + string ret = str.Substring(startIndex, index - startIndex); if (mode == Mode.Quotable) ret = ret.Trim('"'); @@ -139,21 +139,21 @@ private void LoadFromString() while (true) { CurrentLine++; - var line = tr.ReadLine()?.Trim(); + string line = tr.ReadLine()?.Trim(); if (line is null) break; if (line == string.Empty) continue; - var clp = new CueLineParser(line); + CueLineParser clp = new(line); - var key = clp.ReadToken().ToUpperInvariant(); + string key = clp.ReadToken().ToUpperInvariant(); //remove nonsense at beginning if (!IN_Strict) { while (key.Length > 0) { - var c = key[0]; + char c = key[0]; if(c == ';') break; - if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) break; + if (c is >= 'a' and <= 'z' or >= 'A' and <= 'Z') break; key = key.Substring(1); } } @@ -187,7 +187,7 @@ private void LoadFromString() case "FILE": { - var path = clp.ReadPath(); + string path = clp.ReadPath(); CueFileType ft; if (clp.EOF) { @@ -196,7 +196,7 @@ private void LoadFromString() } else { - var strType = clp.ReadToken().ToUpperInvariant(); + string strType = clp.ReadToken().ToUpperInvariant(); switch (strType) { default: @@ -219,7 +219,7 @@ private void LoadFromString() CueTrackFlags flags = default; while (!clp.EOF) { - var flag = clp.ReadToken().ToUpperInvariant(); + string flag = clp.ReadToken().ToUpperInvariant(); switch (flag) { case "DATA": @@ -245,14 +245,14 @@ private void LoadFromString() Error("Incomplete INDEX command"); break; } - var strindexnum = clp.ReadToken(); - if (!int.TryParse(strindexnum, out var indexnum) || indexnum < 0 || indexnum > 99) + string strindexnum = clp.ReadToken(); + if (!int.TryParse(strindexnum, out int indexnum) || indexnum < 0 || indexnum > 99) { Error($"Invalid INDEX number: {strindexnum}"); break; } - var str_timestamp = clp.ReadToken(); - var ts = new Timestamp(str_timestamp); + string str_timestamp = clp.ReadToken(); + Timestamp ts = new(str_timestamp); if (!ts.Valid && !IN_Strict) { //try cleaning it up @@ -276,7 +276,7 @@ private void LoadFromString() Warn("Ignoring empty ISRC command"); else { - var isrc = clp.ReadToken(); + string isrc = clp.ReadToken(); if (isrc.Length != 12) Warn($"Invalid ISRC code ignored: {isrc}"); else @@ -293,8 +293,8 @@ private void LoadFromString() case "POSTGAP": case "PREGAP": { - var str_msf = clp.ReadToken(); - var msf = new Timestamp(str_msf); + string str_msf = clp.ReadToken(); + Timestamp msf = new(str_msf); if (!msf.Valid) Error($"Ignoring {{0}} with invalid length MSF: {str_msf}", key); else @@ -309,11 +309,11 @@ private void LoadFromString() case "REM": { - var comment = clp.ReadLine(); + string comment = clp.ReadLine(); // cues don't support multiple sessions themselves, but it is common for rips to put SESSION # in REM fields // so, if we have such a REM, we'll check if the comment starts with SESSION, and interpret that as a session "command" - var trimmed = comment.Trim(); - if (trimmed.StartsWith("SESSION ", StringComparison.OrdinalIgnoreCase) && int.TryParse(trimmed.Substring(8), out var number) && number > 0) + string trimmed = comment.Trim(); + if (trimmed.StartsWith("SESSION ", StringComparison.OrdinalIgnoreCase) && int.TryParse(trimmed.Substring(8), out int number) && number > 0) { OUT_CueFile.Commands.Add(new CUE_File.Command.SESSION(number)); break; @@ -340,8 +340,8 @@ private void LoadFromString() break; } - var str_tracknum = clp.ReadToken(); - if (!int.TryParse(str_tracknum, out var tracknum) || tracknum is < 1 or > 99) + string str_tracknum = clp.ReadToken(); + if (!int.TryParse(str_tracknum, out int tracknum) || tracknum is < 1 or > 99) { Error($"Invalid TRACK number: {str_tracknum}"); break; @@ -350,7 +350,7 @@ private void LoadFromString() // TODO - check sequentiality? maybe as a warning CueTrackType tt; - var str_trackType = clp.ReadToken(); + string str_trackType = clp.ReadToken(); switch (str_trackType.ToUpperInvariant()) { default: @@ -374,7 +374,7 @@ private void LoadFromString() if (!clp.EOF) { - var remainder = clp.ReadLine(); + string remainder = clp.ReadLine(); if (remainder.TrimStart().StartsWith(';')) { //add a comment diff --git a/src/BizHawk.Emulation.DiscSystem/DiscFormats/CUE/CUE_SynthExtras.cs b/src/BizHawk.Emulation.DiscSystem/DiscFormats/CUE/CUE_SynthExtras.cs index b42e494af05..5fbce0fb3e2 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscFormats/CUE/CUE_SynthExtras.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscFormats/CUE/CUE_SynthExtras.cs @@ -12,7 +12,7 @@ internal class SS_Mode2_Form1_2048 : SS_Base { public override void Synth(SectorSynthJob job) { - var ecm = (job.Parts & ESectorSynthPart.ECMAny) != 0; + bool ecm = (job.Parts & ESectorSynthPart.ECMAny) != 0; if (ecm) { // ecm needs these parts for synth diff --git a/src/BizHawk.Emulation.DiscSystem/DiscFormats/CUE/CUE_Synths.cs b/src/BizHawk.Emulation.DiscSystem/DiscFormats/CUE/CUE_Synths.cs index 299ddd5e8dc..fd595ba5e39 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscFormats/CUE/CUE_Synths.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscFormats/CUE/CUE_Synths.cs @@ -53,7 +53,7 @@ internal class SS_Mode1_2048 : SS_Base { public override void Synth(SectorSynthJob job) { - var ecm = (job.Parts & ESectorSynthPart.ECMAny) != 0; + bool ecm = (job.Parts & ESectorSynthPart.ECMAny) != 0; if (ecm) { // ecm needs these parts for synth @@ -123,7 +123,7 @@ public override void Synth(SectorSynthJob job) Array.Clear(job.DestBuffer2448, job.DestOffset, 2352); byte mode = 255; - var form = -1; + int form = -1; switch (TrackType) { case CueTrackType.Audio: diff --git a/src/BizHawk.Emulation.DiscSystem/DiscFormats/CUE/CueFileResolver.cs b/src/BizHawk.Emulation.DiscSystem/DiscFormats/CUE/CueFileResolver.cs index e5b83baf6d7..94eebb36dfb 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscFormats/CUE/CueFileResolver.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscFormats/CUE/CueFileResolver.cs @@ -46,7 +46,7 @@ public void SetHardcodeResolve(IDictionary hardcodes) { IsHardcodedResolve = true; fisBaseDir = new MyFileInfo[hardcodes.Count]; - var i = 0; + int i = 0; foreach (var kvp in hardcodes) { fisBaseDir[i++] = new() { FullName = kvp.Key, FileInfo = new(kvp.Value) }; @@ -55,8 +55,8 @@ public void SetHardcodeResolve(IDictionary hardcodes) private MyFileInfo[] MyFileInfosFromFileInfos(FileInfo[] fis) { - var myfis = new MyFileInfo[fis.Length]; - for (var i = 0; i < fis.Length; i++) + MyFileInfo[] myfis = new MyFileInfo[fis.Length]; + for (int i = 0; i < fis.Length; i++) { myfis[i].FileInfo = fis[i]; myfis[i].FullName = fis[i].FullName; @@ -89,10 +89,10 @@ public List Resolve(string path) fileInfos = fisBaseDir; } - var results = new List(); + List results = new(); foreach (var fi in fileInfos) { - var ext = Path.GetExtension(fi.FullName).ToLowerInvariant(); + string ext = Path.GetExtension(fi.FullName).ToLowerInvariant(); //some choices are always bad: (we're looking for things like .bin and .wav) //it's a little unclear whether we should go for a whitelist or a blacklist here. @@ -106,9 +106,9 @@ public List Resolve(string path) if (ext is ".7z" or ".rar" or ".zip" or ".bz2" or ".gz") continue; - var fragment = Path.GetFileNameWithoutExtension(fi.FullName); + string fragment = Path.GetFileNameWithoutExtension(fi.FullName); //match files with differing extensions - var cmp = string.Compare(fragment, targetFragment, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase); + int cmp = string.Compare(fragment, targetFragment, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase); if (cmp != 0) //match files with another extension added on (likely to be mygame.bin.ecm) cmp = string.Compare(fragment, targetFile, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase); diff --git a/src/BizHawk.Emulation.DiscSystem/DiscFormats/M3U_file.cs b/src/BizHawk.Emulation.DiscSystem/DiscFormats/M3U_file.cs index c9cb887183e..94602062579 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscFormats/M3U_file.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscFormats/M3U_file.cs @@ -9,18 +9,18 @@ public class M3U_File { public static M3U_File Read(StreamReader sr) { - var ret = new M3U_File(); + M3U_File ret = new(); return !ret.Parse(sr) ? null : ret; } private bool Parse(StreamReader sr) { - var ext = false; - var runtime = -1; + bool ext = false; + int runtime = -1; string title = null; while (true) { - var line = sr.ReadLine(); + string line = sr.ReadLine(); if (line == null) break; if (line.StartsWith('#')) @@ -36,7 +36,7 @@ private bool Parse(StreamReader sr) if (!ext) continue; line = line.Substring(8); - var cidx = line.IndexOf(','); + int cidx = line.IndexOf(','); //don't know what to do with this, but its a comment, so ignore it if (cidx == -1) @@ -50,7 +50,7 @@ private bool Parse(StreamReader sr) continue; } - var e = new Entry + Entry e = new() { Path = line, Runtime = runtime, diff --git a/src/BizHawk.Emulation.DiscSystem/DiscFormats/MDS_Format.cs b/src/BizHawk.Emulation.DiscSystem/DiscFormats/MDS_Format.cs index 496d1514e4c..4cfd9c4240e 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscFormats/MDS_Format.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscFormats/MDS_Format.cs @@ -112,9 +112,9 @@ public class AHeader /// public AHeader Parse(Stream stream) { - var bc = EndianBitConverter.CreateForLittleEndian(); - - var header = new byte[88]; + EndianBitConverter bc = EndianBitConverter.CreateForLittleEndian(); + + byte[] header = new byte[88]; stream.Read(header, 0, 88); this.Signature = Encoding.ASCII.GetString(header.Take(16).ToArray()); @@ -305,10 +305,10 @@ public ATOCEntry(int entryNum) /// header is malformed or identifies file as MDS 2.x, or any track has a DVD mode public static AFile Parse(FileStream stream) { - var bc = EndianBitConverter.CreateForLittleEndian(); - var isDvd = false; + EndianBitConverter bc = EndianBitConverter.CreateForLittleEndian(); + bool isDvd = false; - var aFile = new AFile { MDSPath = stream.Name }; + AFile aFile = new() { MDSPath = stream.Name }; stream.Seek(0, SeekOrigin.Begin); @@ -333,16 +333,16 @@ public static AFile Parse(FileStream stream) } // parse sessions - var aSessions = new Dictionary(); + Dictionary aSessions = new(); stream.Seek(aFile.Header.SessionOffset, SeekOrigin.Begin); - for (var se = 0; se < aFile.Header.SessionCount; se++) + for (int se = 0; se < aFile.Header.SessionCount; se++) { - var sessionHeader = new byte[24]; + byte[] sessionHeader = new byte[24]; stream.Read(sessionHeader, 0, 24); //sessionHeader.Reverse().ToArray(); - var session = new ASession + ASession session = new() { SessionStart = bc.ToInt32(sessionHeader.Take(4).ToArray()), SessionEnd = bc.ToInt32(sessionHeader.Skip(4).Take(4).ToArray()), @@ -361,7 +361,7 @@ public static AFile Parse(FileStream stream) long footerOffset = 0; // parse track blocks - var aTracks = new Dictionary(); + Dictionary aTracks = new(); // iterate through each session block foreach (var session in aSessions.Values) @@ -370,10 +370,10 @@ public static AFile Parse(FileStream stream) //Dictionary sessionToc = new Dictionary(); // iterate through every block specified in each session - for (var bl = 0; bl < session.AllBlocks; bl++) + for (int bl = 0; bl < session.AllBlocks; bl++) { - var trackHeader = new byte[80]; - var track = new ATrack(); + byte[] trackHeader = new byte[80]; + ATrack track = new(); stream.Read(trackHeader, 0, 80); @@ -398,12 +398,12 @@ public static AFile Parse(FileStream stream) // check for track extra block - this can probably be handled in a separate loop, // but I'll just store the current stream position then seek forward to the extra block for this track - var currPos = stream.Position; + long currPos = stream.Position; // Only CDs have extra blocks - for DVDs ExtraOffset = track length if (track.ExtraOffset > 0 && !isDvd) { - var extHeader = new byte[8]; + byte[] extHeader = new byte[8]; stream.Seek(track.ExtraOffset, SeekOrigin.Begin); stream.Read(extHeader, 0, 8); track.ExtraBlock.Pregap = bc.ToInt32(extHeader.Take(4).ToArray()); @@ -417,18 +417,18 @@ public static AFile Parse(FileStream stream) // read the footer/filename block for this track currPos = stream.Position; - var numOfFilenames = track.Files; + long numOfFilenames = track.Files; for (long fi = 1; fi <= numOfFilenames; fi++) { // skip leadin/out info tracks if (track.FooterOffset == 0) continue; - var foot = new byte[16]; + byte[] foot = new byte[16]; stream.Seek(track.FooterOffset, SeekOrigin.Begin); stream.Read(foot, 0, 16); - var f = new AFooter + AFooter f = new() { FilenameOffset = bc.ToInt32(foot.Take(4).ToArray()), WideChar = bc.ToInt32(foot.Skip(4).Take(4).ToArray()) @@ -437,7 +437,7 @@ public static AFile Parse(FileStream stream) track.FooterBlocks = track.FooterBlocks.Distinct().ToList(); // parse the filename string - var fileName = "*.mdf"; + string fileName = "*.mdf"; if (f.FilenameOffset > 0) { // filename offset is present @@ -497,7 +497,7 @@ public static AFile Parse(FileStream stream) stream.Position = currPos; - var point = track.Point; + int point = track.Point; // each session has its own 0xA0/0xA1/0xA3 track // so this can't be used directly as a key if (point is 0xA0 or 0xA1 or 0xA2) @@ -518,7 +518,7 @@ public static AFile Parse(FileStream stream) aFile.ParsedSession = new(); foreach (var s in aSessions.Values) { - var session = new Session(); + Session session = new(); if (!aTracks.TryGetValue(s.FirstTrack, out var startTrack)) { @@ -625,14 +625,14 @@ public class LoadResults public static LoadResults LoadMDSPath(string path) { - var ret = new LoadResults { MdsPath = path }; + LoadResults ret = new() { MdsPath = path }; //ret.MdfPath = Path.ChangeExtension(path, ".mdf"); try { if (!File.Exists(path)) throw new MDSParseException("Malformed MDS format: nonexistent MDS file!"); AFile mdsf; - using (var infMDS = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) + using (FileStream infMDS = new(path, FileMode.Open, FileAccess.Read, FileShare.Read)) mdsf = Parse(infMDS); ret.ParsedMDSFile = mdsf; @@ -650,20 +650,20 @@ public static LoadResults LoadMDSPath(string path) /// path reference no longer points to file private static Dictionary MountBlobs(AFile mdsf, Disc disc) { - var BlobIndex = new Dictionary(); + Dictionary BlobIndex = new(); - var count = 0; + int count = 0; foreach (var track in mdsf.Tracks) { - foreach (var file in track.ImageFileNamePaths.Distinct()) + foreach (string file in track.ImageFileNamePaths.Distinct()) { if (!File.Exists(file)) throw new MDSParseException($"Malformed MDS format: nonexistent image file: {file}"); //mount the file - var mdfBlob = new Blob_RawFile { PhysicalPath = file }; + Blob_RawFile mdfBlob = new() { PhysicalPath = file }; - var dupe = false; + bool dupe = false; foreach (var re in disc.DisposableResources) { if (re.ToString() == mdfBlob.ToString()) @@ -685,13 +685,13 @@ private static Dictionary MountBlobs(AFile mdsf, Disc disc) private static RawTOCEntry EmitRawTOCEntry(ATOCEntry entry) { //this should actually be zero. im not sure if this is stored as BCD2 or not - var tno = BCD2.FromDecimal(entry.TrackNo); + BCD2 tno = BCD2.FromDecimal(entry.TrackNo); //these are special values.. I think, taken from this: //http://www.staff.uni-mainz.de/tacke/scsi/SCSI2-14.html //the CCD will contain Points as decimal values except for these specially converted decimal values which should stay as BCD. //Why couldn't they all be BCD? I don't know. I guess because BCD is inconvenient, but only A0 and friends have special meaning. It's confusing. - var ino = BCD2.FromDecimal(entry.Point); + BCD2 ino = BCD2.FromDecimal(entry.Point); ino.BCDValue = entry.Point switch { 0xA0 or 0xA1 or 0xA2 => (byte)entry.Point, @@ -699,11 +699,11 @@ private static RawTOCEntry EmitRawTOCEntry(ATOCEntry entry) }; // get ADR & Control from ADR_Control byte - var adrc = Convert.ToByte(entry.ADR_Control); - var Control = adrc & 0x0F; - var ADR = adrc >> 4; + byte adrc = Convert.ToByte(entry.ADR_Control); + int Control = adrc & 0x0F; + int ADR = adrc >> 4; - var q = new SubchannelQ + SubchannelQ q = new() { q_status = SubchannelQ.ComputeStatus(ADR, (EControlQ)(Control & 0xF)), q_tno = tno, @@ -728,15 +728,15 @@ public static Disc LoadMDSToDisc(string mdsPath, DiscMountPolicy IN_DiscMountPol if (!loadResults.Valid) throw loadResults.FailureException; - var disc = new Disc(); + Disc disc = new(); // load all blobs var BlobIndex = MountBlobs(loadResults.ParsedMDSFile, disc); var mdsf = loadResults.ParsedMDSFile; - + //generate DiscTOCRaw items from the ones specified in the MDS file - var curSession = 1; + int curSession = 1; disc.Sessions.Add(new() { Number = curSession }); foreach (var entry in mdsf.TOCEntries) { @@ -752,17 +752,17 @@ public static Disc LoadMDSToDisc(string mdsPath, DiscMountPolicy IN_DiscMountPol } //analyze the RAWTocEntries to figure out what type of track track 1 is - var tocSynth = new Synthesize_DiscTOC_From_RawTOCEntries_Job(disc.Session1.RawTOCEntries); + Synthesize_DiscTOC_From_RawTOCEntries_Job tocSynth = new(disc.Session1.RawTOCEntries); tocSynth.Run(); // now build the sectors - var currBlobIndex = 0; + int currBlobIndex = 0; foreach (var session in mdsf.ParsedSession) { // leadin track // we create this only for session 2+, not session 1 - var leadinSize = session.SessionSequence == 1 ? 0 : 4500; - for (var i = 0; i < leadinSize; i++) + int leadinSize = session.SessionSequence == 1 ? 0 : 4500; + for (int i = 0; i < leadinSize; i++) { // this is most certainly wrong // nothing relies on the exact contents for now (only multisession core is VirtualJaguar which doesn't touch leadin) @@ -785,9 +785,9 @@ public static Disc LoadMDSToDisc(string mdsPath, DiscMountPolicy IN_DiscMountPol }); } - for (var i = session.StartTrack; i <= session.EndTrack; i++) + for (int i = session.StartTrack; i <= session.EndTrack; i++) { - var relMSF = -1; + int relMSF = -1; var track = mdsf.TOCEntries.FirstOrDefault(t => t.Point == i); if (track == null) break; @@ -836,18 +836,18 @@ public static Disc LoadMDSToDisc(string mdsPath, DiscMountPolicy IN_DiscMountPol _ => pregapTrackType }; } - for (var pre = 0; pre < track.ExtraBlock.Pregap; pre++) + for (int pre = 0; pre < track.ExtraBlock.Pregap; pre++) { relMSF++; - var ss_gap = new CUE.SS_Gap() + CUE.SS_Gap ss_gap = new() { Policy = IN_DiscMountPolicy, TrackType = pregapTrackType }; disc._Sectors.Add(ss_gap); - var qRelMSF = pre - Convert.ToInt32(track.ExtraBlock.Pregap); + int qRelMSF = pre - Convert.ToInt32(track.ExtraBlock.Pregap); //tweak relMSF due to ambiguity/contradiction in yellowbook docs if (!IN_DiscMountPolicy.CUE_PregapContradictionModeA) @@ -866,17 +866,17 @@ public static Disc LoadMDSToDisc(string mdsPath, DiscMountPolicy IN_DiscMountPol } // pregap processing completed } - + // create track sectors - var currBlobOffset = track.TrackOffset; - for (var sector = session.StartSector; sector <= session.EndSector; sector++) + long currBlobOffset = track.TrackOffset; + for (long sector = session.StartSector; sector <= session.EndSector; sector++) { // get the current blob from the BlobIndex - var currBlob = (Blob_RawFile) BlobIndex[currBlobIndex]; - var currBlobLength = currBlob.Length; + Blob_RawFile currBlob = (Blob_RawFile) BlobIndex[currBlobIndex]; + long currBlobLength = currBlob.Length; if (sector == currBlobLength) currBlobIndex++; - var mdfBlob = (IBlob) disc.DisposableResources[currBlobIndex]; + IBlob mdfBlob = (IBlob) disc.DisposableResources[currBlobIndex]; CUE.SS_Base sBase = track.SectorSize switch { @@ -912,7 +912,7 @@ public static Disc LoadMDSToDisc(string mdsPath, DiscMountPolicy IN_DiscMountPol //http://www.staff.uni-mainz.de/tacke/scsi/SCSI2-14.html //the CCD will contain Points as decimal values except for these specially converted decimal values which should stay as BCD. //Why couldn't they all be BCD? I don't know. I guess because BCD is inconvenient, but only A0 and friends have special meaning. It's confusing. - var ino = BCD2.FromDecimal(track.Point); + BCD2 ino = BCD2.FromDecimal(track.Point); ino.BCDValue = track.Point switch { 0xA0 or 0xA1 or 0xA2 => (byte)track.Point, @@ -920,11 +920,11 @@ public static Disc LoadMDSToDisc(string mdsPath, DiscMountPolicy IN_DiscMountPol }; // get ADR & Control from ADR_Control byte - var adrc = Convert.ToByte(track.ADR_Control); - var Control = adrc & 0x0F; - var ADR = adrc >> 4; + byte adrc = Convert.ToByte(track.ADR_Control); + int Control = adrc & 0x0F; + int ADR = adrc >> 4; - var q = new SubchannelQ + SubchannelQ q = new() { q_status = SubchannelQ.ComputeStatus(ADR, (EControlQ)(Control & 0xF)), q_tno = BCD2.FromDecimal(track.Point), @@ -941,8 +941,8 @@ public static Disc LoadMDSToDisc(string mdsPath, DiscMountPolicy IN_DiscMountPol // leadout track // first leadout is 6750 sectors, later ones are 2250 sectors - var leadoutSize = session.SessionSequence == 1 ? 6750 : 2250; - for (var i = 0; i < leadoutSize; i++) + int leadoutSize = session.SessionSequence == 1 ? 6750 : 2250; + for (int i = 0; i < leadoutSize; i++) { disc._Sectors.Add(new SS_Leadout { diff --git a/src/BizHawk.Emulation.DiscSystem/DiscFormats/NRG_format.cs b/src/BizHawk.Emulation.DiscSystem/DiscFormats/NRG_format.cs index 22c9abb9fc1..083be77a598 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscFormats/NRG_format.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscFormats/NRG_format.cs @@ -361,11 +361,11 @@ private static NRGCue ParseCueChunk(string chunkID, int chunkSize, ReadOnlySpan< throw new NRGParseException("Malformed NRG format: 0 sized CUE chunk!"); } - var v2 = chunkID == "CUEX"; - var ret = new NRGCue { ChunkID = chunkID, ChunkSize = chunkSize }; - for (var i = 0; i < chunkSize; i += 8) + bool v2 = chunkID == "CUEX"; + NRGCue ret = new() { ChunkID = chunkID, ChunkSize = chunkSize }; + for (int i = 0; i < chunkSize; i += 8) { - var trackIndex = new NRGTrackIndex + NRGTrackIndex trackIndex = new() { ADRControl = chunkData[i + 0], Track = BCD2.FromBCD(chunkData[i + 1]), @@ -397,7 +397,7 @@ private static NRGDAOTrackInfo ParseDaoChunk(string chunkID, int chunkSize, Read throw new NRGParseException("Malformed NRG format: DAO chunk is less than 22 bytes!"); } - var ret = new NRGDAOTrackInfo + NRGDAOTrackInfo ret = new() { ChunkID = chunkID, ChunkSize = chunkSize, @@ -412,8 +412,8 @@ private static NRGDAOTrackInfo ParseDaoChunk(string chunkID, int chunkSize, Read LastTrack = chunkData[21], }; - var v2 = chunkID == "DAOX"; - var ntracks = ret.LastTrack - ret.FirstTrack + 1; + bool v2 = chunkID == "DAOX"; + int ntracks = ret.LastTrack - ret.FirstTrack + 1; if (ntracks <= 0 || ret.FirstTrack is < 0 or > 99 || @@ -428,9 +428,9 @@ ret.FirstTrack is < 0 or > 99 || throw new NRGParseException("Malformed NRG format: DAO chunk size does not match number of tracks!"); } - for (var i = 22; i < chunkSize; i += v2 ? 42 : 30) + for (int i = 22; i < chunkSize; i += v2 ? 42 : 30) { - var track = new NRGDAOTrack + NRGDAOTrack track = new() { Isrc = Encoding.ASCII.GetString(chunkData.Slice(i, 12)).TrimEnd('\0'), SectorSize = BinaryPrimitives.ReadUInt16BigEndian(chunkData.Slice(i + 12, sizeof(ushort))), @@ -469,7 +469,7 @@ private static NRGTAOTrackInfo ParseEtnChunk(string chunkID, int chunkSize, Read // ETNF is always a multiple of 20 // ETN2 is always a multiple of 32 - var trackSize = chunkID switch + int trackSize = chunkID switch { "TINF" => 12, "ETNF" => 20, @@ -482,15 +482,15 @@ private static NRGTAOTrackInfo ParseEtnChunk(string chunkID, int chunkSize, Read throw new NRGParseException($"Malformed NRG format: {chunkID} chunk was not a multiple of {trackSize}!"); } - var ret = new NRGTAOTrackInfo + NRGTAOTrackInfo ret = new() { ChunkID = chunkID, ChunkSize = chunkSize, }; - for (var i = 0; i < chunkSize; i += trackSize) + for (int i = 0; i < chunkSize; i += trackSize) { - var track = new NRGTAOTrack(); + NRGTAOTrack track = new(); if (chunkID == "ETN2") { @@ -586,13 +586,13 @@ private static NRGCdText ParseCdtxChunk(string chunkID, int chunkSize, ReadOnlyS // might be legal to have a 0 sized CDTX chunk? - var ret = new NRGCdText + NRGCdText ret = new() { ChunkID = chunkID, ChunkSize = chunkSize, }; - for (var i = 0; i < chunkSize; i += 18) + for (int i = 0; i < chunkSize; i += 18) { ret.CdTextPacks.Add(chunkData.Slice(i, 18).ToArray()); } @@ -626,15 +626,15 @@ private static NRGFilenames ParseAfnmChunk(string chunkID, int chunkSize, ReadOn throw new NRGParseException("Malformed NRG format: Missing null terminator in AFNM chunk!"); } - var ret = new NRGFilenames + NRGFilenames ret = new() { ChunkID = chunkID, ChunkSize = chunkSize, }; - for (var i = 0; i < chunkSize;) + for (int i = 0; i < chunkSize;) { - var j = 0; + int j = 0; while (chunkData[i + j] != 0) { j++; @@ -683,8 +683,8 @@ private static NRGEND ParseEndChunk(string chunkID, int chunkSize, ReadOnlySpan< /// malformed nrg format public static NRGFile ParseFrom(Stream stream) { - var nrgf = new NRGFile(); - using var br = new BinaryReader(stream); + NRGFile nrgf = new(); + using BinaryReader br = new(stream); try { @@ -740,8 +740,8 @@ void AssertIsV2() while (nrgf.End is null) { - var chunkID = br.ReadStringFixedUtf8(4); - var chunkSize = br.ReadInt32(); + string chunkID = br.ReadStringFixedUtf8(4); + int chunkSize = br.ReadInt32(); if (BitConverter.IsLittleEndian) { chunkSize = BinaryPrimitives.ReverseEndianness(chunkSize); @@ -754,7 +754,7 @@ void AssertIsV2() throw new NRGParseException("Malformed NRG format: Chunk size was negative!"); } - var chunkData = br.ReadBytes(chunkSize); + byte[] chunkData = br.ReadBytes(chunkSize); if (chunkData.Length != chunkSize) { @@ -840,7 +840,7 @@ void AssertIsV2() // sanity checks // SessionInfos will be empty if there is only 1 session - var nsessions = Math.Max(nrgf.SessionInfos.Count, 1); + int nsessions = Math.Max(nrgf.SessionInfos.Count, 1); if (nrgf.Cues.Count != nsessions) { @@ -894,7 +894,7 @@ public class LoadResults public static LoadResults LoadNRGPath(string path) { - var ret = new LoadResults + LoadResults ret = new() { NrgPath = path }; @@ -903,7 +903,7 @@ public static LoadResults LoadNRGPath(string path) if (!File.Exists(path)) throw new NRGParseException("Malformed NRG format: nonexistent NRG file!"); NRGFile nrgf; - using (var infNRG = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) + using (FileStream infNRG = new(path, FileMode.Open, FileAccess.Read, FileShare.Read)) nrgf = ParseFrom(infNRG); ret.ParsedNRGFile = nrgf; @@ -924,19 +924,19 @@ public static Disc LoadNRGToDisc(string nrgPath, DiscMountPolicy IN_DiscMountPol if (!loadResults.Valid) throw loadResults.FailureException; - var disc = new Disc(); + Disc disc = new(); var nrgf = loadResults.ParsedNRGFile; IBlob nrgBlob = new Blob_RawFile { PhysicalPath = nrgPath }; disc.DisposableResources.Add(nrgBlob); // SessionInfos will be empty if there is only 1 session - var nsessions = Math.Max(nrgf.SessionInfos.Count, 1); - var dao = nrgf.DAOTrackInfos.Count > 0; // tao otherwise + int nsessions = Math.Max(nrgf.SessionInfos.Count, 1); + bool dao = nrgf.DAOTrackInfos.Count > 0; // tao otherwise - for (var i = 0; i < nsessions; i++) + for (int i = 0; i < nsessions; i++) { - var session = new DiscSession { Number = i + 1 }; + DiscSession session = new() { Number = i + 1 }; int startTrack, endTrack; SessionFormat sessionFormat; @@ -953,7 +953,7 @@ public static Disc LoadNRGToDisc(string nrgPath, DiscMountPolicy IN_DiscMountPol sessionFormat = (SessionFormat)nrgf.TOCTs[i].DiskType; } - var TOCMiscInfo = new Synthesize_A0A1A2_Job( + Synthesize_A0A1A2_Job TOCMiscInfo = new( firstRecordedTrackNumber: startTrack, lastRecordedTrackNumber: endTrack, sessionFormat: sessionFormat, @@ -964,7 +964,7 @@ public static Disc LoadNRGToDisc(string nrgPath, DiscMountPolicy IN_DiscMountPol { if (trackIndex.Track.BCDValue is not (0 or 0xAA) && trackIndex.Index.BCDValue == 1) { - var q = default(SubchannelQ); + SubchannelQ q = default; q.q_status = trackIndex.ADRControl; q.q_tno = BCD2.FromBCD(0); q.q_index = trackIndex.Track; @@ -977,9 +977,9 @@ public static Disc LoadNRGToDisc(string nrgPath, DiscMountPolicy IN_DiscMountPol } // leadin track - var leadinSize = i == 0 ? 0 : 4500; - var isData = (session.RawTOCEntries.First(t => t.QData.q_index.DecimalValue == startTrack).QData.ADR & 4) != 0; - for (var j = 0; j < leadinSize; j++) + int leadinSize = i == 0 ? 0 : 4500; + bool isData = (session.RawTOCEntries.First(t => t.QData.q_index.DecimalValue == startTrack).QData.ADR & 4) != 0; + for (int j = 0; j < leadinSize; j++) { // this is most certainly wrong // nothing relies on the exact contents for now (only multisession core is VirtualJaguar which doesn't touch leadin) @@ -1018,16 +1018,16 @@ static SS_Base CreateSynth(int mode) if (dao) { var tracks = nrgf.DAOTrackInfos[i].Tracks; - for (var j = 0; j < tracks.Count; j++) + for (int j = 0; j < tracks.Count; j++) { var track = nrgf.DAOTrackInfos[i].Tracks[j]; - var relMSF = -(track.TrackStartFileOffset - track.PregapFileOffset) / track.SectorSize; - var trackNumBcd = BCD2.FromDecimal(startTrack + j); + long relMSF = -(track.TrackStartFileOffset - track.PregapFileOffset) / track.SectorSize; + BCD2 trackNumBcd = BCD2.FromDecimal(startTrack + j); var cueIndexes = nrgf.Cues[i].TrackIndices.Where(t => t.Track == trackNumBcd).ToArray(); // do the pregap var pregapCueIndex = cueIndexes[0]; - for (var k = track.PregapFileOffset; k < track.TrackStartFileOffset; k += track.SectorSize) + for (long k = track.PregapFileOffset; k < track.TrackStartFileOffset; k += track.SectorSize) { var synth = CreateSynth(track.Mode); synth.Blob = nrgBlob; @@ -1048,8 +1048,8 @@ static SS_Base CreateSynth(int mode) } // actual data - var curIndex = 1; - for (var k = track.TrackStartFileOffset; k < track.TrackEndFileOffset; k += track.SectorSize) + int curIndex = 1; + for (long k = track.TrackStartFileOffset; k < track.TrackEndFileOffset; k += track.SectorSize) { if (curIndex + 1 != cueIndexes.Length && disc._Sectors.Count == cueIndexes[curIndex + 1].LBA + 150) { @@ -1081,8 +1081,8 @@ static SS_Base CreateSynth(int mode) // leadout track // first leadout is 6750 sectors, later ones are 2250 sectors - var leadoutSize = i == 0 ? 6750 : 2250; - for (var j = 0; j < leadoutSize; j++) + int leadoutSize = i == 0 ? 6750 : 2250; + for (int j = 0; j < leadoutSize; j++) { disc._Sectors.Add(new SS_Leadout { diff --git a/src/BizHawk.Emulation.DiscSystem/DiscFormats/SBI_format.cs b/src/BizHawk.Emulation.DiscSystem/DiscFormats/SBI_format.cs index 5b38a77cf11..4df9080c90e 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscFormats/SBI_format.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscFormats/SBI_format.cs @@ -35,8 +35,8 @@ public static class SBIFormat public static bool QuickCheckISSBI(string path) { using var fs = File.OpenRead(path); - var br = new BinaryReader(fs); - var sig = br.ReadStringFixedUtf8(4); + BinaryReader br = new(fs); + string sig = br.ReadStringFixedUtf8(4); return sig == "SBI\0"; } } diff --git a/src/BizHawk.Emulation.DiscSystem/DiscHasher.cs b/src/BizHawk.Emulation.DiscSystem/DiscHasher.cs index d2d7f0d2d2c..2bc2d9f9a12 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscHasher.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscHasher.cs @@ -26,9 +26,9 @@ public string Calculate_PSX_BizIDHash() //but it will help detect dumps with mangled TOCs which are all too common CRC32 crc = new(); - var buffer2352 = new byte[2352]; + byte[] buffer2352 = new byte[2352]; - var dsr = new DiscSectorReader(disc) + DiscSectorReader dsr = new(disc) { Policy = { DeterministicClearBuffer = false } // live dangerously }; @@ -40,7 +40,7 @@ static void AddAsBytesTo(CRC32 crc32, int i) AddAsBytesTo(crc, (int)disc.TOC.SessionFormat); AddAsBytesTo(crc, disc.TOC.FirstRecordedTrackNumber); AddAsBytesTo(crc, disc.TOC.LastRecordedTrackNumber); - for (var i = 1; i <= 100; i++) + for (int i = 1; i <= 100; i++) { //if (disc.TOC.TOCItems[i].Exists) Console.WriteLine("{0:X8} {1:X2} {2:X2} {3:X8}", crc.Current, (int)disc.TOC.TOCItems[i].Control, disc.TOC.TOCItems[i].Exists ? 1 : 0, disc.TOC.TOCItems[i].LBATimestamp.Sector); //a little debugging AddAsBytesTo(crc, (int)disc.TOC.TOCItems[i].Control); @@ -49,7 +49,7 @@ static void AddAsBytesTo(CRC32 crc32, int i) } //hash first 26 sectors - for (var i = 0; i < 26; i++) + for (int i = 0; i < 26; i++) { dsr.ReadLBA_2352(i, buffer2352, 0); crc.Add(buffer2352); @@ -64,16 +64,16 @@ static void AddAsBytesTo(CRC32 crc32, int i) public uint Calculate_PSX_RedumpHash() { CRC32 crc = new(); - var buffer2352 = new byte[2352]; + byte[] buffer2352 = new byte[2352]; - var dsr = new DiscSectorReader(disc) + DiscSectorReader dsr = new(disc) { Policy = { DeterministicClearBuffer = false } // live dangerously }; //read all sectors for redump hash - for (var i = 0; i < disc.Session1.LeadoutLBA; i++) + for (int i = 0; i < disc.Session1.LeadoutLBA; i++) { dsr.ReadLBA_2352(i, buffer2352, 0); crc.Add(buffer2352); @@ -87,15 +87,15 @@ public uint Calculate_PSX_RedumpHash() //TODO - this is a very platform-specific thing. hashing the TOC may be faster and be just as effective. so, rename it appropriately public string OldHash() { - var buffer = new byte[512 * 2352]; - var dsr = new DiscSectorReader(disc); + byte[] buffer = new byte[512 * 2352]; + DiscSectorReader dsr = new(disc); foreach (var track in disc.Session1.Tracks) { if (track.IsAudio) continue; - var lba_len = Math.Min(track.NextTrack.LBA, 512); - for (var s = 0; s < 512 && s < lba_len; s++) + int lba_len = Math.Min(track.NextTrack.LBA, 512); + for (int s = 0; s < 512 && s < lba_len; s++) dsr.ReadLBA_2352(track.LBA + s, buffer, s * 2352); return MD5Checksum.ComputeDigestHex(buffer.AsSpan(start: 0, length: lba_len * 2352)); diff --git a/src/BizHawk.Emulation.DiscSystem/DiscIdentifier.cs b/src/BizHawk.Emulation.DiscSystem/DiscIdentifier.cs index 80a14f51e8f..4f510f8ea55 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscIdentifier.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscIdentifier.cs @@ -189,8 +189,8 @@ public DiscType DetectDiscType() if (_disc.TOC.SessionFormat == SessionFormat.Type20_CDXA) discView = EDiscStreamView.DiscStreamView_Mode2_Form1_2048; - var iso = new ISOFile(); - var isIso = iso.Parse(new DiscStream(_disc, discView, 0)); + ISOFile iso = new(); + bool isIso = iso.Parse(new DiscStream(_disc, discView, 0)); if (!isIso) { @@ -211,8 +211,8 @@ public DiscType DetectDiscType() return DiscType.SonyPSX; } - var appId = Encoding.ASCII.GetString(iso.VolumeDescriptors[0].ApplicationIdentifier).TrimEnd('\0', ' '); - var sysId = Encoding.ASCII.GetString(iso.VolumeDescriptors[0].SystemIdentifier).TrimEnd('\0', ' '); + string appId = Encoding.ASCII.GetString(iso.VolumeDescriptors[0].ApplicationIdentifier).TrimEnd('\0', ' '); + string sysId = Encoding.ASCII.GetString(iso.VolumeDescriptors[0].SystemIdentifier).TrimEnd('\0', ' '); //for example: PSX magical drop F (JP SLPS_02337) doesn't have the correct iso PVD fields //but, some PSX games (junky rips) don't have the 'licensed by string' so we'll hope they get caught here @@ -256,18 +256,12 @@ public DiscType DetectDiscType() /// /// This is reasonable approach to ID saturn. /// - private bool DetectSegaSaturn() - { - return StringAt("SEGA SEGASATURN", 0); - } + private bool DetectSegaSaturn() => StringAt("SEGA SEGASATURN", 0); /// /// probably wrong /// - private bool DetectMegaCD() - { - return StringAt("SEGADISCSYSTEM", 0) || StringAt("SEGADISCSYSTEM", 16); - } + private bool DetectMegaCD() => StringAt("SEGADISCSYSTEM", 0) || StringAt("SEGADISCSYSTEM", 16); private bool DetectPSX() { @@ -282,7 +276,7 @@ private bool DetectPSX() private bool DetectPCFX() { var toc = _disc.TOC; - for (var t = toc.FirstRecordedTrackNumber; + for (int t = toc.FirstRecordedTrackNumber; t <= toc.LastRecordedTrackNumber; t++) { @@ -311,8 +305,8 @@ private bool DetectTurboGECD() if (!StringAt("CD001", 0x1, 0x10)) return false; - var sector20 = ReadDataSectorCached(20); - var zecrc = CRC32.Calculate(sector20); + byte[] sector20 = ReadDataSectorCached(20); + uint zecrc = CRC32.Calculate(sector20); //known_crcs return zecrc is 0xd7b47c06 // AV Tanjou @@ -327,7 +321,7 @@ or 0xc8d1b5ef // CD Bishoujo [...] private bool DetectTurboCD() { var toc = _disc.TOC; - for (var t = toc.FirstRecordedTrackNumber; + for (int t = toc.FirstRecordedTrackNumber; t <= toc.LastRecordedTrackNumber; t++) { @@ -342,7 +336,7 @@ private bool DetectTurboCD() private bool Detect3DO() { var toc = _disc.TOC; - for (var t = toc.FirstRecordedTrackNumber; + for (int t = toc.FirstRecordedTrackNumber; t <= toc.LastRecordedTrackNumber; t++) { @@ -356,7 +350,7 @@ private bool Detect3DO() //asni - slightly longer running than the others due to its brute-force nature. Should run later in the method private bool DetectDreamcast() { - for (var i = 0; i < 1000; i++) + for (int i = 0; i < 1000; i++) { if (SectorContains("segakatana", i)) return true; @@ -365,18 +359,15 @@ private bool DetectDreamcast() return false; } - private bool DetectCDi() - { - return StringAt("CD-RTOS", 8, 16); - } + private bool DetectCDi() => StringAt("CD-RTOS", 8, 16); private bool DetectGameCube() { - var data = ReadDataSectorCached(0); + byte[] data = ReadDataSectorCached(0); if (data == null) return false; - var magic = data.Skip(28).Take(4).ToArray(); - var hexString = ""; - foreach (var b in magic) + byte[] magic = data.Skip(28).Take(4).ToArray(); + string hexString = ""; + foreach (byte b in magic) hexString += b.ToString("X2"); return hexString == "C2339F3D"; @@ -384,11 +375,11 @@ private bool DetectGameCube() private bool DetectWii() { - var data = ReadDataSectorCached(0); + byte[] data = ReadDataSectorCached(0); if (data == null) return false; - var magic = data.Skip(24).Take(4).ToArray(); - var hexString = ""; - foreach (var b in magic) + byte[] magic = data.Skip(24).Take(4).ToArray(); + string hexString = ""; + foreach (byte b in magic) hexString += b.ToString("X2"); return hexString == "5D1C9EA3"; @@ -402,11 +393,11 @@ private bool DetectJaguarCD() // The core will fixup byteswapped dumps internally if (_disc.Sessions.Count > 2 && !_disc.Sessions[2].TOC.TOCItems[_disc.Sessions[2].TOC.FirstRecordedTrackNumber].IsData) { - var data = new byte[2352]; - for (var i = 0; i < 2; i++) + byte[] data = new byte[2352]; + for (int i = 0; i < 2; i++) { _dsr.ReadLBA_2352(_disc.Sessions[2].Tracks[1].LBA + i, data, 0); - var s = Encoding.ASCII.GetString(data); + string s = Encoding.ASCII.GetString(data); if (s.Contains("ATARI APPROVED DATA HEADER ATRI") || s.Contains("TARA IPARPVODED TA AEHDAREA RT")) { return true; @@ -415,7 +406,7 @@ private bool DetectJaguarCD() // special case, Caves of Fear has the header 27 sectors in _dsr.ReadLBA_2352(_disc.Sessions[2].Tracks[1].LBA + 27, data, 0); - var ss = Encoding.ASCII.GetString(data); + string ss = Encoding.ASCII.GetString(data); if (ss.Contains("ATARI APPROVED DATA HEADER ATRI") || ss.Contains("TARA IPARPVODED TA AEHDAREA RT")) { return true; @@ -430,10 +421,10 @@ private byte[] ReadDataSectorCached(int lba) //read it if we don't have it cached //we wont be caching very much here, it's no big deal //identification is not something we want to take a long time - if (!_sectorCache.TryGetValue(lba, out var data)) + if (!_sectorCache.TryGetValue(lba, out byte[] data)) { data = new byte[2048]; - var read = _dsr.ReadLBA_2048(lba, data, 0); + int read = _dsr.ReadLBA_2048(lba, data, 0); if (read != 2048) return null; _sectorCache[lba] = data; @@ -443,17 +434,17 @@ private byte[] ReadDataSectorCached(int lba) private bool StringAt(string s, int offset, int lba = 0) { - var data = ReadDataSectorCached(lba); + byte[] data = ReadDataSectorCached(lba); if (data == null) return false; - var cmp = Encoding.ASCII.GetBytes(s); - var cmp2 = new byte[cmp.Length]; + byte[] cmp = Encoding.ASCII.GetBytes(s); + byte[] cmp2 = new byte[cmp.Length]; Buffer.BlockCopy(data, offset, cmp2, 0, cmp.Length); return cmp.SequenceEqual(cmp2); } private bool SectorContains(string s, int lba = 0) { - var data = ReadDataSectorCached(lba); + byte[] data = ReadDataSectorCached(lba); return data != null && Encoding.ASCII.GetString(data).Contains(s, StringComparison.OrdinalIgnoreCase); } } diff --git a/src/BizHawk.Emulation.DiscSystem/DiscJob.cs b/src/BizHawk.Emulation.DiscSystem/DiscJob.cs index 6c2c77c2cf8..0526a10db85 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscJob.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscJob.cs @@ -12,12 +12,12 @@ public abstract class DiscJob { internal int CurrentLine = -1; - internal StringWriter swLog = new StringWriter(); - internal void Warn(string format, params object[] args) { Log("WARN ", format, args); } + internal StringWriter swLog = new(); + internal void Warn(string format, params object[] args) => Log("WARN ", format, args); internal void Error(string format, params object[] args) { OUT_ErrorLevel = true; Log("ERROR", format, args); } internal void Log(string level, string format, params object[] args) { - var msg = string.Format(format, args); + string msg = string.Format(format, args); if (CurrentLine == -1) swLog.WriteLine("{0}: {1}", level, msg); else diff --git a/src/BizHawk.Emulation.DiscSystem/DiscMountJob.MednaDisc.cs b/src/BizHawk.Emulation.DiscSystem/DiscMountJob.MednaDisc.cs index 55e0d1099f4..2c4bf5d41de 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscMountJob.MednaDisc.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscMountJob.MednaDisc.cs @@ -19,22 +19,22 @@ public void Synth(SectorSynthJob job) private void RunMednaDisc() { - var disc = new Disc(); + Disc disc = new(); OUT_Disc = disc; //create a MednaDisc and give it to the disc for ownership - var md = new MednaDisc(IN_FromPath); + MednaDisc md = new(IN_FromPath); disc.DisposableResources.Add(md); //"length of disc" for BizHawk's purposes (NOT a robust concept!) is determined by beginning of leadout track var m_leadoutTrack = md.TOCTracks[100]; - var nSectors = (int)m_leadoutTrack.lba; + int nSectors = (int)m_leadoutTrack.lba; //make synth param memos disc.SynthParams.MednaDisc = md; //this is the sole sector synthesizer we'll need - var synth = new SS_MednaDisc(); + SS_MednaDisc synth = new(); OUT_Disc.SynthProvider = new SimpleSectorSynthProvider { SS = synth }; //ADR (q-Mode) is necessarily 0x01 for a RawTOCEntry @@ -50,7 +50,7 @@ private void RunMednaDisc() //entry[0] is placeholder junk, not to be used //entry[100] is the leadout track (A0) //A1 and A2 are in the form of FirstRecordedTrackNumber and LastRecordedTrackNumber - for (var i = 1; i < 101; i++) + for (int i = 1; i < 101; i++) { var m_te = md.TOCTracks[i]; @@ -58,9 +58,9 @@ private void RunMednaDisc() if (!m_te.Valid) continue; - var m_ts = new Timestamp((int)m_te.lba + 150); //these are supposed to be absolute timestamps + Timestamp m_ts = new((int)m_te.lba + 150); //these are supposed to be absolute timestamps - var q = new SubchannelQ + SubchannelQ q = new() { q_status = SubchannelQ.ComputeStatus(kADR, (EControlQ) m_te.control), q_tno = BCD2.FromDecimal(0), //unknown with mednadisc @@ -85,7 +85,7 @@ private void RunMednaDisc() } // synth A0 and A1 entries (indicating first and last recorded tracks and also session type) - var qA0 = new SubchannelQ + SubchannelQ qA0 = new() { q_status = SubchannelQ.ComputeStatus(kADR, kUnknownControl), q_tno = BCD2.FromDecimal(0), //unknown with mednadisc @@ -100,7 +100,7 @@ private void RunMednaDisc() q_crc = 0, //meaningless }; disc.Session1.RawTOCEntries.Add(new() { QData = qA0 }); - var qA1 = new SubchannelQ + SubchannelQ qA1 = new() { q_status = SubchannelQ.ComputeStatus(kADR, kUnknownControl), q_tno = BCD2.FromDecimal(0), //unknown with mednadisc diff --git a/src/BizHawk.Emulation.DiscSystem/DiscMountJob.cs b/src/BizHawk.Emulation.DiscSystem/DiscMountJob.cs index fc0387d96b0..9421276891b 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscMountJob.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscMountJob.cs @@ -80,15 +80,15 @@ public override void Run() OUT_Disc.Name = Path.GetFileName(IN_FromPath); //generate toc and session tracks: - for (var i = 1; i < OUT_Disc.Sessions.Count; i++) + for (int i = 1; i < OUT_Disc.Sessions.Count; i++) { var session = OUT_Disc.Sessions[i]; //1. TOC from RawTOCEntries - var tocSynth = new Synthesize_DiscTOC_From_RawTOCEntries_Job(session.RawTOCEntries); + Synthesize_DiscTOC_From_RawTOCEntries_Job tocSynth = new(session.RawTOCEntries); tocSynth.Run(); session.TOC = tocSynth.Result; //2. DiscTracks from TOC - var tracksSynth = new Synthesize_DiscTracks_From_DiscTOC_Job(OUT_Disc, session); + Synthesize_DiscTracks_From_DiscTOC_Job tracksSynth = new(OUT_Disc, session); tracksSynth.Run(); } @@ -98,7 +98,7 @@ public override void Run() //(although note only VirtualJaguar currently deals with multisession discs and it doesn't care about the leadout so far) if (IN_DiscInterface != DiscInterface.MednaDisc) { - var ss_leadout = new SS_Leadout + SS_Leadout ss_leadout = new() { SessionNumber = OUT_Disc.Sessions.Count - 1, Policy = IN_DiscMountPolicy @@ -108,12 +108,12 @@ public override void Run() } //apply SBI if it exists - var sbiPath = Path.ChangeExtension(IN_FromPath, ".sbi"); + string sbiPath = Path.ChangeExtension(IN_FromPath, ".sbi"); if (File.Exists(sbiPath) && SBI.SBIFormat.QuickCheckISSBI(sbiPath)) { - var loadSbiJob = new SBI.LoadSBIJob(sbiPath); + SBI.LoadSBIJob loadSbiJob = new(sbiPath); loadSbiJob.Run(); - var applySbiJob = new ApplySBIJob(); + ApplySBIJob applySbiJob = new(); applySbiJob.Run(OUT_Disc, loadSbiJob.OUT_Data, IN_DiscMountPolicy.SBI_As_Mednafen); } } @@ -129,14 +129,14 @@ void LoadCue(string cueDirPath, string cueContent) //TODO make sure code is designed so no matter what happens, a disc is disposed in case of errors. // perhaps the CUE_Format2 (once renamed to something like Context) can handle that - var cfr = new CueFileResolver(); - var cueContext = new CUE_Context { DiscMountPolicy = IN_DiscMountPolicy, Resolver = cfr }; + CueFileResolver cfr = new(); + CUE_Context cueContext = new() { DiscMountPolicy = IN_DiscMountPolicy, Resolver = cfr }; if (!cfr.IsHardcodedResolve) cfr.SetBaseDirectory(cueDirPath); // parse the cue file - var parseJob = new ParseCueJob(cueContent); - var okParse = true; + ParseCueJob parseJob = new(cueContent); + bool okParse = true; try { parseJob.Run(); @@ -152,8 +152,8 @@ void LoadCue(string cueDirPath, string cueContent) // compile the cue file // includes resolving required bin files and finding out what would processing would need to happen in order to load the cue - var compileJob = new CompileCueJob(parseJob.OUT_CueFile, cueContext); - var okCompile = true; + CompileCueJob compileJob = new(parseJob.OUT_CueFile, cueContext); + bool okCompile = true; try { compileJob.Run(); @@ -176,7 +176,7 @@ void LoadCue(string cueDirPath, string cueContent) } // actually load it all up - var loadJob = new LoadCueJob(compileJob); + LoadCueJob loadJob = new(compileJob); loadJob.Run(); //TODO need better handling of log output if (!string.IsNullOrEmpty(loadJob.OUT_Log)) Console.WriteLine(loadJob.OUT_Log); @@ -225,7 +225,7 @@ public static string GenerateCue(string binFilename, bool isMode2) public static string GenerateCue(string binFilename, string binFilePath) { - var len = new FileInfo(binFilePath).Length; + long len = new FileInfo(binFilePath).Length; return GenerateCue(binFilename, isMode2: len % 2048 is not 0 && len % 2352 is 0); } diff --git a/src/BizHawk.Emulation.DiscSystem/DiscSectorReader.cs b/src/BizHawk.Emulation.DiscSystem/DiscSectorReader.cs index 79c2fbdaf9b..11b18e19bbf 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscSectorReader.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscSectorReader.cs @@ -56,7 +56,7 @@ public enum EUserData2048Mode /// public class DiscSectorReader { - public DiscSectorReaderPolicy Policy = new DiscSectorReaderPolicy(); + public DiscSectorReaderPolicy Policy = new(); private readonly Disc disc; @@ -299,6 +299,6 @@ public int ReadLBA_Mode(int lba) //lets not try to these as a sector cache. it gets too complicated. its just a temporary variable. private readonly byte[] buf2442 = new byte[2448]; private readonly byte[] buf12 = new byte[12]; - private readonly SectorSynthJob job = new SectorSynthJob(); + private readonly SectorSynthJob job = new(); } } \ No newline at end of file diff --git a/src/BizHawk.Emulation.DiscSystem/DiscSession.cs b/src/BizHawk.Emulation.DiscSystem/DiscSession.cs index 935b7385469..ef34044e228 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscSession.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscSession.cs @@ -73,7 +73,7 @@ public DiscTrack SeekTrack(int lba) { var ses = this; - for (var i = 1; i < Tracks.Count; i++) + for (int i = 1; i < Tracks.Count; i++) { var track = ses.Tracks[i]; //funny logic here: if the current track's LBA is > the requested track number, it means the previous track is the one we wanted diff --git a/src/BizHawk.Emulation.DiscSystem/DiscStream.cs b/src/BizHawk.Emulation.DiscSystem/DiscStream.cs index ef9dda3f8a4..300c6b3f760 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscStream.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscStream.cs @@ -53,7 +53,7 @@ public class DiscStream : System.IO.Stream { private readonly int SectorSize; private readonly int NumSectors; - private Disc Disc; + private readonly Disc Disc; private long currPosition; private readonly byte[] cachedSectorBuffer; @@ -69,19 +69,12 @@ public DiscStream(Disc disc, EDiscStreamView view, int from_lba) dsr = new(disc); //following the provided view - switch (view) + dsr.Policy.UserData2048Mode = view switch { - case EDiscStreamView.DiscStreamView_Mode1_2048: - dsr.Policy.UserData2048Mode = DiscSectorReaderPolicy.EUserData2048Mode.AssumeMode1; - break; - case EDiscStreamView.DiscStreamView_Mode2_Form1_2048: - dsr.Policy.UserData2048Mode = DiscSectorReaderPolicy.EUserData2048Mode.AssumeMode2_Form1; - break; - default: - throw new NotSupportedException($"Unsupported {nameof(EDiscStreamView)}"); - } - - + EDiscStreamView.DiscStreamView_Mode1_2048 => DiscSectorReaderPolicy.EUserData2048Mode.AssumeMode1, + EDiscStreamView.DiscStreamView_Mode2_Form1_2048 => DiscSectorReaderPolicy.EUserData2048Mode.AssumeMode2_Form1, + _ => throw new NotSupportedException($"Unsupported {nameof(EDiscStreamView)}"), + }; currPosition = from_lba * SectorSize; cachedSector = -1; cachedSectorBuffer = new byte[SectorSize]; @@ -90,7 +83,7 @@ public DiscStream(Disc disc, EDiscStreamView view, int from_lba) public override bool CanRead => true; public override bool CanSeek => true; public override bool CanWrite => false; - public override void Flush() { throw new NotImplementedException(); } + public override void Flush() => throw new NotImplementedException(); public override long Length => NumSectors * SectorSize; public override long Position @@ -114,18 +107,18 @@ internal void READLBA_Flat_Implementation(long disc_offset, byte[] buffer, int o //TODO - I'm not sure everything in here makes sense right now.. public override int Read(byte[] buffer, int offset, int count) { - var remainInDisc = Length - currPosition; + long remainInDisc = Length - currPosition; if (count > remainInDisc) count = (int)Math.Min(remainInDisc, int.MaxValue); - var remain = count; - var readed = 0; + int remain = count; + int readed = 0; while (remain > 0) { - var lba = (int)(currPosition / SectorSize); - var lba_within = (int)(currPosition % SectorSize); - var todo = remain; - var remains_in_lba = SectorSize - lba_within; + int lba = (int)(currPosition / SectorSize); + int lba_within = (int)(currPosition % SectorSize); + int todo = remain; + int remains_in_lba = SectorSize - lba_within; if (remains_in_lba < todo) todo = remains_in_lba; if (cachedSector != lba) @@ -154,7 +147,7 @@ public override long Seek(long offset, System.IO.SeekOrigin origin) return Position; } - public override void SetLength(long value) { throw new NotImplementedException(); } - public override void Write(byte[] buffer, int offset, int count) { throw new NotImplementedException(); } + public override void SetLength(long value) => throw new NotImplementedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotImplementedException(); } } \ No newline at end of file diff --git a/src/BizHawk.Emulation.DiscSystem/DiscSubQ.cs b/src/BizHawk.Emulation.DiscSystem/DiscSubQ.cs index 8e467c388eb..d8f6f0a4c00 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscSubQ.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscSubQ.cs @@ -91,9 +91,9 @@ public struct SubchannelQ /// Retrieves the initial set of timestamps (min,sec,frac) as a convenient Timestamp /// public int Timestamp { - get => MSF.ToInt(min.DecimalValue, sec.DecimalValue, frame.DecimalValue); + readonly get => MSF.ToInt(min.DecimalValue, sec.DecimalValue, frame.DecimalValue); set { - var ts = new Timestamp(value); + Timestamp ts = new(value); min.DecimalValue = ts.MIN; sec.DecimalValue = ts.SEC; frame.DecimalValue = ts.FRAC; } } @@ -103,9 +103,9 @@ public int Timestamp { /// TODO - rename everything AP here, it's nonsense. (the P is) /// public int AP_Timestamp { - get => MSF.ToInt(ap_min.DecimalValue, ap_sec.DecimalValue, ap_frame.DecimalValue); + readonly get => MSF.ToInt(ap_min.DecimalValue, ap_sec.DecimalValue, ap_frame.DecimalValue); set { - var ts = new Timestamp(value); + Timestamp ts = new(value); ap_min.DecimalValue = ts.MIN; ap_sec.DecimalValue = ts.SEC; ap_frame.DecimalValue = ts.FRAC; } } @@ -113,28 +113,22 @@ public int AP_Timestamp { /// /// sets the status byte from the provided adr/qmode and control values /// - public void SetStatus(byte adr_or_qmode, EControlQ control) - { - q_status = ComputeStatus(adr_or_qmode, control); - } + public void SetStatus(byte adr_or_qmode, EControlQ control) => q_status = ComputeStatus(adr_or_qmode, control); /// /// computes a status byte from the provided adr/qmode and control values /// - public static byte ComputeStatus(int adr_or_qmode, EControlQ control) - { - return (byte)(adr_or_qmode | (((int)control) << 4)); - } + public static byte ComputeStatus(int adr_or_qmode, EControlQ control) => (byte)(adr_or_qmode | (((int)control) << 4)); /// /// Retrives the ADR field of the q_status member (low 4 bits) /// - public int ADR => q_status & 0xF; + public readonly int ADR => q_status & 0xF; /// /// Retrieves the CONTROL field of the q_status member (high 4 bits) /// - public EControlQ CONTROL => (EControlQ)((q_status >> 4) & 0xF); + public readonly EControlQ CONTROL => (EControlQ)((q_status >> 4) & 0xF); } } diff --git a/src/BizHawk.Emulation.DiscSystem/DiscTOC.cs b/src/BizHawk.Emulation.DiscSystem/DiscTOC.cs index 95a3bd4f60b..80e605e221f 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscTOC.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscTOC.cs @@ -36,7 +36,7 @@ public struct TOCItem /// /// Whether the Control indicates that this is data /// - public bool IsData => (Control & EControlQ.DATA) != 0; + public readonly bool IsData => (Control & EControlQ.DATA) != 0; /// /// The location of the track (Index 1) diff --git a/src/BizHawk.Emulation.DiscSystem/DiscTypes.cs b/src/BizHawk.Emulation.DiscSystem/DiscTypes.cs index 57950f38bb6..4f9fb2dda6b 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscTypes.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscTypes.cs @@ -29,20 +29,11 @@ public enum SessionFormat /// public struct BCD2 : IEquatable { - public bool Equals(BCD2 other) - { - return BCDValue == other.BCDValue; - } + public readonly bool Equals(BCD2 other) => BCDValue == other.BCDValue; - public override bool Equals(object obj) - { - return obj is BCD2 other && Equals(other); - } + public override readonly bool Equals(object obj) => obj is BCD2 other && Equals(other); - public override int GetHashCode() - { - return BCDValue.GetHashCode(); - } + public override int GetHashCode() => BCDValue.GetHashCode(); /// /// The raw BCD value. you can't do math on this number! but you may be asked to supply it to a game program. @@ -54,8 +45,7 @@ public override int GetHashCode() /// The derived decimal value. you can do math on this! the largest number it can logically contain is 99. /// public int DecimalValue - { - get => (BCDValue & 0xF) + ((BCDValue >> 4) & 0xF) * 10; + { readonly get => (BCDValue & 0xF) + ((BCDValue >> 4) & 0xF) * 10; set => BCDValue = IntToBCD(value); } @@ -70,13 +60,13 @@ public static BCD2 FromBCD(byte b) public static int BCDToInt(byte n) { - var bcd = new BCD2 { BCDValue = n }; + BCD2 bcd = new() { BCDValue = n }; return bcd.DecimalValue; } public static byte IntToBCD(int n) { - var tens = Math.DivRem(n, 10, out var ones); + int tens = Math.DivRem(n, 10, out int ones); return (byte)((tens << 4) | ones); } @@ -106,10 +96,7 @@ public readonly struct Timestamp /// /// Checks if the string is a legit MSF. It's strict. /// - public static bool IsMatch(string str) - { - return new Timestamp(str).Valid; - } + public static bool IsMatch(string str) => new Timestamp(str).Valid; public readonly byte MIN; @@ -131,14 +118,14 @@ public Timestamp(string str) Valid = false; if (str.Length != 8) return; - if (str[0] < '0' || str[0] > '9') return; - if (str[1] < '0' || str[1] > '9') return; + if (str[0] is < '0' or > '9') return; + if (str[1] is < '0' or > '9') return; if (str[2] != ':') return; - if (str[3] < '0' || str[3] > '9') return; - if (str[4] < '0' || str[4] > '9') return; + if (str[3] is < '0' or > '9') return; + if (str[4] is < '0' or > '9') return; if (str[5] != ':') return; - if (str[6] < '0' || str[6] > '9') return; - if (str[7] < '0' || str[7] > '9') return; + if (str[6] is < '0' or > '9') return; + if (str[7] is < '0' or > '9') return; Valid = true; MIN = (byte)((str[0] - '0') * 10 + (str[1] - '0')); diff --git a/src/BizHawk.Emulation.DiscSystem/DiscUtils.cs b/src/BizHawk.Emulation.DiscSystem/DiscUtils.cs index deb5ce6a905..2a09663d26e 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscUtils.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscUtils.cs @@ -4,18 +4,20 @@ namespace BizHawk.Emulation.DiscSystem { public static class DiscUtils { + #pragma warning disable IDE0051 private static byte IntToBCD(int n) { - var tens = Math.DivRem(n, 10, out var ones); + int tens = Math.DivRem(n, 10, out int ones); return (byte)((tens << 4) | ones); } + #pragma warning restore IDE0051 /// /// converts the given int to a BCD value /// public static int BCD_Byte(this int val) { - var ret = (byte)(val % 10); + byte ret = (byte)(val % 10); ret += (byte)(16 * (val / 10)); return ret; } @@ -32,9 +34,6 @@ public static void Convert_LBA_To_AMSF(int lba, out byte m, out byte s, out byte } // converts MSF to LBA offset - public static int Convert_AMSF_To_LBA(byte m, byte s, byte f) - { - return f + (s * 75) + (m * 75 * 60) - 150; - } + public static int Convert_AMSF_To_LBA(byte m, byte s, byte f) => f + (s * 75) + (m * 75 * 60) - 150; } } \ No newline at end of file diff --git a/src/BizHawk.Emulation.DiscSystem/DiscoHawkLogic/AudioExtractor.cs b/src/BizHawk.Emulation.DiscSystem/DiscoHawkLogic/AudioExtractor.cs index f2c1d03c3c8..f6254959ebb 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscoHawkLogic/AudioExtractor.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscoHawkLogic/AudioExtractor.cs @@ -11,9 +11,9 @@ public static class AudioExtractor { public static void Extract(Disc disc, string path, string fileBase, Func getOverwritePolicy) { - var dsr = new DiscSectorReader(disc); + DiscSectorReader dsr = new(disc); - var shouldHalt = false; + bool shouldHalt = false; bool? overwriteExisting = null; // true = overwrite, false = skip existing, null = unset var tracks = disc.Session1.Tracks; @@ -22,18 +22,18 @@ public static void Extract(Disc disc, string path, string fileBase, Func(); + HashSet hashedOffenders = new(); for (int i = 0; i < numOffenders; i++) { hashedOffenders.Add(offenders[i]); @@ -224,14 +224,14 @@ void SwDumpChunk(int lba, int dispAddr, int addr, int count, int numOffenders) private static List FindCuesRecurse(string dir) { - var ret = new List(); - var dpTodo = new Queue(); + List ret = new(); + Queue dpTodo = new(); dpTodo.Enqueue(dir); for (; ; ) { if (dpTodo.Count == 0) break; - var dpCurr = dpTodo.Dequeue(); + string dpCurr = dpTodo.Dequeue(); foreach(var fi in new DirectoryInfo(dpCurr).GetFiles("*.cue")) { ret.Add(fi.FullName); @@ -257,7 +257,7 @@ public static bool HawkAndWriteFile(string inputPath, Action errorCallba return false; } var (dir, baseName, _) = inputPath.SplitPathToDirFileAndExt(); - var outfile = Path.Combine(dir!, $"{baseName}_hawked.ccd"); + string outfile = Path.Combine(dir!, $"{baseName}_hawked.ccd"); CCD_Format.Dump(disc, outfile); return true; } @@ -268,7 +268,7 @@ public static void RunWithArgs(string[] args, Action showComparisonResul string dirArg = null; string infile = null; var loadDiscInterface = DiscInterface.BizHawk; - var compareDiscInterfaces = new List(); + List compareDiscInterfaces = new(); bool hawk = false; bool music = false; bool overwrite = false; @@ -311,7 +311,7 @@ public static void RunWithArgs(string[] args, Action showComparisonResul if (music) { if (infile is null) return; - using var disc = Disc.LoadAutomagic(infile); + using Disc disc = Disc.LoadAutomagic(infile); var (path, filename, _) = infile.SplitPathToDirFileAndExt(); bool? CheckOverwrite(string mp3Path) { @@ -328,12 +328,12 @@ public static void RunWithArgs(string[] args, Action showComparisonResul { verbose = false; var todo = FindCuesRecurse(dirArg); - var po = new ParallelOptions(); - var cts = new CancellationTokenSource(); + ParallelOptions po = new(); + CancellationTokenSource cts = new(); po.CancellationToken = cts.Token; po.MaxDegreeOfParallelism = 1; if(po.MaxDegreeOfParallelism < 0) po.MaxDegreeOfParallelism = 1; - object olock = new object(); + object olock = new(); int ctr=0; bool blocked = false; try @@ -351,7 +351,7 @@ public static void RunWithArgs(string[] args, Action showComparisonResul if(!blocked) foreach (var cmpif in compareDiscInterfaces) { - var sw = new StringWriter(); + StringWriter sw = new(); bool success = CompareFile(fp, loadDiscInterface, cmpif, verbose, cts, sw); if (!success) { @@ -377,7 +377,7 @@ public static void RunWithArgs(string[] args, Action showComparisonResul if (compareDiscInterfaces.Count != 0) { - var sw = new StringWriter(); + StringWriter sw = new(); foreach (var cmpif in compareDiscInterfaces) { CompareFile(infile, loadDiscInterface, cmpif, verbose, null, sw); diff --git a/src/BizHawk.Emulation.DiscSystem/DiscoHawkLogic/ECMTest.cs b/src/BizHawk.Emulation.DiscSystem/DiscoHawkLogic/ECMTest.cs index d11f8170b4a..b40abe9f445 100644 --- a/src/BizHawk.Emulation.DiscSystem/DiscoHawkLogic/ECMTest.cs +++ b/src/BizHawk.Emulation.DiscSystem/DiscoHawkLogic/ECMTest.cs @@ -16,14 +16,12 @@ static void Shuffle(IList list, Random rng) { n--; int k = rng.Next(n + 1); - T value = list[k]; - list[k] = list[n]; - list[n] = value; + (list[n], list[k]) = (list[k], list[n]); } } - var plaindisc = Disc.LoadAutomagic("d:\\ecmtest\\test.cue"); - var ecmdisc = Disc.LoadAutomagic("d:\\ecmtest\\ecmtest.cue"); + Disc plaindisc = Disc.LoadAutomagic("d:\\ecmtest\\test.cue"); + Disc ecmdisc = Disc.LoadAutomagic("d:\\ecmtest\\ecmtest.cue"); // var prefs = new CueBinPrefs // { @@ -51,15 +49,15 @@ static void Shuffle(IList list, Random rng) for (; ; ) { Console.WriteLine("running seed {0}", seed); - Random r = new Random(seed); + Random r = new(seed); seed++; byte[] chunkbuf_corlet = new byte[2352 * 20]; byte[] chunkbuf_mine = new byte[2352 * 20]; -// int length = (ecmdisc._Sectors.Count - 150) * 2352; // API has changed - var length = 0; + // int length = (ecmdisc._Sectors.Count - 150) * 2352; // API has changed + int length = 0; int counter = 0; - List> testChunks = new List>(); + List> testChunks = new(); while (counter < length) { int chunk = r.Next(1, 2352 * 20); diff --git a/src/BizHawk.Emulation.DiscSystem/Internal/Algorithms/ECM.cs b/src/BizHawk.Emulation.DiscSystem/Internal/Algorithms/ECM.cs index c47d0828c72..64a618e575d 100644 --- a/src/BizHawk.Emulation.DiscSystem/Internal/Algorithms/ECM.cs +++ b/src/BizHawk.Emulation.DiscSystem/Internal/Algorithms/ECM.cs @@ -50,11 +50,11 @@ private static void Prep_EDC() const uint edc_poly = 0x8001801B; //generate the CRC table - var reverse_edc_poly = BitReverse.Reverse32(edc_poly); + uint reverse_edc_poly = BitReverse.Reverse32(edc_poly); for (uint i = 0; i < 256; ++i) { - var crc = i; - for (var j = 8; j > 0; --j) + uint crc = i; + for (int j = 8; j > 0; --j) { if ((crc & 1) == 1) crc = ((crc >> 1) ^ reverse_edc_poly); @@ -71,10 +71,10 @@ private static void Prep_EDC() private static void Prep_ECC() { //create a table implementing f(i) = i*2 - for (var i = 0; i < 256; i++) + for (int i = 0; i < 256; i++) { - var n = i * 2; - var b = n & 0xFF; + int n = i * 2; + int b = n & 0xFF; if (n > 0xFF) b ^= 0x1D; //primitive polynomial x^8 + x^4 + x^3 + x^2 + 1 -> 0x11D mul2tab[i] = (byte)b; } @@ -89,11 +89,11 @@ private static void Prep_ECC() // System.Diagnostics.Debug.Assert(mul2tab[i] == mul2tab_B[i]); //create a table implementing f(i) = i/3 - for (var i = 0; i < 256; i++) + for (int i = 0; i < 256; i++) { - var x1 = (byte)i; - var x2 = mul2tab[i]; - var x3 = (byte)(x2 ^ x1); //2x + x = 3x + byte x1 = (byte)i; + byte x2 = mul2tab[i]; + byte x3 = (byte)(x2 ^ x1); //2x + x = 3x //instead of dividing 1/3 we write the table backwards since its the inverse of multiplying by 3 //this idea was taken from Corlett's techniques; I know not from whence they came. div3tab[x3] = x1; @@ -153,10 +153,10 @@ public static void CalcECC(byte[] data, int base_offset, int addr_offset, int ad byte pow_accum = 0; byte add_accum = 0; - for (var i = 0; i < todo; i++) + for (int i = 0; i < todo; i++) { addr_offset %= (1118 * 2); //modulo addressing is irrelevant for P-parity calculation but comes into play for Q-parity - var d = data[base_offset + addr_offset]; + byte d = data[base_offset + addr_offset]; addr_offset += addr_add; add_accum ^= d; pow_accum ^= d; @@ -185,10 +185,10 @@ public static void PokeUint(byte[] data, int offset, uint value) public static uint EDC_Calc(byte[] data, int offset, int length) { uint crc = 0; - for (var i = 0; i < length; i++) + for (int i = 0; i < length; i++) { - var b = data[offset + i]; - var entry = ((int)crc ^ b) & 0xFF; + byte b = data[offset + i]; + int entry = ((int)crc ^ b) & 0xFF; crc = edc_table[entry] ^ (crc >> 8); } @@ -226,7 +226,7 @@ private static void SetSectorAddress(byte[] sector, int sector_offset, uint addr public static void ECC_Populate(byte[] src, int src_offset, byte[] dest, int dest_offset, bool zeroSectorAddress) { //save the old sector address, so we can restore it later. SOMETIMES ECC is supposed to be calculated without it? see TODO - var address = GetSectorAddress(src, src_offset); + uint address = GetSectorAddress(src, src_offset); if (zeroSectorAddress) SetSectorAddress(src, src_offset, 0); //all further work takes place relative to offset 12 in the sector @@ -235,9 +235,9 @@ public static void ECC_Populate(byte[] src, int src_offset, byte[] dest, int des //calculate P parity for 86 columns (twice 43 word-columns) byte parity0, parity1; - for (var col = 0; col < 86; col++) + for (int col = 0; col < 86; col++) { - var offset = col; + int offset = col; CalcECC(src, src_offset, offset, 86, 24, out parity0, out parity1); //store the parities in the sector; theyre read for the Q parity calculations dest[dest_offset + 1032 * 2 + col] = parity0; @@ -246,11 +246,11 @@ public static void ECC_Populate(byte[] src, int src_offset, byte[] dest, int des //calculate Q parity for 52 diagonals (twice 26 word-diagonals) //modulo addressing is taken care of in CalcECC - for (var d = 0; d < 26; d++) + for (int d = 0; d < 26; d++) { - for (var w = 0; w < 2; w++) + for (int w = 0; w < 2; w++) { - var offset = d * 86 + w; + int offset = d * 86 + w; CalcECC(src, src_offset, offset, 88, 43, out parity0, out parity1); //store the parities in the sector; that's where theyve got to go anyway dest[dest_offset + 1118 * 2 + d * 2 + w] = parity0; diff --git a/src/BizHawk.Emulation.DiscSystem/Internal/Algorithms/SubQ_CRC.cs b/src/BizHawk.Emulation.DiscSystem/Internal/Algorithms/SubQ_CRC.cs index 2694f23a293..784fa1615de 100644 --- a/src/BizHawk.Emulation.DiscSystem/Internal/Algorithms/SubQ_CRC.cs +++ b/src/BizHawk.Emulation.DiscSystem/Internal/Algorithms/SubQ_CRC.cs @@ -12,7 +12,7 @@ static CRC16_CCITT() for (ushort i = 0; i < 256; ++i) { ushort value = 0; - var temp = (ushort)(i << 8); + ushort temp = (ushort)(i << 8); for (byte j = 0; j < 8; ++j) { if (((value ^ temp) & 0x8000) != 0) @@ -28,10 +28,10 @@ static CRC16_CCITT() public static ushort Calculate(byte[] data, int offset, int length) { ushort Result = 0; - for (var i = 0; i < length; i++) + for (int i = 0; i < length; i++) { - var b = data[offset + i]; - var index = (b ^ ((Result >> 8) & 0xFF)); + byte b = data[offset + i]; + int index = (b ^ ((Result >> 8) & 0xFF)); Result = (ushort)((Result << 8) ^ table[index]); } return Result; diff --git a/src/BizHawk.Emulation.DiscSystem/Internal/Jobs/ApplySBIJob.cs b/src/BizHawk.Emulation.DiscSystem/Internal/Jobs/ApplySBIJob.cs index 82474c9d43f..1f763cf4d11 100644 --- a/src/BizHawk.Emulation.DiscSystem/Internal/Jobs/ApplySBIJob.cs +++ b/src/BizHawk.Emulation.DiscSystem/Internal/Jobs/ApplySBIJob.cs @@ -13,17 +13,17 @@ public void Run(Disc disc, SBI.SubQPatchData sbi, bool asMednafen) //save this, it's small, and we'll want it for disc processing a/b checks disc.Memos["sbi"] = sbi; - var dsr = new DiscSectorReader(disc); + DiscSectorReader dsr = new(disc); - var n = sbi.ABAs.Count; - var b = 0; - for (var i = 0; i < n; i++) + int n = sbi.ABAs.Count; + int b = 0; + for (int i = 0; i < n; i++) { - var lba = sbi.ABAs[i] - 150; + int lba = sbi.ABAs[i] - 150; //create a synthesizer which can return the patched data - var ss_patchq = new SS_PatchQ { Original = disc._Sectors[lba + 150] }; - var subQbuf = ss_patchq.Buffer_SubQ; + SS_PatchQ ss_patchq = new() { Original = disc._Sectors[lba + 150] }; + byte[] subQbuf = ss_patchq.Buffer_SubQ; //read the old subcode dsr.ReadLBA_SubQ(lba, subQbuf, 0); @@ -32,9 +32,9 @@ public void Run(Disc disc, SBI.SubQPatchData sbi, bool asMednafen) disc._Sectors[lba + 150] = ss_patchq; //apply SBI patch - for (var j = 0; j < 12; j++) + for (int j = 0; j < 12; j++) { - var patch = sbi.subq[b++]; + short patch = sbi.subq[b++]; if (patch == -1) continue; subQbuf[j] = (byte)patch; } diff --git a/src/BizHawk.Emulation.DiscSystem/Internal/Jobs/LoadSBIJob.cs b/src/BizHawk.Emulation.DiscSystem/Internal/Jobs/LoadSBIJob.cs index 0a7c67763c4..564af2239a1 100644 --- a/src/BizHawk.Emulation.DiscSystem/Internal/Jobs/LoadSBIJob.cs +++ b/src/BizHawk.Emulation.DiscSystem/Internal/Jobs/LoadSBIJob.cs @@ -24,13 +24,13 @@ internal class LoadSBIJob : DiscJob public override void Run() { using var fs = File.OpenRead(IN_Path); - var br = new BinaryReader(fs); - var sig = br.ReadStringFixedUtf8(4); + BinaryReader br = new(fs); + string sig = br.ReadStringFixedUtf8(4); if (sig != "SBI\0") throw new SBIParseException("Missing magic number"); - var ret = new SubQPatchData(); - var bytes = new List(); + SubQPatchData ret = new(); + List bytes = new(); //read records until done for (; ; ) @@ -40,30 +40,30 @@ public override void Run() break; if (fs.Position + 4 > fs.Length) throw new SBIParseException("Broken record"); - var m = BCD2.BCDToInt(br.ReadByte()); - var s = BCD2.BCDToInt(br.ReadByte()); - var f = BCD2.BCDToInt(br.ReadByte()); - var ts = new Timestamp(m, s, f); + int m = BCD2.BCDToInt(br.ReadByte()); + int s = BCD2.BCDToInt(br.ReadByte()); + int f = BCD2.BCDToInt(br.ReadByte()); + Timestamp ts = new(m, s, f); ret.ABAs.Add(ts.Sector); int type = br.ReadByte(); switch (type) { case 1: //Q0..Q9 if (fs.Position + 10 > fs.Length) throw new SBIParseException("Broken record"); - for (var i = 0; i <= 9; i++) bytes.Add(br.ReadByte()); - for (var i = 10; i <= 11; i++) bytes.Add(-1); + for (int i = 0; i <= 9; i++) bytes.Add(br.ReadByte()); + for (int i = 10; i <= 11; i++) bytes.Add(-1); break; case 2: //Q3..Q5 if (fs.Position + 3 > fs.Length) throw new SBIParseException("Broken record"); - for (var i = 0; i <= 2; i++) bytes.Add(-1); - for (var i = 3; i <= 5; i++) bytes.Add(br.ReadByte()); - for (var i = 6; i <= 11; i++) bytes.Add(-1); + for (int i = 0; i <= 2; i++) bytes.Add(-1); + for (int i = 3; i <= 5; i++) bytes.Add(br.ReadByte()); + for (int i = 6; i <= 11; i++) bytes.Add(-1); break; case 3: //Q7..Q9 if (fs.Position + 3 > fs.Length) throw new SBIParseException("Broken record"); - for (var i = 0; i <= 6; i++) bytes.Add(-1); - for (var i = 7; i <= 9; i++) bytes.Add(br.ReadByte()); - for (var i = 10; i <= 11; i++) bytes.Add(-1); + for (int i = 0; i <= 6; i++) bytes.Add(-1); + for (int i = 7; i <= 9; i++) bytes.Add(br.ReadByte()); + for (int i = 10; i <= 11; i++) bytes.Add(-1); break; default: throw new SBIParseException("Broken record"); diff --git a/src/BizHawk.Emulation.DiscSystem/Internal/Jobs/Synthesize_DiscTOC_From_RawTOCEntries_Job.cs b/src/BizHawk.Emulation.DiscSystem/Internal/Jobs/Synthesize_DiscTOC_From_RawTOCEntries_Job.cs index 6b48907bf00..f641e6a3870 100644 --- a/src/BizHawk.Emulation.DiscSystem/Internal/Jobs/Synthesize_DiscTOC_From_RawTOCEntries_Job.cs +++ b/src/BizHawk.Emulation.DiscSystem/Internal/Jobs/Synthesize_DiscTOC_From_RawTOCEntries_Job.cs @@ -29,13 +29,13 @@ public void Run() Result.TOCItems[0].Control = 0; Result.TOCItems[0].Exists = false; - var minFoundTrack = 100; - var maxFoundTrack = 1; + int minFoundTrack = 100; + int maxFoundTrack = 1; foreach (var te in Entries) { var q = te.QData; - var point = q.q_index.DecimalValue; + int point = q.q_index.DecimalValue; //see ECMD-394 page 5-14 for info about point = 0xA0, 0xA1, 0xA2 diff --git a/src/BizHawk.Emulation.DiscSystem/Internal/Jobs/Synthesize_DiscTracks_From_DiscTOC_Job.cs b/src/BizHawk.Emulation.DiscSystem/Internal/Jobs/Synthesize_DiscTracks_From_DiscTOC_Job.cs index ed208d143cf..8bf821daf7d 100644 --- a/src/BizHawk.Emulation.DiscSystem/Internal/Jobs/Synthesize_DiscTracks_From_DiscTOC_Job.cs +++ b/src/BizHawk.Emulation.DiscSystem/Internal/Jobs/Synthesize_DiscTracks_From_DiscTOC_Job.cs @@ -21,7 +21,7 @@ public Synthesize_DiscTracks_From_DiscTOC_Job(Disc disc, DiscSession session) /// first track of is not 1 public void Run() { - var dsr = new DiscSectorReader(IN_Disc) { Policy = { DeterministicClearBuffer = false } }; + DiscSectorReader dsr = new(IN_Disc) { Policy = { DeterministicClearBuffer = false } }; //add a lead-in track Tracks.Add(new() @@ -31,10 +31,10 @@ public void Run() LBA = -new Timestamp(99,99,99).Sector //obvious garbage }); - for (var i = TOCRaw.FirstRecordedTrackNumber; i <= TOCRaw.LastRecordedTrackNumber; i++) + for (int i = TOCRaw.FirstRecordedTrackNumber; i <= TOCRaw.LastRecordedTrackNumber; i++) { var item = TOCRaw.TOCItems[i]; - var track = new DiscTrack + DiscTrack track = new() { Number = i, Control = item.Control, @@ -68,7 +68,7 @@ public void Run() }); //link track list - for (var i = 0; i < Tracks.Count - 1; i++) + for (int i = 0; i < Tracks.Count - 1; i++) { Tracks[i].NextTrack = Tracks[i + 1]; } diff --git a/src/BizHawk.Emulation.DiscSystem/Internal/Jobs/Synthesize_Leadout_Job.cs b/src/BizHawk.Emulation.DiscSystem/Internal/Jobs/Synthesize_Leadout_Job.cs index b0925a0ff27..2d1274c16f1 100644 --- a/src/BizHawk.Emulation.DiscSystem/Internal/Jobs/Synthesize_Leadout_Job.cs +++ b/src/BizHawk.Emulation.DiscSystem/Internal/Jobs/Synthesize_Leadout_Job.cs @@ -24,7 +24,7 @@ public void Run() { //TODO: encode_mode2_form2_sector - var leadoutTs = Disc.TOC.LeadoutLBA; + int leadoutTs = Disc.TOC.LeadoutLBA; var lastTrackTOCItem = Disc.TOC.TOCItems[Disc.TOC.LastRecordedTrackNumber]; //NOTE: in case LastRecordedTrackNumber is al ie, this will malfunction //leadout flags.. let's set them the same as the last track. @@ -33,18 +33,18 @@ public void Run() //TODO - needs to be encoded as a certain mode (mode 2 form 2 for psx... i guess...) - for (var i = 0; i < Length; i++) + for (int i = 0; i < Length; i++) { //var se = new SectorEntry(sz); //Disc.Sectors.Add(se); SubchannelQ sq = default; - var track_relative_msf = i; + int track_relative_msf = i; sq.min = BCD2.FromDecimal(new Timestamp(track_relative_msf).MIN); sq.sec = BCD2.FromDecimal(new Timestamp(track_relative_msf).SEC); sq.frame = BCD2.FromDecimal(new Timestamp(track_relative_msf).FRAC); - var absolute_msf = i + leadoutTs; + int absolute_msf = i + leadoutTs; sq.ap_min = BCD2.FromDecimal(new Timestamp(absolute_msf + 150).MIN); sq.ap_sec = BCD2.FromDecimal(new Timestamp(absolute_msf + 150).SEC); sq.ap_frame = BCD2.FromDecimal(new Timestamp(absolute_msf + 150).FRAC); diff --git a/src/BizHawk.Emulation.DiscSystem/Internal/SectorSynth.cs b/src/BizHawk.Emulation.DiscSystem/Internal/SectorSynth.cs index 723c6e01bde..701f450e973 100644 --- a/src/BizHawk.Emulation.DiscSystem/Internal/SectorSynth.cs +++ b/src/BizHawk.Emulation.DiscSystem/Internal/SectorSynth.cs @@ -132,7 +132,7 @@ internal class ArraySectorSynthProvider : ISectorSynthProvider public ISectorSynthJob2448 Get(int lba) { - var index = lba - FirstLBA; + int index = lba - FirstLBA; if (index < 0) return null; return index >= Sectors.Count ? null : Sectors[index]; } @@ -145,7 +145,7 @@ internal class SimpleSectorSynthProvider : ISectorSynthProvider { public ISectorSynthJob2448 SS; - public ISectorSynthJob2448 Get(int lba) { return SS; } + public ISectorSynthJob2448 Get(int lba) => SS; } /// @@ -164,11 +164,8 @@ public void Install(Disc disc, Func condition, ISectorSynthJob2448 pa Condition = condition; Patch = patch; } - - public ISectorSynthJob2448 Get(int lba) - { - return Condition(lba) ? Patch : Parent.Get(lba); - } + + public ISectorSynthJob2448 Get(int lba) => Condition(lba) ? Patch : Parent.Get(lba); } /// @@ -207,7 +204,7 @@ public void Synth(SectorSynthJob job) return; //apply patched subQ - for (var i = 0; i < 12; i++) + for (int i = 0; i < 12; i++) job.DestBuffer2448[2352 + 12 + i] = Buffer_SubQ[i]; } } @@ -227,12 +224,12 @@ public void Synth(SectorSynthJob job) // data scrambling properly), but data track->audio leadout could break things in an insidious manner for the more accurate drive emulation code). var ses = job.Disc.Sessions[SessionNumber]; - var lba_relative = job.LBA - ses.LeadoutTrack.LBA; + int lba_relative = job.LBA - ses.LeadoutTrack.LBA; //data is zero - var ts = lba_relative; - var ats = job.LBA; + int ts = lba_relative; + int ats = job.LBA; const int ADR = 0x1; // Q channel data encodes position var control = ses.LeadoutTrack.Control; @@ -260,7 +257,7 @@ public void Synth(SectorSynthJob job) TrackType = CUE.CueTrackType.Mode1_2352; } - var ss_gap = new CUE.SS_Gap + CUE.SS_Gap ss_gap = new() { Policy = Policy, sq = sq, diff --git a/src/BizHawk.Emulation.DiscSystem/Internal/SynthUtils.cs b/src/BizHawk.Emulation.DiscSystem/Internal/SynthUtils.cs index a873e24faa5..687f6ee9518 100644 --- a/src/BizHawk.Emulation.DiscSystem/Internal/SynthUtils.cs +++ b/src/BizHawk.Emulation.DiscSystem/Internal/SynthUtils.cs @@ -9,7 +9,7 @@ internal static class SynthUtils /// location within buffer of Q subchannel public static ushort SubQ_SynthChecksum(byte[] buf12, int offset) { - var crc16 = CRC16_CCITT.Calculate(buf12, offset, 10); + ushort crc16 = CRC16_CCITT.Calculate(buf12, offset, 10); //CRC is stored inverted and big endian buf12[offset + 10] = (byte)(~(crc16 >> 8)); @@ -21,10 +21,7 @@ public static ushort SubQ_SynthChecksum(byte[] buf12, int offset) /// /// Calculates the checksum of the provided Q subchannel buffer /// - public static ushort SubQ_CalcChecksum(byte[] buf12, int offset) - { - return CRC16_CCITT.Calculate(buf12, offset, 10); - } + public static ushort SubQ_CalcChecksum(byte[] buf12, int offset) => CRC16_CCITT.Calculate(buf12, offset, 10); /// /// Serializes the provided SubchannelQ structure into a buffer @@ -51,8 +48,8 @@ public static ushort SubQ_Serialize(byte[] buf12, int offset, ref SubchannelQ sq /// public static void SubP(byte[] buffer12, int offset, bool pause) { - var val = (byte)(pause ? 0xFF : 0x00); - for (var i = 0; i < 12; i++) + byte val = (byte)(pause ? 0xFF : 0x00); + for (int i = 0; i < 12; i++) buffer12[offset + i] = val; } @@ -62,9 +59,9 @@ public static void SubP(byte[] buffer12, int offset, bool pause) public static void SectorHeader(byte[] buffer16, int offset, int LBA, byte mode) { buffer16[offset + 0] = 0x00; - for (var i = 1; i < 11; i++) buffer16[offset + i] = 0xFF; + for (int i = 1; i < 11; i++) buffer16[offset + i] = 0xFF; buffer16[offset + 11] = 0x00; - var ts = new Timestamp(LBA + 150); + Timestamp ts = new(LBA + 150); buffer16[offset + 12] = BCD2.IntToBCD(ts.MIN); buffer16[offset + 13] = BCD2.IntToBCD(ts.SEC); buffer16[offset + 14] = BCD2.IntToBCD(ts.FRAC); @@ -77,7 +74,7 @@ public static void SectorHeader(byte[] buffer16, int offset, int LBA, byte mode) public static void SectorSubHeader(byte[] buffer8, int offset, byte form) { // see mirage_sector_generate_subheader - for (var i = 0; i < 8; i++) buffer8[offset + i] = 0; + for (int i = 0; i < 8; i++) buffer8[offset + i] = 0; if (form == 2) { // these are just 0 in form 1 @@ -91,7 +88,7 @@ public static void SectorSubHeader(byte[] buffer8, int offset, byte form) /// public static void EDC_Mode1(byte[] buf2352, int offset) { - var edc = ECM.EDC_Calc(buf2352, offset, 2064); + uint edc = ECM.EDC_Calc(buf2352, offset, 2064); ECM.PokeUint(buf2352, offset + 2064, edc); } @@ -100,7 +97,7 @@ public static void EDC_Mode1(byte[] buf2352, int offset) /// public static void EDC_Mode2_Form1(byte[] buf2352, int offset) { - var edc = ECM.EDC_Calc(buf2352, offset + 16, 2048 + 8); + uint edc = ECM.EDC_Calc(buf2352, offset + 16, 2048 + 8); ECM.PokeUint(buf2352, offset + 2072, edc); } @@ -109,7 +106,7 @@ public static void EDC_Mode2_Form1(byte[] buf2352, int offset) /// public static void EDC_Mode2_Form2(byte[] buf2352, int offset) { - var edc = ECM.EDC_Calc(buf2352, offset + 16, 2324 + 8); + uint edc = ECM.EDC_Calc(buf2352, offset + 16, 2324 + 8); ECM.PokeUint(buf2352, offset + 2348, edc); } @@ -124,7 +121,7 @@ public static void ECM_Mode1(byte[] buf2352, int offset) EDC_Mode1(buf2352, offset); //reserved, zero - for (var i = 0; i < 8; i++) buf2352[offset + 2068 + i] = 0; + for (int i = 0; i < 8; i++) buf2352[offset + 2068 + i] = 0; //ECC ECM.ECC_Populate(buf2352, offset, buf2352, offset, false); @@ -167,13 +164,13 @@ public static void ECM_Mode2_Form2(byte[] buf2352, int offset) /// public static void InterleaveSubcode(byte[] in_buf, int in_buf_index, byte[] out_buf, int out_buf_index) { - for (var d = 0; d < 12; d++) + for (int d = 0; d < 12; d++) { - for (var bitpoodle = 0; bitpoodle < 8; bitpoodle++) + for (int bitpoodle = 0; bitpoodle < 8; bitpoodle++) { - var rawb = 0; + int rawb = 0; - for (var ch = 0; ch < 8; ch++) + for (int ch = 0; ch < 8; ch++) { rawb |= ((in_buf[ch * 12 + d + in_buf_index] >> (7 - bitpoodle)) & 1) << (7 - ch); } @@ -188,12 +185,12 @@ public static void InterleaveSubcode(byte[] in_buf, int in_buf_index, byte[] out /// public static void DeinterleaveSubcode(byte[] in_buf, int in_buf_index, byte[] out_buf, int out_buf_index) { - for (var i = 0; i < 96; i++) + for (int i = 0; i < 96; i++) out_buf[i] = 0; - for (var ch = 0; ch < 8; ch++) + for (int ch = 0; ch < 8; ch++) { - for (var i = 0; i < 96; i++) + for (int i = 0; i < 96; i++) { out_buf[(ch * 12) + (i >> 3) + out_buf_index] |= (byte)(((in_buf[i + in_buf_index] >> (7 - ch)) & 0x1) << (7 - (i & 0x7))); } @@ -205,18 +202,18 @@ public static void DeinterleaveSubcode(byte[] in_buf, int in_buf_index, byte[] o /// public static unsafe void InterleaveSubcodeInplace(byte[] buf, int buf_index) { - var out_buf = stackalloc byte[96]; + byte* out_buf = stackalloc byte[96]; - for (var i = 0; i < 96; i++) + for (int i = 0; i < 96; i++) out_buf[i] = 0; - for (var d = 0; d < 12; d++) + for (int d = 0; d < 12; d++) { - for (var bitpoodle = 0; bitpoodle < 8; bitpoodle++) + for (int bitpoodle = 0; bitpoodle < 8; bitpoodle++) { - var rawb = 0; + int rawb = 0; - for (var ch = 0; ch < 8; ch++) + for (int ch = 0; ch < 8; ch++) { rawb |= ((buf[ch * 12 + d + buf_index] >> (7 - bitpoodle)) & 1) << (7 - ch); } @@ -224,7 +221,7 @@ public static unsafe void InterleaveSubcodeInplace(byte[] buf, int buf_index) } } - for (var i = 0; i < 96; i++) + for (int i = 0; i < 96; i++) buf[i + buf_index] = out_buf[i]; } @@ -233,20 +230,20 @@ public static unsafe void InterleaveSubcodeInplace(byte[] buf, int buf_index) /// public static unsafe void DeinterleaveSubcodeInplace(byte[] buf, int buf_index) { - var out_buf = stackalloc byte[96]; + byte* out_buf = stackalloc byte[96]; - for (var i = 0; i < 96; i++) + for (int i = 0; i < 96; i++) out_buf[i] = 0; - for (var ch = 0; ch < 8; ch++) + for (int ch = 0; ch < 8; ch++) { - for (var i = 0; i < 96; i++) + for (int i = 0; i < 96; i++) { out_buf[(ch * 12) + (i >> 3)] |= (byte)(((buf[i + buf_index] >> (7 - ch)) & 0x1) << (7 - (i & 0x7))); } } - for (var i = 0; i < 96; i++) + for (int i = 0; i < 96; i++) buf[i + buf_index] = out_buf[i]; } } diff --git a/src/BizHawk.Tests/Client.Common/Api/MemoryApiTests.cs b/src/BizHawk.Tests/Client.Common/Api/MemoryApiTests.cs index ec6c5f14536..e3132a4f150 100644 --- a/src/BizHawk.Tests/Client.Common/Api/MemoryApiTests.cs +++ b/src/BizHawk.Tests/Client.Common/Api/MemoryApiTests.cs @@ -75,7 +75,7 @@ public void TestBulkPoke() { void TestCase(IReadOnlyList expected, Action action, string message) { - var memDomainContents = new byte[8]; + byte[] memDomainContents = new byte[8]; action(CreateDummyApi(memDomainContents)); AssertAreSequenceEqual(expected, memDomainContents, message); } diff --git a/src/BizHawk.Tests/Client.Common/Display/InputDisplayTests.cs b/src/BizHawk.Tests/Client.Common/Display/InputDisplayTests.cs index 612287b86a3..8dd3c5e40af 100644 --- a/src/BizHawk.Tests/Client.Common/Display/InputDisplayTests.cs +++ b/src/BizHawk.Tests/Client.Common/Display/InputDisplayTests.cs @@ -27,8 +27,8 @@ public void Initializer() public void Generate_BoolPressed_GeneratesMnemonic() { _boolController["A"] = true; - var displayGenerator = new Bk2InputDisplayGenerator("NES", _boolController); - var actual = displayGenerator.Generate(); + Bk2InputDisplayGenerator displayGenerator = new("NES", _boolController); + string actual = displayGenerator.Generate(); Assert.AreEqual("A", actual); } @@ -36,16 +36,16 @@ public void Generate_BoolPressed_GeneratesMnemonic() public void Generate_BoolUnPressed_GeneratesSpace() { _boolController["A"] = false; - var displayGenerator = new Bk2InputDisplayGenerator("NES", _boolController); - var actual = displayGenerator.Generate(); + Bk2InputDisplayGenerator displayGenerator = new("NES", _boolController); + string actual = displayGenerator.Generate(); Assert.AreEqual(" ", actual); } [TestMethod] public void Generate_Floats() { - var displayGenerator = new Bk2InputDisplayGenerator("NES", _axisController); - var actual = displayGenerator.Generate(); + Bk2InputDisplayGenerator displayGenerator = new("NES", _axisController); + string actual = displayGenerator.Generate(); Assert.AreEqual(" 0, 0,", actual); } @@ -53,8 +53,8 @@ public void Generate_Floats() public void Generate_MidRangeDisplaysEmpty() { _axisController.AcceptNewAxis("StickX", MidValue); - var displayGenerator = new Bk2InputDisplayGenerator("NES", _axisController); - var actual = displayGenerator.Generate(); + Bk2InputDisplayGenerator displayGenerator = new("NES", _axisController); + string actual = displayGenerator.Generate(); Assert.AreEqual(" 0,", actual); } } diff --git a/src/BizHawk.Tests/Client.Common/Movie/LogGeneratorTests.cs b/src/BizHawk.Tests/Client.Common/Movie/LogGeneratorTests.cs index d2f4c36c296..b50046e28cc 100644 --- a/src/BizHawk.Tests/Client.Common/Movie/LogGeneratorTests.cs +++ b/src/BizHawk.Tests/Client.Common/Movie/LogGeneratorTests.cs @@ -26,9 +26,9 @@ public void Initializer() public void GenerateLogEntry_ExclamationForUnknownButtons() { SimpleController controller = new(new ControllerDefinition("Dummy Gamepad") { BoolButtons = { "Unknown Button" } }.MakeImmutable()); - var lg = new Bk2LogEntryGenerator("NES", controller); + Bk2LogEntryGenerator lg = new("NES", controller); controller["Unknown Button"] = true; - var actual = lg.GenerateLogEntry(); + string actual = lg.GenerateLogEntry(); Assert.AreEqual("|!|", actual); } @@ -36,8 +36,8 @@ public void GenerateLogEntry_ExclamationForUnknownButtons() public void GenerateLogEntry_BoolPressed_GeneratesMnemonic() { _boolController["A"] = true; - var lg = new Bk2LogEntryGenerator("NES", _boolController); - var actual = lg.GenerateLogEntry(); + Bk2LogEntryGenerator lg = new("NES", _boolController); + string actual = lg.GenerateLogEntry(); Assert.AreEqual("|A|", actual); } @@ -45,16 +45,16 @@ public void GenerateLogEntry_BoolPressed_GeneratesMnemonic() public void GenerateLogEntry_BoolUnPressed_GeneratesPeriod() { _boolController["A"] = false; - var lg = new Bk2LogEntryGenerator("NES", _boolController); - var actual = lg.GenerateLogEntry(); + Bk2LogEntryGenerator lg = new("NES", _boolController); + string actual = lg.GenerateLogEntry(); Assert.AreEqual("|.|", actual); } [TestMethod] public void GenerateLogEntry_Floats() { - var lg = new Bk2LogEntryGenerator("NES", _axisController); - var actual = lg.GenerateLogEntry(); + Bk2LogEntryGenerator lg = new("NES", _axisController); + string actual = lg.GenerateLogEntry(); Assert.AreEqual("| 0, 0,|", actual); } } diff --git a/src/BizHawk.Tests/Client.Common/Movie/MovieConversionExtensionTests.cs b/src/BizHawk.Tests/Client.Common/Movie/MovieConversionExtensionTests.cs index 95b18ef784f..a6644ab077b 100644 --- a/src/BizHawk.Tests/Client.Common/Movie/MovieConversionExtensionTests.cs +++ b/src/BizHawk.Tests/Client.Common/Movie/MovieConversionExtensionTests.cs @@ -14,7 +14,7 @@ public class MovieConversionExtensionTests [DataRow("C:\\Temp\\TestMovie.tasproj", "C:\\Temp\\TestMovie.tasproj")] public void ConvertFileNameToTasMovie(string original, string expected) { - var actual = MovieConversionExtensions.ConvertFileNameToTasMovie(original); + string actual = MovieConversionExtensions.ConvertFileNameToTasMovie(original); Assert.AreEqual(expected, actual); } } diff --git a/src/BizHawk.Tests/Client.Common/Movie/MovieServiceTests.cs b/src/BizHawk.Tests/Client.Common/Movie/MovieServiceTests.cs index a9c20cf14d7..f5e848bb600 100644 --- a/src/BizHawk.Tests/Client.Common/Movie/MovieServiceTests.cs +++ b/src/BizHawk.Tests/Client.Common/Movie/MovieServiceTests.cs @@ -16,7 +16,7 @@ public class MovieServiceTests [DataRow("BizHawk v2.0 Tasproj v1.1", TasMovie.CurrentVersion)] public void ParseTasMovieVersion(string movieVersion, double expected) { - var actual = MovieService.ParseTasMovieVersion(movieVersion); + double actual = MovieService.ParseTasMovieVersion(movieVersion); Assert.AreEqual(expected, actual); } } diff --git a/src/BizHawk.Tests/Client.Common/Movie/ZwinderStateManagerTests.cs b/src/BizHawk.Tests/Client.Common/Movie/ZwinderStateManagerTests.cs index 5965b1bb299..ea86e566c00 100644 --- a/src/BizHawk.Tests/Client.Common/Movie/ZwinderStateManagerTests.cs +++ b/src/BizHawk.Tests/Client.Common/Movie/ZwinderStateManagerTests.cs @@ -13,7 +13,7 @@ public class ZwinderStateManagerTests { private ZwinderStateManager CreateSmallZwinder(IStatable ss) { - var zw = new ZwinderStateManager(new ZwinderStateManagerSettings + ZwinderStateManager zw = new(new ZwinderStateManagerSettings { CurrentBufferSize = 1, CurrentTargetFrameLength = 10000, @@ -24,7 +24,7 @@ private ZwinderStateManager CreateSmallZwinder(IStatable ss) AncientStateInterval = 50000 }, f => false); - var ms = new MemoryStream(); + MemoryStream ms = new(); ss.SaveStateBinary(new BinaryWriter(ms)); zw.Engage(ms.ToArray()); return zw; @@ -35,8 +35,8 @@ private ZwinderStateManager CreateSmallZwinder(IStatable ss) [TestMethod] public void SaveCreateRoundTrip() { - var ms = new MemoryStream(); - var zw = new ZwinderStateManager(new ZwinderStateManagerSettings + MemoryStream ms = new(); + ZwinderStateManager zw = new(new ZwinderStateManagerSettings { CurrentBufferSize = 16, CurrentTargetFrameLength = 10000, @@ -47,10 +47,10 @@ public void SaveCreateRoundTrip() AncientStateInterval = 50000 }, f => false); zw.SaveStateHistory(new BinaryWriter(ms)); - var buff = ms.ToArray(); - var rms = new MemoryStream(buff, false); + byte[] buff = ms.ToArray(); + MemoryStream rms = new(buff, false); - var zw2 = ZwinderStateManager.Create(new BinaryReader(rms), zw.Settings, f => false); + ZwinderStateManager zw2 = ZwinderStateManager.Create(new BinaryReader(rms), zw.Settings, f => false); // TODO: we could assert more things here to be thorough Assert.IsNotNull(zw2); @@ -61,16 +61,16 @@ public void SaveCreateRoundTrip() [TestMethod] public void CountEvictWorks() { - using var zb = new ZwinderBuffer(new RewindConfig + using ZwinderBuffer zb = new(new RewindConfig { BufferSize = 1, TargetFrameLength = 1 }); - var ss = new StateSource + StateSource ss = new() { PaddingData = new byte[10] }; - var stateCount = 0; + int stateCount = 0; for (int i = 0; i < 1000000; i++) { zb.Capture(i, s => ss.SaveStateBinary(new BinaryWriter(s)), j => stateCount--, true); @@ -82,14 +82,14 @@ public void CountEvictWorks() [TestMethod] public void SaveCreateBufferRoundTrip() { - RewindConfig config = new RewindConfig + RewindConfig config = new() { BufferSize = 1, TargetFrameLength = 10 }; - var buff = new ZwinderBuffer(config); - var ss = new StateSource { PaddingData = new byte[500] }; - for (var frame = 0; frame < 2090; frame++) + ZwinderBuffer buff = new(config); + StateSource ss = new() { PaddingData = new byte[500] }; + for (int frame = 0; frame < 2090; frame++) { ss.Frame = frame; buff.Capture(frame, (s) => ss.SaveStateBinary(new BinaryWriter(s))); @@ -101,10 +101,10 @@ public void SaveCreateBufferRoundTrip() Assert.AreEqual(StateSource.GetFrameNumberInState(buff.GetState(0).GetReadStream()), 10); Assert.AreEqual(StateSource.GetFrameNumberInState(buff.GetState(2079).GetReadStream()), 2089); - var ms = new MemoryStream(); + MemoryStream ms = new(); buff.SaveStateBinary(new BinaryWriter(ms)); ms.Position = 0; - var buff2 = ZwinderBuffer.Create(new BinaryReader(ms), config); + ZwinderBuffer buff2 = ZwinderBuffer.Create(new BinaryReader(ms), config); Assert.AreEqual(buff.Size, buff2.Size); Assert.AreEqual(buff.Used, buff2.Used); @@ -118,8 +118,8 @@ public void SaveCreateBufferRoundTrip() [TestMethod] public void StateBeforeFrame() { - var ss = new StateSource { PaddingData = new byte[1000] }; - var zw = new ZwinderStateManager(new ZwinderStateManagerSettings + StateSource ss = new() { PaddingData = new byte[1000] }; + ZwinderStateManager zw = new(new ZwinderStateManagerSettings { CurrentBufferSize = 1, CurrentTargetFrameLength = 10000, @@ -130,7 +130,7 @@ public void StateBeforeFrame() AncientStateInterval = 50000 }, f => false); { - var ms = new MemoryStream(); + MemoryStream ms = new(); ss.SaveStateBinary(new BinaryWriter(ms)); zw.Engage(ms.ToArray()); } @@ -140,7 +140,7 @@ public void StateBeforeFrame() zw.Capture(frame, ss); } var (f, data) = zw.GetStateClosestToFrame(10440); - var actual = StateSource.GetFrameNumberInState(data); + int actual = StateSource.GetFrameNumberInState(data); Assert.AreEqual(f, actual); Assert.IsTrue(actual <= 10440); } @@ -160,7 +160,7 @@ public void Last_Correct_WhenReservedGreaterThanCurrent() } // Act - var actual = zw.Last; + int actual = zw.Last; // Assert Assert.AreEqual(futureReservedFrame, actual); @@ -181,7 +181,7 @@ public void Last_Correct_WhenCurrentIsLast() } // Act - var actual = zw.Last; + int actual = zw.Last; // Assert Assert.AreEqual(totalCurrentFrames - expectedFrameGap, actual); @@ -202,7 +202,7 @@ public void HasState_Correct_WhenReservedGreaterThanCurrent() } // Act - var actual = zw.HasState(futureReservedFrame); + bool actual = zw.HasState(futureReservedFrame); // Assert Assert.IsTrue(actual); @@ -223,7 +223,7 @@ public void HasState_Correct_WhenCurrentIsLast() } // Act - var actual = zw.HasState(totalCurrentFrames - expectedFrameGap); + bool actual = zw.HasState(totalCurrentFrames - expectedFrameGap); // Assert Assert.IsTrue(actual); @@ -328,10 +328,10 @@ public void Count_NoReserved() } // Act - var actual = zw.Count; + int actual = zw.Count; // Assert - var expected = (totalCurrentFrames / expectedFrameGap) + 1; + int expected = (totalCurrentFrames / expectedFrameGap) + 1; Assert.AreEqual(expected, actual); } @@ -351,10 +351,10 @@ public void Count_WithReserved() } // Act - var actual = zw.Count; + int actual = zw.Count; // Assert - var expected = (totalCurrentFrames / expectedFrameGap) + 2; + int expected = (totalCurrentFrames / expectedFrameGap) + 2; Assert.AreEqual(expected, actual); } @@ -362,7 +362,7 @@ public void Count_WithReserved() public void StateCache() { var ss = CreateStateSource(); - var zw = new ZwinderStateManager(new ZwinderStateManagerSettings + ZwinderStateManager zw = new(new ZwinderStateManagerSettings { CurrentBufferSize = 2, CurrentTargetFrameLength = 1000, @@ -388,14 +388,14 @@ public void StateCache() zw.Capture(101, ss); - var allStates = zw.AllStates() + System.Collections.Generic.List allStates = zw.AllStates() .Select(s => s.Frame) .ToList(); for (int i = 0; i < 10000; i++) { - var actual = zw.HasState(i); - var expected = allStates.Contains(i); + bool actual = zw.HasState(i); + bool expected = allStates.Contains(i); Assert.AreEqual(expected, actual); } } @@ -424,11 +424,11 @@ public void Clear_KeepsZeroState() [TestMethod] public void WhatIfTheHeadStateWrapsAround() { - var ss = new StateSource + StateSource ss = new() { PaddingData = new byte[400 * 1000] }; - using var zw = new ZwinderBuffer(new RewindConfig + using ZwinderBuffer zw = new(new RewindConfig { BufferSize = 1, TargetFrameLength = 1 @@ -448,7 +448,7 @@ public void WhatIfTheHeadStateWrapsAround() [TestMethod] public void TestReadByteCorruption() { - using var zw = new ZwinderBuffer(new RewindConfig + using ZwinderBuffer zw = new(new RewindConfig { BufferSize = 1, TargetFrameLength = 1 @@ -470,7 +470,7 @@ public void TestReadByteCorruption() [TestMethod] public void TestReadBytesCorruption() { - using var zw = new ZwinderBuffer(new RewindConfig + using ZwinderBuffer zw = new(new RewindConfig { BufferSize = 1, TargetFrameLength = 1 @@ -486,7 +486,7 @@ public void TestReadBytesCorruption() var state = zw.GetState(0); Assert.AreEqual(0, state.Frame); Assert.AreEqual(4, state.Size); - var bb = new byte[2]; + byte[] bb = new byte[2]; state.GetReadStream().Read(bb, 0, 2); Assert.AreEqual(1, bb[0]); Assert.AreEqual(2, bb[1]); @@ -495,7 +495,7 @@ public void TestReadBytesCorruption() [TestMethod] public void TestWriteByteCorruption() { - using var zw = new ZwinderBuffer(new RewindConfig + using ZwinderBuffer zw = new(new RewindConfig { BufferSize = 1, TargetFrameLength = 1 @@ -532,13 +532,13 @@ public void TestWriteByteCorruption() [TestMethod] public void BufferStressTest() { - var r = new Random(8675309); - using var zw = new ZwinderBuffer(new RewindConfig + Random r = new(8675309); + using ZwinderBuffer zw = new(new RewindConfig { BufferSize = 1, TargetFrameLength = 1 }); - var buff = new byte[40000]; + byte[] buff = new byte[40000]; for (int round = 0; round < 10; round++) { @@ -546,8 +546,8 @@ public void BufferStressTest() { zw.Capture(i, s => { - var length = r.Next(40000); - var bw = new BinaryWriter(s); + int length = r.Next(40000); + BinaryWriter bw = new(s); var bytes = buff.AsSpan(0, length); r.NextBytes(bytes); bw.Write(length); @@ -559,8 +559,8 @@ public void BufferStressTest() { var info = zw.GetState(i); var s = info.GetReadStream(); - var br = new BinaryReader(s); - var length = info.Size; + BinaryReader br = new(s); + int length = info.Size; if (length != br.ReadInt32() + 8) throw new Exception("Length field corrupted"); var bytes = buff.AsSpan(0, length - 8); @@ -592,7 +592,7 @@ public void SaveStateBinary(BinaryWriter writer) public static int GetFrameNumberInState(Stream stream) { - var ss = new StateSource(); + StateSource ss = new(); ss.LoadStateBinary(new BinaryReader(stream)); return ss.Frame; } diff --git a/src/BizHawk.Tests/Client.Common/config/CorePickerStabilityTests.cs b/src/BizHawk.Tests/Client.Common/config/CorePickerStabilityTests.cs index bc98692c58d..f2fa5ea5ca3 100644 --- a/src/BizHawk.Tests/Client.Common/config/CorePickerStabilityTests.cs +++ b/src/BizHawk.Tests/Client.Common/config/CorePickerStabilityTests.cs @@ -16,10 +16,10 @@ public sealed class CorePickerStabilityTests [TestMethod] public void AssertAllChoicesInMenu() { - var multiCoreSystems = CoreInventory.Instance.AllCores.Where(kvp => kvp.Value.Count != 1) + HashSet multiCoreSystems = CoreInventory.Instance.AllCores.Where(kvp => kvp.Value.Count != 1) .Select(kvp => kvp.Key) .ToHashSet(); - foreach (var sysID in DefaultCorePrefDict.Keys) + foreach (string sysID in DefaultCorePrefDict.Keys) { Assert.IsTrue(multiCoreSystems.Contains(sysID), $"a default core preference exists for {sysID} but that system doesn't have alternate cores"); } @@ -34,12 +34,12 @@ public void AssertAllChoicesInMenu() [TestMethod] public void AssertNoMissingCores() { - var allCoreNames = CoreInventory.Instance.SystemsFlat.Select(coreInfo => coreInfo.Name).ToHashSet(); + HashSet allCoreNames = CoreInventory.Instance.SystemsFlat.Select(coreInfo => coreInfo.Name).ToHashSet(); foreach (var (sysID, coreName) in DefaultCorePrefDict) { Assert.IsTrue(allCoreNames.Contains(coreName), $"default core preference for {sysID} is \"{coreName}\", which doesn't exist"); } - foreach (var (appliesTo, coreNames) in Config.CorePickerUIData) foreach (var coreName in coreNames) + foreach (var (appliesTo, coreNames) in Config.CorePickerUIData) foreach (string? coreName in coreNames) { Assert.IsTrue(allCoreNames.Contains(coreName), $"core picker includes nonexistant core \"{coreName}\" under {appliesTo[0]} group"); } @@ -49,14 +49,14 @@ public void AssertNoMissingCores() [TestMethod] public void AssertNoMissingSystems() { - var allSysIDs = CoreInventory.Instance.AllCores.Keys.ToHashSet(); + HashSet allSysIDs = CoreInventory.Instance.AllCores.Keys.ToHashSet(); #if false // already covered by AssertAllChoicesInMenu foreach (var sysID in DefaultCorePrefDict.Keys) { Assert.IsTrue(allSysIDs.Contains(sysID), $"a default core preference exists for {sysID}, which isn't emulated by any core"); } #endif - foreach (var (appliesTo, _) in Config.CorePickerUIData) foreach (var sysID in appliesTo) + foreach (var (appliesTo, _) in Config.CorePickerUIData) foreach (string? sysID in appliesTo) { Assert.IsTrue(allSysIDs.Contains(sysID), $"core picker has choices for {sysID}, which isn't emulated by any core"); } diff --git a/src/BizHawk.Tests/Client.Common/dearchive/DearchivalTests.cs b/src/BizHawk.Tests/Client.Common/dearchive/DearchivalTests.cs index b2ce159d8d6..85eca936437 100644 --- a/src/BizHawk.Tests/Client.Common/dearchive/DearchivalTests.cs +++ b/src/BizHawk.Tests/Client.Common/dearchive/DearchivalTests.cs @@ -35,7 +35,7 @@ private static readonly (string Filename, bool HasSharpCompressSupport)[] TestCa public void TestSharpCompress() { var sc = SharpCompressDearchivalMethod.Instance; - foreach (var filename in TestCases.Where(testCase => testCase.HasSharpCompressSupport) + foreach (string? filename in TestCases.Where(testCase => testCase.HasSharpCompressSupport) .Select(testCase => testCase.Filename)) { var archive = EmbeddedData.GetStream(EMBED_GROUP, filename); diff --git a/src/BizHawk.Tests/Client.Common/lua/LuaTests.cs b/src/BizHawk.Tests/Client.Common/lua/LuaTests.cs index 93b70b933a1..9b7f7378371 100644 --- a/src/BizHawk.Tests/Client.Common/lua/LuaTests.cs +++ b/src/BizHawk.Tests/Client.Common/lua/LuaTests.cs @@ -231,7 +231,7 @@ static LuaTests() { foreach (var mi in typeof(LuaTests).GetMethods()) { - var lma = (LuaMethodAttribute?)Attribute.GetCustomAttribute(mi, typeof(LuaMethodAttribute)); + LuaMethodAttribute? lma = (LuaMethodAttribute?)Attribute.GetCustomAttribute(mi, typeof(LuaMethodAttribute)); if (lma is not null) { LuaInstance.RegisterFunction(lma.Name, mi); @@ -240,15 +240,12 @@ static LuaTests() } [TestMethod] - public void Lua_Return_Nil() - { - Assert.IsTrue(LuaInstance.DoString("return nil")[0] is null); - } + public void Lua_Return_Nil() => Assert.IsTrue(LuaInstance.DoString("return nil")[0] is null); [TestMethod] public void Lua_MultiReturn_Nil() { - var ret = LuaInstance.DoString("return nil, nil"); + object[] ret = LuaInstance.DoString("return nil, nil"); Assert.IsTrue(ret.Length == 2); Assert.IsTrue(ret[0] is null); Assert.IsTrue(ret[1] is null); @@ -264,37 +261,31 @@ public void Lua_Return_Boolean() [TestMethod] public void Lua_MultiReturn_Boolean() { - var ret = LuaInstance.DoString("return true, false"); + object[] ret = LuaInstance.DoString("return true, false"); Assert.IsTrue(ret.Length == 2); Assert.IsTrue((bool)ret[0]); Assert.IsFalse((bool)ret[1]); } [TestMethod] - public void Lua_Return_Number() - { - Assert.IsTrue((double)LuaInstance.DoString("return 0.0")[0] == 0.0); - } + public void Lua_Return_Number() => Assert.IsTrue((double)LuaInstance.DoString("return 0.0")[0] == 0.0); [TestMethod] public void Lua_MultiReturn_Number() { - var ret = LuaInstance.DoString("return 0.0, 0.1"); + object[] ret = LuaInstance.DoString("return 0.0, 0.1"); Assert.IsTrue(ret.Length == 2); Assert.IsTrue((double)ret[0] == 0.0); Assert.IsTrue((double)ret[1] == 0.1); } [TestMethod] - public void Lua_Return_String() - { - Assert.IsTrue((string)LuaInstance.DoString("return \"foo\"")[0] == "foo"); - } + public void Lua_Return_String() => Assert.IsTrue((string)LuaInstance.DoString("return \"foo\"")[0] == "foo"); [TestMethod] public void Lua_MultiReturn_String() { - var ret = LuaInstance.DoString("return \"foo\", \"bar\""); + object[] ret = LuaInstance.DoString("return \"foo\", \"bar\""); Assert.IsTrue(ret.Length == 2); Assert.IsTrue((string)ret[0] == "foo"); Assert.IsTrue((string)ret[1] == "bar"); @@ -303,21 +294,21 @@ public void Lua_MultiReturn_String() [TestMethod] public void Lua_Return_String_Utf8() { - var ret = (string)LuaInstance.DoString("return \"こんにちは\"")[0]; + string ret = (string)LuaInstance.DoString("return \"こんにちは\"")[0]; Assert.IsTrue(ret == "こんにちは"); } [TestMethod] public void Lua_Return_Function() { - var ret = (NLua.LuaFunction)LuaInstance.DoString("return function() return 0.123 end")[0]; + NLua.LuaFunction ret = (NLua.LuaFunction)LuaInstance.DoString("return function() return 0.123 end")[0]; Assert.IsTrue((double)ret.Call()[0] == 0.123); } [TestMethod] public void Lua_MultiReturn_Function() { - var ret = LuaInstance.DoString("return function() return 0.123 end, function() return 0.321 end"); + object[] ret = LuaInstance.DoString("return function() return 0.123 end, function() return 0.321 end"); Assert.IsTrue((double)((NLua.LuaFunction)ret[0]).Call()[0] == 0.123); Assert.IsTrue((double)((NLua.LuaFunction)ret[1]).Call()[0] == 0.321); } @@ -325,7 +316,7 @@ public void Lua_MultiReturn_Function() [TestMethod] public void Lua_Return_Table_Array_Style() { - var ret = (NLua.LuaTable)LuaInstance.DoString("return {0.0,1.0,2.0}")[0]; + NLua.LuaTable ret = (NLua.LuaTable)LuaInstance.DoString("return {0.0,1.0,2.0}")[0]; Assert.IsTrue((double)ret[1.0] == 0.0); Assert.IsTrue((double)ret[2.0] == 1.0); Assert.IsTrue((double)ret[3.0] == 2.0); @@ -334,8 +325,8 @@ public void Lua_Return_Table_Array_Style() [TestMethod] public void Lua_MultiReturn_Table_Array_Style() { - var ret = LuaInstance.DoString("return {0.0,1.0,2.0}, {2.0,1.0,0.0}"); - var table = (NLua.LuaTable)ret[0]; + object[] ret = LuaInstance.DoString("return {0.0,1.0,2.0}, {2.0,1.0,0.0}"); + NLua.LuaTable table = (NLua.LuaTable)ret[0]; Assert.IsTrue((double)table[1.0] == 0.0); Assert.IsTrue((double)table[2.0] == 1.0); Assert.IsTrue((double)table[3.0] == 2.0); @@ -348,7 +339,7 @@ public void Lua_MultiReturn_Table_Array_Style() [TestMethod] public void Lua_Return_Table_Dict_Style() { - var ret = (NLua.LuaTable)LuaInstance.DoString("return {[\"foo\"]=0.0,[\"bar\"]=1.0}")[0]; + NLua.LuaTable ret = (NLua.LuaTable)LuaInstance.DoString("return {[\"foo\"]=0.0,[\"bar\"]=1.0}")[0]; Assert.IsTrue((double)ret["foo"] == 0.0); Assert.IsTrue((double)ret["bar"] == 1.0); } @@ -356,8 +347,8 @@ public void Lua_Return_Table_Dict_Style() [TestMethod] public void Lua_MultiReturn_Table_Dict_Style() { - var ret = LuaInstance.DoString("return {[\"foo\"]=0.0,[\"bar\"]=1.0}, {[\"bar\"]=0.0,[\"foo\"]=1.0}"); - var table = (NLua.LuaTable)ret[0]; + object[] ret = LuaInstance.DoString("return {[\"foo\"]=0.0,[\"bar\"]=1.0}, {[\"bar\"]=0.0,[\"foo\"]=1.0}"); + NLua.LuaTable table = (NLua.LuaTable)ret[0]; Assert.IsTrue((double)table["foo"] == 0.0); Assert.IsTrue((double)table["bar"] == 1.0); table = (NLua.LuaTable)ret[1]; diff --git a/src/BizHawk.Tests/Common/CollectionExtensions/CollectionExtensionTests.cs b/src/BizHawk.Tests/Common/CollectionExtensions/CollectionExtensionTests.cs index 620a6fe1d84..06cbc118bf1 100644 --- a/src/BizHawk.Tests/Common/CollectionExtensions/CollectionExtensionTests.cs +++ b/src/BizHawk.Tests/Common/CollectionExtensions/CollectionExtensionTests.cs @@ -67,8 +67,8 @@ public void TestAddRange() [TestMethod] public void TestConcatArray() { - var a123 = new[] { 1, 2, 3 }; - var a456 = new[] { 4, 5, 6 }; + int[] a123 = new[] { 1, 2, 3 }; + int[] a456 = new[] { 4, 5, 6 }; Assert.IsTrue(a123.ConcatArray(a456).SequenceEqual(new[] { 1, 2, 3, 4, 5, 6 })); Assert.AreSame(a123, a123.ConcatArray(Array.Empty())); Assert.AreSame(a456, Array.Empty().ConcatArray(a456)); @@ -78,7 +78,7 @@ public void TestConcatArray() [TestMethod] public void TestRemoveAll() { - static bool Predicate(int i) => 2 <= i && i <= 3; + static bool Predicate(int i) => i is >= 2 and <= 3; List a = new(new[] { 1, 2, 3, 4 }); CE.RemoveAll(a, Predicate); diff --git a/src/BizHawk.Tests/Common/CustomCollections/CustomCollectionTests.cs b/src/BizHawk.Tests/Common/CustomCollections/CustomCollectionTests.cs index 37d79783f99..3e3ac63576d 100644 --- a/src/BizHawk.Tests/Common/CustomCollections/CustomCollectionTests.cs +++ b/src/BizHawk.Tests/Common/CustomCollections/CustomCollectionTests.cs @@ -12,9 +12,11 @@ public class CustomCollectionTests [TestMethod] public void TestSortedListAddRemove() { - var list = new SortedList(new[] { 1, 3, 4, 7, 8, 9, 11 }); // this causes one sort, collection initializer syntax wouldn't - list.Add(5); // `Insert` when `BinarySearch` returns negative - list.Add(8); // `Insert` when `BinarySearch` returns non-negative + SortedList list = new(new[] { 1, 3, 4, 7, 8, 9, 11 }) + { + 5, // `Insert` when `BinarySearch` returns negative + 8 // `Insert` when `BinarySearch` returns non-negative + }; // this causes one sort, collection initializer syntax wouldn't list.Remove(3); // `Remove` when `BinarySearch` returns non-negative Assert.IsTrue(list.ToArray().SequenceEqual(new[] { 1, 4, 5, 7, 8, 8, 9, 11 })); Assert.IsFalse(list.Remove(10)); // `Remove` when `BinarySearch` returns negative @@ -23,7 +25,7 @@ public void TestSortedListAddRemove() [TestMethod] public void TestSortedListContains() { - var list = new SortedList(new[] { 1, 3, 4, 7, 8, 9, 11 }); + SortedList list = new(new[] { 1, 3, 4, 7, 8, 9, 11 }); Assert.IsFalse(list.Contains(6)); // `Contains` when `BinarySearch` returns negative Assert.IsTrue(list.Contains(11)); // `Contains` when `BinarySearch` returns non-negative } @@ -35,7 +37,7 @@ public void TestSortedListContains() [DataRow(new[] { 4, 7 }, new int[] { }, 0)] public void TestSortedListRemoveAfter(int[] before, int[] after, int removeItem) { - var sortlist = new SortedList(before); + SortedList sortlist = new(before); sortlist.RemoveAfter(removeItem); Assert.IsTrue(sortlist.ToArray().SequenceEqual(after)); } diff --git a/src/BizHawk.Tests/Common/MultiPredicateSort/MultiPredicateSortTests.cs b/src/BizHawk.Tests/Common/MultiPredicateSort/MultiPredicateSortTests.cs index 28711116058..18c78ad603e 100644 --- a/src/BizHawk.Tests/Common/MultiPredicateSort/MultiPredicateSortTests.cs +++ b/src/BizHawk.Tests/Common/MultiPredicateSort/MultiPredicateSortTests.cs @@ -37,7 +37,7 @@ public void SanityCheck() [TestMethod] public void TestRigidSort() { - var sorts = new RigidMultiPredicateSort<(int X, string Y)>(new Dictionary> + RigidMultiPredicateSort<(int X, string Y)> sorts = new(new Dictionary> { ["by_x"] = t => t.X, ["by_y"] = t => t.Y diff --git a/src/BizHawk.Tests/Common/StringExtensions/StringExtensionTests.cs b/src/BizHawk.Tests/Common/StringExtensions/StringExtensionTests.cs index 811f6dcff53..f4ba520d2b3 100644 --- a/src/BizHawk.Tests/Common/StringExtensions/StringExtensionTests.cs +++ b/src/BizHawk.Tests/Common/StringExtensions/StringExtensionTests.cs @@ -13,12 +13,12 @@ public class StringExtensionTests [TestMethod] public void In_CaseInsensitive() { - var strArray = new[] + string[] strArray = new[] { "Hello World" }; - var actual = "hello world".In(strArray); + bool actual = "hello world".In(strArray); Assert.IsTrue(actual); } diff --git a/src/BizHawk.Tests/Common/checksums/CRC32Tests.cs b/src/BizHawk.Tests/Common/checksums/CRC32Tests.cs index 734c3d79128..7bd6dd2ff5e 100644 --- a/src/BizHawk.Tests/Common/checksums/CRC32Tests.cs +++ b/src/BizHawk.Tests/Common/checksums/CRC32Tests.cs @@ -18,18 +18,18 @@ public void TestCRC32Stability() { static byte[] InitialiseArray() { - var a = new byte[0x100]; - for (var i = 0; i < 0x100; i++) a[i] = (byte) ~i; + byte[] a = new byte[0x100]; + for (int i = 0; i < 0x100; i++) a[i] = (byte) ~i; return a; } static byte[] InitialiseArrayExtra() { - var a = new byte[0x100]; - for (var i = 0; i < 0x100; i++) a[i] = (byte) i; + byte[] a = new byte[0x100]; + for (int i = 0; i < 0x100; i++) a[i] = (byte) i; return a; } - var data = InitialiseArray(); + byte[] data = InitialiseArray(); Assert.AreEqual(EXPECTED, CRC32.Calculate(data)); data = InitialiseArray(); @@ -37,7 +37,7 @@ static byte[] InitialiseArrayExtra() crc32.Add(data); Assert.AreEqual(EXPECTED, crc32.Result); - var dataExtra = InitialiseArrayExtra(); + byte[] dataExtra = InitialiseArrayExtra(); CRC32 crc32Extra = new(); crc32Extra.Add(dataExtra); Assert.AreEqual(EXPECTED_EXTRA, crc32Extra.Result); diff --git a/src/BizHawk.Tests/EmbeddedData.cs b/src/BizHawk.Tests/EmbeddedData.cs index dc80be02e0f..47171c07818 100644 --- a/src/BizHawk.Tests/EmbeddedData.cs +++ b/src/BizHawk.Tests/EmbeddedData.cs @@ -10,7 +10,7 @@ public static class EmbeddedData public static Stream GetStream(string group, string embedPath) { - var fullPath = $"BizHawk.Tests.data.{group}.{embedPath}"; + string fullPath = $"BizHawk.Tests.data.{group}.{embedPath}"; return Asm.GetManifestResourceStream(fullPath) ?? throw new InvalidOperationException($"Could not find the embedded resource {fullPath}"); } } diff --git a/src/BizHawk.Tests/Emulation.Common/Base Implementations/MemoryCallbackSystemTests.cs b/src/BizHawk.Tests/Emulation.Common/Base Implementations/MemoryCallbackSystemTests.cs index 8753a7a57a5..ef823b61e74 100644 --- a/src/BizHawk.Tests/Emulation.Common/Base Implementations/MemoryCallbackSystemTests.cs +++ b/src/BizHawk.Tests/Emulation.Common/Base Implementations/MemoryCallbackSystemTests.cs @@ -63,7 +63,7 @@ public void TestActiveChangedEvent() MemoryCallback writeCallback = new(ScopeA, MemoryCallbackType.Write, "Callback 2", _testCallbacks.Callback2, null, null); MemoryCallback execCallback = new(ScopeA, MemoryCallbackType.Execute, "Callback 3", _testCallbacks.Callback3, null, null); - var activeChangedInvoked = false; + bool activeChangedInvoked = false; _memoryCallbackSystem.ActiveChanged += () => activeChangedInvoked = true; Assert.IsFalse(_memoryCallbackSystem.HasReads); @@ -202,13 +202,13 @@ public void TestAddingCallbackWithinCallback() MemoryCallback callback2 = new(ScopeA, MemoryCallbackType.Read, "Callback 2", _testCallbacks.Callback2, null, null); MemoryCallback callback3 = new(ScopeA, MemoryCallbackType.Read, "Callback 3", _testCallbacks.Callback3, null, null); - var callback1invoked = false; - MemoryCallbackDelegate callback = (_, _, _) => + bool callback1invoked = false; + void callback(uint _1, uint _2, uint _3) { callback1invoked = true; _memoryCallbackSystem.Add(callback2); _memoryCallbackSystem.Add(callback3); - }; + } MemoryCallback callback1 = new(ScopeA, MemoryCallbackType.Read, "Callback 1", callback, null, null); @@ -227,12 +227,12 @@ public void TestRemovingCallbackWithinCallback() { MemoryCallback callback1 = new(ScopeA, MemoryCallbackType.Read, "Callback 1", _testCallbacks.Callback1, null, null); - var callback2invoked = false; - MemoryCallbackDelegate callback = (_, _, _) => + bool callback2invoked = false; + void callback(uint _1, uint _2, uint _3) { callback2invoked = true; _memoryCallbackSystem.Remove(callback1.Callback); - }; + } MemoryCallback callback2 = new(ScopeA, MemoryCallbackType.Read, "Callback 2", callback, null, null); MemoryCallback callback3 = new(ScopeA, MemoryCallbackType.Read, "Callback 3", _testCallbacks.Callback3, null, null); @@ -258,12 +258,12 @@ public void TestRemovingSelfWithinCallback() MemoryCallback callback1 = new(ScopeA, MemoryCallbackType.Read, "Callback 1", _testCallbacks.Callback1, null, null); MemoryCallback? callback2 = null; - var callback2invoked = false; - MemoryCallbackDelegate callback = (_, _, _) => + bool callback2invoked = false; + void callback(uint _1, uint _2, uint _3) { callback2invoked = true; _memoryCallbackSystem.Remove(callback2!.Callback); - }; + } callback2 = new(ScopeA, MemoryCallbackType.Read, "Callback 2", callback, null, null); MemoryCallback callback3 = new(ScopeA, MemoryCallbackType.Read, "Callback 3", _testCallbacks.Callback3, null, null); diff --git a/src/BizHawk.Tests/Emulation.Common/Database/FirmwareDatabaseTests.cs b/src/BizHawk.Tests/Emulation.Common/Database/FirmwareDatabaseTests.cs index 9a885f3bc5b..030eedf8a79 100644 --- a/src/BizHawk.Tests/Emulation.Common/Database/FirmwareDatabaseTests.cs +++ b/src/BizHawk.Tests/Emulation.Common/Database/FirmwareDatabaseTests.cs @@ -19,7 +19,7 @@ public void CheckFormatOfHashes() { static void CustomAssert(string hash) => Assert.IsTrue(hash.Length == 40 && hash == hash.ToUpperInvariant() && hash.IsHex(), $"incorrectly formatted: {hash}"); - foreach (var hash in FirmwareDatabase.FirmwareFilesByHash.Keys) CustomAssert(hash); + foreach (string? hash in FirmwareDatabase.FirmwareFilesByHash.Keys) CustomAssert(hash); foreach (var fo in FirmwareDatabase.FirmwareOptions) CustomAssert(fo.Hash); } } diff --git a/src/BizHawk.Tests/PlatformTests/Common.PathExtensions/PathExtensionTests.cs b/src/BizHawk.Tests/PlatformTests/Common.PathExtensions/PathExtensionTests.cs index 0726ec3be34..eaa97262460 100644 --- a/src/BizHawk.Tests/PlatformTests/Common.PathExtensions/PathExtensionTests.cs +++ b/src/BizHawk.Tests/PlatformTests/Common.PathExtensions/PathExtensionTests.cs @@ -15,7 +15,7 @@ public void TestNullability() { PlatformTestUtils.RunEverywhere(); - var p = OSTailoredCode.IsUnixHost ? "/" : @"C:\"; + string p = OSTailoredCode.IsUnixHost ? "/" : @"C:\"; Assert.IsFalse(PE.IsSubfolderOf(childPath: null, parentPath: p)); Assert.IsFalse(PE.IsSubfolderOf(childPath: p, parentPath: null)); diff --git a/src/BizHawk.WinForms.Controls/FLPs/MarginlessFLPBase.cs b/src/BizHawk.WinForms.Controls/FLPs/MarginlessFLPBase.cs index a7956b4df55..4e299a43dd6 100644 --- a/src/BizHawk.WinForms.Controls/FLPs/MarginlessFLPBase.cs +++ b/src/BizHawk.WinForms.Controls/FLPs/MarginlessFLPBase.cs @@ -15,6 +15,6 @@ public abstract class MarginlessFLPBase : FlowLayoutPanel protected MarginlessFLPBase() => base.Margin = Padding.Empty; - protected static readonly Size TinySize = new Size(24, 24); + protected static readonly Size TinySize = new(24, 24); } } diff --git a/src/BizHawk.WinForms.Controls/GroupBoxEx/GroupBoxExBase.cs b/src/BizHawk.WinForms.Controls/GroupBoxEx/GroupBoxExBase.cs index f04ca2c4eef..298f8f1e6eb 100644 --- a/src/BizHawk.WinForms.Controls/GroupBoxEx/GroupBoxExBase.cs +++ b/src/BizHawk.WinForms.Controls/GroupBoxEx/GroupBoxExBase.cs @@ -5,7 +5,7 @@ namespace BizHawk.WinForms.Controls { public abstract class GroupBoxExBase : GroupBox { - public readonly RadioButtonGroupTracker Tracker = new RadioButtonGroupTracker(); + public readonly RadioButtonGroupTracker Tracker = new(); [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] diff --git a/src/BizHawk.WinForms.Controls/MenuEx/MenuStripEx.cs b/src/BizHawk.WinForms.Controls/MenuEx/MenuStripEx.cs index e1b6ee1d091..d28e15d3895 100644 --- a/src/BizHawk.WinForms.Controls/MenuEx/MenuStripEx.cs +++ b/src/BizHawk.WinForms.Controls/MenuEx/MenuStripEx.cs @@ -14,7 +14,7 @@ public class MenuStripEx : MenuStrip public new Size Size => base.Size; [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public new Point Location => new Point(0, 0); + public new Point Location => new(0, 0); [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new string Text => "";