Decompiled source of SagaCompanions v1.1.2

plugins/SagaCompanions.dll

Decompiled an hour ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using Splatform;
using TMPro;
using UnityEngine;
using UnityEngine.Animations;
using UnityEngine.Playables;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using WolfGuard.Core;

[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("SagaCompanions")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Companion, mount and tamed-animal improvements for Valheim.")]
[assembly: AssemblyFileVersion("1.1.2.0")]
[assembly: AssemblyInformationalVersion("1.1.2")]
[assembly: AssemblyProduct("SagaCompanions")]
[assembly: AssemblyTitle("SagaCompanions")]
[assembly: AssemblyVersion("1.1.2.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace WolfGuard
{
	internal static class CallingHorn
	{
		internal const string PrefabName = "WolfGuard_CallingHorn";

		internal const string LegacyPrefabName = "TankardAnniversary";

		internal const string BundleResource = "WolfGuard.CallingHorn.bundle";

		internal const string VisualPath = "Assets/CallingHorn/Generated/CallingHorn.prefab";

		internal const string ClipPath = "Assets/CallingHorn/Generated/CallingHornUse.anim";

		internal const string IconPath = "Assets/CallingHorn/Generated/CallingHornIcon.png";

		internal static readonly int PrefabHash = StringExtensionMethods.GetStableHashCode("WolfGuard_CallingHorn");

		internal static readonly int LegacyHash = StringExtensionMethods.GetStableHashCode("TankardAnniversary");

		private static AssetBundle bundle;

		private static CustomItem item;

		private static bool initialized;

		private static bool attempted;

		private static readonly List<Material> materials = new List<Material>();

		internal static AnimationClip UseClip { get; private set; }

		internal static bool Ready
		{
			get
			{
				if (item != null && Object.op_Implicit((Object)(object)item.ItemPrefab))
				{
					return Object.op_Implicit((Object)(object)UseClip);
				}
				return false;
			}
		}

		internal static bool Accepts(int prefab)
		{
			if (prefab != LegacyHash)
			{
				if (prefab == PrefabHash)
				{
					return Ready;
				}
				return false;
			}
			return true;
		}

		internal static bool IsOwn(ItemData weapon)
		{
			if (Object.op_Implicit((Object)(object)weapon?.m_dropPrefab))
			{
				return ((Object)weapon.m_dropPrefab).name == "WolfGuard_CallingHorn";
			}
			return false;
		}

		internal static bool IsHorn(ItemData weapon)
		{
			if (Object.op_Implicit((Object)(object)weapon?.m_dropPrefab))
			{
				return Accepts(StringExtensionMethods.GetStableHashCode(((Object)weapon.m_dropPrefab).name));
			}
			return false;
		}

		internal static void Initialize()
		{
			if (!initialized)
			{
				initialized = true;
				PrefabManager.OnVanillaPrefabsAvailable += Register;
			}
		}

		private static void Register()
		{
			//IL_0242: Unknown result type (might be due to invalid IL or missing references)
			//IL_0253: Unknown result type (might be due to invalid IL or missing references)
			//IL_0264: Unknown result type (might be due to invalid IL or missing references)
			//IL_029f: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a6: Expected O, but got Unknown
			//IL_03c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0403: Expected O, but got Unknown
			//IL_0405: Unknown result type (might be due to invalid IL or missing references)
			//IL_040a: Unknown result type (might be due to invalid IL or missing references)
			//IL_040c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0411: Unknown result type (might be due to invalid IL or missing references)
			//IL_0421: Expected O, but got Unknown
			//IL_0474: Unknown result type (might be due to invalid IL or missing references)
			//IL_047b: Expected O, but got Unknown
			//IL_04a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a8: Expected O, but got Unknown
			//IL_04b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b8: Expected O, but got Unknown
			//IL_04c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c8: Expected O, but got Unknown
			//IL_04d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_04dc: Expected O, but got Unknown
			//IL_045c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0466: Expected O, but got Unknown
			if (attempted)
			{
				return;
			}
			attempted = true;
			GameObject val = null;
			try
			{
				using (Stream stream = typeof(CallingHorn).Assembly.GetManifestResourceStream("WolfGuard.CallingHorn.bundle"))
				{
					if (stream == null)
					{
						throw new InvalidDataException("Falta el paquete del Cuerno de llamada.");
					}
					using MemoryStream memoryStream = new MemoryStream();
					stream.CopyTo(memoryStream);
					bundle = AssetBundle.LoadFromMemory(memoryStream.ToArray());
				}
				if (!Object.op_Implicit((Object)(object)bundle))
				{
					throw new InvalidDataException("Paquete del Cuerno de llamada inválido.");
				}
				GameObject val2 = bundle.LoadAsset<GameObject>("Assets/CallingHorn/Generated/CallingHorn.prefab");
				AnimationClip val3 = bundle.LoadAsset<AnimationClip>("Assets/CallingHorn/Generated/CallingHornUse.anim");
				Sprite val4 = bundle.LoadAsset<Sprite>("Assets/CallingHorn/Generated/CallingHornIcon.png");
				Transform val5 = (Object.op_Implicit((Object)(object)val2) ? val2.transform.Find("attach") : null);
				if (!Object.op_Implicit((Object)(object)val5) || ((Component)val5).GetComponentsInChildren<MeshRenderer>(true).Length == 0 || ((Component)val5).GetComponentsInChildren<MonoBehaviour>(true).Length != 0 || !Object.op_Implicit((Object)(object)val4) || !ValidClip(val3))
				{
					throw new InvalidDataException("El modelo, icono o gesto del cuerno está incompleto.");
				}
				GameObject prefab = PrefabManager.Instance.GetPrefab("TankardAnniversary");
				ItemDrop val6 = (Object.op_Implicit((Object)(object)prefab) ? prefab.GetComponent<ItemDrop>() : null);
				Renderer val7 = (Renderer)(object)(Object.op_Implicit((Object)(object)prefab) ? prefab.GetComponentInChildren<MeshRenderer>(true) : null);
				if (!Object.op_Implicit((Object)(object)val6) || !Object.op_Implicit((Object)(object)val7) || !Object.op_Implicit((Object)(object)val7.sharedMaterial) || !Object.op_Implicit((Object)(object)val7.sharedMaterial.shader))
				{
					throw new InvalidDataException("No está disponible la infraestructura nativa del cuerno.");
				}
				val = PrefabManager.Instance.CreateClonedPrefab("WolfGuard_CallingHorn", prefab);
				if (!Object.op_Implicit((Object)(object)val))
				{
					throw new InvalidDataException("No se pudo crear el objeto independiente.");
				}
				string[] array = new string[4] { "attach", "attach_skin", "attach_back", "equipoffset" };
				foreach (string text in array)
				{
					Transform val8 = val.transform.Find(text);
					if (Object.op_Implicit((Object)(object)val8))
					{
						Object.DestroyImmediate((Object)(object)((Component)val8).gameObject);
					}
				}
				GameObject val9 = Object.Instantiate<GameObject>(((Component)val5).gameObject, val.transform, false);
				((Object)val9).name = "attach";
				val9.transform.localPosition = Vector3.zero;
				val9.transform.localRotation = Quaternion.identity;
				val9.transform.localScale = Vector3.one;
				PrepareMaterials(val9, val7.sharedMaterial);
				AddDropCollider(val, val9);
				ItemDrop component = val.GetComponent<ItemDrop>();
				component.m_itemData = val6.m_itemData.Clone();
				SharedData val10 = new SharedData();
				FieldInfo[] fields = typeof(SharedData).GetFields(BindingFlags.Instance | BindingFlags.Public);
				foreach (FieldInfo fieldInfo in fields)
				{
					fieldInfo.SetValue(val10, fieldInfo.GetValue(val6.m_itemData.m_shared));
				}
				component.m_itemData.m_shared = val10;
				component.m_itemData.m_dropPrefab = val;
				val10.m_name = "$item_wolfguard_callinghorn";
				val10.m_description = "$item_wolfguard_callinghorn_description";
				val10.m_icons = (Sprite[])(object)new Sprite[1] { val4 };
				val10.m_maxStackSize = 1;
				val10.m_maxQuality = 1;
				val10.m_weight = 1f;
				val10.m_useDurability = false;
				val10.m_ammoType = string.Empty;
				val10.m_food = (val10.m_foodStamina = (val10.m_foodEitr = (val10.m_foodRegen = 0f)));
				val10.m_consumeStatusEffect = (val10.m_attackStatusEffect = (val10.m_equipStatusEffect = (val10.m_setStatusEffect = null)));
				val10.m_damages = default(DamageTypes);
				val10.m_damagesPerLevel = default(DamageTypes);
				val10.m_attackForce = 0f;
				val10.m_attack = new Attack
				{
					m_attackType = (AttackType)3,
					m_attackAnimation = string.Empty
				};
				val10.m_secondaryAttack = new Attack
				{
					m_attackType = (AttackType)3,
					m_attackAnimation = string.Empty
				};
				fields = typeof(SharedData).GetFields(BindingFlags.Instance | BindingFlags.Public);
				foreach (FieldInfo fieldInfo2 in fields)
				{
					if (fieldInfo2.FieldType == typeof(EffectList))
					{
						fieldInfo2.SetValue(val10, (object?)new EffectList());
					}
				}
				ItemConfig val11 = new ItemConfig();
				val11.CraftingStation = "piece_workbench";
				val11.MinStationLevel = 2;
				val11.Requirements = (RequirementConfig[])(object)new RequirementConfig[3]
				{
					new RequirementConfig("FineWood", 10, 0, true),
					new RequirementConfig("Bronze", 2, 0, true),
					new RequirementConfig("LeatherScraps", 4, 0, true)
				};
				ItemConfig val12 = val11;
				CustomItem val13 = new CustomItem(val, false, val12);
				AddLocalization();
				if (!ItemManager.Instance.AddItem(val13))
				{
					throw new InvalidDataException("Jötunn rechazó el registro del cuerno.");
				}
				UseClip = val3;
				item = val13;
				ManualLogSource log = WolfPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)string.Format("WOLFGUARD_CALLING_HORN ready=True prefab={0} clip={1} duration={2:F3} events={3}", "WolfGuard_CallingHorn", ((Object)val3).name, val3.length, val3.events.Length));
				}
			}
			catch (Exception ex)
			{
				if (Object.op_Implicit((Object)(object)val))
				{
					Object.Destroy((Object)(object)val);
				}
				ReleaseAssets();
				ManualLogSource log2 = WolfPlugin.Log;
				if (log2 != null)
				{
					log2.LogWarning((object)("WOLFGUARD_CALLING_HORN ready=False; no se registró el objeto incompleto: " + ex.Message));
				}
			}
		}

		internal static bool ValidClip(AnimationClip clip)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)clip) && clip.humanMotion && !clip.legacy && !((Motion)clip).isLooping && clip.events.Length == 0 && clip.length >= 2.6f && clip.length <= 2.8f)
			{
				Vector3 averageSpeed = ((Motion)clip).averageSpeed;
				return ((Vector3)(ref averageSpeed)).sqrMagnitude < 0.0001f;
			}
			return false;
		}

		private static void PrepareMaterials(GameObject visual, Material native)
		{
			//IL_004f: 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_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Expected O, but got Unknown
			Dictionary<Material, Material> dictionary = new Dictionary<Material, Material>();
			Renderer[] componentsInChildren = visual.GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val in componentsInChildren)
			{
				Material[] sharedMaterials = val.sharedMaterials;
				for (int j = 0; j < sharedMaterials.Length; j++)
				{
					Material val2 = sharedMaterials[j];
					if (!Object.op_Implicit((Object)(object)val2))
					{
						throw new InvalidDataException("Material del cuerno ausente.");
					}
					if (!dictionary.TryGetValue(val2, out var value))
					{
						value = (dictionary[val2] = new Material(val2)
						{
							name = "WolfGuard " + ((Object)val2).name,
							shader = native.shader
						});
						materials.Add(value);
					}
					sharedMaterials[j] = value;
				}
				val.sharedMaterials = sharedMaterials;
			}
		}

		private static void AddDropCollider(GameObject root, GameObject visual)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			Bounds val = default(Bounds);
			bool flag = false;
			MeshFilter[] componentsInChildren = visual.GetComponentsInChildren<MeshFilter>(true);
			foreach (MeshFilter val2 in componentsInChildren)
			{
				if (!Object.op_Implicit((Object)(object)val2.sharedMesh))
				{
					continue;
				}
				Bounds bounds = val2.sharedMesh.bounds;
				for (int j = 0; j < 8; j++)
				{
					Vector3 val3 = ((Bounds)(ref bounds)).center + Vector3.Scale(((Bounds)(ref bounds)).extents, new Vector3((float)(((j & 1) != 0) ? 1 : (-1)), (float)(((j & 2) != 0) ? 1 : (-1)), (float)(((j & 4) != 0) ? 1 : (-1))));
					Vector3 val4 = root.transform.InverseTransformPoint(((Component)val2).transform.TransformPoint(val3));
					if (!WolfState.IsFinite(val4))
					{
						throw new InvalidDataException("Geometría del cuerno inválida.");
					}
					if (!flag)
					{
						((Bounds)(ref val))..ctor(val4, Vector3.zero);
						flag = true;
					}
					else
					{
						((Bounds)(ref val)).Encapsulate(val4);
					}
				}
			}
			if (flag)
			{
				Vector3 size = ((Bounds)(ref val)).size;
				if (!(((Vector3)(ref size)).magnitude > 2f))
				{
					size = ((Bounds)(ref val)).size;
					if (!(((Vector3)(ref size)).sqrMagnitude < 0.0025f))
					{
						Collider[] componentsInChildren2 = root.GetComponentsInChildren<Collider>(true);
						for (int i = 0; i < componentsInChildren2.Length; i++)
						{
							Object.DestroyImmediate((Object)(object)componentsInChildren2[i]);
						}
						BoxCollider obj = root.AddComponent<BoxCollider>();
						obj.center = ((Bounds)(ref val)).center;
						obj.size = Vector3.Max(((Bounds)(ref val)).size, Vector3.one * 0.025f);
						return;
					}
				}
			}
			throw new InvalidDataException("Dimensiones del cuerno fuera del contrato.");
		}

		private static void AddLocalization()
		{
			CustomLocalization localization = LocalizationManager.Instance.GetLocalization();
			string text = "English";
			string text2 = "Spanish";
			localization.AddTranslation(ref text, new Dictionary<string, string>
			{
				["item_wolfguard_callinghorn"] = "Calling Horn",
				["item_wolfguard_callinghorn_description"] = "Call your last registered mount to a safe place nearby. Requires a saddle."
			});
			localization.AddTranslation(ref text2, new Dictionary<string, string>
			{
				["item_wolfguard_callinghorn"] = "Cuerno de llamada",
				["item_wolfguard_callinghorn_description"] = "Trae tu última montura registrada a un lugar seguro cercano. Necesita una silla."
			});
		}

		private static void ReleaseAssets()
		{
			UseClip = null;
			foreach (Material material in materials)
			{
				if (Object.op_Implicit((Object)(object)material))
				{
					Object.Destroy((Object)(object)material);
				}
			}
			materials.Clear();
			if (Object.op_Implicit((Object)(object)bundle))
			{
				bundle.Unload(true);
			}
			bundle = null;
		}

		internal static void Shutdown()
		{
			PrefabManager.OnVanillaPrefabsAvailable -= Register;
			CallingHornAnimation.Reset();
			if (item != null && Object.op_Implicit((Object)(object)item.ItemPrefab))
			{
				ItemManager.Instance.RemoveItem(item);
			}
			item = null;
			ReleaseAssets();
			initialized = (attempted = false);
		}
	}
	internal static class CallingHornAnimation
	{
		private sealed class FailedAction
		{
			internal long Id;
		}

		private sealed class LastAction
		{
			internal string Summary;

			internal double FinishedAt;
		}

		internal readonly struct ActionInfo
		{
			internal readonly long Id;

			internal readonly long Started;

			internal readonly long Owner;

			internal readonly int Emote;

			internal readonly int Item;

			internal ActionInfo(long id, long started, long owner, int emote, int item)
			{
				Id = id;
				Started = started;
				Owner = owner;
				Emote = emote;
				Item = item;
			}
		}

		private sealed class Playback
		{
			internal Player Actor;

			internal ZNetView View;

			internal Animator Animator;

			internal RuntimeAnimatorController Controller;

			internal Avatar Avatar;

			internal ActionInfo Action;

			internal UpperBodyPose Pose;

			internal bool AudioAuthorized;

			internal bool AudioPlayed;

			internal bool Entered;

			internal string BeforeState;

			internal string EnteredState;
		}

		private sealed class UpperBodyPose : IDisposable
		{
			private GameObject root;

			private PlayableGraph graph;

			private AnimationClipPlayable clip;

			private readonly List<(Transform Real, Transform Sample)> upper = new List<(Transform, Transform)>(48);

			internal bool Valid
			{
				get
				{
					//IL_001b: Unknown result type (might be due to invalid IL or missing references)
					if (Object.op_Implicit((Object)(object)root) && ((PlayableGraph)(ref graph)).IsValid())
					{
						return PlayableExtensions.IsValid<AnimationClipPlayable>(clip);
					}
					return false;
				}
			}

			internal UpperBodyPose(Animator actual)
			{
				//IL_0019: Unknown result type (might be due to invalid IL or missing references)
				//IL_0023: Expected O, but got Unknown
				//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ce: 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_00eb: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
				//IL_010e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0122: Unknown result type (might be due to invalid IL or missing references)
				//IL_012d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0133: Unknown result type (might be due to invalid IL or missing references)
				//IL_014f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0151: Unknown result type (might be due to invalid IL or missing references)
				//IL_0155: Invalid comparison between Unknown and I4
				//IL_0157: Unknown result type (might be due to invalid IL or missing references)
				//IL_015b: Invalid comparison between Unknown and I4
				//IL_015d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0161: Invalid comparison between Unknown and I4
				//IL_0163: Unknown result type (might be due to invalid IL or missing references)
				//IL_0167: Invalid comparison between Unknown and I4
				//IL_0169: Unknown result type (might be due to invalid IL or missing references)
				//IL_016d: Invalid comparison between Unknown and I4
				//IL_0170: Unknown result type (might be due to invalid IL or missing references)
				//IL_0183: Unknown result type (might be due to invalid IL or missing references)
				Dictionary<Transform, Transform> copies;
				try
				{
					root = new GameObject("WolfGuard horn pose");
					root.SetActive(false);
					((Object)root).hideFlags = (HideFlags)61;
					copies = new Dictionary<Transform, Transform> { [((Component)actual).transform] = root.transform };
					for (int i = 0; i < 55; i++)
					{
						Transform boneTransform = actual.GetBoneTransform((HumanBodyBones)i);
						if (Object.op_Implicit((Object)(object)boneTransform))
						{
							Copy(boneTransform);
						}
					}
					Animator val = root.AddComponent<Animator>();
					val.avatar = actual.avatar;
					val.applyRootMotion = false;
					val.fireEvents = false;
					val.cullingMode = (AnimatorCullingMode)0;
					root.SetActive(true);
					graph = PlayableGraph.Create("WolfGuard horn pose");
					((PlayableGraph)(ref graph)).SetTimeUpdateMode((DirectorUpdateMode)3);
					clip = AnimationClipPlayable.Create(graph, CallingHorn.UseClip);
					((AnimationClipPlayable)(ref clip)).SetApplyFootIK(false);
					((AnimationClipPlayable)(ref clip)).SetApplyPlayableIK(false);
					PlayableExtensions.SetSpeed<AnimationClipPlayable>(clip, 0.0);
					PlayableOutputExtensions.SetSourcePlayable<AnimationPlayableOutput, AnimationClipPlayable>(AnimationPlayableOutput.Create(graph, "Upper body", val), clip);
					((PlayableGraph)(ref graph)).Play();
					for (int j = 7; j < 55; j++)
					{
						HumanBodyBones val2 = (HumanBodyBones)j;
						if ((int)val2 == 19 || (int)val2 == 20 || (int)val2 == 21 || (int)val2 == 22 || (int)val2 == 23)
						{
							continue;
						}
						Transform boneTransform2 = actual.GetBoneTransform(val2);
						if (Object.op_Implicit((Object)(object)boneTransform2))
						{
							Transform boneTransform3 = val.GetBoneTransform(val2);
							if (!Object.op_Implicit((Object)(object)boneTransform3))
							{
								throw new InvalidOperationException("Falta un hueso del avatar del cuerno.");
							}
							upper.Add((boneTransform2, boneTransform3));
						}
					}
					if (upper.Count < 20)
					{
						throw new InvalidOperationException("Avatar humanoide incompleto.");
					}
				}
				catch
				{
					Dispose();
					throw;
				}
				Transform Copy(Transform source)
				{
					//IL_0055: Unknown result type (might be due to invalid IL or missing references)
					//IL_006a: Unknown result type (might be due to invalid IL or missing references)
					//IL_0076: Unknown result type (might be due to invalid IL or missing references)
					//IL_0082: Unknown result type (might be due to invalid IL or missing references)
					if (!Object.op_Implicit((Object)(object)source))
					{
						throw new InvalidOperationException("El avatar no comparte la raíz del animador.");
					}
					if (copies.TryGetValue(source, out var value))
					{
						return value;
					}
					if (copies.Count >= 128)
					{
						throw new InvalidOperationException("Jerarquía de avatar demasiado grande.");
					}
					Transform val3 = Copy(source.parent);
					Transform transform2 = new GameObject(((Object)source).name).transform;
					transform2.SetParent(val3, false);
					transform2.localPosition = source.localPosition;
					transform2.localRotation = source.localRotation;
					transform2.localScale = source.localScale;
					copies[source] = transform2;
					return transform2;
				}
			}

			internal void Apply(double age)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
				//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
				PlayableExtensions.SetTime<AnimationClipPlayable>(clip, Math.Max(0.0, Math.Min(2.7, age)));
				((PlayableGraph)(ref graph)).Evaluate(0f);
				float num = Mathf.Clamp01((float)Math.Min(age / 0.12, (2.7 - age) / 0.18));
				num = num * num * (3f - 2f * num);
				foreach (var item in upper)
				{
					if (Object.op_Implicit((Object)(object)item.Real) && Object.op_Implicit((Object)(object)item.Sample))
					{
						item.Real.localRotation = Quaternion.Slerp(item.Real.localRotation, item.Sample.localRotation, num);
					}
				}
			}

			public void Dispose()
			{
				if (((PlayableGraph)(ref graph)).IsValid())
				{
					((PlayableGraph)(ref graph)).Destroy();
				}
				if (Object.op_Implicit((Object)(object)root))
				{
					Object.Destroy((Object)(object)root);
				}
				root = null;
				upper.Clear();
			}
		}

		[HarmonyPatch(typeof(Player), "UpdateEmote")]
		private static class PrepareNativeEmote
		{
			private static bool Prefix(Player __instance)
			{
				return BeforeEmote(__instance);
			}
		}

		[HarmonyPatch(typeof(Player), "LateUpdate")]
		private static class ApplyUpperBody
		{
			private static void Postfix(Player __instance)
			{
				ApplyPose(__instance);
			}
		}

		internal const double Duration = 2.7;

		internal const double SoundDelay = 0.5;

		internal const string ActionKey = "wolfguard_horn_action";

		internal const string StartedKey = "wolfguard_horn_started";

		internal const string EmoteKey = "wolfguard_horn_emote";

		internal const string ItemKey = "wolfguard_horn_item";

		internal const string OwnerKey = "wolfguard_horn_owner";

		private const int MaximumActions = 64;

		private static readonly FieldRef<Character, ZNetView> View = AccessTools.FieldRefAccess<Character, ZNetView>("m_nview");

		private static readonly FieldRef<Character, Animator> AnimatorOf = AccessTools.FieldRefAccess<Character, Animator>("m_animator");

		private static readonly Action<Player> StopEmote = AccessTools.MethodDelegate<Action<Player>>(AccessTools.Method(typeof(Player), "StopEmote", (Type[])null, (Type[])null), (object)null, true);

		private static readonly Dictionary<Player, Playback> Active = new Dictionary<Player, Playback>();

		private static readonly Dictionary<Player, ActionInfo> PendingAudio = new Dictionary<Player, ActionInfo>();

		private static readonly List<Player> Scratch = new List<Player>();

		private static ConditionalWeakTable<Player, FailedAction> Failed = new ConditionalWeakTable<Player, FailedAction>();

		private static ConditionalWeakTable<Player, LastAction> Last = new ConditionalWeakTable<Player, LastAction>();

		private static long sequence = DateTime.UtcNow.Ticks;

		private static string lastRemoteReceipt;

		private static double lastRemoteAt;

		internal static long NetworkTicks
		{
			get
			{
				if (!Object.op_Implicit((Object)(object)ZNet.instance))
				{
					return 0L;
				}
				return ZNet.instance.GetTime().Ticks;
			}
		}

		private static double Age(ActionInfo action, long now)
		{
			return (double)(now - action.Started) / 10000000.0;
		}

		private static bool Own(ActionInfo action)
		{
			return action.Item == CallingHorn.PrefabHash;
		}

		internal static bool ValidAction(ActionInfo action, long now)
		{
			if (action.Id > 0 && action.Started > 0 && action.Owner != 0L && CallingHorn.Accepts(action.Item) && now > 0 && Age(action, now) >= -0.5)
			{
				return Age(action, now) < 2.7;
			}
			return false;
		}

		private static bool Same(ActionInfo a, ActionInfo b)
		{
			if (a.Id == b.Id && a.Started == b.Started && a.Owner == b.Owner && a.Emote == b.Emote)
			{
				return a.Item == b.Item;
			}
			return false;
		}

		internal static bool TryStart(Player actor, out ActionInfo action)
		{
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			action = default(ActionInfo);
			if (!MountSettings.Enabled || !Object.op_Implicit((Object)(object)actor) || (Object)(object)actor != (Object)(object)Player.m_localPlayer || ((Character)actor).IsDead() || ((Character)actor).IsTeleporting() || ((Character)actor).IsRiding() || ((Character)actor).IsAttached() || ((Character)actor).IsAttachedToShip() || ((Character)actor).InAttack() || ((Character)actor).InDodge() || ((Character)actor).IsDrawingBow() || ((Character)actor).IsStaggering() || !((Character)actor).CanMove())
			{
				return false;
			}
			ItemData currentWeapon = ((Humanoid)actor).GetCurrentWeapon();
			if (!CallingHorn.IsHorn(currentWeapon))
			{
				return false;
			}
			ZNetView val = View.Invoke((Character)(object)actor);
			if (!Object.op_Implicit((Object)(object)val) || !val.IsValid() || !val.IsOwner())
			{
				return false;
			}
			ZDO zDO = val.GetZDO();
			long networkTicks = NetworkTicks;
			if (networkTicks <= 0)
			{
				return false;
			}
			int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)currentWeapon.m_dropPrefab).name);
			bool flag = stableHashCode == CallingHorn.PrefabHash;
			if (flag && ((Character)actor).InEmote())
			{
				return false;
			}
			if (Active.TryGetValue(actor, out var value))
			{
				End(value, stop: true, "replaced");
			}
			int num = zDO.GetInt(ZDOVars.s_emoteID, 0);
			action = new ActionInfo(++sequence, networkTicks, zDO.GetOwner(), flag ? num : (num + 1), stableHashCode);
			Playback playback = Create(actor, action);
			if (playback == null)
			{
				action = default(ActionInfo);
				return false;
			}
			zDO.Set("wolfguard_horn_action", action.Id);
			zDO.Set("wolfguard_horn_started", action.Started);
			zDO.Set("wolfguard_horn_owner", action.Owner);
			zDO.Set("wolfguard_horn_emote", action.Emote);
			zDO.Set("wolfguard_horn_item", action.Item);
			Active[actor] = playback;
			if (!flag && !actor.StartEmote("toast", true))
			{
				End(playback, stop: false, "native-start-rejected");
				action = default(ActionInfo);
				return false;
			}
			if (!Matches(zDO, action))
			{
				End(playback, stop: false, "native-start-mismatch");
				action = default(ActionInfo);
				return false;
			}
			ZDOMan instance = ZDOMan.instance;
			if (instance != null)
			{
				instance.ForceSendZDO(zDO.m_uid);
			}
			return true;
		}

		internal static void AuthorizeAudio(Player actor, ActionInfo action)
		{
			if (!Object.op_Implicit((Object)(object)actor) || ((Character)actor).IsDead() || ((Character)actor).GetOwner() != action.Owner || !ValidAction(action, NetworkTicks) || (Failed.TryGetValue(actor, out var value) && value.Id == action.Id))
			{
				return;
			}
			ActionInfo value3;
			if (Active.TryGetValue(actor, out var value2) && Same(value2.Action, action))
			{
				if (!value2.AudioAuthorized)
				{
					Receipt(actor, action, "pose-first");
				}
				value2.AudioAuthorized = true;
			}
			else if ((!PendingAudio.TryGetValue(actor, out value3) || !Same(value3, action)) && (PendingAudio.Count < 64 || PendingAudio.ContainsKey(actor)))
			{
				PendingAudio[actor] = action;
				Receipt(actor, action, "audio-first");
			}
		}

		private static void Receipt(Player actor, ActionInfo action, string order)
		{
			string text = $"action={action.Id} actor={actor.GetPlayerID()} owner={action.Owner} local={(Object)(object)actor == (Object)(object)Player.m_localPlayer} order={order} age={Age(action, NetworkTicks):F3}";
			ManualLogSource log = WolfPlugin.Log;
			if (log != null)
			{
				log.LogInfo((object)("WOLFGUARD_HORN_ACTION event=audio-authorized " + text));
			}
			if ((Object)(object)actor != (Object)(object)Player.m_localPlayer)
			{
				lastRemoteReceipt = text;
				lastRemoteAt = Time.realtimeSinceStartupAsDouble;
			}
		}

		private static bool NativeMatches(ZDO data, ActionInfo action)
		{
			if (data.GetInt(ZDOVars.s_emoteID, 0) == action.Emote)
			{
				if (!Own(action))
				{
					return data.GetString(ZDOVars.s_emote, "") == "toast";
				}
				return true;
			}
			return false;
		}

		private static bool Matches(ZDO data, ActionInfo action)
		{
			if (data != null && data.GetOwner() == action.Owner && data.GetLong("wolfguard_horn_action", 0L) == action.Id && data.GetLong("wolfguard_horn_started", 0L) == action.Started && data.GetLong("wolfguard_horn_owner", 0L) == action.Owner && data.GetInt("wolfguard_horn_emote", 0) == action.Emote && data.GetInt("wolfguard_horn_item", 0) == action.Item)
			{
				return NativeMatches(data, action);
			}
			return false;
		}

		internal static bool BeforeEmote(Player actor)
		{
			ZNetView val = (Object.op_Implicit((Object)(object)actor) ? View.Invoke((Character)(object)actor) : null);
			if (!Object.op_Implicit((Object)(object)val) || !val.IsValid())
			{
				return true;
			}
			ZDO zDO = val.GetZDO();
			if (Active.TryGetValue(actor, out var value) && !Usable(value))
			{
				End(value, stop: true, EndReason(value));
			}
			long num = zDO.GetLong("wolfguard_horn_action", 0L);
			if (num <= 0)
			{
				return true;
			}
			ActionInfo action = new ActionInfo(num, zDO.GetLong("wolfguard_horn_started", 0L), zDO.GetLong("wolfguard_horn_owner", 0L), zDO.GetInt("wolfguard_horn_emote", 0), zDO.GetInt("wolfguard_horn_item", 0));
			if (!NativeMatches(zDO, action))
			{
				return true;
			}
			if (!MountSettings.Enabled || !Matches(zDO, action) || !ValidAction(action, NetworkTicks))
			{
				if (val.IsOwner())
				{
					ClearOwned(actor, val, action, stop: true);
				}
				return Own(action);
			}
			if (!Active.ContainsKey(actor))
			{
				if (Failed.TryGetValue(actor, out var value2) && value2.Id == action.Id)
				{
					return Own(action);
				}
				Playback playback = Create(actor, action);
				if (playback == null)
				{
					Failed.GetValue(actor, (Player _) => new FailedAction()).Id = action.Id;
					return Own(action);
				}
				Active[actor] = playback;
			}
			return true;
		}

		private static Playback Create(Player actor, ActionInfo action)
		{
			if (Active.Count >= 64 || !CallingHorn.Accepts(action.Item) || !Object.op_Implicit((Object)(object)actor) || ((Character)actor).IsDead() || ((Character)actor).IsTeleporting() || ((Character)actor).IsRiding() || ((Character)actor).IsAttached() || ((Character)actor).IsAttachedToShip() || ((Character)actor).InAttack() || ((Character)actor).InDodge() || ((Character)actor).IsStaggering())
			{
				return null;
			}
			ZNetView val = View.Invoke((Character)(object)actor);
			Animator val2 = AnimatorOf.Invoke((Character)(object)actor);
			if (!Object.op_Implicit((Object)(object)val) || !val.IsValid() || !Object.op_Implicit((Object)(object)val2) || !Object.op_Implicit((Object)(object)val2.runtimeAnimatorController) || val.GetZDO().GetInt(ZDOVars.s_rightItem, 0) != action.Item)
			{
				return null;
			}
			Playback playback = new Playback
			{
				Actor = actor,
				View = val,
				Animator = val2,
				Action = action,
				Controller = val2.runtimeAnimatorController,
				Avatar = val2.avatar,
				BeforeState = DescribeAnimator(val2)
			};
			if (Own(action))
			{
				if (!CallingHorn.Ready || !val2.isHuman || !Object.op_Implicit((Object)(object)val2.avatar) || !val2.avatar.isValid)
				{
					return null;
				}
				try
				{
					playback.Pose = new UpperBodyPose(val2);
				}
				catch (Exception ex)
				{
					ManualLogSource log = WolfPlugin.Log;
					if (log != null)
					{
						log.LogWarning((object)("WOLFGUARD_CALLING_HORN gesture unavailable: " + ex.Message));
					}
					return null;
				}
			}
			if (PendingAudio.TryGetValue(actor, out var value) && Same(value, action))
			{
				playback.AudioAuthorized = true;
				PendingAudio.Remove(actor);
			}
			return playback;
		}

		private static bool Usable(Playback playback)
		{
			Player actor = playback.Actor;
			if (!MountSettings.Enabled || !Object.op_Implicit((Object)(object)actor) || !Object.op_Implicit((Object)(object)playback.View) || !playback.View.IsValid() || !Object.op_Implicit((Object)(object)playback.Animator) || ((Character)actor).IsDead() || ((Character)actor).IsTeleporting() || ((Character)actor).IsRiding() || ((Character)actor).IsAttached() || ((Character)actor).IsAttachedToShip() || ((Character)actor).InAttack() || ((Character)actor).InDodge() || ((Character)actor).IsStaggering())
			{
				return false;
			}
			if (playback.Pose != null && (!playback.Pose.Valid || (Object)(object)playback.Animator.runtimeAnimatorController != (Object)(object)playback.Controller || (Object)(object)playback.Animator.avatar != (Object)(object)playback.Avatar))
			{
				return false;
			}
			ZDO zDO = playback.View.GetZDO();
			if (Matches(zDO, playback.Action) && zDO.GetInt(ZDOVars.s_rightItem, 0) == playback.Action.Item)
			{
				if (!((Object)(object)actor != (Object)(object)Player.m_localPlayer))
				{
					if (Object.op_Implicit((Object)(object)((Humanoid)actor).GetCurrentWeapon()?.m_dropPrefab))
					{
						return StringExtensionMethods.GetStableHashCode(((Object)((Humanoid)actor).GetCurrentWeapon().m_dropPrefab).name) == playback.Action.Item;
					}
					return false;
				}
				return true;
			}
			return false;
		}

		internal static void ApplyPose(Player actor)
		{
			if (!Object.op_Implicit((Object)(object)actor) || !Active.TryGetValue(actor, out var value) || value.Pose == null)
			{
				return;
			}
			if (!Usable(value))
			{
				End(value, stop: true, EndReason(value));
				return;
			}
			double num = Age(value.Action, NetworkTicks);
			if (!ValidAction(value.Action, NetworkTicks))
			{
				End(value, stop: true, (num >= 2.7) ? "completed" : "invalid-clock");
				return;
			}
			value.Pose.Apply(num);
			if (!value.Entered)
			{
				value.Entered = true;
				value.EnteredState = DescribeAnimator(value.Animator);
				ManualLogSource log = WolfPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)$"WOLFGUARD_HORN_ACTION action={value.Action.Id} event=entered mode=upper-body local={(Object)(object)actor == (Object)(object)Player.m_localPlayer} age={num:F3} state=[{value.EnteredState}]");
				}
			}
		}

		internal static void Tick()
		{
			if (Active.Count == 0 && PendingAudio.Count == 0)
			{
				return;
			}
			long networkTicks = NetworkTicks;
			Scratch.Clear();
			Scratch.AddRange(Active.Keys);
			foreach (Player item in Scratch)
			{
				if (!Active.TryGetValue(item, out var value))
				{
					continue;
				}
				double num = Age(value.Action, networkTicks);
				if (!Usable(value))
				{
					End(value, stop: true, EndReason(value));
				}
				else if (!ValidAction(value.Action, networkTicks))
				{
					End(value, stop: true, (num >= 2.7) ? "completed" : "invalid-clock");
				}
				else if (value.AudioAuthorized && !value.AudioPlayed && num >= 0.5 && (value.Pose == null || value.Entered))
				{
					value.AudioPlayed = true;
					MountSounds.PlayHornAudio(item, (float)(num - 0.5));
					ManualLogSource log = WolfPlugin.Log;
					if (log != null)
					{
						log.LogInfo((object)$"WOLFGUARD_HORN_ACTION action={value.Action.Id} event=audio-requested local={(Object)(object)item == (Object)(object)Player.m_localPlayer} age={num:F3} offset={num - 0.5:F3}");
					}
				}
			}
			Scratch.Clear();
			Scratch.AddRange(PendingAudio.Keys);
			foreach (Player item2 in Scratch)
			{
				if (!Object.op_Implicit((Object)(object)item2) || !MountSettings.Enabled || !ValidAction(PendingAudio[item2], networkTicks) || ((Character)item2).GetOwner() != PendingAudio[item2].Owner)
				{
					PendingAudio.Remove(item2);
				}
			}
			Scratch.Clear();
		}

		private static void ClearOwned(Player actor, ZNetView view, ActionInfo action, bool stop)
		{
			if (!Object.op_Implicit((Object)(object)actor) || !Object.op_Implicit((Object)(object)view) || !view.IsValid() || !view.IsOwner())
			{
				return;
			}
			ZDO zDO = view.GetZDO();
			if (zDO.GetLong("wolfguard_horn_action", 0L) == action.Id)
			{
				if (stop && !Own(action) && NativeMatches(zDO, action))
				{
					StopEmote(actor);
				}
				zDO.Set("wolfguard_horn_action", 0L);
				zDO.Set("wolfguard_horn_started", 0L);
				zDO.Set("wolfguard_horn_owner", 0L);
				zDO.Set("wolfguard_horn_emote", 0);
				zDO.Set("wolfguard_horn_item", 0);
			}
		}

		private static string EndReason(Playback playback)
		{
			if (!MountSettings.Enabled)
			{
				return "disabled";
			}
			if (!Object.op_Implicit((Object)(object)playback.Actor) || !Object.op_Implicit((Object)(object)playback.View) || !playback.View.IsValid() || !Object.op_Implicit((Object)(object)playback.Animator))
			{
				return "unloaded";
			}
			if (((Character)playback.Actor).IsDead())
			{
				return "dead";
			}
			ZDO zDO = playback.View.GetZDO();
			if (zDO.GetOwner() != playback.Action.Owner)
			{
				return "owner-changed";
			}
			if (!NativeMatches(zDO, playback.Action))
			{
				return "native-emote-changed";
			}
			if (playback.Pose != null && ((Object)(object)playback.Animator.runtimeAnimatorController != (Object)(object)playback.Controller || (Object)(object)playback.Animator.avatar != (Object)(object)playback.Avatar))
			{
				return "controller-or-avatar-replaced";
			}
			if (zDO.GetInt(ZDOVars.s_rightItem, 0) != playback.Action.Item)
			{
				return "unequipped";
			}
			return "interrupted";
		}

		private static string DescribeAnimator(Animator animator)
		{
			//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_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)animator) || !Object.op_Implicit((Object)(object)animator.runtimeAnimatorController))
			{
				return "unavailable";
			}
			AnimatorStateInfo currentAnimatorStateInfo = animator.GetCurrentAnimatorStateInfo(0);
			AnimatorStateInfo nextAnimatorStateInfo = animator.GetNextAnimatorStateInfo(0);
			string text = "";
			AnimatorClipInfo[] currentAnimatorClipInfo = animator.GetCurrentAnimatorClipInfo(0);
			for (int i = 0; i < currentAnimatorClipInfo.Length && i < 4; i++)
			{
				text = text + ((i == 0) ? "" : ",") + ((Object)((AnimatorClipInfo)(ref currentAnimatorClipInfo[i])).clip).name + ":" + ((AnimatorClipInfo)(ref currentAnimatorClipInfo[i])).weight.ToString("F2");
			}
			return $"controller={((Object)animator.runtimeAnimatorController).name} current={((AnimatorStateInfo)(ref currentAnimatorStateInfo)).fullPathHash} normalized={((AnimatorStateInfo)(ref currentAnimatorStateInfo)).normalizedTime:F3} transition={animator.IsInTransition(0)} next={((AnimatorStateInfo)(ref nextAnimatorStateInfo)).fullPathHash} clips={text}";
		}

		private static void End(Playback playback, bool stop, string reason)
		{
			Active.Remove(playback.Actor);
			Failed.GetValue(playback.Actor, (Player _) => new FailedAction()).Id = playback.Action.Id;
			if (PendingAudio.TryGetValue(playback.Actor, out var value) && value.Id == playback.Action.Id)
			{
				PendingAudio.Remove(playback.Actor);
			}
			ClearOwned(playback.Actor, playback.View, playback.Action, stop);
			MountSounds.StopHornAudio(playback.Actor);
			playback.Pose?.Dispose();
			playback.Pose = null;
			string text = string.Format("action={0} mode={1} local={2} reason={3} age={4:F3} entered={5} audioAuthorized={6} audioPlayed={7} controllerUnchanged={8} before=[{9}] enteredState=[{10}] endState=[{11}]", playback.Action.Id, Own(playback.Action) ? "upper-body" : "legacy-toast", (Object)(object)playback.Actor == (Object)(object)Player.m_localPlayer, reason, Age(playback.Action, NetworkTicks), playback.Entered, playback.AudioAuthorized, playback.AudioPlayed, Object.op_Implicit((Object)(object)playback.Animator) && (Object)(object)playback.Animator.runtimeAnimatorController == (Object)(object)playback.Controller, playback.BeforeState, playback.EnteredState ?? "none", DescribeAnimator(playback.Animator));
			LastAction value2 = Last.GetValue(playback.Actor, (Player _) => new LastAction());
			value2.Summary = text;
			value2.FinishedAt = Time.realtimeSinceStartupAsDouble;
			ManualLogSource log = WolfPlugin.Log;
			if (log != null)
			{
				log.LogInfo((object)("WOLFGUARD_HORN_ACTION event=ended " + text));
			}
		}

		internal static void Reset()
		{
			Scratch.Clear();
			Scratch.AddRange(Active.Keys);
			foreach (Player item in Scratch)
			{
				if (Active.TryGetValue(item, out var value))
				{
					End(value, stop: true, "session-reset");
				}
			}
			Scratch.Clear();
			PendingAudio.Clear();
			Failed = new ConditionalWeakTable<Player, FailedAction>();
			Last = new ConditionalWeakTable<Player, LastAction>();
			lastRemoteReceipt = null;
		}

		internal static void LogDiagnostics()
		{
			Player localPlayer = Player.m_localPlayer;
			object obj;
			if (!Object.op_Implicit((Object)(object)localPlayer))
			{
				obj = "no-player";
			}
			else
			{
				ItemData currentWeapon = ((Humanoid)localPlayer).GetCurrentWeapon();
				if (currentWeapon == null)
				{
					obj = null;
				}
				else
				{
					GameObject dropPrefab = currentWeapon.m_dropPrefab;
					obj = ((dropPrefab != null) ? ((Object)dropPrefab).name : null);
				}
				if (obj == null)
				{
					obj = "none";
				}
			}
			string text = (string)obj;
			Playback value = null;
			if (Object.op_Implicit((Object)(object)localPlayer))
			{
				Active.TryGetValue(localPlayer, out value);
			}
			long networkTicks = NetworkTicks;
			string text2 = ((value == null) ? "idle" : ((Age(value.Action, networkTicks) < 0.5) ? "raising" : ((Age(value.Action, networkTicks) < 2.15) ? "sounding" : "lowering")));
			ManualLogSource log = WolfPlugin.Log;
			if (log != null)
			{
				log.LogInfo((object)$"WOLFGUARD_CALLING_HORN_STATE ready={CallingHorn.Ready} equipped={text} active={value != null} age={((value == null) ? (-1.0) : Age(value.Action, networkTicks)):F3} phase={text2} upperBody={value?.Pose != null} audioAuthorized={value?.AudioAuthorized ?? false} audioPlayed={value?.AudioPlayed ?? false} replicas={Active.Count} pendingAudio={PendingAudio.Count}");
			}
			if (Object.op_Implicit((Object)(object)localPlayer) && Last.TryGetValue(localPlayer, out var value2))
			{
				ManualLogSource log2 = WolfPlugin.Log;
				if (log2 != null)
				{
					log2.LogInfo((object)$"WOLFGUARD_CALLING_HORN_LAST secondsAgo={Time.realtimeSinceStartupAsDouble - value2.FinishedAt:F1} {value2.Summary}");
				}
			}
			if (lastRemoteReceipt != null)
			{
				ManualLogSource log3 = WolfPlugin.Log;
				if (log3 != null)
				{
					log3.LogInfo((object)$"WOLFGUARD_CALLING_HORN_REMOTE secondsAgo={Time.realtimeSinceStartupAsDouble - lastRemoteAt:F1} {lastRemoteReceipt}");
				}
			}
		}
	}
	internal static class ConfigurationMetadata
	{
		private sealed class Presentation
		{
			internal readonly string Category;

			internal readonly string Name;

			internal readonly int Order;

			internal readonly bool Advanced;

			internal readonly bool RawFraction;

			internal Presentation(string category, string name, int order, bool advanced, bool rawFraction = false)
			{
				Category = category;
				Name = name;
				Order = order;
				Advanced = advanced;
				RawFraction = rawFraction;
			}
		}

		private static readonly Dictionary<ConfigDefinition, Presentation> Entries = new Dictionary<ConfigDefinition, Presentation>
		{
			{
				new ConfigDefinition("General", "Enabled"),
				new Presentation("General", "Activar SagaCompanions", 1000, advanced: false)
			},
			{
				new ConfigDefinition("Regeneracion", "Enabled"),
				new Presentation("Animales domesticados", "Activar regeneración", 999, advanced: false)
			},
			{
				new ConfigDefinition("Regeneracion", "InCombatPercentPerSecond"),
				new Presentation("Animales domesticados", "Vida por segundo en combate (%)", 998, advanced: false)
			},
			{
				new ConfigDefinition("Regeneracion", "OutOfCombatPercentPerSecond"),
				new Presentation("Animales domesticados", "Vida por segundo en calma (%)", 997, advanced: false)
			},
			{
				new ConfigDefinition("Regeneracion", "OutOfCombatSeconds"),
				new Presentation("Animales domesticados", "Espera para recuperar en calma (s)", 996, advanced: false)
			},
			{
				new ConfigDefinition("Regeneracion", "RequiresFood"),
				new Presentation("Animales domesticados", "Exigir estar alimentado", 995, advanced: false)
			},
			{
				new ConfigDefinition("Vitalidad", "HealthScalingEnabled"),
				new Presentation("Mejoras de progresión", "Aumentar vida de lobos por jefes", 994, advanced: false)
			},
			{
				new ConfigDefinition("Vitalidad", "HealthPerBossPercent"),
				new Presentation("Mejoras de progresión", "Vida adicional por jefe (%)", 993, advanced: false)
			},
			{
				new ConfigDefinition("Vitalidad", "MaxHealth"),
				new Presentation("Mejoras de progresión", "Tope de vida de lobos", 992, advanced: false)
			},
			{
				new ConfigDefinition("Interfaz local", "ShowBlessingMessage"),
				new Presentation("Interfaz y Audio", "Avisar nuevas bendiciones", 991, advanced: false)
			},
			{
				new ConfigDefinition("Guardia", "GuardRadius"),
				new Presentation("Lobos", "Radio del hogar (m)", 990, advanced: false)
			},
			{
				new ConfigDefinition("Guardia", "PatrolRadius"),
				new Presentation("Lobos", "Radio habitual de patrulla (m)", 989, advanced: false)
			},
			{
				new ConfigDefinition("Guardia", "PatrolExcursionRadius"),
				new Presentation("Lobos", "Radio de paseos largos (m)", 988, advanced: false)
			},
			{
				new ConfigDefinition("Guardia", "PatrolInterval"),
				new Presentation("Lobos", "Paseo de escolta: espera sin avance (s)", 987, advanced: true)
			},
			{
				new ConfigDefinition("Guardia", "PatrolPauseMin"),
				new Presentation("Lobos", "Paseo de escolta: pausa mínima (s)", 986, advanced: true)
			},
			{
				new ConfigDefinition("Guardia", "PatrolPauseMax"),
				new Presentation("Lobos", "Paseo de escolta: pausa máxima (s)", 985, advanced: true)
			},
			{
				new ConfigDefinition("Guardia", "GuardChaseRadius"),
				new Presentation("Lobos", "Persecución desde el hogar (m)", 984, advanced: false)
			},
			{
				new ConfigDefinition("Guardia", "ReturnCooldownSeconds"),
				new Presentation("Lobos", "Pausa de combate tras regresar (s)", 983, advanced: true)
			},
			{
				new ConfigDefinition("Combate", "DetectionRadius"),
				new Presentation("Lobos", "Detección desde el lobo (m)", 982, advanced: false)
			},
			{
				new ConfigDefinition("Combate", "ChaseRadius"),
				new Presentation("Lobos", "Persecución desde el jugador (m)", 981, advanced: false)
			},
			{
				new ConfigDefinition("Combate", "AssistRadius"),
				new Presentation("Lobos", "Alcance de ayuda a compañeros (m)", 980, advanced: true)
			},
			{
				new ConfigDefinition("Combate", "AlertSeconds"),
				new Presentation("Lobos", "Memoria de agresión compartida (s)", 979, advanced: true)
			},
			{
				new ConfigDefinition("Combate", "HuntDeer"),
				new Presentation("Lobos", "Cazar venados y liebres", 977, advanced: false)
			},
			{
				new ConfigDefinition("Alimentacion", "GroundFoodSearchRadius"),
				new Presentation("Lobos", "Búsqueda de comida suelta (m)", 976, advanced: false)
			},
			{
				new ConfigDefinition("Alimentacion", "WolfMeatDietEnabled"),
				new Presentation("Lobos", "Permitir comer carne de lobo", 975, advanced: false)
			},
			{
				new ConfigDefinition("Supervivencia", "AvoidHazards"),
				new Presentation("Lobos", "Evitar fuego y líquidos peligrosos", 974, advanced: false)
			},
			{
				new ConfigDefinition("Supervivencia", "RetreatEnabled"),
				new Presentation("Lobos", "Retirarse al quedar herido", 973, advanced: false)
			},
			{
				new ConfigDefinition("Supervivencia", "FleeHealth"),
				new Presentation("Lobos", "Salud para iniciar retirada (fracción)", 972, advanced: false, rawFraction: true)
			},
			{
				new ConfigDefinition("Supervivencia", "RecoverHealth"),
				new Presentation("Lobos", "Salud para volver al combate (fracción)", 971, advanced: false, rawFraction: true)
			},
			{
				new ConfigDefinition("Escolta", "FormationEnabled"),
				new Presentation("Lobos", "Repartir puestos alrededor del jugador", 970, advanced: false)
			},
			{
				new ConfigDefinition("Escolta", "EscortLeashRadius"),
				new Presentation("Lobos", "Alejamiento sin combate (m)", 969, advanced: true)
			},
			{
				new ConfigDefinition("Escolta", "FormationRadius"),
				new Presentation("Lobos", "Distancia de escolta (m)", 968, advanced: false)
			},
			{
				new ConfigDefinition("Escolta", "EscortWanderRadius"),
				new Presentation("Lobos", "Paseo alrededor del puesto (m)", 967, advanced: true)
			},
			{
				new ConfigDefinition("Escolta", "PersonalSpace"),
				new Presentation("Lobos", "Espacio libre junto al jugador (m)", 966, advanced: true)
			},
			{
				new ConfigDefinition("Rescate", "Enabled"),
				new Presentation("Lobos", "Rescatar lobos atascados", 965, advanced: false)
			},
			{
				new ConfigDefinition("Rescate", "StuckSeconds"),
				new Presentation("Lobos", "Escolta o persecución: espera sin avance (s)", 964, advanced: true)
			},
			{
				new ConfigDefinition("Rescate", "MinDistance"),
				new Presentation("Lobos", "Separación mínima para rescate (m)", 963, advanced: true)
			},
			{
				new ConfigDefinition("Rescate", "GraceAfterOrderSeconds"),
				new Presentation("Lobos", "Gracia antes de medir atasco (s)", 962, advanced: true)
			},
			{
				new ConfigDefinition("Rescate", "CooldownSeconds"),
				new Presentation("Lobos", "Escolta: espera entre rescates (s)", 961, advanced: true)
			},
			{
				new ConfigDefinition("Rescate", "MaxRetrySeconds"),
				new Presentation("Lobos", "Escolta: espera máxima tras fallos (s)", 960, advanced: true)
			},
			{
				new ConfigDefinition("Rescate", "GuardStuckSeconds"),
				new Presentation("Lobos", "Guardián: espera sin avance al volver (s)", 959, advanced: true)
			},
			{
				new ConfigDefinition("Rescate", "GuardCooldownSeconds"),
				new Presentation("Lobos", "Guardián: espera entre rescates (s)", 958, advanced: true)
			},
			{
				new ConfigDefinition("Rescate", "EscortPlacementRadius"),
				new Presentation("Lobos", "Colocación segura junto al jugador (m)", 957, advanced: true)
			},
			{
				new ConfigDefinition("Rescate", "ElevationGap"),
				new Presentation("Lobos", "Desnivel para retorno de escolta (m)", 956, advanced: true)
			},
			{
				new ConfigDefinition("Ordenes", "CommandRange"),
				new Presentation("Lobos", "Alcance de llamada (m)", 955, advanced: false)
			},
			{
				new ConfigDefinition("Ordenes", "AttackCommandRange"),
				new Presentation("Lobos", "Alcance de orden de ataque (m)", 955, advanced: false)
			},
			{
				new ConfigDefinition("Ordenes", "InteractionRange"),
				new Presentation("Lobos", "Alcance de orden individual (m)", 954, advanced: false)
			},
			{
				new ConfigDefinition("Ordenes", "OrderSuppressionSeconds"),
				new Presentation("Lobos", "Pausa de combate tras una orden (s)", 953, advanced: true)
			},
			{
				new ConfigDefinition("Ordenes", "AttackOrderSeconds"),
				new Presentation("Lobos", "Duración máxima de orden de ataque (s)", 952, advanced: true)
			},
			{
				new ConfigDefinition("Teclas locales", "Regroup"),
				new Presentation("Comandos", "Atajo alternativo: reagrupar", 951, advanced: true)
			},
			{
				new ConfigDefinition("Teclas locales", "GuardHere"),
				new Presentation("Comandos", "Atajo alternativo: estacionar grupo", 950, advanced: true)
			},
			{
				new ConfigDefinition("Teclas locales", "Attack"),
				new Presentation("Comandos", "Atajo alternativo: atacar", 949, advanced: true)
			},
			{
				new ConfigDefinition("Teclas locales", "EscortCommand"),
				new Presentation("Comandos", "Ordenar a lobos e invocaciones", 2000, advanced: false)
			},
			{
				new ConfigDefinition("Teclas locales", "DoubleTapSeconds"),
				new Presentation("Comandos", "Intervalo del doble toque (s)", 947, advanced: true)
			},
			{
				new ConfigDefinition("Teclas locales", "Status"),
				new Presentation("Comandos", "Atajo de diagnóstico", 946, advanced: true)
			},
			{
				new ConfigDefinition("Interfaz local", "ShowPanel"),
				new Presentation("Interfaz y Audio", "Mostrar panel de seguidores", 945, advanced: true)
			},
			{
				new ConfigDefinition("Monturas", "Enabled"),
				new Presentation("Monturas", "Activar funciones de monturas", 944, advanced: false)
			},
			{
				new ConfigDefinition("Monturas", "AvoidHazards"),
				new Presentation("Monturas", "Evitar peligros sin jinete", 943, advanced: false)
			},
			{
				new ConfigDefinition("Monturas", "ArrivalDistance"),
				new Presentation("Monturas", "Distancia de llegada al jugador (m)", 942, advanced: true)
			},
			{
				new ConfigDefinition("Monturas", "GuardRadius"),
				new Presentation("Monturas", "Radio de paseo estacionada (m)", 941, advanced: false)
			},
			{
				new ConfigDefinition("Monturas", "DetectionRadius"),
				new Presentation("Monturas", "Detección máxima sin jinete (m)", 940, advanced: false)
			},
			{
				new ConfigDefinition("Monturas", "MountedDetectionRadius"),
				new Presentation("Monturas", "Percepción mínima con jinete (m)", 939, advanced: true)
			},
			{
				new ConfigDefinition("Monturas", "ChaseRadius"),
				new Presentation("Monturas", "Límite de defensa desde el hogar (m)", 938, advanced: false)
			},
			{
				new ConfigDefinition("Monturas", "CallStuckSeconds"),
				new Presentation("Monturas", "Llamada: espera sin avance (s)", 937, advanced: true)
			},
			{
				new ConfigDefinition("Monturas", "GuardStuckSeconds"),
				new Presentation("Monturas", "Guardia: espera sin avance (s)", 936, advanced: true)
			},
			{
				new ConfigDefinition("Monturas", "RescueCooldownSeconds"),
				new Presentation("Monturas", "Espera entre recuperaciones (s)", 935, advanced: true)
			},
			{
				new ConfigDefinition("Monturas", "CallRange"),
				new Presentation("Monturas", "Alcance del silbido (m)", 934, advanced: false)
			},
			{
				new ConfigDefinition("Monturas", "HornCooldownSeconds"),
				new Presentation("Monturas", "Espera entre usos del cuerno (s)", 933, advanced: false)
			},
			{
				new ConfigDefinition("Monturas", "RidingRegenBonusAt100"),
				new Presentation("Monturas", "Regeneración de estamina a Equitación 100 (%)", 932, advanced: false)
			},
			{
				new ConfigDefinition("Teclas locales", "MountCall"),
				new Presentation("Comandos", "Llamar a tu montura", 1999, advanced: false)
			},
			{
				new ConfigDefinition("Audio local", "MountWhistleFile"),
				new Presentation("Interfaz y Audio", "Archivo del silbido de montura", 930, advanced: true)
			},
			{
				new ConfigDefinition("Audio local", "MountHornFile"),
				new Presentation("Interfaz y Audio", "Archivo del cuerno", 929, advanced: true)
			},
			{
				new ConfigDefinition("Audio local", "MountWhistleVolume"),
				new Presentation("Interfaz y Audio", "Volumen del silbido de montura", 928, advanced: false)
			},
			{
				new ConfigDefinition("Defensa", "BossArmorEnabled"),
				new Presentation("Mejoras de progresión", "Aumentar armadura por jefes", 927, advanced: false)
			},
			{
				new ConfigDefinition("Defensa", "WolfArmorPerBoss"),
				new Presentation("Mejoras de progresión", "Lobo: armadura por jefe", 926, advanced: false)
			},
			{
				new ConfigDefinition("Defensa", "WolfArmorCap"),
				new Presentation("Mejoras de progresión", "Lobo: tope de armadura adicional", 925, advanced: false)
			},
			{
				new ConfigDefinition("Defensa", "LoxArmorPerBoss"),
				new Presentation("Mejoras de progresión", "Luey: armadura por jefe", 924, advanced: false)
			},
			{
				new ConfigDefinition("Defensa", "LoxArmorCap"),
				new Presentation("Mejoras de progresión", "Luey: tope de armadura adicional", 923, advanced: false)
			},
			{
				new ConfigDefinition("Defensa", "AsksvinArmorPerBoss"),
				new Presentation("Mejoras de progresión", "Asksvin: armadura por jefe", 922, advanced: false)
			},
			{
				new ConfigDefinition("Defensa", "AsksvinArmorCap"),
				new Presentation("Mejoras de progresión", "Asksvin: tope de armadura adicional", 921, advanced: false)
			},
			{
				new ConfigDefinition("Defensa", "MooseArmorPerBoss"),
				new Presentation("Mejoras de progresión", "Alce: armadura por jefe", 920, advanced: false)
			},
			{
				new ConfigDefinition("Defensa", "MooseArmorCap"),
				new Presentation("Mejoras de progresión", "Alce: tope de armadura adicional", 919, advanced: false)
			},
			{
				new ConfigDefinition("Alforjas", "Enabled"),
				new Presentation("Monturas", "Activar alforjas", 918, advanced: false)
			},
			{
				new ConfigDefinition("Alforjas", "RespectTeleportRestrictions"),
				new Presentation("Monturas", "Respetar restricciones de teletransporte", 917, advanced: false)
			},
			{
				new ConfigDefinition("Teclas locales", "MountStorageModifier"),
				new Presentation("Comandos", "Modificador para retirar la silla", 1998, advanced: false)
			},
			{
				new ConfigDefinition("Animales domesticados", "TamedWildHostility"),
				new Presentation("Animales domesticados", "Hostilidad entre domesticados y salvajes", 915, advanced: false)
			},
			{
				new ConfigDefinition("Mapa local", "ShowTamedWolves"),
				new Presentation("Mapa", "Mostrar lobos y crías", 1997, advanced: false)
			},
			{
				new ConfigDefinition("Mapa local", "WolfIconScale"),
				new Presentation("Mapa", "Tamaño de iconos de lobos", 1996, advanced: false)
			},
			{
				new ConfigDefinition("Mapa local", "ShowWolfNames"),
				new Presentation("Mapa", "Mostrar nombres de lobos", 1995, advanced: false)
			},
			{
				new ConfigDefinition("Mapa local", "ShowRegisteredMounts"),
				new Presentation("Mapa", "Mostrar monturas vinculadas", 1994, advanced: false)
			},
			{
				new ConfigDefinition("Mapa local", "MountIconScale"),
				new Presentation("Mapa", "Tamaño de iconos de monturas", 1993, advanced: false)
			},
			{
				new ConfigDefinition("Mapa local", "ShowMountNames"),
				new Presentation("Mapa", "Mostrar nombres de monturas", 1992, advanced: false)
			},
			{
				new ConfigDefinition("Audio local", "WhistleFile"),
				new Presentation("Interfaz y Audio", "Archivo del silbido de lobos", 907, advanced: true)
			},
			{
				new ConfigDefinition("Audio local", "WolfWhistleVolume"),
				new Presentation("Interfaz y Audio", "Volumen del silbido de lobos", 1000, advanced: false)
			},
			{
				new ConfigDefinition("Audio local", "MountHornVolume"),
				new Presentation("Interfaz y Audio", "Volumen del Cuerno de llamada", 999, advanced: false)
			},
			{
				new ConfigDefinition("Teclas locales", "MountStorageOpen"),
				new Presentation("Comandos", "Abrir alforjas de tu montura", 1997, advanced: false)
			},
			{
				new ConfigDefinition("Alforjas", "Slots"),
				new Presentation("Monturas", "Capacidad de alforjas (casillas)", 917, advanced: false)
			},
			{
				new ConfigDefinition("Animales domesticados", "HostileToPassive"),
				new Presentation("Animales domesticados", "Atacar criaturas pasivas", 914, advanced: false)
			}
		};

		internal static readonly string[] CategoryOrder = new string[9] { "General", "Animales domesticados", "Lobos", "Invocaciones", "Monturas", "Mejoras de progresión", "Mapa", "Comandos", "Interfaz y Audio" };

		internal static int CategoryRank(string category)
		{
			int num = Array.IndexOf(CategoryOrder, category);
			if (num >= 0)
			{
				return num;
			}
			return int.MaxValue;
		}

		internal static void Apply(ConfigEntryBase entry, ConfigurationManagerAttributes attrs)
		{
			if (entry != null && attrs != null && Entries.TryGetValue(entry.Definition, out var value))
			{
				attrs.Category = value.Category;
				attrs.DispName = value.Name;
				attrs.Order = value.Order;
				attrs.IsAdvanced = value.Advanced;
				if (value.RawFraction)
				{
					attrs.ShowRangeAsPercent = false;
				}
			}
		}
	}
	internal static class ConfigurationPacketPolicy
	{
		internal const string FileIdentifier = "local.valheim.wolfguard.cfg";

		private const int MaximumBytes = 16777216;

		private static readonly Encoding StrictUtf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);

		internal static bool TryExcludeOwn(byte[] source, out byte[] filtered, out int removed)
		{
			filtered = null;
			removed = 0;
			if (source == null || source.Length < 5 || source.Length > 16777216)
			{
				return false;
			}
			int num = source[1] | (source[2] << 8) | (source[3] << 16) | (source[4] << 24);
			if (num < 0 || num > (source.Length - 5) / 4)
			{
				return false;
			}
			List<(int, int)> list = new List<(int, int)>();
			int position = 5;
			try
			{
				for (int i = 0; i < num; i++)
				{
					int num2 = position;
					string a = ReadString(source, ref position, decode: true);
					for (int j = 0; j < 3; j++)
					{
						ReadString(source, ref position, decode: false);
					}
					if (string.Equals(a, "local.valheim.wolfguard.cfg", StringComparison.Ordinal))
					{
						removed++;
					}
					else
					{
						list.Add((num2, position - num2));
					}
				}
				if (position != source.Length)
				{
					return false;
				}
				if (removed == 0)
				{
					filtered = source;
					return true;
				}
				using (MemoryStream memoryStream = new MemoryStream(source.Length))
				{
					using BinaryWriter binaryWriter = new BinaryWriter(memoryStream, Encoding.UTF8, leaveOpen: true);
					binaryWriter.Write(source[0]);
					binaryWriter.Write(num - removed);
					foreach (var item in list)
					{
						binaryWriter.Write(source, item.Item1, item.Item2);
					}
					binaryWriter.Flush();
					filtered = memoryStream.ToArray();
				}
				return true;
			}
			catch (Exception ex) when (ex is InvalidDataException || ex is DecoderFallbackException)
			{
				return false;
			}
		}

		private static string ReadString(byte[] source, ref int position, bool decode)
		{
			uint num = 0u;
			bool flag = false;
			for (int i = 0; i <= 28; i += 7)
			{
				if (position >= source.Length)
				{
					throw new InvalidDataException();
				}
				byte b = source[position++];
				if (i == 28 && b > 7)
				{
					throw new InvalidDataException();
				}
				num |= (uint)((b & 0x7F) << i);
				if ((b & 0x80) == 0)
				{
					flag = true;
					break;
				}
			}
			if (!flag || num > source.Length - position)
			{
				throw new InvalidDataException();
			}
			string result = (decode ? StrictUtf8.GetString(source, position, (int)num) : null);
			position += (int)num;
			return result;
		}
	}
	internal static class ConfigurationPresentation
	{
		private static readonly HashSet<ConfigEntryBase> Entries = new HashSet<ConfigEntryBase>();

		private static readonly HashSet<ConfigurationManagerAttributes> Rules = new HashSet<ConfigurationManagerAttributes>();

		private static readonly Dictionary<ConfigEntryBase, GUIContent> Indicators = new Dictionary<ConfigEntryBase, GUIContent>();

		private static readonly FieldInfo DescriptionField = AccessTools.Field(typeof(ConfigEntryBase), "<Description>k__BackingField");

		private static readonly MethodInfo UnlockSetter = AccessTools.PropertySetter(typeof(ConfigurationManagerAttributes), "IsUnlocked");

		private static Harmony patches;

		private static PropertyInfo entryProperty;

		private static MethodInfo indicatorStyle;

		private static MethodInfo tooltipButton;

		private static FieldInfo fixedWidth;

		private static FieldInfo fontColor;

		private static FieldInfo filteredSettings;

		private static FieldInfo pluginInfo;

		private static FieldInfo categories;

		private static FieldInfo categoryName;

		private static bool categoryOrderFaulted;

		private static ConfigFile config;

		private static bool endingSession;

		private static bool indicatorFaulted;

		private static bool indicatorInstalled;

		private static bool CanEditRules
		{
			get
			{
				if (!endingSession && Object.op_Implicit((Object)(object)ZNet.instance))
				{
					return ZNet.instance.IsServer();
				}
				return true;
			}
		}

		internal static void Initialize(ConfigFile file)
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Expected O, but got Unknown
			config = file ?? throw new ArgumentNullException("file");
			Apply();
			if (patches != null)
			{
				return;
			}
			if (typeof(SynchronizationManager).Assembly.GetName().Version != new Version(2, 30, 2, 0))
			{
				throw new NotSupportedException("SagaCompanions host authority requires the verified Jotunn 2.30.2 protocol.");
			}
			patches = new Harmony("local.valheim.wolfguard.configuration");
			try
			{
				PatchRequired(typeof(SynchronizationManager), "ConfigRPC_OnServerReceive", "FilterServer", new Type[2]
				{
					typeof(long),
					typeof(ZPackage)
				});
				PatchRequired(typeof(SynchronizationManager), "ConfigRPC_OnClientReceive", "FilterClient", new Type[2]
				{
					typeof(long),
					typeof(ZPackage)
				});
				PatchRequired(typeof(ConfigurationManagerAttributes), "set_IsUnlocked", "KeepRulesLocked", new Type[1] { typeof(bool) });
				PatchRequired(typeof(ZNet), "Awake", "BeginSession", Type.EmptyTypes);
				PatchRequired(typeof(ZNet), "Shutdown", "EndSession", new Type[1] { typeof(bool) });
				PatchRequired(typeof(ZNet), "ShutdownWithoutSave", "EndSession", new Type[1] { typeof(bool) });
				PatchRequired(typeof(ZNet), "OnDestroy", "EndSession", Type.EmptyTypes);
				TryInstallIndicator();
				string text = ((!Object.op_Implicit((Object)(object)ZNet.instance)) ? "menu" : (ZNet.instance.IsServer() ? "host" : "client"));
				ManualLogSource log = WolfPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)$"SAGACOMPANIONS_CONFIG_READY synchronized={Rules.Count} personal={Entries.Count - Rules.Count} hostOnly=true nativeIndicators={indicatorInstalled} rulesEditable={CanEditRules} context={text}");
				}
			}
			catch
			{
				patches.UnpatchSelf();
				patches = null;
				throw;
			}
		}

		internal static void Apply()
		{
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Expected O, but got Unknown
			if (config == null)
			{
				return;
			}
			foreach (KeyValuePair<ConfigDefinition, ConfigEntryBase> item in config)
			{
				ConfigEntryBase value = item.Value;
				ConfigurationManagerAttributes val = EnsureAttributes(value);
				ConfigurationMetadata.Apply(value, val);
				Entries.Add(value);
				if (val.IsAdminOnly)
				{
					Rules.Add(val);
				}
				SetUnlocked(val, !val.IsAdminOnly || CanEditRules);
				Indicators[value] = new GUIContent(val.IsAdminOnly ? "S" : "C", val.IsAdminOnly ? "Sincronizado. Solo lo cambia el anfitrión o el proceso del servidor dedicado." : "Personal. Se guarda en este equipo y no se sincroniza con otros jugadores.");
			}
		}

		private static ConfigurationManagerAttributes EnsureAttributes(ConfigEntryBase entry)
		{
			//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_002a: Expected O, but got Unknown
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Expected O, but got Unknown
			ConfigDescription description = entry.Description;
			ConfigurationManagerAttributes val = description.Tags.OfType<ConfigurationManagerAttributes>().FirstOrDefault();
			if (val != null)
			{
				return val;
			}
			val = new ConfigurationManagerAttributes
			{
				IsAdminOnly = false
			};
			if (DescriptionField == null)
			{
				throw new MissingFieldException("BepInEx ConfigEntryBase.Description metadata");
			}
			DescriptionField.SetValue(entry, (object?)new ConfigDescription(description.Description, description.AcceptableValues, description.Tags.Concat(new object[1] { val }).ToArray()));
			return val;
		}

		private static void SetUnlocked(ConfigurationManagerAttributes attrs, bool value)
		{
			if (UnlockSetter == null)
			{
				throw new MissingMethodException("Jotunn ConfigurationManagerAttributes.IsUnlocked setter");
			}
			UnlockSetter.Invoke(attrs, new object[1] { value });
		}

		private static void KeepRulesLocked(ConfigurationManagerAttributes __instance, ref bool value)
		{
			if (Rules.Contains(__instance) && !CanEditRules)
			{
				value = false;
			}
		}

		private static void BeginSession()
		{
			endingSession = false;
		}

		private static void EndSession(ZNet __instance)
		{
			if (Object.op_Implicit((Object)(object)ZNet.instance) && ZNet.instance != __instance)
			{
				return;
			}
			endingSession = true;
			foreach (ConfigurationManagerAttributes rule in Rules)
			{
				SetUnlocked(rule, value: true);
			}
		}

		private static void PatchRequired(Type type, string method, string prefix, Type[] signature)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method(type, method, signature, (Type[])null);
			if (methodInfo == null)
			{
				throw new MissingMethodException(type.FullName, method);
			}
			patches.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(ConfigurationPresentation), prefix, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static bool FilterServer(ref ZPackage package, ref IEnumerator __result)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance) || !ZNet.instance.IsServer())
			{
				return true;
			}
			return Filter(ref package, ref __result);
		}

		private static bool FilterClient(long sender, ref ZPackage package, ref IEnumerator __result)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance) || ZNet.instance.IsServer())
			{
				return true;
			}
			ZNetPeer serverPeer = ZNet.instance.GetServerPeer();
			if (serverPeer != null && sender == serverPeer.m_uid)
			{
				return true;
			}
			return Filter(ref package, ref __result);
		}

		private static bool Filter(ref ZPackage package, ref IEnumerator result)
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			if (package == null || !ConfigurationPacketPolicy.TryExcludeOwn(package.GetArray(), out var filtered, out var removed))
			{
				result = Empty();
				ManualLogSource log = WolfPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)"SAGACOMPANIONS_CONFIG rejected malformed configuration proposal; no values applied.");
				}
				return false;
			}
			if (removed == 0)
			{
				return true;
			}
			package = new ZPackage(filtered);
			if (filtered.Length > 5)
			{
				return true;
			}
			result = Empty();
			return false;
		}

		private static IEnumerator Empty()
		{
			yield break;
		}

		private static void TryInstallIndicator()
		{
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Expected O, but got Unknown
			PluginInfo val = ((IEnumerable<PluginInfo>)Chainloader.PluginInfos.Values).FirstOrDefault((Func<PluginInfo, bool>)((PluginInfo info) => Object.op_Implicit((Object)(object)info.Instance) && ((object)info.Instance).GetType().Assembly.GetName().Name == "ConfigurationManager"));
			if (val == null)
			{
				return;
			}
			try
			{
				Assembly assembly = ((object)val.Instance).GetType().Assembly;
				Type type = assembly.GetType("ConfigurationManager.ConfigurationManager", throwOnError: true);
				Type type2 = assembly.GetType("ConfigurationManager.ConfigSettingEntry", throwOnError: true);
				Type type3 = assembly.GetType("ConfigurationManager.SettingEntryBase", throwOnError: true);
				entryProperty = AccessTools.Property(type2, "Entry");
				indicatorStyle = AccessTools.Method(assembly.GetType("ConfigurationManager.ConfigurationManagerStyles", throwOnError: true), "GetSynchronizationIndicatorStyle", (Type[])null, (Type[])null);
				tooltipButton = AccessTools.Method(assembly.GetType("ConfigurationManager.Utilities.GUITooltips", throwOnError: true), "Button", new Type[3]
				{
					typeof(GUIContent),
					typeof(GUIStyle),
					typeof(GUILayoutOption[])
				}, (Type[])null);
				fixedWidth = AccessTools.Field(assembly.GetType("ConfigurationManager.Utilities.GUIHelper", throwOnError: true), "FixedWidth");
				fontColor = AccessTools.Field(type, "_fontColor");
				MethodInfo methodInfo = AccessTools.Method(type, "DrawSynchronizationIndicator", new Type[2]
				{
					type3,
					typeof(bool)
				}, (Type[])null);
				if (entryProperty == null || indicatorStyle == null || tooltipButton == null || fixedWidth == null || fontColor == null || methodInfo == null)
				{
					throw new MissingMemberException("ConfigurationManager synchronization indicator API");
				}
				patches.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(ConfigurationPresentation), "DrawIndicator", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				indicatorInstalled = true;
				TryInstallCategoryOrder(type);
			}
			catch (Exception ex)
			{
				ManualLogSource log = WolfPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("SAGACOMPANIONS_CONFIG optional S/C display unavailable: " + ex.Message));
				}
			}
		}

		private static void TryInstallCategoryOrder(Type manager)
		{
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Expected O, but got Unknown
			try
			{
				Type? nestedType = manager.GetNestedType("PluginSettingsData", BindingFlags.Public | BindingFlags.NonPublic);
				Type type = nestedType?.GetNestedType("PluginSettingsGroupData", BindingFlags.Public | BindingFlags.NonPublic);
				filteredSettings = AccessTools.Field(manager, "_filteredSetings");
				pluginInfo = AccessTools.Field(nestedType, "Info");
				categories = AccessTools.Field(nestedType, "Categories");
				categoryName = AccessTools.Field(type, "Name");
				MethodInfo methodInfo = AccessTools.Method(manager, "RebuildFilteredSettingList", Type.EmptyTypes, (Type[])null);
				if (filteredSettings == null || pluginInfo == null || categories == null || categoryName == null || methodInfo == null)
				{
					throw new MissingMemberException("ConfigurationManager category list API");
				}
				patches.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(ConfigurationPresentation), "OrderCategories", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			catch (Exception ex)
			{
				ManualLogSource log = WolfPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("SAGACOMPANIONS_CONFIG category ordering unavailable: " + ex.Message));
				}
			}
		}

		private static void OrderCategories(object __instance)
		{
			if (categoryOrderFaulted)
			{
				return;
			}
			try
			{
				if (!(filteredSettings.GetValue(__instance) is IList list))
				{
					return;
				}
				foreach (object item in list)
				{
					object? value = pluginInfo.GetValue(item);
					BepInPlugin val = (BepInPlugin)((value is BepInPlugin) ? value : null);
					if (val != null && !(val.GUID != "local.valheim.wolfguard") && categories.GetValue(item) is IList list2)
					{
						object[] array = (from object @group in list2
							orderby ConfigurationMetadata.CategoryRank((string)categoryName.GetValue(@group))
							select @group).ToArray();
						for (int num = 0; num < array.Length; num++)
						{
							list2[num] = array[num];
						}
					}
				}
			}
			catch (Exception ex)
			{
				categoryOrderFaulted = true;
				ManualLogSource log = WolfPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("SAGACOMPANIONS_CONFIG category ordering disabled: " + ex.Message));
				}
			}
		}

		private static bool DrawIndicator(object __0)
		{
			//IL_014e: 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_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			if (indicatorFaulted || __0 == null || !entryProperty.DeclaringType.IsInstanceOfType(__0))
			{
				return true;
			}
			object? value = entryProperty.GetValue(__0);
			ConfigEntryBase val = (ConfigEntryBase)((value is ConfigEntryBase) ? value : null);
			if (val == null || !Entries.Contains(val) || val.ConfigFile != config)
			{
				return true;
			}
			bool enabled = GUI.enabled;
			Color contentColor = GUI.contentColor;
			try
			{
				GUI.enabled = false;
				GUI.contentColor = Color.white;
				ConfigEntry<Color> val2 = fontColor.GetValue(null) as ConfigEntry<Color>;
				GUIContent val3 = Indicators[val];
				string text = val3.text;
				val3.text = "<color=#" + ColorUtility.ToHtmlStringRGBA(val2?.Value ?? Color.white) + ">" + text + "</color>";
				try
				{
					tooltipButton.Invoke(null, new object[3]
					{
						val3,
						indicatorStyle.Invoke(null, null),
						fixedWidth.GetValue(null)
					});
				}
				finally
				{
					val3.text = text;
				}
			}
			catch (Exception ex)
			{
				indicatorFaulted = true;
				ManualLogSource log = WolfPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("SAGACOMPANIONS_CONFIG optional S/C display disabled after drawing failed: " + ex.Message));
				}
				return true;
			}
			finally
			{
				GUI.enabled = enabled;
				GUI.contentColor = contentColor;
			}
			return false;
		}

		internal static void Shutdown()
		{
			Harmony obj = patches;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			patches = null;
			Entries.Clear();
			Rules.Clear();
			Indicators.Clear();
			config = null;
			indicatorFaulted = false;
			indicatorInstalled = false;
			categoryOrderFaulted = false;
		}
	}
	internal static class ConfigurationUpgrade
	{
		internal static bool Needs092(string original)
		{
			return NeedsBefore(original, new Version(0, 9, 2));
		}

		internal static bool Needs094(string original)
		{
			return NeedsBefore(original, new Version(0, 9, 4));
		}

		internal static bool Needs101(string original)
		{
			return NeedsBefore(original, new Version(1, 0, 1));
		}

		internal static bool Needs105(string original)
		{
			return NeedsBefore(original, new Version(1, 0, 5));
		}

		private static bool NeedsBefore(string original, Version next)
		{
			Match match = Regex.Match(original ?? "", "(?m)^## Settings file was created by plugin (?:WolfGuard|SagaCompanions) v(\\d+\\.\\d+\\.\\d+)(?:\\r?$)");
			if (match.Success && Version.TryParse(match.Groups[1].Value, out Version result))
			{
				return result < next;
			}
			return false;
		}

		internal static bool Capture(string path)
		{
			return CaptureFile(path, Needs092);
		}

		internal static bool Capture094(string path)
		{
			return CaptureFile(path, Needs094);
		}

		internal static bool Capture101(string path)
		{
			return CaptureFile(path, Needs101);
		}

		internal static bool Capture105(string path)
		{
			return CaptureFile(path, Needs105);
		}

		private static bool CaptureFile(string path, Func<string, bool> needed)
		{
			try
			{
				return File.Exists(path) && needed(File.ReadAllText(path));
			}
			catch (IOException ex)
			{
				ManualLogSource log = WolfPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("SAGACOMPANIONS_CONFIG migration skipped: " + ex.Message));
				}
				return false;
			}
			catch (UnauthorizedAccessException ex2)
			{
				ManualLogSource log2 = WolfPlugin.Log;
				if (log2 != null)
				{
					log2.LogWarning((object)("SAGACOMPANIONS_CONFIG migration skipped: " + ex2.Message));
				}
				return false;
			}
		}

		internal static int Apply101(ConfigFile config, bool needed)
		{
			if (!needed)
			{
				return 0;
			}
			int num = ReplaceDefault(config, "Invocaciones", "StuckSeconds", 4f, 3f);
			config.Save();
			ManualLogSource log = WolfPlugin.Log;
			if (log != null)
			{
				log.LogInfo((object)$"SAGACOMPANIONS_CONFIG upgraded101={num}; custom summon delay retained; wolf recovery and rescue cooldown unchanged.");
			}
			return num;
		}

		internal static int Apply105(ConfigFile config, bool needed)
		{
			if (!needed)
			{
				return 0;
			}
			int num = 0;
			int num2 = 0;
			bool saveOnConfigSet = config.SaveOnConfigSet;
			config.SaveOnConfigSet = false;
			try
			{
				num = ReplaceDefault(config, "Monturas", "RidingRegenBonusAt100", 30f, 50f);
				num2 = ReplaceDefault(config, "Invocaciones", "RescueCooldown", 8f, 4f);
			}
			finally
			{
				config.SaveOnConfigSet = saveOnConfigSet;
			}
			int num3 = num + num2;
			config.Save();
			ManualLogSource log = WolfPlugin.Log;
			if (log != null)
			{
				log.LogInfo((object)$"SAGACOMPANIONS_CONFIG upgraded105={num3} ridingRegenDefaultsUpdated={num} summonCooldownDefaultsUpdated={num2}; non-default values retained; summon stuck delay, radii, navigation, shared rescue budget and native stamina consumption unchanged.");
			}
			return num3;
		}

		internal static int Apply094(ConfigFile config, bool needed)
		{
			if (!needed)
			{
				return 0;
			}
			int num = ReplaceDefault(config, "Ordenes", "CommandRange", 60f, 120f);
			config.Save();
			ManualLogSource log = WolfPlugin.Log;
			if (log != null)
			{
				log.LogInfo((object)$"SAGACOMPANIONS_CONFIG upgraded094={num}; custom command ranges retained; automatic chase/recovery unchanged.");
			}
			return num;
		}

		internal static int Apply092(ConfigFile config, bool needed)
		{
			if (!needed)
			{
				return 0;
			}
			int num = 0;
			bool saveOnConfigSet = config.SaveOnConfigSet;
			config.SaveOnConfigSet = false;
			try
			{
				num += ReplaceDefault(config, "Regeneracion", "InCombatPercentPerSecond", 0.15f, 0.35f);
				num += ReplaceDefault(config, "Regeneracion", "OutOfCombatPercentPerSecond", 0.4f, 1f);
				num += ReplaceDefault(config, "Defensa", "WolfArmorPerBoss", 10f, 15f);
				num += ReplaceDefault(config, "Defensa", "LoxArmorPerBoss", 5f, 10f);
				num += ReplaceDefault(config, "Defensa", "AsksvinArmorPerBoss", 10f, 15f);
				num += ReplaceDefault(config, "Defensa", "MooseArmorPerBoss", 10f, 15f);
				num += ReplaceDefault(config, "Defensa", "WolfArmorCap", 50f, 75f);
				num += ReplaceDefault(config, "Defensa", "LoxArmorCap", 20f, 40f);
				num += ReplaceDefault(config, "Defensa", "AsksvinArmorCap", 20f, 30f);
				num += ReplaceDefault(config, "Defensa", "MooseArmorCap", 10f, 15f);
			}
			finally
			{
				config.SaveOnConfigSet = saveOnConfigSet;
			}
			config.Save();
			ManualLogSource log = WolfPlugin.Log;
			if (log != null)
			{
				log.LogInfo((object)$"SAGACOMPANIONS_CONFIG upgraded092={num}; custom values retained; navigation/radii unchanged.");
			}
			return num;
		}

		private static int ReplaceDefault(ConfigFile config, string section, string key, float oldValue, float next)
		{
			ConfigEntry<float> val = default(ConfigEntry<float>);
			if (!config.TryGetEntry<float>(section, key, ref val) || Math.Abs(val.Value - oldValue) > 1E-05f)
			{
				return 0;
			}
			val.Value = next;
			return 1;
		}
	}
	internal static class LifecyclePatches
	{
		private sealed class BirthContext
		{
			internal WolfSnapshot Snapshot;

			internal bool Growth;

			internal bool Applied;

			internal Character Source;
		}

		[HarmonyPatch(typeof(Character), "Awake")]
		private static class Attach
		{
			private static void Postfix(Character __instance)
			{
				if (Settings.Enabled && WolfState.IsWolf(__instance))
				{
					WolfState.For(__instance);
				}
			}
		}

		[HarmonyPatch(typeof(Procreation), "Procreate")]
		private static class Birth
		{
			private static void Prefix(Procreation __instance, out BirthContext __state)
			{
				__state = Enter(((Component)__instance).GetComponent<Character>(), growth: false);
			}

			private static Exception Finalizer(Exception __exception, BirthContext __state)
			{
				Leave(__state);
				return __exception;
			}
		}

		[HarmonyPatch(typeof(Growup), "GrowUpdate")]
		private static class Grow
		{
			private static void Prefix(Growup __instance, out BirthContext __state)
			{
				__state = Enter(((Component)__instance).GetComponent<Character>(), growth: true);
			}

			private static Exception Finalizer(Exception __exception, BirthContext __state)
			{
				Leave(__state);
				return __exception;
			}
		}

		[HarmonyPatch(typeof(Character), "SetTamed")]
		private static class Transfer
		{
			private static void Postfix(Character __instance, bool tamed)
			{
				if (!Settings.Enabled || !tamed || contexts == null || contexts.Count == 0 || !Object.op_Implicit((Object)(object)__instance))
				{
					return;
				}
				BirthContext birthContext = contexts.Peek();
				if (birthContext.Applied || (Object)(object)__instance == (Object)(object)birthContext.Source)
				{
					return;
				}
				string text = (birthContext.Growth ? "Wolf" : "Wolf_cub");
				if (WolfState.PrefabName(((Component)__instance).gameObject) != text)
				{
					return;
				}
				WolfState wolfState = WolfState.For(__instance);
				if (Object.op_Implicit((Object)(object)wolfState) && wolfState.IsOwner && __instance.IsTamed())
				{
					wolfState.Inherit(birthContext.Snapshot, birthContext.Growth);
					birthContext.Applied = true;
					if (birthContext.Growth)
					{
						WolfTestCommands.ObserveGrowth(birthContext.Source, wolfState);
					}
				}
			}
		}

		[HarmonyPatch(typeof(Tameable), "UpdateSavedFollowTarget")]
		private static class PreventNameBasedRestore
		{
			private static bool Prefix(Tameable __instance)
			{
				if (!Settings.Enabled)
				{
					return true;
				}
				WolfState component = ((Component)__instance).GetComponent<WolfState>();
				if (Object.op_Implicit((Object)(object)component))
				{
					return !component.Ready;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Tameable), "RPC_Command")]
		private static class ProtectNativeCommands
		{
			private static bool Prefix(Tameable __instance)
			{
				if (!Settings.Enabled)
				{
					return true;
				}
				Character component = ((Component)__instance).GetComponent<Character>();
				if (Object.op_Implicit((Object)(object)component) && component.IsTamed())
				{
					return !WolfState.IsWolf(component);
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Tameable), "Interact")]
		private static class Interact
		{
			private static bool Prefix(Tameable __instance, Humanoid user, bool hold, bool alt, ref bool __result)
			{
				if (!Settings.Enabled)
				{
					return true;
				}
				Character component = ((Component)__instance).GetComponent<Character>();
				if (!Object.op_Implicit((Object)(object)component) || !component.IsTamed() || !WolfState.IsWolf(component))
				{
					return true;
				}
				if (alt)
				{
					return true;
				}
				__result = false;
				if (!hold)
				{
					Player val = (Player)(object)((user is Player) ? user : null);
					if (val != null)
					{
						WolfState wolfState = WolfState.For(component);
						WolfCommands.Request(wolfState, wolfState.Follows(val) ? WolfOrder.GuardHere : WolfOrder.Follow, val);
						__result = true;
						return false;
					}
				}
				return false;
			}
		}

		[ThreadStatic]
		private static Stack<BirthContext> contexts;

		private static BirthContext Enter(Character source, bool growth)
		{
			if (!Settings.Enabled || !Object.op_Implicit((Object)(object)source) || !source.IsTamed() || !WolfState.IsWolf(source))
			{
				return null;
			}
			WolfState wolfState = WolfState.For(source);
			if (!Object.op_Implicit((Object)(object)wolfState) || !wolfState.IsOwner)
			{
				return null;
			}
			BirthContext birthContext = new BirthContext
			{
				Source = source,
				Growth = growth,
				Snapshot = wolfState.Snapshot()
			};
			if (birthContext.Snapshot == null)
			{
				return null;
			}
			if (contexts == null)
			{
				contexts = new Stack<BirthContext>();
			}
			contexts.Push(birthContext);
			return birthContext;
		}

		private static void Leave(BirthContext context)
		{
			if (context != null && contexts != null && contexts.Count != 0)
			{
				if (contexts.Peek() == context)
				{
					contexts.Pop();
				}
				else
				{
					contexts.Clear();
				}
			}
		}
	}
	internal static class MountAwareness
	{
		private sealed class Observation
		{
			internal double NextScan;

			internal double AlertUntil;

			internal double LastScan = -1.0;

			internal bool LastThreat;

			internal bool IntroducedAlert;
		}

		private const double ScanInterval = 1.0;

		private const double AlertMemory = 10.0;

		private static readonly Action<BaseAI, bool> SetAlerted = AccessTools.MethodDelegate<Action<BaseAI, bool>>(AccessTools.Method(typeof(BaseAI), "SetAlerted", (Type[])null, (Type[])null), (object)null, true);

		private static readonly FieldRef<BaseAI, float> SinceHurt = AccessTools.FieldRefAccess<BaseAI, float>("m_timeSinceHurt");

		private static ConditionalWeakTable<MonsterAI, Observation> observations = new ConditionalWeakTable<MonsterAI, Observation>();

		internal static void Reset()
		{
			observations = new ConditionalWeakTable<MonsterAI, Observation>();
		}

		internal static void AfterNativeUpdate(MonsterAI ai, float dt)
		{
			using (WolfPerf.Measure())
			{
				Tick(ai, Time.realtimeSinceStartupAsDouble);
			}
		}

		internal static string Describe(MountState state)
		{
			if (!Object.op_Implicit((Object)(object)state) || !Object.op_Implicit((Object)(object)state.AI))
			{
				return "awareness=unavailable";
			}
			double realtimeSinceStartupAsDouble = Time.realtimeSinceStartupAsDouble;
			observations.TryGetValue(state.AI, out var value);
			string text = ((value == null) ? "none" : (((BaseAI)state.AI).HaveRider() ? "mounted" : "dismount-memory"));
			return FormattableString.Invariant($"mountedDetection={MountSettings.MountedDetectRange:0.#}m alerted={((BaseAI)state.AI).IsAlerted()} perceived={value?.LastThreat ?? false} awarenessMode={text} awarenessRemaining={Math.Max(0.0, (value?.AlertUntil ?? 0.0) - realtimeSinceStartupAsDouble):0.0}s perceptionAge={((value != null && value.LastScan >= 0.0) ? Math.Max(0.0, realtimeSinceStartupAsDouble - value.LastScan) : (-1.0)):0.0}s");
		}

		internal static void Tick(MonsterAI ai, double now)
		{
			if (!Object.op_Implicit((Object)(object)ai) || double.IsNaN(now) || double.IsInfinity(now))
			{
				return;
			}
			MountState component = ((Component)ai).GetComponent<MountState>();
			if (!MountSettings.Enabled || !Object.op_Implicit((Object)(object)component) || !component.Ready || !component.IsOwner)
			{
				if (observations.TryGetValue(ai, out var value))
				{
					if (Object.op_Implicit((Object)(object)component) && component.IsOwner)
					{
						ReleaseAlert(ai, value);
					}
					observations.Remove(ai);
				}
				return;
			}
			if (!((BaseAI)ai).HaveRider())
			{
				if (observations.TryGetValue(ai, out var value2))
				{
					if (now < value2.AlertUntil)
					{
						MaintainAlert(ai, value2);
						return;
					}
					ReleaseAlert(ai, value2);
					observations.Remove(ai);
				}
				return;
			}
			Observation value3 = observations.GetValue(ai, (MonsterAI _) => new Observation());
			if (now >= value3.NextScan)
			{
				value3.NextScan = now + 1.0;
				value3.LastScan = now;
				value3.LastThreat = HasPerceivedThreat(ai, component.Character);
				if (value3.LastThreat)
				{
					value3.AlertUntil = now + 10.0;
				}
			}
			if (now < value3.AlertUntil)
			{
				MaintainAlert(ai, value3);
			}
			else
			{
				ReleaseAlert(ai, value3);
			}
		}

		private static void MaintainAlert(MonsterAI ai, Observation observation)
		{
			if (!((BaseAI)ai).IsAlerted())
			{
				observation.IntroducedAlert = true;
				SetAlerted((BaseAI)(object)ai, arg2: true);
			}
		}

		private static void ReleaseAlert(MonsterAI ai, Observation observation)
		{
			if (observation.IntroducedAlert && !Object.op_Implicit((Object)(object)((BaseAI)ai).GetTargetCreature()) && !((double)SinceHurt.Invoke((BaseAI)(object)ai) < 10.0))
			{
				SetAlerted((BaseAI)(object)ai, arg2: false);
				observation.IntroducedAlert = false;
			}
		}

		internal static bool HasPerceivedThreat(MonsterAI ai, Character mount)
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)ai) || !Object.op_Implicit((Object)(object)mount) || mount.m_aiCannotTargetOthers || !Object.op_Implicit((Object)(object)mount.m_eye))
			{
				return false;
			}
			float num = Mathf.Max(((BaseAI)ai).m_hearRange, MountSettings.MountedDetectRange);
			float num2 = Mathf.Max(((BaseAI)ai).m_viewRange, MountSettings.MountedDetectRange);
			float num3 = Mathf.Max(num, num2);
			float num4 = num3 * num3;
			Vector3 position = ((Component)mount).transform.position;
			foreach (Character allCharacter in Character.GetAllCharacters())
			{
				if (!Object.op_Implicit((Object)(object)allCharacter) || (Object)(object)allCharacter == (Object)(object)mount || allCharacter.m_aiSkipTarget || allCharacter.IsDead())
				{
					continue;
				}
				Vector3 val = ((Component)allCharacter).transform.position - position;
				if (!(((Vector3)(ref val)).sqrMagnitude > num4) && BaseAI.IsEnemy(mount, allCharacter))
				{
					BaseAI baseAI = allCharacter.GetBaseAI();
					if ((!Object.op_Implicit((Object)(object)baseAI) || !baseAI.IsSleeping()) && BaseAI.CanSenseTarget(((Component)mount).transform, mount.m_eye.position, num, num2, ((BaseAI)ai).m_viewAngle, ((BaseAI)ai).IsAlerted(), ((BaseAI)ai).m_mistVision, allCharacter, ((BaseAI)ai).m_passiveAggresive, true))
					{
						return true;
					}
				}
			}
			return false;
		}
	}
	internal sealed class MountBrain : MonoBehaviour
	{
		private delegate bool MoveToDelegate(BaseAI ai, float dt, Vector3 point, float distance, bool run);

		private delegate bool BaseUpdateDelegate(BaseAI ai, float dt);

		[HarmonyPatch(typeof(MonsterAI), "UpdateAI")]
		private static class MountTick
		{
			private static bool Prefix(MonsterAI __instance, float dt, ref bool __result, out MountBrain __state)
			{
				__state = null;
				if (!MountSettings.Enabled)
				{
					((Component)__instance).GetComponent<MountBrain>()?.RestoreRanges();
					return true;
				}
				MountState component = ((Component)__instance).GetComponent<MountState>();
				if (!Object.op_Implicit((Object)(object)component))
				{
					return true;
				}
				if (!component.Ready)
				{
					((Component)__instance).GetComponent<MountBrain>()?.RestoreRanges();
					return true;
				}
				__state = Ensure(component);
				__state.BeforeTick();
				if (!CanAct(component) || !__state.evading)
				{
					return true;
				}
				__result = UpdateBase((BaseAI)(object)__instance, dt);
				return false;
			}

			private static void Postfix(MonsterAI __instance, float dt, MountBrain __state)
			{
				if (Object.op_Implicit((Object)(object)__state))
				{
					__state.AfterTick(dt);
				}
				MountAwareness.AfterNativeUpdate(__instance, dt);
			}
		}

		[HarmonyPatch(typeof(MonsterAI), "UpdateTarget")]
		private static class ShortDefense
		{
			private static void Prefix(MonsterAI __instance, out bool __state)
			{
				MountBrain component = ((Component)__instance).GetComponent<MountBrain>();
				__state = Object.op_Implicit((Object)(object)component) && CanAct(component.state) && (component.IsCalling || component.returning) && NativePatrol.Invoke((BaseAI)(object)__instance);
				if (__state)
		

plugins/SagaCompanions.Core.dll

Decompiled an hour ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using Microsoft.CodeAnalysis;

[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("SagaCompanions.Core")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.2.0")]
[assembly: AssemblyInformationalVersion("1.1.2")]
[assembly: AssemblyProduct("SagaCompanions")]
[assembly: AssemblyTitle("SagaCompanions.Core")]
[assembly: AssemblyVersion("1.1.2.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 WolfGuard.Core
{
	public static class ArmorPolicy
	{
		public const int BossCount = 5;

		public static int CountBosses(int mask, int firstBoss)
		{
			if (firstBoss < 0 || firstBoss >= 5 || (mask & (1 << firstBoss)) == 0)
			{
				return 0;
			}
			int num = 0;
			for (int i = firstBoss; i < 5; i++)
			{
				if ((mask & (1 << i)) != 0)
				{
					num++;
				}
			}
			return num;
		}

		public static float CalculateBonus(int mask, int firstBoss, float perBoss, float cap)
		{
			if (!Numbers.IsFinite(perBoss) || perBoss <= 0f || !Numbers.IsFinite(cap) || cap <= 0f)
			{
				return 0f;
			}
			return (float)Math.Min((double)CountBosses(mask, firstBoss) * (double)perBoss, cap);
		}
	}
	public static class AudioLevelPolicy
	{
		public const float MaximumSetting = 2f;

		public static float Prepare(float[] samples)
		{
			if (samples == null)
			{
				throw new ArgumentNullException("samples");
			}
			float num = 0f;
			foreach (float num2 in samples)
			{
				if (float.IsNaN(num2) || float.IsInfinity(num2) || Math.Abs(num2) > 1f)
				{
					throw new ArgumentException("PCM samples must be finite and within -1..1.", "samples");
				}
				num = Math.Max(num, Math.Abs(num2));
			}
			float num3 = ((num > 0f) ? Math.Max(1f, Math.Min(2f, 0.999f / num)) : 2f);
			for (int j = 0; j < samples.Length; j++)
			{
				samples[j] *= num3;
			}
			return num3;
		}

		public static float SourceVolume(float setting, float preparedGain, float sfxVolume)
		{
			if (float.IsNaN(setting) || float.IsInfinity(setting))
			{
				setting = 1f;
			}
			if (float.IsNaN(preparedGain) || float.IsInfinity(preparedGain) || preparedGain < 1f)
			{
				preparedGain = 1f;
			}
			if (float.IsNaN(sfxVolume) || float.IsInfinity(sfxVolume))
			{
				sfxVolume = 1f;
			}
			return Math.Max(0f, Math.Min(1f, setting / preparedGain)) * Math.Max(0f, Math.Min(1f, sfxVolume));
		}
	}
	public enum CommandDisposition
	{
		Apply,
		AlreadyApplied,
		Reject
	}
	public static class CommandPolicy
	{
		public static bool CanAuthenticate(long requestActorId, long resolvedActorId, long requestSenderPeer, long resolvedPlayerPeer, bool isPlayerAlive)
		{
			if (isPlayerAlive && requestActorId != 0L && requestActorId == resolvedActorId && requestSenderPeer != 0L)
			{
				return requestSenderPeer == resolvedPlayerPeer;
			}
			return false;
		}

		public static CommandDisposition Evaluate(long sender, long lastSender, long sequence, long lastSequence, long expectedRevision, long currentRevision, bool ordersOwnEscort = false)
		{
			if (sender == 0L || sequence <= 0 || lastSequence < 0 || expectedRevision < 0 || currentRevision < 0)
			{
				return CommandDisposition.Reject;
			}
			if (lastSender == sender)
			{
				if (sequence == lastSequence)
				{
					return CommandDisposition.AlreadyApplied;
				}
				if (sequence < lastSequence)
				{
					return CommandDisposition.Reject;
				}
			}
			bool flag = ordersOwnEscort && sender == lastSender && expectedRevision < currentRevision;
			if ((expectedRevision != currentRevision && !flag) || currentRevision == long.MaxValue)
			{
				return CommandDisposition.Reject;
			}
			return CommandDisposition.Apply;
		}

		public static bool CanApplyToMode(int order, WolfMode mode, long commanderId, long actorId, float distance, float interactionRange, float commandRange)
		{
			if (actorId == 0L || order < 0 || order > 3 || mode < WolfMode.Guard || mode > WolfMode.Hold || !Numbers.IsNonNegativeFinite(distance) || !Numbers.IsNonNegativeFinite(interactionRange) || !Numbers.IsNonNegativeFinite(commandRange))
			{
				return false;
			}
			if (order == 0)
			{
				if (distance <= interactionRange)
				{
					if (!WolfPolicy.IsStationed(mode) && commanderId != 0L)
					{
						return commanderId == actorId;
					}
					return true;
				}
				return false;
			}
			if (distance > commandRange)
			{
				return false;
			}
			if (commanderId == actorId && (mode == WolfMode.Follow || mode == WolfMode.Regroup))
			{
				return true;
			}
			if (order == 1 && commanderId == actorId && WolfPolicy.IsStationed(mode))
			{
				return distance <= interactionRange;
			}
			return false;
		}
	}
	public sealed class DietOverlay<T> where T : class
	{
		private List<T>? ownedList;

		private T? addedItem;

		private int addedIndex;

		public List<T> Apply(List<T>? current, T food, Predicate<T> matchesFood)
		{
			if (food == null)
			{
				throw new ArgumentNullException("food");
			}
			if (matchesFood == null)
			{
				throw new ArgumentNullException("matchesFood");
			}
			if (current != ownedList)
			{
				ForgetOwnership();
			}
			if (current != null)
			{
				for (int i = 0; i < current.Count; i++)
				{
					if (current[i] != null && matchesFood(current[i]))
					{
						return current;
					}
				}
			}
			List<T> list = ((current == null) ? new List<T>() : new List<T>(current));
			addedIndex = list.Count;
			list.Add(food);
			ownedList = list;
			addedItem = food;
			return list;
		}

		public List<T>? Restore(List<T>? current)
		{
			if (current != null && current == ownedList && addedItem != null)
			{
				int num = ((addedIndex < current.Count && current[addedIndex] == addedItem) ? addedIndex : (-1));
				if (num < 0)
				{
					for (int i = 0; i < current.Count; i++)
					{
						if (current[i] == addedItem)
						{
							num = i;
							break;
						}
					}
				}
				if (num >= 0)
				{
					List<T> list = new List<T>(current);
					list.RemoveAt(num);
					current = list;
				}
			}
			ForgetOwnership();
			return current;
		}

		private void ForgetOwnership()
		{
			ownedList = null;
			addedItem = null;
			addedIndex = -1;
		}
	}
	public enum GestureOrder
	{
		None,
		Attack,
		Regroup
	}
	public sealed class EscortCommandGesture<T> where T : class
	{
		private T? target;

		private double started;

		private double deadline;

		private bool regrouped;

		public bool Pending { get; private set; }

		public bool StartsNewGestureAt(double now)
		{
			if ((Pending || regrouped) && !(now < started))
			{
				return now > deadline;
			}
			return true;
		}

		public GestureOrder Advance(double now, bool pressed, T? aimedTarget, double window, out T? attackTarget)
		{
			attackTarget = null;
			if (!Numbers.IsFinite(now) || !Numbers.IsFinite(window) || window <= 0.0)
			{
				Reset();
				return GestureOrder.None;
			}
			if (now < started)
			{
				Reset();
			}
			if (pressed && !StartsNewGestureAt(now))
			{
				bool pending = Pending;
				target = null;
				Pending = false;
				regrouped = true;
				started = now;
				deadline = now + window;
				if (!pending)
				{
					return GestureOrder.None;
				}
				return GestureOrder.Regroup;
			}
			if (Pending && now > deadline)
			{
				attackTarget = target;
				Reset();
			}
			if (pressed)
			{
				started = now;
				deadline = now + window;
				target = aimedTarget;
				Pending = true;
				regrouped = false;
			}
			if (attackTarget != null)
			{
				return GestureOrder.Attack;
			}
			return GestureOrder.None;
		}

		public void Reset()
		{
			Pending = false;
			regrouped = false;
			target = null;
		}
	}
	public static class EscortPolicy
	{
		public static bool RunOnTrail(bool catchingUp, bool levelRunway, float alignment, float remaining, float speed)
		{
			if (catchingUp && levelRunway && alignment >= 0.95f && Numbers.IsNonNegativeFinite(speed) && Numbers.IsNonNegativeFinite(remaining))
			{
				return remaining > Math.Max(1.35f, 0.55f + speed * 0.25f);
			}
			return false;
		}

		public static WorldPoint BacktrackOnSameLevel(IReadOnlyList<WorldPoint> route, float spacing, float verticalBand)
		{
			if (route == null || route.Count == 0)
			{
				throw new ArgumentException("A route is required", "route");
			}
			WorldPoint worldPoint = route[route.Count - 1];
			if (!worldPoint.IsFinite || !Numbers.IsNonNegativeFinite(spacing) || !Numbers.IsNonNegativeFinite(verticalBand))
			{
				return worldPoint;
			}
			WorldPoint worldPoint2 = worldPoint;
			float num = spacing;
			for (int num2 = route.Count - 2; num2 >= 0; num2--)
			{
				WorldPoint worldPoint3 = route[num2];
				if (!worldPoint3.IsFinite)
				{
					return worldPoint2;
				}
				float num3 = WorldPoint.Distance(worldPoint2, worldPoint3);
				if (num3 < 0.0001f)
				{
					worldPoint2 = worldPoint3;
				}
				else
				{
					float num4 = Math.Min(1f, num / num3);
					float num5 = worldPoint2.Y + (worldPoint3.Y - worldPoint2.Y) * num4;
					bool num6 = Math.Abs(num5 - worldPoint.Y) > verticalBand;
					if (num6)
					{
						float num7 = worldPoint.Y + ((num5 > worldPoint.Y) ? verticalBand : (0f - verticalBand));
						num4 = Math.Max(0f, Math.Min(num4, (num7 - worldPoint2.Y) / (worldPoint3.Y - worldPoint2.Y)));
					}
					WorldPoint result = new WorldPoint(worldPoint2.X + (worldPoint3.X - worldPoint2.X) * num4, worldPoint2.Y + (worldPoint3.Y - worldPoint2.Y) * num4, worldPoint2.Z + (worldPoint3.Z - worldPoint2.Z) * num4);
					if (num6 || num3 >= num)
					{
						return result;
					}
					num -= num3;
					worldPoint2 = worldPoint3;
				}
			}
			return worldPoint2;
		}

		public static WorldPoint KeepOutsidePersonalSpace(WorldPoint leader, WorldPoint desired, float personalSpace, WorldPoint fallbackDirection)
		{
			if (!leader.IsFinite || !desired.IsFinite || !Numbers.IsNonNegativeFinite(personalSpace) || personalSpace == 0f)
			{
				return desired;
			}
			double num = desired.X - leader.X;
			double num2 = desired.Z - leader.Z;
			double num3 = Math.Sqrt(num * num + num2 * num2);
			if (num3 >= (double)personalSpace)
			{
				return desired;
			}
			if (num3 < 0.0001)
			{
				num = (fallbackDirection.IsFinite ? ((double)fallbackDirection.X) : 1.0);
				num2 = (fallbackDirection.IsFinite ? ((double)fallbackDirection.Z) : 0.0);
				num3 = Math.Sqrt(num * num + num2 * num2);
				if (num3 < 0.0001)
				{
					num = 1.0;
					num2 = 0.0;
					num3 = 1.0;
				}
			}
			return new WorldPoint(leader.X + (float)(num * (double)personalSpace / num3), desired.Y, leader.Z + (float)(num2 * (double)personalSpace / num3));
		}
	}
	public static class EscortRecoveryPolicy
	{
		public static bool NeedsCatchUp(WorldPoint wolf, WorldPoint leader, float horizontalThreshold, float elevationGap)
		{
			if (!wolf.IsFinite || !leader.IsFinite || !Numbers.IsNonNegativeFinite(horizontalThreshold) || !Numbers.IsNonNegativeFinite(elevationGap) || elevationGap <= 0f)
			{
				return false;
			}
			double num = (double)wolf.X - (double)leader.X;
			double num2 = (double)wolf.Z - (double)leader.Z;
			if (!(num * num + num2 * num2 > (double)horizontalThreshold * (double)horizontalThreshold))
			{
				return Math.Abs((double)wolf.Y - (double)leader.Y) >= (double)elevationGap;
			}
			return true;
		}
	}
	public sealed class EscortTrail
	{
		public readonly struct LaterStep
		{
			internal readonly EscortTrail Source;

			internal readonly long Revision;

			internal readonly int FromCursor;

			internal readonly float DistanceSquared;

			public readonly int ForwardIndex;

			public readonly WorldPoint Entry;

			public readonly WorldPoint Forward;

			internal LaterStep(EscortTrail trail, WorldPoint entry, int forwardIndex, float distanceSquared)
			{
				Source = trail;
				Revision = trail.revision;
				FromCursor = trail.cursor;
				Entry = entry;
				ForwardIndex = forwardIndex;
				Forward = trail.points[forwardIndex];
				DistanceSquared = distanceSquared;
			}
		}

		private const int MaxSteps = 192;

		private const float EntranceHistory = 4f;

		private readonly List<WorldPoint> points = new List<WorldPoint>(48);

		private int cursor = -1;

		private int breakBefore = -1;

		private double lastObservation;

		private long revision;

		public bool ReachedLanding { get; private set; }

		public bool HasActiveTrail => cursor >= 0;

		public int RecordedSteps => points.Count;

		public int PendingIndex => cursor;

		public bool TryGetPendingStep(out WorldPoint point)
		{
			point = ((cursor >= 0) ? points[cursor] : default(WorldPoint));
			return cursor >= 0;
		}

		public void Clear()
		{
			points.Clear();
			cursor = (breakBefore = -1);
			ReachedLanding = false;
			revision++;
		}

		public void Observe(WorldPoint leader, double now)
		{
			if (!leader.IsFinite || !Numbers.IsFinite(now))
			{
				Clear();
				return;
			}
			if (now < lastObservation || now - lastObservation > 1.5)
			{
				Clear();
			}
			lastObservation = now;
			if (points.Count != 0)
			{
				float num = WorldPoint.Distance(points[points.Count - 1], leader);
				if (num < 0.55f)
				{
					return;
				}
				if (num > 2.5f)
				{
					Clear();
				}
			}
			Append(leader);
		}

		private void Append(WorldPoint point)
		{
			if (points.Count == 192)
			{
				int num = ((cursor >= 1) ? FirstApproachIndex() : 0);
				if (num > 0)
				{
					RemovePrefix(num);
				}
				else
				{
					Compact();
				}
				if (points.Count == 192)
				{
					if (breakBefore < 0)
					{
						breakBefore = 96;
					}
					points.RemoveRange(breakBefore, Math.Min(24, 192 - breakBefore - 1));
				}
			}
			points.Add(point);
		}

		private void RemovePrefix(int count)
		{
			points.RemoveRange(0, count);
			cursor = Math.Max(-1, cursor - count);
			breakBefore = ((breakBefore > count) ? (breakBefore - count) : (-1));
			revision++;
		}

		private void Compact()
		{
			int num = 0;
			int num2 = -1;
			for (int i = 0; i < points.Count; i++)
			{
				if (i == breakBefore)
				{
					num2 = num;
				}
				if (i <= cursor + 1 || i <= 0 || i + 1 >= points.Count || i == breakBefore || i + 1 == breakBefore || !Mergeable(points[num - 1], points[i], points[i + 1]))
				{
					points[num++] = points[i];
				}
			}
			points.RemoveRange(num, points.Count - num);
			breakBefore = num2;
			revision++;
		}

		private static bool Mergeable(WorldPoint a, WorldPoint b, WorldPoint c)
		{
			float num = WorldPoint.Distance(a, b);
			float num2 = WorldPoint.Distance(b, c);
			if (num + num2 > 2f)
			{
				return false;
			}
			return (b.X - a.X) * (c.X - b.X) + (b.Y - a.Y) * (c.Y - b.Y) + (b.Z - a.Z) * (c.Z - b.Z) > num * num2 * 0.999f;
		}

		public bool TryNext(WorldPoint wolf, WorldPoint leader, out WorldPoint target)
		{
			return TryNext(wolf, leader, out target, keepTrailOnLevel: false);
		}

		public bool TryNext(WorldPoint wolf, WorldPoint leader, out WorldPoint target, bool keepTrailOnLevel)
		{
			target = wolf;
			ReachedLanding = false;
			if (!wolf.IsFinite || !leader.IsFinite || points.Count < 2)
			{
				return false;
			}
			if (cursor < 0)
			{
				cursor = FindJoin(wolf, leader, 4f, keepTrailOnLevel, out var _);
				if (cursor < 0)
				{
					return false;
				}
				if (breakBefore >= 0 && cursor >= breakBefore)
				{
					RemovePrefix(breakBefore);
				}
			}
			while (ReachedOrPassed(wolf, cursor))
			{
				if (cursor + 1 == breakBefore)
				{
					RemovePrefix(breakBefore);
					return false;
				}
				bool flag = cursor == points.Count - 1;
				if (flag)
				{
					float num = WorldPoint.Distance(points[cursor], leader);
					if (num > 0.1f && num < 0.55f)
					{
						Append(leader);
						continue;
					}
				}
				bool flag2 = cursor > 0 && Math.Abs(points[cursor].Y - points[cursor - 1].Y) < 0.15f;
				if ((flag || (flag2 && !keepTrailOnLevel)) && Math.Abs(wolf.Y - leader.Y) < 0.15f)
				{
					if (cursor > 1)
					{
						RemovePrefix(cursor - 1);
					}
					cursor = -1;
					ReachedLanding = true;
					revision++;
					return false;
				}
				if (flag)
				{
					break;
				}
				cursor++;
			}
			int i = cursor;
			WorldPoint worldPoint = points[cursor];
			for (; i + 1 < points.Count && i + 1 != breakBefore && !IsBend(i); i++)
			{
				WorldPoint b = points[i + 1];
				float num2 = WorldPoint.Distance(wolf, b);
				float num3 = WorldPoint.Distance(wolf, points[i]) + WorldPoint.Distance(points[i], b);
				if (num2 > 1.8f || num3 - num2 > 0.04f || WorldPoint.Distance(wolf, worldPoint) + WorldPoint.Distance(worldPoint, b) - num2 > 0.04f)
				{
					break;
				}
			}
			target = points[i];
			return WorldPoint.Distance(wolf, target) <= 4f;
		}

		public bool TryGetRejoinPoint(WorldPoint wolf, WorldPoint leader, out WorldPoint point, bool keepTrailOnLevel)
		{
			point = wolf;
			if (wolf.IsFinite && leader.IsFinite && points.Count >= 2)
			{
				return FindJoin(wolf, leader, 9f, keepTrailOnLevel || HasActiveTrail, out point) >= 0;
			}
			return false;
		}

		private int FirstApproachIndex()
		{
			int num = cursor;
			float num2 = 0f;
			while (num > 0 && num != breakBefore)
			{
				num2 += WorldPoint.Distance(points[num], points[num - 1]);
				if (num2 > 4f)
				{
					break;
				}
				num--;
			}
			return num;
		}

		public bool TryGetApproachEntrance(WorldPoint wolf, out WorldPoint entrance)
		{
			entrance = default(WorldPoint);
			if (!wolf.IsFinite || cursor < 0 || Math.Abs(points[cursor].Y - wolf.Y) > 1.5f)
			{
				return false;
			}
			int num = FirstApproachIndex();
			float num2 = float.PositiveInfinity;
			for (int num3 = Math.Max(num, cursor - 1); num3 >= num; num3--)
			{
				WorldPoint worldPoint = points[num3];
				float num4 = Math.Abs(wolf.Y - worldPoint.Y);
				if (!(num4 > 0.35f) && !(WorldPoint.Distance(wolf, worldPoint) > 40f))
				{
					if (num4 <= 0.2f && num3 > num && Math.Abs(points[num3 - 1].Y - worldPoint.Y) <= 0.1f)
					{
						entrance = worldPoint;
						return true;
					}
					if (num4 < num2)
					{
						num2 = num4;
						entrance = worldPoint;
					}
				}
			}
			return num2 < float.PositiveInfinity;
		}

		public int GetLaterSteps(WorldPoint wolf, List<LaterStep> output, int limit = 4)
		{
			output.Clear();
			if (!wolf.IsFinite || cursor < 0 || limit <= 0)
			{
				return 0;
			}
			int num = ((breakBefore > cursor) ? (breakBefore - 1) : (points.Count - 1));
			for (int i = Math.Max(1, cursor); i < num; i++)
			{
				int num2 = i + 1;
				if (!TryProject(wolf, points[i], points[num2], out var join, out var _))
				{
					continue;
				}
				if (HorizontalSquared(join, points[num2]) < 0.01f)
				{
					join = points[num2];
					num2++;
					if (num2 > num || HorizontalSquared(join, points[num2]) < 0.01f)
					{
						continue;
					}
				}
				float num3 = join.Y - wolf.Y;
				float num4 = HorizontalSquared(wolf, join) + num3 * num3;
				if (!(num4 > 81f) && !(Math.Abs(num3) > 0.7f))
				{
					AddCandidate(output, new LaterStep(this, join, num2, num4), limit);
				}
			}
			return output.Count;
		}

		private static void AddCandidate(List<LaterStep> output, LaterStep candidate, int limit)
		{
			if (output.Count == limit && candidate.DistanceSquared >= output[limit - 1].DistanceSquared)
			{
				return;
			}
			int num = output.Count;
			for (int i = 0; i < output.Count; i++)
			{
				LaterStep laterStep = output[i];
				if (NearlySame(candidate.Entry, laterStep.Entry) && NearlySame(candidate.Forward, laterStep.Forward))
				{
					return;
				}
				if (num == output.Count && candidate.DistanceSquared < laterStep.DistanceSquared)
				{
					num = i;
				}
			}
			if (output.Count == limit)
			{
				output.RemoveAt(limit - 1);
			}
			output.Insert(num, candidate);
		}

		public bool TryGetCornerExit(out LaterStep step)
		{
			step = default(LaterStep);
			if (cursor < 0 || cursor + 1 >= points.Count || cursor + 1 == breakBefore)
			{
				return false;
			}
			step = new LaterStep(this, points[cursor], cursor + 1, 0f);
			return true;
		}

		public bool TryCompleteCorner(LaterStep step, WorldPoint wolf)
		{
			if (!IsCurrent(step) || step.ForwardIndex != cursor + 1 || !wolf.IsFinite || WorldPoint.Distance(wolf, step.Forward) > 0.2f)
			{
				return false;
			}
			cursor = step.ForwardIndex;
			ReachedLanding = false;
			return true;
		}

		public bool IsCurrent(LaterStep step)
		{
			if (step.Source == this && step.Revision == revision && step.FromCursor == cursor && cursor >= 0)
			{
				return step.ForwardIndex > cursor;
			}
			return false;
		}

		public bool TryCommitLaterStep(LaterStep step, WorldPoint wolf)
		{
			if (!IsCurrent(step) || !wolf.IsFinite || HorizontalSquared(wolf, step.Entry) > 0.122499995f || Math.Abs(wolf.Y - step.Entry.Y) > 0.35f)
			{
				return false;
			}
			cursor = step.ForwardIndex;
			ReachedLanding = false;
			return true;
		}

		private static float HorizontalSquared(WorldPoint a, WorldPoint b)
		{
			float num = a.X - b.X;
			float num2 = a.Z - b.Z;
			return num * num + num2 * num2;
		}

		private static bool NearlySame(WorldPoint a, WorldPoint b)
		{
			float num = a.Y - b.Y;
			return HorizontalSquared(a, b) + num * num < 0.0025000002f;
		}

		private static bool TryProject(WorldPoint wolf, WorldPoint start, WorldPoint end, out WorldPoint join, out float along)
		{
			join = start;
			along = 0f;
			float num = end.X - start.X;
			float num2 = end.Y - start.Y;
			float num3 = end.Z - start.Z;
			if (num * num + num3 * num3 < 0.01f)
			{
				return false;
			}
			along = ((wolf.X - start.X) * num + (wolf.Y - start.Y) * num2 + (wolf.Z - start.Z) * num3) / (num * num + num2 * num2 + num3 * num3);
			along = Math.Max(0f, Math.Min(1f, along));
			join = new WorldPoint(start.X + along * num, start.Y + along * num2, start.Z + along * num3);
			return join.IsFinite;
		}

		private int FindJoin(WorldPoint wolf, WorldPoint leader, float radius, bool allowSameLevel, out WorldPoint point)
		{
			point = wolf;
			if (!allowSameLevel && Math.Abs(wolf.Y - leader.Y) < 0.5f)
			{
				return -1;
			}
			int num = ((cursor >= 0) ? Math.Max(0, cursor - 1) : 0);
			int num2 = ((cursor < 0) ? (points.Count - 1) : Math.Max(1, cursor));
			int result = -1;
			float num3 = radius;
			for (int i = num; i < num2; i++)
			{
				if (i + 1 != breakBefore && TryProject(wolf, points[i], points[i + 1], out var join, out var along) && !(Math.Abs(join.Y - wolf.Y) > 0.7f) && (allowSameLevel || !(Math.Abs(join.Y - leader.Y) < 0.35f)))
				{
					float num4 = WorldPoint.Distance(wolf, join);
					if (!(num4 > num3))
					{
						num3 = num4;
						point = join;
						result = ((along > 0.05f) ? (i + 1) : i);
					}
				}
			}
			return result;
		}

		public bool TryGetLevelRunway(WorldPoint wolf, WorldPoint shortGoal, out WorldPoint end)
		{
			end = wolf;
			if (cursor < 0 || !wolf.IsFinite || !shortGoal.IsFinite || Math.Abs(shortGoal.Y - wolf.Y) > 0.12f)
			{
				return false;
			}
			int num = cursor - 1;
			for (int i = cursor; i < points.Count && i < cursor + 8 && (i <= cursor || i != breakBefore) && !(HorizontalSquared(wolf, points[i]) > 16f) && !(Math.Abs(points[i].Y - wolf.Y) > 0.12f); i++)
			{
				num = i;
				if (IsBend(i))
				{
					break;
				}
			}
			for (int num2 = num; num2 >= cursor; num2--)
			{
				float num3 = (float)Math.Sqrt(HorizontalSquared(wolf, points[num2]));
				if (!(num3 < 2.5f))
				{
					float dx = (points[num2].X - wolf.X) / num3;
					float dz = (points[num2].Z - wolf.Z) / num3;
					if (FitsLevelChord(wolf, dx, dz, num2))
					{
						end = points[num2];
						return true;
					}
				}
			}
			return false;
		}

		private bool FitsLevelChord(WorldPoint wolf, float dx, float dz, int last)
		{
			float num = 0f;
			for (int i = cursor; i <= last; i++)
			{
				float num2 = points[i].X - wolf.X;
				float num3 = points[i].Z - wolf.Z;
				float num4 = num2 * dx + num3 * dz;
				if (num4 < num - 0.05f || Math.Abs(num2 * dz - num3 * dx) > 0.32f)
				{
					return false;
				}
				num = num4;
			}
			return true;
		}

		public void ObserveRunwayProgress(WorldPoint wolf)
		{
			while (wolf.IsFinite && cursor >= 0 && cursor + 1 < points.Count && cursor + 1 != breakBefore && !IsBend(cursor) && ReachedOrPassed(wolf, cursor))
			{
				cursor++;
			}
		}

		public bool TryShortStep(WorldPoint wolf, out WorldPoint target)
		{
			target = ((cursor < 0) ? wolf : points[cursor]);
			if (cursor >= 0 && wolf.IsFinite)
			{
				return WorldPoint.Distance(wolf, target) <= 4f;
			}
			return false;
		}

		private bool ReachedOrPassed(WorldPoint wolf, int index)
		{
			WorldPoint b = points[index];
			bool flag = IsBend(index);
			if (WorldPoint.Distance(wolf, b) <= (flag ? 0.32f : 0.5f) && (!flag || Math.Abs(wolf.Y - b.Y) <= 0.15f))
			{
				return true;
			}
			if (index + 1 == points.Count || index + 1 == breakBefore)
			{
				return false;
			}
			WorldPoint worldPoint = points[index + 1];
			float num = worldPoint.X - b.X;
			float num2 = worldPoint.Z - b.Z;
			float num3 = num * num + num2 * num2;
			if (num3 < 0.01f)
			{
				return false;
			}
			float num4 = ((wolf.X - b.X) * num + (wolf.Z - b.Z) * num2) / num3;
			if (num4 <= 0.05f)
			{
				return false;
			}
			num4 = Math.Min(1f, num4);
			float num5 = wolf.X - (b.X + num4 * num);
			float num6 = wolf.Z - (b.Z + num4 * num2);
			float num7 = (flag ? 0.45f : 0.85f);
			float num8 = b.Y + num4 * (worldPoint.Y - b.Y);
			if (num5 * num5 + num6 * num6 <= num7 * num7)
			{
				return Math.Abs(wolf.Y - num8) <= (flag ? 0.15f : 0.35f);
			}
			return false;
		}

		private bool IsBend(int index)
		{
			if (index == 0 || index + 1 == points.Count || index == breakBefore || index + 1 == breakBefore)
			{
				return false;
			}
			WorldPoint a = points[index - 1];
			WorldPoint worldPoint = points[index];
			WorldPoint b = points[index + 1];
			float num = (worldPoint.X - a.X) * (b.X - worldPoint.X) + (worldPoint.Y - a.Y) * (b.Y - worldPoint.Y) + (worldPoint.Z - a.Z) * (b.Z - worldPoint.Z);
			float num2 = WorldPoint.Distance(a, worldPoint);
			float num3 = WorldPoint.Distance(worldPoint, b);
			if (!(Math.Abs(worldPoint.Y - a.Y) > 0.3f * num2) || !(Math.Abs(b.Y - worldPoint.Y) < 0.12f * num3))
			{
				return num < 0.9f * num2 * num3;
			}
			return true;
		}
	}
	public enum FoodAttemptResult
	{
		Continue,
		Blocked,
		NoRoute,
		NoProgress,
		TimeLimit
	}
	public sealed class FoodAttemptPolicy
	{
		private readonly Dictionary<int, double> blockedUntil = new Dictionary<int, double>();

		private bool active;

		private int target;

		private float bestRemaining;

		private double startedAt;

		private double progressAt;

		private double lastNow;

		public double ProgressTimeout { get; set; } = 8.0;

		public double AttemptTimeout { get; set; } = 30.0;

		public double RetryDelay { get; set; } = 45.0;

		public float ProgressMeters { get; set; } = 0.4f;

		public void ResetAttempt()
		{
			active = false;
		}

		public void ClearBlock(int id)
		{
			blockedUntil.Remove(id);
		}

		public bool IsBlocked(int id, double now)
		{
			CheckClock(now);
			if (!blockedUntil.TryGetValue(id, out var value))
			{
				return false;
			}
			if (now < value)
			{
				return true;
			}
			blockedUntil.Remove(id);
			return false;
		}

		public void Block(int id, double now)
		{
			CheckClock(now);
			if (!Numbers.IsFinite(now))
			{
				return;
			}
			if (blockedUntil.Count >= 32 && !blockedUntil.ContainsKey(id))
			{
				int key = 0;
				double num = double.MaxValue;
				foreach (KeyValuePair<int, double> item in blockedUntil)
				{
					if (item.Value < num)
					{
						key = item.Key;
						num = item.Value;
					}
				}
				blockedUntil.Remove(key);
			}
			blockedUntil[id] = now + RetryDelay;
			if (active && target == id)
			{
				ResetAttempt();
			}
		}

		public FoodAttemptResult Observe(int id, double now, float remainingRoute, bool routeAvailable)
		{
			CheckClock(now);
			if (IsBlocked(id, now))
			{
				return FoodAttemptResult.Blocked;
			}
			if (!routeAvailable || !Numbers.IsNonNegativeFinite(remainingRoute) || !Numbers.IsFinite(now))
			{
				Block(id, now);
				return FoodAttemptResult.NoRoute;
			}
			if (!active)
			{
				active = true;
				target = id;
				bestRemaining = remainingRoute;
				startedAt = (progressAt = now);
				return FoodAttemptResult.Continue;
			}
			if (target != id)
			{
				target = id;
				bestRemaining = remainingRoute;
				progressAt = now;
			}
			if (remainingRoute <= bestRemaining - ProgressMeters)
			{
				bestRemaining = remainingRoute;
				progressAt = now;
			}
			int num;
			if (!(now - startedAt >= AttemptTimeout))
			{
				if (!(now - progressAt >= ProgressTimeout))
				{
					num = 0;
					goto IL_00ce;
				}
				num = 3;
			}
			else
			{
				num = 4;
			}
			if (num != 0)
			{
				Block(id, now);
			}
			goto IL_00ce;
			IL_00ce:
			return (FoodAttemptResult)num;
		}

		public FoodAttemptResult ObserveDeferred(int id, double now)
		{
			CheckClock(now);
			if (IsBlocked(id, now))
			{
				return FoodAttemptResult.Blocked;
			}
			if (!Numbers.IsFinite(now))
			{
				return FoodAttemptResult.NoRoute;
			}
			if (!active || target != id)
			{
				if (!active)
				{
					startedAt = now;
				}
				active = true;
				target = id;
				bestRemaining = float.PositiveInfinity;
				progressAt = now;
			}
			if (now - startedAt < AttemptTimeout)
			{
				return FoodAttemptResult.Continue;
			}
			Block(id, now);
			return FoodAttemptResult.TimeLimit;
		}

		private void CheckClock(double now)
		{
			if (!Numbers.IsFinite(now))
			{
				ResetAttempt();
				return;
			}
			if (now < lastNow)
			{
				ResetAttempt();
				blockedUntil.Clear();
			}
			lastNow = now;
		}
	}
	public sealed class FoodReturnSpeed
	{
		private double speedTime;

		public double Seconds { get; private set; }

		public double Mean
		{
			get
			{
				if (!(Seconds > 0.0))
				{
					return 0.0;
				}
				return speedTime / Seconds;
			}
		}

		public float Peak { get; private set; }

		public void Observe(float speedXZ, float activeSeconds)
		{
			if (Numbers.IsNonNegativeFinite(speedXZ) && Numbers.IsFinite(activeSeconds) && !(activeSeconds <= 0f))
			{
				Seconds += activeSeconds;
				speedTime += (double)speedXZ * (double)activeSeconds;
				if (speedXZ > Peak)
				{
					Peak = speedXZ;
				}
			}
		}
	}
	public sealed class GroundMealAttempt
	{
		public int Sequence { get; private set; }

		public int Target { get; private set; }

		public bool Active { get; private set; }

		public bool Select(int item)
		{
			if (item == 0 || Active)
			{
				return false;
			}
			Target = item;
			Active = true;
			Sequence++;
			return true;
		}

		public bool End(int item)
		{
			if (!Active || item != Target)
			{
				return false;
			}
			Active = false;
			return true;
		}

		public void Reset()
		{
			Active = false;
			Target = 0;
		}
	}
	public enum GuardFoodTripPhase
	{
		None,
		Approaching,
		ReturnRequired
	}
	public sealed class GuardFoodTripPolicy
	{
		private int target;

		private double startedAt;

		private double lastNow;

		public GuardFoodTripPhase Phase { get; private set; }

		public bool Pending => Phase != GuardFoodTripPhase.None;

		public bool Approaching => Phase == GuardFoodTripPhase.Approaching;

		public bool ReturnRequired => Phase == GuardFoodTripPhase.ReturnRequired;

		public double AttemptTimeout { get; set; } = 30.0;

		public static bool WithinBounds(float distanceFromHome, float guardRadius, float foodSearchRadius)
		{
			if (Numbers.IsNonNegativeFinite(distanceFromHome) && Numbers.IsNonNegativeFinite(guardRadius) && Numbers.IsNonNegativeFinite(foodSearchRadius) && Numbers.IsFinite(guardRadius + foodSearchRadius))
			{
				return distanceFromHome <= guardRadius + foodSearchRadius;
			}
			return false;
		}

		public bool CanSelect(int foodId, float distanceFromHome, float guardRadius, float foodSearchRadius)
		{
			if (foodId != 0 && WithinBounds(distanceFromHome, guardRadius, foodSearchRadius) && !ReturnRequired)
			{
				if (Approaching)
				{
					return foodId == target;
				}
				return true;
			}
			return false;
		}

		public bool Begin(int foodId, double now, float distanceFromHome, float guardRadius, float foodSearchRadius, bool routeLeavesHome = false)
		{
			if (!Numbers.IsFinite(now) || !CanSelect(foodId, distanceFromHome, guardRadius, foodSearchRadius))
			{
				return false;
			}
			if (!Pending && (distanceFromHome > guardRadius || routeLeavesHome))
			{
				target = foodId;
				startedAt = (lastNow = now);
				Phase = GuardFoodTripPhase.Approaching;
			}
			return true;
		}

		public bool IsTarget(int foodId)
		{
			if (Approaching && foodId != 0)
			{
				return foodId == target;
			}
			return false;
		}

		public void Observe(double now, bool retainsMeal, bool withinBounds, bool interrupted, bool arrivedHome)
		{
			if (Pending)
			{
				if (Approaching && (!Numbers.IsFinite(now) || now < lastNow || !retainsMeal || !withinBounds || interrupted || !Numbers.IsFinite(AttemptTimeout) || AttemptTimeout <= 0.0 || now - startedAt >= AttemptTimeout))
				{
					Interrupt();
				}
				if (Numbers.IsFinite(now))
				{
					lastNow = now;
				}
				if (ReturnRequired && arrivedHome)
				{
					Reset();
				}
			}
		}

		public void Interrupt()
		{
			if (Pending)
			{
				Phase = GuardFoodTripPhase.ReturnRequired;
			}
		}

		public void Restore(bool pending)
		{
			Reset();
			if (pending)
			{
				Phase = GuardFoodTripPhase.ReturnRequired;
			}
		}

		public void Reset()
		{
			Phase = GuardFoodTripPhase.None;
			target = 0;
			startedAt = (lastNow = 0.0);
		}
	}
	public static class MountStaminaPolicy
	{
		public static float Multiplier(float skillFactor, float bonusPercent)
		{
			if (!Finite(skillFactor) || !Finite(bonusPercent) || bonusPercent <= 0f)
			{
				return 1f;
			}
			return 1f + Math.Max(0f, Math.Min(1f, skillFactor)) * Math.Min(100f, bonusPercent) * 0.01f;
		}

		private static bool Finite(float value)
		{
			if (!float.IsNaN(value))
			{
				return !float.IsInfinity(value);
			}
			return false;
		}
	}
	public static class MountStorageLayout
	{
		public const int Maximum = 10;

		public static int Clamp(int slots)
		{
			return Math.Max(1, Math.Min(10, slots));
		}

		public static (int Width, int Height) Dimensions(int requested, int occupied)
		{
			if (occupied < 0 || occupied > 10)
			{
				throw new ArgumentOutOfRangeException("occupied");
			}
			int num = Math.Max(Clamp(requested), occupied);
			int num2 = (int)Math.Sqrt(num);
			while (num % num2 != 0)
			{
				num2--;
			}
			return (Width: num / num2, Height: num2);
		}

		public static (int X, int Y)[] Arrange(int requested, IReadOnlyList<(int X, int Y)> positions)
		{
			(int, int) tuple = Dimensions(requested, positions.Count);
			(int, int)[] array = new(int, int)[positions.Count];
			HashSet<(int, int)> hashSet = new HashSet<(int, int)>();
			for (int i = 0; i < positions.Count; i++)
			{
				(int, int) tuple2 = positions[i];
				if (tuple2.Item1 < 0 || tuple2.Item2 < 0 || tuple2.Item1 >= 10 || tuple2.Item2 >= 10 || !hashSet.Add(tuple2))
				{
					throw new ArgumentException("Invalid or duplicate cargo position", "positions");
				}
				array[i] = tuple2;
			}
			hashSet.Clear();
			for (int j = 0; j < array.Length; j++)
			{
				if (array[j].Item1 < tuple.Item1 && array[j].Item2 < tuple.Item2)
				{
					hashSet.Add(array[j]);
				}
			}
			int k = 0;
			for (int l = 0; l < array.Length; l++)
			{
				if (array[l].Item1 >= tuple.Item1 || array[l].Item2 >= tuple.Item2)
				{
					for (; hashSet.Contains((k % tuple.Item1, k / tuple.Item1)); k++)
					{
					}
					array[l] = (k % tuple.Item1, k / tuple.Item1);
					hashSet.Add(array[l]);
				}
			}
			return array;
		}

		public static bool DepositsAllowed(int requested, int width, int height, int occupied)
		{
			if (occupied <= Clamp(requested))
			{
				return width * height <= Clamp(requested);
			}
			return false;
		}
	}
	public sealed class PathQueryBudget
	{
		public const int RegularLimit = 16;

		public const int TotalLimit = 20;

		private int lastFrame = -1;

		private int used;

		public bool Available(int frame, bool emergency = false)
		{
			if (frame == lastFrame)
			{
				return used < (emergency ? 20 : 16);
			}
			return true;
		}

		public bool TryTake(int frame, bool emergency = false)
		{
			if (frame != lastFrame)
			{
				lastFrame = frame;
				used = 0;
			}
			if (!Available(frame, emergency))
			{
				return false;
			}
			used++;
			return true;
		}
	}
	public static class RescueRetryPolicy
	{
		public static double DelaySeconds(int consecutiveFailures, double baseSeconds, double maximumSeconds)
		{
			if (!Numbers.IsFinite(baseSeconds) || baseSeconds <= 0.0)
			{
				baseSeconds = 15.0;
			}
			if (!Numbers.IsFinite(maximumSeconds) || maximumSeconds < baseSeconds)
			{
				maximumSeconds = baseSeconds;
			}
			double num = baseSeconds;
			for (int i = 1; i < Math.Min(consecutiveFailures, 31); i++)
			{
				if (!(num < maximumSeconds))
				{
					break;
				}
				num = ((num >= maximumSeconds / 2.0) ? maximumSeconds : (num * 2.0));
			}
			return num;
		}
	}
	public static class RouteSearch
	{
		public static bool Find(IReadOnlyList<WorldPoint> points, Func<int, int, float> legCost, int queryBudget, List<int> result)
		{
			result.Clear();
			if (points == null || points.Count < 2 || points.Count > 32 || queryBudget <= 0)
			{
				return false;
			}
			int count = points.Count;
			float[] array = new float[count];
			int[] array2 = new int[count];
			bool[] array3 = new bool[count];
			for (int i = 0; i < count; i++)
			{
				if (!points[i].IsFinite)
				{
					return false;
				}
				array[i] = float.PositiveInfinity;
				array2[i] = -1;
			}
			array[0] = 0f;
			int num = 0;
			for (int j = 0; j < count; j++)
			{
				int num2 = -1;
				float num3 = float.PositiveInfinity;
				for (int k = 0; k < count; k++)
				{
					if (!array3[k])
					{
						float num4 = array[k] + WorldPoint.Distance(points[k], points[1]);
						if (num4 < num3)
						{
							num3 = num4;
							num2 = k;
						}
					}
				}
				if (num2 < 0)
				{
					return false;
				}
				if (num2 == 1)
				{
					for (int num5 = 1; num5 >= 0; num5 = array2[num5])
					{
						result.Add(num5);
					}
					result.Reverse();
					return true;
				}
				array3[num2] = true;
				for (int l = 1; l < count; l++)
				{
					if (array3[l] || l == num2)
					{
						continue;
					}
					if (++num > queryBudget)
					{
						return false;
					}
					float num6 = legCost(num2, l);
					if (float.IsNaN(num6))
					{
						return false;
					}
					if (Numbers.IsNonNegativeFinite(num6))
					{
						float num7 = array[num2] + num6;
						if (!(num7 >= array[l]))
						{
							array[l] = num7;
							array2[l] = num2;
						}
					}
				}
			}
			return false;
		}
	}
	public enum SimpleGuardRecoveryAssessment
	{
		NotSampled,
		Inactive,
		Waiting,
		Progressing,
		Cooldown,
		Ready
	}
	public sealed class SimpleGuardRecoveryPolicy
	{
		private bool observing;

		private WorldPoint checkpoint;

		private double lastProgress;

		private double lastSample;

		private double nextSample;

		private double cooldownUntil;

		public void ResetObservation()
		{
			observing = false;
			nextSample = 0.0;
		}

		public void RestoreCooldown(double now, bool pending, double cooldownSeconds)
		{
			ResetObservation();
			lastSample = now;
			cooldownUntil = (pending ? (now + Duration(cooldownSeconds, 120.0)) : now);
		}

		public void Attempted(double now, double cooldownSeconds)
		{
			observing = false;
			cooldownUntil = now + Duration(cooldownSeconds, 120.0);
		}

		public double CooldownRemaining(double now)
		{
			if (!Numbers.IsFinite(now))
			{
				return 0.0;
			}
			return Math.Max(0.0, cooldownUntil - now);
		}

		public double NoProgressSeconds(double now)
		{
			if (!observing || !Numbers.IsFinite(now))
			{
				return 0.0;
			}
			return Math.Max(0.0, now - lastProgress);
		}

		public SimpleGuardRecoveryAssessment Observe(double now, WorldPoint position, bool pendingReturn, double stuckSeconds)
		{
			if (!Numbers.IsFinite(now) || !position.IsFinite)
			{
				ResetObservation();
				return SimpleGuardRecoveryAssessment.Inactive;
			}
			if (now < lastSample)
			{
				double num = Math.Max(0.0, cooldownUntil - lastSample);
				cooldownUntil = now + num;
				ResetObservation();
			}
			if (now < nextSample)
			{
				return SimpleGuardRecoveryAssessment.NotSampled;
			}
			lastSample = now;
			nextSample = now + 1.0;
			if (!pendingReturn)
			{
				observing = false;
				return SimpleGuardRecoveryAssessment.Inactive;
			}
			bool flag = now < cooldownUntil;
			if (!observing)
			{
				observing = true;
				checkpoint = position;
				lastProgress = now;
				if (!flag)
				{
					return SimpleGuardRecoveryAssessment.Waiting;
				}
				return SimpleGuardRecoveryAssessment.Cooldown;
			}
			if (WorldPoint.Distance(position, checkpoint) >= 1.5f)
			{
				checkpoint = position;
				lastProgress = now;
				if (!flag)
				{
					return SimpleGuardRecoveryAssessment.Progressing;
				}
				return SimpleGuardRecoveryAssessment.Cooldown;
			}
			if (flag)
			{
				return SimpleGuardRecoveryAssessment.Cooldown;
			}
			if (!(now - lastProgress >= Duration(stuckSeconds, 30.0)))
			{
				return SimpleGuardRecoveryAssessment.Waiting;
			}
			return SimpleGuardRecoveryAssessment.Ready;
		}

		private static double Duration(double value, double fallback)
		{
			if (!Numbers.IsFinite(value) || !(value > 0.0))
			{
				return fallback;
			}
			return value;
		}
	}
	public enum RescueAssessment
	{
		Inactive,
		GracePeriod,
		Waiting,
		Progressing,
		Stuck
	}
	public sealed class RescueSettings
	{
		public float MinDistance { get; set; } = 5f;

		public float ProgressMeters { get; set; } = 0.5f;

		public double StuckSeconds { get; set; } = 8.0;
	}
	public sealed class StuckTracker
	{
		private enum Observation
		{
			Ordinary,
			Escort,
			GuardReturn,
			GuardPatrol
		}

		private bool initialized;

		private double lastSampleAt;

		private double lastProgressAt;

		private WorldPoint checkpoint;

		private float checkpointDistance;

		private Observation observation;

		public double NoProgressSeconds(double now)
		{
			if (!initialized || !Numbers.IsFinite(now))
			{
				return 0.0;
			}
			return Math.Max(0.0, now - lastProgressAt);
		}

		public float TravelSinceProgress(WorldPoint position)
		{
			if (!initialized || !position.IsFinite)
			{
				return 0f;
			}
			return WorldPoint.Distance(position, checkpoint);
		}

		public void Reset()
		{
			initialized = false;
		}

		public RescueAssessment Observe(double now, WorldPoint position, WorldPoint destination, bool attemptingMovement, bool combatBlocksRescue, double graceUntil, RescueSettings settings)
		{
			return ObserveCore(now, position, destination, attemptingMovement, combatBlocksRescue, graceUntil, settings, Observation.Ordinary);
		}

		public RescueAssessment ObserveEscort(double now, WorldPoint position, WorldPoint leaderAnchor, bool attemptingMovement, bool combatBlocksRescue, double graceUntil, RescueSettings settings)
		{
			return ObserveCore(now, position, leaderAnchor, attemptingMovement, combatBlocksRescue, graceUntil, settings, Observation.Escort);
		}

		public RescueAssessment ObserveGuard(double now, WorldPoint position, WorldPoint home, bool attemptingMovement, bool combatBlocksRescue, double graceUntil, RescueSettings settings, bool patrolFailure)
		{
			return ObserveCore(now, position, home, attemptingMovement, combatBlocksRescue, graceUntil, settings, patrolFailure ? Observation.GuardPatrol : Observation.GuardReturn);
		}

		private RescueAssessment ObserveCore(double now, WorldPoint position, WorldPoint destination, bool attemptingMovement, bool combatBlocksRescue, double graceUntil, RescueSettings settings, Observation mode)
		{
			if (settings == null)
			{
				throw new ArgumentNullException("settings");
			}
			if (!Numbers.IsFinite(now) || !Numbers.IsFinite(graceUntil) || !position.IsFinite || !destination.IsFinite || !Numbers.IsNonNegativeFinite(settings.MinDistance) || !Numbers.IsNonNegativeFinite(settings.ProgressMeters) || settings.ProgressMeters <= 0f || !Numbers.IsFinite(settings.StuckSeconds) || settings.StuckSeconds <= 0.0)
			{
				Reset();
				return RescueAssessment.Inactive;
			}
			float num = WorldPoint.Distance(position, destination);
			bool flag = mode == Observation.GuardReturn || mode == Observation.GuardPatrol;
			if (!Numbers.IsNonNegativeFinite(num) || !attemptingMovement || combatBlocksRescue || (!flag && num <= settings.MinDistance))
			{
				Reset();
				return RescueAssessment.Inactive;
			}
			if (!initialized || now < lastSampleAt || observation != mode)
			{
				observation = mode;
				Start(now, position, num);
				if (!(now < graceUntil))
				{
					return RescueAssessment.Waiting;
				}
				return RescueAssessment.GracePeriod;
			}
			lastSampleAt = now;
			if (now < graceUntil)
			{
				Start(now, position, num);
				return RescueAssessment.GracePeriod;
			}
			float num2 = WorldPoint.Distance(position, checkpoint);
			if (mode == Observation.GuardReturn && num2 >= Math.Max(1.5f, settings.ProgressMeters * 3f))
			{
				Start(now, position, num);
				return RescueAssessment.Progressing;
			}
			if (mode == Observation.Escort || mode == Observation.GuardPatrol)
			{
				float num3 = ((mode == Observation.GuardPatrol) ? settings.ProgressMeters : Math.Max(1.5f, settings.ProgressMeters * 3f));
				if (num2 >= num3)
				{
					Start(now, position, num);
					return RescueAssessment.Progressing;
				}
				if (!(now - Math.Max(lastProgressAt, graceUntil) >= settings.StuckSeconds))
				{
					return RescueAssessment.Waiting;
				}
				return RescueAssessment.Stuck;
			}
			float num4 = destination.X - checkpoint.X;
			float num5 = destination.Y - checkpoint.Y;
			float num6 = destination.Z - checkpoint.Z;
			double num7 = Math.Sqrt(num4 * num4 + num5 * num5 + num6 * num6);
			bool num8 = ((num7 > 0.0001) ? ((double)((position.X - checkpoint.X) * num4 + (position.Y - checkpoint.Y) * num5 + (position.Z - checkpoint.Z) * num6) / num7) : 0.0) >= (double)settings.ProgressMeters;
			bool flag2 = num2 >= settings.ProgressMeters && checkpointDistance - num >= settings.ProgressMeters;
			if (num8 || flag2)
			{
				Start(now, position, num);
				return RescueAssessment.Progressing;
			}
			if (!(now - Math.Max(lastProgressAt, graceUntil) >= settings.StuckSeconds))
			{
				return RescueAssessment.Waiting;
			}
			return RescueAssessment.Stuck;
		}

		private void Start(double now, WorldPoint position, float distance)
		{
			initialized = true;
			lastSampleAt = now;
			lastProgressAt = now;
			checkpoint = position;
			checkpointDistance = distance;
		}
	}
	public static class SubmergedFoodPolicy
	{
		public static bool IsInaccessible(float waterDepth, float swimDepth, float consumeRange, float distance3D)
		{
			if (!Numbers.IsFinite(waterDepth) || !Numbers.IsNonNegativeFinite(swimDepth) || !Numbers.IsNonNegativeFinite(consumeRange) || !Numbers.IsNonNegativeFinite(distance3D))
			{
				return false;
			}
			if (waterDepth <= 0f || distance3D <= consumeRange)
			{
				return false;
			}
			return (double)waterDepth - (double)swimDepth > (double)consumeRange;
		}
	}
	public static class TamedRegenPolicy
	{
		public static float HealAmount(float currentHealth, float maxHealth, double elapsedSeconds, bool inCombat, bool hungry, bool alive, float combatPercent, float quietPercent, bool requiresFood)
		{
			if (!alive || (requiresFood && hungry) || !Finite(currentHealth) || !Finite(maxHealth) || currentHealth <= 0f || maxHealth <= 0f || currentHealth >= maxHealth || !Finite(elapsedSeconds) || elapsedSeconds <= 0.0 || elapsedSeconds > 2.0 || !Finite(combatPercent) || combatPercent < 0f || !Finite(quietPercent) || quietPercent < 0f)
			{
				return 0f;
			}
			double num = (inCombat ? combatPercent : quietPercent);
			double val = (double)maxHealth * (num / 100.0) * elapsedSeconds;
			return (float)Math.Min((double)maxHealth - (double)currentHealth, val);
		}

		public static bool IsInCombat(double now, bool hasTarget, double lastCombatAt, double quietSeconds)
		{
			if (!Finite(now) || now < 0.0 || !Finite(lastCombatAt) || (lastCombatAt < 0.0 && lastCombatAt != -1.0) || !Finite(quietSeconds) || quietSeconds < 0.0 || lastCombatAt > now)
			{
				return true;
			}
			if (!hasTarget)
			{
				if (lastCombatAt >= 0.0)
				{
					return now - lastCombatAt < quietSeconds;
				}
				return false;
			}
			return true;
		}

		public static bool HasActualHealthLoss(float before, float after)
		{
			if (Finite(before) && Finite(after) && before > 0f && after >= 0f)
			{
				return after < before;
			}
			return false;
		}

		private static bool Finite(float value)
		{
			if (!float.IsNaN(value))
			{
				return !float.IsInfinity(value);
			}
			return false;
		}

		private static bool Finite(double value)
		{
			if (!double.IsNaN(value))
			{
				return !double.IsInfinity(value);
			}
			return false;
		}
	}
	public sealed class TamedRegenClock
	{
		public const double TickSeconds = 1.0;

		public const double MaximumGapSeconds = 2.0;

		private const double Precision = 1E-06;

		private bool initialized;

		private double lastObserved;

		private double lastTick;

		public bool ShouldWriteStamp { get; private set; }

		public string LastAdvanceReason { get; private set; } = "inactive";

		public void Reset()
		{
			initialized = false;
			ShouldWriteStamp = false;
			LastAdvanceReason = "inactive";
		}

		public bool TryAdvance(double now, double sharedLastTick, bool active, out double elapsed)
		{
			elapsed = 0.0;
			ShouldWriteStamp = false;
			if (!active)
			{
				Reset();
				return false;
			}
			if (!Finite(now) || now < 0.0)
			{
				Reset();
				LastAdvanceReason = "invalid-clock";
				return false;
			}
			if (!Finite(sharedLastTick) || (sharedLastTick < 0.0 && sharedLastTick != -1.0) || sharedLastTick > now + 1E-06)
			{
				return Baseline(now, "shared-clock-reset");
			}
			if (!initialized)
			{
				return Baseline(now, "initial-baseline");
			}
			if (now < lastObserved)
			{
				return Baseline(now, "clock-rewind");
			}
			if (now - lastObserved > 2.0)
			{
				return Baseline(now, "observation-gap");
			}
			lastObserved = now;
			if (sharedLastTick >= 0.0)
			{
				lastTick = Math.Max(lastTick, Math.Min(now, sharedLastTick));
			}
			double num = now - lastTick;
			if (num > 2.0)
			{
				return Baseline(now, "elapsed-gap");
			}
			if (num + 1E-06 < 1.0)
			{
				LastAdvanceReason = "cadence";
				return false;
			}
			elapsed = num;
			lastTick = now;
			ShouldWriteStamp = true;
			LastAdvanceReason = "tick";
			return true;
		}

		private bool Baseline(double now, string reason)
		{
			initialized = true;
			lastObserved = (lastTick = now);
			ShouldWriteStamp = true;
			LastAdvanceReason = reason;
			return false;
		}

		private static bool Finite(double value)
		{
			if (!double.IsNaN(value))
			{
				return !double.IsInfinity(value);
			}
			return false;
		}
	}
	public static class WhistleNetworkPolicy
	{
		public const float AudibleRange = 35f;

		public const double MinimumInterval = 0.25;

		public const int MaximumPeers = 64;

		public static bool InRange(float distance)
		{
			if (Numbers.IsNonNegativeFinite(distance))
			{
				return distance <= 35f;
			}
			return false;
		}

		public static bool Authenticated(long sender, long localPeer, long sourcePeer, long requestedPlayer, long resolvedPlayer, bool sourceAlive, float distance)
		{
			if (localPeer != 0L && sender != localPeer && CommandPolicy.CanAuthenticate(requestedPlayer, resolvedPlayer, sender, sourcePeer, sourceAlive))
			{
				return InRange(distance);
			}
			return false;
		}
	}
	public sealed class WhistleReceiveGate
	{
		private struct Receipt
		{
			internal long Sequence;

			internal double PlayedAt;
		}

		private readonly Dictionary<long, Receipt> receipts = new Dictionary<long, Receipt>();

		public bool Accept(long peer, long sequence, double now)
		{
			if (peer == 0L || sequence <= 0 || double.IsNaN(now) || double.IsInfinity(now) || now < 0.0)
			{
				return false;
			}
			if (receipts.TryGetValue(peer, out var value))
			{
				if (sequence <= value.Sequence)
				{
					return false;
				}
				value.Sequence = sequence;
				if (now < value.PlayedAt || now - value.PlayedAt < 0.25)
				{
					receipts[peer] = value;
					return false;
				}
			}
			else if (receipts.Count >= 64)
			{
				return false;
			}
			receipts[peer] = new Receipt
			{
				Sequence = sequence,
				PlayedAt = now
			};
			return true;
		}

		public void Clear()
		{
			receipts.Clear();
		}
	}
	public sealed class WhistlePcm
	{
		public int SampleRate { get; }

		public int Channels { get; }

		public float[] Samples { get; }

		public int Frames => Samples.Length / Channels;

		private WhistlePcm(int sampleRate, int channels, float[] samples)
		{
			SampleRate = sampleRate;
			Channels = channels;
			Samples = samples;
		}

		public static WhistlePcm Read(Stream stream)
		{
			using BinaryReader binaryReader = new BinaryReader(stream, Encoding.ASCII, leaveOpen: true);
			if (stream.Length < 44 || stream.Length > 4194304 || binaryReader.ReadUInt32() != 1179011410)
			{
				throw new InvalidDataException("Se esperaba un WAV corto en formato RIFF.");
			}
			long num = (long)binaryReader.ReadUInt32() + 8L;
			if (num > stream.Length || binaryReader.ReadUInt32() != 1163280727)
			{
				throw new InvalidDataException("Cabecera WAVE incompleta.");
			}
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			long num5 = -1L;
			while (stream.Position + 8 <= num)
			{
				uint num6 = binaryReader.ReadUInt32();
				uint num7 = binaryReader.ReadUInt32();
				long position = stream.Position;
				long num8 = position + num7 + (num7 & 1);
				if (num8 > num)
				{
					throw new InvalidDataException("Bloque de sonido incompleto.");
				}
				switch (num6)
				{
				case 544501094u:
					if (num7 < 16 || binaryReader.ReadUInt16() != 1)
					{
						throw new InvalidDataException("El silbido debe ser PCM de 16 bits.");
					}
					num2 = binaryReader.ReadUInt16();
					num3 = binaryReader.ReadInt32();
					binaryReader.ReadUInt32();
					if ((num2 != 1 && num2 != 2) || num3 < 8000 || num3 > 96000 || binaryReader.ReadUInt16() != num2 * 2 || binaryReader.ReadUInt16() != 16)
					{
						throw new InvalidDataException("Se requiere PCM16 mono o estéreo de 8 a 96 kHz.");
					}
					break;
				case 1635017060u:
					if (num5 < 0)
					{
						num5 = position;
						num4 = (int)num7;
					}
					break;
				}
				stream.Position = num8;
			}
			if (num5 < 0 || num2 == 0 || num4 == 0 || num4 % (2 * num2) != 0 || num4 > 10 * num3 * num2 * 2)
			{
				throw new InvalidDataException("El WAV debe contener entre una muestra y diez segundos de audio.");
			}
			stream.Position = num5;
			float[] array = new float[num4 / 2];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = (float)binaryReader.ReadInt16() / 32768f;
			}
			return new WhistlePcm(num3, num2, array);
		}
	}
	public static class WolfHealthPolicy
	{
		public const int BossCountLimit = 5;

		public static float CalculateMax(float normalMax, int bossCount, float percent, float cap)
		{
			if (!Numbers.IsFinite(normalMax) || normalMax <= 0f)
			{
				return 0f;
			}
			if (bossCount <= 0 || !Numbers.IsFinite(percent) || percent <= 0f || !Numbers.IsFinite(cap) || cap <= 0f)
			{
				return normalMax;
			}
			int num = Math.Min(bossCount, 5);
			double val = (double)normalMax * (1.0 + (double)percent * (double)num / 100.0);
			double val2 = Math.Max(normalMax, cap);
			return (float)Math.Min(val, val2);
		}

		public static float PreserveFraction(float current, float oldMax, float newMax)
		{
			if (!Numbers.IsFinite(current) || current <= 0f)
			{
				return 0f;
			}
			if (!Numbers.IsFinite(newMax) || newMax <= 0f)
			{
				return current;
			}
			if (!Numbers.IsFinite(oldMax) || oldMax <= 0f)
			{
				return Math.Min(current, newMax);
			}
			double num = Math.Min(1.0, (double)current / (double)oldMax);
			return (float)Math.Min(newMax, num * (double)newMax);
		}
	}
	public enum WolfMode
	{
		Guard,
		Follow,
		Regroup,
		Hold
	}
	public enum EscortBoundary
	{
		Inside,
		IdleLimit,
		WolfOutsideChase,
		TargetOutsideChase
	}
	public readonly struct WorldPoint
	{
		public readonly float X;

		public readonly float Y;

		public readonly float Z;

		public bool IsFinite
		{
			get
			{
				if (Numbers.IsFinite(X) && Numbers.IsFinite(Y))
				{
					return Numbers.IsFinite(Z);
				}
				return false;
			}
		}

		public WorldPoint(float x, float y, float z)
		{
			X = x;
			Y = y;
			Z = z;
		}

		public static float Distance(WorldPoint a, WorldPoint b)
		{
			float num = a.X - b.X;
			float num2 = a.Y - b.Y;
			float num3 = a.Z - b.Z;
			return (float)Math.Sqrt(num * num + num2 * num2 + num3 * num3);
		}
	}
	public sealed class ThreatCandidate
	{
		public bool IsAlive { get; set; } = true;

		public bool IsTamed { get; set; }

		public bool IsHostile { get; set; }

		public bool IsWildlife { get; set; }

		public bool IsDeer { get; set; }

		public bool IsHare { get; set; }

		public bool IsDetected { get; set; }

		public bool IsCurrentTarget { get; set; }

		public bool IsManualTarget { get; set; }

		public bool AttackedOwner { get; set; }

		public bool AttackedPack { get; set; }

		public bool AttackedSelf { get; set; }

		public bool ThreateningProtected { get; set; }

		public bool NavigationBlocked { get; set; }

		public bool NewAggressionAfterBlock { get; set; }

		public bool IsLocalDefenseTarget { get; set; }

		public float DistanceFromWolf { get; set; }

		public float DistanceFromAnchor { get; set; }

		public float DistanceFromLeader { get; set; }
	}
	public sealed class CombatContext
	{
		public WolfMode Mode { get; set; }

		public double Now { get; set; }

		public double SuppressUntil { get; set; }

		public double ReturnCooldownUntil { get; set; }

		public bool IsReturningHome { get; set; }

		public bool IsRetreating { get; set; }

		public bool IgnoreWildlife { get; set; } = true;

		public bool HuntDeer { get; set; } = true;

		public float GuardRadius { get; set; } = 20f;

		public float GuardChaseRadius { get; set; } = 80f;

		public float FollowLeashRadius { get; set; } = 40f;

		public float ManualAttackRadius { get; set; } = 80f;

		public float DetectionRadius { get; set; } = 35f;

		public float AssistRadius { get; set; } = 25f;

		public float WolfDistanceFromAnchor { get; set; }

		public float WolfDistanceFromLeader { get; set; }
	}
	public static class WolfPolicy
	{
		public static bool CanIssueFollowerCommand(long actorId, long followingPlayerId, bool isTamed, bool isAlive)
		{
			return actorId != 0L && actorId == followingPlayerId && isTamed && isAlive;
		}

		public static bool IsStationed(WolfMode mode)
		{
			if (mode != WolfMode.Guard)
			{
				return mode == WolfMode.Hold;
			}
			return true;
		}

		public static bool InEscortChaseRange(float distanceFromLeader, float chaseRadius)
		{
			if (Numbers.IsNonNegativeFinite(distanceFromLeader) && Numbers.IsNonNegativeFinite(chaseRadius))
			{
				return distanceFromLeader <= chaseRadius;
			}
			return false;
		}

		public static float EscortTargetRadius(CombatContext context, ThreatCandidate candidate)
		{
			if (!candidate.IsManualTarget)
			{
				return context.FollowLeashRadius;
			}
			return context.ManualAttackRadius;
		}

		public static EscortBoundary CheckEscortBoundary(WorldPoint wolf, WorldPoint leader, WorldPoint? pursued, float idleRadius, float elevationGap, float chaseRadius)
		{
			if (pursued.HasValue)
			{
				if (!InEscortChaseRange(WorldPoint.Distance(wolf, leader), chaseRadius))
				{
					return EscortBoundary.WolfOutsideChase;
				}
				if (!InEscortChaseRange(WorldPoint.Distance(pursued.Value, leader), chaseRadius))
				{
					return EscortBoundary.TargetOutsideChase;
				}
				return EscortBoundary.Inside;
			}
			float num = wolf.X - leader.X;
			float num2 = wolf.Z - leader.Z;
			if (!(num * num + num2 * num2 > idleRadius * idleRadius) && !(Math.Abs(wolf.Y - leader.Y) >= elevationGap))
			{
				return EscortBoundary.Inside;
			}
			return EscortBoundary.IdleLimit;
		}

		public static bool ShouldReturnToAnchor(WolfMode mode, float distanceFromAnchor, float allowedRadius)
		{
			if (IsStationed(mode) && Numbers.IsNonNegativeFinite(distanceFromAnchor) && Numbers.IsNonNegativeFinite(allowedRadius))
			{
				return distanceFromAnchor > allowedRadius;
			}
			return false;
		}

		public static WorldPoint RescueDestination(WolfMode mode, WorldPoint home, WorldPoint leader)
		{
			if (!IsStationed(mode))
			{
				return leader;
			}
			return home;
		}

		public static bool UpdateGuardReturn(bool currentlyReturning, float distanceFromHome, bool hasCombatTarget, float targetDistanceFromHome, float normalRadius, float hardChaseRadius, float arrivalRadius)
		{
			if (!Numbers.IsNonNegativeFinite(distanceFromHome) || !Numbers.IsNonNegativeFinite(normalRadius) || !Numbers.IsNonNegativeFinite(hardChaseRadius) || !Numbers.IsNonNegativeFinite(arrivalRadius) || hardChaseRadius < normalRadius || arrivalRadius > normalRadius)
			{
				return currentlyReturning;
			}
			if (currentlyReturning)
			{
				return distanceFromHome > arrivalRadius;
			}
			if (distanceFromHome > hardChaseRadius)
			{
				return true;
			}
			if (hasCombatTarget)
			{
				if (Numbers.IsNonNegativeFinite(targetDistanceFromHome))
				{
					return targetDistanceFromHome > hardChaseRadius;
				}
				return false;
			}
			return distanceFromHome > normalRadius;
		}

		public static int SelectThreat(CombatContext context, IReadOnlyList<ThreatCandidate> candidates)
		{
			if (context == null)
			{
				throw new ArgumentNullException("context");
			}
			if (candidates == null)
			{
				throw new ArgumentNullException("candidates");
			}
			int result = -1;
			int num = -1;
			bool flag = false;
			float num2 = float.MaxValue;
			for (int i = 0; i < candidates.Count; i++)
			{
				ThreatCandidate threatCandidate = candidates[i];
				if (CanEngage(context, threatCandidate))
				{
					int num3 = (threatCandidate.AttackedOwner ? 5 : (threatCandidate.AttackedSelf ? 4 : ((threatCandidate.AttackedPack || threatCandidate.ThreateningProtected) ? 3 : (threatCandidate.IsWildlife ? 1 : 2))));
					if (num3 > num || (num3 == num && ((threatCandidate.IsCurrentTarget && !flag) || (threatCandidate.IsCurrentTarget == flag && threatCandidate.DistanceFromWolf < num2))))
					{
						result = i;
						num = num3;
						flag = threatCandidate.IsCurrentTarget;
						num2 = threatCandidate.DistanceFromWolf;
					}
				}
			}
			return result;
		}

		public static bool RequiresLocalDefense(CombatContext context, ThreatCandidate candidate)
		{
			if (context != null && candidate != null)
			{
				if (!context.IsReturningHome && !(context.Now < context.ReturnCooldownUntil) && !candidate.NavigationBlocked)
				{
					return candidate.IsLocalDefenseTarget;
				}
				return true;
			}
			return false;
		}

		public static bool IsLocalDefense(CombatContext context, ThreatCandidate candidate)
		{
			if (context == null || candidate == null || !candidate.IsAlive || candidate.IsTamed || context.Mode == WolfMode.Regroup || context.IsRetreating)
			{
				return false;
			}
			if (!Numbers.IsFinite(context.Now) || !Numbers.IsFinite(context.SuppressUntil) || !Numbers.IsFinite(context.ReturnCooldownUntil) || context.Now < context.SuppressUntil)
			{
				return false;
			}
			if (!HasDefensiveThreat(candidate))
			{
				return false;
			}
			if (candidate.NavigationBlocked && !candidate.NewAggressionAfterBlock)
			{
				return false;
			}
			if (!Numbers.IsNonNegativeFinite(candidate.DistanceFromWolf) || !Numbers.IsNonNegativeFinite(context.AssistRadius) || !Numbers.IsNonNegativeFinite(context.DetectionRadius) || candidate.DistanceFromWolf > Math.Min(context.AssistRadius, context.DetectionRadius))
			{
				return false;
			}
			if (IsStationed(context.Mode))
			{
				if (Numbers.IsNonNegativeFinite(context.GuardRadius) && Numbers.IsNonNegativeFinite(context.GuardChaseRadius) && context.GuardChaseRadius >= context.GuardRadius && Numbers.IsNonNegativeFinite(context.WolfDistanceFromAnchor) && Numbers.IsNonNegativeFinite(candidate.DistanceFromAnchor) && context.WolfDistanceFromAnchor <= context.GuardChaseRadius)
				{
					return candidate.DistanceFromAnchor <= context.GuardChaseRadius;
				}
				return false;
			}
			if (context.Mode == WolfMode.Follow)
			{
				if (InEscortChaseRange(context.WolfDistanceFromLeader, EscortTargetRadius(context, candidate)))
				{
					return InEscortChaseRange(candidate.DistanceFromLeader, EscortTargetRadius(context, candidate));
				}
				return false;
			}
			return false;
		}

		public static bool HasDefensiveThreat(ThreatCandidate candidate)
		{
			if (candidate != null)
			{
				if (!candidate.AttackedSelf && !candidate.AttackedPack && !candidate.AttackedOwner)
				{
					if (candidate.ThreateningProtected && candidate.IsHostile && !candidate.IsWildlife)
					{
						return candidate.IsDetected;
					}
					return false;
				}
				return true;
			}
			return false;
		}

		public static bool CanEngage(CombatContext context, ThreatCandidate candidate)
		{
			if (context == null || candidate == null || !candidate.IsAlive || candidate.IsTamed)
			{
				return false;
			}
			if (context.Mode == WolfMode.Regroup || context.IsRetreating)
			{
				return false;
			}
			if (!Numbers.IsFinite(context.Now) || !Numbers.IsFinite(context.SuppressUntil) || !Numbers.IsFinite(context.ReturnCooldownUntil) || context.Now < context.SuppressUntil)
			{
				return false;
			}
			if (RequiresLocalDefense(context, candidate))
			{
				return IsLocalDefense(context, candidate);
			}
			if (!Numbers.IsNonNegativeFinite(candidate.DistanceFromWolf))
			{
				return false;
			}
			bool flag = candidate.AttackedOwner || candidate.AttackedPack || candidate.AttackedSelf;
			if (!candidate.IsHostile && !flag)
			{
				return false;
			}
			if (candidate.IsWildlife && !flag && ((candidate.IsDeer || candidate.IsHare) ? (!context.HuntDeer) : context.IgnoreWildlife))
			{
				return false;
			}
			if (IsStationed(context.Mode))
			{
				if (!Numbers.IsNonNegativeFinite(context.GuardRadius) || !Numbers.IsNonNegativeFinite(context.GuardChaseRadius) || context.GuardChaseRadius < context.GuardRadius || !Numbers.IsNonNegativeFinite(candidate.DistanceFromAnchor))
				{
					return false;
				}
				if (candidate.IsCurrentTarget)
				{
					return candidate.DistanceFromAnchor <= context.GuardChaseRadius;
				}
				if (candidate.DistanceFromAnchor > context.GuardChaseRadius)
				{
					return false;
				}
			}
			else
			{
				if (context.Mode != WolfMode.Follow)
				{
					return false;
				}
				float chaseRadius = EscortTargetRadius(context, candidate);
				if (!InEscortChaseRange(candidate.DistanceFromLeader, chaseRadius) || (candidate.IsManualTarget && !InEscortChaseRange(context.WolfDistanceFromLeader, chaseRadius)))
				{
					return false;
				}
				if (candidate.IsCurrentTarget)
				{
					return true;
				}
			}
			if (!Numbers.IsNonNegativeFinite(context.DetectionRadius) || candidate.DistanceFromWolf > context.DetectionRadius)
			{
				return false;
			}
			if (candidate.IsDetected)
			{
				return true;
			}
			if (flag && Numbers.IsNonNegativeFinite(context.AssistRadius))
			{
				return candidate.DistanceFromWolf <= context.AssistRadius;
			}
			return false;
		}

		public static bool UpdateRetreat(bool currentlyRetreating, float healthFraction, float retreatAt, float recoverAt)
		{
			if (!Numbers.IsFinite(healthFraction) || !Numbers.IsFinite(retreatAt) || !Numbers.IsFinite(recoverAt))
			{
				return currentlyRetreating;
			}
			if (retreatAt <= 0f)
			{
				return false;
			}
			retreatAt = Math.Min(retreatAt, 0.95f);
			recoverAt = Math.Max(retreatAt + 0.05f, Math.Min(recoverAt, 1f));
			if (currentlyRetreating)
			{
				return healthFraction < recoverAt;
			}
			return healthFraction <= retreatAt;
		}
	}
	internal static class Numbers
	{
		internal static bool IsFinite(float value)
		{
			if (!float.IsNaN(value))
			{
				return !float.IsInfinity(value);
			}
			return false;
		}

		internal static bool IsFinite(double value)
		{
			if (!double.IsNaN(value))
			{
				return !double.IsInfinity(value);
			}
			return false;
		}

		internal static bool IsNonNegativeFinite(float value)
		{
			if (IsFinite(value))
			{
				return value >= 0f;
			}
			return false;
		}
	}
}