Skip to content

Commit

Permalink
Handle disconnect and server/client stop
Browse files Browse the repository at this point in the history
  • Loading branch information
toberge committed May 26, 2024
1 parent f9edb4e commit 403e3a7
Show file tree
Hide file tree
Showing 11 changed files with 129 additions and 234 deletions.
2 changes: 1 addition & 1 deletion Assets/Scenes/CraterTown.unity
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ RenderSettings:
m_ReflectionIntensity: 1
m_CustomReflection: {fileID: 0}
m_Sun: {fileID: 662445327}
m_IndirectSpecularColor: {r: 0.062285002, g: 0.21922584, b: 0.4949425, a: 1}
m_IndirectSpecularColor: {r: 0.062542364, g: 0.2194215, b: 0.49499997, a: 1}
m_UseRadianceAmbientProbe: 0
--- !u!157 &3
LightmapSettings:
Expand Down
14 changes: 1 addition & 13 deletions Assets/Scenes/Menu.unity
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ RenderSettings:
m_ReflectionIntensity: 1
m_CustomReflection: {fileID: 0}
m_Sun: {fileID: 785370674}
m_IndirectSpecularColor: {r: 0.062482566, g: 0.21938902, b: 0.4950583, a: 1}
m_IndirectSpecularColor: {r: 0.057661593, g: 0.2159689, b: 0.49404582, a: 1}
m_UseRadianceAmbientProbe: 0
--- !u!157 &3
LightmapSettings:
Expand Down Expand Up @@ -416,18 +416,6 @@ PrefabInstance:
serializedVersion: 3
m_TransformParent: {fileID: 0}
m_Modifications:
- target: {fileID: 3717336014748129540, guid: 0e2ad36662a02c3488301a5286b27635, type: 3}
propertyPath: startingBody
value:
objectReference: {fileID: 11400000, guid: 0abfdcb5f304f2647b378f82907d538c, type: 2}
- target: {fileID: 3717336014748129540, guid: 0e2ad36662a02c3488301a5286b27635, type: 3}
propertyPath: startingBarrel
value:
objectReference: {fileID: 11400000, guid: 9c1da148c8d07ab428c6bc9a70aecae8, type: 2}
- target: {fileID: 3717336014748129540, guid: 0e2ad36662a02c3488301a5286b27635, type: 3}
propertyPath: startingExtension
value:
objectReference: {fileID: 11400000, guid: 2c332edf0b10a07489ea78f82b8f7045, type: 2}
- target: {fileID: 8579357797008554893, guid: 0e2ad36662a02c3488301a5286b27635, type: 3}
propertyPath: m_Name
value: StaticInfo
Expand Down
18 changes: 11 additions & 7 deletions Assets/Scenes/TrainingMode.unity
Original file line number Diff line number Diff line change
Expand Up @@ -565,15 +565,9 @@ MonoBehaviour:
m_Script: {fileID: 11500000, guid: b18a938eb13d13540b14e958b874d1b0, type: 3}
m_Name:
m_EditorClassIdentifier:
playerPrefab: {fileID: 2770875744502568649, guid: 1ccbc17fde8c55a21ac6331f0517f402, type: 3}
spawnPoints:
- {fileID: 1104924655}
playerSelectItemPrefab: {fileID: 0}
aIOpponent: {fileID: 0}
aIBidder: {fileID: 0}
aiIdentity: {fileID: 0}
globalHUDController: {fileID: 0}
overrideMatchManager: 1
--- !u!4 &168459266
Transform:
m_ObjectHideFlags: 0
Expand Down Expand Up @@ -4278,6 +4272,10 @@ PrefabInstance:
propertyPath: m_ConstrainProportionsScale
value: 1
objectReference: {fileID: 0}
- target: {fileID: 508678544827238946, guid: e795d78bc3458864bad12d1dc75182fb, type: 3}
propertyPath: m_Enabled
value: 0
objectReference: {fileID: 0}
- target: {fileID: 1245620792704334073, guid: e795d78bc3458864bad12d1dc75182fb, type: 3}
propertyPath: m_Materials.Array.size
value: 1
Expand All @@ -4294,7 +4292,13 @@ PrefabInstance:
propertyPath: m_Mesh
value:
objectReference: {fileID: 962209921104072034, guid: 96e02cb082c4f82d495b4b45861a50f6, type: 3}
m_RemovedComponents: []
- target: {fileID: 5543259695900803521, guid: e795d78bc3458864bad12d1dc75182fb, type: 3}
propertyPath: m_IsTrigger
value: 1
objectReference: {fileID: 0}
m_RemovedComponents:
- {fileID: 508678544827238946, guid: e795d78bc3458864bad12d1dc75182fb, type: 3}
- {fileID: 3873721530690488933, guid: e795d78bc3458864bad12d1dc75182fb, type: 3}
m_RemovedGameObjects: []
m_AddedGameObjects: []
m_AddedComponents:
Expand Down
42 changes: 24 additions & 18 deletions Assets/Scripts/Control&Input/ItemSelectManager.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,10 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Mirror;
using UnityEngine;

