Decompiled source of POGShops v0.1.0

POGShops.dll

Decompiled 5 hours ago
using System;
using System.Collections;
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 System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using HarmonyLib;
using Il2Cpp;
using Il2CppAnimations;
using Il2CppGame.Gameplay;
using Il2CppGame.Menu;
using Il2CppGame.Networking;
using Il2CppGame.Spawning;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppInventory;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using MelonLoader;
using MelonLoader.Preferences;
using MelonLoader.Utils;
using POGLib.Core;
using POGLib.Items;
using POGLib.Shops;
using POGLib.Shops.Dev;
using POGLib.Shops.Model;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(ShopsMod), "POGShops", "0.1.0", "largo", null)]
[assembly: MelonGame(null, "Pit of Goblin")]
[assembly: MelonPriority(-900)]
[assembly: MelonAdditionalDependencies(new string[] { "POGLib" })]
[assembly: HarmonyDontPatchAll]
[assembly: InternalsVisibleTo("POGLibRuntimeDriver")]
[assembly: AssemblyMetadata("POGModCheck", "same-version")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("POGShops")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+b5619a05bea7c9f5bb75ab270bed9fe461336193")]
[assembly: AssemblyProduct("POGShops")]
[assembly: AssemblyTitle("POGShops")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace POGLib.Shops
{
	internal static class SellerTemplates
	{
		public const string MerchantList = "PropList_EntranceCave_MerchantOrAdventurer";

		public const string Vanilla = "vanilla";

		private static readonly HashSet<int> _injected = new HashSet<int>();

		private static readonly Dictionary<string, int> _originalCopies = new Dictionary<string, int>(StringComparer.Ordinal);

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

		public static int Copies(double weight)
		{
			if (!(weight <= 0.0))
			{
				return Mathf.Max(1, Mathf.RoundToInt((float)weight));
			}
			return 0;
		}

		public static void BuildPending(ShopCatalog catalog)
		{
			if (catalog == null || catalog.Sellers.Count == 0)
			{
				return;
			}
			foreach (PropListAsset item in Resources.FindObjectsOfTypeAll<PropListAsset>())
			{
				if ((Object)(object)item == (Object)null || ((Object)item).name != "PropList_EntranceCave_MerchantOrAdventurer" || item.PropList == null || _injected.Contains(((Object)item).GetInstanceID()))
				{
					continue;
				}
				List<GameObject> list = ((IEnumerable<GameObject>)item.PropList).ToList();
				int count = list.Count;
				List<string> list2 = new List<string>();
				foreach (ShopCatalog.ModSeller s in catalog.Sellers)
				{
					GameObject preset = list.Take(count).FirstOrDefault((Func<GameObject, bool>)((GameObject g) => (Object)(object)g != (Object)null && ((Object)g).name == s.Def.Preset));
					if ((Object)(object)preset == (Object)null)
					{
						MelonLogger.Warning($"[POGLib] [Shops] merchant {s.FullId}: preset '{s.Def.Preset}' is not in {"PropList_EntranceCave_MerchantOrAdventurer"} (it has: {string.Join(", ", (from g in list.Take(count)
							where (Object)(object)g != (Object)null
							select ((Object)g).name).Distinct())})");
					}
					else
					{
						_originalCopies[((Object)preset).name] = list.Take(count).Count((GameObject g) => (Object)(object)g != (Object)null && ((Object)g).name == ((Object)preset).name);
						int num = Copies(s.Def.Weight);
						for (int num2 = 0; num2 < num; num2++)
						{
							list.Add(preset);
						}
						list2.Add($"{s.FullId} on {((Object)preset).name} x{num}");
					}
				}
				Il2CppReferenceArray<GameObject> val = new Il2CppReferenceArray<GameObject>((long)list.Count);
				for (int num3 = 0; num3 < list.Count; num3++)
				{
					((Il2CppArrayBase<GameObject>)(object)val)[num3] = list[num3];
				}
				item.PropList = val;
				_injected.Add(((Object)item).GetInstanceID());
				MelonLogger.Msg($"[POGLib] [Shops] {"PropList_EntranceCave_MerchantOrAdventurer"}: {count} -> {list.Count} entries ({string.Join(", ", list2)}).");
			}
		}

		public static string VariantSlotId(ShopLocation slot, ShopCatalog catalog, Random rng)
		{
			if (catalog == null || catalog.Sellers.Count == 0)
			{
				return null;
			}
			Transform val = null;
			Transform x = ((Component)slot).transform;
			while ((Object)(object)x != (Object)null)
			{
				if (catalog.Sellers.Any((ShopCatalog.ModSeller s) => s.Def.Preset == ShopScene.CleanName(((Object)x).name)))
				{
					val = x;
					break;
				}
				x = x.parent;
			}
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			string preset = ShopScene.CleanName(((Object)val).name);
			int instanceID = ((Object)((Component)val).gameObject).GetInstanceID();
			if (!_variantOf.TryGetValue(instanceID, out var value))
			{
				int value2;
				List<(string, double)> list = new List<(string, double)> { ("vanilla", (!_originalCopies.TryGetValue(preset, out value2)) ? 1 : value2) };
				list.AddRange(from s in catalog.Sellers
					where s.Def.Preset == preset
					select ((string FullId, double))(FullId: s.FullId, Copies(s.Def.Weight)));
				double total = list.Sum<(string, double)>(((string id, double w) o) => o.w);
				int num = WeightedPick.Index<(string, double)>(list, ((string id, double w) o) => o.w, rng.NextDouble());
				value = ((num >= 0) ? list[num].Item1 : "vanilla");
				_variantOf[instanceID] = value;
				MelonLogger.Msg($"[POGLib] [Shops] dungeon merchant {preset} is {((value == "vanilla") ? "the vanilla one" : value)} ({string.Join(", ", list.Select<(string, double), string>(((string id, double w) o) => $"{o.id} {100.0 * o.w / total:0.#}%"))})");
			}
			if (value == "vanilla")
			{
				return null;
			}
			NpcSpawner componentInChildren = ((Component)val).GetComponentInChildren<NpcSpawner>(true);
			int num2 = 0;
			if ((Object)(object)componentInChildren != (Object)null && componentInChildren.m_itemsForSale != null)
			{
				for (int num3 = 0; num3 < ((Il2CppArrayBase<ShopLocation>)(object)componentInChildren.m_itemsForSale).Length; num3++)
				{
					if ((Object)(object)((Il2CppArrayBase<ShopLocation>)(object)componentInChildren.m_itemsForSale)[num3] != (Object)null && ((Il2CppObjectBase)((Il2CppArrayBase<ShopLocation>)(object)componentInChildren.m_itemsForSale)[num3]).Pointer == ((Il2CppObjectBase)slot).Pointer)
					{
						num2 = num3 + 1;
						break;
					}
				}
			}
			if (num2 == 0)
			{
				num2 = Array.IndexOf(((IEnumerable<ShopLocation>)((Component)val).GetComponentsInChildren<ShopLocation>(true)).Select((ShopLocation val2) => ((Il2CppObjectBase)val2).Pointer).ToArray(), ((Il2CppObjectBase)slot).Pointer) + 1;
			}
			return ShopCatalog.SellerSlotId(value, num2);
		}

		public static void Reset()
		{
			_variantOf.Clear();
		}

		public static void ApplyItemDisplays(ShopCatalog catalog)
		{
			//IL_008e: 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)
			if (catalog == null)
			{
				return;
			}
			foreach (KeyValuePair<string, (string, TagDef)> itemDisplay in catalog.ItemDisplays)
			{
				NetworkObject val = ShopScene.ResolveItemPrefab(itemDisplay.Key);
				InventoryItem val2 = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponent<InventoryItem>() : null);
				if (!((Object)(object)val2 == (Object)null))
				{
					TagDef item = itemDisplay.Value.Item2;
					StandingPoints.Ensure(val2, (item?.Pos != null) ? new Vector3?(new Vector3(item.Pos[0], item.Pos[1], item.Pos[2])) : ((Vector3?)null), (item?.Rot != null) ? new Vector3?(new Vector3(item.Rot[0], item.Rot[1], item.Rot[2])) : ((Vector3?)null));
				}
			}
		}
	}
	internal static class ShopChecks
	{
		public const float SceneCheckDelaySeconds = 5f;

		private const string Tag = "[POGLib] [Shops]";

		private static readonly HashSet<string> _reported = new HashSet<string>(StringComparer.Ordinal);

		private static bool Once(string key)
		{
			return _reported.Add(key);
		}

		public static void CheckModItems(ShopCatalog catalog)
		{
			if (catalog == null)
			{
				return;
			}
			foreach (IGrouping<string, ItemReference> item in from r in catalog.ItemReferences
				group r by r.Item)
			{
				if (!ShopIds.IsVanilla(item.Key))
				{
					string usedBy = Describe(item);
					NetworkObject val = ShopScene.ResolveItemPrefab(item.Key);
					if ((Object)(object)val == (Object)null)
					{
						NotLoaded(item.Key, usedBy);
					}
					else
					{
						CheckPrice(item.Key, val, usedBy);
					}
				}
			}
		}

		private static string Describe(IEnumerable<ItemReference> refs)
		{
			List<ItemReference> list = refs.ToList();
			string text = string.Join("; ", from r in list.Take(3)
				select r.ToString());
			if (list.Count <= 3)
			{
				return text;
			}
			return text + $"; +{list.Count - 3} more";
		}

		public static void NotLoaded(string item, string usedBy)
		{
			if (Once("item:" + item))
			{
				ItemsPlugin instance = ItemsPlugin.Instance;
				if (instance != null && instance.IsRegistered(item))
				{
					MelonLogger.Warning($"{"[POGLib] [Shops]"} item '{item}' ({usedBy}) is registered but its template was not built " + "(see the [POGLib] lines about its shell above). Shops leave it out.");
				}
				else
				{
					List<string> list = NearestIds.Of(item, KnownItemIds());
					MelonLogger.Warning($"{"[POGLib] [Shops]"} item '{item}' ({usedBy}) is not loaded: its mod is not installed, or the id is misspelt. Shops leave it out.{((list.Count > 0) ? (" Closest loaded ids: " + string.Join(", ", list)) : "")}");
				}
			}
		}

		public static void CheckPrice(string item, NetworkObject prefab, string usedBy)
		{
			InventoryItem val = (((Object)(object)prefab != (Object)null) ? ((Component)prefab).GetComponent<InventoryItem>() : null);
			if (!((Object)(object)val == (Object)null) && val.m_shopCost <= 0 && Once("free:" + item))
			{
				MelonLogger.Warning($"{"[POGLib] [Shops]"} item '{item}' ({usedBy}) has ShopCost {val.m_shopCost}: a shop sells it for free. " + (ShopIds.IsVanilla(item) ? "The game gives this item no price of its own." : "Set ShopCost in its ModItemDefinition."));
			}
		}

		public static void ReportUnmatchedSlots(string scene, ShopCatalog catalog)
		{
			if (catalog == null)
			{
				return;
			}
			List<string> list = VanillaTargetsIn(scene, catalog);
			if (list.Count == 0)
			{
				return;
			}
			List<string> list2 = (from id in ShopScene.SlotsInLoadedScenes().Where(delegate(ShopLocation s)
				{
					//IL_0006: Unknown result type (might be due to invalid IL or missing references)
					//IL_000b: Unknown result type (might be due to invalid IL or missing references)
					Scene scene2 = ((Component)s).gameObject.scene;
					return ((Scene)(ref scene2)).name == scene;
				}).Select(ShopScene.SlotId)
				where id != null
				select id).Distinct().ToList();
			HashSet<string> hashSet = new HashSet<string>(list2, StringComparer.Ordinal);
			foreach (string item in list)
			{
				if (!hashSet.Contains(item) && Once("slot:" + item))
				{
					List<string> list3 = NearestIds.Of(item, list2);
					MelonLogger.Warning($"{"[POGLib] [Shops]"} {string.Join(", ", catalog.ModsTargeting(item))}: slot '{item}' is not in {scene} ({5f:0} s after its slots spawned), so those rules do nothing on this visit. " + ((list3.Count > 0) ? ("Closest slot ids here: " + string.Join(" | ", list3) + ". ") : "The scene has no shop slots. ") + "A slot of a seller the game draws at random can be absent on some visits.");
				}
			}
		}

		public static List<string> VanillaTargetsIn(string scene, ShopCatalog catalog)
		{
			return catalog.TargetedSlots.Where((string id) => ShopIds.SceneOfVanilla(id) == scene).OrderBy<string, string>((string id) => id, StringComparer.Ordinal).ToList();
		}

		private static IEnumerable<string> KnownItemIds()
		{
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			List<string> list = new List<string>();
			foreach (NetworkObject allPrefab in CoreServices.Content.AllPrefabs)
			{
				InventoryItem val = (((Object)(object)allPrefab != (Object)null) ? ((Component)allPrefab).GetComponent<InventoryItem>() : null);
				if ((Object)(object)val != (Object)null && !string.IsNullOrEmpty(val.m_itemID))
				{
					list.Add(val.m_itemID);
				}
			}
			foreach (InventoryItem item in Resources.FindObjectsOfTypeAll<InventoryItem>())
			{
				if ((Object)(object)item != (Object)null)
				{
					Scene scene = ((Component)item).gameObject.scene;
					if (!((Scene)(ref scene)).IsValid() && !ShopScene.IsTemplate(((Component)item).transform))
					{
						list.Add(ShopIds.VanillaItem(((Object)((Component)item).gameObject).name));
					}
				}
			}
			return list;
		}
	}
	[HarmonyPatch(typeof(ShopLocation), "OnNetworkSpawn")]
	internal static class Patch_ShopLocation_OnNetworkSpawn
	{
		private static void Prefix(ShopLocation __instance)
		{
			try
			{
				ShopRuntime.OnSlotSpawning(__instance);
			}
			catch (Exception value)
			{
				MelonLogger.Error($"[POGLib] [Shops] stocking failed, the game's own choice stays: {value}");
			}
		}

		private static void Postfix(ShopLocation __instance)
		{
			try
			{
				if ((Object)(object)__instance != (Object)null && ((Object)((Component)__instance).gameObject).name.StartsWith("POGShopSlot|"))
				{
					TemplateCopies.Release(((Component)__instance).gameObject);
				}
			}
			catch (Exception ex)
			{
				MelonLogger.Warning("[POGLib] [Shops] " + ex.GetType().Name + ": " + ex.Message);
			}
			try
			{
				ShopEmptySlots.HideTagIfEmpty(__instance);
			}
			catch (Exception ex2)
			{
				MelonLogger.Warning("[POGLib] [Shops] " + ex2.GetType().Name + ": " + ex2.Message);
			}
			try
			{
				SlotSync.OnClientSlotSpawned(__instance);
			}
			catch (Exception ex3)
			{
				MelonLogger.Warning("[POGLib] [Shops] asking the host about a slot: " + ex3.GetType().Name + ": " + ex3.Message);
			}
		}
	}
	[HarmonyPatch(typeof(ClientNetworkParenting), "SetParentBeforeSpawn")]
	internal static class Patch_ClientNetworkParenting_SetParentBeforeSpawn
	{
		private static void Prefix(ClientNetworkParenting __instance, NetworkObject parent)
		{
			try
			{
				if (!((Object)(object)__instance == (Object)null) && !((Object)(object)parent == (Object)null))
				{
					ShopLocation component = ((Component)parent).GetComponent<ShopLocation>();
					if (!((Object)(object)component == (Object)null))
					{
						ShopItemPose.StandUpright(component, ((Component)__instance).GetComponent<InventoryItem>());
					}
				}
			}
			catch (Exception ex)
			{
				MelonLogger.Warning("[POGLib] [Shops] standing an item upright: " + ex.GetType().Name + ": " + ex.Message);
			}
		}
	}
	internal static class ShopItemPose
	{
		public const float TiltToleranceDegrees = 5f;

		private static readonly HashSet<string> _logged = new HashSet<string>(StringComparer.Ordinal);

		public static void StandUpright(ShopLocation slot, InventoryItem item)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: 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_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: 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_012f: 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_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: 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_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)slot == (Object)null || (Object)(object)item == (Object)null)
			{
				return;
			}
			ItemsPlugin instance = ItemsPlugin.Instance;
			if (instance == null || !instance.IsModItem(item))
			{
				return;
			}
			Transform transform = ((Component)item).transform;
			float num = Vector3.Angle(transform.up, Vector3.up);
			string item2 = ((Object)((Component)slot).gameObject).name + "|" + item.m_itemID;
			bool flag = _logged.Add(item2);
			if (num <= 5f)
			{
				if (flag)
				{
					MelonLogger.Msg($"[POGLib] [Shops] {item.m_itemID} in '{((Object)((Component)slot).gameObject).name}': upright already (tilt {num:0}°).");
				}
				return;
			}
			Transform standingTransform = item.m_standingTransform;
			Vector3 val = (((Object)(object)standingTransform != (Object)null) ? standingTransform.position : transform.position);
			Vector3 val2 = Vector3.ProjectOnPlane(transform.forward, Vector3.up);
			if (((Vector3)(ref val2)).sqrMagnitude < 0.0001f)
			{
				val2 = Vector3.ProjectOnPlane(transform.up, Vector3.up);
			}
			if (((Vector3)(ref val2)).sqrMagnitude < 0.0001f)
			{
				val2 = Vector3.forward;
			}
			Quaternion rotation = Quaternion.LookRotation(((Vector3)(ref val2)).normalized, Vector3.up);
			transform.rotation = rotation;
			if ((Object)(object)standingTransform != (Object)null)
			{
				transform.position += val - standingTransform.position;
			}
			if (flag)
			{
				MelonLogger.Msg($"[POGLib] [Shops] {item.m_itemID} in '{((Object)((Component)slot).gameObject).name}': stood upright (the slot tilted it {num:0}°).");
			}
		}
	}
	internal static class ShopEmptySlots
	{
		private static readonly HashSet<int> _empty = new HashSet<int>();

		public static void Mark(ShopLocation slot)
		{
			_empty.Add(((Object)slot).GetInstanceID());
		}

		public static void HideTagIfEmpty(ShopLocation slot)
		{
			if (!((Object)(object)slot == (Object)null) && _empty.Contains(((Object)slot).GetInstanceID()) && (Object)(object)slot.m_priceTagText != (Object)null)
			{
				((Component)SlotTemplates.TopChildOf(slot.m_priceTagText.transform, ((Component)slot).transform)).gameObject.SetActive(false);
			}
		}

		public static void Reset()
		{
			_empty.Clear();
		}
	}
	internal static class ShopChoices
	{
		private static readonly Dictionary<int, NetworkObject> _chosen = new Dictionary<int, NetworkObject>();

		private static string _standIn;

		public static void Set(ShopLocation slot, NetworkObject prefab)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			_chosen[((Object)slot).GetInstanceID()] = prefab;
			((SpawnerBase)slot).m_loadedPrefab = prefab;
			AssetReferenceGameObject networkPrefabRef = ((SpawnerBase)slot).m_networkPrefabRef;
			if (networkPrefabRef == null || string.IsNullOrEmpty(((AssetReference)networkPrefabRef).AssetGUID))
			{
				string text = StandInGuid();
				if (text != null)
				{
					((SpawnerBase)slot).m_networkPrefabRef = new AssetReferenceGameObject(text);
				}
			}
		}

		private static string StandInGuid()
		{
			if (!string.IsNullOrEmpty(_standIn))
			{
				return _standIn;
			}
			try
			{
				NetworkHandler singleton = NetworkHandler.Singleton;
				object standIn;
				if (singleton == null)
				{
					standIn = null;
				}
				else
				{
					AssetReferenceGameObject persistentPlayer = singleton.m_persistentPlayer;
					standIn = ((persistentPlayer != null) ? ((AssetReference)persistentPlayer).AssetGUID : null);
				}
				_standIn = (string)standIn;
			}
			catch
			{
				_standIn = null;
			}
			if (string.IsNullOrEmpty(_standIn))
			{
				MelonLogger.Warning("[POGLib] [Shops] no stand-in reference for slots without one; their choice may not reach the game.");
			}
			return _standIn;
		}

		public static bool TryGet(Object spawner, out NetworkObject prefab)
		{
			prefab = null;
			if (spawner != (Object)null && _chosen.Count > 0)
			{
				return _chosen.TryGetValue(spawner.GetInstanceID(), out prefab);
			}
			return false;
		}

		public static void Reset()
		{
			_chosen.Clear();
		}
	}
	[HarmonyPatch(/*Could not decode attribute arguments.*/)]
	internal static class Patch_SpawnerBase_HasNetworkPrefab
	{
		private static bool Prefix(SpawnerBase __instance, ref bool __result)
		{
			if (!ShopChoices.TryGet((Object)(object)__instance, out var prefab))
			{
				return true;
			}
			__result = (Object)(object)prefab != (Object)null;
			return false;
		}
	}
	[HarmonyPatch(typeof(SpawnerBase), "LoadNetworkPrefab")]
	internal static class Patch_SpawnerBase_LoadNetworkPrefab
	{
		private static bool Prefix(SpawnerBase __instance, ref NetworkObject __result)
		{
			if (!ShopChoices.TryGet((Object)(object)__instance, out var prefab))
			{
				return true;
			}
			__result = prefab;
			return false;
		}
	}
	[HarmonyPatch(typeof(SpawnerBase), "PreloadNetworkPrefab")]
	internal static class Patch_SpawnerBase_PreloadNetworkPrefab
	{
		private static bool Prefix(SpawnerBase __instance)
		{
			NetworkObject prefab;
			return !ShopChoices.TryGet((Object)(object)__instance, out prefab);
		}
	}
	[HarmonyPatch(/*Could not decode attribute arguments.*/)]
	internal static class Patch_ShopLocation_HasLootTable
	{
		private static bool Prefix(ShopLocation __instance, ref bool __result)
		{
			if (!ShopChoices.TryGet((Object)(object)__instance, out var _))
			{
				return true;
			}
			__result = false;
			return false;
		}
	}
	[HarmonyPatch(typeof(ShopLocation), "LoadLootTable")]
	internal static class Patch_ShopLocation_LoadLootTable
	{
		private static bool Prefix(ShopLocation __instance, ref InventoryLootTable __result)
		{
			if (!ShopChoices.TryGet((Object)(object)__instance, out var _))
			{
				return true;
			}
			__result = null;
			return false;
		}
	}
	internal sealed class SlotRecord
	{
		public string SlotId { get; internal set; }

		public ShopLocation Slot { get; internal set; }

		public ResolvedSlot Resolved { get; internal set; }

		public List<VanillaEntry> Vanilla { get; internal set; } = new List<VanillaEntry>();

		public string Picked { get; internal set; }

		public List<string> Notes { get; } = new List<string>();
	}
	internal static class ShopRuntime
	{
		private sealed class Memo
		{
			public List<VanillaEntry> Vanilla;

			public string Picked;

			public NetworkObject Prefab;
		}

		private static readonly Dictionary<string, SlotRecord> _records = new Dictionary<string, SlotRecord>(StringComparer.Ordinal);

		private static Random _rng = new Random();

		private static readonly Dictionary<int, Memo> _memo = new Dictionary<int, Memo>();

		private static readonly Dictionary<string, string> _placedAfter = new Dictionary<string, string>(StringComparer.Ordinal);

		public static IReadOnlyDictionary<string, SlotRecord> Records => _records;

		private static ShopCatalog Catalog => ShopsPlugin.Instance?.Catalog;

		private static bool IsHost
		{
			get
			{
				NetworkManager singleton = NetworkManager.Singleton;
				if ((Object)(object)singleton != (Object)null && singleton.IsListening)
				{
					return singleton.IsServer;
				}
				return false;
			}
		}

		public static void SetRandomSeed(int? seed)
		{
			_rng = (seed.HasValue ? new Random(seed.Value) : new Random());
		}

		internal static void Reset()
		{
			_records.Clear();
			_memo.Clear();
			_placedAfter.Clear();
			ShopChoices.Reset();
			SellerTemplates.Reset();
		}

		internal static void OnSlotSpawning(ShopLocation slot)
		{
			ShopCatalog catalog = Catalog;
			if (catalog == null || (Object)(object)slot == (Object)null || !IsHost)
			{
				return;
			}
			int instanceID = ((Object)slot).GetInstanceID();
			if (_memo.TryGetValue(instanceID, out var value))
			{
				if ((Object)(object)value.Prefab != (Object)null || value.Picked == "nothing")
				{
					ApplyChoice(slot, value.Prefab);
				}
				return;
			}
			string text = SellerTemplates.VariantSlotId(slot, catalog, _rng) ?? ShopScene.SlotId(slot);
			List<VanillaEntry> vanilla = ShopScene.VanillaEntriesOf(slot);
			Memo memo = new Memo
			{
				Vanilla = vanilla
			};
			_memo[instanceID] = memo;
			ResolvedSlot resolvedSlot = catalog.Resolve(text, vanilla);
			SlotRecord slotRecord = new SlotRecord
			{
				SlotId = text,
				Slot = slot,
				Resolved = resolvedSlot,
				Vanilla = vanilla
			};
			_records[text] = slotRecord;
			if (resolvedSlot.Untouched)
			{
				return;
			}
			Dictionary<string, NetworkObject> prefabs = new Dictionary<string, NetworkObject>(StringComparer.Ordinal);
			foreach (SlotEntry entry in resolvedSlot.Entries)
			{
				if (WeightedPick.Usable(entry.Weight) && !(entry.Item == "nothing") && !prefabs.ContainsKey(entry.Item))
				{
					NetworkObject val = ShopScene.ResolveItemPrefab(entry.Item);
					prefabs[entry.Item] = val;
					string usedBy = entry.AddedBy + " in " + text;
					if ((Object)(object)val == (Object)null)
					{
						slotRecord.Notes.Add(entry.Item + " (from " + entry.AddedBy + ") is not loaded; left out");
						ShopChecks.NotLoaded(entry.Item, usedBy);
					}
					else
					{
						ShopChecks.CheckPrice(entry.Item, val, usedBy);
					}
				}
			}
			NetworkObject value2;
			Func<SlotEntry, bool> usable = (SlotEntry e) => e.Item == "nothing" || (prefabs.TryGetValue(e.Item, out value2) && (Object)(object)value2 != (Object)null);
			SlotEntry slotEntry = resolvedSlot.Pick(_rng.NextDouble(), usable);
			if (slotEntry == null)
			{
				slotRecord.Picked = (memo.Picked = "nothing");
				slotRecord.Notes.Add("no usable entry: the slot stays empty");
				MakeEmpty(slot, slotRecord);
				return;
			}
			slotRecord.Picked = (memo.Picked = slotEntry.Item);
			NetworkObject val2 = (memo.Prefab = ((slotEntry.Item == "nothing") ? null : prefabs[slotEntry.Item]));
			if ((Object)(object)val2 == (Object)null)
			{
				MakeEmpty(slot, slotRecord);
				return;
			}
			ApplyChoice(slot, val2);
			MelonLogger.Msg($"[POGLib] [Shops] {text}: {slotEntry.Item} ({100.0 * resolvedSlot.ChanceAmong(slotEntry, usable):0.#}% of {resolvedSlot.Entries.Count((SlotEntry e) => usable(e) && WeightedPick.Usable(e.Weight))} candidate(s))");
		}

		private static void MakeEmpty(ShopLocation slot, SlotRecord rec)
		{
			ApplyChoice(slot, null);
			ShopEmptySlots.Mark(slot);
			MelonLogger.Msg("[POGLib] [Shops] " + rec.SlotId + ": stays empty");
		}

		private static void ApplyChoice(ShopLocation slot, NetworkObject prefab)
		{
			ShopChoices.Set(slot, prefab);
		}

		internal static void OnSceneLoaded()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			ShopCatalog catalog = Catalog;
			if (catalog != null)
			{
				Scene activeScene = SceneManager.GetActiveScene();
				string scene = ((Scene)(ref activeScene)).name;
				bool flag = catalog.ModSlots.Values.Any((ShopCatalog.ModSlot s) => s.Def.Scene == scene);
				bool flag2 = ShopChecks.VanillaTargetsIn(scene, catalog).Count > 0;
				if (flag || flag2)
				{
					MelonCoroutines.Start(WhenSlotsSpawned(scene, flag, flag2));
				}
			}
		}

		private static IEnumerator WhenSlotsSpawned(string scene, bool modSlots, bool vanillaRules)
		{
			float deadline = Time.realtimeSinceStartup + 60f;
			Scene activeScene;
			while (Time.realtimeSinceStartup < deadline)
			{
				activeScene = SceneManager.GetActiveScene();
				if (((Scene)(ref activeScene)).name != scene)
				{
					yield break;
				}
				if (IsHost && ShopScene.SlotsInLoadedScenes().Any((ShopLocation s) => ((NetworkBehaviour)s).IsSpawned))
				{
					break;
				}
				yield return (object)new WaitForSeconds(0.5f);
			}
			if (!IsHost)
			{
				yield break;
			}
			yield return (object)new WaitForSeconds(1f);
			if (modSlots)
			{
				SpawnModSlots(scene);
			}
			if (vanillaRules)
			{
				yield return (object)new WaitForSeconds(4f);
				activeScene = SceneManager.GetActiveScene();
				if (((Scene)(ref activeScene)).name == scene)
				{
					ShopChecks.ReportUnmatchedSlots(scene, Catalog);
				}
			}
		}

		internal static void SpawnModSlots(string scene)
		{
			ShopCatalog catalog = Catalog;
			int num = 0;
			int num2 = 0;
			foreach (ShopCatalog.ModSlot item in catalog.ModSlots.Values.Where((ShopCatalog.ModSlot s) => s.Def.Scene == scene))
			{
				try
				{
					if (SpawnOne(item))
					{
						num++;
					}
					else
					{
						num2++;
					}
				}
				catch (Exception ex)
				{
					num2++;
					MelonLogger.Error($"[POGLib] [Shops] slot {item.FullId} failed: {ex.GetType().Name}: {ex.Message}");
				}
			}
			MelonLogger.Msg($"[POGLib] [Shops] {scene}: placed {num} mod slot(s){((num2 > 0) ? $", {num2} failed" : "")}.");
		}

		private static bool SpawnOne(ShopCatalog.ModSlot ms)
		{
			//IL_047f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0484: Unknown result type (might be due to invalid IL or missing references)
			//IL_0489: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0544: Unknown result type (might be due to invalid IL or missing references)
			//IL_0549: Unknown result type (might be due to invalid IL or missing references)
			//IL_054b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0550: Unknown result type (might be due to invalid IL or missing references)
			//IL_0555: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_050c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0511: Unknown result type (might be due to invalid IL or missing references)
			//IL_0513: Unknown result type (might be due to invalid IL or missing references)
			//IL_055d: Unknown result type (might be due to invalid IL or missing references)
			//IL_055f: Unknown result type (might be due to invalid IL or missing references)
			//IL_056f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0520: Unknown result type (might be due to invalid IL or missing references)
			//IL_0522: Unknown result type (might be due to invalid IL or missing references)
			//IL_0684: Unknown result type (might be due to invalid IL or missing references)
			//IL_06d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_05c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_05c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0698: Unknown result type (might be due to invalid IL or missing references)
			//IL_0770: Unknown result type (might be due to invalid IL or missing references)
			SlotDef def = ms.Def;
			if ((Object)(object)ShopScene.FindSlot(ms.FullId) != (Object)null)
			{
				return true;
			}
			ShopLocation val = SlotTemplates.Get(ms.FullId);
			if ((Object)(object)val == (Object)null)
			{
				SlotTemplates.BuildPending(Catalog);
				val = SlotTemplates.Get(ms.FullId);
			}
			if ((Object)(object)val == (Object)null)
			{
				MelonLogger.Warning("[POGLib] [Shops] slot " + ms.FullId + ": no template (the game's slot prefab is not in memory)");
				return false;
			}
			uint globalObjectIdHash = ((Component)val).GetComponent<NetworkObject>().GlobalObjectIdHash;
			NetworkManager singleton = NetworkManager.Singleton;
			object obj;
			if (singleton == null)
			{
				obj = null;
			}
			else
			{
				NetworkConfig networkConfig = singleton.NetworkConfig;
				if (networkConfig == null)
				{
					obj = null;
				}
				else
				{
					NetworkPrefabs prefabs = networkConfig.Prefabs;
					obj = ((prefabs != null) ? prefabs.NetworkPrefabOverrideLinks : null);
				}
			}
			Dictionary<uint, NetworkPrefab> val2 = (Dictionary<uint, NetworkPrefab>)obj;
			if (val2 != null && !val2.ContainsKey(globalObjectIdHash))
			{
				MelonLogger.Warning($"[POGLib] [Shops] slot {ms.FullId}: the game's slot prefab ({globalObjectIdHash}) is not a registered network prefab on this build; not placed");
				return false;
			}
			NpcSpawner val3 = (string.IsNullOrEmpty(def.Seller) ? null : ShopScene.FindSeller(def.Seller));
			if (!string.IsNullOrEmpty(def.Seller) && (Object)(object)val3 == (Object)null)
			{
				MelonLogger.Warning($"[POGLib] [Shops] slot {ms.FullId}: seller '{def.Seller}' not found; placed without a seller");
			}
			Vector3 pos;
			Transform val5;
			if (!string.IsNullOrEmpty(def.After))
			{
				bool? flag = SlotDef.SideOf(def.After);
				ShopLocation val4;
				if (flag.HasValue)
				{
					if ((Object)(object)val3 == (Object)null)
					{
						MelonLogger.Warning($"[POGLib] [Shops] slot {ms.FullId}: \"after\": \"{def.After}\" needs its seller, which is not here; not placed");
						return false;
					}
					val4 = EndOnSide(val3, flag.Value, out var why);
					if ((Object)(object)val4 == (Object)null)
					{
						MelonLogger.Warning($"[POGLib] [Shops] slot {ms.FullId}: no {def.After} end at {ShopScene.SellerId(val3)}: {why}; not placed");
						return false;
					}
				}
				else
				{
					val4 = ShopScene.FindSlot(def.After);
					if ((Object)(object)val4 == (Object)null)
					{
						MelonLogger.Warning($"[POGLib] [Shops] slot {ms.FullId}: the slot it goes after, '{def.After}', is not in scene {def.Scene}");
						return false;
					}
					if ((Object)(object)val3 == (Object)null)
					{
						val3 = val4.m_shopKeeper;
					}
				}
				if (!PlaceAfter(val4, val3, ms.FullId, ShopScene.SlotId(val4), out pos, out var why2))
				{
					MelonLogger.Warning($"[POGLib] [Shops] slot {ms.FullId}: cannot go after '{def.After}': {why2}; not placed");
					return false;
				}
				val5 = ((Component)val4).transform;
			}
			else
			{
				string text = (string.IsNullOrEmpty(def.Anchor) ? def.Seller : def.Anchor);
				val5 = ShopScene.FindAnchor(text);
				if ((Object)(object)val5 == (Object)null)
				{
					MelonLogger.Warning($"[POGLib] [Shops] slot {ms.FullId}: anchor '{text}' is not in scene {def.Scene}");
					return false;
				}
				pos = val5.TransformPoint(new Vector3(def.Pos[0], def.Pos[1], def.Pos[2]));
			}
			GameObject obj2 = Object.Instantiate<GameObject>(((Component)val).gameObject);
			((Object)obj2).name = "POGShopSlot|" + ms.FullId;
			Vector3 val6 = (Vector3)((def.Rot != null) ? new Vector3(def.Rot[0], def.Rot[1], def.Rot[2]) : Vector3.zero);
			string value = "";
			Quaternion val7;
			if (!string.IsNullOrEmpty(def.After))
			{
				val7 = Quaternion.Euler(0f, val5.eulerAngles.y + val6.y, 0f);
				if (TryFloorUnder(pos, out var ground, out var hitName))
				{
					pos = ground;
					value = ", on the floor (" + hitName + ")";
				}
				else
				{
					value = ", no floor found within 1 m: at the row's height";
				}
			}
			else
			{
				val7 = val5.rotation * Quaternion.Euler(val6);
			}
			obj2.transform.SetPositionAndRotation(pos, val7);
			ShopLocation component = obj2.GetComponent<ShopLocation>();
			Faction result = (Faction)0;
			if ((Object)(object)val3 != (Object)null)
			{
				component.m_shopKeeper = val3;
				ShopLocation val8 = ((IEnumerable<ShopLocation>)val3.m_itemsForSale).FirstOrDefault((Func<ShopLocation, bool>)((ShopLocation s) => (Object)(object)s != (Object)null && s.m_shopFaction != null));
				if ((Object)(object)val8 != (Object)null)
				{
					result = val8.m_shopFaction.Value;
				}
				AppendToSeller(val3, component);
			}
			else if (!string.IsNullOrEmpty(def.Faction) && !Enum.TryParse<Faction>(def.Faction, out result))
			{
				MelonLogger.Warning($"[POGLib] [Shops] slot {ms.FullId}: unknown faction '{def.Faction}' (use {string.Join(", ", Enum.GetNames(typeof(Faction)))})");
			}
			obj2.GetComponent<NetworkObject>().Spawn(true);
			if ((int)result != 0 && component.m_shopFaction != null)
			{
				component.m_shopFaction.Value = result;
			}
			MelonLogger.Msg($"[POGLib] [Shops] placed {ms.FullId} at {pos:F2} {(string.IsNullOrEmpty(def.After) ? "next to" : "in the row after")} {((Object)val5).name}{value}{(((Object)(object)val3 != (Object)null) ? $", sold by {ShopScene.SellerId(val3)} ({result})" : "")}");
			MelonCoroutines.Start(StockIfMissed(component, ms.FullId));
			return true;
		}

		private static bool TryFloorUnder(Vector3 at, out Vector3 ground, out string hitName)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: 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_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_0082: 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)
			ground = at;
			hitName = null;
			Il2CppStructArray<RaycastHit> val = Physics.RaycastAll(at + Vector3.up, Vector3.down, 2f, -1, (QueryTriggerInteraction)1);
			if (val == null)
			{
				return false;
			}
			float num = float.MaxValue;
			foreach (RaycastHit item in (Il2CppArrayBase<RaycastHit>)(object)val)
			{
				RaycastHit current = item;
				Collider collider = ((RaycastHit)(ref current)).collider;
				if (!((Object)(object)collider == (Object)null) && !collider.isTrigger && !((Object)(object)((Component)collider).GetComponentInParent<NetworkObject>() != (Object)null) && ((RaycastHit)(ref current)).distance < num)
				{
					num = ((RaycastHit)(ref current)).distance;
					ground = ((RaycastHit)(ref current)).point;
					hitName = ((Object)((Component)collider).gameObject).name;
				}
			}
			return hitName != null;
		}

		private static ShopLocation EndOnSide(NpcSpawner seller, bool right, out string why)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: 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_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			List<ShopLocation> list = OwnSlots(seller);
			Vector3 position = ((Component)seller).transform.position;
			if (!SlotRow.TryEndOnSide(list.Select(delegate(ShopLocation s)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0014: Unknown result type (might be due to invalid IL or missing references)
				//IL_001d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				Vector3 position2 = ((Component)s).transform.position;
				return new float[3] { position2.x, position2.y, position2.z };
			}).ToList(), new float[3] { position.x, position.y, position.z }, right, out var index, out why))
			{
				return null;
			}
			return list[index];
		}

		private static List<ShopLocation> OwnSlots(NpcSpawner seller)
		{
			if (((seller != null) ? seller.m_itemsForSale : null) != null)
			{
				return ((IEnumerable<ShopLocation>)seller.m_itemsForSale).Where((ShopLocation s) => (Object)(object)s != (Object)null && !((Object)((Component)s).gameObject).name.StartsWith("POGShopSlot|")).ToList();
			}
			return new List<ShopLocation>();
		}

		private static bool PlaceAfter(ShopLocation after, NpcSpawner seller, string fullId, string afterId, out Vector3 pos, out string why)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: 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_0095: 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_0126: Unknown result type (might be due to invalid IL or missing references)
			pos = default(Vector3);
			if (((seller != null) ? seller.m_itemsForSale : null) == null)
			{
				why = "it has no seller, so there is no row to follow";
				return false;
			}
			List<float[]> list = new List<float[]>();
			int num = -1;
			foreach (ShopLocation item in OwnSlots(seller))
			{
				if (((Il2CppObjectBase)item).Pointer == ((Il2CppObjectBase)after).Pointer)
				{
					num = list.Count;
				}
				Vector3 position = ((Component)item).transform.position;
				list.Add(new float[3] { position.x, position.y, position.z });
			}
			if (num < 0)
			{
				why = "it is not one of the slots of " + ShopScene.SellerId(seller);
				return false;
			}
			int num2 = _placedAfter.Count((KeyValuePair<string, string> kv) => kv.Value == afterId && kv.Key != fullId && (Object)(object)ShopScene.FindSlot(kv.Key) != (Object)null);
			if (!SlotRow.TryPlaceAfter(list, num, num2 + 1, out var pos2, out why))
			{
				return false;
			}
			_placedAfter[fullId] = afterId;
			pos = new Vector3(pos2[0], pos2[1], pos2[2]);
			return true;
		}

		private static IEnumerator StockIfMissed(ShopLocation slot, string id)
		{
			float deadline = Time.realtimeSinceStartup + 20f;
			while (Time.realtimeSinceStartup < deadline)
			{
				if ((Object)(object)slot == (Object)null || !IsHost || (Object)(object)slot.CurrentShopItem != (Object)null)
				{
					yield break;
				}
				if (ShopScene.SlotsInLoadedScenes().Any((ShopLocation s) => (Object)(object)s != (Object)null && ((Object)s).GetInstanceID() != ((Object)slot).GetInstanceID() && ((NetworkBehaviour)s).IsSpawned && (Object)(object)s.CurrentShopItem != (Object)null))
				{
					break;
				}
				yield return (object)new WaitForSeconds(0.5f);
			}
			yield return (object)new WaitForSeconds(1f);
			if (!((Object)(object)slot == (Object)null) && IsHost && !((Object)(object)slot.CurrentShopItem != (Object)null))
			{
				((MonoBehaviour)slot).StartCoroutine(slot.CreateShopItems());
				MelonLogger.Msg("[POGLib] [Shops] " + id + ": stocked by the library (placed after the scene's own slots were stocked).");
			}
		}

		private static void AppendToSeller(NpcSpawner seller, ShopLocation slot)
		{
			Il2CppReferenceArray<ShopLocation> itemsForSale = seller.m_itemsForSale;
			Il2CppReferenceArray<ShopLocation> val = new Il2CppReferenceArray<ShopLocation>((long)(((Il2CppArrayBase<ShopLocation>)(object)itemsForSale).Length + 1));
			for (int i = 0; i < ((Il2CppArrayBase<ShopLocation>)(object)itemsForSale).Length; i++)
			{
				((Il2CppArrayBase<ShopLocation>)(object)val)[i] = ((Il2CppArrayBase<ShopLocation>)(object)itemsForSale)[i];
			}
			((Il2CppArrayBase<ShopLocation>)(object)val)[((Il2CppArrayBase<ShopLocation>)(object)itemsForSale).Length] = slot;
			seller.m_itemsForSale = val;
		}
	}
	public static class ShopsApi
	{
		public static bool AddFile(ShopFile file)
		{
			if (ShopsPlugin.Instance != null)
			{
				return ShopsPlugin.Instance.AddFile(file);
			}
			return false;
		}

		public static void Reload()
		{
			ShopsPlugin.Instance?.Reload();
		}
	}
	internal static class ShopScene
	{
		public const string ModSlotPrefix = "POGShopSlot|";

		public static string SlotId(ShopLocation slot)
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)slot == (Object)null)
			{
				return null;
			}
			string name = ((Object)((Component)slot).gameObject).name;
			if (name.StartsWith("POGShopSlot|"))
			{
				return name.Substring("POGShopSlot|".Length).Replace("(Clone)", "");
			}
			Scene scene = ((Component)slot).gameObject.scene;
			return ShopIds.VanillaSlot(((Scene)(ref scene)).name, PathOf(((Component)slot).transform));
		}

		public static string SellerId(NpcSpawner seller)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)seller == (Object)null)
			{
				return null;
			}
			if (!string.IsNullOrEmpty(seller.m_npcFlag))
			{
				return "vanilla:" + seller.m_npcFlag;
			}
			Scene scene = ((Component)seller).gameObject.scene;
			return ShopIds.VanillaSlot(((Scene)(ref scene)).name, PathOf(((Component)seller).transform));
		}

		public static string PathOf(Transform t)
		{
			//IL_0074: 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)
			List<string> list = new List<string>();
			Transform val = t;
			while ((Object)(object)val != (Object)null)
			{
				string name = ((Object)val).name;
				Transform parent = val.parent;
				int num = 0;
				int num2 = 0;
				if ((Object)(object)parent != (Object)null)
				{
					for (int i = 0; i < parent.childCount; i++)
					{
						Transform child = parent.GetChild(i);
						if (!(((Object)child).name != name))
						{
							num++;
							if ((Object)(object)child == (Object)(object)val)
							{
								num2 = num;
							}
						}
					}
				}
				else
				{
					Scene scene = ((Component)val).gameObject.scene;
					foreach (GameObject item in (Il2CppArrayBase<GameObject>)(object)((Scene)(ref scene)).GetRootGameObjects())
					{
						if (!(((Object)item).name != name))
						{
							num++;
							if ((Object)(object)item.transform == (Object)(object)val)
							{
								num2 = num;
							}
						}
					}
				}
				list.Add((num2 > 1) ? (name + "#" + num2) : name);
				val = val.parent;
			}
			list.Reverse();
			return string.Join("/", list);
		}

		public static bool IsTemplate(Transform t)
		{
			if ((Object)(object)t != (Object)null && (Object)(object)t.root != (Object)null)
			{
				return ((Object)t.root).name.StartsWith("POGLib_");
			}
			return false;
		}

		public static IEnumerable<ShopLocation> SlotsInLoadedScenes()
		{
			return ((IEnumerable<ShopLocation>)Object.FindObjectsOfType<ShopLocation>(true)).Where((ShopLocation s) => (Object)(object)s != (Object)null && !IsTemplate(((Component)s).transform));
		}

		public static IEnumerable<NpcSpawner> SellersInLoadedScenes()
		{
			return ((IEnumerable<NpcSpawner>)Object.FindObjectsOfType<NpcSpawner>(true)).Where((NpcSpawner s) => (Object)(object)s != (Object)null && !IsTemplate(((Component)s).transform) && s.m_itemsForSale != null && ((Il2CppArrayBase<ShopLocation>)(object)s.m_itemsForSale).Length > 0);
		}

		public static NpcSpawner FindSeller(string sellerId)
		{
			if (!string.IsNullOrEmpty(sellerId))
			{
				return ((IEnumerable<NpcSpawner>)Object.FindObjectsOfType<NpcSpawner>(true)).FirstOrDefault((Func<NpcSpawner, bool>)((NpcSpawner s) => (Object)(object)s != (Object)null && !IsTemplate(((Component)s).transform) && SellerId(s) == sellerId));
			}
			return null;
		}

		public static ShopLocation FindSlot(string slotId)
		{
			if (!string.IsNullOrEmpty(slotId))
			{
				return SlotsInLoadedScenes().FirstOrDefault((Func<ShopLocation, bool>)((ShopLocation s) => SlotId(s) == slotId));
			}
			return null;
		}

		public static Transform FindAnchor(string anchorId)
		{
			NpcSpawner val = FindSeller(anchorId);
			if ((Object)(object)val != (Object)null)
			{
				return ((Component)val).transform;
			}
			ShopLocation val2 = FindSlot(anchorId);
			if ((Object)(object)val2 != (Object)null)
			{
				return ((Component)val2).transform;
			}
			return null;
		}

		public static List<VanillaEntry> VanillaEntriesOf(ShopLocation slot)
		{
			List<VanillaEntry> list = new List<VanillaEntry>();
			if (((SpawnerBase)slot).HasNetworkPrefab)
			{
				string text = Addresses.PrefabNameOf((AssetReference)(object)((SpawnerBase)slot).m_networkPrefabRef) ?? (((Object)(object)((SpawnerBase)slot).m_loadedPrefab != (Object)null) ? CleanName(((Object)((SpawnerBase)slot).m_loadedPrefab).name) : null);
				if (text != null)
				{
					list.Add(new VanillaEntry(ShopIds.VanillaItem(text), 1));
				}
			}
			else if (slot.HasLootTable)
			{
				AssetReferenceT<InventoryLootTable> lootTableRef = slot.m_lootTableRef;
				Dictionary<string, int> dictionary = Addresses.ReadNow<InventoryLootTable, Dictionary<string, int>>((lootTableRef != null) ? ((AssetReference)lootTableRef).AssetGUID : null, (Func<InventoryLootTable, Dictionary<string, int>>)delegate(InventoryLootTable table)
				{
					Dictionary<string, int> dictionary2 = new Dictionary<string, int>();
					List<InventoryItem> items = table.Items;
					if (items == null)
					{
						return dictionary2;
					}
					for (int i = 0; i < items.Count; i++)
					{
						InventoryItem val = items[i];
						if (!((Object)(object)val == (Object)null))
						{
							string key = ShopIds.VanillaItem(CleanName(((Object)((Component)val).gameObject).name));
							dictionary2[key] = ((!dictionary2.TryGetValue(key, out var value)) ? 1 : (value + 1));
						}
					}
					return dictionary2;
				});
				if (dictionary != null)
				{
					foreach (KeyValuePair<string, int> item in dictionary)
					{
						list.Add(new VanillaEntry(item.Key, item.Value));
					}
				}
			}
			return list;
		}

		public static NetworkObject ResolveItemPrefab(string itemId)
		{
			if (!ShopIds.TrySplit(itemId, out var owner, out var local))
			{
				return null;
			}
			if (owner == "vanilla")
			{
				InventoryItem val = GameAssets.FindItemPrefab(local);
				if (!((Object)(object)val != (Object)null))
				{
					return null;
				}
				return ((Component)val).GetComponent<NetworkObject>();
			}
			NetworkObject prefabByHash = CoreServices.Content.GetPrefabByHash(ContentRegistry.ComputeHash(owner, local, 0));
			if (IsItem(prefabByHash, itemId))
			{
				return prefabByHash;
			}
			foreach (NetworkObject allPrefab in CoreServices.Content.AllPrefabs)
			{
				if (IsItem(allPrefab, itemId))
				{
					return allPrefab;
				}
			}
			return null;
		}

		private static bool IsItem(NetworkObject p, string itemId)
		{
			if ((Object)(object)p == (Object)null)
			{
				return false;
			}
			InventoryItem component = ((Component)p).GetComponent<InventoryItem>();
			if ((Object)(object)component != (Object)null)
			{
				return component.m_itemID == itemId;
			}
			return false;
		}

		public static string CleanName(string n)
		{
			return n?.Replace("(Clone)", "").Trim();
		}
	}
	public sealed class ShopsMod : MelonMod
	{
		internal const string VERSION = "0.1.0";

		private const string Tag = "[POGShops]";

		private const string BuiltForCore = "0.1.0";

		private static readonly (Type type, string[] members)[] Expected = new(Type, string[])[2]
		{
			(typeof(ShopLocation), new string[5] { "m_lootTableRef", "m_itemHolder", "m_priceTagText", "LoadLootTable", "CreateShopItems" }),
			(typeof(SpawnerBase), new string[4] { "m_networkPrefabRef", "m_loadedPrefab", "LoadNetworkPrefab", "HasNetworkPrefab" })
		};

		private static readonly (string name, Func<Type> touch)[] CompiledBindings = new(string, Func<Type>)[2]
		{
			("ShopLocation", () => typeof(ShopLocation)),
			("NpcSpawner", () => typeof(NpcSpawner))
		};

		private bool _on;

		private bool _patchesChecked;

		public override void OnInitializeMelon()
		{
			MelonInfoAttribute? customAttribute = typeof(Plugin).Assembly.GetCustomAttribute<MelonInfoAttribute>();
			string text = ((customAttribute != null) ? customAttribute.Version : null) ?? "?";
			if (MajorMinor(text) != MajorMinor("0.1.0"))
			{
				MelonLogger.Error($"{"[POGShops]"} This POGShops {"0.1.0"} is built for POGLib {MajorMinor("0.1.0")}.x, but POGLib {text} " + "is installed: shops stay off (mod items still work). Install the POGShops that matches this POGLib.");
			}
			else if (!CoreServices.Ready)
			{
				MelonLogger.Error("[POGShops] POGLib did not start (see its lines above): shops stay off.");
			}
			else
			{
				_on = true;
				CompatibilityProbe.Check("[POGShops]", Expected, CompiledBindings);
				PluginRegistry.Add((IPOGPlugin)(object)new ShopsPlugin());
				HarmonyPatcher.PatchEachClass(typeof(ShopsMod).Assembly, ((MelonBase)this).HarmonyInstance, "[POGShops]");
				ShopDevTools.Init();
				MelonLogger.Msg($"{"[POGShops]"} {"0.1.0"} started on POGLib {text}.");
			}
		}

		public override void OnSceneWasLoaded(int buildIndex, string sceneName)
		{
			if (_on && !_patchesChecked)
			{
				_patchesChecked = true;
				HarmonyPatcher.CheckEachPatchOnce(((MelonBase)this).HarmonyInstance, "[POGShops]");
			}
		}

		public override void OnUpdate()
		{
			if (_on)
			{
				ShopDevTools.OnUpdate();
			}
		}

		public override void OnGUI()
		{
			if (_on)
			{
				ShopDevTools.OnGUI();
			}
		}

		private static string MajorMinor(string version)
		{
			string[] array = (version ?? "").Split('.');
			if (array.Length < 2)
			{
				return version;
			}
			return array[0] + "." + array[1];
		}
	}
	internal sealed class ShopsPlugin : IPOGPlugin
	{
		private readonly List<ShopFile> _codeFiles = new List<ShopFile>();

		private List<ShopFile> _files = new List<ShopFile>();

		private readonly List<Diagnostic> _loadDiagnostics = new List<Diagnostic>();

		public const string PreferencesCategory = "POGLib_Shops";

		private MelonPreferences_Entry<double> _vanillaWeight;

		private bool _badWeightReported;

		public string Name => "Shops";

		public string Version => "0.1.0";

		public static ShopsPlugin Instance { get; private set; }

		public ShopCatalog Catalog { get; private set; }

		public IReadOnlyList<ShopFile> Files => _files;

		public IReadOnlyList<Diagnostic> LoadDiagnostics => _loadDiagnostics;

		public static string UserShopsDirectory => Path.Combine(MelonEnvironment.UserDataDirectory, "POGLib", "Shops");

		public void Build(PluginGraph graph)
		{
			Instance = this;
			SlotSync.Register();
			MelonPreferences_Category val = MelonPreferences.CreateCategory("POGLib_Shops", "POGLib shops");
			_vanillaWeight = val.CreateEntry<double>("VanillaWeight", 10.0, "Vanilla item weight", $"When a mod adds items to a game shop slot, each of the game's own items there gets this weight. Mods weigh their items against {10.0:0}: a mod item of weight {10.0:0} " + "is as likely as a vanilla one. 0 = only the mods' items in such slots. Applies on the host, from the next scene.", false, false, (ValueValidator)null, (string)null);
			graph.AddSystem((PluginStage)1, Name, (Action)delegate
			{
				if (Catalog == null || Catalog.Options.DefaultVanillaWeight != Options().DefaultVanillaWeight)
				{
					Reload();
				}
				SellerTemplates.ApplyItemDisplays(Catalog);
				SlotTemplates.BuildPending(Catalog);
				SellerTemplates.BuildPending(Catalog);
				ShopRuntime.OnSceneLoaded();
			});
			graph.AddSystem((PluginStage)4, Name, (Action)delegate
			{
				if (Catalog == null)
				{
					Reload();
				}
				SellerTemplates.ApplyItemDisplays(Catalog);
				SlotTemplates.BuildPending(Catalog);
			});
			graph.AddSystem((PluginStage)2, Name, (Action)delegate
			{
				ShopChecks.CheckModItems(Catalog);
			});
			graph.AddSystem((PluginStage)3, Name, (Action)delegate
			{
				ShopRuntime.Reset();
				ShopEmptySlots.Reset();
				SlotSync.Reset();
			});
		}

		public ShopCatalogOptions Options()
		{
			double num = _vanillaWeight?.Value ?? 10.0;
			if (ShopCatalogOptions.IsValidVanillaWeight(num))
			{
				return new ShopCatalogOptions
				{
					DefaultVanillaWeight = num
				};
			}
			if (!_badWeightReported)
			{
				_badWeightReported = true;
				MelonLogger.Warning($"[POGLib] [Shops] {"POGLib_Shops"}.VanillaWeight = {num} is not a number >= 0; using {10.0:0}.");
			}
			return new ShopCatalogOptions();
		}

		public bool AddFile(ShopFile file)
		{
			List<Diagnostic> list = new List<Diagnostic>();
			if (file.SourcePath == null)
			{
				string text = (file.SourcePath = "code:" + file.Mod);
			}
			bool num = ShopFileIO.Validate(file, list) && ShopFileIO.CheckModScope(file, list);
			Log(list);
			if (!num)
			{
				return false;
			}
			_codeFiles.Add(file);
			if (Catalog != null)
			{
				Reload();
			}
			return true;
		}

		public void Reload()
		{
			_loadDiagnostics.Clear();
			List<ShopFile> list = new List<ShopFile>();
			foreach (string item in FindFiles())
			{
				try
				{
					ShopFile shopFile = ShopFileIO.Parse(File.ReadAllText(item), Relative(item), _loadDiagnostics);
					if (shopFile != null)
					{
						list.Add(shopFile);
					}
				}
				catch (Exception ex)
				{
					_loadDiagnostics.Add(new Diagnostic(Severity.Error, Relative(item), "cannot read: " + ex.Message));
				}
			}
			string userDir = Path.GetFullPath(UserShopsDirectory);
			HashSet<string> packaged = new HashSet<string>(from f in list
				where !IsUserFile(f, userDir)
				select f.Mod, StringComparer.Ordinal);
			HashSet<string> overridden = new HashSet<string>(from f in list
				where IsUserFile(f, userDir)
				select f.Mod, StringComparer.Ordinal);
			foreach (string mod in overridden)
			{
				foreach (ShopFile item2 in list.Where((ShopFile f) => f.Mod == mod && !IsUserFile(f, userDir)))
				{
					_loadDiagnostics.Add(new Diagnostic(Severity.Info, item2.SourcePath, "replaced by your working copy in UserData/POGLib/Shops (" + mod + ")"));
				}
			}
			list = list.Where((ShopFile f) => !overridden.Contains(f.Mod) || IsUserFile(f, userDir)).ToList();
			list = list.Where((ShopFile f) => !packaged.Contains(f.Mod) || ShopFileIO.CheckModScope(f, _loadDiagnostics)).ToList();
			list.AddRange(_codeFiles);
			_files = list;
			Catalog = ShopCatalog.Build(list, Options());
			Log(_loadDiagnostics);
			Log(Catalog.Diagnostics);
			MelonLogger.Msg($"[POGLib] [Shops] {list.Count} shop file(s) from {list.Select((ShopFile f) => f.Mod).Distinct().Count()} mod(s): {Catalog.ModSlots.Count} new slot(s), {Catalog.TargetedSlots.Count()} slot(s) with rules, {Catalog.Sellers.Count} merchant(s); order {string.Join(" > ", Catalog.ModOrder)}" + ((Catalog.Options.DefaultVanillaWeight != 10.0) ? $"; vanilla weight {Catalog.Options.DefaultVanillaWeight:0.##} (player setting)" : ""));
		}

		private static bool IsUserFile(ShopFile f, string userDir)
		{
			string path = Path.Combine(MelonEnvironment.GameRootDirectory, f.SourcePath ?? "");
			try
			{
				return Path.GetFullPath(path).StartsWith(userDir, StringComparison.OrdinalIgnoreCase) || Path.GetFullPath(f.SourcePath ?? "").StartsWith(userDir, StringComparison.OrdinalIgnoreCase);
			}
			catch
			{
				return false;
			}
		}

		private static IEnumerable<string> FindFiles()
		{
			List<string> list = new List<string>();
			try
			{
				if (Directory.Exists(MelonEnvironment.ModsDirectory))
				{
					list.AddRange(Directory.EnumerateFiles(MelonEnvironment.ModsDirectory, "*.json", SearchOption.AllDirectories).Where(delegate(string p)
					{
						string text = Path.GetFileName(p).ToLowerInvariant();
						return text == "pogshop.json" || text.EndsWith(".pogshop.json");
					}));
				}
				if (Directory.Exists(UserShopsDirectory))
				{
					list.AddRange(Directory.EnumerateFiles(UserShopsDirectory, "*.json", SearchOption.TopDirectoryOnly));
				}
			}
			catch (Exception ex)
			{
				MelonLogger.Warning("[POGLib] [Shops] searching for shop files: " + ex.Message);
			}
			return list.OrderBy<string, string>((string p) => p, StringComparer.Ordinal);
		}

		private static string Relative(string path)
		{
			string gameRootDirectory = MelonEnvironment.GameRootDirectory;
			if (!path.StartsWith(gameRootDirectory))
			{
				return path;
			}
			return path.Substring(gameRootDirectory.Length).TrimStart('/', '\\');
		}

		private static void Log(IEnumerable<Diagnostic> diagnostics)
		{
			foreach (Diagnostic diagnostic in diagnostics)
			{
				string text = "[POGLib] [Shops] " + diagnostic.Source + ": " + diagnostic.Message;
				switch (diagnostic.Severity)
				{
				case Severity.Error:
					MelonLogger.Error(text);
					break;
				case Severity.Warning:
					MelonLogger.Warning(text);
					break;
				default:
					MelonLogger.Msg(text);
					break;
				}
			}
		}
	}
	internal static class SlotSync
	{
		public const string AskAction = "shops.slot?";

		public const string InfoAction = "shops.slot";

		private const float AskWithin = 60f;

		private static bool _registered;

		private static readonly List<ulong> _pending = new List<ulong>();

		private static bool _flushing;

		private static bool _badAnswerReported;

		public static void Register()
		{
			if (!_registered && CoreServices.Bridge != null)
			{
				CoreServices.Bridge.RegisterHandler("shops.slot?", (Action<ulong, string>)OnAsk);
				CoreServices.Bridge.RegisterHandler("shops.slot", (Action<ulong, string>)OnInfo);
				_registered = true;
			}
		}

		public static void Reset()
		{
			_pending.Clear();
		}

		public static void OnClientSlotSpawned(ShopLocation slot)
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)slot == (Object)null || (Object)(object)singleton == (Object)null || singleton.IsServer)
			{
				return;
			}
			NetworkObject component = ((Component)slot).GetComponent<NetworkObject>();
			if ((Object)(object)component == (Object)null)
			{
				return;
			}
			string name = ((Object)((Component)slot).gameObject).name;
			if (!name.StartsWith("POGShopSlot|") && name.EndsWith("(Clone)"))
			{
				_pending.Add(component.NetworkObjectId);
				if (!_flushing)
				{
					_flushing = true;
					MelonCoroutines.Start(AskWhenConnected());
				}
			}
		}

		private static IEnumerator AskWhenConnected()
		{
			float deadline = Time.realtimeSinceStartup + 60f;
			while (Time.realtimeSinceStartup < deadline)
			{
				NetworkManager singleton = NetworkManager.Singleton;
				if ((Object)(object)singleton == (Object)null || !singleton.IsListening)
				{
					break;
				}
				if (singleton.IsConnectedClient)
				{
					foreach (ulong item in _pending)
					{
						HostBridge bridge = CoreServices.Bridge;
						if (bridge != null)
						{
							bridge.SendToServer("shops.slot?", SlotInfo.Ask(item));
						}
					}
					_pending.Clear();
					break;
				}
				yield return (object)new WaitForSeconds(0.25f);
			}
			_pending.Clear();
			_flushing = false;
		}

		private static void OnInfo(ulong sender, string payload)
		{
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || singleton.IsServer || sender != NetworkManager.ServerClientId)
			{
				return;
			}
			if (!SlotInfo.TryDecode(payload, out var info))
			{
				if (!_badAnswerReported)
				{
					MelonLogger.Warning("[POGLib] [Shops] The host described a slot in a form this version cannot read: '" + payload + "'.");
				}
				_badAnswerReported = true;
				return;
			}
			ShopLocation val = SpawnedSlot(singleton, info.NetworkId);
			if ((Object)(object)val == (Object)null)
			{
				MelonLogger.Msg("[POGLib] [Shops] " + info.SlotId + ": the slot left before the host's answer came.");
				return;
			}
			((Object)((Component)val).gameObject).name = "POGShopSlot|" + info.SlotId;
			Transform val2 = (((Object)(object)val.m_priceTagText != (Object)null) ? SlotTemplates.TopChildOf(val.m_priceTagText.transform, ((Component)val).transform) : null);
			if ((Object)(object)val2 != (Object)null)
			{
				if (info.TagPos != null)
				{
					val2.localPosition = new Vector3(info.TagPos[0], info.TagPos[1], info.TagPos[2]);
				}
				if (info.TagRot != null)
				{
					val2.localEulerAngles = new Vector3(info.TagRot[0], info.TagRot[1], info.TagRot[2]);
				}
				if (info.TagHidden)
				{
					((Component)val2).gameObject.SetActive(false);
				}
			}
			MelonLogger.Msg($"[POGLib] [Shops] {info.SlotId}: shown as the host placed it (price tag {(((Object)(object)val2 == (Object)null) ? "not found" : (info.TagHidden ? "hidden" : "posed"))}).");
		}

		private static void OnAsk(ulong sender, string payload)
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsServer || !SlotInfo.TryReadAsk(payload, out var networkId))
			{
				return;
			}
			ShopLocation val = SpawnedSlot(singleton, networkId);
			if (!((Object)(object)val == (Object)null) && ((Object)((Component)val).gameObject).name.StartsWith("POGShopSlot|"))
			{
				HostBridge bridge = CoreServices.Bridge;
				if (bridge != null)
				{
					bridge.SendToClient(sender, "shops.slot", Describe(networkId, val).Encode());
				}
			}
		}

		internal static SlotInfo Describe(ulong id, ShopLocation slot)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: 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_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: 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)
			float[] tagPos = null;
			float[] tagRot = null;
			bool tagHidden = false;
			if ((Object)(object)slot.m_priceTagText != (Object)null)
			{
				Transform val = SlotTemplates.TopChildOf(slot.m_priceTagText.transform, ((Component)slot).transform);
				Vector3 localPosition = val.localPosition;
				Vector3 localEulerAngles = val.localEulerAngles;
				tagPos = new float[3] { localPosition.x, localPosition.y, localPosition.z };
				tagRot = new float[3] { localEulerAngles.x, localEulerAngles.y, localEulerAngles.z };
				tagHidden = !((Component)val).gameObject.activeSelf;
			}
			return new SlotInfo(id, ShopScene.SlotId(slot), tagPos, tagRot, tagHidden);
		}

		private static ShopLocation SpawnedSlot(NetworkManager nm, ulong id)
		{
			NetworkSpawnManager spawnManager = nm.SpawnManager;
			Dictionary<ulong, NetworkObject> val = ((spawnManager != null) ? spawnManager.SpawnedObjects : null);
			if (val == null || !val.ContainsKey(id))
			{
				return null;
			}
			NetworkObject val2 = val[id];
			if (!((Object)(object)val2 != (Object)null))
			{
				return null;
			}
			return ((Component)val2).GetComponent<ShopLocation>();
		}
	}
	internal static class SlotTemplates
	{
		internal const string FloorTemplate = "ShopLocationSlim";

		private static GameObject _holder;

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

		internal static ShopLocation Donor => FindDonor(null);

		public static int Count => _built.Count;

		internal static GameObject Holder
		{
			get
			{
				EnsureHolder();
				return _holder;
			}
		}

		public static ShopLocation Get(string fullSlotId)
		{
			if (!_built.TryGetValue(fullSlotId, out var value))
			{
				return null;
			}
			return value;
		}

		public static void BuildPending(ShopCatalog catalog)
		{
			if (catalog == null)
			{
				return;
			}
			List<ShopCatalog.ModSlot> list = catalog.ModSlots.Values.Where((ShopCatalog.ModSlot s) => !_built.ContainsKey(s.FullId)).ToList();
			if (list.Count == 0)
			{
				return;
			}
			ShopLocation val = FindDonor(null);
			if ((Object)(object)val == (Object)null)
			{
				MelonLogger.Msg("[POGLib] [Shops] No vanilla shop slot in memory yet to copy for new slots (will retry on the next scene).");
				return;
			}
			EnsureHolder();
			foreach (ShopCatalog.ModSlot item in list)
			{
				ShopLocation val2 = Build(FindDonor((!string.IsNullOrEmpty(item.Def.Template)) ? item.Def.Template : ((!string.IsNullOrEmpty(item.Def.After)) ? "ShopLocationSlim" : null)) ?? val, item);
				if ((Object)(object)val2 != (Object)null)
				{
					_built[item.FullId] = val2;
				}
			}
			MelonLogger.Msg($"[POGLib] [Shops] Slot templates ready: {_built.Count} (copied from the game's '{((Object)((Component)val).gameObject).name}', network hash {((Component)val).GetComponent<NetworkObject>().GlobalObjectIdHash}; nothing new to register).");
		}

		private static ShopLocation FindDonor(string preferredName)
		{
			List<ShopLocation> source = ((IEnumerable<ShopLocation>)Resources.FindObjectsOfTypeAll<ShopLocation>()).Where(delegate(ShopLocation s)
			{
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0014: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)s != (Object)null)
				{
					Scene scene = ((Component)s).gameObject.scene;
					if (!((Scene)(ref scene)).IsValid() && (Object)(object)((Component)s).GetComponent<NetworkObject>() != (Object)null && (Object)(object)s.m_priceTagText != (Object)null)
					{
						return (Object)(object)s.m_itemHolder != (Object)null;
					}
				}
				return false;
			}).ToList();
			if (!string.IsNullOrEmpty(preferredName))
			{
				string owner;
				string local2;
				string local = (ShopIds.TrySplit(preferredName, out owner, out local2) ? local2 : preferredName);
				ShopLocation val = ((IEnumerable<ShopLocation>)source).FirstOrDefault((Func<ShopLocation, bool>)((ShopLocation s) => ((Object)((Component)s).gameObject).name == local || ((Object)((Component)s).gameObject).name.EndsWith(local)));
				if ((Object)(object)val != (Object)null)
				{
					return val;
				}
			}
			return source.FirstOrDefault();
		}

		private static void EnsureHolder()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			if (!((Object)(object)_holder != (Object)null))
			{
				_holder = new GameObject("POGLib_ShopTemplates");
				_holder.SetActive(false);
				Object.DontDestroyOnLoad((Object)(object)_holder);
				((Object)_holder).hideFlags = (HideFlags)61;
			}
		}

		private static ShopLocation Build(ShopLocation donor, ShopCatalog.ModSlot s)
		{
			//IL_00a4: 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)
			GameObject val = Object.Instantiate<GameObject>(((Component)donor).gameObject, _holder.transform);
			((Object)val).name = "POGShopSlot|" + s.FullId;
			val.SetActive(true);
			ShopLocation component = val.GetComponent<ShopLocation>();
			((SpawnerBase)component).m_networkPrefabRef = null;
			component.m_lootTableRef = null;
			component.m_shopKeeper = null;
			TagDef priceTag = s.Def.PriceTag;
			if (priceTag != null && (Object)(object)component.m_priceTagText != (Object)null)
			{
				Transform val2 = TopChildOf(component.m_priceTagText.transform, val.transform);
				if (priceTag.Pos != null)
				{
					val2.localPosition = new Vector3(priceTag.Pos[0], priceTag.Pos[1], priceTag.Pos[2]);
				}
				if (priceTag.Rot != null)
				{
					val2.localEulerAngles = new Vector3(priceTag.Rot[0], priceTag.Rot[1], priceTag.Rot[2]);
				}
			}
			return component;
		}

		internal static Transform TopChildOf(Transform t, Transform root)
		{
			Transform val = t;
			while ((Object)(object)val.parent != (Object)null && (Object)(object)val.parent != (Object)(object)root)
			{
				val = val.parent;
			}
			if (!((Object)(object)val.parent == (Object)(object)root))
			{
				return t;
			}
			return val;
		}
	}
}
namespace POGLib.Shops.Model
{
	internal sealed class HistoryRecord
	{
		public string Mod { get; }

