Decompiled source of NeckTamingMod v1.0.0

plugins/NeckTamingMod.dll

Decompiled 2 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("NeckTamingMod")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NeckTamingMod")]
[assembly: AssemblyCopyright("Copyright ©  2025")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("934d3332-9f81-4421-88b8-3fc11f6c15dc")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace NeckTamingMod;

[BepInPlugin("com.yourname.necktaming", "Neck Taming Mod", "1.0.0")]
public class NeckTamingMod : BaseUnityPlugin
{
	[Serializable]
	[CompilerGenerated]
	private sealed class <>c
	{
		public static readonly <>c <>9 = new <>c();

		public static ConsoleEvent <>9__38_0;

		public static ConsoleEvent <>9__38_1;

		public static ConsoleEvent <>9__38_4;

		public static ConsoleEvent <>9__38_5;

		internal void <RegisterConsoleCommandsDirectly>b__38_0(ConsoleEventArgs args)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Player.m_localPlayer == (Object)null)
			{
				args.Context.AddString("Ошибка: игрок не найден!");
				return;
			}
			try
			{
				Vector3 val = ((Component)Player.m_localPlayer).transform.position + ((Component)Player.m_localPlayer).transform.forward * 3f + Vector3.up;
				GameObject prefab = ZNetScene.instance.GetPrefab("Neck");
				if ((Object)(object)prefab != (Object)null)
				{
					GameObject neck = Object.Instantiate<GameObject>(prefab, val, Quaternion.identity);
					MakeBabyNeck(neck);
					args.Context.AddString("Никсёнок создан!");
				}
				else
				{
					args.Context.AddString("Ошибка: префаб никса не найден!");
				}
			}
			catch (Exception ex)
			{
				Debug.LogError((object)$"Ошибка создания никсёнка: {ex}");
				args.Context.AddString("Ошибка: " + ex.Message);
			}
		}

		internal void <RegisterConsoleCommandsDirectly>b__38_1(ConsoleEventArgs args)
		{
			List<MonsterAI> list = FindAllNecks();
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			int num5 = 0;
			int num6 = 0;
			foreach (MonsterAI item in list)
			{
				if ((Object)(object)item == (Object)null)
				{
					continue;
				}
				num++;
				bool flag = IsNeckTamed(item);
				bool flag2 = IsBabyNeck(((Component)item).gameObject);
				if (flag)
				{
					num2++;
					if (flag2)
					{
						num3++;
						num5++;
					}
					else if (NeckBreedingSystem.CanBreed(item))
					{
						num6++;
					}
				}
				else
				{
					num4++;
				}
			}
			args.Context.AddString($"Всего: {num}, Приручено: {num2}, Диких: {num4}");
			args.Context.AddString($"Никсёнков: {num3} (растут: {num5})");
			args.Context.AddString($"Взрослых готовых к размножению: {num6}");
			int num7 = 1;
			foreach (MonsterAI item2 in list)
			{
				if ((Object)(object)item2 != (Object)null && IsBabyNeck(((Component)item2).gameObject))
				{
					ZNetView component = ((Component)item2).GetComponent<ZNetView>();
					if ((Object)(object)component != (Object)null && component.IsValid())
					{
						float @float = component.GetZDO().GetFloat("neck_ageInDays", 0f);
						float float2 = component.GetZDO().GetFloat("neck_currentSize", 0.4f);
						float float3 = component.GetZDO().GetFloat("neck_growthProgress", 0f);
						long @long = component.GetZDO().GetLong("neck_bornTime", 0L);
						double num8 = (((Object)(object)ZNet.instance != (Object)null) ? ZNet.instance.GetTimeSeconds() : 0.0);
						double num9 = ((@long > 0) ? ((num8 - (double)@long) / 1800.0) : 0.0);
						double num10 = Math.Max(0.0, (double)GrowthDays.Value - num9);
						float num11 = float3 * 100f;
						args.Context.AddString($"Никсёнок {num7}: {num9:F2}/{GrowthDays.Value} дн. ({num11:F1}%) Размер: {float2:F2}");
						num7++;
					}
				}
			}
			if (num3 == 0)
			{
				args.Context.AddString("Нет растущих никсёнков");
			}
		}

		internal void <RegisterConsoleCommandsDirectly>b__38_4(ConsoleEventArgs args)
		{
			NeckBreedingSystem.UpdateBreeding();
			args.Context.AddString("Система размножения никсов обновлена!");
		}

		internal void <RegisterConsoleCommandsDirectly>b__38_5(ConsoleEventArgs args)
		{
			args.Context.AddString($"Система инициализирована: {_isInitialized}");
			args.Context.AddString($"ZNet доступен: {(Object)(object)ZNet.instance != (Object)null}");
			args.Context.AddString($"Серверный режим: {(Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer()}");
			List<MonsterAI> list = FindAllNecks();
			args.Context.AddString($"Всего никсов в мире: {list.Count}");
			int num = 0;
			foreach (MonsterAI item in list)
			{
				if ((Object)(object)item != (Object)null && IsBabyNeck(((Component)item).gameObject))
				{
					num++;
					ZNetView component = ((Component)item).GetComponent<ZNetView>();
					if ((Object)(object)component != (Object)null && component.IsValid())
					{
						double num2 = (((Object)(object)ZNet.instance != (Object)null) ? ZNet.instance.GetTimeSeconds() : 0.0);
						long @long = component.GetZDO().GetLong("neck_bornTime", 0L);
						float num3 = ((@long > 0) ? ((float)((num2 - (double)@long) / 1800.0)) : 0f);
						float @float = component.GetZDO().GetFloat("neck_currentSize", 0.4f);
						float float2 = component.GetZDO().GetFloat("neck_growthProgress", 0f);
						args.Context.AddString($"Никсёнок: возраст {num3:F2} дн., размер {@float:F2}, прогресс {float2:P0}");
					}
				}
			}
			args.Context.AddString($"Активных никсёнков: {num}");
		}
	}

	[CompilerGenerated]
	private sealed class <BreedingUpdateRoutine>d__27 : IEnumerator<object>, IDisposable, IEnumerator
	{
		private int <>1__state;

		private object <>2__current;

		public NeckTamingMod <>4__this;

		object IEnumerator<object>.Current
		{
			[DebuggerHidden]
			get
			{
				return <>2__current;
			}
		}

		object IEnumerator.Current
		{
			[DebuggerHidden]
			get
			{
				return <>2__current;
			}
		}

		[DebuggerHidden]
		public <BreedingUpdateRoutine>d__27(int <>1__state)
		{
			this.<>1__state = <>1__state;
		}

		[DebuggerHidden]
		void IDisposable.Dispose()
		{
			<>1__state = -2;
		}

		private bool MoveNext()
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			switch (<>1__state)
			{
			default:
				return false;
			case 0:
				<>1__state = -1;
				break;
			case 1:
				<>1__state = -1;
				if (_isInitialized && (Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer())
				{
					NeckBreedingSystem.UpdateBreeding();
				}
				break;
			}
			<>2__current = (object)new WaitForSeconds(60f);
			<>1__state = 1;
			return true;
		}

		bool IEnumerator.MoveNext()
		{
			//ILSpy generated this explicit interface implementation from .override directive in MoveNext
			return this.MoveNext();
		}

		[DebuggerHidden]
		void IEnumerator.Reset()
		{
			throw new NotSupportedException();
		}
	}

	[CompilerGenerated]
	private sealed class <DelayedInitialization>d__25 : IEnumerator<object>, IDisposable, IEnumerator
	{
		private int <>1__state;

		private object <>2__current;

		public NeckTamingMod <>4__this;

		object IEnumerator<object>.Current
		{
			[DebuggerHidden]
			get
			{
				return <>2__current;
			}
		}

		object IEnumerator.Current
		{
			[DebuggerHidden]
			get
			{
				return <>2__current;
			}
		}

		[DebuggerHidden]
		public <DelayedInitialization>d__25(int <>1__state)
		{
			this.<>1__state = <>1__state;
		}

		[DebuggerHidden]
		void IDisposable.Dispose()
		{
			<>1__state = -2;
		}

		private bool MoveNext()
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			switch (<>1__state)
			{
			default:
				return false;
			case 0:
				<>1__state = -1;
				<>2__current = (object)new WaitForSeconds(5f);
				<>1__state = 1;
				return true;
			case 1:
				<>1__state = -1;
				if (!_isInitialized)
				{
					InitializeSystem();
				}
				Debug.Log((object)"NeckTamingMod: Отложенная инициализация завершена");
				return false;
			}
		}

		bool IEnumerator.MoveNext()
		{
			//ILSpy generated this explicit interface implementation from .override directive in MoveNext
			return this.MoveNext();
		}

		[DebuggerHidden]
		void IEnumerator.Reset()
		{
			throw new NotSupportedException();
		}
	}

	[CompilerGenerated]
	private sealed class <GrowthUpdateRoutine>d__26 : IEnumerator<object>, IDisposable, IEnumerator
	{
		private int <>1__state;

		private object <>2__current;

		public NeckTamingMod <>4__this;

		object IEnumerator<object>.Current
		{
			[DebuggerHidden]
			get
			{
				return <>2__current;
			}
		}

		object IEnumerator.Current
		{
			[DebuggerHidden]
			get
			{
				return <>2__current;
			}
		}

		[DebuggerHidden]
		public <GrowthUpdateRoutine>d__26(int <>1__state)
		{
			this.<>1__state = <>1__state;
		}

		[DebuggerHidden]
		void IDisposable.Dispose()
		{
			<>1__state = -2;
		}

		private bool MoveNext()
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			switch (<>1__state)
			{
			default:
				return false;
			case 0:
				<>1__state = -1;
				break;
			case 1:
				<>1__state = -1;
				if (_isInitialized && (Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer())
				{
					<>4__this.UpdateAllNeckGrowth();
				}
				break;
			}
			<>2__current = (object)new WaitForSeconds(30f);
			<>1__state = 1;
			return true;
		}

		bool IEnumerator.MoveNext()
		{
			//ILSpy generated this explicit interface implementation from .override directive in MoveNext
			return this.MoveNext();
		}

		[DebuggerHidden]
		void IEnumerator.Reset()
		{
			throw new NotSupportedException();
		}
	}

	private readonly Harmony _harmony = new Harmony("com.yourname.necktaming");

	public static ConfigEntry<float> TameTime;

	public static ConfigEntry<float> FedDuration;

	public static ConfigEntry<string> ConsumableItems;

	public static ConfigEntry<float> GrowthDays;

	public static ConfigEntry<float> BreedChance;

	public static ConfigEntry<float> BreedCooldownDays;

	private static bool _isInitialized;

	private Coroutine _growthCoroutine;

	private Coroutine _breedingCoroutine;

	public const string ZDO_BABY = "neck_isBaby";

	public const string ZDO_BORN_TIME = "neck_bornTime";

	public const string ZDO_AGE_DAYS = "neck_ageInDays";

	public const string ZDO_CURRENT_SIZE = "neck_currentSize";

	public const string ZDO_GROWTH_COMPLETE = "neck_growthComplete";

	public const string ZDO_GROWTH_PROGRESS = "neck_growthProgress";

	public const string ZDO_NO_DROP = "neck_noDrop";

	public const string ZDO_LAST_BREED_TIME = "neck_lastBreedTime";

	public static NeckTamingMod Instance { get; private set; }

	private void Awake()
	{
		Instance = this;
		TameTime = ((BaseUnityPlugin)this).Config.Bind<float>("General", "TameTime", 1800f, "Время приручения никса в секундах (30 минут)");
		FedDuration = ((BaseUnityPlugin)this).Config.Bind<float>("General", "FedDuration", 400f, "Время сытости никса в секундах");
		ConsumableItems = ((BaseUnityPlugin)this).Config.Bind<string>("General", "ConsumableItems", "MeadTasty", "Предметы для приручения (через точку с запятой)");
		GrowthDays = ((BaseUnityPlugin)this).Config.Bind<float>("Growth", "GrowthDays", 3f, "Количество игровых суток для роста никсёнка");
		BreedChance = ((BaseUnityPlugin)this).Config.Bind<float>("Breeding", "BreedChance", 0.3f, "Шанс размножения при встрече (0-1)");
		BreedCooldownDays = ((BaseUnityPlugin)this).Config.Bind<float>("Breeding", "BreedCooldownDays", 2f, "Количество дней между возможностями размножения");
		RegisterConsoleCommandsDirectly();
		try
		{
			_harmony.PatchAll(typeof(ZNetScenePatches));
			_harmony.PatchAll(typeof(CharacterHoverPatches));
			_harmony.PatchAll(typeof(TameablePatches));
			_harmony.PatchAll(typeof(CharacterStatePatches));
			_harmony.PatchAll(typeof(PlayerPatches));
			_harmony.PatchAll(typeof(ZNetPatches));
			_harmony.PatchAll(typeof(CharacterDeathPatches));
			_harmony.PatchAll(typeof(MonsterAIPatches));
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Neck Taming Mod v1.0.0 loaded successfully!");
		}
		catch (Exception arg)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)$"Harmony patching completed with errors: {arg}");
		}
	}

	private void Start()
	{
		_growthCoroutine = ((MonoBehaviour)this).StartCoroutine(GrowthUpdateRoutine());
		_breedingCoroutine = ((MonoBehaviour)this).StartCoroutine(BreedingUpdateRoutine());
		((MonoBehaviour)this).StartCoroutine(DelayedInitialization());
	}

	private void OnDestroy()
	{
		Harmony harmony = _harmony;
		if (harmony != null)
		{
			harmony.UnpatchSelf();
		}
		if (_growthCoroutine != null)
		{
			((MonoBehaviour)this).StopCoroutine(_growthCoroutine);
		}
		if (_breedingCoroutine != null)
		{
			((MonoBehaviour)this).StopCoroutine(_breedingCoroutine);
		}
	}

	[IteratorStateMachine(typeof(<DelayedInitialization>d__25))]
	private IEnumerator DelayedInitialization()
	{
		//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
		return new <DelayedInitialization>d__25(0)
		{
			<>4__this = this
		};
	}

	[IteratorStateMachine(typeof(<GrowthUpdateRoutine>d__26))]
	private IEnumerator GrowthUpdateRoutine()
	{
		//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
		return new <GrowthUpdateRoutine>d__26(0)
		{
			<>4__this = this
		};
	}

	[IteratorStateMachine(typeof(<BreedingUpdateRoutine>d__27))]
	private IEnumerator BreedingUpdateRoutine()
	{
		//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
		return new <BreedingUpdateRoutine>d__27(0)
		{
			<>4__this = this
		};
	}

	public void UpdateAllNeckGrowth()
	{
		if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
		{
			return;
		}
		try
		{
			double timeSeconds = ZNet.instance.GetTimeSeconds();
			List<MonsterAI> list = FindAllNecks();
			int num = 0;
			foreach (MonsterAI item in list)
			{
				if ((Object)(object)item == (Object)null)
				{
					continue;
				}
				try
				{
					if (UpdateSingleNeckGrowth(((Component)item).gameObject, timeSeconds))
					{
						num++;
					}
				}
				catch (Exception ex)
				{
					Debug.LogError((object)("Ошибка роста никса " + ((Object)((Component)item).gameObject).name + ": " + ex.Message));
				}
			}
			if (num > 0)
			{
				Debug.Log((object)$"NeckTamingMod: Обновлен рост {num} никсов");
			}
		}
		catch (Exception ex2)
		{
			Debug.LogError((object)("Ошибка в системе роста: " + ex2.Message));
		}
	}

	private bool UpdateSingleNeckGrowth(GameObject neck, double currentTime)
	{
		ZNetView component = neck.GetComponent<ZNetView>();
		if ((Object)(object)component == (Object)null || !component.IsValid())
		{
			return false;
		}
		bool @bool = component.GetZDO().GetBool("neck_isBaby", false);
		bool bool2 = component.GetZDO().GetBool("neck_growthComplete", false);
		if (!@bool || bool2)
		{
			return false;
		}
		long num = component.GetZDO().GetLong("neck_bornTime", 0L);
		if (num == 0)
		{
			num = (long)currentTime;
			component.GetZDO().Set("neck_bornTime", num);
			Debug.Log((object)$"NeckTamingMod: Установлено время рождения никсёнка: {currentTime}");
		}
		double num2 = currentTime - (double)num;
		double num3 = num2 / 1800.0;
		component.GetZDO().Set("neck_ageInDays", (float)num3);
		float num4 = Mathf.Clamp01((float)num3 / GrowthDays.Value);
		float num5 = CalculateGrowthCurve(num4);
		float num6 = Mathf.Lerp(0.4f, 1f, num5);
		float @float = component.GetZDO().GetFloat("neck_currentSize", 0.4f);
		if (Mathf.Abs(num6 - @float) > 0.001f)
		{
			component.GetZDO().Set("neck_currentSize", num6);
			UpdateNeckSizeImmediate(neck, num6);
			float num7 = (num6 - 0.4f) / 0.6f;
			component.GetZDO().Set("neck_growthProgress", num7);
			Debug.Log((object)$"NeckTamingMod: Никсёнок растет: возраст {num3:F2}/{GrowthDays.Value} дней, размер {num6:F2}, прогресс {num7:P0}");
			if (num4 >= 0.999f)
			{
				CompleteNeckGrowth(neck, component);
				return true;
			}
			return true;
		}
		return false;
	}

	public void RestoreNeckState(GameObject neck)
	{
		//IL_0120: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)neck == (Object)null)
		{
			return;
		}
		ZNetView component = neck.GetComponent<ZNetView>();
		if ((Object)(object)component == (Object)null || !component.IsValid())
		{
			return;
		}
		bool @bool = component.GetZDO().GetBool("neck_isBaby", false);
		bool bool2 = component.GetZDO().GetBool("neck_growthComplete", false);
		bool bool3 = component.GetZDO().GetBool("neck_noDrop", false);
		if (@bool && !bool2)
		{
			float @float = component.GetZDO().GetFloat("neck_currentSize", 0.4f);
			UpdateNeckSizeImmediate(neck, @float);
			if (bool3)
			{
				DisableBabyNeckDrops(neck);
			}
			Debug.Log((object)$"NeckTamingMod: Состояние никсёнка восстановлено. Размер: {@float:F2}, isBaby: {@bool}, growthComplete: {bool2}");
		}
		else if (bool2)
		{
			neck.transform.localScale = Vector3.one;
			RestoreAdultNeckDrops(neck);
			Debug.Log((object)$"NeckTamingMod: Взрослый никс восстановлен. isBaby: {@bool}, growthComplete: {bool2}");
		}
		else
		{
			neck.transform.localScale = Vector3.one;
			Debug.Log((object)$"NeckTamingMod: Дикий никс восстановлен. isBaby: {@bool}, growthComplete: {bool2}");
		}
	}

	public void UpdateNeckSizeImmediate(GameObject neck, float newSize)
	{
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)neck == (Object)null)
		{
			return;
		}
		try
		{
			neck.transform.localScale = Vector3.one * newSize;
			Character component = neck.GetComponent<Character>();
			if ((Object)(object)component != (Object)null)
			{
				component.SetMaxHealth(component.GetMaxHealth());
			}
		}
		catch (Exception ex)
		{
			Debug.LogError((object)("Ошибка обновления размера никсёнка: " + ex.Message));
		}
	}

	private void CompleteNeckGrowth(GameObject neck, ZNetView znetView)
	{
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			neck.transform.localScale = Vector3.one;
			znetView.GetZDO().Set("neck_isBaby", false);
			znetView.GetZDO().Set("neck_currentSize", 1f);
			znetView.GetZDO().Set("neck_growthComplete", true);
			znetView.GetZDO().Set("neck_growthProgress", 1f);
			znetView.GetZDO().Set("neck_noDrop", false);
			RestoreAdultNeckDrops(neck);
			Debug.Log((object)"NeckTamingMod: Никсёнок полностью вырос во взрослого никса!");
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer != (Object)null)
			{
				((Character)localPlayer).Message((MessageType)2, "Никсёнок вырос во взрослого никса!", 0, (Sprite)null);
			}
		}
		catch (Exception ex)
		{
			Debug.LogError((object)("Ошибка завершения роста: " + ex.Message));
		}
	}

	public void RestoreAdultNeckDrops(GameObject neck)
	{
		try
		{
			CharacterDrop component = neck.GetComponent<CharacterDrop>();
			if (!((Object)(object)component != (Object)null))
			{
				return;
			}
			GameObject prefab = ZNetScene.instance.GetPrefab("Neck");
			if ((Object)(object)prefab != (Object)null)
			{
				CharacterDrop component2 = prefab.GetComponent<CharacterDrop>();
				if ((Object)(object)component2 != (Object)null && component2.m_drops != null)
				{
					component.m_drops = new List<Drop>(component2.m_drops);
					Debug.Log((object)"NeckTamingMod: Дроп восстановлен для взрослого никса");
				}
			}
		}
		catch (Exception ex)
		{
			Debug.LogError((object)("Ошибка восстановления дропа для взрослого никса: " + ex.Message));
		}
	}

	public void DisableBabyNeckDrops(GameObject neck)
	{
		try
		{
			CharacterDrop component = neck.GetComponent<CharacterDrop>();
			if ((Object)(object)component != (Object)null)
			{
				component.m_drops = new List<Drop>();
				Debug.Log((object)"NeckTamingMod: Дроп отключен для никсёнка");
			}
		}
		catch (Exception ex)
		{
			Debug.LogError((object)("Ошибка отключения дропа для никсёнка: " + ex.Message));
		}
	}

	private float CalculateGrowthCurve(float progress)
	{
		return progress * progress * (3f - 2f * progress);
	}

	public static void InitializeSystem()
	{
		if (!_isInitialized)
		{
			_isInitialized = true;
			if ((Object)(object)Instance != (Object)null)
			{
				Instance.RestoreAllBabyNecks();
			}
			Debug.Log((object)"NeckTamingMod: Система роста инициализирована");
		}
	}

	public void RestoreAllBabyNecks()
	{
		try
		{
			List<MonsterAI> list = FindAllNecks();
			int num = 0;
			foreach (MonsterAI item in list)
			{
				if ((Object)(object)item != (Object)null && (Object)(object)((Component)item).gameObject != (Object)null)
				{
					RestoreNeckState(((Component)item).gameObject);
					num++;
				}
			}
			Debug.Log((object)$"NeckTamingMod: Восстановлено состояние {num} никсов");
		}
		catch (Exception ex)
		{
			Debug.LogError((object)("Ошибка восстановления никсов: " + ex.Message));
		}
	}

	private void RegisterConsoleCommandsDirectly()
	{
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0025: Unknown result type (might be due to invalid IL or missing references)
		//IL_002b: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Expected O, but got Unknown
		//IL_0091: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bb: Expected O, but got Unknown
		//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
		//IL_0058: Unknown result type (might be due to invalid IL or missing references)
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: Expected O, but got Unknown
		//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_00da: Unknown result type (might be due to invalid IL or missing references)
		//IL_00df: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e5: Expected O, but got Unknown
		//IL_0126: Unknown result type (might be due to invalid IL or missing references)
		//IL_0112: Unknown result type (might be due to invalid IL or missing references)
		//IL_0117: Unknown result type (might be due to invalid IL or missing references)
		//IL_011d: Expected O, but got Unknown
		try
		{
			object obj = <>c.<>9__38_0;
			if (obj == null)
			{
				ConsoleEvent val = delegate(ConsoleEventArgs args)
				{
					//IL_0033: Unknown result type (might be due to invalid IL or missing references)
					//IL_0042: Unknown result type (might be due to invalid IL or missing references)
					//IL_004c: Unknown result type (might be due to invalid IL or missing references)
					//IL_0051: Unknown result type (might be due to invalid IL or missing references)
					//IL_0056: Unknown result type (might be due to invalid IL or missing references)
					//IL_005b: Unknown result type (might be due to invalid IL or missing references)
					//IL_0060: Unknown result type (might be due to invalid IL or missing references)
					//IL_007e: Unknown result type (might be due to invalid IL or missing references)
					//IL_007f: Unknown result type (might be due to invalid IL or missing references)
					if ((Object)(object)Player.m_localPlayer == (Object)null)
					{
						args.Context.AddString("Ошибка: игрок не найден!");
						return;
					}
					try
					{
						Vector3 val5 = ((Component)Player.m_localPlayer).transform.position + ((Component)Player.m_localPlayer).transform.forward * 3f + Vector3.up;
						GameObject prefab = ZNetScene.instance.GetPrefab("Neck");
						if ((Object)(object)prefab != (Object)null)
						{
							GameObject neck = Object.Instantiate<GameObject>(prefab, val5, Quaternion.identity);
							MakeBabyNeck(neck);
							args.Context.AddString("Никсёнок создан!");
						}
						else
						{
							args.Context.AddString("Ошибка: префаб никса не найден!");
						}
					}
					catch (Exception ex2)
					{
						Debug.LogError((object)$"Ошибка создания никсёнка: {ex2}");
						args.Context.AddString("Ошибка: " + ex2.Message);
					}
				};
				<>c.<>9__38_0 = val;
				obj = (object)val;
			}
			new ConsoleCommand("spawnbabyneck", "Создает никсёнка", (ConsoleEvent)obj, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
			object obj2 = <>c.<>9__38_1;
			if (obj2 == null)
			{
				ConsoleEvent val2 = delegate(ConsoleEventArgs args)
				{
					List<MonsterAI> list3 = FindAllNecks();
					int num5 = 0;
					int num6 = 0;
					int num7 = 0;
					int num8 = 0;
					int num9 = 0;
					int num10 = 0;
					foreach (MonsterAI item in list3)
					{
						if (!((Object)(object)item == (Object)null))
						{
							num5++;
							bool flag = IsNeckTamed(item);
							bool flag2 = IsBabyNeck(((Component)item).gameObject);
							if (flag)
							{
								num6++;
								if (flag2)
								{
									num7++;
									num9++;
								}
								else if (NeckBreedingSystem.CanBreed(item))
								{
									num10++;
								}
							}
							else
							{
								num8++;
							}
						}
					}
					args.Context.AddString($"Всего: {num5}, Приручено: {num6}, Диких: {num8}");
					args.Context.AddString($"Никсёнков: {num7} (растут: {num9})");
					args.Context.AddString($"Взрослых готовых к размножению: {num10}");
					int num11 = 1;
					foreach (MonsterAI item2 in list3)
					{
						if ((Object)(object)item2 != (Object)null && IsBabyNeck(((Component)item2).gameObject))
						{
							ZNetView component3 = ((Component)item2).GetComponent<ZNetView>();
							if ((Object)(object)component3 != (Object)null && component3.IsValid())
							{
								float float3 = component3.GetZDO().GetFloat("neck_ageInDays", 0f);
								float float4 = component3.GetZDO().GetFloat("neck_currentSize", 0.4f);
								float float5 = component3.GetZDO().GetFloat("neck_growthProgress", 0f);
								long long2 = component3.GetZDO().GetLong("neck_bornTime", 0L);
								double num12 = (((Object)(object)ZNet.instance != (Object)null) ? ZNet.instance.GetTimeSeconds() : 0.0);
								double num13 = ((long2 > 0) ? ((num12 - (double)long2) / 1800.0) : 0.0);
								double num14 = Math.Max(0.0, (double)GrowthDays.Value - num13);
								float num15 = float5 * 100f;
								args.Context.AddString($"Никсёнок {num11}: {num13:F2}/{GrowthDays.Value} дн. ({num15:F1}%) Размер: {float4:F2}");
								num11++;
							}
						}
					}
					if (num7 == 0)
					{
						args.Context.AddString("Нет растущих никсёнков");
					}
				};
				<>c.<>9__38_1 = val2;
				obj2 = (object)val2;
			}
			new ConsoleCommand("neckinfo", "Информация о никсах", (ConsoleEvent)obj2, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
			new ConsoleCommand("forcegrownecks", "Мгновенно вырастить всех никсёнков", (ConsoleEvent)delegate(ConsoleEventArgs args)
			{
				int num4 = 0;
				List<MonsterAI> list2 = FindAllNecks();
				foreach (MonsterAI item3 in list2)
				{
					if (!((Object)(object)item3 == (Object)null))
					{
						try
						{
							if (IsBabyNeck(((Component)item3).gameObject))
							{
								ZNetView component2 = ((Component)item3).GetComponent<ZNetView>();
								if ((Object)(object)component2 != (Object)null && component2.IsValid())
								{
									CompleteNeckGrowth(((Component)item3).gameObject, component2);
									num4++;
								}
							}
						}
						catch (Exception ex)
						{
							Debug.LogError((object)("Error growing baby neck: " + ex.Message));
						}
					}
				}
				args.Context.AddString($"Мгновенно выращено {num4} никсёнков!");
			}, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
			new ConsoleCommand("neckgrowthupdate", "Принудительно обновить систему роста", (ConsoleEvent)delegate(ConsoleEventArgs args)
			{
				UpdateAllNeckGrowth();
				args.Context.AddString("Система роста никсов обновлена!");
			}, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
			object obj3 = <>c.<>9__38_4;
			if (obj3 == null)
			{
				ConsoleEvent val3 = delegate(ConsoleEventArgs args)
				{
					NeckBreedingSystem.UpdateBreeding();
					args.Context.AddString("Система размножения никсов обновлена!");
				};
				<>c.<>9__38_4 = val3;
				obj3 = (object)val3;
			}
			new ConsoleCommand("neckbreedingupdate", "Принудительно обновить систему размножения", (ConsoleEvent)obj3, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
			object obj4 = <>c.<>9__38_5;
			if (obj4 == null)
			{
				ConsoleEvent val4 = delegate(ConsoleEventArgs args)
				{
					args.Context.AddString($"Система инициализирована: {_isInitialized}");
					args.Context.AddString($"ZNet доступен: {(Object)(object)ZNet.instance != (Object)null}");
					args.Context.AddString($"Серверный режим: {(Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer()}");
					List<MonsterAI> list = FindAllNecks();
					args.Context.AddString($"Всего никсов в мире: {list.Count}");
					int num = 0;
					foreach (MonsterAI item4 in list)
					{
						if ((Object)(object)item4 != (Object)null && IsBabyNeck(((Component)item4).gameObject))
						{
							num++;
							ZNetView component = ((Component)item4).GetComponent<ZNetView>();
							if ((Object)(object)component != (Object)null && component.IsValid())
							{
								double num2 = (((Object)(object)ZNet.instance != (Object)null) ? ZNet.instance.GetTimeSeconds() : 0.0);
								long @long = component.GetZDO().GetLong("neck_bornTime", 0L);
								float num3 = ((@long > 0) ? ((float)((num2 - (double)@long) / 1800.0)) : 0f);
								float @float = component.GetZDO().GetFloat("neck_currentSize", 0.4f);
								float float2 = component.GetZDO().GetFloat("neck_growthProgress", 0f);
								args.Context.AddString($"Никсёнок: возраст {num3:F2} дн., размер {@float:F2}, прогресс {float2:P0}");
							}
						}
					}
					args.Context.AddString($"Активных никсёнков: {num}");
				};
				<>c.<>9__38_5 = val4;
				obj4 = (object)val4;
			}
			new ConsoleCommand("neckdiagnostic", "Диагностика системы роста", (ConsoleEvent)obj4, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"NeckTamingMod: Консольные команды успешно зарегистрированы!");
		}
		catch (Exception arg)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)$"Ошибка регистрации команд: {arg}");
		}
	}

	public static bool IsNeckTamed(MonsterAI neck)
	{
		if ((Object)(object)neck == (Object)null)
		{
			return false;
		}
		try
		{
			if (GetPrivateField<bool>(neck, "m_tamed"))
			{
				return true;
			}
			ZNetView component = ((Component)neck).GetComponent<ZNetView>();
			if ((Object)(object)component != (Object)null && component.IsValid())
			{
				return component.GetZDO().GetBool("tamed", false);
			}
		}
		catch (Exception ex)
		{
			Debug.LogError((object)("Ошибка проверки приручения: " + ex.Message));
		}
		return false;
	}

	public static bool IsBabyNeck(GameObject neck)
	{
		if ((Object)(object)neck == (Object)null)
		{
			return false;
		}
		ZNetView component = neck.GetComponent<ZNetView>();
		if ((Object)(object)component != (Object)null && component.IsValid())
		{
			bool @bool = component.GetZDO().GetBool("neck_isBaby", false);
			bool bool2 = component.GetZDO().GetBool("neck_growthComplete", false);
			return @bool && !bool2;
		}
		return false;
	}

	public static T GetPrivateField<T>(object obj, string fieldName)
	{
		if (obj == null)
		{
			return default(T);
		}
		FieldInfo field = obj.GetType().GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);
		return (field != null) ? ((T)field.GetValue(obj)) : default(T);
	}

	public static void SetPrivateField(object obj, string fieldName, object value)
	{
		if (obj != null)
		{
			FieldInfo field = obj.GetType().GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);
			if (field != null && value != null && field.FieldType == value.GetType())
			{
				field.SetValue(obj, value);
			}
		}
	}

	public static List<MonsterAI> FindAllNecks()
	{
		List<MonsterAI> list = new List<MonsterAI>();
		MonsterAI[] array = Object.FindObjectsByType<MonsterAI>((FindObjectsSortMode)0);
		MonsterAI[] array2 = array;
		foreach (MonsterAI val in array2)
		{
			if ((Object)(object)val != (Object)null && (Object)(object)((Component)val).gameObject != (Object)null)
			{
				string text = ((Object)((Component)val).gameObject).name.ToLower();
				if (text.Contains("neck") && !text.Contains("bear"))
				{
					list.Add(val);
				}
			}
		}
		return list;
	}

	public static void MakeBabyNeck(GameObject neck)
	{
		//IL_003c: 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)neck == (Object)null)
		{
			return;
		}
		try
		{
			double num = (((Object)(object)ZNet.instance != (Object)null) ? ZNet.instance.GetTimeSeconds() : 0.0);
			neck.transform.localScale = Vector3.one * 0.4f;
			Character component = neck.GetComponent<Character>();
			if ((Object)(object)component != (Object)null)
			{
				component.SetTamed(true);
				component.SetLevel(1);
				Instance.DisableBabyNeckDrops(neck);
			}
			MonsterAI component2 = neck.GetComponent<MonsterAI>();
			if ((Object)(object)component2 != (Object)null)
			{
				SetPrivateField(component2, "m_tamed", true);
				SetPrivateField(component2, "m_tamable", true);
				SetPrivateField(component2, "m_commandable", true);
				SetPrivateField(component2, "m_tameTimer", TameTime.Value);
			}
			Tameable component3 = neck.GetComponent<Tameable>();
			if ((Object)(object)component3 != (Object)null)
			{
				SetPrivateField(component3, "m_tamed", true);
				SetPrivateField(component3, "m_timeSinceFeeding", 0f);
			}
			ZNetView component4 = neck.GetComponent<ZNetView>();
			if ((Object)(object)component4 != (Object)null && component4.IsValid())
			{
				component4.GetZDO().Set("tamed", true);
				component4.GetZDO().Set("neck_isBaby", true);
				component4.GetZDO().Set("neck_bornTime", (long)num);
				component4.GetZDO().Set("neck_ageInDays", 0f);
				component4.GetZDO().Set("neck_currentSize", 0.4f);
				component4.GetZDO().Set("neck_growthComplete", false);
				component4.GetZDO().Set("neck_growthProgress", 0f);
				component4.GetZDO().Set("neck_noDrop", true);
			}
			Debug.Log((object)$"NeckTamingMod: Прирученный никсёнок создан! Время рождения: {num}");
		}
		catch (Exception ex)
		{
			Debug.LogError((object)("Ошибка создания никсёнка: " + ex.Message));
		}
	}
}
[HarmonyPatch(typeof(Player))]
public static class PlayerPatches
{
	[HarmonyPatch("OnSpawned")]
	[HarmonyPostfix]
	private static void OnPlayerSpawned(Player __instance)
	{
		if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer)
		{
			NeckTamingMod.InitializeSystem();
			Debug.Log((object)"NeckTamingMod: Игрок заспавнен, система роста активирована");
			if ((Object)(object)NeckTamingMod.Instance != (Object)null)
			{
				NeckTamingMod.Instance.RestoreAllBabyNecks();
			}
		}
	}
}
[HarmonyPatch(typeof(ZNet))]
public static class ZNetPatches
{
	[HarmonyPatch("OnWorldLoad")]
	[HarmonyPostfix]
	private static void OnWorldLoad(ZNet __instance)
	{
		if (__instance.IsServer())
		{
			NeckTamingMod.InitializeSystem();
			Debug.Log((object)"NeckTamingMod: Мир загружен, запущено восстановление никсёнков");
		}
	}
}
[HarmonyPatch(typeof(Tameable))]
public static class TameablePatches
{
	[HarmonyPatch("GetHoverText")]
	[HarmonyPostfix]
	private static void OnHoverText(Tameable __instance, ref string __result)
	{
		if ((Object)(object)NeckTamingMod.Instance != (Object)null && (Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer())
		{
			NeckTamingMod.Instance.UpdateAllNeckGrowth();
		}
		if (!((Object)(object)__instance != (Object)null))
		{
			return;
		}
		string text = ((Object)((Component)__instance).gameObject).name.ToLower();
		if (!text.Contains("neck"))
		{
			return;
		}
		bool privateField = NeckTamingMod.GetPrivateField<bool>(__instance, "m_tamed");
		if (!privateField)
		{
			MonsterAI component = ((Component)__instance).GetComponent<MonsterAI>();
			if ((Object)(object)component != (Object)null)
			{
				if (NeckTamingMod.GetPrivateField<bool>(component, "m_afraid"))
				{
					__result += "\n<color=orange>Боится</color>";
				}
				else
				{
					__result += "\n<color=yellow>Дикий</color>";
				}
			}
		}
		if (privateField && NeckTamingMod.IsBabyNeck(((Component)__instance).gameObject))
		{
			ZNetView component2 = ((Component)__instance).GetComponent<ZNetView>();
			if ((Object)(object)component2 != (Object)null && component2.IsValid())
			{
				float @float = component2.GetZDO().GetFloat("neck_currentSize", 0.4f);
				float float2 = component2.GetZDO().GetFloat("neck_ageInDays", 0f);
				long @long = component2.GetZDO().GetLong("neck_bornTime", 0L);
				float float3 = component2.GetZDO().GetFloat("neck_growthProgress", 0f);
				double num = (((Object)(object)ZNet.instance != (Object)null) ? ZNet.instance.GetTimeSeconds() : 0.0);
				double num2 = ((@long > 0) ? ((num - (double)@long) / 1800.0) : 0.0);
				double num3 = Math.Max(0.0, (double)NeckTamingMod.GrowthDays.Value - num2);
				float num4 = float3 * 100f;
				__result += $"\n(Растет: {num4:F1}%, {num3:F1} дн. осталось)";
				__result += $"\n(Размер: {@float:F2}, возраст: {num2:F2} дн.)";
			}
		}
		else if (privateField && !NeckTamingMod.IsBabyNeck(((Component)__instance).gameObject))
		{
			MonsterAI component3 = ((Component)__instance).GetComponent<MonsterAI>();
			if ((Object)(object)component3 != (Object)null && NeckBreedingSystem.CanBreed(component3))
			{
				__result += "\n(Готов к размножению)";
			}
		}
	}

	[HarmonyPatch("Interact")]
	[HarmonyPrefix]
	private static bool HandlePetCommand(Tameable __instance, Humanoid user, bool hold, bool alt)
	{
		if (hold || alt)
		{
			return true;
		}
		string text = ((Object)((Component)__instance).gameObject).name.ToLower();
		if (!text.Contains("neck"))
		{
			return true;
		}
		try
		{
			if (NeckTamingMod.GetPrivateField<bool>(__instance, "m_tamed"))
			{
				MonsterAI component = ((Component)__instance).GetComponent<MonsterAI>();
				if ((Object)(object)component != (Object)null)
				{
					bool privateField = NeckTamingMod.GetPrivateField<bool>(component, "m_follow");
					NeckTamingMod.SetPrivateField(component, "m_follow", !privateField);
					if (!privateField)
					{
						((Character)user).Message((MessageType)2, "$hud_animal_follow", 0, (Sprite)null);
					}
					else
					{
						((Character)user).Message((MessageType)2, "$hud_animal_stay", 0, (Sprite)null);
					}
					return false;
				}
			}
		}
		catch (Exception ex)
		{
			Debug.LogError((object)("Ошибка обработки команды приласкать: " + ex.Message));
		}
		return true;
	}
}
[HarmonyPatch(typeof(ZNetScene))]
public static class ZNetScenePatches
{
	private static bool _prefabsInitialized;

