Decompiled source of ManeaterCandy v0.1.0

ManeaterCandy.dll

Decompiled an hour ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ManeaterCandy
{
	[BepInPlugin("ManeaterCandy", "ManeaterCandy", "0.1.0")]
	public class Plugin : BaseUnityPlugin
	{
		private class CalmState
		{
			public bool Active;

			public float CalmUntil;

			public float NextTick;

			public float NextScan;

			public float NextSitSync;

			public float LastWitnessCheck;

			public float BodyWatched;

			public bool[] WasDead;
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static HandleNamedMessageDelegate <0>__OnFeedResult;

			public static HandleNamedMessageDelegate <1>__OnSettings;

			public static HandleNamedMessageDelegate <2>__OnFeedRequest;

			public static HandleNamedMessageDelegate <3>__OnSettingsRequest;
		}

		internal static ManualLogSource Log;

		internal static ConfigEntry<float> CalmSeconds;

		internal static ConfigEntry<string> FoodItems;

		internal static ConfigEntry<float> FeedDistance;

		internal static ConfigEntry<bool> FeedByDropping;

		internal static ConfigEntry<float> FeedRadius;

		internal static ConfigEntry<float> WitnessRadius;

		internal static ConfigEntry<float> BodyWatchSeconds;

		internal static ConfigEntry<bool> EatingEffects;

		private const string RequestMsg = "ManeaterCandy.FeedRequest";

		private const string ResultMsg = "ManeaterCandy.FeedResult";

		private const string SettingsRequestMsg = "ManeaterCandy.SettingsRequest";

		private const string SettingsMsg = "ManeaterCandy.Settings";

		private static string hostFoodItems;

		private static CustomMessagingManager registeredFor;

		private static float nextRequestAllowed;

		private static readonly FieldInfo MaskField = AccessTools.Field(typeof(PlayerControllerB), "interactableObjectsMask");

		private static readonly ConditionalWeakTable<CaveDwellerAI, CalmState> States = new ConditionalWeakTable<CaveDwellerAI, CalmState>();

		private void Awake()
		{
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Expected O, but got Unknown
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Expected O, but got Unknown
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Expected O, but got Unknown
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Expected O, but got Unknown
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Expected O, but got Unknown
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Expected O, but got Unknown
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Expected O, but got Unknown
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Expected O, but got Unknown
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_0220: Expected O, but got Unknown
			//IL_0220: Unknown result type (might be due to invalid IL or missing references)
			//IL_023b: Expected O, but got Unknown
			//IL_023b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0256: Expected O, but got Unknown
			//IL_0256: Unknown result type (might be due to invalid IL or missing references)
			//IL_0271: Expected O, but got Unknown
			//IL_028b: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			CalmSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("General", "CalmSeconds", 240f, "How many seconds the baby Maneater stays calm (sitting, no following, no crying) after eating.");
			FoodItems = ((BaseUnityPlugin)this).Config.Bind<string>("General", "FoodItems", "Candy", "Item names the baby will eat, separated by commas. Must match the in-game item name exactly (e.g. Candy,Rubber Ducky).");
			FeedDistance = ((BaseUnityPlugin)this).Config.Bind<float>("General", "FeedDistance", 6f, "Safety check on the host: the player feeding the baby must be within this many meters of it.");
			FeedByDropping = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "FeedByDropping", false, "If true, food dropped on the ground next to the baby is eaten too (old behaviour). If false, food must be given with E.");
			FeedRadius = ((BaseUnityPlugin)this).Config.Bind<float>("General", "FeedRadius", 3f, "Only used when FeedByDropping is true: how close (in meters) dropped food must be to the baby.");
			WitnessRadius = ((BaseUnityPlugin)this).Config.Bind<float>("General", "WitnessRadius", 15f, "How far (in meters) the baby can see a player die or a dead body and get scared.");
			BodyWatchSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("General", "BodyWatchSeconds", 20f, "How many seconds the baby must keep seeing a dead body before it gets scared.");
			EatingEffects = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "EatingEffects", true, "If true, the baby plays the game's own eating animation and bite sound (and gets a little chubbier) when it is fed.");
			Harmony val = new Harmony("ManeaterCandy");
			PatchMethod(val, typeof(CaveDwellerAI), "Update", null, "UpdatePostfix");
			PatchMethod(val, typeof(CaveDwellerAI), "DoBabyAIInterval", "DoBabyAIIntervalPrefix", null);
			PatchMethod(val, typeof(CaveDwellerAI), "SetCryingLocalClient", "SetCryingPrefix", null);
			PatchMethod(val, typeof(CaveDwellerAI), "SetBabyCryingServerRpc", "SetCryingPrefix", null);
			PatchMethod(val, typeof(CaveDwellerAI), "ScareBaby", "BlockWhileCalmPrefix", null);
			PatchMethod(val, typeof(CaveDwellerAI), "DetectNoise", "BlockWhileCalmPrefix", null);
			PatchMethod(val, typeof(CaveDwellerAI), "HitEnemy", "DamagePrefix", null);
			PatchMethod(val, typeof(CaveDwellerAI), "KillEnemy", "DamagePrefix", null);
			PatchMethod(val, typeof(EnemyAI), "SetEnemyStunned", "StunPrefix", null);
			PatchMethod(val, typeof(EnemyAI), "ChangeOwnershipOfEnemy", "OwnershipPrefix", null);
			PatchMethod(val, typeof(PlayerControllerB), "BeginGrabObject", "BeginGrabPrefix", null);
			PatchMethod(val, typeof(PlayerControllerB), "SetHoverTipAndCurrentInteractTrigger", null, "HoverTipPostfix");
			PatchMethod(val, typeof(PlayerControllerB), "ConnectClientToPlayerObject", null, "ConnectPostfix");
			Log.LogInfo((object)"ManeaterCandy loaded.");
		}

		private static void PatchMethod(Harmony harmony, Type type, string methodName, string prefix, string postfix)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			MethodInfo methodInfo = AccessTools.Method(type, methodName, (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				Log.LogError((object)("Could not find " + type.Name + "." + methodName + " - this part of the mod will not work."));
			}
			else
			{
				harmony.Patch((MethodBase)methodInfo, (prefix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(Plugin), prefix, (Type[])null), (postfix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(Plugin), postfix, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Log.LogInfo((object)("Patched " + type.Name + "." + methodName));
			}
		}

		private static bool IsCalm(CaveDwellerAI baby)
		{
			if (States.TryGetValue(baby, out var value) && value.Active)
			{
				return Time.time < value.CalmUntil;
			}
			return false;
		}

		internal static void UpdatePostfix(CaveDwellerAI __instance)
		{
			if (!((NetworkBehaviour)__instance).IsServer || ((EnemyAI)__instance).isEnemyDead)
			{
				return;
			}
			CalmState orCreateValue = States.GetOrCreateValue(__instance);
			if (orCreateValue.Active && ((EnemyAI)__instance).currentBehaviourStateIndex != 0)
			{
				EndCalm(__instance, orCreateValue, "it is no longer a baby");
				return;
			}
			if (orCreateValue.Active)
			{
				HoldCalm(__instance);
			}
			if (Time.time < orCreateValue.NextTick)
			{
				return;
			}
			orCreateValue.NextTick = Time.time + 0.2f;
			EnsureHandlers();
			if (((EnemyAI)__instance).currentBehaviourStateIndex != 0)
			{
				return;
			}
			if (orCreateValue.Active)
			{
				if (Time.time >= orCreateValue.CalmUntil)
				{
					EndCalm(__instance, orCreateValue, "calm time is over");
					return;
				}
				CheckWitness(__instance, orCreateValue);
				if (orCreateValue.Active)
				{
					EnforceCalm(__instance, orCreateValue);
				}
			}
			else if (FeedByDropping.Value)
			{
				TryFeedDropped(__instance, orCreateValue);
			}
		}

		internal static bool DoBabyAIIntervalPrefix(CaveDwellerAI __instance)
		{
			if (IsCalm(__instance) && !__instance.holdingBaby)
			{
				return false;
			}
			return true;
		}

		internal static bool SetCryingPrefix(CaveDwellerAI __instance, bool __0)
		{
			if (__0)
			{
				return !IsCalm(__instance);
			}
			return true;
		}

		internal static bool BlockWhileCalmPrefix(CaveDwellerAI __instance)
		{
			return !IsCalm(__instance);
		}

		internal static void DamagePrefix(CaveDwellerAI __instance)
		{
			if (States.TryGetValue(__instance, out var value) && value.Active)
			{
				EndCalm(__instance, value, "it was hurt");
			}
		}

		internal static void StunPrefix(EnemyAI __instance, bool __0)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			if (__0)
			{
				CaveDwellerAI val = (CaveDwellerAI)(object)((__instance is CaveDwellerAI) ? __instance : null);
				if (!((Object)(object)val == (Object)null) && States.TryGetValue(val, out var value) && value.Active)
				{
					Trigger(val, value, ((Component)val).transform.position, "it was stunned");
				}
			}
		}

		internal static bool OwnershipPrefix(EnemyAI __instance, ulong __0)
		{
			CaveDwellerAI val = (CaveDwellerAI)(object)((__instance is CaveDwellerAI) ? __instance : null);
			if ((Object)(object)val != (Object)null && __0 != 0L && !val.holdingBaby && IsCalm(val))
			{
				return false;
			}
			return true;
		}

		internal static bool BeginGrabPrefix(PlayerControllerB __instance)
		{
			try
			{
				if (!((NetworkBehaviour)__instance).IsOwner)
				{
					return true;
				}
				GrabbableObject currentlyHeldObjectServer = __instance.currentlyHeldObjectServer;
				if ((Object)(object)currentlyHeldObjectServer == (Object)null || (Object)(object)currentlyHeldObjectServer.itemProperties == (Object)null || !IsFood(currentlyHeldObjectServer.itemProperties.itemName))
				{
					return true;
				}
				CaveDwellerAI val = FindAimedBaby(__instance);
				if ((Object)(object)val == (Object)null)
				{
					return true;
				}
				if (Time.time < nextRequestAllowed)
				{
					return false;
				}
				nextRequestAllowed = Time.time + 1f;
				NetworkManager singleton = NetworkManager.Singleton;
				if ((Object)(object)singleton == (Object)null)
				{
					return true;
				}
				EnsureHandlers();
				ulong networkObjectId = ((NetworkBehaviour)val).NetworkObject.NetworkObjectId;
				ulong networkObjectId2 = ((NetworkBehaviour)currentlyHeldObjectServer).NetworkObject.NetworkObjectId;
				if (singleton.IsServer)
				{
					HandleFeedRequest(singleton.LocalClientId, networkObjectId, networkObjectId2);
				}
				else
				{
					SendNamed("ManeaterCandy.FeedRequest", 0uL, networkObjectId, networkObjectId2);
				}
				return false;
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Feeding with E failed: " + ex.Message));
				return true;
			}
		}

		internal static void HoverTipPostfix(PlayerControllerB __instance)
		{
			try
			{
				if (((NetworkBehaviour)__instance).IsOwner)
				{
					GrabbableObject currentlyHeldObjectServer = __instance.currentlyHeldObjectServer;
					if (!((Object)(object)currentlyHeldObjectServer == (Object)null) && !((Object)(object)currentlyHeldObjectServer.itemProperties == (Object)null) && IsFood(currentlyHeldObjectServer.itemProperties.itemName) && !((Object)(object)FindAimedBaby(__instance) == (Object)null))
					{
						((TMP_Text)__instance.cursorTip).text = "Feed baby : [E]";
					}
				}
			}
			catch (Exception)
			{
			}
		}

		private static CaveDwellerAI FindAimedBaby(PlayerControllerB player)
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)player.gameplayCamera == (Object)null || MaskField == null)
			{
				return null;
			}
			Transform transform = ((Component)player.gameplayCamera).transform;
			int num = (int)MaskField.GetValue(player);
			RaycastHit val = default(RaycastHit);
			if (!Physics.Raycast(new Ray(transform.position, transform.forward), ref val, player.grabDistance, num))
			{
				return null;
			}
			CaveDwellerPhysicsProp componentInParent = ((Component)((RaycastHit)(ref val)).collider).GetComponentInParent<CaveDwellerPhysicsProp>();
			if ((Object)(object)componentInParent == (Object)null)
			{
				return null;
			}
			return componentInParent.caveDwellerScript;
		}

		internal static void ConnectPostfix()
		{
			EnsureHandlers();
		}

		private static void EnsureHandlers()
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Expected O, but got Unknown
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Expected O, but got Unknown
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Expected O, but got Unknown
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || singleton.CustomMessagingManager == null)
			{
				return;
			}
			CustomMessagingManager customMessagingManager = singleton.CustomMessagingManager;
			if (customMessagingManager == registeredFor)
			{
				return;
			}
			registeredFor = customMessagingManager;
			hostFoodItems = null;
			object obj = <>O.<0>__OnFeedResult;
			if (obj == null)
			{
				HandleNamedMessageDelegate val = OnFeedResult;
				<>O.<0>__OnFeedResult = val;
				obj = (object)val;
			}
			customMessagingManager.RegisterNamedMessageHandler("ManeaterCandy.FeedResult", (HandleNamedMessageDelegate)obj);
			object obj2 = <>O.<1>__OnSettings;
			if (obj2 == null)
			{
				HandleNamedMessageDelegate val2 = OnSettings;
				<>O.<1>__OnSettings = val2;
				obj2 = (object)val2;
			}
			customMessagingManager.RegisterNamedMessageHandler("ManeaterCandy.Settings", (HandleNamedMessageDelegate)obj2);
			if (singleton.IsServer)
			{
				object obj3 = <>O.<2>__OnFeedRequest;
				if (obj3 == null)
				{
					HandleNamedMessageDelegate val3 = OnFeedRequest;
					<>O.<2>__OnFeedRequest = val3;
					obj3 = (object)val3;
				}
				customMessagingManager.RegisterNamedMessageHandler("ManeaterCandy.FeedRequest", (HandleNamedMessageDelegate)obj3);
				object obj4 = <>O.<3>__OnSettingsRequest;
				if (obj4 == null)
				{
					HandleNamedMessageDelegate val4 = OnSettingsRequest;
					<>O.<3>__OnSettingsRequest = val4;
					obj4 = (object)val4;
				}
				customMessagingManager.RegisterNamedMessageHandler("ManeaterCandy.SettingsRequest", (HandleNamedMessageDelegate)obj4);
			}
			Log.LogInfo((object)("Feeding messages registered (" + (singleton.IsServer ? "host" : "client") + ")."));
			if (!singleton.IsServer)
			{
				SendNamed("ManeaterCandy.SettingsRequest", 0uL, 0uL, 0uL);
			}
		}

		private unsafe static void OnSettingsRequest(ulong senderClientId, FastBufferReader reader)
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsServer || singleton.CustomMessagingManager == null)
			{
				return;
			}
			string text = FoodItems.Value ?? "";
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(FastBufferWriter.GetWriteSize(text, false), (Allocator)2, -1);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe(text, false);
				singleton.CustomMessagingManager.SendNamedMessage("ManeaterCandy.Settings", senderClientId, val, (NetworkDelivery)2);
			}
			finally
			{
				((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
			}
		}

		private static void OnSettings(ulong senderClientId, FastBufferReader reader)
		{
			string text = default(string);
			((FastBufferReader)(ref reader)).ReadValueSafe(ref text, false);
			hostFoodItems = text;
			Log.LogInfo((object)("Using the host's food list: " + text));
		}

		private unsafe static void SendNamed(string name, ulong target, ulong a, ulong b)
		{
			//IL_0029: 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_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || singleton.CustomMessagingManager == null)
			{
				return;
			}
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(16, (Allocator)2, -1);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe<ulong>(ref a, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<ulong>(ref b, default(ForPrimitives));
				singleton.CustomMessagingManager.SendNamedMessage(name, target, val, (NetworkDelivery)2);
			}
			finally
			{
				((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
			}
		}

		private static void OnFeedRequest(ulong senderClientId, FastBufferReader reader)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			ulong babyId = default(ulong);
			((FastBufferReader)(ref reader)).ReadValueSafe<ulong>(ref babyId, default(ForPrimitives));
			ulong itemId = default(ulong);
			((FastBufferReader)(ref reader)).ReadValueSafe<ulong>(ref itemId, default(ForPrimitives));
			HandleFeedRequest(senderClientId, babyId, itemId);
		}

		private static void OnFeedResult(ulong senderClientId, FastBufferReader reader)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			ulong itemId = default(ulong);
			((FastBufferReader)(ref reader)).ReadValueSafe<ulong>(ref itemId, default(ForPrimitives));
			ulong num = default(ulong);
			((FastBufferReader)(ref reader)).ReadValueSafe<ulong>(ref num, default(ForPrimitives));
			ApplyResult(itemId, (int)num);
		}

		private static void Reply(ulong target, ulong itemId, int code)
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if (!((Object)(object)singleton == (Object)null))
			{
				if (target == singleton.LocalClientId)
				{
					ApplyResult(itemId, code);
				}
				else
				{
					SendNamed("ManeaterCandy.FeedResult", target, itemId, (ulong)code);
				}
			}
		}

		private static void ApplyResult(ulong itemId, int code)
		{
			try
			{
				if (code == 1)
				{
					ConsumeHeldFood(itemId);
				}
				else if ((Object)(object)HUDManager.Instance != (Object)null)
				{
					string text = ((code == 2) ? "It is already full and calm." : "It does not trust anyone yet.");
					HUDManager.Instance.DisplayTip("Maneater", text, false, false, "LC_Tip1");
				}
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Could not apply the feeding result: " + ex.Message));
			}
		}

		private static void ConsumeHeldFood(ulong itemId)
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if (!((Object)(object)singleton == (Object)null) && singleton.SpawnManager.SpawnedObjects.TryGetValue(itemId, out var value))
			{
				GrabbableObject component = ((Component)value).GetComponent<GrabbableObject>();
				PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
				if (!((Object)(object)component == (Object)null) && !((Object)(object)localPlayerController == (Object)null) && !((Object)(object)component.playerHeldBy != (Object)(object)localPlayerController))
				{
					component.DestroyObjectInHand(localPlayerController);
				}
			}
		}

		private static void HandleFeedRequest(ulong sender, ulong babyId, ulong itemId)
		{
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsServer)
			{
				return;
			}
			Dictionary<ulong, NetworkObject> spawnedObjects = singleton.SpawnManager.SpawnedObjects;
			if (!spawnedObjects.TryGetValue(babyId, out var value) || !spawnedObjects.TryGetValue(itemId, out var value2))
			{
				return;
			}
			CaveDwellerAI component = ((Component)value).GetComponent<CaveDwellerAI>();
			GrabbableObject component2 = ((Component)value2).GetComponent<GrabbableObject>();
			if ((Object)(object)component == (Object)null || (Object)(object)component2 == (Object)null || (Object)(object)component2.itemProperties == (Object)null)
			{
				return;
			}
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null || !instance.ClientPlayerList.TryGetValue(sender, out var value3))
			{
				return;
			}
			PlayerControllerB val = instance.allPlayerScripts[value3];
			if (!((Object)(object)val == (Object)null) && component2.isHeld && !((Object)(object)component2.playerHeldBy != (Object)(object)val) && IsFood(component2.itemProperties.itemName) && !(Vector3.Distance(((Component)val).transform.position, ((Component)component).transform.position) > FeedDistance.Value))
			{
				CalmState orCreateValue = States.GetOrCreateValue(component);
				if (orCreateValue.Active)
				{
					Reply(sender, itemId, 2);
					return;
				}
				if (!CanBeFed(component))
				{
					Reply(sender, itemId, 3);
					return;
				}
				StartCalm(component, orCreateValue, component2.itemProperties.itemName);
				Reply(sender, itemId, 1);
			}
		}

		private static bool CanBeFed(CaveDwellerAI baby)
		{
			if (((EnemyAI)baby).isEnemyDead || ((EnemyAI)baby).currentBehaviourStateIndex != 0 || baby.holdingBaby)
			{
				return false;
			}
			return Traverse.Create((object)baby).Field("playersSeen").GetValue<int>() > 0;
		}

		private static void TryFeedDropped(CaveDwellerAI baby, CalmState s)
		{
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			if (Time.time < s.NextScan)
			{
				return;
			}
			s.NextScan = Time.time + 0.5f;
			if (!CanBeFed(baby))
			{
				return;
			}
			GrabbableObject[] array = Object.FindObjectsOfType<GrabbableObject>();
			foreach (GrabbableObject val in array)
			{
				if (!((Object)(object)val == (Object)null) && !val.isHeld && !val.isHeldByEnemy && !((Object)(object)val.itemProperties == (Object)null) && IsFood(val.itemProperties.itemName) && !(Vector3.Distance(((Component)val).transform.position, ((Component)baby).transform.position) > FeedRadius.Value))
				{
					string itemName = val.itemProperties.itemName;
					NetworkObject networkObject = ((NetworkBehaviour)val).NetworkObject;
					if ((Object)(object)networkObject != (Object)null && networkObject.IsSpawned)
					{
						networkObject.Despawn(true);
					}
					StartCalm(baby, s, itemName);
					break;
				}
			}
		}

		private static void StartCalm(CaveDwellerAI baby, CalmState s, string foodName)
		{
			Log.LogInfo((object)("Baby Maneater ate " + foodName + " and is calm for " + CalmSeconds.Value + "s."));
			s.Active = true;
			s.CalmUntil = Time.time + CalmSeconds.Value;
			s.BodyWatched = 0f;
			s.LastWitnessCheck = Time.time;
			SnapshotDead(s);
			if (EatingEffects.Value)
			{
				PlayEatEffects(baby);
			}
			try
			{
				if (!((NetworkBehaviour)baby).IsOwner)
				{
					((EnemyAI)baby).ChangeOwnershipOfEnemy(0uL);
				}
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Could not take ownership of the baby: " + ex.Message));
			}
			((EnemyAI)baby).targetPlayer = null;
			((EnemyAI)baby).movingTowardsTargetPlayer = false;
			((EnemyAI)baby).moveTowardsDestination = false;
			if (baby.babyCrying)
			{
				CallRpc(baby, "SetBabyCryingServerRpc", value: false);
			}
			if (baby.babyRunning)
			{
				baby.babyRunning = false;
				CallRpc(baby, "SetBabyRunningServerRpc", value: false);
			}
			EnforceCalm(baby, s);
		}

		private static void PlayEatEffects(CaveDwellerAI baby)
		{
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Traverse obj = Traverse.Create((object)baby);
				int num = obj.Field("scrapEaten").GetValue<int>() + 1;
				obj.Field("scrapEaten").SetValue((object)num);
				obj.Field("timeSinceBiting").SetValue((object)Time.realtimeSinceStartup);
				if ((Object)(object)baby.babyCreatureAnimator != (Object)null)
				{
					baby.babyCreatureAnimator.SetTrigger("Bite");
				}
				if ((Object)(object)baby.babyVoice != (Object)null && (Object)(object)baby.biteSFX != (Object)null)
				{
					baby.babyVoice.PlayOneShot(baby.biteSFX);
				}
				if ((Object)(object)baby.spine2 != (Object)null)
				{
					float num2 = Mathf.Lerp(1f, 1.6f, (float)Mathf.Min(num, 3) / 3f);
					baby.spine2.localScale = new Vector3(num2, 1f, num2);
				}
				CallRpc(baby, "ClearBabyObservingClientRpc", value: true);
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Could not play the eating effects: " + ex.Message));
			}
		}

		private static void HoldCalm(CaveDwellerAI baby)
		{
			baby.lonelinessMeter = 0f;
			baby.stressMeter = 0f;
			((EnemyAI)baby).movingTowardsTargetPlayer = false;
			if (!baby.holdingBaby)
			{
				float realtimeSinceStartup = Time.realtimeSinceStartup;
				Traverse obj = Traverse.Create((object)baby);
				obj.Field("currentActivityTimer").SetValue((object)realtimeSinceStartup);
				obj.Field("fallOverWhileSittingChanceInterval").SetValue((object)realtimeSinceStartup);
				obj.Field("pathingTowardsNearestPlayer").SetValue((object)false);
			}
		}

		private static void EnforceCalm(CaveDwellerAI baby, CalmState s)
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			if (baby.holdingBaby)
			{
				return;
			}
			((EnemyAI)baby).targetPlayer = null;
			((EnemyAI)baby).moveTowardsDestination = false;
			try
			{
				if (baby.babySearchRoutine != null && baby.babySearchRoutine.inProgress)
				{
					((EnemyAI)baby).StopSearch(baby.babySearchRoutine, true);
				}
				if ((Object)(object)((EnemyAI)baby).agent != (Object)null && ((EnemyAI)baby).agent.isOnNavMesh)
				{
					((EnemyAI)baby).agent.ResetPath();
					((EnemyAI)baby).agent.velocity = Vector3.zero;
					((EnemyAI)baby).agent.isStopped = true;
				}
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Could not stop the baby: " + ex.Message));
			}
			if (baby.babyRunning)
			{
				baby.babyRunning = false;
				CallRpc(baby, "SetBabyRunningServerRpc", value: false);
			}
			if (baby.sittingDown || baby.rolledOver || !(Time.time >= s.NextSitSync))
			{
				return;
			}
			s.NextSitSync = Time.time + 1f;
			baby.sittingDown = true;
			try
			{
				baby.SetBabySittingServerRpc(true);
			}
			catch (Exception ex2)
			{
				Log.LogWarning((object)("Could not sit the baby down: " + ex2.Message));
			}
		}

		private static void EndCalm(CaveDwellerAI baby, CalmState s, string why)
		{
			if (!s.Active)
			{
				return;
			}
			s.Active = false;
			s.CalmUntil = 0f;
			s.BodyWatched = 0f;
			Log.LogInfo((object)("Baby Maneater is no longer calm: " + why + "."));
			try
			{
				if ((Object)(object)((EnemyAI)baby).agent != (Object)null && ((EnemyAI)baby).agent.isOnNavMesh)
				{
					((EnemyAI)baby).agent.isStopped = false;
				}
			}
			catch (Exception)
			{
			}
			Traverse.Create((object)baby).Field("currentActivityTimer").SetValue((object)Time.realtimeSinceStartup);
		}

		private static void Trigger(CaveDwellerAI baby, CalmState s, Vector3 from, string why)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			EndCalm(baby, s, why);
			try
			{
				Traverse.Create((object)baby).Method("ScareBaby", new object[1] { from }).GetValue();
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Could not scare the baby: " + ex.Message));
			}
		}

		private static void SnapshotDead(CalmState s)
		{
			StartOfRound instance = StartOfRound.Instance;
			if (!((Object)(object)instance == (Object)null) && instance.allPlayerScripts != null)
			{
				PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts;
				s.WasDead = new bool[allPlayerScripts.Length];
				for (int i = 0; i < allPlayerScripts.Length; i++)
				{
					s.WasDead[i] = (Object)(object)allPlayerScripts[i] != (Object)null && allPlayerScripts[i].isPlayerDead;
				}
			}
		}

		private static Vector3 BodyPosition(PlayerControllerB p)
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			DeadBodyInfo deadBody = p.deadBody;
			if ((Object)(object)deadBody != (Object)null)
			{
				if (deadBody.bodyParts != null && deadBody.bodyParts.Length != 0 && (Object)(object)deadBody.bodyParts[0] != (Object)null)
				{
					return ((Component)deadBody.bodyParts[0]).transform.position;
				}
				return ((Component)deadBody).transform.position;
			}
			return ((Component)p).transform.position;
		}

		private static bool CanSee(CaveDwellerAI baby, Vector3 pos)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			float value = WitnessRadius.Value;
			if (Vector3.Distance(((Component)baby).transform.position, pos) > value)
			{
				return false;
			}
			return ((EnemyAI)baby).CheckLineOfSightForPosition(pos, 160f, (int)Mathf.Ceil(value), 4f, baby.BabyEye);
		}

		private static void CheckWitness(CaveDwellerAI baby, CalmState s)
		{
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null || instance.allPlayerScripts == null)
			{
				return;
			}
			PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts;
			if (s.WasDead == null || s.WasDead.Length != allPlayerScripts.Length)
			{
				SnapshotDead(s);
			}
			float num = Mathf.Min(Time.time - s.LastWitnessCheck, 1f);
			s.LastWitnessCheck = Time.time;
			bool flag = false;
			for (int i = 0; i < allPlayerScripts.Length; i++)
			{
				PlayerControllerB val = allPlayerScripts[i];
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				if (!val.isPlayerDead)
				{
					s.WasDead[i] = false;
					continue;
				}
				Vector3 val2 = BodyPosition(val);
				bool flag2 = CanSee(baby, val2);
				if (!s.WasDead[i])
				{
					s.WasDead[i] = true;
					if (flag2)
					{
						Trigger(baby, s, val2, "it saw a player die");
						return;
					}
				}
				if (flag2 && (Object)(object)val.deadBody != (Object)null)
				{
					flag = true;
				}
			}
			if (flag)
			{
				s.BodyWatched += num;
				if (s.BodyWatched >= BodyWatchSeconds.Value)
				{
					Trigger(baby, s, ((Component)baby).transform.position, "it watched a dead body for too long");
				}
			}
			else
			{
				s.BodyWatched = 0f;
			}
		}

		private static void CallRpc(CaveDwellerAI baby, string method, bool value)
		{
			try
			{
				Traverse.Create((object)baby).Method(method, new object[1] { value }).GetValue();
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Could not call " + method + ": " + ex.Message));
			}
		}

		private static bool IsFood(string itemName)
		{
			if (string.IsNullOrEmpty(itemName))
			{
				return false;
			}
			string[] array = (hostFoodItems ?? FoodItems.Value).Split(',');
			for (int i = 0; i < array.Length; i++)
			{
				if (string.Equals(array[i].Trim(), itemName.Trim(), StringComparison.OrdinalIgnoreCase))
				{
					return true;
				}
			}
			return false;
		}
	}
}