Decompiled source of Balronds Badlands with Enigma Mode Beta v1.0.2

plugins/BAOBossRewardBonuses/BAOBossRewardBonuses.dll

Decompiled 5 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("BAOBossRewardBonuses")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]
[assembly: AssemblyProduct("BAOBossRewardBonuses")]
[assembly: AssemblyTitle("BAOBossRewardBonuses")]
[assembly: AssemblyVersion("1.0.1.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace BaoCartBonus
{
	[BepInPlugin("local.baoenigma.bossrewardbonus", "BAO Boss Reward Bonuses", "1.0.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	public sealed class CartReceipt : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(Character), "OnDeath")]
		private static class DeathHook
		{
			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{
				//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c7: Expected O, but got Unknown
				//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
				//IL_0109: Expected O, but got Unknown
				List<CodeInstruction> list = instructions.ToList();
				MethodInfo destroy = AccessTools.Method(typeof(ZNetScene), "Destroy", new Type[1] { typeof(GameObject) }, (Type[])null);
				int[] array = (from x in list.Select((CodeInstruction v, int i) => new { v, i })
					where CodeInstructionExtensions.Calls(x.v, destroy)
					select x.i).ToArray();
				if (array.Length != 1)
				{
					throw new InvalidOperationException("RWD736: unsupported Character.OnDeath destroy layout; refusing to patch");
				}
				int num = array[0];
				CodeInstruction val = new CodeInstruction(OpCodes.Ldarg_0, (object)null);
				CodeInstructionExtensions.MoveLabelsTo(list[num], val);
				list.Insert(num, val);
				list.Insert(num + 1, new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(CartReceipt), "SendConfirmedDeath", (Type[])null, (Type[])null)));
				return list;
			}
		}

		private const string Rpc = "BAO_BossReward736_Death";

		private const string Marker = "baoReward736•confirmedDeath";

		private static CartReceipt Self;

		private static ZRoutedRpc registered;

		private static readonly HashSet<ZDOID> Sent = new HashSet<ZDOID>();

		private Harmony harmony;

		private float next;

		private static readonly string[] Bosses = new string[7] { "Eikthyr", "gd_king", "Bonemass", "Dragon", "GoblinKing", "SeekerQueen", "Fader" };

		private static readonly string[] Excluded = new string[8] { "townfall•hostile", "bossRaidSourceUntouchable", "bossRaidBeginnerEikthyr", "bf132•owned", "bossNemesis", "karlIntro", "enigma•nonKillDeparture", "bossRaidBoss" };

		private void Awake()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			Self = this;
			harmony = new Harmony("local.baoenigma.bossrewardbonus");
			harmony.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"RWD736|loaded|1.0.0|normal-boss-spawned-rewards|no-progression-credit|gameplay=UNVERIFIED");
		}

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

		private void Update()
		{
			if (!(Time.realtimeSinceStartup < next))
			{
				next = Time.realtimeSinceStartup + 1f;
				Register();
			}
		}

		private static void Register()
		{
			if (ZRoutedRpc.instance != null && registered != ZRoutedRpc.instance)
			{
				ZRoutedRpc.instance.Register<ZPackage>("BAO_BossReward736_Death", (Action<long, ZPackage>)Receive);
				registered = ZRoutedRpc.instance;
				Sent.Clear();
			}
		}

		private static bool Eligible(ZDO z)
		{
			return z != null && Bosses.Any((string n) => z.GetPrefab() == StringExtensionMethods.GetStableHashCode(n)) && !Excluded.Any((string k) => z.GetInt(k, 0) == 1);
		}

		public unsafe static void SendConfirmedDeath(Character actor)
		{
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Expected O, but got Unknown
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Register();
				if (!Object.op_Implicit((Object)(object)actor) || !actor.IsDead() || float.IsNaN(actor.GetHealth()) || actor.GetHealth() > 0f || ZRoutedRpc.instance == null || !Object.op_Implicit((Object)(object)ZNet.instance))
				{
					return;
				}
				ZNetView component = ((Component)actor).GetComponent<ZNetView>();
				if (!Object.op_Implicit((Object)(object)component) || !component.IsValid() || !component.IsOwner())
				{
					return;
				}
				ZDO zDO = component.GetZDO();
				if (Eligible(zDO) && Sent.Add(zDO.m_uid))
				{
					ZPackage val = new ZPackage();
					val.Write(zDO.m_uid);
					val.SetPos(0);
					if (ZNet.instance.IsServer())
					{
						Receive(ZNet.GetUID(), val);
					}
					else
					{
						ZRoutedRpc.instance.InvokeRoutedRPC("BAO_BossReward736_Death", new object[1] { val });
					}
					ManualLogSource logger = ((BaseUnityPlugin)Self).Logger;
					ZDOID uid = zDO.m_uid;
					logger.LogInfo((object)("RWD736|death-receipt-sent|boss=" + ((object)(*(ZDOID*)(&uid))/*cast due to .constrained prefix*/).ToString() + "|actualHealth=" + actor.GetHealth()));
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)Self).Logger.LogError((object)("RWD736|send-failed|" + ex));
			}
		}

		private unsafe static void Receive(long sender, ZPackage p)
		{
			//IL_0030: 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_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)ZNet.instance) || !ZNet.instance.IsServer() || ZDOMan.instance == null)
			{
				return;
			}
			try
			{
				ZDOID val = p.ReadZDOID();
				ZDO zDO = ZDOMan.instance.GetZDO(val);
				bool flag = sender == ZNet.GetUID();
				if (zDO == null || zDO.GetOwner() != sender || (!flag && ZNet.instance.GetPeer(sender) == null) || !Eligible(zDO))
				{
					ManualLogSource logger = ((BaseUnityPlugin)Self).Logger;
					ZDOID val2 = val;
					logger.LogWarning((object)("RWD736|receipt-rejected|boss=" + ((object)(*(ZDOID*)(&val2))/*cast due to .constrained prefix*/).ToString() + "|reason=missing-entity-owner-or-eligibility"));
				}
				else if (zDO.GetInt("baoReward736•confirmedDeath", 0) != 1)
				{
					zDO.Set("baoReward736•confirmedDeath", 1);
					ManualLogSource logger2 = ((BaseUnityPlugin)Self).Logger;
					ZDOID val2 = val;
					logger2.LogInfo((object)("RWD736|death-receipt-admitted|boss=" + ((object)(*(ZDOID*)(&val2))/*cast due to .constrained prefix*/).ToString() + "|snapshotHealth=" + zDO.GetFloat("health", -1f)));
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)Self).Logger.LogError((object)("RWD736|receive-failed|" + ex));
			}
		}
	}
}

plugins/BAOEnigmaBetaFeatures/BAOEnigmaBetaFeatures.dll

