Decompiled source of RustyHeathensWarSaddle v1.0.2

RustyHeathensWarSaddle.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using UnityEngine;
using UnityEngine.Rendering;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Rusty Heathens War Saddle")]
[assembly: AssemblyDescription("Animated moose saddlebags with configurable server-controlled storage")]
[assembly: AssemblyCompany("RustyHeathens")]
[assembly: AssemblyFileVersion("1.0.2.0")]
[assembly: AssemblyVersion("1.0.2.0")]
namespace RustyHeathensWarSaddle;

[BepInPlugin("com.rustyheathens.warsaddle", "Rusty Heathens War Saddle", "1.0.2")]
public sealed class Plugin : BaseUnityPlugin
{
	[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
	private static class ConnectionPatch
	{
		private static void Postfix(ZNetPeer __0)
		{
			if ((Object)(object)Instance != (Object)null && Instance.Capacity != null)
			{
				Instance.Capacity.Register(__0);
			}
		}
	}

	[HarmonyPatch(typeof(Tameable), "Awake")]
	private static class SpawnPatch
	{
		private static void Postfix(Tameable __instance)
		{
			Attach(((Component)__instance).GetComponent<Character>());
		}
	}

	[HarmonyPatch(typeof(Tameable), "DropSaddle")]
	private static class RemovePatch
	{
		private static bool Prefix(Tameable __instance, ref bool __result)
		{
			WarMount component = ((Component)__instance).GetComponent<WarMount>();
			if ((Object)(object)component == (Object)null || component.CanRemove())
			{
				return true;
			}
			Tell("Empty and close Jo-bags before removing the saddle.");
			__result = false;
			return false;
		}
	}

	[HarmonyPatch(typeof(Sadle), "Interact")]
	private static class LocalRemovePatch
	{
		private static bool Prefix(Sadle __instance, bool __2, ref bool __result)
		{
			WarMount componentInParent = ((Component)__instance).GetComponentInParent<WarMount>();
			if (!__2 || (Object)(object)componentInParent == (Object)null || componentInParent.CanRemove())
			{
				return true;
			}
			Tell("Empty and close Jo-bags before removing the saddle.");
			__result = true;
			return false;
		}
	}

	[HarmonyPatch(typeof(Sadle), "RPC_RequestControl")]
	private static class RidePatch
	{
		private static bool Prefix(Sadle __instance, long __0)
		{
			WarMount componentInParent = ((Component)__instance).GetComponentInParent<WarMount>();
			if ((Object)(object)componentInParent == (Object)null || !componentInParent.View.IsOwner() || (Object)(object)componentInParent.Bag == (Object)null || !componentInParent.Bag.IsInUse())
			{
				return true;
			}
			componentInParent.View.InvokeRPC(__0, "RequestRespons", new object[1] { false });
			return false;
		}
	}

	[HarmonyPatch(typeof(Tameable), "GetHoverText")]
	private static class HoverPatch
	{
		private static void Postfix(Tameable __instance, ref string __result)
		{
			AppendHover(((Component)__instance).GetComponent<WarMount>(), ref __result);
		}
	}

	[HarmonyPatch(typeof(Sadle), "GetHoverText")]
	private static class SaddleHoverPatch
	{
		private static void Postfix(Sadle __instance, ref string __result)
		{
			AppendHover(((Component)__instance).GetComponentInParent<WarMount>(), ref __result);
		}
	}

	[HarmonyPatch(typeof(Character), "OnDeath")]
	private static class DeathPatch
	{
		private static bool Prefix(Character __instance)
		{
			WarMount component = ((Component)__instance).GetComponent<WarMount>();
			if (!((Object)(object)component == (Object)null))
			{
				return component.PrepareDeath();
			}
			return true;
		}
	}

	public const string Id = "com.rustyheathens.warsaddle";

	public const string Version = "1.0.2";

	internal static Plugin Instance;

	internal ConfigEntry<KeyboardShortcut> OpenKey;

	internal ConfigEntry<float> BagScale;

	internal ConfigEntry<float> HeadScale;

	internal ConfigEntry<Vector3> BagOffset;

	internal ConfigEntry<Vector3> HeadOffset;

	internal ConfigEntry<Vector3> HeadAngles;

	internal ConfigEntry<bool> Diagnostics;

	internal ConfigEntry<bool> ShowHeadArmor;

	internal CapacitySync Capacity;

	private Harmony harmony;

	private float nextScan;

	private void Awake()
	{
		//IL_001e: 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_008c: Expected O, but got Unknown
		//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ca: Expected O, but got Unknown
		//IL_00e0: 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_012a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0176: Unknown result type (might be due to invalid IL or missing references)
		//IL_0180: Expected O, but got Unknown
		Instance = this;
		OpenKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Controls", "OpenBags", new KeyboardShortcut((KeyCode)107, Array.Empty<KeyCode>()), "Look at a saddled moose while dismounted and press this shortcut.");
		ShowHeadArmor = ((BaseUnityPlugin)this).Config.Bind<bool>("Appearance", "ShowHeadArmor", false, "Show the experimental head armor. Disabled while Jo-bags are being fitted. Restart to apply.");
		BagScale = ((BaseUnityPlugin)this).Config.Bind<float>("Appearance", "BagScale", 1f, new ConfigDescription("Cosmetic bag size. Restart to apply.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 1.5f), Array.Empty<object>()));
		HeadScale = ((BaseUnityPlugin)this).Config.Bind<float>("Appearance", "HeadArmorScale", 1f, new ConfigDescription("Cosmetic head plate size. Restart to apply.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 1.5f), Array.Empty<object>()));
		BagOffset = ((BaseUnityPlugin)this).Config.Bind<Vector3>("Appearance", "BagOffset", Vector3.zero, "Bag offset in moose-local meters (x right, y up, z forward). Restart to apply.");
		HeadOffset = ((BaseUnityPlugin)this).Config.Bind<Vector3>("Appearance", "HeadOffset", Vector3.zero, "Head armor offset in its fitting frame (x right, y up, z nose). Restart to apply.");
		HeadAngles = ((BaseUnityPlugin)this).Config.Bind<Vector3>("Appearance", "HeadAngles", Vector3.zero, "Additional head plate rotation in degrees. Restart to apply.");
		Diagnostics = ((BaseUnityPlugin)this).Config.Bind<bool>("Diagnostics", "LogFitting", false, "Log model-fitting and attachment details for troubleshooting.");
		Capacity = new CapacitySync(((BaseUnityPlugin)this).Config);
		harmony = new Harmony("com.rustyheathens.warsaddle");
		harmony.PatchAll(typeof(Plugin).Assembly);
		((BaseUnityPlugin)this).Logger.LogInfo((object)"War Saddle 1.0.2 loaded. K opens Jo-bags. Armor is cosmetic only.");
	}

	private void Update()
	{
		//IL_0078: 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)
		Capacity.Tick();
		if (Time.realtimeSinceStartup >= nextScan)
		{
			nextScan = Time.realtimeSinceStartup + 3f;
			foreach (Character allCharacter in Character.GetAllCharacters())
			{
				Attach(allCharacter);
			}
		}
		Player localPlayer = Player.m_localPlayer;
		if ((Object)(object)localPlayer == (Object)null || ((Character)localPlayer).IsDead())
		{
			return;
		}
		KeyboardShortcut value = OpenKey.Value;
		if (!((KeyboardShortcut)(ref value)).IsDown() || ((Object)(object)Chat.instance != (Object)null && Chat.instance.HasFocus()) || Console.IsVisible() || TextInput.IsVisible() || Menu.IsVisible() || InventoryGui.IsVisible() || Minimap.IsOpen() || StoreGui.IsVisible())
		{
			return;
		}
		if (localPlayer.GetDoodadController() != null)
		{
			Tell("Dismount before opening Jo-bags.");
			return;
		}
		GameObject hoverObject = ((Humanoid)localPlayer).GetHoverObject();
		WarMount warMount = (((Object)(object)hoverObject == (Object)null) ? null : hoverObject.GetComponentInParent<WarMount>());
		if ((Object)(object)warMount != (Object)null)
		{
			warMount.Open(localPlayer);
		}
	}

	internal static void Attach(Character character)
	{
		if (!((Object)(object)character == (Object)null) && Rules.IsMoose(((Object)((Component)character).gameObject).name) && !((Object)(object)((Component)character).GetComponent<WarMount>() != (Object)null))
		{
			ZNetView component = ((Component)character).GetComponent<ZNetView>();
			if (!((Object)(object)component == (Object)null) && component.IsValid() && !((Object)(object)((Component)character).GetComponent<Tameable>() == (Object)null))
			{
				((Component)character).gameObject.AddComponent<WarMount>();
			}
		}
	}

	internal static void Tell(string text)
	{
		if ((Object)(object)Player.m_localPlayer != (Object)null)
		{
			((Character)Player.m_localPlayer).Message((MessageType)2, text, 0, (Sprite)null, false);
		}
	}

	internal static void LogInfo(string text)
	{
		if ((Object)(object)Instance != (Object)null)
		{
			((BaseUnityPlugin)Instance).Logger.LogInfo((object)text);
		}
	}

	internal static void Error(string text)
	{
		if ((Object)(object)Instance != (Object)null)
		{
			((BaseUnityPlugin)Instance).Logger.LogError((object)text);
		}
	}

	private void OnDestroy()
	{
		if (Capacity != null)
		{
			Capacity.Dispose();
		}
		if (harmony != null)
		{
			harmony.UnpatchSelf();
		}
		Instance = null;
	}

	private static void AppendHover(WarMount m, ref string text)
	{
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		if (!((Object)(object)m == (Object)null) && !((Object)(object)m.Bag == (Object)null) && !((Object)(object)Instance == (Object)null))
		{
			text = text + "\n[<color=#73bcff>" + ((object)Instance.OpenKey.Value/*cast due to .constrained prefix*/).ToString() + "</color>] Jo-bags (" + m.Bag.GetInventory().GetWidth() * m.Bag.GetInventory().GetHeight() + " slots)";
			if (m.ResizePending)
			{
				text += "\nEmpty and close bags to apply the new size";
			}
		}
	}
}
internal static class Rules
{
	internal const int Width = 4;

	internal const int Height = 4;

	internal const int MaxWidth = 8;

	internal const int MaxHeight = 4;

	internal static bool ValidSize(int width, int height)
	{
		if (width >= 1 && width <= 8 && height >= 1)
		{
			return height <= 4;
		}
		return false;
	}

	internal static bool CanResize(int oldWidth, int oldHeight, int width, int height, int itemCount)
	{
		if (ValidSize(width, height))
		{
			if (itemCount != 0)
			{
				if (width >= oldWidth)
				{
					return height >= oldHeight;
				}
				return false;
			}
			return true;
		}
		return false;
	}

	internal static bool TryCapacityMessage(string text, out int width, out int height)
	{
		width = (height = 0);
		if (text == null || text.Length > 40)
		{
			return false;
		}
		string[] array = text.Split('|');
		if (array.Length == 4 && array[0] == "S" && array[1] == "1" && int.TryParse(array[2], out width) && int.TryParse(array[3], out height))
		{
			return ValidSize(width, height);
		}
		return false;
	}

	internal static bool IsMoose(string name)
	{
		if (name == null)
		{
			return false;
		}
		if (name.EndsWith("(Clone)", StringComparison.Ordinal))
		{
			name = name.Substring(0, name.Length - 7);
		}
		return name == "Moose";
	}

	internal static bool CanOpen(bool tamed, bool saddled, bool alive, bool ridden, bool loaded)
	{
		return tamed && saddled && alive && !ridden && loaded;
	}

	internal static bool CanRemove(bool loaded, int count, bool inUse)
	{
		if (loaded && count == 0)
		{
			return !inUse;
		}
		return false;
	}

	internal static bool IsPlausibleBakedSpan(float baked, float visible)
	{
		if (!float.IsNaN(baked) && !float.IsInfinity(baked) && !float.IsNaN(visible) && !float.IsInfinity(visible) && baked > 0f && visible > 0f && baked / visible >= 0.1f)
		{
			return baked / visible <= 4f;
		}
		return false;
	}

	internal static bool NeedsGridRebuild(int width, int height, int elements, int cachedWidth, int cachedHeight)
	{
		if (width > 0 && height > 0 && cachedWidth == width && cachedHeight == height)
		{
			return elements != width * height;
		}
		return false;
	}

	internal static bool ShouldCreate(bool tamed, bool saddled, bool savedItems)
	{
		return (tamed && saddled) || savedItems;
	}
}
internal sealed class WarVisuals : IDisposable
{
	private sealed class Parts
	{
		private readonly WarVisuals owner;

		private readonly Transform parent;

		private readonly Dictionary<Material, List<CombineInstance>> batches = new Dictionary<Material, List<CombineInstance>>();

		private readonly List<Mesh> temporary = new List<Mesh>();

		internal Parts(WarVisuals o, Transform p)
		{
			owner = o;
			parent = p;
		}

		internal void Box(Vector3 center, Vector3 size, Material material, float bevel)
		{
			//IL_0001: 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)
			Add(Geometry.BevelBox(size, bevel), center, material);
		}

		internal void CurvedPlate(Vector3 center, float width, float height, float curve, Material material)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			Add(Geometry.Breastplate(width, height, curve), center, material);
		}

		internal void Add(Mesh mesh, Vector3 center, Material material)
		{
			//IL_0032: 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_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			temporary.Add(mesh);
			if (!batches.TryGetValue(material, out var value))
			{
				value = new List<CombineInstance>();
				batches.Add(material, value);
			}
			List<CombineInstance> list = value;
			CombineInstance item = default(CombineInstance);
			((CombineInstance)(ref item)).mesh = mesh;
			((CombineInstance)(ref item)).transform = Matrix4x4.Translate(center);
			list.Add(item);
		}

		internal void Flush()
		{
			//IL_001e: 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_0035: 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_0056: Expected O, but got Unknown
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			foreach (KeyValuePair<Material, List<CombineInstance>> batch in batches)
			{
				GameObject val = new GameObject("RHWS_CosmeticMesh");
				val.transform.SetParent(parent, false);
				val.layer = ((Component)owner.mount).gameObject.layer;
				Mesh val2 = new Mesh();
				((Object)val2).name = "RHWS_Combined";
				val2.CombineMeshes(batch.Value.ToArray(), true, true);
				val2.RecalculateBounds();
				owner.owned.Add((Object)(object)val2);
				val.AddComponent<MeshFilter>().sharedMesh = val2;
				MeshRenderer obj = val.AddComponent<MeshRenderer>();
				((Renderer)obj).sharedMaterial = batch.Key;
				((Renderer)obj).shadowCastingMode = (ShadowCastingMode)1;
				((Renderer)obj).receiveShadows = true;
			}
			foreach (Mesh item in temporary)
			{
				Object.Destroy((Object)(object)item);
			}
			temporary.Clear();
		}
	}

	private readonly List<GameObject> roots = new List<GameObject>();

	private readonly List<Object> owned = new List<Object>();

	private readonly Material metal;

	private readonly Material leather;

	private readonly Material trim;

	private readonly Material strapLeather;

	private readonly Material thread;

	private readonly WarMount mount;

	private static readonly FieldInfo HeadField = AccessTools.Field(typeof(Character), "m_head");

	internal unsafe WarVisuals(WarMount m)
	{
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c8: Unknown result type (might be due to invalid IL or missing references)
		//IL_02cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0306: Unknown result type (might be due to invalid IL or missing references)
		//IL_0329: Unknown result type (might be due to invalid IL or missing references)
		//IL_032b: Unknown result type (might be due to invalid IL or missing references)
		//IL_033b: Unknown result type (might be due to invalid IL or missing references)
		//IL_034b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0352: Unknown result type (might be due to invalid IL or missing references)
		//IL_035f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0377: Unknown result type (might be due to invalid IL or missing references)
		//IL_0379: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f8: Unknown result type (might be due to invalid IL or missing references)
		//IL_02fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0302: Unknown result type (might be due to invalid IL or missing references)
		//IL_03cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_03d1: Unknown result type (might be due to invalid IL or missing references)
		//IL_03dd: Unknown result type (might be due to invalid IL or missing references)
		//IL_03e3: Unknown result type (might be due to invalid IL or missing references)
		//IL_03f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_03fb: Unknown result type (might be due to invalid IL or missing references)
		//IL_0400: Unknown result type (might be due to invalid IL or missing references)
		//IL_0405: Unknown result type (might be due to invalid IL or missing references)
		//IL_0409: Unknown result type (might be due to invalid IL or missing references)
		//IL_040e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0410: Unknown result type (might be due to invalid IL or missing references)
		//IL_0418: Unknown result type (might be due to invalid IL or missing references)
		//IL_05e9: Unknown result type (might be due to invalid IL or missing references)
		//IL_05eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_0605: Unknown result type (might be due to invalid IL or missing references)
		//IL_0607: Unknown result type (might be due to invalid IL or missing references)
		//IL_04c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_04cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_04d0: Unknown result type (might be due to invalid IL or missing references)
		//IL_04d5: Unknown result type (might be due to invalid IL or missing references)
		//IL_04ea: Unknown result type (might be due to invalid IL or missing references)
		//IL_04ef: Unknown result type (might be due to invalid IL or missing references)
		//IL_04fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_04ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_0504: Unknown result type (might be due to invalid IL or missing references)
		//IL_0506: Unknown result type (might be due to invalid IL or missing references)
		//IL_0515: Unknown result type (might be due to invalid IL or missing references)
		//IL_0524: Unknown result type (might be due to invalid IL or missing references)
		//IL_0529: Unknown result type (might be due to invalid IL or missing references)
		//IL_052e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0429: Unknown result type (might be due to invalid IL or missing references)
		//IL_042b: Unknown result type (might be due to invalid IL or missing references)
		//IL_047c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0482: Unknown result type (might be due to invalid IL or missing references)
		//IL_0495: Unknown result type (might be due to invalid IL or missing references)
		//IL_049b: Unknown result type (might be due to invalid IL or missing references)
		//IL_04a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_04a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_04a9: Unknown result type (might be due to invalid IL or missing references)
		//IL_04ae: Unknown result type (might be due to invalid IL or missing references)
		mount = m;
		try
		{
			Material val = FindTemplate(m);
			metal = Material(val, new Color(0.22f, 0.25f, 0.29f), 0.72f, 0.35f);
			leather = Material(val, new Color(0.36f, 0.2f, 0.1f), 0f, 0.18f);
			trim = Material(val, new Color(0.1f, 0.24f, 0.32f), 0.58f, 0.32f);
			strapLeather = Material(val, new Color(0.22f, 0.115f, 0.055f), 0f, 0.12f);
			thread = Material(val, new Color(0.48f, 0.33f, 0.18f), 0f, 0.08f);
			AddLeatherGrain();
			if (Plugin.Instance.Diagnostics.Value)
			{
				Plugin.LogInfo("WarSaddle surface: template=" + ((Object)val).name + "; shader=" + ((Object)val.shader).name);
			}
			Transform val2 = (Transform)((HeadField == null) ? null : /*isinst with value type is only supported in some contexts*/);
			Transform val3 = null;
			Transform[] componentsInChildren = ((Component)m).GetComponentsInChildren<Transform>(true);
			List<string> list = new List<string>();
			Transform[] array = componentsInChildren;
			foreach (Transform val4 in array)
			{
				string text = ((Object)val4).name.ToLowerInvariant();
				if (text.Contains("head") || text.Contains("spine") || text.Contains("neck"))
				{
					list.Add(((Object)val4).name);
				}
				if ((Object)(object)val2 == (Object)null && (text == "head" || text.EndsWith(":head") || text.EndsWith("_head")))
				{
					val2 = val4;
				}
				if (text == "neck" || text.EndsWith(":neck") || text.EndsWith("_neck"))
				{
					val3 = val4;
				}
			}
			if ((Object)(object)val2 == (Object)null)
			{
				array = componentsInChildren;
				foreach (Transform val5 in array)
				{
					if (((Object)val5).name.ToLowerInvariant().Contains("head") && !((Object)val5).name.ToLowerInvariant().Contains("mesh"))
					{
						val2 = val5;
						break;
					}
				}
			}
			List<Vector3> list2 = BakePoints(m);
			Bounds val6 = EstimateBody(list2, m);
			Vector3 val7 = ((Component)m).transform.InverseTransformPoint(((Component)m.Tame.m_saddle).transform.position);
			Sadle saddle = m.Tame.m_saddle;
			if ((Object)(object)saddle.m_attachPoint != (Object)null)
			{
				val7 = ((Component)m).transform.InverseTransformPoint(saddle.m_attachPoint.position);
			}
			float num = Mathf.Clamp(((Bounds)(ref val6)).size.z * 0.28f, 0.45f, 1.1f);
			float num2 = MeasureFlank(list2, val7, val7.z - num * 0.48f, val6, 0.65f);
			Vector3 position = default(Vector3);
			((Vector3)(ref position))..ctor(val7.x, val7.y - 0.3f, val7.z);
			Transform val8 = Frame("RHWS_Saddlebags", ((Component)m).transform, position, Quaternion.identity);
			BuildBags(val8, num2, num);
			Transform val9 = FindBagAnchor(m, saddle, componentsInChildren);
			val8.SetParent(val9, true);
			Vector3 val11;
			if ((Object)(object)val2 != (Object)null && Plugin.Instance.ShowHeadArmor.Value)
			{
				Vector3 val10 = ((Component)m).transform.forward;
				if ((Object)(object)val3 != (Object)null && Vector3.Distance(val2.position, val3.position) > 0.08f)
				{
					val11 = val2.position - val3.position;
					Vector3 normalized = ((Vector3)(ref val11)).normalized;
					if (Vector3.Dot(normalized, ((Component)m).transform.forward) > 0.15f)
					{
						val10 = normalized;
					}
				}
				array = ((Component)val2).GetComponentsInChildren<Transform>(true);
				foreach (Transform val12 in array)
				{
					string text2 = ((Object)val12).name.ToLowerInvariant();
					if ((text2.Contains("nose") || text2.Contains("snout") || text2.Contains("muzzle")) && Vector3.Distance(val12.position, val2.position) > 0.05f)
					{
						val11 = val12.position - val2.position;
						val10 = ((Vector3)(ref val11)).normalized;
						break;
					}
				}
				Quaternion val13 = Quaternion.LookRotation(val10, ((Component)m).transform.up);
				Transform val14 = Frame("RHWS_OpenFaceHeadArmor", ((Component)m).transform, ((Component)m).transform.InverseTransformPoint(val2.position), Quaternion.Inverse(((Component)m).transform.rotation) * val13);
				val14.localRotation *= Quaternion.Euler(Plugin.Instance.HeadAngles.Value);
				float size = Mathf.Clamp(num2 * 0.68f, 0.25f, 0.6f) * Plugin.Instance.HeadScale.Value;
				BuildHead(val14, size);
				val14.SetParent(val2, true);
			}
			else if (Plugin.Instance.ShowHeadArmor.Value)
			{
				Plugin.Error("WarSaddle could not identify the animated head. Head armor was skipped; send the fitting log so the correct bone can be mapped.");
			}
			if (Plugin.Instance.Diagnostics.Value)
			{
				string[] obj = new string[14]
				{
					"WarSaddle fit: head=",
					((Object)(object)val2 == (Object)null) ? "NOT FOUND" : ((Object)val2).name,
					"; attachment=",
					((Object)val9).name,
					"; saddle=",
					null,
					null,
					null,
					null,
					null,
					null,
					null,
					null,
					null
				};
				val11 = val7;
				obj[5] = ((object)(*(Vector3*)(&val11))/*cast due to .constrained prefix*/).ToString();
				obj[6] = "; body=";
				Bounds val15 = val6;
				obj[7] = ((object)(*(Bounds*)(&val15))/*cast due to .constrained prefix*/).ToString();
				obj[8] = "; halfWidth=";
				obj[9] = num2.ToString();
				obj[10] = "; sampledVertices=";
				obj[11] = list2.Count.ToString();
				obj[12] = "; bones=";
				obj[13] = string.Join(",", list.ToArray());
				Plugin.LogInfo(string.Concat(obj));
			}
		}
		catch
		{
			Dispose();
			throw;
		}
	}

	private static bool IsBackBone(Transform bone)
	{
		if ((Object)(object)bone == (Object)null)
		{
			return false;
		}
		string text = ((Object)bone).name.ToLowerInvariant();
		if (!text.Contains("spine") && !(text == "back") && !text.EndsWith(":back"))
		{
			return text.EndsWith("_back");
		}
		return true;
	}

	private static bool IsSaddleMesh(SkinnedMeshRenderer renderer, Sadle seat)
	{
		if (((Component)renderer).transform.IsChildOf(((Component)seat).transform))
		{
			return true;
		}
		if (((Object)renderer).name.ToLowerInvariant().Contains("saddle") || ((Object)renderer).name.ToLowerInvariant().Contains("sadle"))
		{
			return true;
		}
		if ((Object)(object)renderer.sharedMesh != (Object)null && ((Object)renderer.sharedMesh).name.ToLowerInvariant().Contains("saddle"))
		{
			return true;
		}
		Material[] sharedMaterials = ((Renderer)renderer).sharedMaterials;
		foreach (Material val in sharedMaterials)
		{
			if ((Object)(object)val != (Object)null && ((Object)val).name.ToLowerInvariant().Contains("saddle"))
			{
				return true;
			}
		}
		return false;
	}

	private static void VoteBone(Dictionary<Transform, float> scores, Transform[] bones, int index, float weight, float proximity)
	{
		if (index >= 0 && index < bones.Length && !(weight <= 0f) && IsBackBone(bones[index]))
		{
			scores.TryGetValue(bones[index], out var value);
			scores[bones[index]] = value + weight * proximity;
		}
	}

	private static Transform FindBagAnchor(WarMount m, Sadle seat, Transform[] all)
	{
		//IL_0021: 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_0026: Unknown result type (might be due to invalid IL or missing references)
		//IL_0380: Unknown result type (might be due to invalid IL or missing references)
		//IL_0385: Unknown result type (might be due to invalid IL or missing references)
		//IL_0386: Unknown result type (might be due to invalid IL or missing references)
		//IL_038b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b9: Expected O, but got Unknown
		//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f1: 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_010d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0118: 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_0134: Unknown result type (might be due to invalid IL or missing references)
		//IL_0140: 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_0149: Unknown result type (might be due to invalid IL or missing references)
		//IL_0172: Unknown result type (might be due to invalid IL or missing references)
		//IL_0177: Unknown result type (might be due to invalid IL or missing references)
		//IL_017c: Unknown result type (might be due to invalid IL or missing references)
		//IL_017d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0182: Unknown result type (might be due to invalid IL or missing references)
		//IL_019d: 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)
		Vector3 val = (((Object)(object)seat.m_attachPoint != (Object)null) ? seat.m_attachPoint.position : ((Component)seat).transform.position);
		SkinnedMeshRenderer[] componentsInChildren = ((Component)m).GetComponentsInChildren<SkinnedMeshRenderer>(true);
		Bounds val4 = default(Bounds);
		for (int i = 0; i < 2; i++)
		{
			Dictionary<Transform, float> dictionary = new Dictionary<Transform, float>();
			SkinnedMeshRenderer[] array = componentsInChildren;
			foreach (SkinnedMeshRenderer val2 in array)
			{
				if ((Object)(object)val2.sharedMesh == (Object)null || !((Component)val2).gameObject.activeInHierarchy)
				{
					continue;
				}
				bool flag = IsSaddleMesh(val2, seat);
				if (i == 0 != flag)
				{
					continue;
				}
				Mesh val3 = null;
				try
				{
					BoneWeight[] boneWeights = val2.sharedMesh.boneWeights;
					Transform[] bones = val2.bones;
					if (boneWeights.Length == 0 || bones.Length == 0)
					{
						continue;
					}
					val3 = new Mesh();
					val2.BakeMesh(val3, true);
					Vector3[] vertices = val3.vertices;
					if (vertices.Length != boneWeights.Length)
					{
						continue;
					}
					((Bounds)(ref val4))..ctor(((Component)val2).transform.TransformPoint(vertices[0]), Vector3.zero);
					Vector3[] array2 = vertices;
					foreach (Vector3 val5 in array2)
					{
						((Bounds)(ref val4)).Encapsulate(((Component)val2).transform.TransformPoint(val5));
					}
					float baked = MaxAxis(((Bounds)(ref val4)).size);
					Bounds bounds = ((Renderer)val2).bounds;
					if (Rules.IsPlausibleBakedSpan(baked, MaxAxis(((Bounds)(ref bounds)).size)))
					{
						for (int l = 0; l < vertices.Length; l++)
						{
							Vector3 val6 = ((Component)val2).transform.TransformPoint(vertices[l]) - val;
							float proximity = 1f / (0.04f + ((Vector3)(ref val6)).sqrMagnitude);
							BoneWeight val7 = boneWeights[l];
							VoteBone(dictionary, bones, ((BoneWeight)(ref val7)).boneIndex0, ((BoneWeight)(ref val7)).weight0, proximity);
							VoteBone(dictionary, bones, ((BoneWeight)(ref val7)).boneIndex1, ((BoneWeight)(ref val7)).weight1, proximity);
							VoteBone(dictionary, bones, ((BoneWeight)(ref val7)).boneIndex2, ((BoneWeight)(ref val7)).weight2, proximity);
							VoteBone(dictionary, bones, ((BoneWeight)(ref val7)).boneIndex3, ((BoneWeight)(ref val7)).weight3, proximity);
						}
					}
				}
				catch (Exception ex)
				{
					if (Plugin.Instance.Diagnostics.Value)
					{
						Plugin.LogInfo("WarSaddle attachment: cannot sample " + ((Object)val2).name + ": " + ex.Message);
					}
				}
				finally
				{
					if ((Object)(object)val3 != (Object)null)
					{
						Object.Destroy((Object)(object)val3);
					}
				}
			}
			Transform val8 = null;
			float num = 0f;
			float num2 = 0f;
			foreach (KeyValuePair<Transform, float> item in dictionary)
			{
				num2 += item.Value;
				if (item.Value > num)
				{
					num = item.Value;
					val8 = item.Key;
				}
			}
			if ((Object)(object)val8 != (Object)null)
			{
				if (Plugin.Instance.Diagnostics.Value)
				{
					Plugin.LogInfo("WarSaddle attachment: bone=" + ((Object)val8).name + "; source=" + ((i == 0) ? "saddle skin weights" : "body skin weights") + "; share=" + num / num2);
				}
				return val8;
			}
		}
		Transform val9 = null;
		float num3 = float.PositiveInfinity;
		foreach (Transform val10 in all)
		{
			if (IsBackBone(val10))
			{
				Vector3 val11 = val10.position - val;
				float sqrMagnitude = ((Vector3)(ref val11)).sqrMagnitude;
				if (sqrMagnitude < num3)
				{
					num3 = sqrMagnitude;
					val9 = val10;
				}
			}
		}
		if ((Object)(object)val9 != (Object)null)
		{
			Plugin.LogInfo("WarSaddle attachment: bone=" + ((Object)val9).name + "; source=nearest spine fallback");
			return val9;
		}
		Plugin.Error("WarSaddle found no animated back bone. Bags use the interaction object as a fallback; send the WarSaddle fitting log.");
		return ((Component)seat).transform;
	}

	private static Material FindTemplate(WarMount m)
	{
		Material val = (((Object)(object)m.Tame.m_saddle == (Object)null) ? null : FindOpaque(((Component)m.Tame.m_saddle).GetComponentsInChildren<Renderer>(true)));
		if ((Object)(object)val == (Object)null)
		{
			val = FindOpaque(((Component)m).GetComponentsInChildren<Renderer>(true));
		}
		if ((Object)(object)val == (Object)null)
		{
			throw new InvalidOperationException("Moose and saddle have no loaded opaque material yet.");
		}
		return val;
	}

	private static Material FindOpaque(Renderer[] renderers)
	{
		foreach (Renderer val in renderers)
		{
			if (!(val is MeshRenderer) && !(val is SkinnedMeshRenderer))
			{
				continue;
			}
			Material[] sharedMaterials = val.sharedMaterials;
			foreach (Material val2 in sharedMaterials)
			{
				if (!((Object)(object)val2 == (Object)null) && !((Object)(object)val2.shader == (Object)null) && val2.shader.isSupported)
				{
					string text = ((Object)val2.shader).name.ToLowerInvariant();
					if (val2.renderQueue < 3000 && !text.Contains("particle") && !text.Contains("transparent") && !text.Contains("error"))
					{
						return val2;
					}
				}
			}
		}
		return null;
	}

	private Material Material(Material template, Color color, float metallic, float gloss)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		//IL_005c: 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_00a9: Unknown result type (might be due to invalid IL or missing references)
		//IL_013a: Unknown result type (might be due to invalid IL or missing references)
		Material val = new Material(template);
		((Object)val).name = "RHWS_Surface";
		owned.Add((Object)(object)val);
		string[] array = new string[3] { "_MainTex", "_BaseMap", "_BaseColorMap" };
		foreach (string text in array)
		{
			if (val.HasProperty(text))
			{
				val.SetTexture(text, (Texture)(object)Texture2D.whiteTexture);
				val.SetTextureScale(text, Vector2.one);
				val.SetTextureOffset(text, Vector2.zero);
			}
		}
		array = new string[2] { "_Color", "_BaseColor" };
		foreach (string text2 in array)
		{
			if (val.HasProperty(text2))
			{
				val.SetColor(text2, color);
			}
		}
		array = new string[4] { "_BumpMap", "_NormalMap", "_MetallicGlossMap", "_EmissionMap" };
		foreach (string text3 in array)
		{
			if (val.HasProperty(text3))
			{
				val.SetTexture(text3, (Texture)null);
			}
		}
		val.DisableKeyword("_NORMALMAP");
		val.DisableKeyword("_EMISSION");
		val.DisableKeyword("_METALLICGLOSSMAP");
		if (val.HasProperty("_EmissionColor"))
		{
			val.SetColor("_EmissionColor", Color.black);
		}
		if (val.HasProperty("_Metallic"))
		{
			val.SetFloat("_Metallic", metallic);
		}
		if (val.HasProperty("_Glossiness"))
		{
			val.SetFloat("_Glossiness", gloss);
		}
		if (val.HasProperty("_Smoothness"))
		{
			val.SetFloat("_Smoothness", gloss);
		}
		return val;
	}

	private Transform Frame(string name, Transform parent, Vector3 position, Quaternion rotation)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		GameObject val = new GameObject(name);
		roots.Add(val);
		val.transform.SetParent(parent, false);
		val.transform.localPosition = position;
		val.transform.localRotation = rotation;
		return val.transform;
	}

	private static List<Vector3> BakePoints(WarMount m)
	{
		//IL_008e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0095: Expected O, but got Unknown
		//IL_00a8: 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_00c8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d3: 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_011e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0123: Unknown result type (might be due to invalid IL or missing references)
		//IL_0127: Unknown result type (might be due to invalid IL or missing references)
		//IL_0135: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_0102: Unknown result type (might be due to invalid IL or missing references)
		//IL_0104: Unknown result type (might be due to invalid IL or missing references)
		//IL_0191: Unknown result type (might be due to invalid IL or missing references)
		//IL_0196: Unknown result type (might be due to invalid IL or missing references)
		//IL_023c: Unknown result type (might be due to invalid IL or missing references)
		//IL_022e: Unknown result type (might be due to invalid IL or missing references)
		//IL_025c: Unknown result type (might be due to invalid IL or missing references)
		//IL_024e: Unknown result type (might be due to invalid IL or missing references)
		//IL_027c: Unknown result type (might be due to invalid IL or missing references)
		//IL_026e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0292: Unknown result type (might be due to invalid IL or missing references)
		//IL_0294: Unknown result type (might be due to invalid IL or missing references)
		List<Vector3> list = new List<Vector3>();
		GameObject visual = m.Character.GetVisual();
		SkinnedMeshRenderer[] componentsInChildren = (((Object)(object)visual != (Object)null) ? visual : ((Component)m).gameObject).GetComponentsInChildren<SkinnedMeshRenderer>(true);
		Vector3 val6 = default(Vector3);
		foreach (SkinnedMeshRenderer val in componentsInChildren)
		{
			if ((Object)(object)val.sharedMesh == (Object)null || !((Component)val).gameObject.activeInHierarchy || ((Object)(object)m.Tame.m_saddle != (Object)null && ((Component)val).transform.IsChildOf(((Component)m.Tame.m_saddle).transform)))
			{
				continue;
			}
			Mesh val2 = new Mesh();
			try
			{
				val.BakeMesh(val2, true);
				List<Vector3> list2 = new List<Vector3>();
				Bounds val3 = default(Bounds);
				bool flag = true;
				Vector3[] vertices = val2.vertices;
				foreach (Vector3 val4 in vertices)
				{
					Vector3 val5 = ((Component)val).transform.TransformPoint(val4);
					if (flag)
					{
						((Bounds)(ref val3))..ctor(val5, Vector3.zero);
						flag = false;
					}
					else
					{
						((Bounds)(ref val3)).Encapsulate(val5);
					}
					list2.Add(((Component)m).transform.InverseTransformPoint(val5));
				}
				Bounds bounds = ((Renderer)val).bounds;
				float baked = MaxAxis(((Bounds)(ref val3)).size);
				float num = MaxAxis(((Bounds)(ref bounds)).size);
				bool flag2 = !flag && Rules.IsPlausibleBakedSpan(baked, num);
				if (Plugin.Instance.Diagnostics.Value)
				{
					Plugin.LogInfo("WarSaddle mesh scale: " + ((Object)val).name + "; lossy=" + ((object)((Component)val).transform.lossyScale/*cast due to .constrained prefix*/).ToString() + "; bakedWorldSpan=" + baked + "; visibleWorldSpan=" + num + "; useBaked=" + flag2);
				}
				if (flag2)
				{
					list.AddRange(list2);
				}
				else if (num > 0f && !float.IsInfinity(num) && !float.IsNaN(num))
				{
					for (int k = 0; k < 8; k++)
					{
						((Vector3)(ref val6))..ctor(((k & 1) == 0) ? ((Bounds)(ref bounds)).min.x : ((Bounds)(ref bounds)).max.x, ((k & 2) == 0) ? ((Bounds)(ref bounds)).min.y : ((Bounds)(ref bounds)).max.y, ((k & 4) == 0) ? ((Bounds)(ref bounds)).min.z : ((Bounds)(ref bounds)).max.z);
						list.Add(((Component)m).transform.InverseTransformPoint(val6));
					}
				}
			}
			finally
			{
				Object.Destroy((Object)(object)val2);
			}
		}
		return list;
	}

	private static float MaxAxis(Vector3 size)
	{
		//IL_0000: 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_000c: Unknown result type (might be due to invalid IL or missing references)
		return Mathf.Max(size.x, Mathf.Max(size.y, size.z));
	}

	private static float MeasureFlank(List<Vector3> points, Vector3 seat, float z, Bounds body, float band)
	{
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: 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_0044: 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_00a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_0064: Unknown result type (might be due to invalid IL or missing references)
		//IL_006a: Unknown result type (might be due to invalid IL or missing references)
		float num = 0f;
		foreach (Vector3 point in points)
		{
			if (Mathf.Abs(point.z - z) < band && point.y < seat.y + 0.1f && point.y > ((Bounds)(ref body)).min.y + ((Bounds)(ref body)).size.y * 0.3f)
			{
				num = Mathf.Max(num, Mathf.Abs(point.x - seat.x));
			}
		}
		return Mathf.Max(0.45f, (num > 0.2f) ? num : ((Bounds)(ref body)).extents.x);
	}

	private void AddLeatherGrain()
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: Expected O, but got Unknown
		//IL_007f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0084: 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)
		Texture2D val = new Texture2D(32, 32, (TextureFormat)4, false);
		((Object)val).name = "RHWS_LeatherGrain";
		((Texture)val).filterMode = (FilterMode)0;
		((Texture)val).wrapMode = (TextureWrapMode)0;
		owned.Add((Object)(object)val);
		Color[] array = (Color[])(object)new Color[1024];
		for (int i = 0; i < 32; i++)
		{
			for (int j = 0; j < 32; j++)
			{
				int num = ((j * 73 + i * 151) ^ (j * i * 19)) & 0x1F;
				float num2 = 0.8f + (float)num / 155f;
				array[i * 32 + j] = new Color(num2, num2, num2, 1f);
			}
		}
		val.SetPixels(array);
		val.Apply(false, true);
		Material[] array2 = (Material[])(object)new Material[2] { leather, strapLeather };
		foreach (Material val2 in array2)
		{
			string[] array3 = new string[3] { "_MainTex", "_BaseMap", "_BaseColorMap" };
			foreach (string text in array3)
			{
				if (val2.HasProperty(text))
				{
					val2.SetTexture(text, (Texture)(object)val);
					val2.SetTextureScale(text, new Vector2(3f, 3f));
				}
			}
		}
	}

	private static Bounds EstimateBody(List<Vector3> points, WarMount m)
	{
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: 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_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_007b: Unknown result type (might be due to invalid IL or missing references)
		if (points.Count == 0)
		{
			return new Bounds(new Vector3(0f, 1.4f, 0f), new Vector3(1.4f, 2.4f, 3f));
		}
		Bounds result = default(Bounds);
		((Bounds)(ref result))..ctor(points[0], Vector3.zero);
		foreach (Vector3 point in points)
		{
			((Bounds)(ref result)).Encapsulate(point);
		}
		return result;
	}

	private void BuildBags(Transform frame, float halfWidth, float length)
	{
		//IL_0012: 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_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0053: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_006a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0070: 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_0078: Unknown result type (might be due to invalid IL or missing references)
		//IL_0080: Unknown result type (might be due to invalid IL or missing references)
		//IL_008e: 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_00c6: 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_00e9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0119: Unknown result type (might be due to invalid IL or missing references)
		//IL_0124: Unknown result type (might be due to invalid IL or missing references)
		//IL_0135: Unknown result type (might be due to invalid IL or missing references)
		//IL_0140: 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_0159: Unknown result type (might be due to invalid IL or missing references)
		//IL_015f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0190: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_0200: Unknown result type (might be due to invalid IL or missing references)
		//IL_0217: Unknown result type (might be due to invalid IL or missing references)
		//IL_021c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0230: Unknown result type (might be due to invalid IL or missing references)
		//IL_0236: Unknown result type (might be due to invalid IL or missing references)
		//IL_024e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0265: Unknown result type (might be due to invalid IL or missing references)
		//IL_026a: Unknown result type (might be due to invalid IL or missing references)
		//IL_027e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0284: Unknown result type (might be due to invalid IL or missing references)
		//IL_02aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c0: 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_02d9: Unknown result type (might be due to invalid IL or missing references)
		//IL_02df: Unknown result type (might be due to invalid IL or missing references)
		Parts parts = new Parts(this, frame);
		Vector3 value = Plugin.Instance.BagOffset.Value;
		float value2 = Plugin.Instance.BagScale.Value;
		for (int i = -1; i <= 1; i += 2)
		{
			Vector3 val = new Vector3((float)i * (halfWidth + 0.06f + 0.19f * value2), -0.35f, (0f - length) * 0.48f) + value;
			Vector3 val2 = new Vector3(0.38f, 0.67f, 0.78f) * value2;
			parts.Add(Geometry.SoftBag(val2, i), val, leather);
			parts.Add(Geometry.BagRibbon(val2, i, strap: false, 0f), val, leather);
			for (int j = 0; j < 18; j++)
			{
				float num = (((float)j + 0.5f) / 18f - 0.5f) * val2.z * 0.76f;
				float num2 = val2.y * (0.045f + 0.1f * (float)Math.Pow(Math.Abs(num / (val2.z * 0.4f)), 3.0)) + 0.009f * value2;
				float num3 = Geometry.BagFront(val2, num2, num) + val2.x * 0.048f;
				parts.Box(val + new Vector3((float)i * num3, num2, num), new Vector3(0.003f, 0.003f, 0.012f) * value2, thread, 0.001f * value2);
			}
			for (int k = -1; k <= 1; k += 2)
			{
				float num4 = (float)k * val2.z * 0.25f;
				parts.Add(Geometry.BagRibbon(val2, i, strap: true, num4), val, strapLeather);
				float num5 = (0f - val2.y) * 0.08f;
				Vector3 val3 = val + new Vector3((float)i * (Geometry.BagFront(val2, num5, num4) + val2.x * 0.11f), num5, num4);
				for (int l = -1; l <= 1; l += 2)
				{
					parts.Box(val3 + new Vector3(0f, (float)l * 0.037f * value2, 0f), new Vector3(0.014f, 0.009f, 0.071f) * value2, metal, 0.003f * value2);
					parts.Box(val3 + new Vector3(0f, 0f, (float)l * 0.031f * value2), new Vector3(0.014f, 0.074f, 0.009f) * value2, metal, 0.003f * value2);
				}
				parts.Box(val3 + new Vector3((float)i * 0.006f * value2, 0f, 0f), new Vector3(0.01f, 0.009f, 0.057f) * value2, metal, 0.002f * value2);
			}
		}
		parts.Flush();
	}

	private void BuildHead(Transform frame, float size)
	{
		//IL_0012: 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_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0066: Unknown result type (might be due to invalid IL or missing references)
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0077: Unknown result type (might be due to invalid IL or missing references)
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
		//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_00f3: Unknown result type (might be due to invalid IL or missing references)
		//IL_010b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0123: Unknown result type (might be due to invalid IL or missing references)
		//IL_0128: Unknown result type (might be due to invalid IL or missing references)
		//IL_0142: Unknown result type (might be due to invalid IL or missing references)
		//IL_015a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0174: Unknown result type (might be due to invalid IL or missing references)
		//IL_0179: Unknown result type (might be due to invalid IL or missing references)
		//IL_0193: Unknown result type (might be due to invalid IL or missing references)
		Parts parts = new Parts(this, frame);
		Vector3 value = Plugin.Instance.HeadOffset.Value;
		Vector3 val = value + new Vector3(0f, size * 0.58f, size * 0.2f);
		parts.Box(val, new Vector3(size * 0.84f, size * 0.13f, size * 1.28f), metal, size * 0.12f);
		parts.Box(val + Vector3.up * size * 0.085f, new Vector3(size * 0.075f, size * 0.07f, size * 1.08f), trim, size * 0.025f);
		for (int i = -1; i <= 1; i += 2)
		{
			Vector3 val2 = value + new Vector3((float)i * size * 0.55f, (0f - size) * 0.22f, (0f - size) * 0.06f);
			parts.Box(val2, new Vector3(size * 0.1f, size * 0.35f, size * 0.55f), metal, size * 0.075f);
			parts.Box(val2 + new Vector3((float)i * size * 0.06f, size * 0.11f, 0f), new Vector3(size * 0.04f, size * 0.05f, size * 0.4f), trim, size * 0.012f);
			parts.Box(value + new Vector3((float)i * size * 0.43f, size * 0.33f, (0f - size) * 0.29f), new Vector3(size * 0.09f, size * 0.4f, size * 0.1f), leather, size * 0.025f);
		}
		parts.Flush();
	}

	internal void SetVisible(bool visible)
	{
		foreach (GameObject root in roots)
		{
			if ((Object)(object)root != (Object)null)
			{
				root.SetActive(visible);
			}
		}
	}

	public void Dispose()
	{
		foreach (GameObject root in roots)
		{
			if ((Object)(object)root != (Object)null)
			{
				Object.Destroy((Object)(object)root);
			}
		}
		foreach (Object item in owned)
		{
			if (item != (Object)null)
			{
				Object.Destroy(item);
			}
		}
		roots.Clear();
		owned.Clear();
	}
}
public sealed class BagMarker : MonoBehaviour
{
	internal WarMount Mount;
}
internal static class BagAccess
{
	internal static readonly FieldInfo InventoryField = AccessTools.Field(typeof(Container), "m_inventory");

