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 System.Text.RegularExpressions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using LethalLevelLoader; using Microsoft.CodeAnalysis; using UnityEngine; using UnityEngine.Events; using UnityEngine.SceneManagement; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Elowiny.RandomMoonsTest")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.4.0")] [assembly: AssemblyInformationalVersion("1.0.4+15d6f9d5fbd32de9b1884f29ddec3be9133bd912")] [assembly: AssemblyProduct("Elowiny.RandomMoonsTest")] [assembly: AssemblyTitle("Elowiny.RandomMoonsTest")] [assembly: AssemblyVersion("1.0.4.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 RandomMoonsTest { internal static class DawnCompatibility { private static object zeroCost; private static FieldInfo moonsField; private static PropertyInfo purchaseProperty; private static PropertyInfo routeProperty; private static PropertyInfo receiptProperty; private static PropertyInfo levelProperty; private static PropertyInfo predicateProperty; private static MethodInfo costSetter; internal static void Initialize(Harmony harmony) { //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Expected O, but got Unknown Type type = AccessTools.TypeByName("Dawn.DawnMoonInfo"); if (!(type == null)) { zeroCost = Activator.CreateInstance(AccessTools.TypeByName("Dawn.SimpleProvider`1").MakeGenericType(typeof(int)), 0); moonsField = AccessTools.Field(AccessTools.TypeByName("Dawn.LethalContent"), "Moons"); purchaseProperty = AccessTools.Property(type, "DawnPurchaseInfo"); routeProperty = AccessTools.Property(type, "RouteNode"); receiptProperty = AccessTools.Property(type, "ReceiptNode"); levelProperty = AccessTools.Property(type, "Level"); Type type2 = AccessTools.TypeByName("Dawn.DawnPurchaseInfo"); costSetter = AccessTools.PropertySetter(type2, "Cost"); predicateProperty = AccessTools.Property(type2, "PurchasePredicate"); if (moonsField == null || costSetter == null || purchaseProperty == null) { throw new InvalidOperationException("Installed DawnLib moon-price API does not match the audited 0.9.25 API."); } harmony.Patch((MethodBase)AccessTools.Method("Dawn.MoonRegistrationHandler:UpdateMoonPrice", (Type[])null, (Type[])null), new HarmonyMethod(typeof(DawnCompatibility), "PrepareMoonPrice", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } private static IEnumerable Values() { object obj = moonsField?.GetValue(null); if (obj != null) { return AccessTools.Property(obj.GetType(), "Values")?.GetValue(obj) as IEnumerable; } return null; } internal static void Refresh() { IEnumerable enumerable = Values(); if (enumerable == null) { return; } foreach (object item in enumerable) { PrepareMoonPrice(item); } } private static void PrepareMoonPrice(object moonInfo) { if (moonInfo != null && zeroCost != null) { object value = purchaseProperty.GetValue(moonInfo); costSetter.Invoke(value, new object[1] { zeroCost }); object? value2 = routeProperty.GetValue(moonInfo); Plugin.FreeNode((TerminalNode)((value2 is TerminalNode) ? value2 : null)); object? value3 = receiptProperty.GetValue(moonInfo); Plugin.FreeNode((TerminalNode)((value3 is TerminalNode) ? value3 : null)); } } internal static bool CanRoute(SelectableLevel level) { IEnumerable enumerable = Values(); if (enumerable == null) { return true; } foreach (object item in enumerable) { object? value = levelProperty.GetValue(item); if (!((Object)((value is SelectableLevel) ? value : null) != (Object)(object)level)) { object value2 = purchaseProperty.GetValue(item); object value3 = predicateProperty.GetValue(value2); object obj = AccessTools.Method(value3.GetType(), "CanPurchase", (Type[])null, (Type[])null).Invoke(value3, null); if (obj == null) { return false; } string name = obj.GetType().Name; if (name == "SuccessPurchaseResult") { return true; } if (name == "HiddenPurchaseResult") { return AccessTools.Property(obj.GetType(), "IsFailure").GetValue(obj) is bool flag && !flag; } return false; } } return true; } private static object FindMoon(SelectableLevel level) { IEnumerable enumerable = Values(); if (enumerable != null) { foreach (object item in enumerable) { object? value = levelProperty.GetValue(item); if ((Object)((value is SelectableLevel) ? value : null) == (Object)(object)level) { return item; } } } return null; } internal static TerminalNode Receipt(SelectableLevel level) { object obj = FindMoon(level); if (obj != null) { object? value = receiptProperty.GetValue(obj); return (TerminalNode)((value is TerminalNode) ? value : null); } return null; } internal static IEnumerable Tags(SelectableLevel level) { object obj = FindMoon(level); IEnumerable enumerable = ((obj == null) ? null : (AccessTools.Method(obj.GetType(), "AllTags", (Type[])null, (Type[])null).Invoke(obj, null) as IEnumerable)); if (enumerable == null) { yield break; } foreach (object item in enumerable) { yield return item.ToString(); } } internal static bool IsVanilla(SelectableLevel level) { object obj = FindMoon(level); if (obj == null) { return false; } object value = AccessTools.Property(obj.GetType(), "Key").GetValue(obj); object obj2 = AccessTools.Method(value.GetType(), "IsVanilla", (Type[])null, (Type[])null).Invoke(value, null); bool flag = default(bool); int num; if (obj2 is bool) { flag = (bool)obj2; num = 1; } else { num = 0; } return (byte)((uint)num & (flag ? 1u : 0u)) != 0; } } [BepInPlugin("elowiny.randommoonstest", "Random Moons Test", "1.0.4")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] public sealed class Bootstrap : BaseUnityPlugin { private void Awake() { new Plugin(((BaseUnityPlugin)this).Config, ((BaseUnityPlugin)this).Logger); } private void OnDestroy() { ((BaseUnityPlugin)this).Logger.LogInfo((object)("BOOTSTRAP_DESTROYED runtime retained=" + (Plugin.Instance != null))); } } internal sealed class Plugin { [HarmonyPatch(typeof(StartOfRound), "Update")] private static class TickPatch { [HarmonyPostfix] private static void Postfix() { Instance?.Update(); } } [HarmonyPatch(typeof(Terminal), "ParsePlayerSentence")] private static class ParsePatch { [HarmonyPrefix] [HarmonyPriority(800)] private static bool Prefix(Terminal __instance, ref TerminalNode __result) { if (Instance == null) { return true; } try { TerminalNode result; bool num = Instance.Parse(__instance, out result); if (!num) { __result = result; } return num; } catch (Exception ex) { Instance.awaitingChoice = false; Instance.Logger.LogError((object)ex); __result = Instance.NewResponse("Random route failed safely. See BepInEx/LogOutput.log.\nType random to try again.\n"); return false; } } } [HarmonyPatch(typeof(Terminal), "BeginUsingTerminal")] private static class EnterPatch { [HarmonyPostfix] private static void Postfix(Terminal __instance) { Instance?.FreeRoutes(); Instance?.RegisterNativeCommand(__instance); } } [HarmonyPatch(typeof(StartOfRound), "Start")] private static class LobbyPatch { [HarmonyPostfix] private static void Postfix() { if (Instance != null) { Instance.history.Clear(); Instance.landing.Reset(); Instance.session = StartOfRound.Instance; Terminal val = Object.FindObjectOfType(); if ((Object)(object)val != (Object)null) { Instance.RegisterNativeCommand(val); } } } } [HarmonyPatch(typeof(StartOfRound), "OnShipLandedMiscEvents")] private static class LandingPatch { [HarmonyPostfix] private static void Postfix(StartOfRound __instance) { if (Instance != null && !((Object)(object)__instance.currentLevel == (Object)null) && Instance.landing.Observe(landed: true)) { string text = Identity(__instance.currentLevel); Instance.history.Land(text); Instance.Logger.LogInfo((object)$"LANDING_VISIT {text} count={Instance.history.Count(text)}"); } } } [HarmonyPatch(typeof(StartOfRound), "StartGame")] private static class DescentPatch { [HarmonyPrefix] private static void Prefix(StartOfRound __instance) { if (Instance != null && __instance.inShipPhase) { Instance.landing.Reset(); } } } [HarmonyPatch(typeof(Terminal), "QuitTerminal")] private static class ExitPatch { [HarmonyPostfix] private static void Postfix() { if (Instance != null) { Instance.awaitingChoice = false; } } } [HarmonyPatch(typeof(Terminal), "LoadNewNodeIfAffordable")] private static class PricePatch { [HarmonyPrefix] [HarmonyPriority(0)] private static void Prefix(TerminalNode node) { FreeNode(node); } } [HarmonyPatch(typeof(Terminal), "LoadNewNode")] private static class DisplayPatch { [HarmonyPrefix] [HarmonyPriority(800)] private static void Prefix(Terminal __instance, TerminalNode node) { if (Instance != null && (Object)(object)node == (Object)(object)Instance.nativeMenu) { Instance.RefreshNativeMenu(__instance); } FreeNode(node); } } [HarmonyPatch(/*Could not decode attribute arguments.*/)] private static class LoaderPricePatch { [HarmonyPrefix] private static void Prefix(ref int value) { value = 0; } } [HarmonyPatch(/*Could not decode attribute arguments.*/)] private static class LoaderPriceReadPatch { [HarmonyPrefix] private static void Prefix(ExtendedLevel __instance) { FreeNode(__instance.RouteNode); FreeNode(__instance.RouteConfirmNode); } [HarmonyPostfix] private static void Postfix(ref int __result) { __result = 0; } } public const string Guid = "elowiny.randommoonstest"; internal static Plugin Instance; private readonly ConfigFile Config; private readonly ManualLogSource Logger; private Harmony harmony; private ConfigEntry repeatWeight; private ConfigEntry excludedScenes; private readonly LandingHistory history = new LandingHistory(); private readonly LandingObserver landing = new LandingObserver(); private readonly Random random = new Random(); private StartOfRound session; private Terminal choiceTerminal; private TerminalNode response; private bool awaitingChoice; private bool updateReported; private Terminal eventTerminal; private UnityAction textListener; private Terminal registeredTerminal; private TerminalKeyword nativeRandom; private TerminalNode nativeMenu; private string catalogueSignature; private readonly List nativeMenuObjects = new List(); private static readonly Regex DollarPrice = new Regex("\\$\\d[\\d,]*", RegexOptions.Compiled); internal Plugin(ConfigFile config, ManualLogSource logger) { //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Expected O, but got Unknown //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Expected O, but got Unknown Config = config; Logger = logger; Instance = this; SceneManager.sceneLoaded += SceneLoaded; repeatWeight = Config.Bind("Selection", "RepeatWeight", 0.01f, new ConfigDescription("Weight of a more-visited moon relative to a least-visited moon. Positive: repeats remain possible.", (AcceptableValueBase)(object)new AcceptableValueRange(1E-06f, 1f), Array.Empty())); excludedScenes = Config.Bind("Safety", "ExcludedScenes", "CompanyBuilding", "Comma-separated scene names always excluded from random. Manual routing is still available and free."); harmony = new Harmony("elowiny.randommoonstest"); Type[] array = new Type[11] { typeof(ParsePatch), typeof(EnterPatch), typeof(ExitPatch), typeof(PricePatch), typeof(DisplayPatch), typeof(LoaderPricePatch), typeof(LoaderPriceReadPatch), typeof(LobbyPatch), typeof(LandingPatch), typeof(DescentPatch), typeof(TickPatch) }; foreach (Type type in array) { harmony.CreateClassProcessor(type).Patch(); } DawnCompatibility.Initialize(harmony); Patches patchInfo = Harmony.GetPatchInfo((MethodBase)AccessTools.Method(typeof(Terminal), "ParsePlayerSentence", (Type[])null, (Type[])null)); if (patchInfo == null || !patchInfo.Prefixes.Any((Patch p) => p.owner == "elowiny.randommoonstest")) { throw new InvalidOperationException("Random terminal parser hook was not installed."); } Logger.LogInfo((object)"Random Moons Test 1.0.4 ready; automatic registered moon discovery; managed runtime survives bootstrap destruction."); } private void SceneLoaded(Scene scene, LoadSceneMode mode) { bool flag = Harmony.GetPatchInfo((MethodBase)AccessTools.Method(typeof(Terminal), "ParsePlayerSentence", (Type[])null, (Type[])null))?.Prefixes.Any((Patch p) => p.owner == "elowiny.randommoonstest") ?? false; Logger.LogInfo((object)$"SCENE_CALLBACK {((Scene)(ref scene)).name} parserRecorded={flag} instanceMatches={Instance == this} terminalAssembly={typeof(Terminal).Assembly.FullName}"); BindTerminalEvents(); } private void BindTerminalEvents() { Terminal terminal = Object.FindObjectOfType(); if ((Object)(object)terminal == (Object)null || (Object)(object)terminal.screenText == (Object)null) { return; } RegisterNativeCommand(terminal); if ((Object)(object)eventTerminal == (Object)(object)terminal) { return; } if ((Object)(object)eventTerminal != (Object)null && textListener != null) { ((UnityEvent)(object)eventTerminal.screenText.onValueChanged).RemoveListener(textListener); } eventTerminal = terminal; textListener = delegate(string text) { RegisterNativeCommand(terminal); if (terminal.terminalInUse && terminal.textAdded > 0 && text.Substring(Math.Max(0, text.Length - terminal.textAdded)).Trim().ToLowerInvariant() == "random") { Logger.LogInfo((object)"INPUT_EVENT random"); FreeRoutes(); RefreshNativeMenu(terminal, activateChoice: false); } }; ((UnityEvent)(object)terminal.screenText.onValueChanged).AddListener(textListener); RefreshNativeMenu(terminal, activateChoice: false); Logger.LogInfo((object)"TERMINAL_EVENTS_BOUND native keyword and menu ready"); } private void Update() { if (!updateReported) { updateReported = true; Logger.LogInfo((object)"RUNTIME_TICK managed runtime active"); } StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance != (Object)(object)session) { session = instance; history.Clear(); landing.Reset(); awaitingChoice = false; } if ((Object)(object)instance == (Object)null) { return; } if ((Object)(object)eventTerminal == (Object)null) { BindTerminalEvents(); } if ((Object)(object)registeredTerminal == (Object)null && PatchedContent.ExtendedLevels.Count > 0) { Terminal val = Object.FindObjectOfType(); if ((Object)(object)val != (Object)null) { RegisterNativeCommand(val); } } if (landing.Observe(instance.shipHasLanded) && (Object)(object)instance.currentLevel != (Object)null) { string text = Identity(instance.currentLevel); history.Land(text); Logger.LogInfo((object)$"LANDING_VISIT {text} count={history.Count(text)}"); } } internal static string Identity(SelectableLevel level) { if (!((Object)(object)level == (Object)null)) { return ((Object)level).name + ":" + ((Object)level).GetInstanceID(); } return ""; } private static HashSet SceneSet(string value) { return new HashSet(from s in (value ?? "").Split(',') select s.Trim() into s where s.Length > 0 select s, StringComparer.OrdinalIgnoreCase); } internal List Candidates() { //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Invalid comparison between Unknown and I4 List list = new List(); StartOfRound instance = StartOfRound.Instance; if (instance?.levels == null) { return list; } HashSet hashSet = SceneSet(excludedScenes.Value); for (int i = 0; i < instance.levels.Length; i++) { SelectableLevel level = instance.levels[i]; if (!((Object)(object)level == (Object)null)) { ExtendedLevel val = ((IEnumerable)PatchedContent.ExtendedLevels).FirstOrDefault((Func)((ExtendedLevel e) => (Object)(object)e != (Object)null && (Object)(object)e.SelectableLevel == (Object)(object)level)); string text = level.sceneName ?? ""; string id = Identity(level); bool modded = (((Object)(object)val != (Object)null) ? ((int)((ExtendedContent)val).ContentType > 0) : (!DawnCompatibility.IsVanilla(level))); IEnumerable first = ((val == null) ? null : (from t in ((ExtendedContent)val).ContentTags?.Where((ContentTag t) => (Object)(object)t != (Object)null) select t.contentTagName)) ?? Enumerable.Empty(); bool selling = SelectionRules.IsSellingDestination(text, first.Concat(DawnCompatibility.Tags(level))); if (SelectionRules.Eligible(text.Length > 0, selling, (Object)(object)val != (Object)null && val.IsRouteLocked, (Object)(object)val != (Object)null && val.IsRouteRemoved, (Object)(object)GameNetworkManager.Instance != (Object)null && GameNetworkManager.Instance.isDemo && level.lockedForDemo, level.spawnEnemiesAndScrap, level.planetHasTime, hashSet.Contains(text)) && !((Object)(object)ResolveRoute(level, i) == (Object)null) && DawnCompatibility.CanRoute(level)) { list.Add(new MoonChoice { Id = id, Name = level.PlanetName, Modded = modded, Index = i }); } } } string text2 = string.Join("|", list.Select((MoonChoice m) => m.Id + ":" + m.Modded)); if (text2 != catalogueSignature) { catalogueSignature = text2; Logger.LogInfo((object)$"AUTO_MOONS_DISCOVERED registered={instance.levels.Length} eligible={list.Count} modded={list.Count((MoonChoice m) => m.Modded)} vanilla={list.Count((MoonChoice m) => !m.Modded)}"); } return list; } private static TerminalNode ResolveRoute(SelectableLevel level, int index) { ExtendedLevel? obj = ((IEnumerable)PatchedContent.ExtendedLevels).FirstOrDefault((Func)((ExtendedLevel e) => (Object)(object)e != (Object)null && (Object)(object)e.SelectableLevel == (Object)(object)level)); TerminalNode val = ((obj != null) ? obj.RouteConfirmNode : null) ?? DawnCompatibility.Receipt(level); if ((Object)(object)val != (Object)null && !val.isConfirmationNode && val.buyRerouteToMoon == index) { return val; } return ((IEnumerable)Resources.FindObjectsOfTypeAll()).FirstOrDefault((Func)((TerminalNode n) => (Object)(object)n != (Object)null && !n.isConfirmationNode && n.buyRerouteToMoon == index)); } internal static bool IsRouteNode(TerminalNode node) { if ((Object)(object)node != (Object)null) { if (node.buyRerouteToMoon < 0 && node.buyRerouteToMoon != -2) { return node.displayPlanetInfo >= 0; } return true; } return false; } internal static void FreeNode(TerminalNode node) { if (IsRouteNode(node)) { node.itemCost = 0; if (!string.IsNullOrEmpty(node.displayText)) { node.displayText = DollarPrice.Replace(node.displayText, "$0"); } } } internal void FreeRoutes() { DawnCompatibility.Refresh(); foreach (ExtendedLevel extendedLevel in PatchedContent.ExtendedLevels) { if (!((Object)(object)extendedLevel == (Object)null)) { extendedLevel.RoutePrice = 0; FreeNode(extendedLevel.RouteNode); FreeNode(extendedLevel.RouteConfirmNode); } } TerminalNode[] array = Resources.FindObjectsOfTypeAll(); for (int i = 0; i < array.Length; i++) { FreeNode(array[i]); } } internal bool Parse(Terminal terminal, out TerminalNode result) { result = null; FreeRoutes(); RegisterNativeCommand(terminal); if ((Object)(object)terminal.screenText == (Object)null || terminal.textAdded <= 0) { return true; } string text = terminal.screenText.text; string text2 = text.Substring(Math.Max(0, text.Length - terminal.textAdded)).Trim().ToLowerInvariant(); if (text2 == "random") { awaitingChoice = true; choiceTerminal = terminal; Logger.LogInfo((object)"COMMAND_RECEIVED random"); result = NewResponse(Prompt()); return false; } if (!awaitingChoice || (Object)(object)choiceTerminal != (Object)(object)terminal) { return true; } switch (text2) { case "cancel": case "back": case "deny": awaitingChoice = false; result = NewResponse("Random route cancelled.\n"); return false; default: { if (text2 != "mod" && text2 != "vanilla" && text2 != "all") { awaitingChoice = false; if ((Object)(object)terminal.currentNode == (Object)(object)nativeMenu) { nativeMenu.overrideOptions = false; } return true; } List list = SelectionRules.Filter(Candidates(), text2); if (list.Count == 0) { result = NewResponse("No eligible " + text2 + " moons available.\n\n" + Prompt()); return false; } StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance == (Object)null || !instance.inShipPhase || instance.travellingToNewLevel || instance.beganLoadingNewLevel || instance.shipIsLeaving || instance.isChallengeFile || (Object)(object)RoundManager.Instance == (Object)null || RoundManager.Instance.dungeonIsGenerating || terminal.useCreditsCooldown) { result = NewResponse("Wait until the ship is idle in orbit, then enter " + text2 + " again.\n"); return false; } MoonChoice moonChoice = SelectionRules.Pick(list, history, Identity(instance.currentLevel), repeatWeight.Value, random.NextDouble); if ((Object)(object)instance.currentLevel == (Object)(object)instance.levels[moonChoice.Index]) { awaitingChoice = false; result = NewResponse("Already orbiting " + moonChoice.Name + ", the only eligible moon.\nLand to visit it, or type random to choose again.\n"); return false; } TerminalNode val = ResolveRoute(instance.levels[moonChoice.Index], moonChoice.Index); if ((Object)(object)val == (Object)null || val.isConfirmationNode || val.buyRerouteToMoon != moonChoice.Index) { throw new InvalidOperationException("Route confirmation node does not match the installed moon index: " + moonChoice.Id); } FreeNode(val); awaitingChoice = false; Logger.LogInfo((object)$"RANDOM_ROUTE category={text2} scene={instance.levels[moonChoice.Index].sceneName} identity={moonChoice.Id} landedCount={history.Count(moonChoice.Id)} credits={terminal.groupCredits}"); result = val; return false; } } } private string Prompt() { bool flag = Candidates().Any((MoonChoice m) => m.Modded); return "RANDOM MOONS — all routes are free\n\n" + (flag ? "mod — random modded moon\n" : "mod — unavailable (no eligible modded moons)\n") + "vanilla — random vanilla moon\nall — either kind\n\ncancel — exit\n\nReroll with random. Only landing counts as a visit.\n"; } private TerminalNode NewResponse(string text) { TerminalNode val = response; response = ScriptableObject.CreateInstance(); ((Object)response).name = "RandomMoonsResponse"; response.displayText = text; response.clearPreviousText = true; response.maxCharactersToType = 80; response.buyItemIndex = (response.buyVehicleIndex = (response.buyRerouteToMoon = (response.shipUnlockableID = (response.displayPlanetInfo = -1)))); if ((Object)(object)val != (Object)null) { Object.Destroy((Object)(object)val); } return response; } internal void RegisterNativeCommand(Terminal terminal) { if (terminal.terminalNodes?.allKeywords != null && (!((Object)(object)registeredTerminal == (Object)(object)terminal) || !((Object)(object)nativeRandom != (Object)null) || !terminal.terminalNodes.allKeywords.Contains(nativeRandom))) { nativeMenu = ScriptableObject.CreateInstance(); ((Object)nativeMenu).name = "RandomMoonsNativeMenu"; nativeMenu.displayText = Prompt(); nativeMenu.clearPreviousText = true; nativeMenu.maxCharactersToType = 80; nativeMenu.buyItemIndex = (nativeMenu.buyVehicleIndex = (nativeMenu.buyRerouteToMoon = (nativeMenu.shipUnlockableID = (nativeMenu.displayPlanetInfo = -1)))); nativeRandom = ScriptableObject.CreateInstance(); ((Object)nativeRandom).name = "RandomMoonsKeyword"; nativeRandom.word = "random"; nativeRandom.specialKeywordResult = nativeMenu; terminal.terminalNodes.allKeywords = terminal.terminalNodes.allKeywords.Where((TerminalKeyword k) => (Object)(object)k != (Object)null && !string.Equals(k.word, "random", StringComparison.OrdinalIgnoreCase)).Concat((IEnumerable)(object)new TerminalKeyword[1] { nativeRandom }).ToArray(); registeredTerminal = terminal; Logger.LogInfo((object)$"COMMAND_REGISTERED random keywords={terminal.terminalNodes.allKeywords.Length}"); } } private void RefreshNativeMenu(Terminal terminal, bool activateChoice = true) { //IL_01f3: Unknown result type (might be due to invalid IL or missing references) //IL_01fd: Expected O, but got Unknown foreach (Object nativeMenuObject in nativeMenuObjects) { if (nativeMenuObject != (Object)null) { Object.Destroy(nativeMenuObject); } } nativeMenuObjects.Clear(); List list = new List(); string[] array = new string[5] { "mod", "vanilla", "all", "cancel", "random" }; foreach (string text in array) { TerminalKeyword val = ScriptableObject.CreateInstance(); val.word = text; nativeMenuObjects.Add((Object)(object)val); TerminalNode val2 = nativeMenu; List list2 = SelectionRules.Filter(Candidates(), text); StartOfRound instance = StartOfRound.Instance; if (text != "random" && text != "cancel" && (Object)(object)instance != (Object)null && list2.Count > 0) { MoonChoice moonChoice = SelectionRules.Pick(list2, history, Identity(instance.currentLevel), repeatWeight.Value, random.NextDouble); val2 = ResolveRoute(instance.levels[moonChoice.Index], moonChoice.Index); FreeNode(val2); } else if (text != "random") { val2 = ScriptableObject.CreateInstance(); val2.clearPreviousText = true; val2.displayText = ((text == "cancel") ? "Random route cancelled.\n" : ("No eligible " + text + " moons. Type random to choose again.\n")); val2.buyItemIndex = (val2.buyVehicleIndex = (val2.buyRerouteToMoon = (val2.shipUnlockableID = (val2.displayPlanetInfo = -1)))); nativeMenuObjects.Add((Object)(object)val2); } list.Add(new CompatibleNoun(val, val2)); } nativeMenu.displayText = Prompt(); nativeMenu.overrideOptions = true; nativeMenu.terminalOptions = list.ToArray(); if (activateChoice) { awaitingChoice = true; choiceTerminal = terminal; } Logger.LogInfo((object)"COMMAND_MENU_LOADED native fallback ready"); } } public sealed class LandingHistory { private readonly Dictionary counts = new Dictionary(StringComparer.OrdinalIgnoreCase); public string LastLanded { get; private set; } public int Count(string id) { if (!counts.TryGetValue(id, out var value)) { return 0; } return value; } public void Land(string id) { if (!string.IsNullOrEmpty(id)) { counts[id] = Count(id) + 1; LastLanded = id; } } public void Clear() { counts.Clear(); LastLanded = null; } } public sealed class LandingObserver { private bool wasLanded; public bool Observe(bool landed) { bool result = landed && !wasLanded; wasLanded = landed; return result; } public void Reset() { wasLanded = false; } } public sealed class MoonChoice { public string Id; public string Name; public bool Modded; public int Index; } public static class SelectionRules { public static List Filter(IEnumerable choices, string category) { if (category != "all" && category != "mod" && category != "vanilla") { return new List(); } return (from g in choices.Where((MoonChoice m) => category == "all" || m.Modded == (category == "mod")).GroupBy((MoonChoice m) => m.Id, StringComparer.OrdinalIgnoreCase) select g.First()).ToList(); } public static MoonChoice Pick(IReadOnlyList pool, LandingHistory history, string currentId, double repeatWeight, Func draw) { if (pool.Count == 0) { return null; } if (pool.Count == 1) { return pool[0]; } repeatWeight = Math.Max(1E-06, Math.Min(1.0, repeatWeight)); int num = pool.Min((MoonChoice m) => history.Count(m.Id)); double[] array = new double[pool.Count]; for (int num2 = 0; num2 < pool.Count; num2++) { if (!string.Equals(pool[num2].Id, currentId, StringComparison.OrdinalIgnoreCase)) { array[num2] = ((history.Count(pool[num2].Id) == num) ? 1.0 : repeatWeight); if (string.Equals(pool[num2].Id, history.LastLanded, StringComparison.OrdinalIgnoreCase)) { array[num2] *= repeatWeight; } } } double num3 = array.Sum(); if (num3 == 0.0) { return pool[0]; } double num4 = Math.Max(0.0, Math.Min(0.9999999999999999, draw())) * num3; MoonChoice result = null; for (int num5 = 0; num5 < pool.Count; num5++) { if (!(array[num5] <= 0.0)) { result = pool[num5]; if (num4 < array[num5]) { return pool[num5]; } num4 -= array[num5]; } } return result; } public static bool IsSellingDestination(string scene, IEnumerable tags) { if (string.Equals(scene, "CompanyBuilding", StringComparison.OrdinalIgnoreCase)) { return true; } using (IEnumerator enumerator = (tags ?? Enumerable.Empty()).GetEnumerator()) { while (enumerator.MoveNext()) { switch (new string((enumerator.Current ?? "").Split(':').Last().Where(char.IsLetterOrDigit) .ToArray()).ToLowerInvariant()) { case "company": case "selling": case "companymoon": case "sellingmoon": case "companybuilding": case "sell": case "sellmoon": case "scrapselling": case "scrapsellingmoon": case "sellingdestination": return true; } } } return false; } public static bool Eligible(bool hasScene, bool selling, bool locked, bool removed, bool demoLocked, bool spawnsScrap, bool hasTime, bool excluded) { if (hasScene && !selling && !locked && !removed && !demoLocked && spawnsScrap && hasTime) { return !excluded; } return false; } } }