Decompiled source of QuickStackToChests v1.2.5

BepInEx\plugins\QuickStackToChests.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.Configuration;
using BepInEx.Logging;
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: AssemblyCompany("QuickStackToChests")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Valheim BepInEx mod: quick stack inventory into nearby chests by hotkey.")]
[assembly: AssemblyFileVersion("1.2.5.0")]
[assembly: AssemblyInformationalVersion("1.2.5+7180696863c35b2c76a2af9cf6d5034c2d981a29")]
[assembly: AssemblyProduct("QuickStackToChests")]
[assembly: AssemblyTitle("QuickStackToChests")]
[assembly: AssemblyVersion("1.2.5.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 QuickStackToChests
{
	[BepInPlugin("blajion.quickstacktochests", "QuickStackToChests", "1.2.5")]
	[BepInProcess("valheim.exe")]
	public class QuickStackPlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "blajion.quickstacktochests";

		public const string PluginName = "QuickStackToChests";

		public const string PluginVersion = "1.2.5";

		internal static ManualLogSource Log;

		internal static ConfigEntry<KeyboardShortcut> HotKey;

		internal static ConfigEntry<float> Radius;

		internal static ConfigEntry<bool> SkipFirstRow;

		internal static ConfigEntry<bool> SkipEquipped;

		internal static ConfigEntry<bool> IgnoreExtraSlots;

		internal static ConfigEntry<bool> IncludeBackpacks;

		internal static ConfigEntry<bool> IncludeNonStackable;

		internal static ConfigEntry<bool> FillEmptySlots;

		internal static ConfigEntry<bool> StrictWorldLevelMatch;

		internal static ConfigEntry<bool> RespectWards;

		internal static ConfigEntry<bool> SkipContainersInUse;

		internal static ConfigEntry<string> ExcludedItems;

		internal static ConfigEntry<string> ExcludedContainers;

		internal static ConfigEntry<bool> ShowMessage;

		internal static ConfigEntry<bool> Diagnostics;

		internal static ConfigEntry<bool> VerboseLog;

		private float _nextAllowedRun;

		private bool _settingsOpen;

		private bool _waitingForHotKey;

		private Rect _settingsRect = new Rect(30f, 100f, 480f, 570f);

		private string _teleportFixStatus = string.Empty;

		private float _teleportFixStatusClearTime;

		private static MethodInfo _chatHasFocus;

		private static bool _chatHasFocusResolved;

		private void Awake()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Expected O, but got Unknown
			//IL_025d: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			HotKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("1. Управление", "HotKey", new KeyboardShortcut((KeyCode)113, (KeyCode[])(object)new KeyCode[1] { (KeyCode)306 }), "Горячая клавиша переноса. Формат BepInEx: 'Q + LeftControl', 'V', 'S + LeftAlt' и т.п.");
			Radius = ((BaseUnityPlugin)this).Config.Bind<float>("2. Поиск сундуков", "Radius", 12f, new ConfigDescription("Радиус поиска сундуков вокруг игрока (метры).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 60f), Array.Empty<object>()));
			SkipContainersInUse = ((BaseUnityPlugin)this).Config.Bind<bool>("2. Поиск сундуков", "SkipContainersInUse", true, "Пропускать сундуки, которые сейчас открыты кем-то (в том числе вами).");
			RespectWards = ((BaseUnityPlugin)this).Config.Bind<bool>("2. Поиск сундуков", "RespectWards", true, "Учитывать ворды (Ward) и приватные сундуки: не трогать чужое.");
			ExcludedContainers = ((BaseUnityPlugin)this).Config.Bind<string>("2. Поиск сундуков", "ExcludedContainers", "", "Префабы сундуков, которые игнорировать. Через запятую, например: piece_chest_private, Container_wood");
			SkipFirstRow = ((BaseUnityPlugin)this).Config.Bind<bool>("3. Предметы", "SkipFirstRow", true, "Не трогать первый ряд инвентаря (хотбар) - там обычно инструменты и еда.");
			SkipEquipped = ((BaseUnityPlugin)this).Config.Bind<bool>("3. Предметы", "SkipEquipped", true, "Не трогать экипированные предметы.");
			IgnoreExtraSlots = ((BaseUnityPlugin)this).Config.Bind<bool>("3. Предметы", "IgnoreExtraSlots", true, "Не трогать предметы в дополнительных слотах модов (ExtraSlots, QuickSlots, слоты для еды, заклинаний, стрел).");
			IncludeBackpacks = ((BaseUnityPlugin)this).Config.Bind<bool>("3. Предметы", "IncludeBackpacks", true, "Также переносить подходящие предметы из рюкзаков (Backpacks от Smoothbrain, ReefPacks, AdventureBackpacks).");
			IncludeNonStackable = ((BaseUnityPlugin)this).Config.Bind<bool>("3. Предметы", "IncludeNonStackable", true, "Переносить и нестакающиеся предметы (оружие, броня, инструменты), если такие же лежат в сундуке.");
			FillEmptySlots = ((BaseUnityPlugin)this).Config.Bind<bool>("3. Предметы", "FillEmptySlots", true, "Если в сундуке уже есть такой предмет, но стаки заполнены - докладывать остаток в свободные слоты этого сундука.");
			StrictWorldLevelMatch = ((BaseUnityPlugin)this).Config.Bind<bool>("3. Предметы", "StrictWorldLevelMatch", false, "Строго сравнивать m_worldLevel предметов. Включать только если мод объединяет предметы разных уровней мира, которые в игре не стакаются.");
			ExcludedItems = ((BaseUnityPlugin)this).Config.Bind<string>("3. Предметы", "ExcludedItems", "", "Предметы, которые никогда не переносить. Через запятую, префаб или имя: Wood, Coins, $item_coins");
			ShowMessage = ((BaseUnityPlugin)this).Config.Bind<bool>("4. Прочее", "ShowMessage", true, "Показывать сообщение о результате переноса на экране.");
			Diagnostics = ((BaseUnityPlugin)this).Config.Bind<bool>("4. Прочее", "Diagnostics", true, "Писать в лог итог каждого нажатия: сколько найдено сундуков, сколько перенесено и почему предметы пропущены.");
			VerboseLog = ((BaseUnityPlugin)this).Config.Bind<bool>("4. Прочее", "VerboseLog", false, "Подробный лог каждого переноса по предметам и сундукам (шумно).");
			Log.LogInfo((object)string.Format("{0} v{1} loaded. Hotkey: {2}", "QuickStackToChests", "1.2.5", HotKey.Value));
		}

		private void Update()
		{
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Player.m_localPlayer == (Object)null || (Object)(object)ZNetScene.instance == (Object)null)
			{
				return;
			}
			if (Input.GetKeyDown((KeyCode)289) && !Console.IsVisible() && !TextInput.IsVisible())
			{
				_settingsOpen = !_settingsOpen;
				_waitingForHotKey = false;
			}
			if (_settingsOpen)
			{
				Cursor.lockState = (CursorLockMode)0;
				Cursor.visible = true;
				if (_waitingForHotKey)
				{
					TryReadSideMouseBinding();
				}
			}
			else
			{
				if (Time.time < _nextAllowedRun || IsTypingOrBlocked())
				{
					return;
				}
				KeyboardShortcut value = HotKey.Value;
				if (((KeyboardShortcut)(ref value)).IsDown())
				{
					_nextAllowedRun = Time.time + 0.3f;
					try
					{
						QuickStack.Run();
					}
					catch (Exception arg)
					{
						Log.LogError((object)$"Quick stack error: {arg}");
					}
				}
			}
		}

		private void OnGUI()
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			//IL_003c: 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)
			if (_settingsOpen)
			{
				Cursor.lockState = (CursorLockMode)0;
				Cursor.visible = true;
				_settingsRect = GUI.Window(731942, _settingsRect, new WindowFunction(DrawSettingsWindow), Translations.Text("QuickStackToChests — Settings", "QuickStackToChests — Настройки"));
			}
		}

		private void DrawSettingsWindow(int windowId)
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e9: Unknown result type (might be due to invalid IL or missing references)
			GUILayout.BeginVertical(Array.Empty<GUILayoutOption>());
			GUILayout.Label(Translations.Text("F8 — close. Changes save immediately.", "F8 — закрыть. Настройки сохраняются сразу."), Array.Empty<GUILayoutOption>());
			GUILayout.Space(8f);
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUILayout.Label(Translations.Text("Quick stack hotkey:", "Быстрая сортировка:"), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(150f) });
			if (GUILayout.Button(_waitingForHotKey ? Translations.Text("Press a key or side mouse button… (Esc — cancel)", "Нажми клавишу или боковую кнопку мыши… (Esc — отмена)") : ((object)HotKey.Value/*cast due to .constrained prefix*/).ToString(), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(260f) }))
			{
				_waitingForHotKey = true;
			}
			GUILayout.EndHorizontal();
			if (_waitingForHotKey)
			{
				ReadNewHotKey(Event.current);
			}
			GUILayout.Space(8f);
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUILayout.Label(Translations.Text($"Chest radius: {Radius.Value:0} m", $"Радиус сундуков: {Radius.Value:0} м"), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(180f) });
			float num = Mathf.Round(GUILayout.HorizontalSlider(Radius.Value, 1f, 60f, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(220f) }));
			if (!Mathf.Approximately(num, Radius.Value))
			{
				Radius.Value = num;
				((BaseUnityPlugin)this).Config.Save();
			}
			GUILayout.EndHorizontal();
			DrawToggle(Translations.Text("Skip first inventory row", "Не трогать первый ряд инвентаря"), SkipFirstRow);
			DrawToggle(Translations.Text("Skip equipped items", "Не трогать экипированные вещи"), SkipEquipped);
			DrawToggle(Translations.Text("Ignore extra slots (food, spells, ammo)", "Не трогать экстра-слоты (еда, спеллы, стрелы)"), IgnoreExtraSlots);
			DrawToggle(Translations.Text("Include backpack inventory", "Переносить вещи из рюкзаков"), IncludeBackpacks);
			DrawToggle(Translations.Text("Respect wards and private chests", "Уважать ворды и приватные сундуки"), RespectWards);
			DrawToggle(Translations.Text("Skip chests currently in use", "Пропускать открытые сундуки"), SkipContainersInUse);
			DrawToggle(Translations.Text("Fill empty slots in matching chests", "Класть остаток в свободные ячейки сундука"), FillEmptySlots);
			DrawToggle(Translations.Text("Include weapons, armor and tools", "Переносить оружие, броню и инструменты"), IncludeNonStackable);
			DrawToggle(Translations.Text("Strict world-level match", "Строгое сравнение уровня мира"), StrictWorldLevelMatch);
			DrawToggle(Translations.Text("Log diagnostics", "Писать диагностику в лог"), Diagnostics);
			DrawTeleportFixSection();
			GUILayout.FlexibleSpace();
			if (GUILayout.Button(Translations.Text("Close (F8)", "Закрыть (F8)"), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(28f) }))
			{
				_settingsOpen = false;
				_waitingForHotKey = false;
			}
			GUILayout.EndVertical();
			GUI.DragWindow(new Rect(0f, 0f, 10000f, 24f));
		}

		private void DrawTeleportFixSection()
		{
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: 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_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0225: Unknown result type (might be due to invalid IL or missing references)
			GUILayout.Space(6f);
			GUILayout.BeginVertical(GUI.skin.box, Array.Empty<GUILayoutOption>());
			bool flag = TeleportFixer.IsPlayerStuckInTeleport();
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUILayout.Label(Translations.Text("Teleport recovery:", "Разбаговка портала:"), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) });
			if (flag)
			{
				GUI.color = new Color(1f, 0.45f, 0.45f, 1f);
				GUILayout.Label(Translations.Text("⚠\ufe0f Teleport stuck detected!", "⚠\ufe0f Зависание в портале!"), Array.Empty<GUILayoutOption>());
				GUI.color = Color.white;
			}
			else
			{
				GUI.color = new Color(0.6f, 0.9f, 0.6f, 1f);
				GUILayout.Label(Translations.Text("Normal (not teleporting)", "В норме (не в портале)"), Array.Empty<GUILayoutOption>());
				GUI.color = Color.white;
			}
			GUILayout.EndHorizontal();
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUI.color = (Color)(flag ? new Color(0.35f, 1f, 0.45f, 1f) : Color.white);
			if (GUILayout.Button(Translations.Text("⚡ Fix & Exit Here", "⚡ Разбаговать здесь"), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(28f) }))
			{
				if (TeleportFixer.UnstickTeleport())
				{
					_teleportFixStatus = Translations.Text("Teleport unstick applied!", "Телепортация успешно разбагована!");
					_settingsOpen = false;
				}
				else
				{
					_teleportFixStatus = Translations.Text("Player is not in teleport mode.", "Персонаж не застрял в телепортации.");
				}
				_teleportFixStatusClearTime = Time.time + 4f;
			}
			GUI.color = (Color)(flag ? new Color(1f, 0.85f, 0.35f, 1f) : Color.white);
			if (GUILayout.Button(Translations.Text("↩ Return to Source", "↩ Вернуть к источнику"), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(28f) }))
			{
				if (TeleportFixer.UnstickTeleport(returnToOrigin: true))
				{
					_teleportFixStatus = Translations.Text("Returned to origin portal!", "Возвращен к исходному порталу!");
					_settingsOpen = false;
				}
				else
				{
					_teleportFixStatus = Translations.Text("Player is not in teleport mode.", "Персонаж не застрял в телепортации.");
				}
				_teleportFixStatusClearTime = Time.time + 4f;
			}
			GUI.color = Color.white;
			GUILayout.EndHorizontal();
			if (!string.IsNullOrEmpty(_teleportFixStatus) && Time.time < _teleportFixStatusClearTime)
			{
				GUILayout.Space(2f);
				GUILayout.Label(_teleportFixStatus, Array.Empty<GUILayoutOption>());
			}
			GUILayout.EndVertical();
		}

		private void DrawToggle(string label, ConfigEntry<bool> setting)
		{
			bool flag = GUILayout.Toggle(setting.Value, label, Array.Empty<GUILayoutOption>());
			if (flag != setting.Value)
			{
				setting.Value = flag;
				((BaseUnityPlugin)this).Config.Save();
			}
		}

		private void ReadNewHotKey(Event currentEvent)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Invalid comparison between Unknown and I4
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Invalid comparison between Unknown and I4
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: 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_00ba: Unknown result type (might be due to invalid IL or missing references)
			if (currentEvent == null || (int)currentEvent.type != 4)
			{
				return;
			}
			if ((int)currentEvent.keyCode == 27)
			{
				_waitingForHotKey = false;
				currentEvent.Use();
			}
			else if (!IsModifierKey(currentEvent.keyCode))
			{
				List<KeyCode> list = new List<KeyCode>();
				if (currentEvent.control)
				{
					list.Add((KeyCode)306);
				}
				if (currentEvent.shift)
				{
					list.Add((KeyCode)304);
				}
				if (currentEvent.alt)
				{
					list.Add((KeyCode)308);
				}
				if (currentEvent.command)
				{
					list.Add((KeyCode)310);
				}
				HotKey.Value = new KeyboardShortcut(currentEvent.keyCode, list.ToArray());
				((BaseUnityPlugin)this).Config.Save();
				Log.LogInfo((object)$"New quick stack hotkey: {HotKey.Value}");
				_waitingForHotKey = false;
				currentEvent.Use();
			}
		}

		private void TryReadSideMouseBinding()
		{
			if (Input.GetMouseButtonDown(3))
			{
				SetMouseHotKey((KeyCode)326);
			}
			else if (Input.GetMouseButtonDown(4))
			{
				SetMouseHotKey((KeyCode)327);
			}
			else if (Input.GetMouseButtonDown(5))
			{
				SetMouseHotKey((KeyCode)328);
			}
		}

		private void SetMouseHotKey(KeyCode mouseButton)
		{
			//IL_0005: 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_002f: Unknown result type (might be due to invalid IL or missing references)
			HotKey.Value = new KeyboardShortcut(mouseButton, Array.Empty<KeyCode>());
			((BaseUnityPlugin)this).Config.Save();
			Log.LogInfo((object)$"New quick stack hotkey: {HotKey.Value}");
			_waitingForHotKey = false;
		}

		private static bool IsModifierKey(KeyCode key)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Invalid comparison between Unknown and I4
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Invalid comparison between Unknown and I4
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Invalid comparison between Unknown and I4
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Invalid comparison between Unknown and I4
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Invalid comparison between Unknown and I4
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Invalid comparison between Unknown and I4
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Invalid comparison between Unknown and I4
			if ((int)key != 306 && (int)key != 305 && (int)key != 304 && (int)key != 303 && (int)key != 308 && (int)key != 307 && (int)key != 310)
			{
				return (int)key == 309;
			}
			return true;
		}

		private static bool IsTypingOrBlocked()
		{
			if (Console.IsVisible())
			{
				return true;
			}
			if (TextInput.IsVisible())
			{
				return true;
			}
			if (Menu.IsVisible())
			{
				return true;
			}
			if (IsChatFocused())
			{
				return true;
			}
			return false;
		}

		private static bool IsChatFocused()
		{
			if ((Object)(object)Chat.instance == (Object)null)
			{
				return false;
			}
			if (!_chatHasFocusResolved)
			{
				_chatHasFocusResolved = true;
				_chatHasFocus = typeof(Chat).GetMethod("HasFocus", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy, null, Type.EmptyTypes, null);
			}
			if (_chatHasFocus == null)
			{
				return false;
			}
			try
			{
				object obj = _chatHasFocus.Invoke(Chat.instance, null);
				bool flag = default(bool);
				int num;
				if (obj is bool)
				{
					flag = (bool)obj;
					num = 1;
				}
				else
				{
					num = 0;
				}
				return (byte)((uint)num & (flag ? 1u : 0u)) != 0;
			}
			catch
			{
				return false;
			}
		}
	}
	internal static class QuickStack
	{
		private sealed class Stats
		{
			internal string ScanMode = "-";

			internal int Scanned;

			internal int Inspected;

			internal int ContainersSeen;

			internal int ContainersFound;

			internal int ContainersInUse;

			internal int ContainersNoAccess;

			internal int ContainersNotLoaded;

			internal int ContainersNoInventory;

			internal int ContainersExcluded;

			internal int ContainersOnCharacter;

			internal float NearestDistance = float.MaxValue;

			internal string NearestName = "-";

			internal double ScanMs;

			internal int SkippedFirstRow;

			internal int SkippedEquipped;

			internal int SkippedExtraSlots;

			internal int SkippedNonStackable;

			internal int SkippedExcluded;

			internal int SkippedQuest;

			internal int NoMatchInChests;

			internal int MatchedButFull;

			internal int MoveFailed;

			internal readonly HashSet<string> NoMatchNames = new HashSet<string>();

			internal readonly HashSet<string> FullNames = new HashSet<string>();

			internal readonly HashSet<string> FailedNames = new HashSet<string>();
		}

		private sealed class SourceInventory
		{
			internal Inventory Inventory;

			internal bool IsPlayerMain;

			internal string Name;
		}

		private const BindingFlags AllInstance = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

		private const BindingFlags AllStatic = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

		private const float DiagnosticBand = 20f;

		private static readonly MethodInfo ContainerSaveMethod = typeof(Container).GetMethod("Save", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);

		private static readonly MethodInfo ContainerLoadMethod = typeof(Container).GetMethod("Load", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);

		private static readonly FieldInfo ContainerNViewField = typeof(Container).GetField("m_nview", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

		private static readonly MethodInfo ContainerCheckAccessMethod = typeof(Container).GetMethod("CheckAccess", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(long) }, null);

		private static readonly MethodInfo MoveItemToThisMethod = typeof(Inventory).GetMethod("MoveItemToThis", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[5]
		{
			typeof(Inventory),
			typeof(ItemData),
			typeof(int),
			typeof(int),
			typeof(int)
		}, null);

		private static readonly MethodInfo InventoryChangedNoArgs = typeof(Inventory).GetMethod("Changed", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);

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

		private static readonly MethodInfo PrivateAreaCheckAccess4 = typeof(PrivateArea).GetMethod("CheckAccess", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[4]
		{
			typeof(Vector3),
			typeof(float),
			typeof(bool),
			typeof(bool)
		}, null);

		private static readonly MethodInfo PrivateAreaCheckAccess3 = typeof(PrivateArea).GetMethod("CheckAccess", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[3]
		{
			typeof(Vector3),
			typeof(float),
			typeof(bool)
		}, null);

		private static readonly MethodInfo InCutsceneMethod = typeof(Character).GetMethod("InCutscene", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);

		private static readonly FieldInfo WorldLevelField = typeof(ItemData).GetField("m_worldLevel", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

		private static readonly FieldInfo ZNetSceneInstancesField = typeof(ZNetScene).GetField("m_instances", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

		private static Func<ItemData, bool> _extraSlotsIsItemInSlot;

		private static bool _extraSlotsFound;

		private static bool _extraSlotsSearched;

		private static Func<Inventory, IEnumerable<Inventory>> _sbGetAllBackpacks;

		private static Func<Inventory> _sbGetEquippedBackpack;

		private static bool _sbIntegrated;

		private static Func<Player, ItemData> _rfWornPack;

		private static Func<ItemData, object> _rfGetPackData;

		private static FieldInfo _rfPackInvField;

		private static bool _rfIntegrated;

		private static int _backpackSearchAttempts;

		internal static void Run()
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || ((Character)localPlayer).IsDead() || IsInCutscene(localPlayer))
			{
				return;
			}
			Inventory inventory = ((Humanoid)localPlayer).GetInventory();
			if (inventory == null)
			{
				return;
			}
			EnsureExtraSlotsIntegration();
			Stats stats = new Stats();
			HashSet<string> excludedItems = ParseList(QuickStackPlugin.ExcludedItems.Value);
			HashSet<string> excluded = ParseList(QuickStackPlugin.ExcludedContainers.Value);
			List<Container> list = FindNearbyContainers(localPlayer, excluded, stats);
			if (list.Count == 0)
			{
				Message(localPlayer, BuildNoContainersMessage(stats));
				LogSummary(stats, 0, 0);
				return;
			}
			List<SourceInventory> list2 = new List<SourceInventory>
			{
				new SourceInventory
				{
					Inventory = inventory,
					IsPlayerMain = true,
					Name = "Инвентарь"
				}
			};
			if (QuickStackPlugin.IncludeBackpacks.Value)
			{
				List<Inventory> backpackInventories = GetBackpackInventories(localPlayer, inventory);
				for (int i = 0; i < backpackInventories.Count; i++)
				{
					list2.Add(new SourceInventory
					{
						Inventory = backpackInventories[i],
						IsPlayerMain = false,
						Name = ((backpackInventories.Count == 1) ? "Рюкзак" : $"Рюкзак {i + 1}")
					});
				}
			}
			int num = 0;
			int num2 = 0;
			HashSet<Inventory> hashSet = new HashSet<Inventory>();
			List<(SourceInventory, List<ItemData>)> list3 = new List<(SourceInventory, List<ItemData>)>();
			int num3 = 0;
			foreach (SourceInventory source in list2)
			{
				List<ItemData> list4 = (from item in source.Inventory.GetAllItems()
					where IsTransferable(item, excludedItems, stats, source.IsPlayerMain)
					select item).ToList();
				num3 += list4.Count;
				if (list4.Count > 0)
				{
					list3.Add((source, list4));
				}
			}
			foreach (Container item in list)
			{
				bool flag = false;
				foreach (var sc in list3)
				{
					if (sc.Item2.Any((ItemData item) => item.m_stack > 0 && sc.Item1.Inventory.ContainsItem(item)))
					{
						flag = true;
						break;
					}
				}
				if (!flag)
				{
					break;
				}
				Inventory val = PrepareContainer(item);
				if (val == null)
				{
					continue;
				}
				int num4 = 0;
				foreach (var item2 in list3)
				{
					foreach (ItemData item3 in item2.Item2)
					{
						if (item3.m_stack > 0 && item2.Item1.Inventory.ContainsItem(item3))
						{
							int num5 = StackItemIntoContainer(item2.Item1.Inventory, val, item3, stats, item);
							if (num5 > 0)
							{
								num4 += num5;
								hashSet.Add(item2.Item1.Inventory);
							}
						}
					}
				}
				if (num4 > 0)
				{
					num += num4;
					num2++;
					FinishContainer(item);
				}
			}
			if (num > 0)
			{
				foreach (Inventory item4 in hashSet)
				{
					NotifyChanged(item4);
				}
				Message(localPlayer, $"Разложено {num} шт. по {num2} сундукам");
			}
			else
			{
				Message(localPlayer, BuildNothingMessage(stats, num3, list.Count));
			}
			LogSummary(stats, num, num2);
		}

		private static string BuildNoContainersMessage(Stats stats)
		{
			List<string> list = new List<string>();
			if (stats.ContainersInUse > 0)
			{
				list.Add($"открыты: {stats.ContainersInUse}");
			}
			if (stats.ContainersNoAccess > 0)
			{
				list.Add($"нет доступа: {stats.ContainersNoAccess}");
			}
			if (stats.ContainersNotLoaded > 0)
			{
				list.Add($"не загружены: {stats.ContainersNotLoaded}");
			}
			if (stats.ContainersNoInventory > 0)
			{
				list.Add($"без инвентаря: {stats.ContainersNoInventory}");
			}
			if (stats.ContainersExcluded > 0)
			{
				list.Add($"исключены: {stats.ContainersExcluded}");
			}
			if (list.Count > 0)
			{
				return "Сундуки недоступны (" + string.Join(", ", list.ToArray()) + ")";
			}
			if (stats.NearestDistance < float.MaxValue)
			{
				return $"Сундуки есть, но дальше {QuickStackPlugin.Radius.Value:0} м (ближайший: {stats.NearestDistance:0.0} м)";
			}
			return "Рядом нет доступных сундуков";
		}

		private static string BuildNothingMessage(Stats stats, int candidateCount, int containerCount)
		{
			if (candidateCount == 0)
			{
				List<string> list = new List<string>();
				if (stats.SkippedFirstRow > 0)
				{
					list.Add($"1-й ряд: {stats.SkippedFirstRow}");
				}
				if (stats.SkippedEquipped > 0)
				{
					list.Add($"надето: {stats.SkippedEquipped}");
				}
				if (stats.SkippedExtraSlots > 0)
				{
					list.Add($"экстра-слоты: {stats.SkippedExtraSlots}");
				}
				if (stats.SkippedNonStackable > 0)
				{
					list.Add($"не стакается: {stats.SkippedNonStackable}");
				}
				if (stats.SkippedExcluded > 0)
				{
					list.Add($"исключено: {stats.SkippedExcluded}");
				}
				if (list.Count <= 0)
				{
					return "Инвентарь пуст";
				}
				return "Всё отфильтровано (" + string.Join(", ", list.ToArray()) + ")";
			}
			if (stats.MoveFailed > 0)
			{
				return $"Не удалось перенести ({stats.MoveFailed} попыток) - см. лог";
			}
			if (stats.MatchedButFull > 0)
			{
				return "Совпадения есть, но сундуки забиты";
			}
			return $"Нет совпадений: проверено {candidateCount} предметов в {containerCount} сундуках";
		}

		private static void LogSummary(Stats stats, int moved, int usedContainers)
		{
			if (QuickStackPlugin.Diagnostics.Value)
			{
				QuickStackPlugin.Log.LogInfo((object)($"[quickstack] поиск={stats.ScanMode} за {stats.ScanMs:0.0} мс, объектов: {stats.Scanned}, проверено близких: {stats.Inspected}, " + $"сундуков: {stats.ContainersSeen}, годных: {stats.ContainersFound}, ближайший: {stats.NearestName} на " + $"{((stats.NearestDistance == float.MaxValue) ? (-1f) : stats.NearestDistance):0.0} м, радиус: {QuickStackPlugin.Radius.Value:0} м"));
				QuickStackPlugin.Log.LogInfo((object)($"[quickstack] сундуки отклонены [открыты: {stats.ContainersInUse}, нет доступа: {stats.ContainersNoAccess}, " + $"не загружены: {stats.ContainersNotLoaded}, без инвентаря: {stats.ContainersNoInventory}, " + $"на персонаже: {stats.ContainersOnCharacter}, исключены: {stats.ContainersExcluded}]"));
				QuickStackPlugin.Log.LogInfo((object)($"[quickstack] перенесено: {moved} шт. в {usedContainers}; " + $"предметы пропущены [1й ряд: {stats.SkippedFirstRow}, надето: {stats.SkippedEquipped}, экстра-слоты: {stats.SkippedExtraSlots}, не стак: {stats.SkippedNonStackable}, " + $"искл: {stats.SkippedExcluded}, квест: {stats.SkippedQuest}]; " + $"без совпадения: {stats.NoMatchInChests}, сундук полный: {stats.MatchedButFull}, ошибка переноса: {stats.MoveFailed}"));
				if (stats.NoMatchNames.Count > 0)
				{
					QuickStackPlugin.Log.LogInfo((object)("[quickstack] нет таких в сундуках: " + string.Join(", ", stats.NoMatchNames.ToArray())));
				}
				if (stats.FullNames.Count > 0)
				{
					QuickStackPlugin.Log.LogInfo((object)("[quickstack] места нет для: " + string.Join(", ", stats.FullNames.ToArray())));
				}
				if (stats.FailedNames.Count > 0)
				{
					QuickStackPlugin.Log.LogWarning((object)("[quickstack] перенос не удался для: " + string.Join(", ", stats.FailedNames.ToArray())));
				}
			}
		}

		private static List<Container> FindNearbyContainers(Player player, HashSet<string> excluded, Stats stats)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: 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)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			List<Container> list = new List<Container>();
			HashSet<Container> hashSet = new HashSet<Container>();
			Vector3 center = ((Component)player).transform.position;
			float value = QuickStackPlugin.Radius.Value;
			long playerID = player.GetPlayerID();
			Stopwatch stopwatch = Stopwatch.StartNew();
			List<Container> list2 = CollectContainers(center, value, stats);
			stopwatch.Stop();
			stats.ScanMs = stopwatch.Elapsed.TotalMilliseconds;
			foreach (Container item in list2)
			{
				if (!((Object)(object)item == (Object)null) && hashSet.Add(item))
				{
					stats.ContainersSeen++;
					float num = Vector3.Distance(((Component)item).transform.position, center);
					if (num < stats.NearestDistance)
					{
						stats.NearestDistance = num;
						stats.NearestName = ((Object)item).name;
					}
					if (!(num > value) && IsUsableContainer(item, playerID, excluded, stats))
					{
						list.Add(item);
					}
				}
			}
			stats.ContainersFound = list.Count;
			list.Sort((Container a, Container b) => Vector3.SqrMagnitude(((Component)a).transform.position - center).CompareTo(Vector3.SqrMagnitude(((Component)b).transform.position - center)));
			return list;
		}

		private static List<Container> CollectContainers(Vector3 center, float radius, Stats stats)
		{
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			List<Container> list = new List<Container>();
			float num = radius * radius;
			float num2 = (radius + 20f) * (radius + 20f);
			if (ZNetSceneInstancesField != null && (Object)(object)ZNetScene.instance != (Object)null)
			{
				try
				{
					if (ZNetSceneInstancesField.GetValue(ZNetScene.instance) is IDictionary dictionary)
					{
						foreach (object value in dictionary.Values)
						{
							stats.Scanned++;
							ZNetView val = (ZNetView)((value is ZNetView) ? value : null);
							if (val == null || (Object)(object)val == (Object)null)
							{
								continue;
							}
							float num3 = Vector3.SqrMagnitude(((Component)val).transform.position - center);
							if (!(num3 > num2))
							{
								stats.Inspected++;
								Container val2 = ((Component)val).GetComponent<Container>();
								if ((Object)(object)val2 == (Object)null && num3 <= num)
								{
									val2 = ((Component)val).GetComponentInChildren<Container>();
								}
								if ((Object)(object)val2 != (Object)null)
								{
									list.Add(val2);
								}
							}
						}
						stats.ScanMode = "znetscene";
						return list;
					}
				}
				catch (Exception ex)
				{
					QuickStackPlugin.Log.LogWarning((object)("Обход ZNetScene.m_instances не удался (" + ex.Message + "), использую физику."));
				}
			}
			Collider[] array = Physics.OverlapSphere(center, radius, -1, (QueryTriggerInteraction)2);
			foreach (Collider val3 in array)
			{
				stats.Scanned++;
				stats.Inspected++;
				if (!((Object)(object)val3 == (Object)null))
				{
					Container componentInParent = ((Component)val3).GetComponentInParent<Container>();
					if ((Object)(object)componentInParent != (Object)null)
					{
						list.Add(componentInParent);
					}
				}
			}
			stats.ScanMode = "physics";
			return list;
		}

		private static bool IsUsableContainer(Container container, long playerId, HashSet<string> excluded, Stats stats)
		{
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			ZNetView containerNView = GetContainerNView(container);
			if ((Object)(object)containerNView == (Object)null || !containerNView.IsValid())
			{
				stats.ContainersNotLoaded++;
				return false;
			}
			if ((Object)(object)((Component)container).GetComponentInParent<Character>() != (Object)null)
			{
				stats.ContainersOnCharacter++;
				return false;
			}
			if (container.GetInventory() == null)
			{
				stats.ContainersNoInventory++;
				return false;
			}
			if (QuickStackPlugin.SkipContainersInUse.Value && container.IsInUse())
			{
				stats.ContainersInUse++;
				return false;
			}
			if (!HasContainerAccess(container, playerId))
			{
				stats.ContainersNoAccess++;
				return false;
			}
			if (QuickStackPlugin.RespectWards.Value && !CheckWardAccess(((Component)container).transform.position))
			{
				stats.ContainersNoAccess++;
				return false;
			}
			if (excluded.Count > 0)
			{
				string prefabName = Utils.GetPrefabName(((Component)container).gameObject);
				if (excluded.Contains(Normalize(prefabName)) || excluded.Contains(Normalize(container.m_name)))
				{
					stats.ContainersExcluded++;
					return false;
				}
			}
			return true;
		}

		private static ZNetView GetContainerNView(Container container)
		{
			if ((Object)(object)container == (Object)null)
			{
				return null;
			}
			try
			{
				object? obj = ContainerNViewField?.GetValue(container);
				return (ZNetView)(((obj is ZNetView) ? obj : null) ?? container.m_rootObjectOverride ?? ((Component)container).GetComponent<ZNetView>());
			}
			catch (Exception ex)
			{
				QuickStackPlugin.Log.LogWarning((object)("Не удалось получить ZNetView сундука: " + ex.Message));
				return null;
			}
		}

		private static bool HasContainerAccess(Container container, long playerId)
		{
			if (ContainerCheckAccessMethod == null)
			{
				QuickStackPlugin.Log.LogWarning((object)"Container.CheckAccess не найден; сундук пропущен.");
				return false;
			}
			try
			{
				return (bool)ContainerCheckAccessMethod.Invoke(container, new object[1] { playerId });
			}
			catch (Exception ex)
			{
				QuickStackPlugin.Log.LogWarning((object)("Не удалось проверить доступ к сундуку: " + ex.Message));
				return false;
			}
		}

		private static bool CheckWardAccess(Vector3 position)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (PrivateAreaCheckAccess4 != null)
				{
					return (bool)PrivateAreaCheckAccess4.Invoke(null, new object[4] { position, 0f, false, false });
				}
				if (PrivateAreaCheckAccess3 != null)
				{
					return (bool)PrivateAreaCheckAccess3.Invoke(null, new object[3] { position, 0f, false });
				}
			}
			catch (Exception ex)
			{
				QuickStackPlugin.Log.LogWarning((object)("PrivateArea.CheckAccess недоступен: " + ex.Message));
			}
			return true;
		}

		private static bool IsInCutscene(Player player)
		{
			if (InCutsceneMethod == null)
			{
				return false;
			}
			try
			{
				return (bool)InCutsceneMethod.Invoke(player, null);
			}
			catch
			{
				return false;
			}
		}

		private static Inventory PrepareContainer(Container container)
		{
			ZNetView containerNView = GetContainerNView(container);
			if ((Object)(object)containerNView == (Object)null || !containerNView.IsValid())
			{
				return null;
			}
			if (!containerNView.IsOwner())
			{
				containerNView.ClaimOwnership();
				Invoke(ContainerLoadMethod, container, "Container.Load");
			}
			return container.GetInventory();
		}

		private static void FinishContainer(Container container)
		{
			Inventory inventory = container.GetInventory();
			if (inventory != null)
			{
				NotifyChanged(inventory);
			}
			Invoke(ContainerSaveMethod, container, "Container.Save");
		}

		private static void NotifyChanged(Inventory inventory)
		{
			if (inventory == null)
			{
				return;
			}
			try
			{
				if (InventoryChangedNoArgs != null)
				{
					InventoryChangedNoArgs.Invoke(inventory, null);
				}
				else if (InventoryChangedTwoArgs != null)
				{
					InventoryChangedTwoArgs.Invoke(inventory, new object[2] { false, false });
				}
			}
			catch (Exception ex)
			{
				QuickStackPlugin.Log.LogWarning((object)("Inventory.Changed завершился ошибкой: " + ex.Message));
			}
		}

		private static void Invoke(MethodInfo method, Container container, string label)
		{
			if (method == null)
			{
				return;
			}
			try
			{
				method.Invoke(container, null);
			}
			catch (Exception ex)
			{
				QuickStackPlugin.Log.LogWarning((object)(label + " завершился ошибкой: " + ex.Message));
			}
		}

		private static bool IsTransferable(ItemData item, HashSet<string> excluded, Stats stats, bool isPlayerMain = true)
		{
			if (item == null || item.m_shared == null || item.m_stack <= 0)
			{
				return false;
			}
			if (isPlayerMain)
			{
				if (QuickStackPlugin.SkipEquipped.Value && item.m_equipped)
				{
					stats.SkippedEquipped++;
					return false;
				}
				if (QuickStackPlugin.SkipFirstRow.Value && item.m_gridPos.y == 0)
				{
					stats.SkippedFirstRow++;
					return false;
				}
				if (QuickStackPlugin.IgnoreExtraSlots.Value && IsExtraSlotItem(item))
				{
					stats.SkippedExtraSlots++;
					return false;
				}
			}
			if (item.m_shared.m_questItem)
			{
				stats.SkippedQuest++;
				return false;
			}
			if (!QuickStackPlugin.IncludeNonStackable.Value && item.m_shared.m_maxStackSize <= 1)
			{
				stats.SkippedNonStackable++;
				return false;
			}
			if (excluded.Count > 0)
			{
				string value = (((Object)(object)item.m_dropPrefab != (Object)null) ? ((Object)item.m_dropPrefab).name : string.Empty);
				if (excluded.Contains(Normalize(value)) || excluded.Contains(Normalize(item.m_shared.m_name)) || excluded.Contains(Normalize(Localization.instance.Localize(item.m_shared.m_name))))
				{
					stats.SkippedExcluded++;
					return false;
				}
			}
			return true;
		}

		private static void EnsureExtraSlotsIntegration()
		{
			if (_extraSlotsSearched && (_extraSlotsFound || (Object)(object)Player.m_localPlayer != (Object)null))
			{
				return;
			}
			_extraSlotsSearched = true;
			try
			{
				Type type = Type.GetType("ExtraSlots.API, ExtraSlots");
				if (type == null)
				{
					Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
					foreach (Assembly assembly in assemblies)
					{
						if (string.Equals(assembly.GetName().Name, "ExtraSlots", StringComparison.OrdinalIgnoreCase))
						{
							type = assembly.GetType("ExtraSlots.API");
							break;
						}
					}
				}
				if (type != null)
				{
					MethodInfo method = type.GetMethod("IsItemInSlot", BindingFlags.Static | BindingFlags.Public, null, new Type[1] { typeof(ItemData) }, null);
					if (method != null)
					{
						_extraSlotsIsItemInSlot = (Func<ItemData, bool>)Delegate.CreateDelegate(typeof(Func<ItemData, bool>), method);
						_extraSlotsFound = true;
						QuickStackPlugin.Log.LogInfo((object)"[QuickStackToChests] Подключена интеграция с ExtraSlots: защита слотов еды, спеллов, стрел и экипировки активна.");
					}
				}
			}
			catch (Exception ex)
			{
				QuickStackPlugin.Log.LogWarning((object)("[QuickStackToChests] Ошибка привязки к ExtraSlots.API: " + ex.Message));
			}
		}

		private static bool IsExtraSlotItem(ItemData item)
		{
			if (item == null)
			{
				return false;
			}
			if (_extraSlotsIsItemInSlot != null)
			{
				try
				{
					if (_extraSlotsIsItemInSlot(item))
					{
						return true;
					}
				}
				catch
				{
				}
			}
			if (item.m_customData != null && item.m_customData.Count > 0 && (item.m_customData.ContainsKey("ExtraSlotsEquippedSlot") || item.m_customData.ContainsKey("eaqs_slot") || item.m_customData.ContainsKey("ExtendedInventory") || item.m_customData.ContainsKey("QuickSlots") || item.m_customData.ContainsKey("AzuEPI_Slot")))
			{
				return true;
			}
			return false;
		}

		private static void EnsureBackpacksIntegration()
		{
			if (!_sbIntegrated && _backpackSearchAttempts < 10)
			{
				try
				{
					Type type = Type.GetType("Backpacks.API, Backpacks");
					if (type == null)
					{
						Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
						foreach (Assembly assembly in assemblies)
						{
							if (string.Equals(assembly.GetName().Name, "Backpacks", StringComparison.OrdinalIgnoreCase))
							{
								type = assembly.GetType("Backpacks.API");
								break;
							}
						}
					}
					if (type != null)
					{
						MethodInfo getAll = type.GetMethod("GetAllBackpackInventories", BindingFlags.Static | BindingFlags.Public, null, new Type[1] { typeof(Inventory) }, null);
						if (getAll != null)
						{
							_sbGetAllBackpacks = (Inventory inv) => getAll.Invoke(null, new object[1] { inv }) as IEnumerable<Inventory>;
						}
						MethodInfo getEquipped = type.GetMethod("GetEquippedBackpackInventory", BindingFlags.Static | BindingFlags.Public, null, Type.EmptyTypes, null);
						if (getEquipped != null)
						{
							_sbGetEquippedBackpack = delegate
							{
								object? obj = getEquipped.Invoke(null, null);
								return (Inventory)((obj is Inventory) ? obj : null);
							};
						}
						if (_sbGetAllBackpacks != null || _sbGetEquippedBackpack != null)
						{
							_sbIntegrated = true;
							QuickStackPlugin.Log.LogInfo((object)"[QuickStackToChests] Подключена интеграция с Smoothbrain Backpacks: перенос предметов из рюкзаков активен.");
						}
					}
				}
				catch (Exception ex)
				{
					QuickStackPlugin.Log.LogWarning((object)("[QuickStackToChests] Ошибка интеграции с Smoothbrain Backpacks: " + ex.Message));
				}
			}
			if (!_rfIntegrated && _backpackSearchAttempts < 10)
			{
				try
				{
					Type type2 = null;
					Type type3 = null;
					Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
					foreach (Assembly assembly2 in assemblies)
					{
						if (string.Equals(assembly2.GetName().Name, "ReefPacks", StringComparison.OrdinalIgnoreCase))
						{
							type2 = assembly2.GetType("ReefPacks.PackUi");
							type3 = assembly2.GetType("ReefPacks.PackData");
							break;
						}
					}
					if (type2 != null && type3 != null)
					{
						MethodInfo wornMethod = type2.GetMethod("WornPack", BindingFlags.Static | BindingFlags.Public, null, new Type[1] { typeof(Player) }, null);
						MethodInfo getMethod = type3.GetMethod("Get", BindingFlags.Static | BindingFlags.Public, null, new Type[1] { typeof(ItemData) }, null);
						FieldInfo field = type3.GetField("Inv", BindingFlags.Instance | BindingFlags.Public);
						if (wornMethod != null && getMethod != null && field != null)
						{
							_rfWornPack = delegate(Player p)
							{
								object? obj = wornMethod.Invoke(null, new object[1] { p });
								return (ItemData)((obj is ItemData) ? obj : null);
							};
							_rfGetPackData = (ItemData item) => getMethod.Invoke(null, new object[1] { item });
							_rfPackInvField = field;
							_rfIntegrated = true;
							QuickStackPlugin.Log.LogInfo((object)"[QuickStackToChests] Подключена интеграция с ReefPacks: перенос предметов из рюкзака активен.");
						}
					}
				}
				catch (Exception ex2)
				{
					QuickStackPlugin.Log.LogWarning((object)("[QuickStackToChests] Ошибка интеграции с ReefPacks: " + ex2.Message));
				}
			}
			if (!_sbIntegrated || !_rfIntegrated)
			{
				_backpackSearchAttempts++;
			}
		}

		private static List<Inventory> GetBackpackInventories(Player player, Inventory playerInventory)
		{
			List<Inventory> list = new List<Inventory>();
			HashSet<Inventory> hashSet = new HashSet<Inventory>();
			EnsureBackpacksIntegration();
			if (_sbGetAllBackpacks != null && playerInventory != null)
			{
				try
				{
					IEnumerable<Inventory> enumerable = _sbGetAllBackpacks(playerInventory);
					if (enumerable != null)
					{
						foreach (Inventory item in enumerable)
						{
							if (item != null && hashSet.Add(item))
							{
								list.Add(item);
							}
						}
					}
				}
				catch (Exception ex)
				{
					QuickStackPlugin.Log.LogWarning((object)("[QuickStackToChests] Ошибка вызова GetAllBackpackInventories: " + ex.Message));
				}
			}
			if (_sbGetEquippedBackpack != null)
			{
				try
				{
					Inventory val = _sbGetEquippedBackpack();
					if (val != null && hashSet.Add(val))
					{
						list.Add(val);
					}
				}
				catch (Exception ex2)
				{
					QuickStackPlugin.Log.LogWarning((object)("[QuickStackToChests] Ошибка вызова GetEquippedBackpackInventory: " + ex2.Message));
				}
			}
			if (_rfWornPack != null && _rfGetPackData != null && _rfPackInvField != null && (Object)(object)player != (Object)null)
			{
				try
				{
					ItemData val2 = _rfWornPack(player);
					if (val2 != null)
					{
						object obj = _rfGetPackData(val2);
						if (obj != null)
						{
							object? value = _rfPackInvField.GetValue(obj);
							Inventory val3 = (Inventory)((value is Inventory) ? value : null);
							if (val3 != null && hashSet.Add(val3))
							{
								list.Add(val3);
							}
						}
					}
				}
				catch (Exception ex3)
				{
					QuickStackPlugin.Log.LogWarning((object)("[QuickStackToChests] Ошибка получения инвентаря ReefPacks: " + ex3.Message));
				}
			}
			return list;
		}

		private static bool IsSameItem(ItemData a, ItemData b)
		{
			if (a == null || b == null || a.m_shared == null || b.m_shared == null)
			{
				return false;
			}
			if (a == b)
			{
				return false;
			}
			if (a.m_shared.m_name != b.m_shared.m_name)
			{
				return false;
			}
			if (a.m_quality != b.m_quality || a.m_variant != b.m_variant)
			{
				return false;
			}
			if (QuickStackPlugin.StrictWorldLevelMatch.Value && WorldLevelField != null)
			{
				object? value = WorldLevelField.GetValue(a);
				object value2 = WorldLevelField.GetValue(b);
				if (!object.Equals(value, value2))
				{
					return false;
				}
			}
			return true;
		}

		private static int StackItemIntoContainer(Inventory from, Inventory to, ItemData item, Stats stats, Container container)
		{
			if (!to.GetAllItems().Any((ItemData existing) => IsSameItem(existing, item)))
			{
				stats.NoMatchInChests++;
				stats.NoMatchNames.Add(ItemLabel(item));
				return 0;
			}
			int num = 0;
			bool flag = false;
			foreach (ItemData item2 in (from existing in to.GetAllItems()
				where IsSameItem(existing, item) && existing.m_stack < existing.m_shared.m_maxStackSize
				select existing).ToList())
			{
				if (item.m_stack <= 0 || !from.ContainsItem(item))
				{
					break;
				}
				int num2 = item2.m_shared.m_maxStackSize - item2.m_stack;
				if (num2 > 0)
				{
					int amount = Mathf.Min(num2, item.m_stack);
					flag = true;
					int num3 = MoveStack(from, to, item, amount, item2.m_gridPos.x, item2.m_gridPos.y);
					if (num3 > 0)
					{
						num += num3;
						continue;
					}
					stats.MoveFailed++;
					stats.FailedNames.Add(ItemLabel(item));
				}
			}
			if (QuickStackPlugin.FillEmptySlots.Value)
			{
				int num4 = 0;
				while (item.m_stack > 0 && from.ContainsItem(item) && num4++ < 64)
				{
					if (!FindEmptySlot(to, out var x, out var y))
					{
						if (item.m_stack > 0)
						{
							stats.MatchedButFull++;
							stats.FullNames.Add(ItemLabel(item));
						}
						break;
					}
					int amount2 = Mathf.Min(item.m_stack, Mathf.Max(1, item.m_shared.m_maxStackSize));
					flag = true;
					int num5 = MoveStack(from, to, item, amount2, x, y);
					if (num5 <= 0)
					{
						stats.MoveFailed++;
						stats.FailedNames.Add(ItemLabel(item));
						break;
					}
					num += num5;
				}
			}
			else if (num == 0 && !flag)
			{
				stats.MatchedButFull++;
				stats.FullNames.Add(ItemLabel(item));
			}
			if (num > 0 && QuickStackPlugin.VerboseLog.Value)
			{
				QuickStackPlugin.Log.LogInfo((object)$"[quickstack] {ItemLabel(item)} -> {((Object)container).name}: {num} шт.");
			}
			return num;
		}

		private static int MoveStack(Inventory from, Inventory to, ItemData item, int amount, int x, int y)
		{
			if (amount <= 0)
			{
				return 0;
			}
			string name = item.m_shared.m_name;
			int num = CountByName(to, name);
			if (MoveItemToThisMethod != null)
			{
				try
				{
					MoveItemToThisMethod.Invoke(to, new object[5] { from, item, amount, x, y });
					int num2 = CountByName(to, name) - num;
					if (num2 > 0)
					{
						return num2;
					}
				}
				catch (Exception ex)
				{
					QuickStackPlugin.Log.LogWarning((object)("MoveItemToThis недоступен (" + ex.Message + "), переключаюсь на ручной перенос."));
				}
			}
			if (MoveStackFallback(from, to, item, amount, x, y))
			{
				int num3 = CountByName(to, name) - num;
				if (num3 <= 0)
				{
					return amount;
				}
				return num3;
			}
			return 0;
		}

		private static int CountByName(Inventory inventory, string sharedName)
		{
			int num = 0;
			foreach (ItemData allItem in inventory.GetAllItems())
			{
				if (allItem != null && allItem.m_shared != null && allItem.m_shared.m_name == sharedName)
				{
					num += allItem.m_stack;
				}
			}
			return num;
		}

		private static bool MoveStackFallback(Inventory from, Inventory to, ItemData item, int amount, int x, int y)
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			ItemData itemAt = to.GetItemAt(x, y);
			if (itemAt != null)
			{
				if (!IsSameItem(itemAt, item))
				{
					return false;
				}
				if (itemAt.m_shared.m_maxStackSize - itemAt.m_stack < amount)
				{
					return false;
				}
				itemAt.m_stack += amount;
			}
			else
			{
				ItemData val = item.Clone();
				val.m_stack = amount;
				val.m_gridPos = new Vector2i(x, y);
				if (!to.AddItem(val))
				{
					return false;
				}
			}
			from.RemoveItem(item, amount);
			return true;
		}

		private static bool FindEmptySlot(Inventory inventory, out int x, out int y)
		{
			int width = inventory.GetWidth();
			int height = inventory.GetHeight();
			for (int i = 0; i < height; i++)
			{
				for (int j = 0; j < width; j++)
				{
					if (inventory.GetItemAt(j, i) == null)
					{
						x = j;
						y = i;
						return true;
					}
				}
			}
			x = -1;
			y = -1;
			return false;
		}

		private static string ItemLabel(ItemData item)
		{
			if (item == null || item.m_shared == null)
			{
				return "?";
			}
			string text = item.m_shared.m_name;
			try
			{
				if (Localization.instance != null)
				{
					text = Localization.instance.Localize(text);
				}
			}
			catch
			{
			}
			if (item.m_quality <= 1)
			{
				return text;
			}
			return $"{text} (ур.{item.m_quality})";
		}

		private static HashSet<string> ParseList(string raw)
		{
			HashSet<string> hashSet = new HashSet<string>();
			if (string.IsNullOrEmpty(raw))
			{
				return hashSet;
			}
			string[] array = raw.Split(new char[1] { ',' });
			for (int i = 0; i < array.Length; i++)
			{
				string text = Normalize(array[i]);
				if (text.Length > 0)
				{
					hashSet.Add(text);
				}
			}
			return hashSet;
		}

		private static string Normalize(string value)
		{
			if (!string.IsNullOrEmpty(value))
			{
				return value.Trim().ToLowerInvariant();
			}
			return string.Empty;
		}

		private static void Message(Player player, string text)
		{
			if (QuickStackPlugin.ShowMessage.Value && !((Object)(object)player == (Object)null))
			{
				((Character)player).Message((MessageType)2, text, 0, (Sprite)null, false);
			}
		}
	}
	public static class TeleportFixer
	{
		private static readonly FieldInfo FieldTeleporting = typeof(Player).GetField("m_teleporting", BindingFlags.Instance | BindingFlags.NonPublic);

		private static readonly FieldInfo FieldTeleportTimer = typeof(Player).GetField("m_teleportTimer", BindingFlags.Instance | BindingFlags.NonPublic);

		private static readonly FieldInfo FieldTeleportCooldown = typeof(Player).GetField("m_teleportCooldown", BindingFlags.Instance | BindingFlags.NonPublic);

		private static readonly FieldInfo FieldTeleportFromPos = typeof(Player).GetField("m_teleportFromPos", BindingFlags.Instance | BindingFlags.NonPublic);

		private static readonly FieldInfo FieldTeleportFromRot = typeof(Player).GetField("m_teleportFromRot", BindingFlags.Instance | BindingFlags.NonPublic);

		private static readonly FieldInfo FieldTeleportTargetPos = typeof(Player).GetField("m_teleportTargetPos", BindingFlags.Instance | BindingFlags.NonPublic);

		private static readonly FieldInfo FieldTeleportTargetRot = typeof(Player).GetField("m_teleportTargetRot", BindingFlags.Instance | BindingFlags.NonPublic);

		private static readonly FieldInfo FieldMaxAirAltitude = typeof(Character).GetField("m_maxAirAltitude", BindingFlags.Instance | BindingFlags.NonPublic);

		public static bool IsPlayerStuckInTeleport()
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return false;
			}
			bool flag = false;
			flag = ((!(FieldTeleporting != null)) ? ((Character)localPlayer).IsTeleporting() : ((bool)FieldTeleporting.GetValue(localPlayer)));
			bool flag2 = (Object)(object)Hud.instance != (Object)null && (Object)(object)Hud.instance.m_loadingScreen != (Object)null && ((Component)Hud.instance.m_loadingScreen).gameObject.activeSelf;
			bool flag3 = (Object)(object)Hud.instance != (Object)null && (Object)(object)Hud.instance.m_teleportingProgress != (Object)null && Hud.instance.m_teleportingProgress.activeSelf;
			return flag || flag2 || flag3;
		}

		public static bool UnstickTeleport(bool returnToOrigin = false)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: 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_005b: 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_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: 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)
			//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_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: 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_010c: 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_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: 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_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_025c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0376: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return false;
			}
			if (!IsPlayerStuckInTeleport())
			{
				QuickStackPlugin.Log.LogInfo((object)"[QuickStackToChests] TeleportFixer: player is not teleporting, skipping unstick.");
				return false;
			}
			try
			{
				Vector3 val = Vector3.zero;
				Quaternion val2 = Quaternion.identity;
				Vector3 val3 = Vector3.zero;
				Quaternion val4 = Quaternion.identity;
				if (FieldTeleportFromPos != null)
				{
					val = (Vector3)FieldTeleportFromPos.GetValue(localPlayer);
				}
				if (FieldTeleportFromRot != null)
				{
					val2 = (Quaternion)FieldTeleportFromRot.GetValue(localPlayer);
				}
				if (FieldTeleportTargetPos != null)
				{
					val3 = (Vector3)FieldTeleportTargetPos.GetValue(localPlayer);
				}
				if (FieldTeleportTargetRot != null)
				{
					val4 = (Quaternion)FieldTeleportTargetRot.GetValue(localPlayer);
				}
				Vector3 val5 = ((Component)localPlayer).transform.position;
				Quaternion rotation = ((Component)localPlayer).transform.rotation;
				if (returnToOrigin && val != Vector3.zero)
				{
					val5 = val;
					rotation = val2;
				}
				else if (val3 != Vector3.zero)
				{
					Vector3 val6 = ((Component)localPlayer).transform.position - val3;
					if (((Vector3)(ref val6)).sqrMagnitude > 4f)
					{
						val5 = val3;
						rotation = val4;
					}
				}
				if ((Object)(object)ZoneSystem.instance != (Object)null && val5 != Vector3.zero)
				{
					float num = 0f;
					if (ZoneSystem.instance.FindFloor(val5, ref num))
					{
						val5.y = num + 0.15f;
					}
					else
					{
						float solidHeight = ZoneSystem.instance.GetSolidHeight(val5);
						if (solidHeight > -100f && solidHeight < 5000f)
						{
							val5.y = solidHeight + 0.5f;
						}
					}
				}
				if (val5 != Vector3.zero)
				{
					((Component)localPlayer).transform.position = val5;
					((Component)localPlayer).transform.rotation = rotation;
				}
				Rigidbody component = ((Component)localPlayer).GetComponent<Rigidbody>();
				if ((Object)(object)component != (Object)null)
				{
					component.velocity = Vector3.zero;
					component.angularVelocity = Vector3.zero;
				}
				if (FieldTeleporting != null)
				{
					FieldTeleporting.SetValue(localPlayer, false);
				}
				if (FieldTeleportTimer != null)
				{
					FieldTeleportTimer.SetValue(localPlayer, 0f);
				}
				if (FieldTeleportCooldown != null)
				{
					FieldTeleportCooldown.SetValue(localPlayer, 4f);
				}
				if (FieldMaxAirAltitude != null)
				{
					FieldMaxAirAltitude.SetValue(localPlayer, val5.y);
				}
				((Character)localPlayer).ResetCloth();
				if ((Object)(object)EnvMan.instance != (Object)null)
				{
					EnvMan.instance.ForceInstantEnvironmentSwitch();
				}
				if ((Object)(object)Hud.instance != (Object)null)
				{
					if ((Object)(object)Hud.instance.m_loadingScreen != (Object)null)
					{
						Hud.instance.m_loadingScreen.alpha = 0f;
						((Component)Hud.instance.m_loadingScreen).gameObject.SetActive(false);
					}
					if ((Object)(object)Hud.instance.m_teleportingProgress != (Object)null)
					{
						Hud.instance.m_teleportingProgress.SetActive(false);
					}
					if ((Object)(object)Hud.instance.m_loadingProgress != (Object)null)
					{
						Hud.instance.m_loadingProgress.SetActive(false);
					}
					if ((Object)(object)Hud.instance.m_sleepingProgress != (Object)null)
					{
						Hud.instance.m_sleepingProgress.SetActive(false);
					}
				}
				string text = (returnToOrigin ? Translations.Text("Teleport cancelled: returned to source portal", "Телепортация отменена: возврат к исходному порталу") : Translations.Text("Teleport unstick applied successfully!", "Телепортация успешно разбагована!"));
				((Character)localPlayer).Message((MessageType)2, text, 0, (Sprite)null, false);
				QuickStackPlugin.Log.LogInfo((object)$"[QuickStackToChests] TeleportFixer: Unstick applied at {val5} (returnToOrigin: {returnToOrigin}).");
				return true;
			}
			catch (Exception arg)
			{
				QuickStackPlugin.Log.LogError((object)$"[QuickStackToChests] TeleportFixer failed: {arg}");
				return false;
			}
		}
	}
	internal static class Translations
	{
		internal static bool IsRussian
		{
			get
			{
				try
				{
					return Localization.instance != null && string.Equals(Localization.instance.GetSelectedLanguage(), "Russian", StringComparison.OrdinalIgnoreCase);
				}
				catch
				{
					return false;
				}
			}
		}

		internal static string NoNearbyChests => Text("No accessible chests nearby", "Рядом нет доступных сундуков");

		internal static string NothingToStack => Text("Nothing to stack", "Нечего раскладывать");

		internal static string Text(string english, string russian)
		{
			if (!IsRussian)
			{
				return english;
			}
			return russian;
		}

		internal static string Stacked(int items, int chests)
		{
			return Text($"Stacked {items} item(s) into {chests} chest(s)", $"Разложено {items} шт. по {chests} сундукам");
		}
	}
}