Decompiled source of BeastRoads v0.1.0

plugins/BeastRoads/BeastRoads.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using TMPro;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace BeastRoads;

internal class Kind
{
	internal string Prefab;

	internal string Name;

	internal string Trophy;

	internal int Slots;

	internal float Pull;
}
internal static class Beasts
{
	internal const float MinTravelSeconds = 20f;

	private static readonly Kind[] Kinds = new Kind[3]
	{
		new Kind
		{
			Prefab = "Lox",
			Name = "Lox",
			Trophy = "TrophyLox",
			Slots = 0,
			Pull = 4f
		},
		new Kind
		{
			Prefab = "Bjorn",
			Name = "Bear",
			Trophy = "TrophyBjorn",
			Slots = 9,
			Pull = 3.2f
		},
		new Kind
		{
			Prefab = "Asksvin",
			Name = "Asksvin",
			Trophy = "TrophyAsksvin",
			Slots = 13,
			Pull = 5f
		}
	};

	internal static readonly int IdKey = StringExtensionMethods.GetStableHashCode("BeastRoads_id");

	internal static readonly int CartKey = StringExtensionMethods.GetStableHashCode("BeastRoads_cart");

	internal static readonly int SignKey = StringExtensionMethods.GetStableHashCode("BeastRoads_sign");

	internal static readonly int SignNameKey = StringExtensionMethods.GetStableHashCode("BeastRoads_signName");

	internal static readonly int OwnerKey = StringExtensionMethods.GetStableHashCode("BeastRoads_owner");

	internal static readonly int OwnerNameKey = StringExtensionMethods.GetStableHashCode("BeastRoads_ownerName");

	private static readonly Dictionary<long, Character> _byId = new Dictionary<long, Character>();

	private static float _next;

	internal static Kind KindOf(string prefab)
	{
		Kind[] kinds = Kinds;
		foreach (Kind kind in kinds)
		{
			if (kind.Prefab == prefab)
			{
				return kind;
			}
		}
		return null;
	}

	internal static Kind KindOf(Character c)
	{
		if ((Object)(object)c == (Object)null || c.IsPlayer())
		{
			return null;
		}
		return KindOf(Utils.GetPrefabName(((Component)c).gameObject));
	}

	internal static bool CanPull(Character c)
	{
		if ((Object)(object)c != (Object)null && !c.IsDead() && c.IsTamed())
		{
			return KindOf(c) != null;
		}
		return false;
	}

	internal static long NewId()
	{
		long num = Random.Range(1, int.MaxValue);
		long num2 = DateTime.UtcNow.Ticks & 0x7FFFFFFF;
		long num3 = (num << 31) ^ num2;
		if (num3 != 0)
		{
			return num3;
		}
		return 1L;
	}

	internal static long Id(Character c)
	{
		ZDO val = BK.Zdo((Component)(object)c);
		if (val == null)
		{
			return 0L;
		}
		return val.GetLong(IdKey, 0L);
	}

	internal static long EnsureId(Character c)
	{
		ZNetView val = BK.View((Component)(object)c);
		if ((Object)(object)val == (Object)null || !val.IsValid())
		{
			return 0L;
		}
		long num = val.GetZDO().GetLong(IdKey, 0L);
		if (num != 0)
		{
			return num;
		}
		if (!val.IsOwner())
		{
			val.ClaimOwnership();
		}
		num = NewId();
		val.GetZDO().Set(IdKey, num);
		return num;
	}

	internal static string Name(Character c)
	{
		if ((Object)(object)c == (Object)null)
		{
			return "it";
		}
		string hoverName = c.GetHoverName();
		if (!string.IsNullOrEmpty(hoverName))
		{
			return hoverName;
		}
		return "it";
	}

	internal static Sprite Icon(string prefab)
	{
		Kind kind = KindOf(prefab);
		if (kind == null || (Object)(object)ObjectDB.instance == (Object)null)
		{
			return null;
		}
		GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(kind.Trophy);
		if ((Object)(object)itemPrefab == (Object)null)
		{
			return null;
		}
		ItemDrop component = itemPrefab.GetComponent<ItemDrop>();
		Sprite[] array = (((Object)(object)component != (Object)null) ? component.m_itemData.m_shared.m_icons : null);
		if (array == null || array.Length <= 0)
		{
			return null;
		}
		return array[0];
	}

	internal static Character Find(long id)
	{
		if (id == 0)
		{
			return null;
		}
		Refresh();
		if (_byId.TryGetValue(id, out var value) && (Object)(object)value != (Object)null && !value.IsDead())
		{
			return value;
		}
		return null;
	}

	internal static void Refresh()
	{
		if (Time.time < _next)
		{
			return;
		}
		_next = Time.time + 0.25f;
		_byId.Clear();
		foreach (Character allCharacter in Character.GetAllCharacters())
		{
			if ((Object)(object)allCharacter == (Object)null || allCharacter.IsPlayer())
			{
				continue;
			}
			ZDO val = BK.Zdo((Component)(object)allCharacter);
			if (val != null)
			{
				long num = val.GetLong(IdKey, 0L);
				if (num != 0)
				{
					_byId[num] = allCharacter;
				}
			}
		}
	}

	internal static void Forget()
	{
		_next = 0f;
	}
}
internal static class BK
{
	internal static readonly int LeashKey = StringExtensionMethods.GetStableHashCode("Beastkeeper_leash");

	internal static readonly int RiderKey = StringExtensionMethods.GetStableHashCode("Beastkeeper_rider");

	internal static readonly int HomeKey = StringExtensionMethods.GetStableHashCode("Beastkeeper_home");

	internal static readonly int TieKey = StringExtensionMethods.GetStableHashCode("Beastkeeper_tie");

	private static MethodInfo _release;

	private static MethodInfo _catch;

	private static MethodInfo _equipped;

	private static MethodInfo _material;

	private static object _lassoSet;

	internal static void Init()
	{
		Type type = AccessTools.TypeByName("Beastkeeper.Leash");
		Type type2 = AccessTools.TypeByName("Beastkeeper.Lasso");
		Type type3 = AccessTools.TypeByName("Beastkeeper.Rope");
		if (type != null)
		{
			_release = AccessTools.Method(type, "Release", new Type[2]
			{
				typeof(Character),
				typeof(bool)
			}, (Type[])null);
			_catch = AccessTools.Method(type, "CatchTamed", new Type[2]
			{
				typeof(Character),
				typeof(Player)
			}, (Type[])null);
		}
		if (type2 != null)
		{
			FieldInfo fieldInfo = AccessTools.Field(type2, "Set");
			_lassoSet = ((fieldInfo != null) ? fieldInfo.GetValue(null) : null);
			if (_lassoSet != null)
			{
				_equipped = AccessTools.Method(_lassoSet.GetType(), "Equipped", new Type[1] { typeof(Player) }, (Type[])null);
			}
		}
		if (type3 != null)
		{
			_material = AccessTools.Method(type3, "Material", (Type[])null, (Type[])null);
		}
		if (_release == null || _catch == null || _equipped == null)
		{
			Plugin.Log.LogWarning((object)"Beastkeeper was found, but not all of it: hitching may not work. Is Beastkeeper up to date?");
		}
	}

	internal static ZDO Zdo(Component c)
	{
		if ((Object)(object)c == (Object)null)
		{
			return null;
		}
		ZNetView component = c.GetComponent<ZNetView>();
		if (!((Object)(object)component != (Object)null) || !component.IsValid())
		{
			return null;
		}
		return component.GetZDO();
	}

	internal static ZNetView View(Component c)
	{
		if (!((Object)(object)c != (Object)null))
		{
			return null;
		}
		return c.GetComponent<ZNetView>();
	}

	internal static long Holder(Character c)
	{
		ZDO val = Zdo((Component)(object)c);
		if (val == null)
		{
			return 0L;
		}
		return val.GetLong(LeashKey, 0L);
	}

	internal static long Rider(Character c)
	{
		ZDO val = Zdo((Component)(object)c);
		if (val == null)
		{
			return 0L;
		}
		return val.GetLong(RiderKey, 0L);
	}

	internal static bool Ridden(Character c)
	{
		return Rider(c) != 0;
	}

	internal static bool RiddenBy(Character c, Player p)
	{
		if ((Object)(object)p != (Object)null)
		{
			return Rider(c) == p.GetPlayerID();
		}
		return false;
	}

	internal static bool Tied(Character c)
	{
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		ZDO val = Zdo((Component)(object)c);
		if (val != null)
		{
			return val.GetVec3(TieKey, Vector3.zero) != Vector3.zero;
		}
		return false;
	}

	internal static bool LassoInHand(Player p)
	{
		if ((Object)(object)p == (Object)null)
		{
			return false;
		}
		if (_equipped != null && _lassoSet != null)
		{
			try
			{
				object obj = _equipped.Invoke(_lassoSet, new object[1] { p });
				if (obj is int)
				{
					return (int)obj > 0;
				}
			}
			catch (Exception ex)
			{
				Plugin.Debug("[bk] lasso check failed: " + ex.Message);
			}
		}
		if (((Humanoid)p).GetInventory() == null)
		{
			return false;
		}
		foreach (ItemData equippedItem in ((Humanoid)p).GetInventory().GetEquippedItems())
		{
			if (IsLasso(equippedItem))
			{
				return true;
			}
		}
		return false;
	}

	private static bool IsLasso(ItemData item)
	{
		if (item != null && (Object)(object)item.m_dropPrefab != (Object)null)
		{
			return ((Object)item.m_dropPrefab).name.StartsWith("Beastkeeper_Lasso");
		}
		return false;
	}

	internal static void LetGo(Character c)
	{
		if (_release != null)
		{
			_release.Invoke(null, new object[2] { c, true });
			return;
		}
		ZDO val = Zdo((Component)(object)c);
		if (val != null)
		{
			val.Set(LeashKey, 0L);
		}
	}

	internal static void OnRope(Character c, Player p)
	{
		if (_catch != null)
		{
			_catch.Invoke(null, new object[2] { c, p });
		}
	}

	internal static Material RopeMaterial()
	{
		if (_material != null)
		{
			object? obj = _material.Invoke(null, null);
			Material val = (Material)((obj is Material) ? obj : null);
			if ((Object)(object)val != (Object)null)
			{
				return val;
			}
		}
		return null;
	}
}
[HarmonyPatch]
internal static class CartLoad
{
	private class Cap
	{
		internal int Limit;

		internal string Who;
	}

	private const string Mark = "BeastRoads_blocked";

	private static Dictionary<Inventory, Cap> _caps = new Dictionary<Inventory, Cap>();

	private static Dictionary<Inventory, Cap> _next = new Dictionary<Inventory, Cap>();

	private static float _toldAt;

	private static readonly Color Shade = new Color(0f, 0f, 0f, 0.6f);

	private static readonly Color Cross = new Color(0.8f, 0.12f, 0.08f, 0.9f);

	private static readonly HashSet<InventoryGrid> _shown = new HashSet<InventoryGrid>();

	internal static void Begin()
	{
		_next.Clear();
	}

	internal static void Add(Inventory inv, int limit, string who)
	{
		if (inv != null && limit < inv.GetWidth() * inv.GetHeight())
		{
			_next[inv] = new Cap
			{
				Limit = limit,
				Who = who
			};
		}
	}

	internal static void End()
	{
		Dictionary<Inventory, Cap> caps = _caps;
		_caps = _next;
		_next = caps;
	}

	private static Cap CapOf(Inventory inv)
	{
		if (_caps.Count == 0 || inv == null || !_caps.TryGetValue(inv, out var value))
		{
			return null;
		}
		return value;
	}

	private static bool Open(Inventory inv, Cap cap, int x, int y)
	{
		return y * inv.GetWidth() + x < cap.Limit;
	}

	private static bool Full(Inventory inv, Cap cap)
	{
		return inv.GetAllItems().Count >= cap.Limit;
	}

	private static int OpenFree(Inventory inv, Cap cap)
	{
		int num = 0;
		int width = inv.GetWidth();
		int height = inv.GetHeight();
		for (int i = 0; i < cap.Limit && i < width * height; i++)
		{
			if (inv.GetItemAt(i % width, i / width) == null)
			{
				num++;
			}
		}
		return num;
	}