	internal static readonly FieldInfo InventoryWidth = AccessTools.Field(typeof(Inventory), "m_width");

	internal static readonly FieldInfo CurrentContainer = AccessTools.Field(typeof(InventoryGui), "m_currentContainer");

	internal static WarMount For(Container c)
	{
		BagMarker bagMarker = (((Object)(object)c == (Object)null) ? null : ((Component)c).GetComponent<BagMarker>());
		if (!((Object)(object)bagMarker == (Object)null))
		{
			return bagMarker.Mount;
		}
		return null;
	}
}
public sealed class WarMount : MonoBehaviour
{
	internal const string ItemsKey = "RHWarSaddle.Items.v1";

	internal const string WidthKey = "RHWarSaddle.Columns.v1";

	internal const string HeightKey = "RHWarSaddle.Rows.v1";

	internal const string EnabledKey = "RHWarSaddle.Enabled.v1";

	internal ZNetView View;

	internal Tameable Tame;

	internal Character Character;

	internal Container Bag;

	internal bool Loaded;

	internal bool Failed;

	internal bool Dying;

	private int lastRequestedWidth = -1;

	private int lastRequestedHeight = -1;

	private uint lastRevision;

	private bool everLoaded;

	private float nextTick;

	private WarVisuals visuals;

	private bool conflictLogged;

