Decompiled source of Hunting v1.4.5

Hunting.dll

Decompiled 3 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using Hunting.Functions;
using Hunting.Patches;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using ServerSync;
using SkillManager;
using Splatform;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("blacks7ar")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.4.5")]
[assembly: AssemblyInformationalVersion("1.0.0+b9837a44bfab3c9be80e0fe0f3d485463a88c11f")]
[assembly: AssemblyProduct("Hunting")]
[assembly: AssemblyTitle("Hunting")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.4.5.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Hunting
{
	[BepInPlugin("blacks7ar.Hunting", "Hunting", "1.4.5")]
	public class Plugin : BaseUnityPlugin
	{
		public enum DisplayOptions
		{
			Numerical,
			Percentage
		}

		private const string modGUID = "blacks7ar.Hunting";

		public const string modName = "Hunting";

		public const string modAuthor = "blacks7ar";

		public const string modVersion = "1.4.5";

		private static readonly Harmony _harmony = new Harmony("blacks7ar.Hunting");

		private static readonly ConfigSync _configSync = new ConfigSync("blacks7ar.Hunting")
		{
			DisplayName = "Hunting",
			CurrentVersion = "1.4.5",
			MinimumRequiredVersion = "1.4.5"
		};

		private static ConfigEntry<Toggle> _serverConfigLocked;

		private static ConfigEntry<float> _expGainFactor;

		public static ConfigEntry<float> _huntingYieldFactor;

		public static ConfigEntry<string> _tier1Meadows;

		public static ConfigEntry<int> _tier1MeadowsLevel;

		public static ConfigEntry<string> _tier2BlackForest;

		public static ConfigEntry<int> _tier2BlackForestLevel;

		public static ConfigEntry<string> _tier3Swamps;

		public static ConfigEntry<int> _tier3SwampsLevel;

		public static ConfigEntry<string> _tier4Mountains;

		public static ConfigEntry<int> _tier4MountainsLevel;

		public static ConfigEntry<string> _tier5Plains;

		public static ConfigEntry<int> _tier5PlainsLevel;

		public static ConfigEntry<string> _tier6Mistlands;

		public static ConfigEntry<int> _tier6MistlandsLevel;

		public static ConfigEntry<string> _tier7Ashlands;

		public static ConfigEntry<int> _tier7AshlandsLevel;

		public static ConfigEntry<string> _tier8DeepNorth;

		public static ConfigEntry<int> _tier8DeepNorthLevel;

		public static ConfigEntry<float> _detectionRadius;

		public static ConfigEntry<Toggle> _displayExpGained;

		public static ConfigEntry<Toggle> _displayEnemyHPEnable;

		public static ConfigEntry<int> _displayEnemyHPLevel;

		public static ConfigEntry<DisplayOptions> _displayEnemyHPOptions;

		private static ConfigEntry<int> _expLoss;

		public static ConfigEntry<Toggle> _useDropSystem;

		public static ConfigEntry<Toggle> _iconsOnly;

		public static ConfigEntry<int> _maxPin;

		public static ConfigEntry<KeyboardShortcut> _hidePinKey;

		public static bool _hidePins;

		private static Skill _hunting;

		public static HashSet<string> _CreatureList;

		private ConfigEntry<T> config<T>(string group, string name, T value, ConfigDescription description, bool synchronizedConfig = true)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			ConfigDescription val = new ConfigDescription(description.Description + (synchronizedConfig ? " [Synced with Server]" : " [Not Synced with Server]"), description.AcceptableValues, description.Tags);
			ConfigEntry<T> val2 = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, val);
			_configSync.AddConfigEntry<T>(val2).SynchronizedConfig = synchronizedConfig;
			return val2;
		}

		private ConfigEntry<T> config2<T>(string group, string name, T value, string desc, bool synchronizedConfig = true)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			Hunting.Functions.ConfigurationManagerAttributes configurationManagerAttributes = new Hunting.Functions.ConfigurationManagerAttributes
			{
				CustomDrawer = TextBox
			};
			return config(group, name, value, new ConfigDescription(desc, (AcceptableValueBase)null, new object[1] { configurationManagerAttributes }), synchronizedConfig);
		}

		public void Awake()
		{
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Expected O, but got Unknown
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Expected O, but got Unknown
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Expected O, but got Unknown
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Expected O, but got Unknown
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Expected O, but got Unknown
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Expected O, but got Unknown
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Expected O, but got Unknown
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0229: Expected O, but got Unknown
			//IL_02ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b6: Expected O, but got Unknown
			//IL_0338: Unknown result type (might be due to invalid IL or missing references)
			//IL_0343: Expected O, but got Unknown
			//IL_03c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d0: Expected O, but got Unknown
			//IL_0452: Unknown result type (might be due to invalid IL or missing references)
			//IL_045d: Expected O, but got Unknown
			//IL_04df: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ea: Expected O, but got Unknown
			//IL_056c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0577: Expected O, but got Unknown
			//IL_05f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0604: Expected O, but got Unknown
			//IL_0620: Unknown result type (might be due to invalid IL or missing references)
			//IL_062b: Expected O, but got Unknown
			//IL_0647: Unknown result type (might be due to invalid IL or missing references)
			//IL_0652: Expected O, but got Unknown
			//IL_068b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0696: Expected O, but got Unknown
			//IL_06b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_06bd: Expected O, but got Unknown
			//IL_06eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_06f6: Expected O, but got Unknown
			//IL_0756: Unknown result type (might be due to invalid IL or missing references)
			//IL_0761: Expected O, but got Unknown
			((BaseUnityPlugin)this).Config.SaveOnConfigSet = false;
			_hunting = new Skill("Hunting", "deericon2.png");
			_hunting.Description.English("Increase item yield when hunting wild animals and pins them on the minimap for easy hunting.");
			_hunting.Configurable = false;
			_serverConfigLocked = config("1- ServerSync", "Lock Configuration", Toggle.On, new ConfigDescription("If On, the configuration is locked and can be changed by server admins only.", (AcceptableValueBase)null, Array.Empty<object>()));
			_configSync.AddLockingConfigEntry<Toggle>(_serverConfigLocked);
			_huntingYieldFactor = config("2- Hunting", "Hunting Yield Factor", 2f, new ConfigDescription("Hunting yield factor at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 5f), Array.Empty<object>()));
			_detectionRadius = config("2- Hunting", "Detection Radius", 30f, new ConfigDescription("Detection radius for tracking down prey.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 50f), Array.Empty<object>()));
			_useDropSystem = config("2- Hunting", "Use Drop System", Toggle.On, new ConfigDescription("If On, calculating the drops from preys will be handled by this mod.", (AcceptableValueBase)null, Array.Empty<object>()));
			_iconsOnly = config("2- Hunting", "Icons Only", Toggle.Off, new ConfigDescription("If On, only icons will be visible on the world map.", (AcceptableValueBase)null, Array.Empty<object>()));
			_maxPin = config("2- Hunting", "Max Pin", 10, new ConfigDescription("Max number of pins to be displayed on the map.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50), Array.Empty<object>()));
			_hidePinKey = config<KeyboardShortcut>("2- Hunting", "Hide Pin Hotkey", new KeyboardShortcut((KeyCode)102, (KeyCode[])(object)new KeyCode[1] { (KeyCode)308 }), new ConfigDescription("Quick hotkey to hide pins on the map", (AcceptableValueBase)null, Array.Empty<object>()), synchronizedConfig: false);
			_tier1Meadows = config2("3- Hunters Instinct", "Tier1 Meadows", "Deer,Boar,Neck,BOH_Hare_Brown,BOH_Hare_Native,BOH_Hare_DarkGrey,BOH_Hare_Exotic,BOH_Hare_White,Fox_TW", "Prefab names of creatures you want to track in meadows biome.\n(NOTE: You need to logout if you added additional creature while in-game)");
			_tier1Meadows.SettingChanged += delegate
			{
				GenerateCreatureList();
			};
			_tier1MeadowsLevel = config("3- Hunters Instinct", "Tier1 Meadows Level", 10, new ConfigDescription("Required skill level needed to track down prey on meadows biome and pin them on the map.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new Hunting.Functions.ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false
				}
			}));
			_tier2BlackForest = config2("3- Hunters Instinct", "Tier2 BlackForest", "Bjorn,Razorback_TW,BlackBear_TW", "Prefab names of creatures you want to track in blackforest biomes.\n(NOTE: You need to logout if you added additional creature while in-game)");
			_tier2BlackForest.SettingChanged += delegate
			{
				GenerateCreatureList();
			};
			_tier2BlackForestLevel = config("3- Hunters Instinct", "Tier2 BlackForest Level", 20, new ConfigDescription("Required skill level needed to track down prey on blackforest biome and pin them on the map.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new Hunting.Functions.ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false
				}
			}));
			_tier3Swamps = config2("3- Hunters Instinct", "Tier3 Swamp", "RottingElk_TW", "Prefab names of creatures you want to track in swamp biome.\n(NOTE: You need to logout if you added additional creature while in-game)");
			_tier3Swamps.SettingChanged += delegate
			{
				GenerateCreatureList();
			};
			_tier3SwampsLevel = config("3- Hunters Instinct", "Tier3 Swamp Level", 30, new ConfigDescription("Required skill level needed to track down prey on swamp biome and pin them on the map.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new Hunting.Functions.ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false
				}
			}));
			_tier4Mountains = config2("3- Hunters Instinct", "Tier4 Mountain", "Wolf,GrizzlyBear_TW", "Prefab names of creatures you want to track in mountain biome.\n(NOTE: You need to logout if you added additional creature while in-game)");
			_tier4Mountains.SettingChanged += delegate
			{
				GenerateCreatureList();
			};
			_tier4MountainsLevel = config("3- Hunters Instinct", "Tier4 Mountain Level", 40, new ConfigDescription("Required skill level needed to track down prey on mountain biome and pin them on the map.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new Hunting.Functions.ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false
				}
			}));
			_tier5Plains = config2("3- Hunters Instinct", "Tier5 Plains", "Unbjorn,Lox,Prowler_TW", "Prefab names of creatures you want to track in plains biome.\n(NOTE: You need to logout if you added additional creature while in-game)");
			_tier5Plains.SettingChanged += delegate
			{
				GenerateCreatureList();
			};
			_tier5PlainsLevel = config("3- Hunters Instinct", "Tier5 Plains Level", 50, new ConfigDescription("Required skill level needed to track down prey on plains biome and pin them on the map.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new Hunting.Functions.ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false
				}
			}));
			_tier6Mistlands = config2("3- Hunters Instinct", "Tier6 Mistlands", "Hare", "Prefab names of creatures you want to track in mistlands biome.\n(NOTE: You need to logout if you added additional creature while in-game)");
			_tier6Mistlands.SettingChanged += delegate
			{
				GenerateCreatureList();
			};
			_tier6MistlandsLevel = config("3- Hunters Instinct", "Tier6 Mistlands Level", 60, new ConfigDescription("Required skill level needed to track down prey on mistlands biome and pin them on the map.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new Hunting.Functions.ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false
				}
			}));
			_tier7Ashlands = config2("3- Hunters Instinct", "Tier7 Ashlands", "AshenScorpid_TW,AshenDimetrodon_TW,AshenDrake_TW,AshenCrab_TW", "Prefab names of creatures you want to track in ashlands biome.\n(NOTE: You need to logout if you added additional creature while in-game)");
			_tier7Ashlands.SettingChanged += delegate
			{
				GenerateCreatureList();
			};
			_tier7AshlandsLevel = config("3- Hunters Instinct", "Tier7 Ashlands Level", 70, new ConfigDescription("Required skill level needed to track down prey on ashlands biome and pin them on the map.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new Hunting.Functions.ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false
				}
			}));
			_tier8DeepNorth = config2("3- Hunters Instinct", "Tier8 DeepNorth", "ArcticBear_TW,ArcticWolf_TW,ArcticDrake_TW,ArcticSerpent_TW", "Prefab names of creatures you want to track in deepnorth biome.\n(NOTE: You need to logout if you added additional creature while in-game)");
			_tier8DeepNorth.SettingChanged += delegate
			{
				GenerateCreatureList();
			};
			_tier8DeepNorthLevel = config("3- Hunters Instinct", "Tier8 DeepNorth Level", 80, new ConfigDescription("Required skill level needed to track down prey on deepnorth biome and pin them on the map.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new Hunting.Functions.ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false
				}
			}));
			_displayEnemyHPEnable = config("4- Hunters Vision", "Enable", Toggle.On, new ConfigDescription("If On, creatures health will be displayed in numerical or percentage value.", (AcceptableValueBase)null, Array.Empty<object>()));
			_displayEnemyHPOptions = config("4- Hunters Vision", "Display Creatures Health In", DisplayOptions.Percentage, new ConfigDescription("Displays creatures health in either numerical or percentage value.", (AcceptableValueBase)null, Array.Empty<object>()));
			_displayEnemyHPLevel = config("4- Hunters Vision", "Hunters Vision Level", 15, new ConfigDescription("Required skill level needed to display creatures health.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new Hunting.Functions.ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false
				}
			}));
			_displayExpGained = config("5- Skills Exp", "Display Exp Gain", Toggle.On, new ConfigDescription("Enable/Disable exp gain notification.", (AcceptableValueBase)null, Array.Empty<object>()));
			_expGainFactor = config("5- Skills Exp", "Exp Gain Factor", 1f, new ConfigDescription("Exp gain factor for Hunting skill.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), Array.Empty<object>()));
			_expGainFactor.SettingChanged += delegate
			{
				_hunting.SkillGainFactor = _expGainFactor.Value;
			};
			_hunting.SkillGainFactor = _expGainFactor.Value;
			_expLoss = config("5- Skills Exp", "Exp Loss Amount", 0, new ConfigDescription("Skills exp loss on death.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			_expLoss.SettingChanged += delegate
			{
				_hunting.SkillLoss = _expLoss.Value;
			};
			_hunting.SkillLoss = _expLoss.Value;
			((BaseUnityPlugin)this).Config.SaveOnConfigSet = true;
			((BaseUnityPlugin)this).Config.Save();
			GenerateCreatureList();
			_hidePins = false;
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			_harmony.PatchAll(executingAssembly);
		}

		public void Update()
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if (!Object.op_Implicit((Object)(object)localPlayer))
			{
				return;
			}
			KeyboardShortcut value = _hidePinKey.Value;
			if (((KeyboardShortcut)(ref value)).IsDown() && ((Character)localPlayer).TakeInput() && !_hidePins)
			{
				_hidePins = true;
				((Character)localPlayer).Message((MessageType)2, "Hunting tracker is turned Off.", 0, (Sprite)null, false);
				return;
			}
			value = _hidePinKey.Value;
			if (((KeyboardShortcut)(ref value)).IsDown() && ((Character)localPlayer).TakeInput() && _hidePins)
			{
				((Character)localPlayer).Message((MessageType)2, "Hunting tracker is turned On.", 0, (Sprite)null, false);
				_hidePins = false;
			}
		}

		private void OnDestroy()
		{
			((BaseUnityPlugin)this).Config.Save();
		}

		private static void GenerateCreatureList()
		{
			HashSet<string> other = new HashSet<string>(_tier1Meadows.Value.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries));
			HashSet<string> other2 = new HashSet<string>(_tier2BlackForest.Value.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries));
			HashSet<string> other3 = new HashSet<string>(_tier3Swamps.Value.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries));
			HashSet<string> other4 = new HashSet<string>(_tier4Mountains.Value.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries));
			HashSet<string> other5 = new HashSet<string>(_tier5Plains.Value.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries));
			HashSet<string> other6 = new HashSet<string>(_tier6Mistlands.Value.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries));
			HashSet<string> other7 = new HashSet<string>(_tier7Ashlands.Value.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries));
			HashSet<string> other8 = new HashSet<string>(_tier8DeepNorth.Value.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries));
			HashSet<string> hashSet = new HashSet<string>();
			hashSet.UnionWith(other);
			hashSet.UnionWith(other2);
			hashSet.UnionWith(other3);
			hashSet.UnionWith(other4);
			hashSet.UnionWith(other5);
			hashSet.UnionWith(other6);
			hashSet.UnionWith(other7);
			hashSet.UnionWith(other8);
			_CreatureList = hashSet;
		}

		private static void TextBox(ConfigEntryBase entryBase)
		{
			entryBase.BoxedValue = GUILayout.TextArea((string)entryBase.BoxedValue, (GUILayoutOption[])(object)new GUILayoutOption[2]
			{
				GUILayout.ExpandWidth(true),
				GUILayout.ExpandHeight(true)
			});
		}
	}
}
namespace Hunting.Patches
{
	[HarmonyPatch(typeof(CharacterDrop), "GenerateDropList")]
	public class CharacterDropPatch
	{
		[HarmonyPriority(0)]
		[UsedImplicitly]
		private static void Postfix(CharacterDrop __instance, ref List<KeyValuePair<GameObject, int>> __result)
		{
			if (!CharacterPatch._isHunting || (Object)(object)__instance.m_character == (Object)null || (Object)(object)Player.m_localPlayer == (Object)null || !CharacterPatch.IsPrey(__instance.m_character) || __instance.m_character.IsTamed() || Plugin._useDropSystem.Value == Toggle.Off)
			{
				return;
			}
			List<KeyValuePair<GameObject, int>> list = new List<KeyValuePair<GameObject, int>>();
			foreach (KeyValuePair<GameObject, int> item in __result)
			{
				if (item.Value < 0)
				{
					return;
				}
				int num = new Random().Next(1, 100);
				((Character)Player.m_localPlayer).GetSkills().m_skillData.TryGetValue((SkillType)Mathf.Abs(StringExtensionMethods.GetStableHashCode("Hunting")), out var value);
				GameObject key = item.Key;
				int num2 = item.Value;
				if ((float)num <= value?.m_level)
				{
					float num3 = 1f + Plugin._huntingYieldFactor.Value * ((Character)(object)Player.m_localPlayer).GetSkillFactor("Hunting");
					num2 *= (int)num3;
				}
				list.Add(new KeyValuePair<GameObject, int>(key, num2));
			}
			__result = list;
		}
	}
	[HarmonyPatch]
	public class CharacterPatch
	{
		public static bool _isHunting;

