Decompiled source of HereComesTheVein v0.1.13

plugins\HereComesTheVein\HereComesTheVein.dll

Decompiled 2 months 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 BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[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: AssemblyVersion("0.0.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 HereComesTheVein
{
	[BepInPlugin("com.r4v9n1.herecomesthevein", "HereComesTheVein", "0.1.13")]
	public sealed class HereComesTheVeinPlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "com.r4v9n1.herecomesthevein";

		public const string PluginName = "HereComesTheVein";

		public const string PluginVersion = "0.1.13";

		private const string ElderActivatedRpc = "HereComesTheVein_ElderActivated";

		private static bool _elderRpcRegistered;

		internal const int IronOreSharePercent = 20;

		internal static ManualLogSource ModLog;

		private static GameObject _ironOrePrefab;

		private static Texture2D _ironTexture;

		private static bool _warnedMissingIronOre;

		private Harmony _harmony;

		private void Awake()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			ModLog = ((BaseUnityPlugin)this).Logger;
			_harmony = new Harmony("com.r4v9n1.herecomesthevein");
			_harmony.PatchAll(typeof(HereComesTheVeinPlugin).Assembly);
			((BaseUnityPlugin)this).Logger.LogInfo((object)("HereComesTheVein 0.1.13 loaded. Copper veins now have a 20% chance to drop IronOre alongside normal CopperOre; runtime=" + (Application.isBatchMode ? "dedicated-server" : "client") + "."));
		}

		private void Update()
		{
			if (!_elderRpcRegistered && ZRoutedRpc.instance != null)
			{
				ZRoutedRpc.instance.Register("HereComesTheVein_ElderActivated", (Action<long>)OnElderActivatedRpc);
				_elderRpcRegistered = true;
			}
		}

		private static void OnElderActivatedRpc(long sender)
		{
			if (!((Object)(object)ZNet.instance != (Object)null) || ZNet.instance.IsServer())
			{
				ZoneSystem instance = ZoneSystem.instance;
				if (instance != null)
				{
					instance.SetGlobalKey("defeated_gd_king");
				}
				ManualLogSource modLog = ModLog;
				if (modLog != null)
				{
					modLog.LogInfo((object)"Received Elder activation from a client; IronOre drops are unlocked world-wide.");
				}
			}
		}

		private void OnDestroy()
		{
			if (_harmony != null)
			{
				_harmony.UnpatchSelf();
			}
		}

		internal static void TryConvertCopperVein(GameObject instance)
		{
			if (!((Object)(object)instance == (Object)null))
			{
				IsCopperVein(((Object)instance).name);
			}
		}

		private static bool IsCopperVein(string objectName)
		{
			if (string.IsNullOrEmpty(objectName))
			{
				return false;
			}
			return objectName.StartsWith("rock4_copper", StringComparison.OrdinalIgnoreCase);
		}

		private static bool IsIronVeinPosition(Vector3 position)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			int num = Mathf.RoundToInt(position.x);
			int num2 = Mathf.RoundToInt(position.z);
			int num3 = (((-2128831035 ^ num) * 16777619) ^ num2) * 16777619;
			int num4 = (num3 ^ (num3 >>> 16)) * 2146121005;
			_ = (num4 ^ (num4 >>> 15)) * -2073254261;
			return true;
		}

		private static void ApplyHoverName(GameObject instance)
		{
			Type type = AccessTools.TypeByName("HoverText");
			if (type == null)
			{
				return;
			}
			Component component = instance.GetComponent(type);
			if (!((Object)(object)component == (Object)null))
			{
				FieldInfo fieldInfo = AccessTools.Field(type, "m_text");
				if (fieldInfo != null)
				{
					fieldInfo.SetValue(component, "Iron Vein");
				}
			}
		}

		private static void ReplaceCopperDrops(GameObject instance)
		{
			GameObject val = ResolveItemPrefab("IronOre") ?? ResolveItemPrefab("IronScrap");
			if ((Object)(object)val == (Object)null)
			{
				if (!_warnedMissingIronOre)
				{
					_warnedMissingIronOre = true;
					ManualLogSource modLog = ModLog;
					if (modLog != null)
					{
						modLog.LogWarning((object)"Could not resolve IronOre or IronScrap from ObjectDB/ZNetScene. The vein will be recolored but drops were left unchanged.");
					}
				}
			}
			else
			{
				ReplaceCopperEntriesOnComponent(instance, "MineRock5", val);
				ReplaceCopperEntriesOnComponent(instance, "MineRock", val);
			}
		}

		private static void ReplaceCopperEntriesOnComponent(GameObject instance, string componentTypeName, GameObject ironOre)
		{
			Type type = AccessTools.TypeByName(componentTypeName);
			if (type == null)
			{
				return;
			}
			Component component = instance.GetComponent(type);
			if ((Object)(object)component == (Object)null)
			{
				return;
			}
			object obj = AccessTools.Field(type, "m_dropItems")?.GetValue(component);
			if (obj == null || !(AccessTools.Field(obj.GetType(), "m_drops")?.GetValue(obj) is IList list) || list.Cast<object>().Any(delegate(object entry)
			{
				object? obj5 = ((entry == null) ? null : AccessTools.Field(entry.GetType(), "m_item"))?.GetValue(entry);
				return IsIronOre((GameObject)((obj5 is GameObject) ? obj5 : null));
			}))
			{
				return;
			}
			int count = list.Count;
			for (int num = 0; num < count; num++)
			{
				object obj2 = list[num];
				if (obj2 == null)
				{
					continue;
				}
				FieldInfo fieldInfo = AccessTools.Field(obj2.GetType(), "m_item");
				object? obj3 = fieldInfo?.GetValue(obj2);
				if (IsCopperOre((GameObject)((obj3 is GameObject) ? obj3 : null)))
				{
					object obj4 = Activator.CreateInstance(obj2.GetType());
					FieldInfo[] fields = obj2.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					foreach (FieldInfo fieldInfo2 in fields)
					{
						fieldInfo2.SetValue(obj4, fieldInfo2.GetValue(obj2));
					}
					fieldInfo.SetValue(obj4, ironOre);
					FieldInfo fieldInfo3 = AccessTools.Field(obj2.GetType(), "m_weight");
					if (fieldInfo3 != null && fieldInfo3.FieldType == typeof(float))
					{
						float num3 = (float)fieldInfo3.GetValue(obj2);
						fieldInfo3.SetValue(obj4, num3 * (2f / 3f));
					}
					list.Add(obj4);
				}
			}
		}

		private static bool IsCopperOre(GameObject item)
		{
			if ((Object)(object)item == (Object)null)
			{
				return false;
			}
			string text = ((Object)item).name ?? string.Empty;
			if (text.EndsWith("(Clone)", StringComparison.Ordinal))
			{
				text = text.Substring(0, text.Length - "(Clone)".Length);
			}
			return string.Equals(text, "CopperOre", StringComparison.OrdinalIgnoreCase);
		}

		private static bool IsIronOre(GameObject item)
		{
			if ((Object)(object)item == (Object)null)
			{
				return false;
			}
			string text = ((Object)item).name ?? string.Empty;
			if (text.EndsWith("(Clone)", StringComparison.Ordinal))
			{
				text = text.Substring(0, text.Length - "(Clone)".Length);
			}
			return string.Equals(text, "IronOre", StringComparison.OrdinalIgnoreCase);
		}

		private static GameObject ResolveItemPrefab(string prefabName)
		{
			if (string.Equals(prefabName, "IronOre", StringComparison.Ordinal) && (Object)(object)_ironOrePrefab != (Object)null)
			{
				return _ironOrePrefab;
			}
			GameObject val = ResolveFromObjectDb(prefabName) ?? ResolveFromZNetScene(prefabName);
			if ((Object)(object)val != (Object)null && string.Equals(prefabName, "IronOre", StringComparison.Ordinal))
			{
				_ironOrePrefab = val;
			}
			return val;
		}

		private static GameObject ResolveFromObjectDb(string prefabName)
		{
			try
			{
				Type type = AccessTools.TypeByName("ObjectDB");
				if (type == null)
				{
					return null;
				}
				object obj = AccessTools.Property(type, "instance")?.GetValue(null, null) ?? AccessTools.Field(type, "instance")?.GetValue(null);
				if (obj == null)
				{
					return null;
				}
				object? obj2 = AccessTools.Method(type, "GetItemPrefab", new Type[1] { typeof(string) }, (Type[])null)?.Invoke(obj, new object[1] { prefabName });
				return (GameObject)((obj2 is GameObject) ? obj2 : null);
			}
			catch (Exception ex)
			{
				ManualLogSource modLog = ModLog;
				if (modLog != null)
				{
					modLog.LogDebug((object)("ObjectDB lookup failed for " + prefabName + ": " + ex.Message));
				}
				return null;
			}
		}

		private static GameObject ResolveFromZNetScene(string prefabName)
		{
			try
			{
				Type type = AccessTools.TypeByName("ZNetScene");
				if (type == null)
				{
					return null;
				}
				object obj = AccessTools.Property(type, "instance")?.GetValue(null, null) ?? AccessTools.Field(type, "instance")?.GetValue(null);
				if (obj == null)
				{
					return null;
				}
				object? obj2 = AccessTools.Method(type, "GetPrefab", new Type[1] { typeof(string) }, (Type[])null)?.Invoke(obj, new object[1] { prefabName });
				return (GameObject)((obj2 is GameObject) ? obj2 : null);
			}
			catch (Exception ex)
			{
				ManualLogSource modLog = ModLog;
				if (modLog != null)
				{
					modLog.LogDebug((object)("ZNetScene lookup failed for " + prefabName + ": " + ex.Message));
				}
				return null;
			}
		}

		private static void ApplyIronVisual(GameObject instance)
		{
			//IL_00db: 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)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: Unknown result type (might be due to invalid IL or missing references)
			if (Application.isBatchMode)
			{
				return;
			}
			Texture2D ironTexture = GetIronTexture();
			Renderer[] componentsInChildren = instance.GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val in componentsInChildren)
			{
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				Material[] materials = val.materials;
				foreach (Material val2 in materials)
				{
					if ((Object)(object)val2 == (Object)null)
					{
						continue;
					}
					if ((Object)(object)ironTexture != (Object)null)
					{
						if (val2.HasProperty("_MainTex"))
						{
							val2.SetTexture("_MainTex", (Texture)(object)ironTexture);
							val2.SetTextureScale("_MainTex", new Vector2(2f, 2f));
						}
						if (val2.HasProperty("_BaseMap"))
						{
							val2.SetTexture("_BaseMap", (Texture)(object)ironTexture);
							val2.SetTextureScale("_BaseMap", new Vector2(2f, 2f));
						}
					}
					if (val2.HasProperty("_Color"))
					{
						val2.SetColor("_Color", Color.white);
					}
					if (val2.HasProperty("_BaseColor"))
					{
						val2.SetColor("_BaseColor", Color.white);
					}
					if (val2.HasProperty("_Metallic"))
					{
						val2.SetFloat("_Metallic", 0.72f);
					}
					if (val2.HasProperty("_Glossiness"))
					{
						val2.SetFloat("_Glossiness", 0.28f);
					}
					if (val2.HasProperty("_Smoothness"))
					{
						val2.SetFloat("_Smoothness", 0.28f);
					}
					if (val2.HasProperty("_EmissionColor"))
					{
						val2.SetColor("_EmissionColor", new Color(0.02f, 0.025f, 0.03f, 1f));
					}
				}
			}
		}

		private static Texture2D GetIronTexture()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_ironTexture != (Object)null)
			{
				return _ironTexture;
			}
			Texture2D val = new Texture2D(128, 128, (TextureFormat)4, true);
			((Object)val).name = "HereComesTheVein_BlackSilver";
			((Texture)val).wrapMode = (TextureWrapMode)0;
			((Texture)val).filterMode = (FilterMode)1;
			Color val2 = default(Color);
			for (int i = 0; i < 128; i++)
			{
				for (int j = 0; j < 128; j++)
				{
					float num = Mathf.PerlinNoise((float)j * 0.045f, (float)i * 0.045f);
					float num2 = Mathf.PerlinNoise(17.3f + (float)j * 0.13f, 31.7f + (float)i * 0.13f);
					float num3 = Mathf.Abs(Mathf.Sin((float)j * 0.11f + (float)i * 0.065f + num * 4.5f));
					float num4 = ((num > 0.56f && num3 > 0.72f) ? Mathf.Lerp(0.48f, 0.82f, num2) : Mathf.Lerp(0.055f, 0.19f, num * 0.75f + num2 * 0.25f));
					((Color)(ref val2))..ctor(num4 * 0.96f, num4, Mathf.Min(1f, num4 * 1.06f), 1f);
					val.SetPixel(j, i, val2);
				}
			}
			val.Apply(true, false);
			_ironTexture = val;
			return _ironTexture;
		}
	}
	[HarmonyPatch(typeof(Player), "ActivateGuardianPower")]
	internal static class ElderGuardianPowerActivationPatch
	{
		private static void Prefix(Player __instance)
		{
			if (!((Object)(object)__instance == (Object)null) && string.Equals(__instance.GetGuardianPowerName(), "GP_TheElder", StringComparison.OrdinalIgnoreCase) && !(__instance.m_guardianPowerCooldown > 0f))
			{
				if ((Object)(object)ZoneSystem.instance != (Object)null)
				{
					ZoneSystem.instance.SetGlobalKey("defeated_gd_king");
				}
				if (ZRoutedRpc.instance != null && (Object)(object)ZNet.instance != (Object)null && !ZNet.instance.IsServer())
				{
					ZRoutedRpc.instance.InvokeRoutedRPC("HereComesTheVein_ElderActivated", Array.Empty<object>());
				}
			}
		}
	}
	[HarmonyPatch]
	internal static class CopperDropListPatch
	{
		private static IEnumerable<MethodBase> TargetMethods()
		{
			Type type = AccessTools.TypeByName("DropTable");
			if (!(type == null))
			{
				return from method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
					where method.Name == "GetDropList" && typeof(List<GameObject>).IsAssignableFrom(method.ReturnType)
					select method;
			}
			return Enumerable.Empty<MethodBase>();
		}

		[HarmonyPostfix]
		private static void Postfix(List<GameObject> __result)
		{
			if (__result == null || __result.Count == 0)
			{
				return;
			}
			GameObject val = ResolveIronOre();
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			int num = 0;
			for (int i = 0; i < __result.Count; i++)
			{
				GameObject val2 = __result[i];
				if ((Object)(object)val2 != (Object)null && IsCopperOreName(((Object)val2).name) && Random.value < 0.2f)
				{
					__result[i] = val;
					num++;
				}
			}
			if (num > 0)
			{
				ManualLogSource modLog = HereComesTheVeinPlugin.ModLog;
				if (modLog != null)
				{
					modLog.LogDebug((object)("Converted " + num + " CopperOre drop(s) to IronOre at the 20% loot-roll rate."));
				}
			}
		}

		private static bool ElderHasBeenDefeated()
		{
			Type type = AccessTools.TypeByName("ZoneSystem");
			object obj = AccessTools.Property(type, "instance")?.GetValue(null, null);
			if (obj == null)
			{
				return false;
			}
			Type type2 = AccessTools.TypeByName("GlobalKeys");
			if (type2 == null)
			{
				return false;
			}
			object obj2;
			try
			{
				obj2 = Enum.Parse(type2, "defeated_gd_king");
			}
			catch
			{
				return false;
			}
			MethodInfo methodInfo = AccessTools.Method(type, "GetGlobalKey", new Type[1] { type2 }, (Type[])null);
			if (methodInfo != null && (bool)methodInfo.Invoke(obj, new object[1] { obj2 }))
			{
				return true;
			}
			return ElderTrophyIsActivatedOnAltar();
		}

		private static bool ElderTrophyIsActivatedOnAltar()
		{
			Type type = AccessTools.TypeByName("OfferingBowl");
			Type type2 = AccessTools.TypeByName("ItemStand");
			if (type == null || type2 == null)
			{
				return false;
			}
			MethodInfo method = typeof(Object).GetMethod("FindObjectsOfType", BindingFlags.Static | BindingFlags.Public, null, new Type[1] { typeof(Type) }, null);
			MethodInfo methodInfo = AccessTools.Method(type, "FindItemStands", (Type[])null, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(type2, "GetAttachedItem", (Type[])null, (Type[])null);
			if (method == null || methodInfo == null || methodInfo2 == null)
			{
				return false;
			}
			if (!(method.Invoke(null, new object[1] { type }) is Array array))
			{
				return false;
			}
			foreach (object item in array)
			{
				FieldInfo fieldInfo = AccessTools.Field(type, "m_useItemStands");
				if (fieldInfo == null || !(bool)fieldInfo.GetValue(item) || !(methodInfo.Invoke(item, null) is IEnumerable enumerable))
				{
					continue;
				}
				foreach (object item2 in enumerable)
				{
					int num = (int)methodInfo2.Invoke(item2, null);
					if (num != 0)
					{
						GameObject val = ResolveItemPrefab(num);
						if ((Object)(object)val != (Object)null && string.Equals(((Object)val).name, "TrophyTheElder", StringComparison.OrdinalIgnoreCase))
						{
							return true;
						}
					}
				}
			}
			return false;
		}

		private static GameObject ResolveItemPrefab(int hash)
		{
			Type type = AccessTools.TypeByName("ObjectDB");
			object obj = AccessTools.Property(type, "instance")?.GetValue(null, null);
			object? obj2 = AccessTools.Method(type, "GetItemPrefab", new Type[1] { typeof(int) }, (Type[])null)?.Invoke(obj, new object[1] { hash });
			return (GameObject)((obj2 is GameObject) ? obj2 : null);
		}

		private static GameObject ResolveIronOre()
		{
			Type type = AccessTools.TypeByName("ObjectDB");
			object obj = AccessTools.Property(type, "instance")?.GetValue(null, null);
			object? obj2 = AccessTools.Method(type, "GetItemPrefab", new Type[1] { typeof(string) }, (Type[])null)?.Invoke(obj, new object[1] { "IronOre" });
			return (GameObject)((obj2 is GameObject) ? obj2 : null);
		}

		private static bool IsCopperOreName(string itemName)
		{
			return string.Equals(itemName?.Replace("(Clone)", ""), "CopperOre", StringComparison.OrdinalIgnoreCase);
		}
	}
	[HarmonyPatch]
	internal static class ZNetSceneCreateObjectPatch
	{
		private static MethodBase TargetMethod()
		{
			Type type = AccessTools.TypeByName("ZNetScene");
			if (type == null)
			{
				throw new MissingMemberException("ZNetScene type was not found.");
			}
			MethodInfo[] source = (from method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
				where method.Name == "CreateObject" && typeof(GameObject).IsAssignableFrom(method.ReturnType)
				select method).ToArray();
			MethodInfo? obj = source.FirstOrDefault(delegate(MethodInfo method)
			{
				ParameterInfo[] parameters = method.GetParameters();
				return parameters.Length == 1 && string.Equals(parameters[0].ParameterType.Name, "ZDO", StringComparison.Ordinal);
			}) ?? source.FirstOrDefault();
			if (obj == null)
			{
				throw new MissingMethodException("Could not find a ZNetScene.CreateObject method returning GameObject.");
			}
			return obj;
		}

		[HarmonyPostfix]
		private static void Postfix(GameObject __result)
		{
			HereComesTheVeinPlugin.TryConvertCopperVein(__result);
		}
	}
	[HarmonyPatch(typeof(MineRock5), "Awake")]
	internal static class MineRock5ActivationPatch
	{
		private static void Postfix(MineRock5 __instance)
		{
			if ((Object)(object)__instance != (Object)null)
			{
				HereComesTheVeinPlugin.TryConvertCopperVein(((Component)__instance).gameObject);
			}
		}
	}
	[HarmonyPatch(typeof(MineRock5), "Damage")]
	internal static class MineRock5DamagePatch
	{
		private static void Prefix(MineRock5 __instance)
		{
			if ((Object)(object)__instance != (Object)null)
			{
				HereComesTheVeinPlugin.TryConvertCopperVein(((Component)__instance).gameObject);
			}
		}
	}
	[HarmonyPatch(typeof(MineRock), "Damage")]
	internal static class MineRockDamagePatch
	{
		private static void Prefix(MineRock __instance)
		{
			if ((Object)(object)__instance != (Object)null)
			{
				HereComesTheVeinPlugin.TryConvertCopperVein(((Component)__instance).gameObject);
			}
		}
	}
}