Decompiled source of ItemLagFix v1.0.0

BepInEx/plugins/ItemLagFix/ItemLagFix.dll

Decompiled an hour 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 BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Steamworks;
using Steamworks.Data;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace ItemLagFix;

internal static class PCB
{
	internal static readonly FieldRef<PlayerControllerB, GrabbableObject> currentlyGrabbingObject = AccessTools.FieldRefAccess<PlayerControllerB, GrabbableObject>("currentlyGrabbingObject");

	internal static readonly FieldRef<PlayerControllerB, Coroutine> grabObjectCoroutine = AccessTools.FieldRefAccess<PlayerControllerB, Coroutine>("grabObjectCoroutine");

	internal static readonly FieldRef<PlayerControllerB, bool> grabbedObjectValidated = AccessTools.FieldRefAccess<PlayerControllerB, bool>("grabbedObjectValidated");

	internal static readonly FieldRef<PlayerControllerB, bool> grabInvalidated = AccessTools.FieldRefAccess<PlayerControllerB, bool>("grabInvalidated");

	internal static readonly FieldRef<PlayerControllerB, bool> throwingObject = AccessTools.FieldRefAccess<PlayerControllerB, bool>("throwingObject");

	private static readonly MethodInfo mFirstEmptyItemSlot = AccessTools.Method(typeof(PlayerControllerB), "FirstEmptyItemSlot", new Type[1] { typeof(GrabbableObject) }, (Type[])null);

	private static readonly MethodInfo mSwitchToItemSlot = AccessTools.Method(typeof(PlayerControllerB), "SwitchToItemSlot", new Type[2]
	{
		typeof(int),
		typeof(GrabbableObject)
	}, (Type[])null);

	private static readonly MethodInfo mSetSpecialGrabAnimationBool = AccessTools.Method(typeof(PlayerControllerB), "SetSpecialGrabAnimationBool", new Type[2]
	{
		typeof(bool),
		typeof(GrabbableObject)
	}, (Type[])null);

	private static readonly Func<PlayerControllerB, GrabbableObject, int> dFirstEmptyItemSlot = AccessTools.MethodDelegate<Func<PlayerControllerB, GrabbableObject, int>>(mFirstEmptyItemSlot, (object)null, true);

	private static readonly Action<PlayerControllerB, int, GrabbableObject> dSwitchToItemSlot = AccessTools.MethodDelegate<Action<PlayerControllerB, int, GrabbableObject>>(mSwitchToItemSlot, (object)null, true);

	private static readonly Action<PlayerControllerB, bool, GrabbableObject> dSetSpecialGrabAnimationBool = AccessTools.MethodDelegate<Action<PlayerControllerB, bool, GrabbableObject>>(mSetSpecialGrabAnimationBool, (object)null, true);

	internal static int FirstEmptyItemSlot(PlayerControllerB p, GrabbableObject o)
	{
		return dFirstEmptyItemSlot(p, o);
	}

	internal static void SwitchToItemSlot(PlayerControllerB p, int slot, GrabbableObject o)
	{
		dSwitchToItemSlot(p, slot, o);
	}

	internal static void SetSpecialGrabAnimationBool(PlayerControllerB p, bool on, GrabbableObject o)
	{
		dSetSpecialGrabAnimationBool(p, on, o);
	}
}
internal static class Net
{
	private static readonly FieldInfo execStage = AccessTools.Field(typeof(NetworkBehaviour), "__rpc_exec_stage");

	internal static bool IsRemoteClient
	{
		get
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton != (Object)null && singleton.IsClient && !singleton.IsServer)
			{
				return singleton.IsConnectedClient;
			}
			return false;
		}
	}

	internal static PlayerControllerB LocalPlayer
	{
		get
		{
			GameNetworkManager instance = GameNetworkManager.Instance;
			if (!((Object)(object)instance != (Object)null))
			{
				return null;
			}
			return instance.localPlayerController;
		}
	}

	internal static bool IsLocalPlayer(PlayerControllerB p)
	{
		if ((Object)(object)p != (Object)null && ((NetworkBehaviour)p).IsOwner)
		{
			return (Object)(object)p == (Object)(object)LocalPlayer;
		}
		return false;
	}

	internal static bool IsExecutingRpc(NetworkBehaviour b)
	{
		if (execStage == null)
		{
			return true;
		}
		try
		{
			return Convert.ToInt32(execStage.GetValue(b)) == 1;
		}
		catch
		{
			return true;
		}
	}
}
internal sealed class AckCounter<TKey>
{
	private struct Entry
	{
		public int Count;

		public float Time;
	}

	private readonly Dictionary<TKey, Entry> map = new Dictionary<TKey, Entry>();

	private readonly float expiry;

	private readonly string name;

	internal AckCounter(string name, float expirySeconds = 20f)
	{
		this.name = name;
		expiry = expirySeconds;
	}

	internal void Add(TKey key)
	{
		map.TryGetValue(key, out var value);
		value.Count++;
		value.Time = Time.realtimeSinceStartup;
		map[key] = value;
	}

	internal bool TryConsume(TKey key)
	{
		if (!map.TryGetValue(key, out var value))
		{
			return false;
		}
		if (Time.realtimeSinceStartup - value.Time > expiry)
		{
			map.Remove(key);
			Plugin.Debug($"[{name}] dropped stale pending confirmation for {key}");
			return false;
		}
		value.Count--;
		if (value.Count <= 0)
		{
			map.Remove(key);
		}
		else
		{
			map[key] = value;
		}
		return true;
	}

	internal void Clear()
	{
		map.Clear();
	}
}
internal static class DropPrediction
{
	internal static readonly AckCounter<ulong> ThrowAcks = new AckCounter<ulong>("throw");

	internal static readonly AckCounter<ulong> PlaceAcks = new AckCounter<ulong>("place");

	internal static readonly AckCounter<ulong> DespawnAcks = new AckCounter<ulong>("despawn");

	internal static void Apply()
	{
		Type? typeFromHandle = typeof(PlayerControllerB);
		Type typeFromHandle2 = typeof(DropPrediction);
		Plugin.Patch(AccessTools.Method(typeFromHandle, "ThrowObjectServerRpc", (Type[])null, (Type[])null), "throw prediction", null, Plugin.HM(typeFromHandle2, "ThrowServerRpcPostfix"));
		Plugin.Patch(AccessTools.Method(typeFromHandle, "ThrowObjectClientRpc", (Type[])null, (Type[])null), "throw echo", Plugin.HM(typeFromHandle2, "ThrowClientRpcPrefix"));
		Plugin.Patch(AccessTools.Method(typeFromHandle, "PlaceObjectServerRpc", (Type[])null, (Type[])null), "place prediction", null, Plugin.HM(typeFromHandle2, "PlaceServerRpcPostfix"));
		Plugin.Patch(AccessTools.Method(typeFromHandle, "PlaceObjectClientRpc", (Type[])null, (Type[])null), "place echo", Plugin.HM(typeFromHandle2, "PlaceClientRpcPrefix"));
		Plugin.Patch(AccessTools.Method(typeFromHandle, "DespawnHeldObject", (Type[])null, (Type[])null), "despawn prediction", Plugin.HM(typeFromHandle2, "DespawnPrefix"), Plugin.HM(typeFromHandle2, "DespawnPostfix"));
		Plugin.Patch(AccessTools.Method(typeFromHandle, "DespawnHeldObjectClientRpc", (Type[])null, (Type[])null), "despawn echo", Plugin.HM(typeFromHandle2, "DespawnClientRpcPrefix"));
	}

	internal static void Reset()
	{
		ThrowAcks.Clear();
		PlaceAcks.Clear();
		DespawnAcks.Clear();
	}

	private static bool Active(PlayerControllerB p)
	{
		if (Plugin.PredictDrops.Value && Net.IsRemoteClient)
		{
			return Net.IsLocalPlayer(p);
		}
		return false;
	}