		[HarmonyPrefix]
		[HarmonyPatch(typeof(Character), "RPC_Damage")]
		private static void RpcDamage_Prefix(Character __instance, HitData hit)
		{
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			Character attacker = hit.GetAttacker();
			Player val = (Player)(object)((attacker is Player) ? attacker : null);
			if (val != null && ((Humanoid)val).GetCurrentWeapon() != null && ((Humanoid)val).GetCurrentWeapon() != ((Humanoid)val).m_unarmedWeapon.m_itemData && IsUsingHuntingWeapon(val) && IsPrey(__instance) && !__instance.IsTamed())
			{
				_isHunting = true;
				((Character)val).GetSkills().m_skillData.TryGetValue((SkillType)Mathf.Abs(StringExtensionMethods.GetStableHashCode("Hunting")), out var value);
				string value2 = ((Object)((Component)__instance).gameObject).name.Replace("(Clone)", "");
				string[] source = Plugin._tier1Meadows.Value.Split(',', ' ');
				if (value != null && value.m_level > 10f)
				{
					((Character)val).RaiseSkill(Skill.fromName("Hunting"), source.Contains(value2) ? 0.8f : 1f);
				}
				else if (value != null && value.m_level > 20f)
				{
					((Character)val).RaiseSkill(Skill.fromName("Hunting"), source.Contains(value2) ? 0.5f : 1f);
				}
				else if (value != null && value.m_level > 30f)
				{
					((Character)val).RaiseSkill(Skill.fromName("Hunting"), source.Contains(value2) ? 0.2f : 1f);
				}
				else
				{
					((Character)val).RaiseSkill(Skill.fromName("Hunting"), 1f);
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Character), "Awake")]
		private static void Awake_Postfix(Character __instance)
		{
			if (!((Object)(object)__instance == (Object)null) && !__instance.IsTamed() && !((Object)(object)((Component)__instance).GetComponent<Tracker>() != (Object)null))
			{
				string name = ((Object)((Component)__instance).gameObject).name;
				string localName = ((Localization.instance != null) ? Localization.instance.Localize(__instance.m_name) : __instance.m_name);
				AddTierTracker(((Component)__instance).gameObject, name, localName);
			}
		}

		private static void AddTierTracker(GameObject go, string name, string localName)
		{
			AddTracker(go, name, localName, Helper._Tier1Icons, Helper.GetTier1PinIcons, Plugin._tier1MeadowsLevel.Value);
			AddTracker(go, name, localName, Helper._Tier2Icons, Helper.GetTier2PinIcons, Plugin._tier2BlackForestLevel.Value);
			AddTracker(go, name, localName, Helper._Tier3Icons, Helper.GetTier3PinIcons, Plugin._tier3SwampsLevel.Value);
			AddTracker(go, name, localName, Helper._Tier4Icons, Helper.GetTier4PinIcons, Plugin._tier4MountainsLevel.Value);
			AddTracker(go, name, localName, Helper._Tier5Icons, Helper.GetTier5PinIcons, Plugin._tier5PlainsLevel.Value);
			AddTracker(go, name, localName, Helper._Tier6Icons, Helper.GetTier6PinIcons, Plugin._tier6MistlandsLevel.Value);
			AddTracker(go, name, localName, Helper._Tier7Icons, Helper.GetTier7PinIcons, Plugin._tier7AshlandsLevel.Value);
			AddTracker(go, name, localName, Helper._Tier8Icons, Helper.GetTier8PinIcons, Plugin._tier8DeepNorthLevel.Value);
		}

