Decompiled source of CustomWeapons v1.0.0

CustomWeapons.dll

Decompiled 6 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Logging;
using HarmonyLib;
using Mirror;
using MoveClasses;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("CustomWeapons")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CustomWeapons")]
[assembly: AssemblyCopyright("Copyright ©  2024")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("20407d30-12f9-423a-91fa-208389dec286")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
[BepInPlugin("com.yourname.tridentmod", "Trident Mod", "1.5.0")]
public class TridentMod : BaseUnityPlugin
{
	private static ManualLogSource Logger;

	private AssetBundle weaponBundle;

	private string weaponBundlePath;

	public static Dictionary<int, GameObject> customWeapons = new Dictionary<int, GameObject>();

	public static Dictionary<int, Texture2D> customWeaponImages = new Dictionary<int, Texture2D>();

	public static Dictionary<int, string> customWeaponNames = new Dictionary<int, string>();

	public static Dictionary<int, EquipmentTypeItem> customWeaponOptions = new Dictionary<int, EquipmentTypeItem>();

	private readonly List<string> addedJsonFiles = new List<string>();

	private readonly string playerCharacterName = "PlayerCharacter";

	private readonly string playerCharacterMultiplayerName = "PlayerCharacterMultiplayer";

	private void Awake()
	{
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Expected O, but got Unknown
		Logger = ((BaseUnityPlugin)this).Logger;
		((Object)Chainloader.ManagerObject).hideFlags = (HideFlags)61;
		weaponBundlePath = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "weapons.weapon");
		LoadWeaponsBundle();
		Harmony val = new Harmony("com.yourname.tridentmod");
		val.PatchAll();
	}

	private void Start()
	{
		FindPlayerCharacterPrefabs();
		CopyMoveSetsToSaveFolder();
		((MonoBehaviour)this).StartCoroutine(MonitorSpawnPrefabs());
		((MonoBehaviour)this).StartCoroutine(UpdateInputsPanel());
	}

	private void LoadWeaponsBundle()
	{
		if (File.Exists(weaponBundlePath))
		{
			weaponBundle = AssetBundle.LoadFromFile(weaponBundlePath);
			if ((Object)(object)weaponBundle != (Object)null)
			{
				Logger.LogInfo((object)"Weapon bundle loaded successfully.");
				LoadCustomWeapons();
			}
			else
			{
				Logger.LogError((object)"Failed to load weapon bundle.");
			}
		}
		else
		{
			Logger.LogError((object)("Weapon bundle not found at path: " + weaponBundlePath));
		}
	}

	private void LoadCustomWeapons()
	{
		string[] allAssetNames = weaponBundle.GetAllAssetNames();
		string[] array = allAssetNames;
		foreach (string text in array)
		{
			if (!text.StartsWith("assets/weapon/"))
			{
				continue;
			}
			string[] array2 = text.Split(new char[1] { '/' });
			if (array2.Length < 4)
			{
				continue;
			}
			string text2 = array2[2];
			string[] array3 = text2.Split(new char[1] { '-' });
			if (array3.Length == 2 && int.TryParse(array3[1], out var result))
			{
				string text3 = array3[0];
				GameObject val = weaponBundle.LoadAsset<GameObject>($"{result}");
				Texture2D val2 = weaponBundle.LoadAsset<Texture2D>(text3 + ".png");
				if ((Object)(object)val != (Object)null)
				{
					customWeapons[result] = val;
					customWeaponNames[result] = text3;
					Logger.LogInfo((object)$"Loaded weapon prefab: {text3} ({result})");
					LoadEquipmentOptionsFromBundle(result, text2);
					NetworkClient.RegisterPrefab(val);
					Logger.LogInfo((object)("Registered prefab for networking: " + text3));
				}
				else
				{
					Logger.LogWarning((object)$"Failed to load weapon prefab for {text3} ({result})");
				}
				if ((Object)(object)val2 != (Object)null)
				{
					customWeaponImages[result] = val2;
					Logger.LogInfo((object)("Loaded weapon image: " + text3 + ".png"));
				}
				else
				{
					Logger.LogWarning((object)("Failed to load weapon image for " + text3));
				}
			}
		}
	}

	private void LoadEquipmentOptionsFromBundle(int prefabID, string folderName)
	{
		string text = $"assets/weapon/{folderName}/equipmentOptions-{prefabID}.json";
		TextAsset val = weaponBundle.LoadAsset<TextAsset>(text);
		if ((Object)(object)val != (Object)null)
		{
			string text2 = val.text;
			EquipmentTypeItem val2 = JsonConvert.DeserializeObject<EquipmentTypeItem>(text2);
			if (val2 != null)
			{
				customWeaponOptions[prefabID] = val2;
				Logger.LogInfo((object)("Loaded equipment options for " + folderName + ": " + text2));
			}
			else
			{
				Logger.LogWarning((object)("Failed to deserialize equipment options for " + folderName));
			}
		}
		else
		{
			Logger.LogWarning((object)("No equipment options asset found in bundle for " + folderName + " (expected at: " + text + ")"));
		}
	}

	private void CopyMoveSetsToSaveFolder()
	{
		string moveSetsSaveFolder = GetMoveSetsSaveFolder();
		Directory.CreateDirectory(moveSetsSaveFolder);
		string[] allAssetNames = weaponBundle.GetAllAssetNames();
		string[] array = allAssetNames;
		foreach (string text in array)
		{
			if (text.StartsWith("assets/weapon/movesets/") && text.EndsWith(".json"))
			{
				TextAsset val = weaponBundle.LoadAsset<TextAsset>(text);
				if ((Object)(object)val != (Object)null)
				{
					string fileName = Path.GetFileName(text);
					string text2 = Path.Combine(moveSetsSaveFolder, fileName);
					File.WriteAllText(text2, val.text);
					addedJsonFiles.Add(text2);
					Logger.LogInfo((object)("Copied moveset JSON to: " + text2));
				}
				else
				{
					Logger.LogWarning((object)("Failed to load moveset JSON asset: " + text));
				}
			}
		}
	}

	private string GetMoveSetsSaveFolder()
	{
		MethodInfo methodInfo = Type.GetType("Utils.SettingsHelper, Assembly-CSharp")?.GetMethod("GetMoveSetsSaveFolder", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
		if (methodInfo != null)
		{
			return (string)methodInfo.Invoke(null, null);
		}
		Logger.LogError((object)"Failed to call GetMoveSetsSaveFolder() via reflection.");
		return Application.persistentDataPath;
	}

	private void FindPlayerCharacterPrefabs()
	{
		//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)
		GameObject[] array = Resources.FindObjectsOfTypeAll<GameObject>();
		GameObject[] array2 = array;
		foreach (GameObject val in array2)
		{
			if (((Object)val).name == playerCharacterName || ((Object)val).name == playerCharacterMultiplayerName)
			{
				Scene scene = val.scene;
				if (!((Scene)(ref scene)).IsValid())
				{
					Logger.LogInfo((object)("Found " + ((Object)val).name + " prefab in memory."));
					AddCustomWeaponsToPlayerPrefab(val);
				}
			}
		}
		GameObject[] array3 = Object.FindObjectsOfType<GameObject>();
		GameObject[] array4 = array3;
		foreach (GameObject val2 in array4)
		{
			if (((Object)val2).name.StartsWith(playerCharacterName) || ((Object)val2).name.StartsWith(playerCharacterMultiplayerName))
			{
				AddCustomWeaponsToPlayerPrefab(val2);
			}
		}
	}

	private void AddCustomWeaponsToPlayerPrefab(GameObject playerCharacter)
	{
		PlayerHealth component = playerCharacter.GetComponent<PlayerHealth>();
		if ((Object)(object)component != (Object)null)
		{
			if (component.equipmentList != null)
			{
				foreach (GameObject value in customWeapons.Values)
				{
					if (!component.equipmentList.Contains(value))
					{
						component.equipmentList.Add(value);
						Logger.LogInfo((object)("Added custom weapon prefab " + ((Object)value).name + " to equipment list."));
					}
				}
				return;
			}
			Logger.LogWarning((object)"Equipment list is null.");
		}
		else
		{
			Logger.LogError((object)"PlayerHealth component not found on the GameObject.");
		}
	}

	private IEnumerator MonitorSpawnPrefabs()
	{
		while (true)
		{
			List<GameObject> spawnPrefabs = NetworkManager.singleton.spawnPrefabs;
			foreach (GameObject weaponPrefab in customWeapons.Values)
			{
				if (!spawnPrefabs.Contains(weaponPrefab))
				{
					spawnPrefabs.Add(weaponPrefab);
					Logger.LogInfo((object)("Re-added missing prefab to NetworkManager.spawnPrefabs: " + ((Object)weaponPrefab).name));
				}
			}
			yield return (object)new WaitForSeconds(1f);
		}
	}

	private IEnumerator UpdateInputsPanel()
	{
		while (true)
		{
			GameObject inputsPanel = GameObject.Find("InputsPanel");
			if ((Object)(object)inputsPanel != (Object)null)
			{
				Transform editorPanel = inputsPanel.transform.Find("EquipmentEditorPanel(Clone)");
				if ((Object)(object)editorPanel != (Object)null)
				{
					Transform slotPanel = ((Component)editorPanel).transform.Find("EquipmentSlotPanel");
					if ((Object)(object)slotPanel != (Object)null)
					{
						foreach (Transform item in slotPanel)
						{
							Transform child = item;
							Transform textTransform = child.Find("Text");
							if (!((Object)(object)textTransform != (Object)null))
							{
								continue;
							}
							Text textComponent = ((Component)textTransform).GetComponent<Text>();
							if (!((Object)(object)textComponent != (Object)null) || !int.TryParse(textComponent.text, out var weaponId) || !customWeaponNames.ContainsKey(weaponId))
							{
								continue;
							}
							textComponent.text = customWeaponNames[weaponId];
							Logger.LogInfo((object)$"Updated button text for weapon ID {weaponId} to {customWeaponNames[weaponId]}.");
							Transform rawImageTransform = child.Find("RawImage");
							if ((Object)(object)rawImageTransform != (Object)null)
							{
								RawImage rawImageComponent = ((Component)rawImageTransform).GetComponent<RawImage>();
								if ((Object)(object)rawImageComponent != (Object)null && customWeaponImages.ContainsKey(weaponId))
								{
									rawImageComponent.texture = (Texture)(object)customWeaponImages[weaponId];
									((Component)rawImageTransform).gameObject.SetActive(true);
									Logger.LogInfo((object)$"Updated RawImage for weapon ID {weaponId}.");
								}
							}
						}
					}
				}
			}
			yield return (object)new WaitForSeconds(0.1f);
		}
	}

	public static Texture2D GetWeaponImage(int prefabID)
	{
		return customWeaponImages.ContainsKey(prefabID) ? customWeaponImages[prefabID] : null;
	}

	public static string GetWeaponName(int prefabID)
	{
		return customWeaponNames.ContainsKey(prefabID) ? customWeaponNames[prefabID] : prefabID.ToString();
	}

	private void OnApplicationQuit()
	{
		foreach (string addedJsonFile in addedJsonFiles)
		{
			if (File.Exists(addedJsonFile))
			{
				File.Delete(addedJsonFile);
				Logger.LogInfo((object)("Deleted JSON file: " + addedJsonFile));
			}
		}
	}
}
[HarmonyPatch(typeof(EquipmentTypeItem), "GetEquipmentTypeItems")]
public static class TridentMod_EquipmentTypeItemPatch
{
	private static void Postfix(ref List<EquipmentTypeItem> __result)
	{
		//IL_0061: Unknown result type (might be due to invalid IL or missing references)
		//IL_0066: 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_0085: Unknown result type (might be due to invalid IL or missing references)
		//IL_0097: Expected O, but got Unknown
		foreach (KeyValuePair<int, GameObject> weapon in TridentMod.customWeapons)
		{
			if (TridentMod.customWeaponOptions.TryGetValue(weapon.Key, out var value) && !__result.Exists((EquipmentTypeItem item) => (int)item.equipmentType == weapon.Key))
			{
				__result.Add(new EquipmentTypeItem
				{
					equipmentType = (EquipmentType)weapon.Key,
					equipmentPositions = value.equipmentPositions,
					equipmentPoints = value.equipmentPoints
				});
			}
		}
	}
}
[HarmonyPatch(typeof(EquipmentPanel), "createButtonForEquipment")]
public static class EquipmentPanelCreateButtonPatch
{
	private static void Postfix(EquipmentTypeItem item, Button __result)
	{
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Expected I4, but got Unknown
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Expected I4, but got Unknown
		//IL_0087: Unknown result type (might be due to invalid IL or missing references)
		//IL_0091: Expected I4, but got Unknown
		if (item == null || !TridentMod.customWeapons.ContainsKey((int)item.equipmentType))
		{
			return;
		}
		Transform obj = ((Component)__result).transform.Find("Text");
		Text val = ((obj != null) ? ((Component)obj).GetComponent<Text>() : null);
		if ((Object)(object)val != (Object)null)
		{
			val.text = TridentMod.GetWeaponName((int)item.equipmentType);
		}
		Transform obj2 = ((Component)__result).transform.Find("RawImage");
		RawImage val2 = ((obj2 != null) ? ((Component)obj2).GetComponent<RawImage>() : null);
		if ((Object)(object)val2 != (Object)null)
		{
			Texture2D weaponImage = TridentMod.GetWeaponImage((int)item.equipmentType);
			if ((Object)(object)weaponImage != (Object)null)
			{
				val2.texture = (Texture)(object)weaponImage;
				((Component)val2).gameObject.SetActive(true);
				((Component)val).gameObject.SetActive(true);
			}
		}
	}
}