Decompiled source of Hogtied v0.1.0

Hogtied.dll

Decompiled 4 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Hogtied.Client;
using Hogtied.Host;
using Hogtied.Net;
using Hogtied.Shared;
using Microsoft.CodeAnalysis;
using TMPro;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Hogtied")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+e40bc8e654bf23d6a33d285eeab1379a4658b002")]
[assembly: AssemblyProduct("Hogtied")]
[assembly: AssemblyTitle("Hogtied")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Hogtied
{
	public static class HogtieState
	{
		private readonly struct Identity : IEquatable<Identity>
		{
			public readonly bool Steam;

			public readonly ulong Id;

			public Identity(bool steam, ulong id)
			{
				Steam = steam;
				Id = id;
			}

			public bool Equals(Identity other)
			{
				if (Steam == other.Steam)
				{
					return Id == other.Id;
				}
				return false;
			}

			public override bool Equals(object obj)
			{
				if (obj is Identity other)
				{
					return Equals(other);
				}
				return false;
			}

			public override int GetHashCode()
			{
				return (Id.GetHashCode() * 397) ^ (Steam ? 1 : 0);
			}

			public override string ToString()
			{
				if (!Steam)
				{
					return $"client:{Id}";
				}
				return $"steam:{Id}";
			}
		}

		private static readonly HashSet<ulong> _clientIds = new HashSet<ulong>();

		private static readonly HashSet<Identity> _hostIdentities = new HashSet<Identity>();

		private static HashSet<ulong> _lastBroadcast = new HashSet<ulong>();

		public static IReadOnlyCollection<ulong> HogtiedClientIds => _clientIds;

		public static bool IsLocalHogtied => _clientIds.Contains(Players.LocalClientId);

		public static event Action Changed;

		public static event Action LocalBecameHogtied;

		public static bool IsHogtied(ulong clientId)
		{
			return _clientIds.Contains(clientId);
		}

		internal static void ApplyFromHost(IEnumerable<ulong> clientIds)
		{
			HashSet<ulong> hashSet = new HashSet<ulong>(clientIds);
			if (!hashSet.SetEquals(_clientIds))
			{
				bool isLocalHogtied = IsLocalHogtied;
				_clientIds.Clear();
				_clientIds.UnionWith(hashSet);
				Raise(HogtieState.Changed, "Changed");
				if (!isLocalHogtied && IsLocalHogtied)
				{
					Raise(HogtieState.LocalBecameHogtied, "LocalBecameHogtied");
				}
			}
		}

		private static void Raise(Action handler, string name)
		{
			if (handler == null)
			{
				return;
			}
			Delegate[] invocationList = handler.GetInvocationList();
			for (int i = 0; i < invocationList.Length; i++)
			{
				Action action = (Action)invocationList[i];
				try
				{
					action();
				}
				catch (Exception arg)
				{
					Plugin.Log.LogError((object)$"HogtieState.{name} handler failed: {arg}");
				}
			}
		}

		private static bool TryGetIdentity(ulong clientId, out Identity identity)
		{
			identity = default(Identity);
			PlayerControllerB val = Players.ByClientId(clientId);
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			if ((Object)(object)GameNetworkManager.Instance == (Object)null || GameNetworkManager.Instance.disableSteam)
			{
				identity = new Identity(steam: false, clientId);
				return true;
			}
			if (!val.sentPlayerValues)
			{
				return false;
			}
			identity = ((val.playerSteamId != 0L) ? new Identity(steam: true, val.playerSteamId) : new Identity(steam: false, clientId));
			return true;
		}

		internal static bool HostCanIdentify(ulong clientId)
		{
			Identity identity;
			return TryGetIdentity(clientId, out identity);
		}

		internal static bool HostIsHogtied(ulong clientId)
		{
			if (TryGetIdentity(clientId, out var identity))
			{
				return _hostIdentities.Contains(identity);
			}
			return false;
		}

		internal static bool HostSet(ulong clientId, bool hogtied)
		{
			if (!Players.IsHost || !TryGetIdentity(clientId, out var identity))
			{
				return false;
			}
			if (hogtied ? _hostIdentities.Add(identity) : _hostIdentities.Remove(identity))
			{
				Plugin.Log.LogInfo((object)string.Format("{0} {1} ({2})", hogtied ? "Hogtied" : "Untied", Players.NameOf(clientId), identity));
			}
			HostTick();
			return true;
		}

		internal static ulong[] HostConnectedHogtied()
		{
			return (from id in Players.ConnectedClientIds().Where(HostIsHogtied)
				orderby id
				select id).ToArray();
		}

		internal static void HostTick()
		{
			if (Players.IsHost)
			{
				HashSet<ulong> hashSet = new HashSet<ulong>(HostConnectedHogtied());
				if (!hashSet.SetEquals(_lastBroadcast))
				{
					Messages.BroadcastState(hashSet.ToArray());
					_lastBroadcast = hashSet;
				}
			}
		}

		internal static void Reset()
		{
			_hostIdentities.Clear();
			_lastBroadcast = new HashSet<ulong>();
			if (_clientIds.Count != 0)
			{
				_clientIds.Clear();
				Raise(HogtieState.Changed, "Changed");
			}
		}
	}
	[BepInPlugin("hogtied", "Hogtied", "0.1.0")]
	public class Plugin : BaseUnityPlugin
	{
		private Harmony _harmony;

		public static Plugin Instance { get; private set; }

		public static ManualLogSource Log { get; private set; }

		private void Awake()
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			PluginConfig.Bind(((BaseUnityPlugin)this).Config);
			_harmony = new Harmony("hogtied");
			Install("RpcGate", RpcGate.Install);
			Install("Messages", Messages.Install);
			Install("ChatCommands", ChatCommands.Install);
			Install("VoteManager", VoteManager.Install);
			Install("HostRejections", HostRejections.Install);
			Install("LocalBlocks", LocalBlocks.Install);
			Install("TerminalCommands", TerminalCommands.Install);
			Install("VotePopup", VotePopup.Install);
			Log.LogInfo((object)"Hogtied 0.1.0 loaded");
		}

		private void Install(string module, Action<Harmony> install)
		{
			try
			{
				install(_harmony);
			}
			catch (Exception arg)
			{
				Log.LogError((object)$"Module {module} failed to install: {arg}");
			}
		}
	}
	internal static class PluginConfig
	{
		public static ConfigEntry<int> VoteDurationSeconds { get; private set; }

		public static ConfigEntry<int> FailedVoteCooldownSeconds { get; private set; }

		public static ConfigEntry<bool> DebugCommands { get; private set; }

		public static void Bind(ConfigFile config)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Expected O, but got Unknown
			VoteDurationSeconds = config.Bind<int>("Voting", "VoteDurationSeconds", 30, new ConfigDescription("How long a vote runs, in seconds.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(5, 300), Array.Empty<object>()));
			FailedVoteCooldownSeconds = config.Bind<int>("Voting", "FailedVoteCooldownSeconds", 60, new ConfigDescription("Seconds a player must wait to start another vote after one they started fails.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 3600), Array.Empty<object>()));
			DebugCommands = config.Bind<bool>("Debug", "DebugCommands", false, "Host-only /forcetie, /forceuntie and /testvote commands for solo testing.");
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "hogtied";

		public const string PLUGIN_NAME = "Hogtied";

		public const string PLUGIN_VERSION = "0.1.0";
	}
}
namespace Hogtied.Shared
{
	public static class NameMatcher
	{
		public static bool TryMatch(string query, out ulong clientId, out PlayerControllerB player, out string error)
		{
			return TryMatch(query, Players.Connected(), out clientId, out player, out error);
		}

		public static bool TryMatch(string query, IEnumerable<KeyValuePair<ulong, PlayerControllerB>> candidates, out ulong clientId, out PlayerControllerB player, out string error)
		{
			clientId = 0uL;
			player = null;
			string q = (query ?? "").Trim().Trim('"', '\'').Trim();
			if (q.Length == 0)
			{
				error = "No player name given.";
				return false;
			}
			List<KeyValuePair<ulong, PlayerControllerB>> source = candidates.Where((KeyValuePair<ulong, PlayerControllerB> c) => (Object)(object)c.Value != (Object)null && !string.IsNullOrEmpty(c.Value.playerUsername)).ToList();
			List<KeyValuePair<ulong, PlayerControllerB>> list = source.Where((KeyValuePair<ulong, PlayerControllerB> c) => string.Equals(c.Value.playerUsername, q, StringComparison.OrdinalIgnoreCase)).ToList();
			if (list.Count == 0)
			{
				list = source.Where((KeyValuePair<ulong, PlayerControllerB> c) => c.Value.playerUsername.StartsWith(q, StringComparison.OrdinalIgnoreCase)).ToList();
			}
			if (list.Count == 0)
			{
				list = source.Where((KeyValuePair<ulong, PlayerControllerB> c) => c.Value.playerUsername.IndexOf(q, StringComparison.OrdinalIgnoreCase) >= 0).ToList();
			}
			if (list.Count == 1)
			{
				clientId = list[0].Key;
				player = list[0].Value;
				error = null;
				return true;
			}
			error = ((list.Count == 0) ? ("No player matches '" + q + "'.") : ("'" + q + "' matches several players: " + string.Join(", ", list.Select((KeyValuePair<ulong, PlayerControllerB> m) => m.Value.playerUsername)) + "."));
			return false;
		}
	}
	public static class Players
	{
		public static bool IsHost
		{
			get
			{
				NetworkManager singleton = NetworkManager.Singleton;
				if ((Object)(object)singleton != (Object)null && singleton.IsListening)
				{
					return singleton.IsServer;
				}
				return false;
			}
		}

		public static ulong LocalClientId
		{
			get
			{
				if (!((Object)(object)NetworkManager.Singleton != (Object)null))
				{
					return 0uL;
				}
				return NetworkManager.Singleton.LocalClientId;
			}
		}

		public static PlayerControllerB Local
		{
			get
			{
				if (!((Object)(object)GameNetworkManager.Instance != (Object)null))
				{
					return null;
				}
				return GameNetworkManager.Instance.localPlayerController;
			}
		}

		public static bool IsLocal(PlayerControllerB player)
		{
			if ((Object)(object)player != (Object)null)
			{
				return (Object)(object)player == (Object)(object)Local;
			}
			return false;
		}

		public static bool IsConnected(ulong clientId)
		{
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance != (Object)null)
			{
				return instance.ClientPlayerList.ContainsKey(clientId);
			}
			return false;
		}

		public static PlayerControllerB ByClientId(ulong clientId)
		{
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null || !instance.ClientPlayerList.TryGetValue(clientId, out var value))
			{
				return null;
			}
			PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts;
			if (value < 0 || value >= allPlayerScripts.Length)
			{
				return null;
			}
			return allPlayerScripts[value];
		}

		public static bool TryGetClientId(PlayerControllerB player, out ulong clientId)
		{
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance != (Object)null && (Object)(object)player != (Object)null)
			{
				foreach (KeyValuePair<ulong, int> clientPlayer in instance.ClientPlayerList)
				{
					if (clientPlayer.Value >= 0 && clientPlayer.Value < instance.allPlayerScripts.Length && (Object)(object)instance.allPlayerScripts[clientPlayer.Value] == (Object)(object)player)
					{
						clientId = clientPlayer.Key;
						return true;
					}
				}
			}
			clientId = 0uL;
			return false;
		}

		public static string NameOf(ulong clientId)
		{
			PlayerControllerB val = ByClientId(clientId);
			if (!((Object)(object)val != (Object)null))
			{
				return $"Player {clientId}";
			}
			return val.playerUsername;
		}

		public static List<ulong> ConnectedClientIds()
		{
			StartOfRound instance = StartOfRound.Instance;
			if (!((Object)(object)instance != (Object)null))
			{
				return new List<ulong>();
			}
			return new List<ulong>(instance.ClientPlayerList.Keys);
		}

		public static List<KeyValuePair<ulong, PlayerControllerB>> Connected()
		{
			List<KeyValuePair<ulong, PlayerControllerB>> list = new List<KeyValuePair<ulong, PlayerControllerB>>();
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return list;
			}
			foreach (KeyValuePair<ulong, int> clientPlayer in instance.ClientPlayerList)
			{
				if (clientPlayer.Value >= 0 && clientPlayer.Value < instance.allPlayerScripts.Length && (Object)(object)instance.allPlayerScripts[clientPlayer.Value] != (Object)null)
				{
					list.Add(new KeyValuePair<ulong, PlayerControllerB>(clientPlayer.Key, instance.allPlayerScripts[clientPlayer.Value]));
				}
			}
			return list;
		}
	}
	public enum VoteKind : byte
	{
		Hogtie,
		Untie,
		Test
	}
	public enum VoteStatus : byte
	{
		Running,
		Passed,
		Failed
	}
	public sealed class VoteSnapshot
	{
		public const ulong NoTarget = ulong.MaxValue;

		public int Id;

		public VoteKind Kind;

		public ulong StarterClientId;

		public string StarterName = "";

		public ulong TargetClientId = ulong.MaxValue;

		public string TargetName = "";

		public float SecondsLeft;

		public int Yes;

		public int No;

		public int Needed;

		public VoteStatus Status;

		public ulong[] YesVoters = Array.Empty<ulong>();

		public ulong[] NoVoters = Array.Empty<ulong>();

		public bool IsRunning => Status == VoteStatus.Running;

		internal int MaxSize => 576 + 8 * (YesVoters.Length + NoVoters.Length);

		public bool CanVote(ulong clientId)
		{
			return clientId != TargetClientId;
		}

		public bool? BallotOf(ulong clientId)
		{
			if (YesVoters.Contains(clientId))
			{
				return true;
			}
			if (NoVoters.Contains(clientId))
			{
				return false;
			}
			return null;
		}

		internal void Write(FastBufferWriter w)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: 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_0039: 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_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: 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_00a9: 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_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			((FastBufferWriter)(ref w)).WriteValueSafe<int>(ref Id, default(ForPrimitives));
			byte kind = (byte)Kind;
			((FastBufferWriter)(ref w)).WriteValueSafe<byte>(ref kind, default(ForPrimitives));
			((FastBufferWriter)(ref w)).WriteValueSafe<ulong>(ref StarterClientId, default(ForPrimitives));
			((FastBufferWriter)(ref w)).WriteValueSafe(StarterName ?? "", false);
			((FastBufferWriter)(ref w)).WriteValueSafe<ulong>(ref TargetClientId, default(ForPrimitives));
			((FastBufferWriter)(ref w)).WriteValueSafe(TargetName ?? "", false);
			((FastBufferWriter)(ref w)).WriteValueSafe<float>(ref SecondsLeft, default(ForPrimitives));
			((FastBufferWriter)(ref w)).WriteValueSafe<int>(ref Yes, default(ForPrimitives));
			((FastBufferWriter)(ref w)).WriteValueSafe<int>(ref No, default(ForPrimitives));
			((FastBufferWriter)(ref w)).WriteValueSafe<int>(ref Needed, default(ForPrimitives));
			kind = (byte)Status;
			((FastBufferWriter)(ref w)).WriteValueSafe<byte>(ref kind, default(ForPrimitives));
			WriteIds(w, YesVoters);
			WriteIds(w, NoVoters);
		}

		internal static VoteSnapshot Read(FastBufferReader r)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: 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_003f: 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_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: 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_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: 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)
			VoteSnapshot voteSnapshot = new VoteSnapshot();
			((FastBufferReader)(ref r)).ReadValueSafe<int>(ref voteSnapshot.Id, default(ForPrimitives));
			byte kind = default(byte);
			((FastBufferReader)(ref r)).ReadValueSafe<byte>(ref kind, default(ForPrimitives));
			voteSnapshot.Kind = (VoteKind)kind;
			((FastBufferReader)(ref r)).ReadValueSafe<ulong>(ref voteSnapshot.StarterClientId, default(ForPrimitives));
			((FastBufferReader)(ref r)).ReadValueSafe(ref voteSnapshot.StarterName, false);
			((FastBufferReader)(ref r)).ReadValueSafe<ulong>(ref voteSnapshot.TargetClientId, default(ForPrimitives));
			((FastBufferReader)(ref r)).ReadValueSafe(ref voteSnapshot.TargetName, false);
			((FastBufferReader)(ref r)).ReadValueSafe<float>(ref voteSnapshot.SecondsLeft, default(ForPrimitives));
			((FastBufferReader)(ref r)).ReadValueSafe<int>(ref voteSnapshot.Yes, default(ForPrimitives));
			((FastBufferReader)(ref r)).ReadValueSafe<int>(ref voteSnapshot.No, default(ForPrimitives));
			((FastBufferReader)(ref r)).ReadValueSafe<int>(ref voteSnapshot.Needed, default(ForPrimitives));
			byte status = default(byte);
			((FastBufferReader)(ref r)).ReadValueSafe<byte>(ref status, default(ForPrimitives));
			voteSnapshot.Status = (VoteStatus)status;
			voteSnapshot.YesVoters = ReadIds(r);
			voteSnapshot.NoVoters = ReadIds(r);
			return voteSnapshot;
		}

		internal static void WriteIds(FastBufferWriter w, ulong[] ids)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			int num = ids.Length;
			((FastBufferWriter)(ref w)).WriteValueSafe<int>(ref num, default(ForPrimitives));
			for (num = 0; num < ids.Length; num++)
			{
				ulong num2 = ids[num];
				((FastBufferWriter)(ref w)).WriteValueSafe<ulong>(ref num2, default(ForPrimitives));
			}
		}

		internal static ulong[] ReadIds(FastBufferReader r)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			int num = default(int);
			((FastBufferReader)(ref r)).ReadValueSafe<int>(ref num, default(ForPrimitives));
			if (num < 0 || num > 1024)
			{
				throw new InvalidOperationException($"Bad id count {num}");
			}
			ulong[] array = new ulong[num];
			for (int i = 0; i < num; i++)
			{
				((FastBufferReader)(ref r)).ReadValueSafe<ulong>(ref array[i], default(ForPrimitives));
			}
			return array;
		}
	}
	public static class VoteState
	{
		private static float _receivedAt;

		public static VoteSnapshot Current
		{
			get
			{
				if (Last == null || !Last.IsRunning)
				{
					return null;
				}
				return Last;
			}
		}

		public static VoteSnapshot Last { get; private set; }

		public static float SecondsLeft
		{
			get
			{
				if (Current != null)
				{
					return Mathf.Max(0f, Current.SecondsLeft - (Time.realtimeSinceStartup - _receivedAt));
				}
				return 0f;
			}
		}

		public static event Action Updated;

		internal static void Apply(VoteSnapshot snapshot)
		{
			Last = snapshot;
			_receivedAt = Time.realtimeSinceStartup;
			Raise();
		}

		internal static void Reset()
		{
			if (Last != null)
			{
				Last = null;
				Raise();
			}
		}

		private static void Raise()
		{
			try
			{
				VoteState.Updated?.Invoke();
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"VoteState.Updated handler failed: {arg}");
			}
		}
	}
}
namespace Hogtied.Net
{
	public static class Messages
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static HandleNamedMessageDelegate <0>__OnHello;