		private static void AddTracker(GameObject go, string name, string localName, IDictionary<string, Sprite> iconDict, Action<string> fetchIcons, int level)
		{
			fetchIcons(name);
			if (iconDict.TryGetValue(name, out Sprite value) && !((Object)(object)go.GetComponents<Tracker>().FirstOrDefault((Tracker t) => ((Object)t).name == localName) != (Object)null))
			{
				go.AddComponent<Tracker>().Create(localName, Plugin._detectionRadius.Value, value, level);
			}
		}

		public static bool IsPrey(Character character)
		{
			string[] source = Plugin._CreatureList.ToArray();
			string text = ((Object)character).name.Replace("(Clone)", "");
			return source.Any((string name) => text == name);
		}

		private static bool IsUsingHuntingWeapon(Player player)
		{
			//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_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Invalid comparison between Unknown and I4
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Invalid comparison between Unknown and I4
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Invalid comparison between Unknown and I4
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Invalid comparison between Unknown and I4
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Invalid comparison between Unknown and I4
			SkillType skillType = ((Humanoid)player).GetCurrentWeapon().m_shared.m_skillType;
			if ((int)skillType <= 5)
			{
				if ((int)skillType == 2 || (int)skillType == 5)
				{
					goto IL_0028;
				}
			}
			else if ((int)skillType == 8 || (int)skillType == 14)
			{
				goto IL_0028;
			}
			return false;
			IL_0028:
			return true;
		}
	}
	[HarmonyPatch]
	public class EnemyHudPatch
	{
		private static readonly ConditionalWeakTable<HudData, TMP_Text> HpText = new ConditionalWeakTable<HudData, TMP_Text>();

