Refactor lobby status (#10550)

This commit is contained in:
wrexbe
2022-08-14 12:54:49 -07:00
committed by GitHub
parent c535214aa2
commit c4d135e253
15 changed files with 126 additions and 108 deletions

View File

@@ -37,7 +37,7 @@ namespace Content.Client.GameTicking.Managers
[ViewVariables] public TimeSpan StartTime { get; private set; } [ViewVariables] public TimeSpan StartTime { get; private set; }
[ViewVariables] public TimeSpan RoundStartTimeSpan { get; private set; } [ViewVariables] public TimeSpan RoundStartTimeSpan { get; private set; }
[ViewVariables] public new bool Paused { get; private set; } [ViewVariables] public new bool Paused { get; private set; }
[ViewVariables] public Dictionary<NetUserId, LobbyPlayerStatus> Status { get; private set; } = new();
[ViewVariables] public IReadOnlyDictionary<EntityUid, Dictionary<string, uint?>> JobsAvailable => _jobsAvailable; [ViewVariables] public IReadOnlyDictionary<EntityUid, Dictionary<string, uint?>> JobsAvailable => _jobsAvailable;
[ViewVariables] public IReadOnlyDictionary<EntityUid, string> StationNames => _stationNames; [ViewVariables] public IReadOnlyDictionary<EntityUid, string> StationNames => _stationNames;
@@ -66,7 +66,6 @@ namespace Content.Client.GameTicking.Managers
SubscribeNetworkEvent<TickerJobsAvailableEvent>(UpdateJobsAvailable); SubscribeNetworkEvent<TickerJobsAvailableEvent>(UpdateJobsAvailable);
SubscribeNetworkEvent<RoundRestartCleanupEvent>(RoundRestartCleanup); SubscribeNetworkEvent<RoundRestartCleanupEvent>(RoundRestartCleanup);
Status = new Dictionary<NetUserId, LobbyPlayerStatus>();
_initialized = true; _initialized = true;
} }
@@ -97,8 +96,6 @@ namespace Content.Client.GameTicking.Managers
LobbySong = message.LobbySong; LobbySong = message.LobbySong;
LobbyBackground = message.LobbyBackground; LobbyBackground = message.LobbyBackground;
Paused = message.Paused; Paused = message.Paused;
if (IsGameStarted)
Status.Clear();
LobbyStatusUpdated?.Invoke(); LobbyStatusUpdated?.Invoke();
} }
@@ -123,11 +120,6 @@ namespace Content.Client.GameTicking.Managers
private void LobbyReady(TickerLobbyReadyEvent message) private void LobbyReady(TickerLobbyReadyEvent message)
{ {
// Merge the Dictionaries
foreach (var p in message.Status)
{
Status[p.Key] = p.Value;
}
LobbyReadyUpdated?.Invoke(); LobbyReadyUpdated?.Invoke();
} }

View File

