Decompiled source of ThisIsValheim v0.1.2

ThisIsValheim.dll

Decompiled 2 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("assembly_utils")]
[assembly: IgnoresAccessChecksTo("assembly_valheim")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("ThisIsValheim")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+e04ed725ff3bf8678203c36bea55678c46ebfa14")]
[assembly: AssemblyProduct("ThisIsValheim")]
[assembly: AssemblyTitle("ThisIsValheim")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.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;
		}
	}
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}
namespace ThisIsValheim
{
	[BepInPlugin("rauschekuh.thisisvalheim", "This Is Valheim!", "0.1.2")]
	public class ThisIsValheimPlugin : BaseUnityPlugin
	{
		private enum Refusal
		{
			None,
			Busy,
			Ward,
			Key
		}

		[HarmonyPatch(typeof(ZNetScene), "Awake")]
		private static class ResolveOnLoad
		{
			private static void Postfix()
			{
				ResolveEffects();
			}
		}

		[HarmonyPatch(typeof(Game), "Start")]
		private static class RegisterRpc
		{
			private static void Postfix()
			{
				ZRoutedRpc instance = ZRoutedRpc.instance;
				if (instance != null && instance != registeredOn)
				{
					registeredOn = instance;
					instance.Register<ZDOID>("ThisIsValheim_Kick", (Action<long, ZDOID>)RPC_Kick);
				}
			}
		}

