Decompiled source of Inventory Freeze Fix v0.1.3

plugins/InventoryFreezeFix.dll

Decompiled 4 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using AzNean.SotfCommon;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using InventoryFreezeFix.Patches;
using Microsoft.CodeAnalysis;
using Sons.Inventory;
using TheForest.Utils;
using UnityEngine;
using UnityEngine.Rendering.HighDefinition;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("InventoryFreezeFix")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.3.0")]
[assembly: AssemblyInformationalVersion("0.1.3+b0595e3393fda9ded105ebc2b6a7d6b00c81dd62")]
[assembly: AssemblyProduct("InventoryFreezeFix")]
[assembly: AssemblyTitle("InventoryFreezeFix")]
[assembly: AssemblyVersion("0.1.3.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 AzNean.SotfCommon
{
	internal static class ModLog
	{
		private static ManualLogSource _log;

		private static ConfigEntry<bool> _full;

		private static readonly HashSet<string> _once = new HashSet<string>();

		private static readonly Dictionary<(int, string), int> _state = new Dictionary<(int, string), int>();

		internal static bool Full => _full.Value;

		internal static void Init(ManualLogSource log, ConfigEntry<bool> full)
		{
			_log = log;
			_full = full;
		}

		internal static void Trace(string message)
		{
			if (_full.Value)
			{
				_log.LogInfo((object)message);
			}
		}

		internal static bool Changed(int id, string what, int state)
		{
			if (!_full.Value || (_state.TryGetValue((id, what), out var value) && value == state))
			{
				return false;
			}
			_state[(id, what)] = state;
			return true;
		}

		internal static void Once(string key, string message, LogLevel level = (LogLevel)16)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if (_once.Add(key))
			{
				_log.Log(level, (object)message);
			}
		}
	}
}
namespace InventoryFreezeFix
{
	[BepInPlugin("aznan.sotf.inventoryfreezefix", "InventoryFreezeFix", "0.1.3")]
	public class Plugin : BasePlugin
	{
		internal const string Version = "0.1.3";

		internal static ManualLogSource Logger;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<bool> KeepUpscalerAlive;

		internal static ConfigEntry<bool> KeepCameraBuffers;

		internal static ConfigEntry<bool> InventoryUpscalerOff;

		internal static ConfigEntry<bool> FullLogging;

		internal static ConfigEntry<float> HitchLogSeconds;

		public override void Load()
		{
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Expected O, but got Unknown
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: 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_012a: Expected O, but got Unknown
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Expected O, but got Unknown
			Logger = ((BasePlugin)this).Log;
			Enabled = ((BasePlugin)this).Config.Bind<bool>("General", "Enabled", true, "True = opening and closing the inventory no longer freezes the game when DLSS is on (most visible with OptiScaler on AMD/Intel cards). False = the game's behaviour. Takes effect at the next inventory opening. Default: true.");
			KeepUpscalerAlive = ((BasePlugin)this).Config.Bind<bool>("Upscaler", "KeepUpscalerAlive", true, "True = DLSS keeps its working data for every camera that still exists (player view, inventory view) instead of rebuilding it after a few seconds unused: that rebuild is the freeze. Costs some video memory (one DLSS set per camera), nothing per frame. False = the game's behaviour. Default: true.");
			KeepCameraBuffers = ((BasePlugin)this).Config.Bind<bool>("Upscaler", "KeepCameraBuffers", true, new ConfigDescription("True = the inventory camera keeps its render buffers while the inventory is closed, and your normal view keeps its own while the inventory is open (the game turns it off), so neither is rebuilt at each opening or closing. Costs some video memory, nothing per frame. False = the game's behaviour (after reloading the save). Default: true.", (AcceptableValueBase)null, new object[1] { "ReloadSave" }));
			InventoryUpscalerOff = ((BasePlugin)this).Config.Bind<bool>("Upscaler", "InventoryUpscalerOff", true, new ConfigDescription("True = the inventory view is drawn without DLSS or dynamic resolution (native resolution), so no DLSS data is ever made for it: this removes the last freeze, at the first opening after loading a save. The inventory may look slightly different (no DLSS sharpening). False = the inventory view uses DLSS like the game (after reloading the save). Default: true.", (AcceptableValueBase)null, new object[1] { "ReloadSave" }));
			HitchLogSeconds = ((BasePlugin)this).Config.Bind<float>("Debug", "HitchLogSeconds", 0.25f, "Any frame longer than this, in seconds, is written to the BepInEx log with whether the inventory was open: the proof that the freeze is gone (or not). 0 = never. Advised: 0.1 to 2. Default: 0.25.");
			FullLogging = ((BasePlugin)this).Config.Bind<bool>("Debug", "FullLogging", false, "True = the BepInEx log gets every step useful to diagnose a problem (values read and set at each inventory opening). False = only loading, version, the once-per-game summary, long frames and errors.");
			ModLog.Init(Logger, FullLogging);
			new Harmony("aznan.sotf.inventoryfreezefix").PatchAll();
			ClassInjector.RegisterTypeInIl2Cpp<HitchWatcher>();
			GameObject val = new GameObject("InventoryFreezeFix");
			Object.DontDestroyOnLoad((Object)val);
			((Object)val).hideFlags = (HideFlags)61;
			val.AddComponent<HitchWatcher>();
			ManualLogSource logger = Logger;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(27, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("InventoryFreezeFix ");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>("0.1.3");
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" loaded.");
			}
			logger.LogInfo(val2);
		}
	}
	public class HitchWatcher : MonoBehaviour
	{
		private const float Window = 3f;

		private bool _wasOpen;

		private int _closedLong;

		private float _closedWorst;

		private float _since = -1f;

		private float _longest;

		private float _usual = 1f / 60f;

		public HitchWatcher(IntPtr ptr)
			: base(ptr)
		{
		}

		private void Update()
		{
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			//IL_0240: Unknown result type (might be due to invalid IL or missing references)
			//IL_0247: Expected O, but got Unknown
			float value = Plugin.HitchLogSeconds.Value;
			float unscaledDeltaTime = Time.unscaledDeltaTime;
			bool isOpen = InventoryCamera.IsOpen;
			if (isOpen != _wasOpen)
			{
				_wasOpen = isOpen;
				_since = Time.unscaledTime;
				_longest = unscaledDeltaTime;
			}
			bool flag = _since >= 0f;
			bool flag2 = default(bool);
			if (!flag && unscaledDeltaTime < 0.2f)
			{
				_usual += (unscaledDeltaTime - _usual) * 0.05f;
			}
			else if (flag)
			{
				if (unscaledDeltaTime > _longest)
				{
					_longest = unscaledDeltaTime;
				}
				if (Time.unscaledTime - _since >= 3f)
				{
					ManualLogSource logger = Plugin.Logger;
					BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(92, 7, ref flag2);
					if (flag2)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Inventory ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(isOpen ? "opened" : "closed");
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": fix ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(Plugin.Enabled.Value ? "active" : "off");
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" (DLSS lifetime ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<ulong>(DLSSPass.sMaximumFrameExpiration);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" frames), longest frame in the next ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(3f, "0");
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" s: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(_longest, "0.00");
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" s (usual frame ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(_usual, "0.000");
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" s)");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>((isOpen && _closedLong > 0) ? $"; before it, {_closedLong} long frame(s) with the inventory closed, longest {_closedWorst:0.00} s" : "");
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(".");
					}
					logger.LogInfo(val);
					if (isOpen)
					{
						_closedLong = 0;
						_closedWorst = 0f;
					}
					_since = -1f;
				}
			}
			if (!(value > 0f) || !(unscaledDeltaTime >= value) || flag)
			{
				return;
			}
			if (isOpen)
			{
				ManualLogSource logger2 = Plugin.Logger;
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(37, 1, ref flag2);
				if (flag2)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Long frame: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(unscaledDeltaTime, "0.00");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" s (inventory view open).");
				}
				logger2.LogInfo(val);
			}
			else
			{
				_closedLong++;
				if (unscaledDeltaTime > _closedWorst)
				{
					_closedWorst = unscaledDeltaTime;
				}
			}
		}
	}
}
namespace InventoryFreezeFix.Patches
{
	[HarmonyPatch(typeof(InventoryCameraController), "OnEnable")]
	internal static class InventoryCamera
	{
		private static ulong? _gameExpiration;