		[HarmonyPrefix]
		[HarmonyPatch(typeof(EnemyHud), "ShowHud")]
		private static void ShowHud_Prefix(ref EnemyHud __instance, ref Character c, ref bool __state)
		{
			__state = __instance.m_huds.ContainsKey(c);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(EnemyHud), "ShowHud")]
		private static void ShowHud_Postfix(ref EnemyHud __instance, ref Character c, ref bool __state)
		{
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			if (!__state && __instance.m_huds.TryGetValue(c, out var value) && !c.IsPlayer() && !((Object)(object)c == (Object)null) && !((Object)(object)Player.m_localPlayer == (Object)null) && !((Object)(object)c == (Object)(object)Player.m_localPlayer) && Plugin._displayEnemyHPEnable.Value != Toggle.Off && Plugin._displayEnemyHPLevel.Value > 0 && ((Character)(object)Player.m_localPlayer).GetSkillFactor("Hunting") >= (float)Plugin._displayEnemyHPLevel.Value / 100f)
			{
				TMP_Text val = (TMP_Text)(object)Object.Instantiate<TextMeshProUGUI>(value.m_name, ((TMP_Text)value.m_name).transform.parent);
				((Object)val).name = "enemyHPText";
				switch (Plugin._displayEnemyHPOptions.Value)
				{
				case Plugin.DisplayOptions.Numerical:
				{
					float health = value.m_character.GetHealth();
					float maxHealth = value.m_character.GetMaxHealth();
					val.text = $"{health:0}/{maxHealth:0}";
					break;
				}
				case Plugin.DisplayOptions.Percentage:
				{
					float healthPercentage = value.m_character.GetHealthPercentage();
					val.text = $"{Mathf.FloorToInt(healthPercentage * 100f)}%";
					break;
				}
				}
				((Graphic)val).color = Color.white;
				if (c.IsBoss())
				{
					val.rectTransform.anchoredPosition = new Vector2(val.rectTransform.anchoredPosition.x, -7f);
					val.fontSizeMax = 17f;
					val.fontSizeMin = 10f;
				}
				else
				{
					val.rectTransform.anchoredPosition = new Vector2(val.rectTransform.anchoredPosition.x, 6f);
					val.fontSizeMax = 13f;
					val.fontSizeMin = 7f;
				}
				HpText.Add(value, val);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(EnemyHud), "UpdateHuds")]
		private static void UpdateHuds_Postfix(ref EnemyHud __instance)
		{
			Character val = null;
			foreach (HudData item in __instance.m_huds.Select((KeyValuePair<Character, HudData> hud) => hud.Value))
			{
				if (!Object.op_Implicit((Object)(object)item.m_character) || !__instance.TestShow(item.m_character, true))
				{
					if ((Object)(object)val == (Object)null)
					{
						val = item.m_character;
						Object.Destroy((Object)(object)item.m_gui);
					}
					continue;
				}
				if (item.m_character.IsPlayer())
				{
					return;
				}
				if (!HpText.TryGetValue(item, out TMP_Text value))
				{
					continue;
				}
				if ((Object)(object)item.m_character == (Object)null || (Object)(object)Player.m_localPlayer == (Object)null || (Object)(object)item.m_character == (Object)(object)Player.m_localPlayer)
				{
					return;
				}
				if (Plugin._displayEnemyHPEnable.Value == Toggle.On && Plugin._displayEnemyHPLevel.Value > 0 && ((Character)(object)Player.m_localPlayer).GetSkillFactor("Hunting") >= (float)Plugin._displayEnemyHPLevel.Value / 100f)
				{
					switch (Plugin._displayEnemyHPOptions.Value)
					{
					case Plugin.DisplayOptions.Numerical:
					{
						float health = item.m_character.GetHealth();
						float maxHealth = item.m_character.GetMaxHealth();
						value.text = $"{health:0}/{maxHealth:0}";
						break;
					}
					case Plugin.DisplayOptions.Percentage:
					{
						float healthPercentage = item.m_character.GetHealthPercentage();
						value.text = $"{Mathf.FloorToInt(healthPercentage * 100f)}%";
						break;
					}
					}
				}
				else if (Plugin._displayEnemyHPEnable.Value == Toggle.Off || Plugin._displayEnemyHPLevel.Value <= 0 || !(((Character)(object)Player.m_localPlayer).GetSkillFactor("Hunting") >= (float)Plugin._displayEnemyHPLevel.Value / 100f))
				{
					value.text = "";
				}
			}
			if ((Object)(object)val != (Object)null)
			{
				__instance.m_huds.Remove(val);
			}
		}
	}
	[HarmonyPatch(typeof(ObjectDB), "UpdateRegisters")]
	public class ObjectDBPatch
	{
		public static readonly IDictionary<string, Sprite> _SpritesDictTier1 = new Dictionary<string, Sprite>();

		public static readonly IDictionary<string, Sprite> _SpritesDictTier2 = new Dictionary<string, Sprite>();

		public static readonly IDictionary<string, Sprite> _SpritesDictTier3 = new Dictionary<string, Sprite>();

		public static readonly IDictionary<string, Sprite> _SpritesDictTier4 = new Dictionary<string, Sprite>();

		public static readonly IDictionary<string, Sprite> _SpritesDictTier5 = new Dictionary<string, Sprite>();

		public static readonly IDictionary<string, Sprite> _SpritesDictTier6 = new Dictionary<string, Sprite>();

		public static readonly IDictionary<string, Sprite> _SpritesDictTier7 = new Dictionary<string, Sprite>();

		public static readonly IDictionary<string, Sprite> _SpritesDictTier8 = new Dictionary<string, Sprite>();

		[HarmonyPostfix]
		private static void Postfix(ObjectDB __instance)
		{
			GetTier1Sprites(__instance);
			GetTier2Sprites(__instance);
			GetTier3Sprites(__instance);
			GetTier4Sprites(__instance);
			GetTier5Sprites(__instance);
			GetTier6Sprites(__instance);
			GetTier7Sprites(__instance);
			GetTier8Sprites(__instance);
		}

		private static void GetTier1Sprites(ObjectDB objectDB)
		{
			_SpritesDictTier1.Clear();
			HashSet<string> hashSet = new HashSet<string>(Plugin._tier1Meadows.Value.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries));
			ZNetScene instance = ZNetScene.instance;
			if (!Object.op_Implicit((Object)(object)instance) || instance.m_prefabs.Count <= 0)
			{
				return;
			}
			foreach (string item in hashSet)
			{
				string text = item;
				GameObject prefab = instance.GetPrefab(StringExtensionMethods.GetStableHashCode(item));
				if ((Object)(object)prefab == (Object)null)
				{
					continue;
				}
				CharacterDrop component = prefab.GetComponent<CharacterDrop>();
				if ((Object)(object)component != (Object)null)
				{
					foreach (Drop drop in component.m_drops)
					{
						text = (((Object)drop.m_prefab).name.ToLower().Contains("trophy") ? ((Object)drop.m_prefab).name : ((Object)component.m_drops[0].m_prefab).name);
					}
				}
				GameObject itemPrefab = objectDB.GetItemPrefab(StringExtensionMethods.GetStableHashCode(text));
				if ((Object)(object)itemPrefab == (Object)null)
				{
					continue;
				}
				ItemDrop component2 = itemPrefab.GetComponent<ItemDrop>();
				if ((Object)(object)component2 != (Object)null)
				{
					_SpritesDictTier1.Add(item, component2.m_itemData.GetIcon());
					continue;
				}
				Sprite value = ((IEnumerable<Sprite>)Resources.FindObjectsOfTypeAll<Sprite>()).SingleOrDefault((Func<Sprite, bool>)((Sprite x) => ((Object)x).name == "mapicon_pin"));
				_SpritesDictTier1.Add(item, value);
			}
		}

		private static void GetTier2Sprites(ObjectDB objectDB)
		{
			_SpritesDictTier2.Clear();
			HashSet<string> hashSet = new HashSet<string>(Plugin._tier2BlackForest.Value.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries));
			ZNetScene instance = ZNetScene.instance;
			if (!Object.op_Implicit((Object)(object)instance) || instance.m_prefabs.Count <= 0)
			{
				return;
			}
			foreach (string item in hashSet)
			{
				string text = item;
				GameObject prefab = instance.GetPrefab(StringExtensionMethods.GetStableHashCode(item));
				if ((Object)(object)prefab == (Object)null)
				{
					continue;
				}
				CharacterDrop component = prefab.GetComponent<CharacterDrop>();
				if ((Object)(object)component != (Object)null)
				{
					foreach (Drop drop in component.m_drops)
					{
						text = (((Object)drop.m_prefab).name.ToLower().Contains("trophy") ? ((Object)drop.m_prefab).name : ((Object)component.m_drops[0].m_prefab).name);
					}
				}
				GameObject itemPrefab = objectDB.GetItemPrefab(StringExtensionMethods.GetStableHashCode(text));
				if ((Object)(object)itemPrefab == (Object)null)
				{
					continue;
				}
				ItemDrop component2 = itemPrefab.GetComponent<ItemDrop>();
				if ((Object)(object)component2 != (Object)null)
				{
					_SpritesDictTier2.Add(item, component2.m_itemData.GetIcon());
					continue;
				}
				Sprite value = ((IEnumerable<Sprite>)Resources.FindObjectsOfTypeAll<Sprite>()).SingleOrDefault((Func<Sprite, bool>)((Sprite x) => ((Object)x).name == "mapicon_pin"));
				_SpritesDictTier2.Add(item, value);
			}
		}

		private static void GetTier3Sprites(ObjectDB objectDB)
		{
			_SpritesDictTier3.Clear();
			HashSet<string> hashSet = new HashSet<string>(Plugin._tier3Swamps.Value.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries));
			ZNetScene instance = ZNetScene.instance;
			if (!Object.op_Implicit((Object)(object)instance) || instance.m_prefabs.Count <= 0)
			{
				return;
			}
			foreach (string item in hashSet)
			{
				string text = item;
				GameObject prefab = instance.GetPrefab(StringExtensionMethods.GetStableHashCode(item));
				if ((Object)(object)prefab == (Object)null)
				{
					continue;
				}
				CharacterDrop component = prefab.GetComponent<CharacterDrop>();
				if ((Object)(object)component != (Object)null)
				{
					foreach (Drop drop in component.m_drops)
					{
						text = (((Object)drop.m_prefab).name.ToLower().Contains("trophy") ? ((Object)drop.m_prefab).name : ((Object)component.m_drops[0].m_prefab).name);
					}
				}
				GameObject itemPrefab = objectDB.GetItemPrefab(StringExtensionMethods.GetStableHashCode(text));
				if ((Object)(object)itemPrefab == (Object)null)
				{
					continue;
				}
				ItemDrop component2 = itemPrefab.GetComponent<ItemDrop>();
				if ((Object)(object)component2 != (Object)null)
				{
					_SpritesDictTier3.Add(item, component2.m_itemData.GetIcon());
					continue;
				}
				Sprite value = ((IEnumerable<Sprite>)Resources.FindObjectsOfTypeAll<Sprite>()).SingleOrDefault((Func<Sprite, bool>)((Sprite x) => ((Object)x).name == "mapicon_pin"));
				_SpritesDictTier3.Add(item, value);
			}
		}

		private static void GetTier4Sprites(ObjectDB objectDB)
		{
			_SpritesDictTier4.Clear();
			HashSet<string> hashSet = new HashSet<string>(Plugin._tier4Mountains.Value.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries));
			ZNetScene instance = ZNetScene.instance;
			if (!Object.op_Implicit((Object)(object)instance) || instance.m_prefabs.Count <= 0)
			{
				return;
			}
			foreach (string item in hashSet)
			{
				string text = item;
				GameObject prefab = instance.GetPrefab(StringExtensionMethods.GetStableHashCode(item));
				if ((Object)(object)prefab == (Object)null)
				{
					continue;
				}
				CharacterDrop component = prefab.GetComponent<CharacterDrop>();
				if ((Object)(object)component != (Object)null)
				{
					foreach (Drop drop in component.m_drops)
					{
						text = (((Object)drop.m_prefab).name.ToLower().Contains("trophy") ? ((Object)drop.m_prefab).name : ((Object)component.m_drops[0].m_prefab).name);
					}
				}
				GameObject itemPrefab = objectDB.GetItemPrefab(StringExtensionMethods.GetStableHashCode(text));
				if ((Object)(object)itemPrefab == (Object)null)
				{
					continue;
				}
				ItemDrop component2 = itemPrefab.GetComponent<ItemDrop>();
				if ((Object)(object)component2 != (Object)null)
				{
					_SpritesDictTier4.Add(item, component2.m_itemData.GetIcon());
					continue;
				}
				Sprite value = ((IEnumerable<Sprite>)Resources.FindObjectsOfTypeAll<Sprite>()).SingleOrDefault((Func<Sprite, bool>)((Sprite x) => ((Object)x).name == "mapicon_pin"));
				_SpritesDictTier4.Add(item, value);
			}
		}

		private static void GetTier5Sprites(ObjectDB objectDB)
		{
			_SpritesDictTier5.Clear();
			HashSet<string> hashSet = new HashSet<string>(Plugin._tier5Plains.Value.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries));
			ZNetScene instance = ZNetScene.instance;
			if (!Object.op_Implicit((Object)(object)instance) || instance.m_prefabs.Count <= 0)
			{
				return;
			}
			foreach (string item in hashSet)
			{
				string text = item;
				GameObject prefab = instance.GetPrefab(StringExtensionMethods.GetStableHashCode(item));
				if ((Object)(object)prefab == (Object)null)
				{
					continue;
				}
				CharacterDrop component = prefab.GetComponent<CharacterDrop>();
				if ((Object)(object)component != (Object)null)
				{
					foreach (Drop drop in component.m_drops)
					{
						text = (((Object)drop.m_prefab).name.ToLower().Contains("trophy") ? ((Object)drop.m_prefab).name : ((Object)component.m_drops[0].m_prefab).name);
					}
				}
				GameObject itemPrefab = objectDB.GetItemPrefab(StringExtensionMethods.GetStableHashCode(text));
				if ((Object)(object)itemPrefab == (Object)null)
				{
					continue;
				}
				ItemDrop component2 = itemPrefab.GetComponent<ItemDrop>();
				if ((Object)(object)component2 != (Object)null)
				{
					_SpritesDictTier5.Add(item, component2.m_itemData.GetIcon());
					continue;
				}
				Sprite value = ((IEnumerable<Sprite>)Resources.FindObjectsOfTypeAll<Sprite>()).SingleOrDefault((Func<Sprite, bool>)((Sprite x) => ((Object)x).name == "mapicon_pin"));
				_SpritesDictTier5.Add(item, value);
			}
		}

		private static void GetTier6Sprites(ObjectDB objectDB)
		{
			_SpritesDictTier6.Clear();
			HashSet<string> hashSet = new HashSet<string>(Plugin._tier6Mistlands.Value.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries));
			ZNetScene instance = ZNetScene.instance;
			if (!Object.op_Implicit((Object)(object)instance) || instance.m_prefabs.Count <= 0)
			{
				return;
			}
			foreach (string item in hashSet)
			{
				string text = item;
				GameObject prefab = instance.GetPrefab(StringExtensionMethods.GetStableHashCode(item));
				if ((Object)(object)prefab == (Object)null)
				{
					continue;
				}
				CharacterDrop component = prefab.GetComponent<CharacterDrop>();
				if ((Object)(object)component != (Object)null)
				{
					foreach (Drop drop in component.m_drops)
					{
						text = (((Object)drop.m_prefab).name.ToLower().Contains("trophy") ? ((Object)drop.m_prefab).name : ((Object)component.m_drops[0].m_prefab).name);
					}
				}
				GameObject itemPrefab = objectDB.GetItemPrefab(StringExtensionMethods.GetStableHashCode(text));
				if ((Object)(object)itemPrefab == (Object)null)
				{
					continue;
				}
				ItemDrop component2 = itemPrefab.GetComponent<ItemDrop>();
				if ((Object)(object)component2 != (Object)null)
				{
					_SpritesDictTier6.Add(item, component2.m_itemData.GetIcon());
					continue;
				}
				Sprite value = ((IEnumerable<Sprite>)Resources.FindObjectsOfTypeAll<Sprite>()).SingleOrDefault((Func<Sprite, bool>)((Sprite x) => ((Object)x).name == "mapicon_pin"));
				_SpritesDictTier6.Add(item, value);
			}
		}

		private static void GetTier7Sprites(ObjectDB objectDB)
		{
			_SpritesDictTier7.Clear();
			HashSet<string> hashSet = new HashSet<string>(Plugin._tier7Ashlands.Value.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries));
			ZNetScene instance = ZNetScene.instance;
			if (!Object.op_Implicit((Object)(object)instance) || instance.m_prefabs.Count <= 0)
			{
				return;
			}
			foreach (string item in hashSet)
			{
				string text = item;
				GameObject prefab = instance.GetPrefab(StringExtensionMethods.GetStableHashCode(item));
				if ((Object)(object)prefab == (Object)null)
				{
					continue;
				}
				CharacterDrop component = prefab.GetComponent<CharacterDrop>();
				if ((Object)(object)component != (Object)null)
				{
					foreach (Drop drop in component.m_drops)
					{
						text = (((Object)drop.m_prefab).name.ToLower().Contains("trophy") ? ((Object)drop.m_prefab).name : ((Object)component.m_drops[0].m_prefab).name);
					}
				}
				GameObject itemPrefab = objectDB.GetItemPrefab(StringExtensionMethods.GetStableHashCode(text));
				if ((Object)(object)itemPrefab == (Object)null)
				{
					continue;
				}
				ItemDrop component2 = itemPrefab.GetComponent<ItemDrop>();
				if ((Object)(object)component2 != (Object)null)
				{
					_SpritesDictTier7.Add(item, component2.m_itemData.GetIcon());
					continue;
				}
				Sprite value = ((IEnumerable<Sprite>)Resources.FindObjectsOfTypeAll<Sprite>()).SingleOrDefault((Func<Sprite, bool>)((Sprite x) => ((Object)x).name == "mapicon_pin"));
				_SpritesDictTier7.Add(item, value);
			}
		}

		private static void GetTier8Sprites(ObjectDB objectDB)
		{
			_SpritesDictTier8.Clear();
			HashSet<string> hashSet = new HashSet<string>(Plugin._tier8DeepNorth.Value.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries));
			ZNetScene instance = ZNetScene.instance;
			if (!Object.op_Implicit((Object)(object)instance) || instance.m_prefabs.Count <= 0)
			{
				return;
			}
			foreach (string item in hashSet)
			{
				string text = item;
				GameObject prefab = instance.GetPrefab(StringExtensionMethods.GetStableHashCode(item));
				if ((Object)(object)prefab == (Object)null)
				{
					continue;
				}
				CharacterDrop component = prefab.GetComponent<CharacterDrop>();
				if ((Object)(object)component != (Object)null)
				{
					foreach (Drop drop in component.m_drops)
					{
						text = (((Object)drop.m_prefab).name.ToLower().Contains("trophy") ? ((Object)drop.m_prefab).name : ((Object)component.m_drops[0].m_prefab).name);
					}
				}
				GameObject itemPrefab = objectDB.GetItemPrefab(StringExtensionMethods.GetStableHashCode(text));
				if ((Object)(object)itemPrefab == (Object)null)
				{
					continue;
				}
				ItemDrop component2 = itemPrefab.GetComponent<ItemDrop>();
				if ((Object)(object)component2 != (Object)null)
				{
					_SpritesDictTier8.Add(item, component2.m_itemData.GetIcon());
					continue;
				}
				Sprite value = ((IEnumerable<Sprite>)Resources.FindObjectsOfTypeAll<Sprite>()).SingleOrDefault((Func<Sprite, bool>)((Sprite x) => ((Object)x).name == "mapicon_pin"));
				_SpritesDictTier8.Add(item, value);
			}
		}
	}
	[HarmonyPatch]
	public class PlayerPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(Player), "Awake")]
		private static void Awake_Postfix(Player __instance)
		{
			((Character)__instance).m_nview.Register<int>("Hunting IncreaseSkill", (Action<long, int>)delegate(long _, int factor)
			{
				((Character)(object)__instance).RaiseSkill("Hunting", factor);
			});
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Player), "Update")]
		private static void Update_Postfix(ref Player __instance)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)__instance != (Object)(object)Player.m_localPlayer))
			{
				((Character)__instance).m_nview.GetZDO().Set("Hunting Skill Factor", ((Character)__instance).GetSkillFactor(Skill.fromName("Hunting")));
			}
		}
	}
	[HarmonyPatch(typeof(Projectile), "OnHit")]
	public class ProjectilePatch
	{
		private static void Prefix(Projectile __instance, Collider collider, Vector3 hitPoint, bool water)
		{
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Invalid comparison between Unknown and I4
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Invalid comparison between Unknown and I4
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Invalid comparison between Unknown and I4
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			Character owner = __instance.m_owner;
			Player val = (Player)(object)((owner is Player) ? owner : null);
			if (val == null)
			{
				return;
			}
			GameObject val2 = (Object.op_Implicit((Object)(object)collider) ? Projectile.FindHitObject(collider) : null);
			bool flag = false;
			bool flag2 = false;
			IDestructible val3 = (Object.op_Implicit((Object)(object)val2) ? val2.GetComponent<IDestructible>() : null);
			if (val3 != null)
			{
				flag2 = val3 is Character;
				if (!__instance.IsValidTarget(val3))
				{
					return;
				}
				flag = true;
			}
			Character val4 = (Character)(object)((val3 is Character) ? val3 : null);
			if (!flag || (Object)(object)__instance.m_owner == (Object)null || !flag2 || !Object.op_Implicit((Object)(object)val4) || !CharacterPatch.IsPrey(val4) || val4.IsTamed() || ((int)__instance.m_skill != 5 && (int)__instance.m_skill != 2 && (int)__instance.m_skill != 7))
			{
				return;
			}
			((Character)val).GetSkills().m_skillData.TryGetValue((SkillType)Mathf.Abs(StringExtensionMethods.GetStableHashCode("Hunting")), out var value);
			string value2 = ((Object)((Component)val4).gameObject).name.Replace("(Clone)", "");
			string[] array = Plugin._tier1Meadows.Value.Split(',', ' ');
			if (Plugin._tier4MountainsLevel.Value > 0 && value?.m_level > (float)Plugin._tier4MountainsLevel.Value)
			{
				if (array.Length != 0 && array.Contains(value2))
				{
					((Character)val).RaiseSkill(Skill.fromName("Hunting"), 0.2f);
				}
			}
			else
			{
				((Character)val).RaiseSkill(Skill.fromName("Hunting"), 1f);
			}
		}
	}
	[HarmonyPatch(typeof(Skills), "RaiseSkill")]
	public class SkillsPatch
	{
		private static void Postfix(Skills __instance, SkillType skillType, float factor = 1f)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			if (Plugin._displayExpGained.Value == Toggle.Off)
			{
				return;
			}
			((Character)__instance.m_player).GetSkills().m_skillData.TryGetValue((SkillType)Mathf.Abs(StringExtensionMethods.GetStableHashCode("Hunting")), out var value);
			if ((SkillType?)skillType != value?.m_info.m_skill)
			{
				return;
			}
			try
			{
				if (value.m_level < 100f)
				{
					float value2 = value.m_accumulator / (value.GetNextLevelRequirement() / 100f);
					((Character)__instance.m_player).Message((MessageType)1, $"Level {value.m_level.tFloat(0)} Hunting [{value.m_accumulator.tFloat(2)}/{value.GetNextLevelRequirement().tFloat(2)}] ({value2.tFloat(0)}%)", 0, value.m_info.m_icon, false);
				}
			}
			catch
			{
			}
		}
	}
	public class Tracker : MonoBehaviour
	{
		public string m_resourceName = "";

		private float m_trackRange;

		private Sprite? m_pinIcon;

		private PinData? m_pinData;

		private int m_requiredLevel;

		private static readonly List<PinData> m_pinList = new List<PinData>();

		public void Create(string resourceName, float trackRange, Sprite pinIcon, int requiredLevel)
		{
			m_resourceName = resourceName;
			m_trackRange = trackRange;
			m_pinIcon = pinIcon;
			m_pinData = null;
			m_requiredLevel = requiredLevel;
		}

		private void Update()
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: 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_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0218: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			Player player = Player.m_localPlayer;
			if (!Object.op_Implicit((Object)(object)player))
			{
				return;
			}
			Vector3 position = ((Component)this).transform.position;
			position.y = 0f;
			Vector2 val = default(Vector2);
			((Vector2)(ref val))..ctor(((Component)player).transform.position.x - position.x, ((Component)player).transform.position.z - position.z);
			float magnitude = ((Vector2)(ref val)).magnitude;
			float skillFactor = ((Character)(object)player).GetSkillFactor("Hunting");
			bool flag = Plugin._iconsOnly.Value == Toggle.On;
			bool flag2 = magnitude < m_trackRange;
			m_pinList.RemoveAll((PinData pin) => pin == null || Vector3.Distance(((Component)player).transform.position, pin.m_pos) > m_trackRange);
			if (m_pinList.Count >= Plugin._maxPin.Value)
			{
				PinData val2 = m_pinList[0];
				if (val2 != null)
				{
					Minimap.instance.RemovePin(val2);
				}
				m_pinList.RemoveAt(0);
			}
			if (m_pinData == null && flag2 && m_requiredLevel > 0 && skillFactor >= (float)m_requiredLevel / 100f && m_pinList.Count < Plugin._maxPin.Value)
			{
				m_pinData = Minimap.instance.AddPin(position, (PinType)8, flag ? "" : m_resourceName, false, false, 0L, default(PlatformUserID));
				if (m_pinData != null)
				{
					m_pinData.m_icon = m_pinIcon;
					m_pinData.m_worldSize = 0f;
					m_pinList.Add(m_pinData);
				}
			}
			else if (m_pinData != null && !flag2)
			{
				RemovePin();
			}
			else if (m_pinData != null && (m_requiredLevel <= 0 || (float)m_requiredLevel / 100f > skillFactor))
			{
				RemovePin();
			}
			else if (m_pinData != null && Plugin._hidePins)
			{
				RemovePin();
			}
			if (m_pinData != null)
			{
				m_pinData.m_pos = position;
			}
		}

		private void RemovePin()
		{
			if (m_pinData == null)
			{
				return;
			}
			try
			{
				if (m_pinList.Contains(m_pinData))
				{
					m_pinList.Remove(m_pinData);
				}
				Minimap.instance.RemovePin(m_pinData);
			}
			catch
			{
			}
			finally
			{
				m_pinData = null;
			}
		}

		private void OnDestroy()
		{
			RemovePin();
		}
	}
}
namespace Hunting.Functions
{
	public class ConfigurationManagerAttributes
	{
		[UsedImplicitly]
		public bool? ShowRangeAsPercent;

