Decompiled source of GamesOMG Teleport v0.3.3
GamesOMG.PlanetCrafterTeleport.dll
Decompiled an hour ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using Microsoft.CodeAnalysis; using SpaceCraft; using Unity.Netcode; using UnityEngine; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Controls; using UnityEngine.InputSystem.Utilities; 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("GamesOMG.PlanetCrafterTeleport")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.3.3.0")] [assembly: AssemblyInformationalVersion("0.3.3+e0a97a57c1d9cddd355c1070134c06e584b6010d")] [assembly: AssemblyProduct("GamesOMG.PlanetCrafterTeleport")] [assembly: AssemblyTitle("GamesOMG.PlanetCrafterTeleport")] [assembly: AssemblyMetadata("AI_Assisted_Creation", "This assembly was partially or fully created with the assistance of Generative AI (OpenAI Codex and ChatGPT, Anthropic Claude), directed and tested in game by GamesOMG.")] [assembly: AssemblyMetadata("AI_Model_Vendor", "OpenAI/Anthropic")] [assembly: AssemblyVersion("0.3.3.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace GamesOMG.PlanetCrafterTeleport { internal sealed class BackupInfo { public string Path = ""; public string Reason = ""; public DateTime When; public long Bytes; } internal sealed class Backups { public const int Keep = 10; private static readonly Regex Name = new Regex("^places-(\\d{8}-\\d{6})(?:-(\\d+))?-([a-z0-9-]+)\\.json$", RegexOptions.CultureInvariant); private readonly string dir; private readonly Func<DateTime> now; public string Folder => dir; public Backups(string dir, Func<DateTime> now = null) { this.dir = dir; this.now = now ?? ((Func<DateTime>)(() => DateTime.Now)); } public static string Slug(string reason) { string text = Regex.Replace((reason ?? "").ToLowerInvariant(), "[^a-z0-9]+", "-").Trim('-'); if (text.Length != 0) { if (text.Length <= 40) { return text; } return text.Substring(0, 40); } return "manual"; } public string Take(string json, string reason, out string path) { path = null; try { Directory.CreateDirectory(dir); string text = now().ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture); string text2 = Slug(reason); path = Path.Combine(dir, "places-" + text + "-" + text2 + ".json"); int num = 2; while (File.Exists(path)) { path = Path.Combine(dir, "places-" + text + "-" + num + "-" + text2 + ".json"); num++; } string text3 = path + ".tmp"; File.WriteAllText(text3, json ?? ""); File.Move(text3, path); Prune(path); return null; } catch (Exception ex) { path = null; return ex.GetType().Name; } } private void Prune(string keepThis) { List<BackupInfo> list = List(); for (int i = 10; i < list.Count; i++) { if (!string.Equals(list[i].Path, keepThis, StringComparison.OrdinalIgnoreCase)) { try { File.Delete(list[i].Path); } catch (Exception) { } } } } public List<BackupInfo> List() { List<BackupInfo> list = new List<BackupInfo>(); if (!Directory.Exists(dir)) { return list; } string[] files = Directory.GetFiles(dir, "places-*.json"); foreach (string text in files) { Match match = Name.Match(Path.GetFileName(text)); if (match.Success && DateTime.TryParseExact(match.Groups[1].Value, "yyyyMMdd-HHmmss", CultureInfo.InvariantCulture, DateTimeStyles.None, out var result)) { long bytes = 0L; try { bytes = new FileInfo(text).Length; } catch (Exception) { } list.Add(new BackupInfo { Path = text, Reason = match.Groups[3].Value, When = result.AddTicks(match.Groups[2].Success ? int.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture) : 0), Bytes = bytes }); } } list.Sort((BackupInfo a, BackupInfo b) => (!(b.When != a.When)) ? string.CompareOrdinal(b.Path, a.Path) : b.When.CompareTo(a.When)); return list; } } internal sealed class DestinationSectors { private readonly List<Sector> sectors = new List<Sector>(); private readonly List<Sector> requested = new List<Sector>(); private SectorEnter[] entries; private SectorExit[] exits; private readonly HashSet<Sector> seen = new HashSet<Sector>(); private float margin; public bool Ready { get { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) foreach (Sector sector in sectors) { if ((Object)(object)sector != (Object)null) { Scene sceneByName = SceneManager.GetSceneByName(((Object)((Component)sector).gameObject).name); if (!((Scene)(ref sceneByName)).isLoaded) { return false; } } } return true; } } private DestinationSectors(SectorEnter[] entries, SectorExit[] exits) { this.entries = entries; this.exits = exits; } public static bool TryStart(PlayerMainController player, TeleportRequest target, out DestinationSectors loading, out string reason) { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) reason = null; SectorEnter[] array = Object.FindObjectsByType<SectorEnter>((FindObjectsSortMode)0); SectorExit[] array2 = Object.FindObjectsByType<SectorExit>((FindObjectsSortMode)0); loading = new DestinationSectors(array, array2); CharacterController component = ((Component)player).GetComponent<CharacterController>(); DestinationSectors obj = loading; float num; if (!((Object)(object)component != (Object)null)) { num = 3f; } else { Bounds bounds = ((Collider)component).bounds; Vector3 extents = ((Bounds)(ref bounds)).extents; num = ((Vector3)(ref extents)).magnitude + 1f; } obj.margin = num; return loading.Add(target, out reason) >= 0; } public bool Rescan(TeleportRequest target, out string reason) { entries = Object.FindObjectsByType<SectorEnter>((FindObjectsSortMode)0); exits = Object.FindObjectsByType<SectorExit>((FindObjectsSortMode)0); return Add(target, out reason) > 0; } private int Add(TeleportRequest target, out string reason, bool capped = true) { //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) reason = null; List<Sector> list = new List<Sector>(); SectorEnter[] array = entries; foreach (SectorEnter val in array) { if ((Object)(object)val != (Object)null) { Consider(val.sector, val.collider, target, list); } } SectorExit[] array2 = exits; foreach (SectorExit val2 in array2) { if ((Object)(object)val2 != (Object)null) { Consider(val2.sector, val2.collider, target, list); } } sectors.AddRange(list); if (capped && sectors.Count > 16) { reason = L.T("land.tooManySectors"); return -1; } foreach (Sector item in list) { Scene sceneByName = SceneManager.GetSceneByName(((Object)((Component)item).gameObject).name); if (!((Scene)(ref sceneByName)).IsValid()) { requested.Add(item); } if (!((Scene)(ref sceneByName)).isLoaded) { item.LoadSector(); } } return list.Count; } private void Consider(Sector sector, Collider box, TeleportRequest target, List<Sector> added) { if (!((Object)(object)sector == (Object)null) && Holds(box, target) && seen.Add(sector)) { added.Add(sector); } } private bool Holds(Collider box, TeleportRequest target) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)box == (Object)null || !box.enabled) { return false; } Bounds bounds = box.bounds; ((Bounds)(ref bounds)).Expand(new Vector3(margin * 2f, 0f, margin * 2f)); if (!(target.X < ((Bounds)(ref bounds)).min.x) && !(target.X > ((Bounds)(ref bounds)).max.x) && !(target.Z < ((Bounds)(ref bounds)).min.z)) { return !(target.Z > ((Bounds)(ref bounds)).max.z); } return false; } public void ReleaseUnused() { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) PlayerMainController[] occupants = Object.FindObjectsByType<PlayerMainController>((FindObjectsSortMode)0); foreach (Sector item in requested) { if ((Object)(object)item == (Object)null) { continue; } Scene sceneByName = SceneManager.GetSceneByName(((Object)((Component)item).gameObject).name); if (!((Scene)(ref sceneByName)).isLoaded) { continue; } bool flag = false; SectorEnter[] array = entries; foreach (SectorEnter val in array) { if ((Object)(object)val != (Object)null && (Object)(object)val.sector == (Object)(object)item && Occupied(val.collider, occupants)) { flag = true; break; } } if (!flag) { SectorExit[] array2 = exits; foreach (SectorExit val2 in array2) { if ((Object)(object)val2 != (Object)null && (Object)(object)val2.sector == (Object)(object)item && Occupied(val2.collider, occupants)) { flag = true; break; } } } if (!flag) { item.UnloadSector(); } } } private static bool Occupied(Collider box, PlayerMainController[] occupants) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)box == (Object)null) { return false; } Bounds bounds = box.bounds; foreach (PlayerMainController val in occupants) { if (!((Object)(object)val == (Object)null)) { CharacterController component = ((Component)val).GetComponent<CharacterController>(); if (((Bounds)(ref bounds)).Contains(((Component)val).transform.position) || ((Object)(object)component != (Object)null && ((Collider)component).enabled && ((Bounds)(ref bounds)).Intersects(((Collider)component).bounds))) { return true; } } } return false; } } internal interface IFarSwitch { bool ActiveSelf { get; } float X { get; } float Y { get; } float Z { get; } float Reach { get; } bool RootActive { get; } void SetActive(bool on); } internal sealed class DestinationWake { private readonly List<IFarSwitch> woken = new List<IFarSwitch>(); public int Count => woken.Count; public static bool WillBeOn(IFarSwitch s, TeleportRequest at) { if (s == null || !s.RootActive) { return false; } double num = s.X - at.X; double num2 = s.Z - at.Z; double num3 = num * num + num2 * num2; if (!at.AutomaticHeight) { double num4 = s.Y - at.Y; num3 += num4 * num4; } return num3 <= (double)s.Reach * (double)s.Reach; } public int Wake(IEnumerable<IFarSwitch> all, TeleportRequest at) { if (all == null) { return 0; } foreach (IFarSwitch item in new List<IFarSwitch>(all)) { if (item != null && !item.ActiveSelf && WillBeOn(item, at)) { item.SetActive(on: true); woken.Add(item); } } return woken.Count; } public int Undo(Action<string> log = null) { int num = 0; foreach (IFarSwitch item in woken) { try { item.SetActive(on: false); num++; } catch (Exception ex) { log?.Invoke("A floor switched on for the check could not be switched off: " + ex.GetType().Name); } } woken.Clear(); return num; } public void Keep() { woken.Clear(); } } internal sealed class Diagnostics { public const int Keep = 8; private readonly List<string> recent = new List<string>(); public IReadOnlyList<string> Recent => recent; public void Note(string messageId, float atSeconds) { if (!string.IsNullOrEmpty(messageId) && L.Has(messageId)) { recent.Add(messageId + " @" + Math.Round(atSeconds) + "s"); if (recent.Count > 8) { recent.RemoveAt(0); } } } public string Text(IList<KeyValuePair<string, string>> facts) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("GamesOMG Teleport diagnostics\n"); foreach (KeyValuePair<string, string> fact in facts) { stringBuilder.Append(fact.Key).Append(": ").Append(Clean(fact.Value)) .Append('\n'); } stringBuilder.Append("Recent refusals/failures: ").Append((recent.Count == 0) ? "none" : string.Join(", ", recent.ToArray())).Append('\n'); stringBuilder.Append("(No clipboard text, place names or positions are included.)\n"); return stringBuilder.ToString(); } private static string Clean(string value) { value = (value ?? "").Replace('\n', ' ').Replace('\r', ' '); if (value.Length <= 200) { return value; } return value.Substring(0, 200); } } internal static class FarSwitches { private sealed class Switch : IFarSwitch { private readonly PerformancerDisableIfFarAway c; private readonly Vector3 at; private readonly bool rootActive; public bool ActiveSelf { get { if ((Object)(object)c != (Object)null) { return ((Component)c).gameObject.activeSelf; } return false; } } public float X => at.x; public float Y => at.y; public float Z => at.z; public float Reach { get { if (!((Object)(object)c != (Object)null)) { return 0f; } return c.disableIfPlayerIsFarerThan; } } public bool RootActive => rootActive; public Switch(PerformancerDisableIfFarAway c) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) this.c = c; at = ((Component)c).transform.position; GroupNetworkBase componentInParent = ((Component)c).GetComponentInParent<GroupNetworkBase>(true); rootActive = (Object)(object)componentInParent == (Object)null || ((Component)componentInParent).gameObject.activeInHierarchy; } public void SetActive(bool on) { if ((Object)(object)c != (Object)null) { ((Component)c).gameObject.SetActive(on); } } } private static readonly FieldInfo Registered = typeof(GlobalCoroutineUpdater<PerformancerDisableIfFarAway, PerformancersManager>).GetField("_components", BindingFlags.Static | BindingFlags.NonPublic); public static bool Available => Registered != null; public static List<IFarSwitch> Now() { List<IFarSwitch> list = new List<IFarSwitch>(); if (Registered == null) { return list; } if (!(Registered.GetValue(null) is IEnumerable enumerable)) { return list; } foreach (object item in enumerable) { PerformancerDisableIfFarAway val = (PerformancerDisableIfFarAway)((item is PerformancerDisableIfFarAway) ? item : null); if (val != null && (Object)(object)val != (Object)null) { list.Add(new Switch(val)); } } return list; } } internal sealed class FoundSet { public string Key = ""; public string Url = ""; public string Map = ""; public string Hash = ""; public readonly List<string> Worlds = new List<string>(); public readonly List<string> Ids = new List<string>(); public readonly List<int> W = new List<int>(); public const string Origin = "https://gamesomg.com"; private static readonly Regex Link = new Regex("(?:^|[#&?\\s])foundset=([^&\\s#]+)", RegexOptions.CultureInvariant); private static readonly Regex Parts = new Regex("^(.+)\\.([0-9a-z]{1,8})\\.([zb])([A-Za-z0-9_-]*)$", RegexOptions.CultureInvariant); public static bool LooksLikeLink(string text) { if (text != null) { return text.IndexOf("foundset=", StringComparison.Ordinal) >= 0; } return false; } public static FoundSet Read(byte[] deflated) { Dictionary<string, object> dictionary = MiniJson.O(MiniJson.Parse(Encoding.UTF8.GetString(SpotSet.Inflate(deflated, 4194304)))); if (dictionary == null || MiniJson.N(MiniJson.Get(dictionary, "v")) != 1.0) { throw new FormatException("not a v1 found set"); } FoundSet f = new FoundSet { Key = MiniJson.S(MiniJson.Get(dictionary, "key")), Url = MiniJson.S(MiniJson.Get(dictionary, "url")), Map = MiniJson.S(MiniJson.Get(dictionary, "map")), Hash = MiniJson.S(MiniJson.Get(dictionary, "hash")) }; foreach (object item in MiniJson.A(MiniJson.Get(dictionary, "worlds")) ?? new List<object>()) { f.Worlds.Add(MiniJson.S(item)); } foreach (object item2 in MiniJson.A(MiniJson.Get(dictionary, "ids")) ?? new List<object>()) { f.Ids.Add(MiniJson.S(item2)); } foreach (object item3 in MiniJson.A(MiniJson.Get(dictionary, "w")) ?? new List<object>()) { f.W.Add((int)MiniJson.N(item3)); } if (f.Ids.Count == 0 || f.W.Count != f.Ids.Count || f.W.Exists((int i) => i < 0 || i >= f.Worlds.Count)) { throw new FormatException("a found set without its planets"); } if (HashOf(f.Ids) != f.Hash) { throw new FormatException("the packed hash is not the hash of the packed ids"); } return f; } public static string HashOf(List<string> ids) { uint num = 2166136261u; string text = string.Join("\n", ids.ToArray()); for (int i = 0; i < text.Length; i++) { num ^= text[i]; num *= 16777619; } return Base36(num); } private static string Base36(uint v) { if (v == 0) { return "0"; } StringBuilder stringBuilder = new StringBuilder(); while (v != 0) { stringBuilder.Insert(0, "0123456789abcdefghijklmnopqrstuvwxyz"[(int)(v % 36)]); v /= 36; } return stringBuilder.ToString(); } public bool TryRead(string text, out List<int> ticked, out string reason) { ticked = new List<int>(); reason = null; Match match = ((text == null) ? null : Link.Match(text.Trim())); if (match == null || !match.Success) { reason = L.T("found.notLink"); return false; } string text2 = match.Groups[1].Value; try { text2 = Uri.UnescapeDataString(text2); } catch (Exception) { } Match match2 = Parts.Match(text2); if (!match2.Success) { reason = L.T("found.damaged"); return false; } if (match2.Groups[1].Value != Key) { reason = L.T("found.otherList"); return false; } if (match2.Groups[2].Value != Hash) { reason = L.T("found.otherHash"); return false; } byte[] array; try { array = SpotSet.Unbase64Url(match2.Groups[4].Value); if (match2.Groups[3].Value == "z") { array = SpotSet.Inflate(array, 262144); } } catch (Exception) { reason = L.T("found.damaged"); return false; } if (array.Length > (Ids.Count + 7) / 8) { reason = L.T("found.damaged"); return false; } for (int i = 0; i < Ids.Count; i++) { if (i >> 3 < array.Length && (array[i >> 3] & (1 << (i & 7))) != 0) { ticked.Add(i); } } return true; } public string CodeOf(Func<int, bool> on) { byte[] array = new byte[(Ids.Count + 7) / 8]; int num = 0; for (int i = 0; i < Ids.Count; i++) { if (on(i)) { array[i >> 3] |= (byte)(1 << (i & 7)); num = (i >> 3) + 1; } } byte[] array2 = new byte[num]; Array.Copy(array, array2, num); string text = "b" + SpotSet.Base64Url(array2); string text2 = text; if (num > 0) { string text3 = "z" + SpotSet.Base64Url(SpotSet.Deflate(array2)); if (text3.Length < text.Length) { text2 = text3; } } return Key + "." + Hash + "." + text2; } public string LinkOf(Func<int, bool> on) { return "https://gamesomg.com" + Url + "#foundset=" + CodeOf(on); } } internal sealed class HotKey : IDisposable { private readonly ConfigEntry<string> path; private readonly ManualLogSource log; private readonly string name; private InputAction action; private bool logged; public string Path => path.Value; public string Label => KeyCheck.Label(path?.Value); private bool Unset => KeyCheck.Empty(path?.Value); public HotKey(string name, ConfigEntry<string> path, ManualLogSource log) { this.name = name; this.path = path; this.log = log; path.SettingChanged += delegate { Bind(); }; Bind(); } private void Bind() { //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown InputAction obj = action; if (obj != null) { obj.Disable(); } InputAction obj2 = action; if (obj2 != null) { obj2.Dispose(); } action = null; logged = false; if (Unset) { return; } try { action = new InputAction("GamesOMG" + name, (InputActionType)1, path.Value, (string)null, (string)null, (string)null); action.Enable(); } catch (Exception ex) { log.LogWarning((object)(name + " key binding was rejected: " + ex.GetType().Name)); } } public void Tick() { //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) if (action != null && !action.enabled) { action.Enable(); } if (action != null && action.enabled && !logged) { logged = true; log.LogInfo((object)(name + " key " + path.Value + " is on, matched to " + action.controls.Count + " control(s).")); } } public bool Pressed(out string via) { //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) via = null; if (Unset) { return false; } if (action != null && action.WasPressedThisFrame()) { via = "action"; return true; } Keyboard current = Keyboard.current; if (current == null || !((ButtonControl)current.anyKey).wasPressedThisFrame) { return false; } try { InputControlList<InputControl> val = InputSystem.FindControls(path.Value); try { for (int i = 0; i < val.Count; i++) { InputControl obj = val[i]; ButtonControl val2 = (ButtonControl)(object)((obj is ButtonControl) ? obj : null); if (val2 != null && val2.wasPressedThisFrame) { via = "device " + ((InputControl)val[i].device).displayName; log.LogInfo((object)("The " + name + " action missed a press that " + via + " saw; using it.")); return true; } } } finally { ((IDisposable)val/*cast due to .constrained prefix*/).Dispose(); } } catch (Exception ex) { log.LogWarning((object)(name + " key lookup failed: " + ex.GetType().Name)); } return false; } public void Dispose() { InputAction obj = action; if (obj != null) { obj.Disable(); } InputAction obj2 = action; if (obj2 != null) { obj2.Dispose(); } action = null; } } internal sealed class InputHold { private static readonly FieldInfo OpenedUi = typeof(WindowsHandler).GetField("_openedUi", BindingFlags.Instance | BindingFlags.NonPublic); private readonly ManualLogSource log; private readonly List<InputAction> disabled = new List<InputAction>(); private WindowsHandler windows; private PlayerMainController player; private bool markerSet; private bool cursorWasLocked; public bool Active { get; private set; } public PlayerMainController Player => player; public static bool Available { get { if (OpenedUi != null) { return OpenedUi.FieldType == typeof(UiType); } return false; } } public InputHold(ManualLogSource log) { this.log = log; } public bool Begin(PlayerMainController who) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Invalid comparison between Unknown and I4 if (Active) { return true; } WindowsHandler val = InputHold.SafeManager<WindowsHandler>(); if ((Object)(object)val == (Object)null || (Object)(object)who == (Object)null || !Available) { if (!Available) { log.LogWarning((object)"Input hold unavailable: WindowsHandler._openedUi not found in this build."); } return false; } windows = val; player = who; try { cursorWasLocked = (int)Cursor.lockState == 1; OpenedUi.SetValue(windows, (object)(UiType)12); markerSet = true; Active = true; Keep(); SetCursorLocked(locked: false); } catch (Exception ex) { log.LogWarning((object)("Input hold could not start (" + ex.GetType().Name + "); undone.")); if (Active) { End("the hold could not start"); } windows = null; player = null; return false; } log.LogInfo((object)("Input held: " + disabled.Count + " game actions off.")); return true; } public unsafe string Check() { //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Invalid comparison between Unknown and I4 if (!Active) { return null; } WindowsHandler val = InputHold.SafeManager<WindowsHandler>(); if ((Object)(object)val == (Object)null || (Object)(object)val != (Object)(object)windows || (Object)(object)player == (Object)null || !Object.op_Implicit((Object)(object)player)) { return "the world changed"; } UiType openedUi; try { openedUi = val.GetOpenedUi(); } catch (Exception) { return "the window handler went away"; } if ((int)openedUi != 12) { markerSet = false; return "a game window opened (" + ((object)(*(UiType*)(&openedUi))/*cast due to .constrained prefix*/).ToString() + ")"; } Keep(); return null; } private void Keep() { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: 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_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) foreach (InputActionAsset item in GameInputAssets()) { Enumerator<InputActionMap> enumerator2 = item.actionMaps.GetEnumerator(); try { while (enumerator2.MoveNext()) { Enumerator<InputAction> enumerator3 = enumerator2.Current.actions.GetEnumerator(); try { while (enumerator3.MoveNext()) { InputAction current = enumerator3.Current; if (current.enabled) { current.Disable(); if (!disabled.Contains(current)) { disabled.Add(current); } } } } finally { ((IDisposable)enumerator3/*cast due to .constrained prefix*/).Dispose(); } } } finally { ((IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose(); } } } private IEnumerable<InputActionAsset> GameInputAssets() { List<InputActionAsset> list = new List<InputActionAsset>(); try { PlayerInputDispatcher val = (((Object)(object)player != (Object)null) ? ((Component)player).GetComponent<PlayerInputDispatcher>() : null); if ((Object)(object)val != (Object)null && (Object)(object)val.inputMap != (Object)null) { list.Add(val.inputMap); } WindowsGamepadHandler val2 = InputHold.SafeManager<WindowsGamepadHandler>(); if ((Object)(object)val2 != (Object)null && (Object)(object)val2.InputMap != (Object)null && !list.Contains(val2.InputMap)) { list.Add(val2.InputMap); } } catch (Exception ex) { log.LogWarning((object)("Game input lookup failed: " + ex.GetType().Name)); } return list; } public void End(string why) { //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Invalid comparison between Unknown and I4 if (!Active) { return; } Active = false; HashSet<InputAction> hashSet = GameWindowActions(); try { if (markerSet && (Object)(object)windows != (Object)null && Object.op_Implicit((Object)(object)windows) && (int)windows.GetOpenedUi() == 12) { OpenedUi.SetValue(windows, (object)(UiType)0); } } catch (Exception ex) { log.LogWarning((object)("Input hold marker cleanup: " + ex.GetType().Name)); } markerSet = false; int num = 0; int num2 = 0; foreach (InputAction item in disabled) { if (hashSet.Contains(item)) { num2++; continue; } try { item.Enable(); num++; } catch (Exception ex2) { log.LogWarning((object)("Could not switch a game key back on: " + ex2.GetType().Name)); } } if (num2 > 0) { log.LogInfo((object)("Input: " + num2 + " game actions left to the game's open window.")); } disabled.Clear(); try { bool flag = (Object)(object)windows != (Object)null && Object.op_Implicit((Object)(object)windows) && windows.GetHasUiOpen(); if (cursorWasLocked && !flag) { SetCursorLocked(locked: true); } } catch (Exception ex3) { log.LogWarning((object)("Input hold cursor restore: " + ex3.GetType().Name)); } windows = null; player = null; GUIUtility.keyboardControl = 0; log.LogInfo((object)("Input released (" + why + "); " + num + " game actions back on.")); } private HashSet<InputAction> GameWindowActions() { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Invalid comparison between Unknown and I4 //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) HashSet<InputAction> hashSet = new HashSet<InputAction>(); try { if ((Object)(object)windows == (Object)null || !Object.op_Implicit((Object)(object)windows)) { return hashSet; } UiType openedUi = windows.GetOpenedUi(); if ((int)openedUi == 0 || (int)openedUi == 12) { return hashSet; } WindowsGamepadHandler val = InputHold.SafeManager<WindowsGamepadHandler>(); if ((Object)(object)val == (Object)null || (Object)(object)val.InputMap == (Object)null) { return hashSet; } ReadOnlyArray<InputActionMap> actionMaps = val.InputMap.actionMaps; for (int i = 0; i < actionMaps.Count && i < 2; i++) { Enumerator<InputAction> enumerator = actionMaps[i].actions.GetEnumerator(); try { while (enumerator.MoveNext()) { InputAction current = enumerator.Current; hashSet.Add(current); } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } } } catch (Exception ex) { log.LogWarning((object)("Game window input lookup failed: " + ex.GetType().Name)); } return hashSet; } private static void SetCursorLocked(bool locked) { try { CursorStateManager.SetLockCursorStatus(locked); } catch (Exception) { Cursor.lockState = (CursorLockMode)(locked ? 1 : 0); Cursor.visible = !locked; } } public static T SafeManager<T>() where T : MonoBehaviour { try { T manager = Managers.GetManager<T>(); return ((Object)(object)manager != (Object)null && Object.op_Implicit((Object)(object)manager)) ? manager : default(T); } catch (Exception) { return default(T); } } } internal sealed class GameBinding { public string Map = ""; public string Action = ""; public string Path = ""; } internal sealed class Clash { public string Ours = ""; public string With = ""; public string Path = ""; public bool Game; } internal static class KeyCheck { public const string PlayMap = "PlayerMovable"; public static string Norm(string path) { return (path ?? "").Trim().Replace(" ", "").ToLowerInvariant(); } public static bool Empty(string path) { return Norm(path).Length == 0; } public static bool Overlap(string a, string b) { a = Norm(a); b = Norm(b); if (a.Length == 0 || b.Length == 0 || a.IndexOf('{') >= 0 || b.IndexOf('{') >= 0 || a.IndexOf('/') < 0 || b.IndexOf('/') < 0) { return false; } if (a == b || b.StartsWith(a + "/", StringComparison.Ordinal) || a.StartsWith(b + "/", StringComparison.Ordinal)) { return true; } string text = a.Substring(a.IndexOf('/')); string text2 = b.Substring(b.IndexOf('/')); if (IsPad(a) && IsPad(b)) { if (!(text == text2) && !text2.StartsWith(text + "/", StringComparison.Ordinal)) { return text.StartsWith(text2 + "/", StringComparison.Ordinal); } return true; } return false; } public static bool IsPad(string path) { string text = Norm(path); if (!text.StartsWith("<gamepad>", StringComparison.Ordinal) && !text.StartsWith("<xinputcontroller>", StringComparison.Ordinal) && !text.StartsWith("<dualshockgamepad>", StringComparison.Ordinal) && !text.StartsWith("<dualsensegamepad>", StringComparison.Ordinal)) { return text.StartsWith("<switchprocontrollerhid>", StringComparison.Ordinal); } return true; } public static List<Clash> Find(IList<KeyValuePair<string, string>> ours, IList<GameBinding> game) { List<Clash> list = new List<Clash>(); for (int i = 0; i < ours.Count; i++) { if (Empty(ours[i].Value)) { continue; } for (int j = i + 1; j < ours.Count; j++) { if (Overlap(ours[i].Value, ours[j].Value)) { list.Add(new Clash { Ours = ours[i].Key, With = ours[j].Key, Path = ours[i].Value }); list.Add(new Clash { Ours = ours[j].Key, With = ours[i].Key, Path = ours[j].Value }); } } if (game == null) { continue; } HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal); foreach (GameBinding item in game) { if (item.Map == "PlayerMovable" && Overlap(ours[i].Value, item.Path) && hashSet.Add(item.Action)) { list.Add(new Clash { Ours = ours[i].Key, With = item.Action, Path = item.Path, Game = true }); } } } return list; } public static Clash Refuse(string action, string path, IList<KeyValuePair<string, string>> ours, IList<GameBinding> game) { if (Empty(path)) { return null; } List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>(action, path) }; foreach (KeyValuePair<string, string> our in ours) { if (our.Key != action) { list.Add(our); } } Clash clash = null; foreach (Clash item in Find(list, game)) { if (!(item.Ours != action)) { if (!item.Game) { return item; } if (clash == null) { clash = item; } } } return clash; } public static string Words(string action) { if (string.IsNullOrEmpty(action)) { return ""; } StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < action.Length; i++) { char c = action[i]; if (i > 0 && char.IsUpper(c) && !char.IsUpper(action[i - 1])) { stringBuilder.Append(' ').Append(char.ToLowerInvariant(c)); } else { stringBuilder.Append(c); } } return stringBuilder.ToString(); } public static string Label(string path, bool playStation = false) { string text = Norm(path); if (text.Length == 0) { return L.T("key.none"); } int num = text.IndexOf('/'); string text2 = ((num >= 0) ? text.Substring(num + 1) : text); if (IsPad(text)) { switch (text2) { case "buttonsouth": if (!playStation) { return "A"; } return "Cross"; case "buttoneast": if (!playStation) { return "B"; } return "Circle"; case "buttonwest": if (!playStation) { return "X"; } return "Square"; case "buttonnorth": if (!playStation) { return "Y"; } return "Triangle"; case "leftshoulder": if (!playStation) { return "LB"; } return "L1"; case "rightshoulder": if (!playStation) { return "RB"; } return "R1"; case "lefttrigger": if (!playStation) { return "LT"; } return "L2"; case "righttrigger": if (!playStation) { return "RT"; } return "R2"; case "leftstickpress": if (!playStation) { return "LS"; } return "L3"; case "rightstickpress": if (!playStation) { return "RS"; } return "R3"; case "select": if (!playStation) { return "View"; } return "Share"; case "start": if (!playStation) { return "Menu"; } return "Options"; case "dpad/up": return L.T("key.dpadUp"); case "dpad/down": return L.T("key.dpadDown"); case "dpad/left": return L.T("key.dpadLeft"); case "dpad/right": return L.T("key.dpadRight"); default: return text2; } } switch (text2) { case "escape": return "Esc"; case "enter": return "Enter"; case "numpadenter": return "Num Enter"; case "backquote": return "`"; case "space": return L.T("key.space"); case "tab": return "Tab"; case "backspace": return "Backspace"; case "shift": case "leftshift": return "Shift"; case "leftctrl": case "ctrl": return "Ctrl"; case "alt": case "leftalt": return "Alt"; case "pageup": return "Page Up"; case "pagedown": return "Page Down"; case "insert": return "Insert"; case "delete": return "Delete"; case "home": return "Home"; case "end": return "End"; default: if (text2.StartsWith("numpad", StringComparison.Ordinal) && text2.Length == 7) { return "Num " + text2.Substring(6); } if (text2.StartsWith("digit", StringComparison.Ordinal) && text2.Length == 6) { return text2.Substring(5); } return text2.ToUpperInvariant(); } } } internal static class LandingGeometry { public static bool TryPivotY(float floor, float normalY, float height, float radius, float centerOffsetY, float skin, out float pivot) { pivot = 0f; if (!Finite(floor) || !Finite(normalY) || !Finite(height) || !Finite(radius) || !Finite(centerOffsetY) || !Finite(skin) || normalY <= 0f || normalY > 1.001f || radius <= 0f || height < radius * 2f || skin < 0f) { return false; } float num = radius / normalY - radius; pivot = floor + height / 2f - centerOffsetY + num + Math.Max(skin, 0.03f); return Finite(pivot); } private static bool Finite(float value) { if (!float.IsNaN(value)) { return !float.IsInfinity(value); } return false; } } internal sealed class Library { public enum Bulk { Found, Recent, Saved } private readonly PlaceFile file; private readonly Backups backups; private readonly Action<string> log; private readonly Func<DateTime> now; private PlaceStore store; private string loadNote; private string blocked; private string boundSave; private uint boundSeed; private Func<string, bool> boundExists; public readonly Prefs Prefs; public readonly string DataDir; public readonly string ExportsDir; public string PlacesPath { get; } public string BackupsDir => backups.Folder; public PlaceStore Store { get { Ensure(); return store; } } public string CurrentSave => Store.Current; public Library(string placesPath, string dataDir, Prefs prefs, Action<string> log, Func<DateTime> now = null) { this.log = log ?? ((Action<string>)delegate { }); this.now = now ?? ((Func<DateTime>)(() => DateTime.Now)); file = new PlaceFile(placesPath, this.log); DataDir = dataDir; ExportsDir = Path.Combine(dataDir, "exports"); backups = new Backups(Path.Combine(dataDir, "backups"), this.now); Prefs = prefs ?? new Prefs(); PlacesPath = placesPath; } private void Ensure() { if (store != null) { return; } store = file.Load(); loadNote = file.Note; if (file.LastText != null && store.ReadVersion < 4) { string path; string text = backups.Take(file.LastText, "before-migration", out path); if (text != null) { blocked = L.T("lib.migrationBackupFailed", text); loadNote = ((loadNote != null) ? (loadNote + " ") : "") + blocked; log("Migration backup failed (" + text + "): nothing will be written this session."); } else { log("Places file v" + store.ReadVersion + " backed up before its first v" + 4 + " write: " + Path.GetFileName(path)); } } } public string TakeLoadNote() { Ensure(); string result = loadNote; loadNote = null; return result; } public string Save() { Ensure(); if (blocked != null) { return blocked; } return file.Save(store); } public string Bind(string save, uint seed, Func<string, bool> exists, out string saveFailed) { Ensure(); saveFailed = null; boundSave = save; boundSeed = seed; boundExists = exists; string text = store.Use(save, seed, exists); if (text != null) { saveFailed = Save(); } return text; } public Removed Delete(string world, Place place, out string saveFailed) { Removed removed = Store.Delete(world, place); saveFailed = ((removed != null) ? Save() : null); return removed; } public bool Undo(Removed removed, out string saveFailed) { bool flag = Store.Undo(removed); saveFailed = (flag ? Save() : null); return flag; } public int CountOf(Bulk what, string world) { PlanetPlaces planetPlaces = Store.For(world); return what switch { Bulk.Recent => planetPlaces.Recent.Count, Bulk.Found => planetPlaces.Visited.Count, _ => planetPlaces.Saved.Count, }; } public string Clear(Bulk what, string world, out int cleared) { cleared = 0; if (CountOf(what, world) == 0) { return null; } string text = Backup("before-clear-" + what.ToString().ToLowerInvariant()); if (text != null) { return text; } cleared = what switch { Bulk.Recent => store.ClearRecent(world), Bulk.Found => store.ClearFound(world), _ => store.ClearSaved(world), }; return Save(); } private string Backup(string reason) { Ensure(); string path; string text = backups.Take(store.ToJson(), reason, out path); if (text != null) { return L.T("lib.backupFailed", text); } return null; } public List<BackupInfo> ListBackups() { return backups.List(); } public string Restore(BackupInfo backup, out string summary) { summary = null; PlaceStore placeStore; try { placeStore = PlaceStore.FromJson(File.ReadAllText(backup.Path)); } catch (Exception ex) { log("Backup unreadable (" + ex.GetType().Name + ")."); return L.T("lib.backupUnreadable"); } if (placeStore.ReadVersion > 4) { return L.T("lib.backupNewer"); } string text = Backup("before-restore"); if (text != null) { return text; } store = placeStore; if (boundSave != null) { store.Use(boundSave, boundSeed, boundExists); } summary = Summary(store); return Save(); } public static string Summary(PlaceStore s) { int num = 0; int num2 = 0; int num3 = 0; foreach (string saveName in s.SaveNames) { SaveData saveData = s.SaveOf(saveName); if (saveData == null || saveData.Empty) { continue; } num++; foreach (PlanetPlaces value in saveData.Planets.Values) { num2 += value.Saved.Count; num3 += value.Visited.Count; } } return L.T("lib.summary", num, num2, num3); } public string Export(string modVersion, bool withSettings, out string path) { path = null; Ensure(); try { Directory.CreateDirectory(ExportsDir); string text = "GamesOMG-Teleport-PlanetCrafter-" + now().ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture); path = Path.Combine(ExportsDir, text + ".json"); int num = 2; while (File.Exists(path)) { path = Path.Combine(ExportsDir, text + "-" + num + ".json"); num++; } File.WriteAllText(path, Transfer.Export(store, modVersion, now().ToUniversalTime(), withSettings ? Prefs.Snapshot() : null)); return null; } catch (Exception ex) { log("Export not written: " + ex.GetType().Name); path = null; return L.T("lib.exportFailed", ex.GetType().Name); } } public List<string> ImportCandidates() { List<string> list = new List<string>(); try { if (Directory.Exists(ExportsDir)) { list.AddRange(Directory.GetFiles(ExportsDir, "*.json")); } list.Sort((string a, string b) => File.GetLastWriteTimeUtc(b).CompareTo(File.GetLastWriteTimeUtc(a))); } catch (Exception ex) { log("Exports folder unreadable: " + ex.GetType().Name); } return list; } public ExportFile ReadImport(string path) { string json; try { json = File.ReadAllText(path); } catch (Exception) { throw new FormatException(L.T("xfer.cantOpen")); } return Transfer.Read(json); } public ImportPlan Preview(ExportFile from, string sourceSave, string destSave) { return Transfer.Plan(from, sourceSave, Store, destSave); } public string Import(ImportPlan plan, bool replace, ExportFile from, bool applySettings, out int settingsChanged) { settingsChanged = 0; string text = Backup(replace ? "before-import-replace" : "before-import"); if (text != null) { return text; } Transfer.Apply(plan, store, replace); if (applySettings && from?.Settings != null) { settingsChanged = Prefs.Apply(from.Settings); } return Save(); } public int ResetPrefs(string section) { return Prefs.Reset(section); } } internal static class MiniJson { public static object Parse(string text) { int i = 0; object result = Value(text, ref i, 0); Space(text, ref i); if (i != text.Length) { throw new FormatException("trailing text at " + i); } return result; } private static void Space(string s, ref int i) { while (i < s.Length && (s[i] == ' ' || s[i] == '\t' || s[i] == '\n' || s[i] == '\r')) { i++; } } private static object Value(string s, ref int i, int depth) { if (depth > 64) { throw new FormatException("nested too deep"); } Space(s, ref i); if (i >= s.Length) { throw new FormatException("unexpected end"); } char c = s[i]; switch (c) { case '{': { Dictionary<string, object> dictionary = new Dictionary<string, object>(StringComparer.Ordinal); i++; Space(s, ref i); if (i < s.Length && s[i] == '}') { i++; return dictionary; } while (true) { Space(s, ref i); if (i >= s.Length || s[i] != '"') { throw new FormatException("expected a key at " + i); } string key = Str(s, ref i); Space(s, ref i); if (i >= s.Length || s[i] != ':') { throw new FormatException("expected : at " + i); } i++; dictionary[key] = Value(s, ref i, depth + 1); Space(s, ref i); if (i >= s.Length || s[i] != ',') { break; } i++; } if (i < s.Length && s[i] == '}') { i++; return dictionary; } throw new FormatException("expected , or } at " + i); } case '[': { List<object> list = new List<object>(); i++; Space(s, ref i); if (i < s.Length && s[i] == ']') { i++; return list; } while (true) { list.Add(Value(s, ref i, depth + 1)); Space(s, ref i); if (i >= s.Length || s[i] != ',') { break; } i++; } if (i < s.Length && s[i] == ']') { i++; return list; } throw new FormatException("expected , or ] at " + i); } case '"': return Str(s, ref i); default: { if (Word(s, ref i, "true")) { return true; } if (Word(s, ref i, "false")) { return false; } if (Word(s, ref i, "null")) { return null; } int num = i; while (i < s.Length && "+-0123456789.eE".IndexOf(s[i]) >= 0) { i++; } if (num == i) { throw new FormatException("unexpected '" + c + "' at " + i); } if (!double.TryParse(s.Substring(num, i - num), NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { throw new FormatException("bad number at " + num); } return result; } } } private static bool Word(string s, ref int i, string word) { if (string.CompareOrdinal(s, i, word, 0, word.Length) != 0) { return false; } i += word.Length; return true; } private static string Str(string s, ref int i) { StringBuilder stringBuilder = new StringBuilder(); i++; while (i < s.Length) { char c = s[i++]; switch (c) { case '"': return stringBuilder.ToString(); default: stringBuilder.Append(c); continue; case '\\': break; } if (i >= s.Length) { break; } char c2 = s[i++]; switch (c2) { case '"': stringBuilder.Append('"'); break; case '\\': stringBuilder.Append('\\'); break; case '/': stringBuilder.Append('/'); break; case 'b': stringBuilder.Append('\b'); break; case 'f': stringBuilder.Append('\f'); break; case 'n': stringBuilder.Append('\n'); break; case 'r': stringBuilder.Append('\r'); break; case 't': stringBuilder.Append('\t'); break; case 'u': if (i + 4 > s.Length) { throw new FormatException("bad \\u escape"); } stringBuilder.Append((char)int.Parse(s.Substring(i, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture)); i += 4; break; default: throw new FormatException("bad escape \\" + c2); } } throw new FormatException("unterminated string"); } public static string Write(object value) { return Write(value, 2); } public static string Write(object value, int decimals) { StringBuilder stringBuilder = new StringBuilder(); Write(stringBuilder, value, decimals); return stringBuilder.ToString(); } private static void Write(StringBuilder b, object v, int decimals) { if (v != null) { if (!(v is string s)) { if (!(v is bool flag)) { if (!(v is double d)) { if (!(v is float num)) { if (!(v is int num2)) { if (!(v is long num3)) { if (!(v is IDictionary<string, object> dictionary)) { if (v is IEnumerable enumerable) { b.Append('['); bool flag2 = true; foreach (object item in enumerable) { if (!flag2) { b.Append(','); } flag2 = false; Write(b, item, decimals); } b.Append(']'); return; } throw new ArgumentException("cannot write " + v.GetType().Name); } b.Append('{'); bool flag3 = true; foreach (KeyValuePair<string, object> item2 in dictionary) { if (!flag3) { b.Append(','); } flag3 = false; Quote(b, item2.Key); b.Append(':'); Write(b, item2.Value, decimals); } b.Append('}'); } else { b.Append(num3.ToString(CultureInfo.InvariantCulture)); } } else { b.Append(num2.ToString(CultureInfo.InvariantCulture)); } } else { b.Append(Num(num, decimals)); } } else { b.Append(Num(d, decimals)); } } else { b.Append(flag ? "true" : "false"); } } else { Quote(b, s); } } else { b.Append("null"); } } private static string Num(double d, int decimals) { if (double.IsNaN(d) || double.IsInfinity(d)) { return "null"; } return Math.Round(d, decimals).ToString("0." + new string('#', Math.Max(1, decimals)), CultureInfo.InvariantCulture); } private static void Quote(StringBuilder b, string s) { b.Append('"'); foreach (char c in s) { if (c == '"') { b.Append("\\\""); } else if (c == '\\') { b.Append("\\\\"); } else if (c < ' ') { StringBuilder stringBuilder = b.Append("\\u"); int num = c; stringBuilder.Append(num.ToString("x4", CultureInfo.InvariantCulture)); } else { b.Append(c); } } b.Append('"'); } public static string S(object o, string fallback = "") { return (o as string) ?? fallback; } public static double N(object o, double fallback = double.NaN) { if (o is double) { return (double)o; } return fallback; } public static List<object> A(object o) { return o as List<object>; } public static Dictionary<string, object> O(object o) { return o as Dictionary<string, object>; } public static object Get(Dictionary<string, object> o, string key) { if (o == null || !o.TryGetValue(key, out var value)) { return null; } return value; } } internal sealed class Nav { private readonly List<string> order = new List<string>(); private readonly List<string> building = new List<string>(); private readonly Dictionary<string, float[]> rects = new Dictionary<string, float[]>(StringComparer.Ordinal); private readonly Stack<string> saved = new Stack<string>(); private int lastIndex; public bool Visible; public bool Moved; public string Focus { get; private set; } = ""; public IReadOnlyList<string> Order => order; public void Begin() { building.Clear(); } public void Add(string id) { if (!string.IsNullOrEmpty(id) && !building.Contains(id)) { building.Add(id); } } public void End() { order.Clear(); order.AddRange(building); if (order.Count == 0) { Focus = ""; return; } int num = order.IndexOf(Focus); if (num < 0) { Focus = order[Math.Min(Math.Max(lastIndex, 0), order.Count - 1)]; num = order.IndexOf(Focus); } lastIndex = num; } public bool Is(string id) { return Focus == id; } public void Set(string id, bool byKey = false) { if (!string.IsNullOrEmpty(id)) { Focus = id; int num = order.IndexOf(id); if (num >= 0) { lastIndex = num; } if (byKey) { Visible = true; Moved = true; } } } public void Move(int step) { if (order.Count != 0) { int num = order.IndexOf(Focus); if (num < 0) { num = Math.Min(Math.Max(lastIndex, 0), order.Count - 1); } else if (Visible) { num = Math.Min(Math.Max(num + step, 0), order.Count - 1); } Set(order[num], byKey: true); } } public void First() { if (order.Count > 0) { Set(order[0], byKey: true); } } public void Last() { if (order.Count > 0) { Set(order[order.Count - 1], byKey: true); } } public void NextArea(int step, Func<string, string> areaOf) { if (order.Count == 0) { return; } int num = Math.Max(order.IndexOf(Focus), 0); string text = areaOf(order[num]); for (int i = num + step; i >= 0 && i < order.Count; i += step) { if (areaOf(order[i]) != text) { Set(order[i], byKey: true); return; } } Set(order[(step <= 0) ? (order.Count - 1) : 0], byKey: true); } public void Push(string focusInDialog) { saved.Push(Focus); Focus = focusInDialog ?? ""; } public void Pop() { if (saved.Count != 0) { Focus = saved.Pop(); Moved = Visible; } } public void Place(string id, float y, float height) { rects[id] = new float[2] { y, height }; } public void ClearPlaces() { rects.Clear(); } public float ScrollFor(float scroll, float viewHeight, float margin = 0f) { if (!rects.TryGetValue(Focus, out var value)) { return scroll; } float num = value[0] - margin; float num2 = value[0] + value[1] + margin; if (num < scroll) { return Math.Max(0f, num); } if (num2 > scroll + viewHeight) { return Math.Max(0f, num2 - viewHeight); } return scroll; } } internal enum Cmd { None, Up, Down, Left, Right, PageUp, PageDown, Home, End, Next, Prev, Activate, Back, TabLeft, TabRight, SaveHere, Actions } internal sealed class PadInput { private const float Delay = 0.38f; private const float Rate = 0.085f; private const float Dead = 0.55f; private int heldDir; private float nextRepeat; private Vector2 lastMouse; public bool UsingPad { get; private set; } public bool PlayStation { get; private set; } public Cmd Read(bool textFocused) { //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_0242: Unknown result type (might be due to invalid IL or missing references) //IL_0247: Unknown result type (might be due to invalid IL or missing references) //IL_025b: Unknown result type (might be due to invalid IL or missing references) //IL_027f: Unknown result type (might be due to invalid IL or missing references) //IL_02a3: Unknown result type (might be due to invalid IL or missing references) //IL_02c7: Unknown result type (might be due to invalid IL or missing references) Keyboard current = Keyboard.current; Gamepad current2 = Gamepad.current; Mouse current3 = Mouse.current; Vector2 val; if (current2 != null && AnyPad(current2)) { UsingPad = true; string text = ((InputControl)current2).layout ?? ""; PlayStation = text.Contains("DualShock") || text.Contains("DualSense"); } else if (current != null && ((ButtonControl)current.anyKey).wasPressedThisFrame) { UsingPad = false; } else if (current3 != null) { val = ((InputControl<Vector2>)(object)((Pointer)current3).position).ReadValue(); if (!current3.leftButton.wasPressedThisFrame) { Vector2 val2 = val - lastMouse; if (!(((Vector2)(ref val2)).sqrMagnitude > 64f)) { goto IL_00b4; } } UsingPad = false; goto IL_00b4; } goto IL_00bc; IL_00b4: lastMouse = val; goto IL_00bc; IL_00bc: if (current != null) { bool isPressed = current.shiftKey.isPressed; if (((ButtonControl)current.escapeKey).wasPressedThisFrame) { return Cmd.Back; } if (((ButtonControl)current.enterKey).wasPressedThisFrame || ((ButtonControl)current.numpadEnterKey).wasPressedThisFrame) { return Cmd.Activate; } if (((ButtonControl)current.tabKey).wasPressedThisFrame) { if (!isPressed) { return Cmd.Next; } return Cmd.Prev; } if (((ButtonControl)current.pageUpKey).wasPressedThisFrame) { return Cmd.PageUp; } if (((ButtonControl)current.pageDownKey).wasPressedThisFrame) { return Cmd.PageDown; } if (!textFocused) { if (((ButtonControl)current.homeKey).wasPressedThisFrame) { return Cmd.Home; } if (((ButtonControl)current.endKey).wasPressedThisFrame) { return Cmd.End; } if (((ButtonControl)current.spaceKey).wasPressedThisFrame) { return Cmd.Activate; } } } if (current2 != null) { if (current2.buttonSouth.wasPressedThisFrame) { return Cmd.Activate; } if (current2.buttonEast.wasPressedThisFrame) { return Cmd.Back; } if (current2.leftShoulder.wasPressedThisFrame) { return Cmd.TabLeft; } if (current2.rightShoulder.wasPressedThisFrame) { return Cmd.TabRight; } if (current2.buttonWest.wasPressedThisFrame) { return Cmd.SaveHere; } if (current2.buttonNorth.wasPressedThisFrame) { return Cmd.Actions; } if (current2.leftTrigger.wasPressedThisFrame) { return Cmd.PageUp; } if (current2.rightTrigger.wasPressedThisFrame) { return Cmd.PageDown; } } int num = 0; if (current != null) { if (((ButtonControl)current.upArrowKey).isPressed) { num = 1; } else if (((ButtonControl)current.downArrowKey).isPressed) { num = 2; } else if (!textFocused && ((ButtonControl)current.leftArrowKey).isPressed) { num = 3; } else if (!textFocused && ((ButtonControl)current.rightArrowKey).isPressed) { num = 4; } } if (num == 0 && current2 != null) { Vector2 val3 = ((InputControl<Vector2>)(object)current2.leftStick).ReadValue(); if (current2.dpad.up.isPressed || val3.y > 0.55f) { num = 1; } else if (current2.dpad.down.isPressed || val3.y < -0.55f) { num = 2; } else if (current2.dpad.left.isPressed || val3.x < -0.55f) { num = 3; } else if (current2.dpad.right.isPressed || val3.x > 0.55f) { num = 4; } } if (num == 0) { heldDir = 0; return Cmd.None; } float unscaledTime = Time.unscaledTime; if (num != heldDir) { heldDir = num; nextRepeat = unscaledTime + 0.38f; return (Cmd)num; } if (unscaledTime >= nextRepeat) { nextRepeat = unscaledTime + 0.085f; return (Cmd)num; } return Cmd.None; } private static bool AnyPad(Gamepad pad) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) Enumerator<InputControl> enumerator = ((InputDevice)pad).allControls.GetEnumerator(); try { while (enumerator.MoveNext()) { InputControl current = enumerator.Current; ButtonControl val = (ButtonControl)(object)((current is ButtonControl) ? current : null); if (val != null && val.wasPressedThisFrame) { return true; } } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } Vector2 val2 = ((InputControl<Vector2>)(object)pad.leftStick).ReadValue(); Vector2 val3 = ((InputControl<Vector2>)(object)pad.rightStick).ReadValue(); if (!(((Vector2)(ref val2)).sqrMagnitude > 0.3025f)) { return ((Vector2)(ref val3)).sqrMagnitude > 0.3025f; } return true; } public static string Captured(out bool cancelled) { //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) cancelled = false; Keyboard current = Keyboard.current; if (current != null && ((ButtonControl)current.escapeKey).wasPressedThisFrame) { cancelled = true; return null; } if (current != null && ((ButtonControl)current.anyKey).wasPressedThisFrame) { Enumerator<KeyControl> enumerator = current.allKeys.GetEnumerator(); try { while (enumerator.MoveNext()) { KeyControl current2 = enumerator.Current; if (current2 != null && ((ButtonControl)current2).wasPressedThisFrame && current2 != current.escapeKey && current2 != current.enterKey && current2 != current.numpadEnterKey) { return "<Keyboard>/" + ((InputControl)current2).name; } } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } } Gamepad current3 = Gamepad.current; if (current3 != null) { Enumerator<InputControl> enumerator2 = ((InputDevice)current3).allControls.GetEnumerator(); try { while (enumerator2.MoveNext()) { InputControl current4 = enumerator2.Current; ButtonControl val = (ButtonControl)(object)((current4 is ButtonControl) ? current4 : null); if (val != null && val.wasPressedThisFrame) { string text = current4.path.Substring(((InputControl)current3).path.Length).TrimStart('/'); if (!(text == "dpad") && !text.StartsWith("leftStick/") && !text.StartsWith("rightStick/")) { return "<Gamepad>/" + text; } } } } finally { ((IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose(); } } return null; } } internal interface IPanelHost { bool Busy { get; } Look Look { get; } string Version { get; } void Go(TeleportRequest request, string label); void GoBack(); string Binding(string action); string SetBinding(string action, string path); List<GameBinding> GameBindings(); string Diagnostics(); void Sound(bool ok); void ReplayFirstRun(); List<string> GameSaves(); void Opened(string why); } internal sealed class Look { public Func<int> TextSize; public Func<int> Opacity; public Func<bool> Left; public Func<bool> Compact; public Func<bool> ReducedMotion; public Func<bool> QuickTeleport; public Func<bool> CloseAfter; public Func<bool> Sounds; public Action<string, string> Set; } internal sealed class Panel { public enum Tab { Mine, Places } private enum View { Places, Settings } private enum Section { Controls, Appearance, Behaviour, Data, Help } private enum Dlg { None, Paste, Rename, Confirm, ImportList, ImportPreview, Backups, Capture } private sealed class ActionButton { public readonly string Id; public readonly string Label; public readonly Icon Icon; public readonly Action Act; public readonly bool Enabled; public ActionButton(string id, string label, Icon icon, Action act, bool enabled = true) { Id = id; Label = label; Icon = icon; Act = act; Enabled = enabled; } } public const string ActPlaces = "Places"; public const string ActTeleport = "Teleport"; public const string ActReturn = "Return"; public const string ActPadPlaces = "PadPlaces"; public const string ActPadReturn = "PadReturn"; public static readonly string[] Actions = new string[5] { "Places", "Teleport", "Return", "PadPlaces", "PadReturn" }; public const string MapUrl = "https://gamesomg.com/planet-crafter-map/"; private readonly ManualLogSource log; private readonly InputHold hold; private readonly IPanelHost host; private readonly Theme theme; private readonly Nav nav = new Nav(); private readonly PadInput input = new PadInput(); public readonly Library Lib; private string world = ""; private string planetName = ""; private Tab tab; private View view; private Section section; private Dlg dlg; private Vector2 scroll; private Vector2 setScroll; private Vector2 dlgScroll; private float listViewHeight = 300f; private float setViewHeight = 300f; private float slide; private Action pending; private readonly Dictionary<string, Action> acts = new Dictionary<string, Action>(StringComparer.Ordinal); private readonly Dictionary<string, Action> lefts = new Dictionary<string, Action>(StringComparer.Ordinal); private readonly Dictionary<string, Action> rights = new Dictionary<string, Action>(StringComparer.Ordinal); private bool layoutPass; private bool inScroll; private float innerWidth = 380f; private string focusField; private string focusedNow = ""; private string lastClickId; private float lastClickAt; private Place selPlace; private Poi selPoi; private string status; private bool statusBad; private bool statusShown; private float statusUntil; private Removed undo; private Action undoLook; private string search = ""; private string rename = ""; private string paste = ""; private string pasteWhy; private string searchUsed = ""; private string confirmTitle; private string confirmBody; private string confirmYes; private Action confirmAct; private bool confirmDanger; private string captureFor; private float captureUntil; private List<string> importFiles = new List<string>(); private ExportFile importFile; private string importPath; private List<string> srcSaves = new List<string>(); private List<string> dstSaves = new List<string>(); private int srcAt; private int dstAt; private ImportPlan plan; private bool importSettings; private bool exportSettings; private List<BackupInfo> backupList = new List<BackupInfo>(); private readonly Dictionary<string, PoiWorld> pois = new Dictionary<string, PoiWorld>(StringComparer.Ordinal); private readonly Dictionary<string, PlacesTree> trees = new Dictionary<string, PlacesTree>(StringComparer.Ordinal); private bool hideFound; private bool byName; private List<TreeRow> rows = new List<TreeRow>(); private FoundSet foundSet; private bool foundTried; private string noteRow; private object noteItem; private string noteText = ""; private bool dropFocus; private readonly Dictionary<string, object> rowItems = new Dictionary<string, object>(StringComparer.Ordinal); internal readonly Dictionary<string, Rect> Drawn = new Dictionary<string, Rect>(StringComparer.Ordinal); public bool Open { get; private set; } public PlaceStore Store => Lib.Store; public bool UsingPad => input.UsingPad; public bool PlayStation => input.PlayStation; public Theme Theme => theme; private bool HasSelection { get { if (selPlace == null) { return selPoi != null; } return true; } } private string SaveLabel { get { if (Store.Current.Length != 0) { if (!Store.Current.StartsWith("co-op ", StringComparison.Ordinal)) { return Store.Current; } return L.T("save.coop"); } return L.T("save.unknown"); } } public Panel(ManualLogSource log, Library lib, IPanelHost host, string cacheDir) { this.log = log; Lib = lib; this.host = host; theme = new Theme(cacheDir, delegate(string line) { log.LogInfo((object)line); }); hold = new InputHold(log); } public string TakeLoadNote() { return Lib.TakeLoadNote(); } public bool SaveStore() { string text = Lib.Save(); if (text == null) { return true; } Say(text, bad: true); if (!Open) { host.Sound(ok: false); } return false; } public bool Show(PlayerMainController player, PlanetData planet, string prefill, string note, bool noteBad) { if (Lib.Store == null || !hold.Begin(player)) { return false; } Open = true; slide = (host.Look.ReducedMotion() ? 1 : 0); planetName = planet.id; world = PlaceStore.WorldOf(planet.id); if (selPoi != null) { PoiWorld poiWorld = PoisFor(world); if (poiWorld == null || !poiWorld.ById.ContainsKey(selPoi.Id)) { selPoi = null; } } if (selPlace != null && !Store.For(world).Saved.Contains(selPlace) && !Store.For(world).Recent.Contains(selPlace)) { selPlace = null; } if (prefill != null) { paste = prefill; pasteWhy = note; OpenDialog(Dlg.Paste, "d:pastefield"); note = null; } if (note != null) { Say(note, noteBad); } if (string.IsNullOrEmpty(nav.Focus) || (dlg == Dlg.None && view == View.Places && !nav.Focus.StartsWith("r", StringComparison.Ordinal))) { nav.Set("a:clip"); } nav.Visible = input.UsingPad; host.Opened("Panel opened on " + world + ": " + Store.For(world).Saved.Count + " places, " + Store.For(world).Recent.Count + " recent."); return true; } public void Hide(string why) { if (Open) { Open = false; pending = null; focusField = null; noteRow = null; noteItem = null; if (dlg == Dlg.Capture) { dlg = Dlg.None; } hold.End(why); log.LogInfo((object)("Panel closed (" + why + ").")); } } public void Refused(string why) { Say(why, bad: true); } public void Update(bool closeKey) { string text = hold.Check(); if (text != null) { Hide(text); return; } slide = (host.Look.ReducedMotion() ? 1f : Mathf.MoveTowards(slide, 1f, Time.unscaledDeltaTime * 7f)); if (dlg == Dlg.Capture) { Capture(); return; } bool flag = GUIUtility.keyboardControl != 0 && focusedNow.Length > 0; if (closeKey && !flag) { Hide("the key again"); return; } Cmd cmd = input.Read(flag); if (cmd != Cmd.None) { Command(cmd, flag); } Action action = pending; pending = null; action?.Invoke(); if (nav.Moved) { nav.Moved = false; float margin = theme.Px(8f); if (dlg == Dlg.None && view == View.Places) { scroll.y = nav.ScrollFor(scroll.y, listViewHeight, margin); } else if (dlg == Dlg.None) { setScroll.y = nav.ScrollFor(setScroll.y, setViewHeight, margin); } else { dlgScroll.y = nav.ScrollFor(dlgScroll.y, setViewHeight, margin); } FocusMoved(); } } private void Command(Cmd cmd, bool typing) { //IL_02dd: Unknown result type (might be due to invalid IL or missing references) //IL_02e2: Unknown result type (might be due to invalid IL or missing references) switch (cmd) { case Cmd.Back: Back(typing); break; case Cmd.Activate: { if (typing && focusedNow == "f:search") { GUIUtility.keyboardControl = 0; dropFocus = true; nav.Move(1); break; } if (typing && focusedNow == "d:renamefield") { pending = DoRename; break; } if (typing && focusedNow == "d:pastefield") { pending = SubmitPaste; break; } if (typing && focusedNow == "ne:field") { string typed = noteText; pending = delegate { SaveNote(typed); }; break; } if (!nav.Visible && !typing) { nav.Move(0); break; } Action action = Act(nav.Focus); if (action != null) { pending = action; } else { nav.Move(0); } break; } case Cmd.Up: LeaveField(); nav.Move(-1); break; case Cmd.Down: LeaveField(); nav.Move(1); break; case Cmd.PageUp: { LeaveField(); for (int i = 0; i < 8; i++) { nav.Move(-1); } break; } case Cmd.PageDown: { LeaveField(); for (int j = 0; j < 8; j++) { nav.Move(1); } break; } case Cmd.Home: nav.First(); break; case Cmd.End: nav.Last(); break; case Cmd.Next: LeaveField(); nav.Move(1); break; case Cmd.Prev: LeaveField(); nav.Move(-1); break; case Cmd.Left: { if (lefts.TryGetValue(nav.Focus, out var value2) && nav.Visible) { pending = value2; } else { nav.Move(-1); } break; } case Cmd.Right: { if (rights.TryGetValue(nav.Focus, out var value) && nav.Visible) { pending = value; } else { nav.Move(1); } break; } case Cmd.TabLeft: case Cmd.TabRight: if (dlg == Dlg.None) { int num = ((cmd == Cmd.TabRight) ? 1 : (-1)); if (view == View.Places) { SetTab((tab == Tab.Mine) ? Tab.Places : Tab.Mine); nav.Set((tab == Tab.Mine) ? "t:mine" : "t:places", byKey: true); } else { section = (Section)((int)(section + num + 5) % 5); setScroll = Vector2.zero; nav.Set("set:" + section, byKey: true); } } break; case Cmd.SaveHere: if (dlg == Dlg.None && view == View.Places) { pending = SaveHere; } break; case Cmd.Actions: if (dlg == Dlg.None && view == View.Places) { SelectFocused(); if (HasSelection) { nav.Set("s:go", byKey: true); } } break; } } private Action Act(string id) { if (id == null || !acts.TryGetValue(id, out var value)) { return null; } return value; } private void LeaveField() { if (GUIUtility.keyboardControl != 0) { GUIUtility.keyboardControl = 0; } dropFocus = true; } private void Back(bool typing) { if (noteRow != null) { CancelNote(); } else if (typing) { GUIUtility.keyboardControl = 0; focusField = null; dropFocus = true; } else if (dlg != Dlg.None) { CloseDialog(); } else if (view == View.Settings) { view = View.Places; nav.Set("h:settings", nav.Visible); } else { Hide(input.UsingPad ? "B" : "Esc"); } } private void FocusMoved() { string focus = nav.Focus; if (!focus.StartsWith("f:", StringComparison.Ordinal)) { switch (focus) { case "d:renamefield": case "d:pastefield": case "ne:field": break; default: goto IL_0057; } } if (!input.UsingPad) { focusField = focus; } goto IL_005d; IL_0057: LeaveField(); goto IL_005d; IL_005d: if (dlg == Dlg.None && view == View.Places) { SelectFocused(); } } private void SelectFocused() { if (rowItems.TryGetValue(nav.Focus, out var value)) { if (value is Place place) { selPlace = place; selPoi = null; } else if (value is Poi poi) { selPoi = poi; selPlace = null; } } } private void Say(string text, bool bad, Removed undoable = null, Action undoAppearance = null) { status = text; statusBad = bad; statusUntil = Time.realtimeSinceStartup + ((undoable != null || undoAppearance != null) ? 12f : 8f); undo = undoable; undoLook = undoAppearance; } private void SetTab(Tab t) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (tab != t) { tab = t; scroll = Vector2.zero; } } private void FromClipboard() { string text = null; try { text = GUIUtility.systemCopyBuffer; } catch (Exception ex) { log.LogWarning((object)("Clipboard unavailable: " + ex.GetType().Name)); } string text2 = (text ?? "").Trim(); if (TeleportRequest.TryParse(text2, out var request)) { host.Go(request, Coords(request)); return; } if (text2.Length <= 60000 && (SpotSet.LooksLikeLink(text2) || FoundSet.LooksLikeLink(text2))) { ImportLink(text2); return; } bool flag = text2.Length > 0 && text2.Length <= 300 && text2.IndexOf('\n') < 0 && text2.StartsWith("/tp", StringComparison.Ordinal); paste = (flag ? text2 : ""); pasteWhy = ((text2.Length == 0) ? L.T("paste.empty") : (flag ? TeleportRequest.Explain(text2) : L.T("paste.notOne"))); OpenDialog(Dlg.Paste, "d:pastefield"); } private static string Coords(TeleportRequest r) { return Mathf.RoundToInt(r.X) + ", " + (r.AutomaticHeight ? "~" : Mathf.RoundToInt(r.Y).ToString()) + ", " + Mathf.RoundToInt(r.Z); } private void SubmitPaste() { string text = (paste ?? "").Trim(); TeleportRequest request; string reason; if (SpotSet.LooksLikeLink(text) || FoundSet.LooksLikeLink(text)) { CloseDialog(); ImportLink(text); } else if (!TeleportRequest.Parse(text, out request, out reason)) { pasteWhy = reason; host.Sound(ok: false); } else { CloseDialog(); host.Go(request, Coords(request)); } } public void SaveHere() { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) PlayerMainController player = hold.Player; if ((Object)(object)player == (Object)null || !Object.op_Implicit((Object)(object)player)) { return; } Vector3 val = Feet(player); PoiWorld pw = PoisFor(world); string name = PlaceStore.AutoName(planetName, val.x, val.z, delegate(float x, float z) { Poi poi = pw?.Closest(x, z, 60f); return (poi == null) ? null : pw.NameOf(poi); }); Place place = Store.Save(world, name, val.x, val.y, val.z); if (place == null) { Say(L.T("save.full"), bad: true); host.Sound(ok: false); return; } selPlace = place; selPoi = null; SetTab(Tab.Mine); if (SaveStore()) { Say(L.T("save.done", place.Name), bad: false); host.Sound(ok: true); } nav.Set(RowId(place, "m"), nav.Visible); log.LogInfo((object)("Panel: saved a place on " + world + ".")); } public static Vector3 Feet(PlayerMainController player) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) CharacterController component = ((Component)player).GetComponent<CharacterController>(); Vector3 position = ((Component)player).transform.position; if ((Object)(object)component == (Object)null) { return position; } Vector3 val = ((Component)player).transform.TransformPoint(component.center); return new Vector3(position.x, val.y - component.height * 0.5f * Mathf.Abs(((Component)player).transform.lossyScale.y), position.z); } public string NameForSpot(string w, float x, float z) { Place place = null; float num = 30f; foreach (Place item in Store.For(w).Saved) { float num2 = item.Distance2D(x, z); if (num2 <= num) { place = item; num = num2; } } if (place != null) { return place.Name; } PoiWorld poiWorld = PoisFor(w); Poi poi = poiWorld?.Closest(x, z, 30f); if (poi == null) { return ""; } return poiWorld.NameOf(poi); } private void ImportLink(string text) { List<string> list = new List<string>(); bool flag = false; bool flag2 = false; if (SpotSet.LooksLikeLink(text)) { if (ImportSpots(text, out var said)) { flag = true; } else { flag2 = true; } list.Add(said); } if (FoundSet.LooksLikeLink(text)) { if (ImportFound(text, out var said2)) { flag = true; } else { flag2 = true; } list.Add(said2); } Say(string.Join(" ", list.ToArray()), flag2 && !flag); host.Sound(!flag2 || flag); } private bool ImportFound(string text, out string said) { FoundSet foundSet = Found(); if (foundSet == null) { said = L.T("found.cantRead"); return false; } if (!foundSet.TryRead(text, out var ticked, out var reason)) { said = reason; log.LogInfo((object)"Panel: a found-set link refused."); return false; } int num = 0; Dictionary<string, int> dictionary = new Dictionary<string, int>(StringComparer.Ordinal); foreach (int item in ticked) { string key = foundSet.Worlds[foundSet.W[item]]; if (Store.For(key).Visited.Add(foundSet.Ids[item])) { num++; dictionary[key] = ((!dictionary.TryGetValue(key, out var value)) ? 1 : (value + 1)); } } string text2 = ((num > 0) ? Lib.Save() : null); List<string> list = new List<string>(); foreach (KeyValuePair<string, int> item2 in dictionary) { list.Add(Title(item2.Key) + " " + item2.Value); } said = ((ticked.Count == 0) ? L.T("found.none") : ((num == 0) ? L.T("found.allAlready") : (L.N("found.added", num, string.Join(", ", list.ToArray())) + ((ticked.Count > num) ? (" " + L.T("found.someAlready", ticked.Count - num)) : "")))); if (text2 != null) { said = said + " " + text2; } log.LogInfo((object)("Panel: imported a found-set link: " + num + " marked, " + (ticked.Count - num) + " already.")); return text2 == null; } private bool ImportSpots(string text, out string said) { if (!SpotSet.TryRead(text, out var spots, out var from, out var reason)) { said = reason; return false; } ImportResult importResult = Store.Import(spots, world, delegate(string w, string pin) { PoiWorld poiWorld = PoisFor(w); Poi value; return (poiWorld != null && poiWorld.ById.TryGetValue(pin, out value) && value.HasLanding) ? new float[3] { value.LX, value.LY, value.LZ } : null; }); string text2 = ((importResult.Added > 0) ? Lib.Save() : null); said = PlaceStore.Describe(importResult, Title); if (from.Length > 0 && importResult.Added > 0) { said = L.T("import.from", from) + " " + said; } if (text2 != null) { said = said + " " + text2; } log.LogInfo((object)("Panel: imported a spot-set (" + spots.Count + " spots): " + importResult.Added + " added, " + importResult.Skipped + " skipped.")); return text2 == null; } private void CopyForMap() { FoundSet fs = Found(); if (fs == null) { Say(L.T("found.cantWrite"), bad: true); return; } int n = 0; string systemCopyBuffer = fs.LinkOf(delegate(int i) { bool num = Store.For(fs.Worlds[fs.W[i]]).Visited.Contains(fs.Ids[i]); if (num) { n++; } return num; }); try { GUIUtility.systemCopyBuffer = systemCopyBuffer; } catch (Exception ex) { log.LogWarning((object)("Clipboard unavailable: " + ex.GetType().Name)); Say(L.T("clip.refused"), bad: true); return; } Say((n == 0) ? L.T("found.copiedNone") : L.N("found.copied", n), bad: false); host.Sound(ok: true); log.LogInfo((object)("Panel: copied a found-set link for the map (" + n + " marks).")); } public FoundSet Found() { if (foundTried) { return foundSet; } foundTried = true; try { using Stream stream = typeof(Panel).Assembly.GetManifestResourceStream("foundset-pc.json.z"); if (stream == null) { return null; } byte[] array = new byte[stream.Length]; int num; for (int i = 0; i < array.Length; i += num) { num = stream.Read(array, i, array.Length - i); if (num <= 0) { break; } } foundSet = FoundSet.Read(array); log.LogInfo((object)("Found list: " + foundSet.Ids.Count + " pins over " + foundSet.Worlds.Count + " planets (map " + foundSet.Map.Substring(0, 9) + ", hash " + foundSet.Hash + ").")); } catch (Exception ex) { log.LogWarning((object)("Found list unreadable: " + ex.GetType().Name)); } return foundSet; } public PoiWorld PoisFor(string w) { w = PlaceStore.WorldOf(w); if (pois.TryGetValue(w, out var value)) { return value; } PoiWorld poiWorld = null; try { using Stream stream = typeof(Panel).Assembly.GetManifestResourceStream("pois-" + w + ".json.z"); if (stream != null) { byte[] array = new byte[stream.Length]; int num; for (int i = 0; i < array.Length; i += num) { num = stream.Read(array, i, array.Length - i); if (num <= 0) { break; } } poiWorld = PoiWorld.Read(array); log.LogInfo((object)("Places: " + w + " has " + poiWorld.Pins.Count + " POIs (map " + poiWorld.Map.Substring(0, 9) + ", build " + poiWorld.Build + ").")); } } catch (Exception ex) { log.LogWarning((object)("Places list for " + w + " unreadable: " + ex.GetType().Name)); } return pois[w] = poiWorld; } private PlacesTree TreeFor(PoiWorld pw) { if (!trees.TryGetValue(world, out var value)) { value = (trees[world] = new PlacesTree(pw.StartLayers())); } value.ByName = byName; return value; } private static string Title(string w) { if (w.Length != 0) { return char.ToUpperInvariant(w[0]) + w.Substring(1); } return w; } private void Teleport() { if (host.Busy) { Say(L.T("tp.preparing"), bad: true); } else if (selPlace != null) { host.Go(selPlace.Request, selPlace.Name); } else if (selPoi != null && selPoi.HasLanding) { host.Go(selPoi.Landing, PoisFor(world).NameOf(selPoi)); } else if (selPoi != null) { Say(L.T("poi.noLanding"), bad: true); host.Sound(ok: false); } } private void ToggleFav() { if (selPlace != null) { selPlace.Fav = !selPlace.Fav; if (SaveStore()) { Say(L.T(selPlace.Fav ? "fav.on" : "fav.off", selPlace.Name), bad: false); } } else { if (selPoi == null) { return; } string name = PoisFor(world).NameOf(selPoi); Place place = Store.For(world).Saved.Find((Place p) => p.Pin == selPoi.Id); if (place != null) { place.Fav = true; if (SaveStore()) { Say(L.T("fav.on", place.Name), bad: false); } return; } if (!selPoi.HasLanding) { Say(L.T("poi.noLanding"), bad: true); return; } Place place2 = Store.Save(world, name, selPoi.LX, selPoi.LY, selPoi.LZ); if (place2 == null) { Say(L.T("save.full"), bad: true); return; } place2.Pin = selPoi.Id; place2.Fav = true; if (SaveStore()) { Say(L.T("fav.saved", place2.Name), bad: false); host.Sound(ok: true); } } } private void ToggleFound() { if (selPoi != null && PoisFor(world).Cats[selPoi.Cat].Findable) { HashSet<string> visited = Store.For(world).Visited; bool flag = !visited.Remove(selPoi.Id); if (flag) { visited.Add(selPoi.Id); } if (SaveStore()) { Say(L.T(flag ? "found.marked" : "found.unmarked", PoisFor(world).NameOf(selPoi)), bad: false); } } } private void ShowOnMap() { //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Unknown result type (might be due to invalid IL or missing references) string text; if (selPoi != null) { text = "https://gamesomg.com/planet-crafter-map/#pin=" + selPoi.Id; } else { if (selPlace != null && !string.IsNullOrEmpty(selPlace.Pin)) { PoiWorld poiWorld = PoisFor(world); if (poiWorld != null && poiWorld.ById.ContainsKey(selPlace.Pin)) { text = "https://gamesomg.com/planet-crafter-map/#pin=" + selPlace.Pin; goto IL_01b7; } } if (selPlace != null) { text = "https://gamesomg.com/planet-crafter-map/#spot=" + Math.Round(selPlace.X) + "," + Math.Round(selPlace.Z) + "," + Uri.EscapeDataString(selPlace.Name) + ",," + world; } else { PlayerMainController player = hold.Player; if ((Object)(object)player == (Object)null || !Object.op_Implicit((Object)(object)player)) { return; } Vector3 position = ((Component)player).transform.position; text = "https://gamesomg.com/planet-crafter-map/#spot=" + Math.Round(position.x) + "," + Math.Round(position.z) + "," + Uri.EscapeDataString(L.T("map.youWereHere")) + ",," + world; } } goto IL_01b7; IL_01b7: try { Application.OpenURL(text); Say(L.T("map.opened"), bad: false); } catch (Exception ex) { log.LogWarning((object)("Browser did not open: " + ex.GetType().Name)); Say(L.T("map.failed"), bad: true); } } private void DeleteSelected() { if (selPlace != null) { string saveFailed; Removed removed = Lib.Delete(world, selPlace, out saveFailed); if (removed != null) { Say(saveFailed ?? L.T("delete.done", removed.Place.Name), saveFailed != null, (saveFailed == null) ? removed : null); selPlace = null; } } } private void Undo() { if (undoLook != null) { Action action = undoLook; undoLook = null; action(); Say(L.T("look.undone"), bad: false); } else if (undo != null) { Removed removed = undo; undo = null; if (Lib.Undo(removed, out var saveFailed)) { selPlace = removed.Place; Say(saveFailed ?? L.T("undo.done", removed.Place.Name), saveFailed != null); } else { Say(L.T("undo.taken", removed.Place.Name), bad: true); } } } private void DoRename() { if (selPlace == null) { CloseDialog(); return; } string text = Store.Rename(world, selPlace, rename); if (text == null) { Say(L.T("rename.empty"), bad: true); return; } CloseDialog(); if (SaveStore()) { Say(L.T("rename.done", text), bad: false); } } private string NoteOf(object item) { if (!(item is Place place)) { if (!(item is Poi poi)) { return ""; } return Store.NoteOf(world, poi.Id); } return place.Note; } private string NameOf(object item) { if (!(item is Place place)) { if (item is Poi p) { PoiWorld poiWorld = PoisFor(world); if (poiWorld != null) { return poiWorld.NameOf(p); } } return ""; } return place.Name; } private void OpenNote(string rowId, object item) { if (item is Place place) { selPlace = place; selPoi = null; } else if (item is Poi poi) { selPoi = poi; selPlace = null; } noteRow = rowId; noteItem = item; noteText = NoteOf(item); string id = (input.UsingPad ? "ne:p0" : "ne:field"); nav.Set(id, nav.Visible || input.UsingPad); if (!input.UsingPad) { focusField = id; } } private void CancelNote() { if (noteRow != null) { string id = noteRow; noteRow = null; noteItem = null; GUIUtility.keyboardControl = 0; focusField = null; dropFocus = true; nav.Set(id, nav.Visible); } } private void SaveNote(string text) { object obj = noteItem; string id = noteRow; if (obj == null) { return; } string text2 = NoteOf(obj); string text3 = ((obj is Place place) ? PlaceStore.SetNote(place, text) : ((obj is Poi poi) ? Store.SetNote(world, poi.Id, text) : text2)); noteRow = null; noteItem = null; GUIUtility.keyboardControl = 0; focusField = null; dropFocus = true; nav.Set(id, nav.Visible); if (!(text3 == text2)) { if (SaveStore()) { Say((text3.Length == 0) ? L.T("note.deleted", NameOf(obj)) : L.T("note.saved", NameOf(obj)), bad: false); } log.LogInfo((object)("Panel: a note " + ((text3.Length == 0) ? "deleted" : ((text2.Length == 0) ? "added" : "changed")) + " on " + world + ".")); } } private void OpenDialog(Dlg d, string focus) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) if (dlg == Dlg.None) { nav.Push(focus); } else { nav.Set(focus); } dlg = d; dlgScroll = Vector2.zero; if ((focus == "d:pastefield" || focus == "d:renamefield") && !input.UsingPad) { focusField = focus; } nav.Visible = nav.Visible || input.UsingPad; } private void CloseDialog() { if (dlg != Dlg.None) { dlg = Dlg.None; focusField = null; GUIUtility.keyboardControl = 0; dropFocus = true; nav.Pop(); } } private void Confirm(string title, string body, string yes, bool danger, Action act) { confirmTitle = title; confirmBody = body; confirmYes = yes; confirmDanger = danger; confirmAct = act; OpenDialog(Dlg.Confirm, danger ? "d:no" : "d:yes"); } private void Capture() { bool cancelled; string text = PadInput.Captured(out cancelled); if (cancelled || Time.realtimeSinceStartup > captureUntil) { CloseDialog(); Say(L.T("bind.cancelled"), bad: false); } else { if (text == null) { return; } bool num = KeyCheck.IsPad(text); bool flag = captureFor == "PadPlaces" || captureFor == "PadReturn"; if (num != flag) { Say(L.T(flag ? "bind.wantButton" : "bind.wantKey"), bad: true); return; } string text2 = host.SetBinding(captureFor, text); CloseDialog(); if (text2 != null) { Say(text2, bad: true); host.Sound(ok: false); } else { Say(L.