	private static void ApplyOwnerEcho(PlayerControllerB p, GrabbableObject obj)
	{
		if (!obj.itemProperties.syncDiscardFunction)
		{
			obj.playerHeldBy = null;
		}
		if ((Object)(object)p.currentlyHeldObjectServer == (Object)(object)obj)
		{
			p.currentlyHeldObjectServer = null;
		}
		PCB.throwingObject.Invoke(p) = false;
	}

	private static void ThrowServerRpcPostfix(PlayerControllerB __instance, NetworkObjectReference grabbedObject)
	{
		NetworkObject val = default(NetworkObject);
		if (Active(__instance) && ((NetworkObjectReference)(ref grabbedObject)).TryGet(ref val, (NetworkManager)null) && !((Object)(object)val == (Object)null))
		{
			GrabbableObject component = ((Component)val).GetComponent<GrabbableObject>();
			if (!((Object)(object)component == (Object)null))
			{
				ApplyOwnerEcho(__instance, component);
				ThrowAcks.Add(val.NetworkObjectId);
				Plugin.Debug($"Predicted drop of {component.itemProperties.itemName} ({val.NetworkObjectId})");
			}
		}
	}

	private static bool ThrowClientRpcPrefix(PlayerControllerB __instance, NetworkObjectReference grabbedObject)
	{
		if (!((NetworkBehaviour)__instance).IsOwner || !Net.IsRemoteClient || !Net.IsExecutingRpc((NetworkBehaviour)(object)__instance))
		{
			return true;
		}
		if (!ThrowAcks.TryConsume(((NetworkObjectReference)(ref grabbedObject)).NetworkObjectId))
		{
			return true;
		}
		Plugin.Debug($"Swallowed drop confirmation for {((NetworkObjectReference)(ref grabbedObject)).NetworkObjectId}");
		return false;
	}

	private static void PlaceServerRpcPostfix(PlayerControllerB __instance, NetworkObjectReference grabbedObject)
	{
		NetworkObject val = default(NetworkObject);
		if (Active(__instance) && ((NetworkObjectReference)(ref grabbedObject)).TryGet(ref val, (NetworkManager)null) && !((Object)(object)val == (Object)null))
		{
			GrabbableObject component = ((Component)val).GetComponent<GrabbableObject>();
			if (!((Object)(object)component == (Object)null))
			{
				ApplyOwnerEcho(__instance, component);
				PlaceAcks.Add(val.NetworkObjectId);
				Plugin.Debug($"Predicted placement of {component.itemProperties.itemName} ({val.NetworkObjectId})");
			}
		}
	}

	private static bool PlaceClientRpcPrefix(PlayerControllerB __instance, NetworkObjectReference grabbedObject)
	{
		if (!((NetworkBehaviour)__instance).IsOwner || !Net.IsRemoteClient || !Net.IsExecutingRpc((NetworkBehaviour)(object)__instance))
		{
			return true;
		}
		if (!PlaceAcks.TryConsume(((NetworkObjectReference)(ref grabbedObject)).NetworkObjectId))
		{
			return true;
		}
		Plugin.Debug($"Swallowed placement confirmation for {((NetworkObjectReference)(ref grabbedObject)).NetworkObjectId}");
		return false;
	}

	private static void DespawnPrefix(PlayerControllerB __instance, out GrabbableObject __state)
	{
		__state = __instance.currentlyHeldObjectServer;
	}

	private static void DespawnPostfix(PlayerControllerB __instance, GrabbableObject __state)
	{
		if (!((Object)(object)__state == (Object)null) && Plugin.PredictKeyDespawn.Value && Net.IsRemoteClient && Net.IsLocalPlayer(__instance))
		{
			try
			{
				__state.EnableItemMeshes(false);
			}
			catch
			{
			}
			PCB.throwingObject.Invoke(__instance) = false;
			DespawnAcks.Add(__instance.playerClientId);
			Plugin.Debug("Predicted despawn of held " + __state.itemProperties.itemName);
		}
	}

	private static bool DespawnClientRpcPrefix(PlayerControllerB __instance)
	{
		if (!((NetworkBehaviour)__instance).IsOwner || !Net.IsRemoteClient || !Net.IsExecutingRpc((NetworkBehaviour)(object)__instance))
		{
			return true;
		}
		return !DespawnAcks.TryConsume(__instance.playerClientId);
	}
}
internal static class FurniturePrediction
{
	private static readonly AckCounter<int> ConfirmAcks = new AckCounter<int>("furniture");

	private static readonly Func<PlaceableObjectsSurface, Transform, GrabbableObject, Vector3> itemPlacementPosition = AccessTools.MethodDelegate<Func<PlaceableObjectsSurface, Transform, GrabbableObject, Vector3>>(AccessTools.Method(typeof(PlaceableObjectsSurface), "itemPlacementPosition", (Type[])null, (Type[])null), (object)null, true);

	internal static void Apply()
	{
		Type? typeFromHandle = typeof(PlaceableObjectsSurface);
		Type typeFromHandle2 = typeof(FurniturePrediction);
		Plugin.Patch(AccessTools.Method(typeFromHandle, "PlaceObject", (Type[])null, (Type[])null), "furniture prediction", Plugin.HM(typeFromHandle2, "PlaceObjectPrefix"));
		Plugin.Patch(AccessTools.Method(typeFromHandle, "ConfirmPlaceOnFurnitureClientRpc", (Type[])null, (Type[])null), "furniture echo", Plugin.HM(typeFromHandle2, "ConfirmPrefix"));
	}

	internal static void Reset()
	{
		ConfirmAcks.Clear();
	}

	private static bool PlaceObjectPrefix(PlaceableObjectsSurface __instance, PlayerControllerB playerWhoTriggered)
	{
		//IL_007b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0080: Unknown result type (might be due to invalid IL or missing references)
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_0082: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b8: 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_00be: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
		if (!Plugin.PredictFurniturePlacement.Value || !Net.IsRemoteClient || !Net.IsLocalPlayer(playerWhoTriggered))
		{
			return true;
		}
		if (!playerWhoTriggered.isHoldingObject || playerWhoTriggered.isGrabbingObjectAnimation || (Object)(object)playerWhoTriggered.currentlyHeldObjectServer == (Object)null)
		{
			return true;
		}
		if ((Object)(object)__instance.parentTo == (Object)null || !__instance.parentTo.IsSpawned || !((NetworkBehaviour)__instance).IsSpawned)
		{
			return true;
		}
		Vector3 val = itemPlacementPosition(__instance, ((Component)playerWhoTriggered.gameplayCamera).transform, playerWhoTriggered.currentlyHeldObjectServer);
		if (val == Vector3.zero)
		{
			return false;
		}
		__instance.CheckIfFurnitureIsAvailableForPlacingServerRpc((int)playerWhoTriggered.playerClientId);
		ConfirmAcks.Add(((Object)__instance).GetInstanceID());
		val = ((Component)__instance.parentTo).transform.InverseTransformPoint(val);
		playerWhoTriggered.DiscardHeldObject(true, __instance.parentTo, val, false);
		Plugin.Debug("Predicted furniture placement");
		return false;
	}

	private static bool ConfirmPrefix(PlaceableObjectsSurface __instance, int playerId)
	{
		if (!Net.IsRemoteClient || !Net.IsExecutingRpc((NetworkBehaviour)(object)__instance))
		{
			return true;
		}
		PlayerControllerB localPlayer = Net.LocalPlayer;
		if ((Object)(object)localPlayer == (Object)null || (int)localPlayer.playerClientId != playerId)
		{
			return true;
		}
		return !ConfirmAcks.TryConsume(((Object)__instance).GetInstanceID());
	}
}
internal sealed class GrabState
{
	internal PlayerControllerB P;

	internal GrabbableObject Obj;

	internal ulong Id;

	internal int PrevSlot;

