Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of ServerPlayerList v1.3.2
ServerPlayerList.dll
Decompiled 19 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using JetBrains.Annotations; using JoksterCube.ServerPlayerList.Common; using JoksterCube.ServerPlayerList.Domain; using JoksterCube.ServerPlayerList.MonoBehaviours; using JoksterCube.ServerPlayerList.Settings; using Microsoft.CodeAnalysis; using ServerSync; using TMPro; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("ServerPlayerList")] [assembly: AssemblyDescription("Shows how many players are online, with their names, distances and directions.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("JoksterCube")] [assembly: AssemblyProduct("ServerPlayerList")] [assembly: AssemblyCopyright("Copyright © 2025")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("39da2684-0d87-45f0-9265-a09885c0b1ba")] [assembly: AssemblyFileVersion("1.3.2")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.3.2.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 JoksterCube.ServerPlayerList { [BepInPlugin("JoksterCube.ServerPlayerList", "ServerPlayerList", "1.3.2")] public class Plugin : BaseUnityPlugin { public static readonly ManualLogSource ModLogger = Logger.CreateLogSource("ServerPlayerList"); internal static string ConnectionError = string.Empty; private static readonly ConfigSync ConfigSync = new ConfigSync("JoksterCube.ServerPlayerList") { DisplayName = "ServerPlayerList", CurrentVersion = "1.3.2", MinimumRequiredVersion = "1.3.2" }; internal static readonly CustomSyncedValue<string> RconPlayerName = new CustomSyncedValue<string>(ConfigSync, "RconPlayerName", string.Empty); private readonly string ConfigFileFullPath; private FileSystemWatcher? _configWatcher; private readonly Harmony _harmony; private const float RconNameCheckInterval = 1f; private float _nextRconNameCheck; internal static bool InitialConfigSyncDone => ConfigSync.InitialSyncDone; private void Awake() { PluginConfig.Build(((BaseUnityPlugin)this).Config, ConfigSync); Assembly executingAssembly = Assembly.GetExecutingAssembly(); _harmony.PatchAll(executingAssembly); SetupWatcher(); } private void Update() { if (Time.unscaledTime >= _nextRconNameCheck) { _nextRconNameCheck = Time.unscaledTime + 1f; UpdateRconPlayerName(); } InputManager.Update(this); } private static void UpdateRconPlayerName() { if (Object.op_Implicit((Object)(object)ZNet.instance) && ZNet.instance.IsServer()) { string text = string.Empty; ConfigEntry<string> val = default(ConfigEntry<string>); if (Chainloader.PluginInfos.TryGetValue("org.tristan.rcon", out var value) && Object.op_Implicit((Object)(object)value.Instance) && value.Instance.Config.TryGetEntry<string>("3. Chat", "Server name", ref val)) { text = val.Value; } if (RconPlayerName.Value != text) { RconPlayerName.Value = text; } } } private void OnDestroy() { _configWatcher?.Dispose(); ((BaseUnityPlugin)this).Config.Save(); } private void SetupWatcher() { FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(Paths.ConfigPath, "JoksterCube.ServerPlayerList.cfg"); fileSystemWatcher.Changed += ReadConfigValues; fileSystemWatcher.Created += ReadConfigValues; fileSystemWatcher.Renamed += ReadConfigValues; fileSystemWatcher.IncludeSubdirectories = true; fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; _configWatcher = fileSystemWatcher; fileSystemWatcher.EnableRaisingEvents = true; } private void ReadConfigValues(object sender, FileSystemEventArgs e) { if (!File.Exists(ConfigFileFullPath)) { return; } try { ModLogger.LogDebug((object)"ReadConfigValues called"); ((BaseUnityPlugin)this).Config.Reload(); } catch { ModLogger.LogError((object)Constants.DebugMessages.ErrorLoadingConfig); ModLogger.LogError((object)"Please check your config entries for spelling and format!"); } } public Plugin() { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Expected O, but got Unknown string configPath = Paths.ConfigPath; char directorySeparatorChar = Path.DirectorySeparatorChar; ConfigFileFullPath = configPath + directorySeparatorChar + "JoksterCube.ServerPlayerList.cfg"; _harmony = new Harmony("JoksterCube.ServerPlayerList"); ((BaseUnityPlugin)this)..ctor(); } } } namespace JoksterCube.ServerPlayerList.Commonn { internal static class ZRoutedRpcExtensions { internal static bool RegisterOnce(this ZRoutedRpc rpc, string name, Action<long> f) { if (rpc == null || string.IsNullOrEmpty(name) || f == null) { return false; } int stableHashCode = StringExtensionMethods.GetStableHashCode(name); if (rpc.m_functions.ContainsKey(stableHashCode)) { return false; } rpc.Register(name, f); return true; } internal static bool RegisterOnce<T1>(this ZRoutedRpc rpc, string name, Action<long, T1> f) { if (rpc == null || string.IsNullOrEmpty(name) || f == null) { return false; } int stableHashCode = StringExtensionMethods.GetStableHashCode(name); if (rpc.m_functions.ContainsKey(stableHashCode)) { return false; } rpc.Register<T1>(name, f); return true; } internal static bool RegisterOnce<T1, T2>(this ZRoutedRpc rpc, string name, Action<long, T1, T2> f) { if (rpc == null || string.IsNullOrEmpty(name) || f == null) { return false; } int stableHashCode = StringExtensionMethods.GetStableHashCode(name); if (rpc.m_functions.ContainsKey(stableHashCode)) { return false; } rpc.Register<T1, T2>(name, f); return true; } internal static bool RegisterOnce<T1, T2, T3>(this ZRoutedRpc rpc, string name, Action<long, T1, T2, T3> f) { if (rpc == null || string.IsNullOrEmpty(name) || f == null) { return false; } int stableHashCode = StringExtensionMethods.GetStableHashCode(name); if (rpc.m_functions.ContainsKey(stableHashCode)) { return false; } rpc.Register<T1, T2, T3>(name, f); return true; } } } namespace JoksterCube.ServerPlayerList.Settings { internal enum DirectionReference { Camera, Character } internal static class Constants { internal static class Plugin { internal const string ModName = "ServerPlayerList"; internal const string ModVersion = "1.3.2"; internal const string Author = "JoksterCube"; internal const string ModGUID = "JoksterCube.ServerPlayerList"; internal const string Description = "Shows how many players are online, with their names, distances and directions."; internal const string Copyright = "Copyright © 2025"; internal const string Guid = "39da2684-0d87-45f0-9265-a09885c0b1ba"; internal const string ConfigFileName = "JoksterCube.ServerPlayerList.cfg"; } internal static class DisplayMessages { } internal static class DebugMessages { internal const string ReadConfigCalled = "ReadConfigValues called"; internal static readonly string ErrorLoadingConfig = "There was an issue loading your JoksterCube.ServerPlayerList.cfg"; internal const string RequestCheckConfig = "Please check your config entries for spelling and format!"; } internal static class Groups { internal static class General { internal const string Group = "1 - General"; internal static readonly ConfigInfo<Toggle> Lock = new ConfigInfo<Toggle>("1 - General", "Lock Configuration", "If on, the configuration is locked and can be changed by server admins only.", Toggle.On); internal static readonly ConfigInfo<float> RefreshDelay = new ConfigInfo<float>("1 - General", "Refresh Delay", new ConfigDescription("Time in seconds between refreshes.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 10f), Array.Empty<object>()), 0.25f); } internal static class PlayerList { internal const string Group = "2 - Player List"; internal static readonly ConfigInfo<Toggle> ShowPlayers = new ConfigInfo<Toggle>("2 - Player List", "Show Players", "Expanded view: show player rows below the online count. Off shows only the count. Toggled with the Show List keyboard shortcut.", Toggle.On, synchronized: false); internal static readonly ConfigInfo<Toggle> HideLocalPlayer = new ConfigInfo<Toggle>("2 - Player List", "Hide Local Player", "Hide your own non-favorite row from the expanded list. Does not affect the online player count.", Toggle.On, synchronized: false); internal static readonly ConfigInfo<Toggle> HideNaPlayers = new ConfigInfo<Toggle>("2 - Player List", "Hide Players with N/A Distance", "Hide non-favorite players who are not sharing their position from the expanded list. Does not affect the online player count.", Toggle.Off, synchronized: false); internal static readonly ConfigInfo<string> IgnoredUsers = new ConfigInfo<string>("2 - Player List", "Ignored users", "Comma-separated player names to hide. Synced from the server when ServerPlayerList is installed there; otherwise uses your local setting. Each occurrence hides one exact, case-sensitive match, preferring N/A distance entries. Repeat a name to hide multiple players. Spaces around entries and empty entries are ignored. Applied after RCON filtering.", string.Empty); internal static readonly ConfigInfo<Toggle> UseKilometers = new ConfigInfo<Toggle>("2 - Player List", "Use Kilometers", "Show distances of 1000 m or more in km instead of m.", Toggle.On, synchronized: false); internal static readonly ConfigInfo<float> MaxPlayerDistance = new ConfigInfo<float>("2 - Player List", "Maximum Player Distance", new ConfigDescription("Hide non-favorite players farther than this distance in meters. Players with N/A distance are also hidden while this is set. Set to 0 to disable.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 20000f), Array.Empty<object>()), 0f, synchronized: false); internal static readonly ConfigInfo<int> MaxVisiblePlayers = new ConfigInfo<int>("2 - Player List", "Maximum Visible Players", new ConfigDescription("Maximum number of player rows to show. Favorites fill the limit first, and all favorites remain visible if they exceed it. Set to 0 for no limit.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 20), Array.Empty<object>()), 0, synchronized: false); internal static readonly ConfigInfo<string> FavoritePlayers = new ConfigInfo<string>("2 - Player List", "Favorite Players", "Comma-separated player names to always show while online, above other players. Favorites bypass local display filters and remain visible when their count exceeds the row limit; explicit ignored-user and RCON filters still apply. Matching is exact and case-sensitive.", string.Empty, synchronized: false); internal static readonly ConfigInfo<Toggle> ShowPlayerDirection = new ConfigInfo<Toggle>("2 - Player List", "Show Player Direction", "Show a relative direction arrow before the distance for players sharing their position.", Toggle.On, synchronized: false); internal static readonly ConfigInfo<DirectionReference> DirectionReference = new ConfigInfo<DirectionReference>("2 - Player List", "Direction Reference", "Choose whether direction arrows are relative to the camera or character facing direction.", JoksterCube.ServerPlayerList.Settings.DirectionReference.Camera, synchronized: false); internal static readonly ConfigInfo<string> LocalPlayerTag = new ConfigInfo<string>("2 - Player List", "Local Player Tag", "Text shown instead of distance for your player. Use a symbol supported by the game font; leave empty to hide it.", "ᛝ", synchronized: false); } internal static class Appearance { internal const string Group = "3 - Appearance"; internal static readonly ConfigInfo<Vector2> AnchorPosition = new ConfigInfo<Vector2>("3 - Appearance", "Anchor Position", "Offset of the panel from the upper-right corner of the screen. Drag the panel to change it.", new Vector2(-239.75f, -243.25f), synchronized: false); internal static readonly ConfigInfo<float> Width = new ConfigInfo<float>("3 - Appearance", "Width", "Width of the panel.", 199.5f, synchronized: false); internal static readonly ConfigInfo<Color> BackgroundColor = new ConfigInfo<Color>("3 - Appearance", "Background Color", "Color of the panel background.", new Color(0f, 0f, 0f, 0.3f), synchronized: false); internal static readonly ConfigInfo<Color> HeaderTextColor = new ConfigInfo<Color>("3 - Appearance", "Header Text Color", "Color of the header text.", Color.white, synchronized: false); internal static readonly ConfigInfo<Color> HeaderHighlightTextColor = new ConfigInfo<Color>("3 - Appearance", "Header Highlight Text Color", "Color of the online player count in the header.", new Color(1f, 0.84f, 0f, 1f), synchronized: false); internal static readonly ConfigInfo<int> HeaderFontSize = new ConfigInfo<int>("3 - Appearance", "Header Font Size", "Size of the header font.", 28, synchronized: false); internal static readonly ConfigInfo<int> ListFontSize = new ConfigInfo<int>("3 - Appearance", "List Font Size", "Size of the player row font.", 22, synchronized: false); internal static readonly ConfigInfo<Color> FavoritePlayerNameColor = new ConfigInfo<Color>("3 - Appearance", "Favorite Player Name Color", "Name color used to identify favorite players in the list.", new Color(1f, 0.84f, 0f, 1f), synchronized: false); internal static readonly ConfigInfo<string> HeaderText = new ConfigInfo<string>("3 - Appearance", "Header Text", "Text shown before the online player count.", "Currently online:", synchronized: false); } internal static class Inputs { internal const string Group = "4 - Inputs"; internal static readonly ConfigInfo<KeyboardShortcut> ShowListKeyboardShortcut = new ConfigInfo<KeyboardShortcut>("4 - Inputs", "Show List Keyboard shortcut", "Toggle between the compact view (count only) and the expanded view (player rows). Ignored while typing or in game menus.", new KeyboardShortcut((KeyCode)111, (KeyCode[])(object)new KeyCode[1] { (KeyCode)305 }), synchronized: false); } } internal static class GameObjectNames { internal const string ServerPlayerListMain = "JoksterCube.ServerPlayerList.Main"; internal const string ServerPlayerListBackground = "JoksterCube.ServerPlayerList.Background"; internal const string ServerPlayerListHeader = "JoksterCube.ServerPlayerList.Header"; internal const string ServerPlayerListContainer = "JoksterCube.ServerPlayerList.Container"; internal const string ServerPlayerListPlayerInfo = "JoksterCube.ServerPlayerList.PlayerInfo"; internal const string ServerPlayerListPlayerName = "JoksterCube.ServerPlayerList.PlayerName"; internal const string ServerPlayerListDistance = "JoksterCube.ServerPlayerList.Distance"; } internal static readonly Dictionary<PlayerDistance, Color> DistanceColors = new Dictionary<PlayerDistance, Color> { { PlayerDistance.Close, new Color(0f, 1f, 0f) }, { PlayerDistance.Medium, new Color(1f, 1f, 0f) }, { PlayerDistance.Far, new Color(1f, 0.65f, 0f) }, { PlayerDistance.VeryFar, new Color(1f, 0.2f, 0.2f) }, { PlayerDistance.Distant, new Color(0.8f, 0.8f, 0.85f) } }; } internal static class PluginConfig { private static ConfigEntry<Toggle> _serverConfigLocked; internal static ConfigEntry<Toggle> ShowPlayers; internal static ConfigEntry<Toggle> HideLocalPlayer; internal static ConfigEntry<Toggle> HideNaPlayers; internal static ConfigEntry<string> IgnoredUsers; internal static ConfigEntry<float> RefreshDelay; internal static ConfigEntry<Vector2> AnchorPosition; internal static ConfigEntry<float> Width; internal static ConfigEntry<Color> BackgroundColor; internal static ConfigEntry<Color> HeaderTextColor; internal static ConfigEntry<Color> HeaderHighlightTextColor; internal static ConfigEntry<int> HeaderFontSize; internal static ConfigEntry<int> ListFontSize; internal static ConfigEntry<Color> FavoritePlayerNameColor; internal static ConfigEntry<Toggle> UseKilometers; internal static ConfigEntry<float> MaxPlayerDistance; internal static ConfigEntry<int> MaxVisiblePlayers; internal static ConfigEntry<string> FavoritePlayers; internal static ConfigEntry<Toggle> ShowPlayerDirection; internal static ConfigEntry<DirectionReference> DirectionReference; internal static ConfigEntry<string> LocalPlayerTag; internal static ConfigEntry<string> HeaderText; internal static ConfigEntry<KeyboardShortcut> ShowListKeyboardShortcut; internal static void Build(ConfigFile config, ConfigSync configSync) { ConfigOptions.Initialize(config, configSync); _serverConfigLocked = ConfigOptions.Config(Constants.Groups.General.Lock); configSync.AddLockingConfigEntry<Toggle>(_serverConfigLocked); ShowPlayers = ConfigOptions.Config(Constants.Groups.PlayerList.ShowPlayers); HideLocalPlayer = ConfigOptions.Config(Constants.Groups.PlayerList.HideLocalPlayer); HideNaPlayers = ConfigOptions.Config(Constants.Groups.PlayerList.HideNaPlayers); IgnoredUsers = ConfigOptions.Config(Constants.Groups.PlayerList.IgnoredUsers); RefreshDelay = ConfigOptions.Config(Constants.Groups.General.RefreshDelay); AnchorPosition = ConfigOptions.Config(Constants.Groups.Appearance.AnchorPosition); Width = ConfigOptions.Config(Constants.Groups.Appearance.Width); BackgroundColor = ConfigOptions.Config(Constants.Groups.Appearance.BackgroundColor); HeaderTextColor = ConfigOptions.Config(Constants.Groups.Appearance.HeaderTextColor); HeaderHighlightTextColor = ConfigOptions.Config(Constants.Groups.Appearance.HeaderHighlightTextColor); HeaderFontSize = ConfigOptions.Config(Constants.Groups.Appearance.HeaderFontSize); ListFontSize = ConfigOptions.Config(Constants.Groups.Appearance.ListFontSize); FavoritePlayerNameColor = ConfigOptions.Config(Constants.Groups.Appearance.FavoritePlayerNameColor); UseKilometers = ConfigOptions.Config(Constants.Groups.PlayerList.UseKilometers); MaxPlayerDistance = ConfigOptions.Config(Constants.Groups.PlayerList.MaxPlayerDistance); MaxVisiblePlayers = ConfigOptions.Config(Constants.Groups.PlayerList.MaxVisiblePlayers); FavoritePlayers = ConfigOptions.Config(Constants.Groups.PlayerList.FavoritePlayers); ShowPlayerDirection = ConfigOptions.Config(Constants.Groups.PlayerList.ShowPlayerDirection); DirectionReference = ConfigOptions.Config(Constants.Groups.PlayerList.DirectionReference); LocalPlayerTag = ConfigOptions.Config(Constants.Groups.PlayerList.LocalPlayerTag); HeaderText = ConfigOptions.Config(Constants.Groups.Appearance.HeaderText); ShowListKeyboardShortcut = ConfigOptions.Config(Constants.Groups.Inputs.ShowListKeyboardShortcut); } } } namespace JoksterCube.ServerPlayerList.Patches { [HarmonyPatch(typeof(ZNetScene), "Awake")] internal class ZNetSceneAwakePatch { private static void Postfix(ZNetScene __instance) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 if ((int)SystemInfo.graphicsDeviceType != 4) { ((MonoBehaviour)__instance).StartCoroutine(EnsureAfterHud()); } } private static IEnumerator EnsureAfterHud() { while ((Object)(object)Hud.instance == (Object)null || (Object)(object)Hud.instance.m_rootObject == (Object)null || (Object)(object)EnemyHud.instance == (Object)null || (Object)(object)EnemyHud.instance.m_baseHudPlayer == (Object)null) { yield return null; } yield return null; ComponentBootstrap.Ensure(); } } } namespace JoksterCube.ServerPlayerList.MonoBehaviours { internal class PlayerInfoElement : MonoBehaviour { private ServerPlayerInfo? lastInfo; private Toggle lastUseKilometers; private Toggle lastShowPlayerDirection; private string? lastLocalPlayerTag; private Color _defaultNameColor; private bool _hasDefaultNameColor; private Color _lastFavoriteNameColor; internal ServerPlayerInfo? PlayerInfo { get; set; } internal TMP_Text Name { get; set; } internal TMP_Text Distance { get; set; } internal event Action? FavoriteChanged; internal void SetPlayerInfo(ServerPlayerInfo playerInfo) { PlayerInfo = playerInfo; UpdateDisplay(); } internal void ToggleFavorite() { if (PlayerInfo != null) { ServerPlayerTracker.ToggleFavorite(PlayerInfo.Name); this.FavoriteChanged?.Invoke(); } } private void Update() { UpdateDisplay(); } private void UpdateDisplay() { //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_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0048: 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_00b0: 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_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) ServerPlayerInfo playerInfo = PlayerInfo; Toggle value = PluginConfig.UseKilometers.Value; Toggle value2 = PluginConfig.ShowPlayerDirection.Value; string value3 = PluginConfig.LocalPlayerTag.Value; Color value4 = PluginConfig.FavoritePlayerNameColor.Value; if (!_hasDefaultNameColor) { _defaultNameColor = ((Graphic)Name).color; _hasDefaultNameColor = true; } if (playerInfo != null && (playerInfo != lastInfo || value != lastUseKilometers || value2 != lastShowPlayerDirection || !(value3 == lastLocalPlayerTag) || !(value4 == _lastFavoriteNameColor))) { Name.text = playerInfo.Name; ((Graphic)Name).color = (playerInfo.IsFavorite ? value4 : _defaultNameColor); ((Graphic)Distance).color = DistanceColor(playerInfo); Distance.text = (playerInfo.IsMe ? value3 : ((value2.IsOn() ? playerInfo.Direction : string.Empty) + " " + FormatDistance(playerInfo, value.IsOn())).Trim()); lastInfo = playerInfo; lastUseKilometers = value; lastShowPlayerDirection = value2; lastLocalPlayerTag = value3; _lastFavoriteNameColor = value4; } } private static Color DistanceColor(ServerPlayerInfo playerInfo) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) return Constants.DistanceColors[playerInfo.DistancIndicator]; } private static string FormatDistance(ServerPlayerInfo playerInfo, bool useKilometers) { if (!playerInfo.IsPublic) { return "N/A"; } if (useKilometers && playerInfo.Distance >= 1000f) { return $"{playerInfo.Distance / 1000f:F2} km"; } float distance = playerInfo.Distance; if (!(distance >= 100f)) { if (distance >= 10f) { return $"{playerInfo.Distance:F1} m"; } return $"{playerInfo.Distance:F2} m"; } return $"{playerInfo.Distance:F0} m"; } } internal class FavoritePlayerName : MonoBehaviour, IPointerClickHandler, IEventSystemHandler, IPointerEnterHandler, IPointerExitHandler { private PlayerInfoElement _playerInfoElement; private TMP_Text _text; private FontStyles _defaultFontStyle; internal void Initialize(PlayerInfoElement playerInfoElement) { //IL_001a: 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) _playerInfoElement = playerInfoElement; _text = ((Component)this).GetComponent<TMP_Text>(); _defaultFontStyle = _text.fontStyle; } public void OnPointerClick(PointerEventData eventData) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 if ((int)eventData.button == 1) { _playerInfoElement.ToggleFavorite(); } } public void OnPointerEnter(PointerEventData eventData) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) _text.fontStyle = (FontStyles)(_defaultFontStyle | 4); } public void OnPointerExit(PointerEventData eventData) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) _text.fontStyle = _defaultFontStyle; } } internal class ServerPlayerListInterfaceComponent : DragNDrop { private const int Pad = 5; private static readonly Vector2 LegacyDefaultAnchorPosition = new Vector2(720.25f, 296.75f); private static readonly Vector2 DefaultAnchorPosition = new Vector2(-239.75f, -243.25f); private TMP_FontAsset _font; private Color _color; private bool _applyingFromConfig; private RectTransform _mainRect; private Image _background; private TMP_Text _headerText; private Transform _container; private readonly List<PlayerInfoElement> _containerElements = new List<PlayerInfoElement>(); private float lastRefresh; private bool IsShowing => ((Component)_container).gameObject.activeSelf; protected override void Awake() { SetHudCanvasAsParent(); base.Awake(); GetStyles(); InitGameObjects(); ApplyFromConfig(); RegisterEvents(); } private void Update() { if (!ShouldBeVisible()) { ToggleVisibility(visible: false); return; } bool flag = PluginConfig.ShowPlayers.Value.IsOn() && !RpcHandlers.ShouldWaitForInitialConfigSync; bool flag2 = false; if (!((Component)_background).gameObject.activeSelf || (flag && !IsShowing) || Time.time - lastRefresh >= PluginConfig.RefreshDelay.Value) { lastRefresh = Time.time; Refresh(flag); flag2 = true; } flag2 |= SetListVisibility(flag); if (flag2 | ToggleVisibility(visible: true)) { RebuildLayout(); } } private void GetStyles() { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) TMP_Text componentInChildren = EnemyHud.instance.m_baseHudPlayer.GetComponentInChildren<TMP_Text>(true); _font = componentInChildren.font; _color = ((Graphic)componentInChildren).color; } private void RebuildLayout() { LayoutRebuilder.ForceRebuildLayoutImmediate(_mainRect); } private bool SetListVisibility(bool visible) { if (IsShowing == visible) { return false; } ((Component)_container).gameObject.SetActive(visible); return true; } private void Refresh(bool showPlayers) { if (showPlayers) { ServerPlayerTracker.UpdatePlayerInfo(); UpdateContainer(); } else { ServerPlayerTracker.UpdatePlayerCount(); } SetCurrentlyOnlineText(); } private void SetCurrentlyOnlineText() { //IL_001a: Unknown result type (might be due to invalid IL or missing references) _headerText.text = $"{PluginConfig.HeaderText.Value} <color=#{ColorUtility.ToHtmlStringRGB(PluginConfig.HeaderHighlightTextColor.Value)}>{ServerPlayerTracker.CurrentlyOnline}</color>"; } private void UpdateContainer() { List<ServerPlayerInfo> currenlyOnlineList = ServerPlayerTracker.GetCurrenlyOnlineList(); int num = currenlyOnlineList.Count - _containerElements.Count; if (num > 0) { SpawnElements(num); } else if (num < 0) { DeleteElements(-num); } UpdateElements(currenlyOnlineList); } private void UpdateElements(List<ServerPlayerInfo> infos) { for (int i = 0; i < _containerElements.Count; i++) { _containerElements[i].SetPlayerInfo(infos[i]); } } private void OnDestroy() { DeregisterEvents(); } private void RegisterEvents() { base.OnDragEnded += Save; PluginConfig.AnchorPosition.SettingChanged += OnConfigChanged; PluginConfig.Width.SettingChanged += OnConfigChanged; PluginConfig.BackgroundColor.SettingChanged += OnConfigChanged; PluginConfig.HeaderTextColor.SettingChanged += OnConfigChanged; PluginConfig.HeaderFontSize.SettingChanged += OnConfigChanged; PluginConfig.ListFontSize.SettingChanged += OnConfigChanged; PluginConfig.ShowPlayers.SettingChanged += OnShowPlayersChanged; } private void DeregisterEvents() { base.OnDragEnded -= Save; PluginConfig.AnchorPosition.SettingChanged -= OnConfigChanged; PluginConfig.Width.SettingChanged -= OnConfigChanged; PluginConfig.BackgroundColor.SettingChanged -= OnConfigChanged; PluginConfig.HeaderTextColor.SettingChanged -= OnConfigChanged; PluginConfig.HeaderFontSize.SettingChanged -= OnConfigChanged; PluginConfig.ListFontSize.SettingChanged -= OnConfigChanged; PluginConfig.ShowPlayers.SettingChanged -= OnShowPlayersChanged; } private void OnShowPlayersChanged(object sender, EventArgs e) { if (PluginConfig.ShowPlayers.Value.IsOn()) { if (!IsShowing && ShouldBeVisible() && !RpcHandlers.ShouldWaitForInitialConfigSync) { lastRefresh = Time.time; Refresh(showPlayers: true); SetListVisibility(visible: true); ToggleVisibility(visible: true); RebuildLayout(); } } else { SetListVisibility(visible: false); } } private void OnConfigChanged(object sender, EventArgs e) { if (!_applyingFromConfig) { ApplyFromConfig(); } } private void ApplyFromConfig() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0013: 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) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) _applyingFromConfig = true; try { Vector2 val = PluginConfig.AnchorPosition.Value; if (val == LegacyDefaultAnchorPosition) { val = DefaultAnchorPosition; PluginConfig.AnchorPosition.Value = val; } SetAnchoredPosition(val); SetMainFromConfig(); SetBackgroundFromConfig(); SetHeaderFromConfig(); SetListFromConfig(); } finally { _applyingFromConfig = false; } } private void SetMainFromConfig() { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) _mainRect.sizeDelta = new Vector2(PluginConfig.Width.Value, _mainRect.sizeDelta.y); } private void SetBackgroundFromConfig() { //IL_000b: Unknown result type (might be due to invalid IL or missing references) ((Graphic)_background).color = PluginConfig.BackgroundColor.Value; } private void SetHeaderFromConfig() { //IL_000b: Unknown result type (might be due to invalid IL or missing references) ((Graphic)_headerText).color = PluginConfig.HeaderTextColor.Value; _headerText.fontSize = PluginConfig.HeaderFontSize.Value; } private void SetListFromConfig() { foreach (PlayerInfoElement containerElement in _containerElements) { containerElement.Name.fontSize = PluginConfig.ListFontSize.Value; containerElement.Distance.fontSize = PluginConfig.ListFontSize.Value; ((Component)containerElement).GetComponent<LayoutElement>().preferredHeight = GetPreferredRowHeight(containerElement); } } private static float GetPreferredRowHeight(PlayerInfoElement element) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) float y = element.Name.GetPreferredValues("M").y; float y2 = element.Distance.GetPreferredValues("↑ 999.99 km").y; return Mathf.Ceil(Mathf.Max(y, y2)); } private void Save(Vector2 anchoredPosition) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) if (!_applyingFromConfig && !(PluginConfig.AnchorPosition.Value == anchoredPosition)) { PluginConfig.AnchorPosition.Value = anchoredPosition; } } internal static bool ShouldBeVisible() { if (!Object.op_Implicit((Object)(object)Hud.instance)) { return false; } if (!Object.op_Implicit((Object)(object)Hud.instance.m_rootObject) || !Hud.instance.m_rootObject.activeInHierarchy) { return false; } if (Minimap.IsOpen()) { return false; } Player localPlayer = Player.m_localPlayer; if (!Object.op_Implicit((Object)(object)localPlayer)) { return false; } if (((Character)localPlayer).IsTeleporting()) { return false; } if (localPlayer.IsSleeping()) { return false; } if (((Character)localPlayer).IsDead()) { return false; } if (((Character)localPlayer).InCutscene()) { return false; } return true; } private bool ToggleVisibility(bool visible) { if (((Component)_background).gameObject.activeSelf == visible) { return false; } ((Component)_background).gameObject.SetActive(visible); return true; } private void SetHudCanvasAsParent() { ((Component)this).transform.SetParent(((Component)Hud.instance.m_rootObject.GetComponentInParent<Canvas>()).transform, false); } private void InitGameObjects() { InitMain(); InitBackground(); InitHeader(); InitListContainer(); } private void InitMain() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) _mainRect = (RectTransform)((Component)this).transform; _mainRect.anchorMin = Vector2.one; _mainRect.anchorMax = Vector2.one; _mainRect.pivot = Vector2.up; AddLayout<VerticalLayoutGroup>(((Component)this).gameObject, 0f, 0); FitHeight(((Component)this).gameObject); SetMainFromConfig(); } private void InitBackground() { GameObject val = CreateChild("JoksterCube.ServerPlayerList.Background", ((Component)this).transform); AddLayout<VerticalLayoutGroup>(val, 5f, 5); FitHeight(val); _background = val.AddComponent<Image>(); SetBackgroundFromConfig(); } private void InitHeader() { _headerText = CreateText("JoksterCube.ServerPlayerList.Header", ((Component)_background).transform, (TextAlignmentOptions)258, PluginConfig.HeaderFontSize.Value); SetHeaderFromConfig(); } private void InitListContainer() { GameObject val = CreateChild("JoksterCube.ServerPlayerList.Container", ((Component)_background).transform); AddLayout<VerticalLayoutGroup>(val, 0f, 0); FitHeight(val); _container = val.transform; } private void SpawnElements(int number) { for (int i = 0; i < number; i++) { _containerElements.Add(SpawnElement()); } } private PlayerInfoElement SpawnElement() { //IL_0052: Unknown result type (might be due to invalid IL or missing references) GameObject obj = CreateChild("JoksterCube.ServerPlayerList.PlayerInfo", _container); AddLayout<HorizontalLayoutGroup>(obj, 0f, 0); FitHeight(obj); LayoutElement val = obj.AddComponent<LayoutElement>(); PlayerInfoElement playerInfoElement = obj.AddComponent<PlayerInfoElement>(); playerInfoElement.Name = CreateListText("JoksterCube.ServerPlayerList.PlayerName", ((Component)playerInfoElement).transform, (TextAlignmentOptions)513); ((Graphic)playerInfoElement.Name).color = _color; playerInfoElement.Name.richText = false; ((Component)playerInfoElement.Name).gameObject.AddComponent<FavoritePlayerName>().Initialize(playerInfoElement); playerInfoElement.Distance = CreateListText("JoksterCube.ServerPlayerList.Distance", ((Component)playerInfoElement).transform, (TextAlignmentOptions)516); playerInfoElement.FavoriteChanged += OnFavoriteChanged; val.preferredHeight = GetPreferredRowHeight(playerInfoElement); return playerInfoElement; } private void OnFavoriteChanged() { lastRefresh = Time.time; Refresh(showPlayers: true); RebuildLayout(); } private TMP_Text CreateListText(string name, Transform parent, TextAlignmentOptions alignment) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) TMP_Text obj = CreateText(name, parent, alignment, PluginConfig.ListFontSize.Value); obj.overflowMode = (TextOverflowModes)1; return obj; } private TMP_Text CreateText(string name, Transform parent, TextAlignmentOptions alignment, float fontSize) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown //IL_0055: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject(name, new Type[1] { typeof(RectTransform) }); val.SetActive(false); val.transform.SetParent(parent, false); FitHeight(val); TextMeshProUGUI obj = val.AddComponent<TextMeshProUGUI>(); ((TMP_Text)obj).font = _font; ((TMP_Text)obj).fontStyle = (FontStyles)1; ((TMP_Text)obj).textWrappingMode = (TextWrappingModes)0; ((TMP_Text)obj).alignment = alignment; ((TMP_Text)obj).fontSize = fontSize; val.SetActive(true); return (TMP_Text)(object)obj; } private static GameObject CreateChild(string name, Transform parent) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected O, but got Unknown GameObject val = new GameObject(name, new Type[1] { typeof(RectTransform) }); val.transform.SetParent(parent, false); return val; } private static void AddLayout<T>(GameObject target, float spacing = 0f, int padding = 0) where T : HorizontalOrVerticalLayoutGroup { //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Expected O, but got Unknown T val = target.AddComponent<T>(); ((HorizontalOrVerticalLayoutGroup)val).childControlWidth = true; ((HorizontalOrVerticalLayoutGroup)val).childControlHeight = false; ((HorizontalOrVerticalLayoutGroup)val).childForceExpandWidth = true; ((HorizontalOrVerticalLayoutGroup)val).childForceExpandHeight = false; ((HorizontalOrVerticalLayoutGroup)val).spacing = spacing; ((LayoutGroup)(object)val).padding = new RectOffset(padding, padding, padding, padding); } private static void FitHeight(GameObject target) { ContentSizeFitter obj = target.AddComponent<ContentSizeFitter>(); obj.horizontalFit = (FitMode)0; obj.verticalFit = (FitMode)2; } private void DeleteElements(int number) { for (int i = 0; i < number; i++) { if (_containerElements.Count <= 0) { break; } DeleteElement(_containerElements.Count - 1); } } private void DeleteElement(int index) { Object.Destroy((Object)(object)((Component)_containerElements[index]).gameObject); _containerElements.RemoveAt(index); } } } namespace JoksterCube.ServerPlayerList.Domain { internal static class ComponentBootstrap { private static ServerPlayerListInterfaceComponent? _interface; internal static void Ensure() { //IL_0032: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)_interface)) { _interface = new GameObject("JoksterCube.ServerPlayerList.Main", new Type[2] { typeof(RectTransform), typeof(ServerPlayerListInterfaceComponent) }).GetComponent<ServerPlayerListInterfaceComponent>(); } } internal static void Clear() { if (Object.op_Implicit((Object)(object)_interface)) { Object.Destroy((Object)(object)((Component)_interface).gameObject); _interface = null; } } } internal static class InputManager { internal static void Update(Plugin plugin) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) bool flag = PluginConfig.ShowListKeyboardShortcut.Value.IsKeyDown(); if (flag && ServerPlayerListInterfaceComponent.ShouldBeVisible() && !IsTyping()) { if (flag) { PluginConfig.ShowPlayers.Value = PluginConfig.ShowPlayers.Value.Not(); } ((BaseUnityPlugin)plugin).Config.Save(); } } private static bool IsTyping() { if ((!Object.op_Implicit((Object)(object)Chat.instance) || !Chat.instance.HasFocus()) && !Console.IsVisible() && !TextInput.IsVisible() && !Menu.IsVisible() && !InventoryGui.IsVisible() && !StoreGui.IsVisible()) { return IsInputFieldFocused(); } return true; } private static bool IsInputFieldFocused() { EventSystem current = EventSystem.current; if (!Object.op_Implicit((Object)(object)current)) { return false; } GameObject currentSelectedGameObject = current.currentSelectedGameObject; if (!Object.op_Implicit((Object)(object)currentSelectedGameObject)) { return false; } TMP_InputField component = currentSelectedGameObject.GetComponent<TMP_InputField>(); if (Object.op_Implicit((Object)(object)component) && component.isFocused) { return true; } InputField component2 = currentSelectedGameObject.GetComponent<InputField>(); if (Object.op_Implicit((Object)(object)component2)) { return component2.isFocused; } return false; } } internal enum PlayerDistance { Close, Medium, Far, VeryFar, Distant } internal static class ServerPlayerTracker { private static List<PlayerInfo> _players = new List<PlayerInfo>(); private static int _currentlyOnline; internal static int CurrentlyOnline => _currentlyOnline; internal static void ToggleFavorite(string playerName) { List<string> list = (from name in PluginConfig.FavoritePlayers.Value.Split(new char[1] { ',' }) select name.Trim() into name where name.Length > 0 select name).ToList(); if (list.RemoveAll((string name) => string.Equals(name, playerName, StringComparison.Ordinal)) <= 0) { list.Add(playerName); } PluginConfig.FavoritePlayers.Value = string.Join(", ", list); } internal static List<ServerPlayerInfo> GetCurrenlyOnlineList() { HashSet<string> favoritePlayers = new HashSet<string>(from name in PluginConfig.FavoritePlayers.Value.Split(new char[1] { ',' }) select name.Trim() into name where name.Length > 0 select name); bool hideLocalPlayer = PluginConfig.HideLocalPlayer.Value.IsOn(); bool hideNaPlayers = PluginConfig.HideNaPlayers.Value.IsOn(); float maxDistance = PluginConfig.MaxPlayerDistance.Value; int value = PluginConfig.MaxVisiblePlayers.Value; List<ServerPlayerInfo> list = (from x in _players select new ServerPlayerInfo(x, favoritePlayers.Contains(x.m_name.Trim())) into info where info.IsFavorite || ((!hideLocalPlayer || !info.IsMe) && (!hideNaPlayers || info.IsMe || info.IsPublic) && (maxDistance <= 0f || info.Distance <= maxDistance)) orderby info.IsMe descending, info.IsFavorite descending, info.Distance, info.Name select info).ToList(); if (value <= 0) { return list; } int count = Math.Max(0, value - list.Count((ServerPlayerInfo info) => info.IsFavorite)); HashSet<ServerPlayerInfo> regularRows = new HashSet<ServerPlayerInfo>(list.Where((ServerPlayerInfo info) => !info.IsFavorite).Take(count)); return list.Where((ServerPlayerInfo info) => info.IsFavorite || regularRows.Contains(info)).ToList(); } internal static void UpdatePlayerInfo() { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { return; } string value = Plugin.RconPlayerName.Value; _players = ZNet.instance.GetPlayerList().ToList(); if (!string.IsNullOrEmpty(value)) { RemovePlayer(value, requirePrivatePosition: true); } string[] array = PluginConfig.IgnoredUsers.Value.Split(new char[1] { ',' }); for (int i = 0; i < array.Length; i++) { string text = array[i].Trim(); if (text.Length > 0) { RemovePlayer(text, requirePrivatePosition: false); } } _currentlyOnline = _players.Count; } internal static void UpdatePlayerCount() { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { return; } _players.Clear(); List<PlayerInfo> playerList = ZNet.instance.GetPlayerList(); bool[] array = new bool[playerList.Count]; int num = 0; string value = Plugin.RconPlayerName.Value; if (!string.IsNullOrEmpty(value)) { int num2 = FindPlayerIndex(playerList, array, value, requirePrivatePosition: true, skipLocalPlayer: true); if (num2 >= 0) { array[num2] = true; num++; } } string[] array2 = PluginConfig.IgnoredUsers.Value.Split(new char[1] { ',' }); for (int i = 0; i < array2.Length; i++) { string text = array2[i].Trim(); if (text.Length != 0) { int num3 = FindPlayerIndex(playerList, array, text, requirePrivatePosition: true, skipLocalPlayer: true); if (num3 < 0) { num3 = FindPlayerIndex(playerList, array, text, requirePrivatePosition: false, skipLocalPlayer: false); } if (num3 >= 0) { array[num3] = true; num++; } } } _currentlyOnline = playerList.Count - num; } private static int FindPlayerIndex(List<PlayerInfo> players, bool[] removedPlayers, string name, bool requirePrivatePosition, bool skipLocalPlayer) { //IL_001a: 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: 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_0026: 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_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0044: 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) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) Player localPlayer = Player.m_localPlayer; ZDOID val = (ZDOID)(Object.op_Implicit((Object)(object)localPlayer) ? ((Character)localPlayer).GetZDOID() : default(ZDOID)); for (int i = 0; i < players.Count; i++) { PlayerInfo val2 = players[i]; if (!removedPlayers[i] && !(val2.m_name != name) && (!requirePrivatePosition || !val2.m_publicPosition) && (!skipLocalPlayer || !Object.op_Implicit((Object)(object)localPlayer) || !(val2.m_characterID == val))) { return i; } } return -1; } private static void RemovePlayer(string name, bool requirePrivatePosition) { //IL_0037: 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_002e: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) Player localPlayer = Player.m_localPlayer; ZDOID localPlayerId = (ZDOID)(Object.op_Implicit((Object)(object)localPlayer) ? ((Character)localPlayer).GetZDOID() : default(ZDOID)); int num = _players.FindIndex((PlayerInfo player) => player.m_name == name && !player.m_publicPosition && (!Object.op_Implicit((Object)(object)localPlayer) || !(player.m_characterID == localPlayerId))); if (num < 0 && !requirePrivatePosition) { num = _players.FindIndex((PlayerInfo player) => player.m_name == name); } if (num >= 0) { _players.RemoveAt(num); } } } internal class ServerPlayerInfo { private static readonly string[] DirectionArrows = new string[8] { "↑", "↗", "→", "↘", "↓", "↙", "←", "↖" }; internal string Name { get; } internal float Distance { get; } internal string Direction { get; } public bool IsPublic { get; } internal bool IsMe { get; } internal bool IsFavorite { get; } internal PlayerDistance DistancIndicator { get { float distance = Distance; if (!(distance < 100f)) { if (!(distance < 400f)) { if (!(distance < 1200f)) { if (distance < 2400f) { return PlayerDistance.VeryFar; } return PlayerDistance.Distant; } return PlayerDistance.Far; } return PlayerDistance.Medium; } return PlayerDistance.Close; } } internal ServerPlayerInfo(string name, float distance, bool isPublic, bool isMe = false, string direction = "", bool isFavorite = false) { Name = name; Distance = distance; IsPublic = isPublic; IsMe = isMe; Direction = direction; IsFavorite = isFavorite; } internal ServerPlayerInfo(PlayerInfo info, bool isFavorite = false) : this(info.m_name.Trim(), GetDistance(info), IsPublicPosition(info), IsLocalPlayer(info), GetDirection(info), isFavorite) { }//IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) private static string GetDirection(PlayerInfo info) { //IL_000e: 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_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_006f: 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) Player localPlayer = Player.m_localPlayer; if (!Object.op_Implicit((Object)(object)localPlayer) || !info.m_publicPosition || IsLocalPlayer(info)) { return string.Empty; } Vector3 val = info.m_position - ((Component)localPlayer).transform.position; if (((Vector3)(ref val)).sqrMagnitude < 0.01f) { return DirectionArrows[0]; } float num = Mathf.Atan2(val.x, val.z) * 57.29578f; float y = ((Component)localPlayer).transform.eulerAngles.y; if (PluginConfig.DirectionReference.Value == DirectionReference.Camera && Object.op_Implicit((Object)(object)Camera.main)) { y = ((Component)Camera.main).transform.eulerAngles.y; } int num2 = (Mathf.RoundToInt(Mathf.DeltaAngle(y, num) / 45f) + DirectionArrows.Length) % DirectionArrows.Length; return DirectionArrows[num2]; } private static bool IsLocalPlayer(PlayerInfo info) { //IL_0011: 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) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) Player localPlayer = Player.m_localPlayer; if (!Object.op_Implicit((Object)(object)localPlayer)) { return false; } ZDOID zDOID = ((Character)localPlayer).GetZDOID(); return info.m_characterID == zDOID; } private static float GetDistance(PlayerInfo info) { //IL_0000: 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_0026: 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_002c: Unknown result type (might be due to invalid IL or missing references) if (IsLocalPlayer(info)) { return float.NegativeInfinity; } if (!info.m_publicPosition) { return float.PositiveInfinity; } return Vector3.Distance(((Component)Player.m_localPlayer).transform.position, info.m_position); } private static bool IsPublicPosition(PlayerInfo info) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) return info.m_publicPosition; } } } namespace JoksterCube.ServerPlayerList.Common { internal static class ConfigOptions { private class ConfigurationManagerAttributes { [UsedImplicitly] public int? Order; [UsedImplicitly] public bool? Browsable; [UsedImplicitly] public string Category; [UsedImplicitly] public Action<ConfigEntryBase> CustomDrawer; } private class AcceptableShortcuts : AcceptableValueBase { public AcceptableShortcuts() : base(typeof(KeyboardShortcut)) { } public override object Clamp(object value) { return value; } public override bool IsValid(object value) { return true; } public override string ToDescriptionString() { return "# Acceptable values: " + string.Join(", ", UnityInput.Current.SupportedKeyCodes); } } private static ConfigFile? ConfigFile; private static ConfigSync? ConfigSync; internal static void Initialize(ConfigFile config, ConfigSync configSync) { ConfigFile = config; ConfigSync = configSync; } internal static ConfigEntry<T> Config<T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Expected O, but got Unknown ConfigDescription val = new ConfigDescription(description.Description + (synchronizedSetting ? " [Synced with Server]" : " [Not Synced with Server]"), description.AcceptableValues, description.Tags); ConfigEntry<T> val2 = (ConfigFile ?? throw new InvalidOperationException("ConfigOptions is not initialized.")).Bind<T>(group, name, value, val); (ConfigSync ?? throw new InvalidOperationException("ConfigOptions is not initialized.")).AddConfigEntry<T>(val2).SynchronizedConfig = synchronizedSetting; return val2; } internal static ConfigEntry<T> Config<T>(string group, string name, T value, string description, bool synchronizedSetting = true) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown return Config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting); } internal static ConfigEntry<T> Config<T>(ConfigInfo<T> configInfo) { return Config(configInfo.Group, configInfo.Name, configInfo.DefaultValue, configInfo.Description, configInfo.Synchronized); } } internal class DragNDrop : MonoBehaviour, IPointerDownHandler, IEventSystemHandler, IPointerUpHandler, IDragHandler { private RectTransform _target; private RectTransform? _clampWithin; private bool _shouldReturn; private Canvas? _rootCanvas; private bool _isDragging; private Vector2 _dragOffset; private Vector2 _startAnchoredPosition; public event Action<Vector2>? OnPositionChanged; public event Action<Vector2>? OnDragEnded; protected virtual void Awake() { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown if (!Object.op_Implicit((Object)(object)_target)) { _target = (RectTransform)((Component)this).transform; } if (!Object.op_Implicit((Object)(object)_clampWithin)) { ref RectTransform? clampWithin = ref _clampWithin; Transform parent = ((Transform)_target).parent; clampWithin = (RectTransform?)(object)((parent is RectTransform) ? parent : null); } _rootCanvas = ((Component)_target).GetComponentInParent<Canvas>(); } public void OnPointerDown(PointerEventData eventData) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: 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_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) if (Object.op_Implicit((Object)(object)_rootCanvas) && (int)eventData.button == 0) { _isDragging = true; _startAnchoredPosition = _target.anchoredPosition; Vector2 val = ScreenToLocal(eventData.position); _dragOffset = _target.anchoredPosition - val; } } public void OnDrag(PointerEventData eventData) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //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_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_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) if (_isDragging && Object.op_Implicit((Object)(object)_rootCanvas)) { Vector2 desired = ScreenToLocal(eventData.position) + _dragOffset; Vector2 val = ClampAnchoredPosition(desired); _target.anchoredPosition = val; this.OnPositionChanged?.Invoke(val); } } public void OnPointerUp(PointerEventData eventData) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) if (_isDragging && (int)eventData.button == 0) { _isDragging = false; if (_shouldReturn) { _target.anchoredPosition = _startAnchoredPosition; this.OnPositionChanged?.Invoke(_target.anchoredPosition); } this.OnDragEnded?.Invoke(_target.anchoredPosition); } } internal void SetShouldReturn(bool value) { _shouldReturn = value; } internal void SetAnchoredPosition(Vector2 anchoredPos, bool clamp = true, bool notify = false) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0004: 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) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0026: 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) if (clamp) { anchoredPos = ClampAnchoredPosition(anchoredPos); } if (!(_target.anchoredPosition == anchoredPos)) { _target.anchoredPosition = anchoredPos; if (notify) { this.OnPositionChanged?.Invoke(anchoredPos); } } } private Vector2 ScreenToLocal(Vector2 screenPos) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_004e: 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) Camera val = ((Object.op_Implicit((Object)(object)_rootCanvas) && (int)_rootCanvas.renderMode != 0) ? _rootCanvas.worldCamera : null); Vector2 result = default(Vector2); RectTransformUtility.ScreenPointToLocalPointInRectangle((RectTransform)(Object.op_Implicit((Object)(object)_clampWithin) ? ((object)_clampWithin) : ((object)(RectTransform)((Transform)_target).parent)), screenPos, val, ref result); return result; } private Vector2 ClampAnchoredPosition(Vector2 desired) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)_clampWithin)) { return desired; } Rect rect = _clampWithin.rect; Rect rect2 = _target.rect; Vector2 val = default(Vector2); ((Vector2)(ref val))..ctor(Mathf.Lerp(((Rect)(ref rect)).xMin, ((Rect)(ref rect)).xMax, _target.anchorMin.x), Mathf.Lerp(((Rect)(ref rect)).yMin, ((Rect)(ref rect)).yMax, _target.anchorMin.y)); float num = ((Rect)(ref rect)).xMin - val.x - ((Rect)(ref rect2)).xMin; float num2 = ((Rect)(ref rect)).xMax - val.x - ((Rect)(ref rect2)).xMax; float num3 = ((Rect)(ref rect)).yMin - val.y - ((Rect)(ref rect2)).yMin; float num4 = ((Rect)(ref rect)).yMax - val.y - ((Rect)(ref rect2)).yMax; desired.x = Mathf.Clamp(desired.x, num, num2); desired.y = Mathf.Clamp(desired.y, num3, num4); return desired; } } internal static class KeyboardExtensions { internal static bool IsKeyDown(this KeyboardShortcut shortcut) { //IL_0002: 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) if ((int)((KeyboardShortcut)(ref shortcut)).MainKey != 0 && Input.GetKeyDown(((KeyboardShortcut)(ref shortcut)).MainKey)) { return ((KeyboardShortcut)(ref shortcut)).Modifiers.All((Func<KeyCode, bool>)Input.GetKey); } return false; } internal static bool IsKeyHeld(this KeyboardShortcut shortcut) { //IL_0002: 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) if ((int)((KeyboardShortcut)(ref shortcut)).MainKey != 0 && Input.GetKey(((KeyboardShortcut)(ref shortcut)).MainKey)) { return ((KeyboardShortcut)(ref shortcut)).Modifiers.All((Func<KeyCode, bool>)Input.GetKey); } return false; } } internal static class PlayerExtensions { internal static void Message(MessageType messageType, string message) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) ((Character)Player.m_localPlayer).Message(messageType, message, 0, (Sprite)null, false); } internal static void FormatedMessage(MessageType messageType, string message, params object[] args) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) Message(messageType, string.Format(message, args)); } internal static void FormatedCenterMessage(string message, params object[] args) { FormatedMessage((MessageType)2, message, args); } internal static void FormatedTopLeftMessage(string message, params object[] args) { FormatedMessage((MessageType)1, message, args); } } internal static class PluginUtils { internal static class Vector2Extensions { internal static readonly Vector2 Center = Vector2.one * 0.5f; } } public enum Toggle { On = 1, Off = 0 } internal static class ToggleExtensions { internal static Toggle Not(this Toggle toggle) { return toggle switch { Toggle.On => Toggle.Off, Toggle.Off => Toggle.On, _ => throw new NotImplementedException(), }; } internal static bool IsOn(this Toggle toggle) { return toggle == Toggle.On; } internal static bool IsOn(this ConfigEntry<Toggle> toggleConfig) { return toggleConfig.Value.IsOn(); } internal static Toggle ToToggle(this bool value) { if (!value) { return Toggle.Off; } return Toggle.On; } } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] internal static class RegisterAndCheckVersion { private static void Prefix(ZNetPeer peer, ref ZNet __instance) { //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Expected O, but got Unknown if (!__instance.IsServer()) { RpcHandlers.BeginServerVersionCheck(); } Plugin.ModLogger.LogDebug((object)"Registering version RPC handler"); peer.m_rpc.Register<ZPackage>("ServerPlayerList_VersionCheck", (Action<ZRpc, ZPackage>)RpcHandlers.RPC_ServerSyncModTemplate_Version); Plugin.ModLogger.LogInfo((object)"Invoking version check"); ZPackage val = new ZPackage(); val.Write("1.3.2"); peer.m_rpc.Invoke("ServerPlayerList_VersionCheck", new object[1] { val }); } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] internal static class BlockMismatchedClient { private static bool Prefix(ZRpc rpc, ref ZNet __instance) { if (__instance.IsServer()) { return !RpcHandlers.RejectedPeers.Contains(rpc); } return true; } } [HarmonyPatch(typeof(FejdStartup), "ShowConnectError")] internal class ShowConnectionError { private static void Postfix(FejdStartup __instance) { if (__instance.m_connectionFailedPanel.activeSelf) { __instance.m_connectionFailedError.fontSizeMax = 25f; __instance.m_connectionFailedError.fontSizeMin = 15f; TMP_Text connectionFailedError = __instance.m_connectionFailedError; connectionFailedError.text = connectionFailedError.text + "\n" + Plugin.ConnectionError; } } } [HarmonyPatch(typeof(ZNet), "Disconnect")] internal static class RemoveDisconnectedPeerFromRejected { private static void Prefix(ZNetPeer peer, ref ZNet __instance) { if (!__instance.IsServer()) { RpcHandlers.ResetServerVersionCheck(); } else { RpcHandlers.RejectedPeers.Remove(peer.m_rpc); } } } internal static class RpcHandlers { internal static readonly HashSet<ZRpc> RejectedPeers = new HashSet<ZRpc>(); private static bool _waitingForServerVersion; private static bool _serverVersionReceived; private static float _serverVersionCheckStartedAt; internal static bool ShouldWaitForInitialConfigSync { get { if (!Object.op_Implicit((Object)(object)ZNet.instance) || ZNet.instance.IsServer() || !_waitingForServerVersion) { return false; } if (_serverVersionReceived) { return !Plugin.InitialConfigSyncDone; } return Time.realtimeSinceStartup - _serverVersionCheckStartedAt < 1f; } } internal static void BeginServerVersionCheck() { _waitingForServerVersion = true; _serverVersionReceived = false; _serverVersionCheckStartedAt = Time.realtimeSinceStartup; Plugin.ConnectionError = string.Empty; } internal static void ResetServerVersionCheck() { _waitingForServerVersion = false; _serverVersionReceived = false; } private static string SanitizeRemoteText(string text) { string text2 = text.Replace("<", string.Empty).Replace(">", string.Empty); if (text2.Length <= 32) { return text2; } return text2.Substring(0, 32); } internal static void RPC_ServerSyncModTemplate_Version(ZRpc rpc, ZPackage pkg) { string text = pkg.ReadString(); ZNet instance = ZNet.instance; if (!Object.op_Implicit((Object)(object)instance)) { return; } bool flag = instance.IsServer(); if (!flag) { _serverVersionReceived = true; } Plugin.ModLogger.LogInfo((object)("Version check, local: 1.3.2, remote: " + text)); if (text != "1.3.2") { Plugin.ConnectionError = "ServerPlayerList Installed: 1.3.2\n Needed: " + SanitizeRemoteText(text); if (flag) { Plugin.ModLogger.LogWarning((object)("Peer (" + rpc.m_socket.GetHostName() + ") has incompatible version, disconnecting...")); RejectedPeers.Add(rpc); rpc.Invoke("Error", new object[1] { 3 }); } } else if (!flag) { Plugin.ModLogger.LogInfo((object)"Received same version from server!"); } } } internal class ConfigInfo<T> { internal string Group { get; } internal string Name { get; } internal ConfigDescription Description { get; } internal T DefaultValue { get; } internal bool Synchronized { get; } internal ConfigInfo(string group, string name, string description, T defaultValue, bool synchronized = true) : this(group, name, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), defaultValue, synchronized) { }//IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown internal ConfigInfo(string group, string name, ConfigDescription description, T defaultValue, bool synchronized = true) { Group = group; Name = name; Description = description; DefaultValue = defaultValue; Synchronized = synchronized; } } } namespace ServerSync { [PublicAPI] internal abstract class OwnConfigEntryBase { public object? LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } [PublicAPI] internal class SyncedConfigEntry<T>(ConfigEntry<T> sourceConfig) : OwnConfigEntryBase() { public readonly ConfigEntry<T> SourceConfig = sourceConfig; public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig; public T Value { get { return SourceConfig.Value; } set { SourceConfig.Value = value; } } public void AssignLocalValue(T value) { if (LocalBaseValue == null) { Value = value; } else { LocalBaseValue = value; } } } internal abstract class CustomSyncedValueBase { public object? LocalBaseValue; public readonly string Identifier; public readonly Type Type; private object? boxedValue; protected bool localIsOwner; public readonly int Priority; public object? BoxedValue { get { return boxedValue; } set { boxedValue = value; this.ValueChanged?.Invoke(); } } public event Action? ValueChanged; protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type, int priority) { Priority = priority; Identifier = identifier; Type = type; configSync.AddCustomValue(this); localIsOwner = configSync.IsSourceOfTruth; configSync.SourceOfTruthChanged += delegate(bool truth) { localIsOwner = truth; }; } } [PublicAPI] internal sealed class CustomSyncedValue<T> : CustomSyncedValueBase { public T Value { get { return (T)base.BoxedValue; } set { base.BoxedValue = value; } } public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T), int priority = 0) : base(configSync, identifier, typeof(T), priority) { Value = value; } public void AssignLocalValue(T value) { if (localIsOwner) { Value = value; } else { LocalBaseValue = value; } } } internal class ConfigurationManagerAttributes { [UsedImplicitly] public bool? ReadOnly = false; } [PublicAPI] internal class ConfigSync { [HarmonyPatch(typeof(ZRpc), "HandlePackage")] private static class SnatchCurrentlyHandlingRPC { public static ZRpc? currentRpc; [HarmonyPrefix] private static void Prefix(ZRpc __instance) { currentRpc = __instance; } } [HarmonyPatch(typeof(ZNet), "Awake")] internal static class RegisterRPCPatch { [HarmonyPostfix] private static void Postfix(ZNet __instance) { isServer = __instance.IsServer(); foreach (ConfigSync configSync2 in configSyncs) { ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_FromOtherClientConfigSync); if (isServer) { configSync2.InitialSyncDone = true; Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections")); } } if (isServer) { ((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges()); } static void SendAdmin(List<ZNetPeer> peers, bool isAdmin) { ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1] { new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = isAdmin } }); ConfigSync configSync = configSyncs.First(); if (configSync != null) { ((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package)); } } static IEnumerator WatchAdminListChanges() { MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); List<string> CurrentList = new List<string>(adminList.GetList()); while (true) { yield return (object)new WaitForSeconds(30f); if (!adminList.GetList().SequenceEqual(CurrentList)) { CurrentList = new List<string>(adminList.GetList()); List<ZNetPeer> adminPeer = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p) { string hostName = p.m_rpc.GetSocket().GetHostName(); return ((object)listContainsId == null) ? adminList.Contains(hostName) : ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName })); }).ToList(); List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList(); SendAdmin(nonAdminPeer, isAdmin: false); SendAdmin(adminPeer, isAdmin: true); } } } } } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] private static class RegisterClientRPCPatch { [HarmonyPostfix] private static void Postfix(ZNet __instance, ZNetPeer peer) { if (__instance.IsServer()) { return; } foreach (ConfigSync configSync in configSyncs) { peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync); } } } private class ParsedConfigs { public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new Dictionary<OwnConfigEntryBase, object>(); public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new Dictionary<CustomSyncedValueBase, object>(); } [HarmonyPatch(typeof(ZNet), "Shutdown")] private class ResetConfigsOnShutdown { [HarmonyPostfix] private static void Postfix() { ProcessingServerUpdate = true; foreach (ConfigSync configSync in configSyncs) { configSync.resetConfigsFromServer(); configSync.IsSourceOfTruth = true; configSync.InitialSyncDone = false; } ProcessingServerUpdate = false; } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] private class SendConfigsAfterLogin { private class BufferingSocket : ZPlayFabSocket, ISocket { public volatile bool finished = false; public volatile int versionMatchQueued = -1; public readonly List<ZPackage> Package = new List<ZPackage>(); public readonly ISocket Original; public BufferingSocket(ISocket original) { Original = original; ((ZPlayFabSocket)this)..ctor(); } public bool IsConnected() { return Original.IsConnected(); } public ZPackage Recv() { return Original.Recv(); } public int GetSendQueueSize() { return Original.GetSendQueueSize(); } public int GetCurrentSendRate() { return Original.GetCurrentSendRate(); } public bool IsHost() { return Original.IsHost(); } public void Dispose() { Original.Dispose(); } public bool GotNewData() { return Original.GotNewData(); } public void Close() { Original.Close(); } public string GetEndPointString() { return Original.GetEndPointString(); } public void GetAndResetStats(out int totalSent, out int totalRecv) { Original.GetAndResetStats(ref totalSent, ref totalRecv); } public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec) { Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec); } public ISocket Accept() { return Original.Accept(); } public int GetHostPort() { return Original.GetHostPort(); } public bool Flush() { return Original.Flush(); } public string GetHostName() { return Original.GetHostName(); } public void VersionMatch() { if (finished) { Original.VersionMatch(); } else { versionMatchQueued = Package.Count; } } public void Send(ZPackage pkg) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Expected O, but got Unknown int pos = pkg.GetPos(); pkg.SetPos(0); int num = pkg.ReadInt(); if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished) { ZPackage val = new ZPackage(pkg.GetArray()); val.SetPos(pos); Package.Add(val); } else { pkg.SetPos(pos); Original.Send(pkg); } } } [HarmonyPriority(800)] [HarmonyPrefix] private static void Prefix(ref Dictionary<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc) { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Invalid comparison between Unknown and I4 if (!__instance.IsServer()) { return; } BufferingSocket bufferingSocket = new BufferingSocket(rpc.GetSocket()); AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket); object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (val != null && (int)ZNet.m_onlineBackend > 0) { FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket"); object? value = fieldInfo.GetValue(val); ZPlayFabSocket val2 = (ZPlayFabSocket)((value is ZPlayFabSocket) ? value : null); if (val2 != null) { typeof(ZPlayFabSocket).GetField("m_remotePlayerId").SetValue(bufferingSocket, val2.m_remotePlayerId); } fieldInfo.SetValue(val, bufferingSocket); } if (__state == null) { __state = new Dictionary<Assembly, BufferingSocket>(); } __state[Assembly.GetExecutingAssembly()] = bufferingSocket; } [HarmonyPostfix] private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc) { ZNetPeer peer; if (__instance.IsServer()) { object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (peer == null) { SendBufferedData(); } else { ((MonoBehaviour)__instance).StartCoroutine(sendAsync()); } } void SendBufferedData() { if (rpc.GetSocket() is BufferingSocket bufferingSocket) { AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original); object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null); if (val != null) { AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original); } } BufferingSocket bufferingSocket2 = __state[Assembly.GetExecutingAssembly()]; bufferingSocket2.finished = true; for (int i = 0; i < bufferingSocket2.Package.Count; i++) { if (i == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } bufferingSocket2.Original.Send(bufferingSocket2.Package[i]); } if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } } IEnumerator sendAsync() { foreach (ConfigSync configSync in configSyncs) { List<PackageEntry> entries = new List<PackageEntry>(); if (configSync.CurrentVersion != null) { entries.Add(new PackageEntry { section = "Internal", key = "serverversion", type = typeof(string), value = configSync.CurrentVersion }); } MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); entries.Add(new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2] { adminList, rpc.GetSocket().GetHostName() })) }); ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false); yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package)); } SendBufferedData(); } } } private class PackageEntry { public string section = null; public string key = null; public Type type = null; public object? value; } [HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")] private static class PreventSavingServerInfo { [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, ref string __result) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase)) { return true; } __result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType); return false; } } [HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")] private static class PreventConfigRereadChangingValues { [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, string value) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null) { return true; } try { ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType); } catch (Exception ex) { Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}"); } return false; } } private class InvalidDeserializationTypeException : Exception { public string expected = null; public string received = null; public string field = ""; } public static bool ProcessingServerUpdate; public readonly string Name; public string? DisplayName; public string? CurrentVersion; public string? MinimumRequiredVersion; public bool ModRequired = false; private bool? forceConfigLocking; private bool isSourceOfTruth = true; private static readonly HashSet<ConfigSync> configSyncs; private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>(); private HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>(); private static bool isServer; private static bool lockExempt; private OwnConfigEntryBase? lockedConfig = null; private const byte PARTIAL_CONFIGS = 1; private const byte FRAGMENTED_CONFIG = 2; private const byte COMPRESSED_CONFIG = 4; private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>(); private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>(); private static long packageCounter; public bool IsLocked { get { bool? flag = forceConfigLocking; bool num; if (!flag.HasValue) { if (lockedConfig == null) { goto IL_0052; } num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0; } else { num = flag == true; } if (!num) { goto IL_0052; } int result = ((!lockExempt) ? 1 : 0); goto IL_0053; IL_0052: result = 0; goto IL_0053; IL_0053: return (byte)result != 0; } set { forceConfigLocking = value; } } public bool IsAdmin => lockExempt || isSourceOfTruth; public bool IsSourceOfTruth { get { return isSourceOfTruth; } private set { if (value != isSourceOfTruth) { isSourceOfTruth = value; this.SourceOfTruthChanged?.Invoke(value); } } } public bool InitialSyncDone { get; private set; } = false; public event Action<bool>? SourceOfTruthChanged; private event Action? lockedConfigChanged; static ConfigSync() { ProcessingServerUpdate = false; configSyncs = new HashSet<ConfigSync>(); lockExempt = false; packageCounter = 0L; RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle); } public ConfigSync(string name) { Name = name; configSyncs.Add(this); new VersionCheck(this); } public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry) { OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry); SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>; if (syncedEntry == null) { syncedEntry = new SyncedConfigEntry<T>(configEntry); AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1] { new ConfigurationManagerAttributes() }.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray()); configEntry.SettingChanged += delegate { if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig) { Broadcast(0L, (ConfigEntryBase)configEntry); } }; allConfigs.Add(syncedEntry); } return syncedEntry; } public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible { if (lockedConfig != null) { throw new Exception("Cannot initialize locking ConfigEntry twice"); } lockedConfig = AddConfigEntry<T>(lockingConfig); lockingConfig.SettingChanged += delegate { this.lockedConfigChanged?.Invoke(); }; return (SyncedConfigEntry<T>)lockedConfig; } internal void AddCustomValue(CustomSyncedValueBase customValue) { if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue.Identifier)) { throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)"); } allCustomValues.Add(customValue); allCustomValues = new HashSet<CustomSyncedValueBase>(allCustomValues.OrderByDescending((CustomSyncedValueBase v) => v.Priority)); customValue.ValueChanged += delegate { if (!ProcessingServerUpdate) { Broadcast(0L, customValue); } }; } private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package) { lockedConfigChanged += serverLockedSettingChanged; IsSourceOfTruth = false; if (HandleConfigSyncRPC(0L, package, clientUpdate: false)) { InitialSyncDone = true; } } private void RPC_FromOtherClientConfigSync(long sender, ZPackage package) { HandleConfigSyncRPC(sender, package, clientUpdate: true); } private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate) { //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Expected O, but got Unknown //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Expected O, but got Unknown //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Expected O, but got Unknown try { if (isServer && IsLocked) { ZRpc? currentRpc = SnatchCurrentlyHandlingRPC.currentRpc; object obj; if (currentRpc == null) { obj = null; } else { ISocket socket = currentRpc.GetSocket(); obj = ((socket != null) ? socket.GetHostName() : null); } string text = (string)obj; if (text != null) { MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text })))) { return false; } } } cacheExpirations.RemoveAll(delegate(KeyValuePair<long, string> kv) { if (kv.Key < DateTimeOffset.Now.Ticks) { configValueCache.Remove(kv.Value); return true; } return false; }); byte b = package.ReadByte(); if ((b & 2) != 0) { long num = package.ReadLong(); string text2 = sender.ToString() + num; if (!configValueCache.TryGetValue(text2, out SortedDictionary<int, byte[]> value)) { value = new SortedDictionary<int, byte[]>(); configValueCache[text2] = value; cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2)); } int key = package.ReadInt(); int num2 = package.ReadInt(); value.Add(key, package.ReadByteArray()); if (value.Count < num2) { return false; } configValueCache.Remove(text2); package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray()); b = package.ReadByte(); } ProcessingServerUpdate = true; if ((b & 4) != 0) { byte[] buffer = package.ReadByteArray(); MemoryStream stream = new MemoryStream(buffer); MemoryStream memoryStream = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress)) { deflateStream.CopyTo(memoryStream); } package = new ZPackage(memoryStream.ToArray()); b = package.ReadByte(); } if ((b & 1) == 0) { resetConfigsFromServer(); } ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package); ConfigFile val2 = null; bool saveOnConfigSet = false; foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues) { if (!isServer && configValue.Key.LocalBaseValue == null) { configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue; } if (val2 == null) { val2 = configValue.Key.BaseConfig.ConfigFile; saveOnConfigSet = val2.SaveOnConfigSet; val2.SaveOnConfigSet = false; } configValue.Key.BaseConfig.BoxedValue = configValue.Value; } if (val2 != null) { val2.SaveOnConfigSet = saveOnConfigSet; val2.Save(); } foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues) { if (!isServer) { CustomSyncedValueBase key2 = customValue.Key; if (key2.LocalBaseValue == null) { key2.LocalBaseValue = customValue.Key.BoxedValue; } } customValue.Key.BoxedValue = customValue.Value; } Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name)); if (!isServer) { serverLockedSettingChanged(); } return true; } finally { ProcessingServerUpdate = false; } } private ParsedConfigs ReadConfigsFromPackage(ZPackage package) { ParsedConfigs parsedConfigs = new ParsedConfigs(); Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c); Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c); int num = package.ReadInt(); for (int num2 = 0; num2 < num; num2++) { string text = package.ReadString(); string text2 = package.ReadString(); string text3 = package.ReadString(); Type type = Type.GetType(text3); if (text3 == "" || type != null) { object obj; try { obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type)); } catch (InvalidDeserializationTypeException ex) { Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected)); continue; } OwnConfigEntryBase value2; if (text == "Internal") { CustomSyncedValueBase value; if (text2 == "serverversion") { if (obj?.ToString() != CurrentVersion) { Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown"))); } } else if (text2 == "lockexempt") { if (obj is bool flag) { lockExempt = flag; } } else if (dictionary2.TryGetValue(text2, out value)) { if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3) { parsedConfigs.customValues[value] = obj; continue; } Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName)); } } else if (dictionary.TryGetValue(text + "_" + text2, out value2)) { Type type2 = configType(value2.BaseConfig); if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3) { parsedConfigs.configValues[value2] = obj; continue; } Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName)); } else { Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match.")); } continue; } Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs")); return new ParsedConfigs(); } return parsedConfigs; } private static bool isWritableConfig(OwnConfigEntryBase config) { ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config)); if (configSync == null) { return true; } return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null || (!configSync.IsLocked && (config != configSync.lockedConfig || lockExempt)); } private void serverLockedSettingChanged() { foreach (OwnConfigEntryBase allConfig in allConfigs) { configAttribute<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig); } } private void resetConfigsFromServer() { ConfigFile val = null;