			public static HandleNamedMessageDelegate <1>__OnState;

			public static HandleNamedMessageDelegate <2>__OnVote;

			public static HandleNamedMessageDelegate <3>__OnCommand;

			public static HandleNamedMessageDelegate <4>__OnNotice;
		}

		public const string Hello = "Hogtied.Hello";

		public const string State = "Hogtied.State";

		public const string Vote = "Hogtied.Vote";

		public const string Command = "Hogtied.Command";

		public const string Notice = "Hogtied.Notice";

		private const float HelloTimeoutSeconds = 20f;

		private const float HostReplyGraceSeconds = 10f;

		private const int MaxHelloAttempts = 5;

		private const int MaxCommandLength = 256;

		private const int MaxNoticeLength = 512;

		private static CustomMessagingManager _registeredOn;

		private static StartOfRound _session;

		private static bool _helloSent;

		private static int _helloAttempts;

		private static float _helloSentAt;

		private static bool _hostReplied;

		private static readonly HashSet<ulong> _hasMod = new HashSet<ulong>();

		private static readonly Dictionary<ulong, float> _connectedAt = new Dictionary<ulong, float>();

		private static readonly HashSet<ulong> _warned = new HashSet<ulong>();

		public static bool HostHasMod
		{
			get
			{
				if (!Players.IsHost)
				{
					return _hostReplied;
				}
				return true;
			}
		}

		internal static bool AwaitingHostReply
		{
			get
			{
				if (!HostHasMod)
				{
					if (_helloSent)
					{
						return Time.realtimeSinceStartup - _helloSentAt < 10f;
					}
					return true;
				}
				return false;
			}
		}

		public static void Install(Harmony harmony)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Expected O, but got Unknown
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Expected O, but got Unknown
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Expected O, but got Unknown
			harmony.Patch((MethodBase)AccessTools.Method(typeof(StartOfRound), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Messages), "SessionStartPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(StartOfRound), "OnDestroy", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Messages), "SessionEndPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(PlayerControllerB), "ConnectClientToPlayerObject", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Messages), "LocalPlayerReadyPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(StartOfRound), "OnClientConnect", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Messages), "ClientConnectPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.Method(typeof(StartOfRound), "OnClientDisconnect", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Messages), "ClientDisconnectPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		public static bool HasMod(ulong clientId)
		{
			if (clientId != 0L && (!Players.IsHost || clientId != Players.LocalClientId))
			{
				return _hasMod.Contains(clientId);
			}
			return true;
		}

		public unsafe static void SendCommand(string command)
		{
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsListening || string.IsNullOrWhiteSpace(command))
			{
				return;
			}
			string text = command.Trim();
			if (text.Length > 256)
			{
				text = text.Substring(0, 256);
			}
			if (singleton.IsServer)
			{
				HandleCommand(singleton.LocalClientId, text);
				return;
			}
			EnsureRegistered();
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(64, (Allocator)2, 4096);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe(text, false);
				singleton.CustomMessagingManager.SendNamedMessage("Hogtied.Command", 0uL, val, (NetworkDelivery)3);
			}
			finally
			{
				((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
			}
		}

		internal unsafe static void BroadcastState(ulong[] hogtiedClientIds)
		{
			//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_002c: Unknown result type (might be due to invalid IL or missing references)
			HogtieState.ApplyFromHost(hogtiedClientIds);
			List<ulong> list = RemoteModdedClients();
			if (list.Count == 0)
			{
				return;
			}
			FastBufferWriter val = WriteState(hogtiedClientIds);
			try
			{
				NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("Hogtied.State", (IReadOnlyList<ulong>)list, val, (NetworkDelivery)3);
			}
			finally
			{
				((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
			}
		}

		internal unsafe static void BroadcastVote(VoteSnapshot snapshot)
		{
			//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_002c: Unknown result type (might be due to invalid IL or missing references)
			VoteState.Apply(snapshot);
			List<ulong> list = RemoteModdedClients();
			if (list.Count == 0)
			{
				return;
			}
			FastBufferWriter val = WriteVote(snapshot);
			try
			{
				NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("Hogtied.Vote", (IReadOnlyList<ulong>)list, val, (NetworkDelivery)3);
			}
			finally
			{
				((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
			}
		}

		internal unsafe static void SendNotice(ulong clientId, string text)
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			if (clientId == Players.LocalClientId)
			{
				ShowNotice(text);
				return;
			}
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsServer)
			{
				return;
			}
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(64, (Allocator)2, 4096);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe(Truncate(text, 512), false);
				singleton.CustomMessagingManager.SendNamedMessage("Hogtied.Notice", clientId, val, (NetworkDelivery)3);
			}
			finally
			{
				((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
			}
		}

		internal static void ShowNotice(string text)
		{
			if (!((Object)(object)HUDManager.Instance == (Object)null) && !((Object)(object)GameNetworkManager.Instance?.localPlayerController == (Object)null))
			{
				HUDManager.Instance.AddChatMessage("[Hogtied] " + text, "", -1, false);
			}
		}

		internal static void HostTick()
		{
			if (!Players.IsHost)
			{
				return;
			}
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			foreach (KeyValuePair<ulong, float> item in _connectedAt.ToList())
			{
				if (!_hasMod.Contains(item.Key) && !_warned.Contains(item.Key))
				{
					if (!Players.IsConnected(item.Key))
					{
						_connectedAt.Remove(item.Key);
					}
					else if (!(realtimeSinceStartup - item.Value < 20f))
					{
						_warned.Add(item.Key);
						Plugin.Log.LogWarning((object)string.Format("Client {0} ({1}) has not sent {2} after {3:0}s; they probably do not have Hogtied installed.", item.Key, Players.NameOf(item.Key), "Hogtied.Hello", 20f));
					}
				}
			}
		}

		private static List<ulong> RemoteModdedClients()
		{
			NetworkManager nm = NetworkManager.Singleton;
			if ((Object)(object)nm == (Object)null || !nm.IsServer || nm.CustomMessagingManager == null)
			{
				return new List<ulong>();
			}
			return nm.ConnectedClientsIds.Where((ulong id) => id != nm.LocalClientId && _hasMod.Contains(id)).ToList();
		}

		private static FastBufferWriter WriteState(ulong[] ids)
		{
			//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)
			FastBufferWriter val = new FastBufferWriter(16 + 8 * ids.Length, (Allocator)2, 65536);
			VoteSnapshot.WriteIds(val, ids);
			return val;
		}

		private static FastBufferWriter WriteVote(VoteSnapshot snapshot)
		{
			//IL_0014: 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)
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(snapshot.MaxSize, (Allocator)2, 65536);
			snapshot.Write(val);
			return val;
		}

		private static void EnsureRegistered()
		{
			//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_0046: Expected O, but got Unknown
			//IL_0061: 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_006c: Expected O, but got Unknown
			//IL_0087: 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_0092: Expected O, but got Unknown
			//IL_00ad: 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_00b8: Expected O, but got Unknown
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Expected O, but got Unknown
			NetworkManager singleton = NetworkManager.Singleton;
			CustomMessagingManager val = (((Object)(object)singleton != (Object)null) ? singleton.CustomMessagingManager : null);
			if (val != null && val != _registeredOn)
			{
				object obj = <>O.<0>__OnHello;
				if (obj == null)
				{
					HandleNamedMessageDelegate val2 = OnHello;
					<>O.<0>__OnHello = val2;
					obj = (object)val2;
				}
				val.RegisterNamedMessageHandler("Hogtied.Hello", (HandleNamedMessageDelegate)obj);
				object obj2 = <>O.<1>__OnState;
				if (obj2 == null)
				{
					HandleNamedMessageDelegate val3 = OnState;
					<>O.<1>__OnState = val3;
					obj2 = (object)val3;
				}
				val.RegisterNamedMessageHandler("Hogtied.State", (HandleNamedMessageDelegate)obj2);
				object obj3 = <>O.<2>__OnVote;
				if (obj3 == null)
				{
					HandleNamedMessageDelegate val4 = OnVote;
					<>O.<2>__OnVote = val4;
					obj3 = (object)val4;
				}
				val.RegisterNamedMessageHandler("Hogtied.Vote", (HandleNamedMessageDelegate)obj3);
				object obj4 = <>O.<3>__OnCommand;
				if (obj4 == null)
				{
					HandleNamedMessageDelegate val5 = OnCommand;
					<>O.<3>__OnCommand = val5;
					obj4 = (object)val5;
				}
				val.RegisterNamedMessageHandler("Hogtied.Command", (HandleNamedMessageDelegate)obj4);
				object obj5 = <>O.<4>__OnNotice;
				if (obj5 == null)
				{
					HandleNamedMessageDelegate val6 = OnNotice;
					<>O.<4>__OnNotice = val6;
					obj5 = (object)val6;
				}
				val.RegisterNamedMessageHandler("Hogtied.Notice", (HandleNamedMessageDelegate)obj5);
				_registeredOn = val;
				Plugin.Log.LogDebug((object)"Registered named messages");
			}
		}

		private static void Unregister()
		{
			NetworkManager singleton = NetworkManager.Singleton;
			CustomMessagingManager val = (((Object)(object)singleton != (Object)null) ? singleton.CustomMessagingManager : null);
			if (val != null && val == _registeredOn)
			{
				val.UnregisterNamedMessageHandler("Hogtied.Hello");
				val.UnregisterNamedMessageHandler("Hogtied.State");
				val.UnregisterNamedMessageHandler("Hogtied.Vote");
				val.UnregisterNamedMessageHandler("Hogtied.Command");
				val.UnregisterNamedMessageHandler("Hogtied.Notice");
			}
			_registeredOn = null;
		}

		private static void ResetSession()
		{
			_helloSent = false;
			_helloAttempts = 0;
			_helloSentAt = 0f;
			_hostReplied = false;
			_hasMod.Clear();
			_connectedAt.Clear();
			_warned.Clear();
			VoteManager.Reset();
			HogtieState.Reset();
			VoteState.Reset();
		}

		private static void SessionStartPostfix(StartOfRound __instance)
		{
			try
			{
				ResetSession();
				_session = __instance;
				Unregister();
				EnsureRegistered();
				HostTicker.Ensure();
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Session start failed: {arg}");
			}
		}

		private static void SessionEndPostfix(StartOfRound __instance)
		{
			if (__instance != _session)
			{
				return;
			}
			try
			{
				Unregister();
				ResetSession();
				_session = null;
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Session end failed: {arg}");
			}
		}

		private static void LocalPlayerReadyPostfix(PlayerControllerB __instance)
		{
			if (!__instance.isTestingPlayer && !_helloSent)
			{
				TrySendHello();
			}
		}

		internal static void ClientTick()
		{
			if (!_helloSent && _helloAttempts > 0 && _helloAttempts < 5)
			{
				TrySendHello();
			}
		}

		private unsafe static void TrySendHello()
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				NetworkManager singleton = NetworkManager.Singleton;
				if ((Object)(object)singleton == (Object)null || !singleton.IsListening)
				{
					return;
				}
				_helloAttempts++;
				EnsureRegistered();
				if (singleton.IsServer)
				{
					_helloSent = true;
					HogtieState.HostTick();
					return;
				}
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(32, (Allocator)2, 1024);
				try
				{
					((FastBufferWriter)(ref val)).WriteValueSafe("0.1.0", false);
					singleton.CustomMessagingManager.SendNamedMessage("Hogtied.Hello", 0uL, val, (NetworkDelivery)3);
					_helloSent = true;
					_helloSentAt = Time.realtimeSinceStartup;
					Plugin.Log.LogInfo((object)"Sent hello to host");
				}
				finally
				{
					((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Sending hello failed (attempt {_helloAttempts}): {arg}");
			}
		}

		private static void ClientConnectPostfix(ulong clientId)
		{
			if (Players.IsHost && clientId != Players.LocalClientId)
			{
				_connectedAt[clientId] = Time.realtimeSinceStartup;
				_warned.Remove(clientId);
			}
		}

		private static void ClientDisconnectPostfix(ulong clientId)
		{
			if (!Players.IsHost || clientId == Players.LocalClientId)
			{
				return;
			}
			try
			{
				_hasMod.Remove(clientId);
				_connectedAt.Remove(clientId);
				_warned.Remove(clientId);
				VoteManager.OnPlayerLeft(clientId);
				HogtieState.HostTick();
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Handling disconnect of {clientId} failed: {arg}");
			}
		}

		private unsafe static void OnHello(ulong sender, FastBufferReader reader)
		{
			//IL_00a5: 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_00b7: 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_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				NetworkManager singleton = NetworkManager.Singleton;
				if ((Object)(object)singleton == (Object)null || !singleton.IsServer || sender == singleton.LocalClientId)
				{
					return;
				}
				string text = default(string);
				((FastBufferReader)(ref reader)).ReadValueSafe(ref text, false);
				if (text != "0.1.0")
				{
					Plugin.Log.LogWarning((object)string.Format("Client {0} ({1}) runs Hogtied {2}, host runs {3}", sender, Players.NameOf(sender), text, "0.1.0"));
				}
				_hasMod.Add(sender);
				Plugin.Log.LogInfo((object)$"Hello from client {sender} ({Players.NameOf(sender)})");
				FastBufferWriter val = WriteState(HogtieState.HostConnectedHogtied());
				try
				{
					singleton.CustomMessagingManager.SendNamedMessage("Hogtied.State", sender, val, (NetworkDelivery)3);
				}
				finally
				{
					((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
				}
				VoteSnapshot voteSnapshot = VoteManager.CurrentSnapshot();
				if (voteSnapshot == null)
				{
					return;
				}
				FastBufferWriter val2 = WriteVote(voteSnapshot);
				try
				{
					singleton.CustomMessagingManager.SendNamedMessage("Hogtied.Vote", sender, val2, (NetworkDelivery)3);
				}
				finally
				{
					((IDisposable)(*(FastBufferWriter*)(&val2))/*cast due to .constrained prefix*/).Dispose();
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)string.Format("Handling {0} from {1} failed: {2}", "Hogtied.Hello", sender, arg));
			}
		}

		private static void OnState(ulong sender, FastBufferReader reader)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (FromHost(sender))
				{
					_hostReplied = true;
					HogtieState.ApplyFromHost(VoteSnapshot.ReadIds(reader));
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)string.Format("Handling {0} failed: {1}", "Hogtied.State", arg));
			}
		}

		private static void OnVote(ulong sender, FastBufferReader reader)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (FromHost(sender))
				{
					_hostReplied = true;
					VoteState.Apply(VoteSnapshot.Read(reader));
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)string.Format("Handling {0} failed: {1}", "Hogtied.Vote", arg));
			}
		}

		private static void OnNotice(ulong sender, FastBufferReader reader)
		{
			try
			{
				if (FromHost(sender))
				{
					string text = default(string);
					((FastBufferReader)(ref reader)).ReadValueSafe(ref text, false);
					ShowNotice(Truncate(text, 512));
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)string.Format("Handling {0} failed: {1}", "Hogtied.Notice", arg));
			}
		}

		private static void OnCommand(ulong sender, FastBufferReader reader)
		{
			try
			{
				NetworkManager singleton = NetworkManager.Singleton;
				if (!((Object)(object)singleton == (Object)null) && singleton.IsServer && sender != singleton.LocalClientId)
				{
					string text = default(string);
					((FastBufferReader)(ref reader)).ReadValueSafe(ref text, false);
					HandleCommand(sender, Truncate(text, 256));
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)string.Format("Handling {0} from {1} failed: {2}", "Hogtied.Command", sender, arg));
			}
		}

		private static void HandleCommand(ulong sender, string text)
		{
			string text2 = (text ?? "").Trim();
			if (text2.Length != 0)
			{
				string text3 = (text2.StartsWith("/") ? text2 : ("/" + text2));
				if (!ChatCommands.Handle(sender, text3))
				{
					ChatCommands.Reply(sender, "Unknown command '" + text2 + "'.");
				}
			}
		}

		private static bool FromHost(ulong sender)
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton != (Object)null && !singleton.IsServer)
			{
				return sender == 0;
			}
			return false;
		}

		private static string Truncate(string text, int max)
		{
			if (text != null)
			{
				if (text.Length > max)
				{
					return text.Substring(0, max);
				}
				return text;
			}
			return "";
		}
	}
}
namespace Hogtied.Host
{
	public static class ChatCommands
	{
		public const string Prefix = "[Hogtied] ";