	private bool deathPending;

	private int visualAttempts;

	private float nextVisualAttempt;

	private float nextDeathRetry;

	private static readonly MethodInfo DeathMethod = AccessTools.Method(typeof(Character), "OnDeath", (Type[])null, (Type[])null);

	private static readonly MethodInfo DropSaveMethod = AccessTools.Method(typeof(ItemDrop), "Save", (Type[])null, (Type[])null);

	private static readonly MethodInfo HaveSaddleMethod = AccessTools.Method(typeof(Tameable), "HaveSaddle", (Type[])null, (Type[])null);

	internal bool HasSaddle
	{
		get
		{
			if ((Object)(object)Tame != (Object)null)
			{
				return (bool)HaveSaddleMethod.Invoke(Tame, null);
			}
			return false;
		}
	}

	internal bool ResizePending
	{
		get
		{
			if ((Object)(object)Bag != (Object)null && Loaded && Plugin.Instance.Capacity.Ready)
			{
				if (Bag.GetInventory().GetWidth() == Plugin.Instance.Capacity.Width)
				{
					return Bag.GetInventory().GetHeight() != Plugin.Instance.Capacity.Height;
				}
				return true;
			}
			return false;
		}
	}

	private void Awake()
	{
		View = ((Component)this).GetComponent<ZNetView>();
		Tame = ((Component)this).GetComponent<Tameable>();
		Character = ((Component)this).GetComponent<Character>();
	}