		[UsedImplicitly]
		public int? Order;

		[UsedImplicitly]
		public bool? Browsable;

		[UsedImplicitly]
		public string Category;

		[UsedImplicitly]
		public Action<ConfigEntryBase> CustomDrawer;
	}
	public static class Helper
	{
		public static readonly IDictionary<string, Sprite> _Tier1Icons = new Dictionary<string, Sprite>();

		public static readonly IDictionary<string, Sprite> _Tier2Icons = new Dictionary<string, Sprite>();

		public static readonly IDictionary<string, Sprite> _Tier3Icons = new Dictionary<string, Sprite>();

		public static readonly IDictionary<string, Sprite> _Tier4Icons = new Dictionary<string, Sprite>();

		public static readonly IDictionary<string, Sprite> _Tier5Icons = new Dictionary<string, Sprite>();

		public static readonly IDictionary<string, Sprite> _Tier6Icons = new Dictionary<string, Sprite>();

		public static readonly IDictionary<string, Sprite> _Tier7Icons = new Dictionary<string, Sprite>();

		public static readonly IDictionary<string, Sprite> _Tier8Icons = new Dictionary<string, Sprite>();

		public static float tFloat(this float value, int digits)
		{
			double num = Math.Pow(10.0, digits);
			return (float)(Math.Truncate(num * (double)value) / num);
		}

		private static string TrackPrey(string prey, string track)
		{
			Match match = new Regex(track, RegexOptions.IgnoreCase).Match(prey);
			if (!match.Success)
			{
				return "";
			}
			return match.Value;
		}

		public static void GetTier1PinIcons(string prey)
		{
			if (_Tier1Icons.ContainsKey(prey))
			{
				return;
			}
			foreach (string key in ObjectDBPatch._SpritesDictTier1.Keys)
			{
				if (!(TrackPrey(prey, key) == ""))
				{
					_Tier1Icons.Add(prey, ObjectDBPatch._SpritesDictTier1[key]);
					break;
				}
			}
		}

		public static void GetTier2PinIcons(string prey)
		{
			if (_Tier2Icons.ContainsKey(prey))
			{
				return;
			}
			foreach (string key in ObjectDBPatch._SpritesDictTier2.Keys)
			{
				if (!(TrackPrey(prey, key) == ""))
				{
					_Tier2Icons.Add(prey, ObjectDBPatch._SpritesDictTier2[key]);
					break;
				}
			}
		}

		public static void GetTier3PinIcons(string prey)
		{
			if (_Tier3Icons.ContainsKey(prey))
			{
				return;
			}
			foreach (string key in ObjectDBPatch._SpritesDictTier3.Keys)
			{
				if (!(TrackPrey(prey, key) == ""))
				{
					_Tier3Icons.Add(prey, ObjectDBPatch._SpritesDictTier3[key]);
					break;
				}
			}
		}

		public static void GetTier4PinIcons(string prey)
		{
			if (_Tier4Icons.ContainsKey(prey))
			{
				return;
			}
			foreach (string key in ObjectDBPatch._SpritesDictTier4.Keys)
			{
				if (!(TrackPrey(prey, key) == ""))
				{
					_Tier4Icons.Add(prey, ObjectDBPatch._SpritesDictTier4[key]);
					break;
				}
			}
		}

		public static void GetTier5PinIcons(string prey)
		{
			if (_Tier5Icons.ContainsKey(prey))
			{
				return;
			}
			foreach (string key in ObjectDBPatch._SpritesDictTier5.Keys)
			{
				if (!(TrackPrey(prey, key) == ""))
				{
					_Tier5Icons.Add(prey, ObjectDBPatch._SpritesDictTier5[key]);
					break;
				}
			}
		}

