Decompiled source of EventGoldRewardsX10 v0.1.0

plugins/EventGoldRewardsX10/EventGoldRewardsX10.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using EventGoldRewardsX10.Core;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("EventGoldRewardsX10")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0")]
[assembly: AssemblyProduct("EventGoldRewardsX10")]
[assembly: AssemblyTitle("EventGoldRewardsX10")]
[assembly: AssemblyVersion("0.1.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace EventGoldRewardsX10
{
	internal static class GoldHooks
	{
		internal sealed class Payout
		{
			internal readonly EventAction Action;

			internal readonly List<Character> Recipients;

			internal bool GrantInProgress;

			internal Payout(EventAction action, List<Character> recipients)
			{
				Action = action;
				Recipients = recipients;
			}
		}

		internal static void EventSequence(PartyEvent partyEvent, EventAction eventAction, List<Character> effectedCharacters, bool __runOriginal, ref IEnumerator __result)
		{
			if (!__runOriginal || __result == null || (Object)(object)partyEvent == (Object)null || eventAction == null || effectedCharacters == null)
			{
				return;
			}
			try
			{
				if (Plugin.Active)
				{
					__result = new ScopedEnumerator<Payout>(__result, new Payout(eventAction, effectedCharacters));
				}
			}
			catch (Exception ex)
			{
				Plugin.Warn("event remains native: " + ex.Message);
			}
		}

		internal static void BeforeGiveGold(Character __instance, ref float goldValue, bool showMessage, bool addToStats, out Payout? __state)
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			__state = null;
			try
			{
				Payout active = ScopedEnumerator<Payout>.Active;
				if (active == null || active.GrantInProgress || !Plugin.Active || !showMessage || !addToStats || !(goldValue > 0f))
				{
					return;
				}
				GameLogic instance = GameLogic.instance;
				if ((Object)(object)instance == (Object)null)
				{
					return;
				}
				foreach (EventActionEffects eventActionEffect in active.Action.GetEventActionEffects())
				{
					if (IsReward(eventActionEffect) && EventWindow.MatchesEventActionTargetType(__instance, active.Recipients, eventActionEffect.EventActionEffectTargetType) && GoldPolicy.TryScaleMatched(goldValue, instance.ApplyGoldModifiers(eventActionEffect.modifyGoldAmount), out var output))
					{
						active.GrantInProgress = true;
						__state = active;
						goldValue = output;
						Plugin.Detail("event gold -> " + output.ToString("0"));
						return;
					}
				}
				Plugin.Detail("in-scope gold grant matched no reward effect of this event: " + goldValue.ToString("0.##"));
			}
			catch (Exception ex)
			{
				Plugin.Warn("award lookup failed: " + ex.Message);
			}
		}

		internal static Exception? AfterGiveGold(Exception? __exception, Payout? __state)
		{
			if (__state != null)
			{
				__state.GrantInProgress = false;
			}
			return __exception;
		}

		internal static void BeforePreview(ref string original, PartyEvent partyEvent)
		{
			try
			{
				if (Plugin.Active && !string.IsNullOrEmpty(original) && !((Object)(object)partyEvent == (Object)null) && !((Object)(object)GameLogic.instance == (Object)null) && (original.IndexOf("_gold]", StringComparison.Ordinal) >= 0 || original.IndexOf("_Gold]", StringComparison.Ordinal) >= 0))
				{
					original = GoldPolicy.RewritePreview(original, (int o, int a, int e) => Preview(partyEvent, o, a, e), (string word) => OptionsManager.Localize(word, (LanguageGender)0, (Gender)2));
				}
			}
			catch (Exception ex)
			{
				Plugin.Warn("preview remains native: " + ex.Message);
			}
		}

		private static bool IsReward(EventActionEffects? effect)
		{
			if (effect != null)
			{
				return GoldPolicy.IsPositiveReward(effect.modifyGoldAmount, effect.giveGold, effect.overrideGiveGold, effect.takeGold);
			}
			return false;
		}

		private static float? Preview(PartyEvent partyEvent, int optionIndex, int actionIndex, int effectIndex)
		{
			EventOption[] eventOptions = partyEvent.eventOptions;
			if (eventOptions == null || optionIndex > eventOptions.Length)
			{
				return null;
			}
			EventAction[] array = eventOptions[optionIndex - 1]?.eventActions;
			if (array == null || actionIndex > array.Length)
			{
				return null;
			}
			EventAction obj = array[actionIndex - 1];
			List<EventActionEffects> list = ((obj != null) ? obj.GetEventActionEffects() : null);
			if (list == null || effectIndex > list.Count)
			{
				return null;
			}
			EventActionEffects val = list[effectIndex - 1];
			if (!IsReward(val))
			{
				return null;
			}
			if (!GoldPolicy.TryScaleFinal(GameLogic.instance.ApplyGoldModifiers(val.modifyGoldAmount), out var output))
			{
				return null;
			}
			return output;
		}
	}
	[BepInPlugin("com.gumatos.eventgoldrewardsx10", "Event Gold Rewards x10", "0.1.0")]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string Id = "com.gumatos.eventgoldrewardsx10";

		public const string DisplayName = "Event Gold Rewards x10";

		public const string Version = "0.1.0";

		private static bool ready;

		private static ConfigEntry<bool>? enabledSetting;

		private static ConfigEntry<bool>? verbose;

		private static ManualLogSource? log;

		internal static bool Active
		{
			get
			{
				if (ready)
				{
					return enabledSetting?.Value ?? false;
				}
				return false;
			}
		}

		internal static void Detail(string text)
		{
			ConfigEntry<bool>? obj = verbose;
			if (obj != null && obj.Value)
			{
				ManualLogSource? obj2 = log;
				if (obj2 != null)
				{
					obj2.LogInfo((object)("EGR: " + text));
				}
			}
		}

		internal static void Warn(string text)
		{
			ManualLogSource? obj = log;
			if (obj != null)
			{
				obj.LogWarning((object)("EGR: " + text));
			}
		}

		private void Awake()
		{
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_019d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			log = ((BaseUnityPlugin)this).Logger;
			enabledSetting = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Multiply positive gold rewards from events by ten.");
			verbose = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Verbose", false, "Log changes to event gold payouts.");
			try
			{
				if (typeof(EventWindow).Module.ModuleVersionId != new Guid("f22b3897-820d-40a9-947c-d30f21940690"))
				{
					throw new NotSupportedException("unsupported Stolen Realm build");
				}
				MethodInfo methodInfo = Target(typeof(EventWindow), "ExecuteActivateEvent", typeof(IEnumerator), typeof(ObservableRoomData), typeof(PartyEvent), typeof(EventOption), typeof(EventAction), typeof(List<Character>), typeof(float));
				MethodInfo methodInfo2 = Target(typeof(Character), "GiveGold", typeof(void), typeof(float), typeof(bool), typeof(bool));
				MethodInfo methodInfo3 = Target(typeof(EventWindow), "TailorEventText", typeof(string), typeof(TextMeshProUGUI), typeof(string), typeof(PartyEvent), typeof(Character));
				Harmony val = new Harmony("com.gumatos.eventgoldrewardsx10");
				val.Patch((MethodBase)methodInfo, (HarmonyMethod)null, Hook("EventSequence"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				val.Patch((MethodBase)methodInfo2, Hook("BeforeGiveGold"), (HarmonyMethod)null, (HarmonyMethod)null, Hook("AfterGiveGold"), (HarmonyMethod)null);
				val.Patch((MethodBase)methodInfo3, Hook("BeforePreview"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				ready = Own(Harmony.GetPatchInfo((MethodBase)methodInfo)?.Postfixes) && Own(Harmony.GetPatchInfo((MethodBase)methodInfo2)?.Prefixes) && Own(Harmony.GetPatchInfo((MethodBase)methodInfo2)?.Finalizers) && Own(Harmony.GetPatchInfo((MethodBase)methodInfo3)?.Prefixes);
				if (!ready)
				{
					throw new InvalidOperationException("one or more native hooks did not attach");
				}
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Event Gold Rewards x10 0.1.0 carregado. EGR: 3/3 alvos.");
			}
			catch (Exception ex)
			{
				ready = false;
				Warn("inactive; native event gold is unchanged: " + ex.Message);
			}
		}

		private static MethodInfo Target(Type owner, string name, Type returns, params Type[] args)
		{
			MethodInfo methodInfo = AccessTools.DeclaredMethod(owner, name, args, (Type[])null);
			if (!(methodInfo == null) && !(methodInfo.ReturnType != returns))
			{
				MethodBody? methodBody = methodInfo.GetMethodBody();
				if (methodBody != null && methodBody.ExceptionHandlingClauses.Count == 0)
				{
					return methodInfo;
				}
			}
			throw new NotSupportedException("unexpected native method: " + name);
		}

		private static HarmonyMethod Hook(string name)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return new HarmonyMethod(typeof(GoldHooks), name, (Type[])null);
		}

		private static bool Own(IEnumerable<Patch>? patches)
		{
			return patches?.Any((Patch p) => p.owner == "com.gumatos.eventgoldrewardsx10") ?? false;
		}
	}
}
namespace EventGoldRewardsX10.Core
{
	internal static class GoldPolicy
	{
		private static readonly Regex GoldToken = new Regex("\\[o([1-9][0-9]*)a([1-9][0-9]*)(?:e([1-9][0-9]*))?_([Gg]old)\\]", RegexOptions.CultureInvariant);

		internal static bool IsPositiveReward(float original, bool giveGold, bool converted, bool takeGold = false)
		{
			if ((giveGold || converted) && original > 0f)
			{
				return !float.IsInfinity(original);
			}
			return false;
		}

		internal static bool TryScaleFinal(float original, out float output)
		{
			output = original;
			if (!(original > 0f) || float.IsInfinity(original))
			{
				return false;
			}
			double num = Math.Ceiling(original) * 10.0;
			if (num > 3.4028234663852886E+38)
			{
				return false;
			}
			output = (float)num;
			return true;
		}

		internal static bool TryScaleMatched(float paid, float expectedNative, out float output)
		{
			output = paid;
			if (!(paid > 0f) || float.IsInfinity(paid))
			{
				return false;
			}
			if (!(Math.Abs(paid - expectedNative) <= 0.0001f))
			{
				return false;
			}
			return TryScaleFinal(paid, out output);
		}

		internal static string RewritePreview(string text, Func<int, int, int, float?> resolve, Func<string, string> localize)
		{
			return GoldToken.Replace(text, delegate(Match m)
			{
				int index = 1;
				if (!Parse(m.Groups[1].Value, out var index2) || !Parse(m.Groups[2].Value, out var index3) || (m.Groups[3].Success && !Parse(m.Groups[3].Value, out index)))
				{
					return m.Value;
				}
				float? num = resolve(index2, index3, index);
				return (!num.HasValue) ? m.Value : (num.Value.ToString("0", CultureInfo.CurrentCulture) + " " + localize(m.Groups[4].Value));
			});
			static bool Parse(string s, out int index)
			{
				return int.TryParse(s, NumberStyles.None, CultureInfo.InvariantCulture, out index);
			}
		}
	}
	internal sealed class ScopedEnumerator<T> : IEnumerator, IDisposable where T : class
	{
		private readonly IEnumerator native;

		private readonly T scope;

		[ThreadStatic]
		private static T? active;

		internal static T? Active => active;

		public object Current => native.Current;

		internal ScopedEnumerator(IEnumerator native, T scope)
		{
			this.native = native;
			this.scope = scope;
		}

		public bool MoveNext()
		{
			T val = active;
			active = scope;
			try
			{
				return native.MoveNext();
			}
			finally
			{
				active = val;
			}
		}

		public void Reset()
		{
			native.Reset();
		}

		public void Dispose()
		{
			(native as IDisposable)?.Dispose();
		}
	}
}