Misc cleanups in Client.Common

This commit is contained in:
adelikat 2017-05-19 13:17:07 -05:00
parent f89bcf4bfa
commit 43cb50d5c3
36 changed files with 728 additions and 730 deletions

View File

@ -86,8 +86,8 @@ namespace BizHawk.Client.Common
}
}
public virtual string ReadName => Name;
public virtual string WriteName => Ext != null ? Name + '.' + Ext : Name;
public string ReadName => Name;
public string WriteName => Ext != null ? Name + '.' + Ext : Name;
public string Name { get; protected set; }
public string Ext { get; protected set; }
@ -203,7 +203,7 @@ namespace BizHawk.Client.Common
}
}
private static byte[] zipheader = { 0x50, 0x4b, 0x03, 0x04 };
private static readonly byte[] Zipheader = { 0x50, 0x4b, 0x03, 0x04 };
public static BinaryStateLoader LoadAndDetect(string filename, bool isMovieLoad = false)
{
var ret = new BinaryStateLoader();
@ -212,7 +212,7 @@ namespace BizHawk.Client.Common
{
byte[] data = new byte[4];
fs.Read(data, 0, 4);
if (!data.SequenceEqual(zipheader))
if (!data.SequenceEqual(Zipheader))
{
return null;
}

View File

@ -100,7 +100,7 @@ namespace BizHawk.Client.Common
}
// zero 09-mar-2015 - not sure if adding + 1 here is correct.. but... maybe?
var output = (input * multiplier + 10000.0f) * (range.Max - range.Min + 1) / 20000.0f + range.Min;
var output = (((input * multiplier) + 10000.0f) * (range.Max - range.Min + 1) / 20000.0f) + range.Min;
// zero 09-mar-2015 - at this point, we should only have integers, since thats all 100% of consoles ever see
// if this becomes a problem we can add flags to the range and update GUIs to be able to display floats

View File

@ -96,8 +96,9 @@ namespace BizHawk.Client.Common
return resolved.FilePath;
}
public class RealFirmwareReader : IDisposable
private class RealFirmwareReader : IDisposable
{
private readonly List<RealFirmwareFile> _files = new List<RealFirmwareFile>();
private SHA1 _sha1 = SHA1.Create();
public void Dispose()
@ -117,13 +118,12 @@ namespace BizHawk.Client.Common
}
rff.Hash = _sha1.Hash.BytesToHexString();
dict[rff.Hash] = rff;
Dict[rff.Hash] = rff;
_files.Add(rff);
return rff;
}
public readonly Dictionary<string, RealFirmwareFile> dict = new Dictionary<string, RealFirmwareFile>();
private readonly List<RealFirmwareFile> _files = new List<RealFirmwareFile>();
public Dictionary<string, RealFirmwareFile> Dict { get; } = new Dictionary<string, RealFirmwareFile>();
}
public void DoScanAndResolve()
@ -184,12 +184,12 @@ namespace BizHawk.Client.Common
var hash = fo.Hash;
// did we find this firmware?
if (reader.dict.ContainsKey(hash))
if (reader.Dict.ContainsKey(hash))
{
// rad! then we can use it
var ri = new ResolutionInfo
{
FilePath = reader.dict[hash].FileInfo.FullName,
FilePath = reader.Dict[hash].FileInfo.FullName,
KnownFirmwareFile = FirmwareDatabase.FirmwareFilesByHash[hash],
Hash = hash,
Size = fo.Size

View File

@ -31,9 +31,9 @@ namespace BizHawk.Client.Common
public static AutofireController AutofireNullControls;
// the movie will be spliced inbetween these if it is present
public static CopyControllerAdapter MovieInputSourceAdapter = new CopyControllerAdapter();
public static CopyControllerAdapter MovieOutputHardpoint = new CopyControllerAdapter();
public static MultitrackRewiringControllerAdapter MultitrackRewiringAdapter = new MultitrackRewiringControllerAdapter();
public static readonly CopyControllerAdapter MovieInputSourceAdapter = new CopyControllerAdapter();
public static readonly CopyControllerAdapter MovieOutputHardpoint = new CopyControllerAdapter();
public static readonly MultitrackRewiringControllerAdapter MultitrackRewiringAdapter = new MultitrackRewiringControllerAdapter();
// dont take my word for it, since the final word is actually in RewireInputChain, but here is a guide...
// user -> Input -> ActiveController -> UDLR -> StickyXORPlayerInputAdapter -> TurboAdapter(TBD) -> Lua(?TBD?) -> ..
@ -47,26 +47,26 @@ namespace BizHawk.Client.Common
public static AutofireController AutoFireController;
// the "output" port for the controller chain.
public static CopyControllerAdapter ControllerOutput = new CopyControllerAdapter();
public static readonly CopyControllerAdapter ControllerOutput = new CopyControllerAdapter();
public static UD_LR_ControllerAdapter UD_LR_ControllerAdapter = new UD_LR_ControllerAdapter();
public static readonly UD_LR_ControllerAdapter UD_LR_ControllerAdapter = new UD_LR_ControllerAdapter();
public static AutoFireStickyXorAdapter AutofireStickyXORAdapter = new AutoFireStickyXorAdapter();
public static readonly AutoFireStickyXorAdapter AutofireStickyXORAdapter = new AutoFireStickyXorAdapter();
/// <summary>
/// provides an opportunity to mutate the player's input in an autohold style
/// </summary>
public static StickyXorAdapter StickyXORAdapter = new StickyXorAdapter();
public static readonly StickyXorAdapter StickyXORAdapter = new StickyXorAdapter();
/// <summary>
/// Used to AND to another controller, used for Joypad.Set()
/// </summary>
public static OverrideAdaptor LuaAndAdaptor = new OverrideAdaptor();
public static readonly OverrideAdaptor LuaAndAdaptor = new OverrideAdaptor();
/// <summary>
/// fire off one-frame logical button clicks here. useful for things like ti-83 virtual pad and reset buttons
/// </summary>
public static ClickyVirtualPadController ClickyVirtualPadController = new ClickyVirtualPadController();
public static readonly ClickyVirtualPadController ClickyVirtualPadController = new ClickyVirtualPadController();
public static SimpleController MovieOutputController = new SimpleController();

View File

@ -5,6 +5,10 @@ using System.Runtime.InteropServices;
using BizHawk.Common;
using BizHawk.Emulation.Common;
// ReSharper disable InconsistentNaming
// ReSharper disable StyleCop.SA1304
// ReSharper disable StyleCop.SA1307
// ReSharper disable StyleCop.SA1401
namespace BizHawk.Client.Common
{
public class QuickBmpFile
@ -12,23 +16,24 @@ namespace BizHawk.Client.Common
#region Structs
[StructLayout(LayoutKind.Sequential, Pack = 1)]
class BITMAPFILEHEADER
private class Bitmapfileheader
{
public readonly uint bfSize;
public ushort bfType;
public uint bfSize;
public ushort bfReserved1;
public ushort bfReserved2;
public uint bfOffBits;
public BITMAPFILEHEADER()
public Bitmapfileheader()
{
bfSize = (uint)Marshal.SizeOf(this);
}
public static BITMAPFILEHEADER FromStream(Stream s)
public static Bitmapfileheader FromStream(Stream s)
{
var ret = GetObject<BITMAPFILEHEADER>(s);
if (ret.bfSize != Marshal.SizeOf(typeof(BITMAPFILEHEADER)))
var ret = GetObject<Bitmapfileheader>(s);
if (ret.bfSize != Marshal.SizeOf(typeof(Bitmapfileheader)))
{
throw new InvalidOperationException();
}
@ -38,9 +43,9 @@ namespace BizHawk.Client.Common
}
[StructLayout(LayoutKind.Sequential)]
class BITMAPINFOHEADER
private class Bitmapinfoheader
{
public uint biSize;
public readonly uint biSize;
public int biWidth;
public int biHeight;
public ushort biPlanes;
@ -52,15 +57,15 @@ namespace BizHawk.Client.Common
public uint biClrUsed;
public uint biClrImportant;
public BITMAPINFOHEADER()
public Bitmapinfoheader()
{
biSize = (uint)Marshal.SizeOf(this);
}
public static BITMAPINFOHEADER FromStream(Stream s)
public static Bitmapinfoheader FromStream(Stream s)
{
var ret = GetObject<BITMAPINFOHEADER>(s);
if (ret.biSize != Marshal.SizeOf(typeof(BITMAPINFOHEADER)))
var ret = GetObject<Bitmapinfoheader>(s);
if (ret.biSize != Marshal.SizeOf(typeof(Bitmapinfoheader)))
{
throw new InvalidOperationException();
}
@ -141,18 +146,18 @@ namespace BizHawk.Client.Common
{
int w = dst.Width;
int h = dst.Height;
int in_w = src.Width;
int in_h = src.Height;
int inW = src.Width;
int inH = src.Height;
int* sp = src.Data;
int* dp = dst.Data;
// vflip along the way
for (int j = h - 1; j >= 0; j--)
{
sp = src.Data + in_w * (j * in_h / h);
sp = src.Data + (inW * (j * inH / h));
for (int i = 0; i < w; i++)
{
dp[i] = sp[i * in_w / w];
dp[i] = sp[i * inW / w];
}
dp += w;
@ -163,17 +168,17 @@ namespace BizHawk.Client.Common
{
int w = dst.Width;
int h = dst.Height;
int in_w = src.Width;
int in_h = src.Height;
int inW = src.Width;
int inH = src.Height;
int* sp = src.Data;
int* dp = dst.Data;
for (int j = 0; j < h; j++)
{
sp = src.Data + in_w * (j * in_h / h);
sp = src.Data + (inW * (j * inH / h));
for (int i = 0; i < w; i++)
{
dp[i] = sp[i * in_w / w];
dp[i] = sp[i * inW / w];
}
dp += w;
@ -239,8 +244,8 @@ namespace BizHawk.Client.Common
public static unsafe bool Load(IVideoProvider v, Stream s)
{
var bf = BITMAPFILEHEADER.FromStream(s);
var bi = BITMAPINFOHEADER.FromStream(s);
var bf = Bitmapfileheader.FromStream(s);
var bi = Bitmapinfoheader.FromStream(s);
if (bf.bfType != 0x4d42
|| bf.bfOffBits != bf.bfSize + bi.biSize
|| bi.biPlanes != 1
@ -250,17 +255,17 @@ namespace BizHawk.Client.Common
return false;
}
int in_w = bi.biWidth;
int in_h = bi.biHeight;
int inW = bi.biWidth;
int inH = bi.biHeight;
byte[] src = new byte[in_w * in_h * 4];
byte[] src = new byte[inW * inH * 4];
s.Read(src, 0, src.Length);
if (v is LoadedBMP)
{
var l = v as LoadedBMP;
l.BufferWidth = in_w;
l.BufferHeight = in_h;
l.VideoBuffer = new int[in_w * in_h];
l.BufferWidth = inW;
l.BufferHeight = inH;
l.VideoBuffer = new int[inW * inH];
}
int[] dst = v.GetVideoBuffer();
@ -273,8 +278,8 @@ namespace BizHawk.Client.Common
Blit(new BMP
{
Data = (int*)srcp,
Width = in_w,
Height = in_h
Width = inW,
Height = inH
},
new BMP
{
@ -290,8 +295,8 @@ namespace BizHawk.Client.Common
public static unsafe void Save(IVideoProvider v, Stream s, int w, int h)
{
var bf = new BITMAPFILEHEADER();
var bi = new BITMAPINFOHEADER();
var bf = new Bitmapfileheader();
var bi = new Bitmapinfoheader();
bf.bfType = 0x4d42;
bf.bfOffBits = bf.bfSize + bi.biSize;

View File

@ -62,7 +62,7 @@ namespace BizHawk.Client.Common
using (new SimpleTime("Save Framebuffer"))
{
bs.PutLump(BinaryStateLump.Framebuffer, (s) => QuickBmpFile.Save(Global.Emulator.AsVideoProvider(), s, out_w, out_h));
bs.PutLump(BinaryStateLump.Framebuffer, s => QuickBmpFile.Save(Global.Emulator.AsVideoProvider(), s, out_w, out_h));
}
}
}

View File

@ -10,19 +10,20 @@ namespace BizHawk.Client.Common
{
private class RangBuffer
{
const int LEN = 4096;
const int MASK = 4095;
byte[] buff = new byte[LEN];
private const int Len = 4096;
private const int Mask = 4095;
int wpos = 0;
int rpos = 0;
private readonly byte[] _buff = new byte[Len];
bool writeclosed;
bool readclosed;
private readonly object _sharedlock = new object();
private readonly ManualResetEvent _full = new ManualResetEvent(true);
private readonly ManualResetEvent _empty = new ManualResetEvent(false);
object sharedlock = new object();
ManualResetEvent full = new ManualResetEvent(true);
ManualResetEvent empty = new ManualResetEvent(false);
private int _wpos;
private int _rpos;
private bool _writeclosed;
private bool _readclosed;
public Stream W { get; }
public Stream R { get; }
@ -38,23 +39,23 @@ namespace BizHawk.Client.Common
// slow, but faster than using the other overload with byte[1]
while (true)
{
empty.WaitOne();
lock (sharedlock)
_empty.WaitOne();
lock (_sharedlock)
{
if (rpos != wpos)
if (_rpos != _wpos)
{
byte ret = buff[rpos++];
rpos &= MASK;
full.Set();
byte ret = _buff[_rpos++];
_rpos &= Mask;
_full.Set();
return ret;
}
else if (writeclosed)
else if (_writeclosed)
{
return -1;
}
else
{
empty.Reset();
_empty.Reset();
}
}
}
@ -65,14 +66,14 @@ namespace BizHawk.Client.Common
int ret = 0;
while (count > 0)
{
empty.WaitOne();
lock (sharedlock)
_empty.WaitOne();
lock (_sharedlock)
{
int start = rpos;
int end = wpos;
int start = _rpos;
int end = _wpos;
if (end < start) // wrap
{
end = LEN;
end = Len;
}
if (end - start > count)
@ -83,20 +84,20 @@ namespace BizHawk.Client.Common
int c = end - start;
if (c > 0)
{
Buffer.BlockCopy(buff, start, buffer, offset, c);
Buffer.BlockCopy(_buff, start, buffer, offset, c);
count -= c;
ret += c;
offset += c;
rpos = end & MASK;
full.Set();
_rpos = end & Mask;
_full.Set();
}
else if (writeclosed)
else if (_writeclosed)
{
break;
}
else
{
empty.Reset();
_empty.Reset();
}
}
}
@ -106,10 +107,10 @@ namespace BizHawk.Client.Common
public void CloseRead()
{
lock (sharedlock)
lock (_sharedlock)
{
readclosed = true;
full.Set();
_readclosed = true;
_full.Set();
}
}
@ -117,25 +118,24 @@ namespace BizHawk.Client.Common
{
while (true)
{
full.WaitOne();
lock (sharedlock)
_full.WaitOne();
lock (_sharedlock)
{
int next = (wpos + 1) & MASK;
if (next != rpos)
int next = (_wpos + 1) & Mask;
if (next != _rpos)
{
buff[wpos] = value;
wpos = next;
empty.Set();
_buff[_wpos] = value;
_wpos = next;
_empty.Set();
return true;
}
else if (readclosed)
if (_readclosed)
{
return false;
}
else
{
full.Reset();
}
_full.Reset();
}
}
}
@ -145,14 +145,14 @@ namespace BizHawk.Client.Common
int ret = 0;
while (count > 0)
{
full.WaitOne();
lock (sharedlock)
_full.WaitOne();
lock (_sharedlock)
{
int start = wpos;
int end = (rpos - 1) & MASK;
int start = _wpos;
int end = (_rpos - 1) & Mask;
if (end < start) // wrap
{
end = LEN;
end = Len;
}
if (end - start > count)
@ -163,20 +163,20 @@ namespace BizHawk.Client.Common
int c = end - start;
if (c > 0)
{
Buffer.BlockCopy(buffer, offset, buff, start, c);
Buffer.BlockCopy(buffer, offset, _buff, start, c);
count -= c;
ret += c;
offset += c;
wpos = end & MASK;
empty.Set();
_wpos = end & Mask;
_empty.Set();
}
else if (readclosed)
else if (_readclosed)
{
break;
}
else
{
full.Reset();
_full.Reset();
}
}
}
@ -186,10 +186,10 @@ namespace BizHawk.Client.Common
public void CloseWrite()
{
lock (sharedlock)
lock (_sharedlock)
{
writeclosed = true;
empty.Set();
_writeclosed = true;
_empty.Set();
}
}
@ -262,11 +262,12 @@ namespace BizHawk.Client.Common
private class RStream : Stream
{
public override bool CanRead { get { return true; } }
public override bool CanSeek { get { return false; } }
public override bool CanWrite { get { return false; } }
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override void Flush() { }
public override long Length { get { return 1; } } // { get { throw new NotSupportedException(); } }
public override long Length => 1; // { get { throw new NotSupportedException(); } }
public override long Seek(long offset, SeekOrigin origin) { return 0; } // { throw new NotSupportedException(); }
public override void SetLength(long value) { throw new NotSupportedException(); }
public override long Position
@ -328,43 +329,43 @@ namespace BizHawk.Client.Common
}
}
private SevenZip.SevenZipCompressor svc;
private readonly SevenZip.SevenZipCompressor _svc;
private readonly string _path;
private bool first = true;
private string path;
private int compressionlevel;
private bool _first = true;
private int _compressionlevel;
public SevenZipWriter(string path, int compressionlevel)
{
this.path = path;
this.compressionlevel = compressionlevel;
_path = path;
_compressionlevel = compressionlevel;
svc = new SevenZip.SevenZipCompressor { ArchiveFormat = SevenZip.OutArchiveFormat.Zip };
_svc = new SevenZip.SevenZipCompressor { ArchiveFormat = SevenZip.OutArchiveFormat.Zip };
switch (compressionlevel)
{
default:
case 0:
svc.CompressionLevel = SevenZip.CompressionLevel.None;
_svc.CompressionLevel = SevenZip.CompressionLevel.None;
break;
case 1:
case 2:
svc.CompressionLevel = SevenZip.CompressionLevel.Fast;
_svc.CompressionLevel = SevenZip.CompressionLevel.Fast;
break;
case 3:
case 4:
svc.CompressionLevel = SevenZip.CompressionLevel.Low;
_svc.CompressionLevel = SevenZip.CompressionLevel.Low;
break;
case 5:
case 6:
svc.CompressionLevel = SevenZip.CompressionLevel.Normal;
_svc.CompressionLevel = SevenZip.CompressionLevel.Normal;
break;
case 7:
case 8:
svc.CompressionLevel = SevenZip.CompressionLevel.High;
_svc.CompressionLevel = SevenZip.CompressionLevel.High;
break;
case 9:
svc.CompressionLevel = SevenZip.CompressionLevel.Ultra;
_svc.CompressionLevel = SevenZip.CompressionLevel.Ultra;
break;
}
}
@ -374,19 +375,19 @@ namespace BizHawk.Client.Common
var dict = new Dictionary<string, Stream>();
var r = new RangBuffer();
dict[name] = r.R;
if (first)
if (_first)
{
first = false;
svc.CompressionMode = SevenZip.CompressionMode.Create;
_first = false;
_svc.CompressionMode = SevenZip.CompressionMode.Create;
}
else
{
svc.CompressionMode = SevenZip.CompressionMode.Append;
_svc.CompressionMode = SevenZip.CompressionMode.Append;
}
var task = Task.Factory.StartNew(() =>
{
svc.CompressStreamDictionary(dict, path);
_svc.CompressStreamDictionary(dict, _path);
});
try
{

View File

@ -206,7 +206,7 @@ namespace BizHawk.Client.Common
}
/// <summary>
/// Gets the haschode for current insance
/// Gets the haschode for current instance
/// </summary>
/// <returns>This instance hashcode</returns>
public override int GetHashCode()
@ -241,7 +241,7 @@ namespace BizHawk.Client.Common
/// </summary>
/// <param name="system1">First <see cref="SystemInfo"/></param>
/// <param name="system2">Second <see cref="SystemInfo"/></param>
/// <returns>True if both system are diferent; otherwise, false</returns>
/// <returns>True if both system are different; otherwise, false</returns>
public static bool operator !=(SystemInfo system1, SystemInfo system2)
{
return !(system1 == system2);

View File

@ -13,17 +13,10 @@ namespace BizHawk.Client.Common
{
public class XmlGame
{
public XmlGame()
{
Assets = new List<KeyValuePair<string, byte[]>>();
AssetFullPaths = new List<string>();
GI = new GameInfo();
}
public XmlDocument Xml { get; set; }
public GameInfo GI { get; }
public IList<KeyValuePair<string, byte[]>> Assets { get; }
public IList<string> AssetFullPaths { get; } // TODO: Hack work around, to avoid having to refactor Assets into a object array, should be refactored!
public GameInfo GI { get; } = new GameInfo();
public IList<KeyValuePair<string, byte[]>> Assets { get; } = new List<KeyValuePair<string, byte[]>>();
public IList<string> AssetFullPaths { get; } = new List<string>(); // TODO: Hack work around, to avoid having to refactor Assets into a object array, should be refactored!
public static XmlGame Create(HawkFile f)
{
@ -52,8 +45,8 @@ namespace BizHawk.Client.Common
var n = y.SelectSingleNode("./LoadAssets");
if (n != null)
{
var HashStream = new MemoryStream();
int? OriginalIndex = null;
var hashStream = new MemoryStream();
int? originalIndex = null;
foreach (XmlNode a in n.ChildNodes)
{
@ -65,9 +58,9 @@ namespace BizHawk.Client.Common
var ai = f.FindArchiveMember(filename.Substring(1));
if (ai != null)
{
if (OriginalIndex == null)
if (originalIndex == null)
{
OriginalIndex = f.GetBoundIndex();
originalIndex = f.GetBoundIndex();
}
f.Unbind();
@ -112,16 +105,16 @@ namespace BizHawk.Client.Common
using (var sha1 = System.Security.Cryptography.SHA1.Create())
{
sha1.TransformFinalBlock(data, 0, data.Length);
HashStream.Write(sha1.Hash, 0, sha1.Hash.Length);
hashStream.Write(sha1.Hash, 0, sha1.Hash.Length);
}
}
ret.GI.Hash = HashStream.GetBuffer().HashSHA1(0, (int)HashStream.Length);
HashStream.Close();
if (OriginalIndex != null)
ret.GI.Hash = hashStream.GetBuffer().HashSHA1(0, (int)hashStream.Length);
hashStream.Close();
if (originalIndex != null)
{
f.Unbind();
f.BindArchiveMember((int)OriginalIndex);
f.BindArchiveMember((int)originalIndex);
}
}
else

View File

@ -15,12 +15,12 @@ namespace BizHawk.Client.Common
{
public class Binding
{
public string DisplayName;
public string Bindings;
public string DefaultBinding;
public string TabGroup;
public string ToolTip;
public int Ordinal = 0;
public string DisplayName { get; set; }
public string Bindings { get; set; }
public string DefaultBinding { get; set; }
public string TabGroup { get; set; }
public string ToolTip { get; set; }
public int Ordinal { get; set; }
}
[Newtonsoft.Json.JsonObject]
@ -29,9 +29,9 @@ namespace BizHawk.Client.Common
public List<Binding> Bindings { get; }
[Newtonsoft.Json.JsonConstructor]
public BindingCollection(List<Binding> Bindings)
public BindingCollection(List<Binding> bindings)
{
this.Bindings = Bindings;
Bindings = bindings;
}
public BindingCollection()
@ -105,15 +105,15 @@ namespace BizHawk.Client.Common
}
}
private static List<Binding> s_DefaultValues;
private static List<Binding> _defaultValues;
public static List<Binding> DefaultValues
{
get
{
if (s_DefaultValues == null)
if (_defaultValues == null)
{
s_DefaultValues = new List<Binding>
_defaultValues = new List<Binding>
{
Bind("General", "Frame Advance", "F"),
Bind("General", "Rewind", "Shift+R, J1 B7, X1 LeftTrigger"),
@ -261,13 +261,13 @@ namespace BizHawk.Client.Common
};
// set ordinals based on order in list
for (int i = 0; i < s_DefaultValues.Count; i++)
for (int i = 0; i < _defaultValues.Count; i++)
{
s_DefaultValues[i].Ordinal = i;
_defaultValues[i].Ordinal = i;
}
} // if (s_DefaultValues == null)
return s_DefaultValues;
return _defaultValues;
}
}
}

View File

@ -18,19 +18,19 @@ namespace BizHawk.Client.Common
public override string Name => "memorysavestate";
private readonly Dictionary<Guid, byte[]> MemorySavestates = new Dictionary<Guid, byte[]>();
[RequiredService]
private IStatable _statableCore { get; set; }
private IStatable StatableCore { get; set; }
private readonly Dictionary<Guid, byte[]> _memorySavestates = new Dictionary<Guid, byte[]>();
[LuaMethodAttributes(
"savecorestate", "creates a core savestate and stores it in memory. Note: a core savestate is only the raw data from the core, and not extras such as movie input logs, or framebuffers. Returns a unique identifer for the savestate")]
public string SaveCoreStateToMemory()
{
var guid = Guid.NewGuid();
var bytes = (byte[])_statableCore.SaveStateBinary().Clone();
var bytes = (byte[])StatableCore.SaveStateBinary().Clone();
MemorySavestates.Add(guid, bytes);
_memorySavestates.Add(guid, bytes);
return guid.ToString();
}
@ -42,12 +42,12 @@ namespace BizHawk.Client.Common
try
{
var state = MemorySavestates[guid];
var state = _memorySavestates[guid];
using (var ms = new MemoryStream(state))
using (var br = new BinaryReader(ms))
{
_statableCore.LoadStateBinary(br);
StatableCore.LoadStateBinary(br);
}
}
catch
@ -60,13 +60,13 @@ namespace BizHawk.Client.Common
public void DeleteState(string identifier)
{
var guid = new Guid(identifier);
MemorySavestates.Remove(guid);
_memorySavestates.Remove(guid);
}
[LuaMethodAttributes("clearstatesfrommemory", "clears all savestates stored in memory")]
public void ClearInMemoryStates()
{
MemorySavestates.Clear();
_memorySavestates.Clear();
}
}
}

View File

@ -82,7 +82,7 @@ __Types and notation__
public string Scope { get; set; }
[JsonProperty(PropertyName = "completions")]
public List<Completion> Completions = new List<Completion>();
public List<Completion> Completions { get; set; } = new List<Completion>();
public class Completion
{

View File

@ -16,10 +16,10 @@ namespace BizHawk.Client.Common
[OptionalService]
protected IMemoryDomains MemoryDomainCore { get; set; }
public LuaMemoryBase(Lua lua)
protected LuaMemoryBase(Lua lua)
: base(lua) { }
public LuaMemoryBase(Lua lua, Action<string> logOutputCallback)
protected LuaMemoryBase(Lua lua, Action<string> logOutputCallback)
: base(lua, logOutputCallback) { }
protected abstract MemoryDomain Domain { get; }

View File

@ -83,7 +83,7 @@ namespace BizHawk.Client.Common
// Color tag open
if (addcolortag)
{
uint rgb = (Color & 0x00FFFFFF);
uint rgb = Color & 0x00FFFFFF;
sb.Append("<font color=\"#");
sb.Append(rgb.ToString("X6"));
sb.Append("\">");

View File

@ -15,49 +15,46 @@ namespace BizHawk.Client.Common
.Replace("P4 ", "")
.Replace("Key ", "");
if (SystemOverrides.ContainsKey(Global.Emulator.SystemId) && SystemOverrides[Global.Emulator.SystemId].ContainsKey(key))
if (_systemOverrides.ContainsKey(Global.Emulator.SystemId) && _systemOverrides[Global.Emulator.SystemId].ContainsKey(key))
{
return SystemOverrides[Global.Emulator.SystemId][key];
return _systemOverrides[Global.Emulator.SystemId][key];
}
if (BaseMnemonicLookupTable.ContainsKey(key))
if (_baseMnemonicLookupTable.ContainsKey(key))
{
return BaseMnemonicLookupTable[key];
return _baseMnemonicLookupTable[key];
}
return button;
}
}
private readonly Dictionary<string, string> BaseMnemonicLookupTable = new Dictionary<string, string>
private readonly Dictionary<string, string> _baseMnemonicLookupTable = new Dictionary<string, string>
{
{ "Zapper X", "zapX" },
{ "Zapper Y", "zapY" },
{ "Paddle", "Pad" },
{ "Pen", "Pen" },
{ "Mouse X", "mX" },
{ "Mouse Y", "mY" },
{ "Lightgun X", "lX" },
{ "Lightgun Y", "lY" },
{ "X Axis", "aX" },
{ "Y Axis", "aY" },
{ "LStick X", "lsX" },
{ "LStick Y", "lsY" },
{ "RStick X", "rsX" },
{ "RStick Y", "rsY" },
{ "Disc Select", "Disc" }
["Zapper X"] = "zapX",
["Zapper Y"] = "zapY",
["Paddle"] = "Pad",
["Pen"] = "Pen",
["Mouse X"] = "mX",
["Mouse Y"] = "mY",
["Lightgun X"] = "lX",
["Lightgun Y"] = "lY",
["X Axis"] = "aX",
["Y Axis"] = "aY",
["LStick X"] = "lsX",
["LStick Y"] = "lsY",
["RStick X"] = "rsX",
["RStick Y"] = "rsY",
["Disc Select"] = "Disc"
};
private readonly Dictionary<string, Dictionary<string, string>> SystemOverrides = new Dictionary<string, Dictionary<string, string>>
private readonly Dictionary<string, Dictionary<string, string>> _systemOverrides = new Dictionary<string, Dictionary<string, string>>
{
["A78"] = new Dictionary<string, string>
{
"A78",
new Dictionary<string, string>
{
{ "VPos", "X" },
{ "HPos", "Y" }
}
},
["VPos"] = "X",
["HPos"] = "Y"
}
};
}
}

View File

@ -8,8 +8,8 @@ namespace BizHawk.Client.Common
{
public class Bk2LogEntryGenerator : ILogEntryGenerator
{
private readonly Bk2MnemonicConstants Mnemonics = new Bk2MnemonicConstants();
private readonly Bk2FloatConstants FloatLookup = new Bk2FloatConstants();
private readonly Bk2MnemonicConstants _mnemonics = new Bk2MnemonicConstants();
private readonly Bk2FloatConstants _floatLookup = new Bk2FloatConstants();
private readonly string _logKey;
private IController _source;
@ -72,11 +72,11 @@ namespace BizHawk.Client.Common
{
if (_source.Definition.BoolButtons.Contains(button))
{
dict.Add(button, Mnemonics[button].ToString());
dict.Add(button, _mnemonics[button].ToString());
}
else if (_source.Definition.FloatControls.Contains(button))
{
dict.Add(button, FloatLookup[button]);
dict.Add(button, _floatLookup[button]);
}
}
}
@ -131,7 +131,7 @@ namespace BizHawk.Client.Common
}
else
{
sb.Append(_source.IsPressed(button) ? Mnemonics[button] : forInputDisplay ? ' ' : '.');
sb.Append(_source.IsPressed(button) ? _mnemonics[button] : forInputDisplay ? ' ' : '.');
}
}
}

View File

@ -178,7 +178,7 @@ namespace BizHawk.Client.Common
bs.PutLump(BinaryStateLump.Subtitles, tw => tw.WriteLine(Subtitles.ToString()));
bs.PutLump(BinaryStateLump.SyncSettings, tw => tw.WriteLine(_syncSettingsJson));
bs.PutLump(BinaryStateLump.Input, tw => WriteInputLog(tw));
bs.PutLump(BinaryStateLump.Input, WriteInputLog);
if (StartsFromSavestate)
{
@ -211,7 +211,7 @@ namespace BizHawk.Client.Common
protected void ClearBeforeLoad()
{
Header.Clear();
_log.Clear();
Log.Clear();
Subtitles.Clear();
Comments.Clear();
_syncSettingsJson = "";

View File

@ -6,8 +6,8 @@ namespace BizHawk.Client.Common
{
public partial class Bk2Movie
{
protected IStringLog _log;
protected string LogKey = "";
protected IStringLog Log { get; set; }
protected string LogKey { get; set; } = "";
public void WriteInputLog(TextWriter writer)
{
@ -24,13 +24,13 @@ namespace BizHawk.Client.Common
if (LoopOffset.HasValue)
{
if (frame < _log.Count)
if (frame < Log.Count)
{
getframe = frame;
}
else
{
getframe = ((frame - LoopOffset.Value) % (_log.Count - LoopOffset.Value)) + LoopOffset.Value;
getframe = ((frame - LoopOffset.Value) % (Log.Count - LoopOffset.Value)) + LoopOffset.Value;
}
}
else
@ -38,7 +38,7 @@ namespace BizHawk.Client.Common
getframe = frame;
}
return _log[getframe];
return Log[getframe];
}
return "";
@ -52,13 +52,13 @@ namespace BizHawk.Client.Common
// We are in record mode so replace the movie log with the one from the savestate
if (!Global.MovieSession.MultiTrack.IsActive)
{
if (Global.Config.EnableBackupMovies && MakeBackup && _log.Count != 0)
if (Global.Config.EnableBackupMovies && MakeBackup && Log.Count != 0)
{
SaveBackup();
MakeBackup = false;
}
_log.Clear();
Log.Clear();
while (true)
{
var line = reader.ReadLine();
@ -102,7 +102,7 @@ namespace BizHawk.Client.Common
}
else if (line[0] == '|')
{
_log.Add(line);
Log.Add(line);
}
}
}
@ -162,21 +162,21 @@ namespace BizHawk.Client.Common
var stateFramei = stateFrame ?? 0;
if (stateFramei > 0 && stateFramei < _log.Count)
if (stateFramei > 0 && stateFramei < Log.Count)
{
if (!Global.Config.VBAStyleMovieLoadState)
{
Truncate(stateFramei);
}
}
else if (stateFramei > _log.Count) // Post movie savestate
else if (stateFramei > Log.Count) // Post movie savestate
{
if (!Global.Config.VBAStyleMovieLoadState)
{
Truncate(_log.Count);
Truncate(Log.Count);
}
_mode = Moviemode.Finished;
Mode = Moviemode.Finished;
}
if (IsCountingRerecords)
@ -243,7 +243,7 @@ namespace BizHawk.Client.Common
stateFrame = newLog.Count; // In case the frame count failed to parse, revert to using the entire state input log
}
if (_log.Count < stateFrame)
if (Log.Count < stateFrame)
{
if (IsFinished)
{
@ -253,14 +253,14 @@ namespace BizHawk.Client.Common
errorMessage = "The savestate is from frame "
+ newLog.Count
+ " which is greater than the current movie length of "
+ _log.Count;
+ Log.Count;
return false;
}
for (var i = 0; i < stateFrame; i++)
{
if (_log[i] != newLog[i])
if (Log[i] != newLog[i])
{
errorMessage = "The savestate input does not match the movie input at frame "
+ (i + 1)
@ -272,18 +272,18 @@ namespace BizHawk.Client.Common
if (stateFrame > newLog.Count) // stateFrame is greater than state input log, so movie finished mode
{
if (_mode == Moviemode.Play || _mode == Moviemode.Finished)
if (Mode == Moviemode.Play || Mode == Moviemode.Finished)
{
_mode = Moviemode.Finished;
Mode = Moviemode.Finished;
return true;
}
return false;
}
if (_mode == Moviemode.Finished)
if (Mode == Moviemode.Finished)
{
_mode = Moviemode.Play;
Mode = Moviemode.Play;
}
return true;
@ -296,7 +296,7 @@ namespace BizHawk.Client.Common
writer.WriteLine(lg.GenerateLogKey());
foreach (var record in _log)
foreach (var record in Log)
{
writer.WriteLine(record);
}

View File

@ -9,41 +9,41 @@ namespace BizHawk.Client.Common
Inactive, Play, Record, Finished
}
protected Moviemode _mode = Moviemode.Inactive;
protected Moviemode Mode { get; set; } = Moviemode.Inactive;
public bool IsActive => _mode != Moviemode.Inactive;
public bool IsActive => Mode != Moviemode.Inactive;
public bool IsPlaying => _mode == Moviemode.Play || _mode == Moviemode.Finished;
public bool IsPlaying => Mode == Moviemode.Play || Mode == Moviemode.Finished;
public bool IsRecording => _mode == Moviemode.Record;
public bool IsRecording => Mode == Moviemode.Record;
public bool IsFinished => _mode == Moviemode.Finished;
public bool IsFinished => Mode == Moviemode.Finished;
public virtual void StartNewRecording()
{
_mode = Moviemode.Record;
if (Global.Config.EnableBackupMovies && MakeBackup && _log.Any())
Mode = Moviemode.Record;
if (Global.Config.EnableBackupMovies && MakeBackup && Log.Any())
{
SaveBackup();
MakeBackup = false;
}
_log.Clear();
Log.Clear();
}
public virtual void StartNewPlayback()
{
_mode = Moviemode.Play;
Mode = Moviemode.Play;
}
public virtual void SwitchToRecord()
{
_mode = Moviemode.Record;
Mode = Moviemode.Record;
}
public virtual void SwitchToPlay()
{
_mode = Moviemode.Play;
Mode = Moviemode.Play;
}
public virtual bool Stop(bool saveChanges = true)
@ -51,7 +51,7 @@ namespace BizHawk.Client.Common
bool saved = false;
if (saveChanges)
{
if (_mode == Moviemode.Record || (IsActive && Changes))
if (Mode == Moviemode.Record || (IsActive && Changes))
{
Save();
saved = true;
@ -59,14 +59,14 @@ namespace BizHawk.Client.Common
}
Changes = false;
_mode = Moviemode.Inactive;
Mode = Moviemode.Inactive;
return saved;
}
public void FinishedMode()
{
_mode = Moviemode.Finished;
Mode = Moviemode.Finished;
}
}
}

View File

@ -6,8 +6,6 @@ namespace BizHawk.Client.Common
{
public partial class Bk2Movie : IMovie
{
protected bool MakeBackup = true;
public Bk2Movie(string filename)
: this()
{
@ -22,14 +20,16 @@ namespace BizHawk.Client.Common
Filename = "";
IsCountingRerecords = true;
_mode = Moviemode.Inactive;
Mode = Moviemode.Inactive;
MakeBackup = true;
Header[HeaderKeys.MOVIEVERSION] = "BizHawk v2.0.0";
_log = StringLogUtil.MakeStringLog();
Log = StringLogUtil.MakeStringLog();
}
protected bool MakeBackup { get; set; }
private string _filename;
public string Filename
@ -70,11 +70,11 @@ namespace BizHawk.Client.Common
return double.PositiveInfinity;
}
return _log.Count;
return Log.Count;
}
}
public int InputLogLength => _log.Count;
public int InputLogLength => Log.Count;
#region Log Editing
@ -82,7 +82,7 @@ namespace BizHawk.Client.Common
{
var lg = LogGeneratorInstance();
lg.SetSource(source);
_log.Add(lg.GenerateLogEntry());
Log.Add(lg.GenerateLogEntry());
Changes = true;
}
@ -90,7 +90,7 @@ namespace BizHawk.Client.Common
{
if (Global.Config.VBAStyleMovieLoadState)
{
if (Global.Emulator.Frame < _log.Count)
if (Global.Emulator.Frame < Log.Count)
{
Truncate(Global.Emulator.Frame);
}
@ -109,9 +109,9 @@ namespace BizHawk.Client.Common
// and it is weird for Truncate to possibly not truncate
if (!Global.MovieSession.MultiTrack.IsActive)
{
if (frame < _log.Count)
if (frame < Log.Count)
{
_log.RemoveRange(frame, _log.Count - frame);
Log.RemoveRange(frame, Log.Count - frame);
Changes = true;
}
}
@ -125,13 +125,13 @@ namespace BizHawk.Client.Common
if (LoopOffset.HasValue)
{
if (frame < _log.Count)
if (frame < Log.Count)
{
getframe = frame;
}
else
{
getframe = ((frame - LoopOffset.Value) % (_log.Count - LoopOffset.Value)) + LoopOffset.Value;
getframe = ((frame - LoopOffset.Value) % (Log.Count - LoopOffset.Value)) + LoopOffset.Value;
}
}
else
@ -144,7 +144,7 @@ namespace BizHawk.Client.Common
Definition = Global.MovieSession.MovieControllerAdapter.Definition
};
adapter.SetControllersAsMnemonic(_log[getframe]);
adapter.SetControllersAsMnemonic(Log[getframe]);
return adapter;
}
@ -172,13 +172,13 @@ namespace BizHawk.Client.Common
protected void SetFrameAt(int frameNum, string frame)
{
if (_log.Count > frameNum)
if (Log.Count > frameNum)
{
_log[frameNum] = frame;
Log[frameNum] = frame;
}
else
{
_log.Add(frame);
Log.Add(frame);
}
}
}

View File

@ -8,8 +8,8 @@ namespace BizHawk.Client.Common
{
public static class StringLogUtil
{
public static bool DefaultToDisk;
public static bool DefaultToAWE;
public static bool DefaultToDisk { get; set; }
public static bool DefaultToAWE { get; set; }
public static IStringLog MakeStringLog()
{
if (DefaultToDisk)
@ -55,23 +55,24 @@ namespace BizHawk.Client.Common
}
/// <summary>
/// A dumb-ish IStringLog with storage on disk with no provision for recovering lost space, except upon Clear()
/// The purpose here is to avoid having too complicated buggy logic or a dependency on sqlite or such.
/// A dumb IStringLog with storage on disk with no provision for recovering lost space, except upon Clear()
/// The purpose here is to avoid having too complicated buggy logic or a dependency on SQLite or such.
/// It should be faster than those alternatives, but wasteful of disk space.
/// It should also be easier to add new IList&lt;string&gt;-like methods than dealing with a database
/// </summary>
internal class StreamStringLog : IStringLog
{
List<long> Offsets = new List<long>();
long cursor = 0;
BinaryWriter bw;
BinaryReader br;
bool mDisk;
private readonly Stream stream;
private readonly List<long> _offsets = new List<long>();
private readonly BinaryWriter _bw;
private readonly BinaryReader _br;
private readonly bool _mDisk;
private long _cursor;
Stream stream;
public StreamStringLog(bool disk)
{
mDisk = disk;
_mDisk = disk;
if (disk)
{
var path = TempFileCleaner.GetTempFilename("movieOnDisk");
@ -82,13 +83,13 @@ namespace BizHawk.Client.Common
stream = new AWEMemoryStream();
}
bw = new BinaryWriter(stream);
br = new BinaryReader(stream);
_bw = new BinaryWriter(stream);
_br = new BinaryReader(stream);
}
public IStringLog Clone()
{
StreamStringLog ret = new StreamStringLog(mDisk); // doesnt necessarily make sense to copy the mDisk value, they could be designated for different targets...
StreamStringLog ret = new StreamStringLog(_mDisk); // doesnt 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]);
@ -102,52 +103,52 @@ namespace BizHawk.Client.Common
stream.Dispose();
}
public int Count => Offsets.Count;
public int Count => _offsets.Count;
public void Clear()
{
stream.SetLength(0);
Offsets.Clear();
cursor = 0;
_offsets.Clear();
_cursor = 0;
}
public void Add(string str)
{
stream.Position = stream.Length;
Offsets.Add(stream.Position);
bw.Write(str);
bw.Flush();
_offsets.Add(stream.Position);
_bw.Write(str);
_bw.Flush();
}
public void RemoveAt(int index)
{
// no garbage collection in the disk file... oh well.
Offsets.RemoveAt(index);
_offsets.RemoveAt(index);
}
public string this[int index]
{
get
{
stream.Position = Offsets[index];
return br.ReadString();
stream.Position = _offsets[index];
return _br.ReadString();
}
set
{
stream.Position = stream.Length;
Offsets[index] = stream.Position;
bw.Write(value);
bw.Flush();
_offsets[index] = stream.Position;
_bw.Write(value);
_bw.Flush();
}
}
public void Insert(int index, string val)
{
stream.Position = stream.Length;
Offsets.Insert(index, stream.Position);
bw.Write(val);
bw.Flush();
_offsets.Insert(index, stream.Position);
_bw.Write(val);
_bw.Flush();
}
public void InsertRange(int index, IEnumerable<string> collection)
@ -168,35 +169,37 @@ namespace BizHawk.Client.Common
private class Enumerator : IEnumerator<string>
{
public StreamStringLog log;
int index = -1;
public string Current { get { return log[index]; } }
object System.Collections.IEnumerator.Current { get { return log[index]; } }
public StreamStringLog Log { get; set; }
private int _index = -1;
public string Current => Log[_index];
object System.Collections.IEnumerator.Current => Log[_index];
bool System.Collections.IEnumerator.MoveNext()
{
index++;
if (index >= log.Count)
_index++;
if (_index >= Log.Count)
{
index = log.Count;
_index = Log.Count;
return false;
}
return true;
}
void System.Collections.IEnumerator.Reset() { index = -1; }
void System.Collections.IEnumerator.Reset() { _index = -1; }
public void Dispose() { }
}
IEnumerator<string> IEnumerable<string>.GetEnumerator()
{
return new Enumerator { log = this };
return new Enumerator { Log = this };
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new Enumerator { log = this };
return new Enumerator { Log = this };
}
public void RemoveRange(int index, int count)

View File

@ -487,7 +487,7 @@ namespace BizHawk.Client.Common
for (int player = 1; player <= BkmMnemonicConstants.Players[ControlType]; player++)
{
int srcindex = (player - 1) * (BkmMnemonicConstants.Buttons[ControlType].Count + BkmMnemonicConstants.Analogs[ControlType].Count * 4 + 1 + 1);
int srcindex = (player - 1) * (BkmMnemonicConstants.Buttons[ControlType].Count + (BkmMnemonicConstants.Analogs[ControlType].Count * 4) + 1 + 1);
if (mnemonic.Length < srcindex + 3 + BkmMnemonicConstants.Buttons[ControlType].Count - 1)
{

View File

@ -45,7 +45,7 @@ namespace BizHawk.Client.Common
}
else if (line.ToLower().StartsWith("emuversion"))
{
Result.Movie.Comments.Add($"{EMULATIONORIGIN} {emulator} version {ParseHeader(line, "emuVersion")}");
Result.Movie.Comments.Add($"{Emulationorigin} {emulator} version {ParseHeader(line, "emuVersion")}");
}
else if (line.ToLower().StartsWith("version"))
{
@ -57,7 +57,7 @@ namespace BizHawk.Client.Common
}
else
{
Result.Movie.Comments.Add(MOVIEORIGIN + " .fm2 version 3");
Result.Movie.Comments.Add(Movieorigin + " .fm2 version 3");
}
}
else if (line.ToLower().StartsWith("romfilename"))

View File

@ -11,25 +11,25 @@ namespace BizHawk.Client.Common
public abstract class MovieImporter : IMovieImport
{
public const string COMMENT = "comment";
public const string COREORIGIN = "CoreOrigin";
public const string Comment = "comment";
public const string Coreorigin = "CoreOrigin";
public const string CRC16 = "CRC16";
public const string CRC32 = "CRC32";
public const string EMULATIONORIGIN = "emuOrigin";
public const string GAMECODE = "GameCode";
public const string INTERNALCHECKSUM = "InternalChecksum";
public const string JAPAN = "Japan";
public const string MD5 = "MD5";
public const string MOVIEORIGIN = "MovieOrigin";
public const string PORT1 = "port1";
public const string PORT2 = "port2";
public const string PROJECTID = "ProjectID";
protected const string Emulationorigin = "emuOrigin";
public const string Gamecode = "GameCode";
public const string InternalChecksum = "InternalChecksum";
public const string Japan = "Japan";
protected const string MD5 = "MD5";
protected const string Movieorigin = "MovieOrigin";
public const string Port1 = "port1";
public const string Port2 = "port2";
public const string ProjectId = "ProjectID";
public const string SHA256 = "SHA256";
public const string SUPERGAMEBOYMODE = "SuperGameBoyMode";
public const string STARTSECOND = "StartSecond";
public const string STARTSUBSECOND = "StartSubSecond";
public const string SYNCHACK = "SyncHack";
public const string UNITCODE = "UnitCode";
public const string SuperGameboyMode = "SuperGameBoyMode";
public const string StartSecond = "StartSecond";
public const string StartSubSecond = "StartSubSecond";
public const string SyncHack = "SyncHack";
public const string UnitCode = "UnitCode";
public ImportResult Import(string path)
{
@ -49,9 +49,9 @@ namespace BizHawk.Client.Common
return Result;
}
protected ImportResult Result = new ImportResult();
protected ImportResult Result { get; } = new ImportResult();
protected FileInfo SourceFile;
protected FileInfo SourceFile { get; private set; }
protected abstract void RunImport();

View File

@ -22,9 +22,9 @@ namespace BizHawk.Client.Common
{
var info = ParseHeader(movie, "PJM ", br);
fs.Seek(info.controllerDataOffset, SeekOrigin.Begin);
fs.Seek(info.ControllerDataOffset, SeekOrigin.Begin);
if (info.binaryFormat)
if (info.BinaryFormat)
{
ParseBinaryInputLog(br, movie, info);
}
@ -87,7 +87,7 @@ namespace BizHawk.Client.Common
if ((flags & 0x40) != 0)
{
info.binaryFormat = false;
info.BinaryFormat = false;
}
if ((flags & 0x80) != 0 || (flags2 & 0x01) != 0)
@ -103,13 +103,13 @@ namespace BizHawk.Client.Common
// to mean no controller present.
case 0:
case 8:
info.player1Type = OctoshockDll.ePeripheralType.None;
info.Player1Type = OctoshockDll.ePeripheralType.None;
break;
case 4:
info.player1Type = OctoshockDll.ePeripheralType.Pad;
info.Player1Type = OctoshockDll.ePeripheralType.Pad;
break;
case 7:
info.player1Type = OctoshockDll.ePeripheralType.DualShock;
info.Player1Type = OctoshockDll.ePeripheralType.DualShock;
break;
default:
Result.Errors.Add("Movie has unrecognised controller type for Player 1.");
@ -121,13 +121,13 @@ namespace BizHawk.Client.Common
{
case 0:
case 8:
info.player1Type = OctoshockDll.ePeripheralType.None;
info.Player1Type = OctoshockDll.ePeripheralType.None;
break;
case 4:
info.player1Type = OctoshockDll.ePeripheralType.Pad;
info.Player1Type = OctoshockDll.ePeripheralType.Pad;
break;
case 7:
info.player1Type = OctoshockDll.ePeripheralType.DualShock;
info.Player1Type = OctoshockDll.ePeripheralType.DualShock;
break;
default:
Result.Errors.Add("Movie has unrecognised controller type for Player 2.");
@ -140,11 +140,11 @@ namespace BizHawk.Client.Common
{
Devices8 = new[]
{
info.player1Type,
info.Player1Type,
OctoshockDll.ePeripheralType.None,
OctoshockDll.ePeripheralType.None,
OctoshockDll.ePeripheralType.None,
info.player2Type,
info.Player2Type,
OctoshockDll.ePeripheralType.None,
OctoshockDll.ePeripheralType.None,
OctoshockDll.ePeripheralType.None
@ -162,7 +162,7 @@ namespace BizHawk.Client.Common
};
movie.SyncSettingsJson = JsonConvert.SerializeObject(new { o = (object)syncsettings }, jsonSettings);
info.frameCount = br.ReadUInt32();
info.FrameCount = br.ReadUInt32();
uint rerecordCount = br.ReadUInt32();
movie.HeaderEntries[HeaderKeys.RERECORDS] = rerecordCount.ToString();
@ -176,14 +176,14 @@ namespace BizHawk.Client.Common
// so not so useful.
br.ReadBytes(20);
info.controllerDataOffset = br.ReadUInt32();
info.ControllerDataOffset = br.ReadUInt32();
uint authorNameLength = br.ReadUInt32();
char[] authorName = br.ReadChars((int)authorNameLength);
movie.HeaderEntries[HeaderKeys.AUTHOR] = new string(authorName);
info.parseSuccessful = true;
info.ParseSuccessful = true;
return info;
}
@ -193,9 +193,9 @@ namespace BizHawk.Client.Common
SimpleController controllers = new SimpleController();
settings.FIOConfig.Devices8 = new[]
{
info.player1Type,
info.Player1Type,
OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None,
info.player2Type,
info.Player2Type,
OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None
};
controllers.Definition = Octoshock.CreateControllerDefinition(settings);
@ -209,9 +209,9 @@ namespace BizHawk.Client.Common
bool isCdTrayOpen = false;
int cdNumber = 1;
for (int frame = 0; frame < info.frameCount; ++frame)
for (int frame = 0; frame < info.FrameCount; ++frame)
{
if (info.player1Type != OctoshockDll.ePeripheralType.None)
if (info.Player1Type != OctoshockDll.ePeripheralType.None)
{
ushort controllerState = br.ReadUInt16();
@ -228,7 +228,7 @@ namespace BizHawk.Client.Common
}
}
if (info.player1Type == OctoshockDll.ePeripheralType.DualShock)
if (info.Player1Type == OctoshockDll.ePeripheralType.DualShock)
{
controllers["P1 L3"] = (controllerState & 0x2) != 0;
controllers["P1 R3"] = (controllerState & 0x4) != 0;
@ -241,7 +241,7 @@ namespace BizHawk.Client.Common
}
}
if (info.player2Type != OctoshockDll.ePeripheralType.None)
if (info.Player2Type != OctoshockDll.ePeripheralType.None)
{
ushort controllerState = br.ReadUInt16();
for (int button = 0; button < buttons.Length; button++)
@ -253,7 +253,7 @@ namespace BizHawk.Client.Common
}
}
if (info.player2Type == OctoshockDll.ePeripheralType.DualShock)
if (info.Player2Type == OctoshockDll.ePeripheralType.DualShock)
{
Tuple<string, float> leftX = new Tuple<string, float>("P2 LStick X", (float)br.ReadByte());
Tuple<string, float> leftY = new Tuple<string, float>("P2 LStick Y", (float)br.ReadByte());
@ -304,9 +304,9 @@ namespace BizHawk.Client.Common
SimpleController controllers = new SimpleController();
settings.FIOConfig.Devices8 = new[]
{
info.player1Type,
info.Player1Type,
OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None,
info.player2Type,
info.Player2Type,
OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None
};
controllers.Definition = Octoshock.CreateControllerDefinition(settings);
@ -320,15 +320,15 @@ namespace BizHawk.Client.Common
bool isCdTrayOpen = false;
int cdNumber = 1;
for (int frame = 0; frame < info.frameCount; ++frame)
for (int frame = 0; frame < info.FrameCount; ++frame)
{
if (info.player1Type != OctoshockDll.ePeripheralType.None)
if (info.Player1Type != OctoshockDll.ePeripheralType.None)
{
// As L3 and R3 don't exist on a standard gamepad, handle them separately later. Unfortunately
// due to the layout, we handle select separately too first.
controllers["P1 Select"] = br.ReadChar() != '.';
if (info.player1Type == OctoshockDll.ePeripheralType.DualShock)
if (info.Player1Type == OctoshockDll.ePeripheralType.DualShock)
{
controllers["P1 L3"] = br.ReadChar() != '.';
controllers["P1 R3"] = br.ReadChar() != '.';
@ -339,7 +339,7 @@ namespace BizHawk.Client.Common
controllers["P1 " + buttons[button]] = br.ReadChar() != '.';
}
if (info.player1Type == OctoshockDll.ePeripheralType.DualShock)
if (info.Player1Type == OctoshockDll.ePeripheralType.DualShock)
{
// The analog controls are encoded as four space-separated numbers with a leading space
string leftXRaw = new string(br.ReadChars(4)).Trim();
@ -359,13 +359,13 @@ namespace BizHawk.Client.Common
// Each controller is terminated with a pipeline.
br.ReadChar();
if (info.player2Type != OctoshockDll.ePeripheralType.None)
if (info.Player2Type != OctoshockDll.ePeripheralType.None)
{
// As L3 and R3 don't exist on a standard gamepad, handle them separately later. Unfortunately
// due to the layout, we handle select separately too first.
controllers["P2 Select"] = br.ReadChar() != '.';
if (info.player2Type == OctoshockDll.ePeripheralType.DualShock)
if (info.Player2Type == OctoshockDll.ePeripheralType.DualShock)
{
controllers["P2 L3"] = br.ReadChar() != '.';
controllers["P2 R3"] = br.ReadChar() != '.';
@ -376,7 +376,7 @@ namespace BizHawk.Client.Common
controllers["P2 " + buttons[button]] = br.ReadChar() != '.';
}
if (info.player2Type == OctoshockDll.ePeripheralType.DualShock)
if (info.Player2Type == OctoshockDll.ePeripheralType.DualShock)
{
// The analog controls are encoded as four space-separated numbers with a leading space
string leftXRaw = new string(br.ReadChars(4)).Trim();
@ -435,13 +435,12 @@ namespace BizHawk.Client.Common
protected class MiscHeaderInfo
{
public bool binaryFormat = true;
public uint controllerDataOffset;
public uint frameCount;
public OctoshockDll.ePeripheralType player1Type;
public OctoshockDll.ePeripheralType player2Type;
public bool parseSuccessful = false;
public bool BinaryFormat { get; set; } = true;
public uint ControllerDataOffset { get; set; }
public uint FrameCount { get; set; }
public OctoshockDll.ePeripheralType Player1Type { get; set; }
public OctoshockDll.ePeripheralType Player2Type { get; set; }
public bool ParseSuccessful { get; set; }
}
}
}

View File

@ -23,9 +23,9 @@ namespace BizHawk.Client.Common.Movie.Import
{
var info = ParseHeader(movie, "PXM ", br);
fs.Seek(info.controllerDataOffset, SeekOrigin.Begin);
fs.Seek(info.ControllerDataOffset, SeekOrigin.Begin);
if (info.binaryFormat)
if (info.BinaryFormat)
{
ParseBinaryInputLog(br, movie, info);
}

View File

@ -39,7 +39,7 @@ namespace BizHawk.Client.Common
return _state;
}
return _manager.ndbdatabase.FetchAll(_id.ToString());
return _manager.NdbDatabase.FetchAll(_id.ToString());
}
set
@ -80,7 +80,7 @@ namespace BizHawk.Client.Common
return;
}
_manager.ndbdatabase.Store(_id.ToString(), _state, 0, _state.Length);
_manager.NdbDatabase.Store(_id.ToString(), _state, 0, _state.Length);
_state = null;
}
@ -92,8 +92,8 @@ namespace BizHawk.Client.Common
}
string key = _id.ToString();
_state = _manager.ndbdatabase.FetchAll(key);
_manager.ndbdatabase.Release(key);
_state = _manager.NdbDatabase.FetchAll(key);
_manager.NdbDatabase.Release(key);
}
public void Dispose()
@ -103,7 +103,7 @@ namespace BizHawk.Client.Common
return;
}
_manager.ndbdatabase.Release(_id.ToString());
_manager.NdbDatabase.Release(_id.ToString());
}
}
}

View File

@ -9,27 +9,26 @@ namespace BizHawk.Client.Common
public class TasLagLog
{
// TODO: Change this into a regular list.
private List<bool> LagLog = new List<bool>();
private List<bool> WasLag = new List<bool>();
private List<bool> _lagLog = new List<bool>();
private List<bool> _wasLag = new List<bool>();
public bool? this[int frame]
{
get
{
if (frame < LagLog.Count)
if (frame < _lagLog.Count)
{
if (frame < 0)
{
return null;
}
return LagLog[frame];
return _lagLog[frame];
}
if (frame == Global.Emulator.Frame && frame == LagLog.Count)
if (frame == Global.Emulator.Frame && frame == _lagLog.Count)
{
// LagLog[frame] = Global.Emulator.AsInputPollable().IsLagFrame; // Note: Side effects!
////LagLog[frame] = Global.Emulator.AsInputPollable().IsLagFrame; // Note: Side effects!
return Global.Emulator.AsInputPollable().IsLagFrame;
}
@ -40,7 +39,7 @@ namespace BizHawk.Client.Common
{
if (!value.HasValue)
{
LagLog.RemoveAt(frame);
_lagLog.RemoveAt(frame);
return;
}
@ -49,61 +48,61 @@ namespace BizHawk.Client.Common
return; // Nothing to do
}
if (frame > LagLog.Count)
if (frame > _lagLog.Count)
{
System.Diagnostics.Debug.Print("Lag Log error. f" + frame + ", log: " + LagLog.Count);
System.Diagnostics.Debug.Print("Lag Log error. f" + frame + ", log: " + _lagLog.Count);
return; // Can this break anything?
}
bool wasValue;
if (frame < LagLog.Count)
if (frame < _lagLog.Count)
{
wasValue = LagLog[frame];
wasValue = _lagLog[frame];
}
else if (frame == WasLag.Count)
else if (frame == _wasLag.Count)
{
wasValue = value.Value;
}
else
{
wasValue = WasLag[frame];
wasValue = _wasLag[frame];
}
if (frame == WasLag.Count)
if (frame == _wasLag.Count)
{
WasLag.Add(wasValue);
_wasLag.Add(wasValue);
}
else
{
WasLag[frame] = wasValue;
_wasLag[frame] = wasValue;
}
if (frame != 0)
{
WasLag[frame - 1] = LagLog[frame - 1];
_wasLag[frame - 1] = _lagLog[frame - 1];
}
if (frame >= LagLog.Count)
if (frame >= _lagLog.Count)
{
LagLog.Add(value.Value);
_lagLog.Add(value.Value);
}
else
{
LagLog[frame] = value.Value;
_lagLog[frame] = value.Value;
}
}
}
public void Clear()
{
LagLog.Clear();
_lagLog.Clear();
}
public bool RemoveFrom(int frame)
{
if (LagLog.Count > frame && frame >= 0)
if (_lagLog.Count > frame && frame >= 0)
{
LagLog.RemoveRange(frame + 1, LagLog.Count - frame - 1);
_lagLog.RemoveRange(frame + 1, _lagLog.Count - frame - 1);
return true;
}
@ -112,41 +111,41 @@ namespace BizHawk.Client.Common
public void RemoveHistoryAt(int frame)
{
WasLag.RemoveAt(frame);
_wasLag.RemoveAt(frame);
}
public void InsertHistoryAt(int frame, bool isLag)
{
// LagLog was invalidated when the frame was inserted
if (frame <= LagLog.Count)
if (frame <= _lagLog.Count)
{
LagLog.Insert(frame, isLag);
_lagLog.Insert(frame, isLag);
}
WasLag.Insert(frame, isLag);
_wasLag.Insert(frame, isLag);
}
public void Save(BinaryWriter bw)
{
bw.Write((byte)1); // New saving format.
bw.Write(LagLog.Count);
bw.Write(WasLag.Count);
for (int i = 0; i < LagLog.Count; i++)
bw.Write(_lagLog.Count);
bw.Write(_wasLag.Count);
for (int i = 0; i < _lagLog.Count; i++)
{
bw.Write(LagLog[i]);
bw.Write(WasLag[i]);
bw.Write(_lagLog[i]);
bw.Write(_wasLag[i]);
}
for (int i = LagLog.Count; i < WasLag.Count; i++)
for (int i = _lagLog.Count; i < _wasLag.Count; i++)
{
bw.Write(WasLag[i]);
bw.Write(_wasLag[i]);
}
}
public void Load(BinaryReader br)
{
LagLog.Clear();
WasLag.Clear();
_lagLog.Clear();
_wasLag.Clear();
////if (br.BaseStream.Length > 0)
////{ BaseStream.Length does not return the expected value.
int formatVersion = br.ReadByte();
@ -157,8 +156,8 @@ namespace BizHawk.Client.Common
for (int i = 0; i < length; i++)
{
br.ReadInt32();
LagLog.Add(br.ReadBoolean());
WasLag.Add(LagLog.Last());
_lagLog.Add(br.ReadBoolean());
_wasLag.Add(_lagLog.Last());
}
}
else if (formatVersion == 1)
@ -167,13 +166,13 @@ namespace BizHawk.Client.Common
int lenWas = br.ReadInt32();
for (int i = 0; i < length; i++)
{
LagLog.Add(br.ReadBoolean());
WasLag.Add(br.ReadBoolean());
_lagLog.Add(br.ReadBoolean());
_wasLag.Add(br.ReadBoolean());
}
for (int i = length; i < lenWas; i++)
{
WasLag.Add(br.ReadBoolean());
_wasLag.Add(br.ReadBoolean());
}
}
////}
@ -181,14 +180,14 @@ namespace BizHawk.Client.Common
public bool? History(int frame)
{
if (frame < WasLag.Count)
if (frame < _wasLag.Count)
{
if (frame < 0)
{
return null;
}
return WasLag[frame];
return _wasLag[frame];
}
return null;
@ -198,12 +197,12 @@ namespace BizHawk.Client.Common
{
get
{
if (LagLog.Count == 0)
if (_lagLog.Count == 0)
{
return 0;
}
return LagLog.Count - 1;
return _lagLog.Count - 1;
}
}
@ -211,21 +210,21 @@ namespace BizHawk.Client.Common
{
return new TasLagLog
{
LagLog = LagLog.ToList(),
WasLag = WasLag.ToList()
_lagLog = _lagLog.ToList(),
_wasLag = _wasLag.ToList()
};
}
public void FromLagLog(TasLagLog log)
{
LagLog = log.LagLog.ToList();
WasLag = log.WasLag.ToList();
_lagLog = log._lagLog.ToList();
_wasLag = log._wasLag.ToList();
}
public void StartFromFrame(int index)
{
LagLog.RemoveRange(0, index);
WasLag.RemoveRange(0, index);
_lagLog.RemoveRange(0, index);
_wasLag.RemoveRange(0, index);
}
}
}

View File

@ -38,7 +38,7 @@ namespace BizHawk.Client.Common
bool endBatch = ChangeLog.BeginNewBatch("Truncate Movie: " + frame, true);
ChangeLog.AddGeneralUndo(frame, InputLogLength - 1);
if (frame < _log.Count - 1)
if (frame < Log.Count - 1)
{
Changes = true;
}
@ -91,7 +91,7 @@ namespace BizHawk.Client.Common
bool endBatch = ChangeLog.BeginNewBatch("Remove Frame: " + frame, true);
ChangeLog.AddGeneralUndo(frame, InputLogLength - 1);
_log.RemoveAt(frame);
Log.RemoveAt(frame);
if (BindMarkersToInput)
{
bool wasRecording = ChangeLog.IsRecording;
@ -138,9 +138,9 @@ namespace BizHawk.Client.Common
foreach (var frame in frames.OrderByDescending(f => f)) // Removing them in reverse order allows us to remove by index;
{
if (frame < _log.Count)
if (frame < Log.Count)
{
_log.RemoveAt(frame);
Log.RemoveAt(frame);
}
if (BindMarkersToInput) // TODO: This is slow, is there a better way to do it?
@ -186,7 +186,7 @@ namespace BizHawk.Client.Common
for (int i = removeUpTo - 1; i >= removeStart; i--)
{
_log.RemoveAt(i);
Log.RemoveAt(i);
}
if (BindMarkersToInput)
@ -228,7 +228,7 @@ namespace BizHawk.Client.Common
bool endBatch = ChangeLog.BeginNewBatch("Insert Frame: " + frame, true);
ChangeLog.AddGeneralUndo(frame, InputLogLength);
_log.Insert(frame, inputState);
Log.Insert(frame, inputState);
Changes = true;
InvalidateAfter(frame);
@ -261,7 +261,7 @@ namespace BizHawk.Client.Common
bool endBatch = ChangeLog.BeginNewBatch("Insert Frame: " + frame, true);
ChangeLog.AddGeneralUndo(frame, InputLogLength + inputLog.Count() - 1);
_log.InsertRange(frame, inputLog);
Log.InsertRange(frame, inputLog);
Changes = true;
InvalidateAfter(frame);
@ -311,22 +311,22 @@ namespace BizHawk.Client.Common
var lg = LogGeneratorInstance();
var states = inputStates.ToList();
if (_log.Count < states.Count + frame)
if (Log.Count < states.Count + frame)
{
ExtendMovieForEdit(states.Count + frame - _log.Count);
ExtendMovieForEdit(states.Count + frame - Log.Count);
}
ChangeLog.AddGeneralUndo(frame, frame + inputStates.Count() - 1, "Copy Over Input: " + frame);
for (int i = 0; i < states.Count; i++)
{
if (_log.Count <= frame + i)
if (Log.Count <= frame + i)
{
break;
}
lg.SetSource(states[i]);
_log[frame + i] = lg.GenerateLogEntry();
Log[frame + i] = lg.GenerateLogEntry();
}
ChangeLog.EndBatch();
@ -344,14 +344,14 @@ namespace BizHawk.Client.Common
var lg = LogGeneratorInstance();
lg.SetSource(Global.MovieSession.MovieControllerInstance());
if (frame > _log.Count())
if (frame > Log.Count())
{
frame = _log.Count();
frame = Log.Count();
}
for (int i = 0; i < count; i++)
{
_log.Insert(frame, lg.EmptyEntry);
Log.Insert(frame, lg.EmptyEntry);
}
if (BindMarkersToInput)
@ -380,7 +380,7 @@ namespace BizHawk.Client.Common
ChangeLog.EndBatch();
}
if (Global.Emulator.Frame < _log.Count) // Don't stay in recording mode? Fixes TAStudio recording after paint inserting.
if (Global.Emulator.Frame < Log.Count) // Don't stay in recording mode? Fixes TAStudio recording after paint inserting.
{
SwitchToPlay();
}
@ -399,7 +399,7 @@ namespace BizHawk.Client.Common
for (int i = 0; i < numFrames; i++)
{
_log.Add(lg.GenerateLogEntry());
Log.Add(lg.GenerateLogEntry());
}
Changes = true;
@ -410,7 +410,7 @@ namespace BizHawk.Client.Common
ChangeLog.EndBatch();
}
if (Global.Emulator.Frame < _log.Count) // Don't stay in recording mode? Fixes TAStudio recording after paint inserting.
if (Global.Emulator.Frame < Log.Count) // Don't stay in recording mode? Fixes TAStudio recording after paint inserting.
{
SwitchToPlay();
}
@ -418,9 +418,9 @@ namespace BizHawk.Client.Common
public void ToggleBoolState(int frame, string buttonName)
{
if (frame >= _log.Count) // Insert blank frames up to this point
if (frame >= Log.Count) // Insert blank frames up to this point
{
ExtendMovieForEdit(frame - _log.Count + 1);
ExtendMovieForEdit(frame - Log.Count + 1);
}
var adapter = GetInputState(frame) as Bk2ControllerAdapter;
@ -428,7 +428,7 @@ namespace BizHawk.Client.Common
var lg = LogGeneratorInstance();
lg.SetSource(adapter);
_log[frame] = lg.GenerateLogEntry();
Log[frame] = lg.GenerateLogEntry();
Changes = true;
InvalidateAfter(frame);
@ -437,9 +437,9 @@ namespace BizHawk.Client.Common
public void SetBoolState(int frame, string buttonName, bool val)
{
if (frame >= _log.Count) // Insert blank frames up to this point
if (frame >= Log.Count) // Insert blank frames up to this point
{
ExtendMovieForEdit(frame - _log.Count + 1);
ExtendMovieForEdit(frame - Log.Count + 1);
}
var adapter = GetInputState(frame) as Bk2ControllerAdapter;
@ -448,7 +448,7 @@ namespace BizHawk.Client.Common
var lg = LogGeneratorInstance();
lg.SetSource(adapter);
_log[frame] = lg.GenerateLogEntry();
Log[frame] = lg.GenerateLogEntry();
if (old != val)
{
@ -460,9 +460,9 @@ namespace BizHawk.Client.Common
public void SetBoolStates(int frame, int count, string buttonName, bool val)
{
if (frame + count >= _log.Count) // Insert blank frames up to this point
if (frame + count >= Log.Count) // Insert blank frames up to this point
{
ExtendMovieForEdit(frame - _log.Count + 1);
ExtendMovieForEdit(frame - Log.Count + 1);
}
ChangeLog.AddGeneralUndo(frame, frame + count - 1, "Set " + buttonName + "(" + (val ? "On" : "Off") + "): " + frame + "-" + (frame + count - 1));
@ -476,7 +476,7 @@ namespace BizHawk.Client.Common
var lg = LogGeneratorInstance();
lg.SetSource(adapter);
_log[frame + i] = lg.GenerateLogEntry();
Log[frame + i] = lg.GenerateLogEntry();
if (changed == -1 && old != val)
{
@ -495,9 +495,9 @@ namespace BizHawk.Client.Common
public void SetFloatState(int frame, string buttonName, float val)
{
if (frame >= _log.Count) // Insert blank frames up to this point
if (frame >= Log.Count) // Insert blank frames up to this point
{
ExtendMovieForEdit(frame - _log.Count + 1);
ExtendMovieForEdit(frame - Log.Count + 1);
}
var adapter = GetInputState(frame) as Bk2ControllerAdapter;
@ -506,7 +506,7 @@ namespace BizHawk.Client.Common
var lg = LogGeneratorInstance();
lg.SetSource(adapter);
_log[frame] = lg.GenerateLogEntry();
Log[frame] = lg.GenerateLogEntry();
if (old != val)
{
@ -518,9 +518,9 @@ namespace BizHawk.Client.Common
public void SetFloatStates(int frame, int count, string buttonName, float val)
{
if (frame + count >= _log.Count) // Insert blank frames up to this point
if (frame + count >= Log.Count) // Insert blank frames up to this point
{
ExtendMovieForEdit(frame - _log.Count + 1);
ExtendMovieForEdit(frame - Log.Count + 1);
}
ChangeLog.AddGeneralUndo(frame, frame + count - 1, "Set " + buttonName + "(" + val + "): " + frame + "-" + (frame + count - 1));
@ -534,7 +534,7 @@ namespace BizHawk.Client.Common
var lg = LogGeneratorInstance();
lg.SetSource(adapter);
_log[frame + i] = lg.GenerateLogEntry();
Log[frame + i] = lg.GenerateLogEntry();
if (changed == -1 && old != val)
{

View File

@ -6,10 +6,21 @@ namespace BizHawk.Client.Common
{
public class TasMovieChangeLog
{
private readonly List<List<IMovieAction>> History;
public List<string> Names;
public int UndoIndex = -1;
public TasMovieChangeLog(TasMovie movie)
{
_history = new List<List<IMovieAction>>();
_movie = movie;
}
private readonly List<List<IMovieAction>> _history = new List<List<IMovieAction>>();
private readonly TasMovie _movie;
private int _maxSteps = 100;
private int _totalSteps;
private bool _recordingBatch;
public List<string> Names { get; } = new List<string>();
public int UndoIndex { get; private set; } = -1;
public int MaxSteps
{
@ -21,46 +32,35 @@ namespace BizHawk.Client.Common
set
{
_maxSteps = value;
if (History.Count > value)
if (_history.Count > value)
{
if (History.Count <= value)
if (_history.Count <= value)
{
ClearLog();
}
else
{
ClearLog(History.Count - value);
ClearLog(_history.Count - value);
}
}
}
}
private int _totalSteps = 0;
private bool RecordingBatch = false;
/// <summary>
/// Gets or sets a value indicating whether the movie is in recording mode
/// This is not intended to turn off the ChangeLog, but to disable the normal recording process.
/// Use this to manually control the ChangeLog. (Useful for when you are making lots of
/// </summary>
public bool IsRecording = true;
public TasMovie Movie;
public TasMovieChangeLog(TasMovie movie)
{
History = new List<List<IMovieAction>>();
Names = new List<string>();
Movie = movie;
}
public bool IsRecording { get; set; } = true;
public void ClearLog(int upTo = -1)
{
if (upTo == -1)
{
upTo = History.Count;
upTo = _history.Count;
}
History.RemoveRange(0, upTo);
_history.RemoveRange(0, upTo);
Names.RemoveRange(0, upTo);
UndoIndex -= upTo;
if (UndoIndex < -1)
@ -68,25 +68,25 @@ namespace BizHawk.Client.Common
UndoIndex = -1;
}
if (History.Count == 0)
if (_history.Count == 0)
{
RecordingBatch = false;
_recordingBatch = false;
}
}
private void TruncateLog(int from)
{
History.RemoveRange(from, History.Count - from);
_history.RemoveRange(from, _history.Count - from);
Names.RemoveRange(from, Names.Count - from);
if (UndoIndex < History.Count - 1)
if (UndoIndex < _history.Count - 1)
{
UndoIndex = History.Count - 1;
UndoIndex = _history.Count - 1;
}
if (RecordingBatch)
if (_recordingBatch)
{
RecordingBatch = false;
_recordingBatch = false;
BeginNewBatch();
}
}
@ -106,7 +106,7 @@ namespace BizHawk.Client.Common
}
bool ret = true;
if (RecordingBatch)
if (_recordingBatch)
{
if (keepOldBatch)
{
@ -123,7 +123,7 @@ namespace BizHawk.Client.Common
ret = AddMovieAction(name);
}
RecordingBatch = true;
_recordingBatch = true;
return ret;
}
@ -134,16 +134,16 @@ namespace BizHawk.Client.Common
/// </summary>
public void EndBatch()
{
if (!IsRecording || !RecordingBatch)
if (!IsRecording || !_recordingBatch)
{
return;
}
RecordingBatch = false;
List<IMovieAction> last = History.Last();
_recordingBatch = false;
List<IMovieAction> last = _history.Last();
if (last.Count == 0) // Remove batch if it's empty.
{
History.RemoveAt(History.Count - 1);
_history.RemoveAt(_history.Count - 1);
Names.RemoveAt(Names.Count - 1);
UndoIndex--;
}
@ -161,22 +161,22 @@ namespace BizHawk.Client.Common
{
if (UndoIndex == -1)
{
return Movie.InputLogLength;
return _movie.InputLogLength;
}
List<IMovieAction> batch = History[UndoIndex];
List<IMovieAction> batch = _history[UndoIndex];
for (int i = batch.Count - 1; i >= 0; i--)
{
batch[i].Undo(Movie);
batch[i].Undo(_movie);
}
UndoIndex--;
RecordingBatch = false;
_recordingBatch = false;
if (batch.All(a => a.GetType() == typeof(MovieActionMarker)))
{
return Movie.InputLogLength;
return _movie.InputLogLength;
}
return PreviousUndoFrame;
@ -188,30 +188,30 @@ namespace BizHawk.Client.Common
/// <returns>Returns the frame which the movie needs to rewind to.</returns>
public int Redo()
{
if (UndoIndex == History.Count - 1)
if (UndoIndex == _history.Count - 1)
{
return Movie.InputLogLength;
return _movie.InputLogLength;
}
UndoIndex++;
List<IMovieAction> batch = History[UndoIndex];
List<IMovieAction> batch = _history[UndoIndex];
foreach (IMovieAction b in batch)
{
b.Redo(Movie);
b.Redo(_movie);
}
RecordingBatch = false;
_recordingBatch = false;
if (batch.All(a => a.GetType() == typeof(MovieActionMarker)))
{
return Movie.InputLogLength;
return _movie.InputLogLength;
}
return PreviousRedoFrame;
}
public bool CanUndo => UndoIndex > -1;
public bool CanRedo => UndoIndex < History.Count - 1;
public bool CanRedo => UndoIndex < _history.Count - 1;
public string NextUndoStepName
{
@ -230,17 +230,17 @@ namespace BizHawk.Client.Common
{
get
{
if (UndoIndex == History.Count - 1)
if (UndoIndex == _history.Count - 1)
{
return Movie.InputLogLength;
return _movie.InputLogLength;
}
if (History[UndoIndex + 1].Count == 0)
if (_history[UndoIndex + 1].Count == 0)
{
return Movie.InputLogLength;
return _movie.InputLogLength;
}
return History[UndoIndex + 1].Min(a => a.FirstFrame);
return _history[UndoIndex + 1].Min(a => a.FirstFrame);
}
}
@ -250,15 +250,15 @@ namespace BizHawk.Client.Common
{
if (UndoIndex == -1)
{
return Movie.InputLogLength;
return _movie.InputLogLength;
}
if (History[UndoIndex].Count == 0)
if (_history[UndoIndex].Count == 0)
{
return Movie.InputLogLength;
return _movie.InputLogLength;
}
return History[UndoIndex].Min(a => a.FirstFrame);
return _history[UndoIndex].Min(a => a.FirstFrame);
}
}
@ -266,7 +266,7 @@ namespace BizHawk.Client.Common
private bool AddMovieAction(string name)
{
if (UndoIndex + 1 != History.Count)
if (UndoIndex + 1 != _history.Count)
{
TruncateLog(UndoIndex + 1);
}
@ -277,20 +277,20 @@ namespace BizHawk.Client.Common
}
bool ret = false;
if (!RecordingBatch)
if (!_recordingBatch)
{
ret = true;
History.Add(new List<IMovieAction>(1));
_history.Add(new List<IMovieAction>(1));
Names.Add(name);
_totalSteps += 1;
if (History.Count <= MaxSteps)
if (_history.Count <= MaxSteps)
{
UndoIndex += 1;
}
else
{
History.RemoveAt(0);
_history.RemoveAt(0);
Names.RemoveAt(0);
ret = false;
}
@ -312,8 +312,8 @@ namespace BizHawk.Client.Common
if (IsRecording || force)
{
AddMovieAction(name);
History.Last().Add(new MovieAction(first, last, Movie));
_lastGeneral = History.Last().Count - 1;
_history.Last().Add(new MovieAction(first, last, _movie));
_lastGeneral = _history.Last().Count - 1;
}
}
@ -321,7 +321,7 @@ namespace BizHawk.Client.Common
{
if (IsRecording || force)
{
(History.Last()[_lastGeneral] as MovieAction).SetRedoLog(Movie);
(_history.Last()[_lastGeneral] as MovieAction).SetRedoLog(_movie);
}
}
@ -330,7 +330,7 @@ namespace BizHawk.Client.Common
if (IsRecording || force)
{
AddMovieAction(name);
History.Last().Add(new MovieActionFrameEdit(frame, button, oldState, !oldState));
_history.Last().Add(new MovieActionFrameEdit(frame, button, oldState, !oldState));
}
}
@ -339,11 +339,11 @@ namespace BizHawk.Client.Common
if (IsRecording || force)
{
AddMovieAction(name);
History.Last().Add(new MovieActionFrameEdit(frame, button, oldState, newState));
_history.Last().Add(new MovieActionFrameEdit(frame, button, oldState, newState));
}
}
public void AddMarkerChange(TasMovieMarker newMarker, int oldPosition = -1, string old_message = "", string name = "", bool force = false)
public void AddMarkerChange(TasMovieMarker newMarker, int oldPosition = -1, string oldMessage = "", string name = "", bool force = false)
{
if (IsRecording || force)
{
@ -357,7 +357,7 @@ namespace BizHawk.Client.Common
}
AddMovieAction(name);
History.Last().Add(new MovieActionMarker(newMarker, oldPosition, old_message));
_history.Last().Add(new MovieActionMarker(newMarker, oldPosition, oldMessage));
}
}
@ -366,7 +366,7 @@ namespace BizHawk.Client.Common
if (IsRecording || force)
{
AddMovieAction(name);
History.Last().Add(new MovieActionBindInput(Movie, frame, isDelete));
_history.Last().Add(new MovieActionBindInput(_movie, frame, isDelete));
}
}
@ -392,7 +392,7 @@ namespace BizHawk.Client.Common
private readonly int _undoLength;
private int _redoLength;
private int length => LastFrame - FirstFrame + 1;
private int Length => LastFrame - FirstFrame + 1;
private readonly List<string> _oldLog;
private List<string> _newLog;
@ -402,7 +402,7 @@ namespace BizHawk.Client.Common
{
FirstFrame = firstFrame;
LastFrame = lastFrame;
_oldLog = new List<string>(length);
_oldLog = new List<string>(Length);
_undoLength = Math.Min(LastFrame + 1, movie.InputLogLength) - FirstFrame;
for (int i = 0; i < _undoLength; i++)
@ -430,12 +430,12 @@ namespace BizHawk.Client.Common
movie.ChangeLog.IsRecording = false;
movie.BindMarkersToInput = _bindMarkers;
if (_redoLength != length)
if (_redoLength != Length)
{
movie.InsertEmptyFrame(FirstFrame, length - _redoLength, true);
movie.InsertEmptyFrame(FirstFrame, Length - _redoLength, true);
}
if (_undoLength != length)
if (_undoLength != Length)
{
movie.RemoveFrames(FirstFrame, movie.InputLogLength - _undoLength, true);
}
@ -456,12 +456,12 @@ namespace BizHawk.Client.Common
movie.ChangeLog.IsRecording = false;
movie.BindMarkersToInput = _bindMarkers;
if (_undoLength != length)
if (_undoLength != Length)
{
movie.InsertEmptyFrame(FirstFrame, length - _undoLength);
movie.InsertEmptyFrame(FirstFrame, Length - _undoLength);
}
if (_redoLength != length)
if (_redoLength != Length)
{
movie.RemoveFrames(FirstFrame, movie.InputLogLength - _redoLength);
}
@ -484,18 +484,18 @@ namespace BizHawk.Client.Common
private readonly string _oldMessage;
private readonly string _newMessage;
public MovieActionMarker(TasMovieMarker marker, int oldPosition = -1, string old_message = "")
public MovieActionMarker(TasMovieMarker marker, int oldPosition = -1, string oldMessage = "")
{
FirstFrame = oldPosition;
if (marker == null)
{
LastFrame = -1;
_oldMessage = old_message;
_oldMessage = oldMessage;
}
else
{
LastFrame = marker.Frame;
_oldMessage = old_message == "" ? marker.Message : old_message;
_oldMessage = oldMessage == "" ? marker.Message : oldMessage;
_newMessage = marker.Message;
}
}

View File

@ -31,7 +31,7 @@ namespace BizHawk.Client.Common
public TasLagLog TasLagLog => _lagLog;
public IStringLog InputLog => _log;
public IStringLog InputLog => Log;
public TasMovieMarkerList Markers { get; private set; }
@ -139,12 +139,12 @@ namespace BizHawk.Client.Common
public override void SwitchToPlay()
{
_mode = Moviemode.Play;
Mode = Moviemode.Play;
}
public override void SwitchToRecord()
{
_mode = Moviemode.Record;
Mode = Moviemode.Record;
}
/// <summary>
@ -250,18 +250,18 @@ namespace BizHawk.Client.Common
public void DeleteLogBefore(int frame)
{
if (frame < _log.Count)
if (frame < Log.Count)
{
_log.RemoveRange(0, frame);
Log.RemoveRange(0, frame);
}
}
public void CopyLog(IEnumerable<string> log)
{
_log.Clear();
Log.Clear();
foreach (var entry in log)
{
_log.Add(entry);
Log.Add(entry);
}
}
@ -275,10 +275,10 @@ namespace BizHawk.Client.Common
public IStringLog GetLogEntries()
{
return _log;
return Log;
}
private int? TimelineBranchFrame = null;
private int? _timelineBranchFrame = null;
// TODO: this is 99% copy pasting of bad code
public override bool ExtractInputLog(TextReader reader, out string errorMessage)
@ -291,9 +291,9 @@ namespace BizHawk.Client.Common
// We are in record mode so replace the movie log with the one from the savestate
if (!Global.MovieSession.MultiTrack.IsActive)
{
TimelineBranchFrame = null;
_timelineBranchFrame = null;
if (Global.Config.EnableBackupMovies && MakeBackup && _log.Count != 0)
if (Global.Config.EnableBackupMovies && MakeBackup && Log.Count != 0)
{
SaveBackup();
MakeBackup = false;
@ -341,17 +341,17 @@ namespace BizHawk.Client.Common
else if (line[0] == '|')
{
newLog.Add(line);
if (!TimelineBranchFrame.HasValue && counter < _log.Count && line != _log[counter])
if (!_timelineBranchFrame.HasValue && counter < Log.Count && line != Log[counter])
{
TimelineBranchFrame = counter;
_timelineBranchFrame = counter;
}
counter++;
}
}
_log.Clear();
_log.AddRange(newLog);
Log.Clear();
Log.AddRange(newLog);
}
else // Multitrack mode
{
@ -410,21 +410,21 @@ namespace BizHawk.Client.Common
var stateFramei = stateFrame ?? 0;
if (stateFramei > 0 && stateFramei < _log.Count)
if (stateFramei > 0 && stateFramei < Log.Count)
{
if (!Global.Config.VBAStyleMovieLoadState)
{
Truncate(stateFramei);
}
}
else if (stateFramei > _log.Count) // Post movie savestate
else if (stateFramei > Log.Count) // Post movie savestate
{
if (!Global.Config.VBAStyleMovieLoadState)
{
Truncate(_log.Count);
Truncate(Log.Count);
}
_mode = Moviemode.Finished;
Mode = Moviemode.Finished;
}
if (IsCountingRerecords)
@ -432,10 +432,10 @@ namespace BizHawk.Client.Common
Rerecords++;
}
if (TimelineBranchFrame.HasValue)
if (_timelineBranchFrame.HasValue)
{
_lagLog.RemoveFrom(TimelineBranchFrame.Value);
TasStateManager.Invalidate(TimelineBranchFrame.Value);
_lagLog.RemoveFrom(_timelineBranchFrame.Value);
TasStateManager.Invalidate(_timelineBranchFrame.Value);
}
return true;
@ -510,10 +510,10 @@ namespace BizHawk.Client.Common
public void LoadBranch(TasBranch branch)
{
int? divergentPoint = DivergentPoint(_log, branch.InputLog);
int? divergentPoint = DivergentPoint(Log, branch.InputLog);
_log?.Dispose();
_log = branch.InputLog.Clone();
Log?.Dispose();
Log = branch.InputLog.Clone();
////_changes = true;
// if there are branch states, they will be loaded anyway

View File

@ -26,26 +26,26 @@ namespace BizHawk.Client.Common
InvalidateCallback?.Invoke(index);
}
private readonly List<StateManagerState> lowPriorityStates = new List<StateManagerState>();
internal NDBDatabase ndbdatabase;
private Guid guid = Guid.NewGuid();
private SortedList<int, StateManagerState> States = new SortedList<int, StateManagerState>();
private readonly List<StateManagerState> _lowPriorityStates = new List<StateManagerState>();
internal NDBDatabase NdbDatabase { get; set; }
private Guid _guid = Guid.NewGuid();
private SortedList<int, StateManagerState> _states = new SortedList<int, StateManagerState>();
private string statePath
private string StatePath
{
get
{
var basePath = PathManager.MakeAbsolutePath(Global.Config.PathEntries["Global", "TAStudio states"].Path, null);
return Path.Combine(basePath, guid.ToString());
return Path.Combine(basePath, _guid.ToString());
}
}
private bool _isMountedForWrite;
private readonly TasMovie _movie;
private ulong _expectedStateSize = 0;
private ulong _expectedStateSize;
private readonly int _minFrequency = VersionInfo.DeveloperBuild ? 2 : 1;
private const int _maxFrequency = 16;
private const int MaxFrequency = 16;
private int StateFrequency
{
@ -58,18 +58,18 @@ namespace BizHawk.Client.Common
return _minFrequency;
}
if (freq > _maxFrequency)
if (freq > MaxFrequency)
{
return _maxFrequency;
return MaxFrequency;
}
return freq;
}
}
private int maxStates => (int)(Settings.Cap / _expectedStateSize) + (int)((ulong)Settings.DiskCapacitymb * 1024 * 1024 / _expectedStateSize);
private int MaxStates => (int)(Settings.Cap / _expectedStateSize) + (int)((ulong)Settings.DiskCapacitymb * 1024 * 1024 / _expectedStateSize);
private int _stateGap => 1 << Settings.StateGap;
private int StateGap => 1 << Settings.StateGap;
public TasStateManager(TasMovie movie)
{
@ -77,7 +77,7 @@ namespace BizHawk.Client.Common
Settings = new TasStateManagerSettings(Global.Config.DefaultTasProjSettings);
accessed = new List<StateManagerState>();
_accessed = new List<StateManagerState>();
if (_movie.StartsFromSavestate)
{
@ -88,7 +88,7 @@ namespace BizHawk.Client.Common
public void Dispose()
{
// States and BranchStates don't need cleaning because they would only contain an ndbdatabase entry which was demolished by the below
ndbdatabase?.Dispose();
NdbDatabase?.Dispose();
}
/// <summary>
@ -109,17 +109,17 @@ namespace BizHawk.Client.Common
if (_expectedStateSize > 0)
{
limit = maxStates;
limit = MaxStates;
}
States = new SortedList<int, StateManagerState>(limit);
_states = new SortedList<int, StateManagerState>(limit);
if (_expectedStateSize > int.MaxValue)
{
throw new InvalidOperationException();
}
ndbdatabase = new NDBDatabase(statePath, Settings.DiskCapacitymb * 1024 * 1024, (int)_expectedStateSize);
NdbDatabase = new NDBDatabase(StatePath, Settings.DiskCapacitymb * 1024 * 1024, (int)_expectedStateSize);
}
public TasStateManagerSettings Settings { get; set; }
@ -138,17 +138,17 @@ namespace BizHawk.Client.Common
return new KeyValuePair<int, byte[]>(0, InitialState);
}
if (States.ContainsKey(frame))
if (_states.ContainsKey(frame))
{
StateAccessed(frame);
return new KeyValuePair<int, byte[]>(frame, States[frame].State);
return new KeyValuePair<int, byte[]>(frame, _states[frame].State);
}
return new KeyValuePair<int, byte[]>(-1, new byte[0]);
}
}
private readonly List<StateManagerState> accessed;
private readonly List<StateManagerState> _accessed;
public byte[] InitialState
{
@ -159,7 +159,7 @@ namespace BizHawk.Client.Common
return _movie.BinarySavestate;
}
return States[0].State;
return _states[0].State;
}
}
@ -169,7 +169,7 @@ namespace BizHawk.Client.Common
/// </summary>
public void Capture(bool force = false)
{
bool shouldCapture = false;
bool shouldCapture;
int frame = Global.Emulator.Frame;
if (_movie.StartsFromSavestate && frame == 0) // Never capture frame 0 on savestate anchored movies since we have it anyway
@ -215,8 +215,8 @@ namespace BizHawk.Client.Common
{
lastMemState++;
}
while (States[accessed[lastMemState].Frame] == null);
MoveStateToDisk(accessed[lastMemState].Frame);
while (_states[_accessed[lastMemState].Frame] == null);
MoveStateToDisk(_accessed[lastMemState].Frame);
}
}
@ -228,9 +228,9 @@ namespace BizHawk.Client.Common
// X is frame, Y is branch
Point shouldRemove = new Point(-1, -1);
if (BranchStates.Any() && Settings.EraseBranchStatesFirst)
if (_branchStates.Any() && Settings.EraseBranchStatesFirst)
{
var kvp = BranchStates.Count > 1 ? BranchStates.ElementAt(1) : BranchStates.ElementAt(0);
var kvp = _branchStates.Count > 1 ? _branchStates.ElementAt(1) : _branchStates.ElementAt(0);
shouldRemove.X = kvp.Key;
shouldRemove.Y = kvp.Value.Keys[0];
@ -238,14 +238,14 @@ namespace BizHawk.Client.Common
}
int i = 0;
int markerSkips = maxStates / 2;
int markerSkips = MaxStates / 2;
// lowPrioritySates (e.g. states with only lag frames between them)
do
{
if (lowPriorityStates.Count > i)
if (_lowPriorityStates.Count > i)
{
shouldRemove = findState(lowPriorityStates[i]);
shouldRemove = FindState(_lowPriorityStates[i]);
}
else
{
@ -261,18 +261,18 @@ namespace BizHawk.Client.Common
i++;
}
while (StateIsMarker(shouldRemove.X, shouldRemove.Y) && markerSkips > -1 || shouldRemove.X == 0);
while ((StateIsMarker(shouldRemove.X, shouldRemove.Y) && markerSkips > -1) || shouldRemove.X == 0);
// by last accessed
markerSkips = maxStates / 2;
markerSkips = MaxStates / 2;
if (shouldRemove.X < 1)
{
i = 0;
do
{
if (accessed.Count > i)
if (_accessed.Count > i)
{
shouldRemove = findState(accessed[i]);
shouldRemove = FindState(_accessed[i]);
}
else
{
@ -288,20 +288,20 @@ namespace BizHawk.Client.Common
i++;
}
while (StateIsMarker(shouldRemove.X, shouldRemove.Y) && markerSkips > -1 || shouldRemove.X == 0);
while ((StateIsMarker(shouldRemove.X, shouldRemove.Y) && markerSkips > -1) || shouldRemove.X == 0);
}
if (shouldRemove.X < 1) // only found marker states above
{
if (BranchStates.Any() && !Settings.EraseBranchStatesFirst)
if (_branchStates.Any() && !Settings.EraseBranchStatesFirst)
{
var kvp = BranchStates.Count > 1 ? BranchStates.ElementAt(1) : BranchStates.ElementAt(0);
var kvp = _branchStates.Count > 1 ? _branchStates.ElementAt(1) : _branchStates.ElementAt(0);
shouldRemove.X = kvp.Key;
shouldRemove.Y = kvp.Value.Keys[0];
}
else
{
StateManagerState s = States.Values[1];
StateManagerState s = _states.Values[1];
shouldRemove.X = s.Frame;
shouldRemove.Y = -1;
}
@ -319,12 +319,12 @@ namespace BizHawk.Client.Common
if (branch == -1)
{
return _movie.Markers.IsMarker(States[frame].Frame + 1);
return _movie.Markers.IsMarker(_states[frame].Frame + 1);
}
if (_movie.GetBranch(_movie.BranchIndexByHash(branch)).Markers == null)
{
return _movie.Markers.IsMarker(States[frame].Frame + 1);
return _movie.Markers.IsMarker(_states[frame].Frame + 1);
}
return _movie.GetBranch(branch).Markers.Any(m => m.Frame + 1 == frame);
@ -354,14 +354,14 @@ namespace BizHawk.Client.Common
private void MoveStateToDisk(int index)
{
Used -= (ulong)States[index].Length;
States[index].MoveToDisk();
Used -= (ulong)_states[index].Length;
_states[index].MoveToDisk();
}
private void MoveStateToMemory(int index)
{
States[index].MoveToRAM();
Used += (ulong)States[index].Length;
_states[index].MoveToRAM();
Used += (ulong)_states[index].Length;
}
internal void SetState(int frame, byte[] state, bool skipRemoval = true)
@ -371,27 +371,27 @@ namespace BizHawk.Client.Common
MaybeRemoveStates(); // Remove before adding so this state won't be removed.
}
if (States.ContainsKey(frame))
if (_states.ContainsKey(frame))
{
if (stateHasDuplicate(frame, -1) != -2)
if (StateHasDuplicate(frame, -1) != -2)
{
Used += (ulong)state.Length;
}
States[frame].State = state;
_states[frame].State = state;
}
else
{
Used += (ulong)state.Length;
States.Add(frame, new StateManagerState(this, state, frame));
_states.Add(frame, new StateManagerState(this, state, frame));
}
StateAccessed(frame);
int i = States.IndexOfKey(frame);
if (i > 0 && AllLag(States.Keys[i - 1], States.Keys[i]))
int i = _states.IndexOfKey(frame);
if (i > 0 && AllLag(_states.Keys[i - 1], _states.Keys[i]))
{
lowPriorityStates.Add(States[frame]);
_lowPriorityStates.Add(_states[frame]);
}
}
@ -399,49 +399,49 @@ namespace BizHawk.Client.Common
{
if (branch == -1)
{
accessed.Remove(States[frame]);
_accessed.Remove(_states[frame]);
}
else if (accessed.Contains(BranchStates[frame][branch]) && !Settings.EraseBranchStatesFirst)
else if (_accessed.Contains(_branchStates[frame][branch]) && !Settings.EraseBranchStatesFirst)
{
accessed.Remove(BranchStates[frame][branch]);
_accessed.Remove(_branchStates[frame][branch]);
}
StateManagerState state;
bool hasDuplicate = stateHasDuplicate(frame, branch) != -2;
bool hasDuplicate = StateHasDuplicate(frame, branch) != -2;
if (branch == -1)
{
state = States[frame];
if (States[frame].IsOnDisk)
state = _states[frame];
if (_states[frame].IsOnDisk)
{
States[frame].Dispose();
_states[frame].Dispose();
}
else
{
Used -= (ulong)States[frame].Length;
Used -= (ulong)_states[frame].Length;
}
States.RemoveAt(States.IndexOfKey(frame));
_states.RemoveAt(_states.IndexOfKey(frame));
}
else
{
state = BranchStates[frame][branch];
state = _branchStates[frame][branch];
if (BranchStates[frame][branch].IsOnDisk)
if (_branchStates[frame][branch].IsOnDisk)
{
BranchStates[frame][branch].Dispose();
_branchStates[frame][branch].Dispose();
}
BranchStates[frame].RemoveAt(BranchStates[frame].IndexOfKey(branch));
_branchStates[frame].RemoveAt(_branchStates[frame].IndexOfKey(branch));
if (BranchStates[frame].Count == 0)
if (_branchStates[frame].Count == 0)
{
BranchStates.Remove(frame);
_branchStates.Remove(frame);
}
}
if (!hasDuplicate)
{
lowPriorityStates.Remove(state);
_lowPriorityStates.Remove(state);
}
}
@ -452,23 +452,23 @@ namespace BizHawk.Client.Common
return;
}
StateManagerState state = States[frame];
bool removed = accessed.Remove(state);
accessed.Add(state);
StateManagerState state = _states[frame];
bool removed = _accessed.Remove(state);
_accessed.Add(state);
if (States[frame].IsOnDisk)
if (_states[frame].IsOnDisk)
{
if (!States[accessed[0].Frame].IsOnDisk)
if (!_states[_accessed[0].Frame].IsOnDisk)
{
MoveStateToDisk(accessed[0].Frame);
MoveStateToDisk(_accessed[0].Frame);
}
MoveStateToMemory(frame);
}
if (!removed && accessed.Count > maxStates)
if (!removed && _accessed.Count > MaxStates)
{
accessed.RemoveAt(0);
_accessed.RemoveAt(0);
}
}
@ -479,7 +479,7 @@ namespace BizHawk.Client.Common
return true;
}
return States.ContainsKey(frame);
return _states.ContainsKey(frame);
}
/// <summary>
@ -497,7 +497,7 @@ namespace BizHawk.Client.Common
}
List<KeyValuePair<int, StateManagerState>> statesToRemove =
States.Where(s => s.Key >= frame).ToList();
_states.Where(s => s.Key >= frame).ToList();
anyInvalidated = statesToRemove.Any();
@ -517,21 +517,21 @@ namespace BizHawk.Client.Common
/// </summary>
public void Clear()
{
States.Clear();
accessed.Clear();
_states.Clear();
_accessed.Clear();
Used = 0;
ClearDiskStates();
}
public void ClearStateHistory()
{
if (States.Any())
if (_states.Any())
{
StateManagerState power = States.Values.FirstOrDefault(s => s.Frame == 0);
StateManagerState power = _states.Values.First(s => s.Frame == 0);
StateAccessed(power.Frame);
States.Clear();
accessed.Clear();
_states.Clear();
_accessed.Clear();
SetState(0, power.State);
Used = (ulong)power.State.Length;
@ -542,7 +542,7 @@ namespace BizHawk.Client.Common
private void ClearDiskStates()
{
ndbdatabase?.Clear();
NdbDatabase?.Clear();
}
/// <summary>
@ -564,9 +564,9 @@ namespace BizHawk.Client.Common
{
index++;
}
while (!accessed[index].IsOnDisk);
while (!_accessed[index].IsOnDisk);
accessed[index].MoveToRAM();
_accessed[index].MoveToRAM();
}
if (Used > Settings.Cap)
@ -582,23 +582,23 @@ namespace BizHawk.Client.Common
// respect state gap no matter how small the resulting size will be
// still leave marker states
for (int i = 1; i < States.Count; i++)
for (int i = 1; i < _states.Count; i++)
{
if (_movie.Markers.IsMarker(States.ElementAt(i).Key + 1)
|| States.ElementAt(i).Key % _stateGap == 0)
if (_movie.Markers.IsMarker(_states.ElementAt(i).Key + 1)
|| _states.ElementAt(i).Key % StateGap == 0)
{
continue;
}
ret.Add(i);
if (States.ElementAt(i).Value.IsOnDisk)
if (_states.ElementAt(i).Value.IsOnDisk)
{
saveUsed -= _expectedStateSize;
}
else
{
saveUsed -= (ulong)States.ElementAt(i).Value.Length;
saveUsed -= (ulong)_states.ElementAt(i).Value.Length;
}
}
@ -610,27 +610,27 @@ namespace BizHawk.Client.Common
do
{
index++;
if (index >= States.Count)
if (index >= _states.Count)
{
break;
}
}
while (_movie.Markers.IsMarker(States.ElementAt(index).Key + 1));
while (_movie.Markers.IsMarker(_states.ElementAt(index).Key + 1));
if (index >= States.Count)
if (index >= _states.Count)
{
break;
}
ret.Add(index);
if (States.ElementAt(index).Value.IsOnDisk)
if (_states.ElementAt(index).Value.IsOnDisk)
{
saveUsed -= _expectedStateSize;
}
else
{
saveUsed -= (ulong)States.ElementAt(index).Value.Length;
saveUsed -= (ulong)_states.ElementAt(index).Value.Length;
}
}
@ -644,13 +644,13 @@ namespace BizHawk.Client.Common
ret.Add(index);
}
if (States.ElementAt(index).Value.IsOnDisk)
if (_states.ElementAt(index).Value.IsOnDisk)
{
saveUsed -= _expectedStateSize;
}
else
{
saveUsed -= (ulong)States.ElementAt(index).Value.Length;
saveUsed -= (ulong)_states.ElementAt(index).Value.Length;
}
}
@ -661,16 +661,16 @@ namespace BizHawk.Client.Common
{
List<int> noSave = ExcludeStates();
bw.Write(States.Count - noSave.Count);
for (int i = 0; i < States.Count; i++)
bw.Write(_states.Count - noSave.Count);
for (int i = 0; i < _states.Count; i++)
{
if (noSave.Contains(i))
{
continue;
}
StateAccessed(States.ElementAt(i).Key);
KeyValuePair<int, StateManagerState> kvp = States.ElementAt(i);
StateAccessed(_states.ElementAt(i).Key);
KeyValuePair<int, StateManagerState> kvp = _states.ElementAt(i);
bw.Write(kvp.Key);
bw.Write(kvp.Value.Length);
bw.Write(kvp.Value.State);
@ -680,7 +680,7 @@ namespace BizHawk.Client.Common
public void Load(BinaryReader br)
{
States.Clear();
_states.Clear();
try
{
int nstates = br.ReadInt32();
@ -704,8 +704,8 @@ namespace BizHawk.Client.Common
public void SaveBranchStates(BinaryWriter bw)
{
bw.Write(BranchStates.Count);
foreach (var s in BranchStates)
bw.Write(_branchStates.Count);
foreach (var s in _branchStates)
{
bw.Write(s.Key);
bw.Write(s.Value.Count);
@ -722,7 +722,7 @@ namespace BizHawk.Client.Common
try
{
int c = br.ReadInt32();
BranchStates = new SortedList<int, SortedList<int, StateManagerState>>(c);
_branchStates = new SortedList<int, SortedList<int, StateManagerState>>(c);
while (c > 0)
{
int key = br.ReadInt32();
@ -736,7 +736,7 @@ namespace BizHawk.Client.Common
c2--;
}
BranchStates.Add(key, list);
_branchStates.Add(key, list);
c--;
}
}
@ -748,7 +748,7 @@ namespace BizHawk.Client.Common
public KeyValuePair<int, byte[]> GetStateClosestToFrame(int frame)
{
var s = States.LastOrDefault(state => state.Key < frame);
var s = _states.LastOrDefault(state => state.Key < frame);
return this[s.Key];
}
@ -785,37 +785,37 @@ namespace BizHawk.Client.Common
{
get
{
if (ndbdatabase == null)
if (NdbDatabase == null)
{
return 0;
}
return (ulong)ndbdatabase.Consumed;
return (ulong)NdbDatabase.Consumed;
}
}
public int StateCount => States.Count;
public int StateCount => _states.Count;
public bool Any()
{
if (_movie.StartsFromSavestate)
{
return States.Count > 0;
return _states.Count > 0;
}
return States.Count > 1;
return _states.Count > 1;
}
public int LastKey
{
get
{
if (States.Count == 0)
if (_states.Count == 0)
{
return 0;
}
return States.Last().Key;
return _states.Last().Key;
}
}
@ -834,45 +834,45 @@ namespace BizHawk.Client.Common
#region Branches
private SortedList<int, SortedList<int, StateManagerState>> BranchStates = new SortedList<int, SortedList<int, StateManagerState>>();
private SortedList<int, SortedList<int, StateManagerState>> _branchStates = new SortedList<int, SortedList<int, StateManagerState>>();
/// <summary>
/// Checks if the state at frame in the given branch (-1 for current) has any duplicates.
/// </summary>
/// <returns>Index of the branch (-1 for current) of the first match. If no match, returns -2.</returns>
private int stateHasDuplicate(int frame, int branchHash)
private int StateHasDuplicate(int frame, int branchHash)
{
StateManagerState stateToMatch;
// Get the state instance
if (branchHash == -1)
{
stateToMatch = States[frame];
stateToMatch = _states[frame];
}
else
{
if (!BranchStates[frame].ContainsKey(branchHash))
if (!_branchStates[frame].ContainsKey(branchHash))
{
return -2;
}
stateToMatch = BranchStates[frame][branchHash];
stateToMatch = _branchStates[frame][branchHash];
// Check the current branch for duplicate.
if (States.ContainsKey(frame) && States[frame] == stateToMatch)
if (_states.ContainsKey(frame) && _states[frame] == stateToMatch)
{
return -1;
}
}
// Check if there are any branch states for the given frame.
if (!BranchStates.ContainsKey(frame) || BranchStates[frame] == null || branchHash == -1)
if (!_branchStates.ContainsKey(frame) || _branchStates[frame] == null || branchHash == -1)
{
return -2;
}
// Loop through branch states for the given frame.
SortedList<int, StateManagerState> stateList = BranchStates[frame];
SortedList<int, StateManagerState> stateList = _branchStates[frame];
for (int i = 0; i < stateList.Count; i++)
{
// Don't check the branch containing the state to match.
@ -890,16 +890,16 @@ namespace BizHawk.Client.Common
return -2; // No match.
}
private Point findState(StateManagerState s)
private Point FindState(StateManagerState s)
{
Point ret = new Point(0, -1);
ret.X = s.Frame;
if (!States.ContainsValue(s))
if (!_states.ContainsValue(s))
{
if (BranchStates.ContainsKey(s.Frame))
if (_branchStates.ContainsKey(s.Frame))
{
int index = BranchStates[s.Frame].Values.IndexOf(s);
ret.Y = BranchStates[s.Frame].Keys.ElementAt(index);
int index = _branchStates[s.Frame].Values.IndexOf(s);
ret.Y = _branchStates[s.Frame].Keys.ElementAt(index);
}
if (ret.Y == -1)
@ -915,19 +915,19 @@ namespace BizHawk.Client.Common
{
int branchHash = _movie.BranchHashByIndex(_movie.BranchCount - 1);
foreach (KeyValuePair<int, StateManagerState> kvp in States)
foreach (KeyValuePair<int, StateManagerState> kvp in _states)
{
if (!BranchStates.ContainsKey(kvp.Key))
if (!_branchStates.ContainsKey(kvp.Key))
{
BranchStates.Add(kvp.Key, new SortedList<int, StateManagerState>());
_branchStates.Add(kvp.Key, new SortedList<int, StateManagerState>());
}
SortedList<int, StateManagerState> stateList = BranchStates[kvp.Key];
SortedList<int, StateManagerState> stateList = _branchStates[kvp.Key];
if (stateList == null) // when does this happen?
{
stateList = new SortedList<int, StateManagerState>();
BranchStates[kvp.Key] = stateList;
_branchStates[kvp.Key] = stateList;
}
// We aren't creating any new states, just adding a reference to an already-existing one; so Used doesn't need to be updated.
@ -939,7 +939,7 @@ namespace BizHawk.Client.Common
{
int branchHash = _movie.BranchHashByIndex(index);
foreach (KeyValuePair<int, SortedList<int, StateManagerState>> kvp in BranchStates.ToList())
foreach (KeyValuePair<int, SortedList<int, StateManagerState>> kvp in _branchStates.ToList())
{
SortedList<int, StateManagerState> stateList = kvp.Value;
if (stateList == null)
@ -960,7 +960,7 @@ namespace BizHawk.Client.Common
stateList.Remove(branchHash);
if (stateList.Count == 0)
{
BranchStates.Remove(kvp.Key);
_branchStates.Remove(kvp.Key);
}
}
}
@ -975,7 +975,7 @@ namespace BizHawk.Client.Common
int branchHash = _movie.BranchHashByIndex(index);
// RemoveBranch
foreach (KeyValuePair<int, SortedList<int, StateManagerState>> kvp in BranchStates.ToList())
foreach (KeyValuePair<int, SortedList<int, StateManagerState>> kvp in _branchStates.ToList())
{
SortedList<int, StateManagerState> stateList = kvp.Value;
if (stateList == null)
@ -996,24 +996,24 @@ namespace BizHawk.Client.Common
stateList.Remove(branchHash);
if (stateList.Count == 0)
{
BranchStates.Remove(kvp.Key);
_branchStates.Remove(kvp.Key);
}
}
// AddBranch
foreach (KeyValuePair<int, StateManagerState> kvp in States)
foreach (KeyValuePair<int, StateManagerState> kvp in _states)
{
if (!BranchStates.ContainsKey(kvp.Key))
if (!_branchStates.ContainsKey(kvp.Key))
{
BranchStates.Add(kvp.Key, new SortedList<int, StateManagerState>());
_branchStates.Add(kvp.Key, new SortedList<int, StateManagerState>());
}
SortedList<int, StateManagerState> stateList = BranchStates[kvp.Key];
SortedList<int, StateManagerState> stateList = _branchStates[kvp.Key];
if (stateList == null)
{
stateList = new SortedList<int, StateManagerState>();
BranchStates[kvp.Key] = stateList;
_branchStates[kvp.Key] = stateList;
}
stateList.Add(branchHash, kvp.Value);
@ -1031,9 +1031,9 @@ namespace BizHawk.Client.Common
////Invalidate(0); // Not a good way of doing it?
foreach (KeyValuePair<int, SortedList<int, StateManagerState>> kvp in BranchStates)
foreach (KeyValuePair<int, SortedList<int, StateManagerState>> kvp in _branchStates)
{
if (kvp.Key == 0 && States.ContainsKey(0))
if (kvp.Key == 0 && _states.ContainsKey(0))
{
continue; // TODO: It might be a better idea to just not put state 0 in BranchStates.
}

View File

@ -253,10 +253,10 @@ namespace BizHawk.Client.Common
if (thisByteMatches || i == stateLength - 1)
{
const int maxHeaderSize = 10;
const int MaxHeaderSize = 10;
int length = i - changeSequenceStartOffset + (thisByteMatches ? 0 : 1);
if (index + length + maxHeaderSize >= stateLength)
if (index + length + MaxHeaderSize >= stateLength)
{
// If the delta ends up being larger than the full state, capture the full state instead
goto CaptureFullState;

View File

@ -285,15 +285,15 @@ namespace BizHawk.Client.Common
public long EndExclusive => Index + Length;
}
private static byte[] test_BufferManage(byte[] inbuf, ref long size, bool allocate)
private static byte[] Test_BufferManage(byte[] inbuf, ref long size, bool allocate)
{
if (allocate)
{
// if we have an appropriate buffer free, return it
if (test_rewindFellationBuf != null && test_rewindFellationBuf.LongLength == size)
if (testRewindFellationBuf != null && testRewindFellationBuf.LongLength == size)
{
var ret = test_rewindFellationBuf;
test_rewindFellationBuf = null;
var ret = testRewindFellationBuf;
testRewindFellationBuf = null;
return ret;
}
@ -301,15 +301,15 @@ namespace BizHawk.Client.Common
return new byte[size];
}
test_rewindFellationBuf = inbuf;
testRewindFellationBuf = inbuf;
return null;
}
private static byte[] test_rewindFellationBuf;
private static byte[] testRewindFellationBuf;
private static void test(string[] args)
private static void Test(string[] args)
{
var sbb = new StreamBlobDatabase(false, 1024, test_BufferManage);
var sbb = new StreamBlobDatabase(false, 1024, Test_BufferManage);
Random r = new Random(0);
byte[] temp = new byte[1024];
int trials = 0;

View File

@ -13,6 +13,17 @@ namespace BizHawk.Client.Common
{
public class CheatCollection : ICollection<Cheat>
{
private const string NameColumn = "NamesColumn";
private const string AddressColumn = "AddressColumn";
private const string ValueColumn = "ValueColumn";
private const string CompareColumn = "CompareColumn";
private const string OnColumn = "OnColumn";
private const string DomainColumn = "DomainColumn";
private const string SizeColumn = "SizeColumn";
private const string EndianColumn = "EndianColumn";
private const string TypeColumn = "DisplayTypeColumn";
private const string ComparisonType = "ComparisonTypeColumn";
private List<Cheat> _cheatList = new List<Cheat>();
private string _currentFileName = "";
private string _defaultFileName = "";
@ -512,7 +523,7 @@ namespace BizHawk.Client.Common
{
switch (column)
{
case NAME:
case NameColumn:
if (reverse)
{
_cheatList = _cheatList
@ -529,7 +540,7 @@ namespace BizHawk.Client.Common
}
break;
case ADDRESS:
case AddressColumn:
if (reverse)
{
_cheatList = _cheatList
@ -546,7 +557,7 @@ namespace BizHawk.Client.Common
}
break;
case VALUE:
case ValueColumn:
if (reverse)
{
_cheatList = _cheatList
@ -565,7 +576,7 @@ namespace BizHawk.Client.Common
}
break;
case COMPARE:
case CompareColumn:
if (reverse)
{
_cheatList = _cheatList
@ -584,7 +595,7 @@ namespace BizHawk.Client.Common
}
break;
case ON:
case OnColumn:
if (reverse)
{
_cheatList = _cheatList
@ -603,7 +614,7 @@ namespace BizHawk.Client.Common
}
break;
case DOMAIN:
case DomainColumn:
if (reverse)
{
_cheatList = _cheatList
@ -622,7 +633,7 @@ namespace BizHawk.Client.Common
}
break;
case SIZE:
case SizeColumn:
if (reverse)
{
_cheatList = _cheatList
@ -641,7 +652,7 @@ namespace BizHawk.Client.Common
}
break;
case ENDIAN:
case EndianColumn:
if (reverse)
{
_cheatList = _cheatList
@ -660,7 +671,7 @@ namespace BizHawk.Client.Common
}
break;
case TYPE:
case TypeColumn:
if (reverse)
{
_cheatList = _cheatList
@ -679,7 +690,7 @@ namespace BizHawk.Client.Common
}
break;
case COMPARISONTYPE:
case ComparisonType:
if (reverse)
{
_cheatList = _cheatList
@ -721,16 +732,5 @@ namespace BizHawk.Client.Common
public Cheat Cheat { get; private set; }
}
private const string NAME = "NamesColumn";
private const string ADDRESS = "AddressColumn";
private const string VALUE = "ValueColumn";
private const string COMPARE = "CompareColumn";
private const string ON = "OnColumn";
private const string DOMAIN = "DomainColumn";
private const string SIZE = "SizeColumn";
private const string ENDIAN = "EndianColumn";
private const string TYPE = "DisplayTypeColumn";
private const string COMPARISONTYPE = "ComparisonTypeColumn";
}
}

View File

@ -83,6 +83,7 @@
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=SG/@EntryIndexedValue">SG</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=SGB/@EntryIndexedValue">SGB</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=SGX/@EntryIndexedValue">SGX</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=SHA/@EntryIndexedValue">SHA</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=SNES/@EntryIndexedValue">SNES</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=TAS/@EntryIndexedValue">TAS</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=TI/@EntryIndexedValue">TI</s:String>