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 BetterVC v1.1.1
plugins/bobabulkerENTERPRISE.BetterVC.dll
Decompiled 2 days ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using BetterVC.Compatibility; using BetterVC.Patches; using Dissonance; using GameNetcodeStuff; using HarmonyLib; using LCAlwaysHearWalkieMod; using Microsoft.CodeAnalysis; using TMPro; using Unity.Collections; using Unity.Netcode; using UnityEngine; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("bobabulkerENTERPRISE.BetterVC")] [assembly: AssemblyConfiguration("Thunderstore")] [assembly: AssemblyFileVersion("1.1.1.0")] [assembly: AssemblyInformationalVersion("1.1.1")] [assembly: AssemblyProduct("BetterVC")] [assembly: AssemblyTitle("bobabulkerENTERPRISE.BetterVC")] [assembly: AssemblyVersion("1.1.1.0")] [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 BetterVC { public enum HudVisibilityMode { Always, Never, WhenHavingWalkie, WhenHoldingWalkie } public enum OutOfFocusAudio { MuteAll, MuteAllButPlayers, MuteAllButSpectators, Off } [BepInPlugin("bobabulkerENTERPRISE.BetterVC", "BetterVC", "1.1.1")] [BepInDependency(/*Could not decode attribute arguments.*/)] [DefaultExecutionOrder(32000)] public class Plugin : BaseUnityPlugin { internal static ConfigEntry<float> MinimumDistance = null; internal static ConfigEntry<float> WalkieVolume = null; internal static ConfigEntry<float> RadioEffectStrength = null; internal static ConfigEntry<float> SpeakerVolume = null; internal static ConfigEntry<float> SpeakerEffectStrength = null; internal static ConfigEntry<float> NearbySoundsVolume = null; internal static ConfigEntry<float> SpectatorVolume = null; internal static ConfigEntry<OutOfFocusAudio> OutOfFocusAudioBehavior = null; internal static ConfigEntry<HudVisibilityMode> HudVisibility = null; internal static ConfigEntry<float> HudScale = null; private static readonly Dictionary<string, int> FailureCounts = new Dictionary<string, int>(); internal static ManualLogSource Logger { get; private set; } = null; private void Awake() { //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Expected O, but got Unknown //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Expected O, but got Unknown //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Expected O, but got Unknown //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Expected O, but got Unknown //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Expected O, but got Unknown //IL_016a: Unknown result type (might be due to invalid IL or missing references) //IL_0174: Expected O, but got Unknown //IL_01a7: Unknown result type (might be due to invalid IL or missing references) //IL_01b1: Expected O, but got Unknown //IL_021f: Unknown result type (might be due to invalid IL or missing references) //IL_0225: Expected O, but got Unknown Logger = ((BaseUnityPlugin)this).Logger; MinimumDistance = ((BaseUnityPlugin)this).Config.Bind<float>("Routing", "MinimumDistance", 20f, new ConfigDescription("Between you and a player who is transmitting on a walkie, while you are listening on one (you carry a powered-on walkie, or the game or another mod says you are listening): closer than this (meters) you hear them in person, with the game's normal 3D stereo, and the walkie is silent. Farther than this you hear them only through the walkie, centered. Players who are not transmitting on a walkie are always heard in person.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 200f), Array.Empty<object>())); WalkieVolume = ((BaseUnityPlugin)this).Config.Bind<float>("Walkie Audio", "WalkieVolume", 0.5f, new ConfigDescription("Volume of the walkie voice. 1 = normal voice volume.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); RadioEffectStrength = ((BaseUnityPlugin)this).Config.Bind<float>("Walkie Audio", "RadioEffectStrength", 0.65f, new ConfigDescription("How radio-like a walkie voice sounds. 0 = crisp, like in person. 1 = the game's full walkie sound.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); SpeakerVolume = ((BaseUnityPlugin)this).Config.Bind<float>("Walkie Audio", "SpeakerVolume", 0.25f, new ConfigDescription("Volume of a walkie voice while you carry NO powered-on walkie yourself (you only hear it from a walkie lying on the ground or held by someone else). Always applied in that case, so a far player never sounds like they stand next to you. 1 = normal voice volume.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); SpeakerEffectStrength = ((BaseUnityPlugin)this).Config.Bind<float>("Walkie Audio", "SpeakerEffectStrength", 1f, new ConfigDescription("How radio-like a voice sounds while you carry no powered-on walkie of your own (small tinny speaker). 0 = crisp, 1 = the game's full walkie sound. Never weaker than RadioEffectStrength.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); NearbySoundsVolume = ((BaseUnityPlugin)this).Config.Bind<float>("Walkie Audio", "NearbySoundsVolume", 0.5f, new ConfigDescription("Volume of the sounds around a player who is talking on a walkie (a noisy item in their pocket, footsteps, creatures), as they come through the walkie to you. They only come through while that player is talking, centered like the walkie voices, and they follow how you hear that player: none from a player you muted, quieter when you turn their voice down, none when they are close enough to hear in person. 1 = the base game's loudness, 0 = off.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); SpectatorVolume = ((BaseUnityPlugin)this).Config.Bind<float>("Spectating", "SpectatorVolume", 0.3f, new ConfigDescription("Client-side. While you are dead and spectating, the game's audio and the living players' voices are multiplied by this (1 = unchanged, 0.25 = a quarter as loud, 0 = muted). The voice chat of the other dead players is never changed.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); OutOfFocusAudioBehavior = ((BaseUnityPlugin)this).Config.Bind<OutOfFocusAudio>("Window Focus", "OutOfFocusAudioBehavior", OutOfFocusAudio.MuteAllButSpectators, "Client-side. What the game's audio does while its window is not in front (alt-tabbed or minimized). MuteAll: everything is muted. MuteAllButPlayers: the game's sounds are muted, the voices of the players are not. MuteAllButSpectators: like MuteAllButPlayers, but only the voices of the other spectators stay, and only while you are a spectator yourself (a living player cannot hear the dead, so for them everything is muted). Off: nothing changes."); HudVisibility = ((BaseUnityPlugin)this).Config.Bind<HudVisibilityMode>("HUD", "Visibility", HudVisibilityMode.Always, "When the list of talking players is shown."); HudScale = ((BaseUnityPlugin)this).Config.Bind<float>("HUD", "HudScale", 1f, "Size of the list of talking players. 1 = default."); Harmony val = new Harmony("bobabulkerENTERPRISE.BetterVC"); val.PatchAll(); try { AlwaysHearActiveWalkies.Patch(val); } catch (Exception ex) { Logger.LogWarning((object)("[compat] could not patch the always-hear mod: " + ex.Message)); } Runner.Create(); Logger.LogInfo((object)"bobabulkerENTERPRISE.BetterVC v1.1.1 has loaded!"); } private void Update() { Driver.Tick(); } private void LateUpdate() { Driver.Late(); } private void OnGUI() { Driver.Draw(); } internal static void Debug(string message) { Logger.LogInfo((object)message); } internal static void PerFrame(float dt) { if (Runner.Lost) { Runner.Lost = false; Runner.Create(); } Mirage.DetectOnce(); try { Routing.ResetIfNewLobby(); } catch (Exception e) { ReportFailure("Lobby change check", e); } try { NearbySounds.Tick(); } catch (Exception e2) { ReportFailure("Nearby sounds", e2); } try { MoreScreams.Tick(); } catch (Exception e3) { ReportFailure("MoreScreams death tone", e3); } try { Routing.Tick(dt); } catch (Exception e4) { ReportFailure("Voice routing", e4); } try { VoiceHealth.Tick(dt); } catch (Exception e5) { ReportFailure("Voice health", e5); } try { WalkieSync.Tick(dt); } catch (Exception e6) { ReportFailure("Walkie power sync", e6); } try { WalkieIcon.Tick(); } catch (Exception e7) { ReportFailure("Walkie icon", e7); } try { VoiceHud.Sample(dt); } catch (Exception e8) { ReportFailure("Voice list", e8); } } internal static void ReportFailure(string part, Exception e) { FailureCounts.TryGetValue(part, out var value); FailureCounts[part] = value + 1; if (value < 5) { Logger.LogError((object)$"{part} failed ({value + 1}): {e}"); } } } internal static class AutoTransmit { private enum SendResult { Skipped, Sent, Failed } private static readonly FieldInfo? HolderField = AccessTools.Field(typeof(WalkieTalkie), "previousPlayerHeldBy"); private static bool on; private static bool sending; private static int lastPlayers = -1; private static bool? lastLanded; private static bool everTransmitted; private static bool warnedOwner; private static bool warnedField; private static bool warnedAnnounce; private const float AnnounceInterval = 20f; private static readonly float[] JoinSchedule = new float[9] { 1f, 2f, 3f, 4f, 6f, 8f, 12f, 16f, 20f }; private static readonly float[] ShipSchedule = new float[4] { 1f, 3f, 6f, 12f }; private static readonly float[] ChangeSchedule = new float[2] { 3f, 8f }; private static float nextAnnounce; private static float[]? schedule; private static int scheduleStep; private const float EventJitter = 1.5f; private static float flagResendAt = -1f; private const float StateCalm = 5f; private const float MaxStateGap = 10f; private const int FreeStateSends = 4; private const float SettleSeconds = 0.3f; private static float lastStateSend = -1000f; private static float stateGap; private static int quickStateSends; private static bool lastDesired; private static float desiredSince; private static bool warnedFlapping; private static bool warnedSend; internal static bool Available => HolderField != null; internal static bool Wanted => on; internal static bool Sending => sending; internal static void Reset() { on = false; sending = false; lastPlayers = -1; lastLanded = null; everTransmitted = false; nextAnnounce = 0f; schedule = null; scheduleStep = 0; warnedOwner = false; warnedAnnounce = false; flagResendAt = -1f; lastStateSend = -1000f; stateGap = 0f; quickStateSends = 0; lastDesired = false; desiredSince = 0f; warnedFlapping = false; warnedSend = false; } internal static WalkieTalkie? FindPoweredWalkie(PlayerControllerB? player) { if ((Object)(object)player == (Object)null) { return null; } GrabbableObject itemOnlySlot = player.ItemOnlySlot; WalkieTalkie val = (WalkieTalkie)(object)((itemOnlySlot is WalkieTalkie) ? itemOnlySlot : null); if (val != null && (Object)(object)val != (Object)null && ((GrabbableObject)val).isBeingUsed) { return val; } GrabbableObject[] itemSlots = player.ItemSlots; if (itemSlots != null) { foreach (GrabbableObject obj in itemSlots) { WalkieTalkie val2 = (WalkieTalkie)(object)((obj is WalkieTalkie) ? obj : null); if (val2 != null && (Object)(object)val2 != (Object)null && ((GrabbableObject)val2).isBeingUsed) { return val2; } } } List<WalkieTalkie> allWalkieTalkies = WalkieTalkie.allWalkieTalkies; if (allWalkieTalkies != null) { for (int j = 0; j < allWalkieTalkies.Count; j++) { WalkieTalkie val3 = allWalkieTalkies[j]; if ((Object)(object)val3 != (Object)null && ((GrabbableObject)val3).isBeingUsed && (Object)(object)((GrabbableObject)val3).playerHeldBy == (Object)(object)player && !((GrabbableObject)val3).isHeldByEnemy) { return val3; } } } return null; } internal static bool HasPoweredWalkie(PlayerControllerB? player) { return (Object)(object)FindPoweredWalkie(player) != (Object)null; } private static float Total(float[] steps) { float num = 0f; for (int i = 0; i < steps.Length; i++) { num += steps[i]; } return num; } private static float Remaining(float[]? steps, int from) { if (steps == null) { return 0f; } float num = 0f; for (int i = from; i < steps.Length; i++) { num += steps[i]; } return num; } private static void BeginSchedule(float[] steps, bool sendSoon) { if (schedule == steps && scheduleStep == 0) { return; } if (schedule != null && Remaining(schedule, scheduleStep) > Total(steps)) { if (sendSoon) { SendSoon(); } return; } schedule = steps; scheduleStep = 0; if (sendSoon) { SendSoon(); } } private static void SendSoon() { float unscaledTime = Time.unscaledTime; float num = unscaledTime + Random.Range(0.1f, 1.5f); if (nextAnnounce < unscaledTime || nextAnnounce > num) { nextAnnounce = num; } } private static bool StateSendAllowed(float now) { return now - lastStateSend >= stateGap; } private static void NoteStateSend(float now) { if (now - lastStateSend < 5f) { quickStateSends++; stateGap = ((quickStateSends <= 4) ? 0f : Mathf.Min((stateGap <= 0f) ? 1f : (stateGap * 2f), 10f)); if (stateGap >= 10f && !warnedFlapping) { warnedFlapping = true; Plugin.Logger.LogWarning((object)$"{Clock.Stamp()} [auto] the transmit state keeps changing (something may be clearing it over and over); starts and stops are now limited to one every {10f:F0}s until it settles"); } } else { quickStateSends = 0; stateGap = 0f; } lastStateSend = now; } private static float NextDelay() { if (schedule != null && scheduleStep < schedule.Length) { return schedule[scheduleStep++] + Random.Range(0f, 1f); } schedule = null; scheduleStep = 0; return 20f + Random.Range(0f, 3f); } internal static void Tick() { GameNetworkManager instance = GameNetworkManager.Instance; StartOfRound instance2 = StartOfRound.Instance; PlayerControllerB val = (((Object)(object)instance != (Object)null) ? instance.localPlayerController : null); if ((Object)(object)instance2 == (Object)null || (Object)(object)val == (Object)null) { return; } if (HolderField == null) { if (!warnedField) { warnedField = true; Plugin.Logger.LogWarning((object)(Clock.Stamp() + " [auto] WalkieTalkie.previousPlayerHeldBy was not found (game changed?). Automatic transmit is off; the walkie must be used by hand.")); } return; } int num = 0; PlayerControllerB[] allPlayerScripts = instance2.allPlayerScripts; foreach (PlayerControllerB val2 in allPlayerScripts) { if ((Object)(object)val2 != (Object)null && (val2.isPlayerControlled || val2.isPlayerDead)) { num++; } } WalkieTalkie val3 = (val.isPlayerDead ? null : FindPoweredWalkie(val)); bool flag = (Object)(object)val3 != (Object)null; float unscaledTime = Time.unscaledTime; if (flag != lastDesired) { lastDesired = flag; desiredSince = unscaledTime; } bool flag2 = unscaledTime - desiredSince >= 0.3f; bool shipHasLanded = instance2.shipHasLanded; if (lastLanded.HasValue && lastLanded.Value != shipHasLanded) { BeginSchedule(ShipSchedule, sendSoon: true); Plugin.Logger.LogInfo((object)string.Format("{0} [auto] ship {1}; transmit state will be re-sent over the next {2:F0}s", Clock.Stamp(), shipHasLanded ? "landed" : "left", Total(ShipSchedule))); } lastLanded = shipHasLanded; if (lastPlayers >= 0 && num > lastPlayers) { BeginSchedule(JoinSchedule, sendSoon: true); Plugin.Logger.LogInfo((object)$"{Clock.Stamp()} [auto] player count changed ({lastPlayers} -> {num}); transmit state will be re-sent over the next {Total(JoinSchedule):F0}s so the new player sees it"); } float unscaledTime2 = Time.unscaledTime; bool flag3 = num > 1; if ((Object)(object)val3 != (Object)null) { if (!val.holdingWalkieTalkie) { val.holdingWalkieTalkie = true; } bool flag4 = on && !val.speakingToWalkieTalkie; if (!on || flag4) { bool flag5 = true; if (flag4) { if (flagResendAt < 0f) { flagResendAt = unscaledTime2 + Random.Range(0.1f, 1.5f); } flag5 = unscaledTime2 >= flagResendAt; } if (flag5 && (flag4 || flag2) && StateSendAllowed(unscaledTime2)) { flagResendAt = -1f; SendResult sendResult = Send(speaking: true, val3, val, on); if (sendResult != SendResult.Skipped) { NoteStateSend(unscaledTime2); } if (sendResult == SendResult.Sent) { BeginSchedule(ChangeSchedule, sendSoon: false); nextAnnounce = unscaledTime2 + NextDelay(); } } } else { flagResendAt = -1f; if (flag3 && unscaledTime2 >= nextAnnounce) { Announce(speaking: true, val3, val); nextAnnounce = unscaledTime2 + NextDelay(); } } } else { flagResendAt = -1f; if (on) { if (flag2 && StateSendAllowed(unscaledTime2)) { SendResult sendResult2 = Send(speaking: false, FindCarrier(val), val, resend: false); if (sendResult2 != SendResult.Skipped) { NoteStateSend(unscaledTime2); } if (sendResult2 == SendResult.Sent) { BeginSchedule(ChangeSchedule, sendSoon: false); nextAnnounce = unscaledTime2 + NextDelay(); } } } else if (flag3 && everTransmitted && unscaledTime2 >= nextAnnounce) { Announce(speaking: false, FindCarrier(val), val); nextAnnounce = unscaledTime2 + NextDelay(); } } lastPlayers = num; } private static void Announce(bool speaking, WalkieTalkie? carrier, PlayerControllerB local) { if ((Object)(object)carrier == (Object)null || !((NetworkBehaviour)carrier).IsOwner) { return; } try { int num = (int)local.playerClientId; if (speaking) { carrier.SetPlayerSpeakingOnWalkieTalkieServerRpc(num); } else { carrier.UnsetPlayerSpeakingOnWalkieTalkieServerRpc(num); } } catch (Exception ex) { if (!warnedAnnounce) { warnedAnnounce = true; Plugin.Logger.LogWarning((object)(Clock.Stamp() + " [auto] could not re-send the transmit state (" + ex.Message + "); other clients that missed the first message will not catch up")); } } } private static WalkieTalkie? FindCarrier(PlayerControllerB local) { List<WalkieTalkie> allWalkieTalkies = WalkieTalkie.allWalkieTalkies; if (allWalkieTalkies == null) { return null; } WalkieTalkie val = null; for (int i = 0; i < allWalkieTalkies.Count; i++) { WalkieTalkie val2 = allWalkieTalkies[i]; if (!((Object)(object)val2 == (Object)null) && ((NetworkBehaviour)val2).IsOwner) { if ((Object)(object)((GrabbableObject)val2).playerHeldBy == (Object)(object)local) { return val2; } if (val == null) { val = val2; } } } return val; } private static SendResult Send(bool speaking, WalkieTalkie? carrier, PlayerControllerB local, bool resend) { if ((Object)(object)carrier == (Object)null || !((NetworkBehaviour)carrier).IsOwner) { if (speaking && !warnedOwner) { warnedOwner = true; Plugin.Logger.LogWarning((object)(Clock.Stamp() + " [auto] this client does not own its walkie, so it cannot start transmitting yet (will retry)")); } if (!speaking) { local.speakingToWalkieTalkie = false; on = false; if (!Routing.LobbyClosing()) { Plugin.Logger.LogWarning((object)(Clock.Stamp() + " [auto] no walkie to send the stop message through; cleared the flag locally only")); } } return SendResult.Skipped; } warnedOwner = false; try { HolderField.SetValue(carrier, local); if (resend || (speaking && local.speakingToWalkieTalkie)) { local.speakingToWalkieTalkie = !speaking; } sending = true; carrier.SetLocalClientSpeaking(speaking); } catch (Exception ex) { if (!warnedSend) { warnedSend = true; Plugin.Logger.LogWarning((object)(Clock.Stamp() + " [auto] could not send the transmit state (" + ex.Message + "); will retry")); } return SendResult.Failed; } finally { sending = false; } if (on != speaking) { Plugin.Logger.LogInfo((object)(Clock.Stamp() + " [auto] " + (speaking ? "now transmitting (powered walkie carried)" : "stopped transmitting (no powered walkie)"))); } on = speaking; if (speaking) { everTransmitted = true; } return SendResult.Sent; } } internal static class Clock { private static bool? lastWasNetwork; internal static string Stamp() { //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) NetworkManager singleton = NetworkManager.Singleton; bool flag = (Object)(object)singleton != (Object)null && singleton.IsListening; if (lastWasNetwork != flag) { lastWasNetwork = flag; Plugin.Debug(flag ? "[clock] log lines are now stamped [S...] with the network's server time (comparable across players' logs)" : "[clock] log lines are stamped [L...] with this machine's local time (not comparable across players' logs)"); } if (!flag) { return $"[L{Time.realtimeSinceStartupAsDouble:F2}]"; } NetworkTime serverTime = singleton.ServerTime; return $"[S{((NetworkTime)(ref serverTime)).Time:F2}]"; } } internal static class Driver { private static int lastUpdateFrame = -1; private static int lastLateFrame = -1; private static int lastRepaintFrame = -1; private static bool guiFailed; internal static void Late() { int frameCount = Time.frameCount; if (frameCount == lastLateFrame) { return; } lastLateFrame = frameCount; try { Routing.Apply(); } catch (Exception e) { Plugin.ReportFailure("Applying voice routing (late)", e); } try { Spectator.Apply(Time.unscaledDeltaTime); } catch (Exception e2) { Plugin.ReportFailure("Spectator volume", e2); Spectator.Abort(); } } internal static void Tick() { int frameCount = Time.frameCount; if (frameCount != lastUpdateFrame) { lastUpdateFrame = frameCount; Plugin.PerFrame(Time.unscaledDeltaTime); } } internal static void Draw() { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Invalid comparison between Unknown and I4 Event current = Event.current; if (current == null || (int)current.type != 7) { return; } int frameCount = Time.frameCount; if (frameCount == lastRepaintFrame) { return; } lastRepaintFrame = frameCount; if (guiFailed) { return; } try { VoiceHud.Draw(); } catch (Exception arg) { guiFailed = true; Plugin.Logger.LogError((object)$"HUD drawing failed, disabling it: {arg}"); } } } [DefaultExecutionOrder(32000)] internal sealed class Runner : MonoBehaviour { private static Runner? instance; private static bool quitting; internal static bool Lost; internal static void Create() { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Expected O, but got Unknown if ((Object)(object)instance != (Object)null) { return; } if (!quitting) { Application.quitting += delegate { quitting = true; }; } GameObject val = new GameObject("BetterVC.Runner"); ((Object)val).hideFlags = (HideFlags)61; Object.DontDestroyOnLoad((Object)(object)val); instance = val.AddComponent<Runner>(); val.AddComponent<EarlyRunner>(); } private void Update() { Driver.Tick(); } private void LateUpdate() { Driver.Late(); } private void OnGUI() { Driver.Draw(); } private void OnDestroy() { instance = null; if (!quitting) { Plugin.Logger.LogWarning((object)"[driver] the Runner object was destroyed by something (it will be recreated)"); Lost = true; } } } [DefaultExecutionOrder(-32000)] internal sealed class EarlyRunner : MonoBehaviour { private void Update() { try { Spectator.Restore(); } catch (Exception e) { Plugin.ReportFailure("Spectator volume (restore)", e); Spectator.Abort(); } } } internal static class FocusAudio { private const float RampSeconds = 0.15f; private static float factor = 1f; private static bool lastMute; internal static bool Active => factor < 1f; internal static float ListenerFactor { get { if (!UsesListener()) { return 1f; } return factor; } } internal static float SourceFactor { get { if (!UsesListener()) { return factor; } return 1f; } } internal static void Step(float dt) { bool flag = Plugin.OutOfFocusAudioBehavior.Value != OutOfFocusAudio.Off && !Application.isFocused; factor = Mathf.MoveTowards(factor, flag ? 0f : 1f, dt / 0.15f); if (flag != lastMute) { lastMute = flag; if (flag) { Plugin.Logger.LogInfo((object)string.Format("{0} [focus] window lost focus: muting ({1}, {2})", Clock.Stamp(), Plugin.OutOfFocusAudioBehavior.Value, UsesListener() ? "whole mix" : "per source")); return; } Plugin.Logger.LogInfo((object)$"{Clock.Stamp()} [focus] window back in front: unmuting (the volume was rewritten by the game or a mod {Spectator.ListenerRewrites} time(s) while muted)"); Spectator.ListenerRewrites = 0; } } internal static void Reset() { factor = 1f; } private static bool Spectating() { PlayerControllerB local = Routing.GetLocal(); if ((Object)(object)local != (Object)null) { return local.isPlayerDead; } return false; } private static bool UsesListener() { return Plugin.OutOfFocusAudioBehavior.Value switch { OutOfFocusAudio.MuteAll => true, OutOfFocusAudio.MuteAllButSpectators => !Spectating(), _ => false, }; } internal static void CollectExempt(HashSet<AudioSource> into) { OutOfFocusAudio value = Plugin.OutOfFocusAudioBehavior.Value; if (value == OutOfFocusAudio.Off || value == OutOfFocusAudio.MuteAll) { return; } StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance == (Object)null) { return; } bool flag = Spectating(); if (value == OutOfFocusAudio.MuteAllButSpectators && !flag) { return; } PlayerControllerB local = Routing.GetLocal(); PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts; foreach (PlayerControllerB val in allPlayerScripts) { if (!((Object)(object)val == (Object)null) && !((Object)(object)val == (Object)(object)local) && (value != OutOfFocusAudio.MuteAllButSpectators || val.isPlayerDead)) { AudioSource currentVoiceChatAudioSource = val.currentVoiceChatAudioSource; if ((Object)(object)currentVoiceChatAudioSource != (Object)null) { into.Add(currentVoiceChatAudioSource); } } } } } internal static class LitWalkieScreenData { internal const int IconSize = 256; internal const int OffsetX = 116; internal const int OffsetY = 115; internal const int Width = 46; internal const int Height = 32; internal const string Png = "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"; } internal static class NearbySounds { private enum Kind { None, Centered, Speaker } private struct Route { public Kind Kind; public Transform? Speaker; public float Gain; } private struct Hit { public Route Route; public float Volume; } private sealed class Copy { public GameObject Object; public AudioSource Source; public AudioLowPassFilter Low; public AudioHighPassFilter High; } private const float HangSeconds = 0.6f; private const float SyncDrift = 0.15f; private const float DropBelow = 0.0005f; private const float HighPassCap = 250f; private const float LogEvery = 15f; private const int MaxLogLines = 40; private static FieldRef<WalkieTalkie, List<AudioSource>>? toReplay; private static FieldRef<WalkieTalkie, float>? recordingRange; private static FieldRef<WalkieTalkie, float>? maxVolume; private static bool resolved; private static bool available; private static GameObject? root; private static Copy? shotCentered; private static Copy? shotSpeaker; private static readonly Dictionary<AudioSource, Copy> Copies = new Dictionary<AudioSource, Copy>(); private static readonly Dictionary<AudioSource, Hit> Best = new Dictionary<AudioSource, Hit>(); private static readonly HashSet<AudioSource> VoiceSources = new HashSet<AudioSource>(); private static readonly List<AudioSource> Forget = new List<AudioSource>(); private static readonly Dictionary<ulong, float> LastSpoke = new Dictionary<ulong, float>(); private static int seenShots; private static int playedShots; private static int noTransmitter; private static int outOfRange; private static int notOnRadio; private static float nextSummary; private static int summaryLines; private static bool patchesLogged; internal static bool Available { get { if (resolved) { return available; } resolved = true; try { toReplay = AccessTools.FieldRefAccess<WalkieTalkie, List<AudioSource>>("audioSourcesToReplay"); recordingRange = AccessTools.FieldRefAccess<WalkieTalkie, float>("recordingRange"); maxVolume = AccessTools.FieldRefAccess<WalkieTalkie, float>("maxVolume"); available = true; } catch (Exception ex) { Plugin.Logger.LogWarning((object)("[nearby] could not read the walkie's relay fields (" + ex.Message + "); the base game's relay is left as it is")); } return available; } } private static bool Transmitting(WalkieTalkie walkie, out PlayerControllerB holder) { holder = ((GrabbableObject)walkie).playerHeldBy; if ((Object)(object)holder == (Object)null || !walkie.clientIsHoldingAndSpeakingIntoThis || !((GrabbableObject)walkie).isBeingUsed) { return false; } float unscaledTime = Time.unscaledTime; if (IsTalkingNow(holder)) { LastSpoke[holder.playerClientId] = unscaledTime; } if (LastSpoke.TryGetValue(holder.playerClientId, out var value)) { return unscaledTime - value < 0.6f; } return false; } private static bool IsTalkingNow(PlayerControllerB player) { StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance == (Object)null) { return false; } if ((Object)(object)player == (Object)(object)Routing.GetLocal()) { DissonanceComms voiceChatModule = instance.voiceChatModule; if ((Object)(object)voiceChatModule == (Object)null || voiceChatModule.IsMuted) { return false; } VoicePlayerState val = voiceChatModule.FindPlayer(voiceChatModule.LocalPlayerName); if (val != null && val.IsSpeaking) { return val.Amplitude > 0.002f; } return false; } return VoiceHud.IsHeardTalking(player); } private static float VoiceGain(PlayerControllerB player) { float[] array = (((Object)(object)SoundManager.Instance != (Object)null) ? SoundManager.Instance.playerVoiceVolumes : null); if (array == null || player.playerClientId >= (ulong)array.Length) { return 1f; } float num = array[player.playerClientId]; if (num <= -60f) { return 0f; } return Mathf.Clamp01(Mathf.Pow(10f, 0.8f * (Mathf.Min(num, 1f) - 1f))); } private static Route RouteFor(PlayerControllerB holder, PlayerControllerB listener, bool ownWalkie, Transform? speaker) { Route result = new Route { Kind = Kind.None }; if ((Object)(object)holder == (Object)(object)listener) { return result; } VoicePlayerState voicePlayerState = holder.voicePlayerState; if (voicePlayerState != null && voicePlayerState.IsLocallyMuted) { return result; } if (VoiceHud.IsSliderMuted(holder)) { return result; } if (!Routing.TryGetLinked(holder, out var onRadio) || !onRadio) { return result; } float num = VoiceGain(holder); if (num <= 0.001f) { return result; } if (!ownWalkie && (Object)(object)speaker != (Object)null) { return new Route { Kind = Kind.Speaker, Speaker = speaker, Gain = num }; } return new Route { Kind = Kind.Centered, Gain = num }; } internal static void OneShot(AudioSource audioSource, AudioClip clip, float volume) { //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) float num = Mathf.Clamp01(Plugin.NearbySoundsVolume.Value); List<WalkieTalkie> allWalkieTalkies = WalkieTalkie.allWalkieTalkies; PlayerControllerB val = Routing.CurrentListener(); if (num <= 0.001f || (Object)(object)clip == (Object)null || (Object)(object)audioSource == (Object)null || allWalkieTalkies == null || (Object)(object)val == (Object)null || val.isPlayerDead) { return; } bool flag = AutoTransmit.HasPoweredWalkie(val); Transform speaker = (flag ? null : Routing.FindSpeaker(val)); seenShots++; bool flag2 = false; bool flag3 = false; Hit hit = default(Hit); for (int i = 0; i < allWalkieTalkies.Count; i++) { WalkieTalkie val2 = allWalkieTalkies[i]; if ((Object)(object)val2 == (Object)null || !Transmitting(val2, out PlayerControllerB holder)) { continue; } flag2 = true; float num2 = recordingRange.Invoke(val2); float num3 = Vector3.Distance(((Component)val2).transform.position, ((Component)audioSource).transform.position); if (!(num3 < num2)) { continue; } flag3 = true; Route route = RouteFor(holder, val, flag, speaker); if (route.Kind != Kind.None) { float num4 = Mathf.Lerp(maxVolume.Invoke(val2), 0f, num3 / (num2 + 3f)) * volume * num * route.Gain; if (num4 > hit.Volume) { hit = new Hit { Route = route, Volume = num4 }; } } } if (hit.Volume <= 0.0005f) { if (!flag2) { noTransmitter++; } else if (!flag3) { outOfRange++; } else { notOnRadio++; } } else { playedShots++; Copy copy = ((hit.Route.Kind == Kind.Speaker) ? (shotSpeaker ?? (shotSpeaker = NewCopy("one-shot (speaker)"))) : (shotCentered ?? (shotCentered = NewCopy("one-shot (centered)")))); Configure(copy, hit.Route); copy.Source.PlayOneShot(clip, Mathf.Clamp01(hit.Volume)); } } internal static void Tick() { //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) if (!Available) { return; } LogPatchOwners(); LogSummary(); List<WalkieTalkie> allWalkieTalkies = WalkieTalkie.allWalkieTalkies; PlayerControllerB val = Routing.CurrentListener(); float num = Mathf.Clamp01(Plugin.NearbySoundsVolume.Value); bool flag = allWalkieTalkies != null && (Object)(object)val != (Object)null && !val.isPlayerDead && num > 0.001f; Best.Clear(); if (allWalkieTalkies != null) { bool flag2 = false; Transform speaker = null; if (flag) { flag2 = AutoTransmit.HasPoweredWalkie(val); speaker = (flag2 ? null : Routing.FindSpeaker(val)); CollectVoiceSources(); } for (int i = 0; i < allWalkieTalkies.Count; i++) { WalkieTalkie val2 = allWalkieTalkies[i]; if ((Object)(object)val2 == (Object)null) { continue; } List<AudioSource> list = toReplay.Invoke(val2); float num2 = recordingRange.Invoke(val2); Prune(list, val2, num2); if (!flag || list.Count == 0 || !Transmitting(val2, out PlayerControllerB holder)) { continue; } Route route = RouteFor(holder, val, flag2, speaker); if (route.Kind == Kind.None) { continue; } float num3 = maxVolume.Invoke(val2); for (int j = 0; j < list.Count; j++) { AudioSource val3 = list[j]; if (!((Object)(object)val3 == (Object)null) && !VoiceSources.Contains(val3)) { float num4 = Vector3.Distance(((Component)val3).transform.position, ((Component)val2).transform.position); float num5 = Mathf.Lerp(num3, 0f, num4 / (num2 + 3f)) * num * route.Gain; if (!(num5 <= 0.0005f) && (!Best.TryGetValue(val3, out var value) || num5 > value.Volume)) { Best[val3] = new Hit { Route = route, Volume = num5 }; } } } } } Forget.Clear(); foreach (KeyValuePair<AudioSource, Copy> copy in Copies) { if ((Object)(object)copy.Key == (Object)null || !Best.ContainsKey(copy.Key)) { Forget.Add(copy.Key); } } for (int k = 0; k < Forget.Count; k++) { Discard(Forget[k]); } Forget.Clear(); foreach (KeyValuePair<AudioSource, Hit> item in Best) { AudioSource key = item.Key; if (!Copies.TryGetValue(key, out Copy value2)) { value2 = NewCopy("copy"); Copies[key] = value2; } Configure(value2, item.Value.Route); value2.Source.volume = Mathf.Clamp01(item.Value.Volume); Follow(key, value2.Source); } } private static void Follow(AudioSource original, AudioSource copy) { AudioClip clip = original.clip; bool flag = (Object)(object)clip != (Object)null && original.isPlaying && ((Component)original).gameObject.activeInHierarchy; if ((Object)(object)clip == (Object)null) { return; } if ((Object)(object)copy.clip != (Object)(object)clip) { copy.clip = clip; if (flag) { copy.time = ClampTime(original.time, clip); copy.Play(); } } else if (flag) { if (!copy.isPlaying) { copy.time = ClampTime(original.time, clip); copy.Play(); } else if (Mathf.Abs(copy.time - original.time) > 0.15f) { copy.time = ClampTime(original.time, clip); } } else if (copy.isPlaying) { copy.Stop(); } } private static float ClampTime(float time, AudioClip clip) { return Mathf.Clamp(time, 0f, Mathf.Max(0f, clip.length - 0.01f)); } private static void Prune(List<AudioSource> sources, WalkieTalkie walkie, float range) { //IL_0022: 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) for (int num = sources.Count - 1; num >= 0; num--) { AudioSource val = sources[num]; if ((Object)(object)val == (Object)null || Vector3.Distance(((Component)val).transform.position, ((Component)walkie).transform.position) > range + 7f) { sources.RemoveAt(num); } } } private static void CollectVoiceSources() { VoiceSources.Clear(); StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance == (Object)null) { return; } PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts; foreach (PlayerControllerB val in allPlayerScripts) { AudioSource val2 = (((Object)(object)val != (Object)null) ? val.currentVoiceChatAudioSource : null); if ((Object)(object)val2 != (Object)null) { VoiceSources.Add(val2); } } } private static void LogPatchOwners() { if (patchesLogged) { return; } patchesLogged = true; string[] array = new string[3] { "TransmitOneShotAudio", "TimeAllAudioSources", "GetAllAudioSourcesToReplay" }; foreach (string text in array) { MethodBase methodBase = AccessTools.Method(typeof(WalkieTalkie), text, (Type[])null, (Type[])null); Patches val = ((methodBase != null) ? Harmony.GetPatchInfo(methodBase) : null); if (val != null) { Plugin.Logger.LogInfo((object)("[nearby] " + text + ": prefixes [" + Owners(val.Prefixes) + "], postfixes [" + Owners(val.Postfixes) + "], transpilers [" + Owners(val.Transpilers) + "]")); } } static string Owners(IEnumerable<Patch> patches) { return string.Join(", ", patches.Select((Patch p) => $"{p.owner} (priority {p.priority})")); } } private static void LogSummary() { float unscaledTime = Time.unscaledTime; if (!(unscaledTime < nextSummary)) { nextSummary = unscaledTime + 15f; if (seenShots != 0 && summaryLines < 40) { summaryLines++; Plugin.Logger.LogInfo((object)$"{Clock.Stamp()} [nearby] last {15f:F0}s: {seenShots} one-shot sounds, {playedShots} passed on; not passed on: no player transmitting and talking {noTransmitter}, out of range of the walkie {outOfRange}, heard in person or muted or not linked {notOnRadio}; {Copies.Count} continuous copies"); seenShots = (playedShots = (noTransmitter = (outOfRange = (notOnRadio = 0)))); } } } private static Copy NewCopy(string name) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Expected O, but got Unknown //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown if ((Object)(object)root == (Object)null) { root = new GameObject("BetterVC nearby sounds"); Object.DontDestroyOnLoad((Object)(object)root); } GameObject val = new GameObject(name); val.transform.SetParent(root.transform, false); AudioSource val2 = val.AddComponent<AudioSource>(); val2.playOnAwake = false; val2.loop = false; val2.dopplerLevel = 0f; val2.spatialize = false; val2.rolloffMode = (AudioRolloffMode)1; val2.minDistance = 1f; val2.maxDistance = Mathf.Max(5f, AlwaysHearActiveWalkies.AudibleDistance); return new Copy { Object = val, Source = val2, Low = val.AddComponent<AudioLowPassFilter>(), High = val.AddComponent<AudioHighPassFilter>() }; } private static void Configure(Copy copy, Route route) { //IL_006e: Unknown result type (might be due to invalid IL or missing references) float num = Mathf.Clamp01(Plugin.RadioEffectStrength.Value); if (route.Kind == Kind.Speaker && (Object)(object)route.Speaker != (Object)null) { num = Mathf.Max(num, Mathf.Clamp01(Plugin.SpeakerEffectStrength.Value)); copy.Source.spatialBlend = 1f; copy.Source.panStereo = 0f; copy.Object.transform.position = route.Speaker.position; } else { copy.Source.spatialBlend = 0f; copy.Source.panStereo = 0f; } Routing.RadioFilter(num, out var highPassHz, out var lowPassHz, out var resonanceQ); highPassHz = Mathf.Min(highPassHz, 250f); if (!((Behaviour)copy.High).enabled) { ((Behaviour)copy.High).enabled = true; } if (!((Behaviour)copy.Low).enabled) { ((Behaviour)copy.Low).enabled = true; } if (Mathf.Abs(copy.High.cutoffFrequency - highPassHz) > 0.5f) { copy.High.cutoffFrequency = highPassHz; } if (Mathf.Abs(copy.Low.cutoffFrequency - lowPassHz) > 0.5f) { copy.Low.cutoffFrequency = lowPassHz; } if (Mathf.Abs(copy.Low.lowpassResonanceQ - resonanceQ) > 0.01f) { copy.Low.lowpassResonanceQ = resonanceQ; } } private static void Discard(AudioSource original) { if (Copies.TryGetValue(original, out Copy value)) { Copies.Remove(original); if ((Object)(object)value.Object != (Object)null) { Object.Destroy((Object)(object)value.Object); } } } internal static void Reset() { foreach (Copy value in Copies.Values) { if ((Object)(object)value.Object != (Object)null) { Object.Destroy((Object)(object)value.Object); } } Copies.Clear(); Best.Clear(); LastSpoke.Clear(); VoiceSources.Clear(); if ((Object)(object)root != (Object)null) { Object.Destroy((Object)(object)root); } root = null; shotCentered = null; shotSpeaker = null; } } internal static class Routing { private sealed class VoiceParts { public AudioSource Source; public AudioLowPassFilter LowPass; public AudioHighPassFilter HighPass; public OccludeAudio Occlude; } private const float PollInterval = 0.25f; private const float VoiceRefreshCooldown = 3f; private const float RadioLowPass = 4000f; private const float RadioQ = 3f; private const float OpenLowPass = 22000f; private const float EdgeMargin = 0.5f; private static readonly Dictionary<ulong, bool> Linked = new Dictionary<ulong, bool>(); private static readonly Dictionary<ulong, float> HighPassDefaults = new Dictionary<ulong, float>(); private static float pollTimer; private static float nextVoiceRefreshAllowed; private static readonly Dictionary<ulong, int> RefreshTries = new Dictionary<ulong, int>(); private static readonly Dictionary<ulong, float> RefreshNext = new Dictionary<ulong, float>(); private static StartOfRound? knownRound; private static readonly Dictionary<ulong, VoiceParts> PartsCache = new Dictionary<ulong, VoiceParts>(); internal static float MinimumDistance => Plugin.MinimumDistance.Value; internal static bool PositionalRadioActive { get; private set; } internal static PlayerControllerB? GetLocal() { GameNetworkManager instance = GameNetworkManager.Instance; if (!((Object)(object)instance != (Object)null)) { return null; } return instance.localPlayerController; } internal static bool LobbyClosing() { GameNetworkManager instance = GameNetworkManager.Instance; if ((Object)(object)instance != (Object)null && instance.isDisconnecting) { return true; } NetworkManager singleton = NetworkManager.Singleton; if (!((Object)(object)singleton == (Object)null)) { return !singleton.IsListening; } return true; } internal static PlayerControllerB? CurrentListener() { PlayerControllerB local = GetLocal(); if ((Object)(object)local == (Object)null) { return null; } if (!local.isPlayerDead || !((Object)(object)local.spectatedPlayerScript != (Object)null)) { return local; } return local.spectatedPlayerScript; } internal static bool TryGetLinked(PlayerControllerB p, out bool onRadio) { return Linked.TryGetValue(p.playerClientId, out onRadio); } internal static void ResetIfNewLobby() { StartOfRound val = (((Object)(object)StartOfRound.Instance != (Object)null) ? StartOfRound.Instance : null); if (val != knownRound) { bool flag = knownRound != null; knownRound = val; if (flag) { Linked.Clear(); HighPassDefaults.Clear(); PartsCache.Clear(); RefreshNext.Clear(); nextVoiceRefreshAllowed = 0f; pollTimer = 0f; AutoTransmit.Reset(); NearbySounds.Reset(); MoreScreams.Reset(); Spectator.Reset(); VoiceHealth.Reset(); WalkieSync.Reset(); VoiceHud.Reset(); Plugin.Logger.LogInfo((object)(Clock.Stamp() + " [lobby] lobby changed: routing state cleared")); } } } internal static void Tick(float dt) { pollTimer += dt; if (!(pollTimer < 0.25f)) { pollTimer = 0f; try { AutoTransmit.Tick(); } catch (Exception e) { Plugin.ReportFailure("Automatic transmit", e); } if (Evaluate()) { StartOfRound.Instance.UpdatePlayerVoiceEffects(); } } } internal static bool Evaluate() { //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) StartOfRound instance = StartOfRound.Instance; PlayerControllerB local = GetLocal(); if ((Object)(object)instance == (Object)null || (Object)(object)local == (Object)null) { return false; } PlayerControllerB val = CurrentListener() ?? local; bool flag = !val.isPlayerDead && (AutoTransmit.HasPoweredWalkie(val) || val.holdingWalkieTalkie); float minimumDistance = MinimumDistance; bool result = false; PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts; foreach (PlayerControllerB val2 in allPlayerScripts) { if ((Object)(object)val2 == (Object)null || (Object)(object)val2 == (Object)(object)local) { continue; } ulong playerClientId = val2.playerClientId; if (val2.isPlayerControlled || val2.isPlayerDead) { CheckVoiceObjects(val2); } else { ClearEmptySlot(val2); } bool flag2 = flag && (Object)(object)val2 != (Object)(object)val && IsRoutable(val2); bool value; bool flag3 = Linked.TryGetValue(playerClientId, out value); if (!flag2) { if (flag3) { Linked.Remove(playerClientId); result = true; Plugin.Logger.LogInfo((object)$"{Clock.Stamp()} [route] {val2.playerUsername} (#{playerClientId}): no longer linked (back to the base game)"); } continue; } float num = Vector3.Distance(((Component)val).transform.position, ((Component)val2).transform.position); bool flag4 = ((flag3 && value) ? (num >= minimumDistance - 0.5f) : (num > minimumDistance + 0.5f)) && val2.speakingToWalkieTalkie; if (!flag3 || value != flag4) { Linked[playerClientId] = flag4; result = true; Plugin.Logger.LogInfo((object)string.Format("{0} [route] {1} (#{2}): {3} {4} (dist={5:F1}m)", Clock.Stamp(), val2.playerUsername, playerClientId, flag3 ? "now" : "linked, starting", flag4 ? "on the radio" : "in person", num)); } } return result; } private static bool IsRoutable(PlayerControllerB p) { if (!p.isPlayerControlled || p.isPlayerDead) { return false; } if (p.voicePlayerState == null || (Object)(object)p.currentVoiceChatAudioSource == (Object)null || (Object)(object)p.currentVoiceChatIngameSettings == (Object)null) { return false; } if (p.currentVoiceChatIngameSettings._playerState != p.voicePlayerState) { return false; } try { return p.voicePlayerState.IsConnected; } catch (Exception) { return false; } } private static void CheckVoiceObjects(PlayerControllerB p) { PlayerVoiceIngameSettings currentVoiceChatIngameSettings = p.currentVoiceChatIngameSettings; if ((Object)(object)currentVoiceChatIngameSettings == (Object)null || p.voicePlayerState == null || LobbyClosing()) { return; } ulong playerClientId = p.playerClientId; if (currentVoiceChatIngameSettings._playerState == p.voicePlayerState) { if (RefreshTries.Count > 0) { RefreshTries.Remove(playerClientId); RefreshNext.Remove(playerClientId); } return; } float unscaledTime = Time.unscaledTime; if (!(unscaledTime < nextVoiceRefreshAllowed) && (!RefreshNext.TryGetValue(playerClientId, out var value) || !(unscaledTime < value))) { RefreshTries.TryGetValue(playerClientId, out var value2); RefreshTries[playerClientId] = value2 + 1; RefreshNext[playerClientId] = unscaledTime + Mathf.Min(3f * (float)(1 << Mathf.Min(value2, 5)), 60f); nextVoiceRefreshAllowed = unscaledTime + 3f; StartOfRound.Instance.RefreshPlayerVoicePlaybackObjects(); if (value2 < 3) { Plugin.Logger.LogInfo((object)$"{Clock.Stamp()} [voice] {p.playerUsername} (#{p.playerClientId}): voice state did not match the audio source (a rejoin leaves a stale one); asked the game to rebuild its voice objects"); } else if (value2 == 3) { Plugin.Logger.LogInfo((object)$"{Clock.Stamp()} [voice] {p.playerUsername} (#{p.playerClientId}): voice state still does not match after {value2} rebuilds; asking less and less often"); } } } private static void ClearEmptySlot(PlayerControllerB p) { if (p.holdingWalkieTalkie) { p.holdingWalkieTalkie = false; } if (p.speakingToWalkieTalkie) { p.speakingToWalkieTalkie = false; TransmitSfx.Forget((int)p.playerClientId); } } private static VoiceParts? GetParts(PlayerControllerB p) { AudioSource currentVoiceChatAudioSource = p.currentVoiceChatAudioSource; if (PartsCache.TryGetValue(p.playerClientId, out VoiceParts value) && (Object)(object)value.Source == (Object)(object)currentVoiceChatAudioSource && (Object)(object)value.LowPass != (Object)null && (Object)(object)value.HighPass != (Object)null && (Object)(object)value.Occlude != (Object)null) { return value; } AudioLowPassFilter component = ((Component)currentVoiceChatAudioSource).GetComponent<AudioLowPassFilter>(); AudioHighPassFilter component2 = ((Component)currentVoiceChatAudioSource).GetComponent<AudioHighPassFilter>(); OccludeAudio component3 = ((Component)currentVoiceChatAudioSource).GetComponent<OccludeAudio>(); if ((Object)(object)component == (Object)null || (Object)(object)component2 == (Object)null || (Object)(object)component3 == (Object)null) { return null; } VoiceParts voiceParts = new VoiceParts { Source = currentVoiceChatAudioSource, LowPass = component, HighPass = component2, Occlude = component3 }; PartsCache[p.playerClientId] = voiceParts; return voiceParts; } internal static void Apply() { PositionalRadioActive = false; if (Linked.Count == 0) { return; } StartOfRound instance = StartOfRound.Instance; PlayerControllerB val = CurrentListener(); if ((Object)(object)instance == (Object)null || (Object)(object)val == (Object)null || val.isPlayerDead) { return; } Transform speaker = null; bool flag = false; bool flag2 = false; PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts; foreach (PlayerControllerB val2 in allPlayerScripts) { if ((Object)(object)val2 == (Object)null || !Linked.TryGetValue(val2.playerClientId, out var value) || !IsRoutable(val2)) { continue; } try { VoiceParts parts = GetParts(val2); if (parts == null) { continue; } if (value) { if (!flag) { flag = true; flag2 = AutoTransmit.HasPoweredWalkie(val); speaker = (flag2 ? null : FindSpeaker(val)); } ApplyRadio(val2, parts, speaker, !flag2); } else { ApplyInPerson(val2, parts); } } catch (Exception e) { Plugin.ReportFailure("Applying voice routing to " + val2.playerUsername, e); } } } internal static Transform? FindSpeaker(PlayerControllerB local) { //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_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) List<WalkieTalkie> allWalkieTalkies = WalkieTalkie.allWalkieTalkies; if (allWalkieTalkies == null) { return null; } Vector3 position = ((Component)local).transform.position; float audibleDistance = AlwaysHearActiveWalkies.AudibleDistance; Transform result = null; float num = audibleDistance * audibleDistance; for (int i = 0; i < allWalkieTalkies.Count; i++) { WalkieTalkie val = allWalkieTalkies[i]; if (!((Object)(object)val == (Object)null) && ((GrabbableObject)val).isBeingUsed && !((Object)(object)((GrabbableObject)val).playerHeldBy == (Object)(object)local)) { Vector3 val2 = ((Component)val).transform.position - position; float sqrMagnitude = ((Vector3)(ref val2)).sqrMagnitude; if (!(sqrMagnitude > num)) { num = sqrMagnitude; result = ((Component)val).transform; } } } return result; } internal static void RadioFilter(float strength, out float highPassHz, out float lowPassHz, out float resonanceQ) { float num = Mathf.Clamp01(strength); float num2 = 600f; using (Dictionary<ulong, float>.ValueCollection.Enumerator enumerator = HighPassDefaults.Values.GetEnumerator()) { if (enumerator.MoveNext()) { float current = enumerator.Current; num2 = current; } } highPassHz = Mathf.Clamp(LogLerp(10f, Mathf.Max(10f, num2), Mathf.Pow(num, 0.6f)), 10f, 5000f); lowPassHz = Mathf.Clamp(LogLerp(22000f, 4000f, num), 300f, 22000f); resonanceQ = Mathf.Clamp(Mathf.Lerp(1f, 3f, num * num * num), 1f, 10f); } private static void SetEnabled(Behaviour b, bool value) { if (b.enabled != value) { b.enabled = value; } } private static void SetFloat(float current, float value, Action<float> write) { if (Mathf.Abs(current - value) > 0.001f) { write(value); } } private static void ApplyInPerson(PlayerControllerB p, VoiceParts v) { SetEnabled((Behaviour)(object)v.LowPass, value: true); SetEnabled((Behaviour)(object)v.HighPass, value: false); if (v.Occlude.overridingLowPass != p.voiceMuffledByEnemy) { v.Occlude.overridingLowPass = p.voiceMuffledByEnemy; } SetFloat(v.LowPass.lowpassResonanceQ, 1f, delegate(float x) { v.LowPass.lowpassResonanceQ = x; }); if (p.currentVoiceChatIngameSettings.set2D) { p.currentVoiceChatIngameSettings.set2D = false; } SetFloat(v.Source.spatialBlend, 1f, delegate(float x) { v.Source.spatialBlend = x; }); SetFloat(v.Source.panStereo, 0f, delegate(float x) { v.Source.panStereo = x; }); PlayerControllerB local = GetLocal(); float value = (((Object)(object)local != (Object)null && local.isPlayerDead) ? 0.8f : 1f); SetFloat(p.voicePlayerState.Volume, value, delegate(float x) { p.voicePlayerState.Volume = x; }); } private static void ApplyRadio(PlayerControllerB p, VoiceParts v, Transform? speaker, bool listenerHasNoWalkie) { //IL_022d: Unknown result type (might be due to invalid IL or missing references) //IL_0232: Unknown result type (might be due to invalid IL or missing references) //IL_0244: Unknown result type (might be due to invalid IL or missing references) //IL_0249: Unknown result type (might be due to invalid IL or missing references) //IL_024b: Unknown result type (might be due to invalid IL or missing references) //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0270: Unknown result type (might be due to invalid IL or missing references) float num = Mathf.Clamp01(Plugin.RadioEffectStrength.Value); float num2 = Mathf.Clamp01(Plugin.WalkieVolume.Value); if (listenerHasNoWalkie) { num = Mathf.Max(num, Mathf.Clamp01(Plugin.SpeakerEffectStrength.Value)); num2 = Mathf.Min(num2, Mathf.Clamp01(Plugin.SpeakerVolume.Value)); } if (!HighPassDefaults.TryGetValue(p.playerClientId, out var value)) { value = v.HighPass.cutoffFrequency; HighPassDefaults[p.playerClientId] = value; } float value2 = Mathf.Clamp(LogLerp(10f, Mathf.Max(10f, value), Mathf.Pow(num, 0.6f)), 10f, 5000f); float value3 = Mathf.Clamp(LogLerp(22000f, 4000f, num), 300f, 22000f); SetEnabled((Behaviour)(object)v.LowPass, value: true); SetEnabled((Behaviour)(object)v.HighPass, value: true); SetFloat(v.HighPass.cutoffFrequency, value2, delegate(float x) { v.HighPass.cutoffFrequency = x; }); if (!v.Occlude.overridingLowPass) { v.Occlude.overridingLowPass = true; } if (!p.voiceMuffledByEnemy) { SetFloat(v.Occlude.lowPassOverride, value3, delegate(float x) { v.Occlude.lowPassOverride = x; }); } SetFloat(v.LowPass.lowpassResonanceQ, Mathf.Clamp(Mathf.Lerp(1f, 3f, num * num * num), 1f, 10f), delegate(float x) { v.LowPass.lowpassResonanceQ = x; }); if ((Object)(object)speaker != (Object)null) { PositionalRadioActive = true; if (p.currentVoiceChatIngameSettings.set2D) { p.currentVoiceChatIngameSettings.set2D = false; } SetFloat(v.Source.spatialBlend, 1f, delegate(float x) { v.Source.spatialBlend = x; }); Vector3 position = speaker.position; Vector3 val = ((Component)v.Source).transform.position - position; if (((Vector3)(ref val)).sqrMagnitude > 0.0001f) { ((Component)v.Source).transform.position = position; } } else { if (!p.currentVoiceChatIngameSettings.set2D) { p.currentVoiceChatIngameSettings.set2D = true; } SetFloat(v.Source.spatialBlend, 0f, delegate(float x) { v.Source.spatialBlend = x; }); } SetFloat(v.Source.panStereo, 0f, delegate(float x) { v.Source.panStereo = x; }); SetFloat(p.voicePlayerState.Volume, num2, delegate(float x) { p.voicePlayerState.Volume = x; }); } private static float LogLerp(float from, float to, float t) { if (from <= 0f || to <= 0f) { return Mathf.Lerp(from, to, t); } return from * Mathf.Pow(to / from, Mathf.Clamp01(t)); } } internal static class Spectator { private sealed class Held { public AudioSource Source; public float Orig; public float Attenuated; public float Rest; public bool Volatile; } private const float RampSeconds = 0.4f; private const float ScanInterval = 0.25f; private const float FocusScanInterval = 0.1f; private static readonly Dictionary<AudioSource, Held> Tracked = new Dictionary<AudioSource, Held>(); private static readonly HashSet<AudioSource> ExemptSources = new HashSet<AudioSource>(); private static readonly HashSet<AudioSource> FocusExempt = new HashSet<AudioSource>(); private static readonly List<Mirage.Mimic> MimicScratch = new List<Mirage.Mimic>(); private static readonly List<AudioSource> ToRemove = new List<AudioSource>(); private static float applied = 1f; private static float scanTimer = float.MaxValue; private static bool listenerHeld; private static float listenerOrig; private static float listenerAttenuated; internal static int ListenerRewrites; internal static float Target { get { PlayerControllerB local = Routing.GetLocal(); if (!((Object)(object)local != (Object)null) || !local.isPlayerDead) { return 1f; } return Mathf.Clamp01(Plugin.SpectatorVolume.Value); } } internal static void Abort() { try { foreach (Held value in Tracked.Values) { if ((Object)(object)value.Source != (Object)null) { value.Source.volume = value.Orig; } } } catch { } try { if (listenerHeld) { AudioListener.volume = listenerOrig; } } catch { } listenerHeld = false; Tracked.Clear(); applied = 1f; FocusAudio.Reset(); scanTimer = float.MaxValue; } internal static void Reset() { foreach (Held value in Tracked.Values) { if ((Object)(object)value.Source != (Object)null && Mathf.Abs(value.Source.volume - value.Attenuated) <= 0.0001f) { value.Source.volume = value.Orig; } } if (listenerHeld && Mathf.Abs(AudioListener.volume - listenerAttenuated) <= 0.0001f) { AudioListener.volume = listenerOrig; } listenerHeld = false; Tracked.Clear(); applied = 1f; FocusAudio.Reset(); scanTimer = float.MaxValue; } internal static void Restore() { foreach (Held value in Tracked.Values) { AudioSource source = value.Source; if ((Object)(object)source == (Object)null) { continue; } float volume = source.volume; if (Mathf.Abs(volume - value.Attenuated) <= 0.0001f) { if (value.Volatile && Mathf.Abs(volume - value.Orig) > 0.0001f) { source.volume = value.Orig; } } else { value.Orig = volume; value.Volatile = true; } value.Rest = source.volume; } } internal static void Apply(float dt) { applied = ((Plugin.SpectatorVolume.Value >= 1f) ? 1f : Mathf.MoveTowards(applied, Target, dt / 0.4f)); FocusAudio.Step(dt); ApplyListener(); float sourceFactor = FocusAudio.SourceFactor; bool flag = applied < 1f || sourceFactor < 1f; if (!flag && Tracked.Count == 0) { scanTimer = float.MaxValue; return; } if (flag) { CollectExemptSources(dt); scanTimer += dt; if (scanTimer >= ((sourceFactor < 1f) ? 0.1f : 0.25f)) { scanTimer = 0f; Scan(); } } ToRemove.Clear(); foreach (KeyValuePair<AudioSource, Held> item in Tracked) { AudioSource key = item.Key; Held value = item.Value; if ((Object)(object)key == (Object)null) { ToRemove.Add(item.Key); continue; } float volume = key.volume; if (Mathf.Abs(volume - value.Rest) > 0.0001f) { value.Orig = volume; value.Volatile = true; } float num = FactorFor(key, sourceFactor); if (num >= 1f) { if (Mathf.Abs(volume - value.Orig) > 0.0001f) { key.volume = value.Orig; } ToRemove.Add(key); continue; } float num2 = value.Orig * num; if (Mathf.Abs(volume - num2) > 0.0001f) { key.volume = num2; } value.Attenuated = key.volume; value.Rest = value.Attenuated; } for (int i = 0; i < ToRemove.Count; i++) { Tracked.Remove(ToRemove[i]); } ToRemove.Clear(); } private static void ApplyListener() { float listenerFactor = FocusAudio.ListenerFactor; if (listenerFactor >= 1f && !listenerHeld) { return; } float volume = AudioListener.volume; if (!listenerHeld) { listenerHeld = true; listenerOrig = (listenerAttenuated = volume); ListenerRewrites = 0; } else if (Mathf.Abs(volume - listenerAttenuated) > 0.0001f) { listenerOrig = volume; ListenerRewrites++; } if (listenerFactor >= 1f) { if (Mathf.Abs(volume - listenerOrig) > 0.0001f) { AudioListener.volume = listenerOrig; } listenerHeld = false; return; } float num = listenerOrig * listenerFactor; if (Mathf.Abs(volume - num) > 0.0001f) { AudioListener.volume = num; } listenerAttenuated = AudioListener.volume; } private static float FactorFor(AudioSource src, float focus) { return ((applied >= 1f || ExemptSources.Contains(src)) ? 1f : applied) * ((focus >= 1f || FocusExempt.Contains(src)) ? 1f : focus); } private static void CollectExemptSources(float dt) { ExemptSources.Clear(); FocusExempt.Clear(); FocusAudio.CollectExempt(FocusExempt); StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance == (Object)null) { return; } PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts; foreach (PlayerControllerB val in allPlayerScripts) { if (!((Object)(object)val == (Object)null) && val.isPlayerDead) { AudioSource currentVoiceChatAudioSource = val.currentVoiceChatAudioSource; if ((Object)(object)currentVoiceChatAudioSource != (Object)null) { ExemptSources.Add(currentVoiceChatAudioSource); } } } if (!Mirage.Present) { return; } PlayerControllerB local = Routing.GetLocal(); Mirage.Collect(MimicScratch, dt); foreach (Mirage.Mimic item in MimicScratch) { PlayerControllerB player = item.Player; if ((Object)(object)player != (Object)(object)local && player.isPlayerControlled && !player.isPlayerDead) { ExemptSources.Add(item.Source); } } } private static void Scan() { AudioSource[] array = Object.FindObjectsByType<AudioSource>((FindObjectsSortMode)0); foreach (AudioSource val in array) { if (!((Object)(object)val == (Object)null) && !Tracked.ContainsKey(val) && !(FactorFor(val, FocusAudio.SourceFactor) >= 1f)) { float volume = val.volume; Tracked[val] = new Held { Source = val, Orig = volume, Attenuated = volume, Rest = volume }; } } } } internal static class VoiceHealth { private struct Pending { public float Due; public bool Heal; public bool Dump; public string Label; } private const float PollInterval = 0.5f; private static readonly float[] CheckDelays = new float[3] { 1.5f, 4f, 30f }; private static readonly float[] DumpDelays = new float[3] { 0f, 4f, 30f }; private static readonly Dictionary<ulong, string> Present = new Dictionary<ulong, string>(); private static readonly List<Pending> Queue = new List<Pending>(); private static bool haveBaseline; private static float timer; internal static void Reset() { Present.Clear(); Queue.Clear(); haveBaseline = false; timer = 0f; } internal static void Tick(float dt) { timer += dt; if (!(timer < 0.5f)) { timer = 0f; StartOfRound instance = StartOfRound.Instance; PlayerControllerB local = Routing.GetLocal(); if (!((Object)(object)instance == (Object)null) && !((Object)(object)local == (Object)null)) { WatchMembership(instance, local); RunDue(instance, local); } } } private static void WatchMembership(StartOfRound round, PlayerControllerB local) { Dictionary<ulong, string> dictionary = new Dictionary<ulong, string>(); PlayerControllerB[] allPlayerScripts = round.allPlayerScripts; foreach (PlayerControllerB val in allPlayerScripts) { if (!((Object)(object)val == (Object)null) && !((Object)(object)val == (Object)(object)local) && (val.isPlayerControlled || val.isPlayerDead)) { dictionary[val.playerClientId] = NameOf(val); } } if (!haveBaseline) { haveBaseline = true; Present.Clear(); { foreach (KeyValuePair<ulong, string> item in dictionary) { Present[item.Key] = item.Value; } return; } } StringBuilder stringBuilder = null; StringBuilder stringBuilder2 = null; foreach (KeyValuePair<ulong, string> item2 in Present) { if (!dictionary.ContainsKey(item2.Key)) { (stringBuilder ?? (stringBuilder = new StringBuilder())).Append(' ').Append(item2.Value).Append(" (#") .Append(item2.Key) .Append(')'); } } foreach (KeyValuePair<ulong, string> item3 in dictionary) { if (!Present.ContainsKey(item3.Key)) { (stringBuilder2 ?? (stringBuilder2 = new StringBuilder())).Append(' ').Append(item3.Value).Append(" (#") .Append(item3.Key) .Append(')'); } } Present.Clear(); foreach (KeyValuePair<ulong, string> item4 in dictionary) { Present[item4.Key] = item4.Value; } if (stringBuilder != null || stringBuilder2 != null) { string text = ((stringBuilder != null) ? ("left:" + stringBuilder) : "") + ((stringBuilder != null && stringBuilder2 != null) ? " |" : "") + ((stringBuilder2 != null) ? (" joined:" + stringBuilder2) : ""); Plugin.Logger.LogInfo((object)$"{Clock.Stamp()} [health] lobby membership changed ({text.Trim()}); {dictionary.Count} other player(s) now"); Queue.Clear(); float unscaledTime = Time.unscaledTime; for (int j = 0; j < CheckDelays.Length; j++) { Queue.Add(new Pending { Due = unscaledTime + CheckDelays[j], Heal = true, Dump = false, Label = $"+{CheckDelays[j]:F1}s" }); } for (int k = 0; k < DumpDelays.Length; k++) { Queue.Add(new Pending { Due = unscaledTime + DumpDelays[k], Heal = false, Dump = true, Label = $"+{DumpDelays[k]:F0}s" }); } } } private static void RunDue(StartOfRound round, PlayerControllerB local) { if (Queue.Count == 0) { return; } float unscaledTime = Time.unscaledTime; for (int i = 0; i < Queue.Count; i++) { Pending pending = Queue[i]; if (unscaledTime < pending.Due) { continue; } Queue.RemoveAt(i--); try { if (pending.Dump) { Dump(round, local, pending.Label); } if (pending.Heal) { Heal(round, local, pending.Label); } } catch (Exception e) { Plugin.ReportFailure("Voice health", e); } } } private static string? Problem(PlayerControllerB p) { PlayerVoiceIngameSettings currentVoiceChatIngameSettings = p.currentVoiceChatIngameSettings; if ((Object)(object)currentVoiceChatIngameSettings == (Object)null) { return "no voice settings object"; } if (p.voicePlayerState == null) { return "no voice state"; } if (currentVoiceChatIngameSettings._playerState == null) { return "voice settings object has no state (its playback object was pooled or is not set up)"; } if (currentVoiceChatIngameSettings._playerState != p.voicePlayerState) { return "voice state differs from the one the audio source uses"; } if ((Object)(object)p.currentVoiceChatAudioSource == (Object)null) { return "no audio source"; } if (!((Behaviour)p.currentVoiceChatAudioSource).isActiveAndEnabled) { return "audio source is switched off"; } if (!SafeConnected(p)) { return "Dissonance no longer has this voice connected"; } return null; } private static bool SafeConnected(PlayerControllerB p) { try { return p.voicePlayerState.IsConnected; } catch (Exception) { return false; } } private static void Heal(StartOfRound round, PlayerControllerB local, string label) { if (Routing.LobbyClosing()) { return; } List<string> list = null; PlayerControllerB[] allPlayerScripts = round.allPlayerScripts; foreach (PlayerControllerB val in allPlayerScripts) { if (!((Object)(object)val == (Object)null) && !((Object)(object)val == (Object)(object)local) && (val.isPlayerControlled || val.isPlayerDead)) { string text = Problem(val); if (text != null) { (list ?? (list = new List<string>())).Add($"{NameOf(val)} (#{val.playerClientId}): {text}"); } } } if (list == null) { return; } Plugin.Logger.LogWarning((object)string.Format("{0} [health] {1}: {2} voice(s) look broken ({3}); asking the game to rebuild its voice objects", Clock.Stamp(), label, list.Count, string.Join("; ", list))); round.RefreshPlayerVoicePlaybackObjects(); round.UpdatePlayerVoiceEffects(); int num = 0; PlayerControllerB[] allPlayerScripts2 = round.allPlayerScripts; foreach (PlayerControllerB val2 in allPlayerScripts2) { if (!((Object)(object)val2 == (Object)null) && !((Object)(object)val2 == (Object)(object)local) && (val2.isPlayerControlled || val2.isPlayerDead)) { string text2 = Problem(val2); if (text2 != null) { num++; Plugin.Logger.LogWarning((object)$"{Clock.Stamp()} [health] {label}: {NameOf(val2)} (#{val2.playerClientId}) is still broken after the rebuild: {text2}"); } } } if (num == 0) { Plugin.Logger.LogInfo((object)(Clock.Stamp() + " [health] " + label + ": the rebuild repaired every voice")); } } private static void Dump(StartOfRound round, PlayerControllerB local, string label) { float[] array = (((Object)(object)SoundManager.Instance != (Object)null) ? SoundManager.Instance.playerVoiceVolumes : null); Plugin.Logger.LogInfo((object)$"{Clock.Stamp()} [health] voices {label}: AudioListener.pause={AudioListener.pause} volume={AudioListener.volume:F2}"); PlayerControllerB[] allPlayerScripts = round.allPlayerScripts; foreach (PlayerControllerB val in allPlayerScripts) { if (!((Object)(object)val == (Object)null) && !((Object)(object)val == (Object)(object)local) && (val.isPlayerControlled || val.isPlayerDead)) { VoicePlayerState voicePlayerState = val.voicePlayerState; PlayerVoiceIngameSettings currentVoiceChatIngameSettings = val.currentVoiceChatIngameSettings; AudioSource currentVoiceChatAudioSource = val.currentVoiceChatAudioSource; string text = ((voicePlayerState == null) ? "none" : $"conn={SafeConnected(val)} speaking={voicePlayerState.IsSpeaking} amp={voicePlayerState.Amplitude:F3} vol={voicePlayerState.Volume:F2} muted={voicePlayerState.IsLocallyMuted}"); string text2 = (((Object)(object)currentVoiceChatIngameSettings == (Object)null) ? "none" : ((currentVoiceChatIngameSettings._playerState == null) ? "no-state" : ((currentVoiceChatIngameSettings._playerState == voicePlayerState) ? "same-state" : "DIFFERENT-state"))); string text3 = (((Object)(object)currentVoiceChatAudioSource == (Object)null) ? "none" : string.Format("playing={0} enabled={1} vol={2:F2} mute={3} blend={4:F1} pan={5:F1} mixer={6}", currentVoiceChatAudioSource.isPlaying, ((Behaviour)currentVoiceChatAudioSource).isActiveAndEnabled, currentVoiceChatAudioSource.volume, currentVoiceChatAudioSource.mute, currentVoiceChatAudioSource.spatialBlend, currentVoiceChatAudioSource.panStereo, ((Object)(object)currentVoiceChatAudioSource.outputAudioMixerGroup != (Object)null) ? ((Object)currentVoiceChatAudioSource.outputAudioMixerGroup).name : "none")); string text4 = ((array != null && val.playerClientId < (ulong)array.Length) ? array[val.playerClientId].ToString("F0") : "n/a"); string text5 = (((Object)(object)currentVoiceChatIngameSettings != (Object)null && (Object)(object)currentVoiceChatIngameSettings._playbackComponent != (Object)null) ? (currentVoiceChatIngameSettings._playbackComponent.PlayerName ?? "null") : "n/a"); Plugin.Logger.LogInfo((object)$"{Clock.Stamp()} [health] {NameOf(val)} (#{val.playerClientId}) ctrl={val.isPlayerControlled} dead={val.isPlayerDead} state[{text}] settings={text2} playbackName={text5} src[{text3}] slider={text4} walkieFlag={val.speakingToWalkieTalkie} holdingFlag={val.holdingWalkieTalkie}"); } } LogWalkies(label); } private static void LogWalkies(string label) { List<WalkieTalkie> allWalkieTalkies = WalkieTalkie.allWalkieTalkies; if (allWalkieTalkies == null) { return; } StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < allWalkieTalkies.Count; i++) { WalkieTalkie val = allWalkieTalkies[i]; if (!((Object)(object)val == (Object)null)) { stringBuilder.Append(' ').Append(((NetworkBehaviour)val).NetworkObjectId).Append(':') .Append(((GrabbableObject)val).isBeingUsed ? "on" : "off") .Append('@') .Append(((Object)(object)((GrabbableObject)val).playerHeldBy != (Object)null) ? $"#{((GrabbableObject)val).playerHeldBy.playerClientId}" : "floor"); } } Plugin.Logger.LogInfo((object)$"{Clock.Stamp()} [health] walkies {label}:{stringBuilder}"); } private static string NameOf(PlayerControllerB p) { if (!string.IsNullOrEmpty(p.playerUsername)) { return p.playerUsername; } return $"Player {p.playerClientId}"; } } internal enum VoiceBand { InPerson, Walkie } internal static class VoiceHud { private sealed class Entry { public string Name = ""; public VoiceBand Band; public bool FromSpeaker; public float Y = float.NaN; public float Presence; public float Audible = 1f; public int LastFrame; } private struct MimicHit { public float Visibility; public string Name; } private const float FadeOutSeconds = 0.4f; private const float SlideRate = 12f; private const float MinAmplitude = 0.002f; private const float MimicMinRms = 0.002f; private const float AudibleFloor = 0.08f; private const float AudibleFull = 0.85f; private const float MuffledHz = 600f; private const float ClearHz = 3500f; private const float AudibilityRate = 4f; private const float HiddenBelow = 0.01f; private static readonly Dictionary<ulong, Entry> Entries = new Dictionary<ulong, Entry>(); private static readonly Dictionary<ulong, AudioLowPassFilter?> LowPasses = new Dictionary<ulong, AudioLowPassFilter>(); private static bool rolloffLogged; private static readonly List<Mirage.Mimic> MimicList = new List<Mirage.Mimic>(); private static readonly Dictionary<ulong, MimicHit> MimicHits = new Dictionary<ulong, MimicHit>(); private static readonly float[] OutputSamples = new float[256]; private static readonly List<ulong> SortedIds = new List<ulong>(); private static GUIStyle? nameStyle; private static Font? gameFont; private static bool fontSearched; internal static bool IsHeardTalking(PlayerControllerB p) { VoicePlayerState voicePlayerState = p.voicePlayerState; AudioSource currentVoiceChatAudioSource = p.currentVoiceChatAudioSource; if (voicePlayerState != null && (Object)(object)currentVoiceChatAudioSource != (Object)null && currentVoiceChatAudioSource.isPlaying && voicePlayerState.IsSpeaking) { return voicePlayerState.Amplitude > 0.002f; } return false; } private static bool Allowed(PlayerControllerB listener) { switch (Plugin.HudVisibility.Value) { case HudVisibilityMode.Never: return false; case HudVisibilityMode.WhenHavingWalkie: return AutoTransmit.HasPoweredWalkie(listener); case HudVisibilityMode.WhenHoldingWalkie: { GrabbableObject currentlyHeldObjectServer = listener.currentlyHeldObjectServer; WalkieTalkie val = (WalkieTalkie)(object)((currentlyHeldObjectServer is WalkieTalkie) ? currentlyHeldObjectServer : null); if (val != null) { return (Object)(object)val != (Object)null; } return false; } default: return true; } } internal static VoiceBand BandFor(PlayerControllerB p) { if (Routing.TryGetLinked(p, out var onRadio) && onRadio) { return VoiceBand.Walkie; } if (Routing.TryGetLinked(p, out var _)) { return VoiceBand.InPerson; } AudioSource currentVoiceChatAudioSource = p.currentVoiceChatAudioSource; VoicePlayerState voicePlayerState = p.voicePlayerState; if ((Object)(object)currentVoiceChatAudioSource != (Object)null && voicePlayerState != null && currentVoiceChatAudioSource.spatialBlend < 0.5f && voicePlayerState.Volume > 0.02f) { return VoiceBand.Walkie; } return VoiceBand.InPerson; } private static float Audibility(AudioSource? src, ulong cacheKey, float distance) { if ((Object)(object)src == (Object)null) { return 0f; } float num = DistanceGain(src, distance); float num2 = 22000f; LowPasses.TryGetValue(cacheKey, out AudioLowPassFilter value); if ((Object)(object)value == (Object)null || (Object)(object)((Component)value).gameObject != (Object)(object)((Component)src).gameObject) { value = ((Component)src).GetComponent<AudioLowPassFilter>(); LowPasses[cacheKey] = value; } if ((Object)(object)value != (Object)null && ((Behaviour)value).enabled) { num2 = value.cutoffFrequency; } float num3 = Mathf.Clamp01(Mathf.InverseLerp(600f, 3500f, num2)); return num * num3; } private static float DistanceGain(AudioSource src, float distance) { //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Invalid comparison between Unknown and I4 //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Invalid comparison between Unknown and I4 float num = Mathf.Max(0.01f, src.minDistance); float num2 = Mathf.Max(num + 0.01f, src.maxDistance); if (!rolloffLogged) { rolloffLogged = true; Plugin.Debug($"[hud] voice distance falloff: {src.rolloffMode}, min {num:F1} m, max {num2:F1} m"); } AudioRolloffMode rolloffMode = src.rolloffMode; if ((int)rolloffMode != 1) { if ((int)rolloffMode == 2) { AnimationCurve customCurve = src.GetCustomCurve((AudioSourceCurveType)0); if (customCurve == null) { return 1f; } return Mathf.Clamp01(customCurve.Evaluate(Mathf.Clamp01(distance / num2))); } if (!(distance <= num)) { return Mathf.Clamp01(num / Mathf.Min(distance, num2)); } return 1f; } return 1f - Mathf.Clamp01((distance - num) / (num2 - num)); } private static float Visibility(float audibility) { return Mathf.SmoothStep(0f, 1f, Mathf.InverseLerp(0.08f, 0.85f, audibility)); } internal static bool IsSliderMuted(PlayerControllerB p) { float[] array = (((Object)(object)SoundManager.Instance != (Object)null) ? SoundManager.Instance.playerVoiceVolumes : null); if (array != null && p.playerClientId < (ulong)array.Length) { return array[p.playerClientId] <= -60f; } return false; } internal static void Reset() { Entries.Clear(); LowPasses.Clear(); MimicHits.Clear(); Mirage.Reset(); } private static void CollectMimicVoices(PlayerControllerB listener, float dt) { //IL_0163: Unknown result type (might be due to invalid IL or missing references) //IL_016f: Unknown result type (might be due to invalid IL or missing references) MimicHits.Clear(); Mirage.Collect(MimicList, dt); if (MimicList.Count == 0) { return; } PlayerControllerB val = (((Object)(object)StartOfRound.Instance != (Object)null) ? StartOfRound.Instance.localPlayerController : null); foreach (Mirage.Mimic mimic in MimicList) { PlayerControllerB player = mimic.Player; AudioSource source = mimic.Source; if ((Object)(object)player == (Object)(object)listener || (Object)(object)player == (Object)(object)val || (!player.isPlayerControlled && !player.isPlayerDead) || player.disconnectedMidGame) { continue; } VoicePlayerState voicePlayerState = player.voicePlayerState; if ((voicePlayerState != null && voicePlayerState.IsLocallyMuted) || IsSliderMuted(player) || !((Behaviour)source).enabled || !((Component)source).gameObject.activeInHierarchy || source.mute || !source.isPlaying || source.volume <= 0.001f) { continue; } source.GetOutputData(OutputSamples, 0); float num = 0f; for (int i = 0; i < OutputSamples.Length; i++) { num += OutputSamples[i] * OutputSamples[i]; } if (!(Mathf.Sqrt(num / (float)OutputSamples.Length) < 0.002f)) { float distance = Vector3.Distance(((Component)listener).transform.position, ((Component)source).transform.position); float num2 = Visibility(Audibility(source, MimicCacheKey(source), distance)); if (!MimicHits.TryGetValue(player.playerClientId, out var value) || !(value.Visibility >= num2)) { string name = (string.IsNullOrEmpty(player.playerUsername) ? $"Player {player.playerClientId}" : player.playerUsername); MimicHits[player.playerClientId] = new MimicHit { Visibility = num2, Name = name }; } } } } private static ulong MimicCacheKey(AudioSource source) { return 0x10000000000uL | (ulong)(uint)((Object)source).GetInstanceID(); } internal static void Sample(float dt) { //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) StartOfRound instance = StartOfRound.Instance; PlayerControllerB val = Routing.CurrentListener(); if ((Object)(object)instance == (Object)null || (Object)(object)val == (Object)null || !Allowed(val)) { Entries.Clear(); return; } bool flag = AutoTransmit.HasPoweredWalkie(val); PlayerControllerB local = Routing.GetLocal(); CollectMimicVoices(val, dt); PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts; foreach (PlayerControllerB val2 in allPlayerScripts) { if (!((Object)(object)val2 == (Object)null) && !((Object)(object)val2 == (Object)(object)local) && val2.isPlayerControlled && !val2.isPlayerDead) { VoicePlayerState voicePlayerState = val2.voicePlayerState; float distance = Vector3.Distance(((Component)val).transform.position, ((Component)val2).transform.position); VoiceBand voiceBand = BandFor(val2); AudioSource currentVoiceChatAudioSource = val2.currentVoiceChatAudioSource; bool flag2 = voicePlayerState != null && !voicePlayerState.IsLocallyMuted && !IsSliderMuted(val2) && (Object)(object)currentVoiceChatAudioSource != (Object)null && currentVoiceChatAudioSource.isPlaying && voicePlayerState.IsSpeaking && voicePlayerState.Amplitude > 0.002f; string name = (string.IsNullOrEmpty(val2.playerUsername) ? $"Player {val2.playerClientId}" : val2.playerUsername); float num = ((flag2 || Entries.ContainsKey(val2.playerClientId)) ? Visibility(Audibility(currentVoiceChatAudioSource, val2.playerClientId, distance)) : 0f); if (MimicHits.Remove(val2.playerClientId, out var value) && (!flag2 || (voiceBand == VoiceBand.InPerson && value.Visibility > num))) { flag2 = true; voiceBand = VoiceBand.InPerson; num = value.Visibility; } Feed(val2.playerClientId, name, flag2, voiceBand, !flag, num, dt); } } foreach (KeyValuePair<ulong, MimicHit> mimicHit in MimicHits) { Feed(mimicHit.Key, mimicHit.Value.Name, speaking: true, VoiceBand.InPerson, fromSpeaker: false, mimicHit.Value.Visibility, dt); } MimicHits.Clear(); List<ulong> list = null; foreach (KeyValuePair<ulong, Entry> entry in Entries) { Entry value2 = entry.Value; if (value2.LastFrame != Time.frameCount) { value2.Presence -= dt / 0.4f; } if (value2.Presence <= 0f) { (list ?? (list = new List<ulong>())).Add(entry.Key); } } if (list == null) { return; } foreach (ulong item in list) { Entries.Remove(item); } } internal static void Feed(ulong id, string name, bool speaking, VoiceBand band, bool fromSpeaker, float visibility, float dt) { if (!Entries.TryGetValue(id, out Entry value)) { if (!speaking) { return; } value = new Entry { Audible = visibility }; Entries[id] = value; } value.LastFrame = Time.frameCount; value.Name = name; if (speaking) { value.Band = band; value.FromSpeaker = fromSpeaker; } float num = ((value.Band == VoiceBand.InPerson) ? visibility : 1f); value.Audible = Mathf.MoveTowards(value.Audible, num, 4f * dt); if (speaking) { value.Presence = 1f; } else { value.Presence -= dt / 0.4f; } } internal static void Draw() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Invalid comparison between Unknown and I4 //IL_0257: Unknown result type (might be due to invalid IL or missing references) //IL_01c8: Unknown result type (might be due to invalid IL or missing references) //IL_01fe: Unknown result type (might be due to invalid IL or missing references) //IL_0216: Unknown result type (might be due to invalid IL or missing references) //IL_021b: Unknown result type (might be due to invalid IL or missing references) //IL_0226: Unknown result type (might be due to invalid IL or missing references) //IL_022d: Unknown result type (might be due to invalid IL or missing references) if ((int)Event.current.type != 7) { return; } float num = (float)Screen.height / 1080f * Plugin.HudScale.Value; if (Entries.Count == 0) { return; } SortedIds.Clear(); foreach (KeyValuePair<ulong, Entry> entry2 in Entries) { if (Alpha(entry2.Value) >= 0.01f) { SortedIds.Add(entry2.Key); } else { entry2.Value.Y = float.NaN; } } if (SortedIds.Count != 0) { EnsureNameStyle(); float num2 = 34f * num; float num3 = 24f * num; SortedIds.Sort(delegate(ulong a, ulong b) { int num9 = Entries[a].Band.CompareTo(Entries[b].Band); return (num9 == 0) ? a.CompareTo(b) : num9; }); float num4 = ((float)Screen.height - (float)SortedIds.Count * num2) / 2f; float num5 = 1f - Mathf.Exp(-12f * Time.unscaledDeltaTime); nameStyle.fontSize = Mathf.Max(10, Mathf.RoundToInt(24f * num)); Rect val = default(Rect); for (int num6 = 0; num6 < SortedIds.Count; num6++) { Entry entry = Entries[SortedIds[num6]]; float num7 = num4 + (float)num6 * num2; entry.Y = (float.IsNaN(entry.Y) ? num7 : Mathf.Lerp(entry.Y, num7, num5)); ((Rect)(ref val))..ctor(num3, entry.Y, 520f * num, num2); float num8 = Alpha(entry); GUI.color = new Color(0f, 0f, 0f, 0.85f * num8); GUI.Label(new Rect(((Rect)(ref val)).x + num * 1.5f, ((Rect)(ref val)).y + num * 1.5f, ((Rect)(ref val)).width, ((Rect)(ref val)).height), entry.Name, nameStyle); Color color = NameColor(entry); color.a = num8; GUI.color = color; GUI.Label(val, entry.Name, nameStyle); } GUI.color = Color.white; } } private static float Alpha(Entry e) { return e.Presence * ((e.Band == VoiceBand.InPerson) ? e.Audible : 1f); } private static Color NameColor(Entry e) { //IL_003d: 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) //IL_0022: Unknown result type (might be due to invalid IL or missing references) VoiceBand band = e.Band; if (band == VoiceBand.Walkie) { if (!e.FromSpeaker) { return new Color(0.3f, 1f, 0.4f); } return new Color(1f, 0.85f, 0.2f); } return Color.white; } private static Font? FindGameFont() { try { TMP_FontAsset[] array = Resources.FindObjectsOfTypeAll<TMP_FontAsset>(); foreach (TMP_FontAsset val in array) { if ((Object)(object)val != (Object)null && ((Object)val).name.IndexOf("3270", StringComparison.OrdinalIgnoreCase) >= 0 && (Object)(object)val.sourceFontFile != (Object)null) { Plugin.Debug("[hud] using the game's font '" + ((Object)val.sourceFontFile).name + "' (from '" + ((Object)val).name + "')"); return val.sourceFontFile; } } Font[] array2 = Resources.FindObjectsOfTypeAll<Font>(); foreach (Font val2 in array2) { if ((Object)(object)val2 != (Object)null && ((Object)val2).name.IndexOf("3270", StringComparison.OrdinalIgnoreCase) >= 0) { Plugin.Debug("[hud] using the game's font '" + ((Object)val2).name + "'"); return val2; } } Plugin.Logger.LogWarning((object)"[hud] the game's 3270 font was not found as a usable Font; using a monospace system font instead"); } catch (Exception ex) { Plugin.Logger.LogWarning((object)("[hud] font lookup failed (" + ex.Message + "); using a monospace system font instead")); } return Font.CreateDynamicFontFromOSFont(new string[4] { "Consolas", "Lucida Console", "DejaVu Sans Mono", "Courier New" }, 24); } private static void EnsureNameStyle() { //IL_0029: 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_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_0043: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Expected O, but got Unknown if (nameStyle == null) { if (!fontSearched) { fontSearched = true; gameFont = FindGameFont(); }