Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of MoonHistory v1.0.1
MoonHistory.dll
Decompiled 5 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using LethalModDataLib.Enums; using LethalModDataLib.Events; using LethalModDataLib.Features; using LethalNetworkAPI; using Microsoft.CodeAnalysis; using Unity.Netcode; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("MoonHistory")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.1.0")] [assembly: AssemblyInformationalVersion("1.0.1")] [assembly: AssemblyProduct("MoonHistory")] [assembly: AssemblyTitle("MoonHistory")] [assembly: AssemblyMetadata("AI_Assisted_Creation", "Code generated with Anthropic Claude (Claude Opus 5.5 and other Claude models, via Claude Code); designed and tested by the author")] [assembly: AssemblyMetadata("AI_Model_Vendor", "Anthropic")] [assembly: AssemblyVersion("1.0.1.0")] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace MoonHistory { internal static class Game { private sealed class LevelInfo { internal string Key; internal string Name; } private const BindingFlags All = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; private static readonly Dictionary<string, Type> TypeCache = new Dictionary<string, Type>(); private static readonly Dictionary<SelectableLevel, LevelInfo> LevelCache = new Dictionary<SelectableLevel, LevelInfo>(); private static int _loadedCount = -1; private static HashSet<string> _loadedKeys = new HashSet<string>(); private static Dictionary<string, int> _nameCounts = new Dictionary<string, int>(); private static readonly Regex BcmLine = new Regex("-\\s*<color=(#?[0-9A-Fa-f]{6,8})>(.*?)</color>", RegexOptions.Singleline); private static readonly Regex Tags = new Regex("<[^>]*>"); private static readonly string[] BcmLists = new string[7] { "currentEvents", "forcedEvents", "events", "vanillaEvents", "moddedEvents", "customEvents", "disabledEvents" }; private static bool _corInit; private static MethodInfo _corGet; internal static bool IsServer { get { NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)singleton != (Object)null && singleton.IsListening) { return singleton.IsServer; } return false; } } internal static bool IsHosting { get { if ((Object)(object)GameNetworkManager.Instance != (Object)null) { return GameNetworkManager.Instance.isHostingGame; } return false; } } internal static string CurrentSaveFile { get { if (!((Object)(object)GameNetworkManager.Instance != (Object)null)) { return null; } return GameNetworkManager.Instance.currentSaveFileName; } } internal static string LocalName { get { PlayerControllerB val = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null); if (!((Object)(object)val != (Object)null)) { return null; } return val.playerUsername; } } internal static bool BcmInstalled => T("BrutalCompanyMinus.Minus.EventManager") != null; internal static Type T(string fullName) { if (TypeCache.TryGetValue(fullName, out var value)) { return value; } value = null; Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { try { value = assembly.GetType(fullName, throwOnError: false); } catch { } if (value != null) { break; } } TypeCache[fullName] = value; return value; } internal static object Get(object obj, string member) { if (obj == null) { return null; } Type type = obj.GetType(); PropertyInfo property = type.GetProperty(member, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (property != null) { return property.GetValue(obj, null); } return type.GetField(member, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(obj); } internal static object SGet(Type type, string member) { if (type == null) { return null; } PropertyInfo property = type.GetProperty(member, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (property != null) { return property.GetValue(null, null); } return type.GetField(member, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(null); } internal static bool IsCompany(SelectableLevel l) { if ((Object)(object)l != (Object)null) { if (l.levelID != 3) { return string.Equals(l.sceneName, "CompanyBuilding", StringComparison.OrdinalIgnoreCase); } return true; } return false; } private static object ExtendedLevel(SelectableLevel level) { if (SGet(T("LethalLevelLoader.PatchedContent"), "ExtendedLevelDictionary") is IDictionary dictionary && (Object)(object)level != (Object)null && dictionary.Contains(level)) { return dictionary[level]; } return null; } private static LevelInfo Info(SelectableLevel level) { if ((Object)(object)level == (Object)null) { return null; } if (LevelCache.TryGetValue(level, out var value)) { return value; } value = new LevelInfo(); object obj = null; try { obj = ExtendedLevel(level); } catch { } string text = ((obj != null) ? (Get(obj, "UniqueIdentificationName") as string) : null); value.Key = ((!string.IsNullOrEmpty(text)) ? text : ("scene:" + level.sceneName)); if (IsCompany(level)) { value.Name = "The Company"; } else { string text2 = ((obj != null) ? (Get(obj, "NumberlessPlanetName") as string) : null); if (!string.IsNullOrEmpty(text2)) { value.Name = text2; } else { string text3 = level.PlanetName ?? "?"; int num = text3.IndexOf(' '); if (num > 0 && char.IsDigit(text3[0])) { text3 = text3.Substring(num + 1); } value.Name = text3; } } if (obj != null || T("LethalLevelLoader.PatchedContent") == null) { LevelCache[level] = value; } return value; } internal static string MoonKey(SelectableLevel level) { return Info(level)?.Key; } internal static string MoonName(SelectableLevel level) { return Info(level)?.Name; } internal static HashSet<string> LoadedKeys(StartOfRound sor, out Dictionary<string, int> nameCounts) { SelectableLevel[] array = (((Object)(object)sor != (Object)null) ? sor.levels : null); int num = ((array != null) ? array.Length : 0); if (num != _loadedCount) { HashSet<string> hashSet = new HashSet<string>(); Dictionary<string, int> dictionary = new Dictionary<string, int>(); bool flag = true; if (array != null) { SelectableLevel[] array2 = array; foreach (SelectableLevel val in array2) { if ((Object)(object)val == (Object)null) { continue; } LevelInfo levelInfo = Info(val); if (levelInfo != null) { if (!LevelCache.ContainsKey(val)) { flag = false; } hashSet.Add(levelInfo.Key); dictionary.TryGetValue(levelInfo.Name, out var value); dictionary[levelInfo.Name] = value + 1; } } } _loadedKeys = hashSet; _nameCounts = dictionary; _loadedCount = (flag ? num : (-1)); } nameCounts = _nameCounts; return _loadedKeys; } internal static string Interior(RoundManager rm) { Object val = null; try { val = (Object)(object)(((Object)(object)rm != (Object)null && (Object)(object)rm.dungeonGenerator != (Object)null) ? rm.dungeonGenerator.Generator.DungeonFlow : null); } catch { } object obj2 = SGet(T("LethalLevelLoader.DungeonManager"), "CurrentExtendedDungeonFlow"); if (obj2 != null) { object obj3 = Get(obj2, "DungeonFlow"); Object val2 = (Object)((obj3 is Object) ? obj3 : null); if (val == (Object)null || val2 == val) { string text = Get(obj2, "DungeonName") as string; if (!string.IsNullOrEmpty(text)) { return text; } } } if (val != (Object)null) { if (SGet(T("LethalLevelLoader.PatchedContent"), "ExtendedDungeonFlows") is IEnumerable enumerable) { foreach (object item in enumerable) { if (item != null && Get(item, "DungeonFlow") == val) { string text2 = Get(item, "DungeonName") as string; if (!string.IsNullOrEmpty(text2)) { return text2; } } } } return val.name; } return null; } internal static string WeatherName(SelectableLevel level) { if ((Object)(object)level == (Object)null) { return null; } string text = null; Type type = T("WeatherRegistry.WeatherManager"); if (type != null) { object obj = SGet(type, "IsSetupFinished"); bool flag = default(bool); int num; if (obj is bool) { flag = (bool)obj; num = 1; } else { num = 0; } if (((uint)num & (flag ? 1u : 0u)) != 0) { text = Get(type.GetMethod("GetCurrentWeather", BindingFlags.Static | BindingFlags.Public, null, new Type[1] { typeof(SelectableLevel) }, null)?.Invoke(null, new object[1] { level }), "Name") as string; } } if (string.IsNullOrEmpty(text)) { text = ((object)Unsafe.As<LevelWeatherType, LevelWeatherType>(ref level.currentWeather)/*cast due to .constrained prefix*/).ToString(); } if (text == "None" || text == "-1") { text = "Clear"; } return text; } internal static bool Dilation(SelectableLevel level, out int kind, out int dayPercent) { kind = 0; dayPercent = 0; Type type = T("TimeDilation.DilationState"); if (type == null || (Object)(object)level == (Object)null) { return false; } if (!(SGet(type, "Planet") is string text) || text != level.PlanetName) { return false; } kind = Convert.ToInt32(SGet(type, "Kind")); dayPercent = Convert.ToInt32(SGet(type, "DayPercent")); return true; } internal static List<string> EventsHost() { Type type = T("BrutalCompanyMinus.Minus.EventManager"); if (type == null) { return null; } List<string> list = new List<string>(); if (SGet(type, "currentEvents") is IList list2) { foreach (object item in list2) { string text = EventName(item); if (!string.IsNullOrEmpty(text) && !list.Contains(text)) { list.Add(text); } } } return list; } internal static List<string> EventsClient() { Type type = T("BrutalCompanyMinus.Minus.EventManager"); Type type2 = T("BrutalCompanyMinus.Net"); if (type == null || type2 == null) { return null; } string text = Get(Get(SGet(type2, "Instance"), "textUI"), "Value")?.ToString(); if (string.IsNullOrEmpty(text)) { return null; } int num = text.IndexOf("Other:", StringComparison.OrdinalIgnoreCase); if (num >= 0) { text = text.Substring(0, num); } List<string> list = new List<string>(); foreach (Match item in BcmLine.Matches(text)) { string text2 = Norm(item.Groups[2].Value); if (text2.Length != 0) { string text3 = EventName(FindByDescription(type, text2)); if (!string.IsNullOrEmpty(text3) && !list.Contains(text3)) { list.Add(text3); } } } return list; } private static object FindByDescription(Type em, string normDesc) { string[] bcmLists = BcmLists; foreach (string member in bcmLists) { if (!(SGet(em, member) is IList list)) { continue; } foreach (object item in list) { if (!(Get(item, "Descriptions") is IList list2)) { continue; } foreach (object item2 in list2) { if (item2 is string s && Norm(s) == normDesc) { return item; } } } } return null; } private static string Norm(string s) { if (s == null) { return ""; } s = Tags.Replace(s, ""); return Regex.Replace(s, "\\s+", " ").Trim().ToLowerInvariant(); } private static string EventName(object e) { if (e == null) { return null; } try { MethodInfo method = e.GetType().GetMethod("Name", Type.EmptyTypes); if (method != null && method.Invoke(e, null) is string { Length: >0 } text) { return text; } } catch { } return e.GetType().Name; } internal static string CauseTag(PlayerControllerB p) { if (!_corInit) { _corInit = true; _corGet = T("Coroner.API")?.GetMethod("GetCauseOfDeath", BindingFlags.Static | BindingFlags.Public, null, new Type[1] { typeof(PlayerControllerB) }, null); } if (_corGet != null) { try { object obj = _corGet.Invoke(null, new object[1] { p }); if (obj != null && obj.GetType().GetMethod("GetLanguageTag", Type.EmptyTypes)?.Invoke(obj, null) is string { Length: >0 } text) { return text; } } catch (Exception e) { Safe.Fail("Coroner.GetCauseOfDeath", e); } } return "Vanilla" + ((object)Unsafe.As<CauseOfDeath, CauseOfDeath>(ref p.causeOfDeath)/*cast due to .constrained prefix*/).ToString(); } internal static int? StlLives() { Type type = T("SimpleTeamLives.TeamLives"); if (type == null) { return null; } object obj = SGet(type, "LivesForDisplay"); if (obj == null) { return null; } int num = Convert.ToInt32(obj); if (num < 0) { return null; } return num; } internal static List<ScrapItem> ShipScrap() { List<ScrapItem> list = new List<ScrapItem>(); GrabbableObject[] array = Object.FindObjectsOfType<GrabbableObject>(); foreach (GrabbableObject val in array) { if (!((Object)(object)val == (Object)null) && !((Object)(object)val.itemProperties == (Object)null) && val.itemProperties.isScrap && !val.deactivated && !val.itemUsedUp && (val.isInShipRoom || (val.isHeld && val.isInElevator))) { NetworkObject networkObject = ((NetworkBehaviour)val).NetworkObject; if (!((Object)(object)networkObject == (Object)null) && networkObject.IsSpawned) { list.Add(new ScrapItem(networkObject.NetworkObjectId, val.scrapValue)); } } } return list; } internal static float DayMinutes() { TimeOfDay instance = TimeOfDay.Instance; if ((Object)(object)instance == (Object)null) { return 0f; } return instance.normalizedTimeOfDay * (float)instance.numberOfHours * 60f; } } public static class HistoryApi { public const int ApiVersion = 1; private static int _serial = 1; private static string _short; private static string[] _full; private static int _keyStore = -1; private static int _keyCfg = -1; private static int _keyDay = int.MinValue; private static int _keyLevel; private static bool _keyLanded; private static bool _keyAvail; private static int _errors; public static bool Available { get { try { return Store.Enabled; } catch { return false; } } } public static int Serial { get { try { Refresh(); return _serial; } catch { return _serial; } } } public static string ShortLine { get { try { Refresh(); return _short; } catch { return null; } } } public static string[] FullLines { get { try { Refresh(); return _full; } catch { return null; } } } private static void Refresh() { bool enabled = Store.Enabled; StartOfRound instance = StartOfRound.Instance; SelectableLevel val = (((Object)(object)instance != (Object)null) ? instance.currentLevel : null); int num = (((Object)(object)val != (Object)null) ? ((Object)val).GetInstanceID() : 0); bool flag = (Object)(object)instance != (Object)null && !instance.inShipPhase; int num2 = (((Object)(object)instance != (Object)null && instance.gameStats != null) ? instance.gameStats.daysSpent : (-1)); if (enabled == _keyAvail && Store.Serial == _keyStore && Cfg.Version == _keyCfg && num == _keyLevel && flag == _keyLanded && num2 == _keyDay) { return; } _keyAvail = enabled; _keyStore = Store.Serial; _keyCfg = Cfg.Version; _keyLevel = num; _keyLanded = flag; _keyDay = num2; _serial++; _short = null; _full = null; if (!enabled || (Object)(object)instance == (Object)null || (Object)(object)val == (Object)null) { return; } try { Build(instance, val, flag, num2); _errors = 0; } catch (Exception e) { _short = null; _full = null; if (++_errors <= 1) { Safe.Fail("HistoryApi.Build", e); } } } private static void Build(StartOfRound sor, SelectableLevel level, bool landed, int day) { Dictionary<string, int> nameCounts; HashSet<string> loadedKeys = Game.LoadedKeys(sor, out nameCounts); string text = Game.MoonName(level); MoonQuery moonQuery = new MoonQuery { Key = Game.MoonKey(level), Name = text, Challenge = sor.isChallengeFile, LoadedKeys = loadedKeys }; RunStatus status = Store.Status; IEnumerable<Visit> enumerable2; if (status != RunStatus.Ok) { IEnumerable<Visit> enumerable = new Visit[0]; enumerable2 = enumerable; } else { IEnumerable<Visit> enumerable = Store.Run.Visits; enumerable2 = enumerable; } IEnumerable<Visit> visits = enumerable2; IEnumerable<Visit> enumerable3; if (!Store.AllTimeOn) { IEnumerable<Visit> enumerable = new Visit[0]; enumerable3 = enumerable; } else { IEnumerable<Visit> enumerable = Store.AllTime.Visits; enumerable3 = enumerable; } IEnumerable<Visit> enumerable4 = enumerable3; SideStats run = SideStats.Build(visits, moonQuery); SideStats all = SideStats.Build(enumerable4, moonQuery); int num = 0; if (!moonQuery.Challenge) { foreach (Visit item in enumerable4) { if (item.Challenge && moonQuery.SameMoon(item)) { num++; } } } int value; LineContext c = new LineContext { MoonName = text, Company = Game.IsCompany(level), Landed = landed, NowDay = ((day >= 0) ? new int?(day) : ((int?)null)), GapDays = ((status == RunStatus.Ok) ? Store.Run.GapDays : 0), Status = status, AllTimeOn = Store.AllTimeOn, ChallengeVisits = num, ClashKey = ((text != null && nameCounts.TryGetValue(text, out value) && value > 1) ? moonQuery.Key : null), Options = Cfg.Options() }; _short = (Cfg.ShowShortLine.Value ? Lines.Short(run, all, c) : null); _full = Lines.Full(run, all, c); } } internal static class Json { internal sealed class ObjWriter { private readonly StringBuilder _sb; private bool _first = true; internal ObjWriter(StringBuilder sb) { _sb = sb; _sb.Append('{'); } private void Key(string k) { if (!_first) { _sb.Append(','); } _first = false; Str(_sb, k); _sb.Append(':'); } internal ObjWriter S(string k, string v) { if (v == null) { return this; } Key(k); Str(_sb, v); return this; } internal ObjWriter I(string k, int v) { Key(k); _sb.Append(v.ToString(CultureInfo.InvariantCulture)); return this; } internal ObjWriter I(string k, int? v) { if (v.HasValue) { I(k, v.Value); } return this; } internal ObjWriter B(string k, bool v) { Key(k); _sb.Append(v ? "true" : "false"); return this; } internal ObjWriter BTrue(string k, bool v) { if (v) { B(k, v: true); } return this; } internal ObjWriter Arr(string k, List<string> list) { if (list == null) { return this; } Key(k); _sb.Append('['); for (int i = 0; i < list.Count; i++) { if (i > 0) { _sb.Append(','); } Str(_sb, list[i]); } _sb.Append(']'); return this; } internal ObjWriter Raw(string k, string json) { Key(k); _sb.Append(json); return this; } internal void End() { _sb.Append('}'); } } private sealed class Parser { private readonly string _s; internal int Pos; internal bool End => Pos >= _s.Length; internal Parser(string s) { _s = s; } internal void Ws() { while (Pos < _s.Length && char.IsWhiteSpace(_s[Pos])) { Pos++; } } private char Peek() { if (Pos >= _s.Length) { return '\0'; } return _s[Pos]; } private void Expect(char c) { if (Peek() != c) { throw new FormatException("expected '" + c + "' at " + Pos); } Pos++; } internal object Value() { Ws(); char c = Peek(); switch (c) { case '{': return Obj(); case '[': return Arr(); case '"': return Str(); case 't': Word("true"); return true; case 'f': Word("false"); return false; case 'n': Word("null"); return null; default: switch (c) { case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return Num(); default: throw new FormatException("unexpected '" + c + "' at " + Pos); } } } private void Word(string w) { if (string.CompareOrdinal(_s, Pos, w, 0, w.Length) != 0) { throw new FormatException("bad literal at " + Pos); } Pos += w.Length; } private Dictionary<string, object> Obj() { Expect('{'); Dictionary<string, object> dictionary = new Dictionary<string, object>(); Ws(); if (Peek() == '}') { Pos++; return dictionary; } while (true) { Ws(); string key = Str(); Ws(); Expect(':'); dictionary[key] = Value(); Ws(); if (Peek() != ',') { break; } Pos++; } Expect('}'); return dictionary; } private List<object> Arr() { Expect('['); List<object> list = new List<object>(); Ws(); if (Peek() == ']') { Pos++; return list; } while (true) { list.Add(Value()); Ws(); if (Peek() != ',') { break; } Pos++; } Expect(']'); return list; } private string Str() { Expect('"'); StringBuilder stringBuilder = new StringBuilder(); while (Pos < _s.Length) { char c = _s[Pos++]; switch (c) { case '"': return stringBuilder.ToString(); default: stringBuilder.Append(c); break; case '\\': { if (Pos >= _s.Length) { throw new FormatException("bad escape"); } char c2 = _s[Pos++]; switch (c2) { case '"': stringBuilder.Append('"'); break; case '\\': stringBuilder.Append('\\'); break; case '/': stringBuilder.Append('/'); break; case 'b': stringBuilder.Append('\b'); break; case 'f': stringBuilder.Append('\f'); break; case 'n': stringBuilder.Append('\n'); break; case 'r': stringBuilder.Append('\r'); break; case 't': stringBuilder.Append('\t'); break; case 'u': if (Pos + 4 > _s.Length) { throw new FormatException("bad \\u escape"); } stringBuilder.Append((char)int.Parse(_s.Substring(Pos, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture)); Pos += 4; break; default: throw new FormatException("bad escape \\" + c2); } break; } } } throw new FormatException("unterminated string"); } private double Num() { int pos = Pos; if (Peek() == '-') { Pos++; } while (Pos < _s.Length && "0123456789.eE+-".IndexOf(_s[Pos]) >= 0) { Pos++; } return double.Parse(_s.Substring(pos, Pos - pos), NumberStyles.Float, CultureInfo.InvariantCulture); } } internal static void Str(StringBuilder sb, string s) { if (s == null) { sb.Append("null"); return; } sb.Append('"'); foreach (char c in s) { switch (c) { case '"': sb.Append("\\\""); continue; case '\\': sb.Append("\\\\"); continue; case '\n': sb.Append("\\n"); continue; case '\r': sb.Append("\\r"); continue; case '\t': sb.Append("\\t"); continue; } if (c < ' ') { StringBuilder stringBuilder = sb.Append("\\u"); int num = c; stringBuilder.Append(num.ToString("x4")); } else { sb.Append(c); } } sb.Append('"'); } internal static object Parse(string text) { if (text == null) { throw new FormatException("null JSON"); } Parser parser = new Parser(text); parser.Ws(); object result = parser.Value(); parser.Ws(); if (!parser.End) { throw new FormatException("trailing characters at " + parser.Pos); } return result; } internal static string GetS(Dictionary<string, object> d, string k) { if (!d.TryGetValue(k, out var value)) { return null; } return value as string; } internal static int? GetI(Dictionary<string, object> d, string k) { if (!d.TryGetValue(k, out var value) || value == null) { return null; } if (value is double a) { return (int)Math.Round(a); } if (value is string s && int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { return result; } return null; } internal static bool GetB(Dictionary<string, object> d, string k) { bool flag = default(bool); int num; if (d.TryGetValue(k, out var value)) { if (value is bool) { flag = (bool)value; num = 1; } else { num = 0; } } else { num = 0; } return (byte)((uint)num & (flag ? 1u : 0u)) != 0; } internal static List<string> GetSList(Dictionary<string, object> d, string k) { if (!d.TryGetValue(k, out var value) || !(value is List<object> list)) { return null; } List<string> list2 = new List<string>(list.Count); foreach (object item2 in list) { if (item2 is string item) { list2.Add(item); } } return list2; } } internal static class Net { private const float FirstRequestDelay = 3f; private const float RetryAfter = 10f; private static LNetworkMessage<string> _msg; private static readonly ChunkAssembler Assembler = new ChunkAssembler(); private static int _syncToken; private static bool _gotSnapshot; private static bool CanSend { get { if (_msg != null && Game.IsServer && Store.Enabled) { return Cfg.SendToClients.Value; } return false; } } internal static void Init() { Safe.Optional("Net.Init", delegate { _msg = LNetworkMessage<string>.Connect("History", (Action<string, ulong>)OnServer, (Action<string>)OnClient, (Action<string, ulong>)null); }); if (_msg == null) { Plugin.Log.LogWarning((object)"Networking failed to set up: this run's history won't be shared with other players"); } } internal static void SendVisit(Visit v) { if (CanSend) { Safe.Optional("Net.SendVisit", delegate { _msg.SendClients("V|" + v.ToJson()); }); } } internal static void SendFired(string visitId, string newRunId) { if (CanSend) { Safe.Optional("Net.SendFired", delegate { _msg.SendClients("F|" + visitId + "|" + newRunId); }); } } internal static void SendNewRun(string runId) { if (CanSend) { Safe.Optional("Net.SendNewRun", delegate { _msg.SendClients("N|" + runId); }); } } private static void OnServer(string data, ulong clientId) { Safe.Optional("Net.OnServer", delegate { if (!(data != "R") && CanSend) { string text = Store.SnapshotJson(); if (text != null) { List<string> list = Chunks.Split(Chunks.Pack(text)); string text2 = Guid.NewGuid().ToString("N").Substring(0, 8); for (int i = 0; i < list.Count; i++) { _msg.SendClient("S|" + text2 + "|" + i + "|" + list.Count + "|" + list[i], clientId); } Plugin.Log.LogInfo((object)$"Sent this run's history to client {clientId}: {Store.Run.Visits.Count} visit(s), {text.Length} characters in {list.Count} piece(s)"); } } }); } internal static void StartClientSync() { Assembler.Reset(); _gotSnapshot = false; int token = ++_syncToken; if (_msg == null) { Store.OnSyncResult(RunStatus.NoHostMod); return; } Runner.After(3f, "Net.Request", delegate { if (token == _syncToken && !Game.IsServer) { Request(); Runner.After(10f, "Net.Retry", delegate { if (token == _syncToken && !_gotSnapshot) { Plugin.Log.LogInfo((object)"No reply from the host yet; asking once more"); Request(); Runner.After(10f, "Net.GiveUp", delegate { if (token == _syncToken && !_gotSnapshot) { Store.OnSyncResult((Assembler.Started || Store.HostHasMod) ? RunStatus.SyncFailed : RunStatus.NoHostMod); } }); } }); } }); } private static void Request() { Safe.Optional("Net.Request", delegate { _msg.SendServer("R"); }); } private static void OnClient(string data) { Safe.Optional("Net.OnClient", delegate { if (!string.IsNullOrEmpty(data) && !Game.IsServer && Store.Enabled) { char c = data[0]; string text = ((data.Length > 2) ? data.Substring(2) : ""); switch (c) { case 'S': { string[] array2 = text.Split(new char[1] { '|' }, 4); if (array2.Length >= 4) { string text2 = Assembler.Add(array2[0], int.Parse(array2[1]), int.Parse(array2[2]), array2[3]); if (text2 != null) { _gotSnapshot = true; Store.OnSnapshot(RunRecord.FromJson(Chunks.Unpack(text2))); } } break; } case 'V': Store.OnHostVisit(Visit.FromJson(text)); break; case 'F': { string[] array = text.Split('|'); Store.OnHostFired((array.Length != 0 && array[0].Length > 0) ? array[0] : null, (array.Length > 1) ? array[1] : null); break; } case 'N': Store.OnHostNewRun(text); break; } } }); } } internal static class Patches { internal static int Wanted; internal static int Applied; private static Harmony _h; private static bool _bcmTried; internal static void Apply(Harmony h) { _h = h; Patch("session start", AccessTools.Method(typeof(StartOfRound), "Start", (Type[])null, (Type[])null), null, "SorStart_Post"); Patch("landing (host)", AccessTools.Method(typeof(StartOfRound), "StartGame", (Type[])null, (Type[])null), null, "StartGame_Post"); Patch("level facts", AccessTools.Method(typeof(RoundManager), "FinishGeneratingNewLevelClientRpc", (Type[])null, (Type[])null), null, "Generated_Post"); Patch("ship leaving", AccessTools.Method(typeof(StartOfRound), "ShipLeave", (Type[])null, (Type[])null), "ShipLeave_Pre", null, 800); bool flag = Patch("takeoff", AccessTools.Method(typeof(HUDManager), "FillEndGameStats", new Type[2] { typeof(EndOfGameStats), typeof(int) }, (Type[])null), null, "FillEndGameStats_Post"); bool flag2 = Patch("takeoff (Company)", AccessTools.Method(typeof(StartOfRound), "EndOfGame", new Type[3] { typeof(int), typeof(int), typeof(int) }, (Type[])null), "EndOfGame_Pre"); Patch("end-of-day haul (host)", AccessTools.Method(typeof(RoundManager), "DespawnPropsAtEndOfRound", new Type[1] { typeof(bool) }, (Type[])null), null, "Despawn_Post", 400, 0); if (!flag && !flag2) { Safe.Disable("neither takeoff hook could be applied (game update?)"); } } private static bool Patch(string feature, MethodBase target, string prefix = null, string postfix = null, int prefixPriority = 400, int postfixPriority = 400) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) Wanted++; try { if (target == null) { Plugin.Log.LogWarning((object)("Hook target for '" + feature + "' not found; that part of the history is off")); return false; } _h.Patch(target, (prefix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(AccessTools.Method(typeof(Patches), prefix, (Type[])null, (Type[])null)) { priority = prefixPriority }, (postfix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(AccessTools.Method(typeof(Patches), postfix, (Type[])null, (Type[])null)) { priority = postfixPriority }, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Applied++; return true; } catch (Exception e) { Safe.Fail("Patch." + feature, e); Plugin.Log.LogWarning((object)("Couldn't hook " + target?.DeclaringType?.Name + "." + target?.Name + " ('" + feature + "'); that part of the history is off")); return false; } } private static void TryPatchBcm() { if (!_bcmTried) { _bcmTried = true; Type type = Game.T("BrutalCompanyMinus.Minus.EventManager"); if (!(type == null) && Patch("BCM events (host)", AccessTools.Method(type, "ApplyEvents", (Type[])null, (Type[])null), null, "BcmApply_Post")) { Plugin.Log.LogInfo((object)"Brutal Company Minus found: recording event names"); } } } private static void SorStart_Post() { Safe.Optional("TryPatchBcm", TryPatchBcm); Safe.Core("SessionStart", Store.OnSessionStart); } private static void StartGame_Post() { Safe.Core("StartGame", Store.OnStartGame); } private static void Generated_Post() { Safe.Core("Generated", Store.OnGenerated); } private static void BcmApply_Post() { Safe.Optional("BcmApplied", Store.OnBcmApplied); } private static void ShipLeave_Pre() { Safe.Core("ShipLeave", Store.OnShipLeave); } private static void FillEndGameStats_Post(int scrapCollected) { Safe.Core("Takeoff", delegate { Store.OnTakeoff(scrapCollected); }); } private static void EndOfGame_Pre(int scrapCollected) { Safe.Core("Takeoff", delegate { Store.OnTakeoff(scrapCollected); }); } private static void Despawn_Post() { Safe.Core("Commit", Store.OnDespawnProps); } } public enum HaulMethodKind { Kept, Vanilla } [BepInPlugin("jacob.moonhistory", "MoonHistory", "1.0.1")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] public class Plugin : BaseUnityPlugin { public const string Guid = "jacob.moonhistory"; public const string Name = "MoonHistory"; public const string Version = "1.0.1"; internal static ManualLogSource Log; internal static bool Ready; internal static string PluginDir; private void Awake() { Log = ((BaseUnityPlugin)this).Logger; PluginDir = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location); Step("config", delegate { Cfg.Init(((BaseUnityPlugin)this).Config); }); Step("causes table", LoadCauses); Step("all-time log", Store.LoadAllTime); Step("networking", Net.Init); Step("save hooks", Store.InitSaveEvents); Step("game hooks", delegate { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Expected O, but got Unknown Patches.Apply(new Harmony("jacob.moonhistory")); }); Step("runner", delegate { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown GameObject val = new GameObject("MoonHistoryRunner") { hideFlags = (HideFlags)61 }; Object.DontDestroyOnLoad((Object)val); Runner.Instance = val.AddComponent<Runner>(); }); Ready = true; if (!Cfg.Enabled.Value) { Log.LogInfo((object)"MoonHistory 1.0.1 loaded but Enabled = false: nothing is recorded"); return; } if (Safe.Disabled) { Log.LogWarning((object)("MoonHistory 1.0.1 loaded but is OFF: " + Safe.DisabledReason)); return; } Log.LogInfo((object)(string.Format("{0} {1} loaded: {2} all-time visits in {3}, ", "MoonHistory", "1.0.1", Store.AllTimeCount, Store.AllTimePathShort) + $"haul method {Cfg.Haul.Value}, {Patches.Applied}/{Patches.Wanted} hooks")); } private static void LoadCauses() { string path = Path.Combine(PluginDir ?? "", "MoonHistory-causes.txt"); if (File.Exists(path)) { int num = Causes.LoadOverrides(File.ReadAllLines(path)); Log.LogInfo((object)$"Read {num} cause names from MoonHistory-causes.txt"); } } private static void Step(string name, Action action) { try { action(); } catch (Exception e) { Safe.Fail("Startup." + name, e); if (name == "game hooks" || name == "config") { Safe.Disable("startup failed at " + name); } } } } internal static class Cfg { internal static ConfigEntry<bool> Enabled; internal static ConfigEntry<bool> RecordAllTime; internal static ConfigEntry<bool> RecordChallengeMoons; internal static ConfigEntry<bool> RecordCompany; internal static ConfigEntry<HaulMethodKind> Haul; internal static ConfigEntry<bool> ShowShortLine; internal static ConfigEntry<bool> ShowAllTime; internal static ConfigEntry<bool> ShowTimeSpent; internal static ConfigEntry<bool> ShowLastDeath; internal static ConfigEntry<bool> ShowPastMoonTotals; internal static ConfigEntry<int> MaxListItems; internal static ConfigEntry<bool> SendToClients; internal static ConfigEntry<bool> AcceptFromHost; internal static ConfigEntry<bool> KeepBackup; internal static int Version; internal static void Init(ConfigFile c) { //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Expected O, but got Unknown Enabled = c.Bind<bool>("General", "Enabled", true, "Off: records nothing and the panel shows no history."); RecordAllTime = c.Bind<bool>("General", "RecordAllTime", true, "Keep the per-profile all-time log (BepInEx/MoonHistory/visits.jsonl)."); RecordChallengeMoons = c.Bind<bool>("General", "RecordChallengeMoons", false, "Record challenge-moon days. They're kept apart from normal moons either way. Host's setting decides the run record."); RecordCompany = c.Bind<bool>("General", "RecordCompany", true, "Count Company visits and sales."); Haul = c.Bind<HaulMethodKind>("Haul", "HaulMethod", HaulMethodKind.Kept, "Kept: value of scrap that wasn't on the ship at landing and is still there after the end-of-day clean-up (counts a magneted Cruiser's load and scrap kept on a wipe paid with a SimpleTeamLives life). Vanilla: the game's 'collected' figure (0 on any wipe)."); ShowShortLine = c.Bind<bool>("Panel", "ShowShortLine", true, "The one-line history in the Day Info short view."); ShowAllTime = c.Bind<bool>("Panel", "ShowAllTime", true, "All-time figures beside this run's."); MaxListItems = c.Bind<int>("Panel", "MaxListItems", 4, new ConfigDescription("Items per list before '+N more'.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 12), Array.Empty<object>())); ShowTimeSpent = c.Bind<bool>("Panel", "ShowTimeSpent", true, "'Time here' line (in-game minutes)."); ShowLastDeath = c.Bind<bool>("Panel", "ShowLastDeath", true, "'Last: name, cause (day N)' line."); ShowPastMoonTotals = c.Bind<bool>("Panel", "ShowPastMoonTotals", true, "Show 'brought back X of Y' from past visits (Y = the moon's total scrap that day)."); SendToClients = c.Bind<bool>("Network", "SendToClients", true, "Host sends the run record and each new visit to clients."); AcceptFromHost = c.Bind<bool>("Network", "AcceptFromHost", true, "Client uses the host's run record. Off: the client only ever shows its own all-time data."); KeepBackup = c.Bind<bool>("Storage", "KeepBackup", true, "Keep visits.jsonl.bak when the file is compacted at startup."); c.SettingChanged += delegate { Version++; }; } internal static LineOptions Options() { return new LineOptions { ShowAllTime = ShowAllTime.Value, MaxListItems = MaxListItems.Value, ShowTimeSpent = ShowTimeSpent.Value, ShowLastDeath = ShowLastDeath.Value, ShowPastMoonTotals = ShowPastMoonTotals.Value }; } } internal sealed class Runner : MonoBehaviour { internal static Runner Instance; private IEnumerator Start() { WaitForSecondsRealtime wait = new WaitForSecondsRealtime(1f); while (true) { yield return wait; Safe.Optional("PollDeaths", Store.PollDeaths); } } internal static void After(float seconds, string site, Action action) { if ((Object)(object)Instance == (Object)null) { Safe.WarnOnce("NoRunner", "MoonHistory's timer object is missing; delayed jobs run straight away"); Safe.Optional(site, action); } else { ((MonoBehaviour)Instance).StartCoroutine(Instance.Wait(seconds, site, action)); } } private IEnumerator Wait(float seconds, string site, Action action) { yield return (object)new WaitForSecondsRealtime(seconds); Safe.Optional(site, action); } } public struct ScrapItem { public ulong Id; public int Value; public ScrapItem(ulong id, int value) { Id = id; Value = value; } } public struct HaulResult { public int Haul; public int ShipAfter; public int? Lost; } public static class HaulMath { public static HaulResult Kept(ICollection<ulong> beforeIds, int shipBefore, IEnumerable<ScrapItem> after, bool wipe) { HaulResult result = default(HaulResult); HashSet<ulong> hashSet = new HashSet<ulong>(); foreach (ScrapItem item in after) { if (hashSet.Add(item.Id)) { result.ShipAfter += item.Value; if (beforeIds == null || !beforeIds.Contains(item.Id)) { result.Haul += item.Value; } } } if (wipe) { int num = shipBefore + result.Haul - result.ShipAfter; if (num > 0) { result.Lost = num; } } return result; } public static HaulResult Vanilla(int scrapCollected, int shipBefore, bool wipe) { HaulResult result = new HaulResult { Haul = Math.Max(0, scrapCollected) }; if (wipe && shipBefore > 0) { result.Lost = shipBefore; } return result; } public static int Sum(IEnumerable<ScrapItem> items) { int num = 0; foreach (ScrapItem item in items) { num += item.Value; } return num; } } public static class Causes { private static readonly string[] Prefixes = new string[6] { "DeathEnemy", "DeathPlayer", "DeathOther", "DeathPit", "Death", "Vanilla" }; public static readonly Dictionary<string, string> Defaults = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "DeathAbandoned", "Left behind" }, { "DeathUnknown", "Unknown" }, { "VanillaUnknown", "Unknown" }, { "VanillaAbandoned", "Left behind" }, { "VanillaStrangulation", "Strangled" }, { "DeathEnemyForestGiantEaten", "Forest Giant" }, { "DeathEnemyForestGiantDeath", "Forest Giant" }, { "DeathEnemyButlerStab", "Butler" }, { "DeathEnemyButlerExplode", "Butler" }, { "DeathEnemyMaskHornets", "Mask Hornets" }, { "DeathEnemyMaskedPlayerWear", "Mask" }, { "DeathEnemyMaskedPlayerVictim", "Masked" }, { "DeathEnemyNutcrackerKicked", "Nutcracker" }, { "DeathEnemyNutcrackerShot", "Nutcracker" }, { "DeathEnemyTulipSnakeDrop", "Tulip Snake" }, { "DeathEnemyOldBirdRocket", "Old Bird" }, { "DeathEnemyOldBirdCharge", "Old Bird" }, { "DeathEnemyOldBirdStomp", "Old Bird" }, { "DeathEnemyOldBirdTorch", "Old Bird" }, { "DeathEnemyCadaverGrowth", "Cadaver" }, { "DeathEnemyCadaverBloom", "Cadaver" }, { "DeathPlayerJetpackGravity", "Jetpack" }, { "DeathPlayerJetpackBlast", "Jetpack" }, { "DeathPlayerMurderShovel", "Crewmate" }, { "DeathPlayerMurderStopSign", "Crewmate" }, { "DeathPlayerMurderYieldSign", "Crewmate" }, { "DeathPlayerMurderShotgun", "Crewmate" }, { "DeathPlayerMurderKnife", "Crewmate" }, { "DeathPlayerCruiserDriver", "Cruiser" }, { "DeathPlayerCruiserPassenger", "Cruiser" }, { "DeathPlayerCruiserExplodeBystander", "Cruiser" }, { "DeathPlayerCruiserRanOver", "Cruiser" }, { "DeathPlayerEasterEgg", "Easter egg" }, { "DeathPlayerStunGrenade", "Stun grenade" }, { "DeathPitGeneric", "Fall" }, { "DeathPitFacilityPit", "Pit" }, { "DeathPitFacilityCatwalkJump", "Catwalk jump" }, { "DeathPitMinePit", "Pit" }, { "DeathPitMineCave", "Pit" }, { "DeathPitMineElevator", "Mine elevator" }, { "DeathOtherDepositItemsDesk", "Company desk" }, { "DeathOtherItemDropship", "Dropship" }, { "DeathOtherOutOfBounds", "Out of bounds" }, { "DeathOtherSpikeTrap", "Spike Trap" } }; private static Dictionary<string, string> _table = new Dictionary<string, string>(Defaults, StringComparer.OrdinalIgnoreCase); public static int LoadOverrides(IEnumerable<string> lines) { Dictionary<string, string> dictionary = new Dictionary<string, string>(Defaults, StringComparer.OrdinalIgnoreCase); int num = 0; foreach (string line in lines) { string text = line.Trim(); if (text.Length == 0 || text.StartsWith("#")) { continue; } int num2 = text.IndexOf('='); if (num2 > 0) { string text2 = text.Substring(0, num2).Trim(); string text3 = text.Substring(num2 + 1).Trim(); if (text2.Length != 0 && text3.Length != 0) { dictionary[text2] = text3; num++; } } } _table = dictionary; return num; } public static bool IsVague(string tag) { if (!string.IsNullOrEmpty(tag) && !tag.EndsWith("Unknown", StringComparison.OrdinalIgnoreCase)) { return tag.EndsWith("Abandoned", StringComparison.OrdinalIgnoreCase); } return true; } public static string Pick(string seenDuringRound, string atTakeoff) { string text; if (IsVague(seenDuringRound)) { if (!string.IsNullOrEmpty(atTakeoff)) { return atTakeoff; } text = seenDuringRound; if (text == null) { return "VanillaUnknown"; } } else { text = seenDuringRound; } return text; } public static string ShortName(string tag) { if (string.IsNullOrEmpty(tag)) { return "Unknown"; } if (_table.TryGetValue(tag, out var value)) { return value; } string text = tag; string[] prefixes = Prefixes; foreach (string text2 in prefixes) { if (text.Length > text2.Length && text.StartsWith(text2, StringComparison.Ordinal) && char.IsUpper(text[text2.Length])) { text = text.Substring(text2.Length); break; } } return SplitCamel(text); } public static string SplitCamel(string s) { if (string.IsNullOrEmpty(s)) { return s; } StringBuilder stringBuilder = new StringBuilder(s.Length + 4); for (int i = 0; i < s.Length; i++) { char c = s[i]; if (c == '_' || c == '-') { if (stringBuilder.Length > 0 && stringBuilder[stringBuilder.Length - 1] != ' ') { stringBuilder.Append(' '); } continue; } if (i > 0 && stringBuilder.Length > 0 && stringBuilder[stringBuilder.Length - 1] != ' ') { char c2 = s[i - 1]; char c3 = ((i + 1 < s.Length) ? s[i + 1] : '\0'); if ((char.IsUpper(c) && (char.IsLower(c2) || char.IsDigit(c2))) || (char.IsUpper(c) && char.IsUpper(c2) && char.IsLower(c3)) || (char.IsDigit(c) && char.IsLetter(c2))) { stringBuilder.Append(' '); } } stringBuilder.Append(c); } return stringBuilder.ToString().Trim(); } } public static class Chunks { public const int MaxPiece = 8000; public static string Pack(string text) { byte[] bytes = Encoding.UTF8.GetBytes(text ?? ""); using MemoryStream memoryStream = new MemoryStream(); using (GZipStream gZipStream = new GZipStream(memoryStream, CompressionMode.Compress, leaveOpen: true)) { gZipStream.Write(bytes, 0, bytes.Length); } return Convert.ToBase64String(memoryStream.ToArray()); } public static string Unpack(string packed) { using MemoryStream stream = new MemoryStream(Convert.FromBase64String(packed)); using GZipStream gZipStream = new GZipStream(stream, CompressionMode.Decompress); using MemoryStream memoryStream = new MemoryStream(); byte[] array = new byte[8192]; int count; while ((count = gZipStream.Read(array, 0, array.Length)) > 0) { memoryStream.Write(array, 0, count); } return Encoding.UTF8.GetString(memoryStream.ToArray()); } public static List<string> Split(string packed, int size = 8000) { List<string> list = new List<string>(); if (string.IsNullOrEmpty(packed)) { list.Add(""); return list; } for (int i = 0; i < packed.Length; i += size) { list.Add(packed.Substring(i, Math.Min(size, packed.Length - i))); } return list; } } public sealed class ChunkAssembler { private string _xfer; private string[] _parts; private int _have; public bool Started => _parts != null; public bool Partial { get { if (_parts != null) { return _have < _parts.Length; } return false; } } public string Add(string xfer, int index, int count, string piece) { if (count <= 0 || count > 10000 || index < 0 || index >= count) { return null; } if (_xfer != xfer || _parts == null || _parts.Length != count) { _xfer = xfer; _parts = new string[count]; _have = 0; } if (_parts[index] == null) { _have++; } _parts[index] = piece ?? ""; if (_have < count) { return null; } string result = string.Concat(_parts); Reset(); return result; } public void Reset() { _xfer = null; _parts = null; _have = 0; } } internal static class Fmt { internal static string N(int n) { return n.ToString("N0", CultureInfo.InvariantCulture); } internal static string Ordinal(int n) { int num = n % 100; if (num >= 11 && num <= 13) { return n + "th"; } return (n % 10) switch { 1 => n + "st", 2 => n + "nd", 3 => n + "rd", _ => n + "th", }; } internal static string Plural(int n, string one, string many) { if (n != 1) { return N(n) + " " + many; } return "1 " + one; } internal static string Date(DateTime? utc) { if (!utc.HasValue) { return "?"; } return utc.Value.ToLocalTime().ToString("d MMM", CultureInfo.InvariantCulture); } internal static string Minutes(int minutes) { if (minutes < 60) { return minutes + " min"; } int num = minutes / 60; int num2 = minutes % 60; if (num2 != 0) { return num + " h " + num2 + " min"; } return num + " h"; } } public sealed class MoonQuery { public string Key; public string Name; public bool Challenge; public ICollection<string> LoadedKeys; public bool SameMoon(Visit v) { if (v == null) { return false; } if (v.MoonKey == Key) { return true; } if (Name != null && LoadedKeys != null && v.MoonName == Name) { return !LoadedKeys.Contains(v.MoonKey); } return false; } public bool Matches(Visit v) { if (SameMoon(v)) { return v.Challenge == Challenge; } return false; } } public sealed class SideStats { public int Count; public Visit Last; public int HaulCount; public int HaulSum; public int Best = -1; public Visit BestVisit; public int Deaths; public int Wipes; public int WipesCostLife; public int WipesEndedRun; public int SoldSum; public int SoldCount; public Death LastDeath; public Visit LastDeathVisit; public int LongDays; public int ShortDays; public int GameMinutes; public int TotalCount; public long TotalHaulSum; public long TotalSum; public Visit LastTotal; public List<KeyValuePair<string, int>> Causes = new List<KeyValuePair<string, int>>(); public List<KeyValuePair<string, int>> Interiors = new List<KeyValuePair<string, int>>(); public List<KeyValuePair<string, int>> Weathers = new List<KeyValuePair<string, int>>(); public List<KeyValuePair<string, int>> Events = new List<KeyValuePair<string, int>>(); public int AvgHaul { get { if (HaulCount != 0) { return (int)Math.Round((double)HaulSum / (double)HaulCount); } return 0; } } public static SideStats Build(IEnumerable<Visit> visits, MoonQuery q) { SideStats sideStats = new SideStats(); Dictionary<string, int> d = new Dictionary<string, int>(); Dictionary<string, int> d2 = new Dictionary<string, int>(); Dictionary<string, int> d3 = new Dictionary<string, int>(); Dictionary<string, int> d4 = new Dictionary<string, int>(); foreach (Visit visit in visits) { if (q != null && !q.Matches(visit)) { continue; } sideStats.Count++; if (sideStats.Last == null || Later(visit, sideStats.Last)) { sideStats.Last = visit; } if (!visit.Company && visit.Haul.HasValue) { sideStats.HaulCount++; sideStats.HaulSum += visit.Haul.Value; if (visit.Haul.Value > sideStats.Best) { sideStats.Best = visit.Haul.Value; sideStats.BestVisit = visit; } if (visit.MoonTotal.HasValue && visit.MoonTotal.Value > 0) { sideStats.TotalCount++; sideStats.TotalHaulSum += visit.Haul.Value; sideStats.TotalSum += visit.MoonTotal.Value; if (sideStats.LastTotal == null || Later(visit, sideStats.LastTotal)) { sideStats.LastTotal = visit; } } } if (visit.Sold.HasValue) { sideStats.SoldCount++; sideStats.SoldSum += visit.Sold.Value; } if (visit.Deaths != null) { foreach (Death death in visit.Deaths) { sideStats.Deaths++; string k = CauseOf(death); Inc(d, k); if (sideStats.LastDeathVisit == null || !Later(sideStats.LastDeathVisit, visit)) { sideStats.LastDeath = death; sideStats.LastDeathVisit = visit; } } } if (visit.Wipe) { sideStats.Wipes++; if (visit.Fired) { sideStats.WipesEndedRun++; } else if (visit.LivesAfter.HasValue) { sideStats.WipesCostLife++; } } if (!visit.Company) { if (!string.IsNullOrEmpty(visit.Interior)) { Inc(d2, visit.Interior); } if (!string.IsNullOrEmpty(visit.Weather)) { Inc(d3, visit.Weather); } if (visit.Events != null) { foreach (string @event in visit.Events) { if (!string.IsNullOrEmpty(@event)) { Inc(d4, @event); } } } if (visit.Dilation == 1) { sideStats.LongDays++; } else if (visit.Dilation == 2) { sideStats.ShortDays++; } } if (visit.GameMinutes.HasValue && visit.GameMinutes.Value > 0) { sideStats.GameMinutes += visit.GameMinutes.Value; } } sideStats.Causes = Sorted(d); sideStats.Interiors = Sorted(d2); sideStats.Weathers = Sorted(d3); sideStats.Events = Sorted(d4); return sideStats; } internal static string CauseOf(Death d) { if (!string.IsNullOrEmpty(d.Tag)) { return MoonHistory.Causes.ShortName(d.Tag); } if (!string.IsNullOrEmpty(d.Cause)) { return d.Cause; } return "Unknown"; } internal static bool Later(Visit a, Visit b) { DateTime? utcTime = a.UtcTime; DateTime? utcTime2 = b.UtcTime; if (utcTime.HasValue && utcTime2.HasValue && utcTime.Value != utcTime2.Value) { return utcTime.Value > utcTime2.Value; } return a.Day > b.Day; } private static void Inc(Dictionary<string, int> d, string k) { d.TryGetValue(k, out var value); d[k] = value + 1; } internal static List<KeyValuePair<string, int>> Sorted(Dictionary<string, int> d) { List<KeyValuePair<string, int>> list = new List<KeyValuePair<string, int>>(d); list.Sort((KeyValuePair<string, int> a, KeyValuePair<string, int> b) => (a.Value == b.Value) ? string.Compare(a.Key, b.Key, StringComparison.OrdinalIgnoreCase) : b.Value.CompareTo(a.Value)); return list; } } public enum RunStatus { Ok, Waiting, NoHostMod, SyncFailed, Off } public sealed class LineOptions { public bool ShowAllTime = true; public int MaxListItems = 4; public bool ShowTimeSpent = true; public bool ShowLastDeath = true; public bool ShowPastMoonTotals = true; } public sealed class LineContext { public string MoonName; public bool Company; public bool Landed; public int? NowDay; public int GapDays; public RunStatus Status; public bool AllTimeOn = true; public int ChallengeVisits; public string ClashKey; public LineOptions Options = new LineOptions(); } public static class Lines { public const int MaxWidth = 70; private const string Dot = " · "; public static string Short(SideStats run, SideStats all, LineContext c) { LineOptions options = c.Options; bool flag = c.AllTimeOn && options.ShowAllTime; if (c.Status == RunStatus.Waiting) { return "History: waiting for host"; } bool flag2 = c.Status == RunStatus.Ok; if (c.Company) { if (flag2) { if (run.Count == 0) { return Fit("History: Company · no visits this run" + ((flag && all.Count > 0) ? (" · " + Fmt.Plural(all.Count, "visit", "visits") + " all time") : "")); } string text = "History: Company · " + Fmt.Plural(run.Count, "visit", "visits") + " this run"; if (run.SoldCount > 0) { text = text + " · sold " + Fmt.N(run.SoldSum); } return Fit(text); } if (flag && all.Count > 0) { return Fit("History: Company · " + Fmt.Plural(all.Count, "visit", "visits") + " all time" + ((all.SoldCount > 0) ? (" · sold " + Fmt.N(all.SoldSum)) : "")); } return "History: Company · no visits yet"; } if (flag2 && run.Count > 0) { string text2 = "History: " + Fmt.Ordinal(run.Count + 1) + " visit"; if (run.HaulCount > 0) { text2 = text2 + " · avg " + Fmt.N(run.AvgHaul) + " · best " + Fmt.N(run.Best); } if (run.Wipes > 0) { return Fit(text2 + " · " + Fmt.Plural(run.Wipes, "wipe", "wipes")); } if (run.Deaths == 0) { return Fit(text2); } string text3 = text2 + " · " + Fmt.Plural(run.Deaths, "death", "deaths"); for (int num = 2; num >= 1; num--) { string text4 = text3 + " (" + NameList(run.Causes, num) + ")"; if (text4.Length <= 70) { return text4; } } return Fit(text3); } if (flag && all.Count > 0) { string text5 = c.Status switch { RunStatus.Ok => "first time this run", RunStatus.NoHostMod => "host has no MoonHistory", RunStatus.SyncFailed => "couldn't sync", _ => null, }; string text6 = "all time " + Fmt.Plural(all.Count, "visit", "visits") + ((all.HaulCount > 0) ? (", avg " + Fmt.N(all.AvgHaul)) : ""); return Fit("History: " + ((text5 == null) ? text6 : (text5 + " · " + text6))); } if (flag2 || all.Count == 0) { if (!c.Landed) { return "History: never landed here"; } return "History: first visit"; } return "History: never landed here"; } public static string[] Full(SideStats run, SideStats all, LineContext c) { LineOptions options = c.Options; bool flag = c.AllTimeOn && options.ShowAllTime; bool flag2 = c.Status == RunStatus.Ok; List<string> list = new List<string>(); list.Add("HISTORY · " + (c.MoonName ?? "?").ToUpperInvariant()); if (!string.IsNullOrEmpty(c.ClashKey)) { list.Add(" (" + c.ClashKey + ")"); } bool flag3 = flag2 && run.Count > 0; bool flag4 = flag && all.Count > 0; if (!flag3 && !flag4) { list.Add((c.Status == RunStatus.Waiting) ? "Waiting for host." : "Never landed here."); StatusLine(list, c); ChallengeLine(list, c); return list.ToArray(); } List<string> list2 = new List<string>(); if (flag2) { list2.Add(Fmt.N(run.Count) + " this run"); } if (flag) { list2.Add(Fmt.N(all.Count) + " all time"); } string text = null; string text2 = null; if (flag3 && run.Last != null) { text2 = "last: day " + run.Last.Day; text = text2 + ", quota " + run.Last.Quota; if (c.NowDay.HasValue) { int num = c.NowDay.Value - run.Last.Day; string text3 = ((num == 0) ? " (just now)" : ((num == 1) ? " (1 day ago)" : ((num > 1) ? (" (" + num + " days ago)") : ""))); text += text3; text2 += text3; } } else if (flag4 && all.Last != null) { text = (text2 = "last: " + Fmt.Date(all.Last.UtcTime)); } string text4 = "Visits: " + string.Join(" · ", list2); if (text == null) { list.Add(text4); } else { string text5 = text4 + " · " + text; list.Add((text5.Length <= 70) ? text5 : (text4 + " · " + text2)); } if (c.Company) { List<string> list3 = new List<string>(); if (flag3 && run.SoldCount > 0) { list3.Add(Fmt.N(run.SoldSum) + " this run"); } if (flag4 && all.SoldCount > 0) { list3.Add(Fmt.N(all.SoldSum) + " all time"); } if (list3.Count > 0) { list.Add("Sold: " + string.Join(" · ", list3)); } DeathLines(list, run, all, c, flag3, flag); StatusLine(list, c); GapLine(list, c); return list.ToArray(); } string text6 = null; string text7 = null; string text8 = null; if (flag3 && run.HaulCount > 0) { text7 = "avg " + Fmt.N(run.AvgHaul) + ", best " + Fmt.N(run.Best); text6 = text7 + ((run.BestVisit != null) ? (" (day " + run.BestVisit.Day + ")") : ""); } if (flag4 && all.HaulCount > 0) { text8 = "all time avg " + Fmt.N(all.AvgHaul) + ", best " + Fmt.N(all.Best); } if (text6 != null || text8 != null) { string text9; if (text6 == null || text8 == null) { text9 = ((text6 == null) ? ("Haul: " + text8 + ((all.BestVisit != null) ? (" (" + Fmt.Date(all.BestVisit.UtcTime) + ")") : "")) : ("Haul: " + text6)); } else { text9 = "Haul: " + text6 + " · " + text8; if (text9.Length > 70) { text9 = "Haul: " + text7 + " · " + text8; } } list.Add(Fit(text9)); } SideStats sideStats = (flag ? all : run); string text10 = (flag ? " (all time)" : " (this run)"); bool flag5 = (flag ? flag4 : flag3); if (options.ShowPastMoonTotals && flag5 && sideStats.TotalCount > 0) { int n = (int)Math.Round((double)sideStats.TotalHaulSum / (double)sideStats.TotalCount); int n2 = (int)Math.Round((double)sideStats.TotalSum / (double)sideStats.TotalCount); int num2 = ((sideStats.TotalSum > 0) ? ((int)Math.Round(100.0 * (double)sideStats.TotalHaulSum / (double)sideStats.TotalSum)) : 0); string text11 = "Brought back: avg " + Fmt.N(n) + " of " + Fmt.N(n2) + " (" + num2 + "%)"; if (sideStats.LastTotal != null && sideStats.TotalCount > 1) { string text12 = text11 + " · last " + Fmt.N(sideStats.LastTotal.Haul.GetValueOrDefault()) + " of " + Fmt.N(sideStats.LastTotal.MoonTotal.GetValueOrDefault()); if (text12.Length <= 70) { text11 = text12; } } list.Add(Fit(text11)); } DeathLines(list, run, all, c, flag3, flag); if (flag5) { ListLine(list, "Interiors: ", sideStats.Interiors, options.MaxListItems, text10); ListLine(list, "Weather: ", sideStats.Weathers, options.MaxListItems, text10); if (sideStats.LongDays > 0 || sideStats.ShortDays > 0) { List<string> list4 = new List<string>(); if (sideStats.LongDays > 0) { list4.Add(sideStats.LongDays + " long"); } if (sideStats.ShortDays > 0) { list4.Add(sideStats.ShortDays + " short"); } list.Add("Days: " + string.Join(", ", list4) + text10); } ListLine(list, "Events: ", sideStats.Events, options.MaxListItems, text10); if (options.ShowTimeSpent && sideStats.GameMinutes > 0) { list.Add("Time here: " + Fmt.Minutes(sideStats.GameMinutes) + " in-game" + text10); } } ChallengeLine(list, c); GapLine(list, c); StatusLine(list, c); return list.ToArray(); } private static void DeathLines(List<string> lines, SideStats run, SideStats all, LineContext c, bool anyRun, bool allOn) { bool flag = c.Status == RunStatus.Ok; if ((!anyRun || (run.Deaths <= 0 && run.Wipes <= 0)) && (!allOn || (all.Deaths <= 0 && all.Wipes <= 0))) { return; } List<string> list = new List<string>(); if (flag) { list.Add(Fmt.N(run.Deaths) + " this run"); } if (allOn) { list.Add(Fmt.N(all.Deaths) + " all time"); } SideStats sideStats = (allOn ? all : run); if ((flag && run.Wipes > 0) || sideStats.Wipes > 0) { List<string> list2 = new List<string>(); if (flag && allOn) { list2.Add("all time " + all.Wipes); } if (sideStats.WipesCostLife > 0) { list2.Add(sideStats.WipesCostLife + " cost a life"); } if (sideStats.WipesEndedRun > 0) { list2.Add(sideStats.WipesEndedRun + " ended the run"); } string text = "wipes " + (flag ? run.Wipes : sideStats.Wipes); string text2 = ((list2.Count > 0) ? (text + " (" + string.Join(", ", list2) + ")") : text); string text3 = "Deaths: " + string.Join(" · ", list) + " · " + text2; list.Add((text3.Length <= 70) ? text2 : text); } lines.Add(Fit("Deaths: " + string.Join(" · ", list))); SideStats sideStats2 = (allOn ? all : run); if (sideStats2.Causes.Count > 0) { lines.Add(Fit(" " + ListText(sideStats2.Causes, c.Options.MaxListItems, 68))); } if (c.Options.ShowLastDeath) { if (anyRun && run.LastDeath != null) { lines.Add(Fit(" Last: " + (run.LastDeathVisit.Wipe ? "team wipe, " : "") + (run.LastDeath.Name ?? "?") + ", " + CauseName(run.LastDeath) + " (day " + run.LastDeathVisit.Day + ")")); } else if (allOn && all.LastDeath != null) { lines.Add(Fit(" Last: " + (all.LastDeathVisit.Wipe ? "team wipe, " : "") + (all.LastDeath.Name ?? "?") + ", " + CauseName(all.LastDeath) + " (" + Fmt.Date(all.LastDeathVisit.UtcTime) + ")")); } } } private static string CauseName(Death d) { return SideStats.CauseOf(d); } private static void StatusLine(List<string> lines, LineContext c) { switch (c.Status) { case RunStatus.Waiting: lines.Add(" This run: waiting for host"); break; case RunStatus.NoHostMod: lines.Add(" This run: host has no MoonHistory"); break; case RunStatus.SyncFailed: lines.Add(" This run: couldn't sync with the host"); break; } } private static void GapLine(List<string> lines, LineContext c) { if (c.Status == RunStatus.Ok && c.GapDays > 0) { lines.Add(" " + Fmt.Plural(c.GapDays, "day", "days") + " of this run " + ((c.GapDays == 1) ? "wasn't" : "weren't") + " recorded"); } } private static void ChallengeLine(List<string> lines, LineContext c) { if (c.ChallengeVisits > 0) { lines.Add(" Challenge: " + Fmt.Plural(c.ChallengeVisits, "visit", "visits")); } } private static void ListLine(List<string> lines, string label, List<KeyValuePair<string, int>> items, int max, string suffix) { if (items != null && items.Count != 0) { lines.Add(label + ListText(items, max, 70 - label.Length - suffix.Length) + suffix); } } public static string ListText(List<KeyValuePair<string, int>> items, int max, int width) { if (max < 1) { max = 1; } StringBuilder stringBuilder = new StringBuilder(); int num = 0; for (int i = 0; i < items.Count; i++) { if (num >= max) { break; } string text = items[i].Key + " ×" + items[i].Value; int num2 = items.Count - (num + 1); string text2 = ((num > 0) ? " · " : "") + text; int num3 = ((num2 > 0) ? (" · +" + num2 + " more").Length : 0); if (num > 0 && stringBuilder.Length + text2.Length + num3 > width) { break; } stringBuilder.Append(text2); num++; } int num4 = items.Count - num; if (num4 > 0) { stringBuilder.Append(" · ").Append('+').Append(num4) .Append(" more"); } return stringBuilder.ToString(); } public static string NameList(List<KeyValuePair<string, int>> items, int max) { List<string> list = new List<string>(); for (int i = 0; i < items.Count && i < max; i++) { list.Add(items[i].Key); } string text = string.Join(", ", list); if (items.Count > max) { text = text + " +" + (items.Count - max); } return text; } private static string Fit(string s) { if (s == null || s.Length <= 70) { return s; } return s.Substring(0, 69).TrimEnd() + "…"; } } internal static class Safe { private const int CoreFailuresBeforeDisable = 3; private static readonly Dictionary<string, int> FailureCounts = new Dictionary<string, int>(); private static readonly HashSet<string> WarnedOnce = new HashSet<string>(); private static readonly HashSet<string> LoggedErrors = new HashSet<string>(); private static int _coreFailures; internal static bool Disabled { get; private set; } internal static string DisabledReason { get; private set; } internal static void Core(string site, Action action) { if (Disabled) { return; } try { action(); } catch (Exception e) { Fail(site, e); if (++_coreFailures >= 3) { Disable($"{_coreFailures} errors in the recording logic (last in {site})"); } } } internal static void Optional(string site, Action action) { try { action(); } catch (Exception e) { Fail(site, e); } } internal static T Optional<T>(string site, Func<T> func, T fallback) { try { return func(); } catch (Exception e) { Fail(site, e); return fallback; } } internal static int Fail(string site, Exception e) { FailureCounts.TryGetValue(site, out var value); value = (FailureCounts[site] = value + 1); switch (value) { case 1: { Exception ex = e; while (ex.InnerException != null) { ex = ex.InnerException; } string item = ex.GetType().FullName + ": " + ex.Message; if (LoggedErrors.Add(item)) { ManualLogSource log2 = Plugin.Log; if (log2 != null) { log2.LogError((object)("[" + site + "] " + e.GetType().Name + ": " + e.Message + ((ex != e) ? ("\n caused by " + ex.GetType().Name + ": " + ex.Message) : "") + "\n" + ex.StackTrace)); } } else { ManualLogSource log3 = Plugin.Log; if (log3 != null) { log3.LogDebug((object)("[" + site + "] same error as above (" + ex.GetType().Name + ")")); } } break; } case 2: { ManualLogSource log = Plugin.Log; if (log != null) { log.LogError((object)("[" + site + "] failed again; further errors from here are not logged")); } break; } } return value; } internal static void WarnOnce(string key, string message) { if (WarnedOnce.Add(key)) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)message); } } } internal static void Disable(string reason) { if (!Disabled) { Disabled = true; DisabledReason = reason; ManualLogSource log = Plugin.Log; if (log != null) { log.LogError((object)("MoonHistory is OFF for this session: " + reason + ". Nothing more is recorded until the game restarts; the game itself is unaffected.")); } Store.BumpSerial(); } } } internal static class Store { private enum DayState { Idle, Active, Skipped, Captured } [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static Action<string> <>9__37_0; public static PostLoadGameEventHandler <>9__38_0; public static PostSaveGameEventHandler <>9__38_1; public static PostAutoSaveEventHandler <>9__38_2; public static PostResetSavedGameValuesEventHandler <>9__38_3; public static Func<string> <>9__51_0; public static Action <>9__52_0; public static Func<List<string>> <>9__55_0; public static Func<List<string>> <>9__56_5; public static Action <>9__60_0; internal void <LoadAllTime>b__37_0(string s) { Plugin.Log.LogWarning((object)s); } internal void <InitSaveEvents>b__38_0(bool challenge, string file) { Safe.Core("OnLoadGame", new <>c__DisplayClass38_0 { file = file }.<InitSaveEvents>b__4); } internal void <InitSaveEvents>b__38_1(bool challenge, string file) { Safe.Optional("OnSaveGame", SaveRun); } internal void <InitSaveEvents>b__38_2(bool challenge, string file) { Safe.Optional("OnAutoSave", SaveRun); } internal void <InitSaveEvents>b__38_3() { Safe.Core("OnFired", OnFired); } internal string <OnGenerated>b__51_0() { return Game.Interior(RoundManager.Instance); } internal void <Begin>b__52_0() { List<ScrapItem> list = Game.ShipScrap(); _beforeIds = new HashSet<ulong>(); foreach (ScrapItem item in list) { _beforeIds.Add(item.Id); } _cur.ShipBefore = HaulMath.Sum(list); } internal List<string> <OnShipLeave>b__55_0() { if (!Game.IsServer) { return Game.EventsClient(); } return Game.EventsHost(); } internal List<string> <OnTakeoff>b__56_5() { if (!Game.IsServer) { return Game.EventsClient(); } return Game.EventsHost(); } internal void <LogPanel>b__60_0() { string shortLine = HistoryApi.ShortLine; if (!string.IsNullOrEmpty(shortLine)) { Plugin.Log.LogInfo((object)("Panel: " + shortLine)); } string[] fullLines = HistoryApi.FullLines; if (fullLines != null) { Plugin.Log.LogDebug((object)("Panel (full):\n " + string.Join("\n ", fullLines))); } } } [CompilerGenerated] private sealed class <>c__DisplayClass38_0 { public string file; internal void <InitSaveEvents>b__4() { OnLoadGame(file); } } private const string RunKey = "MoonHistory.Run"; private const float HostCommitFallbackSeconds = 20f; private const float ClientWaitForHostSeconds = 30f; private const float FiredWindowSeconds = 600f; internal static RunRecord Run = new RunRecord(); private static string _runFile; private static bool _runIsHosts; private static bool _runBlocked; internal static RunStatus Status = RunStatus.Ok; internal static bool HostHasMod; internal static VisitLog AllTime; private static int _serial; private static DayState _state = DayState.Idle; private static Visit _cur; private static SelectableLevel _curLevel; private static HashSet<ulong> _beforeIds; private static int _quotaStart; private static float _realStart; private static float? _minutesStart; private static float? _minutesEnd; private static bool _generated; private static int _vanillaHaul; private static int _dayToken; private static Visit _lastCommitted; private static float _lastCommitTime = -10000f; private static readonly Dictionary<string, string> _seenCause = new Dictionary<string, string>(); internal static int Serial => _serial; internal static int AllTimeCount { get { if (AllTime == null) { return 0; } return AllTime.Visits.Count; } } internal static string AllTimePathShort { get { if (AllTime == null) { return "(none)"; } return "BepInEx/MoonHistory/" + Path.GetFileName(AllTime.PathName); } } internal static bool AllTimeOn { get { if (AllTime != null) { return Cfg.RecordAllTime.Value; } return false; } } internal static bool Enabled { get { if (Plugin.Ready && Cfg.Enabled.Value) { return !Safe.Disabled; } return false; } } internal static void BumpSerial() { _serial++; } internal static void LoadAllTime() { AllTime = new VisitLog(Path.Combine(Path.Combine(Paths.BepInExRootPath, "MoonHistory"), "visits.jsonl"), Cfg.KeepBackup.Value, delegate(string s) { Plugin.Log.LogWarning((object)s); }); Stopwatch stopwatch = Stopwatch.StartNew(); AllTime.Load(); stopwatch.Stop(); if (AllTime.Compacted) { Plugin.Log.LogInfo((object)($"Compacted visits.jsonl: {AllTime.Duplicates} replaced visit line(s) removed" + (Cfg.KeepBackup.Value ? ", old file kept as visits.jsonl.bak" : ""))); } Plugin.Log.LogDebug((object)$"All-time log read in {stopwatch.ElapsedMilliseconds} ms"); _serial++; } internal static void InitSaveEvents() { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Expected O, but got Unknown //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Expected O, but got Unknown //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Expected O, but got Unknown object obj = <>c.<>9__38_0; if (obj == null) { PostLoadGameEventHandler val = delegate(bool challenge, string file) { Safe.Core("OnLoadGame", delegate { OnLoadGame(file); }); }; <>c.<>9__38_0 = val; obj = (object)val; } SaveLoadEvents.PostLoadGameEvent += (PostLoadGameEventHandler)obj; object obj2 = <>c.<>9__38_1; if (obj2 == null) { PostSaveGameEventHandler val2 = delegate { Safe.Optional("OnSaveGame", SaveRun); }; <>c.<>9__38_1 = val2; obj2 = (object)val2; } SaveLoadEvents.PostSaveGameEvent += (PostSaveGameEventHandler)obj2; object obj3 = <>c.<>9__38_2; if (obj3 == null) { PostAutoSaveEventHandler val3 = delegate { Safe.Optional("OnAutoSave", SaveRun); }; <>c.<>9__38_2 = val3; obj3 = (object)val3; } SaveLoadEvents.PostAutoSaveEvent += (PostAutoSaveEventHandler)obj3; object obj4 = <>c.<>9__38_3; if (obj4 == null) { PostResetSavedGameValuesEventHandler val4 = delegate { Safe.Core("OnFired", OnFired); }; <>c.<>9__38_3 = val4; obj4 = (object)val4; } SaveLoadEvents.PostResetSavedGameValuesEvent += (PostResetSavedGameValuesEventHandler)obj4; } private static void OnLoadGame(string file) { if (Game.IsHosting) { LoadRun(file); } } private static void LoadRun(string file) { string text = null; bool flag = false; try { text = SaveLoadHandler.LoadData<string>("MoonHistory.Run", (SaveLocation)0, (string)null, false); } catch (Exception e) { Safe.Fail("LoadRun", e); flag = true; } RunRecord runRecord = null; if (!flag && !string.IsNullOrEmpty(text)) { try { runRecord = RunRecord.FromJson(text); } catch (Exception ex) { Plugin.Log.LogWarning((object)("This run's history in " + file + " couldn't be read (" + ex.Message + "); it won't be written this session, to protect it")); flag = true; } } _runBlocked = flag; _runIsHosts = true; _runFile = Game.CurrentSaveFile; Status = RunStatus.Ok; if (runRecord == null) { Run = new RunRecord(); if (!flag) { Plugin.Log.LogInfo((object)("New run on " + file)); } } else { Run = runRecord; Plugin.Log.LogInfo((object)($"Loaded this run's history from {file}: {Run.Visits.Count} visit(s), day {Run.DaysSeen}" + ((Run.GapDays > 0) ? $", {Run.GapDays} unrecorded day(s)" : ""))); } _serial++; } private static void SaveRun() { if (Game.IsHosting && _runIsHosts && !_runBlocked && Run != null && !(_runFile != Game.CurrentSaveFile) && !SaveLoadHandler.SaveData<string>(Run.ToJson(), "MoonHistory.Run", (SaveLocation)0, false)) { Safe.WarnOnce("SaveRun", "LethalModDataLib couldn't save this run's history (further failures not logged)"); } } private static void EnsureHostRun() { if (!_runIsHosts || !(_runFile == Game.CurrentSaveFile) || Run == null) { Safe.WarnOnce("LateLoad", "This run's history wasn't loaded with the save; loading it now"); LoadRun(Game.CurrentSaveFile ?? "current save"); } } private static void CheckDays(int daysSpent) { if (daysSpent > Run.DaysSeen) { if (Run.DaysSeen > 0 || Run.Visits.Count > 0 || daysSpent > 0) { int num = daysSpent - Run.DaysSeen; Run.GapDays += num; Plugin.Log.LogInfo((object)$"{num} day(s) of this run weren't recorded (save is at day {daysSpent}, record at day {Run.DaysSeen})"); } Run.DaysSeen = daysSpent; _serial++; } else if (daysSpent < Run.DaysSeen) { Plugin.Log.LogInfo((object)$"The save is at day {daysSpent} but this run's history is at day {Run.DaysSeen}: the slot was reset elsewhere, starting a new run"); Run = new RunRecord { DaysSeen = daysSpent }; Net.SendNewRun(Run.RunId); _serial++; } } private static void OnFired() { if (!Game.IsHosting) { return; } ResetDay(); string id = ((Run != null) ? Run.RunId : null); string text = null; if (_lastCommitted != null && Time.realtimeSinceStartup - _lastCommitTime < 600f && Run != null) { _lastCommitted.Fired = true; Run.Put(_lastCommitted); if (AllTimeOn && AllTime.Contains(_lastCommitted.Id)) { AllTime.Add(_lastCommitted.Clone()); } text = _lastCommitted.Id; } _lastCommitted = null; Run = new RunRecord(); _runIsHosts = true; _runFile = Game.CurrentSaveFile; _runBlocked = false; Status = RunStatus.Ok; SaveRun(); Net.SendFired(text, Run.RunId); _serial++; Plugin.Log.LogInfo((object)("Crew fired: run " + Short(id) + " closed" + ((text != null) ? (" (day " + text.Substring(text.LastIndexOf('-') + 1) + " marked fired)") : "") + ", new run " + Short(Run.RunId) + " started")); } private static string Short(string id) { if (!string.IsNullOrEmpty(id)) { if (id.Length <= 8) { return id; } return id.Substring(0, 8); } return "?"; } internal static void OnSessionStart() { ResetDay(); _lastCommitted = null; if (Game.IsServer) { if (Game.IsHosting) { EnsureHostRun(); } Status = RunStatus.Ok; } else { _runIsHosts = false; _runFile = null; Run = new RunRecord(); HostHasMod = false; Status = (Cfg.AcceptFromHost.Value ? RunStatus.Waiting : RunStatus.Off); Net.StartClientSync(); } _serial++; } internal static void PollDeaths() { if (!Enabled || _state != DayState.Active) { return; } StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance == (Object)null || instance.allPlayerScripts == null) { return; } PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts; foreach (PlayerControllerB p in allPlayerScripts) { if ((Object)(object)p == (Object)null || !p.isPlayerDead) { continue; } string key = (string.IsNullOrEmpty(p.playerUsername) ? "Player" : p.playerUsername); if (!_seenCause.TryGetValue(key, out var value) || Causes.IsVague(value)) { string value2 = Safe.Optional("CauseTag.Poll", () => Game.CauseTag(p), null); if (!string.IsNullOrEmpty(value2)) { _seenCause[key] = value2; } } } } private static void ResetDay() { _seenCause.Clear(); _state = DayState.Idle; _cur = null; _curLevel = null; _beforeIds = null; _generated = false; _minutesStart = (_minutesEnd = null); _dayToken++; } internal static void OnStartGame() { if (!Enabled || !Game.IsServer) { return; } StartOfRound instance = StartOfRound.Instance; if (!((Object)(object)instance == (Object)null) && !((Object)(object)instance.currentLevel == (Object)null)) { if (_state == DayState.Captured) { Plugin.Log.LogWarning((object)"The previous day was never committed; it's dropped"); } ResetDay(); Begin(instance, instance.currentLevel); } } internal static void OnGenerated() { if (!Enabled) { return; } StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance == (Object)null || (Object)(object)instance.currentLevel == (Object)null) { return; } if (_state == DayState.Idle || (_state == DayState.Active && (Object)(object)_curLevel != (Object)(object)instance.currentLevel)) { ResetDay(); Begin(instance, instance.currentLevel); } if (_state != DayState.Active || _generated) { return; } _generated = true; SelectableLevel level = instance.currentLevel; if (!_cur.Company) { _cur.Interior = Safe.Optional("Interior", () => Game.Interior(RoundManager.Instance), null); _cur.Weather = Safe.Optional("Weather", () => Game.WeatherName(level), null); ReadDilation(level); } if (level.planetHasTime) { _minutesStart = Game.DayMinutes(); } } private static void Begin(StartOfRound sor, SelectableLevel level) { bool isChallengeFile = sor.isChallengeFile; bool flag = Game.IsCompany(level); _curLevel = level; if ((isChallengeFile && !Cfg.RecordChallengeMoons.Value) || (flag && !Cfg.RecordCompany.Value)) { _state = DayState.Skipped; return; } int num = ((sor.gameStats != null) ? sor.gameStats.daysSpent : 0); if (Game.IsServer && Game.IsHosting) { EnsureHostRun(); CheckDays(num); } TimeOfDay instance = TimeOfDay.Instance; _cur = new Visit { MoonKey = Game.MoonKey(level), MoonName = Game.MoonName(level), Day = num + 1, Quota = (((Object)(object)instance != (Object)null) ? (instance.timesFulfilledQuota + 1) : 0), Company = flag, Challenge = isChallengeFile, Host = Game.IsServer }; _quotaStart = (((Object)(object)instance != (Object)null) ? instance.quotaFulfilled : 0); _realStart = Time.realtimeSinceStartup; Safe.Optional("ShipBefore", delegate { List<ScrapItem> list = Game.ShipScrap(); _beforeIds = new HashSet<ulong>(); foreach (ScrapItem item in list) { _beforeIds.Add(item.Id); } _cur.ShipBefore = HaulMath.Sum(list); }); _state = DayState.Active; } private static void ReadDilation(SelectableLevel level) { if (_cur.Dilation != 0 || _cur.DayPercent.HasValue) { return; } Safe.Optional("Dilation", delegate { if (Game.Dilation(level, out var kind, out var dayPercent)) { _cur.Dilation = ((kind == 1 || kind == 2) ? kind : 0); if (_cur.Dilation != 0) { _cur.DayPercent = dayPercent; } } }); } internal static void OnBcmApplied() { if (_state == DayState.Active && !_cur.Company) { List<string> list = Game.EventsHost(); if (list != null && list.Count > 0) { _cur.Events = list; } } } internal static void OnShipLeave() { if (_state != DayState.Active) { return; } Safe.Optional("PollDeaths.Leave", PollDeaths); SelectableLevel level = _curLevel; if (!_cur.Company) { List<string> list = Safe.Optional("Events", () => (!Game.IsServer) ? Game.EventsClient() : Game.EventsHost(), null); if (list != null && list.Count > 0) { _cur.Events = list; } string text = Safe.Optional("WeatherLater", () => Game.WeatherName(level), null); if (!string.IsNullOrEmpty(text) && !string.IsNullOrEmpty(_cur.Weather) && text != _cur.Weather) { _cur.WeatherLater = text; } ReadDilation(level); } if ((Object)(object)level != (Object)null && level.planetHasTime) { _minutesEnd = Game.DayMinutes(); } } internal static void OnTakeoff(int scrapCollected) { if (!Enabled) { return; } StartOfRound sor = StartOfRound.Instance; if ((Object)(object)sor == (Object)null) { return; } if (_state == DayState.Skipped) { if (Game.IsServer && Game.IsHosting && _runIsHosts && sor.gameStats != null) { Run.DaysSeen = Math.Max(Run.DaysSeen, sor.gameStats.daysSpent + 1); } ResetDay(); } else { if (_state != DayState.Active) { return; } Visit v = _cur; if (v.Events == null && !v.Company) { List<string> list = Safe.Optional("Events.Takeoff", () => (!Game.IsServer) ? Game.EventsClient() : Game.EventsHost(), null); if (list != null && list.Count > 0) { v.Events = list; } } v.Utc = DateTime.UtcNow.ToString("o"); v.RealSeconds = (int)Math.Round(Time.realtimeSinceStartup - _realStart); if ((Object)(object)_curLevel != (Object)null && _curLevel.planetHasTime) { float num = _minutesEnd ?? Game.DayMinutes(); if (_minutesStart.HasValue && num >= _minutesStart.Value) { v.GameMinutes = (int)Math.Round(num - _minutesStart.Value); } } Safe.Optional("Crew", delegate { ReadCrew(sor, v); }); v.Wipe = sor.allPlayersDead || (v.Crew.Count > 0 && v.Deaths.Count == v.Crew.Count); if (!v.Company) { Safe.Optional("MoonTotal", delegate { RoundManager instance = RoundManager.Instance; if ((Object)(object)instance != (Object)null && instance.totalScrapValueInLevel > 0f) { v.MoonTotal = (int)Math.Round(instance.totalScrapValueInLevel); } }); } if (v.Company) { Safe.Optional("Sold", delegate { TimeOfDay instance = TimeOfDay.Instance; if ((Object)(object)instance != (Object)null && instance.quotaFulfilled >= _quotaStart) { v.Sold = instance.quotaFulfilled - _quotaStart; } }); } if (Game.IsServer) { v.LivesAfter = Safe.Optional("StlLives", Game.StlLives, null); } _vanillaHaul = scrapCollected; _state = DayState.Captured; int token = _dayToken; if (Game.IsServer) { if (Game.IsHosting && _runIsHosts) { Run.DaysSeen = Math.Max(Run.DaysSeen, v.Day); } Runner.After(20f, "HostCommitFallback", delegate { if (token == _dayToken && _state == DayState.Captured) { Safe.WarnOnce("NoDespawnHook", "The end-of-day clean-up hook didn't run; this visit uses the game's 'collected' figure"); CommitHost(HaulMath.Vanilla(_vanillaHaul, _cur.ShipBefore.GetValueOrDefault(), _cur.Wipe), "vanilla"); } }); } else if (Cfg.AcceptFromHost.Value && (HostHasMod || Status == RunStatus.Waiting)) { Runner.After(30f, "ClientCommitFallback", delegate { if (token == _dayToken && _state == DayState.Captured) { Plugin.Log.LogWarning((object)"The host's record of this day didn't arrive; keeping our own copy in all time"); CommitLocal(); } }); } else { CommitLocal(); } } } private static void ReadCrew(StartOfRound sor, Visit v) { if (sor.allPlayerScripts == null) { return; } PlayerControllerB[] allPlayerScripts = sor.allPlayerScripts; foreach (PlayerControllerB p in allPlayerScripts) { if ((Object)(object)p == (Object)null || p.disconnectedMidGame || (!p.isPlayerControlled && !p.isPlayerDead)) { continue; } string text = (string.IsNullOrEmpty(p.playerUsername) ? "Player" : p.playerUsername); v.Crew.Add(text); if (p.isPlayerDead) { string atTakeoff = Safe.Optional("CauseTag", () => Game.CauseTag(p), "VanillaUnknown"); _seenCause.TryGetValue(text, out var value); string tag = Causes.Pick(value, atTakeoff); v.Deaths.Add(new Death { Name = text, Tag = tag, Cause = Causes.ShortName(tag) }); } } } internal static void OnDespawnProps() { if (_state != DayState.Captured || !Game.IsServer) { return; } bool wipe = _cur.Wipe; HaulResult r; string method; if (_cur.Company) { r = default(HaulResult); method = null; } else if (Cfg.Haul.Value == HaulMethodKind.Vanilla) { r = HaulMath.Vanilla(_vanillaHaul, _cur.ShipBefore.GetValueOrDefault(), wipe); method = "vanilla"; } else { try { if (_beforeIds == null) { throw new InvalidOperationException("no landing snapshot of the ship"); } r = HaulMath.Kept(_beforeIds, _cur.ShipBefore.GetValueOrDefault(), Game.ShipScrap(), wipe); method = "kept"; } catch (Exception ex) { Safe.WarnOnce("HaulFallback", "Couldn't work out the kept haul (" + ex.Message + "); using the game's figure for this visit (further cases not logged)"); r = HaulMath.Vanilla(_vanillaHaul, _cur.ShipBefore.GetValueOrDefault(), wipe); method = "vanilla"; } } CommitHost(r, method); } private static void CommitHost(HaulResult r, string method) { Visit cur = _cur; if (!cur.Company) { cur.Haul = r.Haul; cur.HaulMethod = method; if (method == "kept") { cur.ShipAfter = r.ShipAfter; } cur.Lost = r.Lost; } if (Game.IsHosting) { EnsureHostRun(); } cur.Id = Run.RunId + "-" + cur.Day; Run.Put(cur); Run.DaysSeen = Math.Max(Run.DaysSeen, cur.Day); if (AllTimeOn) { AllTime.Add(cur.Clone()); } Net.SendVisit(cur); _lastCommitted = cur; _lastCommitTime = Time.realtimeSinceStartup; ResetDay(); _serial++; Plugin.Log.LogInfo((object)Describe(cur, "recorded")); LogPanel(); } private static void LogPanel() { Safe.Optional("LogPanel", delegate { string shortLine = HistoryApi.ShortLine; if (!string.IsNullOrEmpty(shortLine)) { Plugin.Log.LogInfo((object)("Panel: " + shortLine)); } string[] fullLines = HistoryApi.FullLines; if (fullLines != null) { Plugin.Log.LogDebug((object)("Panel (full):\n " + string.Join("\n ", fullLines))); } }); } private static void CommitLocal() { Visit cur = _cur; if (!cur.Company) { cur.Haul = HaulMath.Vanilla(_vanillaHaul, cur.ShipBefore.GetValueOrDefault(), cur.Wipe).Haul; cur.HaulMethod = "vanilla"; } cur.Host = false; cur.Id = "local-" + DateTime.UtcNow.Ticks; if (AllTimeOn) { AllTime.Add(cur); } ResetDay(); _serial++; Plugin.Log.LogInfo((object)Describe(cur, "recorded locally (all time only)")); } private static string Describe(Visit v, string what) { string text = $"Day {v.Day} on {v.MoonName} {what}"; text = ((!v.Company) ? (text + ": haul " + (v.Haul.HasValue ? Fmt.N(v.Haul.Value) : "?") + " (" + (v.HaulMethod ?? "?") + ")") : (text + (v.Sold.HasValue ? (": sold " + Fmt.N(v.Sold.Value)) : ""))); if (v.Deaths.Count > 0) { text += $", {v.Deaths.Count} death(s)"; } if (v.Wipe) { text = text + ", team wipe" + (v.Lost.HasValue ? (" (lost " + Fmt.N(v.Lost.Value) + ")") : ""); } if (v.LivesAfter.HasValue) { text += $", lives {v.LivesAfter.Value}"; } return text; } internal static void OnSnapshot(RunRecord r) { HostHasMod = true; if (Cfg.AcceptFromHost.Value) { Run = r; _runIsHosts = false; Status = RunStatus.Ok; _serial++; Plugin.Log.LogInfo((object)$"Got this run's history from the host: {r.Visits.Count} visit(s)"); } } internal static void OnHostVisit(Visit v) { HostHasMod = true; if (v == null || !Cfg.AcceptFromHost.Value) { return; } string localName = Game.LocalName; bool flag = (localName != null && v.Crew != null && v.Crew.Contains(localName)) || (_state == DayState.Captured && _cur != null && _cur.MoonKey == v.MoonKey); if (flag) { if (_state == DayState.Captured) { ResetDay(); } if (AllTimeOn) { Visit visit = v.Clone(); visit.Host = false; AllTime.Add(visit); } } Run.Put(v); if (Status != RunStatus.Ok && Status != RunStatus.Off) { Status = RunStatus.Ok; } _serial++; Plugin.Log.LogInfo((object)Describe(v, flag ? "received from the host" : "received from the host (not added to all time: not in the crew)")); LogPanel(); } internal static void OnHostFired(string visitId, string newRunId) { HostHasMod = true; if (!string.IsNullOrEmpty(visitId)) { foreach (Visit visit2 in Run.Visits) { if (visit2.Id == visitId) { visit2.Fired = true; } } if (AllTimeOn && AllTime.Contains(visitId)) { foreach (Visit visit3 in AllTime.Visits) { if (!(visit3.Id != visitId)) { Visit visit = visit3.Clone(); visit.Fired = true; AllTime.Add(visit); break; } } } } if (Cfg.AcceptFromHost.Value) { Run = new RunRecord { RunId = (newRunId ?? Guid.NewGuid().ToString("N")) }; Status = RunStatus.Ok; } _serial++; Plugin.Log.LogInfo((object)"Host: crew fired, new run started"); } internal static void OnHostNewRun(string runId) { HostHasMod = true; if (Cfg.AcceptFromHost.Value) { Run = new RunRecord { RunId = (runId ?? Guid.NewGuid().ToString("N")) }; Status = RunStatus.Ok; _serial++; } } internal static void OnSyncResult(RunStatus status) { if (Status != RunStatus.Ok && Status != RunStatus.Off) { Status = status; _serial++; Plugin.Log.LogInfo((object)((status == RunStatus.NoHostMod) ? "The host doesn't seem to run MoonHistory: recording our own visits to all time only" : "Couldn't get this run's history from the host (pieces missing); showing our own all time")); } } internal static string SnapshotJson() { if (Run == null || !_runIsHosts) { return null; } return Run.ToJson(); } } public sealed class Death { public string Name; public string Tag; public string Cause; } public sealed class Visit { public const int FormatVersion = 1; public string Id; public string MoonKey; public string MoonName; public int Day; public int Quota; public string Utc; public int? Haul; public int? ShipBefore; public int? ShipAfter; public int? Lost; public int? MoonTotal; public List<Death> Deaths = new List<Death>(); public bool Wipe; public int? LivesAfter; public bool Fired; public string Interior; public string Weather; public string WeatherLater; public int Dilation; public int? DayPercent; public List<string> Events; public List<string> Crew = new List<string>(); public int? RealSeconds; public int? GameMinutes; public bool Company; public int? Sold; public bool Challenge; public bool Host; public string HaulMethod; public DateTime? UtcTime { get { if (string.IsNullOrEmpty(Utc)) { return null; } if (!DateTime.TryParse(Utc, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out var result)) { return null; } return result; } } public Visit Clone() { Visit visit = (Visit)MemberwiseClone(); visit.Deaths = new List<Death>(); foreach (Death death in Deaths) { visit.Deaths.Add(new Death { Name = death