diff --git a/Robust.Server/AI/AiLogicProcessor.cs b/Robust.Server/AI/AiLogicProcessor.cs index 45ac81a34..4b097b12f 100644 --- a/Robust.Server/AI/AiLogicProcessor.cs +++ b/Robust.Server/AI/AiLogicProcessor.cs @@ -15,7 +15,7 @@ namespace Robust.Server.AI /// /// Entity this AI is controlling. /// - public IEntity SelfEntity { get; set; } + public IEntity SelfEntity { get; set; } = default!; /// /// One-Time setup when the processor is created. diff --git a/Robust.Server/BaseServer.cs b/Robust.Server/BaseServer.cs index cb2f57a9c..c05633c25 100644 --- a/Robust.Server/BaseServer.cs +++ b/Robust.Server/BaseServer.cs @@ -58,38 +58,36 @@ namespace Robust.Server "The IGameTiming.CurTick of the server."); -#pragma warning disable 649 - [Dependency] private readonly IConfigurationManager _config; - [Dependency] private readonly IComponentManager _components; - [Dependency] private readonly IServerEntityManager _entities; - [Dependency] private readonly ILogManager _log; - [Dependency] private readonly IRobustSerializer _serializer; - [Dependency] private readonly IGameTiming _time; - [Dependency] private readonly IResourceManagerInternal _resources; - [Dependency] private readonly IMapManager _mapManager; - [Dependency] private readonly ITimerManager timerManager; - [Dependency] private readonly IServerGameStateManager _stateManager; - [Dependency] private readonly IServerNetManager _network; - [Dependency] private readonly ISystemConsoleManager _systemConsole; - [Dependency] private readonly ITaskManager _taskManager; - [Dependency] private readonly IRuntimeLog runtimeLog; - [Dependency] private readonly IModLoader _modLoader; - [Dependency] private readonly IWatchdogApi _watchdogApi; - [Dependency] private readonly IScriptHost _scriptHost; - [Dependency] private readonly IMetricsManager _metricsManager; -#pragma warning restore 649 + [Dependency] private readonly IConfigurationManager _config = default!; + [Dependency] private readonly IComponentManager _components = default!; + [Dependency] private readonly IServerEntityManager _entities = default!; + [Dependency] private readonly ILogManager _log = default!; + [Dependency] private readonly IRobustSerializer _serializer = default!; + [Dependency] private readonly IGameTiming _time = default!; + [Dependency] private readonly IResourceManagerInternal _resources = default!; + [Dependency] private readonly IMapManager _mapManager = default!; + [Dependency] private readonly ITimerManager timerManager = default!; + [Dependency] private readonly IServerGameStateManager _stateManager = default!; + [Dependency] private readonly IServerNetManager _network = default!; + [Dependency] private readonly ISystemConsoleManager _systemConsole = default!; + [Dependency] private readonly ITaskManager _taskManager = default!; + [Dependency] private readonly IRuntimeLog runtimeLog = default!; + [Dependency] private readonly IModLoader _modLoader = default!; + [Dependency] private readonly IWatchdogApi _watchdogApi = default!; + [Dependency] private readonly IScriptHost _scriptHost = default!; + [Dependency] private readonly IMetricsManager _metricsManager = default!; private readonly Stopwatch _uptimeStopwatch = new Stopwatch(); - private CommandLineArgs _commandLineArgs; - private FileLogHandler fileLogHandler; - private IGameLoop _mainLoop; + private CommandLineArgs _commandLineArgs = default!; + private FileLogHandler fileLogHandler = default!; + private IGameLoop _mainLoop = default!; private TimeSpan _lastTitleUpdate; private int _lastReceivedBytes; private int _lastSentBytes; - private string _shutdownReason; + private string? _shutdownReason; private readonly ManualResetEventSlim _shutdownEvent = new ManualResetEventSlim(false); @@ -109,7 +107,7 @@ namespace Robust.Server } /// - public void Shutdown(string reason) + public void Shutdown(string? reason) { if (string.IsNullOrWhiteSpace(reason)) Logger.InfoS("srv", "Shutting down..."); @@ -281,7 +279,7 @@ namespace Robust.Server return false; } - private void ProcessExiting(object sender, EventArgs e) + private void ProcessExiting(object? sender, EventArgs e) { _taskManager.RunOnMainThread(() => Shutdown("ProcessExited")); // Give the server 10 seconds to shut down. diff --git a/Robust.Server/CommandLineArgs.cs b/Robust.Server/CommandLineArgs.cs index c6b247714..6ba5bb3a3 100644 --- a/Robust.Server/CommandLineArgs.cs +++ b/Robust.Server/CommandLineArgs.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using Robust.Shared.Utility; using C = System.Console; @@ -6,17 +7,17 @@ namespace Robust.Server { internal sealed class CommandLineArgs { - public string ConfigFile { get; } - public string DataDir { get; } + public string? ConfigFile { get; } + public string? DataDir { get; } public IReadOnlyCollection<(string key, string value)> CVars { get; } // Manual parser because C# has no good command line parsing libraries. Also dependencies bad. // Also I don't like spending 100ms parsing command line args. Do you? - public static bool TryParse(IReadOnlyList args, out CommandLineArgs parsed) + public static bool TryParse(IReadOnlyList args, [NotNullWhen(true)] out CommandLineArgs? parsed) { parsed = null; - string configFile = null; - string dataDir = null; + string? configFile = null; + string? dataDir = null; var cvars = new List<(string, string)>(); using var enumerator = args.GetEnumerator(); @@ -90,7 +91,7 @@ Options: "); } - private CommandLineArgs(string configFile, string dataDir, IReadOnlyCollection<(string, string)> cVars) + private CommandLineArgs(string? configFile, string? dataDir, IReadOnlyCollection<(string, string)> cVars) { ConfigFile = configFile; DataDir = dataDir; diff --git a/Robust.Server/Console/Commands/AddCompCommand.cs b/Robust.Server/Console/Commands/AddCompCommand.cs index e2d6b2c74..eb0439086 100644 --- a/Robust.Server/Console/Commands/AddCompCommand.cs +++ b/Robust.Server/Console/Commands/AddCompCommand.cs @@ -14,7 +14,7 @@ namespace Robust.Server.Console.Commands public string Description => "Adds a component to an entity"; public string Help => "addcomp "; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { if (args.Length != 2) { diff --git a/Robust.Server/Console/Commands/CVarCommand.cs b/Robust.Server/Console/Commands/CVarCommand.cs index 22f496aa5..18dc981cc 100644 --- a/Robust.Server/Console/Commands/CVarCommand.cs +++ b/Robust.Server/Console/Commands/CVarCommand.cs @@ -11,7 +11,7 @@ namespace Robust.Server.Console.Commands [UsedImplicitly] internal sealed class CVarCommand : SharedCVarCommand, IClientCommand { - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { if (args.Length < 1 || args.Length > 2) { diff --git a/Robust.Server/Console/Commands/DeleteCommand.cs b/Robust.Server/Console/Commands/DeleteCommand.cs index 744cbff73..53d432741 100644 --- a/Robust.Server/Console/Commands/DeleteCommand.cs +++ b/Robust.Server/Console/Commands/DeleteCommand.cs @@ -12,7 +12,7 @@ namespace Robust.Server.Console.Commands public string Description => "Deletes the entity with the specified ID."; public string Help => "delete "; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { if (args.Length != 1) { diff --git a/Robust.Server/Console/Commands/ListAssembliesCommand.cs b/Robust.Server/Console/Commands/ListAssembliesCommand.cs index a8e373450..4af32f2c8 100644 --- a/Robust.Server/Console/Commands/ListAssembliesCommand.cs +++ b/Robust.Server/Console/Commands/ListAssembliesCommand.cs @@ -13,7 +13,7 @@ namespace Robust.Server.Console.Commands public string Description => "Lists loaded assemblies by load context."; public string Help => Command; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { var sb = new StringBuilder(); foreach (var context in AssemblyLoadContext.All) diff --git a/Robust.Server/Console/Commands/ListCommands.cs b/Robust.Server/Console/Commands/ListCommands.cs index 7f5cb6233..550ad4565 100644 --- a/Robust.Server/Console/Commands/ListCommands.cs +++ b/Robust.Server/Console/Commands/ListCommands.cs @@ -11,7 +11,7 @@ namespace Robust.Server.Console.Commands public string Description => "Outputs a list of all commands which are currently available to you."; public string Help => "list"; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { var builder = new StringBuilder("SIDE NAME DESC\n-------------------------\n"); foreach (var command in shell.AvailableCommands.Values.OrderBy(c => c.Command)) diff --git a/Robust.Server/Console/Commands/LogCommands.cs b/Robust.Server/Console/Commands/LogCommands.cs index 871cbb854..f2b8d7d67 100644 --- a/Robust.Server/Console/Commands/LogCommands.cs +++ b/Robust.Server/Console/Commands/LogCommands.cs @@ -13,7 +13,7 @@ namespace Robust.Server.Console.Commands + "\n sawmill: A label prefixing log messages. This is the one you're setting the level for." + "\n level: The log level. Must match one of the values of the LogLevel enum."; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { if (args.Length != 2) { @@ -50,7 +50,7 @@ namespace Robust.Server.Console.Commands + "\n level: The log level. Must match one of the values of the LogLevel enum." + "\n message: The message to be logged. Wrap this in double quotes if you want to use spaces."; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { if (args.Length != 3) { diff --git a/Robust.Server/Console/Commands/MapCommands.cs b/Robust.Server/Console/Commands/MapCommands.cs index c1a562f5e..dea1fdf0e 100644 --- a/Robust.Server/Console/Commands/MapCommands.cs +++ b/Robust.Server/Console/Commands/MapCommands.cs @@ -18,7 +18,7 @@ namespace Robust.Server.Console.Commands public string Description => "Adds a new empty map to the round. If the mapID already exists, this command does nothing."; public string Help => "addmap [initialize]"; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { if (args.Length < 1) return; @@ -48,7 +48,7 @@ namespace Robust.Server.Console.Commands public string Command => "rmmap"; public string Description => "Removes a map from the world. You cannot remove nullspace."; public string Help => "rmmap "; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { if (args.Length != 1) { @@ -76,7 +76,7 @@ namespace Robust.Server.Console.Commands public string Description => "Serializes a grid to disk."; public string Help => "savebp "; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { if (args.Length < 2) { @@ -118,7 +118,7 @@ namespace Robust.Server.Console.Commands public string Description => "Loads a blueprint from disk into the game."; public string Help => "loadbp "; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { if (args.Length < 2) { @@ -157,7 +157,7 @@ namespace Robust.Server.Console.Commands public string Description => "Serializes a map to disk."; public string Help => "savemap "; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { if (args.Length < 1) return; @@ -186,7 +186,7 @@ namespace Robust.Server.Console.Commands public string Description => "Loads a map from disk into the game."; public string Help => "loadmap "; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { if (args.Length < 1) return; @@ -223,9 +223,9 @@ namespace Robust.Server.Console.Commands public string Description => "Prints the absolute location of the player's entity to console."; public string Help => "loc"; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { - if(player.AttachedEntity == null) + if(player?.AttachedEntity == null) return; var pos = player.AttachedEntity.Transform.GridPosition; @@ -239,7 +239,7 @@ namespace Robust.Server.Console.Commands public string Command => "pausemap"; public string Description => "Pauses a map, pausing all simulation processing on it."; public string Help => "Usage: pausemap "; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { var arg = args[0]; var mapId = new MapId(int.Parse(arg, CultureInfo.InvariantCulture)); @@ -260,7 +260,7 @@ namespace Robust.Server.Console.Commands public string Command => "unpausemap"; public string Description => "unpauses a map, resuming all simulation processing on it."; public string Help => "Usage: unpausemap "; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { var arg = args[0]; var mapId = new MapId(int.Parse(arg, CultureInfo.InvariantCulture)); @@ -281,7 +281,7 @@ namespace Robust.Server.Console.Commands public string Command => "querymappaused"; public string Description => "Check whether a map is paused or not."; public string Help => "Usage: querymappaused "; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { var arg = args[0]; var mapId = new MapId(int.Parse(arg, CultureInfo.InvariantCulture)); @@ -303,7 +303,7 @@ namespace Robust.Server.Console.Commands public string Description => "Teleports a grid to a new location."; public string Help => "tpgrid []"; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { if (args.Length < 3 || args.Length > 4) { @@ -333,7 +333,7 @@ namespace Robust.Server.Console.Commands public string Command => "rmgrid"; public string Description => "Removes a grid from a map. You cannot remove the default grid."; public string Help => "rmgrid "; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { if (args.Length != 1) { @@ -358,10 +358,10 @@ namespace Robust.Server.Console.Commands internal sealed class RunMapInitCommand : IClientCommand { public string Command => "mapinit"; - public string Description => default; + public string Description => "Runs map init on a map"; public string Help => "mapinit "; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { if (args.Length != 1) { @@ -394,10 +394,10 @@ namespace Robust.Server.Console.Commands internal sealed class ListMapsCommand : IClientCommand { public string Command => "lsmap"; - public string Description => default; + public string Description => "Lists maps"; public string Help => "lsmap"; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { var mapManager = IoCManager.Resolve(); var pauseManager = IoCManager.Resolve(); @@ -420,10 +420,10 @@ namespace Robust.Server.Console.Commands internal sealed class ListGridsCommand : IClientCommand { public string Command => "lsgrid"; - public string Description => default; + public string Description => "List grids"; public string Help => "lsgrid"; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { var mapManager = IoCManager.Resolve(); diff --git a/Robust.Server/Console/Commands/PlayerCommands.cs b/Robust.Server/Console/Commands/PlayerCommands.cs index 10daf4988..9b780715f 100644 --- a/Robust.Server/Console/Commands/PlayerCommands.cs +++ b/Robust.Server/Console/Commands/PlayerCommands.cs @@ -1,18 +1,15 @@ using System; +using System.Linq; using System.Text; using Robust.Server.Interfaces.Console; -using Robust.Server.Interfaces.GameObjects; using Robust.Server.Interfaces.Player; using Robust.Shared.Enums; -using Robust.Shared.Interfaces.GameObjects; -using Robust.Shared.Interfaces.GameObjects.Components; using Robust.Shared.Interfaces.Map; using Robust.Shared.Interfaces.Network; using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Network; -using Robust.Shared.Players; namespace Robust.Server.Console.Commands { @@ -22,9 +19,9 @@ namespace Robust.Server.Console.Commands public string Description => "Teleports a player to any location in the round."; public string Help => "tp []"; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { - if (player.Status != SessionStatus.InGame || player.AttachedEntity == null) + if (player?.Status != SessionStatus.InGame || player.AttachedEntity == null) return; if (args.Length < 2 || !float.TryParse(args[0], out var posX) || !float.TryParse(args[1], out var posY)) @@ -70,7 +67,7 @@ namespace Robust.Server.Console.Commands public string Description => "Lists all players currently connected"; public string Help => "listplayers"; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { // Player: number of people connected and their byond keys // Admin: read a byond variable which shows their ip, byond version, ckey, attached entity and hardware id @@ -102,17 +99,24 @@ namespace Robust.Server.Console.Commands public string Description => "Kicks a connected player out of the server, disconnecting them."; public string Help => "kick []"; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { + var players = IoCManager.Resolve(); if (args.Length < 1) { - shell.SendText(player, $"You need to provide a player to kick. Try running 'kick {player.Name}' as an example."); + var toKickPlayer = player ?? players.GetAllPlayers().FirstOrDefault(); + if (toKickPlayer == null) + { + shell.SendText(player, "You need to provide a player to kick."); + return; + } + shell.SendText(player, + $"You need to provide a player to kick. Try running 'kick {toKickPlayer?.Name}' as an example."); return; } var name = args[0]; - var players = IoCManager.Resolve(); var index = new NetSessionId(name); if (players.ValidSessionId(index)) diff --git a/Robust.Server/Console/Commands/SpawnCommand.cs b/Robust.Server/Console/Commands/SpawnCommand.cs index d97abd4c9..4494ea396 100644 --- a/Robust.Server/Console/Commands/SpawnCommand.cs +++ b/Robust.Server/Console/Commands/SpawnCommand.cs @@ -12,7 +12,7 @@ namespace Robust.Server.Console.Commands public string Description => "Spawns an entity with specific type at your feet."; public string Help => "spawn "; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { var ent = IoCManager.Resolve(); if (player?.AttachedEntity != null) diff --git a/Robust.Server/Console/Commands/SysCommands.cs b/Robust.Server/Console/Commands/SysCommands.cs index 4e1184074..56c8eb163 100644 --- a/Robust.Server/Console/Commands/SysCommands.cs +++ b/Robust.Server/Console/Commands/SysCommands.cs @@ -19,7 +19,7 @@ namespace Robust.Server.Console.Commands public string Description => "Gracefully restarts the server (not just the round)."; public string Help => "restart"; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { IoCManager.Resolve().Restart(); } @@ -31,7 +31,7 @@ namespace Robust.Server.Console.Commands public string Description => "Gracefully shuts down the server."; public string Help => "shutdown"; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { IoCManager.Resolve().Shutdown(null); } @@ -43,7 +43,7 @@ namespace Robust.Server.Console.Commands public string Description => "Saves the server configuration to the config file"; public string Help => "saveconfig"; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { IoCManager.Resolve().SaveToFile(); } @@ -55,7 +55,7 @@ namespace Robust.Server.Console.Commands public string Description => "Prints into about NetMsg security."; public string Help => "netaudit"; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { var network = (NetManager) IoCManager.Resolve(); @@ -84,7 +84,7 @@ namespace Robust.Server.Console.Commands public string Help => "Help"; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { switch (args.Length) { @@ -117,7 +117,7 @@ namespace Robust.Server.Console.Commands public string Description => "Shows the server time."; public string Help => "showtime"; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { var timing = IoCManager.Resolve(); shell.SendText(player, @@ -131,7 +131,7 @@ namespace Robust.Server.Console.Commands public string Description => "Run the GC."; public string Help => "gc [generation]"; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { if (args.Length == 0) { @@ -156,14 +156,14 @@ namespace Robust.Server.Console.Commands public string Help => "gc_mode [type]"; - public void Execute(IConsoleShell console, IPlayerSession player, params string[] args) + public void Execute(IConsoleShell console, IPlayerSession? player, string[] args) { var prevMode = GCSettings.LatencyMode; if (args.Length == 0) { console.SendText(player,$"current gc latency mode: {(int) prevMode} ({prevMode})"); console.SendText(player,"possible modes:"); - foreach (int mode in Enum.GetValues(typeof(GCLatencyMode))) + foreach (var mode in (int[]) Enum.GetValues(typeof(GCLatencyMode))) { console.SendText(player,$" {mode}: {Enum.GetName(typeof(GCLatencyMode), mode)}"); } @@ -200,7 +200,7 @@ namespace Robust.Server.Console.Commands public string Help => "szr_stats"; - public void Execute(IConsoleShell console, IPlayerSession player, params string[] args) + public void Execute(IConsoleShell console, IPlayerSession? player, string[] args) { console.SendText(player,$"serialized: {RobustSerializer.BytesSerialized} bytes, {RobustSerializer.ObjectsSerialized} objects"); @@ -217,7 +217,7 @@ namespace Robust.Server.Console.Commands public string Description => "prints memory info"; public string Help => "mem"; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { #if !NETCOREAPP shell.SendText(player, "Memory info is only available on .NET Core"); diff --git a/Robust.Server/Console/ConGroupContainer.cs b/Robust.Server/Console/ConGroupContainer.cs index abe01e4dc..00f9dac87 100644 --- a/Robust.Server/Console/ConGroupContainer.cs +++ b/Robust.Server/Console/ConGroupContainer.cs @@ -116,7 +116,7 @@ namespace Robust.Server.Console { if (_groups.TryGetValue(groupIndex, out var group)) { - return group.Commands.Contains(cmdName); + return group.Commands!.Contains(cmdName); } _logger.Error($"Unknown groupIndex: {groupIndex}"); diff --git a/Robust.Server/Console/ConGroupController.cs b/Robust.Server/Console/ConGroupController.cs index b63d2f680..db2b5549a 100644 --- a/Robust.Server/Console/ConGroupController.cs +++ b/Robust.Server/Console/ConGroupController.cs @@ -18,16 +18,14 @@ namespace Robust.Server.Console /// internal class ConGroupController : IConGroupController { -#pragma warning disable 649 - [Dependency] private readonly IResourceManager _resourceManager; - [Dependency] private readonly IConfigurationManager _configurationManager; - [Dependency] private readonly ILogManager _logManager; - [Dependency] private readonly IPlayerManager _playerManager; - [Dependency] private readonly INetManager _netManager; -#pragma warning restore 649 + [Dependency] private readonly IResourceManager _resourceManager = default!; + [Dependency] private readonly IConfigurationManager _configurationManager = default!; + [Dependency] private readonly ILogManager _logManager = default!; + [Dependency] private readonly IPlayerManager _playerManager = default!; + [Dependency] private readonly INetManager _netManager = default!; - private ConGroupContainer _groups; - private SessionGroupContainer _sessions; + private ConGroupContainer _groups = default!; + private SessionGroupContainer _sessions = default!; public void Initialize() { @@ -49,7 +47,7 @@ namespace Robust.Server.Console UpdateAllClientData(); } - private void _onClientStatusChanged(object sender, SessionStatusEventArgs e) + private void _onClientStatusChanged(object? sender, SessionStatusEventArgs e) { _sessions.OnClientStatusChanged(sender, e); diff --git a/Robust.Server/Console/ConsoleShell.cs b/Robust.Server/Console/ConsoleShell.cs index 4b98da1e8..819eeb26d 100644 --- a/Robust.Server/Console/ConsoleShell.cs +++ b/Robust.Server/Console/ConsoleShell.cs @@ -21,15 +21,13 @@ namespace Robust.Server.Console { private const string SawmillName = "con"; -#pragma warning disable 649 - [Dependency] private readonly IReflectionManager _reflectionManager; - [Dependency] private readonly IPlayerManager _players; - [Dependency] private readonly IServerNetManager _net; - [Dependency] private readonly ISystemConsoleManager _systemConsole; - [Dependency] private readonly ILogManager _logMan; - [Dependency] private readonly IConfigurationManager _configMan; - [Dependency] private readonly IConGroupController _groupController; -#pragma warning restore 649 + [Dependency] private readonly IReflectionManager _reflectionManager = default!; + [Dependency] private readonly IPlayerManager _players = default!; + [Dependency] private readonly IServerNetManager _net = default!; + [Dependency] private readonly ISystemConsoleManager _systemConsole = default!; + [Dependency] private readonly ILogManager _logMan = default!; + [Dependency] private readonly IConfigurationManager _configMan = default!; + [Dependency] private readonly IConGroupController _groupController = default!; private readonly Dictionary _availableCommands = new Dictionary(); @@ -87,7 +85,7 @@ namespace Robust.Server.Console _availableCommands.Clear(); foreach (var type in _reflectionManager.GetAllChildren()) { - var instance = (IClientCommand) Activator.CreateInstance(type, null); + var instance = (IClientCommand) Activator.CreateInstance(type, null)!; if (AvailableCommands.TryGetValue(instance.Command, out var duplicate)) throw new InvalidImplementationException(instance.GetType(), typeof(IClientCommand), $"Command name already registered: {instance.Command}, previous: {duplicate.GetType()}"); @@ -114,7 +112,7 @@ namespace Robust.Server.Console } /// - public void ExecuteCommand(IPlayerSession session, string command) + public void ExecuteCommand(IPlayerSession? session, string command) { try { @@ -156,7 +154,7 @@ namespace Robust.Server.Console } /// - public void SendText(IPlayerSession session, string text) + public void SendText(IPlayerSession? session, string? text) { if (session != null) SendText(session.ConnectedClient, text); @@ -165,14 +163,14 @@ namespace Robust.Server.Console } /// - public void SendText(INetChannel target, string text) + public void SendText(INetChannel target, string? text) { var replyMsg = _net.CreateNetMessage(); replyMsg.Text = text; _net.ServerSendMessage(replyMsg, target); } - private static string FormatPlayerString(IPlayerSession session) + private static string FormatPlayerString(IPlayerSession? session) { return session != null ? $"{session.Name}" : "[HOST]"; } @@ -204,7 +202,7 @@ namespace Robust.Server.Console public string Description => "Elevates client to admin permission group."; public string Help => "login"; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { // system console can't log in to itself, and is pointless anyways if (player == null) @@ -234,7 +232,7 @@ namespace Robust.Server.Console public string Description => "Prints your current permission group."; public string Help => "group"; - public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) + public void Execute(IConsoleShell shell, IPlayerSession? player, string[] args) { // only the local server console bypasses permissions if (player == null) diff --git a/Robust.Server/Console/SessionGroupContainer.cs b/Robust.Server/Console/SessionGroupContainer.cs index 9e7593909..d9ecc47a0 100644 --- a/Robust.Server/Console/SessionGroupContainer.cs +++ b/Robust.Server/Console/SessionGroupContainer.cs @@ -45,7 +45,7 @@ namespace Robust.Server.Console /// /// Event handler for when the status of a player session changes. /// - public void OnClientStatusChanged(object sender, SessionStatusEventArgs e) + public void OnClientStatusChanged(object? sender, SessionStatusEventArgs e) { switch (e.NewStatus) { diff --git a/Robust.Server/Console/SystemConsoleManager.cs b/Robust.Server/Console/SystemConsoleManager.cs index 0d09f0074..0584aa643 100644 --- a/Robust.Server/Console/SystemConsoleManager.cs +++ b/Robust.Server/Console/SystemConsoleManager.cs @@ -11,11 +11,9 @@ namespace Robust.Server.Console { internal sealed class SystemConsoleManager : ISystemConsoleManager, IPostInjectInit, IDisposable { -#pragma warning disable 649 - [Dependency] private readonly IConsoleShell _conShell; - [Dependency] private readonly ITaskManager _taskManager; - [Dependency] private readonly IBaseServer _baseServer; -#pragma warning restore 649 + [Dependency] private readonly IConsoleShell _conShell = default!; + [Dependency] private readonly ITaskManager _taskManager = default!; + [Dependency] private readonly IBaseServer _baseServer = default!; private readonly Dictionary commandHistory = new Dictionary(); private string currentBuffer = ""; diff --git a/Robust.Server/Debugging/DebugDrawingManager.cs b/Robust.Server/Debugging/DebugDrawingManager.cs index 1e18df554..ba965d93d 100644 --- a/Robust.Server/Debugging/DebugDrawingManager.cs +++ b/Robust.Server/Debugging/DebugDrawingManager.cs @@ -9,10 +9,8 @@ namespace Robust.Server.Debugging { internal class DebugDrawingManager : IDebugDrawingManager { -#pragma warning disable 649 - [Dependency] private readonly IServerNetManager _net; - [Dependency] private readonly IPhysicsManager _physics; -#pragma warning restore 649 + [Dependency] private readonly IServerNetManager _net = default!; + [Dependency] private readonly IPhysicsManager _physics = default!; public void Initialize() { diff --git a/Robust.Server/GameObjects/Components/Actor/BasicActorComponent.cs b/Robust.Server/GameObjects/Components/Actor/BasicActorComponent.cs index e86640b53..d889fd3e0 100644 --- a/Robust.Server/GameObjects/Components/Actor/BasicActorComponent.cs +++ b/Robust.Server/GameObjects/Components/Actor/BasicActorComponent.cs @@ -12,8 +12,7 @@ namespace Robust.Server.GameObjects { public override string Name => "BasicActor"; - [ViewVariables] - public IPlayerSession playerSession { get; internal set; } + [ViewVariables] public IPlayerSession playerSession { get; internal set; } = default!; /// protected override void Shutdown() diff --git a/Robust.Server/GameObjects/Components/Appearance/AppearanceComponent.cs b/Robust.Server/GameObjects/Components/Appearance/AppearanceComponent.cs index 103ed8f5d..516c2c5fc 100644 --- a/Robust.Server/GameObjects/Components/Appearance/AppearanceComponent.cs +++ b/Robust.Server/GameObjects/Components/Appearance/AppearanceComponent.cs @@ -2,6 +2,7 @@ using Robust.Shared.GameObjects.Components.Appearance; using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; namespace Robust.Server.GameObjects { @@ -31,17 +32,17 @@ namespace Robust.Server.GameObjects return (T)data[key]; } - public override bool TryGetData(Enum key, out T data) + public override bool TryGetData(Enum key, [MaybeNullWhen(false)] out T data) { return TryGetData(key, out data); } - public override bool TryGetData(string key, out T data) + public override bool TryGetData(string key, [MaybeNullWhen(false)] out T data) { return TryGetData(key, out data); } - bool TryGetData(object key, out T data) + bool TryGetData(object key, [MaybeNullWhen(false)] out T data) { if (this.data.TryGetValue(key, out var dat)) { diff --git a/Robust.Server/GameObjects/Components/Container/Container.cs b/Robust.Server/GameObjects/Components/Container/Container.cs index 1904ff3fb..1a1a08032 100644 --- a/Robust.Server/GameObjects/Components/Container/Container.cs +++ b/Robust.Server/GameObjects/Components/Container/Container.cs @@ -77,7 +77,7 @@ namespace Robust.Server.GameObjects.Components.Container /// [ViewVariables] - public IEntity Owner => Manager?.Owner; + public IEntity Owner => Manager.Owner; /// [ViewVariables] @@ -96,7 +96,7 @@ namespace Robust.Server.GameObjects.Components.Container protected BaseContainer(string id, IContainerManager manager) { DebugTools.Assert(!string.IsNullOrEmpty(id)); - DebugTools.Assert(manager != null); + DebugTools.AssertNotNull(manager); ID = id; Manager = manager; @@ -195,8 +195,9 @@ namespace Robust.Server.GameObjects.Components.Container protected virtual void InternalRemove(IEntity toremove) { DebugTools.Assert(!Deleted); - DebugTools.Assert(Manager != null); - DebugTools.Assert(toremove != null && toremove.IsValid()); + DebugTools.AssertNotNull(Manager); + DebugTools.AssertNotNull(toremove); + DebugTools.Assert(toremove.IsValid()); Owner?.EntityManager.EventBus.RaiseEvent(EventSource.Local, new EntRemovedFromContainerMessage(toremove, this)); @@ -219,7 +220,6 @@ namespace Robust.Server.GameObjects.Components.Container { Manager.Dirty(); Deleted = true; - Manager = null; } } diff --git a/Robust.Server/GameObjects/Components/Container/ContainerManagerComponent.cs b/Robust.Server/GameObjects/Components/Container/ContainerManagerComponent.cs index effc713cd..28f6f7a31 100644 --- a/Robust.Server/GameObjects/Components/Container/ContainerManagerComponent.cs +++ b/Robust.Server/GameObjects/Components/Container/ContainerManagerComponent.cs @@ -2,6 +2,7 @@ using Robust.Shared.Interfaces.GameObjects; using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using Robust.Shared.GameObjects.Components.Containers; using Robust.Shared.Interfaces.GameObjects.Components; @@ -15,12 +16,10 @@ namespace Robust.Server.GameObjects.Components.Container { public sealed class ContainerManagerComponent : SharedContainerManagerComponent { -#pragma warning disable 649 - [Dependency] private readonly IReflectionManager _reflectionManager; -#pragma warning restore 649 + [Dependency] private readonly IReflectionManager _reflectionManager = default!; private readonly Dictionary EntityContainers = new Dictionary(); - private Dictionary> _entitiesWaitingResolve; + private Dictionary>? _entitiesWaitingResolve; [ViewVariables] private IEnumerable _allContainers => EntityContainers.Values; @@ -82,7 +81,7 @@ namespace Robust.Server.GameObjects.Components.Container { throw new ArgumentException($"Container with specified ID already exists: '{id}'"); } - var container = (IContainer)Activator.CreateInstance(type, id, this); + var container = (IContainer)Activator.CreateInstance(type, id, this)!; EntityContainers[id] = container; Dirty(); return container; @@ -105,7 +104,7 @@ namespace Robust.Server.GameObjects.Components.Container } /// - public override bool TryGetContainer(string id, out IContainer container) + public override bool TryGetContainer(string id, [NotNullWhen(true)] out IContainer? container) { if (!HasContainer(id)) { @@ -116,7 +115,7 @@ namespace Robust.Server.GameObjects.Components.Container return true; } - public override bool TryGetContainer(IEntity entity, out IContainer container) + public override bool TryGetContainer(IEntity entity, [NotNullWhen(true)] out IContainer? container) { foreach (var contain in EntityContainers.Values) { @@ -198,6 +197,11 @@ namespace Robust.Server.GameObjects.Components.Container _entitiesWaitingResolve = new Dictionary>(); foreach (var (key, datum) in data) { + if (datum.Type == null) + { + throw new InvalidOperationException("Container does not have type set."); + } + var type = _reflectionManager.LooseGetType(datum.Type); MakeContainer(key, type); @@ -216,11 +220,12 @@ namespace Robust.Server.GameObjects.Components.Container foreach (var (key, container) in EntityContainers) { var list = new List(container.ContainedEntities.Select(e => e.Uid)); - var data = new ContainerPrototypeData(list, container.GetType().FullName); + var data = new ContainerPrototypeData(list, container.GetType().FullName!); dict.Add(key, data); } - serializer.DataWriteFunction("containers", null, () => dict); + // ReSharper disable once RedundantTypeArgumentsOfMethod + serializer.DataWriteFunction?>("containers", null, () => dict); } } @@ -256,7 +261,7 @@ namespace Robust.Server.GameObjects.Components.Container private struct ContainerPrototypeData : IExposeData { public List Entities; - public string Type; + public string? Type; public ContainerPrototypeData(List entities, string type) { @@ -266,7 +271,7 @@ namespace Robust.Server.GameObjects.Components.Container public void ExposeData(ObjectSerializer serializer) { - serializer.DataField(ref Entities, "entities", null); + serializer.DataField(ref Entities, "entities", new List()); serializer.DataField(ref Type, "type", null); } } diff --git a/Robust.Server/GameObjects/Components/Physics/PhysicsComponent.cs b/Robust.Server/GameObjects/Components/Physics/PhysicsComponent.cs index 88ff91626..2a68246d7 100644 --- a/Robust.Server/GameObjects/Components/Physics/PhysicsComponent.cs +++ b/Robust.Server/GameObjects/Components/Physics/PhysicsComponent.cs @@ -19,7 +19,7 @@ namespace Robust.Server.GameObjects private float _mass; private Vector2 _linVelocity; private float _angVelocity; - private VirtualController _controller = null; + private VirtualController? _controller = null; private BodyStatus _status; /// @@ -99,7 +99,7 @@ namespace Robust.Server.GameObjects /// /// Represents a virtual controller acting on the physics component. /// - public override VirtualController Controller + public override VirtualController? Controller { get => _controller; } diff --git a/Robust.Server/GameObjects/Components/Renderable/SpriteComponent.cs b/Robust.Server/GameObjects/Components/Renderable/SpriteComponent.cs index cd17a1322..3faffade4 100644 --- a/Robust.Server/GameObjects/Components/Renderable/SpriteComponent.cs +++ b/Robust.Server/GameObjects/Components/Renderable/SpriteComponent.cs @@ -23,7 +23,7 @@ namespace Robust.Server.GameObjects private Vector2 _offset; private Color _color; private bool _directional; - private string _baseRSIPath; + private string? _baseRSIPath; private Angle _rotation; [ViewVariables] @@ -104,7 +104,7 @@ namespace Robust.Server.GameObjects } [ViewVariables(VVAccess.ReadWrite)] - public string BaseRSIPath + public string? BaseRSIPath { get => _baseRSIPath; set @@ -415,8 +415,8 @@ namespace Robust.Server.GameObjects serializer.ReadDataField>("layers", new List()); { - var baseState = serializer.ReadDataField("state", null); - var texturePath = serializer.ReadDataField("texture", null); + var baseState = serializer.ReadDataField("state", null); + var texturePath = serializer.ReadDataField("texture", null); if (baseState != null || texturePath != null) { diff --git a/Robust.Server/GameObjects/Components/UserInterface/ServerUserInterfaceComponent.cs b/Robust.Server/GameObjects/Components/UserInterface/ServerUserInterfaceComponent.cs index ddb7e5188..1b3490471 100644 --- a/Robust.Server/GameObjects/Components/UserInterface/ServerUserInterfaceComponent.cs +++ b/Robust.Server/GameObjects/Components/UserInterface/ServerUserInterfaceComponent.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using Robust.Server.GameObjects.EntitySystems; using Robust.Server.Interfaces.Player; @@ -54,7 +55,7 @@ namespace Robust.Server.GameObjects.Components.UserInterface return _interfaces[uiKey]; } - public bool TryGetBoundUserInterface(object uiKey, out BoundUserInterface boundUserInterface) + public bool TryGetBoundUserInterface(object uiKey, [NotNullWhen(true)] out BoundUserInterface? boundUserInterface) { return _interfaces.TryGetValue(uiKey, out boundUserInterface); } @@ -70,7 +71,7 @@ namespace Robust.Server.GameObjects.Components.UserInterface } public override void HandleNetworkMessage(ComponentMessage message, INetChannel netChannel, - ICommonSession session = null) + ICommonSession? session = null) { base.HandleNetworkMessage(message, netChannel, session); @@ -89,7 +90,7 @@ namespace Robust.Server.GameObjects.Components.UserInterface return; } - @interface.ReceiveMessage(wrapped.Message, session as IPlayerSession); + @interface.ReceiveMessage(wrapped.Message, (IPlayerSession)session); break; } } @@ -105,7 +106,7 @@ namespace Robust.Server.GameObjects.Components.UserInterface public object UiKey { get; } public ServerUserInterfaceComponent Owner { get; } private readonly HashSet _subscribedSessions = new HashSet(); - private BoundUserInterfaceState _lastState; + private BoundUserInterfaceState? _lastState; private bool _stateDirty; @@ -117,8 +118,8 @@ namespace Robust.Server.GameObjects.Components.UserInterface /// public IEnumerable SubscribedSessions => _subscribedSessions; - public event Action OnReceiveMessage; - public event Action OnClosed; + public event Action? OnReceiveMessage; + public event Action? OnClosed; public BoundUserInterface(object uiKey, ServerUserInterfaceComponent owner) { @@ -140,7 +141,7 @@ namespace Robust.Server.GameObjects.Components.UserInterface /// The player session to send this new state to. /// Set to null for sending it to every subscribed player session. /// - public void SetState(BoundUserInterfaceState state, IPlayerSession session = null) + public void SetState(BoundUserInterfaceState state, IPlayerSession? session = null) { if (session == null) { @@ -197,7 +198,7 @@ namespace Robust.Server.GameObjects.Components.UserInterface session.PlayerStatusChanged += OnSessionOnPlayerStatusChanged; } - private void OnSessionOnPlayerStatusChanged(object sender, SessionStatusEventArgs args) + private void OnSessionOnPlayerStatusChanged(object? sender, SessionStatusEventArgs args) { if (args.NewStatus == SessionStatus.Disconnected) { @@ -339,7 +340,7 @@ namespace Robust.Server.GameObjects.Components.UserInterface foreach (var playerSession in _subscribedSessions) { - if (!_playerStateOverrides.ContainsKey(playerSession)) + if (!_playerStateOverrides.ContainsKey(playerSession) && _lastState != null) { SendMessage(new UpdateBoundStateMessage(_lastState), playerSession); } diff --git a/Robust.Server/GameObjects/EntitySystems/AudioSystem.cs b/Robust.Server/GameObjects/EntitySystems/AudioSystem.cs index f61f1f778..2ca8b5ce5 100644 --- a/Robust.Server/GameObjects/EntitySystems/AudioSystem.cs +++ b/Robust.Server/GameObjects/EntitySystems/AudioSystem.cs @@ -13,7 +13,7 @@ namespace Robust.Server.GameObjects.EntitySystems { public class AudioSystem : EntitySystem { - [Dependency] private IPlayerManager _playerManager; + [Dependency] private readonly IPlayerManager _playerManager = default!; public const int AudioDistanceRange = 25; @@ -23,9 +23,9 @@ namespace Robust.Server.GameObjects.EntitySystems { private readonly uint _id; private readonly AudioSystem _audioSystem; - private readonly IEnumerable _sessions; + private readonly IEnumerable? _sessions; - internal AudioSourceServer(AudioSystem parent, uint identifier, IEnumerable sessions = null) + internal AudioSourceServer(AudioSystem parent, uint identifier, IEnumerable? sessions = null) { _audioSystem = parent; _id = identifier; @@ -37,7 +37,7 @@ namespace Robust.Server.GameObjects.EntitySystems } } - private void InternalStop(uint id, IEnumerable sessions = null) + private void InternalStop(uint id, IEnumerable? sessions = null) { var msg = new StopAudioMessageClient { @@ -64,7 +64,7 @@ namespace Robust.Server.GameObjects.EntitySystems /// The resource path to the OGG Vorbis file to play. /// /// The predicate that will be used to send the audio to players, or null to send to everyone. - public AudioSourceServer PlayGlobal(string filename, AudioParams? audioParams = null, Func predicate = null) + public AudioSourceServer PlayGlobal(string filename, AudioParams? audioParams = null, Func? predicate = null) { var id = CacheIdentifier(); var msg = new PlayAudioGlobalMessage diff --git a/Robust.Server/GameObjects/EntitySystems/EffectSystem.cs b/Robust.Server/GameObjects/EntitySystems/EffectSystem.cs index e8c924b55..592cb7f69 100644 --- a/Robust.Server/GameObjects/EntitySystems/EffectSystem.cs +++ b/Robust.Server/GameObjects/EntitySystems/EffectSystem.cs @@ -12,9 +12,7 @@ namespace Robust.Server.GameObjects.EntitySystems /// public class EffectSystem : EntitySystem { -#pragma warning disable 649 - [Dependency] private readonly IGameTiming _timing; -#pragma warning restore 649 + [Dependency] private readonly IGameTiming _timing = default!; /// /// Priority queue sorted by how soon the effect will die, we remove messages from the front of the queue during update until caught up @@ -44,8 +42,23 @@ namespace Robust.Server.GameObjects.EntitySystems /// public class EffectMessageComparer : IComparer { - public int Compare(EffectSystemMessage x, EffectSystemMessage y) + public int Compare(EffectSystemMessage? x, EffectSystemMessage? y) { + if (x == null && y == null) + { + return 0; + } + + if (y == null) + { + return 1; + } + + if (x == null) + { + return -1; + } + return y.DeathTime.CompareTo(x.DeathTime); } } diff --git a/Robust.Server/GameObjects/EntitySystems/InputSystem.cs b/Robust.Server/GameObjects/EntitySystems/InputSystem.cs index bff443ce4..a013b7808 100644 --- a/Robust.Server/GameObjects/EntitySystems/InputSystem.cs +++ b/Robust.Server/GameObjects/EntitySystems/InputSystem.cs @@ -16,9 +16,7 @@ namespace Robust.Server.GameObjects.EntitySystems /// public class InputSystem : SharedInputSystem { -#pragma warning disable 649 - [Dependency] private readonly IPlayerManager _playerManager; -#pragma warning restore 649 + [Dependency] private readonly IPlayerManager _playerManager = default!; private readonly Dictionary _playerInputs = new Dictionary(); @@ -78,7 +76,7 @@ namespace Robust.Server.GameObjects.EntitySystems return _lastProcessedInputCmd[session]; } - private void OnPlayerStatusChanged(object sender, SessionStatusEventArgs args) + private void OnPlayerStatusChanged(object? sender, SessionStatusEventArgs args) { switch (args.NewStatus) { diff --git a/Robust.Server/GameObjects/EntitySystems/PhysicsSystem.cs b/Robust.Server/GameObjects/EntitySystems/PhysicsSystem.cs index 1ffd5bdf2..a99bd79a6 100644 --- a/Robust.Server/GameObjects/EntitySystems/PhysicsSystem.cs +++ b/Robust.Server/GameObjects/EntitySystems/PhysicsSystem.cs @@ -20,17 +20,15 @@ namespace Robust.Server.GameObjects.EntitySystems [UsedImplicitly] internal class PhysicsSystem : EntitySystem { -#pragma warning disable 649 - [Dependency] private readonly IPauseManager _pauseManager; - [Dependency] private readonly ITileDefinitionManager _tileDefinitionManager; - [Dependency] private readonly IMapManager _mapManager; - [Dependency] private readonly IPhysicsManager _physicsManager; - [Dependency] private readonly IRobustRandom _random; -#pragma warning restore 649 + [Dependency] private readonly IPauseManager _pauseManager = default!; + [Dependency] private readonly ITileDefinitionManager _tileDefinitionManager = default!; + [Dependency] private readonly IMapManager _mapManager = default!; + [Dependency] private readonly IPhysicsManager _physicsManager = default!; + [Dependency] private readonly IRobustRandom _random = default!; private const float Epsilon = 1.0e-6f; - private List _collisionCache = new List(); + private readonly List _collisionCache = new List(); public PhysicsSystem() { @@ -124,10 +122,10 @@ namespace Robust.Server.GameObjects.EntitySystems foreach (var collision in _collisionCache) { // Apply onCollide behavior - var aBehaviors = (collision.A as CollidableComponent).Owner.GetAllComponents(); + var aBehaviors = ((CollidableComponent)collision.A).Owner.GetAllComponents(); foreach (var behavior in aBehaviors) { - var entity = (collision.B as CollidableComponent).Owner; + var entity = ((CollidableComponent)collision.B).Owner; if (entity.Deleted) continue; behavior.CollideWith(entity); if (collisionsWith.ContainsKey(behavior)) @@ -139,10 +137,10 @@ namespace Robust.Server.GameObjects.EntitySystems collisionsWith[behavior] = 1; } } - var bBehaviors = (collision.B as CollidableComponent).Owner.GetAllComponents(); + var bBehaviors = ((CollidableComponent)collision.B).Owner.GetAllComponents(); foreach (var behavior in bBehaviors) { - var entity = (collision.A as CollidableComponent).Owner; + var entity = ((CollidableComponent)collision.A).Owner; if (entity.Deleted) continue; behavior.CollideWith(entity); if (collisionsWith.ContainsKey(behavior)) @@ -270,7 +268,7 @@ namespace Robust.Server.GameObjects.EntitySystems if (ContainerHelpers.IsInContainer(entity) && physics.LinearVelocity != Vector2.Zero) { - entity.Transform.Parent.Owner.SendMessage(entity.Transform, new RelayMovementEntityMessage(entity)); + entity.Transform.Parent!.Owner.SendMessage(entity.Transform, new RelayMovementEntityMessage(entity)); // This prevents redundant messages from being sent if solveIterations > 1 and also simulates the entity "colliding" against the locker door when it opens. physics.LinearVelocity = Vector2.Zero; } @@ -290,9 +288,9 @@ namespace Robust.Server.GameObjects.EntitySystems if (penetration > allowance) { var correction = collision.Normal * Math.Abs(penetration) * percent; - if (collision.APhysics != null && !(collision.APhysics as PhysicsComponent).Anchored && !collision.APhysics.Deleted) + if (collision.APhysics != null && !((PhysicsComponent)collision.APhysics).Anchored && !collision.APhysics.Deleted) collision.APhysics.Owner.Transform.WorldPosition -= correction; - if (collision.BPhysics != null && !(collision.BPhysics as PhysicsComponent).Anchored && !collision.BPhysics.Deleted) + if (collision.BPhysics != null && !((PhysicsComponent)collision.BPhysics).Anchored && !collision.BPhysics.Deleted) collision.BPhysics.Owner.Transform.WorldPosition += correction; } } diff --git a/Robust.Server/GameObjects/ServerEntityManager.cs b/Robust.Server/GameObjects/ServerEntityManager.cs index 793fb66d2..42e39b9b7 100644 --- a/Robust.Server/GameObjects/ServerEntityManager.cs +++ b/Robust.Server/GameObjects/ServerEntityManager.cs @@ -36,13 +36,9 @@ namespace Robust.Server.GameObjects #region IEntityManager Members -#pragma warning disable 649 - [Dependency] private readonly IMapManager _mapManager; - - [Dependency] private readonly IPauseManager _pauseManager; - - [Dependency] private readonly IConfigurationManager _configurationManager; -#pragma warning restore 649 + [Dependency] private readonly IMapManager _mapManager = default!; + [Dependency] private readonly IPauseManager _pauseManager = default!; + [Dependency] private readonly IConfigurationManager _configurationManager = default!; private float? _maxUpdateRangeCache; @@ -60,13 +56,13 @@ namespace Robust.Server.GameObjects } /// - public override IEntity CreateEntityUninitialized(string prototypeName) + public override IEntity CreateEntityUninitialized(string? prototypeName) { return CreateEntityServer(prototypeName); } /// - public override IEntity CreateEntityUninitialized(string prototypeName, GridCoordinates coordinates) + public override IEntity CreateEntityUninitialized(string? prototypeName, GridCoordinates coordinates) { var newEntity = CreateEntityServer(prototypeName); if (coordinates.GridID != GridId.Invalid) @@ -80,7 +76,7 @@ namespace Robust.Server.GameObjects } /// - public override IEntity CreateEntityUninitialized(string prototypeName, MapCoordinates coordinates) + public override IEntity CreateEntityUninitialized(string? prototypeName, MapCoordinates coordinates) { var newEntity = CreateEntityServer(prototypeName); newEntity.Transform.AttachParent(_mapManager.GetMapEntity(coordinates.MapId)); @@ -88,7 +84,7 @@ namespace Robust.Server.GameObjects return newEntity; } - private Entity CreateEntityServer(string prototypeName) + private Entity CreateEntityServer(string? prototypeName) { var entity = CreateEntity(prototypeName); @@ -116,7 +112,7 @@ namespace Robust.Server.GameObjects } /// - public override IEntity SpawnEntity(string protoName, GridCoordinates coordinates) + public override IEntity SpawnEntity(string? protoName, GridCoordinates coordinates) { if (coordinates.GridID == GridId.Invalid) throw new InvalidOperationException($"Tried to spawn entity {protoName} onto invalid grid."); @@ -133,7 +129,7 @@ namespace Robust.Server.GameObjects } /// - public override IEntity SpawnEntity(string protoName, MapCoordinates coordinates) + public override IEntity SpawnEntity(string? protoName, MapCoordinates coordinates) { var entity = CreateEntityUninitialized(protoName, coordinates); InitializeAndStartEntity((Entity) entity); @@ -141,7 +137,7 @@ namespace Robust.Server.GameObjects } /// - public override IEntity SpawnEntityNoMapInit(string protoName, GridCoordinates coordinates) + public override IEntity SpawnEntityNoMapInit(string? protoName, GridCoordinates coordinates) { var newEnt = CreateEntityUninitialized(protoName, coordinates); InitializeAndStartEntity((Entity) newEnt); @@ -149,7 +145,7 @@ namespace Robust.Server.GameObjects } /// - public List GetEntityStates(GameTick fromTick) + public List? GetEntityStates(GameTick fromTick) { var stateEntities = new List(); foreach (var entity in AllEntities) @@ -338,7 +334,7 @@ namespace Robust.Server.GameObjects = new PlayerSeenEntityStatesResources(false); /// - public List UpdatePlayerSeenEntityStates(GameTick fromTick, IPlayerSession player, float range) + public List? UpdatePlayerSeenEntityStates(GameTick fromTick, IPlayerSession player, float range) { var playerEnt = player.AttachedEntity; if (playerEnt == null) @@ -698,7 +694,7 @@ namespace Robust.Server.GameObjects _deletionHistory.Add((CurrentTick, e.Uid)); } - public List GetDeletedEntities(GameTick fromTick) + public List? GetDeletedEntities(GameTick fromTick) { var list = new List(); foreach (var (tick, id) in _deletionHistory) @@ -834,7 +830,7 @@ namespace Robust.Server.GameObjects #endregion IEntityManager Members - IEntity IServerEntityManagerInternal.AllocEntity(string prototypeName, EntityUid? uid) + IEntity IServerEntityManagerInternal.AllocEntity(string? prototypeName, EntityUid? uid) { return AllocEntity(prototypeName, uid); } @@ -844,7 +840,7 @@ namespace Robust.Server.GameObjects return new EntityUid(_nextServerEntityUid++); } - void IServerEntityManagerInternal.FinishEntityLoad(IEntity entity, IEntityLoadContext context) + void IServerEntityManagerInternal.FinishEntityLoad(IEntity entity, IEntityLoadContext? context) { LoadEntity((Entity) entity, context); } @@ -897,13 +893,13 @@ namespace Robust.Server.GameObjects { // Can't be null since it's returned by GetNetComponents // ReSharper disable once PossibleInvalidOperationException - changed.Add(ComponentChanged.Added(comp.NetID.Value, comp.Name)); + changed.Add(ComponentChanged.Added(comp.NetID!.Value, comp.Name)); } else if (comp.Deleted && comp.LastModifiedTick >= fromTick) { // Can't be null since it's returned by GetNetComponents // ReSharper disable once PossibleInvalidOperationException - changed.Add(ComponentChanged.Removed(comp.NetID.Value)); + changed.Add(ComponentChanged.Removed(comp.NetID!.Value)); } } diff --git a/Robust.Server/GameObjects/ServerEntityNetworkManager.cs b/Robust.Server/GameObjects/ServerEntityNetworkManager.cs index d2b215fcc..dfc74dc46 100644 --- a/Robust.Server/GameObjects/ServerEntityNetworkManager.cs +++ b/Robust.Server/GameObjects/ServerEntityNetworkManager.cs @@ -21,18 +21,16 @@ namespace Robust.Server.GameObjects /// public class ServerEntityNetworkManager : IServerEntityNetworkManager, IPostInjectInit { -#pragma warning disable 649 - [Dependency] private readonly IServerNetManager _networkManager; - [Dependency] private readonly IGameTiming _gameTiming; - [Dependency] private readonly IPlayerManager _playerManager; - [Dependency] private readonly IConfigurationManager _configurationManager; -#pragma warning restore 649 + [Dependency] private readonly IServerNetManager _networkManager = default!; + [Dependency] private readonly IGameTiming _gameTiming = default!; + [Dependency] private readonly IPlayerManager _playerManager = default!; + [Dependency] private readonly IConfigurationManager _configurationManager = default!; /// - public event EventHandler ReceivedComponentMessage; + public event EventHandler? ReceivedComponentMessage; /// - public event EventHandler ReceivedSystemMessage; + public event EventHandler? ReceivedSystemMessage; private readonly PriorityQueue _queue = new PriorityQueue(new MessageSequenceComparer()); @@ -65,7 +63,7 @@ namespace Robust.Server.GameObjects } /// - public void SendComponentNetworkMessage(INetChannel channel, IEntity entity, IComponent component, + public void SendComponentNetworkMessage(INetChannel? channel, IEntity entity, IComponent component, ComponentMessage message) { if (_networkManager.IsClient) @@ -157,13 +155,13 @@ namespace Robust.Server.GameObjects case EntityMessageType.SystemMessage: var msg = message.SystemMessage; var sessionType = typeof(EntitySessionMessage<>).MakeGenericType(msg.GetType()); - var sessionMsg = Activator.CreateInstance(sessionType, new EntitySessionEventArgs(player), msg); + var sessionMsg = Activator.CreateInstance(sessionType, new EntitySessionEventArgs(player), msg)!; ReceivedSystemMessage?.Invoke(this, sessionMsg); return; } } - private void OnPlayerStatusChanged(object sender, SessionStatusEventArgs args) + private void OnPlayerStatusChanged(object? sender, SessionStatusEventArgs args) { switch (args.NewStatus) { @@ -179,12 +177,12 @@ namespace Robust.Server.GameObjects private sealed class MessageSequenceComparer : IComparer { - public int Compare(MsgEntity x, MsgEntity y) + public int Compare(MsgEntity? x, MsgEntity? y) { DebugTools.AssertNotNull(x); DebugTools.AssertNotNull(y); - var cmp = y.SourceTick.CompareTo(x.SourceTick); + var cmp = y!.SourceTick.CompareTo(x!.SourceTick); if (cmp != 0) { return cmp; diff --git a/Robust.Server/GameStates/ServerGameStateManager.cs b/Robust.Server/GameStates/ServerGameStateManager.cs index 75a40dbb6..12941e2aa 100644 --- a/Robust.Server/GameStates/ServerGameStateManager.cs +++ b/Robust.Server/GameStates/ServerGameStateManager.cs @@ -27,16 +27,14 @@ namespace Robust.Server.GameStates private readonly Dictionary _ackedStates = new Dictionary(); private GameTick _lastOldestAck = GameTick.Zero; -#pragma warning disable 649 - [Dependency] private readonly IServerEntityManager _entityManager; - [Dependency] private readonly IGameTiming _gameTiming; - [Dependency] private readonly IServerNetManager _networkManager; - [Dependency] private readonly IPlayerManager _playerManager; - [Dependency] private readonly IMapManager _mapManager; - [Dependency] private readonly IEntitySystemManager _systemManager; - [Dependency] private readonly IServerEntityNetworkManager _entityNetworkManager; - [Dependency] private readonly IConfigurationManager _configurationManager; -#pragma warning restore 649 + [Dependency] private readonly IServerEntityManager _entityManager = default!; + [Dependency] private readonly IGameTiming _gameTiming = default!; + [Dependency] private readonly IServerNetManager _networkManager = default!; + [Dependency] private readonly IPlayerManager _playerManager = default!; + [Dependency] private readonly IMapManager _mapManager = default!; + [Dependency] private readonly IEntitySystemManager _systemManager = default!; + [Dependency] private readonly IServerEntityNetworkManager _entityNetworkManager = default!; + [Dependency] private readonly IConfigurationManager _configurationManager = default!; public bool PvsEnabled => _configurationManager.GetCVar("net.pvs"); @@ -53,7 +51,7 @@ namespace Robust.Server.GameStates _configurationManager.RegisterCVar("net.maxupdaterange", 12.5f, CVar.ARCHIVE); } - private void HandleClientConnected(object sender, NetChannelArgs e) + private void HandleClientConnected(object? sender, NetChannelArgs e) { if (!_ackedStates.ContainsKey(e.Channel.ConnectionId)) _ackedStates.Add(e.Channel.ConnectionId, GameTick.Zero); @@ -61,7 +59,7 @@ namespace Robust.Server.GameStates _ackedStates[e.Channel.ConnectionId] = GameTick.Zero; } - private void HandleClientDisconnect(object sender, NetChannelArgs e) + private void HandleClientDisconnect(object? sender, NetChannelArgs e) { _entityManager.DropPlayerState(_playerManager.GetSessionById(e.Channel.SessionId)); diff --git a/Robust.Server/Interfaces/Console/IClientCommand.cs b/Robust.Server/Interfaces/Console/IClientCommand.cs index 2546dce22..551dd3b9d 100644 --- a/Robust.Server/Interfaces/Console/IClientCommand.cs +++ b/Robust.Server/Interfaces/Console/IClientCommand.cs @@ -14,6 +14,6 @@ namespace Robust.Server.Interfaces.Console /// The console that executed this command. /// The player that ran this command. This is null if the command was ran by the server console. /// An array of all the parsed arguments. - void Execute(IConsoleShell shell, IPlayerSession player, string[] args); + void Execute(IConsoleShell shell, IPlayerSession? player, string[] args); } } diff --git a/Robust.Server/Interfaces/Console/IConsoleShell.cs b/Robust.Server/Interfaces/Console/IConsoleShell.cs index dc7eee572..610013247 100644 --- a/Robust.Server/Interfaces/Console/IConsoleShell.cs +++ b/Robust.Server/Interfaces/Console/IConsoleShell.cs @@ -30,14 +30,14 @@ namespace Robust.Server.Interfaces.Console /// /// Remote player to send the text message to. If this is null, the text is sent to the local console. /// Text message to send. - void SendText(IPlayerSession session, string text); + void SendText(IPlayerSession? session, string? text); /// /// Sends a text string to the remote console. /// /// Net channel to send the text string to. /// Text message to send. - void SendText(INetChannel target, string text); + void SendText(INetChannel target, string? text); /// /// Execute a command string on the local shell. @@ -50,7 +50,7 @@ namespace Robust.Server.Interfaces.Console /// /// Session of the remote player. If this is null, the command is executed as the local console. /// Command string to execute. - void ExecuteCommand(IPlayerSession player, string command); + void ExecuteCommand(IPlayerSession? player, string command); /// /// Elevates a player shell from user group to administrator group. diff --git a/Robust.Server/Interfaces/GameObjects/IServerEntityManager.cs b/Robust.Server/Interfaces/GameObjects/IServerEntityManager.cs index 61769a76b..4f2a8fa62 100644 --- a/Robust.Server/Interfaces/GameObjects/IServerEntityManager.cs +++ b/Robust.Server/Interfaces/GameObjects/IServerEntityManager.cs @@ -12,18 +12,18 @@ namespace Robust.Server.Interfaces.GameObjects /// /// Gets all entity states that have been modified after and including the provided tick. /// - [CanBeNull] List GetEntityStates(GameTick fromTick); + List? GetEntityStates(GameTick fromTick); /// /// Gets all entity states within an AABB that have been modified after and including the provided tick. /// - [CanBeNull] List UpdatePlayerSeenEntityStates(GameTick fromTick, IPlayerSession player, float range); + List? UpdatePlayerSeenEntityStates(GameTick fromTick, IPlayerSession player, float range); // Keep track of deleted entities so we can sync deletions with the client. /// /// Gets a list of all entity UIDs that were deleted between and now. /// - [CanBeNull] List GetDeletedEntities(GameTick fromTick); + List? GetDeletedEntities(GameTick fromTick); /// /// Remove deletion history. diff --git a/Robust.Server/Interfaces/GameObjects/IServerEntityManagerInternal.cs b/Robust.Server/Interfaces/GameObjects/IServerEntityManagerInternal.cs index c9fd6084d..a602b2142 100644 --- a/Robust.Server/Interfaces/GameObjects/IServerEntityManagerInternal.cs +++ b/Robust.Server/Interfaces/GameObjects/IServerEntityManagerInternal.cs @@ -8,9 +8,9 @@ namespace Robust.Server.Interfaces.GameObjects // These methods are used by the map loader to do multi-stage entity construction during map load. // I would recommend you refer to the MapLoader for usage. - IEntity AllocEntity(string prototypeName, EntityUid? uid = null); + IEntity AllocEntity(string? prototypeName, EntityUid? uid = null); - void FinishEntityLoad(IEntity entity, IEntityLoadContext context = null); + void FinishEntityLoad(IEntity entity, IEntityLoadContext? context = null); void FinishEntityInitialization(IEntity entity); diff --git a/Robust.Server/Interfaces/IBaseServer.cs b/Robust.Server/Interfaces/IBaseServer.cs index 9d7d26f46..f161d561b 100644 --- a/Robust.Server/Interfaces/IBaseServer.cs +++ b/Robust.Server/Interfaces/IBaseServer.cs @@ -34,7 +34,7 @@ namespace Robust.Server.Interfaces /// Shuts down the server, and ends the process. /// /// Reason why the server was shut down. - void Shutdown(string reason); + void Shutdown(string? reason); /// /// Enters the main loop of the server. This functions blocks until the server is shut down. diff --git a/Robust.Server/Interfaces/Maps/IMapLoader.cs b/Robust.Server/Interfaces/Maps/IMapLoader.cs index 0a048bfce..8013c2b8f 100644 --- a/Robust.Server/Interfaces/Maps/IMapLoader.cs +++ b/Robust.Server/Interfaces/Maps/IMapLoader.cs @@ -4,7 +4,7 @@ namespace Robust.Server.Interfaces.Maps { public interface IMapLoader { - IMapGrid LoadBlueprint(MapId mapId, string path); + IMapGrid? LoadBlueprint(MapId mapId, string path); void SaveBlueprint(GridId gridId, string yamlPath); void LoadMap(MapId mapId, string path); diff --git a/Robust.Server/Interfaces/Placement/IPlacementManager.cs b/Robust.Server/Interfaces/Placement/IPlacementManager.cs index b78c3afb3..553b65935 100644 --- a/Robust.Server/Interfaces/Placement/IPlacementManager.cs +++ b/Robust.Server/Interfaces/Placement/IPlacementManager.cs @@ -63,6 +63,6 @@ namespace Robust.Server.Interfaces.Placement /// void RevokeAllBuildPermissions(IEntity mob); - Func AllowPlacementFunc { get; set; } + Func? AllowPlacementFunc { get; set; } } } diff --git a/Robust.Server/Interfaces/Player/IPlayerData.cs b/Robust.Server/Interfaces/Player/IPlayerData.cs index 51a6aff82..4d168fcab 100644 --- a/Robust.Server/Interfaces/Player/IPlayerData.cs +++ b/Robust.Server/Interfaces/Player/IPlayerData.cs @@ -22,6 +22,6 @@ namespace Robust.Server.Interfaces.Player /// Custom field that content can assign anything to. /// Go wild. /// - object ContentDataUncast { get; set; } + object? ContentDataUncast { get; set; } } } diff --git a/Robust.Server/Interfaces/Player/IPlayerManager.cs b/Robust.Server/Interfaces/Player/IPlayerManager.cs index 8f26a38b0..e591c4e07 100644 --- a/Robust.Server/Interfaces/Player/IPlayerManager.cs +++ b/Robust.Server/Interfaces/Player/IPlayerManager.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using Robust.Server.Player; using Robust.Shared.Enums; using Robust.Shared.GameStates; @@ -49,9 +50,9 @@ namespace Robust.Server.Interfaces.Player IPlayerSession GetSessionByChannel(INetChannel channel); - bool TryGetSessionByChannel(INetChannel channel, out IPlayerSession session); + bool TryGetSessionByChannel(INetChannel channel, [NotNullWhen(true)] out IPlayerSession? session); - bool TryGetSessionById(NetSessionId sessionId, out IPlayerSession session); + bool TryGetSessionById(NetSessionId sessionId, [NotNullWhen(true)] out IPlayerSession? session); /// /// Checks to see if a PlayerIndex is a valid session. @@ -59,7 +60,7 @@ namespace Robust.Server.Interfaces.Player bool ValidSessionId(NetSessionId index); IPlayerData GetPlayerData(NetSessionId sessionId); - bool TryGetPlayerData(NetSessionId sessionId, out IPlayerData data); + bool TryGetPlayerData(NetSessionId sessionId, [NotNullWhen(true)] out IPlayerData? data); bool HasPlayerData(NetSessionId sessionId); IEnumerable GetAllPlayerData(); @@ -68,6 +69,6 @@ namespace Robust.Server.Interfaces.Player List GetPlayersInRange(GridCoordinates worldPos, int range); List GetPlayersBy(Func predicate); List GetAllPlayers(); - List GetPlayerStates(GameTick fromTick); + List? GetPlayerStates(GameTick fromTick); } } diff --git a/Robust.Server/Maps/MapLoader.cs b/Robust.Server/Maps/MapLoader.cs index 882088550..1d63dec7d 100644 --- a/Robust.Server/Maps/MapLoader.cs +++ b/Robust.Server/Maps/MapLoader.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.IO; using Robust.Server.Interfaces.GameObjects; using Robust.Server.Interfaces.Maps; @@ -30,23 +31,13 @@ namespace Robust.Server.Maps { private const int MapFormatVersion = 2; - [Dependency] -#pragma warning disable 649 - private readonly IResourceManager _resMan; - - [Dependency] - private readonly IMapManagerInternal _mapManager; - - [Dependency] - private readonly ITileDefinitionManager _tileDefinitionManager; - - [Dependency] - private readonly IServerEntityManagerInternal _serverEntityManager; - - [Dependency] private readonly IPauseManager _pauseManager; - [Dependency] private readonly IComponentManager _componentManager; - [Dependency] private readonly IPrototypeManager _prototypeManager; -#pragma warning restore 649 + [Dependency] private readonly IResourceManager _resMan = default!; + [Dependency] private readonly IMapManagerInternal _mapManager = default!; + [Dependency] private readonly ITileDefinitionManager _tileDefinitionManager = default!; + [Dependency] private readonly IServerEntityManagerInternal _serverEntityManager = default!; + [Dependency] private readonly IPauseManager _pauseManager = default!; + [Dependency] private readonly IComponentManager _componentManager = default!; + [Dependency] private readonly IPrototypeManager _prototypeManager = default!; /// public void SaveBlueprint(GridId gridId, string yamlPath) @@ -74,7 +65,7 @@ namespace Robust.Server.Maps } /// - public IMapGrid LoadBlueprint(MapId mapId, string path) + public IMapGrid? LoadBlueprint(MapId mapId, string path) { TextReader reader; var resPath = new ResourcePath(path).ToRootedPath(); @@ -233,12 +224,12 @@ namespace Robust.Server.Maps private readonly YamlMappingNode RootNode; private readonly MapId TargetMap; - private Dictionary CurrentReadingEntityComponents; + private Dictionary? CurrentReadingEntityComponents; - private string CurrentWritingComponent; - private IEntity CurrentWritingEntity; + private string? CurrentWritingComponent; + private IEntity? CurrentWritingEntity; - private Dictionary _tileMap; + private Dictionary? _tileMap; public bool MapIsPostInit { get; private set; } @@ -340,7 +331,7 @@ namespace Robust.Server.Maps { foreach (var (entity, data) in _entitiesToDeserialize) { - if (!data.TryGetNode("components", out YamlSequenceNode componentList)) + if (!data.TryGetNode("components", out YamlSequenceNode? componentList)) { continue; } @@ -443,7 +434,7 @@ namespace Robust.Server.Maps _mapManager, TargetMap, ref newId, (YamlMappingNode)grid["settings"], (YamlSequenceNode)grid["chunks"], - _tileMap, + _tileMap!, _tileDefinitionManager ); @@ -476,7 +467,7 @@ namespace Robust.Server.Maps var entities = RootNode.GetNode("entities"); foreach (var entityDef in entities.Cast()) { - string type = null; + string? type = null; if (entityDef.TryGetNode("type", out var typeNode)) { type = typeNode.AsString(); @@ -500,7 +491,7 @@ namespace Robust.Server.Maps foreach (var (entity, data) in _entitiesToDeserialize) { CurrentReadingEntityComponents = new Dictionary(); - if (data.TryGetNode("components", out YamlSequenceNode componentList)) + if (data.TryGetNode("components", out YamlSequenceNode? componentList)) { foreach (var compData in componentList) { @@ -665,7 +656,7 @@ namespace Robust.Server.Maps } } - public override bool TryNodeToType(YamlNode node, Type type, out object obj) + public override bool TryNodeToType(YamlNode node, Type type, [NotNullWhen(true)] out object? obj) { if (type == typeof(GridId)) { @@ -722,7 +713,7 @@ namespace Robust.Server.Maps return false; } - public override bool TryTypeToNode(object obj, out YamlNode node) + public override bool TryTypeToNode(object obj, [NotNullWhen(true)] out YamlNode? node) { switch (obj) { @@ -742,7 +733,7 @@ namespace Robust.Server.Maps if (!EntityUidMap.TryGetValue(entityUid, out var entityUidMapped)) { // Terrible hack to mute this warning on the grids themselves when serializing blueprints. - if (!IsBlueprintMode || !CurrentWritingEntity.HasComponent() || + if (!IsBlueprintMode || !CurrentWritingEntity!.HasComponent() || CurrentWritingComponent != "Transform") { Logger.WarningS("map", "Cannot write entity UID '{0}'.", entityUid); @@ -774,40 +765,41 @@ namespace Robust.Server.Maps } // Create custom object serializers that will correctly allow data to be overriden by the map file. - ObjectSerializer IEntityLoadContext.GetComponentSerializer(string componentName, YamlMappingNode protoData) + ObjectSerializer IEntityLoadContext.GetComponentSerializer(string componentName, YamlMappingNode? protoData) { if (CurrentReadingEntityComponents == null) { throw new InvalidOperationException(); } + var list = new List(); if (CurrentReadingEntityComponents.TryGetValue(componentName, out var mapping)) { - var list = new List {mapping}; - if (protoData != null) - { - list.Add(protoData); - } - return YamlObjectSerializer.NewReader(list, this); + list.Add(mapping); } - return YamlObjectSerializer.NewReader(protoData, this); + if (protoData != null) + { + list.Add(protoData); + } + + return YamlObjectSerializer.NewReader(list, this); } public IEnumerable GetExtraComponentTypes() { - return CurrentReadingEntityComponents.Keys; + return CurrentReadingEntityComponents!.Keys; } public override bool IsValueDefault(string field, T value, WithFormat format) { - if (CurrentWritingEntity.Prototype == null) + if (CurrentWritingEntity!.Prototype == null) { // No prototype, can't be default. return false; } - if (!CurrentWritingEntity.Prototype.Components.TryGetValue(CurrentWritingComponent, out var compData)) + if (!CurrentWritingEntity.Prototype.Components.TryGetValue(CurrentWritingComponent!, out var compData)) { // This component was added mid-game. return false; diff --git a/Robust.Server/Placement/PlacementManager.cs b/Robust.Server/Placement/PlacementManager.cs index 839d9a616..b2f407989 100644 --- a/Robust.Server/Placement/PlacementManager.cs +++ b/Robust.Server/Placement/PlacementManager.cs @@ -18,13 +18,11 @@ namespace Robust.Server.Placement { public class PlacementManager : IPlacementManager { -#pragma warning disable 649 - [Dependency] private readonly ITileDefinitionManager _tileDefinitionManager; - [Dependency] private readonly IServerNetManager _networkManager; - [Dependency] private readonly IPlayerManager _playerManager; - [Dependency] private readonly IServerEntityManager _entityManager; - [Dependency] private readonly IMapManager _mapManager; -#pragma warning restore 649 + [Dependency] private readonly ITileDefinitionManager _tileDefinitionManager = default!; + [Dependency] private readonly IServerNetManager _networkManager = default!; + [Dependency] private readonly IPlayerManager _playerManager = default!; + [Dependency] private readonly IServerEntityManager _entityManager = default!; + [Dependency] private readonly IMapManager _mapManager = default!; //TO-DO: Expand for multiple permission per mob? // Add support for multi-use placeables (tiles etc.). @@ -32,7 +30,7 @@ namespace Robust.Server.Placement //Holds build permissions for all mobs. A list of mobs and the objects they're allowed to request and how. One permission per mob. - public Func AllowPlacementFunc { get; set; } + public Func? AllowPlacementFunc { get; set; } #region IPlacementManager Members @@ -46,7 +44,7 @@ namespace Robust.Server.Placement /// public void HandleNetMessage(MsgPlacement msg) { - if (!AllowPlacementFunc(msg)) + if (AllowPlacementFunc != null && !AllowPlacementFunc(msg)) { return; } @@ -134,7 +132,7 @@ namespace Robust.Server.Placement var gridsInArea = _mapManager.FindGridsIntersecting(mapId, gridSearchBox); - IMapGrid closest = null; + IMapGrid? closest = null; float distance = float.PositiveInfinity; Box2 intersect = new Box2(); foreach (var grid in gridsInArea) @@ -353,7 +351,7 @@ namespace Robust.Server.Placement #endregion IPlacementManager Members - private PlacementInformation GetPermission(EntityUid uid, string alignOpt) + private PlacementInformation? GetPermission(EntityUid uid, string alignOpt) { foreach (var buildPermission in BuildPermissions) { diff --git a/Robust.Server/Player/PlayerData.cs b/Robust.Server/Player/PlayerData.cs index f6a6f568b..5adce6694 100644 --- a/Robust.Server/Player/PlayerData.cs +++ b/Robust.Server/Player/PlayerData.cs @@ -15,6 +15,6 @@ namespace Robust.Server.Player public NetSessionId SessionId { get; } [ViewVariables] - public object ContentDataUncast { get; set; } + public object? ContentDataUncast { get; set; } } } diff --git a/Robust.Server/Player/PlayerManager.cs b/Robust.Server/Player/PlayerManager.cs index 64a0d7d12..a41e076c8 100644 --- a/Robust.Server/Player/PlayerManager.cs +++ b/Robust.Server/Player/PlayerManager.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Prometheus; @@ -29,15 +30,13 @@ namespace Robust.Server.Player private static readonly Gauge PlayerCountMetric = Metrics .CreateGauge("robust_player_count", "Number of players on the server."); -#pragma warning disable 649 - [Dependency] private readonly IBaseServer _baseServer; - [Dependency] private readonly IGameTiming _timing; - [Dependency] private readonly IServerNetManager _network; - [Dependency] private readonly IReflectionManager _reflectionManager; - [Dependency] private readonly IMapManager _mapManager; -#pragma warning restore 649 + [Dependency] private readonly IBaseServer _baseServer = default!; + [Dependency] private readonly IGameTiming _timing = default!; + [Dependency] private readonly IServerNetManager _network = default!; + [Dependency] private readonly IReflectionManager _reflectionManager = default!; + [Dependency] private readonly IMapManager _mapManager = default!; - public BoundKeyMap KeyMap { get; private set; } + public BoundKeyMap KeyMap { get; private set; } = default!; private GameTick _lastStateUpdate; @@ -46,9 +45,9 @@ namespace Robust.Server.Player /// /// Active sessions of connected clients to the server. /// - private Dictionary _sessions; + private readonly Dictionary _sessions = new Dictionary(); - private Dictionary _playerData; + private readonly Dictionary _playerData = new Dictionary(); /// public int PlayerCount @@ -71,7 +70,7 @@ namespace Robust.Server.Player public int MaxPlayers { get; private set; } = 32; /// - public event EventHandler PlayerStatusChanged; + public event EventHandler? PlayerStatusChanged; /// public void Initialize(int maxPlayers) @@ -80,8 +79,6 @@ namespace Robust.Server.Player KeyMap.PopulateKeyFunctionsMap(); MaxPlayers = maxPlayers; - _sessions = new Dictionary(maxPlayers); - _playerData = new Dictionary(maxPlayers); _network.RegisterNetMessage(MsgServerInfoReq.NAME, HandleWelcomeMessageReq); _network.RegisterNetMessage(MsgServerInfo.NAME); @@ -94,7 +91,7 @@ namespace Robust.Server.Player } IPlayerSession IPlayerManager.GetSessionByChannel(INetChannel channel) => GetSessionByChannel(channel); - public bool TryGetSessionByChannel(INetChannel channel, out IPlayerSession session) + public bool TryGetSessionByChannel(INetChannel channel, [NotNullWhen(true)] out IPlayerSession? session) { _sessionsLock.EnterReadLock(); try @@ -156,7 +153,7 @@ namespace Robust.Server.Player } } - public bool TryGetSessionById(NetSessionId sessionId, out IPlayerSession session) + public bool TryGetSessionById(NetSessionId sessionId, [NotNullWhen(true)] out IPlayerSession? session) { _sessionsLock.EnterReadLock(); try @@ -276,7 +273,7 @@ namespace Robust.Server.Player /// /// /// - public List GetPlayerStates(GameTick fromTick) + public List? GetPlayerStates(GameTick fromTick) { if (_lastStateUpdate < fromTick) { @@ -296,7 +293,7 @@ namespace Robust.Server.Player } } - private void OnConnecting(object sender, NetConnectingArgs args) + private void OnConnecting(object? sender, NetConnectingArgs args) { if (PlayerCount >= _baseServer.MaxPlayers) args.Deny = true; @@ -307,7 +304,7 @@ namespace Robust.Server.Player /// /// /// - private void NewSession(object sender, NetChannelArgs args) + private void NewSession(object? sender, NetChannelArgs args) { if (!_playerData.TryGetValue(args.Channel.SessionId, out var data)) { @@ -339,7 +336,7 @@ namespace Robust.Server.Player /// /// Ends a clients session, and disconnects them. /// - private void EndSession(object sender, NetChannelArgs args) + private void EndSession(object? sender, NetChannelArgs args) { var session = GetSessionByChannel(args.Channel); @@ -419,7 +416,7 @@ namespace Robust.Server.Player return _playerData[sessionId]; } - public bool TryGetPlayerData(NetSessionId sessionId, out IPlayerData data) + public bool TryGetPlayerData(NetSessionId sessionId, [NotNullWhen(true)] out IPlayerData? data) { if (_playerData.TryGetValue(sessionId, out var _data)) { diff --git a/Robust.Server/Player/PlayerSession.cs b/Robust.Server/Player/PlayerSession.cs index b50502fd2..37595fc28 100644 --- a/Robust.Server/Player/PlayerSession.cs +++ b/Robust.Server/Player/PlayerSession.cs @@ -37,7 +37,7 @@ namespace Robust.Server.Player [ViewVariables] public INetChannel ConnectedClient { get; } - [ViewVariables] public IEntity AttachedEntity { get; private set; } + [ViewVariables] public IEntity? AttachedEntity { get; private set; } [ViewVariables] public EntityUid? AttachedEntityUid => AttachedEntity?.Uid; @@ -79,7 +79,7 @@ namespace Robust.Server.Player [ViewVariables] public IPlayerData Data => _data; /// - public event EventHandler PlayerStatusChanged; + public event EventHandler? PlayerStatusChanged; /// public void AttachToEntity(IEntity a) diff --git a/Robust.Server/Program.cs b/Robust.Server/Program.cs index 08f45bd39..af8262f54 100644 --- a/Robust.Server/Program.cs +++ b/Robust.Server/Program.cs @@ -60,7 +60,7 @@ namespace Robust.Server return; } - string strVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); + string strVersion = Assembly.GetExecutingAssembly().GetName().Version!.ToString(); Logger.Info("Server Version " + strVersion + " -> Ready"); IoCManager.Resolve().MaybeStart(); diff --git a/Robust.Server/Robust.Server.csproj b/Robust.Server/Robust.Server.csproj index 143d3a88e..ed48505fd 100644 --- a/Robust.Server/Robust.Server.csproj +++ b/Robust.Server/Robust.Server.csproj @@ -8,6 +8,7 @@ Exe false ../bin/Server + enable diff --git a/Robust.Server/ServerSignalHandler.cs b/Robust.Server/ServerSignalHandler.cs index aa09945c3..2d4a25e8e 100644 --- a/Robust.Server/ServerSignalHandler.cs +++ b/Robust.Server/ServerSignalHandler.cs @@ -6,9 +6,7 @@ namespace Robust.Server { internal sealed class ServerSignalHandler : SignalHandler { -#pragma warning disable 649 - [Dependency] private readonly IBaseServer _baseServer; -#pragma warning restore 649 + [Dependency] private readonly IBaseServer _baseServer = default!; protected override void OnReceiveTerminationSignal(string signal) { diff --git a/Robust.Server/ServerStatus/StatusHost.Handlers.cs b/Robust.Server/ServerStatus/StatusHost.Handlers.cs index aa3e9bfc1..bbd598b19 100644 --- a/Robust.Server/ServerStatus/StatusHost.Handlers.cs +++ b/Robust.Server/ServerStatus/StatusHost.Handlers.cs @@ -86,7 +86,7 @@ namespace Robust.Server.ServerStatus var downloadUrlWindows = _configurationManager.GetCVar("build.download_url_windows"); - JObject buildInfo; + JObject? buildInfo; if (downloadUrlWindows == null) { diff --git a/Robust.Server/ServerStatus/StatusHost.HttpContext.cs b/Robust.Server/ServerStatus/StatusHost.HttpContext.cs index 4b292557a..697d278ec 100644 --- a/Robust.Server/ServerStatus/StatusHost.HttpContext.cs +++ b/Robust.Server/ServerStatus/StatusHost.HttpContext.cs @@ -13,7 +13,7 @@ namespace Robust.Server.ServerStatus internal sealed partial class StatusHost { - private HttpContextFactory _ctxFactory; + private HttpContextFactory _ctxFactory = default!; public HttpContext CreateContext(IFeatureCollection contextFeatures) => _ctxFactory.Create(contextFeatures); @@ -45,7 +45,7 @@ namespace Robust.Server.ServerStatus } IoCManager.Clear(); - ILogManager logMgr = null; + ILogManager? logMgr = null; WaitSync(() => { logMgr = IoCManager.Resolve(); diff --git a/Robust.Server/ServerStatus/StatusHost.Lifetime.cs b/Robust.Server/ServerStatus/StatusHost.Lifetime.cs index 262c5b8aa..0b0b7e80c 100644 --- a/Robust.Server/ServerStatus/StatusHost.Lifetime.cs +++ b/Robust.Server/ServerStatus/StatusHost.Lifetime.cs @@ -15,7 +15,7 @@ namespace Robust.Server.ServerStatus public void StopApplication() => Dispose(); - private static CancellationTokenSource _cancelled; + private static CancellationTokenSource? _cancelled; private static CancellationToken GetCancelledToken() { if (_cancelled == null) diff --git a/Robust.Server/ServerStatus/StatusHost.Sync.cs b/Robust.Server/ServerStatus/StatusHost.Sync.cs index e5051d469..f709e89e1 100644 --- a/Robust.Server/ServerStatus/StatusHost.Sync.cs +++ b/Robust.Server/ServerStatus/StatusHost.Sync.cs @@ -7,7 +7,7 @@ namespace Robust.Server.ServerStatus internal sealed partial class StatusHost { - private SynchronizationContext _syncCtx; + private SynchronizationContext _syncCtx = default!; public void DeferSync(Action a) { @@ -16,7 +16,7 @@ namespace Robust.Server.ServerStatus return; } - _syncCtx.Post(x => ((Action) x)(), a); + _syncCtx.Post(x => ((Action) x!)(), a); } public void WaitSync(Action a, CancellationToken ct = default) diff --git a/Robust.Server/ServerStatus/StatusHost.cs b/Robust.Server/ServerStatus/StatusHost.cs index 965513903..41ae26e9b 100644 --- a/Robust.Server/ServerStatus/StatusHost.cs +++ b/Robust.Server/ServerStatus/StatusHost.cs @@ -42,11 +42,9 @@ namespace Robust.Server.ServerStatus private readonly List _handlers = new List(); -#pragma warning disable 649 - [Dependency] private IConfigurationManager _configurationManager; -#pragma warning restore 649 + [Dependency] private readonly IConfigurationManager _configurationManager = default!; - private KestrelServer _server; + private KestrelServer _server = default!; public Task ProcessRequestAsync(HttpContext context) { @@ -84,9 +82,9 @@ namespace Robust.Server.ServerStatus return Task.CompletedTask; } - public event Action OnStatusRequest; + public event Action? OnStatusRequest; - public event Action OnInfoRequest; + public event Action? OnInfoRequest; public void AddHandler(StatusHostHandler handler) => _handlers.Add(handler); @@ -123,7 +121,7 @@ namespace Robust.Server.ServerStatus _server.StartAsync(this, ApplicationStopping); - _syncCtx = SynchronizationContext.Current; + _syncCtx = SynchronizationContext.Current!; if (_syncCtx == null) { @@ -161,7 +159,7 @@ namespace Robust.Server.ServerStatus private void RegisterCVars() { - BuildInfo info = null; + BuildInfo? info = null; try { var buildInfo = File.ReadAllText(PathHelpers.ExecutableRelativeFile("build.json")); @@ -173,7 +171,7 @@ namespace Robust.Server.ServerStatus _configurationManager.RegisterCVar("status.enabled", true, CVar.ARCHIVE); _configurationManager.RegisterCVar("status.bind", "*:1212", CVar.ARCHIVE); - _configurationManager.RegisterCVar("status.connectaddress", null, CVar.ARCHIVE); + _configurationManager.RegisterCVar("status.connectaddress", null, CVar.ARCHIVE); _configurationManager.RegisterCVar("build.fork_id", info?.ForkId, CVar.ARCHIVE); _configurationManager.RegisterCVar("build.version", info?.Version, CVar.ARCHIVE); @@ -185,20 +183,21 @@ namespace Robust.Server.ServerStatus _configurationManager.RegisterCVar("build.hash_linux", info?.Hashes.Linux, CVar.ARCHIVE); } - + [JsonObject(ItemRequired = Required.DisallowNull)] private sealed class BuildInfo { - [JsonProperty("hashes")] public PlatformData Hashes { get; set; } - [JsonProperty("downloads")] public PlatformData Downloads { get; set; } - [JsonProperty("fork_id")] public string ForkId { get; set; } - [JsonProperty("version")] public string Version { get; set; } + [JsonProperty("hashes")] public PlatformData Hashes { get; set; } = default!; + [JsonProperty("downloads")] public PlatformData Downloads { get; set; } = default!; + [JsonProperty("fork_id")] public string ForkId { get; set; } = default!; + [JsonProperty("version")] public string Version { get; set; } = default!; } + [JsonObject(ItemRequired = Required.DisallowNull)] private sealed class PlatformData { - [JsonProperty("windows")] public string Windows { get; set; } - [JsonProperty("linux")] public string Linux { get; set; } - [JsonProperty("macos")] public string MacOS { get; set; } + [JsonProperty("windows")] public string Windows { get; set; } = default!; + [JsonProperty("linux")] public string Linux { get; set; } = default!; + [JsonProperty("macos")] public string MacOS { get; set; } = default!; } } diff --git a/Robust.Server/ServerStatus/StatusHostHelpers.cs b/Robust.Server/ServerStatus/StatusHostHelpers.cs index d09f9a3ee..04a284413 100644 --- a/Robust.Server/ServerStatus/StatusHostHelpers.cs +++ b/Robust.Server/ServerStatus/StatusHostHelpers.cs @@ -1,3 +1,4 @@ +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Net; using System.Net.Http; @@ -33,6 +34,7 @@ namespace Robust.Server.ServerStatus writer.Write(text); } + [return: MaybeNull] public static T GetFromJson(this HttpRequest request) { using var streamReader = new StreamReader(request.Body, EncodingHelpers.UTF8); diff --git a/Robust.Server/Timing/PauseManager.cs b/Robust.Server/Timing/PauseManager.cs index a95b04c08..6f7b03c2c 100644 --- a/Robust.Server/Timing/PauseManager.cs +++ b/Robust.Server/Timing/PauseManager.cs @@ -12,10 +12,8 @@ namespace Robust.Server.Timing { internal sealed class PauseManager : IPauseManager, IPostInjectInit { -#pragma warning disable 649 - [Dependency] private IMapManager _mapManager; - [Dependency] private IEntityManager _entityManager; -#pragma warning restore 649 + [Dependency] private readonly IMapManager _mapManager = default!; + [Dependency] private readonly IEntityManager _entityManager = default!; [ViewVariables] private readonly HashSet _pausedMaps = new HashSet(); [ViewVariables] private readonly HashSet _unInitializedMaps = new HashSet(); diff --git a/Robust.Server/ViewVariables/Traits/ViewVariablesTraitEntity.cs b/Robust.Server/ViewVariables/Traits/ViewVariablesTraitEntity.cs index d75b2afee..bf1c1892f 100644 --- a/Robust.Server/ViewVariables/Traits/ViewVariablesTraitEntity.cs +++ b/Robust.Server/ViewVariables/Traits/ViewVariablesTraitEntity.cs @@ -14,7 +14,7 @@ namespace Robust.Server.ViewVariables.Traits _entity = (IEntity) Session.Object; } - public override ViewVariablesBlob DataRequest(ViewVariablesRequest viewVariablesRequest) + public override ViewVariablesBlob? DataRequest(ViewVariablesRequest viewVariablesRequest) { if (viewVariablesRequest is ViewVariablesRequestEntityComponents) { diff --git a/Robust.Server/ViewVariables/Traits/ViewVariablesTraitEnumerable.cs b/Robust.Server/ViewVariables/Traits/ViewVariablesTraitEnumerable.cs index c446743a8..830dff4b2 100644 --- a/Robust.Server/ViewVariables/Traits/ViewVariablesTraitEnumerable.cs +++ b/Robust.Server/ViewVariables/Traits/ViewVariablesTraitEnumerable.cs @@ -1,13 +1,14 @@ using System.Collections; using System.Collections.Generic; +using Robust.Shared.Utility; using Robust.Shared.ViewVariables; namespace Robust.Server.ViewVariables.Traits { internal sealed class ViewVariablesTraitEnumerable : ViewVariablesTrait { - private readonly List _cache = new List(); - private IEnumerator _enumerator; + private readonly List _cache = new List(); + private IEnumerator? _enumerator; private readonly IEnumerable _enumerable; private bool Ended => _enumerator == null; @@ -17,7 +18,7 @@ namespace Robust.Server.ViewVariables.Traits _refresh(); } - public override ViewVariablesBlob DataRequest(ViewVariablesRequest viewVariablesRequest) + public override ViewVariablesBlob? DataRequest(ViewVariablesRequest viewVariablesRequest) { if (viewVariablesRequest is ViewVariablesRequestEnumerable requestEnumerable) { @@ -26,7 +27,7 @@ namespace Robust.Server.ViewVariables.Traits _refresh(); } _cacheTo(requestEnumerable.ToIndex); - var list = new List(); + var list = new List(); for (var i = requestEnumerable.FromIndex; i < _cache.Count && i <= requestEnumerable.ToIndex; i++) { @@ -39,7 +40,7 @@ namespace Robust.Server.ViewVariables.Traits return base.DataRequest(viewVariablesRequest); } - public override bool TryGetRelativeObject(object property, out object value) + public override bool TryGetRelativeObject(object property, out object? value) { if (!(property is ViewVariablesEnumerableIndexSelector selector)) { @@ -66,6 +67,8 @@ namespace Robust.Server.ViewVariables.Traits private void _cacheTo(int index) { + DebugTools.AssertNotNull(_enumerator); + if (Ended || index < _cache.Count) { return; @@ -73,12 +76,12 @@ namespace Robust.Server.ViewVariables.Traits while (_cache.Count <= index) { - if (!_enumerator.MoveNext()) + if (!_enumerator!.MoveNext()) { _enumerator = null; break; } - _cache.Add(_enumerator.Current); + _cache.Add(_enumerator!.Current); } } diff --git a/Robust.Server/ViewVariables/Traits/ViewVariablesTraitMembers.cs b/Robust.Server/ViewVariables/Traits/ViewVariablesTraitMembers.cs index ad5626563..6b3685353 100644 --- a/Robust.Server/ViewVariables/Traits/ViewVariablesTraitMembers.cs +++ b/Robust.Server/ViewVariables/Traits/ViewVariablesTraitMembers.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Reflection; using Robust.Shared.Log; using Robust.Shared.Utility; @@ -15,7 +16,7 @@ namespace Robust.Server.ViewVariables.Traits { } - public override ViewVariablesBlob DataRequest(ViewVariablesRequest messageRequestMeta) + public override ViewVariablesBlob? DataRequest(ViewVariablesRequest messageRequestMeta) { if (!(messageRequestMeta is ViewVariablesRequestMembers)) { @@ -83,7 +84,7 @@ namespace Robust.Server.ViewVariables.Traits return blob; } - public override bool TryGetRelativeObject(object property, out object value) + public override bool TryGetRelativeObject(object property, out object? value) { if (!(property is ViewVariablesMemberSelector selector)) { @@ -150,7 +151,7 @@ namespace Robust.Server.ViewVariables.Traits case PropertyInfo propertyInfo: try { - propertyInfo.GetSetMethod(true).Invoke(Session.Object, new[] {value}); + propertyInfo.GetSetMethod(true)!.Invoke(Session.Object, new[] {value}); return true; } catch (Exception e) diff --git a/Robust.Server/ViewVariables/ViewVariablesHost.cs b/Robust.Server/ViewVariables/ViewVariablesHost.cs index 100e21947..8cfeaaacd 100644 --- a/Robust.Server/ViewVariables/ViewVariablesHost.cs +++ b/Robust.Server/ViewVariables/ViewVariablesHost.cs @@ -17,15 +17,13 @@ namespace Robust.Server.ViewVariables { internal class ViewVariablesHost : ViewVariablesManagerShared, IViewVariablesHost { -#pragma warning disable 649 - [Dependency] private readonly INetManager _netManager; - [Dependency] private readonly IEntityManager _entityManager; - [Dependency] private readonly IPlayerManager _playerManager; - [Dependency] private readonly IComponentManager _componentManager; - [Dependency] private readonly IConGroupController _groupController; - [Dependency] private readonly IRobustSerializer _robustSerializer; - [Dependency] private readonly IReflectionManager _reflectionManager; -#pragma warning restore 649 + [Dependency] private readonly INetManager _netManager = default!; + [Dependency] private readonly IEntityManager _entityManager = default!; + [Dependency] private readonly IPlayerManager _playerManager = default!; + [Dependency] private readonly IComponentManager _componentManager = default!; + [Dependency] private readonly IConGroupController _groupController = default!; + [Dependency] private readonly IRobustSerializer _robustSerializer = default!; + [Dependency] private readonly IReflectionManager _reflectionManager = default!; private readonly Dictionary _sessions = new Dictionary(); @@ -145,7 +143,7 @@ namespace Robust.Server.ViewVariables return; } - object value; + object? value; try { if (!relSession.TryGetRelativeObject(sessionRelativeSelector.PropertyIndex, out value)) diff --git a/Robust.Server/ViewVariables/ViewVariablesSession.cs b/Robust.Server/ViewVariables/ViewVariablesSession.cs index b5faf686f..7c5e3c286 100644 --- a/Robust.Server/ViewVariables/ViewVariablesSession.cs +++ b/Robust.Server/ViewVariables/ViewVariablesSession.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using Robust.Server.ViewVariables.Traits; using Robust.Shared.Interfaces.Serialization; using Robust.Shared.Network; @@ -53,7 +54,7 @@ namespace Robust.Server.ViewVariables } } - public ViewVariablesBlob DataRequest(ViewVariablesRequest messageRequestMeta) + public ViewVariablesBlob? DataRequest(ViewVariablesRequest messageRequestMeta) { if (messageRequestMeta is ViewVariablesRequestMetadata) { @@ -89,7 +90,7 @@ namespace Robust.Server.ViewVariables } } - public bool TryGetRelativeObject(object[] propertyIndex, out object value) + public bool TryGetRelativeObject(object[] propertyIndex, out object? value) { foreach (var trait in _traits) { diff --git a/Robust.Server/ViewVariables/ViewVariablesTrait.cs b/Robust.Server/ViewVariables/ViewVariablesTrait.cs index bd48ee36c..15e000f88 100644 --- a/Robust.Server/ViewVariables/ViewVariablesTrait.cs +++ b/Robust.Server/ViewVariables/ViewVariablesTrait.cs @@ -1,3 +1,4 @@ +using System.Diagnostics.CodeAnalysis; using Robust.Server.ViewVariables.Traits; using Robust.Shared.Network.Messages; using Robust.Shared.Utility; @@ -31,7 +32,7 @@ namespace Robust.Server.ViewVariables /// If this trait doesn't care about this request, a meaningful blob otherwise. /// No, not the game mode, the other kind of blob. /// - public virtual ViewVariablesBlob DataRequest(ViewVariablesRequest viewVariablesRequest) + public virtual ViewVariablesBlob? DataRequest(ViewVariablesRequest viewVariablesRequest) { return null; } @@ -55,7 +56,7 @@ namespace Robust.Server.ViewVariables /// /// The to-be value of the object if this trait managed to retrieve it. /// True if we retrieved a value, false otherwise. - public virtual bool TryGetRelativeObject(object property, out object value) + public virtual bool TryGetRelativeObject(object property, out object? value) { value = default; return false; @@ -81,7 +82,7 @@ namespace Robust.Server.ViewVariables /// /// Swaps values like references over to reference tokens to prevent issues. /// - protected object MakeValueNetSafe(object value) + protected object? MakeValueNetSafe(object? value) { if (value == null) { diff --git a/Robust.Shared/ContentPack/ResourceManager.cs b/Robust.Shared/ContentPack/ResourceManager.cs index 008c03a65..2afbe6016 100644 --- a/Robust.Shared/ContentPack/ResourceManager.cs +++ b/Robust.Shared/ContentPack/ResourceManager.cs @@ -36,7 +36,7 @@ namespace Robust.Shared.ContentPack public IWritableDirProvider UserData { get; private set; } = default!; /// - public void Initialize(string userData) + public void Initialize(string? userData) { if (userData != null) { diff --git a/Robust.Shared/GameObjects/Components/Appearance/SharedAppearanceComponent.cs b/Robust.Shared/GameObjects/Components/Appearance/SharedAppearanceComponent.cs index 71d95263f..994cb2824 100644 --- a/Robust.Shared/GameObjects/Components/Appearance/SharedAppearanceComponent.cs +++ b/Robust.Shared/GameObjects/Components/Appearance/SharedAppearanceComponent.cs @@ -1,6 +1,7 @@ using Robust.Shared.Serialization; using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; namespace Robust.Shared.GameObjects.Components.Appearance { @@ -21,8 +22,8 @@ namespace Robust.Shared.GameObjects.Components.Appearance public abstract T GetData(string key); public abstract T GetData(Enum key); - public abstract bool TryGetData(string key, out T data); - public abstract bool TryGetData(Enum key, out T data); + public abstract bool TryGetData(string key, [MaybeNullWhen(false)] out T data); + public abstract bool TryGetData(Enum key, [MaybeNullWhen(false)] out T data); [Serializable, NetSerializable] protected class AppearanceComponentState : ComponentState diff --git a/Robust.Shared/GameObjects/Components/Containers/SharedContainerManagerComponent.cs b/Robust.Shared/GameObjects/Components/Containers/SharedContainerManagerComponent.cs index 24b88a39a..0ffaa5187 100644 --- a/Robust.Shared/GameObjects/Components/Containers/SharedContainerManagerComponent.cs +++ b/Robust.Shared/GameObjects/Components/Containers/SharedContainerManagerComponent.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using Robust.Shared.Interfaces.GameObjects; using Robust.Shared.Interfaces.GameObjects.Components; using Robust.Shared.Serialization; @@ -15,10 +16,10 @@ namespace Robust.Shared.GameObjects.Components.Containers public abstract bool Remove(IEntity entity); public abstract IContainer GetContainer(string id); public abstract bool HasContainer(string id); - public abstract bool TryGetContainer(string id, out IContainer container); + public abstract bool TryGetContainer(string id, [NotNullWhen(true)] out IContainer? container); /// - public abstract bool TryGetContainer(IEntity entity, out IContainer container); + public abstract bool TryGetContainer(IEntity entity, [NotNullWhen(true)] out IContainer? container); public abstract bool ContainsEntity(IEntity entity); public abstract void ForceRemove(IEntity entity); diff --git a/Robust.Shared/GameObjects/Components/Renderable/SharedSpriteComponent.cs b/Robust.Shared/GameObjects/Components/Renderable/SharedSpriteComponent.cs index 09cd9efce..52a1c5765 100644 --- a/Robust.Shared/GameObjects/Components/Renderable/SharedSpriteComponent.cs +++ b/Robust.Shared/GameObjects/Components/Renderable/SharedSpriteComponent.cs @@ -27,7 +27,7 @@ namespace Robust.Shared.GameObjects.Components.Renderable public readonly Vector2 Offset; public readonly Color Color; public readonly bool Directional; - public readonly string BaseRsiPath; + public readonly string? BaseRsiPath; public readonly List Layers; public readonly uint RenderOrder; @@ -39,7 +39,7 @@ namespace Robust.Shared.GameObjects.Components.Renderable Vector2 offset, Color color, bool directional, - string baseRsiPath, + string? baseRsiPath, List layers, uint renderOrder) : base(NetIDs.SPRITE) diff --git a/Robust.Shared/GameObjects/EntityManager.cs b/Robust.Shared/GameObjects/EntityManager.cs index c64299d52..ad869abe5 100644 --- a/Robust.Shared/GameObjects/EntityManager.cs +++ b/Robust.Shared/GameObjects/EntityManager.cs @@ -216,7 +216,7 @@ namespace Robust.Shared.GameObjects /// /// Allocates an entity and stores it but does not load components or do initialization. /// - private protected Entity AllocEntity(string prototypeName, EntityUid? uid = null) + private protected Entity AllocEntity(string? prototypeName, EntityUid? uid = null) { EntityPrototype? prototype = null; if (!string.IsNullOrWhiteSpace(prototypeName)) @@ -267,7 +267,7 @@ namespace Robust.Shared.GameObjects /// /// Allocates an entity and loads components but does not do initialization. /// - private protected Entity CreateEntity(string prototypeName, EntityUid? uid = null) + private protected Entity CreateEntity(string? prototypeName, EntityUid? uid = null) { if (prototypeName == null) return AllocEntity(uid); @@ -287,7 +287,7 @@ namespace Robust.Shared.GameObjects } } - private protected void LoadEntity(Entity entity, IEntityLoadContext context) + private protected void LoadEntity(Entity entity, IEntityLoadContext? context) { EntityPrototype.LoadEntity(entity.Prototype, entity, ComponentFactory, context); } diff --git a/Robust.Shared/GameObjects/EntitySystemMessages/EntParentChangedMessage.cs b/Robust.Shared/GameObjects/EntitySystemMessages/EntParentChangedMessage.cs index b3fe25ee3..4905a26fa 100644 --- a/Robust.Shared/GameObjects/EntitySystemMessages/EntParentChangedMessage.cs +++ b/Robust.Shared/GameObjects/EntitySystemMessages/EntParentChangedMessage.cs @@ -10,7 +10,7 @@ namespace Robust.Shared.GameObjects.EntitySystemMessages /// /// Entity that was adopted. The transform component has a property with the new parent. /// - public IEntity? Entity { get; } + public IEntity Entity { get; } /// /// Old parent that abandoned the Entity. @@ -22,7 +22,7 @@ namespace Robust.Shared.GameObjects.EntitySystemMessages /// /// /// - public EntParentChangedMessage(IEntity? entity, IEntity? oldParent) + public EntParentChangedMessage(IEntity entity, IEntity? oldParent) { Entity = entity; OldParent = oldParent; diff --git a/Robust.Shared/GameStates/GameState.cs b/Robust.Shared/GameStates/GameState.cs index 89dc0ec66..e72d41c85 100644 --- a/Robust.Shared/GameStates/GameState.cs +++ b/Robust.Shared/GameStates/GameState.cs @@ -25,7 +25,7 @@ namespace Robust.Shared.GameStates /// /// Constructor! /// - public GameState(GameTick fromSequence, GameTick toSequence, uint lastInput, EntityState[] entities, PlayerState[] players, EntityUid[] deletions, GameStateMapData mapData) + public GameState(GameTick fromSequence, GameTick toSequence, uint lastInput, EntityState[]? entities, PlayerState[]? players, EntityUid[]? deletions, GameStateMapData? mapData) { FromSequence = fromSequence; ToSequence = toSequence; @@ -41,11 +41,9 @@ namespace Robust.Shared.GameStates public readonly uint LastProcessedInput; - [CanBeNull] - public readonly EntityState[] EntityStates; - public readonly PlayerState[] PlayerStates; - [CanBeNull] - public readonly EntityUid[] EntityDeletions; - public readonly GameStateMapData MapData; + public readonly EntityState[]? EntityStates; + public readonly PlayerState[]? PlayerStates; + public readonly EntityUid[]? EntityDeletions; + public readonly GameStateMapData? MapData; } } diff --git a/Robust.Shared/Interfaces/GameObjects/Components/IContainerManager.cs b/Robust.Shared/Interfaces/GameObjects/Components/IContainerManager.cs index c25a23b09..4fcc215b7 100644 --- a/Robust.Shared/Interfaces/GameObjects/Components/IContainerManager.cs +++ b/Robust.Shared/Interfaces/GameObjects/Components/IContainerManager.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; namespace Robust.Shared.Interfaces.GameObjects.Components { @@ -47,7 +48,7 @@ namespace Robust.Shared.Interfaces.GameObjects.Components /// The ID to look up. /// The container if it was found, null if not found. /// True if the container was found, false otherwise. - bool TryGetContainer(string id, out IContainer container); + bool TryGetContainer(string id, [NotNullWhen(true)] out IContainer? container); /// /// Attempt to retrieve a container that contains a specific entity. @@ -56,7 +57,7 @@ namespace Robust.Shared.Interfaces.GameObjects.Components /// The container if it was found, null if not found. /// True if the container was found, false otherwise. /// True if the container was found, false otherwise. - bool TryGetContainer(IEntity entity, out IContainer container); + bool TryGetContainer(IEntity entity, [NotNullWhen(true)] out IContainer? container); bool ContainsEntity(IEntity entity); diff --git a/Robust.Shared/Interfaces/Physics/IPhysicsManager.cs b/Robust.Shared/Interfaces/Physics/IPhysicsManager.cs index 20bf5a5f2..3f8d5b562 100644 --- a/Robust.Shared/Interfaces/Physics/IPhysicsManager.cs +++ b/Robust.Shared/Interfaces/Physics/IPhysicsManager.cs @@ -123,7 +123,6 @@ namespace Robust.Shared.Interfaces.Physics get; } - [CanBeNull] public RayCastResults? Results { get; } public float MaxLength { get; } } @@ -159,15 +158,15 @@ namespace Robust.Shared.Interfaces.Physics public readonly Vector2 Normal; public readonly ICollidableComponent A; public readonly ICollidableComponent B; - [CanBeNull] public SharedPhysicsComponent APhysics; - [CanBeNull] public SharedPhysicsComponent BPhysics; + public SharedPhysicsComponent? APhysics; + public SharedPhysicsComponent? BPhysics; public float InvAMass => 1 / APhysics?.Mass ?? 0.0f; public float InvBMass => 1 / BPhysics?.Mass ?? 0.0f; public bool Unresolved => Vector2.Dot(RelativeVelocity, Normal) < 0; - public Manifold(ICollidableComponent A, ICollidableComponent B, [CanBeNull] SharedPhysicsComponent aPhysics, [CanBeNull] SharedPhysicsComponent bPhysics) + public Manifold(ICollidableComponent A, ICollidableComponent B, SharedPhysicsComponent? aPhysics, SharedPhysicsComponent? bPhysics) { var physicsManager = IoCManager.Resolve(); this.A = A; diff --git a/Robust.Shared/Interfaces/Resources/IResourceManager.cs b/Robust.Shared/Interfaces/Resources/IResourceManager.cs index fca27c7a2..bd00f4292 100644 --- a/Robust.Shared/Interfaces/Resources/IResourceManager.cs +++ b/Robust.Shared/Interfaces/Resources/IResourceManager.cs @@ -141,8 +141,11 @@ namespace Robust.Shared.Interfaces.Resources /// /// Sets the manager up so that the base game can run. /// - /// The directory to use for user data. - void Initialize(string userData); + /// + /// The directory to use for user data. + /// If null, a virtual temporary file system is used instead. + /// + void Initialize(string? userData); /// /// Mounts a single stream as a content file. Useful for unit testing. diff --git a/Robust.Shared/Physics/PhysicsManager.cs b/Robust.Shared/Physics/PhysicsManager.cs index 5d034cb08..04b1b038c 100644 --- a/Robust.Shared/Physics/PhysicsManager.cs +++ b/Robust.Shared/Physics/PhysicsManager.cs @@ -87,7 +87,7 @@ namespace Robust.Shared.Physics var normal = CalculateNormal(manifold.A, manifold.B); var rV = aP != null ? bP != null ? bP.LinearVelocity - aP.LinearVelocity : -aP.LinearVelocity - : bP.LinearVelocity; + : bP!.LinearVelocity; var vAlongNormal = Vector2.Dot(rV, normal); if (vAlongNormal > 0) diff --git a/Robust.Shared/Physics/SharedPhysicsComponent.cs b/Robust.Shared/Physics/SharedPhysicsComponent.cs index d2ede9cf9..9410b23d4 100644 --- a/Robust.Shared/Physics/SharedPhysicsComponent.cs +++ b/Robust.Shared/Physics/SharedPhysicsComponent.cs @@ -19,8 +19,7 @@ namespace Robust.Shared.Physics public abstract bool OnGround { get; } - [CanBeNull] - public abstract VirtualController Controller { get; } + public abstract VirtualController? Controller { get; } } [Serializable, NetSerializable] public enum BodyStatus diff --git a/Robust.Shared/Physics/VirtualController.cs b/Robust.Shared/Physics/VirtualController.cs index 7b75c319d..2600a24ba 100644 --- a/Robust.Shared/Physics/VirtualController.cs +++ b/Robust.Shared/Physics/VirtualController.cs @@ -6,7 +6,7 @@ namespace Robust.Shared.Physics /// public abstract class VirtualController { - public abstract SharedPhysicsComponent ControlledComponent { set; } + public abstract SharedPhysicsComponent? ControlledComponent { set; } /// /// Modify a physics component before processing impulses diff --git a/Robust.Shared/Players/ICommonSession.cs b/Robust.Shared/Players/ICommonSession.cs index d679957dd..db6e374c0 100644 --- a/Robust.Shared/Players/ICommonSession.cs +++ b/Robust.Shared/Players/ICommonSession.cs @@ -13,6 +13,6 @@ namespace Robust.Shared.Players /// SessionStatus Status { get; set; } - IEntity AttachedEntity { get; } + IEntity? AttachedEntity { get; } } }