		public static void Install(Harmony harmony)
		{
			RpcGate.Block(typeof(HUDManager), "AddPlayerChatMessageServerRpc", (RpcCall call) => Handle(call.Sender, call.Arg<string>(0)));
		}

		public static bool Handle(ulong sender, string text)
		{
			if (!Players.IsHost || string.IsNullOrEmpty(text))
			{
				return false;
			}
			string text2 = text.Trim();
			if (!text2.StartsWith("/"))
			{
				return false;
			}
			string text3 = text2.Substring(1).Trim();
			int num = text3.IndexOf(' ');
			string text4 = ((num < 0) ? text3 : text3.Substring(0, num)).ToLowerInvariant();
			string arg = ((num < 0) ? "" : text3.Substring(num + 1).Trim());
			bool value = PluginConfig.DebugCommands.Value;
			Action action;
			switch (text4)
			{
			case "hogtie":
				action = delegate
				{
					StartVote(VoteKind.Hogtie, sender, arg);
				};
				break;
			case "untie":
				action = delegate
				{
					StartVote(VoteKind.Untie, sender, arg);
				};
				break;
			case "yes":
				action = delegate
				{
					Cast(sender, yes: true);
				};
				break;
			case "no":
				action = delegate
				{
					Cast(sender, yes: false);
				};
				break;
			case "forcetie":
				if (value)
				{
					action = delegate
					{
						Force(sender, arg, hogtie: true);
					};
					break;
				}
				goto default;
			case "forceuntie":
				if (value)
				{
					action = delegate
					{
						Force(sender, arg, hogtie: false);
					};
					break;
				}
				goto default;
			case "testvote":
				if (value)
				{
					action = delegate
					{
						TestVote(sender);
					};
					break;
				}
				goto default;
			default:
				action = null;
				break;
			}
			Action action2 = action;
			if (action2 == null)
			{
				return false;
			}
			try
			{
				action2();
			}
			catch (Exception arg2)
			{
				Plugin.Log.LogError((object)$"Command '{text2}' from {sender} failed: {arg2}");
			}
			return true;
		}