		public string Text { get; }

		public HistoryRecord(string mod, string text)
		{
			Mod = mod;
			Text = text;
		}

		public override string ToString()
		{
			return Mod + ": " + Text;
		}
	}
	internal sealed class SlotEntry
	{
		public string Item { get; internal set; }

		public double Weight { get; internal set; }

		public string AddedBy { get; }

		public SlotEntry(string item, double weight, string addedBy)
		{
			Item = item;
			Weight = weight;
			AddedBy = addedBy;
		}

		public override string ToString()
		{
			return $"{Item} x{Weight} ({AddedBy})";
		}
	}
	internal sealed class ResolvedSlot
	{
		public string SlotId { get; }

		public IReadOnlyList<SlotEntry> Entries { get; }

		public IReadOnlyList<HistoryRecord> History { get; }

		public double TotalWeight { get; }

		public bool Untouched { get; }

		internal ResolvedSlot(string slotId, List<SlotEntry> entries, List<HistoryRecord> history, bool untouched)
		{
			SlotId = slotId;
			Entries = entries;
			History = history;
			TotalWeight = entries.Sum((SlotEntry e) => e.Weight);
			Untouched = untouched;
		}

		public double ChanceOf(SlotEntry e)
		{
			if (!(TotalWeight > 0.0))
			{
				return 0.0;
			}
			return e.Weight / TotalWeight;
		}

