Decompiled source of Arboriculteur v1.0.0

plugins/Arboriculteur.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("Arboriculteur")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+e9dcccf63988cad4c0bcddcd668edddb0e538496")]
[assembly: AssemblyProduct("Arboriculteur")]
[assembly: AssemblyTitle("Arboriculteur")]
[assembly: AssemblyVersion("1.0.0.0")]
[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 Arboriculteur
{
	internal enum Habitat
	{
		Soil,
		OpenSoil,
		StoneShelter,
		Ashlands,
		Cold
	}
	internal sealed class CropSpec
	{
		internal string Source { get; }

		internal string Boss { get; }

		internal GlobalKeys Key { get; }

		internal Habitat Habitat { get; }

		internal float Spacing { get; }

		internal int Cost { get; }

		internal int Yield { get; }

		internal int FirstDays { get; }

		internal int RegrowDays { get; }

		internal bool IsMushroom => Habitat == Habitat.StoneShelter;

		internal bool IsBush => Source.EndsWith("Bush", StringComparison.Ordinal);

		internal CropSpec(string source, string boss, GlobalKeys key, Habitat habitat, float spacing, int cost, int yield, int firstDays, int regrowDays)
		{
			//IL_0015: 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)
			Source = source;
			Boss = boss;
			Key = key;
			Habitat = habitat;
			Spacing = spacing;
			Cost = cost;
			Yield = yield;
			FirstDays = firstDays;
			RegrowDays = regrowDays;
		}
	}
	internal static class Catalog
	{
		internal static readonly CropSpec[] Crops = new CropSpec[10]
		{
			new CropSpec("RaspberryBush", "Eikthyr", (GlobalKeys)42, Habitat.OpenSoil, 1.5f, 3, 2, 3, 4),
			new CropSpec("Pickable_Mushroom", "Eikthyr", (GlobalKeys)42, Habitat.StoneShelter, 0.8f, 1, 1, 2, 0),
			new CropSpec("Pickable_Dandelion", "Eikthyr", (GlobalKeys)42, Habitat.Soil, 0.6f, 2, 1, 2, 2),
			new CropSpec("BlueberryBush", "The Elder", (GlobalKeys)45, Habitat.Soil, 1.5f, 3, 2, 3, 4),
			new CropSpec("Pickable_Mushroom_yellow", "The Elder", (GlobalKeys)45, Habitat.StoneShelter, 0.8f, 1, 1, 3, 0),
			new CropSpec("Pickable_Thistle", "The Elder", (GlobalKeys)45, Habitat.Soil, 0.8f, 2, 1, 3, 3),
			new CropSpec("CloudberryBush", "Yagluth", (GlobalKeys)44, Habitat.OpenSoil, 1.2f, 3, 2, 3, 4),
			new CropSpec("Pickable_Fiddlehead", "Fader", (GlobalKeys)48, Habitat.Ashlands, 1f, 2, 1, 3, 3),
			new CropSpec("Pickable_SmokePuff", "Fader", (GlobalKeys)48, Habitat.StoneShelter, 0.8f, 1, 1, 3, 0),
			new CropSpec("LingonberryBush", "Kall Fimbulbringer", (GlobalKeys)49, Habitat.Cold, 1.2f, 3, 2, 4, 5)
		};
	}
	internal static class CropCycle
	{
		internal const int Finished = -1;

		internal static int ReadyMask(int count)
		{
			return (1 << count) - 1;
		}

		internal static bool CanPick(int mask, int slot)
		{
			if (mask > 0 && slot >= 0 && slot < 3)
			{
				return (mask & (1 << slot)) != 0;
			}
			return false;
		}

		internal static int Pick(int mask, int slot)
		{
			return mask & ~(1 << slot);
		}

		internal static long TimeLeft(long due, long now, long pausedAt)
		{
			return Math.Max(0L, due - ((pausedAt > 0) ? pausedAt : now));
		}

		internal static long Resume(long due, long now, long pausedAt)
		{
			return now + TimeLeft(due, now, pausedAt);
		}
	}
	internal static class CropPlacement
	{
		[HarmonyPatch(typeof(Hud), "SetupPieceInfo")]
		private static class ShowBossInCultivator
		{
			private static void Postfix(Hud __instance, Piece piece)
			{
				PlantedCrop plantedCrop = default(PlantedCrop);
				if (Object.op_Implicit((Object)(object)piece) && ((Component)piece).TryGetComponent<PlantedCrop>(ref plantedCrop))
				{
					string text = BossProblem(plantedCrop.Spec);
					if (text != null)
					{
						TMP_Text pieceDescription = __instance.m_pieceDescription;
						pieceDescription.text = pieceDescription.text + "\n" + text;
					}
				}
			}
		}

		[HarmonyPatch(typeof(Player), "UpdatePlacementGhost")]
		private static class ValidatePreview
		{
			private static void Postfix(Player __instance, GameObject ___m_placementGhost, ref PlacementStatus ___m_placementStatus)
			{
				PlantedCrop ghost = default(PlantedCrop);
				if ((int)___m_placementStatus == 0 && Object.op_Implicit((Object)(object)___m_placementGhost) && ___m_placementGhost.TryGetComponent<PlantedCrop>(ref ghost) && Problem(ghost) != null)
				{
					___m_placementStatus = (PlacementStatus)1;
					SetGhostValid(__instance, arg2: false);
				}
			}

			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{
				MethodInfo noBuild = AccessTools.Method(typeof(Location), "IsInsideNoBuildLocation", (Type[])null, (Type[])null);
				MethodInfo check = AccessTools.Method(typeof(CropPlacement), "IsNoBuildLocation", (Type[])null, (Type[])null);
				foreach (CodeInstruction instruction in instructions)
				{
					if (CodeInstructionExtensions.Calls(instruction, noBuild))
					{
						CodeInstruction val = new CodeInstruction(OpCodes.Ldarg_0, (object)null);
						val.labels.AddRange(instruction.labels);
						instruction.labels.Clear();
						yield return val;
						instruction.operand = check;
					}
					yield return instruction;
				}
			}
		}

		[HarmonyPatch(typeof(Player), "TryPlacePiece")]
		private static class ExplainRejectedPlacement
		{
			private static bool Prefix(Player __instance, Piece piece, ref bool __result)
			{
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_003e: 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_0043: Invalid comparison between Unknown and I4
				//IL_0045: Unknown result type (might be due to invalid IL or missing references)
				//IL_0048: Invalid comparison between Unknown and I4
				//IL_004a: Unknown result type (might be due to invalid IL or missing references)
				//IL_004c: Invalid comparison between Unknown and I4
				PlantedCrop plantedCrop = default(PlantedCrop);
				if (!((Component)piece).TryGetComponent<PlantedCrop>(ref plantedCrop))
				{
					return true;
				}
				UpdateGhost(__instance, arg2: true);
				GameObject val = Ghost.Invoke(__instance);
				PlacementStatus placementStatus = __instance.GetPlacementStatus();
				PlantedCrop ghost = default(PlantedCrop);
				if (!Object.op_Implicit((Object)(object)val) || !val.TryGetComponent<PlantedCrop>(ref ghost) || ((int)placementStatus != 0 && (int)placementStatus != 1 && (int)placementStatus != 10 && (int)placementStatus != 8))
				{
					return true;
				}
				string text = Problem(ghost);
				if (text == null)
				{
					return true;
				}
				((Character)__instance).Message((MessageType)2, text, 0, (Sprite)null, false);
				__result = false;
				return false;
			}
		}

		[HarmonyPatch(typeof(Player), "RemovePiece")]
		private static class Uproot
		{
			private static bool Prefix(Player __instance, PieceTable ___m_buildPieces, ref bool __result)
			{
				if (!Plugin.IsCultivator(___m_buildPieces))
				{
					return true;
				}
				Piece hoveringPiece = __instance.GetHoveringPiece();
				PlantedCrop plantedCrop = default(PlantedCrop);
				if (Object.op_Implicit((Object)(object)hoveringPiece) && ((Component)hoveringPiece).TryGetComponent<PlantedCrop>(ref plantedCrop))
				{
					__result = plantedCrop.RequestUproot();
					return false;
				}
				return Plugin.NativeCultivatorRemoval;
			}
		}

		private static readonly int CoverLayers = LayerMask.GetMask(new string[6] { "Default", "static_solid", "Default_small", "piece", "terrain", "vehicle" });

		private static readonly int TerrainLayer = LayerMask.GetMask(new string[1] { "terrain" });

		private static readonly RaycastHit[] RoofHits = (RaycastHit[])(object)new RaycastHit[16];

		private static readonly RaycastHit[] FloorHits = (RaycastHit[])(object)new RaycastHit[8];

		private static readonly FieldRef<Player, GameObject> Ghost = AccessTools.FieldRefAccess<Player, GameObject>("m_placementGhost");

		private static readonly Action<Player, bool> UpdateGhost = AccessTools.MethodDelegate<Action<Player, bool>>(AccessTools.Method(typeof(Player), "UpdatePlacementGhost", (Type[])null, (Type[])null), (object)null, true);

		private static readonly Action<Player, bool> SetGhostValid = AccessTools.MethodDelegate<Action<Player, bool>>(AccessTools.Method(typeof(Player), "SetPlacementGhostValid", (Type[])null, (Type[])null), (object)null, true);

		internal static string SiteProblem(CropSpec spec, Vector3 position)
		{
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: 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_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: 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_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: 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_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Invalid comparison between Unknown and I4
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Invalid comparison between Unknown and I4
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Invalid comparison between Unknown and I4
			if (spec.IsMushroom)
			{
				bool flag = Character.InInterior(position);
				if (flag && !InMushroomCave(position))
				{
					return Plugin.Text("Choisis une grotte d’ours ou de troll.", "Choose a bear or troll cave.");
				}
				if (!flag && !HasStoneShelter(position + Vector3.up * 0.35f))
				{
					return Plugin.Text("Abri de pierre requis.", "Stone shelter required.");
				}
				if (!HasGround(position, CoverLayers))
				{
					return Plugin.Text("Une surface ferme est requise.", "A solid surface is required.");
				}
				return null;
			}
			Heightmap val = Heightmap.FindHeightmap(position);
			if (!Object.op_Implicit((Object)(object)val) || Character.InInterior(position) || !HasGround(position, TerrainLayer))
			{
				return Plugin.Text("Ce pied doit être planté en pleine terre.", "Plant this crop in the ground.");
			}
			if (position.y < ZoneSystem.instance.m_waterLevel - 0.05f)
			{
				return Plugin.Text("Le pied est sous l’eau.", "The plant is underwater.");
			}
			if (spec.Habitat == Habitat.OpenSoil && Cover.IsUnderRoof(position + Vector3.up * 0.55f))
			{
				return Plugin.Text("Ce pied a besoin de pousser à ciel ouvert.", "This plant needs open sky.");
			}
			Biome biome = val.GetBiome(position, 0.02f, false);
			if (spec.Habitat == Habitat.Ashlands && ((int)biome != 32 || val.IsLava(position, 0.5f)))
			{
				return Plugin.Text("Sol des Ashlands hors lave requis.", "Ashlands soil outside lava required.");
			}
			if (spec.Habitat == Habitat.Cold && (int)biome != 4 && (int)biome != 64)
			{
				return Plugin.Text("Terrain des Montagnes ou du Grand Nord requis.", "Mountain or Deep North ground required.");
			}
			return null;
		}

		private static bool HasGround(Vector3 position, int mask)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: 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_003e: Unknown result type (might be due to invalid IL or missing references)
			int num = Physics.RaycastNonAlloc(position + Vector3.up * 0.1f, Vector3.down, FloorHits, 0.35f, mask, (QueryTriggerInteraction)1);
			for (int i = 0; i < num; i++)
			{
				RaycastHit val = FloorHits[i];
				if (((RaycastHit)(ref val)).normal.y >= 0.5f && Object.op_Implicit((Object)(object)((RaycastHit)(ref val)).collider) && !Object.op_Implicit((Object)(object)((Component)((RaycastHit)(ref val)).collider).GetComponentInParent<PlantedCrop>()))
				{
					return true;
				}
			}
			return false;
		}

		private static bool HasStoneShelter(Vector3 point)
		{
			//IL_0000: 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)
			//IL_0022: 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_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Invalid comparison between Unknown and I4
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Invalid comparison between Unknown and I4
			float num = default(float);
			bool flag = default(bool);
			Cover.GetCoverForPoint(point, ref num, ref flag, 0.25f);
			if (!flag || num < 0.8f)
			{
				return false;
			}
			int num2 = Physics.SphereCastNonAlloc(point, 0.1f, Vector3.up, RoofHits, 100f, CoverLayers, (QueryTriggerInteraction)1);
			for (int i = 0; i < num2; i++)
			{
				Collider collider = ((RaycastHit)(ref RoofHits[i])).collider;
				if (!Object.op_Implicit((Object)(object)collider) || ((Component)collider).CompareTag("leaky"))
				{
					continue;
				}
				WearNTear componentInParent = ((Component)collider).GetComponentInParent<WearNTear>();
				if (Object.op_Implicit((Object)(object)componentInParent))
				{
					MaterialType materialType = componentInParent.m_materialType;
					if ((int)materialType == 1 || materialType - 4 <= 1)
					{
						return true;
					}
				}
			}
			return false;
		}

		private static bool InMushroomCave(Vector3 position)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			if (!Character.InInterior(position))
			{
				return false;
			}
			Location zoneLocation = Location.GetZoneLocation(position);
			if (!Object.op_Implicit((Object)(object)zoneLocation))
			{
				return false;
			}
			string prefabName = Utils.GetPrefabName(((Component)zoneLocation).gameObject);
			if (!(prefabName == "BearCave"))
			{
				return prefabName == "TrollCave02";
			}
			return true;
		}

		private static string SpacingProblem(CropSpec spec, Vector3 position)
		{
			//IL_001b: 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_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: 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)
			//IL_0056: 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: Unknown result type (might be due to invalid IL or missing references)
			foreach (PlantedCrop activeCrop in PlantedCrop.ActiveCrops)
			{
				Vector3 val = ((Component)activeCrop).transform.position - position;
				float num = Mathf.Max(spec.Spacing, activeCrop.Spec.Spacing);
				if (Mathf.Abs(val.y) <= 0.6f && val.x * val.x + val.z * val.z < num * num)
				{
					return Plugin.Text("Trop près d’un autre pied.", "Too close to another crop.");
				}
			}
			return null;
		}

		private static string Problem(PlantedCrop ghost)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: 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)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			CropSpec spec = ghost.Spec;
			Vector3 position = ((Component)ghost).transform.position;
			return BossProblem(spec) ?? SiteProblem(spec, position) ?? SpacingProblem(spec, position);
		}

		private static string BossProblem(CropSpec spec)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)ZoneSystem.instance) || !ZoneSystem.instance.GetGlobalKey(spec.Key))
			{
				return Plugin.Text("Boss à vaincre dans ce monde\u00a0: " + spec.Boss + ".", "Defeat " + spec.Boss + " in this world.");
			}
			return null;
		}

		private static bool IsNoBuildLocation(Vector3 position, Player player)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Ghost.Invoke(player);
			PlantedCrop plantedCrop = default(PlantedCrop);
			if (Object.op_Implicit((Object)(object)val) && val.TryGetComponent<PlantedCrop>(ref plantedCrop) && plantedCrop.Spec.IsMushroom && InMushroomCave(position))
			{
				return false;
			}
			return Location.IsInsideNoBuildLocation(position);
		}
	}
	internal sealed class PlantedCrop : MonoBehaviour
	{
		internal static readonly HashSet<PlantedCrop> ActiveCrops = new HashSet<PlantedCrop>();

		private const string MaskKey = "arboriculteur.mask";

		private const string DueKey = "arboriculteur.due";

		private const string PauseKey = "arboriculteur.pause";

		private const string RegrowthKey = "arboriculteur.regrowth";

		private const string PickRpc = "Arboriculteur_Pick";

		private const string UprootRpc = "Arboriculteur_Uproot";

		public int CropIndex;

		public ItemDrop HarvestItem;

		public EffectList HarvestEffect;

		public CropTarget[] Targets;

		private ZNetView view;

		private int displayedMask = int.MinValue;

		internal CropSpec Spec => Catalog.Crops[CropIndex];

		private void Start()
		{
			view = ((Component)this).GetComponent<ZNetView>();
			if (Object.op_Implicit((Object)(object)view) && view.IsValid())
			{
				view.Register<int>("Arboriculteur_Pick", (Action<long, int>)OnPick);
				view.Register("Arboriculteur_Uproot", (Action<long>)OnUproot);
				ActiveCrops.Add(this);
				ShowMask(view.GetZDO().GetInt("arboriculteur.mask", 0));
				((MonoBehaviour)this).InvokeRepeating("Tick", Random.Range(0.1f, 0.9f), 1f);
			}
		}

		private void OnDestroy()
		{
			ActiveCrops.Remove(this);
		}

		private void Tick()
		{
			if (view.IsValid() && Object.op_Implicit((Object)(object)ZNet.instance) && Object.op_Implicit((Object)(object)EnvMan.instance))
			{
				ZDO zDO = view.GetZDO();
				if (view.IsOwner())
				{
					UpdateGrowth(zDO, ZNet.instance.GetTime().Ticks);
				}
				if (view.IsValid())
				{
					ShowMask(zDO.GetInt("arboriculteur.mask", 0));
				}
			}
		}

		private void UpdateGrowth(ZDO zdo, long now)
		{
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			int num = zdo.GetInt("arboriculteur.mask", 0);
			if (num == -1)
			{
				view.Destroy();
				return;
			}
			long num2 = zdo.GetLong("arboriculteur.due", 0L);
			if (num2 == 0L)
			{
				num2 = now + Days(Spec.FirstDays);
				zdo.Set("arboriculteur.due", num2);
			}
			long num3 = zdo.GetLong("arboriculteur.pause", 0L);
			if (CropPlacement.SiteProblem(Spec, ((Component)this).transform.position) != null)
			{
				if (num3 == 0L)
				{
					zdo.Set("arboriculteur.pause", now);
				}
				return;
			}
			if (num3 > 0)
			{
				num2 = CropCycle.Resume(num2, now, num3);
				zdo.Set("arboriculteur.due", num2);
				zdo.Set("arboriculteur.pause", 0L);
			}
			if (num == 0 && now >= num2)
			{
				int count = ((!Spec.IsMushroom) ? 1 : Random.Range(1, Targets.Length + 1));
				zdo.Set("arboriculteur.mask", CropCycle.ReadyMask(count));
			}
		}

		private void ShowMask(int mask)
		{
			if (mask != displayedMask)
			{
				displayedMask = mask;
				for (int i = 0; i < Targets.Length; i++)
				{
					bool flag = CropCycle.CanPick(mask, i);
					((Component)Targets[i]).gameObject.SetActive(flag || (i == 0 && mask == 0));
					Targets[i].SetMature(flag, Spec.IsBush);
				}
			}
		}

		private static long Days(int days)
		{
			return TimeSpan.FromSeconds(EnvMan.instance.m_dayLengthSec * days).Ticks;
		}

		internal string HoverText(int slot)
		{
			if (!Object.op_Implicit((Object)(object)view) || !view.IsValid() || !Object.op_Implicit((Object)(object)ZNet.instance) || !Object.op_Implicit((Object)(object)EnvMan.instance))
			{
				return string.Empty;
			}
			ZDO zDO = view.GetZDO();
			long num = zDO.GetLong("arboriculteur.pause", 0L);
			int num2 = zDO.GetInt("arboriculteur.mask", 0);
			string text;
			if (num > 0)
			{
				text = Plugin.Text("En dormance", "Dormant");
			}
			else if (CropCycle.CanPick(num2, slot))
			{
				text = Plugin.Text("Prêt à récolter", "Ready to harvest") + "\n[<color=yellow><b>$KEY_Use</b></color>] $inventory_pickup";
			}
			else
			{
				if (num2 != 0)
				{
					return string.Empty;
				}
				long ticks = ZNet.instance.GetTime().Ticks;
				long num3 = CropCycle.TimeLeft(zDO.GetLong("arboriculteur.due", ticks + Days(Spec.FirstDays)), ticks, num);
				string text2 = ((num3 >= Days(1)) ? (Math.Ceiling((double)num3 / (double)Days(1)) + Plugin.Text(" j", " d")) : (Math.Max(1.0, Math.Ceiling(TimeSpan.FromTicks(num3).TotalMinutes)) + " min"));
				text = (zDO.GetBool("arboriculteur.regrowth", false) ? Plugin.Text("Repousse dans ", "Regrowth in ") : Plugin.Text("Mûrit dans ", "Matures in ")) + text2;
			}
			return Plugin.Localize(HarvestItem.m_itemData.m_shared.m_name + "\n" + text);
		}

		internal bool RequestPick(int slot, Humanoid user, bool hold)
		{
			if (hold || !(user is Player) || !Object.op_Implicit((Object)(object)view) || !view.IsValid())
			{
				return false;
			}
			ZDO zDO = view.GetZDO();
			if (!CropCycle.CanPick(zDO.GetInt("arboriculteur.mask", 0), slot) || zDO.GetLong("arboriculteur.pause", 0L) != 0L)
			{
				return false;
			}
			view.InvokeRPC("Arboriculteur_Pick", new object[1] { slot });
			return true;
		}

		internal bool RequestUproot()
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)view) || !view.IsValid() || !PrivateArea.CheckAccess(((Component)this).transform.position, 0f, true, false))
			{
				return false;
			}
			view.InvokeRPC("Arboriculteur_Uproot", Array.Empty<object>());
			return true;
		}

		private void OnPick(long sender, int slot)
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: 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)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			if (!view.IsValid() || !view.IsOwner())
			{
				return;
			}
			ZDO zDO = view.GetZDO();
			int mask = zDO.GetInt("arboriculteur.mask", 0);
			if (CropCycle.CanPick(mask, slot) && CropPlacement.SiteProblem(Spec, ((Component)this).transform.position) == null)
			{
				Vector3 position = ((Component)Targets[slot]).transform.position;
				int num = CropCycle.Pick(mask, slot);
				if (num == 0 && !Spec.IsMushroom)
				{
					zDO.Set("arboriculteur.regrowth", true);
					zDO.Set("arboriculteur.due", ZNet.instance.GetTime().Ticks + Days(Spec.RegrowDays));
				}
				zDO.Set("arboriculteur.mask", (num == 0 && Spec.IsMushroom) ? (-1) : num);
				Object.Instantiate<GameObject>(((Component)HarvestItem).gameObject, position + Vector3.up * 0.22f, Quaternion.identity).GetComponent<ItemDrop>().m_itemData.m_stack = Spec.Yield;
				EffectList harvestEffect = HarvestEffect;
				if (harvestEffect != null)
				{
					harvestEffect.Create(position, Quaternion.identity, (Transform)null, 1f, -1, default(ZDOID));
				}
				if (num == 0 && Spec.IsMushroom)
				{
					view.Destroy();
				}
				else
				{
					ShowMask(num);
				}
			}
		}

		private void OnUproot(long sender)
		{
			if (view.IsValid() && view.IsOwner())
			{
				view.GetZDO().Set("arboriculteur.mask", -1);
				view.Destroy();
			}
		}
	}
	internal sealed class CropTarget : MonoBehaviour, Hoverable, Interactable
	{
		public PlantedCrop Crop;

		public int Slot;

		public Transform Visual;

		public GameObject Fruit;

		internal void SetMature(bool mature, bool bush)
		{
			//IL_0006: 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)
			Visual.localScale = Vector3.one * ((mature || bush) ? 1f : 0.65f);
			if (Object.op_Implicit((Object)(object)Fruit))
			{
				Fruit.SetActive(mature);
			}
		}

		public string GetHoverName()
		{
			return Plugin.Localize(Crop.HarvestItem.m_itemData.m_shared.m_name);
		}

		public string GetHoverText()
		{
			return Crop.HoverText(Slot);
		}

		public float GetHoverOffset()
		{
			return 0f;
		}

		public bool Interact(Humanoid user, bool hold, bool alt)
		{
			return Crop.RequestPick(Slot, user, hold);
		}

		public bool UseItem(Humanoid user, ItemData item)
		{
			return false;
		}
	}
	[BepInPlugin("fr.romaindurand.arboriculteur", "Arboriculteur", "1.0.0")]
	public sealed class Plugin : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(ZNetScene), "Awake")]
		private static class RegisterCrops
		{
			private static void Postfix(ZNetScene __instance, Dictionary<int, GameObject> ___m_namedPrefabs)
			{
				//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b6: Expected O, but got Unknown
				RestoreCultivator();
				GameObject prefab = __instance.GetPrefab("Cultivator");
				cultivator = ((prefab == null) ? null : prefab.GetComponent<ItemDrop>()?.m_itemData.m_shared.m_buildPieces);
				if (!Object.op_Implicit((Object)(object)cultivator))
				{
					((BaseUnityPlugin)instance).Logger.LogError((object)"Cultivator piece table is missing.");
					return;
				}
				cultivator.m_pieces.RemoveAll((GameObject piece) => !Object.op_Implicit((Object)(object)piece) || ((Object)piece).name.StartsWith("Arboriculteur_", StringComparison.Ordinal));
				nativeRemoval = cultivator.m_canRemovePieces;
				cultivator.m_canRemovePieces = true;
				cropScene = __instance;
				templates = new GameObject("Arboriculteur crop prefabs");
				templates.transform.SetParent(((Component)__instance).transform, false);
				templates.SetActive(false);
				GameObject? obj = cultivator.m_pieces.Find((GameObject piece) => ((Object)piece).name == "cultivate_v2");
				EffectList sowingEffect = ((obj != null) ? obj.GetComponent<Piece>().m_placeEffect : null);
				int num = 0;
				ItemDrop item = default(ItemDrop);
				for (int num2 = 0; num2 < Catalog.Crops.Length; num2++)
				{
					CropSpec cropSpec = Catalog.Crops[num2];
					GameObject prefab2 = __instance.GetPrefab(cropSpec.Source);
					Pickable val = ((prefab2 != null) ? prefab2.GetComponent<Pickable>() : null);
					if (!Object.op_Implicit((Object)(object)val) || !Object.op_Implicit((Object)(object)val.m_itemPrefab) || !val.m_itemPrefab.TryGetComponent<ItemDrop>(ref item))
					{
						((BaseUnityPlugin)instance).Logger.LogError((object)("Missing wild crop or harvest item: " + cropSpec.Source));
						continue;
					}
					GameObject val2 = MakePrefab(num2, val, item, sowingEffect);
					___m_namedPrefabs.Add(StringExtensionMethods.GetStableHashCode(((Object)val2).name), val2);
					__instance.m_prefabs.Add(val2);
					cultivator.m_pieces.Add(val2);
					num++;
				}
				((BaseUnityPlugin)instance).Logger.LogInfo((object)$"Registered {num}/{Catalog.Crops.Length} Arboriculteur crops.");
			}
		}

		[HarmonyPatch(typeof(ZNetScene), "OnDestroy")]
		private static class RestoreCultivatorOnExit
		{
			private static void Prefix(ZNetScene __instance)
			{
				if ((Object)(object)cropScene == (Object)(object)__instance)
				{
					RestoreCultivator();
				}
			}
		}

		internal const string Guid = "fr.romaindurand.arboriculteur";

		internal const string Version = "1.0.0";

		private static Plugin instance;

		private Harmony harmony;

		private static GameObject templates;

		private static ZNetScene cropScene;

		private static PieceTable cultivator;

		private static bool nativeRemoval;

		internal static bool NativeCultivatorRemoval => nativeRemoval;

		private void Awake()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			instance = this;
			harmony = new Harmony("fr.romaindurand.arboriculteur");
			harmony.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Arboriculteur 1.0.0 loaded.");
		}

		private void OnDestroy()
		{
			RestoreCultivator();
			Harmony obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
		}

		internal static bool IsCultivator(PieceTable table)
		{
			if (Object.op_Implicit((Object)(object)cultivator))
			{
				return (Object)(object)table == (Object)(object)cultivator;
			}
			return false;
		}

		internal static string Text(string french, string english)
		{
			Localization obj = Localization.instance;
			if (!(((obj != null) ? obj.GetSelectedLanguage() : null) == "French"))
			{
				return english;
			}
			return french;
		}

		internal static string Localize(string text)
		{
			Localization obj = Localization.instance;
			return ((obj != null) ? obj.Localize(text) : null) ?? text;
		}

		private static void RestoreCultivator()
		{
			if (Object.op_Implicit((Object)(object)cultivator))
			{
				cultivator.m_canRemovePieces = nativeRemoval;
				cultivator.m_pieces.RemoveAll((GameObject piece) => !Object.op_Implicit((Object)(object)piece) || ((Object)piece).name.StartsWith("Arboriculteur_", StringComparison.Ordinal));
			}
			if (Object.op_Implicit((Object)(object)templates))
			{
				Object.Destroy((Object)(object)templates);
			}
			cropScene = null;
			cultivator = null;
			templates = null;
		}

		private static GameObject MakePrefab(int index, Pickable wild, ItemDrop item, EffectList sowingEffect)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: 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_0119: Expected O, but got Unknown
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			CropSpec cropSpec = Catalog.Crops[index];
			GameObject val = new GameObject("Arboriculteur_" + cropSpec.Source);
			val.transform.SetParent(templates.transform, false);
			val.AddComponent<ZNetView>().m_persistent = true;
			Piece val2 = val.AddComponent<Piece>();
			val2.m_name = item.m_itemData.m_shared.m_name;
			val2.m_description = item.m_itemData.m_shared.m_description;
			val2.m_icon = item.m_itemData.GetIcon();
			val2.m_category = (PieceCategory)0;
			val2.m_enabled = true;
			((StaticTarget)val2).m_randomTarget = false;
			val2.m_allowedInDungeons = cropSpec.IsMushroom;
			val2.m_allowedInDeepSnow = cropSpec.Habitat == Habitat.Cold || cropSpec.IsMushroom;
			val2.m_groundOnly = !cropSpec.IsMushroom;
			val2.m_clipGround = true;
			val2.m_noInWater = true;
			val2.m_canBeRemoved = false;
			val2.m_canRotate = !cropSpec.IsMushroom;
			val2.m_resources = (Requirement[])(object)new Requirement[1]
			{
				new Requirement
				{
					m_resItem = item,
					m_amount = cropSpec.Cost,
					m_recover = false
				}
			};
			if (sowingEffect != null)
			{
				val2.m_placeEffect = sowingEffect;
			}
			PlantedCrop plantedCrop = val.AddComponent<PlantedCrop>();
			plantedCrop.CropIndex = index;
			plantedCrop.HarvestItem = item;
			plantedCrop.HarvestEffect = wild.m_pickEffector;
			plantedCrop.Targets = new CropTarget[(!cropSpec.IsMushroom) ? 1 : 3];
			plantedCrop.Targets[0] = CreateTarget(plantedCrop, wild, 0, Vector3.zero);
			if (cropSpec.IsMushroom)
			{
				plantedCrop.Targets[1] = CreateTarget(plantedCrop, wild, 1, new Vector3(0.26f, 0f, 0.09f));
				plantedCrop.Targets[2] = CreateTarget(plantedCrop, wild, 2, new Vector3(-0.15f, 0f, 0.25f));
				((Component)plantedCrop.Targets[1]).gameObject.SetActive(false);
				((Component)plantedCrop.Targets[2]).gameObject.SetActive(false);
			}
			return val;
		}

		private static CropTarget CreateTarget(PlantedCrop crop, Pickable wild, int slot, Vector3 offset)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_019d: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject($"Pick {slot + 1}")
			{
				layer = LayerMask.NameToLayer("piece")
			};
			val.transform.SetParent(((Component)crop).transform, false);
			val.transform.localPosition = offset;
			CropTarget cropTarget = val.AddComponent<CropTarget>();
			cropTarget.Crop = crop;
			cropTarget.Slot = slot;
			GameObject val2 = Object.Instantiate<GameObject>(((Component)wild).gameObject, val.transform, false);
			val2.transform.SetLocalPositionAndRotation(Vector3.zero, Quaternion.identity);
			Pickable component = val2.GetComponent<Pickable>();
			cropTarget.Visual = val2.transform;
			if (crop.Spec.IsBush && (Object)(object)component.m_hideWhenPicked != (Object)(object)val2)
			{
				cropTarget.Fruit = component.m_hideWhenPicked;
			}
			MonoBehaviour[] componentsInChildren = val2.GetComponentsInChildren<MonoBehaviour>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren[i]);
			}
			Collider[] componentsInChildren2 = val2.GetComponentsInChildren<Collider>(true);
			for (int i = 0; i < componentsInChildren2.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren2[i]);
			}
			Rigidbody[] componentsInChildren3 = val2.GetComponentsInChildren<Rigidbody>(true);
			for (int i = 0; i < componentsInChildren3.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren3[i]);
			}
			BoxCollider obj = val.AddComponent<BoxCollider>();
			float num = (crop.Spec.IsBush ? 0.75f : 0.32f);
			float num2 = (crop.Spec.IsBush ? 0.65f : (crop.Spec.IsMushroom ? 0.18f : 0.32f));
			obj.center = Vector3.up * (num / 2f);
			obj.size = new Vector3(num2, num, num2);
			return cropTarget;
		}
	}
}