From a7819817b9c7d036be255513d6e1654978b71c5a Mon Sep 17 00:00:00 2001 From: Lacyway <20912169+Lacyway@users.noreply.github.com> Date: Mon, 20 May 2024 23:21:12 +0200 Subject: [PATCH 01/32] Change raid settings sync - Now sent from Aki server --- Fika.Core/Coop/GameMode/CoopGame.cs | 11 +++----- .../MatchmakerAcceptPatches.cs | 2 +- .../MatchmakerAcceptScreen_Show_Patch.cs | 4 +-- .../Coop/PacketHandlers/ClientPacketSender.cs | 4 --- ...arkovApplication_LocalGameCreator_Patch.cs | 13 ++++++--- Fika.Core/FikaPlugin.cs | 2 +- Fika.Core/Networking/FikaClient.cs | 13 --------- Fika.Core/Networking/FikaServer.cs | 18 ------------ Fika.Core/Networking/Http/FikaHttpHandler.cs | 5 ++++ .../Networking/Models/RaidSettingsRequest.cs | 17 +++++++++++ .../Networking/Models/RaidSettingsResponse.cs | 13 +++++++++ .../Packets/Backend/SessionSettingsPacket.cs | 28 ------------------- Fika.Core/UI/Custom/MatchMakerUIScript.cs | 10 +++---- 13 files changed, 56 insertions(+), 84 deletions(-) create mode 100644 Fika.Core/Networking/Models/RaidSettingsRequest.cs create mode 100644 Fika.Core/Networking/Models/RaidSettingsResponse.cs delete mode 100644 Fika.Core/Networking/Packets/Backend/SessionSettingsPacket.cs diff --git a/Fika.Core/Coop/GameMode/CoopGame.cs b/Fika.Core/Coop/GameMode/CoopGame.cs index f177d7ba..06e1fc73 100644 --- a/Fika.Core/Coop/GameMode/CoopGame.cs +++ b/Fika.Core/Coop/GameMode/CoopGame.cs @@ -719,16 +719,13 @@ public override async Task vmethod_2(int playerId, Vector3 position if (!CoopHandler.TryGetCoopHandler(out CoopHandler coopHandler)) { Logger.LogDebug($"{nameof(vmethod_2)}:Unable to find {nameof(CoopHandler)}"); - await Task.Delay(5000); + throw new MissingComponentException("CoopHandler was missing during CoopGame init"); } - if (MatchmakerAcceptPatches.IsServer) + if (RaidSettings.MetabolismDisabled) { - if (RaidSettings.MetabolismDisabled) - { - myPlayer.HealthController.DisableMetabolism(); - NotificationManagerClass.DisplayMessageNotification("Metabolism disabled", iconType: EFT.Communications.ENotificationIconType.Alert); - } + myPlayer.HealthController.DisableMetabolism(); + NotificationManagerClass.DisplayMessageNotification("Metabolism disabled", iconType: EFT.Communications.ENotificationIconType.Alert); } CoopPlayer coopPlayer = (CoopPlayer)myPlayer; diff --git a/Fika.Core/Coop/Matchmaker/MatchmakerAccept/MatchmakerAcceptPatches.cs b/Fika.Core/Coop/Matchmaker/MatchmakerAccept/MatchmakerAcceptPatches.cs index fa521a98..5aac7c1c 100644 --- a/Fika.Core/Coop/Matchmaker/MatchmakerAccept/MatchmakerAcceptPatches.cs +++ b/Fika.Core/Coop/Matchmaker/MatchmakerAccept/MatchmakerAcceptPatches.cs @@ -74,7 +74,7 @@ public static void SetTimestamp(long ts) timestamp = ts; } - public static bool JoinMatch(RaidSettings settings, string profileId, string serverId, out CreateMatch result, out string errorMessage) + public static bool JoinMatch(string profileId, string serverId, out CreateMatch result, out string errorMessage) { result = new CreateMatch(); errorMessage = $"No server matches the data provided or the server no longer exists"; diff --git a/Fika.Core/Coop/Matchmaker/MatchmakerAccept/MatchmakerAcceptScreen_Show_Patch.cs b/Fika.Core/Coop/Matchmaker/MatchmakerAccept/MatchmakerAcceptScreen_Show_Patch.cs index 7e0ba5af..247f50a3 100644 --- a/Fika.Core/Coop/Matchmaker/MatchmakerAccept/MatchmakerAcceptScreen_Show_Patch.cs +++ b/Fika.Core/Coop/Matchmaker/MatchmakerAccept/MatchmakerAcceptScreen_Show_Patch.cs @@ -12,12 +12,10 @@ namespace Fika.Core.Coop.Matchmaker public class MatchmakerAcceptScreen_Show_Patch : ModulePatch { protected override MethodBase GetTargetMethod() => typeof(MatchMakerAcceptScreen).GetMethods(BindingFlags.Public | BindingFlags.Instance).First(x => x.Name == "Show" && x.GetParameters()[0].Name == "session"); - private static GameObject MatchmakerObject { get; set; } [PatchPrefix] - private static void PreFix(ref ISession session, ref RaidSettings raidSettings, Profile ___profile_0, MatchMakerAcceptScreen __instance, - DefaultUIButton ____acceptButton, DefaultUIButton ____backButton, MatchMakerPlayerPreview ____playerModelView) + private static void PreFix(ref RaidSettings raidSettings, DefaultUIButton ____acceptButton, DefaultUIButton ____backButton) { if (MatchmakerObject == null) { diff --git a/Fika.Core/Coop/PacketHandlers/ClientPacketSender.cs b/Fika.Core/Coop/PacketHandlers/ClientPacketSender.cs index c545e3d6..1e7169d4 100644 --- a/Fika.Core/Coop/PacketHandlers/ClientPacketSender.cs +++ b/Fika.Core/Coop/PacketHandlers/ClientPacketSender.cs @@ -140,10 +140,6 @@ private IEnumerator SyncWorld() yield return null; } - Writer?.Reset(); - SessionSettingsPacket settingsPacket = new(true); - Client?.SendData(Writer, ref settingsPacket, DeliveryMethod.ReliableOrdered); - CoopGame coopGame = (CoopGame)Singleton.Instance; if (coopGame == null) diff --git a/Fika.Core/Coop/Patches/LocalGame/TarkovApplication_LocalGameCreator_Patch.cs b/Fika.Core/Coop/Patches/LocalGame/TarkovApplication_LocalGameCreator_Patch.cs index c84b2c7b..f39d1200 100644 --- a/Fika.Core/Coop/Patches/LocalGame/TarkovApplication_LocalGameCreator_Patch.cs +++ b/Fika.Core/Coop/Patches/LocalGame/TarkovApplication_LocalGameCreator_Patch.cs @@ -8,6 +8,8 @@ using Fika.Core.Coop.Matchmaker; using Fika.Core.Modding; using Fika.Core.Modding.Events; +using Fika.Core.Networking.Http.Models; +using Fika.Core.Networking.Http; using System; using System.Linq; using System.Reflection; @@ -82,15 +84,11 @@ public static async Task Postfix(Task __result, TarkovApplication __instance, Ti ISession session = CurrentSession; - /*Profile profile = session.Profile; - Profile profileScav = session.ProfileOfPet;*/ - Profile profile = session.GetProfileBySide(____raidSettings.Side); profile.Inventory.Stash = null; profile.Inventory.QuestStashItems = null; profile.Inventory.DiscardLimits = Singleton.Instance.GetDiscardLimits(); - //____raidSettings.RaidMode = ERaidMode.Online; Logger.LogDebug("TarkovApplication_LocalGameCreator_Patch:Postfix: Attempt to set Raid Settings"); @@ -99,6 +97,12 @@ public static async Task Postfix(Task __result, TarkovApplication __instance, Ti if (MatchmakerAcceptPatches.IsClient) { timeHasComeScreenController.ChangeStatus("Joining Coop Game"); + + RaidSettingsRequest data = new(); + RaidSettingsResponse raidSettingsResponse = await FikaRequestHandler.GetRaidSettings(data); + + ____raidSettings.MetabolismDisabled = raidSettingsResponse.MetabolismDisabled; + ____raidSettings.PlayersSpawnPlace = (EPlayersSpawnPlace)Enum.Parse(typeof(EPlayersSpawnPlace), raidSettingsResponse.PlayersSpawnPlace); } else { @@ -114,6 +118,7 @@ public static async Task Postfix(Task __result, TarkovApplication __instance, Ti ____raidSettings.WavesSettings, ____raidSettings.SelectedDateTime, new Callback(startHandler.HandleStart), ____fixedDeltaTime, EUpdateQueue.Update, session, TimeSpan.FromSeconds(60 * ____raidSettings.SelectedLocation.EscapeTimeLimit), ____raidSettings ); + Singleton.Create(localGame); FikaEventDispatcher.DispatchEvent(new AbstractGameCreatedEvent(localGame)); diff --git a/Fika.Core/FikaPlugin.cs b/Fika.Core/FikaPlugin.cs index daf2a0ce..64570021 100644 --- a/Fika.Core/FikaPlugin.cs +++ b/Fika.Core/FikaPlugin.cs @@ -44,7 +44,7 @@ namespace Fika.Core /// Originally by: Paulov
/// Re-written by: Lacyway /// - [BepInPlugin("com.fika.core", "Fika.Core", "0.9.89")] + [BepInPlugin("com.fika.core", "Fika.Core", "0.9.8906")] [BepInProcess("EscapeFromTarkov.exe")] [BepInDependency("com.spt-aki.custom", BepInDependency.DependencyFlags.HardDependency)] // This is used so that we guarantee to load after aki-custom, that way we can disable its patches [BepInDependency("com.spt-aki.singleplayer", BepInDependency.DependencyFlags.HardDependency)] // This is used so that we guarantee to load after aki-singleplayer, that way we can disable its patches diff --git a/Fika.Core/Networking/FikaClient.cs b/Fika.Core/Networking/FikaClient.cs index d27e79b5..eca51392 100644 --- a/Fika.Core/Networking/FikaClient.cs +++ b/Fika.Core/Networking/FikaClient.cs @@ -80,7 +80,6 @@ protected void Start() packetProcessor.SubscribeNetSerializable(OnAssignNetIdPacketReceived); packetProcessor.SubscribeNetSerializable(OnSyncNetIdPacketReceived); packetProcessor.SubscribeNetSerializable(OnOperationCallbackPacketReceived); - packetProcessor.SubscribeNetSerializable(OnSessionSettingsPacketReceived); _netClient = new NetManager(this) { @@ -115,18 +114,6 @@ protected void Start() ClientReady = true; } - private void OnSessionSettingsPacketReceived(SessionSettingsPacket packet) - { - if (!packet.IsRequest) - { - if (packet.MetabolismDisabled) - { - Singleton.Instance.MainPlayer.HealthController.DisableMetabolism(); - NotificationManagerClass.DisplayMessageNotification("Metabolism disabled", iconType: EFT.Communications.ENotificationIconType.Alert); - } - } - } - private void OnOperationCallbackPacketReceived(OperationCallbackPacket packet) { if (Players.TryGetValue(packet.NetId, out CoopPlayer player) && player.IsYourPlayer) diff --git a/Fika.Core/Networking/FikaServer.cs b/Fika.Core/Networking/FikaServer.cs index b6a25dd2..3ce0aaed 100644 --- a/Fika.Core/Networking/FikaServer.cs +++ b/Fika.Core/Networking/FikaServer.cs @@ -83,7 +83,6 @@ public async void Start() packetProcessor.SubscribeNetSerializable(OnMinePacketReceived); packetProcessor.SubscribeNetSerializable(OnBorderZonePacketReceived); packetProcessor.SubscribeNetSerializable(OnSendCharacterPacketReceived); - packetProcessor.SubscribeNetSerializable(OnSessionSettingsPacketReceived); _netServer = new NetManager(this) { @@ -165,23 +164,6 @@ await Task.Run(async () => ServerReady = true; } - private void OnSessionSettingsPacketReceived(SessionSettingsPacket packet, NetPeer peer) - { - if (packet.IsRequest) - { - CoopGame coopGame = (CoopGame)Singleton.Instance; - if (coopGame != null) - { - SessionSettingsPacket returnPacket = new(false) - { - MetabolismDisabled = coopGame.RaidSettings.MetabolismDisabled - }; - - SendDataToPeer(peer, new(), ref returnPacket, DeliveryMethod.ReliableUnordered); - } - } - } - public int PopNetId() { int netId = _currentNetId; diff --git a/Fika.Core/Networking/Http/FikaHttpHandler.cs b/Fika.Core/Networking/Http/FikaHttpHandler.cs index 232b7db0..28abbce5 100644 --- a/Fika.Core/Networking/Http/FikaHttpHandler.cs +++ b/Fika.Core/Networking/Http/FikaHttpHandler.cs @@ -135,5 +135,10 @@ public static Dictionary AvailableReceivers(AvailableReceiversRe { return PostJson>("/fika/senditem/availablereceivers", data); } + + public static async Task GetRaidSettings(RaidSettingsRequest data) + { + return await PostJsonAsync("/fika/raid/getsettings", data); + } } } \ No newline at end of file diff --git a/Fika.Core/Networking/Models/RaidSettingsRequest.cs b/Fika.Core/Networking/Models/RaidSettingsRequest.cs new file mode 100644 index 00000000..b6df6a28 --- /dev/null +++ b/Fika.Core/Networking/Models/RaidSettingsRequest.cs @@ -0,0 +1,17 @@ +using Fika.Core.Coop.Components; +using System.Runtime.Serialization; + +namespace Fika.Core.Networking.Http.Models +{ + [DataContract] + public struct RaidSettingsRequest + { + [DataMember(Name = "serverId")] + public string ServerId; + + public RaidSettingsRequest() + { + ServerId = CoopHandler.GetServerId(); + } + } +} \ No newline at end of file diff --git a/Fika.Core/Networking/Models/RaidSettingsResponse.cs b/Fika.Core/Networking/Models/RaidSettingsResponse.cs new file mode 100644 index 00000000..bb627ba5 --- /dev/null +++ b/Fika.Core/Networking/Models/RaidSettingsResponse.cs @@ -0,0 +1,13 @@ +using System.Runtime.Serialization; + +namespace Fika.Core.Networking.Http.Models +{ + [DataContract] + public struct RaidSettingsResponse(bool metabolismDisabled, string playersSpawnPlace) + { + [DataMember(Name = "metabolismDisabled")] + public bool MetabolismDisabled = metabolismDisabled; + [DataMember(Name = "playersSpawnPlace")] + public string PlayersSpawnPlace = playersSpawnPlace; + } +} \ No newline at end of file diff --git a/Fika.Core/Networking/Packets/Backend/SessionSettingsPacket.cs b/Fika.Core/Networking/Packets/Backend/SessionSettingsPacket.cs deleted file mode 100644 index d71661c5..00000000 --- a/Fika.Core/Networking/Packets/Backend/SessionSettingsPacket.cs +++ /dev/null @@ -1,28 +0,0 @@ -using LiteNetLib.Utils; - -namespace Fika.Core.Networking -{ - public struct SessionSettingsPacket(bool isRequest) : INetSerializable - { - public bool IsRequest = isRequest; - public bool MetabolismDisabled; - - public void Deserialize(NetDataReader reader) - { - IsRequest = reader.GetBool(); - if (!IsRequest) - { - MetabolismDisabled = reader.GetBool(); - } - } - - public void Serialize(NetDataWriter writer) - { - writer.Put(IsRequest); - if (!IsRequest) - { - writer.Put(MetabolismDisabled); - } - } - } -} diff --git a/Fika.Core/UI/Custom/MatchMakerUIScript.cs b/Fika.Core/UI/Custom/MatchMakerUIScript.cs index 67e837d9..c0a6c4d8 100644 --- a/Fika.Core/UI/Custom/MatchMakerUIScript.cs +++ b/Fika.Core/UI/Custom/MatchMakerUIScript.cs @@ -34,14 +34,14 @@ internal class MatchMakerUIScript : MonoBehaviour private float _lastRefreshed; - private void Start() + protected void Start() { CreateMatchMakerUI(); StartCoroutine(ServerQuery()); } - void Update() + protected void Update() { if (Input.GetKeyDown(KeyCode.Escape)) { @@ -64,7 +64,7 @@ private void DestroyThis() Destroy(this); } - private void OnDestroy() + protected void OnDestroy() { StopQuery = true; if (NewBackButton != null) @@ -232,12 +232,12 @@ private IEnumerator JoinMatch(string profileId, string serverId, Button button) pingingClient.NetClient?.Stop(); pingingClient = null; - if (MatchmakerAcceptPatches.JoinMatch(RaidSettings, profileId, serverId, out CreateMatch result, out string errorMessage)) + if (MatchmakerAcceptPatches.JoinMatch(profileId, serverId, out CreateMatch result, out string errorMessage)) { MatchmakerAcceptPatches.SetGroupId(result.ServerId); MatchmakerAcceptPatches.SetTimestamp(result.Timestamp); MatchmakerAcceptPatches.MatchingType = EMatchmakerType.GroupPlayer; - MatchmakerAcceptPatches.HostExpectedNumberOfPlayers = result.ExpectedNumberOfPlayers; + MatchmakerAcceptPatches.HostExpectedNumberOfPlayers = result.ExpectedNumberOfPlayers; DestroyThis(); From 1ddec4b62511b04dc2b2b64bdb3ac3c5b77e3e0e Mon Sep 17 00:00:00 2001 From: Lacyway <20912169+Lacyway@users.noreply.github.com> Date: Mon, 20 May 2024 23:24:59 +0200 Subject: [PATCH 02/32] Fixes #53 - Remove dog tag on exfil --- Fika.Core/Coop/GameMode/CoopGame.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Fika.Core/Coop/GameMode/CoopGame.cs b/Fika.Core/Coop/GameMode/CoopGame.cs index 06e1fc73..768c2422 100644 --- a/Fika.Core/Coop/GameMode/CoopGame.cs +++ b/Fika.Core/Coop/GameMode/CoopGame.cs @@ -1524,6 +1524,18 @@ public override void Stop(string profileId, ExitStatus exitStatus, string exitNa CoopPlayer myPlayer = (CoopPlayer)Singleton.Instance.MainPlayer; myPlayer.PacketSender?.DestroyThis(); + if (myPlayer.Side != EPlayerSide.Savage) + { + if (myPlayer.Equipment.GetSlot(EquipmentSlot.Dogtag).ContainedItem != null) + { + GStruct414 result = InteractionsHandlerClass.Remove(myPlayer.Equipment.GetSlot(EquipmentSlot.Dogtag).ContainedItem, myPlayer.GClass2761_0, false, true); + if (result.Error != null) + { + FikaPlugin.Instance.FikaLogger.LogWarning("CoopGame::Stop: Error removing dog tag!"); + } + } + } + if (!myPlayer.ActiveHealthController.IsAlive && exitStatus == ExitStatus.Survived) { exitStatus = ExitStatus.Killed; From db7743cf5d77c02bd45dc9e7b1213d17705f912a Mon Sep 17 00:00:00 2001 From: Lacyway <20912169+Lacyway@users.noreply.github.com> Date: Tue, 21 May 2024 10:17:07 +0200 Subject: [PATCH 03/32] Remove null propagation and null-coalescing operators - Apparently these do not function well with UnityObjects --- Fika.Core/Coop/BTR/FikaBTRManager_Host.cs | 2 +- .../BotClasses/CoopBotHealthController.cs | 4 +- .../BotClasses/CoopBotInventoryController.cs | 2 +- .../CoopClientHealthController.cs | 4 +- .../CoopClientInventoryController.cs | 4 +- .../CoopClientFirearmController.cs | 54 +++---- .../CoopClientGrenadeController.cs | 14 +- .../CoopClientKnifeController.cs | 8 +- .../CoopClientQuickGrenadeController.cs | 2 +- Fika.Core/Coop/Components/CoopExfilManager.cs | 6 +- Fika.Core/Coop/Components/CoopHandler.cs | 8 +- .../GameMode/{AMPTGame.cs => AFikaGame.cs} | 12 +- Fika.Core/Coop/GameMode/CoopGame.cs | 149 +++++++++++++----- .../Coop/PacketHandlers/BotPacketSender.cs | 22 +-- .../Coop/PacketHandlers/ClientPacketSender.cs | 36 ++--- .../Coop/PacketHandlers/ServerPacketSender.cs | 28 ++-- .../Minefield/Minefield_method_2_Patch.cs | 2 +- Fika.Core/Coop/Players/CoopBot.cs | 4 +- Fika.Core/Coop/Players/CoopPlayer.cs | 69 ++++---- Fika.Core/Coop/Players/ObservedCoopPlayer.cs | 23 ++- Fika.Core/Networking/FikaClient.cs | 20 ++- Fika.Core/Networking/FikaServer.cs | 14 +- 22 files changed, 293 insertions(+), 194 deletions(-) rename Fika.Core/Coop/GameMode/{AMPTGame.cs => AFikaGame.cs} (90%) diff --git a/Fika.Core/Coop/BTR/FikaBTRManager_Host.cs b/Fika.Core/Coop/BTR/FikaBTRManager_Host.cs index e0ef2313..b5bcbb52 100644 --- a/Fika.Core/Coop/BTR/FikaBTRManager_Host.cs +++ b/Fika.Core/Coop/BTR/FikaBTRManager_Host.cs @@ -456,7 +456,7 @@ private void UpdateBTRSideDoorState(byte state) { try { - BTRSide btrSide = lastInteractPlayer.BtrInteractionSide ?? lastInteractedBtrSide; + BTRSide btrSide = lastInteractPlayer.BtrInteractionSide != null ? lastInteractPlayer.BtrInteractionSide : lastInteractedBtrSide; byte sideId = btrClientSide.GetSideId(btrSide); switch (sideId) { diff --git a/Fika.Core/Coop/BotClasses/CoopBotHealthController.cs b/Fika.Core/Coop/BotClasses/CoopBotHealthController.cs index 67876d7f..15c779f2 100644 --- a/Fika.Core/Coop/BotClasses/CoopBotHealthController.cs +++ b/Fika.Core/Coop/BotClasses/CoopBotHealthController.cs @@ -22,11 +22,11 @@ public override void SendNetworkSyncPacket(GStruct346 packet) { if (packet.SyncType == GStruct346.ESyncType.IsAlive && !packet.Data.IsAlive.IsAlive) { - coopBot?.PacketSender?.HealthSyncPackets.Enqueue(coopBot.SetupDeathPacket(packet)); + coopBot.PacketSender.HealthSyncPackets.Enqueue(coopBot.SetupDeathPacket(packet)); return; } - coopBot?.PacketSender?.HealthSyncPackets.Enqueue(new(coopBot.NetId) + coopBot.PacketSender.HealthSyncPackets.Enqueue(new(coopBot.NetId) { Packet = packet }); diff --git a/Fika.Core/Coop/BotClasses/CoopBotInventoryController.cs b/Fika.Core/Coop/BotClasses/CoopBotInventoryController.cs index 3dd9336a..03410663 100644 --- a/Fika.Core/Coop/BotClasses/CoopBotInventoryController.cs +++ b/Fika.Core/Coop/BotClasses/CoopBotInventoryController.cs @@ -33,7 +33,7 @@ public override void Execute(GClass2837 operation, [CanBeNull] Callback callback OperationBytes = opBytes }; - CoopBot.PacketSender?.InventoryPackets?.Enqueue(packet); + CoopBot.PacketSender.InventoryPackets.Enqueue(packet); } } } diff --git a/Fika.Core/Coop/ClientClasses/CoopClientHealthController.cs b/Fika.Core/Coop/ClientClasses/CoopClientHealthController.cs index 8ab98cf0..1263336e 100644 --- a/Fika.Core/Coop/ClientClasses/CoopClientHealthController.cs +++ b/Fika.Core/Coop/ClientClasses/CoopClientHealthController.cs @@ -22,11 +22,11 @@ public override void SendNetworkSyncPacket(GStruct346 packet) { if (packet.SyncType == GStruct346.ESyncType.IsAlive && !packet.Data.IsAlive.IsAlive) { - coopPlayer?.PacketSender?.HealthSyncPackets.Enqueue(coopPlayer.SetupDeathPacket(packet)); + coopPlayer.PacketSender.HealthSyncPackets.Enqueue(coopPlayer.SetupDeathPacket(packet)); return; } - coopPlayer?.PacketSender?.HealthSyncPackets.Enqueue(new(coopPlayer.NetId) + coopPlayer.PacketSender.HealthSyncPackets.Enqueue(new(coopPlayer.NetId) { Packet = packet }); diff --git a/Fika.Core/Coop/ClientClasses/CoopClientInventoryController.cs b/Fika.Core/Coop/ClientClasses/CoopClientInventoryController.cs index 355164a4..d8edf451 100644 --- a/Fika.Core/Coop/ClientClasses/CoopClientInventoryController.cs +++ b/Fika.Core/Coop/ClientClasses/CoopClientInventoryController.cs @@ -69,7 +69,7 @@ public override void Execute(GClass2837 operation, [CanBeNull] Callback callback OperationBytes = opBytes }; - CoopPlayer.PacketSender?.InventoryPackets?.Enqueue(packet); + CoopPlayer.PacketSender.InventoryPackets.Enqueue(packet); return; } @@ -113,7 +113,7 @@ public override void Execute(GClass2837 operation, [CanBeNull] Callback callback OperationBytes = opBytes }; - CoopPlayer.PacketSender?.InventoryPackets?.Enqueue(packet); + CoopPlayer.PacketSender.InventoryPackets.Enqueue(packet); } } diff --git a/Fika.Core/Coop/ClientClasses/HandsControllers/CoopClientFirearmController.cs b/Fika.Core/Coop/ClientClasses/HandsControllers/CoopClientFirearmController.cs index e442c781..91802259 100644 --- a/Fika.Core/Coop/ClientClasses/HandsControllers/CoopClientFirearmController.cs +++ b/Fika.Core/Coop/ClientClasses/HandsControllers/CoopClientFirearmController.cs @@ -95,7 +95,7 @@ public override bool CheckChamber() bool flag = base.CheckChamber(); if (flag) { - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { CheckChamber = true }); @@ -108,7 +108,7 @@ public override bool CheckAmmo() bool flag = base.CheckAmmo(); if (flag) { - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { CheckAmmo = true }); @@ -121,7 +121,7 @@ public override bool ChangeFireMode(Weapon.EFireMode fireMode) bool flag = base.ChangeFireMode(fireMode); if (flag) { - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { ChangeFireMode = true, FireMode = fireMode @@ -133,7 +133,7 @@ public override bool ChangeFireMode(Weapon.EFireMode fireMode) public override void ChangeAimingMode() { base.ChangeAimingMode(); - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { ToggleAim = true, AimingIndex = IsAiming ? Item.AimIndex.Value : -1 @@ -147,7 +147,7 @@ public override void SetAim(bool value) base.SetAim(value); if (IsAiming != isAiming || aimingInterruptedByOverlap) { - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { ToggleAim = true, AimingIndex = IsAiming ? Item.AimIndex.Value : -1 @@ -160,7 +160,7 @@ public override bool CheckFireMode() bool flag = base.CheckFireMode(); if (flag) { - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { CheckFireMode = true }); @@ -171,7 +171,7 @@ public override bool CheckFireMode() public override void DryShot(int chamberIndex = 0, bool underbarrelShot = false) { base.DryShot(chamberIndex, underbarrelShot); - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { HasShotInfo = true, ShotInfoPacket = new() @@ -190,7 +190,7 @@ public override bool ExamineWeapon() bool flag = base.ExamineWeapon(); if (flag) { - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { ExamineWeapon = true }); @@ -224,7 +224,7 @@ public override void InitiateShot(GInterface322 weapon, BulletClass ammo, Vector break; } - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { HasShotInfo = true, ShotInfoPacket = new() @@ -259,7 +259,7 @@ public override void QuickReloadMag(MagazineClass magazine, Callback callback) base.QuickReloadMag(magazine, callback); - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { HasQuickReloadMagPacket = true, QuickReloadMagPacket = new() @@ -312,7 +312,7 @@ public override void ReloadGrenadeLauncher(GClass2495 ammoPack, Callback callbac string[] reloadingAmmoIds = ammoPack.GetReloadingAmmoIds(); - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { ReloadLauncher = new() { @@ -352,7 +352,7 @@ public override void SetLightsState(GStruct163[] lightsStates, bool force = fals { if (force || CurrentOperation.CanChangeLightState(lightsStates)) { - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { ToggleTacticalCombo = true, LightStatesPacket = new() @@ -372,7 +372,7 @@ public override void SetScopeMode(GStruct164[] scopeStates) return; } - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { ChangeSightMode = true, ScopeStatesPacket = new() @@ -408,7 +408,7 @@ public override void ShotMisfired(BulletClass ammo, Weapon.EMalfunctionState mal break; } - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { HasShotInfo = true, ShotInfoPacket = new() @@ -429,7 +429,7 @@ public override bool ToggleLauncher() bool flag = base.ToggleLauncher(); if (flag) { - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { ToggleLauncher = true }); @@ -440,7 +440,7 @@ public override bool ToggleLauncher() public override void Loot(bool p) { base.Loot(p); - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { Loot = p }); @@ -449,7 +449,7 @@ public override void Loot(bool p) public override void SetInventoryOpened(bool opened) { base.SetInventoryOpened(opened); - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { EnableInventory = true, InventoryStatus = opened @@ -459,7 +459,7 @@ public override void SetInventoryOpened(bool opened) public override void ChangeLeftStance() { base.ChangeLeftStance(); - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { HasStanceChange = true, LeftStanceState = coopPlayer.MovementContext.LeftStanceEnabled @@ -473,7 +473,7 @@ public override void SendStartOneShotFire() public override void CreateFlareShot(BulletClass flareItem, Vector3 shotPosition, Vector3 forward) { - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { HasFlareShot = true, FlareShotPacket = new() @@ -488,7 +488,7 @@ public override void CreateFlareShot(BulletClass flareItem, Vector3 shotPosition private void SendAbortReloadPacket(int amount) { - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { HasReloadWithAmmoPacket = true, ReloadWithAmmo = new() @@ -507,7 +507,7 @@ public override void RollCylinder(bool rollToZeroCamora) return; } - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { HasRollCylinder = true, RollToZeroCamora = rollToZeroCamora @@ -518,7 +518,7 @@ public override void RollCylinder(bool rollToZeroCamora) private void SendEndReloadPacket(int amount) { - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { HasReloadWithAmmoPacket = true, ReloadWithAmmo = new() @@ -532,7 +532,7 @@ private void SendEndReloadPacket(int amount) private void SendBoltActionReloadPacket() { - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { ReloadBoltAction = true }); @@ -684,7 +684,7 @@ public void Process(IResult error) if (error.Succeed) { - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { HasReloadMagPacket = true, ReloadMagPacket = new() @@ -709,7 +709,7 @@ private class ReloadCylinderMagazineHandler(CoopPlayer coopPlayer, CoopClientFir public void Process(IResult error) { - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { HasReloadWithAmmoPacket = true, ReloadWithAmmo = new() @@ -756,7 +756,7 @@ public void Process(IResult error) if (coopPlayer.HealthController.IsAlive) { - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { HasReloadBarrelsPacket = true, ReloadBarrels = new() @@ -779,7 +779,7 @@ public void Process(IResult error) { if (error.Succeed) { - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { HasReloadWithAmmoPacket = true, ReloadWithAmmo = new() diff --git a/Fika.Core/Coop/ClientClasses/HandsControllers/CoopClientGrenadeController.cs b/Fika.Core/Coop/ClientClasses/HandsControllers/CoopClientGrenadeController.cs index ee72f5d9..a34d3617 100644 --- a/Fika.Core/Coop/ClientClasses/HandsControllers/CoopClientGrenadeController.cs +++ b/Fika.Core/Coop/ClientClasses/HandsControllers/CoopClientGrenadeController.cs @@ -24,7 +24,7 @@ public static CoopClientGrenadeController Create(CoopPlayer player, GrenadeClass public override void ExamineWeapon() { - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { HasGrenadePacket = true, GrenadePacket = new() @@ -37,7 +37,7 @@ public override void ExamineWeapon() public override void HighThrow() { - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { HasGrenadePacket = true, GrenadePacket = new() @@ -50,7 +50,7 @@ public override void HighThrow() public override void LowThrow() { - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { HasGrenadePacket = true, GrenadePacket = new() @@ -63,7 +63,7 @@ public override void LowThrow() public override void PullRingForHighThrow() { - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { HasGrenadePacket = true, GrenadePacket = new() @@ -76,7 +76,7 @@ public override void PullRingForHighThrow() public override void PullRingForLowThrow() { - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { HasGrenadePacket = true, GrenadePacket = new() @@ -89,7 +89,7 @@ public override void PullRingForLowThrow() public override void vmethod_2(float timeSinceSafetyLevelRemoved, Vector3 position, Quaternion rotation, Vector3 force, bool lowThrow) { - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { HasGrenadePacket = true, GrenadePacket = new() @@ -109,7 +109,7 @@ public override void ActualDrop(Result controller, float { // TODO: Override Class1025 - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { CancelGrenade = true }); diff --git a/Fika.Core/Coop/ClientClasses/HandsControllers/CoopClientKnifeController.cs b/Fika.Core/Coop/ClientClasses/HandsControllers/CoopClientKnifeController.cs index df26a601..273560a8 100644 --- a/Fika.Core/Coop/ClientClasses/HandsControllers/CoopClientKnifeController.cs +++ b/Fika.Core/Coop/ClientClasses/HandsControllers/CoopClientKnifeController.cs @@ -23,7 +23,7 @@ public override void ExamineWeapon() { base.ExamineWeapon(); - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { HasKnifePacket = true, KnifePacket = new() @@ -39,7 +39,7 @@ public override bool MakeKnifeKick() if (knifeKick) { - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { HasKnifePacket = true, KnifePacket = new() @@ -58,7 +58,7 @@ public override bool MakeAlternativeKick() if (alternateKnifeKick) { - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { HasKnifePacket = true, KnifePacket = new() @@ -75,7 +75,7 @@ public override void BrakeCombo() { base.BrakeCombo(); - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { HasKnifePacket = true, KnifePacket = new() diff --git a/Fika.Core/Coop/ClientClasses/HandsControllers/CoopClientQuickGrenadeController.cs b/Fika.Core/Coop/ClientClasses/HandsControllers/CoopClientQuickGrenadeController.cs index 131a71b1..aa1d8316 100644 --- a/Fika.Core/Coop/ClientClasses/HandsControllers/CoopClientQuickGrenadeController.cs +++ b/Fika.Core/Coop/ClientClasses/HandsControllers/CoopClientQuickGrenadeController.cs @@ -25,7 +25,7 @@ public static CoopClientQuickGrenadeController Create(CoopPlayer player, Grenade public override void vmethod_2(float timeSinceSafetyLevelRemoved, Vector3 position, Quaternion rotation, Vector3 force, bool lowThrow) { - coopPlayer.PacketSender?.FirearmPackets?.Enqueue(new() + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { HasGrenadePacket = true, GrenadePacket = new() diff --git a/Fika.Core/Coop/Components/CoopExfilManager.cs b/Fika.Core/Coop/Components/CoopExfilManager.cs index 7e3ef0ee..b7a587e4 100644 --- a/Fika.Core/Coop/Components/CoopExfilManager.cs +++ b/Fika.Core/Coop/Components/CoopExfilManager.cs @@ -201,16 +201,16 @@ private void ExfiltrationPoint_OnStatusChanged(ExfiltrationPoint point, EExfiltr ExfilStartTime = point.ExfiltrationStartTime }; - NetDataWriter writer = mainPlayer.PacketSender?.Writer; + NetDataWriter writer = mainPlayer.PacketSender.Writer; writer.Reset(); if (MatchmakerAcceptPatches.IsServer) { - mainPlayer.PacketSender?.Server?.SendDataToAll(writer, ref packet, DeliveryMethod.ReliableOrdered); + mainPlayer.PacketSender.Server.SendDataToAll(writer, ref packet, DeliveryMethod.ReliableOrdered); } else if (MatchmakerAcceptPatches.IsClient) { - mainPlayer.PacketSender?.Client?.SendData(writer, ref packet, DeliveryMethod.ReliableOrdered); + mainPlayer.PacketSender.Client.SendData(writer, ref packet, DeliveryMethod.ReliableOrdered); } } countdownPoints.Add(point); diff --git a/Fika.Core/Coop/Components/CoopHandler.cs b/Fika.Core/Coop/Components/CoopHandler.cs index 8ef25c45..25fad416 100644 --- a/Fika.Core/Coop/Components/CoopHandler.cs +++ b/Fika.Core/Coop/Components/CoopHandler.cs @@ -315,7 +315,7 @@ private void ReadFromServerCharacters() if (writer != null) { writer.Reset(); - Singleton.Instance?.SendData(writer, ref requestPacket, DeliveryMethod.ReliableOrdered); + Singleton.Instance.SendData(writer, ref requestPacket, DeliveryMethod.ReliableOrdered); } } @@ -353,15 +353,15 @@ await Singleton.Instance.LoadBundlesAndCreatePools(PoolManager.Pool { if (x.IsCompleted) { - Logger.LogDebug($"SpawnPlayer::{spawnObject.Profile.Info.Nickname}::Load Complete."); + Logger.LogDebug($"SpawnPlayer::{spawnObject.Profile.Info.Nickname}::Load Complete"); } else if (x.IsFaulted) { - Logger.LogError($"SpawnPlayer::{spawnObject.Profile.Info.Nickname}::Load Failed."); + Logger.LogError($"SpawnPlayer::{spawnObject.Profile.Info.Nickname}::Load Failed"); } else if (x.IsCanceled) { - Logger.LogError($"SpawnPlayer::{spawnObject.Profile.Info.Nickname}::Load Cancelled?"); + Logger.LogError($"SpawnPlayer::{spawnObject.Profile.Info.Nickname}::Load Cancelled"); } }); diff --git a/Fika.Core/Coop/GameMode/AMPTGame.cs b/Fika.Core/Coop/GameMode/AFikaGame.cs similarity index 90% rename from Fika.Core/Coop/GameMode/AMPTGame.cs rename to Fika.Core/Coop/GameMode/AFikaGame.cs index 54ff351c..75ae3cb4 100644 --- a/Fika.Core/Coop/GameMode/AMPTGame.cs +++ b/Fika.Core/Coop/GameMode/AFikaGame.cs @@ -23,7 +23,10 @@ BotsController IBotGame.BotsController { get { - BotsController ??= (BotsController)GetType().GetFields().Where(x => x.FieldType == typeof(BotsController)).FirstOrDefault().GetValue(this); + if (BotsController == null) + { + BotsController = (BotsController)GetType().GetFields().Where(x => x.FieldType == typeof(BotsController)).FirstOrDefault().GetValue(this); + } return BotsController; } } @@ -34,8 +37,11 @@ public BotsController PBotsController { get { - BotsController ??= (BotsController)GetType().GetFields().Where(x => x.FieldType == typeof(BotsController)).FirstOrDefault().GetValue(this); - return BotsController; + if (BotsController == null) + { + BotsController = (BotsController)GetType().GetFields().Where(x => x.FieldType == typeof(BotsController)).FirstOrDefault().GetValue(this); + } + return BotsController; } } diff --git a/Fika.Core/Coop/GameMode/CoopGame.cs b/Fika.Core/Coop/GameMode/CoopGame.cs index 768c2422..76e76a27 100644 --- a/Fika.Core/Coop/GameMode/CoopGame.cs +++ b/Fika.Core/Coop/GameMode/CoopGame.cs @@ -370,7 +370,7 @@ private async Task CreateBot(Profile profile, Vector3 position) netId = server.PopNetId(); SendCharacterPacket packet = new(new FikaSerialization.PlayerInfoPacket() { Profile = profile }, true, true, position, netId); - Singleton.Instance?.SendDataToAll(new NetDataWriter(), ref packet, LiteNetLib.DeliveryMethod.ReliableUnordered); + Singleton.Instance.SendDataToAll(new NetDataWriter(), ref packet, LiteNetLib.DeliveryMethod.ReliableUnordered); if (server.NetServer.ConnectedPeersCount > 0) { @@ -517,7 +517,10 @@ private void DespawnBot(CoopHandler coopHandler, Player bot) BotsController.Bots.Remove(botOwner); bot.HealthController.DiedEvent -= botOwner.method_6; // Unsubscribe from the event to prevent errors. BotUnspawn(botOwner); - botOwner?.Dispose(); + if (botOwner != null) + { + botOwner.Dispose(); + } CoopPlayer coopPlayer = (CoopPlayer)bot; coopHandler.Players.Remove(coopPlayer.NetId); @@ -548,7 +551,10 @@ private async void DeployScreen(float timeBeforeDeploy) Destroy(fikaStartButton); } - dynamicAI?.AddHumans(); + if (dynamicAI != null) + { + dynamicAI.AddHumans(); + } SetStatusModel status = new(coopHandler.MyPlayer.ProfileId, LobbyEntry.ELobbyStatus.IN_GAME); await FikaRequestHandler.UpdateSetStatus(status); @@ -563,7 +569,10 @@ private async void DeployScreen(float timeBeforeDeploy) MatchmakerAcceptPatches.GClass3163.ChangeStatus("Waiting for other players to finish loading..."); - fikaStartButton?.SetActive(true); + if (fikaStartButton != null) + { + fikaStartButton.SetActive(true); + } if (MatchmakerAcceptPatches.IsServer) { @@ -598,7 +607,10 @@ private async void DeployScreen(float timeBeforeDeploy) Singleton.Instance.SendDataToAll(writer, ref syncPacket, LiteNetLib.DeliveryMethod.ReliableUnordered); } - dynamicAI?.AddHumans(); + if (dynamicAI != null) + { + dynamicAI.AddHumans(); + } } else if (MatchmakerAcceptPatches.IsClient) { @@ -790,10 +802,16 @@ public override async Task vmethod_2(int playerId, Vector3 position writer.Reset(); Singleton.Instance.SendDataToAll(writer, ref packet, LiteNetLib.DeliveryMethod.ReliableOrdered); - fikaStartButton?.SetActive(false); + if (fikaStartButton != null) + { + fikaStartButton.SetActive(false); + } }); Traverse.Create(startButtonComponent).Field("OnClick").SetValue(newStartEvent); - customButton?.SetActive(true); + if (customButton != null) + { + customButton.SetActive(true); + } fikaStartButton = customButtonStart; } } @@ -827,7 +845,10 @@ public override async Task vmethod_2(int playerId, Vector3 position await WaitForPlayers(); Destroy(customButton); - fikaStartButton?.SetActive(false); + if (fikaStartButton != null) + { + fikaStartButton.SetActive(false); + } myPlayer.ActiveHealthController.DiedEvent += MainPlayerDied; @@ -962,7 +983,10 @@ private async Task WaitForPlayers() { Logger.LogInfo("Starting task to wait for other players."); - MatchmakerAcceptPatches.GClass3163?.ChangeStatus($"Initializing Coop Game..."); + if (MatchmakerAcceptPatches.GClass3163 != null) + { + MatchmakerAcceptPatches.GClass3163.ChangeStatus($"Initializing Coop Game..."); + } int numbersOfPlayersToWaitFor = 0; if (MatchmakerAcceptPatches.IsServer) @@ -1193,14 +1217,20 @@ public override IEnumerator vmethod_4(float startDelay, BotControllerSettings co if (Location_0.OldSpawn && wavesSpawnScenario_0.SpawnWaves != null && wavesSpawnScenario_0.SpawnWaves.Length != 0) { Logger.LogInfo("Running old spawn system. Waves: " + wavesSpawnScenario_0.SpawnWaves.Length); - wavesSpawnScenario_0?.Run(EBotsSpawnMode.Anyway); + if (wavesSpawnScenario_0 != null) + { + wavesSpawnScenario_0.Run(EBotsSpawnMode.Anyway); + } } if (Location_0.NewSpawn) { Logger.LogInfo("Running new spawn system."); - nonWavesSpawnScenario_0?.Run(); - } + if (nonWavesSpawnScenario_0 != null) + { + nonWavesSpawnScenario_0.Run(); + } + } GClass579.Run(EBotsSpawnMode.Anyway); @@ -1208,9 +1238,18 @@ public override IEnumerator vmethod_4(float startDelay, BotControllerSettings co } else { - wavesSpawnScenario_0?.Stop(); - nonWavesSpawnScenario_0?.Stop(); - GClass579?.Stop(); + if (wavesSpawnScenario_0 != null) + { + wavesSpawnScenario_0.Stop(); + } + if (nonWavesSpawnScenario_0 != null) + { + nonWavesSpawnScenario_0.Stop(); + } + if (GClass579 != null) + { + GClass579.Stop(); + } } yield return new WaitForEndOfFrame(); @@ -1421,11 +1460,11 @@ public void Extract(Player player, ExfiltrationPoint point) { if (MatchmakerAcceptPatches.IsClient) { - Singleton.Instance?.SendData(new NetDataWriter(), ref genericPacket, LiteNetLib.DeliveryMethod.ReliableOrdered); + Singleton.Instance.SendData(new NetDataWriter(), ref genericPacket, LiteNetLib.DeliveryMethod.ReliableOrdered); } else if (MatchmakerAcceptPatches.IsServer) { - Singleton.Instance?.SendDataToAll(new NetDataWriter(), ref genericPacket, LiteNetLib.DeliveryMethod.ReliableOrdered); + Singleton.Instance.SendDataToAll(new NetDataWriter(), ref genericPacket, LiteNetLib.DeliveryMethod.ReliableOrdered); ClearHostAI(player); } } @@ -1522,7 +1561,7 @@ public override void Stop(string profileId, ExitStatus exitStatus, string exitNa Logger.LogInfo("CoopGame::Stop"); CoopPlayer myPlayer = (CoopPlayer)Singleton.Instance.MainPlayer; - myPlayer.PacketSender?.DestroyThis(); + myPlayer.PacketSender.DestroyThis(); if (myPlayer.Side != EPlayerSide.Savage) { @@ -1555,9 +1594,18 @@ public override void Stop(string profileId, ExitStatus exitStatus, string exitNa botsController_0.DestroyInfo(gparam_0.Player); } - GClass579?.Stop(); - nonWavesSpawnScenario_0?.Stop(); - wavesSpawnScenario_0?.Stop(); + if (GClass579 != null) + { + GClass579.Stop(); + } + if (nonWavesSpawnScenario_0 != null) + { + nonWavesSpawnScenario_0.Stop(); + } + if (wavesSpawnScenario_0 != null) + { + wavesSpawnScenario_0.Stop(); + } try { @@ -1631,7 +1679,10 @@ public override void Stop(string profileId, ExitStatus exitStatus, string exitNa { gameUI.TimerPanel.Close(); } - EnvironmentManager.Instance?.Stop(); + if (EnvironmentManager.Instance != null) + { + EnvironmentManager.Instance.Stop(); + } MonoBehaviourSingleton.Instance.StartBlackScreenShow(1f, 1f, new Action(stopManager.method_0)); GClass549.Config.UseSpiritPlayer = false; } @@ -1641,7 +1692,7 @@ private void StopFromError(string profileId, ExitStatus exitStatus) Logger.LogInfo("CoopGame::StopFromError"); CoopPlayer myPlayer = (CoopPlayer)Singleton.Instance.MainPlayer; - myPlayer.PacketSender?.DestroyThis(); + myPlayer.PacketSender.DestroyThis(); string exitName = null; float delay = 0f; @@ -1676,11 +1727,18 @@ private void StopFromError(string profileId, ExitStatus exitStatus) Destroy(CoopHandler.CoopHandlerParent); } - GClass579?.Stop(); - - nonWavesSpawnScenario_0?.Stop(); - - wavesSpawnScenario_0?.Stop(); + if (GClass579 != null) + { + GClass579.Stop(); + } + if (nonWavesSpawnScenario_0 != null) + { + nonWavesSpawnScenario_0.Stop(); + } + if (wavesSpawnScenario_0 != null) + { + wavesSpawnScenario_0.Stop(); + } ErrorExitManager stopManager = new() { @@ -1702,17 +1760,29 @@ private void StopFromError(string profileId, ExitStatus exitStatus) } } - exfilManager?.Stop(); + if (exfilManager != null) + { + exfilManager.Stop(); + } Status = GameStatus.Stopping; - GameTimer?.TryStop(); - endByExitTrigger?.Stop(); + if (GameTimer != null) + { + GameTimer.TryStop(); + } + if (endByExitTrigger != null) + { + endByExitTrigger.Stop(); + } if (gameUI.TimerPanel.enabled) { gameUI.TimerPanel.Close(); } - EnvironmentManager.Instance?.Stop(); + if (EnvironmentManager.Instance != null) + { + EnvironmentManager.Instance.Stop(); + } MonoBehaviourSingleton.Instance.StartBlackScreenShow(1f, 1f, new Action(stopManager.ExitOverride)); GClass549.Config.UseSpiritPlayer = false; } @@ -1749,9 +1819,9 @@ public override void Dispose() if (MatchmakerAcceptPatches.IsServer) { CoopPlayer coopPlayer = (CoopPlayer)Singleton.Instance.MainPlayer; - coopPlayer?.PacketSender.DestroyThis(); + coopPlayer.PacketSender.DestroyThis(); - Singleton.Instance?.NetServer.Stop(); + Singleton.Instance.NetServer.Stop(); Singleton.TryRelease(Singleton.Instance); FikaDynamicAI newDynamicAI = gameObject.GetComponent(); @@ -1764,7 +1834,7 @@ public override void Dispose() } else if (MatchmakerAcceptPatches.IsClient) { - Singleton.Instance?.NetClient.Stop(); + Singleton.Instance.NetClient.Stop(); Singleton.TryRelease(Singleton.Instance); // Resetting this array to null forces the game to re-allocate it if the client hosts the next session @@ -1807,12 +1877,15 @@ public void ExitOverride() { instance.CloseAllScreensForced(); } - baseLocalGame_0?.CleanUp(); - if (baseLocalGame_0 is not null) + if (baseLocalGame_0 != null) { + baseLocalGame_0.CleanUp(); baseLocalGame_0.Status = GameStatus.Stopped; } - MonoBehaviourSingleton.Instance?.FadeOutVolumeAfterRaid(); + if (MonoBehaviourSingleton.Instance != null) + { + MonoBehaviourSingleton.Instance.FadeOutVolumeAfterRaid(); + } MonoBehaviour instance2 = StaticManager.Instance; float num = delay; Action action; diff --git a/Fika.Core/Coop/PacketHandlers/BotPacketSender.cs b/Fika.Core/Coop/PacketHandlers/BotPacketSender.cs index 02fc1b1e..ef51e3eb 100644 --- a/Fika.Core/Coop/PacketHandlers/BotPacketSender.cs +++ b/Fika.Core/Coop/PacketHandlers/BotPacketSender.cs @@ -50,7 +50,7 @@ protected void FixedUpdate() player.hasGround, player.CurrentSurface, player.MovementContext.SurfaceNormal); Writer.Reset(); - Server?.SendDataToAll(Writer, ref playerStatePacket, DeliveryMethod.Unreliable); + Server.SendDataToAll(Writer, ref playerStatePacket, DeliveryMethod.Unreliable); player.LastDirection = Vector2.zero; // Bots give a constant input for some odd reason, resetting on FixedUpdate should be ok from my testing and does not cause sliding for clients } @@ -65,8 +65,8 @@ protected void Update() WeaponPacket firearmPacket = FirearmPackets.Dequeue(); firearmPacket.NetId = player.NetId; - Writer?.Reset(); - Server?.SendDataToAll(Writer, ref firearmPacket, DeliveryMethod.ReliableOrdered); + Writer.Reset(); + Server.SendDataToAll(Writer, ref firearmPacket, DeliveryMethod.ReliableOrdered); } } int healthPackets = DamagePackets.Count; @@ -77,8 +77,8 @@ protected void Update() DamagePacket healthPacket = DamagePackets.Dequeue(); healthPacket.NetId = player.NetId; - Writer?.Reset(); - Server?.SendDataToAll(Writer, ref healthPacket, DeliveryMethod.ReliableOrdered); + Writer.Reset(); + Server.SendDataToAll(Writer, ref healthPacket, DeliveryMethod.ReliableOrdered); } } int inventoryPackets = InventoryPackets.Count; @@ -89,8 +89,8 @@ protected void Update() InventoryPacket inventoryPacket = InventoryPackets.Dequeue(); inventoryPacket.NetId = player.NetId; - Writer?.Reset(); - Server?.SendDataToAll(Writer, ref inventoryPacket, DeliveryMethod.ReliableOrdered); + Writer.Reset(); + Server.SendDataToAll(Writer, ref inventoryPacket, DeliveryMethod.ReliableOrdered); } } int commonPlayerPackets = CommonPlayerPackets.Count; @@ -101,8 +101,8 @@ protected void Update() CommonPlayerPacket commonPlayerPacket = CommonPlayerPackets.Dequeue(); commonPlayerPacket.NetId = player.NetId; - Writer?.Reset(); - Server?.SendDataToAll(Writer, ref commonPlayerPacket, DeliveryMethod.ReliableOrdered); + Writer.Reset(); + Server.SendDataToAll(Writer, ref commonPlayerPacket, DeliveryMethod.ReliableOrdered); } } int healthSyncPackets = HealthSyncPackets.Count; @@ -113,8 +113,8 @@ protected void Update() HealthSyncPacket healthSyncPacket = HealthSyncPackets.Dequeue(); healthSyncPacket.NetId = player.NetId; - Writer?.Reset(); - Server?.SendDataToAll(Writer, ref healthSyncPacket, DeliveryMethod.ReliableOrdered); + Writer.Reset(); + Server.SendDataToAll(Writer, ref healthSyncPacket, DeliveryMethod.ReliableOrdered); } } } diff --git a/Fika.Core/Coop/PacketHandlers/ClientPacketSender.cs b/Fika.Core/Coop/PacketHandlers/ClientPacketSender.cs index 1e7169d4..3475682a 100644 --- a/Fika.Core/Coop/PacketHandlers/ClientPacketSender.cs +++ b/Fika.Core/Coop/PacketHandlers/ClientPacketSender.cs @@ -53,7 +53,7 @@ protected void FixedUpdate() player.hasGround, player.CurrentSurface, player.MovementContext.SurfaceNormal); Writer.Reset(); - Client?.SendData(Writer, ref playerStatePacket, DeliveryMethod.Unreliable); + Client.SendData(Writer, ref playerStatePacket, DeliveryMethod.Unreliable); if (player.MovementIdlingTime > 0.01f) { @@ -71,8 +71,8 @@ protected void Update() WeaponPacket firearmPacket = FirearmPackets.Dequeue(); firearmPacket.NetId = player.NetId; - Writer?.Reset(); - Client?.SendData(Writer, ref firearmPacket, DeliveryMethod.ReliableOrdered); + Writer.Reset(); + Client.SendData(Writer, ref firearmPacket, DeliveryMethod.ReliableOrdered); } } int healthPackets = DamagePackets.Count; @@ -83,8 +83,8 @@ protected void Update() DamagePacket healthPacket = DamagePackets.Dequeue(); healthPacket.NetId = player.NetId; - Writer?.Reset(); - Client?.SendData(Writer, ref healthPacket, DeliveryMethod.ReliableOrdered); + Writer.Reset(); + Client.SendData(Writer, ref healthPacket, DeliveryMethod.ReliableOrdered); } } int inventoryPackets = InventoryPackets.Count; @@ -95,8 +95,8 @@ protected void Update() InventoryPacket inventoryPacket = InventoryPackets.Dequeue(); inventoryPacket.NetId = player.NetId; - Writer?.Reset(); - Client?.SendData(Writer, ref inventoryPacket, DeliveryMethod.ReliableOrdered); + Writer.Reset(); + Client.SendData(Writer, ref inventoryPacket, DeliveryMethod.ReliableOrdered); } } int commonPlayerPackets = CommonPlayerPackets.Count; @@ -107,8 +107,8 @@ protected void Update() CommonPlayerPacket commonPlayerPacket = CommonPlayerPackets.Dequeue(); commonPlayerPacket.NetId = player.NetId; - Writer?.Reset(); - Client?.SendData(Writer, ref commonPlayerPacket, DeliveryMethod.ReliableOrdered); + Writer.Reset(); + Client.SendData(Writer, ref commonPlayerPacket, DeliveryMethod.ReliableOrdered); } } int healthSyncPackets = HealthSyncPackets.Count; @@ -119,8 +119,8 @@ protected void Update() HealthSyncPacket healthSyncPacket = HealthSyncPackets.Dequeue(); healthSyncPacket.NetId = player.NetId; - Writer?.Reset(); - Client?.SendData(Writer, ref healthSyncPacket, DeliveryMethod.ReliableOrdered); + Writer.Reset(); + Client.SendData(Writer, ref healthSyncPacket, DeliveryMethod.ReliableOrdered); } } if (FikaPlugin.UsePingSystem.Value @@ -129,7 +129,7 @@ protected void Update() && Input.GetKey(FikaPlugin.PingButton.Value.MainKey) && FikaPlugin.PingButton.Value.Modifiers.All(Input.GetKey)) { - player?.Ping(); + player.Ping(); } } @@ -154,13 +154,13 @@ private IEnumerator SyncWorld() yield return new WaitForSeconds(10f); - Writer?.Reset(); + Writer.Reset(); GameTimerPacket gameTimerPacket = new(true); - Client?.SendData(Writer, ref gameTimerPacket, DeliveryMethod.ReliableOrdered); + Client.SendData(Writer, ref gameTimerPacket, DeliveryMethod.ReliableOrdered); - Writer?.Reset(); + Writer.Reset(); ExfiltrationPacket exfilPacket = new(true); - Client?.SendData(Writer, ref exfilPacket, DeliveryMethod.ReliableOrdered); + Client.SendData(Writer, ref exfilPacket, DeliveryMethod.ReliableOrdered); } private IEnumerator SyncWeather() @@ -188,8 +188,8 @@ private IEnumerator SyncWeather() HasData = false }; - Writer?.Reset(); - Client?.SendData(Writer, ref packet, DeliveryMethod.ReliableOrdered); + Writer.Reset(); + Client.SendData(Writer, ref packet, DeliveryMethod.ReliableOrdered); } public void DestroyThis() diff --git a/Fika.Core/Coop/PacketHandlers/ServerPacketSender.cs b/Fika.Core/Coop/PacketHandlers/ServerPacketSender.cs index 99f40b1e..58efa421 100644 --- a/Fika.Core/Coop/PacketHandlers/ServerPacketSender.cs +++ b/Fika.Core/Coop/PacketHandlers/ServerPacketSender.cs @@ -60,7 +60,7 @@ protected void FixedUpdate() player.hasGround, player.CurrentSurface, player.MovementContext.SurfaceNormal); Writer.Reset(); - Server?.SendDataToAll(Writer, ref playerStatePacket, DeliveryMethod.Unreliable); + Server.SendDataToAll(Writer, ref playerStatePacket, DeliveryMethod.Unreliable); if (player.MovementIdlingTime > 0.01f) { @@ -78,8 +78,8 @@ protected void Update() WeaponPacket firearmPacket = FirearmPackets.Dequeue(); firearmPacket.NetId = player.NetId; - Writer?.Reset(); - Server?.SendDataToAll(Writer, ref firearmPacket, DeliveryMethod.ReliableOrdered); + Writer.Reset(); + Server.SendDataToAll(Writer, ref firearmPacket, DeliveryMethod.ReliableOrdered); } } int healthPackets = DamagePackets.Count; @@ -90,8 +90,8 @@ protected void Update() DamagePacket healthPacket = DamagePackets.Dequeue(); healthPacket.NetId = player.NetId; - Writer?.Reset(); - Server?.SendDataToAll(Writer, ref healthPacket, DeliveryMethod.ReliableOrdered); + Writer.Reset(); + Server.SendDataToAll(Writer, ref healthPacket, DeliveryMethod.ReliableOrdered); } } int inventoryPackets = InventoryPackets.Count; @@ -102,8 +102,8 @@ protected void Update() InventoryPacket inventoryPacket = InventoryPackets.Dequeue(); inventoryPacket.NetId = player.NetId; - Writer?.Reset(); - Server?.SendDataToAll(Writer, ref inventoryPacket, DeliveryMethod.ReliableOrdered); + Writer.Reset(); + Server.SendDataToAll(Writer, ref inventoryPacket, DeliveryMethod.ReliableOrdered); } } int commonPlayerPackets = CommonPlayerPackets.Count; @@ -114,8 +114,8 @@ protected void Update() CommonPlayerPacket commonPlayerPacket = CommonPlayerPackets.Dequeue(); commonPlayerPacket.NetId = player.NetId; - Writer?.Reset(); - Server?.SendDataToAll(Writer, ref commonPlayerPacket, DeliveryMethod.ReliableOrdered); + Writer.Reset(); + Server.SendDataToAll(Writer, ref commonPlayerPacket, DeliveryMethod.ReliableOrdered); } } int healthSyncPackets = HealthSyncPackets.Count; @@ -126,8 +126,8 @@ protected void Update() HealthSyncPacket healthSyncPacket = HealthSyncPackets.Dequeue(); healthSyncPacket.NetId = player.NetId; - Writer?.Reset(); - Server?.SendDataToAll(Writer, ref healthSyncPacket, DeliveryMethod.ReliableOrdered); + Writer.Reset(); + Server.SendDataToAll(Writer, ref healthSyncPacket, DeliveryMethod.ReliableOrdered); } } if (FikaPlugin.UsePingSystem.Value @@ -136,7 +136,7 @@ protected void Update() && Input.GetKey(FikaPlugin.PingButton.Value.MainKey) && FikaPlugin.PingButton.Value.Modifiers.All(Input.GetKey)) { - player?.Ping(); + player.Ping(); } } @@ -178,8 +178,8 @@ private IEnumerator SendTrainTime() DepartureTime = time }; - Writer?.Reset(); - Server?.SendDataToAll(Writer, ref packet, DeliveryMethod.ReliableOrdered); + Writer.Reset(); + Server.SendDataToAll(Writer, ref packet, DeliveryMethod.ReliableOrdered); } else { diff --git a/Fika.Core/Coop/Patches/Minefield/Minefield_method_2_Patch.cs b/Fika.Core/Coop/Patches/Minefield/Minefield_method_2_Patch.cs index f774406f..386fcdaf 100644 --- a/Fika.Core/Coop/Patches/Minefield/Minefield_method_2_Patch.cs +++ b/Fika.Core/Coop/Patches/Minefield/Minefield_method_2_Patch.cs @@ -74,7 +74,7 @@ private static void DoReplicatedMineDamage(IPlayer player, float distance, bool foreach (BodyPartCollider bodyPartCollider in enumerable) { - coopPlayer.PacketSender?.DamagePackets?.Enqueue(new() + coopPlayer.PacketSender.DamagePackets.Enqueue(new() { DamageInfo = new() { diff --git a/Fika.Core/Coop/Players/CoopBot.cs b/Fika.Core/Coop/Players/CoopBot.cs index e1d594de..1821ed80 100644 --- a/Fika.Core/Coop/Players/CoopBot.cs +++ b/Fika.Core/Coop/Players/CoopBot.cs @@ -253,7 +253,7 @@ private IEnumerator DestroyNetworkedComponents() { yield return new WaitForSeconds(2); - PacketSender?.DestroyThis(); + PacketSender.DestroyThis(); } public override void UpdateTick() @@ -359,7 +359,7 @@ internal void SendPacket() return; } - coopBot.PacketSender?.CommonPlayerPackets?.Enqueue(new() + coopBot.PacketSender.CommonPlayerPackets.Enqueue(new() { HasProceedPacket = true, ProceedPacket = new() diff --git a/Fika.Core/Coop/Players/CoopPlayer.cs b/Fika.Core/Coop/Players/CoopPlayer.cs index eb50eb76..afa32b7a 100644 --- a/Fika.Core/Coop/Players/CoopPlayer.cs +++ b/Fika.Core/Coop/Players/CoopPlayer.cs @@ -124,8 +124,8 @@ public override void BtrInteraction(BTRSide btr, byte placeId, EInteractionType InteractPacket = btr.GetInteractWithBtrPacket(placeId, interaction) }; - PacketSender?.Writer?.Reset(); - PacketSender?.Client?.SendData(PacketSender?.Writer, ref packet, LiteNetLib.DeliveryMethod.ReliableOrdered); + PacketSender.Writer.Reset(); + PacketSender.Client.SendData(PacketSender.Writer, ref packet, LiteNetLib.DeliveryMethod.ReliableOrdered); } else if (MatchmakerAcceptPatches.IsServer) { @@ -142,8 +142,8 @@ public override void BtrInteraction(BTRSide btr, byte placeId, EInteractionType InteractPacket = interactPacket }; - PacketSender?.Writer?.Reset(); - PacketSender?.Server?.SendDataToAll(PacketSender?.Writer, ref packet, LiteNetLib.DeliveryMethod.ReliableOrdered); + PacketSender.Writer.Reset(); + PacketSender.Server.SendDataToAll(PacketSender.Writer, ref packet, LiteNetLib.DeliveryMethod.ReliableOrdered); } } } @@ -158,7 +158,10 @@ public void ProcessInteractWithBTR(BTRInteractionPacket packet) { if (CoopHandler.TryGetCoopHandler(out CoopHandler coopHandler)) { - coopHandler.clientBTR?.ClientInteraction(this, packet.InteractPacket); + if (coopHandler.clientBTR != null) + { + coopHandler.clientBTR.ClientInteraction(this, packet.InteractPacket); + } } } } @@ -216,7 +219,7 @@ public override GClass1676 ApplyShot(DamageInfo damageInfo, EBodyPart bodyPartTy public override void Proceed(bool withNetwork, Callback callback, bool scheduled = true) { base.Proceed(withNetwork, callback, scheduled); - PacketSender?.CommonPlayerPackets?.Enqueue(new() + PacketSender.CommonPlayerPackets.Enqueue(new() { HasProceedPacket = true, ProceedPacket = new() @@ -322,7 +325,7 @@ public override void DropCurrentController(Action callback, bool fastDrop, Item { base.DropCurrentController(callback, fastDrop, nextControllerItem); - /*PacketSender?.CommonPlayerPackets?.Enqueue(new() + /*PacketSender.CommonPlayerPackets.Enqueue(new() { HasDrop = true, DropPacket = new() @@ -342,7 +345,7 @@ public override void SetInventoryOpened(bool opened) } base.SetInventoryOpened(opened); - PacketSender?.CommonPlayerPackets?.Enqueue(new() + PacketSender.CommonPlayerPackets.Enqueue(new() { HasInventoryChanged = true, SetInventoryOpen = opened @@ -352,7 +355,7 @@ public override void SetInventoryOpened(bool opened) public override void SetCompassState(bool value) { base.SetCompassState(value); - PacketSender?.FirearmPackets?.Enqueue(new() + PacketSender.FirearmPackets.Enqueue(new() { HasCompassChange = true, CompassState = value @@ -373,7 +376,7 @@ public override void SendHeadlightsPacket(bool isSilent) { GStruct163[] lightStates = _helmetLightControllers.Select(new Func(ClientPlayer.Class1430.class1430_0.method_0)).ToArray(); - PacketSender?.CommonPlayerPackets?.Enqueue(new() + PacketSender.CommonPlayerPackets.Enqueue(new() { HasHeadLightsPacket = true, HeadLightsPacket = new() @@ -395,7 +398,7 @@ public override void OnPhraseTold(EPhraseTrigger @event, TaggedClip clip, TagBan if (ActiveHealthController.IsAlive) { - PacketSender?.CommonPlayerPackets?.Enqueue(new() + PacketSender.CommonPlayerPackets.Enqueue(new() { Phrase = @event, PhraseIndex = clip.NetId @@ -406,7 +409,7 @@ public override void OnPhraseTold(EPhraseTrigger @event, TaggedClip clip, TagBan public override void OperateStationaryWeapon(StationaryWeapon stationaryWeapon, GStruct169.EStationaryCommand command) { base.OperateStationaryWeapon(stationaryWeapon, command); - PacketSender?.CommonPlayerPackets?.Enqueue(new() + PacketSender.CommonPlayerPackets.Enqueue(new() { HasStationaryPacket = true, StationaryPacket = new() @@ -447,7 +450,7 @@ public override void vmethod_0(WorldInteractiveObject interactiveObject, Interac ItemId = (interactionResult is GClass2964 keyInteractionResult) ? keyInteractionResult.Key.Item.Id : string.Empty } }; - PacketSender?.CommonPlayerPackets?.Enqueue(packet); + PacketSender.CommonPlayerPackets.Enqueue(packet); } // Execute @@ -472,7 +475,7 @@ public override void vmethod_1(WorldInteractiveObject door, InteractionResult in ItemId = (interactionResult is GClass2964 keyInteractionResult) ? keyInteractionResult.Key.Item.Id : string.Empty } }; - PacketSender?.CommonPlayerPackets?.Enqueue(packet); + PacketSender.CommonPlayerPackets.Enqueue(packet); UpdateInteractionCast(); } @@ -480,7 +483,7 @@ public override void vmethod_1(WorldInteractiveObject door, InteractionResult in public override void vmethod_3(EGesture gesture) { base.vmethod_3(gesture); - PacketSender?.FirearmPackets?.Enqueue(new() + PacketSender.FirearmPackets.Enqueue(new() { Gesture = gesture }); @@ -530,7 +533,7 @@ private IEnumerator DestroyNetworkedComponents() { yield return new WaitForSeconds(2); - PacketSender?.DestroyThis(); + PacketSender.DestroyThis(); } public override void Move(Vector2 direction) @@ -761,7 +764,7 @@ public void Ping() Color pingColor = FikaPlugin.PingColor.Value; pingColor = new(pingColor.r, pingColor.g, pingColor.b, 1); // ref so that we can mutate it if we want to, ex: if I ping a switch I want it at the switch.gameObject.position + Vector3.up - abstractPing?.Initialize(ref hitPoint, userData, pingColor); + abstractPing.Initialize(ref hitPoint, userData, pingColor); GenericPacket genericPacket = new() { @@ -773,14 +776,14 @@ public void Ping() Nickname = Profile.Nickname }; - PacketSender?.Writer?.Reset(); + PacketSender.Writer.Reset(); if (MatchmakerAcceptPatches.IsServer) { - PacketSender?.Server?.SendDataToAll(PacketSender.Writer, ref genericPacket, LiteNetLib.DeliveryMethod.ReliableOrdered); + PacketSender.Server.SendDataToAll(PacketSender.Writer, ref genericPacket, LiteNetLib.DeliveryMethod.ReliableOrdered); } else if (MatchmakerAcceptPatches.IsClient) { - PacketSender?.Client?.SendData(PacketSender.Writer, ref genericPacket, LiteNetLib.DeliveryMethod.ReliableOrdered); + PacketSender.Client.SendData(PacketSender.Writer, ref genericPacket, LiteNetLib.DeliveryMethod.ReliableOrdered); } if (FikaPlugin.PlayPingAnimation.Value) @@ -934,7 +937,7 @@ public virtual void HandleCommonPacket(in CommonPlayerPacket packet) { if (this is ObservedCoopPlayer observedCoopPlayer) { - observedCoopPlayer?.HandleProceedPacket(packet.ProceedPacket); + observedCoopPlayer.HandleProceedPacket(packet.ProceedPacket); } } @@ -1339,7 +1342,7 @@ public override void OnDestroy() public override void Dispose() { base.Dispose(); - PacketSender?.DestroyThis(); + PacketSender.DestroyThis(); } public override void SendHandsInteractionStateChanged(bool value, int animationId) @@ -1347,7 +1350,7 @@ public override void SendHandsInteractionStateChanged(bool value, int animationI base.SendHandsInteractionStateChanged(value, animationId); if (value) { - PacketSender?.CommonPlayerPackets?.Enqueue(new() + PacketSender.CommonPlayerPackets.Enqueue(new() { Pickup = value, PickupAnimation = animationId @@ -1357,7 +1360,7 @@ public override void SendHandsInteractionStateChanged(bool value, int animationI public override void OnVaulting() { - PacketSender?.CommonPlayerPackets?.Enqueue(new() + PacketSender.CommonPlayerPackets.Enqueue(new() { HasVaultPacket = true, VaultPacket = new() @@ -1421,7 +1424,7 @@ private class LootableContainerInteractionHandler(CoopPlayer player, LootableCon public void Handle() { - player.PacketSender?.CommonPlayerPackets?.Enqueue(new() + player.PacketSender.CommonPlayerPackets.Enqueue(new() { HasContainerInteractionPacket = true, ContainerInteractionPacket = new() @@ -1459,7 +1462,7 @@ internal void SendPacket() return; } - coopPlayer.PacketSender?.CommonPlayerPackets?.Enqueue(new() + coopPlayer.PacketSender.CommonPlayerPackets.Enqueue(new() { HasProceedPacket = true, ProceedPacket = new() @@ -1494,7 +1497,7 @@ internal QuickUseItemController ReturnController() internal void SendPacket() { - coopPlayer.PacketSender?.CommonPlayerPackets?.Enqueue(new() + coopPlayer.PacketSender.CommonPlayerPackets.Enqueue(new() { HasProceedPacket = true, ProceedPacket = new() @@ -1531,7 +1534,7 @@ internal MedsController ReturnController() internal void SendPacket() { - coopPlayer.PacketSender?.CommonPlayerPackets?.Enqueue(new() + coopPlayer.PacketSender.CommonPlayerPackets.Enqueue(new() { HasProceedPacket = true, ProceedPacket = new() @@ -1571,7 +1574,7 @@ internal MedsController ReturnController() internal void SendPacket() { - coopPlayer.PacketSender?.CommonPlayerPackets?.Enqueue(new() + coopPlayer.PacketSender.CommonPlayerPackets.Enqueue(new() { HasProceedPacket = true, ProceedPacket = new() @@ -1609,7 +1612,7 @@ internal CoopClientKnifeController ReturnController() internal void SendPacket() { - coopPlayer.PacketSender?.CommonPlayerPackets?.Enqueue(new() + coopPlayer.PacketSender.CommonPlayerPackets.Enqueue(new() { HasProceedPacket = true, ProceedPacket = new() @@ -1644,7 +1647,7 @@ internal QuickKnifeKickController ReturnController() internal void SendPacket() { - coopPlayer.PacketSender?.CommonPlayerPackets?.Enqueue(new() + coopPlayer.PacketSender.CommonPlayerPackets.Enqueue(new() { HasProceedPacket = true, ProceedPacket = new() @@ -1679,7 +1682,7 @@ internal CoopClientGrenadeController ReturnController() internal void SendPacket() { - coopPlayer.PacketSender?.CommonPlayerPackets?.Enqueue(new() + coopPlayer.PacketSender.CommonPlayerPackets.Enqueue(new() { HasProceedPacket = true, ProceedPacket = new() @@ -1714,7 +1717,7 @@ internal CoopClientQuickGrenadeController ReturnController() internal void SendPacket() { - coopPlayer.PacketSender?.CommonPlayerPackets?.Enqueue(new() + coopPlayer.PacketSender.CommonPlayerPackets.Enqueue(new() { HasProceedPacket = true, ProceedPacket = new() diff --git a/Fika.Core/Coop/Players/ObservedCoopPlayer.cs b/Fika.Core/Coop/Players/ObservedCoopPlayer.cs index a604f011..aeb4b949 100644 --- a/Fika.Core/Coop/Players/ObservedCoopPlayer.cs +++ b/Fika.Core/Coop/Players/ObservedCoopPlayer.cs @@ -261,7 +261,7 @@ public override void ApplyDamageInfo(DamageInfo damageInfo, EBodyPart bodyPartTy { if (damageInfo.DamageType == EDamageType.Landmine && MatchmakerAcceptPatches.IsServer) { - PacketSender?.DamagePackets?.Enqueue(new() + PacketSender.DamagePackets.Enqueue(new() { DamageInfo = new() { @@ -333,7 +333,7 @@ public override GClass1676 ApplyShot(DamageInfo damageInfo, EBodyPart bodyPartTy if (damageInfo.DamageType == EDamageType.Sniper && MatchmakerAcceptPatches.IsServer) { ShotReactions(damageInfo, bodyPartType); - PacketSender?.DamagePackets?.Enqueue(new() + PacketSender.DamagePackets.Enqueue(new() { DamageInfo = new() { @@ -401,7 +401,7 @@ public override GClass1676 ApplyShot(DamageInfo damageInfo, EBodyPart bodyPartTy colliderType = bodyPartCollider.BodyPartColliderType; } - PacketSender?.DamagePackets?.Enqueue(new() + PacketSender.DamagePackets.Enqueue(new() { DamageInfo = new() { @@ -461,7 +461,7 @@ public override GClass1676 ApplyShot(DamageInfo damageInfo, EBodyPart bodyPartTy colliderType = bodyPartCollider.BodyPartColliderType; } - PacketSender?.DamagePackets?.Enqueue(new() + PacketSender.DamagePackets.Enqueue(new() { DamageInfo = new() { @@ -602,7 +602,10 @@ public override void vmethod_3(EGesture gesture) if (gesture == EGesture.Hello) { InteractionRaycast(); - InteractablePlayer?.ShowHelloNotification(Profile.Nickname); + if (InteractablePlayer != null) + { + InteractablePlayer.ShowHelloNotification(Profile.Nickname); + } } base.vmethod_3(gesture); } @@ -826,7 +829,10 @@ public override void SetInventory(EquipmentClass equipmentClass) Transform alternativeHolsterBone = PlayerBody.GetAlternativeHolsterBone(equipmentSlot); PlayerBody.GClass1860 gclass = new(PlayerBody, Inventory.Equipment.GetSlot(equipmentSlot), slotBone, equipmentSlot, Inventory.Equipment.GetSlot(EquipmentSlot.Backpack), alternativeHolsterBone); PlayerBody.GClass1860 gclass2 = PlayerBody.SlotViews.AddOrReplace(equipmentSlot, gclass); - gclass2?.Dispose(); + if (gclass2 != null) + { + gclass2.Dispose(); + } } //PlayerBody.Init(PlayerBody.BodyCustomization, Inventory.Equipment, shouldSet ? itemInHands : null, LayerMask.NameToLayer("Player"), Side); @@ -1142,7 +1148,10 @@ public override void InitAudioController() private void SetSoundRollOff() { - NestedStepSoundSource?.SetRolloff(60f * ProtagonistHearing); + if (NestedStepSoundSource != null) + { + NestedStepSoundSource.SetRolloff(60f * ProtagonistHearing); + } } public override bool UpdateGrenadeAnimatorDuePoV() diff --git a/Fika.Core/Networking/FikaClient.cs b/Fika.Core/Networking/FikaClient.cs index eca51392..ec69f925 100644 --- a/Fika.Core/Networking/FikaClient.cs +++ b/Fika.Core/Networking/FikaClient.cs @@ -245,7 +245,10 @@ private void OnBTRInteractionPacketReceived(BTRInteractionPacket packet) private void OnBTRPacketReceived(BTRPacket packet) { - CoopHandler.clientBTR?.btrPackets.Enqueue(packet); + if (CoopHandler.clientBTR != null) + { + CoopHandler.clientBTR.btrPackets.Enqueue(packet); + } } private void OnWeatherPacketReceived(WeatherPacket packet) @@ -423,7 +426,10 @@ private void OnGenericPacketReceived(GenericPacket packet) break; case EPackageType.TraderServiceNotification: { - CoopHandler.clientBTR?.DisplayNetworkNotification(packet.TraderServiceType); + if (CoopHandler.clientBTR) + { + CoopHandler.clientBTR.DisplayNetworkNotification(packet.TraderServiceType); + } } break; case EPackageType.DisposeBot: @@ -499,7 +505,7 @@ private void OnHealthSyncPacketReceived(HealthSyncPacket packet) { if (Players.TryGetValue(packet.NetId, out CoopPlayer playerToApply)) { - playerToApply?.PacketReceiver?.HealthSyncPackets?.Enqueue(packet); + playerToApply.PacketReceiver?.HealthSyncPackets?.Enqueue(packet); } } @@ -593,7 +599,7 @@ private void OnCommonPlayerPacketReceived(CommonPlayerPacket packet) { if (Players.TryGetValue(packet.NetId, out CoopPlayer playerToApply)) { - playerToApply?.PacketReceiver?.CommonPlayerPackets?.Enqueue(packet); + playerToApply.PacketReceiver?.CommonPlayerPackets?.Enqueue(packet); } } @@ -601,7 +607,7 @@ private void OnInventoryPacketReceived(InventoryPacket packet) { if (Players.TryGetValue(packet.NetId, out CoopPlayer playerToApply)) { - playerToApply?.PacketReceiver?.InventoryPackets?.Enqueue(packet); + playerToApply.PacketReceiver?.InventoryPackets?.Enqueue(packet); } } @@ -609,7 +615,7 @@ private void OnDamagePacketReceived(DamagePacket packet) { if (Players.TryGetValue(packet.NetId, out CoopPlayer playerToApply)) { - playerToApply?.PacketReceiver?.DamagePackets?.Enqueue(packet); + playerToApply.PacketReceiver?.DamagePackets?.Enqueue(packet); } } @@ -617,7 +623,7 @@ private void OnFirearmPacketReceived(WeaponPacket packet) { if (Players.TryGetValue(packet.NetId, out CoopPlayer playerToApply)) { - playerToApply?.PacketReceiver?.FirearmPackets?.Enqueue(packet); + playerToApply.PacketReceiver?.FirearmPackets?.Enqueue(packet); } } diff --git a/Fika.Core/Networking/FikaServer.cs b/Fika.Core/Networking/FikaServer.cs index 3ce0aaed..20d0a820 100644 --- a/Fika.Core/Networking/FikaServer.cs +++ b/Fika.Core/Networking/FikaServer.cs @@ -229,7 +229,10 @@ private void OnDeathPacketReceived(DeathPacket packet, NetPeer peer) private void OnBTRServicePacketReceived(BTRServicePacket packet, NetPeer peer) { - CoopHandler.serverBTR?.NetworkBtrTraderServicePurchased(packet); + if (CoopHandler.serverBTR != null) + { + CoopHandler.serverBTR.NetworkBtrTraderServicePurchased(packet); + } } private void OnBTRInteractionPacketReceived(BTRInteractionPacket packet, NetPeer peer) @@ -389,7 +392,7 @@ private void OnHealthSyncPacketReceived(HealthSyncPacket packet, NetPeer peer) { if (Players.TryGetValue(packet.NetId, out CoopPlayer playerToApply)) { - playerToApply?.PacketReceiver?.HealthSyncPackets?.Enqueue(packet); + playerToApply.PacketReceiver?.HealthSyncPackets?.Enqueue(packet); } _dataWriter.Reset(); @@ -415,7 +418,6 @@ private void OnInformationPacketReceived(InformationPacket packet, NetPeer peer) private void OnAllCharacterRequestPacketReceived(AllCharacterRequestPacket packet, NetPeer peer) { - // This method needs to be refined. For some reason the ping-pong has to be run twice for it to work on the host? if (packet.IsRequest) { foreach (CoopPlayer player in CoopHandler.Players.Values) @@ -469,7 +471,7 @@ private void OnCommonPlayerPacketReceived(CommonPlayerPacket packet, NetPeer pee { if (Players.TryGetValue(packet.NetId, out CoopPlayer playerToApply)) { - playerToApply?.PacketReceiver?.CommonPlayerPackets?.Enqueue(packet); + playerToApply.PacketReceiver?.CommonPlayerPackets?.Enqueue(packet); } _dataWriter.Reset(); @@ -571,7 +573,7 @@ private void OnDamagePacketReceived(DamagePacket packet, NetPeer peer) { if (Players.TryGetValue(packet.NetId, out CoopPlayer playerToApply)) { - playerToApply?.PacketReceiver?.DamagePackets?.Enqueue(packet); + playerToApply.PacketReceiver?.DamagePackets?.Enqueue(packet); } _dataWriter.Reset(); @@ -582,7 +584,7 @@ private void OnFirearmPacketReceived(WeaponPacket packet, NetPeer peer) { if (Players.TryGetValue(packet.NetId, out CoopPlayer playerToApply)) { - playerToApply?.PacketReceiver?.FirearmPackets?.Enqueue(packet); + playerToApply.PacketReceiver?.FirearmPackets?.Enqueue(packet); } _dataWriter.Reset(); From 65d448a320fe0d74584932b812b4d26a0e629eb7 Mon Sep 17 00:00:00 2001 From: Lacyway <20912169+Lacyway@users.noreply.github.com> Date: Tue, 21 May 2024 10:20:42 +0200 Subject: [PATCH 04/32] Null checks to destroy --- Fika.Core/Coop/Players/CoopBot.cs | 5 ++++- Fika.Core/Coop/Players/CoopPlayer.cs | 10 ++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/Fika.Core/Coop/Players/CoopBot.cs b/Fika.Core/Coop/Players/CoopBot.cs index 1821ed80..e5ad3f05 100644 --- a/Fika.Core/Coop/Players/CoopBot.cs +++ b/Fika.Core/Coop/Players/CoopBot.cs @@ -253,7 +253,10 @@ private IEnumerator DestroyNetworkedComponents() { yield return new WaitForSeconds(2); - PacketSender.DestroyThis(); + if (PacketSender != null) + { + PacketSender.DestroyThis(); + } } public override void UpdateTick() diff --git a/Fika.Core/Coop/Players/CoopPlayer.cs b/Fika.Core/Coop/Players/CoopPlayer.cs index afa32b7a..4bef608b 100644 --- a/Fika.Core/Coop/Players/CoopPlayer.cs +++ b/Fika.Core/Coop/Players/CoopPlayer.cs @@ -533,7 +533,10 @@ private IEnumerator DestroyNetworkedComponents() { yield return new WaitForSeconds(2); - PacketSender.DestroyThis(); + if (PacketSender != null) + { + PacketSender.DestroyThis(); + } } public override void Move(Vector2 direction) @@ -1342,7 +1345,10 @@ public override void OnDestroy() public override void Dispose() { base.Dispose(); - PacketSender.DestroyThis(); + if (PacketSender != null) + { + PacketSender.DestroyThis(); + } } public override void SendHandsInteractionStateChanged(bool value, int animationId) From 702c758b3489603fbd2978fc1c29e1954f449aa6 Mon Sep 17 00:00:00 2001 From: Lacyway <20912169+Lacyway@users.noreply.github.com> Date: Tue, 21 May 2024 11:12:17 +0200 Subject: [PATCH 05/32] Fix field assignment --- Fika.Core/Coop/Players/ObservedCoopPlayer.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Fika.Core/Coop/Players/ObservedCoopPlayer.cs b/Fika.Core/Coop/Players/ObservedCoopPlayer.cs index aeb4b949..64ed3d5d 100644 --- a/Fika.Core/Coop/Players/ObservedCoopPlayer.cs +++ b/Fika.Core/Coop/Players/ObservedCoopPlayer.cs @@ -1016,7 +1016,7 @@ public override void LandingAdjustments(float d) transform.localRotation = Quaternion.identity; transform.localPosition = Vector3.zero; method_29(transform.gameObject); - compassInstantiated = true; + Traverse.Create(this).Field("_compassInstantiated").SetValue(true); return; } } From fabac8d4f1f512b0fba55e414518d5452c582ddc Mon Sep 17 00:00:00 2001 From: Lacyway <20912169+Lacyway@users.noreply.github.com> Date: Tue, 21 May 2024 19:16:20 +0200 Subject: [PATCH 06/32] Fix item sending UI causing errors when used from transfer window --- Fika.Core/UI/Patches/ItemContext_Patch.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Fika.Core/UI/Patches/ItemContext_Patch.cs b/Fika.Core/UI/Patches/ItemContext_Patch.cs index 2af2a52d..e0aff788 100644 --- a/Fika.Core/UI/Patches/ItemContext_Patch.cs +++ b/Fika.Core/UI/Patches/ItemContext_Patch.cs @@ -40,6 +40,14 @@ private static void Prefix(ItemInfoInteractionsAbstractClass co return; } + // Save as variable in case we need to add more checks later... + MenuUI menuUI = Singleton.Instance; + + if (menuUI.HideoutAreaTransferItemsScreen.isActiveAndEnabled) + { + return; + } + IEnumerable parentItems = item.GetAllParentItems(); if (parentItems.Any(x => x is EquipmentClass)) { From 5c956dec3a7c046e5e2c7c239e3ce60df7f44ae0 Mon Sep 17 00:00:00 2001 From: Lacyway <20912169+Lacyway@users.noreply.github.com> Date: Tue, 21 May 2024 22:18:13 +0200 Subject: [PATCH 07/32] Fix startup errors and restructure init of players --- Fika.Core/Coop/Components/CoopHandler.cs | 12 +++--- Fika.Core/Coop/GameMode/CoopGame.cs | 2 +- .../Coop/PacketHandlers/ServerPacketSender.cs | 2 +- Fika.Core/Coop/Players/CoopBot.cs | 11 ++---- Fika.Core/Coop/Players/CoopPlayer.cs | 37 +++++++++++-------- Fika.Core/Coop/Players/ObservedCoopPlayer.cs | 15 ++++---- 6 files changed, 40 insertions(+), 39 deletions(-) diff --git a/Fika.Core/Coop/Components/CoopHandler.cs b/Fika.Core/Coop/Components/CoopHandler.cs index 25fad416..b881b263 100644 --- a/Fika.Core/Coop/Components/CoopHandler.cs +++ b/Fika.Core/Coop/Components/CoopHandler.cs @@ -365,7 +365,7 @@ await Singleton.Instance.LoadBundlesAndCreatePools(PoolManager.Pool } }); - LocalPlayer otherPlayer = SpawnObservedPlayer(spawnObject.Profile, spawnObject.Position, playerId, spawnObject.IsAI, spawnObject.NetId); + ObservedCoopPlayer otherPlayer = SpawnObservedPlayer(spawnObject.Profile, spawnObject.Position, playerId, spawnObject.IsAI, spawnObject.NetId); if (!spawnObject.IsAlive) { @@ -453,9 +453,9 @@ public WorldInteractiveObject GetInteractiveObject(string objectId, out WorldInt return null; } - private LocalPlayer SpawnObservedPlayer(Profile profile, Vector3 position, int playerId, bool isAI, int netId) + private ObservedCoopPlayer SpawnObservedPlayer(Profile profile, Vector3 position, int playerId, bool isAI, int netId) { - LocalPlayer otherPlayer = ObservedCoopPlayer.CreateObservedPlayer(playerId, position, Quaternion.identity, + ObservedCoopPlayer otherPlayer = ObservedCoopPlayer.CreateObservedPlayer(playerId, position, Quaternion.identity, "Player", isAI == true ? "Bot_" : $"Player_{profile.Nickname}_", EPointOfView.ThirdPerson, profile, isAI, EUpdateQueue.Update, Player.EUpdateMode.Manual, Player.EUpdateMode.Auto, GClass549.Config.CharacterController.ObservedPlayerMode, @@ -468,7 +468,7 @@ private LocalPlayer SpawnObservedPlayer(Profile profile, Vector3 position, int p return null; } - ((CoopPlayer)otherPlayer).NetId = netId; + otherPlayer.NetId = netId; Logger.LogInfo($"SpawnObservedPlayer: {profile.Nickname} spawning with NetId {netId}"); if (!isAI) { @@ -477,7 +477,7 @@ private LocalPlayer SpawnObservedPlayer(Profile profile, Vector3 position, int p if (!Players.ContainsKey(netId)) { - Players.Add(netId, (CoopPlayer)otherPlayer); + Players.Add(netId, otherPlayer); } else { @@ -532,6 +532,8 @@ private LocalPlayer SpawnObservedPlayer(Profile profile, Vector3 position, int p } } + otherPlayer.InitObservedPlayer(); + Logger.LogDebug($"CreateLocalPlayer::{profile.Info.Nickname}::Spawned."); SetWeaponInHandsOfNewPlayer(otherPlayer, () => { }); diff --git a/Fika.Core/Coop/GameMode/CoopGame.cs b/Fika.Core/Coop/GameMode/CoopGame.cs index 76e76a27..90902739 100644 --- a/Fika.Core/Coop/GameMode/CoopGame.cs +++ b/Fika.Core/Coop/GameMode/CoopGame.cs @@ -824,7 +824,7 @@ public override async Task vmethod_2(int playerId, Vector3 position } else { - Singleton.Instance?.SendData(new NetDataWriter(), ref packet, LiteNetLib.DeliveryMethod.ReliableUnordered); + Singleton.Instance.SendData(new NetDataWriter(), ref packet, LiteNetLib.DeliveryMethod.ReliableUnordered); } if (MatchmakerAcceptPatches.IsServer) diff --git a/Fika.Core/Coop/PacketHandlers/ServerPacketSender.cs b/Fika.Core/Coop/PacketHandlers/ServerPacketSender.cs index 58efa421..042467f3 100644 --- a/Fika.Core/Coop/PacketHandlers/ServerPacketSender.cs +++ b/Fika.Core/Coop/PacketHandlers/ServerPacketSender.cs @@ -47,7 +47,7 @@ protected void Start() protected void FixedUpdate() { - if (player == null || Writer == null) + if (player == null || Writer == null || Server == null) { return; } diff --git a/Fika.Core/Coop/Players/CoopBot.cs b/Fika.Core/Coop/Players/CoopBot.cs index e5ad3f05..6b9dc07b 100644 --- a/Fika.Core/Coop/Players/CoopBot.cs +++ b/Fika.Core/Coop/Players/CoopBot.cs @@ -51,6 +51,9 @@ public static async Task CreateBot(int playerId, Vector3 position, InventoryControllerClass inventoryController = new CoopBotInventoryController(player, profile, true); + player.PacketSender = player.gameObject.AddComponent(); + player.PacketReceiver = player.gameObject.AddComponent(); + await player.Init(rotation, layerName, pointOfView, profile, inventoryController, new CoopBotHealthController(profile.Health, player, inventoryController, profile.Skills, aiControl), new CoopObservedStatisticsManager(), null, null, filter, @@ -137,14 +140,6 @@ public override GClass1676 ApplyShot(DamageInfo damageInfo, EBodyPart bodyPartTy protected override void Start() { - PacketSender = gameObject.AddComponent(); - PacketReceiver = gameObject.AddComponent(); - - /*if (FikaPlugin.DynamicAI.Value) - { - dynamicAi = gameObject.AddComponent(); - }*/ - if (FikaPlugin.DisableBotMetabolism.Value) { HealthController.DisableMetabolism(); diff --git a/Fika.Core/Coop/Players/CoopPlayer.cs b/Fika.Core/Coop/Players/CoopPlayer.cs index 4bef608b..5b1dd094 100644 --- a/Fika.Core/Coop/Players/CoopPlayer.cs +++ b/Fika.Core/Coop/Players/CoopPlayer.cs @@ -72,6 +72,17 @@ public static async Task Create(int playerId, Vector3 position, Qua achievementsController.Init(); achievementsController.Run(); + if (MatchmakerAcceptPatches.IsServer) + { + player.PacketSender = player.gameObject.AddComponent(); + } + else if (MatchmakerAcceptPatches.IsClient) + { + player.PacketSender = player.gameObject.AddComponent(); + } + + player.PacketReceiver = player.gameObject.AddComponent(); + await player.Init(rotation, layerName, pointOfView, profile, inventoryController, new CoopClientHealthController(profile.Health, player, inventoryController, profile.Skills, aiControl), statisticsManager, questController, achievementsController, filter, @@ -376,15 +387,18 @@ public override void SendHeadlightsPacket(bool isSilent) { GStruct163[] lightStates = _helmetLightControllers.Select(new Func(ClientPlayer.Class1430.class1430_0.method_0)).ToArray(); - PacketSender.CommonPlayerPackets.Enqueue(new() + if (PacketSender != null) { - HasHeadLightsPacket = true, - HeadLightsPacket = new() + PacketSender.CommonPlayerPackets.Enqueue(new() { - Amount = lightStates.Count(), - LightStates = lightStates - } - }); + HasHeadLightsPacket = true, + HeadLightsPacket = new() + { + Amount = lightStates.Count(), + LightStates = lightStates + } + }); + } } public override void OnItemAddedOrRemoved(Item item, ItemAddress location, bool added) @@ -827,15 +841,6 @@ public override void TryInteractionCallback(LootableContainer container) protected virtual void Start() { - if (MatchmakerAcceptPatches.IsServer) - { - PacketSender = gameObject.AddComponent(); - } - else if (MatchmakerAcceptPatches.IsClient) - { - PacketSender = gameObject.AddComponent(); - } - PacketReceiver = gameObject.AddComponent(); Profile.Info.GroupId = "Fika"; if (Side != EPlayerSide.Savage) diff --git a/Fika.Core/Coop/Players/ObservedCoopPlayer.cs b/Fika.Core/Coop/Players/ObservedCoopPlayer.cs index 64ed3d5d..1b24c571 100644 --- a/Fika.Core/Coop/Players/ObservedCoopPlayer.cs +++ b/Fika.Core/Coop/Players/ObservedCoopPlayer.cs @@ -115,7 +115,7 @@ public override float SqrCameraDistance } #endregion - public static async Task CreateObservedPlayer(int playerId, Vector3 position, Quaternion rotation, + public static async Task CreateObservedPlayer(int playerId, Vector3 position, Quaternion rotation, string layerName, string prefix, EPointOfView pointOfView, Profile profile, bool aiControl, EUpdateQueue updateQueue, EUpdateMode armsUpdateMode, EUpdateMode bodyUpdateMode, CharacterControllerSpawner.Mode characterControllerMode, Func getSensitivity, @@ -890,7 +890,7 @@ private IEnumerator DestroyNetworkedComponents() } } - protected override async void Start() + public void InitObservedPlayer() { if (gameObject.name.StartsWith("Bot_")) { @@ -954,18 +954,17 @@ protected override async void Start() EFT.Communications.ENotificationDurationType.Default, EFT.Communications.ENotificationIconType.Friend); } - // Spawn these later to prevent errors - while (coopGame.Status != GameStatus.Started) - { - await Task.Delay(TimeSpan.FromSeconds(1)); - } - healthBar = gameObject.AddComponent(); RaycastCameraTransform = Traverse.Create(this).Field("_playerLookRaycastTransform").GetValue(); } } + protected override void Start() + { + // Do nothing + } + public override void LateUpdate() { DistanceDirty = true; From f8be681a287aefc1e9e32791ef0dfaf67a2348af Mon Sep 17 00:00:00 2001 From: Lacyway <20912169+Lacyway@users.noreply.github.com> Date: Tue, 21 May 2024 23:15:22 +0200 Subject: [PATCH 08/32] Remove jumpscare on game start --- Fika.Core/UI/FikaUIUtils.cs | 102 +++++++++++++++++++++++++++++- Fika.Core/UI/Patches/TOS_Patch.cs | 12 ++-- 2 files changed, 107 insertions(+), 7 deletions(-) diff --git a/Fika.Core/UI/FikaUIUtils.cs b/Fika.Core/UI/FikaUIUtils.cs index 957870d9..bbb6c72e 100644 --- a/Fika.Core/UI/FikaUIUtils.cs +++ b/Fika.Core/UI/FikaUIUtils.cs @@ -1,12 +1,17 @@ // © 2024 Lacyway All Rights Reserved +using Diz.Utils; +using EFT.InputSystem; using EFT.UI; +using HarmonyLib; +using System; +using System.Reflection; using TMPro; using UnityEngine; namespace Fika.Core.UI { - internal class FikaUIUtils + internal static class FikaUIUtils { public static TextMeshProUGUI CreateOverlayText(string overlayText) { @@ -15,13 +20,13 @@ public static TextMeshProUGUI CreateOverlayText(string overlayText) if (labelObj != null) { - Object.Destroy(labelObj); + UnityEngine.Object.Destroy(labelObj); } ClientWatermark watermarkText = obj.GetComponent(); if (watermarkText != null) { - Object.Destroy(watermarkText); + UnityEngine.Object.Destroy(watermarkText); } obj.active = true; @@ -33,5 +38,96 @@ public static TextMeshProUGUI CreateOverlayText(string overlayText) return text; } + + public static GClass3085 ShowFikaMessage(this PreloaderUI preloaderUI, string header, string message, + ErrorScreen.EButtonType buttonType, float waitingTime, Action acceptCallback, Action endTimeCallback) + { + Traverse preloaderUiTraverse = Traverse.Create(preloaderUI); + + PreloaderUI.Class2561 messageHandler = new() + { + preloaderUI_0 = preloaderUI, + acceptCallback = acceptCallback, + endTimeCallback = endTimeCallback + }; + + if (!AsyncWorker.CheckIsMainThread()) + { + FikaPlugin.Instance.FikaLogger.LogError("You are trying to show error screen from non-main thread!"); + return new GClass3085(); + } + + ErrorScreen errorScreenTemplate = preloaderUiTraverse.Field("_criticalErrorScreenTemplate").GetValue(); + EmptyInputNode errorScreenContainer = preloaderUiTraverse.Field("_criticalErrorScreenContainer").GetValue(); + + messageHandler.errorScreen = UnityEngine.Object.Instantiate(errorScreenTemplate, errorScreenContainer.transform, false); + errorScreenContainer.AddChildNode(messageHandler.errorScreen); + return messageHandler.errorScreen.ShowFikaMessage(header, message, new Action(messageHandler.method_1), waitingTime, new Action(messageHandler.method_2), buttonType, true); + } + + public static GClass3087 ShowFikaMessage(this ErrorScreen errorScreen, string title, string message, + Action closeManuallyCallback = null, float waitingTime = 0f, Action timeOutCallback = null, + ErrorScreen.EButtonType buttonType = ErrorScreen.EButtonType.OkButton, bool removeHtml = true) + { + Traverse errorScreenTraverse = Traverse.Create(errorScreen); + + ErrorScreen.Class2352 errorScreenHandler = new() + { + errorScreen_0 = errorScreen + }; + if (!MonoBehaviourSingleton.Instance.CanShowErrorScreen) + { + return new GClass3087(); + } + if (removeHtml) + { + message = ErrorScreen.smethod_0(message); + } + ItemUiContext.Instance.CloseAllWindows(); + + Action action_1 = timeOutCallback ?? closeManuallyCallback; + errorScreenTraverse.Field("action_1").SetValue(action_1); + MethodBase baseShow = typeof(ErrorScreen).BaseType.GetMethod("Show"); + + errorScreenHandler.context = (GClass3087)baseShow.Invoke(errorScreen, [closeManuallyCallback]); + errorScreenHandler.context.OnAccept += errorScreen.method_3; + errorScreenHandler.context.OnDecline += errorScreen.method_4; + errorScreenHandler.context.OnCloseSilent += errorScreen.method_4; + + GClass767 ui = Traverse.Create(errorScreen).Field("UI").GetValue(); + + ui.AddDisposable(new Action(errorScreenHandler.method_0)); + string text = buttonType switch + { + ErrorScreen.EButtonType.OkButton => "I UNDERSTAND", + ErrorScreen.EButtonType.CancelButton => "CANCEL", + ErrorScreen.EButtonType.QuitButton => "I DECLINE", + _ => throw new ArgumentOutOfRangeException() + }; + + DefaultUIButton exitButton = errorScreenTraverse.Field("_exitButton").GetValue(); + + exitButton.SetHeaderText(text, exitButton.HeaderSize); + errorScreen.RectTransform.anchoredPosition = Vector2.zero; + + errorScreen.Caption.SetText(string.IsNullOrEmpty(title) ? "ERROR" : title); + + string string_1 = message.SubstringIfNecessary(500); + errorScreenTraverse.Field("string_1").SetValue(string_1); + + TextMeshProUGUI errorDescription = Traverse.Create(errorScreen).Field("_errorDescription").GetValue(); + errorDescription.text = string_1; + + Coroutine coroutine_0 = errorScreenTraverse.Field("coroutine_0").GetValue(); + if (coroutine_0 != null) + { + errorScreen.StopCoroutine(coroutine_0); + } + if (waitingTime > 0f) + { + errorScreenTraverse.Field("coroutine_0").SetValue(errorScreen.StartCoroutine(errorScreen.method_2(GClass1296.Now.AddSeconds((double)waitingTime)))); + } + return errorScreenHandler.context; + } } } diff --git a/Fika.Core/UI/Patches/TOS_Patch.cs b/Fika.Core/UI/Patches/TOS_Patch.cs index d387aac3..ad221cb2 100644 --- a/Fika.Core/UI/Patches/TOS_Patch.cs +++ b/Fika.Core/UI/Patches/TOS_Patch.cs @@ -32,18 +32,22 @@ public static void PostFix() { byte[] str_1_b = Convert.FromBase64String(str_1); string str_1_d = Encoding.UTF8.GetString(str_1_b); - Singleton.Instance.ShowCriticalErrorScreen("Fika", str_1_d, ErrorScreen.EButtonType.QuitButton, 30f, - Application.Quit, - () => { FikaPlugin.AcceptedTOS.Value = true; }); + Singleton.Instance.ShowFikaMessage("FIKA", str_1_d, ErrorScreen.EButtonType.QuitButton, 30f, + Application.Quit, AcceptTos); } else { byte[] str_2_b = Convert.FromBase64String(str_2); string str_2_d = Encoding.UTF8.GetString(str_2_b); - Singleton.Instance.ShowCriticalErrorScreen("Fika", str_2_d, ErrorScreen.EButtonType.OkButton, 0f, + Singleton.Instance.ShowFikaMessage("FIKA", str_2_d, ErrorScreen.EButtonType.OkButton, 0f, null, null); } } + + private static void AcceptTos() + { + FikaPlugin.AcceptedTOS.Value = true; + } } } From 9ba46903e624ad12ceed4857a93f94521f51117a Mon Sep 17 00:00:00 2001 From: Lacyway <20912169+Lacyway@users.noreply.github.com> Date: Tue, 21 May 2024 23:24:20 +0200 Subject: [PATCH 09/32] More efficient traverse reflection --- Fika.Core/Coop/Players/ObservedCoopPlayer.cs | 31 ++++++++++--------- .../FikaVersionLabel_Patch.cs | 6 ++-- 2 files changed, 21 insertions(+), 16 deletions(-) diff --git a/Fika.Core/Coop/Players/ObservedCoopPlayer.cs b/Fika.Core/Coop/Players/ObservedCoopPlayer.cs index 1b24c571..ca66c405 100644 --- a/Fika.Core/Coop/Players/ObservedCoopPlayer.cs +++ b/Fika.Core/Coop/Players/ObservedCoopPlayer.cs @@ -898,6 +898,7 @@ public void InitObservedPlayer() } PacketSender = gameObject.AddComponent(); + Traverse playerTraverse = Traverse.Create(this); if (IsObservedAI) { @@ -909,18 +910,20 @@ public void InitObservedPlayer() PacketSender.Writer.Reset(); PacketSender.Client.SendData(PacketSender.Writer, ref genericPacket, LiteNetLib.DeliveryMethod.ReliableOrdered); - IVaultingComponent vaultingComponent = Traverse.Create(this).Field("_vaultingComponent").GetValue(); + IVaultingComponent vaultingComponent = playerTraverse.Field("_vaultingComponent").GetValue(); if (vaultingComponent != null) { UpdateEvent -= vaultingComponent.DoVaultingTick; } - Traverse.Create(this).Field("_vaultingComponent").SetValue(null); - Traverse.Create(this).Field("_vaultingComponentDebug").SetValue(null); - Traverse.Create(this).Field("_vaultingParameters").SetValue(null); - Traverse.Create(this).Field("_vaultingGameplayRestrictions").SetValue(null); - Traverse.Create(this).Field("_vaultAudioController").SetValue(null); - Traverse.Create(this).Field("_sprintVaultAudioController").SetValue(null); - Traverse.Create(this).Field("_climbAudioController").SetValue(null); + + + playerTraverse.Field("_vaultingComponent").SetValue(null); + playerTraverse.Field("_vaultingComponentDebug").SetValue(null); + playerTraverse.Field("_vaultingParameters").SetValue(null); + playerTraverse.Field("_vaultingGameplayRestrictions").SetValue(null); + playerTraverse.Field("_vaultAudioController").SetValue(null); + playerTraverse.Field("_sprintVaultAudioController").SetValue(null); + playerTraverse.Field("_climbAudioController").SetValue(null); if (FikaPlugin.CullPlayers.Value) { @@ -936,15 +939,15 @@ public void InitObservedPlayer() CoopGame coopGame = (CoopGame)Singleton.Instance; - IVaultingComponent vaultingComponent = Traverse.Create(this).Field("_vaultingComponent").GetValue(); + IVaultingComponent vaultingComponent = playerTraverse.Field("_vaultingComponent").GetValue(); if (vaultingComponent != null) { UpdateEvent -= vaultingComponent.DoVaultingTick; } - Traverse.Create(this).Field("_vaultingComponent").SetValue(null); - Traverse.Create(this).Field("_vaultingComponentDebug").SetValue(null); - Traverse.Create(this).Field("_vaultingParameters").SetValue(null); - Traverse.Create(this).Field("_vaultingGameplayRestrictions").SetValue(null); + playerTraverse.Field("_vaultingComponent").SetValue(null); + playerTraverse.Field("_vaultingComponentDebug").SetValue(null); + playerTraverse.Field("_vaultingParameters").SetValue(null); + playerTraverse.Field("_vaultingGameplayRestrictions").SetValue(null); InitVaultingAudioControllers(ObservedVaultingParameters); @@ -956,7 +959,7 @@ public void InitObservedPlayer() healthBar = gameObject.AddComponent(); - RaycastCameraTransform = Traverse.Create(this).Field("_playerLookRaycastTransform").GetValue(); + RaycastCameraTransform = playerTraverse.Field("_playerLookRaycastTransform").GetValue(); } } diff --git a/Fika.Core/EssentialPatches/FikaVersionLabel_Patch.cs b/Fika.Core/EssentialPatches/FikaVersionLabel_Patch.cs index 1ad96296..5d7f1d23 100644 --- a/Fika.Core/EssentialPatches/FikaVersionLabel_Patch.cs +++ b/Fika.Core/EssentialPatches/FikaVersionLabel_Patch.cs @@ -33,8 +33,10 @@ internal static void PatchPostfix(string major, object __result) string fikaVersion = Assembly.GetAssembly(typeof(FikaVersionLabel_Patch)).GetName().Version.ToString(); - Traverse.Create(MonoBehaviourSingleton.Instance).Field("_alphaVersionLabel").Property("LocalizationKey").SetValue("{0}"); - Traverse.Create(MonoBehaviourSingleton.Instance).Field("string_2").SetValue($"Fika {fikaVersion} |"); + Traverse preloaderUiTraverse = Traverse.Create(MonoBehaviourSingleton.Instance); + + preloaderUiTraverse.Field("_alphaVersionLabel").Property("LocalizationKey").SetValue("{0}"); + preloaderUiTraverse.Field("string_2").SetValue($"Fika {fikaVersion} |"); Traverse.Create(__result).Field("Major").SetValue($"FIKA BETA {fikaVersion} | {_versionLabel}"); } } From 6badce5b3065f3620ac24efd2b06121631f6414b Mon Sep 17 00:00:00 2001 From: Lacyway <20912169+Lacyway@users.noreply.github.com> Date: Wed, 22 May 2024 12:08:00 +0200 Subject: [PATCH 10/32] Fix Lightkeeper quests freezing the dialogue --- Fika.Core/Coop/Players/CoopPlayer.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Fika.Core/Coop/Players/CoopPlayer.cs b/Fika.Core/Coop/Players/CoopPlayer.cs index 5b1dd094..4745a995 100644 --- a/Fika.Core/Coop/Players/CoopPlayer.cs +++ b/Fika.Core/Coop/Players/CoopPlayer.cs @@ -64,11 +64,13 @@ public static async Task Create(int playerId, Vector3 position, Qua CoopClientInventoryController inventoryController = new(player, profile, true); - GClass3206 questController = new(profile, inventoryController, null, true); + ISession session = Singleton>.Instance.GetClientBackEndSession(); + + GClass3206 questController = new(profile, inventoryController, session, true); questController.Init(); questController.Run(); - AchievementControllerClass achievementsController = new(profile, inventoryController, null, true); + AchievementControllerClass achievementsController = new(profile, inventoryController, session, true); achievementsController.Init(); achievementsController.Run(); From a6f4cef166b7348cfe53964ff983781eced4cbee Mon Sep 17 00:00:00 2001 From: Lacyway <20912169+Lacyway@users.noreply.github.com> Date: Wed, 22 May 2024 12:13:34 +0200 Subject: [PATCH 11/32] Remove return on marker plant for host --- .../CoopClientInventoryController.cs | 47 +++++++++---------- 1 file changed, 23 insertions(+), 24 deletions(-) diff --git a/Fika.Core/Coop/ClientClasses/CoopClientInventoryController.cs b/Fika.Core/Coop/ClientClasses/CoopClientInventoryController.cs index d8edf451..e4eb6aa4 100644 --- a/Fika.Core/Coop/ClientClasses/CoopClientInventoryController.cs +++ b/Fika.Core/Coop/ClientClasses/CoopClientInventoryController.cs @@ -26,33 +26,35 @@ public override void CallMalfunctionRepaired(Weapon weapon) base.CallMalfunctionRepaired(weapon); if (!Player.IsAI && (bool)Singleton.Instance.Game.Settings.MalfunctionVisability) { - MonoBehaviourSingleton.Instance.MalfunctionGlow.ShowGlow(BattleUIMalfunctionGlow.GlowType.Repaired, force: true, method_44()); + MonoBehaviourSingleton.Instance.MalfunctionGlow.ShowGlow(BattleUIMalfunctionGlow.GlowType.Repaired, true, method_44()); } } public override void Execute(GClass2837 operation, [CanBeNull] Callback callback) { + // Do not replicate picking up quest items, throws an error on the other clients + if (operation is GClass2839 pickupOperation) + { + if (pickupOperation.Item.Template.QuestItem) + { + base.Execute(operation, callback); + return; + } + } + if (MatchmakerAcceptPatches.IsServer) { + // Do not replicate quest operations + if (operation is GClass2866 or GClass2879) + { + base.Execute(operation, callback); + return; + } + HostInventoryOperationManager operationManager = new(this, operation, callback); if (vmethod_0(operationManager.operation)) { - operationManager.operation.vmethod_0(operationManager.HandleResult); - - // Do not replicate picking up quest items, throws an error on the other clients - if (operation is GClass2839 pickupOperation) - { - if (pickupOperation.Item.Template.QuestItem) - { - return; - } - } - - // TODO: Check for glass increments - if (operation is GClass2870) - { - return; - } + operationManager.operation.vmethod_0(operationManager.HandleResult); InventoryPacket packet = new() { @@ -78,14 +80,11 @@ public override void Execute(GClass2837 operation, [CanBeNull] Callback callback } else if (MatchmakerAcceptPatches.IsClient) { - // Do not replicate picking up quest items, throws an error on the other clients - if (operation is GClass2839 pickupOperation) + // Do not replicate quest operations + if (operation is GClass2866 or GClass2879) { - if (pickupOperation.Item.Template.QuestItem) - { - base.Execute(operation, callback); - return; - } + base.Execute(operation, callback); + return; } InventoryPacket packet = new() From 16b142483041ac549ca8d2cc938771fc3605e1e6 Mon Sep 17 00:00:00 2001 From: Lacyway <20912169+Lacyway@users.noreply.github.com> Date: Wed, 22 May 2024 15:44:04 +0200 Subject: [PATCH 12/32] Remove dogtag when cancelling --- Fika.Core/Coop/GameMode/CoopGame.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Fika.Core/Coop/GameMode/CoopGame.cs b/Fika.Core/Coop/GameMode/CoopGame.cs index 90902739..2777bd4f 100644 --- a/Fika.Core/Coop/GameMode/CoopGame.cs +++ b/Fika.Core/Coop/GameMode/CoopGame.cs @@ -1694,6 +1694,18 @@ private void StopFromError(string profileId, ExitStatus exitStatus) CoopPlayer myPlayer = (CoopPlayer)Singleton.Instance.MainPlayer; myPlayer.PacketSender.DestroyThis(); + if (myPlayer.Side != EPlayerSide.Savage) + { + if (myPlayer.Equipment.GetSlot(EquipmentSlot.Dogtag).ContainedItem != null) + { + GStruct414 result = InteractionsHandlerClass.Remove(myPlayer.Equipment.GetSlot(EquipmentSlot.Dogtag).ContainedItem, myPlayer.GClass2761_0, false, true); + if (result.Error != null) + { + FikaPlugin.Instance.FikaLogger.LogWarning("CoopGame::StopFromError: Error removing dog tag!"); + } + } + } + string exitName = null; float delay = 0f; From cbd4be79d4e6cebd17c4e8885df8d6fc98c72b64 Mon Sep 17 00:00:00 2001 From: Lacyway <20912169+Lacyway@users.noreply.github.com> Date: Wed, 22 May 2024 15:44:15 +0200 Subject: [PATCH 13/32] Allow dynamic AI rate to be changed during session --- Fika.Core/Coop/GameMode/CoopGame.cs | 79 ++++++++++++++++------------- 1 file changed, 44 insertions(+), 35 deletions(-) diff --git a/Fika.Core/Coop/GameMode/CoopGame.cs b/Fika.Core/Coop/GameMode/CoopGame.cs index 2777bd4f..10418138 100644 --- a/Fika.Core/Coop/GameMode/CoopGame.cs +++ b/Fika.Core/Coop/GameMode/CoopGame.cs @@ -1,6 +1,5 @@ using Aki.Custom.Airdrops; using Aki.Reflection.Utils; -using BepInEx.Configuration; using BepInEx.Logging; using Comfort.Common; using CommonAssets.Scripts.Game; @@ -60,7 +59,7 @@ internal sealed class CoopGame : BaseLocalGame, IBotGame, IFika private CoopExfilManager exfilManager; private GameObject fikaStartButton; private readonly Dictionary botQueue = []; - private FikaDynamicAI dynamicAI; + public FikaDynamicAI DynamicAI { get; private set; } public RaidSettings RaidSettings { get; private set; } @@ -517,7 +516,7 @@ private void DespawnBot(CoopHandler coopHandler, Player bot) BotsController.Bots.Remove(botOwner); bot.HealthController.DiedEvent -= botOwner.method_6; // Unsubscribe from the event to prevent errors. BotUnspawn(botOwner); - if (botOwner != null) + if (botOwner != null) { botOwner.Dispose(); } @@ -551,9 +550,9 @@ private async void DeployScreen(float timeBeforeDeploy) Destroy(fikaStartButton); } - if (dynamicAI != null) + if (DynamicAI != null) { - dynamicAI.AddHumans(); + DynamicAI.AddHumans(); } SetStatusModel status = new(coopHandler.MyPlayer.ProfileId, LobbyEntry.ELobbyStatus.IN_GAME); @@ -571,7 +570,7 @@ private async void DeployScreen(float timeBeforeDeploy) if (fikaStartButton != null) { - fikaStartButton.SetActive(true); + fikaStartButton.SetActive(true); } if (MatchmakerAcceptPatches.IsServer) @@ -607,9 +606,9 @@ private async void DeployScreen(float timeBeforeDeploy) Singleton.Instance.SendDataToAll(writer, ref syncPacket, LiteNetLib.DeliveryMethod.ReliableUnordered); } - if (dynamicAI != null) + if (DynamicAI != null) { - dynamicAI.AddHumans(); + DynamicAI.AddHumans(); } } else if (MatchmakerAcceptPatches.IsClient) @@ -717,7 +716,7 @@ public override async Task vmethod_2(int playerId, Vector3 position CharacterControllerSpawner.Mode characterControllerMode, Func getSensitivity, Func getAimingSensitivity, IStatisticsManager statisticsManager, AbstractQuestControllerClass questController, AbstractAchievementControllerClass achievementsController) { - Logger.LogInfo("Creating CoopHandler!"); + Logger.LogInfo("Creating CoopHandler"); await CreateCoopHandler(); CoopHandler.GetCoopHandler().LocalGameInstance = this; @@ -804,13 +803,13 @@ public override async Task vmethod_2(int playerId, Vector3 position if (fikaStartButton != null) { - fikaStartButton.SetActive(false); + fikaStartButton.SetActive(false); } }); Traverse.Create(startButtonComponent).Field("OnClick").SetValue(newStartEvent); if (customButton != null) { - customButton.SetActive(true); + customButton.SetActive(true); } fikaStartButton = customButtonStart; } @@ -847,7 +846,7 @@ public override async Task vmethod_2(int playerId, Vector3 position Destroy(customButton); if (fikaStartButton != null) { - fikaStartButton.SetActive(false); + fikaStartButton.SetActive(false); } myPlayer.ActiveHealthController.DiedEvent += MainPlayerDied; @@ -985,7 +984,7 @@ private async Task WaitForPlayers() if (MatchmakerAcceptPatches.GClass3163 != null) { - MatchmakerAcceptPatches.GClass3163.ChangeStatus($"Initializing Coop Game..."); + MatchmakerAcceptPatches.GClass3163.ChangeStatus($"Initializing Coop Game..."); } int numbersOfPlayersToWaitFor = 0; @@ -1160,7 +1159,7 @@ public override IEnumerator vmethod_4(float startDelay, BotControllerSettings co botsController_0.BotSpawner.SetMaxBots(limits); } - dynamicAI = gameObject.AddComponent(); + DynamicAI = gameObject.AddComponent(); } else if (MatchmakerAcceptPatches.IsClient) { @@ -1219,7 +1218,7 @@ public override IEnumerator vmethod_4(float startDelay, BotControllerSettings co Logger.LogInfo("Running old spawn system. Waves: " + wavesSpawnScenario_0.SpawnWaves.Length); if (wavesSpawnScenario_0 != null) { - wavesSpawnScenario_0.Run(EBotsSpawnMode.Anyway); + wavesSpawnScenario_0.Run(EBotsSpawnMode.Anyway); } } @@ -1228,27 +1227,28 @@ public override IEnumerator vmethod_4(float startDelay, BotControllerSettings co Logger.LogInfo("Running new spawn system."); if (nonWavesSpawnScenario_0 != null) { - nonWavesSpawnScenario_0.Run(); + nonWavesSpawnScenario_0.Run(); } - } + } GClass579.Run(EBotsSpawnMode.Anyway); FikaPlugin.DynamicAI.SettingChanged += DynamicAI_SettingChanged; + FikaPlugin.DynamicAIRate.SettingChanged += DynamicAIRate_SettingChanged; } else { if (wavesSpawnScenario_0 != null) { - wavesSpawnScenario_0.Stop(); + wavesSpawnScenario_0.Stop(); } if (nonWavesSpawnScenario_0 != null) { - nonWavesSpawnScenario_0.Stop(); + nonWavesSpawnScenario_0.Stop(); } if (GClass579 != null) { - GClass579.Stop(); + GClass579.Stop(); } } @@ -1273,11 +1273,19 @@ public override IEnumerator vmethod_4(float startDelay, BotControllerSettings co yield break; } + private void DynamicAIRate_SettingChanged(object sender, EventArgs e) + { + if (DynamicAI != null) + { + DynamicAI.RateChanged(FikaPlugin.DynamicAIRate.Value); + } + } + private void DynamicAI_SettingChanged(object sender, EventArgs e) { - if (dynamicAI != null) + if (DynamicAI != null) { - dynamicAI.SettingChanged(FikaPlugin.DynamicAI.Value); + DynamicAI.EnabledChange(FikaPlugin.DynamicAI.Value); } } @@ -1596,15 +1604,15 @@ public override void Stop(string profileId, ExitStatus exitStatus, string exitNa if (GClass579 != null) { - GClass579.Stop(); + GClass579.Stop(); } if (nonWavesSpawnScenario_0 != null) { - nonWavesSpawnScenario_0.Stop(); + nonWavesSpawnScenario_0.Stop(); } if (wavesSpawnScenario_0 != null) { - wavesSpawnScenario_0.Stop(); + wavesSpawnScenario_0.Stop(); } try @@ -1681,7 +1689,7 @@ public override void Stop(string profileId, ExitStatus exitStatus, string exitNa } if (EnvironmentManager.Instance != null) { - EnvironmentManager.Instance.Stop(); + EnvironmentManager.Instance.Stop(); } MonoBehaviourSingleton.Instance.StartBlackScreenShow(1f, 1f, new Action(stopManager.method_0)); GClass549.Config.UseSpiritPlayer = false; @@ -1741,15 +1749,15 @@ private void StopFromError(string profileId, ExitStatus exitStatus) if (GClass579 != null) { - GClass579.Stop(); + GClass579.Stop(); } if (nonWavesSpawnScenario_0 != null) { - nonWavesSpawnScenario_0.Stop(); + nonWavesSpawnScenario_0.Stop(); } if (wavesSpawnScenario_0 != null) { - wavesSpawnScenario_0.Stop(); + wavesSpawnScenario_0.Stop(); } ErrorExitManager stopManager = new() @@ -1774,17 +1782,17 @@ private void StopFromError(string profileId, ExitStatus exitStatus) if (exfilManager != null) { - exfilManager.Stop(); + exfilManager.Stop(); } Status = GameStatus.Stopping; if (GameTimer != null) { - GameTimer.TryStop(); + GameTimer.TryStop(); } if (endByExitTrigger != null) { - endByExitTrigger.Stop(); + endByExitTrigger.Stop(); } if (gameUI.TimerPanel.enabled) { @@ -1793,7 +1801,7 @@ private void StopFromError(string profileId, ExitStatus exitStatus) if (EnvironmentManager.Instance != null) { - EnvironmentManager.Instance.Stop(); + EnvironmentManager.Instance.Stop(); } MonoBehaviourSingleton.Instance.StartBlackScreenShow(1f, 1f, new Action(stopManager.ExitOverride)); GClass549.Config.UseSpiritPlayer = false; @@ -1843,6 +1851,7 @@ public override void Dispose() } FikaPlugin.DynamicAI.SettingChanged -= DynamicAI_SettingChanged; + FikaPlugin.DynamicAIRate.SettingChanged -= DynamicAIRate_SettingChanged; } else if (MatchmakerAcceptPatches.IsClient) { @@ -1891,12 +1900,12 @@ public void ExitOverride() } if (baseLocalGame_0 != null) { - baseLocalGame_0.CleanUp(); + baseLocalGame_0.CleanUp(); baseLocalGame_0.Status = GameStatus.Stopped; } if (MonoBehaviourSingleton.Instance != null) { - MonoBehaviourSingleton.Instance.FadeOutVolumeAfterRaid(); + MonoBehaviourSingleton.Instance.FadeOutVolumeAfterRaid(); } MonoBehaviour instance2 = StaticManager.Instance; float num = delay; From c247e14f5fceffb758a289c16e44eba7ccc23c6c Mon Sep 17 00:00:00 2001 From: Lacyway <20912169+Lacyway@users.noreply.github.com> Date: Wed, 22 May 2024 15:44:23 +0200 Subject: [PATCH 14/32] Enable bots before disposing --- Fika.Core/Coop/Custom/FikaDynamicAI.cs | 21 +++++++++++++++++++-- Fika.Core/Coop/Players/CoopBot.cs | 2 ++ Fika.Core/Networking/FikaClient.cs | 4 ++++ 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/Fika.Core/Coop/Custom/FikaDynamicAI.cs b/Fika.Core/Coop/Custom/FikaDynamicAI.cs index 4728bdb1..59081045 100644 --- a/Fika.Core/Coop/Custom/FikaDynamicAI.cs +++ b/Fika.Core/Coop/Custom/FikaDynamicAI.cs @@ -59,10 +59,16 @@ protected void Awake() private void Spawner_OnBotRemoved(BotOwner botOwner) { - if (!bots.Remove((CoopBot)botOwner.GetPlayer)) + CoopBot bot = (CoopBot)botOwner.GetPlayer; + if (!bots.Remove(bot)) { logger.LogWarning($"Could not remove {botOwner.gameObject.name} from bots list."); } + + if (disabledBots.Contains(bot)) + { + disabledBots.Remove(bot); + } } private void Spawner_OnBotCreated(BotOwner botOwner) @@ -184,7 +190,7 @@ private void CheckForPlayers(CoopBot bot) } } - public void SettingChanged(bool value) + public void EnabledChange(bool value) { if (!value) { @@ -196,5 +202,16 @@ public void SettingChanged(bool value) disabledBots.Clear(); } } + + internal void RateChanged(FikaPlugin.DynamicAIRates value) + { + resetCounter = value switch + { + FikaPlugin.DynamicAIRates.Low => 600, + FikaPlugin.DynamicAIRates.Medium => 300, + FikaPlugin.DynamicAIRates.High => 120, + _ => 300, + }; + } } } diff --git a/Fika.Core/Coop/Players/CoopBot.cs b/Fika.Core/Coop/Players/CoopBot.cs index 6b9dc07b..9b10fa7b 100644 --- a/Fika.Core/Coop/Players/CoopBot.cs +++ b/Fika.Core/Coop/Players/CoopBot.cs @@ -311,6 +311,8 @@ public override void OnDestroy() CoopGame coopGame = (CoopGame)Singleton.Instance; if (coopGame != null && coopGame.Status == GameStatus.Started) { + coopGame.DynamicAI.RemoveBot(this); + FikaServer server = Singleton.Instance; GenericPacket packet = new(EPackageType.DisposeBot) { diff --git a/Fika.Core/Networking/FikaClient.cs b/Fika.Core/Networking/FikaClient.cs index ec69f925..81d1c141 100644 --- a/Fika.Core/Networking/FikaClient.cs +++ b/Fika.Core/Networking/FikaClient.cs @@ -436,6 +436,10 @@ private void OnGenericPacketReceived(GenericPacket packet) { if (CoopHandler.Players.TryGetValue(packet.BotNetId, out CoopPlayer botToDispose)) { + if (!botToDispose.gameObject.activeSelf) + { + botToDispose.gameObject.SetActive(true); + } if (CoopHandler.Players.Remove(packet.BotNetId)) { From 1a019688e16a3e8ae93257c84bcb8084736ed280 Mon Sep 17 00:00:00 2001 From: Lacyway <20912169+Lacyway@users.noreply.github.com> Date: Wed, 22 May 2024 15:46:37 +0200 Subject: [PATCH 15/32] Delete unused method --- Fika.Core/Coop/Players/CoopBot.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/Fika.Core/Coop/Players/CoopBot.cs b/Fika.Core/Coop/Players/CoopBot.cs index 9b10fa7b..6b9dc07b 100644 --- a/Fika.Core/Coop/Players/CoopBot.cs +++ b/Fika.Core/Coop/Players/CoopBot.cs @@ -311,8 +311,6 @@ public override void OnDestroy() CoopGame coopGame = (CoopGame)Singleton.Instance; if (coopGame != null && coopGame.Status == GameStatus.Started) { - coopGame.DynamicAI.RemoveBot(this); - FikaServer server = Singleton.Instance; GenericPacket packet = new(EPackageType.DisposeBot) { From c1f3c2f0c5969a9c77a79c858c45e3cfc5d8d5c2 Mon Sep 17 00:00:00 2001 From: Lacyway <20912169+Lacyway@users.noreply.github.com> Date: Wed, 22 May 2024 15:58:22 +0200 Subject: [PATCH 16/32] Reorganize CoopGame class --- Fika.Core/Coop/Components/CoopExfilManager.cs | 2 +- Fika.Core/Coop/GameMode/CoopGame.cs | 76 ++++++++++++------- 2 files changed, 48 insertions(+), 30 deletions(-) diff --git a/Fika.Core/Coop/Components/CoopExfilManager.cs b/Fika.Core/Coop/Components/CoopExfilManager.cs index b7a587e4..66bfc26c 100644 --- a/Fika.Core/Coop/Components/CoopExfilManager.cs +++ b/Fika.Core/Coop/Components/CoopExfilManager.cs @@ -73,7 +73,7 @@ protected void Update() if (!exfiltrationPoint.UnmetRequirements(player).Any()) { game.MyExitLocation = exfiltrationPoint.Settings.Name; - game.Extract(player, exfiltrationPoint); + game.Extract((CoopPlayer)player, exfiltrationPoint); } } diff --git a/Fika.Core/Coop/GameMode/CoopGame.cs b/Fika.Core/Coop/GameMode/CoopGame.cs index 10418138..43ffe13f 100644 --- a/Fika.Core/Coop/GameMode/CoopGame.cs +++ b/Fika.Core/Coop/GameMode/CoopGame.cs @@ -49,26 +49,31 @@ namespace Fika.Core.Coop.GameMode /// internal sealed class CoopGame : BaseLocalGame, IBotGame, IFikaGame { - public new bool InRaid { get => true; } - public string InfiltrationPoint; - public bool HasAddedFenceRep = false; - public bool forceStart = false; + public ExitStatus MyExitStatus { get; set; } = ExitStatus.Survived; + public string MyExitLocation { get; set; } = null; + public ISpawnSystem SpawnSystem { get; set; } + + public Dictionary Bots { get; set; } = []; private CoopExfilManager exfilManager; private GameObject fikaStartButton; private readonly Dictionary botQueue = []; - public FikaDynamicAI DynamicAI { get; private set; } + private Coroutine extractRoutine; + private GClass2928 spawnPoints = null; + private ISpawnPoint spawnPoint = null; + private GClass579 GClass579; + private WavesSpawnScenario wavesSpawnScenario_0; + private NonWavesSpawnScenario nonWavesSpawnScenario_0; + private Func func_1; + public FikaDynamicAI DynamicAI { get; private set; } public RaidSettings RaidSettings { get; private set; } - //WildSpawnType for sptUsec and sptBear const int sptUsecValue = 47; const int sptBearValue = 48; - public ISession BackEndSession { get => PatchConstants.BackEndSession; } - BotsController IBotGame.BotsController { get @@ -76,7 +81,6 @@ BotsController IBotGame.BotsController return botsController_0; } } - public BotsController BotsController { get @@ -84,7 +88,6 @@ public BotsController BotsController return botsController_0; } } - public IWeatherCurve WeatherCurve { get @@ -93,7 +96,6 @@ public IWeatherCurve WeatherCurve } } - private static ManualLogSource Logger; internal static CoopGame Create(InputTree inputTree, Profile profile, GameDateTime backendDateTime, InsuranceCompanyClass insurance, MenuUI menuUI, @@ -214,8 +216,6 @@ public async Task CreateCoopHandler() } } - public Dictionary Bots { get; set; } = []; - private List GetPlayers(CoopHandler coopHandler) { List humanPlayers = []; @@ -687,9 +687,6 @@ private async Task SendOrReceiveSpawnPoint() } } - GClass2928 spawnPoints = null; - ISpawnPoint spawnPoint = null; - /// /// Creating the EFT.LocalPlayer /// @@ -1433,7 +1430,7 @@ public void ResetExfilPointsFromServer(ExfiltrationPoint[] points) /// /// The local player to start the Coroutine on /// - public void Extract(Player player, ExfiltrationPoint point) + public void Extract(CoopPlayer player, ExfiltrationPoint point) { PreloaderUI preloaderUI = Singleton.Instance; @@ -1460,7 +1457,7 @@ public void Extract(Player player, ExfiltrationPoint point) GenericPacket genericPacket = new() { - NetId = ((CoopPlayer)player).NetId, + NetId = player.NetId, PacketType = EPackageType.ClientExtract }; @@ -1495,6 +1492,8 @@ public void Extract(Player player, ExfiltrationPoint point) player.ActiveHealthController.DisableMetabolism(); player.ActiveHealthController.PauseAllEffects(); + extractRoutine = StartCoroutine(ExtractRoutine(player)); + // Prevents players from looting after extracting GClass3107.Instance.CloseAllScreensForced(); @@ -1524,6 +1523,30 @@ public void Extract(Player player, ExfiltrationPoint point) } } + /// + /// Used to make sure no stims or mods reset the DamageCoeff + /// + /// The to run the coroutine on + /// + private IEnumerator ExtractRoutine(CoopPlayer player) + { + while (true) + { + if (player != null && player.ActiveHealthController != null) + { + if (player.ActiveHealthController.DamageCoeff != 0) + { + player.ActiveHealthController.SetDamageCoeff(0); + } + } + else + { + yield break; + } + yield return new WaitForEndOfFrame(); + } + } + public void ClearHostAI(Player player) { if (player != null) @@ -1550,10 +1573,6 @@ public void ClearHostAI(Player player) } } - public ExitStatus MyExitStatus { get; set; } = ExitStatus.Survived; - public string MyExitLocation { get; set; } = null; - public ISpawnSystem SpawnSystem { get; set; } - private void HealthController_DiedEvent(EDamageType obj) { gparam_0.Player.HealthController.DiedEvent -= method_15; @@ -1836,6 +1855,11 @@ public override void Dispose() Singleton.Instance.MineManager.OnExplosion -= OnMineExplode; } + if (extractRoutine != null) + { + StopCoroutine(extractRoutine); + } + if (MatchmakerAcceptPatches.IsServer) { CoopPlayer coopPlayer = (CoopPlayer)Singleton.Instance.MainPlayer; @@ -1884,11 +1908,6 @@ public override void Dispose() base.Dispose(); } - private GClass579 GClass579; - private WavesSpawnScenario wavesSpawnScenario_0; - private NonWavesSpawnScenario nonWavesSpawnScenario_0; - private Func func_1; - private class ErrorExitManager : Class1364 { public void ExitOverride() @@ -1918,10 +1937,9 @@ public void ExitOverride() } } - public new void method_6(string backendUrl, string locationId, int variantId) { - Logger.LogInfo("CoopGame:method_6"); + Logger.LogDebug("CoopGame::method_6"); return; } } From e282e2c3e0422adc11d48470d86f71892da19b2f Mon Sep 17 00:00:00 2001 From: Lacyway <20912169+Lacyway@users.noreply.github.com> Date: Wed, 22 May 2024 16:02:28 +0200 Subject: [PATCH 17/32] More cleaning --- Fika.Core/Coop/GameMode/CoopGame.cs | 4 ++-- Fika.Core/Coop/GameMode/{IMPTGame.cs => IFikaGame.cs} | 0 2 files changed, 2 insertions(+), 2 deletions(-) rename Fika.Core/Coop/GameMode/{IMPTGame.cs => IFikaGame.cs} (100%) diff --git a/Fika.Core/Coop/GameMode/CoopGame.cs b/Fika.Core/Coop/GameMode/CoopGame.cs index 43ffe13f..1027c086 100644 --- a/Fika.Core/Coop/GameMode/CoopGame.cs +++ b/Fika.Core/Coop/GameMode/CoopGame.cs @@ -54,9 +54,9 @@ internal sealed class CoopGame : BaseLocalGame, IBotGame, IFika public bool forceStart = false; public ExitStatus MyExitStatus { get; set; } = ExitStatus.Survived; public string MyExitLocation { get; set; } = null; - public ISpawnSystem SpawnSystem { get; set; } + public ISpawnSystem SpawnSystem; - public Dictionary Bots { get; set; } = []; + public Dictionary Bots = []; private CoopExfilManager exfilManager; private GameObject fikaStartButton; private readonly Dictionary botQueue = []; diff --git a/Fika.Core/Coop/GameMode/IMPTGame.cs b/Fika.Core/Coop/GameMode/IFikaGame.cs similarity index 100% rename from Fika.Core/Coop/GameMode/IMPTGame.cs rename to Fika.Core/Coop/GameMode/IFikaGame.cs From 99d92df21d56fcf3ead3aaa8d41d382034990371 Mon Sep 17 00:00:00 2001 From: Archangel Date: Wed, 22 May 2024 17:56:08 +0200 Subject: [PATCH 18/32] Save profile immediately upon death --- Fika.Core/Coop/GameMode/CoopGame.cs | 36 +++++++++++++++++++++++++++- Fika.Core/Coop/Players/CoopPlayer.cs | 9 +++++++ Fika.Core/FikaPlugin.cs | 1 + 3 files changed, 45 insertions(+), 1 deletion(-) diff --git a/Fika.Core/Coop/GameMode/CoopGame.cs b/Fika.Core/Coop/GameMode/CoopGame.cs index 1027c086..678ac773 100644 --- a/Fika.Core/Coop/GameMode/CoopGame.cs +++ b/Fika.Core/Coop/GameMode/CoopGame.cs @@ -1,5 +1,10 @@ -using Aki.Custom.Airdrops; +using Aki.Common.Http; +using Aki.Custom.Airdrops; using Aki.Reflection.Utils; +using Aki.SinglePlayer.Models.Progression; +using Aki.SinglePlayer.Utils.Healing; +using Aki.SinglePlayer.Utils.Insurance; +using Aki.SinglePlayer.Utils.Progression; using BepInEx.Logging; using Comfort.Common; using CommonAssets.Scripts.Game; @@ -34,6 +39,7 @@ using HarmonyLib; using JsonType; using LiteNetLib.Utils; +using Newtonsoft.Json; using System; using System.Collections; using System.Collections.Generic; @@ -1510,6 +1516,8 @@ public void Extract(CoopPlayer player, ExfiltrationPoint point) player.ActiveHealthController.DiedEvent -= MainPlayerDied; + SavePlayer(coopPlayer, MyExitStatus, null); + if (FikaPlugin.AutoExtract.Value) { if (MatchmakerAcceptPatches.IsClient) @@ -1581,6 +1589,8 @@ private void HealthController_DiedEvent(EDamageType obj) PlayerOwner.vmethod_1(); MyExitStatus = ExitStatus.Killed; MyExitLocation = null; + + SavePlayer((CoopPlayer)gparam_0.Player, MyExitStatus, null); } public override void Stop(string profileId, ExitStatus exitStatus, string exitName, float delay = 0f) @@ -1714,6 +1724,30 @@ public override void Stop(string profileId, ExitStatus exitStatus, string exitNa GClass549.Config.UseSpiritPlayer = false; } + private void SavePlayer(CoopPlayer player, ExitStatus exitStatus, string exitName) + { + //Since we're bypassing saving on exiting, run this now. + player.Profile.EftStats.LastPlayerState = null; + player.StatisticsManager.EndStatisticsSession(exitStatus, base.PastTime); + player.CheckAndResetControllers(exitStatus, base.PastTime, base.Location_0.Id, exitName); + + //Method taken directly from AKI, can be found in the aki-singleplayer assembly as OfflineSaveProfilePatch + var converterClass = typeof(AbstractGame).Assembly.GetTypes().First(t => t.GetField("Converters", BindingFlags.Static | BindingFlags.Public) != null); + + JsonConverter[] Converters = Traverse.Create(converterClass).Field("Converters").Value; + + SaveProfileRequest SaveRequest = new SaveProfileRequest + { + Exit = exitStatus.ToString().ToLowerInvariant(), + Profile = player.Profile, + Health = HealthListener.Instance.CurrentHealth, + Insurance = InsuredItemManager.Instance.GetTrackedItems(), + IsPlayerScav = RaidSettings.IsScav // If session joining mixed with both PMC's and scavs is added this might have to be changed + }; + + RequestHandler.PutJson("/raid/profile/save", SaveRequest.ToJson(Converters.AddItem(new NotesJsonConverter()).ToArray())); + } + private void StopFromError(string profileId, ExitStatus exitStatus) { Logger.LogInfo("CoopGame::StopFromError"); diff --git a/Fika.Core/Coop/Players/CoopPlayer.cs b/Fika.Core/Coop/Players/CoopPlayer.cs index 4745a995..d2be9f3f 100644 --- a/Fika.Core/Coop/Players/CoopPlayer.cs +++ b/Fika.Core/Coop/Players/CoopPlayer.cs @@ -1339,6 +1339,15 @@ public virtual void SetupDogTag() } } + public void CheckAndResetControllers(ExitStatus exitStatus, float pastTime, string locationId, string exitName) + { + _questController?.CheckExitConditionCounters(exitStatus, pastTime, locationId, exitName, HealthController.BodyPartEffects, TriggerZones); + _questController?.ResetCurrentNullableCounters(); + + _achievementsController?.CheckExitConditionCounters(exitStatus, pastTime, locationId, exitName, HealthController.BodyPartEffects, TriggerZones); + _achievementsController?.ResetCurrentNullableCounters(); + } + public virtual void SetInventory(EquipmentClass equipmentClass) { // Do nothing diff --git a/Fika.Core/FikaPlugin.cs b/Fika.Core/FikaPlugin.cs index 64570021..33e5e6b1 100644 --- a/Fika.Core/FikaPlugin.cs +++ b/Fika.Core/FikaPlugin.cs @@ -453,6 +453,7 @@ private void DisableSPTPatches() new BTRInteractionPatch().Disable(); new BTRExtractPassengersPatch().Disable(); new BTRPatch().Disable(); + new OfflineSaveProfilePatch().Disable(); //Disable this as we've moved it forward immediately after extraction or death } private void EnableOverridePatches() From 2ced37864151311ff65d411c90e57b6e9c978e1b Mon Sep 17 00:00:00 2001 From: Archangel Date: Wed, 22 May 2024 19:03:32 +0200 Subject: [PATCH 19/32] Make saving on death a server-side configuration --- Fika.Core/Coop/GameMode/CoopGame.cs | 10 ++++++++-- Fika.Core/FikaPlugin.cs | 7 +++++++ Fika.Core/Models/ClientConfigModel.cs | 6 +++++- 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/Fika.Core/Coop/GameMode/CoopGame.cs b/Fika.Core/Coop/GameMode/CoopGame.cs index 678ac773..4052fa18 100644 --- a/Fika.Core/Coop/GameMode/CoopGame.cs +++ b/Fika.Core/Coop/GameMode/CoopGame.cs @@ -1516,7 +1516,10 @@ public void Extract(CoopPlayer player, ExfiltrationPoint point) player.ActiveHealthController.DiedEvent -= MainPlayerDied; - SavePlayer(coopPlayer, MyExitStatus, null); + if(FikaPlugin.Instance.ForceSaveOnDeath) + { + SavePlayer(coopPlayer, MyExitStatus, null); + } if (FikaPlugin.AutoExtract.Value) { @@ -1590,7 +1593,10 @@ private void HealthController_DiedEvent(EDamageType obj) MyExitStatus = ExitStatus.Killed; MyExitLocation = null; - SavePlayer((CoopPlayer)gparam_0.Player, MyExitStatus, null); + if(FikaPlugin.Instance.ForceSaveOnDeath) + { + SavePlayer((CoopPlayer)gparam_0.Player, MyExitStatus, null); + } } public override void Stop(string profileId, ExitStatus exitStatus, string exitName, float delay = 0f) diff --git a/Fika.Core/FikaPlugin.cs b/Fika.Core/FikaPlugin.cs index 33e5e6b1..2f07f7ff 100644 --- a/Fika.Core/FikaPlugin.cs +++ b/Fika.Core/FikaPlugin.cs @@ -180,6 +180,7 @@ public class FikaPlugin : BaseUnityPlugin public bool DynamicVExfils; public bool AllowFreeCam; public bool AllowItemSending; + public bool ForceSaveOnDeath; #endregion protected void Awake() @@ -228,6 +229,11 @@ protected void Awake() new ItemContext_Patch().Enable(); } + if(ForceSaveOnDeath) + { + new OfflineSaveProfilePatch().Disable(); //Disable this as we've moved it forward immediately after extraction or death + } + BotDifficulties = FikaRequestHandler.GetBotDifficulties(); ConsoleScreen.Processor.RegisterCommandGroup(); @@ -258,6 +264,7 @@ private void GetClientConfig() DynamicVExfils = clientConfig.DynamicVExfils; AllowFreeCam = clientConfig.AllowFreeCam; AllowItemSending = clientConfig.AllowItemSending; + ForceSaveOnDeath = clientConfig.ForceSaveOnDeath; clientConfig.ToString(); } diff --git a/Fika.Core/Models/ClientConfigModel.cs b/Fika.Core/Models/ClientConfigModel.cs index bcabfec6..bdaa2e37 100644 --- a/Fika.Core/Models/ClientConfigModel.cs +++ b/Fika.Core/Models/ClientConfigModel.cs @@ -21,13 +21,17 @@ public struct ClientConfigModel [DataMember(Name = "allowItemSending")] public bool AllowItemSending; - public ClientConfigModel(bool useBTR, bool friendlyFire, bool dynamicVExfils, bool allowFreeCam, bool allowItemSending) + [DataMember(Name = "forceSaveOnDeath")] + public bool ForceSaveOnDeath; + + public ClientConfigModel(bool useBTR, bool friendlyFire, bool dynamicVExfils, bool allowFreeCam, bool allowItemSending, bool forceSaveOnDeath) { UseBTR = useBTR; FriendlyFire = friendlyFire; DynamicVExfils = dynamicVExfils; AllowFreeCam = allowFreeCam; AllowItemSending = allowItemSending; + ForceSaveOnDeath = forceSaveOnDeath; } public new void ToString() From 3a0d0fd08a37bbe0e872eba3c173f7c462a49d44 Mon Sep 17 00:00:00 2001 From: Archangel Date: Wed, 22 May 2024 19:10:58 +0200 Subject: [PATCH 20/32] Do not disable OfflineSaveProfilePatch by default --- Fika.Core/FikaPlugin.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Fika.Core/FikaPlugin.cs b/Fika.Core/FikaPlugin.cs index 2f07f7ff..ca473c8a 100644 --- a/Fika.Core/FikaPlugin.cs +++ b/Fika.Core/FikaPlugin.cs @@ -460,7 +460,6 @@ private void DisableSPTPatches() new BTRInteractionPatch().Disable(); new BTRExtractPassengersPatch().Disable(); new BTRPatch().Disable(); - new OfflineSaveProfilePatch().Disable(); //Disable this as we've moved it forward immediately after extraction or death } private void EnableOverridePatches() From edc10dcc91eff579c93311e1d181d7fae4644848 Mon Sep 17 00:00:00 2001 From: Archangel Date: Thu, 23 May 2024 07:17:33 +0200 Subject: [PATCH 21/32] Apply requested changes --- Fika.Core/Coop/GameMode/CoopGame.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Fika.Core/Coop/GameMode/CoopGame.cs b/Fika.Core/Coop/GameMode/CoopGame.cs index 4052fa18..9cf75756 100644 --- a/Fika.Core/Coop/GameMode/CoopGame.cs +++ b/Fika.Core/Coop/GameMode/CoopGame.cs @@ -1738,7 +1738,7 @@ private void SavePlayer(CoopPlayer player, ExitStatus exitStatus, string exitNam player.CheckAndResetControllers(exitStatus, base.PastTime, base.Location_0.Id, exitName); //Method taken directly from AKI, can be found in the aki-singleplayer assembly as OfflineSaveProfilePatch - var converterClass = typeof(AbstractGame).Assembly.GetTypes().First(t => t.GetField("Converters", BindingFlags.Static | BindingFlags.Public) != null); + Type converterClass = typeof(AbstractGame).Assembly.GetTypes().First(t => t.GetField("Converters", BindingFlags.Static | BindingFlags.Public) != null); JsonConverter[] Converters = Traverse.Create(converterClass).Field("Converters").Value; @@ -1748,7 +1748,7 @@ private void SavePlayer(CoopPlayer player, ExitStatus exitStatus, string exitNam Profile = player.Profile, Health = HealthListener.Instance.CurrentHealth, Insurance = InsuredItemManager.Instance.GetTrackedItems(), - IsPlayerScav = RaidSettings.IsScav // If session joining mixed with both PMC's and scavs is added this might have to be changed + IsPlayerScav = player.Side is EPlayerSide.Savage }; RequestHandler.PutJson("/raid/profile/save", SaveRequest.ToJson(Converters.AddItem(new NotesJsonConverter()).ToArray())); From 1a2ef4c772473a9dd2e2d2bb13a532dbbd2205e3 Mon Sep 17 00:00:00 2001 From: Lacyway <20912169+Lacyway@users.noreply.github.com> Date: Thu, 23 May 2024 08:27:12 +0200 Subject: [PATCH 22/32] Use coroutine to prevent nullref on HP bars --- Fika.Core/Coop/Players/ObservedCoopPlayer.cs | 24 +++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/Fika.Core/Coop/Players/ObservedCoopPlayer.cs b/Fika.Core/Coop/Players/ObservedCoopPlayer.cs index ca66c405..ab3764e4 100644 --- a/Fika.Core/Coop/Players/ObservedCoopPlayer.cs +++ b/Fika.Core/Coop/Players/ObservedCoopPlayer.cs @@ -37,6 +37,7 @@ public class ObservedCoopPlayer : CoopPlayer private readonly float interpolationRatio = 0.5f; private float observedFixedTime = 0f; private FikaHealthBar healthBar = null; + private Coroutine waitForStartRoutine; public GClass2417 NetworkHealthController { get => HealthController as GClass2417; @@ -937,6 +938,8 @@ public void InitObservedPlayer() { Profile.Info.GroupId = "Fika"; + var asd = Side; + CoopGame coopGame = (CoopGame)Singleton.Instance; IVaultingComponent vaultingComponent = playerTraverse.Field("_vaultingComponent").GetValue(); @@ -957,12 +960,31 @@ public void InitObservedPlayer() EFT.Communications.ENotificationDurationType.Default, EFT.Communications.ENotificationIconType.Friend); } - healthBar = gameObject.AddComponent(); + waitForStartRoutine = StartCoroutine(CreateHealthBar()); RaycastCameraTransform = playerTraverse.Field("_playerLookRaycastTransform").GetValue(); } } + private IEnumerator CreateHealthBar() + { + CoopGame coopGame = (CoopGame)Singleton.Instance; + + if (coopGame == null) + { + yield break; + } + + while (coopGame.Status != GameStatus.Started) + { + yield return null; + } + + healthBar = gameObject.AddComponent(); + + yield break; + } + protected override void Start() { // Do nothing From 31b4bce7ed22b2bb05b5b6060f66b9eeaa1327e8 Mon Sep 17 00:00:00 2001 From: Lacyway <20912169+Lacyway@users.noreply.github.com> Date: Thu, 23 May 2024 09:14:06 +0200 Subject: [PATCH 23/32] Cleanup --- .../ClientClasses/CoopClientInventoryController.cs | 2 +- Fika.Core/Coop/Custom/FikaDynamicAI.cs | 3 +-- Fika.Core/Coop/Custom/FikaHealthBar.cs | 2 +- Fika.Core/Coop/GameMode/AFikaGame.cs | 12 ++++++------ Fika.Core/Coop/GameMode/CoopGame.cs | 6 +++--- .../TarkovApplication_LocalGameCreator_Patch.cs | 2 +- Fika.Core/Coop/Players/CoopBot.cs | 2 +- Fika.Core/Coop/Players/CoopPlayer.cs | 8 ++++---- Fika.Core/Coop/Players/ObservedCoopPlayer.cs | 6 +++--- Fika.Core/FikaPlugin.cs | 2 +- Fika.Core/Networking/FikaClient.cs | 4 ++-- Fika.Core/Networking/FikaServer.cs | 2 +- Fika.Core/UI/Custom/MatchMakerUIScript.cs | 2 +- 13 files changed, 26 insertions(+), 27 deletions(-) diff --git a/Fika.Core/Coop/ClientClasses/CoopClientInventoryController.cs b/Fika.Core/Coop/ClientClasses/CoopClientInventoryController.cs index e4eb6aa4..ae5d9882 100644 --- a/Fika.Core/Coop/ClientClasses/CoopClientInventoryController.cs +++ b/Fika.Core/Coop/ClientClasses/CoopClientInventoryController.cs @@ -54,7 +54,7 @@ public override void Execute(GClass2837 operation, [CanBeNull] Callback callback HostInventoryOperationManager operationManager = new(this, operation, callback); if (vmethod_0(operationManager.operation)) { - operationManager.operation.vmethod_0(operationManager.HandleResult); + operationManager.operation.vmethod_0(operationManager.HandleResult); InventoryPacket packet = new() { diff --git a/Fika.Core/Coop/Custom/FikaDynamicAI.cs b/Fika.Core/Coop/Custom/FikaDynamicAI.cs index 59081045..16d3af2e 100644 --- a/Fika.Core/Coop/Custom/FikaDynamicAI.cs +++ b/Fika.Core/Coop/Custom/FikaDynamicAI.cs @@ -5,7 +5,6 @@ using EFT; using Fika.Core.Coop.Components; using Fika.Core.Coop.Players; -using System; using System.Collections.Generic; using UnityEngine; @@ -123,7 +122,7 @@ private void DeactivateBot(CoopBot bot) if (!disabledBots.Contains(bot)) { - disabledBots.Add(bot); + disabledBots.Add(bot); } else { diff --git a/Fika.Core/Coop/Custom/FikaHealthBar.cs b/Fika.Core/Coop/Custom/FikaHealthBar.cs index cb2dc73a..177caabf 100644 --- a/Fika.Core/Coop/Custom/FikaHealthBar.cs +++ b/Fika.Core/Coop/Custom/FikaHealthBar.cs @@ -99,7 +99,7 @@ private void UpdateScreenSpacePosition(bool throttleUpdate) float processedDistance = Mathf.Clamp(sqrDistance / 625, 0.6f, 1f); Vector3 position = new(currentPlayer.PlayerBones.Neck.position.x, currentPlayer.PlayerBones.Neck.position.y + (1f * processedDistance), currentPlayer.PlayerBones.Neck.position.z); - + if (!WorldToScreen.GetScreenPoint(position, mainPlayer, out Vector3 screenPoint)) { UpdateColorTextMeshProUGUI(playerPlate.playerNameScreen, 0); diff --git a/Fika.Core/Coop/GameMode/AFikaGame.cs b/Fika.Core/Coop/GameMode/AFikaGame.cs index 75ae3cb4..b1acc974 100644 --- a/Fika.Core/Coop/GameMode/AFikaGame.cs +++ b/Fika.Core/Coop/GameMode/AFikaGame.cs @@ -26,7 +26,7 @@ BotsController IBotGame.BotsController if (BotsController == null) { BotsController = (BotsController)GetType().GetFields().Where(x => x.FieldType == typeof(BotsController)).FirstOrDefault().GetValue(this); - } + } return BotsController; } } @@ -37,11 +37,11 @@ public BotsController PBotsController { get { - if (BotsController == null) - { - BotsController = (BotsController)GetType().GetFields().Where(x => x.FieldType == typeof(BotsController)).FirstOrDefault().GetValue(this); - } - return BotsController; + if (BotsController == null) + { + BotsController = (BotsController)GetType().GetFields().Where(x => x.FieldType == typeof(BotsController)).FirstOrDefault().GetValue(this); + } + return BotsController; } } diff --git a/Fika.Core/Coop/GameMode/CoopGame.cs b/Fika.Core/Coop/GameMode/CoopGame.cs index 9cf75756..2cd42b87 100644 --- a/Fika.Core/Coop/GameMode/CoopGame.cs +++ b/Fika.Core/Coop/GameMode/CoopGame.cs @@ -1516,7 +1516,7 @@ public void Extract(CoopPlayer player, ExfiltrationPoint point) player.ActiveHealthController.DiedEvent -= MainPlayerDied; - if(FikaPlugin.Instance.ForceSaveOnDeath) + if (FikaPlugin.Instance.ForceSaveOnDeath) { SavePlayer(coopPlayer, MyExitStatus, null); } @@ -1548,7 +1548,7 @@ private IEnumerator ExtractRoutine(CoopPlayer player) if (player.ActiveHealthController.DamageCoeff != 0) { player.ActiveHealthController.SetDamageCoeff(0); - } + } } else { @@ -1593,7 +1593,7 @@ private void HealthController_DiedEvent(EDamageType obj) MyExitStatus = ExitStatus.Killed; MyExitLocation = null; - if(FikaPlugin.Instance.ForceSaveOnDeath) + if (FikaPlugin.Instance.ForceSaveOnDeath) { SavePlayer((CoopPlayer)gparam_0.Player, MyExitStatus, null); } diff --git a/Fika.Core/Coop/Patches/LocalGame/TarkovApplication_LocalGameCreator_Patch.cs b/Fika.Core/Coop/Patches/LocalGame/TarkovApplication_LocalGameCreator_Patch.cs index f39d1200..cd340717 100644 --- a/Fika.Core/Coop/Patches/LocalGame/TarkovApplication_LocalGameCreator_Patch.cs +++ b/Fika.Core/Coop/Patches/LocalGame/TarkovApplication_LocalGameCreator_Patch.cs @@ -8,8 +8,8 @@ using Fika.Core.Coop.Matchmaker; using Fika.Core.Modding; using Fika.Core.Modding.Events; -using Fika.Core.Networking.Http.Models; using Fika.Core.Networking.Http; +using Fika.Core.Networking.Http.Models; using System; using System.Linq; using System.Reflection; diff --git a/Fika.Core/Coop/Players/CoopBot.cs b/Fika.Core/Coop/Players/CoopBot.cs index 6b9dc07b..f414af6f 100644 --- a/Fika.Core/Coop/Players/CoopBot.cs +++ b/Fika.Core/Coop/Players/CoopBot.cs @@ -250,7 +250,7 @@ private IEnumerator DestroyNetworkedComponents() if (PacketSender != null) { - PacketSender.DestroyThis(); + PacketSender.DestroyThis(); } } diff --git a/Fika.Core/Coop/Players/CoopPlayer.cs b/Fika.Core/Coop/Players/CoopPlayer.cs index d2be9f3f..ce0c2ed4 100644 --- a/Fika.Core/Coop/Players/CoopPlayer.cs +++ b/Fika.Core/Coop/Players/CoopPlayer.cs @@ -173,7 +173,7 @@ public void ProcessInteractWithBTR(BTRInteractionPacket packet) { if (coopHandler.clientBTR != null) { - coopHandler.clientBTR.ClientInteraction(this, packet.InteractPacket); + coopHandler.clientBTR.ClientInteraction(this, packet.InteractPacket); } } } @@ -399,7 +399,7 @@ public override void SendHeadlightsPacket(bool isSilent) Amount = lightStates.Count(), LightStates = lightStates } - }); + }); } } @@ -551,7 +551,7 @@ private IEnumerator DestroyNetworkedComponents() if (PacketSender != null) { - PacketSender.DestroyThis(); + PacketSender.DestroyThis(); } } @@ -1363,7 +1363,7 @@ public override void Dispose() base.Dispose(); if (PacketSender != null) { - PacketSender.DestroyThis(); + PacketSender.DestroyThis(); } } diff --git a/Fika.Core/Coop/Players/ObservedCoopPlayer.cs b/Fika.Core/Coop/Players/ObservedCoopPlayer.cs index ab3764e4..0df67055 100644 --- a/Fika.Core/Coop/Players/ObservedCoopPlayer.cs +++ b/Fika.Core/Coop/Players/ObservedCoopPlayer.cs @@ -605,7 +605,7 @@ public override void vmethod_3(EGesture gesture) InteractionRaycast(); if (InteractablePlayer != null) { - InteractablePlayer.ShowHelloNotification(Profile.Nickname); + InteractablePlayer.ShowHelloNotification(Profile.Nickname); } } base.vmethod_3(gesture); @@ -832,7 +832,7 @@ public override void SetInventory(EquipmentClass equipmentClass) PlayerBody.GClass1860 gclass2 = PlayerBody.SlotViews.AddOrReplace(equipmentSlot, gclass); if (gclass2 != null) { - gclass2.Dispose(); + gclass2.Dispose(); } } @@ -1174,7 +1174,7 @@ private void SetSoundRollOff() { if (NestedStepSoundSource != null) { - NestedStepSoundSource.SetRolloff(60f * ProtagonistHearing); + NestedStepSoundSource.SetRolloff(60f * ProtagonistHearing); } } diff --git a/Fika.Core/FikaPlugin.cs b/Fika.Core/FikaPlugin.cs index ca473c8a..a1345d6f 100644 --- a/Fika.Core/FikaPlugin.cs +++ b/Fika.Core/FikaPlugin.cs @@ -229,7 +229,7 @@ protected void Awake() new ItemContext_Patch().Enable(); } - if(ForceSaveOnDeath) + if (ForceSaveOnDeath) { new OfflineSaveProfilePatch().Disable(); //Disable this as we've moved it forward immediately after extraction or death } diff --git a/Fika.Core/Networking/FikaClient.cs b/Fika.Core/Networking/FikaClient.cs index 81d1c141..dce47735 100644 --- a/Fika.Core/Networking/FikaClient.cs +++ b/Fika.Core/Networking/FikaClient.cs @@ -247,7 +247,7 @@ private void OnBTRPacketReceived(BTRPacket packet) { if (CoopHandler.clientBTR != null) { - CoopHandler.clientBTR.btrPackets.Enqueue(packet); + CoopHandler.clientBTR.btrPackets.Enqueue(packet); } } @@ -428,7 +428,7 @@ private void OnGenericPacketReceived(GenericPacket packet) { if (CoopHandler.clientBTR) { - CoopHandler.clientBTR.DisplayNetworkNotification(packet.TraderServiceType); + CoopHandler.clientBTR.DisplayNetworkNotification(packet.TraderServiceType); } } break; diff --git a/Fika.Core/Networking/FikaServer.cs b/Fika.Core/Networking/FikaServer.cs index 20d0a820..68da25bc 100644 --- a/Fika.Core/Networking/FikaServer.cs +++ b/Fika.Core/Networking/FikaServer.cs @@ -231,7 +231,7 @@ private void OnBTRServicePacketReceived(BTRServicePacket packet, NetPeer peer) { if (CoopHandler.serverBTR != null) { - CoopHandler.serverBTR.NetworkBtrTraderServicePurchased(packet); + CoopHandler.serverBTR.NetworkBtrTraderServicePurchased(packet); } } diff --git a/Fika.Core/UI/Custom/MatchMakerUIScript.cs b/Fika.Core/UI/Custom/MatchMakerUIScript.cs index c0a6c4d8..18697328 100644 --- a/Fika.Core/UI/Custom/MatchMakerUIScript.cs +++ b/Fika.Core/UI/Custom/MatchMakerUIScript.cs @@ -237,7 +237,7 @@ private IEnumerator JoinMatch(string profileId, string serverId, Button button) MatchmakerAcceptPatches.SetGroupId(result.ServerId); MatchmakerAcceptPatches.SetTimestamp(result.Timestamp); MatchmakerAcceptPatches.MatchingType = EMatchmakerType.GroupPlayer; - MatchmakerAcceptPatches.HostExpectedNumberOfPlayers = result.ExpectedNumberOfPlayers; + MatchmakerAcceptPatches.HostExpectedNumberOfPlayers = result.ExpectedNumberOfPlayers; DestroyThis(); From 8ab45ce6b5ccddae21cd901716db1588a68a6760 Mon Sep 17 00:00:00 2001 From: Lacyway <20912169+Lacyway@users.noreply.github.com> Date: Thu, 23 May 2024 10:09:55 +0200 Subject: [PATCH 24/32] Use own saving methods to support new saveondeath --- Fika.Core/Coop/GameMode/CoopGame.cs | 73 +++++++++++++++++++++-------- Fika.Core/FikaPlugin.cs | 6 +-- 2 files changed, 55 insertions(+), 24 deletions(-) diff --git a/Fika.Core/Coop/GameMode/CoopGame.cs b/Fika.Core/Coop/GameMode/CoopGame.cs index 2cd42b87..212fac93 100644 --- a/Fika.Core/Coop/GameMode/CoopGame.cs +++ b/Fika.Core/Coop/GameMode/CoopGame.cs @@ -1516,11 +1516,6 @@ public void Extract(CoopPlayer player, ExfiltrationPoint point) player.ActiveHealthController.DiedEvent -= MainPlayerDied; - if (FikaPlugin.Instance.ForceSaveOnDeath) - { - SavePlayer(coopPlayer, MyExitStatus, null); - } - if (FikaPlugin.AutoExtract.Value) { if (MatchmakerAcceptPatches.IsClient) @@ -1595,7 +1590,7 @@ private void HealthController_DiedEvent(EDamageType obj) if (FikaPlugin.Instance.ForceSaveOnDeath) { - SavePlayer((CoopPlayer)gparam_0.Player, MyExitStatus, null); + SavePlayer((CoopPlayer)gparam_0.Player, MyExitStatus, null, true); } } @@ -1693,13 +1688,7 @@ public override void Stop(string profileId, ExitStatus exitStatus, string exitNa Destroy(CoopHandler.CoopHandlerParent); } - Class1364 stopManager = new() - { - baseLocalGame_0 = this, - exitStatus = exitStatus, - exitName = exitName, - delay = delay - }; + ExitManager stopManager = new(this, exitStatus, exitName, delay, myPlayer); EndByExitTrigerScenario endByExitTrigger = GetComponent(); EndByTimerScenario endByTimerScenario = GetComponent(); @@ -1726,16 +1715,19 @@ public override void Stop(string profileId, ExitStatus exitStatus, string exitNa { EnvironmentManager.Instance.Stop(); } - MonoBehaviourSingleton.Instance.StartBlackScreenShow(1f, 1f, new Action(stopManager.method_0)); + MonoBehaviourSingleton.Instance.StartBlackScreenShow(1f, 1f, new Action(stopManager.HandleExit)); GClass549.Config.UseSpiritPlayer = false; } - private void SavePlayer(CoopPlayer player, ExitStatus exitStatus, string exitName) + private void SavePlayer(CoopPlayer player, ExitStatus exitStatus, string exitName, bool fromDeath) { - //Since we're bypassing saving on exiting, run this now. - player.Profile.EftStats.LastPlayerState = null; - player.StatisticsManager.EndStatisticsSession(exitStatus, base.PastTime); - player.CheckAndResetControllers(exitStatus, base.PastTime, base.Location_0.Id, exitName); + if (fromDeath) + { + //Since we're bypassing saving on exiting, run this now. + player.Profile.EftStats.LastPlayerState = null; + player.StatisticsManager.EndStatisticsSession(exitStatus, PastTime); + player.CheckAndResetControllers(exitStatus, PastTime, Location_0.Id, exitName); + } //Method taken directly from AKI, can be found in the aki-singleplayer assembly as OfflineSaveProfilePatch Type converterClass = typeof(AbstractGame).Assembly.GetTypes().First(t => t.GetField("Converters", BindingFlags.Static | BindingFlags.Public) != null); @@ -1948,6 +1940,49 @@ public override void Dispose() base.Dispose(); } + private class ExitManager(CoopGame localGame, ExitStatus exitStatus, string exitName, float delay, CoopPlayer localPlayer) + { + private readonly CoopGame localGame = localGame; + private readonly ExitStatus exitStatus = exitStatus; + private readonly string exitName = exitName; + private readonly float delay = delay; + private readonly CoopPlayer localPlayer = localPlayer; + private Action EndAction; + + public void HandleExit() + { + GClass3107 screenManager = GClass3107.Instance; + if (screenManager.CheckCurrentScreen(EEftScreenType.Reconnect)) + { + screenManager.CloseAllScreensForced(); + } + localGame.gparam_0.Player.OnGameSessionEnd(exitStatus, localGame.PastTime, localGame.Location_0.Id, exitName); + localGame.CleanUp(); + localGame.Status = GameStatus.Stopped; + TimeSpan timeSpan = GClass1296.Now - localGame.dateTime_0; + localGame.ginterface145_0.OfflineRaidEnded(exitStatus, exitName, timeSpan.TotalSeconds).HandleExceptions(); + MonoBehaviourSingleton.Instance.FadeOutVolumeAfterRaid(); + StaticManager staticManager = StaticManager.Instance; + float num = delay; + Action action; + if ((action = EndAction) == null) + { + action = (EndAction = new Action(FireCallback)); + } + staticManager.WaitSeconds(num, action); + } + + private void FireCallback() + { + Callback endCallback = Traverse.Create(localGame).Field("callback_0").GetValue>(); + + localGame.SavePlayer(localPlayer, exitStatus, exitName, false); + + endCallback(new Result(exitStatus, GClass1296.Now - localGame.dateTime_0, new MetricsClass())); + UIEventSystem.Instance.Enable(); + } + } + private class ErrorExitManager : Class1364 { public void ExitOverride() diff --git a/Fika.Core/FikaPlugin.cs b/Fika.Core/FikaPlugin.cs index a1345d6f..954b3ca5 100644 --- a/Fika.Core/FikaPlugin.cs +++ b/Fika.Core/FikaPlugin.cs @@ -229,11 +229,6 @@ protected void Awake() new ItemContext_Patch().Enable(); } - if (ForceSaveOnDeath) - { - new OfflineSaveProfilePatch().Disable(); //Disable this as we've moved it forward immediately after extraction or death - } - BotDifficulties = FikaRequestHandler.GetBotDifficulties(); ConsoleScreen.Processor.RegisterCommandGroup(); @@ -456,6 +451,7 @@ private void DisableSPTPatches() new AmmoUsedCounterPatch().Disable(); new ArmorDamageCounterPatch().Disable(); new DogtagPatch().Disable(); + new OfflineSaveProfilePatch().Disable(); // We handle this with our own exit manager new BTRInteractionPatch().Disable(); new BTRExtractPassengersPatch().Disable(); From 634f1b70c87004ba3eab900719eb99208c6dd29e Mon Sep 17 00:00:00 2001 From: Lacyway <20912169+Lacyway@users.noreply.github.com> Date: Thu, 23 May 2024 11:26:54 +0200 Subject: [PATCH 25/32] More checks to save --- Fika.Core/Coop/GameMode/CoopGame.cs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/Fika.Core/Coop/GameMode/CoopGame.cs b/Fika.Core/Coop/GameMode/CoopGame.cs index 212fac93..3343d109 100644 --- a/Fika.Core/Coop/GameMode/CoopGame.cs +++ b/Fika.Core/Coop/GameMode/CoopGame.cs @@ -73,6 +73,7 @@ internal sealed class CoopGame : BaseLocalGame, IBotGame, IFika private WavesSpawnScenario wavesSpawnScenario_0; private NonWavesSpawnScenario nonWavesSpawnScenario_0; private Func func_1; + private bool hasSaved = false; public FikaDynamicAI DynamicAI { get; private set; } public RaidSettings RaidSettings { get; private set; } @@ -1721,6 +1722,11 @@ public override void Stop(string profileId, ExitStatus exitStatus, string exitNa private void SavePlayer(CoopPlayer player, ExitStatus exitStatus, string exitName, bool fromDeath) { + if (hasSaved) + { + return; + } + if (fromDeath) { //Since we're bypassing saving on exiting, run this now. @@ -1734,7 +1740,7 @@ private void SavePlayer(CoopPlayer player, ExitStatus exitStatus, string exitNam JsonConverter[] Converters = Traverse.Create(converterClass).Field("Converters").Value; - SaveProfileRequest SaveRequest = new SaveProfileRequest + SaveProfileRequest SaveRequest = new() { Exit = exitStatus.ToString().ToLowerInvariant(), Profile = player.Profile, @@ -1744,6 +1750,8 @@ private void SavePlayer(CoopPlayer player, ExitStatus exitStatus, string exitNam }; RequestHandler.PutJson("/raid/profile/save", SaveRequest.ToJson(Converters.AddItem(new NotesJsonConverter()).ToArray())); + + hasSaved = true; } private void StopFromError(string profileId, ExitStatus exitStatus) From e841bd02bdd869793f3f2db5afe19cca676122f8 Mon Sep 17 00:00:00 2001 From: Lacyway <20912169+Lacyway@users.noreply.github.com> Date: Thu, 23 May 2024 11:27:01 +0200 Subject: [PATCH 26/32] CameraController improvements --- .../Coop/FreeCamera/FreeCameraController.cs | 152 +++++++++++------- 1 file changed, 98 insertions(+), 54 deletions(-) diff --git a/Fika.Core/Coop/FreeCamera/FreeCameraController.cs b/Fika.Core/Coop/FreeCamera/FreeCameraController.cs index 8c7d2d9e..b5e8cca0 100644 --- a/Fika.Core/Coop/FreeCamera/FreeCameraController.cs +++ b/Fika.Core/Coop/FreeCamera/FreeCameraController.cs @@ -6,10 +6,13 @@ using Fika.Core.Coop.GameMode; using Fika.Core.Coop.Players; using Fika.Core.UI; +using HarmonyLib; using Koenigz.PerfectCulling; using Koenigz.PerfectCulling.EFT; +using System.Collections; using System.Collections.Generic; using System.Linq; +using System.Reflection; using TMPro; using UnityEngine; @@ -31,7 +34,8 @@ public class FreeCameraController : MonoBehaviour private bool _effectsCleared = false; private GamePlayerOwner _gamePlayerOwner; - private Player _player => Singleton.Instance.MainPlayer; + private CoopPlayer _player => (CoopPlayer)Singleton.Instance.MainPlayer; + private CoopHandler coopHandler; public GameObject CameraParent; public Camera CameraFreeCamera { get; private set; } @@ -41,7 +45,6 @@ public class FreeCameraController : MonoBehaviour private bool extracted = false; private DeathFade deathFade; private bool deathFadeEnabled; - private float DeadTime = 0f; private DisablerCullingObjectBase[] allCullingObjects; private List previouslyActiveBakeGroups; @@ -80,6 +83,26 @@ protected void Start() allCullingObjects = FindObjectsOfType(); previouslyActiveBakeGroups = []; + + _player.ActiveHealthController.DiedEvent += MainPlayer_DiedEvent; + + if (CoopHandler.TryGetCoopHandler(out CoopHandler cHandler)) + { + coopHandler = cHandler; + } + } + + private void MainPlayer_DiedEvent(EDamageType obj) + { + _player.ActiveHealthController.DiedEvent -= MainPlayer_DiedEvent; + + if (!deathFadeEnabled) + { + deathFade.EnableEffect(); + deathFadeEnabled = true; + } + + StartCoroutine(DeathRoutine()); } protected void Update() @@ -97,18 +120,7 @@ protected void Update() if (_player.PlayerHealthController == null) { return; - } - - if (!CoopHandler.TryGetCoopHandler(out CoopHandler coopHandler)) - { - return; - } - - CoopGame coopGame = (CoopGame)coopHandler.LocalGameInstance; - if (coopGame == null) - { - return; - } + } CoopHandler.EQuitState quitState = coopHandler.GetQuitState(); @@ -134,7 +146,8 @@ protected void Update() if (quitState == CoopHandler.EQuitState.YouHaveExtracted && !extracted) { - if (coopGame.ExtractedPlayers.Contains(((CoopPlayer)_player).NetId)) + CoopGame coopGame = (CoopGame)coopHandler.LocalGameInstance; + if (coopGame.ExtractedPlayers.Contains((_player).NetId)) { extracted = true; ShowExtractMessage(); @@ -161,64 +174,95 @@ protected void Update() _effectsCleared = true; } } + } - if (!_player.HealthController.IsAlive) + private IEnumerator DeathRoutine() + { + yield return new WaitForSeconds(5); + + CameraClass cameraClassInstance = CameraClass.Instance; + if (cameraClassInstance == null) { - DeadTime += Time.deltaTime; - if (!deathFadeEnabled) - { - deathFade.EnableEffect(); - deathFadeEnabled = true; - } + yield break; } - // Player is dead. Remove all effects! - if (!_player.HealthController.IsAlive && !_freeCamScript.IsActive && DeadTime > 5f) + if (cameraClassInstance.EffectsController == null) { - CameraClass cameraClassInstance = CameraClass.Instance; - if (cameraClassInstance == null) - { - return; - } + yield break; + } + + if (cameraClassInstance.Camera != null) + { + cameraClassInstance.Camera.fieldOfView = Singleton.Instance.Game.Settings.FieldOfView; + } + + // Disable the DeathFade effect & Toggle the Camera + deathFade.DisableEffect(); + if (!_freeCamScript.IsActive) + { + ToggleCamera(); + ToggleUi(); + } + ShowExtractMessage(); - if (cameraClassInstance.EffectsController == null) + if (!_effectsCleared) + { + if (_player != null) { - return; + _player.Muffled = false; + _player.HeavyBreath = false; } - if (cameraClassInstance.Camera != null) + if (CameraClass.Exist) { - cameraClassInstance.Camera.fieldOfView = Singleton.Instance.Game.Settings.FieldOfView; + ClearEffects(); } + _effectsCleared = true; + } + } - // Disable the DeathFade effect & Toggle the Camera - deathFade.DisableEffect(); - ToggleCamera(); - ToggleUi(); - ShowExtractMessage(); + private void ClearEffects() + { + CameraClass cameraClass = CameraClass.Instance; + cameraClass.EffectsController.method_4(false); - if (!_effectsCleared) + Traverse effectsController = Traverse.Create(cameraClass.EffectsController); + + BloodOnScreen bloodOnScreen = effectsController.Field("bloodOnScreen_0").GetValue(); + if (bloodOnScreen != null) + { + Destroy(bloodOnScreen); + } + + List effectsManagerList = effectsController.Field("list_0").GetValue>(); + if (effectsManagerList != null) + { + foreach (EffectsController.Class566 effectsManager in effectsManagerList) { - if (_player != null) + while (effectsManager.ActiveEffects.Count > 0) { - _player.Muffled = false; - _player.HeavyBreath = false; + IEffect effect = effectsManager.ActiveEffects[0]; + effectsManager.DeleteEffect(effect); } + } + effectsManagerList.Clear(); + } - if (CameraClass.Exist) - { - ClearEffects(); - } - _effectsCleared = true; + CC_Wiggle wiggleEffect = cameraClass.Camera.gameObject.GetComponent(); + if (wiggleEffect != null) + { + wiggleEffect.enabled = false; + } + + CC_Blend[] blendEffects = cameraClass.Camera.gameObject.GetComponents(); + if (blendEffects.Length > 0) + { + foreach (CC_Blend blendEffect in blendEffects) + { + blendEffect.enabled = false; } } - } - private void ClearEffects() - { - CameraClass cameraClass = CameraClass.Instance; - cameraClass.EffectsController.method_4(false); - cameraClass.EffectsController.enabled = false; Destroy(cameraClass.EffectsController); cameraClass.VisorEffect.Clear(); Destroy(cameraClass.VisorEffect); @@ -432,11 +476,11 @@ public void OnDestroy() // Destroy FreeCamScript before FreeCamController if exists Destroy(_freeCamScript); - Destroy(this); if (extractText != null) { Destroy(extractText); } + Destroy(this); } } } From 186df30814b7bed86e2ef876be2fa845bb0e301d Mon Sep 17 00:00:00 2001 From: Lacyway <20912169+Lacyway@users.noreply.github.com> Date: Thu, 23 May 2024 13:06:56 +0200 Subject: [PATCH 27/32] Fix patch not modifying ref --- .../Coop/Patches/AbstractGame/AbstractGame_InRaid_Patch.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Fika.Core/Coop/Patches/AbstractGame/AbstractGame_InRaid_Patch.cs b/Fika.Core/Coop/Patches/AbstractGame/AbstractGame_InRaid_Patch.cs index 43043ca0..8a5f9a6e 100644 --- a/Fika.Core/Coop/Patches/AbstractGame/AbstractGame_InRaid_Patch.cs +++ b/Fika.Core/Coop/Patches/AbstractGame/AbstractGame_InRaid_Patch.cs @@ -16,7 +16,7 @@ protected override MethodBase GetTargetMethod() } [PatchPrefix] - private static bool PreFix(AbstractGame __instance, bool __result) + private static bool PreFix(AbstractGame __instance, ref bool __result) { __result = __instance is CoopGame; return false; From 1e08ee16ac5b2b89119fd75012cf162e996c4f86 Mon Sep 17 00:00:00 2001 From: Lacyway <20912169+Lacyway@users.noreply.github.com> Date: Thu, 23 May 2024 15:31:43 +0200 Subject: [PATCH 28/32] Fix grenade launchers --- .../CoopClientFirearmController.cs | 26 +++++++++++-- .../Coop/FreeCamera/FreeCameraController.cs | 5 +-- Fika.Core/Coop/GameMode/CoopGame.cs | 2 +- .../CoopObservedFirearmController.cs | 37 ++++++++++++++++--- .../Packets/FirearmController/WeaponPacket.cs | 6 +++ 5 files changed, 63 insertions(+), 13 deletions(-) diff --git a/Fika.Core/Coop/ClientClasses/HandsControllers/CoopClientFirearmController.cs b/Fika.Core/Coop/ClientClasses/HandsControllers/CoopClientFirearmController.cs index 91802259..cd92be42 100644 --- a/Fika.Core/Coop/ClientClasses/HandsControllers/CoopClientFirearmController.cs +++ b/Fika.Core/Coop/ClientClasses/HandsControllers/CoopClientFirearmController.cs @@ -237,7 +237,7 @@ public override void InitiateShot(GInterface322 weapon, BulletClass ammo, Vector FireportPosition = fireportPosition, ChamberIndex = chamberIndex, Overheat = overheat, - UnderbarrelShot = weapon.IsUnderbarrelWeapon, + UnderbarrelShot = Weapon.IsUnderBarrelDeviceActive, AmmoTemplate = ammo.AmmoTemplate._id, LastShotOverheat = weapon.MalfState.LastShotOverheat, LastShotTime = weapon.MalfState.LastShotTime, @@ -308,18 +308,36 @@ public override void ReloadGrenadeLauncher(GClass2495 ammoPack, Callback callbac return; } - CurrentOperation.ReloadGrenadeLauncher(ammoPack, callback); - string[] reloadingAmmoIds = ammoPack.GetReloadingAmmoIds(); - coopPlayer.PacketSender.FirearmPackets.Enqueue(new() { + HasReloadLauncherPacket = true, ReloadLauncher = new() { Reload = true, AmmoIds = reloadingAmmoIds } }); + + CurrentOperation.ReloadGrenadeLauncher(ammoPack, callback); + } + + public override void UnderbarrelSightingRangeUp() + { + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() + { + UnderbarrelSightingRangeUp = true + }); + base.UnderbarrelSightingRangeUp(); + } + + public override void UnderbarrelSightingRangeDown() + { + coopPlayer.PacketSender.FirearmPackets.Enqueue(new() + { + UnderbarrelSightingRangeDown = true + }); + base.UnderbarrelSightingRangeDown(); } public override void ReloadMag(MagazineClass magazine, GClass2769 gridItemAddress, Callback callback) diff --git a/Fika.Core/Coop/FreeCamera/FreeCameraController.cs b/Fika.Core/Coop/FreeCamera/FreeCameraController.cs index b5e8cca0..812b80bb 100644 --- a/Fika.Core/Coop/FreeCamera/FreeCameraController.cs +++ b/Fika.Core/Coop/FreeCamera/FreeCameraController.cs @@ -12,7 +12,6 @@ using System.Collections; using System.Collections.Generic; using System.Linq; -using System.Reflection; using TMPro; using UnityEngine; @@ -120,7 +119,7 @@ protected void Update() if (_player.PlayerHealthController == null) { return; - } + } CoopHandler.EQuitState quitState = coopHandler.GetQuitState(); @@ -201,7 +200,7 @@ private IEnumerator DeathRoutine() if (!_freeCamScript.IsActive) { ToggleCamera(); - ToggleUi(); + ToggleUi(); } ShowExtractMessage(); diff --git a/Fika.Core/Coop/GameMode/CoopGame.cs b/Fika.Core/Coop/GameMode/CoopGame.cs index 3343d109..26351d76 100644 --- a/Fika.Core/Coop/GameMode/CoopGame.cs +++ b/Fika.Core/Coop/GameMode/CoopGame.cs @@ -1732,7 +1732,7 @@ private void SavePlayer(CoopPlayer player, ExitStatus exitStatus, string exitNam //Since we're bypassing saving on exiting, run this now. player.Profile.EftStats.LastPlayerState = null; player.StatisticsManager.EndStatisticsSession(exitStatus, PastTime); - player.CheckAndResetControllers(exitStatus, PastTime, Location_0.Id, exitName); + player.CheckAndResetControllers(exitStatus, PastTime, Location_0.Id, exitName); } //Method taken directly from AKI, can be found in the aki-singleplayer assembly as OfflineSaveProfilePatch diff --git a/Fika.Core/Coop/ObservedClasses/HandsControllers/CoopObservedFirearmController.cs b/Fika.Core/Coop/ObservedClasses/HandsControllers/CoopObservedFirearmController.cs index c3290abb..c7507469 100644 --- a/Fika.Core/Coop/ObservedClasses/HandsControllers/CoopObservedFirearmController.cs +++ b/Fika.Core/Coop/ObservedClasses/HandsControllers/CoopObservedFirearmController.cs @@ -3,8 +3,10 @@ using Comfort.Common; using EFT; using EFT.InventoryLogic; +using EFT.UI; using Fika.Core.Coop.Players; using Fika.Core.Networking; +using HarmonyLib; using System; using System.Collections; using System.Collections.Generic; @@ -28,6 +30,7 @@ public class CoopObservedFirearmController : FirearmController private float aimMovementSpeed = 1f; private bool hasFired = false; private WeaponPrefab weaponPrefab; + private GClass1582 underBarrelManager; public override bool IsAiming { get => base.IsAiming; @@ -43,7 +46,7 @@ public override bool IsAiming } _isAiming = value; - _player.Skills.FastAimTimer.Target = (value ? 0f : 2f); + _player.Skills.FastAimTimer.Target = value ? 0f : 2f; _player.MovementContext.SetAimingSlowdown(IsAiming, 0.33f + aimMovementSpeed); _player.Physical.Aim((!_isAiming || !(_player.MovementContext.StationaryWeapon == null)) ? 0f : ErgonomicWeight); coopPlayer.ProceduralWeaponAnimation.IsAiming = _isAiming; @@ -62,6 +65,10 @@ protected void Start() _objectInHandsAnimator.SetAiming(false); aimMovementSpeed = coopPlayer.Skills.GetWeaponInfo(Item).AimMovementSpeed; weaponPrefab = ControllerGameObject.GetComponent(); + if (UnderbarrelWeapon != null) + { + underBarrelManager = Traverse.Create(this).Field("gclass1582_0").GetValue(); + } } public static CoopObservedFirearmController Create(CoopPlayer player, Weapon weapon) @@ -226,7 +233,7 @@ public void HandleFirearmPacket(in WeaponPacket packet, InventoryControllerClass } BulletClass ammo = (BulletClass)Singleton.Instance.CreateItem(MongoID.Generate(), packet.ShotInfoPacket.AmmoTemplate, null); - InitiateShot(Item, ammo, packet.ShotInfoPacket.ShotPosition, packet.ShotInfoPacket.ShotDirection, + InitiateShot(packet.ShotInfoPacket.UnderbarrelShot ? UnderbarrelWeapon : Item, ammo, packet.ShotInfoPacket.ShotPosition, packet.ShotInfoPacket.ShotDirection, packet.ShotInfoPacket.FireportPosition, packet.ShotInfoPacket.ChamberIndex, packet.ShotInfoPacket.Overheat); if (Weapon.SelectedFireMode == Weapon.EFireMode.fullauto) @@ -254,6 +261,18 @@ public void HandleFirearmPacket(in WeaponPacket packet, InventoryControllerClass FirearmsAnimator.SetFire(true); + if (packet.ShotInfoPacket.UnderbarrelShot) + { + if (UnderbarrelWeapon.Chamber.ContainedItem is BulletClass grenadeBullet && !grenadeBullet.IsUsed) + { + grenadeBullet.IsUsed = true; + UnderbarrelWeapon.Chamber.RemoveItem(); + underBarrelManager?.DestroyPatronInWeapon(); + } + FirearmsAnimator.SetFire(false); + return; + } + if (Weapon.HasChambers) { if (Weapon.ReloadMode is Weapon.EReloadMode.OnlyBarrel) @@ -284,7 +303,7 @@ public void HandleFirearmPacket(in WeaponPacket packet, InventoryControllerClass } else { - Weapon.Chambers[0].RemoveItem(false); + Weapon.Chambers[0].RemoveItem(); if (weaponPrefab != null && weaponPrefab.ObjectInHands is GClass1668 weaponEffectsManager) { HandleShellEvent(weaponEffectsManager, packet, ammo, magazine); @@ -521,8 +540,6 @@ public void HandleFirearmPacket(in WeaponPacket packet, InventoryControllerClass { CurrentOperation.SetTriggerPressed(true); } - - }*/ if (packet.HasRollCylinder && Weapon is GClass2696 rollWeapon) @@ -594,6 +611,16 @@ public void HandleFirearmPacket(in WeaponPacket packet, InventoryControllerClass { StartCoroutine(ObservedBoltAction(FirearmsAnimator, this, inventoryController)); } + + if (packet.UnderbarrelSightingRangeUp) + { + UnderbarrelSightingRangeUp(); + } + + if (packet.UnderbarrelSightingRangeDown) + { + UnderbarrelSightingRangeDown(); + } } private IEnumerator ObservedBoltAction(FirearmsAnimator animator, FirearmController controller, InventoryControllerClass inventoryController) diff --git a/Fika.Core/Networking/Packets/FirearmController/WeaponPacket.cs b/Fika.Core/Networking/Packets/FirearmController/WeaponPacket.cs index ede93653..7a841088 100644 --- a/Fika.Core/Networking/Packets/FirearmController/WeaponPacket.cs +++ b/Fika.Core/Networking/Packets/FirearmController/WeaponPacket.cs @@ -54,6 +54,8 @@ public struct WeaponPacket(int netId) : INetSerializable public bool ReloadBoltAction = false; public bool HasRollCylinder = false; public bool RollToZeroCamora = false; + public bool UnderbarrelSightingRangeUp = false; + public bool UnderbarrelSightingRangeDown = false; public void Deserialize(NetDataReader reader) { @@ -123,6 +125,8 @@ public void Deserialize(NetDataReader reader) HasRollCylinder = reader.GetBool(); if (HasRollCylinder) RollToZeroCamora = reader.GetBool(); + UnderbarrelSightingRangeUp = reader.GetBool(); + UnderbarrelSightingRangeDown = reader.GetBool(); } public void Serialize(NetDataWriter writer) @@ -189,6 +193,8 @@ public void Serialize(NetDataWriter writer) writer.Put(HasRollCylinder); if (HasRollCylinder) writer.Put(RollToZeroCamora); + writer.Put(UnderbarrelSightingRangeUp); + writer.Put(UnderbarrelSightingRangeDown); } } } From 7da41e91734a8de81beaa6229b877111c7236b83 Mon Sep 17 00:00:00 2001 From: Archangel Date: Thu, 23 May 2024 16:04:08 +0200 Subject: [PATCH 29/32] Allow examination of items in raid --- Fika.Core/Coop/Players/CoopPlayer.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Fika.Core/Coop/Players/CoopPlayer.cs b/Fika.Core/Coop/Players/CoopPlayer.cs index ce0c2ed4..5da9fe75 100644 --- a/Fika.Core/Coop/Players/CoopPlayer.cs +++ b/Fika.Core/Coop/Players/CoopPlayer.cs @@ -62,7 +62,7 @@ public static async Task Create(int playerId, Vector3 position, Qua player.IsYourPlayer = true; player.NetId = netId; - CoopClientInventoryController inventoryController = new(player, profile, true); + CoopClientInventoryController inventoryController = new(player, profile, false); ISession session = Singleton>.Instance.GetClientBackEndSession(); From 848697e726925e119b6ce46a48285eb0bbb67f8d Mon Sep 17 00:00:00 2001 From: Lacyway <20912169+Lacyway@users.noreply.github.com> Date: Thu, 23 May 2024 16:56:16 +0200 Subject: [PATCH 30/32] Improve DynamicAI disabling --- Fika.Core/Coop/Custom/FikaDynamicAI.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Fika.Core/Coop/Custom/FikaDynamicAI.cs b/Fika.Core/Coop/Custom/FikaDynamicAI.cs index 16d3af2e..909212e8 100644 --- a/Fika.Core/Coop/Custom/FikaDynamicAI.cs +++ b/Fika.Core/Coop/Custom/FikaDynamicAI.cs @@ -6,6 +6,7 @@ using Fika.Core.Coop.Components; using Fika.Core.Coop.Players; using System.Collections.Generic; +using System.Linq; using UnityEngine; namespace Fika.Core.Coop.Custom @@ -193,9 +194,10 @@ public void EnabledChange(bool value) { if (!value) { - foreach (CoopBot bot in disabledBots) + CoopBot[] disabledBotsArray = [.. disabledBots]; + for (int i = 0; i < disabledBotsArray.Length; i++) { - bot.gameObject.SetActive(true); + ActivateBot(disabledBotsArray[i]); } disabledBots.Clear(); From 07e99490e94f5dbd8d8310920f7efbc0ecb13b3a Mon Sep 17 00:00:00 2001 From: Lacyway <20912169+Lacyway@users.noreply.github.com> Date: Thu, 23 May 2024 16:56:47 +0200 Subject: [PATCH 31/32] Only use max AI if enforced is enabled --- Fika.Core/Coop/GameMode/CoopGame.cs | 41 ++++++++++++++++------------- Fika.Core/FikaPlugin.cs | 20 +++++++------- 2 files changed, 32 insertions(+), 29 deletions(-) diff --git a/Fika.Core/Coop/GameMode/CoopGame.cs b/Fika.Core/Coop/GameMode/CoopGame.cs index 26351d76..47f27e43 100644 --- a/Fika.Core/Coop/GameMode/CoopGame.cs +++ b/Fika.Core/Coop/GameMode/CoopGame.cs @@ -323,7 +323,7 @@ private async Task CreateBot(Profile profile, Vector3 position) if (!CoopHandler.TryGetCoopHandler(out CoopHandler coopHandler)) { - Logger.LogDebug($"{nameof(CreateBot)}:Unable to find {nameof(CoopHandler)}"); + Logger.LogError($"{nameof(CreateBot)}:Unable to find {nameof(CoopHandler)}"); return null; } @@ -1142,25 +1142,28 @@ public override IEnumerator vmethod_4(float startDelay, BotControllerSettings co botsController_0.SetSettings(numberOfBots, BackEndSession.BackEndConfig.BotPresets, BackEndSession.BackEndConfig.BotWeaponScatterings); botsController_0.AddActivePLayer(PlayerOwner.Player); - int limits = Location_0.Id.ToLower() switch - { - "factory4_day" => FikaPlugin.MaxBotsFactory.Value, - "factory4_night" => FikaPlugin.MaxBotsFactory.Value, - "bigmap" => FikaPlugin.MaxBotsCustoms.Value, - "interchange" => FikaPlugin.MaxBotsInterchange.Value, - "rezervbase" => FikaPlugin.MaxBotsReserve.Value, - "woods" => FikaPlugin.MaxBotsWoods.Value, - "shoreline" => FikaPlugin.MaxBotsShoreline.Value, - "tarkovstreets" => FikaPlugin.MaxBotsStreets.Value, - "sandbox" => FikaPlugin.MaxBotsGroundZero.Value, - "laboratory" => FikaPlugin.MaxBotsLabs.Value, - "lighthouse" => FikaPlugin.MaxBotsLighthouse.Value, - _ => 0 - }; - - if (limits > 0) + if (FikaPlugin.EnforcedSpawnLimits.Value) { - botsController_0.BotSpawner.SetMaxBots(limits); + int limits = Location_0.Id.ToLower() switch + { + "factory4_day" => FikaPlugin.MaxBotsFactory.Value, + "factory4_night" => FikaPlugin.MaxBotsFactory.Value, + "bigmap" => FikaPlugin.MaxBotsCustoms.Value, + "interchange" => FikaPlugin.MaxBotsInterchange.Value, + "rezervbase" => FikaPlugin.MaxBotsReserve.Value, + "woods" => FikaPlugin.MaxBotsWoods.Value, + "shoreline" => FikaPlugin.MaxBotsShoreline.Value, + "tarkovstreets" => FikaPlugin.MaxBotsStreets.Value, + "sandbox" => FikaPlugin.MaxBotsGroundZero.Value, + "laboratory" => FikaPlugin.MaxBotsLabs.Value, + "lighthouse" => FikaPlugin.MaxBotsLighthouse.Value, + _ => 0 + }; + + if (limits > 0) + { + botsController_0.BotSpawner.SetMaxBots(limits); + } } DynamicAI = gameObject.AddComponent(); diff --git a/Fika.Core/FikaPlugin.cs b/Fika.Core/FikaPlugin.cs index 954b3ca5..d351c479 100644 --- a/Fika.Core/FikaPlugin.cs +++ b/Fika.Core/FikaPlugin.cs @@ -350,25 +350,25 @@ private void SetupConfig() DespawnMinimumDistance = Config.Bind("Performance | Max Bots", "Despawn Minimum Distance", 200.0f, new ConfigDescription("Don't despawn bots within this distance.", new AcceptableValueRange(50f, 3000f), new ConfigurationManagerAttributes() { Order = 12 })); - MaxBotsFactory = Config.Bind("Performance | Max Bots", "Max Bots Factory", 0, new ConfigDescription("Max amount of bots that can be active at the same time on Factory. Useful if you have a weaker PC. Set to 0 to use vanilla limits.", new AcceptableValueRange(0, 50), new ConfigurationManagerAttributes() { Order = 11 })); + MaxBotsFactory = Config.Bind("Performance | Max Bots", "Max Bots Factory", 0, new ConfigDescription("Max amount of bots that can be active at the same time on Factory. Useful if you have a weaker PC. Set to 0 to use vanilla limits. Cannot be changed during a raid.", new AcceptableValueRange(0, 50), new ConfigurationManagerAttributes() { Order = 11 })); - MaxBotsCustoms = Config.Bind("Performance | Max Bots", "Max Bots Customs", 0, new ConfigDescription("Max amount of bots that can be active at the same time on Customs. Useful if you have a weaker PC. Set to 0 to use vanilla limits.", new AcceptableValueRange(0, 50), new ConfigurationManagerAttributes() { Order = 10 })); + MaxBotsCustoms = Config.Bind("Performance | Max Bots", "Max Bots Customs", 0, new ConfigDescription("Max amount of bots that can be active at the same time on Customs. Useful if you have a weaker PC. Set to 0 to use vanilla limits. Cannot be changed during a raid.", new AcceptableValueRange(0, 50), new ConfigurationManagerAttributes() { Order = 10 })); - MaxBotsInterchange = Config.Bind("Performance | Max Bots", "Max Bots Interchange", 0, new ConfigDescription("Max amount of bots that can be active at the same time on Interchange. Useful if you have a weaker PC. Set to 0 to use vanilla limits.", new AcceptableValueRange(0, 50), new ConfigurationManagerAttributes() { Order = 8 })); + MaxBotsInterchange = Config.Bind("Performance | Max Bots", "Max Bots Interchange", 0, new ConfigDescription("Max amount of bots that can be active at the same time on Interchange. Useful if you have a weaker PC. Set to 0 to use vanilla limits. Cannot be changed during a raid.", new AcceptableValueRange(0, 50), new ConfigurationManagerAttributes() { Order = 8 })); - MaxBotsReserve = Config.Bind("Performance | Max Bots", "Max Bots Reserve", 0, new ConfigDescription("Max amount of bots that can be active at the same time on Reserve. Useful if you have a weaker PC. Set to 0 to use vanilla limits.", new AcceptableValueRange(0, 50), new ConfigurationManagerAttributes() { Order = 7 })); + MaxBotsReserve = Config.Bind("Performance | Max Bots", "Max Bots Reserve", 0, new ConfigDescription("Max amount of bots that can be active at the same time on Reserve. Useful if you have a weaker PC. Set to 0 to use vanilla limits. Cannot be changed during a raid.", new AcceptableValueRange(0, 50), new ConfigurationManagerAttributes() { Order = 7 })); - MaxBotsWoods = Config.Bind("Performance | Max Bots", "Max Bots Woods", 0, new ConfigDescription("Max amount of bots that can be active at the same time on Woods. Useful if you have a weaker PC. Set to 0 to use vanilla limits.", new AcceptableValueRange(0, 50), new ConfigurationManagerAttributes() { Order = 6 })); + MaxBotsWoods = Config.Bind("Performance | Max Bots", "Max Bots Woods", 0, new ConfigDescription("Max amount of bots that can be active at the same time on Woods. Useful if you have a weaker PC. Set to 0 to use vanilla limits. Cannot be changed during a raid.", new AcceptableValueRange(0, 50), new ConfigurationManagerAttributes() { Order = 6 })); - MaxBotsShoreline = Config.Bind("Performance | Max Bots", "Max Bots Shoreline", 0, new ConfigDescription("Max amount of bots that can be active at the same time on Shoreline. Useful if you have a weaker PC. Set to 0 to use vanilla limits.", new AcceptableValueRange(0, 50), new ConfigurationManagerAttributes() { Order = 5 })); + MaxBotsShoreline = Config.Bind("Performance | Max Bots", "Max Bots Shoreline", 0, new ConfigDescription("Max amount of bots that can be active at the same time on Shoreline. Useful if you have a weaker PC. Set to 0 to use vanilla limits. Cannot be changed during a raid.", new AcceptableValueRange(0, 50), new ConfigurationManagerAttributes() { Order = 5 })); - MaxBotsStreets = Config.Bind("Performance | Max Bots", "Max Bots Streets", 0, new ConfigDescription("Max amount of bots that can be active at the same time on Streets of Tarkov. Useful if you have a weaker PC. Set to 0 to use vanilla limits.", new AcceptableValueRange(0, 50), new ConfigurationManagerAttributes() { Order = 4 })); + MaxBotsStreets = Config.Bind("Performance | Max Bots", "Max Bots Streets", 0, new ConfigDescription("Max amount of bots that can be active at the same time on Streets of Tarkov. Useful if you have a weaker PC. Set to 0 to use vanilla limits. Cannot be changed during a raid.", new AcceptableValueRange(0, 50), new ConfigurationManagerAttributes() { Order = 4 })); - MaxBotsGroundZero = Config.Bind("Performance | Max Bots", "Max Bots Ground Zero", 0, new ConfigDescription("Max amount of bots that can be active at the same time on Ground Zero. Useful if you have a weaker PC. Set to 0 to use vanilla limits.", new AcceptableValueRange(0, 50), new ConfigurationManagerAttributes() { Order = 3 })); + MaxBotsGroundZero = Config.Bind("Performance | Max Bots", "Max Bots Ground Zero", 0, new ConfigDescription("Max amount of bots that can be active at the same time on Ground Zero. Useful if you have a weaker PC. Set to 0 to use vanilla limits. Cannot be changed during a raid.", new AcceptableValueRange(0, 50), new ConfigurationManagerAttributes() { Order = 3 })); - MaxBotsLabs = Config.Bind("Performance | Max Bots", "Max Bots Labs", 0, new ConfigDescription("Max amount of bots that can be active at the same time on Labs. Useful if you have a weaker PC. Set to 0 to use vanilla limits.", new AcceptableValueRange(0, 50), new ConfigurationManagerAttributes() { Order = 2 })); + MaxBotsLabs = Config.Bind("Performance | Max Bots", "Max Bots Labs", 0, new ConfigDescription("Max amount of bots that can be active at the same time on Labs. Useful if you have a weaker PC. Set to 0 to use vanilla limits. Cannot be changed during a raid.", new AcceptableValueRange(0, 50), new ConfigurationManagerAttributes() { Order = 2 })); - MaxBotsLighthouse = Config.Bind("Performance | Max Bots", "Max Bots Lighthouse", 0, new ConfigDescription("Max amount of bots that can be active at the same time on Lighthouse. Useful if you have a weaker PC. Set to 0 to use vanilla limits.", new AcceptableValueRange(0, 50), new ConfigurationManagerAttributes() { Order = 1 })); + MaxBotsLighthouse = Config.Bind("Performance | Max Bots", "Max Bots Lighthouse", 0, new ConfigDescription("Max amount of bots that can be active at the same time on Lighthouse. Useful if you have a weaker PC. Set to 0 to use vanilla limits. Cannot be changed during a raid.", new AcceptableValueRange(0, 50), new ConfigurationManagerAttributes() { Order = 1 })); // Network From df9e0e5fcf8116abc30016fa2f7ddf7b35c9db5c Mon Sep 17 00:00:00 2001 From: Lacyway <20912169+Lacyway@users.noreply.github.com> Date: Thu, 23 May 2024 17:14:00 +0200 Subject: [PATCH 32/32] Improve logic to enforced spawn limits --- Fika.Core/Coop/GameMode/CoopGame.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Fika.Core/Coop/GameMode/CoopGame.cs b/Fika.Core/Coop/GameMode/CoopGame.cs index 47f27e43..3e368d87 100644 --- a/Fika.Core/Coop/GameMode/CoopGame.cs +++ b/Fika.Core/Coop/GameMode/CoopGame.cs @@ -323,7 +323,7 @@ private async Task CreateBot(Profile profile, Vector3 position) if (!CoopHandler.TryGetCoopHandler(out CoopHandler coopHandler)) { - Logger.LogError($"{nameof(CreateBot)}:Unable to find {nameof(CoopHandler)}"); + Logger.LogError($"{nameof(CreateBot)}: Unable to find {nameof(CoopHandler)}"); return null; } @@ -337,7 +337,7 @@ private async Task CreateBot(Profile profile, Vector3 position) isSpecial = true; } - if (FikaPlugin.EnforcedSpawnLimits.Value && botsController_0.AliveAndLoadingBotsCount >= botsController_0.BotSpawner.MaxBots) + if (FikaPlugin.EnforcedSpawnLimits.Value && Bots.Count >= botsController_0.BotSpawner.MaxBots) { bool despawned = false; @@ -485,6 +485,9 @@ private bool TryDespawnFurthest(Profile profile, Vector3 position, CoopHandler c if (botKey == string.Empty) { +#if DEBUG + Logger.LogWarning("TryDespawnFurthest: botKey was empty"); +#endif return false; }