Decompiled source of GetLootForKills v1.2.5

GetLootForKills.dll

Decompiled 5 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using GetLootForKills.Component;
using GetLootForKills.Patches;
using HarmonyLib;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("GetLootForKills")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("GetLootForKills")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("ce02e902-d269-45a5-8803-912b4e01b23b")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace GetLootForKills
{
	[BepInPlugin("GoldenKitten.GetLootForKills", "GetLootForKills", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		private const string modGUID = "GoldenKitten.GetLootForKills";

		private const string modName = "GetLootForKills";

		private const string modVersion = "1.0.0";

		private readonly Harmony harmony = new Harmony("GoldenKitten.GetLootForKills");

		public static Plugin Instance;

		public static ConfigEntry<string> possibleItems;

		public static ManualLogSource logger;

		public static List<EnemyType> enemies;

		public static List<Item> items;

		public static Dictionary<string, List<float>> deathTimes;

		private void Awake()
		{
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Expected O, but got Unknown
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			logger = Logger.CreateLogSource("GoldenKitten.GetLootForKills");
			harmony.PatchAll(typeof(Plugin));
			harmony.PatchAll(typeof(StartOfRoundPatch));
			harmony.PatchAll(typeof(RoundManagerPatch));
			MethodInfo methodInfo = AccessTools.Method(typeof(EnemyAI), "KillEnemyOnOwnerClient", (Type[])null, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(KillPatch), "PatchKillEnemyOnOwnerClient", (Type[])null, (Type[])null);
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			logger.LogInfo((object)"GetLootForKills initiated!");
		}

		public static string RemoveWhitespaces(string source)
		{
			return string.Join("", source.Split((string[]?)null, StringSplitOptions.RemoveEmptyEntries));
		}

		public static string RemoveSpecialCharacters(string source)
		{
			StringBuilder stringBuilder = new StringBuilder();
			foreach (char c in source)
			{
				if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
				{
					stringBuilder.Append(c);
				}
			}
			return stringBuilder.ToString();
		}

		public static string RemoveInvalidCharacters(string source)
		{
			return RemoveWhitespaces(RemoveSpecialCharacters(source));
		}

		public static Item GetItemByName(string name)
		{
			Item itemBy = null;
			items.ForEach(delegate(Item item)
			{
				if (RemoveInvalidCharacters(item.itemName).Equals(name, StringComparison.OrdinalIgnoreCase))
				{
					itemBy = item;
				}
			});
			return itemBy;
		}

		public static List<string> GetMobItems(string mobName)
		{
			foreach (ConfigDefinition key in ((BaseUnityPlugin)Instance).Config.Keys)
			{
				if (RemoveInvalidCharacters(key.Key.ToUpper()).Equals(mobName))
				{
					if (Utility.IsNullOrWhiteSpace(((BaseUnityPlugin)Instance).Config[key].BoxedValue.ToString().ToUpper()))
					{
						logger.LogInfo((object)("Invalid Entries For: " + mobName));
						return new List<string>();
					}
					logger.LogInfo((object)("Found Items: " + mobName));
					return ((BaseUnityPlugin)Instance).Config[key].BoxedValue.ToString().ToUpper().Replace(" ", "")
						.Split(new string[1] { "," }, StringSplitOptions.RemoveEmptyEntries)
						.ToList();
				}
			}
			logger.LogInfo((object)("No Items: " + mobName));
			return new List<string>();
		}
	}
}
namespace GetLootForKills.Patches
{
	internal class KillPatch
	{
		public class ItemToDrop
		{
			public int scrapValue;

			public Item scrapItem;

			public ItemToDrop(Item item, int value)
			{
				scrapValue = value;
				scrapItem = item;
			}
		}

		public static void PatchKillEnemyOnOwnerClient(ref EnemyAI __instance, bool overrideDestroy = false)
		{
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)((Component)__instance).gameObject.GetComponent<DroppedItemEnemy>() == (Object)null) || !((NetworkBehaviour)__instance).IsOwner)
			{
				return;
			}
			if (__instance is HoarderBugAI)
			{
				HoarderBugAI val = (HoarderBugAI)__instance;
				if (val.heldItem != null)
				{
					GrabbableObject itemGrabbableObject = val.heldItem.itemGrabbableObject;
					val.DropItemServerRpc(NetworkObjectReference.op_Implicit(((Component)itemGrabbableObject).GetComponent<NetworkObject>()), ((Component)__instance).transform.position, false);
				}
			}
			string mobName = Plugin.RemoveInvalidCharacters(__instance.enemyType.enemyName.ToUpper());
			Vector3 position = ((Component)__instance).transform.position + Vector3.up * 0.6f;
			List<ItemToDrop> itemsForMob = GetItemsForMob(mobName);
			if (itemsForMob.Any())
			{
				for (int i = 0; i < itemsForMob.Count; i++)
				{
					if ((Object)(object)itemsForMob[i].scrapItem.spawnPrefab != (Object)null)
					{
						DropItem(__instance, position, itemsForMob[i].scrapItem.spawnPrefab, itemsForMob[i].scrapValue);
					}
				}
			}
			((Component)__instance).gameObject.AddComponent<DroppedItemEnemy>();
		}

		private static void DropItem(EnemyAI enemy, Vector3 position, GameObject itemPrefab, int scrapValue)
		{
			//IL_0018: 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)
			PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
			if (((NetworkBehaviour)localPlayerController).IsHost)
			{
				DropItemHost(localPlayerController, position, itemPrefab, scrapValue);
			}
			else if (((NetworkBehaviour)localPlayerController).IsClient && !((NetworkBehaviour)localPlayerController).IsHost)
			{
				DropItemServerRpc(localPlayerController, position, itemPrefab, scrapValue);
			}
		}

		[ServerRpc]
		private static void DropItemServerRpc(PlayerControllerB player, Vector3 position, GameObject itemPrefab, int scrapValue)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			DropItemHost(player, position, itemPrefab, scrapValue);
		}

		private static void DropItemHost(PlayerControllerB player, Vector3 position, GameObject itemPrefab, int scrapValue)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: 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_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				RoundManager instance = RoundManager.Instance;
				Transform spawnedScrapContainer = instance.spawnedScrapContainer;
				position += new Vector3(Random.Range(-0.8f, 0.8f), 0f, Random.Range(-0.8f, 0.8f));
				GameObject val = Object.Instantiate<GameObject>(itemPrefab, position, Quaternion.identity, spawnedScrapContainer);
				GrabbableObject component = val.GetComponent<GrabbableObject>();
				((Component)component).transform.rotation = Quaternion.Euler(component.itemProperties.restingRotation);
				component.fallTime = 0f;
				int num = scrapValue;
				if (instance.scrapValueMultiplier > 1f)
				{
					num = (int)((float)num * instance.scrapValueMultiplier);
				}
				component.itemProperties.isScrap = true;
				component.SetScrapValue(num);
				component.itemProperties.creditsWorth = num;
				instance.totalScrapValueInLevel += (float)num;
				NetworkObject component2 = val.GetComponent<NetworkObject>();
				component2.Spawn(false);
				SyncScrapValuesClientRpc(player, (NetworkObjectReference[])(object)new NetworkObjectReference[1] { NetworkObjectReference.op_Implicit(component2) }, new int[1] { num });
			}
			catch (Exception ex)
			{
				Plugin.logger.LogInfo((object)("Problem Dropping Item: " + ex.StackTrace));
			}
		}

		[ClientRpc]
		private static void SyncScrapValuesClientRpc(PlayerControllerB player, NetworkObjectReference[] spawnedScrap, int[] allScrapValue)
		{
			Plugin.logger.LogInfo((object)$"clientRPC scrap values length: {allScrapValue.Length}");
			int num = 0;
			NetworkObject val = default(NetworkObject);
			for (int i = 0; i < spawnedScrap.Length; i++)
			{
				if (((NetworkObjectReference)(ref spawnedScrap[i])).TryGet(ref val, (NetworkManager)null))
				{
					GrabbableObject component = ((Component)val).GetComponent<GrabbableObject>();
					if ((Object)(object)component != (Object)null)
					{
						if (i >= allScrapValue.Length)
						{
							Plugin.logger.LogError((object)$"spawnedScrap amount exceeded allScrapValue!: {spawnedScrap.Length}");
							break;
						}
						component.SetScrapValue(allScrapValue[i]);
						num += allScrapValue[i];
						if (component.itemProperties.meshVariants.Length != 0)
						{
							((Component)component).gameObject.GetComponent<MeshFilter>().mesh = component.itemProperties.meshVariants[Random.Range(0, component.itemProperties.meshVariants.Length)];
						}
						try
						{
							if (component.itemProperties.materialVariants.Length != 0)
							{
								((Renderer)((Component)component).gameObject.GetComponent<MeshRenderer>()).sharedMaterial = component.itemProperties.materialVariants[Random.Range(0, component.itemProperties.materialVariants.Length)];
							}
						}
						catch (Exception arg)
						{
							Plugin.logger.LogInfo((object)$"Item name: {((Object)((Component)component).gameObject).name}; {arg}");
						}
					}
					else
					{
						Plugin.logger.LogError((object)("Scrap networkobject object did not contain grabbable object!: " + ((Object)((Component)val).gameObject).name));
					}
				}
				else
				{
					Plugin.logger.LogError((object)$"Failed to get networkobject reference for scrap. id: {((NetworkObjectReference)(ref spawnedScrap[i])).NetworkObjectId}");
				}
			}
			RoundManager instance = RoundManager.Instance;
			instance.totalScrapValueInLevel += (float)num;
			Plugin.logger.LogInfo((object)$"Round Manager Total Scrap Value: {RoundManager.Instance.totalScrapValueInLevel}");
		}

		private static List<ItemToDrop> GetItemsForMob(string mobName)
		{
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Expected O, but got Unknown
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Expected O, but got Unknown
			List<ItemToDrop> list = new List<ItemToDrop>();
			List<string> mobItems = Plugin.GetMobItems(mobName);
			if (mobItems.Any() && mobItems != null)
			{
				for (int i = 0; i < mobItems.Count / 6; i++)
				{
					int num = 6 * i;
					if (!Utility.IsNullOrWhiteSpace(mobItems[num]))
					{
						string text = Plugin.RemoveInvalidCharacters(mobItems[num]);
						int result;
						if (text.ToUpper().Equals("NONE"))
						{
							Item val = (Item)ScriptableObject.CreateInstance(typeof(Item));
							((Object)val).name = "NONE";
							val.spawnPrefab = new GameObject("NONE");
							val.minValue = 0;
							val.maxValue = 0;
							val.creditsWorth = 0;
							list.Add(new ItemToDrop(val, 1));
							Plugin.logger.LogInfo((object)"Worthless Item Dropped!");
						}
						else if (int.TryParse(Plugin.RemoveInvalidCharacters(mobItems[num + 1]), out result))
						{
							if (int.TryParse(Plugin.RemoveInvalidCharacters(mobItems[num + 2]), out var result2))
							{
								if (int.TryParse(Plugin.RemoveInvalidCharacters(mobItems[num + 3]), out var result3))
								{
									if (int.TryParse(Plugin.RemoveInvalidCharacters(mobItems[num + 4]), out var result4))
									{
										if (int.TryParse(Plugin.RemoveInvalidCharacters(mobItems[num + 5]), out var result5))
										{
											int num2 = Random.Range(1, 1000);
											if (num2 >= result5)
											{
												continue;
											}
											foreach (Item item in Plugin.items)
											{
												if (text.ToUpper().Equals("RANDOM"))
												{
													int index = Random.Range(0, RoundManager.Instance.currentLevel.spawnableScrap.Count);
													num2 = 0;
													num2 = ((result < result2) ? Random.Range(result, result2 + 1) : result);
													if (num2 <= 0)
													{
														break;
													}
													int num3 = 0;
													num3 = ((result3 < result4) ? Random.Range(result3, result4) : result3);
													for (int j = 0; j < num2; j++)
													{
														if (num3 < 0)
														{
															num3 = 0;
														}
														list.Add(new ItemToDrop(RoundManager.Instance.currentLevel.spawnableScrap[index].spawnableItem, num3));
														Plugin.logger.LogInfo((object)"Spawning random item!");
													}
													break;
												}
												if (!Plugin.RemoveInvalidCharacters(item.itemName.ToUpper()).Equals(Plugin.RemoveInvalidCharacters(text.ToUpper())))
												{
													continue;
												}
												num2 = 0;
												num2 = ((result < result2) ? Random.Range(result, result2) : result);
												if (num2 <= 0)
												{
													break;
												}
												int num4 = 0;
												num4 = ((result3 < result4) ? Random.Range(result3, result4) : result3);
												for (int k = 0; k < num2; k++)
												{
													if (num4 < 0)
													{
														num4 = 0;
													}
													list.Add(new ItemToDrop(item, num4));
												}
												break;
											}
										}
										else
										{
											Plugin.logger.LogInfo((object)"Drop Chance is not a number!");
										}
									}
									else
									{
										Plugin.logger.LogInfo((object)"Max Scrap Value is not a number!");
									}
								}
								else
								{
									Plugin.logger.LogInfo((object)"Min Scrap Value is not a number!");
								}
							}
							else
							{
								Plugin.logger.LogInfo((object)"Max Item Drop is not a number!");
							}
						}
						else
						{
							Plugin.logger.LogInfo((object)"Min Item Drop is not a number!");
						}
					}
					else
					{
						Plugin.logger.LogInfo((object)"The Item Name does not match any existing item names!");
					}
				}
			}
			else
			{
				Plugin.logger.LogInfo((object)"Item name either does not exist or is empty. Backup Item Loaded!");
				int index2 = Random.Range(0, RoundManager.Instance.currentLevel.spawnableScrap.Count);
				list.Add(new ItemToDrop(RoundManager.Instance.currentLevel.spawnableScrap[index2].spawnableItem, Random.Range(30, 100)));
			}
			return list;
		}
	}
	[HarmonyPatch(typeof(RoundManager))]
	internal class RoundManagerPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void PatchStart()
		{
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Expected O, but got Unknown
			Plugin.enemies = (from EnemyType e in Resources.FindObjectsOfTypeAll(typeof(EnemyType))
				where (Object)(object)e != (Object)null
				select e).ToList().Distinct().ToList();
			Plugin.items = (from Item i in Resources.FindObjectsOfTypeAll(typeof(Item))
				where (Object)(object)i != (Object)null
				select i).ToList().Distinct().ToList();
			List<string> list = Plugin.items.ConvertAll((Item i) => Plugin.RemoveInvalidCharacters(i.itemName));
			list.Sort();
			Plugin.possibleItems = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<string>("General", "ItemNames", "Notice The List Please", string.Join("|", list) ?? "");
			foreach (EnemyType enemy in Plugin.enemies)
			{
				string text = Plugin.RemoveInvalidCharacters(enemy.enemyName);
				if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text)))
				{
					ConfigEntry<string> val = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<string>("Mobs", text, "Old phone, 1, 3, 50, 80, 1000, Flask, 1, 1, 200, 400, 100", "The First setting is the item name.The Second setting is the minimum item drop amount.The Third setting is the max item drop amount.The Fourth setting is the minimum scrap value amount.The Fifth setting is the maximum scrap value amount.The Last setting is the chance of it dropping from 1-1000.You can add more items like all config entries do,up to however many you want(each has 2 item drops default).You can also put 'None' so that the mob drops nothing.");
				}
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound))]
	internal class StartOfRoundPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void PatchStart()
		{
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Expected O, but got Unknown
			Plugin.enemies = (from EnemyType e in Resources.FindObjectsOfTypeAll(typeof(EnemyType))
				where (Object)(object)e != (Object)null
				select e).ToList().Distinct().ToList();
			Plugin.items = (from Item i in Resources.FindObjectsOfTypeAll(typeof(Item))
				where (Object)(object)i != (Object)null
				select i).ToList().Distinct().ToList();
			List<string> list = Plugin.items.ConvertAll((Item i) => Plugin.RemoveInvalidCharacters(i.itemName));
			list.Sort();
			Plugin.possibleItems = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<string>("General", "ItemNames", "Notice The List Please", string.Join("|", list) ?? "");
			foreach (EnemyType enemy in Plugin.enemies)
			{
				string text = Plugin.RemoveInvalidCharacters(enemy.enemyName);
				if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text)))
				{
					ConfigEntry<string> val = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<string>("Mobs", text, "Old phone, 1, 3, 50, 80, 1000, Flask, 1, 1, 200, 400, 100", "The First setting is the item name.The Second setting is the minimum item drop amount.The Third setting is the max item drop amount.The Fourth setting is the minimum scrap value amount.The Fifth setting is the maximum scrap value amount.The Last setting is the chance of it dropping from 1-1000.You can add more items like all config entries do,up to however many you want(each has 2 item drops default).You can also put 'None' so that the mob drops nothing.");
				}
			}
		}
	}
	internal class TimeOfDayPatch
	{
		public static void MoveTimeOfDayPatch(ref TimeOfDay __instance)
		{
			if (!DoOntime("6:45 AM", __instance))
			{
			}
		}

		public static bool DoOntime(string timeToDo, TimeOfDay day)
		{
			float num = ClockToTime(timeToDo, day);
			float normalizedTimeOfDay = day.normalizedTimeOfDay;
			if (normalizedTimeOfDay >= num && normalizedTimeOfDay < num + 0.0001f)
			{
				return true;
			}
			return false;
		}

		public static float ClockToTime(string timeString, TimeOfDay day)
		{
			int numberOfHours = day.numberOfHours;
			float lengthOfHours = day.lengthOfHours;
			float totalTime = day.totalTime;
			int num = 24 - numberOfHours;
			string[] array = timeString.Split(new char[1] { ':' });
			int num2 = int.Parse(array[0]);
			int num3 = int.Parse(array[1].Substring(0, 2));
			string text = array[1].Substring(2);
			if (text == "PM")
			{
				num2 += 12;
			}
			else if (text == "AM" && num2 == 12)
			{
				num2 = 0;
			}
			num2 -= num;
			float num4 = (float)num2 * lengthOfHours + (float)num3;
			return num4 / totalTime;
		}
	}
}
namespace GetLootForKills.Component
{
	internal class DroppedItemEnemy : MonoBehaviour
	{
		private void Awake()
		{
			Plugin.logger.LogInfo((object)"Enemy Object Drop Loaded.");
		}
	}
}