Decompiled source of Citadel Valheim v1.0.28

TombstoneTakeAllFix.dll

Decompiled 3 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using HarmonyLib;
using UnityEngine;

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

[BepInPlugin("com.geniz.tombstonefix", "TombstoneTakeAllFix", "1.4.1")]
public class Plugin : BaseUnityPlugin
{
	[HarmonyPatch(typeof(Player), "Load")]
	public static class Player_Load_Guard
	{
		[HarmonyFinalizer]
		public static Exception Finalizer(Exception __exception)
		{
			if (__exception != null)
			{
				Debug.LogWarning((object)("[TombstoneFix] Suppressed exception during Player.Load: " + __exception.Message));
				return null;
			}
			return null;
		}
	}

	private struct StoryCinematic
	{
		public string Video;

		public string ReqGlobalKey;

		public string Description;

		public StoryCinematic(string video, string reqKey, string desc)
		{
			Video = video;
			ReqGlobalKey = reqKey;
			Description = desc;
		}
	}

	private const string CINEMATIC_CUSTOM_DATA_KEY = "Citadel_SeenCinematics";

	private const int MAX_LOCAL_FISH = 6;

	private const float FISH_LINGER_DURATION = 150f;

	private static Plugin instance;

	private static bool _chebsAwakeDone = false;

	private static Type _phylType;

	private static MethodInfo _mHasFuel;

	private static MethodInfo _mRemoveFuel;

	private static MethodInfo _mReceiveLoc;

	private static FieldInfo _fRpc;

	private static MethodInfo _mSendPkg;

	private static int _phylHash = 0;

	private static int _creatorHash = 0;

	private static Dictionary<long, ZDOID> _phylCache = new Dictionary<long, ZDOID>();

	private static float _lastPhylScan = 0f;

	private static FieldInfo _fObjectsByID = null;

	private static bool _latePluginsHooked = false;

	private static HashSet<int> _boostedSpawnSystems = new HashSet<int>();

	private static readonly StoryCinematic[] _storyCinematics = new StoryCinematic[8]
	{
		new StoryCinematic("intro", null, "First Night in Valheim"),
		new StoryCinematic("blackforest", "defeated_eikthyr", "Defeated Eikthyr (Black Forest)"),
		new StoryCinematic("swamp", "defeated_gdking", "Defeated The Elder (Swamps)"),
		new StoryCinematic("mountains", "defeated_bonemass", "Defeated Bonemass (Mountains)"),
		new StoryCinematic("plains", "defeated_dragon", "Defeated Moder (Plains)"),
		new StoryCinematic("mistlands", "defeated_goblinking", "Defeated Yagluth (Mistlands)"),
		new StoryCinematic("ashlands", "defeated_queen", "Defeated The Queen (Ashlands)"),
		new StoryCinematic("deepnorth", "defeated_fader", "Defeated Fader (Deep North)")
	};

	private static FieldInfo _fDreamCinematic = AccessTools.Field(typeof(CinematicsManager), "m_dreamCinematic");

	private static bool _isStoryCinematicPlaying = false;

	private static bool _pendingSleepStop = false;

	private static bool _serverWasSleeping = false;

	private static readonly HashSet<long> _serverWatchingPlayers = new HashSet<long>();

	private static float _serverCinematicSleepStartTime = 0f;

	private static readonly FieldInfo _fGameSleeping = AccessTools.Field(typeof(Game), "m_sleeping");

	private static readonly MethodInfo _mGameSleepStop = AccessTools.Method(typeof(Game), "SleepStop", new Type[1] { typeof(long) }, (Type[])null);

	private static float _lastFishSpawnCheckTime = 0f;

	private static float _lastFishingGearActiveTime = 0f;

	private static readonly Dictionary<ZDOID, float> _spawnedFishTracker = new Dictionary<ZDOID, float>();

	private static readonly FieldInfo _fProjectileOwner = AccessTools.Field(typeof(Projectile), "m_owner");

	private static readonly MethodInfo _mFindFloatOwner = AccessTools.Method(typeof(FishingFloat), "FindFloat", new Type[1] { typeof(Character) }, (Type[])null);

