Decompiled source of SummonNPC v0.7.0

plugins/SummonNPC.dll

Decompiled 4 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 BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using ServerSync;
using TMPro;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("SummonNPC")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.7.0.0")]
[assembly: AssemblyInformationalVersion("0.7.0+9292a9704e676047179c93a1f8f0049b3afc0d41")]
[assembly: AssemblyProduct("SummonNPC")]
[assembly: AssemblyTitle("SummonNPC")]
[assembly: AssemblyVersion("0.7.0.0")]
[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 SummonNPC
{
	[BepInPlugin("com.summonnpc.valheim", "SummonNPC", "0.7.0")]
	public sealed class SummonNpcPlugin : BaseUnityPlugin
	{
		private enum PrefabChoice
		{
			Hair,
			Beard,
			Helmet,
			Chest,
			Legs,
			Cape,
			Shield
		}

		internal const string PluginGuid = "com.summonnpc.valheim";

		internal const string PluginName = "SummonNPC";

		internal const string PluginVersion = "0.7.0";

		internal static readonly string SummonPrefabName = "SummonNPC_Summon";

		private static readonly string[] ExcludedPrefabPrefixes = new string[7] { "FW", "SP", "Goblin", "Charred", "Dverger", "Jotun", "StoneGolem" };

		private static readonly string[] SummonShieldPrefabs = new string[2] { "ShieldWood", "ShieldBronzeBuckler" };

		internal static readonly Dictionary<string, ConfigEntry<string>> ShieldAppearances = new Dictionary<string, ConfigEntry<string>>(StringComparer.Ordinal);

		private static bool _appearanceConfigBound;

		private Harmony? _harmony;

		internal static ManualLogSource LogSource { get; private set; } = null;

		internal static ConfigEntry<bool> EnableMod { get; private set; } = null;

		internal static ConfigEntry<bool> DebugLogging { get; private set; } = null;

		internal static ConfigEntry<string> NpcNames { get; private set; } = null;

		internal static ConfigEntry<string> BodyType { get; private set; } = null;

		internal static ConfigEntry<string> HairPrefab { get; private set; } = null;

		internal static ConfigEntry<string> BeardPrefab { get; private set; } = null;

		internal static ConfigEntry<string> HairColor { get; private set; } = null;

		internal static ConfigEntry<string> SkinColor { get; private set; } = null;

		internal static ConfigEntry<string> HelmetPrefab { get; private set; } = null;

		internal static ConfigEntry<string> ChestPrefab { get; private set; } = null;

		internal static ConfigEntry<string> LegsPrefab { get; private set; } = null;

		internal static ConfigEntry<string> CapePrefab { get; private set; } = null;

		internal static ConfigEntry<string> MeleeWeapon { get; private set; } = null;

		internal static ConfigEntry<string> BowPrefab { get; private set; } = null;

		private static ConfigFile PluginConfig { get; set; } = null;

		internal static ConfigSync ServerConfigSync { get; private set; } = null;

		internal static bool UsesSkeletonBody => string.Equals(BodyType.Value, "Skeleton", StringComparison.OrdinalIgnoreCase);

		private void Awake()
		{
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Expected O, but got Unknown
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Expected O, but got Unknown
			LogSource = ((BaseUnityPlugin)this).Logger;
			PluginConfig = ((BaseUnityPlugin)this).Config;
			EnableMod = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enable Mod", true, "Set to false to leave the game's summon behavior unchanged. Restart the game after changing this setting.");
			DebugLogging = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Debug Logging", false, "Enable extra local troubleshooting messages. Restart to capture startup details.");
			NpcNames = ((BaseUnityPlugin)this).Config.Bind<string>("Summon", "NPC Names", "NPC", "Comma-separated names; one name is randomly selected for each summon.");
			BodyType = ((BaseUnityPlugin)this).Config.Bind<string>("Appearance", "Body Type", "Male", new ConfigDescription("Body model used by the summoned NPC: Male, Female, or the vanilla skeleton. Restart the game after changing this setting. Hair and beard appearance settings apply to player bodies.", (AcceptableValueBase)(object)new AcceptableValueList<string>(new string[3] { "Male", "Female", "Skeleton" }), Array.Empty<object>()));
			ServerConfigSync = new ConfigSync("com.summonnpc.valheim")
			{
				DisplayName = "SummonNPC",
				CurrentVersion = "0.7.0",
				MinimumRequiredVersion = "0.7.0",
				ModRequired = true,
				IsLocked = true
			};
			AddSynchronizedConfigEntry<bool>(EnableMod);
			AddSynchronizedConfigEntry<string>(NpcNames);
			AddSynchronizedConfigEntry<string>(BodyType);
			LogSource.LogInfo((object)"Loading SummonNPC.");
			_harmony = new Harmony("com.summonnpc.valheim");
			_harmony.PatchAll(typeof(SummonNpcPlugin).Assembly);
		}

		private IEnumerator Start()
		{
			while (!IsObjectDatabaseReady(ObjectDB.instance))
			{
				yield return null;
			}
			BindAppearanceConfig(ObjectDB.instance);
			while ((Object)(object)ZNet.instance == (Object)null || (Object)(object)ZNetScene.instance == (Object)null || !ServerConfigSync.InitialSyncDone)
			{
				yield return null;
			}
			RegisterSummonNpcPatch.TryRegister(ZNetScene.instance);
		}

		private void OnDestroy()
		{
			Harmony? harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}

		internal static void TryBindAppearanceConfig()
		{
			ObjectDB instance = ObjectDB.instance;
			if (IsObjectDatabaseReady(instance))
			{
				BindAppearanceConfig(instance);
			}
		}

		private static bool IsObjectDatabaseReady(ObjectDB? objectDatabase)
		{
			if ((Object)(object)objectDatabase != (Object)null)
			{
				return objectDatabase.m_items.Count > 0;
			}
			return false;
		}

		private static void BindAppearanceConfig(ObjectDB objectDatabase)
		{
			if (!_appearanceConfigBound)
			{
				string[] prefabOptions = GetPrefabOptions(objectDatabase, PrefabChoice.Hair, "HairNone");
				string[] prefabOptions2 = GetPrefabOptions(objectDatabase, PrefabChoice.Beard, "BeardNone");
				string[] prefabOptions3 = GetPrefabOptions(objectDatabase, PrefabChoice.Helmet, "HelmetBronze");
				string[] prefabOptions4 = GetPrefabOptions(objectDatabase, PrefabChoice.Chest, "ArmorBronzeChest");
				string[] prefabOptions5 = GetPrefabOptions(objectDatabase, PrefabChoice.Legs, "ArmorBronzeLegs");
				string[] prefabOptions6 = GetPrefabOptions(objectDatabase, PrefabChoice.Cape, "CapeTrollHide");
				string[] meleeWeaponOptions = GetMeleeWeaponOptions(objectDatabase);
				string[] bowOptions = GetBowOptions(objectDatabase);
				string[] prefabOptions7 = GetPrefabOptions(objectDatabase, PrefabChoice.Shield, "None");
				prefabOptions7[0] = "Default";
				HairPrefab = BindPrefabChoice("Hair", "HairNone", "Hair prefab name; use HairNone to remove hair.", prefabOptions);
				BeardPrefab = BindPrefabChoice("Beard", "BeardNone", "Beard prefab name; use BeardNone to remove the beard.", prefabOptions2);
				HairColor = PluginConfig.Bind<string>("Appearance", "Hair Color", "#8C6345", "Hex hair color, such as #8C6345. Use Default to preserve the game's default hair color.");
				SkinColor = PluginConfig.Bind<string>("Appearance", "Skin Color", "#A6A6A6", "Hex skin color, such as #A6A6A6.");
				AddSynchronizedConfigEntry<string>(HairColor);
				AddSynchronizedConfigEntry<string>(SkinColor);
				HelmetPrefab = BindPrefabChoice("Helmet Prefab", "HelmetBronze", "Helmet prefab name, or None to remove the helmet.", prefabOptions3, "Equipment");
				ChestPrefab = BindPrefabChoice("Chest Prefab", "ArmorBronzeChest", "Chest armor prefab name, or None to remove chest armor.", prefabOptions4, "Equipment");
				LegsPrefab = BindPrefabChoice("Legs Prefab", "ArmorBronzeLegs", "Leg armor prefab name, or None to remove leg armor.", prefabOptions5, "Equipment");
				CapePrefab = BindPrefabChoice("Cape Prefab", "CapeTrollHide", "Cape prefab name, or None to remove the cape.", prefabOptions6, "Equipment");
				MeleeWeapon = BindPrefabChoice("Melee Weapon", "Default", "Weapon appearance. Default keeps the vanilla look; combat and ranged loadouts remain unchanged.", meleeWeaponOptions, "Equipment");
				BowPrefab = BindPrefabChoice("Bow Prefab", "Default", "Bow appearance for ranged summons. Default keeps the vanilla look; damage, attacks, and summon loadout chances remain unchanged.", bowOptions, "Equipment");
				BindShieldAppearances(prefabOptions7);
				_appearanceConfigBound = true;
				if (DebugLogging.Value)
				{
					LogSource.LogInfo((object)($"Loaded appearance choices: hair={prefabOptions.Length}, beard={prefabOptions2.Length}, " + $"helmets={prefabOptions3.Length - 1}, chest={prefabOptions4.Length - 1}, " + $"legs={prefabOptions5.Length - 1}, capes={prefabOptions6.Length - 1}, " + $"melee weapons={meleeWeaponOptions.Length - 1}, bows={bowOptions.Length - 1}, " + $"shields={prefabOptions7.Length - 1}."));
				}
			}
		}

		private static void BindShieldAppearances(string[] options)
		{
			string[] summonShieldPrefabs = SummonShieldPrefabs;
			foreach (string text in summonShieldPrefabs)
			{
				string text2 = text + " Appearance";
				ConfigEntry<string> val = PluginConfig.Bind<string>("Shield Replacements", text2, "Default", "Previous location for this shield appearance.");
				string text3 = val.Value;
				if (Array.IndexOf(options, text3) < 0)
				{
					LogSource.LogWarning((object)("Previous shield appearance '" + text3 + "' is unavailable; using Default."));
					text3 = "Default";
				}
				ShieldAppearances.Add(text, BindPrefabChoice(text2, text3, "Appearance for summons carrying " + text + "; Default keeps the original shield. This does not change combat or add shields to summons.", options, "Equipment"));
				PluginConfig.Remove(((ConfigEntryBase)val).Definition);
			}
			PluginConfig.Save();
			if (options.Length == 1)
			{
				LogSource.LogWarning((object)"No usable shield appearances were found in the item database.");
			}
		}

		private static void AddSynchronizedConfigEntry<T>(ConfigEntry<T> configEntry)
		{
			ServerConfigSync.AddConfigEntry<T>(configEntry).SynchronizedConfig = true;
		}

		private static ConfigEntry<string> BindPrefabChoice(string key, string defaultValue, string description, string[] options, string section = "Appearance")
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			ConfigEntry<string> obj = PluginConfig.Bind<string>(section, key, defaultValue, new ConfigDescription(description, (AcceptableValueBase)(object)new AcceptableValueList<string>(options), Array.Empty<object>()));
			AddSynchronizedConfigEntry<string>(obj);
			return obj;
		}

		private static string[] GetPrefabOptions(ObjectDB objectDatabase, PrefabChoice choice, string defaultValue)
		{
			HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
			bool flag = (uint)choice <= 1u;
			AddPrefabOptions(objectDatabase.m_items, hashSet, choice);
			GameObject itemPrefab = objectDatabase.GetItemPrefab(defaultValue);
			ItemDrop val = ((itemPrefab != null) ? itemPrefab.GetComponent<ItemDrop>() : null);
			if (!string.Equals(defaultValue, "None", StringComparison.OrdinalIgnoreCase) && (Object)(object)val != (Object)null)
			{
				hashSet.Add(defaultValue);
			}
			List<string> list = new List<string>(hashSet);
			if (flag)
			{
				list.Remove(defaultValue);
			}
			list.Sort(StringComparer.OrdinalIgnoreCase);
			if (flag)
			{
				if (hashSet.Contains(defaultValue))
				{
					list.Insert(0, defaultValue);
				}
			}
			else
			{
				list.Insert(0, "None");
			}
			if (list.Count == 0)
			{
				LogSource.LogWarning((object)$"No {choice} prefabs were found in the loaded prefab registry.");
			}
			return list.ToArray();
		}

		private static string[] GetMeleeWeaponOptions(ObjectDB objectDatabase)
		{
			HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
			foreach (Recipe recipe in objectDatabase.m_recipes)
			{
				ItemDrop val = recipe?.m_item;
				if (!((Object)(object)val == (Object)null) && !IsExcludedPrefab(((Object)((Component)val).gameObject).name))
				{
					GameObject itemPrefab = objectDatabase.GetItemPrefab(((Object)((Component)val).gameObject).name);
					if ((Object)(object)itemPrefab != (Object)null && IsMeleeWeaponPrefab(itemPrefab))
					{
						hashSet.Add(((Object)itemPrefab).name);
					}
				}
			}
			GameObject itemPrefab2 = objectDatabase.GetItemPrefab("AxeBronze");
			if ((Object)(object)itemPrefab2 != (Object)null && IsMeleeWeaponPrefab(itemPrefab2))
			{
				hashSet.Add(((Object)itemPrefab2).name);
			}
			GameObject itemPrefab3 = objectDatabase.GetItemPrefab("Tankard_dvergr");
			if ((Object)(object)itemPrefab3 != (Object)null && (Object)(object)itemPrefab3.GetComponent<ItemDrop>() != (Object)null)
			{
				hashSet.Add(((Object)itemPrefab3).name);
			}
			else
			{
				LogSource.LogWarning((object)"Tankard_dvergr is unavailable in the item database; its appearance cannot be selected.");
			}
			List<string> list = new List<string>(hashSet);
			list.Sort(StringComparer.OrdinalIgnoreCase);
			list.Insert(0, "Default");
			if (list.Count == 1)
			{
				LogSource.LogWarning((object)"No melee weapon appearances were found in the item database.");
			}
			return list.ToArray();
		}

		private static bool IsMeleeWeaponPrefab(GameObject? prefab)
		{
			return IsMeleeWeaponData((prefab == null) ? null : prefab.GetComponent<ItemDrop>()?.m_itemData?.m_shared);
		}

		private static bool IsMeleeWeaponData(SharedData? data)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Invalid comparison between Unknown and I4
			Attack val = data?.m_attack;
			if (data != null && (int)data.m_itemType == 3 && val != null && !string.IsNullOrWhiteSpace(val.m_attackAnimation))
			{
				return (Object)(object)val.m_attackProjectile == (Object)null;
			}
			return false;
		}

		private static string[] GetBowOptions(ObjectDB objectDatabase)
		{
			HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
			foreach (GameObject item in objectDatabase.m_items)
			{
				if ((Object)(object)item != (Object)null && ((Object)item).name.StartsWith("Bow", StringComparison.OrdinalIgnoreCase))
				{
					AddBowOption(item, hashSet);
				}
			}
			foreach (Recipe recipe in objectDatabase.m_recipes)
			{
				ItemDrop val = recipe?.m_item;
				if ((Object)(object)val != (Object)null)
				{
					AddBowOption(objectDatabase.GetItemPrefab(((Object)((Component)val).gameObject).name), hashSet);
				}
			}
			List<string> list = new List<string>(hashSet);
			list.Sort(StringComparer.OrdinalIgnoreCase);
			list.Insert(0, "Default");
			if (list.Count == 1)
			{
				LogSource.LogWarning((object)"No player bow appearances were found in the item database.");
			}
			return list.ToArray();
		}

		private static void AddBowOption(GameObject? prefab, HashSet<string> prefabNames)
		{
			if (!((Object)(object)prefab == (Object)null) && !IsExcludedPrefab(((Object)prefab).name) && IsPlayerBowData(prefab.GetComponent<ItemDrop>()?.m_itemData?.m_shared))
			{
				prefabNames.Add(((Object)prefab).name);
			}
		}

		private static bool IsPlayerBowData(SharedData? data)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Invalid comparison between Unknown and I4
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Invalid comparison between Unknown and I4
			if (data != null && (int)data.m_itemType == 4 && (int)data.m_skillType == 8 && data.m_attack != null)
			{
				return !string.IsNullOrWhiteSpace(data.m_attack.m_attackAnimation);
			}
			return false;
		}

		private static void AddPrefabOptions(IEnumerable<GameObject> prefabs, HashSet<string> prefabNames, PrefabChoice choice)
		{
			foreach (GameObject prefab in prefabs)
			{
				if (!((Object)(object)prefab == (Object)null) && !IsExcludedPrefab(((Object)prefab).name) && (choice != PrefabChoice.Shield || !IsExcludedShieldPrefab(((Object)prefab).name)) && !string.Equals(((Object)prefab).name, "None", StringComparison.OrdinalIgnoreCase))
				{
					string text = ((object)Unsafe.As<ItemType, ItemType>(ref prefab.GetComponent<ItemDrop>()?.m_itemData?.m_shared?.m_itemType)/*cast due to .constrained prefix*/).ToString() ?? string.Empty;
					if (choice switch
					{
						PrefabChoice.Hair => ((Object)prefab).name.StartsWith("Hair", StringComparison.Ordinal), 
						PrefabChoice.Beard => ((Object)prefab).name.StartsWith("Beard", StringComparison.Ordinal), 
						PrefabChoice.Helmet => text == "Helmet", 
						PrefabChoice.Chest => text == "Chest", 
						PrefabChoice.Legs => text == "Legs", 
						PrefabChoice.Cape => text == "Shoulder", 
						PrefabChoice.Shield => text == "Shield", 
						_ => false, 
					})
					{
						prefabNames.Add(((Object)prefab).name);
					}
				}
			}
		}

		private static bool IsExcludedShieldPrefab(string prefabName)
		{
			if (!string.Equals(prefabName, "Axe1h_JotunWarrior 1", StringComparison.OrdinalIgnoreCase))
			{
				return string.Equals(prefabName, "Axe1h_JotunWarrior1", StringComparison.OrdinalIgnoreCase);
			}
			return true;
		}

		private static bool IsExcludedPrefab(string prefabName)
		{
			string[] excludedPrefabPrefixes = ExcludedPrefabPrefixes;
			foreach (string value in excludedPrefabPrefixes)
			{
				if (prefabName.StartsWith(value, StringComparison.OrdinalIgnoreCase))
				{
					return true;
				}
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(ZNetScene), "Awake")]
	internal static class RegisterSummonNpcPatch
	{
		private const string SourceSummonPrefabName = "Skeleton_Friendly";

		private const string StaffPrefabName = "StaffSkeleton";

		private const string PlayerPrefabName = "Player";

		private static GameObject? _cloneContainer;

		private static ZNetScene? _registeredScene;

		private static bool _registrationComplete;

		private static bool _waitingForServerConfigLogged;

		private static void Postfix(ZNetScene __instance)
		{
			SummonNpcPlugin.TryBindAppearanceConfig();
			if (!SummonNpcPlugin.ServerConfigSync.InitialSyncDone)
			{
				if (!_waitingForServerConfigLogged)
				{
					SummonNpcPlugin.LogSource.LogInfo((object)"Waiting for the server configuration sync before registering the custom summon.");
					_waitingForServerConfigLogged = true;
				}
			}
			else
			{
				TryRegister(__instance);
			}
		}

		internal static void TryRegister(ZNetScene scene)
		{
			if (_registeredScene == scene && _registrationComplete)
			{
				return;
			}
			_registrationComplete = false;
			if (!SummonNpcPlugin.EnableMod.Value)
			{
				SummonNpcPlugin.LogSource.LogInfo((object)"SummonNPC is disabled by the server configuration; vanilla summon behavior is unchanged.");
				_registeredScene = scene;
				_registrationComplete = true;
				return;
			}
			GameObject prefab = scene.GetPrefab("Skeleton_Friendly");
			GameObject prefab2 = scene.GetPrefab("Player");
			GameObject prefab3 = scene.GetPrefab("StaffSkeleton");
			if ((Object)(object)prefab == (Object)null || (Object)(object)prefab2 == (Object)null || (Object)(object)prefab3 == (Object)null)
			{
				SummonNpcPlugin.LogSource.LogWarning((object)"Could not find the vanilla Player, StaffSkeleton, or Skeleton_Friendly prefab; the Dead Raiser is unchanged.");
				return;
			}
			GameObject val = scene.GetPrefab(SummonNpcPlugin.SummonPrefabName);
			if ((Object)(object)val == (Object)null)
			{
				int bodyModelIndex = (string.Equals(SummonNpcPlugin.BodyType.Value, "Female", StringComparison.OrdinalIgnoreCase) ? 1 : 0);
				val = CreateSummonPrefab(prefab, prefab2, bodyModelIndex);
				if ((Object)(object)val == (Object)null)
				{
					return;
				}
				if (!RegisterPrefab(scene, val))
				{
					Object.Destroy((Object)(object)val);
					return;
				}
			}
			GameObject val2 = prefab3.GetComponent<ItemDrop>()?.m_itemData?.m_shared?.m_attack?.m_attackProjectile;
			SpawnAbility val3 = (((Object)(object)val2 != (Object)null) ? val2.GetComponent<SpawnAbility>() : null);
			if ((Object)(object)val3 == (Object)null || val3.m_spawnPrefab == null)
			{
				SummonNpcPlugin.LogSource.LogWarning((object)"Could not find the Dead Raiser SpawnAbility; the Dead Raiser is unchanged.");
				return;
			}
			bool flag = false;
			GameObject[] array = (GameObject[])val3.m_spawnPrefab.Clone();
			for (int i = 0; i < array.Length; i++)
			{
				if (!((Object)(object)array[i] == (Object)null) && !(((Object)array[i]).name != "Skeleton_Friendly"))
				{
					array[i] = val;
					flag = true;
				}
			}
			if (!flag)
			{
				SummonNpcPlugin.LogSource.LogWarning((object)"The Dead Raiser no longer references Skeleton_Friendly; leaving its spawn unchanged.");
				return;
			}
			val3.m_spawnPrefab = array;
			SummonNpcPlugin.LogSource.LogInfo((object)"Dead Raiser now spawns the configured custom summon with vanilla friendly-skeleton behavior.");
			_registeredScene = scene;
			_registrationComplete = true;
		}

		private static GameObject? CreateSummonPrefab(GameObject sourceSummon, GameObject playerPrefab, int bodyModelIndex)
		{
			//IL_036a: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ea: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)sourceSummon.GetComponent<VisEquipment>()?.m_bodyModel == (Object)null)
			{
				SummonNpcPlugin.LogSource.LogWarning((object)"Could not find the vanilla summon body model; the Dead Raiser is unchanged.");
				return null;
			}
			Transform cloneContainer = GetCloneContainer();
			GameObject val = Object.Instantiate<GameObject>(sourceSummon, cloneContainer);
			((Object)val).name = SummonNpcPlugin.SummonPrefabName;
			SummonNpcMarker summonNpcMarker = val.AddComponent<SummonNpcMarker>();
			Character component = val.GetComponent<Character>();
			VisEquipment component2 = val.GetComponent<VisEquipment>();
			if ((Object)(object)component == (Object)null || (Object)(object)component2?.m_bodyModel == (Object)null)
			{
				Object.Destroy((Object)(object)val);
				SummonNpcPlugin.LogSource.LogWarning((object)"The friendly skeleton prefab is missing its Character or VisEquipment component; the Dead Raiser is unchanged.");
				return null;
			}
			component.m_name = "NPC";
			if (SummonNpcPlugin.UsesSkeletonBody)
			{
				VisEquipment component3 = playerPrefab.GetComponent<VisEquipment>();
				summonNpcMarker.PlayerHelmetMount = CreatePlayerHelmetMount(component3, component2);
				summonNpcMarker.ChestOverlay = SkeletonChestOverlay.Create(component3, component2);
				if (SummonNpcPlugin.DebugLogging.Value)
				{
					SummonNpcPlugin.LogSource.LogInfo((object)"Using the vanilla skeleton body and equipment mounts for the summoned NPC.");
				}
				return val;
			}
			VisEquipment component4 = playerPrefab.GetComponent<VisEquipment>();
			if ((Object)(object)component4?.m_bodyModel == (Object)null || component4.m_models == null || component4.m_models.Length <= bodyModelIndex || (Object)(object)component4.m_models[bodyModelIndex].m_mesh == (Object)null || (Object)(object)component4.m_bodyModel.rootBone == (Object)null || ((Renderer)component4.m_bodyModel).sharedMaterials.Length == 0)
			{
				Object.Destroy((Object)(object)val);
				SummonNpcPlugin.LogSource.LogWarning((object)"Could not find the player and summon body models; the Dead Raiser is unchanged.");
				return null;
			}
			SkinnedMeshRenderer bodyModel = component4.m_bodyModel;
			PlayerModel val2 = component4.m_models[bodyModelIndex];
			Mesh mesh = val2.m_mesh;
			Material[] bodyMaterials = GetBodyMaterials(bodyModel, val2, bodyModelIndex, mesh.subMeshCount);
			if (bodyModel.bones.Length != mesh.bindposes.Length || bodyMaterials.Length != mesh.subMeshCount)
			{
				Object.Destroy((Object)(object)val);
				SummonNpcPlugin.LogSource.LogWarning((object)("The " + SummonNpcPlugin.BodyType.Value + " body mesh is incompatible with the player rig " + $"(bones={bodyModel.bones.Length}, bind poses={mesh.bindposes.Length}, " + $"materials={bodyMaterials.Length}, submeshes={mesh.subMeshCount}); " + "the Dead Raiser is unchanged."));
				return null;
			}
			Transform[] bones = bodyModel.bones;
			if (bones.Length == 0)
			{
				Object.Destroy((Object)(object)val);
				SummonNpcPlugin.LogSource.LogWarning((object)"The player body model has no animation bones; the Dead Raiser is unchanged.");
				return null;
			}
			SummonAppearance.CopyDefaultHairColor(component4, component2);
			Transform val3 = FindMatchingBone(bodyModel.rootBone, component2.m_bodyModel.rootBone, bodyModel.rootBone);
			if ((Object)(object)val3 == (Object)null)
			{
				Object.Destroy((Object)(object)val);
				SummonNpcPlugin.LogSource.LogWarning((object)"Could not match the player and cloned-skeleton animation rigs; the Dead Raiser is unchanged.");
				return null;
			}
			Transform[] array = (Transform[])(object)new Transform[bones.Length];
			for (int i = 0; i < bones.Length; i++)
			{
				Transform val4 = FindMatchingBone(bodyModel.rootBone, component2.m_bodyModel.rootBone, bones[i]);
				if ((Object)(object)val4 == (Object)null)
				{
					Object.Destroy((Object)(object)val);
					ManualLogSource logSource = SummonNpcPlugin.LogSource;
					Transform obj = bones[i];
					logSource.LogWarning((object)("Could not map player bone '" + ((obj != null) ? ((Object)obj).name : null) + "' to the cloned skeleton; the Dead Raiser is unchanged."));
					return null;
				}
				array[i] = val4;
			}
			SkinnedMeshRenderer bodyModel2 = component2.m_bodyModel;
			bodyModel2.sharedMesh = mesh;
			((Renderer)bodyModel2).sharedMaterials = bodyMaterials;
			bodyModel2.rootBone = val3;
			bodyModel2.bones = array;
			((Renderer)bodyModel2).localBounds = ((Renderer)bodyModel).localBounds;
			bodyModel2.updateWhenOffscreen = true;
			((Renderer)bodyModel2).enabled = true;
			Transform val5 = CreatePlayerHelmetMount(component4, component2);
			if ((Object)(object)val5 != (Object)null)
			{
				component2.m_helmet = val5;
			}
			if (SummonNpcPlugin.DebugLogging.Value)
			{
				SummonNpcPlugin.LogSource.LogInfo((object)$"Configured {SummonNpcPlugin.BodyType.Value} summon body mesh '{((Object)bodyModel2.sharedMesh).name}' with {array.Length} cloned bones and bounds {((Renderer)bodyModel2).localBounds}.");
			}
			return val;
		}

		private static Transform? CreatePlayerHelmetMount(VisEquipment? playerVisuals, VisEquipment cloneVisuals)
		{
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			Transform val = playerVisuals?.m_helmet;
			object obj;
			if (playerVisuals == null)
			{
				obj = null;
			}
			else
			{
				SkinnedMeshRenderer bodyModel = playerVisuals.m_bodyModel;
				obj = ((bodyModel != null) ? bodyModel.rootBone : null);
			}
			Transform sourceRoot = (Transform)obj;
			SkinnedMeshRenderer bodyModel2 = cloneVisuals.m_bodyModel;
			Transform targetRoot = ((bodyModel2 != null) ? bodyModel2.rootBone : null);
			Transform val2 = (((Object)(object)val != (Object)null) ? FindMatchingBone(sourceRoot, targetRoot, val.parent) : null);
			if ((Object)(object)val2 == (Object)null || (Object)(object)val == (Object)null)
			{
				SummonNpcPlugin.LogSource.LogWarning((object)"Could not map the player's helmet mount to the cloned skeleton rig; keeping the skeleton's helmet mount.");
				return null;
			}
			Transform transform = new GameObject("SummonNPC_SummonHelmetMount").transform;
			transform.SetParent(val2, false);
			transform.localPosition = val.localPosition;
			transform.localRotation = val.localRotation;
			transform.localScale = val.localScale;
			if (SummonNpcPlugin.DebugLogging.Value)
			{
				SummonNpcPlugin.LogSource.LogInfo((object)("Created the summon helmet attachment from the player mount offset at '" + ((Object)val2).name + "'."));
			}
			return transform;
		}

		private static Material[] GetBodyMaterials(SkinnedMeshRenderer sourceBody, PlayerModel playerModel, int bodyModelIndex, int subMeshCount)
		{
			Material[] sharedMaterials = ((Renderer)sourceBody).sharedMaterials;
			if (bodyModelIndex == 0 && sharedMaterials.Length == subMeshCount)
			{
				return sharedMaterials;
			}
			Material val = playerModel.m_baseMaterial;
			if ((Object)(object)val == (Object)null && sharedMaterials.Length != 0)
			{
				val = sharedMaterials[0];
			}
			if ((Object)(object)val == (Object)null)
			{
				return Array.Empty<Material>();
			}
			Material[] array = (Material[])(object)new Material[subMeshCount];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = val;
			}
			return array;
		}

		private static Transform GetCloneContainer()
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			if ((Object)(object)_cloneContainer != (Object)null)
			{
				return _cloneContainer.transform;
			}
			GameObject val = new GameObject("SummonNPC_ClonedPrefabs");
			val.SetActive(false);
			Object.DontDestroyOnLoad((Object)val);
			_cloneContainer = val;
			return val.transform;
		}

		internal static Transform? FindMatchingBone(Transform? sourceRoot, Transform? targetRoot, Transform? sourceBone)
		{
			if ((Object)(object)sourceRoot == (Object)null || (Object)(object)targetRoot == (Object)null || (Object)(object)sourceBone == (Object)null)
			{
				return null;
			}
			if ((Object)(object)sourceBone == (Object)(object)sourceRoot)
			{
				return targetRoot;
			}
			List<string> list = new List<string>();
			Transform val = sourceBone;
			while ((Object)(object)val != (Object)null && (Object)(object)val != (Object)(object)sourceRoot)
			{
				list.Add(((Object)val).name);
				val = val.parent;
			}
			if ((Object)(object)val != (Object)(object)sourceRoot)
			{
				return null;
			}
			Transform val2 = targetRoot;
			for (int num = list.Count - 1; num >= 0; num--)
			{
				val2 = ((val2 != null) ? val2.Find(list[num]) : null);
				if ((Object)(object)val2 == (Object)null)
				{
					return null;
				}
			}
			return val2;
		}

		private static bool RegisterPrefab(ZNetScene scene, GameObject prefab)
		{
			if (!(AccessTools.Field(typeof(ZNetScene), "m_namedPrefabs")?.GetValue(scene) is IDictionary dictionary))
			{
				SummonNpcPlugin.LogSource.LogWarning((object)"Could not access the prefab hash registry; the Dead Raiser is unchanged.");
				return false;
			}
			int prefabHash = scene.GetPrefabHash(prefab);
			if (prefabHash == 0)
			{
				SummonNpcPlugin.LogSource.LogWarning((object)"Could not calculate the custom summon prefab hash; the Dead Raiser is unchanged.");
				return false;
			}
			if (!scene.m_prefabs.Contains(prefab))
			{
				scene.m_prefabs.Add(prefab);
			}
			dictionary[prefabHash] = prefab;
			return true;
		}
	}
	internal sealed class SummonNpcMarker : MonoBehaviour
	{
		public Transform? PlayerHelmetMount;

		public SkeletonChestOverlay? ChestOverlay;
	}
	[HarmonyPatch(typeof(VisEquipment), "SetRightHandEquipped")]
	internal static class SummonMeleeWeaponAppearancePatch
	{
		private static void Prefix(VisEquipment __instance, ref int hash)
		{
			if (SummonAppearance.IsSummon(((Component)__instance).gameObject) && !string.Equals(SummonNpcPlugin.MeleeWeapon.Value, "Default", StringComparison.OrdinalIgnoreCase) && SummonAppearance.TryGetPrefabHash("skeleton_sword2", out var hash2) && hash == hash2 && SummonAppearance.TryGetPrefabHash(SummonNpcPlugin.MeleeWeapon.Value, out var hash3))
			{
				hash = hash3;
			}
		}
	}
	[HarmonyPatch(typeof(VisEquipment), "SetLeftHandEquipped")]
	internal static class SummonLeftHandAppearancePatch
	{
		private static void Prefix(VisEquipment __instance, ref int hash, ref int variant)
		{
			if (!SummonAppearance.IsSummon(((Component)__instance).gameObject) || hash == 0)
			{
				return;
			}
			ObjectDB instance = ObjectDB.instance;
			GameObject val = ((instance != null) ? instance.GetItemPrefab(hash) : null);
			if (!((Object)(object)val == (Object)null))
			{
				ConfigEntry<string> value;
				if (string.Equals(((Object)val).name, "skeleton_bow2", StringComparison.Ordinal))
				{
					value = SummonNpcPlugin.BowPrefab;
				}
				else if (!SummonNpcPlugin.ShieldAppearances.TryGetValue(((Object)val).name, out value))
				{
					return;
				}
				if (!string.Equals(value.Value, "Default", StringComparison.OrdinalIgnoreCase) && SummonAppearance.TryGetPrefabHash(value.Value, out var hash2) && hash2 != hash)
				{
					hash = hash2;
					variant = 0;
				}
			}
		}
	}
	internal static class SummonAppearance
	{
		private const string AssignedNpcNameZdoKey = "SummonNPC_NpcName";

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

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

		private static readonly FieldInfo? HairItemField = AccessTools.Field(typeof(VisEquipment), "m_hairItem");

		private static readonly FieldInfo? BeardItemField = AccessTools.Field(typeof(VisEquipment), "m_beardItem");

		private static readonly FieldInfo? HelmetHideHairField = AccessTools.Field(typeof(VisEquipment), "m_helmetHideHair");

		private static readonly FieldInfo? HelmetHideBeardField = AccessTools.Field(typeof(VisEquipment), "m_helmetHideBeard");

		private static readonly MethodInfo? HairEquippedMethod = AccessTools.Method(typeof(VisEquipment), "SetHairEquipped", (Type[])null, (Type[])null);

		private static readonly MethodInfo? BeardEquippedMethod = AccessTools.Method(typeof(VisEquipment), "SetBeardEquipped", (Type[])null, (Type[])null);

		private static readonly MethodInfo? HairItemSelectionMethod = AccessTools.Method(typeof(VisEquipment), "GetHairItem", (Type[])null, (Type[])null);

		private static readonly Type? AccessoryType = typeof(VisEquipment).Assembly.GetType("ItemDrop+ItemData+AccessoryType");

		private static readonly object? HairAccessoryType = GetAccessoryType("Hair");

		private static readonly object? BeardAccessoryType = GetAccessoryType("Beard");

		private static bool _emptyNamesWarningLogged;

		private static bool _invalidHairColorWarningLogged;

		private static bool _invalidSkinColorWarningLogged;

		private static bool _missingHairItemFieldWarningLogged;

		private static bool _missingBeardItemFieldWarningLogged;

		private static bool _missingHairEquippedMethodWarningLogged;

		private static bool _missingBeardEquippedMethodWarningLogged;

		private static bool _missingHelmetHairSettingsWarningLogged;

		internal static bool IsSummon(GameObject gameObject)
		{
			if (!((Object)(object)gameObject.GetComponent<SummonNpcMarker>() != (Object)null))
			{
				return ((Object)gameObject).name.StartsWith(SummonNpcPlugin.SummonPrefabName, StringComparison.Ordinal);
			}
			return true;
		}

		internal static void InitializeAssignedName(Tameable tameable)
		{
			TryGetAssignedName(tameable);
		}

		internal static string GetAssignedName(Tameable tameable, string fallback)
		{
			return TryGetAssignedName(tameable) ?? fallback;
		}

		private static string? TryGetAssignedName(Tameable tameable)
		{
			ZNetView component = ((Component)tameable).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				return null;
			}
			ZDO zDO = component.GetZDO();
			if (zDO == null)
			{
				return null;
			}
			string text = zDO.GetString("SummonNPC_NpcName", string.Empty);
			if (string.IsNullOrWhiteSpace(text) && component.IsOwner())
			{
				text = SelectNpcName();
				zDO.Set("SummonNPC_NpcName", text);
			}
			if (!string.IsNullOrWhiteSpace(text) && component.IsOwner() && !string.Equals(zDO.GetString(ZDOVars.s_tamedName, string.Empty), text, StringComparison.Ordinal))
			{
				zDO.Set(ZDOVars.s_tamedName, text);
			}
			if (string.IsNullOrWhiteSpace(text))
			{
				return null;
			}
			return text;
		}

		internal static void CopyDefaultHairColor(VisEquipment source, VisEquipment target)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			if (AccessTools.Field(typeof(VisEquipment), "m_hairColor")?.GetValue(source) is Vector3 hairColor)
			{
				target.SetHairColor(hairColor);
			}
			else
			{
				SummonNpcPlugin.LogSource.LogWarning((object)"Could not read the vanilla default hair color; the summon will keep its current hair color.");
			}
		}

		internal static bool TryGetConfiguredPrefabHash(string prefabName, out int hash)
		{
			if (IsNone(prefabName))
			{
				hash = 0;
				return true;
			}
			return TryGetPrefabHash(prefabName.Trim(), out hash);
		}

		internal static bool IsNone(string prefabName)
		{
			if (!string.IsNullOrWhiteSpace(prefabName))
			{
				return string.Equals(prefabName.Trim(), "None", StringComparison.OrdinalIgnoreCase);
			}
			return true;
		}

		internal static bool CanApplyConfiguredPrefab(string prefabName)
		{
			int hash;
			if (!IsNone(prefabName))
			{
				return TryGetConfiguredPrefabHash(prefabName, out hash);
			}
			return false;
		}

		internal static void PrepareConfiguredHairAndBeard(VisEquipment visuals)
		{
			if (TryGetConfiguredPrefabHash(SummonNpcPlugin.HairPrefab.Value, out var hash))
			{
				if (HairItemField != null)
				{
					HairItemField.SetValue(visuals, hash);
				}
				else if (!_missingHairItemFieldWarningLogged)
				{
					SummonNpcPlugin.LogSource.LogWarning((object)"Could not access VisEquipment.m_hairItem; configured hair may not be applied.");
					_missingHairItemFieldWarningLogged = true;
				}
			}
			if (TryGetConfiguredPrefabHash(SummonNpcPlugin.BeardPrefab.Value, out var hash2))
			{
				if (BeardItemField != null)
				{
					BeardItemField.SetValue(visuals, hash2);
				}
				else if (!_missingBeardItemFieldWarningLogged)
				{
					SummonNpcPlugin.LogSource.LogWarning((object)"Could not access VisEquipment.m_beardItem; configured beard may not be applied.");
					_missingBeardItemFieldWarningLogged = true;
				}
			}
		}

		internal static void ApplyConfiguredHairAndBeard(VisEquipment visuals)
		{
			PrepareConfiguredHairAndBeard(visuals);
			if (TryGetConfiguredPrefabHash(SummonNpcPlugin.HairPrefab.Value, out var hash))
			{
				if (HairEquippedMethod != null)
				{
					object obj = HairEquippedMethod.Invoke(visuals, new object[1] { hash });
					if (obj is bool && (bool)obj && SummonNpcPlugin.DebugLogging.Value)
					{
						SummonNpcPlugin.LogSource.LogInfo((object)("Applied hair prefab '" + SummonNpcPlugin.HairPrefab.Value + "'."));
					}
				}
				else if (!_missingHairEquippedMethodWarningLogged)
				{
					SummonNpcPlugin.LogSource.LogWarning((object)"Could not access VisEquipment.SetHairEquipped; configured hair may not be applied.");
					_missingHairEquippedMethodWarningLogged = true;
				}
			}
			if (!TryGetConfiguredPrefabHash(SummonNpcPlugin.BeardPrefab.Value, out var hash2))
			{
				return;
			}
			if (BeardEquippedMethod != null)
			{
				object obj = BeardEquippedMethod.Invoke(visuals, new object[1] { hash2 });
				if (obj is bool && (bool)obj && SummonNpcPlugin.DebugLogging.Value)
				{
					SummonNpcPlugin.LogSource.LogInfo((object)("Applied beard prefab '" + SummonNpcPlugin.BeardPrefab.Value + "'."));
				}
			}
			else if (!_missingBeardEquippedMethodWarningLogged)
			{
				SummonNpcPlugin.LogSource.LogWarning((object)"Could not access VisEquipment.SetBeardEquipped; configured beard may not be applied.");
				_missingBeardEquippedMethodWarningLogged = true;
			}
		}

		internal static int GetHelmetAdjustedAccessoryHash(VisEquipment visuals, int configuredHash, bool beard)
		{
			FieldInfo fieldInfo = (beard ? HelmetHideBeardField : HelmetHideHairField);
			object obj = (beard ? BeardAccessoryType : HairAccessoryType);
			if (HairItemSelectionMethod == null || fieldInfo == null || obj == null)
			{
				if (!_missingHelmetHairSettingsWarningLogged)
				{
					SummonNpcPlugin.LogSource.LogWarning((object)"Could not access Valheim's helmet hair settings; configured hair or beard may clip through helmets.");
					_missingHelmetHairSettingsWarningLogged = true;
				}
				return configuredHash;
			}
			object value = fieldInfo.GetValue(visuals);
			object obj2 = HairItemSelectionMethod.Invoke(visuals, new object[3] { value, configuredHash, obj });
			if (obj2 is int)
			{
				return (int)obj2;
			}
			throw new InvalidOperationException("Valheim's GetHairItem method did not return an accessory prefab hash.");
		}

		internal static void ApplyConfiguredHairColor(VisEquipment visuals)
		{
			//IL_000a: 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_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			if (TryGetConfiguredHairColor(out var color))
			{
				visuals.SetHairColor(new Vector3(color.r, color.g, color.b));
			}
		}

		internal static bool TryGetPrefabHash(string prefabName, out int hash)
		{
			if (PrefabHashes.TryGetValue(prefabName, out hash))
			{
				return true;
			}
			ZNetScene instance = ZNetScene.instance;
			ObjectDB instance2 = ObjectDB.instance;
			GameObject val = ((instance2 != null) ? instance2.GetItemPrefab(prefabName) : null) ?? ((instance != null) ? instance.GetPrefab(prefabName) : null);
			if ((Object)(object)instance == (Object)null || (Object)(object)val == (Object)null)
			{
				WarnMissingPrefab(prefabName);
				hash = 0;
				return false;
			}
			hash = instance.GetPrefabHash(val);
			if (hash == 0)
			{
				WarnMissingPrefab(prefabName);
				return false;
			}
			PrefabHashes[prefabName] = hash;
			if (SummonNpcPlugin.DebugLogging.Value)
			{
				SummonNpcPlugin.LogSource.LogInfo((object)("Using '" + prefabName + "' for summon appearance."));
			}
			return true;
		}

		private static string SelectNpcName()
		{
			List<string> list = new List<string>();
			string[] array = SummonNpcPlugin.NpcNames.Value.Split(',');
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length > 0)
				{
					list.Add(text);
				}
			}
			if (list.Count == 0)
			{
				if (!_emptyNamesWarningLogged)
				{
					SummonNpcPlugin.LogSource.LogWarning((object)"NPC Names contains no usable names; using 'NPC' instead.");
					_emptyNamesWarningLogged = true;
				}
				return "NPC";
			}
			return list[Random.Range(0, list.Count)];
		}

		private static bool TryGetConfiguredHairColor(out Color color)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			string text = SummonNpcPlugin.HairColor.Value.Trim();
			if (string.Equals(text, "Default", StringComparison.OrdinalIgnoreCase))
			{
				color = default(Color);
				return false;
			}
			if (TryParseHexColor(text, out color))
			{
				return true;
			}
			if (!_invalidHairColorWarningLogged)
			{
				SummonNpcPlugin.LogSource.LogWarning((object)("Invalid Hair Color '" + text + "'; use 'Default' or a hex value such as #AABBCC."));
				_invalidHairColorWarningLogged = true;
			}
			color = default(Color);
			return false;
		}

		internal static Color GetConfiguredSkinColor()
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			string text = SummonNpcPlugin.SkinColor.Value.Trim();
			if (TryParseHexColor(text, out var color))
			{
				return color;
			}
			if (!_invalidSkinColorWarningLogged)
			{
				SummonNpcPlugin.LogSource.LogWarning((object)("Invalid Skin Color '" + text + "'; use a hex value such as #A6A6A6. Keeping the default skin tone."));
				_invalidSkinColorWarningLogged = true;
			}
			return new Color(0.65f, 0.65f, 0.65f, 1f);
		}

		private static bool TryParseHexColor(string value, out Color color)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			if ((value.Length == 7 || value.Length == 9) && value[0] == '#' && ColorUtility.TryParseHtmlString(value, ref color))
			{
				return true;
			}
			color = default(Color);
			return false;
		}

		private static object? GetAccessoryType(string name)
		{
			if (!(AccessoryType != null) || !Enum.IsDefined(AccessoryType, name))
			{
				return null;
			}
			return Enum.Parse(AccessoryType, name);
		}

		private static void WarnMissingPrefab(string prefabName)
		{
			if (MissingPrefabWarnings.Add(prefabName))
			{
				SummonNpcPlugin.LogSource.LogWarning((object)("Could not resolve appearance prefab '" + prefabName + "'; leaving that visual unchanged."));
			}
		}
	}
	[HarmonyPatch(typeof(VisEquipment), "SetChestEquipped")]
	internal static class ApplySummonChestArmorPatch
	{
		private static void Prefix(VisEquipment __instance, ref int hash)
		{
			if (SummonAppearance.IsSummon(((Component)__instance).gameObject) && SummonAppearance.TryGetConfiguredPrefabHash(SummonNpcPlugin.ChestPrefab.Value, out var hash2))
			{
				hash = hash2;
			}
		}

		private static void Postfix(VisEquipment __instance, int hash, bool __result)
		{
			if (__result && SummonNpcPlugin.UsesSkeletonBody && SummonAppearance.IsSummon(((Component)__instance).gameObject))
			{
				((Component)__instance).GetComponent<SummonNpcMarker>()?.ChestOverlay?.ApplyArmor(hash);
			}
		}
	}
	internal sealed class SkeletonChestOverlay : MonoBehaviour
	{
		private static readonly HashSet<string> OverlayChestPrefabs = new HashSet<string>(StringComparer.Ordinal)
		{
			"ArmorBronzeChest", "ArmorLeatherChest", "ArmorPaddedCuirass", "ArmorRagsChest", "ArmorTrollLeatherChest", "ArmorDress1", "ArmorDress2", "ArmorDress3", "ArmorDress4", "ArmorDress5",
			"ArmorDress6", "ArmorDress7", "ArmorDress8", "ArmorDress9", "ArmorDress10"
		};

		private static readonly int ChestTexture = Shader.PropertyToID("_ChestTex");

		private static readonly int ChestBump = Shader.PropertyToID("_ChestBumpMap");

		[SerializeField]
		private Shader? _shader;

		private Material? _material;

		internal static SkeletonChestOverlay? Create(VisEquipment? player, VisEquipment skeleton)
		{
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: Unknown result type (might be due to invalid IL or missing references)
			//IL_023e: Unknown result type (might be due to invalid IL or missing references)
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0258: Unknown result type (might be due to invalid IL or missing references)
			//IL_027c: Unknown result type (might be due to invalid IL or missing references)
			SkinnedMeshRenderer val = player?.m_bodyModel;
			SkinnedMeshRenderer bodyModel = skeleton.m_bodyModel;
			if ((Object)(object)val == (Object)null || (Object)(object)bodyModel == (Object)null || player?.m_models == null || player.m_models.Length == 0 || (Object)(object)player.m_models[0].m_mesh == (Object)null)
			{
				SummonNpcPlugin.LogSource.LogWarning((object)"Cannot create skeleton chest overlay: body data is unavailable.");
				return null;
			}
			Mesh mesh = player.m_models[0].m_mesh;
			Transform[] bones = val.bones;
			if (!mesh.isReadable || mesh.subMeshCount == 0 || bones.Length != mesh.bindposeCount)
			{
				SummonNpcPlugin.LogSource.LogWarning((object)"Cannot create skeleton chest overlay: player mesh is incompatible.");
				return null;
			}
			Transform[] array = (Transform[])(object)new Transform[bones.Length];
			bool[] array2 = new bool[bones.Length];
			for (int i = 0; i < bones.Length; i++)
			{
				Transform val2 = RegisterSummonNpcPatch.FindMatchingBone(val.rootBone, bodyModel.rootBone, bones[i]);
				if ((Object)(object)val2 == (Object)null)
				{
					ManualLogSource logSource = SummonNpcPlugin.LogSource;
					Transform obj = bones[i];
					logSource.LogWarning((object)("Cannot create skeleton chest overlay: player bone '" + ((obj != null) ? ((Object)obj).name : null) + "' is missing."));
					return null;
				}
				array[i] = val2;
				array2[i] = ((Object)bones[i]).name.IndexOf("spine", StringComparison.OrdinalIgnoreCase) >= 0;
			}
			BoneWeight[] boneWeights = mesh.boneWeights;
			int[] triangles = mesh.GetTriangles(0);
			List<int> list = new List<int>();
			for (int j = 0; j + 2 < triangles.Length; j += 3)
			{
				int num = triangles[j];
				int num2 = triangles[j + 1];
				int num3 = triangles[j + 2];
				if (IsTorsoVertex(num, boneWeights, array2) || IsTorsoVertex(num2, boneWeights, array2) || IsTorsoVertex(num3, boneWeights, array2))
				{
					list.Add(num);
					list.Add(num2);
					list.Add(num3);
				}
			}
			if (list.Count == 0)
			{
				SummonNpcPlugin.LogSource.LogWarning((object)"Cannot create skeleton chest overlay: no torso triangles were found.");
				return null;
			}
			Mesh val3 = Object.Instantiate<Mesh>(mesh);
			((Object)val3).name = "SummonNPC_ChestOverlay";
			val3.subMeshCount = 1;
			val3.SetTriangles(list, 0);
			GameObject val4 = new GameObject("SummonNPC_ChestOverlay");
			Transform transform = val4.transform;
			transform.SetParent(((Component)bodyModel).transform.parent, false);
			transform.localPosition = ((Component)bodyModel).transform.localPosition;
			transform.localRotation = ((Component)bodyModel).transform.localRotation;
			transform.localScale = ((Component)bodyModel).transform.localScale;
			SkinnedMeshRenderer obj2 = val4.AddComponent<SkinnedMeshRenderer>();
			obj2.sharedMesh = val3;
			obj2.rootBone = bodyModel.rootBone;
			obj2.bones = array;
			((Renderer)obj2).localBounds = ((Renderer)val).localBounds;
			obj2.updateWhenOffscreen = true;
			((Renderer)obj2).enabled = false;
			if (SummonNpcPlugin.DebugLogging.Value)
			{
				SummonNpcPlugin.LogSource.LogInfo((object)$"Created skeleton chest overlay with {list.Count / 3} torso triangles.");
			}
			SkeletonChestOverlay skeletonChestOverlay = val4.AddComponent<SkeletonChestOverlay>();
			skeletonChestOverlay._shader = (((Object)(object)((Renderer)bodyModel).sharedMaterial != (Object)null) ? ((Renderer)bodyModel).sharedMaterial.shader : null);
			return skeletonChestOverlay;
		}

		private static bool IsTorsoVertex(int index, BoneWeight[] weights, bool[] spineBones)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			if (index < 0 || index >= weights.Length)
			{
				return false;
			}
			BoneWeight val = weights[index];
			return BoneContribution(((BoneWeight)(ref val)).boneIndex0, ((BoneWeight)(ref val)).weight0, spineBones) + BoneContribution(((BoneWeight)(ref val)).boneIndex1, ((BoneWeight)(ref val)).weight1, spineBones) + BoneContribution(((BoneWeight)(ref val)).boneIndex2, ((BoneWeight)(ref val)).weight2, spineBones) + BoneContribution(((BoneWeight)(ref val)).boneIndex3, ((BoneWeight)(ref val)).weight3, spineBones) >= 0.25f;
		}

		private static float BoneContribution(int index, float weight, bool[] spineBones)
		{
			if (index < 0 || index >= spineBones.Length || !spineBones[index])
			{
				return 0f;
			}
			return weight;
		}

		internal void ApplyArmor(int hash)
		{
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Invalid comparison between Unknown and I4
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Expected O, but got Unknown
			SkinnedMeshRenderer component = ((Component)this).GetComponent<SkinnedMeshRenderer>();
			((Renderer)component).enabled = false;
			if (hash == 0)
			{
				return;
			}
			ObjectDB instance = ObjectDB.instance;
			GameObject val = ((instance != null) ? instance.GetItemPrefab(hash) : null);
			if ((Object)(object)val == (Object)null)
			{
				SummonNpcPlugin.LogSource.LogWarning((object)$"Cannot apply skeleton chest overlay: missing armor hash {hash}.");
			}
			else
			{
				if (!OverlayChestPrefabs.Contains(((Object)val).name) && !((Object)val).name.StartsWith("ArmorTunic", StringComparison.Ordinal))
				{
					return;
				}
				Material val2 = val.GetComponent<ItemDrop>()?.m_itemData?.m_shared?.m_armorMaterial;
				Texture val3 = (((Object)(object)val2 != (Object)null && val2.HasProperty(ChestTexture)) ? val2.GetTexture(ChestTexture) : null);
				if ((Object)(object)val3 == (Object)null)
				{
					SummonNpcPlugin.LogSource.LogWarning((object)("Cannot apply skeleton chest overlay: '" + ((Object)val).name + "' has no chest texture."));
				}
				else
				{
					if ((int)SystemInfo.graphicsDeviceType == 4)
					{
						return;
					}
					if ((Object)(object)_material == (Object)null)
					{
						if ((Object)(object)_shader == (Object)null || !_shader.isSupported)
						{
							SummonNpcPlugin.LogSource.LogWarning((object)"Cannot apply skeleton chest overlay: the skeleton shader is unavailable.");
							return;
						}
						_material = new Material(_shader);
						_material.SetFloat("_Cutoff", 0.3f);
						((Renderer)component).sharedMaterial = _material;
					}
					_material.mainTexture = val3;
					_material.SetTexture("_BumpMap", ((Object)(object)val2 != (Object)null && val2.HasProperty(ChestBump)) ? val2.GetTexture(ChestBump) : null);
					((Renderer)component).enabled = true;
					if (SummonNpcPlugin.DebugLogging.Value)
					{
						SummonNpcPlugin.LogSource.LogInfo((object)("Applied skeleton chest overlay for '" + ((Object)val).name + "'."));
					}
				}
			}
		}

		private void OnDestroy()
		{
			if ((Object)(object)_material != (Object)null)
			{
				Object.Destroy((Object)(object)_material);
			}
		}
	}
	[HarmonyPatch(typeof(VisEquipment), "SetHelmetEquipped")]
	internal static class ApplySummonHelmetPatch
	{
		private static readonly Vector3 SkeletonHelmetOffset = new Vector3(0f, 0.1f, -0.06f);

		private static readonly FieldInfo? HelmetItemInstanceField = AccessTools.Field(typeof(VisEquipment), "m_helmetItemInstance");

		private static readonly HashSet<string> LoggedHelmetFits = new HashSet<string>();

		private static bool _missingHelmetInstanceWarningLogged;

		private static void Prefix(VisEquipment __instance, ref int hash)
		{
			if (SummonAppearance.IsSummon(((Component)__instance).gameObject) && SummonAppearance.TryGetConfiguredPrefabHash(SummonNpcPlugin.HelmetPrefab.Value, out var hash2))
			{
				hash = hash2;
			}
		}

		private static void Postfix(VisEquipment __instance, bool __result)
		{
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Unknown result type (might be due to invalid IL or missing references)
			//IL_0224: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ab: Unknown result type (might be due to invalid IL or missing references)
			if (!__result || !SummonAppearance.IsSummon(((Component)__instance).gameObject) || !SummonNpcPlugin.UsesSkeletonBody || !SummonAppearance.TryGetConfiguredPrefabHash(SummonNpcPlugin.HelmetPrefab.Value, out var hash))
			{
				return;
			}
			ObjectDB instance = ObjectDB.instance;
			GameObject val = ((instance != null) ? instance.GetItemPrefab(hash) : null);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			object? obj = HelmetItemInstanceField?.GetValue(__instance);
			GameObject val2 = (GameObject)((obj is GameObject) ? obj : null);
			if (val2 == null)
			{
				if (!_missingHelmetInstanceWarningLogged)
				{
					SummonNpcPlugin.LogSource.LogWarning((object)"Could not access the equipped helmet instance; skeleton helmet fit was not adjusted.");
					_missingHelmetInstanceWarningLogged = true;
				}
				return;
			}
			Transform transform = val2.transform;
			SummonNpcMarker component = ((Component)__instance).GetComponent<SummonNpcMarker>();
			bool flag = (Object)(object)val.transform.Find("equipoffset") != (Object)null;
			Vector3 skeletonHelmetOffset = SkeletonHelmetOffset;
			if ((Object)(object)transform.parent == (Object)(object)__instance.m_helmet)
			{
				if (!flag)
				{
					transform.localRotation = Quaternion.Euler(0f, -90f, 0f) * transform.localRotation;
					if ((Object)(object)component != (Object)null && (Object)(object)component.PlayerHelmetMount != (Object)null)
					{
						Vector3 up = ((Component)__instance).transform.up;
						float num = Vector3.Dot(component.PlayerHelmetMount.position - transform.position, up);
						transform.position += up * num;
					}
					if (!string.Equals(((Object)val).name, "HelmetPadded", StringComparison.Ordinal))
					{
						skeletonHelmetOffset.z = 0f;
					}
				}
				switch (((Object)val).name)
				{
				case "HelmetBerserkerHood":
				case "HelmetBerserkerUndead":
					skeletonHelmetOffset.z += 0.03f;
					break;
				case "HelmetYule":
					skeletonHelmetOffset.y += 0.03f;
					break;
				}
				transform.position += ((Component)__instance).transform.TransformVector(skeletonHelmetOffset);
			}
			else
			{
				Transform reference = (((Object)(object)component != (Object)null && (Object)(object)component.PlayerHelmetMount != (Object)null) ? component.PlayerHelmetMount.parent : ((Component)__instance).transform);
				val2.AddComponent<SkeletonHelmetBoneOffset>().Initialize(reference, ((Component)__instance).transform.TransformVector(skeletonHelmetOffset));
			}
			if (SummonNpcPlugin.DebugLogging.Value && LoggedHelmetFits.Add(((Object)val).name))
			{
				SummonNpcPlugin.LogSource.LogInfo((object)("Skeleton helmet fit for '" + ((Object)val).name + "': attachment=" + (((Object)(object)transform.parent == (Object)(object)__instance.m_helmet) ? "rigid" : "skinned") + ", " + $"equipoffset={flag}, adjustment={skeletonHelmetOffset}."));
			}
		}
	}
	internal sealed class SkeletonHelmetBoneOffset : MonoBehaviour
	{
		private readonly Dictionary<Transform, Transform> _boneProxies = new Dictionary<Transform, Transform>();

		private Transform _reference;

		private Vector3 _localOffset;

		internal void Initialize(Transform reference, Vector3 worldOffset)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			_reference = reference;
			_localOffset = reference.InverseTransformVector(worldOffset);
			SkinnedMeshRenderer[] componentsInChildren = ((Component)this).GetComponentsInChildren<SkinnedMeshRenderer>();
			foreach (SkinnedMeshRenderer val in componentsInChildren)
			{
				Transform[] bones = val.bones;
				for (int j = 0; j < bones.Length; j++)
				{
					Transform val2 = bones[j];
					if (!((Object)(object)val2 == (Object)null))
					{
						if (!_boneProxies.TryGetValue(val2, out Transform value))
						{
							value = new GameObject("SummonNPC_HelmetBoneOffset").transform;
							value.SetParent(val2, false);
							value.position = val2.position + worldOffset;
							_boneProxies.Add(val2, value);
						}
						bones[j] = value;
					}
				}
				val.bones = bones;
			}
			if (_boneProxies.Count == 0)
			{
				SummonNpcPlugin.LogSource.LogWarning((object)"Could not find skinned helmet bones; skeleton helmet fit was not adjusted.");
			}
		}

		private void LateUpdate()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: 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_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = _reference.TransformVector(_localOffset);
			foreach (KeyValuePair<Transform, Transform> boneProxy in _boneProxies)
			{
				if ((Object)(object)boneProxy.Key != (Object)null && (Object)(object)boneProxy.Value != (Object)null)
				{
					boneProxy.Value.position = boneProxy.Key.position + val;
				}
			}
		}

		private void OnDestroy()
		{
			foreach (Transform value in _boneProxies.Values)
			{
				if ((Object)(object)value != (Object)null)
				{
					Object.Destroy((Object)(object)((Component)value).gameObject);
				}
			}
		}
	}
	[HarmonyPatch(typeof(VisEquipment), "SetLegEquipped")]
	internal static class ApplySummonLegArmorPatch
	{
		private static void Prefix(VisEquipment __instance, ref int hash)
		{
			if (SummonAppearance.IsSummon(((Component)__instance).gameObject) && SummonAppearance.TryGetConfiguredPrefabHash(SummonNpcPlugin.LegsPrefab.Value, out var hash2))
			{
				hash = hash2;
			}
		}
	}
	[HarmonyPatch(typeof(VisEquipment), "SetShoulderEquipped")]
	internal static class ApplySummonCapePatch
	{
		private static void Prefix(VisEquipment __instance, ref int hash, ref int variant, ref int quality)
		{
			if (SummonAppearance.IsSummon(((Component)__instance).gameObject) && SummonAppearance.TryGetConfiguredPrefabHash(SummonNpcPlugin.CapePrefab.Value, out var hash2))
			{
				hash = hash2;
				variant = 0;
				quality = 0;
			}
		}
	}
	[HarmonyPatch(typeof(VisEquipment), "SetHairEquipped")]
	internal static class ApplySummonHairPatch
	{
		private static void Prefix(VisEquipment __instance, ref int hash)
		{
			if (SummonAppearance.IsSummon(((Component)__instance).gameObject) && !SummonNpcPlugin.UsesSkeletonBody && SummonAppearance.TryGetConfiguredPrefabHash(SummonNpcPlugin.HairPrefab.Value, out var hash2))
			{
				hash = SummonAppearance.GetHelmetAdjustedAccessoryHash(__instance, hash2, beard: false);
			}
		}
	}
	[HarmonyPatch(typeof(VisEquipment), "SetBeardEquipped")]
	internal static class ApplySummonBeardPatch
	{
		private static void Prefix(VisEquipment __instance, ref int hash)
		{
			if (SummonAppearance.IsSummon(((Component)__instance).gameObject) && !SummonNpcPlugin.UsesSkeletonBody && SummonAppearance.TryGetConfiguredPrefabHash(SummonNpcPlugin.BeardPrefab.Value, out var hash2))
			{
				hash = SummonAppearance.GetHelmetAdjustedAccessoryHash(__instance, hash2, beard: true);
			}
		}
	}
	[HarmonyPatch(typeof(Tameable), "Awake")]
	internal static class InitializeSummonNamePatch
	{
		private static void Postfix(Tameable __instance)
		{
			if (SummonAppearance.IsSummon(((Component)__instance).gameObject))
			{
				SummonAppearance.InitializeAssignedName(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(ZNetScene), "CreateObject")]
	internal static class InitializeSummonNameAfterNetworkSpawnPatch
	{
		private static void Postfix(GameObject __result)
		{
			if ((Object)(object)__result != (Object)null && SummonAppearance.IsSummon(__result))
			{
				Tameable component = __result.GetComponent<Tameable>();
				if ((Object)(object)component != (Object)null)
				{
					SummonAppearance.InitializeAssignedName(component);
				}
			}
		}
	}
	[HarmonyPatch(typeof(Tameable), "GetName")]
	internal static class SetSummonTamedNamePatch
	{
		private static void Postfix(Tameable __instance, ref string __result)
		{
			if (SummonAppearance.IsSummon(((Component)__instance).gameObject))
			{
				__result = SummonAppearance.GetAssignedName(__instance, __result);
			}
		}
	}
	[HarmonyPatch(typeof(Tameable), "GetHoverName")]
	internal static class SetSummonHoverNamePatch
	{
		private static void Postfix(Tameable __instance, ref string __result)
		{
			if (SummonAppearance.IsSummon(((Component)__instance).gameObject))
			{
				__result = SummonAppearance.GetAssignedName(__instance, __result);
			}
		}
	}
	[HarmonyPatch(typeof(VisEquipment), "UpdateVisuals")]
	internal static class ApplySummonSkinColorPatch
	{
		private static readonly int SkinColorProperty = Shader.PropertyToID("_SkinColor");

		private static readonly MaterialPropertyBlock PropertyBlock = new MaterialPropertyBlock();

		private static void Prefix(VisEquipment __instance)
		{
			if (SummonAppearance.IsSummon(((Component)__instance).gameObject) && !SummonNpcPlugin.UsesSkeletonBody)
			{
				SummonAppearance.PrepareConfiguredHairAndBeard(__instance);
			}
		}

		private static void Postfix(VisEquipment __instance)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			if (!SummonAppearance.IsSummon(((Component)__instance).gameObject) || SummonNpcPlugin.UsesSkeletonBody)
			{
				return;
			}
			SummonAppearance.ApplyConfiguredHairAndBeard(__instance);
			SummonAppearance.ApplyConfiguredHairColor(__instance);
			SkinnedMeshRenderer bodyModel = __instance.m_bodyModel;
			if ((Object)(object)bodyModel == (Object)null)
			{
				return;
			}
			Mesh sharedMesh = bodyModel.sharedMesh;
			if (!((Object)(object)sharedMesh == (Object)null))
			{
				for (int i = 0; i < sharedMesh.subMeshCount; i++)
				{
					((Renderer)bodyModel).GetPropertyBlock(PropertyBlock, i);
					PropertyBlock.SetColor(SkinColorProperty, SummonAppearance.GetConfiguredSkinColor());
					((Renderer)bodyModel).SetPropertyBlock(PropertyBlock, i);
				}
			}
		}
	}
	[HarmonyPatch(typeof(VisEquipment), "SetupNpcHair")]
	internal static class SuppressSummonHairPatch
	{
		private static bool Prefix(VisEquipment __instance)
		{
			if (!SummonAppearance.IsSummon(((Component)__instance).gameObject) || SummonNpcPlugin.UsesSkeletonBody)
			{
				return true;
			}
			if (!SummonAppearance.CanApplyConfiguredPrefab(SummonNpcPlugin.HairPrefab.Value))
			{
				return false;
			}
			__instance.m_npcHairChance = 1f;
			return true;
		}
	}
	[HarmonyPatch(typeof(VisEquipment), "SetupNpcBeard")]
	internal static class SuppressSummonBeardPatch
	{
		private static bool Prefix(VisEquipment __instance)
		{
			if (!SummonAppearance.IsSummon(((Component)__instance).gameObject) || SummonNpcPlugin.UsesSkeletonBody)
			{
				return true;
			}
			if (!SummonAppearance.CanApplyConfiguredPrefab(SummonNpcPlugin.BeardPrefab.Value))
			{
				return false;
			}
			__instance.m_npcBeardChance = 1f;
			return true;
		}
	}
}
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 distri