Skip to content

Commit

Permalink
Refactor JoinServerBackend
Browse files Browse the repository at this point in the history
  • Loading branch information
Jannify committed Mar 15, 2024
1 parent 9e76e0b commit cfbe84c
Show file tree
Hide file tree
Showing 7 changed files with 88 additions and 108 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Collections;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using NitroxClient.Communication.Abstract;
using NitroxClient.Communication.Exceptions;
Expand All @@ -14,86 +15,18 @@

namespace NitroxClient.MonoBehaviours.Gui.MainMenu.ServerJoin;

public class JoinServerBackend : MonoBehaviour
public static class JoinServerBackend
{
private static JoinServerBackend instance;
private static PlayerPreferenceManager preferencesManager;
private static PlayerPreference activePlayerPreference;
private static IMultiplayerSession multiplayerSession;

public static JoinServerBackend Instance
{
get
{
if (!instance)
{
GameObject persistentGameobject = GameObject.Find("Nitrox");
instance = persistentGameobject.EnsureComponent<JoinServerBackend>();
}
return instance;
}
}

private PlayerPreferenceManager preferencesManager;
private PlayerPreference activePlayerPreference;
private IMultiplayerSession multiplayerSession;
private static GameObject multiplayerClient;

private string serverIp;
private int serverPort;
private static string serverIp;
private static int serverPort;

public async Task ShowAsync(string ip, int port)
{
serverIp = ip;
serverPort = port;
NitroxServiceLocator.BeginNewLifetimeScope();

preferencesManager = NitroxServiceLocator.LocateService<PlayerPreferenceManager>();
activePlayerPreference = preferencesManager.GetPreference(serverIp);

multiplayerSession = NitroxServiceLocator.LocateService<IMultiplayerSession>();

gameObject.SetActive(true);
await StartMultiplayerClientAsync();
}

private GameObject multiplayerClient;

private async Task StartMultiplayerClientAsync()
{
if (!multiplayerClient)
{
multiplayerClient = new GameObject("Multiplayer Client");
multiplayerClient.AddComponent<Multiplayer>();
multiplayerSession.ConnectionStateChanged += SessionConnectionStateChangedHandler;
}

try
{
await multiplayerSession.ConnectAsync(serverIp, serverPort);
}
catch (ClientConnectionFailedException ex)
{
Log.ErrorSensitive("Unable to contact the remote server at: {ip}:{port}", serverIp, serverPort);
string msg = $"{Language.main.Get("Nitrox_UnableToConnect")} {serverIp}:{serverPort}";

if (serverIp.Equals("127.0.0.1"))
{
if (Process.GetProcessesByName("NitroxServer-Subnautica").Length == 0)
{
Log.Error("No server process was found while address was 127.0.0.1");
msg += $"\n{Language.main.Get("Nitrox_StartServer")}";
}
else
{
Log.Error(ex);
msg += $"\n{Language.main.Get("Nitrox_FirewallInterfering")}";
}
}

Log.InGame(msg);
StopMultiplayerClient(msg);
MainMenuNotificationPanel.ShowMessage(msg, MainMenuServerListPanel.NAME);
}
}

public void RequestSessionReservation(string playerName, Color playerColor)
public static void RequestSessionReservation(string playerName, Color playerColor)
{
preferencesManager.SetPreference(serverIp, new PlayerPreference(playerName, playerColor));

Expand All @@ -103,7 +36,7 @@ public void RequestSessionReservation(string playerName, Color playerColor)
multiplayerSession.RequestSessionReservation(new PlayerSettings(playerColor.ToDto()), authenticationContext);
}

private void SessionConnectionStateChangedHandler(IMultiplayerSessionConnectionState state)
private static void SessionConnectionStateChangedHandler(IMultiplayerSessionConnectionState state)
{
switch (state.CurrentStage)
{
Expand Down Expand Up @@ -140,7 +73,7 @@ private void SessionConnectionStateChangedHandler(IMultiplayerSessionConnectionS
Multiplayer.SubnauticaLoadingStarted();
IEnumerator startNewGame = uGUI_MainMenu.main.StartNewGame(GameMode.Survival);
#pragma warning restore CS0618 // God damn it UWE...
StartCoroutine(startNewGame);
UWE.CoroutineHost.StartCoroutine(startNewGame);
LoadingScreenVersionText.Initialize();

break;
Expand All @@ -167,26 +100,71 @@ private void SessionConnectionStateChangedHandler(IMultiplayerSessionConnectionS
}
}

// TODO: Maybe move to MainMenuServerListPanel OnEnabled
/// <param name="error"> If set to something it will display the message with <see cref="MainMenuNotificationPanel"/> after stopping the client</param>
public void StopMultiplayerClient(string error = null)
[SuppressMessage("Usage", "DIMA001:Dependency Injection container is used directly")]
public static async Task StartMultiplayerClientAsync(string ip, int port)
{
if (!multiplayerClient || !Multiplayer.Main)
serverIp = ip;
serverPort = port;
NitroxServiceLocator.BeginNewLifetimeScope();

preferencesManager = NitroxServiceLocator.LocateService<PlayerPreferenceManager>();
activePlayerPreference = preferencesManager.GetPreference(serverIp);
multiplayerSession = NitroxServiceLocator.LocateService<IMultiplayerSession>();

if (!multiplayerClient)
{
return;
multiplayerClient = new GameObject("Nitrox Multiplayer Client");
multiplayerClient.AddComponent<Multiplayer>();
multiplayerSession.ConnectionStateChanged += SessionConnectionStateChangedHandler;
}

Multiplayer.Main.StopCurrentSession();
Destroy(multiplayerClient);
multiplayerClient = null;
if (multiplayerSession != null)
try
{
await multiplayerSession.ConnectAsync(serverIp, serverPort);
}
catch (ClientConnectionFailedException ex)
{
Log.ErrorSensitive("Unable to contact the remote server at: {ip}:{port}", serverIp, serverPort);
string msg = $"{Language.main.Get("Nitrox_UnableToConnect")} {serverIp}:{serverPort}";

if (serverIp.Equals("127.0.0.1"))
{
if (Process.GetProcessesByName("NitroxServer-Subnautica").Length == 0)
{
Log.Error("No server process was found while address was 127.0.0.1");
msg += $"\n{Language.main.Get("Nitrox_StartServer")}";
}
else
{
Log.Error(ex);
msg += $"\n{Language.main.Get("Nitrox_FirewallInterfering")}";
}
}

Log.InGame(msg);
StopMultiplayerClient();
MainMenuNotificationPanel.ShowMessage(msg, MainMenuServerListPanel.NAME);
}
}

[SuppressMessage("Usage", "DIMA001:Dependency Injection container is used directly")]
public static void StopMultiplayerClient()
{
if (!multiplayerClient || !Multiplayer.Main)
{
multiplayerSession.ConnectionStateChanged -= SessionConnectionStateChangedHandler;
return;
}

if (error != null)
if (multiplayerSession.CurrentState.CurrentStage != MultiplayerSessionConnectionStage.DISCONNECTED)
{
MainMenuNotificationPanel.ShowMessage($"Connection broke\n+{error}", MainMenuServerListPanel.NAME);
multiplayerSession.Disconnect();
}
multiplayerSession.ConnectionStateChanged -= SessionConnectionStateChangedHandler;

Multiplayer.Main.StopCurrentSession();
NitroxServiceLocator.EndCurrentLifetimeScope(); //Always do this last.

Object.Destroy(multiplayerClient);
multiplayerClient = null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ private void OnConfirmButtonClicked()

private static void OnCancelClick()
{
JoinServerBackend.Instance.StopMultiplayerClient();
JoinServerBackend.StopMultiplayerClient();
MainMenuRightSide.main.OpenGroup(MainMenuServerListPanel.NAME);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,12 +109,12 @@ private void OnJoinClick()
return;
}

JoinServerBackend.Instance.RequestSessionReservation(playerName, colorPicker.currentColor);
JoinServerBackend.RequestSessionReservation(playerName, colorPicker.currentColor);
}

private static void OnCancelClick()
{
JoinServerBackend.Instance.StopMultiplayerClient();
JoinServerBackend.StopMultiplayerClient();
MainMenuRightSide.main.OpenGroup(MainMenuServerListPanel.NAME);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Linq;
using FMODUnity;
using NitroxClient.Unity.Helper;
Expand Down Expand Up @@ -132,7 +132,7 @@ public void OnConfirm()
{
if (selectedItem.TryGetComponentInChildren(out TMP_InputField inputField))
{
inputField.Select();
inputField.ActivateInputField();
}

if (selectedItem.TryGetComponentInChildren(out Button button))
Expand Down Expand Up @@ -172,6 +172,11 @@ public void SelectItem(object item)
selectedItem.transform.GetChild(0).GetComponent<Image>().sprite = MainMenuServerListPanel.SelectedSprite;
}

if (!EventSystem.current.alreadySelecting)
{
EventSystem.current.SetSelectedGameObject(selectedItem);
}

selectedItem.GetComponentsInChildren<TextMeshProUGUI>().ForEach(txt => txt.color = Color.black);
RuntimeManager.PlayOneShot(MainMenuServerListPanel.HoverSound.path);
}
Expand All @@ -185,14 +190,19 @@ public void DeselectItem()

if (selectedItem.TryGetComponent(out TMP_InputField selectedInputField))
{
selectedInputField.DeactivateInputField();
selectedInputField.ReleaseSelection();
EventSystem.current.SetSelectedGameObject(null);
}
else
{
selectedItem.transform.GetChild(0).GetComponent<Image>().sprite = MainMenuServerListPanel.NormalSprite;
}

if (!EventSystem.current.alreadySelecting)
{
EventSystem.current.SetSelectedGameObject(null);
}

selectedItem.GetComponentsInChildren<TextMeshProUGUI>().ForEach(txt => txt.color = Color.white);
selectedItem = null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ public static async System.Threading.Tasks.Task OpenJoinServerMenuAsync(string s
}

MainMenuNotificationPanel.ShowLoading();
await JoinServerBackend.Instance.ShowAsync(endpoint.Address.ToString(), endpoint.Port);
await JoinServerBackend.StartMultiplayerClientAsync(endpoint.Address.ToString(), endpoint.Port);
}

private static IPEndPoint ResolveIPEndPoint(string serverIp, int serverPort)
Expand Down
12 changes: 2 additions & 10 deletions NitroxClient/MonoBehaviours/Multiplayer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
using NitroxClient.GameLogic.PlayerLogic.PlayerModel.ColorSwap;
using NitroxClient.MonoBehaviours.Discord;
using NitroxClient.MonoBehaviours.Gui.MainMenu;
using NitroxClient.MonoBehaviours.Gui.MainMenu.ServerJoin;
using NitroxModel.Core;
using NitroxModel.Packets;
using NitroxModel.Packets.Processors.Abstract;
Expand Down Expand Up @@ -172,16 +173,7 @@ public void InitMonoBehaviours()
public void StopCurrentSession()
{
SceneManager.sceneLoaded -= SceneManager_sceneLoaded;

if (multiplayerSession.CurrentState.CurrentStage != MultiplayerSessionConnectionStage.DISCONNECTED)
{
multiplayerSession.Disconnect();
}

OnAfterMultiplayerEnd?.Invoke();

//Always do this last.
NitroxServiceLocator.EndCurrentLifetimeScope();
}

private static void SetLoadingComplete()
Expand Down Expand Up @@ -222,7 +214,7 @@ private void SceneManager_sceneLoaded(Scene scene, LoadSceneMode loadMode)
{
// If we just disconnected from a multiplayer session, then we need to kill the connection here.
// Maybe a better place for this, but here works in a pinch.
StopCurrentSession();
JoinServerBackend.StopMultiplayerClient();
SceneCleaner.Open();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public static void Prefix(string target)
// Stopping the client if we leave the joining process
if (target is not (MainMenuJoinServerPanel.NAME or MainMenuEnterPasswordPanel.NAME or MainMenuNotificationPanel.NAME))
{
JoinServerBackend.Instance.StopMultiplayerClient();
JoinServerBackend.StopMultiplayerClient();
}
}
}

0 comments on commit cfbe84c

Please sign in to comment.