Decompiled source of NomadTent v1.1.1

plugins\NomadTent.dll

Decompiled 2 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
[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 NomadTent
{
	[BepInPlugin("com.ethicalinfant.nomadtent", "NomadTent", "1.1.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGUID = "com.ethicalinfant.nomadtent";

		public const string PluginName = "NomadTent";

		public const string PluginVersion = "1.1.1";

		public static ConfigEntry<KeyCode> PackUpKey;

		public static ConfigEntry<float> TentRadius;

		private Harmony _harmony;

		public static Plugin Instance { get; private set; }

		public static ManualLogSource Log => ((BaseUnityPlugin)Instance).Logger;

		private void Awake()
		{
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Expected O, but got Unknown
			Instance = this;
			PackUpKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("Controls", "PackUpKey", (KeyCode)113, "Hotkey to pack up your pitched Nomad Tent when standing inside its radius (Shift + E also works).");
			TentRadius = ((BaseUnityPlugin)this).Config.Bind<float>("General", "TentRadius", 8f, "Radius in meters around the central Ward where pack-up and station protection apply.");
			PrefabManager.OnVanillaPrefabsAvailable += RegisterNomadTentKit;
			ItemManager.OnItemsRegistered += BindWorkbenchRecipe;
			_harmony = new Harmony("com.ethicalinfant.nomadtent");
			_harmony.PatchAll();
		}

		private void OnDestroy()
		{
			PrefabManager.OnVanillaPrefabsAvailable -= RegisterNomadTentKit;
			ItemManager.OnItemsRegistered -= BindWorkbenchRecipe;
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}

		private void Update()
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)Player.m_localPlayer == (Object)null) && Object.op_Implicit((Object)(object)ZNetScene.instance) && !Console.IsVisible() && !TextInput.IsVisible() && !Menu.IsVisible() && !Minimap.IsOpen() && !InventoryGui.IsVisible())
			{
				bool keyDown = Input.GetKeyDown(PackUpKey.Value);
				bool flag = (Input.GetKey((KeyCode)304) || Input.GetKey((KeyCode)303)) && ZInput.GetButtonDown("Use");
				if (keyDown || flag)
				{
					TentManager.TryPackUpNearestOwnedTent(Player.m_localPlayer);
				}
			}
		}

		private void RegisterNomadTentKit()
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Expected O, but got Unknown
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Expected O, but got Unknown
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Expected O, but got Unknown
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!((Object)(object)PrefabManager.Instance.GetPrefab("NomadTentKit") != (Object)null))
				{
					ItemConfig val = new ItemConfig();
					val.Name = "Nomad Tent Kit";
					val.Description = "A compact, upgradeable nomadic shelter. Use to pitch camp; press Q or Shift+E inside to pack up with all stored gear.";
					val.CraftingStation = CraftingStations.Workbench;
					val.MinStationLevel = 1;
					val.Amount = 1;
					val.Requirements = (RequirementConfig[])(object)new RequirementConfig[4]
					{
						new RequirementConfig("Wood", 20, 0, true),
						new RequirementConfig("LeatherScraps", 10, 0, true),
						new RequirementConfig("DeerHide", 5, 0, true),
						new RequirementConfig("Stone", 5, 0, true)
					};
					ItemConfig val2 = val;
					GameObject prefab = PrefabManager.Instance.GetPrefab("piece_bed02");
					Piece val3 = default(Piece);
					if ((Object)(object)prefab != (Object)null && prefab.TryGetComponent<Piece>(ref val3) && (Object)(object)val3.m_icon != (Object)null)
					{
						val2.Icon = val3.m_icon;
					}
					CustomItem val4 = new CustomItem("NomadTentKit", "ShieldWood", val2);
					SharedData shared = val4.ItemDrop.m_itemData.m_shared;
					shared.m_itemType = (ItemType)2;
					shared.m_maxStackSize = 1;
					shared.m_weight = 1f;
					shared.m_movementModifier = 0f;
					shared.m_useDurability = false;
					shared.m_teleportable = true;
					ItemManager.Instance.AddItem(val4);
					Log.LogInfo((object)"Nomad Tent Kit registered successfully.");
				}
			}
			catch (Exception arg)
			{
				Log.LogError((object)$"Failed to register Nomad Tent Kit: {arg}");
			}
			finally
			{
				PrefabManager.OnVanillaPrefabsAvailable -= RegisterNomadTentKit;
			}
		}

		private void BindWorkbenchRecipe()
		{
			try
			{
				if ((Object)(object)ObjectDB.instance == (Object)null || ObjectDB.instance.m_recipes == null)
				{
					return;
				}
				PrefabManager instance = PrefabManager.Instance;
				object obj = ((instance != null) ? instance.GetPrefab("piece_workbench") : null);
				if (obj == null)
				{
					ZNetScene instance2 = ZNetScene.instance;
					obj = ((instance2 != null) ? instance2.GetPrefab("piece_workbench") : null);
				}
				GameObject val = (GameObject)obj;
				CraftingStation craftingStation = default(CraftingStation);
				if ((Object)(object)val == (Object)null || !val.TryGetComponent<CraftingStation>(ref craftingStation))
				{
					Log.LogWarning((object)"Could not find piece_workbench CraftingStation while binding NomadTentKit recipe.");
					return;
				}
				foreach (Recipe recipe in ObjectDB.instance.m_recipes)
				{
					if ((Object)(object)recipe != (Object)null && (Object)(object)recipe.m_item != (Object)null && ((Object)((Component)recipe.m_item).gameObject).name == "NomadTentKit")
					{
						recipe.m_craftingStation = craftingStation;
						recipe.m_minStationLevel = 1;
						recipe.m_enabled = true;
						Log.LogInfo((object)"Bound NomadTentKit recipe to piece_workbench.");
						return;
					}
				}
				Log.LogWarning((object)"NomadTentKit recipe not found in ObjectDB.m_recipes during BindWorkbenchRecipe.");
			}
			catch (Exception arg)
			{
				Log.LogError((object)$"Error binding NomadTentKit recipe: {arg}");
			}
		}

		public static string LoadBlueprintText(int tier)
		{
			string text = $"NomadTent_T{tier}.blueprint";
			string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? "", "blueprints", text);
			if (File.Exists(path))
			{
				return File.ReadAllText(path);
			}
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			string text2 = "NomadTent.blueprints." + text;
			using Stream stream = executingAssembly.GetManifestResourceStream(text2);
			if (stream == null)
			{
				Log.LogError((object)("Missing embedded blueprint resource: " + text2));
				return null;
			}
			using StreamReader streamReader = new StreamReader(stream);
			return streamReader.ReadToEnd();
		}
	}
	[HarmonyPatch]
	public static class StationPatches
	{
		[HarmonyPatch(typeof(Player), "ConsumeItem")]
		[HarmonyPrefix]
		public static bool Player_ConsumeItem_Prefix(Player __instance, Inventory inventory, ItemData item, ref bool __result)
		{
			if (item != null && (Object)(object)item.m_dropPrefab != (Object)null && ((Object)item.m_dropPrefab).name == "NomadTentKit")
			{
				__result = TentManager.DeployTentFromKit(__instance, item);
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(Piece), "Awake")]
		[HarmonyPostfix]
		public static void Piece_Awake_Postfix(Piece __instance)
		{
			if (!((Object)(object)__instance == (Object)null))
			{
				ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
				if (!((Object)(object)component == (Object)null) && component.IsValid() && !string.IsNullOrEmpty(component.GetZDO().GetString(TentManager.KeyTentGuid, "")))
				{
					TentManager.ConfigurePieceIndestructibleAndLights(((Component)__instance).gameObject);
				}
			}
		}

		[HarmonyPatch(typeof(PrivateArea), "GetHoverText")]
		[HarmonyPrefix]
		public static bool PrivateArea_GetHoverText_Prefix(PrivateArea __instance, ref string __result)
		{
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				return true;
			}
			if (string.IsNullOrEmpty(component.GetZDO().GetString(TentManager.KeyTentGuid, "")))
			{
				return true;
			}
			int num = Mathf.Clamp(component.GetZDO().GetInt(TentManager.KeyTentTier, 1), 1, 7);
			string text = component.GetZDO().GetString(TentManager.KeyTentOwnerName, "Nomad");
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine($"<color=orange>Nomad Tent (Tier {num}/{7})</color>");
			stringBuilder.AppendLine("Owner: " + text);
			if (num < 7)
			{
				UpgradeRequirement[] upgradeCost = TentTierConfig.GetUpgradeCost(num);
				stringBuilder.AppendLine($"[<color=yellow>E</color>] Upgrade to Tier {num + 1}:");
				UpgradeRequirement[] array = upgradeCost;
				for (int i = 0; i < array.Length; i++)
				{
					UpgradeRequirement upgradeRequirement = array[i];
					stringBuilder.AppendLine($"  • {upgradeRequirement.Amount}x {upgradeRequirement.DisplayName}");
				}
			}
			else
			{
				stringBuilder.AppendLine("<color=green>Max Tier Reached</color>");
			}
			stringBuilder.AppendLine($"[<color=yellow>{Plugin.PackUpKey.Value}</color> / <color=yellow>Shift+E</color>] Pack Up Tent");
			__result = stringBuilder.ToString();
			return false;
		}

		[HarmonyPatch(typeof(PrivateArea), "Interact")]
		[HarmonyPrefix]
		public static bool PrivateArea_Interact_Prefix(PrivateArea __instance, Humanoid human, bool hold, ref bool __result)
		{
			if (hold)
			{
				return true;
			}
			ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				return true;
			}
			if (string.IsNullOrEmpty(component.GetZDO().GetString(TentManager.KeyTentGuid, "")))
			{
				return true;
			}
			Player val = (Player)(object)((human is Player) ? human : null);
			if (val != null)
			{
				TentManager.TryUpgradeTent(val, component);
			}
			__result = true;
			return false;
		}

		[HarmonyPatch(typeof(CraftingStation), "GetLevel")]
		[HarmonyPostfix]
		public static void CraftingStation_GetLevel_Postfix(CraftingStation __instance, ref int __result)
		{
			if ((Object)(object)__instance == (Object)null)
			{
				return;
			}
			ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
			if (!((Object)(object)component == (Object)null) && component.IsValid() && !string.IsNullOrEmpty(component.GetZDO().GetString(TentManager.KeyTentGuid, "")))
			{
				int tier = Mathf.Clamp(component.GetZDO().GetInt(TentManager.KeyTentTier, 1), 1, 7);
				switch (Utils.GetPrefabName(((Component)__instance).gameObject).ToLowerInvariant())
				{
				case "piece_workbench":
					__result = Mathf.Max(__result, TentTierConfig.GetEffectiveWorkbenchLevel(tier));
					break;
				case "forge":
					__result = Mathf.Max(__result, TentTierConfig.GetEffectiveForgeLevel(tier));
					break;
				case "piece_cauldron":
					__result = Mathf.Max(__result, TentTierConfig.GetEffectiveCauldronLevel(tier));
					break;
				case "blackforge":
					__result = Mathf.Max(__result, TentTierConfig.GetEffectiveBlackForgeLevel(tier));
					break;
				}
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "CanRepair")]
		[HarmonyPostfix]
		public static void InventoryGui_CanRepair_Postfix(ItemData item, ref bool __result)
		{
			if (__result || item == null || (Object)(object)Player.m_localPlayer == (Object)null)
			{
				return;
			}
			CraftingStation currentCraftingStation = Player.m_localPlayer.GetCurrentCraftingStation();
			if ((Object)(object)currentCraftingStation == (Object)null)
			{
				return;
			}
			ZNetView component = ((Component)currentCraftingStation).GetComponent<ZNetView>();
			if (!((Object)(object)component == (Object)null) && component.IsValid() && !string.IsNullOrEmpty(component.GetZDO().GetString(TentManager.KeyTentGuid, "")))
			{
				int num = Mathf.Clamp(component.GetZDO().GetInt(TentManager.KeyTentTier, 1), 1, 7);
				string text = Utils.GetPrefabName(((Component)currentCraftingStation).gameObject).ToLowerInvariant();
				if (num >= 5 && text == "blackforge" && item.m_durability < item.GetMaxDurability())
				{
					__result = true;
				}
			}
		}
	}
	[HarmonyPatch]
	public static class PlayerHaveRequirementsPatch
	{
		[HarmonyTargetMethod]
		public static MethodBase TargetMethod()
		{
			return typeof(Player).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault((MethodInfo m) => m.Name == "HaveRequirements" && m.GetParameters().Length >= 3 && m.GetParameters()[0].ParameterType == typeof(Recipe));
		}

		[HarmonyPostfix]
		public static void Postfix(Player __instance, Recipe recipe, bool discover, int qualityLevel, ref bool __result)
		{
			if (__result || (Object)(object)recipe == (Object)null || (Object)(object)recipe.m_craftingStation == (Object)null)
			{
				return;
			}
			CraftingStation currentCraftingStation = __instance.GetCurrentCraftingStation();
			if ((Object)(object)currentCraftingStation == (Object)null)
			{
				return;
			}
			ZNetView component = ((Component)currentCraftingStation).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid() || string.IsNullOrEmpty(component.GetZDO().GetString(TentManager.KeyTentGuid, "")))
			{
				return;
			}
			int num = Mathf.Clamp(component.GetZDO().GetInt(TentManager.KeyTentTier, 1), 1, 7);
			if (num < 5 || Utils.GetPrefabName(((Component)currentCraftingStation).gameObject).ToLowerInvariant() != "blackforge")
			{
				return;
			}
			string text = Utils.GetPrefabName(((Component)recipe.m_craftingStation).gameObject).ToLowerInvariant();
			int requiredStationLevel = recipe.GetRequiredStationLevel(qualityLevel);
			bool flag = false;
			if (text == "piece_workbench" && TentTierConfig.GetEffectiveWorkbenchLevel(num) >= requiredStationLevel)
			{
				flag = true;
			}
			if (text == "forge" && TentTierConfig.GetEffectiveForgeLevel(num) >= requiredStationLevel)
			{
				flag = true;
			}
			if (text == "blackforge" && TentTierConfig.GetEffectiveBlackForgeLevel(num) >= requiredStationLevel)
			{
				flag = true;
			}
			if (num >= 6 && text == "piece_magetable" && TentTierConfig.GetEffectiveGaldrTableLevel(num) >= requiredStationLevel)
			{
				flag = true;
			}
			if (!flag)
			{
				return;
			}
			Requirement[] resources = recipe.m_resources;
			foreach (Requirement val in resources)
			{
				if (!((Object)(object)val.m_resItem == (Object)null))
				{
					int amount = val.GetAmount(qualityLevel);
					if (amount > 0 && ((Humanoid)__instance).GetInventory().CountItems(val.m_resItem.m_itemData.m_shared.m_name, -1, true) < amount)
					{
						return;
					}
				}
			}
			__result = true;
		}
	}
	[Serializable]
	public class SavedStandItem
	{
		public string PrefabName;

		public int Stack;

		public int Quality;

		public float Durability;

		public int Variant;

		public long CrafterID;

		public string CrafterName;

		public string CustomDataBase64;

		public Vector3 LocalPosition;
	}
	[Serializable]
	public class TentSaveState
	{
		public string TentGuid;

		public int Tier = 1;

		public string ChestBase64 = "";

		public List<SavedStandItem> StandItems = new List<SavedStandItem>();

		public List<float> SavedHeights = new List<float>();

		public Vector3 TerrainOrigin;
	}
	public struct UpgradeRequirement
	{
		public string Prefab;

		public int Amount;

		public string DisplayName;

		public UpgradeRequirement(string prefab, int amount, string displayName)
		{
			Prefab = prefab;
			Amount = amount;
			DisplayName = displayName;
		}
	}
	public static class TentTierConfig
	{
		public const int MaxTier = 7;

		public static UpgradeRequirement[] GetUpgradeCost(int currentTier)
		{
			return currentTier switch
			{
				1 => new UpgradeRequirement[5]
				{
					new UpgradeRequirement("RoundLog", 10, "Core Wood"),
					new UpgradeRequirement("Bronze", 6, "Bronze"),
					new UpgradeRequirement("TrollHide", 4, "Troll Hide"),
					new UpgradeRequirement("Thistle", 8, "Thistle"),
					new UpgradeRequirement("GreydwarfEye", 6, "Greydwarf Eyes")
				}, 
				2 => new UpgradeRequirement[5]
				{
					new UpgradeRequirement("FineWood", 10, "Fine Wood"),
					new UpgradeRequirement("Iron", 10, "Iron"),
					new UpgradeRequirement("ElderBark", 4, "Ancient Bark"),
					new UpgradeRequirement("SurtlingCore", 2, "Surtling Core"),
					new UpgradeRequirement("Entrails", 4, "Entrails")
				}, 
				3 => new UpgradeRequirement[5]
				{
					new UpgradeRequirement("Silver", 8, "Silver"),
					new UpgradeRequirement("BlackMetal", 8, "Black Metal"),
					new UpgradeRequirement("LinenThread", 4, "Linen Thread"),
					new UpgradeRequirement("Tar", 4, "Tar"),
					new UpgradeRequirement("LoxPelt", 2, "Lox Pelt")
				}, 
				4 => new UpgradeRequirement[5]
				{
					new UpgradeRequirement("BlackMarble", 10, "Black Marble"),
					new UpgradeRequirement("YggdrasilWood", 5, "Yggdrasil Wood"),
					new UpgradeRequirement("Carapace", 4, "Carapace"),
					new UpgradeRequirement("ScaleHide", 2, "Scale Hide"),
					new UpgradeRequirement("Sap", 2, "Sap")
				}, 
				5 => new UpgradeRequirement[5]
				{
					new UpgradeRequirement("Eitr", 6, "Refined Eitr"),
					new UpgradeRequirement("FlametalNew", 6, "Flametal"),
					new UpgradeRequirement("Blackwood", 6, "Ashwood"),
					new UpgradeRequirement("AskHide", 2, "Asksvin Pelt"),
					new UpgradeRequirement("CelestialFeather", 2, "Celestial Feather")
				}, 
				6 => new UpgradeRequirement[6]
				{
					new UpgradeRequirement("TimberWood", 6, "Timberwood"),
					new UpgradeRequirement("Bloodgold", 4, "Bloodgold"),
					new UpgradeRequirement("MooseHide", 2, "Moose Hide"),
					new UpgradeRequirement("SealPelt", 2, "Seal Pelt"),
					new UpgradeRequirement("Nornathread", 2, "Nornathread"),
					new UpgradeRequirement("Frostcore", 2, "Frostcore")
				}, 
				_ => Array.Empty<UpgradeRequirement>(), 
			};
		}

		public static int GetEffectiveWorkbenchLevel(int tier)
		{
			if (tier <= 1)
			{
				return 1;
			}
			return tier switch
			{
				2 => 2, 
				3 => 3, 
				_ => 4, 
			};
		}

		public static int GetEffectiveForgeLevel(int tier)
		{
			if (tier < 2)
			{
				return 0;
			}
			return tier switch
			{
				2 => 1, 
				3 => 2, 
				4 => 5, 
				_ => 7, 
			};
		}

		public static int GetEffectiveCauldronLevel(int tier)
		{
			if (tier < 2)
			{
				return 0;
			}
			return tier switch
			{
				2 => 1, 
				3 => 2, 
				4 => 3, 
				5 => 4, 
				6 => 5, 
				_ => 6, 
			};
		}

		public static int GetEffectiveBlackForgeLevel(int tier)
		{
			if (tier < 5)
			{
				return 0;
			}
			return tier switch
			{
				5 => 3, 
				6 => 4, 
				_ => 5, 
			};
		}

		public static int GetEffectiveGaldrTableLevel(int tier)
		{
			if (tier < 6)
			{
				return 0;
			}
			if (tier == 6)
			{
				return 3;
			}
			return 4;
		}
	}
	[Serializable]
	public class SavedItemData
	{
		public string PrefabName;

		public string SharedName;

		public int Stack;

		public float Durability;

		public int Quality;

		public int Variant;

		public long CrafterID;

		public string CrafterName;

		public List<string> CustomDataKeys = new List<string>();

		public List<string> CustomDataValues = new List<string>();
	}
	[Serializable]
	public class SavedContainerData
	{
		public string LocalPosKey;

		public List<SavedItemData> Items = new List<SavedItemData>();
	}
	[Serializable]
	public class TentSaveData
	{
		public string TentGuid;

		public int Tier = 1;

		public List<SavedContainerData> Containers = new List<SavedContainerData>();
	}
	public static class TentManager
	{
		public static readonly int KeyTentGuid = StringExtensionMethods.GetStableHashCode("NomadTent_Guid");

		public static readonly int KeyTentTier = StringExtensionMethods.GetStableHashCode("NomadTent_Tier");

		public static readonly int KeyTentOwnerId = StringExtensionMethods.GetStableHashCode("NomadTent_OwnerId");

		public static readonly int KeyTentOwnerName = StringExtensionMethods.GetStableHashCode("NomadTent_OwnerName");

		public static readonly int KeyTentLocalPos = StringExtensionMethods.GetStableHashCode("NomadTent_LocalPos");

		private const float DoorYawOffset = -65f;

		private const float FootprintRadius = 6f;

		private const float DeployForwardDistance = 8f;

		private const float LeftNudgeDistance = 0f;

		private static readonly Dictionary<string, string> RecentSavesByGuid = new Dictionary<string, string>();

		private static string LastPackedSavePayload = "";

		public static bool DeployTentFromKit(Player player, ItemData kitItem)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: 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_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: 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)
			//IL_00d2: 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_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: 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_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)player == (Object)null || kitItem == null || (Object)(object)ZNetScene.instance == (Object)null)
			{
				return false;
			}
			float value = Plugin.TentRadius.Value;
			Vector3 forward = ((Component)player).transform.forward;
			forward.y = 0f;
			if (((Vector3)(ref forward)).sqrMagnitude < 0.001f)
			{
				forward = Vector3.forward;
			}
			((Vector3)(ref forward)).Normalize();
			Vector3 right = ((Component)player).transform.right;
			right.y = 0f;
			if (((Vector3)(ref right)).sqrMagnitude < 0.001f)
			{
				right = Vector3.right;
			}
			((Vector3)(ref right)).Normalize();
			TentSaveData tentSaveData = ReadSaveDataFromItem(kitItem);
			if (string.IsNullOrEmpty(tentSaveData.TentGuid))
			{
				tentSaveData.TentGuid = Guid.NewGuid().ToString("N");
			}
			tentSaveData.Tier = Mathf.Clamp(tentSaveData.Tier, 1, 7);
			Quaternion val = Quaternion.LookRotation(forward, Vector3.up) * Quaternion.Euler(0f, -65f, 0f);
			Vector3 blueprintHorizontalCenterOffset = GetBlueprintHorizontalCenterOffset(tentSaveData.Tier);
			Vector3 val2 = ((Component)player).transform.position + forward * 8f - right * 0f;
			float num = ((Component)player).transform.position.y;
			if ((Object)(object)ZoneSystem.instance != (Object)null)
			{
				float waterLevel = ZoneSystem.instance.m_waterLevel;
				if (num < waterLevel + 0.35f)
				{
					num = waterLevel + 0.35f;
				}
			}
			val2.y = num;
			Vector3 center = val2 + val * blueprintHorizontalCenterOffset;
			center.y = num;
			if (IsBlockedByWardOrExistingTent(player, center, value))
			{
				return false;
			}
			RaiseAndFlattenTerrain(center, 6f, tentSaveData.TentGuid);
			ClearNaturalObstacles(center, 6f);
			if (!SpawnTentStructure(player, val2, val, tentSaveData))
			{
				((Character)player).Message((MessageType)2, "Failed to pitch Nomad Tent.", 0, (Sprite)null, false);
				return false;
			}
			ConsumeKitItem(player, kitItem);
			((Character)player).Message((MessageType)2, $"Nomad Tent (Tier {tentSaveData.Tier}) pitched!", 0, (Sprite)null, false);
			return true;
		}

		private static void ConsumeKitItem(Player player, ItemData kitItem)
		{
			if (!((Object)(object)player == (Object)null) && kitItem != null)
			{
				Inventory inventory = ((Humanoid)player).GetInventory();
				if (inventory != null)
				{
					inventory.RemoveItem(kitItem, 1);
				}
			}
		}

		private static Vector3 GetBlueprintHorizontalCenterOffset(int tier)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			string text = Plugin.LoadBlueprintText(tier);
			if (string.IsNullOrEmpty(text))
			{
				return Vector3.zero;
			}
			float num = float.MaxValue;
			float num2 = float.MinValue;
			float num3 = float.MaxValue;
			float num4 = float.MinValue;
			int num5 = 0;
			float num6 = float.MaxValue;
			float num7 = float.MinValue;
			float num8 = float.MaxValue;
			float num9 = float.MinValue;
			int num10 = 0;
			string[] array = text.Split(new char[2] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
			for (int i = 0; i < array.Length; i++)
			{
				string text2 = array[i].Trim();
				if (string.IsNullOrEmpty(text2) || text2.StartsWith("#"))
				{
					continue;
				}
				string[] array2 = text2.Split(new char[1] { ';' });
				if (array2.Length < 5)
				{
					continue;
				}
				float num11 = ParseFloat(array2[2]);
				float num12 = ParseFloat(array2[3]);
				float num13 = ParseFloat(array2[4]);
				if (num11 < num6)
				{
					num6 = num11;
				}
				if (num11 > num7)
				{
					num7 = num11;
				}
				if (num13 < num8)
				{
					num8 = num13;
				}
				if (num13 > num9)
				{
					num9 = num13;
				}
				num10++;
				if (num12 <= 1.25f)
				{
					if (num11 < num)
					{
						num = num11;
					}
					if (num11 > num2)
					{
						num2 = num11;
					}
					if (num13 < num3)
					{
						num3 = num13;
					}
					if (num13 > num4)
					{
						num4 = num13;
					}
					num5++;
				}
			}
			if (num5 > 0)
			{
				return new Vector3((num + num2) * 0.5f, 0f, (num3 + num4) * 0.5f);
			}
			if (num10 > 0)
			{
				return new Vector3((num6 + num7) * 0.5f, 0f, (num8 + num9) * 0.5f);
			}
			return Vector3.zero;
		}

		private static bool IsBlockedByWardOrExistingTent(Player player, Vector3 center, float radius)
		{
			//IL_006f: 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_0043: Unknown result type (might be due to invalid IL or missing references)
			ZNetView[] array = Object.FindObjectsByType<ZNetView>((FindObjectsSortMode)0);
			foreach (ZNetView val in array)
			{
				if (!((Object)(object)val == (Object)null) && val.IsValid() && !string.IsNullOrEmpty(val.GetZDO().GetString(KeyTentGuid, "")) && Vector3.Distance(center, ((Component)val).transform.position) < 9f)
				{
					((Character)player).Message((MessageType)2, "Too close to another pitched Nomad Tent.", 0, (Sprite)null, false);
					return true;
				}
			}
			if (!PrivateArea.CheckAccess(center, 6f, true, true))
			{
				((Character)player).Message((MessageType)2, "Blocked by a nearby Ward.", 0, (Sprite)null, false);
				return true;
			}
			return false;
		}

		public static void RaiseAndFlattenTerrain(Vector3 center, float radius, string tentGuid = "")
		{
			//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_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				string obj = (string.IsNullOrEmpty(tentGuid) ? "NomadTent_TerrainModifier" : ("NomadTent_TerrainModifier_" + tentGuid));
				GameObject val = GameObject.Find(obj);
				if ((Object)(object)val != (Object)null)
				{
					Object.Destroy((Object)(object)val);
				}
				GameObject val2 = new GameObject(obj);
				val2.transform.position = center;
				TerrainModifier obj2 = val2.AddComponent<TerrainModifier>();
				obj2.m_level = true;
				obj2.m_levelRadius = radius;
				obj2.m_levelOffset = 0f;
				obj2.m_smooth = true;
				obj2.m_smoothRadius = radius + 2f;
				obj2.m_smoothPower = 0.85f;
				obj2.m_paintCleared = true;
				obj2.m_paintType = (PaintType)0;
				obj2.m_paintRadius = radius;
				obj2.m_playerModifiction = true;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Terrain leveling warning: " + ex.Message));
			}
		}

		public static void RestoreTerrain(Vector3 center, float radius, string tentGuid = "")
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!string.IsNullOrEmpty(tentGuid))
				{
					GameObject val = GameObject.Find("NomadTent_TerrainModifier_" + tentGuid);
					if ((Object)(object)val != (Object)null)
					{
						Object.Destroy((Object)(object)val);
					}
				}
				if ((Object)(object)ClutterSystem.instance != (Object)null)
				{
					ClutterSystem.instance.ResetGrass(center, radius + 1f);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Terrain restore warning: " + ex.Message));
			}
		}

		private static void ClearNaturalObstacles(Vector3 center, float radius)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			Collider[] array = Physics.OverlapSphere(center, radius);
			foreach (Collider val in array)
			{
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				TreeBase componentInParent = ((Component)val).GetComponentInParent<TreeBase>();
				if ((Object)(object)componentInParent != (Object)null)
				{
					ZNetView component = ((Component)componentInParent).GetComponent<ZNetView>();
					if ((Object)(object)component != (Object)null && component.IsValid())
					{
						component.ClaimOwnership();
						component.Destroy();
					}
					continue;
				}
				TreeLog componentInParent2 = ((Component)val).GetComponentInParent<TreeLog>();
				if ((Object)(object)componentInParent2 != (Object)null)
				{
					ZNetView component2 = ((Component)componentInParent2).GetComponent<ZNetView>();
					if ((Object)(object)component2 != (Object)null && component2.IsValid())
					{
						component2.ClaimOwnership();
						component2.Destroy();
					}
					continue;
				}
				Destructible componentInParent3 = ((Component)val).GetComponentInParent<Destructible>();
				if ((Object)(object)componentInParent3 != (Object)null && (Object)(object)((Component)componentInParent3).GetComponentInParent<Piece>() == (Object)null && (Object)(object)((Component)componentInParent3).GetComponentInParent<Character>() == (Object)null)
				{
					ZNetView component3 = ((Component)componentInParent3).GetComponent<ZNetView>();
					if ((Object)(object)component3 != (Object)null && component3.IsValid())
					{
						component3.ClaimOwnership();
						component3.Destroy();
					}
				}
			}
		}

		private static bool SpawnTentStructure(Player player, Vector3 anchorPos, Quaternion anchorRot, TentSaveData saveData)
		{
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: 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)
			string text = Plugin.LoadBlueprintText(saveData.Tier);
			if (string.IsNullOrEmpty(text))
			{
				return false;
			}
			long playerID = player.GetPlayerID();
			string playerName = player.GetPlayerName();
			List<KeyValuePair<string, Container>> list = new List<KeyValuePair<string, Container>>();
			string[] array = text.Split(new char[2] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
			Vector3 val = default(Vector3);
			Quaternion val2 = default(Quaternion);
			for (int i = 0; i < array.Length; i++)
			{
				string text2 = array[i].Trim();
				if (string.IsNullOrEmpty(text2) || text2.StartsWith("#"))
				{
					continue;
				}
				string[] array2 = text2.Split(new char[1] { ';' });
				if (array2.Length < 9)
				{
					continue;
				}
				string text3 = array2[0].Trim();
				GameObject prefab = ZNetScene.instance.GetPrefab(text3);
				if ((Object)(object)prefab == (Object)null)
				{
					Plugin.Log.LogWarning((object)("Blueprint prefab '" + text3 + "' not found in ZNetScene; skipping."));
					continue;
				}
				((Vector3)(ref val))..ctor(ParseFloat(array2[2]), ParseFloat(array2[3]), ParseFloat(array2[4]));
				((Quaternion)(ref val2))..ctor(ParseFloat(array2[5]), ParseFloat(array2[6]), ParseFloat(array2[7]), ParseFloat(array2[8]));
				Vector3 val3 = anchorPos + anchorRot * val;
				Quaternion val4 = anchorRot * val2;
				GameObject val5 = Object.Instantiate<GameObject>(prefab, val3, val4);
				string text4 = FormatPosKey(val);
				ZNetView[] componentsInChildren = val5.GetComponentsInChildren<ZNetView>(true);
				foreach (ZNetView val6 in componentsInChildren)
				{
					if ((Object)(object)val6 != (Object)null && val6.IsValid())
					{
						val6.ClaimOwnership();
						val6.GetZDO().Set(KeyTentGuid, saveData.TentGuid);
						val6.GetZDO().Set(KeyTentTier, saveData.Tier, false);
						val6.GetZDO().Set(KeyTentOwnerId, playerID);
						val6.GetZDO().Set(KeyTentOwnerName, playerName);
						val6.GetZDO().Set(KeyTentLocalPos, text4);
					}
				}
				ZNetView component = val5.GetComponent<ZNetView>();
				if ((Object)(object)component != (Object)null && component.IsValid())
				{
					PrivateArea component2 = val5.GetComponent<PrivateArea>();
					if ((Object)(object)component2 != (Object)null)
					{
						component2.m_radius = Plugin.TentRadius.Value;
						component.GetZDO().Set(ZDOVars.s_enabled, true);
					}
				}
				Container componentInChildren = val5.GetComponentInChildren<Container>();
				if ((Object)(object)componentInChildren != (Object)null)
				{
					list.Add(new KeyValuePair<string, Container>(text4, componentInChildren));
				}
				ConfigurePieceIndestructibleAndLights(val5);
			}
			RestoreAllContainers(player, saveData.Containers, list);
			return true;
		}

		private static void RestoreAllContainers(Player player, List<SavedContainerData> savedContainers, List<KeyValuePair<string, Container>> spawnedContainers)
		{
			if (savedContainers == null || savedContainers.Count == 0)
			{
				return;
			}
			HashSet<Container> usedContainers = new HashSet<Container>();
			foreach (SavedContainerData saved in savedContainers)
			{
				if (saved == null || saved.Items == null || saved.Items.Count == 0)
				{
					continue;
				}
				Container val = spawnedContainers.FirstOrDefault((KeyValuePair<string, Container> kvp) => kvp.Key == saved.LocalPosKey && !usedContainers.Contains(kvp.Value)).Value ?? spawnedContainers.FirstOrDefault((KeyValuePair<string, Container> kvp) => !usedContainers.Contains(kvp.Value)).Value ?? spawnedContainers.FirstOrDefault().Value;
				if ((Object)(object)val != (Object)null)
				{
					usedContainers.Add(val);
					RestoreContainerInventory(player, val, saved);
					continue;
				}
				foreach (SavedItemData item in saved.Items)
				{
					DropSavedItemAtPlayer(player, item);
				}
			}
		}

		public static void ConfigurePieceIndestructibleAndLights(GameObject go)
		{
			if ((Object)(object)go == (Object)null)
			{
				return;
			}
			WearNTear component = go.GetComponent<WearNTear>();
			if ((Object)(object)component != (Object)null)
			{
				component.m_noRoofWear = false;
				component.m_noSupportWear = false;
				component.m_health = 999999f;
			}
			Fireplace component2 = go.GetComponent<Fireplace>();
			if ((Object)(object)component2 != (Object)null)
			{
				component2.m_infiniteFuel = true;
				ZNetView component3 = go.GetComponent<ZNetView>();
				if ((Object)(object)component3 != (Object)null && component3.IsValid())
				{
					component3.GetZDO().Set(ZDOVars.s_fuel, component2.m_maxFuel);
				}
			}
		}

		private static GameObject FindUpgradeItemPrefab(UpgradeRequirement req)
		{
			if ((Object)(object)ObjectDB.instance == (Object)null || string.IsNullOrEmpty(req.DisplayName))
			{
				return null;
			}
			string text = req.DisplayName.Trim();
			string text2 = text.Replace(" ", "");
			GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(text2);
			if ((Object)(object)itemPrefab != (Object)null)
			{
				return itemPrefab;
			}
			string text3 = text.ToLowerInvariant();
			string text4 = text2.ToLowerInvariant();
			foreach (GameObject item in ObjectDB.instance.m_items)
			{
				if ((Object)(object)item == (Object)null)
				{
					continue;
				}
				ItemDrop component = item.GetComponent<ItemDrop>();
				if (!((Object)(object)component == (Object)null) && component.m_itemData != null && component.m_itemData.m_shared != null)
				{
					string text5 = ((Object)item).name.ToLowerInvariant();
					string text6 = component.m_itemData.m_shared.m_name ?? "";
					string text7 = (text6.StartsWith("$") ? text6.Substring(1) : text6).ToLowerInvariant();
					if (text5 == text3 || text5 == text4 || text7 == text3 || text7 == text4)
					{
						return item;
					}
				}
			}
			return null;
		}

		public static void TryUpgradeTent(Player player, ZNetView wardZnv)
		{
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: 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_01bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Unknown result type (might be due to invalid IL or missing references)
			//IL_020d: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0211: Unknown result type (might be due to invalid IL or missing references)
			//IL_0216: Unknown result type (might be due to invalid IL or missing references)
			//IL_021b: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0246: Unknown result type (might be due to invalid IL or missing references)
			//IL_0250: Unknown result type (might be due to invalid IL or missing references)
			//IL_0252: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)player == (Object)null || (Object)(object)wardZnv == (Object)null || !wardZnv.IsValid())
			{
				return;
			}
			string text = wardZnv.GetZDO().GetString(KeyTentGuid, "");
			if (string.IsNullOrEmpty(text))
			{
				return;
			}
			long num = wardZnv.GetZDO().GetLong(KeyTentOwnerId, 0L);
			if (num != 0L && num != player.GetPlayerID())
			{
				((Character)player).Message((MessageType)2, "Only the tent owner can upgrade this tent.", 0, (Sprite)null, false);
				return;
			}
			int num2 = Mathf.Clamp(wardZnv.GetZDO().GetInt(KeyTentTier, 1), 1, 7);
			if (num2 >= 7)
			{
				((Character)player).Message((MessageType)2, "Nomad Tent is already at Maximum Tier!", 0, (Sprite)null, false);
				return;
			}
			UpgradeRequirement[] upgradeCost = TentTierConfig.GetUpgradeCost(num2);
			UpgradeRequirement[] array = upgradeCost;
			for (int i = 0; i < array.Length; i++)
			{
				UpgradeRequirement req = array[i];
				GameObject val = FindUpgradeItemPrefab(req);
				if (!((Object)(object)val == (Object)null))
				{
					string name = val.GetComponent<ItemDrop>().m_itemData.m_shared.m_name;
					if (((Humanoid)player).GetInventory().CountItems(name, -1, true) < req.Amount)
					{
						((Character)player).Message((MessageType)2, $"Missing upgrade materials ({req.Amount}x {req.DisplayName}).", 0, (Sprite)null, false);
						return;
					}
				}
			}
			array = upgradeCost;
			for (int i = 0; i < array.Length; i++)
			{
				UpgradeRequirement req2 = array[i];
				GameObject val2 = FindUpgradeItemPrefab(req2);
				if (!((Object)(object)val2 == (Object)null))
				{
					string name2 = val2.GetComponent<ItemDrop>().m_itemData.m_shared.m_name;
					((Humanoid)player).GetInventory().RemoveItem(name2, req2.Amount, -1, true);
				}
			}
			Vector3 position = ((Component)wardZnv).transform.position;
			Quaternion rotation = ((Component)wardZnv).transform.rotation;
			TentSaveData tentSaveData = CollectAndDestroyTentPieces(text, num2, player);
			tentSaveData.Tier = num2 + 1;
			float num3 = position.y;
			if ((Object)(object)ZoneSystem.instance != (Object)null)
			{
				float waterLevel = ZoneSystem.instance.m_waterLevel;
				if (num3 < waterLevel + 0.35f)
				{
					num3 = waterLevel + 0.35f;
				}
			}
			position.y = num3;
			Vector3 blueprintHorizontalCenterOffset = GetBlueprintHorizontalCenterOffset(tentSaveData.Tier);
			Vector3 center = position + rotation * blueprintHorizontalCenterOffset;
			center.y = num3;
			float radius = 6f + (float)tentSaveData.Tier * 0.25f;
			RaiseAndFlattenTerrain(center, radius, text);
			ClearNaturalObstacles(center, radius);
			SpawnTentStructure(player, position, rotation, tentSaveData);
			((Character)player).Message((MessageType)2, $"Nomad Tent upgraded to Tier {tentSaveData.Tier}!", 0, (Sprite)null, false);
		}

		public static void TryPackUpNearestOwnedTent(Player player)
		{
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)player == (Object)null || (Object)(object)ZNetScene.instance == (Object)null)
			{
				return;
			}
			long playerID = player.GetPlayerID();
			float num = Plugin.TentRadius.Value + 4f;
			PrivateArea[] array = Object.FindObjectsByType<PrivateArea>((FindObjectsSortMode)0);
			PrivateArea val = null;
			float num2 = float.MaxValue;
			PrivateArea[] array2 = array;
			foreach (PrivateArea val2 in array2)
			{
				if ((Object)(object)val2 == (Object)null)
				{
					continue;
				}
				ZNetView component = ((Component)val2).GetComponent<ZNetView>();
				if ((Object)(object)component == (Object)null || !component.IsValid() || string.IsNullOrEmpty(component.GetZDO().GetString(KeyTentGuid, "")))
				{
					continue;
				}
				long num3 = component.GetZDO().GetLong(KeyTentOwnerId, 0L);
				if (num3 == 0L || num3 == playerID)
				{
					float num4 = Vector3.Distance(((Component)player).transform.position, ((Component)val2).transform.position);
					if (num4 <= num && num4 < num2)
					{
						num2 = num4;
						val = val2;
					}
				}
			}
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			ZNetView component2 = ((Component)val).GetComponent<ZNetView>();
			string tentGuid = component2.GetZDO().GetString(KeyTentGuid, "");
			int num5 = Mathf.Clamp(component2.GetZDO().GetInt(KeyTentTier, 1), 1, 7);
			Vector3 position = ((Component)val).transform.position;
			TentSaveData data = CollectAndDestroyTentPieces(tentGuid, num5, player);
			RestoreTerrain(position, 6f + (float)num5 * 0.25f, tentGuid);
			GameObject itemPrefab = ObjectDB.instance.GetItemPrefab("NomadTentKit");
			if ((Object)(object)itemPrefab != (Object)null)
			{
				ItemData val3 = itemPrefab.GetComponent<ItemDrop>().m_itemData.Clone();
				val3.m_stack = 1;
				WriteSaveDataToItem(val3, data);
				Inventory inventory = ((Humanoid)player).GetInventory();
				if (inventory == null || !inventory.AddItem(val3))
				{
					ItemDrop.DropItem(val3, 1, ((Component)player).transform.position + Vector3.up, Quaternion.identity);
				}
			}
			((Character)player).Message((MessageType)2, $"Packed up Nomad Tent (Tier {num5})!", 0, (Sprite)null, false);
		}

		private static TentSaveData CollectAndDestroyTentPieces(string tentGuid, int tier, Player player = null)
		{
			TentSaveData tentSaveData = new TentSaveData
			{
				TentGuid = tentGuid,
				Tier = tier
			};
			ZNetView[] array = (from v in Object.FindObjectsByType<ZNetView>((FindObjectsSortMode)0)
				where (Object)(object)v != (Object)null && v.IsValid() && v.GetZDO().GetString(KeyTentGuid, "") == tentGuid
				select v).ToArray();
			MethodInfo method = typeof(Container).GetMethod("Save", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			ZNetView[] array2 = array;
			foreach (ZNetView val in array2)
			{
				string localPosKey = val.GetZDO().GetString(KeyTentLocalPos, "");
				Container[] componentsInChildren = ((Component)val).GetComponentsInChildren<Container>(true);
				foreach (Container val2 in componentsInChildren)
				{
					if ((Object)(object)val2 == (Object)null)
					{
						continue;
					}
					ZNetView val3 = ((Component)val2).GetComponent<ZNetView>() ?? val;
					if ((Object)(object)val3 != (Object)null && val3.IsValid())
					{
						val3.ClaimOwnership();
					}
					method?.Invoke(val2, null);
					List<ItemData> list = new List<ItemData>();
					Inventory inventory = val2.GetInventory();
					if (inventory != null)
					{
						list.AddRange(inventory.GetAllItems());
					}
					if (list.Count == 0 && (Object)(object)val3 != (Object)null && val3.IsValid())
					{
						TryReadItemsFromContainerZdo(val3.GetZDO(), list);
					}
					SavedContainerData savedContainerData = new SavedContainerData
					{
						LocalPosKey = localPosKey
					};
					foreach (ItemData item in list)
					{
						SavedItemData savedItemData = SerializeItem(item);
						if (savedItemData != null)
						{
							savedContainerData.Items.Add(savedItemData);
						}
					}
					if (savedContainerData.Items.Count > 0)
					{
						tentSaveData.Containers.Add(savedContainerData);
					}
				}
			}
			array2 = array;
			foreach (ZNetView val4 in array2)
			{
				if ((Object)(object)val4 != (Object)null && val4.IsValid())
				{
					val4.ClaimOwnership();
					val4.Destroy();
				}
			}
			return tentSaveData;
		}

		private static void TryReadItemsFromContainerZdo(ZDO zdo, List<ItemData> output)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			if (zdo == null || output == null)
			{
				return;
			}
			string text = zdo.GetString(ZDOVars.s_items, "");
			if (string.IsNullOrEmpty(text))
			{
				return;
			}
			try
			{
				ZPackage val = new ZPackage(text);
				Inventory val2 = new Inventory("TempCapture", (Sprite)null, 6, 4);
				val2.Load(val);
				output.AddRange(val2.GetAllItems());
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Failed to read container ZDO items: " + ex.Message));
			}
		}

		private static string ResolveItemPrefabName(ItemData item)
		{
			if (item == null)
			{
				return "";
			}
			if ((Object)(object)item.m_dropPrefab != (Object)null && !string.IsNullOrEmpty(((Object)item.m_dropPrefab).name))
			{
				return ((Object)item.m_dropPrefab).name;
			}
			GameObject val = FindPrefabByNameOrShared((item.m_shared != null) ? (item.m_shared.m_name ?? "") : "");
			if (!((Object)(object)val != (Object)null))
			{
				return "";
			}
			return ((Object)val).name;
		}

		private static GameObject FindPrefabByNameOrShared(string nameOrShared)
		{
			if (string.IsNullOrEmpty(nameOrShared) || (Object)(object)ObjectDB.instance == (Object)null)
			{
				return null;
			}
			GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(nameOrShared);
			if ((Object)(object)itemPrefab != (Object)null)
			{
				return itemPrefab;
			}
			string text = nameOrShared.Trim();
			string obj = (text.StartsWith("$") ? text.Substring(1) : text);
			string text2 = text.ToLowerInvariant();
			string text3 = obj.ToLowerInvariant();
			foreach (GameObject item in ObjectDB.instance.m_items)
			{
				if ((Object)(object)item == (Object)null)
				{
					continue;
				}
				if (((Object)item).name.ToLowerInvariant() == text2 || ((Object)item).name.ToLowerInvariant() == text3)
				{
					return item;
				}
				ItemDrop component = item.GetComponent<ItemDrop>();
				if ((Object)(object)component != (Object)null && component.m_itemData != null && component.m_itemData.m_shared != null)
				{
					string text4 = component.m_itemData.m_shared.m_name ?? "";
					string text5 = (text4.StartsWith("$") ? text4.Substring(1) : text4);
					if (text4.ToLowerInvariant() == text2 || text5.ToLowerInvariant() == text3)
					{
						return item;
					}
				}
			}
			return null;
		}

		private static SavedItemData SerializeItem(ItemData item)
		{
			if (item == null)
			{
				return null;
			}
			SavedItemData savedItemData = new SavedItemData
			{
				PrefabName = ResolveItemPrefabName(item),
				SharedName = ((item.m_shared != null) ? (item.m_shared.m_name ?? "") : ""),
				Stack = item.m_stack,
				Durability = item.m_durability,
				Quality = item.m_quality,
				Variant = item.m_variant,
				CrafterID = item.m_crafterID,
				CrafterName = (item.m_crafterName ?? "")
			};
			if (item.m_customData != null)
			{
				foreach (KeyValuePair<string, string> customDatum in item.m_customData)
				{
					savedItemData.CustomDataKeys.Add(customDatum.Key);
					savedItemData.CustomDataValues.Add(customDatum.Value);
				}
			}
			return savedItemData;
		}

		private static ItemData BuildItemDataFromSaved(SavedItemData sItem)
		{
			if (sItem == null || (Object)(object)ObjectDB.instance == (Object)null)
			{
				return null;
			}
			GameObject val = FindPrefabByNameOrShared((!string.IsNullOrEmpty(sItem.PrefabName)) ? sItem.PrefabName : sItem.SharedName);
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			ItemDrop component = val.GetComponent<ItemDrop>();
			if ((Object)(object)component == (Object)null || component.m_itemData == null)
			{
				return null;
			}
			ItemData val2 = component.m_itemData.Clone();
			val2.m_dropPrefab = val;
			val2.m_stack = Mathf.Max(1, sItem.Stack);
			val2.m_durability = ((sItem.Durability > 0f) ? sItem.Durability : val2.m_durability);
			val2.m_quality = Mathf.Max(1, sItem.Quality);
			val2.m_variant = sItem.Variant;
			val2.m_crafterID = sItem.CrafterID;
			val2.m_crafterName = sItem.CrafterName ?? "";
			if (sItem.CustomDataKeys != null && sItem.CustomDataValues != null)
			{
				int num = Mathf.Min(sItem.CustomDataKeys.Count, sItem.CustomDataValues.Count);
				for (int i = 0; i < num; i++)
				{
					val2.m_customData[sItem.CustomDataKeys[i]] = sItem.CustomDataValues[i];
				}
			}
			return val2;
		}

		private static void RestoreContainerInventory(Player player, Container container, SavedContainerData saved)
		{
			if ((Object)(object)container == (Object)null || saved == null || saved.Items == null)
			{
				return;
			}
			Inventory inventory = container.GetInventory();
			if (inventory == null)
			{
				foreach (SavedItemData item in saved.Items)
				{
					DropSavedItemAtPlayer(player, item);
				}
				return;
			}
			foreach (SavedItemData item2 in saved.Items)
			{
				ItemData val = BuildItemDataFromSaved(item2);
				if (val == null || !inventory.AddItem(val))
				{
					DropSavedItemAtPlayer(player, item2);
				}
			}
			typeof(Container).GetMethod("Save", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.Invoke(container, null);
		}

		private static void DropSavedItemAtPlayer(Player player, SavedItemData sItem)
		{
			//IL_0031: 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_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)player == (Object)null) && sItem != null && !((Object)(object)ObjectDB.instance == (Object)null))
			{
				ItemData val = BuildItemDataFromSaved(sItem);
				if (val != null)
				{
					ItemDrop.DropItem(val, val.m_stack, ((Component)player).transform.position + Vector3.up * 0.5f, Quaternion.identity);
				}
			}
		}

		private static string EncodeField(string s)
		{
			if (string.IsNullOrEmpty(s))
			{
				return "";
			}
			return Convert.ToBase64String(Encoding.UTF8.GetBytes(s));
		}

		private static string DecodeField(string b64)
		{
			if (string.IsNullOrEmpty(b64))
			{
				return "";
			}
			try
			{
				return Encoding.UTF8.GetString(Convert.FromBase64String(b64));
			}
			catch
			{
				return "";
			}
		}

		private static string SerializeSaveData(TentSaveData data)
		{
			if (data == null)
			{
				return "";
			}
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("V3|");
			stringBuilder.Append(EncodeField(data.TentGuid ?? "")).Append("|");
			stringBuilder.Append(data.Tier).Append("|");
			List<SavedContainerData> list = data.Containers ?? new List<SavedContainerData>();
			stringBuilder.Append(list.Count).Append("|");
			foreach (SavedContainerData item in list)
			{
				List<SavedItemData> list2 = item?.Items ?? new List<SavedItemData>();
				stringBuilder.Append(EncodeField(item?.LocalPosKey ?? "")).Append(":");
				stringBuilder.Append(list2.Count).Append(":");
				foreach (SavedItemData item2 in list2)
				{
					stringBuilder.Append(EncodeField(item2?.PrefabName ?? "")).Append(",");
					stringBuilder.Append(EncodeField(item2?.SharedName ?? "")).Append(",");
					stringBuilder.Append(item2?.Stack ?? 1).Append(",");
					stringBuilder.Append((item2?.Durability ?? 100f).ToString(CultureInfo.InvariantCulture)).Append(",");
					stringBuilder.Append(item2?.Quality ?? 1).Append(",");
					stringBuilder.Append(item2?.Variant ?? 0).Append(",");
					stringBuilder.Append(item2?.CrafterID ?? 0).Append(",");
					stringBuilder.Append(EncodeField(item2?.CrafterName ?? "")).Append(";");
				}
				stringBuilder.Append("|");
			}
			stringBuilder.Append("0|");
			return stringBuilder.ToString();
		}

		private static TentSaveData DeserializeSaveData(string payload)
		{
			TentSaveData tentSaveData = new TentSaveData();
			if (string.IsNullOrEmpty(payload) || (!payload.StartsWith("V3|") && !payload.StartsWith("V2|")))
			{
				return tentSaveData;
			}
			try
			{
				string[] array = payload.Split(new char[1] { '|' });
				if (array.Length < 5)
				{
					return tentSaveData;
				}
				tentSaveData.TentGuid = DecodeField(array[1]);
				tentSaveData.Tier = ((!int.TryParse(array[2], out var result)) ? 1 : result);
				int result2;
				int num = (int.TryParse(array[3], out result2) ? result2 : 0);
				int num2 = 4;
				int num3 = 0;
				while (num3 < num && num2 < array.Length)
				{
					string text = array[num2];
					int num4 = text.IndexOf(':');
					if (num4 >= 0)
					{
						int num5 = text.IndexOf(':', num4 + 1);
						if (num5 >= 0)
						{
							SavedContainerData savedContainerData = new SavedContainerData
							{
								LocalPosKey = DecodeField(text.Substring(0, num4))
							};
							string text2 = text.Substring(num5 + 1);
							if (!string.IsNullOrEmpty(text2))
							{
								string[] array2 = text2.Split(new char[1] { ';' }, StringSplitOptions.RemoveEmptyEntries);
								for (int i = 0; i < array2.Length; i++)
								{
									string[] array3 = array2[i].Split(new char[1] { ',' });
									if (array3.Length >= 8)
									{
										savedContainerData.Items.Add(new SavedItemData
										{
											PrefabName = DecodeField(array3[0]),
											SharedName = DecodeField(array3[1]),
											Stack = ((!int.TryParse(array3[2], out var result3)) ? 1 : result3),
											Durability = ParseFloat(array3[3]),
											Quality = ((!int.TryParse(array3[4], out var result4)) ? 1 : result4),
											Variant = (int.TryParse(array3[5], out var result5) ? result5 : 0),
											CrafterID = (long.TryParse(array3[6], out var result6) ? result6 : 0),
											CrafterName = DecodeField(array3[7])
										});
									}
								}
							}
							tentSaveData.Containers.Add(savedContainerData);
						}
					}
					num3++;
					num2++;
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Failed to deserialize saveData payload: " + ex.Message));
			}
			return tentSaveData;
		}

		private static TentSaveData ReadSaveDataFromItem(ItemData item)
		{
			string text = "";
			if (item != null && item.m_customData != null && item.m_customData.TryGetValue("NomadTent_Data", out var value) && !string.IsNullOrEmpty(value))
			{
				text = value;
			}
			else
			{
				if (item != null && item.m_customData != null && item.m_customData.TryGetValue("NomadTent_GuidRef", out var value2) && !string.IsNullOrEmpty(value2) && RecentSavesByGuid.TryGetValue(value2, out var value3) && !string.IsNullOrEmpty(value3))
				{
					text = value3;
				}
				if (string.IsNullOrEmpty(text) && !string.IsNullOrEmpty(LastPackedSavePayload))
				{
					text = LastPackedSavePayload;
				}
			}
			if (string.IsNullOrEmpty(text))
			{
				return new TentSaveData();
			}
			return DeserializeSaveData(text);
		}

		private static void WriteSaveDataToItem(ItemData item, TentSaveData data)
		{
			if (item != null && data != null)
			{
				if (item.m_customData == null)
				{
					item.m_customData = new Dictionary<string, string>();
				}
				string text = SerializeSaveData(data);
				item.m_customData["NomadTent_Data"] = text;
				if (!string.IsNullOrEmpty(data.TentGuid))
				{
					item.m_customData["NomadTent_GuidRef"] = data.TentGuid;
					RecentSavesByGuid[data.TentGuid] = text;
				}
				LastPackedSavePayload = text;
			}
		}

		private static float ParseFloat(string s)
		{
			if (!float.TryParse(s.Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
			{
				return 0f;
			}
			return result;
		}

		private static string FormatPosKey(Vector3 pos)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			return string.Format(CultureInfo.InvariantCulture, "{0:F2}_{1:F2}_{2:F2}", pos.x, pos.y, pos.z);
		}
	}
}