	internal int Slot = -1;

	internal bool Applied;

	internal bool Acked;

	internal bool Invalidated;

	internal bool Finalized;

	internal bool LockHeld;

	internal float Start;

	internal float AckTime;

	internal int AliveFrame;

	internal Transform OldParent;

	internal Vector3 OldLocalPos;

	internal Vector3 OldLocalScale;

	internal Quaternion OldLocalRot;

	internal bool OldHasHitGround;

	internal bool OldReachedFloorTarget;

	internal bool OldInFactory;

	internal bool OldInElevator;

	internal bool OldInShipRoom;

	internal bool OldHasBeenHeld;

	internal float OldFallTime;

	internal Vector3 OldTargetFloor;

	internal Vector3 OldStartFalling;

	internal int OldFloorYRot;

	internal bool CoroutineAlive => Time.frameCount - AliveFrame <= 2;
}
internal static class GrabPrediction
{
	internal static readonly Dictionary<ulong, GrabState> States = new Dictionary<ulong, GrabState>();

	private const float AckTimeout = 15f;

	private const float OwnershipGrace = 3f;

	private static string blocklistRaw;

	private static HashSet<string> blocklist = new HashSet<string>();

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

	internal static void Apply()
	{
		Type? typeFromHandle = typeof(PlayerControllerB);
		Type typeFromHandle2 = typeof(GrabPrediction);
		Plugin.Patch(AccessTools.Method(typeFromHandle, "GrabObject", (Type[])null, (Type[])null), "grab prediction", Plugin.HM(typeFromHandle2, "GrabObjectPrefix"));
		Plugin.Patch(AccessTools.Method(typeFromHandle, "GrabObjectClientRpc", (Type[])null, (Type[])null), "grab confirmation", Plugin.HM(typeFromHandle2, "GrabClientRpcPrefix"));
	}

	internal static void Reset()
	{
		States.Clear();
	}

	internal static GrabState LockingStateFor(PlayerControllerB p)
	{
		foreach (GrabState value in States.Values)
		{
			if ((Object)(object)value.P == (Object)(object)p && value.LockHeld && value.CoroutineAlive)
			{
				return value;
			}
		}
		return null;
	}

	private static bool Blocked(GrabbableObject obj)
	{
		string text = Plugin.GrabBlocklist.Value ?? "";
		if ((object)text != blocklistRaw)
		{
			blocklistRaw = text;
			blocklist = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			string[] array = text.Split(',');
			for (int i = 0; i < array.Length; i++)
			{
				string text2 = array[i].Trim();
				if (text2.Length > 0)
				{
					blocklist.Add(text2);
				}
			}
		}
		if (blocklist.Count > 0 && (Object)(object)obj.itemProperties != (Object)null)
		{
			return blocklist.Contains(obj.itemProperties.itemName ?? "");
		}
		return false;
	}

	internal static bool IsOwnerSensitive(Type type)
	{
		if (sensitiveCache.TryGetValue(type, out var value))
		{
			return value;
		}
		bool flag = false;
		HashSet<MethodBase> visited = new HashSet<MethodBase>();
		Type type2 = type;
		while (type2 != null && type2 != typeof(GrabbableObject) && !flag)
		{
			MethodInfo methodInfo = AccessTools.DeclaredMethod(type2, "EquipItem", Type.EmptyTypes, (Type[])null);
			if (methodInfo != null && ScanSensitive(methodInfo, 0, visited))
			{
				flag = true;
			}
			type2 = type2.BaseType;
		}
		sensitiveCache[type] = flag;
		if (flag)
		{
			Plugin.Debug(type.Name + " picks up with ownership-dependent code; not predicting its grab");
		}
		return flag;
	}

	private static bool ScanSensitive(MethodBase m, int depth, HashSet<MethodBase> visited)
	{
		if (m == null || !visited.Add(m))
		{
			return false;
		}
		List<CodeInstruction> originalInstructions;
		try
		{
			originalInstructions = PatchProcessor.GetOriginalInstructions(m, (ILGenerator)null);
		}
		catch
		{
			return true;
		}
		foreach (CodeInstruction item in originalInstructions)
		{
			if (!(item.operand is MethodBase methodBase))
			{
				continue;
			}
			string name = methodBase.Name;
			switch (name)
			{
			default:
				if (!name.EndsWith("Rpc", StringComparison.Ordinal))
				{
					if (depth >= 3)
					{
						break;
					}
					Type declaringType = methodBase.DeclaringType;
					if (!(declaringType == null) && !(declaringType == typeof(GrabbableObject)) && typeof(GrabbableObject).IsAssignableFrom(declaringType))
					{
						if (ScanSensitive(methodBase, depth + 1, visited))
						{
							return true;
						}
						IteratorStateMachineAttribute customAttribute = methodBase.GetCustomAttribute<IteratorStateMachineAttribute>();
						if (customAttribute != null && ScanSensitive(AccessTools.Method(customAttribute.StateMachineType, "MoveNext", (Type[])null, (Type[])null), depth + 1, visited))
						{
							return true;
						}
					}
					break;
				}
				goto case "get_IsOwner";
			case "get_IsOwner":
			case "get_OwnerClientId":
			case "ChangeOwnership":
				return true;
			}
		}
		return false;
	}

	private static bool GrabObjectPrefix(PlayerControllerB __instance, ref IEnumerator __result)
	{
		try
		{
			if (!Plugin.PredictGrabs.Value || !Net.IsRemoteClient || !Net.IsLocalPlayer(__instance))
			{
				return true;
			}
			if (__instance.isTestingPlayer)
			{
				return true;
			}
			GrabbableObject val = PCB.currentlyGrabbingObject.Invoke(__instance);
			if ((Object)(object)val == (Object)null || (Object)(object)val.itemProperties == (Object)null || val.isHeld || val.isPocketed)
			{
				return true;
			}
			NetworkObject networkObject = ((NetworkBehaviour)val).NetworkObject;
			if ((Object)(object)networkObject == (Object)null || !networkObject.IsSpawned)
			{
				return true;
			}
			if (States.ContainsKey(networkObject.NetworkObjectId))
			{
				return true;
			}
			if (Blocked(val) || IsOwnerSensitive(((object)val).GetType()))
			{
				return true;
			}
			if (PCB.FirstEmptyItemSlot(__instance, val) == -1)
			{
				return true;
			}
			GrabState grabState = new GrabState
			{
				P = __instance,
				Obj = val,
				Id = networkObject.NetworkObjectId,
				Start = Time.time,
				AliveFrame = Time.frameCount,
				LockHeld = true
			};
			States[grabState.Id] = grabState;
			__result = Run(grabState);
			return false;
		}
		catch (Exception arg)
		{
			Plugin.Log.LogError((object)$"Grab prediction setup failed, using vanilla grab: {arg}");
			return true;
		}
	}

	private static bool GrabClientRpcPrefix(PlayerControllerB __instance, bool grabValidated, NetworkObjectReference grabbedObject)
	{
		if (!((NetworkBehaviour)__instance).IsOwner || !Net.IsRemoteClient || !Net.IsExecutingRpc((NetworkBehaviour)(object)__instance))
		{
			return true;
		}
		if (!States.TryGetValue(((NetworkObjectReference)(ref grabbedObject)).NetworkObjectId, out var value) || (Object)(object)value.P != (Object)(object)__instance)
		{
			return true;
		}
		try
		{
			if (grabValidated)
			{
				value.Acked = true;
				value.AckTime = Time.time;
				Plugin.Debug("Host confirmed grab of " + Name(value));
				if (!value.CoroutineAlive)
				{
					FinishGrab(value);
					if ((Object)(object)PCB.currentlyGrabbingObject.Invoke(value.P) == (Object)(object)value.Obj && value.P.isGrabbingObjectAnimation)
					{
						ReleaseLock(value, replay: false);
					}
					States.Remove(value.Id);
				}
			}
			else
			{
				value.Invalidated = true;
				Plugin.Debug("Host refused grab of " + Name(value) + "; undoing");
				if (!value.CoroutineAlive)
				{
					Rollback(value, (Object)(object)PCB.currentlyGrabbingObject.Invoke(value.P) == (Object)(object)value.Obj);
				}
			}
		}
		catch (Exception arg)
		{
			Plugin.Log.LogError((object)$"Error handling grab confirmation: {arg}");
		}
		return false;
	}

