using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Text; using HarmonyLib; using UnityEngine; using Object = UnityEngine.Object; namespace UltraParadise { internal static class ModBridge { private const char REC = '\u001d', SEP = '\u001c'; private sealed class Def { public string Guid, Type; public string[] Methods; public string[] Actions; public Def(string guid, string type, string[] methods, params string[] actions) { Guid = guid; Type = type; Methods = methods; Actions = actions; } } private static readonly Def[] Defs = { new Def("getstinky", "GetStinky.StinkMenu", new[] { "Update", "OnGUI" }, "max=Max Stink", "plus=+25% Stink", "clean=Clean Me"), new Def("nodurability", "NoDurability.Runner", new[] { "Update", "OnGUI" }, "toggle=Turn On / Off"), new Def("saveanywhere", null, null, "save=Save Now"), new Def("controllersupport", null, null), new Def("hatshatshats", null, null), new Def("thighhighsrevamped", null, null), new Def("pickyournumber", null, null), new Def("alwaysgivenachance", null, null), new Def("nomoresoundcannons", null, null), new Def("bossmusic", null, null), }; private static readonly Dictionary taken = new Dictionary(); private static readonly Dictionary patched = new Dictionary(); private static Harmony harmony; private static float nextStat; private static Def Find(string guid) { foreach (Def d in Defs) if (d.Guid == guid) return d; return null; } private static object Prop(object o, string name) { if (o == null) return null; try { PropertyInfo p = o.GetType().GetProperty(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (p != null) return p.GetValue(o, null); FieldInfo f = o.GetType().GetField(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); return f != null ? f.GetValue(o) : null; } catch (Exception) { return null; } } private static object Plugin(string guid) { IDictionary d = DebugFeed.BepPlugins(); if (d == null || !d.Contains(guid)) return null; return d[guid]; } private static IEnumerable Entries(object info) { List list = new List(); IEnumerable cfg = Prop(Prop(info, "Instance"), "Config") as IEnumerable; if (cfg == null) return list; foreach (object kv in cfg) { object e = Prop(kv, "Value"); if (e != null) list.Add(e); } return list; } private static string Clean(object o) { string s = o == null ? "" : o.ToString(); return s.Replace('\r', ' ').Replace('\n', ' ').Replace(REC, ' ').Replace(SEP, ' '); } private static string Serialized(object entry) { try { MethodInfo m = entry.GetType().GetMethod("GetSerializedValue", BindingFlags.Public | BindingFlags.Instance); if (m != null) return m.Invoke(entry, null) as string; } catch (Exception) { } return Clean(Prop(entry, "BoxedValue")); } public static string List() { StringBuilder sb = new StringBuilder("MODS "); bool first = true; foreach (Def d in Defs) { object info = Plugin(d.Guid); if (info == null) continue; object meta = Prop(info, "Metadata"); if (!first) sb.Append(REC); first = false; bool can = d.Type != null && AccessTools.TypeByName(d.Type) != null; bool on; taken.TryGetValue(d.Guid, out on); sb.Append('M').Append(SEP).Append(d.Guid).Append(SEP).Append(Clean(Prop(meta, "Name"))).Append(SEP).Append(Clean(Prop(meta, "Version"))) .Append(SEP).Append(can ? '1' : '0').Append(SEP).Append(on ? '1' : '0').Append(SEP).Append(Clean(string.Join(";", d.Actions))); foreach (object e in Entries(info)) { object def = Prop(e, "Definition"); object desc = Prop(e, "Description"); Type t = Prop(e, "SettingType") as Type; object acc = Prop(desc, "AcceptableValues"); string min = "", max = "", opts = ""; if (acc != null) { object lo = Prop(acc, "MinValue"), hi = Prop(acc, "MaxValue"); if (lo != null && hi != null) { min = Convert.ToString(lo, CultureInfo.InvariantCulture); max = Convert.ToString(hi, CultureInfo.InvariantCulture); } IEnumerable vals = Prop(acc, "AcceptableValues") as IEnumerable; if (vals != null) { List l = new List(); foreach (object v in vals) l.Add(Clean(v)); opts = string.Join("|", l.ToArray()); } } if (t != null && t.IsEnum && opts.Length == 0) opts = string.Join("|", Enum.GetNames(t)); string kind = t == null ? "text" : t == typeof(bool) ? "bool" : t == typeof(int) ? "int" : t == typeof(float) || t == typeof(double) ? "float" : t == typeof(KeyCode) || t.Name == "KeyboardShortcut" ? "key" : t.IsEnum ? "enum" : "text"; sb.Append(REC).Append('E').Append(SEP).Append(d.Guid).Append(SEP).Append(Clean(Prop(def, "Section"))).Append(SEP).Append(Clean(Prop(def, "Key"))) .Append(SEP).Append(kind).Append(SEP).Append(Clean(Serialized(e))).Append(SEP).Append(Clean(Prop(desc, "Description"))) .Append(SEP).Append(min).Append(SEP).Append(max).Append(SEP).Append(opts); } } return sb.ToString(); } private static string SetConfig(string guid, string section, string key, string value) { if (Find(guid) == null) return "That mod isn't supported."; object info = Plugin(guid); if (info == null) return "That mod isn't loaded."; foreach (object e in Entries(info)) { object def = Prop(e, "Definition"); if (Clean(Prop(def, "Section")) != section || Clean(Prop(def, "Key")) != key) continue; try { MethodInfo m = e.GetType().GetMethod("SetSerializedValue", BindingFlags.Public | BindingFlags.Instance); if (m == null) return "Couldn't change that setting."; m.Invoke(e, new object[] { value }); return null; } catch (Exception ex) { return "Couldn't change it: " + (ex.InnerException ?? ex).Message; } } return "That setting wasn't found."; } public static bool Skip(MethodBase __originalMethod) { string g; bool on; return !(__originalMethod != null && patched.TryGetValue(__originalMethod, out g) && taken.TryGetValue(g, out on) && on); } private static string Take(string guid, bool on) { Def d = Find(guid); if (d == null || d.Type == null) return "That mod has no in-game window to take over."; Type t = AccessTools.TypeByName(d.Type); if (t == null || Plugin(guid) == null) return "That mod isn't loaded."; if (on) { if (harmony == null) harmony = new Harmony("casualexpie.ultraparadise.mymods"); MethodInfo skip = typeof(ModBridge).GetMethod("Skip", BindingFlags.Public | BindingFlags.Static); foreach (string name in d.Methods) { MethodInfo m = AccessTools.Method(t, name); if (m == null || patched.ContainsKey(m)) continue; try { harmony.Patch(m, new HarmonyMethod(skip)); patched[m] = guid; } catch (Exception e) { return "Couldn't take over " + name + ": " + e.Message; } } foreach (Object o in Resources.FindObjectsOfTypeAll(t)) { FieldInfo open = AccessTools.Field(t, "open"); if (open != null && open.FieldType == typeof(bool)) open.SetValue(o, false); FieldInfo blocker = AccessTools.Field(t, "blocker"); GameObject b = blocker != null ? blocker.GetValue(o) as GameObject : null; if (b != null) { Object.Destroy(b); blocker.SetValue(o, null); } } } taken[guid] = on; return null; } public static void ReleaseAll() { taken.Clear(); } private static Body Player() { try { if (PlayerCamera.main != null && PlayerCamera.main.body != null && WorldGeneration.world != null) return PlayerCamera.main.body; } catch (Exception) { } return null; } private static object Instance(string type) { Type t = AccessTools.TypeByName(type); if (t == null) return null; Object[] all = Resources.FindObjectsOfTypeAll(t); return all.Length > 0 ? all[0] : null; } private static bool ConfigBool(string guid, string key) { object info = Plugin(guid); if (info == null) return false; foreach (object e in Entries(info)) if (Clean(Prop(Prop(e, "Definition"), "Key")) == key) return Prop(e, "BoxedValue") is bool && (bool)Prop(e, "BoxedValue"); return false; } private static string Act(string guid, string id) { if (guid == "getstinky") { Body b = Player(); if (b == null) return "Start a run first."; object menu = Instance("GetStinky.StinkMenu"); MethodInfo set = menu != null ? AccessTools.Method(menu.GetType(), "SetDirt") : null; float v = id == "max" ? 100f : id == "plus" ? b.dirtyness + 25f : 0f; if (set != null) set.Invoke(menu, new object[] { b, v }); else b.dirtyness = Mathf.Clamp(v, 0f, 100f); return null; } if (guid == "nodurability" && id == "toggle") return SetConfig(guid, "General", "Enabled", ConfigBool(guid, "Enabled") ? "false" : "true"); if (guid == "saveanywhere" && id == "save") { Type r = AccessTools.TypeByName("SaveAnywhere.Runner"); Type s = AccessTools.TypeByName("SaveAnywhere.Slots"); if (r == null || s == null) return "Save Anywhere isn't loaded."; MethodInfo inRun = AccessTools.Method(r, "InRun"); if (inRun != null && !(bool)inRun.Invoke(null, null)) return "Start a run first."; MethodInfo pick = AccessTools.Method(s, "PickManualSlot"); if (pick != null && (int)pick.Invoke(null, null) <= 0) return "Pick a slot first: pause the game and click Save once."; MethodInfo save = AccessTools.Method(r, "SaveAsync"); if (save == null) return "This version of Save Anywhere can't be saved from the trainer."; save.Invoke(null, new object[] { false, 0, null }); return null; } return "Unknown action."; } public static bool Handle(string cmd, string[] p) { if (cmd == "MODS") { Link.Post(List()); return true; } if (cmd != "MODCFG" && cmd != "MODTAKE" && cmd != "MODACT") return false; if (p.Length < 3) return true; string err; try { if (cmd == "MODTAKE") err = Take(p[1], p[2] == "1"); else if (cmd == "MODACT") err = Act(p[1], p[2]); else { string[] f = p[2].Split(SEP); err = f.Length < 3 ? "Bad setting." : SetConfig(p[1], f[0], f[1], f[2]); } } catch (Exception e) { err = (e.InnerException ?? e).Message; } if (err != null) Link.Send("MODERR " + p[1] + " " + Clean(err)); Link.Post(List()); return true; } public static void Tick() { if (!Link.Connected || Time.unscaledTime < nextStat) return; nextStat = Time.unscaledTime + 1f; StringBuilder sb = new StringBuilder(); if (Plugin("getstinky") != null) { Body b = Player(); sb.Append("getstinky").Append(SEP).Append(b == null ? "Not in a run." : "Dirtiness " + Mathf.RoundToInt(b.dirtyness) + "%" + (ConfigBool("getstinky", "StayStinkyForever") ? " (locked)" : "")); } if (Plugin("nodurability") != null) { if (sb.Length > 0) sb.Append(REC); sb.Append("nodurability").Append(SEP).Append(ConfigBool("nodurability", "Enabled") ? "No Durability is ON" : "No Durability is OFF"); } if (sb.Length > 0) Link.Post("MODSTAT " + sb); } } }