	private void Awake()
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: Expected O, but got Unknown
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Expected O, but got Unknown
		//IL_011e: Unknown result type (might be due to invalid IL or missing references)
		//IL_012c: Expected O, but got Unknown
		//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d1: Expected O, but got Unknown
		//IL_0298: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a6: Expected O, but got Unknown
		//IL_033a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0348: Expected O, but got Unknown
		instance = this;
		Harmony val = new Harmony("com.geniz.tombstonefix");
		val.PatchAll(typeof(Plugin));
		try
		{
			Type type = AccessTools.TypeByName("AzuEPI.Game.Favoriting.FavoritingMode");
			if (type != null)
			{
				MethodInfo methodInfo = AccessTools.Method(type, "IsExternalFavoritingModLoaded", (Type[])null, (Type[])null);
				if (methodInfo != null)
				{
					MethodInfo methodInfo2 = AccessTools.Method(typeof(Plugin), "AzuEPI_IsExternalFavoritingModLoaded_Prefix", (Type[])null, (Type[])null);
					val.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					((BaseUnityPlugin)this).Logger.LogInfo((object)"Successfully hooked AzuEPI IsExternalFavoritingModLoaded to delegate favoriting to OttoStash.");
				}
			}
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not hook AzuEPI FavoritingMode: " + ex.Message));
		}
		try
		{
			Type type2 = AccessTools.TypeByName("ChebsNecromancy.BasePlugin");
			if (type2 != null)
			{
				MethodInfo methodInfo3 = AccessTools.Method(type2, "<Awake>b__43_0", (Type[])null, (Type[])null);
				if (methodInfo3 != null)
				{
					MethodInfo methodInfo2 = AccessTools.Method(typeof(Plugin), "ChebsAwakeB430_Prefix", (Type[])null, (Type[])null);
					val.Patch((MethodBase)methodInfo3, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					((BaseUnityPlugin)this).Logger.LogInfo((object)"Successfully hooked ChebsNecromancy <Awake>b__43_0 to prevent duplicate reload crash.");
				}
			}
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not hook ChebsNecromancy: " + ex.Message));
		}
		try
		{
			Type type3 = AccessTools.TypeByName("AzuEPI.Game.Panels.Stats.StatsPanelController");
			if (type3 != null)
			{
				MethodInfo methodInfo4 = AccessTools.Method(type3, "OnPlayerListChanged", (Type[])null, (Type[])null);
				if (methodInfo4 != null)
				{
					MethodInfo methodInfo2 = AccessTools.Method(typeof(Plugin), "StatsPanelController_OnPlayerListChanged_Prefix", (Type[])null, (Type[])null);
					val.Patch((MethodBase)methodInfo4, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					((BaseUnityPlugin)this).Logger.LogInfo((object)"Successfully hooked AzuEPI StatsPanelController.OnPlayerListChanged (prevented UI GC leak).");
				}
			}
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not hook AzuEPI StatsPanelController: " + ex.Message));
		}
		try
		{
			Type type4 = AccessTools.TypeByName("ChebsNecromancy.Structures.Phylactery");
			if (type4 != null)
			{
				MethodInfo methodInfo5 = AccessTools.Method(type4, "PhylacteryCheckRPCServerReceive", new Type[2]
				{
					typeof(long),
					typeof(ZPackage)
				}, (Type[])null);
				if (methodInfo5 != null)
				{
					InitPhylacteryFast(type4);
					MethodInfo methodInfo2 = AccessTools.Method(typeof(Plugin), "PhylacteryCheckRPCServerReceive_Prefix", (Type[])null, (Type[])null);
					val.Patch((MethodBase)methodInfo5, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					((BaseUnityPlugin)this).Logger.LogInfo((object)"Successfully hooked ChebsNecromancy PhylacteryCheckRPCServerReceive (O(1) fast lookup).");
				}
			}
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not hook ChebsNecromancy Phylactery: " + ex.Message));
		}
		try
		{
			Type type5 = AccessTools.TypeByName("MyLittleUI.Crafting.CraftNew+Player_Load_FillRequiredItems");
			if (type5 != null)
			{
				MethodInfo methodInfo = AccessTools.Method(type5, "Postfix", (Type[])null, (Type[])null);
				if (methodInfo != null)
				{
					MethodInfo methodInfo2 = AccessTools.Method(typeof(Plugin), "MyLittleUI_Player_Load_FillRequiredItems_Prefix", (Type[])null, (Type[])null);
					val.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					((BaseUnityPlugin)this).Logger.LogInfo((object)"Successfully hooked MyLittleUI Player_Load_FillRequiredItems (prevented character load NRE).");
				}
			}
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not hook MyLittleUI: " + ex.Message));
		}
		try
		{
			FieldInfo fieldInfo = AccessTools.Field(typeof(ZRpc), "m_timeout");
			if (fieldInfo != null)
			{
				fieldInfo.SetValue(null, 180f);
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Increased ZRpc.m_timeout to 180s.");
			}
		}
		catch
		{
		}
		CleanPieceManagerPatches();
		((BaseUnityPlugin)this).Logger.LogInfo((object)"TombstoneTakeAllFix v1.2.7 (with ZDO network uncap, 180s ZRpc timeout, fast phylactery, MyLittleUI/BuildUi spawn guard, piece table null cleaner & resilient spawn loop guard) loaded successfully.");
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(ZNet), "Awake")]
	public static void ZNet_Awake_Timeout_Postfix()
	{
		try
		{
			FieldInfo fieldInfo = AccessTools.Field(typeof(ZRpc), "m_timeout");
			if (fieldInfo != null)
			{
				fieldInfo.SetValue(null, 180f);
				Debug.Log((object)"[TombstoneTakeAllFix] Enforced ZRpc.m_timeout = 180s after ZNet.Awake.");
			}
		}
		catch
		{
		}
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(ZSteamSocket), "GetSendQueueSize")]
	public static void ZSteamSocket_GetSendQueueSize_Postfix(ref int __result)
	{
		if (__result < 262144)
		{
			__result = 0;
		}
	}

	private static void InitPhylacteryFast(Type pt)
	{
		_phylType = pt;
		_mHasFuel = AccessTools.Method(_phylType, "PhylacteryZDOHasFuel", new Type[1] { typeof(ZDO) }, (Type[])null);
		_mRemoveFuel = AccessTools.Method(_phylType, "RemoveFuelFromPhylactery", new Type[1] { typeof(ZDO) }, (Type[])null);
		_mReceiveLoc = AccessTools.Method(_phylType, "ReceivePhylacteryLocation", new Type[2]
		{
			typeof(string),
			typeof(long)
		}, (Type[])null);
		_fRpc = AccessTools.Field(_phylType, "PhylacteryCheckRPC");
		if (_fRpc != null)
		{
			_mSendPkg = AccessTools.Method(_fRpc.FieldType, "SendPackage", new Type[2]
			{
				typeof(long),
				typeof(ZPackage)
			}, (Type[])null);
		}
		FieldInfo fieldInfo = AccessTools.Field(_phylType, "PhylacteryHash");
		_phylHash = ((fieldInfo != null) ? ((int)fieldInfo.GetValue(null)) : StringExtensionMethods.GetStableHashCode("ChebGonaz_Phylactery"));
		_creatorHash = StringExtensionMethods.GetStableHashCode("creator");
	}

	private static Dictionary<ZDOID, ZDO> GetZDOObjects()
	{
		if (ZDOMan.instance == null)
		{
			return null;
		}
		if (_fObjectsByID == null)
		{
			_fObjectsByID = AccessTools.Field(typeof(ZDOMan), "m_objectsByID");
		}
		return (_fObjectsByID != null) ? (_fObjectsByID.GetValue(ZDOMan.instance) as Dictionary<ZDOID, ZDO>) : null;
	}

	private static ZDO FindPhylacteryFast(long creatorId)
	{
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_0151: Unknown result type (might be due to invalid IL or missing references)
		//IL_0109: Unknown result type (might be due to invalid IL or missing references)
		Dictionary<ZDOID, ZDO> zDOObjects = GetZDOObjects();
		if (zDOObjects == null)
		{
			return null;
		}
		if (_phylCache.TryGetValue(creatorId, out var value))
		{
			ZDO zDO = ZDOMan.instance.GetZDO(value);
			if (zDO != null && zDO.IsValid() && zDO.GetPrefab() == _phylHash)
			{
				return zDO;
			}
			_phylCache.Remove(creatorId);
		}
		float time = Time.time;
		if (time - _lastPhylScan > 30f)
		{
			_lastPhylScan = time;
			_phylCache.Clear();
			foreach (KeyValuePair<ZDOID, ZDO> item in zDOObjects)
			{
				ZDO zDO = item.Value;
				if (zDO != null && zDO.GetPrefab() == _phylHash)
				{
					long num = zDO.GetLong(_creatorHash, 0L);
					if (num != 0)
					{
						_phylCache[num] = zDO.m_uid;
					}
				}
			}
			if (_phylCache.TryGetValue(creatorId, out value))
			{
				return ZDOMan.instance.GetZDO(value);
			}
		}
		return null;
	}

	public static bool PhylacteryCheckRPCServerReceive_Prefix(long sender, ZPackage package, ref IEnumerator __result)
	{
		__result = FastPhylacteryCheck(sender, package);
		return false;
	}