	private static string Name(GrabState s)
	{
		if (!((Object)(object)s.Obj != (Object)null) || !((Object)(object)s.Obj.itemProperties != (Object)null))
		{
			return "?";
		}
		return s.Obj.itemProperties.itemName;
	}

	private static IEnumerator Run(GrabState s)
	{
		PlayerControllerB p = s.P;
		GrabbableObject obj = s.Obj;
		PCB.grabbedObjectValidated.Invoke(p) = false;
		PCB.grabInvalidated.Invoke(p) = false;
		try
		{
			ApplyPredictedGrab(s);
		}
		catch (Exception arg)
		{
			Plugin.Log.LogError((object)$"Predicting grab of {Name(s)} failed: {arg}");
		}
		while (Time.time - s.Start < 0.1f && !s.Invalidated)
		{
			s.AliveFrame = Time.frameCount;
			yield return null;
		}
		s.AliveFrame = Time.frameCount;
		if (!s.Invalidated && (Object)(object)obj != (Object)null)
		{
			try
			{
				AudioClip[] playerGrabSFX = StartOfRound.Instance.playerGrabSFX;
				if (playerGrabSFX != null && playerGrabSFX.Length != 0)
				{
					p.itemAudio.PlayOneShot(playerGrabSFX[Random.Range(0, playerGrabSFX.Length)]);
				}
				if ((Object)(object)PCB.currentlyGrabbingObject.Invoke(p) == (Object)(object)obj)
				{
					obj.parentObject = p.localItemHolder;
				}
				if ((Object)(object)obj.itemProperties.grabSFX != (Object)null)
				{
					p.itemAudio.PlayOneShot(obj.itemProperties.grabSFX, 1f);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)ex);
			}
		}
		float animEnd = Time.time + Mathf.Max(0f, p.grabObjectAnimationTime - 0.2f);
		while (true)
		{
			s.AliveFrame = Time.frameCount;
			if (s.Invalidated)
			{
				Rollback(s, ownsLock: true);
				yield break;
			}
			if (!s.Finalized && s.Acked && (Object)(object)obj != (Object)null && (((NetworkBehaviour)obj).IsOwner || Time.time - s.AckTime > 3f))
			{
				FinishGrab(s);
			}
			if (s.Finalized && Time.time >= animEnd)
			{
				break;
			}
			if (!s.Acked && Time.time - s.Start > 15f)
			{
				Plugin.Log.LogWarning((object)$"No answer from host about picking up {Name(s)} after {15f} s; undoing the pick-up.");
				Rollback(s, ownsLock: true);
				yield break;
			}
			yield return null;
		}
		ReleaseLock(s, replay: true);
		States.Remove(s.Id);
	}

	private static void ApplyPredictedGrab(GrabState s)
	{
		//IL_0023: 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_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_009b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
		PlayerControllerB p = s.P;
		GrabbableObject obj = s.Obj;
		Transform transform = ((Component)obj).transform;
		s.OldParent = transform.parent;
		s.OldLocalPos = transform.localPosition;
		s.OldLocalRot = transform.localRotation;
		s.OldLocalScale = transform.localScale;
		s.OldHasHitGround = obj.hasHitGround;
		s.OldReachedFloorTarget = obj.reachedFloorTarget;
		s.OldInFactory = obj.isInFactory;
		s.OldInElevator = obj.isInElevator;
		s.OldInShipRoom = obj.isInShipRoom;
		s.OldHasBeenHeld = obj.hasBeenHeld;
		s.OldFallTime = obj.fallTime;
		s.OldTargetFloor = obj.targetFloorPosition;
		s.OldStartFalling = obj.startFallingPosition;
		s.OldFloorYRot = obj.floorYRot;
		s.PrevSlot = p.currentItemSlot;
		s.Slot = PCB.FirstEmptyItemSlot(p, obj);
		PCB.SwitchToItemSlot(p, s.Slot, obj);
		s.Applied = true;
		GrabbableObject currentlyHeldObjectServer = p.currentlyHeldObjectServer;
		if ((Object)(object)currentlyHeldObjectServer == (Object)null)
		{
			return;
		}
		currentlyHeldObjectServer.EnablePhysics(false);
		currentlyHeldObjectServer.isHeld = true;
		currentlyHeldObjectServer.hasHitGround = false;
		currentlyHeldObjectServer.isInFactory = p.isInsideFactory;
		p.SetItemInElevator(p.isInHangarShipRoom, p.isInElevator, currentlyHeldObjectServer);
		StartOfRound val = (((Object)(object)p.playersManager != (Object)null) ? p.playersManager : StartOfRound.Instance);
		Transform parent = ((Component)currentlyHeldObjectServer).transform.parent;
		if ((Object)(object)parent != (Object)(object)val.propsContainer && (Object)(object)parent != (Object)(object)val.elevatorTransform)
		{
			((Component)currentlyHeldObjectServer).transform.SetParent(currentlyHeldObjectServer.isInElevator ? val.elevatorTransform : val.propsContainer, true);
		}
		p.twoHanded = currentlyHeldObjectServer.itemProperties.twoHanded;
		p.twoHandedAnimation = currentlyHeldObjectServer.itemProperties.twoHandedAnimation;
		if (p.currentItemSlot == 50 && !StartOfRound.Instance.localHasGrabbedAnItemBefore)
		{
			try
			{
				if (!ES3.Load<bool>("grabbedItemBefore", "LCGeneralSaveData", false))
				{
					HUDManager.Instance.DisplayTip("Equipped to utility belt!", "Press TAB to select the utility belt. This can only hold one-handed tools.", false, false, "LC_Tip1");
					Animator component = ((Component)HUDManager.Instance.itemOnlySlotIconFrame).GetComponent<Animator>();
					if ((Object)(object)component != (Object)null)
					{
						component.SetTrigger("firstTimeSelected");
					}
					ES3.Save<bool>("grabbedItemBefore", true, "LCGeneralSaveData");
				}
				else
				{
					StartOfRound.Instance.localHasGrabbedAnItemBefore = true;
				}
			}
			catch (Exception ex)
			{
				Plugin.Debug("utility belt tip: " + ex.Message);
			}
		}
		Plugin.Debug($"Predicted grab of {Name(s)} into slot {s.Slot}");
	}

	private static void FinishGrab(GrabState s)
	{
		if (s.Finalized)
		{
			return;
		}
		s.Finalized = true;
		PlayerControllerB p = s.P;
		PCB.grabbedObjectValidated.Invoke(p) = true;
		if ((Object)(object)p.currentlyHeldObjectServer != (Object)null && (Object)(object)p.currentlyHeldObjectServer == (Object)(object)s.Obj)
		{
			if (((NetworkBehaviour)s.Obj).IsOwner)
			{
				s.Obj.GrabItemOnClient();
			}
			else
			{
				Plugin.Log.LogWarning((object)("Host confirmed " + Name(s) + " but never gave us ownership; item functions may not work until re-grabbed."));
			}
			p.isHoldingObject = true;
		}
	}

	private static void ReleaseLock(GrabState s, bool replay)
	{
		//IL_0033: 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)
		PlayerControllerB p = s.P;
		s.LockHeld = false;
		p.playerBodyAnimator.SetBool("GrabValidated", true);
		p.isGrabbingObjectAnimation = false;
		if (p.queueDiscardObject)
		{
			p.DiscardHeldObject(false, (NetworkObject)null, default(Vector3), true);
			p.queueDiscardObject = false;
		}
		if (replay)
		{
			InputBuffer.Replay(p);
		}
		else
		{
			InputBuffer.Clear(p);
		}
	}

	private static void Rollback(GrabState s, bool ownsLock)
	{
		//IL_014a: Unknown result type (might be due to invalid IL or missing references)
		//IL_015b: Unknown result type (might be due to invalid IL or missing references)
		//IL_016c: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
		States.Remove(s.Id);
		s.LockHeld = false;
		PlayerControllerB p = s.P;
		GrabbableObject obj = s.Obj;
		try
		{
			bool flag = false;
			if (s.Applied && (Object)(object)obj != (Object)null)
			{
				if (s.Slot == 50)
				{
					if ((Object)(object)p.ItemOnlySlot == (Object)(object)obj)
					{
						p.ItemOnlySlot = null;
						((Behaviour)HUDManager.Instance.itemOnlySlotIcon).enabled = false;
					}
				}
				else if (s.Slot >= 0 && s.Slot < p.ItemSlots.Length && (Object)(object)p.ItemSlots[s.Slot] == (Object)(object)obj)
				{
					p.ItemSlots[s.Slot] = null;
					if (s.Slot < HUDManager.Instance.itemSlotIcons.Length)
					{
						((Behaviour)HUDManager.Instance.itemSlotIcons[s.Slot]).enabled = false;
					}
				}
				if ((Object)(object)p.currentlyHeldObjectServer == (Object)(object)obj)
				{
					flag = true;
					p.currentlyHeldObjectServer = null;
				}
				if ((Object)(object)obj.playerHeldBy == (Object)(object)p)
				{
					obj.playerHeldBy = null;
					obj.parentObject = null;
					obj.isHeld = false;
					obj.isPocketed = false;
					p.SetItemInElevator(s.OldInShipRoom, s.OldInElevator, obj);
					((Component)obj).transform.SetParent(s.OldParent, false);
					((Component)obj).transform.localPosition = s.OldLocalPos;
					((Component)obj).transform.localRotation = s.OldLocalRot;
					((Component)obj).transform.localScale = s.OldLocalScale;
					obj.EnablePhysics(true);
					obj.EnableItemMeshes(true);
					obj.hasHitGround = s.OldHasHitGround;
					obj.reachedFloorTarget = s.OldReachedFloorTarget;
					obj.isInFactory = s.OldInFactory;
					obj.fallTime = s.OldFallTime;
					obj.targetFloorPosition = s.OldTargetFloor;
					obj.startFallingPosition = s.OldStartFalling;
					obj.floorYRot = s.OldFloorYRot;
					if (!s.OldHasBeenHeld && obj.hasBeenHeld)
					{
						obj.hasBeenHeld = false;
						StartOfRound instance = StartOfRound.Instance;
						if (!s.OldInShipRoom && (Object)(object)instance != (Object)null && !instance.inShipPhase && (Object)(object)instance.currentLevel != (Object)null && instance.currentLevel.spawnEnemiesAndScrap && (Object)(object)RoundManager.Instance != (Object)null)
						{
							RoundManager instance2 = RoundManager.Instance;
							instance2.valueOfFoundScrapItems -= obj.scrapValue;
						}
					}
				}
				else if ((Object)(object)obj.playerHeldBy != (Object)null && (Object)(object)obj.parentObject == (Object)(object)p.localItemHolder)
				{
					obj.parentObject = obj.playerHeldBy.serverItemHolder;
				}
			}
			if (ownsLock)
			{
				if (flag && !p.isPlayerDead && p.isPlayerControlled)
				{
					PCB.SwitchToItemSlot(p, s.PrevSlot, null);
				}
				else
				{
					p.twoHanded = false;
				}
				PCB.SetSpecialGrabAnimationBool(p, on: false, obj);
				if ((Object)(object)p.currentlyHeldObjectServer != (Object)null)
				{
					p.playerBodyAnimator.SetBool("Grab", true);
				}
				p.playerBodyAnimator.SetBool("GrabInvalidated", true);
				p.isGrabbingObjectAnimation = false;
				PCB.currentlyGrabbingObject.Invoke(p) = null;
				p.queueDiscardObject = false;
				PCB.grabInvalidated.Invoke(p) = false;
				InputBuffer.Clear(p);
			}
			if ((Object)(object)obj != (Object)null && (Object)(object)obj.itemProperties != (Object)null)
			{
				p.carryWeight = Mathf.Clamp(p.carryWeight - (obj.itemProperties.weight - 1f), 1f, 10f);
				StartOfRound.Instance.SendChangedWeightEvent();
			}
		}
		catch (Exception arg)
		{
			Plugin.Log.LogError((object)$"Undoing grab of {Name(s)} failed: {arg}");
			if (ownsLock)
			{
				p.isGrabbingObjectAnimation = false;
				PCB.currentlyGrabbingObject.Invoke(p) = null;
			}
		}
	}
}
internal static class InputBuffer
{
	private enum Kind
	{
		Use,
		UseRelease,
		Drop,
		Interact
	}

