Decompiled source of ItemTweaker v0.3.1

ItemTweaker/ItemTweaker.dll

Decompiled 17 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using GKAPI;
using GKAPI.Items;
using Gatekeeper.Infrastructure.Providers.InfoProviders;
using Gatekeeper.Items;
using Gatekeeper.MainMenuScripts.Database;
using Gatekeeper.MainMenuScripts.Database.ItemsDatabaseController;
using HarmonyLib;
using Il2CppSystem.Collections.Generic;
using ItemTweakerMod;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("ItemTweaker")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("ItemTweaker")]
[assembly: AssemblyTitle("ItemTweaker")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace ItemTweaker
{
	[BepInPlugin("com.yourname.itemtweaker", "Item Tweaker", "0.7.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BasePlugin
	{
		private readonly struct ChangedParamModificationKey : IEquatable<ChangedParamModificationKey>
		{
			public readonly ItemParamModificationType ModificationType;

			public readonly int FirstHash;

			public readonly int OtherHash;

			public ChangedParamModificationKey(ItemParamModificationType modificationType, float first, float other)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				ModificationType = modificationType;
				FirstHash = QuantizeFloatKey(first);
				OtherHash = QuantizeFloatKey(other);
			}

			public bool Equals(ChangedParamModificationKey other)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				if (ModificationType == other.ModificationType && FirstHash == other.FirstHash)
				{
					return OtherHash == other.OtherHash;
				}
				return false;
			}

			public override bool Equals(object obj)
			{
				if (obj is ChangedParamModificationKey other)
				{
					return Equals(other);
				}
				return false;
			}

			public override int GetHashCode()
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return HashCode.Combine<ItemParamModificationType, int, int>(ModificationType, FirstHash, OtherHash);
			}
		}

		private readonly struct ChangedGrowthModifierKey : IEquatable<ChangedGrowthModifierKey>
		{
			public readonly ItemID ItemId;

			public readonly ItemParamModificationType ModificationType;

			public ChangedGrowthModifierKey(ItemID itemId, ItemParamModificationType modificationType)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0002: 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_0009: Unknown result type (might be due to invalid IL or missing references)
				ItemId = itemId;
				ModificationType = modificationType;
			}

			public bool Equals(ChangedGrowthModifierKey other)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: 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)
				//IL_0015: Unknown result type (might be due to invalid IL or missing references)
				if (ItemId == other.ItemId)
				{
					return ModificationType == other.ModificationType;
				}
				return false;
			}

			public override bool Equals(object obj)
			{
				if (obj is ChangedGrowthModifierKey other)
				{
					return Equals(other);
				}
				return false;
			}

			public override int GetHashCode()
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				return HashCode.Combine<ItemID, ItemParamModificationType>(ItemId, ModificationType);
			}
		}

		private readonly struct GameplayGrowthValue
		{
			public readonly float First;

			public readonly float Other;

			public readonly ItemParamGrowthType GrowthType;

			public GameplayGrowthValue(float first, float other, ItemParamGrowthType growthType)
			{
				//IL_000f: 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)
				First = first;
				Other = other;
				GrowthType = growthType;
			}
		}

		internal static ManualLogSource Log;

		private static readonly List<string> UiDebugEntries = new List<string>();

		private static readonly object UiDebugLock = new object();

		private static readonly HashSet<ChangedParamModificationKey> ChangedParamModifications = new HashSet<ChangedParamModificationKey>();

		private static readonly HashSet<ChangedGrowthModifierKey> ChangedGrowthModifiers = new HashSet<ChangedGrowthModifierKey>();

		private static readonly HashSet<ChangedGrowthModifierKey> NativeBaselineGrowthModifiers = new HashSet<ChangedGrowthModifierKey>();

		private static readonly Dictionary<ChangedGrowthModifierKey, GameplayGrowthValue> GameplayGrowthValues = new Dictionary<ChangedGrowthModifierKey, GameplayGrowthValue>();

		private static readonly Dictionary<Type, MethodInfo> GetItemQuantityMethods = new Dictionary<Type, MethodInfo>();

		private static readonly Dictionary<ItemID, int> CurrentItemQuantities = new Dictionary<ItemID, int>();

		private static readonly HashSet<ItemID> ChangedItemIds = new HashSet<ItemID>();

		private static readonly string Folder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Thunderstore Mod Manager", "DataFolder", "Gatekeeper", "profiles", "kakahas", "BepInEx", "plugins", "ItemTweaker");

		private static readonly string DatabasePath = Path.Combine(Folder, "ItemsDatabase.json");

		private static readonly string ConfigPath = Path.Combine(Folder, "ItemsConfig.json");

		private static readonly List<MethodInfo> ThunderAcquireMethods = new List<MethodInfo>();

		private static readonly List<MethodInfo> ThunderLostMethods = new List<MethodInfo>();

		private static MethodInfo ThunderStopMethod;

		private static MethodInfo ThunderPlayLoopMethod;

		private static FieldInfo ThunderRadiusField;

		private static PropertyInfo ThunderRadiusProperty;

		private static Type ThunderRingControllerType;

		private static bool ThunderRingFixInstalled;

		private static string CachedPerStackSuffix = " per stack";

		private static bool _useRussianPerStackSuffix;

		public override void Load()
		{
			Log = ((BasePlugin)this).Log;
			Log.LogInfo((object)"==============================");
			Log.LogInfo((object)"Item Tweaker loaded!");
			Log.LogInfo((object)"Version 0.7.3");
			Log.LogInfo((object)"==============================");
			Log.LogInfo((object)("[PATH] ItemTweaker folder: " + Folder));
			Log.LogInfo((object)("[PATH] ItemsDatabase: " + DatabasePath));
			Log.LogInfo((object)("[PATH] ItemsConfig: " + ConfigPath));
			Directory.CreateDirectory(Folder);
			EventHandler.LateInit = (Action)Delegate.Combine(EventHandler.LateInit, new Action(OnLateInit));
		}

		private static void OnLateInit()
		{
			try
			{
				Log.LogInfo((object)"==============================");
				Log.LogInfo((object)"Item Tweaker initialization");
				Log.LogInfo((object)"==============================");
				if (!File.Exists(DatabasePath))
				{
					Log.LogInfo((object)"ItemsDatabase.json not found.");
					Log.LogInfo((object)"Creating original database export...");
					ExportItems(DatabasePath);
					Log.LogInfo((object)"ItemsDatabase.json created.");
				}
				else
				{
					Log.LogInfo((object)"Using existing ItemsDatabase.json");
				}
				if (!File.Exists(ConfigPath))
				{
					Log.LogInfo((object)"ItemsConfig.json not found.");
					Log.LogInfo((object)"Creating FULL editable ItemsConfig.json...");
					ExportItems(ConfigPath);
					Log.LogInfo((object)("[CONFIG] ItemsConfig created: " + ConfigPath));
				}
				else
				{
					Log.LogInfo((object)"Using existing ItemsConfig.json");
					Log.LogInfo((object)"Existing config is never overwritten automatically.");
				}
				ApplyConfig();
				InstallThunderRingRuntimeFix();
				InstallItemLocalizerFix();
				Log.LogInfo((object)"==============================");
				Log.LogInfo((object)"Item Tweaker ready!");
				Log.LogInfo((object)"==============================");
			}
			catch (Exception ex)
			{
				Log.LogError((object)("[INIT ERROR] " + ex));
			}
		}

		private static bool IsChangedModifier(ItemParamModificationType modificationType, float first, float other)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			ChangedParamModificationKey item = new ChangedParamModificationKey(modificationType, first, other);
			return ChangedParamModifications.Contains(item);
		}

		private static bool IsChangedGrowthModifier(ItemID itemId, ItemParamModificationType modificationType)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			ChangedGrowthModifierKey item = new ChangedGrowthModifierKey(itemId, modificationType);
			return ChangedGrowthModifiers.Contains(item);
		}

		private static int QuantizeFloatKey(float value)
		{
			return (int)Math.Round(value * 100000f);
		}

		private static void InstallThunderRingRuntimeFix()
		{
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Expected O, but got Unknown
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Expected O, but got Unknown
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Expected O, but got Unknown
			try
			{
				ThunderRingControllerType = FindTypeBySimpleName("ThunderRingController");
				if (ThunderRingControllerType == null)
				{
					Log.LogWarning((object)"[THUNDER] ThunderRingController was not found.");
					return;
				}
				MethodInfo[] methods = ThunderRingControllerType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (MethodInfo methodInfo in methods)
				{
					if (methodInfo.Name == "ClientHandleItemAcquired")
					{
						ThunderAcquireMethods.Add(methodInfo);
					}
					else if (methodInfo.Name == "ClientHandleItemLost")
					{
						ThunderLostMethods.Add(methodInfo);
					}
					else if (methodInfo.Name == "ClientStopThunder")
					{
						ThunderStopMethod = methodInfo;
					}
					else if (methodInfo.Name == "ClientPlayThunderLoop")
					{
						ThunderPlayLoopMethod = methodInfo;
					}
				}
				ThunderRadiusField = FindFieldRecursive(ThunderRingControllerType, "_thunderFindRadius");
				ThunderRadiusProperty = FindPropertyRecursive(ThunderRingControllerType, "ThunderFindRadius");
				if (ThunderStopMethod == null || ThunderPlayLoopMethod == null)
				{
					Log.LogWarning((object)"[THUNDER] Could not find ClientStopThunder/ClientPlayThunderLoop. Controller will not be restarted.");
					return;
				}
				Harmony val = new Harmony("com.yourname.itemtweaker.thunderring");
				MethodInfo method = typeof(Plugin).GetMethod("ThunderRing_ItemStackChanged_Postfix", BindingFlags.Static | BindingFlags.NonPublic);
				foreach (MethodInfo thunderAcquireMethod in ThunderAcquireMethods)
				{
					val.Patch((MethodBase)thunderAcquireMethod, (HarmonyMethod)null, new HarmonyMethod(method), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				foreach (MethodInfo thunderLostMethod in ThunderLostMethods)
				{
					val.Patch((MethodBase)thunderLostMethod, (HarmonyMethod)null, new HarmonyMethod(method), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				ThunderRingFixInstalled = true;
				Log.LogInfo((object)("[THUNDER] Runtime fix installed: acquire=" + ThunderAcquireMethods.Count + ", lost=" + ThunderLostMethods.Count + ", radiusField=" + (ThunderRadiusField != null)));
			}
			catch (Exception ex)
			{
				Log.LogError((object)("[THUNDER INSTALL ERROR] " + ex));
			}
		}

		private static Type FindTypeBySimpleName(string simpleName)
		{
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				Type[] types;
				try
				{
					types = assembly.GetTypes();
				}
				catch (ReflectionTypeLoadException ex)
				{
					types = ex.Types;
				}
				catch
				{
					continue;
				}
				if (types == null)
				{
					continue;
				}
				Type[] array = types;
				foreach (Type type in array)
				{
					if (type != null && type.Name == simpleName)
					{
						return type;
					}
				}
			}
			return null;
		}

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

		private static PropertyInfo FindPropertyRecursive(Type type, string name)
		{
			while (type != null)
			{
				PropertyInfo property = type.GetProperty(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (property != null)
				{
					return property;
				}
				type = type.BaseType;
			}
			return null;
		}

		private static void ThunderRing_ItemStackChanged_Postfix(object __instance, object[] __args)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Invalid comparison between Unknown and I4
			try
			{
				if (!ThunderRingFixInstalled || __instance == null)
				{
					return;
				}
				bool flag = false;
				if (__args != null)
				{
					foreach (object obj in __args)
					{
						if (obj != null)
						{
							if (obj is ItemID val && (int)val == 27)
							{
								flag = true;
								break;
							}
							if (string.Equals(obj.ToString(), "ThunderRing", StringComparison.OrdinalIgnoreCase))
							{
								flag = true;
								break;
							}
						}
					}
				}
				if (flag)
				{
					Object val2 = (Object)((__instance is Object) ? __instance : null);
					if (val2 == null || !(val2 == (Object)null))
					{
						ThunderStopMethod.Invoke(__instance, null);
						ThunderPlayLoopMethod.Invoke(__instance, null);
						UpdateThunderRadius(__instance);
					}
				}
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("[THUNDER] Runtime refresh failed: " + ex.Message));
			}
		}

		private static void UpdateThunderRadius(object controller)
		{
			if (controller == null)
			{
				return;
			}
			try
			{
				object obj = FindCharItemManager(controller);
				if (obj == null)
				{
					return;
				}
				MethodInfo methodInfo = FindMethod(obj.GetType(), "GetModificationValue", 1);
				if (methodInfo == null)
				{
					return;
				}
				object obj2 = methodInfo.Invoke(obj, new object[1] { (object)(ItemParamModificationType)76 });
				if (obj2 != null)
				{
					float num = Convert.ToSingle(obj2);
					if (ThunderRadiusField != null)
					{
						ThunderRadiusField.SetValue(controller, num);
					}
					else if (ThunderRadiusProperty != null && ThunderRadiusProperty.CanWrite)
					{
						ThunderRadiusProperty.SetValue(controller, num);
					}
				}
			}
			catch
			{
			}
		}

		private static object FindCharItemManager(object controller)
		{
			Type type = controller.GetType();
			while (type != null)
			{
				FieldInfo[] fields = type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (FieldInfo fieldInfo in fields)
				{
					if (fieldInfo.Name.IndexOf("itemManager", StringComparison.OrdinalIgnoreCase) >= 0)
					{
						try
						{
							object value = fieldInfo.GetValue(controller);
							if (value != null)
							{
								return value;
							}
						}
						catch
						{
						}
					}
					if (!(fieldInfo.FieldType != null) || fieldInfo.FieldType.Name.IndexOf("CharItemManager", StringComparison.OrdinalIgnoreCase) < 0)
					{
						continue;
					}
					try
					{
						object value2 = fieldInfo.GetValue(controller);
						if (value2 != null)
						{
							return value2;
						}
					}
					catch
					{
					}
				}
				type = type.BaseType;
			}
			return null;
		}

		private static void InstallGameplayModificationFix()
		{
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Expected O, but got Unknown
			try
			{
				Type type = AccessTools.TypeByName("Gatekeeper.Char_Scripts.General.CharItemManager");
				if (type == null)
				{
					Log.LogError((object)"[GAMEPLAY] CharItemManager type was not found.");
					return;
				}
				MethodInfo methodInfo = FindMethod(type, "GetFirstLevelModificationParam", 2);
				if (methodInfo == null)
				{
					Log.LogError((object)"[GAMEPLAY] GetFirstLevelModificationParam was not found.");
					return;
				}
				MethodInfo method = typeof(Plugin).GetMethod("CharItemManager_GetFirstLevelModificationParam_Postfix", BindingFlags.Static | BindingFlags.NonPublic);
				if (method == null)
				{
					Log.LogError((object)"[GAMEPLAY] Gameplay postfix was not found.");
					return;
				}
				new Harmony("com.yourname.itemtweaker.gameplay").Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(method), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Log.LogInfo((object)"[GAMEPLAY] Patched CharItemManager.GetFirstLevelModificationParam.");
				Log.LogInfo((object)"[GAMEPLAY] Linear per-stack values will now affect the real gameplay value.");
			}
			catch (Exception ex)
			{
				Log.LogError((object)("[GAMEPLAY INSTALL ERROR] " + ex));
			}
		}

		private static MethodInfo FindMethod(Type type, string name, int parameterCount)
		{
			MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (MethodInfo methodInfo in methods)
			{
				if (!(methodInfo.Name != name) && methodInfo.GetParameters().Length == parameterCount)
				{
					return methodInfo;
				}
			}
			return null;
		}

		private static bool TryGetGameplayGrowthValue(ItemID itemId, ItemParamModificationType modificationType, out GameplayGrowthValue value)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return GameplayGrowthValues.TryGetValue(new ChangedGrowthModifierKey(itemId, modificationType), out value);
		}

		private static bool TryGetItemQuantity(object charItemManager, ItemID itemId, out int quantity)
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			quantity = 0;
			if (charItemManager == null)
			{
				return false;
			}
			try
			{
				Type type = charItemManager.GetType();
				MethodInfo value;
				lock (GetItemQuantityMethods)
				{
					if (!GetItemQuantityMethods.TryGetValue(type, out value))
					{
						value = FindMethod(type, "GetItemQuantity", 1);
						GetItemQuantityMethods[type] = value;
					}
				}
				if (value == null)
				{
					return false;
				}
				object obj = value.Invoke(charItemManager, new object[1] { itemId });
				if (obj == null)
				{
					return false;
				}
				quantity = Convert.ToInt32(obj);
				return true;
			}
			catch
			{
				return false;
			}
		}

		private static bool TryCalculateLinearGameplayValue(object charItemManager, ItemID itemId, ItemParamModificationType modificationType, out float value)
		{
			//IL_0007: 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_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Invalid comparison between Unknown and I4
			value = 0f;
			if (!TryGetGameplayGrowthValue(itemId, modificationType, out var value2))
			{
				return false;
			}
			if (!TryGetItemQuantity(charItemManager, itemId, out var quantity))
			{
				return false;
			}
			if (quantity <= 0)
			{
				return false;
			}
			ItemParamGrowthType growthType = value2.GrowthType;
			if ((int)growthType != 0)
			{
				if ((int)growthType == 3)
				{
					value = value2.First;
					return true;
				}
				return false;
			}
			value = value2.First + value2.Other * (float)(quantity - 1);
			return true;
		}

		private static void CharItemManager_GetFirstLevelModificationParam_Postfix(object __instance, ItemID itemId, ItemParamModificationType modificationType, ref float __result)
		{
			//IL_0001: 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_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (TryGetItemQuantity(__instance, itemId, out var quantity) && quantity > 0)
				{
					lock (CurrentItemQuantities)
					{
						CurrentItemQuantities[itemId] = quantity;
					}
				}
				if (TryCalculateLinearGameplayValue(__instance, itemId, modificationType, out var value))
				{
					__result = value;
				}
			}
			catch
			{
			}
		}

		private static void InstallItemLocalizerFix()
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Expected O, but got Unknown
			try
			{
				MethodInfo method = typeof(ItemLocalizer).GetMethod("GetFormattedValue", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (method == null)
				{
					Log.LogError((object)"Could not find ItemLocalizer.GetFormattedValue.");
					return;
				}
				MethodInfo method2 = typeof(Plugin).GetMethod("ItemLocalizer_GetFormattedValue_Postfix", BindingFlags.Static | BindingFlags.NonPublic);
				if (method2 == null)
				{
					Log.LogError((object)"Could not find UI postfix method.");
					return;
				}
				UpdateCachedPerStackLocale();
				new Harmony("com.yourname.itemtweaker.ui").Patch((MethodBase)method, (HarmonyMethod)null, new HarmonyMethod(method2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Log.LogInfo((object)"ItemLocalizer UI stack-growth fix 0.6.1 installed.");
			}
			catch (Exception ex)
			{
				Log.LogError((object)("[UI INSTALL ERROR] " + ex));
			}
		}

		private static void AddUiDebug(string message)
		{
		}

		private static void PrintUiDebugSummary(string reason)
		{
		}

		private static bool TryGetItemIdFromLocalizer(ItemLocalizer instance, out ItemID itemId)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected I4, but got Unknown
			itemId = (ItemID)0;
			if (instance == null)
			{
				return false;
			}
			try
			{
				ItemDatabaseInfo itemDatabaseInfo = instance._itemDatabaseInfo;
				if ((Object)(object)itemDatabaseInfo == (Object)null)
				{
					return false;
				}
				itemId = (ItemID)(int)itemDatabaseInfo.ItemId;
				return true;
			}
			catch
			{
				return false;
			}
		}

		private static string RemoveDuplicatePerStack(string value)
		{
			if (string.IsNullOrEmpty(value))
			{
				return value;
			}
			string input = Regex.Replace(value, "</color>\\s*%+", "</color>", RegexOptions.IgnoreCase);
			input = Regex.Replace(input, "</?color[^>]*>", string.Empty, RegexOptions.IgnoreCase).Trim();
			while (true)
			{
				MatchCollection matchCollection = Regex.Matches(input, "\\([^()]*(?:per\\s+stack|за\\s*шт\\.?)[^()]*\\)", RegexOptions.IgnoreCase);
				if (matchCollection.Count <= 1)
				{
					break;
				}
				for (int num = matchCollection.Count - 2; num >= 0; num--)
				{
					input = input.Remove(matchCollection[num].Index, matchCollection[num].Length);
				}
				input = Regex.Replace(input, "\\s{2,}", " ", RegexOptions.IgnoreCase).Trim();
			}
			input = Regex.Replace(input, "\\s*%+\\s*$", string.Empty, RegexOptions.IgnoreCase);
			input = RemoveTrailingPercentAfterParenthesis(input);
			return input.Trim();
		}

		private static string RemoveAllPerStackSuffixes(string value)
		{
			if (string.IsNullOrEmpty(value))
			{
				return value;
			}
			string input = Regex.Replace(value, "</color>\\s*%+", "</color>", RegexOptions.IgnoreCase);
			input = Regex.Replace(input, "</?color[^>]*>", string.Empty, RegexOptions.IgnoreCase);
			string b;
			do
			{
				b = input;
				input = Regex.Replace(input, "\\([^()]*(?:per\\s+stack|за\\s*шт\\.?)[^()]*\\)", string.Empty, RegexOptions.IgnoreCase);
				input = Regex.Replace(input, "\\s{2,}", " ", RegexOptions.IgnoreCase).Trim();
			}
			while (!string.Equals(input, b, StringComparison.Ordinal));
			input = Regex.Replace(input, "\\s*%+\\s*$", string.Empty, RegexOptions.IgnoreCase);
			input = RemoveTrailingPercentAfterParenthesis(input);
			return input.Trim();
		}

		private static string RemoveTrailingPercentAfterParenthesis(string value)
		{
			if (string.IsNullOrEmpty(value))
			{
				return value;
			}
			return Regex.Replace(Regex.Replace(Regex.Replace(value, "\\)\\s*%+\\s*", ")", RegexOptions.IgnoreCase), "(</color>)\\s*%+\\s*", "$1", RegexOptions.IgnoreCase), "\\s*%+\\s*$", string.Empty, RegexOptions.IgnoreCase).Trim();
		}

		private static string CleanFormattedResult(string value)
		{
			if (string.IsNullOrEmpty(value))
			{
				return value;
			}
			return Regex.Replace(RemoveTrailingPercentAggressive(RemoveTrailingPercentAfterParenthesis(Regex.Replace(Regex.Replace(Regex.Replace(value, "(?:</color>|\\))\\s*(?:&#37;|%|\\uFEFF|\\u200B)+", (Match m) => (!m.Value.StartsWith("</color>", StringComparison.OrdinalIgnoreCase)) ? ")" : "</color>", RegexOptions.IgnoreCase), "(?<=</color>)\\s*(?:&#37;|%)+", string.Empty, RegexOptions.IgnoreCase), "(?<=\\))\\s*(?:&#37;|%)+", string.Empty, RegexOptions.IgnoreCase))), "\\s{2,}", " ", RegexOptions.None).Trim();
		}

		private static bool HasNativeBaselineGrowth(ItemID itemId, ItemParamModificationType modificationType)
		{
			//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)
			lock (NativeBaselineGrowthModifiers)
			{
				return NativeBaselineGrowthModifiers.Contains(new ChangedGrowthModifierKey(itemId, modificationType));
			}
		}

		private static void ItemLocalizer_GetFormattedValue_Postfix(ItemLocalizer __instance, ItemParamModificationType modificationType, float originalValue, float modifiedValue, ref string __result)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: 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_0112: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (__instance == null || __instance._itemModifications == null)
				{
					return;
				}
				ParamModification val = null;
				List<ParamModification> itemModifications = __instance._itemModifications;
				for (int i = 0; i < itemModifications.Count; i++)
				{
					ParamModification val2 = itemModifications[i];
					if (val2 != null && val2.modificationType == modificationType)
					{
						val = val2;
						break;
					}
				}
				if (val == null)
				{
					return;
				}
				float firstLevelModificationValue = val.firstLevelModificationValue;
				float otherLevelModificationValue = val.otherLevelModificationValue;
				if (IsChangedModifier(modificationType, firstLevelModificationValue, otherLevelModificationValue) && !(Math.Abs(otherLevelModificationValue) <= 1E-06f) && TryGetItemIdFromLocalizer(__instance, out var itemId) && IsChangedGrowthModifier(itemId, modificationType) && !HasNativeBaselineGrowth(itemId, modificationType))
				{
					float num = CorrectDisplayedSign(firstLevelModificationValue, originalValue, modifiedValue);
					if (float.IsNaN(num) || float.IsInfinity(num))
					{
						num = firstLevelModificationValue;
					}
					bool num2 = IsThresholdPercentageValue(modificationType);
					bool flag = num2 || IsPercentageValueFast(modificationType, __result);
					string text;
					string text2;
					if (num2)
					{
						text = FormatPercentNoSign(num);
						text2 = FormatSignedPercentNoSymbol(otherLevelModificationValue);
					}
					else
					{
						text = (flag ? FormatPercent(num) : FormatNumber(num));
						float uiGrowthStep = GetUiGrowthStep(itemId, modificationType, firstLevelModificationValue, otherLevelModificationValue, num);
						text2 = (flag ? FormatSignedPercent(uiGrowthStep) : FormatSignedNumber(uiGrowthStep));
					}
					__result = text + " <color=#9BEA6A>(" + text2 + CachedPerStackSuffix + ")</color>";
				}
			}
			catch
			{
			}
		}

		private static float CorrectDisplayedSign(float first, float originalValue, float modifiedValue)
		{
			if (float.IsNaN(modifiedValue) || float.IsInfinity(modifiedValue))
			{
				return first;
			}
			if (Math.Abs(first) > 1E-06f && Math.Abs(originalValue) > 1E-06f)
			{
				bool num = first < 0f;
				bool flag = originalValue < 0f;
				if (num != flag)
				{
					return 0f - modifiedValue;
				}
			}
			else if (Math.Abs(first) > 1E-06f && Math.Abs(modifiedValue) > 1E-06f)
			{
				bool num2 = first < 0f;
				bool flag2 = modifiedValue < 0f;
				if (num2 != flag2)
				{
					return 0f - modifiedValue;
				}
			}
			return modifiedValue;
		}

		private static float GetUiGrowthStep(ItemID itemId, ItemParamModificationType modificationType, float first, float other, float currentValue)
		{
			//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_000d: Invalid comparison between Unknown and I4
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			if (!TryGetGameplayGrowthType(itemId, modificationType, out var growthType) || (int)growthType != 1)
			{
				return other;
			}
			int value = 0;
			lock (CurrentItemQuantities)
			{
				CurrentItemQuantities.TryGetValue(itemId, out value);
			}
			if (value <= 1)
			{
				return other;
			}
			float num = (currentValue - first) / (float)(value - 1);
			if (float.IsNaN(num) || float.IsInfinity(num))
			{
				return other;
			}
			return num;
		}

		private static bool TryGetGameplayGrowthType(ItemID itemId, ItemParamModificationType modificationType, out ItemParamGrowthType growthType)
		{
			//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)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected I4, but got Unknown
			lock (GameplayGrowthValues)
			{
				if (GameplayGrowthValues.TryGetValue(new ChangedGrowthModifierKey(itemId, modificationType), out var value))
				{
					growthType = (ItemParamGrowthType)(int)value.GrowthType;
					return true;
				}
			}
			growthType = (ItemParamGrowthType)3;
			return false;
		}

		private unsafe static bool IsThresholdPercentageValue(ItemParamModificationType modificationType)
		{
			string text = ((object)(*(ItemParamModificationType*)(&modificationType))/*cast due to .constrained prefix*/).ToString();
			if (text.IndexOf("HealthThreshold", StringComparison.OrdinalIgnoreCase) < 0)
			{
				return text.IndexOf("HpLimit", StringComparison.OrdinalIgnoreCase) >= 0;
			}
			return true;
		}

		private static string FormatSignedPercentNoSymbol(float value)
		{
			float num = value * 100f;
			return string.Concat(str1: (!(Math.Abs(num - MathF.Round(num)) < 0.0001f)) ? Math.Abs(num).ToString("0.##") : MathF.Round(Math.Abs(num)).ToString("0"), str0: (value >= 0f) ? "+" : "-");
		}

		private unsafe static bool IsPercentageValueFast(ItemParamModificationType modificationType, string formattedValue)
		{
			string text = ((object)(*(ItemParamModificationType*)(&modificationType))/*cast due to .constrained prefix*/).ToString();
			if (text.IndexOf("Perc", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Chance", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Prob", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Ratio", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return true;
			}
			if (text.IndexOf("HealthThreshold", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return true;
			}
			if (formattedValue != null)
			{
				return formattedValue.IndexOf('%') >= 0;
			}
			return false;
		}

		private static void UpdateCachedPerStackLocale()
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Invalid comparison between Unknown and I4
			bool flag = false;
			try
			{
				if (TryGetForcedLocaleOverride(out var localeCode, out var _))
				{
					flag = !string.IsNullOrEmpty(localeCode) && localeCode.StartsWith("ru", StringComparison.OrdinalIgnoreCase);
				}
			}
			catch
			{
			}
			bool flag2 = string.Equals(CultureInfo.CurrentUICulture.TwoLetterISOLanguageName, "ru", StringComparison.OrdinalIgnoreCase) || string.Equals(CultureInfo.CurrentCulture.TwoLetterISOLanguageName, "ru", StringComparison.OrdinalIgnoreCase) || string.Equals(CultureInfo.InstalledUICulture.TwoLetterISOLanguageName, "ru", StringComparison.OrdinalIgnoreCase);
			_useRussianPerStackSuffix = flag || (int)Application.systemLanguage == 30 || flag2;
			CachedPerStackSuffix = (_useRussianPerStackSuffix ? " за шт." : " per stack");
		}

		private static string NormalizeFormattedValue(string value)
		{
			return RemoveDuplicatePerStack(value ?? string.Empty);
		}

		private static void DumpTrailingChars(string label, string value, int count = 12)
		{
			if (!string.IsNullOrEmpty(value))
			{
				int length = value.Length;
				int num = Math.Max(0, length - count);
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.Append(label + " tail:");
				for (int i = num; i < length; i++)
				{
					char c = value[i];
					stringBuilder.AppendFormat(" '{0}'(0x{1:X4})", c, (int)c);
				}
				AddUiDebug(stringBuilder.ToString());
			}
		}

		private static string RemoveTrailingPercentAggressive(string value)
		{
			if (string.IsNullOrEmpty(value))
			{
				return value;
			}
			string text = value;
			string b;
			do
			{
				b = text;
				text = Regex.Replace(text, "\\)\\s*(?:&#37;|%)+\\s*(</color>)?", ")$1", RegexOptions.IgnoreCase);
				text = Regex.Replace(text, "(</color>)\\s*(?:&#37;|%)+\\s*", "$1", RegexOptions.IgnoreCase);
				text = Regex.Replace(text, "\\s*(?:&#37;|%)+\\s*$", string.Empty, RegexOptions.IgnoreCase);
				text = Regex.Replace(text, "(?<=\\))\\s*(?:&#37;|%)+", string.Empty, RegexOptions.IgnoreCase);
				text = Regex.Replace(text, "(?<=</color>)\\s*(?:&#37;|%)+", string.Empty, RegexOptions.IgnoreCase);
				text = Regex.Replace(text, "%{2,}", "%", RegexOptions.None);
				text = text.Trim();
			}
			while (!string.Equals(text, b, StringComparison.Ordinal));
			return text;
		}

		private unsafe static bool IsPercentageValue(ItemParamModificationType modificationType, string formattedValue)
		{
			string text = ((object)(*(ItemParamModificationType*)(&modificationType))/*cast due to .constrained prefix*/).ToString();
			if (text.IndexOf("Perc", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return true;
			}
			if (text.IndexOf("Chance", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return true;
			}
			if (text.IndexOf("Prob", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return true;
			}
			if (formattedValue != null)
			{
				return formattedValue.IndexOf("%", StringComparison.Ordinal) >= 0;
			}
			return false;
		}

		private static string FormatPercent(float value)
		{
			float num = value * 100f;
			if (Math.Abs(num - MathF.Round(num)) < 0.0001f)
			{
				return MathF.Round(num).ToString("0") + "%";
			}
			return num.ToString("0.##") + "%";
		}

		private static string FormatPercentNoSign(float value)
		{
			float num = value * 100f;
			if (Math.Abs(num - MathF.Round(num)) < 0.0001f)
			{
				return MathF.Round(num).ToString("0");
			}
			return num.ToString("0.##");
		}

		private static string FormatSignedPercent(float value)
		{
			float num = value * 100f;
			return string.Concat(str1: (!(Math.Abs(num - MathF.Round(num)) < 0.0001f)) ? num.ToString("0.##") : MathF.Round(num).ToString("0"), str0: (value >= 0f) ? "+" : "-", str2: "%");
		}

		private static string FormatNumber(float value)
		{
			if (Math.Abs(value - MathF.Round(value)) < 0.0001f)
			{
				return MathF.Round(value).ToString("0");
			}
			return value.ToString("0.##");
		}

		private static string FormatSignedNumber(float value)
		{
			string text = FormatNumber(Math.Abs(value));
			return ((value >= 0f) ? "+" : "-") + text;
		}

		private static bool TryGetForcedLocaleOverride(out string localeCode, out string source)
		{
			localeCode = null;
			source = null;
			try
			{
				string environmentVariable = Environment.GetEnvironmentVariable("ITEMTWEAKER_LOCALE");
				if (!string.IsNullOrEmpty(environmentVariable))
				{
					localeCode = environmentVariable.Trim();
					source = "environment variable ITEMTWEAKER_LOCALE";
					return true;
				}
			}
			catch
			{
			}
			string[] array = new string[2] { "force_locale.txt", "force_ru_locale.txt" };
			string text = null;
			try
			{
				string text2 = Assembly.GetExecutingAssembly()?.Location;
				if (!string.IsNullOrEmpty(text2))
				{
					text = Path.GetDirectoryName(text2);
				}
			}
			catch
			{
			}
			string[] array2 = new string[4]
			{
				Folder,
				text ?? string.Empty,
				AppDomain.CurrentDomain.BaseDirectory ?? string.Empty,
				Environment.CurrentDirectory ?? string.Empty
			};
			foreach (string text3 in array2)
			{
				if (string.IsNullOrEmpty(text3))
				{
					continue;
				}
				string[] array3 = array;
				foreach (string text4 in array3)
				{
					string text5 = Path.Combine(text3, text4);
					if (!File.Exists(text5))
					{
						continue;
					}
					try
					{
						if (string.Equals(text4, "force_ru_locale.txt", StringComparison.OrdinalIgnoreCase))
						{
							localeCode = "ru";
							source = text5;
							return true;
						}
						string text6 = File.ReadAllText(text5).Trim();
						if (string.IsNullOrEmpty(text6))
						{
							continue;
						}
						localeCode = ((text6.Length >= 2) ? text6.Substring(0, 2) : text6);
						source = text5;
						return true;
					}
					catch (Exception ex)
					{
						AddUiDebug("[UI LOCALE OVERRIDE] failed to read " + text5 + ": " + ex.Message);
					}
				}
			}
			return false;
		}

		private unsafe static void ApplyConfig()
		{
			//IL_0988: Unknown result type (might be due to invalid IL or missing references)
			//IL_09a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_09a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_09bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_09ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bf7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bf9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_0638: Unknown result type (might be due to invalid IL or missing references)
			//IL_063a: Unknown result type (might be due to invalid IL or missing references)
			//IL_048b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0490: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0506: Unknown result type (might be due to invalid IL or missing references)
			//IL_050b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0532: Unknown result type (might be due to invalid IL or missing references)
			//IL_0534: Unknown result type (might be due to invalid IL or missing references)
			//IL_0539: Unknown result type (might be due to invalid IL or missing references)
			//IL_0840: Unknown result type (might be due to invalid IL or missing references)
			//IL_0845: Unknown result type (might be due to invalid IL or missing references)
			//IL_085c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0863: Expected O, but got Unknown
			//IL_0865: Unknown result type (might be due to invalid IL or missing references)
			//IL_08d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0932: Unknown result type (might be due to invalid IL or missing references)
			//IL_0934: Unknown result type (might be due to invalid IL or missing references)
			//IL_096c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0971: Unknown result type (might be due to invalid IL or missing references)
			//IL_097b: Unknown result type (might be due to invalid IL or missing references)
			//IL_097d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0982: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				ItemConfigRoot itemConfigRoot = JsonSerializer.Deserialize<ItemConfigRoot>(File.ReadAllText(ConfigPath), new JsonSerializerOptions
				{
					PropertyNameCaseInsensitive = true
				});
				ItemConfigRoot baselineRoot = null;
				if (File.Exists(DatabasePath))
				{
					try
					{
						baselineRoot = JsonSerializer.Deserialize<ItemConfigRoot>(File.ReadAllText(DatabasePath), new JsonSerializerOptions
						{
							PropertyNameCaseInsensitive = true
						});
					}
					catch (Exception ex)
					{
						Log.LogWarning((object)("Failed to parse ItemsDatabase.json: " + ex.Message));
					}
				}
				else
				{
					Log.LogWarning((object)"ItemsDatabase.json not found when applying config. Baseline growth filtering disabled.");
				}
				if (itemConfigRoot == null || itemConfigRoot.items == null)
				{
					Log.LogError((object)"ItemsConfig.json is empty or invalid!");
					return;
				}
				lock (ChangedParamModifications)
				{
					ChangedParamModifications.Clear();
				}
				lock (ChangedItemIds)
				{
					ChangedItemIds.Clear();
				}
				Log.LogInfo((object)("Applying config for " + itemConfigRoot.items.Count + " items..."));
				foreach (ItemConfig item2 in itemConfigRoot.items)
				{
					try
					{
						Log.LogInfo((object)"--------------------------------");
						Log.LogInfo((object)("[CONFIG READ] id=" + item2.id));
						Log.LogInfo((object)("[CONFIG READ] cost=" + item2.itemCost + ", costStep=" + item2.itemCostStep + ", maxCount=" + item2.itemMaxCount));
						Log.LogInfo((object)("[CONFIG READ] modifiers=" + ((item2.modifiers != null) ? item2.modifiers.Count : 0)));
						if (!Enum.TryParse<ItemID>(item2.id, out ItemID result))
						{
							Log.LogWarning((object)("Unknown ItemID: " + item2.id));
							continue;
						}
						ItemDatabaseInfo itemById = ItemAPI.Instance.GetItemById(result);
						if ((Object)(object)itemById == (Object)null)
						{
							Log.LogWarning((object)("Item not found: " + item2.id));
							continue;
						}
						ItemConfig baselineItem = FindBaselineConfig(baselineRoot, item2.id);
						Log.LogInfo((object)("[DATABASE FOUND] " + item2.id));
						Log.LogInfo((object)("[BEFORE] " + item2.id + ": itemCost=" + itemById.itemCost + ", itemCostStep=" + itemById.itemCostStep + ", maxCount=" + itemById.itemMaxCount));
						itemById.itemCost = item2.itemCost;
						itemById.itemCostStep = item2.itemCostStep;
						itemById.itemSellingCost = item2.itemSellingCost;
						itemById.itemCreateCost = item2.itemCreateCost;
						itemById.itemUnlockCost = item2.itemUnlockCost;
						itemById.itemExcludeCost = item2.itemExcludeCost;
						itemById.itemObeliskCost = item2.itemObeliskCost;
						itemById.itemPedestalCost = item2.itemPedestalCost;
						itemById.itemTriadCost = item2.itemTriadCost;
						itemById.itemTriadCostStep = item2.itemTriadCostStep;
						itemById.itemMaxCount = item2.itemMaxCount;
						itemById.hideInForge = item2.hideInForge;
						itemById.ignoreByConstructs = item2.ignoreByConstructs;
						((BaseDatabaseInfo)itemById).hideInDatabase = item2.hideInDatabase;
						((BaseDatabaseInfo)itemById).unlocked = item2.unlocked;
						((BaseDatabaseInfo)itemById).wasSeen = item2.wasSeen;
						Log.LogInfo((object)("[AFTER] " + item2.id + ": itemCost=" + itemById.itemCost + ", itemCostStep=" + itemById.itemCostStep + ", maxCount=" + itemById.itemMaxCount));
						if (item2.growthType.HasValue)
						{
							Log.LogInfo((object)("[GROWTH] " + item2.id + ": setting growth type = " + ((object)item2.growthType.Value/*cast due to .constrained prefix*/).ToString()));
							bool flag = ItemGrowthHelper.SetItemGrowthType(result, item2.growthType.Value);
							Log.LogInfo((object)("[GROWTH APPLY] " + item2.id + ": applied=" + flag + ", type=" + ((object)item2.growthType.Value/*cast due to .constrained prefix*/).ToString()));
							try
							{
								ItemsInfoProvider items = DatabaseInfoProvider.Items;
								if (items != null)
								{
									ItemParamGrowthType itemGrowthType = items.GetItemGrowthType(result);
									Log.LogInfo((object)("[GROWTH VERIFY] " + item2.id + ": actual=" + ((object)(*(ItemParamGrowthType*)(&itemGrowthType))/*cast due to .constrained prefix*/).ToString()));
								}
							}
							catch (Exception ex2)
							{
								Log.LogWarning((object)("[GROWTH VERIFY] " + item2.id + ": " + ex2.Message));
							}
						}
						if (item2.modifiers != null)
						{
							foreach (ModifierConfig modifier in item2.modifiers)
							{
								try
								{
									if (!Enum.TryParse<ItemParamModificationType>(modifier.type, out ItemParamModificationType result2))
									{
										Log.LogWarning((object)("Unknown modifier type '" + modifier.type + "' on " + item2.id));
										continue;
									}
									ModifierConfig modifierConfig = FindBaselineModifier(baselineItem, modifier.type);
									if (modifierConfig != null && Math.Abs(modifierConfig.other) > 1E-06f)
									{
										lock (NativeBaselineGrowthModifiers)
										{
											NativeBaselineGrowthModifiers.Add(new ChangedGrowthModifierKey(result, result2));
										}
									}
									bool flag2 = modifierConfig == null || Math.Abs(modifier.other - modifierConfig.other) > 1E-06f;
									bool flag3 = modifierConfig == null || Math.Abs(modifier.first - modifierConfig.first) > 1E-06f;
									bool flag4 = modifierConfig == null || flag3 || flag2;
									if (modifierConfig != null && !flag4)
									{
										Log.LogInfo((object)("[SKIP MODIFIER] " + item2.id + " / " + modifier.type + " unchanged from baseline; skipping."));
										continue;
									}
									Log.LogInfo((object)("[MOD READ] " + item2.id + ": type=" + modifier.type + ", first=" + modifier.first + ", other=" + modifier.other + ", cup=" + modifier.logGrowthCup + ", baselineFirst=" + ((modifierConfig == null) ? "<none>" : modifierConfig.first.ToString()) + ", baselineOther=" + ((modifierConfig == null) ? "<none>" : modifierConfig.other.ToString()) + ", otherChanged=" + flag2));
									if (itemById.modificationParams == null)
									{
										Log.LogWarning((object)(item2.id + " has no modificationParams; cannot add " + modifier.type));
										continue;
									}
									ParamModification val = null;
									Enumerator<ParamModification> enumerator3 = itemById.modificationParams.GetEnumerator();
									while (enumerator3.MoveNext())
									{
										ParamModification current3 = enumerator3.Current;
										if (current3 != null && current3.modificationType == result2)
										{
											val = current3;
											break;
										}
									}
									if (val == null)
									{
										val = new ParamModification();
										val.modificationType = result2;
										itemById.modificationParams.Add(val);
										Log.LogInfo((object)("[MOD CREATED] " + item2.id + ": " + modifier.type));
									}
									else
									{
										Log.LogInfo((object)("[MOD FOUND] " + item2.id + ": " + modifier.type));
									}
									if (flag4)
									{
										ChangedParamModificationKey item = new ChangedParamModificationKey(result2, modifier.first, modifier.other);
										lock (ChangedParamModifications)
										{
											ChangedParamModifications.Add(item);
										}
										if (flag2)
										{
											lock (ChangedGrowthModifiers)
											{
												ChangedGrowthModifiers.Add(new ChangedGrowthModifierKey(result, result2));
											}
											ItemParamGrowthType growthType;
											if (item2.growthType.HasValue)
											{
												growthType = item2.growthType.Value;
											}
											else
											{
												try
												{
													growthType = DatabaseInfoProvider.Items.GetItemGrowthType(result);
												}
												catch
												{
													growthType = (ItemParamGrowthType)0;
												}
											}
											lock (GameplayGrowthValues)
											{
												GameplayGrowthValues[new ChangedGrowthModifierKey(result, result2)] = new GameplayGrowthValue(modifier.first, modifier.other, growthType);
											}
										}
										lock (ChangedItemIds)
										{
											ChangedItemIds.Add(result);
										}
									}
									Log.LogInfo((object)("[MOD BEFORE] " + item2.id + " / " + modifier.type + ": first=" + val.firstLevelModificationValue + ", other=" + val.otherLevelModificationValue));
									val.firstLevelModificationValue = modifier.first;
									val.otherLevelModificationValue = modifier.other;
									Log.LogInfo((object)("[MOD AFTER] " + item2.id + " / " + modifier.type + ": first=" + val.firstLevelModificationValue + ", other=" + val.otherLevelModificationValue));
									Log.LogInfo((object)("[MOD VERIFY] " + item2.id + " / " + modifier.type + ": first=" + val.firstLevelModificationValue + ", other=" + val.otherLevelModificationValue));
									if (Math.Abs(modifier.other) > 1E-06f)
									{
										Log.LogInfo((object)("[GROWTH PARAM] " + item2.id + " / " + modifier.type + ": other=" + modifier.other + ", cup=" + modifier.logGrowthCup));
										bool flag5 = ItemGrowthHelper.EnsureGrowthParameter(result, result2, modifier.logGrowthCup);
										Log.LogInfo((object)("[GROWTH PARAM APPLY] " + item2.id + " / " + modifier.type + ": applied=" + flag5));
									}
								}
								catch (Exception ex3)
								{
									Log.LogWarning((object)("Failed modifier " + modifier.type + " on " + item2.id + ": " + ex3));
								}
							}
						}
						Log.LogInfo((object)("[ITEM FINAL] " + item2.id + ": cost=" + itemById.itemCost + ", maxCount=" + itemById.itemMaxCount + ", modifiers=" + ((itemById.modificationParams != null) ? itemById.modificationParams.Count : 0)));
						Log.LogInfo((object)("Applied: " + item2.id));
					}
					catch (Exception ex4)
					{
						Log.LogWarning((object)("Failed to apply " + item2.id + ": " + ex4));
					}
				}
				Log.LogInfo((object)"==============================");
				Log.LogInfo((object)"ItemsConfig applied successfully!");
				Log.LogInfo((object)"==============================");
			}
			catch (Exception ex5)
			{
				Log.LogError((object)("[CONFIG ERROR] " + ex5));
			}
		}

		private static void ExportItems(string path)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: 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_0237: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			Log.LogInfo((object)"Exporting items...");
			ItemConfigRoot itemConfigRoot = new ItemConfigRoot();
			float value = default(float);
			foreach (ItemID value2 in Enum.GetValues(typeof(ItemID)))
			{
				try
				{
					ItemDatabaseInfo itemById = ItemAPI.Instance.GetItemById(value2);
					if ((Object)(object)itemById == (Object)null)
					{
						continue;
					}
					ItemConfig itemConfig = new ItemConfig();
					itemConfig.id = ((object)value2/*cast due to .constrained prefix*/).ToString();
					itemConfig.itemCost = itemById.itemCost;
					itemConfig.itemCostStep = itemById.itemCostStep;
					itemConfig.itemSellingCost = itemById.itemSellingCost;
					itemConfig.itemCreateCost = itemById.itemCreateCost;
					itemConfig.itemUnlockCost = itemById.itemUnlockCost;
					itemConfig.itemExcludeCost = itemById.itemExcludeCost;
					itemConfig.itemObeliskCost = itemById.itemObeliskCost;
					itemConfig.itemPedestalCost = itemById.itemPedestalCost;
					itemConfig.itemTriadCost = itemById.itemTriadCost;
					itemConfig.itemTriadCostStep = itemById.itemTriadCostStep;
					itemConfig.itemMaxCount = itemById.itemMaxCount;
					itemConfig.hideInForge = itemById.hideInForge;
					itemConfig.ignoreByConstructs = itemById.ignoreByConstructs;
					itemConfig.hideInDatabase = ((BaseDatabaseInfo)itemById).hideInDatabase;
					itemConfig.unlocked = ((BaseDatabaseInfo)itemById).unlocked;
					itemConfig.wasSeen = ((BaseDatabaseInfo)itemById).wasSeen;
					try
					{
						ItemsInfoProvider items = DatabaseInfoProvider.Items;
						if (items != null)
						{
							itemConfig.growthType = items.GetItemGrowthType(value2);
						}
					}
					catch (Exception ex)
					{
						Log.LogWarning((object)("Failed to export growth type for " + ((object)value2/*cast due to .constrained prefix*/).ToString() + ": " + ex.Message));
					}
					itemConfig.modifiers = new List<ModifierConfig>();
					if (itemById.modificationParams != null)
					{
						Enumerator<ParamModification> enumerator2 = itemById.modificationParams.GetEnumerator();
						while (enumerator2.MoveNext())
						{
							ParamModification current = enumerator2.Current;
							try
							{
								ModifierConfig modifierConfig = new ModifierConfig
								{
									type = ((object)current.modificationType/*cast due to .constrained prefix*/).ToString(),
									first = current.firstLevelModificationValue,
									other = current.otherLevelModificationValue,
									logGrowthCup = null
								};
								try
								{
									ItemsInfoProvider items2 = DatabaseInfoProvider.Items;
									if (items2 != null && items2.TryGetLogGrowthCup(current.modificationType, ref value))
									{
										modifierConfig.logGrowthCup = value;
									}
								}
								catch
								{
								}
								itemConfig.modifiers.Add(modifierConfig);
							}
							catch (Exception ex2)
							{
								Log.LogWarning((object)("Failed modifier on " + ((object)value2/*cast due to .constrained prefix*/).ToString() + ": " + ex2.Message));
							}
						}
					}
					itemConfigRoot.items.Add(itemConfig);
				}
				catch (Exception ex3)
				{
					Log.LogWarning((object)("Skip " + ((object)value2/*cast due to .constrained prefix*/).ToString() + ": " + ex3));
				}
			}
			JsonSerializerOptions options = new JsonSerializerOptions
			{
				WriteIndented = true
			};
			string contents = JsonSerializer.Serialize(itemConfigRoot, options);
			File.WriteAllText(path, contents);
			Log.LogInfo((object)("Exported " + itemConfigRoot.items.Count + " items."));
		}

		private static ItemConfig FindBaselineConfig(ItemConfigRoot baselineRoot, string itemId)
		{
			if (baselineRoot == null || baselineRoot.items == null)
			{
				return null;
			}
			foreach (ItemConfig item in baselineRoot.items)
			{
				if (string.Equals(item.id, itemId, StringComparison.OrdinalIgnoreCase))
				{
					return item;
				}
			}
			return null;
		}

		private static ModifierConfig FindBaselineModifier(ItemConfig baselineItem, string modifierType)
		{
			if (baselineItem == null || baselineItem.modifiers == null)
			{
				return null;
			}
			foreach (ModifierConfig modifier in baselineItem.modifiers)
			{
				if (string.Equals(modifier.type, modifierType, StringComparison.OrdinalIgnoreCase))
				{
					return modifier;
				}
			}
			return null;
		}

		private static bool HasBaselineGrowth(ItemConfig baselineItem)
		{
			if (baselineItem == null || baselineItem.modifiers == null)
			{
				return false;
			}
			foreach (ModifierConfig modifier in baselineItem.modifiers)
			{
				if (Math.Abs(modifier.other) > 1E-06f)
				{
					return true;
				}
			}
			return false;
		}
	}
	public class ItemConfigRoot
	{
		public List<ItemConfig> items { get; set; } = new List<ItemConfig>();
	}
	public class ItemConfig
	{
		public string id { get; set; }

		public int itemCost { get; set; }

		public float itemCostStep { get; set; }

		public int itemSellingCost { get; set; }

		public int itemCreateCost { get; set; }

		public int itemUnlockCost { get; set; }

		public int itemExcludeCost { get; set; }

		public int itemObeliskCost { get; set; }

		public int itemPedestalCost { get; set; }

		public int itemTriadCost { get; set; }

		public int itemTriadCostStep { get; set; }

		public int itemMaxCount { get; set; }

		public bool hideInForge { get; set; }

		public bool ignoreByConstructs { get; set; }

		public bool hideInDatabase { get; set; }

		public bool unlocked { get; set; }

		public bool wasSeen { get; set; }

		public ItemParamGrowthType? growthType { get; set; }

		public List<ModifierConfig> modifiers { get; set; } = new List<ModifierConfig>();
	}
	public class ModifierConfig
	{
		public string type { get; set; }

		public float first { get; set; }

		public float other { get; set; }

		public float? logGrowthCup { get; set; }
	}
	public static class SimpleJsonParser
	{
		public static Dictionary<string, Dictionary<string, float>> Parse(string json)
		{
			return JsonSerializer.Deserialize<Dictionary<string, Dictionary<string, float>>>(json);
		}
	}
}
namespace ItemTweakerMod
{
	public static class ItemGrowthHelper
	{
		private static readonly Regex GrowthTextRegex = new Regex("\\s*\\(\\+\\d+(\\.\\d+)?%?\\s*(per stack|за стак)?\\)\\%?", RegexOptions.IgnoreCase | RegexOptions.Compiled);

