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 ControlCompanyReloaded v1.0.0
ControlCompanyReloaded.dll
Decompiled an hour ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using System.Text; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using Dissonance; using Dissonance.Audio.Capture; using GameNetcodeStuff; using HarmonyLib; using NAudio.Wave; using Steamworks; using Steamworks.Data; using TMPro; using Unity.Netcode; using UnityEngine; using UnityEngine.AI; using UnityEngine.InputSystem; using UnityEngine.Rendering; using UnityEngine.Rendering.HighDefinition; using UnityEngine.UI; [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] namespace ControlCompanyReloaded; internal static class BodyLock { internal const string Part = "Body lock"; internal static bool Away; private static bool setMoveFlag; private static readonly string[] handlers = new string[19] { "Jump_performed", "Crouch_performed", "Interact_performed", "Discard_performed", "InspectItem_performed", "ItemSecondaryUse_performed", "ItemTertiaryUse_performed", "QEItemInteract_performed", "ScrollMouse_performed", "UseUtilitySlot_performed", "ActivateItem_performed", "ActivateItem_canceled", "OpenMenu_performed", "Emote1_performed", "Emote2_performed", "Look_performed", "SetFreeCamera_performed", "SpeedCheat_performed", "ClickHoldInteraction" }; internal static void Start() { HarmonyMethod prefix = Hooks.Method(typeof(BodyLock), "SkipWhileAway"); int num = 0; string[] array = handlers; foreach (string text in array) { try { Hooks.Patch("Body lock", typeof(PlayerControllerB), text, null, prefix); } catch (PatchTargetMissing) { num++; Check.Info("Body lock", "the game has no PlayerControllerB." + text + " (skipped)"); } } Hooks.Patch("Body lock", typeof(PlayerControllerB), "PlayerLookInput", Type.EmptyTypes, prefix); string part = "Body lock"; Type typeFromHandle = typeof(HUDManager); string method = "CanPlayerScan"; Type[] emptyTypes = Type.EmptyTypes; HarmonyMethod postfix = Hooks.Method(typeof(BodyLock), "NoScan"); Hooks.Patch(part, typeFromHandle, method, emptyTypes, null, postfix); if (num > 0) { Check.Info("Body lock", num + " input handler(s) not found; the rest are locked"); } } [MethodImpl(MethodImplOptions.NoInlining)] private static bool SkipWhileAway(PlayerControllerB __instance) { return !Away || !((Object)(object)__instance == (Object)(object)Game.Local); } [MethodImpl(MethodImplOptions.NoInlining)] private static void NoScan(ref bool __result) { if (Away) { __result = false; } } internal static void Leave(PlayerControllerB local) { Away = true; if (!local.disableMoveInput) { local.disableMoveInput = true; setMoveFlag = true; } ShowBody(local, outside: true); } internal static void Return(PlayerControllerB local) { Away = false; if ((Object)(object)local == (Object)null) { setMoveFlag = false; return; } if (setMoveFlag) { local.disableMoveInput = false; } setMoveFlag = false; ShowBody(local, outside: false); } private static void ShowBody(PlayerControllerB local, bool outside) { try { if (!local.isPlayerDead) { if ((Object)(object)local.thisPlayerModel != (Object)null) { ((Renderer)local.thisPlayerModel).shadowCastingMode = (ShadowCastingMode)(outside ? 1 : 3); } if ((Object)(object)local.thisPlayerModelArms != (Object)null) { ((Renderer)local.thisPlayerModelArms).enabled = !outside; } } } catch (Exception ex) { Check.Problem("Body lock", "showing the body: " + ex.Message); } } } internal static class BodyWalk { internal const string Part = "Body walk"; private const float TurnSpeed = 150f; private const float SendEvery = 0.05f; private static float sinceSent; private static bool turning; private static bool saidWalk; private static bool saidTurn; private static bool saidSent; internal static bool On { get; private set; } internal static void Start() { string part = "Body walk"; Type typeFromHandle = typeof(PlayerControllerB); string method = "SetFaceUnderwaterFilters"; Type[] emptyTypes = Type.EmptyTypes; HarmonyMethod postfix = Hooks.Method(typeof(BodyWalk), "ArrowsIn"); Hooks.Patch(part, typeFromHandle, method, emptyTypes, null, postfix); } internal static bool Can(PlayerControllerB p) { return (Object)(object)p != (Object)null && p.isPlayerControlled && !p.isPlayerDead; } internal static void Toggle(PlayerControllerB p) { On = !On; if (!On) { Stop(p); } Check.Info("Body walk", (!On) ? "off" : "on: the arrow keys walk the body"); } private static bool Free(PlayerControllerB p) { return !p.isTypingChat && !p.inTerminalMenu && !p.inVehicleAnimation && ((Object)(object)p.quickMenuManager == (Object)null || !p.quickMenuManager.isMenuOpen) && (!p.inSpecialInteractAnimation || p.isClimbingLadder || p.inShockingMinigame); } private static float Axis(Key plus, Key minus) { return ((!plus.Held) ? 0f : 1f) - ((!minus.Held) ? 0f : 1f); } [MethodImpl(MethodImplOptions.NoInlining)] private static void ArrowsIn(PlayerControllerB __instance) { //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) if (On && BodyLock.Away && !((Object)(object)__instance != (Object)(object)Game.Local) && Keys.BodyForward != null && Can(__instance) && Free(__instance)) { float num = Axis(Keys.BodyForward, Keys.BodyBack); __instance.moveInputVector = new Vector2(0f, num); if (num != 0f && !saidWalk) { saidWalk = true; Check.Ok("Body walk", "the arrow keys walked the body"); } } } internal static void Turn(PlayerControllerB p, bool keysOff) { if (!On || (Object)(object)p == (Object)null || !Can(p) || (Object)(object)p.thisPlayerBody == (Object)null) { return; } sinceSent += Time.deltaTime; float num = ((!keysOff && Free(p)) ? Axis(Keys.BodyRight, Keys.BodyLeft) : 0f); if (num != 0f) { p.thisPlayerBody.Rotate(0f, num * 150f * Time.deltaTime, 0f, (Space)1); turning = true; if (!saidTurn) { saidTurn = true; Check.Ok("Body walk", "the arrow keys turned the body"); } if (sinceSent >= 0.05f) { Send(p, always: false); } } else if (turning) { turning = false; Send(p, always: true); } } internal static void Stop(PlayerControllerB p) { if (turning && (Object)(object)p != (Object)null && Can(p) && (Object)(object)p.thisPlayerBody != (Object)null) { Send(p, always: true); } turning = false; } private static void Send(PlayerControllerB p, bool always) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) float y = p.thisPlayerBody.localEulerAngles.y; if (!always && Mathf.Abs(Mathf.DeltaAngle(p.previousYRot, y)) <= 1.5f) { return; } sinceSent = 0f; StartOfRound playersManager = p.playersManager; if ((Object)(object)playersManager != (Object)null && playersManager.newGameIsLoading) { return; } p.oldCameraUp = p.cameraUp; p.previousYRot = y; if (!((Object)(object)playersManager != (Object)null) || !((NetworkBehaviour)p).IsServer || playersManager.connectedPlayersAmount >= 1) { p.UpdatePlayerRotationServerRpc((short)p.cameraUp, (short)y); if (!saidSent) { saidSent = true; Check.Ok("Body walk", "sent the turned body's facing to the other players"); } } } } internal static class Check { private static readonly HashSet<string> said = new HashSet<string>(); private static readonly object gate = new object(); internal static void Ok(string part, string detail) { lock (gate) { if (!said.Add("ok|" + part + "|" + detail)) { return; } } Plugin.Log.LogInfo((object)("[OK] " + part + ": " + detail)); } internal static void Problem(string part, string detail) { string text = ((detail.Length <= 160) ? detail : detail.Substring(0, 160)); lock (gate) { if (!said.Add("problem|" + part + "|" + text)) { return; } } Plugin.Log.LogError((object)("[PROBLEM] " + part + ": " + detail)); } internal static void Info(string part, string detail) { Plugin.Log.LogInfo((object)(part + ": " + detail)); } } internal static class Compat { internal const string Part = "Other mods"; private const string StarlancerAssembly = "StarlancerAI"; private const string StarlancerType = "StarlancerAIFix.Patches.AIFix"; private static readonly string[] StarlancerLists = new string[4] { "insideSpawnedEnemies", "outsideSpawnedEnemies", "daytimeSpawnedEnemies", "weedSpawnedEnemies" }; private static bool looked; private static readonly List<FieldInfo> lists = new List<FieldInfo>(); private static bool saidLeftOut; private static void Find() { looked = true; Assembly assembly = null; Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly2 in assemblies) { try { if (assembly2.GetName().Name == "StarlancerAI") { assembly = assembly2; break; } } catch (Exception) { } } if (assembly == null) { return; } try { Type type = assembly.GetType("StarlancerAIFix.Patches.AIFix"); string text = ((!(type == null)) ? string.Empty : " StarlancerAIFix.Patches.AIFix"); if (type != null) { string[] starlancerLists = StarlancerLists; foreach (string text2 in starlancerLists) { FieldInfo field = type.GetField(text2, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (field != null && typeof(IList).IsAssignableFrom(field.FieldType)) { lists.Add(field); } else { text = text + " " + text2; } } } if (text.Length == 0) { Check.Info("Other mods", "Starlancer AI Fix found: enemies this mod spawns are left out of its power count"); } else { Check.Problem("Other mods", "Starlancer AI Fix found, but it lacks" + text + ": the moon's power count may drop when an enemy of ours is removed"); } } catch (Exception ex2) { Check.Problem("Other mods", "looking into Starlancer AI Fix: " + ex2.Message); } } internal static void LeaveOut(EnemyAI e) { if ((Object)(object)e == (Object)null) { return; } if (!looked) { Find(); } if (lists.Count == 0) { return; } bool flag = false; foreach (FieldInfo list2 in lists) { try { IList list = list2.GetValue(null) as IList; while (list != null && list.Contains(e)) { list.Remove(e); flag = true; } } catch (Exception ex) { Check.Problem("Other mods", "Starlancer AI Fix's " + list2.Name + ": " + ex.Message); } } if (flag && !saidLeftOut) { saidLeftOut = true; Check.Ok("Other mods", "left " + ((object)e).GetType().Name + " out of Starlancer AI Fix's power count"); } } } internal sealed class EnemyVoice : IMicrophoneSubscriber { private sealed class Before { internal Component Stream; internal Component Mimic; internal PlayerControllerB Mimicked; internal object Allowed; internal bool Masked; internal float Due = float.MaxValue; } internal const string Part = "Enemy voice"; private const string MirageGuid = "qwbarch.Mirage"; private const int Rate = 48000; private const int Frame = 960; private const int StartPackets = 50; private const int MaxSeconds = 30; private const int MaxPackets = 1500; private const float PutBackAfter = 2f; private static bool looked; private static bool found; private static Type streamType; private static Type mimicType; private static PropertyInfo allowedSender; private static PropertyInfo mimicking; private static MethodInfo startLine; private static MethodInfo sendPacket; private static MethodInfo mimicPlayer; private static MethodInfo resetMimic; private static MethodInfo makeEncoder; private static MethodInfo encode; private static ConstructorInfo newPacket; private static readonly EnemyVoice mic = new EnemyVoice(); private static DissonanceComms subscribed; private static Before saved; private static EnemyAI talkingAs; private static Component stream; private static object encoder; private static int sent; private static readonly float[] frame = new float[960]; private static readonly float[] silence = new float[960]; private static readonly byte[] encoded = new byte[1275]; private static readonly object[] encodeArgs = new object[6]; private static bool saidLine; private static bool saidPadded; private static bool saidMasked; private readonly object gate = new object(); private readonly float[] ring = new float[96000]; private int head; private int count; private volatile bool capturing; private float[] mono = new float[480]; private double resampleAt; private float lastIn; private volatile string format_; private bool saidFormat; internal static bool Available { get { if (!looked) { Find(); } return found; } } internal static bool Talking { get; private set; } private static void Find() { looked = true; if (!Chainloader.PluginInfos.TryGetValue("qwbarch.Mirage", out var value)) { return; } string text = ((value.Metadata == null) ? "?" : value.Metadata.Version.ToString()); try { Assembly assembly = Loaded("Mirage"); Assembly assembly2 = Loaded("Mirage.Core"); Type type = null; Type type2 = null; if (assembly != null) { streamType = assembly.GetType("Mirage.Unity.AudioStream+AudioStream"); mimicType = assembly.GetType("Mirage.Unity.MimicPlayer+MimicPlayer"); type = assembly.GetType("Mirage.Domain.Audio.Packet+OpusPacket"); } if (assembly2 != null) { type2 = assembly2.GetType("Mirage.Core.Audio.Opus.Codec"); } if (streamType != null && type != null) { allowedSender = streamType.GetProperty("AllowedSenderId", BindingFlags.Instance | BindingFlags.Public); startLine = streamType.GetMethod("InitializeAudioReceiverClientRpc", new Type[1] { typeof(int) }); sendPacket = streamType.GetMethod("SendPacketClientRpc", new Type[1] { type }); newPacket = type.GetConstructor(new Type[3] { typeof(int), typeof(byte[]), typeof(int) }); } if (mimicType != null) { mimicking = mimicType.GetProperty("MimickingPlayer", BindingFlags.Instance | BindingFlags.Public); mimicPlayer = mimicType.GetMethod("MimicPlayer", new Type[1] { typeof(int) }); resetMimic = mimicType.GetMethod("ResetMimicPlayer", Type.EmptyTypes); } if (type2 != null) { makeEncoder = type2.GetMethod("OpusEncoder", BindingFlags.Static | BindingFlags.Public, null, Type.EmptyTypes, null); } if (makeEncoder != null) { encode = makeEncoder.ReturnType.GetMethod("Encode", new Type[6] { typeof(float[]), typeof(int), typeof(int), typeof(byte[]), typeof(int), typeof(int) }); } string text2 = string.Empty; if (streamType == null) { text2 += " AudioStream"; } if (mimicType == null) { text2 += " MimicPlayer"; } if (type == null) { text2 += " OpusPacket"; } if (allowedSender == null) { text2 += " AllowedSenderId"; } if (startLine == null) { text2 += " InitializeAudioReceiverClientRpc"; } if (sendPacket == null) { text2 += " SendPacketClientRpc"; } if (newPacket == null) { text2 += " OpusPacket(int,byte[],int)"; } if (mimicking == null) { text2 += " MimickingPlayer"; } if (mimicPlayer == null) { text2 += " MimicPlayer(int)"; } if (resetMimic == null) { text2 += " ResetMimicPlayer"; } if (makeEncoder == null) { text2 += " Codec.OpusEncoder"; } if (encode == null) { text2 += " Encode(float[]...)"; } if (allowedSender != null && !allowedSender.PropertyType.IsClass) { text2 += " (AllowedSenderId isn't an F# option)"; } found = text2.Length == 0; if (found) { Check.Info("Enemy voice", "Mirage " + text + " found: " + Keys.TalkAsEnemy.Label + " talks as the enemy"); } else { Check.Problem("Enemy voice", "Mirage " + text + " lacks what talking as the enemy needs, the key stays off; missing:" + text2); } } catch (Exception ex) { found = false; Check.Problem("Enemy voice", "looking into Mirage " + text + ", the key stays off: " + ex); } } private static Assembly Loaded(string name) { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { try { if (assembly.GetName().Name == name) { return assembly; } } catch (Exception) { } } return null; } internal static string Label(Possession p) { if (p == null || !p.Alive || !Voice.MicOn() || !Available) { return null; } return (!Talking) ? "Talk as enemy" : Panel.Warn("Talking as enemy"); } internal static string Tick(PlayerControllerB local, Possession p, bool keysOff) { try { if (saved != null && !Talking && Time.time >= saved.Due) { PutBack(); } EnemyAI val = ((p == null || !p.Alive) ? null : p.Enemy); if (Talking) { if (!((Object)(object)val != (Object)null) || !((Object)(object)val == (Object)(object)talkingAs) || keysOff || !Keys.TalkAsEnemy.Held || !Voice.MicOn() || !((Object)(object)stream != (Object)null)) { End(); return null; } Pump(); if (sent >= 1500) { End(); return 30 + " s at most"; } return null; } if ((Object)(object)val == (Object)null || keysOff || (Object)(object)local == (Object)null || !Keys.TalkAsEnemy.Pressed || !Voice.MicOn() || !Available) { return null; } return Begin(local, val); } catch (Exception ex) { Check.Problem("Enemy voice", "talking as the enemy: " + ex); Abort(); return "Talking as the enemy failed (see the log)"; } } private static string Begin(PlayerControllerB local, EnemyAI e) { Component val = On(e, streamType); Component val2 = On(e, mimicType); if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null) { return "No Mirage voice on this enemy"; } DissonanceComms val3 = ((!((Object)(object)IngamePlayerSettings.Instance != (Object)null)) ? null : IngamePlayerSettings.Instance.comms); if ((Object)(object)val3 == (Object)null) { return "No voice chat"; } object? value = mimicking.GetValue(val2, null); PlayerControllerB val4 = (PlayerControllerB)((value is PlayerControllerB) ? value : null); bool flag = e is MaskedPlayerEnemy; if (flag && (Object)(object)val4 == (Object)null) { return "It mimics nobody"; } if (saved != null && (Object)(object)saved.Stream != (Object)(object)val) { PutBack(); } if (saved == null) { Before before = new Before(); before.Stream = val; before.Mimic = val2; before.Mimicked = val4; before.Allowed = allowedSender.GetValue(val, null); before.Masked = flag; saved = before; } saved.Due = float.MaxValue; if (!flag && (Object)(object)val4 != (Object)(object)local) { mimicPlayer.Invoke(val2, new object[1] { (int)local.playerClientId }); } allowedSender.SetValue(val, null, null); if (flag && (Object)(object)val4 != (Object)(object)local && !saidMasked) { saidMasked = true; Check.Info("Enemy voice", "a Masked keeps mimicking " + val4.playerUsername + ((!val4.isPlayerDead) ? ", who doesn't hear the line" : string.Empty)); } if ((Object)(object)subscribed != (Object)(object)val3) { val3.SubscribeToRecordedAudio((IMicrophoneSubscriber)(object)mic); subscribed = val3; } mic.Clear(); encoder = makeEncoder.Invoke(null, null); startLine.Invoke(val, new object[1] { 1440000 }); stream = val; talkingAs = e; sent = 0; mic.capturing = true; Talking = true; Check.Info("Enemy voice", "talking as " + ((object)e).GetType().Name + ((!((Object)(object)val4 == (Object)(object)local) && !flag) ? (" (it mimicked " + ((!((Object)(object)val4 != (Object)null)) ? "nobody" : val4.playerUsername) + ")") : string.Empty)); return null; } private static void Pump() { if (!mic.saidFormat && mic.format_ != null) { mic.saidFormat = true; Check.Info("Enemy voice", "microphone: " + mic.format_); } while (sent < 1500 && mic.Take(frame)) { Send(frame); } if (!saidLine && sent >= 50) { saidLine = true; Check.Ok("Enemy voice", "sent a second of the host's voice through the enemy (the others start playing it now)"); } } private static void Send(float[] pcm) { encodeArgs[0] = pcm; encodeArgs[1] = 0; encodeArgs[2] = 960; encodeArgs[3] = encoded; encodeArgs[4] = 0; encodeArgs[5] = encoded.Length; int num = (int)encode.Invoke(encoder, encodeArgs); if (num <= 0) { throw new InvalidOperationException("the Opus encoder returned " + num); } byte[] array = new byte[num]; Buffer.BlockCopy(encoded, 0, array, 0, num); object obj = newPacket.Invoke(new object[3] { num, array, sent * 960 }); sendPacket.Invoke(stream, new object[1] { obj }); sent++; } private static void End() { mic.capturing = false; Talking = false; try { if ((Object)(object)stream != (Object)null) { Pump(); if (sent > 0 && sent < 50 && !saidPadded) { saidPadded = true; Check.Info("Enemy voice", "a short line (" + sent * 20 + " ms) was padded to a second, or it wouldn't play"); } while (sent > 0 && sent < 50) { Send(silence); } } } finally { if (saved != null) { saved.Due = Time.time + 2f; } stream = null; talkingAs = null; encoder = null; } } private static void Abort() { mic.capturing = false; Talking = false; stream = null; talkingAs = null; encoder = null; try { if (saved != null) { PutBack(); } } catch (Exception ex) { Check.Problem("Enemy voice", "putting Mirage back: " + ex.Message); saved = null; } } private static void PutBack() { Before before = saved; saved = null; if (before == null || (Object)(object)before.Stream == (Object)null || (Object)(object)before.Mimic == (Object)null) { return; } if (!before.Masked && (Object)(object)before.Mimic != (Object)null) { object? value = mimicking.GetValue(before.Mimic, null); PlayerControllerB val = (PlayerControllerB)((value is PlayerControllerB) ? value : null); if ((Object)(object)val != (Object)(object)before.Mimicked) { if ((Object)(object)before.Mimicked != (Object)null) { mimicPlayer.Invoke(before.Mimic, new object[1] { (int)before.Mimicked.playerClientId }); } else { resetMimic.Invoke(before.Mimic, null); } } } if ((Object)(object)before.Stream != (Object)null) { allowedSender.SetValue(before.Stream, before.Allowed, null); } Check.Info("Enemy voice", "the enemy mimics " + ((!((Object)(object)before.Mimicked != (Object)null)) ? "nobody" : before.Mimicked.playerUsername) + " again"); } internal static void Forget() { mic.capturing = false; Talking = false; stream = null; talkingAs = null; encoder = null; saved = null; if ((Object)(object)subscribed != (Object)null) { try { subscribed.UnsubscribeFromRecordedAudio((IMicrophoneSubscriber)(object)mic); } catch (Exception) { } subscribed = null; } } private static Component On(EnemyAI e, Type t) { Component val = ((Component)e).GetComponent(t); if ((Object)(object)val == (Object)null) { val = ((Component)e).GetComponentInParent(t); } if ((Object)(object)val == (Object)null) { val = ((Component)e).GetComponentInChildren(t); } return val; } public void ReceiveMicrophoneData(ArraySegment<float> buffer, WaveFormat format) { if (!capturing || buffer.Array == null || format == null) { return; } int num = Math.Max(1, format.Channels); int sampleRate = format.SampleRate; int num2 = buffer.Count / num; if (num2 <= 0 || sampleRate <= 0) { return; } lock (gate) { if (format_ == null) { format_ = sampleRate + " Hz, " + num + " channel(s)"; } if (mono.Length < num2) { mono = new float[num2]; } for (int i = 0; i < num2; i++) { float num3 = 0f; for (int j = 0; j < num; j++) { num3 += buffer.Array[buffer.Offset + i * num + j]; } mono[i] = num3 / (float)num; } if (sampleRate == 48000) { for (int k = 0; k < num2; k++) { Push(mono[k]); } return; } double num4 = (double)sampleRate / 48000.0; while (resampleAt <= (double)(num2 - 1)) { int num5 = (int)Math.Floor(resampleAt); float num6 = (float)(resampleAt - (double)num5); float num7 = ((num5 >= 0) ? mono[num5] : lastIn); float num8 = mono[(num5 + 1 >= num2) ? (num2 - 1) : (num5 + 1)]; Push(num7 + (num8 - num7) * num6); resampleAt += num4; } resampleAt -= num2; lastIn = mono[num2 - 1]; } } public void Reset() { Clear(); } private void Clear() { lock (gate) { head = 0; count = 0; resampleAt = 0.0; lastIn = 0f; } } private void Push(float x) { ring[(head + count) % ring.Length] = x; if (count < ring.Length) { count++; } else { head = (head + 1) % ring.Length; } } private bool Take(float[] into) { lock (gate) { if (count < into.Length) { return false; } for (int i = 0; i < into.Length; i++) { into[i] = ring[head]; head = (head + 1) % ring.Length; } count -= into.Length; return true; } } } internal static class Game { private static MoldSpreadManager mold; private static bool moldSearched; internal const float InsideBelow = -80f; internal static PlayerControllerB Local { [CompilerGenerated] get { return (!((Object)(object)GameNetworkManager.Instance != (Object)null)) ? null : GameNetworkManager.Instance.localPlayerController; } } internal static bool IsHost { [CompilerGenerated] get { return (Object)(object)NetworkManager.Singleton != (Object)null && NetworkManager.Singleton.IsHost; } } internal static bool InRound { get { StartOfRound instance = StartOfRound.Instance; return (Object)(object)instance != (Object)null && (Object)(object)RoundManager.Instance != (Object)null && (Object)(object)RoundManager.Instance.currentLevel != (Object)null && !instance.inShipPhase && !instance.shipIsLeaving && instance.shipDoorsEnabled; } } internal static string RoundState { get { StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance == (Object)null) { return "no StartOfRound"; } return "in orbit " + instance.inShipPhase + ", ship leaving " + instance.shipIsLeaving + ", doors on " + instance.shipDoorsEnabled + ", day started " + ((Object)(object)TimeOfDay.Instance != (Object)null && TimeOfDay.Instance.currentDayTimeStarted) + ", level " + ((!((Object)(object)RoundManager.Instance != (Object)null) || !((Object)(object)RoundManager.Instance.currentLevel != (Object)null)) ? "none" : RoundManager.Instance.currentLevel.PlanetName); } } internal static bool HasWeeds { get { if (!moldSearched) { moldSearched = true; mold = Object.FindObjectOfType<MoldSpreadManager>(); } if ((Object)(object)mold == (Object)null || (Object)(object)mold.grassInstancer == (Object)null) { return false; } List<Vector3> batchedPositions = mold.grassInstancer.batchedPositions; return batchedPositions != null && batchedPositions.Count > 0 && mold.mostSurroundingSpores != 0; } } internal static void ForgetRound() { moldSearched = false; mold = null; } internal static bool IsOutside(Vector3 pos) { return pos.y > -80f; } internal static int Layer(string name) { return LayerMask.NameToLayer(name); } internal static int Mask(params string[] names) { int num = 0; foreach (string text in names) { int num2 = LayerMask.NameToLayer(text); if (num2 >= 0) { num |= 1 << num2; } } return num; } } internal static class Hearing { private sealed class Heard { internal AudioSource Source; internal VoicePlayerState State; internal OccludeAudio Occlude; internal float Volume; internal bool Blocked; internal float NextCheck; } internal const string Part = "Hearing"; private const int WallMask = 256; private const float CheckEvery = 0.5f; private static readonly Dictionary<PlayerControllerB, Heard> fromBody = new Dictionary<PlayerControllerB, Heard>(); private static readonly Dictionary<AudioSource, AnimationCurve> curves = new Dictionary<AudioSource, AnimationCurve>(); private static bool saidCurve; private static bool saidBody; private static bool saidRolloff; internal static bool On { get; private set; } internal static void Toggle() { On = !On; if (!On) { Restore(); } Check.Info("Hearing", (!On) ? "off" : "on: voices near the body are heard too"); } internal static void Apply(PlayerControllerB local) { //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_01aa: Unknown result type (might be due to invalid IL or missing references) //IL_01af: Unknown result type (might be due to invalid IL or missing references) //IL_01b3: Unknown result type (might be due to invalid IL or missing references) //IL_01b5: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Unknown result type (might be due to invalid IL or missing references) //IL_01c6: Unknown result type (might be due to invalid IL or missing references) //IL_028c: Unknown result type (might be due to invalid IL or missing references) //IL_028e: Unknown result type (might be due to invalid IL or missing references) StartOfRound instance = StartOfRound.Instance; if (!On || !BodyWalk.Can(local) || (Object)(object)instance == (Object)null || (Object)(object)instance.audioListener == (Object)null || instance.allPlayerScripts == null) { Restore(); return; } Vector3 position = ((Component)instance.audioListener).transform.position; Vector3 val = ((!((Object)(object)local.gameplayCamera != (Object)null)) ? (((Component)local).transform.position + Vector3.up * 1.6f) : ((Component)local.gameplayCamera).transform.position); PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts; RaycastHit val3 = default(RaycastHit); foreach (PlayerControllerB val2 in allPlayerScripts) { if ((Object)(object)val2 == (Object)null || (Object)(object)val2 == (Object)(object)local) { continue; } fromBody.TryGetValue(val2, out var value); AudioSource currentVoiceChatAudioSource = val2.currentVoiceChatAudioSource; VoicePlayerState voicePlayerState = val2.voicePlayerState; PlayerVoiceIngameSettings currentVoiceChatIngameSettings = val2.currentVoiceChatIngameSettings; if (value != null && ((Object)(object)value.Source != (Object)(object)currentVoiceChatAudioSource || value.State != voicePlayerState)) { PutBack(value); fromBody.Remove(val2); value = null; } if (!val2.isPlayerControlled || val2.isPlayerDead || !((Object)(object)currentVoiceChatAudioSource != (Object)null) || voicePlayerState == null || !((Object)(object)currentVoiceChatIngameSettings != (Object)null) || currentVoiceChatIngameSettings.set2D) { if (value != null) { PutBack(value); fromBody.Remove(val2); } continue; } Vector3 position2 = ((Component)currentVoiceChatAudioSource).transform.position; float num = Loudness(currentVoiceChatAudioSource, Vector3.Distance(position2, val)); float num2 = Loudness(currentVoiceChatAudioSource, Vector3.Distance(position2, position)); if (num <= num2) { if (value != null) { PutBack(value); fromBody.Remove(val2); } continue; } if (value == null) { Heard heard = new Heard(); heard.Source = currentVoiceChatAudioSource; heard.State = voicePlayerState; heard.Occlude = ((Component)currentVoiceChatAudioSource).GetComponent<OccludeAudio>(); heard.Volume = voicePlayerState.Volume; value = heard; fromBody[val2] = value; if (!saidBody) { saidBody = true; Check.Ok("Hearing", "a voice closer to the body than to the camera is heard from the body"); } } if (Time.time >= value.NextCheck) { value.NextCheck = Time.time + 0.5f; value.Blocked = Physics.Linecast(position2, val, ref val3, 256, (QueryTriggerInteraction)1); } currentVoiceChatAudioSource.spatialBlend = 0f; voicePlayerState.Volume = value.Volume * num; if ((Object)(object)value.Occlude != (Object)null) { value.Occlude.occluded = value.Blocked; } } } internal static void Restore() { if (fromBody.Count == 0) { return; } foreach (KeyValuePair<PlayerControllerB, Heard> item in fromBody) { PutBack(item.Value); } fromBody.Clear(); } private static void PutBack(Heard v) { try { if ((Object)(object)v.Source != (Object)null) { v.Source.spatialBlend = 1f; } if (v.State != null) { v.State.Volume = v.Volume; } } catch (Exception ex) { Check.Problem("Hearing", "putting a voice back: " + ex.Message); } } private static float Loudness(AudioSource src, float distance) { //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Invalid comparison between Unknown and I4 //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Invalid comparison between Unknown and I4 if (!saidRolloff) { saidRolloff = true; Check.Info("Hearing", string.Concat("voice distance: ", src.rolloffMode, " rolloff, ", src.minDistance, "-", src.maxDistance, " m")); } float num = Mathf.Max(0.01f, src.minDistance); float num2 = Mathf.Max(num + 0.01f, src.maxDistance); AudioRolloffMode rolloffMode = src.rolloffMode; if ((int)rolloffMode != 1) { if ((int)rolloffMode == 2) { AnimationCurve val = Curve(src); return (val == null || val.length <= 0) ? 1f : Mathf.Clamp01(val.Evaluate(Mathf.Clamp01(distance / num2))); } return num / Mathf.Clamp(distance, num, num2); } return 1f - Mathf.Clamp01((distance - num) / (num2 - num)); } private static AnimationCurve Curve(AudioSource src) { if (curves.TryGetValue(src, out var value)) { return value; } if (curves.Count > 64) { curves.Clear(); } value = src.GetCustomCurve((AudioSourceCurveType)0); curves[src] = value; if (!saidCurve) { saidCurve = true; Check.Info("Hearing", "voice distance: custom curve of " + ((value != null) ? value.length : 0) + " keys, " + src.minDistance + "-" + src.maxDistance + " m"); } return value; } } internal sealed class PatchTargetMissing : Exception { internal PatchTargetMissing(string message) : base(message) { } } internal static class Hooks { private sealed class Applied { internal MethodBase Original; internal MethodInfo Patch; internal string Part; internal string Kind; } private static readonly List<Applied> applied = new List<Applied>(); private static readonly HashSet<MethodBase> guarded = new HashSet<MethodBase>(); private static readonly HashSet<MethodInfo> tripped = new HashSet<MethodInfo>(); private static readonly List<MethodInfo> toRemove = new List<MethodInfo>(); private static readonly Assembly self = typeof(Hooks).Assembly; internal static int Count { get { lock (applied) { return applied.Count; } } } internal static void Patch(string part, MethodBase original, HarmonyMethod prefix = null, HarmonyMethod postfix = null) { //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Expected O, but got Unknown HarmonyMethod val = prefix ?? postfix; if (val == null || val.method == null) { throw new ArgumentException("a patch without a patch method"); } if (original == null) { throw new PatchTargetMissing("the method to patch wasn't found (for " + Name(val.method) + ")"); } Plugin.Harmony.Patch(original, prefix, postfix, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); bool flag; lock (applied) { flag = guarded.Add(original); } if (flag) { try { Harmony harmony = Plugin.Harmony; HarmonyMethod val2 = new HarmonyMethod(typeof(Hooks), "Guard", (Type[])null); harmony.Patch(original, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, val2, (HarmonyMethod)null); } catch (Exception ex) { Plugin.Log.LogWarning((object)(part + ": no guard on " + Name(original) + " (" + ex.Message + ")")); } } lock (applied) { if (prefix != null) { applied.Add(new Applied { Original = original, Patch = prefix.method, Part = part, Kind = "prefix" }); } if (postfix != null) { applied.Add(new Applied { Original = original, Patch = postfix.method, Part = part, Kind = "postfix" }); } } } internal static void Patch(string part, Type type, string method, Type[] args, HarmonyMethod prefix = null, HarmonyMethod postfix = null) { MethodInfo methodInfo = ((!(type == null)) ? AccessTools.Method(type, method, args, (Type[])null) : null); if (methodInfo == null) { throw new PatchTargetMissing(((!(type != null)) ? "?" : type.Name) + "." + method + " wasn't found (changed in a game update?)"); } Patch(part, methodInfo, prefix, postfix); } internal static HarmonyMethod Method(Type owner, string name) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Expected O, but got Unknown return new HarmonyMethod(AccessTools.Method(owner, name, (Type[])null, (Type[])null)); } internal static bool Has(MethodBase original, MethodInfo patch) { lock (applied) { return applied.Any((Applied a) => a.Original == original && a.Patch == patch); } } internal static int Undo(string part) { List<Applied> list; lock (applied) { list = applied.Where((Applied a) => a.Part == part).ToList(); applied.RemoveAll((Applied a) => a.Part == part); } foreach (Applied item in list) { try { Plugin.Harmony.Unpatch(item.Original, item.Patch); } catch (Exception ex) { Plugin.Log.LogWarning((object)(part + ": couldn't take " + Name(item.Patch) + " out again: " + ex.Message)); } } return list.Count; } private static Exception Guard(Exception __exception) { if (__exception == null) { return null; } Applied applied = null; try { StackFrame[] frames = new StackTrace(__exception, fNeedFileInfo: false).GetFrames(); if (frames == null) { return __exception; } lock (Hooks.applied) { StackFrame[] array = frames; foreach (StackFrame stackFrame in array) { MethodBase method = stackFrame.GetMethod(); if (!(method == null) && !(method.DeclaringType == null) && !(method.DeclaringType.Assembly != self)) { applied = Hooks.applied.FirstOrDefault((Applied a) => a.Patch == method); if (applied != null) { break; } } } if (applied == null) { return __exception; } if (!tripped.Add(applied.Patch)) { return null; } toRemove.Add(applied.Patch); } } catch (Exception) { return __exception; } Check.Problem(applied.Part, "its " + applied.Kind + " " + Name(applied.Patch) + " on " + Name(applied.Original) + " threw and was switched off (the game method carries on without it): " + __exception); return null; } internal static void Flush() { List<Applied> list; lock (applied) { if (toRemove.Count == 0) { return; } list = applied.Where((Applied a) => toRemove.Contains(a.Patch)).ToList(); applied.RemoveAll((Applied a) => toRemove.Contains(a.Patch)); toRemove.Clear(); } foreach (Applied item in list) { try { Plugin.Harmony.Unpatch(item.Original, item.Patch); } catch (Exception ex) { Plugin.Log.LogWarning((object)(item.Part + ": couldn't remove " + Name(item.Patch) + ": " + ex.Message)); } } } internal static string Name(MethodBase method) { return (!(method == null)) ? (((!(method.DeclaringType != null)) ? string.Empty : (method.DeclaringType.Name + ".")) + method.Name) : "?"; } } internal sealed class Key { private InputAction action; internal string Path { get; private set; } internal bool Pressed { [CompilerGenerated] get { return action.WasPressedThisFrame(); } } internal bool Released { [CompilerGenerated] get { return action.WasReleasedThisFrame(); } } internal bool Held { [CompilerGenerated] get { return action.IsPressed(); } } internal bool Found { [CompilerGenerated] get { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) return action.controls.Count > 0; } } internal string Label { [CompilerGenerated] get { return Keys.Label(Path); } } internal Key(string path) { Set(path); } internal Key(ConfigEntry<string> entry) { Key key = this; Set(entry.Value); entry.SettingChanged += delegate { key.Set(entry.Value); }; } private void Set(string text) { //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Expected O, but got Unknown if (action != null) { action.Disable(); action.Dispose(); } Path = Keys.ToPath(text); action = new InputAction((string)null, (InputActionType)1, Path, (string)null, (string)null, (string)null); action.Enable(); } } internal static class Keys { internal static Key Ghost; internal static Key Back; internal static Key TakeOver; internal static Key NextPlayer; internal static Key PrevTarget; internal static Key NextTarget; internal static Key Primary; internal static Key Secondary; internal static Key Ai; internal static Key Light; internal static Key FreeLook; internal static Key Panel; internal static Key Cheat; internal static Key Teleport; internal static Key SetFree; internal static Key HearBody; internal static Key WalkBody; internal static Key TalkAsEnemy; internal static Key BodyForward; internal static Key BodyBack; internal static Key BodyLeft; internal static Key BodyRight; internal static readonly List<Key> Slots = new List<Key>(); internal static readonly List<Key> Digits = new List<Key>(); [CompilerGenerated] private static Dictionary<string, int> <>f__switch$map1; internal static int SlotsBeforeDigits { get; private set; } internal static void Make() { Ghost = new Key(Settings.GhostKey); Back = new Key(Settings.BackKey); TakeOver = new Key(Settings.TakeOverKey); NextPlayer = new Key(Settings.NextPlayerKey); PrevTarget = new Key(Settings.PrevTargetKey); NextTarget = new Key(Settings.NextTargetKey); Primary = new Key(Settings.PrimaryKey); Secondary = new Key(Settings.SecondaryKey); Ai = new Key(Settings.AiKey); Light = new Key(Settings.LightKey); FreeLook = new Key(Settings.FreeLookKey); Panel = new Key(Settings.PanelKey); Cheat = new Key(Settings.CheatKey); Teleport = new Key(Settings.TeleportKey); SetFree = new Key(Settings.SetFreeKey); HearBody = new Key(Settings.HearBodyKey); WalkBody = new Key(Settings.BodyWalkKey); TalkAsEnemy = new Key(Settings.TalkAsEnemyKey); BodyForward = new Key("<Keyboard>/upArrow"); BodyBack = new Key("<Keyboard>/downArrow"); BodyLeft = new Key("<Keyboard>/leftArrow"); BodyRight = new Key("<Keyboard>/rightArrow"); MakeSlots(); Settings.EnemyKeys.SettingChanged += delegate { MakeSlots(); }; } private static void MakeSlots() { Slots.Clear(); string[] array = Settings.EnemyKeys.Value.Split(','); foreach (string text in array) { if (text.Trim().Length > 0) { Slots.Add(new Key(text)); } } if (Slots.Count == 0) { string[] array2 = ((string)((ConfigEntryBase)Settings.EnemyKeys).DefaultValue).Split(','); foreach (string path in array2) { Slots.Add(new Key(path)); } } if (Digits.Count == 0) { string[] array3 = new string[10] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" }; foreach (string path2 in array3) { Digits.Add(new Key(path2)); } } SlotsBeforeDigits = Slots.Count; for (int l = 0; l < Slots.Count; l++) { string path3 = Slots[l].Path; if (path3.StartsWith("<Keyboard>/") && path3.Length == 12 && char.IsDigit(path3[11])) { SlotsBeforeDigits = l; break; } } } internal static string SlotsFound() { int num = 0; foreach (Key slot in Slots) { if (slot.Found) { num++; } } return num + " of " + Slots.Count; } internal static string ToPath(string text) { string text2 = (text ?? string.Empty).Trim(); if (text2.Contains("<")) { return text2; } switch (text2.ToLowerInvariant()) { case "lmb": case "mouse1": return "<Mouse>/leftButton"; case "rmb": case "mouse2": return "<Mouse>/rightButton"; case "mmb": case "mouse3": return "<Mouse>/middleButton"; case "esc": return "<Keyboard>/escape"; case "`": return "<Keyboard>/backquote"; case "alt": return "<Keyboard>/leftAlt"; case "ctrl": return "<Keyboard>/leftCtrl"; case "shift": return "<Keyboard>/leftShift"; default: return "<Keyboard>/" + text2.ToLowerInvariant(); } } internal static string Label(string path) { string text; try { text = InputControlPath.ToHumanReadableString(path, (HumanReadableStringOptions)2, (InputControl)null); } catch (Exception) { text = path; } if (text != null) { if (<>f__switch$map1 == null) { Dictionary<string, int> dictionary = new Dictionary<string, int>(9); dictionary.Add("Left Button", 0); dictionary.Add("Right Button", 1); dictionary.Add("Middle Button", 2); dictionary.Add("Escape", 3); dictionary.Add("Backquote", 4); dictionary.Add("Left Alt", 5); dictionary.Add("Right Alt", 6); dictionary.Add("Page Up", 7); dictionary.Add("Page Down", 8); <>f__switch$map1 = dictionary; } if (<>f__switch$map1.TryGetValue(text, out var value)) { switch (value) { case 0: return "LMB"; case 1: return "RMB"; case 2: return "MMB"; case 3: return "Esc"; case 4: return "`"; case 5: return "L-Alt"; case 6: return "R-Alt"; case 7: return "PgUp"; case 8: return "PgDn"; } } } return (text.Length != 1) ? text : text.ToUpperInvariant(); } internal static InputAction Game(string name) { try { InputActionAsset actions = InputSystem.actions; InputAction val = ((!((Object)(object)actions != (Object)null)) ? null : actions.FindAction(name, false)); if (val == null && (Object)(object)IngamePlayerSettings.Instance != (Object)null && (Object)(object)IngamePlayerSettings.Instance.playerInput != (Object)null) { val = IngamePlayerSettings.Instance.playerInput.actions.FindAction(name, false); } return val; } catch (Exception) { return null; } } internal static string GameLabel(string name) { InputAction val = Game(name); if (val == null) { return name; } try { string bindingDisplayString = InputActionRebindingExtensions.GetBindingDisplayString(val, 0, (DisplayStringOptions)0); return (!string.IsNullOrEmpty(bindingDisplayString)) ? bindingDisplayString : name; } catch (Exception) { return name; } } internal static bool GamePressed(string name) { InputAction val = Game(name); return val != null && val.WasPressedThisFrame(); } internal static bool GameHeld(string name) { InputAction val = Game(name); return val != null && val.IsPressed(); } } internal static class Lobby { internal const string Part = "Lobby marking"; internal const char Marker = '\u200b'; internal const string DataKey = "controlcompanyreloaded"; private const string Label = "[ENEMY CONTROL] "; internal static void Start() { string part = "Lobby marking"; Type typeFromHandle = typeof(GameNetworkManager); string method = "SteamMatchmaking_OnLobbyCreated"; Type[] args = new Type[2] { typeof(Result), typeof(Lobby) }; HarmonyMethod postfix = Hooks.Method(typeof(Lobby), "AfterLobbyCreated"); Hooks.Patch(part, typeFromHandle, method, args, null, postfix); method = "Lobby marking"; typeFromHandle = typeof(LobbySlot); part = "Awake"; args = Type.EmptyTypes; postfix = Hooks.Method(typeof(Lobby), "AfterSlotAwake"); Hooks.Patch(method, typeFromHandle, part, args, null, postfix); } [MethodImpl(MethodImplOptions.NoInlining)] private static void AfterLobbyCreated(Result __0, Lobby __1) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 if ((int)__0 != 1 || !Settings.MarkLobbies.Value) { return; } GameNetworkManager instance = GameNetworkManager.Instance; if (!((Object)(object)instance == (Object)null) && instance.lobbyHostSettings != null && instance.lobbyHostSettings.isLobbyPublic) { string text = ((Lobby)(ref __1)).GetData("name") ?? string.Empty; if (text.IndexOf('\u200b') < 0) { int num = ((text.Length <= 1 || !char.IsSurrogatePair(text, 0)) ? 1 : 2); string text2 = ((text.Length <= 0) ? '\u200b'.ToString() : (text.Substring(0, num) + '\u200b' + text.Substring(num))); ((Lobby)(ref __1)).SetData("name", text2); } ((Lobby)(ref __1)).SetData("controlcompanyreloaded", "1.0.0"); Check.Ok("Lobby marking", "marked the public lobby"); } } [MethodImpl(MethodImplOptions.NoInlining)] private static void AfterSlotAwake(LobbySlot __instance) { if (Settings.HighlightLobbies.Value && !((Object)(object)__instance == (Object)null)) { ((MonoBehaviour)__instance).StartCoroutine(Highlight(__instance)); } } private static IEnumerator Highlight(LobbySlot slot) { yield return null; if (!((Object)(object)slot == (Object)null) && !((Object)(object)slot.LobbyName == (Object)null)) { bool marked = false; try { string text = ((Lobby)(ref slot.thisLobby)).GetData("name") ?? string.Empty; marked = text.IndexOf('\u200b') >= 0 || !string.IsNullOrEmpty(((Lobby)(ref slot.thisLobby)).GetData("controlcompanyreloaded")); } catch (Exception) { } if (marked && !((TMP_Text)slot.LobbyName).text.StartsWith("[ENEMY CONTROL] ")) { ((Graphic)slot.LobbyName).color = new Color(0.88f, 0.19f, 0.16f, 1f); ((TMP_Text)slot.LobbyName).text = "[ENEMY CONTROL] " + ((TMP_Text)slot.LobbyName).text; Check.Ok("Lobby marking", "highlighted a lobby whose host can control enemies"); } } } } internal struct PanelLine { internal readonly string Text; internal readonly int Size; internal readonly float Gap; internal PanelLine(string text, int size, float gap) { Text = text; Size = size; Gap = gap; } internal bool Same(PanelLine o) { return Size == o.Size && Gap == o.Gap && Text == o.Text; } } internal static class Panel { internal const string Part = "Panel"; internal const string Red = "#FF4B3E"; internal const string Grey = "#A0A0A0"; internal const string Yellow = "#FFD24A"; internal const int TitleSize = 28; internal const int TextSize = 24; internal const int SmallSize = 20; internal const float GroupGap = 18f; internal const float SmallGroupGap = 10f; private static GameObject root; private static RectTransform box; private static Font font; private static readonly List<Text> pool = new List<Text>(); private static readonly List<PanelLine> shown = new List<PanelLine>(); private static bool hidden; private static bool saidLayout; internal static void Toggle() { hidden = !hidden; Apply(); } internal static void Show(List<PanelLine> lines) { //IL_0043: Unknown result type (might be due to invalid IL or missing references) if (Make()) { root.SetActive(true); if (!SameAsShown(lines)) { Layout(lines); } Apply(); float value = Settings.PanelScale.Value; ((Transform)box).localScale = new Vector3(value, value, 1f); } } internal static void Hide() { if ((Object)(object)root != (Object)null) { root.SetActive(false); } } private static void Apply() { if ((Object)(object)box != (Object)null) { ((Component)box).gameObject.SetActive(!hidden && shown.Count > 0); } } private static bool SameAsShown(List<PanelLine> lines) { if (lines.Count != shown.Count) { return false; } for (int i = 0; i < lines.Count; i++) { if (!lines[i].Same(shown[i])) { return false; } } return true; } private static void Layout(List<PanelLine> lines) { //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) ((Component)box).gameObject.SetActive(true); shown.Clear(); float num = 0f; for (int i = 0; i < lines.Count; i++) { PanelLine item = lines[i]; shown.Add(item); Text val = ((i >= pool.Count) ? AddLine() : pool[i]); if (!((Component)val).gameObject.activeSelf) { ((Component)val).gameObject.SetActive(true); } if (val.fontSize != item.Size) { val.fontSize = item.Size; } if (val.text != item.Text) { val.text = item.Text; } num += item.Gap; float num2 = val.preferredHeight; if (num2 <= 0f || float.IsNaN(num2)) { num2 = (float)item.Size * 1.15f; } RectTransform rectTransform = ((Graphic)val).rectTransform; rectTransform.anchoredPosition = new Vector2(0f, 0f - num); rectTransform.sizeDelta = new Vector2(1000f, num2); num += num2; } for (int j = lines.Count; j < pool.Count; j++) { if (((Component)pool[j]).gameObject.activeSelf) { ((Component)pool[j]).gameObject.SetActive(false); } } if (!saidLayout && lines.Count > 2) { saidLayout = true; Check.Info("Panel", "line heights: " + Heights(lines.Count)); } } private static string Heights(int count) { //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) string text = string.Empty; for (int i = 0; i < count && i < 4; i++) { string text2 = text; text = text2 + ((i <= 0) ? string.Empty : ", ") + pool[i].fontSize + " px text " + ((Graphic)pool[i]).rectTransform.sizeDelta.y.ToString("0.0"); } return text; } private static bool Make() { //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Expected O, but got Unknown //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Expected O, but got Unknown //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Expected O, but got Unknown //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)root != (Object)null) { return true; } try { font = LoadFont(); if ((Object)(object)font == (Object)null) { throw new Exception("no font found (not Unity's built-in one, and no Arial-like font on this system)"); } root = new GameObject("Control Company Reloaded panel"); Object.DontDestroyOnLoad((Object)(object)root); Canvas val = root.AddComponent<Canvas>(); val.renderMode = (RenderMode)0; val.sortingOrder = 400; CanvasScaler val2 = root.AddComponent<CanvasScaler>(); val2.uiScaleMode = (ScaleMode)1; val2.referenceResolution = new Vector2(1920f, 1080f); val2.matchWidthOrHeight = 1f; GameObject val3 = new GameObject("Lines", new Type[1] { typeof(RectTransform) }); val3.transform.SetParent(root.transform, false); box = (RectTransform)val3.transform; RectTransform obj = box; Vector2 val4 = new Vector2(1f, 1f); box.pivot = val4; val4 = val4; box.anchorMax = val4; obj.anchorMin = val4; box.anchoredPosition = new Vector2(-40f, -34f); box.sizeDelta = new Vector2(1000f, 1000f); Check.Ok("Panel", "made the panel (font " + ((Object)font).name + ")"); return true; } catch (Exception ex) { Check.Problem("Panel", "couldn't make the panel: " + ex); if ((Object)(object)root != (Object)null) { Object.Destroy((Object)(object)root); } root = null; box = null; pool.Clear(); shown.Clear(); return false; } } private static Text AddLine() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject("Line " + pool.Count); val.transform.SetParent((Transform)(object)box, false); Text val2 = val.AddComponent<Text>(); val2.font = font; val2.fontSize = 24; val2.alignment = (TextAnchor)2; val2.supportRichText = true; val2.horizontalOverflow = (HorizontalWrapMode)1; val2.verticalOverflow = (VerticalWrapMode)1; ((Graphic)val2).color = Color.white; ((Graphic)val2).raycastTarget = false; RectTransform rectTransform = ((Graphic)val2).rectTransform; Vector2 val3 = (rectTransform.pivot = new Vector2(1f, 1f)); val3 = (rectTransform.anchorMax = val3); rectTransform.anchorMin = val3; Outline val6 = val.AddComponent<Outline>(); ((Shadow)val6).effectColor = new Color(0f, 0f, 0f, 0.9f); ((Shadow)val6).effectDistance = new Vector2(1.4f, -1.4f); pool.Add(val2); return val2; } private static Font LoadFont() { string[] array = new string[2] { "LegacyRuntime.ttf", "Arial.ttf" }; foreach (string text in array) { try { Font builtinResource = Resources.GetBuiltinResource<Font>(text); if ((Object)(object)builtinResource != (Object)null) { return builtinResource; } } catch (Exception) { } } try { return Font.CreateDynamicFontFromOSFont(new string[3] { "Arial", "Liberation Sans", "DejaVu Sans" }, 24); } catch (Exception) { return null; } } internal static string Key(string label) { return "<color=#FF4B3E>" + label + "</color>"; } internal static string Dim(string s) { return "<color=#A0A0A0>" + s + "</color>"; } internal static string Warn(string s) { return "<color=#FFD24A>" + s + "</color>"; } internal static string Title(string s) { return "<b><color=#FF4B3E>" + s + "</color></b>"; } } internal sealed class Possession { internal const string Part = "Enemy control"; internal static Possession Current; internal readonly EnemyAI Enemy; internal readonly Driver Driver; internal readonly string Title; internal readonly bool Spawned; private static readonly HashSet<EnemyAI> made = new HashSet<EnemyAI>(); private float yaw; private float syncTimer; private Vector3 lastPlaced; private bool placedOnce; private bool saidMoved; private bool saidSynced; internal static EnemyAI Arriving; private bool wasLent; private bool hadDestination; private bool hadChase; private int stateWhenTaken; private float ownThreshold = -1f; private float ownerCheckAt = -1f; private int ownerAsks; private static readonly List<NavMeshAgent> released = new List<NavMeshAgent>(); private static bool saidOwnBody; internal bool OnAI { get; private set; } internal static bool Ready { get; private set; } internal float Yaw { [CompilerGenerated] get { return yaw; } } internal bool Alive { [CompilerGenerated] get { return (Object)(object)Enemy != (Object)null && !Enemy.isEnemyDead; } } internal bool OffSide { [CompilerGenerated] get { return (Object)(object)Enemy != (Object)null && (Object)(object)Enemy.enemyType != (Object)null && Enemy.isOutside != Enemy.enemyType.isOutsideEnemy; } } internal bool Lent { get { if ((Object)(object)Enemy == (Object)null) { return false; } try { return Driver.InPlayersHands(Enemy); } catch (Exception) { return false; } } } private static ulong HostId { [CompilerGenerated] get { return (!((Object)(object)NetworkManager.Singleton != (Object)null)) ? 0 : NetworkManager.Singleton.LocalClientId; } } internal bool MayMove { [CompilerGenerated] get { return !OnAI && Alive && SafeCanMove(); } } private Possession(EnemyAI enemy, Driver driver, string title, bool spawned) { //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) Enemy = enemy; Driver = driver; Title = title; Spawned = spawned; yaw = ((Component)enemy).transform.eulerAngles.y; } internal static void Made(EnemyAI e) { if (!((Object)(object)e == (Object)null)) { made.Add(e); Compat.LeaveOut(e); } } internal static void ForgetRound() { made.Clear(); } internal static bool Driving(EnemyAI e) { return Current != null && (Object)(object)Current.Enemy == (Object)(object)e && !Current.OnAI; } private static bool Held(EnemyAI e) { return Current != null && (Object)(object)Current.Enemy == (Object)(object)e && (!Current.OnAI || Current.OffSide) && !Current.Lent; } internal static void Start() { Hooks.Patch("Enemy control", typeof(EnemyAI), "ChangeOwnershipOfEnemy", new Type[1] { typeof(ulong) }, Hooks.Method(typeof(Possession), "KeepWithHost")); Hooks.Patch("Enemy control", typeof(EnemyAI), "ChangeEnemyOwnerServerRpc", new Type[1] { typeof(ulong) }, Hooks.Method(typeof(Possession), "KeepWithHost")); Hooks.Patch("Enemy control", typeof(NetworkObject), "ChangeOwnership", new Type[1] { typeof(ulong) }, Hooks.Method(typeof(Possession), "KeepObjectWithHost")); Hooks.Patch("Enemy control", typeof(EnemyAI), "DoAIInterval", Type.EmptyTypes, Hooks.Method(typeof(Possession), "SkipAI")); Hooks.Patch("Enemy control", typeof(EnemyAI), "CheckTimeOfDayToLeave", Type.EmptyTypes, Hooks.Method(typeof(Possession), "StayForTheDay")); Hooks.Patch("Enemy control", typeof(EnemyAI), "MeetsStandardPlayerCollisionConditions", new Type[3] { typeof(Collider), typeof(bool), typeof(bool) }, Hooks.Method(typeof(Possession), "NotOwnBody")); Hooks.Patch("Enemy control", typeof(SandWormAI), "OnCollideWithPlayer", new Type[1] { typeof(Collider) }, Hooks.Method(typeof(Possession), "NoTouch")); Hooks.Patch("Enemy control", typeof(LassoManAI), "OnCollideWithPlayer", new Type[1] { typeof(Collider) }, Hooks.Method(typeof(Possession), "NoTouch")); Hooks.Patch("Enemy control", typeof(PlayerControllerB), "HasLineOfSightToPosition", new Type[5] { typeof(Vector3), typeof(float), typeof(int), typeof(float), typeof(int) }, Hooks.Method(typeof(Possession), "BodyDoesntWatch")); Ready = true; } [MethodImpl(MethodImplOptions.NoInlining)] private static bool KeepWithHost(EnemyAI __instance, ulong __0) { if (__0 == HostId) { return true; } if ((Object)(object)__instance == (Object)(object)Arriving) { return false; } return !Held(__instance); } [MethodImpl(MethodImplOptions.NoInlining)] private static bool KeepObjectWithHost(NetworkObject __instance, ulong __0) { if (Current == null || (Object)(object)Current.Enemy == (Object)null || __0 == HostId) { return true; } return !((Object)(object)((NetworkBehaviour)Current.Enemy).NetworkObject == (Object)(object)__instance) || !Held(Current.Enemy); } [MethodImpl(MethodImplOptions.NoInlining)] private static bool SkipAI(EnemyAI __instance) { return !Driving(__instance) || !Current.Driver.Pause; } private static void PausePatchFor(Type type) { //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Expected O, but got Unknown MethodInfo methodInfo = AccessTools.Method(type, "DoAIInterval", Type.EmptyTypes, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(typeof(Possession), "SkipAI", (Type[])null, (Type[])null); if (!(methodInfo == null) && !(methodInfo.DeclaringType == typeof(EnemyAI)) && !Hooks.Has(methodInfo, methodInfo2)) { Hooks.Patch("Enemy control", methodInfo, new HarmonyMethod(methodInfo2)); } } internal static Possession Take(EnemyAI enemy, string title, bool spawned) { Driver driver = Drivers.For(enemy); try { PausePatchFor(((object)enemy).GetType()); } catch (Exception ex) { Check.Problem("Enemy control", "couldn't pause the AI of " + ((object)enemy).GetType().Name + " (it keeps deciding for itself): " + ex.Message); } Possession possession = (Current = new Possession(enemy, driver, title, spawned)); try { possession.Grab(); } catch { Current = null; try { possession.FreeAgent(); } catch (Exception) { } throw; } Check.Info("Enemy control", "took control of " + title + " (" + ((object)enemy).GetType().Name + ", driver " + driver.GetType().Name + ")"); return possession; } private void Grab() { //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) OnAI = false; placedOnce = false; wasLent = false; hadDestination = Enemy.moveTowardsDestination; hadChase = Enemy.movingTowardsTargetPlayer; stateWhenTaken = Enemy.currentBehaviourStateIndex; ownThreshold = Enemy.updatePositionThreshold; Enemy.updatePositionThreshold = Mathf.Min(ownThreshold, 0.2f); TakeOwnership(); HoldAgent(); try { Driver.OnTake(Enemy); } catch (Exception ex) { Check.Problem(Driver.GetType().Name, "taking control: " + ex); } yaw = ((Component)Enemy).transform.eulerAngles.y; } private void TakeOwnership() { ownerCheckAt = -1f; ownerAsks = 0; if (!Lent) { ulong hostId = HostId; if ((Object)(object)((NetworkBehaviour)Enemy).NetworkObject != (Object)null && ((NetworkBehaviour)Enemy).NetworkObject.OwnerClientId != hostId) { Enemy.ChangeEnemyOwnerServerRpc(hostId); } ownerCheckAt = Time.time + 1f; ownerAsks = 0; } } private void CheckOwnership() { if (!(ownerCheckAt < 0f) && !(Time.time < ownerCheckAt) && !((Object)(object)((NetworkBehaviour)Enemy).NetworkObject == (Object)null)) { ulong hostId = HostId; if (((NetworkBehaviour)Enemy).NetworkObject.OwnerClientId == hostId) { ownerCheckAt = -1f; Check.Ok("Enemy control", "the host owns the controlled enemy"); return; } if (ownerAsks++ < 3) { Enemy.ChangeEnemyOwnerServerRpc(hostId); ownerCheckAt = Time.time + 1f; return; } ownerCheckAt = -1f; Check.Problem("Enemy control", "couldn't make the host own " + Title + " (owner " + ((NetworkBehaviour)Enemy).NetworkObject.OwnerClientId + "): its attacks may not reach the others"); } } private void HoldAgent() { NavMeshAgent agent = Enemy.agent; if (!((Object)(object)agent == (Object)null) && ((Behaviour)agent).enabled) { agent.updatePosition = false; agent.updateRotation = false; if (agent.isOnNavMesh) { agent.isStopped = true; agent.ResetPath(); } } } private void FreeAgent() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0064: 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) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) NavMeshAgent agent = Enemy.agent; if ((Object)(object)agent == (Object)null) { return; } Vector3 position = ((Component)Enemy).transform.position; agent.updatePosition = true; agent.updateRotation = true; if (!((Behaviour)agent).enabled) { released.Add(agent); return; } RoundManager instance = RoundManager.Instance; Vector3 val = position; if ((Object)(object)instance != (Object)null) { val = instance.GetNavMeshPosition(position, default(NavMeshHit), 5f, -1); RaycastHit val2 = default(RaycastHit); if (!instance.GotNavMeshPositionResult && Physics.Raycast(position, Vector3.down, ref val2, 300f, Game.Mask("Default", "Room", "Colliders", "Terrain", "MiscLevelGeometry"), (QueryTriggerInteraction)1)) { val = instance.GetNavMeshPosition(((RaycastHit)(ref val2)).point, default(NavMeshHit), 10f, -1); } } if ((Object)(object)instance != (Object)null && !instance.GotNavMeshPositionResult && agent.isOnNavMesh) { val = agent.nextPosition; } agent.Warp(val); if (agent.isOnNavMesh) { agent.isStopped = false; } else { released.Add(agent); } } internal static void Settle() { for (int num = released.Count - 1; num >= 0; num--) { NavMeshAgent val = released[num]; bool flag = Current != null && !Current.OnAI && (Object)(object)Current.Enemy != (Object)null && (Object)(object)Current.Enemy.agent == (Object)(object)val; if ((Object)(object)val == (Object)null || flag) { released.RemoveAt(num); } else if (((Behaviour)val).enabled && val.isOnNavMesh) { val.isStopped = false; released.RemoveAt(num); } } } internal void GiveToAI() { //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) if (!OnAI && !((Object)(object)Enemy == (Object)null)) { try { Driver.OnGiveBack(Enemy); } catch (Exception ex) { Check.Problem(Driver.GetType().Name, "handing to the AI: " + ex); } if (hadDestination) { Enemy.moveTowardsDestination = true; } Enemy.prevDestination = Vector3.zero; PlayerControllerB targetPlayer = Enemy.targetPlayer; if (hadChase && Enemy.currentBehaviourStateIndex == stateWhenTaken && (Object)(object)targetPlayer != (Object)null && targetPlayer.isPlayerControlled && !targetPlayer.isPlayerDead) { Enemy.movingTowardsTargetPlayer = true; } if (ownThreshold >= 0f) { Enemy.updatePositionThreshold = ownThreshold; } OnAI = true; FreeAgent(); if (!Lent) { ResetClientsOwnership(); } Check.Info("Enemy control", "handed " + Title + " to its AI"); } } internal void TakeBack() { if (OnAI && !((Object)(object)Enemy == (Object)null)) { Grab(); Check.Info("Enemy control", "took " + Title + " back from its AI"); } } private void ResetClientsOwnership() { try { PlayerControllerB local = Game.Local; if ((Object)(object)local != (Object)null && ((NetworkBehaviour)Enemy).IsSpawned) { Enemy.ChangeEnemyOwnerClientRpc((int)local.playerClientId); } } catch (Exception ex) { Check.Problem("Enemy control", "resetting the ownership bookkeeping: " + ex.Message); } } internal bool TryRemove(bool force, bool despawn, out string refused) { refused = null; if ((Object)(object)Enemy == (Object)null) { Current = null; return true; } if (!despawn && Alive) { if (!OnAI) { GiveToAI(); } Check.Info("Enemy control", "left " + Title + " in the round, with its AI"); Current = null; return true; } if (!force && Alive) { refused = Driver.RefuseRemove(Enemy); if (refused != null) { return false; } if (!Driver.ReadyToRemove(Enemy)) { return false; } } try { if (Alive) { Driver.BeforeRemove(Enemy); } } catch (Exception ex) { Check.Problem(Driver.GetType().Name, "before removing: " + ex); } if (Alive && (Object)(object)((NetworkBehaviour)Enemy).NetworkObject != (Object)null && ((NetworkBehaviour)Enemy).NetworkObject.IsSpawned && (Object)(object)RoundManager.Instance != (Object)null) { Despawn(Enemy); Check.Info("Enemy control", "removed " + Title + ((!Spawned) ? " (cheat: it wasn't one of ours)" : string.Empty)); } else if ((Object)(object)Enemy != (Object)null) { OnAI = true; ResetClientsOwnership(); } Current = null; return true; } internal string SetFree() { if ((Object)(object)Enemy == (Object)null) { Current = null; return null; } if (!Alive) { return "It's dead"; } if (OffSide) { return "It can't stay on this side"; } if (!OnAI) { GiveToAI(); } Check.Info("Enemy control", "set " + Title + " free: it stays in the round with its AI"); Current = null; return null; } internal static void Despawn(EnemyAI e) { RoundManager instance = RoundManager.Instance; if ((Object)(object)instance == (Object)null || (Object)(object)e == (Object)null || (Object)(object)((NetworkBehaviour)e).NetworkObject == (Object)null || !((NetworkBehaviour)e).NetworkObject.IsSpawned) { return; } bool flag = made.Remove(e); if (flag) { Compat.LeaveOut(e); } bool cannotSpawnMoreInsideEnemies = instance.cannotSpawnMoreInsideEnemies; if (flag && (Object)(object)e.enemyType != (Object)null) { float powerLevel = e.enemyType.PowerLevel; if (e.enemyType.isOutsideEnemy) { instance.currentOutsideEnemyPower += powerLevel; } else if (e.enemyType.isDaytimeEnemy) { instance.currentDaytimeEnemyPower += powerLevel; } else { instance.currentEnemyPower += powerLevel; } } e.removedPowerLevel = true; instance.DespawnEnemyOnServer(((NetworkBehaviour)e).NetworkObject); if (flag) { instance.cannotSpawnMoreInsideEnemies = cannotSpawnMoreInsideEnemies; } } internal static void Abandon() { Possession current = Current; if (current == null) { return; } if (current.Spawned) { Drop(); return; } try { current.GiveToAI(); } catch (Exception ex) { Check.Problem("Enemy control", "handing it back after a failed take-over: " + ex.Message); } Current = null; } internal static void Drop() { if (Current != null) { try { Current.TryRemove(force: true, Current.Spawned, out var _); } catch (Exception ex) { Check.Problem("Enemy control", "letting go at the end of the round: " + ex.Message); } Current = null; } } private bool SafeCanMove() { try { return Driver.CanMove(Enemy); } catch (Exception ex) { Check.Problem(Driver.GetType().Name, "CanMove: " + ex); return true; } } internal void Follow(Rig rig, bool moving, bool sprinting, bool aiming, bool freeLook) { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0268: Unknown result type (might be due to invalid IL or missing references) //IL_01d7: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_0192: Unknown result type (might be due to invalid IL or missing references) //IL_0197: Unknown result type (might be due to invalid IL or missing references) //IL_019c: Unknown result type (might be due to invalid IL or missing references) //IL_027e: Unknown result type (might be due to invalid IL or missing references) //IL_0283: Unknown result type (might be due to invalid IL or missing references) //IL_01bb: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_030f: Unknown result type (might be due to invalid IL or missing references) //IL_0314: Unknown result type (might be due to invalid IL or missing references) //IL_02f4: 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) if ((Object)(object)Enemy == (Object)null) { return; } if (OnAI || !Alive) { rig.Track(((Component)Enemy).transform.position); return; } bool lent = Lent; if (lent != wasLent) { wasLent = lent; if (lent) { Check.Info("Enemy control", Title + " is in a player's hands: theirs until they let go"); } else { PlayerControllerB local = Game.Local; if ((Object)(object)local != (Object)null) { Enemy.currentOwnershipOnThisClient = (int)local.playerClientId; } TakeOwnership(); Check.Info("Enemy control", Title + " was let go: back with the host"); } } if (lent) { rig.Track(((Component)Enemy).transform.position); if (!((NetworkBehaviour)Enemy).IsOwner) { Check.Ok("Enemy control", "a player holding the driven enemy owns it while holding it, as in the game"); } try { Driver.Tick(Enemy, moving, sprinting); return; } catch (Exception ex) { Check.Problem(Driver.GetType().Name, "Tick: " + ex); return; } } HoldAgent(); CheckOwnership(); bool flag = SafeCanMove(); bool flag2; try { flag2 = Driver.CanTurn(Enemy); } catch (Exception) { flag2 = flag; } if (flag && placedOnce) { Vector3 val = ((Component)Enemy).transform.position - lastPlaced; if (((Vector3)(ref val)).sqrMagnitude > 9f) { rig.Teleport(((Component)Enemy).transform.position); } } if (flag) { ((Component)Enemy).transform.position = rig.Feet; NavMeshAgent agent = Enemy.agent; if ((Object)(object)agent != (Object)null && ((Behaviour)agent).enabled && agent.isOnNavMesh) { agent.nextPosition = rig.Feet; } if (moving && !saidMoved) { saidMoved = true; Check.Ok("Enemy control", "moved " + Title + " with the player's keys"); } } else { rig.Track(((Component)Enemy).transform.position); } lastPlaced = ((Component)Enemy).transform.position; placedOnce = true; if (flag2 && !freeLook && (moving || aiming)) { yaw = Mathf.MoveTowardsAngle(yaw, rig.Yaw, Driver.TurnSpeed * Time.deltaTime); } if (flag2) { ((Component)Enemy).transform.rotation = Quaternion.Euler(0f, yaw, 0f); } else { yaw = ((Component)Enemy).transform.eulerAngles.y; } Enemy.enemySwimTimer = 0f; try { Driver.Tick(Enemy, moving, sprinting); } catch (Exception ex3) { Check.Problem(Driver.GetType().Name, "Tick: " + ex3); } syncTimer -= Time.deltaTime; if (syncTimer <= 0f && !Enemy.inSpecialAnimation) { syncTimer = 0.1f; try { Driver.SendPosition(Enemy); } catch (Exception ex4) { Check.Problem(Driver.GetType().Name, "SendPosition: " + ex4); } if (moving && !saidSynced) { saidSynced = true; Check.Ok("Enemy control", "sent " + Title + "'s position to the other players"); } } } [MethodImpl(MethodImplOptions.NoInlining)] private static bool StayForTheDay(EnemyAI __instance) { return !Driving(__instance) && (Object)(object)__instance != (Object)(object)Arriving; } [MethodImpl(MethodImplOptions.NoInlining)] private static bool NotOwnBody(EnemyAI __instance, Collider __0, ref PlayerControllerB __result) { if (!Driving(__instance)) { return true; } __result = null; if (!saidOwnBody && (Object)(object)__0 != (Object)null && (Object)(object)Game.Local != (Object)null && (Object)(object)((Component)__0).gameObject == (Object)(object)((Component)Game.Local).gameObject) { saidOwnBody = true; Check.Ok("Enemy control", "the driven enemy touched the host's own body and left it alone"); } return false; } [MethodImpl(MethodImplOptions.NoInlining)] private static bool NoTouch(EnemyAI __instance) { return !Driving(__instance); } [MethodImpl(MethodImplOptions.NoInlining)] private static bool BodyDoesntWatch(PlayerControllerB __instance, Vector3 __0, ref bool __result) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) Possession current = Current; if (current == null || current.OnAI || (Object)(object)current.Enemy == (Object)null || (Object)(object)__instance != (Object)(object)Game.Local) { return true; } Vector3 val = __0 - ((Component)current.Enemy).transform.position; if (((Vector3)(ref val)).sqrMagnitude > 16f) { return true; } __result = false; return false; } internal void Face(Vector3 dir) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) dir.y = 0f; if (!((Object)(object)Enemy == (Object)null) && !(((Vector3)(ref dir)).sqrMagnitude < 0.01f)) { Quaternion val = Quaternion.LookRotation(dir); yaw = ((Quaternion)(ref val)).eulerAngles.y; ((Component)Enemy).transform.rotation = Quaternion.Euler(0f, yaw, 0f); } } internal float SpeedNow(bool sprint) { try { return Driver.Speed(Enemy, sprint); } catch (Exception) { return (!sprint) ? Driver.Walk : Driver.Run; } } internal float AccelNow() { try { return Driver.Acceleration(Enemy); } catch (Exception) { return 0f; } } } internal sealed class Rig { internal sealed class Touch : MonoBehaviour { internal DoorLock Door; private void OnControllerColliderHit(ControllerColliderHit hit) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)hit.collider == (Object)null) && !(hit.normal.y > 0.5f)) { DoorLock componentInParent = ((Component)hit.collider).GetComponentInParent<DoorLock>(); if ((Object)(object)componentInParent != (Object)null) { Door = componentInParent; } } } } internal const string Part = "Camera"; private readonly GameObject root; private readonly CharacterController body; internal readonly Camera Cam; private readonly Light lamp; private float yaw; private float pitch; private float vertical; private bool ghost; private bool unsynced; private bool flying; private Vector3 lastGround; private Vector3 planar; private float ghostEye = 2.35f; private float ghostHeight = 2.6f; private float ghostRadius = 0.4f; private float lastJumpTap = -10f; private const float DoubleTap = 0.35f; private const float GhostRunFactor = 1.3f; private const float GhostFlySprint = 2.2f; internal const float Gravity = 20f; internal const float JumpHeight = 2.25f; internal static readonly float JumpSpeed = Mathf.Sqrt(90f); private readonly Touch touch; private static readonly string[] solidLayers = new string[5] { "Default", "Room", "Colliders", "Terrain", "MiscLevelGeometry" }; private float camHeight = 2f; private float camDistance = 4f; private Vector3 camTarget; private readonly int ghostExclude; private readonly int enemyExclude; private readonly int camMask; internal float Yaw { [CompilerGenerated] get { return yaw; } } internal float Pitch { [CompilerGenerated] get { return pitch; } } internal Vector3 Feet { [CompilerGenerated] get { //IL_000b: Unknown result type (might be due to invalid IL or missing references) return root.transform.position; } } internal Vector3 Eye { [CompilerGenerated] get { //IL_000b: Unknown result type (might be due to invalid IL or missing references) return ((Component)Cam).transform.position; } } internal Vector3 Forward { [CompilerGenerated] get { //IL_000b: Unknown result type (might be due to invalid IL or missing references) return ((Component)Cam).transform.forward; } } internal bool Alive { [CompilerGenerated] get { return (Object)(object)root != (Object)null && (Object)(object)Cam != (Object)null; } } internal bool LightOn { [CompilerGenerated] get { return (Object)(object)lamp != (Object)null && ((Behaviour)lamp).enabled; } } internal bool Flying { [CompilerGenerated] get { return ghost && flying; } } private Rig(PlayerControllerB local) { //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Expected O, but got Unknown //IL_0173: Unknown result type (might be due to invalid IL or missing references) //IL_0193: Unknown result type (might be due to invalid IL or missing references) //IL_0199: Expected O, but got Unknown int num = Game.Mask(solidLayers); int num2 = num; if ((Object)(object)StartOfRound.Instance != (Object)null) { num2 |= StartOfRound.Instance.walkableSurfacesMask & ~Game.Mask("Player"); } num2 |= Game.Mask("Railing"); ghostExclude = ~num2; enemyExclude = ~(num2 | Game.Mask("InteractableObject", "PlaceableShipObjects", "CompanyCruiser")); camMask = num; Check.Info("Camera", "the ghost stands on: " + Names(num2)); root = new GameObject("Control Company Reloaded body"); int num3 = PickLayer(); if (num3 >= 0) { root.layer = num3; } body = root.AddComponent<CharacterController>(); body.slopeLimit = 60f; body.stepOffset = 0.4f; body.skinWidth = 0.05f; body.minMoveDistance = 0f; ((Collider)body).includeLayers = LayerMask.op_Implicit(num2); touch = root.AddComponent<Touch>(); GameObject val = new GameObject("Control Company Reloaded camera"); Cam = val.AddComponent<Camera>(); Camera gameplayCamera = local.gameplayCamera; Cam.CopyFrom(gameplayCamera); HDAdditionalCameraData component = ((Component)gameplayCamera).GetComponent<HDAdditionalCameraData>(); HDAdditionalCameraData val2 = val.GetComponent<HDAdditionalCameraData>() ?? val.AddComponent<HDAdditionalCameraData>(); if ((Object)(object)component != (Object)null) { component.CopyTo(val2); } Camera cam = Cam; cam.cullingMask &= ~Game.Mask("HelmetVisor"); ((Behaviour)Cam).enabled = false; lamp = MakeLight(local, val.transform); } private static Light MakeLight(PlayerControllerB local, Transform parent) { //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Expected O, but got Unknown //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) try { Light nightVision = local.nightVision; HDAdditionalLightData val = ((!((Object)(object)nightVision != (Object)null)) ? null : ((Component)nightVision).GetComponent<HDAdditionalLightData>()); bool flag = (Object)(object)nightVision != (Object)null && ((Component)nightVision).transform.childCount == 0; if (flag) { Component[] components = ((Component)nightVision).GetComponents<Component>(); foreach (Component val2 in components) { if (!(val2 is Transform) && !(val2 is Light) && !(val2 is HDAdditionalLightData)) { flag = false; break; } } } GameObject val3; if (flag) { val3 = Object.Instantiate<GameObject>(((Component)nightVision).gameObject, parent); } else { val3 = new GameObject(); val3.transform.SetParent(parent, false); Light val4 = val3.AddComponent<Light>(); val4.type = (LightType)2; if ((Object)(object)nightVision != (Object)null) { val4.color = nightVision.color; } val3.AddComponent<HDAdditionalLightData>(); } ((Object)val3).name = "Control Company Reloaded light"; val3.transform.localPosition = Vector3.zero; val3.transform.localRotation = Quaternion.identity; val3.SetActive(true); Light component = val3.GetComponent<Light>(); HDAdditionalLightData component2 = val3.GetComponent<HDAdditionalLightData>(); float num = (((Object)(object)val != (Object)null) ? val.intensity : ((!((Object)(object)nightVision != (Object)null)) ? 0f : nightVision.intensity)); if ((Object)(object)component2 != (Object)null) { if (num > 0f) { component2.intensity = num * 4f; } component2.range = 30f; } else if ((Object)(object)component != (Object)null) { component.intensity = Mathf.Max(1f, num) * 4f; component.range = 30f; } if ((Object)(object)component != (Object)null) { ((Behaviour)component).enabled = false; } Check.Info("Camera", "night vision light " + ((!flag) ? "made new" : "copied from the player's") + ", intensity " + num * 4f); return component; } catch (Exception ex) { Check.Problem("Camera", "no night vision: " + ex.Message); return null; } } private static string Names(int mask) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < 32; i++) { if ((mask & (1 << i)) != 0) { string text = LayerMask.LayerToName(i); stringBuilder.Append((stringBuilder.Length <= 0) ? string.Empty : ", ").Append((!string.IsNullOrEmpty(text)) ? text : i.ToString()); } } return stringBuilder.ToString(); } private static int PickLayer() { string text = null; string[] array = new string[4] { "Ignore Raycast", "PlayerRagdoll", "Enemies", "Default" }; foreach (string text2 in array) { int num = Game.Layer(text2); if (num < 0) { continue; } bool flag = true; string[] array2 = solidLayers; foreach (string name in array2) { int num2 = Game.Layer(name); if (num2 >= 0 && Physics.GetIgnoreLayerCollision(num, num2)) { flag = false; break; } } if (flag) { text = text2; break; } } if (text == null) { text = "Ignore Raycast"; } Check.Info("Camera", "capsule on the " + text + " layer, with the level's layers included on it"); return Game.Layer(text); } internal DoorLock TakeDoorHit() { if ((Object)(object)touch == (Object)null) { return null; } DoorLock door = touch.Door; touch.Door = null; return door; } internal static Rig Make(PlayerControllerB local) { Rig result = new Rig(local); Check.Ok("Camera", "made the camera (copy of the player's, HDRP settings " + ((!((Object)(object)((Component)local.gameplayCamera).GetComponent<HDAdditionalCameraData>() != (Object)null)) ? "not found" : "copied") + ")"); return result; } internal void Destroy() { if ((Object)(object)Cam != (Object)null) { Object.Destroy((Object)(object)((Component)Cam).gameObject); } if ((Object)(object)root != (Object)null) { Object.Destroy((Object)(object)root); } } internal void SetLight(bool on) { if ((Object)(object)lamp != (Object)null) { ((Behaviour)lamp).enabled = on; } } internal void SizeGhost(float eye, float height, float radius) { ghostEye = Mathf.Clamp(eye, 1.2f, 3.2f); ghostHeight = Mathf.Clamp(height, ghostEye + 0.12f, 3.5f); ghostRadius = Mathf.Clamp(radius, 0.2f, 0.6f); } internal void BecomeGhost(Vector3 feet, float lookYaw, float lookPitch) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) ghost = true; flying = false; planar = Vector3.zero; lastJumpTap = -10f; ((Collider)body).excludeLayers = LayerMask.op_Implicit(ghostExclude); body.radius = ghostRadius; body.height = ghostHeight; body.center = new Vector3(0f, body.height / 2f + body.skinWidth, 0f); Teleport(feet); lastGround = feet; yaw = lookYaw; pitch = Mathf.Clamp(lookPitch, -85f, 85f); vertical = 0f; } internal bool GhostFits(Vector3 feet) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) return !Physics.CheckCapsule(feet + Vector3.up * (ghostRadius + 0.1f), feet + Vector3.up * (ghostHeight - ghostRadius), ghostRadius, camMask, (QueryTriggerInteraction)1); } internal void BecomeEnemy(Driver driver, EnemyAI enemy) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) ghost = false; planar = Vector3.zero; ((Collider)body).excludeLayers = LayerMask.op_Implicit(enemyExclude); body.radius = driver.Radius; body.height = Mathf.Max(driver.Height, driver.Radius * 2f); body.center = new Vector3(0f, body.height / 2f + body.skinWidth, 0f); camHeight = driver.CamHeight; camDistance = driver.CamDistance; Teleport(((Component)enemy).transform.position); Collider[] componentsInChildren = ((Component)enemy).GetComponentsInChildren<Collider>(); foreach (Collider val in componentsInChildren) { if ((Object)(object)val != (Object)null && (Object)(object)val != (Object)(object)body && val.enabled) { Physics.IgnoreCollision((Collider)(object)body, val, true); } } yaw = ((Component)enemy).transform.eulerAngles.y; pitch = 15f; vertical = 0f; } internal void BecomeFixed(float lookYaw, float height, float distance) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) ghost = false; flying = false; planar = Vector3.zero; vertical = 0f; camHeight = height; camDistance = distance; yaw = lookYaw; pitch = 15f; } internal void Teleport(Vector3 pos) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) root.transform.position = pos; lastGround = pos; unsynced = true; } private void CatchFall() { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Unknown result type (might be due to invalid IL or missing references) //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) if (root.transform.position.y >= lastGround.y - 80f) { return; } Vector3 val = lastGround; RoundManager instance = RoundManager.Instance; if ((Object)(object)instance != (Object)null) { Vector3 navMeshPosition = instance.GetNavMeshPosition(lastGround, default(NavMeshHit), 10f, -1); if (instance.GotNavMeshPositionResult) { val = navMeshPosition; } else { float num = float.MaxValue; GameObject[][] array = new GameObject[2][] { instance.outsideAINodes, instance.insideAINodes }; foreach (GameObject[] array2 in array) { if (array2 == null) { continue; } GameObject[] array3 = array2; foreach (GameObject val2 in array3) { if (!((Object)(object)val2 == (Object)null)) { Vector3 val3 = val2.transform.position - lastGround; float sqrMagnitude = ((Vector3)(ref val3)).sqrMagn