Decompiled source of Taming v0.1.66

BepInEx/plugins/Zephyrfit-Taming/ZephyrfitTaming.dll

Decompiled 2 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using Splatform;
using TMPro;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;
using UnityEngine.TextCore;
using UnityEngine.UI;
using YamlDotNet.Serialization;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("ZephyrfitTaming")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.66.0")]
[assembly: AssemblyInformationalVersion("0.1.66")]
[assembly: AssemblyProduct("ZephyrfitTaming")]
[assembly: AssemblyTitle("ZephyrfitTaming")]
[assembly: AssemblyVersion("0.1.66.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 Zephyrfit.Taming
{
	internal static class AdditionalMountsNativeRegression
	{
		internal static int Inspect(Func<string, Character> actor, ZNetScene scene)
		{
			//IL_03bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0668: Unknown result type (might be due to invalid IL or missing references)
			//IL_067c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0681: Unknown result type (might be due to invalid IL or missing references)
			//IL_0686: Unknown result type (might be due to invalid IL or missing references)
			//IL_068d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0697: Unknown result type (might be due to invalid IL or missing references)
			//IL_069c: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_06b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_06bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_06c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0866: Unknown result type (might be due to invalid IL or missing references)
			//IL_086b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0879: Unknown result type (might be due to invalid IL or missing references)
			//IL_087e: Unknown result type (might be due to invalid IL or missing references)
			//IL_08ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_08b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_08d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_08dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a7c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a88: Unknown result type (might be due to invalid IL or missing references)
			//IL_0aa6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ab2: Unknown result type (might be due to invalid IL or missing references)
			int checks = 0;
			TameRule value3;
			Dictionary<string, MountRule> dictionary = CreatureMapCatalog.AdditionalMounts.ToDictionary((string s) => s, (string s) => (!MountUpSetup.customMounts.TryGetValue(s, out value3)) ? null : value3);
			string value = MountRegistry.Allow.Value;
			MountRegistrySnapshot snapshot = MountRegistry.Snapshot;
			PresetCatalog server = PresetLibrary.Server;
			Dictionary<string, object> dictionary2 = new string[3] { "identity", "fingerprint", "records" }.ToDictionary((string n) => n, (string n) => AccessTools.Field(typeof(MountRegistry), n).GetValue(null));
			RuleTable<TameRule> tames = Providers.Tames;
			Dictionary<string, TameRule> dictionary3 = CreatureMapCatalog.AdditionalMounts.ToDictionary((string s) => s, (string s) => (!tames.TryGetValue(s, out value3)) ? null : value3);
			bool value2 = Plugin.Markers.Value;
			Plugin.Markers.Value = true;
			List<MountPackVisual> list = new List<MountPackVisual>();
			string text = Path.Combine(PresetLibrary.Folder, "diagnostics", "mounts043");
			Directory.CreateDirectory(text);
			try
			{
				string[] additionalMounts = CreatureMapCatalog.AdditionalMounts;
				foreach (string text2 in additionalMounts)
				{
					GameObject prefab = PrefabManager.Instance.GetPrefab(text2);
					Check(Object.op_Implicit((Object)(object)prefab) && Object.op_Implicit((Object)(object)prefab.GetComponent<Humanoid>()) && Object.op_Implicit((Object)(object)prefab.GetComponent<MonsterAI>()), text2 + " native supported rig/AI available");
					((Dictionary<int, GameObject>)AccessTools.Field(typeof(ZNetScene), "m_namedPrefabs").GetValue(scene))[StringExtensionMethods.GetStableHashCode(text2)] = prefab;
					Transform val = prefab.transform.Find("Visual");
					Check(Object.op_Implicit((Object)(object)val), text2 + " native Visual root");
					Transform val2 = ((IEnumerable<Transform>)((Component)val).GetComponentsInChildren<Transform>(true)).FirstOrDefault((Func<Transform, bool>)((Transform t) => ((Object)t).name.Equals("Spine2", StringComparison.OrdinalIgnoreCase))) ?? ((IEnumerable<Transform>)((Component)val).GetComponentsInChildren<Transform>(true)).FirstOrDefault((Func<Transform, bool>)((Transform t) => ((Object)t).name.Equals("Spine1", StringComparison.OrdinalIgnoreCase))) ?? ((IEnumerable<Transform>)((Component)val).GetComponentsInChildren<Transform>(true)).FirstOrDefault((Func<Transform, bool>)((Transform t) => ((Object)t).name.IndexOf("spine", StringComparison.OrdinalIgnoreCase) >= 0));
					Check(Object.op_Implicit((Object)(object)val2), text2 + " verified native spinal attachment");
					string text3 = MountMorphology.Path(val, val2);
					Check(PresetRules.Anchor(text3), text2 + " native path fits placement schema");
					MountUpSetup.customMounts[text2] = new MountRule
					{
						PrefabName = text2,
						mountPath = text3,
						customSaddle = "Zephyrfit_BjornSaddle",
						saddleTier = 0,
						stamina = 120f,
						flyingStamina = -1f
					};
					tames[text2] = new TameRule
					{
						consumeItems = "Raspberry",
						tamingTime = 3600f,
						procreation = false
					};
					File.AppendAllText(Path.Combine(text, "verified-mount-paths.txt"), text2 + "\n  mountPath: " + text3 + "\n");
					Plugin.Info("MOUNT043 CONFIG species=" + text2 + " attachment=" + text3 + " flying=" + prefab.GetComponent<Character>().IsFlying() + " nativeScale=" + ((object)prefab.transform.localScale/*cast due to .constrained prefix*/).ToString());
				}
				MountRegistry.Allow.Value = "Troll,Hatchling,GoblinBrute";
				AccessTools.Method(typeof(MountRegistry), "Build", (Type[])null, (Type[])null).Invoke(null, Array.Empty<object>());
				Check(CreatureMapCatalog.AdditionalMounts.All(MountRegistry.Allowed), "effective server registry admits declared/allowed three species");
				Check(!MountRegistry.Allowed("Wolf"), "registry never bypasses explicit species allowlist");
				PresetLibrary.Server = new PresetCatalog
				{
					scope = MountRegistry.Scope
				};
				additionalMounts = CreatureMapCatalog.AdditionalMounts;
				foreach (string text4 in additionalMounts)
				{
					MountRule mountRule = MountUpSetup.customMounts[text4];
					TameRule tameRule = tames[text4];
					Policy.LimitList(tames);
					Policy.LimitMounts();
					Check(mountRule == MountUpSetup.customMounts[text4] && tameRule == tames[text4] && tameRule.consumeItems == "Raspberry", text4 + " external declaration and diet preserved");
					Character val3 = actor(text4);
					ZNetView component = ((Component)val3).GetComponent<ZNetView>();
					Tameable component2 = ((Component)val3).GetComponent<Tameable>();
					Component component3 = ((Component)val3).GetComponent(Providers.Mountable);
					Check(Object.op_Implicit((Object)(object)component3) && Object.op_Implicit((Object)(object)component2.m_saddle) && Object.op_Implicit((Object)(object)component2.m_saddle.m_attachPoint), text4 + " dependency actually builds native saddle and seat");
					bool flag = MountUpSetup.CanFly(val3);
					MountPlacement mountPlacement = MountPlacement.Bind(val3);
					Check(Object.op_Implicit((Object)(object)mountPlacement) && mountPlacement.Ready(), text4 + " generic placement binds actual dependency rig");
					MountPlacement p = mountPlacement;
					Dictionary<Transform, (Vector3, Quaternion, Vector3)> dictionary4 = (from t in ((Component)p.Visual).GetComponentsInChildren<Transform>(true)
						where !t.IsChildOf(p.Model) && (Object)(object)t != (Object)(object)p.Seat && !p.OwnedVisual(t)
						select t).ToDictionary((Transform t) => t, (Transform t) => (localPosition: t.localPosition, localRotation: t.localRotation, localScale: t.localScale));
					string[] array = StyleIds.For(text4);
					foreach (string text5 in array)
					{
						component.GetZDO().Set("zf_saddle_style_v1", text5);
						PlacementPreset placementPreset = p.CaptureNative();
						placementPreset.Style = text5;
						placementPreset.Enabled = true;
						placementPreset.Position += new Vector3(0.03f, 0.02f, -0.01f);
						placementPreset.Scale = Vector3.one * 0.95f;
						placementPreset.Seat += new Vector3(0.03f, 0.06f, 0.04f);
						placementPreset.Packs = MountPackVisual.AutomaticPlacement(p);
						placementPreset.Packs.position[1] += 0.04f;
						MountPlacement.Previews[((Object)p).GetInstanceID()] = placementPreset.Copy();
						p.Apply();
						if (text5 != "native")
						{
							Check(Object.op_Implicit((Object)(object)((Component)p.Model).GetComponent<SaddleStyleRenderer>().PickSurface), text4 + "/" + text5 + " authored saddle exists");
						}
						else
						{
							Check(((Component)p.Model).GetComponent<SaddleStyleRenderer>().NativeRenderers.Any((Renderer r) => Object.op_Implicit((Object)(object)r) && r.enabled), text4 + " native saddle remains available");
						}
						PresetRecord presetRecord = PresetLibrary.Record(text4, placementPreset, "Configured " + text4);
						Check(PresetRules.Valid(presetRecord), text4 + "/" + text5 + " F9 schema supports complete placement");
						component.GetZDO().Set("zf_active_placement_v1", PresetJson.ToJson(new ActivePlacementRecord
						{
							scope = MountRegistry.Scope,
							species = text4,
							style = text5,
							revision = 1,
							placement = presetRecord,
							source = "fixture"
						}));
						MountPlacement.Previews.Remove(((Object)p).GetInstanceID());
						p.Apply();
						Vector3 position = p.Seat.position;
						Vector3 position2 = p.Model.position;
						AccessTools.Method(Providers.Mountable, "ResetMountPoint", (Type[])null, (Type[])null).Invoke(component3, Array.Empty<object>());
						Near(p.Seat.position, position, text4 + "/" + text5 + " dependency reset retains saved rider offset");
						Near(p.Model.position, position2, text4 + "/" + text5 + " dependency reset retains saddle position");
						MountPackVisual mountPackVisual = new MountPackVisual();
						list.Add(mountPackVisual);
						mountPackVisual.ShowPlacement(p, placementPreset.Packs, 1, cosmetic: true);
						Check(((Component)p.Visual).GetComponentsInChildren<Transform>(true).Any((Transform t) => ((Object)t).name == "ZF_CosmeticPanniers"), text4 + "/" + text5 + " F9 cosmetic pannier editor available");
						mountPackVisual.Clear();
					}
					PresetLibrary.Save(PresetLibrary.Record(text4, p.Effective, "Personal " + text4));
					Check(PresetLibrary.Selected(text4, p.Style)?.species == text4, text4 + " F9 personal model stored and selected");
					MountPanel obj = Object.FindAnyObjectByType<MountPanel>();
					AccessTools.Method(typeof(MountPanel), "Select", (Type[])null, (Type[])null).Invoke(obj, new object[1] { p });
					Check((string)AccessTools.Field(typeof(MountPanel), "species").GetValue(obj) == text4, text4 + " F9 selects declared mount");
					foreach (KeyValuePair<Transform, (Vector3, Quaternion, Vector3)> item in dictionary4)
					{
						if (Object.op_Implicit((Object)(object)item.Key))
						{
							Near(item.Key.localPosition, item.Value.Item1, text4 + " rig position retained");
							Check(Quaternion.Angle(item.Key.localRotation, item.Value.Item2) < 0.02f, text4 + " rig rotation retained");
						}
					}
					Check(MountUpSetup.CanFly(val3) == flag && (Object)(object)((Component)val3).GetComponent<MountRiding>() == (Object)null, text4 + " dependency flight/movement retained");
					p.Release();
					Check(p.Effective == null && !PlacementLifecycle.Bound.Contains(p) && AccessTools.Field(typeof(RiderPlacement), "placement").GetValue(((Component)val3).GetComponent<RiderPlacement>()) == null, text4 + " release clears owned placement references");
				}
				ZRoutedRpc instance = ZRoutedRpc.instance;
				MountMarkers.Reset();
				MountMarkers.Tick();
				MountMarkers.Reset();
				MountMarkers.Tick();
				Check(instance == ZRoutedRpc.instance, "map reset safely reuses the same native RPC instance without duplicate registration");
				for (int num3 = 0; num3 < 80; num3++)
				{
					if (CreatureMapCatalog.AdditionalMounts.All((string s) => MountMarkers.Snapshot().Any((MountMarkers.Record r) => r.Species == s)))
					{
						break;
					}
					AccessTools.Field(typeof(MountMarkers), "next").SetValue(null, 0.0);
					MountMarkers.Tick();
				}
				additionalMounts = CreatureMapCatalog.AdditionalMounts;
				foreach (string species in additionalMounts)
				{
					MountMarkers.Record record = MountMarkers.Snapshot().FirstOrDefault((MountMarkers.Record r) => r.Species == species);
					Check(record != null, species + " actual tamed ZDO is tracked");
					Check(MountMarkers.Label(record, lastKnown: false) == MountMarkers.SpeciesLabel(species), species + " marker label uses localized species");
				}
				Plugin.Info("MOUNT043 PASS " + checks + " native inactive-prefab checks; all nineteen styles + native saddle, F9 placement, persistent offsets and dependency reset. No real riding, flight or multiplayer claim.");
				return checks;
			}
			finally
			{
				foreach (MountPackVisual item2 in list)
				{
					item2.Clear();
				}
				MountPlacement.Previews.Clear();
				MountMarkers.Reset();
				Plugin.Markers.Value = value2;
				foreach (KeyValuePair<string, MountRule> item3 in dictionary)
				{
					if (item3.Value == null)
					{
						MountUpSetup.customMounts.Remove(item3.Key);
					}
					else
					{
						MountUpSetup.customMounts[item3.Key] = item3.Value;
					}
				}
				foreach (KeyValuePair<string, TameRule> item4 in dictionary3)
				{
					if (item4.Value == null)
					{
						tames.Remove(item4.Key);
					}
					else
					{
						tames[item4.Key] = item4.Value;
					}
				}
				MountRegistry.Allow.Value = value;
				MountRegistry.Snapshot = snapshot;
				PresetLibrary.Server = server;
				foreach (KeyValuePair<string, object> item5 in dictionary2)
				{
					AccessTools.Field(typeof(MountRegistry), item5.Key).SetValue(null, item5.Value);
				}
			}
			void Check(bool okay, string why)
			{
				if (!okay)
				{
					throw new InvalidOperationException(why);
				}
				checks++;
			}
			unsafe void Near(Vector3 a, Vector3 b, string why)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_003d: Unknown result type (might be due to invalid IL or missing references)
				//IL_003e: Unknown result type (might be due to invalid IL or missing references)
				bool okay = Vector3.Distance(a, b) < 0.0003f;
				string[] obj2 = new string[5] { why, " ", null, null, null };
				Vector3 val4 = a;
				obj2[2] = ((object)(*(Vector3*)(&val4))/*cast due to .constrained prefix*/).ToString();
				obj2[3] = " vs ";
				val4 = b;
				obj2[4] = ((object)(*(Vector3*)(&val4))/*cast due to .constrained prefix*/).ToString();
				Check(okay, string.Concat(obj2));
			}
		}
	}
	[Serializable]
	internal sealed class AdminCreatureOptions
	{
		public string name = "";

		public string sex = "Automatic";

		[OptionalField]
		public int packs;

		internal bool Valid(SexMode mode, string species, int level, int packLimit = 0)
		{
			if (ValidName(name) && packs >= 0 && (packs == 0 || packs <= packLimit))
			{
				if (!(sex == "Automatic"))
				{
					if (mode == SexMode.MaleFemale && (sex == "Male" || sex == "Female"))
					{
						if (!(species != "Deer"))
						{
							return sex == "Female" == (level == 1);
						}
						return true;
					}
					return false;
				}
				return true;
			}
			return false;
		}

		internal static bool ValidName(string value)
		{
			if (value != null && value.Length <= 64)
			{
				return !value.Any((char c) => char.IsControl(c) || c == '<' || c == '>');
			}
			return false;
		}
	}
	internal static class MountAdministration
	{
		private enum Removal
		{
			Clear,
			Missing,
			Identity,
			Position,
			Range,
			Ward,
			Rider,
			Saddle,
			Bags,
			Cargo,
			Inventory,
			Marker,
			Confirmation,
			Owner,
			Pending,
			Timeout,
			Internal
		}

		private sealed class PendingDespawn
		{
			internal string Operation = "";

			internal string Species = "";

			internal long Client;

			internal long Owner;

			internal ZDOID Target;

			internal float Until;

			internal bool OwnerRemoved;
		}

		private sealed class PendingSpawn
		{
			internal long Client;

			internal long Player;

			internal string Species = "";

			internal string Marker = "";

			internal string CapSource = "";

			internal int Level;

			internal int Cap;

			internal Vector3 Center;

			internal AdminCreatureOptions Options;

			internal float Until;

			internal bool Acknowledged;

			internal ZDOID Target;
		}

		private sealed class SpawnReply
		{
			internal bool Success;

			internal string Text = "";

			internal ZDOID Target;
		}

		internal const float DespawnRange = 15f;

		private const string DespawnGrantRpc = "ZF_AdminDespawnGrant_v1";

		private const string DespawnAckRpc = "ZF_AdminDespawnAck_v1";

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

		private const string SpawnGrantRpc = "ZF_MountAdminSpawnGrant_v1";

		private const string SpawnAckRpc = "ZF_MountAdminSpawnAck_v1";

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

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

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

		internal const string Marker = "zf_wizard_test_v1";

		private const string RequestRpc = "ZF_MountAdminRequest_v1";

		private const string ResultRpc = "ZF_MountAdminResult_v1";

		private const string MotionRpc = "ZF_MountAdminMotion_v1";

		private static ZNet? world;

		private static ZRoutedRpc? rpc;

		private static byte[]? secret;

		private static string receiptScope = "";

		private static TestSpawnReceipts receipts = new TestSpawnReceipts();

		private static readonly Dictionary<string, Action<bool, string, ZDOID>> callbacks = new Dictionary<string, Action<bool, string, ZDOID>>();

		private static readonly Dictionary<long, float> rate = new Dictionary<long, float>();

		private static string ReceiptFile => Path.Combine(PresetLibrary.Folder, "wizard-tests", MountRegistry.Scope.Replace(':', '_') + ".json");

		private static void RegisterDespawns()
		{
			rpc.Register<ZPackage>("ZF_AdminDespawnGrant_v1", (Action<long, ZPackage>)delegate(long sender, ZPackage packet)
			{
				ReadRemovalPacket(sender, packet, ReceiveDespawnGrant);
			});
			rpc.Register<ZPackage>("ZF_AdminDespawnAck_v1", (Action<long, ZPackage>)delegate(long sender, ZPackage packet)
			{
				ReadRemovalPacket(sender, packet, ReceiveDespawnAck);
			});
		}

		private static void ReadRemovalPacket(long sender, ZPackage packet, Action<long, ZPackage> read)
		{
			if (packet == null || packet.Size() > 2048)
			{
				return;
			}
			try
			{
				read(sender, packet);
			}
			catch (Exception ex) when (ex is IOException || ex is FormatException || ex is ArgumentException)
			{
				MountRegistry.Diagnostic("despawn-packet", "Invalid removal message: " + ex.GetType().Name);
			}
		}

		private static string RemovalMessage(Removal reason)
		{
			return reason switch
			{
				Removal.Missing => "This creature is no longer present.", 
				Removal.Identity => "The selected creature or species has changed.", 
				Removal.Position => "The creature or administrator position is unavailable.", 
				Removal.Range => "Move within 15 m of the creature.", 
				Removal.Ward => "A ward denies access to this creature.", 
				Removal.Rider => "The creature still has a rider.", 
				Removal.Saddle => "Remove the saddle before removing the creature.", 
				Removal.Bags => "Remove all saddlebag pairs before removing the creature.", 
				Removal.Cargo => "Recover the stored cargo before removing the creature.", 
				Removal.Inventory => "Recover the creature's equipment or external storage first.", 
				Removal.Marker => "Select a signed test animal or confirm removal under Natural creatures.", 
				Removal.Confirmation => "Confirm removal of this exact creature under Natural creatures.", 
				Removal.Owner => "The creature's simulation owner is unavailable or has changed. Select it again.", 
				Removal.Pending => "A creature removal is already pending. Please wait.", 
				Removal.Timeout => "Removal was not confirmed. Check the creature before trying again.", 
				_ => "The creature's equipment could not be verified.", 
			};
		}

		private static Removal Protection(ZDO z)
		{
			if (z.GetLong(ZDOVars.s_user, 0L) != 0L)
			{
				return Removal.Rider;
			}
			if (z.GetBool("zf_mount_packs_v1", false) || z.GetInt("zf_mount_pack_pairs_v1", 0) > 0)
			{
				return Removal.Bags;
			}
			byte[] byteArray = z.GetByteArray("zf_mount_pack_items_v1", (byte[])null);
			if (((byteArray != null && byteArray.Length != 0) ? 1 : 0) <= (false ? 1 : 0))
			{
				byte[] byteArray2 = z.GetByteArray(MountPackStorage.DataKey(1), (byte[])null);
				if (((byteArray2 != null && byteArray2.Length != 0) ? 1 : 0) <= (false ? 1 : 0))
				{
					if (z.GetBool(ZDOVars.s_haveSaddleHash, false))
					{
						return Removal.Saddle;
					}
					return Removal.Clear;
				}
			}
			return Removal.Cargo;
		}

		private static Removal Identity(string op, string confirmation, string species, ZDO z)
		{
			if (op == "despawn")
			{
				if (!Marked(z, species))
				{
					return Removal.Marker;
				}
				return Removal.Clear;
			}
			if (!(op == "despawnNatural") || !(confirmation == ((object)Unsafe.As<ZDOID, ZDOID>(ref z.m_uid)/*cast due to .constrained prefix*/).ToString()))
			{
				return Removal.Confirmation;
			}
			return Removal.Clear;
		}

		private static Removal LiveEquipment(GameObject go, GameObject prefab, ZDO z)
		{
			if (Object.op_Implicit((Object)(object)go.GetComponent<Player>()) || !Object.op_Implicit((Object)(object)go.GetComponent<Character>()))
			{
				return Removal.Identity;
			}
			Removal removal = Protection(z);
			if (removal != Removal.Clear)
			{
				return removal;
			}
			if (MountInteractions.Occupied(go.GetComponent<Tameable>()?.m_saddle))
			{
				return Removal.Rider;
			}
			if (!MountPacks.Foreign(go.GetComponent<Character>()) && !HasNonDefaultInventory(go, prefab))
			{
				return Removal.Clear;
			}
			return Removal.Inventory;
		}

		internal static void ValidateDespawn(string operation, string confirmation, string species, GameObject go, GameObject prefab, ZDO z)
		{
			Removal removal = Identity(operation, confirmation, species, z);
			if (removal == Removal.Clear)
			{
				removal = LiveEquipment(go, prefab, z);
			}
			if (removal != Removal.Clear)
			{
				throw new InvalidOperationException(RemovalMessage(removal));
			}
		}

		private static Removal Location(Vector3 center, Vector3 point, long player)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			if (!SaddleGeometry.Finite(center) || !SaddleGeometry.Finite(point))
			{
				return Removal.Position;
			}
			if (!Nearby(center, point, 15.0))
			{
				return Removal.Range;
			}
			if (!MountPacks.Access(player, point))
			{
				return Removal.Ward;
			}
			return Removal.Clear;
		}

		private static void BeginDespawn(long sender, string id, string op, string species, ZDOID target, string data, ZDO player, long playerId, Vector3 center)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: 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)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0280: Unknown result type (might be due to invalid IL or missing references)
			//IL_0287: Expected O, but got Unknown
			//IL_0299: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0268: Unknown result type (might be due to invalid IL or missing references)
			//IL_0327: Unknown result type (might be due to invalid IL or missing references)
			//IL_0331: Expected O, but got Unknown
			ZDO zDO = ZDOMan.instance.GetZDO(target);
			GameObject val = ((zDO == null) ? null : ZNetScene.instance.GetPrefab(zDO.GetPrefab()));
			long num = ((zDO != null) ? zDO.GetOwner() : 0);
			PendingDespawn value = new PendingDespawn
			{
				Client = sender,
				Operation = op,
				Species = species,
				Target = target,
				Owner = num,
				Until = Time.realtimeSinceStartup + 12f
			};
			Removal removal = Removal.Clear;
			if (zDO == null)
			{
				removal = Removal.Missing;
			}
			else if (!Object.op_Implicit((Object)(object)val) || ((Object)val).name != species || !AdministrativeTaming.Eligible(val))
			{
				removal = Removal.Identity;
			}
			else if ((removal = Location(center, zDO.GetPosition(), playerId)) == Removal.Clear && (removal = Identity(op, data, species, zDO)) == Removal.Clear && (removal = Protection(zDO)) == Removal.Clear)
			{
				if (num == 0L || (num != ZDOMan.GetSessionID() && world.GetPeer(num) == null))
				{
					removal = Removal.Owner;
				}
				else if (pendingDespawns.Count >= 32 || pendingDespawns.ContainsKey(id) || pendingDespawns.Values.Any((PendingDespawn p) => p.Target == target))
				{
					removal = Removal.Pending;
				}
			}
			string text = ((zDO == null) ? "?" : Vector3.Distance(center, zDO.GetPosition()).ToString("0.0", CultureInfo.InvariantCulture));
			Plugin.Info(string.Format("ADMIN {0} target={1} prefab={2} zdo={3} serverInstance={4} distance={5}m rider={6} saddle={7} pairs={8} owner={9} decision={10}", op, target, species, zDO != null, Object.op_Implicit((Object)(object)ZNetScene.instance.FindInstance(target)), text, (zDO != null) ? new long?(zDO.GetLong(ZDOVars.s_user, 0L)) : ((long?)null), (zDO != null) ? new bool?(zDO.GetBool(ZDOVars.s_haveSaddleHash, false)) : ((bool?)null), (zDO != null) ? new int?(zDO.GetInt("zf_mount_pack_pairs_v1", 0)) : ((int?)null), num, removal));
			if (removal != Removal.Clear)
			{
				Deliver(sender, id, success: false, Texts.ErrorNotice(RemovalMessage(removal)), target);
				return;
			}
			pendingDespawns.Add(id, value);
			ZPackage val2 = new ZPackage();
			Header(val2);
			val2.Write(id);
			val2.Write(target);
			val2.Write(species);
			val2.Write(op == "despawn");
			val2.Write(zDO.GetString("zf_wizard_test_v1", ""));
			val2.Write(player.m_uid);
			val2.Write(playerId);
			val2.Write(world.GetTime().AddSeconds(8.0).Ticks);
			if (num == ZDOMan.GetSessionID())
			{
				ReceiveDespawnGrant(num, new ZPackage(val2.GetArray()));
				return;
			}
			rpc.InvokeRoutedRPC(num, "ZF_AdminDespawnGrant_v1", new object[1] { val2 });
		}

		private static void ReceiveDespawnGrant(long sender, ZPackage p)
		{
			//IL_025a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0261: Expected O, but got Unknown
			//IL_0272: Unknown result type (might be due to invalid IL or missing references)
			//IL_0295: Unknown result type (might be due to invalid IL or missing references)
			//IL_029f: Expected O, but got Unknown
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_020d: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)world) || PlacementLifecycle.Ending || p.Size() > 2048)
			{
				return;
			}
			long num = (world.IsServer() ? ZDOMan.GetSessionID() : (world.GetServerPeer()?.m_uid ?? 0));
			if (sender != num || num == 0L || !ReadHeader(p))
			{
				return;
			}
			string text = p.ReadString();
			ZDOID val = p.ReadZDOID();
			string text2 = p.ReadString();
			bool flag = p.ReadBool();
			string text3 = p.ReadString();
			ZDOID val2 = p.ReadZDOID();
			long num2 = p.ReadLong();
			long num3 = p.ReadLong();
			if (!Guid.TryParseExact(text, "N", out var _) || !MountBridgeRules.Prefab(text2) || text3.Length > 256 || p.GetPos() != p.Size())
			{
				return;
			}
			Removal removal = Removal.Internal;
			try
			{
				GameObject val3 = ZNetScene.instance.FindInstance(val);
				ZNetView val4 = (Object.op_Implicit((Object)(object)val3) ? val3.GetComponent<ZNetView>() : null);
				GameObject prefab = ZNetScene.instance.GetPrefab(text2);
				ZDO zDO = ZDOMan.instance.GetZDO(val2);
				if (world.GetTime().Ticks > num3)
				{
					removal = Removal.Timeout;
				}
				else if (!Object.op_Implicit((Object)(object)val4) || !val4.IsValid() || !val4.IsOwner())
				{
					removal = Removal.Owner;
				}
				else if (val4.GetZDO().m_uid != val || !Object.op_Implicit((Object)(object)prefab) || val4.GetZDO().GetPrefab() != StringExtensionMethods.GetStableHashCode(((Object)prefab).name) || !AdministrativeTaming.Eligible(val3) || Utils.GetPrefabName(val3) != text2)
				{
					removal = Removal.Identity;
				}
				else if (zDO == null || zDO.GetLong(ZDOVars.s_playerID, 0L) != num2 || !CreatureState.Alive(zDO))
				{
					removal = Removal.Position;
				}
				else if (flag && (text3.Length == 0 || val4.GetZDO().GetString("zf_wizard_test_v1", "") != text3))
				{
					removal = Removal.Marker;
				}
				else if ((removal = Location(zDO.GetPosition(), val3.transform.position, num2)) == Removal.Clear && (removal = LiveEquipment(val3, prefab, val4.GetZDO())) == Removal.Clear)
				{
					ZNetScene.instance.Destroy(val3);
				}
			}
			catch (Exception ex)
			{
				removal = Removal.Internal;
				MountRegistry.Diagnostic("despawn-owner", ex.ToString());
			}
			ZPackage val5 = new ZPackage();
			Header(val5);
			val5.Write(text);
			val5.Write(val);
			val5.Write((int)removal);
			if (world.IsServer())
			{
				ReceiveDespawnAck(num, new ZPackage(val5.GetArray()));
				return;
			}
			rpc.InvokeRoutedRPC(num, "ZF_AdminDespawnAck_v1", new object[1] { val5 });
		}

		private static void ReceiveDespawnAck(long sender, ZPackage p)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)world) || !world.IsServer() || PlacementLifecycle.Ending || p.Size() > 512 || !ReadHeader(p))
			{
				return;
			}
			string text = p.ReadString();
			ZDOID val = p.ReadZDOID();
			Removal removal = (Removal)p.ReadInt();
			if (p.GetPos() == p.Size() && pendingDespawns.TryGetValue(text, out PendingDespawn value) && value.Owner == sender && !(value.Target != val) && !value.OwnerRemoved && Enum.IsDefined(typeof(Removal), removal))
			{
				if (removal != Removal.Clear)
				{
					EndDespawn(text, value, removal);
				}
				else
				{
					value.OwnerRemoved = true;
				}
			}
		}

		private static void TickDespawns()
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			if (pendingDespawns.Count == 0)
			{
				return;
			}
			KeyValuePair<string, PendingDespawn>[] array = pendingDespawns.ToArray();
			for (int i = 0; i < array.Length; i++)
			{
				KeyValuePair<string, PendingDespawn> keyValuePair = array[i];
				PendingDespawn value = keyValuePair.Value;
				if (value.OwnerRemoved && ZDOMan.instance.GetZDO(value.Target) == null)
				{
					EndDespawn(keyValuePair.Key, value, Removal.Clear);
				}
				else if (Time.realtimeSinceStartup > value.Until)
				{
					EndDespawn(keyValuePair.Key, value, Removal.Timeout);
				}
			}
		}

		private static void EndDespawn(string id, PendingDespawn request, Removal reason)
		{
			//IL_0028: 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_00c4: Unknown result type (might be due to invalid IL or missing references)
			pendingDespawns.Remove(id);
			bool flag = reason == Removal.Clear;
			Plugin.Info(string.Format("ADMIN {0} target={1} prefab={2} owner={3} ownerRemoved={4} serverZdoPresent={5} result={6}", request.Operation, request.Target, request.Species, request.Owner, request.OwnerRemoved, ZDOMan.instance.GetZDO(request.Target) != null, flag ? "removed" : reason.ToString()));
			Deliver(request.Client, id, flag, flag ? Texts.Wire("Créature supprimée.", "Creature removed.") : Texts.ErrorNotice(RemovalMessage(reason)), request.Target);
		}

		internal static int PackLimit(string species)
		{
			MountSpeciesRecord mountSpeciesRecord = MountRegistry.Get(species);
			if (!MountPacks.Enabled.Value || mountSpeciesRecord == null || !mountSpeciesRecord.storage)
			{
				return 0;
			}
			return mountSpeciesRecord.capacity.pairs;
		}

		private static void ResetSpawns()
		{
			pendingSpawns.Clear();
			localSpawnUntil.Clear();
			spawnReplies.Clear();
		}

		private static void RegisterSpawns()
		{
			rpc.Register<ZPackage>("ZF_MountAdminSpawnGrant_v1", (Action<long, ZPackage>)ReceiveSpawnGrant);
			rpc.Register<ZPackage>("ZF_MountAdminSpawnAck_v1", (Action<long, ZPackage>)ReceiveSpawnAck);
		}

		private static bool Nearby(Vector3 a, Vector3 b, double radius = 12.0)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			return AdminSpawnRules.Near(a.x, a.y, a.z, b.x, b.y, b.z, radius);
		}

		private static void QueueSpawn(long sender, string id, string species, int level, Vector3 center, long player, AdminCreatureOptions options, int cap, string capSource)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: 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)
			//IL_00c1: Expected O, but got Unknown
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Expected O, but got Unknown
			if (pendingSpawns.Count >= 32)
			{
				throw new InvalidOperationException("Too many pending creature creations");
			}
			PendingSpawn pendingSpawn = new PendingSpawn
			{
				Client = sender,
				Player = player,
				Species = species,
				Level = level,
				Center = center,
				Options = options,
				Cap = cap,
				CapSource = capSource,
				Marker = id + "|" + Sign(id, species),
				Until = Time.realtimeSinceStartup + 10f
			};
			receipts.created[id] = "pending";
			PresetLibrary.Write(ReceiptFile, PresetJson.ToJson(receipts));
			pendingSpawns.Add(id, pendingSpawn);
			ZPackage val = new ZPackage();
			Header(val);
			val.Write(id);
			val.Write(species);
			val.Write(level);
			val.Write(center);
			val.Write(player);
			val.Write(pendingSpawn.Marker);
			val.Write(PresetJson.ToJson(options));
			if (sender == ZDOMan.GetSessionID())
			{
				ReceiveSpawnGrant(sender, new ZPackage(val.GetArray()));
				return;
			}
			rpc.InvokeRoutedRPC(sender, "ZF_MountAdminSpawnGrant_v1", new object[1] { val });
		}

		private static void ReceiveSpawnGrant(long sender, ZPackage p)
		{
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_021a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0343: Unknown result type (might be due to invalid IL or missing references)
			//IL_0348: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a4: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)world) || PlacementLifecycle.Ending || !Plugin.ConfigReady || !SynchronizationAccess.Admin || p.Size() > 8192)
			{
				return;
			}
			long num = (world.IsServer() ? ZDOMan.GetSessionID() : (world.GetServerPeer()?.m_uid ?? 0));
			if (sender != num || num == 0L)
			{
				return;
			}
			string text = "";
			GameObject val = null;
			try
			{
				if (!ReadHeader(p))
				{
					return;
				}
				text = p.ReadString();
				string text2 = p.ReadString();
				int num2 = p.ReadInt();
				Vector3 val2 = p.ReadVector3();
				long num3 = p.ReadLong();
				string text3 = p.ReadString();
				string text4 = p.ReadString();
				if (!Guid.TryParseExact(text, "N", out var _) || !MountBridgeRules.Prefab(text2) || num2 < 1 || num2 > 1000 || !SaddleGeometry.Finite(val2) || text3.Length > 256 || !text3.StartsWith(text + "|", StringComparison.Ordinal) || text4.Length > 4096 || p.GetPos() != p.Size() || !callbacks.ContainsKey(text) || !localSpawnUntil.TryGetValue(text, out var value) || Time.realtimeSinceStartup > value)
				{
					return;
				}
				if (spawnReplies.TryGetValue(text, out SpawnReply value2))
				{
					SendSpawnAck(text, value2);
					return;
				}
				SpawnReply spawnReply = new SpawnReply();
				spawnReplies.Add(text, spawnReply);
				Player localPlayer = Player.m_localPlayer;
				ZNetView val3 = (Object.op_Implicit((Object)(object)localPlayer) ? ((Component)localPlayer).GetComponent<ZNetView>() : null);
				if (!Object.op_Implicit((Object)(object)localPlayer) || ((Character)localPlayer).IsDead() || !Object.op_Implicit((Object)(object)val3) || !val3.IsValid() || !val3.IsOwner() || val3.GetZDO().GetLong(ZDOVars.s_playerID, 0L) != num3 || !Nearby(((Component)localPlayer).transform.position, val2) || !Object.op_Implicit((Object)(object)ZNetScene.instance) || !Object.op_Implicit((Object)(object)ZoneSystem.instance) || !AdministrativeTaming.CanTame(text2) || !MountPacks.Access(num3, val2))
				{
					spawnReply.Text = Texts.Wire("Le joueur ou la scène a changé ; aucun animal créé.", "Player or scene changed; no creature created.");
					SendSpawnAck(text, spawnReply);
					return;
				}
				GameObject prefab = ZNetScene.instance.GetPrefab(text2);
				AdminCreatureOptions adminCreatureOptions = PresetJson.FromJson<AdminCreatureOptions>(text4);
				if (!Object.op_Implicit((Object)(object)prefab) || !prefab.activeSelf || Object.op_Implicit((Object)(object)prefab.GetComponent<Growup>()) || adminCreatureOptions == null || !adminCreatureOptions.Valid(AnimalSexState.SpeciesMode(text2), text2, num2, PackLimit(text2)))
				{
					spawnReply.Text = Texts.Wire("Les réglages de la créature ont changé ; rouvrir le menu administrateur.", "Creature settings changed; reopen the administrator panel.");
					SendSpawnAck(text, spawnReply);
					return;
				}
				if (!TrySpawnGround(val2, num3, prefab, out Vector3 spawn, out string failure))
				{
					spawnReply.Text = failure;
					SendSpawnAck(text, spawnReply);
					return;
				}
				GameObject obj = Object.Instantiate<GameObject>(prefab, spawn, Quaternion.identity);
				Character component = obj.GetComponent<Character>();
				ZNetView component2 = obj.GetComponent<ZNetView>();
				val = obj;
				if (!Object.op_Implicit((Object)(object)component) || !Object.op_Implicit((Object)(object)component2) || !component2.IsValid() || !component2.IsOwner())
				{
					throw new InvalidOperationException("Native local network creation failed");
				}
				spawnReply.Target = component2.GetZDO().m_uid;
				component2.GetZDO().Set("zf_wizard_test_v1", text3);
				component.SetLevel(num2);
				if (!Object.op_Implicit((Object)(object)((Component)component).GetComponent<Tameable>()))
				{
					component2.GetZDO().Set("zf_admin_tame_v1", true);
				}
				if (!Object.op_Implicit((Object)(object)AdministrativeTaming.Ensure(component)))
				{
					throw new InvalidOperationException("Native tame component unavailable");
				}
				((Component)component).GetComponent<MonsterAI>().MakeTame();
				AdminSpawnIdentity.Apply(component, adminCreatureOptions);
				Tameable component3 = ((Component)component).GetComponent<Tameable>();
				AutomaticSaddles.Repair(component3);
				if (adminCreatureOptions.packs > 0)
				{
					if (!Object.op_Implicit((Object)(object)component3.m_saddle))
					{
						StandaloneMounts.Ensure(component3);
					}
					if (!Object.op_Implicit((Object)(object)component3.m_saddle) || !NativeMountAccess.Allowed(component))
					{
						throw new InvalidOperationException("No permitted saddle.");
					}
					component2.InvokeRPC("AddSaddle", Array.Empty<object>());
					MountPackStorage mountPackStorage = MountPacks.Bind(component);
					GameObject itemPrefab = ObjectDB.instance.GetItemPrefab("Zephyrfit_MountSaddlebags");
					if (!Object.op_Implicit((Object)(object)mountPackStorage) || !Object.op_Implicit((Object)(object)itemPrefab))
					{
						throw new InvalidOperationException("Saddlebag unavailable.");
					}
					ItemData val4 = itemPrefab.GetComponent<ItemDrop>().m_itemData.Clone();
					val4.m_dropPrefab = itemPrefab;
					for (int i = 0; i < adminCreatureOptions.packs; i++)
					{
						if (!mountPackStorage.Apply(val4))
						{
							throw new InvalidOperationException("Test saddlebag could not be equipped.");
						}
					}
				}
				ZDOMan.instance.ForceSendZDO(spawnReply.Target);
				spawnReply.Success = true;
				val = null;
				SendSpawnAck(text, spawnReply);
			}
			catch (Exception ex)
			{
				if (Object.op_Implicit((Object)(object)val))
				{
					ZNetView component4 = val.GetComponent<ZNetView>();
					if (component4 != null && component4.IsValid() && component4.IsOwner())
					{
						ZNetScene.instance.Destroy(val);
					}
				}
				MountRegistry.Diagnostic("admin-spawn-client", ex.GetType().Name + ": " + ex.Message);
				if (text.Length == 32 && spawnReplies.TryGetValue(text, out SpawnReply value3))
				{
					value3.Text = Texts.Wire("Création incomplète ; vérifier les animaux proches avant de réessayer.", "Creature creation incomplete; check nearby animals before retrying.");
					SendSpawnAck(text, value3);
				}
			}
		}

		private static bool TrySpawnGround(Vector3 center, long player, GameObject prefab, out Vector3 spawn, out string failure)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: 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_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: 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_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			spawn = Vector3.zero;
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			int num5 = 0;
			Vector3 val = MountMorphology.Reference(prefab);
			float num6 = default(float);
			Vector3 val3 = default(Vector3);
			GameObject val4 = default(GameObject);
			for (int i = 0; i < 8; i++)
			{
				Vector3 val2 = center + Quaternion.Euler(0f, (float)(i * 45), 0f) * Vector3.forward * 5f;
				if (!ZoneSystem.instance.GetSolidHeight(val2, ref num6, ref val3, ref val4) || !SaddleGeometry.Finite(val3) || !MovementMath.Finite(num6))
				{
					num++;
					continue;
				}
				if (Vector3.Angle(val3, Vector3.up) > 35f)
				{
					num2++;
					continue;
				}
				if (num6 < ZoneSystem.instance.m_waterLevel + 0.5f)
				{
					num3++;
					continue;
				}
				val2.y = num6 + 0.4f;
				if (!Nearby(center, val2) || !MountPacks.Access(player, val2))
				{
					num5++;
					continue;
				}
				if (Physics.CheckSphere(val2 + Vector3.up * Mathf.Max(0.5f, val.y * 0.5f), Mathf.Clamp(val.x * 0.45f, 0.25f, 3f), LayerMask.GetMask(new string[3] { "character", "piece", "static_solid" }), (QueryTriggerInteraction)1))
				{
					num4++;
					continue;
				}
				spawn = val2;
				failure = "";
				return true;
			}
			MountRegistry.Diagnostic("admin-spawn-ground-" + ((Object)prefab).name, $"Terrain={num}, slope={num2}, water={num3}, blocked={num4}, protected/range={num5}; native client queries, no fallback coordinates.");
			failure = Texts.Wire("Aucun sol sec adapté : terrain absent {0}, pente {1}, eau {2}, obstacle {3}, accès {4}.", "No suitable dry ground: terrain unavailable {0}, slope {1}, water {2}, obstacle {3}, access {4}.", num, num2, num3, num4, num5);
			return false;
		}

		private static void SendSpawnAck(string id, SpawnReply reply)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Expected O, but got Unknown
			if (!Object.op_Implicit((Object)(object)world) || rpc == null || PlacementLifecycle.Ending)
			{
				return;
			}
			ZPackage val = new ZPackage();
			Header(val);
			val.Write(id);
			val.Write(reply.Success);
			val.Write(reply.Target);
			val.Write(reply.Text);
			if (world.IsServer())
			{
				ReceiveSpawnAck(ZDOMan.GetSessionID(), new ZPackage(val.GetArray()));
				return;
			}
			ZNetPeer serverPeer = world.GetServerPeer();
			if (serverPeer != null)
			{
				rpc.InvokeRoutedRPC(serverPeer.m_uid, "ZF_MountAdminSpawnAck_v1", new object[1] { val });
			}
		}

		private unsafe static void ReceiveSpawnAck(long sender, ZPackage p)
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: 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)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)world) || !world.IsServer() || PlacementLifecycle.Ending || p.Size() > 8192)
			{
				return;
			}
			try
			{
				if (!ReadHeader(p))
				{
					return;
				}
				string text = p.ReadString();
				bool flag = p.ReadBool();
				ZDOID val = p.ReadZDOID();
				string text2 = p.ReadString();
				if (p.GetPos() != p.Size() || text2.Length > 4096 || !pendingSpawns.TryGetValue(text, out PendingSpawn value) || sender != value.Client || value.Acknowledged)
				{
					return;
				}
				value.Target = val;
				value.Acknowledged = true;
				if (!flag)
				{
					pendingSpawns.Remove(text);
					Dictionary<string, string> created = receipts.created;
					object value2;
					if (!(val == default(ZDOID)))
					{
						ZDOID val2 = val;
						value2 = "incomplete:" + ((object)(*(ZDOID*)(&val2))/*cast due to .constrained prefix*/).ToString();
					}
					else
					{
						value2 = "refused";
					}
					created[text] = (string)value2;
					PresetLibrary.Write(ReceiptFile, PresetJson.ToJson(receipts));
					Deliver(sender, text, success: false, text2, val);
				}
				else
				{
					CompleteSpawn(text, value);
				}
			}
			catch (Exception ex)
			{
				MountRegistry.Diagnostic("admin-spawn-ack", ex.GetType().Name + ": " + ex.Message);
			}
		}

		private static bool CompleteSpawn(string id, PendingSpawn request)
		{
			//IL_0006: 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_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a5: Unknown result type (might be due to invalid IL or missing references)
			ZDO zDO = ZDOMan.instance.GetZDO(request.Target);
			if (zDO == null)
			{
				return false;
			}
			if (!AdminSpawnRules.Receipt(request.Acknowledged, request.Client, ((ZDOID)(ref zDO.m_uid)).UserID, request.Marker, zDO.GetString("zf_wizard_test_v1", ""), StringExtensionMethods.GetStableHashCode(request.Species), zDO.GetPrefab(), request.Level, zDO.GetInt(ZDOVars.s_level, 1), zDO.GetBool(ZDOVars.s_tamed, false), CreatureState.Alive(zDO), Nearby(request.Center, zDO.GetPosition())))
			{
				return false;
			}
			if (!PlacementAuthority.Admin(request.Client) || !PlacementAuthority.PlayerContext(request.Client, out ZDO _, out long id2, out Vector3 position) || id2 != request.Player || !Nearby(position, zDO.GetPosition(), 20.0) || !AdministrativeTaming.CanTame(request.Species) || !MountPacks.Access(id2, zDO.GetPosition()))
			{
				return false;
			}
			if (request.Options.sex != "Automatic" && zDO.GetInt("zf_sex_v1", 0) != (int)(AnimalSex)Enum.Parse(typeof(AnimalSex), request.Options.sex))
			{
				return false;
			}
			if (request.Options.name.Trim().Length > 0 && zDO.GetString(ZDOVars.s_tamedName, "") != request.Options.name.Trim())
			{
				return false;
			}
			if (request.Options.packs > 0 && (!zDO.GetBool(ZDOVars.s_haveSaddleHash, false) || zDO.GetInt("zf_mount_pack_pairs_v1", 0) != request.Options.packs))
			{
				return false;
			}
			pendingSpawns.Remove(id);
			receipts.created[id] = ((object)Unsafe.As<ZDOID, ZDOID>(ref zDO.m_uid)/*cast due to .constrained prefix*/).ToString();
			PresetLibrary.Write(ReceiptFile, PresetJson.ToJson(receipts));
			int num = Math.Max(0, request.Level - 1);
			string text = ((request.CapSource == "administrative fallback") ? Texts.Wire("Animal de test créé : niveau interne {0}, étoiles {1}, plafond administratif {2}.", "Test animal created: internal level {0}, stars {1}; administrative cap: {2}.", request.Level, num, request.Cap) : Texts.Wire("Animal de test créé : niveau interne {0}, étoiles {1} ; plafond : {2} ({3}).", "Test animal created: internal level {0}, stars {1}; cap: {2} ({3}).", request.Level, num, request.Cap, request.CapSource));
			Deliver(request.Client, id, success: true, text, zDO.m_uid);
			return true;
		}

		private unsafe static void TickSpawns()
		{
			//IL_024f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			if (pendingSpawns.Count == 0 && localSpawnUntil.Count == 0)
			{
				return;
			}
			float now = Time.realtimeSinceStartup;
			if (Object.op_Implicit((Object)(object)world) && world.IsServer())
			{
				KeyValuePair<string, PendingSpawn>[] array = pendingSpawns.ToArray();
				for (int i = 0; i < array.Length; i++)
				{
					KeyValuePair<string, PendingSpawn> keyValuePair = array[i];
					try
					{
						if ((!keyValuePair.Value.Acknowledged || !CompleteSpawn(keyValuePair.Key, keyValuePair.Value)) && !(now <= keyValuePair.Value.Until))
						{
							pendingSpawns.Remove(keyValuePair.Key);
							Dictionary<string, string> created = receipts.created;
							string key = keyValuePair.Key;
							ZDOID target = keyValuePair.Value.Target;
							created[key] = "unconfirmed:" + ((object)(*(ZDOID*)(&target))/*cast due to .constrained prefix*/).ToString();
							PresetLibrary.Write(ReceiptFile, PresetJson.ToJson(receipts));
							MountRegistry.Diagnostic("admin-spawn-timeout-" + keyValuePair.Value.Species, $"Request={keyValuePair.Key} peer={keyValuePair.Value.Client} acknowledged={keyValuePair.Value.Acknowledged} target={keyValuePair.Value.Target}; creation not repeated.");
							Deliver(keyValuePair.Value.Client, keyValuePair.Key, success: false, Texts.Wire("Création non confirmée ; vérifier les animaux proches avant de réessayer.", "Creature creation not confirmed; check nearby animals before retrying."), keyValuePair.Value.Target);
						}
					}
					catch (Exception ex) when (ex is IOException || ex is ArgumentException || ex is InvalidOperationException)
					{
						pendingSpawns.Remove(keyValuePair.Key);
						MountRegistry.Diagnostic("admin-spawn-receipt", ex.GetType().Name + ": " + ex.Message);
						Deliver(keyValuePair.Value.Client, keyValuePair.Key, success: false, Texts.Wire("Création non confirmée ; vérifier les animaux proches avant de réessayer.", "Creature creation not confirmed; check nearby animals before retrying."), keyValuePair.Value.Target);
					}
				}
			}
			string[] array2 = (from e in localSpawnUntil
				where now > e.Value + 30f
				select e.Key).ToArray();
			foreach (string key2 in array2)
			{
				localSpawnUntil.Remove(key2);
				spawnReplies.Remove(key2);
				callbacks.Remove(key2);
			}
		}

		internal static void Tick()
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance) || ZRoutedRpc.instance == null || !MountRegistry.Ready || PlacementLifecycle.Ending)
			{
				ResetSpawns();
				pendingDespawns.Clear();
				world = null;
				rpc = null;
				callbacks.Clear();
				rate.Clear();
				receiptScope = "";
				return;
			}
			if ((Object)(object)world != (Object)(object)ZNet.instance)
			{
				ResetSpawns();
				pendingDespawns.Clear();
				world = ZNet.instance;
				callbacks.Clear();
				rate.Clear();
				receiptScope = "";
			}
			if (rpc != ZRoutedRpc.instance)
			{
				rpc = ZRoutedRpc.instance;
				rpc.Register<ZPackage>("ZF_MountAdminRequest_v1", (Action<long, ZPackage>)Receive);
				rpc.Register<ZPackage>("ZF_MountAdminResult_v1", (Action<long, ZPackage>)Result);
				rpc.Register<ZPackage>("ZF_MountAdminMotion_v1", (Action<long, ZPackage>)Motion);
				RegisterSpawns();
				RegisterDespawns();
			}
			TickSpawns();
			TickDespawns();
		}

		private static void Header(ZPackage p)
		{
			p.Write(world.GetWorldUID());
			p.Write(MountRegistry.Scope);
		}

		private static bool ReadHeader(ZPackage p)
		{
			if (Object.op_Implicit((Object)(object)world) && p.ReadLong() == world.GetWorldUID())
			{
				return p.ReadString() == MountRegistry.Scope;
			}
			return false;
		}

		internal static bool Request(string operation, string species, int level, ZDOID target, string data, Action<bool, string, ZDOID> callback)
		{
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Expected O, but got Unknown
			//IL_0096: 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)
			//IL_00c5: Expected O, but got Unknown
			if (!SynchronizationAccess.Admin || !Object.op_Implicit((Object)(object)world) || rpc == null || callbacks.Count >= 32)
			{
				return false;
			}
			string text = Guid.NewGuid().ToString("N");
			callbacks[text] = callback;
			if (operation == "spawn")
			{
				localSpawnUntil[text] = Time.realtimeSinceStartup + 12f;
			}
			ZPackage val = new ZPackage();
			Header(val);
			val.Write(text);
			val.Write(operation);
			val.Write(species);
			val.Write(level);
			val.Write(target);
			val.Write(data);
			if (world.IsServer())
			{
				Receive(ZDOMan.GetSessionID(), new ZPackage(val.GetArray()));
			}
			else
			{
				rpc.InvokeRoutedRPC(world.GetServerPeer().m_uid, "ZF_MountAdminRequest_v1", new object[1] { val });
			}
			return true;
		}

		private static void EnsureReceipts()
		{
			if (!(receiptScope == MountRegistry.Scope))
			{
				TestSpawnReceipts testSpawnReceipts = (File.Exists(ReceiptFile) ? PresetJson.FromJson<TestSpawnReceipts>(File.ReadAllText(ReceiptFile)) : new TestSpawnReceipts());
				if (testSpawnReceipts.created == null || testSpawnReceipts.created.Count > 4096)
				{
					throw new InvalidDataException("Invalid test creation journal; original retained");
				}
				receipts = testSpawnReceipts;
				receiptScope = MountRegistry.Scope;
			}
		}

		private static byte[] Secret()
		{
			if (secret != null)
			{
				return secret;
			}
			string text = Path.Combine(PresetLibrary.Folder, "wizard-secret.txt");
			if (File.Exists(text))
			{
				secret = Convert.FromBase64String(File.ReadAllText(text));
			}
			else
			{
				secret = new byte[32];
				using (RandomNumberGenerator randomNumberGenerator = RandomNumberGenerator.Create())
				{
					randomNumberGenerator.GetBytes(secret);
				}
				PresetLibrary.Write(text, Convert.ToBase64String(secret));
			}
			if (secret.Length != 32)
			{
				throw new InvalidDataException("Invalid test marker signing secret; original retained");
			}
			return secret;
		}

		private static string Sign(string id, string species)
		{
			using HMACSHA256 hMACSHA = new HMACSHA256(Secret());
			return Convert.ToBase64String(hMACSHA.ComputeHash(Encoding.UTF8.GetBytes(MountRegistry.Scope + "|" + id + "|" + species)));
		}

		private static bool Marked(ZDO z, string species)
		{
			string[] array = z.GetString("zf_wizard_test_v1", "").Split(new char[1] { '|' });
			if (array.Length == 2 && Guid.TryParseExact(array[0], "N", out var _))
			{
				return array[1] == Sign(array[0], species);
			}
			return false;
		}

		internal static bool TestMarker(Character c)
		{
			ZNetView val = (Object.op_Implicit((Object)(object)c) ? ((Component)c).GetComponent<ZNetView>() : null);
			if (Object.op_Implicit((Object)(object)val) && val.IsValid())
			{
				return val.GetZDO().GetString("zf_wizard_test_v1", "").Length > 0;
			}
			return false;
		}

		private static bool HasNonDefaultInventory(GameObject go, GameObject prefab)
		{
			Humanoid component = go.GetComponent<Humanoid>();
			Humanoid component2 = prefab.GetComponent<Humanoid>();
			if (Object.op_Implicit((Object)(object)component) && Object.op_Implicit((Object)(object)component2))
			{
				HashSet<string> defaults = (from g in (component2.m_defaultItems ?? Array.Empty<GameObject>()).Concat(component2.m_randomWeapon ?? Array.Empty<GameObject>()).Concat(component2.m_randomArmor ?? Array.Empty<GameObject>()).Concat(component2.m_randomShield ?? Array.Empty<GameObject>())
						.Concat((component2.m_randomSets ?? Array.Empty<ItemSet>()).SelectMany((ItemSet s) => s.m_items ?? Array.Empty<GameObject>()))
						.Concat((component2.m_randomItems ?? Array.Empty<RandomItem>()).Select((RandomItem i) => i.m_prefab))
					where Object.op_Implicit((Object)(object)g) && Object.op_Implicit((Object)(object)g.GetComponent<ItemDrop>())
					select g.GetComponent<ItemDrop>().m_itemData.m_shared.m_name).ToHashSet();
				if (Object.op_Implicit((Object)(object)component2.m_unarmedWeapon))
				{
					defaults.Add(component2.m_unarmedWeapon.m_itemData.m_shared.m_name);
				}
				return component.GetInventory().GetAllItems().Any((ItemData i) => !defaults.Contains(i.m_shared.m_name));
			}
			return false;
		}

		private static void Receive(long sender, ZPackage p)
		{
			//IL_070d: Unknown result type (might be due to invalid IL or missing references)
			//IL_06ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_06f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_06c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_037d: Unknown result type (might be due to invalid IL or missing references)
			//IL_051b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0543: Unknown result type (might be due to invalid IL or missing references)
			//IL_041e: Unknown result type (might be due to invalid IL or missing references)
			//IL_058a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0487: Unknown result type (might be due to invalid IL or missing references)
			//IL_0596: Unknown result type (might be due to invalid IL or missing references)
			//IL_059a: Unknown result type (might be due to invalid IL or missing references)
			//IL_05af: Unknown result type (might be due to invalid IL or missing references)
			//IL_062a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0631: Expected O, but got Unknown
			//IL_063a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0671: Unknown result type (might be due to invalid IL or missing references)
			//IL_067b: Expected O, but got Unknown
			//IL_069e: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a0: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)world) || !world.IsServer() || !PlacementAuthority.Admin(sender))
			{
				return;
			}
			string text = "";
			string text2 = "";
			string text3 = "";
			ZDOID target = default(ZDOID);
			ZDOID val = default(ZDOID);
			try
			{
				if (!ReadHeader(p))
				{
					return;
				}
				text = p.ReadString();
				text2 = p.ReadString();
				text3 = p.ReadString();
				int requested = p.ReadInt();
				val = p.ReadZDOID();
				string data = p.ReadString();
				if (!Guid.TryParseExact(text, "N", out var _) || !MountBridgeRules.Prefab(text3) || data.Length > 32768 || p.GetPos() != p.Size())
				{
					return;
				}
				if (rate.TryGetValue(sender, out var value) && Time.realtimeSinceStartup < value)
				{
					Deliver(sender, text, success: false, Texts.Wire("Patienter.", "Please wait."), target);
					return;
				}
				rate[sender] = Time.realtimeSinceStartup + 0.5f;
				if (!PlacementAuthority.PlayerContext(sender, out ZDO player, out long id, out Vector3 position))
				{
					Deliver(sender, text, success: false, Texts.Wire("Autorité d’apprivoisement en cours de synchronisation.", "Taming authority is synchronizing."), target);
					return;
				}
				switch (text2)
				{
				case "capacity":
				{
					StorageCapacity storageCapacity = PresetJson.FromJson<StorageCapacity>(data);
					if (!storageCapacity.Valid() || !MountRegistry.Allowed(text3))
					{
						throw new InvalidDataException("Capacity/species invalid");
					}
					Dictionary<string, StorageCapacity> dictionary = PresetJson.FromJson<Dictionary<string, StorageCapacity>>(MountRegistry.CapacityJson.Value);
					dictionary[text3] = storageCapacity;
					if (dictionary.Count > 256)
					{
						throw new InvalidDataException("Species limit");
					}
					SaveServerSetting(MountRegistry.CapacityJson, PresetJson.ToJson(dictionary));
					MountRegistry.Queue();
					break;
				}
				case "speciesRules":
					PresetJson.FromJson<AdminSpeciesEdit>(data).Save(text3);
					break;
				case "sexPolicy":
				{
					if (!AdministrativeTaming.Permitted(text3) || text3 == "Deer" || !new string[4] { "Inherit", "Disabled", "MaleFemale", "Hermaphrodite" }.Contains(data))
					{
						throw new InvalidOperationException("Invalid species sex rule");
					}
					Dictionary<string, SexMode> dictionary2 = SpeciesSexRules.Parse(AnimalSexState.SpeciesOverrides.Value);
					if (data == "Inherit")
					{
						dictionary2.Remove(text3);
					}
					else
					{
						dictionary2[text3] = (SexMode)Enum.Parse(typeof(SexMode), data);
					}
					string text4 = PresetJson.ToJson(dictionary2.ToDictionary((KeyValuePair<string, SexMode> e) => e.Key, (KeyValuePair<string, SexMode> e) => e.Value.ToString()));
					SpeciesSexRules.Parse(text4);
					SaveServerSetting(AnimalSexState.SpeciesOverrides, text4);
					break;
				}
				case "naturalFood":
					NaturalFoodSettings.Save(text3, data);
					break;
				case "breedingPolicy":
				case "ridingPolicy":
					SpeciesActivitySettings.Save(text3, text2 == "ridingPolicy", data);
					break;
				case "spawn":
				{
					if (!AdministrativeTaming.CanTame(text3) || !MountPacks.Access(id, position))
					{
						throw new InvalidOperationException("Species/access refused");
					}
					AdminCreatureOptions adminCreatureOptions = ((data.Length == 0) ? new AdminCreatureOptions() : PresetJson.FromJson<AdminCreatureOptions>(data));
					string source;
					int cap = MountLevelCapApi.Resolve(text3, out source);
					int level = MountBridgeRules.Level(requested, cap);
					if (adminCreatureOptions == null || !adminCreatureOptions.Valid(AnimalSexState.SpeciesMode(text3), text3, level, PackLimit(text3)))
					{
						throw new InvalidOperationException("Invalid name/sex for this server species rule");
					}
					EnsureReceipts();
					if (receipts.created.ContainsKey(text))
					{
						Deliver(sender, text, success: false, Texts.Wire("Création déjà enregistrée ; aucun second animal.", "Creation already recorded; no second animal."), target);
						return;
					}
					if (receipts.created.Count >= 4096)
					{
						throw new InvalidOperationException("Test journal full; archive it after checking remaining test animals");
					}
					GameObject prefab = ZNetScene.instance.GetPrefab(text3);
					if (!Object.op_Implicit((Object)(object)prefab) || !prefab.activeSelf || Object.op_Implicit((Object)(object)prefab.GetComponent<Growup>()))
					{
						throw new InvalidOperationException("Adult active prefab required");
					}
					QueueSpawn(sender, text, text3, level, position, id, adminCreatureOptions, cap, source);
					return;
				}
				case "despawn":
				case "despawnNatural":
					BeginDespawn(sender, text, text2, text3, val, data, player, id, position);
					return;
				case "rest":
				case "walk":
				case "run":
				case "turn":
				case "attack":
				{
					ZDO zDO = ZDOMan.instance.GetZDO(val);
					GameObject val2 = ((zDO == null) ? null : ZNetScene.instance.GetPrefab(zDO.GetPrefab()));
					GameObject val3 = ZNetScene.instance.FindInstance(val);
					if (zDO == null || !Object.op_Implicit((Object)(object)val2) || ((Object)val2).name != text3 || !Object.op_Implicit((Object)(object)val3) || Object.op_Implicit((Object)(object)val3.GetComponent<Player>()) || !AdministrativeTaming.Eligible(val3) || !SaddleGeometry.Finite(zDO.GetPosition()) || Vector3.Distance(position, zDO.GetPosition()) > 15f || !MountPacks.Access(id, zDO.GetPosition()) || zDO.GetLong(ZDOVars.s_user, 0L) != 0L)
					{
						throw new InvalidOperationException("Target unavailable, occupied or inaccessible");
					}
					if (!AdministrativeTaming.Permitted(text3) || !AdministrativeTaming.Supported(val3))
					{
						throw new InvalidOperationException("Species disabled or unsupported");
					}
					if (text2 == "attack" && !WizardActions.Attacks(val3.GetComponent<Humanoid>()).Any((MountCapabilities.WeaponAttack a) => WizardActions.Key(a) == data))
					{
						throw new InvalidOperationException("Native attack unavailable");
					}
					ZPackage val4 = new ZPackage();
					Header(val4);
					val4.Write(val);
					val4.Write(text2);
					val4.Write(data);
					if (zDO.GetOwner() == ZDOMan.GetSessionID())
					{
						Motion(ZDOMan.GetSessionID(), new ZPackage(val4.GetArray()));
					}
					else
					{
						rpc.InvokeRoutedRPC(zDO.GetOwner(), "ZF_MountAdminMotion_v1", new object[1] { val4 });
					}
					target = val;
					break;
				}
				default:
					throw new InvalidDataException("Unknown administrative action");
				}
				Deliver(sender, text, success: true, Texts.Wire("Action administrative acceptée.", "Administrative action accepted."), target);
			}
			catch (Exception ex)
			{
				if (text.Length == 32)
				{
					Deliver(sender, text, success: false, Texts.ErrorNotice(ex.Message), default(ZDOID));
				}
				MountRegistry.Diagnostic("admin", $"{text2} target={val} prefab={text3} {ex.GetType().Name}: {ex.Message}");
			}
		}

		private static void Motion(long sender, ZPackage p)
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)world) || sender != (world.IsServer() ? ZDOMan.GetSessionID() : world.GetServerPeer().m_uid))
			{
				return;
			}
			try
			{
				if (!ReadHeader(p))
				{
					return;
				}
				ZDOID val = p.ReadZDOID();
				string value = p.ReadString();
				string data = p.ReadString();
				GameObject val2 = ZNetScene.instance.FindInstance(val);
				ZNetView val3 = (Object.op_Implicit((Object)(object)val2) ? val2.GetComponent<ZNetView>() : null);
				if (Object.op_Implicit((Object)(object)val3) && val3.IsValid() && val3.IsOwner() && val3.GetZDO().GetLong(ZDOVars.s_user, 0L) == 0L && new string[5] { "rest", "walk", "run", "turn", "attack" }.Contains(value) && p.GetPos() == p.Size() && Object.op_Implicit((Object)(object)val2) && Object.op_Implicit((Object)(object)val2.GetComponent<Character>()) && !val2.GetComponent<Character>().IsDead() && AdministrativeTaming.Permitted(Utils.GetPrefabName(val2)))
				{
					WizardMotion wizardMotion = val2.GetComponent<WizardMotion>();
					if (!Object.op_Implicit((Object)(object)wizardMotion))
					{
						wizardMotion = val2.AddComponent<WizardMotion>();
					}
					wizardMotion.Begin(value, data);
				}
			}
			catch (Exception ex)
			{
				MountRegistry.Diagnostic("motion", ex.GetType().Name);
			}
		}

		private static void Deliver(long client, string id, bool success, string text, ZDOID target)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			if (client == ZDOMan.GetSessionID())
			{
				if (callbacks.TryGetValue(id, out Action<bool, string, ZDOID> value))
				{
					callbacks.Remove(id);
					value(success, Texts.Resolve(text), target);
				}
				return;
			}
			ZPackage val = new ZPackage();
			Header(val);
			val.Write(id);
			val.Write(success);
			val.Write(text);
			val.Write(target);
			rpc.InvokeRoutedRPC(client, "ZF_MountAdminResult_v1", new object[1] { val });
		}

		internal static void SaveServerSetting(ConfigEntry<string> entry, string value)
		{
			SaveServerSettings((entry, value));
		}

		internal static void SaveServerSettings(params (ConfigEntry<string> entry, string value)[] updates)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance) || !ZNet.instance.IsServer())
			{
				throw new InvalidOperationException("Server authority required.");
			}
			(ConfigEntry<string>, string)[] array = updates.Where(((ConfigEntry<string> entry, string value) p) => p.entry.Value != p.value).ToArray();
			if (array.Length == 0)
			{
				return;
			}
			ConfigFile config = ((BaseUnityPlugin)Plugin.Instance).Config;
			string[] array2 = array.Select(((ConfigEntry<string> entry, string value) p) => p.entry.Value).ToArray();
			string text = ConfigMigrations.Backup(config);
			bool saveOnConfigSet = config.SaveOnConfigSet;
			try
			{
				config.SaveOnConfigSet = false;
				(ConfigEntry<string>, string)[] array3 = array;
				for (int num = 0; num < array3.Length; num++)
				{
					(ConfigEntry<string>, string) tuple = array3[num];
					tuple.Item1.Value = tuple.Item2;
				}
				config.Save();
			}
			catch
			{
				for (int num2 = 0; num2 < array.Length; num2++)
				{
					array[num2].Item1.Value = array2[num2];
				}
				if (text != null)
				{
					File.Copy(text, config.ConfigFilePath, overwrite: true);
				}
				throw;
			}
			finally
			{
				config.SaveOnConfigSet = saveOnConfigSet;
			}
			config.Reload();
			StandaloneSettings.PublishEdits();
		}

		private static void Result(long sender, ZPackage p)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)world) || world.IsServer() || sender != world.GetServerPeer().m_uid)
			{
				return;
			}
			try
			{
				if (ReadHeader(p))
				{
					string key = p.ReadString();
					bool arg = p.ReadBool();
					string text = p.ReadString();
					ZDOID arg2 = p.ReadZDOID();
					if (text.Length <= 2048 && callbacks.TryGetValue(key, out Action<bool, string, ZDOID> value))
					{
						callbacks.Remove(key);
						value(arg, Texts.Resolve(text), arg2);
					}
				}
			}
			catch (Exception ex)
			{
				MountRegistry.Diagnostic("admin-result", ex.GetType().Name);
			}
		}
	}
	internal static class AdministrativeTaming
	{
		private sealed class Batch
		{
			internal long Client;

			internal float Until;

			internal int Changed;

			internal int Skipped;

			internal readonly Dictionary<ZDOID, long> Waiting = new Dictionary<ZDOID, long>();
		}

		private sealed class Callback
		{
			internal float Until;

			internal Action<bool, string> Done;
		}

		internal const string Created = "zf_admin_tame_v1";

		internal static ConfigEntry<string> Allowed = null;

		internal static ConfigEntry<string> Forbidden = null;

		private static string parsed = "";

		private static AdminTameRules? rules;

		private const string RequestRpc = "ZF_AdminTameRequest_v1";

		private const string GrantRpc = "ZF_AdminTameGrant_v1";

		private const string AckRpc = "ZF_AdminTameAck_v1";

		private const string ResultRpc = "ZF_AdminTameResult_v1";

		private static readonly ConditionalWeakTable<ZRoutedRpc, object> registered = new ConditionalWeakTable<ZRoutedRpc, object>();

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

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

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

		private static readonly Dictionary<long, float> rates = new Dictionary<long, float>();

		private static ZNet? world;

		private static ZRoutedRpc? rpc;

		private static ZNetScene? catalogScene;

		private static string catalogRules = "";

		private static int catalogSize;

		private static float catalogUntil;

		private static string[] catalog = Array.Empty<string>();

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

		private static readonly FieldRef<BaseAI, Tameable> AITame = AccessTools.FieldRefAccess<BaseAI, Tameable>("m_tamable");

		private static readonly FieldRef<BaseAI, Character> AICharacter = AccessTools.FieldRefAccess<BaseAI, Character>("m_character");

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

		private static readonly FieldRef<Tameable, Character> TameCharacter = AccessTools.FieldRefAccess<Tameable, Character>("m_character");

		private static readonly FieldRef<Tameable, MonsterAI> TameAI = AccessTools.FieldRefAccess<Tameable, MonsterAI>("m_monsterAI");

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

		internal static void Configure(ConfigFile config)
		{
			Allowed = config.Bind<string>("Administrative Taming", "Allowed prefabs", "*", Rule("Species allowed for the administrator tame command and creature catalog. * allows supported loaded AI creatures; an empty list allows none. Use exact prefab IDs separated by commas. Does not add food, breeding or mounting rights."));
			Forbidden = config.Bind<string>("Administrative Taming", "Forbidden prefabs", "", Rule("Comma-separated exact prefab IDs excluded from administrative tame. Exclusions take priority over Allowed prefabs, including *. * forbids all. LetMeTameYou removeTameable exclusions also take priority. Existing pets are retained."));
			static ConfigDescription Rule(string text)
			{
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0017: Expected O, but got Unknown
				//IL_0017: Unknown result type (might be due to invalid IL or missing references)
				//IL_001d: Expected O, but got Unknown
				return new ConfigDescription(text, (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
				{
					IsAdminOnly = true
				} });
			}
		}

		private static AdminTameRules? CurrentRules()
		{
			if (Allowed == null || Forbidden == null)
			{
				return null;
			}
			string text = Allowed.Value + "\n" + Forbidden.Value;
			if (text != parsed)
			{
				parsed = text;
				rules = null;
				try
				{
					rules = new AdminTameRules(Allowed.Value, Forbidden.Value);
				}
				catch (ArgumentException ex)
				{
					MountRegistry.Diagnostic("admin-tame-config", ex.Message + "; administrative taming refused until corrected.");
				}
			}
			return rules;
		}

		internal static bool Permitted(string species)
		{
			AdminTameRules? adminTameRules = CurrentRules();
			if (adminTameRules != null && adminTameRules.Allows(species))
			{
				if (Providers.Tames.TryGetValue(species, out TameRule value))
				{
					return !value.removeTameable;
				}
				return true;
			}
			return false;
		}

		internal static bool ExcludesFoodOverride(string species)
		{
			AdminTameRules? adminTameRules = CurrentRules();
			if (adminTameRules != null && !adminTameRules.Excludes(species))
			{
				if (Providers.Tames.TryGetValue(species, out TameRule value))
				{
					return value.removeTameable;
				}
				return false;
			}
			return true;
		}

		internal static bool Eligible(GameObject prefab)
		{
			if (Object.op_Implicit((Object)(object)prefab) && Object.op_Implicit((Object)(object)prefab.GetComponent<Character>()) && !Object.op_Implicit((Object)(object)prefab.GetComponent<Player>()))
			{
				return Object.op_Implicit((Object)(object)prefab.GetComponent<BaseAI>());
			}
			return false;
		}

		internal static bool Supported(GameObject prefab)
		{
			if (Eligible(prefab))
			{
				return Object.op_Implicit((Object)(object)prefab.GetComponent<MonsterAI>());
			}
			return false;
		}

		internal static bool CanTame(string species)
		{
			GameObject val = (Object.op_Implicit((Object)(object)ZNetScene.instance) ? ZNetScene.instance.GetPrefab(species) : null);
			if (Object.op_Implicit((Object)(object)val) && Permitted(species))
			{
				return Supported(val);
			}
			return false;
		}

		internal static IEnumerable<string> Catalog()
		{
			ZNetScene instance = ZNetScene.instance;
			if (!Object.op_Implicit((Object)(object)instance))
			{
				return Array.Empty<string>();
			}
			string text = Allowed.Value + "\n" + Forbidden.Value;
			if ((Object)(object)catalogScene != (Object)(object)instance || catalogRules != text || catalogSize != instance.m_prefabs.Count || Time.realtimeSinceStartup >= catalogUntil)
			{
				catalogScene = instance;
				catalogRules = text;
				catalogSize = instance.m_prefabs.Count;
				catalogUntil = Time.realtimeSinceStartup + 2f;
				catalog = (from p in instance.m_prefabs
					where Eligible(p) && !Object.op_Implicit((Object)(object)p.GetComponent<Growup>()) && Permitted(((Object)p).name)
					select ((Object)p).name).Distinct<string>(StringComparer.Ordinal).OrderBy<string, string>((string n) => n, StringComparer.Ordinal).ToArray();
			}
			return catalog;
		}

		internal static void Tick()
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance) || !Plugin.ConfigReady || !MountRegistry.Ready || ZRoutedRpc.instance == null)
			{
				Reset();
				return;
			}
			if ((Object)(object)world != (Object)(object)ZNet.instance)
			{
				Reset();
				world = ZNet.instance;
			}
			rpc = ZRoutedRpc.instance;
			if (!registered.TryGetValue(rpc, out object _))
			{
				rpc.Register<ZPackage>("ZF_AdminTameRequest_v1", (Action<long, ZPackage>)Receive);
				rpc.Register<ZPackage>("ZF_AdminTameGrant_v1", (Action<long, ZPackage>)Grant);
				rpc.Register<ZPackage>("ZF_AdminTameAck_v1", (Action<long, ZPackage>)Ack);
				rpc.Register<ZPackage>("ZF_AdminTameResult_v1", (Action<long, ZPackage>)Result);
				registered.Add(rpc, new object());
			}
			if (batches.Count != 0 || callbacks.Count != 0 || seen.Count != 0)
			{
				string[] array = (from b in batches
					where b.Value.Until < Time.realtimeSinceStartup
					select b.Key).ToArray();
				foreach (string text in array)
				{
					batches[text].Skipped += batches[text].Waiting.Count;
					batches[text].Waiting.Clear();
					Finish(text);
				}
				array = (from c in callbacks
					where c.Value.Until < Time.realtimeSinceStartup
					select c.Key).ToArray();
				foreach (string key in array)
				{
					Callback callback = callbacks[key];
					callbacks.Remove(key);
					callback.Done(arg1: false, Texts.T("Délai dépassé : vérifier les créatures avant de relancer tame.", "Timeout: inspect the creatures before retrying tame."));
				}
				array = (from s in seen
					where s.Value < Time.realtimeSinceStartup
					select s.Key).ToArray();
				foreach (string key2 in array)
				{
					seen.Remove(key2);
				}
			}
		}

		internal static void Reset()
		{
			world = null;
			rpc = null;
			catalogScene = null;
			catalog = Array.Empty<string>();
			batches.Clear();
			callbacks.Clear();
			rates.Clear();
			seen.Clear();
		}

		private static void Header(ZPackage p)
		{
			p.Write(world.GetWorldUID());
			p.Write(MountRegistry.Scope);
		}

		private static bool HeaderValid(ZPackage p)
		{
			if (Object.op_Implicit((Object)(object)world) && p.ReadLong() == world.GetWorldUID())
			{
				return p.ReadString() == MountRegistry.Scope;
			}
			return false;
		}

		private static bool Server(long sender)
		{
			if (Object.op_Implicit((Object)(object)world))
			{
				return sender == (world.IsServer() ? new long?(ZDOMan.GetSessionID()) : world.GetServerPeer()?.m_uid);
			}
			return false;
		}

		internal static bool Request(IEnumerable<ZDOID> targets, Action<bool, string> done)
		{
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Expected O, but got Unknown
			if (!SynchronizationAccess.Admin || !Object.op_Implicit((Object)(object)world) || rpc == null || callbacks.Count >= 16 || (!world.IsServer() && world.GetServerPeer() == null))
			{
				return false;
			}
			ZDOID[] array = targets.Distinct().Take(64).ToArray();
			if (array.Length == 0)
			{
				done(arg1: false, Texts.T("Aucune créature proche à apprivoiser.", "No nearby creature to tame."));
				return true;
			}
			string text = Guid.NewGuid().ToString("N");
			callbacks[text] = new Callback
			{
				Until = Time.realtimeSinceStartup + 12f,
				Done = done
			};
			ZPackage val = new ZPackage();
			Header(val);
			val.Write(text);
			val.Write(array.Length);
			ZDOID[] array2 = array;
			foreach (ZDOID val2 in array2)
			{
				val.Write(val2);
			}
			if (world.IsServer())
			{
				Receive(ZDOMan.GetSessionID(), new ZPackage(val.GetArray()));
			}
			else
			{
				rpc.InvokeRoutedRPC(world.GetServerPeer().m_uid, "ZF_AdminTameRequest_v1", new object[1] { val });
			}
			return true;
		}

		internal static void Around(Vector3 point, float radius)
		{
			Player player = Player.m_localPlayer;
			if (!Object.op_Implicit((Object)(object)player) || !SynchronizationAccess.Admin)
			{
				Notice(Texts.T("tame est réservé aux administrateurs du serveur.", "tame requires server administrator access."));
				return;
			}
			float range = Mathf.Clamp(radius, 0f, 20f);
			if (!Request((from c in Character.GetAllCharacters()
				where Object.op_Implicit((Object)(object)c) && !c.IsPlayer() && !c.IsDead() && !c.IsTamed() && Supported(((Component)c).gameObject) && Permitted(Utils.GetPrefabName(((Component)c).gameObject)) && Vector3.Distance(((Component)c).transform.position, ((Component)player).transform.position) <= range
				select ((Component)c).GetComponent<ZNetView>() into v
				where Object.op_Implicit((Object)(object)v) && v.IsValid()
				select v.GetZDO().m_uid).ToArray(), delegate(bool _, string text)
			{
				Notice(text);
			}))
			{
				Notice(Texts.T("Autorité d’apprivoisement en cours de synchronisation.", "Taming authority is synchronizing."));
			}
		}

		private static void Notice(string text)
		{
			if (Object.op_Implicit((Object)(object)Console.instance))
			{
				Console.instance.Print(text);
			}
			if (Object.op_Implicit((Object)(object)MessageHud.instance))
			{
				MessageHud.instance.ShowMessage((MessageType)2, text, 0, (Sprite)null, false, true);
			}
		}

		private static void Receive(long sender, ZPackage p)
		{
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0252: Expected O, but got Unknown
			//IL_0265: Unknown result type (might be due to invalid IL or missing references)
			//IL_0271: Unknown result type (might be due to invalid IL or missing references)
			//IL_0291: Unknown result type (might be due to invalid IL or missing references)
			//IL_029b: Expected O, but got Unknown
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0207: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)world) || !world.IsServer() || !PlacementAuthority.Admin(sender) || p.Size() > 4096)
			{
				return;
			}
			try
			{
				if (!HeaderValid(p) || !PlacementAuthority.PlayerContext(sender, out ZDO _, out long _, out Vector3 position))
				{
					return;
				}
				string text = p.ReadString();
				int num = p.ReadInt();
				if (!Guid.TryParseExact(text, "N", out var _) || num < 1 || num > 64 || batches.ContainsKey(text) || batches.Count >= 32)
				{
					return;
				}
				List<ZDOID> list = new List<ZDOID>();
				for (int i = 0; i < num; i++)
				{
					list.Add(p.ReadZDOID());
				}
				if (p.GetPos() != p.Size())
				{
					return;
				}
				if (rates.TryGetValue(sender, out var value) && value > Time.realtimeSinceStartup)
				{
					Deliver(sender, text, okay: false, "Please wait / Patienter.");
					return;
				}
				rates[sender] = Time.realtimeSinceStartup + 0.5f;
				Batch batch = new Batch
				{
					Client = sender,
					Until = Time.realtimeSinceStartup + 8f
				};
				batches[text] = batch;
				foreach (ZDOID item in list.Distinct())
				{
					ZDO zDO = ZDOMan.instance.GetZDO(item);
					GameObject val = ((zDO == null) ? null : ZNetScene.instance.GetPrefab(zDO.GetPrefab()));
					long num2 = ((zDO != null) ? zDO.GetOwner() : 0);
					if (zDO == null || !Object.op_Implicit((Object)(object)val) || !Supported(val) || !Permitted(((Object)val).name) || !SaddleGeometry.Finite(zDO.GetPosition()) || !CreatureState.Alive(zDO) || Vector3.Distance(position, zDO.GetPosition()) > 20f || num2 == 0L || (num2 != ZDOMan.GetSessionID() && world.GetPeer(num2) == null))
					{
						batch.Skipped++;
					}
					else
					{
						batch.Waiting[item] = num2;
					}
				}
				KeyValuePair<ZDOID, long>[] array = batch.Waiting.ToArray();
				for (int j = 0; j < array.Length; j++)
				{
					KeyValuePair<ZDOID, long> keyValuePair = array[j];
					ZPackage val2 = new ZPackage();
					Header(val2);
					val2.Write(text);
					val2.Write(keyValuePair.Key);
					val2.Write(position);
					if (keyValuePair.Value == ZDOMan.GetSessionID())
					{
						Grant(ZDOMan.GetSessionID(), new ZPackage(val2.GetArray()));
						continue;
					}
					rpc.InvokeRoutedRPC(keyValuePair.Value, "ZF_AdminTameGrant_v1", new object[1] { val2 });
				}
				Finish(text);
			}
			catch (Exception ex) when (ex is ArgumentException || ex is EndOfStreamException || ex is InvalidOperationException)
			{
				MountRegistry.Diagnostic("admin-tame-request", ex.GetType().Name + ": " + ex.Message);
			}
		}

		private unsafe static void Grant(long sender, ZPackage p)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_030e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0315: Expected O, but got Unknown
			//IL_0326: Unknown result type (might be due to invalid IL or missing references)
			//IL_0354: Unknown result type (might be due to invalid IL or missing references)
			//IL_035e: Expected O, but got Unknown
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//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)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a0: Unknown result type (might be due to invalid IL or missing references)
			if (!Server(sender) || p.Size() > 1024)
			{
				return;
			}
			string text = "";
			ZDOID val = default(ZDOID);
			bool flag = false;
			bool flag2 = false;
			try
			{
				if (!HeaderValid(p))
				{
					return;
				}
				text = p.ReadString();
				val = p.ReadZDOID();
				Vector3 val2 = p.ReadVector3();
				if (!Guid.TryParseExact(text, "N", out var _) || p.GetPos() != p.Size() || !SaddleGeometry.Finite(val2))
				{
					return;
				}
				string text2 = text;
				ZDOID val3 = val;
				string key = text2 + "/" + ((object)(*(ZDOID*)(&val3))/*cast due to .constrained prefix*/).ToString();
				if (seen.ContainsKey(key) || seen.Count >= 2048)
				{
					return;
				}
				seen[key] = Time.realtimeSinceStartup + 30f;
				GameObject val4 = ZNetScene.instance.FindInstance(val);
				Character val5 = (Object.op_Implicit((Object)(object)val4) ? val4.GetComponent<Character>() : null);
				ZNetView val6 = (Object.op_Implicit((Object)(object)val5) ? ((Component)val5).GetComponent<ZNetView>() : null);
				MonsterAI val7 = (Object.op_Implicit((Object)(object)val5) ? ((Component)val5).GetComponent<MonsterAI>() : null);
				if (Object.op_Implicit((Object)(object)val5) && Object.op_Implicit((Object)(object)val6) && val6.IsValid() && val6.IsOwner() && !val5.IsDead() && Object.op_Implicit((Object)(object)val7) && (Object)(object)AICharacter.Invoke((BaseAI)(object)val7) == (Object)(object)val5 && (Object)(object)AIView.Invoke((BaseAI)(object)val7) == (Object)(object)val6 && Object.op_Implicit((Object)(object)Game.instance) && Supported(((Component)val5).gameObject) && Permitted(Utils.GetPrefabName(((Component)val5).gameObject)) && Vector3.Distance(((Component)val5).transform.position, val2) <= 20f)
				{
					bool flag3 = val5.IsTamed();
					bool flag4 = Object.op_Implicit((Object)(object)((Component)val5).GetComponent<Tameable>());
					if (!flag4)
					{
						val6.GetZDO().Set("zf_admin_tame_v1", true);
					}
					Tameable val8 = Ensure(val5);
					if (Object.op_Implicit((Object)(object)val8) && (Object)(object)TameCharacter.Invoke(val8) == (Object)(object)val5 && (Object)(object)TameAI.Invoke(val8) == (Object)(object)val7 && (Object)(object)TameView.Invoke(val8) == (Object)(object)val6)
					{
						if (!flag3)
						{
							NativeTame(val8);
						}
						flag = val5.IsTamed();
						flag2 = flag && (!flag3 || !flag4);
						if (flag)
						{
							ZDOMan.instance.ForceSendZDO(val);
						}
					}
				}
			}
			catch (Exception ex) when (ex is ArgumentException || ex is InvalidOperationException || ex is EndOfStreamException)
			{
				MountRegistry.Diagnostic("admin-tame-owner", ex.GetType().Name + ": " + ex.Message);
			}
			if (text.Length == 32)
			{
				ZPackage val9 = new ZPackage();
				Header(val9);
				val9.Write(text);
				val9.Write(val);
				val9.Write(flag);
				val9.Write(flag2);
				if (world.IsServer())
				{
					Ack(ZDOMan.GetSessionID(), new ZPackage(val9.GetArray()));
					return;
				}
				rpc.InvokeRoutedRPC(world.GetServerPeer().m_uid, "ZF_AdminTameAck_v1", new object[1] { val9 });
			}
		}

		private static void Ack(long sender, ZPackage p)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)world) || !world.IsServer() || p.Size() > 1024)
			{
				return;
			}
			try
			{
				if (!HeaderValid(p))
				{
					return;
				}
				string text = p.ReadString();
				ZDOID val = p.ReadZDOID();
				bool flag = p.ReadBool();
				bool flag2 = p.ReadBool();
				if (p.GetPos() == p.Size() && batches.TryGetValue(text, out Batch value) && value.Waiting.TryGetValue(val, out var value2) && sender == value2)
				{
					ZDO zDO = ZDOMan.instance.GetZDO(val);
					flag = flag && zDO != null && zDO.GetOwner() == value2 && zDO.GetBool(Z