		public static void Announce(string text)
		{
			if (Players.IsHost && !((Object)(object)HUDManager.Instance == (Object)null))
			{
				HUDManager.Instance.AddTextMessageClientRpc("[Hogtied] " + text);
			}
		}

		public static void Reply(ulong clientId, string text)
		{
			if (Players.IsHost)
			{
				if (clientId == Players.LocalClientId || Messages.HasMod(clientId))
				{
					Messages.SendNotice(clientId, text);
				}
				else
				{
					Announce(Players.NameOf(clientId) + ": " + text);
				}
			}
		}

		private static void StartVote(VoteKind kind, ulong sender, string arg)
		{
			string text = ((kind == VoteKind.Hogtie) ? "hogtie" : "untie");
			if (arg.Length == 0)
			{
				Reply(sender, "Usage: /" + text + " <name>");
				return;
			}
			if (!NameMatcher.TryMatch(arg, out var clientId, out var player, out var error))
			{
				Reply(sender, error);
				return;
			}
			string playerUsername = player.playerUsername;
			if (kind == VoteKind.Hogtie && clientId == sender)
			{
				Reply(sender, "You can't start a hogtie vote on yourself.");
				return;
			}
			if (!HogtieState.HostCanIdentify(clientId))
			{
				Reply(sender, playerUsername + " is still joining. Try again in a moment.");
				return;
			}
			bool flag = HogtieState.HostIsHogtied(clientId);
			if (kind == VoteKind.Hogtie && flag)
			{
				Reply(sender, playerUsername + " is already hogtied.");
			}
			else if (kind == VoteKind.Untie && !flag)
			{
				Reply(sender, playerUsername + " is not hogtied.");
			}
			else if (!VoteManager.TryStart(kind, sender, clientId, out error))
			{
				Reply(sender, error);
			}
		}

		private static void Cast(ulong sender, bool yes)
		{
			if (!VoteManager.TryCast(sender, yes, out var error))
			{
				Reply(sender, error);
			}
		}

		private static void Force(ulong sender, string arg, bool hogtie)
		{
			string text = (hogtie ? "/forcetie" : "/forceuntie");
			if (sender != 0L)
			{
				Reply(sender, "Only the host can use " + text + ".");
				return;
			}
			ulong clientId = sender;
			string text2 = Players.NameOf(sender);
			if (arg.Length > 0)
			{
				if (!NameMatcher.TryMatch(arg, out clientId, out var player, out var error))
				{
					Reply(sender, error);
					return;
				}
				text2 = player.playerUsername;
			}
			if (!HogtieState.HostSet(clientId, hogtie))
			{
				Reply(sender, text2 + " is still joining. Try again in a moment.");
			}
			else
			{
				Announce(hogtie ? ("The host force-hogtied " + text2 + ".") : ("The host force-untied " + text2 + "."));
			}
		}

		private static void TestVote(ulong sender)
		{
			string error;
			if (sender != 0L)
			{
				Reply(sender, "Only the host can use /testvote.");
			}
			else if (!VoteManager.TryStart(VoteKind.Test, sender, ulong.MaxValue, out error))
			{
				Reply(sender, error);
			}
		}
	}
	internal static class HostRejections
	{
		private const string BellRootName = "BellDinger";

		private const float LeverPullWindowSeconds = 10f;

		private static readonly HashSet<ulong> _knownHogtied = new HashSet<ulong>();

		private static readonly Dictionary<ulong, (bool start, float at)> _acceptedPulls = new Dictionary<ulong, (bool, float)>();

		public static void Install(Harmony harmony)
		{
			Refuse(typeof(StartOfRound), "StartGameServerRpc", (RpcCall call) => !TakeAcceptedPull(call.Sender, start: true), delegate
			{
				CancelLeverStart(null);
			});
			Refuse(typeof(StartMatchLever), "PlayLeverPullEffectsServerRpc", null, delegate(RpcCall call)
			{
				if (call.Arg<bool>(0))
				{
					CancelLeverStart(call.Target<StartMatchLever>());
				}
			});
			RpcGate.Block(typeof(StartMatchLever), "PlayLeverPullEffectsServerRpc", delegate(RpcCall call)
			{
				_acceptedPulls[call.Sender] = (call.Arg<bool>(0), Time.realtimeSinceStartup);
				return false;
			});
			Refuse(typeof(StartOfRound), "EndGameServerRpc", (RpcCall call) => !TakeAcceptedPull(call.Sender, start: false));
			Refuse(typeof(Terminal), "SetTerminalInUseServerRpc", (RpcCall call) => call.Arg<bool>(0), delegate(RpcCall call)
			{
				call.Target<Terminal>().KickOffTerminalClientRpc();
			});
			Refuse(typeof(AnimatedObjectTrigger), "UpdateAnimTriggerServerRpc", (RpcCall call) => IsBell(call.Instance));
			Refuse(typeof(DepositItemsDesk), "SetTimesHeardNoiseServerRpc", null, null, quiet: true);
			Refuse(typeof(DepositItemsDesk), "SetPatienceServerRpc", null, null, quiet: true);
			Refuse(typeof(ShipBuildModeManager), "PlaceShipObjectServerRpc", null, RestoreFurniture);
			Refuse(typeof(ShipBuildModeManager), "StoreObjectServerRpc");
			Refuse(typeof(PlayerControllerB), "GrabObjectServerRpc", (RpcCall call) => IsToolGrab(call.Arg<NetworkObjectReference>(0)), delegate(RpcCall call)
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				call.Target<PlayerControllerB>().GrabObjectClientRpc(false, call.Arg<NetworkObjectReference>(0));
			}, quiet: false, includeHost: true);
			Refuse(typeof(ShipLights), "SetShipLightsServerRpc", null, delegate(RpcCall call)
			{
				ShipLights obj = call.Target<ShipLights>();
				obj.SetShipLightsClientRpc(obj.areLightsOn);
			});
			Refuse(typeof(AnimatedObjectTrigger), "UpdateAnimServerRpc", (RpcCall call) => IsShipLightSwitch(call.Target<AnimatedObjectTrigger>()), delegate(RpcCall call)
			{
				AnimatedObjectTrigger obj = call.Target<AnimatedObjectTrigger>();
				obj.UpdateAnimClientRpc(obj.boolValue, false, -1);
			});
			HogtieState.Changed += OnHogtiedChanged;
		}

		private static void Refuse(Type type, string rpcName, Func<RpcCall, bool> when = null, Action<RpcCall> onBlocked = null, bool quiet = false, bool includeHost = false)
		{
			string name = type.Name + "." + rpcName;
			RpcGate.Block(type, rpcName, (RpcCall call) => (includeHost || !call.FromHost) && HogtieState.HostIsHogtied(call.Sender) && (when == null || when(call)), delegate(RpcCall call)
			{
				string text = $"Refused {name} from hogtied {Players.NameOf(call.Sender)} ({call.Sender})";
				if (quiet)
				{
					Plugin.Log.LogDebug((object)text);
				}
				else
				{
					Plugin.Log.LogInfo((object)text);
				}
				onBlocked?.Invoke(call);
			});
		}

		private static bool TakeAcceptedPull(ulong sender, bool start)
		{
			if (!_acceptedPulls.TryGetValue(sender, out (bool, float) value) || value.Item1 != start || Time.realtimeSinceStartup - value.Item2 > 10f)
			{
				return false;
			}
			_acceptedPulls.Remove(sender);
			Plugin.Log.LogInfo((object)string.Format("Allowing {0} of game from hogtied {1} ({2}): pull began before the hogtie", start ? "start" : "end", Players.NameOf(sender), sender));
			return true;
		}

		private static void CancelLeverStart(StartMatchLever lever)
		{
			StartOfRound instance = StartOfRound.Instance;
			if (!((Object)(object)instance == (Object)null) && instance.inShipPhase && !instance.beganLoadingNewLevel)
			{
				if ((Object)(object)lever == (Object)null)
				{
					lever = Object.FindObjectOfType<StartMatchLever>();
				}
				if (!((Object)(object)lever == (Object)null) && !lever.leverHasBeenPulled)
				{
					lever.CancelStartGameClientRpc();
				}
			}
		}

		private static bool IsBell(NetworkBehaviour trigger)
		{
			Transform val = ((Component)trigger).transform;
			while ((Object)(object)val != (Object)null)
			{
				if (((Object)val).name == "BellDinger")
				{
					return true;
				}
				val = val.parent;
			}
			return false;
		}

		private static bool IsShipLightSwitch(AnimatedObjectTrigger aot)
		{
			if ((Object)(object)aot == (Object)null || !aot.isBool)
			{
				return false;
			}
			InteractTrigger[] components = ((Component)aot).GetComponents<InteractTrigger>();
			for (int i = 0; i < components.Length; i++)
			{
				InteractEvent onInteract = components[i].onInteract;
				if (onInteract == null)
				{
					continue;
				}
				for (int j = 0; j < ((UnityEventBase)onInteract).GetPersistentEventCount(); j++)
				{
					if (((UnityEventBase)onInteract).GetPersistentTarget(j) is ShipLights && ((UnityEventBase)onInteract).GetPersistentMethodName(j) == "ToggleShipLights")
					{
						return true;
					}
				}
			}
			return false;
		}

		private static bool IsToolGrab(NetworkObjectReference reference)
		{
			NetworkObject val = default(NetworkObject);
			if (!((NetworkObjectReference)(ref reference)).TryGet(ref val, (NetworkManager)null))
			{
				return false;
			}
			GrabbableObject componentInChildren = ((Component)val).GetComponentInChildren<GrabbableObject>();
			if ((Object)(object)componentInChildren != (Object)null && (Object)(object)componentInChildren.itemProperties != (Object)null)
			{
				return !componentInChildren.itemProperties.isScrap;
			}
			return false;
		}

