-
Notifications
You must be signed in to change notification settings - Fork 0
/
ServerCharSelectState.cs
298 lines (262 loc) · 11.9 KB
/
ServerCharSelectState.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
using System;
using System.Collections;
using Unity.BossRoom.ConnectionManagement;
using Unity.BossRoom.Gameplay.GameplayObjects;
using Unity.BossRoom.Infrastructure;
using Unity.Multiplayer.Samples.BossRoom;
using Unity.Multiplayer.Samples.Utilities;
using Unity.Netcode;
using UnityEngine;
using VContainer;
namespace Unity.BossRoom.Gameplay.GameState
{
/// <summary>
/// Server specialization of Character Select game state.
/// </summary>
[RequireComponent(typeof(NetcodeHooks), typeof(NetworkCharSelection))]
public class ServerCharSelectState : GameStateBehaviour
{
[SerializeField]
NetcodeHooks m_NetcodeHooks;
public override GameState ActiveState => GameState.CharSelect;
public NetworkCharSelection networkCharSelection { get; private set; }
Coroutine m_WaitToEndLobbyCoroutine;
[Inject]
ConnectionManager m_ConnectionManager;
protected override void Awake()
{
base.Awake();
networkCharSelection = GetComponent<NetworkCharSelection>();
m_NetcodeHooks.OnNetworkSpawnHook += OnNetworkSpawn;
m_NetcodeHooks.OnNetworkDespawnHook += OnNetworkDespawn;
}
protected override void OnDestroy()
{
base.OnDestroy();
if (m_NetcodeHooks)
{
m_NetcodeHooks.OnNetworkSpawnHook -= OnNetworkSpawn;
m_NetcodeHooks.OnNetworkDespawnHook -= OnNetworkDespawn;
}
}
void OnClientChangedSeat(ulong clientId, int newSeatIdx, bool lockedIn)
{
int idx = FindLobbyPlayerIdx(clientId);
if (idx == -1)
{
throw new Exception($"OnClientChangedSeat: client ID {clientId} is not a lobby player and cannot change seats! Shouldn't be here!");
}
if (networkCharSelection.IsLobbyClosed.Value)
{
// The user tried to change their class after everything was locked in... too late! Discard this choice
return;
}
if (newSeatIdx == -1)
{
// we can't lock in with no seat
lockedIn = false;
}
else
{
// see if someone has already locked-in that seat! If so, too late... discard this choice
foreach (NetworkCharSelection.LobbyPlayerState playerInfo in networkCharSelection.LobbyPlayers)
{
if (playerInfo.ClientId != clientId && playerInfo.SeatIdx == newSeatIdx && playerInfo.SeatState == NetworkCharSelection.SeatState.LockedIn)
{
// somebody already locked this choice in. Stop!
// Instead of granting lock request, change this player to Inactive state.
networkCharSelection.LobbyPlayers[idx] = new NetworkCharSelection.LobbyPlayerState(clientId,
networkCharSelection.LobbyPlayers[idx].PlayerName,
networkCharSelection.LobbyPlayers[idx].PlayerNumber,
NetworkCharSelection.SeatState.Inactive);
// then early out
return;
}
}
}
networkCharSelection.LobbyPlayers[idx] = new NetworkCharSelection.LobbyPlayerState(clientId,
networkCharSelection.LobbyPlayers[idx].PlayerName,
networkCharSelection.LobbyPlayers[idx].PlayerNumber,
lockedIn ? NetworkCharSelection.SeatState.LockedIn : NetworkCharSelection.SeatState.Active,
newSeatIdx,
Time.time);
if (lockedIn)
{
// to help the clients visually keep track of who's in what seat, we'll "kick out" any other players
// who were also in that seat. (Those players didn't click "Ready!" fast enough, somebody else took their seat!)
for (int i = 0; i < networkCharSelection.LobbyPlayers.Count; ++i)
{
if (networkCharSelection.LobbyPlayers[i].SeatIdx == newSeatIdx && i != idx)
{
// change this player to Inactive state.
networkCharSelection.LobbyPlayers[i] = new NetworkCharSelection.LobbyPlayerState(
networkCharSelection.LobbyPlayers[i].ClientId,
networkCharSelection.LobbyPlayers[i].PlayerName,
networkCharSelection.LobbyPlayers[i].PlayerNumber,
NetworkCharSelection.SeatState.Inactive);
}
}
}
CloseLobbyIfReady();
}
/// <summary>
/// Returns the index of a client in the master LobbyPlayer list, or -1 if not found
/// </summary>
int FindLobbyPlayerIdx(ulong clientId)
{
for (int i = 0; i < networkCharSelection.LobbyPlayers.Count; ++i)
{
if (networkCharSelection.LobbyPlayers[i].ClientId == clientId)
return i;
}
return -1;
}
/// <summary>
/// Looks through all our connections and sees if everyone has locked in their choice;
/// if so, we lock in the whole lobby, save state, and begin the transition to gameplay
/// </summary>
void CloseLobbyIfReady()
{
foreach (NetworkCharSelection.LobbyPlayerState playerInfo in networkCharSelection.LobbyPlayers)
{
if (playerInfo.SeatState != NetworkCharSelection.SeatState.LockedIn)
return; // nope, at least one player isn't locked in yet!
}
// everybody's ready at the same time! Lock it down!
networkCharSelection.IsLobbyClosed.Value = true;
// remember our choices so the next scene can use the info
SaveLobbyResults();
// Delay a few seconds to give the UI time to react, then switch scenes
m_WaitToEndLobbyCoroutine = StartCoroutine(WaitToEndLobby());
}
/// <summary>
/// Cancels the process of closing the lobby, so that if a new player joins, they are able to chose a character.
/// </summary>
void CancelCloseLobby()
{
if (m_WaitToEndLobbyCoroutine != null)
{
StopCoroutine(m_WaitToEndLobbyCoroutine);
}
networkCharSelection.IsLobbyClosed.Value = false;
}
void SaveLobbyResults()
{
foreach (NetworkCharSelection.LobbyPlayerState playerInfo in networkCharSelection.LobbyPlayers)
{
var playerNetworkObject = NetworkManager.Singleton.SpawnManager.GetPlayerNetworkObject(playerInfo.ClientId);
if (playerNetworkObject && playerNetworkObject.TryGetComponent(out PersistentPlayer persistentPlayer))
{
// pass avatar GUID to PersistentPlayer
// it'd be great to simplify this with something like a NetworkScriptableObjects :(
persistentPlayer.NetworkAvatarGuidState.AvatarGuid.Value =
networkCharSelection.AvatarConfiguration[playerInfo.SeatIdx].Guid.ToNetworkGuid();
}
}
}
IEnumerator WaitToEndLobby()
{
yield return new WaitForSeconds(3);
SceneLoaderWrapper.Instance.LoadScene("BossRoom", useNetworkSceneManager: true);
}
public void OnNetworkDespawn()
{
if (NetworkManager.Singleton)
{
NetworkManager.Singleton.OnClientDisconnectCallback -= OnClientDisconnectCallback;
NetworkManager.Singleton.SceneManager.OnSceneEvent -= OnSceneEvent;
}
if (networkCharSelection)
{
networkCharSelection.OnClientChangedSeat -= OnClientChangedSeat;
}
}
public void OnNetworkSpawn()
{
if (!NetworkManager.Singleton.IsServer)
{
enabled = false;
}
else
{
NetworkManager.Singleton.OnClientDisconnectCallback += OnClientDisconnectCallback;
networkCharSelection.OnClientChangedSeat += OnClientChangedSeat;
NetworkManager.Singleton.SceneManager.OnSceneEvent += OnSceneEvent;
}
}
void OnSceneEvent(SceneEvent sceneEvent)
{
// We need to filter out the event that are not a client has finished loading the scene
if (sceneEvent.SceneEventType != SceneEventType.LoadComplete) return;
// When the client finishes loading the Lobby Map, we will need to Seat it
SeatNewPlayer(sceneEvent.ClientId);
}
int GetAvailablePlayerNumber()
{
for (int possiblePlayerNumber = 0; possiblePlayerNumber < m_ConnectionManager.MaxConnectedPlayers; ++possiblePlayerNumber)
{
if (IsPlayerNumberAvailable(possiblePlayerNumber))
{
return possiblePlayerNumber;
}
}
// we couldn't get a Player# for this person... which means the lobby is full!
return -1;
}
bool IsPlayerNumberAvailable(int playerNumber)
{
bool found = false;
foreach (NetworkCharSelection.LobbyPlayerState playerState in networkCharSelection.LobbyPlayers)
{
if (playerState.PlayerNumber == playerNumber)
{
found = true;
break;
}
}
return !found;
}
void SeatNewPlayer(ulong clientId)
{
// If lobby is closing and waiting to start the game, cancel to allow that new player to select a character
if (networkCharSelection.IsLobbyClosed.Value)
{
CancelCloseLobby();
}
SessionPlayerData? sessionPlayerData = SessionManager<SessionPlayerData>.Instance.GetPlayerData(clientId);
if (sessionPlayerData.HasValue)
{
var playerData = sessionPlayerData.Value;
if (playerData.PlayerNumber == -1 || !IsPlayerNumberAvailable(playerData.PlayerNumber))
{
// If no player num already assigned or if player num is no longer available, get an available one.
playerData.PlayerNumber = GetAvailablePlayerNumber();
}
if (playerData.PlayerNumber == -1)
{
// Sanity check. We ran out of seats... there was no room!
throw new Exception($"we shouldn't be here, connection approval should have refused this connection already for client ID {clientId} and player num {playerData.PlayerNumber}");
}
networkCharSelection.LobbyPlayers.Add(new NetworkCharSelection.LobbyPlayerState(clientId, playerData.PlayerName, playerData.PlayerNumber, NetworkCharSelection.SeatState.Inactive));
SessionManager<SessionPlayerData>.Instance.SetPlayerData(clientId, playerData);
}
}
void OnClientDisconnectCallback(ulong clientId)
{
// clear this client's PlayerNumber and any associated visuals (so other players know they're gone).
for (int i = 0; i < networkCharSelection.LobbyPlayers.Count; ++i)
{
if (networkCharSelection.LobbyPlayers[i].ClientId == clientId)
{
networkCharSelection.LobbyPlayers.RemoveAt(i);
break;
}
}
if (!networkCharSelection.IsLobbyClosed.Value)
{
// If the lobby is not already closing, close if the remaining players are all ready
CloseLobbyIfReady();
}
}
}
}