	private static Vector2i FirstOpen(Inventory inv, Cap cap)
	{
		//IL_0041: 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)
		int width = inv.GetWidth();
		int height = inv.GetHeight();
		for (int i = 0; i < cap.Limit && i < width * height; i++)
		{
			if (inv.GetItemAt(i % width, i / width) == null)
			{
				return new Vector2i(i % width, i / width);
			}
		}
		return new Vector2i(-1, -1);
	}

	private static void Tell(Cap cap)
	{
		if (!(Time.time - _toldAt < 2f))
		{
			_toldAt = Time.time;
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer != (Object)null && InventoryGui.IsVisible())
			{
				((Character)localPlayer).Message((MessageType)2, cap.Who + " pulls only the first " + cap.Limit + " slots of this cart", 0, (Sprite)null, false);
			}
		}
	}

	[HarmonyPatch(typeof(Inventory), "FindEmptySlot")]
	[HarmonyPostfix]
	private static void NoSlot(Inventory __instance, ref Vector2i __result)
	{
		//IL_0048: 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_004d: Unknown result type (might be due to invalid IL or missing references)
		if (__result.x < 0)
		{
			return;
		}
		Cap cap = CapOf(__instance);
		if (cap != null && (!Open(__instance, cap, __result.x, __result.y) || Full(__instance, cap)))
		{
			__result = (Vector2i)(Full(__instance, cap) ? new Vector2i(-1, -1) : FirstOpen(__instance, cap));
			if (__result.x < 0)
			{
				Tell(cap);
			}
		}
	}

	[HarmonyPatch(typeof(Inventory), "HaveEmptySlot")]
	[HarmonyPostfix]
	private static void NoEmpty(Inventory __instance, ref bool __result)
	{
		Cap cap = CapOf(__instance);
		if (__result && cap != null)
		{
			__result = !Full(__instance, cap) && OpenFree(__instance, cap) > 0;
		}
	}

	[HarmonyPatch(typeof(Inventory), "GetEmptySlots")]
	[HarmonyPostfix]
	private static void FewerEmpty(Inventory __instance, ref int __result)
	{
		Cap cap = CapOf(__instance);
		if (cap != null)
		{
			__result = Mathf.Max(0, Mathf.Min(__result, Mathf.Min(cap.Limit - __instance.GetAllItems().Count, OpenFree(__instance, cap))));
		}
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(Inventory), "AddItem", new Type[]
	{
		typeof(ItemData),
		typeof(int),
		typeof(int),
		typeof(int),
		typeof(bool)
	})]
	private static bool AtSlot(Inventory __instance, ItemData item, int x, int y, ref bool __result)
	{
		if (!Blocked(__instance, item, x, y))
		{
			return true;
		}
		__result = false;
		return false;
	}

	[HarmonyPatch(typeof(Inventory), "AddItem", new Type[]
	{
		typeof(ItemData),
		typeof(Vector2i)
	})]
	[HarmonyPrefix]
	private static bool AtPos(Inventory __instance, ItemData item, Vector2i pos, ref bool __result)
	{
		if (!Blocked(__instance, item, pos.x, pos.y))
		{
			return true;
		}
		__result = false;
		return false;
	}

	private static bool Blocked(Inventory inv, ItemData item, int x, int y)
	{
		Cap cap = CapOf(inv);
		if (cap == null || item == null)
		{
			return false;
		}
		if (inv.GetItemAt(x, y) != null)
		{
			return false;
		}
		bool flag = inv.ContainsItem(item);
		if (Open(inv, cap, x, y) && (flag || !Full(inv, cap)))
		{
			return false;
		}
		Tell(cap);
		return true;
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(InventoryGrid), "UpdateGui")]
	private static void ShowBlocked(InventoryGrid __instance, Inventory ___m_inventory, List<InventoryElement> ___m_elements)
	{
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		if (___m_elements == null || ___m_inventory == null)
		{
			return;
		}
		Cap cap = CapOf(___m_inventory);
		if (cap == null && !Shown(__instance))
		{
			return;
		}
		for (int i = 0; i < ___m_elements.Count; i++)
		{
			InventoryElement val = ___m_elements[i];
			if ((Object)(object)val == (Object)null)
			{
				continue;
			}
			Vector2i position = val.Position;
			bool flag = cap != null && !Open(___m_inventory, cap, position.x, position.y);
			Transform val2 = ((Component)val).transform.Find("BeastRoads_blocked");
			if (!flag)
			{
				if ((Object)(object)val2 != (Object)null && ((Component)val2).gameObject.activeSelf)
				{
					((Component)val2).gameObject.SetActive(false);
				}
				continue;
			}
			if ((Object)(object)val2 == (Object)null)
			{
				val2 = NewMark(val).transform;
			}
			if (!((Component)val2).gameObject.activeSelf)
			{
				((Component)val2).gameObject.SetActive(true);
			}
			val2.SetAsLastSibling();
		}
		Shown(__instance, cap != null);
	}

	private static bool Shown(InventoryGrid g)
	{
		return _shown.Contains(g);
	}

	private static void Shown(InventoryGrid g, bool on)
	{
		if (on)
		{
			_shown.Add(g);
		}
		else
		{
			_shown.Remove(g);
		}
	}

	private static GameObject NewMark(InventoryElement e)
	{
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Expected O, but got Unknown
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Expected O, but got Unknown
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Unknown result type (might be due to invalid IL or missing references)
		//IL_0084: 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_00b7: 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_00c6: Unknown result type (might be due to invalid IL or missing references)
		GameObject val = new GameObject("BeastRoads_blocked", new Type[1] { typeof(RectTransform) });
		RectTransform val2 = (RectTransform)val.transform;
		((Transform)val2).SetParent(((Component)e).transform, false);
		val2.anchorMin = Vector2.zero;
		val2.anchorMax = Vector2.one;
		val2.offsetMin = new Vector2(2f, 2f);
		val2.offsetMax = new Vector2(-2f, -2f);
		Image val3 = val.AddComponent<Image>();
		((Graphic)val3).color = Shade;
		((Graphic)val3).raycastTarget = false;
		Transform transform = ((Component)e).transform;
		RectTransform val4 = (RectTransform)(object)((transform is RectTransform) ? transform : null);
		float num;
		if (!((Object)(object)val4 != (Object)null))
		{
			num = 64f;
		}
		else
		{
			Rect rect = val4.rect;
			float width = ((Rect)(ref rect)).width;
			Rect rect2 = val4.rect;
			num = Mathf.Min(width, ((Rect)(ref rect2)).height);
		}
		float num2 = num;
		if (num2 < 8f)
		{
			num2 = 64f;
		}
		Bar(val2, num2 * 0.8f, 45f);
		Bar(val2, num2 * 0.8f, -45f);
		return val;
	}

	private static void Bar(RectTransform parent, float length, float angle)
	{
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Expected O, but got Unknown
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Expected O, but got Unknown
		//IL_0040: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		//IL_004d: 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_007d: 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)
		GameObject val = new GameObject("x", new Type[1] { typeof(RectTransform) });
		RectTransform val2 = (RectTransform)val.transform;
		((Transform)val2).SetParent((Transform)(object)parent, false);
		Vector2 anchorMin = (val2.anchorMax = new Vector2(0.5f, 0.5f));
		val2.anchorMin = anchorMin;
		val2.sizeDelta = new Vector2(length, Mathf.Max(3f, length * 0.07f));
		((Transform)val2).localRotation = Quaternion.Euler(0f, 0f, angle);
		Image val4 = val.AddComponent<Image>();
		((Graphic)val4).color = Cross;
		((Graphic)val4).raycastTarget = false;
	}
}
internal class Delivery : MonoBehaviour
{
	internal static readonly List<Delivery> All = new List<Delivery>();

	private ZNetView _nv;

	internal ZNetView View => _nv;

	internal ZDO Zdo
	{
		get
		{
			if (!((Object)(object)_nv != (Object)null) || !_nv.IsValid())
			{
				return null;
			}
			return _nv.GetZDO();
		}
	}

	private void Awake()
	{
		_nv = ((Component)this).GetComponent<ZNetView>();
		if ((Object)(object)_nv != (Object)null && _nv.GetZDO() != null)
		{
			All.Add(this);
		}
	}

	private void OnDestroy()
	{
		All.Remove(this);
	}
}
[HarmonyPatch]
internal static class Deliveries
{
	internal const string PrefabName = "BeastRoads_Delivery";

	private const string RpcCall = "BeastRoads_Call";

	private const string RpcAnswer = "BeastRoads_CallAnswer";

	internal static readonly int ToKey = StringExtensionMethods.GetStableHashCode("BeastRoads_to");

	internal static readonly int ToNameKey = StringExtensionMethods.GetStableHashCode("BeastRoads_toName");

	internal static readonly int FromKey = StringExtensionMethods.GetStableHashCode("BeastRoads_from");

	internal static readonly int FromNameKey = StringExtensionMethods.GetStableHashCode("BeastRoads_fromName");

	internal static readonly int ArriveKey = StringExtensionMethods.GetStableHashCode("BeastRoads_arrive");

	internal static readonly int BeastPkgKey = StringExtensionMethods.GetStableHashCode("BeastRoads_beastData");

	internal static readonly int CartPkgKey = StringExtensionMethods.GetStableHashCode("BeastRoads_cartData");

	internal static readonly int BeastPrefabKey = StringExtensionMethods.GetStableHashCode("BeastRoads_beastPrefab");

	internal static readonly int CartPrefabKey = StringExtensionMethods.GetStableHashCode("BeastRoads_cartPrefab");

	internal static readonly int BeastPrefabNameKey = StringExtensionMethods.GetStableHashCode("BeastRoads_beastPrefabName");

	internal static readonly int BeastIdKey = StringExtensionMethods.GetStableHashCode("BeastRoads_beastId");

	internal static readonly int BeastNameKey = StringExtensionMethods.GetStableHashCode("BeastRoads_beastName");

	internal static readonly int SenderKey = StringExtensionMethods.GetStableHashCode("BeastRoads_sender");

	internal static readonly int RelPosKey = StringExtensionMethods.GetStableHashCode("BeastRoads_relPos");

	internal static readonly int RelRotKey = StringExtensionMethods.GetStableHashCode("BeastRoads_relRot");

	private static readonly int ArrivedAtKey = StringExtensionMethods.GetStableHashCode("BeastRoads_arrivedAt");

	private static readonly FieldInfo AllZdos = AccessTools.Field(typeof(ZDOMan), "m_objectsByID");

	private static readonly MethodInfo ServerPeer = AccessTools.Method(typeof(ZRoutedRpc), "GetServerPeerID", (Type[])null, (Type[])null);

	private static ZRoutedRpc _registeredOn;

	private static float _callWait;

	private static long _callBeast;

	private static long _callTo;

	private static string _callToName;

	private static GameObject _prefab;

	internal static int Hash => StringExtensionMethods.GetStableHashCode("BeastRoads_Delivery");

	internal static GameObject Prefab()
	{
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Expected O, but got Unknown
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_003a: Expected O, but got Unknown
		if ((Object)(object)_prefab != (Object)null)
		{
			return _prefab;
		}
		GameObject val = new GameObject("BeastRoads_DeliveryHolder");
		val.SetActive(false);
		Object.DontDestroyOnLoad((Object)(object)val);
		_prefab = new GameObject("BeastRoads_Delivery");
		_prefab.transform.SetParent(val.transform, false);
		ZNetView val2 = _prefab.AddComponent<ZNetView>();
		val2.m_persistent = true;
		_prefab.AddComponent<Delivery>();
		return _prefab;
	}

	internal static long NowMs()
	{
		if (!((Object)(object)ZNet.instance != (Object)null))
		{
			return 0L;
		}
		return (long)(ZNet.instance.GetTimeSeconds() * 1000.0);
	}

	internal static float TravelSeconds(Kind k, float length)
	{
		float num = ((k != null && k.Pull > 0f) ? k.Pull : 4f);
		return Mathf.Max(20f, length / num);
	}

	internal static string Clock(float seconds)
	{
		int num = Mathf.Max(0, Mathf.CeilToInt(seconds));
		return num / 60 + ":" + (num % 60).ToString("00");
	}

	internal static float SecondsLeft(ZDO d)
	{
		return (float)(d.GetLong(ArriveKey, 0L) - NowMs()) / 1000f;
	}

