Decompiled source of CrouchHeal v1.2.0

CrouchHeal.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("CrouchHeal")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.2.0.0")]
[assembly: AssemblyInformationalVersion("1.2.0")]
[assembly: AssemblyProduct("CrouchHeal")]
[assembly: AssemblyTitle("CrouchHeal")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.2.0.0")]
[module: UnverifiableCode]
[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 CrouchHeal
{
	internal sealed class CrouchCycle
	{
		private bool standingSeen;

		private bool armed;

		public void Reset()
		{
			standingSeen = false;
			armed = false;
		}

		public bool Sample(bool valid, bool crouching)
		{
			if (!valid)
			{
				Reset();
				return false;
			}
			if (crouching)
			{
				if (standingSeen)
				{
					armed = true;
				}
				return false;
			}
			bool result = armed;
			standingSeen = true;
			armed = false;
			return result;
		}

		public static int Amount(int configured, int current, int maximum)
		{
			if (current <= 0 || maximum <= current)
			{
				return 0;
			}
			return Math.Min((configured < 1) ? 1 : ((configured > 200) ? 200 : configured), maximum - current);
		}
	}
	internal sealed class LocalizedConfig : IDisposable
	{
		internal sealed class Row
		{
			public string LegacySection;

			public string LegacyKey;

			public string EnSection;

			public string ZhSection;

			public string EnKey;

			public string ZhKey;

			public string EnDescription;

			public string ZhDescription;

			public ConfigDefinition Definition(bool zh)
			{
				//IL_0022: Unknown result type (might be due to invalid IL or missing references)
				//IL_0028: Expected O, but got Unknown
				return new ConfigDefinition(zh ? ZhSection : EnSection, zh ? ZhKey : EnKey);
			}

			public string Description(bool zh)
			{
				if (!zh)
				{
					return EnDescription;
				}
				return ZhDescription;
			}
		}

		internal static readonly Row LanguageRow = new Row
		{
			LegacySection = "Interface",
			LegacyKey = "Language",
			EnSection = "0.Language",
			ZhSection = "0.语言",
			EnKey = "Language 语言",
			ZhKey = "Language 语言",
			EnDescription = "Select English or 简体中文 to switch this mod's configuration names, groups and descriptions immediately. Auto follows the game language (English fallback). No restart required.",
			ZhDescription = "选择 English 或简体中文可立即切换本模组配置的分组、名称和说明,无需重启。Auto 跟随游戏语言,其他语言回退英文。"
		};

		internal static readonly Row EnabledRow = new Row
		{
			LegacySection = "General",
			LegacyKey = "Enabled",
			EnSection = "1.General",
			ZhSection = "1.常规",
			EnKey = "Enable mod",
			ZhKey = "启用模组",
			EnDescription = "Enable self-healing after a completed crouch-to-stand cycle. Holding crouch does not heal continuously. Only your living local character is healed.",
			ZhDescription = "启用蹲下后起身回血;每完成一轮只恢复一次,保持蹲姿不会持续回血。只治疗自己的存活角色。"
		};

		internal static readonly Row AmountRow = new Row
		{
			LegacySection = "General",
			LegacyKey = "HealAmount",
			EnSection = "1.General",
			ZhSection = "1.常规",
			EnKey = "Heal amount",
			ZhKey = "单次回血量",
			EnDescription = "HP restored per completed crouch-to-stand cycle. Default: 5. Range: 1–200 (integer). Never exceeds your current maximum health; does not raise max HP or revive you.",
			ZhDescription = "每次完成蹲下后起身恢复的生命值。默认 5,范围 1–200(整数),不超过角色当前生命上限,不增加最大生命、不复活。"
		};

		private readonly ConfigFile config;

		private readonly Func<bool> gameIsChinese;

		private readonly Action<string> warn;

		private readonly Dictionary<Row, ConfigEntryBase> entries = new Dictionary<Row, ConfigEntryBase>();

		public ConfigEntry<string> Language { get; }

		public ConfigEntry<bool> Enabled { get; }

		public ConfigEntry<int> HealAmount { get; }

		public bool Chinese { get; private set; }

		public event Action Changed;

		public LocalizedConfig(ConfigFile config, Func<bool> gameIsChinese, Action<string> warn)
		{
			this.config = config;
			this.gameIsChinese = gameIsChinese;
			this.warn = warn;
			bool saveOnConfigSet = config.SaveOnConfigSet;
			config.SaveOnConfigSet = false;
			try
			{
				Language = Bind(LanguageRow, "Auto", (AcceptableValueBase)(object)new AcceptableValueList<string>(new string[3] { "Auto", "English", "简体中文" }));
				Chinese = ResolveLanguage();
				Enabled = Bind(EnabledRow, fallback: true);
				HealAmount = Bind(AmountRow, 5, (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 200));
				Apply(notify: false);
				RemoveObsoleteEntries();
				config.Save();
			}
			finally
			{
				config.SaveOnConfigSet = saveOnConfigSet;
			}
			Language.SettingChanged += LanguageChanged;
		}

		private ConfigEntry<T> Bind<T>(Row row, T fallback, AcceptableValueBase range = null)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			string text = FindSaved(row);
			ConfigEntry<T> val = config.Bind<T>(row.Definition(Chinese), fallback, new ConfigDescription(row.Description(Chinese), range, Array.Empty<object>()));
			if (text != null)
			{
				((ConfigEntryBase)val).SetSerializedValue(text);
			}
			entries.Add(row, (ConfigEntryBase)(object)val);
			return val;
		}

		private string FindSaved(Row row)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			if (!(Member(config, "OrphanedEntries") is IDictionary dictionary))
			{
				return null;
			}
			ConfigDefinition[] array = (ConfigDefinition[])(object)new ConfigDefinition[3]
			{
				row.Definition(Chinese),
				row.Definition(!Chinese),
				new ConfigDefinition(row.LegacySection, row.LegacyKey)
			};
			foreach (ConfigDefinition key in array)
			{
				if (dictionary.Contains(key))
				{
					return dictionary[key] as string;
				}
			}
			return null;
		}

		private void RemoveObsoleteEntries()
		{
			if (!(Member(config, "OrphanedEntries") is IDictionary dictionary))
			{
				return;
			}
			List<object> list = new List<object>();
			foreach (DictionaryEntry item in dictionary)
			{
				object key = item.Key;
				ConfigDefinition key2 = (ConfigDefinition)((key is ConfigDefinition) ? key : null);
				if (key2 != null && (entries.Keys.Any((Row row) => key2.Equals(row.Definition(zh: false)) || key2.Equals(row.Definition(zh: true)) || key2.Equals(new ConfigDefinition(row.LegacySection, row.LegacyKey))) || (key2.Section == "Interface" && (key2.Key == "MenuKey" || key2.Key == "ShowHealMessage"))))
				{
					list.Add(item.Key);
				}
			}
			foreach (object item2 in list)
			{
				dictionary.Remove(item2);
			}
		}

		public void ConsumeLanguageDraft(IDictionary pending, IDictionary originals)
		{
			if (pending == null || !pending.Contains(Language))
			{
				return;
			}
			string text = pending[Language] as string;
			if (text != "Auto" && text != "English" && text != "简体中文")
			{
				return;
			}
			pending.Remove(Language);
			try
			{
				Language.Value = text;
				if (originals != null)
				{
					originals[Language] = Language.Value;
				}
			}
			catch
			{
				pending[Language] = text;
				throw;
			}
		}

		public string TranslateLabel(string value)
		{
			foreach (Row key in entries.Keys)
			{
				if (value == key.EnSection || value == key.ZhSection)
				{
					return Chinese ? key.ZhSection : key.EnSection;
				}
				if (value == key.EnKey || value == key.ZhKey)
				{
					return Chinese ? key.ZhKey : key.EnKey;
				}
				if (value == key.EnDescription || value == key.ZhDescription)
				{
					return key.Description(Chinese);
				}
			}
			return value;
		}

		private bool ResolveLanguage()
		{
			if (Language != null)
			{
				if (!(Language.Value == "简体中文"))
				{
					if (Language.Value == "Auto")
					{
						return gameIsChinese();
					}
					return false;
				}
				return true;
			}
			return false;
		}

		private void LanguageChanged(object sender, EventArgs args)
		{
			Apply(notify: true);
		}

		public void Tick()
		{
			if (ResolveLanguage() != Chinese)
			{
				Apply(notify: true);
			}
		}

		private void Apply(bool notify)
		{
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Expected O, but got Unknown
			Chinese = ResolveLanguage();
			try
			{
				IDictionary dictionary = (Member(config, "Entries") as IDictionary) ?? throw new MissingFieldException("ConfigFile.Entries");
				foreach (KeyValuePair<Row, ConfigEntryBase> entry in entries)
				{
					ConfigEntryBase value = entry.Value;
					dictionary.Remove(value.Definition);
					SetBacking(value, "Definition", entry.Key.Definition(Chinese));
					SetBacking(value, "Description", (object)new ConfigDescription(entry.Key.Description(Chinese), value.Description.AcceptableValues, value.Description.Tags));
					dictionary.Add(value.Definition, value);
				}
				RemoveObsoleteEntries();
				config.Save();
				if (notify)
				{
					this.Changed?.Invoke();
				}
			}
			catch (Exception ex)
			{
				warn("Configuration localization failed: " + ex);
			}
		}

		internal static object Member(object instance, string name)
		{
			Type type = instance.GetType();
			while (type != null)
			{
				FieldInfo fieldInfo = type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) ?? type.GetField("<" + name + ">k__BackingField", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (fieldInfo != null)
				{
					return fieldInfo.GetValue(instance);
				}
				PropertyInfo property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (property != null)
				{
					return property.GetValue(instance);
				}
				type = type.BaseType;
			}
			return null;
		}

		private static void SetBacking(object instance, string name, object value)
		{
			Type type = instance.GetType();
			while (type != null)
			{
				FieldInfo field = type.GetField("<" + name + ">k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic);
				if (field != null)
				{
					field.SetValue(instance, value);
					return;
				}
				type = type.BaseType;
			}
			throw new MissingFieldException(instance.GetType().Name, name);
		}

		public void Dispose()
		{
			Language.SettingChanged -= LanguageChanged;
		}
	}
	[BepInPlugin("com.yanyan.repo.crouchheal", "Crouch Heal 蹲起回血", "1.2.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string Id = "com.yanyan.repo.crouchheal";

		public const string Version = "1.2.0";

		internal static Plugin Instance;

		internal static ManualLogSource Log;

		private LocalizedConfig settings;

		private readonly CrouchCycle cycle = new CrouchCycle();

		private Harmony harmony;

		private PlayerController tracked;

		private PlayerAvatar trackedAvatar;

		private int scene = -1;

		private object room;

		private float nextError;

		private string lastBlocker;

		private float nextBlockerLog;

		private void Awake()
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Expected O, but got Unknown
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			settings = new LocalizedConfig(((BaseUnityPlugin)this).Config, GameIsChinese, delegate(string message)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)message);
			});
			settings.Enabled.SettingChanged += ResetCycle;
			harmony = new Harmony("com.yanyan.repo.crouchheal");
			harmony.PatchAll(typeof(ControllerPatch));
			RepoConfigBridge.Initialize(settings, harmony);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Crouch Heal 1.2.0 loaded. Local player only; no custom UI, hotkeys or healing messages.");
		}

		private static bool GameIsChinese()
		{
			try
			{
				return (SemiFunc.LocaleGetCode() ?? "en").StartsWith("zh", StringComparison.OrdinalIgnoreCase);
			}
			catch
			{
				return false;
			}
		}

		private void ResetCycle(object sender, EventArgs e)
		{
			cycle.Reset();
		}

		private void Update()
		{
			RepoConfigBridge.Tick();
			settings.Tick();
			if (!Valid(PlayerController.instance))
			{
				cycle.Reset();
			}
		}

		private bool Valid(PlayerController pc)
		{
			return Blocker(pc) == null;
		}

		private string Blocker(PlayerController pc)
		{
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Invalid comparison between Unknown and I4
			if (!((Behaviour)this).isActiveAndEnabled || !settings.Enabled.Value)
			{
				return "mod disabled";
			}
			if (!Application.isFocused)
			{
				return "game not focused";
			}
			if (!Object.op_Implicit((Object)(object)pc) || !((Behaviour)pc).isActiveAndEnabled)
			{
				return "no active player controller";
			}
			PlayerAvatar playerAvatarScript = pc.playerAvatarScript;
			if (!Object.op_Implicit((Object)(object)playerAvatarScript))
			{
				return "no player avatar";
			}
			if (!playerAvatarScript.isLocal)
			{
				return "avatar is not local";
			}
			if (!playerAvatarScript.spawned)
			{
				return "avatar not spawned";
			}
			if (playerAvatarScript.isDisabled || playerAvatarScript.deadSet)
			{
				return "player dead or disabled";
			}
			if (playerAvatarScript.isTumbling)
			{
				return "tumbling";
			}
			PlayerHealth playerHealth = playerAvatarScript.playerHealth;
			if (!Object.op_Implicit((Object)(object)playerHealth) || !((Behaviour)playerHealth).isActiveAndEnabled || playerHealth.isMenuAvatar)
			{
				return "no player health";
			}
			if (playerHealth.health <= 0)
			{
				return "health is zero";
			}
			if (SemiFunc.IsMultiplayer() && (!Object.op_Implicit((Object)(object)playerAvatarScript.photonView) || !playerAvatarScript.photonView.IsMine || !Object.op_Implicit((Object)(object)playerHealth.photonView) || !playerHealth.photonView.IsMine))
			{
				return "not the owner of this avatar";
			}
			if (SemiFunc.MenuLevel())
			{
				return "in a menu level";
			}
			if (!SemiFunc.NoTextInputsActive())
			{
				return "text input active";
			}
			if (Time.timeScale <= 0f)
			{
				return "game paused";
			}
			if (!Object.op_Implicit((Object)(object)LevelGenerator.Instance) || !LevelGenerator.Instance.Generated)
			{
				return "level not generated";
			}
			if (Object.op_Implicit((Object)(object)MenuManager.instance) && Object.op_Implicit((Object)(object)MenuManager.instance.currentMenuPage))
			{
				return "menu open";
			}
			if (!Object.op_Implicit((Object)(object)GameDirector.instance))
			{
				return "no game director";
			}
			if ((int)GameDirector.instance.currentState != 2)
			{
				return "game state is " + ((object)Unsafe.As<gameState, gameState>(ref GameDirector.instance.currentState)/*cast due to .constrained prefix*/).ToString();
			}
			if (GameDirector.instance.DisableInput)
			{
				return "input disabled by game";
			}
			if (pc.InputDisableTimer > 0f)
			{
				return "controls temporarily disabled";
			}
			return null;
		}

		internal void BeforePhysics(PlayerController pc)
		{
			if (!Valid(pc))
			{
				cycle.Reset();
			}
		}

		private void LogBlocked(PlayerController pc, string reason)
		{
			if (reason != null && pc.Crouching && (!(reason == lastBlocker) || !(Time.unscaledTime < nextBlockerLog)))
			{
				lastBlocker = reason;
				nextBlockerLog = Time.unscaledTime + 30f;
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Crouch heal waiting: " + reason));
			}
		}

		internal void Sample(PlayerController pc)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Scene activeScene = SceneManager.GetActiveScene();
				int num = SceneHandle.op_Implicit(((Scene)(ref activeScene)).handle);
				Room currentRoom = PhotonNetwork.CurrentRoom;
				if ((Object)(object)tracked != (Object)(object)pc || (Object)(object)trackedAvatar != (Object)(object)pc.playerAvatarScript || scene != num || room != currentRoom)
				{
					cycle.Reset();
					tracked = pc;
					trackedAvatar = pc.playerAvatarScript;
					scene = num;
					room = currentRoom;
				}
				string text = Blocker(pc);
				LogBlocked(pc, text);
				if (cycle.Sample(text == null, pc.Crouching))
				{
					PlayerHealth playerHealth = pc.playerAvatarScript.playerHealth;
					int num2 = CrouchCycle.Amount(settings.HealAmount.Value, playerHealth.health, playerHealth.maxHealth);
					if (num2 > 0)
					{
						playerHealth.Heal(num2, true);
					}
				}
			}
			catch (Exception ex)
			{
				cycle.Reset();
				if (!(Time.unscaledTime < nextError))
				{
					nextError = Time.unscaledTime + 10f;
					((BaseUnityPlugin)this).Logger.LogWarning((object)("Crouch heal skipped: " + ex));
				}
			}
		}

		private void OnDisable()
		{
			cycle.Reset();
		}

		private void OnDestroy()
		{
			Harmony obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			RepoConfigBridge.Shutdown();
			if (settings != null)
			{
				settings.Enabled.SettingChanged -= ResetCycle;
				settings.Dispose();
			}
			if ((Object)(object)Instance == (Object)(object)this)
			{
				Instance = null;
			}
		}
	}
	[HarmonyPatch(typeof(PlayerController), "FixedUpdate")]
	internal static class ControllerPatch
	{
		[HarmonyPrefix]
		private static void Prefix(PlayerController __instance)
		{
			if ((Object)(object)__instance == (Object)(object)PlayerController.instance && Object.op_Implicit((Object)(object)Plugin.Instance))
			{
				Plugin.Instance.BeforePhysics(__instance);
			}
		}

		[HarmonyPostfix]
		private static void Postfix(PlayerController __instance)
		{
			if ((Object)(object)__instance == (Object)(object)PlayerController.instance && Object.op_Implicit((Object)(object)Plugin.Instance))
			{
				Plugin.Instance.Sample(__instance);
			}
		}
	}
	internal static class RepoConfigBridge
	{
		private static LocalizedConfig settings;

		private static FieldInfo pendingField;

		private static FieldInfo originalField;

		private static Component currentPage;

		private static bool relabel;

		private static bool warned;

		public static void Initialize(LocalizedConfig value, Harmony harmony)
		{
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Expected O, but got Unknown
			settings = value;
			settings.Changed += LanguageChanged;
			Type type = AccessTools.TypeByName("REPOConfig.ConfigMenu");
			if (type == null)
			{
				return;
			}
			try
			{
				pendingField = AccessTools.Field(type, "changedEntryValues");
				originalField = AccessTools.Field(type, "originalEntryValues");
				MethodInfo methodInfo = AccessTools.GetDeclaredMethods(type).Single((MethodInfo m) => m.Name == "CreateModEntries" && m.GetParameters().Length == 2);
				if (pendingField == null || originalField == null)
				{
					throw new MissingFieldException("REPOConfig configuration dictionaries");
				}
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(RepoConfigBridge), "PageCreated", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			catch (Exception e)
			{
				Warn(e);
			}
		}

		private static void PageCreated(object __0, ConfigEntryBase[] __1)
		{
			if (settings != null && __1.Any((ConfigEntryBase entry) => (object)entry == settings.Language) && !__1.Any((ConfigEntryBase entry) => entry.ConfigFile != ((ConfigEntryBase)settings.Language).ConfigFile))
			{
				currentPage = (Component)((__0 is Component) ? __0 : null);
				relabel = true;
			}
		}

		private static void LanguageChanged()
		{
			relabel = true;
		}

		public static void Tick()
		{
			if (settings == null)
			{
				return;
			}
			try
			{
				settings.ConsumeLanguageDraft(pendingField?.GetValue(null) as IDictionary, originalField?.GetValue(null) as IDictionary);
				if (relabel && Object.op_Implicit((Object)(object)currentPage))
				{
					relabel = false;
					RelabelCurrentPage();
				}
			}
			catch (Exception e)
			{
				Warn(e);
			}
		}

		private static void RelabelCurrentPage()
		{
			TMP_Text[] componentsInChildren = currentPage.GetComponentsInChildren<TMP_Text>(true);
			foreach (TMP_Text val in componentsInChildren)
			{
				val.text = settings.TranslateLabel(val.text);
			}
		}

		private static void Warn(Exception e)
		{
			if (!warned)
			{
				warned = true;
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("REPOConfig live-label adapter unavailable: " + e.Message));
				}
			}
		}

		public static void Shutdown()
		{
			if (settings != null)
			{
				settings.Changed -= LanguageChanged;
			}
			settings = null;
			currentPage = null;
			pendingField = (originalField = null);
			relabel = false;
			warned = false;
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}