	private void Update()
	{
		if ((Object)(object)View == (Object)null || !View.IsValid() || (Object)(object)Tame == (Object)null || Time.realtimeSinceStartup < nextTick)
		{
			return;
		}
		nextTick = Time.realtimeSinceStartup + 0.5f;
		if (deathPending && View.IsOwner() && Time.realtimeSinceStartup >= nextDeathRetry)
		{
			nextDeathRetry = Time.realtimeSinceStartup + 5f;
			DeathMethod.Invoke(Character, null);
			return;
		}
		bool savedItems = View.GetZDO().GetByteArray("RHWarSaddle.Items.v1", (byte[])null) != null;
		if ((Object)(object)Bag == (Object)null && Rules.ShouldCreate(Character.IsTamed(), HasSaddle, savedItems))
		{
			EnsureBag();
		}
		if ((Object)(object)Bag != (Object)null && !Bag.IsInUse())
		{
			Load(force: false);
		}
		bool flag = (Object)(object)Bag != (Object)null && Character.IsTamed() && HasSaddle && !Character.IsDead();
		if (flag && visuals == null && visualAttempts < 6 && Time.realtimeSinceStartup >= nextVisualAttempt && !ZNet.instance.IsDedicated())
		{
			try
			{
				visualAttempts++;
				visuals = new WarVisuals(this);
			}
			catch (Exception ex)
			{
				nextVisualAttempt = Time.realtimeSinceStartup + 5f;
				Plugin.Error("WarSaddle visual fitting failed (attempt " + visualAttempts + "/6): " + ex);
			}
		}
		if (visuals != null)
		{
			visuals.SetVisible(flag);
		}
	}