// TODO remove first two structs if unused
internal struct StartTrackingMessage : NetworkMessage
{
}

internal struct ReadyToTrackMessage : NetworkMessage
{
}

internal struct ClientReadyMessage : NetworkMessage
{
}
Expand Down Expand Up @@ -45,27 +37,29 @@ public void StartTrackingMenus()

if (isServer)
{
InitializeServerData();
NetworkServer.RegisterHandler<ClientReadyMessage>(OnClientReady);
NetworkServer.RegisterHandler<ClientNotReadyMessage>(OnClientNotReady);
InitializeServerState();
}
}

private void InitializeServerState()
{
clientReadyByID = Peer2PeerTransport.Connections
.ToDictionary(c => c.connectionId, c => false);
((Peer2PeerTransport)NetworkManager.singleton).OnDisconnect += OnDisconnect;
NetworkServer.RegisterHandler<ClientReadyMessage>(OnClientReady);
NetworkServer.RegisterHandler<ClientNotReadyMessage>(OnClientNotReady);
}

private void OnDestroy()
{
if (isServer)
{
((Peer2PeerTransport)Peer2PeerTransport.singleton).OnDisconnect -= OnDisconnect;
NetworkServer.UnregisterHandler<ClientReadyMessage>();
NetworkServer.UnregisterHandler<ClientNotReadyMessage>();
}
}

private void InitializeServerData()
{
clientReadyByID = Peer2PeerTransport.Connections
.ToDictionary(c => c.connectionId, c => false);
}

[Server]
private void Finish()
{
Expand All @@ -75,6 +69,7 @@ private void Finish()
[ClientRpc]
private void RpcFinish()
{
((Peer2PeerTransport)Peer2PeerTransport.singleton).UpdateLoadout();
StartCoroutine(MatchController.Singleton.WaitAndStartNextRound());
}

Expand Down Expand Up @@ -107,9 +102,20 @@ private void OnClientNotReady(NetworkConnectionToClient connection, ClientNotRea
}
}

private void OnDisconnect(int connectionID)
{
clientReadyByID.Remove(connectionID);
CheckIfAllAreReady();
}

private void OnClientReady(NetworkConnectionToClient connection, ClientReadyMessage message)
{
clientReadyByID[connection.connectionId] = true;
CheckIfAllAreReady();
}