		public double ChanceOfItem(string item)
		{
			if (!(TotalWeight > 0.0))
			{
				return 0.0;
			}
			return Entries.Where((SlotEntry e) => e.Item == item).Sum((SlotEntry e) => e.Weight) / TotalWeight;
		}

		public SlotEntry Pick(double r, Func<SlotEntry, bool> usable = null)
		{
			int num = WeightedPick.Index(Entries, (SlotEntry e) => (usable != null && !usable(e)) ? 0.0 : e.Weight, r);
			if (num >= 0)
			{
				return Entries[num];
			}
			return null;
		}

		public double ChanceAmong(SlotEntry e, Func<SlotEntry, bool> usable)
		{
			double num = Entries.Where((SlotEntry x) => usable(x) && WeightedPick.Usable(x.Weight)).Sum((SlotEntry x) => x.Weight);
			if (!(num > 0.0) || !usable(e) || !WeightedPick.Usable(e.Weight))
			{
				return 0.0;
			}
			return e.Weight / num;
		}
	}
	internal readonly struct VanillaEntry
	{
		public string Item { get; }

		public int Count { get; }

		public VanillaEntry(string item, int count)
		{
			Item = item;
			Count = count;
		}
	}
	internal sealed class ShopCatalog
	{
		private enum OpKind
		{
			Add,
			SetWeight,
			Remove,
			Replace
		}