	private static IEnumerator FastPhylacteryCheck(long sender, ZPackage pkg)
	{
		while ((Object)(object)ZNet.instance == (Object)null)
		{
			yield return null;
		}
		if (pkg == null)
		{
			yield break;
		}
		byte[] arr = pkg.GetArray();
		if (arr == null || arr.Length == 0)
		{
			yield break;
		}
		string str = Encoding.UTF8.GetString(arr);
		if (str.StartsWith("CG_1"))
		{
			string[] array = str.Split(new char[1] { ' ' });
			long result = 0L;
			if (array.Length >= 2 && long.TryParse(array[1], out result))
			{
				ZDO val = FindPhylacteryFast(result);
				byte[] array2 = ((val == null || !(_mHasFuel != null)) ? Encoding.UTF8.GetBytes("CG_2") : ((!(bool)_mHasFuel.Invoke(null, new object[1] { val })) ? Encoding.UTF8.GetBytes("CG_2") : Encoding.UTF8.GetBytes("CG_2" + ((object)val.GetPosition()/*cast due to .constrained prefix*/).ToString())));
				if (_fRpc != null && _mSendPkg != null)
				{
					object value = _fRpc.GetValue(null);
					_mSendPkg.Invoke(value, new object[2]
					{
						sender,
						(object)new ZPackage(array2)
					});
				}
			}
		}
		else if (str.StartsWith("CG_3"))
		{
			string[] array = str.Split(new char[1] { ' ' });
			long result = 0L;
			if (array.Length >= 2 && long.TryParse(array[1], out result))
			{
				ZDO val = FindPhylacteryFast(result);
				if (val != null && _mRemoveFuel != null)
				{
					_mRemoveFuel.Invoke(null, new object[1] { val });
				}
			}
		}
		else if (str.StartsWith("CG_2") && _mReceiveLoc != null)
		{
			_mReceiveLoc.Invoke(null, new object[2] { str, sender });
		}
	}

	public static bool StatsPanelController_OnPlayerListChanged_Prefix()
	{
		if ((Object)(object)InventoryGui.instance == (Object)null || !InventoryGui.IsVisible())
		{
			return false;
		}
		return true;
	}

	public static bool ChebsAwakeB430_Prefix()
	{
		if (_chebsAwakeDone)
		{
			return false;
		}
		_chebsAwakeDone = true;
		return true;
	}

	public static bool AzuEPI_IsExternalFavoritingModLoaded_Prefix(ref bool __result)
	{
		if (Chainloader.PluginInfos != null && Chainloader.PluginInfos.ContainsKey("potto007.OttoStash"))
		{
			__result = true;
			return false;
		}
		return true;
	}

	[HarmonyPatch(typeof(FejdStartup), "Awake")]
	[HarmonyPrefix]
	public static void FejdStartup_Awake_Prefix()
	{
		CleanPieceManagerPatches();
		HookLatePlugins();
	}