		private static int _loggedCamera;

		private static InventoryCameraController _controller;

		internal static bool IsOpen
		{
			get
			{
				if ((Object)(object)_controller != (Object)null)
				{
					return ((Behaviour)_controller).isActiveAndEnabled;
				}
				return false;
			}
		}

		private static void Postfix(InventoryCameraController __instance)
		{
			//IL_0357: Unknown result type (might be due to invalid IL or missing references)
			//IL_035e: Expected O, but got Unknown
			_controller = __instance;
			try
			{
				ulong valueOrDefault = _gameExpiration.GetValueOrDefault();
				if (!_gameExpiration.HasValue)
				{
					valueOrDefault = DLSSPass.sMaximumFrameExpiration;
					_gameExpiration = valueOrDefault;
				}
				bool value = Plugin.Enabled.Value;
				DLSSPass.sMaximumFrameExpiration = ((value && Plugin.KeepUpscalerAlive.Value) ? ulong.MaxValue : _gameExpiration.Value);
				Camera camera = __instance.Camera;
				HDAdditionalCameraData val = (((Object)(object)camera != (Object)null) ? ((Component)camera).GetComponent<HDAdditionalCameraData>() : null);
				if ((Object)(object)val == (Object)null)
				{
					ModLog.Once("nohd" + (((Object)(object)camera != (Object)null) ? ((Object)camera).GetInstanceID() : 0), "Inventory camera without HDRP camera data: only the DLSS lifetime was changed.", (LogLevel)4);
					return;
				}
				bool hasPersistentHistory = val.hasPersistentHistory;
				bool allowDeepLearningSuperSampling = val.allowDeepLearningSuperSampling;
				bool allowDynamicResolution = camera.allowDynamicResolution;
				HDAdditionalCameraData val2 = (((Object)(object)LocalPlayer.MainCam != (Object)null) ? ((Component)LocalPlayer.MainCam).GetComponent<HDAdditionalCameraData>() : null);
				bool value2 = (Object)(object)val2 != (Object)null && val2.hasPersistentHistory;
				string value3 = "untouched";
				if (value && Plugin.KeepCameraBuffers.Value)
				{
					val.hasPersistentHistory = true;
					if ((Object)(object)val2 != (Object)null)
					{
						val2.hasPersistentHistory = true;
					}
				}
				if (value && Plugin.InventoryUpscalerOff.Value)
				{
					camera.allowDynamicResolution = false;
					val.allowDynamicResolution = false;
					val.allowDeepLearningSuperSampling = false;
					Component component = ((Component)camera).GetComponent("DynamicResolutionSettingReceiver");
					value3 = (((Object)(object)component == (Object)null) ? "none" : "turned off");
					if ((Object)(object)component != (Object)null)
					{
						((Il2CppObjectBase)component).Cast<Behaviour>().enabled = false;
					}
				}
				string text = $"applied to inventory camera {((Object)camera).name} (enabled {value}; DLSS lifetime {_gameExpiration} -> {DLSSPass.sMaximumFrameExpiration} frames; persistent history {hasPersistentHistory} -> {val.hasPersistentHistory}, player view {(((Object)(object)val2 == (Object)null) ? "not found" : $"{value2} -> {val2.hasPersistentHistory}")}; DLSS {allowDeepLearningSuperSampling} -> {val.allowDeepLearningSuperSampling}; dynamic resolution {allowDynamicResolution} -> {camera.allowDynamicResolution}; game DLSS receiver {value3})";
				int instanceID = ((Object)camera).GetInstanceID();
				bool flag = ModLog.Changed(instanceID, "applied", text.GetHashCode());
				if (instanceID != _loggedCamera)
				{
					_loggedCamera = instanceID;
					Plugin.Logger.LogInfo((object)text);
				}
				else if (flag)
				{
					ModLog.Trace(text);
				}
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag2 = default(bool);
				BepInExErrorLogInterpolatedStringHandler val3 = new BepInExErrorLogInterpolatedStringHandler(41, 1, ref flag2);
				if (flag2)
				{
					((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Could not apply to the inventory camera: ");
					((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<Exception>(ex);
				}
				logger.LogError(val3);
			}
		}
	}
}