		public static string StripVanillaGrowthText(string text)
		{
			if (string.IsNullOrEmpty(text))
			{
				return text;
			}
			return GrowthTextRegex.Replace(text, "").Trim();
		}

		public static string FormatStat(string statLabel, float baseVal, float growthVal, bool isPercentage)
		{
			if (isPercentage)
			{
				if (!(Math.Abs(growthVal) > 1E-06f))
				{
					return $"{statLabel}: {baseVal}%";
				}
				return $"{statLabel}: {baseVal}% ({((growthVal >= 0f) ? "+" : "")}{growthVal}% per stack)";
			}
			if (!(Math.Abs(growthVal) > 1E-06f))
			{
				return $"{statLabel}: {baseVal}";
			}
			return $"{statLabel}: {baseVal} ({((growthVal >= 0f) ? "+" : "")}{growthVal} per stack)";
		}

		public static bool SetItemGrowthType(ItemID itemId, ItemParamGrowthType growthType)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				ItemsInfoProvider items = DatabaseInfoProvider.Items;
				if (items == null)
				{
					return false;
				}
				Dictionary<ItemID, ItemParamGrowthType> itemParamGrowthTypes = items._itemParamGrowthTypes;
				if (itemParamGrowthTypes == null)
				{
					return false;
				}
				itemParamGrowthTypes[itemId] = growthType;
				return true;
			}
			catch
			{
				return false;
			}
		}

		public static bool EnsureGrowthParameter(ItemID itemId, ItemParamModificationType modificationType, float? logGrowthCup = null)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				ItemsInfoProvider items = DatabaseInfoProvider.Items;
				if (items == null)
				{
					return false;
				}
				if (!logGrowthCup.HasValue)
				{
					return true;
				}
				ItemParamGrowthTypesInfo itemParamLogGrowthTypesInfo = items.ItemParamLogGrowthTypesInfo;
				if ((Object)(object)itemParamLogGrowthTypesInfo == (Object)null)
				{
					return false;
				}
				Dictionary<ItemParamModificationType, float> logGrowthParams = itemParamLogGrowthTypesInfo.LogGrowthParams;
				if (logGrowthParams == null)
				{
					return false;
				}
				logGrowthParams[modificationType] = logGrowthCup.Value;
				return true;
			}
			catch
			{
				return false;
			}
		}
	}
	public class ItemModifier
	{
		public void ApplyItemTweaks(ItemData item, ItemTweaks tweaks)
		{
			if (item != null && tweaks != null)
			{
				if (tweaks.OverrideDamage)
				{
					item.damage = tweaks.NewDamage;
				}
				if (tweaks.OverrideDamageOther)
				{
					item.damageOther = tweaks.NewDamageOther;
				}
				if (tweaks.OverrideChance)
				{
					item.chance = tweaks.NewChance;
				}
				if (tweaks.OverrideChanceOther)
				{
					item.chanceOther = tweaks.NewChanceOther;
				}
				UpdateItemDescription(item, tweaks);
			}
		}

		private void UpdateItemDescription(ItemData item, ItemTweaks tweaks)
		{
			if (!string.IsNullOrEmpty(item.description))
			{
				string text = ItemGrowthHelper.StripVanillaGrowthText(item.description);
				if (tweaks.OverrideChance || tweaks.OverrideChanceOther)
				{
					float chance = item.chance;
					float chanceOther = item.chanceOther;
					string newFormattedString = ItemGrowthHelper.FormatStat("Chance", chance, chanceOther, isPercentage: true);
					text = ReplaceOrAppendStat(text, "Chance", newFormattedString);
				}
				if (tweaks.OverrideDamage || tweaks.OverrideDamageOther)
				{
					float damage = item.damage;
					float damageOther = item.damageOther;
					string newFormattedString2 = ItemGrowthHelper.FormatStat("Damage", damage, damageOther, isPercentage: false);
					text = ReplaceOrAppendStat(text, "Damage", newFormattedString2);
				}
				item.description = text;
			}
		}

		private string ReplaceOrAppendStat(string text, string statKey, string newFormattedString)
		{
			int num = text.IndexOf(statKey, StringComparison.OrdinalIgnoreCase);
			if (num >= 0)
			{
				int num2 = text.IndexOf('\n', num);
				if (num2 < 0)
				{
					num2 = text.Length;
				}
				string oldValue = text.Substring(num, num2 - num);
				return text.Replace(oldValue, newFormattedString);
			}
			return text + "\n" + newFormattedString;
		}
	}
	public class ItemTweaks
	{
		public bool OverrideDamage;

		public float NewDamage;

		public bool OverrideDamageOther;

		public float NewDamageOther;

		public bool OverrideChance;

		public float NewChance;

		public bool OverrideChanceOther;

		public float NewChanceOther;
	}
	public class ItemData
	{
		public string description;

		public float damage;

		public float damageOther;

		public float chance;

		public float chanceOther;
	}
}