	[HarmonyPatch("Awake")]
	[HarmonyPostfix]
	private static void SetupNeckPrefab(ZNetScene __instance)
	{
		if (_prefabsInitialized)
		{
			return;
		}
		try
		{
			GameObject prefab = __instance.GetPrefab("Neck");
			if ((Object)(object)prefab == (Object)null)
			{
				Debug.LogError((object)"NeckTamingMod: Префаб никса не найден!");
				return;
			}
			SetupNeckTameable(prefab);
			_prefabsInitialized = true;
			Debug.Log((object)"NeckTamingMod: Настройка префаба никса завершена!");
		}
		catch (Exception arg)
		{
			Debug.LogError((object)$"Ошибка настройка префаба никса: {arg}");
		}
	}

	private static void SetupNeckTameable(GameObject neckPrefab)
	{
		Tameable val = neckPrefab.GetComponent<Tameable>();
		if ((Object)(object)val == (Object)null)
		{
			val = neckPrefab.AddComponent<Tameable>();
			Debug.Log((object)"NeckTamingMod: Добавлен компонент Tameable к никсy");
		}
		val.m_tamingTime = NeckTamingMod.TameTime.Value;
		val.m_fedDuration = NeckTamingMod.FedDuration.Value;
		val.m_commandable = true;
		MonsterAI component = neckPrefab.GetComponent<MonsterAI>();
		if ((Object)(object)component != (Object)null)
		{
			NeckTamingMod.SetPrivateField(component, "m_tamable", true);
			NeckTamingMod.SetPrivateField(component, "m_tamingTime", NeckTamingMod.TameTime.Value);
			SetupConsumableItems(component);
			Debug.Log((object)"NeckTamingMod: Настроен MonsterAI для никса");
		}
		else
		{
			Debug.LogError((object)"NeckTamingMod: У префаба никса нет компонента MonsterAI!");
		}
	}

