using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Threading; using HarmonyLib; using UnityEngine; using Object = UnityEngine.Object; [assembly: AssemblyMetadata("Notice", "Copyright (c) casualexpie. All rights reserved. Do NOT decompile, disassemble, or reverse-engineer this assembly. Report bug symptoms on the Nexus Bugs page; do not post decompiled or reconstructed source. Reverse-engineering this DLL is not authorized.")] [assembly: AssemblyTitle("Ultra Paradise CU:Trainer Payload")] [assembly: AssemblyProduct("Ultra Paradise CU:Trainer")] [assembly: AssemblyCopyright("Copyright (c) casualexpie")] namespace UltraParadise { public static class Loader { private static int started; public static void Init() { if (Interlocked.Exchange(ref started, 1) == 1) return; AppDomain.CurrentDomain.AssemblyResolve += Resolve; Application.onBeforeRender += Boot; } private static Assembly Resolve(object sender, ResolveEventArgs args) { string name; try { name = new AssemblyName(args.Name).Name; } catch (Exception) { return null; } foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) { try { if (a.GetName().Name == name) return a; } catch (Exception) { } } Stream s = typeof(Loader).Assembly.GetManifestResourceStream("lib." + name + ".dll"); if (s == null) return null; using (s) { MemoryStream ms = new MemoryStream(); byte[] buf = new byte[81920]; int n; while ((n = s.Read(buf, 0, buf.Length)) > 0) ms.Write(buf, 0, n); return Assembly.Load(ms.ToArray()); } } private static void Boot() { Application.onBeforeRender -= Boot; try { GameObject go = new GameObject("UltraParadise"); go.hideFlags = HideFlags.HideAndDontSave; Object.DontDestroyOnLoad(go); #if LINUXPLUGIN go.AddComponent(); #endif go.AddComponent(); } catch (Exception e) { Debug.LogError("[Ultra Paradise] Couldn't start: " + e); } } } internal static class Link { private static readonly object gate = new object(); private static readonly Queue inbox = new Queue(); private static TcpClient client; private static StreamWriter writer; private static Thread thread; public static volatile bool Connected; #if LINUXPLUGIN public const string Version = "L1"; #else public const string Version = "4"; #endif public static void Start() { if (thread != null) return; thread = new Thread(Loop); thread.IsBackground = true; thread.Name = "Ultra Paradise link"; thread.Start(); } private static string LinkFile() { #if LINUXPLUGIN return LinuxHost.LinkFile; #endif return Path.Combine(Path.Combine(Path.GetTempPath(), "UltraParadise"), "link-" + System.Diagnostics.Process.GetCurrentProcess().Id + ".txt"); } private static void Loop() { string file = LinkFile(); while (true) { try { if (File.Exists(file)) { string[] parts = File.ReadAllText(file).Trim().Split(' '); int port; if (parts.Length == 2 && int.TryParse(parts[0], out port) && port > 0 && port < 65536) Session(port, parts[1]); } } catch (Exception) { } Connected = false; Thread.Sleep(1000); } } private static void Session(int port, string token) { TcpClient c = new TcpClient(); try { c.NoDelay = true; c.Connect("127.0.0.1", port); NetworkStream ns = c.GetStream(); StreamReader r = new StreamReader(ns, new UTF8Encoding(false)); StreamWriter w = new StreamWriter(ns, new UTF8Encoding(false)); w.NewLine = "\n"; w.AutoFlush = true; w.WriteLine("HELLO " + token + " " + Version); if (r.ReadLine() != "OK") return; lock (gate) { client = c; writer = w; } Connected = true; Enqueue("CONNECTED"); string line; while ((line = r.ReadLine()) != null) { if (line.Length > 512) continue; Enqueue(line); } } catch (Exception) { } finally { lock (gate) { client = null; writer = null; } Connected = false; Enqueue("DISCONNECTED"); try { c.Close(); } catch (Exception) { } } } private static void Enqueue(string s) { lock (inbox) inbox.Enqueue(s); } public static bool TryTake(out string s) { lock (inbox) { if (inbox.Count == 0) { s = null; return false; } s = inbox.Dequeue(); return true; } } #if LINUXPLUGIN internal static void Inject(string s) { Enqueue(s); } #endif public static void Send(string s) { #if LINUXPLUGIN LinuxHost.Sent(s); #endif lock (gate) { if (writer == null) return; try { writer.WriteLine(s.Replace('\n', ' ').Replace('\r', ' ')); } catch (Exception) { try { client.Close(); } catch (Exception) { } } } } private static readonly object frameGate = new object(); private static readonly AutoResetEvent frameReady = new AutoResetEvent(false); private static readonly Queue bulk = new Queue(); private static Thread frameThread; public static bool FramePending { get { lock (frameGate) return bulk.Count > 0; } } public static void PostFrame(string s) { Post(s); } public static void Post(string s) { lock (frameGate) { if (bulk.Count >= 64) return; bulk.Enqueue(s); } if (frameThread == null) { frameThread = new Thread(FrameLoop); frameThread.IsBackground = true; frameThread.Name = "Ultra Paradise bulk"; frameThread.Start(); } frameReady.Set(); } private static void FrameLoop() { while (true) { frameReady.WaitOne(); while (true) { string s; lock (frameGate) { if (bulk.Count == 0) break; s = bulk.Dequeue(); } Send(s); } } } } internal sealed class Flag { public bool Value; } internal sealed class Num { public float Value; public Num(float v) { Value = v; } } internal sealed class LogShim { public void LogInfo(object o) { Debug.Log("[Ultra Paradise] " + o); } public void LogWarning(object o) { Debug.LogWarning("[Ultra Paradise] " + o); } public void LogError(object o) { Debug.LogError("[Ultra Paradise] " + o); } } internal static class Feed { internal static void Mod(string text) { DebugFeed.Feed("MOD", null, text); } internal static void Add(string tag, string color, string text) { DebugFeed.Feed(tag, color, text); } } internal static partial class Plugin { internal static readonly LogShim Log = new LogShim(); internal static float GameSpeed = 1f; internal static float CameraZoom = 1f; internal static readonly Flag GodMode = new Flag(), NoFallDamage = new Flag(), InfiniteStamina = new Flag(), NoHunger = new Flag(), NoThirst = new Flag(), NoTiredness = new Flag(), MoodLock = new Flag(), FreezeEnemies = new Flag(), OneHitKills = new Flag(), MaxTraderRep = new Flag(), FreeShopping = new Flag(), InstantMine = new Flag(), UnlimitedAmmo = new Flag(), LongerEscape = new Flag(), NoBleeding = new Flag(), NoPain = new Flag(), NoInfection = new Flag(), NoSickness = new Flag(), NoRadiation = new Flag(), UnlimitedOxygen = new Flag(), StableTemperature = new Flag(), FasterHealing = new Flag(), MoreXp = new Flag(), FasterMovement = new Flag(), FasterClimbing = new Flag(), HigherJumps = new Flag(), UnlimitedJumps = new Flag(), UnlimitedWallJumps = new Flag(), LowGravity = new Flag(), FlyMode = new Flag(), Noclip = new Flag(), ClickTeleport = new Flag(), FreeCrafting = new Flag(), NoCraftFail = new Flag(), AllRecipes = new Flag(), NoDegradation = new Flag(), UnlimitedCarry = new Flag(), UnlimitedLiquids = new Flag(), UnlimitedBattery = new Flag(), MasterLockpick = new Flag(), NoGunJams = new Flag(), NoRecoil = new Flag(), MoreDamage = new Flag(), FasterAttacks = new Flag(), Invisibility = new Flag(), DisableTraps = new Flag(), PauseRadiation = new Flag(), NoEarthquakes = new Flag(), MoreLoot = new Flag(), FullBright = new Flag(), FreeCamera = new Flag(), InfiniteCredit = new Flag(), FragileBody = new Flag(), FastMetabolism = new Flag(), HopelessStart = new Flag(), BrittleGear = new Flag(), StrongerEnemies = new Flag(), FastRadiation = new Flag(), UnchippedChallenge = new Flag(), ColdCaves = new Flag(), MoreTraps = new Flag(), LootScarcity = new Flag(); internal static readonly Num MoveSpeedMult = new Num(1.6f), ClimbSpeedMult = new Num(2f), JumpMult = new Num(1.5f), GravityScale = new Num(0.4f), FlySpeed = new Num(18f), HealingMult = new Num(3f), XpMult = new Num(3f), DamageMult = new Num(2f), AttackSpeedMult = new Num(2.5f), LootMult = new Num(2f); private static Dictionary flags; private static Dictionary nums; private static void Index() { if (flags != null) return; flags = new Dictionary(); nums = new Dictionary(); foreach (FieldInfo f in typeof(Plugin).GetFields(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public)) { if (f.FieldType == typeof(Flag)) flags[f.Name] = (Flag)f.GetValue(null); else if (f.FieldType == typeof(Num)) nums[f.Name] = (Num)f.GetValue(null); } } internal static Flag FindFlag(string id) { Index(); Flag f; return flags.TryGetValue(id, out f) ? f : null; } internal static Num FindNum(string id) { Index(); Num n; return nums.TryGetValue(id, out n) ? n : null; } internal static void AllOff() { Index(); foreach (Flag f in flags.Values) f.Value = false; GameSpeed = 1f; CameraZoom = 1f; MoodTarget = float.NaN; } } internal static class Patcher { private static Harmony harmony; internal static int Apply() { harmony = new Harmony("ultraparadise.cutrainer"); int fails = 0; Type[] types; try { types = typeof(Patcher).Assembly.GetTypes(); } catch (ReflectionTypeLoadException e) { types = e.Types; } foreach (Type t in types) { if (t == null || t.GetCustomAttributes(typeof(HarmonyPatch), false).Length == 0) continue; try { harmony.CreateClassProcessor(t).Patch(); } catch (Exception e) { fails++; Plugin.Log.LogWarning("Couldn't patch " + t.Name + ": " + e.Message); } } return fails; } internal static void Remove() { try { if (harmony != null) harmony.UnpatchSelf(); } catch (Exception) { } } } public class Agent : MonoBehaviour { private bool blocked; private string blockedWhy; private int patchState = int.MinValue; private float nextInfo, nextMp, nextSlow, nextTickError, nextWorldSync; private bool lastFullBright, lastNoclip, lastFreecam, weSetUnchipped; private float appliedSpeed = 1f; private Camera zoomCam; private float zoomBase; private Behaviour zoomPpc; private bool zoomPpcWasOn; private TraderScript trader; private float traderDist; private const float TraderRange = 20f; private const int CreditCap = 9999; private static readonly FieldInfo BonusTemp = typeof(WorldGeneration).GetField("bonusTemperatureOffset", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); private void Awake() { blockedWhy = MultiplayerCheck(); blocked = blockedWhy != null; if (!blocked) StartPatches(); Link.Start(); Plugin.Log.LogInfo("Trainer attached." + (blocked ? " Cheats are off: " + blockedWhy : "")); } private void StartPatches() { try { patchState = Patcher.Apply(); } catch (Exception e) { patchState = -1; Plugin.Log.LogError("Patch library failed to load: " + e); } } private static string MultiplayerCheck() { string[] words = { "krokmp", "casualtiestogether", "casualtiesmp", "levskittne" }; foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) { string n; try { n = a.GetName().Name.ToLowerInvariant().Replace(" ", "").Replace("-", "").Replace("_", "").Replace(".", ""); } catch (Exception) { continue; } foreach (string w in words) if (n.Contains(w)) return "a multiplayer mod is loaded (" + a.GetName().Name + ")"; } return null; } private void Block(string why) { blocked = true; blockedWhy = why; Plugin.AllOff(); Patcher.Remove(); Link.Send("BLOCKED " + why); } private static bool InGame() { return PlayerCamera.main != null && PlayerCamera.main.body != null && WorldGeneration.world != null; } private static Body Player() { return InGame() ? PlayerCamera.main.body : null; } private void Update() { string msg; int guard = 0; while (guard++ < 256 && Link.TryTake(out msg)) { try { Handle(msg); } catch (Exception e) { Plugin.Log.LogWarning("Command failed: " + e.Message); } } if (!blocked && Time.unscaledTime >= nextMp) { nextMp = Time.unscaledTime + 10f; string why = MultiplayerCheck(); if (why != null) Block(why); } try { HealthMirror.Tick(); MoodleFeed.Pump(); BarkFeed.Tick(); } catch (Exception e) { if (Time.unscaledTime >= nextTickError) { nextTickError = Time.unscaledTime + 10f; Plugin.Log.LogWarning("Health readout failed: " + e); } } try { DebugFeed.Tick(); } catch (Exception) { } try { ModBridge.Tick(); } catch (Exception) { } try { GameMusic.Tick(); } catch (Exception) { } if (SteamManager.disableAchievements) SteamManager.disableAchievements = false; if (blocked) return; try { Tick(); } catch (Exception e) { if (Time.unscaledTime >= nextTickError) { nextTickError = Time.unscaledTime + 10f; Plugin.Log.LogWarning("Cheat tick failed: " + e); } } if (Time.unscaledTime >= nextSlow) { nextSlow = Time.unscaledTime + 0.5f; try { Slow(); } catch (Exception) { } } if (Time.unscaledTime >= nextInfo) { nextInfo = Time.unscaledTime + 0.5f; SendInfo(); } } private void Slow() { Durability.Sweep(); if (SteamManager.disableAchievements) SteamManager.disableAchievements = false; Plugin.TryResume(); FindTrader(); if (Plugin.InfiniteCredit.Value && trader != null && trader.valueGiven < CreditCap) SetCredit(CreditCap); if (Plugin.MaxTraderRep.Value && trader != null && (trader.reputation < 200f || trader.hostility > 0f)) { trader.reputation = 200f; trader.hostility = 0f; RefreshTraderUI(); } } private void Tick() { bool inGame = InGame(); ConsoleScript con = ConsoleScript.instance; Body b = inGame ? PlayerCamera.main.body : null; if (con != null) { if (Plugin.FullBright.Value) con.fullBright = true; else if (lastFullBright) con.fullBright = false; } lastFullBright = Plugin.FullBright.Value; if (con != null && b != null && b.rb != null) { if (Plugin.Noclip.Value && !con.noClip) { con.noClip = true; con.noClipPos = b.transform.position; b.rb.simulated = false; } else if (!Plugin.Noclip.Value && lastNoclip && con.noClip) { con.noClip = false; b.rb.simulated = true; b.rb.velocity = Vector2.zero; } } lastNoclip = Plugin.Noclip.Value; if (inGame && con != null) { if (Plugin.FreeCamera.Value && !PlayerCamera.main.isFreecam) { PlayerCamera.main.isFreecam = true; con.freecamPos = PlayerCamera.main.transform.position; } else if (!Plugin.FreeCamera.Value && lastFreecam && PlayerCamera.main.isFreecam) { PlayerCamera.main.isFreecam = false; } } lastFreecam = Plugin.FreeCamera.Value; if (inGame && !PauseHandler.paused && Time.timeScale > 0f) { float want = Plugin.GameSpeed; if (want != 1f) { if (Mathf.Approximately(Time.timeScale, 1f) || Mathf.Approximately(Time.timeScale, appliedSpeed)) Time.timeScale = want; appliedSpeed = want; } else if (appliedSpeed != 1f) { if (Mathf.Approximately(Time.timeScale, appliedSpeed)) Time.timeScale = 1f; appliedSpeed = 1f; } } Camera cam = Camera.main; if (zoomCam != null && zoomCam != cam) zoomCam = null; if (inGame && cam != null && Plugin.CameraZoom != 1f) { if (zoomCam == null) { zoomCam = cam; zoomPpc = cam.GetComponent("PixelPerfectCamera") as Behaviour; zoomPpcWasOn = zoomPpc != null && zoomPpc.enabled; if (zoomPpc != null) zoomPpc.enabled = false; zoomBase = cam.orthographicSize; } cam.orthographicSize = zoomBase * Plugin.CameraZoom; } else if (zoomCam != null) { zoomCam.orthographicSize = zoomBase; if (zoomPpc != null) zoomPpc.enabled = zoomPpcWasOn; zoomCam = null; } if (b != null && Plugin.ClickTeleport.Value && Input.GetMouseButtonDown(2)) Actions.TeleportToCursor(); WorldGeneration w = WorldGeneration.world; if (b != null && w != null && w.worldExists && Time.unscaledTime >= nextWorldSync) { nextWorldSync = Time.unscaledTime + 0.5f; if (BonusTemp != null) BonusTemp.SetValue(w, WorldGeneration.GetRunSettingFloat("temperatureoffset")); WorldGeneration.globalDecayRate = WorldGeneration.GetRunSettingFloat("itemdecayrate"); w.maxTimePerLayer = WorldGeneration.GetRunSettingFloat("timelimit") * 60f; if (Plugin.UnchippedChallenge.Value && !w.unchippedMode) { w.SetUnchipped(true); weSetUnchipped = true; } else if (!Plugin.UnchippedChallenge.Value && weSetUnchipped) { weSetUnchipped = false; if (w.unchippedMode && !WorldGeneration.GetRunSettingBool("unchipped")) w.SetUnchipped(false); } } } private void Handle(string line) { if (line == "CONNECTED") { if (blocked) Link.Send("BLOCKED " + blockedWhy); else Link.Send("READY " + patchState); Link.Send("LOADER " + (Environment.GetEnvironmentVariable("ULTRAPARA_VERSION") ?? "none")); SendInfo(); MoodleFeed.Reset(); BarkFeed.Reset(); #if LINUXPLUGIN LinuxHost.OnConnected(); #endif return; } if (line == "DISCONNECTED") { #if !LINUXPLUGIN Plugin.AllOff(); #endif HealthMirror.SetMode(0); DebugFeed.SetOn(false); ModBridge.ReleaseAll(); GameMusic.Reset(); return; } string[] p = line.Split(new char[] { ' ' }, 3); string cmd = p[0]; if (cmd == "PING") { Link.Send("PONG"); return; } #if LINUXPLUGIN if (LinuxHost.Handle(cmd, p)) return; #endif if (cmd == "HEALTH" && p.Length >= 2) { int m; if (int.TryParse(p[1], out m)) HealthMirror.SetMode(m); return; } if (ModBridge.Handle(cmd, p)) return; if (GameMusic.Handle(cmd, p)) return; if (cmd == "DEBUG" && p.Length >= 2) { DebugFeed.SetOn(p[1] == "1"); return; } if (DebugFeed.On && (cmd == "SET" || cmd == "VAL" || cmd == "ACT" || cmd == "SPAWN")) DebugFeed.Add("COMMAND", line); if (cmd == "GETSFX" && p.Length >= 2) { BarkFeed.Request(p[1]); return; } if (blocked) { if (cmd == "ACT" || cmd == "SPAWN") Link.Send("MSG Cheats are off: " + blockedWhy); return; } if (cmd == "SET" && p.Length >= 3) { Flag f = Plugin.FindFlag(p[1]); if (f == null) return; bool v = p[2] == "1"; bool was = f.Value; f.Value = v; if (f == Plugin.MoodLock && v && !was) { Body b = Player(); if (b != null) { Plugin.MoodBody = b; Plugin.MoodTarget = b.happiness; } } if (f == Plugin.FreeShopping) RefreshTraderUI(); } else if (cmd == "VAL" && p.Length >= 3) { float v; if (!float.TryParse(p[2], NumberStyles.Float, CultureInfo.InvariantCulture, out v) || float.IsNaN(v) || float.IsInfinity(v)) return; if (p[1] == "GameSpeed") Plugin.GameSpeed = Mathf.Clamp(v, 0.1f, 5f); else if (p[1] == "CameraZoom") Plugin.CameraZoom = Mathf.Clamp(v, 0.25f, 5f); else { Num n = Plugin.FindNum(p[1]); if (n != null) n.Value = Mathf.Clamp(v, 0.01f, 100f); } } else if (cmd == "ACT" && p.Length >= 2) { string r; try { r = Act(p[1], p.Length >= 3 ? p[2] : ""); } catch (Exception e) { r = "That didn't work (" + e.GetType().Name + ")"; } if (!string.IsNullOrEmpty(r)) Link.Send("MSG " + r); } else if (cmd == "SPAWN" && p.Length >= 3) { int n; if (!int.TryParse(p[2], out n)) n = 1; n = Mathf.Clamp(n, 1, 50); string r; try { r = Actions.SpawnItem(p[1], n); } catch (Exception e) { r = "Couldn't spawn that (" + e.GetType().Name + ")"; } Link.Send("MSG " + r); } else if (cmd == "ITEMS") SendItems(); } private void SendItems() { if (Item.GlobalItems == null || Item.GlobalItems.Count == 0) { Link.Send("ITEMSEND 0"); return; } int n = 0; foreach (string key in new List(Item.GlobalItems.Keys)) { if (string.IsNullOrEmpty(key)) continue; Link.Send("ITEM " + key + "\t" + Actions.ItemName(key).Replace('\t', ' ')); n++; } Link.Send("ITEMSEND " + n); } private static string Clean(string s) { return s == null ? "" : s.Replace('|', '/').Replace('=', '-'); } private void SendInfo() { #if !LINUXPLUGIN if (!Link.Connected) return; #endif StringBuilder sb = new StringBuilder("INFO "); Body b = Player(); WorldGeneration w = WorldGeneration.world; if (b == null || w == null) sb.Append("where=main menu"); else { if (w.biomeOverride != WorldGeneration.OverrideSceneType.None) sb.Append("where=special area"); else sb.Append("where=layer ").Append(w.biomeDepth + 1).Append(" of ").Append(w.amountOfLayers); sb.Append("|alive=").Append(b.alive ? 1 : 0); sb.Append("|mood=").Append(b.totalHappiness.ToString("0", CultureInfo.InvariantCulture)); sb.Append("|px=").Append(b.transform.position.x.ToString("0.0", CultureInfo.InvariantCulture)).Append("|py=").Append(b.transform.position.y.ToString("0.0", CultureInfo.InvariantCulture)); sb.Append("|depth=").Append(w.biomeOverride != WorldGeneration.OverrideSceneType.None ? -1 : w.biomeDepth); if (b.skills != null) sb.Append("|str=").Append(b.skills.STR).Append("|res=").Append(b.skills.RES).Append("|int=").Append(b.skills.INT); if (Plugin.GodMode.Value && Plugin.Paused(b)) sb.Append("|paused=").Append(Clean(Plugin.PauseReason)); if (trader != null) { sb.Append("|trader=").Append(Clean(trader.gameObject.name.Replace("(Clone)", "").Trim())); sb.Append("|credit=").Append(trader.valueGiven); sb.Append("|rep=").Append((int)trader.reputation); sb.Append("|tdist=").Append(traderDist.ToString("0", CultureInfo.InvariantCulture)); if (trader.hostile) sb.Append("|hostile=1"); } } sb.Append("|savecheat=").Append(SaveFlag()).Append("|achoff=").Append(SteamManager.disableAchievements ? 1 : 0); Link.Send(sb.ToString()); } private static DateTime saveStamp = DateTime.MinValue; private static string saveFlag = "none"; private static float nextSaveCheck; private static string SaveFlag() { if (Time.unscaledTime < nextSaveCheck) return saveFlag; nextSaveCheck = Time.unscaledTime + 2f; try { string p = Path.Combine(Application.persistentDataPath, "save.sv"); if (!File.Exists(p)) { saveStamp = DateTime.MinValue; saveFlag = "none"; return saveFlag; } DateTime t = File.GetLastWriteTimeUtc(p); if (t == saveStamp) return saveFlag; string json = SaveSystem.Unzip(File.ReadAllBytes(p)); saveStamp = t; saveFlag = json.Contains("\"cheatedSave\":true") ? "cheated" : json.Contains("\"cheatedSave\":false") ? "clean" : "unknown"; } catch (Exception) { saveFlag = "error"; } return saveFlag; } private string Act(string id, string arg) { Body mb = Player(); switch (id) { case "heal": return Actions.HealWounds(); case "limbs": return Actions.ReattachLimbs(); case "em_full": case "em_bleed": case "em_breathe": case "em_heart": case "em_cure": case "em_body": return Actions.Emergency(id); case "tpgo": { if (mb == null) return "Not in a run"; WorldGeneration tw = WorldGeneration.world; string[] a = arg.Split(' '); float tx, ty; int td; if (a.Length != 3 || !float.TryParse(a[0], NumberStyles.Float, CultureInfo.InvariantCulture, out tx) || !float.TryParse(a[1], NumberStyles.Float, CultureInfo.InvariantCulture, out ty) || !int.TryParse(a[2], out td)) return null; if (float.IsNaN(tx) || float.IsNaN(ty) || float.IsInfinity(tx) || float.IsInfinity(ty)) return null; if (tw == null || tw.generatingWorld || !tw.worldExists) return "Wait for the layer to finish loading"; int cur = tw.biomeOverride != WorldGeneration.OverrideSceneType.None ? -1 : tw.biomeDepth; if (cur != td) return "That bookmark is on another layer"; Actions.Teleport(mb, new Vector2(tx, ty)); return "Teleported to the bookmark"; } case "killall": return Actions.KillAllEnemies(); case "spiders": return Actions.SpiderAmbush(); case "exit": return Actions.TeleportToExit(); case "back": return Actions.PreviousLayer(); case "skip": return Actions.SkipLayer(); case "quake": return Actions.StartEarthquake(); case "downpour": return Actions.FungalDownpour(); case "unlock": return Actions.UnlockCharacters(); case "starterkit": return Actions.StarterKit(); case "randomloadout": return Actions.RandomLoadout(); case "moodmax": if (mb == null) return "Not in a run"; Plugin.SetMood(mb, Plugin.MoodMax(mb)); return "Mood set to max"; case "mood": { if (mb == null) return "Not in a run"; int d; if (!int.TryParse(arg, out d)) return null; Plugin.SetMood(mb, mb.happiness + d); return "Mood " + (d > 0 ? "+" : "") + d; } case "skill": { string[] a = arg.Split(' '); int stat, d; if (a.Length != 2 || !int.TryParse(a[0], out stat) || !int.TryParse(a[1], out d)) return null; return Actions.AddSkill(Mathf.Clamp(stat, 0, 2), d); } case "credit": { if (mb == null) return "Not in a run"; if (trader == null) return "Walk up to a survivor first"; if (arg == "zero") { Plugin.InfiniteCredit.Value = false; SetCredit(0); return "Trade credit set to 0"; } int d; if (!int.TryParse(arg, out d)) return null; SetCredit(trader.valueGiven + d); return "Trade credit " + trader.valueGiven; } case "restock": if (mb == null) return "Not in a run"; if (trader == null) return "Walk up to a survivor first"; trader.GenerateInventory(); RefreshTraderUI(); return "Restocked (" + trader.items.Count + " items)"; } return null; } private void FindTrader() { trader = null; traderDist = 0f; Body b = Player(); if (b == null) return; Vector2 p = b.transform.position; float best = TraderRange; TraderScript[] all = Object.FindObjectsOfType(); for (int i = 0; i < all.Length; i++) { float d = Vector2.Distance(p, all[i].transform.position); if (d <= best) { best = d; trader = all[i]; } } if (trader != null) traderDist = best; } private void RefreshTraderUI() { PlayerCamera cam = PlayerCamera.main; if (cam == null || trader == null) return; TraderScript prev = cam.currentTrader; cam.currentTrader = trader; try { cam.UpdateTradeTexts(); cam.RefreshTraderInventories(); } catch (Exception) { } cam.currentTrader = prev; } private void SetCredit(int amount) { if (trader == null) return; trader.valueGiven = Math.Max(0, amount); RefreshTraderUI(); } } }