	public static void HookLatePlugins()
	{
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: Expected O, but got Unknown
		//IL_009b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a1: Expected O, but got Unknown
		//IL_0119: Unknown result type (might be due to invalid IL or missing references)
		//IL_011f: Expected O, but got Unknown
		//IL_007b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0089: Expected O, but got Unknown
		//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0107: Expected O, but got Unknown
		//IL_0177: Unknown result type (might be due to invalid IL or missing references)
		//IL_0185: Expected O, but got Unknown
		if (_latePluginsHooked)
		{
			return;
		}
		_latePluginsHooked = true;
		try
		{
			Harmony val = new Harmony("com.geniz.tombstonefix");
			Type type = AccessTools.TypeByName("MyLittleUI.Crafting.CraftNew+Player_Load_FillRequiredItems");
			if (type != null)
			{
				MethodInfo methodInfo = AccessTools.Method(type, "Postfix", (Type[])null, (Type[])null);
				if (methodInfo != null)
				{
					MethodInfo methodInfo2 = AccessTools.Method(typeof(Plugin), "NoOpPrefix", (Type[])null, (Type[])null);
					val.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
		}
		catch
		{
		}
		try
		{
			Harmony val = new Harmony("com.geniz.tombstonefix");
			Type type2 = AccessTools.TypeByName("PieceManager.RegisterClientRPCPatch");
			if (type2 != null)
			{
				MethodInfo methodInfo = AccessTools.Method(type2, "RPC_InitialAdminSync", (Type[])null, (Type[])null);
				if (methodInfo != null)
				{
					MethodInfo methodInfo2 = AccessTools.Method(typeof(Plugin), "NoOpPrefix", (Type[])null, (Type[])null);
					val.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
		}
		catch
		{
		}
		try
		{
			Harmony val = new Harmony("com.geniz.tombstonefix");
			Type type3 = AccessTools.TypeByName("FishTrap.Solution.FishTrap");
			if (type3 != null)
			{
				MethodInfo methodInfo = AccessTools.Method(type3, "Update", (Type[])null, (Type[])null);
				if (methodInfo != null)
				{
					MethodInfo methodInfo2 = AccessTools.Method(typeof(Plugin), "NoOpPrefix", (Type[])null, (Type[])null);
					val.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
		}
		catch
		{
		}
	}

	public static bool NoOpPrefix()
	{
		return false;
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(BuildUi), "OnFavoritePieceAdded")]
	public static bool BuildUi_OnFavoritePieceAdded_Prefix(BuildUi __instance, string pieceName)
	{
		if ((Object)(object)__instance == (Object)null)
		{
			return false;
		}
		try
		{
			if (Traverse.Create((object)__instance).Field("m_pieceButtons").GetValue() is IList list)
			{
				for (int i = 0; i < list.Count; i++)
				{
					object obj = list[i];
					if (obj != null)
					{
						Piece value = Traverse.Create(obj).Property("Piece", (object[])null).GetValue<Piece>();
						if (!((Object)(object)value == (Object)null) && !((Object)(object)((Component)value).gameObject == (Object)null) && ((Object)((Component)value).gameObject).name == pieceName)
						{
							Traverse.Create(obj).Method("RefreshFavorite", new object[0]).GetValue();
						}
					}
				}
			}
		}
		catch
		{
		}
		return false;
	}

	[HarmonyPatch(typeof(BuildUi), "OnFavoritePieceRemoved")]
	[HarmonyPrefix]
	public static bool BuildUi_OnFavoritePieceRemoved_Prefix(BuildUi __instance, string pieceName)
	{
		if ((Object)(object)__instance == (Object)null)
		{
			return false;
		}
		try
		{
			if (Traverse.Create((object)__instance).Field("m_pieceButtons").GetValue() is IList list)
			{
				for (int i = 0; i < list.Count; i++)
				{
					object obj = list[i];
					if (obj != null)
					{
						Piece value = Traverse.Create(obj).Property("Piece", (object[])null).GetValue<Piece>();
						if (!((Object)(object)value == (Object)null) && !((Object)(object)((Component)value).gameObject == (Object)null) && ((Object)((Component)value).gameObject).name == pieceName)
						{
							Traverse.Create(obj).Method("RefreshFavorite", new object[0]).GetValue();
						}
					}
				}
			}
		}
		catch
		{
		}
		return false;
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(Player), "UpdateKnownRecipesList")]
	public static void Player_UpdateKnownRecipesList_Prefix(Player __instance)
	{
		if ((Object)(object)__instance == (Object)null)
		{
			return;
		}
		try
		{
			Inventory inventory = ((Humanoid)__instance).GetInventory();
			if (inventory == null)
			{
				return;
			}
			List<ItemData> allItems = inventory.GetAllItems();
			if (allItems == null)
			{
				return;
			}
			for (int i = 0; i < allItems.Count; i++)
			{
				ItemData val = allItems[i];
				if (val == null || val.m_shared == null || !((Object)(object)val.m_shared.m_buildPieces != (Object)null))
				{
					continue;
				}
				PieceTable buildPieces = val.m_shared.m_buildPieces;
				if (buildPieces.m_pieces != null)
				{
					buildPieces.m_pieces.RemoveAll((GameObject p) => (Object)(object)p == (Object)null);
				}
			}
		}
		catch
		{
		}
	}

	[HarmonyFinalizer]
	[HarmonyPatch(typeof(Player), "UpdateKnownRecipesList")]
	public static Exception Player_UpdateKnownRecipesList_Finalizer(Exception __exception)
	{
		if (__exception != null)
		{
			Debug.LogWarning((object)("[TombstoneTakeAllFix] Caught and suppressed NRE in Player.UpdateKnownRecipesList: " + __exception.Message));
			return null;
		}
		return null;
	}

	[HarmonyPatch(typeof(Inventory), "GetAllPieceTables")]
	[HarmonyPostfix]
	public static void Inventory_GetAllPieceTables_Postfix(List<PieceTable> tables)
	{
		if (tables == null)
		{
			return;
		}
		for (int i = 0; i < tables.Count; i++)
		{
			PieceTable val = tables[i];
			if ((Object)(object)val != (Object)null && val.m_pieces != null)
			{
				val.m_pieces.RemoveAll((GameObject p) => (Object)(object)p == (Object)null);
			}
		}
	}

	[HarmonyPatch(typeof(PieceTable), "UpdateAvailable")]
	[HarmonyPrefix]
	public static void PieceTable_UpdateAvailable_Prefix(PieceTable __instance)
	{
		if ((Object)(object)__instance != (Object)null && __instance.m_pieces != null)
		{
			__instance.m_pieces.RemoveAll((GameObject p) => (Object)(object)p == (Object)null);
		}
	}

	[HarmonyFinalizer]
	[HarmonyPatch(typeof(PieceTable), "UpdateAvailable")]
	public static Exception PieceTable_UpdateAvailable_Finalizer(Exception __exception)
	{
		if (__exception != null)
		{
			return null;
		}
		return null;
	}

	[HarmonyFinalizer]
	[HarmonyPatch(typeof(Player), "OnSpawned")]
	public static Exception Player_OnSpawned_Finalizer(Exception __exception)
	{
		if (__exception != null)
		{
			Debug.LogWarning((object)("[TombstoneTakeAllFix] Caught and suppressed exception in Player.OnSpawned: " + __exception.Message));
			return null;
		}
		return null;
	}

	[HarmonyPatch(typeof(Game), "SpawnPlayer")]
	[HarmonyFinalizer]
	public static Exception Game_SpawnPlayer_Finalizer(Game __instance, Exception __exception)
	{
		if (__exception != null)
		{
			Debug.LogWarning((object)("[TombstoneTakeAllFix] Caught exception in Game.SpawnPlayer, forcing m_respawnWait = false: " + __exception.Message));
			if ((Object)(object)__instance != (Object)null)
			{
				Traverse.Create((object)__instance).Field("m_respawnWait").SetValue((object)false);
			}
			return null;
		}
		return null;
	}

	public static bool MyLittleUI_Player_Load_FillRequiredItems_Prefix()
	{
		return false;
	}

	public static void CleanPieceManagerPatches()
	{
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Expected O, but got Unknown
		try
		{
			MethodInfo methodInfo = AccessTools.Method(typeof(PieceTable), "UpdateAvailable", (Type[])null, (Type[])null);
			if (methodInfo != null)
			{
				Harmony val = new Harmony("com.geniz.tombstonefix");
				val.Unpatch((MethodBase)methodInfo, (HarmonyPatchType)0, "org.bepinex.helpers.PieceManager");
				val.Unpatch((MethodBase)methodInfo, (HarmonyPatchType)0, "RustyMods.FishTrap");
			}
		}
		catch
		{
		}
	}

	[HarmonyPatch(typeof(SpawnSystem), "UpdateSpawning")]
	[HarmonyPrefix]
	public static void SpawnSystem_UpdateSpawning_Prefix(SpawnSystem __instance)
	{
		if ((Object)(object)__instance == (Object)null || __instance.m_spawnLists == null)
		{
			return;
		}
		int instanceID = ((Object)__instance).GetInstanceID();
		if (_boostedSpawnSystems.Contains(instanceID))
		{
			return;
		}
		_boostedSpawnSystems.Add(instanceID);
		try
		{
			for (int i = 0; i < __instance.m_spawnLists.Count; i++)
			{
				SpawnSystemList val = __instance.m_spawnLists[i];
				if ((Object)(object)val == (Object)null || val.m_spawners == null)
				{
					continue;
				}
				for (int j = 0; j < val.m_spawners.Count; j++)
				{
					SpawnData val2 = val.m_spawners[j];
					if (val2 != null && (Object)(object)val2.m_prefab != (Object)null && (Object)(object)val2.m_prefab.GetComponent<Fish>() != (Object)null)
					{
						val2.m_maxSpawned = 25;
						val2.m_spawnInterval = 10f;
						val2.m_spawnChance = 80f;
						val2.m_groupSizeMin = 3;
						val2.m_groupSizeMax = 7;
						val2.m_groupRadius = 8f;
					}
				}
			}
		}
		catch
		{
		}
	}

	public static VideoEntry ResolveVideoEntry(string query)
	{
		if ((Object)(object)CinematicsManager.s_instance == (Object)null || CinematicsManager.s_instance.m_videos == null)
		{
			return null;
		}
		string text = (query ?? "").Trim().ToLower();
		string text2 = text.TrimStart(new char[1] { '$' });
		if (text2.StartsWith("biome_"))
		{
			text2 = text2.Substring(6);
		}
		if (text2.StartsWith("cinematics_"))
		{
			text2 = text2.Substring(11);
		}
		for (int i = 0; i < CinematicsManager.s_instance.m_videos.Count; i++)
		{
			VideoEntry val = CinematicsManager.s_instance.m_videos[i];
			if (val != null && !string.IsNullOrEmpty(val.m_name) && string.Equals(val.m_name, query, StringComparison.OrdinalIgnoreCase))
			{
				return val;
			}
		}
		for (int i = 0; i < CinematicsManager.s_instance.m_videos.Count; i++)
		{
			VideoEntry val = CinematicsManager.s_instance.m_videos[i];
			if (val != null && !string.IsNullOrEmpty(val.m_name))
			{
				string text3 = val.m_name.Trim().ToLower().TrimStart(new char[1] { '$' });
				if (text3.StartsWith("biome_"))
				{
					text3 = text3.Substring(6);
				}
				if (text3.StartsWith("cinematics_"))
				{
					text3 = text3.Substring(11);
				}
				if (text3 == text2 || text3.TrimEnd(new char[1] { 's' }) == text2.TrimEnd(new char[1] { 's' }) || text3.Contains(text2) || text2.Contains(text3))
				{
					return val;
				}
			}
		}
		return null;
	}

	public static string GetNextPartyCinematic()
	{
		if ((Object)(object)ZoneSystem.instance == (Object)null)
		{
			return null;
		}
		for (int i = 0; i < _storyCinematics.Length; i++)
		{
			StoryCinematic storyCinematic = _storyCinematics[i];
			string text = "Citadel_PartyWatched_" + storyCinematic.Video.ToLower();
			if (!ZoneSystem.instance.GetGlobalKey(text))
			{
				bool flag = false;
				if (string.IsNullOrEmpty(storyCinematic.ReqGlobalKey))
				{
					flag = true;
				}
				else if (ZoneSystem.instance.GetGlobalKey(storyCinematic.ReqGlobalKey))
				{
					flag = true;
				}
				if (flag)
				{
					return storyCinematic.Video;
				}
				break;
			}
		}
		return null;
	}

	public static void MarkPartyCinematicWatched(string video)
	{
		if (!((Object)(object)ZoneSystem.instance == (Object)null) && !string.IsNullOrEmpty(video))
		{
			string globalKey = "Citadel_PartyWatched_" + video.ToLower();
			ZoneSystem.instance.SetGlobalKey(globalKey);
		}
	}

	public static void ResetPartyCinematics()
	{
		if (!((Object)(object)ZoneSystem.instance == (Object)null))
		{
			for (int i = 0; i < _storyCinematics.Length; i++)
			{
				string text = "Citadel_PartyWatched_" + _storyCinematics[i].Video.ToLower();
				ZoneSystem.instance.RemoveGlobalKey(text);
			}
			Debug.Log((object)"[CitadelStoryCinematics] Party cinematics history reset by server.");
		}
	}

	public static bool SetPartyCinematicsTo(string targetVideo)
	{
		if ((Object)(object)ZoneSystem.instance == (Object)null)
		{
			return false;
		}
		int num = -1;
		for (int i = 0; i < _storyCinematics.Length; i++)
		{
			if (string.Equals(_storyCinematics[i].Video, targetVideo, StringComparison.OrdinalIgnoreCase))
			{
				num = i;
				break;
			}
		}
		if (num == -1)
		{
			return false;
		}
		for (int i = 0; i < num; i++)
		{
			string globalKey = "Citadel_PartyWatched_" + _storyCinematics[i].Video.ToLower();
			ZoneSystem.instance.SetGlobalKey(globalKey);
		}
		for (int i = num; i < _storyCinematics.Length; i++)
		{
			string globalKey = "Citadel_PartyWatched_" + _storyCinematics[i].Video.ToLower();
			ZoneSystem.instance.RemoveGlobalKey(globalKey);
		}
		Debug.Log((object)("[CitadelStoryCinematics] Party cinematics progress set to: " + targetVideo));
		return true;
	}

	private static void OnServerSleepStarted()
	{
		string nextPartyCinematic = GetNextPartyCinematic();
		if (!string.IsNullOrEmpty(nextPartyCinematic))
		{
			Debug.Log((object)("[CitadelStoryCinematics] Server broadcasting party cinematic for sleep: " + nextPartyCinematic));
			MarkPartyCinematicWatched(nextPartyCinematic);
			_serverWatchingPlayers.Clear();
			_serverCinematicSleepStartTime = Time.time;
			if (ZRoutedRpc.instance != null)
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(0L, "Citadel_PlayPartyCinematic", new object[1] { nextPartyCinematic });
			}
		}
	}

	public static void EndStoryCinematic()
	{
		if (!_isStoryCinematicPlaying)
		{
			return;
		}
		_isStoryCinematicPlaying = false;
		Debug.Log((object)"[CitadelStoryCinematics] Cinematic playback finished.");
		if (ZRoutedRpc.instance != null)
		{
			ZRoutedRpc.instance.InvokeRoutedRPC(0L, "Citadel_CinematicPlaying", new object[1] { false });
		}
		if (_pendingSleepStop)
		{
			_pendingSleepStop = false;
			Debug.Log((object)"[CitadelStoryCinematics] Executing deferred SleepStop after cinematic.");
			if ((Object)(object)Game.instance != (Object)null && _mGameSleepStop != null)
			{
				_mGameSleepStop.Invoke(Game.instance, new object[1] { 0L });
			}
		}
	}

	[HarmonyPatch(typeof(Game), "Start")]
	[HarmonyPostfix]
	public static void Game_Start_Cinematics_Postfix()
	{
		if (ZRoutedRpc.instance != null)
		{
			ZRoutedRpc.instance.Register<bool>("Citadel_CinematicPlaying", (Action<long, bool>)RPC_Citadel_CinematicPlaying);
			ZRoutedRpc.instance.Register<string>("Citadel_PlayPartyCinematic", (Action<long, string>)RPC_Citadel_PlayPartyCinematic);
			ZRoutedRpc.instance.Register("Citadel_ResetPartyCinematics", (Action<long>)RPC_Citadel_ResetPartyCinematics);
			ZRoutedRpc.instance.Register<string>("Citadel_SetPartyCinematics", (Action<long, string>)RPC_Citadel_SetPartyCinematics);
		}
	}

	public static void RPC_Citadel_PlayPartyCinematic(long sender, string videoKey)
	{
		//IL_0071: Unknown result type (might be due to invalid IL or missing references)
		//IL_007b: Expected O, but got Unknown
		Debug.Log((object)("[CitadelStoryCinematics] Received party cinematic request from server: " + videoKey));
		VideoEntry val = ResolveVideoEntry(videoKey);
		if (val == null)
		{
			return;
		}
		_isStoryCinematicPlaying = true;
		_pendingSleepStop = false;
		if (ZRoutedRpc.instance != null)
		{
			ZRoutedRpc.instance.InvokeRoutedRPC(0L, "Citadel_CinematicPlaying", new object[1] { true });
		}
		if (!CinematicsManager.Play(val, (VideoCompleteAction)delegate
		{
			EndStoryCinematic();
		}))
		{
			_isStoryCinematicPlaying = false;
			if (ZRoutedRpc.instance != null)
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(0L, "Citadel_CinematicPlaying", new object[1] { false });
			}
		}
	}

	public static void RPC_Citadel_ResetPartyCinematics(long sender)
	{
		if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer())
		{
			ResetPartyCinematics();
		}
	}

	public static void RPC_Citadel_SetPartyCinematics(long sender, string targetVideo)
	{
		if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer())
		{
			SetPartyCinematicsTo(targetVideo);
		}
	}