		private sealed class Op
		{
			public OpKind Kind;

			public string Mod;

			public string Item;

			public double Weight;

			public string ReplaceWith;
		}

		public sealed class ModSlot
		{
			public string FullId { get; internal set; }

			public string Mod { get; internal set; }

			public SlotDef Def { get; internal set; }
		}

		public sealed class ModSeller
		{
			public string FullId { get; internal set; }

			public string Mod { get; internal set; }

			public SellerDef Def { get; internal set; }
		}

		private readonly Dictionary<string, List<Op>> _ops = new Dictionary<string, List<Op>>(StringComparer.Ordinal);

		private readonly Dictionary<string, ModSlot> _modSlots = new Dictionary<string, ModSlot>(StringComparer.Ordinal);

		private readonly List<ModSeller> _sellers = new List<ModSeller>();

		private readonly Dictionary<string, (string mod, List<PoolEntry> pool)> _sellerSlots = new Dictionary<string, (string, List<PoolEntry>)>(StringComparer.Ordinal);

		private readonly Dictionary<string, (string mod, TagDef standing)> _displays = new Dictionary<string, (string, TagDef)>(StringComparer.Ordinal);

		private readonly List<Diagnostic> _diagnostics = new List<Diagnostic>();

		private readonly List<ItemReference> _itemRefs = new List<ItemReference>();