		public static void GetTier6PinIcons(string prey)
		{
			if (_Tier6Icons.ContainsKey(prey))
			{
				return;
			}
			foreach (string key in ObjectDBPatch._SpritesDictTier6.Keys)
			{
				if (!(TrackPrey(prey, key) == ""))
				{
					_Tier6Icons.Add(prey, ObjectDBPatch._SpritesDictTier6[key]);
					break;
				}
			}
		}

		public static void GetTier7PinIcons(string prey)
		{
			if (_Tier7Icons.ContainsKey(prey))
			{
				return;
			}
			foreach (string key in ObjectDBPatch._SpritesDictTier7.Keys)
			{
				if (!(TrackPrey(prey, key) == ""))
				{
					_Tier7Icons.Add(prey, ObjectDBPatch._SpritesDictTier7[key]);
					break;
				}
			}
		}

		public static void GetTier8PinIcons(string prey)
		{
			if (_Tier8Icons.ContainsKey(prey))
			{
				return;
			}
			foreach (string key in ObjectDBPatch._SpritesDictTier8.Keys)
			{
				if (!(TrackPrey(prey, key) == ""))
				{
					_Tier8Icons.Add(prey, ObjectDBPatch._SpritesDictTier8[key]);
					break;
				}
			}
		}
	}
	public enum Toggle
	{
		On = 1,
		Off = 0
	}
}
namespace ServerSync
{
	[PublicAPI]
	internal abstract class OwnConfigEntryBase
	{
		public object? LocalBaseValue;

		public bool SynchronizedConfig = true;

		public abstract ConfigEntryBase BaseConfig { get; }
	}
	[PublicAPI]
	internal class SyncedConfigEntry<T>(ConfigEntry<T> sourceConfig) : OwnConfigEntryBase()
	{
		public readonly ConfigEntry<T> SourceConfig = sourceConfig;

		public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig;

		public T Value
		{
			get
			{
				return SourceConfig.Value;
			}
			set
			{
				SourceConfig.Value = value;
			}
		}

		public void AssignLocalValue(T value)
		{
			if (LocalBaseValue == null)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal abstract class CustomSyncedValueBase
	{
		public object? LocalBaseValue;

		public readonly string Identifier;

		public readonly Type Type;

		private object? boxedValue;

		protected bool localIsOwner;

		public readonly int Priority;

		public object? BoxedValue
		{
			get
			{
				return boxedValue;
			}
			set
			{
				boxedValue = value;
				this.ValueChanged?.Invoke();
			}
		}

		public event Action? ValueChanged;

		protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type, int priority)
		{
			Priority = priority;
			Identifier = identifier;
			Type = type;
			configSync.AddCustomValue(this);
			localIsOwner = configSync.IsSourceOfTruth;
			configSync.SourceOfTruthChanged += delegate(bool truth)
			{
				localIsOwner = truth;
			};
		}
	}
	[PublicAPI]
	internal sealed class CustomSyncedValue<T> : CustomSyncedValueBase
	{
		public T Value
		{
			get
			{
				return (T)base.BoxedValue;
			}
			set
			{
				base.BoxedValue = value;
			}
		}

		public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T), int priority = 0)
			: base(configSync, identifier, typeof(T), priority)
		{
			Value = value;
		}