	public static void RPC_Citadel_CinematicPlaying(long sender, bool isPlaying)
	{
		if (isPlaying)
		{
			_serverWatchingPlayers.Add(sender);
			_serverCinematicSleepStartTime = Time.time;
			Debug.Log((object)("[CitadelStoryCinematics] Player " + sender + " started watching cinematic. Holding server sleep."));
			return;
		}
		_serverWatchingPlayers.Remove(sender);
		Debug.Log((object)("[CitadelStoryCinematics] Player " + sender + " ended cinematic. Remaining viewers: " + _serverWatchingPlayers.Count));
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(Game), "UpdateSleeping")]
	public static bool Game_UpdateSleeping_Prefix(Game __instance)
	{
		if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer())
		{
			bool flag = _fGameSleeping != null && (bool)_fGameSleeping.GetValue(__instance);
			if (flag && !_serverWasSleeping)
			{
				_serverWasSleeping = true;
				OnServerSleepStarted();
			}
			else if (!flag && _serverWasSleeping)
			{
				_serverWasSleeping = false;
			}
			if (flag && _serverWatchingPlayers.Count > 0)
			{
				if (Time.time - _serverCinematicSleepStartTime < 120f)
				{
					return false;
				}
				Debug.LogWarning((object)"[CitadelStoryCinematics] Sleep hold timed out after 120s.");
				_serverWatchingPlayers.Clear();
			}
		}
		return true;
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(CinematicsManager), "OnSleep")]
	public static bool CinematicsManager_OnSleep_Prefix()
	{
		//IL_0062: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Expected O, but got Unknown
		if (_isStoryCinematicPlaying || CinematicsManager.IsPlaying() || CinematicsManager.IsStartedPlaying())
		{
			return false;
		}
		try
		{
			string nextPartyCinematic = GetNextPartyCinematic();
			if (!string.IsNullOrEmpty(nextPartyCinematic))
			{
				VideoEntry val = ResolveVideoEntry(nextPartyCinematic);
				if (val != null)
				{
					_isStoryCinematicPlaying = true;
					MarkPartyCinematicWatched(nextPartyCinematic);
					CinematicsManager.Play(val, (VideoCompleteAction)delegate
					{
						EndStoryCinematic();
					});
					return false;
				}
			}
		}
		catch
		{
		}
		return true;
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(DreamTexts), "GetRandomDreamText")]
	public static void DreamTexts_GetRandomDreamText_Postfix(DreamTexts __instance, ref DreamText __result)
	{
		try
		{
			if (__result != null || (Object)(object)__instance == (Object)null || __instance.m_texts == null || __instance.m_texts.Count == 0 || CinematicsManager.IsPlaying())
			{
				return;
			}
			List<DreamText> list = new List<DreamText>();
			for (int i = 0; i < __instance.m_texts.Count; i++)
			{
				DreamText val = __instance.m_texts[i];
				if (val == null)
				{
					continue;
				}
				bool flag = true;
				if ((Object)(object)ZoneSystem.instance != (Object)null)
				{
					if (val.m_trueKeys != null)
					{
						for (int j = 0; j < val.m_trueKeys.Count; j++)
						{
							if (!ZoneSystem.instance.GetGlobalKey(val.m_trueKeys[j]))
							{
								flag = false;
								break;
							}
						}
					}
					if (flag && val.m_falseKeys != null)
					{
						for (int j = 0; j < val.m_falseKeys.Count; j++)
						{
							if (ZoneSystem.instance.GetGlobalKey(val.m_falseKeys[j]))
							{
								flag = false;
								break;
							}
						}
					}
				}
				if (flag)
				{
					list.Add(val);
				}
			}
			if (list.Count > 0)
			{
				int index = Random.Range(0, list.Count);
				__result = list[index];
			}
		}
		catch
		{
		}
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(Terminal), "InitTerminal")]
	public static void Terminal_InitTerminal_Postfix()
	{
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Expected O, but got Unknown
		//IL_006e: 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: Expected O, but got Unknown
		//IL_00a7: 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_0096: Expected O, but got Unknown
		//IL_00e0: 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_00cf: Expected O, but got Unknown
		try
		{
			new ConsoleCommand("cinematic_queue", "Show Citadel Party Story Cinematics Queue status", (ConsoleEvent)delegate(ConsoleEventArgs args)
			{
				if ((Object)(object)ZoneSystem.instance == (Object)null)
				{
					args.Context.AddString("World not loaded yet.");
				}
				else
				{
					args.Context.AddString("=== Citadel Party Story Cinematics Queue ===");
					bool flag = false;
					for (int i = 0; i < _storyCinematics.Length; i++)
					{
						StoryCinematic storyCinematic = _storyCinematics[i];
						string text = "Citadel_PartyWatched_" + storyCinematic.Video.ToLower();
						if (ZoneSystem.instance.GetGlobalKey(text))
						{
							args.Context.AddString("[X] " + storyCinematic.Video + " - " + storyCinematic.Description + " (Watched by party)");
						}
						else
						{
							bool flag2 = false;
							if (string.IsNullOrEmpty(storyCinematic.ReqGlobalKey))
							{
								flag2 = true;
							}
							else if (ZoneSystem.instance.GetGlobalKey(storyCinematic.ReqGlobalKey))
							{
								flag2 = true;
							}
							if (!flag && flag2)
							{
								args.Context.AddString("[>] " + storyCinematic.Video + " - " + storyCinematic.Description + " (READY: Will play TOGETHER on next sleep!)");
								flag = true;
							}
							else if (!flag2)
							{
								args.Context.AddString("[ ] " + storyCinematic.Video + " - " + storyCinematic.Description + " (Locked: requires '" + storyCinematic.ReqGlobalKey + "')");
							}
							else
							{
								args.Context.AddString("[ ] " + storyCinematic.Video + " - " + storyCinematic.Description + " (Unlocked, queued after earlier scenes)");
							}
						}
					}
				}
			}, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
			new ConsoleCommand("cinematic_reset", "Reset party story cinematics to intro for all players", (ConsoleEvent)delegate(ConsoleEventArgs args)
			{
				if (ZRoutedRpc.instance != null)
				{
					ZRoutedRpc.instance.InvokeRoutedRPC(0L, "Citadel_ResetPartyCinematics", new object[0]);
					args.Context.AddString("Party story cinematics reset! The entire party will re-experience unlocked cinematics in order on each sleep.");
				}
			}, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
			new ConsoleCommand("cinematic_set", "Set party story cinematics progress to a specific scene (e.g. blackforest)", (ConsoleEvent)delegate(ConsoleEventArgs args)
			{
				if (args.Length < 2)
				{
					args.Context.AddString("Usage: cinematic_set <scene_name>");
					args.Context.AddString("Available: intro, blackforest, swamp, mountains, plains, mistlands, ashlands, deepnorth");
				}
				else
				{
					string text = args[1].Trim().ToLower();
					if (ZRoutedRpc.instance != null)
					{
						ZRoutedRpc.instance.InvokeRoutedRPC(0L, "Citadel_SetPartyCinematics", new object[1] { text });
						args.Context.AddString("Party story cinematics progress set to: " + text + "! Next sleep will play this scene together.");
					}
				}
			}, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
			new ConsoleCommand("cinematic_play", "Play a cinematic video locally by name", (ConsoleEvent)delegate(ConsoleEventArgs args)
			{
				if (args.Length < 2)
				{
					args.Context.AddString("Usage: cinematic_play <name>");
					args.Context.AddString("Available: intro, blackforest, swamp, mountains, plains, mistlands, ashlands, deepnorth, outro, credits");
				}
				else
				{
					string text = args[1].Trim();
					VideoEntry val = ResolveVideoEntry(text);
					if (val != null)
					{
						bool flag = CinematicsManager.Play(val, (VideoCompleteAction)null);
						args.Context.AddString("Playing cinematic: " + val.m_name + " (result: " + flag + ")");
					}
					else
					{
						args.Context.AddString("Could not find cinematic matching: " + text);
					}
				}
			}, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
		}
		catch (Exception ex)
		{
			Debug.LogWarning((object)("[CitadelStoryCinematics] Error registering console commands: " + ex));
		}
	}

	private static bool IsFishingGear(ItemData item)
	{
		if (item == null)
		{
			return false;
		}
		if ((Object)(object)item.m_dropPrefab != (Object)null)
		{
			string name = ((Object)item.m_dropPrefab).name;
			if (name.Equals("FishingRod", StringComparison.OrdinalIgnoreCase) || name.Equals("ChitinHarpoon", StringComparison.OrdinalIgnoreCase) || name.IndexOf("fishingrod", StringComparison.OrdinalIgnoreCase) >= 0 || name.IndexOf("harpoon", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return true;
			}
		}
		if (item.m_shared != null && !string.IsNullOrEmpty(item.m_shared.m_name))
		{
			string name2 = item.m_shared.m_name;
			if (name2.IndexOf("fishingrod", StringComparison.OrdinalIgnoreCase) >= 0 || name2.IndexOf("harpoon", StringComparison.OrdinalIgnoreCase) >= 0 || name2.IndexOf("chitinharpoon", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return true;
			}
		}
		return false;
	}

	private static bool IsPlayerFishingActive(Player player)
	{
		if ((Object)(object)player == (Object)null)
		{
			return false;
		}
		if (IsFishingGear(((Humanoid)player).RightItem) || IsFishingGear(((Humanoid)player).LeftItem))
		{
			return true;
		}
		try
		{
			if (_mFindFloatOwner != null)
			{
				object obj = _mFindFloatOwner.Invoke(null, new object[1] { player });
				if (obj != null)
				{
					return true;
				}
			}
		}
		catch
		{
		}
		return false;
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(Fish), "SetVisible")]
	public static void Fish_SetVisible_Prefix(Fish __instance, ref bool visible)
	{
		//IL_0031: 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)
		try
		{
			if (!visible)
			{
				Player localPlayer = Player.m_localPlayer;
				if ((Object)(object)localPlayer != (Object)null && (Object)(object)__instance != (Object)null && Vector3.Distance(((Component)localPlayer).transform.position, ((Component)__instance).transform.position) < 65f)
				{
					visible = true;
				}
			}
		}
		catch
		{
		}
	}

	[HarmonyPatch(typeof(Fish), "CustomFixedUpdate")]
	[HarmonyPrefix]
	public static void Fish_CustomFixedUpdate_Prefix(Fish __instance)
	{
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_0064: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			if ((Object)(object)__instance == (Object)null)
			{
				return;
			}
			ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
			if (!((Object)(object)component == (Object)null) && component.IsValid())
			{
				Player localPlayer = Player.m_localPlayer;
				if ((Object)(object)localPlayer != (Object)null && !component.IsOwner() && Vector3.Distance(((Component)localPlayer).transform.position, ((Component)__instance).transform.position) < 40f && !component.HasOwner())
				{
					component.ClaimOwnership();
				}
			}
		}
		catch
		{
		}
	}

	[HarmonyPatch(typeof(Projectile), "OnHit")]
	[HarmonyPrefix]
	public static void Projectile_OnHit_FishCatch_Prefix(Projectile __instance, Collider collider)
	{
		try
		{
			if ((Object)(object)__instance == (Object)null || (Object)(object)collider == (Object)null)
			{
				return;
			}
			Fish componentInParent = ((Component)collider).GetComponentInParent<Fish>();
			if ((Object)(object)componentInParent != (Object)null)
			{
				Player val = (Player)(((object)((_fProjectileOwner != null) ? /*isinst with value type is only supported in some contexts*/: null)) ?? ((object)Player.m_localPlayer));
				if ((Object)(object)val != (Object)null)
				{
					componentInParent.Pickup((Humanoid)(object)val);
				}
			}
		}
		catch
		{
		}
	}

	[HarmonyPatch(typeof(Player), "Update")]
	[HarmonyPostfix]
	public static void Player_Update_FishController_Postfix(Player __instance)
	{
		//IL_00ba: 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_00c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_0200: Unknown result type (might be due to invalid IL or missing references)
		//IL_0205: 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)
		//IL_0111: Unknown result type (might be due to invalid IL or missing references)
		//IL_028b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0290: Unknown result type (might be due to invalid IL or missing references)
		//IL_0298: Unknown result type (might be due to invalid IL or missing references)
		//IL_029d: Unknown result type (might be due to invalid IL or missing references)
		//IL_029f: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e7: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e9: Unknown result type (might be due to invalid IL or missing references)
		//IL_02eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f0: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f8: Unknown result type (might be due to invalid IL or missing references)
		//IL_02fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0302: Unknown result type (might be due to invalid IL or missing references)
		//IL_0304: Unknown result type (might be due to invalid IL or missing references)
		//IL_0231: Unknown result type (might be due to invalid IL or missing references)
		//IL_0236: Unknown result type (might be due to invalid IL or missing references)
		//IL_019b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0400: Unknown result type (might be due to invalid IL or missing references)
		//IL_0405: Unknown result type (might be due to invalid IL or missing references)
		//IL_0407: Unknown result type (might be due to invalid IL or missing references)
		//IL_0409: Unknown result type (might be due to invalid IL or missing references)
		//IL_040b: Unknown result type (might be due to invalid IL or missing references)
		//IL_040f: Invalid comparison between Unknown and I4
		//IL_0156: Unknown result type (might be due to invalid IL or missing references)
		//IL_0439: Unknown result type (might be due to invalid IL or missing references)
		//IL_043d: Invalid comparison between Unknown and I4
		//IL_0411: Unknown result type (might be due to invalid IL or missing references)
		//IL_0414: Unknown result type (might be due to invalid IL or missing references)
		//IL_0426: Expected I4, but got Unknown
		//IL_0456: Unknown result type (might be due to invalid IL or missing references)
		//IL_045d: Invalid comparison between Unknown and I4
		//IL_043f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0443: Invalid comparison between Unknown and I4
		//IL_0426: Unknown result type (might be due to invalid IL or missing references)
		//IL_0429: Invalid comparison between Unknown and I4
		//IL_035d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0462: Unknown result type (might be due to invalid IL or missing references)
		//IL_0469: Invalid comparison between Unknown and I4
		//IL_0448: Unknown result type (might be due to invalid IL or missing references)
		//IL_044c: Invalid comparison between Unknown and I4
		//IL_042b: Unknown result type (might be due to invalid IL or missing references)
		//IL_042f: Invalid comparison between Unknown and I4
		//IL_05ac: Unknown result type (might be due to invalid IL or missing references)
		//IL_05c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_0607: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			if ((Object)(object)__instance == (Object)null || (Object)(object)__instance != (Object)(object)Player.m_localPlayer || (Object)(object)ZNetScene.instance == (Object)null || (Object)(object)ZoneSystem.instance == (Object)null)
			{
				return;
			}
			bool flag = IsPlayerFishingActive(__instance);
			float time = Time.time;
			if (flag)
			{
				_lastFishingGearActiveTime = time;
			}
			if (_spawnedFishTracker.Count > 0)
			{
				bool flag2 = time - _lastFishingGearActiveTime > 150f;
				List<ZDOID> list = null;
				foreach (KeyValuePair<ZDOID, float> item in _spawnedFishTracker)
				{
					ZDOID key = item.Key;
					GameObject val = ZNetScene.instance.FindInstance(key);
					if ((Object)(object)val == (Object)null)
					{
						if (list == null)
						{
							list = new List<ZDOID>();
						}
						list.Add(key);
						continue;
					}
					float num = Vector3.Distance(val.transform.position, ((Component)__instance).transform.position);
					if (num > 85f || flag2)
					{
						ZNetScene.instance.Destroy(val);
						if (list == null)
						{
							list = new List<ZDOID>();
						}
						list.Add(key);
					}
				}
				if (list != null)
				{
					for (int i = 0; i < list.Count; i++)
					{
						_spawnedFishTracker.Remove(list[i]);
					}
				}
			}
			if (!flag || time - _lastFishSpawnCheckTime < 3f)
			{
				return;
			}
			_lastFishSpawnCheckTime = time;
			int num2 = 0;
			if (Fish.Instances != null)
			{
				Vector3 position = ((Component)__instance).transform.position;
				for (int i = 0; i < Fish.Instances.Count; i++)
				{
					IMonoUpdater obj = Fish.Instances[i];
					Fish val2 = (Fish)(object)((obj is Fish) ? obj : null);
					if ((Object)(object)val2 != (Object)null && Vector3.Distance(((Component)val2).transform.position, position) < 35f)
					{
						num2++;
					}
				}
			}
			if (num2 >= 6)
			{
				return;
			}
			Vector3 position2 = ((Component)__instance).transform.position;
			Vector3 forward = ((Component)__instance).transform.forward;
			Vector3 zero = Vector3.zero;
			bool flag3 = false;
			for (int j = 0; j < 8; j++)
			{
				float num = Random.Range(8f, 20f);
				float num3 = Random.Range(-110f, 110f);
				Quaternion val3 = Quaternion.Euler(0f, num3, 0f);
				Vector3 val4 = val3 * forward;
				Vector3 val5 = position2 + val4 * num;
				float num4 = Floating.GetLiquidLevel(val5, 1f, (LiquidType)0);
				if (num4 < -5000f && (Object)(object)ZoneSystem.instance != (Object)null)
				{
					num4 = ZoneSystem.instance.m_waterLevel;
				}
				if (!(num4 > -5000f))
				{
					continue;
				}
				float solidHeight = ZoneSystem.instance.GetSolidHeight(val5);
				if (solidHeight > -5000f && solidHeight < 10000f)
				{
					float num5 = num4 - solidHeight;
					if (num5 >= 1.2f)
					{
						float num6 = Random.Range(0.4f, Mathf.Min(num5 * 0.7f, 2f));
						((Vector3)(ref zero))..ctor(val5.x, num4 - num6, val5.z);
						flag3 = true;
						break;
					}
				}
			}
			if (!flag3)
			{
				return;
			}
			Biome currentBiome = __instance.GetCurrentBiome();
			Biome val6 = currentBiome;
			string[] array;
			if ((int)val6 <= 16)
			{
				switch (val6 - 2)
				{
				case 0:
					goto IL_0496;
				case 2:
					goto IL_04b0;
				case 1:
					goto IL_055b;
				}
				if ((int)val6 != 8)
				{
					if ((int)val6 != 16)
					{
						goto IL_055b;
					}
					array = new string[2] { "Fish6", "Fish7" };
				}
				else
				{
					array = new string[2] { "Fish2", "Fish3" };
				}
			}
			else if ((int)val6 <= 64)
			{
				if ((int)val6 != 32)
				{
					if ((int)val6 != 64)
					{
						goto IL_055b;
					}
					array = new string[1] { "Fish12" };
				}
				else
				{
					array = new string[1] { "Fish11" };
				}
			}
			else if ((int)val6 != 256)
			{
				if ((int)val6 != 512)
				{
					goto IL_055b;
				}
				array = new string[2] { "Fish9", "Fish10" };
			}
			else
			{
				array = new string[2] { "Fish7", "Fish8" };
			}
			goto IL_057b;
			IL_055b:
			array = new string[2] { "Fish1", "Fish2" };
			goto IL_057b;
			IL_04b0:
			array = new string[1] { "Fish4_cave" };
			goto IL_057b;
			IL_057b:
			string text = array[Random.Range(0, array.Length)];
			GameObject prefab = ZNetScene.instance.GetPrefab(text);
			if ((Object)(object)prefab != (Object)null)
			{
				GameObject val7 = Object.Instantiate<GameObject>(prefab, zero, Quaternion.Euler(0f, Random.Range(0f, 360f), 0f));
				ZNetView component = val7.GetComponent<ZNetView>();
				if ((Object)(object)component != (Object)null && component.GetZDO() != null)
				{
					_spawnedFishTracker[component.GetZDO().m_uid] = time;
				}
			}
			return;
			IL_0496:
			array = new string[1] { "Fish5" };
			goto IL_057b;
		}
		catch (Exception ex)
		{
			Debug.LogWarning((object)("[FishController] Error in fish update: " + ex.Message));
		}
	}
}