		public ShopCatalogOptions Options { get; }

		public IReadOnlyList<string> ModOrder { get; private set; } = Array.Empty<string>();

		public IReadOnlyDictionary<string, ModSlot> ModSlots => _modSlots;

		public IReadOnlyList<ModSeller> Sellers => _sellers;

		public IReadOnlyDictionary<string, (string mod, TagDef standing)> ItemDisplays => _displays;

		public IReadOnlyList<Diagnostic> Diagnostics => _diagnostics;

		public IEnumerable<string> TargetedSlots => _ops.Keys.Concat(_modSlots.Keys).Concat(_sellerSlots.Keys).Distinct();

		public IReadOnlyList<ItemReference> ItemReferences => _itemRefs;

		public static string SellerSlotId(string fullSellerId, int n)
		{
			return fullSellerId + "#" + n;
		}

		private ShopCatalog(ShopCatalogOptions options)
		{
			Options = options ?? new ShopCatalogOptions();
		}

		public static ShopCatalog Build(IEnumerable<ShopFile> files, ShopCatalogOptions options = null)
		{
			ShopCatalog shopCatalog = new ShopCatalog(options);
			shopCatalog.BuildFrom(files.Where((ShopFile f) => f != null).ToList());
			return shopCatalog;
		}

		private void BuildFrom(List<ShopFile> files)
		{
			Dictionary<string, List<ShopFile>> dictionary = new Dictionary<string, List<ShopFile>>(StringComparer.Ordinal);
			foreach (ShopFile item in files.OrderBy<ShopFile, string>((ShopFile f) => f.SourcePath ?? "", StringComparer.Ordinal))
			{
				if (!dictionary.TryGetValue(item.Mod, out var value))
				{
					value = (dictionary[item.Mod] = new List<ShopFile>());
				}
				value.Add(item);
			}
			ModOrder = OrderMods(dictionary);
			Dictionary<string, HashSet<string>> requires = new Dictionary<string, HashSet<string>>(StringComparer.Ordinal);
			foreach (KeyValuePair<string, List<ShopFile>> item2 in dictionary)
			{
				requires[item2.Key] = RequiresOf(item2.Value, null);
			}
			foreach (string item3 in ModOrder)
			{
				foreach (ShopFile item4 in dictionary[item3])
				{
					foreach (SlotDef slot in item4.Slots)
					{
						string text = item3 + ":" + slot.Id;
						if (_modSlots.ContainsKey(text))
						{
							Diag(Severity.Error, item4, "slot '" + text + "' is defined twice; the second is ignored");
							continue;
						}
						_modSlots[text] = new ModSlot
						{
							FullId = text,
							Mod = item3,
							Def = slot
						};
					}
					foreach (SellerDef seller in item4.Sellers)
					{
						string text2 = item3 + ":" + seller.Id;
						_sellers.Add(new ModSeller
						{
							FullId = text2,
							Mod = item3,
							Def = seller
						});
						for (int num = 0; num < (seller.Slots?.Count ?? 0); num++)
						{
							if (seller.Slots[num] != null && seller.Slots[num].Count > 0)
							{
								_sellerSlots[SellerSlotId(text2, num + 1)] = (item3, seller.Slots[num]);
							}
						}
					}
					foreach (ItemDisplayDef item5 in item4.Items)
					{
						string text3 = ShopIds.Qualify(item5.Item, item3);
						if (_displays.ContainsKey(text3))
						{
							Diag(Severity.Warning, item4, "standing point of " + text3 + " is set twice; the later one is used");
						}
						_displays[text3] = (item3, item5.Standing);
					}
				}
			}
			foreach (string item6 in ModOrder)
			{
				foreach (ShopFile item7 in dictionary[item6])
				{
					foreach (AddOp item8 in item7.Add)
					{
						AddOpTo(ShopIds.Qualify(item8.Slot, item6), new Op
						{
							Kind = OpKind.Add,
							Mod = item6,
							Item = ShopIds.Qualify(item8.Item, item6),
							Weight = item8.Weight
						});
					}
				}
			}
			foreach (string mod in ModOrder)
			{
				foreach (ShopFile item9 in dictionary[mod])
				{
					foreach (PatchOp item10 in item9.Patch)
					{
						string text4 = ShopIds.Qualify(item10.Slot, mod);
						string text5 = ShopIds.Qualify(item10.Item, mod);
						List<string> list2 = new string[2]
						{
							ShopIds.OwnerOf(text4),
							ShopIds.OwnerOf(text5)
						}.Where((string o) => o != null && o != "vanilla" && o != mod && !requires[mod].Contains(o)).Distinct().ToList();
						if (list2.Count > 0)
						{
							Diag(Severity.Error, item9, $"patch on {text4} / {text5} touches {string.Join(", ", list2)} without listing it in \"requires\"; refused");
							continue;
						}
						Op op = new Op
						{
							Mod = mod,
							Item = text5
						};
						if (item10.Weight.HasValue)
						{
							op.Kind = OpKind.SetWeight;
							op.Weight = item10.Weight.Value;
						}
						else if (item10.Remove)
						{
							op.Kind = OpKind.Remove;
						}
						else
						{
							op.Kind = OpKind.Replace;
							op.ReplaceWith = ShopIds.Qualify(item10.ReplaceWith, mod);
						}
						AddOpTo(text4, op);
					}
				}
			}
			foreach (string item11 in ModOrder)
			{
				foreach (string item12 in requires[item11])
				{
					if (!dictionary.ContainsKey(item12))
					{
						_diagnostics.Add(new Diagnostic(Severity.Info, item11, $"requires '{item12}', which has no shop file loaded; its patches on '{item12}' content will find nothing"));
					}
				}
			}
			CollectItemReferences(dictionary);
			CheckModSlotTargets(dictionary);
		}

