Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor GameTimer And Weather #317

Merged
merged 1 commit into from
May 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions Source/Coop/Components/CoopGameComponents/SITGameComponent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -348,16 +348,16 @@ private void GameWorld_AfterGameStarted()
{
GameWorldGameStarted = true;
Logger.LogDebug(nameof(GameWorld_AfterGameStarted));
//if (Singleton<GameWorld>.Instance.RegisteredPlayers.Any())
//{
// // Send My Player to Aki, so that other clients know about me
// CoopSITGame.SendPlayerDataToServer((LocalPlayer)Singleton<GameWorld>.Instance.RegisteredPlayers.First(x => x.IsYourPlayer));
//}

this.GetOrAddComponent<SITGameGCComponent>();
this.GetOrAddComponent<SITGameTimeAndWeatherSyncComponent>();
this.GetOrAddComponent<SITGameExtractionComponent>();

// Add Server Authority components
if (SITMatchmaking.IsServer)
{
this.GetOrAddComponent<SITGameTimeAndWeatherSyncComponent>();
}

StartCoroutine(SendPlayerStatePacket());

// tell clients which exfils are disabled
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ void Update()
{
LastTimeSent = DateTime.Now;

TimeAndWeatherPacket packet = new TimeAndWeatherPacket();
TimeAndWeatherPacket packet = new();

var sitGame = Singleton<ISITGame>.Instance as BaseLocalGame<GamePlayerOwner>;
var sitGame = Singleton<ISITGame>.Instance;

if (sitGame.GameDateTime != null)
packet.GameDateTime = sitGame.GameDateTime.Calculate().Ticks;
Expand All @@ -58,6 +58,13 @@ void Update()

Networking.GameClient.SendData(packet.Serialize());
}

if (sitGame.GameTimer.StartDateTime.HasValue && sitGame.GameTimer.SessionTime.HasValue)
{
RaidTimerPacket raidTimerPacket = new();
raidTimerPacket.SessionTime = (sitGame.GameTimer.SessionTime - sitGame.GameTimer.PastTime).Value.Ticks;
Networking.GameClient.SendData(raidTimerPacket.Serialize());
}
}
}
}
Expand Down
42 changes: 32 additions & 10 deletions Source/Coop/NetworkPacket/Raid/RaidTimerPacket.cs
Original file line number Diff line number Diff line change
@@ -1,20 +1,27 @@
using EFT.UI.BattleTimer;
using BepInEx.Logging;
using Comfort.Common;
using EFT;
using EFT.UI.BattleTimer;
using HarmonyLib.Tools;
using StayInTarkov.Coop.Components.CoopGameComponents;
using StayInTarkov.Coop.Matchmaker;
using StayInTarkov.Coop.SITGameModes;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace StayInTarkov.Coop.NetworkPacket.Raid
{
internal sealed class RaidTimerPacket : BasePacket
{
static RaidTimerPacket()
{
Logger = BepInEx.Logging.Logger.CreateLogSource(nameof(RaidTimerPacket));
}

public long SessionTime { get; set; }
public static ManualLogSource Logger { get; }

public RaidTimerPacket() : base(nameof(RaidTimerPacket))
{
Expand All @@ -23,15 +30,15 @@ public RaidTimerPacket() : base(nameof(RaidTimerPacket))
public override byte[] Serialize()
{
var ms = new MemoryStream();
using BinaryWriter writer = new BinaryWriter(ms);
using BinaryWriter writer = new(ms);
WriteHeader(writer);
writer.Write(SessionTime);
return ms.ToArray();
}

public override ISITPacket Deserialize(byte[] bytes)
{
using BinaryReader reader = new BinaryReader(new MemoryStream(bytes));
using BinaryReader reader = new(new MemoryStream(bytes));
ReadHeader(reader);
SessionTime = reader.ReadInt64();
return this;
Expand All @@ -48,9 +55,24 @@ public override void Process()

var sessionTime = new TimeSpan(SessionTime);

if (coopGameComponent.LocalGameInstance is CoopSITGame coopGame)
if (!Singleton<ISITGame>.Instantiated)
{
Logger.LogError($"{nameof(Process)} failed {nameof(ISITGame)} was not instantiated!");
return;
}

if (!Singleton<AbstractGame>.Instantiated)
{
Logger.LogError($"{nameof(Process)} failed {nameof(AbstractGame)} was not instantiated!");
return;
}

var sitGame = Singleton<ISITGame>.Instance;
var abstractGame = Singleton<AbstractGame>.Instance;

//if (coopGameComponent.LocalGameInstance is CoopSITGame coopGame)
{
var gameTimer = coopGame.GameTimer;
var gameTimer = sitGame.GameTimer;
if (gameTimer.StartDateTime.HasValue && gameTimer.SessionTime.HasValue)
{
if (gameTimer.PastTime.TotalSeconds < 3)
Expand All @@ -64,7 +86,7 @@ public override void Process()
StayInTarkovHelperConstants.Logger.LogInfo($"RaidTimer: New SessionTime {timeRemain.TraderFormat()}");
gameTimer.ChangeSessionTime(timeRemain);

MainTimerPanel mainTimerPanel = ReflectionHelpers.GetFieldOrPropertyFromInstance<MainTimerPanel>(coopGame.GameUi.TimerPanel, "_mainTimerPanel", false);
MainTimerPanel mainTimerPanel = ReflectionHelpers.GetFieldOrPropertyFromInstance<MainTimerPanel>(abstractGame.GameUi.TimerPanel, "_mainTimerPanel", false);
if (mainTimerPanel != null)
{
FieldInfo extractionDateTimeField = ReflectionHelpers.GetFieldFromType(typeof(TimerPanel), "dateTime_0");
Expand Down
105 changes: 15 additions & 90 deletions Source/Coop/SITGameModes/CoopSITGame.cs
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@
Logger.LogDebug("OnDestroy()");
Singleton<GameWorld>.Instance.AfterGameStarted -= Instance_AfterGameStarted;

Comfort.Common.Singleton<ISITGame>.TryRelease(this);
Comfort.Common.Singleton<ISITGame>.TryRelease(this);
}

public void CreateCoopGameComponent()
Expand All @@ -242,8 +242,6 @@

if (SITMatchmaking.IsServer)
{
StartCoroutine(GameTimerSync());
StartCoroutine(TimeAndWeatherSync());
StartCoroutine(ArmoredTrainTimeSync());
}

Expand Down Expand Up @@ -288,79 +286,6 @@
}
}

private IEnumerator GameTimerSync()
{
var waitSeconds = new WaitForSeconds(10f);

while (true)
{
yield return waitSeconds;

if (!SITGameComponent.TryGetCoopGameComponent(out var coopGameComponent))
yield break;

if (GameTimer.StartDateTime.HasValue && GameTimer.SessionTime.HasValue)
{
//Dictionary<string, object> raidTimerDict = new()
//{
// { "serverId", coopGameComponent.ServerId },
// { "m", "RaidTimer" },
// { "sessionTime", (GameTimer.SessionTime - GameTimer.PastTime).Value.Ticks },
//};
//Networking.GameClient.SendData(raidTimerDict.ToJson());
RaidTimerPacket packet = new RaidTimerPacket();
packet.SessionTime = (GameTimer.SessionTime - GameTimer.PastTime).Value.Ticks;
Networking.GameClient.SendData(packet.Serialize());
}
}
}

private IEnumerator TimeAndWeatherSync()
{
var waitSeconds = new WaitForSeconds(15f);

while (true)
{
yield return waitSeconds;

if (!SITGameComponent.TryGetCoopGameComponent(out var coopGameComponent))
yield break;

Dictionary<string, object> timeAndWeatherDict = new()
{
{ "serverId", coopGameComponent.ServerId },
{ "m", "TimeAndWeather" }
};

if (GameDateTime != null)
timeAndWeatherDict.Add("GameDateTime", GameDateTime.Calculate().Ticks);

var weatherController = WeatherController.Instance;
if (weatherController != null)
{
if (weatherController.CloudsController != null)
timeAndWeatherDict.Add("CloudDensity", weatherController.CloudsController.Density);

var weatherCurve = weatherController.WeatherCurve;
if (weatherCurve != null)
{
timeAndWeatherDict.Add("Fog", weatherCurve.Fog);
timeAndWeatherDict.Add("LightningThunderProbability", weatherCurve.LightningThunderProbability);
timeAndWeatherDict.Add("Rain", weatherCurve.Rain);
timeAndWeatherDict.Add("Temperature", weatherCurve.Temperature);
timeAndWeatherDict.Add("WindDirection.x", weatherCurve.Wind.x);
timeAndWeatherDict.Add("WindDirection.y", weatherCurve.Wind.y);
timeAndWeatherDict.Add("TopWindDirection.x", weatherCurve.TopWind.x);
timeAndWeatherDict.Add("TopWindDirection.y", weatherCurve.TopWind.y);
}

string packet = timeAndWeatherDict.ToJson();
Logger.LogDebug(packet);
Networking.GameClient.SendData(packet);
}
}
}

private IEnumerator ArmoredTrainTimeSync()
{
var waitSeconds = new WaitForSeconds(30f);
Expand Down Expand Up @@ -535,7 +460,7 @@
base.vmethod_1(timeBeforeDeploy);
}

public static async Task<ISpawnPoint?> SendOrReceiveSpawnPoint(ISpawnPoint selectedSpawnPoint, SpawnPoints spawnPoints)

Check warning on line 463 in Source/Coop/SITGameModes/CoopSITGame.cs

View workflow job for this annotation

GitHub Actions / Build-SIT (Debug)

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
{
var position = selectedSpawnPoint.Position;
if (!SITMatchmaking.IsClient)
Expand Down Expand Up @@ -619,7 +544,7 @@
switch (SITMatchmaking.SITProtocol)
{
case ESITProtocol.RelayTcp:
JObject j = new JObject();
JObject j = new();
j.Add("serverId", SITGameComponent.GetServerId());
j.Add("profileId", profile.ProfileId);
j.Add("connect", true);
Expand Down Expand Up @@ -771,7 +696,7 @@
}
//});

ReadyToStartGamePacket packet = new ReadyToStartGamePacket(SITMatchmaking.Profile.ProfileId);
ReadyToStartGamePacket packet = new(SITMatchmaking.Profile.ProfileId);
GameClient.SendData(packet.Serialize());
}

Expand Down Expand Up @@ -836,7 +761,7 @@

if (!SITMatchmaking.IsClient)
{
HostStartingGamePacket packet = new HostStartingGamePacket();
HostStartingGamePacket packet = new();
GameClient.SendData(packet.Serialize());
}
}
Expand Down Expand Up @@ -895,7 +820,7 @@

private void SendRequestSpawnPlayersPacket()
{
RequestSpawnPlayersPacket requestSpawnPlayersPacket = new RequestSpawnPlayersPacket([Singleton<GameWorld>.Instance.MainPlayer.ProfileId]);
RequestSpawnPlayersPacket requestSpawnPlayersPacket = new([Singleton<GameWorld>.Instance.MainPlayer.ProfileId]);
GameClient.SendData(requestSpawnPlayersPacket.Serialize());
}

Expand Down Expand Up @@ -1069,7 +994,7 @@
try
{
bool isWinter = BackEndSession.IsWinter;
WinterEventController winterEventController = new WinterEventController();
WinterEventController winterEventController = new();
ReflectionHelpers.GetFieldFromTypeByFieldType(typeof(GameWorld), typeof(WinterEventController)).SetValue(Singleton<GameWorld>.Instance, winterEventController);
winterEventController.Run(isWinter).ContinueWith(x => { if (x.IsFaulted) Logger.LogError(x.Exception); return Task.CompletedTask; });
}
Expand Down Expand Up @@ -1398,7 +1323,7 @@

value.Dispose();

if(value.gameObject != null)
if (value.gameObject != null)
AssetPoolObject.ReturnToPool(value.gameObject);
}
catch (Exception exception)
Expand Down Expand Up @@ -1477,19 +1402,19 @@
location = await BackEndSession.LoadLocationLoot(Location_0.Id, variantId);
}
}

