Decompiled source of PeglinOrbOrder v1.0.0

PeglinOrbOrder.dll

Decompiled 2 hours ago
using System;
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 Battle;
using Battle.Attacks;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using PeglinOrbOrder.Core;
using PeglinUI.OrbDisplay;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("PeglinOrbOrder")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("PeglinOrbOrder")]
[assembly: AssemblyTitle("PeglinOrbOrder")]
[assembly: AssemblyVersion("1.0.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 PeglinOrbOrder
{
	[HarmonyPatch(typeof(DeckManager), "ShuffleCompleteDeck")]
	internal static class DeckShufflePatch
	{
		private static bool _missingRandomLogged;

		[HarmonyPostfix]
		private static void Postfix(DeckManager __instance)
		{
			if (!Plugin.Active || !BattleController.BattleActive)
			{
				return;
			}
			try
			{
				Func<double> func = GameRandom(__instance);
				if (func == null)
				{
					if (!_missingRandomLogged)
					{
						_missingRandomLogged = true;
						Plugin.Log.LogWarning((object)"No saved deck random state for this battle; leaving the game's own draw order.");
					}
				}
				else
				{
					Reorder(__instance, func);
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Weighted shuffle failed, keeping the game's own order: {arg}");
			}
		}

		internal static Func<double> GameRandom(DeckManager deckManager)
		{
			SerializableRandomState state = (((Object)(object)deckManager == (Object)null) ? null : deckManager.deckOrderRandomState);
			if (state == null)
			{
				return null;
			}
			return () => state.GetRandomValue();
		}

		internal static void Reorder(DeckManager deckManager, Func<double> nextUnit)
		{
			Stack<GameObject> stack = (((Object)(object)deckManager == (Object)null) ? null : deckManager.shuffledDeck);
			if (stack != null && stack.Count >= 2)
			{
				GameObject[] array = stack.ToArray();
				WeightedOrder.ShuffleInPlace(array, OrbKeys.Of, Plugin.Weights, Plugin.Exponent, nextUnit);
				stack.Clear();
				for (int num = array.Length - 1; num >= 0; num--)
				{
					stack.Push(array[num]);
				}
				if (Plugin.LogOrder.Value)
				{
					Plugin.Log.LogInfo((object)("Weighted draw order: " + Describe(array)));
				}
			}
		}

		internal static string Describe(GameObject[] order)
		{
			string text = string.Join(", ", from orb in order.Take(15)
				select $"{OrbKeys.DisplayName(orb)}={Plugin.Weights.For(OrbKeys.Of(orb))}");
			if (order.Length <= 15)
			{
				return text;
			}
			return $"{text} (+{order.Length - 15} more)";
		}
	}
	internal static class OrbKeys
	{
		public static string Of(GameObject orb)
		{
			if ((Object)(object)orb == (Object)null)
			{
				return null;
			}
			Attack component = orb.GetComponent<Attack>();
			if (!((Object)(object)component == (Object)null))
			{
				return component.locNameString;
			}
			return null;
		}

		public static string DisplayName(GameObject orb)
		{
			if ((Object)(object)orb == (Object)null)
			{
				return "null";
			}
			Attack component = orb.GetComponent<Attack>();
			if ((Object)(object)component == (Object)null)
			{
				return ((Object)orb).name;
			}
			string name = component.Name;
			if (!string.IsNullOrEmpty(name))
			{
				return name;
			}
			return component.locNameString;
		}
	}
	[HarmonyPatch(typeof(UpcomingOrbDisplay), "Initialize")]
	internal static class UpcomingOrbDisplayPatch
	{
		private static readonly FieldInfo TextCanvasField = AccessTools.Field(typeof(UpcomingOrbDisplay), "_textCanvas");

		private const float LabelOffsetX = 0f;

		private const float LabelOffsetY = -0.45f;

		private const float LabelScale = 0.8f;

		private static bool _missingTemplateLogged;

		private static bool _canvasWarningLogged;

		private static int _failuresLogged;

		[HarmonyPostfix]
		private static void Postfix(UpcomingOrbDisplay __instance, GameObject orbPrefab)
		{
			try
			{
				if (Plugin.ShowWeights.Value && !((Object)(object)orbPrefab == (Object)null))
				{
					AddLabel(__instance, orbPrefab);
				}
			}
			catch (Exception ex)
			{
				if (_failuresLogged < 3)
				{
					_failuresLogged++;
					Plugin.Log.LogWarning((object)("Couldn't add a weight number: " + ex.Message));
				}
			}
		}

		private static void AddLabel(UpcomingOrbDisplay display, GameObject orbPrefab)
		{
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			object? obj = TextCanvasField?.GetValue(display);
			CanvasGroup val = (CanvasGroup)((obj is CanvasGroup) ? obj : null);
			TMP_Text val2 = (((Object)(object)val == (Object)null) ? null : ((Component)val).GetComponentInChildren<TMP_Text>(true));
			if ((Object)(object)val2 == (Object)null)
			{
				if (!_missingTemplateLogged)
				{
					_missingTemplateLogged = true;
					Plugin.Log.LogWarning((object)"The upcoming-orb display has no text label to copy, so weight numbers are off.");
				}
				return;
			}
			OrbWeightLabelHolder orbWeightLabelHolder = ((Component)display).GetComponent<OrbWeightLabelHolder>();
			if ((Object)(object)orbWeightLabelHolder == (Object)null)
			{
				orbWeightLabelHolder = ((Component)display).gameObject.AddComponent<OrbWeightLabelHolder>();
			}
			if ((Object)(object)orbWeightLabelHolder.Label != (Object)null)
			{
				orbWeightLabelHolder.Label.SetActive(false);
				Object.Destroy((Object)(object)orbWeightLabelHolder.Label);
				orbWeightLabelHolder.Label = null;
			}
			int weight = Plugin.Weights.For(OrbKeys.Of(orbPrefab));
			GameObject val3 = Object.Instantiate<GameObject>(((Component)val2).gameObject, ((Component)display).transform);
			((Object)val3).name = "OrbOrderWeight";
			val3.SetActive(true);
			CanvasGroup component = val3.GetComponent<CanvasGroup>();
			if ((Object)(object)component != (Object)null)
			{
				component.alpha = 1f;
			}
			TMP_Text component2 = val3.GetComponent<TMP_Text>();
			if ((Object)(object)component2 == (Object)null)
			{
				Object.Destroy((Object)(object)val3);
				return;
			}
			component2.text = weight.ToString(CultureInfo.InvariantCulture);
			((Graphic)component2).color = ColorFor(weight);
			((Graphic)component2).raycastTarget = false;
			Transform transform = val3.transform;
			transform.localPosition = new Vector3(0f, -0.45f, -0.05f);
			transform.localRotation = Quaternion.identity;
			transform.localScale = Vector3.one * 0.8f;
			orbWeightLabelHolder.Label = val3;
			if (!_canvasWarningLogged && val2 is TextMeshProUGUI && (Object)(object)val3.GetComponentInParent<Canvas>() == (Object)null)
			{
				_canvasWarningLogged = true;
				Plugin.Log.LogWarning((object)"Weight numbers have no Canvas ancestor, so they may not be visible. Set ShowWeights=false to turn them off and report this.");
			}
		}

		internal static Color ColorFor(int weight)
		{
			//IL_0014: 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)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			if (weight > 50)
			{
				return new Color(0.45f, 1f, 0.45f);
			}
			if (weight == 50)
			{
				return Color.white;
			}
			if (weight > 0)
			{
				return new Color(1f, 0.72f, 0.25f);
			}
			return new Color(0.7f, 0.7f, 0.7f);
		}
	}
	[HarmonyPatch(typeof(UpcomingOrbDisplay), "SetActive")]
	internal static class ActiveOrbLabelPatch
	{
		[HarmonyPostfix]
		private static void Postfix(UpcomingOrbDisplay __instance)
		{
			OrbWeightLabelHolder component = ((Component)__instance).GetComponent<OrbWeightLabelHolder>();
			if ((Object)(object)component != (Object)null && (Object)(object)component.Label != (Object)null)
			{
				component.Label.SetActive(false);
			}
		}
	}
	internal sealed class OrbWeightLabelHolder : MonoBehaviour
	{
		public GameObject Label;
	}
	[BepInPlugin("PeglinOrbOrder", "PeglinOrbOrder", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string Guid = "PeglinOrbOrder";

		public const string Name = "PeglinOrbOrder";

		public const string Version = "1.0.0";

		public const string SupportedGameVersion = "2.0.12";

		internal const string WeightsFileName = "PeglinOrbOrder.weights.json";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<bool> ShowWeights;

		internal static ConfigEntry<bool> LogOrder;

		private static OrbWeightsDocument _document;

		private static OrbWeightTable _weights;

		internal static OrbWeightTable Weights => _weights ?? (_weights = OrbWeightTable.Defaults());

		internal static double Exponent => _document?.Exponent ?? 1.0;

		internal static bool Active
		{
			get
			{
				if (Enabled != null)
				{
					return Enabled.Value;
				}
				return true;
			}
		}

		internal static string WeightsPath => Path.Combine(Paths.ConfigPath, "PeglinOrbOrder.weights.json");

		private void Awake()
		{
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			CheckGameVersion();
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Reorder the sack so heavier orbs (see the weights JSON) are more likely to be drawn earlier. Turn this off to play with the game's normal shuffle.");
			ShowWeights = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ShowWeights", true, "Show each queued orb's draw weight as a number on it, colour-coded: green above baseline, white at 50, amber below, grey at 0 (never first).");
			LogOrder = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "LogOrder", false, "Write the weighted draw order to the log every time the sack is shuffled.");
			ReloadWeights();
			Harmony val = new Harmony("PeglinOrbOrder");
			val.PatchAll(typeof(Plugin).Assembly);
			int num = val.GetPatchedMethods().Count();
			if (num < 3)
			{
				Log.LogError((object)string.Format("{0} only patched {1} of 3 game methods. Peglin may have changed; the mod will do nothing.", "PeglinOrbOrder", num));
			}
			else
			{
				Log.LogInfo((object)string.Format("{0} {1} loaded; patched {2} game method(s).", "PeglinOrbOrder", "1.0.0", num));
			}
		}

		private static void ReloadWeights()
		{
			string weightsPath = WeightsPath;
			try
			{
				if (!File.Exists(weightsPath))
				{
					OrbWeightsDocument orbWeightsDocument = OrbWeightsJson.CreateDefault();
					WriteAtomically(weightsPath, OrbWeightsJson.Serialize(orbWeightsDocument));
					_document = orbWeightsDocument;
					_weights = orbWeightsDocument.Table;
					Log.LogInfo((object)$"Wrote default orb weights to {weightsPath} ({orbWeightsDocument.Orbs.Count} orbs).");
				}
				else
				{
					OrbWeightsDocument orbWeightsDocument2 = OrbWeightsJson.Parse(File.ReadAllText(weightsPath));
					ReportUnknownKeys(orbWeightsDocument2);
					int num = orbWeightsDocument2.MissingDefaultCount();
					orbWeightsDocument2.WithMissingDefaults();
					_document = orbWeightsDocument2;
					_weights = orbWeightsDocument2.Table;
					Log.LogInfo((object)($"Loaded orb weights from {weightsPath} ({orbWeightsDocument2.Orbs.Count} orbs, exponent " + orbWeightsDocument2.Exponent.ToString("0.##", CultureInfo.InvariantCulture) + ((num > 0) ? $", {num} orb(s) filled from defaults" : "") + ")."));
				}
			}
			catch (Exception ex)
			{
				Log.LogError((object)("Couldn't read " + weightsPath + ": " + ex.Message + " Using the built-in default weights."));
				_document = OrbWeightsJson.CreateDefault();
				_weights = _document.Table;
			}
		}

		private static void WriteAtomically(string path, string contents)
		{
			string text = path + ".tmp";
			File.WriteAllText(text, contents);
			File.Move(text, path);
		}

		private static void ReportUnknownKeys(OrbWeightsDocument document)
		{
			List<string> list = document.UnknownKeys().ToList();
			if (list.Count != 0)
			{
				string arg = string.Join(", ", list.Take(5));
				Log.LogWarning((object)($"Weights file has {list.Count} orb key(s) this mod doesn't know: {arg}" + ((list.Count > 5) ? ", ..." : "") + ". Check for typos; those lines do nothing."));
			}
		}

		private void CheckGameVersion()
		{
			string version = Application.version;
			if (!(version == "2.0.12"))
			{
				Log.LogWarning((object)("PeglinOrbOrder 1.0.0 was built for Peglin v2.0.12, but this is Peglin v" + version + ". Orb weights may not apply until the mod is updated for this game version."));
			}
		}
	}
}
namespace PeglinOrbOrder.Core
{
	public static class DefaultWeights
	{
		public static readonly IReadOnlyDictionary<string, int> All = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase)
		{
			{ "poison_orb", 95 },
			{ "cauldron_bubball", 95 },
			{ "toil_and_trouball", 90 },
			{ "balleviation", 85 },
			{ "generatorb", 80 },
			{ "splatorb", 80 },
			{ "twooze_company", 80 },
			{ "chemiball_hazard", 70 },
			{ "potion_belt", 70 },
			{ "ballm", 65 },
			{ "douball_douball", 45 },
			{ "blind", 90 },
			{ "transpherency_orb", 90 },
			{ "blind_ice", 85 },
			{ "debuff", 80 },
			{ "bramble", 80 },
			{ "susceptiball", 75 },
			{ "roundabout", 75 },
			{ "exacorbate", 60 },
			{ "ballestra", 40 },
			{ "instigatorb", 100 },
			{ "summoning_circle", 90 },
			{ "activatorb", 85 },
			{ "orbust", 80 },
			{ "ballad", 75 },
			{ "arccentuate", 70 },
			{ "rubber_applier", 70 },
			{ "twinorb", 70 },
			{ "best_foot_forworb", 65 },
			{ "renewed_vigorb", 60 },
			{ "potentiorb", 45 },
			{ "nimball", 40 },
			{ "critiball", 80 },
			{ "critorb", 75 },
			{ "cleavorb", 50 },
			{ "dagger", 50 },
			{ "evis", 50 },
			{ "all_orb_nothing", 50 },
			{ "extra_orbinary", 45 },
			{ "refreshorb", 70 },
			{ "refreshiball", 65 },
			{ "shuffle", 65 },
			{ "double_edged_sworb", 60 },
			{ "refresh_on_exit", 60 },
			{ "circcae", 75 },
			{ "double_trouball", 70 },
			{ "multiball", 65 },
			{ "forbification", 85 },
			{ "bomborb", 80 },
			{ "buff", 80 },
			{ "protectorb", 80 },
			{ "bucklorb", 75 },
			{ "chopping_ballock", 75 },
			{ "collatorball_damage", 75 },
			{ "ultra_buff_orb", 70 },
			{ "duplicatorb", 70 },
			{ "magnet", 70 },
			{ "jupitorb", 65 },
			{ "fireball", 65 },
			{ "spin_doctorb", 65 },
			{ "morbid", 55 },
			{ "destroy_peg_orb", 55 },
			{ "necorb", 55 },
			{ "special_pegs_orb", 50 },
			{ "evasive_maneuvorb", 80 },
			{ "ellucircle", 75 },
			{ "best_orbfence", 45 },
			{ "irresponsiball", 40 },
			{ "creates_coins", 70 },
			{ "ballectrum", 70 },
			{ "coins_contribute_damage", 60 },
			{ "coin_doubling_orb", 55 },
			{ "spinterest", 55 },
			{ "oreb", 50 },
			{ "pupil_orb", 70 },
			{ "egg", 50 },
			{ "heal_orb", 45 },
			{ "heal_orb_basic", 45 },
			{ "vampire_orb", 45 },
			{ "orbrasion", 55 },
			{ "orberos", 55 },
			{ "offering", 55 },
			{ "snowball", 45 },
			{ "bomb_buff", 45 },
			{ "spinpoint", 45 },
			{ "memorb", 40 },
			{ "self_damage_basic", 40 },
			{ "countorb_attack", 40 },
			{ "angry_tomahawk", 40 },
			{ "self_damage_boost", 35 },
			{ "stone", 50 },
			{ "sworb", 50 },
			{ "warhammer", 50 },
			{ "boulder", 50 },
			{ "icicle", 50 },
			{ "lightning", 50 },
			{ "ballanx", 50 },
			{ "lazorb", 50 },
			{ "sphear", 50 },
			{ "rubber", 50 },
			{ "horriball", 50 },
			{ "terriball", 50 },
			{ "portal", 50 },
			{ "mirror", 50 },
			{ "assemball", 50 },
			{ "dense_orb", 50 },
			{ "echo_orb", 50 },
			{ "ghost", 50 },
			{ "orbelisk", 50 },
			{ "orbbery", 50 }
		};
	}
	public sealed class OrbWeightsDocument
	{
		[JsonProperty("readme", Order = 0)]
		public string Readme = "Draw weights for Peglin orbs, 0-100. Higher weights are drawn earlier more often, and the roll is fresh each battle. 50 is the baseline (Pebballs and plain damage orbs). Support orbs sit at 60-100 so they tend to open the battle. 0 means never first, always drawn last (no shipped orb uses it). 'exponent' sharpens or softens every weight: 0 is a plain shuffle (orbs set to 0 still come last), 1 uses the weights as written, 2 makes each point count twice as much. Orb keys this file leaves out keep their shipped weight; 'defaultWeight' covers orb keys the mod doesn't know, such as one added by a game update.";

		[JsonProperty("defaultWeight", Order = 1)]
		public long DefaultWeight = 50L;

		[JsonProperty("exponent", Order = 2)]
		public double Exponent = 1.0;

		[JsonProperty("orbs", Order = 3)]
		public Dictionary<string, long> Orbs = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase);

		public const string WeightsFileReadme = "Draw weights for Peglin orbs, 0-100. Higher weights are drawn earlier more often, and the roll is fresh each battle. 50 is the baseline (Pebballs and plain damage orbs). Support orbs sit at 60-100 so they tend to open the battle. 0 means never first, always drawn last (no shipped orb uses it). 'exponent' sharpens or softens every weight: 0 is a plain shuffle (orbs set to 0 still come last), 1 uses the weights as written, 2 makes each point count twice as much. Orb keys this file leaves out keep their shipped weight; 'defaultWeight' covers orb keys the mod doesn't know, such as one added by a game update.";

		private OrbWeightTable _table;

		[JsonIgnore]
		public OrbWeightTable Table
		{
			get
			{
				if (_table == null)
				{
					Dictionary<string, int> dictionary = new Dictionary<string, int>(Orbs.Count, StringComparer.OrdinalIgnoreCase);
					foreach (KeyValuePair<string, long> orb in Orbs)
					{
						dictionary[orb.Key] = (int)Math.Max(0L, Math.Min(100L, orb.Value));
					}
					_table = new OrbWeightTable(dictionary, (int)DefaultWeight);
				}
				return _table;
			}
		}

		public IEnumerable<string> UnknownKeys()
		{
			foreach (string key in Orbs.Keys)
			{
				if (!DefaultWeights.All.ContainsKey(key))
				{
					yield return key;
				}
			}
		}

		public OrbWeightsDocument Sanitize()
		{
			DefaultWeight = Math.Max(0L, Math.Min(100L, DefaultWeight));
			if (double.IsNaN(Exponent) || double.IsInfinity(Exponent))
			{
				Exponent = 1.0;
			}
			Exponent = Math.Max(0.0, Math.Min(4.0, Exponent));
			Dictionary<string, long> dictionary = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase);
			if (Orbs != null)
			{
				foreach (KeyValuePair<string, long> orb in Orbs)
				{
					if (!string.IsNullOrEmpty(orb.Key))
					{
						dictionary[orb.Key] = Math.Max(0L, Math.Min(100L, orb.Value));
					}
				}
			}
			Orbs = dictionary;
			_table = null;
			return this;
		}

		public OrbWeightsDocument WithMissingDefaults()
		{
			if (Orbs == null)
			{
				Orbs = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase);
			}
			foreach (KeyValuePair<string, int> item in DefaultWeights.All)
			{
				if (!Orbs.ContainsKey(item.Key))
				{
					Orbs[item.Key] = item.Value;
				}
			}
			_table = null;
			return this;
		}

		public int MissingDefaultCount()
		{
			int num = 0;
			foreach (string key in DefaultWeights.All.Keys)
			{
				if (Orbs == null || !Orbs.ContainsKey(key))
				{
					num++;
				}
			}
			return num;
		}
	}
	public static class OrbWeightsJson
	{
		public const double MinExponent = 0.0;

		public const double MaxExponent = 4.0;

		public static OrbWeightsDocument CreateDefault()
		{
			OrbWeightsDocument orbWeightsDocument = new OrbWeightsDocument
			{
				DefaultWeight = 50L,
				Exponent = 1.0
			};
			foreach (KeyValuePair<string, int> item in DefaultWeights.All)
			{
				orbWeightsDocument.Orbs[item.Key] = item.Value;
			}
			return orbWeightsDocument;
		}

		public static OrbWeightsDocument Parse(string json)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(json))
			{
				throw new JsonException("The weights file is empty.");
			}
			return (JsonConvert.DeserializeObject<OrbWeightsDocument>(json) ?? throw new JsonException("The weights file did not contain a JSON object.")).Sanitize();
		}

		public static string Serialize(OrbWeightsDocument document)
		{
			return JsonConvert.SerializeObject((object)document.Sanitize(), (Formatting)1);
		}
	}
	public sealed class OrbWeightTable
	{
		public const int DefaultWeight = 50;

		public const int MinWeight = 0;

		public const int MaxWeight = 100;

		private readonly Dictionary<string, int> _weights;

		public int DefaultForUnknown { get; }

		public int Count => _weights.Count;

		public OrbWeightTable(IEnumerable<KeyValuePair<string, int>> weights, int defaultWeight = 50)
		{
			DefaultForUnknown = Clamp(defaultWeight);
			_weights = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
			if (weights == null)
			{
				return;
			}
			foreach (KeyValuePair<string, int> weight in weights)
			{
				if (!string.IsNullOrEmpty(weight.Key))
				{
					_weights[weight.Key] = Clamp(weight.Value);
				}
			}
		}

		public int For(string key)
		{
			if (string.IsNullOrEmpty(key))
			{
				return DefaultForUnknown;
			}
			if (!_weights.TryGetValue(key, out var value))
			{
				return DefaultForUnknown;
			}
			return value;
		}

		public static int Clamp(int weight)
		{
			if (weight < 0)
			{
				return 0;
			}
			if (weight <= 100)
			{
				return weight;
			}
			return 100;
		}

		public static OrbWeightTable Defaults()
		{
			return new OrbWeightTable(DefaultWeights.All);
		}
	}
	public static class WeightedOrder
	{
		public static void ShuffleInPlace<T>(IList<T> items, Func<T, string> keyOf, OrbWeightTable table, double exponent, Func<double> nextUnit)
		{
			if (keyOf == null)
			{
				throw new ArgumentNullException("keyOf");
			}
			if (table == null)
			{
				throw new ArgumentNullException("table");
			}
			if (nextUnit == null)
			{
				throw new ArgumentNullException("nextUnit");
			}
			if (items == null || items.Count < 2)
			{
				return;
			}
			int count = items.Count;
			double[] keys = new double[count];
			int[] array = new int[count];
			for (int i = 0; i < count; i++)
			{
				array[i] = i;
				int num = table.For(keyOf(items[i]));
				if (num <= 0)
				{
					keys[i] = 0.0;
					continue;
				}
				double num2 = EffectiveWeight(num, exponent);
				double num3 = nextUnit();
				if (double.IsNaN(num3) || num3 <= 0.0)
				{
					num3 = double.Epsilon;
				}
				else if (num3 > 1.0)
				{
					num3 = 1.0;
				}
				keys[i] = Math.Pow(num3, 1.0 / num2);
			}
			Array.Sort(array, delegate(int a, int b)
			{
				int num6 = keys[b].CompareTo(keys[a]);
				return (num6 == 0) ? a.CompareTo(b) : num6;
			});
			T[] array2 = new T[count];
			for (int num4 = 0; num4 < count; num4++)
			{
				array2[num4] = items[num4];
			}
			for (int num5 = 0; num5 < count; num5++)
			{
				items[num5] = array2[array[num5]];
			}
		}

		public static double EffectiveWeight(int weight, double exponent)
		{
			if (weight <= 0)
			{
				return 0.0;
			}
			if (double.IsNaN(exponent) || exponent < 0.0)
			{
				exponent = 1.0;
			}
			return Math.Pow(weight, exponent);
		}
	}
}