From 0b13e006271b5b90d1f340e64b485c2671754036 Mon Sep 17 00:00:00 2001 From: Benjamin Sutas Date: Wed, 15 Nov 2023 12:14:56 +1100 Subject: [PATCH 1/3] update projects to .net 8.0 --- OpenLocoTool/OpenLocoTool.csproj | 2 +- OpenLocoToolCommon/OpenLocoToolCommon.csproj | 2 +- OpenLocoToolGui/OpenLocoToolGui.csproj | 2 +- OpenLocoToolTests/OpenLocoToolTests.csproj | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/OpenLocoTool/OpenLocoTool.csproj b/OpenLocoTool/OpenLocoTool.csproj index 04b22b55..41e0831e 100644 --- a/OpenLocoTool/OpenLocoTool.csproj +++ b/OpenLocoTool/OpenLocoTool.csproj @@ -2,7 +2,7 @@ Exe - net7.0 + net8.0 enable enable latest diff --git a/OpenLocoToolCommon/OpenLocoToolCommon.csproj b/OpenLocoToolCommon/OpenLocoToolCommon.csproj index cfadb03d..30402ac0 100644 --- a/OpenLocoToolCommon/OpenLocoToolCommon.csproj +++ b/OpenLocoToolCommon/OpenLocoToolCommon.csproj @@ -1,7 +1,7 @@ - net7.0 + net8.0 enable enable diff --git a/OpenLocoToolGui/OpenLocoToolGui.csproj b/OpenLocoToolGui/OpenLocoToolGui.csproj index fbbe460e..7bb406c6 100644 --- a/OpenLocoToolGui/OpenLocoToolGui.csproj +++ b/OpenLocoToolGui/OpenLocoToolGui.csproj @@ -2,7 +2,7 @@ WinExe - net7.0-windows + net8.0-windows7.0 enable true enable diff --git a/OpenLocoToolTests/OpenLocoToolTests.csproj b/OpenLocoToolTests/OpenLocoToolTests.csproj index d3ac5d03..c25eeda3 100644 --- a/OpenLocoToolTests/OpenLocoToolTests.csproj +++ b/OpenLocoToolTests/OpenLocoToolTests.csproj @@ -1,7 +1,7 @@ - net7.0 + net8.0 enable enable From 66c95465e72e746fefff093add59e96c0c925fcd Mon Sep 17 00:00:00 2001 From: Benjamin Sutas Date: Wed, 15 Nov 2023 12:49:00 +1100 Subject: [PATCH 2/3] apply many vs refactoring suggestions --- OpenLocoTool/DatFileParsing/ByteReader.cs | 2 +- OpenLocoTool/DatFileParsing/ByteReaderT.cs | 15 ++++ OpenLocoTool/DatFileParsing/ByteWriter.cs | 7 +- OpenLocoTool/DatFileParsing/ByteWriterT.cs | 17 ++++- OpenLocoTool/DatFileParsing/LocoAttributes.cs | 26 +++---- OpenLocoTool/DatFileParsing/LocoObject.cs | 12 +--- .../DatFileParsing/ObjectAnnotator.cs | 13 ++-- .../DatFileParsing/SawyerStreamReader.cs | 63 +++++++--------- .../DatFileParsing/SawyerStreamWriter.cs | 18 ++--- OpenLocoTool/Data/OriginalDataFiles.cs | 6 +- OpenLocoTool/Data/OriginalObjectFiles.cs | 6 +- OpenLocoTool/Headers/G1Header.cs | 4 +- OpenLocoTool/ObjectManager.cs | 4 +- OpenLocoTool/Objects/AirportObject.cs | 6 +- OpenLocoTool/Objects/IndustryObject.cs | 16 +++-- OpenLocoTool/Objects/RoadObject.cs | 2 +- OpenLocoTool/Objects/Vehicle/BodySprite.cs | 2 +- OpenLocoTool/Objects/Vehicle/VehicleObject.cs | 4 +- OpenLocoTool/OpenLocoTool.csproj | 2 +- OpenLocoTool/Program.cs | 19 ----- OpenLocoToolCommon/Logger.cs | 9 +-- OpenLocoToolCommon/ReflectionLogger.cs | 4 +- OpenLocoToolGui/GuiSettings.cs | 4 +- OpenLocoToolGui/MainForm.cs | 72 +++++++++---------- OpenLocoToolGui/MainFormModel.cs | 31 ++++---- OpenLocoToolGui/PaletteHelpers.cs | 5 +- OpenLocoToolGui/ProgressBarForm.cs | 5 +- OpenLocoToolGui/StringTableUserControl.cs | 7 +- OpenLocoToolTests/ObjectLoadingTests.cs | 52 +++----------- 29 files changed, 185 insertions(+), 248 deletions(-) delete mode 100644 OpenLocoTool/Program.cs diff --git a/OpenLocoTool/DatFileParsing/ByteReader.cs b/OpenLocoTool/DatFileParsing/ByteReader.cs index ee0187d1..520db8d9 100644 --- a/OpenLocoTool/DatFileParsing/ByteReader.cs +++ b/OpenLocoTool/DatFileParsing/ByteReader.cs @@ -136,7 +136,7 @@ public static ILocoStruct ReadLocoStruct(ReadOnlySpan data, Type t) args.Add(ReadT(data, p.PropertyType, offsetAttr.Offset, arrLength)); } - return (ILocoStruct?)Activator.CreateInstance(t, args.ToArray()) ?? throw new InvalidDataException("couldn't parse"); + return (ILocoStruct?)Activator.CreateInstance(t, [.. args]) ?? throw new InvalidDataException("couldn't parse"); } public static IList ReadLocoStructArray(ReadOnlySpan data, Type t, int count, int structSize) // could get struct size from attribute, but easier just to pass in diff --git a/OpenLocoTool/DatFileParsing/ByteReaderT.cs b/OpenLocoTool/DatFileParsing/ByteReaderT.cs index f538049c..a5e456f5 100644 --- a/OpenLocoTool/DatFileParsing/ByteReaderT.cs +++ b/OpenLocoTool/DatFileParsing/ByteReaderT.cs @@ -23,19 +23,34 @@ public static int32_t Read_int32t(ReadOnlySpan data, int offset) public static T Read(ReadOnlySpan data, int offset) where T : struct { if (typeof(T) == typeof(uint8_t)) + { return (T)(dynamic)Read_uint8t(data, offset); + } + if (typeof(T) == typeof(int8_t)) + { return (T)(dynamic)Read_int8t(data, offset); + } if (typeof(T) == typeof(uint16_t)) + { return (T)(dynamic)Read_uint16t(data, offset); + } + if (typeof(T) == typeof(int16_t)) + { return (T)(dynamic)Read_int16t(data, offset); + } if (typeof(T) == typeof(uint32_t)) + { return (T)(dynamic)Read_uint32t(data, offset); + } + if (typeof(T) == typeof(int32_t)) + { return (T)(dynamic)Read_int32t(data, offset); + } throw new NotImplementedException(""); } diff --git a/OpenLocoTool/DatFileParsing/ByteWriter.cs b/OpenLocoTool/DatFileParsing/ByteWriter.cs index 3b9d2b69..1cb88475 100644 --- a/OpenLocoTool/DatFileParsing/ByteWriter.cs +++ b/OpenLocoTool/DatFileParsing/ByteWriter.cs @@ -114,12 +114,7 @@ public static ReadOnlySpan WriteLocoStruct(ILocoStruct obj) arrLength = arrLengthAttr.Length; } - var propVal = p.GetValue(obj); - if (propVal == null) - { - throw new NullReferenceException(); - } - + var propVal = p.GetValue(obj) ?? throw new NullReferenceException(); WriteT(buf, p.PropertyType, offsetAttr.Offset, propVal); } diff --git a/OpenLocoTool/DatFileParsing/ByteWriterT.cs b/OpenLocoTool/DatFileParsing/ByteWriterT.cs index 70472efb..a25669b6 100644 --- a/OpenLocoTool/DatFileParsing/ByteWriterT.cs +++ b/OpenLocoTool/DatFileParsing/ByteWriterT.cs @@ -23,22 +23,33 @@ public static void Write_int32t(Span data, int offset, int32_t val) public static void Write(Span data, int offset, T val) where T : struct { if (typeof(T) == typeof(uint8_t)) + { Write_uint8t(data, offset, (uint8_t)(dynamic)val); + } else if (typeof(T) == typeof(int8_t)) + { Write_int8t(data, offset, (int8_t)(dynamic)val); - + } else if (typeof(T) == typeof(uint16_t)) + { Write_uint16t(data, offset, (uint16_t)(dynamic)val); + } else if (typeof(T) == typeof(int16_t)) + { Write_int16t(data, offset, (int16_t)(dynamic)val); - + } else if (typeof(T) == typeof(uint32_t)) + { Write_uint32t(data, offset, (uint32_t)(dynamic)val); + } else if (typeof(T) == typeof(int32_t)) + { Write_int32t(data, offset, (int32_t)(dynamic)val); - + } else + { throw new NotImplementedException($"{typeof(T)}"); + } } public static T[] Write_Array(Span data, int count, int offset = 0) where T : struct diff --git a/OpenLocoTool/DatFileParsing/LocoAttributes.cs b/OpenLocoTool/DatFileParsing/LocoAttributes.cs index ea7aebbb..0604d896 100644 --- a/OpenLocoTool/DatFileParsing/LocoAttributes.cs +++ b/OpenLocoTool/DatFileParsing/LocoAttributes.cs @@ -1,37 +1,27 @@ namespace OpenLocoTool.DatFileParsing { [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = false)] - public class LocoArrayLengthAttribute : Attribute + public class LocoArrayLengthAttribute(int length) : Attribute { - public LocoArrayLengthAttribute(int length) => Length = length; - public int Length { get; } + public int Length => length; } [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = false)] - public class LocoStructOffsetAttribute : Attribute + public class LocoStructOffsetAttribute(int offset) : Attribute { - public LocoStructOffsetAttribute(int offset) => Offset = offset; - - public int Offset { get; } + public int Offset => offset; } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false)] - public class LocoStructSizeAttribute : Attribute + public class LocoStructSizeAttribute(int size) : Attribute { - public LocoStructSizeAttribute(int size) => Size = size; - - public int Size { get; } + public int Size => size; } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false)] - public class LocoStringTableAttribute : Attribute + public class LocoStringTableAttribute(params string[] names) : Attribute { - public LocoStringTableAttribute(params string[] names) - { - Names = names; - } - - public string[] Names { get; } + public string[] Names => names; public int Count => Names.Length; } diff --git a/OpenLocoTool/DatFileParsing/LocoObject.cs b/OpenLocoTool/DatFileParsing/LocoObject.cs index 1d8b10e4..4d6e6c0b 100644 --- a/OpenLocoTool/DatFileParsing/LocoObject.cs +++ b/OpenLocoTool/DatFileParsing/LocoObject.cs @@ -81,16 +81,10 @@ public interface ILocoObject } [TypeConverter(typeof(ExpandableObjectConverter))] - public class G1Dat + public class G1Dat(G1Header g1Header, List g1Elements) { - public G1Dat(G1Header g1Header, List g1Elements) - { - G1Header = g1Header; - G1Elements = g1Elements; - } - - public G1Header G1Header { get; set; } - public List G1Elements { get; set; } + public G1Header G1Header { get; set; } = g1Header; + public List G1Elements { get; set; } = g1Elements; } public static class ObjectTypeFixedSize diff --git a/OpenLocoTool/DatFileParsing/ObjectAnnotator.cs b/OpenLocoTool/DatFileParsing/ObjectAnnotator.cs index 30ce59fb..ea054ad1 100644 --- a/OpenLocoTool/DatFileParsing/ObjectAnnotator.cs +++ b/OpenLocoTool/DatFileParsing/ObjectAnnotator.cs @@ -31,9 +31,11 @@ public static IList Annotate(byte[] bytelist, out byte[] fullData) runningCount += ObjectHeader.StructLength; // Decode Loco Struct - fullData = bytelist[..runningCount] - .Concat(SawyerStreamReader.Decode(objectHeader.Encoding, bytelist.AsSpan()[runningCount..(int)(runningCount + objectHeader.DataLength)])) - .ToArray(); + fullData = + [ + .. bytelist[..runningCount], + .. SawyerStreamReader.Decode(objectHeader.Encoding, bytelist.AsSpan()[runningCount..(int)(runningCount + objectHeader.DataLength)]), + ]; var locoStruct = SawyerStreamReader.GetLocoStruct(s5Header.ObjectType, fullData.AsSpan()[runningCount..]); if (locoStruct == null) @@ -164,7 +166,6 @@ public static int AnnotateStringTable(byte[] fullData, int runningCount, ILocoSt while (continuing); var endIndexOfStringList = index + runningCount; - var nullIndex = 0; var elementRoot = new Annotation("Element " + i, root, runningCount, index); annotations.Add(elementRoot); @@ -172,7 +173,7 @@ public static int AnnotateStringTable(byte[] fullData, int runningCount, ILocoSt { annotations.Add(new Annotation(((LanguageId)fullData[runningCount]).ToString(), elementRoot, runningCount, 1)); runningCount++; - nullIndex = Array.IndexOf(fullData[runningCount..], (byte)0); + var nullIndex = Array.IndexOf(fullData[runningCount..], (byte)0); var stringElement = Encoding.ASCII.GetString(fullData[runningCount..(runningCount + nullIndex)]); @@ -187,7 +188,7 @@ public static int AnnotateStringTable(byte[] fullData, int runningCount, ILocoSt return runningCount; } - static IList AnnotateProperties(object o, int runningCount = 0, Annotation? root = null) + static List AnnotateProperties(object o, int runningCount = 0, Annotation? root = null) { var annotations = new List(); diff --git a/OpenLocoTool/DatFileParsing/SawyerStreamReader.cs b/OpenLocoTool/DatFileParsing/SawyerStreamReader.cs index 2e850fbc..4da11b29 100644 --- a/OpenLocoTool/DatFileParsing/SawyerStreamReader.cs +++ b/OpenLocoTool/DatFileParsing/SawyerStreamReader.cs @@ -8,13 +8,8 @@ namespace OpenLocoTool.DatFileParsing { - public class SawyerStreamReader + public class SawyerStreamReader(ILogger logger) { - private readonly ILogger Logger; - - public SawyerStreamReader(ILogger logger) - => Logger = logger; - static uint ComputeObjectChecksum(ReadOnlySpan flagByte, ReadOnlySpan name, ReadOnlySpan data) { static uint32_t ComputeChecksum(ReadOnlySpan data, uint32_t seed) @@ -39,7 +34,7 @@ public G1Dat LoadG1(string filename) { ReadOnlySpan fullData = LoadBytesFromFile(filename); var (g1Header, imageTable, imageTableBytesRead) = LoadImageTable(fullData); - Logger.Log(LogLevel.Info, $"FileLength={new FileInfo(filename).Length} NumEntries={g1Header.NumEntries} TotalSize={g1Header.TotalSize} ImageTableLength={imageTableBytesRead}"); + logger.Log(LogLevel.Info, $"FileLength={new FileInfo(filename).Length} NumEntries={g1Header.NumEntries} TotalSize={g1Header.TotalSize} ImageTableLength={imageTableBytesRead}"); return new G1Dat(g1Header, imageTable); } @@ -75,7 +70,7 @@ public ILocoObject LoadFull(string filename, bool loadExtra = true) if (checksum != s5Header.Checksum) { //throw new ArgumentException($"{s5Header.Name} had incorrect checksum. expected={s5Header.Checksum} actual={checksum}"); - Logger.Error($"{s5Header.Name} had incorrect checksum. expected={s5Header.Checksum} actual={checksum}"); + logger.Error($"{s5Header.Name} had incorrect checksum. expected={s5Header.Checksum} actual={checksum}"); } // every object has a string table @@ -95,7 +90,7 @@ public ILocoObject LoadFull(string filename, bool loadExtra = true) // some objects have graphics data var (g1Header, imageTable, imageTableBytesRead) = LoadImageTable(remainingData); - Logger.Log(LogLevel.Info, $"FileLength={new FileInfo(filename).Length} HeaderLength={S5Header.StructLength} DataLength={objectHeader.DataLength} StringTableLength={stringTableBytesRead} ImageTableLength={imageTableBytesRead}"); + logger.Log(LogLevel.Info, $"FileLength={new FileInfo(filename).Length} HeaderLength={S5Header.StructLength} DataLength={objectHeader.DataLength} StringTableLength={stringTableBytesRead} ImageTableLength={imageTableBytesRead}"); var newObj = new LocoObject(s5Header, objectHeader, locoStruct, stringTable, g1Header, imageTable); @@ -107,10 +102,9 @@ public ILocoObject LoadFull(string filename, bool loadExtra = true) static (StringTable table, int bytesRead) LoadStringTable(ReadOnlySpan data, ILocoStruct locoStruct) { - var stringTableAttr = locoStruct.GetType().GetCustomAttribute(typeof(LocoStringTableAttribute), inherit: false) as LocoStringTableAttribute; var stringTable = new StringTable(); - if (data.Length == 0 || stringTableAttr == null || stringTableAttr.Count == 0) + if (data.Length == 0 || locoStruct.GetType().GetCustomAttribute(typeof(LocoStringTableAttribute), inherit: false) is not LocoStringTableAttribute stringTableAttr || stringTableAttr.Count == 0) { return (stringTable, 0); } @@ -120,7 +114,7 @@ public ILocoObject LoadFull(string filename, bool loadExtra = true) for (var i = 0; i < stringTableAttr.Count; ++i) { var stringName = stringTableAttr.Names[i]; - stringTable.Add(stringName, new()); + stringTable.Add(stringName, []); var languageDict = stringTable[stringName]; for (; ptr < data.Length && data[ptr] != 0xFF;) @@ -128,18 +122,17 @@ public ILocoObject LoadFull(string filename, bool loadExtra = true) var lang = (LanguageId)data[ptr++]; var ini = ptr; - while (data[ptr++] != '\0') ; + while (data[ptr++] != '\0') + { + ; + } var str = Encoding.ASCII.GetString(data[ini..(ptr - 1)]); // do -1 to exclude the \0 - if (languageDict.ContainsKey(lang)) + if (!languageDict.TryAdd(lang, str)) { //Logger.Error($"Key {(i, lang)} already exists (this shouldn't happen)"); break; } - else - { - languageDict.Add(lang, str); - } } ptr++; // add one because we skipped the 0xFF byte at the end @@ -264,7 +257,9 @@ public static byte[] DecodeRLEImageData(G1Element32 img) } if (isEndOfLine) + { break; + } } } @@ -299,12 +294,9 @@ public static S5Header LoadHeader(string filename) using (var fs = new FileStream(filename, FileMode.Open, FileAccess.Read)) { var bytesRead = fs.Read(data, 0, size); - if (bytesRead != size) - { - throw new InvalidOperationException($"bytes read ({bytesRead}) didn't match bytes expected ({size})"); - } - - return S5Header.Read(data); + return bytesRead != size + ? throw new InvalidOperationException($"bytes read ({bytesRead}) didn't match bytes expected ({size})") + : S5Header.Read(data); } } @@ -349,22 +341,19 @@ public static ILocoStruct GetLocoStruct(ObjectType objectType, ReadOnlySpan data) + public static byte[] Decode(SawyerEncoding encoding, ReadOnlySpan data) => encoding switch { - return encoding switch - { - SawyerEncoding.Uncompressed => data.ToArray(), - SawyerEncoding.RunLengthSingle => DecodeRunLengthSingle(data), - SawyerEncoding.RunLengthMulti => DecodeRunLengthMulti(DecodeRunLengthSingle(data)), - SawyerEncoding.Rotate => DecodeRotate(data), - _ => throw new InvalidDataException("Unknown chunk encoding scheme"), - }; - } + SawyerEncoding.Uncompressed => data.ToArray(), + SawyerEncoding.RunLengthSingle => DecodeRunLengthSingle(data), + SawyerEncoding.RunLengthMulti => DecodeRunLengthMulti(DecodeRunLengthSingle(data)), + SawyerEncoding.Rotate => DecodeRotate(data), + _ => throw new InvalidDataException("Unknown chunk encoding scheme"), + }; // taken from openloco SawyerStreamReader::decodeRunLengthSingle private static byte[] DecodeRunLengthSingle(ReadOnlySpan data) { - List buffer = new(); + List buffer = []; for (var i = 0; i < data.Length; ++i) { @@ -411,7 +400,7 @@ private static byte[] DecodeRunLengthSingle(ReadOnlySpan data) // taken from openloco SawyerStreamReader::decodeRunLengthMulti private static byte[] DecodeRunLengthMulti(ReadOnlySpan data) { - List buffer = new(); + List buffer = []; for (var i = 0; i < data.Length; i++) { @@ -461,7 +450,7 @@ private static byte[] DecodeRunLengthMulti(ReadOnlySpan data) private static byte[] DecodeRotate(ReadOnlySpan data) { - List buffer = new(); + List buffer = []; byte code = 1; for (var i = 0; i < data.Length; i++) diff --git a/OpenLocoTool/DatFileParsing/SawyerStreamWriter.cs b/OpenLocoTool/DatFileParsing/SawyerStreamWriter.cs index 45f0b844..d0c9595e 100644 --- a/OpenLocoTool/DatFileParsing/SawyerStreamWriter.cs +++ b/OpenLocoTool/DatFileParsing/SawyerStreamWriter.cs @@ -2,21 +2,13 @@ namespace OpenLocoTool.DatFileParsing { - public class SawyerStreamWriter + public class SawyerStreamWriter(ILogger logger) { - private readonly ILogger Logger; - - public SawyerStreamWriter(ILogger logger) - => Logger = logger; - public void Save(string filepath, ILocoObject locoObject) { - if (locoObject == null) - { - throw new ArgumentNullException(nameof(locoObject)); - } + ArgumentNullException.ThrowIfNull(locoObject); - Logger.Log(LogLevel.Info, $"Writing \"{locoObject.S5Header.Name}\" to {filepath}"); + logger.Log(LogLevel.Info, $"Writing \"{locoObject.S5Header.Name}\" to {filepath}"); var objBytes = WriteLocoObject(locoObject); @@ -70,7 +62,7 @@ public ReadOnlySpan Encode(SawyerEncoding encoding, ReadOnlySpan dat //case SawyerEncoding.rotate: // return encodeRotate(data); default: - Logger.Log(LogLevel.Error, "Unknown chunk encoding scheme"); + logger.Log(LogLevel.Error, "Unknown chunk encoding scheme"); throw new InvalidDataException("Unknown encoding"); } } @@ -89,7 +81,7 @@ public static void WriteToFile(string filepath, ReadOnlySpan s5Header, Rea // not sure why it doesn't work, but it doesn't work. gets the first 10 or so bytes correct for SIGC3.dat but then fails private static Span EncodeRunLengthSingle(ReadOnlySpan data) { - List buffer = new(); + List buffer = []; var src = 0; // ptr var srcNormStart = 0; // ptr var srcEnd = data.Length; diff --git a/OpenLocoTool/Data/OriginalDataFiles.cs b/OpenLocoTool/Data/OriginalDataFiles.cs index 53fd5d83..a2fb6396 100644 --- a/OpenLocoTool/Data/OriginalDataFiles.cs +++ b/OpenLocoTool/Data/OriginalDataFiles.cs @@ -2,8 +2,8 @@ { public static class OriginalDataFiles { - public static readonly HashSet Names = new() - { + public static readonly HashSet Names = + [ "Data/g1.DAT", "plugin.dat", "plugin2.dat", @@ -59,6 +59,6 @@ public static class OriginalDataFiles "1.TMP", "ObjData", "Scenarios", - }; + ]; } } diff --git a/OpenLocoTool/Data/OriginalObjectFiles.cs b/OpenLocoTool/Data/OriginalObjectFiles.cs index 203db6f3..95b80441 100644 --- a/OpenLocoTool/Data/OriginalObjectFiles.cs +++ b/OpenLocoTool/Data/OriginalObjectFiles.cs @@ -2,8 +2,8 @@ { public static class OriginalObjectFiles { - public static readonly HashSet Names = new() - { + public static readonly HashSet Names = + [ "114", "142", "158", @@ -548,6 +548,6 @@ public static class OriginalObjectFiles "WWAKE1", "YEW", "YUKKA", - }; + ]; } } diff --git a/OpenLocoTool/Headers/G1Header.cs b/OpenLocoTool/Headers/G1Header.cs index be601d9f..23ca6cb0 100644 --- a/OpenLocoTool/Headers/G1Header.cs +++ b/OpenLocoTool/Headers/G1Header.cs @@ -23,8 +23,8 @@ public record G1Element32( [property: LocoStructOffset(0x00)] uint32_t Offset, [property: LocoStructOffset(0x04)] int16_t Width, [property: LocoStructOffset(0x06)] int16_t Height, - [property: LocoStructOffset(0x08)] int16_t xOffset, - [property: LocoStructOffset(0x0A)] int16_t yOffset, + [property: LocoStructOffset(0x08)] int16_t XOffset, + [property: LocoStructOffset(0x0A)] int16_t YOffset, [property: LocoStructOffset(0x0C)] G1ElementFlags Flags, [property: LocoStructOffset(0x0E)] int16_t ZoomOffset ) : ILocoStruct diff --git a/OpenLocoTool/ObjectManager.cs b/OpenLocoTool/ObjectManager.cs index e1baf984..a65cdcce 100644 --- a/OpenLocoTool/ObjectManager.cs +++ b/OpenLocoTool/ObjectManager.cs @@ -5,13 +5,13 @@ namespace OpenLocoTool { public static class SObjectManager { - static readonly Dictionary> Objects = new(); + static readonly Dictionary> Objects = []; static SObjectManager() { foreach (var v in Enum.GetValues(typeof(ObjectType))) { - Objects.Add((ObjectType)v, new List()); + Objects.Add((ObjectType)v, []); } } diff --git a/OpenLocoTool/Objects/AirportObject.cs b/OpenLocoTool/Objects/AirportObject.cs index de316870..2178077d 100644 --- a/OpenLocoTool/Objects/AirportObject.cs +++ b/OpenLocoTool/Objects/AirportObject.cs @@ -99,7 +99,11 @@ public ReadOnlySpan Load(ReadOnlySpan remainingData) { var_1C.Add(ByteReaderT.Read_uint8t(remainingData[0..1], 0)); var ptr_1C = 0; - while (remainingData[ptr_1C++] != 0xFF) ; + while (remainingData[ptr_1C++] != 0xFF) + { + ; + } + remainingData = remainingData[ptr_1C..]; } diff --git a/OpenLocoTool/Objects/IndustryObject.cs b/OpenLocoTool/Objects/IndustryObject.cs index 898f717d..0c65bbf2 100644 --- a/OpenLocoTool/Objects/IndustryObject.cs +++ b/OpenLocoTool/Objects/IndustryObject.cs @@ -43,8 +43,8 @@ public enum IndustryObjectFlags : uint32_t [LocoStructSize(0x02)] public record BuildingPartAnimation( - [property: LocoStructOffset(0x00)] uint8_t numFrames, // Must be a power of 2 (0 = no part animation, could still have animation sequence) - [property: LocoStructOffset(0x01)] uint8_t animationSpeed // Also encodes in bit 7 if the animation is position modified + [property: LocoStructOffset(0x00)] uint8_t NumFrames, // Must be a power of 2 (0 = no part animation, could still have animation sequence) + [property: LocoStructOffset(0x01)] uint8_t AnimationSpeed // Also encodes in bit 7 if the animation is position modified ) : ILocoStruct { public static int StructSize => 0x2; @@ -65,8 +65,8 @@ public record IndustryObjectUnk38( [LocoStructSize(0x04)] public record IndustryObjectProductionRateRange( - [property: LocoStructOffset(0x00)] uint16_t min, - [property: LocoStructOffset(0x02)] uint16_t max + [property: LocoStructOffset(0x00)] uint16_t Min, + [property: LocoStructOffset(0x02)] uint16_t Max ) : ILocoStruct { public static int StructSize => 0x04; @@ -126,13 +126,13 @@ public record IndustryObject( public static ObjectType ObjectType => ObjectType.Industry; public static int StructSize => 0xF4; - public static int AnimationSequencesSize = 4; + public const int AnimationSequencesSize = 4; public const int MaxProducedCargoType = 2; public const int MaxRequiredCargoType = 3; - public List ProducedCargo { get; set; } = new(); - public List RequiredCargo { get; set; } = new(); + public List ProducedCargo { get; set; } = []; + public List RequiredCargo { get; set; } = []; public ReadOnlySpan Load(ReadOnlySpan remainingData) { @@ -183,6 +183,7 @@ public ReadOnlySpan Load(ReadOnlySpan remainingData) { ProducedCargo.Add(header); } + remainingData = remainingData[S5Header.StructLength..]; } @@ -194,6 +195,7 @@ public ReadOnlySpan Load(ReadOnlySpan remainingData) { RequiredCargo.Add(header); } + remainingData = remainingData[S5Header.StructLength..]; } diff --git a/OpenLocoTool/Objects/RoadObject.cs b/OpenLocoTool/Objects/RoadObject.cs index 5df411ff..e810a048 100644 --- a/OpenLocoTool/Objects/RoadObject.cs +++ b/OpenLocoTool/Objects/RoadObject.cs @@ -26,7 +26,7 @@ public enum RoadObjectPieceFlags : uint16_t Track = 1 << 1, Slope = 1 << 2, SteepSlope = 1 << 3, - Intersection = 1 << 2, + Intersection = 1 << 4, OneSided = 1 << 5, Overtake = 1 << 6, StreetLights = 1 << 8, diff --git a/OpenLocoTool/Objects/Vehicle/BodySprite.cs b/OpenLocoTool/Objects/Vehicle/BodySprite.cs index a3dd02f7..a39e5e2b 100644 --- a/OpenLocoTool/Objects/Vehicle/BodySprite.cs +++ b/OpenLocoTool/Objects/Vehicle/BodySprite.cs @@ -21,7 +21,7 @@ public record BodySprite( [property: LocoStructOffset(0x0C)] uint8_t SlopedYawAccuracy, // 0 - 3 accuracy of yaw on slopes built from numSlopedRotationFrames (0 = lowest accuracy 3bits, 3 = highest accuracy 6bits) [property: LocoStructOffset(0x0D)] uint8_t NumFramesPerRotation, // numAnimationFrames * numCargoFrames * numRollFrames + 1 (for braking lights) [property: LocoStructOffset(0x0E)] uint32_t FlatImageId, - [property: LocoStructOffset(0x12)] uint32_t unkImageId, + [property: LocoStructOffset(0x12)] uint32_t UnkImageId, [property: LocoStructOffset(0x16)] uint32_t GentleImageId, [property: LocoStructOffset(0x1A)] uint32_t SteepImageId ) : ILocoStruct diff --git a/OpenLocoTool/Objects/Vehicle/VehicleObject.cs b/OpenLocoTool/Objects/Vehicle/VehicleObject.cs index 595597b6..8462f54c 100644 --- a/OpenLocoTool/Objects/Vehicle/VehicleObject.cs +++ b/OpenLocoTool/Objects/Vehicle/VehicleObject.cs @@ -12,9 +12,9 @@ public class VehicleObject : ILocoStruct, ILocoStructVariableData public static ObjectType ObjectType => ObjectType.Vehicle; public const int StructSize = 0x15E; public const int MaxBodySprites = 4; - public List CargoMatchFlags { get; set; } = new(); + public List CargoMatchFlags { get; set; } = []; - public List CompatibleCargo { get; set; } = new(); + public List CompatibleCargo { get; set; } = []; public VehicleObject(/*ushort name,*/ TransportMode mode, VehicleType type, byte var_04, byte trackType, byte numMods, byte costIndex, short costFactor, byte reliability, byte runCostIndex, short runCostFactor, byte colourType, byte numCompat, ushort[] compatibleVehicles, byte[] requiredTrackExtras, VehicleObjectUnk[] var_24, BodySprite[] bodySprites, BogieSprite[] bogieSprites, ushort power, short speed, short rackSpeed, ushort weight, VehicleObjectFlags flags, byte[] maxCargo, uint[] cargoTypes, byte[] cargoTypeSpriteOffsets, byte numSimultaneousCargoTypes, SimpleAnimation[] animation, byte var_113, ushort designed, ushort obsolete, byte rackRailType, DrivingSoundType drivingSoundType, byte[] pad_135, byte numStartSounds, byte[] startSounds) { diff --git a/OpenLocoTool/OpenLocoTool.csproj b/OpenLocoTool/OpenLocoTool.csproj index 41e0831e..59a1d7b6 100644 --- a/OpenLocoTool/OpenLocoTool.csproj +++ b/OpenLocoTool/OpenLocoTool.csproj @@ -1,7 +1,7 @@ - Exe + Library net8.0 enable enable diff --git a/OpenLocoTool/Program.cs b/OpenLocoTool/Program.cs deleted file mode 100644 index 5846b578..00000000 --- a/OpenLocoTool/Program.cs +++ /dev/null @@ -1,19 +0,0 @@ -// See https://aka.ms/new-console-template for more information - -using OpenLocoToolCommon; - -var logger = new Logger(); -logger.Level = LogLevel.Debug2; -logger.LogAdded += (s, e) => Console.WriteLine(e.Log); - -logger.Log(LogLevel.Info, "=== Welcome to OpenLocoTool ==="); - -const string path = "Q:\\Steam\\steamapps\\common\\Locomotion\\ObjData\\STEAM.dat"; - -//var decoder = new DatDecoder(logger); -//decoder.Decode(path); - -//var ssr = new SawyerStreamReader(logger); -//var obj = ssr.Load(path); - -Console.ReadLine(); \ No newline at end of file diff --git a/OpenLocoToolCommon/Logger.cs b/OpenLocoToolCommon/Logger.cs index d9f3f2aa..81b6d67c 100644 --- a/OpenLocoToolCommon/Logger.cs +++ b/OpenLocoToolCommon/Logger.cs @@ -1,11 +1,8 @@ namespace OpenLocoToolCommon { - public class LogAddedEventArgs : EventArgs + public class LogAddedEventArgs(LogLine log) : EventArgs { - public readonly LogLine Log; - - public LogAddedEventArgs(LogLine log) - => Log = log; + public readonly LogLine Log = log; } public record LogLine @@ -20,7 +17,7 @@ public override string ToString() public class Logger : ILogger { - public readonly List Logs = new(); + public readonly List Logs = []; public LogLevel Level = LogLevel.Info; public event EventHandler LogAdded; diff --git a/OpenLocoToolCommon/ReflectionLogger.cs b/OpenLocoToolCommon/ReflectionLogger.cs index acdb557b..a3b2ae1f 100644 --- a/OpenLocoToolCommon/ReflectionLogger.cs +++ b/OpenLocoToolCommon/ReflectionLogger.cs @@ -51,7 +51,7 @@ static StringBuilder ToString(T obj, StringBuilder sb) var fieldValue = field.GetValue(obj); sb.Append(fieldName); - sb.Append("="); + sb.Append('='); sb.Append(ToString(fieldValue)); if (i < fields.Length - 1) @@ -67,7 +67,7 @@ static StringBuilder ToString(T obj, StringBuilder sb) var propertyValue = property.GetValue(obj); sb.Append(propertyName); - sb.Append("="); + sb.Append('='); sb.Append(ToString(propertyValue)); if (i < properties.Length - 1) diff --git a/OpenLocoToolGui/GuiSettings.cs b/OpenLocoToolGui/GuiSettings.cs index 52e4e8de..b84e9d9d 100644 --- a/OpenLocoToolGui/GuiSettings.cs +++ b/OpenLocoToolGui/GuiSettings.cs @@ -11,7 +11,7 @@ public string ObjDataDirectory set { objectDirectory = value; - ObjDataDirectories ??= new(); + ObjDataDirectories ??= []; ObjDataDirectories.Add(objectDirectory); } } @@ -25,7 +25,7 @@ public string DataDirectory set { dataDirectory = value; - DataDirectories ??= new(); + DataDirectories ??= []; DataDirectories.Add(dataDirectory); } } diff --git a/OpenLocoToolGui/MainForm.cs b/OpenLocoToolGui/MainForm.cs index c5355b98..2b5d208a 100644 --- a/OpenLocoToolGui/MainForm.cs +++ b/OpenLocoToolGui/MainForm.cs @@ -62,14 +62,14 @@ int CurrentUIImagePageNumber // DAT Dump viewer fields IList DATDumpAnnotations; - readonly IDictionary DATDumpAnnotationIdentifiers = new Dictionary(); - readonly IDictionary imageHeaderIndexToNode = new Dictionary(); - readonly IDictionary imageDataIndexToNode = new Dictionary(); + readonly Dictionary DATDumpAnnotationIdentifiers = []; + readonly Dictionary imageHeaderIndexToNode = []; + readonly Dictionary imageDataIndexToNode = []; const int bytesPerDumpLine = 32; const int addressStringSizeBytes = 8; const int addressStringSizePrependBytes = addressStringSizeBytes + 2; const int dumpWordSize = 4; - readonly IDictionary> tvUniqueLoadValues = new Dictionary>(); + readonly Dictionary> tvUniqueLoadValues = []; // End DAT Dump viewer fields const int imagesPerPage = 50; @@ -286,7 +286,7 @@ void InitCategoryTreeView(bool vanillaOnly, string fileFilter) } var objDataNode = new TreeNode("ObjData"); - objDataNode.Nodes.AddRange(nodesToAdd.ToArray()); + objDataNode.Nodes.AddRange([.. nodesToAdd]); tvObjType.Nodes.Add(objDataNode); tvObjType.Sort(); } @@ -305,13 +305,14 @@ void InitToolStripMenuItems() if (model.Settings.ObjDataDirectories != null) { // regenerate them - List newObjDirs = new(); + List newObjDirs = []; foreach (var objDir in model.Settings.ObjDataDirectories) { var tsmi = new ToolStripMenuItem(objDir + (model.Settings.ObjDataDirectory == objDir ? " (Current)" : string.Empty)); tsmi.Click += (sender, e) => setObjectDirectoryToolStripMenuItem_ClickCore(objDir); newObjDirs.Add(tsmi); } + objectDirectoriesToolStripMenuItem.DropDownItems.AddRange(newObjDirs.ToArray()); } @@ -324,13 +325,14 @@ void InitToolStripMenuItems() if (model.Settings.DataDirectories != null) { // regenerate them - List newDataDirs = new(); + List newDataDirs = []; foreach (var dataDir in model.Settings.DataDirectories) { var tsmi = new ToolStripMenuItem(dataDir + (model.Settings.DataDirectory == dataDir ? " (Current)" : string.Empty)); tsmi.Click += (sender, e) => setDataDirectoryToolStripMenuItem_ClickCore(dataDir); newDataDirs.Add(tsmi); } + dataDirectoriesToolStripMenuItem.DropDownItems.AddRange(newDataDirs.ToArray()); } } @@ -415,9 +417,7 @@ private void recreateIndexToolStripMenuItem_Click(object sender, EventArgs e) } void tbFileFilter_TextChanged(object sender, EventArgs e) - { - InitUI(cbVanillaObjects.Checked, tbFileFilter.Text); - } + => InitUI(cbVanillaObjects.Checked, tbFileFilter.Text); void LoadDataDump(string path, bool isG1 = false) { @@ -446,11 +446,14 @@ void LoadDataDump(string path, bool isG1 = false) tvDATDumpAnnotations.SuspendLayout(); tvDATDumpAnnotations.Nodes.Clear(); var currentParent = new TreeNode(); - IDictionary parents = new Dictionary(); + + static string constructAnnotationText(Annotation annotation) + => string.Format("{0} (0x{1:X}-0x{2:X})", annotation.Name, annotation.Start, annotation.End); + + var parents = new Dictionary(); foreach (var annotation in DATDumpAnnotations) { - var constructAnnotationText = (Annotation annotation) => string.Format("{0} (0x{1:X}-0x{2:X})", annotation.Name, annotation.Start, annotation.End); var annotationText = constructAnnotationText(annotation); parents[annotationText] = new TreeNode(annotationText); DATDumpAnnotationIdentifiers[annotationText] = (annotation.Start, annotation.End); @@ -496,11 +499,11 @@ void tv_AfterSelect(object sender, TreeViewEventArgs e) } var nodeText = e.Node.Text.ToLower(); - if (tvUniqueLoadValues.ContainsKey(nodeText)) // for custom functions for the individual data files + if (tvUniqueLoadValues.TryGetValue(nodeText, out var value)) // for custom functions for the individual data files { - tvUniqueLoadValues[nodeText].Invoke(e.Node.Name); + value.Invoke(e.Node.Name); } - else if (Path.GetExtension(e.Node.Name).ToLower() == ".dat") + else if (Path.GetExtension(e.Node.Name).Equals(".dat", StringComparison.CurrentCultureIgnoreCase)) { var filename = e.Node.Name; CurrentUIObject = model.LoadAndCacheObject(filename); @@ -567,11 +570,13 @@ void CreateSounds(SoundObject soundObject) Dock = DockStyle.Bottom, }; - var tb = new TextBox(); - tb.MinimumSize = new Size(96, 16); - tb.Text = $"i={count} w={g1Elements[count].Width} h={g1Elements[count].Height}"; + var tb = new TextBox + { + MinimumSize = new Size(96, 16), + Text = $"i={count} w={g1Elements[count].Width} h={g1Elements[count].Height}", + Dock = DockStyle.Top + }; count++; - tb.Dock = DockStyle.Top; panel.Controls.Add(tb); panel.Controls.Add(pb); @@ -627,7 +632,7 @@ IEnumerable CreateImages(List G1Elements, Color[] palette, } } - Bitmap? G1ElementToBitmap(G1Element32 currElement, Color[] palette, bool useTransparency = false) + static Bitmap? G1ElementToBitmap(G1Element32 currElement, Color[] palette, bool useTransparency = false) { var imageData = currElement.ImageData; var dstImg = new Bitmap(currElement.Width, currElement.Height); @@ -678,9 +683,7 @@ void SelectNewPalette() } private void setPaletteToolStripMenuItem_Click(object sender, EventArgs e) - { - SelectNewPalette(); - } + => SelectNewPalette(); private void RefreshObjectUI() { @@ -739,9 +742,7 @@ private void imgContextMenuSave_Click(object sender, EventArgs e) } private void btnPagePrevious_Click(object sender, EventArgs e) - { - CurrentUIImagePageNumber = Math.Max(CurrentUIImagePageNumber - 1, 0); - } + => CurrentUIImagePageNumber = Math.Max(CurrentUIImagePageNumber - 1, 0); private void btnPageNext_Click(object sender, EventArgs e) { @@ -753,7 +754,7 @@ private void btnPageNext_Click(object sender, EventArgs e) private void dataDumpAnnotations_AfterSelect(object sender, TreeViewEventArgs e) { - var dumpPositionToRTBPosition = (int position) => rtbDATDumpView.GetFirstCharIndexFromLine( + int dumpPositionToRTBPosition(int position) => rtbDATDumpView.GetFirstCharIndexFromLine( position / bytesPerDumpLine) + (position % bytesPerDumpLine * 2) // Bytes are displayed 2 characters wide + (position % bytesPerDumpLine / dumpWordSize) // Every word is separated by an extra space @@ -776,11 +777,11 @@ private void headerToolStripMenuItem_Click(object sender, EventArgs e) { var index = currentUIImages.IndexOf(pb); var keys = "Header " + (index + 1); - if (index >= 0 && imageHeaderIndexToNode.ContainsKey(keys)) + if (index >= 0 && imageHeaderIndexToNode.TryGetValue(keys, out var value)) { tcObjectOverview.SelectedIndex = 1; - tvDATDumpAnnotations.SelectedNode = imageHeaderIndexToNode[keys]; - dataDumpAnnotations_AfterSelect(sender, new TreeViewEventArgs(imageHeaderIndexToNode[keys])); + tvDATDumpAnnotations.SelectedNode = value; + dataDumpAnnotations_AfterSelect(sender, new TreeViewEventArgs(value)); tvDATDumpAnnotations.Focus(); } } @@ -792,19 +793,16 @@ private void pictureDataToolStripMenuItem_Click(object sender, EventArgs e) { var index = currentUIImages.IndexOf(pb); var keys = "Image " + (index + 1); - if (index >= 0 && imageDataIndexToNode.ContainsKey(keys)) + if (index >= 0 && imageDataIndexToNode.TryGetValue(keys, out var value)) { tcObjectOverview.SelectedIndex = 1; - tvDATDumpAnnotations.SelectedNode = imageDataIndexToNode[keys]; - dataDumpAnnotations_AfterSelect(sender, new TreeViewEventArgs(imageDataIndexToNode[keys])); + tvDATDumpAnnotations.SelectedNode = value; + dataDumpAnnotations_AfterSelect(sender, new TreeViewEventArgs(value)); tvDATDumpAnnotations.Focus(); } } } - private void cbVanillaObjects_CheckedChanged(object sender, EventArgs e) - { - InitUI(cbVanillaObjects.Checked, tbFileFilter.Text); - } + private void cbVanillaObjects_CheckedChanged(object sender, EventArgs e) => InitUI(cbVanillaObjects.Checked, tbFileFilter.Text); } } diff --git a/OpenLocoToolGui/MainFormModel.cs b/OpenLocoToolGui/MainFormModel.cs index 89de5aec..3b351949 100644 --- a/OpenLocoToolGui/MainFormModel.cs +++ b/OpenLocoToolGui/MainFormModel.cs @@ -17,9 +17,9 @@ class MainFormModel private readonly SawyerStreamReader reader; private readonly SawyerStreamWriter writer; - public HeaderIndex HeaderIndex { get; private set; } = new(); + public HeaderIndex HeaderIndex { get; private set; } = []; - public ObjectCache ObjectCache { get; private set; } = new(); + public ObjectCache ObjectCache { get; private set; } = []; //public OpenLocoTool.ObjectManager ObjectManager { get; private set; } = new(); @@ -81,6 +81,7 @@ public MainFormModel(ILogger logger, string settingsFile) { logger.Debug($"Preloading dependent {depObjectType} objects"); } + foreach (var dep in HeaderIndex.Where(kvp => dependentObjectTypes.Contains(kvp.Value.ObjectType))) { reader.LoadFull(dep.Key); @@ -144,7 +145,8 @@ static bool ValidateSettings(GuiSettings settings, ILogger logger) public void SaveSettings() { - var text = JsonSerializer.Serialize(Settings, new JsonSerializerOptions() { WriteIndented = true }); + var options = GetOptions(); + var text = JsonSerializer.Serialize(Settings, options); File.WriteAllText(SettingsFile, text); } @@ -168,7 +170,9 @@ void CreateIndex(string[] allFiles, IProgress progress) VehicleType? veh = null; if (locoObject.Object is VehicleObject vo) + { veh = vo.Type; + } var indexObjectHeader = new IndexObjectHeader(locoObject.S5Header.Name, locoObject.S5Header.ObjectType, veh); if (!ccHeaderIndex.TryAdd(file, indexObjectHeader)) @@ -192,9 +196,7 @@ void CreateIndex(string[] allFiles, IProgress progress) } public void SaveFile(string path, ILocoObject obj) - { - writer.Save(path, obj); - } + => writer.Save(path, obj); public bool LoadDataDirectory(string directory) { @@ -203,6 +205,7 @@ public bool LoadDataDirectory(string directory) logger.Warning("Invalid directory"); return false; } + Settings.DataDirectory = directory; // load G1 only for now @@ -249,15 +252,18 @@ public void LoadObjDirectory(string directory, IProgress progress, bool u { logger.Info("Recreating index file"); CreateIndex(allFiles, progress); - SerialiseHeaderIndexToFile(Settings.IndexFilePath, HeaderIndex); + SerialiseHeaderIndexToFile(Settings.IndexFilePath, HeaderIndex, GetOptions()); } SaveSettings(); } - static void SerialiseHeaderIndexToFile(string filename, HeaderIndex headerIndex) + private static JsonSerializerOptions GetOptions() + => new() { WriteIndented = true, Converters = { new JsonStringEnumConverter() }, }; + + static void SerialiseHeaderIndexToFile(string filename, HeaderIndex headerIndex, JsonSerializerOptions options) { - var json = JsonSerializer.Serialize(headerIndex, new JsonSerializerOptions() { WriteIndented = true, Converters = { new JsonStringEnumConverter() }, }); + var json = JsonSerializer.Serialize(headerIndex, options); File.WriteAllText(filename, json); } @@ -269,7 +275,8 @@ static void SerialiseHeaderIndexToFile(string filename, HeaderIndex headerIndex) } var json = File.ReadAllText(filename); - return JsonSerializer.Deserialize(json, new JsonSerializerOptions() { WriteIndented = true, Converters = { new JsonStringEnumConverter() }, }) ?? new(); + + return JsonSerializer.Deserialize(json, GetOptions()) ?? []; } public ILocoObject? LoadAndCacheObject(string filename) @@ -279,9 +286,9 @@ static void SerialiseHeaderIndexToFile(string filename, HeaderIndex headerIndex) return null; } - if (ObjectCache.ContainsKey(filename)) + if (ObjectCache.TryGetValue(filename, out var value)) { - return ObjectCache[filename]; + return value; } else { diff --git a/OpenLocoToolGui/PaletteHelpers.cs b/OpenLocoToolGui/PaletteHelpers.cs index 0fd0444a..f6b44279 100644 --- a/OpenLocoToolGui/PaletteHelpers.cs +++ b/OpenLocoToolGui/PaletteHelpers.cs @@ -41,10 +41,7 @@ public static byte[] Palettise(Bitmap img) return bytes; } - static byte ColorToPaletteIndex(Color c) - { - return 0; - } + static byte ColorToPaletteIndex(Color c) => 0; } public static class ImageHelpers diff --git a/OpenLocoToolGui/ProgressBarForm.cs b/OpenLocoToolGui/ProgressBarForm.cs index b1065c69..4bdbf604 100644 --- a/OpenLocoToolGui/ProgressBarForm.cs +++ b/OpenLocoToolGui/ProgressBarForm.cs @@ -2,10 +2,7 @@ { public partial class ProgressBarForm : Form { - public ProgressBarForm() - { - InitializeComponent(); - } + public ProgressBarForm() => InitializeComponent(); public void SetProgress(int value) { diff --git a/OpenLocoToolGui/StringTableUserControl.cs b/OpenLocoToolGui/StringTableUserControl.cs index ecffc2f7..c53f9752 100644 --- a/OpenLocoToolGui/StringTableUserControl.cs +++ b/OpenLocoToolGui/StringTableUserControl.cs @@ -5,12 +5,9 @@ namespace OpenLocoToolGui { public partial class StringTableUserControl : UserControl { - private BindingList blKeys = new BindingList(); + private readonly BindingList blKeys = []; - public StringTableUserControl() - { - InitializeComponent(); - } + public StringTableUserControl() => InitializeComponent(); public void SetDataBinding(Dictionary> data) { diff --git a/OpenLocoToolTests/ObjectLoadingTests.cs b/OpenLocoToolTests/ObjectLoadingTests.cs index 91d6e41a..14019277 100644 --- a/OpenLocoToolTests/ObjectLoadingTests.cs +++ b/OpenLocoToolTests/ObjectLoadingTests.cs @@ -21,7 +21,7 @@ static ILocoObject LoadObject(string filename) return loaded; } - T LoadObject(string filename) + static T LoadObject(string filename) => (T)LoadObject(filename).Object; //[Test] @@ -272,16 +272,10 @@ public void LoadHillShapesObject() } [Test] - public void LoadIndustryObject() - { - Assert.Fail(); - } + public void LoadIndustryObject() => Assert.Fail(); [Test] - public void LoadInterfaceSkinObject() - { - Assert.Fail(); - } + public void LoadInterfaceSkinObject() => Assert.Fail(); [Test] public void LoadLandObject() @@ -365,16 +359,10 @@ public void LoadRoadExtraObject() } [Test] - public void LoadRoadObject() - { - Assert.Fail(); - } + public void LoadRoadObject() => Assert.Fail(); [Test] - public void LoadRoadStationObject() - { - Assert.Fail(); - } + public void LoadRoadStationObject() => Assert.Fail(); [Test] public void LoadScaffoldingObject() @@ -415,16 +403,10 @@ public void LoadSnowObject() } [Test] - public void LoadSoundObject() - { - Assert.Fail(); - } + public void LoadSoundObject() => Assert.Fail(); [Test] - public void LoadSteamObject() - { - Assert.Fail(); - } + public void LoadSteamObject() => Assert.Fail(); [Test] public void LoadStreetLightObject() @@ -441,10 +423,7 @@ public void LoadStreetLightObject() } [Test] - public void LoadTownNamesObject() - { - Assert.Fail(); - } + public void LoadTownNamesObject() => Assert.Fail(); [Test] public void LoadTrackExtraObject() @@ -464,22 +443,13 @@ public void LoadTrackExtraObject() } [Test] - public void LoadTrackObject() - { - Assert.Fail(); - } + public void LoadTrackObject() => Assert.Fail(); [Test] - public void LoadTrainSignalObject() - { - Assert.Fail(); - } + public void LoadTrainSignalObject() => Assert.Fail(); [Test] - public void LoadTrainStationObject() - { - Assert.Fail(); - } + public void LoadTrainStationObject() => Assert.Fail(); [Test] public void LoadTreeObject() From 5bfb9fa552a3d6f7efd2112e82284d300dd7d463 Mon Sep 17 00:00:00 2001 From: Benjamin Sutas Date: Wed, 15 Nov 2023 15:33:37 +1100 Subject: [PATCH 3/3] more cleanup --- DatFileRenamer/DatFileRenamer.csproj | 2 +- DatFileRenamer/Program.cs | 2 +- OpenLocoTool.sln | 16 ++++++++- OpenLocoTool/DatFileParsing/LocoAttributes.cs | 5 +++ .../DatFileParsing/SawyerStreamReader.cs | 34 ++++++++----------- .../DatFileParsing/SawyerStreamWriter.cs | 4 +-- OpenLocoTool/Headers/ObjectHeader.cs | 2 +- OpenLocoTool/Headers/S5Header.cs | 2 +- OpenLocoTool/Objects/Vehicle/VehicleObject.cs | 2 +- OpenLocoToolCommon/ILogger.cs | 33 +++++++++++++----- OpenLocoToolCommon/Logger.cs | 18 +++++----- OpenLocoToolGui/MainFormModel.cs | 22 ++++++++---- OpenLocoToolTests/ObjectLoadingTests.cs | 2 +- OpenLocoToolTests/ObjectSavingTests.cs | 2 +- 14 files changed, 93 insertions(+), 53 deletions(-) diff --git a/DatFileRenamer/DatFileRenamer.csproj b/DatFileRenamer/DatFileRenamer.csproj index 74abf5c9..91b464af 100644 --- a/DatFileRenamer/DatFileRenamer.csproj +++ b/DatFileRenamer/DatFileRenamer.csproj @@ -2,7 +2,7 @@ Exe - net6.0 + net8.0 enable enable diff --git a/DatFileRenamer/Program.cs b/DatFileRenamer/Program.cs index ece19d1a..6d799025 100644 --- a/DatFileRenamer/Program.cs +++ b/DatFileRenamer/Program.cs @@ -20,7 +20,7 @@ // read each files S5Header using var fileStream = new FileStream(datFile, FileMode.Open, FileAccess.Read, FileShare.None, 32, FileOptions.SequentialScan | FileOptions.Asynchronous); using var reader = new BinaryReader(fileStream); - var data = reader.ReadBytes(0x10); + var data = reader.ReadBytes(0x10).AsSpan(); var flags = BitConverter.ToUInt32(data[0..4]); var datName = System.Text.Encoding.ASCII.GetString(data[4..12]).Trim(); diff --git a/OpenLocoTool.sln b/OpenLocoTool.sln index ded7e317..439107ef 100644 --- a/OpenLocoTool.sln +++ b/OpenLocoTool.sln @@ -12,7 +12,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenLocoToolGui", "OpenLoco EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenLocoToolCommon", "OpenLocoToolCommon\OpenLocoToolCommon.csproj", "{BCD93536-D322-4C14-B193-1F643D03C788}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenLocoToolTests", "OpenLocoToolTests\OpenLocoToolTests.csproj", "{55293DEB-00FA-45AD-814D-CB37383BE0D5}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenLocoToolTests", "OpenLocoToolTests\OpenLocoToolTests.csproj", "{55293DEB-00FA-45AD-814D-CB37383BE0D5}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DatFileRenamer", "DatFileRenamer\DatFileRenamer.csproj", "{AD079FD2-EC1C-459C-BDE6-8D0C527767AB}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -72,6 +74,18 @@ Global {55293DEB-00FA-45AD-814D-CB37383BE0D5}.Release|x64.Build.0 = Release|Any CPU {55293DEB-00FA-45AD-814D-CB37383BE0D5}.Release|x86.ActiveCfg = Release|Any CPU {55293DEB-00FA-45AD-814D-CB37383BE0D5}.Release|x86.Build.0 = Release|Any CPU + {AD079FD2-EC1C-459C-BDE6-8D0C527767AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AD079FD2-EC1C-459C-BDE6-8D0C527767AB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AD079FD2-EC1C-459C-BDE6-8D0C527767AB}.Debug|x64.ActiveCfg = Debug|Any CPU + {AD079FD2-EC1C-459C-BDE6-8D0C527767AB}.Debug|x64.Build.0 = Debug|Any CPU + {AD079FD2-EC1C-459C-BDE6-8D0C527767AB}.Debug|x86.ActiveCfg = Debug|Any CPU + {AD079FD2-EC1C-459C-BDE6-8D0C527767AB}.Debug|x86.Build.0 = Debug|Any CPU + {AD079FD2-EC1C-459C-BDE6-8D0C527767AB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AD079FD2-EC1C-459C-BDE6-8D0C527767AB}.Release|Any CPU.Build.0 = Release|Any CPU + {AD079FD2-EC1C-459C-BDE6-8D0C527767AB}.Release|x64.ActiveCfg = Release|Any CPU + {AD079FD2-EC1C-459C-BDE6-8D0C527767AB}.Release|x64.Build.0 = Release|Any CPU + {AD079FD2-EC1C-459C-BDE6-8D0C527767AB}.Release|x86.ActiveCfg = Release|Any CPU + {AD079FD2-EC1C-459C-BDE6-8D0C527767AB}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/OpenLocoTool/DatFileParsing/LocoAttributes.cs b/OpenLocoTool/DatFileParsing/LocoAttributes.cs index 0604d896..3bee66e5 100644 --- a/OpenLocoTool/DatFileParsing/LocoAttributes.cs +++ b/OpenLocoTool/DatFileParsing/LocoAttributes.cs @@ -30,4 +30,9 @@ public class LocoStringTableAttribute(params string[] names) : Attribute [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = false)] public class LocoStructVariableLoadAttribute : Attribute { } + + // basically a 'skip' attribute to allow deferred loading for variable data, and writing of this property will be 0 + [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = false)] + public class LocoStructZeroAttribute : Attribute + { } } diff --git a/OpenLocoTool/DatFileParsing/SawyerStreamReader.cs b/OpenLocoTool/DatFileParsing/SawyerStreamReader.cs index 4da11b29..e75cc596 100644 --- a/OpenLocoTool/DatFileParsing/SawyerStreamReader.cs +++ b/OpenLocoTool/DatFileParsing/SawyerStreamReader.cs @@ -34,13 +34,15 @@ public G1Dat LoadG1(string filename) { ReadOnlySpan fullData = LoadBytesFromFile(filename); var (g1Header, imageTable, imageTableBytesRead) = LoadImageTable(fullData); - logger.Log(LogLevel.Info, $"FileLength={new FileInfo(filename).Length} NumEntries={g1Header.NumEntries} TotalSize={g1Header.TotalSize} ImageTableLength={imageTableBytesRead}"); + logger.Info($"FileLength={new FileInfo(filename).Length} NumEntries={g1Header.NumEntries} TotalSize={g1Header.TotalSize} ImageTableLength={imageTableBytesRead}"); return new G1Dat(g1Header, imageTable); } // load file - public ILocoObject LoadFull(string filename, bool loadExtra = true) + public static ILocoObject LoadFull(string filename, ILogger? logger = null, bool loadExtra = true) { + logger?.Info($"Full-loading \"{filename}\" with loadExtra={loadExtra}"); + ReadOnlySpan fullData = LoadBytesFromFile(filename); // make openlocotool useful objects @@ -57,7 +59,7 @@ public ILocoObject LoadFull(string filename, bool loadExtra = true) if (locoStruct == null) { Debugger.Break(); - throw new NullReferenceException("loco object was null"); + throw new NullReferenceException($"{filename} was unable to be decoded"); } var structSize = AttributeHelper.Get(locoStruct.GetType()); @@ -69,8 +71,7 @@ public ILocoObject LoadFull(string filename, bool loadExtra = true) if (checksum != s5Header.Checksum) { - //throw new ArgumentException($"{s5Header.Name} had incorrect checksum. expected={s5Header.Checksum} actual={checksum}"); - logger.Error($"{s5Header.Name} had incorrect checksum. expected={s5Header.Checksum} actual={checksum}"); + logger?.Error($"{s5Header.Name} had incorrect checksum. expected={s5Header.Checksum} actual={checksum}"); } // every object has a string table @@ -90,7 +91,7 @@ public ILocoObject LoadFull(string filename, bool loadExtra = true) // some objects have graphics data var (g1Header, imageTable, imageTableBytesRead) = LoadImageTable(remainingData); - logger.Log(LogLevel.Info, $"FileLength={new FileInfo(filename).Length} HeaderLength={S5Header.StructLength} DataLength={objectHeader.DataLength} StringTableLength={stringTableBytesRead} ImageTableLength={imageTableBytesRead}"); + logger?.Info($"FileLength={new FileInfo(filename).Length} HeaderLength={S5Header.StructLength} DataLength={objectHeader.DataLength} StringTableLength={stringTableBytesRead} ImageTableLength={imageTableBytesRead}"); var newObj = new LocoObject(s5Header, objectHeader, locoStruct, stringTable, g1Header, imageTable); @@ -278,26 +279,21 @@ public static byte[] LoadBytesFromFile(string filename) return File.ReadAllBytes(filename); } - public static S5Header LoadHeader(string filename) + public static S5Header LoadHeader(string filename, ILogger? logger) { if (!File.Exists(filename)) { - //Logger.Log(LogLevel.Error, $"Path doesn't exist: {filename}"); - - throw new InvalidOperationException($"File doesn't exist: {filename}"); + logger?.Error($"Path doesn't exist: {filename}"); } - //Logger.Log(LogLevel.Info, $"Loading header for {filename}"); - var size = S5Header.StructLength; - var data = new byte[size]; + logger?.Info($"Loading header for {filename}"); - using (var fs = new FileStream(filename, FileMode.Open, FileAccess.Read)) - { - var bytesRead = fs.Read(data, 0, size); - return bytesRead != size - ? throw new InvalidOperationException($"bytes read ({bytesRead}) didn't match bytes expected ({size})") + using var fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.None, 32, FileOptions.SequentialScan | FileOptions.Asynchronous); + using var reader = new BinaryReader(fileStream); + var data = reader.ReadBytes(S5Header.StructLength); + return data.Length != S5Header.StructLength + ? throw new InvalidOperationException($"bytes read ({data.Length}) didn't match bytes expected ({S5Header.StructLength})") : S5Header.Read(data); - } } public static ILocoStruct GetLocoStruct(ObjectType objectType, ReadOnlySpan data) diff --git a/OpenLocoTool/DatFileParsing/SawyerStreamWriter.cs b/OpenLocoTool/DatFileParsing/SawyerStreamWriter.cs index d0c9595e..ed641f27 100644 --- a/OpenLocoTool/DatFileParsing/SawyerStreamWriter.cs +++ b/OpenLocoTool/DatFileParsing/SawyerStreamWriter.cs @@ -8,7 +8,7 @@ public void Save(string filepath, ILocoObject locoObject) { ArgumentNullException.ThrowIfNull(locoObject); - logger.Log(LogLevel.Info, $"Writing \"{locoObject.S5Header.Name}\" to {filepath}"); + logger.Info($"Writing \"{locoObject.S5Header.Name}\" to {filepath}"); var objBytes = WriteLocoObject(locoObject); @@ -62,7 +62,7 @@ public ReadOnlySpan Encode(SawyerEncoding encoding, ReadOnlySpan dat //case SawyerEncoding.rotate: // return encodeRotate(data); default: - logger.Log(LogLevel.Error, "Unknown chunk encoding scheme"); + logger.Error("Unknown chunk encoding scheme"); throw new InvalidDataException("Unknown encoding"); } } diff --git a/OpenLocoTool/Headers/ObjectHeader.cs b/OpenLocoTool/Headers/ObjectHeader.cs index 410f9e2e..64c513f3 100644 --- a/OpenLocoTool/Headers/ObjectHeader.cs +++ b/OpenLocoTool/Headers/ObjectHeader.cs @@ -13,7 +13,7 @@ public record ObjectHeader(SawyerEncoding Encoding, uint32_t DataLength) public static ObjectHeader Read(ReadOnlySpan data) { - Verify.Equals(data.Length, StructLength); + Verify.AreEqual(data.Length, StructLength); var encoding = (SawyerEncoding)data[0]; var dataLength = BitConverter.ToUInt32(data[1..5]); diff --git a/OpenLocoTool/Headers/S5Header.cs b/OpenLocoTool/Headers/S5Header.cs index 077dbadd..514493aa 100644 --- a/OpenLocoTool/Headers/S5Header.cs +++ b/OpenLocoTool/Headers/S5Header.cs @@ -39,7 +39,7 @@ public ObjectType ObjectType public static S5Header Read(ReadOnlySpan data) { - Verify.Equals(data.Length, StructLength); + Verify.AreEqual(data.Length, StructLength); var flags = BitConverter.ToUInt32(data[0..4]); var name = System.Text.Encoding.ASCII.GetString(data[4..12]); diff --git a/OpenLocoTool/Objects/Vehicle/VehicleObject.cs b/OpenLocoTool/Objects/Vehicle/VehicleObject.cs index 8462f54c..b0551657 100644 --- a/OpenLocoTool/Objects/Vehicle/VehicleObject.cs +++ b/OpenLocoTool/Objects/Vehicle/VehicleObject.cs @@ -109,7 +109,7 @@ public ReadOnlySpan Load(ReadOnlySpan remainingData) // dependent objects if (!Flags.HasFlag(VehicleObjectFlags.unk_09) && (Mode == TransportMode.Rail || Mode == TransportMode.Road)) { - var trackHeader = S5Header.Read(remainingData); + var trackHeader = S5Header.Read(remainingData[..S5Header.StructLength]); dependentObjects.Add(trackHeader); TrackType = trackType; // load the object handle for the track header, and set tracktype to its id diff --git a/OpenLocoToolCommon/ILogger.cs b/OpenLocoToolCommon/ILogger.cs index 9af1ca7b..8b11fa8d 100644 --- a/OpenLocoToolCommon/ILogger.cs +++ b/OpenLocoToolCommon/ILogger.cs @@ -1,16 +1,33 @@ -namespace OpenLocoToolCommon +using System.Runtime.CompilerServices; + +namespace OpenLocoToolCommon { public enum LogLevel { Debug2, Debug, Info, Warning, Error }; public interface ILogger { - void Log(LogLevel level, string message); - void Debug2(string message) => Log(LogLevel.Debug2, message); - void Debug(string message) => Log(LogLevel.Debug, message); - void Info(string message) => Log(LogLevel.Info, message); - void Warning(string message) => Log(LogLevel.Warning, message); - void Error(string message) => Log(LogLevel.Error, message); + // should be 'private' + void Log(LogLevel level, string message, string callerMemberName); + + void Debug2(string message, [CallerMemberName] string callerMemberName = "") + => Log(LogLevel.Debug2, message, callerMemberName); + + void Debug(string message, [CallerMemberName] string callerMemberName = "") + => Log(LogLevel.Debug, message, callerMemberName); + + void Info(string message, [CallerMemberName] string callerMemberName = "") + => Log(LogLevel.Info, message, callerMemberName); + + void Warning(string message, [CallerMemberName] string callerMemberName = "") + => Log(LogLevel.Warning, message, callerMemberName); + + void Error(string message, [CallerMemberName] string callerMemberName = "") + => Log(LogLevel.Error, message, callerMemberName); + + void Error(Exception ex, [CallerMemberName] string callerMemberName = "") + => Log(LogLevel.Error, $"{ex.Message} - {ex.StackTrace}", callerMemberName); - void Error(Exception ex) => Log(LogLevel.Error, ex.Message); + void Error(string message, Exception ex, [CallerMemberName] string callerMemberName = "") + => Log(LogLevel.Error, $"{message} - {ex.Message} - {ex.StackTrace}", callerMemberName); } } \ No newline at end of file diff --git a/OpenLocoToolCommon/Logger.cs b/OpenLocoToolCommon/Logger.cs index 81b6d67c..91605aa0 100644 --- a/OpenLocoToolCommon/Logger.cs +++ b/OpenLocoToolCommon/Logger.cs @@ -1,18 +1,16 @@ -namespace OpenLocoToolCommon +using System.Runtime.CompilerServices; + +namespace OpenLocoToolCommon { public class LogAddedEventArgs(LogLine log) : EventArgs { public readonly LogLine Log = log; } - public record LogLine + public record LogLine(DateTime Time, LogLevel Level, string Caller, string Message) { - public DateTime Time; - public LogLevel Level; - public string Message = null!; - public override string ToString() - => $"[{Time}] [{Level}] {Message}"; + => $"[{Time}] [{Level}] [{Caller}] {Message}"; } public class Logger : ILogger @@ -20,11 +18,11 @@ public class Logger : ILogger public readonly List Logs = []; public LogLevel Level = LogLevel.Info; - public event EventHandler LogAdded; + public event EventHandler? LogAdded; - public void Log(LogLevel level, string message) + public void Log(LogLevel level, string message, string callerMemberName = "") { - var log = new LogLine { Time = DateTime.Now, Level = level, Message = message }; + var log = new LogLine(DateTime.Now, level, callerMemberName, message); Logs.Add(log); if (Level <= level) diff --git a/OpenLocoToolGui/MainFormModel.cs b/OpenLocoToolGui/MainFormModel.cs index 3b351949..a8434682 100644 --- a/OpenLocoToolGui/MainFormModel.cs +++ b/OpenLocoToolGui/MainFormModel.cs @@ -8,6 +8,7 @@ using OpenLocoTool.Objects; using OpenLocoToolCommon; using OpenLocoTool.Headers; +using System.Diagnostics; namespace OpenLocoToolGui { @@ -84,7 +85,7 @@ public MainFormModel(ILogger logger, string settingsFile) foreach (var dep in HeaderIndex.Where(kvp => dependentObjectTypes.Contains(kvp.Value.ObjectType))) { - reader.LoadFull(dep.Key); + SawyerStreamReader.LoadFull(dep.Key); } } @@ -156,13 +157,18 @@ void CreateIndex(string[] allFiles, IProgress progress) ConcurrentDictionary ccHeaderIndex = new(); // key is full path/filename ConcurrentDictionary ccObjectCache = new(); // key is full path/filename - var total = (float)allFiles.Length; var count = 0; + + logger.Info($"Creating index on {allFiles.Length} files"); + var sw = new Stopwatch(); + sw.Start(); + Parallel.ForEach(allFiles, (file) => + //foreach (var file in allFiles) { try { - var locoObject = reader.LoadFull(file); + var locoObject = SawyerStreamReader.LoadFull(file); if (!ccObjectCache.TryAdd(file, locoObject)) { logger.Warning($"Didn't add file {file} to cache - already exists (how???)"); @@ -182,17 +188,21 @@ void CreateIndex(string[] allFiles, IProgress progress) } catch (Exception ex) { - logger.Error(ex); + logger.Error($"Failed to load \"{file}\"", ex); } finally { Interlocked.Increment(ref count); - progress.Report(count / total); + progress.Report(count / (float)allFiles.Length); } + //} }); HeaderIndex = ccHeaderIndex.OrderBy(kvp => kvp.Key).ToDictionary(kvp => kvp.Key, kvp => kvp.Value); ObjectCache = ccObjectCache.OrderBy(kvp => kvp.Key).ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + + sw.Stop(); + logger.Info($"Finished creating index. Time={sw.Elapsed}"); } public void SaveFile(string path, ILocoObject obj) @@ -292,7 +302,7 @@ static void SerialiseHeaderIndexToFile(string filename, HeaderIndex headerIndex, } else { - var obj = reader.LoadFull(filename); + var obj = SawyerStreamReader.LoadFull(filename); ObjectCache.TryAdd(filename, obj); return obj; } diff --git a/OpenLocoToolTests/ObjectLoadingTests.cs b/OpenLocoToolTests/ObjectLoadingTests.cs index 14019277..e1ee8a6c 100644 --- a/OpenLocoToolTests/ObjectLoadingTests.cs +++ b/OpenLocoToolTests/ObjectLoadingTests.cs @@ -14,7 +14,7 @@ static ILocoObject LoadObject(string filename) var fileSize = new FileInfo(filename).Length; var logger = new OpenLocoToolCommon.Logger(); var ssr = new SawyerStreamReader(logger); - var loaded = ssr.LoadFull(filename); + var loaded = SawyerStreamReader.LoadFull(filename); Assert.That(loaded.ObjectHeader.DataLength, Is.EqualTo(fileSize - S5Header.StructLength - ObjectHeader.StructLength), "ObjectHeader.Length didn't match actual size of struct"); diff --git a/OpenLocoToolTests/ObjectSavingTests.cs b/OpenLocoToolTests/ObjectSavingTests.cs index ebb2ad63..d777a70d 100644 --- a/OpenLocoToolTests/ObjectSavingTests.cs +++ b/OpenLocoToolTests/ObjectSavingTests.cs @@ -18,7 +18,7 @@ public void WriteLocoStruct() var logger = new Logger(); var ssr = new SawyerStreamReader(logger); var ssw = new SawyerStreamWriter(logger); - var loaded = ssr.LoadFull(testFile); + var loaded = SawyerStreamReader.LoadFull(testFile); // load data in raw bytes for test ReadOnlySpan fullData = SawyerStreamReader.LoadBytesFromFile(testFile);