BackendConfigManagerConfig config = BackendConfigManager.Config;
if (config.FixedFrameRate > 0f)
{
base.FixedDeltaTime = 1f / config.FixedFrameRate;
}
EFT.Player player = await CreatePlayerSpawn();
dictionary_0.Add(player.ProfileId, player);
gparam_0 = func_1(player);
PlayerCameraController.Create(gparam_0.Player);
CameraClass.Instance.SetOcclusionCullingEnabled(Location_0.OcculsionCullingEnabled);
CameraClass.Instance.IsActive = false;

EFT.Player player = await CreatePlayerSpawn();
dictionary_0.Add(player.ProfileId, player);
gparam_0 = func_1(player);
PlayerCameraController.Create(gparam_0.Player);
CameraClass.Instance.SetOcclusionCullingEnabled(Location_0.OcculsionCullingEnabled);
CameraClass.Instance.IsActive = false;

await SpawnLoot(location);
await WaitForPlayersToSpawn();
Expand Down
4 changes: 4 additions & 0 deletions Source/Coop/SITGameModes/ISITGame.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,5 +47,9 @@ public interface ISITGame
//Task WaitForPlayersToSpawn();
//Task WaitForPlayersToBeReady();

GameDateTime GameDateTime { get; set; }

public GameTimerClass GameTimer { get; set; }

}
}
Loading