	private static byte[] Pack(ZDO z)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Expected O, but got Unknown
		ZPackage val = new ZPackage();
		z.Serialize(val);
		return val.GetArray();
	}

	private static ZDO Unpack(byte[] data, int prefab, Vector3 at, Quaternion rot)
	{
		//IL_0005: 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_0019: Expected O, but got Unknown
		//IL_001a: 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)
		ZDO val = ZDOMan.instance.CreateNewZDO(at, prefab);
		val.Deserialize(new ZPackage(data));
		val.SetPosition(at);
		val.SetRotation(rot);
		val.Set(ArrivedAtKey, NowMs());
		return val;
	}

	internal static void Register(Player p, RoadSign s, Character c)
	{
		ZNetView val = BK.View((Component)(object)c);
		if (!val.IsOwner())
		{
			val.ClaimOwnership();
		}
		long num = Beasts.EnsureId(c);
		ZDO zDO = val.GetZDO();
		zDO.Set(Beasts.SignKey, s.Id);
		zDO.Set(Beasts.SignNameKey, s.Name);
		zDO.Set(Beasts.OwnerKey, p.GetPlayerID());
		zDO.Set(Beasts.OwnerNameKey, p.GetPlayerName());
		BeastRec beastRec = new BeastRec();
		beastRec.Id = num;
		beastRec.Sign = s.Id;
		beastRec.SignName = s.Name;
		beastRec.Name = Beasts.Name(c);
		beastRec.Prefab = Utils.GetPrefabName(((Component)c).gameObject);
		Store.SetBeast(beastRec);
		Plugin.Say(p, Beasts.Name(c) + " is registered at " + s.Name + ".");
		Plugin.Debug("[sign] registered " + ((Object)c).name + " (" + num + ") at '" + s.Name + "'");
	}

	internal static long SignOf(Character c)
	{
		ZDO val = BK.Zdo((Component)(object)c);
		if (val == null)
		{
			return 0L;
		}
		return val.GetLong(Beasts.SignKey, 0L);
	}

	internal static Dictionary<long, float> Destinations(long from)
	{
		Dictionary<long, long> prev;
		return Destinations(from, out prev);
	}

	internal static Dictionary<long, float> Destinations(long from, out Dictionary<long, long> prev)
	{
		Dictionary<long, float> dictionary = new Dictionary<long, float>();
		prev = new Dictionary<long, long>();
		HashSet<long> hashSet = new HashSet<long>();
		dictionary[from] = 0f;
		while (hashSet.Count < 500)
		{
			long num = 0L;
			float num2 = float.MaxValue;
			foreach (KeyValuePair<long, float> item in dictionary)
			{
				if (!hashSet.Contains(item.Key) && item.Value < num2)
				{
					num = item.Key;
					num2 = item.Value;
				}
			}
			if (num == 0)
			{
				break;
			}
			hashSet.Add(num);
			foreach (KeyValuePair<long, float> item2 in Signs.RoadsFrom(num))
			{
				if (item2.Key != from && item2.Key != 0 && Store.Knows(item2.Key))
				{
					float num3 = num2 + item2.Value;
					if (!dictionary.TryGetValue(item2.Key, out var value) || !(value <= num3))
					{
						dictionary[item2.Key] = num3;
						prev[item2.Key] = num;
					}
				}
			}
		}
		dictionary.Remove(from);
		return dictionary;
	}

	internal static List<long> Via(long from, long to, Dictionary<long, long> prev)
	{
		List<long> list = new List<long>();
		long key = to;
		long value;
		while (prev.TryGetValue(key, out value) && value != from && list.Count < 50)
		{
			list.Insert(0, value);
			key = value;
		}
		return list;
	}

	internal static string CanSend(Player p, RoadSign s, Character c)
	{
		//IL_0044: 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_0067: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)p == (Object)null || (Object)(object)s == (Object)null || (Object)(object)c == (Object)null || !Beasts.CanPull(c))
		{
			return "";
		}
		if (SignOf(c) != s.Id)
		{
			return "Register it at this sign first.";
		}
		if (!Signs.InArea(s, ((Component)c).transform.position))
		{
			return "Bring it into the circle in front of the sign.";
		}
		if (Vector3.Distance(((Component)p).transform.position, ((Component)s).transform.position) > 10f)
		{
			return "Come closer to the sign.";
		}
		if (BK.Ridden(c))
		{
			return "Get off it first.";
		}
		Vagon val = Hitch.CartOf(c);
		if ((Object)(object)val == (Object)null)
		{
			return "Hitch it to a cart first.";
		}
		Kind k = Beasts.KindOf(c);
		if (Hitch.TooFull(val, c))
		{
			return "The cart is too full for it (" + Hitch.Load(val, k) + ").";
		}
		if (Destinations(s.Id).Count == 0)
		{
			return "No road leads from this sign to a sign you know yet.";
		}
		return null;
	}

	internal static void Send(Player p, RoadSign from, Character c, Vagon cart, long to, float length)
	{
		//IL_00ff: 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_0109: 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_012b: 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_013b: 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_014d: 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)
		if ((Object)(object)from == (Object)null || (Object)(object)c == (Object)null || (Object)(object)cart == (Object)null)
		{
			Plugin.Say(p, "Too far from the sign: nothing was sent.");
			return;
		}
		string text = CanSend(p, from, c);
		if (text != null)
		{
			Plugin.Say(p, (text.Length > 0) ? text : "It can't be sent.");
			return;
		}
		SignInfo signInfo = Store.Sign(to);
		if (signInfo == null || (Object)(object)Hitch.CartOf(c) != (Object)(object)cart)
		{
			Plugin.Say(p, "It can't be sent.");
			return;
		}
		ZNetView val = BK.View((Component)(object)c);
		ZNetView val2 = BK.View((Component)(object)cart);
		if (!val.IsOwner())
		{
			val.ClaimOwnership();
		}
		if (!val2.IsOwner())
		{
			val2.ClaimOwnership();
		}
		Kind kind = Beasts.KindOf(c);
		float num = TravelSeconds(kind, length);
		ZDO zDO = val.GetZDO();
		ZDO zDO2 = val2.GetZDO();
		zDO.Set(Beasts.SignKey, to);
		zDO.Set(Beasts.SignNameKey, signInfo.Name);
		zDO.Set(BK.LeashKey, 0L);
		zDO.Set(BK.RiderKey, 0L);
		Quaternion val3 = Quaternion.Inverse(((Component)c).transform.rotation);
		Parcels.Add(MakeParcel(to, signInfo.Name, from.Id, from.Name, zDO, zDO2, val3 * (((Component)cart).transform.position - ((Component)c).transform.position), val3 * ((Component)cart).transform.rotation, Utils.GetPrefabName(((Component)c).gameObject), Beasts.Name(c), p.GetPlayerName(), num));
		long num2 = Beasts.Id(c);
		string text2 = Beasts.Name(c);
		ZNetScene.instance.Destroy(((Component)cart).gameObject);
		ZNetScene.instance.Destroy(((Component)c).gameObject);
		Beasts.Forget();
		BeastRec beastRec = new BeastRec();
		beastRec.Id = num2;
		beastRec.Sign = to;
		beastRec.SignName = signInfo.Name;
		beastRec.Name = text2;
		beastRec.Prefab = kind.Prefab;
		beastRec.ArriveMs = NowMs() + (long)(num * 1000f);
		Store.SetBeast(beastRec);
		Plugin.Say(p, text2 + " is on the way to " + signInfo.Name + " with the cart. It arrives in about " + Clock(num) + ". Go there to receive it.");
		Plugin.Debug("[send] " + text2 + " (" + num2 + ") from '" + from.Name + "' to '" + signInfo.Name + "', " + length.ToString("0") + " m, " + num.ToString("0") + " s");
	}

	private static Parcel MakeParcel(long to, string toName, long fromId, string fromName, ZDO beast, ZDO cart, Vector3 relPos, Quaternion relRot, string prefab, string name, string sender, float travel)
	{
		//IL_00d6: 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_00de: 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)
		Parcel parcel = new Parcel();
		parcel.To = to;
		parcel.ToName = toName;
		parcel.From = fromId;
		parcel.FromName = fromName ?? "";
		parcel.Arrive = NowMs() + (long)(travel * 1000f);
		parcel.Beast = Pack(beast);
		parcel.BeastPrefab = beast.GetPrefab();
		parcel.BeastId = beast.GetLong(Beasts.IdKey, 0L);
		parcel.Owner = beast.GetLong(Beasts.OwnerKey, 0L);
		parcel.Name = name ?? "";
		parcel.Sender = sender ?? "";
		parcel.Prefab = prefab ?? "";
		Parcel parcel2 = parcel;
		if (cart != null)
		{
			parcel2.Cart = Pack(cart);
			parcel2.CartPrefab = cart.GetPrefab();
			parcel2.RelPos = relPos;
			parcel2.RelRot = relRot;
		}
		return parcel2;
	}

	private static Parcel FromOld(ZDO d)
	{
		//IL_012a: 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_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_014a: Unknown result type (might be due to invalid IL or missing references)
		Parcel parcel = new Parcel();
		parcel.To = d.GetLong(ToKey, 0L);
		parcel.ToName = d.GetString(ToNameKey, "");
		parcel.From = d.GetLong(FromKey, 0L);
		parcel.FromName = d.GetString(FromNameKey, "");
		parcel.Arrive = d.GetLong(ArriveKey, 0L);
		parcel.Beast = d.GetByteArray(BeastPkgKey, (byte[])null);
		parcel.BeastPrefab = d.GetInt(BeastPrefabKey, 0);
		parcel.BeastId = d.GetLong(BeastIdKey, 0L);
		parcel.Owner = d.GetLong(Beasts.OwnerKey, 0L);
		parcel.Name = d.GetString(BeastNameKey, "");
		parcel.Sender = d.GetString(SenderKey, "");
		parcel.Prefab = d.GetString(BeastPrefabNameKey, "");
		Parcel parcel2 = parcel;
		byte[] byteArray = d.GetByteArray(CartPkgKey, (byte[])null);
		if (byteArray != null)
		{
			parcel2.Cart = byteArray;
			parcel2.CartPrefab = d.GetInt(CartPrefabKey, 0);
			parcel2.RelPos = d.GetVec3(RelPosKey, parcel2.RelPos);
			parcel2.RelRot = d.GetQuaternion(RelRotKey, Quaternion.identity);
		}
		return parcel2;
	}

	internal static void Receive(Player p, RoadSign s, Parcel pc)
	{
		//IL_0034: 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_007d: 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_0084: Unknown result type (might be due to invalid IL or missing references)
		//IL_0089: Unknown result type (might be due to invalid IL or missing references)
		//IL_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)
		//IL_0094: Unknown result type (might be due to invalid IL or missing references)
		//IL_0099: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a2: 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_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_00b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
		//IL_009e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bb: 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)
		//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e7: 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_00fb: Unknown result type (might be due to invalid IL or missing references)
		//IL_0100: Unknown result type (might be due to invalid IL or missing references)
		//IL_0113: Unknown result type (might be due to invalid IL or missing references)
		//IL_011d: Unknown result type (might be due to invalid IL or missing references)
		//IL_011f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0120: Unknown result type (might be due to invalid IL or missing references)
		//IL_0122: Unknown result type (might be due to invalid IL or missing references)
		//IL_0127: Unknown result type (might be due to invalid IL or missing references)
		//IL_012c: 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_0164: 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_0167: Unknown result type (might be due to invalid IL or missing references)
		//IL_0169: Unknown result type (might be due to invalid IL or missing references)
		if (pc == null || (Object)(object)s == (Object)null || !Parcels.All().Contains(pc))
		{
			return;
		}
		if (pc.SecondsLeft > 0f)
		{
			Plugin.Say(p, "It hasn't arrived yet.");
			return;
		}
		string text = Area.Check(s.AreaCenter, 4.5f);
		if (text != null)
		{
			Plugin.Say(p, text);
			return;
		}
		byte[] beast = pc.Beast;
		if (beast == null || beast.Length == 0)
		{
			Plugin.Say(p, "This delivery is empty.");
			Parcels.Remove(pc);
			return;
		}
		byte[] cart = pc.Cart;
		Quaternion val = Quaternion.LookRotation(s.Front);
		Vector3 relPos = pc.RelPos;
		Quaternion relRot = pc.RelRot;
		Vector3 areaCenter = s.AreaCenter;
		Vector3 val2 = ((cart != null) ? (areaCenter - val * relPos * 0.5f) : areaCenter);
		val2.y = Hitch.Ground(val2, areaCenter.y) + 0.1f;
		Parcels.Remove(pc);
		ZDO val3 = Unpack(beast, pc.BeastPrefab, val2, val);
		if (val3.GetVec3(BK.HomeKey, Vector3.zero) != Vector3.zero)
		{
			val3.Set(BK.HomeKey, val2);
		}
		if (cart != null)
		{
			Vector3 at = val2 + val * relPos;
			at.y = Mathf.Max(val2.y + relPos.y, Hitch.Ground(at, val2.y)) + 0.15f;
			Unpack(cart, pc.CartPrefab, at, val * relRot);
		}
		string text2 = ((pc.Name.Length > 0) ? pc.Name : "The animal");
		long beastId = pc.BeastId;
		val3.Set(Beasts.SignKey, s.Id);
		val3.Set(Beasts.SignNameKey, s.Name);
		Beasts.Forget();
		if (Store.Beasts().TryGetValue(beastId, out var value))
		{
			value.Sign = s.Id;
			value.SignName = s.Name;
			value.ArriveMs = 0L;
			Store.SetBeast(value);
		}
		Plugin.Say(p, text2 + " arrived at " + s.Name + ((cart != null) ? " with the cart." : "."));
		Plugin.Debug("[receive] " + text2 + " (" + beastId + ") at '" + s.Name + "'");
	}

	internal static string CanCall(RoadSign here, BeastRec b)
	{
		if ((Object)(object)here == (Object)null || b == null)
		{
			return "";
		}
		if (b.Sign == here.Id)
		{
			return "It is registered here.";
		}
		if (!Signs.RoadsFrom(here.Id).ContainsKey(b.Sign))
		{
			return "No road leads from here to " + b.SignName + ".";
		}
		if (b.ArriveMs > NowMs())
		{
			return "Still on the way to " + b.SignName + " (" + Clock((float)(b.ArriveMs - NowMs()) / 1000f) + ").";
		}
		if (_callWait > Time.time)
		{
			return "Waiting for an answer...";
		}
		return null;
	}

	internal static void Call(Player p, RoadSign here, BeastRec b)
	{
		//IL_0177: Unknown result type (might be due to invalid IL or missing references)
		//IL_017e: Expected O, but got Unknown
		//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
		string text = CanCall(here, b);
		if (text != null)
		{
			if (text.Length > 0)
			{
				Plugin.Say(p, text);
			}
			return;
		}
		Register();
		float length = Signs.RoadsFrom(here.Id)[b.Sign];
		Kind k = Beasts.KindOf(b.Prefab);
		Parcel parcel = Parcels.OfBeast(b.Id);
		if (parcel != null)
		{
			float num = TravelSeconds(k, length);
			parcel.From = parcel.To;
			parcel.FromName = parcel.ToName;
			parcel.To = here.Id;
			parcel.ToName = here.Name;
			parcel.Sender = p.GetPlayerName();
			parcel.Arrive = NowMs() + (long)(num * 1000f);
			Parcels.Save();
			b.Sign = here.Id;
			b.SignName = here.Name;
			b.ArriveMs = parcel.Arrive;
			Store.SetBeast(b);
			Plugin.Say(p, b.Name + " is on the way here. It arrives in about " + Clock(num) + ".");
			Plugin.Debug("[call] " + b.Name + " (" + b.Id + ") turned around to '" + here.Name + "', " + num.ToString("0") + " s");
			return;
		}
		ZPackage val = new ZPackage();
		val.Write(b.Id);
		val.Write(b.Sign);
		val.Write(here.Id);
		val.Write(here.Name);
		val.Write(((Component)here).transform.position);
		val.Write(TravelSeconds(k, length));
		val.Write(p.GetPlayerName());
		_callWait = Time.time + 8f;
		_callBeast = b.Id;
		_callTo = here.Id;
		_callToName = here.Name;
		Plugin.Debug("[call] asking the server for " + b.Name + " (" + b.Id + ") from '" + b.SignName + "'");
		if (ZNet.instance.IsServer())
		{
			OnCall(ZDOMan.GetSessionID(), val);
			return;
		}
		long num2 = ((ServerPeer != null) ? ((long)ServerPeer.Invoke(ZRoutedRpc.instance, null)) : 0);
		ZRoutedRpc.instance.InvokeRoutedRPC(num2, "BeastRoads_Call", new object[1] { val });
	}

	private static void Register()
	{
		ZRoutedRpc instance = ZRoutedRpc.instance;
		if (instance != null && instance != _registeredOn)
		{
			instance.Register<ZPackage>("BeastRoads_Call", (Action<long, ZPackage>)OnCall);
			instance.Register<ZPackage>("BeastRoads_CallAnswer", (Action<long, ZPackage>)OnAnswer);
			_registeredOn = instance;
		}
	}

	private static void OnCall(long sender, ZPackage pkg)
	{
		//IL_003e: Unknown result type (might be due to invalid IL or missing references)
		//IL_045c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0463: Expected O, but got Unknown
		//IL_0491: Unknown result type (might be due to invalid IL or missing references)
		//IL_0498: Expected O, but got Unknown
		//IL_02dd: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e7: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f4: 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_02ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_0304: Unknown result type (might be due to invalid IL or missing references)
		//IL_0309: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_030e: Unknown result type (might be due to invalid IL or missing references)
		//IL_031b: Unknown result type (might be due to invalid IL or missing references)
		//IL_031f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0324: Unknown result type (might be due to invalid IL or missing references)
		//IL_0314: 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_03a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_03a7: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
		{
			return;
		}
		pkg.SetPos(0);
		long num = pkg.ReadLong();
		long num2 = pkg.ReadLong();
		long num3 = pkg.ReadLong();
		string text = pkg.ReadString();
		pkg.ReadVector3();
		float num4 = pkg.ReadSingle();
		string sender2 = pkg.ReadString();
		float num5 = 0f;
		Parcel parcel = null;
		Dictionary<ZDOID, ZDO> dictionary = ((AllZdos != null) ? (AllZdos.GetValue(ZDOMan.instance) as Dictionary<ZDOID, ZDO>) : null);
		ZDO val = null;
		ZDO val2 = null;
		ZDO val3 = null;
		if (dictionary != null)
		{
			foreach (ZDO value in dictionary.Values)
			{
				if (value == null || !value.IsValid())
				{
					continue;
				}
				if (value.GetPrefab() == Hash)
				{
					if (value.GetLong(BeastIdKey, 0L) == num)
					{
						val3 = value;
					}
				}
				else if (value.GetLong(Beasts.IdKey, 0L) == num)
				{
					val = value;
				}
			}
		}
		long sessionID = ZDOMan.GetSessionID();
		bool flag;
		string text2;
		if (val3 != null)
		{
			if (SecondsLeft(val3) > 0f)
			{
				flag = false;
				text2 = "It is still on the way to " + val3.GetString(ToNameKey, "its sign") + ".";
			}
			else
			{
				parcel = FromOld(val3);
				parcel.From = parcel.To;
				parcel.FromName = parcel.ToName;
				parcel.To = num3;
				parcel.ToName = text;
				parcel.Sender = sender2;
				parcel.Arrive = NowMs() + (long)(num4 * 1000f);
				val3.SetOwner(sessionID);
				ZDOMan.instance.DestroyZDO(val3);
				flag = true;
				num5 = num4;
				text2 = "";
			}
		}
		else if (val != null)
		{
			if (val.GetLong(Beasts.SignKey, 0L) != num2)
			{
				flag = false;
				text2 = "It is no longer registered at that sign.";
			}
			else if (val.GetLong(BK.RiderKey, 0L) != 0)
			{
				flag = false;
				text2 = "Someone is riding it.";
			}
			else
			{
				long num6 = val.GetLong(Beasts.CartKey, 0L);
				if (num6 != 0)
				{
					foreach (ZDO value2 in dictionary.Values)
					{
						if (value2 != null && value2.IsValid() && value2.GetLong(Hitch.CartIdKey, 0L) == num6 && value2.GetLong(Hitch.BeastKey, 0L) == num)
						{
							val2 = value2;
							break;
						}
					}
				}
				if (val2 == null && num6 != 0)
				{
					val.Set(Beasts.CartKey, 0L);
				}
				val.SetOwner(sessionID);
				val.Set(Beasts.SignKey, num3);
				val.Set(Beasts.SignNameKey, text);
				val.Set(BK.LeashKey, 0L);
				Quaternion val4 = Quaternion.Inverse(val.GetRotation());
				Vector3 relPos = ((val2 != null) ? (val4 * (val2.GetPosition() - val.GetPosition())) : Vector3.zero);
				Quaternion relRot = ((val2 != null) ? (val4 * val2.GetRotation()) : Quaternion.identity);
				string text3 = "";
				GameObject val5 = (((Object)(object)ZNetScene.instance != (Object)null) ? ZNetScene.instance.GetPrefab(val.GetPrefab()) : null);
				if ((Object)(object)val5 != (Object)null)
				{
					text3 = ((Object)val5).name;
				}
				string text4 = val.GetString(ZDOVars.s_tamedName, "");
				if (string.IsNullOrEmpty(text4))
				{
					text4 = ((text3.Length > 0) ? text3 : "Your animal");
				}
				parcel = MakeParcel(num3, text, num2, "", val, val2, relPos, relRot, text3, text4, sender2, num4);
				if (val2 != null)
				{
					val2.SetOwner(sessionID);
					ZDOMan.instance.DestroyZDO(val2);
				}
				ZDOMan.instance.DestroyZDO(val);
				flag = true;
				num5 = num4;
				text2 = "";
			}
		}
		else
		{
			flag = false;
			text2 = "It can't be found anywhere in the world.";
		}
		Plugin.Debug("[call] server: " + num + " -> '" + text + "': " + (flag ? ("on the way, " + num5.ToString("0") + " s") : text2));
		ZPackage val6 = new ZPackage();
		val6.Write(flag);
		val6.Write(text2);
		val6.Write(num5);
		val6.Write(parcel != null);
		if (parcel != null)
		{
			ZPackage val7 = new ZPackage();
			parcel.Write(val7);
			val6.Write(val7.GetArray());
		}
		if (sender == sessionID)
		{
			OnAnswer(sender, val6);
			return;
		}
		ZRoutedRpc.instance.InvokeRoutedRPC(sender, "BeastRoads_CallAnswer", new object[1] { val6 });
	}

	private static void OnAnswer(long sender, ZPackage answer)
	{
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0037: Expected O, but got Unknown
		answer.SetPos(0);
		bool flag = answer.ReadBool();
		string msg = answer.ReadString();
		float num = answer.ReadSingle();
		Parcel parcel = (answer.ReadBool() ? Parcel.Read(new ZPackage(answer.ReadByteArray())) : null);
		_callWait = 0f;
		Player localPlayer = Player.m_localPlayer;
		if (parcel != null)
		{
			if ((Object)(object)localPlayer != (Object)null)
			{
				Parcels.Add(parcel);
			}
			else
			{
				Plugin.Log.LogError((object)("[call] " + parcel.Name + " came back with nobody to carry it."));
			}
		}
		if ((Object)(object)localPlayer == (Object)null)
		{
			return;
		}
		Store.Beasts().TryGetValue(_callBeast, out var value);
		string text = ((value != null) ? value.Name : "Your animal");
		if (!flag)
		{
			Plugin.Say(localPlayer, msg);
			return;
		}
		if (value != null)
		{
			value.Sign = _callTo;
			value.SignName = _callToName;
			value.ArriveMs = NowMs() + (long)(num * 1000f);
			Store.SetBeast(value);
		}
		Plugin.Say(localPlayer, text + " is on the way here. It arrives in about " + Clock(num) + ".");
	}

	internal static void Update()
	{
		Register();
		if (_callWait > 0f && Time.time > _callWait)
		{
			_callWait = 0f;
			Plugin.Say(Player.m_localPlayer, "No answer: the server needs Beast Roads installed for \"Call here\".");
		}
	}
}
[HarmonyPatch]
internal static class Hitch
{
	private const float MaxGap = 4f;