		private void CheckModSlotTargets(Dictionary<string, List<ShopFile>> byMod)
		{
			foreach (KeyValuePair<string, List<Op>> item in _ops.OrderBy<KeyValuePair<string, List<Op>>, string>((KeyValuePair<string, List<Op>> k) => k.Key, StringComparer.Ordinal))
			{
				string key = item.Key;
				string owner = ShopIds.OwnerOf(key);
				if (owner == null || owner == "vanilla" || _modSlots.ContainsKey(key) || _sellerSlots.ContainsKey(key) || IsSlotOfKnownSeller(key))
				{
					continue;
				}
				string source = string.Join(", ", item.Value.Select((Op o) => o.Mod).Distinct());
				if (!byMod.ContainsKey(owner))
				{
					_diagnostics.Add(new Diagnostic(Severity.Info, source, $"rules target slot '{key}', but '{owner}' has no shop file loaded; they do nothing until it is installed"));
					continue;
				}
				IEnumerable<string> candidates = _modSlots.Keys.Where((string id) => ShopIds.OwnerOf(id) == owner).Concat(from s in _sellers
					where s.Mod == owner
					select SellerSlotId(s.FullId, 1));
				List<string> list = NearestIds.Of(key, candidates);
				_diagnostics.Add(new Diagnostic(Severity.Warning, source, $"rules target slot '{key}', which '{owner}' does not define; they do nothing." + ((list.Count > 0) ? (" Closest ids: " + string.Join(", ", list)) : (" '" + owner + "' defines no slots."))));
			}
		}

