Decompiled source of SakeysJapaneseFoodFARM v0.0.2

BepInEx/plugins/Sakey's Japanese food FARM/Sakey's Japanese food FARM.dll

Decompiled 7 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
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("Sakey's Japanese food FARM")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("Sakey's Japanese food FARM")]
[assembly: AssemblyTitle("Sakey's Japanese food FARM")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace SakeysJapaneseFoodFARM;

[BepInPlugin("com.sakey.japanesefarm", "Sakey's Japanese food FARM", "0.0.2")]
[BepInDependency("com.jotunn.jotunn", "2.30.2")]
[BepInDependency("com.sakey.japanesefood", "1.0.6")]
[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
public sealed class Plugin : BaseUnityPlugin
{
	private sealed class Crop
	{
		public string Id;

		public string ItemPrefab;

		public string YoungModel;

		public string GrownModel;

		public ConfigEntry<float> GrowMinMinutes;

		public ConfigEntry<float> GrowMaxMinutes;

		public ConfigEntry<int> HarvestAmount;

		public GameObject SaplingPrefab;

		public GameObject GrownPrefab;
	}

	public const string PluginGuid = "com.sakey.japanesefarm";

	public const string PluginName = "Sakey's Japanese food FARM";

	public const string PluginVersion = "0.0.2";

	public const string JapaneseFoodGuid = "com.sakey.japanesefood";

	public const string AssetBundleName = "jpfarm";

	private const string CultivatorPieceTable = "_CultivatorPieceTable";

	private const string SaplingBasePrefab = "sapling_barley";

	private const string GrownBasePrefab = "Pickable_Barley";

	private AssetBundle _bundle;

	private bool _prefabsBuilt;

	private bool _itemLinksApplied;

	private ConfigEntry<float> _growthMultiplier;

	private ConfigEntry<float> _kabotyaGrowMin;

	private ConfigEntry<float> _kabotyaGrowMax;

	private ConfigEntry<int> _kabotyaYield;

	private ConfigEntry<float> _okomeGrowMin;

	private ConfigEntry<float> _okomeGrowMax;

	private ConfigEntry<int> _okomeYield;

	private ConfigEntry<float> _mameGrowMin;

	private ConfigEntry<float> _mameGrowMax;

	private ConfigEntry<int> _mameYield;

	private ConfigEntry<bool> _allowMeadows;

	private ConfigEntry<bool> _allowBlackForest;

	private ConfigEntry<bool> _allowPlains;

	private ConfigEntry<bool> _allowAshlands;

	private readonly List<Crop> _crops = new List<Crop>();

	private void Awake()
	{
		BindConfig();
		RegisterLocalization();
		string text = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location) ?? string.Empty, "jpfarm");
		_bundle = AssetBundle.LoadFromFile(text);
		if ((Object)(object)_bundle == (Object)null)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("AssetBundle load failed: " + text));
			return;
		}
		_crops.Add(new Crop
		{
			Id = "kabotya",
			ItemPrefab = "food_kabotya",
			YoungModel = "farm_kabotya1",
			GrownModel = "farm_kabotya2",
			GrowMinMinutes = _kabotyaGrowMin,
			GrowMaxMinutes = _kabotyaGrowMax,
			HarvestAmount = _kabotyaYield
		});
		_crops.Add(new Crop
		{
			Id = "okome",
			ItemPrefab = "food_okome",
			YoungModel = "farm_kome1",
			GrownModel = "farm_kome2",
			GrowMinMinutes = _okomeGrowMin,
			GrowMaxMinutes = _okomeGrowMax,
			HarvestAmount = _okomeYield
		});
		_crops.Add(new Crop
		{
			Id = "mame",
			ItemPrefab = "food_mame",
			YoungModel = "farm_mame1",
			GrownModel = "farm_mame2",
			GrowMinMinutes = _mameGrowMin,
			GrowMaxMinutes = _mameGrowMax,
			HarvestAmount = _mameYield
		});
		SubscribeConfigChanges();
		PrefabManager.OnVanillaPrefabsAvailable += BuildCropPrefabs;
		ItemManager.OnItemsRegistered += ApplyJapaneseFoodLinks;
		PieceManager.OnPiecesRegistered += VerifyCultivatorRegistration;
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Sakey's Japanese food FARM 0.0.2 loaded. AssetBundle: jpfarm");
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Hard dependency direction: FARM -> Sakey's Japanese food. Japanese Food does not require FARM.");
	}

	private void BindConfig()
	{
		((BaseUnityPlugin)this).Config.SaveOnConfigSet = true;
		_growthMultiplier = BindFloatWithMigration("Growth - General", "GrowthMultiplier", "成長時間の倍率です。1.0=通常、0.1=通常の10分の1、0.01=通常の100分の1。\nScales crop growth time. 1.0=normal, 0.1=10x faster, 0.01=100x faster.", 1f, 0.01f, 10f, "成長時間 / Growth Time - 共通 / General", "速度倍率 / Speed Multiplier");
		_kabotyaGrowMin = BindFloatWithMigration("Growth - Kabotya", "MinimumMinutes", "カボチャが育つまでの最短時間です。0.01分まで短縮できます。\nShortest time for pumpkin to mature. Can be reduced to 0.01 minutes.", 66.67f, 0.01f, 600f, "成長時間 / Growth Time - カボチャ / Pumpkin", "最短時間(分) / Minimum (min)");
		_kabotyaGrowMax = BindFloatWithMigration("Growth - Kabotya", "MaximumMinutes", "カボチャが育つまでの最長時間です。最短時間より小さい場合は最短時間に合わせます。\nLongest time for pumpkin to mature. If lower than the minimum, the minimum is used.", 83.33f, 0.01f, 600f, "成長時間 / Growth Time - カボチャ / Pumpkin", "最長時間(分) / Maximum (min)");
		_kabotyaYield = BindIntWithMigration("Harvest - Kabotya", "Amount", "成熟したカボチャ1株から収穫できる個数です。\nNumber of pumpkins harvested from one mature plant.", 6, 1, 999, "収穫量 / Harvest - カボチャ / Pumpkin", "収穫個数 / Amount");
		_okomeGrowMin = BindFloatWithMigration("Growth - Okome", "MinimumMinutes", "お米が育つまでの最短時間です。0.01分まで短縮できます。\nShortest time for rice to mature. Can be reduced to 0.01 minutes.", 66.67f, 0.01f, 600f, "成長時間 / Growth Time - お米 / Rice", "最短時間(分) / Minimum (min)");
		_okomeGrowMax = BindFloatWithMigration("Growth - Okome", "MaximumMinutes", "お米が育つまでの最長時間です。最短時間より小さい場合は最短時間に合わせます。\nLongest time for rice to mature. If lower than the minimum, the minimum is used.", 83.33f, 0.01f, 600f, "成長時間 / Growth Time - お米 / Rice", "最長時間(分) / Maximum (min)");
		_okomeYield = BindIntWithMigration("Harvest - Okome", "Amount", "成熟した稲1株から収穫できる個数です。\nNumber of rice items harvested from one mature plant.", 6, 1, 999, "収穫量 / Harvest - お米 / Rice", "収穫個数 / Amount");
		_mameGrowMin = BindFloatWithMigration("Growth - Mame", "MinimumMinutes", "豆が育つまでの最短時間です。0.01分まで短縮できます。\nShortest time for beans to mature. Can be reduced to 0.01 minutes.", 66.67f, 0.01f, 600f, "成長時間 / Growth Time - 豆 / Beans", "最短時間(分) / Minimum (min)");
		_mameGrowMax = BindFloatWithMigration("Growth - Mame", "MaximumMinutes", "豆が育つまでの最長時間です。最短時間より小さい場合は最短時間に合わせます。\nLongest time for beans to mature. If lower than the minimum, the minimum is used.", 83.33f, 0.01f, 600f, "成長時間 / Growth Time - 豆 / Beans", "最長時間(分) / Maximum (min)");
		_mameYield = BindIntWithMigration("Harvest - Mame", "Amount", "成熟した豆の株1つから収穫できる個数です。\nNumber of beans harvested from one mature plant.", 6, 1, 999, "収穫量 / Harvest - 豆 / Beans", "収穫個数 / Amount");
		_allowMeadows = BindBoolWithMigration("Growth - Biomes", "Meadows", "草原で作物を育てられるようにします。 / Allow crops to grow in Meadows.", defaultValue: true, "栽培可能バイオーム / Allowed Biomes", "草原 / Meadows");
		_allowBlackForest = BindBoolWithMigration("Growth - Biomes", "BlackForest", "黒い森で作物を育てられるようにします。 / Allow crops to grow in Black Forest.", defaultValue: true, "栽培可能バイオーム / Allowed Biomes", "黒い森 / Black Forest");
		_allowPlains = BindBoolWithMigration("Growth - Biomes", "Plains", "平地で作物を育てられるようにします。 / Allow crops to grow in Plains.", defaultValue: true, "栽培可能バイオーム / Allowed Biomes", "平地 / Plains");
		_allowAshlands = BindBoolWithMigration("Growth - Biomes", "Ashlands", "アッシュランドで作物を育てられるようにします。耐熱性は追加されません。\nAllow crops to grow in Ashlands. Heat tolerance is not added.", defaultValue: false, "栽培可能バイオーム / Allowed Biomes", "アッシュランド / Ashlands");
	}

	private ConfigEntry<float> BindFloatWithMigration(string oldSection, string oldKey, string description, float defaultValue, float min, float max, string newSection, string newKey)
	{
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_004e: Expected O, but got Unknown
		ConfigEntry<float> val = ((BaseUnityPlugin)this).Config.Bind<float>(oldSection, oldKey, defaultValue, (ConfigDescription)null);
		float value = val.Value;
		((BaseUnityPlugin)this).Config.Remove(((ConfigEntryBase)val).Definition);
		return ((BaseUnityPlugin)this).Config.Bind<float>(newSection, newKey, value, new ConfigDescription(description, (AcceptableValueBase)(object)new AcceptableValueRange<float>(min, max), Array.Empty<object>()));
	}

	private ConfigEntry<int> BindIntWithMigration(string oldSection, string oldKey, string description, int defaultValue, int min, int max, string newSection, string newKey)
	{
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_004e: Expected O, but got Unknown
		ConfigEntry<int> val = ((BaseUnityPlugin)this).Config.Bind<int>(oldSection, oldKey, defaultValue, (ConfigDescription)null);
		int value = val.Value;
		((BaseUnityPlugin)this).Config.Remove(((ConfigEntryBase)val).Definition);
		return ((BaseUnityPlugin)this).Config.Bind<int>(newSection, newKey, value, new ConfigDescription(description, (AcceptableValueBase)(object)new AcceptableValueRange<int>(min, max), Array.Empty<object>()));
	}

	private ConfigEntry<bool> BindBoolWithMigration(string oldSection, string oldKey, string description, bool defaultValue, string newSection, string newKey)
	{
		ConfigEntry<bool> val = ((BaseUnityPlugin)this).Config.Bind<bool>(oldSection, oldKey, defaultValue, (ConfigDescription)null);
		bool value = val.Value;
		((BaseUnityPlugin)this).Config.Remove(((ConfigEntryBase)val).Definition);
		return ((BaseUnityPlugin)this).Config.Bind<bool>(newSection, newKey, value, description);
	}

	private void SubscribeConfigChanges()
	{
		_growthMultiplier.SettingChanged += OnGrowthConfigChanged;
		_kabotyaGrowMin.SettingChanged += OnGrowthConfigChanged;
		_kabotyaGrowMax.SettingChanged += OnGrowthConfigChanged;
		_okomeGrowMin.SettingChanged += OnGrowthConfigChanged;
		_okomeGrowMax.SettingChanged += OnGrowthConfigChanged;
		_mameGrowMin.SettingChanged += OnGrowthConfigChanged;
		_mameGrowMax.SettingChanged += OnGrowthConfigChanged;
		_kabotyaYield.SettingChanged += OnHarvestConfigChanged;
		_okomeYield.SettingChanged += OnHarvestConfigChanged;
		_mameYield.SettingChanged += OnHarvestConfigChanged;
		_allowMeadows.SettingChanged += OnGrowthConfigChanged;
		_allowBlackForest.SettingChanged += OnGrowthConfigChanged;
		_allowPlains.SettingChanged += OnGrowthConfigChanged;
		_allowAshlands.SettingChanged += OnGrowthConfigChanged;
	}

	private void OnGrowthConfigChanged(object sender, EventArgs args)
	{
		foreach (Crop crop in _crops)
		{
			ApplyGrowthSettings(crop, updateExisting: true);
		}
		((BaseUnityPlugin)this).Logger.LogInfo((object)"FARM growth settings changed; crop prefabs and planted crops updated.");
	}

	private void OnHarvestConfigChanged(object sender, EventArgs args)
	{
		foreach (Crop crop in _crops)
		{
			ApplyHarvestSettings(crop, updateExisting: true);
		}
		((BaseUnityPlugin)this).Logger.LogInfo((object)"FARM harvest settings changed; harvest prefabs and planted crops updated.");
	}

	private void RegisterLocalization()
	{
		try
		{
			CustomLocalization localization = LocalizationManager.Instance.GetLocalization();
			string text = "English";
			localization.AddTranslation(ref text, new Dictionary<string, string> { { "piece_sakey_jpfarm_plant_desc", "Plant one Japanese Food item and grow a crop for harvesting." } });
			text = "Japanese";
			localization.AddTranslation(ref text, new Dictionary<string, string> { { "piece_sakey_jpfarm_plant_desc", "日本食MODのアイテムを1個植えて、成長した作物を収穫します。" } });
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Localization registration failed: " + ex));
		}
	}

	private void BuildCropPrefabs()
	{
		//IL_021d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0227: Expected O, but got Unknown
		//IL_048e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0498: Expected O, but got Unknown
		if (_prefabsBuilt)
		{
			return;
		}
		_prefabsBuilt = true;
		PrefabManager.OnVanillaPrefabsAvailable -= BuildCropPrefabs;
		GameObject prefab = PrefabManager.Instance.GetPrefab("sapling_barley");
		GameObject prefab2 = PrefabManager.Instance.GetPrefab("Pickable_Barley");
		if ((Object)(object)prefab == (Object)null || (Object)(object)prefab2 == (Object)null)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)"Could not find vanilla crop bases: sapling_barley / Pickable_Barley");
			return;
		}
		foreach (Crop crop in _crops)
		{
			try
			{
				GameObject val = _bundle.LoadAsset<GameObject>(crop.YoungModel);
				GameObject val2 = _bundle.LoadAsset<GameObject>(crop.GrownModel);
				if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null)
				{
					((BaseUnityPlugin)this).Logger.LogError((object)("Missing model in jpfarm AssetBundle for " + crop.Id + ". Expected " + crop.YoungModel + " and " + crop.GrownModel));
					continue;
				}
				crop.GrownPrefab = PrefabManager.Instance.CreateClonedPrefab("sakey_jpfarm_pickable_" + crop.Id, "Pickable_Barley");
				if ((Object)(object)crop.GrownPrefab == (Object)null)
				{
					((BaseUnityPlugin)this).Logger.LogError((object)("Could not clone Pickable_Barley for " + crop.Id));
					continue;
				}
				ReplaceGrownVisual(crop.GrownPrefab, val2);
				Pickable component = crop.GrownPrefab.GetComponent<Pickable>();
				if ((Object)(object)component == (Object)null)
				{
					((BaseUnityPlugin)this).Logger.LogError((object)("Cloned grown prefab has no Pickable: " + crop.Id));
					continue;
				}
				SetField(component, "m_harvestable", true);
				SetField(component, "m_respawnTimeMinutes", 0f);
				if (!SetField(component, "m_hideWhenPicked", null))
				{
					((BaseUnityPlugin)this).Logger.LogError((object)("Could not clear Pickable.m_hideWhenPicked for one-shot FARM crop: " + crop.Id));
				}
				else
				{
					((BaseUnityPlugin)this).Logger.LogInfo((object)("Configured one-shot harvest cleanup for FARM crop: " + crop.Id));
				}
				ApplyHarvestSettings(crop, updateExisting: false);
				PrefabManager.Instance.AddPrefab(new CustomPrefab(crop.GrownPrefab, false));
				crop.SaplingPrefab = PrefabManager.Instance.CreateClonedPrefab("sakey_jpfarm_sapling_" + crop.Id, "sapling_barley");
				if ((Object)(object)crop.SaplingPrefab == (Object)null)
				{
					((BaseUnityPlugin)this).Logger.LogError((object)("Could not clone sapling_barley for " + crop.Id));
					continue;
				}
				Plant component2 = crop.SaplingPrefab.GetComponent<Plant>();
				Piece component3 = crop.SaplingPrefab.GetComponent<Piece>();
				if ((Object)(object)component2 == (Object)null || (Object)(object)component3 == (Object)null)
				{
					((BaseUnityPlugin)this).Logger.LogError((object)("Cloned sapling is missing Plant or Piece: " + crop.Id));
					continue;
				}
				ReplacePlantStage(component2, "m_healthy", val, crop.Id + "_young_healthy");
				ReplacePlantStage(component2, "m_unhealthy", val, crop.Id + "_young_unhealthy");
				ReplacePlantStage(component2, "m_healthyGrown", val2, crop.Id + "_grown_healthy");
				ReplacePlantStage(component2, "m_unhealthyGrown", val2, crop.Id + "_grown_unhealthy");
				SetField(component2, "m_grownPrefabs", new GameObject[1] { crop.GrownPrefab });
				ApplyGrowthSettings(crop, updateExisting: false);
				SetField(component2, "m_growRadius", 0.5f);
				SetField(component2, "m_needCultivatedGround", true);
				SetField(component2, "m_destroyIfCantGrow", true);
				SetField(component2, "m_tolerateHeat", false);
				object value = CreateBiomeMask(GetBiomeMask());
				if (!SetField(component3, "m_cultivatedGroundOnly", true))
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not set Piece.m_cultivatedGroundOnly for " + crop.Id));
				}
				if (!SetField(component3, "m_onlyInBiome", value))
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not set Piece.m_onlyInBiome for " + crop.Id));
				}
				if (!SetField(component3, "m_canBeRemoved", true))
				{
					((BaseUnityPlugin)this).Logger.LogError((object)("Could not enable Hammer removal for FARM crop: " + crop.Id + " (Piece.m_canBeRemoved field was not found or could not be written)"));
				}
				else
				{
					((BaseUnityPlugin)this).Logger.LogInfo((object)("Enabled Hammer removal for FARM crop: " + crop.Id));
				}
				SetField(component2, "m_tolerateCold", false);
				if (!PieceManager.Instance.AddPiece(new CustomPiece(crop.SaplingPrefab, "_CultivatorPieceTable", false)))
				{
					((BaseUnityPlugin)this).Logger.LogError((object)("Jotunn rejected FARM cultivator piece: " + crop.Id + " | prefab=" + ((Object)crop.SaplingPrefab).name + " | table=_CultivatorPieceTable"));
				}
				else
				{
					((BaseUnityPlugin)this).Logger.LogInfo((object)("Queued FARM cultivator piece through PieceManager: " + crop.Id + " | prefab=" + ((Object)crop.SaplingPrefab).name));
				}
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Created crop prefabs: " + crop.Id + " (sapling=sakey_jpfarm_sapling_" + crop.Id + ", grown=sakey_jpfarm_pickable_" + crop.Id + ")"));
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Failed to build crop " + crop.Id + ": " + ex));
			}
		}
	}

	private static int GetHarvestAmount(Crop crop)
	{
		return Mathf.Max(1, crop.HarvestAmount.Value);
	}

	private void ApplyGrowthSettings(Crop crop, bool updateExisting)
	{
		if (crop == null)
		{
			return;
		}
		float num = Mathf.Max(0.01f, _growthMultiplier.Value);
		float num2 = Mathf.Max(0.01f, crop.GrowMinMinutes.Value) * num;
		float num3 = Mathf.Max(num2, crop.GrowMaxMinutes.Value * num);
		float num4 = num2 * 60f;
		float num5 = num3 * 60f;
		object value = CreateBiomeMask(GetBiomeMask());
		if ((Object)(object)crop.SaplingPrefab != (Object)null)
		{
			Plant component = crop.SaplingPrefab.GetComponent<Plant>();
			if ((Object)(object)component != (Object)null)
			{
				SetField(component, "m_growTime", num4);
				SetField(component, "m_growTimeMax", num5);
				SetField(component, "m_biome", value);
			}
			Piece component2 = crop.SaplingPrefab.GetComponent<Piece>();
			if ((Object)(object)component2 != (Object)null)
			{
				SetField(component2, "m_cultivatedGroundOnly", true);
				SetField(component2, "m_onlyInBiome", value);
			}
		}
		if (!updateExisting || (Object)(object)crop.SaplingPrefab == (Object)null)
		{
			return;
		}
		int num6 = 0;
		Plant[] array = Object.FindObjectsOfType<Plant>();
		string name = ((Object)crop.SaplingPrefab).name;
		Plant[] array2 = array;
		foreach (Plant val in array2)
		{
			if (!((Object)(object)val == (Object)null) && !((Object)(object)((Component)val).gameObject == (Object)null) && ((Object)((Component)val).gameObject).name.StartsWith(name, StringComparison.Ordinal))
			{
				SetField(val, "m_growTime", num4);
				SetField(val, "m_growTimeMax", num5);
				SetField(val, "m_biome", value);
				num6++;
			}
		}
		((BaseUnityPlugin)this).Logger.LogInfo((object)("Updated growth settings: " + crop.Id + " | min=" + num2 + " min | max=" + num3 + " min | live plants=" + num6));
	}

	private void ApplyHarvestSettings(Crop crop, bool updateExisting)
	{
		if (crop == null)
		{
			return;
		}
		int harvestAmount = GetHarvestAmount(crop);
		if ((Object)(object)crop.GrownPrefab != (Object)null)
		{
			Pickable component = crop.GrownPrefab.GetComponent<Pickable>();
			if ((Object)(object)component != (Object)null)
			{
				SetField(component, "m_amount", harvestAmount);
				SetField(component, "m_minAmountScaled", harvestAmount);
				SetField(component, "m_harvestable", true);
				SetField(component, "m_respawnTimeMinutes", 0f);
			}
		}
		if (!updateExisting || (Object)(object)crop.GrownPrefab == (Object)null)
		{
			return;
		}
		int num = 0;
		Pickable[] array = Object.FindObjectsOfType<Pickable>();
		string name = ((Object)crop.GrownPrefab).name;
		Pickable[] array2 = array;
		foreach (Pickable val in array2)
		{
			if (!((Object)(object)val == (Object)null) && !((Object)(object)((Component)val).gameObject == (Object)null) && ((Object)((Component)val).gameObject).name.StartsWith(name, StringComparison.Ordinal))
			{
				SetField(val, "m_amount", harvestAmount);
				SetField(val, "m_minAmountScaled", harvestAmount);
				num++;
			}
		}
		((BaseUnityPlugin)this).Logger.LogInfo((object)("Updated harvest amount: " + crop.Id + " | amount=" + harvestAmount + " | live plants=" + num));
	}

	private int GetBiomeMask()
	{
		int num = 0;
		if (_allowMeadows.Value)
		{
			num |= 1;
		}
		if (_allowBlackForest.Value)
		{
			num |= 8;
		}
		if (_allowPlains.Value)
		{
			num |= 0x10;
		}
		if (_allowAshlands.Value)
		{
			num |= 0x400;
		}
		return num;
	}

	private static object CreateBiomeMask(int mask)
	{
		FieldInfo fieldInfo = FindField(typeof(Plant), "m_biome");
		if (fieldInfo == null)
		{
			throw new MissingFieldException(typeof(Plant).FullName, "m_biome");
		}
		return Enum.ToObject(fieldInfo.FieldType, mask);
	}

	private void ApplyJapaneseFoodLinks()
	{
		if (_itemLinksApplied || (Object)(object)ObjectDB.instance == (Object)null)
		{
			return;
		}
		bool itemLinksApplied = true;
		foreach (Crop crop in _crops)
		{
			GameObject val = PrefabManager.Instance.GetPrefab(crop.ItemPrefab);
			if ((Object)(object)val == (Object)null)
			{
				val = ObjectDB.instance.GetItemPrefab(crop.ItemPrefab);
			}
			ItemDrop val2 = (((Object)(object)val != (Object)null) ? val.GetComponent<ItemDrop>() : null);
			if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Japanese Food item is not available yet: " + crop.ItemPrefab));
				itemLinksApplied = false;
				continue;
			}
			if ((Object)(object)crop.SaplingPrefab == (Object)null || (Object)(object)crop.GrownPrefab == (Object)null)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Crop prefab creation did not complete: " + crop.Id));
				itemLinksApplied = false;
				continue;
			}
			Pickable component = crop.GrownPrefab.GetComponent<Pickable>();
			Plant component2 = crop.SaplingPrefab.GetComponent<Plant>();
			Piece component3 = crop.SaplingPrefab.GetComponent<Piece>();
			if ((Object)(object)component == (Object)null || (Object)(object)component2 == (Object)null || (Object)(object)component3 == (Object)null)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Missing Pickable/Plant/Piece while linking item: " + crop.Id));
				itemLinksApplied = false;
				continue;
			}
			SetField(component, "m_itemPrefab", val);
			ReplaceDestroyedDropItems(crop.GrownPrefab, val, crop.Id);
			ApplyHarvestSettings(crop, updateExisting: false);
			Sprite val3 = null;
			if (val2.m_itemData.m_shared.m_icons != null && val2.m_itemData.m_shared.m_icons.Length != 0)
			{
				val3 = val2.m_itemData.GetIcon();
			}
			if ((Object)(object)val3 == (Object)null)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Japanese Food item icon is null: " + crop.ItemPrefab));
			}
			else
			{
				SetField(component3, "m_icon", val3);
			}
			SetField(component2, "m_name", val2.m_itemData.m_shared.m_name);
			SetField(component3, "m_name", val2.m_itemData.m_shared.m_name);
			SetField(component3, "m_description", "$piece_sakey_jpfarm_plant_desc");
			if (!SetSinglePlantingRequirement(component3, val2))
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Could not configure planting requirement for " + crop.Id));
				itemLinksApplied = false;
				continue;
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Japanese Food link complete: " + crop.Id + " | item=" + crop.ItemPrefab + " | plant cost=1 | harvest=" + crop.HarvestAmount.Value + " | scythe harvestable=true"));
		}
		_itemLinksApplied = itemLinksApplied;
	}

	private void VerifyCultivatorRegistration()
	{
		PieceTable val = ((PieceManager.Instance != null) ? PieceManager.Instance.GetPieceTable("_CultivatorPieceTable") : null);
		if ((Object)(object)val == (Object)null || val.m_pieces == null)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)"Cultivator table verification failed: table/list is null. _CultivatorPieceTable");
			return;
		}
		int num = 0;
		List<string> list = new List<string>();
		foreach (GameObject piece in val.m_pieces)
		{
			if ((Object)(object)piece == (Object)null)
			{
				list.Add("<null>");
				continue;
			}
			string name = ((Object)piece).name;
			list.Add(name);
			if (name.StartsWith("sakey_jpfarm_sapling_", StringComparison.Ordinal))
			{
				num++;
			}
		}
		((BaseUnityPlugin)this).Logger.LogInfo((object)("Cultivator table after Jotunn registration | total=" + val.m_pieces.Count + " | FARM=" + num + "/" + _crops.Count + " | entries=" + string.Join(", ", list.ToArray())));
		foreach (Crop crop in _crops)
		{
			if (!((Object)(object)crop.SaplingPrefab != (Object)null) || !val.m_pieces.Contains(crop.SaplingPrefab))
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("FARM piece was queued but is missing after Jotunn registration: " + crop.Id + " | prefab=" + (((Object)(object)crop.SaplingPrefab != (Object)null) ? ((Object)crop.SaplingPrefab).name : "<null>")));
			}
		}
	}

	private void ReplaceDestroyedDropItems(GameObject grownPrefab, GameObject itemPrefab, string cropId)
	{
		if ((Object)(object)grownPrefab == (Object)null || (Object)(object)itemPrefab == (Object)null)
		{
			return;
		}
		Component component = grownPrefab.GetComponent("DropOnDestroyed");
		if ((Object)(object)component == (Object)null)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("No DropOnDestroyed component on grown prefab: " + cropId));
			return;
		}
		if (!(GetFieldValue(GetFieldValue(component, "m_dropWhenDestroyed"), "m_drops") is IList list))
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("No DropOnDestroyed drop list: " + cropId));
			return;
		}
		int num = 0;
		for (int i = 0; i < list.Count; i++)
		{
			object obj = list[i];
			if (obj != null && SetField(obj, "m_item", itemPrefab))
			{
				list[i] = obj;
				num++;
			}
		}
		((BaseUnityPlugin)this).Logger.LogInfo((object)("Replaced destroyed-crop drops: " + cropId + " | item=" + ((Object)itemPrefab).name + " | entries=" + num));
	}

	private static bool SetSinglePlantingRequirement(Piece piece, ItemDrop itemDrop)
	{
		Type nestedType = typeof(Piece).GetNestedType("Requirement", BindingFlags.Public | BindingFlags.NonPublic);
		if (nestedType == null)
		{
			return false;
		}
		object obj = Activator.CreateInstance(nestedType);
		if (obj == null)
		{
			return false;
		}
		if (!SetField(obj, "m_resItem", itemDrop) || !SetField(obj, "m_amount", 1) || !SetField(obj, "m_amountPerLevel", 0) || !SetField(obj, "m_recover", false))
		{
			return false;
		}
		Array array = Array.CreateInstance(nestedType, 1);
		array.SetValue(obj, 0);
		return SetField(piece, "m_resources", array);
	}

	private static void ReplacePlantStage(Plant plant, string fieldName, GameObject model, string instanceName)
	{
		object fieldValue = GetFieldValue(plant, fieldName);
		GameObject val = (GameObject)((fieldValue is GameObject) ? fieldValue : null);
		if ((Object)(object)val == (Object)null)
		{
			throw new InvalidOperationException("Plant stage object is null: " + fieldName);
		}
		for (int num = val.transform.childCount - 1; num >= 0; num--)
		{
			Object.DestroyImmediate((Object)(object)((Component)val.transform.GetChild(num)).gameObject);
		}
		Renderer[] components = val.GetComponents<Renderer>();
		for (int i = 0; i < components.Length; i++)
		{
			Object.DestroyImmediate((Object)(object)components[i]);
		}
		MeshFilter[] components2 = val.GetComponents<MeshFilter>();
		for (int i = 0; i < components2.Length; i++)
		{
			Object.DestroyImmediate((Object)(object)components2[i]);
		}
		LODGroup[] components3 = val.GetComponents<LODGroup>();
		for (int i = 0; i < components3.Length; i++)
		{
			Object.DestroyImmediate((Object)(object)components3[i]);
		}
		GameObject obj = Object.Instantiate<GameObject>(model, val.transform, false);
		((Object)obj).name = "SakeyFARM_" + instanceName;
		StripCollidersAndRigidbodies(obj);
		obj.SetActive(true);
	}

	private static void ReplaceGrownVisual(GameObject grownPrefab, GameObject model)
	{
		Renderer[] componentsInChildren = grownPrefab.GetComponentsInChildren<Renderer>(true);
		for (int i = 0; i < componentsInChildren.Length; i++)
		{
			componentsInChildren[i].enabled = false;
		}
		GameObject obj = Object.Instantiate<GameObject>(model, grownPrefab.transform, false);
		((Object)obj).name = "SakeyFARM_GrownVisual";
		StripCollidersAndRigidbodies(obj);
		obj.SetActive(true);
	}

	private static void StripCollidersAndRigidbodies(GameObject root)
	{
		Collider[] componentsInChildren = root.GetComponentsInChildren<Collider>(true);
		for (int i = 0; i < componentsInChildren.Length; i++)
		{
			Object.DestroyImmediate((Object)(object)componentsInChildren[i]);
		}
		Rigidbody[] componentsInChildren2 = root.GetComponentsInChildren<Rigidbody>(true);
		for (int i = 0; i < componentsInChildren2.Length; i++)
		{
			Object.DestroyImmediate((Object)(object)componentsInChildren2[i]);
		}
	}

	private static FieldInfo FindField(Type type, string fieldName)
	{
		while (type != null)
		{
			FieldInfo field = type.GetField(fieldName, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (field != null)
			{
				return field;
			}
			type = type.BaseType;
		}
		return null;
	}

	private static object GetFieldValue(object target, string fieldName)
	{
		if (target == null)
		{
			return null;
		}
		FieldInfo fieldInfo = FindField(target.GetType(), fieldName);
		if (!(fieldInfo != null))
		{
			return null;
		}
		return fieldInfo.GetValue(target);
	}

	private static bool SetField(object target, string fieldName, object value)
	{
		if (target == null)
		{
			return false;
		}
		FieldInfo fieldInfo = FindField(target.GetType(), fieldName);
		if (fieldInfo == null)
		{
			return false;
		}
		try
		{
			fieldInfo.SetValue(target, value);
			return true;
		}
		catch (Exception)
		{
			return false;
		}
	}

	private void OnDestroy()
	{
		PrefabManager.OnVanillaPrefabsAvailable -= BuildCropPrefabs;
		ItemManager.OnItemsRegistered -= ApplyJapaneseFoodLinks;
		PieceManager.OnPiecesRegistered -= VerifyCultivatorRegistration;
		if (_growthMultiplier != null)
		{
			_growthMultiplier.SettingChanged -= OnGrowthConfigChanged;
		}
		if (_kabotyaGrowMin != null)
		{
			_kabotyaGrowMin.SettingChanged -= OnGrowthConfigChanged;
		}
		if (_kabotyaGrowMax != null)
		{
			_kabotyaGrowMax.SettingChanged -= OnGrowthConfigChanged;
		}
		if (_okomeGrowMin != null)
		{
			_okomeGrowMin.SettingChanged -= OnGrowthConfigChanged;
		}
		if (_okomeGrowMax != null)
		{
			_okomeGrowMax.SettingChanged -= OnGrowthConfigChanged;
		}
		if (_mameGrowMin != null)
		{
			_mameGrowMin.SettingChanged -= OnGrowthConfigChanged;
		}
		if (_mameGrowMax != null)
		{
			_mameGrowMax.SettingChanged -= OnGrowthConfigChanged;
		}
		if (_allowMeadows != null)
		{
			_allowMeadows.SettingChanged -= OnGrowthConfigChanged;
		}
		if (_allowBlackForest != null)
		{
			_allowBlackForest.SettingChanged -= OnGrowthConfigChanged;
		}
		if (_allowPlains != null)
		{
			_allowPlains.SettingChanged -= OnGrowthConfigChanged;
		}
		if (_allowAshlands != null)
		{
			_allowAshlands.SettingChanged -= OnGrowthConfigChanged;
		}
		if (_kabotyaYield != null)
		{
			_kabotyaYield.SettingChanged -= OnHarvestConfigChanged;
		}
		if (_okomeYield != null)
		{
			_okomeYield.SettingChanged -= OnHarvestConfigChanged;
		}
		if (_mameYield != null)
		{
			_mameYield.SettingChanged -= OnHarvestConfigChanged;
		}
	}
}