	private const float LooseGap = 10f;

	private const float HoldToUnhitch = 0.6f;

	private const float LeadRange = 20f;

	private const float PullMassTimes = 4f;

	private const float CrashSpeed = 8f;

	internal static readonly int CartIdKey = StringExtensionMethods.GetStableHashCode("BeastRoads_cartId");

	internal static readonly int BeastKey = StringExtensionMethods.GetStableHashCode("BeastRoads_beast");

	internal static readonly int AnchorKey = StringExtensionMethods.GetStableHashCode("BeastRoads_anchor");

	private static readonly FieldInfo JointF = AccessTools.Field(typeof(Vagon), "m_attachJoin");

	private static readonly FieldInfo AttachedF = AccessTools.Field(typeof(Vagon), "m_attachedObject");

	private static readonly FieldInfo InstancesF = AccessTools.Field(typeof(Vagon), "m_instances");

	private static readonly FieldInfo LineF = AccessTools.Field(typeof(Vagon), "m_lineRenderer");

	private static readonly MethodInfo DetachM = AccessTools.Method(typeof(Vagon), "Detach", (Type[])null, (Type[])null);

	private static readonly MethodInfo SetMassM = AccessTools.Method(typeof(Vagon), "SetMass", (Type[])null, (Type[])null);

	private static readonly MethodInfo UpdateMassM = AccessTools.Method(typeof(Vagon), "UpdateMass", (Type[])null, (Type[])null);

