using System;
using System.Collections;
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.Configuration;
using BepInEx.Logging;
using BetterRiskRewardLoot.Core;
using BetterRiskRewardLoot.Runtime;
using Burst2Flame;
using Burst2Flame.Observable;
using HarmonyLib;
using UnityEngine;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("BetterRiskRewardLoot")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.1.0")]
[assembly: AssemblyInformationalVersion("0.1.1")]
[assembly: AssemblyProduct("BetterRiskRewardLoot")]
[assembly: AssemblyTitle("BetterRiskRewardLoot")]
[assembly: AssemblyVersion("0.1.1.0")]
namespace BetterRiskRewardLoot
{
[BepInPlugin("com.gumatos.betterriskrewardloot", "Better Risk Reward Loot", "0.1.1")]
public sealed class Plugin : BaseUnityPlugin
{
public const string Guid = "com.gumatos.betterriskrewardloot";
public const string Version = "0.1.1";
private void Awake()
{
//IL_008a: Unknown result type (might be due to invalid IL or missing references)
//IL_0090: Expected O, but got Unknown
ConfigEntry<bool> enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Scale item rarity rolls for victories in solo Roguelike.");
ConfigEntry<bool> details = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Verbose", false, "Log eligible affix counts at victory and when generating the reward.");
ManualLogSource log = ((BaseUnityPlugin)this).Logger;
RuntimeStatus.Enabled = () => enabled.Value;
RuntimeStatus.Warn = delegate(string message)
{
log.LogWarning((object)message);
};
RuntimeStatus.Detail = delegate(string message)
{
if (details.Value)
{
log.LogInfo((object)message);
}
};
Harmony val = new Harmony("com.gumatos.betterriskrewardloot");
try
{
int num = NativePatches.Install(val);
RuntimeStatus.Ready = true;
((BaseUnityPlugin)this).Logger.LogInfo((object)string.Format("Better Risk Reward Loot {0} carregado. BRRL: {1}/9 alvos, 2/2 chamadas; Roguelike solo e co-op.", "0.1.1", num));
}
catch (Exception ex)
{
RuntimeStatus.Ready = false;
((BaseUnityPlugin)this).Logger.LogWarning((object)("BRRL: desativado; nenhum ajuste de recompensa: " + ex.GetType().Name + ": " + ex.Message));
try
{
val.UnpatchSelf();
}
catch (Exception ex2)
{
RuntimeStatus.Fault(ex2);
}
}
}
}
}
namespace BetterRiskRewardLoot.Runtime
{
internal static class RuntimeStatus
{
internal static Func<bool> Enabled = () => true;
internal static Action<string> Warn = delegate
{
};
internal static Action<string> Detail = delegate
{
};
internal static bool Ready { get; set; }
internal static bool Active
{
get
{
if (Ready)
{
return Enabled();
}
return false;
}
}
internal static void Fault(Exception ex)
{
try
{
Warn("BRRL: mantendo comportamento nativo: " + ex.GetType().Name + ": " + ex.Message);
}
catch
{
}
}
}
internal static class BattleHooks
{
internal sealed class Pending
{
internal readonly RewardFlow.Victory Ticket;
internal readonly List<CharacterLevelUpInfo> Queue;
internal readonly int OldCount;
internal Pending(RewardFlow.Victory ticket, List<CharacterLevelUpInfo> queue)
{
Ticket = ticket;
Queue = queue;
OldCount = queue.Count;
}
}
private sealed class Window
{
internal readonly RoguelikeManager Manager;
internal readonly CharacterLevelUpInfo Entry;
internal Window(RoguelikeManager manager, CharacterLevelUpInfo entry)
{
Manager = manager;
Entry = entry;
}
}
private sealed class RewardSequence : IEnumerator, IDisposable
{
private readonly IEnumerator original;
private readonly RewardFlow.Victory ticket;
private bool completed;
public object Current => original.Current;
internal RewardSequence(IEnumerator original, RewardFlow.Victory ticket)
{
this.original = original;
this.ticket = ticket;
}
public bool MoveNext()
{
using (LocalScope<RewardFlow.Victory>.Push(ticket))
{
try
{
bool num = original.MoveNext();
if (!num)
{
completed = true;
}
return num;
}
catch
{
Flow.Cancel(ticket);
throw;
}
}
}
public void Reset()
{
original.Reset();
}
public void Dispose()
{
if (!completed)
{
Flow.Cancel(ticket);
}
(original as IDisposable)?.Dispose();
}
}
private static readonly RewardFlow Flow = new RewardFlow();
private static bool TryIdentity(out Root root, out BattleIdentity identity)
{
NetworkingManager instance = NetworkingManager.Instance;
root = ((instance == null) ? null : ((Observer<Root>)(object)instance.NetworkManager)?.Root);
identity = default(BattleIdentity);
if (!RuntimeStatus.Active || (Object)(object)instance == (Object)null || root == null || !root.PlayingRoguelike || root.ObservableQuestData == null)
{
return false;
}
identity = new BattleIdentity(root, root.ObservableQuestData, instance.SessionGeneration);
return true;
}
internal static void Started(GameLogic __instance, bool __runOriginal)
{
if (!__runOriginal)
{
return;
}
try
{
if (TryIdentity(out var root, out var identity) && root.BattleCurrentlyActive && __instance == GameLogic.instance)
{
Flow.Begin(identity, __instance.CurrentBattle);
}
else
{
Flow.Clear();
}
}
catch (Exception ex)
{
Flow.Clear();
RuntimeStatus.Fault(ex);
}
}
internal static void Result(bool victory, List<Character> roguelikeCharactersToLevel, bool __runOriginal, ref IEnumerator __result)
{
if (!__runOriginal || __result == null)
{
return;
}
try
{
if (!TryIdentity(out var root, out var identity) || root.BattleCurrentlyActive || root.FledBattle || root.LastBattleWasVictory != victory)
{
return;
}
GameLogic instance = GameLogic.instance;
if ((Object)(object)instance == (Object)null)
{
return;
}
object obj = ((object)instance.CurrentBattle) ?? ((object)instance);
if (!Flow.IsAwaiting(identity, obj))
{
NetworkingManager instance2 = NetworkingManager.Instance;
if ((Object)(object)instance2 == (Object)null || instance2.IsServer)
{
return;
}
Flow.Begin(identity, obj);
if (!Flow.IsAwaiting(identity, obj))
{
return;
}
}
long affixes = ((victory && roguelikeCharactersToLevel != null && roguelikeCharactersToLevel.Count != 0) ? CountAffixes(instance) : 0);
RewardFlow.Victory victory2 = Flow.Finish(identity, obj, victory, affixes, roguelikeCharactersToLevel);
if (victory2 != null)
{
RuntimeStatus.Detail("BRRL: victoria com afixos=" + victory2.Affixes);
__result = new RewardSequence(__result, victory2);
}
}
catch (Exception ex)
{
Flow.Clear();
RuntimeStatus.Fault(ex);
}
}
private static long CountAffixes(GameLogic game)
{
//IL_0030: Unknown result type (might be due to invalid IL or missing references)
AffixCounter affixCounter = new AffixCounter();
foreach (Character item in game.RewardedKills())
{
if (item != null && item.TeamIndex == 1 && !item.IsSummon && (int)item.CharacterType == 0)
{
affixCounter.Add(item, AffixIds(item.EnemyMods));
}
}
return affixCounter.Total;
}
private static IEnumerable<Guid> AffixIds(List<EnemyMod> mods)
{
if (mods == null)
{
yield break;
}
foreach (EnemyMod mod in mods)
{
if ((Object)(object)mod != (Object)null)
{
yield return mod.Guid;
}
}
}
internal static void BeforeEnqueue(RoguelikeManager __instance, Character character, bool isReroll, int forcedTier, bool immediateShow, out Pending __state)
{
__state = null;
RewardFlow.Victory current = LocalScope<RewardFlow.Victory>.Current;
if (current == null || isReroll || forcedTier != -1 || immediateShow)
{
return;
}
try
{
if (character != null && character.Owned && character.IsRoguelikeCharacter && TryIdentity(out var root, out var identity) && !root.BattleCurrentlyActive && root.LastBattleWasVictory && Flow.CanBind(identity, current, character))
{
List<CharacterLevelUpInfo> charactersWaitingForLevelUp = __instance.CharactersWaitingForLevelUp;
if (charactersWaitingForLevelUp != null)
{
__state = new Pending(current, charactersWaitingForLevelUp);
}
}
}
catch (Exception ex)
{
RuntimeStatus.Fault(ex);
}
}
internal static void AfterEnqueue(RoguelikeManager __instance, Character character, bool __runOriginal, Pending __state)
{
if (!__runOriginal || __state == null)
{
return;
}
try
{
if (!TryIdentity(out var root, out var identity) || root.BattleCurrentlyActive || !root.LastBattleWasVictory)
{
return;
}
List<CharacterLevelUpInfo> charactersWaitingForLevelUp = __instance.CharactersWaitingForLevelUp;
if (charactersWaitingForLevelUp == __state.Queue && charactersWaitingForLevelUp.Count > __state.OldCount)
{
CharacterLevelUpInfo val = charactersWaitingForLevelUp[charactersWaitingForLevelUp.Count - 1];
if (val != null && !val.IsReroll && val.Character == character)
{
Flow.Bind(identity, __state.Ticket, character, val);
}
}
}
catch (Exception ex)
{
RuntimeStatus.Fault(ex);
}
}
internal static void BeforeWindow(RoguelikeManager __instance, CharacterLevelUpInfo characterLevelUpInfo, out IDisposable __state)
{
Window next = null;
if (characterLevelUpInfo != null && !characterLevelUpInfo.IsReroll)
{
next = new Window(__instance, characterLevelUpInfo);
}
__state = LocalScope<Window>.Push(next);
}
internal static Exception AfterWindow(Exception __exception, IDisposable __state)
{
__state?.Dispose();
return __exception;
}
internal static long AffixesFor(RoguelikeManager manager, Character recipient)
{
Window current = LocalScope<Window>.Current;
if (current == null || current.Manager != manager || current.Entry.Character != recipient)
{
return 0L;
}
try
{
if (recipient == null || !recipient.Owned || !TryIdentity(out var root, out var identity) || root.BattleCurrentlyActive || !root.LastBattleWasVictory || root.FledBattle)
{
return 0L;
}
return Flow.CountFor(identity, recipient, current.Entry);
}
catch (Exception ex)
{
RuntimeStatus.Fault(ex);
return 0L;
}
}
}
internal static class RarityHooks
{
private sealed class RollContext
{
internal readonly long Affixes;
internal readonly bool Boss;
internal RollContext(long affixes, bool boss)
{
Affixes = affixes;
Boss = boss;
}
}
private sealed class PersonalRoll
{
internal static readonly PersonalRoll Marker = new PersonalRoll();
}
internal static List<Item> ItemChoices(RoguelikeManager manager, int level, Character recipient, CharacterInfo boss)
{
long num = BattleHooks.AffixesFor(manager, recipient);
if (num == 0L && LocalScope<RollContext>.Current == null)
{
return manager.GetItemChoices(level, recipient, boss);
}
using (LocalScope<RollContext>.Push((num == 0L) ? null : new RollContext(num, (Object)(object)boss != (Object)null)))
{
return manager.GetItemChoices(level, recipient, boss);
}
}
internal static void WorldRoll(ref float percentage, string message)
{
RollContext current = LocalScope<RollContext>.Current;
if (current != null && LocalScope<PersonalRoll>.Current == null && AffixCurve.TryWorldRank(message, out var rarity))
{
percentage = AffixCurve.Roll(rarity, percentage, current.Affixes);
}
}
internal static void PersonalChance(ItemLootChance __instance, ref float __result)
{
//IL_0025: Unknown result type (might be due to invalid IL or missing references)
//IL_0037: Expected I4, but got Unknown
RollContext current = LocalScope<RollContext>.Current;
if (current == null || !current.Boss)
{
return;
}
try
{
ItemInfo itemInfo = __instance.ItemInfo;
if ((Object)(object)itemInfo != (Object)null)
{
__result = AffixCurve.Weight((LootRank)itemInfo.Rarity, __result, current.Affixes);
}
}
catch (Exception ex)
{
RuntimeStatus.Fault(ex);
}
}
internal static void BeforePersonalRoll(out IDisposable __state)
{
__state = ((LocalScope<RollContext>.Current == null) ? null : LocalScope<PersonalRoll>.Push(PersonalRoll.Marker));
}
internal static Exception AfterPersonalRoll(Exception __exception, IDisposable __state)
{
__state?.Dispose();
return __exception;
}
internal static ChanceByQuality WeightedChance(List<ChanceByQuality> items, Func<ChanceByQuality, float> getWeight, Random rand)
{
RollContext context = LocalScope<RollContext>.Current;
if (context == null)
{
return Game.RandomBasedOnWeight<ChanceByQuality>(items, getWeight, rand);
}
return Game.RandomBasedOnWeight<ChanceByQuality>(items, (Func<ChanceByQuality, float>)((ChanceByQuality item) => AffixCurve.Weight((LootRank)item.rarity, getWeight(item), context.Affixes)), rand);
}
}
internal static class NativePatches
{
private sealed class Entry
{
internal readonly MethodInfo Original;
internal readonly MethodInfo Prefix;
internal readonly MethodInfo Postfix;
internal readonly MethodInfo Transpiler;
internal readonly MethodInfo Finalizer;
internal Entry(MethodInfo method, MethodInfo prefix = null, MethodInfo postfix = null, MethodInfo transpiler = null, MethodInfo finalizer = null)
{
Original = method;
Prefix = prefix;
Postfix = postfix;
Transpiler = transpiler;
Finalizer = finalizer;
}
}
private static readonly Guid SupportedMvid = new Guid("f22b3897-820d-40a9-947c-d30f21940690");
private static readonly FieldInfo InstructionLabels = typeof(CodeInstruction).GetField("labels");
private static readonly Type[] ChoiceArgs = new Type[3]
{
typeof(int),
typeof(Character),
typeof(CharacterInfo)
};
private static readonly MethodInfo NativeChoices = Target(typeof(RoguelikeManager), "GetItemChoices", ChoiceArgs);
private static readonly MethodInfo NativeWeighted = (from method in typeof(Game).GetMethods(BindingFlags.Static | BindingFlags.Public)
where method.Name == "RandomBasedOnWeight" && method.IsGenericMethodDefinition && method.GetGenericArguments().Length == 1
select method.MakeGenericMethod(typeof(ChanceByQuality))).Single((MethodInfo method) => (from p in method.GetParameters()
select p.ParameterType).SequenceEqual(new Type[3]
{
typeof(List<ChanceByQuality>),
typeof(Func<ChanceByQuality, float>),
typeof(Random)
}));
private static int populatedRewrites;
private static int fallbackRewrites;
private static MethodInfo Target(Type type, string name, params Type[] arguments)
{
return AccessTools.DeclaredMethod(type, name, arguments, (Type[])null) ?? throw new MissingMethodException(type.FullName, name);
}
private static MethodInfo Hook(Type type, string name)
{
return type.GetMethod(name, BindingFlags.Static | BindingFlags.NonPublic) ?? throw new MissingMethodException(type.FullName, name);
}
private static HarmonyMethod Wrap(MethodInfo method)
{
//IL_000a: Unknown result type (might be due to invalid IL or missing references)
//IL_0010: Expected O, but got Unknown
if (!(method == null))
{
return new HarmonyMethod(method);
}
return null;
}
internal static int Install(Harmony harmony)
{
if (typeof(GameLogic).Module.ModuleVersionId != SupportedMvid)
{
throw new NotSupportedException("Assembly-CSharp fora da build homologada");
}
Type typeFromHandle = typeof(BattleHooks);
Type typeFromHandle2 = typeof(RarityHooks);
Type typeFromHandle3 = typeof(NativePatches);
Entry[] array = new Entry[9]
{
new Entry(Target(typeof(GameLogic), "InitBattleAndStart"), null, Hook(typeFromHandle, "Started")),
new Entry(Target(typeof(PostBattleManager), "ExecutePostBattleMenuSequence", typeof(bool), typeof(float), typeof(float), typeof(List<Item>), typeof(List<Character>), typeof(bool), typeof(float)), null, Hook(typeFromHandle, "Result")),
new Entry(Target(typeof(RoguelikeManager), "AddToSkillSelectionQueue", typeof(Character), typeof(bool), typeof(int), typeof(int), typeof(bool)), Hook(typeFromHandle, "BeforeEnqueue"), Hook(typeFromHandle, "AfterEnqueue")),
new Entry(Target(typeof(RoguelikeManager), "OpenSkillSelectWindow", typeof(CharacterLevelUpInfo), typeof(bool)), Hook(typeFromHandle, "BeforeWindow"), null, null, Hook(typeFromHandle, "AfterWindow")),
new Entry(Target(typeof(RoguelikeManager), "PopulateItemChoices", ChoiceArgs), null, null, Hook(typeFromHandle3, "PopulateCall")),
new Entry(Target(typeof(LootTable), "GetGuaranteedWorldLoot", typeof(int), typeof(LootRestrictions), typeof(Random), typeof(List<ItemInfo>)), null, null, Hook(typeFromHandle3, "FallbackCall")),
new Entry(Target(typeof(PercentageRoller), "GetRollResult", typeof(float), typeof(string)), Hook(typeFromHandle2, "WorldRoll")),
new Entry(Target(typeof(PercentageRoller), "GetRollResult", typeof(Random), typeof(float), typeof(string)), Hook(typeFromHandle2, "BeforePersonalRoll"), null, null, Hook(typeFromHandle2, "AfterPersonalRoll")),
new Entry(Target(typeof(ItemLootChance), "ChanceAt", typeof(int)), null, Hook(typeFromHandle2, "PersonalChance"))
};
Entry[] array2 = array;
foreach (Entry entry in array2)
{
MethodBody? methodBody = entry.Original.GetMethodBody();
if (methodBody == null || methodBody.ExceptionHandlingClauses.Count != 0 || entry.Original.GetCustomAttributesData().Any((CustomAttributeData attr) => attr.AttributeType.Name == "NetworkMethodAttribute"))
{
throw new NotSupportedException("alvo nativo inseguro: " + entry.Original);
}
}
populatedRewrites = (fallbackRewrites = 0);
array2 = array;
foreach (Entry entry2 in array2)
{
harmony.Patch((MethodBase)entry2.Original, Wrap(entry2.Prefix), Wrap(entry2.Postfix), Wrap(entry2.Transpiler), Wrap(entry2.Finalizer), (HarmonyMethod)null);
Patches patchInfo = Harmony.GetPatchInfo((MethodBase)entry2.Original);
if (patchInfo == null || !Attached(patchInfo.Prefixes, harmony.Id, entry2.Prefix) || !Attached(patchInfo.Postfixes, harmony.Id, entry2.Postfix) || !Attached(patchInfo.Transpilers, harmony.Id, entry2.Transpiler) || !Attached(patchInfo.Finalizers, harmony.Id, entry2.Finalizer))
{
throw new InvalidOperationException("gancho ausente: " + entry2.Original);
}
}
if (populatedRewrites != 1 || fallbackRewrites != 1)
{
throw new InvalidOperationException("chamadas de recompensa nao confirmadas");
}
return array.Length;
}
private static bool Attached(IEnumerable<Patch> patches, string owner, MethodInfo expected)
{
if (!(expected == null))
{
return patches.Any((Patch p) => p.owner == owner && p.PatchMethod.Equals(expected));
}
return true;
}
internal static IEnumerable<CodeInstruction> PopulateCall(IEnumerable<CodeInstruction> instructions)
{
return Replace(instructions, NativeChoices, Hook(typeof(RarityHooks), "ItemChoices"), out populatedRewrites);
}
internal static IEnumerable<CodeInstruction> FallbackCall(IEnumerable<CodeInstruction> instructions)
{
return Replace(instructions, NativeWeighted, Hook(typeof(RarityHooks), "WeightedChance"), out fallbackRewrites);
}
private static List<CodeInstruction> Replace(IEnumerable<CodeInstruction> instructions, MethodInfo from, MethodInfo to, out int count)
{
count = 0;
List<CodeInstruction> list = instructions.ToList();
CodeInstruction[] array = list.Where((CodeInstruction i) => (i.opcode == OpCodes.Call || i.opcode == OpCodes.Callvirt) && object.Equals(i.operand, from)).ToArray();
IEnumerable<Type> enumerable = from p in @from.GetParameters()
select p.ParameterType;
if (!from.IsStatic)
{
enumerable = new Type[1] { from.DeclaringType }.Concat(enumerable);
}
if (array.Length != 1 || array[0].opcode != OpCodes.Call || !(InstructionLabels?.GetValue(array[0]) is IList { Count: 0 }) || array[0].blocks.Count != 0 || !to.IsStatic || !enumerable.SequenceEqual(from p in to.GetParameters()
select p.ParameterType) || from.ReturnType != to.ReturnType)
{
throw new NotSupportedException("forma da chamada mudou: " + from);
}
array[0].operand = to;
count = 1;
return list;
}
}
}
namespace BetterRiskRewardLoot.Core
{
internal enum LootRank
{
Common,
Uncommon,
Rare,
Legendary,
Mythic
}
internal static class AffixCurve
{
private static double Factor(LootRank rarity, long affixes)
{
long num = Math.Max(0L, affixes);
switch (rarity)
{
case LootRank.Common:
case LootRank.Uncommon:
return Math.Max(0.5, 1.0 - 0.05 * (double)num);
case LootRank.Rare:
return 1.0 + 0.2 * (double)num;
case LootRank.Legendary:
return 1.0 + 0.4 * (double)num;
case LootRank.Mythic:
return 1.0 + 0.6 * (double)num;
default:
return 1.0;
}
}
internal static float Weight(LootRank rarity, float native, long affixes)
{
return Scale(rarity, native, affixes, float.MaxValue);
}
internal static float Roll(LootRank rarity, float native, long affixes)
{
return Scale(rarity, native, affixes, 100f);
}
private static float Scale(LootRank rarity, float native, long affixes, float ceiling)
{
if (!(native > 0f) || float.IsInfinity(native))
{
return native;
}
double num = Factor(rarity, affixes);
if (num != 1.0)
{
return (float)Math.Min(ceiling, (double)native * num);
}
return native;
}
internal static bool TryWorldRank(string message, out LootRank rarity)
{
switch (message)
{
case "Global Common":
rarity = LootRank.Common;
return true;
case "Global Uncommon":
rarity = LootRank.Uncommon;
return true;
case "Global Rare":
rarity = LootRank.Rare;
return true;
case "Global Legendary":
rarity = LootRank.Legendary;
return true;
case "Global Mythic":
rarity = LootRank.Mythic;
return true;
default:
rarity = LootRank.Common;
return false;
}
}
}
internal readonly struct BattleIdentity
{
private readonly object root;
private readonly object quest;
private readonly int generation;
internal bool Valid
{
get
{
if (root != null)
{
return quest != null;
}
return false;
}
}
internal BattleIdentity(object root, object quest, int generation)
{
this.root = root;
this.quest = quest;
this.generation = generation;
}
internal bool Matches(BattleIdentity other)
{
if (Valid && generation == other.generation && root == other.root)
{
return quest == other.quest;
}
return false;
}
}
internal sealed class RefComparer : IEqualityComparer<object>
{
internal static readonly RefComparer Instance = new RefComparer();
public new bool Equals(object a, object b)
{
return a == b;
}
public int GetHashCode(object subject)
{
return RuntimeHelpers.GetHashCode(subject);
}
}
internal sealed class AffixCounter
{
private readonly HashSet<object> enemies = new HashSet<object>(RefComparer.Instance);
internal long Total { get; private set; }
internal void Add(object actor, IEnumerable<Guid> affixes)
{
if (actor == null || affixes == null || !enemies.Add(actor))
{
return;
}
HashSet<Guid> hashSet = new HashSet<Guid>();
foreach (Guid affix in affixes)
{
if (affix != Guid.Empty && hashSet.Add(affix))
{
long total = Total + 1;
Total = total;
}
}
}
}
internal sealed class RewardFlow
{
internal sealed class Victory
{
internal readonly long Affixes;
internal readonly HashSet<object> Eligible = new HashSet<object>(RefComparer.Instance);
internal Victory(long affixes, IEnumerable<object> recipients)
{
Affixes = affixes;
foreach (object recipient in recipients)
{
if (recipient != null)
{
Eligible.Add(recipient);
}
}
}
}
private BattleIdentity identity;
private object battle;
private bool awaitingResult;
private Victory granted;
private readonly Dictionary<object, object> entries = new Dictionary<object, object>(RefComparer.Instance);
internal void Begin(BattleIdentity context, object battle)
{
if (!IsAwaiting(context, battle))
{
Clear();
if (context.Valid && battle != null)
{
identity = context;
this.battle = battle;
awaitingResult = true;
}
}
}
internal bool IsAwaiting(BattleIdentity context, object observedBattle)
{
if (awaitingResult && identity.Matches(context))
{
return battle == observedBattle;
}
return false;
}
internal Victory Finish(BattleIdentity context, object battle, bool won, long affixes, IEnumerable<object> recipients)
{
if (!IsAwaiting(context, battle))
{
return null;
}
awaitingResult = false;
this.battle = null;
if (!won || affixes <= 0 || recipients == null)
{
return null;
}
Victory victory = new Victory(affixes, recipients);
if (victory.Eligible.Count == 0)
{
return null;
}
return granted = victory;
}
internal bool CanBind(BattleIdentity context, Victory victory, object character)
{
if (victory != null && granted == victory && identity.Matches(context) && character != null)
{
return victory.Eligible.Contains(character);
}
return false;
}
internal bool Bind(BattleIdentity context, Victory victory, object character, object entry)
{
if (entry == null || !CanBind(context, victory, character) || entries.ContainsKey(entry))
{
return false;
}
entries.Add(entry, character);
victory.Eligible.Remove(character);
return true;
}
internal long CountFor(BattleIdentity context, object character, object entry)
{
if (granted == null || !identity.Matches(context) || entry == null || !entries.TryGetValue(entry, out var value) || value != character)
{
return 0L;
}
return granted.Affixes;
}
internal void Cancel(Victory victory)
{
if (victory != null && granted == victory)
{
Clear();
}
}
internal void Clear()
{
identity = default(BattleIdentity);
awaitingResult = false;
battle = null;
granted = null;
entries.Clear();
}
}
internal static class LocalScope<T> where T : class
{
private sealed class Lease : IDisposable
{
private readonly T previous;
private bool disposed;
internal Lease(T previous)
{
this.previous = previous;
}
public void Dispose()
{
if (!disposed)
{
LocalScope<T>.current = previous;
disposed = true;
}
}
}
[ThreadStatic]
private static T current;
internal static T Current => current;
internal static IDisposable Push(T next)
{
Lease result = new Lease(current);
current = next;
return result;
}
}
}