		private static void RestoreFurniture(RpcCall call)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			NetworkObjectReference val = call.Arg<NetworkObjectReference>(2);
			NetworkObject val2 = default(NetworkObject);
			if (((NetworkObjectReference)(ref val)).TryGet(ref val2, (NetworkManager)null))
			{
				PlaceableShipObject componentInChildren = ((Component)val2).GetComponentInChildren<PlaceableShipObject>();
				if (!((Object)(object)componentInChildren == (Object)null) && !((Object)(object)componentInChildren.placeObjectCollider == (Object)null) && !((Object)(object)componentInChildren.mainMesh == (Object)null) && !StartOfRound.Instance.unlockablesList.unlockables[componentInChildren.unlockableID].inStorage)
				{
					call.Target<ShipBuildModeManager>().PlaceShipObjectClientRpc(((Component)componentInChildren.placeObjectCollider).transform.position, ((Component)componentInChildren.mainMesh).transform.eulerAngles, val, -1);
				}
			}
		}

		private static void OnHogtiedChanged()
		{
			ulong[] array = HogtieState.HogtiedClientIds.ToArray();
			ulong[] array2 = array.Where((ulong id) => !_knownHogtied.Contains(id)).ToArray();
			_knownHogtied.Clear();
			_knownHogtied.UnionWith(array);
			if (Players.IsHost)
			{
				ulong[] array3 = array2;
				foreach (ulong clientId in array3)
				{
					ForceDropIfUnmodded(clientId);
					KickOffTerminal(clientId);
				}
			}
		}

		private static void KickOffTerminal(ulong clientId)
		{
			try
			{
				if (clientId == 0L)
				{
					return;
				}
				Terminal val = Object.FindObjectOfType<Terminal>();
				if ((Object)(object)val == (Object)null || (Object)(object)val.placeableObject == (Object)null || !val.placeableObject.inUse || (Object)(object)val.terminalTrigger == (Object)null)
				{
					return;
				}
				PlayerControllerB val2 = Players.ByClientId(clientId);
				if ((Object)(object)val2 == (Object)null || !val2.inSpecialInteractAnimation || (Object)(object)val2.currentTriggerInAnimationWith != (Object)(object)val.terminalTrigger)
				{
					return;
				}
				foreach (KeyValuePair<ulong, PlayerControllerB> item in Players.Connected())
				{
					if (item.Key != clientId && (Object)(object)item.Value.currentTriggerInAnimationWith == (Object)(object)val.terminalTrigger)
					{
						return;
					}
				}
				Plugin.Log.LogInfo((object)$"Kicking {Players.NameOf(clientId)} ({clientId}) off the terminal: hogtied");
				val.KickOffTerminalClientRpc();
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Terminal kick for {clientId} failed: {arg}");
			}
		}

		private static void ForceDropIfUnmodded(ulong clientId)
		{
			try
			{
				if (clientId != 0L && !Messages.HasMod(clientId))
				{
					PlayerControllerB val = Players.ByClientId(clientId);
					if (!((Object)(object)val == (Object)null))
					{
						Plugin.Log.LogInfo((object)$"Forcing {Players.NameOf(clientId)} ({clientId}) to drop held items: no Hogtied hello");
						val.DropAllHeldItemsAndSyncNonexact();
					}
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Forced drop for {clientId} failed: {arg}");
			}
		}
	}
	internal sealed class HostTicker : MonoBehaviour
	{
		private const float SlowInterval = 1f;

		private const float VoteInterval = 0.2f;

		private static HostTicker _instance;

		private float _nextSlow;

		private float _nextVote;

		public static void Ensure()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			if (!((Object)(object)_instance != (Object)null))
			{
				GameObject val = new GameObject("HogtiedHostTicker")
				{
					hideFlags = (HideFlags)61
				};
				Object.DontDestroyOnLoad((Object)val);
				_instance = val.AddComponent<HostTicker>();
			}
		}

		private void Update()
		{
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (!Players.IsHost)
			{
				if (realtimeSinceStartup >= _nextSlow)
				{
					_nextSlow = realtimeSinceStartup + 1f;
					Run(Messages.ClientTick, "Messages");
				}
				return;
			}
			if (realtimeSinceStartup >= _nextVote)
			{
				_nextVote = realtimeSinceStartup + 0.2f;
				Run(VoteManager.Tick, "VoteManager");
			}
			if (realtimeSinceStartup >= _nextSlow)
			{
				_nextSlow = realtimeSinceStartup + 1f;
				Run(HogtieState.HostTick, "HogtieState");
				Run(Messages.HostTick, "Messages");
			}
		}

		private static void Run(Action tick, string name)
		{
			try
			{
				tick();
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"{name} tick failed: {arg}");
			}
		}
	}
	public readonly struct RpcCall
	{
		public readonly NetworkBehaviour Instance;

		public readonly ulong Sender;

		public readonly object[] Args;

		public bool FromHost => Sender == 0;

		internal RpcCall(NetworkBehaviour instance, ulong sender, object[] args)
		{
			Instance = instance;
			Sender = sender;
			Args = args;
		}

		public T Target<T>() where T : NetworkBehaviour
		{
			return (T)(object)Instance;
		}

		public T Arg<T>(int index)
		{
			return (T)Args[index];
		}
	}
	public static class RpcGate
	{
		private sealed class Gate
		{
			public Func<RpcCall, bool> ShouldBlock;

			public Action<RpcCall> OnBlocked;

			public string Name;
		}

		private sealed class Frame
		{
			public NetworkBehaviour Target;

			public MethodBase Rpc;

			public ulong Sender;

			public bool Used;
		}

		private static Harmony _harmony;

		private static readonly Dictionary<IntPtr, MethodBase> _handlerToRpc = new Dictionary<IntPtr, MethodBase>();

		private static readonly Dictionary<IntPtr, List<Gate>> _gates = new Dictionary<IntPtr, List<Gate>>();

		private static readonly Stack<Frame> _frames = new Stack<Frame>();

		private static readonly FieldInfo _execStage = AccessTools.Field(typeof(NetworkBehaviour), "__rpc_exec_stage");

		private const int ExecStageSend = 0;

		private const int ExecStageExecute = 1;

		public static void Install(Harmony harmony)
		{
			_harmony = harmony;
			if (_execStage == null)
			{
				Plugin.Log.LogError((object)"RpcGate: NetworkBehaviour.__rpc_exec_stage not found; gates will not run");
			}
		}

		public static bool Block(Type type, string rpcName, Func<RpcCall, bool> shouldBlock, Action<RpcCall> onBlocked = null)
		{
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ee: Expected O, but got Unknown
			//IL_01ee: Expected O, but got Unknown
			//IL_022a: Unknown result type (might be due to invalid IL or missing references)
			//IL_022f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0243: Expected O, but got Unknown
			string text = type?.Name + "." + rpcName;
			try
			{
				if (_harmony == null)
				{
					throw new InvalidOperationException("RpcGate.Install has not run");
				}
				if (type == null || string.IsNullOrEmpty(rpcName) || shouldBlock == null)
				{
					throw new ArgumentException("type, rpcName and shouldBlock are required");
				}
				List<MethodInfo> list = FindHandlers(type, rpcName);
				if (list.Count == 0)
				{
					Plugin.Log.LogError((object)("RpcGate: no __rpc_handler registered for " + text + "; gate not installed"));
					return false;
				}
				if (list.Count > 1)
				{
					Plugin.Log.LogError((object)$"RpcGate: {text} is overloaded ({list.Count} registrations); gate not installed");
					return false;
				}
				MethodInfo methodInfo = list[0];
				MethodInfo methodInfo2 = FindCalledRpc(methodInfo, type, rpcName);
				if (methodInfo2 == null)
				{
					Plugin.Log.LogError((object)("RpcGate: handler " + methodInfo.Name + " for " + text + " does not call the RPC method; gate not installed"));
					return false;
				}
				object obj = methodInfo2.GetCustomAttributes(inherit: true).FirstOrDefault((object a) => a is RpcAttribute);
				if (obj == null || obj.GetType() != typeof(ServerRpcAttribute))
				{
					Plugin.Log.LogError((object)("RpcGate: " + text + " is " + ((obj == null) ? "not an RPC" : obj.GetType().Name) + ", only classic [ServerRpc] can be gated (a universal [Rpc] is relayed before the host could refuse it); gate not installed"));
					return false;
				}
				if (!_handlerToRpc.ContainsKey(Key(methodInfo)))
				{
					_harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(RpcGate), "HandlerPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(RpcGate), "HandlerFinalizer", (Type[])null), (HarmonyMethod)null);
					_handlerToRpc[Key(methodInfo)] = methodInfo2;
				}
				if (!_gates.TryGetValue(Key(methodInfo2), out var value))
				{
					_harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(RpcGate), "RpcPrefix", (Type[])null)
					{
						priority = 800
					}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					value = (_gates[Key(methodInfo2)] = new List<Gate>());
				}
				value.Add(new Gate
				{
					ShouldBlock = shouldBlock,
					OnBlocked = onBlocked,
					Name = text
				});
				Plugin.Log.LogDebug((object)("RpcGate: gating " + text + " via " + methodInfo.Name));
				return true;
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"RpcGate: failed to gate {text}: {arg}");
				return false;
			}
		}

		private static List<MethodInfo> FindHandlers(Type type, string rpcName)
		{
			MethodInfo methodInfo = AccessTools.DeclaredMethod(type, "__initializeRpcs", (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				return new List<MethodInfo>();
			}
			List<MethodInfo> list = new List<MethodInfo>();
			MethodInfo methodInfo2 = null;
			foreach (CodeInstruction originalInstruction in PatchProcessor.GetOriginalInstructions((MethodBase)methodInfo, (ILGenerator)null))
			{
				if (originalInstruction.opcode == OpCodes.Ldftn && originalInstruction.operand is MethodInfo methodInfo3 && methodInfo3.Name.StartsWith("__rpc_handler_"))
				{
					methodInfo2 = methodInfo3;
				}
				else if (originalInstruction.opcode == OpCodes.Ldstr && originalInstruction.operand is string text && methodInfo2 != null)
				{
					if (text == rpcName)
					{
						list.Add(methodInfo2);
					}
					methodInfo2 = null;
				}
			}
			return list;
		}

		private static MethodInfo FindCalledRpc(MethodInfo handler, Type type, string rpcName)
		{
			foreach (CodeInstruction originalInstruction in PatchProcessor.GetOriginalInstructions((MethodBase)handler, (ILGenerator)null))
			{
				if ((originalInstruction.opcode == OpCodes.Call || originalInstruction.opcode == OpCodes.Callvirt) && originalInstruction.operand is MethodInfo methodInfo && methodInfo.Name == rpcName && methodInfo.DeclaringType == type)
				{
					return methodInfo;
				}
			}
			return null;
		}

		private static void HandlerPrefix(MethodBase __originalMethod, NetworkBehaviour __0, __RpcParams __2)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			_handlerToRpc.TryGetValue(Key(__originalMethod), out var value);
			_frames.Push(new Frame
			{
				Target = __0,
				Rpc = value,
				Sender = __2.Server.Receive.SenderClientId
			});
		}

		private static Exception HandlerFinalizer(Exception __exception)
		{
			if (_frames.Count > 0)
			{
				_frames.Pop();
			}
			return __exception;
		}

		private static bool RpcPrefix(MethodBase __originalMethod, object __instance, object[] __args)
		{
			if (_frames.Count == 0 || _execStage == null)
			{
				return true;
			}
			Frame frame = _frames.Peek();
			NetworkBehaviour val = (NetworkBehaviour)((__instance is NetworkBehaviour) ? __instance : null);
			if (frame.Used || (Object)(object)val == (Object)null || frame.Target != val || frame.Rpc == null || Key(frame.Rpc) != Key(__originalMethod))
			{
				return true;
			}
			frame.Used = true;
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsServer || GetStage(val) != 1)
			{
				return true;
			}
			if (!_gates.TryGetValue(Key(__originalMethod), out var value))
			{
				return true;
			}
			RpcCall rpcCall = new RpcCall(val, frame.Sender, __args);
			SetStage(val, 0);
			foreach (Gate item in value)
			{
				bool flag;
				try
				{
					flag = item.ShouldBlock(rpcCall);
				}
				catch (Exception arg)
				{
					Plugin.Log.LogError((object)$"RpcGate: gate on {item.Name} threw: {arg}");
					continue;
				}
				if (flag)
				{
					try
					{
						item.OnBlocked?.Invoke(rpcCall);
					}
					catch (Exception arg2)
					{
						Plugin.Log.LogError((object)$"RpcGate: onBlocked for {item.Name} threw: {arg2}");
					}
					return false;
				}
			}
			SetStage(val, 1);
			return true;
		}

		private static IntPtr Key(MethodBase method)
		{
			return method.MethodHandle.Value;
		}

		private static int GetStage(NetworkBehaviour instance)
		{
			return Convert.ToInt32(_execStage.GetValue(instance));
		}

		private static void SetStage(NetworkBehaviour instance, int stage)
		{
			_execStage.SetValue(instance, Enum.ToObject(_execStage.FieldType, stage));
		}
	}
	internal static class VoteManager
	{
		private sealed class Vote
		{
			public int Id;

			public VoteKind Kind;

			public ulong Starter;

			public string StarterCooldownKey;

			public string StarterName;

			public ulong Target;

			public string TargetName;

			public float EndsAt;

			public VoteStatus Status;

			public readonly Dictionary<ulong, bool> Ballots = new Dictionary<ulong, bool>();

			public int Eligible;

			public int Yes;

			public int No;

			public int Needed;
		}

		public const string TestTargetName = "Test Dummy";

		private static Vote _vote;

		private static int _nextId = 1;

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

		public static bool IsRunning
		{
			get
			{
				if (_vote != null)
				{
					return _vote.Status == VoteStatus.Running;
				}
				return false;
			}
		}

		public static void Install(Harmony harmony)
		{
		}

		public static VoteSnapshot CurrentSnapshot()
		{
			if (!IsRunning)
			{
				return null;
			}
			return Snapshot(_vote);
		}

		public static bool TryStart(VoteKind kind, ulong starter, ulong target, out string error)
		{
			error = null;
			if (!Players.IsHost)
			{
				error = "Only the host runs votes.";
				return false;
			}
			if (IsRunning)
			{
				error = "A vote is already running.";
				return false;
			}
			string text = CooldownKey(starter);
			if (kind != VoteKind.Test && _cooldownUntil.TryGetValue(text, out var value))
			{
				float num = value - Time.realtimeSinceStartup;
				if (num > 0f)
				{
					error = $"Your last vote failed. You can start another in {Mathf.CeilToInt(num)}s.";
					return false;
				}
				_cooldownUntil.Remove(text);
			}
			Vote vote = new Vote
			{
				Id = _nextId++,
				Kind = kind,
				Starter = starter,
				StarterCooldownKey = text,
				StarterName = Players.NameOf(starter),
				Target = ((kind == VoteKind.Test) ? ulong.MaxValue : target),
				TargetName = ((kind == VoteKind.Test) ? "Test Dummy" : Players.NameOf(target)),
				EndsAt = Time.realtimeSinceStartup + (float)PluginConfig.VoteDurationSeconds.Value,
				Status = VoteStatus.Running
			};
			if (kind != VoteKind.Test && starter != target)
			{
				vote.Ballots[starter] = true;
			}
			_vote = vote;
			int value2 = PluginConfig.VoteDurationSeconds.Value;
			ChatCommands.Announce(string.Format("{0} F1 = yes, F2 = no, or type /yes or /no. {1}s.", kind switch
			{
				VoteKind.Hogtie => vote.StarterName + " wants to hogtie " + vote.TargetName + ".", 
				VoteKind.Untie => (starter == target) ? (vote.StarterName + " asks to be untied.") : (vote.StarterName + " wants to untie " + vote.TargetName + "."), 
				_ => vote.StarterName + " started a test vote.", 
			}, value2));
			Plugin.Log.LogInfo((object)$"Vote {vote.Id} started: {kind} {vote.TargetName} by {vote.StarterName}");
			Evaluate(forceBroadcast: true);
			return true;
		}

		public static bool TryCast(ulong voter, bool yes, out string error)
		{
			error = null;
			if (!IsRunning)
			{
				error = "There is no vote running.";
				return false;
			}
			if (voter == _vote.Target)
			{
				error = "You can't vote on your own vote.";
				return false;
			}
			if (!Players.IsConnected(voter))
			{
				error = "You are not in the lobby.";
				return false;
			}
			_vote.Ballots[voter] = yes;
			Evaluate(forceBroadcast: true);
			return true;
		}

		public static void Tick()
		{
			if (IsRunning)
			{
				Evaluate(forceBroadcast: false);
			}
		}

		public static void OnPlayerLeft(ulong clientId)
		{
			if (IsRunning)
			{
				Evaluate(forceBroadcast: false);
			}
		}

		public static void Reset()
		{
			_vote = null;
			_cooldownUntil.Clear();
		}

		private static void Evaluate(bool forceBroadcast)
		{
			Vote vote = _vote;
			if (vote == null || vote.Status != VoteStatus.Running)
			{
				return;
			}
			List<ulong> list = Players.ConnectedClientIds();
			List<ulong> list2 = list.Where((ulong id) => id != vote.Target).ToList();
			foreach (ulong item in vote.Ballots.Keys.ToList())
			{
				if (!list2.Contains(item))
				{
					vote.Ballots.Remove(item);
				}
			}
			int num = vote.Ballots.Count((KeyValuePair<ulong, bool> b) => b.Value);
			int num2 = vote.Ballots.Count((KeyValuePair<ulong, bool> b) => !b.Value);
			int num3 = list2.Count / 2 + 1;
			bool flag = num != vote.Yes || num2 != vote.No || num3 != vote.Needed || list2.Count != vote.Eligible;
			vote.Yes = num;
			vote.No = num2;
			vote.Needed = num3;
			vote.Eligible = list2.Count;
			bool flag2 = Time.realtimeSinceStartup >= vote.EndsAt;
			if (vote.Kind != VoteKind.Test && !list.Contains(vote.Target))
			{
				Resolve(vote, passed: false, vote.TargetName + " left the lobby.", applyCooldown: false);
			}
			else if (vote.Kind == VoteKind.Test)
			{
				if (flag2)
				{
					Resolve(vote, num >= num3, null);
				}
				else if (flag || forceBroadcast)
				{
					Broadcast(vote);
				}
			}
			else if (num >= num3)
			{
				Resolve(vote, passed: true, null);
			}
			else if (list2.Count - num2 < num3 || flag2)
			{
				Resolve(vote, passed: false, flag2 ? "Time ran out." : null);
			}
			else if (flag || forceBroadcast)
			{
				Broadcast(vote);
			}
		}

		private static void Resolve(Vote vote, bool passed, string reason, bool applyCooldown = true)
		{
			vote.Status = (passed ? VoteStatus.Passed : VoteStatus.Failed);
			try
			{
				ApplyResult(vote, passed, reason, applyCooldown);
			}
			finally
			{
				Broadcast(vote);
			}
		}

		private static void ApplyResult(Vote vote, bool passed, string reason, bool applyCooldown)
		{
			string text = $"Yes {vote.Yes}, No {vote.No}, needed {vote.Needed} of {vote.Eligible}.";
			string text2;
			if (passed)
			{
				switch (vote.Kind)
				{
				case VoteKind.Hogtie:
					HogtieState.HostSet(vote.Target, hogtied: true);
					text2 = "Vote passed: " + vote.TargetName + " is hogtied.";
					break;
				case VoteKind.Untie:
					HogtieState.HostSet(vote.Target, hogtied: false);
					text2 = "Vote passed: " + vote.TargetName + " is untied.";
					break;
				default:
					text2 = "Test vote passed.";
					break;
				}
			}
			else
			{
				text2 = vote.Kind switch
				{
					VoteKind.Hogtie => "Vote failed: " + vote.TargetName + " stays free.", 
					VoteKind.Untie => "Vote failed: " + vote.TargetName + " stays hogtied.", 
					_ => "Test vote failed.", 
				};
				if (vote.Kind != VoteKind.Test && applyCooldown)
				{
					int value = PluginConfig.FailedVoteCooldownSeconds.Value;
					if (value > 0)
					{
						_cooldownUntil[vote.StarterCooldownKey] = Time.realtimeSinceStartup + (float)value;
					}
				}
			}
			ChatCommands.Announce((reason == null) ? (text2 + " " + text) : (text2 + " " + reason + " " + text));
			Plugin.Log.LogInfo((object)$"Vote {vote.Id} {vote.Status}: {text} {reason}");
		}

		private static void Broadcast(Vote vote)
		{
			Messages.BroadcastVote(Snapshot(vote));
		}

		private static VoteSnapshot Snapshot(Vote vote)
		{
			return new VoteSnapshot
			{
				Id = vote.Id,
				Kind = vote.Kind,
				StarterClientId = vote.Starter,
				StarterName = vote.StarterName,
				TargetClientId = vote.Target,
				TargetName = vote.TargetName,
				SecondsLeft = ((vote.Status == VoteStatus.Running) ? Mathf.Max(0f, vote.EndsAt - Time.realtimeSinceStartup) : 0f),
				Yes = vote.Yes,
				No = vote.No,
				Needed = vote.Needed,
				Status = vote.Status,
				YesVoters = (from b in vote.Ballots
					where b.Value
					select b.Key into id
					orderby id
					select id).ToArray(),
				NoVoters = (from b in vote.Ballots
					where !b.Value
					select b.Key into id
					orderby id
					select id).ToArray()
			};
		}

		private static string CooldownKey(ulong clientId)
		{
			PlayerControllerB val = Players.ByClientId(clientId);
			if (!((Object)(object)GameNetworkManager.Instance != (Object)null) || GameNetworkManager.Instance.disableSteam || !((Object)(object)val != (Object)null) || !val.sentPlayerValues || val.playerSteamId == 0L)
			{
				return $"client:{clientId}";
			}
			return $"steam:{val.playerSteamId}";
		}
	}
}
namespace Hogtied.Client
{
	internal static class Feedback
	{
		private const float Cooldown = 2f;