		public void AssignLocalValue(T value)
		{
			if (localIsOwner)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal class ConfigurationManagerAttributes
	{
		[UsedImplicitly]
		public bool? ReadOnly = false;
	}
	[PublicAPI]
	internal class ConfigSync
	{
		[HarmonyPatch(typeof(ZRpc), "HandlePackage")]
		private static class SnatchCurrentlyHandlingRPC
		{
			public static ZRpc? currentRpc;

			[HarmonyPrefix]
			private static void Prefix(ZRpc __instance)
			{
				currentRpc = __instance;
			}
		}

		[HarmonyPatch(typeof(ZNet), "Awake")]
		internal static class RegisterRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance)
			{
				isServer = __instance.IsServer();
				foreach (ConfigSync configSync2 in configSyncs)
				{
					ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_FromOtherClientConfigSync);
					if (isServer)
					{
						configSync2.InitialSyncDone = true;
						Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections"));
					}
				}
				if (isServer)
				{
					((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges());
				}
				static void SendAdmin(List<ZNetPeer> peers, bool isAdmin)
				{
					ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1]
					{
						new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = isAdmin
						}
					});
					ConfigSync configSync = configSyncs.First();
					if (configSync != null)
					{
						((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package));
					}
				}
				static IEnumerator WatchAdminListChanges()
				{
					MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
					SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
					List<string> CurrentList = new List<string>(adminList.GetList());
					while (true)
					{
						yield return (object)new WaitForSeconds(30f);
						if (!adminList.GetList().SequenceEqual(CurrentList))
						{
							CurrentList = new List<string>(adminList.GetList());
							List<ZNetPeer> adminPeer = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p)
							{
								string hostName = p.m_rpc.GetSocket().GetHostName();
								return ((object)listContainsId == null) ? adminList.Contains(hostName) : ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName }));
							}).ToList();
							List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList();
							SendAdmin(nonAdminPeer, isAdmin: false);
							SendAdmin(adminPeer, isAdmin: true);
						}
					}
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static class RegisterClientRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance, ZNetPeer peer)
			{
				if (__instance.IsServer())
				{
					return;
				}
				foreach (ConfigSync configSync in configSyncs)
				{
					peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync);
				}
			}
		}

		private class ParsedConfigs
		{
			public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new Dictionary<OwnConfigEntryBase, object>();

			public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new Dictionary<CustomSyncedValueBase, object>();
		}

		[HarmonyPatch(typeof(ZNet), "Shutdown")]
		private class ResetConfigsOnShutdown
		{
			[HarmonyPostfix]
			private static void Postfix()
			{
				ProcessingServerUpdate = true;
				foreach (ConfigSync configSync in configSyncs)
				{
					configSync.resetConfigsFromServer();
					configSync.IsSourceOfTruth = true;
					configSync.InitialSyncDone = false;
				}
				ProcessingServerUpdate = false;
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private class SendConfigsAfterLogin
		{
			private class BufferingSocket : ZPlayFabSocket, ISocket
			{
				public volatile bool finished = false;

				public volatile int versionMatchQueued = -1;

				public readonly List<ZPackage> Package = new List<ZPackage>();

				public readonly ISocket Original;

				public BufferingSocket(ISocket original)
				{
					Original = original;
					((ZPlayFabSocket)this)..ctor();
				}

				public bool IsConnected()
				{
					return Original.IsConnected();
				}

				public ZPackage Recv()
				{
					return Original.Recv();
				}

				public int GetSendQueueSize()
				{
					return Original.GetSendQueueSize();
				}

				public int GetCurrentSendRate()
				{
					return Original.GetCurrentSendRate();
				}

				public bool IsHost()
				{
					return Original.IsHost();
				}

				public void Dispose()
				{
					Original.Dispose();
				}

				public bool GotNewData()
				{
					return Original.GotNewData();
				}

				public void Close()
				{
					Original.Close();
				}

				public string GetEndPointString()
				{
					return Original.GetEndPointString();
				}

				public void GetAndResetStats(out int totalSent, out int totalRecv)
				{
					Original.GetAndResetStats(ref totalSent, ref totalRecv);
				}

				public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec)
				{
					Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec);
				}

				public ISocket Accept()
				{
					return Original.Accept();
				}

				public int GetHostPort()
				{
					return Original.GetHostPort();
				}

				public bool Flush()
				{
					return Original.Flush();
				}

				public string GetHostName()
				{
					return Original.GetHostName();
				}

				public void VersionMatch()
				{
					if (finished)
					{
						Original.VersionMatch();
					}
					else
					{
						versionMatchQueued = Package.Count;
					}
				}

				public void Send(ZPackage pkg)
				{
					//IL_0057: Unknown result type (might be due to invalid IL or missing references)
					//IL_005d: Expected O, but got Unknown
					int pos = pkg.GetPos();
					pkg.SetPos(0);
					int num = pkg.ReadInt();
					if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished)
					{
						ZPackage val = new ZPackage(pkg.GetArray());
						val.SetPos(pos);
						Package.Add(val);
					}
					else
					{
						pkg.SetPos(pos);
						Original.Send(pkg);
					}
				}
			}

			[HarmonyPriority(800)]
			[HarmonyPrefix]
			private static void Prefix(ref Dictionary<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc)
			{
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Invalid comparison between Unknown and I4
				if (!__instance.IsServer())
				{
					return;
				}
				BufferingSocket bufferingSocket = new BufferingSocket(rpc.GetSocket());
				AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket);
				object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
				ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
				if (val != null && (int)ZNet.m_onlineBackend > 0)
				{
					FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket");
					object? value = fieldInfo.GetValue(val);
					ZPlayFabSocket val2 = (ZPlayFabSocket)((value is ZPlayFabSocket) ? value : null);
					if (val2 != null)
					{
						typeof(ZPlayFabSocket).GetField("m_remotePlayerId").SetValue(bufferingSocket, val2.m_remotePlayerId);
					}
					fieldInfo.SetValue(val, bufferingSocket);
				}
				if (__state == null)
				{
					__state = new Dictionary<Assembly, BufferingSocket>();
				}
				__state[Assembly.GetExecutingAssembly()] = bufferingSocket;
			}

			[HarmonyPostfix]
			private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				ZNetPeer peer;
				if (__instance.IsServer())
				{
					object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (peer == null)
					{
						SendBufferedData();
					}
					else
					{
						((MonoBehaviour)__instance).StartCoroutine(sendAsync());
					}
				}
				void SendBufferedData()
				{
					if (rpc.GetSocket() is BufferingSocket bufferingSocket)
					{
						AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original);
						object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
						ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null);
						if (val != null)
						{
							AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original);
						}
					}
					BufferingSocket bufferingSocket2 = __state[Assembly.GetExecutingAssembly()];
					bufferingSocket2.finished = true;
					for (int i = 0; i < bufferingSocket2.Package.Count; i++)
					{
						if (i == bufferingSocket2.versionMatchQueued)
						{
							bufferingSocket2.Original.VersionMatch();
						}
						bufferingSocket2.Original.Send(bufferingSocket2.Package[i]);
					}
					if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued)
					{
						bufferingSocket2.Original.VersionMatch();
					}
				}
				IEnumerator sendAsync()
				{
					foreach (ConfigSync configSync in configSyncs)
					{
						List<PackageEntry> entries = new List<PackageEntry>();
						if (configSync.CurrentVersion != null)
						{
							entries.Add(new PackageEntry
							{
								section = "Internal",
								key = "serverversion",
								type = typeof(string),
								value = configSync.CurrentVersion
							});
						}
						MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						entries.Add(new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2]
							{
								adminList,
								rpc.GetSocket().GetHostName()
							}))
						});
						ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false);
						yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package));
					}
					SendBufferedData();
				}
			}
		}

		private class PackageEntry
		{
			public string section = null;

			public string key = null;

			public Type type = null;

			public object? value;
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")]
		private static class PreventSavingServerInfo
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, ref string __result)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase))
				{
					return true;
				}
				__result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType);
				return false;
			}
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")]
		private static class PreventConfigRereadChangingValues
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, string value)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null)
				{
					return true;
				}
				try
				{
					ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType);
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}");
				}
				return false;
			}
		}

		private class InvalidDeserializationTypeException : Exception
		{
			public string expected = null;

			public string received = null;

			public string field = "";
		}

		public static bool ProcessingServerUpdate;

		public readonly string Name;

		public string? DisplayName;

		public string? CurrentVersion;

		public string? MinimumRequiredVersion;

		public bool ModRequired = false;

		private bool? forceConfigLocking;

		private bool isSourceOfTruth = true;

		private static readonly HashSet<ConfigSync> configSyncs;

		private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>();

		private HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>();

		private static bool isServer;

		private static bool lockExempt;

		private OwnConfigEntryBase? lockedConfig = null;

		private const byte PARTIAL_CONFIGS = 1;

		private const byte FRAGMENTED_CONFIG = 2;

		private const byte COMPRESSED_CONFIG = 4;

		private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>();

		private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>();

		private static long packageCounter;

		public bool IsLocked
		{
			get
			{
				bool? flag = forceConfigLocking;
				bool num;
				if (!flag.HasValue)
				{
					if (lockedConfig == null)
					{
						goto IL_0052;
					}
					num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0;
				}
				else
				{
					num = flag == true;
				}
				if (!num)
				{
					goto IL_0052;
				}
				int result = ((!lockExempt) ? 1 : 0);
				goto IL_0053;
				IL_0052:
				result = 0;
				goto IL_0053;
				IL_0053:
				return (byte)result != 0;
			}
			set
			{
				forceConfigLocking = value;
			}
		}

		public bool IsAdmin => lockExempt || isSourceOfTruth;

		public bool IsSourceOfTruth
		{
			get
			{
				return isSourceOfTruth;
			}
			private set
			{
				if (value != isSourceOfTruth)
				{
					isSourceOfTruth = value;
					this.SourceOfTruthChanged?.Invoke(value);
				}
			}
		}

		public bool InitialSyncDone { get; private set; } = false;

		public event Action<bool>? SourceOfTruthChanged;

		private event Action? lockedConfigChanged;

		static ConfigSync()
		{
			ProcessingServerUpdate = false;
			configSyncs = new HashSet<ConfigSync>();
			lockExempt = false;
			packageCounter = 0L;
			RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle);
		}

		public ConfigSync(string name)
		{
			Name = name;
			configSyncs.Add(this);
			new VersionCheck(this);
		}

		public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry)
		{
			OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry);
			SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>;
			if (syncedEntry == null)
			{
				syncedEntry = new SyncedConfigEntry<T>(configEntry);
				AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1]
				{
					new ConfigurationManagerAttributes()
				}.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray());
				configEntry.SettingChanged += delegate
				{
					if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig)
					{
						Broadcast(0L, (ConfigEntryBase)configEntry);
					}
				};
				allConfigs.Add(syncedEntry);
			}
			return syncedEntry;
		}

		public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible
		{
			if (lockedConfig != null)
			{
				throw new Exception("Cannot initialize locking ConfigEntry twice");
			}
			lockedConfig = AddConfigEntry<T>(lockingConfig);
			lockingConfig.SettingChanged += delegate
			{
				this.lockedConfigChanged?.Invoke();
			};
			return (SyncedConfigEntry<T>)lockedConfig;
		}

		internal void AddCustomValue(CustomSyncedValueBase customValue)
		{
			if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue.Identifier))
			{
				throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)");
			}
			allCustomValues.Add(customValue);
			allCustomValues = new HashSet<CustomSyncedValueBase>(allCustomValues.OrderByDescending((CustomSyncedValueBase v) => v.Priority));
			customValue.ValueChanged += delegate
			{
				if (!ProcessingServerUpdate)
				{
					Broadcast(0L, customValue);
				}
			};
		}

		private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package)
		{
			lockedConfigChanged += serverLockedSettingChanged;
			IsSourceOfTruth = false;
			if (HandleConfigSyncRPC(0L, package, clientUpdate: false))
			{
				InitialSyncDone = true;
			}
		}

		private void RPC_FromOtherClientConfigSync(long sender, ZPackage package)
		{
			HandleConfigSyncRPC(sender, package, clientUpdate: true);
		}

		private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate)
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Expected O, but got Unknown
			//IL_0250: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Expected O, but got Unknown
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Expected O, but got Unknown
			try
			{
				if (isServer && IsLocked)
				{
					ZRpc? currentRpc = SnatchCurrentlyHandlingRPC.currentRpc;
					object obj;
					if (currentRpc == null)
					{
						obj = null;
					}
					else
					{
						ISocket socket = currentRpc.GetSocket();
						obj = ((socket != null) ? socket.GetHostName() : null);
					}
					string text = (string)obj;
					if (text != null)
					{
						MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text }))))
						{
							return false;
						}
					}
				}
				cacheExpirations.RemoveAll(delegate(KeyValuePair<long, string> kv)
				{
					if (kv.Key < DateTimeOffset.Now.Ticks)
					{
						configValueCache.Remove(kv.Value);
						return true;
					}
					return false;
				});
				byte b = package.ReadByte();
				if ((b & 2) != 0)
				{
					long num = package.ReadLong();
					string text2 = sender.ToString() + num;
					if (!configValueCache.TryGetValue(text2, out SortedDictionary<int, byte[]> value))
					{
						value = new SortedDictionary<int, byte[]>();
						configValueCache[text2] = value;
						cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2));
					}
					int key = package.ReadInt();
					int num2 = package.ReadInt();
					value.Add(key, package.ReadByteArray());
					if (value.Count < num2)
					{
						return false;
					}
					configValueCache.Remove(text2);
					package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray());
					b = package.ReadByte();
				}
				ProcessingServerUpdate = true;
				if ((b & 4) != 0)
				{
					byte[] buffer = package.ReadByteArray();
					MemoryStream stream = new MemoryStream(buffer);
					MemoryStream memoryStream = new MemoryStream();
					using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress))
					{
						deflateStream.CopyTo(memoryStream);
					}
					package = new ZPackage(memoryStream.ToArray());
					b = package.ReadByte();
				}
				if ((b & 1) == 0)
				{
					resetConfigsFromServer();
				}
				ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package);
				ConfigFile val2 = null;
				bool saveOnConfigSet = false;
				foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues)
				{
					if (!isServer && configValue.Key.LocalBaseValue == null)
					{
						configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue;
					}
					if (val2 == null)
					{
						val2 = configValue.Key.BaseConfig.ConfigFile;
						saveOnConfigSet = val2.SaveOnConfigSet;
						val2.SaveOnConfigSet = false;
					}
					configValue.Key.BaseConfig.BoxedValue = configValue.Value;
				}
				if (val2 != null)
				{
					val2.SaveOnConfigSet = saveOnConfigSet;
					val2.Save();
				}
				foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues)
				{
					if (!isServer)
					{
						CustomSyncedValueBase key2 = customValue.Key;
						if (key2.LocalBaseValue == null)
						{
							key2.LocalBaseValue = customValue.Key.BoxedValue;
						}
					}
					customValue.Key.BoxedValue = customValue.Value;
				}
				Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name));
				if (!isServer)
				{
					serverLockedSettingChanged();
				}
				return true;
			}
			finally
			{
				ProcessingServerUpdate = false;
			}
		}

		private ParsedConfigs ReadConfigsFromPackage(ZPackage package)
		{
			ParsedConfigs parsedConfigs = new ParsedConfigs();
			Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c);
			Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c);
			int num = package.ReadInt();
			for (int num2 = 0; num2 < num; num2++)
			{
				string text = package.ReadString();
				string text2 = package.ReadString();
				string text3 = package.ReadString();
				Type type = Type.GetType(text3);
				if (text3 == "" || type != null)
				{
					object obj;
					try
					{
						obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type));
					}
					catch (InvalidDeserializationTypeException ex)
					{
						Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected));
						continue;
					}
					OwnConfigEntryBase value2;
					if (text == "Internal")
					{
						CustomSyncedValueBase value;
						if (text2 == "serverversion")
						{
							if (obj?.ToString() != CurrentVersion)
							{
								Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown")));
							}
						}
						else if (text2 == "lockexempt")
						{
							if (obj is bool flag)
							{
								lockExempt = flag;
							}
						}
						else if (dictionary2.TryGetValue(text2, out value))
						{
							if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3)
							{
								parsedConfigs.customValues[value] = obj;
								continue;
							}
							Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName));
						}
					}
					else if (dictionary.TryGetValue(text + "_" + text2, out value2))
					{
						Type type2 = configType(value2.BaseConfig);
						if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3)
						{
							parsedConfigs.configValues[value2] = obj;
							continue;
						}
						Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName));
					}
					else
					{
						Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match."));
					}
					continue;
				}
				Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs"));
				return new ParsedConfigs();
			}
			return parsedConfigs;
		}

		private static bool isWritableConfig(OwnConfigEntryBase config)
		{
			ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config));
			if (configSync == null)
			{
				return true;
			}
			return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null || (!configSync.IsLocked && (config != configSync.lockedConfig || lockExempt));
		}

		private void serverLockedSettingChanged()
		{
			foreach (OwnConfigEntryBase allConfig in allConfigs)
			{
				configAttribute<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig);
			}
		}

		private void resetConfigsFromServer()
		{
			ConfigFile val = null;
			bool saveOnConfigSet = false;
			foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null))
			{
				if (val == null)
				{
					val = item.BaseConfig.ConfigFile;
					saveOnConfigSet = val.SaveOnConfigSet;
					val.SaveOnConfigSet = false;
				}
				item.BaseConfig.BoxedValue = item.LocalBaseValue;
				item.LocalBaseValue = null;
			}
			if (val != null)
			{
				val.SaveOnConfigSet = saveOnConfigSet;
			}
			foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null))
			{
				item2.BoxedValue = item2.LocalBaseValue;
				item2.LocalBaseValue = null;
			}
			lockedConfigChanged -= serverLockedSettingChanged;
			serverLockedSettingChanged();
		}

		private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package)
		{
			ZRoutedRpc rpc = ZRoutedRpc.instance;
			if (rpc == null)
			{
				yield break;
			}
			byte[] data = package.GetArray();
			if (data != null && data.LongLength > 250000)
			{
				int fragments = (int)(1 + (data.LongLength - 1) / 250000);
				long packageIdentifier = ++packageCounter;
				int fragment = 0;
				while (fragment < fragments)
				{
					foreach (bool item in waitForQueue())
					{
						yield return item;
					}
					if (peer.m_socket.IsConnected())
					{
						ZPackage fragmentedPackage = new ZPackage();
						fragmentedPackage.Write((byte)2);
						fragmentedPackage.Write(packageIdentifier);
						fragmentedPackage.Write(fragment);
						fragmentedPackage.Write(fragments);
						fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray());
						SendPackage(fragmentedPackage);
						if (fragment != fragments - 1)
						{
							yield return true;
						}
						int num = fragment + 1;
						fragment = num;
						continue;
					}
					break;
				}
				yield break;
			}
			foreach (bool item2 in waitForQueue())
			{
				yield return item2;
			}
			SendPackage(package);
			void SendPackage(ZPackage pkg)
			{
				string text = Name + " ConfigSync";
				if (isServer)
				{
					peer.m_rpc.Invoke(text, new object[1] { pkg });
				}
				else
				{
					rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg });
				}
			}
			IEnumerable<bool> waitForQueue()
			{
				float timeout = Time.time + 30f;
				while (peer.m_socket.GetSendQueueSize() > 20000)
				{
					if (Time.time > timeout)
					{
						Debug.Log((object)$"Disconnecting {peer.m_uid} after 30 seconds config sending timeout");
						peer.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 });
						ZNet.instance.Disconnect(peer);
						break;
					}
					yield return false;
				}
			}
		}

		private IEnumerator sendZPackage(long target, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				return Enumerable.Empty<object>().GetEnumerator();
			}
			List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance);
			if (target != 0)
			{
				list = list.Where((ZNetPeer p) => p.m_uid == target).ToList();
			}
			return sendZPackage(list, package);
		}

		private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				yield break;
			}
			byte[] rawData = package.GetArray();
			if (rawData != null && rawData.LongLength > 10000)
			{
				ZPackage compressedPackage = new ZPackage();
				compressedPackage.Write((byte)4);
				MemoryStream output = new MemoryStream();
				using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal))
				{
					deflateStream.Write(rawData, 0, rawData.Length);
				}
				compressedPackage.Write(output.ToArray());
				package = compressedPackage;
			}
			List<IEnumerator<bool>> writers = (from p in peers
				where p.IsReady()
				select distributeConfigToPeers(p, package)).ToList();
			writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			while (writers.Count > 0)
			{
				yield return null;
				writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			}
		}

		private void Broadcast(long target, params ConfigEntryBase[] configs)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(configs);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private void Broadcast(long target, params CustomSyncedValueBase[] customValues)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(null, customValues);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private static OwnConfigEntryBase? configData(ConfigEntryBase config)
		{
			return config.Description.Tags?.OfType<OwnConfigEntryBase>().SingleOrDefault();
		}

		public static SyncedConfigEntry<T>? ConfigData<T>(ConfigEntry<T> config)
		{
			return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault();
		}

		private static T configAttribute<T>(ConfigEntryBase config)
		{
			return config.Description.Tags.OfType<T>().First();
		}

		private static Type configType(ConfigEntryBase config)
		{
			return configType(config.SettingType);
		}

		private static Type configType(Type type)
		{
			return type.IsEnum ? Enum.GetUnderlyingType(type) : type;
		}

		private static ZPackage ConfigsToPackage(IEnumerable<ConfigEntryBase>? configs = null, IEnumerable<CustomSyncedValueBase>? customValues = null, IEnumerable<PackageEntry>? packageEntries = null, bool partial = true)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			List<ConfigEntryBase> list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List<ConfigEntryBase>();
			List<CustomSyncedValueBase> list2 = customValues?.ToList() ?? new List<CustomSyncedValueBase>();
			ZPackage val = new ZPackage();
			val.Write((byte)(partial ? 1 : 0));
			val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0));
			foreach (PackageEntry item in packageEntries ?? Array.Empty<PackageEntry>())
			{
				AddEntryToPackage(val, item);
			}
			foreach (CustomSyncedValueBase item2 in list2)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = "Internal",
					key = item2.Identifier,
					type = item2.Type,
					value = item2.BoxedValue
				});
			}
			foreach (ConfigEntryBase item3 in list)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = item3.Definition.Section,
					key = item3.Definition.Key,
					type = configType(item3),
					value = item3.BoxedValue
				});
			}
			return val;
		}

		private static void AddEntryToPackage(ZPackage package, PackageEntry entry)
		{
			package.Write(entry.section);
			package.Write(entry.key);
			package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type));
			AddValueToZPackage(package, entry.value);
		}

		private static string GetZPackageTypeString(Type type)
		{
			return type.AssemblyQualifiedName;
		}

		private static void AddValueToZPackage(ZPackage package, object? value)
		{
			Type type = value?.GetType();
			if (value is Enum)
			{
				value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture);
			}
			else
			{
				if (value is ICollection collection)
				{
					package.Write(collection.Count);
					{
						foreach (object item in collection)
						{
							AddValueToZPackage(package, item);
						}
						return;
					}
				}
				if ((object)type != null && type.IsValueType && !type.IsPrimitive)
				{
					FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					package.Write(fields.Length);
					FieldInfo[] array = fields;
					foreach (FieldInfo fieldInfo in array)
					{
						package.Write(GetZPackageTypeString(fieldInfo.FieldType));
						AddValueToZPackage(package, fieldInfo.GetValue(value));
					}
					return;
				}
			}
			ZRpc.Serialize(new object[1] { value }, ref package);
		}

		private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type)
		{
			if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum)
			{
				FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				int num = package.ReadInt();
				if (num != fields.Length)
				{
					throw new InvalidDeserializationTypeException
					{
						received = $"(field count: {num})",
						expected = $"(field count: {fields.Length})"
					};
				}
				object uninitializedObject = FormatterServices.GetUninitializedObject(type);
				FieldInfo[] array = fields;
				foreach (FieldInfo fieldInfo in array)
				{
					string text = package.ReadString();
					if (text != GetZPackageTypeString(fieldInfo.FieldType))
					{
						throw new InvalidDeserializationTypeException
						{
							received = text,
							expected = GetZPackageTypeString(fieldInfo.FieldType),
							field = fieldInfo.Name
						};
					}
					fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType));
				}
				return uninitializedObject;
			}
			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >))
			{
				int num2 = package.ReadInt();
				IDictionary dictionary = (IDictionary)Activator.CreateInstance(type);
				Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments);
				FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic);
				FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic);
				for (int j = 0; j < num2; j++)
				{
					object obj = ReadValueWithTypeFromZPackage(package, type2);
					dictionary.Add(field.GetValue(obj), field2.GetValue(obj));
				}
				return dictionary;
			}
			if (type != typeof(List<string>) && type.IsGenericType)
			{
				Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]);
				if ((object)type3 != null && type3.IsAssignableFrom(type))
				{
					int num3 = package.ReadInt();
					object obj2 = Activator.CreateInstance(type);
					MethodInfo method = type3.GetMethod("Add");
					for (int k = 0; k < num3; k++)
					{
						method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) });
					}
					return obj2;
				}
			}
			ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo));
			AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type);
			List<object> source = new List<object>();
			ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source);
			return source.First();
		}
	}
	[PublicAPI]
	[HarmonyPatch]
	internal class VersionCheck
	{
		private static readonly HashSet<VersionCheck> versionChecks;

		private static readonly Dictionary<string, string> notProcessedNames;

		public string Name;

		private string? displayName;

		private string? currentVersion;

		private string? minimumRequiredVersion;

		public bool ModRequired = true;

		private string? ReceivedCurrentVersion;

		private string? ReceivedMinimumRequiredVersion;

		private readonly List<ZRpc> ValidatedClients = new List<ZRpc>();

		private ConfigSync? ConfigSync;

		public string DisplayName
		{
			get
			{
				return displayName ?? Name;
			}
			set
			{
				displayName = value;
			}
		}

		public string CurrentVersion
		{
			get
			{
				return currentVersion ?? "0.0.0";
			}
			set
			{
				currentVersion = value;
			}
		}

		public string MinimumRequiredVersion
		{
			get
			{
				return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0");
			}
			set
			{
				minimumRequiredVersion = value;
			}
		}

		private static void PatchServerSync()
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null));
			if (patchInfo != null && patchInfo.Postfixes.Count((Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0)
			{
				return;
			}
			Harmony val = new Harmony("org.bepinex.helpers.ServerSync");
			foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) })
				where t.IsClass
				select t)
			{
				val.PatchAll(item);
			}
		}

		static VersionCheck()
		{
			versionChecks = new HashSet<VersionCheck>();
			notProcessedNames = new Dictionary<string, string>();
			typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1]
			{
				new Action(PatchServerSync)
			});
		}

		public VersionCheck(string name)
		{
			Name = name;
			ModRequired = true;
			versionChecks.Add(this);
		}

		public VersionCheck(ConfigSync configSync)
		{
			ConfigSync = configSync;
			Name = ConfigSync.Name;
			versionChecks.Add(this);
		}

		public void Initialize()
		{
			ReceivedCurrentVersion = null;
			ReceivedMinimumRequiredVersion = null;
			if (ConfigSync != null)
			{
				Name = ConfigSync.Name;
				DisplayName = ConfigSync.DisplayName;
				CurrentVersion = ConfigSync.CurrentVersion;
				MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion;
				ModRequired = ConfigSync.ModRequired;
			}
		}

		private bool IsVersionOk()
		{
			if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null)
			{
				return !ModRequired;
			}
			bool flag = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion);
			bool flag2 = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion);
			return flag && flag2;
		}

		private string ErrorClient()
		{
			if (ReceivedMinimumRequiredVersion == null)
			{
				return DisplayName + " is not installed on the server.";
			}
			return (new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion)) ? (DisplayName + " may not be higher than version " + ReceivedCurrentVersion + ". You have version " + CurrentVersion + ".") : (DisplayName + " needs to be at least version " + ReceivedMinimumRequiredVersion + ". You have version " + CurrentVersion + ".");
		}

		private string ErrorServer(ZRpc rpc)
		{
			return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion;
		}

		private string Error(ZRpc? rpc = null)
		{
			return (rpc == null) ? ErrorClient() : ErrorServer(rpc);
		}

		private static VersionCheck[] GetFailedClient()
		{
			return versionChecks.Where((VersionCheck check) => !check.IsVersionOk()).ToArray();
		}

		private static VersionCheck[] GetFailedServer(ZRpc rpc)
		{
			return versionChecks.Where((VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc)).ToArray();
		}

		private static void Logout()
		{
			Game.instance.Logout(true, true);