	private void EnsureBag()
	{
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: Expected O, but got Unknown
		//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)((Component)this).GetComponentInChildren<Container>(true) != (Object)null)
		{
			if (!conflictLogged)
			{
				Plugin.Error("WarSaddle skipped a moose that already has another Container. Disable the other mount-storage mod before testing.");
				conflictLogged = true;
			}
			return;
		}
		GameObject val = new GameObject("RHWarSaddle_Storage");
		val.SetActive(false);
		val.transform.SetParent(((Component)this).transform, false);
		val.AddComponent<BagMarker>().Mount = this;
		Bag = val.AddComponent<Container>();
		Bag.m_rootObjectOverride = View;
		Bag.m_name = "Jo-bags";
		Bag.m_width = 4;
		Bag.m_height = 4;
		Bag.m_privacy = (PrivacySetting)2;
		Bag.m_checkGuardStone = true;
		Bag.m_autoDestroyEmpty = false;
		val.SetActive(true);
		Load(force: true);
		if (View.IsOwner())
		{
			View.GetZDO().Set("RHWarSaddle.Enabled.v1", true);
		}
	}

	internal bool Load(bool force)
	{
		//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ee: Expected O, but got Unknown
		//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fd: Expected O, but got Unknown
		//IL_011b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0125: Expected O, but got Unknown
		if ((Object)(object)Bag == (Object)null || (Object)(object)View == (Object)null || !View.IsValid() || Bag.GetInventory() == null)
		{
			return false;
		}
		if (Bag.IsInUse() && !force)
		{
			return false;
		}
		ZDO zDO = View.GetZDO();
		CapacitySync capacity = Plugin.Instance.Capacity;
		bool flag = capacity.Ready && (lastRequestedWidth != capacity.Width || lastRequestedHeight != capacity.Height || (ResizePending && Bag.GetInventory().NrOfItems() == 0));
		if (!force && everLoaded && lastRevision == zDO.DataRevision && !flag)
		{
			return false;
		}
		byte[] byteArray = zDO.GetByteArray("RHWarSaddle.Items.v1", (byte[])null);
		try
		{
			Inventory val = new Inventory("Jo-bags", Bag.m_bkg, 8, 4);
			if (byteArray != null && byteArray.Length != 0)
			{
				ZPackage val2 = new ZPackage(byteArray);
				int num = ((val2.ReadInt() >= 108) ? val2.ReadUShort() : val2.ReadInt());
				val.Load(new ZPackage(byteArray));
				if (num != val.NrOfItems())
				{
					throw new InvalidOperationException("Some saved items could not load. Original saved bytes are retained.");
				}
			}
			int num2 = zDO.GetInt("RHWarSaddle.Columns.v1", 4);
			int num3 = zDO.GetInt("RHWarSaddle.Rows.v1", 4);
			if (!Rules.ValidSize(num2, num3))
			{
				throw new InvalidOperationException("Saved bag dimensions are outside the supported 8x4 area.");
			}
			HashSet<int> hashSet = new HashSet<int>();
			foreach (ItemData allItem in val.GetAllItems())
			{
				int x = allItem.m_gridPos.x;
				int y = allItem.m_gridPos.y;
				if (x < 0 || x >= 8 || y < 0 || y >= 4 || !hashSet.Add(y * 8 + x))
				{
					throw new InvalidOperationException("Saved items have invalid or overlapping positions. Original saved bytes are retained.");
				}
				num2 = Math.Max(num2, x + 1);
				num3 = Math.Max(num3, y + 1);
			}
			if (capacity.Ready && Rules.CanResize(num2, num3, capacity.Width, capacity.Height, val.NrOfItems()))
			{
				num2 = capacity.Width;
				num3 = capacity.Height;
			}
			BagAccess.InventoryWidth.SetValue(val, num2);
			val.SetHeight(num3);
			val.m_onChanged = Bag.GetInventory().m_onChanged;
			BagAccess.InventoryField.SetValue(Bag, val);
			Bag.m_width = num2;
			Bag.m_height = num3;
			lastRequestedWidth = (capacity.Ready ? capacity.Width : (-1));
			lastRequestedHeight = (capacity.Ready ? capacity.Height : (-1));
			Loaded = true;
			Failed = false;
			everLoaded = true;
			lastRevision = zDO.DataRevision;
			if (View.IsOwner() && (zDO.GetInt("RHWarSaddle.Columns.v1", 0) != num2 || zDO.GetInt("RHWarSaddle.Rows.v1", 0) != num3))
			{
				Save();
			}
			return true;
		}
		catch (Exception ex)
		{
			Loaded = false;
			if (!Failed)
			{
				Plugin.Error("WarSaddle inventory could not load; saved bytes retained, access blocked: " + ex);
			}
			Failed = true;
			return false;
		}
	}