		private static float _nextTipTime;

		public static void Deny()
		{
			HUDManager instance = HUDManager.Instance;
			if (!((Object)(object)instance == (Object)null) && !(Time.realtimeSinceStartup < _nextTipTime))
			{
				_nextTipTime = Time.realtimeSinceStartup + 2f;
				instance.DisplayTip("Hogtied", "You can't do that while hogtied.", false, false, "LC_Tip1");
			}
		}
	}
	internal static class LocalBlocks
	{
		private const string BellRootName = "BellDinger";

		private const float GrabWaitTimeout = 3f;

		private static readonly Dictionary<Type, bool> _overridesLeftRight = new Dictionary<Type, bool>();

		private static bool _leverAnimationRanUntied;

		private static int _dropToken;

		public static void Install(Harmony harmony)
		{
			Type typeFromHandle = typeof(PlayerControllerB);
			Prefix(harmony, typeFromHandle, "ActivateItem_performed", "ActivateItemPrefix");
			Prefix(harmony, typeFromHandle, "ActivateItem_canceled", "ActivateItemCanceledPrefix");
			Prefix(harmony, typeFromHandle, "ItemSecondaryUse_performed", "ItemQEPrefix");
			Prefix(harmony, typeFromHandle, "ItemTertiaryUse_performed", "ItemQEPrefix");
			Prefix(harmony, typeFromHandle, "QEItemInteract_performed", "ItemQEPrefix");
			Prefix(harmony, typeFromHandle, "BeginGrabObject", "BeginGrabObjectPrefix");
			Prefix(harmony, typeof(InteractTrigger), "Interact", "InteractPrefix");
			Prefix(harmony, typeof(StartMatchLever), "LeverAnimation", "LeverAnimationPrefix");
			Prefix(harmony, typeof(StartMatchLever), "PullLever", "PullLeverPrefix");
			Prefix(harmony, typeof(StartMatchLever), "BeginHoldingInteractOnLever", "BeginHoldingLeverPrefix");
			Prefix(harmony, typeof(Terminal), "BeginUsingTerminal", "BeginUsingTerminalPrefix");
			Prefix(harmony, typeof(ShipLights), "ToggleShipLights", "ToggleShipLightsPrefix");
			Prefix(harmony, typeof(ShipBuildModeManager), "EnterBuildMode", "EnterBuildModePrefix");
			Prefix(harmony, typeof(ShipBuildModeManager), "StoreObjectLocalClient", "StoreObjectPrefix");
			HogtieState.LocalBecameHogtied += OnLocalBecameHogtied;
		}

