Decompiled source of PlayerSort v1.0.1

plugins/PlayerSort.dll

Decompiled a week ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("PlayerSort")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1+10c725ef950396220c49aebb2b3d338eaad35133")]
[assembly: AssemblyProduct("PlayerSort")]
[assembly: AssemblyTitle("PlayerSort")]
[assembly: AssemblyVersion("1.0.1.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 PlayerSort
{
	[BepInPlugin("w00ds.valheim.playersort", "PlayerSort", "1.0.1")]
	public class PlayerSortPlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "w00ds.valheim.playersort";

		public const string PluginName = "PlayerSort";

		public const string PluginVersion = "1.0.1";

		private static readonly MethodInfo InventoryChangedMethod = typeof(Inventory).GetMethod("Changed", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[2]
		{
			typeof(bool),
			typeof(bool)
		}, null);

		private GameObject _sortButtonObject;

		private float _nextUiCheck;

		private void Awake()
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)"PlayerSort 1.0.1 loaded");
		}

		private void Update()
		{
			if (!(Time.unscaledTime < _nextUiCheck))
			{
				_nextUiCheck = Time.unscaledTime + 1f;
				EnsureSortButton();
			}
		}

		private void EnsureSortButton()
		{
			if ((Object)(object)InventoryGui.instance == (Object)null)
			{
				return;
			}
			Transform val = FindDirectChild(((Component)InventoryGui.instance).transform, "root");
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			Transform val2 = FindDirectChild(val, "Player");
			if ((Object)(object)val2 == (Object)null)
			{
				return;
			}
			Transform val3 = FindDirectChild(val2, "Container");
			if ((Object)(object)val3 == (Object)null)
			{
				return;
			}
			Transform val4 = FindDirectChild(val3, "StackAll");
			if ((Object)(object)val4 == (Object)null)
			{
				return;
			}
			Transform val5 = FindRecursive(val2, "PlayerGrid");
			if ((Object)(object)val5 == (Object)null)
			{
				return;
			}
			RectTransform val6 = (RectTransform)(object)((val5 is RectTransform) ? val5 : null);
			RectTransform val7 = (RectTransform)(object)((val2 is RectTransform) ? val2 : null);
			if (!((Object)(object)val6 == (Object)null) && !((Object)(object)val7 == (Object)null))
			{
				if ((Object)(object)_sortButtonObject == (Object)null)
				{
					CreateSortButton(val4, val2);
				}
				if ((Object)(object)_sortButtonObject != (Object)null)
				{
					UpdateSortButtonPosition(val6, val7);
				}
			}
		}

		private void CreateSortButton(Transform buttonTemplate, Transform playerPanel)
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Expected O, but got Unknown
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Expected O, but got Unknown
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = null;
			try
			{
				val = Object.Instantiate<GameObject>(((Component)buttonTemplate).gameObject, playerPanel);
				((Object)val).name = "PlayerSort_Sort";
				Button component = val.GetComponent<Button>();
				if ((Object)(object)component == (Object)null)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)"StackAll template has no Button component");
					Object.Destroy((Object)(object)val);
					return;
				}
				component.onClick = new ButtonClickedEvent();
				((UnityEvent)component.onClick).AddListener(new UnityAction(SortPlayerInventory));
				SetButtonText(val, "Sort");
				RectTransform component2 = val.GetComponent<RectTransform>();
				if ((Object)(object)component2 == (Object)null)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)"Sort button has no RectTransform");
					Object.Destroy((Object)(object)val);
					return;
				}
				component2.sizeDelta = new Vector2(65f, 30f);
				val.SetActive(true);
				val.transform.SetAsLastSibling();
				_sortButtonObject = val;
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Sort button created from vanilla StackAll template");
			}
			catch (Exception arg)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)$"Could not create Sort button: {arg}");
				if ((Object)(object)val != (Object)null)
				{
					Object.Destroy((Object)(object)val);
				}
				_sortButtonObject = null;
			}
		}

		private void UpdateSortButtonPosition(RectTransform playerGrid, RectTransform parent)
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_sortButtonObject == (Object)null) && !((Object)(object)playerGrid == (Object)null) && !((Object)(object)parent == (Object)null))
			{
				RectTransform component = _sortButtonObject.GetComponent<RectTransform>();
				if (!((Object)(object)component == (Object)null))
				{
					Vector3[] array = (Vector3[])(object)new Vector3[4];
					playerGrid.GetWorldCorners(array);
					Vector3 val = ((Transform)parent).InverseTransformPoint(array[0]);
					component.anchorMin = new Vector2(0.5f, 0.5f);
					component.anchorMax = new Vector2(0.5f, 0.5f);
					component.pivot = new Vector2(0.5f, 0.5f);
					float x = val.x;
					Rect rect = component.rect;
					float num = x + ((Rect)(ref rect)).width / 2f;
					float num2 = val.y - 5f;
					rect = component.rect;
					((Transform)component).localPosition = new Vector3(num, num2 - ((Rect)(ref rect)).height / 2f, 0f);
				}
			}
		}

		private void SortPlayerInventory()
		{
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Player localPlayer = Player.m_localPlayer;
				if ((Object)(object)localPlayer == (Object)null)
				{
					return;
				}
				Inventory inventory = ((Humanoid)localPlayer).GetInventory();
				if (inventory == null)
				{
					return;
				}
				int width = inventory.GetWidth();
				int height = inventory.GetHeight();
				List<ItemData> list = (from item in inventory.GetAllItems()
					where item != null && item.m_gridPos.y > 0
					select item).ToList();
				if (list.Count <= 1)
				{
					return;
				}
				List<ItemData> list2 = list.OrderBy((ItemData item) => GetSortCategory(item)).ThenBy<ItemData, string>((ItemData item) => item.m_shared.m_name, StringComparer.Ordinal).ThenByDescending((ItemData item) => item.m_quality)
					.ThenByDescending((ItemData item) => item.m_stack)
					.ToList();
				int num = 0;
				for (int num2 = 1; num2 < height; num2++)
				{
					for (int num3 = 0; num3 < width; num3++)
					{
						if (num >= list2.Count)
						{
							break;
						}
						list2[num].m_gridPos = new Vector2i(num3, num2);
						num++;
					}
				}
				NotifyInventoryChanged(inventory);
				((BaseUnityPlugin)this).Logger.LogInfo((object)$"Sorted {list2.Count} player inventory items");
			}
			catch (Exception arg)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)$"Inventory sorting failed: {arg}");
			}
		}

		private void NotifyInventoryChanged(Inventory inventory)
		{
			if (InventoryChangedMethod == null)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"Inventory.Changed(bool, bool) was not found; the inventory UI may not refresh immediately");
				return;
			}
			InventoryChangedMethod.Invoke(inventory, new object[2] { false, false });
		}

		private static int GetSortCategory(ItemData item)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: 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)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected I4, but got Unknown
			ItemType itemType = item.m_shared.m_itemType;
			switch (itemType - 1)
			{
			case 2:
			case 3:
			case 13:
			case 21:
				return 10;
			case 18:
				return 20;
			case 4:
			case 5:
			case 6:
			case 10:
			case 16:
			case 17:
				return 30;
			case 1:
				return 40;
			case 8:
			case 22:
				return 50;
			case 0:
				return 60;
			case 12:
				return 70;
			default:
				return 100;
			}
		}

		private static void SetButtonText(GameObject buttonObject, string text)
		{
			TMP_Text[] componentsInChildren = buttonObject.GetComponentsInChildren<TMP_Text>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				componentsInChildren[i].text = text;
			}
		}

		private static Transform FindDirectChild(Transform parent, string name)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			if ((Object)(object)parent == (Object)null)
			{
				return null;
			}
			foreach (Transform item in parent)
			{
				Transform val = item;
				if (((Object)val).name == name)
				{
					return val;
				}
			}
			return null;
		}

		private static Transform FindRecursive(Transform parent, string name)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			if ((Object)(object)parent == (Object)null)
			{
				return null;
			}
			foreach (Transform item in parent)
			{
				Transform val = item;
				if (((Object)val).name == name)
				{
					return val;
				}
				Transform val2 = FindRecursive(val, name);
				if ((Object)(object)val2 != (Object)null)
				{
					return val2;
				}
			}
			return null;
		}
	}
}