	private static void SetupConsumableItems(MonsterAI neckAI)
	{
		if (neckAI.m_consumeItems == null)
		{
			neckAI.m_consumeItems = new List<ItemDrop>();
		}
		else
		{
			neckAI.m_consumeItems.Clear();
		}
		string[] array = NeckTamingMod.ConsumableItems.Value.Split(new char[1] { ';' });
		string[] array2 = array;
		foreach (string text in array2)
		{
			string text2 = text.Trim();
			if (!string.IsNullOrEmpty(text2))
			{
				AddConsumableItem(neckAI, text2);
			}
		}
		if (neckAI.m_consumeItems == null || neckAI.m_consumeItems.Count == 0)
		{
			AddConsumableItem(neckAI, "MeadTasty");
			Debug.Log((object)"NeckTamingMod: Добавлен предмет по умолчанию: MeadTasty");
		}
	}

	private static void AddConsumableItem(MonsterAI neckAI, string itemName)
	{
		GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(itemName);
		if ((Object)(object)itemPrefab != (Object)null)
		{
			ItemDrop component = itemPrefab.GetComponent<ItemDrop>();
			if ((Object)(object)component != (Object)null)
			{
				neckAI.m_consumeItems.Add(component);
				Debug.Log((object)("NeckTamingMod: Добавлен предмет для приручения: " + itemName));
			}
			else
			{
				Debug.LogError((object)("NeckTamingMod: У предмета " + itemName + " нет компонента ItemDrop"));
			}
		}
		else
		{
			Debug.LogError((object)("NeckTamingMod: Не удалось найти предмет: " + itemName));
		}
	}
}
[HarmonyPatch(typeof(Character))]
public static class CharacterHoverPatches
{
	[HarmonyPatch("GetHoverName")]
	[HarmonyPostfix]
	private static void ModifyNeckHoverName(Character __instance, ref string __result)
	{
		if ((Object)(object)__instance == (Object)null)
		{
			return;
		}
		string text = ((Object)((Component)__instance).gameObject).name.ToLower();
		if (!text.Contains("neck"))
		{
			return;
		}
		try
		{
			MonsterAI component = ((Component)__instance).GetComponent<MonsterAI>();
			if (!((Object)(object)component == (Object)null))
			{
				bool flag = NeckTamingMod.IsNeckTamed(component);
				if (NeckTamingMod.IsBabyNeck(((Component)__instance).gameObject))
				{
					__result = "Никсёнок";
				}
				else if (flag)
				{
					__result = "Прирученный никс";
				}
				else
				{
					__result = "Никс";
				}
			}
		}
		catch (Exception ex)
		{
			Debug.LogError((object)("Ошибка изменения имени никса: " + ex.Message));
		}
	}
}
[HarmonyPatch(typeof(Character))]
public static class CharacterStatePatches
{
	[HarmonyPatch("Start")]
	[HarmonyPostfix]
	private static void RestoreNeckState(Character __instance)
	{
		if ((Object)(object)__instance == (Object)null || (Object)(object)((Component)__instance).gameObject == (Object)null)
		{
			return;
		}
		string text = ((Object)((Component)__instance).gameObject).name.ToLower();
		if (!text.Contains("neck"))
		{
			return;
		}
		try
		{
			NeckTamingMod.Instance.RestoreNeckState(((Component)__instance).gameObject);
		}
		catch (Exception ex)
		{
			Debug.LogError((object)("Ошибка восстановления состояния никса: " + ex.Message));
		}
	}
}
[HarmonyPatch(typeof(Character))]
public static class CharacterDeathPatches
{
	[HarmonyPatch("OnDeath")]
	[HarmonyPrefix]
	private static void OnDeathPrefix(Character __instance)
	{
		if ((Object)(object)__instance == (Object)null)
		{
			return;
		}
		string text = ((Object)((Component)__instance).gameObject).name.ToLower();
		if (!text.Contains("neck"))
		{
			return;
		}
		try
		{
			if (NeckTamingMod.IsBabyNeck(((Component)__instance).gameObject))
			{
				NeckTamingMod.Instance.DisableBabyNeckDrops(((Component)__instance).gameObject);
				Debug.Log((object)"NeckTamingMod: Дроп отключен для убитого никсёнка");
			}
			else
			{
				NeckTamingMod.Instance.RestoreAdultNeckDrops(((Component)__instance).gameObject);
			}
		}
		catch (Exception ex)
		{
			Debug.LogError((object)("Ошибка обработки смерти никса: " + ex.Message));
		}
	}
}
[HarmonyPatch(typeof(MonsterAI))]
public static class MonsterAIPatches
{
	[HarmonyPatch("Awake")]
	[HarmonyPostfix]
	private static void OnMonsterAIStart(MonsterAI __instance)
	{
		if ((Object)(object)__instance == (Object)null || (Object)(object)((Component)__instance).gameObject == (Object)null)
		{
			return;
		}
		string text = ((Object)((Component)__instance).gameObject).name.ToLower();
		if (!text.Contains("neck"))
		{
			return;
		}
		try
		{
			NeckTamingMod.Instance?.RestoreNeckState(((Component)__instance).gameObject);
		}
		catch (Exception ex)
		{
			Debug.LogError((object)("Ошибка восстановления состояния никса в MonsterAI: " + ex.Message));
		}
	}
}
public static class NeckBreedingSystem
{
	public static Dictionary<GameObject, long> _lastBreedTimes = new Dictionary<GameObject, long>();