	private struct Press
	{
		public Kind Kind;

		public float Time;
	}

	private static readonly List<Press> presses = new List<Press>();

	private static bool replaying;

	internal static void Apply()
	{
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Expected O, but got Unknown
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_0053: Expected O, but got Unknown
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Expected O, but got Unknown
		//IL_0095: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a6: Expected O, but got Unknown
		//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d2: Expected O, but got Unknown
		Type? typeFromHandle = typeof(PlayerControllerB);
		Type typeFromHandle2 = typeof(InputBuffer);
		HarmonyMethod val = new HarmonyMethod(AccessTools.Method(typeFromHandle2, "ForcePerformed", (Type[])null, (Type[])null));
		Harmony.ReversePatch((MethodBase)AccessTools.Method(typeFromHandle, "ActivateItem_performed", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.Method(typeFromHandle2, "VanillaUse", (Type[])null, (Type[])null)), val.method, (MethodInfo)null);
		Harmony.ReversePatch((MethodBase)AccessTools.Method(typeFromHandle, "ActivateItem_canceled", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.Method(typeFromHandle2, "VanillaUseRelease", (Type[])null, (Type[])null)), (MethodInfo)null, (MethodInfo)null);
		Harmony.ReversePatch((MethodBase)AccessTools.Method(typeFromHandle, "Discard_performed", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.Method(typeFromHandle2, "VanillaDrop", (Type[])null, (Type[])null)), val.method, (MethodInfo)null);
		Harmony.ReversePatch((MethodBase)AccessTools.Method(typeFromHandle, "Interact_performed", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.Method(typeFromHandle2, "VanillaInteract", (Type[])null, (Type[])null)), val.method, (MethodInfo)null);
		Plugin.Patch(AccessTools.Method(typeFromHandle, "ActivateItem_performed", (Type[])null, (Type[])null), "buffer use", Plugin.HM(typeFromHandle2, "UsePrefix"));
		Plugin.Patch(AccessTools.Method(typeFromHandle, "ActivateItem_canceled", (Type[])null, (Type[])null), "buffer use release", Plugin.HM(typeFromHandle2, "UseReleasePrefix"));
		Plugin.Patch(AccessTools.Method(typeFromHandle, "Discard_performed", (Type[])null, (Type[])null), "buffer drop", Plugin.HM(typeFromHandle2, "DropPrefix"));
		Plugin.Patch(AccessTools.Method(typeFromHandle, "Interact_performed", (Type[])null, (Type[])null), "buffer interact", Plugin.HM(typeFromHandle2, "InteractPrefix"));
	}

	[MethodImpl(MethodImplOptions.NoInlining)]
	private static void VanillaUse(PlayerControllerB instance, CallbackContext context)
	{
		throw new NotImplementedException("reverse patch");
	}