		[HarmonyPatch(typeof(Attack), "AddHitPoint")]
		private static class NoticeKick
		{
			private static void Postfix(Attack __instance, GameObject go, Vector3 point)
			{
				//IL_0050: Unknown result type (might be due to invalid IL or missing references)
				try
				{
					Player localPlayer = Player.m_localPlayer;
					if (!((Object)(object)go == (Object)null) && !((Object)(object)localPlayer == (Object)null) && !((Object)(object)__instance.m_character != (Object)(object)localPlayer) && IsKick(__instance.m_attackAnimation))
					{
						Door componentInParent = go.GetComponentInParent<Door>();
						if ((Object)(object)componentInParent != (Object)null && TryKick(componentInParent, localPlayer))
						{
							KickNeighbours(componentInParent, localPlayer, point);
						}
					}
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)("[ThisIsValheim] kick check failed: " + ex));
				}
			}
		}

		[HarmonyPatch(typeof(Humanoid), "StartAttack")]
		private static class KickAtDoor
		{
			private static void Prefix(Humanoid __instance, bool secondaryAttack)
			{
				forceUnarmed = false;
				Player val = (Player)(object)((__instance is Player) ? __instance : null);
				if (secondaryAttack && !((Object)(object)val == (Object)null) && !((Object)(object)val != (Object)(object)Player.m_localPlayer) && !((Object)(object)((Humanoid)val).m_unarmedWeapon == (Object)null))
				{
					GameObject hoverObject = ((Humanoid)val).GetHoverObject();
					Door val2 = (((Object)(object)hoverObject != (Object)null) ? hoverObject.GetComponentInParent<Door>() : null);
					forceUnarmed = (Object)(object)val2 != (Object)null && Check(val2, val) != Refusal.Busy;
				}
			}

			private static void Finalizer()
			{
				forceUnarmed = false;
			}
		}

		[HarmonyPatch(typeof(Humanoid), "GetCurrentWeapon")]
		private static class KickWeapon
		{
			private static void Postfix(Humanoid __instance, ref ItemData __result)
			{
				if (forceUnarmed && (Object)(object)__instance == (Object)(object)Player.m_localPlayer && (Object)(object)__instance.m_unarmedWeapon != (Object)null)
				{
					__result = __instance.m_unarmedWeapon.m_itemData;
				}
			}
		}

		[HarmonyPatch(typeof(Door), "GetHoverText")]
		private static class ShowKickHint
		{
			private static void Postfix(Door __instance, ref string __result)
			{
				Player localPlayer = Player.m_localPlayer;
				if (showHint.Value && !string.IsNullOrEmpty(__result) && !((Object)(object)localPlayer == (Object)null) && !((Object)(object)((Humanoid)localPlayer).m_unarmedWeapon == (Object)null) && Check(__instance, localPlayer) == Refusal.None)
				{
					__result += Localization.instance.Localize("\n[<color=yellow><b>$KEY_SecondaryAttack</b></color>] Kick");
				}
			}
		}

		public const string GUID = "rauschekuh.thisisvalheim";

		public const string NAME = "This Is Valheim!";

		public const string VERSION = "0.1.2";

		private const string KickRpc = "ThisIsValheim_Kick";

		private const float SwingWindow = 1.5f;

		private const float KickCooldown = 0.6f;

		private const float SeamReach = 0.6f;

		private const float SoundHeight = 1f;

		private const float EffectLifetime = 6f;

		private const string DefaultEffects = "sfx_battering_ram_impact,sfx_wood_break,vfx_SawDust,fx_hit_camshake";

		private const string KickHint = "\n[<color=yellow><b>$KEY_SecondaryAttack</b></color>] Kick";

		private static ThisIsValheimPlugin instance;

		private static ZRoutedRpc registeredOn;

		private static bool forceUnarmed;

		private static EffectList effects;

		private static readonly Dictionary<Door, Coroutine> swinging = new Dictionary<Door, Coroutine>();

		private static readonly Dictionary<Door, float> kicked = new Dictionary<Door, float>();

		private static ConfigEntry<float> swingSpeed;

		private static ConfigEntry<bool> lockedDoors;

		private static ConfigEntry<bool> showHint;

		private static ConfigEntry<string> effectPrefabs;

		private void Awake()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			instance = this;
			swingSpeed = ((BaseUnityPlugin)this).Config.Bind<float>("Kick", "SwingSpeed", 4f, new ConfigDescription("How many times faster than normal a kicked door swings open.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 10f), Array.Empty<object>()));
			lockedDoors = ((BaseUnityPlugin)this).Config.Bind<bool>("Kick", "LockedDoors", false, "Whether a door that wants a key can be kicked open without it. Off keeps the crypts shut until you have found the key, the way the game intends - carry the key and the kick opens the door with it.");
			showHint = ((BaseUnityPlugin)this).Config.Bind<bool>("Kick", "ShowHint", true, "Whether a door you could kick open says so when you look at it.");
			effectPrefabs = ((BaseUnityPlugin)this).Config.Bind<string>("Effects", "Prefabs", "sfx_battering_ram_impact,sfx_wood_break,vfx_SawDust,fx_hit_camshake", "The game's own effect prefabs that go off at the door, by name, separated by commas. Drop one to lose that layer, or put fx_GP_Activation in for the sound a Forsaken power makes when you call on it. An empty list makes the kick silent.");
			effectPrefabs.SettingChanged += delegate
			{
				ResolveEffects();
			};
			Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), "rauschekuh.thisisvalheim");
		}

		private static bool IsKick(string animation)
		{
			if (!string.IsNullOrEmpty(animation))
			{
				return animation.IndexOf("kick", StringComparison.OrdinalIgnoreCase) >= 0;
			}
			return false;
		}

		private static Refusal Check(Door door, Player player)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			ZNetView nview = door.m_nview;
			if ((Object)(object)nview == (Object)null || !nview.IsValid() || (Object)(object)door.m_animator == (Object)null || nview.GetZDO().GetInt(ZDOVars.s_state, 0) != 0 || !door.CanInteract())
			{
				return Refusal.Busy;
			}
			if (door.m_checkGuardStone && !PrivateArea.CheckAccess(((Component)door).transform.position, 0f, false, false))
			{
				return Refusal.Ward;
			}
			if (NeedsKey(door) && !door.HaveKey((Humanoid)(object)player, true))
			{
				return Refusal.Key;
			}
			return Refusal.None;
		}

		private static bool NeedsKey(Door door)
		{
			if ((Object)(object)door.m_keyItem != (Object)null)
			{
				return !lockedDoors.Value;
			}
			return false;
		}

		private static void KickNeighbours(Door door, Player player, Vector3 point)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			Collider[] array = Physics.OverlapSphere(point, 0.6f);
			for (int i = 0; i < array.Length; i++)
			{
				Door componentInParent = ((Component)array[i]).GetComponentInParent<Door>();
				if ((Object)(object)componentInParent != (Object)null && (Object)(object)componentInParent != (Object)(object)door)
				{
					TryKick(componentInParent, player);
				}
			}
		}

		private static bool TryKick(Door door, Player player)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			if (Recent(door))
			{
				return false;
			}
			Refusal refusal = Check(door, player);
			if (refusal == Refusal.Busy)
			{
				return false;
			}
			kicked[door] = Time.time;
			Vector3 val = ((Component)player).transform.position - ((Component)door).transform.position;
			Vector3 normalized = ((Vector3)(ref val)).normalized;
			if (refusal != Refusal.None)
			{
				Rebuff(door, player, normalized, refusal);
				return false;
			}
			if (NeedsKey(door))
			{
				string name = door.m_keyItem.m_itemData.m_shared.m_name;
				if (door.m_consumeKey)
				{
					((Humanoid)player).GetInventory().RemoveItem(name, 1, -1, true);
				}
				((Character)player).Message((MessageType)2, Localization.instance.Localize("$msg_door_usingkey", new string[1] { name }), 0, (Sprite)null, false);
			}
			if (ZRoutedRpc.instance != null)
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(0L, "ThisIsValheim_Kick", new object[1] { door.m_nview.GetZDO().m_uid });
			}
			door.Open(normalized);
			if ((Object)(object)Game.instance != (Object)null)
			{
				Game.instance.IncrementPlayerStat((PlayerStatType)74, 1f, false);
			}
			return true;
		}

		private static void Rebuff(Door door, Player player, Vector3 away, Refusal refusal)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: 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)
			door.m_lockedEffects.Create(((Component)door).transform.position, ((Component)door).transform.rotation, (Transform)null, 1f, -1, default(ZDOID));
			((Character)player).Message((MessageType)2, (refusal == Refusal.Key) ? Localization.instance.Localize("$msg_door_needkey", new string[1] { door.m_keyItem.m_itemData.m_shared.m_name }) : Localization.instance.Localize("$piece_noaccess"), 0, (Sprite)null, false);
			((Character)player).Stagger(away);
		}

		private static bool Recent(Door door)
		{
			if (kicked.TryGetValue(door, out var value) && Time.time - value < 0.6f)
			{
				return true;
			}
			if (kicked.Count > 8)
			{
				kicked.Clear();
			}
			return false;
		}

		private static void RPC_Kick(long sender, ZDOID id)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsDedicated())
			{
				return;
			}
			try
			{
				if (!((Object)(object)ZNetScene.instance == (Object)null))
				{
					GameObject val = ZNetScene.instance.FindInstance(id);
					Door val2 = (((Object)(object)val != (Object)null) ? val.GetComponent<Door>() : null);
					if (!((Object)(object)val2 == (Object)null))
					{
						Swing(val2);
						Bang(((Component)val2).transform.position + Vector3.up * 1f);
					}
				}
			}
			catch (Exception ex)
			{
				Debug.LogWarning((object)("[ThisIsValheim] kick effects failed: " + ex));
			}
		}

		private static void Bang(Vector3 pos)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			EffectList val = effects;
			if (val != null)
			{
				bool forceDisableInit = ZNetView.m_forceDisableInit;
				ZNetView.m_forceDisableInit = true;
				GameObject[] spawned;
				try
				{
					spawned = val.Create(pos, Quaternion.identity, (Transform)null, 1f, -1, default(ZDOID));
				}
				finally
				{
					ZNetView.m_forceDisableInit = forceDisableInit;
				}
				Sweep(spawned);
			}
		}

		private static void Sweep(GameObject[] spawned)
		{
			foreach (GameObject val in spawned)
			{
				if ((Object)(object)val != (Object)null && (Object)(object)val.GetComponentInChildren<TimedDestruction>(true) == (Object)null)
				{
					Object.Destroy((Object)(object)val, 6f);
				}
			}
		}

		private static void ResolveEffects()
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Expected O, but got Unknown
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Expected O, but got Unknown
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Expected O, but got Unknown
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Expected O, but got Unknown
			effects = null;
			if ((Object)(object)ZNetScene.instance == (Object)null)
			{
				return;
			}
			List<EffectData> list = new List<EffectData>();
			List<string> list2 = new List<string>();
			string[] array = effectPrefabs.Value.Split(new char[1] { ',' });
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length != 0)
				{
					GameObject prefab = ZNetScene.instance.GetPrefab(text);
					if ((Object)(object)prefab != (Object)null)
					{
						list.Add(new EffectData
						{
							m_prefab = prefab,
							m_enabled = true
						});
					}
					else
					{
						list2.Add(text);
					}
				}
			}
			if (list2.Count > 0)
			{
				Dictionary<string, GameObject> dictionary = new Dictionary<string, GameObject>();
				GameObject[] array2 = Resources.FindObjectsOfTypeAll<GameObject>();
				foreach (GameObject val in array2)
				{
					int num = list2.IndexOf(((Object)val).name);
					if (num < 0)
					{
						continue;
					}
					if ((Object)(object)val.transform.parent != (Object)null)
					{
						Scene scene = val.scene;
						if (!((Scene)(ref scene)).IsValid() && !dictionary.ContainsKey(((Object)val).name))
						{
							dictionary.Add(((Object)val).name, val);
						}
						continue;
					}
					list.Add(new EffectData
					{
						m_prefab = val,
						m_enabled = true
					});
					list2.RemoveAt(num);
					if (list2.Count == 0)
					{
						break;
					}
				}
				for (int num2 = list2.Count - 1; num2 >= 0; num2--)
				{
					if (dictionary.TryGetValue(list2[num2], out var value))
					{
						list.Add(new EffectData
						{
							m_prefab = value,
							m_enabled = true
						});
						list2.RemoveAt(num2);
					}
				}
			}
			foreach (string item in list2)
			{
				Debug.LogWarning((object)("[ThisIsValheim] no effect prefab called " + item));
			}
			if (list.Count > 0)
			{
				effects = new EffectList
				{
					m_effectPrefabs = list.ToArray()
				};
			}
		}

		private static void Swing(Door door)
		{
			if (!((Object)(object)instance == (Object)null) && !((Object)(object)door.m_animator == (Object)null))
			{
				if (swinging.TryGetValue(door, out var value))
				{
					((MonoBehaviour)instance).StopCoroutine(value);
				}
				swinging[door] = ((MonoBehaviour)instance).StartCoroutine(SwingRoutine(door, door.m_animator));
			}
		}

		private static IEnumerator SwingRoutine(Door door, Animator animator)
		{
			animator.speed = Mathf.Max(1f, swingSpeed.Value);
			bool opened = false;
			float until = Time.time + 1.5f;
			while ((Object)(object)animator != (Object)null && Time.time < until)
			{
				int integer = animator.GetInteger("state");
				if (opened && integer == 0)
				{
					break;
				}
				if (integer != 0)
				{
					opened = true;
					AnimatorStateInfo currentAnimatorStateInfo = animator.GetCurrentAnimatorStateInfo(0);
					if (((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsTag("open") && !animator.IsInTransition(0) && ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).normalizedTime >= 1f)
					{
						break;
					}
				}
				yield return null;
			}
			if ((Object)(object)animator != (Object)null)
			{
				animator.speed = 1f;
			}
			swinging.Remove(door);
		}
	}
}