using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Pipes; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using BiggerLobbies; using BiggerLobbies.Integrations; using BiggerLobbies.Utils; using HarmonyLib; using Il2Cpp; using Il2CppFishNet; using Il2CppFishNet.Connection; using Il2CppFishNet.Managing.Server; using Il2CppFishNet.Managing.Transporting; using Il2CppFishNet.Transporting; using Il2CppFishNet.Transporting.Multipass; using Il2CppFishySteamworks; using Il2CppFishySteamworks.Server; using Il2CppInterop.Runtime.InteropTypes; using Il2CppInterop.Runtime.InteropTypes.Arrays; using Il2CppScheduleOne.AvatarFramework; using Il2CppScheduleOne.Core.Items.Framework; using Il2CppScheduleOne.DevUtilities; using Il2CppScheduleOne.GameTime; using Il2CppScheduleOne.Growing; using Il2CppScheduleOne.ItemFramework; using Il2CppScheduleOne.NPCs.Behaviour; using Il2CppScheduleOne.Networking; using Il2CppScheduleOne.ObjectScripts; using Il2CppScheduleOne.Persistence; using Il2CppScheduleOne.Persistence.Datas; using Il2CppScheduleOne.Platform; using Il2CppScheduleOne.PlayerScripts; using Il2CppScheduleOne.State; using Il2CppScheduleOne.UI; using Il2CppScheduleOne.UI.MainMenu; using Il2CppScheduleOne.UI.Multiplayer; using Il2CppSteamworks; using Il2CppSystem; using Il2CppSystem.Collections.Generic; using Il2CppSystem.Reflection; using Il2CppTMPro; using MelonLoader; using MelonLoader.Preferences; using MelonLoader.Utils; using Microsoft.CodeAnalysis; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Controls; using UnityEngine.Rendering; using UnityEngine.SceneManagement; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: MelonInfo(typeof(Core), "BiggerLobbies", "2.0.0", "Bars", null)] [assembly: MelonGame("TVGS", "Schedule I")] [assembly: MelonIncompatibleAssemblies(new string[] { "ModManager&PhoneApp" })] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("BiggerLobbies_Il2cpp")] [assembly: AssemblyConfiguration("Il2cpp")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+19afa723c03a18bac3568b8fe811fc6c8cf8e1c8")] [assembly: AssemblyProduct("BiggerLobbies_Il2cpp")] [assembly: AssemblyTitle("BiggerLobbies_Il2cpp")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [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 BiggerLobbies { public class Core : MelonMod { public static Core? Instance { get; private set; } public override void OnInitializeMelon() { Instance = this; HarmonyPatches.SetModInstance(this); AutoSave.Init(); } public override void OnUpdate() { AutoSave.Update(); DebugDummies.Update(); DepartedPlayers.Update(); HostSettingsMenu.Update(); DiscordPresence.Update(); } public override void OnSceneWasInitialized(int buildIndex, string sceneName) { DebugDummies.OnSceneLoaded(sceneName); HostSettingsMenu.OnSceneLoaded(sceneName); } public override void OnApplicationQuit() { DiscordPresence.Shutdown(); Instance = null; } } } namespace BiggerLobbies.Utils { public static class Constants { public static class Game { public const string GAME_STUDIO = "TVGS"; public const string GAME_NAME = "Schedule I"; } public const string MOD_NAME = "BiggerLobbies"; public const string MOD_VERSION = "2.0.0"; public const string MOD_AUTHOR = "Bars"; public const int MAX_PLAYERS = 20; public const int VANILLA_LIMIT = 4; } public static class Log { private static MelonPreferences_Entry? _diag; public static bool Verbose => _diag?.Value ?? false; public static void Init(MelonPreferences_Category cat) { _diag = cat.CreateEntry("DiagnosticLog", false, "Diagnostic log", "Writes detailed info lines to the MelonLoader log (lobby events, kicks, bans, saves). Leave off unless you're reporting a problem. Warnings and errors are always logged.", false, false, (ValueValidator)null, (string)null); } public static void Info(string s) { if (Verbose) { MelonLogger.Msg(s); } } } public static class MiniJson { public static object? Parse(string s) { int i = 0; object result = Value(s, ref i); Ws(s, ref i); if (i != s.Length) { throw new FormatException($"unexpected text at {i}"); } return result; } private static void Ws(string s, ref int i) { while (i < s.Length && char.IsWhiteSpace(s[i])) { i++; } } private static object? Value(string s, ref int i) { Ws(s, ref i); if (i >= s.Length) { throw new FormatException("unexpected end"); } switch (s[i]) { case '{': return Obj(s, ref i); case '[': return Arr(s, ref 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; } return Num(s, ref i); } } private static bool Word(string s, ref int i, string w) { if (string.CompareOrdinal(s, i, w, 0, w.Length) != 0) { return false; } i += w.Length; return true; } private static Dictionary Obj(string s, ref int i) { Dictionary dictionary = new Dictionary(); i++; Ws(s, ref i); if (i < s.Length && s[i] == '}') { i++; return dictionary; } while (true) { Ws(s, ref i); if (i >= s.Length || s[i] != '"') { throw new FormatException($"expected a key at {i}"); } string key = Str(s, ref i); Ws(s, ref i); if (i >= s.Length || s[i] != ':') { throw new FormatException($"expected ':' at {i}"); } i++; dictionary[key] = Value(s, ref i); Ws(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}"); } private static List Arr(string s, ref int i) { List list = new List(); i++; Ws(s, ref i); if (i < s.Length && s[i] == ']') { i++; return list; } while (true) { list.Add(Value(s, ref i)); Ws(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}"); } 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 'n': stringBuilder.Append('\n'); break; case 't': stringBuilder.Append('\t'); break; case 'r': stringBuilder.Append('\r'); break; case 'b': stringBuilder.Append('\b'); break; case 'f': stringBuilder.Append('\f'); break; case 'u': { if (i + 4 > s.Length || !int.TryParse(s.Substring(i, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var result)) { throw new FormatException($"bad \\u escape at {i}"); } stringBuilder.Append((char)result); i += 4; break; } default: stringBuilder.Append(c2); break; } } throw new FormatException("unterminated string"); } private static double Num(string s, ref int i) { int num = i; while (i < s.Length && "+-0123456789.eE".IndexOf(s[i]) >= 0) { i++; } if (i == num || !double.TryParse(s.Substring(num, i - num), NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { throw new FormatException($"bad value at {num}"); } return result; } public static string Quote(string v) { StringBuilder stringBuilder = new StringBuilder("\""); string text = v ?? ""; foreach (char c in text) { switch (c) { case '"': stringBuilder.Append("\\\""); continue; case '\\': stringBuilder.Append("\\\\"); continue; case '\n': stringBuilder.Append("\\n"); continue; case '\r': stringBuilder.Append("\\r"); continue; case '\t': stringBuilder.Append("\\t"); continue; } if (c < ' ') { StringBuilder stringBuilder2 = stringBuilder.Append("\\u"); int num = c; stringBuilder2.Append(num.ToString("x4")); } else { stringBuilder.Append(c); } } return stringBuilder.Append('"').ToString(); } public static string Number(double v) { return v.ToString("R", CultureInfo.InvariantCulture); } public static string Canonical(object? v) { if (v != null) { if (!(v is bool)) { if (!(v is double v2)) { if (!(v is string v3)) { Dictionary dictionary = v as Dictionary; if (dictionary == null) { if (v is List source) { return "[" + string.Join(",", source.Select(Canonical)) + "]"; } return Quote(v.ToString() ?? ""); } return "{" + string.Join(",", from k in dictionary.Keys.OrderBy((string k) => k, StringComparer.Ordinal) select Quote(k) + ":" + Canonical(dictionary[k])) + "}"; } return Quote(v3); } return Number(v2); } return ((bool)v) ? "true" : "false"; } return "null"; } public static string Str(Dictionary o, string key) { object value; return (o.TryGetValue(key, out value) && value is string text) ? text : ""; } public static double Num(Dictionary o, string key) { object value; return (o.TryGetValue(key, out value) && value is double num) ? num : 0.0; } } } namespace BiggerLobbies.Integrations { [HarmonyPatch] public static class HarmonyPatches { private static Core? _modInstance; private static LobbyInterface? _ui; public static void SetModInstance(Core modInstance) { _modInstance = modInstance; } [HarmonyPrefix] [HarmonyPatch(typeof(Lobby), "TryOpenInviteInterface")] private static bool Lobby_TryOpenInviteInterface_Prefix(Lobby __instance) { try { if (!__instance.IsInLobby || __instance.PlayerCount < 4) { return true; } if (__instance.PlayerCount >= LobbySize.MaxPlayers) { MelonLogger.Warning("Lobby already at max capacity!"); return false; } ILobbyService lobbyService = __instance._lobbyService; SteamLobbyService val = ((lobbyService != null) ? ((Il2CppObjectBase)lobbyService).TryCast() : null); if (val == null) { return true; } val.OpenInviteUI(); return false; } catch (Exception arg) { MelonLogger.Error($"Failed to patch TryOpenInviteInterface: {arg}"); return true; } } private static void EnsurePlayersArray(SteamLobbyService svc) { //IL_0043: Unknown result type (might be due to invalid IL or missing references) Il2CppStructArray players = svc._players; if (players != null && ((Il2CppArrayBase)(object)players).Length >= 250) { return; } Il2CppStructArray val = new Il2CppStructArray(250L); if (players != null) { for (int i = 0; i < ((Il2CppArrayBase)(object)players).Length; i++) { ((Il2CppArrayBase)(object)val)[i] = ((Il2CppArrayBase)(object)players)[i]; } } svc._players = val; } [HarmonyPostfix] [HarmonyPatch(typeof(SteamLobbyService), "Initialize")] private static void Service_Initialize_Postfix(SteamLobbyService __instance) { try { EnsurePlayersArray(__instance); } catch (Exception arg) { MelonLogger.Error($"Failed to resize players array: {arg}"); } } [HarmonyPrefix] [HarmonyPatch(typeof(SteamLobbyService), "UpdateLobbyMembers")] private static void Service_UpdateLobbyMembers_Prefix(SteamLobbyService __instance) { try { EnsurePlayersArray(__instance); } catch (Exception arg) { MelonLogger.Error($"Failed to resize players array: {arg}"); } } [HarmonyPrefix] [HarmonyPatch(typeof(SteamLobbyService), "CreateLobby")] private static void Service_CreateLobby_Prefix(SteamLobbyService __instance, ref int maxPlayers) { if (maxPlayers < LobbySize.MaxPlayers) { maxPlayers = LobbySize.MaxPlayers; } try { EnsurePlayersArray(__instance); } catch (Exception arg) { MelonLogger.Error($"Failed to resize players array: {arg}"); } } [HarmonyPostfix] [HarmonyPatch(typeof(SteamLobbyService), "OnLobbyCreated")] private static void Service_OnLobbyCreated_Postfix(LobbyCreated_t result) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Invalid comparison between Unknown and I4 //IL_0019: 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_003e: 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_005d: Unknown result type (might be due to invalid IL or missing references) try { if ((int)result.m_eResult == 1) { CSteamID val = default(CSteamID); ((CSteamID)(ref val))..ctor(result.m_ulSteamIDLobby); string text = LobbySize.MaxPlayers.ToString(); SteamMatchmaking.SetLobbyMemberLimit(val, LobbySize.MaxPlayers); SteamMatchmaking.SetLobbyData(val, "max_players", text); SteamMatchmaking.SetLobbyData(val, "num_slots", text); Log.Info($"Lobby {result.m_ulSteamIDLobby} created with {LobbySize.MaxPlayers} slots"); } } catch (Exception arg) { MelonLogger.Error($"Failed to set lobby limits: {arg}"); } } [HarmonyPostfix] [HarmonyPatch(typeof(LobbyInterface), "Start")] private static void LobbyInterface_Start_Postfix(LobbyInterface __instance) { try { ExpandSlots(__instance); } catch (Exception arg) { MelonLogger.Error($"Failed to expand lobby UI: {arg}"); } } public static void RefreshLobbyScreen() { try { if (!((Object)(object)_ui == (Object)null) && !((Il2CppObjectBase)_ui).WasCollected) { ExpandSlots(_ui); _ui.UpdatePlayers(); _ui.UpdateButtons(); } } catch (Exception ex) { MelonLogger.Warning("Couldn't refresh the lobby screen: " + ex.Message); } } private static void ExpandSlots(LobbyInterface ui) { _ui = ui; GridLayoutGroup componentInChildren = ((Component)ui).GetComponentInChildren(true); if ((Object)(object)componentInChildren == (Object)null) { MelonLogger.Error("Could not find GridLayoutGroup in LobbyInterface"); return; } Transform transform = ((Component)componentInChildren).transform; if (transform.childCount < 2) { MelonLogger.Warning("Lobby UI has no player slot to clone"); return; } int num = transform.childCount - 1; Transform child = transform.GetChild(1); for (int i = num; i < LobbySize.MaxPlayers; i++) { GameObject val = Object.Instantiate(((Component)child).gameObject, transform); ((Object)val).name = $"{((Object)((Component)child).gameObject).name} ({transform.childCount - 1})"; } LobbySize.RememberGrid(componentInChildren); int num2 = transform.childCount - 1; Il2CppReferenceArray val2 = new Il2CppReferenceArray((long)num2); for (int j = 1; j < transform.childCount; j++) { ((Il2CppArrayBase)(object)val2)[j - 1] = ((Component)transform.GetChild(j)).GetComponent(); } ui.PlayerSlots = val2; UpdateTitle(ui); try { ui.UpdateUI(); } catch { } } private static void UpdateTitle(LobbyInterface ui, int hidden = 0, int fake = 0) { if (!((Object)(object)ui.Lobby == (Object)null) && !((Object)(object)ui.LobbyTitle == (Object)null)) { string text = ((hidden > 0) ? $" +{hidden}" : ""); string text2 = ((fake > 0) ? " [test]" : ""); if (LobbySize.MaxPlayers > 20) { ((TMP_Text)ui.LobbyTitle).enableWordWrapping = false; } ((TMP_Text)ui.LobbyTitle).text = $"Lobby ({ui.Lobby.PlayerCount + fake}/{LobbySize.MaxPlayers}){text}{text2}"; } } private static int CountActive(Il2CppReferenceArray? slots) { int num = 0; if (slots != null) { for (int i = 0; i < ((Il2CppArrayBase)(object)slots).Length; i++) { if ((Object)(object)((Il2CppArrayBase)(object)slots)[i] != (Object)null && ((Component)((Il2CppArrayBase)(object)slots)[i]).gameObject.activeSelf) { num++; } } } return num; } [HarmonyPostfix] [HarmonyPatch(typeof(LobbyInterface), "UpdatePlayers")] private static void LobbyInterface_UpdatePlayers_Postfix(LobbyInterface __instance) { try { int hidden = 0; int num = 0; int num2 = 0; try { Il2CppReferenceArray playerSlots = __instance.PlayerSlots; if (LobbySize.FakePlayers > 0) { int num3 = CountActive(playerSlots); num = LobbySize.ShowFakePlayers(playerSlots); num2 = num - (CountActive(playerSlots) - num3); } hidden = LobbySize.FitRow(playerSlots) + num2; } catch (Exception arg) { MelonLogger.Error($"Failed to fit lobby row: {arg}"); } UpdateTitle(__instance, hidden, num); } catch (Exception arg2) { MelonLogger.Error($"Failed to update lobby title: {arg2}"); } } [HarmonyPostfix] [HarmonyPatch(typeof(LobbyInterface), "UpdateButtons")] private static void LobbyInterface_UpdateButtons_Postfix(LobbyInterface __instance) { try { if (!((Object)(object)__instance.Lobby == (Object)null) && !((Object)(object)__instance.InviteButton == (Object)null)) { ((Component)__instance.InviteButton).gameObject.SetActive(__instance.Lobby.IsHost && __instance.Lobby.PlayerCount < LobbySize.MaxPlayers); } } catch (Exception arg) { MelonLogger.Error($"Failed to patch UpdateButtons: {arg}"); } } } [HarmonyPatch] public static class LobbyDedupePatches { private static float _pendingSince = -1f; private const float PendingTimeout = 15f; private static bool _openInviteWhenReady; private static SteamLobbyService? _service; private static bool CreatePending => _pendingSince >= 0f && Time.realtimeSinceStartup - _pendingSince < 15f; private static void Log(string s) { BiggerLobbies.Utils.Log.Info("[diag] " + s); } private static bool ServiceInLobby() { try { return _service != null && _service.IsInLobby; } catch { return false; } } [HarmonyPostfix] [HarmonyPatch(typeof(SteamLobbyService), "Initialize")] private static void Svc_Initialize_Postfix(SteamLobbyService __instance) { _service = __instance; } [HarmonyPrefix] [HarmonyPatch(typeof(SteamMatchmaking), "CreateLobby")] private static bool Steam_CreateLobby_Prefix(ELobbyType eLobbyType, int cMaxMembers, ref SteamAPICall_t __result) { //IL_0057: 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) if (CreatePending || ServiceInLobby()) { Log($"Steam.CreateLobby BLOCKED duplicate (pending={CreatePending} inLobby={ServiceInLobby()})"); __result = SteamAPICall_t.Invalid; return false; } _pendingSince = Time.realtimeSinceStartup; Log($"Steam.CreateLobby type={eLobbyType} max={cMaxMembers}"); return true; } [HarmonyPostfix] [HarmonyPatch(typeof(SteamLobbyService), "OnLobbyCreated")] private static void Svc_OnLobbyCreated_Postfix() { _pendingSince = -1f; } [HarmonyPrefix] [HarmonyPatch(typeof(SteamLobbyService), "OpenInviteUI")] private static bool Svc_OpenInviteUI_Prefix(SteamLobbyService __instance) { _service = __instance; bool isInLobby = __instance.IsInLobby; Log($"Svc.OpenInviteUI inLobby={isInLobby} pending={CreatePending}"); if (isInLobby) { return true; } _openInviteWhenReady = true; if (!CreatePending) { try { __instance.CreateLobby(LobbySize.MaxPlayers); } catch (Exception arg) { MelonLogger.Error($"CreateLobby from OpenInviteUI failed: {arg}"); } } return false; } [HarmonyPostfix] [HarmonyPatch(typeof(SteamLobbyService), "OnLobbyEntered")] private static void Svc_OnLobbyEntered_Postfix(SteamLobbyService __instance) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) _pendingSince = -1f; if (!_openInviteWhenReady) { return; } _openInviteWhenReady = false; try { Log($"Opening deferred invite overlay for lobby {__instance._lobbySteamID.m_SteamID}"); __instance.OpenInviteUI(); } catch (Exception arg) { MelonLogger.Error($"Deferred OpenInviteUI failed: {arg}"); } } [HarmonyPrefix] [HarmonyPatch(typeof(SteamMatchmaking), "JoinLobby")] private static void Steam_JoinLobby(CSteamID steamIDLobby) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) Log($"Steam.JoinLobby {steamIDLobby.m_SteamID}"); } [HarmonyPrefix] [HarmonyPatch(typeof(SteamMatchmaking), "LeaveLobby")] private static void Steam_LeaveLobby(CSteamID steamIDLobby) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) Log($"Steam.LeaveLobby {steamIDLobby.m_SteamID}"); } [HarmonyPrefix] [HarmonyPatch(typeof(SteamFriends), "ActivateGameOverlayInviteDialog")] private static void Steam_InviteDialog(CSteamID steamIDLobby) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) Log($"Steam.ActivateGameOverlayInviteDialog {steamIDLobby.m_SteamID}"); } } [HarmonyPatch] public static class DiagnosticPatches { private static string Id(Il2CppObjectBase? o) { return (o == null) ? "null" : o.Pointer.ToString("X"); } private static void Log(string s) { BiggerLobbies.Utils.Log.Info("[diag] " + s); } [HarmonyPrefix] [HarmonyPatch(typeof(Lobby), "Awake")] private static void Lobby_Awake(Lobby __instance) { Log("Lobby.Awake lobby=" + Id((Il2CppObjectBase?)(object)__instance)); } [HarmonyPrefix] [HarmonyPatch(typeof(Lobby), "Start")] private static void Lobby_Start(Lobby __instance) { Log("Lobby.Start lobby=" + Id((Il2CppObjectBase?)(object)__instance)); } [HarmonyPostfix] [HarmonyPatch(typeof(Lobby), "CreateLobbyService")] private static void Lobby_CreateLobbyService(Lobby __instance) { Log("Lobby.CreateLobbyService lobby=" + Id((Il2CppObjectBase?)(object)__instance) + " service=" + Id((Il2CppObjectBase?)(object)__instance._lobbyService)); } [HarmonyPrefix] [HarmonyPatch(typeof(Lobby), "CreateLobby")] private static void Lobby_CreateLobby(Lobby __instance) { Log($"Lobby.CreateLobby lobby={Id((Il2CppObjectBase?)(object)__instance)} inLobby={__instance.IsInLobby}"); } [HarmonyPrefix] [HarmonyPatch(typeof(Lobby), "TryOpenInviteInterface")] private static void Lobby_TryOpenInvite(Lobby __instance) { Log($"Lobby.TryOpenInviteInterface lobby={Id((Il2CppObjectBase?)(object)__instance)} inLobby={__instance.IsInLobby} count={__instance.PlayerCount}"); } [HarmonyPrefix] [HarmonyPatch(typeof(Lobby), "SendLobbyMessage")] private static void Lobby_SendLobbyMessage(string message) { Log("Lobby.SendLobbyMessage '" + message + "'"); } [HarmonyPrefix] [HarmonyPatch(typeof(Lobby), "SetLobbyData")] private static void Lobby_SetLobbyData(string key, string value) { Log("Lobby.SetLobbyData " + key + "=" + value); } [HarmonyPrefix] [HarmonyPatch(typeof(SteamLobbyService), "Initialize")] private static void Svc_Initialize(SteamLobbyService __instance) { Log("Svc.Initialize service=" + Id((Il2CppObjectBase?)(object)__instance)); } [HarmonyPrefix] [HarmonyPatch(typeof(SteamLobbyService), "CreateLobby")] private static void Svc_CreateLobby(SteamLobbyService __instance, int maxPlayers) { Log($"Svc.CreateLobby service={Id((Il2CppObjectBase?)(object)__instance)} maxPlayers={maxPlayers} inLobby={__instance.IsInLobby}"); } [HarmonyPrefix] [HarmonyPatch(typeof(SteamLobbyService), "OnLobbyCreated")] private static void Svc_OnLobbyCreated(SteamLobbyService __instance, LobbyCreated_t result) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0016: 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) Log($"Svc.OnLobbyCreated service={Id((Il2CppObjectBase?)(object)__instance)} lobby={result.m_ulSteamIDLobby} result={result.m_eResult}"); } [HarmonyPrefix] [HarmonyPatch(typeof(SteamLobbyService), "OnLobbyEntered")] private static void Svc_OnLobbyEntered(SteamLobbyService __instance, LobbyEnter_t result) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) Log($"Svc.OnLobbyEntered service={Id((Il2CppObjectBase?)(object)__instance)} lobby={result.m_ulSteamIDLobby} response={result.m_EChatRoomEnterResponse}"); } [HarmonyPrefix] [HarmonyPatch(typeof(SteamLobbyService), "JoinLobby")] private static void Svc_JoinLobby(SteamLobbyService __instance) { Log("Svc.JoinLobby service=" + Id((Il2CppObjectBase?)(object)__instance)); } [HarmonyPrefix] [HarmonyPatch(typeof(SteamLobbyService), "LeaveLobby")] private static void Svc_LeaveLobby(SteamLobbyService __instance) { Log("Svc.LeaveLobby service=" + Id((Il2CppObjectBase?)(object)__instance)); } [HarmonyPrefix] [HarmonyPatch(typeof(SteamLobbyService), "SendMessage")] private static void Svc_SendMessage(SteamLobbyService __instance, string message) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) Log($"Svc.SendMessage service={Id((Il2CppObjectBase?)(object)__instance)} '{message}' lobby={__instance._lobbySteamID.m_SteamID}"); } [HarmonyPrefix] [HarmonyPatch(typeof(SteamLobbyService), "SetLobbyData")] private static void Svc_SetLobbyData(SteamLobbyService __instance, string key, string value) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) Log($"Svc.SetLobbyData service={Id((Il2CppObjectBase?)(object)__instance)} {key}={value} lobby={__instance._lobbySteamID.m_SteamID}"); } [HarmonyPrefix] [HarmonyPatch(typeof(SteamLobbyService), "UpdateLobbyMembers")] private static void Svc_UpdateMembers(SteamLobbyService __instance) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) Log($"Svc.UpdateLobbyMembers service={Id((Il2CppObjectBase?)(object)__instance)} lobby={__instance._lobbySteamID.m_SteamID}"); } [HarmonyPrefix] [HarmonyPatch(typeof(SteamLobbyService), "PlayerEnterOrLeave")] private static void Svc_PlayerEnterOrLeave(SteamLobbyService __instance) { Log("Svc.PlayerEnterOrLeave service=" + Id((Il2CppObjectBase?)(object)__instance)); } [HarmonyPrefix] [HarmonyPatch(typeof(SteamLobbyService), "OnLobbyChatMessage")] private static void Svc_OnChat(SteamLobbyService __instance) { Log("Svc.OnLobbyChatMessage service=" + Id((Il2CppObjectBase?)(object)__instance)); } } public static class AutoSave { private static MelonPreferences_Category? _cat; private static MelonPreferences_Entry? _enabled; private static MelonPreferences_Entry? _minutes; private static MelonPreferences_Entry? _playerSaveEnabled; private static MelonPreferences_Entry? _playerSaveSeconds; private static float _nextCheck; private static float _nextPlayerSave; private static int _lastPlayerCount = -1; private static readonly HashSet _remoteCodes = new HashSet(); public static bool WorldEnabled { get { return _enabled?.Value ?? false; } set { if (_enabled != null) { _enabled.Value = value; } } } public static int WorldMinutes { get { return Math.Max(1, _minutes?.Value ?? 5); } set { if (_minutes != null) { _minutes.Value = Math.Clamp(value, 1, 60); } } } public static bool PlayersEnabled { get { return _playerSaveEnabled?.Value ?? false; } set { if (_playerSaveEnabled != null) { _playerSaveEnabled.Value = value; } } } public static int PlayerSeconds { get { return Math.Max(10, _playerSaveSeconds?.Value ?? 30); } set { if (_playerSaveSeconds != null) { _playerSaveSeconds.Value = Math.Clamp(value, 10, 300); } } } public static void Init() { _cat = MelonPreferences.CreateCategory("BiggerLobbies"); Log.Init(_cat); LobbySize.Init(_cat); DebugDummies.Init(_cat); LobbyPrivacy.Init(_cat); BanList.Init(_cat); Whitelist.Init(_cat); Crews.Init(_cat); ModHandshake.Init(_cat); DiscordPresence.Init(_cat); HostSettingsMenu.Init(_cat); _enabled = _cat.CreateEntry("AutoSaveEnabled", true, "Host autosave enabled", "As host, periodically run the game's normal save so a crash doesn't lose progress since the last sleep.", false, false, (ValueValidator)null, (string)null); _minutes = _cat.CreateEntry("AutoSaveMinutes", 5, "Autosave interval (minutes)", (string)null, false, false, (ValueValidator)null, (string)null); _playerSaveEnabled = _cat.CreateEntry("PlayerSaveEnabled", true, "Client player saves enabled", "As host, save each connected client's money, inventory and position more often than the full autosave.", false, false, (ValueValidator)null, (string)null); _playerSaveSeconds = _cat.CreateEntry("PlayerSaveSeconds", 30, "Client player save interval (seconds)", (string)null, false, false, (ValueValidator)null, (string)null); GrowSyncFix.Init(_cat); LateJoinFix.Init(_cat); AlwaysHostLobby.Init(_cat); } private static bool Hosting() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) Scene activeScene = SceneManager.GetActiveScene(); return ((Scene)(ref activeScene)).name == "Main" && InstanceFinder.IsServer; } public static float? SecondsSinceLastSave() { try { if (!Hosting()) { return null; } SaveManager instance = Singleton.Instance; return ((Object)(object)instance == (Object)null) ? ((float?)null) : new float?(instance.SecondsSinceLastSave); } catch { return null; } } public static string SaveNow() { try { if (!Hosting()) { return "Load a save as host to save"; } SaveManager instance = Singleton.Instance; if ((Object)(object)instance == (Object)null) { return "The game isn't ready to save"; } if (instance.IsSaving) { return "Already saving"; } SleepController instance2 = NetworkSingleton.Instance; if ((Object)(object)instance2 != (Object)null && instance2.IsSleepInProgress) { return "Can't save while everyone's sleeping"; } instance.Save(); return "Saved"; } catch (Exception arg) { MelonLogger.Error($"Save now failed: {arg}"); return "Save failed. See the log"; } } public static void Update() { //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) float realtimeSinceStartup = Time.realtimeSinceStartup; if (realtimeSinceStartup < _nextCheck) { return; } _nextCheck = realtimeSinceStartup + 5f; try { Scene activeScene = SceneManager.GetActiveScene(); if (((Scene)(ref activeScene)).name != "Main" || !InstanceFinder.IsServer) { return; } SaveManager instance = Singleton.Instance; if ((Object)(object)instance == (Object)null || instance.IsSaving) { return; } SleepController instance2 = NetworkSingleton.Instance; if (!((Object)(object)instance2 != (Object)null) || !instance2.IsSleepInProgress) { if (ClientLeft()) { Log.Info("A player left; saving now"); instance.Save(); } else if (!TryFullSave(instance)) { TrySavePlayers(realtimeSinceStartup); } } } catch (Exception arg) { MelonLogger.Error($"Autosave failed: {arg}"); _nextCheck = realtimeSinceStartup + 60f; } } private static bool ClientLeft() { if (_enabled == null || !_enabled.Value) { return false; } List playerList = Player.PlayerList; if (playerList == null) { return false; } HashSet hashSet = new HashSet(); for (int i = 0; i < playerList.Count; i++) { Player val = playerList[i]; if (!((Object)(object)val == (Object)null) && !val.IsLocalPlayer && !string.IsNullOrEmpty(val.PlayerCode)) { hashSet.Add(val.PlayerCode); } } bool result = false; foreach (string remoteCode in _remoteCodes) { if (!hashSet.Contains(remoteCode)) { result = true; break; } } _remoteCodes.Clear(); _remoteCodes.UnionWith(hashSet); return result; } private static bool TryFullSave(SaveManager save) { if (_enabled == null || !_enabled.Value) { return false; } float num = (float)Math.Max(1, _minutes.Value) * 60f; if (save.SecondsSinceLastSave < num) { return false; } Log.Info($"Autosaving (last save {save.SecondsSinceLastSave / 60f:0.0} min ago)"); save.Save(); return true; } private static void TrySavePlayers(float now) { if (_playerSaveEnabled == null || !_playerSaveEnabled.Value || now < _nextPlayerSave) { return; } _nextPlayerSave = now + (float)Math.Max(10, _playerSaveSeconds.Value); PlayerManager instance = Singleton.Instance; List playerList = Player.PlayerList; if ((Object)(object)instance == (Object)null || playerList == null) { return; } int num = 0; for (int i = 0; i < playerList.Count; i++) { Player val = playerList[i]; if (!((Object)(object)val == (Object)null) && !val.IsLocalPlayer && !string.IsNullOrEmpty(val.PlayerCode)) { try { instance.SavePlayer(val); num++; } catch (Exception arg) { MelonLogger.Error($"Saving player {val.PlayerCode} failed: {arg}"); } } } if (num != _lastPlayerCount) { if (num > 0) { Log.Info($"Saving {num} connected player(s) every {Math.Max(10, _playerSaveSeconds.Value)} s"); } _lastPlayerCount = num; } } } public static class GrowSyncFix { [HarmonyPatch(typeof(WaterPotBehaviour), "OnActionSuccess")] private static class WaterPotPatch { private static void Postfix(WaterPotBehaviour __instance) { if (!Server) { return; } try { PushMoisture(((GrowContainerBehaviour)__instance)._growContainer); } catch (Exception arg) { MelonLogger.Error($"Plant sync (botanist water) failed: {arg}"); } } } [HarmonyPatch(typeof(GrowContainer), "OnTimeSkipped")] private static class TimeSkipPatch { private static void Postfix(GrowContainer __instance) { if (!Server) { return; } try { PushMoisture(__instance); } catch (Exception arg) { MelonLogger.Error($"Plant sync (time skip) failed: {arg}"); } } } [HarmonyPatch(typeof(Pot), "OnMinPass")] private static class MinPassPatch { private static readonly Dictionary Ticks = new Dictionary(); private static void Postfix(Pot __instance) { if (!Server) { return; } int num = _minutes?.Value ?? 30; if (num <= 0) { return; } try { int instanceID = ((Object)__instance).GetInstanceID(); Ticks.TryGetValue(instanceID, out var value); if (++value < num) { Ticks[instanceID] = value; return; } Ticks[instanceID] = (instanceID & 0x7FFFFFFF) % 7; PushMoisture((GrowContainer?)(object)__instance); Plant plant = __instance.Plant; if ((Object)(object)plant != (Object)null) { __instance.SetGrowthProgress_Client(plant.NormalizedGrowthProgress); } } catch (Exception arg) { MelonLogger.Error($"Plant sync (resync) failed: {arg}"); } } } private static MelonPreferences_Entry? _enabled; private static MelonPreferences_Entry? _minutes; private static bool Server { get { try { return _enabled != null && _enabled.Value && InstanceFinder.IsServer; } catch { return false; } } } public static void Init(MelonPreferences_Category cat) { _enabled = cat.CreateEntry("PlantSyncEnabled", true, "Plant sync enabled", "As host, send pot water level and growth progress to clients so everyone sees the same values.", false, false, (ValueValidator)null, (string)null); _minutes = cat.CreateEntry("PlantSyncMinutes", 30, "Plant resync interval (in-game minutes)", (string)null, false, false, (ValueValidator)null, (string)null); } private static void PushMoisture(GrowContainer? c) { if (!((Object)(object)c == (Object)null)) { c.SetMoistureData_Client((NetworkConnection)null, c._currentMoistureAmount); } } } public static class LateJoinFix { [HarmonyPatch(typeof(SteamLobbyService), "PlayerEnterOrLeave")] private static class PlayerEnterOrLeavePatch { private static void Postfix(SteamLobbyService __instance, LobbyChatUpdate_t result) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) try { if (_enabled != null && _enabled.Value && __instance.IsHost && (result.m_rgfChatMemberStateChange & 1) != 0) { LoadManager instance = Singleton.Instance; if (!((Object)(object)instance == (Object)null) && instance.IsGameLoaded && !_pending) { _pending = true; MelonCoroutines.Start(SendReadySoon(__instance)); } } } catch (Exception arg) { MelonLogger.Error($"Late join check failed: {arg}"); } } } private static MelonPreferences_Entry? _enabled; private static bool _pending; private static float _lastSend = -999f; private const float FirstDelay = 2f; private const float MinSpacing = 5f; public static void Init(MelonPreferences_Category cat) { _enabled = cat.CreateEntry("LateJoinEnabled", true, "Late join enabled", "As host, let players join a game that has already started (re-sends the lobby 'ready' message when someone joins).", false, false, (ValueValidator)null, (string)null); } private static IEnumerator SendReadySoon(SteamLobbyService svc) { float now = Time.realtimeSinceStartup; float sendAt = Math.Max(now + 2f, _lastSend + 5f); while (Time.realtimeSinceStartup < sendAt) { yield return null; } _pending = false; try { if (svc.IsHost && svc.IsInLobby) { int members = SteamMatchmaking.GetNumLobbyMembers(svc._lobbySteamID); if (members <= 4) { Log.Info($"Player joined mid-game ({members} in lobby); the game connects them itself"); yield break; } _lastSend = Time.realtimeSinceStartup; svc.SetLobbyData("ready", "true"); svc.SendMessage("ready"); Log.Info("Player joined mid-game; re-sent lobby 'ready' so they can connect"); } } catch (Exception ex) { Exception e = ex; MelonLogger.Error($"Late join 'ready' re-send failed: {e}"); } } } [HarmonyPatch] public static class AlwaysHostLobby { [HarmonyPatch(typeof(LoadManager), "StartGame")] private static class StartGamePatch { private static bool Prefix(LoadManager __instance, SaveInfo info, bool allowLoadStacking, bool allowSaveBackup) { if (_resuming) { return true; } if (_waiting) { return false; } try { if (_enabled == null || !_enabled.Value) { return true; } Lobby instance = Singleton.Instance; if ((Object)(object)instance == (Object)null || instance.IsInLobby) { return true; } string text = WhyNotOnline(); if (text != null) { Log.Info("Always host lobby: " + text + "; loading solo"); return true; } Log.Info("Always host lobby: creating a Steam lobby before loading"); _waiting = true; _created = false; _failed = false; instance.CreateLobby(); MelonCoroutines.Start(WaitThenLoad(__instance, info, allowLoadStacking, allowSaveBackup)); return false; } catch (Exception arg) { MelonLogger.Error($"Always host lobby failed, loading solo: {arg}"); _waiting = false; return true; } } } private static MelonPreferences_Entry? _enabled; private const float TimeoutSeconds = 10f; private static bool _waiting; private static bool _resuming; private static bool _created; private static bool _failed; public static void Init(MelonPreferences_Category cat) { _enabled = cat.CreateEntry("AlwaysHostLobby", true, "Always host a lobby", "Create a Steam lobby automatically when loading a save, so friends can be invited or use Steam's Join Game at any time.", false, false, (ValueValidator)null, (string)null); } private static string? WhyNotOnline() { try { if (!SteamManager.Initialized) { return "Steam isn't initialised"; } if (!SteamAPI.IsSteamRunning()) { return "Steam isn't running"; } if (!SteamUser.BLoggedOn()) { return "not signed in to Steam (offline)"; } } catch (Exception ex) { return "Steam check failed (" + ex.Message + ")"; } return null; } [HarmonyPostfix] [HarmonyPatch(typeof(SteamLobbyService), "OnLobbyCreated")] private static void OnLobbyCreated_Postfix(LobbyCreated_t result) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Invalid comparison between Unknown and I4 //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) if (_waiting) { if ((int)result.m_eResult == 1) { _created = true; return; } _failed = true; MelonLogger.Warning($"Always host lobby: Steam couldn't create the lobby ({result.m_eResult})"); } } private static IEnumerator WaitThenLoad(LoadManager load, SaveInfo info, bool allowLoadStacking, bool allowSaveBackup) { float deadline = Time.realtimeSinceStartup + 10f; while (true) { bool inLobby = false; try { Lobby lobby = Singleton.Instance; if ((Object)(object)lobby != (Object)null) { ILobbyService lobbyService = lobby._lobbyService; SteamLobbyService svc = ((lobbyService != null) ? ((Il2CppObjectBase)lobbyService).TryCast() : null); inLobby = lobby.IsInLobby || (svc != null && svc.IsInLobby); } } catch { } if (inLobby || _created) { Log.Info("Always host lobby: lobby ready; loading as host"); break; } if (_failed) { Log.Info("Always host lobby: loading solo"); break; } if (Time.realtimeSinceStartup > deadline) { MelonLogger.Warning($"Always host lobby: no answer from Steam after {10f:0} s; loading solo"); break; } yield return null; } _waiting = false; _resuming = true; try { load.StartGame(info, allowLoadStacking, allowSaveBackup); } catch (Exception ex) { Exception e = ex; MelonLogger.Error($"Always host lobby: StartGame failed: {e}"); } finally { _resuming = false; } } } [HarmonyPatch] public static class StaleAuthFix { [HarmonyPrefix] [HarmonyPatch(typeof(FishNetSteamAuthenticator), "OnSteamAuthBroadcast")] private static bool OnSteamAuthBroadcast_Prefix(FishNetSteamAuthenticator __instance, NetworkConnection conn, SteamSessionAuthTicket auth) { //IL_01a8: Unknown result type (might be due to invalid IL or missing references) //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Invalid comparison between Unknown and I4 //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_0149: Unknown result type (might be due to invalid IL or missing references) try { if (conn == (NetworkConnection)null || auth == null) { return true; } if (BanList.RejectIfBanned(conn, auth.SteamId)) { return false; } if (Whitelist.RejectIfNotListed(conn, auth.SteamId)) { return false; } if (!conn.Authenticated && auth.SteamId != 0) { BanList.RecordLogin(conn.ClientId, auth.SteamId); KickNotice.Unhide(auth.SteamId); } if (conn.Authenticated) { ulong steamId = auth.SteamId; if (steamId == 0) { return true; } ulong num = BanList.VerifiedSteamId(conn.ClientId); if (num != 0L && num != steamId) { MelonLogger.Warning($"Connection {conn.ClientId} logged in again as a different Steam ID ({steamId}, was {num}); disconnecting"); try { conn.Disconnect(true); } catch { } return false; } PlatformAuth.EndAuthSession(new CSteamID(steamId)); EBeginAuthSessionResult val = PlatformAuth.BeginAuthSession(auth); if ((int)val > 0) { MelonLogger.Warning($"Connection {conn.ClientId} re-authentication failed ({val}); disconnecting"); return true; } __instance.SendAuthenticationResponse(conn, true); Log.Info($"Connection {conn.ClientId} sent authentication again; re-authenticated with Steam ({val})"); return false; } ulong steamId2 = auth.SteamId; if (steamId2 == 0) { return true; } PlatformAuth.EndAuthSession(new CSteamID(steamId2)); Log.Info($"Cleared any old Steam auth session for {steamId2} before authenticating connection {conn.ClientId}"); } catch (Exception arg) { MelonLogger.Error($"Steam auth fix failed: {arg}"); } return true; } [HarmonyPostfix] [HarmonyPatch(typeof(ServerManager), "Transport_OnRemoteConnectionState")] private static void Transport_OnRemoteConnectionState_Postfix(RemoteConnectionStateArgs args) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Invalid comparison between Unknown and I4 //IL_000f: Unknown result type (might be due to invalid IL or missing references) try { if ((int)args.ConnectionState == 0) { BanList.ForgetLogin(args.ConnectionId); } } catch (Exception ex) { MelonLogger.Warning("Couldn't clear a closed connection's login: " + ex.Message); } } } [HarmonyPatch] public static class LobbySize { public const int Min = 4; public const int Max = 250; public const int Tested = 20; private static MelonPreferences_Entry? _entry; private static MelonPreferences_Entry? _fake; private static int _lastLogged = -1; public const int PerRow = 20; public const int MaxRows = 5; private static GridLayoutGroup? _grid; private static float _cellX = 75f; private static float _origSpacingX = -150f; private static float _spacingY; private static bool _loggedLayout; public static int FakePlayers => Math.Clamp(_fake?.Value ?? 0, 0, 250); public static int MaxPlayers { get; private set; } = 20; public static int LiveMin => Math.Max(4, HostLobby.MemberCount()); public static int MaxShown => 100; public static GridLayoutGroup? Grid => _grid; public static void Init(MelonPreferences_Category cat) { _entry = cat.CreateEntry("MaxPlayers", 20, "Max players", $"Lobby size, {4} to {250}. Default {20}. If you edit this file, restart the game. The host panel changes it without a restart.", false, false, (ValueValidator)null, (string)null); int value = _entry.Value; int num = Math.Clamp(value, 4, 250); if (num != value) { MelonLogger.Warning($"MaxPlayers {value} is outside {4}-{250}; using {num}"); } MaxPlayers = num; _fake = cat.CreateEntry("DebugFakePlayers", 0, "Debug: fake lobby players", "Testing only. Shows this many placeholder players on the lobby screen to check the layout. They aren't real, aren't sent over the network and can't be invited. Leave at 0.", false, false, (ValueValidator)null, (string)null); if (FakePlayers > 0) { MelonLogger.Warning($"DebugFakePlayers is {FakePlayers}: the lobby screen shows placeholder players for testing. Set it back to 0 to play normally."); } Log.Info($"Lobby size: {MaxPlayers} players"); } public static void EnsureTransportCapacity(string when) { try { TransportManager transportManager = InstanceFinder.TransportManager; Transport val = ((transportManager != null) ? transportManager.Transport : null); if ((Object)(object)val == (Object)null) { return; } Multipass val2 = ((Il2CppObjectBase)val).TryCast(); if (((val2 != null) ? val2._transports : null) != null) { List transports = val2._transports; for (int i = 0; i < transports.Count; i++) { RaiseSteamLimit(transports[i], when); } } else { RaiseSteamLimit(val, when); } } catch (Exception ex) { MelonLogger.Warning("Couldn't check the network transport's player limit: " + ex.Message); } } private static void RaiseSteamLimit(Transport? t, string when) { FishySteamworks val = ((t != null) ? ((Il2CppObjectBase)t).TryCast() : null); if ((Object)(object)val == (Object)null) { return; } int maximumClients = val._maximumClients; if (maximumClients < MaxPlayers) { val._maximumClients = (ushort)MaxPlayers; try { if (val._server != null) { ((Transport)val).SetMaximumClients(MaxPlayers); } } catch { } Log.Info($"Steam transport player limit raised from {maximumClients} to {MaxPlayers} ({when})"); _lastLogged = MaxPlayers; } else if (maximumClients != _lastLogged) { Log.Info($"Steam transport player limit is {maximumClients}; lobby size {MaxPlayers} fits ({when})"); _lastLogged = maximumClients; } } public static string SetLive(int requested) { //IL_0080: 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_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) int num = Math.Clamp(requested, LiveMin, 250); int maxPlayers = MaxPlayers; if (num == maxPlayers) { return $"Lobby size is {num}"; } MaxPlayers = num; if (_entry != null) { _entry.Value = num; MelonPreferences.Save(); } string text = "not hosting a Steam lobby yet"; if (HostLobby.TryGet(out var lobby)) { bool flag = false; int num2 = -1; try { flag = SteamMatchmaking.SetLobbyMemberLimit(lobby, num); SteamMatchmaking.SetLobbyData(lobby, "max_players", num.ToString()); SteamMatchmaking.SetLobbyData(lobby, "num_slots", num.ToString()); num2 = SteamMatchmaking.GetLobbyMemberLimit(lobby); } catch (Exception ex) { MelonLogger.Warning("SetLobbyMemberLimit failed: " + ex.Message); } text = ((flag && num2 == num) ? $"Steam lobby limit is now {num2}" : string.Format("Steam {0} the change and reports {1}", flag ? "accepted" : "refused", num2)); } string text2 = SetSteamLimit(num); HarmonyPatches.RefreshLobbyScreen(); string s = $"Lobby size changed from {maxPlayers} to {num} while running: {text}; {text2}"; Log.Info(s); return $"Lobby size {num}. {text}"; } private static string SetSteamLimit(int n) { try { TransportManager transportManager = InstanceFinder.TransportManager; Transport val = ((transportManager != null) ? transportManager.Transport : null); if ((Object)(object)val == (Object)null) { return "no network transport yet"; } Multipass val2 = ((Il2CppObjectBase)val).TryCast(); FishySteamworks val3 = null; if (((val2 != null) ? val2._transports : null) != null) { for (int i = 0; i < val2._transports.Count; i++) { if (!((Object)(object)val3 == (Object)null)) { break; } Transport obj = val2._transports[i]; val3 = ((obj != null) ? ((Il2CppObjectBase)obj).TryCast() : null); } } else { val3 = ((Il2CppObjectBase)val).TryCast(); } if ((Object)(object)val3 == (Object)null) { return "no Steam transport found"; } val3._maximumClients = (ushort)n; _lastLogged = n; if (val3._server == null) { return $"transport limit {n} (server not started)"; } val3._server.SetMaximumClients(n); return $"transport limit now {val3._server.GetMaximumClients()}"; } catch (Exception ex) { return "transport limit not changed (" + ex.Message + ")"; } } [HarmonyPrefix] [HarmonyPatch(typeof(SteamLobbyService), "CreateLobby")] private static void CreateLobby_Prefix() { EnsureTransportCapacity("creating lobby"); } [HarmonyPrefix] [HarmonyPatch(typeof(LoadManager), "StartGame")] private static void StartGame_Prefix() { EnsureTransportCapacity("loading save"); } public static void RememberGrid(GridLayoutGroup grid) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0028: 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) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: 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_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Unknown result type (might be due to invalid IL or missing references) _grid = grid; _cellX = grid.cellSize.x; _origSpacingX = grid.spacing.x; _spacingY = grid.spacing.y; if (_loggedLayout) { return; } _loggedLayout = true; try { RectTransform component = ((Component)grid).GetComponent(); Log.Info($"[diag] lobby row: constraint={grid.constraint} count={grid.constraintCount} cell={grid.cellSize} spacing={grid.spacing} " + $"start={grid.startCorner}/{grid.startAxis} align={((LayoutGroup)grid).childAlignment} anchors={component.anchorMin}-{component.anchorMax} pos={component.anchoredPosition}"); } catch { } } public static int ShowFakePlayers(Il2CppReferenceArray? slots) { int fakePlayers = FakePlayers; if (fakePlayers <= 0 || slots == null) { return 0; } int num = 0; for (int i = 0; i < ((Il2CppArrayBase)(object)slots).Length; i++) { if (num >= fakePlayers) { break; } RectTransform val = ((Il2CppArrayBase)(object)slots)[i]; if (!((Object)(object)val == (Object)null) && !((Component)val).gameObject.activeSelf) { ((Component)val).gameObject.SetActive(true); num++; } } return fakePlayers; } private static void MoveInviteOutOfTable() { //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) try { if ((Object)(object)_grid == (Object)null || ((Component)_grid).transform.childCount == 0) { return; } RectTransform component = ((Component)_grid).GetComponent(); LayoutRebuilder.ForceRebuildLayoutImmediate(component); RectTransform component2 = ((Component)((Component)_grid).transform.GetChild(0)).GetComponent(); if (!((Object)(object)component2 == (Object)null)) { Vector2 anchoredPosition = component2.anchoredPosition; LayoutElement val = ((Component)component2).GetComponent(); if ((Object)(object)val == (Object)null) { val = ((Component)component2).gameObject.AddComponent(); } val.ignoreLayout = true; float num = 0f - (_cellX + _origSpacingX); component2.anchoredPosition = new Vector2(anchoredPosition.x - num, anchoredPosition.y); LayoutRebuilder.ForceRebuildLayoutImmediate(component); } } catch (Exception ex) { MelonLogger.Warning("Couldn't move the invite button out of the table: " + ex.Message); } } public static int FitRow(Il2CppReferenceArray? slots) { //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Invalid comparison between Unknown and I4 //IL_00ee: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_grid == (Object)null || slots == null) { return 0; } int num = 0; for (int i = 0; i < ((Il2CppArrayBase)(object)slots).Length; i++) { RectTransform val = ((Il2CppArrayBase)(object)slots)[i]; if (!((Object)(object)val == (Object)null) && ((Component)val).gameObject.activeSelf) { num++; if (num > MaxShown) { ((Component)val).gameObject.SetActive(false); } } } if (MaxPlayers <= 20) { return 0; } if ((int)_grid.constraint != 1 || _grid.constraintCount != 20) { _grid.constraint = (Constraint)1; _grid.constraintCount = 20; _grid.spacing = new Vector2(_origSpacingX, _spacingY); MoveInviteOutOfTable(); } return Math.Max(0, num - MaxShown); } } public static class DebugDummies { private static MelonPreferences_Entry? _count; private static readonly List _dummies = new List(); private static readonly List _phase = new List(); private static Vector3 _centre; private static float _spawnAfter = -1f; private static float _fpsWindowStart; private static float _minFps = float.MaxValue; private static int _frames; public static int Count => Math.Clamp(_count?.Value ?? 0, 0, 250); public static void Init(MelonPreferences_Category cat) { _count = cat.CreateEntry("DebugDummyPlayers", 0, "Debug: dummy characters", "Testing only. After a save loads, spawns this many copies of your character around you and logs the frame rate every 10 s. They aren't real players, aren't networked and aren't saved. Leave at 0.", false, false, (ValueValidator)null, (string)null); if (Count > 0) { MelonLogger.Warning($"DebugDummyPlayers is {Count}: {Count} dummy characters will spawn around you after a save loads. Set it back to 0 to play normally."); } } public static void OnSceneLoaded(string scene) { Despawn(); _spawnAfter = ((scene == "Main" && Count > 0) ? (Time.realtimeSinceStartup + 10f) : (-1f)); } public static void Update() { if (Count <= 0) { return; } try { if (_spawnAfter > 0f && Time.realtimeSinceStartup >= _spawnAfter) { _spawnAfter = -1f; Spawn(); ResetFps(); } Walk(); TrackFps(); } catch (Exception arg) { MelonLogger.Error($"[dummies] {arg}"); _spawnAfter = -1f; } } private static void Spawn() { //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) Despawn(); Player local = Player.Local; object obj; if (local == null) { obj = null; } else { Avatar avatar = local.Avatar; obj = ((avatar != null) ? ((Component)avatar).gameObject : null); } GameObject val = (GameObject)obj; if ((Object)(object)local == (Object)null || (Object)(object)val == (Object)null) { MelonLogger.Warning("[dummies] no local player yet; not spawning"); return; } _centre = ((Component)local).transform.position; int count = Count; for (int i = 0; i < count; i++) { GameObject val2 = Object.Instantiate(val); ((Object)val2).name = $"BiggerLobbies_Dummy_{i + 1}"; MakeVisible(val2); _dummies.Add(val2); _phase.Add(i); } Place(0f); Log.Info($"[dummies] spawned {_dummies.Count} dummy characters around you"); } private static void MakeVisible(GameObject go) { foreach (Transform componentsInChild in go.GetComponentsInChildren(true)) { ((Component)componentsInChild).gameObject.layer = 0; } foreach (Renderer componentsInChild2 in go.GetComponentsInChildren(true)) { componentsInChild2.enabled = true; componentsInChild2.shadowCastingMode = (ShadowCastingMode)1; } go.SetActive(true); } private static void Place(float t) { //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) int num = 0; int num2 = 0; while (num < _dummies.Count) { int num3 = 8 + num2 * 6; float num4 = 3f + (float)num2 * 1.6f; float num5 = ((num2 % 2 == 0) ? 1f : (-1f)); int num6 = 0; while (num6 < num3 && num < _dummies.Count) { GameObject val = _dummies[num]; if (!((Object)(object)val == (Object)null)) { float num7 = (float)num6 / (float)num3 * MathF.PI * 2f + num5 * t * 0.25f / (1f + (float)num2 * 0.3f); Vector3 val2 = _centre + new Vector3(Mathf.Cos(num7) * num4, 0f, Mathf.Sin(num7) * num4); Vector3 val3 = new Vector3(0f - Mathf.Sin(num7), 0f, Mathf.Cos(num7)) * num5; val.transform.SetPositionAndRotation(val2, Quaternion.LookRotation(val3, Vector3.up)); } num6++; num++; } num2++; } } private static void Walk() { if (_dummies.Count != 0) { Place(Time.time); } } public static void Despawn() { foreach (GameObject dummy in _dummies) { if ((Object)(object)dummy != (Object)null) { Object.Destroy((Object)(object)dummy); } } if (_dummies.Count > 0) { Log.Info($"[dummies] removed {_dummies.Count} dummy characters"); } _dummies.Clear(); _phase.Clear(); } private static void ResetFps() { _fpsWindowStart = Time.realtimeSinceStartup; _frames = 0; _minFps = float.MaxValue; } private static void TrackFps() { //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) Scene activeScene = SceneManager.GetActiveScene(); if (!(((Scene)(ref activeScene)).name != "Main")) { if (_fpsWindowStart <= 0f) { ResetFps(); } _frames++; float unscaledDeltaTime = Time.unscaledDeltaTime; if (unscaledDeltaTime > 0f) { _minFps = Math.Min(_minFps, 1f / unscaledDeltaTime); } float num = Time.realtimeSinceStartup - _fpsWindowStart; if (!(num < 10f)) { Log.Info($"[dummies] {_dummies.Count} dummies: {(float)_frames / num:0} fps average, {_minFps:0} lowest (last {num:0} s)"); ResetFps(); } } } } public static class HostLobby { public static SteamLobbyService? Service() { try { Lobby instance = Singleton.Instance; object result; if (instance == null) { result = null; } else { ILobbyService lobbyService = instance._lobbyService; result = ((lobbyService != null) ? ((Il2CppObjectBase)lobbyService).TryCast() : null); } return (SteamLobbyService?)result; } catch { return null; } } public static bool TryGet(out CSteamID lobby) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004a: 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) lobby = default(CSteamID); try { SteamLobbyService val = Service(); if (val == null || !val.IsInLobby) { return false; } lobby = val._lobbySteamID; if (lobby.m_SteamID == 0) { return false; } return SteamMatchmaking.GetLobbyOwner(lobby).m_SteamID == SteamUser.GetSteamID().m_SteamID; } catch (Exception ex) { MelonLogger.Warning("Couldn't read the Steam lobby: " + ex.Message); return false; } } public static int MemberCount() { //IL_000e: Unknown result type (might be due to invalid IL or missing references) try { CSteamID lobby; return TryGet(out lobby) ? SteamMatchmaking.GetNumLobbyMembers(lobby) : 0; } catch { return 0; } } } [HarmonyPatch] public static class LobbyPrivacy { public enum Mode { Private, FriendsOnly, Open } private static MelonPreferences_Entry? _entry; public static Mode Current { get; private set; } = Mode.FriendsOnly; public static void Init(MelonPreferences_Category cat) { _entry = cat.CreateEntry("LobbyPrivacy", "FriendsOnly", "Lobby privacy", "Who can join your lobby: Private (only people you invite), FriendsOnly (Steam friends can use Join Game; the game's default) or Open (anyone who finds it in Steam's lobby search). Can also be changed in Host settings.", false, false, (ValueValidator)null, (string)null); string text = (_entry.Value ?? "").Trim(); if (text.Equals("InviteOnly", StringComparison.OrdinalIgnoreCase)) { text = "Private"; } if (text.Equals("Public", StringComparison.OrdinalIgnoreCase)) { text = "Open"; } if (Enum.TryParse(text, ignoreCase: true, out var result) && Enum.IsDefined(typeof(Mode), result)) { Current = result; } else { MelonLogger.Warning("LobbyPrivacy '" + _entry.Value + "' isn't Private, FriendsOnly or Open; using FriendsOnly"); } if (Current != Mode.FriendsOnly) { Log.Info("Lobby privacy: " + Label(Current)); } } public static string Label(Mode m) { if (1 == 0) { } string result = m switch { Mode.Private => "Private", Mode.Open => "Open", _ => "Friends only", }; if (1 == 0) { } return result; } private static ELobbyType SteamType(Mode m) { //IL_0010: 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_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (1 == 0) { } ELobbyType result = (ELobbyType)(m switch { Mode.Private => 0, Mode.Open => 2, _ => 1, }); if (1 == 0) { } return result; } [HarmonyPrefix] [HarmonyPriority(800)] [HarmonyPatch(typeof(SteamMatchmaking), "CreateLobby")] private static void CreateLobby_Prefix(ref ELobbyType eLobbyType) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: 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_000f: Invalid comparison between I4 and Unknown //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected I4, but got Unknown ELobbyType val = SteamType(Current); if ((int)eLobbyType != (int)val) { Log.Info($"Lobby privacy: {Label(Current)} (the game asked for {eLobbyType})"); eLobbyType = (ELobbyType)(int)val; } } [HarmonyPrefix] [HarmonyPatch(typeof(PlatformFriends), "IsLocalPlayerFriendsWith")] private static bool IsLocalPlayerFriendsWith_Prefix(ref bool __result) { if (Current != Mode.Open) { return true; } __result = true; return false; } public static string Set(Mode m) { //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) Current = m; if (_entry != null) { _entry.Value = m.ToString(); MelonPreferences.Save(); } if (!HostLobby.TryGet(out var lobby)) { return "Privacy set to " + Label(m) + ". It applies when you next host."; } bool flag; try { flag = SteamMatchmaking.SetLobbyType(lobby, SteamType(m)); } catch (Exception ex) { MelonLogger.Warning("SetLobbyType failed: " + ex.Message); flag = false; } Log.Info("Lobby privacy changed to " + Label(m) + " on the open lobby: Steam " + (flag ? "accepted" : "refused") + " it"); return flag ? ("Privacy is now " + Label(m)) : "Steam refused the change. It applies when you next host."; } } public static class BanList { public readonly struct Entry { public readonly ulong SteamId; public readonly string Name; public readonly DateTime? Until; public readonly string Reason; public bool Permanent => !Until.HasValue; public Entry(ulong steamId, string name, DateTime? until = null, string reason = "") { SteamId = steamId; Name = name; Until = until; Reason = reason ?? ""; } } private static MelonPreferences_Entry? _entry; private static readonly List _bans = new List(); private static readonly Dictionary _verified = new Dictionary(); private static readonly Dictionary _lastRefusedLog = new Dictionary(); public static IReadOnlyList Bans { get { Prune(); return _bans; } } public static void Init(MelonPreferences_Category cat) { _entry = cat.CreateEntry("BannedPlayers", "", "Banned players", "Steam IDs that can't join your games, separated by commas. A name in round brackets and a reason in square brackets are just reminders; 'until' and a UTC time make the ban end then. Easiest to manage in Host settings.", false, false, (ValueValidator)null, (string)null); Parse(_entry.Value); MelonPreferences_Entry val = cat.CreateEntry("Blacklist", "", "Blacklist (old)", "Moved to BannedPlayers.", true, false, (ValueValidator)null, (string)null); if (!string.IsNullOrWhiteSpace(val.Value)) { int count = _bans.Count; foreach (Entry e in ParseList(val.Value)) { if (_bans.All((Entry b) => b.SteamId != e.SteamId)) { _bans.Add(e); } } val.Value = ""; Store(); Log.Info($"Moved {_bans.Count - count} ban(s) from the old Blacklist setting to BannedPlayers"); } Prune(); if (_bans.Count > 0) { Log.Info($"Banned players: {_bans.Count}"); } } private static void Parse(string? raw) { _bans.Clear(); _bans.AddRange(ParseList(raw)); } private static List ParseList(string? raw) { List list = new List(); if (string.IsNullOrWhiteSpace(raw)) { return list; } string[] array = raw.Split(','); foreach (string text in array) { string text2 = text.Trim(); int j; for (j = 0; j < text2.Length && char.IsDigit(text2[j]); j++) { } if (j == 0 || !ulong.TryParse(text2.Substring(0, j), out var id) || id == 0) { if (text2.Length > 0) { MelonLogger.Warning("Banned players: '" + text2 + "' doesn't start with a Steam ID; skipped"); } continue; } string text3 = text2.Substring(j).Trim(); DateTime? until = null; string text4 = null; int num = text3.LastIndexOf("until ", StringComparison.OrdinalIgnoreCase); if (num >= 0 && (num == 0 || text3[num - 1] == ' ' || text3[num - 1] == ')')) { text4 = text3.Substring(num + 6); text3 = text3.Substring(0, num); } if (text4 != null) { if (DateTime.TryParse(text4.Trim(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out var result)) { until = DateTime.SpecifyKind(result, DateTimeKind.Utc); } else { MelonLogger.Warning($"Banned players: couldn't read the end time '{text4.Trim()}' for {id}; treating the ban as permanent"); } } string reason = ""; text3 = text3.Trim(); int num2 = (text3.StartsWith("(") ? text3.IndexOf(')') : (-1)); int num3 = text3.IndexOf('[', num2 + 1); if (num3 >= 0 && text3.EndsWith("]")) { reason = text3.Substring(num3 + 1, text3.Length - num3 - 2).Trim(); text3 = text3.Substring(0, num3); } string name = text3.Trim().Trim('(', ')').Trim(); if (list.All((Entry b) => b.SteamId != id)) { list.Add(new Entry(id, name, until, reason)); } } return list; } private static void Store() { if (_entry == null) { return; } StringBuilder stringBuilder = new StringBuilder(); foreach (Entry ban in _bans) { if (stringBuilder.Length > 0) { stringBuilder.Append(", "); } stringBuilder.Append(ban.SteamId); string text = Clean(ban.Name); if (text.Length > 0) { stringBuilder.Append(" (").Append(text).Append(')'); } string text2 = CleanReason(ban.Reason); if (text2.Length > 0) { stringBuilder.Append(" [").Append(text2).Append(']'); } if (ban.Until.HasValue) { stringBuilder.Append(" until ").Append(ban.Until.Value.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture)); } } _entry.Value = stringBuilder.ToString(); MelonPreferences.Save(); } private static void Prune() { DateTime now = DateTime.UtcNow; List list = _bans.Where((Entry b) => b.Until.HasValue && b.Until.Value <= now).ToList(); if (list.Count == 0) { return; } _bans.RemoveAll((Entry b) => b.Until.HasValue && b.Until.Value <= now); foreach (Entry item in list) { Log.Info(string.Format("Ban ended for {0}({1})", (item.Name.Length > 0) ? (item.Name + " ") : "", item.SteamId)); } Store(); } private static string Clean(string? n) { return new string((n ?? "").Where((char c) => c != ',' && c != '(' && c != ')' && !char.IsControl(c)).ToArray()).Replace(" until ", " ").Trim(); } public static string CleanReason(string? r) { string input = new string((r ?? "").Where((char c) => c != ',' && c != '[' && c != ']' && !char.IsControl(c)).ToArray()); input = Regex.Replace(input, "until ", "till ", RegexOptions.IgnoreCase).Trim(); return (input.Length > 40) ? input.Substring(0, 40).Trim() : input; } public static bool IsBanned(ulong id) { if (id == 0) { return false; } Prune(); return _bans.Any((Entry b) => b.SteamId == id); } public static string Remaining(Entry e) { if (!e.Until.HasValue) { return "Permanent"; } TimeSpan timeSpan = e.Until.Value - DateTime.UtcNow; if (timeSpan.TotalMinutes < 1.0) { return "Ending"; } if (timeSpan.TotalMinutes < 60.0) { return $"{Math.Ceiling(timeSpan.TotalMinutes)} min left"; } if (timeSpan.TotalHours < 48.0) { return $"{Math.Ceiling(timeSpan.TotalHours)} h left"; } return $"{Math.Ceiling(timeSpan.TotalDays)} days left"; } public static void RecordLogin(int clientId, ulong steamId) { _verified[clientId] = steamId; } public static ulong VerifiedSteamId(int clientId) { ulong value; return _verified.TryGetValue(clientId, out value) ? value : 0; } public static void ForgetLogin(int clientId) { _verified.Remove(clientId); } public static bool IsConnected(ulong steamId) { if (steamId == 0) { return false; } Dictionary val = null; try { ServerManager serverManager = InstanceFinder.ServerManager; val = ((serverManager != null) ? serverManager.Clients : null); } catch { } NetworkConnection val2 = default(NetworkConnection); foreach (KeyValuePair item in _verified) { if (item.Value != steamId) { continue; } if (val == null) { return true; } try { if (val.TryGetValue(item.Key, ref val2) && val2 != (NetworkConnection)null && val2.IsActive) { return true; } } catch { return true; } } return false; } public static ulong HostSteamId() { //IL_0002: Unknown result type (might be due to invalid IL or missing references) try { return SteamUser.GetSteamID().m_SteamID; } catch { return 0uL; } } public static void Ban(ulong id, string name, TimeSpan? length = null, string reason = "") { if (id == 0) { return; } if (id == HostSteamId()) { MelonLogger.Warning("Refused to ban your own Steam ID"); return; } DateTime? until = (length.HasValue ? new DateTime?(DateTime.UtcNow + length.Value) : ((DateTime?)null)); _bans.RemoveAll((Entry b) => b.SteamId == id); Whitelist.Remove(id); reason = CleanReason(reason); _bans.Add(new Entry(id, Clean(name), until, reason)); Store(); Log.Info(string.Format("Banned {0} ({1}) {2}{3}", Clean(name), id, until.HasValue ? ("until " + until.Value.ToString("u", CultureInfo.InvariantCulture)) : "permanently", (reason.Length > 0) ? (": " + reason) : "")); HostPlayers.DisconnectSteamId(id, length, reason); } public static void Unban(ulong id) { if (_bans.RemoveAll((Entry b) => b.SteamId == id) != 0) { Store(); Log.Info($"Unbanned {id}"); } } public static bool RejectIfBanned(NetworkConnection conn, ulong steamId) { if (!IsBanned(steamId)) { return false; } Entry e = _bans.First((Entry b) => b.SteamId == steamId); float realtimeSinceStartup = Time.realtimeSinceStartup; if (!_lastRefusedLog.TryGetValue(steamId, out var value) || realtimeSinceStartup - value > 60f) { _lastRefusedLog[steamId] = realtimeSinceStartup; Log.Info(string.Format("Refused {0}({1}): banned, {2}", (e.Name.Length > 0) ? (e.Name + " ") : "", steamId, Remaining(e).ToLowerInvariant())); } TimeSpan? length = (e.Until.HasValue ? new TimeSpan?(e.Until.Value - DateTime.UtcNow) : ((TimeSpan?)null)); KickNotice.Remove(conn, steamId, KickNotice.Kind.Ban, length, e.Reason, conn.Authenticated ? 1.5f : 0.5f); return true; } } public static class Whitelist { private static MelonPreferences_Entry? _enabled; private static readonly List _allowed = new List(); private static readonly Dictionary _lastRefusedLog = new Dictionary(); public static bool Enabled => _enabled?.Value ?? false; public static IReadOnlyList Players => _allowed.OrderByDescending((BanList.Entry e) => (int)Friends.StateOf(e.SteamId)).ThenBy((BanList.Entry e) => e.Name, StringComparer.OrdinalIgnoreCase).ToList(); public static void Init(MelonPreferences_Category cat) { _enabled = cat.CreateEntry("WhitelistEnabled", false, "Whitelist", "When true, only players you add to the whitelist in Host settings can join. The list starts empty every time you start the game.", false, false, (ValueValidator)null, (string)null); if (Enabled) { Log.Info("Whitelist is on: only players you add in Host settings can join, and the list starts empty"); } } public static void SetEnabled(bool on) { if (_enabled != null && _enabled.Value != on) { _enabled.Value = on; MelonPreferences.Save(); Log.Info(on ? "Whitelist turned on" : "Whitelist turned off"); } } public static void WarnIfEmpty() { if (Enabled && _allowed.Count == 0) { MelonLogger.Warning("Whitelist is on and empty: nobody else can join until you add players in Host settings (pause menu or F6)"); } } public static bool Contains(ulong id) { return _allowed.Any((BanList.Entry e) => e.SteamId == id); } public static bool Add(ulong id, string name) { if (id == 0L || BanList.IsBanned(id)) { return false; } if (Contains(id)) { return true; } _allowed.Add(new BanList.Entry(id, name ?? "")); Log.Info($"Whitelisted {name} ({id}) for this session"); return true; } public static int Replace(IEnumerable members) { _allowed.Clear(); int num = 0; foreach (BanList.Entry member in members) { if (member.SteamId != 0L && !BanList.IsBanned(member.SteamId) && !Contains(member.SteamId)) { _allowed.Add(new BanList.Entry(member.SteamId, member.Name ?? "")); num++; } } return num; } public static void Remove(ulong id) { if (_allowed.RemoveAll((BanList.Entry e) => e.SteamId == id) > 0) { Log.Info($"Removed {id} from the whitelist"); } } public static bool RejectIfNotListed(NetworkConnection conn, ulong steamId) { if (!Enabled || steamId == 0L || steamId == BanList.HostSteamId() || Contains(steamId)) { return false; } float realtimeSinceStartup = Time.realtimeSinceStartup; if (!_lastRefusedLog.TryGetValue(steamId, out var value) || realtimeSinceStartup - value > 60f) { _lastRefusedLog[steamId] = realtimeSinceStartup; Log.Info($"Refused {Friends.NameOf(steamId)} ({steamId}): not on the whitelist"); } KickNotice.Remove(conn, steamId, KickNotice.Kind.Whitelist, null, "", conn.Authenticated ? 1.5f : 0.5f); return true; } } public static class Crews { public sealed class Crew { public string Name = ""; public List Members = new List(); } private static MelonPreferences_Entry? _entry; private static readonly List _crews = new List(); public const int MaxCrews = 12; public static IReadOnlyList All => _crews; public static void Init(MelonPreferences_Category cat) { _entry = cat.CreateEntry("SavedCrews", "", "Saved crews", "Named whitelists you can load in Host settings. Easiest to manage there.", false, false, (ValueValidator)null, (string)null); Parse(_entry.Value); } private static void Parse(string? raw) { _crews.Clear(); if (string.IsNullOrWhiteSpace(raw)) { return; } string[] array = raw.Split(';'); foreach (string text in array) { int num = text.IndexOf('='); if (num <= 0) { continue; } Crew crew = new Crew { Name = CleanName(text.Substring(0, num)) }; if (crew.Name.Length == 0) { continue; } string[] array2 = text.Substring(num + 1).Split('|'); foreach (string text2 in array2) { string text3 = text2.Trim(); int k; for (k = 0; k < text3.Length && char.IsDigit(text3[k]); k++) { } if (k != 0 && ulong.TryParse(text3.Substring(0, k), out var id) && id != 0) { string name = text3.Substring(k).Trim().Trim('(', ')') .Trim(); if (crew.Members.All((BanList.Entry e) => e.SteamId != id)) { crew.Members.Add(new BanList.Entry(id, name)); } } } if (_crews.All((Crew c) => !c.Name.Equals(crew.Name, StringComparison.OrdinalIgnoreCase))) { _crews.Add(crew); } } } private static void Store() { if (_entry == null) { return; } StringBuilder stringBuilder = new StringBuilder(); foreach (Crew crew in _crews) { if (stringBuilder.Length > 0) { stringBuilder.Append("; "); } stringBuilder.Append(crew.Name).Append('='); stringBuilder.Append(string.Join("|", crew.Members.Select((BanList.Entry m) => $"{m.SteamId} ({CleanMember(m.Name)})"))); } _entry.Value = stringBuilder.ToString(); MelonPreferences.Save(); } public static string CleanName(string? s) { return new string((s ?? "").Where((char c) => c != ';' && c != '=' && c != '|' && c != ',' && !char.IsControl(c)).ToArray()).Trim(); } private static string CleanMember(string? s) { return new string((s ?? "").Where((char c) => c != ';' && c != '=' && c != '|' && c != '(' && c != ')' && !char.IsControl(c)).ToArray()).Trim(); } public static string SaveCurrent(string name) { name = CleanName(name); if (name.Length == 0) { return "Type a name for the crew first"; } List list = Whitelist.Players.ToList(); if (list.Count == 0) { return "Add players to the whitelist first"; } int num = _crews.FindIndex((Crew c) => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); if (num < 0 && _crews.Count >= 12) { return $"You can keep up to {12} crews. Delete one first"; } Crew crew = new Crew { Name = name, Members = list }; if (num >= 0) { _crews[num] = crew; } else { _crews.Add(crew); } Store(); return (num >= 0) ? $"Updated {name} ({list.Count})" : $"Saved {name} ({list.Count})"; } public static string Load(string name) { Crew crew = _crews.FirstOrDefault((Crew c) => c.Name == name); if (crew == null) { return "That crew no longer exists"; } int num = Whitelist.Replace(crew.Members); Whitelist.SetEnabled(on: true); int num2 = crew.Members.Count - num; return (num2 > 0) ? $"Loaded {name}: {num} on the whitelist, {num2} banned and left off" : $"Loaded {name}: whitelist on with {num}"; } public static void Delete(string name) { if (_crews.RemoveAll((Crew c) => c.Name == name) > 0) { Store(); } } } public static class DepartedPlayers { public sealed class Slot { public int Index; public string Json = ""; public string Id = ""; public int Quantity; public ItemInstance? Item; } public sealed class Info { public ulong SteamId; public string Name = ""; public string Folder = ""; public DateTime SavedUtc; public List Items = new List(); public float Cash; } public sealed class TakenSlot { public int Index; public string Literal = ""; public string Id = ""; public int Quantity; public int Returned; } public sealed class TakeRecord { public string Path = ""; public string Save = ""; public string Name = ""; public string Backup = ""; public ulong SteamId; public DateTime Utc; public List Slots = new List(); public double Cash; public double CashReturned; public bool AllReturned => Slots.All((TakenSlot s) => s.Returned >= s.Quantity) && Cash - CashReturned < 0.01; } public sealed class Taken { public DateTime Utc; public ulong SteamId; public string Name = ""; public string Summary = ""; public string Save = ""; public TakeRecord? Record; public bool GiveBack; } private sealed class Literal { public int Start; public int End; public string Value = ""; } private sealed class Held { public ItemSlot Slot = null; public int Before; public int Dropped(string id) { try { ItemInstance itemInstance = Slot.ItemInstance; if (itemInstance == null) { return Before; } if (((BaseItemInstance)itemInstance).ID != id) { return 0; } return Math.Max(0, Before - ((BaseItemInstance)itemInstance).Quantity); } catch { return 0; } } } private sealed class Stock { public string Id = ""; public int Usable; public int Asked; public readonly List Slots = new List(); } private sealed class Pending { public TakenSlot Slot = null; public string Key = ""; public int Asked; } private static List _cache = new List(); private static float _cacheUntil; private const double SettleSeconds = 10.0; private static readonly Regex IdRx = new Regex("\"ID\"\\s*:\\s*\"([^\"]*)\""); private static readonly Regex QtyRx = new Regex("\"Quantity\"\\s*:\\s*(\\d+)"); private static readonly Regex TypeRx = new Regex("\"DataType\"\\s*:\\s*\"([^\"]*)\""); private static readonly Regex CashRx = new Regex("\"CashBalance\"\\s*:\\s*(-?[0-9.eE+-]+)"); private static Dictionary? _names; private static float _nextNameScan; private static bool _namesWarned; private static List? _log; private static DateTime _logStamp; private static bool _givingBack; private static string TakenDir => Path.Combine(MelonEnvironment.UserDataDirectory, "BiggerLobbies", "Taken"); private static string NamesFile => Path.Combine(MelonEnvironment.UserDataDirectory, "BiggerLobbies", "PlayerNames.tsv"); private static string LogFile => Path.Combine(TakenDir, "TakenLog.tsv"); private static string SaveName() { try { LoadManager instance = Singleton.Instance; return Path.GetFileName((((instance != null) ? instance.LoadedGameFolderPath : null) ?? "").TrimEnd('/', '\\')); } catch { return ""; } } private static Dictionary Names() { if (_names != null) { return _names; } _names = new Dictionary(); try { if (File.Exists(NamesFile)) { string[] array = File.ReadAllLines(NamesFile); foreach (string text in array) { string[] array2 = text.Split('\t'); if (array2.Length >= 2 && ulong.TryParse(array2[0], out var result) && result != 0L && array2[1].Trim().Length > 0) { _names[result] = array2[1].Trim(); } } } } catch (Exception ex) { MelonLogger.Warning("Couldn't read saved player names: " + ex.Message); } return _names; } public static void Update() { if (Time.unscaledTime < _nextNameScan) { return; } _nextNameScan = Time.unscaledTime + 5f; try { if (!InstanceFinder.IsServer) { return; } List playerList = Player.PlayerList; if (playerList == null) { return; } Dictionary dictionary = Names(); bool flag = false; for (int i = 0; i < playerList.Count; i++) { Player val = playerList[i]; if ((Object)(object)val == (Object)null || val.IsLocalPlayer) { continue; } NetworkConnection connection = val.Connection; if (!(connection == (NetworkConnection)null) && !connection.IsLocalClient) { ulong num = BanList.VerifiedSteamId(connection.ClientId); string text = Tsv(val.PlayerName ?? "").Trim(); if (num != 0L && text.Length != 0 && (!dictionary.TryGetValue(num, out var value) || !(value == text))) { dictionary[num] = text; flag = true; } } } if (flag) { Directory.CreateDirectory(Path.GetDirectoryName(NamesFile)); File.WriteAllLines(NamesFile, dictionary.Select((KeyValuePair kv) => kv.Key + "\t" + kv.Value)); } } catch (Exception ex) { if (!_namesWarned) { _namesWarned = true; MelonLogger.Warning("Couldn't save player names: " + ex.Message); } } } public static string NameOf(ulong steamId) { try { if (Names().TryGetValue(steamId, out var value) && value.Length > 0) { return value; } } catch { } return Friends.NameOf(steamId); } private static string Tsv(string s) { return (s ?? "").Replace('\t', ' ').Replace('\n', ' ').Replace('\r', ' '); } private static void AppendLog(ulong id, string name, string summary, string record = "") { try { string text = string.Join("\t", DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture), Tsv(SaveName()), id.ToString(), Tsv(name), Tsv(summary), Tsv(record)); File.AppendAllText(LogFile, text + "\n"); _log = null; } catch (Exception ex) { MelonLogger.Warning("Couldn't write the take log: " + ex.Message); } } public static List History(int max = 8) { try { if (!File.Exists(LogFile)) { return new List(); } DateTime lastWriteTimeUtc = File.GetLastWriteTimeUtc(LogFile); if (_log == null || lastWriteTimeUtc != _logStamp) { _logStamp = lastWriteTimeUtc; _log = new List(); string[] array = File.ReadAllLines(LogFile); foreach (string text in array) { string[] array2 = text.Split('\t'); if (array2.Length >= 5 && ulong.TryParse(array2[2], out var result) && DateTime.TryParse(array2[0], CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var result2)) { Taken taken = new Taken { Utc = result2.ToUniversalTime(), Save = array2[1], SteamId = result, Name = array2[3], Summary = array2[4] }; taken.GiveBack = taken.Summary.StartsWith("Gave back", StringComparison.Ordinal); if (array2.Length >= 6 && array2[5].Trim().Length > 0) { taken.Record = ReadRecord(Path.Combine(TakenDir, Path.GetFileName(array2[5].Trim()))); } _log.Add(taken); } } } string save = SaveName(); return (from e in _log where e.Save == save orderby e.Utc descending select e).Take(max).ToList(); } catch { return new List(); } } private static void WriteRecord(TakeRecord r) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("{\n"); stringBuilder.Append(" \"version\": 1,\n"); stringBuilder.Append(" \"save\": ").Append(MiniJson.Quote(r.Save)).Append(",\n"); stringBuilder.Append(" \"steamId\": ").Append(MiniJson.Quote(r.SteamId.ToString())).Append(",\n"); stringBuilder.Append(" \"name\": ").Append(MiniJson.Quote(r.Name)).Append(",\n"); stringBuilder.Append(" \"utc\": ").Append(MiniJson.Quote(r.Utc.ToString("o", CultureInfo.InvariantCulture))).Append(",\n"); stringBuilder.Append(" \"backup\": ").Append(MiniJson.Quote(r.Backup)).Append(",\n"); stringBuilder.Append(" \"slots\": ["); for (int i = 0; i < r.Slots.Count; i++) { TakenSlot takenSlot = r.Slots[i]; stringBuilder.Append((i == 0) ? "\n" : ",\n"); stringBuilder.Append(" {\"index\": ").Append(takenSlot.Index).Append(", \"id\": ") .Append(MiniJson.Quote(takenSlot.Id)) .Append(", \"quantity\": ") .Append(takenSlot.Quantity) .Append(", \"returned\": ") .Append(takenSlot.Returned) .Append(", \"literal\": ") .Append(MiniJson.Quote(takenSlot.Literal)) .Append('}'); } stringBuilder.Append((r.Slots.Count > 0) ? "\n ],\n" : "],\n"); stringBuilder.Append(" \"cash\": ").Append(MiniJson.Number(r.Cash)).Append(",\n"); stringBuilder.Append(" \"cashReturned\": ").Append(MiniJson.Number(r.CashReturned)).Append('\n'); stringBuilder.Append("}\n"); File.WriteAllText(r.Path, stringBuilder.ToString()); } private static TakeRecord? ReadRecord(string path) { try { if (!File.Exists(path)) { return null; } if (!(MiniJson.Parse(File.ReadAllText(path)) is Dictionary dictionary)) { return null; } if (!ulong.TryParse(MiniJson.Str(dictionary, "steamId"), out var result) || result == 0) { return null; } DateTime.TryParse(MiniJson.Str(dictionary, "utc"), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var result2); TakeRecord takeRecord = new TakeRecord { Path = path, Save = MiniJson.Str(dictionary, "save"), SteamId = result, Name = MiniJson.Str(dictionary, "name"), Utc = result2.ToUniversalTime(), Backup = MiniJson.Str(dictionary, "backup"), Cash = MiniJson.Num(dictionary, "cash"), CashReturned = MiniJson.Num(dictionary, "cashReturned") }; if (dictionary.TryGetValue("slots", out var value) && value is List list) { foreach (object item in list) { if (item is Dictionary o) { TakenSlot takenSlot = new TakenSlot { Index = (int)MiniJson.Num(o, "index"), Id = MiniJson.Str(o, "id"), Quantity = (int)MiniJson.Num(o, "quantity"), Returned = (int)MiniJson.Num(o, "returned"), Literal = MiniJson.Str(o, "literal") }; if (takenSlot.Literal.Length != 0 && takenSlot.Id.Length != 0 && takenSlot.Quantity > 0) { takeRecord.Slots.Add(takenSlot); } } } } return takeRecord; } catch (Exception ex) { MelonLogger.Warning("Couldn't read the take record " + Path.GetFileName(path) + ": " + ex.Message); return null; } } private static string? PlayersFolder() { try { LoadManager instance = Singleton.Instance; string text = ((instance != null) ? instance.LoadedGameFolderPath : null); if (string.IsNullOrEmpty(text)) { return null; } string text2 = Path.Combine(text, "Players"); return Directory.Exists(text2) ? text2 : null; } catch { return null; } } private static HashSet OnlineCodes() { HashSet hashSet = new HashSet(); List playerList = Player.PlayerList; if (playerList != null) { for (int i = 0; i < playerList.Count; i++) { if ((Object)(object)playerList[i] != (Object)null && !string.IsNullOrEmpty(playerList[i].PlayerCode)) { hashSet.Add(playerList[i].PlayerCode); } } } return hashSet; } private static bool IsHere(ulong id, HashSet? online = null) { return (online ?? OnlineCodes()).Contains(id.ToString()) || BanList.IsConnected(id); } public static List List() { if (Time.unscaledTime < _cacheUntil) { return _cache; } _cacheUntil = Time.unscaledTime + 2f; List list = new List(); try { if (!InstanceFinder.IsServer) { _cache = list; return list; } string text = PlayersFolder(); if (text == null) { _cache = list; return list; } HashSet online = OnlineCodes(); string[] directories = Directory.GetDirectories(text, "Player_*"); foreach (string text2 in directories) { string s = Path.GetFileName(text2).Substring("Player_".Length); if (!ulong.TryParse(s, out var result) || result == 0 || IsHere(result, online) || result == BanList.HostSteamId()) { continue; } string path = Path.Combine(text2, "Inventory.json"); if (File.Exists(path)) { string text3 = File.ReadAllText(path); List literals; string fileText; List list2 = ReadItems(text3, out literals, out fileText); int index; float num = CashOf(literals, out index); if (list2.Count != 0 || !(num < 0.01f)) { list.Add(new Info { SteamId = result, Name = NameOf(result), Folder = text2, SavedUtc = File.GetLastWriteTimeUtc(path), Items = list2, Cash = num }); } } } } catch (Exception ex) { MelonLogger.Warning("Couldn't read saved players: " + ex.Message); } _cache = list.OrderByDescending((Info r) => r.SavedUtc).ToList(); return _cache; } public static void Invalidate() { _cacheUntil = 0f; } private static List ReadItems(string text, out List literals, out string fileText) { fileText = text; literals = ParseItemsArray(text); List list = new List(); for (int i = 0; i < literals.Count; i++) { string value = literals[i].Value; string value2 = TypeRx.Match(value).Groups[1].Value; string value3 = IdRx.Match(value).Groups[1].Value; int.TryParse(QtyRx.Match(value).Groups[1].Value, out var result); if (!(value2 == "CashData") && value3.Length != 0 && !(value3 == "cash") && result > 0) { ItemInstance item = null; try { item = ItemDeserializer.LoadItem(value); } catch { } list.Add(new Slot { Index = i, Json = value, Id = value3, Quantity = result, Item = item }); } } return list; } private static float CashOf(List literals, out int index) { index = -1; for (int i = 0; i < literals.Count; i++) { string value = literals[i].Value; if (!(TypeRx.Match(value).Groups[1].Value != "CashData")) { index = i; Match match = CashRx.Match(value); float result; return (match.Success && float.TryParse(match.Groups[1].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out result)) ? result : 0f; } } return 0f; } private static List ParseItemsArray(string s) { List list = new List(); int num = s.IndexOf("\"Items\"", StringComparison.Ordinal); if (num < 0) { return list; } num = s.IndexOf('[', num); if (num < 0) { return list; } int num2 = num + 1; while (num2 < s.Length) { switch (s[num2]) { default: num2++; continue; case '"': { int start = num2; StringBuilder stringBuilder = new StringBuilder(); num2++; while (num2 < s.Length && s[num2] != '"') { if (s[num2] == '\\' && num2 + 1 < s.Length) { char c = s[num2 + 1]; switch (c) { case 'n': stringBuilder.Append('\n'); num2 += 2; continue; case 't': stringBuilder.Append('\t'); num2 += 2; continue; case 'r': stringBuilder.Append('\r'); num2 += 2; continue; case 'b': stringBuilder.Append('\b'); num2 += 2; continue; case 'f': stringBuilder.Append('\f'); num2 += 2; continue; case 'u': break; default: stringBuilder.Append(c); num2 += 2; continue; } if (num2 + 5 < s.Length && int.TryParse(s.Substring(num2 + 2, 4), NumberStyles.HexNumber, null, out var result)) { stringBuilder.Append((char)result); num2 += 6; continue; } } stringBuilder.Append(s[num2]); num2++; } list.Add(new Literal { Start = start, End = num2 + 1, Value = stringBuilder.ToString() }); num2++; continue; } case ']': break; } break; } return list; } private static string Splice(string text, List literals, Dictionary replace) { StringBuilder stringBuilder = new StringBuilder(); int num = 0; for (int i = 0; i < literals.Count; i++) { if (replace.TryGetValue(i, out var value)) { stringBuilder.Append(text, num, literals[i].Start - num).Append(value); num = literals[i].End; } } stringBuilder.Append(text, num, text.Length - num); return stringBuilder.ToString(); } private static string EmptySlot(string sample) { string text = Regex.Match(sample, "\"GameVersion\"\\s*:\\s*\"([^\"]*)\"").Groups[1].Value; if (text.Length == 0) { text = Application.version; } return "{\"DataType\":\"ItemData\",\"DataVersion\":0,\"GameVersion\":\"" + text + "\",\"ID\":\"\",\"Quantity\":0}"; } private static string Stamp() { return DateTime.Now.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture); } public static string Take(ulong steamId) { try { if (!InstanceFinder.IsServer) { return "Only the host can take items"; } if (_givingBack) { return "Wait for the give back to finish"; } string text = steamId.ToString(); if (IsHere(steamId)) { return "They're in the game. Items can only be taken after they leave"; } string text2 = PlayersFolder(); if (text2 == null) { return "Couldn't find this save's player folders"; } string path = Path.Combine(text2, "Player_" + text); string text3 = Path.Combine(path, "Inventory.json"); if (!File.Exists(text3)) { return "Nothing saved for that player"; } double totalSeconds = (DateTime.UtcNow - File.GetLastWriteTimeUtc(text3)).TotalSeconds; if (totalSeconds < 10.0) { return $"They only just left. Try again in {Math.Ceiling(10.0 - totalSeconds)} s"; } PlayerInventory instance = PlayerSingleton.Instance; if ((Object)(object)instance == (Object)null) { return "Your inventory isn't ready"; } string text4 = File.ReadAllText(text3); List literals; string fileText; List list = ReadItems(text4, out literals, out fileText); int index; float num = CashOf(literals, out index); if (list.Count == 0 && num < 0.01f) { Invalidate(); return "They aren't carrying anything"; } Directory.CreateDirectory(TakenDir); string text5 = Stamp(); string text6 = text + "_" + text5 + "_Inventory.json"; File.Copy(text3, Path.Combine(TakenDir, text6), overwrite: true); string text7 = NameOf(steamId); TakeRecord takeRecord = new TakeRecord { Save = SaveName(), SteamId = steamId, Name = text7, Utc = DateTime.UtcNow, Backup = text6 }; Dictionary dictionary = new Dictionary(); List list2 = new List(); int num2 = 0; string value = MiniJson.Quote(EmptySlot(literals[0].Value)); foreach (Slot item in list) { ItemInstance val = null; try { val = ItemDeserializer.LoadItem(item.Json); } catch { } if (val == null) { num2++; continue; } int num3 = Math.Max(1, item.Quantity); if (!instance.CanItemFitInInventory(val, num3)) { num2++; continue; } instance.AddItemToInventory(val); dictionary[item.Index] = value; list2.Add($"{num3}x {SafeName(val, item.Id)}"); takeRecord.Slots.Add(new TakenSlot { Index = item.Index, Literal = item.Json, Id = item.Id, Quantity = num3 }); } if (num >= 0.01f && index >= 0 && instance.cashInstance != null) { instance.cashInstance.ChangeBalance(num); dictionary[index] = MiniJson.Quote(CashRx.Replace(literals[index].Value, "\"CashBalance\":0.0", 1)); list2.Add($"${num:N0} cash"); takeRecord.Cash = num; } if (dictionary.Count > 0) { File.WriteAllText(text3, Splice(text4, literals, dictionary)); string text8 = ""; try { text8 = text + "_" + text5 + ".take.json"; int num4 = 2; while (File.Exists(Path.Combine(TakenDir, text8))) { text8 = $"{text}_{text5}-{num4}.take.json"; num4++; } takeRecord.Path = Path.Combine(TakenDir, text8); WriteRecord(takeRecord); } catch (Exception ex) { text8 = ""; MelonLogger.Warning("Couldn't write the take record, so this take can't be given back: " + ex.Message); } Log.Info(string.Format("Took from {0} ({1}): {2}. Their original inventory is saved in UserData/BiggerLobbies/Taken", text7, steamId, string.Join(", ", list2))); AppendLog(steamId, text7, string.Join(", ", list2), text8); } Invalidate(); if (dictionary.Count == 0) { return "Your inventory is full. Make room and try again"; } return (num2 > 0) ? string.Format("Took {0} from {1}. {2} stack{3} left: make room to take the rest", string.Join(", ", list2), text7, num2, (num2 == 1) ? "" : "s") : ("Took everything from " + text7 + ": " + string.Join(", ", list2)); } catch (Exception arg) { MelonLogger.Error($"Take items failed: {arg}"); return "Couldn't take the items. See the log"; } } private static string DataKey(string json) { try { if (!(MiniJson.Parse(json) is Dictionary dictionary)) { return ""; } dictionary.Remove("Quantity"); dictionary.Remove("GameVersion"); return MiniJson.Canonical(dictionary); } catch { return ""; } } private static void Holding(PlayerInventory inv, string id, string key, List found) { List allInventorySlots = inv.GetAllInventorySlots(); if (allInventorySlots == null) { return; } for (int i = 0; i < allInventorySlots.Count; i++) { ItemSlot val = allInventorySlots[i]; if (val == null) { continue; } ItemInstance val2 = null; try { val2 = val.ItemInstance; } catch { } if (val2 != null && !(((BaseItemInstance)val2).ID != id) && ((BaseItemInstance)val2).Quantity > 0 && !val.IsLocked && !val.IsRemovalLocked) { string text = ""; try { text = DataKey(((SaveData)val2.GetItemData()).GetJson(false)); } catch { } if (text.Length != 0 && !(text != key)) { found.Add(new Held { Slot = val, Before = ((BaseItemInstance)val2).Quantity }); } } } } public static string GiveBack(Taken t, Action done) { try { if (!InstanceFinder.IsServer) { return "Only the host can give items back"; } if (_givingBack) { return "Already giving back. Wait a moment"; } if (t.Record == null) { return "That take was logged before Give back existed"; } TakeRecord takeRecord = ReadRecord(t.Record.Path); if (takeRecord == null) { return "Couldn't read what was taken. See the log"; } string text = NameOf(takeRecord.SteamId); if (takeRecord.Save != SaveName()) { return "That take is from a different save"; } if (IsHere(takeRecord.SteamId)) { return text + " is in the game. Items can only be given back while they're away"; } if (takeRecord.AllReturned) { return "Nothing left to give back"; } string text2 = PlayersFolder(); if (text2 == null) { return "Couldn't find this save's player folders"; } string text3 = Path.Combine(text2, "Player_" + takeRecord.SteamId, "Inventory.json"); if (!File.Exists(text3)) { return text + " has no saved inventory in this save"; } double totalSeconds = (DateTime.UtcNow - File.GetLastWriteTimeUtc(text3)).TotalSeconds; if (totalSeconds < 10.0) { return $"{text} only just left. Try again in {Math.Ceiling(10.0 - totalSeconds)} s"; } PlayerInventory instance = PlayerSingleton.Instance; if ((Object)(object)instance == (Object)null) { return "Your inventory isn't ready"; } List list = ParseItemsArray(File.ReadAllText(text3)); if (list.Count == 0) { return "Couldn't read " + text + "'s saved inventory"; } bool flag = false; bool flag2 = false; HashSet hashSet = new HashSet(); List list2 = new List(); Dictionary dictionary = new Dictionary(); foreach (TakenSlot slot in takeRecord.Slots) { int num = slot.Quantity - slot.Returned; if (num <= 0) { continue; } if (slot.Index < 0 || slot.Index >= list.Count || hashSet.Contains(slot.Index)) { flag = true; continue; } string value = list[slot.Index].Value; Match match = IdRx.Match(value); if (!match.Success || match.Groups[1].Value.Length != 0 || TypeRx.Match(value).Groups[1].Value == "CashData") { flag = true; continue; } string text4 = DataKey(slot.Literal); if (text4.Length == 0) { flag2 = true; continue; } if (!dictionary.TryGetValue(text4, out var value2)) { value2 = new Stock { Id = slot.Id }; Holding(instance, slot.Id, text4, value2.Slots); uint val = 0u; try { val = instance.GetAmountOfItem(slot.Id); } catch { } value2.Usable = Math.Min(value2.Slots.Sum((Held x) => x.Before), (int)Math.Min(val, 2147483647u)); dictionary[text4] = value2; } int num2 = Math.Min(num, value2.Usable - value2.Asked); if (num2 <= 0) { flag2 = true; continue; } if (num2 < num) { flag2 = true; } value2.Asked += num2; hashSet.Add(slot.Index); list2.Add(new Pending { Slot = slot, Key = text4, Asked = num2 }); } foreach (Stock value3 in dictionary.Values) { int num3 = value3.Asked; foreach (Held slot2 in value3.Slots) { if (num3 <= 0) { break; } try { int num4 = Math.Min(num3, slot2.Before); if (num4 > 0) { slot2.Slot.ChangeQuantity(-num4, false); num3 -= num4; } } catch (Exception ex) { MelonLogger.Warning("Couldn't take " + value3.Id + " out of your inventory: " + ex.Message); } } } int index = -1; float num5 = 0f; float num6 = 0f; double num7 = takeRecord.Cash - takeRecord.CashReturned; if (num7 >= 0.01) { CashOf(list, out index); if (index < 0 || !CashRx.IsMatch(list[index].Value)) { flag = true; index = -1; } else if (instance.cashInstance == null) { flag2 = true; index = -1; } else { num5 = instance.cashInstance.Balance; num6 = (float)(Math.Floor(Math.Min(num7, num5) * 100.0) / 100.0); if (num6 >= 0.01f) { try { instance.cashInstance.ChangeBalance(0f - num6); } catch (Exception ex2) { MelonLogger.Warning("Couldn't take the cash out of your inventory: " + ex2.Message); } } else { num6 = 0f; index = -1; } if ((double)num6 < num7 - 0.005) { flag2 = true; } } } if (list2.Count == 0 && index < 0) { return (flag2 && !flag) ? ("You don't have any of what you took from " + text) : ((flag && !flag2) ? (text + "'s slots for those items aren't empty any more. Nothing given back") : ("Nothing given back to " + text + ". You don't have the items, or their slots are in use")); } _givingBack = true; MelonCoroutines.Start(FinishGiveBack(takeRecord, text3, text, instance, list2, dictionary, index, num5, num6, flag, flag2, done)); return "Giving back to " + text + "..."; } catch (Exception arg) { MelonLogger.Error($"Give back failed: {arg}"); return "Couldn't give the items back. See the log"; } } private static IEnumerator FinishGiveBack(TakeRecord rec, string file, string name, PlayerInventory inv, List pending, Dictionary stock, int cashIndex, float cashBefore, float cashAsked, bool busy, bool shortOf, Action done) { yield return (object)new WaitForSecondsRealtime(0.5f); string msg; try { msg = WriteGiveBack(rec, file, name, inv, pending, stock, cashIndex, cashBefore, cashAsked, busy, shortOf); } catch (Exception ex) { Exception e = ex; MelonLogger.Error($"Give back failed after taking from your inventory: {e}"); msg = "Give back failed. See the log"; } _givingBack = false; Invalidate(); try { done(msg); } catch { } } private static string WriteGiveBack(TakeRecord rec, string file, string name, PlayerInventory inv, List pending, Dictionary stock, int cashIndex, float cashBefore, float cashAsked, bool busy, bool shortOf) { Dictionary dictionary = new Dictionary(); foreach (KeyValuePair kv in stock) { dictionary[kv.Key] = Math.Min(kv.Value.Asked, kv.Value.Slots.Sum((Held h) => h.Dropped(kv.Value.Id))); } List<(Pending, int)> list = new List<(Pending, int)>(); foreach (Pending item2 in pending) { int num = Math.Min(item2.Asked, dictionary[item2.Key]); dictionary[item2.Key] -= num; if (num < item2.Asked) { shortOf = true; } if (num > 0) { list.Add((item2, num)); } } float num2 = 0f; if (cashIndex >= 0 && inv.cashInstance != null) { num2 = (float)(Math.Floor(Math.Min(cashAsked, cashBefore - inv.cashInstance.Balance) * 100f) / 100.0); } if (IsHere(rec.SteamId) || !File.Exists(file)) { foreach (var (pending2, n) in list) { Restore(inv, pending2.Slot, n); } if (num2 >= 0.01f) { CashInstance cashInstance = inv.cashInstance; if (cashInstance != null) { cashInstance.ChangeBalance(num2); } } return File.Exists(file) ? (name + " rejoined while giving back. Nothing was given back") : (name + "'s saved inventory is gone. Nothing was given back"); } if (list.Count == 0 && num2 < 0.01f) { return "Nothing given back to " + name + ". Your inventory didn't change"; } string text = File.ReadAllText(file); List list2 = ParseItemsArray(text); for (int num3 = list.Count - 1; num3 >= 0; num3--) { int index = list[num3].Item1.Slot.Index; Match match = ((index < list2.Count) ? IdRx.Match(list2[index].Value) : null); if (match == null || !match.Success || match.Groups[1].Value.Length != 0) { Restore(inv, list[num3].Item1.Slot, list[num3].Item2); list.RemoveAt(num3); busy = true; } } if (cashIndex >= list2.Count || (cashIndex >= 0 && !CashRx.IsMatch(list2[cashIndex].Value))) { if (num2 >= 0.01f) { CashInstance cashInstance2 = inv.cashInstance; if (cashInstance2 != null) { cashInstance2.ChangeBalance(num2); } } num2 = 0f; busy = true; } if (list.Count == 0 && num2 < 0.01f) { return "Nothing given back to " + name + ". Their slots aren't empty any more"; } Dictionary dictionary2 = new Dictionary(); List list3 = new List(); foreach (var (pending3, num4) in list) { dictionary2[pending3.Slot.Index] = MiniJson.Quote(QtyRx.Replace(pending3.Slot.Literal, "\"Quantity\":" + num4, 1)); pending3.Slot.Returned += num4; ItemInstance item = null; try { item = ItemDeserializer.LoadItem(pending3.Slot.Literal); } catch { } list3.Add($"{num4}x {SafeName(item, pending3.Slot.Id)}"); } if (num2 >= 0.01f) { string value = list2[cashIndex].Value; Match match2 = CashRx.Match(value); double result; double num5 = ((match2.Success && double.TryParse(match2.Groups[1].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out result)) ? result : 0.0); string text2 = MiniJson.Number(Math.Round(num5 + (double)num2, 2)); if (text2.IndexOf('.') < 0 && text2.IndexOf('E') < 0) { text2 += ".0"; } dictionary2[cashIndex] = MiniJson.Quote(CashRx.Replace(value, "\"CashBalance\":" + text2, 1)); rec.CashReturned += num2; list3.Add($"${num2:N0}"); } Directory.CreateDirectory(TakenDir); File.Copy(file, Path.Combine(TakenDir, $"{rec.SteamId}_{Stamp()}_BeforeGiveBack_Inventory.json"), overwrite: true); File.WriteAllText(file, Splice(text, list2, dictionary2)); WriteRecord(rec); string text3 = string.Join(", ", list3); Log.Info($"Gave back to {name} ({rec.SteamId}) from the take at {rec.Utc:u}: {text3}"); AppendLog(rec.SteamId, name, "Gave back " + text3); if (shortOf) { return "Gave back " + text3 + " to " + name + ". You don't have the rest"; } if (busy) { return "Gave back " + text3 + " to " + name + ". Some of their slots aren't empty any more"; } return "Gave back " + text3 + " to " + name; } private static void Restore(PlayerInventory inv, TakenSlot s, int n) { ItemInstance val = null; try { val = ItemDeserializer.LoadItem(QtyRx.Replace(s.Literal, "\"Quantity\":" + n, 1)); } catch { } if (val != null) { inv.AddItemToInventory(val); } else { MelonLogger.Warning($"Couldn't put {n}x {s.Id} back in your inventory"); } } public static string SafeName(ItemInstance? item, string fallback) { try { string text = ((item != null) ? ((BaseItemInstance)item).Name : null); if (!string.IsNullOrEmpty(text)) { return text; } } catch { } return fallback; } public static Sprite? Icon(ItemInstance? item) { try { return (item != null) ? ((BaseItemInstance)item).Icon : null; } catch { return null; } } } public static class Friends { public struct Friend { public ulong SteamId; public string Name; public bool Online; public bool InThisGame; } public enum Presence { Offline, Online, Playing } public static List List() { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Invalid comparison between Unknown and I4 //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002d: 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_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) List list = new List(); try { uint appId = SteamUtils.GetAppID().m_AppId; int friendCount = SteamFriends.GetFriendCount((EFriendFlags)4); for (int i = 0; i < friendCount; i++) { CSteamID friendByIndex = SteamFriends.GetFriendByIndex(i, (EFriendFlags)4); EPersonaState friendPersonaState = SteamFriends.GetFriendPersonaState(friendByIndex); bool inThisGame = false; try { FriendGameInfo_t val = default(FriendGameInfo_t); inThisGame = SteamFriends.GetFriendGamePlayed(friendByIndex, ref val) && ((CGameID)(ref val.m_gameID)).AppID().m_AppId == appId; } catch { } list.Add(new Friend { SteamId = friendByIndex.m_SteamID, Name = (SteamFriends.GetFriendPersonaName(friendByIndex) ?? friendByIndex.m_SteamID.ToString()), Online = ((int)friendPersonaState > 0), InThisGame = inThisGame }); } } catch (Exception ex) { MelonLogger.Warning("Couldn't read your Steam friends: " + ex.Message); } return (from f in list orderby f.InThisGame descending, f.Online descending select f).ThenBy((Friend f) => f.Name, StringComparer.OrdinalIgnoreCase).ToList(); } public static Presence StateOf(ulong steamId) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Invalid comparison between Unknown and I4 //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0023: 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_003e: Unknown result type (might be due to invalid IL or missing references) try { CSteamID val = default(CSteamID); ((CSteamID)(ref val))..ctor(steamId); if ((int)SteamFriends.GetFriendPersonaState(val) == 0) { return Presence.Offline; } FriendGameInfo_t val2 = default(FriendGameInfo_t); if (SteamFriends.GetFriendGamePlayed(val, ref val2) && ((CGameID)(ref val2.m_gameID)).AppID().m_AppId == SteamUtils.GetAppID().m_AppId) { return Presence.Playing; } return Presence.Online; } catch { return Presence.Offline; } } public static string NameOf(ulong steamId) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) try { string friendPersonaName = SteamFriends.GetFriendPersonaName(new CSteamID(steamId)); if (!string.IsNullOrEmpty(friendPersonaName) && friendPersonaName != "[unknown]") { return friendPersonaName; } } catch { } return steamId.ToString(); } } public static class Avatars { private static readonly Dictionary _cache = new Dictionary(); private static readonly HashSet _requested = new HashSet(); private static readonly List<(RawImage img, ulong id)> _pending = new List<(RawImage, ulong)>(); private static float _nextTry; public static void Show(RawImage img, ulong id) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) ((Graphic)img).color = new Color(0.25f, 0.25f, 0.25f, 1f); img.texture = null; if (id != 0) { Texture2D val = Get(id); if ((Object)(object)val != (Object)null) { Apply(img, val); } else { _pending.Add((img, id)); } } } private static void Apply(RawImage img, Texture2D tex) { //IL_000a: 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) img.texture = (Texture)(object)tex; ((Graphic)img).color = Color.white; img.uvRect = new Rect(0f, 1f, 1f, -1f); } public static void Update() { if (_pending.Count == 0 || Time.unscaledTime < _nextTry) { return; } _nextTry = Time.unscaledTime + 0.5f; for (int num = _pending.Count - 1; num >= 0; num--) { var (val, id) = _pending[num]; if ((Object)(object)val == (Object)null || ((Il2CppObjectBase)val).WasCollected) { _pending.RemoveAt(num); } else { Texture2D val2 = Get(id); if (!((Object)(object)val2 == (Object)null)) { Apply(val, val2); _pending.RemoveAt(num); } } } } private static Texture2D? Get(ulong id) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Expected O, but got Unknown if (_cache.TryGetValue(id, out var value) && (Object)(object)value != (Object)null && !((Il2CppObjectBase)value).WasCollected) { return value; } try { CSteamID val = default(CSteamID); ((CSteamID)(ref val))..ctor(id); int mediumFriendAvatar = SteamFriends.GetMediumFriendAvatar(val); if (mediumFriendAvatar <= 0) { if (_requested.Add(id)) { SteamFriends.RequestUserInformation(val, false); } return null; } uint num = default(uint); uint num2 = default(uint); if (!SteamUtils.GetImageSize(mediumFriendAvatar, ref num, ref num2) || num == 0 || num2 == 0) { return null; } int num3 = (int)(num * num2 * 4); Il2CppStructArray val2 = new Il2CppStructArray((long)num3); if (!SteamUtils.GetImageRGBA(mediumFriendAvatar, val2, num3)) { return null; } Texture2D val3 = new Texture2D((int)num, (int)num2, (TextureFormat)4, false); val3.LoadRawTextureData(val2); val3.Apply(); ((Object)val3).hideFlags = (HideFlags)32; _cache[id] = val3; return val3; } catch { return null; } } } public static class BanLength { public static readonly (string label, TimeSpan? length)[] Options = new(string, TimeSpan?)[4] { ("1 hour", TimeSpan.FromHours(1.0)), ("1 day", TimeSpan.FromDays(1.0)), ("1 week", TimeSpan.FromDays(7.0)), ("Permanent", null) }; public static string Label(TimeSpan? length) { (string, TimeSpan?)[] options = Options; for (int i = 0; i < options.Length; i++) { (string, TimeSpan?) tuple = options[i]; var (result, _) = tuple; if (tuple.Item2 == length) { return result; } } return length.HasValue ? $"{length.Value.TotalHours:0} h" : "Permanent"; } } public static class HostPlayers { public struct Row { public string Name; public ulong SteamId; public int Ping; public int ClientId; public bool Fake; } private static List? _fakes; private static int _fakeCount = -1; private static bool _pingWarned; private static void AddFakes(List rows) { int fakePlayers = LobbySize.FakePlayers; if (fakePlayers <= 0) { return; } if (_fakes == null || _fakeCount != fakePlayers) { _fakeCount = fakePlayers; _fakes = new List(); List list = Friends.List(); for (int i = 0; i < fakePlayers; i++) { bool flag = list.Count > 0; Friends.Friend friend = (flag ? list[i % list.Count] : default(Friends.Friend)); _fakes.Add(new Row { Name = (flag ? ((i < list.Count) ? friend.Name : $"{friend.Name} {i / list.Count + 1}") : $"Test player {i + 1}"), SteamId = (flag ? friend.SteamId : 0), ClientId = -1000 - i, Fake = true }); } } float unscaledTime = Time.unscaledTime; for (int j = 0; j < _fakes.Count; j++) { Row item = _fakes[j]; item.Ping = 30 + j * 37 % 140 + (int)(Mathf.PerlinNoise((float)j * 0.7f, unscaledTime * 0.3f) * 25f); rows.Add(item); } } public static List List() { List list = new List(); try { if (!InstanceFinder.IsServer) { return list; } List playerList = Player.PlayerList; if (playerList == null) { return list; } ServerSocket server = SteamServer(); for (int i = 0; i < playerList.Count; i++) { Player val = playerList[i]; if (!((Object)(object)val == (Object)null) && !val.IsLocalPlayer) { NetworkConnection connection = val.Connection; if (!(connection == (NetworkConnection)null) && !connection.IsLocalClient) { ulong num = BanList.VerifiedSteamId(connection.ClientId); list.Add(new Row { Name = (string.IsNullOrEmpty(val.PlayerName) ? "Unnamed player" : val.PlayerName), SteamId = num, Ping = PingOf(server, num), ClientId = connection.ClientId }); } } } } catch (Exception ex) { MelonLogger.Warning("Couldn't read the player list: " + ex.Message); } try { if (InstanceFinder.IsServer) { AddFakes(list); } } catch { } return list; } public static string Kick(Row r, bool ban, TimeSpan? length = null, string reason = "") { if (r.Fake) { return r.Name + " is a test player (DebugFakePlayers). Nothing to " + (ban ? "ban" : "kick"); } try { if (ban) { BanList.Ban(r.SteamId, r.Name, length, reason); return "Banned " + r.Name + " (" + BanLength.Label(length).ToLowerInvariant() + ")"; } NetworkConnection val = FindConnection(r.ClientId); if (val == (NetworkConnection)null) { return r.Name + " has already left"; } if (val.IsLocalClient) { return ""; } KickNotice.Remove(val, r.SteamId, KickNotice.Kind.Kick); Log.Info("Kicked " + r.Name + ((r.SteamId != 0L) ? $" ({r.SteamId})" : "")); return "Kicked " + r.Name + ". They can rejoin unless you ban them"; } catch (Exception ex) { return "Couldn't remove " + r.Name + ": " + ex.Message; } } public static void DisconnectSteamId(ulong id, TimeSpan? length = null, string reason = "") { try { if (id == 0L || !InstanceFinder.IsServer) { return; } List playerList = Player.PlayerList; if (playerList == null) { return; } for (int i = 0; i < playerList.Count; i++) { Player obj = playerList[i]; NetworkConnection val = ((obj != null) ? obj.Connection : null); if (!(val == (NetworkConnection)null) && !val.IsLocalClient && val.IsActive && BanList.VerifiedSteamId(val.ClientId) == id) { KickNotice.Remove(val, id, KickNotice.Kind.Ban, length, reason); Log.Info($"Disconnected {playerList[i].PlayerName} ({id}): banned"); } } } catch (Exception ex) { MelonLogger.Warning("Couldn't disconnect banned player: " + ex.Message); } } private static NetworkConnection? FindConnection(int clientId) { List playerList = Player.PlayerList; if (playerList == null) { return null; } for (int i = 0; i < playerList.Count; i++) { Player obj = playerList[i]; NetworkConnection val = ((obj != null) ? obj.Connection : null); if (val != (NetworkConnection)null && val.ClientId == clientId && val.IsActive) { return val; } } return null; } private static ServerSocket? SteamServer() { try { TransportManager transportManager = InstanceFinder.TransportManager; Transport val = ((transportManager != null) ? transportManager.Transport : null); if ((Object)(object)val == (Object)null) { return null; } Multipass val2 = ((Il2CppObjectBase)val).TryCast(); if (((val2 != null) ? val2._transports : null) != null) { for (int i = 0; i < val2._transports.Count; i++) { Transport obj = val2._transports[i]; FishySteamworks val3 = ((obj != null) ? ((Il2CppObjectBase)obj).TryCast() : null); if (((val3 != null) ? val3._server : null) != null) { return val3._server; } } } FishySteamworks obj2 = ((Il2CppObjectBase)val).TryCast(); return (obj2 != null) ? obj2._server : null; } catch { return null; } } private static int PingOf(ServerSocket? server, ulong sid) { //IL_0025: 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) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Expected O, but got Unknown //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Expected O, but got Unknown //IL_008d: 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_009a: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Invalid comparison between Unknown and I4 if (server == null || sid == 0) { return -1; } try { int num = default(int); if (!server._steamIds.First.TryGetValue(new CSteamID(sid), ref num)) { return -1; } HSteamNetConnection val = default(HSteamNetConnection); if (!server._steamConnections.Second.TryGetValue(num, ref val)) { return -1; } SteamNetConnectionRealTimeStatus_t val2 = new SteamNetConnectionRealTimeStatus_t { reserved = new Il2CppStructArray(16L) }; SteamNetConnectionRealTimeLaneStatus_t val3 = new SteamNetConnectionRealTimeLaneStatus_t { reserved = new Il2CppStructArray(10L) }; EResult connectionRealTimeStatus = SteamNetworkingSockets.GetConnectionRealTimeStatus(val, ref val2, 0, ref val3); return ((int)connectionRealTimeStatus == 1) ? val2.m_nPing : (-1); } catch (Exception ex) { if (!_pingWarned) { _pingWarned = true; MelonLogger.Warning("Couldn't read ping: " + ex.Message); } return -1; } } } public static class HostSettingsMenu { private sealed class Ui { public bool InGame; public MenuScreen Screen = null; public MenuScreen Picker = null; public RectTransform Layout = null; public RectTransform PickerLayout = null; public TextMeshProUGUI PickerTitle = null; public GameObject LabelT = null; public GameObject TextT = null; public GameObject ButtonT = null; public GameObject SliderT = null; public float RowW; public GameObject? MenuButton; public RectTransform? Panel; public float PanelH0; public float PanelY0; public float ButtonStep; public bool ButtonShown = true; public readonly List<(Button b, LobbyPrivacy.Mode m)> PrivacyButtons = new List<(Button, LobbyPrivacy.Mode)>(); public Button WlOff = null; public Button WlOn = null; public Slider Size = null; public TextMeshProUGUI SizeValue = null; public TextMeshProUGUI SizeHint = null; public TextMeshProUGUI Status = null; public TextMeshProUGUI? PickerStatus; public TextMeshProUGUI? PrivacyHint; public TextMeshProUGUI PlayersHeading = null; public TextMeshProUGUI WhiteHeading = null; public TextMeshProUGUI BlackHeading = null; public RectTransform Players = null; public RectTransform White = null; public RectTransform Black = null; public bool PickForWhitelist; public string LastPlayersKey = ""; public string LastWhiteKey = ""; public string LastBlackKey = ""; public ulong ConfirmBlacklist; public readonly List<(Button b, TimeSpan? len)> BanLenButtons = new List<(Button, TimeSpan?)>(); public TextMeshProUGUI CrewsHeading = null; public TextMeshProUGUI DepartedHeading = null; public RectTransform Departed = null; public string LastDepartedKey = ""; public string LastTakenKey = ""; public TextMeshProUGUI TakenHeading = null; public RectTransform TakenList = null; public readonly List Tabs = new List(); public readonly List TabLabels = new List(); public readonly List Pages = new List(); public int Tab; public RectTransform CrewList = null; public TMP_InputField? CrewName; public TMP_InputField? BanReason; public string LastCrewKey = ""; public string ConfirmDeleteCrew = ""; public Button WorldOff = null; public Button WorldOn = null; public Button PlayersOff = null; public Button PlayersOn = null; public readonly List<(Button off, Button on, Func get)> DiscordToggles = new List<(Button, Button, Func)>(); public TextMeshProUGUI? DiscordHint; public Slider WorldEvery = null; public Slider PlayersEvery = null; public TextMeshProUGUI WorldValue = null; public TextMeshProUGUI PlayersValue = null; public TextMeshProUGUI LastSave = null; public readonly Dictionary PingTexts = new Dictionary(); public readonly List<(GameObject row, string name)> PickerRows = new List<(GameObject, string)>(); public TMP_InputField? Search; public TextMeshProUGUI? PickerCount; public TextMeshProUGUI? NoMatch; public int FriendCount; public int OnlineCount; } private static readonly Color Accent = new Color(0.281f, 0.527f, 0.755f, 1f); private static readonly Color Grey = new Color(0.439f, 0.439f, 0.439f, 1f); private static readonly Color Muted = new Color(0.7f, 0.7f, 0.7f, 1f); private static MelonPreferences_Entry? _keyEntry; private static Key _key = (Key)99; private static Ui? _menu; private static Ui? _pause; private static int _pendingSize = -1; private static float _applySizeAt; private static float _nextRefresh; private static readonly bool[] _injecting = new bool[2]; private static readonly HashSet _awake = new HashSet(); private static readonly HashSet KeepScripts = new HashSet { "MenuScreen", "MonoState", "ButtonSound", "AudioSourceController", "CanvasGroupFader" }; private const float LabelX = 12f; private const float ControlX = 200f; private const float RowH = 36f; private const float AvatarS = 28f; private const float NameX = 52f; private static readonly Color Playing = new Color(0.44f, 0.84f, 0.38f, 1f); private static readonly Color OnlineDot = new Color(0.44f, 0.84f, 0.38f, 1f); private static readonly Color Blocked = new Color(0.86f, 0.36f, 0.32f, 1f); private static readonly Color Danger = new Color(0.7f, 0.22f, 0.2f, 1f); private static TimeSpan? _banLength; private static bool _prefsDirty; private static Sprite? _circle; private static Sprite? _fade; private static bool _spritesSearched; private static readonly string[] TabNames = new string[4] { "Players", "Access", "Lobby", "Saving" }; private static GameObject? _hiddenGrid; public static void Init(MelonPreferences_Category cat) { //IL_0047: 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) //IL_0093: Unknown result type (might be due to invalid IL or missing references) _keyEntry = cat.CreateEntry("HostPanelKey", "F6", "Host settings key", "Key that opens Host settings while you host a save. The same screen is in the pause menu and the main menu.", false, false, (ValueValidator)null, (string)null); if (!Enum.TryParse(_keyEntry.Value?.Trim(), ignoreCase: true, out _key) || (int)_key == 0 || !Enum.IsDefined(typeof(Key), _key)) { MelonLogger.Warning("HostPanelKey '" + _keyEntry.Value + "' isn't a key name; using F6"); _key = (Key)99; } } public static void OnSceneLoaded(string scene) { if (scene == "Menu" && !_injecting[0]) { _menu = null; _injecting[0] = true; MelonCoroutines.Start(InjectWhenReady(inGame: false)); } else if (scene == "Main" && !_injecting[1]) { _pause = null; Whitelist.WarnIfEmpty(); _injecting[1] = true; MelonCoroutines.Start(InjectWhenReady(inGame: true)); } } private static IEnumerator InjectWhenReady(bool inGame) { try { foreach (object item in InjectLoop(inGame)) { yield return item; } } finally { _injecting[inGame ? 1 : 0] = false; } } private static IEnumerable InjectLoop(bool inGame) { for (int i = 0; i < 120; i++) { yield return (object?)new WaitForSecondsRealtime(0.5f); Ui ui; try { ui = (inGame ? InjectPause() : InjectMainMenu()); } catch (Exception ex) { MelonLogger.Error(string.Format(arg1: ex, format: "Couldn't add Host settings to the {0} menu: {1}", arg0: inGame ? "pause" : "main")); break; } if (ui != null) { if (inGame) { _pause = ui; } else { _menu = ui; } Log.Info("Host settings added to the " + (inGame ? "pause" : "main") + " menu"); break; } } } private static Ui? InjectMainMenu() { MenuScreen val = null; GameObject val2 = null; foreach (MenuScreen item in Object.FindObjectsOfType(true)) { if (((Object)item).name == "Home" && (Object)(object)((Component)item).transform.Find("Bank/Panel") != (Object)null) { val = item; } if (((Object)item).name == "Settings" && (Object)(object)((Component)item).GetComponent() != (Object)null) { val2 = ((Component)item).gameObject; } } if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null) { return null; } return Build(val, val2, ((Component)val).transform.Find("Bank/Panel"), inGame: false); } private static Ui? InjectPause() { PauseMenu instance = Singleton.Instance; if ((Object)(object)instance == (Object)null || (Object)(object)instance.Container == (Object)null) { return null; } Transform obj = ((Transform)instance.Container).Find("Menu"); MenuScreen val = ((obj != null) ? ((Component)obj).GetComponent() : null); Transform obj2 = ((Transform)instance.Container).Find("SettingsScreen_Ingame"); GameObject val2 = ((obj2 != null) ? ((Component)obj2).gameObject : null); Transform val3 = ((Transform)instance.Container).Find("Menu/Bank/Panel"); if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null || (Object)(object)val3 == (Object)null) { return null; } return Build(val, val2, val3, inGame: true); } private static Ui Build(MenuScreen home, GameObject settings, Transform panel, bool inGame) { RemoveOld(settings.transform.parent, panel); Ui ui = new Ui { InGame = inGame }; ui.Screen = CloneScreen(settings, home, "Host settings", ui, keepTemplates: true); ui.Picker = CloneScreen(settings, ui.Screen, "Add from friends", ui, keepTemplates: false); ui.PickerTitle = ((Component)((Component)ui.Picker).transform.Find("Title")).GetComponent(); BuildMain(ui); SetupTabs(ui); Header(ui, ui.Screen, delegate { ui.Screen.Close(); }, main: true); Header(ui, ui.Picker, delegate { ui.Picker.Close(); }, main: false); ActivateOnce(ui.Screen); ActivateOnce(ui.Picker); AddMenuButton(ui, panel); return ui; } private static void ActivateOnce(MenuScreen s) { if (_awake.Contains(((Il2CppObjectBase)s).Pointer)) { return; } Transform parent = ((Component)s).transform.parent; if (!((Object)(object)parent != (Object)null) || ((Component)parent).gameObject.activeInHierarchy) { ((Component)s).gameObject.SetActive(true); if (!s.IsOpen) { ((Component)s).gameObject.SetActive(false); } _awake.Add(((Il2CppObjectBase)s).Pointer); } } private static MenuScreen CloneScreen(GameObject settings, MenuScreen previous, string title, Ui ui, bool keepTemplates) { //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_02ac: Unknown result type (might be due to invalid IL or missing references) //IL_02b6: Expected O, but got Unknown //IL_0342: Unknown result type (might be due to invalid IL or missing references) //IL_0349: Expected O, but got Unknown //IL_0463: Unknown result type (might be due to invalid IL or missing references) //IL_0468: Unknown result type (might be due to invalid IL or missing references) bool activeSelf = settings.activeSelf; settings.SetActive(false); GameObject val = Object.Instantiate(settings, settings.transform.parent); settings.SetActive(activeSelf); ((Object)val).name = "BiggerLobbies " + title; SettingsScreen component = val.GetComponent(); int exitInputPriority = (((Object)(object)component != (Object)null) ? ((MenuScreen)component).ExitInputPriority : 0); List list = new List(); if (keepTemplates && (Object)(object)component != (Object)null && component.Categories != null) { for (int i = 0; i < ((Il2CppArrayBase)(object)component.Categories).Length; i++) { SettingsCategory obj = ((Il2CppArrayBase)(object)component.Categories)[i]; Toggle val2 = ((obj != null) ? obj.Toggle : null); if ((Object)(object)val2 != (Object)null) { list.Add(val2); } } } Transform val3 = ((list.Count >= 4) ? ((Component)list[0]).transform.parent : null); if ((Object)(object)component != (Object)null) { Object.DestroyImmediate((Object)(object)component); } RectTransform component2 = val.GetComponent(); component2.sizeDelta = new Vector2(760f, 580f); for (int num = val.transform.childCount - 1; num >= 0; num--) { Transform child = val.transform.GetChild(num); if (!(((Object)child).name == "Background") && !(((Object)child).name == "Title") && !(((Object)child).name == "Content") && (!((Object)(object)val3 != (Object)null) || !val3.IsChildOf(child))) { Object.DestroyImmediate((Object)(object)((Component)child).gameObject); } } ((TMP_Text)((Component)val.transform.Find("Title")).GetComponent()).text = title; Transform val4 = val.transform.Find("Content"); for (int num2 = val4.childCount - 1; num2 >= 0; num2--) { Transform child2 = val4.GetChild(num2); if (((Object)child2).name != "Controls") { Object.DestroyImmediate((Object)(object)((Component)child2).gameObject); } } Transform val5 = val4.Find("Controls"); ((Component)val5).gameObject.SetActive(true); RectTransform component3 = ((Component)val5.Find("ControlsPanel/Scroll View/Viewport/Vertical Layout")).GetComponent(); VerticalLayoutGroup component4 = ((Component)component3).GetComponent(); if ((Object)(object)component4 != (Object)null) { ((HorizontalOrVerticalLayoutGroup)component4).spacing = 4f; ((LayoutGroup)component4).padding = new RectOffset(20, 20, 16, 40); ((LayoutGroup)component4).childAlignment = (TextAnchor)0; } if ((Object)(object)val3 != (Object)null) { for (int num3 = list.Count - 1; num3 >= 4; num3--) { Object.DestroyImmediate((Object)(object)((Component)list[num3]).gameObject); } for (int j = 0; j < 4; j++) { ui.Tabs.Add(list[j]); } } if (keepTemplates) { GameObject val6 = new GameObject("Templates"); val6.SetActive(false); val6.transform.SetParent(val.transform, false); ui.LabelT = Keep(((Transform)component3).Find("SettingsLabel"), val6); ui.TextT = Keep(((Transform)component3).Find("SettingsSlider/Label"), val6); ui.ButtonT = Keep(((Transform)component3).Find("BindingLabel/RestoreDefault"), val6); ui.SliderT = Keep(((Transform)component3).Find("SettingsSlider"), val6); } for (int num4 = ((Transform)component3).childCount - 1; num4 >= 0; num4--) { Object.DestroyImmediate((Object)(object)((Component)((Transform)component3).GetChild(num4)).gameObject); } Strip(val); MenuScreen val7 = val.AddComponent(); val7.Group = val.GetComponent(); val7.State = val.GetComponent(); val7.PreviousScreen = previous; val7.ExitInputPriority = exitInputPriority; if (keepTemplates) { ui.Layout = component3; } else { ui.PickerLayout = component3; } Rect rect = ((Component)((Transform)component3).parent).GetComponent().rect; float num5 = ((Rect)(ref rect)).width - 40f; ui.RowW = ((float.IsNaN(num5) || num5 < 400f) ? 680f : num5); return val7; } private static GameObject Keep(Transform? t, GameObject holder) { if ((Object)(object)t == (Object)null) { throw new Exception("settings screen layout changed; a template is missing"); } GameObject val = Object.Instantiate(((Component)t).gameObject, holder.transform); val.SetActive(true); return val; } private static void Strip(GameObject go) { //IL_0129: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Expected O, but got Unknown //IL_0168: Unknown result type (might be due to invalid IL or missing references) //IL_0172: Expected O, but got Unknown Il2CppArrayBase componentsInChildren = go.GetComponentsInChildren(true); for (int num = componentsInChildren.Length - 1; num >= 0; num--) { MonoBehaviour val = componentsInChildren[num]; if (!((Object)(object)val == (Object)null)) { Type il2CppType = ((Object)val).GetIl2CppType(); string text = il2CppType.Namespace ?? ""; if ((text.StartsWith("ScheduleOne") || text.StartsWith("Il2CppScheduleOne")) && !KeepScripts.Contains(((MemberInfo)il2CppType).Name)) { Object.DestroyImmediate((Object)(object)val); } } } foreach (Transform componentsInChild in go.GetComponentsInChildren(true)) { if (((Object)componentsInChild).name == "Selected Frame" || ((Object)componentsInChild).name == "SelectedFrame") { ((Component)componentsInChild).gameObject.SetActive(false); } } foreach (Button componentsInChild2 in go.GetComponentsInChildren