	internal void Save()
	{
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Expected O, but got Unknown
		if (Loaded && !Failed && !((Object)(object)Bag == (Object)null) && View.IsValid() && View.IsOwner())
		{
			ZPackage val = new ZPackage();
			Bag.GetInventory().Save(val);
			View.GetZDO().Set("RHWarSaddle.Columns.v1", Bag.GetInventory().GetWidth());
			View.GetZDO().Set("RHWarSaddle.Rows.v1", Bag.GetInventory().GetHeight());
			View.GetZDO().Set("RHWarSaddle.Items.v1", val.GetArray());
			lastRevision = View.GetZDO().DataRevision;
		}
	}

	internal bool CanRemove()
	{
		if ((Object)(object)Bag == (Object)null)
		{
			if (!((Object)(object)View == (Object)null) && View.IsValid())
			{
				return View.GetZDO().GetByteArray("RHWarSaddle.Items.v1", (byte[])null) == null;
			}
			return true;
		}
		if (!Bag.IsInUse())
		{
			Load(force: false);
		}
		return Rules.CanRemove(Loaded && !Failed, Bag.GetInventory().NrOfItems(), Bag.IsInUse());
	}

	internal bool CanOpen()
	{
		if (Plugin.Instance.Capacity.Ready)
		{
			return Rules.CanOpen(Character.IsTamed(), HasSaddle, !Character.IsDead() && !Dying, Tame.HaveRider(), Loaded && !Failed);
		}
		return false;
	}

	internal void Open(Player player)
	{
		//IL_0077: Unknown result type (might be due to invalid IL or missing references)
		//IL_0082: Unknown result type (might be due to invalid IL or missing references)
		if (!Plugin.Instance.Capacity.Ready)
		{
			Plugin.Tell("Waiting for Jo-bags settings. Server and clients need the same War Saddle version.");
			return;
		}
		if ((Object)(object)Bag == (Object)null)
		{
			EnsureBag();
		}
		if ((Object)(object)Bag == (Object)null)
		{
			Plugin.Tell("Jo-bags are unavailable on this moose.");
			return;
		}
		if (!Bag.IsInUse())
		{
			Load(force: false);
		}
		if (!CanOpen())
		{
			Plugin.Tell("Use a living, tamed, saddled moose with nobody riding it.");
		}
		else if (Vector3.Distance(((Component)player).transform.position, Character.GetCenterPoint()) > 5f)
		{
			Plugin.Tell("Move closer to the moose.");
		}
		else
		{
			Bag.Interact((Humanoid)(object)player, false, false);
		}
	}

	internal bool PrepareDeath()
	{
		//IL_0101: Unknown result type (might be due to invalid IL or missing references)
		//IL_0108: Expected O, but got Unknown
		//IL_0126: Unknown result type (might be due to invalid IL or missing references)
		//IL_012b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0135: Unknown result type (might be due to invalid IL or missing references)
		//IL_013a: Unknown result type (might be due to invalid IL or missing references)
		//IL_013f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0149: Unknown result type (might be due to invalid IL or missing references)
		//IL_014e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0153: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)View == (Object)null || !View.IsValid() || !View.IsOwner())
		{
			return true;
		}
		Dying = true;
		deathPending = true;
		bool flag = View.GetZDO().GetByteArray("RHWarSaddle.Items.v1", (byte[])null) != null;
		if ((Object)(object)Bag == (Object)null && flag)
		{
			EnsureBag();
		}
		if ((Object)(object)Bag == (Object)null)
		{
			deathPending = flag;
			return !flag;
		}
		if (!Bag.IsInUse())
		{
			Load(force: false);
		}
		if (!Loaded || Failed)
		{
			return false;
		}
		if ((Object)(object)InventoryGui.instance != (Object)null && BagAccess.CurrentContainer.GetValue(InventoryGui.instance) == Bag)
		{
			InventoryGui.instance.Hide();
		}
		foreach (ItemData item in new List<ItemData>(Bag.GetInventory().GetAllItems()))
		{
			GameObject val = null;
			ZPackage val2 = new ZPackage();
			Bag.GetInventory().Save(val2);
			try
			{
				val = Object.Instantiate<GameObject>(item.m_dropPrefab, ((Component)this).transform.position + Vector3.up * 0.6f + Random.insideUnitSphere * 0.25f, Quaternion.identity);
				ItemDrop component = val.GetComponent<ItemDrop>();
				if ((Object)(object)component == (Object)null)
				{
					throw new InvalidOperationException("Drop prefab has no ItemDrop.");
				}
				component.m_itemData = item.Clone();
				if (item.m_quality > 1)
				{
					component.SetQuality(item.m_quality);
				}
				if (component.m_onDrop != null)
				{
					component.m_onDrop(component);
				}
				DropSaveMethod.Invoke(component, null);
				if (!Bag.GetInventory().RemoveItem(item))
				{
					throw new InvalidOperationException("Could not remove the dropped stack from storage.");
				}
				Save();
			}
			catch (Exception ex)
			{
				if ((Object)(object)val != (Object)null)
				{
					ZNetScene.instance.Destroy(val);
				}
				View.GetZDO().Set("RHWarSaddle.Items.v1", val2.GetArray());
				Load(force: true);
				Plugin.Error("WarSaddle death-drop interrupted; stack restored and cleanup will retry: " + ex);
				return false;
			}
		}
		Save();
		deathPending = false;
		return true;
	}

	private void OnDestroy()
	{
		if (visuals != null)
		{
			visuals.Dispose();
		}
	}
}
[HarmonyPatch(typeof(Container), "Save")]
internal static class SavePatch
{
	private static bool Prefix(Container __instance)
	{
		WarMount warMount = BagAccess.For(__instance);
		if ((Object)(object)warMount == (Object)null)
		{
			return true;
		}
		warMount.Save();
		return false;
	}
}
[HarmonyPatch(typeof(Container), "Load")]
internal static class LoadPatch
{
	private static bool Prefix(Container __instance, ref bool __result)
	{
		WarMount warMount = BagAccess.For(__instance);
		if ((Object)(object)warMount == (Object)null)
		{
			return true;
		}
		__result = warMount.Load(force: false);
		return false;
	}
}
[HarmonyPatch(typeof(Container), "RPC_RequestOpen")]
internal static class OpenPatch
{
	private static bool Prefix(Container __instance, long __0)
	{
		WarMount warMount = BagAccess.For(__instance);
		if ((Object)(object)warMount == (Object)null || !warMount.View.IsOwner())
		{
			return true;
		}
		if (!__instance.IsInUse())
		{
			warMount.Load(force: false);
		}
		if (warMount.CanOpen())
		{
			return true;
		}
		warMount.View.InvokeRPC(__0, "RPC_OpenResponse", new object[1] { false });
		return false;
	}
}
[HarmonyPatch(typeof(Container), "RPC_OpenResponse")]
internal static class OpenResponsePatch
{
	private static bool Prefix(Container __instance, bool __1)
	{
		WarMount warMount = BagAccess.For(__instance);
		if ((Object)(object)warMount == (Object)null || !__1)
		{
			return true;
		}
		warMount.Load(force: true);
		if (warMount.CanOpen())
		{
			return true;
		}
		Plugin.Tell("Jo-bags are no longer available.");
		return false;
	}
}
internal static class Geometry
{
	private static readonly float[] BagY = new float[8] { -0.5f, -0.46f, -0.36f, -0.16f, 0.1f, 0.31f, 0.43f, 0.49f };

	private static readonly float[] BagDepth = new float[8] { 0.4f, 0.67f, 0.89f, 1f, 1f, 0.89f, 0.7f, 0.48f };

