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 ValPerfMonitor v1.6.1
plugins/ValPerfMonitor.dll
Decompiled a month 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.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using HarmonyLib.Public.Patching; using Microsoft.CodeAnalysis; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Collections.Generic; using Steamworks; using Unity.Profiling; using UnityEngine; using UnityEngine.Profiling; using UnityEngine.SceneManagement; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("ProbeTest")] [assembly: InternalsVisibleTo("RepTest")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyCompany("ValPerfMonitor")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.6.1.0")] [assembly: AssemblyInformationalVersion("1.6.1+c2bdc1f12ed51549180765c2279617917e522ca0")] [assembly: AssemblyProduct("ValPerfMonitor")] [assembly: AssemblyTitle("ValPerfMonitor")] [assembly: AssemblyVersion("1.6.1.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ValPerfMonitor { internal sealed class AbTest { private sealed class Removed { public MethodBase Original; public Patch Patch; public HarmonyPatchType Type; } public sealed class Phase { public bool On; public int Capture; public double FrameMs; public double CpuMainMs; public double Fps1Low; public double GcPerMin; public double SlowPerMin; public double Seconds; public double GarbageKbPerFrame; public List<string> Weathers = new List<string>(); public float MovedM; public int ObjectsMin = -1; public int ObjectsMax = -1; public bool HasPos; public int ScriptRuns; public Vector3 StartPos; public string WeatherText { get { if (Weathers.Count != 0) { return string.Join(" -> ", Weathers); } return "?"; } } } private sealed class Comparison { public double Diff; public double Spread; public int Pairs; public int LeftOut; public List<string> Problems = new List<string>(); public bool Real; public bool SameWay; public List<double> PairDiffs = new List<double>(); } [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static Func<Removed, string> <>9__45_0; public static Func<MethodInfo, string> <>9__45_1; public static Func<GameObject, bool> <>9__45_2; public static Func<GameObject, string> <>9__45_3; public static Func<ModEntry, bool> <>9__51_0; public static Func<ModEntry, string> <>9__51_3; public static Func<GameObject, Transform> <>9__56_1; public static Func<Phase, bool> <>9__71_0; public static Func<Phase, double> <>9__71_1; public static Func<Phase, double> <>9__71_2; public static Func<Phase, bool> <>9__79_0; public static Func<Phase, bool> <>9__79_1; public static Func<double, string> <>9__79_2; public static Func<Phase, bool> <>9__79_3; public static Func<Phase, double> <>9__79_10; public static Func<Phase, double> <>9__79_11; public static Func<Phase, double> <>9__79_12; public static Func<Phase, double> <>9__79_4; public static Func<Phase, double> <>9__79_5; public static Func<Phase, double> <>9__79_6; public static Func<Phase, double> <>9__79_7; public static Func<Phase, double> <>9__79_8; public static Func<Phase, double> <>9__79_9; public static Func<double, bool> <>9__81_0; public static Func<double, bool> <>9__81_1; public static Func<Phase, double> <>9__83_1; public static Func<Phase, double> <>9__83_2; public static Func<Phase, double> <>9__83_3; public static Func<Phase, double> <>9__83_4; public static Func<Phase, double> <>9__83_5; public static Func<Phase, double> <>9__83_6; public static Func<Phase, double> <>9__83_7; public static Func<Phase, double> <>9__83_8; internal string <Describe>b__45_0(Removed r) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return $"{r.Type} {Instrumenter.Describe(r.Patch.PatchMethod)} on {Instrumenter.Describe(r.Original)}"; } internal string <Describe>b__45_1(MethodInfo m) { return "skip " + Instrumenter.Describe(m); } internal bool <Describe>b__45_2(GameObject o) { return (Object)(object)o != (Object)null; } internal string <Describe>b__45_3(GameObject o) { return $"switch off {PathOf(o.transform)} (instanceId {((Object)o).GetInstanceID()})"; } internal bool <FindMod>b__51_0(ModEntry m) { return !m.IsGame; } internal string <FindMod>b__51_3(ModEntry m) { return m.Name; } internal Transform <FindPath>b__56_1(GameObject r) { return r.transform; } internal bool <MainMetric>b__71_0(Phase x) { return !double.IsNaN(x.CpuMainMs); } internal double <MainMetric>b__71_1(Phase x) { return x.CpuMainMs; } internal double <MainMetric>b__71_2(Phase x) { return x.FrameMs; } internal bool <Judge>b__79_0(Phase x) { return x.On; } internal bool <Judge>b__79_1(Phase x) { return !x.On; } internal string <Judge>b__79_2(double d) { return Signed(d); } internal bool <Judge>b__79_3(Phase x) { return !double.IsNaN(x.GarbageKbPerFrame); } internal double <Judge>b__79_10(Phase x) { return x.GarbageKbPerFrame; } internal double <Judge>b__79_11(Phase x) { return x.GarbageKbPerFrame; } internal double <Judge>b__79_12(Phase x) { return x.GarbageKbPerFrame; } internal double <Judge>b__79_4(Phase x) { return x.GcPerMin; } internal double <Judge>b__79_5(Phase x) { return x.GcPerMin; } internal double <Judge>b__79_6(Phase x) { return x.Fps1Low; } internal double <Judge>b__79_7(Phase x) { return x.Fps1Low; } internal double <Judge>b__79_8(Phase x) { return x.SlowPerMin; } internal double <Judge>b__79_9(Phase x) { return x.SlowPerMin; } internal bool <Compare>b__81_0(double d) { return d > 0.0; } internal bool <Compare>b__81_1(double d) { return d < 0.0; } internal double <CsvLine>b__83_1(Phase x) { return x.CpuMainMs; } internal double <CsvLine>b__83_2(Phase x) { return x.CpuMainMs; } internal double <CsvLine>b__83_3(Phase x) { return x.GarbageKbPerFrame; } internal double <CsvLine>b__83_4(Phase x) { return x.GarbageKbPerFrame; } internal double <CsvLine>b__83_5(Phase x) { return x.FrameMs; } internal double <CsvLine>b__83_6(Phase x) { return x.FrameMs; } internal double <CsvLine>b__83_7(Phase x) { return x.GcPerMin; } internal double <CsvLine>b__83_8(Phase x) { return x.GcPerMin; } } private const float MaxMoveM = 10f; private const double MaxObjectChange = 0.15; public const int MaxRounds = 6; public readonly string What; public readonly string Label; public readonly float Seconds; public readonly List<bool> Plan = new List<bool>(); public readonly List<Phase> Phases = new List<Phase>(); public string Error; public string Verdict = ""; public readonly List<string> VerdictLines = new List<string>(); public bool Done; public int Step = -1; public BridgeScript Script; private int _runsAtTurnStart; public int RoundsUsed; public int RoundsLeftOut; private readonly int _requestedRounds; private Phase _turn = new Phase(); private int _sampleCountdown; private readonly List<Removed> _removed = new List<Removed>(); private readonly List<MethodInfo> _skipped = new List<MethodInfo>(); private readonly List<GameObject> _objects = new List<GameObject>(); private readonly List<GameObject> _switchedOff = new List<GameObject>(); private readonly Harmony _skipHarmony; private readonly ManualLogSource _log; private readonly string _crumbPath; private bool _off; private int _savedTarget; private int _savedVsync; private bool _uncapped; private long _prevHeap = -1L; private long _heapBytes; private int _heapFrames; private ulong _prevCycles; private ulong _cycles; private int _cpuFrames; private static readonly MethodInfo SkipVoid = AccessTools.Method(typeof(AbTest), "SkipPrefix", (Type[])null, (Type[])null); private static readonly MethodInfo SkipBool = AccessTools.Method(typeof(AbTest), "SkipPrefixKeepGoing", (Type[])null, (Type[])null); public const string CsvHeader = "session,time,what,seconds_per_turn,turns,cpu_ms_normal,cpu_ms_off,garbage_kb_per_frame_normal,garbage_kb_per_frame_off,frame_ms_normal,frame_ms_off,gc_per_min_normal,gc_per_min_off,verdict,rounds_used,rounds_left_out,game_version,mods_fingerprint\n"; public int PatchCount => _removed.Count; public int SkipCount => _skipped.Count; public int ObjectCount => _objects.Count; public string Status { get { if (!Done) { return string.Format("A/B test {0}: turn {1}/{2} ({3})", What, Step + 1, Plan.Count, Plan[Math.Max(0, Step)] ? "normal" : "taken off") + ((Script == null) ? "" : string.Format(", action script run {0}{1}", Script.Runs - _runsAtTurnStart, Script.Running ? " running" : "")); } return "A/B test finished"; } } public IEnumerable<string> Describe() { return _removed.Select((Removed r) => $"{r.Type} {Instrumenter.Describe(r.Patch.PatchMethod)} on {Instrumenter.Describe(r.Original)}").Concat(_skipped.Select((MethodInfo m) => "skip " + Instrumenter.Describe(m))).Concat(from o in _objects.Where((GameObject o) => (Object)(object)o != (Object)null).Take(50) select $"switch off {PathOf(o.transform)} (instanceId {((Object)o).GetInstanceID()})"); } private static bool SkipPrefix() { return false; } private static bool SkipPrefixKeepGoing(ref bool __result) { __result = true; return false; } public AbTest(string mod, string patchesOn, string skip, int objectId, string objectPath, string prefab, float seconds, int rounds, string label, ModRegistry registry, string harmonyId, string rootFolder, ManualLogSource log) { //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Expected O, but got Unknown _log = log; _skipHarmony = new Harmony(harmonyId); _crumbPath = Path.Combine(rootFolder, "ab-test-in-progress.txt"); Seconds = Math.Max(10f, seconds); rounds = Math.Max(1, Math.Min(6, rounds)); _requestedRounds = rounds; for (int i = 0; i < rounds; i++) { AddRound(); } if (!string.IsNullOrWhiteSpace(skip)) { What = "skip " + skip.Trim(); FindSkip(skip.Trim(), registry); } else if (!string.IsNullOrWhiteSpace(mod)) { ModEntry modEntry = FindMod(mod.Trim(), registry); if (modEntry == null) { return; } What = modEntry.Name + (string.IsNullOrWhiteSpace(patchesOn) ? " (all its patches)" : (" (its patches on " + patchesOn.Trim() + ")")); FindPatches(modEntry, patchesOn, registry, harmonyId); } else if (objectId != 0 || !string.IsNullOrWhiteSpace(objectPath) || !string.IsNullOrWhiteSpace(prefab)) { What = FindObjects(objectId, objectPath, prefab); } else { Error = "say which mod (mod), which mod method to skip (skip), or which object to switch off (objectId, objectPath or prefab)"; } Label = (string.IsNullOrWhiteSpace(label) ? ("AB " + What) : label.Trim()); if (Error == null && _removed.Count == 0 && _skipped.Count == 0 && _objects.Count == 0) { Error = "nothing to take off: no matching patches, methods or objects found"; } } private ModEntry FindMod(string name, ModRegistry registry) { List<ModEntry> source = registry.Visible.Where((ModEntry m) => !m.IsGame).ToList(); List<ModEntry> list = source.Where((ModEntry m) => string.Equals(m.Guid, name, StringComparison.OrdinalIgnoreCase) || string.Equals(m.Name, name, StringComparison.OrdinalIgnoreCase)).ToList(); if (list.Count == 0) { list = source.Where((ModEntry m) => m.Name.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0).ToList(); } if (list.Count == 1) { return list[0]; } Error = ((list.Count == 0) ? ("no mod called '" + name + "'") : ("'" + name + "' matches several mods: " + string.Join(", ", from m in list.Take(8) select m.Name))); return null; } private void FindPatches(ModEntry entry, string patchesOn, ModRegistry registry, string harmonyId) { HashSet<MethodBase> hashSet = null; if (!string.IsNullOrWhiteSpace(patchesOn)) { hashSet = new HashSet<MethodBase>(ResolveMethods(patchesOn.Trim())); if (hashSet.Count == 0) { Error = "method '" + patchesOn + "' not found (use Type:Method)"; return; } } string monitor = harmonyId.Substring(0, harmonyId.LastIndexOf('.')); List<MethodBase> list; try { list = Harmony.GetAllPatchedMethods().ToList(); } catch (Exception ex) { Error = "could not list patches: " + ex.Message; return; } foreach (MethodBase item in list) { MethodBase original = item; if (hashSet == null || hashSet.Contains(original)) { Patches patchInfo; try { patchInfo = Harmony.GetPatchInfo(original); } catch { continue; } if (patchInfo != null) { Take(patchInfo.Prefixes, (HarmonyPatchType)1); Take(patchInfo.Postfixes, (HarmonyPatchType)2); Take(patchInfo.Transpilers, (HarmonyPatchType)3); Take(patchInfo.Finalizers, (HarmonyPatchType)4); Take(patchInfo.ILManipulators, (HarmonyPatchType)6); } } void Take(IEnumerable<Patch> enumerable, HarmonyPatchType type) { //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) foreach (Patch item2 in enumerable) { if (!(item2.PatchMethod == null) && !item2.owner.StartsWith(monitor, StringComparison.Ordinal) && registry.Resolve(item2.PatchMethod.DeclaringType?.Assembly, item2.owner) == entry) { _removed.Add(new Removed { Original = original, Patch = item2, Type = type }); } } } } } private void FindSkip(string spec, ModRegistry registry) { Assembly assembly = typeof(ZNet).Assembly; foreach (MethodInfo item in ResolveMethods(spec).OfType<MethodInfo>()) { Assembly assembly2 = item.DeclaringType?.Assembly; if (assembly2 == null || assembly2 == assembly || assembly2.GetName().Name.StartsWith("assembly_") || assembly2.GetName().Name.StartsWith("UnityEngine")) { Error = "only mod methods can be skipped, not the game's own"; return; } if (!item.IsAbstract && !item.ContainsGenericParameters && item.GetMethodBody() != null) { if (item.ReturnType == typeof(void)) { _skipped.Add(item); } else if (item.ReturnType == typeof(bool) && IsHarmonyPrefix(item)) { _skipped.Add(item); } } } if (_skipped.Count == 0 && Error == null) { Error = "'" + spec + "': no method that can be skipped safely (it must return nothing, or be a Harmony prefix)"; } } private string FindObjects(int id, string path, string prefab) { if (!string.IsNullOrWhiteSpace(prefab)) { string text = prefab.Trim(); ZNetScene instance = ZNetScene.instance; if ((Object)(object)instance == (Object)null) { Error = "not in a world"; return null; } if ((Object)(object)instance.GetPrefab(text) == (Object)null) { Error = "no prefab called '" + text + "' (use the names perf/objects lists)"; return null; } List<GameObject> list = GameContext.LoadedOfPrefab(StringExtensionMethods.GetStableHashCode(text)); if (list.Count == 0) { Error = "no copies of " + text + " are loaded here"; return null; } foreach (GameObject item in list) { string text2 = Refuse(item); if (text2 != null) { Error = text + ": " + text2; return null; } } _objects.AddRange(list); return $"prefab {text} ({list.Count} loaded copies switched off)"; } GameObject val = null; if (id != 0) { Object val2 = Resources.InstanceIDToObject(id); val = (GameObject)(object)((val2 is GameObject) ? val2 : null); if ((Object)(object)val == (Object)null) { Component val3 = (Component)(object)((val2 is Component) ? val2 : null); if (val3 != null && (Object)(object)val3 != (Object)null) { val = val3.gameObject; } } if ((Object)(object)val == (Object)null) { Error = $"no live object with instanceId {id}"; return null; } } else { val = FindPath(path.Trim().Trim(new char[1] { '/' }), out var error); if ((Object)(object)val == (Object)null) { Error = error; return null; } } string text3 = Refuse(val); if (text3 != null) { Error = text3; return null; } _objects.Add(val); return "object " + PathOf(val.transform); } private static string Refuse(GameObject go) { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer != (Object)null && ((Object)(object)go == (Object)(object)((Component)localPlayer).gameObject || ((Component)localPlayer).transform.IsChildOf(go.transform))) { return "that holds the player character"; } Component[] componentsInChildren = go.GetComponentsInChildren<Component>(true); foreach (Component val in componentsInChildren) { if (!((Object)(object)val == (Object)null)) { if (val is BaseUnityPlugin || ((object)val).GetType().Assembly == typeof(Plugin).Assembly || ((object)val).GetType().Assembly.GetName().Name.StartsWith("ValAgentBridge")) { return "that holds mods' plugins (or this monitor or the bridge), which would stop them"; } if (val is ZNet || val is ZNetScene || val is Game || val is ZoneSystem || val is EnvMan) { return "that is one of the game's core objects; switching it off stops the world"; } } } return null; } private static GameObject FindPath(string path, out string error) { //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) error = null; string[] parts = path.Split(new char[1] { '/' }); if (parts.Length == 0 || parts[0].Length == 0) { error = "empty objectPath"; return null; } List<GameObject> list = new List<GameObject>(); for (int i = 0; i < SceneManager.sceneCount; i++) { Scene sceneAt = SceneManager.GetSceneAt(i); if (((Scene)(ref sceneAt)).isLoaded) { list.AddRange(((Scene)(ref sceneAt)).GetRootGameObjects()); } } Scene val = (Scene)(((Object)(object)Plugin.Instance != (Object)null) ? ((Component)Plugin.Instance).gameObject.scene : default(Scene)); if (((Scene)(ref val)).IsValid() && ((Scene)(ref val)).isLoaded) { list.AddRange(((Scene)(ref val)).GetRootGameObjects()); } List<Transform> list2 = (from r in list where (Object)(object)r != (Object)null && ((Object)r).name == parts[0] select r.transform).ToList(); for (int num = 1; num < parts.Length; num++) { if (list2.Count <= 0) { break; } List<Transform> list3 = new List<Transform>(); foreach (Transform item in list2) { for (int num2 = 0; num2 < item.childCount; num2++) { if (((Object)item.GetChild(num2)).name == parts[num]) { list3.Add(item.GetChild(num2)); } } } list2 = list3; } if (list2.Count == 0) { error = "no object at '" + path + "' (paths as debug/scene_tree shows them)"; return null; } if (list2.Count > 1) { error = $"'{path}' matches {list2.Count} objects; use objectId (from debug/find_objects) to pick one, or prefab for all copies"; return null; } return ((Component)list2[0]).gameObject; } private static string PathOf(Transform t) { List<string> list = new List<string>(); Transform val = t; while ((Object)(object)val != (Object)null) { list.Add(((Object)val).name); val = val.parent; } list.Reverse(); return string.Join("/", list.ToArray()); } private static bool IsHarmonyPrefix(MethodInfo m) { try { return Harmony.GetAllPatchedMethods().Any((MethodBase o) => Harmony.GetPatchInfo(o)?.Prefixes.Any((Patch p) => p.PatchMethod == m) ?? false); } catch { return false; } } private void AddRound() { bool flag = Plan.Count / 2 % 2 == 0; Plan.Add(flag); Plan.Add(!flag); } private static List<MethodBase> ResolveMethods(string spec) { int num = spec.LastIndexOf(':'); if (num <= 0 || num == spec.Length - 1) { return new List<MethodBase>(); } Type type = null; try { type = AccessTools.TypeByName(spec.Substring(0, num)); } catch { } if (type == null) { return new List<MethodBase>(); } string name = spec.Substring(num + 1); return (from m in type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) where m.Name == name select m).Cast<MethodBase>().ToList(); } public void Begin(Plugin p) { _savedTarget = Application.targetFrameRate; _savedVsync = QualitySettings.vSyncCount; _uncapped = true; StartPhase(p, 0); } private void Uncap() { if (_uncapped) { QualitySettings.vSyncCount = 0; Application.targetFrameRate = -1; } } private void RestoreCap() { if (_uncapped) { _uncapped = false; QualitySettings.vSyncCount = _savedVsync; Application.targetFrameRate = _savedTarget; } } public void Frame(bool use) { if (--_sampleCountdown <= 0) { _sampleCountdown = 30; SampleConditions(); } if (CpuClock.Available) { ulong num = CpuClock.Read(); if (use && _prevCycles != 0L && num >= _prevCycles) { _cycles += num - _prevCycles; _cpuFrames++; } _prevCycles = num; } long totalMemory; try { totalMemory = GC.GetTotalMemory(forceFullCollection: false); } catch { return; } if (use && _prevHeap >= 0 && totalMemory >= _prevHeap) { _heapBytes += totalMemory - _prevHeap; _heapFrames++; } _prevHeap = totalMemory; } public void Tick(Plugin p) { Capture current = p.Current; if (Done || current == null) { return; } if (Script != null) { Script.Collect(); if (Script.Failed > 0 || Script.Error != null) { _log.LogWarning((object)("A/B test: the action script " + ((Script.Error != null) ? ("could not start: " + Script.Error) : ("failed: " + Script.LastFailure)) + ". Stopping the test.")); p.StopTest(); return; } if (Script.Running) { return; } if (current.MeasuredSeconds < (double)Seconds || Script.Runs == _runsAtTurnStart) { if (!p.WarmingUp) { Script.Start(); } return; } _turn.ScriptRuns = Script.Runs - _runsAtTurnStart; } else if (current.MeasuredSeconds < (double)Seconds) { return; } RecordPhase(p, current); if (Step + 1 == Plan.Count && Plan.Count / 2 < 6 && _requestedRounds >= 2) { string text = WhyAnotherRound(); if (text != null) { AddRound(); _log.LogInfo((object)$"A/B test: adding round {Plan.Count / 2} ({text})."); } } if (Step + 1 < Plan.Count) { StartPhase(p, Step + 1); } else { Finish(p); } } private void SampleConditions() { //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) try { EnvMan instance = EnvMan.instance; string text = (((Object)(object)instance != (Object)null) ? instance.GetCurrentEnvironment() : null)?.m_name; if (!string.IsNullOrEmpty(text) && (_turn.Weathers.Count == 0 || _turn.Weathers[_turn.Weathers.Count - 1] != text) && _turn.Weathers.Count < 6) { _turn.Weathers.Add(text); } } catch { } Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer != (Object)null) { Vector3 position = ((Component)localPlayer).transform.position; if (!_turn.HasPos) { _turn.HasPos = true; _turn.StartPos = position; } else { _turn.MovedM = Math.Max(_turn.MovedM, Vector3.Distance(_turn.StartPos, position)); } } int num = GameContext.LoadedObjects(); if (num >= 0) { _turn.ObjectsMin = ((_turn.ObjectsMin < 0) ? num : Math.Min(_turn.ObjectsMin, num)); _turn.ObjectsMax = Math.Max(_turn.ObjectsMax, num); } } private static string RoundProblem(Phase a, Phase b) { //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) if (a.Weathers.Concat(b.Weathers).Distinct().ToList() .Count > 1) { return "weather changed (" + a.WeatherText + " | " + b.WeatherText + ")"; } if (a.HasPos && b.HasPos) { float num = Math.Max(Math.Max(a.MovedM, b.MovedM), Vector3.Distance(a.StartPos, b.StartPos)); if (num > 10f) { return $"player moved {num:0} m"; } } int num2 = Math.Min(a.ObjectsMin, b.ObjectsMin); int num3 = Math.Max(a.ObjectsMax, b.ObjectsMax); if (num2 > 0 && (double)(num3 - num2) > 0.15 * (double)num3) { return $"loaded objects changed ({num2} to {num3})"; } return null; } private string WhyAnotherRound() { string name; Comparison comparison = Compare(MainMetric(out name)); if (comparison.LeftOut > 0 && comparison.Pairs < _requestedRounds) { return $"{comparison.LeftOut} round(s) left out because conditions changed"; } if (comparison.Pairs >= 2 && !comparison.Real && comparison.SameWay) { return "every round agrees but the sizes vary"; } return null; } private Func<Phase, double> MainMetric(out string name) { bool flag = Phases.All((Phase x) => !double.IsNaN(x.CpuMainMs)); name = (flag ? "main-thread CPU" : "frame time"); object obj; if (!flag) { obj = <>c.<>9__71_2; if (obj == null) { return <>c.<>9__71_2 = (Phase x) => x.FrameMs; } } else { obj = (Func<Phase, double>)((Phase x) => x.CpuMainMs); } return (Func<Phase, double>)obj; } private void StartPhase(Plugin p, int step) { Step = step; bool flag = Plan[step]; if (flag) { PutBack(); } else { TakeOff(); } Uncap(); _prevHeap = -1L; _heapBytes = 0L; _heapFrames = 0; _prevCycles = 0uL; _cycles = 0uL; _cpuFrames = 0; _turn = new Phase(); _sampleCountdown = 0; _runsAtTurnStart = Script?.Runs ?? 0; p.StartCapture(CaptureMode.Baseline, string.Format("{0} {1} {2}", Label, flag ? "normal" : "off", step + 1)); if (p.Current != null) { p.Current.AbTurn = true; } } private void RecordPhase(Plugin p, Capture c) { Report.Summary summary = Report.Summarize(c.Stats); double num = ((_cpuFrames > 0) ? (CpuClock.ToMs(_cycles) / (double)_cpuFrames) : double.NaN); if (double.IsNaN(num) && p.Counters != null && p.Counters.FrameTimingSeen && p.Counters.TotTimingSamples > 0) { num = p.Counters.TotCpuMain / (double)p.Counters.TotTimingSamples; } double num2 = Math.Max(1.0, c.MeasuredSeconds); SampleConditions(); Phase turn = _turn; turn.On = Plan[Step]; turn.Capture = c.Number; turn.FrameMs = ((summary.Fps > 0.0) ? (1000.0 / summary.Fps) : double.NaN); turn.CpuMainMs = num; turn.Fps1Low = summary.Fps1Low; turn.GcPerMin = summary.GcPerMin; turn.SlowPerMin = (double)c.Stats.SpikeCount / num2 * 60.0; turn.Seconds = num2; turn.GarbageKbPerFrame = ((_heapFrames == 0) ? double.NaN : ((double)_heapBytes / 1024.0 / (double)_heapFrames)); Phases.Add(turn); _turn = new Phase(); } private void TakeOff() { //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Expected O, but got Unknown if (_off) { return; } _off = true; try { File.WriteAllText(_crumbPath, "A/B test had these taken off (only for that session):\n" + string.Join("\n", Describe()) + "\n"); } catch { } foreach (Removed item in _removed) { try { new Harmony(item.Patch.owner).Unpatch(item.Original, item.Patch.PatchMethod); } catch (Exception ex) { _log.LogWarning((object)("A/B test: could not take off " + Instrumenter.Describe(item.Patch.PatchMethod) + ": " + ex.Message)); } } foreach (MethodInfo item2 in _skipped) { try { _skipHarmony.Patch((MethodBase)item2, new HarmonyMethod((item2.ReturnType == typeof(bool)) ? SkipBool : SkipVoid) { priority = 800 }, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } catch (Exception ex2) { _log.LogWarning((object)("A/B test: could not skip " + Instrumenter.Describe(item2) + ": " + ex2.Message)); } } foreach (GameObject @object in _objects) { if (!((Object)(object)@object == (Object)null) && @object.activeSelf) { try { @object.SetActive(false); _switchedOff.Add(@object); } catch (Exception ex3) { _log.LogWarning((object)("A/B test: could not switch off " + ((Object)@object).name + ": " + ex3.Message)); } } } } public void PutBack() { //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Expected O, but got Unknown //IL_015b: Unknown result type (might be due to invalid IL or missing references) //IL_0162: Expected O, but got Unknown //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_0169: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_016e: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Expected I4, but got Unknown if (!_off) { return; } _off = false; int num = 0; foreach (MethodInfo item in _skipped) { try { _skipHarmony.Unpatch((MethodBase)item, (HarmonyPatchType)0, _skipHarmony.Id); } catch (Exception ex) { num++; _log.LogError((object)("A/B test: could not un-skip " + Instrumenter.Describe(item) + ": " + ex.Message)); } } foreach (Removed item2 in _removed) { Patch p = item2.Patch; try { Patches patchInfo = Harmony.GetPatchInfo(item2.Original); if (patchInfo != null && All(patchInfo).Any((Patch x) => x.PatchMethod == p.PatchMethod)) { continue; } } catch { } HarmonyMethod val = new HarmonyMethod(p.PatchMethod) { priority = p.priority, before = p.before, after = p.after, debug = p.debug }; try { Harmony val2 = new Harmony(p.owner); HarmonyPatchType type = item2.Type; switch (type - 1) { case 0: val2.Patch(item2.Original, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); break; case 1: val2.Patch(item2.Original, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); break; case 2: val2.Patch(item2.Original, (HarmonyMethod)null, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null); break; case 3: val2.Patch(item2.Original, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, val, (HarmonyMethod)null); break; case 5: val2.Patch(item2.Original, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, val); break; case 4: break; } } catch (Exception ex2) { num++; _log.LogError((object)("A/B test: could not put back " + Instrumenter.Describe(p.PatchMethod) + " on " + Instrumenter.Describe(item2.Original) + ": " + ex2.Message)); } } foreach (GameObject item3 in _switchedOff) { if (!((Object)(object)item3 == (Object)null)) { try { item3.SetActive(true); } catch (Exception ex3) { num++; _log.LogError((object)("A/B test: could not switch " + ((Object)item3).name + " back on: " + ex3.Message)); } } } _switchedOff.Clear(); if (num > 0) { _log.LogError((object)$"A/B test: {num} patch(es) or object(s) could not be put back. Restart the game before playing on."); return; } try { File.Delete(_crumbPath); } catch { } } private static IEnumerable<Patch> All(Patches i) { return i.Prefixes.Concat(i.Postfixes).Concat(i.Transpilers).Concat(i.Finalizers) .Concat(i.ILManipulators); } public void Abort() { PutBack(); RestoreCap(); Done = true; if (Phases.Count > 0) { Judge(); } } private void Finish(Plugin p) { PutBack(); RestoreCap(); Done = true; Judge(); p.AbFinished(this); } private void Judge() { VerdictLines.Clear(); List<Phase> list = Phases.Where((Phase x) => x.On).ToList(); List<Phase> list2 = Phases.Where((Phase x) => !x.On).ToList(); if (list.Count == 0 || list2.Count == 0) { Verdict = "not enough turns to compare"; return; } string name; Func<Phase, double> func = MainMetric(out name); Comparison comparison = Compare(func); RoundsUsed = comparison.Pairs; RoundsLeftOut = comparison.LeftOut; if (comparison.Pairs == 0 && comparison.LeftOut > 0) { Verdict = "NO RESULT: conditions changed in every round (" + string.Join("; ", comparison.Problems) + "). Stand still in clear, pinned weather and run it again"; VerdictLines.Add(Verdict); return; } double num = list.Average(func); string text = ((num > 0.0) ? $" ({100.0 * Math.Abs(comparison.Diff) / num:0.0}%)" : ""); string text2 = "each normal turn vs the off turn next to it: " + string.Join(", ", comparison.PairDiffs.Select((double d) => Signed(d))) + " ms"; if (comparison.Pairs < 2) { Verdict = name + " " + Signed(comparison.Diff) + " ms per frame lower with it off" + text + ", but only one round: can't tell real from normal variation"; } else if (comparison.Real && Math.Abs(comparison.Diff) >= 0.05) { Verdict = ((comparison.Diff > 0.0) ? $"REAL COST: taking it off saved {comparison.Diff:0.000} ms of {name} per frame{text}; faster in every round ({text2})" : $"REAL: the game used {0.0 - comparison.Diff:0.000} ms more {name} per frame with it off{text}; slower in every round ({text2})"); } else if (comparison.SameWay && comparison.Pairs >= 3 && Math.Abs(comparison.Diff) >= 0.05) { Verdict = "LEANS " + ((comparison.Diff > 0.0) ? "COST" : "SLOWER WITHOUT IT") + ": every round pointed the same way (" + Signed(comparison.Diff) + " ms per frame on average" + text + "), but the rounds vary too much in size to be sure; run more rounds (" + text2 + ")"; } else { Verdict = "NO CLEAR DIFFERENCE in " + name + ": " + Signed(comparison.Diff) + " ms per frame on average, but the rounds disagree or the difference is smaller than their spread (" + text2 + ")"; } VerdictLines.Add(Verdict); if (comparison.LeftOut > 0) { VerdictLines.Add(string.Format("Left out {0} round(s) because conditions changed: {1}", comparison.LeftOut, string.Join("; ", comparison.Problems))); } if (Phases.All((Phase x) => !double.IsNaN(x.GarbageKbPerFrame))) { Comparison comparison2 = Compare((Phase x) => x.GarbageKbPerFrame); VerdictLines.Add($"Garbage per frame (whole game): {list.Average((Phase x) => x.GarbageKbPerFrame):0.0} KB normal, {list2.Average((Phase x) => x.GarbageKbPerFrame):0.0} KB off" + ((comparison2.Pairs < 2) ? "" : (comparison2.Real ? $" (real: {comparison2.Diff:0.0} KB less per frame with it off in every round)" : " (rounds disagree: within normal variation)"))); } VerdictLines.Add($"Garbage collections per minute: {list.Average((Phase x) => x.GcPerMin):0.0} normal, {list2.Average((Phase x) => x.GcPerMin):0.0} off" + ((Seconds < 45f) ? " (short turns hold only a few collections: rough)" : "")); VerdictLines.Add($"1% low FPS: {list.Average((Phase x) => x.Fps1Low):0.0} normal, {list2.Average((Phase x) => x.Fps1Low):0.0} off; slow frames per minute: {list.Average((Phase x) => x.SlowPerMin):0.0} normal, {list2.Average((Phase x) => x.SlowPerMin):0.0} off"); } private Comparison Compare(Func<Phase, double> f) { Comparison comparison = new Comparison(); for (int i = 0; i + 1 < Phases.Count; i += 2) { Phase phase = Phases[i]; Phase phase2 = Phases[i + 1]; if (phase.On != phase2.On) { string text = RoundProblem(phase, phase2); if (text != null) { comparison.LeftOut++; comparison.Problems.Add($"round {i / 2 + 1}: {text}"); } else { comparison.PairDiffs.Add(phase.On ? (f(phase) - f(phase2)) : (f(phase2) - f(phase))); } } } comparison.Pairs = comparison.PairDiffs.Count; if (comparison.Pairs == 0) { return comparison; } comparison.Diff = comparison.PairDiffs.Average(); comparison.Spread = comparison.PairDiffs.Max() - comparison.PairDiffs.Min(); comparison.SameWay = comparison.PairDiffs.All((double d) => d > 0.0) || comparison.PairDiffs.All((double d) => d < 0.0); comparison.Real = comparison.Pairs >= 2 && comparison.SameWay && Math.Abs(comparison.Diff) > comparison.Spread; return comparison; } private static string Signed(double v) { return ((v >= 0.0) ? "+" : "") + v.ToString("0.000"); } public string CsvLine(string session, ModRegistry registry) { StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder2 = stringBuilder.Append(Csv.Q(session)).Append(',').Append(DateTime.Now.ToString("HH:mm:ss", Csv.Inv)) .Append(',') .Append(Csv.Q(What)) .Append(','); float seconds = Seconds; stringBuilder2.Append(seconds.ToString("0", Csv.Inv)).Append(',').Append(Phases.Count) .Append(','); Func<bool, Func<Phase, double>, string> func = delegate(bool on, Func<Phase, double> f) { List<Phase> list = Phases.Where((Phase x) => x.On == on).ToList(); return (list.Count != 0) ? Csv.F(list.Average(f), "0.000") : ""; }; stringBuilder.Append(func(arg1: true, (Phase x) => x.CpuMainMs)).Append(',').Append(func(arg1: false, (Phase x) => x.CpuMainMs)) .Append(',') .Append(func(arg1: true, (Phase x) => x.GarbageKbPerFrame)) .Append(',') .Append(func(arg1: false, (Phase x) => x.GarbageKbPerFrame)) .Append(',') .Append(func(arg1: true, (Phase x) => x.FrameMs)) .Append(',') .Append(func(arg1: false, (Phase x) => x.FrameMs)) .Append(',') .Append(func(arg1: true, (Phase x) => x.GcPerMin)) .Append(',') .Append(func(arg1: false, (Phase x) => x.GcPerMin)) .Append(',') .Append(Csv.Q(Verdict)) .Append(',') .Append(RoundsUsed) .Append(',') .Append(RoundsLeftOut) .Append(',') .Append(Csv.Q(RunStamp.GameVersion)) .Append(',') .Append(Csv.Q(RunStamp.ModsFingerprint(registry))) .Append('\n'); return stringBuilder.ToString(); } public static void CheckLeftover(string rootFolder, ManualLogSource log) { string path = Path.Combine(rootFolder, "ab-test-in-progress.txt"); try { if (File.Exists(path)) { log.LogWarning((object)("The game closed during an A/B test last time. Nothing needs repairing (patches are only taken off for that session); if it crashed, the cause may be what was taken off:\n" + File.ReadAllText(path))); File.Delete(path); } } catch { } } } internal static class Events { public struct Ev { public double SessionSeconds; public float At; public string Kind; public string Detail; } private static readonly List<Ev> _all = new List<Ev>(); private const int Max = 5000; private static bool _headerWritten; private static readonly ConcurrentQueue<string> _bridgeNames = new ConcurrentQueue<string>(); [ThreadStatic] private static int _callDepth; private static Func<bool> _queueEmpty; private static bool _bridgeFrame; private static FieldRef<int> _lastWorkFrame; private static string _lastBridge = ""; private static bool _inWorld; private static bool _teleporting; private static float _nextSeasonPoll; private static ConfigEntryBase _season; private static FieldInfo _seasonNow; private static bool _seasonLooked; private static string _seasonValue; public static int Count => _all.Count; public static void Mark(string kind, string detail) { Plugin instance = Plugin.Instance; Ev item = new Ev { SessionSeconds = (((Object)(object)instance != (Object)null) ? instance.SessionSeconds : 0.0), At = Time.realtimeSinceStartup, Kind = kind, Detail = (detail ?? "") }; if (_all.Count >= 5000) { _all.RemoveRange(0, 1000); } _all.Add(item); if (instance?.Writer != null && instance.SessionFolder != null) { string path = Path.Combine(instance.SessionFolder, "events.csv"); BackgroundWriter writer = instance.Writer; string[] obj = new string[11] { _headerWritten ? "" : "time,session_s,kind,detail,recording\n", DateTime.Now.ToString("HH:mm:ss", Csv.Inv), ",", Csv.F(item.SessionSeconds, "0.0"), ",", kind, ",", Csv.Q(item.Detail), ",", null, null }; object obj2; if (instance.Current == null) { obj2 = ""; } else { int number = instance.Current.Number; obj2 = number.ToString(Csv.Inv); } obj[9] = (string)obj2; obj[10] = "\n"; writer.Append(path, string.Concat(obj)); _headerWritten = true; } } public static string Label(Ev e) { if (e.Detail.Length <= 0) { return e.Kind; } return e.Kind + " " + e.Detail; } public static string Since(ref int from) { if (from > _all.Count) { from = 0; } if (from == _all.Count) { return ""; } string result = string.Join("; ", _all.Skip(from).Take(10).Select(Label) .ToArray()) + ((_all.Count - from > 10) ? $"; +{_all.Count - from - 10} more" : ""); from = _all.Count; return result; } public static string Recent(float now, float seconds, out string kind) { kind = null; if (_all.Count == 0) { return null; } Ev e = _all[_all.Count - 1]; if (now - e.At > seconds) { return null; } kind = e.Kind; return "after " + Label(e) + " (" + (now - e.At).ToString("0.0", Csv.Inv) + " s)"; } public static List<Ev> Last(int n) { return _all.Skip(Math.Max(0, _all.Count - n)).ToList(); } public static bool WatchBridge(Harmony harmony, ManualLogSource log) { //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Unknown result type (might be due to invalid IL or missing references) //IL_0172: Expected O, but got Unknown //IL_0172: Expected O, but got Unknown //IL_0213: Unknown result type (might be due to invalid IL or missing references) //IL_022a: Unknown result type (might be due to invalid IL or missing references) //IL_0235: Expected O, but got Unknown //IL_0235: Expected O, but got Unknown //IL_0249: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Expected O, but got Unknown Assembly assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((Assembly a) => a.GetName().Name == "ValAgentBridge"); if (assembly == null) { return false; } Type type = assembly.GetType("ValAgentBridge.MainThreadDispatcher", throwOnError: false); Type type2 = ((type == null) ? null : AppDomain.CurrentDomain.GetAssemblies().Select(delegate(Assembly a) { try { return a.GetType("Lib.GAB.Tools.ToolRegistry", throwOnError: false); } catch { return (Type)null; } }).FirstOrDefault((Type t) => t != null)); if (type2 == null || type == null) { return false; } try { MethodInfo methodInfo = AccessTools.Method(type2, "CallToolAsync", new Type[2] { typeof(string), typeof(object) }, (Type[])null); FieldInfo fieldInfo = AccessTools.Field(type, "LastWorkFrame"); if (methodInfo != null && fieldInfo != null && fieldInfo.IsStatic && fieldInfo.FieldType == typeof(int)) { _lastWorkFrame = AccessTools.StaticFieldRefAccess<int>(fieldInfo); harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(Events), "CallPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(Events), "CallFinalizer", (Type[])null), (HarmonyMethod)null); return true; } MethodInfo methodInfo2 = AccessTools.Method(type, "Update", (Type[])null, (Type[])null); FieldInfo fieldInfo2 = AccessTools.Field(type, "ExecutionQueue"); ConcurrentQueue<Action> queue = ((fieldInfo2 != null && fieldInfo2.IsStatic) ? (fieldInfo2.GetValue(null) as ConcurrentQueue<Action>) : null); if (methodInfo == null || methodInfo2 == null || queue == null) { log.LogInfo((object)"ValAgentBridge is not as expected: its commands are not labelled or left out of captures."); return true; } _queueEmpty = () => queue.IsEmpty; harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(Events), "CallPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(Events), "CallFinalizer", (Type[])null), (HarmonyMethod)null); harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(Events), "DispatchPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } catch (Exception ex) { log.LogInfo((object)("ValAgentBridge commands are not labelled: " + ex.Message)); } return true; } private static void CallPrefix(string name) { if (_callDepth++ == 0 && name != null) { _bridgeNames.Enqueue(name); } } private static void CallFinalizer() { if (_callDepth > 0) { _callDepth--; } } private static void DispatchPrefix() { try { if (_queueEmpty != null && !_queueEmpty()) { _bridgeFrame = true; } } catch { _queueEmpty = null; } } public static bool TakeBridgeFrame(out string name) { string result; while (_bridgeNames.TryDequeue(out result)) { _lastBridge = result; Mark("bridge", result); } name = _lastBridge; if (_lastWorkFrame != null) { try { return _lastWorkFrame.Invoke() == Time.frameCount; } catch { _lastWorkFrame = null; return false; } } bool bridgeFrame = _bridgeFrame; _bridgeFrame = false; return bridgeFrame; } public static void Poll() { Player localPlayer = Player.m_localPlayer; bool flag = (Object)(object)localPlayer != (Object)null && (Object)(object)ZNetScene.instance != (Object)null; if (flag != _inWorld) { _inWorld = flag; Mark(flag ? "login" : "logout", flag ? "entered the world" : "left the world (logout or death)"); if (flag) { FirstOpens.OnLogin(); } } bool flag2 = false; try { flag2 = flag && ((Character)localPlayer).IsTeleporting(); } catch { } if (flag2 && !_teleporting) { Mark("teleport", "teleport or portal"); } _teleporting = flag2; float realtimeSinceStartup = Time.realtimeSinceStartup; if (realtimeSinceStartup < _nextSeasonPoll) { return; } _nextSeasonPoll = realtimeSinceStartup + 1f; if (!_seasonLooked && flag) { _seasonLooked = true; try { if (Chainloader.PluginInfos.TryGetValue("RustyMods.Seasonality", out var value) && (Object)(object)value.Instance != (Object)null) { _seasonNow = ((object)value.Instance).GetType().Assembly.GetType("Seasonality.SeasonTime", throwOnError: false)?.GetField("m_currentSeason", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); _season = ((IEnumerable<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)value.Instance.Config).FirstOrDefault((KeyValuePair<ConfigDefinition, ConfigEntryBase> kv) => kv.Key.Section == "1 - Settings" && kv.Key.Key == "Season").Value; } } catch { } } if (_season != null || !(_seasonNow == null)) { string text; try { text = ((_seasonNow != null) ? _seasonNow.GetValue(null) : _season.BoxedValue)?.ToString(); } catch { _season = null; _seasonNow = null; return; } if (_seasonValue != null && text != _seasonValue) { Mark("season", "change to " + text + " (Seasonality)"); } _seasonValue = text; } } } internal sealed class Alarms { private readonly Plugin _p; private float _nextSecond; private long _lastLogTicks; public double LastSecondLogMs; public const int LinkLimit = 65535; public int Tiles = -1; public int Links = -1; public int LinksQueued = -1; public int TilesQueued = -1; private float _nextPath; private bool _pathBroken; private bool _pathHeader; private float _lastPathWarn = -1E+09f; private static FieldInfo _tilesF; private static FieldInfo _linkQueueF; private static FieldInfo _tileQueueF; private static FieldInfo _links1F; private static FieldInfo _links2F; private float _lastGoWarn = -1E+09f; private float _lastMatWarn = -1E+09f; private float _lastMatWait = -1E+09f; private float _lastLiveWarn = -1E+09f; private float _lastLocNote = -1E+09f; private double _liveWarnedAt; public double LiveAfterGcMb = double.NaN; private int _gcWindow; private long _minUsed; private int _goWarnedAt; private int _matWarnedAt; public Alarms(Plugin p) { _p = p; _lastLogTicks = LogWatch.MainThreadTicks; } public void Tick() { Events.Poll(); float realtimeSinceStartup = Time.realtimeSinceStartup; if (!(realtimeSinceStartup < _nextSecond)) { _nextSecond = realtimeSinceStartup + 1f; long mainThreadTicks = LogWatch.MainThreadTicks; LastSecondLogMs = LogWatch.TicksToMs(mainThreadTicks - _lastLogTicks); _lastLogTicks = mainThreadTicks; CheckFloods(); if (realtimeSinceStartup >= _nextPath) { SamplePathfinding(realtimeSinceStartup); } } } private void CheckFloods() { LogWatch instance = LogWatch.Instance; if (instance == null) { return; } foreach (LogWatch.Flood item in instance.TakeNewFloods()) { double now = LogWatch.Now; if (!(now - item.LastWarned < 300.0)) { item.LastWarned = now; string text = LogWatch.FloodOwner(item, _p.Registry); string text2 = ((item.FloodSeconds > 1) ? $" (flooding again: {item.Total:N0} lines so far)" : ""); string text3 = (LogWatch.Timed ? (" Writing the log took " + LastSecondLogMs.ToString("0", Csv.Inv) + " ms of game time in the last second.") : ""); _p.Log.LogWarning((object)($"Log flood: {text} wrote the same {item.Level} {item.PeakPerSecond} times in one second{text2}: \"{Short(item.Message, 140)}\".{text3} " + "A message repeated this often costs frame time and fills the log. Details: perf/log_errors.")); if (item.Message.IndexOf("NavMeshLink", StringComparison.Ordinal) >= 0) { _nextPath = 0f; } if ((Object)(object)Player.m_localPlayer != (Object)null) { _p.ShowToast($"Log flood: {text} repeats \"{Short(item.Message, 60)}\" {item.PeakPerSecond}x per second.", 12f); } } } } internal static string Short(string s, int n) { if (s.Length > n) { return s.Substring(0, n) + "..."; } return s; } private void SamplePathfinding(float now) { _nextPath = now + 10f; Pathfinding instance = Pathfinding.instance; if (_pathBroken || (Object)(object)instance == (Object)null || (Object)(object)Player.m_localPlayer == (Object)null) { return; } try { if (_tilesF == null) { _tilesF = AccessTools.Field(typeof(Pathfinding), "m_tiles"); _linkQueueF = AccessTools.Field(typeof(Pathfinding), "m_linkRemoveQueue"); _tileQueueF = AccessTools.Field(typeof(Pathfinding), "m_tileRemoveQueue"); Type type = AccessTools.Inner(typeof(Pathfinding), "NavMeshTile"); _links1F = ((type == null) ? null : AccessTools.Field(type, "m_links1")); _links2F = ((type == null) ? null : AccessTools.Field(type, "m_links2")); if (_tilesF == null || _linkQueueF == null || _links1F == null || _links2F == null) { _pathBroken = true; _p.Log.LogInfo((object)"The game's pathfinding code is not as expected: pathfinding links are not counted."); return; } } IDictionary dictionary = (IDictionary)_tilesF.GetValue(instance); int num = 0; foreach (object value in dictionary.Values) { if (value != null) { num += ((ICollection)_links1F.GetValue(value))?.Count ?? 0; num += ((ICollection)_links2F.GetValue(value))?.Count ?? 0; } } Tiles = dictionary.Count; Links = num; LinksQueued = ((ICollection)_linkQueueF.GetValue(instance))?.Count ?? 0; TilesQueued = ((_tileQueueF == null) ? (-1) : (((ICollection)_tileQueueF.GetValue(instance))?.Count ?? 0)); } catch (Exception ex) { _pathBroken = true; _p.Log.LogInfo((object)("Pathfinding links are not counted: " + ex.Message)); return; } _p.MarkHeavy(); if (_p.Writer != null) { _p.Writer.Append(Path.Combine(_p.SessionFolder, "pathfinding.csv"), (_pathHeader ? "" : "time,session_s,tiles,links,links_waiting_removal,tiles_waiting_removal,links_in_use_pct_of_limit,where\n") + string.Format("{0},{1},{2},{3},{4},{5},{6},{7}\n", DateTime.Now.ToString("HH:mm:ss", Csv.Inv), Csv.F(_p.SessionSeconds, "0"), Tiles, Links, LinksQueued, TilesQueued, Csv.F(100.0 * (double)(Links + LinksQueued) / 65535.0, "0.0"), Csv.Q(_p.Context.Short))); _pathHeader = true; } int num2 = Links + LinksQueued; if ((double)num2 >= 49151.25 && now - _lastPathWarn > 300f) { _lastPathWarn = now; _p.Log.LogWarning((object)($"Pathfinding links: {num2:N0} in use ({Links:N0} in {Tiles:N0} tiles, {LinksQueued:N0} waiting to be removed), " + $"{100.0 * (double)num2 / 65535.0:0}% of Unity's limit of about {65535:N0}. At the limit the game logs \"Failed to allocate NavMeshLink\" " + "every frame and creatures stop finding paths. Usually caused by many navigation tiles staying loaded (sailing, big areas built up).")); _p.ShowToast($"Pathfinding links at {100.0 * (double)num2 / 65535.0:0}% of Unity's limit ({num2:N0}).", 12f); } } public void FrameMemory(bool gc) { if (gc) { _gcWindow = 60; _minUsed = long.MaxValue; } if (_gcWindow <= 0) { return; } try { long monoUsedSizeLong = Profiler.GetMonoUsedSizeLong(); if (monoUsedSizeLong > 0 && monoUsedSizeLong < _minUsed) { _minUsed = monoUsedSizeLong; } } catch { _gcWindow = 0; return; } if (--_gcWindow == 0 && _minUsed != long.MaxValue) { LiveAfterGcMb = (double)_minUsed / 1048576.0; } } public void CheckLeak(MemoryTracker.Sample s, List<MemoryTracker.Sample> all) { if (!s.InWorld || s.Instances <= 0) { return; } MemoryTracker.Sample refSample = all.FirstOrDefault((MemoryTracker.Sample x) => x != s && x.InWorld && x.Instances > 0 && (double)Math.Abs(x.Instances - s.Instances) <= 0.15 * (double)s.Instances && x.GameObjects > 0 && SameSpot(x, s)); if (refSample == null) { return; } float realtimeSinceStartup = Time.realtimeSinceStartup; string text = ((s.SessionSeconds - refSample.SessionSeconds) / 60.0).ToString("0", Csv.Inv); bool flag = s.LocationObjects >= 0 && refSample.LocationObjects >= 0; int num = (flag ? (s.LocationObjects - refSample.LocationObjects) : 0); int num2 = refSample.GameObjects - (flag ? refSample.LocationObjects : 0); int num3 = s.GameObjects - (flag ? s.LocationObjects : 0); int num4 = num3 - num2; if (num4 > 20000 && (double)num4 > 0.25 * (double)num2 && (realtimeSinceStartup - _lastGoWarn > 1800f || (double)num3 > (double)_goWarnedAt * 1.25)) { _lastGoWarn = realtimeSinceStartup; _goWarnedAt = num3; string text2 = (flag ? $" Not counting game objects in locations ({refSample.LocationObjects:N0} -> {s.LocationObjects:N0})." : ""); Warn($"Game objects: {num2:N0} -> {num3:N0} in {text} min, while loaded world objects stayed about the same ({refSample.Instances:N0} -> {s.Instances:N0}).{text2}", $"Hidden game objects piling up: {num2:N0} -> {num3:N0}."); } else if (flag && s.GameObjects - refSample.GameObjects > 20000 && (double)(s.GameObjects - refSample.GameObjects) > 0.25 * (double)refSample.GameObjects && realtimeSinceStartup - _lastLocNote > 1800f) { _lastLocNote = realtimeSinceStartup; _p.Log.LogInfo((object)($"Game objects: {refSample.GameObjects:N0} -> {s.GameObjects:N0} in {text} min. Not a leak: {num:N0} of them are in locations " + "loaded while exploring (the game loads a location when you first come near one, and Jotunn keeps a copy of modded ones).")); } int num5 = s.Materials - refSample.Materials; bool flag2 = num > 20000; if (num5 > 1000 && (double)num5 > 0.3 * (double)refSample.Materials && flag2 && realtimeSinceStartup - _lastMatWarn > 1800f) { _lastMatWarn = realtimeSinceStartup; _p.Log.LogInfo((object)($"Materials: {refSample.Materials:N0} -> {s.Materials:N0} in {text} min while exploring ({num:N0} more game objects in locations): " + "new locations bring their own materials. Not counted as a leak.")); } else if (num5 > 1000 && (double)num5 > 0.3 * (double)refSample.Materials && !AssetCleanup.DoneAtSession.Any((double t) => t > refSample.SessionSeconds && t < s.SessionSeconds)) { if (realtimeSinceStartup - _lastMatWait > 1800f) { _lastMatWait = realtimeSinceStartup; _p.Log.LogInfo((object)($"Materials: {refSample.Materials:N0} -> {s.Materials:N0} in {text} min. Not called a leak yet: the game's asset clean-up " + "(every 20-60 min, after a respawn, sleep or a quiet moment) frees materials nothing uses any more. Checked again after the next one.")); } } else if (num5 > 1000 && (double)num5 > 0.3 * (double)refSample.Materials && (realtimeSinceStartup - _lastMatWarn > 1800f || (double)s.Materials > (double)_matWarnedAt * 1.25)) { _lastMatWarn = realtimeSinceStartup; _matWarnedAt = s.Materials; Warn($"Materials: {refSample.Materials:N0} -> {s.Materials:N0} in {text} min, while loaded world objects stayed about the same ({refSample.Instances:N0} -> {s.Instances:N0}).", $"Materials piling up: {refSample.Materials:N0} -> {s.Materials:N0}."); } MemoryTracker.Sample sample = all.FirstOrDefault((MemoryTracker.Sample x) => x != s && x.InWorld && x.Instances > 0 && (double)Math.Abs(x.Instances - s.Instances) <= 0.15 * (double)s.Instances && !double.IsNaN(x.LiveAfterGcMb) && x.WorldSeconds >= 30f && SameSpot(x, s)); if (sample != null && !double.IsNaN(s.LiveAfterGcMb) && s.WorldSeconds >= 30f) { double num6 = s.LiveAfterGcMb - sample.LiveAfterGcMb; if (num6 > 500.0 && num6 > 0.4 * sample.LiveAfterGcMb && (realtimeSinceStartup - _lastLiveWarn > 1800f || s.LiveAfterGcMb > _liveWarnedAt * 1.2)) { _lastLiveWarn = realtimeSinceStartup; _liveWarnedAt = s.LiveAfterGcMb; string text3 = ((s.SessionSeconds - sample.SessionSeconds) / 60.0).ToString("0", Csv.Inv); Warn($"Mod and game memory (lowest point after garbage collection): {sample.LiveAfterGcMb:0} -> {s.LiveAfterGcMb:0} MB in {text3} min, while loaded world objects stayed about the same ({sample.Instances:N0} -> {s.Instances:N0}). More live memory also makes every garbage-collection stutter longer.", $"Memory piling up: {sample.LiveAfterGcMb:0} -> {s.LiveAfterGcMb:0} MB."); } } } private static bool SameSpot(MemoryTracker.Sample a, MemoryTracker.Sample b) { if (float.IsNaN(a.X) || float.IsNaN(b.X)) { if (float.IsNaN(a.X)) { return float.IsNaN(b.X); } return false; } float num = a.X - b.X; float num2 = a.Z - b.Z; return num * num + num2 * num2 <= 10000f; } private void Warn(string what, string toast) { string[] array = (from e in Events.Last(200) where e.Kind != "bridge" group e by e.Kind into g select $"{g.Count()} {g.Key}").ToArray(); _p.Log.LogWarning((object)("Possible leak: " + what + " Something keeps creating them without removing them" + ((array.Length != 0) ? (" (events so far this session: " + string.Join(", ", array) + ")") : "") + ". F11 -> Memory census (or perf/memory_census) lists them by name. Trend: memory.csv.")); _p.ShowToast("Possible leak: " + toast + " Run a memory census (F11) to see what they are.", 15f); } } internal static class AllocCheck { public sealed class Result { public string Method = ""; public string Instance = ""; public string Error; public int Calls; public int GcRuns; public double BytesPerCall; public double MicrosPerCall; } private delegate void Loop(object target, object[] args, int count); public static Result Run(string typeName, string methodName, int calls, string timeArg) { Result result = new Result(); try { Type type = AccessTools.TypeByName(typeName); if (type == null) { result.Error = "type " + typeName + " not found"; return result; } List<MethodInfo> list = (from m in AccessTools.GetDeclaredMethods(type) where m.Name == methodName && !m.IsAbstract && !m.ContainsGenericParameters select m).ToList(); if (list.Count == 0) { result.Error = typeName + "." + methodName + " not found"; return result; } if (list.Count > 1) { result.Error = $"{methodName} has {list.Count} overloads; not supported"; return result; } MethodInfo methodInfo = list[0]; result.Method = type.Name + "." + methodInfo.Name + "(" + string.Join(", ", from p in methodInfo.GetParameters() select p.ParameterType.Name) + ")"; object obj = null; if (!methodInfo.IsStatic) { obj = FindInstance(type); if (obj == null) { result.Error = "no live " + type.Name + " found"; return result; } result.Instance = Describe(obj); } ParameterInfo[] parameters = methodInfo.GetParameters(); object[] array = new object[parameters.Length]; for (int num = 0; num < parameters.Length; num++) { if (parameters[num].ParameterType.IsByRef && !parameters[num].IsOut) { result.Error = "ref parameter " + parameters[num].Name + " not supported"; return result; } if (!Fill(parameters[num].ParameterType.IsByRef ? parameters[num].ParameterType.GetElementType() : parameters[num].ParameterType, timeArg, out array[num])) { result.Error = "can't fill parameter " + parameters[num].Name + " (" + parameters[num].ParameterType.Name + ")"; return result; } object obj2 = array[num]; Object val = (Object)((obj2 is Object) ? obj2 : null); if (val != null && num == 0 && methodInfo.IsStatic) { result.Instance = Describe(val); } } Loop loop = BuildLoop(methodInfo); loop(obj, array, 20); calls = Mathf.Clamp(calls, 10, 1000000); int num2 = GC.CollectionCount(0); long totalMemory = GC.GetTotalMemory(forceFullCollection: false); Stopwatch stopwatch = Stopwatch.StartNew(); loop(obj, array, calls); stopwatch.Stop(); long totalMemory2 = GC.GetTotalMemory(forceFullCollection: false); result.GcRuns = GC.CollectionCount(0) - num2; result.Calls = calls; result.BytesPerCall = ((result.GcRuns > 0) ? double.NaN : ((double)(totalMemory2 - totalMemory) / (double)calls)); result.MicrosPerCall = stopwatch.Elapsed.TotalMilliseconds * 1000.0 / (double)calls; if (result.GcRuns > 0) { result.Error = "a garbage collection ran during the check; run it again"; } } catch (Exception ex) { result.Error = (ex.InnerException ?? ex).GetType().Name + ": " + (ex.InnerException ?? ex).Message; } return result; } private static object FindInstance(Type type) { string[] array = new string[4] { "instance", "m_instance", "Instance", "m_localPlayer" }; foreach (string text in array) { FieldInfo fieldInfo = AccessTools.Field(type, text); if (fieldInfo != null && fieldInfo.IsStatic && type.IsAssignableFrom(fieldInfo.FieldType)) { object value = fieldInfo.GetValue(null); if (value != null) { Object val = (Object)((value is Object) ? value : null); if (val == null || !(val == (Object)null)) { return value; } } } PropertyInfo propertyInfo = AccessTools.Property(type, text); if (!(propertyInfo != null)) { continue; } MethodInfo? getMethod = propertyInfo.GetGetMethod(nonPublic: true); if ((object)getMethod == null || !getMethod.IsStatic || !type.IsAssignableFrom(propertyInfo.PropertyType)) { continue; } object value2 = propertyInfo.GetValue(null, null); if (value2 != null) { Object val2 = (Object)((value2 is Object) ? value2 : null); if (val2 == null || !(val2 == (Object)null)) { return value2; } } } if (typeof(Object).IsAssignableFrom(type)) { Object[] array2 = Object.FindObjectsByType(type, (FindObjectsInactive)0, (FindObjectsSortMode)0); Player player = Player.m_localPlayer; if (array2.Length == 0) { return null; } if ((Object)(object)player == (Object)null || !typeof(Component).IsAssignableFrom(type)) { return array2[0]; } return array2.Cast<Component>().OrderBy(delegate(Component c) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) Vector3 val3 = c.transform.position - ((Component)player).transform.position; return ((Vector3)(ref val3)).sqrMagnitude; }).First(); } return null; } private static bool Fill(Type t, string timeArg, out object value) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) Player localPlayer = Player.m_localPlayer; Vector3 val = (((Object)(object)localPlayer != (Object)null) ? ((Component)localPlayer).transform.position : Vector3.zero); value = null; if (t == typeof(float)) { float result; if (timeArg == "future") { value = Time.time + 1000000f; } else if (float.TryParse(timeArg, NumberStyles.Float, CultureInfo.InvariantCulture, out result)) { value = result; } else { value = Time.time; } return true; } if (t == typeof(Vector3)) { value = val; return true; } if (t == typeof(Vector2s)) { value = ZoneSystem.GetZone(val); return true; } if (t == typeof(long)) { value = ZDOMan.GetSessionID(); return true; } if (t == typeof(int)) { value = 0; return true; } if (t == typeof(bool)) { value = false; return true; } if (t == typeof(string)) { value = ""; return true; } if (!t.IsValueType) { value = FindInstance(t); return value != null; } return false; } private static string Describe(object o) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) Component val = (Component)((o is Component) ? o : null); if (val == null) { return o.GetType().Name; } return $"{((Object)val).name} at {val.transform.position}"; } private static Loop BuildLoop(MethodInfo method) { ParameterInfo[] parameters = method.GetParameters(); DynamicMethod dynamicMethod = new DynamicMethod("ValPerfMonitor_AllocCheck", typeof(void), new Type[3] { typeof(object), typeof(object[]), typeof(int) }, method.DeclaringType, skipVisibility: true); ILGenerator iLGenerator = dynamicMethod.GetILGenerator(); LocalBuilder localBuilder = null; if (!method.IsStatic) { localBuilder = iLGenerator.DeclareLocal(method.DeclaringType); iLGenerator.Emit(OpCodes.Ldarg_0); iLGenerator.Emit(method.DeclaringType.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, method.DeclaringType); iLGenerator.Emit(OpCodes.Stloc, localBuilder); } LocalBuilder[] array = new LocalBuilder[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { Type type = (parameters[i].ParameterType.IsByRef ? parameters[i].ParameterType.GetElementType() : parameters[i].ParameterType); array[i] = iLGenerator.DeclareLocal(type); iLGenerator.Emit(OpCodes.Ldarg_1); iLGenerator.Emit(OpCodes.Ldc_I4, i); iLGenerator.Emit(OpCodes.Ldelem_Ref); iLGenerator.Emit(type.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, type); iLGenerator.Emit(OpCodes.Stloc, array[i]); } LocalBuilder local = iLGenerator.DeclareLocal(typeof(int)); Label label = iLGenerator.DefineLabel(); Label label2 = iLGenerator.DefineLabel(); iLGenerator.Emit(OpCodes.Ldc_I4_0); iLGenerator.Emit(OpCodes.Stloc, local); iLGenerator.Emit(OpCodes.Br, label); iLGenerator.MarkLabel(label2); if (localBuilder != null) { iLGenerator.Emit(method.DeclaringType.IsValueType ? OpCodes.Ldloca : OpCodes.Ldloc, localBuilder); } for (int j = 0; j < parameters.Length; j++) { iLGenerator.Emit(parameters[j].ParameterType.IsByRef ? OpCodes.Ldloca : OpCodes.Ldloc, array[j]); } iLGenerator.Emit((method.IsStatic || method.DeclaringType.IsValueType) ? OpCodes.Call : OpCodes.Callvirt, method); if (method.ReturnType != typeof(void)) { iLGenerator.Emit(OpCodes.Pop); } iLGenerator.Emit(OpCodes.Ldloc, local); iLGenerator.Emit(OpCodes.Ldc_I4_1); iLGenerator.Emit(OpCodes.Add); iLGenerator.Emit(OpCodes.Stloc, local); iLGenerator.MarkLabel(label); iLGenerator.Emit(OpCodes.Ldloc, local); iLGenerator.Emit(OpCodes.Ldarg_2); iLGenerator.Emit(OpCodes.Blt, label2); iLGenerator.Emit(OpCodes.Ret); return (Loop)dynamicMethod.CreateDelegate(typeof(Loop)); } } internal static class AllocCounter { private static ProfilerRecorder _recorder; private static object _sink; public static string Method { get; private set; } = "unavailable"; public static bool Exact { get; private set; } public static bool Available { get; private set; } public static void Init(ManualLogSource log) { //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) try { MethodInfo method = typeof(GC).GetMethod("GetAllocatedBytesForCurrentThread", BindingFlags.Static | BindingFlags.Public); if (method != null) { Func<long> func = (Func<long>)Delegate.CreateDelegate(typeof(Func<long>), method); if (Verify(func, requireSmall: true)) { Use(func, "GC.GetAllocatedBytesForCurrentThread (exact)", exact: true, log); return; } } } catch (Exception ex) { log.LogDebug((object)("Per-thread allocation counter unusable: " + ex.Message)); } try { _recorder = ProfilerRecorder.StartNew(ProfilerCategory.Memory, "GC Allocated In Frame", 1, (ProfilerRecorderOptions)24); if (((ProfilerRecorder)(ref _recorder)).Valid) { Func<long> func2 = () => ((ProfilerRecorder)(ref _recorder)).CurrentValue; if (Verify(func2, requireSmall: true)) { Use(func2, "Unity 'GC Allocated In Frame' counter (exact, main thread + jobs)", exact: true, log); return; } } ((ProfilerRecorder)(ref _recorder)).Dispose(); } catch (Exception ex2) { log.LogDebug((object)("Unity allocation counter unusable: " + ex2.Message)); } try { Func<long> func3 = () => GC.GetTotalMemory(forceFullCollection: false); if (Verify(func3, requireSmall: false)) { Use(func3, "GC.GetTotalMemory (approximate: heap-block granularity)", exact: false, log); return; } } catch { } log.LogWarning((object)"No working allocation counter found; Allocations mode is unavailable on this runtime."); } private static void Use(Func<long> f, string method, bool exact, ManualLogSource log) { Probe.ReadAllocated = f; Method = method; Exact = exact; Available = true; log.LogInfo((object)("Allocation counter: " + method)); } private static bool Verify(Func<long> read, bool requireSmall) { long num = read(); byte[] sink = new byte[262144]; long num2 = read(); _sink = sink; if (num2 - num < 204800) { return false; } if (!requireSmall) { return true; } long num3 = read(); object[] array = new object[2000]; for (int i = 0; i < array.Length; i++) { array[i] = new object(); } long num4 = read(); _sink = array; _sink = null; return num4 - num3 >= 16000; } } internal static class AssetCleanup { public sealed class Run { public string Reason; public int AskFrame; public int DoneFrame = int.MaxValue; public long AskTick; public long DoneTick = long.MaxValue; public float AskedAt; public float DoneAt = -1f; public double DoneSession = -1.0; public float AskFrameMs; public float LongestMs; public float AfterMs; public int Frames; public bool Timed; public long HeapBefore; public long HeapAfter; public long UnityBefore; public long UnityAfter; public int MaterialsBefore = -1; public int MaterialsAfter = -1; public int TexturesBefore = -1; public int TexturesAfter = -1; public int MeshesBefore = -1; public int MeshesAfter = -1; public AsyncOperation Op; } public static Run Current; public static Run Last; public static readonly List<double> DoneAtSession = new List<double>(); public static bool CountUnityObjects; public static Action<Run> Finished; private const float WatchSeconds = 5f; private const float GiveUpSeconds = 60f; private static ManualLogSource _log; private static bool _transpiled; public static void Attach(string harmonyId, ManualLogSource log) { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Expected O, but got Unknown //IL_007e: Expected O, but got Unknown _log = log; MethodInfo methodInfo = AccessTools.Method(typeof(Game), "CollectResources", new Type[1] { typeof(bool) }, (Type[])null); if (methodInfo == null) { log.LogInfo((object)"Game.CollectResources is not there: the game's asset clean-up is not timed."); return; } try { new Harmony(harmonyId).Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(AssetCleanup), "Prefix", (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(AssetCleanup), "Transpiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null); if (!_transpiled) { log.LogInfo((object)"Game.CollectResources is not as expected: the asset clean-up is timed by the slowest frame in the 5 s after it instead of until Unity is done."); } } catch (Exception ex) { log.LogInfo((object)("The game's asset clean-up is not timed: " + ex.Message)); } } private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { MethodInfo methodInfo = AccessTools.Method(typeof(Resources), "UnloadUnusedAssets", (Type[])null, (Type[])null); MethodInfo operand = AccessTools.Method(typeof(AssetCleanup), "Track", (Type[])null, (Type[])null); List<CodeInstruction> list = instructions.ToList(); int num = 0; for (int i = 0; i + 1 < list.Count; i++) { if (CodeInstructionExtensions.Calls(list[i], methodInfo) && list[i + 1].opcode == OpCodes.Pop) { num++; } } if (num != 1 || methodInfo == null) { return list; } for (int j = 0; j + 1 < list.Count; j++) { if (CodeInstructionExtensions.Calls(list[j], methodInfo) && !(list[j + 1].opcode != OpCodes.Pop)) { list[j + 1].opcode = OpCodes.Call; list[j + 1].operand = operand; break; } } _transpiled = true; return list; } private static void Prefix() { try { Run run = new Run { Reason = Reason(), AskFrame = Time.frameCount, AskTick = Stopwatch.GetTimestamp(), AskedAt = Time.realtimeSinceStartup, HeapBefore = GC.GetTotalMemory(forceFullCollection: false), UnityBefore = Profiler.GetTotalAllocatedMemoryLong() }; if (CountUnityObjects) { run.MaterialsBefore = Count(typeof(Material)); run.TexturesBefore = Count(typeof(Texture)); run.MeshesBefore = Count(typeof(Mesh)); Plugin.Instance?.MarkHeavy(); } if (Current != null) { Finish(Current); } Current = run; Events.Mark("asset cleanup", run.Reason); } catch (Exception ex) { ManualLogSource log = _log; if (log != null) { log.LogDebug((object)("Asset clean-up: " + ex.Message)); } } } public static void Track(AsyncOperation op) { if (Current != null && Current.AskFrame == Time.frameCount) { Current.Op = op; } } private static string Reason() { try { foreach (StackFrame item in (new StackTrace(2, fNeedFileInfo: false).GetFrames() ?? new StackFrame[0]).Take(8)) { MethodBase? method = item.GetMethod(); string text = method?.Name ?? ""; string text2 = method?.DeclaringType?.Name ?? ""; if (text.Contains("CollectResourcesCheckPeriodic")) { return "hourly"; } if (text.Contains("CollectResourcesCheck")) { return "20 min check (respawn, sleep or a quiet moment)"; } if (text.Contains("LoadWorld") || text.Contains("LoadOldWorld")) { return "after loading the world"; } if (text2 == "ZDOMan") { return "leaving the world"; } if (text2 == "Terminal") { return "console command"; } if (text2.Contains("HourlyAssetUnload")) { return "hourly, held for an empty server (ValheimCommunityPatch)"; } } } catch { } return "asked by the game"; } private static int Count(Type t) { try { return Resources.FindObjectsOfTypeAll(t).Length; } catch { return -1; } } public static bool Frame(float ms, int frame, long fromTick = 0L, long toTick = 0L) { Run current = Current; if (current == null) { return false; } bool flag = toTick > 0; if (flag ? (toTick < current.AskTick) : (frame < current.AskFrame)) { return false; } if (flag ? (current.AskTick > fromTick) : (frame == current.AskFrame)) { current.AskFrameMs = ms; return false; } current.Frames++; current.AfterMs += ms; if (ms > current.LongestMs) { current.LongestMs = ms; } float realtimeSinceStartup = Time.realtimeSinceStartup; bool flag2; try { flag2 = ((current.Op != null) ? current.Op.isDone : (realtimeSinceStartup - current.AskedAt >= 5f)); } catch { flag2 = true; } if (!flag2 && realtimeSinceStartup - current.AskedAt < 60f) { return false; } current.Timed = current.Op != null && flag2; current.DoneFrame = frame; if (flag) { current.DoneTick = toTick; } Finish(current); return CountUnityObjects; } private static void Finish(Run r) { if (Current == r) { Current = null; } r.Op = null; r.DoneAt = Time.realtimeSinceStartup; if (r.DoneFrame == int.MaxValue) { r.DoneFrame = Time.frameCount; } if (r.DoneTick == long.MaxValue) { r.DoneTick = Stopwatch.GetTimestamp(); } r.DoneSession = (((Object)(object)Plugin.Instance != (Object)null) ? Plugin.Instance.SessionSeconds : ((double)r.DoneAt)); try { r.HeapAfter = GC.GetTotalMemory(forceFullCollection: false); r.UnityAfter = Profiler.GetTotalAllocatedMemoryLong(); if (CountUnityObjects) { r.MaterialsAfter = Count(typeof(Material)); r.TexturesAfter = Count(typeof(Texture)); r.MeshesAfter = Count(typeof(Mesh)); } } catch { } Last = r; DoneAtSession.Add(r.DoneSession); ManualLogSource log = _log; if (log != null) { log.LogInfo((object)Describe(r)); } try { Finished?.Invoke(r); } catch (Exception ex) { ManualLogSource log2 = _log; if (log2 != null) { log2.LogDebug((object)("Asset clean-up: " + ex.Message)); } } } public static string Label(int frame) { Run[] array = new Run[2] { Current, Last }; foreach (Run run in array) { if (run != null) { if (frame == run.AskFrame) { return "asked"; } if (frame > run.AskFrame && frame <= run.DoneFrame) { return "yes"; } } } return ""; } public static string Label(long fromTick, long toTick) { Run[] array = new Run[2] { Current, Last }; foreach (Run run in array) { if (run != null) { if (run.AskTick > fromTick && run.AskTick <= toTick) { return "asked"; } if (run.AskTick <= fromTick && fromTick < run.DoneTick) { return "yes"; } } } return ""; } public static string Describe(Run r) { string text = (r.Timed ? string.Format("Unity was done after {0} frame{1} ({2:0.0} s); the slowest froze the game for {3:0} ms", r.Frames, (r.Frames == 1) ? "" : "s", r.AfterMs / 1000f, r.LongestMs) : $"slowest frame in the {5f:0} s after it {r.LongestMs:0} ms"); string text2 = "managed memory " + Mb(r.HeapBefore) + " -> " + Mb(r.HeapAfter) + " MB" + ((r.UnityBefore > 0 && r.UnityAfter > 0) ? (", Unity's memory " + Mb(r.UnityBefore) + " -> " + Mb(r.UnityAfter) + " MB") : ""); if (r.MaterialsBefore >= 0 && r.MaterialsAfter >= 0) { text2 += $"; materials {r.MaterialsBefore:N0} -> {r.MaterialsAfter:N0}, textures {r.TexturesBefore:N0} -> {r.TexturesAfter:N0}, meshes {r.MeshesBefore:N0} -> {r.MeshesAfter:N0}"; } return $"Asset clean-up ({r.Reason}; the game's Resources.UnloadUnusedAssets): {text}; the frame that asked for it took {r.AskFrameMs:0} ms. {text2}."; } private static string Mb(long bytes) { return ((double)bytes / 1048576.0).ToString("0", Csv.Inv); } } internal sealed class BackgroundWriter : IDisposable { private readonly Queue<Action> _queue = new Queue<Action>(); private readonly Thread _thread; private readonly ManualLogSource _log; private readonly AutoResetEvent _signal = new AutoResetEvent(initialState: false); private volatile bool _stop; private volatile bool _busy; private static readonly Encoding Utf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); public bool Busy => _busy; public BackgroundWriter(ManualLogSource log) { _log = log; _thread = new Thread(Run) { IsBackground = true, Name = "ValPerfMonitor writer", Priority = ThreadPriority.BelowNormal }; _thread.Start(); } public void Append(string path, string text) { Enqueue(delegate { Save(path, text, append: true); }); } public void Write(string path, string text) { Enqueue(delegate { Save(path, text, append: false); }); } public void Job(Func<(string path, string text)> build) { Enqueue(delegate { var (path, text) = build(); Save(path, text, append: false); }); } private void Enqueue(Action a) { lock (_queue) { _queue.Enqueue(a); } _signal.Set(); } private static void Save(string path, string text, bool append) { Directory.CreateDirectory(Path.GetDirectoryName(path)); if (append) { File.AppendAllText(path, text, Utf8); } else { File.WriteAllText(path, text, Utf8); } } private void Run() { do { _signal.WaitOne(500); while (true) { Action action; lock (_queue) { if (_queue.Count == 0) { break; } action = _queue.Dequeue(); goto IL_0049; } IL_0049: _busy = true; try { action(); } catch (Exception ex) { _log.LogWarning((object)("Log write failed: " + ex.Message)); } finally { _busy = false; } } } while (!_stop); } public void Dispose() { _stop = true; _signal.Set(); _thread.Join(5000); } } internal static class Csv { public static readonly CultureInfo Inv = CultureInfo.InvariantCulture; private static readonly char[] Special = new char[4] { ',', '"', '\n', '\r' }; public static string Q(string s) { if (string.IsNullOrEmpty(s)) { return ""; } if (s.IndexOfAny(Special) >= 0) { return "\"" + s.Replace("\"", "\"\"") + "\""; } return s; } public static string F(double v, string fmt) { if (!double.IsNaN(v) && !double.IsInfinity(v)) { return v.ToString(fmt, Inv); } return ""; } public static string Json(string s) { if (s == null) { return "null"; } StringBuilder stringBuilder = new StringBuilder(s.Length + 2).Append('"'); foreach (char c in s) { switch (c) { case '"': stringBuilder.Append("\\\""); continue; case '\\': stringBuilder.Append("\\\\"); continue; case '\n': stringBuilder.Append("\\n"); continue; case '\t': stringBuilder.Append("\\t"); continue; case '<': stringBuilder.Append("\\u003c"); continue; case '\r': continue; } if (c < ' ') { StringBuilder stringBuilder2 = stringBuilder.Append("\\u"); int num = c; stringBuilder2.Append(num.ToString("x4")); } else { stringBuilder.Append(c); } } return stringBuilder.Append('"').ToString(); } public static string JNum(double v, string fmt = "0.####") { if (!double.IsNaN(v) && !double.IsInfinity(v)) { return v.ToString(fmt, Inv); } return "null"; } } [AttributeUsage(AttributeTargets.Method)] internal sealed class BridgeToolAttribute : Attribute { public string Name { get; } public string Description { get; } public BridgeToolAttribute(string name, string description) { Name = name; Description = description; } } internal static class BridgeCommands { private static Plugin P => Plugin.Instance; private static string Busy(Plugin p, bool refuse) { p.MarkHeavy(); string testRunning = p.TestRunning; if (!refuse || testRunning == null) { return null; } return testRunning + " is running; wait for it to finish, or stop it first (perf/stop)"; } [BridgeTool("perf/status", "What ValPerfMonitor is doing: capture, mode, suite step, seconds counted, warm-up")] private static object Status() { Plugin p = P; if ((Object)(object)p == (Object)null) { return new { success = false, error = "monitor not started" }; } Capture current = p.Current; return new { success = true, recording = (current != null), capture = (current?.Number ?? 0), mode = (current?.Mode.ToString() ?? ""), label = (current?.Label ?? ""), secondsCounted = ((current == null) ? 0.0 : Math.Round(current.MeasuredSeconds, 1)), suite = ((p.Suite == null) ? "" : $"step {p.Suite.Step + 1}/{p.Suite.Steps.Count}"), abTest = ((p.Ab == null) ? "" : p.Ab.Status), playRecording = ((p.Play == null) ? "" : p.Play.Status(p)), warmingUp = p.WarmingUp, worldReady = p.WorldReady, results = p.Results.Count }; } [BridgeTool("perf/start_suite", "Run the full suite (Baseline, Timing, Allocations, Trace) at the current spot with this label")] private static object StartSuite(string label = "", float seconds = 60f) { Plugin p = P; if ((Object)(object)p == (Object)null) { return new { success = false, error = "monitor not started" }; } if (!p.WorldReady) { return new { success = false, error = "not in a world yet (or the world is still loading)" }; } p.StartTimed(fullSuite: true, CaptureMode.Timing, string.IsNullOrWhiteSpace(label) ? null : label, (seconds >= 15f) ? seconds : 0f); return new { success = (p.Suite != null), label = (p.Suite?.Label ?? ""), secondsPerMode = (p.Suite?.Seconds ?? 0f) }; } [BridgeTool("perf/start_play", "Start a full play recording: Timing, Allocations and Trace take turns in blocks while playing, with a memory census now and then and one combined summary (play_summary.txt). Block lengths come from the config section '8 - Full play recording'. Runs until perf/stop; perf/play_summary reads it")] private static object StartPlayTool() { Plugin p = P; if ((Object)(object)p == (Object)null) { return new { success = false, error = "monitor not started" }; } Busy(p, refuse: false); p.StartPlay(); return new { success = true, cycle = p.Play.Describe(), summary = Path.Combine(p.SessionFolder, "play_summary.txt"), note = "blocks start once in a world" }; } [BridgeTool("perf/play_summary", "The full play recording's combined summary so far (also in play_summary.txt): FPS by place, heaviest mods, garbage, slow frames and their causes, memory, server connection, log errors")] private static object PlaySummaryTool() { Plugin p = P; if ((Object)(object)p == (Object)null) { return new { success = false, error = "monitor not started" }; } if (p.Play == null) { return new { success = false, error = "no full play recording is running (perf/start_play)" }; } Busy(p, refuse: false); return new { success = true, status = p.Play.Status(p), blocks = p.Play.Blocks, lines = p.Play.Summary(p) }; } [BridgeTool("perf/split_startup", "On the next launch, split these mods' startup into their own methods (comma-separated names or GUIDs) and/or the N slowest mods of this launch; empty and 0 = off. Results in perf/load_times after restart")] private static object SplitStartup(string mods = "", int slowest = 0) { Plugin p = P; if ((Object)(object)p == (Object)null) { return new { success = false, error = "monitor not started" }; } p.CfgSplitStartupMods.Value = mods ?? ""; p.CfgSplitStartupSlowest.Value = Math.Max(0, Math.Min(20, slowest)); return new { success = true, mods = p.CfgSplitStartupMods.Value, slowest = p.CfgSplitStartupSlowest.Value, note = "takes effect on the next game launch" }; } [BridgeTool("perf/stop", "Stop whatever is recording and save it")] private static object Stop() { Plugin p = P; if ((Object)(object)p == (Object)null) { return new { success = false, error = "monitor not started" }; } p.StopTest(); return new { success = true }; } [BridgeTool("perf/start_capture", "Start a labelled recording in one call: mode = Timing (default), Baseline, Allocations or Trace; label = text stored with the run (shown in compare.html). It records until perf/stop_capture. Any running recording is saved first; a running test is stopped")] private static object StartCaptureTool(string label = "", string mode = "Timing") { Plugin p = P; if ((Object)(object)p == (Object)null) { return new { success = false, error = "monitor not started" }; } Busy(p, refuse: false); if (!Enum.TryParse<CaptureMode>(mode?.Trim() ?? "", ignoreCase: true, out var result)) { return new { success = false, error = "mode '" + mode + "' is not one of Timing, Baseline, Allocations, Trace" }; } if (!p.WorldReady) { return new { success = false, error = "not in a world yet (or the world is still loading)" }; } p.StartLabelled(result, label ?? ""); Capture current = p.Current; if (current == null) { return new { success = false, error = "could not start a recording (see the log)" }; } return new { success = true, capture = current.Number, mode = current.Mode.ToString(), label = current.Label, folder = current.Folder, warmingUp = p.WarmingUp, note = "frames during warm-up are not counted; perf/status shows secondsCounted" }; } [BridgeTool("perf/stop_capture", "Stop the recording started with perf/start_capture (or any running one), save it, and return its result: FPS, 1% low, the heaviest mod and the report")] private static object StopCaptureTool() { Plugin p = P; if ((Object)(object)p == (Object)null) { return new { success = false, error = "monitor not started" }; } Busy(p, refuse: false); Capture current = p.Current; if (current == null) { return new { success = false, error = "nothing is recording" }; } int count = p.Results.Count; p.StopTest(); CaptureResult captureResult = ((p.Results.Count > count) ? p.Results[p.Results.Count - 1] : null); if (captureResult == null) { return new { success = true, capture = current.Number, saved = false, note = "no frames were counted (still warming up?), so no report was written" }; } return new { success = true, capture = captureResult.Number, saved = true, mode = captureResult.Mode.ToString(), label = captureResult.Label, seconds = Math.Round(captureResult.Seconds, 1), fps = Round(captureResult.Fps), fps1Low = Round(captureResult.Fps1Low), modsPerFrame = Round(captureResult.ModsPerFrame), unit = captureResult.Unit, heaviestMod = captureResult.Top, report = captureResult.Report }; } [BridgeTool("perf/results", "Captures finished this session: mode, label, FPS, 1% low, heaviest mod, report path")] private static object Results() { Plugin p = P; if ((Object)(object)p == (Object)null) { return new { success = false, error = "monitor not started" }; } return new { success = true, captures = p.Results.Select((CaptureResult r) => new { Number = r.Number, mode = r.Mode.ToString(), Label = r.Label, seconds = Math.Round(r.Seconds, 0), fps = Math.Round(r.Fps, 1), fps1Low = Math.Round(r.Fps1Low, 1), modsPerFrame = (double.IsNaN(r.ModsPerFrame) ? ((double?)null) : new double?(Math.Round(r.ModsPerFrame, 3))), Unit = r.Unit, heaviest = r.Top, Report = r.Report, numbers = ((r.Mode != CaptureMode.Allocations) ? "measured" : (AllocCounter.Exact ? "exact" : "estimates: see 'How sure' in the report")) }).ToList(), compare = Path.Combine(p.RootFolder, "compare.html") }; } [BridgeTool("perf/connection", "The connection to a dedicated server right now and this visit so far: network ping, ping through the game and how long the server took to answer, connection quality, upload/download KB/s, upload backlog, world objects sent/received, how many loaded objects and creatures you simulate, server hitches (no answer for over a second; server busy or connection trouble), and the last join's steps")] private static object Connection() { ServerLink l = P?.Link; if (l == null) { return new { success = false, error = "monitor not started" }; } JoinWatch joinWatch = JoinWatch.Running ?? JoinWatch.Last; return new { success = true, connected = l.Connected, server = l.Server, minutes = Round(l.MinutesConnected), now = new { Players = l.Players, networkPingMs = Round(l.NetPing), gamePingMs = Round(l.GamePing), serverDelayMs = Round(l.ServerDelay), qualityLocal = Round(l.QualityLocal), qualityRemote = Round(l.QualityRemote), uploadKbs = Round(l.UpKbs), downloadKbs = Round(l.DownKbs), uploadBacklogKb = Round(l.BacklogKb), worldObjectsSentPerSec = l.ZdosSent, worldObjectsReceivedPerSec = l.ZdosRecv, waitingForAnswerSeconds = Round(l.Waiting), objectsNearby = l.Nearby, objectsMine = l.Mine, objectsOtherPlayers = l.Others, creaturesNearby = l.Creatures, creaturesMine = l.CreaturesMine }, summary = (l.Connected ? l.Summary(l.MinutesConnected) : null), upload = ((l.LastUpload == null) ? null : (from r in l.LastUpload.Top(15) where r.Sent + r.Changes > 0 select new { prefab = r.Name, sentPerSec = Round((double)r.Sent / l.LastUpload.Seconds), kbPerSec = Round((double)r.SentBytes / l.LastUpload.Seconds / 1024.0), changesPerSec = Round((double)r.Changes / l.LastUpload.Seconds), changedBy = UploadWatch.ChangedByText(r, 4) }).ToList()), hitches = new { total = l.Hitches, serverBusy = l.HitchesServer, connection = l.HitchesConnection, longestSeconds = Round(l.LongestHitch), recent = l.RecentHitches }, join = ((joinWatch == null) ? null : new { Server = joinWatch.Server, finished = (JoinWatch.Running != joinWatch), totalSeconds = Round(joinWatch.TotalSeconds), steps = joinWatch.Steps.Select(((string step, double at) s) => new { step = s.step, atSeconds = Round(s.at) }).ToList() }) }; } [BridgeTool("perf/load_times", "Startup and world load times this session, with the slowest mods and steps")] private static object LoadTimes() { LoadTimes loadTimes = P?.Loads; if (loadTimes == null) { return new { success = false, error = "monitor not started" }; } return new { success = true, startupDone = loadTimes.StartupDone, totalToMenuSeconds = Round(loadTimes.TotalToMenu), modLoadingSeconds = Round(loadTimes.ModLoading), modsToMenuSeconds = Round(loadTimes.ModsToMenu), slowestMods = (from m in loadTimes.Mods.OrderByDescending((LoadTimes.ModLoad m) => m.Seconds).Take(10) select new { Name = m.Name, seconds = Round(m.Seconds) }).ToList(), startupSteps = (from s in loadTimes.StartupSteps.Take(10) select new { step = s.label, calls = s.calls, seconds = Round(s.seconds) }).ToList(), startupModsInSteps = (from s in loadTimes.StartupStepMods.Take(20) select new {
patchers/ValPerfMonitor.Preloader.dll
Decompiled a month agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using Microsoft.CodeAnalysis; using Mono.Cecil; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyCompany("ValPerfMonitor.Preloader")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.2.0.0")] [assembly: AssemblyInformationalVersion("1.2.0+c2bdc1f12ed51549180765c2279617917e522ca0")] [assembly: AssemblyProduct("ValPerfMonitor.Preloader")] [assembly: AssemblyTitle("ValPerfMonitor.Preloader")] [assembly: AssemblyVersion("1.2.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ValPerfMonitor.Preloader { public static class LoadTimer { public const string Key = "ValPerfMonitor.LoadEvents"; public static IEnumerable<string> TargetDLLs { get; } = new string[0]; public static void Patch(AssemblyDefinition assembly) { } public static void Initialize() { SessionLogs.SaveLast(); List<string> list = new List<string>(); Listener.Record(list, "Preloader patcher started"); AppDomain.CurrentDomain.SetData("ValPerfMonitor.LoadEvents", list); Logger.Listeners.Add((ILogListener)(object)new Listener(list)); } } internal sealed class Listener : ILogListener, IDisposable { private readonly List<string> _events; private bool _done; public Listener(List<string> events) { _events = events; } public void LogEvent(object sender, LogEventArgs e) { if (_done || e.Source == null || e.Source.SourceName != "BepInEx") { return; } string text = (e.Data as string) ?? e.Data?.ToString(); if (text != null) { if (text.StartsWith("Loading [") || text.StartsWith("Chainloader started") || text.StartsWith("Preloader finished")) { Record(_events, text); } else if (text.StartsWith("Chainloader startup complete")) { Record(_events, text); _done = true; } } } internal static void Record(List<string> events, string text) { lock (events) { events.Add(Stopwatch.GetTimestamp() + "\t" + DateTime.UtcNow.Ticks + "\t" + text); } } public void Dispose() { } } internal static class SessionLogs { private sealed class Crash { public DateTime Started; public DateTime Ended; public bool PluginStarted; public string Folder; public List<string> CodeFrames = new List<string>(); public List<string> LastErrors = new List<string>(); public List<string> LastLines = new List<string>(); public string Report(string savedLog) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append($"The game session from {Started:yyyy-MM-dd HH:mm} to {Ended:HH:mm:ss} did not close normally"); stringBuilder.Append(PluginStarted ? ".\n" : " (it ended while the mods were still loading).\n"); if (Folder != null) { stringBuilder.Append("It crashed: Unity left a crash report in ").Append(Folder).Append("\n"); } else { stringBuilder.Append("No crash report from Unity: the game froze and was closed, was ended from Task Manager, or the PC shut down.\n"); } if (savedLog != null) { stringBuilder.Append("Full log of that session: ").Append(savedLog).Append("\n"); } if (CodeFrames.Count > 0) { stringBuilder.Append("\nCode running when it crashed (innermost first):\n ").Append(string.Join("\n ", CodeFrames.ToArray())).Append("\n"); } if (LastErrors.Count > 0) { stringBuilder.Append("\nLast errors in the log:\n").Append(string.Join("\n", LastErrors.ToArray())).Append("\n"); } if (LastLines.Count > 0) { stringBuilder.Append("\nLast lines of the log:\n").Append(string.Join("\n", LastLines.ToArray())).Append("\n"); } return stringBuilder.ToString(); } } internal const string Section = "3 - Logging"; internal const string KeepKey = "Keep past session logs"; internal const string DaysKey = "Days to keep past session logs"; internal const string CrashKey = "ValPerfMonitor.LastCrash"; internal const string MarkerFile = "session-running.txt"; internal const string CrashFile = "last_crash.txt"; public static void SaveLast() { //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Unknown result type (might be due to invalid IL or missing references) ManualLogSource val = Logger.CreateLogSource("ValPerfMonitor"); try { string text = Path.Combine(Paths.BepInExRootPath, "ValPerfMonitor"); string text2 = Path.Combine(text, "session_logs"); FileInfo fileInfo = new FileInfo(Path.Combine(Paths.BepInExRootPath, "LogOutput.log")); bool flag = fileInfo.Exists && fileInfo.Length > 0; string path = Path.Combine(text, "session-running.txt"); string text3 = null; try { if (File.Exists(path)) { text3 = File.ReadAllText(path); } } catch { } Directory.CreateDirectory(text); File.WriteAllText(path, "started=" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture) + "\nphase=preloader\n"); Crash crash = ((text3 == null) ? null : CheckCrash(text3, flag ? fileInfo : null)); ConfigFile val2 = new ConfigFile(Path.Combine(Paths.ConfigPath, "valheimmods.ValPerfMonitor.cfg"), false) { SaveOnConfigSet = false }; bool value = val2.Bind<bool>("3 - Logging", "Keep past session logs", true, (ConfigDescription)null).Value; int value2 = val2.Bind<int>("3 - Logging", "Days to keep past session logs", 14, (ConfigDescription)null).Value; string text4 = null; if (value && flag) { Directory.CreateDirectory(text2); string text5 = fileInfo.LastWriteTime.ToString("yyyy-MM-dd_HH-mm-ss", CultureInfo.InvariantCulture); string text6 = ((crash == null) ? "" : ((crash.Folder != null) ? "_crashed" : "_not-closed")); if (!Directory.GetFiles(text2, text5 + "*.log").Any()) { text4 = Path.Combine(text2, text5 + text6 + ".log"); File.Copy(fileInfo.FullName, text4); val.LogInfo((object)("Past session logs: saved the previous session's log as session_logs\\" + Path.GetFileName(text4) + ".")); } CopyToSessionFolder(text, fileInfo, text6, val); } if (crash != null) { string text7 = crash.Report(text4); File.WriteAllText(Path.Combine(text, "last_crash.txt"), text7); AppDomain.CurrentDomain.SetData("ValPerfMonitor.LastCrash", text7); } if (!value || value2 <= 0 || !Directory.Exists(text2)) { return; } DateTime dateTime = DateTime.Now.AddDays(-value2); FileInfo[] files = new DirectoryInfo(text2).GetFiles("*.log"); foreach (FileInfo fileInfo2 in files) { if (fileInfo2.LastWriteTime < dateTime) { fileInfo2.Delete(); } } } catch (Exception ex) { val.LogWarning((object)("Past session logs: could not check or save the previous session's log - " + ex.GetType().Name + ": " + ex.Message)); } finally { val.Dispose(); } } private static void CopyToSessionFolder(string root, FileInfo source, string suffix, ManualLogSource log) { string path = Path.Combine(root, "last-session-folder.txt"); if (!File.Exists(path)) { return; } try { string fullPath = Path.GetFullPath(File.ReadAllText(path).Trim()); if (fullPath.StartsWith(Path.GetFullPath(root), StringComparison.OrdinalIgnoreCase) && Directory.Exists(fullPath)) { string text = Path.Combine(fullPath, "LogOutput" + suffix + ".log"); if (!File.Exists(text)) { File.Copy(source.FullName, text); log.LogInfo((object)("Past session logs: also saved it in that session's folder, " + Path.GetFileName(fullPath) + ".")); } } } catch (Exception ex) { log.LogWarning((object)("Past session logs: could not copy the log into its session folder - " + ex.Message)); } finally { try { File.Delete(path); } catch { } } } private static Crash CheckCrash(string marker, FileInfo log) { Crash c = new Crash { PluginStarted = marker.Contains("phase=plugin") }; string[] array = marker.Split(new char[1] { '\n' }); foreach (string text in array) { if (text.StartsWith("started=") && DateTime.TryParseExact(text.Substring(8).Trim(), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out var result)) { c.Started = result; } } c.Ended = log?.LastWriteTime ?? DateTime.Now; if (c.Started == default(DateTime)) { c.Started = c.Ended; } try { string path = Path.Combine(Path.Combine(Path.Combine(Path.GetTempPath(), "IronGate"), "Valheim"), "Crashes"); if (Directory.Exists(path)) { DirectoryInfo directoryInfo = (from d in new DirectoryInfo(path).GetDirectories("Crash_*") where d.CreationTime >= c.Started.AddMinutes(-1.0) && d.CreationTime <= DateTime.Now orderby d.CreationTime descending select d).FirstOrDefault(); if (directoryInfo != null) { c.Folder = directoryInfo.FullName; string text2 = Path.Combine(directoryInfo.FullName, "Player.log"); if (File.Exists(text2)) { c.CodeFrames = CrashFrames(text2); } } } } catch { } if (!c.PluginStarted && c.Folder == null) { return null; } if (log != null) { try { List<string> list = ReadShared(log.FullName); c.LastLines = list.Where((string l) => l.Trim().Length > 0).Skip(Math.Max(0, list.Count((string l) => l.Trim().Length > 0) - 12)).ToList(); List<string> list2 = new List<string>(); int num = list.Count - 1; while (num >= 0 && list2.Count < 3) { if (list[num].StartsWith("[Error") || list[num].StartsWith("[Fatal")) { List<string> list3 = new List<string> { list[num] }; for (int num2 = num + 1; num2 < list.Count && num2 <= num + 6 && !list[num2].StartsWith("["); num2++) { if (list[num2].Trim().Length > 0) { list3.Add(list[num2]); } } list2.Insert(0, string.Join("\n", list3.ToArray())); } num--; } c.LastErrors = list2; } catch { } } return c; } private static List<string> CrashFrames(string playerLog) { List<string> list = new List<string>(); bool flag = false; foreach (string item in ReadShared(playerLog)) { if (item.Contains("OUTPUTTING STACK TRACE")) { flag = true; } else { if (!flag) { continue; } if (item.Contains("END OF STACKTRACE")) { break; } int num = item.IndexOf("(Mono JIT Code)", StringComparison.Ordinal); if (num >= 0) { list.Add(item.Substring(num + 15).Trim()); if (list.Count >= 20) { break; } } } } return list; } private static List<string> ReadShared(string path) { using FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); using StreamReader streamReader = new StreamReader(stream); List<string> list = new List<string>(); string item; while ((item = streamReader.ReadLine()) != null) { list.Add(item); } return list; } } }