@@ -109,7 +109,6 @@ namespace Content.Client.Lobby
_lobby.OptionsButton.OnPressed += _ => new OptionsMenu().Open(); _lobby.OptionsButton.OnPressed += _ => new OptionsMenu().Open();
_playerManager.PlayerListUpdated += PlayerManagerOnPlayerListUpdated;
_gameTicker.InfoBlobUpdated += UpdateLobbyUi; _gameTicker.InfoBlobUpdated += UpdateLobbyUi;
_gameTicker.LobbyStatusUpdated += LobbyStatusUpdated; _gameTicker.LobbyStatusUpdated += LobbyStatusUpdated;
_gameTicker.LobbyLateJoinStatusUpdated += LobbyLateJoinStatusUpdated; _gameTicker.LobbyLateJoinStatusUpdated += LobbyLateJoinStatusUpdated;
@@ -117,7 +116,6 @@ namespace Content.Client.Lobby
public override void Shutdown() public override void Shutdown()
{ {
_playerManager.PlayerListUpdated -= PlayerManagerOnPlayerListUpdated;
_gameTicker.InfoBlobUpdated -= UpdateLobbyUi; _gameTicker.InfoBlobUpdated -= UpdateLobbyUi;
_gameTicker.LobbyStatusUpdated -= LobbyStatusUpdated; _gameTicker.LobbyStatusUpdated -= LobbyStatusUpdated;
_gameTicker.LobbyLateJoinStatusUpdated -= LobbyLateJoinStatusUpdated; _gameTicker.LobbyLateJoinStatusUpdated -= LobbyLateJoinStatusUpdated;
@@ -164,23 +162,6 @@ namespace Content.Client.Lobby
_lobby.StartTime.Text = Loc.GetString("lobby-state-round-start-countdown-text", ("timeLeft", text)); _lobby.StartTime.Text = Loc.GetString("lobby-state-round-start-countdown-text", ("timeLeft", text));
} }
private void PlayerManagerOnPlayerListUpdated(object? sender, EventArgs e)
{
var gameTicker = EntitySystem.Get<ClientGameTicker>();
// Remove disconnected sessions from the Ready Dict
foreach (var p in gameTicker.Status)
{
if (!_playerManager.SessionsDict.TryGetValue(p.Key, out _))
{
// This is a shitty fix. Observers can rejoin because they are already in the game.
// So we don't delete them, but keep them if they decide to rejoin
if (p.Value != LobbyPlayerStatus.Observer)
gameTicker.Status.Remove(p.Key);
}
}
}
private void LobbyStatusUpdated() private void LobbyStatusUpdated()
{ {
UpdateLobbyBackground(); UpdateLobbyBackground();

View File

@@ -29,11 +29,7 @@ namespace Content.Server.Administration.Commands
return; return;
} }
foreach (var (player, status) in gameTicker.PlayersInLobby) gameTicker.ToggleReadyAll(ready);
{
if(status != LobbyPlayerStatus.Observer)
gameTicker.ToggleReady(player, ready);
}
} }
} }
} }

View File

@@ -4,6 +4,7 @@ using Content.Server.Database;
using Content.Server.GameTicking; using Content.Server.GameTicking;
using Content.Server.Preferences.Managers; using Content.Server.Preferences.Managers;
using Content.Shared.CCVar; using Content.Shared.CCVar;
using Content.Shared.GameTicking;
using Robust.Server.Player; using Robust.Server.Player;
using Robust.Shared.Configuration; using Robust.Shared.Configuration;
using Robust.Shared.Network; using Robust.Shared.Network;
@@ -114,7 +115,9 @@ The ban reason is: ""{ban.Reason}""
} }
} }
var wasInGame = EntitySystem.TryGet<GameTicker>(out var ticker) && ticker.PlayersInGame.Contains(userId); var wasInGame = EntitySystem.TryGet<GameTicker>(out var ticker) &&
ticker.PlayerGameStatuses.TryGetValue(userId, out var status) &&
status == PlayerGameStatus.JoinedGame;
if ((_plyMgr.PlayerCount >= _cfg.GetCVar(CCVars.SoftMaxPlayers) && adminData is null) && !wasInGame) if ((_plyMgr.PlayerCount >= _cfg.GetCVar(CCVars.SoftMaxPlayers) && adminData is null) && !wasInGame)
{ {
return (ConnectionDenyReason.Full, Loc.GetString("soft-player-cap-full"), null); return (ConnectionDenyReason.Full, Loc.GetString("soft-player-cap-full"), null);

View File

@@ -40,7 +40,7 @@ namespace Content.Server.GameTicking.Commands
var stationSystem = EntitySystem.Get<StationSystem>(); var stationSystem = EntitySystem.Get<StationSystem>();
var stationJobs = EntitySystem.Get<StationJobsSystem>(); var stationJobs = EntitySystem.Get<StationJobsSystem>();
if (!ticker.PlayersInLobby.ContainsKey(player) || ticker.PlayersInLobby[player] == LobbyPlayerStatus.Observer) if (ticker.PlayerGameStatuses.TryGetValue(player.UserId, out var status) && status == PlayerGameStatus.JoinedGame)
{ {
Logger.InfoS("security", $"{player.Name} ({player.UserId}) attempted to latejoin while in-game."); Logger.InfoS("security", $"{player.Name} ({player.UserId}) attempted to latejoin while in-game.");
shell.WriteError($"{player.Name} is not in the lobby. This incident will be reported."); shell.WriteError($"{player.Name} is not in the lobby. This incident will be reported.");

View File

@@ -1,4 +1,5 @@
using Content.Shared.Administration; using Content.Shared.Administration;
using Content.Shared.GameTicking;
using Robust.Server.Player; using Robust.Server.Player;
using Robust.Shared.Console; using Robust.Shared.Console;
@@ -26,10 +27,15 @@ namespace Content.Server.GameTicking.Commands
return; return;
} }
if (ticker.PlayersInLobby.ContainsKey(player)) if (ticker.PlayerGameStatuses.TryGetValue(player.UserId, out var status) &&
status != PlayerGameStatus.JoinedGame)
{
ticker.MakeObserve(player); ticker.MakeObserve(player);
}
else else
{
shell.WriteError($"{player.Name} is not in the lobby. This incident will be reported."); shell.WriteError($"{player.Name} is not in the lobby. This incident will be reported.");
}
} }
} }
} }