Decompiled 5 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("BAOEnigmaBetaFeatures")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("7.1.3.0")]
[assembly: AssemblyInformationalVersion("7.1.3")]
[assembly: AssemblyProduct("BAOEnigmaBetaFeatures")]
[assembly: AssemblyTitle("BAOEnigmaBetaFeatures")]
[assembly: AssemblyVersion("7.1.3.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace BaoEnigmaBeta
{
	[BepInPlugin("local.baoenigma.betafeatures", "BAO Enigma Multiplayer Beta Features", "7.1.3")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		private sealed class ResolvedSnapshot
		{
			internal FieldInfo StringsField;

			internal FieldInfo IntsField;

			internal Dictionary<int, string> Strings;

			internal Dictionary<int, int> Ints;
		}

		[HarmonyPatch]
		private static class EnigmaResolvedWrite
		{
			private static bool Prepare()
			{
				bool flag = AccessTools.TypeByName("Data.ResolvedDataEntry") != null;
				if (!flag)
				{
					Log.LogInfo((object)"B746|client-compatible|EWP absent; server-only resolved trader write hook skipped");
				}
				return flag;
			}

			private static MethodBase TargetMethod()
			{
				Type type = AccessTools.TypeByName("Data.ResolvedDataEntry");
				if (type == null)
				{
					throw new MissingMemberException("Pinned EWP ResolvedDataEntry is missing");
				}
				return AccessTools.Method(type, "Write", new Type[1] { typeof(ZDO) }, (Type[])null);
			}

			private static void Prefix(object __instance, ZDO __0, out ResolvedSnapshot __state)
			{
				__state = null;
				if (!Object.op_Implicit((Object)(object)ZNet.instance) || !ZNet.instance.IsServer() || Data == null)
				{
					return;
				}
				try
				{
					FieldInfo fieldInfo = AccessTools.Field(__instance.GetType(), "Strings");
					FieldInfo fieldInfo2 = AccessTools.Field(__instance.GetType(), "Ints");
					Dictionary<int, string> dictionary = fieldInfo.GetValue(__instance) as Dictionary<int, string>;
					Dictionary<int, int> dictionary2 = fieldInfo2.GetValue(__instance) as Dictionary<int, int>;
					if (dictionary == null || dictionary.Count == 0)
					{
						return;
					}
					Dictionary<int, string> dictionary3 = new Dictionary<int, string>(dictionary);
					Dictionary<int, int> dictionary4 = ((dictionary2 != null) ? new Dictionary<int, int>(dictionary2) : new Dictionary<int, int>());
					if ((!dictionary4.TryGetValue(Key("enigma•coinOffer•schema"), out var value) || value == 0) && (!dictionary4.TryGetValue(Key("playerTradedOnce"), out value) || value == 0) && (!dictionary4.TryGetValue(Key("enigma•coinDeal•paid"), out value) || value == 0) && (!dictionary4.TryGetValue(Key("isWelcomeTrader"), out value) || value == 0) && (!dictionary4.TryGetValue(Key("enigma•summer•ally"), out value) || value == 0) && (!dictionary4.TryGetValue(Key("tfAFK•fixture"), out value) || value == 0) && ((dictionary4.TryGetValue(Key("CoinTrader"), out value) && value == 1) || __0.GetInt("CoinTrader", 0) == 1) && dictionary3.TryGetValue(Key("coinTraderRewardDataName"), out var value2))
					{
						ObserveString(__0, Key("coinTraderRewardDataName"), ref value2);
						dictionary3[Key("coinTraderRewardDataName")] = value2;
					}
					if (__0.GetInt("bao731•bound", 0) != 1)
					{
						return;
					}
					bool flag = (dictionary4.TryGetValue(Key("playerTradedOnce"), out value) && value != 0) || (dictionary4.TryGetValue(Key("enigma•coinDeal•paid"), out value) && value != 0);
					int[] array = new int[3]
					{
						Key("coinTraderRewardText"),
						Key("enigma•deal•page1"),
						Key("enigma•coinOffer•baseText")
					};
					foreach (int key in array)
					{
						if (!flag && dictionary3.TryGetValue(key, out var value3))
						{
							ObserveString(__0, key, ref value3);
							dictionary3[key] = value3;
						}
					}
					if (!flag && dictionary3.ContainsKey(Key("Humanoid.m_name")))
					{
						if (!dictionary4.TryGetValue(Key("wantsCoinPiles"), out var value4))
						{
							value4 = __0.GetInt("wantsCoinPiles", 0);
						}
						dictionary3[Key("Humanoid.m_name")] = "BAO Cointrader · " + __0.GetString("bao731•label", "") + ((value4 > 0) ? (" · " + value4 + " coin piles") : "");
					}
					string text = __0.GetString("bao731•oldFlag", "");
					string text2 = __0.GetString("bao731•newFlag", "");
					if (text.Length > 0 && dictionary4.ContainsKey(Key(text)))
					{
						dictionary4[Key(text)] = 0;
					}
					if (text2.Length > 0)
					{
						dictionary4[Key(text2)] = 1;
					}
					__state = new ResolvedSnapshot
					{
						StringsField = fieldInfo,
						IntsField = fieldInfo2,
						Strings = dictionary,
						Ints = dictionary2
					};
					fieldInfo.SetValue(__instance, dictionary3);
					fieldInfo2.SetValue(__instance, dictionary4);
				}
				catch (Exception ex)
				{
					if (__state != null)
					{
						__state.StringsField.SetValue(__instance, __state.Strings);
						__state.IntsField.SetValue(__instance, __state.Ints);
						__state = null;
					}
					Log.LogError((object)("B731|resolved-write-error|" + ex));
				}
			}

			private static Exception Finalizer(object __instance, ResolvedSnapshot __state, Exception __exception)
			{
				if (__state != null)
				{
					__state.StringsField.SetValue(__instance, __state.Strings);
					__state.IntsField.SetValue(__instance, __state.Ints);
				}
				return __exception;
			}
		}

		[HarmonyPatch(typeof(ZDO), "Set", new Type[]
		{
			typeof(int),
			typeof(string)
		})]
		private static class StringPatch
		{
			private static void Prefix(ZDO __instance, int __0, ref string __1)
			{
				ObserveString(__instance, __0, ref __1);
			}
		}

		[HarmonyPatch(typeof(ZDO), "Set", new Type[]
		{
			typeof(int),
			typeof(int),
			typeof(bool)
		})]
		private static class IntPatch
		{
			private static void Prefix(ZDO __instance, int __0, ref int __1)
			{
				ObserveInt(__instance, __0, ref __1);
			}
		}

		[HarmonyPatch(typeof(Container), "Awake")]
		private static class ContainerAwake
		{
			private static void Postfix(Container __instance)
			{
				Queue(__instance);
			}
		}

		[HarmonyPatch(typeof(Container), "Load")]
		private static class ContainerLoad
		{
			private static void Postfix(Container __instance, bool __result)
			{
				Queue(__instance);
				if (__result && Items.Count > 0)
				{
					try
					{
						TryLoot(__instance);
					}
					catch (Exception ex)
					{
						Log.LogError((object)("B731|loot-load-error|" + ex));
					}
				}
			}
		}

		[HarmonyPatch(typeof(Container), "OnContainerChanged")]
		private static class ContainerChange
		{
			private static void Prefix(Container __instance)
			{
				try
				{
					ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
					if (Object.op_Implicit((Object)(object)component) && component.IsValid() && component.GetZDO() != null && component.GetZDO().GetInt("bao731•loot", 0) == 1)
					{
						TryLoot(__instance);
					}
				}
				catch (Exception ex)
				{
					Log.LogError((object)("B731|loot-change-error|" + ex));
				}
			}
		}

		[HarmonyPatch(typeof(Container), "AddDefaultItems")]
		private static class ContainerDefaults
		{
			private static void Postfix(Container __instance)
			{
				Queue(__instance);
			}
		}

		[HarmonyPatch(typeof(Talker), "RPC_Say")]
		private static class ReportChat
		{
			private static void Prefix(Talker __instance, long __0, int __1, UserInfo __2, string __3)
			{
				try
				{
					Report(__instance, __0, __1, __3);
				}
				catch (Exception ex)
				{
					Log.LogError((object)("B731|report-error|" + ex));
				}
			}
		}

		[HarmonyPatch(typeof(ZNetScene), "Awake")]
		private static class AckRegistration
		{
			private static void Postfix()
			{
				RegisterReportAck();
			}
		}

		public const string Id = "local.baoenigma.betafeatures";

		internal static Plugin Self;

		internal static ManualLogSource Log;

		internal static Catalog Data;

		private Harmony harmony;

		internal static readonly Dictionary<string, LootCandidate> Items = new Dictionary<string, LootCandidate>();

		internal static readonly Dictionary<Container, float> Pending = new Dictionary<Container, float>();

		internal static readonly HashSet<string> Craftable = new HashSet<string>();

		private static ObjectDB catalogDb;

		private static int catalogCount;

		private static int queueCursor;

		[ThreadStatic]
		private static bool writing;

		internal static readonly Dictionary<string, int> Hashes = new Dictionary<string, int>();

		private static readonly HashSet<int> NativeFlags = new HashSet<int>();

		private static ZRoutedRpc registeredRpc;

		private static readonly Dictionary<long, DateTimeOffset> LastReport = new Dictionary<long, DateTimeOffset>();

		private static readonly Dictionary<long, string> LastText = new Dictionary<long, string>();

		private static readonly Queue<DateTimeOffset> GlobalReports = new Queue<DateTimeOffset>();

		private static readonly object ReportLock = new object();

		private static TimeZoneInfo reportZone;

		private static object Read(object o, string name)
		{
			if (o == null)
			{
				return null;
			}
			Type type = (o as Type) ?? o.GetType();
			FieldInfo field = type.GetField(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			return (field != null) ? field.GetValue((o is Type) ? null : o) : null;
		}

		private static void AddOwned(HashSet<string> owned, string type, string field, bool rawStrings = false)
		{
			Type o = AccessTools.TypeByName(type);
			if (!(Read(o, field) is IEnumerable enumerable))
			{
				return;
			}
			foreach (object item in enumerable)
			{
				string text = (rawStrings ? (item as string) : (Read(item, "PrefabId") as string));
				if (!string.IsNullOrEmpty(text))
				{
					owned.Add(text);
				}
			}
		}

		internal static void EnsureCatalog()
		{
			if (!Object.op_Implicit((Object)(object)ObjectDB.instance) || !Object.op_Implicit((Object)(object)ZNetScene.instance) || ((Object)(object)catalogDb == (Object)(object)ObjectDB.instance && catalogCount == ObjectDB.instance.m_items.Count && Items.Count > 0))
			{
				return;
			}
			catalogDb = ObjectDB.instance;
			catalogCount = ObjectDB.instance.m_items.Count;
			Items.Clear();
			Craftable.Clear();
			Dictionary<string, float> dictionary = new Dictionary<string, float>(Data.Tiers);
			HashSet<string> hashSet = new HashSet<string>(Data.Equipment.Keys);
			AddOwned(hashSet, "Balrond.Crafting.FoodBalanceCatalog", "FinishedFoods");
			AddOwned(hashSet, "Balrond.Crafting.FoodBalanceCatalog", "RawEdibleFoods");
			AddOwned(hashSet, "Balrond.Crafting.FoodBalanceCatalog", "SpecialConsumables");
			AddOwned(hashSet, "Balrond.Crafting.FoodBalanceCatalog", "NonEdibleRawIngredients", rawStrings: true);
			AddOwned(hashSet, "Balrond.Alchemy.AlchemyGeneratedPrefabCatalog", "DefinitionsInternal");
			HashSet<string> hashSet2 = new HashSet<string>();
			HashSet<string> ores = new HashSet<string>();
			foreach (Recipe recipe in ObjectDB.instance.m_recipes)
			{
				if (!Object.op_Implicit((Object)(object)recipe) || !recipe.m_enabled || !Object.op_Implicit((Object)(object)recipe.m_item))
				{
					continue;
				}
				Craftable.Add(((Object)recipe.m_item).name);
				Requirement[] array = (Requirement[])(((object)recipe.m_resources) ?? ((object)new Requirement[0]));
				foreach (Requirement val in array)
				{
					if (Object.op_Implicit((Object)(object)val.m_resItem))
					{
						hashSet2.Add(((Object)val.m_resItem).name);
					}
				}
			}
			List<ItemConversion> list = new List<ItemConversion>();
			foreach (GameObject prefab in ZNetScene.instance.m_prefabs)
			{
				if (!Object.op_Implicit((Object)(object)prefab))
				{
					continue;
				}
				Smelter component = prefab.GetComponent<Smelter>();
				if (!Object.op_Implicit((Object)(object)component))
				{
					continue;
				}
				foreach (ItemConversion item in component.m_conversion)
				{
					if (Object.op_Implicit((Object)(object)item.m_from) && Object.op_Implicit((Object)(object)item.m_to))
					{
						list.Add(item);
						ores.Add(((Object)item.m_from).name);
						ores.Add(((Object)item.m_to).name);
						string name = ((Object)item.m_from).name;
						string name2 = ((Object)item.m_to).name;
						if (name.EndsWith("_bal", StringComparison.Ordinal) || name.StartsWith("BAO_", StringComparison.Ordinal) || name2.EndsWith("_bal", StringComparison.Ordinal) || name2.StartsWith("BAO_", StringComparison.Ordinal))
						{
							hashSet.Add(name);
							hashSet.Add(name2);
						}
					}
				}
			}
			for (int j = 0; j < 16; j++)
			{
				bool flag = false;
				foreach (Recipe recipe2 in ObjectDB.instance.m_recipes)
				{
					if (!Object.op_Implicit((Object)(object)recipe2) || !Object.op_Implicit((Object)(object)recipe2.m_item) || !dictionary.TryGetValue(((Object)recipe2.m_item).name, out var value) || value < 0f)
					{
						continue;
					}
					Requirement[] array2 = (Requirement[])(((object)recipe2.m_resources) ?? ((object)new Requirement[0]));
					foreach (Requirement val2 in array2)
					{
						if (Object.op_Implicit((Object)(object)val2.m_resItem) && (!dictionary.TryGetValue(((Object)val2.m_resItem).name, out var value2) || value < value2))
						{
							dictionary[((Object)val2.m_resItem).name] = value;
							flag = true;
						}
					}
				}
				foreach (ItemConversion item2 in list)
				{
					if (dictionary.TryGetValue(((Object)item2.m_to).name, out var value3) && value3 >= 0f && (!dictionary.TryGetValue(((Object)item2.m_from).name, out var value4) || value3 < value4))
					{
						dictionary[((Object)item2.m_from).name] = value3;
						flag = true;
					}
				}
				if (!flag)
				{
					break;
				}
			}
			foreach (GameObject item3 in ObjectDB.instance.m_items)
			{
				if (!Object.op_Implicit((Object)(object)item3))
				{
					continue;
				}
				ItemDrop component2 = item3.GetComponent<ItemDrop>();
				if (!Object.op_Implicit((Object)(object)component2))
				{
					continue;
				}
				string name3 = ((Object)item3).name;
				SharedData shared = component2.m_itemData.m_shared;
				if ((!hashSet.Contains(name3) && !name3.EndsWith("_bal", StringComparison.Ordinal) && !name3.StartsWith("BAO_", StringComparison.Ordinal)) || shared.m_maxStackSize < 1 || ((object)Unsafe.As<ItemType, ItemType>(ref shared.m_itemType)/*cast due to .constrained prefix*/).ToString() == "Trophy")
				{
					continue;
				}
				string text = name3.ToLowerInvariant();
				if (text.Contains("upgrader") || text.Contains("key") || text.Contains("trophy") || text.Contains("bundle") || text.Contains("whistle") || text.Contains("attack"))
				{
					continue;
				}
				string text2 = null;
				if (Gear(shared) && Craftable.Contains(name3) && Data.Equipment.ContainsKey(name3) && shared.m_useDurability)
				{
					text2 = "equipment";
				}
				else if (ores.Contains(name3) || text.Contains("ore_") || text.EndsWith("ore", StringComparison.Ordinal) || text.Contains("scrap_") || text.EndsWith("scrap", StringComparison.Ordinal))
				{
					text2 = "ore-or-ingot";
				}
				else if (text.Contains("spice"))
				{
					text2 = "spice";
				}
				else if (text.Contains("mead") || text.Contains("potion") || text.Contains("tonic") || name3.StartsWith("BAO_Alchemy", StringComparison.Ordinal) || (Object.op_Implicit((Object)(object)shared.m_consumeStatusEffect) && ((object)Unsafe.As<ItemType, ItemType>(ref shared.m_itemType)/*cast due to .constrained prefix*/).ToString() == "Consumable"))
				{
					text2 = "potion-mead-alchemy";
				}
				else if (((object)Unsafe.As<ItemType, ItemType>(ref shared.m_itemType)/*cast due to .constrained prefix*/).ToString() == "Consumable" && (shared.m_food > 0f || shared.m_foodStamina > 0f || shared.m_foodEitr > 0f))
				{
					text2 = "food";
				}
				else if (hashSet2.Contains(name3) || hashSet.Contains(name3))
				{
					text2 = "ingredient-material";
				}
				if (text2 != null)
				{
					if (!dictionary.TryGetValue(name3, out var value5))
					{
						value5 = -1f;
					}
					Items[name3] = new LootCandidate
					{
						Id = name3,
						Category = text2,
						Tier = value5,
						Prefab = item3
					};
				}
			}
			string text3 = Path.Combine(Paths.BepInExRootPath, "BetaReports");
			Directory.CreateDirectory(text3);
			var array3 = (from x in Items.Values.OrderBy<LootCandidate, string>((LootCandidate x) => x.Id, StringComparer.Ordinal)
				select new
				{
					prefab = x.Id,
					category = x.Category,
					tier = x.Tier,
					unknown_minimum_biome = "Mountain",
					registered = true,
					craftable = Craftable.Contains(x.Id),
					smelter_form = ores.Contains(x.Id)
				}).ToArray();
			File.WriteAllText(Path.Combine(text3, "Registered_BAO_Beta_Pools.json"), JsonConvert.SerializeObject((object)array3, (Formatting)1), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
			var array4 = (from x in list
				where Items.ContainsKey(((Object)x.m_from).name) || Items.ContainsKey(((Object)x.m_to).name)
				select new
				{
					raw = ((Object)x.m_from).name,
					processed = ((Object)x.m_to).name,
					raw_eligible = Items.ContainsKey(((Object)x.m_from).name),
					processed_eligible = Items.ContainsKey(((Object)x.m_to).name)
				}).Distinct().ToArray();
			File.WriteAllText(Path.Combine(text3, "Registered_Ore_Ingot_Pairs.json"), JsonConvert.SerializeObject((object)array4, (Formatting)1), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
			Log.LogInfo((object)("B731|pools-ready|registered=" + Items.Count + "|ore-and-ingot-forms=" + Items.Values.Count((LootCandidate x) => x.Category == "ore-or-ingot") + "|unknown-tier=" + Items.Values.Count((LootCandidate x) => x.Tier < 0f)));
		}

		internal unsafe static bool TryLoot(Container c)
		{
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_028f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0294: Unknown result type (might be due to invalid IL or missing references)
			//IL_0538: Unknown result type (might be due to invalid IL or missing references)
			//IL_053d: Unknown result type (might be due to invalid IL or missing references)
			ZNetView component = ((Component)c).GetComponent<ZNetView>();
			if (!Object.op_Implicit((Object)(object)component) || !component.IsValid())
			{
				return false;
			}
			ZDO zDO = component.GetZDO();
			if (zDO == null)
			{
				return false;
			}
			if (zDO.GetInt("bao731•loot", 0) >= 2)
			{
				return true;
			}
			if (!component.IsOwner())
			{
				return false;
			}
			if (zDO.GetInt("loot152•schema", 0) != 1 || string.IsNullOrEmpty(zDO.GetString("loot152•birth", "")) || string.IsNullOrEmpty(zDO.GetString("loot152•world", "")))
			{
				return false;
			}
			if (zDO.GetPrefab() != Key("CargoCrate") || zDO.GetLong("creator", 0L) != 0)
			{
				return false;
			}
			if (zDO.GetInt("cointraderRewardChest", 0) != 0 || zDO.GetInt("enigma•box•schema", 0) != 0 || zDO.GetInt("enigma•cargo•rewardCrate", 0) != 0 || zDO.GetInt("dungeonLootingCrate", 0) != 0 || zDO.GetInt("tfAFK•fixture", 0) != 0 || zDO.GetInt("bp4•schema", 0) != 0 || zDO.GetInt("bp143•schema", 0) != 0)
			{
				return true;
			}
			Inventory inventory = c.GetInventory();
			if (inventory == null || inventory.GetAllItems().Count == 0)
			{
				return false;
			}
			ZDOID uid;
			if (zDO.GetInt("bao731•loot", 0) == 0)
			{
				int biome = BiomeTier(((Component)c).transform.position);
				if (biome < 0)
				{
					return true;
				}
				string text = ((object)Unsafe.As<ZDOID, ZDOID>(ref zDO.m_uid)/*cast due to .constrained prefix*/).ToString() + "|loot731";
				LootCandidate[] array = Items.Values.Where((LootCandidate x) => (x.Tier >= 0f && Math.Floor(x.Tier) <= (double)biome) || (x.Tier < 0f && biome >= 3)).OrderBy<LootCandidate, string>((LootCandidate x) => x.Id, StringComparer.Ordinal).ToArray();
				if (array.Length == 0)
				{
					return true;
				}
				bool flag = Roll(text) % 10000 < 500;
				ManualLogSource log = Log;
				string[] obj = new string[8] { "B731|loot-roll|actor=", null, null, null, null, null, null, null };
				uid = zDO.m_uid;
				obj[1] = ((object)(*(ZDOID*)(&uid))/*cast due to .constrained prefix*/).ToString();
				obj[2] = "|biome-tier=";
				obj[3] = biome.ToString();
				obj[4] = "|candidates=";
				obj[5] = array.Length.ToString();
				obj[6] = "|selected=";
				obj[7] = flag.ToString();
				log.LogInfo((object)string.Concat(obj));
				if (!flag)
				{
					zDO.Set("bao731•loot", 3);
					return true;
				}
				string[] array2 = array.Select((LootCandidate x) => x.Category).Distinct().OrderBy<string, string>((string x) => x, StringComparer.Ordinal)
					.ToArray();
				string category = array2[Roll(text + "|category") % (uint)array2.Length];
				LootCandidate[] array3 = array.Where((LootCandidate x) => x.Category == category).ToArray();
				LootCandidate lootCandidate = array3[Roll(text + "|item") % (uint)array3.Length];
				int val = ((lootCandidate.Category == "equipment") ? 1 : Math.Min(lootCandidate.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_maxStackSize, (lootCandidate.Category == "ore-or-ingot") ? 5 : 3));
				int num = (int)(1 + Roll(text + "|stack") % (uint)Math.Max(1, val));
				zDO.Set("bao731•lootPrefab", lootCandidate.Id);
				zDO.Set("bao731•lootStack", num);
				zDO.Set("bao731•loot", 1);
			}
			if (inventory.GetEmptySlots() < 1)
			{
				return false;
			}
			string text2 = zDO.GetString("bao731•lootPrefab", "");
			int num2 = zDO.GetInt("bao731•lootStack", 0);
			if (!Items.TryGetValue(text2, out var value) || num2 < 1)
			{
				return true;
			}
			ItemData val2 = value.Prefab.GetComponent<ItemDrop>().m_itemData.Clone();
			val2.m_dropPrefab = value.Prefab;
			val2.m_stack = Math.Min(num2, val2.m_shared.m_maxStackSize);
			val2.m_quality = 1;
			zDO.Set("bao731•loot", 2);
			int stack = val2.m_stack;
			bool flag2 = inventory.AddItem(val2);
			ManualLogSource log2 = Log;
			string[] obj2 = new string[9] { "B731|loot-result|actor=", null, null, null, null, null, null, null, null };
			uid = zDO.m_uid;
			obj2[1] = ((object)(*(ZDOID*)(&uid))/*cast due to .constrained prefix*/).ToString();
			obj2[2] = "|prefab=";
			obj2[3] = text2;
			obj2[4] = "|stack=";
			obj2[5] = stack.ToString();
			obj2[6] = "|success=";
			obj2[7] = flag2.ToString();
			obj2[8] = "|no-automatic-retry-after-add";
			log2.LogInfo((object)string.Concat(obj2));
			return true;
		}

		private void Awake()
		{
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Expected O, but got Unknown
			Self = this;
			Log = ((BaseUnityPlugin)this).Logger;
			string path = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "Catalog.json");
			Data = JsonConvert.DeserializeObject<Catalog>(File.ReadAllText(path));
			if (Data == null || Data.Version != "7.1.0-beta.2")
			{
				throw new InvalidDataException("Wrong beta catalog version");
			}
			foreach (string key in Data.NativeOffers.Keys)
			{
				NativeFlags.Add(Key(key.Split('•')[0] + "CoinTrader"));
			}
			harmony = new Harmony("local.baoenigma.betafeatures");
			harmony.PatchAll(typeof(Plugin).Assembly);
			((MonoBehaviour)this).StartCoroutine(Work());
			((BaseUnityPlugin)this).Logger.LogInfo((object)"B731|loaded|beta.2|trade=6% eligible new offers|loot=5% bonus roll|unknown tiers=Mountains onward|gameplay=NOT VERIFIED");
		}

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

		internal static int Key(string s)
		{
			if (Hashes.TryGetValue(s, out var value))
			{
				return value;
			}
			int num = 5381;
			int num2 = num;
			for (int i = 0; i < s.Length && s[i] != 0; i += 2)
			{
				num = ((num << 5) + num) ^ s[i];
				if (i == s.Length - 1 || s[i + 1] == '\0')
				{
					break;
				}
				num2 = ((num2 << 5) + num2) ^ s[i + 1];
			}
			value = num + num2 * 1566083941;
			Hashes[s] = value;
			return value;
		}

		internal static uint Roll(string s)
		{
			uint num = 2166136261u;
			foreach (char c in s)
			{
				num ^= c;
				num *= 16777619;
			}
			return num;
		}

		internal static int BiomeTier(Vector3 pos)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			if (WorldGenerator.instance == null)
			{
				return -1;
			}
			return ((object)WorldGenerator.instance.GetBiome(pos)/*cast due to .constrained prefix*/).ToString() switch
			{
				"Meadows" => 0, 
				"BlackForest" => 1, 
				"Swamp" => 2, 
				"Mountain" => 3, 
				"Plains" => 4, 
				"Mistlands" => 5, 
				"AshLands" => 6, 
				"DeepNorth" => 7, 
				_ => -1, 
			};
		}

		internal static bool Gear(SharedData s)
		{
			string text = ((object)Unsafe.As<ItemType, ItemType>(ref s.m_itemType)/*cast due to .constrained prefix*/).ToString();
			int result;
			switch (text)
			{
			default:
				result = ((text == "Shoulder") ? 1 : 0);
				break;
			case "OneHandedWeapon":
			case "TwoHandedWeapon":
			case "TwoHandedWeaponLeft":
			case "Bow":
			case "Helmet":
			case "Chest":
			case "Legs":
				result = 1;
				break;
			}
			return (byte)result != 0;
		}

		internal static bool Armor(SharedData s)
		{
			string text = ((object)Unsafe.As<ItemType, ItemType>(ref s.m_itemType)/*cast due to .constrained prefix*/).ToString();
			int result;
			switch (text)
			{
			default:
				result = ((text == "Shoulder") ? 1 : 0);
				break;
			case "Helmet":
			case "Chest":
			case "Legs":
				result = 1;
				break;
			}
			return (byte)result != 0;
		}

		private IEnumerator Work()
		{
			while (true)
			{
				yield return (object)new WaitForSeconds(1f);
				try
				{
					RegisterReportAck();
					if (!Object.op_Implicit((Object)(object)ObjectDB.instance) || !Object.op_Implicit((Object)(object)ZNetScene.instance) || !Object.op_Implicit((Object)(object)ZNet.instance))
					{
						continue;
					}
					EnsureCatalog();
					KeyValuePair<Container, float>[] pending = Pending.ToArray();
					for (int i = 0; i < Math.Min(32, pending.Length); i++)
					{
						KeyValuePair<Container, float> pair = pending[(queueCursor + i) % pending.Length];
						if (!Object.op_Implicit((Object)(object)pair.Key) || Time.time > pair.Value || TryLoot(pair.Key))
						{
							Pending.Remove(pair.Key);
						}
					}
					if (pending.Length != 0)
					{
						queueCursor = (queueCursor + 32) % pending.Length;
					}
				}
				catch (Exception ex)
				{
					Log.LogError((object)("B731|work-error|" + ex));
				}
			}
		}

		internal static void Queue(Container c)
		{
			if (!Object.op_Implicit((Object)(object)c) || Pending.ContainsKey(c))
			{
				return;
			}
			ZNetView component = ((Component)c).GetComponent<ZNetView>();
			if (Object.op_Implicit((Object)(object)component) && component.IsValid())
			{
				if (component.GetZDO() == null || component.GetZDO().GetPrefab() != Key("CargoCrate"))
				{
					return;
				}
			}
			else if (((Object)((Component)c).gameObject).name != "CargoCrate" && ((Object)((Component)c).gameObject).name != "CargoCrate(Clone)")
			{
				return;
			}
			Pending[c] = Time.time + 90f;
		}

		internal unsafe static void ObserveString(ZDO z, int key, ref string value)
		{
			//IL_0232: Unknown result type (might be due to invalid IL or missing references)
			//IL_0329: Unknown result type (might be due to invalid IL or missing references)
			//IL_032e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0672: Unknown result type (might be due to invalid IL or missing references)
			//IL_0677: Unknown result type (might be due to invalid IL or missing references)
			if (writing || Data == null || (key != Key("coinTraderRewardDataName") && key != Key("coinTraderRewardText") && key != Key("enigma•deal•page1") && key != Key("enigma•coinOffer•baseText")) || !Object.op_Implicit((Object)(object)ZNet.instance) || !ZNet.instance.IsServer() || !Object.op_Implicit((Object)(object)ZNetScene.instance))
			{
				return;
			}
			try
			{
				writing = true;
				if (key == Key("coinTraderRewardDataName"))
				{
					if (!Data.NativeOffers.TryGetValue(value ?? "", out var value2))
					{
						return;
					}
					if (z.GetInt("bao731•decision", 0) == 0)
					{
						GameObject prefab = ZNetScene.instance.GetPrefab(z.GetPrefab());
						if (!Object.op_Implicit((Object)(object)prefab) || !Object.op_Implicit((Object)(object)prefab.GetComponent<NpcTalk>()) || (!z.IsOwner() && z.GetOwner() != 0) || z.GetInt("isWelcomeTrader", 0) != 0 || z.GetInt("enigma•summer•ally", 0) != 0 || z.GetInt("tfAFK•fixture", 0) != 0 || z.GetInt("enigma•coinOffer•schema", 0) != 0 || z.GetInt("playerTradedOnce", 0) != 0 || z.GetInt("enigma•coinDeal•paid", 0) != 0 || !string.IsNullOrEmpty(z.GetString("enigma•coinDeal•id", "")))
						{
							return;
						}
						EnsureCatalog();
						GameObject val = (Object.op_Implicit((Object)(object)ObjectDB.instance) ? ObjectDB.instance.GetItemPrefab(value2) : null);
						ItemDrop sourceDrop = (Object.op_Implicit((Object)(object)val) ? val.GetComponent<ItemDrop>() : null);
						if (!Object.op_Implicit((Object)(object)sourceDrop) || !Gear(sourceDrop.m_itemData.m_shared))
						{
							return;
						}
						int biome = BiomeTier(z.GetPosition());
						if (!Data.Tiers.TryGetValue(value2, out var tier))
						{
							tier = biome;
						}
						LootCandidate[] array = Items.Values.Where((LootCandidate x) => Data.Equipment.ContainsKey(x.Id) && Craftable.Contains(x.Id) && Gear(x.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared) && Armor(x.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared) == Armor(sourceDrop.m_itemData.m_shared) && ((x.Tier >= 0f && tier >= 0f && Math.Floor(x.Tier) == Math.Floor(tier)) || (x.Tier < 0f && Math.Max(tier, biome) >= 3f))).OrderBy<LootCandidate, string>((LootCandidate x) => x.Id, StringComparer.Ordinal).ToArray();
						if (array.Length == 0)
						{
							return;
						}
						z.Set("bao731•decision", 1);
						string text = ((object)Unsafe.As<ZDOID, ZDOID>(ref z.m_uid)/*cast due to .constrained prefix*/).ToString() + "|trade731";
						bool flag = Roll(text) % 10000 < 600;
						ManualLogSource log = Log;
						string[] obj = new string[10] { "B731|offer-roll|actor=", null, null, null, null, null, null, null, null, null };
						ZDOID uid = z.m_uid;
						obj[1] = ((object)(*(ZDOID*)(&uid))/*cast due to .constrained prefix*/).ToString();
						obj[2] = "|source=";
						obj[3] = value2;
						obj[4] = "|tier=";
						obj[5] = tier.ToString();
						obj[6] = "|candidates=";
						obj[7] = array.Length.ToString();
						obj[8] = "|selected=";
						obj[9] = flag.ToString();
						log.LogInfo((object)string.Concat(obj));
						if (!flag)
						{
							return;
						}
						LootCandidate lootCandidate = array[Roll(text + "|item") % (uint)array.Length];
						ItemDrop component = lootCandidate.Prefab.GetComponent<ItemDrop>();
						SharedData shared = component.m_itemData.m_shared;
						int num = (int)(1 + Roll(text + "|quality") % (uint)Math.Max(1, Math.Min(12, shared.m_maxQuality)));
						int num2 = (int)(1 + Roll(text + "|temper") % 3);
						ItemData val2 = component.m_itemData.Clone();
						val2.m_quality = num;
						float maxDurability = val2.GetMaxDurability();
						float num3 = Math.Max(maxDurability, 4f * shared.m_maxDurability + (float)(2 * (num - 1)) * shared.m_durabilityPerLevel);
						float num4 = maxDurability + (num3 - maxDurability) * num2 switch
						{
							2 => 0.5f, 
							1 => 0.25f, 
							_ => 1f, 
						};
						if (maxDurability <= 0f || !float.IsFinite(num4))
						{
							return;
						}
						string text2 = Data.Equipment[lootCandidate.Id].Reward + (value.EndsWith("•MKXLII", StringComparison.Ordinal) ? "•MKXLII" : "");
						string text3 = ((Localization.instance != null) ? Localization.instance.Localize(shared.m_name) : lootCandidate.Id);
						string text4 = text3 + " · quality " + num + " · temper " + num2 + " · durability " + num4.ToString("0.#", CultureInfo.InvariantCulture);
						z.Set("bao731•sourceReward", value);
						z.Set("bao731•targetReward", text2);
						z.Set("bao731•prefab", lootCandidate.Id);
						z.Set("bao731•oldFlag", value.Split('•')[0] + "CoinTrader");
						z.Set("bao731•newFlag", Data.Equipment[lootCandidate.Id].Reward + "CoinTrader");
						z.Set("bao731•quality", num);
						z.Set("bao731•temper", num2);
						z.Set("bao731•durability", num4);
						z.Set("bao731•label", text4);
						z.Set(z.GetString("bao731•oldFlag", ""), 0);
						z.Set(z.GetString("bao731•newFlag", ""), 1);
						z.Set("bao731•bound", 1);
						ManualLogSource log2 = Log;
						string[] obj2 = new string[15]
						{
							"B731|offer-bound|actor=", null, null, null, null, null, null, null, null, null,
							null, null, null, null, null
						};
						uid = z.m_uid;
						obj2[1] = ((object)(*(ZDOID*)(&uid))/*cast due to .constrained prefix*/).ToString();
						obj2[2] = "|source=";
						obj2[3] = value2;
						obj2[4] = "|item=";
						obj2[5] = lootCandidate.Id;
						obj2[6] = "|tier=";
						obj2[7] = lootCandidate.Tier.ToString();
						obj2[8] = "|quality=";
						obj2[9] = num.ToString();
						obj2[10] = "|temper=";
						obj2[11] = num2.ToString();
						obj2[12] = "|durability=";
						obj2[13] = num4.ToString();
						obj2[14] = "|price=original-native-offer|payment=unchanged";
						log2.LogInfo((object)string.Concat(obj2));
					}
					if (z.GetInt("bao731•bound", 0) == 1)
					{
						value = z.GetString("bao731•targetReward", value);
					}
				}
				else if (z.GetInt("bao731•bound", 0) == 1 && z.GetInt("playerTradedOnce", 0) == 0 && z.GetInt("enigma•coinDeal•paid", 0) == 0)
				{
					value = z.GetString("bao731•label", value);
				}
			}
			catch (Exception ex)
			{
				Log.LogError((object)("B731|offer-error|" + ex));
			}
			finally
			{
				writing = false;
			}
		}

		internal static void ObserveInt(ZDO z, int key, ref int value)
		{
			if (!writing && NativeFlags.Contains(key) && z.GetInt("bao731•bound", 0) == 1)
			{
				string text = z.GetString("bao731•oldFlag", "");
				if (text.Length > 0 && key == Key(text))
				{
					value = 0;
				}
			}
		}

		internal static void RegisterReportAck()
		{
			if (ZRoutedRpc.instance != null && registeredRpc != ZRoutedRpc.instance)
			{
				ZRoutedRpc.instance.Register<string>("BAO_Beta_ReportAck", (Action<long, string>)OnReportAck);
				registeredRpc = ZRoutedRpc.instance;
			}
		}

		private static void OnReportAck(long sender, string text)
		{
			if (ZRoutedRpc.instance != null && Object.op_Implicit((Object)(object)ZNet.instance) && ZNet.instance.GetServerPeer() != null && sender == ZNet.instance.GetServerPeer().m_uid && Object.op_Implicit((Object)(object)Player.m_localPlayer))
			{
				((Character)Player.m_localPlayer).Message((MessageType)1, text, 0, (Sprite)null, false);
			}
		}

		private static void Ack(long target, string text)
		{
			if (ZRoutedRpc.instance != null)
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(target, "BAO_Beta_ReportAck", new object[1] { text });
			}
		}

		private static TimeZoneInfo ReportZone()
		{
			if (reportZone != null)
			{
				return reportZone;
			}
			string[] array = new string[2] { "America/New_York", "Eastern Standard Time" };
			foreach (string id in array)
			{
				try
				{
					reportZone = TimeZoneInfo.FindSystemTimeZoneById(id);
					return reportZone;
				}
				catch (TimeZoneNotFoundException)
				{
				}
				catch (InvalidTimeZoneException)
				{
				}
			}
			reportZone = TimeZoneInfo.Utc;
			Log.LogWarning((object)"B731|reports|Eastern timezone unavailable; using UTC filenames/timestamps");
			return reportZone;
		}

		internal static void Report(Talker talker, long sender, int chatType, string text)
		{
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0332: Unknown result type (might be due to invalid IL or missing references)
			//IL_0340: Unknown result type (might be due to invalid IL or missing references)
			//IL_034e: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)ZNet.instance) || !ZNet.instance.IsServer() || text == null || (!text.Trim().Equals("bug", StringComparison.OrdinalIgnoreCase) && !text.TrimStart().StartsWith("bug ", StringComparison.OrdinalIgnoreCase)))
			{
				return;
			}
			ZNetPeer peer = ZNet.instance.GetPeer(sender);
			ZNetView val = (Object.op_Implicit((Object)(object)talker) ? ((Component)talker).GetComponent<ZNetView>() : null);
			if (peer == null || !Object.op_Implicit((Object)(object)val) || !val.IsValid() || val.GetZDO() == null)
			{
				return;
			}
			ZDO zDO = val.GetZDO();
			if (!(zDO.m_uid == peer.m_characterID) && (peer.m_playerID == 0L || zDO.GetLong("playerID", 0L) != peer.m_playerID || zDO.GetOwner() != sender))
			{
				return;
			}
			string text2 = text.Trim();
			text2 = ((text2.Length > 3) ? text2.Substring(3).Trim() : "");
			if (text2.Length == 0)
			{
				Ack(sender, "Report a problem with: bug box not working");
				return;
			}
			bool flag = text2.Length > 500;
			if (flag)
			{
				text2 = text2.Substring(0, 500);
			}
			StringBuilder stringBuilder = new StringBuilder();
			string text3 = text2;
			foreach (char c in text3)
			{
				stringBuilder.Append(char.IsControl(c) ? ' ' : c);
			}
			text2 = stringBuilder.ToString().Trim();
			DateTimeOffset utcNow = DateTimeOffset.UtcNow;
			lock (ReportLock)
			{
				if (LastReport.TryGetValue(sender, out var value) && (utcNow - value).TotalSeconds < 10.0)
				{
					if (!LastText.TryGetValue(sender, out var value2) || !(value2 == text2))
					{
						Ack(sender, "Please wait 10 seconds between bug reports.");
					}
					return;
				}
				while (GlobalReports.Count > 0 && (utcNow - GlobalReports.Peek()).TotalMinutes >= 1.0)
				{
					GlobalReports.Dequeue();
				}
				if (GlobalReports.Count >= 120)
				{
					Ack(sender, "The report log is busy. Please try again in one minute.");
					return;
				}
				DateTimeOffset dateTimeOffset = TimeZoneInfo.ConvertTime(utcNow, ReportZone());
				string text4 = Guid.NewGuid().ToString("N").Substring(0, 12);
				Vector3 position = ((Component)val).transform.position;
				var anon = new
				{
					report_id = text4,
					timestamp = dateTimeOffset.ToString("o"),
					timestamp_utc = utcNow.ToString("o"),
					timezone = ReportZone().Id,
					pack_version = "7.1.0-beta.2",
					player = peer.m_playerName,
					player_id = peer.m_playerID,
					character_zdo = ((object)Unsafe.As<ZDOID, ZDOID>(ref peer.m_characterID)/*cast due to .constrained prefix*/).ToString(),
					sender_session = sender,
					chat_type = chatType,
					position = new
					{
						x = Math.Round(position.x, 1),
						y = Math.Round(position.y, 1),
						z = Math.Round(position.z, 1)
					},
					message = text2,
					truncated = flag
				};
				string text5 = Path.Combine(Paths.BepInExRootPath, "BetaReports");
				try
				{
					Directory.CreateDirectory(text5);
					string text6 = JsonConvert.SerializeObject((object)anon);
					File.AppendAllText(Path.Combine(text5, "bugs-" + dateTimeOffset.ToString("yyyy-MM-dd") + ".jsonl"), text6 + Environment.NewLine, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
					Log.LogInfo((object)("BETA_BUG|" + text6));
					LastReport[sender] = utcNow;
					LastText[sender] = text2;
					GlobalReports.Enqueue(utcNow);
					Ack(sender, "Bug report saved: " + text4 + (flag ? " (first 500 characters)" : ""));
				}
				catch (Exception ex)
				{
					Log.LogError((object)("B731|bug-report-save-failed|" + ex));
					Ack(sender, "Bug report could not be saved. Please tell the server administrator.");
				}
			}
		}
	}
	public sealed class Binding
	{
		public string Reward;

		public float Tier;

		public string Kind;
	}
	public sealed class Catalog
	{
		public string Version;

		public Dictionary<string, string> NativeOffers;

		public Dictionary<string, Binding> Equipment;

		public Dictionary<string, float> Tiers;
	}
	public sealed class LootCandidate
	{
		public string Id;

		public string Category;

		public float Tier;

		public GameObject Prefab;
	}
}

plugins/BAOEnigmaBoltParity/BAOEnigmaBoltParity.dll

Decompiled 5 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("BAOEnigmaBoltParity")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("7.1.1.0")]
[assembly: AssemblyInformationalVersion("7.1.1")]
[assembly: AssemblyProduct("BAOEnigmaBoltParity")]
[assembly: AssemblyTitle("BAOEnigmaBoltParity")]
[assembly: AssemblyVersion("7.1.1.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace BaoEnigmaBoltParity
{
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("local.baoenigma.boltparity", "BAO Enigma Bolt Parity", "7.1.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		private static readonly Dictionary<int, GameObject> ElementalProjectiles = new Dictionary<int, GameObject>();

		private static readonly HashSet<string> SilverRecipes = new HashSet<string>(StringComparer.Ordinal);

		private static readonly HashSet<string> RoutedReports = new HashSet<string>();

		private static readonly Dictionary<string, int> VanillaElemental = new Dictionary<string, int>
		{
			{ "ArrowFire", 1 },
			{ "ArrowFrost", 2 },
			{ "ArrowSilver", 4 }
		};

		private static readonly FieldInfo HitEffects = AccessTools.Field(typeof(Projectile), "m_hitEffects");

		private static ObjectDB recipeDb;

		private static int recipeCount = -1;

		public const string Id = "local.baoenigma.boltparity";

		private static ManualLogSource Log;

		private static readonly HashSet<string> Reported = new HashSet<string>();

		private static readonly HashSet<string> Errors = new HashSet<string>();

		private static readonly MethodInfo Clone = typeof(object).GetMethod("MemberwiseClone", BindingFlags.Instance | BindingFlags.NonPublic);

		private Harmony harmony;

		private static void RegisterElementalProjectiles()
		{
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Expected O, but got Unknown
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Expected O, but got Unknown
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Expected O, but got Unknown
			//IL_0171: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Expected O, but got Unknown
			try
			{
				for (int i = 1; i <= 7; i++)
				{
					if (ElementalProjectiles.ContainsKey(i))
					{
						continue;
					}
					string text = (((i & 1) != 0) ? "bow_projectile_fire" : (((i & 2) != 0) ? "bow_projectile_frost" : "bow_projectile_silver"));
					string text2 = "RBBR_EnigmaAmmo750_" + i;
					GameObject val = PrefabManager.Instance.CreateClonedPrefab(text2, text);
					if (!Object.op_Implicit((Object)(object)val) || !Object.op_Implicit((Object)(object)val.GetComponent<Projectile>()))
					{
						throw new InvalidOperationException("Missing projectile source " + text);
					}
					Projectile component = val.GetComponent<Projectile>();
					EffectList val2 = (EffectList)HitEffects.GetValue(component);
					if (val2 != null && val2.m_effectPrefabs != null)
					{
						EffectList val3 = new EffectList();
						List<EffectData> list = val2.m_effectPrefabs.Where((EffectData e) => Object.op_Implicit((Object)(object)e.m_prefab) && ((Object)e.m_prefab).name != "vfx_frostarrow_hit" && ((Object)e.m_prefab).name != "vfx_UndeadBurn").ToList();
						string[] array = new string[2]
						{
							((i & 2) != 0) ? "vfx_frostarrow_hit" : null,
							((i & 4) != 0) ? "vfx_UndeadBurn" : null
						};
						foreach (string text3 in array)
						{
							if (text3 != null)
							{
								GameObject prefab = PrefabManager.Instance.GetPrefab(text3);
								if (!Object.op_Implicit((Object)(object)prefab))
								{
									throw new InvalidOperationException("Missing native hit effect " + text3);
								}
								list.Add(new EffectData
								{
									m_prefab = prefab,
									m_enabled = true,
									m_variant = -1
								});
							}
						}
						val3.m_effectPrefabs = list.ToArray();
						HitEffects.SetValue(component, val3);
					}
					PrefabManager.Instance.AddPrefab(new CustomPrefab(val, false));
					ElementalProjectiles[i] = val;
				}
				Log.LogInfo((object)("BLT750|projectiles-registered|count=" + ElementalProjectiles.Count));
			}
			catch (Exception ex)
			{
				Log.LogError((object)("BLT750|registration-failed|" + ex));
			}
		}

		private static bool Contains(string value, string word)
		{
			return !string.IsNullOrEmpty(value) && value.IndexOf(word, StringComparison.OrdinalIgnoreCase) >= 0;
		}

		private static string NameOf(ItemDrop drop)
		{
			return (Object.op_Implicit((Object)(object)drop) && drop.m_itemData != null && Object.op_Implicit((Object)(object)drop.m_itemData.m_dropPrefab)) ? ((Object)drop.m_itemData.m_dropPrefab).name : (Object.op_Implicit((Object)(object)drop) ? ((Object)((Component)drop).gameObject).name : null);
		}

		private static bool SilverResource(ItemDrop drop)
		{
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Invalid comparison between Unknown and I4
			string text = NameOf(drop);
			if (text == "Silver" || text == "SilverOre")
			{
				return true;
			}
			if (!Object.op_Implicit((Object)(object)drop))
			{
				return false;
			}
			string name = drop.m_itemData.m_shared.m_name;
			string value = ((Localization.instance != null) ? Localization.instance.Localize(name) : name);
			return (Contains(text, "silver") || Contains(value, "silver")) && (int)drop.m_itemData.m_shared.m_itemType == 1;
		}

		private static void RefreshSilverRecipes()
		{
			ObjectDB instance = ObjectDB.instance;
			if (!Object.op_Implicit((Object)(object)instance) || ((Object)(object)instance == (Object)(object)recipeDb && instance.m_recipes.Count == recipeCount))
			{
				return;
			}
			SilverRecipes.Clear();
			foreach (Recipe recipe in instance.m_recipes)
			{
				if (Object.op_Implicit((Object)(object)recipe) && Object.op_Implicit((Object)(object)recipe.m_item) && recipe.m_resources != null && recipe.m_resources.Any((Requirement r) => r != null && SilverResource(r.m_resItem)))
				{
					string text = NameOf(recipe.m_item);
					if (text != null)
					{
						SilverRecipes.Add(text);
					}
				}
			}
			recipeDb = instance;
			recipeCount = instance.m_recipes.Count;
		}

		private static void ApplyElementalRoute(ItemData item, string id)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Invalid comparison between Unknown and I4
			//IL_0294: Unknown result type (might be due to invalid IL or missing references)
			//IL_029b: Expected O, but got Unknown
			if (item == null || item.m_shared == null || string.IsNullOrEmpty(id))
			{
				return;
			}
			RefreshSilverRecipes();
			SharedData shared = item.m_shared;
			if ((int)shared.m_itemType != 9 || shared.m_attack == null)
			{
				return;
			}
			string value = ((Localization.instance != null) ? Localization.instance.Localize(shared.m_name) : shared.m_name);
			if (!Contains(id, "arrow") && !Contains(id, "bolt") && !Contains(shared.m_ammoType, "arrow") && !Contains(shared.m_ammoType, "bolt") && !Contains(value, "arrow") && !Contains(value, "bolt"))
			{
				return;
			}
			int num = 0;
			if (Contains(id, "fire") || Contains(id, "flame") || Contains(shared.m_name, "fire") || Contains(shared.m_name, "flame") || Contains(value, "fire") || Contains(value, "flame"))
			{
				num |= 1;
			}
			if (Contains(id, "frost") || Contains(shared.m_name, "frost") || Contains(value, "frost"))
			{
				num |= 2;
			}
			if (Contains(id, "silver") || Contains(shared.m_name, "silver") || Contains(value, "silver") || SilverRecipes.Contains(id))
			{
				num |= 4;
			}
			if (Mapping.Source(id) == "BoltBlackmetal")
			{
				num |= 1;
			}
			if (num == 0 || (VanillaElemental.TryGetValue(id, out var value2) && num == value2))
			{
				return;
			}
			if (!ElementalProjectiles.TryGetValue(num, out var value3))
			{
				if (RoutedReports.Add("missing:" + id))
				{
					Log.LogWarning((object)("BLT750|not-routed|item=" + id + "|mask=" + num + "|reason=projectile-not-registered"));
				}
				return;
			}
			if ((Object)(object)shared.m_attack.m_attackProjectile != (Object)(object)value3)
			{
				Attack val = (Attack)Clone.Invoke(shared.m_attack, null);
				val.m_attackProjectile = value3;
				shared.m_attack = val;
			}
			if (RoutedReports.Add(id + ":" + num))
			{
				Log.LogInfo((object)("BLT750|routed|item=" + id + "|mask=" + num + "|silverRecipe=" + SilverRecipes.Contains(id) + "|projectile=" + ((Object)value3).name));
			}
		}

		private void Awake()
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			PrefabManager.OnVanillaPrefabsAvailable += RegisterElementalProjectiles;
			harmony = new Harmony("local.baoenigma.boltparity");
			harmony.PatchAll(typeof(Plugin).Assembly);
			Type type = AccessTools.TypeByName("Balrond.Fletcher.FletcherPrefabService");
			if (type == null)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"BLT719|BAO Fletcher service missing; parity hooks unavailable");
				return;
			}
			Patch(type, "Build", "AfterBuild");
			Patch(type, "Get", "AfterGet");
			Patch(type, "MakeOutput", "AfterOutput");
			Patch(type, "Damage", "AfterDamage");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"BLT750|loaded|fire-flame=Enigma-arrow-explosion|frost=Enigma-arrow-nova|silver=Enigma-arrow-spirit-lightning|mixed=combined|gameplay=unverified");
			((MonoBehaviour)this).StartCoroutine(Startup());
		}

		private void Patch(Type type, string name, string callback)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method(type, name, (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				Log.LogError((object)("BLT719|missing-method=" + name));
				return;
			}
			harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), callback, (Type[])null)
			{
				priority = 0
			}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private IEnumerator Startup()
		{
			int i = 0;
			while (i < 30)
			{
				yield return (object)new WaitForSeconds(2f);
				Scan();
				int num = i + 1;
				i = num;
			}
		}

		private static GameObject Find(string name)
		{
			GameObject val = (Object.op_Implicit((Object)(object)ObjectDB.instance) ? ObjectDB.instance.GetItemPrefab(name) : null);
			return Object.op_Implicit((Object)(object)val) ? val : (Object.op_Implicit((Object)(object)ZNetScene.instance) ? ZNetScene.instance.GetPrefab(name) : null);
		}

		private static void Scan()
		{
			if (!Object.op_Implicit((Object)(object)ObjectDB.instance) || !Object.op_Implicit((Object)(object)ZNetScene.instance))
			{
				return;
			}
			RefreshSilverRecipes();
			GameObject[] array = ObjectDB.instance.m_items.ToArray();
			foreach (GameObject go in array)
			{
				Apply(go);
			}
			foreach (Player allPlayer in Player.GetAllPlayers())
			{
				foreach (ItemData allItem in ((Humanoid)allPlayer).GetInventory().GetAllItems())
				{
					Apply(allItem);
				}
			}
		}

		private static void AfterBuild()
		{
			Scan();
		}

		private static void AfterGet(GameObject __result)
		{
			Apply(__result);
		}

		private static void AfterOutput(ItemData __result)
		{
			Apply(__result);
		}

		private static void AfterDamage(object __0, ref DamageTypes __result)
		{
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			if (__0 == null)
			{
				return;
			}
			string name = AccessTools.Field(__0.GetType(), "Id")?.GetValue(__0) as string;
			string text = Mapping.Source(name, definition: true);
			if (text != null)
			{
				GameObject obj = Find(text);
				ItemDrop val = ((obj != null) ? obj.GetComponent<ItemDrop>() : null);
				if (Object.op_Implicit((Object)(object)val))
				{
					__result = val.m_itemData.m_shared.m_damages;
				}
			}
		}

		private static void Apply(GameObject go)
		{
			if (Object.op_Implicit((Object)(object)go))
			{
				ItemDrop component = go.GetComponent<ItemDrop>();
				if (Object.op_Implicit((Object)(object)component))
				{
					Apply(component.m_itemData, ((Object)go).name);
				}
			}
		}

		internal static void Apply(ItemData item, string name = null)
		{
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bc: Expected O, but got Unknown
			if (item == null || item.m_shared == null)
			{
				return;
			}
			name = name ?? (Object.op_Implicit((Object)(object)item.m_dropPrefab) ? ((Object)item.m_dropPrefab).name : null);
			string text = Mapping.Source(name);
			if (!Object.op_Implicit((Object)(object)ObjectDB.instance) || !Object.op_Implicit((Object)(object)ZNetScene.instance))
			{
				return;
			}
			if (text == null)
			{
				ApplyElementalRoute(item, name);
				return;
			}
			GameObject obj = Find(text);
			ItemDrop val = ((obj != null) ? obj.GetComponent<ItemDrop>() : null);
			string text2 = Mapping.Projectile(text);
			GameObject prefab = ZNetScene.instance.GetPrefab(text2);
			if (!Object.op_Implicit((Object)(object)val) || !Object.op_Implicit((Object)(object)prefab) || !Object.op_Implicit((Object)(object)prefab.GetComponent<Projectile>()))
			{
				if (Errors.Add(text))
				{
					Log.LogWarning((object)("BLT719|not-applied|missing-source-or-projectile=" + text + "/" + text2));
				}
				return;
			}
			SharedData shared = item.m_shared;
			SharedData shared2 = val.m_itemData.m_shared;
			if (shared.m_attack != null && shared != shared2)
			{
				shared.m_damages = shared2.m_damages;
				shared.m_damagesPerLevel = shared2.m_damagesPerLevel;
				shared.m_attackForce = shared2.m_attackForce;
				shared.m_backstabBonus = shared2.m_backstabBonus;
				shared.m_attackStatusEffect = shared2.m_attackStatusEffect;
				shared.m_attackStatusEffectChance = shared2.m_attackStatusEffectChance;
				if ((Object)(object)shared.m_attack.m_attackProjectile != (Object)(object)prefab)
				{
					Attack val2 = (Attack)Clone.Invoke(shared.m_attack, null);
					val2.m_attackProjectile = prefab;
					shared.m_attack = val2;
				}
				ApplyElementalRoute(item, name);
				if (Reported.Add(name))
				{
					Log.LogInfo((object)("BLT750|damage-parity|item=" + name + "|damageSource=" + text + "|projectile=" + ((Object)shared.m_attack.m_attackProjectile).name + "|damage=" + ((DamageTypes)(ref shared2.m_damages)).GetTotalDamage()));
				}
			}
		}

		private void OnDestroy()
		{
			PrefabManager.OnVanillaPrefabsAvailable -= RegisterElementalProjectiles;
			Harmony obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
		}
	}
	public static class Mapping
	{
		public static string Source(string name, bool definition = false)
		{
			if (string.IsNullOrEmpty(name))
			{
				return null;
			}
			name = name.Replace("(Clone)", "").Trim();
			switch (name)
			{
			case "BoltFire_bal":
				return "BoltBlackmetal";
			case "BoltSilver_bal":
				return "BoltIron";
			default:
				if (!(name == "BoltIce_bal"))
				{
					if (name.StartsWith("BAO_Ammo_v2_", StringComparison.Ordinal))
					{
						name = name.Substring("BAO_Ammo_v2_".Length);
					}
					else if (!definition)
					{
						return null;
					}
					string[] array = name.Split('_');
					if (array.Length != 3 || array[0] != "Bolt")
					{
						return null;
					}
					if (array[2] == "resin" || array[2] == "fire" || array[2] == "flame")
					{
						return "BoltBlackmetal";
					}
					if (array[2] == "frost" || array[2] == "ice")
					{
						return "BoltCarapace";
					}
					if (array[1] == "silver")
					{
						return "BoltIron";
					}
					return null;
				}
				goto case "BoltFrost_bal";
			case "BoltFrost_bal":
				return "BoltCarapace";
			}
		}

		public static string Projectile(string source)
		{
			return source switch
			{
				"BoltBlackmetal" => "arbalest_projectile_blackmetal", 
				"BoltCarapace" => "arbalest_projectile_carapace", 
				"BoltIron" => "arbalest_projectile_iron", 
				_ => null, 
			};
		}
	}
	[HarmonyPatch(typeof(ItemData), "GetDamage", new Type[] { })]
	internal static class DamageRefresh
	{
		[HarmonyPrefix]
		[HarmonyPriority(0)]
		private static void Prefix(ItemData __instance)
		{
			Plugin.Apply(__instance);
		}
	}
	[HarmonyPatch(typeof(ItemDrop), "Awake")]
	internal static class WorldDropRefresh
	{
		[HarmonyPostfix]
		private static void Postfix(ItemDrop __instance)
		{
			Plugin.Apply(__instance.m_itemData, ((Object)((Component)__instance).gameObject).name);
		}
	}
	[HarmonyPatch]
	internal static class InventoryRefresh
	{
		[HarmonyTargetMethods]
		private static IEnumerable<MethodBase> TargetMethods()
		{
			return (from m in AccessTools.GetDeclaredMethods(typeof(Inventory))
				where m.Name == "Load"
				select m).Cast<MethodBase>();
		}

		[HarmonyPostfix]
		private static void Postfix(Inventory __instance)
		{
			foreach (ItemData allItem in __instance.GetAllItems())
			{
				Plugin.Apply(allItem);
			}
		}
	}
	[HarmonyPatch(typeof(ItemData), "GetDamage", new Type[]
	{
		typeof(int),
		typeof(float)
	})]
	internal static class QualityDamageRefresh
	{
		[HarmonyPrefix]
		[HarmonyPriority(0)]
		private static void Prefix(ItemData __instance)
		{
			Plugin.Apply(__instance);
		}
	}
	internal static class SelfDamage
	{
		[HarmonyPatch(typeof(Projectile), "Setup")]
		internal static class RecordShooter
		{
			private static void Postfix(Projectile __instance, Character __0)
			{
				if (!IsAmmo(__instance))
				{
					return;
				}
				ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
				if (Object.op_Implicit((Object)(object)component) && component.IsValid() && component.IsOwner())
				{
					component.GetZDO().Set("rbbr756•shooterPeer", (__0 is Player) ? __0.GetOwner() : 0);
					if (__0 is Player)
					{
						__instance.m_hitOwner = false;
					}
				}
			}
		}

		[HarmonyPatch(typeof(Projectile), "OnHit")]
		internal static class Impact
		{
			private static void Prefix(Projectile __instance, out long __state)
			{
				__state = ImpactPeer;
				ImpactPeer = 0L;
				if (IsAmmo(__instance))
				{
					object? value = ProjectileOwner.GetValue(__instance);
					Player val = (Player)((value is Player) ? value : null);
					if (Object.op_Implicit((Object)(object)val))
					{
						ImpactPeer = ((Character)val).GetOwner();
					}
				}
			}

			private static Exception Finalizer(long __state, Exception __exception)
			{
				ImpactPeer = __state;
				return __exception;
			}
		}

		[HarmonyPatch(typeof(ZNetView), "Awake")]
		internal static class StampImpact
		{
			private static void Postfix(ZNetView __instance)
			{
				if (ImpactPeer != 0L && __instance.IsValid() && __instance.IsOwner())
				{
					__instance.GetZDO().Set("rbbr756•shooterPeer", ImpactPeer);
				}
			}
		}

		[HarmonyPatch(typeof(Aoe), "Setup")]
		internal static class NativeAoe
		{
			private static void Postfix(Aoe __instance)
			{
				if (ImpactPeer != 0)
				{
					__instance.m_hitOwner = false;
					ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
					if (Object.op_Implicit((Object)(object)component) && component.IsValid() && component.IsOwner())
					{
						component.GetZDO().Set("rbbr756•shooterPeer", ImpactPeer);
					}
				}
			}
		}

		[HarmonyPatch(typeof(Aoe), "OnHit")]
		internal static class ExcludeShooter
		{
			private static bool Prefix(Aoe __instance, Collider __0, ref bool __result)
			{
				if (!Object.op_Implicit((Object)(object)__0))
				{
					return true;
				}
				Player componentInParent = ((Component)__0).GetComponentInParent<Player>();
				if (!Object.op_Implicit((Object)(object)componentInParent))
				{
					return true;
				}
				ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
				long num = ((Object.op_Implicit((Object)(object)component) && component.IsValid()) ? component.GetZDO().GetLong("rbbr756•shooterPeer", 0L) : 0);
				if (num == 0L || num != ((Character)componentInParent).GetOwner())
				{
					return true;
				}
				__result = false;
				return false;
			}
		}

		[HarmonyPatch(typeof(Character), "Damage")]
		internal static class DirectDamage
		{
			private static bool Prefix(Character __instance, HitData __0)
			{
				return !Block(__instance, __0);
			}
		}

		[HarmonyPatch(typeof(Character), "RPC_Damage")]
		internal static class ReceivedDamage
		{
			private static bool Prefix(Character __instance, HitData __1)
			{
				return !Block(__instance, __1);
			}
		}

		internal const string Peer = "rbbr756•shooterPeer";

		[ThreadStatic]
		internal static long ImpactPeer;

		private static readonly FieldInfo ProjectileOwner = AccessTools.Field(typeof(Projectile), "m_owner");

		private static readonly FieldInfo AoeOwner = AccessTools.Field(typeof(Aoe), "m_owner");

		internal static bool IsAmmo(Projectile p)
		{
			string name = ((Object)((Component)p).gameObject).name;
			return name.IndexOf("arrow", StringComparison.OrdinalIgnoreCase) >= 0 || name.IndexOf("bolt", StringComparison.OrdinalIgnoreCase) >= 0 || name.StartsWith("bow_projectile", StringComparison.OrdinalIgnoreCase) || name.StartsWith("RBBR_EnigmaAmmo750_", StringComparison.Ordinal);
		}

		private static bool Block(Character victim, HitData hit)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Invalid comparison between Unknown and I4
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Invalid comparison between Unknown and I4
			if (!(victim is Player) || hit == null || !hit.m_ranged)
			{
				return false;
			}
			ZNetView component = ((Component)victim).GetComponent<ZNetView>();
			return Object.op_Implicit((Object)(object)component) && component.IsValid() && hit.m_attacker == component.GetZDO().m_uid && ((int)hit.m_skill == 8 || (int)hit.m_skill == 14);
		}
	}
}