private void CheckIfAllAreReady()
{
var allClientsAreReady = clientReadyByID.Values.All(m => m);
if (allClientsAreReady)
{
Expand Down
3 changes: 1 addition & 2 deletions Assets/Scripts/Control&Input/ItemSelectMenu.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using TMPro;
using SecretName;

public class ItemSelectMenu : MonoBehaviour
Expand Down Expand Up @@ -60,7 +59,7 @@ public class ItemSelectMenu : MonoBehaviour

private AugmentType selectedType = AugmentType.Body;

private ItemSelectSlot selectedSlot => (selectedType) switch
private ItemSelectSlot selectedSlot => selectedType switch
{
AugmentType.Body => bodySlot,
AugmentType.Barrel => barrelSlot,
Expand Down
106 changes: 71 additions & 35 deletions Assets/Scripts/Control&Input/Peer2PeerTransport.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
Expand Down Expand Up @@ -132,33 +131,43 @@ public class Peer2PeerTransport : NetworkManager
/// </summary>
private static List<NetworkConnectionToClient> connections = new();
private static Dictionary<int, List<uint>> playersForConnection = new();
private static List<uint> connectedPlayers = new();
public static ReadOnlyCollection<NetworkConnectionToClient> Connections;

public delegate void LobbyPlayerEvent(PlayerDetails details);
public LobbyPlayerEvent OnPlayerRecieved;

public override void OnStartServer()
{
base.OnStartServer();
NetworkServer.RegisterHandler<PlayerConnectedMessage>(OnSpawnPlayerInput);
NetworkServer.RegisterHandler<UpdateLoadoutMessage>(OnReceiveUpdateLoadout);
public delegate void ConnectionEvent(int connectionID);
public ConnectionEvent OnDisconnect;

// Reinitialize player lookups
private void ResetState()
{
Debug.Log("Reset state");
playerIndex = 0;
players = new();
playerInstances = new();
PlayerInstanceByID = new(playerInstances);
playerIndex = 0;
localPlayerIds = new();

connections = new();
connectedPlayers = new();
playersForConnection = new();
Connections = new(connections);
}

public override void OnStartServer()
{
NetworkServer.RegisterHandler<PlayerConnectedMessage>(OnSpawnPlayerInput);
NetworkServer.RegisterHandler<UpdateLoadoutMessage>(OnReceiveUpdateLoadout);

ResetState();
}

#region Player joining

public override void OnClientConnect()
{
base.OnClientConnect();

NetworkClient.RegisterHandler<StartMatchMessage>(OnStartMatch);
NetworkClient.RegisterHandler<InitialPlayerDetailsMessage>(OnReceivePlayerDetails);
NetworkClient.RegisterHandler<InitializePlayerMessage>(InitializeFPSPlayer);
Expand All @@ -168,30 +177,48 @@ public override void OnClientConnect()
// TODO doesn't work if players haven't pressed a key yet
PlayerInputManagerController.Singleton.JoinAllInputs();

players = new();
playerInstances = new();
PlayerInstanceByID = new(playerInstances);
playerIndex = 0;
ResetState();
}

// TODO OnClientDisconnect and the like must be implemented!!!
// - OnServerDisconnect seems to be the one that runs on the server when a client disconnects

//public override void OnServerDisconnect(NetworkConnectionToClient conn)
//{
// base.OnServerDisconnect(conn);
// throw new NotImplementedException();
//}
//public override void OnClientDisconnect()
//{
// base.OnClientDisconnect();
// throw new NotImplementedException();
//}
//// TODO should this be different?
//public override void OnStopClient()
//{
// base.OnStopClient();
// throw new NotImplementedException();
//}
public override void OnServerDisconnect(NetworkConnectionToClient connection)
{
if (!playersForConnection.ContainsKey(connection.connectionId))
return;
Debug.Log($"Removed connection {connections.IndexOf(connection)} which has players {playersForConnection[connection.connectionId].ToCommaSeparatedString()}");
connections.Remove(connection);
connectedPlayers.RemoveAll(id => playersForConnection[connection.connectionId].Contains(id));
playersForConnection.Remove(connection.connectionId);
// TODO send msg to ItemSelectManager that this connection is invalid
OnDisconnect?.Invoke(connection.connectionId);
}

public override void OnStopServer()
{
Debug.Log("Stopped server");
ResetState();
}

public override void OnStopClient()
{
Debug.Log("Stopped client");
ResetState();
}

public override void OnClientDisconnect()
{
Debug.Log("Disconnected as client");
LoadingScreen.Singleton.Hide();
MusicTrackManager.Singleton.SwitchTo(MusicType.Menu);
PlayerInputManagerController.Singleton.ChangeInputMaps("Menu");
SceneManager.LoadSceneAsync(Scenes.Menu);
if (NetworkClient.active)
StopClient();
else
ResetState();
}

public void JoinLobby(string address = "127.0.0.1")
{
Expand Down Expand Up @@ -266,7 +293,10 @@ private void OnSpawnPlayerInput(NetworkConnectionToClient connection, PlayerConn
// Register connection
PlayerInputManagerController.Singleton.NetworkClients.Add(connection);
if (!connections.Contains(connection))
{
connections.Add(connection);
connectedPlayers.Add((uint)playerIndex);
}
if (!playersForConnection.ContainsKey(connection.connectionId))
playersForConnection[connection.connectionId] = new();
playersForConnection[connection.connectionId].Add((uint)playerIndex);
Expand Down Expand Up @@ -412,7 +442,6 @@ public override void OnServerChangeScene(string newSceneName)
AddAiPlayers();
}


switch (newSceneName)
{
case Scenes.Bidding:
Expand All @@ -427,12 +456,9 @@ public override void OnServerChangeScene(string newSceneName)
NetworkServer.ReplaceHandler<SpawnPlayerMessage>(OnSpawnFPSPlayer);
break;
}

base.OnServerChangeScene(newSceneName);
}

// TODO move to ItemSelectManager (?)
private void UpdateLoadout()
public void UpdateLoadout()
{
Debug.Log($"Found {FindObjectsByType<PlayerIdentity>(FindObjectsInactive.Exclude, FindObjectsSortMode.None).Count()} identitites!");
foreach (var identity in FindObjectsByType<PlayerIdentity>(FindObjectsInactive.Exclude, FindObjectsSortMode.None))
Expand Down Expand Up @@ -469,7 +495,6 @@ private void OnReceiveUpdateLoadout(NetworkConnectionToClient connection, Update

public override void OnClientChangeScene(string newSceneName, SceneOperation sceneOperation, bool customHandling)
{
UpdateLoadout();
var originalSceneName = SceneManager.GetActiveScene().name;
switch (newSceneName)
{
Expand Down Expand Up @@ -502,10 +527,21 @@ private IEnumerator SendSpawnRequestsAfterSceneLoad(string originalSceneName)
{
NetworkClient.Send(new SpawnPlayerMessage(id, PlayerType.Local));
}

if (!NetworkServer.active)
yield break;

// TODO rework this for dedicated server stuff
// (where it needs to do this on server change scene, and without a network client)
// (perhaps you could call the spawn methods directly?)
foreach (var p in players.Values.Where(p => p.type == PlayerType.AI))
{
NetworkClient.Send(new SpawnPlayerMessage(p.id, PlayerType.AI));
}
foreach (var id in players.Keys.Where(id => !connectedPlayers.Contains(id)))
{
NetworkClient.Send(new SpawnPlayerMessage(id, PlayerType.Local));
}
}

#endregion
Expand Down
5 changes: 2 additions & 3 deletions Assets/Scripts/Control&Input/ReturnToMainMenuGate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,9 @@ public void Interact(PlayerManager player)
ReturnToMainMenu();
}

private void OnCollisionEnter(Collision collision)
private void OnTriggerEnter(Collider other)
{
var contact = collision.GetContact(0);
if (contact.otherCollider.TryGetComponent<PlayerManager>(out var _))
if (other.TryGetComponent<PlayerManager>(out var _))
ReturnToMainMenu();
}

Expand Down
Loading

0 comments on commit 403e3a7

Please sign in to comment.