	private static readonly float[] BagWidth = new float[8] { 0.68f, 0.88f, 0.97f, 1f, 0.98f, 0.91f, 0.82f, 0.73f };

	private static float SignedPower(double value, double power)
	{
		return (float)((double)Math.Sign(value) * Math.Pow(Math.Abs(value), power));
	}

	internal static Mesh SoftBag(Vector3 size, int side)
	{
		//IL_0046: 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_0080: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_015d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0170: Unknown result type (might be due to invalid IL or missing references)
		//IL_0185: Unknown result type (might be due to invalid IL or missing references)
		//IL_019d: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
		List<Vector3> list = new List<Vector3>();
		List<int> list2 = new List<int>();
		List<Vector2> list3 = new List<Vector2>();
		for (int i = 0; i < BagY.Length; i++)
		{
			for (int j = 0; j < 32; j++)
			{
				double num = (double)j * Math.PI * 2.0 / 32.0;
				list.Add(new Vector3(size.x * 0.5f * BagDepth[i] * SignedPower(Math.Cos(num), 0.65), size.y * BagY[i], size.z * 0.5f * BagWidth[i] * SignedPower(Math.Sin(num), 0.65)));
				list3.Add(new Vector2((float)j / 32f, BagY[i] + 0.5f));
			}
		}
		for (int k = 0; k < BagY.Length - 1; k++)
		{
			for (int l = 0; l < 32; l++)
			{
				int num2 = k * 32 + l;
				int num3 = k * 32 + (l + 1) % 32;
				IndexQuad(list2, num2, num2 + 32, num3 + 32, num3);
			}
		}
		int count = list.Count;
		list.Add(new Vector3(0f, size.y * BagY[0], 0f));
		list3.Add(new Vector2(0.5f, 0f));
		int count2 = list.Count;
		list.Add(new Vector3(0f, size.y * BagY[BagY.Length - 1], 0f));
		list3.Add(new Vector2(0.5f, 1f));
		for (int m = 0; m < 32; m++)
		{
			int num4 = (m + 1) % 32;
			int num5 = (BagY.Length - 1) * 32;
			list2.Add(count);
			list2.Add(m);
			list2.Add(num4);
			list2.Add(count2);
			list2.Add(num5 + num4);
			list2.Add(num5 + m);
		}
		return Smooth(list, list2, list3, side);
	}

	internal static float BagFront(Vector3 size, float y, float z)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a2: 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)
		float num = y / size.y;
		int i;
		for (i = 0; i < BagY.Length - 2 && num > BagY[i + 1]; i++)
		{
		}
		float num2 = Math.Max(0f, Math.Min(1f, (num - BagY[i]) / (BagY[i + 1] - BagY[i])));
		float num3 = BagDepth[i] + (BagDepth[i + 1] - BagDepth[i]) * num2;
		float num4 = BagWidth[i] + (BagWidth[i + 1] - BagWidth[i]) * num2;
		double x = Math.Min(0.999, (double)Math.Abs(z) / ((double)size.z * 0.5 * (double)num4));
		return size.x * 0.5f * num3 * (float)Math.Pow(1.0 - Math.Pow(x, 3.0769230769230766), 0.325);
	}

	internal static Mesh BagRibbon(Vector3 size, int side, bool strap, float zCenter)
	{
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_0128: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_0166: Unknown result type (might be due to invalid IL or missing references)
		//IL_0158: Unknown result type (might be due to invalid IL or missing references)
		//IL_0149: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
		//IL_019b: Unknown result type (might be due to invalid IL or missing references)
		int num = (strap ? 2 : 16);
		float[] array = ((!strap) ? new float[7] { 0.47f, 0.515f, 0.46f, 0.36f, 0.25f, 0.13f, 0.045f } : new float[10] { 0.47f, 0.515f, 0.46f, 0.36f, 0.25f, 0.13f, 0.01f, -0.12f, -0.24f, -0.34f });
		int num2 = array.Length;
		int num3 = num2 * (num + 1);
		float num4 = size.z * (strap ? 0.066f : 0.8f);
		float num5 = size.x * (strap ? 0.03f : 0.036f);
		List<Vector3> list = new List<Vector3>();
		List<Vector2> list2 = new List<Vector2>();
		List<int> t = new List<int>();
		for (int i = 0; i < 2; i++)
		{
			for (int j = 0; j < num2; j++)
			{
				for (int k = 0; k <= num; k++)
				{
					float num6 = (float)k / (float)num;
					float num7 = (strap ? 1f : ((j < 3) ? 0.82f : ((j == 3) ? 0.94f : 1f)));
					float num8 = zCenter + (num6 - 0.5f) * num4 * num7;
					float num9 = array[j] * size.y;
					if (!strap && j == num2 - 1)
					{
						num9 += size.y * 0.1f * (float)Math.Pow(Math.Abs(2f * num6 - 1f), 3.0);
					}
					float num10 = size.x * (strap ? 0.083f : 0.038f);
					float num11 = j switch
					{
						1 => size.x * 0.06f, 
						0 => (0f - size.x) * 0.24f, 
						_ => BagFront(size, num9, num8) + num10, 
					};
					if (i == 1)
					{
						if (j < 2)
						{
							num9 -= num5;
						}
						else
						{
							num11 -= num5;
						}
					}
					else if (strap && j < 2)
					{
						num9 += size.y * 0.016f;
					}
					list.Add(new Vector3(num11, num9, num8));
					list2.Add(new Vector2(num6, (float)j / (float)(num2 - 1)));
				}
			}
		}
		for (int l = 0; l < num2 - 1; l++)
		{
			for (int m = 0; m < num; m++)
			{
				int num12 = l * (num + 1) + m;
				int num13 = num12 + num + 1;
				IndexQuad(t, num12, num12 + 1, num13 + 1, num13);
				IndexQuad(t, num12 + num3, num13 + num3, num13 + num3 + 1, num12 + num3 + 1);
			}
		}
		for (int n = 0; n < num; n++)
		{
			IndexQuad(t, n, n + num3, n + num3 + 1, n + 1);
			int num14 = (num2 - 1) * (num + 1) + n;
			IndexQuad(t, num14, num14 + 1, num14 + num3 + 1, num14 + num3);
		}
		for (int num15 = 0; num15 < num2 - 1; num15++)
		{
			int num16 = num15 * (num + 1);
			int num17 = num16 + num + 1;
			IndexQuad(t, num16, num17, num17 + num3, num16 + num3);
			num16 += num;
			num17 += num;
			IndexQuad(t, num16, num16 + num3, num17 + num3, num17);
		}
		return Smooth(list, t, list2, side);
	}

	private static void IndexQuad(List<int> t, int a, int b, int c, int d)
	{
		t.Add(a);
		t.Add(b);
		t.Add(c);
		t.Add(a);
		t.Add(c);
		t.Add(d);
	}

	private static Mesh Smooth(List<Vector3> v, List<int> t, List<Vector2> uv, int side)
	{
		//IL_006a: Unknown result type (might be due to invalid IL or missing references)
		//IL_006f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0076: Unknown result type (might be due to invalid IL or missing references)
		//IL_007e: Unknown result type (might be due to invalid IL or missing references)
		//IL_008a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0097: Expected O, but got Unknown
		//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_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		if (side < 0)
		{
			for (int i = 0; i < v.Count; i++)
			{
				Vector3 val = v[i];
				val.x = 0f - val.x;
				v[i] = val;
			}
			for (int j = 0; j < t.Count; j += 3)
			{
				int value = t[j + 1];
				t[j + 1] = t[j + 2];
				t[j + 2] = value;
			}
		}
		Mesh val2 = new Mesh();
		val2.SetVertices(v);
		val2.SetTriangles(t, 0);
		val2.uv = uv.ToArray();
		val2.RecalculateNormals();
		val2.RecalculateBounds();
		return val2;
	}

	internal static Mesh BevelBox(Vector3 size, float bevel)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: 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_00e3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_013c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0147: Unknown result type (might be due to invalid IL or missing references)
		//IL_0152: Unknown result type (might be due to invalid IL or missing references)
		//IL_016b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0176: Unknown result type (might be due to invalid IL or missing references)
		//IL_0181: Unknown result type (might be due to invalid IL or missing references)
		float num = size.x * 0.5f;
		float num2 = size.y * 0.5f;
		float num3 = size.z * 0.5f;
		float num4 = Mathf.Min(bevel, Mathf.Min(num, Mathf.Min(num2, num3)) * 0.8f);
		List<Vector3> v = new List<Vector3>();
		List<int> list = new List<int>();
		float b = Mathf.Min(num4 * 0.35f, Mathf.Min(num - num4, num3 - num4) * 0.8f);
		Vector3[][] array = new Vector3[4][]
		{
			Ring(num - num4, num3 - num4, 0f - num2, b),
			Ring(num, num3, 0f - num2 + num4, num4),
			Ring(num, num3, num2 - num4, num4),
			Ring(num - num4, num3 - num4, num2, b)
		};
		for (int i = 0; i < 3; i++)
		{
			for (int j = 0; j < 8; j++)
			{
				int num5 = (j + 1) % 8;
				Quad(v, list, array[i][j], array[i][num5], array[i + 1][num5], array[i + 1][j]);
			}
		}
		for (int k = 0; k < 8; k++)
		{
			int num6 = (k + 1) % 8;
			Triangle(v, list, new Vector3(0f, 0f - num2, 0f), array[0][num6], array[0][k]);
			Triangle(v, list, new Vector3(0f, num2, 0f), array[3][k], array[3][num6]);
		}
		for (int l = 0; l < list.Count; l += 3)
		{
			int value = list[l + 1];
			list[l + 1] = list[l + 2];
			list[l + 2] = value;
		}
		return Make(v, list);
	}

	private static Vector3[] Ring(float x, float z, float y, float b)
	{
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: 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_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: 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_0055: Unknown result type (might be due to invalid IL or missing references)
		//IL_005a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_007e: Unknown result type (might be due to invalid IL or missing references)
		//IL_008c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0091: Unknown result type (might be due to invalid IL or missing references)
		return (Vector3[])(object)new Vector3[8]
		{
			new Vector3(0f - x + b, y, 0f - z),
			new Vector3(x - b, y, 0f - z),
			new Vector3(x, y, 0f - z + b),
			new Vector3(x, y, z - b),
			new Vector3(x - b, y, z),
			new Vector3(0f - x + b, y, z),
			new Vector3(0f - x, y, z - b),
			new Vector3(0f - x, y, 0f - z + b)
		};
	}

	internal static Mesh Breastplate(float width, float height, float curve)
	{
		//IL_007b: 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_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_0088: 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_008f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0091: Unknown result type (might be due to invalid IL or missing references)
		//IL_0097: 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_00a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d0: 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_00d9: 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_00e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_0101: Unknown result type (might be due to invalid IL or missing references)
		//IL_010d: Unknown result type (might be due to invalid IL or missing references)
		//IL_010f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0111: Unknown result type (might be due to invalid IL or missing references)
		//IL_0116: Unknown result type (might be due to invalid IL or missing references)
		//IL_0118: 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_0121: Unknown result type (might be due to invalid IL or missing references)
		//IL_012d: Unknown result type (might be due to invalid IL or missing references)
		//IL_012f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0131: Unknown result type (might be due to invalid IL or missing references)
		//IL_0136: Unknown result type (might be due to invalid IL or missing references)
		//IL_0138: Unknown result type (might be due to invalid IL or missing references)
		//IL_013a: Unknown result type (might be due to invalid IL or missing references)
		//IL_013f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0141: Unknown result type (might be due to invalid IL or missing references)
		//IL_014e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0150: Unknown result type (might be due to invalid IL or missing references)
		//IL_0152: Unknown result type (might be due to invalid IL or missing references)
		//IL_0154: Unknown result type (might be due to invalid IL or missing references)
		//IL_0156: Unknown result type (might be due to invalid IL or missing references)
		//IL_015b: Unknown result type (might be due to invalid IL or missing references)
		//IL_015d: Unknown result type (might be due to invalid IL or missing references)
		//IL_015f: Unknown result type (might be due to invalid IL or missing references)
		List<Vector3> v = new List<Vector3>();
		List<int> t = new List<int>();
		Vector3 val = default(Vector3);
		Vector3 val2 = default(Vector3);
		for (int i = 0; i < 8; i++)
		{
			float num = -1f + (float)i / 4f;
			float num2 = -1f + (float)(i + 1) / 4f;
			((Vector3)(ref val))..ctor(num * width * 0.5f, height * 0.5f, curve * (1f - num * num));
			((Vector3)(ref val2))..ctor(num2 * width * 0.5f, height * 0.5f, curve * (1f - num2 * num2));
			Vector3 val3 = val2 + Vector3.down * height;
			Vector3 val4 = val + Vector3.down * height;
			Quad(v, t, val, val4, val3, val2);
			Vector3 val5 = Vector3.back * 0.04f;
			Quad(v, t, val2 + val5, val3 + val5, val4 + val5, val + val5);
			Quad(v, t, val, val2, val2 + val5, val + val5);
			Quad(v, t, val4 + val5, val3 + val5, val3, val4);
			if (i == 0)
			{
				Quad(v, t, val + val5, val4 + val5, val4, val);
			}
			if (i == 7)
			{
				Quad(v, t, val2, val3, val3 + val5, val2 + val5);
			}
		}
		return Make(v, t);
	}

	private static void Quad(List<Vector3> v, List<int> t, Vector3 a, Vector3 b, Vector3 c, Vector3 d)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0003: Unknown result type (might be due to invalid IL or missing references)
		//IL_0004: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: 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_0010: Unknown result type (might be due to invalid IL or missing references)
		Triangle(v, t, a, b, c);
		Triangle(v, t, a, c, d);
	}

	private static void Triangle(List<Vector3> v, List<int> t, Vector3 a, Vector3 b, Vector3 c)
	{
		//IL_0008: 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_0016: Unknown result type (might be due to invalid IL or missing references)
		int count = v.Count;
		v.Add(a);
		v.Add(b);
		v.Add(c);
		t.Add(count);
		t.Add(count + 1);
		t.Add(count + 2);
	}

	private static Mesh Make(List<Vector3> v, List<int> t)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Expected O, but got Unknown
		//IL_0029: 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_003f: 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)
		Mesh val = new Mesh();
		val.SetVertices(v);
		val.SetTriangles(t, 0);
		Vector2[] array = (Vector2[])(object)new Vector2[v.Count];
		for (int i = 0; i < array.Length; i++)
		{
			array[i] = new Vector2(v[i].x, v[i].z);
		}
		val.uv = array;
		val.RecalculateNormals();
		val.RecalculateBounds();
		return val;
	}
}
[HarmonyPatch(typeof(InventoryGrid), "UpdateInventory")]
internal static class BagGridPatch
{
	private static readonly FieldInfo Elements = AccessTools.Field(typeof(InventoryGrid), "m_elements");