	private static readonly Func<BaseAI, ZNetView> AIView = Getter();

	private static bool _unhitching;

	internal static int HandledFrame = -1;

	private static float _next;

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

	private static int _groundMask;

	private static readonly Dictionary<Character, float[]> _speeds0 = new Dictionary<Character, float[]>();

	private static readonly HashSet<Character> _pulling = new HashSet<Character>();

	private static readonly HashSet<int> _passed = new HashSet<int>();

	private static readonly FieldInfo MoveDirF = AccessTools.Field(typeof(Character), "m_moveDir");

	private static float _speedLogAt;

	private static float _stuckFor;

	private static bool _stuckTold;

	private static int _blockMask;

	private static Vagon _holdCart;

	private static float _holdFrom;

	private static bool _holdDone;

	private static Func<BaseAI, ZNetView> Getter()
	{
		FieldInfo f = AccessTools.Field(typeof(BaseAI), "m_nview");
		try
		{
			ParameterExpression parameterExpression = Expression.Parameter(typeof(BaseAI), "o");
			return Expression.Lambda<Func<BaseAI, ZNetView>>(Expression.Field(parameterExpression, f), new ParameterExpression[1] { parameterExpression }).Compile();
		}
		catch (Exception)
		{
			return (BaseAI x) => ((Object)(object)x != (Object)null) ? ((ZNetView)f.GetValue(x)) : ((ZNetView)null);
		}
	}

	internal static List<Vagon> Carts()
	{
		List<Vagon> list = ((InstancesF != null) ? (InstancesF.GetValue(null) as List<Vagon>) : null);
		return list ?? new List<Vagon>();
	}

	internal static long BeastOf(Vagon v)
	{
		ZDO val = BK.Zdo((Component)(object)v);
		if (val == null)
		{
			return 0L;
		}
		return val.GetLong(BeastKey, 0L);
	}

	internal static long CartIdOf(Vagon v)
	{
		ZDO val = BK.Zdo((Component)(object)v);
		if (val == null)
		{
			return 0L;
		}
		return val.GetLong(CartIdKey, 0L);
	}

	internal static Vector3 AnchorOf(Vagon v)
	{
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		ZDO val = BK.Zdo((Component)(object)v);
		if (val == null)
		{
			return Vector3.zero;
		}
		return val.GetVec3(AnchorKey, Vector3.zero);
	}

	internal static bool IsHitched(Character c)
	{
		ZDO val = BK.Zdo((Component)(object)c);
		if (val != null)
		{
			return val.GetLong(Beasts.CartKey, 0L) != 0;
		}
		return false;
	}

	internal static Vagon CartOf(Character c)
	{
		long num = Beasts.Id(c);
		if (num == 0)
		{
			return null;
		}
		foreach (Vagon item in Carts())
		{
			if ((Object)(object)item != (Object)null && BeastOf(item) == num)
			{
				return item;
			}
		}
		return null;
	}

	private static Inventory Inv(Vagon v)
	{
		if (!((Object)(object)v != (Object)null) || !((Object)(object)v.m_container != (Object)null))
		{
			return null;
		}
		return v.m_container.GetInventory();
	}

	internal static int Used(Vagon v)
	{
		Inventory val = Inv(v);
		if (val == null)
		{
			return 0;
		}
		return val.GetAllItems().Count;
	}

	internal static int Limit(Vagon v, Kind k)
	{
		Inventory val = Inv(v);
		int num = ((val != null) ? (val.GetWidth() * val.GetHeight()) : 18);
		if (k != null && k.Slots > 0)
		{
			return Mathf.Min(k.Slots, num);
		}
		return num;
	}

	internal static bool TooFull(Vagon v, Character c)
	{
		Kind kind = Beasts.KindOf(c);
		if (kind != null)
		{
			return Used(v) > Limit(v, kind);
		}
		return false;
	}

	internal static string Load(Vagon v, Kind k)
	{
		return Used(v) + " / " + Limit(v, k) + " slots";
	}

	private static ConfigurableJoint Joint(Vagon v)
	{
		if (!(JointF != null))
		{
			return null;
		}
		object? value = JointF.GetValue(v);
		return (ConfigurableJoint)((value is ConfigurableJoint) ? value : null);
	}

	internal static Character OnMyRope(Player p, Vagon v)
	{
		//IL_0061: 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)
		if ((Object)(object)p == (Object)null || (Object)(object)v == (Object)null)
		{
			return null;
		}
		long playerID = p.GetPlayerID();
		Character result = null;
		float num = 20f;
		foreach (Character allCharacter in Character.GetAllCharacters())
		{
			if (!((Object)(object)allCharacter == (Object)null) && !allCharacter.IsPlayer() && Beasts.CanPull(allCharacter) && BK.Holder(allCharacter) == playerID)
			{
				float num2 = Vector3.Distance(((Component)allCharacter).transform.position, ((Component)v).transform.position);
				if (num2 < num)
				{
					num = num2;
					result = allCharacter;
				}
			}
		}
		return result;
	}

	private static Vector3 Flat(Vector3 v)
	{
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		v.y = 0f;
		if (!(((Vector3)(ref v)).sqrMagnitude < 0.0001f))
		{
			return ((Vector3)(ref v)).normalized;
		}
		return Vector3.forward;
	}

	internal static int GroundMask()
	{
		if (_groundMask == 0)
		{
			_groundMask = LayerMask.GetMask(new string[4] { "terrain", "piece", "static_solid", "Default" });
		}
		return _groundMask;
	}