plugins/RBBREnigmaHelpFit/RBBREnigmaHelpFit.dll

Decompiled 5 days ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using BepInEx;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("RBBREnigmaHelpFit")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0")]
[assembly: AssemblyProduct("RBBREnigmaHelpFit")]
[assembly: AssemblyTitle("RBBREnigmaHelpFit")]
[assembly: AssemblyVersion("0.1.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace RbbrHelpFit
{
	[BepInPlugin("local.rbbr.enigmahelpfit", "RBBR Enigma Help Display Fix", "0.1.0")]
	[BepInDependency("seneaL.valheim.ui", "1.2.8")]
	public sealed class HelpFit : BaseUnityPlugin
	{
		private sealed class Layout
		{
			internal bool Active;

			internal bool Auto;

			internal bool Wrap;

			internal bool Rich;

			internal float Font;

			internal float Min;

			internal float Max;

			internal float Character;

			internal float Word;

			internal float Line;

			internal FontStyles Style;

			internal TextAlignmentOptions Alignment;

			internal TextOverflowModes Overflow;

			internal Vector2 AnchorMin;

			internal Vector2 AnchorMax;

			internal Vector2 Pivot;

			internal Vector2 Position;

			internal Vector2 SizeDelta;

			internal Vector4 Margin;

			internal bool[] Decorations;

			internal string Formatted;

			internal float LastWidth;

			internal float LastHeight;

			internal void Capture(object view, TextMeshProUGUI t)
			{
				//IL_007e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0083: Unknown result type (might be due to invalid IL or missing references)
				//IL_008a: Unknown result type (might be due to invalid IL or missing references)
				//IL_008f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0096: Unknown result type (might be due to invalid IL or missing references)
				//IL_009b: 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_00a7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
				//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
				//IL_00de: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
				//IL_011d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0123: Expected O, but got Unknown
				if (!Active)
				{
					Auto = ((TMP_Text)t).enableAutoSizing;
					Wrap = ((TMP_Text)t).enableWordWrapping;
					Rich = ((TMP_Text)t).richText;
					Font = ((TMP_Text)t).fontSize;
					Min = ((TMP_Text)t).fontSizeMin;
					Max = ((TMP_Text)t).fontSizeMax;
					Character = ((TMP_Text)t).characterSpacing;
					Word = ((TMP_Text)t).wordSpacing;
					Line = ((TMP_Text)t).lineSpacing;
					Style = ((TMP_Text)t).fontStyle;
					Alignment = ((TMP_Text)t).alignment;
					Overflow = ((TMP_Text)t).overflowMode;
					Margin = ((TMP_Text)t).margin;
					RectTransform rectTransform = ((TMP_Text)t).rectTransform;
					AnchorMin = rectTransform.anchorMin;
					AnchorMax = rectTransform.anchorMax;
					Pivot = rectTransform.pivot;
					Position = rectTransform.anchoredPosition;
					SizeDelta = rectTransform.sizeDelta;
					Decorations = new bool[DecorationFields.Length];
					for (int i = 0; i < Decorations.Length; i++)
					{
						RectTransform val = (RectTransform)AccessTools.Field(View, DecorationFields[i]).GetValue(view);
						Decorations[i] = Object.op_Implicit((Object)(object)val) && ((Component)val).gameObject.activeSelf;
					}
				}
			}

			internal void Restore(object view, TextMeshProUGUI t)
			{
				//IL_0091: Unknown result type (might be due to invalid IL or missing references)
				//IL_009e: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
				//IL_0100: Unknown result type (might be due to invalid IL or missing references)
				//IL_0116: Unknown result type (might be due to invalid IL or missing references)
				//IL_011c: Expected O, but got Unknown
				//IL_0142: Unknown result type (might be due to invalid IL or missing references)
				//IL_016b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0172: Expected O, but got Unknown
				if (!Active)
				{
					return;
				}
				Active = false;
				((TMP_Text)t).enableAutoSizing = Auto;
				((TMP_Text)t).enableWordWrapping = Wrap;
				((TMP_Text)t).richText = Rich;
				((TMP_Text)t).fontSize = Font;
				((TMP_Text)t).fontSizeMin = Min;
				((TMP_Text)t).fontSizeMax = Max;
				((TMP_Text)t).characterSpacing = Character;
				((TMP_Text)t).wordSpacing = Word;
				((TMP_Text)t).lineSpacing = Line;
				((TMP_Text)t).fontStyle = Style;
				((TMP_Text)t).alignment = Alignment;
				((TMP_Text)t).overflowMode = Overflow;
				((TMP_Text)t).margin = Margin;
				RectTransform rectTransform = ((TMP_Text)t).rectTransform;
				rectTransform.anchorMin = AnchorMin;
				rectTransform.anchorMax = AnchorMax;
				rectTransform.pivot = Pivot;
				rectTransform.anchoredPosition = Position;
				rectTransform.sizeDelta = SizeDelta;
				RectTransform val = (RectTransform)BannerField.GetValue(view);
				if (Object.op_Implicit((Object)(object)val))
				{
					val.anchoredPosition = new Vector2(0f, -300f - (float)ShiftField.GetValue(view));
				}
				for (int i = 0; i < DecorationFields.Length; i++)
				{
					RectTransform val2 = (RectTransform)AccessTools.Field(View, DecorationFields[i]).GetValue(view);
					if (Object.op_Implicit((Object)(object)val2))
					{
						((Component)val2).gameObject.SetActive(Decorations[i]);
					}
				}
			}

			internal void Fit(object view, TextMeshProUGUI t)
			{
				//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b9: Expected O, but got Unknown
				//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
				//IL_004e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0053: Unknown result type (might be due to invalid IL or missing references)
				//IL_0065: Unknown result type (might be due to invalid IL or missing references)
				//IL_006a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0086: Unknown result type (might be due to invalid IL or missing references)
				//IL_008b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0097: Unknown result type (might be due to invalid IL or missing references)
				//IL_009c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0144: Unknown result type (might be due to invalid IL or missing references)
				//IL_0153: Unknown result type (might be due to invalid IL or missing references)
				//IL_0162: Unknown result type (might be due to invalid IL or missing references)
				//IL_016f: Unknown result type (might be due to invalid IL or missing references)
				//IL_019e: Unknown result type (might be due to invalid IL or missing references)
				//IL_01de: Unknown result type (might be due to invalid IL or missing references)
				//IL_010c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0112: Invalid comparison between Unknown and I4
				//IL_0273: Unknown result type (might be due to invalid IL or missing references)
				//IL_027a: Expected O, but got Unknown
				float num = 1280f;
				float num2 = 720f;
				Canvas canvas = ((Graphic)t).canvas;
				if (Object.op_Implicit((Object)(object)canvas) && Object.op_Implicit((Object)(object)canvas.rootCanvas))
				{
					Transform transform = ((Component)canvas.rootCanvas).transform;
					RectTransform val = (RectTransform)(object)((transform is RectTransform) ? transform : null);
					if (Object.op_Implicit((Object)(object)val))
					{
						Rect rect = val.rect;
						if (((Rect)(ref rect)).width > 0f)
						{
							rect = val.rect;
							if (((Rect)(ref rect)).height > 0f)
							{
								rect = val.rect;
								num = ((Rect)(ref rect)).width;
								rect = val.rect;
								num2 = ((Rect)(ref rect)).height;
							}
						}
					}
				}
				RectTransform val2 = (RectTransform)BannerField.GetValue(view);
				if (Object.op_Implicit((Object)(object)val2))
				{
					val2.anchoredPosition = new Vector2(0f, (0f - num2) * 0.45f);
				}
				if (LastWidth == num && LastHeight == num2 && ((TMP_Text)t).text == Formatted && ((TMP_Text)t).enableAutoSizing && (int)((TMP_Text)t).fontStyle == 0)
				{
					return;
				}
				LastWidth = num;
				LastHeight = num2;
				RectTransform rectTransform = ((TMP_Text)t).rectTransform;
				rectTransform.anchorMin = new Vector2(0.5f, 0.5f);
				rectTransform.anchorMax = rectTransform.anchorMin;
				rectTransform.pivot = rectTransform.anchorMin;
				rectTransform.anchoredPosition = Vector2.zero;
				rectTransform.sizeDelta = new Vector2(Mathf.Min(1000f, num * 0.86f), Mathf.Min(720f, num2 * 0.68f));
				((TMP_Text)t).richText = true;
				((TMP_Text)t).fontStyle = (FontStyles)0;
				((TMP_Text)t).characterSpacing = 0f;
				((TMP_Text)t).wordSpacing = 0f;
				((TMP_Text)t).lineSpacing = 0f;
				((TMP_Text)t).margin = Vector4.zero;
				((TMP_Text)t).enableWordWrapping = true;
				((TMP_Text)t).alignment = (TextAlignmentOptions)514;
				((TMP_Text)t).overflowMode = (TextOverflowModes)0;
				((TMP_Text)t).fontSizeMin = 12f;
				((TMP_Text)t).fontSizeMax = 20f;
				((TMP_Text)t).enableAutoSizing = true;
				((TMP_Text)t).fontSize = 20f;
				if (((TMP_Text)t).text != Formatted)
				{
					((TMP_Text)t).text = Formatted;
				}
				for (int i = 0; i < DecorationFields.Length; i++)
				{
					RectTransform val3 = (RectTransform)AccessTools.Field(View, DecorationFields[i]).GetValue(view);
					if (Object.op_Implicit((Object)(object)val3))
					{
						((Component)val3).gameObject.SetActive(false);
					}
				}
			}
		}

		[HarmonyPatch]
		private static class BannerPatch
		{
			private static MethodBase TargetMethod()
			{
				return AccessTools.Method(AccessTools.TypeByName("SeneaLUI.Hud.MessageView"), "SetBanner", new Type[1] { typeof(string) }, (Type[])null);
			}

			private static void Prefix(object __instance, string __0, out string __state)
			{
				__state = __0;
				object? value = TextField.GetValue(__instance);
				TextMeshProUGUI val = (TextMeshProUGUI)((value is TextMeshProUGUI) ? value : null);
				if (Object.op_Implicit((Object)(object)val))
				{
					Layout orCreateValue = Layouts.GetOrCreateValue(__instance);
					if (IsHelp(__0))
					{
						orCreateValue.Capture(__instance, val);
					}
					else
					{
						orCreateValue.Restore(__instance, val);
					}
				}
			}

			private static void Postfix(object __instance, string __state)
			{
				if (!IsHelp(__state))
				{
					return;
				}
				try
				{
					object? value = TextField.GetValue(__instance);
					TextMeshProUGUI val = (TextMeshProUGUI)((value is TextMeshProUGUI) ? value : null);
					if (Object.op_Implicit((Object)(object)val))
					{
						Layout orCreateValue = Layouts.GetOrCreateValue(__instance);
						int tags = 0;
						orCreateValue.Formatted = Size.Replace(__state, (Match m) => (++tags == 1) ? "<size=140%>" : "<size=100%>").Trim();
						orCreateValue.Formatted = Regex.Replace(orCreateValue.Formatted, "(?:<br>\\s*)+$", "", RegexOptions.IgnoreCase);
						orCreateValue.Active = true;
						orCreateValue.LastWidth = 0f;
						orCreateValue.Fit(__instance, val);
						((BaseUnityPlugin)Self).Logger.LogInfo((object)("HELP740|help-formatted|panel=" + ((__state.IndexOf("Enigma Command Index", StringComparison.OrdinalIgnoreCase) >= 0) ? "index" : "intro")));
					}
				}
				catch (Exception ex)
				{
					((BaseUnityPlugin)Self).Logger.LogError((object)("HELP740|format-failed|" + ex));
				}
			}
		}

		[HarmonyPatch]
		private static class TickPatch
		{
			private static MethodBase TargetMethod()
			{
				return AccessTools.Method(AccessTools.TypeByName("SeneaLUI.Hud.MessageView"), "TickBanner", new Type[2]
				{
					typeof(MessageHud),
					typeof(float)
				}, (Type[])null);
			}

			private static void Postfix(object __instance)
			{
				if (Layouts.TryGetValue(__instance, out var value) && value.Active)
				{
					object? value2 = TextField.GetValue(__instance);
					TextMeshProUGUI val = (TextMeshProUGUI)((value2 is TextMeshProUGUI) ? value2 : null);
					if (Object.op_Implicit((Object)(object)val))
					{
						value.Fit(__instance, val);
					}
				}
			}
		}

		private static readonly ConditionalWeakTable<object, Layout> Layouts = new ConditionalWeakTable<object, Layout>();

		private static readonly Regex Size = new Regex("<size\\s*=\\s*[^>]+>", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);

		private static HelpFit Self;

		private Harmony harmony;

		private static Type View;

		private static FieldInfo TextField;

		private static FieldInfo BannerField;

		private static FieldInfo ShiftField;

		private static readonly string[] DecorationFields = new string[4] { "_diamondL", "_diamondR", "_bannerL", "_bannerR" };

		private void Awake()
		{
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Expected O, but got Unknown
			Self = this;
			View = AccessTools.TypeByName("SeneaLUI.Hud.MessageView");
			if (View == null)
			{
				throw new MissingMemberException("SeneaL MessageView is unavailable");
			}
			TextField = Require("_bannerText", typeof(TextMeshProUGUI));
			BannerField = Require("_banner", typeof(RectTransform));
			ShiftField = Require("_shift", typeof(float));
			string[] decorationFields = DecorationFields;
			foreach (string n in decorationFields)
			{
				Require(n, typeof(RectTransform));
			}
			harmony = new Harmony("local.rbbr.enigmahelpfit");
			harmony.PatchAll(typeof(HelpFit).Assembly);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"HELP740|loaded|0.1.0|client help panels only|gameplay=UNVERIFIED");
		}

		private static FieldInfo Require(string n, Type type)
		{
			FieldInfo fieldInfo = AccessTools.Field(View, n);
			if (fieldInfo == null || fieldInfo.FieldType != type)
			{
				throw new MissingFieldException("Unsupported SeneaL field: " + n);
			}
			return fieldInfo;
		}

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

		internal static bool IsHelp(string text)
		{
			return text != null && (text.IndexOf("Begin in Enigma", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Enigma Command Index", StringComparison.OrdinalIgnoreCase) >= 0);
		}
	}
}