		private bool IsSlotOfKnownSeller(string slot)
		{
			int num = slot.LastIndexOf('#');
			if (num <= 0 || !int.TryParse(slot.Substring(num + 1), out var result) || result < 1)
			{
				return false;
			}
			string seller = slot.Substring(0, num);
			return _sellers.Any((ModSeller s) => s.FullId == seller);
		}

		private void CollectItemReferences(Dictionary<string, List<ShopFile>> byMod)
		{
			foreach (ModSlot value in _modSlots.Values)
			{
				foreach (PoolEntry item in value.Def.Pool ?? new List<PoolEntry>())
				{
					if (item != null)
					{
						Ref(ShopIds.Qualify(item.Item, value.Mod), value.Mod, value.FullId, "pool");
					}
				}
			}
			foreach (KeyValuePair<string, (string, List<PoolEntry>)> sellerSlot in _sellerSlots)
			{
				foreach (PoolEntry item2 in sellerSlot.Value.Item2)
				{
					if (item2 != null)
					{
						Ref(ShopIds.Qualify(item2.Item, sellerSlot.Value.Item1), sellerSlot.Value.Item1, sellerSlot.Key, "merchant stock");
					}
				}
			}
			foreach (KeyValuePair<string, List<Op>> op in _ops)
			{
				foreach (Op item3 in op.Value)
				{
					if (item3.Kind == OpKind.Add)
					{
						Ref(item3.Item, item3.Mod, op.Key, "add");
					}
					else if (item3.Kind == OpKind.Replace)
					{
						Ref(item3.ReplaceWith, item3.Mod, op.Key, "replace");
					}
				}
			}
			void Ref(string item, string mod, string slot, string how)
			{
				if (!string.IsNullOrEmpty(item) && item != "nothing")
				{
					_itemRefs.Add(new ItemReference(item, mod, slot, how));
				}
			}
		}

		public IReadOnlyList<string> ModsTargeting(string slotId)
		{
			if (!_ops.TryGetValue(slotId, out var value))
			{
				return new List<string>();
			}
			return value.Select((Op o) => o.Mod).Distinct().ToList();
		}

		private static HashSet<string> RequiresOf(List<ShopFile> files, Func<string, bool> keep)
		{
			HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
			foreach (ShopFile file in files)
			{
				if (file.Requires == null)
				{
					continue;
				}
				foreach (string require in file.Requires)
				{
					if (!string.IsNullOrEmpty(require) && (keep == null || keep(require)))
					{
						hashSet.Add(require);
					}
				}
			}
			return hashSet;
		}

		private void AddOpTo(string slot, Op op)
		{
			if (!_ops.TryGetValue(slot, out var value))
			{
				value = (_ops[slot] = new List<Op>());
			}
			value.Add(op);
		}

		private void Diag(Severity s, ShopFile f, string m)
		{
			_diagnostics.Add(new Diagnostic(s, f.SourcePath ?? f.Mod, m));
		}

		private List<string> OrderMods(Dictionary<string, List<ShopFile>> byMod)
		{
			Dictionary<string, HashSet<string>> deps = new Dictionary<string, HashSet<string>>(StringComparer.Ordinal);
			foreach (KeyValuePair<string, List<ShopFile>> kv in byMod)
			{
				deps[kv.Key] = RequiresOf(kv.Value, (string r) => byMod.ContainsKey(r) && r != kv.Key);
			}
			List<string> list = new List<string>();
			SortedSet<string> remaining = new SortedSet<string>(byMod.Keys, StringComparer.Ordinal);
			while (remaining.Count > 0)
			{
				string text = remaining.FirstOrDefault((string m) => deps[m].All((string d) => !remaining.Contains(d)));
				if (text == null)
				{
					text = remaining.Min;
					_diagnostics.Add(new Diagnostic(Severity.Warning, text, $"\"requires\" forms a cycle among {string.Join(", ", remaining)}; applying '{text}' first"));
				}
				list.Add(text);
				remaining.Remove(text);
			}
			return list;
		}

		public ResolvedSlot Resolve(string slotId, IEnumerable<VanillaEntry> vanilla)
		{
			List<SlotEntry> list = new List<SlotEntry>();
			List<HistoryRecord> list2 = new List<HistoryRecord>();
			bool flag = false;
			(string, List<PoolEntry>) value2;
			if (_modSlots.TryGetValue(slotId, out var value))
			{
				flag = true;
				foreach (PoolEntry item in value.Def.Pool ?? new List<PoolEntry>())
				{
					if (item != null)
					{
						list.Add(new SlotEntry(ShopIds.Qualify(item.Item, value.Mod), item.Weight, value.Mod));
						list2.Add(new HistoryRecord(value.Mod, $"pool: {ShopIds.Qualify(item.Item, value.Mod)} weight {item.Weight:0.##}"));
					}
				}
			}
			else if (_sellerSlots.TryGetValue(slotId, out value2))
			{
				flag = true;
				foreach (PoolEntry item2 in value2.Item2)
				{
					if (item2 != null)
					{
						list.Add(new SlotEntry(ShopIds.Qualify(item2.Item, value2.Item1), item2.Weight, value2.Item1));
						list2.Add(new HistoryRecord(value2.Item1, $"merchant stock: {ShopIds.Qualify(item2.Item, value2.Item1)} weight {item2.Weight:0.##}"));
					}
				}
			}
			else if (vanilla != null)
			{
				foreach (VanillaEntry item3 in vanilla)
				{
					if (item3.Count > 0 && !string.IsNullOrEmpty(item3.Item))
					{
						list.Add(new SlotEntry(item3.Item, Options.DefaultVanillaWeight * (double)item3.Count, "vanilla"));
					}
				}
			}
			if (_ops.TryGetValue(slotId, out var value3))
			{
				flag = true;
				foreach (Op item4 in value3)
				{
					Apply(item4, list, list2);
				}
			}
			return new ResolvedSlot(slotId, list, list2, !flag);
		}

		private static void Apply(Op op, List<SlotEntry> entries, List<HistoryRecord> history)
		{
			if (op.Kind == OpKind.Add)
			{
				entries.Add(new SlotEntry(op.Item, op.Weight, op.Mod));
				history.Add(new HistoryRecord(op.Mod, $"add {op.Item} weight {op.Weight:0.##}"));
				return;
			}
			List<SlotEntry> list = entries.Where((SlotEntry e) => e.Item == op.Item).ToList();
			if (list.Count == 0)
			{
				history.Add(new HistoryRecord(op.Mod, "patch on " + op.Item + " found no such entry (nothing changed)"));
				return;
			}
			switch (op.Kind)
			{
			case OpKind.SetWeight:
			{
				foreach (SlotEntry item in list)
				{
					history.Add(new HistoryRecord(op.Mod, $"weight of {item.Item} (from {item.AddedBy}) {item.Weight:0.##} -> {op.Weight:0.##}"));
					item.Weight = op.Weight;
				}
				break;
			}
			case OpKind.Remove:
			{
				foreach (SlotEntry item2 in list)
				{
					history.Add(new HistoryRecord(op.Mod, $"removed {item2.Item} (from {item2.AddedBy}, weight {item2.Weight:0.##})"));
					entries.Remove(item2);
				}
				break;
			}
			case OpKind.Replace:
			{
				foreach (SlotEntry item3 in list)
				{
					history.Add(new HistoryRecord(op.Mod, $"replaced {item3.Item} (from {item3.AddedBy}) with {op.ReplaceWith}"));
					item3.Item = op.ReplaceWith;
				}
				break;
			}
			}
		}
	}
	internal sealed class ItemReference
	{
		public string Item { get; }