	[MethodImpl(MethodImplOptions.NoInlining)]
	private static void VanillaUseRelease(PlayerControllerB instance, CallbackContext context)
	{
		throw new NotImplementedException("reverse patch");
	}

	[MethodImpl(MethodImplOptions.NoInlining)]
	private static void VanillaDrop(PlayerControllerB instance, CallbackContext context)
	{
		throw new NotImplementedException("reverse patch");
	}

	[MethodImpl(MethodImplOptions.NoInlining)]
	private static void VanillaInteract(PlayerControllerB instance, CallbackContext context)
	{
		throw new NotImplementedException("reverse patch");
	}

	private static IEnumerable<CodeInstruction> ForcePerformed(IEnumerable<CodeInstruction> instructions)
	{
		foreach (CodeInstruction instruction in instructions)
		{
			if ((instruction.opcode == OpCodes.Call || instruction.opcode == OpCodes.Callvirt) && instruction.operand is MethodInfo { Name: "get_performed" } methodInfo && methodInfo.DeclaringType == typeof(CallbackContext))
			{
				yield return new CodeInstruction(OpCodes.Pop, (object)null)
				{
					labels = instruction.labels,
					blocks = instruction.blocks
				};
				yield return new CodeInstruction(OpCodes.Ldc_I4_1, (object)null);
			}
			else
			{
				yield return instruction;
			}
		}
	}

	private static bool ShouldBuffer(PlayerControllerB p)
	{
		if (replaying || !Plugin.BufferInputs.Value || !((NetworkBehaviour)p).IsOwner)
		{
			return false;
		}
		return GrabPrediction.LockingStateFor(p) != null;
	}

	private static void Record(Kind k)
	{
		presses.Add(new Press
		{
			Kind = k,
			Time = Time.time
		});
		if (presses.Count > 8)
		{
			presses.RemoveAt(0);
		}
		Plugin.Debug($"Buffered {k} during pick-up");
	}

	private static bool UsePrefix(PlayerControllerB __instance, CallbackContext context)
	{
		if (!ShouldBuffer(__instance))
		{
			return true;
		}
		if (((CallbackContext)(ref context)).performed)
		{
			Record(Kind.Use);
		}
		return false;
	}

	private static bool UseReleasePrefix(PlayerControllerB __instance)
	{
		if (!ShouldBuffer(__instance))
		{
			return true;
		}
		Record(Kind.UseRelease);
		return false;
	}

	private static bool DropPrefix(PlayerControllerB __instance, CallbackContext context)
	{
		if (!ShouldBuffer(__instance))
		{
			return true;
		}
		if (((CallbackContext)(ref context)).performed)
		{
			Record(Kind.Drop);
		}
		return false;
	}

	private static bool InteractPrefix(PlayerControllerB __instance, CallbackContext context)
	{
		if (!ShouldBuffer(__instance) || __instance.isPlayerDead)
		{
			return true;
		}
		if (((CallbackContext)(ref context)).performed)
		{
			Record(Kind.Interact);
		}
		return false;
	}

	internal static void Clear(PlayerControllerB p)
	{
		presses.Clear();
	}

	internal static void Replay(PlayerControllerB p)
	{
		//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_0104: Unknown result type (might be due to invalid IL or missing references)
		//IL_0120: Unknown result type (might be due to invalid IL or missing references)
		//IL_0126: Unknown result type (might be due to invalid IL or missing references)
		//IL_0145: Unknown result type (might be due to invalid IL or missing references)
		//IL_014b: Unknown result type (might be due to invalid IL or missing references)
		if (presses.Count == 0)
		{
			return;
		}
		List<Press> list = new List<Press>(presses);
		presses.Clear();
		if ((Object)(object)p == (Object)null || p.isPlayerDead || !Plugin.BufferInputs.Value)
		{
			return;
		}
		float value = Plugin.BufferWindow.Value;
		bool flag = false;
		int num = -1;
		for (int i = 0; i < list.Count; i++)
		{
			if (list[i].Kind == Kind.Interact)
			{
				num = i;
			}
		}
		replaying = true;
		try
		{
			for (int j = 0; j < list.Count; j++)
			{
				Press press = list[j];
				bool flag2 = Time.time - press.Time <= value;
				switch (press.Kind)
				{
				case Kind.Use:
					if (flag2)
					{
						Plugin.Debug("Replaying buffered use");
						VanillaUse(p, default(CallbackContext));
						flag = true;
					}
					break;
				case Kind.UseRelease:
					if (flag)
					{
						Plugin.Debug("Replaying buffered use release");
						VanillaUseRelease(p, default(CallbackContext));
						flag = false;
					}
					break;
				case Kind.Drop:
					if (flag2)
					{
						Plugin.Debug("Replaying buffered drop");
						VanillaDrop(p, default(CallbackContext));
					}
					break;
				case Kind.Interact:
					if (flag2 && j == num)
					{
						Plugin.Debug("Replaying buffered interact");
						VanillaInteract(p, default(CallbackContext));
					}
					break;
				}
			}
		}
		catch (Exception arg)
		{
			Plugin.Log.LogError((object)$"Replaying buffered input failed: {arg}");
		}
		finally
		{
			replaying = false;
		}
	}
}
internal static class NetTweaks
{
	private static int applied = -1;

	internal static void ApplyNagle()
	{
		Type type = AccessTools.TypeByName("Netcode.Transports.Facepunch.FacepunchTransport");
		Plugin.Patch((type == null) ? null : AccessTools.Method(type, "NetworkDeliveryToSendType", (Type[])null, (Type[])null), "disable Nagle", null, Plugin.HM(typeof(NetTweaks), "SendTypePostfix"));
	}

	private static void SendTypePostfix(ref SendType __result)
	{
		if (Plugin.DisableNagle.Value)
		{
			__result = (SendType)((uint)__result | 1u);
		}
	}

	internal static void ApplyLatencyHooks()
	{
		Plugin.Patch(AccessTools.Method(typeof(PlayerControllerB), "ConnectClientToPlayerObject", (Type[])null, (Type[])null), "session start hook", null, Plugin.HM(typeof(NetTweaks), "OnLocalPlayerSpawned"));
		Plugin.SimulatedLatencyMs.SettingChanged += delegate
		{
			ApplyLatency();
		};
	}

	private static void OnLocalPlayerSpawned()
	{
		DropPrediction.Reset();
		FurniturePrediction.Reset();
		GrabPrediction.Reset();
		ApplyLatency();
	}

	internal static void ApplyLatency()
	{
		try
		{
			int value = Plugin.SimulatedLatencyMs.Value;
			if (value != applied && SteamClient.IsValid)
			{
				SteamNetworkingUtils.FakeSendPacketLag = value;
				applied = value;
				if (value > 0)
				{
					Plugin.Log.LogWarning((object)$"Simulating {value} ms of extra latency on everything this game sends (Debug.SimulatedLatencyMs). Set it to 0 for normal play.");
				}
				else
				{
					Plugin.Log.LogInfo((object)"Simulated latency off.");
				}
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Could not set simulated latency: " + ex.Message));
		}
	}
}
public static class FindCache
{
	private static class Slot<T> where T : Object
	{
		internal static T Value;

		internal static float NextSearch;
	}

	private const float MissRetrySeconds = 0.5f;

	public static T Get<T>() where T : Object
	{
		T value = Slot<T>.Value;
		if ((Object)(object)value != (Object)null)
		{
			object obj = value;
			Component val = (Component)((obj is Component) ? obj : null);
			if (val == null || val.gameObject.activeInHierarchy)
			{
				return value;
			}
		}
		float realtimeSinceStartup = Time.realtimeSinceStartup;
		if (realtimeSinceStartup < Slot<T>.NextSearch)
		{
			return default(T);
		}
		value = (Slot<T>.Value = Object.FindObjectOfType<T>());
		Slot<T>.NextSearch = (((Object)(object)value == (Object)null) ? (realtimeSinceStartup + 0.5f) : 0f);
		return value;
	}
}
internal static class Perf
{
	private static readonly MethodInfo cachedGet = AccessTools.Method(typeof(FindCache), "Get", (Type[])null, (Type[])null);

