Decompiled source of DisconnectDrops v0.2.0

plugins/StonewardsDisconnectDrops.dll

Decompiled 19 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Mirror;
using MyBox;
using UnityEngine;

[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("StonewardsDisconnectDrops")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.2.0.0")]
[assembly: AssemblyInformationalVersion("0.2.0+d3bb8f925a32fbe03177114348d008421d8a77c1")]
[assembly: AssemblyProduct("StonewardsDisconnectDrops")]
[assembly: AssemblyTitle("StonewardsDisconnectDrops")]
[assembly: AssemblyVersion("0.2.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 StonewardsDisconnectDrops
{
	[BepInPlugin("com.thereisnouser.stonewards.disconnectdrops", "Disconnect Drops", "0.2.0")]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "com.thereisnouser.stonewards.disconnectdrops";

		public const string PluginName = "Disconnect Drops";

		public const string PluginVersion = "0.2.0";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<float> ScatterRadius;

		internal static ConfigEntry<bool> DropTomes;

		internal static ConfigEntry<bool> DropInventory;

		private Harmony _harmony;

		private void Awake()
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Expected O, but got Unknown
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Drop picked-up tomes and inventory items when a player leaves, is kicked or disconnects.");
			ScatterRadius = ((BaseUnityPlugin)this).Config.Bind<float>("General", "ScatterRadius", 1.6f, new ConfigDescription("Horizontal radius of dropped loot in metres.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.25f, 4f), Array.Empty<object>()));
			DropTomes = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "DropTomes", true, "Drop books consumed from the current run; excludes level-up rings.");
			DropInventory = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "DropInventory", true, "Drop inventory items except the first two slots (pickaxe and horn) on disconnect.");
			_harmony = new Harmony("com.thereisnouser.stonewards.disconnectdrops");
			_harmony.PatchAll(typeof(Plugin).Assembly);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Disconnect Drops 0.2.0 loaded (host-only).");
		}

		private void OnDestroy()
		{
			if (_harmony != null)
			{
				_harmony.UnpatchSelf();
			}
		}
	}
	[HarmonyPatch(typeof(StoneWardsNetworkManager), "OnServerDisconnect")]
	internal static class DisconnectPatch
	{
		private static void Prefix(StoneWardsNetworkManager __instance, NetworkConnectionToClient __0)
		{
			LootDropper.OnDisconnect(__instance, __0);
		}
	}
	[HarmonyPatch(typeof(StoneWardsNetworkManager), "OnServerAddPlayer")]
	internal static class PlayerAddedPatch
	{
		private static void Postfix(NetworkConnectionToClient __0)
		{
			LootDropper.OnPlayerAdded(__0);
		}
	}
	[HarmonyPatch(typeof(StoneWardsNetworkManager), "ClearAllRunData")]
	internal static class RunClearedPatch
	{
		private static void Postfix()
		{
			LootDropper.OnRunCleared();
		}
	}
	internal static class LootDropper
	{
		private static readonly HashSet<ulong> ProcessedPlayers = new HashSet<ulong>();

		private static readonly FieldInfo ConnectedField = AccessTools.Field(typeof(StoneWardsNetworkManager), "playerConnected");

		private static readonly FieldInfo DatabaseField = AccessTools.Field(typeof(ItemManager), "itemDataBase");

		internal static void OnPlayerAdded(NetworkConnectionToClient conn)
		{
			if (NetworkServer.active && conn != null && !((Object)(object)((NetworkConnection)conn).identity == (Object)null))
			{
				FirstPersonController component = ((Component)((NetworkConnection)conn).identity).GetComponent<FirstPersonController>();
				if ((Object)(object)component != (Object)null)
				{
					ProcessedPlayers.Remove(component.playerID);
				}
			}
		}

		internal static void OnRunCleared()
		{
			ProcessedPlayers.Clear();
		}

		internal static void OnDisconnect(StoneWardsNetworkManager manager, NetworkConnectionToClient conn)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Invalid comparison between Unknown and I4
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			if (!Plugin.Enabled.Value || !NetworkServer.active || (Object)(object)manager == (Object)null || conn == null || (Object)(object)GameManager.Instance == (Object)null || (int)GameManager.Instance.SceneType != 1)
			{
				return;
			}
			try
			{
				FirstPersonController val = FindPlayer(manager, conn);
				if ((Object)(object)val == (Object)null)
				{
					return;
				}
				ulong playerID = val.playerID;
				if (!ProcessedPlayers.Contains(playerID))
				{
					ProcessedPlayers.Add(playerID);
					Vector3 center = ((Component)val).transform.position + Vector3.up * 0.9f;
					int scatterIndex = 0;
					int stacksDropped = 0;
					int itemsDropped = 0;
					int num = 0;
					if (Plugin.DropInventory.Value)
					{
						DropInventoryItems(val, center, ref scatterIndex, out stacksDropped, out itemsDropped);
					}
					if (Plugin.DropTomes.Value)
					{
						num = DropConsumedTomes(GetRunPlayerData(val), center, ref scatterIndex);
					}
					Plugin.Log.LogInfo((object)("Player " + playerID + " disconnected: dropped " + num + " consumed tomes and " + itemsDropped + " inventory items in " + stacksDropped + " pickups (rings untouched)."));
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Loot drop failed; vanilla disconnect continues. " + ex));
			}
		}

		private static RunPlayerData GetRunPlayerData(FirstPersonController player)
		{
			RunPlayerData value = player.RunPlayerData;
			if (value != null)
			{
				return value;
			}
			SaveManager instance = Singleton<SaveManager>.Instance;
			Dictionary<ulong, RunPlayerData> dictionary = (((Object)(object)instance != (Object)null && instance.saveContainer != null) ? instance.saveContainer.runPlayersData : null);
			if (dictionary == null)
			{
				return null;
			}
			dictionary.TryGetValue(player.playerID, out value);
			return value;
		}

		private static int DropConsumedTomes(RunPlayerData record, Vector3 center, ref int scatterIndex)
		{
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Invalid comparison between Unknown and I4
			//IL_00e1: 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)
			if (record == null || record.rogueUpgrades == null || record.rogueUpgrades.Count == 0)
			{
				return 0;
			}
			RogueLikeUpgradeManager instance = RogueLikeUpgradeManager.Instance;
			PickupUpgradeItemDataSO tomeItemData = GetTomeItemData();
			if ((Object)(object)instance == (Object)null || (Object)(object)tomeItemData == (Object)null)
			{
				Plugin.Log.LogWarning((object)"Cannot drop tomes: manager or pickup prefab unavailable. Saved tomes kept.");
				return 0;
			}
			List<Tuple<RogueUpgradeData, RogueLikeUpgradeSO>> list = new List<Tuple<RogueUpgradeData, RogueLikeUpgradeSO>>();
			foreach (RogueUpgradeData rogueUpgrade in record.rogueUpgrades)
			{
				if (rogueUpgrade != null && !string.IsNullOrEmpty(rogueUpgrade.upgradeID))
				{
					RogueLikeUpgradeSO upgradeSOByID = instance.GetUpgradeSOByID(rogueUpgrade.upgradeID);
					if ((Object)(object)upgradeSOByID != (Object)null && (int)upgradeSOByID.UpgradeCategory == 1)
					{
						list.Add(Tuple.Create<RogueUpgradeData, RogueLikeUpgradeSO>(rogueUpgrade, upgradeSOByID));
					}
				}
			}
			int num = 0;
			foreach (Tuple<RogueUpgradeData, RogueLikeUpgradeSO> item in list)
			{
				if (SpawnTome(tomeItemData, item.Item2, Scatter(center, scatterIndex++)))
				{
					record.rogueUpgrades.Remove(item.Item1);
					num++;
				}
			}
			return num;
		}

		private static void DropInventoryItems(FirstPersonController player, Vector3 center, ref int scatterIndex, out int stacksDropped, out int itemsDropped)
		{
			//IL_0202: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: 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_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			stacksDropped = 0;
			itemsDropped = 0;
			InventorySystem inventorySystem = player.InventorySystem;
			ItemManager instance = ItemManager.Instance;
			if ((Object)(object)inventorySystem == (Object)null || !((NetworkBehaviour)inventorySystem).isServer || (Object)(object)instance == (Object)null)
			{
				Plugin.Log.LogWarning((object)"Inventory unavailable on server at disconnect; saved items kept.");
				return;
			}
			for (int i = 2; i < inventorySystem.InventoryEntries.Count; i++)
			{
				InventoryEntry val = inventorySystem.InventoryEntries[i];
				if (((InventoryEntry)(ref val)).IsEmpty || string.IsNullOrEmpty(val.itemID) || val.count <= 0)
				{
					continue;
				}
				ItemDataSO itemDataSoByID = instance.GetItemDataSoByID(val.itemID);
				if ((Object)(object)itemDataSoByID == (Object)null || (Object)(object)itemDataSoByID.pickableItemPrefab == (Object)null)
				{
					Plugin.Log.LogWarning((object)("Item '" + val.itemID + "' at slot " + i + " has no pickup prefab; keeping saved inventory entry."));
					continue;
				}
				int num = val.count;
				while (num > 0)
				{
					int num2 = ((!itemDataSoByID.isStackable) ? 1 : num);
					PickableItem val2 = null;
					try
					{
						val2 = instance.ServerInstantiatePickableItem(val.itemID, num2, Scatter(center, scatterIndex++), true, true);
						if ((Object)(object)val2 == (Object)null)
						{
							Plugin.Log.LogWarning((object)("Failed spawning '" + val.itemID + "' from slot " + i + "; saved entry unchanged."));
							break;
						}
						if (!inventorySystem.ServerRemoveItemFromSlot(i, num2))
						{
							DestroySpawnedPickup(val2);
							Plugin.Log.LogWarning((object)("Failed removing '" + val.itemID + "' from slot " + i + "; pickup rolled back."));
							break;
						}
						num -= num2;
						itemsDropped += num2;
						stacksDropped++;
					}
					catch (Exception ex)
					{
						if ((Object)(object)val2 != (Object)null)
						{
							DestroySpawnedPickup(val2);
						}
						Plugin.Log.LogError((object)("Failed dropping '" + val.itemID + "': " + ex));
						break;
					}
				}
			}
		}

		private static void DestroySpawnedPickup(PickableItem pickup)
		{
			if ((Object)(object)pickup == (Object)null)
			{
				return;
			}
			try
			{
				if ((Object)(object)((NetworkBehaviour)pickup).netIdentity != (Object)null && ((NetworkBehaviour)pickup).netIdentity.netId != 0)
				{
					NetworkServer.Destroy(((Component)pickup).gameObject);
				}
				else
				{
					Object.Destroy((Object)(object)((Component)pickup).gameObject);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Failed to roll back an inventory pickup: " + ex));
			}
		}

		private static FirstPersonController FindPlayer(StoneWardsNetworkManager manager, NetworkConnectionToClient conn)
		{
			Dictionary<int, FirstPersonController> dictionary = ((ConnectedField != null) ? (ConnectedField.GetValue(manager) as Dictionary<int, FirstPersonController>) : null);
			if (dictionary != null && dictionary.TryGetValue(conn.connectionId, out var value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			if (!((Object)(object)((NetworkConnection)conn).identity != (Object)null))
			{
				return null;
			}
			return ((Component)((NetworkConnection)conn).identity).GetComponent<FirstPersonController>();
		}

		private static PickupUpgradeItemDataSO GetTomeItemData()
		{
			ItemManager instance = ItemManager.Instance;
			ItemDatabaseSO val = (ItemDatabaseSO)(((Object)(object)instance != (Object)null && DatabaseField != null) ? /*isinst with value type is only supported in some contexts*/: null);
			if ((Object)(object)val == (Object)null || val.items == null)
			{
				return null;
			}
			foreach (ItemDataSO item in val.items)
			{
				PickupUpgradeItemDataSO val2 = (PickupUpgradeItemDataSO)(object)((item is PickupUpgradeItemDataSO) ? item : null);
				if ((Object)(object)val2 != (Object)null && ((ItemDataSO)val2).pickableItemPrefab is PickableUpgrade)
				{
					return val2;
				}
			}
			return null;
		}

		private static Vector3 Scatter(Vector3 center, int i)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			float num = (float)i * 2.3999631f;
			float num2 = Mathf.Min(Plugin.ScatterRadius.Value, 0.3f + Mathf.Sqrt((float)i) * 0.24f);
			return center + new Vector3(Mathf.Cos(num) * num2, 0f, Mathf.Sin(num) * num2);
		}

		private static bool SpawnTome(PickupUpgradeItemDataSO itemData, RogueLikeUpgradeSO upgrade, Vector3 position)
		{
			//IL_000a: 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)
			PickableItem val = null;
			bool flag = false;
			try
			{
				val = Object.Instantiate<PickableItem>(((ItemDataSO)itemData).pickableItemPrefab, position, Quaternion.identity);
				PickableUpgrade val2 = (PickableUpgrade)(object)((val is PickableUpgrade) ? val : null);
				if ((Object)(object)val2 == (Object)null)
				{
					return false;
				}
				val.NetworkInit((ItemDataSO)(object)itemData, 1, false);
				val2.SelectPickupUpgrade(0f, new List<RogueLikeUpgradeSO> { upgrade });
				if (val2.NetworkSyncUpgradeID != ((BaseUpgradeSO)upgrade).ID)
				{
					Plugin.Log.LogWarning((object)("Tome selection mismatch: " + ((BaseUpgradeSO)upgrade).ID));
					return false;
				}
				NetworkServer.Spawn(((Component)val).gameObject, (NetworkConnectionToClient)null);
				flag = true;
				return true;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Could not create tome " + ((BaseUpgradeSO)upgrade).ID + ": " + ex));
				return false;
			}
			finally
			{
				if (!flag && (Object)(object)val != (Object)null)
				{
					Object.Destroy((Object)(object)((Component)val).gameObject);
				}
			}
		}
	}
}