		public string Mod { get; }

		public string Slot { get; }

		public string How { get; }

		public ItemReference(string item, string mod, string slot, string how)
		{
			Item = item;
			Mod = mod;
			Slot = slot;
			How = how;
		}

		public override string ToString()
		{
			return $"{How} by {Mod} in {Slot}";
		}
	}
	internal sealed class ShopCatalogOptions
	{
		public const double StandardVanillaWeight = 10.0;

		public double DefaultVanillaWeight { get; set; } = 10.0;

		public static bool IsValidVanillaWeight(double w)
		{
			if (w >= 0.0 && !double.IsNaN(w))
			{
				return !double.IsInfinity(w);
			}
			return false;
		}
	}
	public sealed class ShopFile
	{
		public const int CurrentFormat = 1;

		public int Format { get; set; }

		public string Mod { get; set; }

		public List<string> Requires { get; set; } = new List<string>();

		public List<SlotDef> Slots { get; set; } = new List<SlotDef>();

		public List<AddOp> Add { get; set; } = new List<AddOp>();

		public List<PatchOp> Patch { get; set; } = new List<PatchOp>();

		public List<SellerDef> Sellers { get; set; } = new List<SellerDef>();

		public List<ItemDisplayDef> Items { get; set; } = new List<ItemDisplayDef>();

		[JsonIgnore]
		internal string SourcePath { get; set; }
	}
	public sealed class SlotDef
	{
		public string Id { get; set; }

		public string Scene { get; set; }

		public string Seller { get; set; }

		public string Anchor { get; set; }

		public float[] Pos { get; set; }

		public string After { get; set; }

		public float[] Rot { get; set; }

		public TagDef PriceTag { get; set; }

		public string Template { get; set; }

		public string Faction { get; set; }

		public List<PoolEntry> Pool { get; set; } = new List<PoolEntry>();

		internal static bool? SideOf(string after)
		{
			if (!string.Equals(after, "right", StringComparison.OrdinalIgnoreCase))
			{
				if (!string.Equals(after, "left", StringComparison.OrdinalIgnoreCase))
				{
					return null;
				}
				return false;
			}
			return true;
		}
	}
	public sealed class TagDef
	{
		public float[] Pos { get; set; }

		public float[] Rot { get; set; }
	}
	public sealed class PoolEntry
	{
		public string Item { get; set; }

		public double Weight { get; set; } = 1.0;
	}
	public sealed class AddOp
	{
		public string Slot { get; set; }

		public string Item { get; set; }

		public double Weight { get; set; } = 1.0;
	}
	public sealed class PatchOp
	{
		public string Slot { get; set; }

		public string Item { get; set; }

		public double? Weight { get; set; }

		public bool Remove { get; set; }

		public string ReplaceWith { get; set; }
	}
	public sealed class SellerDef
	{
		public string Id { get; set; }

		public string Preset { get; set; }

		public double Weight { get; set; } = 1.0;

		public List<List<PoolEntry>> Slots { get; set; } = new List<List<PoolEntry>>();
	}
	public sealed class ItemDisplayDef
	{
		public string Item { get; set; }

		public TagDef Standing { get; set; }
	}
	internal enum Severity
	{
		Info,
		Warning,
		Error
	}
	internal sealed class Diagnostic
	{
		public Severity Severity { get; }

		public string Source { get; }

		public string Message { get; }

		public Diagnostic(Severity severity, string source, string message)
		{
			Severity = severity;
			Source = source;
			Message = message;
		}

		public override string ToString()
		{
			return $"{Severity} [{Source}] {Message}";
		}
	}
	internal static class ShopFileIO
	{
		private static readonly JsonSerializerOptions ReadOptions = new JsonSerializerOptions
		{
			PropertyNameCaseInsensitive = true,
			ReadCommentHandling = JsonCommentHandling.Skip,
			AllowTrailingCommas = true
		};

		private static readonly JsonSerializerOptions WriteOptions = new JsonSerializerOptions
		{
			WriteIndented = true,
			PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
			DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
		};

		private static readonly Dictionary<string, HashSet<string>> KnownKeys = new Dictionary<string, HashSet<string>>
		{
			["file"] = Keys(typeof(ShopFile)),
			["display"] = Keys(typeof(ItemDisplayDef)),
			["slot"] = Keys(typeof(SlotDef)),
			["tag"] = Keys(typeof(TagDef)),
			["entry"] = Keys(typeof(PoolEntry)),
			["add"] = Keys(typeof(AddOp)),
			["patch"] = Keys(typeof(PatchOp)),
			["seller"] = Keys(typeof(SellerDef))
		};

		private static HashSet<string> Keys(Type model)
		{
			return new HashSet<string>(from p in model.GetProperties(BindingFlags.Instance | BindingFlags.Public)
				where p.GetCustomAttributes(typeof(JsonIgnoreAttribute), inherit: true).Length == 0
				select JsonNamingPolicy.CamelCase.ConvertName(p.Name), StringComparer.OrdinalIgnoreCase);
		}

		public static ShopFile Parse(string json, string sourcePath, List<Diagnostic> diagnostics)
		{
			ShopFile shopFile;
			try
			{
				using (JsonDocument jsonDocument = JsonDocument.Parse(json, new JsonDocumentOptions
				{
					CommentHandling = JsonCommentHandling.Skip,
					AllowTrailingCommas = true
				}))
				{
					CheckKeys(jsonDocument.RootElement, "file", "", sourcePath, diagnostics);
				}
				shopFile = JsonSerializer.Deserialize<ShopFile>(json, ReadOptions);
			}
			catch (JsonException ex)
			{
				diagnostics.Add(new Diagnostic(Severity.Error, sourcePath, "not valid JSON: " + ex.Message));
				return null;
			}
			if (shopFile == null)
			{
				diagnostics.Add(new Diagnostic(Severity.Error, sourcePath, "empty file"));
				return null;
			}
			shopFile.SourcePath = sourcePath;
			ShopFile shopFile2 = shopFile;
			if (shopFile2.Requires == null)
			{
				List<string> list = (shopFile2.Requires = new List<string>());
			}
			shopFile2 = shopFile;
			if (shopFile2.Slots == null)
			{
				List<SlotDef> list3 = (shopFile2.Slots = new List<SlotDef>());
			}
			shopFile2 = shopFile;
			if (shopFile2.Add == null)
			{
				List<AddOp> list5 = (shopFile2.Add = new List<AddOp>());
			}
			shopFile2 = shopFile;
			if (shopFile2.Patch == null)
			{
				List<PatchOp> list7 = (shopFile2.Patch = new List<PatchOp>());
			}
			shopFile2 = shopFile;
			if (shopFile2.Sellers == null)
			{
				List<SellerDef> list9 = (shopFile2.Sellers = new List<SellerDef>());
			}
			shopFile2 = shopFile;
			if (shopFile2.Items == null)
			{
				List<ItemDisplayDef> list11 = (shopFile2.Items = new List<ItemDisplayDef>());
			}
			if (!Validate(shopFile, diagnostics))
			{
				return null;
			}
			return shopFile;
		}

		public static string Write(ShopFile file)
		{
			return JsonSerializer.Serialize(file, WriteOptions);
		}

		private static void CheckKeys(JsonElement e, string kind, string path, string source, List<Diagnostic> diagnostics)
		{
			if (e.ValueKind != JsonValueKind.Object)
			{
				return;
			}
			foreach (JsonProperty item in e.EnumerateObject())
			{
				string text = ((path.Length == 0) ? item.Name : (path + "." + item.Name));
				if (!KnownKeys[kind].Contains(item.Name))
				{
					diagnostics.Add(new Diagnostic(Severity.Warning, source, "unknown key '" + text + "' is ignored (typo?)"));
					continue;
				}
				string text2 = item.Name.ToLowerInvariant();
				string text3;
				switch (kind)
				{
				case "file":
					switch (text2)
					{
					case "slots":
						break;
					case "add":
						goto IL_0141;
					case "patch":
						goto IL_014a;
					case "sellers":
						goto IL_0153;
					case "items":
						goto IL_015c;
					default:
						goto IL_0180;
					}
					text3 = "slot";
					break;
				case "display":
					if (!(text2 == "standing"))
					{
						goto IL_0180;
					}
					text3 = "tag";
					break;
				case "slot":
					if (!(text2 == "pool"))
					{
						if (!(text2 == "pricetag"))
						{
							goto IL_0180;
						}
						text3 = "tag";
						break;
					}
					text3 = "entry";
					break;
				default:
					goto IL_0180;
					IL_015c:
					text3 = "display";
					break;
					IL_014a:
					text3 = "patch";
					break;
					IL_0153:
					text3 = "seller";
					break;
					IL_0141:
					text3 = "add";
					break;
					IL_0180:
					text3 = null;
					break;
				}
				string text4 = text3;
				if (text4 == null)
				{
					continue;
				}
				if (item.Value.ValueKind == JsonValueKind.Array)
				{
					int num = 0;
					foreach (JsonElement item2 in item.Value.EnumerateArray())
					{
						CheckKeys(item2, text4, $"{text}[{num++}]", source, diagnostics);
					}
				}
				else
				{
					CheckKeys(item.Value, text4, text, source, diagnostics);
				}
			}
		}

		internal static bool CheckModScope(ShopFile f, List<Diagnostic> d)
		{
			bool ok = true;
			List<AddOp> add = f.Add;
			if (add != null && add.Count > 0)
			{
				Err($"\"add\" puts items into slots that are not this mod's ({f.Add.Count} rule(s)): {"a mod's shop file may only place its own slots (\"slots\") and say how its items stand (\"items\") in this version; the file is not used"}. Put the items in a slot of your own instead");
			}
			List<PatchOp> patch = f.Patch;
			if (patch != null && patch.Count > 0)
			{
				Err($"\"patch\" changes what others sell ({f.Patch.Count} rule(s)): {"a mod's shop file may only place its own slots (\"slots\") and say how its items stand (\"items\") in this version; the file is not used"}");
			}
			List<string> requires = f.Requires;
			if (requires != null && requires.Count > 0)
			{
				Err("\"requires\" only serves \"patch\": a mod's shop file may only place its own slots (\"slots\") and say how its items stand (\"items\") in this version; the file is not used");
			}
			List<SellerDef> sellers = f.Sellers;
			if (sellers != null && sellers.Count > 0)
			{
				Err($"\"sellers\" (dungeon merchants) changes the game's list of who stands at the entrance ({f.Sellers.Count} merchant(s)): {"a mod's shop file may only place its own slots (\"slots\") and say how its items stand (\"items\") in this version; the file is not used"}");
			}
			return ok;
			void Err(string m)
			{
				d.Add(new Diagnostic(Severity.Error, f.SourcePath, m));
				ok = false;
			}
		}

		public static bool Validate(ShopFile f, List<Diagnostic> d)
		{
			string src = f.SourcePath ?? f.Mod ?? "?";
			bool ok = true;
			if (f.Format == 0)
			{
				Err("missing \"format\" (use 1)");
			}
			else if (f.Format > 1)
			{
				Err($"format {f.Format} is newer than this POGLib reads ({1}); update POGLib");
			}
			else if (f.Format < 1)
			{
				Err($"format {f.Format} is not a valid format");
			}
			if (!ShopIds.IsValidModId(f.Mod))
			{
				Err("\"mod\" must be your mod id (letters, digits, _ . -), got '" + f.Mod + "'");
			}
			if (!ok)
			{
				return false;
			}
			HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
			for (int i = 0; i < f.Slots.Count; i++)
			{
				SlotDef slotDef = f.Slots[i];
				string text = $"slots[{i}]";
				if (slotDef == null)
				{
					Err(text + " is null");
					continue;
				}
				if (string.IsNullOrEmpty(slotDef.Id) || slotDef.Id.IndexOf(':') >= 0)
				{
					Err(text + ".id must be a local id without ':' (got '" + slotDef.Id + "')");
				}
				else if (!hashSet.Add(slotDef.Id))
				{
					Err(text + ".id '" + slotDef.Id + "' is used twice");
				}
				if (string.IsNullOrEmpty(slotDef.Scene))
				{
					Err(text + ".scene is required");
				}
				if (!string.IsNullOrEmpty(slotDef.After))
				{
					if (slotDef.Pos != null)
					{
						Err(text + " has both \"after\" and \"pos\": \"after\" places it, so leave \"pos\" out");
					}
					if (!string.IsNullOrEmpty(slotDef.Anchor))
					{
						Err(text + " has both \"after\" and \"anchor\": \"after\" places it next to that slot, so leave \"anchor\" out");
					}
					if (SlotDef.SideOf(slotDef.After).HasValue && string.IsNullOrEmpty(slotDef.Seller))
					{
						Err(text + ".after \"" + slotD