		private static void Prefix(Harmony harmony, Type type, string method, string patch)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Expected O, but got Unknown
			try
			{
				MethodInfo methodInfo = AccessTools.Method(type, method, (Type[])null, (Type[])null);
				if (methodInfo == null)
				{
					Plugin.Log.LogError((object)("LocalBlocks: " + type.Name + "." + method + " not found"));
				}
				else
				{
					harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(LocalBlocks), patch, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"LocalBlocks: patching {type.Name}.{method} failed: {arg}");
			}
		}

		private static bool IsRestricted(PlayerControllerB player)
		{
			if (HogtieState.IsLocalHogtied && Players.IsLocal(player))
			{
				return !player.isPlayerDead;
			}
			return false;
		}

		private static bool IsLeverBlocked()
		{
			if (HogtieState.IsLocalHogtied)
			{
				if (Players.IsHost && (Object)(object)GameNetworkManager.Instance != (Object)null)
				{
					return GameNetworkManager.Instance.gameHasStarted;
				}
				return true;
			}
			return false;
		}

		private static bool ActivateItemPrefix(PlayerControllerB __instance)
		{
			if (!IsRestricted(__instance) || __instance.inSpecialMenu || !__instance.CanUseItem())
			{
				return true;
			}
			Feedback.Deny();
			return false;
		}

		private static bool ActivateItemCanceledPrefix(PlayerControllerB __instance)
		{
			if (IsRestricted(__instance))
			{
				return (Object)(object)__instance.currentlyHeldObjectServer == (Object)null;
			}
			return true;
		}