	private static readonly (string type, string method)[] findTargets = new(string, string)[8]
	{
		("GameNetcodeStuff.PlayerControllerB", "Discard_performed"),
		("ClipboardItem", "Update"),
		("BushWolfEnemy", "Update"),
		("VehicleController", "FixedUpdate"),
		("ShowerTrigger", "Update"),
		("SprayPaintItem", "LateUpdate"),
		("RagdollGrabbableObject", "Update"),
		("DisplayPlayerMicVolume", "Update")
	};

	private static readonly MethodInfo debugLog = AccessTools.Method(typeof(Debug), "Log", new Type[1] { typeof(object) }, (Type[])null);

	private static readonly HashSet<string> perFrameNames = new HashSet<string> { "Update", "LateUpdate", "FixedUpdate", "DoAIInterval" };

	private static readonly (string type, string method)[] itemPathTargets = new(string, string)[21]
	{
		("GameNetcodeStuff.PlayerControllerB", "GrabObjectClientRpc"),
		("GameNetcodeStuff.PlayerControllerB", "GrabObjectServerRpc"),
		("GameNetcodeStuff.PlayerControllerB", "ItemSecondaryUse_performed"),
		("GameNetcodeStuff.PlayerControllerB", "DropItemAheadOfPlayer"),
		("GameNetcodeStuff.PlayerControllerB", "DiscardHeldObject"),
		("GameNetcodeStuff.PlayerControllerB", "DropAllHeldItems"),
		("GameNetcodeStuff.PlayerControllerB", "UpdatePlayerPositionRpc"),
		("GameNetcodeStuff.PlayerControllerB", "UpdatePlayerRotationServerRpc"),
		("GameNetcodeStuff.PlayerControllerB", "UpdatePlayerRotationClientRpc"),
		("GameNetcodeStuff.PlayerControllerB", "UpdatePlayerRotationFullServerRpc"),
		("GameNetcodeStuff.PlayerControllerB", "UpdatePlayerRotationFullClientRpc"),
		("GameNetcodeStuff.PlayerControllerB", "UpdatePlayerAnimationServerRpc"),
		("GameNetcodeStuff.PlayerControllerB", "UpdatePlayerAnimationClientRpc"),
		("GrabbableObject", "ActivateItemRpc"),
		("GrabbableObject", "UseItemOnClient"),
		("GrabbableObject", "ItemInteractLeftRightOnClient"),
		("GrabbableObject", "EnableItemMeshes"),
		("PlaceableObjectsSurface", "PlaceObject"),
		("PlaceableObjectsSurface", "ConfirmPlaceOnFurnitureClientRpc"),
		("DepositItemsDesk", "PlaceItemOnCounter"),
		("LungProp", "EquipItem")
	};

	private static readonly HashSet<string> skip = new HashSet<string> { "GrabbableObject.Start" };

	internal static void ApplyFindCache()
	{
		//IL_0023: 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_0034: Expected O, but got Unknown
		if (Plugin.CacheFindObjectOfType.Value)
		{
			HarmonyMethod transpiler = new HarmonyMethod(AccessTools.Method(typeof(Perf), "FindTranspiler", (Type[])null, (Type[])null))
			{
				priority = 200
			};
			(string, string)[] array = findTargets;
			for (int i = 0; i < array.Length; i++)
			{
				(string, string) tuple = array[i];
				string item = tuple.Item1;
				string item2 = tuple.Item2;
				Type type = AccessTools.TypeByName(item);
				Plugin.Patch((type == null) ? null : AccessTools.DeclaredMethod(type, item2, (Type[])null, (Type[])null), "cache FindObjectOfType in " + item + "." + item2, null, null, transpiler);
			}
		}
	}

	private static IEnumerable<CodeInstruction> FindTranspiler(IEnumerable<CodeInstruction> instructions)
	{
		foreach (CodeInstruction instruction in instructions)
		{
			if (instruction.opcode == OpCodes.Call && instruction.operand is MethodInfo { IsGenericMethod: not false, Name: "FindObjectOfType" } methodInfo && methodInfo.DeclaringType == typeof(Object) && methodInfo.GetParameters().Length == 0)
			{
				instruction.operand = cachedGet.MakeGenericMethod(methodInfo.GetGenericArguments());
			}
			yield return instruction;
		}
	}

	internal static void ApplyLogStrip()
	{
		//IL_0023: 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_0030: Expected O, but got Unknown
		if (!Plugin.StripLogSpam.Value)
		{
			return;
		}
		HarmonyMethod transpiler = new HarmonyMethod(AccessTools.Method(typeof(Perf), "LogTranspiler", (Type[])null, (Type[])null))
		{
			priority = 0
		};
		Assembly assembly = typeof(PlayerControllerB).Assembly;
		List<MethodBase> list = new List<MethodBase>();
		Type[] typesFromAssembly = AccessTools.GetTypesFromAssembly(assembly);
		foreach (Type type in typesFromAssembly)
		{
			if (type.IsGenericTypeDefinition)
			{
				continue;
			}
			MethodInfo[] methods;
			try
			{
				methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			}
			catch
			{
				continue;
			}
			MethodInfo[] array = methods;
			foreach (MethodInfo methodInfo in array)
			{
				if (perFrameNames.Contains(methodInfo.Name) && !methodInfo.IsAbstract && methodInfo.GetParameters().Length == 0 && CallsDebugLog(methodInfo))
				{
					list.Add(methodInfo);
				}
			}
		}
		(string, string)[] array2 = itemPathTargets;
		for (int i = 0; i < array2.Length; i++)
		{
			(string, string) tuple = array2[i];
			string item = tuple.Item1;
			string item2 = tuple.Item2;
			Type type2 = AccessTools.TypeByName(item);
			MethodInfo methodInfo2 = ((type2 == null) ? null : AccessTools.DeclaredMethod(type2, item2, (Type[])null, (Type[])null));
			if (methodInfo2 != null && CallsDebugLog(methodInfo2) && !list.Contains(methodInfo2))
			{
				list.Add(methodInfo2);
			}
		}
		Type type3 = typeof(PlayerControllerB).GetNestedTypes(AccessTools.all).FirstOrDefault((Type n) => n.Name.StartsWith("<GrabObject>d__"));
		MethodInfo methodInfo3 = ((type3 == null) ? null : AccessTools.Method(type3, "MoveNext", (Type[])null, (Type[])null));
		if (methodInfo3 != null && CallsDebugLog(methodInfo3))
		{
			list.Add(methodInfo3);
		}
		int num = 0;
		foreach (MethodBase item3 in list)
		{
			if (!skip.Contains(item3.DeclaringType?.Name + "." + item3.Name) && Plugin.Patch(item3, "strip Debug.Log", null, null, transpiler))
			{
				num++;
			}
		}
		Plugin.Log.LogInfo((object)$"Stripped Debug.Log spam from {num} methods.");
	}

	private static bool CallsDebugLog(MethodBase m)
	{
		byte[] array;
		try
		{
			array = m.GetMethodBody()?.GetILAsByteArray();
		}
		catch
		{
			return false;
		}
		if (array == null)
		{
			return false;
		}
		Module module = m.Module;
		for (int i = 0; i + 4 < array.Length; i++)
		{
			if (array[i] != 40)
			{
				continue;
			}
			int num = BitConverter.ToInt32(array, i + 1);
			int num2 = num >> 24;
			if (num2 != 10 && num2 != 6 && num2 != 43)
			{
				continue;
			}
			try
			{
				Type? declaringType = m.DeclaringType;
				if (module.ResolveMethod(num, ((object)declaringType != null && declaringType.IsGenericType) ? m.DeclaringType.GetGenericArguments() : null, null) == debugLog)
				{
					return true;
				}
			}
			catch
			{
			}
		}
		return false;
	}

