diff --git a/README.md b/README.md index 50e2f15..652339d 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,3 @@ -Here's the updated guide with clear instructions for downloading the correct zip file and extracting it, as well as replacing the DLL if you've previously installed the mod: - # ♻ BetterAmongUs ♻ A client-sided mod that enhances the experience for the popular game Among Us! @@ -16,6 +14,7 @@ A client-sided mod that enhances the experience for the popular game Among Us! ## Installation +Here's the updated guide with clear instructions for downloading the correct zip file and extracting it, as well as replacing the DLL if you've previously installed the mod, as this has been requested to be updated multiple times... ### For First-Time Installation: diff --git a/src/Data/SharedSecretExchange.cs b/src/Data/SharedSecretExchange.cs index eea7937..c208b2d 100644 --- a/src/Data/SharedSecretExchange.cs +++ b/src/Data/SharedSecretExchange.cs @@ -12,24 +12,69 @@ internal sealed class SharedSecretExchange private byte[] publicKey; private int tempKey; private byte[] sharedSecret = []; + private bool cryptoDisabled; + + /// + /// Gets a value indicating whether cryptographic operations are available. + /// + internal bool CryptoAvailable => !cryptoDisabled; + + /// + /// Gets or sets a value indicating whether to use the fallback key exchange mechanism. + /// + internal bool UseFallback { get; set; } + + private int? remoteTempKey; /// /// Initializes a new instance of the SharedSecretExchange class with a new ECDH key pair. /// internal SharedSecretExchange() { - dh = ECDiffieHellman.Create(ECCurve.NamedCurves.nistP256); - publicKey = dh.ExportSubjectPublicKeyInfo(); - var random = new Random(); - tempKey = random.Next(); + try + { + dh = ECDiffieHellman.Create(); + dh.GenerateKey(ECCurve.NamedCurves.nistP256); + publicKey = dh.ExportSubjectPublicKeyInfo(); + } + catch (Exception ex) + { + Logger_.Error("ECDH unavailable, using fallback handshake: " + ex.Message); + cryptoDisabled = true; + dh = null; + publicKey = []; + } + + tempKey = GenerateSecureTempKey(); + } + + /// + /// Generates a cryptographically secure random temporary key. + /// + /// A random positive integer used as a temporary key. + private static int GenerateSecureTempKey() + { + byte[] buffer = new byte[4]; + RandomNumberGenerator.Fill(buffer); + return Math.Abs(BitConverter.ToInt32(buffer, 0)); + } + + /// + /// Sets the temporary key received from the remote party. + /// + /// The temporary key from the remote party. + internal void SetRemoteTempKey(int key) + { + remoteTempKey = key; } /// /// Gets the public key for key exchange. /// - /// The public key in SubjectPublicKeyInfo format. + /// The public key in SubjectPublicKeyInfo format, or an empty array if cryptography is disabled. internal byte[] GetPublicKey() { + if (cryptoDisabled) return []; return publicKey; } @@ -46,7 +91,10 @@ internal sealed class SharedSecretExchange /// Gets the established shared secret. /// /// The shared secret byte array. - internal byte[] GetSharedSecret() => sharedSecret; + internal byte[] GetSharedSecret() + { + return sharedSecret; + } /// /// Generates a shared secret using another party's public key. @@ -57,18 +105,31 @@ internal sealed class SharedSecretExchange { if (sharedSecret.Length > 0) return sharedSecret; + if (cryptoDisabled || UseFallback) + { + if (!remoteTempKey.HasValue) + return []; + + sharedSecret = DeriveFallbackSecret(tempKey, remoteTempKey.Value); + return sharedSecret; + } + try { - using ECDiffieHellman otherPartyDH = ECDiffieHellman.Create(); - otherPartyDH.ImportSubjectPublicKeyInfo(otherPartyPublicKey, out _); + using var otherPartyDH = ECDiffieHellman.Create(); + if (otherPartyPublicKey == null || otherPartyPublicKey.Length == 0) + return []; + + otherPartyDH.ImportSubjectPublicKeyInfo(otherPartyPublicKey, out _); sharedSecret = dh.DeriveKeyMaterial(otherPartyDH.PublicKey); + dh.Dispose(); return sharedSecret; } catch (Exception ex) { - Logger_.Error($"Error generating shared secret: {ex.Message}"); + Logger_.Error("Error generating shared secret: " + ex.Message); return []; } } @@ -79,15 +140,40 @@ internal sealed class SharedSecretExchange /// A 32-bit integer hash of the shared secret, or 0 if no shared secret exists. internal int GetSharedSecretHash() { - if (sharedSecret.Length == 0) - return 0; + if (sharedSecret.Length == 0) return 0; using SHA256 sha256 = SHA256.Create(); byte[] hashBytes = sha256.ComputeHash(sharedSecret); - int numericHash = BitConverter.ToInt32(hashBytes, 0); + + int numericHash = (hashBytes[0] << 24) | + (hashBytes[1] << 16) | + (hashBytes[2] << 8) | + hashBytes[3]; + return Math.Abs(numericHash); } + /// + /// Derives a fallback shared secret using temporary keys when ECDH is unavailable. + /// + /// The local temporary key. + /// The remote temporary key. + /// A 256-bit hash derived from the ordered temporary keys. + private static byte[] DeriveFallbackSecret(int local, int remote) + { + using SHA256 sha256 = SHA256.Create(); + + int a = local < remote ? local : remote; + int b = local < remote ? remote : local; + + byte[] buffer = new byte[8]; + + Buffer.BlockCopy(BitConverter.GetBytes(a), 0, buffer, 0, 4); + Buffer.BlockCopy(BitConverter.GetBytes(b), 0, buffer, 4, 4); + + return sha256.ComputeHash(buffer); + } + /// /// Gets a value indicating whether the key exchange data has been cleared for security. /// @@ -104,4 +190,4 @@ internal sealed class SharedSecretExchange tempKey = 0; sharedSecret = []; } -} \ No newline at end of file +} diff --git a/src/Modules/HandshakeHandler.cs b/src/Modules/HandshakeHandler.cs index 0c29192..2db7f3b 100644 --- a/src/Modules/HandshakeHandler.cs +++ b/src/Modules/HandshakeHandler.cs @@ -1,4 +1,4 @@ -using BepInEx.Unity.IL2CPP.Utils; +using BepInEx.Unity.IL2CPP.Utils; using BetterAmongUs.Data; using BetterAmongUs.Data.Config; using BetterAmongUs.Enums; @@ -46,8 +46,8 @@ internal sealed class HandshakeHandler if (GameState.IsFreePlay) yield break; yield return null; } - yield return new WaitForSeconds(1f); + yield return new WaitForSeconds(1f); SendSecretToPlayer(); } @@ -73,8 +73,10 @@ internal sealed class HandshakeHandler if (HasSendSharedSecret) return; HasSendSharedSecret = true; + RPC.SendCustomRpcPacked(CustomRPC.SendSecretToPlayer, writer => { + writer.Write(SharedSecret.CryptoAvailable); writer.WriteBytes(SharedSecret.GetPublicKey()); writer.Write(SharedSecret.GetTempKey()); }, extendedData._Data.ClientId); @@ -89,18 +91,24 @@ internal sealed class HandshakeHandler { if (extendedData._Data?.Object?.IsLocalPlayer() == true) return; + bool senderSupportsCrypto = reader.ReadBoolean(); byte[] sendersPublicKey = reader.ReadBytes(); int tempKey = reader.ReadInt32(); // Logger.Log($"Received public key ({sendersPublicKey.Length} bytes) from {_Data.PlayerName}"); + SharedSecret.UseFallback = !senderSupportsCrypto; + SharedSecret.SetRemoteTempKey(tempKey); + byte[] secret = SharedSecret.GenerateSharedSecret(sendersPublicKey); if (secret.Length == 0) { // Logger.Error("Failed to generate shared secret!"); return; } + extendedData.IsBetterUser = true; + TryHandlePendingVerificationData(); SendSecretHashToSender(tempKey, extendedData._Data.ClientId); ResendSecretToPlayer(); @@ -134,6 +142,7 @@ internal sealed class HandshakeHandler { int tempKey = reader.ReadInt32(); int receivedHash = reader.ReadInt32(); + _pendingVerificationData = (tempKey, receivedHash); TryHandlePendingVerificationData(); } @@ -143,30 +152,29 @@ internal sealed class HandshakeHandler /// internal void TryHandlePendingVerificationData() { - if (_pendingVerificationData?.tempKey == null || _pendingVerificationData?.receivedHash == null) return; + if (!_pendingVerificationData.HasValue) return; if (SharedSecret.GetSharedSecret().Length == 0) return; - var tempKey = _pendingVerificationData?.tempKey; - var receivedHash = _pendingVerificationData?.receivedHash; + var data = _pendingVerificationData.Value; - // Logger.Log($"Received hash check: TempKey={tempKey} (ours={SharedSecret.GetTempKey()}), Hash={receivedHash} (ours={SharedSecret.GetSharedSecretHash()})"); + // Logger.Log($"Received hash check: TempKey={data.tempKey} (ours={SharedSecret.GetTempKey()}), Hash={data.receivedHash} (ours={SharedSecret.GetSharedSecretHash()})"); - if (tempKey != SharedSecret.GetTempKey()) + if (data.tempKey != SharedSecret.GetTempKey()) { - // Logger.Warning($"Invalid tempKey from {_Data.PlayerName}"); + // Logger.Warning($"Invalid tempKey from {extendedData._Data?.PlayerName}"); return; } extendedData.IsBetterUser = true; - if (receivedHash == SharedSecret.GetSharedSecretHash()) + if (data.receivedHash == SharedSecret.GetSharedSecretHash()) { extendedData.IsVerifiedBetterUser = true; - // Logger.Log($"Verified player: {_Data.PlayerName}"); + // Logger.Log($"Verified player: {extendedData._Data?.PlayerName}"); } else { - // Logger.Warning($"Hash mismatch from {_Data.PlayerName}"); + // Logger.Warning($"Hash mismatch from {extendedData._Data?.PlayerName}"); } _pendingVerificationData = null; @@ -179,4 +187,4 @@ internal sealed class HandshakeHandler /// Gets the SharedSecretExchange instance for secure key exchange. /// internal SharedSecretExchange SharedSecret { get; set; } = new(); -} \ No newline at end of file +} diff --git a/src/Mono/ExtendedPlayerInfo.cs b/src/Mono/ExtendedPlayerInfo.cs index 7e7cf10..ac638d1 100644 --- a/src/Mono/ExtendedPlayerInfo.cs +++ b/src/Mono/ExtendedPlayerInfo.cs @@ -15,17 +15,19 @@ internal sealed class ExtendedPlayerInfo : MonoBehaviour, IMonoExtension - /// Gets or sets the base NetworkedPlayerInfo instance. - /// public NetworkedPlayerInfo? BaseMono { get; set; } - /// - /// Gets the NetworkedPlayerInfo instance. - /// internal NetworkedPlayerInfo? _Data => BaseMono; private bool hasSet = false; @@ -47,7 +49,11 @@ internal sealed class ExtendedPlayerInfo : MonoBehaviour, IMonoExtension= ExtendedAntiCheatInfo.MAX_RPC_SENT && !flag) { - BetterNotificationManager.NotifyCheat(_Data.Object, + BetterNotificationManager.NotifyCheat( + _Data.Object, Translator.GetString("AntiCheat.Reason.RPCSentPS"), Translator.GetString("AntiCheat.UnauthorizedAction") ); + Logger_.LogCheat($"{_Data.Object.BetterData().RealName} {AntiCheatInfo.RPCSentPS} Sent."); } timeAccumulator += time; + if (timeAccumulator >= 0.25f - 0.005 * AntiCheatInfo.RPCSentPS) { AntiCheatInfo.RPCSentPS -= 1; @@ -90,7 +99,7 @@ internal sealed class ExtendedPlayerInfo : MonoBehaviour, IMonoExtension [HideFromIl2Cpp] - internal HandshakeHandler HandshakeHandler { get; } + internal HandshakeHandler? HandshakeHandler { get; } /// /// Gets the player ID. diff --git a/src/Mono/PlayerInfoDisplay.cs b/src/Mono/PlayerInfoDisplay.cs index f934d94..9cc3889 100644 --- a/src/Mono/PlayerInfoDisplay.cs +++ b/src/Mono/PlayerInfoDisplay.cs @@ -147,7 +147,14 @@ internal class PlayerInfoDisplay : MonoBehaviour /// private void UpdatePlayerInfo() { - if (_player?.Data == null) return; + if (_player == null) return; + if (_player.Data == null) return; + + if (_nameText == null) return; + if (_cachedTranslations == null) return; + + if (_sbTag == null || _sbTagTop == null || _sbTagBottom == null) return; + if (_topText == null || _bottomText == null || _infoText == null) return; var betterData = _player.BetterData(); @@ -170,19 +177,19 @@ internal class PlayerInfoDisplay : MonoBehaviour string friendCode = ValidateFriendCode(out string friendCodeColor); + if (DataManager.Settings == null || DataManager.Settings.Gameplay == null) + return; + if (DataManager.Settings.Gameplay.StreamerMode) - { platform = _cachedTranslations.PlatformHidden; - } if (!_player.IsInShapeshift()) - { SetPlayerOutline(_sbTag); - } if (GameState.IsInGame && GameState.IsLobby && !GameState.IsFreePlay) { SetLobbyInfo(ref newName, betterData, _sbTag); + _sbTagTop.Append($"{platform}+++") .Append($"Lv: {_player.Data.PlayerLevel + 1}+++"); @@ -197,15 +204,21 @@ internal class PlayerInfoDisplay : MonoBehaviour { if (_player.IsImpostorTeammate()) newName = newName.ToColor(Colors.ImpostorRed); + _player.RawSetName(newName); } else { var targetData = Utils.PlayerDataFromPlayerId(_player.shapeshiftTargetPlayerId); - var name = targetData.BetterData()?.RealName ?? targetData.PlayerName; + if (targetData == null) return; + + var betterTargetData = targetData.BetterData(); + string name = betterTargetData != null ? betterTargetData.RealName : targetData.PlayerName; + if (_player.IsImpostorTeammate()) name = name.ToColor(Colors.ImpostorRed); - if (targetData != null) _player.RawSetName(name); + + _player.RawSetName(name); } UpdateTextIfChanged(_topText, _sbTagTop, ref _lastTopText); @@ -362,22 +375,18 @@ internal class PlayerInfoDisplay : MonoBehaviour } /// - /// Sets lobby-specific information. + /// Sets in-game specific information. /// - /// Reference to the player's name. - /// Extended player data. - /// StringBuilder for tag text. [HideFromIl2Cpp] private void SetLobbyInfo(ref string newName, ExtendedPlayerInfo betterData, StringBuilder sbTag) { - if (betterData == null) return; - if (_player.IsHost() && BAUConfigs.LobbyPlayerInfo.Value) newName = _player.GetPlayerNameAndColor(); if ((_player.IsLocalPlayer() || betterData.IsBetterUser) && !GameState.IsInGamePlay) { string verificationSymbol = betterData.IsVerifiedBetterUser || _player.IsLocalPlayer() ? "✓ " : ""; + sbTag.AppendFormat("{1}{0}+++", _cachedTranslations.BetterUser, verificationSymbol); } diff --git a/src/Patches/Client/PrivateLobbyPatch.cs b/src/Patches/Client/PrivateLobbyPatch.cs index c289a6b..9704506 100644 --- a/src/Patches/Client/PrivateLobbyPatch.cs +++ b/src/Patches/Client/PrivateLobbyPatch.cs @@ -127,8 +127,11 @@ internal static class PrivateLobbyPatch button.enabled = false; // Change inactive sprite to cyan color to indicate locked state - var sprite = __instance.HostPrivateButton.transform.Find("Inactive").GetComponent(); - sprite?.color = new(0.35f, 1, 1, 1); + var sprite = __instance.HostPrivateButton.transform.Find("Inactive")?.GetComponent(); + if (sprite != null) + { + sprite.color = new Color(0.35f, 1f, 1f, 1f); // Corrected colour assignment + } } } } diff --git a/src/Patches/Gameplay/Player/PlayerControlPatch.cs b/src/Patches/Gameplay/Player/PlayerControlPatch.cs index 6d4e0e0..08dc4a8 100644 --- a/src/Patches/Gameplay/Player/PlayerControlPatch.cs +++ b/src/Patches/Gameplay/Player/PlayerControlPatch.cs @@ -58,7 +58,9 @@ internal static class PlayerControlPatch [HarmonyPostfix] private static void PlayerControl_MurderPlayer_Postfix(PlayerControl __instance, PlayerControl target) { - if (target == null) return; + // Check for null references + if (__instance == null || target == null || target.Data == null || __instance.Data == null) + return; // Log kill event with player names and roles Logger_.LogPrivate($"{__instance.Data.PlayerName} Has killed {target.Data.PlayerName} as {__instance.Data.RoleType.GetRoleName()}", "EventLog"); diff --git a/src/Patches/Gameplay/UI/Chat/ChatCommandsPatch.cs b/src/Patches/Gameplay/UI/Chat/ChatCommandsPatch.cs index d1bcc6c..5c1ea1f 100644 --- a/src/Patches/Gameplay/UI/Chat/ChatCommandsPatch.cs +++ b/src/Patches/Gameplay/UI/Chat/ChatCommandsPatch.cs @@ -226,7 +226,10 @@ internal static class ChatCommandsPatch { for (int i = 1; i < typedParts.Length && i <= closestCommand.Arguments.Length; i++) { - closestCommand.Arguments[i - 1]?.Arg = typedParts[i]; + if (closestCommand.Arguments[i - 1] != null) + { + closestCommand.Arguments[i - 1].Arg = typedParts[i]; // Safe assignment + } } } diff --git a/src/Patches/Gameplay/UI/Chat/ChatPatch.cs b/src/Patches/Gameplay/UI/Chat/ChatPatch.cs index ed490fe..f17f4dc 100644 --- a/src/Patches/Gameplay/UI/Chat/ChatPatch.cs +++ b/src/Patches/Gameplay/UI/Chat/ChatPatch.cs @@ -47,7 +47,6 @@ internal static class ChatPatch internal static void ClearCommands() { if (!HudManager.InstanceExists) return; - // Clear only command chat bubbles (keep player chat) foreach (var obj in HudManager.Instance.Chat.chatBubblePool.activeChildren.ToArray()) { @@ -89,21 +88,18 @@ internal static class ChatPatch __instance.freeChatField.textArea.compoText.Color(Color.black); __instance.freeChatField.textArea.outputText.color = Color.black; } - - // Ctrl+X to cut text to clipboard + // Ctrl+x to cut text to clipboard if ((Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) && Input.GetKeyDown(KeyCode.X)) { ClipboardHelper.PutClipboardString(__instance.freeChatField.textArea.text); __instance.freeChatField.textArea.SetText(""); } - // Up arrow for chat history navigation if (Input.GetKeyDown(KeyCode.UpArrow) && ChatHistory.Any()) { CurrentHistorySelection = Mathf.Clamp(--CurrentHistorySelection, 0, ChatHistory.Count - 1); __instance.freeChatField.textArea.SetText(ChatHistory[CurrentHistorySelection]); } - // Down arrow for chat history navigation if (Input.GetKeyDown(KeyCode.DownArrow) && ChatHistory.Any()) { @@ -113,7 +109,6 @@ internal static class ChatPatch else __instance.freeChatField.textArea.SetText(""); } } - // Log chat messages to console [HarmonyPatch(typeof(ChatController), nameof(ChatController.AddChat))] [HarmonyPostfix] @@ -135,11 +130,15 @@ internal static class ChatPatch private static void ChatController_SetChatBubbleName_Postfix(ChatController __instance, ChatBubble bubble, NetworkedPlayerInfo playerInfo, bool isDead, bool didVote) { if (didVote) return; + if (bubble == null || bubble.NameText == null || playerInfo == null) return; + + var sourcePlayer = playerInfo.Object; + var localPlayer = PlayerControl.LocalPlayer; + if (sourcePlayer == null || localPlayer == null) return; StringBuilder sbTag = new(); StringBuilder sbInfo = new(); - var sourcePlayer = playerInfo.Object; string hashPuid = Utils.GetHashPuid(sourcePlayer); string friendCode = playerInfo.FriendCode; string playerName = playerInfo.BetterData()?.RealName ?? "???"; @@ -152,9 +151,14 @@ internal static class ChatPatch { Role = ""; + var betterData = sourcePlayer.BetterData(); + if (betterData == null) return; + // Show BAU user tag - if (sourcePlayer.IsLocalPlayer() || sourcePlayer.BetterData().IsBetterUser) - sbTag.AppendFormat("{1}{0}+++", Translator.GetString("Player.BetterUser"), sourcePlayer.BetterData().IsVerifiedBetterUser || sourcePlayer.IsLocalPlayer() ? "✓ " : ""); + if (sourcePlayer.IsLocalPlayer() || betterData.IsBetterUser) + { + sbTag.AppendFormat("{1}{0}+++", Translator.GetString("Player.BetterUser"), betterData.IsVerifiedBetterUser || sourcePlayer.IsLocalPlayer() ? "✓ " : ""); + } // Show mod-specific tags based on player data if (BetterDataManager.BetterDataFile.SickoData.Any(info => info.CheckPlayerData(sourcePlayer.Data))) @@ -170,46 +174,37 @@ internal static class ChatPatch // Hide roles from alive players (unless same team) if (!sourcePlayer.IsImpostorTeammate()) { - if (PlayerControl.LocalPlayer.IsAlive() && !sourcePlayer.IsLocalPlayer()) - { + if (localPlayer.IsAlive() && !sourcePlayer.IsLocalPlayer()) Role = ""; - } } // Show role for dead players or if local player is Guardian Angel - if (PlayerControl.LocalPlayer.Is(RoleTypes.GuardianAngel) && !sourcePlayer.IsAlive() || !PlayerControl.LocalPlayer.Is(RoleTypes.GuardianAngel)) + if ((localPlayer.Is(RoleTypes.GuardianAngel) && !sourcePlayer.IsAlive()) || !localPlayer.Is(RoleTypes.GuardianAngel)) { sbTag.Append(Role); } // Format tags with separators sbInfo.Append(""); - for (int i = 0; i < sbTag.ToString().Split("+++").Length; i++) + var parts = sbTag.ToString().Split("+++"); + + for (int i = 0; i < parts.Length; i++) { - if (!string.IsNullOrEmpty(sbTag.ToString().Split("+++")[i])) - { - if (i < sbTag.ToString().Split("+++").Length) - { - sbInfo.Append(sbTag.ToString().Split("+++")[i]); - } - if (i != sbTag.ToString().Split("+++").Length - 2) - { - sbInfo.Append(" - "); - } - } + if (string.IsNullOrEmpty(parts[i])) continue; + + sbInfo.Append(parts[i]); + + if (i != parts.Length - 2) + sbInfo.Append(" - "); } + sbInfo.Append(""); // Position tags before local player name, after other players' names - bool flag = sourcePlayer.IsLocalPlayer(); - if (flag) - { - playerName = $"{sbInfo} " + playerName; - } + if (sourcePlayer.IsLocalPlayer()) + playerName = sbInfo + " " + playerName; else - { - playerName += $" {sbInfo}"; - } + playerName += " " + sbInfo; bubble.NameText.SetText(playerName); } @@ -230,7 +225,6 @@ internal static class ChatPatch // Quick chat color chat.quickChatField.background.color = new Color32(40, 40, 40, byte.MaxValue); chat.quickChatField.text.color = Color.white; - // Icons chat.quickChatButton.transform.Find("QuickChatIcon").GetComponent().color = new Color(0.5f, 0.5f, 0.5f, 1f); chat.openKeyboardButton.transform.Find("OpenKeyboardIcon").GetComponent().color = new Color(0.5f, 0.5f, 0.5f, 1f); @@ -240,50 +234,41 @@ internal static class ChatPatch // Quick chat color chat.quickChatField.background.color = new Color32(255, 255, 255, byte.MaxValue); chat.quickChatField.text.color = Color.black; - // Icons chat.quickChatButton.transform.Find("QuickChatIcon").GetComponent().color = new Color(1f, 1f, 1f, 1f); chat.openKeyboardButton.transform.Find("OpenKeyboardIcon").GetComponent().color = new Color(1f, 1f, 1f, 1f); } - // Apply theme to all existing chat bubbles foreach (var item in HudManager.Instance.Chat.chatBubblePool.activeChildren.SelectIl2Cpp(c => c.GetComponent())) { SetChatPoolTheme(item); } } - // Apply theme to individual chat bubble internal static ChatBubble SetChatPoolTheme(ChatBubble asChatBubble) { - ChatBubble chatBubble = asChatBubble; + var chatBubble = asChatBubble; if (BAUConfigs.ChatDarkMode.Value) { - chatBubble.transform.Find("ChatText (TMP)").GetComponentInChildren(true).color = new Color(1f, 1f, 1f, 1f); + chatBubble.transform.Find("ChatText (TMP)").GetComponentInChildren(true).color = Color.white; chatBubble.transform.Find("Background").GetComponentInChildren(true).color = new Color(0.15f, 0.15f, 0.15f, 1f); - // Make dead player chat bubbles more transparent - if (chatBubble.transform.Find("PoolablePlayer/xMark") != null) + var mark = chatBubble.transform.Find("PoolablePlayer/xMark"); + if (mark != null && mark.GetComponentInChildren(true).enabled) { - if (chatBubble.transform.Find("PoolablePlayer/xMark").GetComponentInChildren(true).enabled == true) - { - chatBubble.transform.Find("Background").GetComponentInChildren(true).color = new Color(0.15f, 0.15f, 0.15f, 0.5f); - } + chatBubble.transform.Find("Background").GetComponentInChildren(true).color = new Color(0.15f, 0.15f, 0.15f, 0.5f); } } else { - chatBubble.transform.Find("ChatText (TMP)").GetComponentInChildren(true).color = new Color(0f, 0f, 0f, 1f); - chatBubble.transform.Find("Background").GetComponentInChildren(true).color = new Color(1f, 1f, 1f, 1f); + chatBubble.transform.Find("ChatText (TMP)").GetComponentInChildren(true).color = Color.black; + chatBubble.transform.Find("Background").GetComponentInChildren(true).color = Color.white; - // Make dead player chat bubbles more transparent - if (chatBubble.transform.Find("PoolablePlayer/xMark") != null) + var mark = chatBubble.transform.Find("PoolablePlayer/xMark"); + if (mark != null && mark.GetComponentInChildren(true).enabled) { - if (chatBubble.transform.Find("PoolablePlayer/xMark").GetComponentInChildren(true).enabled == true) - { - chatBubble.transform.Find("Background").GetComponentInChildren(true).color = new Color(1f, 1f, 1f, 0.5f); - } + chatBubble.transform.Find("Background").GetComponentInChildren(true).color = new Color(1f, 1f, 1f, 0.5f); } } @@ -316,14 +301,8 @@ internal static class ChatPatch private static Color GetCharColor(int length) { // Color gradient: green -> yellow -> red as text length increases - Color[] colorGradient = - [ - Color.green, - Color.yellow, - Color.red - ]; - + Color[] colorGradient = [Color.green, Color.yellow, Color.red]; (float min, float max) lerpRange = (0f, 117f); return colorGradient.LerpColor(lerpRange, length); } -} \ No newline at end of file +} diff --git a/src/Patches/Gameplay/UI/GameSummaryPatch.cs b/src/Patches/Gameplay/UI/GameSummaryPatch.cs index 15c0b3b..738179a 100644 --- a/src/Patches/Gameplay/UI/GameSummaryPatch.cs +++ b/src/Patches/Gameplay/UI/GameSummaryPatch.cs @@ -16,6 +16,10 @@ internal static class GameSummaryPatch [HarmonyPostfix] private static void EndGameManager_SetEverythingUp_Postfix(EndGameManager __instance) { + // Check for null references + if (__instance == null) + return; + // Log game end to console LogGameEnd(); diff --git a/src/Patches/Gameplay/UI/MeetingHudPatch.cs b/src/Patches/Gameplay/UI/MeetingHudPatch.cs index eac94a8..0feafa0 100644 --- a/src/Patches/Gameplay/UI/MeetingHudPatch.cs +++ b/src/Patches/Gameplay/UI/MeetingHudPatch.cs @@ -16,24 +16,33 @@ internal static class MeetingHudPatch [HarmonyPostfix] private static void MeetingHud_Start_Postfix(MeetingHud __instance) { + if (__instance == null || __instance.playerStates == null) return; + // Add meeting info display to each player state foreach (var pva in __instance.playerStates) { + if (pva == null) continue; + var target = Utils.PlayerFromPlayerId(pva.TargetPlayerId); + if (target == null) continue; + pva.gameObject.AddComponent().Init(target, pva); } if (!GameState.IsOnlineGame) return; - // Add host icon to meeting UI - __instance.ProceedButton.gameObject.transform.localPosition = new(-2.5f, 2.2f, 0); - __instance.ProceedButton.gameObject.GetComponent().enabled = false; - __instance.ProceedButton.GetComponent().enabled = false; - __instance.HostIcon.enabled = true; - __instance.HostIcon.gameObject.SetActive(true); - __instance.ProceedButton.gameObject.SetActive(true); - MeetingHud.Instance.ProceedButton.DestroyTextTranslators(); - UpdateHostIcon(); + // Add host icon to meeting hud + if (__instance.ProceedButton != null && __instance.HostIcon != null) + { + __instance.ProceedButton.gameObject.transform.localPosition = new(-2.5f, 2.2f, 0); + __instance.ProceedButton.gameObject.GetComponent().enabled = false; + __instance.ProceedButton.GetComponent().enabled = false; + __instance.HostIcon.enabled = true; + __instance.HostIcon.gameObject.SetActive(true); + __instance.ProceedButton.gameObject.SetActive(true); + UpdateHostIcon(); + MeetingHud.Instance.ProceedButton.DestroyTextTranslators(); + } Logger_.LogHeader("Meeting Has Started"); } @@ -42,9 +51,18 @@ internal static class MeetingHudPatch internal static void UpdateHostIcon() { if (MeetingHud.Instance == null) return; + if (GameData.Instance == null) return; - PlayerMaterial.SetColors(GameData.Instance.GetHost().Color, MeetingHud.Instance.HostIcon); - MeetingHud.Instance.ProceedButton.gameObject.GetComponentInChildren().text = string.Format(Translator.GetString("HostInMeeting"), GameData.Instance.GetHost().BetterData().RealName); + var host = GameData.Instance.GetHost(); + if (host == null || host.BetterData() == null) return; + + var hostColor = host.Color; + var hostRealName = host.BetterData().RealName; + + if (MeetingHud.Instance.HostIcon == null || MeetingHud.Instance.ProceedButton == null) return; + + PlayerMaterial.SetColors(hostColor, MeetingHud.Instance.HostIcon); + MeetingHud.Instance.ProceedButton.gameObject.GetComponentInChildren().text = string.Format(Translator.GetString("HostInMeeting"), hostRealName); } internal static float timeOpen = 0f;