	private const float MIN_BREED_DISTANCE = 3f;

	private const float MAX_BREED_DISTANCE = 10f;

	private const float REQUIRED_FULLNESS = 0.7f;

	public static void UpdateBreeding()
	{
		try
		{
			List<MonsterAI> list = NeckTamingMod.FindAllNecks();
			List<MonsterAI> list2 = new List<MonsterAI>();
			foreach (MonsterAI item in list)
			{
				if (!((Object)(object)item == (Object)null) && NeckTamingMod.IsNeckTamed(item) && !NeckTamingMod.IsBabyNeck(((Component)item).gameObject) && CanBreed(item))
				{
					list2.Add(item);
				}
			}
			if (list2.Count < 2)
			{
				return;
			}
			for (int i = 0; i < list2.Count; i++)
			{
				for (int j = i + 1; j < list2.Count; j++)
				{
					if (CheckBreedingPair(list2[i], list2[j]))
					{
						return;
					}
				}
			}
		}
		catch (Exception ex)
		{
			Debug.LogError((object)("Ошибка в системе размножения: " + ex.Message));
		}
	}

	private static bool CheckBreedingPair(MonsterAI neck1, MonsterAI neck2)
	{
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)neck1 == (Object)null || (Object)(object)neck2 == (Object)null)
		{
			return false;
		}
		if (!CanNeckBreedNow(neck1) || !CanNeckBreedNow(neck2))
		{
			return false;
		}
		float num = Vector3.Distance(((Component)neck1).transform.position, ((Component)neck2).transform.position);
		if (num < 3f || num > 10f)
		{
			return false;
		}
		if (Random.Range(0f, 1f) > NeckTamingMod.BreedChance.Value)
		{
			return false;
		}
		Debug.Log((object)"NeckTamingMod: Успешная проверка размножения - создаем никсёнка");
		SpawnBabyNeck(neck1, neck2);
		SetBreedCooldown(neck1);
		SetBreedCooldown(neck2);
		return true;
	}

	public static bool CanNeckBreedNow(MonsterAI neck)
	{
		if ((Object)(object)neck == (Object)null)
		{
			return false;
		}
		if (_lastBreedTimes.ContainsKey(((Component)neck).gameObject))
		{
			long num = _lastBreedTimes[((Component)neck).gameObject];
			long num2 = (long)ZNet.instance.GetTimeSeconds();
			long num3 = (long)(NeckTamingMod.BreedCooldownDays.Value * 1800f);
			long num4 = num2 - num;
			if (num4 < num3)
			{
				return false;
			}
		}
		return true;
	}

	private static void SetBreedCooldown(MonsterAI neck)
	{
		if ((Object)(object)neck != (Object)null)
		{
			long num = (long)ZNet.instance.GetTimeSeconds();
			_lastBreedTimes[((Component)neck).gameObject] = num;
			ZNetView component = ((Component)neck).GetComponent<ZNetView>();
			if ((Object)(object)component != (Object)null && component.IsValid())
			{
				component.GetZDO().Set("neck_lastBreedTime", num);
			}
		}
	}

	public static bool CanBreed(MonsterAI neck)
	{
		if ((Object)(object)neck == (Object)null)
		{
			return false;
		}
		Tameable component = ((Component)neck).GetComponent<Tameable>();
		if ((Object)(object)component != (Object)null)
		{
			float privateField = NeckTamingMod.GetPrivateField<float>(component, "m_timeSinceFeeding");
			if (privateField > component.m_fedDuration * 0.7f)
			{
				return false;
			}
		}
		if (NeckTamingMod.IsBabyNeck(((Component)neck).gameObject))
		{
			return false;
		}
		return true;
	}

	private static void SpawnBabyNeck(MonsterAI parent1, MonsterAI parent2)
	{
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		//IL_006f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0070: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			Vector3 val = (((Component)parent1).transform.position + ((Component)parent2).transform.position) / 2f;
			val += Vector3.up * 0.5f + Random.insideUnitSphere * 1f;
			GameObject prefab = ZNetScene.instance.GetPrefab("Neck");
			if ((Object)(object)prefab != (Object)null)
			{
				GameObject neck = Object.Instantiate<GameObject>(prefab, val, Quaternion.identity);
				NeckTamingMod.MakeBabyNeck(neck);
				Player localPlayer = Player.m_localPlayer;
				if ((Object)(object)localPlayer != (Object)null)
				{
					((Character)localPlayer).Message((MessageType)2, "Никсы произвели потомство!", 0, (Sprite)null);
				}
				Debug.Log((object)"NeckTamingMod: Новый прирученный никсёнок появился через размножение!");
			}
			else
			{
				Debug.LogError((object)"NeckTamingMod: Не удалось найти префаб никса для размножения");
			}
		}
		catch (Exception ex)
		{
			Debug.LogError((object)("Ошибка создания никсёнка: " + ex.Message));
		}
	}
}