Decompiled source of Chemist Routes v1.0.0

Mods/WoodStudios.ChemistRoutes.dll

Decompiled 19 minutes 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 System.Security;
using System.Security.Permissions;
using System.Text.Json;
using ChemistRoutes;
using HarmonyLib;
using Il2CppFishNet;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppScheduleOne.Core.Items.Framework;
using Il2CppScheduleOne.DevUtilities;
using Il2CppScheduleOne.Employees;
using Il2CppScheduleOne.ItemFramework;
using Il2CppScheduleOne.Management;
using Il2CppScheduleOne.NPCs;
using Il2CppScheduleOne.NPCs.Behaviour;
using Il2CppScheduleOne.Persistence;
using Il2CppScheduleOne.Persistence.Datas;
using Il2CppScheduleOne.UI.Management;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using MelonLoader;
using MelonLoader.Preferences;
using MelonLoader.Utils;
using Microsoft.CodeAnalysis;
using S1API.Lifecycle;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(Core), "Chemist Routes", "1.0.0", "Wood Studios", null)]
[assembly: MelonGame("TVGS", "Schedule I")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ChemistRoutes
{
	public class Core : MelonMod
	{
		internal static Instance Log;

		internal static MelonPreferences_Entry<int> MaxRoutes;

		internal static MelonPreferences_Entry<bool> Enabled;

		public override void OnInitializeMelon()
		{
			Log = ((MelonBase)this).LoggerInstance;
			MelonPreferences_Category obj = MelonPreferences.CreateCategory("ChemistRoutes", "Chemist Routes");
			Enabled = obj.CreateEntry<bool>("Enabled", true, "Enabled", "Chemists run their routes when they have no station work.", false, false, (ValueValidator)null, (string)null);
			MaxRoutes = obj.CreateEntry<int>("MaxRoutes", 5, "Routes per chemist", "How many routes each chemist can have (packagers have 5).", false, false, (ValueValidator)null, (string)null);
			GameLifecycle.OnLoadComplete += Routes.OnLoaded;
			GameLifecycle.OnSaveStart += Routes.OnSaving;
			GameLifecycle.OnPreSceneChange += Routes.Reset;
			Log.Msg("Chemist Routes ready: open a chemist on the management clipboard to add routes.");
		}
	}
	internal static class Routes
	{
		private sealed class RouteRec
		{
			public string Src { get; set; }

			public string Dst { get; set; }

			public int Mode { get; set; }

			public List<string> Items { get; set; } = new List<string>();
		}

		private sealed class SaveDoc
		{
			public int Version { get; set; } = 1;

			public string Created { get; set; }

			public Dictionary<string, List<RouteRec>> Chemists { get; set; } = new Dictionary<string, List<RouteRec>>();
		}

		private static readonly Dictionary<IntPtr, RouteListField> Fields = new Dictionary<IntPtr, RouteListField>();

		private static readonly Dictionary<IntPtr, float> NextTry = new Dictionary<IntPtr, float>();

		private static SaveDoc _pending;

		private static bool _ready;

		public static RouteListField Get(ChemistConfiguration cfg, bool create = true)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			if (cfg == null)
			{
				return null;
			}
			IntPtr pointer = ((Il2CppObjectBase)cfg).Pointer;
			if (Fields.TryGetValue(pointer, out var value) && value != null)
			{
				return value;
			}
			if (!create)
			{
				return null;
			}
			value = new RouteListField((EntityConfiguration)(object)cfg);
			value.MaxRoutes = Mathf.Clamp(Core.MaxRoutes.Value, 1, 12);
			Fields[pointer] = value;
			return value;
		}

		public static void TryRoute(Chemist c)
		{
			if (!Core.Enabled.Value || (Object)(object)c == (Object)null)
			{
				return;
			}
			try
			{
				if (!InstanceFinder.IsServer)
				{
					return;
				}
				RouteListField val = Get(c.configuration, create: false);
				if (val == null || val.Routes == null || val.Routes.Count == 0)
				{
					return;
				}
				MoveItemBehaviour moveItemBehaviour = ((Employee)c).MoveItemBehaviour;
				if ((Object)(object)moveItemBehaviour == (Object)null || ((Behaviour)moveItemBehaviour).Active || ((Behaviour)moveItemBehaviour).Enabled || Busy(c))
				{
					return;
				}
				IntPtr pointer = ((Il2CppObjectBase)c).Pointer;
				if (NextTry.TryGetValue(pointer, out var value) && Time.time < value)
				{
					return;
				}
				NextTry[pointer] = Time.time + 1.5f;
				for (int i = 0; i < val.Routes.Count; i++)
				{
					AdvancedTransitRoute val2 = val.Routes[i];
					if (val2 != null && ((TransitRoute)val2).AreEntitiesNonNull())
					{
						ItemInstance itemReadyToMove = val2.GetItemReadyToMove();
						if (itemReadyToMove != null && ((NPC)c).Movement.CanGetTo(((TransitRoute)val2).Source, 1f) && ((NPC)c).Movement.CanGetTo(((TransitRoute)val2).Destination, 1f))
						{
							moveItemBehaviour.Initialize((TransitRoute)(object)val2, itemReadyToMove, ((BaseItemInstance)itemReadyToMove).Quantity, false);
							((Behaviour)moveItemBehaviour).Enable_Networked();
							((Employee)c).SetIdle(false);
							((Employee)c).MarkIsWorking();
							break;
						}
					}
				}
			}
			catch (Exception ex)
			{
				Core.Log.Warning("Route: " + ex.Message);
			}
		}

		private static bool Busy(Chemist c)
		{
			if (!On((Behaviour)(object)c.StartChemistryStationBehaviour) && !On((Behaviour)(object)c.StartLabOvenBehaviour) && !On((Behaviour)(object)c.FinishLabOvenBehaviour) && !On((Behaviour)(object)c.StartCauldronBehaviour))
			{
				return On((Behaviour)(object)c.StartMixingStationBehaviour);
			}
			return true;
		}

		private static bool On(Behaviour b)
		{
			if ((Object)(object)b != (Object)null)
			{
				if (!b.Enabled)
				{
					return b.Active;
				}
				return true;
			}
			return false;
		}

		public static void BindPanel(ChemistConfigPanel panel, List<EntityConfiguration> configs)
		{
			try
			{
				RouteListFieldUI val = EnsureUi(panel);
				if ((Object)(object)val == (Object)null)
				{
					return;
				}
				List<RouteListField> val2 = new List<RouteListField>();
				for (int i = 0; i < configs.Count; i++)
				{
					EntityConfiguration obj = configs[i];
					ChemistConfiguration val3 = ((obj != null) ? ((Il2CppObjectBase)obj).TryCast<ChemistConfiguration>() : null);
					if (val3 != null)
					{
						val2.Add(Get(val3));
					}
				}
				val.Bind(val2);
			}
			catch (Exception ex)
			{
				Core.Log.Warning("Clipboard: " + ex.Message);
			}
		}

		private static RouteListFieldUI EnsureUi(ChemistConfigPanel panel)
		{
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			Transform val = ((Component)panel).transform.Find("CR_Routes");
			if ((Object)(object)val == (Object)null && (Object)(object)panel.StationsUI != (Object)null)
			{
				val = ((Component)panel.StationsUI).transform.parent.Find("CR_Routes");
			}
			if ((Object)(object)val != (Object)null)
			{
				return ((Component)val).GetComponent<RouteListFieldUI>();
			}
			PackagerConfigPanel val2 = PackagerPrefab();
			if ((Object)(object)val2 == (Object)null || (Object)(object)val2.RoutesUI == (Object)null || (Object)(object)panel.StationsUI == (Object)null)
			{
				Core.Log.Warning("Couldn't find the packager's route list to copy.");
				return null;
			}
			RectTransform component = ((Component)val2.StationsUI).GetComponent<RectTransform>();
			RectTransform component2 = ((Component)val2.RoutesUI).GetComponent<RectTransform>();
			RectTransform component3 = ((Component)panel.StationsUI).GetComponent<RectTransform>();
			GameObject obj = Object.Instantiate<GameObject>(((Component)val2.RoutesUI).gameObject, ((Transform)component3).parent, false);
			((Object)obj).name = "CR_Routes";
			obj.SetActive(true);
			obj.GetComponent<RectTransform>().anchoredPosition = component3.anchoredPosition + (component2.anchoredPosition - component.anchoredPosition) + new Vector2(0f, -36f);
			obj.transform.SetSiblingIndex(((Transform)component3).GetSiblingIndex() + 1);
			RectTransform component4 = ((Component)panel).GetComponent<RectTransform>();
			RectTransform component5 = ((Component)val2).GetComponent<RectTransform>();
			if ((Object)(object)component4 != (Object)null && (Object)(object)component5 != (Object)null && component5.sizeDelta.y > component4.sizeDelta.y)
			{
				component4.sizeDelta = new Vector2(component4.sizeDelta.x, component5.sizeDelta.y);
			}
			Core.Log.Msg("Added Routes to the chemist clipboard page.");
			return obj.GetComponent<RouteListFieldUI>();
		}

		private static PackagerConfigPanel PackagerPrefab()
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Invalid comparison between Unknown and I4
			ManagementInterface val = Singleton<ManagementInterface>.Instance ?? Object.FindObjectOfType<ManagementInterface>(true);
			if ((Object)(object)val == (Object)null || val.ConfigPanelPrefabs == null)
			{
				return null;
			}
			foreach (ConfigurableTypePanel item in (Il2CppArrayBase<ConfigurableTypePanel>)(object)val.ConfigPanelPrefabs)
			{
				if (item != null && (int)item.Type == 4 && (Object)(object)item.Panel != (Object)null)
				{
					return ((Il2CppObjectBase)item.Panel).TryCast<PackagerConfigPanel>();
				}
			}
			return null;
		}

		public static void Reset()
		{
			Fields.Clear();
			NextTry.Clear();
			_pending = null;
			_ready = false;
		}

		private static string FilePath()
		{
			try
			{
				LoadManager instance = Singleton<LoadManager>.Instance;
				object obj;
				if (instance == null)
				{
					obj = null;
				}
				else
				{
					SaveInfo activeSaveInfo = instance.ActiveSaveInfo;
					obj = ((activeSaveInfo != null) ? activeSaveInfo.SavePath : null);
				}
				string text = (string)obj;
				if (string.IsNullOrEmpty(text))
				{
					return null;
				}
				string text2 = Path.Combine(MelonEnvironment.UserDataDirectory, "ChemistRoutes");
				Directory.CreateDirectory(text2);
				return Path.Combine(text2, Path.GetFileName(text.TrimEnd('/', '\\')) + ".json");
			}
			catch
			{
				return null;
			}
		}

		private static string Stamp()
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				DateTime dateCreated = Singleton<LoadManager>.Instance.ActiveSaveInfo.DateCreated;
				long ticks = ((DateTime)(ref dateCreated)).Ticks;
				return (ticks > 0) ? ticks.ToString() : "";
			}
			catch
			{
				return "";
			}
		}

		public static void OnLoaded()
		{
			Reset();
			_ready = true;
			try
			{
				if (InstanceFinder.IsClient && !InstanceFinder.IsServer)
				{
					return;
				}
			}
			catch
			{
			}
			string text = FilePath();
			if (text == null || !File.Exists(text))
			{
				return;
			}
			try
			{
				SaveDoc saveDoc = JsonSerializer.Deserialize<SaveDoc>(File.ReadAllText(text));
				string text2 = Stamp();
				if (saveDoc != null && !string.IsNullOrEmpty(saveDoc.Created) && text2.Length > 0 && saveDoc.Created != text2)
				{
					Core.Log.Msg("New game in a used save slot: old chemist routes set aside.");
					File.Move(text, text + ".previous-game", overwrite: true);
				}
				else
				{
					_pending = saveDoc;
					MelonCoroutines.Start(Restore());
				}
			}
			catch (Exception ex)
			{
				Core.Log.Warning("Couldn't read saved routes: " + ex.Message);
			}
		}

		private static IEnumerator Restore()
		{
			for (int i = 0; i < 6; i++)
			{
				yield return (object)new WaitForSeconds(1f);
			}
			SaveDoc pending = _pending;
			_pending = null;
			if (pending?.Chemists == null)
			{
				yield break;
			}
			int num = 0;
			int num2 = 0;
			foreach (Chemist item in Object.FindObjectsOfType<Chemist>())
			{
				if ((Object)(object)item == (Object)null)
				{
					continue;
				}
				string key;
				try
				{
					key = ((object)((NPC)item).GUID/*cast due to .constrained prefix*/).ToString();
				}
				catch
				{
					continue;
				}
				if (!pending.Chemists.TryGetValue(key, out var value) || value == null || value.Count == 0)
				{
					continue;
				}
				try
				{
					List<AdvancedTransitRouteData> val = new List<AdvancedTransitRouteData>();
					foreach (RouteRec item2 in value)
					{
						List<string> val2 = new List<string>();
						foreach (string item3 in item2.Items ?? new List<string>())
						{
							val2.Add(item3);
						}
						val.Add(new AdvancedTransitRouteData(item2.Src, item2.Dst, (EMode)item2.Mode, val2));
					}
					RouteListField val3 = Get(item.configuration);
					val3.Load(new RouteListData(val));
					for (int num3 = val3.Routes.Count - 1; num3 >= 0; num3--)
					{
						AdvancedTransitRoute val4 = val3.Routes[num3];
						if (val4 == null || !((TransitRoute)val4).AreEntitiesNonNull())
						{
							val3.RemoveItem(val4);
						}
					}
					num += val3.Routes.Count;
					num2++;
				}
				catch (Exception ex)
				{
					Core.Log.Warning("Couldn't restore routes for a chemist: " + ex.Message);
				}
			}
			if (num2 > 0)
			{
				Core.Log.Msg($"Restored {num} route(s) for {num2} chemist(s).");
			}
		}

		public static void OnSaving()
		{
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Expected I4, but got Unknown
			if (!_ready)
			{
				return;
			}
			try
			{
				if (InstanceFinder.IsClient && !InstanceFinder.IsServer)
				{
					return;
				}
			}
			catch
			{
			}
			string text = FilePath();
			if (text == null)
			{
				return;
			}
			SaveDoc saveDoc = new SaveDoc
			{
				Created = Stamp()
			};
			if (_pending != null)
			{
				saveDoc.Chemists = _pending.Chemists;
			}
			foreach (Chemist item in Object.FindObjectsOfType<Chemist>())
			{
				if ((Object)(object)item == (Object)null)
				{
					continue;
				}
				RouteListField val = Get(item.configuration, create: false);
				if (val == null)
				{
					continue;
				}
				string key;
				try
				{
					key = ((object)((NPC)item).GUID/*cast due to .constrained prefix*/).ToString();
				}
				catch
				{
					continue;
				}
				List<RouteRec> list = new List<RouteRec>();
				try
				{
					RouteListData data = val.GetData();
					if (((data != null) ? data.Routes : null) != null)
					{
						for (int i = 0; i < data.Routes.Count; i++)
						{
							AdvancedTransitRouteData val2 = data.Routes[i];
							if (val2 == null || string.IsNullOrEmpty(val2.SourceGUID) || string.IsNullOrEmpty(val2.DestinationGUID))
							{
								continue;
							}
							RouteRec routeRec = new RouteRec
							{
								Src = val2.SourceGUID,
								Dst = val2.DestinationGUID,
								Mode = (int)val2.FilterMode
							};
							if (val2.FilterItemIDs != null)
							{
								for (int j = 0; j < val2.FilterItemIDs.Count; j++)
								{
									routeRec.Items.Add(val2.FilterItemIDs[j]);
								}
							}
							list.Add(routeRec);
						}
					}
				}
				catch (Exception ex)
				{
					Core.Log.Warning("Couldn't read a chemist's routes: " + ex.Message);
					continue;
				}
				if (list.Count > 0)
				{
					saveDoc.Chemists[key] = list;
				}
				else
				{
					saveDoc.Chemists.Remove(key);
				}
			}
			try
			{
				string text2 = text + ".tmp";
				File.WriteAllText(text2, JsonSerializer.Serialize(saveDoc, new JsonSerializerOptions
				{
					WriteIndented = true
				}));
				File.Move(text2, text, overwrite: true);
			}
			catch (Exception ex2)
			{
				Core.Log.Warning("Couldn't save routes: " + ex2.Message);
			}
		}
	}
	[HarmonyPatch(typeof(Chemist), "TryStartNewTask")]
	internal static class ChemistTaskPatch
	{
		private static void Postfix(Chemist __instance)
		{
			Routes.TryRoute(__instance);
		}
	}
	[HarmonyPatch(typeof(ChemistConfigPanel), "BindInternal")]
	internal static class ChemistPanelPatch
	{
		private static void Postfix(ChemistConfigPanel __instance, List<EntityConfiguration> configs)
		{
			Routes.BindPanel(__instance, configs);
		}
	}
}