Decompiled source of EnhancedStorage v1.1.6

Mods/EnhancedStorages.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using EnhancedStorageMod;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppScheduleOne.UI;
using MelonLoader;
using MelonLoader.Preferences;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: MelonInfo(typeof(EnhancedStorage), "Enhanced Storage", "1.1.6", "Nebouh", null)]
[assembly: MelonGame("TVGS", "Schedule I")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("EnhancedStorages")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+d37a9b2a51543376d9072d136199183a9fe9f707")]
[assembly: AssemblyProduct("EnhancedStorages")]
[assembly: AssemblyTitle("EnhancedStorages")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 EnhancedStorageMod
{
	public class EnhancedStorage : MelonMod
	{
		[CompilerGenerated]
		private sealed class <DelayedAfterLoad>d__3 : IEnumerator<object>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private object <>2__current;

			public EnhancedStorage <>4__this;

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

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

			[DebuggerHidden]
			public <DelayedAfterLoad>d__3(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(2f);
					<>1__state = 1;
					return true;
				case 1:
					<>1__state = -1;
					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();
			}
		}

		private static bool isPatched;

		public override void OnInitializeMelon()
		{
			if (StorageSettings.LoadPreferences())
			{
				StorageSettings.InitializeSettings();
				StoragePatcher.PatchStorage();
				MelonLogger.Msg("[Enhanced Storage] Successfully initialized.");
			}
		}

		private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			if (((Scene)(ref scene)).name.Equals("Main", StringComparison.OrdinalIgnoreCase) && !isPatched)
			{
				MelonCoroutines.Start(DelayedAfterLoad());
				MelonLogger.Msg("[Enhanced Vehicules] Scene loaded: " + ((Scene)(ref scene)).name + ", now patching...");
				StoragePatcher.PatchStorage();
				isPatched = true;
			}
		}

		[IteratorStateMachine(typeof(<DelayedAfterLoad>d__3))]
		private IEnumerator DelayedAfterLoad()
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <DelayedAfterLoad>d__3(0)
			{
				<>4__this = this
			};
		}
	}
	internal static class StoragePatcher
	{
		[HarmonyPatch(typeof(StorageMenu), "Awake")]
		private static class StorageMenuPatch
		{
			[HarmonyPrefix]
			private static void Prefix(StorageMenu __instance)
			{
				//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
				try
				{
					int value = StorageSettings.GameMaxSlots.Value;
					if (value <= 20)
					{
						return;
					}
					RectTransform container = __instance.Container;
					Transform val = ((container != null) ? ((Transform)container).Find("Slots") : null);
					if (!((Object)(object)val == (Object)null))
					{
						List<ItemSlotUI> list = new List<ItemSlotUI>((IEnumerable<ItemSlotUI>)__instance.SlotsUIs);
						while (val.childCount < value)
						{
							GameObject gameObject = ((Component)val.GetChild(0)).gameObject;
							GameObject val2 = Object.Instantiate<GameObject>(gameObject, val, true);
							((Object)val2).name = ((Object)val2).name.Replace("Clone", $"Extra-[{val.childCount - 1}]");
							val2.SetActive(true);
							val2.transform.localScale = Vector3.one;
							ItemSlotUI item = val2.GetComponent<ItemSlotUI>() ?? val2.AddComponent<ItemSlotUI>();
							list.Add(item);
						}
						__instance.SlotsUIs = Il2CppReferenceArray<ItemSlotUI>.op_Implicit(list.ToArray());
						MelonLogger.Msg($"[Enhanced Vehicules] StorageMenu slots expanded to {val.childCount}.");
					}
				}
				catch (Exception ex)
				{
					MelonLogger.Error("[Enhanced Vehicules] StorageMenu Patch error: " + ex.Message);
				}
			}
		}

		private static Type storageEntityType;

		public static void PatchStorage()
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Expected O, but got Unknown
			try
			{
				storageEntityType = Type.GetType("Il2CppScheduleOne.Storage.StorageEntity, Assembly-CSharp");
				if (storageEntityType == null)
				{
					MelonLogger.Error("[Enhanced Storage] StorageEntity type not found!");
					return;
				}
				Harmony val = new Harmony("com.enhancedstorage.patch");
				val.Patch((MethodBase)storageEntityType.GetMethod("Awake", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic), new HarmonyMethod(typeof(StoragePatcher), "StorageEntityInitialize_Prefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				MelonLogger.Msg("[Enhanced Storage] StorageEntity patched successfully.");
			}
			catch (Exception ex)
			{
				MelonLogger.Error("[Enhanced Storage] Patch error: " + ex.Message);
			}
		}

		private static bool StorageEntityInitialize_Prefix(object __instance)
		{
			try
			{
				MonoBehaviour val = (MonoBehaviour)((__instance is MonoBehaviour) ? __instance : null);
				if (val == null)
				{
					return true;
				}
				foreach (KeyValuePair<string, StorageSettings.RackSettings> rackConfig in StorageSettings.RackConfigs)
				{
					if (!((Object)((Component)val).gameObject).name.Contains(rackConfig.Key))
					{
						continue;
					}
					int num = Mathf.Min(rackConfig.Value.Slots, StorageSettings.GameMaxSlots.Value);
					int rows = rackConfig.Value.Rows;
					SetFieldOrProperty(__instance, "SlotCount", num);
					SetFieldOrProperty(__instance, "DisplayRowCount", rows);
					__instance.GetType().GetMethod("SetupSlots", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.Invoke(__instance, null);
					MelonLogger.Msg($"[Enhanced Storage] Patched {((Object)((Component)val).gameObject).name} (Slots: {num}, Rows: {rows})");
					break;
				}
			}
			catch (Exception ex)
			{
				MelonLogger.Error("[Enhanced Storage] Prefix error: " + ex.Message);
			}
			return true;
		}

		private static void SetFieldOrProperty(object target, string name, object value)
		{
			Type type = storageEntityType;
			PropertyInfo property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (property != null)
			{
				property.SetValue(target, value);
				return;
			}
			FieldInfo field = type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (field != null)
			{
				field.SetValue(target, value);
			}
			else
			{
				MelonLogger.Warning("[Enhanced Storage] Field or property '" + name + "' not found on " + type.Name);
			}
		}
	}
	internal static class StorageSettings
	{
		public struct RackSettings
		{
			public string Key;

			public string Label;

			public int DefaultSlots;

			public int DefaultRows;

			public int Slots;

			public int Rows;

			public MelonPreferences_Entry<int> PrefSlots;

			public MelonPreferences_Entry<int> PrefRows;
		}

		public static MelonPreferences_Category Category;

		public static MelonPreferences_Entry<bool> EnableMod;

		public static MelonPreferences_Entry<bool> UseDefaultSettings;

		public static MelonPreferences_Entry<int> GameMaxSlots;

		public static readonly Dictionary<string, RackSettings> RackConfigs = new Dictionary<string, RackSettings>
		{
			["StorageRack_Small"] = new RackSettings
			{
				Key = "SmallRack",
				Label = "Small Rack",
				DefaultSlots = 4,
				DefaultRows = 1
			},
			["StorageRack_Medium"] = new RackSettings
			{
				Key = "MediumRack",
				Label = "Medium Rack",
				DefaultSlots = 6,
				DefaultRows = 1
			},
			["StorageRack_Large"] = new RackSettings
			{
				Key = "LargeRack",
				Label = "Large Rack",
				DefaultSlots = 8,
				DefaultRows = 2
			},
			["WallMountedShelf_Built"] = new RackSettings
			{
				Key = "WallMountShelf",
				Label = "Wall Mount Shelf",
				DefaultSlots = 4,
				DefaultRows = 1
			},
			["DisplayCabinet"] = new RackSettings
			{
				Key = "DisplayCabinet",
				Label = "Display Cabinet",
				DefaultSlots = 4,
				DefaultRows = 1
			},
			["WoodSquareTable"] = new RackSettings
			{
				Key = "WoodSquareTable",
				Label = "Wood Square Table",
				DefaultSlots = 3,
				DefaultRows = 1
			},
			["MetalSquareTable"] = new RackSettings
			{
				Key = "MetalSquareTable",
				Label = "Metal Square Table",
				DefaultSlots = 3,
				DefaultRows = 1
			},
			["Safe"] = new RackSettings
			{
				Key = "Safe",
				Label = "Safe",
				DefaultSlots = 8,
				DefaultRows = 2
			},
			["CoffeeTable"] = new RackSettings
			{
				Key = "CoffeeTable",
				Label = "CoffeeTable",
				DefaultSlots = 3,
				DefaultRows = 1
			},
			["PalletStand"] = new RackSettings
			{
				Key = "PalletStand",
				Label = "PalletStand",
				DefaultSlots = 3,
				DefaultRows = 1
			}
		};

		public static bool LoadPreferences()
		{
			Category = MelonPreferences.CreateCategory("EnhancedStorage", "Enhanced Storage Settings");
			EnableMod = Category.CreateEntry<bool>("EnableMod", true, "Enable this mod", (string)null, false, false, (ValueValidator)null, (string)null);
			if (!EnableMod.Value)
			{
				MelonLogger.Warning("[Enhanced Storage] Mod is disabled via preferences.");
				return false;
			}
			UseDefaultSettings = Category.CreateEntry<bool>("UseDefaultSettings", false, "Use default rack settings", (string)null, false, false, (ValueValidator)null, (string)null);
			GameMaxSlots = Category.CreateEntry<int>("GameMaxSlots", 20, "Maximum total slots in the game", (string)null, false, false, (ValueValidator)null, (string)null);
			return true;
		}

		public static void InitializeSettings()
		{
			foreach (string item in RackConfigs.Keys.ToList())
			{
				RackSettings value = RackConfigs[item];
				value.PrefSlots = Category.CreateEntry<int>(value.Key + "Slots", value.DefaultSlots, value.Label + " - Number of Slots", (string)null, false, false, (ValueValidator)null, (string)null);
				value.PrefRows = Category.CreateEntry<int>(value.Key + "Rows", value.DefaultRows, value.Label + " - Number of Rows", (string)null, false, false, (ValueValidator)null, (string)null);
				value.Slots = (UseDefaultSettings.Value ? value.DefaultSlots : value.PrefSlots.Value);
				value.Rows = (UseDefaultSettings.Value ? value.DefaultRows : value.PrefRows.Value);
				RackConfigs[item] = value;
			}
		}
	}
}