	internal static float Ground(Vector3 at, float fallback)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: 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_004d: Unknown result type (might be due to invalid IL or missing references)
		RaycastHit val = default(RaycastHit);
		if (Physics.Raycast(at + Vector3.up * 3f, Vector3.down, ref val, 10f, GroundMask(), (QueryTriggerInteraction)1))
		{
			return ((RaycastHit)(ref val)).point.y;
		}
		if ((Object)(object)ZoneSystem.instance != (Object)null)
		{
			return ZoneSystem.instance.GetGroundHeight(at);
		}
		return fallback;
	}

	internal static float RearOf(Character c)
	{
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		CapsuleCollider component = ((Component)c).GetComponent<CapsuleCollider>();
		if ((Object)(object)component != (Object)null)
		{
			float num = ((component.direction == 2) ? (component.height * 0.5f) : component.radius);
			return Mathf.Max(0.3f, (num - component.center.z) * ((Component)c).transform.lossyScale.z);
		}
		return 1.2f;
	}

	internal static float FlankOf(Character c)
	{
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		CapsuleCollider component = ((Component)c).GetComponent<CapsuleCollider>();
		float num = (((Object)(object)component != (Object)null) ? (component.radius * ((Component)c).transform.lossyScale.x) : 0.6f);
		return Mathf.Clamp(num * 0.95f, 0.3f, 1.6f);
	}

	internal static Vector3 OnBody(Character c, Vector3 middle, Vector3 side, float half)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//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)
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: 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_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_006e: 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_0074: Unknown result type (might be due to invalid IL or missing references)
		//IL_0060: Unknown result type (might be due to invalid IL or missing references)
		//IL_0095: 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_009b: Unknown result type (might be due to invalid IL or missing references)
		//IL_008b: 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_009d: Unknown result type (might be due to invalid IL or missing references)
		//IL_009f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00af: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
		Vector3 val = middle + side * (half + 3f);
		Vector3 result = middle + side * half;
		float num = float.MaxValue;
		Collider[] componentsInChildren = ((Component)c).GetComponentsInChildren<Collider>();
		RaycastHit val4 = default(RaycastHit);
		foreach (Collider val2 in componentsInChildren)
		{
			if (!((Object)(object)val2 == (Object)null) && !val2.isTrigger && val2.enabled && (!(val2 is MeshCollider) || ((MeshCollider)val2).convex))
			{
				Vector3 val3 = ((!val2.Raycast(new Ray(val, -side), ref val4, half + 3f)) ? val2.ClosestPoint(val) : ((RaycastHit)(ref val4)).point);
				float num2 = Vector3.Distance(val3, val);
				if (num2 < num)
				{
					num = num2;
					result = val3;
				}
			}
		}
		return result;
	}

	internal static float HalfWidthOf(Character c)
	{
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		CapsuleCollider component = ((Component)c).GetComponent<CapsuleCollider>();
		float num = (((Object)(object)component != (Object)null) ? (component.radius * ((Component)c).transform.lossyScale.x) : 0.6f);
		return Mathf.Clamp(num * 0.6f, 0.25f, 1.2f);
	}

	internal static void Place(Character c, Vector3 at, Quaternion rot)
	{
		//IL_0006: 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_0029: 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_0037: Unknown result type (might be due to invalid IL or missing references)
		//IL_004c: 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)
		((Component)c).transform.position = at;
		((Component)c).transform.rotation = rot;
		Rigidbody component = ((Component)c).GetComponent<Rigidbody>();
		if ((Object)(object)component != (Object)null)
		{
			component.position = at;
			component.rotation = rot;
			component.linearVelocity = Vector3.zero;
		}
		ZDO val = BK.Zdo((Component)(object)c);
		if (val != null)
		{
			val.SetPosition(at);
			val.SetRotation(rot);
		}
	}

	internal static void TryHitch(Player p, Vagon v, Character c)
	{
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		//IL_019f: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b3: 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_01bd: Unknown result type (might be due to invalid IL or missing references)
		//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e5: 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_0202: Unknown result type (might be due to invalid IL or missing references)
		//IL_0204: Unknown result type (might be due to invalid IL or missing references)
		//IL_0214: Unknown result type (might be due to invalid IL or missing references)
		//IL_0216: Unknown result type (might be due to invalid IL or missing references)
		//IL_021b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0286: Unknown result type (might be due to invalid IL or missing references)
		Kind kind = Beasts.KindOf(c);
		string text = Beasts.Name(c);
		if (kind == null || !c.IsTamed())
		{
			Refuse(p, c, "Only a tamed lox, bear or asksvin can pull a cart.");
			return;
		}
		if (BK.Ridden(c))
		{
			Refuse(p, c, "Get off " + text + " first.");
			return;
		}
		if (((Component)v).transform.up.y < 0.5f)
		{
			Refuse(p, c, "Set the cart upright first.");
			return;
		}
		if (BeastOf(v) != 0 && (Object)(object)Beasts.Find(BeastOf(v)) != (Object)null)
		{
			Refuse(p, c, "Another animal already pulls this cart.");
			return;
		}
		if (v.IsAttached() && BeastOf(v) == 0)
		{
			Refuse(p, c, "Someone is pulling this cart.");
			return;
		}
		Vagon val = CartOf(c);
		if ((Object)(object)val != (Object)null && (Object)(object)val != (Object)(object)v)
		{
			Refuse(p, c, text + " already pulls another cart.");
			return;
		}
		if (Used(v) > Limit(v, kind))
		{
			Refuse(p, c, "Too much for " + text + ": the cart uses " + Used(v) + " slots, a " + kind.Name.ToLower() + " pulls at most " + Limit(v, kind) + ". Take some out first.");
			return;
		}
		ZNetView val2 = BK.View((Component)(object)v);
		ZNetView val3 = BK.View((Component)(object)c);
		if (!val2.IsOwner())
		{
			val2.ClaimOwnership();
		}
		if (!val3.IsOwner())
		{
			val3.ClaimOwnership();
		}
		BK.LetGo(c);
		Vector3 position = v.m_attachPoint.position;
		Vector3 val4 = Flat(position - ((Component)v).transform.position);
		Vector3 at = position + val4 * (RearOf(c) + 0.25f);
		at.y = Ground(at, ((Component)c).transform.position.y) + 0.05f;
		Place(c, at, Quaternion.LookRotation(val4));
		Vector3 val5 = ((Component)c).transform.InverseTransformPoint(position);
		val5.y = Mathf.Max(val5.y, HoldHeight(v));
		long num = Beasts.EnsureId(c);
		ZDO zDO = val2.GetZDO();
		long num2 = zDO.GetLong(CartIdKey, 0L);
		if (num2 == 0)
		{
			num2 = Beasts.NewId();
			zDO.Set(CartIdKey, num2);
		}
		zDO.Set(BeastKey, num);
		zDO.Set(AnchorKey, val5);
		val3.GetZDO().Set(Beasts.CartKey, num2);
		Join(v, c);
		if (UpdateMassM != null)
		{
			UpdateMassM.Invoke(v, null);
		}
		Plugin.Say(p, text + " is hitched to the cart. Ride it to pull the cart.");
		Plugin.Debug("[hitch] " + ((Object)c).name + " speeds: walk " + c.m_walkSpeed.ToString("0.0") + ", jog " + c.m_speed.ToString("0.0") + ", run " + c.m_runSpeed.ToString("0.0") + " m/s");
		Plugin.Debug("[hitch] " + ((Object)c).name + " (" + num + ") to cart " + num2 + ", rear " + RearOf(c).ToString("0.00") + ", anchor " + ((Vector3)(ref val5)).ToString("0.00") + ", load " + Load(v, kind));
	}

	private static void Refuse(Player p, Character c, string why)
	{
		Plugin.Say(p, why);
		Plugin.Debug("[hitch] not hitched (" + (((Object)(object)c != (Object)null) ? ((Object)c).name : "?") + "): " + why);
	}

	internal static void Unhitch(Player p, Character c)
	{
		Vagon v = CartOf(c);
		Clear(v, c);
		if ((Object)(object)p != (Object)null)
		{
			if (BK.LassoInHand(p))
			{
				BK.OnRope(c, p);
				Plugin.Say(p, "You unhitch " + Beasts.Name(c) + ". It's on your lasso.");
			}
			else
			{
				Plugin.Say(p, "You unhitch " + Beasts.Name(c) + ".");
			}
		}
		Plugin.Debug("[hitch] unhitched " + (((Object)(object)c != (Object)null) ? ((Object)c).name : "?"));
	}

	internal static void Clear(Vagon v, Character c)
	{
		//IL_0075: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)v != (Object)null)
		{
			ZNetView val = BK.View((Component)(object)v);
			if ((Object)(object)val != (Object)null && val.IsValid())
			{
				if (!val.IsOwner())
				{
					val.ClaimOwnership();
				}
				_unhitching = true;
				try
				{
					if (DetachM != null)
					{
						DetachM.Invoke(v, null);
					}
				}
				finally
				{
					_unhitching = false;
				}
				val.GetZDO().Set(BeastKey, 0L);
				val.GetZDO().Set(AnchorKey, Vector3.zero);
			}
		}
		if (!((Object)(object)c != (Object)null))
		{
			return;
		}
		ZNetView val2 = BK.View((Component)(object)c);
		if ((Object)(object)val2 != (Object)null && val2.IsValid())
		{
			if (!val2.IsOwner())
			{
				val2.ClaimOwnership();
			}
			val2.GetZDO().Set(Beasts.CartKey, 0L);
		}
	}

	private static bool Join(Vagon v, Character c)
	{
		//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_0027: 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_0098: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a3: 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_00f6: 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_012e: 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_014b: 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_008c: Unknown result type (might be due to invalid IL or missing references)
		Rigidbody component = ((Component)c).GetComponent<Rigidbody>();
		if ((Object)(object)component == (Object)null || (Object)(object)v.m_attachPoint == (Object)null)
		{
			return false;
		}
		Vector3 val = AnchorOf(v);
		if (val == Vector3.zero)
		{
			((Vector3)(ref val))..ctor(0f, HoldHeight(v), 0f - RearOf(c));
		}
		if (val.y < HoldHeight(v) - 0.05f)
		{
			val.y = HoldHeight(v);
			ZDO val2 = BK.Zdo((Component)(object)v);
			if (val2 != null && BK.View((Component)(object)v).IsOwner())
			{
				val2.Set(AnchorKey, val);
			}
		}
		float num = Vector3.Distance(v.m_attachPoint.position, ((Component)c).transform.TransformPoint(val));
		if (num > 4f)
		{
			Plugin.Debug("[hitch] too far apart to join (" + num.ToString("0.0") + " m)");
			return false;
		}
		ConfigurableJoint val3 = ((Component)v).gameObject.AddComponent<ConfigurableJoint>();
		((Joint)val3).autoConfigureConnectedAnchor = false;
		((Joint)val3).anchor = v.m_attachPoint.localPosition;
		((Joint)val3).connectedAnchor = val;
		((Joint)val3).breakForce = float.PositiveInfinity;
		val3.xMotion = (ConfigurableJointMotion)1;
		val3.yMotion = (ConfigurableJointMotion)1;
		val3.zMotion = (ConfigurableJointMotion)1;
		SoftJointLimit linearLimit = default(SoftJointLimit);
		((SoftJointLimit)(ref linearLimit)).limit = 0.001f;
		val3.linearLimit = linearLimit;
		SoftJointLimitSpring linearLimitSpring = default(SoftJointLimitSpring);
		((SoftJointLimitSpring)(ref linearLimitSpring)).spring = v.m_spring * 8f;
		((SoftJointLimitSpring)(ref linearLimitSpring)).damper = v.m_springDamping * 4f;
		val3.linearLimitSpring = linearLimitSpring;
		val3.zMotion = (ConfigurableJointMotion)0;
		((Joint)val3).connectedBody = component;
		JointF.SetValue(v, val3);
		if (AttachedF != null)
		{
			AttachedF.SetValue(v, ((Component)c).gameObject);
		}
		BK.Zdo((Component)(object)v).Set(ZDOVars.s_attachJointHash, true);
		Weigh(v, c);
		Touch(v, c, touch: false);
		Plugin.Debug("[hitch] joined cart to " + ((Object)c).name + " (gap " + num.ToString("0.00") + " m, spring " + ((SoftJointLimitSpring)(ref linearLimitSpring)).spring.ToString("0") + ", damper " + ((SoftJointLimitSpring)(ref linearLimitSpring)).damper.ToString("0") + ", cart mass " + v.m_baseMass.ToString("0") + ")");
		return true;
	}

	private static void Weigh(Vagon v, Character c)
	{
		float mass = c.GetMass();
		float extraMass = Mathf.Max(v.m_playerExtraPullMass, v.m_baseMass * 4f - mass);
		c.SetExtraMass(extraMass);
		Plugin.Debug("[hitch] " + ((Object)c).name + " weighs " + mass.ToString("0") + " + " + extraMass.ToString("0") + " while it pulls");
	}

	private static void Touch(Vagon v, Character c, bool touch)
	{
		Collider[] componentsInChildren = ((Component)v).GetComponentsInChildren<Collider>();
		foreach (Collider val in componentsInChildren)
		{
			if ((Object)(object)val == (Object)null || val.isTrigger)
			{
				continue;
			}
			Collider[] componentsInChildren2 = ((Component)c).GetComponentsInChildren<Collider>();
			foreach (Collider val2 in componentsInChildren2)
			{
				if ((Object)(object)val2 != (Object)null && !val2.isTrigger)
				{
					Physics.IgnoreCollision(val, val2, !touch);
				}
			}
		}
	}

	private static void Unweigh(Vagon v)
	{
		GameObject val = (GameObject)((AttachedF != null) ? /*isinst with value type is only supported in some contexts*/: null);
		Character val2 = (((Object)(object)val != (Object)null) ? val.GetComponent<Character>() : null);
		if (!((Object)(object)val2 == (Object)null) && !val2.IsPlayer())
		{
			val2.SetExtraMass(0f);
			Touch(v, val2, touch: true);
			Plugin.Debug("[hitch] " + ((Object)val2).name + " has its own weight back");
		}
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(Vagon), "Detach")]
	[HarmonyPriority(800)]
	private static void DetachUnweigh(Vagon __instance)
	{
		if (Joint(__instance) != null)
		{
			Unweigh(__instance);
		}
	}

	internal static float HoldHeight(Vagon v)
	{
		return Mathf.Clamp(((Object)(object)v != (Object)null) ? v.m_attachOffset.y : 0.8f, 0.4f, 1.5f);
	}

	private static void DropJoint(Vagon v)
	{
		Unweigh(v);
		ConfigurableJoint val = Joint(v);
		if (val != null && (Object)(object)val != (Object)null)
		{
			Object.Destroy((Object)(object)val);
		}
		JointF.SetValue(v, null);
		if (AttachedF != null)
		{
			AttachedF.SetValue(v, null);
		}
	}

	internal static void Update()
	{
		if (Time.time < _next)
		{
			return;
		}
		_next = Time.time + 0.2f;
		CartLoad.Begin();
		try
		{
			Each();
		}
		finally
		{
			CartLoad.End();
		}
	}

	private static void HoldSpeed(Character c, Kind k)
	{
		if (k != null && !(k.Pull <= 0f))
		{
			_pulling.Add(c);
			if (!_speeds0.ContainsKey(c))
			{
				_speeds0[c] = new float[3] { c.m_speed, c.m_runSpeed, c.m_walkSpeed };
				Plugin.Debug("[hitch] " + ((Object)c).name + " walks at " + k.Pull.ToString("0.0") + " m/s while it pulls (its own: walk " + c.m_walkSpeed.ToString("0.0") + ", jog " + c.m_speed.ToString("0.0") + ", run " + c.m_runSpeed.ToString("0.0") + ")");
			}
			c.m_walkSpeed = k.Pull;
			c.m_speed = k.Pull;
			c.m_runSpeed = k.Pull;
		}
	}

	private static void FreeSpeeds()
	{
		if (_speeds0.Count == 0)
		{
			return;
		}
		List<Character> list = null;
		foreach (KeyValuePair<Character, float[]> item in _speeds0)
		{
			if (!((Object)(object)item.Key != (Object)null) || !_pulling.Contains(item.Key))
			{
				if (list == null)
				{
					list = new List<Character>();
				}
				list.Add(item.Key);
			}
		}
		if (list == null)
		{
			return;
		}
		foreach (Character item2 in list)
		{
			if ((Object)(object)item2 != (Object)null)
			{
				item2.m_speed = _speeds0[item2][0];
				item2.m_runSpeed = _speeds0[item2][1];
				item2.m_walkSpeed = _speeds0[item2][2];
				Plugin.Debug("[hitch] " + ((Object)item2).name + " has its own speeds back");
			}
			_speeds0.Remove(item2);
		}
	}

	private static void Each()
	{
		_pulling.Clear();
		try
		{
			EachCart();
		}
		finally
		{
			FreeSpeeds();
		}
	}

	private static void EachCart()
	{
		Vagon[] array = Carts().ToArray();
		foreach (Vagon val in array)
		{
			if ((Object)(object)val == (Object)null)
			{
				continue;
			}
			ZNetView val2 = BK.View((Component)(object)val);
			if ((Object)(object)val2 == (Object)null || !val2.IsValid())
			{
				continue;
			}
			long num = val2.GetZDO().GetLong(BeastKey, 0L);
			if (num == 0)
			{
				continue;
			}
			ConfigurableJoint val3 = Joint(val);
			if (val3 != null && (Object)(object)val3 == (Object)null)
			{
				continue;
			}
			Character val4 = Beasts.Find(num);
			if ((Object)(object)val4 == (Object)null)
			{
				if ((Object)(object)val3 != (Object)null)
				{
					DropJoint(val);
					Plugin.Debug("[hitch] animal out of range, joint dropped");
				}
				continue;
			}
			Kind kind = Beasts.KindOf(val4);
			if (kind != null)
			{
				CartLoad.Add(Inv(val), Limit(val, kind), Beasts.Name(val4));
			}
			ZNetView val5 = BK.View((Component)(object)val4);
			if (val5.IsOwner())
			{
				if (!val2.IsOwner())
				{
					val2.ClaimOwnership();
				}
				if ((Object)(object)val3 == (Object)null && !Join(val, val4))
				{
					Clear(val, val4);
					Plugin.Debug("[hitch] " + ((Object)val4).name + " and its cart were too far apart: unhitched");
				}
				KeepHome(val4, num);
				HoldSpeed(val4, kind);
				PassSigns(val, val4);
				if ((Object)(object)val3 != (Object)null)
				{
					Watch(val, val4, val3);
				}
			}
			else if (val2.IsOwner() && (Object)(object)val3 != (Object)null)
			{
				DropJoint(val);
			}
		}
	}

	private static void PassSigns(Vagon v, Character c)
	{
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		if (_passed.Count > 2000)
		{
			_passed.Clear();
		}
		foreach (RoadSign item2 in RoadSign.All)
		{
			if ((Object)(object)item2 == (Object)null || Vector3.Distance(((Component)item2).transform.position, ((Component)v).transform.position) > 15f)
			{
				continue;
			}
			int item = ((Object)v).GetInstanceID() * 31 + ((Object)item2).GetInstanceID() * 7919 + ((Object)c).GetInstanceID();
			if (!_passed.Add(item))
			{
				continue;
			}
			int num = 0;
			Collider[] componentsInChildren = ((Component)item2).GetComponentsInChildren<Collider>();
			foreach (Collider val in componentsInChildren)
			{
				if ((Object)(object)val == (Object)null || val.isTrigger)
				{
					continue;
				}
				Collider[] componentsInChildren2 = ((Component)v).GetComponentsInChildren<Collider>();
				foreach (Collider val2 in componentsInChildren2)
				{
					if ((Object)(object)val2 != (Object)null && !val2.isTrigger)
					{
						Physics.IgnoreCollision(val, val2, true);
						num++;
					}
				}
				Collider[] componentsInChildren3 = ((Component)c).GetComponentsInChildren<Collider>();
				foreach (Collider val3 in componentsInChildren3)
				{
					if ((Object)(object)val3 != (Object)null && !val3.isTrigger)
					{
						Physics.IgnoreCollision(val, val3, true);
						num++;
					}
				}
			}
			Plugin.Debug("[hitch] " + ((Object)c).name + " and its cart pass through the road sign '" + item2.Name + "' (" + num + " collider pairs)");
		}
	}

	private static void Watch(Vagon v, Character c, ConfigurableJoint j)
	{
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Unknown result type (might be due to invalid IL or missing references)
		//IL_011b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0109: Unknown result type (might be due to invalid IL or missing references)
		//IL_0120: 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_0181: Unknown result type (might be due to invalid IL or missing references)
		//IL_018c: Unknown result type (might be due to invalid IL or missing references)
		//IL_018e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0233: Unknown result type (might be due to invalid IL or missing references)
		//IL_0238: Unknown result type (might be due to invalid IL or missing references)
		//IL_0264: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b6: 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_02f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_02fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_0304: Unknown result type (might be due to invalid IL or missing references)
		//IL_0309: Unknown result type (might be due to invalid IL or missing references)
		//IL_0333: 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)
		if (!Plugin.DetailedLog.Value)
		{
			return;
		}
		Player localPlayer = Player.m_localPlayer;
		if ((Object)(object)localPlayer == (Object)null || BK.Rider(c) != localPlayer.GetPlayerID())
		{
			_stuckFor = 0f;
			_stuckTold = false;
			return;
		}
		Vector3 velocity = c.GetVelocity();
		velocity.y = 0f;
		float magnitude = ((Vector3)(ref velocity)).magnitude;
		Rigidbody component = ((Component)v).GetComponent<Rigidbody>();
		float num;
		if (!((Object)(object)component != (Object)null))
		{
			num = -1f;
		}
		else
		{
			Vector3 linearVelocity = component.linearVelocity;
			num = ((Vector3)(ref linearVelocity)).magnitude;
		}
		float num2 = num;
		if (Time.time >= _speedLogAt)
		{
			_speedLogAt = Time.time + 5f;
			Plugin.Debug("[hitch] riding " + ((Object)c).name + " at " + magnitude.ToString("0.0") + " m/s, cart " + num2.ToString("0.0") + " m/s");
		}
		Vector3 val = (Vector3)((MoveDirF != null) ? ((Vector3)MoveDirF.GetValue(c)) : Vector3.zero);
		if (((Vector3)(ref val)).magnitude < 0.5f || magnitude > 0.6f)
		{
			_stuckFor = 0f;
			_stuckTold = false;
			return;
		}
		_stuckFor += 0.2f;
		if (!(_stuckFor < 0.6f) && !_stuckTold)
		{
			_stuckTold = true;
			Vector3 val2 = AnchorOf(v);
			float num3 = Vector3.Distance(v.m_attachPoint.position, ((Component)c).transform.TransformPoint(val2));
			object[] array = new object[29]
			{
				"[hitch] STUCK: ",
				((Object)c).name,
				" wants to move (",
				((Vector3)(ref val)).magnitude.ToString("0.0"),
				") but goes ",
				magnitude.ToString("0.0"),
				" m/s; cart ",
				num2.ToString("0.0"),
				" m/s, gap ",
				num3.ToString("0.00"),
				" m, pull ",
				null,
				null,
				null,
				null,
				null,
				null,
				null,
				null,
				null,
				null,
				null,
				null,
				null,
				null,
				null,
				null,
				null,
				null
			};
			Vector3 currentForce = ((Joint)j).currentForce;
			array[11] = ((Vector3)(ref currentForce)).magnitude.ToString("0");
			array[12] = ", cart up ";
			float y = ((Component)v).transform.up.y;
			array[13] = y.ToString("0.00");
			array[14] = ", on ground ";
			array[15] = c.IsOnGround();
			array[16] = "; ahead of it: ";
			array[17] = Ahead(((Component)c).transform, ((Component)c).transform.position + Vector3.up * 0.6f, 2.5f, ((Component)v).transform);
			array[18] = "; ahead of the cart: ";
			array[19] = Ahead(((Component)v).transform, ((Component)v).transform.position + Vector3.up * 0.4f, 2f, ((Component)c).transform);
			array[20] = "; under the cart: ";
			array[21] = Below(((Component)v).transform.position);
			array[22] = "; under it: ";
			array[23] = Below(((Component)c).transform.position);
			array[24] = "; the cart touches: ";
			array[25] = Touching(((Component)v).gameObject, ((Component)c).transform, ((Component)v).transform);
			array[26] = "; it touches: ";
			array[27] = Touching(((Component)c).gameObject, ((Component)c).transform, ((Component)v).transform);
			array[28] = (Roads.Recording ? "; recording a road" : "");
			Plugin.Debug(string.Concat(array));
		}
	}

	private static string Ahead(Transform t, Vector3 from, float range, Transform other)
	{
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_0057: Unknown result type (might be due to invalid IL or missing references)
		//IL_0066: Unknown result type (might be due to invalid IL or missing references)
		//IL_006e: 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_0092: 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_00f7: 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_00dd: Unknown result type (might be due to invalid IL or missing references)
		if (_blockMask == 0)
		{
			_blockMask = LayerMask.GetMask(new string[6] { "Default", "static_solid", "Default_small", "piece", "terrain", "vehicle" });
		}
		Vector3 forward = t.forward;
		forward.y = 0f;
		RaycastHit hit = default(RaycastHit);
		bool flag = false;
		RaycastHit[] array = Physics.RaycastAll(from, ((Vector3)(ref forward)).normalized, range, _blockMask, (QueryTriggerInteraction)1);
		for (int i = 0; i < array.Length; i++)
		{
			RaycastHit val = array[i];
			Transform root = ((Component)((RaycastHit)(ref val)).collider).transform.root;
			if (!((Object)(object)root == (Object)(object)t.root) && !((Object)(object)root == (Object)(object)other.root) && (!flag || ((RaycastHit)(ref val)).distance < ((RaycastHit)(ref hit)).distance))
			{
				hit = val;
				flag = true;
			}
		}
		if (!flag)
		{
			return "nothing";
		}
		return Describe(hit);
	}

	private static string Touching(GameObject g, Transform a, Transform b)
	{
		//IL_009b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
		if (_blockMask == 0)
		{
			_blockMask = LayerMask.GetMask(new string[6] { "Default", "static_solid", "Default_small", "piece", "terrain", "vehicle" });
		}
		int num = LayerMask.NameToLayer("terrain");
		List<string> list = new List<string>();
		Collider[] componentsInChildren = g.GetComponentsInChildren<Collider>();
		foreach (Collider val in componentsInChildren)
		{
			if ((Object)(object)val == (Object)null || val.isTrigger || !val.enabled)
			{
				continue;
			}
			Bounds bounds = val.bounds;
			Collider[] array = Physics.OverlapBox(((Bounds)(ref bounds)).center, ((Bounds)(ref bounds)).extents * 1.05f, Quaternion.identity, _blockMask, (QueryTriggerInteraction)1);
			foreach (Collider val2 in array)
			{
				Transform root = ((Component)val2).transform.root;
				if (!((Object)(object)root == (Object)(object)a.root) && !((Object)(object)root == (Object)(object)b.root) && ((Component)val2).gameObject.layer != num)
				{
					string item = ((Object)val2).name + (((Object)(object)root != (Object)(object)((Component)val2).transform) ? (" of " + ((Object)root).name) : "") + " (" + LayerMask.LayerToName(((Component)val2).gameObject.layer) + ")";
					if (!list.Contains(item))
					{
						list.Add(item);
					}
					if (list.Count >= 5)
					{
						break;
					}
				}
			}
		}
		if (list.Count != 0)
		{
			return string.Join(", ", list.ToArray());
		}
		return "nothing";
	}

	private static string Below(Vector3 at)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		RaycastHit hit = default(RaycastHit);
		if (!Physics.Raycast(at + Vector3.up * 0.5f, Vector3.down, ref hit, 3f, _blockMask, (QueryTriggerInteraction)1))
		{
			return "nothing";
		}
		return Describe(hit) + ", slope " + Vector3.Angle(((RaycastHit)(ref hit)).normal, Vector3.up).ToString("0") + " deg";
	}

	private static string Describe(RaycastHit hit)
	{
		Transform root = ((Component)((RaycastHit)(ref hit)).collider).transform.root;
		return ((Object)((RaycastHit)(ref hit)).collider).name + (((Object)(object)root != (Object)(object)((Component)((RaycastHit)(ref hit)).collider).transform) ? (" of " + ((Object)root).name) : "") + " (layer " + LayerMask.LayerToName(((Component)((RaycastHit)(ref hit)).collider).gameObject.layer) + ", " + ((RaycastHit)(ref hit)).distance.ToString("0.0") + " m)";
	}

	private static void KeepHome(Character c, long id)
	{
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0040: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: 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_005a: 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)
		if (!_homeAt.TryGetValue(id, out var value) || !(Time.time < value))
		{
			_homeAt[id] = Time.time + 0.5f;
			ZDO val = BK.Zdo((Component)(object)c);
			Vector3 vec = val.GetVec3(BK.HomeKey, Vector3.zero);
			if (vec != Vector3.zero && Vector3.Distance(vec, ((Component)c).transform.position) > 0.5f)
			{
				val.Set(BK.HomeKey, ((Component)c).transform.position);
			}
		}
	}

	[HarmonyPatch(typeof(ImpactEffect), "OnCollisionEnter")]
	[HarmonyPrefix]
	private static bool CartKnock(ImpactEffect __instance, Collision __0)
	{
		//IL_0071: Unknown result type (might be due to invalid IL or missing references)
		//IL_0076: Unknown result type (might be due to invalid IL or missing references)
		Vagon component = ((Component)__instance).GetComponent<Vagon>();
		if ((Object)(object)component == (Object)null)
		{
			return true;
		}
		ZDO val = BK.Zdo((Component)(object)component);
		long num = ((val != null) ? val.GetLong(BeastKey, 0L) : 0);
		if (num == 0 || __0 == null)
		{
			return true;
		}
		Character val2 = Beasts.Find(num);
		if ((Object)(object)val2 != (Object)null && (Object)(object)__0.collider != (Object)null && ((Component)__0.collider).transform.IsChildOf(((Component)val2).transform))
		{
			return false;
		}
		Vector3 relativeVelocity = __0.relativeVelocity;
		if (((Vector3)(ref relativeVelocity)).magnitude >= 8f)
		{
			return true;
		}
		return false;
	}

	[HarmonyPatch(typeof(Vagon), "Awake")]
	[HarmonyPostfix]
	private static void CartAwake(Vagon __instance)
	{
		if (BK.Zdo((Component)(object)__instance) != null && (Object)(object)((Component)__instance).GetComponent<CartRopes>() == (Object)null)
		{
			((Component)__instance).gameObject.AddComponent<CartRopes>();
		}
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(Vagon), "Detach")]
	private static bool DetachPre(Vagon __instance)
	{
		//IL_0187: 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_007b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ad: 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_0110: Unknown result type (might be due to invalid IL or missing references)
		//IL_0115: Unknown result type (might be due to invalid IL or missing references)
		if (_unhitching || !Plugin.Enabled.Value)
		{
			return true;
		}
		ZNetView val = BK.View((Component)(object)__instance);
		if ((Object)(object)val == (Object)null || !val.IsValid() || !val.IsOwner())
		{
			return true;
		}
		long num = val.GetZDO().GetLong(BeastKey, 0L);
		if (num == 0)
		{
			return true;
		}
		object value = JointF.GetValue(__instance);
		if (value == null)
		{
			return false;
		}
		Character val2 = Beasts.Find(num);
		if ((Object)(object)val2 != (Object)null)
		{
			Vector3 val3 = AnchorOf(__instance);
			Rigidbody component = ((Component)val2).GetComponent<Rigidbody>();
			object[] array = new object[10]
			{
				"[hitch] coming loose: gap ",
				Vector3.Distance(__instance.m_attachPoint.position, ((Component)val2).transform.TransformPoint(val3)).ToString("0.0"),
				" m, cart up ",
				null,
				null,
				null,
				null,
				null,
				null,
				null
			};
			float y = ((Component)__instance).transform.up.y;
			array[3] = y.ToString("0.00");
			array[4] = ", animal speed ";
			object obj;
			if (!((Object)(object)component != (Object)null))
			{
				obj = "?";
			}
			else
			{
				Vector3 linearVelocity = component.linearVelocity;
				obj = ((Vector3)(ref linearVelocity)).magnitude.ToString("0.0");
			}
			array[5] = obj;
			array[6] = ", ridden ";
			array[7] = BK.Ridden(val2);
			array[8] = ", dead ";
			array[9] = val2.IsDead();
			Plugin.Debug(string.Concat(array));
		}
		val.GetZDO().Set(BeastKey, 0L);
		val.GetZDO().Set(AnchorKey, Vector3.zero);
		if ((Object)(object)val2 != (Object)null)
		{
			ZNetView val4 = BK.View((Component)(object)val2);
			if (val4.IsOwner())
			{
				val4.GetZDO().Set(Beasts.CartKey, 0L);
			}
			if (BK.RiddenBy(val2, Player.m_localPlayer))
			{
				Plugin.Say(Player.m_localPlayer, "The cart came loose from " + Beasts.Name(val2) + ".");
			}
		}
		Plugin.Debug("[hitch] the cart came loose");
		return true;
	}

	[HarmonyPatch(typeof(Vagon), "DetachAll")]
	[HarmonyPrefix]
	private static bool DetachAllPre()
	{
		if (!Plugin.Enabled.Value || DetachM == null)
		{
			return true;
		}
		Vagon[] array = Carts().ToArray();
		foreach (Vagon val in array)
		{
			if ((Object)(object)val != (Object)null && BeastOf(val) == 0)
			{
				DetachM.Invoke(val, null);
			}
		}
		return false;
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(Vagon), "CanAttach")]
	private static bool CanAttachPre(Vagon __instance, GameObject go, ref bool __result)
	{
		//IL_003e: 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_004b: 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_0075: 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)
		Character val = (((Object)(object)go != (Object)null) ? go.GetComponent<Character>() : null);
		if ((Object)(object)val == (Object)null || val.IsPlayer())
		{
			return true;
		}
		long num = Beasts.Id(val);
		if (num == 0 || BeastOf(__instance) != num)
		{
			return true;
		}
		Vector3 val2 = AnchorOf(__instance);
		__result = ((Component)__instance).transform.up.y >= 0.1f && !val.IsDead() && Vector3.Distance(__instance.m_attachPoint.position, ((Component)val).transform.TransformPoint(val2)) < 10f;
		return false;
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(Vagon), "UpdateMass")]
	private static bool UpdateMassPre(Vagon __instance)
	{
		if (!Plugin.Enabled.Value || SetMassM == null)
		{
			return true;
		}
		ZNetView val = BK.View((Component)(object)__instance);
		if ((Object)(object)val == (Object)null || !val.IsValid() || !val.IsOwner())
		{
			return true;
		}
		long num = val.GetZDO().GetLong(BeastKey, 0L);
		if (num == 0)
		{
			return true;
		}
		Character val2 = Beasts.Find(num);
		if ((Object)(object)val2 == (Object)null || TooFull(__instance, val2))
		{
			return true;
		}
		SetMassM.Invoke(__instance, new object[1] { __instance.m_baseMass });
		return false;
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(Vagon), "LateUpdate")]
	private static void HideLine(Vagon __instance)
	{
		if (BeastOf(__instance) != 0)
		{
			LineRenderer val = (LineRenderer)((LineF != null) ? /*isinst with value type is only supported in some contexts*/: null);
			if ((Object)(object)val != (Object)null)
			{
				((Renderer)val).enabled = false;
			}
		}
	}

	[HarmonyPatch(typeof(Vagon), "Interact")]
	[HarmonyPrefix]
	private static bool CartInteract(Vagon __instance, Humanoid character, bool hold, ref bool __result)
	{
		if (!Plugin.Enabled.Value)
		{
			return true;
		}
		long num = BeastOf(__instance);
		if (num == 0)
		{
			return true;
		}
		Character val = Beasts.Find(num);
		if ((Object)(object)val == (Object)null)
		{
			if (!hold)
			{
				Clear(__instance, null);
			}
			return !hold;
		}
		Player val2 = (Player)(object)((character is Player) ? character : null);
		__result = false;
		if ((Object)(object)val2 != (Object)(object)Player.m_localPlayer)
		{
			return false;
		}
		if (!hold || (Object)(object)_holdCart != (Object)(object)__instance)
		{
			_holdCart = __instance;
			_holdFrom = Time.time;
			_holdDone = false;
			if (!hold)
			{
				Plugin.Say(val2, "Hold E on the handle to unhitch " + Beasts.Name(val) + ".");
			}
			return false;
		}
		if (!_holdDone && Time.time - _holdFrom >= 0.6f)
		{
			_holdDone = true;
			Unhitch(val2, val);
			__result = true;
		}
		return false;
	}

	[HarmonyPatch(typeof(Player), "Interact")]
	[HarmonyPrefix]
	[HarmonyPriority(800)]
	[HarmonyBefore(new string[] { "felih.Beastkeeper" })]
	private static bool PlayerInteract(Player __instance, GameObject go, bool hold, bool alt)
	{
		if (!Plugin.Enabled.Value || (Object)(object)__instance != (Object)(object)Player.m_localPlayer || (Object)(object)go == (Object)null || hold || alt)
		{
			return true;
		}
		if ((Object)(object)go.GetComponentInParent<Character>() != (Object)null)
		{
			return true;
		}
		Vagon componentInParent = go.GetComponentInParent<Vagon>();
		if ((Object)(object)componentInParent == (Object)null)
		{
			return true;
		}
		if (BeastOf(componentInParent) != 0 && (Object)(object)Beasts.Find(BeastOf(componentInParent)) != (Object)null)
		{
			return true;
		}
		Character val = OnMyRope(__instance, componentInParent);
		if ((Object)(object)val == (Object)null)
		{
			return true;
		}
		HandledFrame = Time.frameCount;
		TryHitch(__instance, componentInParent, val);
		return false;
	}

	[HarmonyPriority(800)]
	[HarmonyPatch(typeof(MonsterAI), "UpdateAI")]
	[HarmonyPrefix]
	private static bool MonsterStand(MonsterAI __instance, ref bool __result)
	{
		return Stand((BaseAI)(object)__instance, ref __result);
	}

	[HarmonyPriority(800)]
	[HarmonyPatch(typeof(AnimalAI), "UpdateAI")]
	[HarmonyPrefix]
	private static bool AnimalStand(AnimalAI __instance, ref bool __result)
	{
		return Stand((BaseAI)(object)__instance, ref __result);
	}

	private static bool Stand(BaseAI ai, ref bool result)
	{
		if (!Plugin.Enabled.Value)
		{
			return true;
		}
		ZNetView val = AIView(ai);
		if ((Object)(object)val == (Object)null || !val.IsValid())
		{
			return true;
		}
		ZDO zDO = val.GetZDO();
		if (zDO.GetLong(Beasts.CartKey, 0L) == 0 || zDO.GetLong(BK.RiderKey, 0L) != 0)
		{
			return true;
		}
		ai.StopMoving();
		result = true;
		return false;
	}

	[HarmonyPostfix]
	[HarmonyPriority(0)]
	[HarmonyPatch(typeof(MonsterAI), "UpdateAI")]
	private static void MonsterStill(MonsterAI __instance)
	{
		Still((BaseAI)(object)__instance);
	}

	[HarmonyPriority(0)]
	[HarmonyPostfix]
	[HarmonyPatch(typeof(AnimalAI), "UpdateAI")]
	private static void AnimalStill(AnimalAI __instance)
	{
		Still((BaseAI)(object)__instance);
	}

	private static void Still(BaseAI ai)
	{
		if (!Plugin.Enabled.Value)
		{
			return;
		}
		ZNetView val = AIView(ai);
		if (!((Object)(object)val == (Object)null) && val.IsValid() && val.IsOwner())
		{
			ZDO zDO = val.GetZDO();
			if (zDO.GetLong(Beasts.CartKey, 0L) != 0 && zDO.GetLong(BK.RiderKey, 0L) == 0)
			{
				ai.StopMoving();
			}
		}
	}

	[HarmonyPostfix]
	[HarmonyPriority(200)]
	[HarmonyPatch(typeof(Tameable), "GetHoverText")]
	private static void TameHover(Tameable __instance, ref string __result)
	{
		__result += HoverLine(((Component)__instance).GetComponent<Character>());
	}

	[HarmonyPatch(typeof(Character), "GetHoverText")]
	[HarmonyPostfix]
	[HarmonyPriority(200)]
	private static void CharHover(Character __instance, ref string __result)
	{
		if (!((Object)(object)((Component)__instance).GetComponent<Tameable>() != (Object)null))
		{
			__result += HoverLine(__instance);
		}
	}

	private static string HoverLine(Character c)
	{
		if (!Plugin.Enabled.Value || (Object)(object)c == (Object)null || !IsHitched(c))
		{
			return "";
		}
		string text = "\n<color=#d8b080>Pulling a cart</color> (hold [<color=yellow><b>E</b></color>] on the cart's handle to unhitch)";
		Vagon val = CartOf(c);
		if ((Object)(object)val != (Object)null && TooFull(val, c))
		{
			text += "\n<color=#ff9060>The cart is too full for it</color>";
		}
		return text;
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(Vagon), "GetHoverText")]
	private static void CartHover(Vagon __instance, ref string __result)
	{
		if (!Plugin.Enabled.Value)
		{
			return;
		}
		Player localPlayer = Player.m_localPlayer;
		string text = Localization.instance.Localize(__instance.m_name);
		long num = BeastOf(__instance);
		Character val = ((num != 0) ? Beasts.Find(num) : null);
		if ((Object)(object)val != (Object)null)
		{
			Kind kind = Beasts.KindOf(val);
			string text2 = ((kind != null) ? ("\nLoad " + Load(__instance, kind)) : "");
			if (kind != null && TooFull(__instance, val))
			{
				te