	private static IEnumerable<CodeInstruction> LogTranspiler(IEnumerable<CodeInstruction> instructions)
	{
		foreach (CodeInstruction instruction in instructions)
		{
			if (instruction.opcode == OpCodes.Call && instruction.operand is MethodInfo methodInfo && methodInfo == debugLog)
			{
				instruction.opcode = OpCodes.Pop;
				instruction.operand = null;
			}
			yield return instruction;
		}
	}

	internal static void ApplyCheapLogs()
	{
		if (Plugin.CheapInfoLogs.Value)
		{
			Application.SetStackTraceLogType((LogType)3, (StackTraceLogType)0);
			Plugin.Log.LogInfo((object)"Info-level log messages no longer capture stack traces.");
		}
	}
}
[BepInPlugin("lcmods.ItemLagFix", "ItemLagFix", "1.0.0")]
public class Plugin : BaseUnityPlugin
{
	public const string GUID = "lcmods.ItemLagFix";

	public const string NAME = "ItemLagFix";

	public const string VERSION = "1.0.0";

	internal static ManualLogSource Log;

	internal static Harmony Harmony;

	internal static ConfigEntry<bool> PredictDrops;

	internal static ConfigEntry<bool> PredictGrabs;

	internal static ConfigEntry<bool> PredictFurniturePlacement;

	internal static ConfigEntry<bool> PredictKeyDespawn;

	internal static ConfigEntry<bool> BufferInputs;

	internal static ConfigEntry<float> BufferWindow;

	internal static ConfigEntry<string> GrabBlocklist;

	internal static ConfigEntry<bool> DisableNagle;

	internal static ConfigEntry<bool> CacheFindObjectOfType;

	internal static ConfigEntry<bool> StripLogSpam;

	internal static ConfigEntry<bool> CheapInfoLogs;

	internal static ConfigEntry<int> SimulatedLatencyMs;

	internal static ConfigEntry<bool> Verbose;

	internal static int Patched;

	internal static int Failed;

	private void Awake()
	{
		//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e3: Expected O, but got Unknown
		//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01bc: Expected O, but got Unknown
		//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f0: Expected O, but got Unknown
		Log = ((BaseUnityPlugin)this).Logger;
		PredictDrops = ((BaseUnityPlugin)this).Config.Bind<bool>("Prediction", "PredictDrops", true, "Finish dropping/throwing/placing an item instantly instead of waiting for the host to confirm. Lets you pick something up or drop the next item straight away.");
		PredictGrabs = ((BaseUnityPlugin)this).Config.Bind<bool>("Prediction", "PredictGrabs", true, "Put a picked-up item into your inventory instantly instead of waiting for the host. If the host refuses the grab (someone else got it first) it is undone automatically.");
		PredictFurniturePlacement = ((BaseUnityPlugin)this).Config.Bind<bool>("Prediction", "PredictFurniturePlacement", true, "Placing items on ship furniture (cupboard, shelves, counters) skips the extra round trip to the host.");
		PredictKeyDespawn = ((BaseUnityPlugin)this).Config.Bind<bool>("Prediction", "PredictKeyDespawn", true, "Using up a held item that gets destroyed (a key on a door, etc.) frees your hands instantly.");
		BufferInputs = ((BaseUnityPlugin)this).Config.Bind<bool>("Prediction", "BufferInputsDuringGrab", true, "Remember a use/drop/pick-up press made while a pick-up is still finishing and do it as soon as it finishes, instead of silently dropping the press like the base game does.");
		BufferWindow = ((BaseUnityPlugin)this).Config.Bind<float>("Prediction", "BufferWindowSeconds", 0.5f, new ConfigDescription("How old a remembered press may be and still be replayed.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.05f, 2f), Array.Empty<object>()));
		GrabBlocklist = ((BaseUnityPlugin)this).Config.Bind<string>("Prediction", "GrabPredictionBlocklist", "", "Comma-separated item names (as shown on the scan/tooltip, case-insensitive) that should never use grab prediction. Items whose pick-up code needs ownership are detected and skipped automatically; use this for anything that still misbehaves.");
		DisableNagle = ((BaseUnityPlugin)this).Config.Bind<bool>("Network", "DisableNagle", true, "Send every network message immediately instead of letting Steam hold it back for up to several milliseconds to bundle it with others. Helps hosts and clients; costs a few extra packets.");
		CacheFindObjectOfType = ((BaseUnityPlugin)this).Config.Bind<bool>("Performance", "CacheFindObjectOfType", true, "Replace whole-scene object searches that the game runs every frame (or on every drop) with a cached lookup. Searches for objects that do not exist are retried at most twice per second instead of every frame.");
		StripLogSpam = ((BaseUnityPlugin)this).Config.Bind<bool>("Performance", "StripLogSpam", true, "Remove Debug.Log calls from per-frame game code and from the item grab/drop/use code paths. Warnings and errors are kept.");
		CheapInfoLogs = ((BaseUnityPlugin)this).Config.Bind<bool>("Performance", "CheapInfoLogs", true, "Do not capture a stack trace for ordinary (info) log messages. Unity normally does this for every single log line, which is the expensive part of logging. Warnings and errors keep their stack traces.");
		SimulatedLatencyMs = ((BaseUnityPlugin)this).Config.Bind<int>("Debug", "SimulatedLatencyMs", 0, new ConfigDescription("Testing only: delay every packet you send by this many milliseconds (adds this much to your ping). 0 = off.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 1000), Array.Empty<object>()));
		Verbose = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "VerboseLogging", false, "Log every prediction, confirmation and rollback.");
		Harmony = new Harmony("lcmods.ItemLagFix");
		Apply("drop/place/despawn prediction", DropPrediction.Apply);
		Apply("furniture placement prediction", FurniturePrediction.Apply);
		Apply("grab prediction", GrabPrediction.Apply);
		Apply("input buffering", InputBuffer.Apply);
		Apply("Nagle", NetTweaks.ApplyNagle);
		Apply("simulated latency", NetTweaks.ApplyLatencyHooks);
		Apply("FindObjectOfType cache", Perf.ApplyFindCache);
		Apply("log spam stripping", Perf.ApplyLogStrip);
		Apply("cheap info logs", Perf.ApplyCheapLogs);
		Log.LogInfo((object)string.Format("{0} {1} loaded ({2} patches applied, {3} failed).", "ItemLagFix", "1.0.0", Patched, Failed));
	}

	private static void Apply(string what, Action a)
	{
		try
		{
			a();
		}
		catch (Exception arg)
		{
			Failed++;
			Log.LogError((object)$"Could not enable {what}: {arg}");
		}
	}

	internal static void Debug(string msg)
	{
		if (Verbose != null && Verbose.Value)
		{
			Log.LogInfo((object)msg);
		}
	}

	internal static bool Patch(MethodBase target, string what, HarmonyMethod prefix = null, HarmonyMethod postfix = null, HarmonyMethod transpiler = null)
	{
		if (target == null)
		{
			Failed++;
			Log.LogWarning((object)("Target for '" + what + "' not found; that part is disabled."));
			return false;
		}
		try
		{
			Harmony.Patch(target, prefix, postfix, transpiler, (HarmonyMethod)null, (HarmonyMethod)null);
			Patched++;
			return true;
		}
		catch (Exception ex)
		{
			Failed++;
			Log.LogError((object)("Patching " + target.DeclaringType?.Name + "." + target.Name + " (" + what + ") failed: " + ex.Message));
			return false;
		}
	}

	internal static HarmonyMethod HM(Type t, string name, int priority = -1)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Expected O, but got Unknown
		HarmonyMethod val = new HarmonyMethod(AccessTools.Method(t, name, (Type[])null, (Type[])null));
		if (priority >= 0)
		{
			val.priority = priority;
		}
		return val;
	}
}