View File

@@ -1,11 +1,12 @@
using Content.Shared.CCVar; using Content.Shared.CCVar;
using Content.Shared.GameTicking;
namespace Content.Server.GameTicking namespace Content.Server.GameTicking
{ {
public sealed partial class GameTicker public sealed partial class GameTicker
{ {
[ViewVariables] [ViewVariables]
public bool LobbyEnabled { get; private set; } = false; public bool LobbyEnabled { get; private set; }
[ViewVariables] [ViewVariables]
public bool DummyTicker { get; private set; } = false; public bool DummyTicker { get; private set; } = false;
@@ -32,7 +33,17 @@ namespace Content.Server.GameTicking
private void InitializeCVars() private void InitializeCVars()
{ {
_configurationManager.OnValueChanged(CCVars.GameLobbyEnabled, value => LobbyEnabled = value, true); _configurationManager.OnValueChanged(CCVars.GameLobbyEnabled, value =>
{
LobbyEnabled = value;
foreach (var (userId, status) in _playerGameStatuses)
{
if (status == PlayerGameStatus.JoinedGame)
continue;
_playerGameStatuses[userId] =
LobbyEnabled ? PlayerGameStatus.NotReadyToPlay : PlayerGameStatus.ReadyToPlay;
}
}, true);
_configurationManager.OnValueChanged(CCVars.GameDummyTicker, value => DummyTicker = value, true); _configurationManager.OnValueChanged(CCVars.GameDummyTicker, value => DummyTicker = value, true);
_configurationManager.OnValueChanged(CCVars.GameLobbyDuration, value => LobbyDuration = TimeSpan.FromSeconds(value), true); _configurationManager.OnValueChanged(CCVars.GameLobbyDuration, value => LobbyDuration = TimeSpan.FromSeconds(value), true);
_configurationManager.OnValueChanged(CCVars.GameDisallowLateJoins, _configurationManager.OnValueChanged(CCVars.GameDisallowLateJoins,

View File

@@ -9,9 +9,7 @@ namespace Content.Server.GameTicking
public sealed partial class GameTicker public sealed partial class GameTicker
{ {
[ViewVariables] [ViewVariables]
private readonly Dictionary<IPlayerSession, LobbyPlayerStatus> _playersInLobby = new(); private readonly Dictionary<NetUserId, PlayerGameStatus> _playerGameStatuses = new();
[ViewVariables] private readonly HashSet<NetUserId> _playersInGame = new();
[ViewVariables] [ViewVariables]
private TimeSpan _roundStartTime; private TimeSpan _roundStartTime;
@@ -25,12 +23,14 @@ namespace Content.Server.GameTicking
[ViewVariables] [ViewVariables]
private bool _roundStartCountdownHasNotStartedYetDueToNoPlayers; private bool _roundStartCountdownHasNotStartedYetDueToNoPlayers;
public IReadOnlyDictionary<IPlayerSession, LobbyPlayerStatus> PlayersInLobby => _playersInLobby; /// <summary>
public IReadOnlySet<NetUserId> PlayersInGame => _playersInGame; /// The game status of a players user Id. May contain disconnected players
/// </summary>
public IReadOnlyDictionary<NetUserId, PlayerGameStatus> PlayerGameStatuses => _playerGameStatuses;
public void UpdateInfoText() public void UpdateInfoText()
{ {
RaiseNetworkEvent(GetInfoMsg(), Filter.Empty().AddPlayers(_playersInLobby.Keys)); RaiseNetworkEvent(GetInfoMsg(), Filter.Empty().AddPlayers(_playerManager.NetworkedSessions));
} }
private string GetInfoText() private string GetInfoText()
@@ -48,31 +48,31 @@ namespace Content.Server.GameTicking
return Loc.GetString("game-ticker-get-info-text",("roundId", RoundId), ("playerCount", playerCount),("mapName", mapName),("gmTitle", gmTitle),("desc", desc)); return Loc.GetString("game-ticker-get-info-text",("roundId", RoundId), ("playerCount", playerCount),("mapName", mapName),("gmTitle", gmTitle),("desc", desc));
} }
private TickerLobbyReadyEvent GetStatusSingle(ICommonSession player, LobbyPlayerStatus status) private TickerLobbyReadyEvent GetStatusSingle(ICommonSession player, PlayerGameStatus gameStatus)
{ {
return new (new Dictionary<NetUserId, LobbyPlayerStatus> { { player.UserId, status } }); return new (new Dictionary<NetUserId, PlayerGameStatus> { { player.UserId, gameStatus } });
} }
private TickerLobbyReadyEvent GetPlayerStatus() private TickerLobbyReadyEvent GetPlayerStatus()
{ {
var players = new Dictionary<NetUserId, LobbyPlayerStatus>(); var players = new Dictionary<NetUserId, PlayerGameStatus>();
foreach (var player in _playersInLobby.Keys) foreach (var player in _playerGameStatuses.Keys)
{ {
_playersInLobby.TryGetValue(player, out var status); _playerGameStatuses.TryGetValue(player, out var status);
players.Add(player.UserId, status); players.Add(player, status);
} }
return new TickerLobbyReadyEvent(players); return new TickerLobbyReadyEvent(players);
} }
private TickerLobbyStatusEvent GetStatusMsg(IPlayerSession session) private TickerLobbyStatusEvent GetStatusMsg(IPlayerSession session)
{ {
_playersInLobby.TryGetValue(session, out var status); _playerGameStatuses.TryGetValue(session.UserId, out var status);
return new TickerLobbyStatusEvent(RunLevel != GameRunLevel.PreRoundLobby, LobbySong, LobbyBackground,status == LobbyPlayerStatus.Ready, _roundStartTime, _roundStartTimeSpan, Paused); return new TickerLobbyStatusEvent(RunLevel != GameRunLevel.PreRoundLobby, LobbySong, LobbyBackground,status == PlayerGameStatus.ReadyToPlay, _roundStartTime, _roundStartTimeSpan, Paused);
} }
private void SendStatusToAll() private void SendStatusToAll()
{ {
foreach (var player in _playersInLobby.Keys) foreach (var player in _playerManager.ServerSessions)
{ {
RaiseNetworkEvent(GetStatusMsg(player), player.ConnectedClient); RaiseNetworkEvent(GetStatusMsg(player), player.ConnectedClient);
} }
@@ -121,16 +121,29 @@ namespace Content.Server.GameTicking
return Paused; return Paused;
} }
public void ToggleReadyAll(bool ready)
{
var status = ready ? PlayerGameStatus.ReadyToPlay : PlayerGameStatus.NotReadyToPlay;
foreach (var playerUserId in _playerGameStatuses.Keys)
{
_playerGameStatuses[playerUserId] = status;
if (!_playerManager.TryGetSessionById(playerUserId, out var playerSession))
continue;
RaiseNetworkEvent(GetStatusMsg(playerSession), playerSession.ConnectedClient);
RaiseNetworkEvent(GetStatusSingle(playerSession, status));
}
}
public void ToggleReady(IPlayerSession player, bool ready) public void ToggleReady(IPlayerSession player, bool ready)
{ {
if (!_playersInLobby.ContainsKey(player)) if (!_playerGameStatuses.ContainsKey(player.UserId))
return; return;
if (!_userDb.IsLoadComplete(player)) if (!_userDb.IsLoadComplete(player))
return; return;
var status = ready ? LobbyPlayerStatus.Ready : LobbyPlayerStatus.NotReady; var status = ready ? PlayerGameStatus.ReadyToPlay : PlayerGameStatus.NotReadyToPlay;
_playersInLobby[player] = ready ? LobbyPlayerStatus.Ready : LobbyPlayerStatus.NotReady; _playerGameStatuses[player.UserId] = ready ? PlayerGameStatus.ReadyToPlay : PlayerGameStatus.NotReadyToPlay;
RaiseNetworkEvent(GetStatusMsg(player), player.ConnectedClient); RaiseNetworkEvent(GetStatusMsg(player), player.ConnectedClient);
RaiseNetworkEvent(GetStatusSingle(player, status)); RaiseNetworkEvent(GetStatusSingle(player, status));
} }

View File

@@ -86,7 +86,7 @@ namespace Content.Server.GameTicking
case SessionStatus.Disconnected: case SessionStatus.Disconnected:
{ {
if (_playersInLobby.ContainsKey(session)) _playersInLobby.Remove(session); _playerGameStatuses.Remove(session.UserId);
_chatManager.SendAdminAnnouncement(Loc.GetString("player-leave-message", ("name", args.Session.Name))); _chatManager.SendAdminAnnouncement(Loc.GetString("player-leave-message", ("name", args.Session.Name)));
@@ -121,18 +121,17 @@ namespace Content.Server.GameTicking
{ {
_chatManager.DispatchServerMessage(session, Loc.GetString("game-ticker-player-join-game-message")); _chatManager.DispatchServerMessage(session, Loc.GetString("game-ticker-player-join-game-message"));
if (_playersInLobby.ContainsKey(session)) if (!_playerGameStatuses.ContainsKey(session.UserId))
_playersInLobby.Remove(session); _playerGameStatuses.Remove(session.UserId);
_playersInGame.Add(session.UserId); _playerGameStatuses[session.UserId] = PlayerGameStatus.JoinedGame;
RaiseNetworkEvent(new TickerJoinGameEvent(), session.ConnectedClient); RaiseNetworkEvent(new TickerJoinGameEvent(), session.ConnectedClient);
} }
private void PlayerJoinLobby(IPlayerSession session) private void PlayerJoinLobby(IPlayerSession session)
{ {
_playersInLobby[session] = LobbyPlayerStatus.NotReady; _playerGameStatuses[session.UserId] = LobbyEnabled ? PlayerGameStatus.NotReadyToPlay : PlayerGameStatus.ReadyToPlay;
_playersInGame.Remove(session.UserId);
var client = session.ConnectedClient; var client = session.ConnectedClient;
RaiseNetworkEvent(new TickerJoinLobbyEvent(), client); RaiseNetworkEvent(new TickerJoinLobbyEvent(), client);

View File

@@ -20,6 +20,7 @@ using Robust.Shared.Random;
using Robust.Shared.Utility; using Robust.Shared.Utility;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Robust.Shared.Players;
namespace Content.Server.GameTicking namespace Content.Server.GameTicking
{ {
@@ -150,7 +151,7 @@ namespace Content.Server.GameTicking
RoundLengthMetric.Set(0); RoundLengthMetric.Set(0);
var playerIds = _playersInLobby.Keys.Select(player => player.UserId.UserId).ToArray(); var playerIds = _playerGameStatuses.Keys.Select(player => player.UserId).ToArray();
var serverName = _configurationManager.GetCVar(CCVars.AdminLogsServerName); var serverName = _configurationManager.GetCVar(CCVars.AdminLogsServerName);
// TODO FIXME AAAAAAAAAAAAAAAAAAAH THIS IS BROKEN // TODO FIXME AAAAAAAAAAAAAAAAAAAH THIS IS BROKEN
// Task.Run as a terrible dirty workaround to avoid synchronization context deadlock from .Result here. // Task.Run as a terrible dirty workaround to avoid synchronization context deadlock from .Result here.
@@ -166,44 +167,32 @@ namespace Content.Server.GameTicking
var startingEvent = new RoundStartingEvent(RoundId); var startingEvent = new RoundStartingEvent(RoundId);
RaiseLocalEvent(startingEvent); RaiseLocalEvent(startingEvent);
List<IPlayerSession> readyPlayers; var readyPlayers = new List<IPlayerSession>();
if (LobbyEnabled) var readyPlayerProfiles = new Dictionary<NetUserId, HumanoidCharacterProfile>();
{
readyPlayers = _playersInLobby.Where(p => p.Value == LobbyPlayerStatus.Ready).Select(p => p.Key)
.ToList();
}
else
{
readyPlayers = _playersInLobby.Keys.ToList();
}
foreach (var (userId, status) in _playerGameStatuses)
{
if (LobbyEnabled && status != PlayerGameStatus.ReadyToPlay) continue;
if (!_playerManager.TryGetSessionById(userId, out var session)) continue;
#if DEBUG #if DEBUG
foreach (var player in readyPlayers) DebugTools.Assert(_userDb.IsLoadComplete(session), $"Player was readied up but didn't have user DB data loaded yet??");
{
DebugTools.Assert(_userDb.IsLoadComplete(player), $"Player was readied up but didn't have user DB data loaded yet??");
}
#endif #endif
if (_roleBanManager.GetRoleBans(userId) == null)
readyPlayers.RemoveAll(p =>
{
if (_roleBanManager.GetRoleBans(p.UserId) != null)
return false;
Logger.ErrorS("RoleBans", $"Role bans for player {p} {p.UserId} have not been loaded yet.");
return true;
});
// Get the profiles for each player for easier lookup.
var profiles = _prefsManager.GetSelectedProfilesForPlayers(
readyPlayers
.Select(p => p.UserId).ToList())
.ToDictionary(p => p.Key, p => (HumanoidCharacterProfile) p.Value);
foreach (var readyPlayer in readyPlayers)
{
if (!profiles.ContainsKey(readyPlayer.UserId))
{ {
profiles.Add(readyPlayer.UserId, HumanoidCharacterProfile.Random()); Logger.ErrorS("RoleBans", $"Role bans for player {session} {userId} have not been loaded yet.");
continue;
} }
readyPlayers.Add(session);
HumanoidCharacterProfile profile;
if (_prefsManager.TryGetCachedPreferences(userId, out var preferences))
{
profile = (HumanoidCharacterProfile) preferences.GetProfile(preferences.SelectedCharacterIndex);
}
else
{
profile = HumanoidCharacterProfile.Random();
}
readyPlayerProfiles.Add(userId, profile);
} }
var origReadyPlayers = readyPlayers.ToArray(); var origReadyPlayers = readyPlayers.ToArray();
@@ -214,7 +203,7 @@ namespace Content.Server.GameTicking
// MapInitialize *before* spawning players, our codebase is too shit to do it afterwards... // MapInitialize *before* spawning players, our codebase is too shit to do it afterwards...
_mapManager.DoMapInitialize(DefaultMap); _mapManager.DoMapInitialize(DefaultMap);
SpawnPlayers(readyPlayers, profiles, force); SpawnPlayers(readyPlayers, readyPlayerProfiles, force);
_roundStartDateTime = DateTime.UtcNow; _roundStartDateTime = DateTime.UtcNow;
RunLevel = GameRunLevel.InRound; RunLevel = GameRunLevel.InRound;
@@ -340,7 +329,6 @@ namespace Content.Server.GameTicking
} }
// This ordering mechanism isn't great (no ordering of minds) but functions // This ordering mechanism isn't great (no ordering of minds) but functions
var listOfPlayerInfoFinal = listOfPlayerInfo.OrderBy(pi => pi.PlayerOOCName).ToArray(); var listOfPlayerInfoFinal = listOfPlayerInfo.OrderBy(pi => pi.PlayerOOCName).ToArray();
_playersInGame.Clear();
RaiseNetworkEvent(new RoundEndMessageEvent(gamemodeTitle, roundEndText, roundDuration, RoundId, RaiseNetworkEvent(new RoundEndMessageEvent(gamemodeTitle, roundEndText, roundDuration, RoundId,
listOfPlayerInfoFinal.Length, listOfPlayerInfoFinal, LobbySong, listOfPlayerInfoFinal.Length, listOfPlayerInfoFinal, LobbySong,
@@ -445,6 +433,11 @@ namespace Content.Server.GameTicking
RaiseNetworkEvent(ev, Filter.Broadcast()); RaiseNetworkEvent(ev, Filter.Broadcast());
DisallowLateJoin = false; DisallowLateJoin = false;
_playerGameStatuses.Clear();
foreach (var session in _playerManager.ServerSessions)
{
_playerGameStatuses[session.UserId] = LobbyEnabled ? PlayerGameStatus.NotReadyToPlay : PlayerGameStatus.ReadyToPlay;
}
} }
public bool DelayStart(TimeSpan time) public bool DelayStart(TimeSpan time)

View File

@@ -231,7 +231,7 @@ namespace Content.Server.GameTicking
public void MakeJoinGame(IPlayerSession player, EntityUid station, string? jobId = null) public void MakeJoinGame(IPlayerSession player, EntityUid station, string? jobId = null)
{ {
if (!_playersInLobby.ContainsKey(player)) if (!_playerGameStatuses.ContainsKey(player.UserId))
return; return;
if (!_userDb.IsLoadComplete(player)) if (!_userDb.IsLoadComplete(player))
@@ -265,8 +265,8 @@ namespace Content.Server.GameTicking
EntitySystem.Get<SharedGhostSystem>().SetCanReturnToBody(ghost, false); EntitySystem.Get<SharedGhostSystem>().SetCanReturnToBody(ghost, false);
newMind.TransferTo(mob); newMind.TransferTo(mob);
_playersInLobby[player] = LobbyPlayerStatus.Observer; _playerGameStatuses[player.UserId] = PlayerGameStatus.JoinedGame;
RaiseNetworkEvent(GetStatusSingle(player, LobbyPlayerStatus.Observer)); RaiseNetworkEvent(GetStatusSingle(player, PlayerGameStatus.JoinedGame));
} }
#region Mob Spawning Helpers #region Mob Spawning Helpers

View File

@@ -1,3 +1,4 @@
using System.Diagnostics.CodeAnalysis;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Content.Shared.Preferences; using Content.Shared.Preferences;
@@ -13,6 +14,7 @@ namespace Content.Server.Preferences.Managers
Task LoadData(IPlayerSession session, CancellationToken cancel); Task LoadData(IPlayerSession session, CancellationToken cancel);
void OnClientDisconnected(IPlayerSession session); void OnClientDisconnected(IPlayerSession session);
bool TryGetCachedPreferences(NetUserId userId, [NotNullWhen(true)] out PlayerPreferences? playerPreferences);
PlayerPreferences GetPreferences(NetUserId userId); PlayerPreferences GetPreferences(NetUserId userId);
IEnumerable<KeyValuePair<NetUserId, ICharacterProfile>> GetSelectedProfilesForPlayers(List<NetUserId> userIds); IEnumerable<KeyValuePair<NetUserId, ICharacterProfile>> GetSelectedProfilesForPlayers(List<NetUserId> userIds);
} }

View File

@@ -1,3 +1,4 @@
using System.Diagnostics.CodeAnalysis;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -215,6 +216,26 @@ namespace Content.Server.Preferences.Managers
return _cachedPlayerPrefs.ContainsKey(session.UserId); return _cachedPlayerPrefs.ContainsKey(session.UserId);
} }
/// <summary>
/// Tries to get the preferences from the cache
/// </summary>
/// <param name="userId">User Id to get preferences for</param>
/// <param name="playerPreferences">The user preferences if true, otherwise null</param>
/// <returns>If preferences are not null</returns>
public bool TryGetCachedPreferences(NetUserId userId,
[NotNullWhen(true)] out PlayerPreferences? playerPreferences)
{
if (_cachedPlayerPrefs.TryGetValue(userId, out var prefs))
{
playerPreferences = prefs.Prefs;
return prefs.Prefs != null;
}
playerPreferences = null;
return false;
}
/// <summary> /// <summary>
/// Retrieves preferences for the given username from storage. /// Retrieves preferences for the given username from storage.
/// Creates and saves default preferences if they are not found, then returns them. /// Creates and saves default preferences if they are not found, then returns them.

View File

@@ -24,6 +24,7 @@ public sealed partial class StationJobsSystem : EntitySystem
[Dependency] private readonly IRobustRandom _random = default!; [Dependency] private readonly IRobustRandom _random = default!;
[Dependency] private readonly GameTicker _gameTicker = default!; [Dependency] private readonly GameTicker _gameTicker = default!;
[Dependency] private readonly StationSystem _stationSystem = default!; [Dependency] private readonly StationSystem _stationSystem = default!;
[Dependency] private readonly IPlayerManager _playerManager = default!;
/// <inheritdoc/> /// <inheritdoc/>
public override void Initialize() public override void Initialize()
@@ -40,7 +41,7 @@ public sealed partial class StationJobsSystem : EntitySystem
if (_availableJobsDirty) if (_availableJobsDirty)
{ {
_cachedAvailableJobs = GenerateJobsAvailableEvent(); _cachedAvailableJobs = GenerateJobsAvailableEvent();
RaiseNetworkEvent(_cachedAvailableJobs, Filter.Empty().AddPlayers(_gameTicker.PlayersInLobby.Keys)); RaiseNetworkEvent(_cachedAvailableJobs, Filter.Empty().AddPlayers(_playerManager.ServerSessions));
_availableJobsDirty = false; _availableJobsDirty = false;
} }
} }

View File

@@ -97,9 +97,9 @@ namespace Content.Shared.GameTicking
/// <summary> /// <summary>
/// The Status of the Player in the lobby (ready, observer, ...) /// The Status of the Player in the lobby (ready, observer, ...)
/// </summary> /// </summary>
public Dictionary<NetUserId, LobbyPlayerStatus> Status { get; } public Dictionary<NetUserId, PlayerGameStatus> Status { get; }
public TickerLobbyReadyEvent(Dictionary<NetUserId, LobbyPlayerStatus> status) public TickerLobbyReadyEvent(Dictionary<NetUserId, PlayerGameStatus> status)
{ {
Status = status; Status = status;
} }
@@ -168,11 +168,11 @@ namespace Content.Shared.GameTicking
[Serializable, NetSerializable] [Serializable, NetSerializable]
public enum LobbyPlayerStatus : sbyte public enum PlayerGameStatus : sbyte
{ {
NotReady = 0, NotReadyToPlay = 0,
Ready, ReadyToPlay,
Observer, JoinedGame,
} }
} }