		private static bool ItemQEPrefix(PlayerControllerB __instance, CallbackContext context)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			if (!IsRestricted(__instance))
			{
				return true;
			}
			if (WouldUseItemQE(__instance, context))
			{
				Feedback.Deny();
			}
			return false;
		}

		private static bool WouldUseItemQE(PlayerControllerB p, CallbackContext context)
		{
			if (p.equippedUsableItemQE && p.isPlayerControlled && ((CallbackContext)(ref context)).performed && !p.isGrabbingObjectAnimation && !p.isTypingChat && !p.inTerminalMenu && !p.inSpecialInteractAnimation && !p.throwingObject && p.timeSinceSwitchingSlots >= 0.2f && (Object)(object)p.currentlyHeldObjectServer != (Object)null && OverridesLeftRight(p.currentlyHeldObjectServer))
			{
				return HasBatteryIfNeeded(p.currentlyHeldObjectServer);
			}
			return false;
		}

		private static bool OverridesLeftRight(GrabbableObject item)
		{
			Type type = ((object)item).GetType();
			if (!_overridesLeftRight.TryGetValue(type, out var value))
			{
				MethodInfo method = type.GetMethod("ItemInteractLeftRight", BindingFlags.Instance | BindingFlags.Public, null, new Type[1] { typeof(bool) }, null);
				value = method != null && method.DeclaringType != typeof(GrabbableObject);
				_overridesLeftRight[type] = value;
			}
			return value;
		}

		private static bool HasBatteryIfNeeded(GrabbableObject item)
		{
			if (!((Object)(object)item.itemProperties == (Object)null) && item.itemProperties.requiresBattery)
			{
				if (item.insertedBattery != null)
				{
					return !item.insertedBattery.empty;
				}
				return false;
			}
			return true;
		}

		private static bool BeginGrabObjectPrefix(PlayerControllerB __instance)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			if (!IsRestricted(__instance) || (Object)(object)__instance.gameplayCamera == (Object)null)
			{
				return true;
			}
			Transform transform = ((Component)__instance.gameplayCamera).transform;
			RaycastHit hit = default(RaycastHit);
			if (!Physics.Raycast(new Ray(transform.position, transform.forward), ref hit, __instance.grabDistance, __instance.interactableObjectsMask) || ((Component)((RaycastHit)(ref hit)).collider).gameObject.layer == 8 || !((Component)((RaycastHit)(ref hit)).collider).CompareTag("PhysicsProp"))
			{
				return true;
			}
			GrabbableObject component = ((Component)((Component)((RaycastHit)(ref hit)).collider).transform).gameObject.GetComponent<GrabbableObject>();
			if ((Object)(object)component == (Object)null || (Object)(object)component.itemProperties == (Object)null || component.itemProperties.isScrap)
			{
				return true;
			}
			if (WouldGrab(__instance, transform, hit, component))
			{
				Feedback.Deny();
			}
			return false;
		}

		private static bool WouldGrab(PlayerControllerB p, Transform cam, RaycastHit hit, GrabbableObject item)
		{
			//IL_0016: 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_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			if (p.twoHanded || p.sinkingValue > 0.73f || Physics.Linecast(cam.position, ((Component)((RaycastHit)(ref hit)).collider).transform.position + ((Component)p).transform.up * 0.16f, 1073741824, (QueryTriggerInteraction)1))
			{
				return false;
			}
			if ((Object)(object)GameNetworkManager.Instance != (Object)null && !GameNetworkManager.Instance.gameHasStarted && !item.itemProperties.canBeGrabbedBeforeGameStart && (Object)(object)StartOfRound.Instance != (Object)null && (Object)(object)StartOfRound.Instance.testRoom == (Object)null)
			{
				return false;
			}
			if (p.inSpecialInteractAnimation || item.isHeld || item.isPocketed)
			{
				return false;
			}
			NetworkObject networkObject = ((NetworkBehaviour)item).NetworkObject;
			if ((Object)(object)networkObject == (Object)null || !networkObject.IsSpawned)
			{
				return false;
			}
			if (item.grabbable)
			{
				return p.FirstEmptyItemSlot(item) != -1;
			}
			return false;
		}

		private static bool InteractPrefix(InteractTrigger __instance, Transform playerTransform)
		{
			if (!HogtieState.IsLocalHogtied || (Object)(object)playerTransform == (Object)null)
			{
				return true;
			}
			PlayerControllerB component = ((Component)playerTransform).GetComponent<PlayerControllerB>();
			if (!IsRestricted(component))
			{
				return true;
			}
			if (!IsBlockedTrigger(__instance))
			{
				return true;
			}
			if (IsLeverTrigger(__instance) && !IsLeverBlocked())
			{
				return true;
			}
			if (WouldInteract(__instance, component))
			{
				Feedback.Deny();
			}
			return false;
		}

		private static bool WouldInteract(InteractTrigger t, PlayerControllerB p)
		{
			if ((t.triggerOnce && t.hasTriggered) || ((Object)(object)StartOfRound.Instance != (Object)null && StartOfRound.Instance.firingPlayersCutsceneRunning))
			{
				return false;
			}
			if (!t.interactable || t.isPlayingSpecialAnimation || t.usingLadder)
			{
				return false;
			}
			if (p.inSpecialInteractAnimation && !p.isClimbingLadder && !t.allowUseWhileInAnimation)
			{
				return false;
			}
			if (t.interactCooldown && t.currentCooldownValue >= 0f)
			{
				return false;
			}
			if (t.isLadder)
			{
				return !p.isInHangarShipRoom;
			}
			return true;
		}

		private static bool IsBlockedTrigger(InteractTrigger trigger)
		{
			if (!CallsBlocked((UnityEventBase)(object)trigger.onInteract))
			{
				return CallsBlocked((UnityEventBase)(object)trigger.onInteractEarly);
			}
			return true;
		}

		private static bool IsLeverTrigger(InteractTrigger trigger)
		{
			if (!CallsLever((UnityEventBase)(object)trigger.onInteract))
			{
				return CallsLever((UnityEventBase)(object)trigger.onInteractEarly);
			}
			return true;
		}

		private static bool CallsLever(UnityEventBase evt)
		{
			if (evt == null)
			{
				return false;
			}
			for (int i = 0; i < evt.GetPersistentEventCount(); i++)
			{
				if (evt.GetPersistentTarget(i) is StartMatchLever)
				{
					return true;
				}
			}
			return false;
		}

		private static bool CallsBlocked(UnityEventBase evt)
		{
			if (evt == null)
			{
				return false;
			}
			for (int i = 0; i < evt.GetPersistentEventCount(); i++)
			{
				Object persistentTarget = evt.GetPersistentTarget(i);
				string persistentMethodName = evt.GetPersistentMethodName(i);
				Object val = persistentTarget;
				if (!(val is StartMatchLever))
				{
					if (!(val is Terminal))
					{
						if (!(val is ShipLights))
						{
							AnimatedObjectTrigger val2 = (AnimatedObjectTrigger)(object)((val is AnimatedObjectTrigger) ? val : null);
							if (val2 == null || !(persistentMethodName == "TriggerAnimation") || !IsBell(val2))
							{
								continue;
							}
							return true;
						}
						if (!(persistentMethodName == "ToggleShipLights"))
						{
							continue;
						}
					}
					else if (!(persistentMethodName == "BeginUsingTerminal"))
					{
						continue;
					}
				}
				else if (!(persistentMethodName == "LeverAnimation") && !(persistentMethodName == "PullLever"))
				{
					continue;
				}
				return true;
			}
			return false;
		}

		private static bool IsBell(AnimatedObjectTrigger aot)
		{
			if ((Object)(object)aot == (Object)null)
			{
				return false;
			}
			Transform val = ((Component)aot).transform;
			while ((Object)(object)val != (Object)null)
			{
				if (((Object)val).name == "BellDinger")
				{
					return true;
				}
				val = val.parent;
			}
			return false;
		}

		private static bool LeverAnimationPrefix()
		{
			_leverAnimationRanUntied = !IsLeverBlocked();
			if (_leverAnimationRanUntied)
			{
				return true;
			}
			Feedback.Deny();
			return false;
		}

		private static bool PullLeverPrefix()
		{
			bool result = !HogtieState.IsLocalHogtied || _leverAnimationRanUntied;
			_leverAnimationRanUntied = false;
			return result;
		}

		private static bool BeginHoldingLeverPrefix()
		{
			return !IsLeverBlocked();
		}

		private static bool BeginUsingTerminalPrefix(Terminal __instance)
		{
			if (!HogtieState.IsLocalHogtied)
			{
				return true;
			}
			Feedback.Deny();
			InteractTrigger terminalTrigger = __instance.terminalTrigger;
			if ((Object)(object)terminalTrigger != (Object)null && (Object)(object)StartOfRound.Instance != (Object)null)
			{
				((MonoBehaviour)StartOfRound.Instance).StartCoroutine(StopSpecialAnimationNextFrame(terminalTrigger));
			}
			return false;
		}

		private static IEnumerator StopSpecialAnimationNextFrame(InteractTrigger trigger)
		{
			yield return null;
			if ((Object)(object)trigger != (Object)null)
			{
				trigger.StopSpecialAnimation();
			}
		}

		private static bool ToggleShipLightsPrefix()
		{
			if (!HogtieState.IsLocalHogtied)
			{
				return true;
			}
			Feedback.Deny();
			return false;
		}

		private static bool EnterBuildModePrefix(ShipBuildModeManager __instance, CallbackContext context)
		{
			PlayerControllerB local = Players.Local;
			if (!((CallbackContext)(ref context)).performed || !IsRestricted(local) || local.isTypingChat)
			{
				return true;
			}
			bool inBuildMode = __instance.InBuildMode;
			__instance.CancelBuildMode(true);
			if (inBuildMode || WouldEnterBuildMode(__instance, local))
			{
				Feedback.Deny();
			}
			return false;
		}

		private static bool WouldEnterBuildMode(ShipBuildModeManager manager, PlayerControllerB local)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: 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)
			manager.player = local;
			if (!manager.PlayerMeetsConditionsToBuild(false) || (Object)(object)local.gameplayCamera == (Object)null)
			{
				return false;
			}
			Transform transform = ((Component)local.gameplayCamera).transform;
			RaycastHit val = default(RaycastHit);
			if (!Physics.Raycast(transform.position, transform.forward, ref val, 4f, manager.placeableShipObjectsMask, (QueryTriggerInteraction)1) && !Physics.Raycast(transform.position + Vector3.up * 5f, Vector3.down, ref val, 5f, manager.placeableShipObjectsMask, (QueryTriggerInteraction)1))
			{
				return false;
			}
			if (((Component)((RaycastHit)(ref val)).collider).gameObject.CompareTag("PlaceableObject") && (Object)(object)((Component)((RaycastHit)(ref val)).collider).gameObject.GetComponent<PlaceableShipObject>() != (Object)null)
			{
				return manager.timeSincePlacingObject > 1f;
			}
			return false;
		}

		private static bool StoreObjectPrefix(ShipBuildModeManager __instance)
		{
			if (!IsRestricted(Players.Local))
			{
				return true;
			}
			if (__instance.InBuildMode)
			{
				Feedback.Deny();
			}
			__instance.CancelBuildMode(true);
			return false;
		}

		private static void OnLocalBecameHogtied()
		{
			StartOfRound instance = StartOfRound.Instance;
			if (!((Object)(object)instance == (Object)null))
			{
				((MonoBehaviour)instance).StartCoroutine(ReleaseEverything(++_dropToken));
			}
		}

		private static IEnumerator ReleaseEverything(int token)
		{
			yield return null;
			if (token != _dropToken || !HogtieState.IsLocalHogtied)
			{
				yield break;
			}
			Terminal val = Object.FindObjectOfType<Terminal>();
			PlayerControllerB local = Players.Local;
			if ((Object)(object)val != (Object)null && val.terminalInUse && (Object)(object)local != (Object)null && local.inTerminalMenu)
			{
				val.QuitTerminal(true);
				yield return null;
			}
			if ((Object)(object)ShipBuildModeManager.Instance != (Object)null)
			{
				ShipBuildModeManager.Instance.CancelBuildMode(true);
			}
			float giveUpWaitingAt = Time.realtimeSinceStartup + 3f;
			while (token == _dropToken && HogtieState.IsLocalHogtied)
			{
				PlayerControllerB local2 = Players.Local;
				if ((Object)(object)local2 != (Object)null && local2.isPlayerDead)
				{
					break;
				}
				bool flag = (Object)(object)local2 != (Object)null && (local2.isGrabbingObjectAnimation || local2.throwingObject);
				if ((Object)(object)local2 != (Object)null && local2.isPlayerControlled && (!flag || Time.realtimeSinceStartup >= giveUpWaitingAt))
				{
					if (HasItems(local2))
					{
						local2.DropAllHeldItemsAndSync(((Component)local2).transform.position, local2.localItemHolder.position, local2.localItemHolder.eulerAngles, local2.playerEye.position, local2.playerEye.eulerAngles);
					}
					break;
				}
				yield return null;
			}
		}

		private static bool HasItems(PlayerControllerB player)
		{
			if (player.isHoldingObject || (Object)(object)player.ItemOnlySlot != (Object)null)
			{
				return true;
			}
			GrabbableObject[] itemSlots = player.ItemSlots;
			for (int i = 0; i < itemSlots.Length; i++)
			{
				if ((Object)(object)itemSlots[i] != (Object)null)
				{
					return true;
				}
			}
			return false;
		}
	}
	internal static class TerminalCommands
	{
		private const string HogtieVerb = "hogtie";

		private const string UntieVerb = "untie";

		private static TerminalNode _node;

		public static void Install(Harmony harmony)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			harmony.Patch((MethodBase)AccessTools.Method(typeof(Terminal), "ParsePlayerSentence", (Type[])null, (Type[])null), new HarmonyMethod(typeof(TerminalCommands), "ParsePlayerSentencePrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static bool ParsePlayerSentencePrefix(Terminal __instance, ref TerminalNode __result)
		{
			string verb;
			string arg;
			try
			{
				if ((Object)(object)__instance.currentNode != (Object)null && __instance.currentNode.overrideOptions)
				{
					return true;
				}
				string text = __instance.screenText.text ?? "";
				int num = Mathf.Clamp(__instance.textAdded, 0, text.Length);
				if (!TrySplit(text.Substring(text.Length - num), out verb, out arg))
				{
					return true;
				}
				if (verb != "hogtie" && verb != "untie")
				{
					return true;
				}
			}
			catch (Exception arg2)
			{
				Plugin.Log.LogError((object)$"Reading terminal input failed: {arg2}");
				return true;
			}
			string text2;
			try
			{
				text2 = Handle(verb, arg);
			}
			catch (Exception arg3)
			{
				Plugin.Log.LogError((object)$"Terminal command '{verb}' failed: {arg3}");
				text2 = "Hogtied hit an error. See the log.";
			}
			try
			{
				__result = Node(text2);
				return false;
			}
			catch (Exception arg4)
			{
				Plugin.Log.LogError((object)$"Building terminal node failed: {arg4}");
				return true;
			}
		}

		private static bool TrySplit(string raw, out string verb, out string arg)
		{
			int i = 0;
			while (i < raw.Length)
			{
				for (; i < raw.Length && raw[i] == ' '; i++)
				{
				}
				int num = i;
				for (; i < raw.Length && raw[i] != ' '; i++)
				{
				}
				string text = StripPunctuation(raw.Substring(num, i - num));
				if (text.Length != 0)
				{
					verb = text;
					arg = raw.Substring(i).Trim();
					return true;
				}
			}
			verb = null;
			arg = null;
			return false;
		}

		private static string StripPunctuation(string s)
		{
			StringBuilder stringBuilder = new StringBuilder(s.Length);
			foreach (char c in s)
			{
				if (!char.IsPunctuation(c))
				{
					stringBuilder.Append(c);
				}
			}
			return stringBuilder.ToString().ToLowerInvariant();
		}

		private static string Handle(string verb, string arg)
		{
			bool flag = verb == "hogtie";
			if (!Messages.HostHasMod)
			{
				if (!Messages.AwaitingHostReply)
				{
					return "The host isn't running Hogtied.";
				}
				return "Still waiting for the host's Hogtied to answer. Try again in a few seconds.";
			}
			if (arg.Length == 0)
			{
				return Usage(verb);
			}
			if (!NameMatcher.TryMatch(arg, out var clientId, out var player, out var error))
			{
				return error;
			}
			string playerUsername = player.playerUsername;
			if (flag && clientId == Players.LocalClientId)
			{
				return "You can't start a hogtie vote on yourself.";
			}
			bool flag2 = HogtieState.IsHogtied(clientId);
			if (flag && flag2)
			{
				return playerUsername + " is already hogtied.";
			}
			if (!flag && !flag2)
			{
				return playerUsername + " is not hogtied.";
			}
			if (VoteState.Current != null)
			{
				return "A vote is already running.";
			}
			Messages.SendCommand(verb + " " + playerUsername);
			return "Vote requested: " + verb + " " + playerUsername + ".\nWatch chat for the vote, or for the host's reply if it is refused.";
		}

		private static string Usage(string verb)
		{
			StringBuilder stringBuilder = new StringBuilder("Usage: " + verb + " <name>\n\n");
			List<string> list = HogtieState.HogtiedClientIds.OrderBy((ulong id) => id).Select(Players.NameOf).ToList();
			if (list.Count == 0)
			{
				stringBuilder.Append("Nobody is hogtied.");
				return stringBuilder.ToString();
			}
			stringBuilder.Append("Hogtied:");
			foreach (string item in list)
			{
				stringBuilder.Append("\n  ").Append(item);
			}
			return stringBuilder.ToString();
		}

		private static TerminalNode Node(string text)
		{
			if ((Object)(object)_node == (Object)null)
			{
				_node = ScriptableObject.CreateInstance<TerminalNode>();
				((Object)_node).name = "HogtiedTerminalNode";
				((Object)_node).hideFlags = (HideFlags)61;
				_node.clearPreviousText = true;
				_node.maxCharactersToType = 35;
			}
			_node.displayText = text + "\n\n";
			return _node;
		}
	}
	internal static class VotePopup
	{
		internal const Key YesKey = (Key)94;

		internal const Key NoKey = (Key)95;

		private const float ResultSeconds = 4f;

		private const float StaleAfterSeconds = 10f;

		private static VotePopupRunner _runner;

		private static int _resolvedId = -1;

		private static float _resolvedUntil;

		private static float _updatedAt;

		public static void Install(Harmony harmony)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			harmony.Patch((MethodBase)AccessTools.Method(typeof(HUDManager), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(VotePopup), "HudAwakePostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			VoteState.Updated += OnVoteUpdated;
		}

		internal unsafe static string Label(Key key)
		{
			return ((object)(*(Key*)(&key))/*cast due to .constrained prefix*/).ToString();
		}

		internal static bool IsStale(VoteSnapshot vote)
		{
			if (vote != null && vote.IsRunning)
			{
				return vote.SecondsLeft - (Time.realtimeSinceStartup - _updatedAt) < -10f;
			}
			return false;
		}

		internal static bool ShowingResult(VoteSnapshot last)
		{
			if (last != null && !last.IsRunning && last.Id == _resolvedId)
			{
				return Time.realtimeSinceStartup < _resolvedUntil;
			}
			return false;
		}

		private static void OnVoteUpdated()
		{
			_updatedAt = Time.realtimeSinceStartup;
			VoteSnapshot last = VoteState.Last;
			if (last == null)
			{
				_resolvedId = -1;
			}
			else if (!last.IsRunning && last.Id != _resolvedId)
			{
				_resolvedId = last.Id;
				_resolvedUntil = Time.realtimeSinceStartup + 4f;
			}
		}

		private static void HudAwakePostfix()
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: 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_0027: Expected O, but got Unknown
			try
			{
				if (!((Object)(object)_runner != (Object)null))
				{
					GameObject val = new GameObject("HogtiedVotePopup")
					{
						hideFlags = (HideFlags)61
					};
					Object.DontDestroyOnLoad((Object)val);
					_runner = val.AddComponent<VotePopupRunner>();
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Creating vote popup failed: {arg}");
			}
		}
	}
	internal sealed class VotePopupRunner : MonoBehaviour
	{
		private const float PanelTop = 135f;

		private const float PanelWidth = 280f;

		private const float RowHeight = 19f;

		private const float Pad = 4f;

		private const float TitleSize = 13f;

		private const float BodySize = 12f;

		private GameObject _root;

		private TextMeshProUGUI _title;

		private TextMeshProUGUI _starter;

		private TextMeshProUGUI _keys;

		private TextMeshProUGUI _choice;

		private TextMeshProUGUI _tally;

		private TextMeshProUGUI _timer;

		private VoteSnapshot _shown;

		private int _shownSeconds = -1;

		private VoteSnapshot _sentOn;

		private bool _sentYes;

		private bool _errorLogged;

		private void Update()
		{
			try
			{
				HandleKeys();
				Refresh();
			}
			catch (Exception arg)
			{
				if (!_errorLogged)
				{
					_errorLogged = true;
					Plugin.Log.LogError((object)$"Vote popup update failed: {arg}");