	private static readonly FieldInfo Width = AccessTools.Field(typeof(InventoryGrid), "m_width");

	private static readonly FieldInfo Height = AccessTools.Field(typeof(InventoryGrid), "m_height");

	private static readonly FieldInfo FirstUpdate = AccessTools.Field(typeof(InventoryGui), "m_firstContainerUpdate");

	private static void Prefix(InventoryGrid __instance, Inventory __0)
	{
		InventoryGui instance = InventoryGui.instance;
		if ((Object)(object)instance == (Object)null || __0 == null || __instance != instance.ContainerGrid)
		{
			return;
		}
		object? value = BagAccess.CurrentContainer.GetValue(instance);
		Container val = (Container)((value is Container) ? value : null);
		if ((Object)(object)BagAccess.For(val) == (Object)null || __0 != val.GetInventory() || !(Elements.GetValue(__instance) is IList list))
		{
			return;
		}
		int cachedWidth = (int)Width.GetValue(__instance);
		int cachedHeight = (int)Height.GetValue(__instance);
		if (Rules.NeedsGridRebuild(__0.GetWidth(), __0.GetHeight(), list.Count, cachedWidth, cachedHeight))
		{
			Width.SetValue(__instance, -1);
			Height.SetValue(__instance, -1);
			FirstUpdate.SetValue(instance, true);
			if (Plugin.Instance.Diagnostics.Value)
			{
				Plugin.LogInfo("WarSaddle grid: rebuilding " + __0.GetWidth() + "x" + __0.GetHeight() + " cells (previous count=" + list.Count + ").");
			}
		}
	}
}
internal sealed class CapacitySync : IDisposable
{
	private const string RpcName = "RHWarSaddle_Capacity_v1";

	private readonly int localWidth;

	private readonly int localHeight;

	private readonly HashSet<ZRpc> registered = new HashSet<ZRpc>();

	private ZNet session;

	private ZRpc serverRpc;

	private int remoteWidth;

	private int remoteHeight;

	private bool received;

	private float nextTick;

	private float nextHello;

	internal bool Ready
	{
		get
		{
			if ((Object)(object)ZNet.instance != (Object)null)
			{
				if (!ZNet.instance.IsServer())
				{
					if (session == ZNet.instance && received && serverRpc != null)
					{
						return serverRpc.IsConnected();
					}
					return false;
				}
				return true;
			}
			return false;
		}
	}

	internal int Width
	{
		get
		{
			if (!((Object)(object)ZNet.instance != (Object)null) || !ZNet.instance.IsServer())
			{
				if (!received)
				{
					return 4;
				}
				return remoteWidth;
			}
			return localWidth;
		}
	}

	internal int Height
	{
		get
		{
			if (!((Object)(object)ZNet.instance != (Object)null) || !ZNet.instance.IsServer())
			{
				if (!received)
				{
					return 4;
				}
				return remoteHeight;
			}
			return localHeight;
		}
	}

	internal CapacitySync(ConfigFile config)
	{
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Expected O, but got Unknown
		//IL_0061: Unknown result type (might be due to invalid IL or missing references)
		//IL_006b: Expected O, but got Unknown
		localWidth = config.Bind<int>("Storage", "Columns", 4, new ConfigDescription("Server setting: saddlebag columns, 1-8. Restart to apply. A reduction waits until bags are emptied and closed.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 8), Array.Empty<object>())).Value;
		localHeight = config.Bind<int>("Storage", "Rows", 4, new ConfigDescription("Server setting: saddlebag rows, 1-4. Maximum 32 slots (8x4). Restart to apply. A reduction waits until bags are emptied and closed.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 4), Array.Empty<object>())).Value;
	}

	private void Reset()
	{
		foreach (ZRpc item in registered)
		{
			item.Unregister("RHWarSaddle_Capacity_v1");
		}
		registered.Clear();
		session = ZNet.instance;
		serverRpc = null;
		received = false;
		nextTick = (nextHello = 0f);
	}

	internal void Register(ZNetPeer peer)
	{
		if (session != ZNet.instance)
		{
			Reset();
		}
		if (peer != null && peer.m_rpc != null && registered.Add(peer.m_rpc))
		{
			peer.m_rpc.Register<string>("RHWarSaddle_Capacity_v1", (Action<ZRpc, string>)Message);
		}
	}

	internal void Tick()
	{
		if (session != ZNet.instance)
		{
			Reset();
		}
		if ((Object)(object)session == (Object)null || Time.realtimeSinceStartup < nextTick)
		{
			return;
		}
		nextTick = Time.realtimeSinceStartup + 0.5f;
		HashSet<ZRpc> hashSet = new HashSet<ZRpc>();
		foreach (ZNetPeer peer in session.GetPeers())
		{
			Register(peer);
			if (peer.m_rpc != null)
			{
				hashSet.Add(peer.m_rpc);
			}
		}
		foreach (ZRpc item in new List<ZRpc>(registered))
		{
			if (!hashSet.Contains(item))
			{
				item.Unregister("RHWarSaddle_Capacity_v1");
				registered.Remove(item);
			}
		}
		if (!session.IsServer())
		{
			ZRpc val = session.GetServerPeer()?.m_rpc;
			if (val != serverRpc)
			{
				serverRpc = val;
				received = false;
				nextHello = 0f;
			}
			if (serverRpc != null && serverRpc.IsConnected() && !received && Time.realtimeSinceStartup >= nextHello)
			{
				nextHello = Time.realtimeSinceStartup + 5f;
				serverRpc.Invoke("RHWarSaddle_Capacity_v1", new object[1] { "H|1" });
			}
		}
	}

	private void Message(ZRpc rpc, string value)
	{
		ZNet instance = ZNet.instance;
		if ((Object)(object)instance == (Object)null || value == null || value.Length > 40)
		{
			return;
		}
		if (instance.IsServer())
		{
			if (value != "H|1")
			{
				return;
			}
			{
				foreach (ZNetPeer peer in instance.GetPeers())
				{
					if (peer.m_rpc == rpc && rpc.IsConnected())
					{
						object[] array = new object[1];
						int num = localWidth;
						string text = num.ToString();
						num = localHeight;
						array[0] = "S|1|" + text + "|" + num;
						rpc.Invoke("RHWarSaddle_Capacity_v1", array);
						break;
					}
				}
				return;
			}
		}
		ZNetPeer serverPeer = instance.GetServerPeer();
		if (serverPeer != null && serverPeer.m_rpc == rpc && Rules.TryCapacityMessage(value, out var width, out var height))
		{
			serverRpc = rpc;
			remoteWidth = width;
			remoteHeight = height;
			received = true;
			Plugin.LogInfo("WarSaddle server capacity: " + width + "x" + height + " (" + width * height + " slots).");
		}
	}

	public void Dispose()
	{
		Reset();
	}
}