diff --git a/Content.Client/GameObjects/Components/CloningPod/CloningPodBoundUserInterface.cs b/Content.Client/GameObjects/Components/CloningPod/CloningPodBoundUserInterface.cs index 6d5376f90c..f0ad47c23b 100644 --- a/Content.Client/GameObjects/Components/CloningPod/CloningPodBoundUserInterface.cs +++ b/Content.Client/GameObjects/Components/CloningPod/CloningPodBoundUserInterface.cs @@ -20,7 +20,7 @@ namespace Content.Client.GameObjects.Components.CloningPod base.Open(); - _window = new CloningPodWindow(new Dictionary()); + _window = new CloningPodWindow(new Dictionary()); _window.OnClose += Close; _window.CloneButton.OnPressed += _ => { diff --git a/Content.Client/GameObjects/Components/CloningPod/CloningPodWindow.cs b/Content.Client/GameObjects/Components/CloningPod/CloningPodWindow.cs index 3ff67bbb99..b09d600d57 100644 --- a/Content.Client/GameObjects/Components/CloningPod/CloningPodWindow.cs +++ b/Content.Client/GameObjects/Components/CloningPod/CloningPodWindow.cs @@ -11,7 +11,7 @@ namespace Content.Client.GameObjects.Components.CloningPod { public sealed class CloningPodWindow : SS14Window { - private Dictionary _scanManager; + private Dictionary _scanManager; private readonly VBoxContainer _scanList; public readonly Button CloneButton; @@ -21,11 +21,11 @@ namespace Content.Client.GameObjects.Components.CloningPod private readonly ProgressBar _cloningProgressBar; private readonly Label _mindState; - private CloningPodBoundUserInterfaceState _lastUpdate = null!; + private CloningPodBoundUserInterfaceState? _lastUpdate; public int? SelectedScan; - public CloningPodWindow(Dictionary scanManager) + public CloningPodWindow(Dictionary scanManager) { SetSize = MinSize = (250, 300); _scanManager = scanManager; @@ -120,7 +120,7 @@ namespace Content.Client.GameObjects.Components.CloningPod { var button = new CloningScanButton { - Scan = scan.Value, + Scan = scan.Value ?? string.Empty, Id = scan.Key }; button.ActualButton.OnToggled += OnItemButtonToggled; diff --git a/Content.Client/GameObjects/Components/Interactable/MultiToolComponent.cs b/Content.Client/GameObjects/Components/Interactable/MultiToolComponent.cs index 6bc7651194..354cc053db 100644 --- a/Content.Client/GameObjects/Components/Interactable/MultiToolComponent.cs +++ b/Content.Client/GameObjects/Components/Interactable/MultiToolComponent.cs @@ -20,7 +20,7 @@ namespace Content.Client.GameObjects.Components.Interactable [ViewVariables(VVAccess.ReadWrite)] private bool _uiUpdateNeeded; [ViewVariables] public bool StatusShowBehavior => _statusShowBehavior; - [ViewVariables] public ToolQuality Behavior => _behavior; + [ViewVariables] public ToolQuality? Behavior => _behavior; public override string Name => "MultiTool"; public override uint? NetID => ContentNetIDs.MULTITOOLS; @@ -63,11 +63,7 @@ namespace Content.Client.GameObjects.Components.Interactable _parent._uiUpdateNeeded = false; - if(!_parent.StatusShowBehavior) - _label.SetMarkup(string.Empty); - else - _label.SetMarkup(_parent.Behavior.ToString()); - + _label.SetMarkup(_parent.StatusShowBehavior ? _parent.Behavior.ToString() ?? string.Empty : string.Empty); } } } diff --git a/Content.Client/GameObjects/Components/Mobs/HumanoidAppearanceComponent.cs b/Content.Client/GameObjects/Components/Mobs/HumanoidAppearanceComponent.cs index 2d0bbe9689..96aa3360c7 100644 --- a/Content.Client/GameObjects/Components/Mobs/HumanoidAppearanceComponent.cs +++ b/Content.Client/GameObjects/Components/Mobs/HumanoidAppearanceComponent.cs @@ -41,7 +41,7 @@ namespace Content.Client.GameObjects.Components.Mobs private void UpdateLooks() { - if (Appearance is null || + if (Appearance is null! || !Owner.TryGetComponent(out SpriteComponent? sprite)) { return; diff --git a/Content.Client/UserInterface/RoundEndSummaryWindow.cs b/Content.Client/UserInterface/RoundEndSummaryWindow.cs index c4b3726e3e..06d90285ff 100644 --- a/Content.Client/UserInterface/RoundEndSummaryWindow.cs +++ b/Content.Client/UserInterface/RoundEndSummaryWindow.cs @@ -74,20 +74,23 @@ namespace Content.Client.UserInterface { var playerInfoText = new RichTextLabel(); - if (playerInfo.Observer) + if (playerInfo.PlayerICName != null) { - playerInfoText.SetMarkup( - Loc.GetString("[color=gray]{0}[/color] was [color=lightblue]{1}[/color], an observer.", - playerInfo.PlayerOOCName, playerInfo.PlayerICName)); - } - else - { - //TODO: On Hover display a popup detailing more play info. - //For example: their antag goals and if they completed them sucessfully. - var icNameColor = playerInfo.Antag ? "red" : "white"; - playerInfoText.SetMarkup( - Loc.GetString("[color=gray]{0}[/color] was [color={1}]{2}[/color] playing role of [color=orange]{3}[/color].", - playerInfo.PlayerOOCName, icNameColor, playerInfo.PlayerICName, Loc.GetString(playerInfo.Role))); + if (playerInfo.Observer) + { + playerInfoText.SetMarkup( + Loc.GetString("[color=gray]{0}[/color] was [color=lightblue]{1}[/color], an observer.", + playerInfo.PlayerOOCName, playerInfo.PlayerICName)); + } + else + { + //TODO: On Hover display a popup detailing more play info. + //For example: their antag goals and if they completed them sucessfully. + var icNameColor = playerInfo.Antag ? "red" : "white"; + playerInfoText.SetMarkup( + Loc.GetString("[color=gray]{0}[/color] was [color={1}]{2}[/color] playing role of [color=orange]{3}[/color].", + playerInfo.PlayerOOCName, icNameColor, playerInfo.PlayerICName, Loc.GetString(playerInfo.Role))); + } } innerScrollContainer.AddChild(playerInfoText); } diff --git a/Content.IntegrationTests/DummyGameTicker.cs b/Content.IntegrationTests/DummyGameTicker.cs index d4b10a106a..699d66f1a2 100644 --- a/Content.IntegrationTests/DummyGameTicker.cs +++ b/Content.IntegrationTests/DummyGameTicker.cs @@ -1,10 +1,12 @@ +#nullable enable using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using Content.Server.GameTicking; using Content.Server.Interfaces.GameTicking; -using Content.Shared.Roles; -using Content.Shared.Preferences; using Content.Server.Mobs; +using Content.Shared.Preferences; +using Content.Shared.Roles; using Robust.Server.Player; using Robust.Shared.GameObjects; using Robust.Shared.Map; @@ -60,7 +62,7 @@ namespace Content.IntegrationTests { } - public void MakeJoinGame(IPlayerSession player, string jobId) + public void MakeJoinGame(IPlayerSession player, string? jobId) { } @@ -76,7 +78,7 @@ namespace Content.IntegrationTests public EntityCoordinates GetJobSpawnPoint(string jobId) => EntityCoordinates.Invalid; public EntityCoordinates GetObserverSpawnPoint() => EntityCoordinates.Invalid; - public void EquipStartingGear(IEntity entity, StartingGearPrototype startingGear, HumanoidCharacterProfile profile) + public void EquipStartingGear(IEntity entity, StartingGearPrototype startingGear, HumanoidCharacterProfile? profile) { } @@ -85,7 +87,12 @@ namespace Content.IntegrationTests return new(); } - public bool HasGameRule(Type type) + public bool HasGameRule(string? type) + { + return false; + } + + public bool HasGameRule(Type? type) { return false; } @@ -96,7 +103,7 @@ namespace Content.IntegrationTests public IEnumerable ActiveGameRules { get; } = Array.Empty(); - public bool TryGetPreset(string name, out Type type) + public bool TryGetPreset(string name, [NotNullWhen(true)] out Type? type) { type = default; return false; diff --git a/Content.Server/AI/Operators/Combat/Melee/SwingMeleeWeaponOperator.cs b/Content.Server/AI/Operators/Combat/Melee/SwingMeleeWeaponOperator.cs index 49bc912171..36e0f1d9ca 100644 --- a/Content.Server/AI/Operators/Combat/Melee/SwingMeleeWeaponOperator.cs +++ b/Content.Server/AI/Operators/Combat/Melee/SwingMeleeWeaponOperator.cs @@ -29,7 +29,7 @@ namespace Content.Server.AI.Operators.Combat.Melee return true; } - if (!_owner.TryGetComponent(out CombatModeComponent combatModeComponent)) + if (!_owner.TryGetComponent(out CombatModeComponent? combatModeComponent)) { return false; } @@ -47,7 +47,7 @@ namespace Content.Server.AI.Operators.Combat.Melee if (!base.Shutdown(outcome)) return false; - if (_owner.TryGetComponent(out CombatModeComponent combatModeComponent)) + if (_owner.TryGetComponent(out CombatModeComponent? combatModeComponent)) { combatModeComponent.IsInCombatMode = false; } @@ -62,16 +62,16 @@ namespace Content.Server.AI.Operators.Combat.Melee return Outcome.Success; } - if (!_owner.TryGetComponent(out HandsComponent hands) || hands.GetActiveHand == null) + if (!_owner.TryGetComponent(out HandsComponent? hands) || hands.GetActiveHand == null) { return Outcome.Failed; } var meleeWeapon = hands.GetActiveHand.Owner; - meleeWeapon.TryGetComponent(out MeleeWeaponComponent meleeWeaponComponent); + meleeWeapon.TryGetComponent(out MeleeWeaponComponent? meleeWeaponComponent); if ((_target.Transform.Coordinates.Position - _owner.Transform.Coordinates.Position).Length > - meleeWeaponComponent.Range) + meleeWeaponComponent?.Range) { return Outcome.Failed; } diff --git a/Content.Server/AI/Operators/Combat/Melee/UnarmedCombatOperator.cs b/Content.Server/AI/Operators/Combat/Melee/UnarmedCombatOperator.cs index 2d0c2b8b0e..18695812bb 100644 --- a/Content.Server/AI/Operators/Combat/Melee/UnarmedCombatOperator.cs +++ b/Content.Server/AI/Operators/Combat/Melee/UnarmedCombatOperator.cs @@ -13,7 +13,7 @@ namespace Content.Server.AI.Operators.Combat.Melee private readonly IEntity _owner; private readonly IEntity _target; - private UnarmedCombatComponent _unarmedCombat; + private UnarmedCombatComponent? _unarmedCombat; public UnarmedCombatOperator(IEntity owner, IEntity target, float burstTime = 1.0f) { @@ -29,7 +29,7 @@ namespace Content.Server.AI.Operators.Combat.Melee return true; } - if (!_owner.TryGetComponent(out CombatModeComponent combatModeComponent)) + if (!_owner.TryGetComponent(out CombatModeComponent? combatModeComponent)) { return false; } @@ -39,7 +39,7 @@ namespace Content.Server.AI.Operators.Combat.Melee combatModeComponent.IsInCombatMode = true; } - if (_owner.TryGetComponent(out UnarmedCombatComponent unarmedCombatComponent)) + if (_owner.TryGetComponent(out UnarmedCombatComponent? unarmedCombatComponent)) { _unarmedCombat = unarmedCombatComponent; } @@ -56,7 +56,7 @@ namespace Content.Server.AI.Operators.Combat.Melee if (!base.Shutdown(outcome)) return false; - if (_owner.TryGetComponent(out CombatModeComponent combatModeComponent)) + if (_owner.TryGetComponent(out CombatModeComponent? combatModeComponent)) { combatModeComponent.IsInCombatMode = false; } @@ -71,7 +71,7 @@ namespace Content.Server.AI.Operators.Combat.Melee return Outcome.Success; } - if (_unarmedCombat.Deleted) + if (_unarmedCombat?.Deleted ?? true) { return Outcome.Failed; } diff --git a/Content.Server/AI/Operators/Inventory/CloseStorageOperator.cs b/Content.Server/AI/Operators/Inventory/CloseStorageOperator.cs index 8de3086357..369f87cbfb 100644 --- a/Content.Server/AI/Operators/Inventory/CloseStorageOperator.cs +++ b/Content.Server/AI/Operators/Inventory/CloseStorageOperator.cs @@ -14,7 +14,7 @@ namespace Content.Server.AI.Operators.Inventory public sealed class CloseLastStorageOperator : AiOperator { private readonly IEntity _owner; - private IEntity _target; + private IEntity? _target; public CloseLastStorageOperator(IEntity owner) { @@ -53,12 +53,12 @@ namespace Content.Server.AI.Operators.Inventory public override Outcome Execute(float frameTime) { - if (!_owner.InRangeUnobstructed(_target, popup: true)) + if (_target == null || !_owner.InRangeUnobstructed(_target, popup: true)) { return Outcome.Failed; } - if (!_target.TryGetComponent(out EntityStorageComponent storageComponent) || + if (!_target.TryGetComponent(out EntityStorageComponent? storageComponent) || storageComponent.IsWeldedShut) { return Outcome.Failed; diff --git a/Content.Server/AI/Operators/Inventory/DropEntityOperator.cs b/Content.Server/AI/Operators/Inventory/DropEntityOperator.cs index faf70677ab..1e282624d0 100644 --- a/Content.Server/AI/Operators/Inventory/DropEntityOperator.cs +++ b/Content.Server/AI/Operators/Inventory/DropEntityOperator.cs @@ -20,7 +20,7 @@ namespace Content.Server.AI.Operators.Inventory /// public override Outcome Execute(float frameTime) { - if (!_owner.TryGetComponent(out HandsComponent handsComponent) || + if (!_owner.TryGetComponent(out HandsComponent? handsComponent) || !handsComponent.TryHand(_entity, out _)) { return Outcome.Failed; diff --git a/Content.Server/AI/Operators/Inventory/DropHandItemsOperator.cs b/Content.Server/AI/Operators/Inventory/DropHandItemsOperator.cs index 4f1a1923c9..bb281df055 100644 --- a/Content.Server/AI/Operators/Inventory/DropHandItemsOperator.cs +++ b/Content.Server/AI/Operators/Inventory/DropHandItemsOperator.cs @@ -14,11 +14,11 @@ namespace Content.Server.AI.Operators.Inventory public override Outcome Execute(float frameTime) { - if (!_owner.TryGetComponent(out HandsComponent handsComponent)) + if (!_owner.TryGetComponent(out HandsComponent? handsComponent)) { return Outcome.Failed; } - + foreach (var item in handsComponent.GetAllHeldItems()) { handsComponent.Drop(item.Owner); diff --git a/Content.Server/AI/Operators/Inventory/EquipEntityOperator.cs b/Content.Server/AI/Operators/Inventory/EquipEntityOperator.cs index 82216f83d4..ce8c0f224d 100644 --- a/Content.Server/AI/Operators/Inventory/EquipEntityOperator.cs +++ b/Content.Server/AI/Operators/Inventory/EquipEntityOperator.cs @@ -15,7 +15,7 @@ namespace Content.Server.AI.Operators.Inventory public override Outcome Execute(float frameTime) { - if (!_owner.TryGetComponent(out HandsComponent handsComponent)) + if (!_owner.TryGetComponent(out HandsComponent? handsComponent)) { return Outcome.Failed; } diff --git a/Content.Server/AI/Operators/Inventory/InteractWithEntityOperator.cs b/Content.Server/AI/Operators/Inventory/InteractWithEntityOperator.cs index f7ac5d21a8..ced5bc0cef 100644 --- a/Content.Server/AI/Operators/Inventory/InteractWithEntityOperator.cs +++ b/Content.Server/AI/Operators/Inventory/InteractWithEntityOperator.cs @@ -33,7 +33,7 @@ namespace Content.Server.AI.Operators.Inventory return Outcome.Failed; } - if (_owner.TryGetComponent(out CombatModeComponent combatModeComponent)) + if (_owner.TryGetComponent(out CombatModeComponent? combatModeComponent)) { combatModeComponent.IsInCombatMode = false; } diff --git a/Content.Server/AI/Operators/Movement/MoveToEntityOperator.cs b/Content.Server/AI/Operators/Movement/MoveToEntityOperator.cs index a1e1f88b3a..f3fc522209 100644 --- a/Content.Server/AI/Operators/Movement/MoveToEntityOperator.cs +++ b/Content.Server/AI/Operators/Movement/MoveToEntityOperator.cs @@ -9,7 +9,7 @@ namespace Content.Server.AI.Operators.Movement { // TODO: This and steering need to support InRangeUnobstructed now private readonly IEntity _owner; - private EntityTargetSteeringRequest _request; + private EntityTargetSteeringRequest? _request; private readonly IEntity _target; // For now we'll just get as close as we can because we're not doing LOS checks to be able to pick up at the max interaction range public float ArrivalDistance { get; } @@ -56,7 +56,7 @@ namespace Content.Server.AI.Operators.Movement public override Outcome Execute(float frameTime) { - switch (_request.Status) + switch (_request?.Status) { case SteeringStatus.Pending: DebugTools.Assert(EntitySystem.Get().IsRegistered(_owner)); diff --git a/Content.Server/AI/Operators/Movement/MoveToGridOperator.cs b/Content.Server/AI/Operators/Movement/MoveToGridOperator.cs index 55af609b10..ff80659c2b 100644 --- a/Content.Server/AI/Operators/Movement/MoveToGridOperator.cs +++ b/Content.Server/AI/Operators/Movement/MoveToGridOperator.cs @@ -9,7 +9,7 @@ namespace Content.Server.AI.Operators.Movement public sealed class MoveToGridOperator : AiOperator { private readonly IEntity _owner; - private GridTargetSteeringRequest _request; + private GridTargetSteeringRequest? _request; private readonly EntityCoordinates _target; public float DesiredRange { get; set; } @@ -45,7 +45,7 @@ namespace Content.Server.AI.Operators.Movement public override Outcome Execute(float frameTime) { - switch (_request.Status) + switch (_request?.Status) { case SteeringStatus.Pending: DebugTools.Assert(EntitySystem.Get().IsRegistered(_owner)); diff --git a/Content.Server/AI/Operators/Sequences/SequenceOperator.cs b/Content.Server/AI/Operators/Sequences/SequenceOperator.cs index 5446a9f5cc..e578a88ecc 100644 --- a/Content.Server/AI/Operators/Sequences/SequenceOperator.cs +++ b/Content.Server/AI/Operators/Sequences/SequenceOperator.cs @@ -9,7 +9,7 @@ namespace Content.Server.AI.Operators.Sequences /// public abstract class SequenceOperator : AiOperator { - public Queue Sequence { get; protected set; } + public Queue Sequence { get; protected set; } = new(); public override Outcome Execute(float frameTime) { diff --git a/Content.Server/AI/Utility/Actions/Clothing/Gloves/EquipGloves.cs b/Content.Server/AI/Utility/Actions/Clothing/Gloves/EquipGloves.cs index a7a28e4913..2051a1584c 100644 --- a/Content.Server/AI/Utility/Actions/Clothing/Gloves/EquipGloves.cs +++ b/Content.Server/AI/Utility/Actions/Clothing/Gloves/EquipGloves.cs @@ -13,7 +13,7 @@ namespace Content.Server.AI.Utility.Actions.Clothing.Gloves { public sealed class EquipGloves : UtilityAction { - public IEntity Target { get; set; } + public IEntity Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { diff --git a/Content.Server/AI/Utility/Actions/Clothing/Gloves/PickUpGloves.cs b/Content.Server/AI/Utility/Actions/Clothing/Gloves/PickUpGloves.cs index 184af45b0f..70cdaaff15 100644 --- a/Content.Server/AI/Utility/Actions/Clothing/Gloves/PickUpGloves.cs +++ b/Content.Server/AI/Utility/Actions/Clothing/Gloves/PickUpGloves.cs @@ -14,7 +14,7 @@ namespace Content.Server.AI.Utility.Actions.Clothing.Gloves { public sealed class PickUpGloves : UtilityAction { - public IEntity Target { get; set; } + public IEntity Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { diff --git a/Content.Server/AI/Utility/Actions/Clothing/Head/EquipHead.cs b/Content.Server/AI/Utility/Actions/Clothing/Head/EquipHead.cs index b1a3a376fe..3f3a7f664f 100644 --- a/Content.Server/AI/Utility/Actions/Clothing/Head/EquipHead.cs +++ b/Content.Server/AI/Utility/Actions/Clothing/Head/EquipHead.cs @@ -13,7 +13,7 @@ namespace Content.Server.AI.Utility.Actions.Clothing.Head { public sealed class EquipHead : UtilityAction { - public IEntity Target { get; set; } + public IEntity Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { diff --git a/Content.Server/AI/Utility/Actions/Clothing/Head/PickUpHead.cs b/Content.Server/AI/Utility/Actions/Clothing/Head/PickUpHead.cs index 86e5d28493..6a380a115b 100644 --- a/Content.Server/AI/Utility/Actions/Clothing/Head/PickUpHead.cs +++ b/Content.Server/AI/Utility/Actions/Clothing/Head/PickUpHead.cs @@ -14,7 +14,7 @@ namespace Content.Server.AI.Utility.Actions.Clothing.Head { public sealed class PickUpHead : UtilityAction { - public IEntity Target { get; set; } + public IEntity Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { diff --git a/Content.Server/AI/Utility/Actions/Clothing/OuterClothing/EquipOuterClothing.cs b/Content.Server/AI/Utility/Actions/Clothing/OuterClothing/EquipOuterClothing.cs index 5e1afb7d91..a9bc02db85 100644 --- a/Content.Server/AI/Utility/Actions/Clothing/OuterClothing/EquipOuterClothing.cs +++ b/Content.Server/AI/Utility/Actions/Clothing/OuterClothing/EquipOuterClothing.cs @@ -13,7 +13,7 @@ namespace Content.Server.AI.Utility.Actions.Clothing.OuterClothing { public sealed class EquipOuterClothing : UtilityAction { - public IEntity Target { get; set; } + public IEntity Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { diff --git a/Content.Server/AI/Utility/Actions/Clothing/OuterClothing/PickUpOuterClothing.cs b/Content.Server/AI/Utility/Actions/Clothing/OuterClothing/PickUpOuterClothing.cs index ee74b40c76..e15440b701 100644 --- a/Content.Server/AI/Utility/Actions/Clothing/OuterClothing/PickUpOuterClothing.cs +++ b/Content.Server/AI/Utility/Actions/Clothing/OuterClothing/PickUpOuterClothing.cs @@ -14,7 +14,7 @@ namespace Content.Server.AI.Utility.Actions.Clothing.OuterClothing { public sealed class PickUpOuterClothing : UtilityAction { - public IEntity Target { get; set; } + public IEntity Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { diff --git a/Content.Server/AI/Utility/Actions/Clothing/Shoes/EquipShoes.cs b/Content.Server/AI/Utility/Actions/Clothing/Shoes/EquipShoes.cs index 6ba9ca0d41..d3ce78c7ff 100644 --- a/Content.Server/AI/Utility/Actions/Clothing/Shoes/EquipShoes.cs +++ b/Content.Server/AI/Utility/Actions/Clothing/Shoes/EquipShoes.cs @@ -13,7 +13,7 @@ namespace Content.Server.AI.Utility.Actions.Clothing.Shoes { public sealed class EquipShoes : UtilityAction { - public IEntity Target { get; set; } + public IEntity Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { diff --git a/Content.Server/AI/Utility/Actions/Clothing/Shoes/PickUpShoes.cs b/Content.Server/AI/Utility/Actions/Clothing/Shoes/PickUpShoes.cs index bc11486eaf..a1780a5115 100644 --- a/Content.Server/AI/Utility/Actions/Clothing/Shoes/PickUpShoes.cs +++ b/Content.Server/AI/Utility/Actions/Clothing/Shoes/PickUpShoes.cs @@ -14,7 +14,7 @@ namespace Content.Server.AI.Utility.Actions.Clothing.Shoes { public sealed class PickUpShoes : UtilityAction { - public IEntity Target { get; set; } + public IEntity Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { diff --git a/Content.Server/AI/Utility/Actions/Combat/Melee/EquipMelee.cs b/Content.Server/AI/Utility/Actions/Combat/Melee/EquipMelee.cs index da40762efd..2a727425ae 100644 --- a/Content.Server/AI/Utility/Actions/Combat/Melee/EquipMelee.cs +++ b/Content.Server/AI/Utility/Actions/Combat/Melee/EquipMelee.cs @@ -15,7 +15,7 @@ namespace Content.Server.AI.Utility.Actions.Combat.Melee { public sealed class EquipMelee : UtilityAction { - public IEntity Target { get; set; } + public IEntity Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { diff --git a/Content.Server/AI/Utility/Actions/Combat/Melee/MeleeWeaponAttackEntity.cs b/Content.Server/AI/Utility/Actions/Combat/Melee/MeleeWeaponAttackEntity.cs index 7f22e786b2..f135c7d40d 100644 --- a/Content.Server/AI/Utility/Actions/Combat/Melee/MeleeWeaponAttackEntity.cs +++ b/Content.Server/AI/Utility/Actions/Combat/Melee/MeleeWeaponAttackEntity.cs @@ -21,13 +21,13 @@ namespace Content.Server.AI.Utility.Actions.Combat.Melee { public sealed class MeleeWeaponAttackEntity : UtilityAction { - public IEntity Target { get; set; } + public IEntity Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { MoveToEntityOperator moveOperator; var equipped = context.GetState().GetValue(); - if (equipped != null && equipped.TryGetComponent(out MeleeWeaponComponent meleeWeaponComponent)) + if (equipped != null && equipped.TryGetComponent(out MeleeWeaponComponent? meleeWeaponComponent)) { moveOperator = new MoveToEntityOperator(Owner, Target, meleeWeaponComponent.Range - 0.01f); } diff --git a/Content.Server/AI/Utility/Actions/Combat/Melee/PickUpMeleeWeapon.cs b/Content.Server/AI/Utility/Actions/Combat/Melee/PickUpMeleeWeapon.cs index a988d7c8d6..272bbbdf2c 100644 --- a/Content.Server/AI/Utility/Actions/Combat/Melee/PickUpMeleeWeapon.cs +++ b/Content.Server/AI/Utility/Actions/Combat/Melee/PickUpMeleeWeapon.cs @@ -15,7 +15,7 @@ namespace Content.Server.AI.Utility.Actions.Combat.Melee { public sealed class PickUpMeleeWeapon : UtilityAction { - public IEntity Target { get; set; } + public IEntity Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { diff --git a/Content.Server/AI/Utility/Actions/Combat/Melee/UnarmedAttackEntity.cs b/Content.Server/AI/Utility/Actions/Combat/Melee/UnarmedAttackEntity.cs index 46ae25d0e6..08250507f4 100644 --- a/Content.Server/AI/Utility/Actions/Combat/Melee/UnarmedAttackEntity.cs +++ b/Content.Server/AI/Utility/Actions/Combat/Melee/UnarmedAttackEntity.cs @@ -19,12 +19,12 @@ namespace Content.Server.AI.Utility.Actions.Combat.Melee { public sealed class UnarmedAttackEntity : UtilityAction { - public IEntity Target { get; set; } + public IEntity Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { MoveToEntityOperator moveOperator; - if (Owner.TryGetComponent(out UnarmedCombatComponent unarmedCombatComponent)) + if (Owner.TryGetComponent(out UnarmedCombatComponent? unarmedCombatComponent)) { moveOperator = new MoveToEntityOperator(Owner, Target, unarmedCombatComponent.Range - 0.01f); } diff --git a/Content.Server/AI/Utility/Actions/Idle/CloseLastEntityStorage.cs b/Content.Server/AI/Utility/Actions/Idle/CloseLastEntityStorage.cs index 6dfb1821a9..0c92ca875a 100644 --- a/Content.Server/AI/Utility/Actions/Idle/CloseLastEntityStorage.cs +++ b/Content.Server/AI/Utility/Actions/Idle/CloseLastEntityStorage.cs @@ -10,7 +10,6 @@ using Content.Server.AI.Utility.Considerations.State; using Content.Server.AI.WorldState; using Content.Server.AI.WorldState.States; using Content.Server.AI.WorldState.States.Inventory; -using Robust.Shared.GameObjects; using Robust.Shared.IoC; namespace Content.Server.AI.Utility.Actions.Idle @@ -26,6 +25,16 @@ namespace Content.Server.AI.Utility.Actions.Idle { var lastStorage = context.GetState().GetValue(); + if (lastStorage == null) + { + ActionOperators = new Queue(new AiOperator[] + { + new CloseLastStorageOperator(Owner), + }); + + return; + } + ActionOperators = new Queue(new AiOperator[] { new MoveToEntityOperator(Owner, lastStorage), diff --git a/Content.Server/AI/Utility/Actions/Nutrition/Drink/PickUpDrink.cs b/Content.Server/AI/Utility/Actions/Nutrition/Drink/PickUpDrink.cs index 8a7fc8ae15..9f7e7e6ac0 100644 --- a/Content.Server/AI/Utility/Actions/Nutrition/Drink/PickUpDrink.cs +++ b/Content.Server/AI/Utility/Actions/Nutrition/Drink/PickUpDrink.cs @@ -14,7 +14,7 @@ namespace Content.Server.AI.Utility.Actions.Nutrition.Drink { public sealed class PickUpDrink : UtilityAction { - public IEntity Target { get; set; } + public IEntity Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { diff --git a/Content.Server/AI/Utility/Actions/Nutrition/Drink/UseDrinkInInventory.cs b/Content.Server/AI/Utility/Actions/Nutrition/Drink/UseDrinkInInventory.cs index a9cfc2a334..7ef0ee9a02 100644 --- a/Content.Server/AI/Utility/Actions/Nutrition/Drink/UseDrinkInInventory.cs +++ b/Content.Server/AI/Utility/Actions/Nutrition/Drink/UseDrinkInInventory.cs @@ -15,7 +15,7 @@ namespace Content.Server.AI.Utility.Actions.Nutrition.Drink { public sealed class UseDrinkInInventory : UtilityAction { - public IEntity Target { get; set; } + public IEntity Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { diff --git a/Content.Server/AI/Utility/Actions/Nutrition/Food/PickUpFood.cs b/Content.Server/AI/Utility/Actions/Nutrition/Food/PickUpFood.cs index 8aa6a5be90..24ede12d18 100644 --- a/Content.Server/AI/Utility/Actions/Nutrition/Food/PickUpFood.cs +++ b/Content.Server/AI/Utility/Actions/Nutrition/Food/PickUpFood.cs @@ -14,7 +14,7 @@ namespace Content.Server.AI.Utility.Actions.Nutrition.Food { public sealed class PickUpFood : UtilityAction { - public IEntity Target { get; set; } + public IEntity Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { diff --git a/Content.Server/AI/Utility/Actions/Nutrition/Food/UseFoodInInventory.cs b/Content.Server/AI/Utility/Actions/Nutrition/Food/UseFoodInInventory.cs index dc7462c5ab..2bce14ccfa 100644 --- a/Content.Server/AI/Utility/Actions/Nutrition/Food/UseFoodInInventory.cs +++ b/Content.Server/AI/Utility/Actions/Nutrition/Food/UseFoodInInventory.cs @@ -15,7 +15,7 @@ namespace Content.Server.AI.Utility.Actions.Nutrition.Food { public sealed class UseFoodInInventory : UtilityAction { - public IEntity Target { get; set; } + public IEntity Target { get; set; } = default!; public override void SetupOperators(Blackboard context) { diff --git a/Content.Server/AI/Utility/Actions/UtilityAction.cs b/Content.Server/AI/Utility/Actions/UtilityAction.cs index 5ff9e5f5a6..fe906ad38e 100644 --- a/Content.Server/AI/Utility/Actions/UtilityAction.cs +++ b/Content.Server/AI/Utility/Actions/UtilityAction.cs @@ -59,7 +59,11 @@ namespace Content.Server.AI.Utility.Actions protected virtual void UpdateBlackboard(Blackboard context) {} // Needs to be able to be instantiated without args via typefactory. - public UtilityAction() {} + public UtilityAction() + { + Owner = default!; + ActionOperators = default!; + } public virtual void Shutdown() {} diff --git a/Content.Server/AI/Utility/AiLogic/UtilityAI.cs b/Content.Server/AI/Utility/AiLogic/UtilityAI.cs index de3347f918..be14607c5a 100644 --- a/Content.Server/AI/Utility/AiLogic/UtilityAI.cs +++ b/Content.Server/AI/Utility/AiLogic/UtilityAI.cs @@ -28,9 +28,9 @@ namespace Content.Server.AI.Utility.AiLogic // TODO: Look at having ParallelOperators (probably no more than that as then you'd have a full-blown BT) // Also RepeatOperators (e.g. if we're following an entity keep repeating MoveToEntity) - private AiActionSystem _planner; + private AiActionSystem _planner = default!; public Blackboard Blackboard => _blackboard; - private Blackboard _blackboard; + private Blackboard _blackboard = default!; /// /// The sum of all BehaviorSets gives us what actions the AI can take @@ -43,7 +43,7 @@ namespace Content.Server.AI.Utility.AiLogic /// /// The currently running action; most importantly are the operators. /// - public UtilityAction CurrentAction { get; private set; } + public UtilityAction? CurrentAction { get; private set; } /// /// How frequently we can re-plan. If an AI's in combat you could decrease the cooldown, @@ -55,9 +55,9 @@ namespace Content.Server.AI.Utility.AiLogic /// /// If we've requested a plan then wait patiently for the action /// - private AiActionRequestJob _actionRequest; + private AiActionRequestJob? _actionRequest; - private CancellationTokenSource _actionCancellation; + private CancellationTokenSource? _actionCancellation; /// /// If we can't do anything then stop thinking; should probably use ActionBlocker instead @@ -126,6 +126,11 @@ namespace Content.Server.AI.Utility.AiLogic private void ReceivedAction() { + if (_actionRequest == null) + { + return; + } + switch (_actionRequest.Exception) { case null: diff --git a/Content.Server/AI/Utility/Considerations/ActionBlocker/CanMoveCon.cs b/Content.Server/AI/Utility/Considerations/ActionBlocker/CanMoveCon.cs index 068bed08af..27d2503788 100644 --- a/Content.Server/AI/Utility/Considerations/ActionBlocker/CanMoveCon.cs +++ b/Content.Server/AI/Utility/Considerations/ActionBlocker/CanMoveCon.cs @@ -9,7 +9,8 @@ namespace Content.Server.AI.Utility.Considerations.ActionBlocker protected override float GetScore(Blackboard context) { var self = context.GetState().GetValue(); - if (!ActionBlockerSystem.CanMove(self)) + + if (self == null || !ActionBlockerSystem.CanMove(self)) { return 0.0f; } diff --git a/Content.Server/AI/Utility/Considerations/Clothing/ClothingInInventoryCon.cs b/Content.Server/AI/Utility/Considerations/Clothing/ClothingInInventoryCon.cs index 961139a648..63c851d0d3 100644 --- a/Content.Server/AI/Utility/Considerations/Clothing/ClothingInInventoryCon.cs +++ b/Content.Server/AI/Utility/Considerations/Clothing/ClothingInInventoryCon.cs @@ -23,7 +23,7 @@ namespace Content.Server.AI.Utility.Considerations.Clothing foreach (var entity in context.GetState().GetValue()) { - if (!entity.TryGetComponent(out ClothingComponent clothingComponent)) + if (!entity.TryGetComponent(out ClothingComponent? clothingComponent)) { continue; } diff --git a/Content.Server/AI/Utility/Considerations/Combat/Melee/CanUnarmedCombatCon.cs b/Content.Server/AI/Utility/Considerations/Combat/Melee/CanUnarmedCombatCon.cs index ad9c4d4ea6..1899ac807a 100644 --- a/Content.Server/AI/Utility/Considerations/Combat/Melee/CanUnarmedCombatCon.cs +++ b/Content.Server/AI/Utility/Considerations/Combat/Melee/CanUnarmedCombatCon.cs @@ -8,7 +8,7 @@ namespace Content.Server.AI.Utility.Considerations.Combat.Melee { protected override float GetScore(Blackboard context) { - return context.GetState().GetValue().HasComponent() ? 1.0f : 0.0f; + return context.GetState().GetValue()?.HasComponent() ?? false ? 1.0f : 0.0f; } } -} \ No newline at end of file +} diff --git a/Content.Server/AI/Utility/Considerations/Combat/Melee/MeleeWeaponDamageCon.cs b/Content.Server/AI/Utility/Considerations/Combat/Melee/MeleeWeaponDamageCon.cs index 9f62896520..e90d8c9f63 100644 --- a/Content.Server/AI/Utility/Considerations/Combat/Melee/MeleeWeaponDamageCon.cs +++ b/Content.Server/AI/Utility/Considerations/Combat/Melee/MeleeWeaponDamageCon.cs @@ -10,7 +10,7 @@ namespace Content.Server.AI.Utility.Considerations.Combat.Melee { var target = context.GetState().GetValue(); - if (target == null || !target.TryGetComponent(out MeleeWeaponComponent meleeWeaponComponent)) + if (target == null || !target.TryGetComponent(out MeleeWeaponComponent? meleeWeaponComponent)) { return 0.0f; } diff --git a/Content.Server/AI/Utility/Considerations/Combat/Melee/MeleeWeaponSpeedCon.cs b/Content.Server/AI/Utility/Considerations/Combat/Melee/MeleeWeaponSpeedCon.cs index 63e1bddd46..fcb48f2727 100644 --- a/Content.Server/AI/Utility/Considerations/Combat/Melee/MeleeWeaponSpeedCon.cs +++ b/Content.Server/AI/Utility/Considerations/Combat/Melee/MeleeWeaponSpeedCon.cs @@ -10,7 +10,7 @@ namespace Content.Server.AI.Utility.Considerations.Combat.Melee { var target = context.GetState().GetValue(); - if (target == null || !target.TryGetComponent(out MeleeWeaponComponent meleeWeaponComponent)) + if (target == null || !target.TryGetComponent(out MeleeWeaponComponent? meleeWeaponComponent)) { return 0.0f; } diff --git a/Content.Server/AI/Utility/Considerations/Combat/TargetHealthCon.cs b/Content.Server/AI/Utility/Considerations/Combat/TargetHealthCon.cs index 4e6a496871..6376feb7ed 100644 --- a/Content.Server/AI/Utility/Considerations/Combat/TargetHealthCon.cs +++ b/Content.Server/AI/Utility/Considerations/Combat/TargetHealthCon.cs @@ -10,7 +10,7 @@ namespace Content.Server.AI.Utility.Considerations.Combat { var target = context.GetState().GetValue(); - if (target == null || target.Deleted || !target.TryGetComponent(out IDamageableComponent damageableComponent)) + if (target == null || target.Deleted || !target.TryGetComponent(out IDamageableComponent? damageableComponent)) { return 0.0f; } diff --git a/Content.Server/AI/Utility/Considerations/Combat/TargetIsCritCon.cs b/Content.Server/AI/Utility/Considerations/Combat/TargetIsCritCon.cs index ebf80fc142..790ec9cc03 100644 --- a/Content.Server/AI/Utility/Considerations/Combat/TargetIsCritCon.cs +++ b/Content.Server/AI/Utility/Considerations/Combat/TargetIsCritCon.cs @@ -10,7 +10,7 @@ namespace Content.Server.AI.Utility.Considerations.Combat { var target = context.GetState().GetValue(); - if (target == null || !target.TryGetComponent(out IMobStateComponent mobState)) + if (target == null || !target.TryGetComponent(out IMobStateComponent? mobState)) { return 0.0f; } diff --git a/Content.Server/AI/Utility/Considerations/Combat/TargetIsDeadCon.cs b/Content.Server/AI/Utility/Considerations/Combat/TargetIsDeadCon.cs index 8cd4998719..947c4a2eea 100644 --- a/Content.Server/AI/Utility/Considerations/Combat/TargetIsDeadCon.cs +++ b/Content.Server/AI/Utility/Considerations/Combat/TargetIsDeadCon.cs @@ -10,7 +10,7 @@ namespace Content.Server.AI.Utility.Considerations.Combat { var target = context.GetState().GetValue(); - if (target == null || !target.TryGetComponent(out IMobStateComponent mobState)) + if (target == null || !target.TryGetComponent(out IMobStateComponent? mobState)) { return 0.0f; } diff --git a/Content.Server/AI/Utility/Considerations/Containers/TargetAccessibleCon.cs b/Content.Server/AI/Utility/Considerations/Containers/TargetAccessibleCon.cs index 961d51c6f1..9408ef3575 100644 --- a/Content.Server/AI/Utility/Considerations/Containers/TargetAccessibleCon.cs +++ b/Content.Server/AI/Utility/Considerations/Containers/TargetAccessibleCon.cs @@ -24,7 +24,7 @@ namespace Content.Server.AI.Utility.Considerations.Containers if (target.TryGetContainer(out var container)) { - if (container.Owner.TryGetComponent(out EntityStorageComponent storageComponent)) + if (container.Owner.TryGetComponent(out EntityStorageComponent? storageComponent)) { if (storageComponent.IsWeldedShut && !storageComponent.Open) { @@ -41,6 +41,11 @@ namespace Content.Server.AI.Utility.Considerations.Containers var owner = context.GetState().GetValue(); + if (owner == null) + { + return 0; + } + return EntitySystem.Get().CanAccess(owner, target, SharedInteractionSystem.InteractionRange) ? 1.0f : 0.0f; } } diff --git a/Content.Server/AI/Utility/Considerations/Hands/FreeHandCon.cs b/Content.Server/AI/Utility/Considerations/Hands/FreeHandCon.cs index 67363574e9..c18ee94e26 100644 --- a/Content.Server/AI/Utility/Considerations/Hands/FreeHandCon.cs +++ b/Content.Server/AI/Utility/Considerations/Hands/FreeHandCon.cs @@ -10,7 +10,7 @@ namespace Content.Server.AI.Utility.Considerations.Hands { var owner = context.GetState().GetValue(); - if (!owner.TryGetComponent(out HandsComponent handsComponent)) + if (owner == null || !owner.TryGetComponent(out HandsComponent? handsComponent)) { return 0.0f; } diff --git a/Content.Server/AI/Utility/Considerations/Movement/TargetDistanceCon.cs b/Content.Server/AI/Utility/Considerations/Movement/TargetDistanceCon.cs index ec6df87121..e3c912acf5 100644 --- a/Content.Server/AI/Utility/Considerations/Movement/TargetDistanceCon.cs +++ b/Content.Server/AI/Utility/Considerations/Movement/TargetDistanceCon.cs @@ -9,7 +9,7 @@ namespace Content.Server.AI.Utility.Considerations.Movement { var self = context.GetState().GetValue(); var target = context.GetState().GetValue(); - if (target == null || target.Deleted || target.Transform.GridID != self.Transform.GridID) + if (target == null || target.Deleted || target.Transform.GridID != self?.Transform.GridID) { return 0.0f; } diff --git a/Content.Server/AI/Utility/Considerations/Nutrition/Drink/DrinkValueCon.cs b/Content.Server/AI/Utility/Considerations/Nutrition/Drink/DrinkValueCon.cs index 047c91cdd3..554451f680 100644 --- a/Content.Server/AI/Utility/Considerations/Nutrition/Drink/DrinkValueCon.cs +++ b/Content.Server/AI/Utility/Considerations/Nutrition/Drink/DrinkValueCon.cs @@ -10,7 +10,7 @@ namespace Content.Server.AI.Utility.Considerations.Nutrition.Drink { var target = context.GetState().GetValue(); - if (target.Deleted || !target.TryGetComponent(out SolutionContainerComponent drink)) + if (target == null || target.Deleted || !target.TryGetComponent(out SolutionContainerComponent? drink)) { return 0.0f; } diff --git a/Content.Server/AI/Utility/Considerations/Nutrition/Drink/ThirstCon.cs b/Content.Server/AI/Utility/Considerations/Nutrition/Drink/ThirstCon.cs index b228d16026..84e03781bc 100644 --- a/Content.Server/AI/Utility/Considerations/Nutrition/Drink/ThirstCon.cs +++ b/Content.Server/AI/Utility/Considerations/Nutrition/Drink/ThirstCon.cs @@ -11,7 +11,7 @@ namespace Content.Server.AI.Utility.Considerations.Nutrition.Drink { var owner = context.GetState().GetValue(); - if (!owner.TryGetComponent(out ThirstComponent thirst)) + if (owner == null || !owner.TryGetComponent(out ThirstComponent? thirst)) { return 0.0f; } diff --git a/Content.Server/AI/Utility/Considerations/Nutrition/Food/FoodValueCon.cs b/Content.Server/AI/Utility/Considerations/Nutrition/Food/FoodValueCon.cs index 14c1e68fad..1f94a77313 100644 --- a/Content.Server/AI/Utility/Considerations/Nutrition/Food/FoodValueCon.cs +++ b/Content.Server/AI/Utility/Considerations/Nutrition/Food/FoodValueCon.cs @@ -10,7 +10,7 @@ namespace Content.Server.AI.Utility.Considerations.Nutrition.Food { var target = context.GetState().GetValue(); - if (target.Deleted || !target.TryGetComponent(out SolutionContainerComponent food)) + if (target == null || target.Deleted || !target.TryGetComponent(out SolutionContainerComponent? food)) { return 0.0f; } diff --git a/Content.Server/AI/Utility/Considerations/Nutrition/Food/HungerCon.cs b/Content.Server/AI/Utility/Considerations/Nutrition/Food/HungerCon.cs index a09eff2924..ba3280eb5f 100644 --- a/Content.Server/AI/Utility/Considerations/Nutrition/Food/HungerCon.cs +++ b/Content.Server/AI/Utility/Considerations/Nutrition/Food/HungerCon.cs @@ -12,7 +12,7 @@ namespace Content.Server.AI.Utility.Considerations.Nutrition.Food { var owner = context.GetState().GetValue(); - if (!owner.TryGetComponent(out HungerComponent hunger)) + if (owner == null || !owner.TryGetComponent(out HungerComponent? hunger)) { return 0.0f; } diff --git a/Content.Server/AI/Utility/Considerations/State/StoredStateEntityIsNullCon.cs b/Content.Server/AI/Utility/Considerations/State/StoredStateEntityIsNullCon.cs index fde48342fe..4e53cdab94 100644 --- a/Content.Server/AI/Utility/Considerations/State/StoredStateEntityIsNullCon.cs +++ b/Content.Server/AI/Utility/Considerations/State/StoredStateEntityIsNullCon.cs @@ -17,12 +17,18 @@ namespace Content.Server.AI.Utility.Considerations.State context.GetState().SetValue(type); return this; } - + protected override float GetScore(Blackboard context) { var stateData = context.GetState().GetValue(); + + if (stateData == null) + { + return 0; + } + context.GetStoredState(stateData, out StoredStateData state); return state.GetValue() == null ? 1.0f : 0.0f; } } -} \ No newline at end of file +} diff --git a/Content.Server/AI/Utility/ExpandableActions/Clothing/Gloves/EquipAnyGlovesExp.cs b/Content.Server/AI/Utility/ExpandableActions/Clothing/Gloves/EquipAnyGlovesExp.cs index 288406654d..64b8d3841e 100644 --- a/Content.Server/AI/Utility/ExpandableActions/Clothing/Gloves/EquipAnyGlovesExp.cs +++ b/Content.Server/AI/Utility/ExpandableActions/Clothing/Gloves/EquipAnyGlovesExp.cs @@ -37,7 +37,7 @@ namespace Content.Server.AI.Utility.ExpandableActions.Clothing.Gloves foreach (var entity in context.GetState().GetValue()) { - if (entity.TryGetComponent(out ClothingComponent clothing) && + if (entity.TryGetComponent(out ClothingComponent? clothing) && (clothing.SlotFlags & EquipmentSlotDefines.SlotFlags.GLOVES) != 0) { yield return new EquipGloves {Owner = owner, Target = entity, Bonus = Bonus}; diff --git a/Content.Server/AI/Utility/ExpandableActions/Clothing/Gloves/PickUpAnyNearbyGlovesExp.cs b/Content.Server/AI/Utility/ExpandableActions/Clothing/Gloves/PickUpAnyNearbyGlovesExp.cs index 9a1c6a9c53..794916ac2d 100644 --- a/Content.Server/AI/Utility/ExpandableActions/Clothing/Gloves/PickUpAnyNearbyGlovesExp.cs +++ b/Content.Server/AI/Utility/ExpandableActions/Clothing/Gloves/PickUpAnyNearbyGlovesExp.cs @@ -35,7 +35,7 @@ namespace Content.Server.AI.Utility.ExpandableActions.Clothing.Gloves foreach (var entity in context.GetState().GetValue()) { - if (entity.TryGetComponent(out ClothingComponent clothing) && + if (entity.TryGetComponent(out ClothingComponent? clothing) && (clothing.SlotFlags & EquipmentSlotDefines.SlotFlags.GLOVES) != 0) { yield return new PickUpGloves {Owner = owner, Target = entity, Bonus = Bonus}; diff --git a/Content.Server/AI/Utility/ExpandableActions/Clothing/Head/EquipAnyHeadExp.cs b/Content.Server/AI/Utility/ExpandableActions/Clothing/Head/EquipAnyHeadExp.cs index 427585ce50..4f0da2993a 100644 --- a/Content.Server/AI/Utility/ExpandableActions/Clothing/Head/EquipAnyHeadExp.cs +++ b/Content.Server/AI/Utility/ExpandableActions/Clothing/Head/EquipAnyHeadExp.cs @@ -36,7 +36,7 @@ namespace Content.Server.AI.Utility.ExpandableActions.Clothing.Head foreach (var entity in context.GetState().GetValue()) { - if (entity.TryGetComponent(out ClothingComponent clothing) && + if (entity.TryGetComponent(out ClothingComponent? clothing) && (clothing.SlotFlags & EquipmentSlotDefines.SlotFlags.HEAD) != 0) { yield return new EquipHead {Owner = owner, Target = entity, Bonus = Bonus}; diff --git a/Content.Server/AI/Utility/ExpandableActions/Clothing/Head/PickUpAnyNearbyHeadExp.cs b/Content.Server/AI/Utility/ExpandableActions/Clothing/Head/PickUpAnyNearbyHeadExp.cs index 1095cd8704..4ce3ac64ec 100644 --- a/Content.Server/AI/Utility/ExpandableActions/Clothing/Head/PickUpAnyNearbyHeadExp.cs +++ b/Content.Server/AI/Utility/ExpandableActions/Clothing/Head/PickUpAnyNearbyHeadExp.cs @@ -35,10 +35,10 @@ namespace Content.Server.AI.Utility.ExpandableActions.Clothing.Head foreach (var entity in context.GetState().GetValue()) { - if (entity.TryGetComponent(out ClothingComponent clothing) && + if (entity.TryGetComponent(out ClothingComponent? clothing) && (clothing.SlotFlags & EquipmentSlotDefines.SlotFlags.HEAD) != 0) { - yield return new PickUpHead() {Owner = owner, Target = entity, Bonus = Bonus}; + yield return new PickUpHead {Owner = owner, Target = entity, Bonus = Bonus}; } } } diff --git a/Content.Server/AI/Utility/ExpandableActions/Clothing/OuterClothing/EquipAnyOuterClothingExp.cs b/Content.Server/AI/Utility/ExpandableActions/Clothing/OuterClothing/EquipAnyOuterClothingExp.cs index 27d516b8dd..19f2989544 100644 --- a/Content.Server/AI/Utility/ExpandableActions/Clothing/OuterClothing/EquipAnyOuterClothingExp.cs +++ b/Content.Server/AI/Utility/ExpandableActions/Clothing/OuterClothing/EquipAnyOuterClothingExp.cs @@ -37,10 +37,10 @@ namespace Content.Server.AI.Utility.ExpandableActions.Clothing.OuterClothing foreach (var entity in context.GetState().GetValue()) { - if (entity.TryGetComponent(out ClothingComponent clothing) && + if (entity.TryGetComponent(out ClothingComponent? clothing) && (clothing.SlotFlags & EquipmentSlotDefines.SlotFlags.OUTERCLOTHING) != 0) { - yield return new EquipOuterClothing() {Owner = owner, Target = entity, Bonus = Bonus}; + yield return new EquipOuterClothing {Owner = owner, Target = entity, Bonus = Bonus}; } } } diff --git a/Content.Server/AI/Utility/ExpandableActions/Clothing/OuterClothing/PickUpAnyNearbyOuterClothingExp.cs b/Content.Server/AI/Utility/ExpandableActions/Clothing/OuterClothing/PickUpAnyNearbyOuterClothingExp.cs index f04551b21a..7732a59111 100644 --- a/Content.Server/AI/Utility/ExpandableActions/Clothing/OuterClothing/PickUpAnyNearbyOuterClothingExp.cs +++ b/Content.Server/AI/Utility/ExpandableActions/Clothing/OuterClothing/PickUpAnyNearbyOuterClothingExp.cs @@ -36,10 +36,10 @@ namespace Content.Server.AI.Utility.ExpandableActions.Clothing.OuterClothing foreach (var entity in context.GetState().GetValue()) { - if (entity.TryGetComponent(out ClothingComponent clothing) && + if (entity.TryGetComponent(out ClothingComponent? clothing) && (clothing.SlotFlags & EquipmentSlotDefines.SlotFlags.OUTERCLOTHING) != 0) { - yield return new PickUpOuterClothing() {Owner = owner, Target = entity, Bonus = Bonus}; + yield return new PickUpOuterClothing {Owner = owner, Target = entity, Bonus = Bonus}; } } } diff --git a/Content.Server/AI/Utility/ExpandableActions/Clothing/Shoes/EquipAnyShoesExp.cs b/Content.Server/AI/Utility/ExpandableActions/Clothing/Shoes/EquipAnyShoesExp.cs index 09d60fd8a8..6d27889db3 100644 --- a/Content.Server/AI/Utility/ExpandableActions/Clothing/Shoes/EquipAnyShoesExp.cs +++ b/Content.Server/AI/Utility/ExpandableActions/Clothing/Shoes/EquipAnyShoesExp.cs @@ -37,10 +37,10 @@ namespace Content.Server.AI.Utility.ExpandableActions.Clothing.Shoes foreach (var entity in context.GetState().GetValue()) { - if (entity.TryGetComponent(out ClothingComponent clothing) && + if (entity.TryGetComponent(out ClothingComponent? clothing) && (clothing.SlotFlags & EquipmentSlotDefines.SlotFlags.SHOES) != 0) { - yield return new EquipShoes() {Owner = owner, Target = entity, Bonus = Bonus}; + yield return new EquipShoes {Owner = owner, Target = entity, Bonus = Bonus}; } } } diff --git a/Content.Server/AI/Utility/ExpandableActions/Clothing/Shoes/PickUpAnyNearbyShoesExp.cs b/Content.Server/AI/Utility/ExpandableActions/Clothing/Shoes/PickUpAnyNearbyShoesExp.cs index 6779ef85ca..fb22fbd202 100644 --- a/Content.Server/AI/Utility/ExpandableActions/Clothing/Shoes/PickUpAnyNearbyShoesExp.cs +++ b/Content.Server/AI/Utility/ExpandableActions/Clothing/Shoes/PickUpAnyNearbyShoesExp.cs @@ -36,7 +36,7 @@ namespace Content.Server.AI.Utility.ExpandableActions.Clothing.Shoes foreach (var entity in context.GetState().GetValue()) { - if (entity.TryGetComponent(out ClothingComponent clothing) && + if (entity.TryGetComponent(out ClothingComponent? clothing) && (clothing.SlotFlags & EquipmentSlotDefines.SlotFlags.SHOES) != 0) { yield return new PickUpShoes {Owner = owner, Target = entity, Bonus = Bonus}; diff --git a/Content.Server/AI/Utility/ExpandableActions/Combat/Melee/EquipMeleeExp.cs b/Content.Server/AI/Utility/ExpandableActions/Combat/Melee/EquipMeleeExp.cs index 86ab1b81a5..533630b2b2 100644 --- a/Content.Server/AI/Utility/ExpandableActions/Combat/Melee/EquipMeleeExp.cs +++ b/Content.Server/AI/Utility/ExpandableActions/Combat/Melee/EquipMeleeExp.cs @@ -38,7 +38,7 @@ namespace Content.Server.AI.Utility.ExpandableActions.Combat.Melee continue; } - yield return new EquipMelee() {Owner = owner, Target = entity, Bonus = Bonus}; + yield return new EquipMelee {Owner = owner, Target = entity, Bonus = Bonus}; } } } diff --git a/Content.Server/AI/Utility/ExpandableActions/Combat/Melee/MeleeAttackNearbyExp.cs b/Content.Server/AI/Utility/ExpandableActions/Combat/Melee/MeleeAttackNearbyExp.cs index 8b70caabf6..214529cbe7 100644 --- a/Content.Server/AI/Utility/ExpandableActions/Combat/Melee/MeleeAttackNearbyExp.cs +++ b/Content.Server/AI/Utility/ExpandableActions/Combat/Melee/MeleeAttackNearbyExp.cs @@ -31,7 +31,7 @@ namespace Content.Server.AI.Utility.ExpandableActions.Combat.Melee public override IEnumerable GetActions(Blackboard context) { var owner = context.GetState().GetValue(); - if (!owner.TryGetComponent(out AiControllerComponent controller)) + if (!owner.TryGetComponent(out AiControllerComponent? controller)) { throw new InvalidOperationException(); } @@ -39,7 +39,7 @@ namespace Content.Server.AI.Utility.ExpandableActions.Combat.Melee foreach (var target in EntitySystem.Get() .GetNearbyHostiles(owner, controller.VisionRadius)) { - yield return new MeleeWeaponAttackEntity() {Owner = owner, Target = target, Bonus = Bonus}; + yield return new MeleeWeaponAttackEntity {Owner = owner, Target = target, Bonus = Bonus}; } } } diff --git a/Content.Server/AI/Utility/ExpandableActions/Combat/Melee/UnarmedAttackNearbyHostilesExp.cs b/Content.Server/AI/Utility/ExpandableActions/Combat/Melee/UnarmedAttackNearbyHostilesExp.cs index 08085fefb8..dcc4d3db8f 100644 --- a/Content.Server/AI/Utility/ExpandableActions/Combat/Melee/UnarmedAttackNearbyHostilesExp.cs +++ b/Content.Server/AI/Utility/ExpandableActions/Combat/Melee/UnarmedAttackNearbyHostilesExp.cs @@ -31,7 +31,7 @@ namespace Content.Server.AI.Utility.ExpandableActions.Combat.Melee public override IEnumerable GetActions(Blackboard context) { var owner = context.GetState().GetValue(); - if (!owner.TryGetComponent(out AiControllerComponent controller)) + if (!owner.TryGetComponent(out AiControllerComponent? controller)) { throw new InvalidOperationException(); } diff --git a/Content.Server/AI/Utility/ExpandableActions/ExpandableUtilityAction.cs b/Content.Server/AI/Utility/ExpandableActions/ExpandableUtilityAction.cs index de2c6549f7..6c3d79ba6c 100644 --- a/Content.Server/AI/Utility/ExpandableActions/ExpandableUtilityAction.cs +++ b/Content.Server/AI/Utility/ExpandableActions/ExpandableUtilityAction.cs @@ -12,7 +12,7 @@ namespace Content.Server.AI.Utility.ExpandableActions /// public abstract class ExpandableUtilityAction : IAiUtility { - public IEntity Owner { get; set; } + public IEntity Owner { get; set; } = default!; public abstract float Bonus { get; } diff --git a/Content.Server/AI/Utility/UtilityAiHelpers.cs b/Content.Server/AI/Utility/UtilityAiHelpers.cs index 68cd796fd1..9e5938294f 100644 --- a/Content.Server/AI/Utility/UtilityAiHelpers.cs +++ b/Content.Server/AI/Utility/UtilityAiHelpers.cs @@ -7,9 +7,9 @@ namespace Content.Server.AI.Utility { public static class UtilityAiHelpers { - public static Blackboard GetBlackboard(IEntity entity) + public static Blackboard? GetBlackboard(IEntity entity) { - if (!entity.TryGetComponent(out AiControllerComponent aiControllerComponent)) + if (!entity.TryGetComponent(out AiControllerComponent? aiControllerComponent)) { return null; } diff --git a/Content.Server/AI/Utils/Visibility.cs b/Content.Server/AI/Utils/Visibility.cs index 1130ac09a9..957079e3f1 100644 --- a/Content.Server/AI/Utils/Visibility.cs +++ b/Content.Server/AI/Utils/Visibility.cs @@ -24,7 +24,7 @@ namespace Content.Server.AI.Utils return false; } - if (owner.TryGetComponent(out AiControllerComponent controller)) + if (owner.TryGetComponent(out AiControllerComponent? controller)) { var targetRange = (target.Transform.Coordinates.Position - owner.Transform.Coordinates.Position).Length; if (targetRange > controller.VisionRadius) diff --git a/Content.Server/AI/WorldState/StateData.cs b/Content.Server/AI/WorldState/StateData.cs index 850faa2cdf..8563ef57fe 100644 --- a/Content.Server/AI/WorldState/StateData.cs +++ b/Content.Server/AI/WorldState/StateData.cs @@ -32,16 +32,16 @@ namespace Content.Server.AI.WorldState public abstract class StateData : IAiState { public abstract string Name { get; } - protected IEntity Owner { get; private set; } + protected IEntity Owner { get; private set; } = default!; public void Setup(IEntity owner) { Owner = owner; } - public abstract T GetValue(); + public abstract T? GetValue(); } - + /// /// For when we want to set StateData but not reset it when re-planning actions /// Useful for group blackboard sharing or to avoid repeating the same action (e.g. bark phrases). @@ -51,21 +51,21 @@ namespace Content.Server.AI.WorldState { // Probably not the best class name but couldn't think of anything better public abstract string Name { get; } - private IEntity Owner { get; set; } + private IEntity? Owner { get; set; } - private T _value; + private T? _value; public void Setup(IEntity owner) { Owner = owner; } - public virtual void SetValue(T value) + public virtual void SetValue(T? value) { _value = value; } - public T GetValue() + public T? GetValue() { return _value; } @@ -79,8 +79,8 @@ namespace Content.Server.AI.WorldState public abstract class PlanningStateData : IAiState, IPlanningState { public abstract string Name { get; } - protected IEntity Owner { get; private set; } - protected T Value; + protected IEntity? Owner { get; private set; } + protected T? Value; public void Setup(IEntity owner) { @@ -89,12 +89,12 @@ namespace Content.Server.AI.WorldState public abstract void Reset(); - public T GetValue() + public T? GetValue() { return Value; } - public virtual void SetValue(T value) + public virtual void SetValue(T? value) { Value = value; } @@ -108,9 +108,9 @@ namespace Content.Server.AI.WorldState public abstract class CachedStateData : IAiState, ICachedState { public abstract string Name { get; } - protected IEntity Owner { get; private set; } + protected IEntity Owner { get; private set; } = default!; private bool _cached; - protected T Value; + protected T Value = default!; private TimeSpan _lastCache = TimeSpan.Zero; /// /// How long something stays in the cache before new values are retrieved @@ -125,7 +125,7 @@ namespace Content.Server.AI.WorldState public void CheckCache() { var curTime = IoCManager.Resolve().CurTime; - + if (!_cached || (curTime - _lastCache).TotalSeconds >= CacheTime) { _cached = false; diff --git a/Content.Server/AI/WorldState/States/Clothing/EquippedClothingState.cs b/Content.Server/AI/WorldState/States/Clothing/EquippedClothingState.cs index 8d305c44d9..462683a1bd 100644 --- a/Content.Server/AI/WorldState/States/Clothing/EquippedClothingState.cs +++ b/Content.Server/AI/WorldState/States/Clothing/EquippedClothingState.cs @@ -15,7 +15,7 @@ namespace Content.Server.AI.WorldState.States.Clothing { var result = new Dictionary(); - if (!Owner.TryGetComponent(out InventoryComponent inventoryComponent)) + if (!Owner.TryGetComponent(out InventoryComponent? inventoryComponent)) { return result; } diff --git a/Content.Server/AI/WorldState/States/Clothing/NearbyClothingState.cs b/Content.Server/AI/WorldState/States/Clothing/NearbyClothingState.cs index 4845bfa663..40feb0241a 100644 --- a/Content.Server/AI/WorldState/States/Clothing/NearbyClothingState.cs +++ b/Content.Server/AI/WorldState/States/Clothing/NearbyClothingState.cs @@ -18,7 +18,7 @@ namespace Content.Server.AI.WorldState.States.Clothing { var result = new List(); - if (!Owner.TryGetComponent(out AiControllerComponent controller)) + if (!Owner.TryGetComponent(out AiControllerComponent? controller)) { return result; } diff --git a/Content.Server/AI/WorldState/States/Combat/Nearby/NearbyMeleeWeapons.cs b/Content.Server/AI/WorldState/States/Combat/Nearby/NearbyMeleeWeapons.cs index 458e6f5518..5c9d1b01f5 100644 --- a/Content.Server/AI/WorldState/States/Combat/Nearby/NearbyMeleeWeapons.cs +++ b/Content.Server/AI/WorldState/States/Combat/Nearby/NearbyMeleeWeapons.cs @@ -16,7 +16,7 @@ namespace Content.Server.AI.WorldState.States.Combat.Nearby { var result = new List(); - if (!Owner.TryGetComponent(out AiControllerComponent controller)) + if (!Owner.TryGetComponent(out AiControllerComponent? controller)) { return result; } diff --git a/Content.Server/AI/WorldState/States/Hands/AnyFreeHandState.cs b/Content.Server/AI/WorldState/States/Hands/AnyFreeHandState.cs index fdf61ebb9a..617ebbfc04 100644 --- a/Content.Server/AI/WorldState/States/Hands/AnyFreeHandState.cs +++ b/Content.Server/AI/WorldState/States/Hands/AnyFreeHandState.cs @@ -9,7 +9,7 @@ namespace Content.Server.AI.WorldState.States.Hands public override string Name => "AnyFreeHand"; public override bool GetValue() { - if (!Owner.TryGetComponent(out HandsComponent handsComponent)) + if (!Owner.TryGetComponent(out HandsComponent? handsComponent)) { return false; } diff --git a/Content.Server/AI/WorldState/States/Hands/FreeHands.cs b/Content.Server/AI/WorldState/States/Hands/FreeHands.cs index 3a8f2e0807..4fe8d4c6ec 100644 --- a/Content.Server/AI/WorldState/States/Hands/FreeHands.cs +++ b/Content.Server/AI/WorldState/States/Hands/FreeHands.cs @@ -13,7 +13,7 @@ namespace Content.Server.AI.WorldState.States.Hands { var result = new List(); - if (!Owner.TryGetComponent(out HandsComponent handsComponent)) + if (!Owner.TryGetComponent(out HandsComponent? handsComponent)) { return result; } diff --git a/Content.Server/AI/WorldState/States/Hands/HandItemsState.cs b/Content.Server/AI/WorldState/States/Hands/HandItemsState.cs index dc8e0c9902..796a279b8b 100644 --- a/Content.Server/AI/WorldState/States/Hands/HandItemsState.cs +++ b/Content.Server/AI/WorldState/States/Hands/HandItemsState.cs @@ -12,7 +12,7 @@ namespace Content.Server.AI.WorldState.States.Hands public override List GetValue() { var result = new List(); - if (!Owner.TryGetComponent(out HandsComponent handsComponent)) + if (!Owner.TryGetComponent(out HandsComponent? handsComponent)) { return result; } diff --git a/Content.Server/AI/WorldState/States/Inventory/EquippedEntityState.cs b/Content.Server/AI/WorldState/States/Inventory/EquippedEntityState.cs index 11a90465e0..5b8d30e172 100644 --- a/Content.Server/AI/WorldState/States/Inventory/EquippedEntityState.cs +++ b/Content.Server/AI/WorldState/States/Inventory/EquippedEntityState.cs @@ -12,9 +12,9 @@ namespace Content.Server.AI.WorldState.States.Inventory { public override string Name => "EquippedEntity"; - public override IEntity GetValue() + public override IEntity? GetValue() { - if (!Owner.TryGetComponent(out HandsComponent handsComponent)) + if (!Owner.TryGetComponent(out HandsComponent? handsComponent)) { return null; } diff --git a/Content.Server/AI/WorldState/States/Inventory/InventoryState.cs b/Content.Server/AI/WorldState/States/Inventory/InventoryState.cs index 695fb488e9..7df2e40ed7 100644 --- a/Content.Server/AI/WorldState/States/Inventory/InventoryState.cs +++ b/Content.Server/AI/WorldState/States/Inventory/InventoryState.cs @@ -12,13 +12,13 @@ namespace Content.Server.AI.WorldState.States.Inventory public override IEnumerable GetValue() { - if (Owner.TryGetComponent(out HandsComponent handsComponent)) + if (Owner.TryGetComponent(out HandsComponent? handsComponent)) { foreach (var item in handsComponent.GetAllHeldItems()) { if (item.Owner.Deleted) continue; - + yield return item.Owner; } } diff --git a/Content.Server/AI/WorldState/States/Inventory/LastOpenedStorageState.cs b/Content.Server/AI/WorldState/States/Inventory/LastOpenedStorageState.cs index ec309c554d..c15881fa83 100644 --- a/Content.Server/AI/WorldState/States/Inventory/LastOpenedStorageState.cs +++ b/Content.Server/AI/WorldState/States/Inventory/LastOpenedStorageState.cs @@ -14,7 +14,7 @@ namespace Content.Server.AI.WorldState.States.Inventory // Fine for now I guess public override string Name => "LastOpenedStorage"; - public override void SetValue(IEntity value) + public override void SetValue(IEntity? value) { base.SetValue(value); if (value != null && !value.HasComponent()) @@ -23,4 +23,4 @@ namespace Content.Server.AI.WorldState.States.Inventory } } } -} \ No newline at end of file +} diff --git a/Content.Server/AI/WorldState/States/Mobs/NearbyBodiesState.cs b/Content.Server/AI/WorldState/States/Mobs/NearbyBodiesState.cs index 764406e0f8..dca076c4f8 100644 --- a/Content.Server/AI/WorldState/States/Mobs/NearbyBodiesState.cs +++ b/Content.Server/AI/WorldState/States/Mobs/NearbyBodiesState.cs @@ -16,7 +16,7 @@ namespace Content.Server.AI.WorldState.States.Mobs { var result = new List(); - if (!Owner.TryGetComponent(out AiControllerComponent controller)) + if (!Owner.TryGetComponent(out AiControllerComponent? controller)) { return result; } diff --git a/Content.Server/AI/WorldState/States/Mobs/NearbyPlayersState.cs b/Content.Server/AI/WorldState/States/Mobs/NearbyPlayersState.cs index d974a2cd01..5c4ca134a3 100644 --- a/Content.Server/AI/WorldState/States/Mobs/NearbyPlayersState.cs +++ b/Content.Server/AI/WorldState/States/Mobs/NearbyPlayersState.cs @@ -17,7 +17,7 @@ namespace Content.Server.AI.WorldState.States.Mobs { var result = new List(); - if (!Owner.TryGetComponent(out AiControllerComponent controller)) + if (!Owner.TryGetComponent(out AiControllerComponent? controller)) { return result; } @@ -27,6 +27,11 @@ namespace Content.Server.AI.WorldState.States.Mobs foreach (var player in nearbyPlayers) { + if (player.AttachedEntity == null) + { + continue; + } + if (player.AttachedEntity != Owner && player.AttachedEntity.HasComponent()) { result.Add(player.AttachedEntity); diff --git a/Content.Server/AI/WorldState/States/Nutrition/HungryState.cs b/Content.Server/AI/WorldState/States/Nutrition/HungryState.cs index b936e47f3d..8a852437d5 100644 --- a/Content.Server/AI/WorldState/States/Nutrition/HungryState.cs +++ b/Content.Server/AI/WorldState/States/Nutrition/HungryState.cs @@ -12,7 +12,7 @@ namespace Content.Server.AI.WorldState.States.Nutrition public override bool GetValue() { - if (!Owner.TryGetComponent(out HungerComponent hungerComponent)) + if (!Owner.TryGetComponent(out HungerComponent? hungerComponent)) { return false; } diff --git a/Content.Server/AI/WorldState/States/Nutrition/NearbyDrinkState.cs b/Content.Server/AI/WorldState/States/Nutrition/NearbyDrinkState.cs index b8574ea998..4816fa09eb 100644 --- a/Content.Server/AI/WorldState/States/Nutrition/NearbyDrinkState.cs +++ b/Content.Server/AI/WorldState/States/Nutrition/NearbyDrinkState.cs @@ -18,7 +18,7 @@ namespace Content.Server.AI.WorldState.States.Nutrition { var result = new List(); - if (!Owner.TryGetComponent(out AiControllerComponent controller)) + if (!Owner.TryGetComponent(out AiControllerComponent? controller)) { return result; } diff --git a/Content.Server/AI/WorldState/States/Nutrition/NearbyFoodState.cs b/Content.Server/AI/WorldState/States/Nutrition/NearbyFoodState.cs index 7abc8ab27d..9da058931e 100644 --- a/Content.Server/AI/WorldState/States/Nutrition/NearbyFoodState.cs +++ b/Content.Server/AI/WorldState/States/Nutrition/NearbyFoodState.cs @@ -18,7 +18,7 @@ namespace Content.Server.AI.WorldState.States.Nutrition { var result = new List(); - if (!Owner.TryGetComponent(out AiControllerComponent controller)) + if (!Owner.TryGetComponent(out AiControllerComponent? controller)) { return result; } diff --git a/Content.Server/AI/WorldState/States/Nutrition/ThirstyState.cs b/Content.Server/AI/WorldState/States/Nutrition/ThirstyState.cs index e8a13e9e17..f71f263ba3 100644 --- a/Content.Server/AI/WorldState/States/Nutrition/ThirstyState.cs +++ b/Content.Server/AI/WorldState/States/Nutrition/ThirstyState.cs @@ -12,7 +12,7 @@ namespace Content.Server.AI.WorldState.States.Nutrition public override bool GetValue() { - if (!Owner.TryGetComponent(out ThirstComponent thirstComponent)) + if (!Owner.TryGetComponent(out ThirstComponent? thirstComponent)) { return false; } diff --git a/Content.Server/Actions/DebugInstant.cs b/Content.Server/Actions/DebugInstant.cs index d20029b192..8ad9ff8366 100644 --- a/Content.Server/Actions/DebugInstant.cs +++ b/Content.Server/Actions/DebugInstant.cs @@ -21,14 +21,14 @@ namespace Content.Server.Actions args.Performer.PopupMessageEveryone(Message); if (Cooldown > 0) { - args.ItemActions.Cooldown(args.ActionType, Cooldowns.SecondsFromNow(Cooldown)); + args.ItemActions?.Cooldown(args.ActionType, Cooldowns.SecondsFromNow(Cooldown)); } } public void DoInstantAction(InstantActionEventArgs args) { args.Performer.PopupMessageEveryone(Message); - args.PerformerActions.Cooldown(args.ActionType, Cooldowns.SecondsFromNow(Cooldown)); + args.PerformerActions?.Cooldown(args.ActionType, Cooldowns.SecondsFromNow(Cooldown)); } } } diff --git a/Content.Server/Administration/Commands/AGhost.cs b/Content.Server/Administration/Commands/AGhost.cs index 4454f79872..ce4ed0d737 100644 --- a/Content.Server/Administration/Commands/AGhost.cs +++ b/Content.Server/Administration/Commands/AGhost.cs @@ -46,7 +46,7 @@ namespace Content.Server.Administration.Commands if (canReturn) { - ghost.Name = mind.CharacterName; + ghost.Name = mind.CharacterName ?? string.Empty; mind.Visit(ghost); } else diff --git a/Content.Server/Administration/Commands/ControlMob.cs b/Content.Server/Administration/Commands/ControlMob.cs index aff1e4526c..eeebabc970 100644 --- a/Content.Server/Administration/Commands/ControlMob.cs +++ b/Content.Server/Administration/Commands/ControlMob.cs @@ -7,6 +7,7 @@ using Robust.Shared.Console; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; +using Robust.Shared.Utility; namespace Content.Server.Administration.Commands { @@ -33,7 +34,6 @@ namespace Content.Server.Administration.Commands } - var mind = player.ContentData().Mind; var entityManager = IoCManager.Resolve(); if (!int.TryParse(args[0], out var targetId)) @@ -51,20 +51,25 @@ namespace Content.Server.Administration.Commands } var target = entityManager.GetEntity(eUid); - if (!target.TryGetComponent(out MindComponent mindComponent)) + if (!target.TryGetComponent(out MindComponent? mindComponent)) { shell.WriteLine(Loc.GetString("Target entity is not a mob!")); return; } - var oldEntity = mind.CurrentEntity; + var mind = player.ContentData()?.Mind; + + DebugTools.AssertNotNull(mind); + + var oldEntity = mind!.CurrentEntity; mindComponent.Mind?.TransferTo(null); mind.TransferTo(target); - if(oldEntity.HasComponent()) - oldEntity.Delete(); + DebugTools.AssertNotNull(oldEntity); + if (oldEntity!.HasComponent()) + oldEntity.Delete(); } } } diff --git a/Content.Server/Administration/Commands/WarpCommand.cs b/Content.Server/Administration/Commands/WarpCommand.cs index 5c3ce5dadf..e5e28ca11f 100644 --- a/Content.Server/Administration/Commands/WarpCommand.cs +++ b/Content.Server/Administration/Commands/WarpCommand.cs @@ -115,7 +115,7 @@ namespace Content.Server.Administration.Commands if (found.GetGridId(entityManager) != GridId.Invalid) { player.AttachedEntity.Transform.Coordinates = found; - if (player.AttachedEntity.TryGetComponent(out IPhysBody physics)) + if (player.AttachedEntity.TryGetComponent(out IPhysBody? physics)) { physics.LinearVelocity = Vector2.Zero; } diff --git a/Content.Server/Alert/Click/ResistFire.cs b/Content.Server/Alert/Click/ResistFire.cs index 7a6e2a5fe0..7eab315dab 100644 --- a/Content.Server/Alert/Click/ResistFire.cs +++ b/Content.Server/Alert/Click/ResistFire.cs @@ -14,7 +14,7 @@ namespace Content.Server.Alert.Click { public void AlertClicked(ClickAlertEventArgs args) { - if (args.Player.TryGetComponent(out FlammableComponent flammable)) + if (args.Player.TryGetComponent(out FlammableComponent? flammable)) { flammable.Resist(); } diff --git a/Content.Server/Alert/Click/StopPiloting.cs b/Content.Server/Alert/Click/StopPiloting.cs index 6b50396d4d..c3dc34d4d6 100644 --- a/Content.Server/Alert/Click/StopPiloting.cs +++ b/Content.Server/Alert/Click/StopPiloting.cs @@ -14,7 +14,7 @@ namespace Content.Server.Alert.Click { public void AlertClicked(ClickAlertEventArgs args) { - if (args.Player.TryGetComponent(out ShuttleControllerComponent controller)) + if (args.Player.TryGetComponent(out ShuttleControllerComponent? controller)) { controller.RemoveController(); } diff --git a/Content.Server/Alert/Click/Unbuckle.cs b/Content.Server/Alert/Click/Unbuckle.cs index 210575748f..1d2b2a3a11 100644 --- a/Content.Server/Alert/Click/Unbuckle.cs +++ b/Content.Server/Alert/Click/Unbuckle.cs @@ -14,7 +14,7 @@ namespace Content.Server.Alert.Click { public void AlertClicked(ClickAlertEventArgs args) { - if (args.Player.TryGetComponent(out BuckleComponent buckle)) + if (args.Player.TryGetComponent(out BuckleComponent? buckle)) { buckle.TryUnbuckle(args.Player); } diff --git a/Content.Server/Atmos/ExcitedGroup.cs b/Content.Server/Atmos/ExcitedGroup.cs index a8add3f1d0..a03e61de11 100644 --- a/Content.Server/Atmos/ExcitedGroup.cs +++ b/Content.Server/Atmos/ExcitedGroup.cs @@ -15,7 +15,7 @@ namespace Content.Server.Atmos private readonly HashSet _tiles = new(); [ViewVariables] - private GridAtmosphereComponent _gridAtmosphereComponent; + private GridAtmosphereComponent _gridAtmosphereComponent = default!; [ViewVariables] public int DismantleCooldown { get; set; } @@ -139,7 +139,7 @@ namespace Content.Server.Atmos Dismantle(false); - _gridAtmosphereComponent = null; + _gridAtmosphereComponent = null!; } } } diff --git a/Content.Server/Atmos/TileAtmosphere.cs b/Content.Server/Atmos/TileAtmosphere.cs index a409408254..d2dfd20dc9 100644 --- a/Content.Server/Atmos/TileAtmosphere.cs +++ b/Content.Server/Atmos/TileAtmosphere.cs @@ -1,3 +1,4 @@ +#nullable disable warnings #nullable enable annotations using System; using System.Buffers; diff --git a/Content.Server/Cargo/CargoBankAccount.cs b/Content.Server/Cargo/CargoBankAccount.cs index 477d148791..4dee23a2cf 100644 --- a/Content.Server/Cargo/CargoBankAccount.cs +++ b/Content.Server/Cargo/CargoBankAccount.cs @@ -21,7 +21,7 @@ namespace Content.Server.Cargo } } - public event Action OnBalanceChange; + public event Action? OnBalanceChange; public CargoBankAccount(int id, string name, int balance) { diff --git a/Content.Server/Cargo/CargoOrderDatabase.cs b/Content.Server/Cargo/CargoOrderDatabase.cs index 6698b65203..c4cd264c59 100644 --- a/Content.Server/Cargo/CargoOrderDatabase.cs +++ b/Content.Server/Cargo/CargoOrderDatabase.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using Content.Shared.Prototypes.Cargo; using Robust.Shared.Localization; @@ -38,15 +39,9 @@ namespace Content.Server.Cargo return _orders.Values.ToList(); } - public bool TryGetOrder(int id, out CargoOrderData order) + public bool TryGetOrder(int id, [NotNullWhen(true)] out CargoOrderData? order) { - if (_orders.TryGetValue(id, out var _order)) - { - order = _order; - return true; - } - order = null; - return false; + return _orders.TryGetValue(id, out order); } public List SpliceApproved() diff --git a/Content.Server/Chat/ChatManager.cs b/Content.Server/Chat/ChatManager.cs index b1781841b0..918b218c3c 100644 --- a/Content.Server/Chat/ChatManager.cs +++ b/Content.Server/Chat/ChatManager.cs @@ -60,7 +60,7 @@ namespace Content.Server.Chat private const string MaxLengthExceededMessage = "Your message exceeded {0} character limit"; //TODO: make prio based? - private List _chatTransformHandlers; + private readonly List _chatTransformHandlers = new(); private bool _oocEnabled = true; private bool _adminOocEnabled = true; @@ -74,8 +74,6 @@ namespace Content.Server.Chat msg.MaxMessageLength = MaxMessageLength; _netManager.ServerSendToAll(msg); - _chatTransformHandlers = new List(); - _configurationManager.OnValueChanged(CCVars.OocEnabled, OnOocEnabledChanged, true); _configurationManager.OnValueChanged(CCVars.AdminOocEnabled, OnAdminOocEnabledChanged, true); } @@ -128,7 +126,7 @@ namespace Content.Server.Chat } // Check if message exceeds the character limit if the sender is a player - if (source.TryGetComponent(out IActorComponent actor) && + if (source.TryGetComponent(out IActorComponent? actor) && message.Length > MaxMessageLength) { var feedback = Loc.GetString(MaxLengthExceededMessage, MaxMessageLength); @@ -158,9 +156,9 @@ namespace Content.Server.Chat message = message[0].ToString().ToUpper() + message.Remove(0, 1); - if (source.TryGetComponent(out InventoryComponent inventory) && - inventory.TryGetSlotItem(EquipmentSlotDefines.Slots.EARS, out ItemComponent item) && - item.Owner.TryGetComponent(out HeadsetComponent headset)) + if (source.TryGetComponent(out InventoryComponent? inventory) && + inventory.TryGetSlotItem(EquipmentSlotDefines.Slots.EARS, out ItemComponent? item) && + item.Owner.TryGetComponent(out HeadsetComponent? headset)) { headset.RadioRequested = true; } @@ -197,13 +195,13 @@ namespace Content.Server.Chat } // Check if entity is a player - if (!source.TryGetComponent(out IActorComponent actor)) + if (!source.TryGetComponent(out IActorComponent? actor)) { return; } // Check if message exceeds the character limit - if (actor.playerSession != null && action.Length > MaxMessageLength) + if (action.Length > MaxMessageLength) { DispatchServerMessage(actor.playerSession, Loc.GetString(MaxLengthExceededMessage, MaxMessageLength)); return; @@ -282,7 +280,7 @@ namespace Content.Server.Chat var msg = _netManager.CreateNetMessage(); msg.Channel = ChatChannel.Dead; msg.Message = message; - msg.MessageWrap = $"{Loc.GetString("DEAD")}: {player.AttachedEntity.Name}: {{0}}"; + msg.MessageWrap = $"{Loc.GetString("DEAD")}: {player.AttachedEntity?.Name}: {{0}}"; msg.SenderEntity = player.AttachedEntityUid.GetValueOrDefault(); _netManager.ServerSendToMany(msg, clients.ToList()); } diff --git a/Content.Server/Chemistry/Metabolism/DefaultDrink.cs b/Content.Server/Chemistry/Metabolism/DefaultDrink.cs index 1803f475f9..adaa63a6ff 100644 --- a/Content.Server/Chemistry/Metabolism/DefaultDrink.cs +++ b/Content.Server/Chemistry/Metabolism/DefaultDrink.cs @@ -25,7 +25,7 @@ namespace Content.Server.Chemistry.Metabolism ReagentUnit IMetabolizable.Metabolize(IEntity solutionEntity, string reagentId, float tickTime) { var metabolismAmount = MetabolismRate * tickTime; - if (solutionEntity.TryGetComponent(out ThirstComponent thirst)) + if (solutionEntity.TryGetComponent(out ThirstComponent? thirst)) thirst.UpdateThirst(metabolismAmount.Float() * HydrationFactor); //Return amount of reagent to be removed, remove reagent regardless of ThirstComponent presence diff --git a/Content.Server/Chemistry/Metabolism/DefaultFood.cs b/Content.Server/Chemistry/Metabolism/DefaultFood.cs index 3cca60f728..4fcfb67727 100644 --- a/Content.Server/Chemistry/Metabolism/DefaultFood.cs +++ b/Content.Server/Chemistry/Metabolism/DefaultFood.cs @@ -27,7 +27,7 @@ namespace Content.Server.Chemistry.Metabolism ReagentUnit IMetabolizable.Metabolize(IEntity solutionEntity, string reagentId, float tickTime) { var metabolismAmount = MetabolismRate * tickTime; - if (solutionEntity.TryGetComponent(out HungerComponent hunger)) + if (solutionEntity.TryGetComponent(out HungerComponent? hunger)) hunger.UpdateFood(metabolismAmount.Float() * NutritionFactor); //Return amount of reagent to be removed, remove reagent regardless of HungerComponent presence diff --git a/Content.Server/Chemistry/ReactionEffects/ExplosionReactionEffect.cs b/Content.Server/Chemistry/ReactionEffects/ExplosionReactionEffect.cs index 6b7167adbb..a5ed1b2244 100644 --- a/Content.Server/Chemistry/ReactionEffects/ExplosionReactionEffect.cs +++ b/Content.Server/Chemistry/ReactionEffects/ExplosionReactionEffect.cs @@ -26,12 +26,12 @@ namespace Content.Server.Chemistry.ReactionEffects /// [DataField("maxScale")] private float _maxScale = 1; - public void React(IEntity solutionEntity, double intensity) + public void React(IEntity? solutionEntity, double intensity) { - var floatIntensity = (float)intensity; + var floatIntensity = (float) intensity; if (solutionEntity == null) return; - if(!solutionEntity.TryGetComponent(out SolutionContainerComponent solution)) + if (!solutionEntity.HasComponent()) return; //Handle scaling diff --git a/Content.Server/Chemistry/TileReactions/CleanTileReaction.cs b/Content.Server/Chemistry/TileReactions/CleanTileReaction.cs index 2780c105bb..8455f1bb53 100644 --- a/Content.Server/Chemistry/TileReactions/CleanTileReaction.cs +++ b/Content.Server/Chemistry/TileReactions/CleanTileReaction.cs @@ -17,7 +17,7 @@ namespace Content.Server.Chemistry.TileReactions var amount = ReagentUnit.Zero; foreach (var entity in entities) { - if (entity.TryGetComponent(out CleanableComponent cleanable)) + if (entity.TryGetComponent(out CleanableComponent? cleanable)) { var next = amount + cleanable.CleanAmount; // Nothing left? diff --git a/Content.Server/Chemistry/TileReactions/ExtinguishTileReaction.cs b/Content.Server/Chemistry/TileReactions/ExtinguishTileReaction.cs index b9e05a5454..8801f4ffb4 100644 --- a/Content.Server/Chemistry/TileReactions/ExtinguishTileReaction.cs +++ b/Content.Server/Chemistry/TileReactions/ExtinguishTileReaction.cs @@ -19,7 +19,7 @@ namespace Content.Server.Chemistry.TileReactions { if (reactVolume <= ReagentUnit.Zero || tile.Tile.IsEmpty) return ReagentUnit.Zero; var tileAtmos = tile.GridIndices.GetTileAtmosphere(tile.GridIndex); - if (tileAtmos == null || !tileAtmos.Hotspot.Valid) return ReagentUnit.Zero; + if (tileAtmos == null || !tileAtmos.Hotspot.Valid || tileAtmos.Air == null) return ReagentUnit.Zero; tileAtmos.Air.Temperature = MathF.Max(MathF.Min(tileAtmos.Air.Temperature - (_coolingTemperature * 1000f), tileAtmos.Air.Temperature / _coolingTemperature), diff --git a/Content.Server/Chemistry/TileReactions/FlammableTileReaction.cs b/Content.Server/Chemistry/TileReactions/FlammableTileReaction.cs index d09312ee28..4ec75728c9 100644 --- a/Content.Server/Chemistry/TileReactions/FlammableTileReaction.cs +++ b/Content.Server/Chemistry/TileReactions/FlammableTileReaction.cs @@ -18,7 +18,7 @@ namespace Content.Server.Chemistry.TileReactions { if (reactVolume <= ReagentUnit.Zero || tile.Tile.IsEmpty) return ReagentUnit.Zero; var tileAtmos = tile.GridIndices.GetTileAtmosphere(tile.GridIndex); - if (tileAtmos == null || !tileAtmos.Hotspot.Valid) return ReagentUnit.Zero; + if (tileAtmos?.Air == null || !tileAtmos.Hotspot.Valid) return ReagentUnit.Zero; tileAtmos.Air.Temperature *= MathF.Max(_temperatureMultiplier * reactVolume.Float(), 1f); tileAtmos.Air.React(tileAtmos); return reactVolume; diff --git a/Content.Server/Commands/Chat/AdminChatCommand.cs b/Content.Server/Commands/Chat/AdminChatCommand.cs index f490c608a6..ce1d1d76fc 100644 --- a/Content.Server/Commands/Chat/AdminChatCommand.cs +++ b/Content.Server/Commands/Chat/AdminChatCommand.cs @@ -17,7 +17,14 @@ namespace Content.Server.Commands.Chat public void Execute(IConsoleShell shell, string argStr, string[] args) { - var player = shell.Player as IPlayerSession; + var player = (IPlayerSession?) shell.Player; + + if (player == null) + { + shell.WriteError("You can't run this command locally."); + return; + } + if (args.Length < 1) return; diff --git a/Content.Server/Commands/Chat/MeCommand.cs b/Content.Server/Commands/Chat/MeCommand.cs index 3c8fc235c1..65b5eda999 100644 --- a/Content.Server/Commands/Chat/MeCommand.cs +++ b/Content.Server/Commands/Chat/MeCommand.cs @@ -40,7 +40,13 @@ namespace Content.Server.Commands.Chat if (mindComponent == null) { - shell.WriteLine("You don't have a mind!"); + shell.WriteError("You don't have a mind!"); + return; + } + + if (mindComponent.OwnedEntity == null) + { + shell.WriteError("You don't have an entity!"); return; } diff --git a/Content.Server/Commands/Chat/OOCCommand.cs b/Content.Server/Commands/Chat/OOCCommand.cs index 98d744ba6a..3144e74fe0 100644 --- a/Content.Server/Commands/Chat/OOCCommand.cs +++ b/Content.Server/Commands/Chat/OOCCommand.cs @@ -16,7 +16,14 @@ namespace Content.Server.Commands.Chat public void Execute(IConsoleShell shell, string argStr, string[] args) { - var player = shell.Player as IPlayerSession; + var player = (IPlayerSession?) shell.Player; + + if (player == null) + { + shell.WriteError("You can't run this command locally."); + return; + } + if (args.Length < 1) return; diff --git a/Content.Server/Commands/Chat/SayCommand.cs b/Content.Server/Commands/Chat/SayCommand.cs index 56bf6770dd..282b1fd57b 100644 --- a/Content.Server/Commands/Chat/SayCommand.cs +++ b/Content.Server/Commands/Chat/SayCommand.cs @@ -53,7 +53,13 @@ namespace Content.Server.Commands.Chat if (mindComponent == null) { - shell.WriteLine("You don't have a mind!"); + shell.WriteError("You don't have a mind!"); + return; + } + + if (mindComponent.OwnedEntity == null) + { + shell.WriteError("You don't have an entity!"); return; } diff --git a/Content.Server/Commands/Chat/SuicideCommand.cs b/Content.Server/Commands/Chat/SuicideCommand.cs index f8e930cc3e..6c58c4ebfb 100644 --- a/Content.Server/Commands/Chat/SuicideCommand.cs +++ b/Content.Server/Commands/Chat/SuicideCommand.cs @@ -69,7 +69,7 @@ namespace Content.Server.Commands.Chat return; var chat = IoCManager.Resolve(); - var owner = player.ContentData()?.Mind?.OwnedComponent.Owner; + var owner = player.ContentData()?.Mind?.OwnedComponent?.Owner; if (owner == null) { diff --git a/Content.Server/Commands/GameTicking/JoinGameCommand.cs b/Content.Server/Commands/GameTicking/JoinGameCommand.cs index 708727ccf3..b18638c94d 100644 --- a/Content.Server/Commands/GameTicking/JoinGameCommand.cs +++ b/Content.Server/Commands/GameTicking/JoinGameCommand.cs @@ -49,11 +49,11 @@ namespace Content.Server.Commands.GameTicking shell.WriteLine($"{jobPrototype.Name} has no available slots."); return; } - ticker.MakeJoinGame(player, args[0].ToString()); + ticker.MakeJoinGame(player, args[0]); return; } - ticker.MakeJoinGame(player, null); + ticker.MakeJoinGame(player); } } } diff --git a/Content.Server/Commands/GameTicking/RespawnCommand.cs b/Content.Server/Commands/GameTicking/RespawnCommand.cs index 731dcb78e6..e765d5d0af 100644 --- a/Content.Server/Commands/GameTicking/RespawnCommand.cs +++ b/Content.Server/Commands/GameTicking/RespawnCommand.cs @@ -50,7 +50,7 @@ namespace Content.Server.Commands.GameTicking return; } - data.ContentData().WipeMind(); + data.ContentData()?.WipeMind(); shell.WriteLine("Player is not currently online, but they will respawn if they come back online"); return; } diff --git a/Content.Server/Commands/GameTicking/TileWallsCommand.cs b/Content.Server/Commands/GameTicking/TileWallsCommand.cs index 4873af00d5..69c18f1982 100644 --- a/Content.Server/Commands/GameTicking/TileWallsCommand.cs +++ b/Content.Server/Commands/GameTicking/TileWallsCommand.cs @@ -90,7 +90,7 @@ namespace Content.Server.Commands.GameTicking continue; } - if (!childEntity.TryGetComponent(out SnapGridComponent snapGrid)) + if (!childEntity.TryGetComponent(out SnapGridComponent? snapGrid)) { continue; } diff --git a/Content.Server/Commands/MachineLinking/SignalLinkerCommand.cs b/Content.Server/Commands/MachineLinking/SignalLinkerCommand.cs index c8c98d89c8..3cca0f84a8 100644 --- a/Content.Server/Commands/MachineLinking/SignalLinkerCommand.cs +++ b/Content.Server/Commands/MachineLinking/SignalLinkerCommand.cs @@ -19,7 +19,14 @@ namespace Content.Server.Commands.MachineLinking public void Execute(IConsoleShell shell, string argStr, string[] args) { - var player = shell.Player as IPlayerSession; + var player = (IPlayerSession?) shell.Player; + + if (player == null) + { + shell.WriteError("This command cannot be run locally."); + return; + } + bool? enable = null; if (args.Length > 0) { diff --git a/Content.Server/Commands/Mobs/AddRoleCommand.cs b/Content.Server/Commands/Mobs/AddRoleCommand.cs index 8e129a93e9..9f846e9c22 100644 --- a/Content.Server/Commands/Mobs/AddRoleCommand.cs +++ b/Content.Server/Commands/Mobs/AddRoleCommand.cs @@ -30,16 +30,21 @@ namespace Content.Server.Commands.Mobs } var mgr = IoCManager.Resolve(); - if (mgr.TryGetPlayerDataByUsername(args[0], out var data)) - { - var mind = data.ContentData().Mind; - var role = new Job(mind, _prototypeManager.Index(args[1])); - mind.AddRole(role); - } - else + if (!mgr.TryGetPlayerDataByUsername(args[0], out var data)) { shell.WriteLine("Can't find that mind"); + return; } + + var mind = data.ContentData()?.Mind; + if (mind == null) + { + shell.WriteLine("Can't find that mind"); + return; + } + + var role = new Job(mind, _prototypeManager.Index(args[1])); + mind.AddRole(role); } } -} \ No newline at end of file +} diff --git a/Content.Server/Commands/Mobs/MindInfoCommand.cs b/Content.Server/Commands/Mobs/MindInfoCommand.cs index 06c3d40e45..b568691686 100644 --- a/Content.Server/Commands/Mobs/MindInfoCommand.cs +++ b/Content.Server/Commands/Mobs/MindInfoCommand.cs @@ -26,23 +26,28 @@ namespace Content.Server.Commands.Mobs } var mgr = IoCManager.Resolve(); - if (mgr.TryGetSessionByUsername(args[0], out var data)) - { - var mind = data.ContentData().Mind; - - var builder = new StringBuilder(); - builder.AppendFormat("player: {0}, mob: {1}\nroles: ", mind.UserId, mind.OwnedComponent?.Owner?.Uid); - foreach (var role in mind.AllRoles) - { - builder.AppendFormat("{0} ", role.Name); - } - - shell.WriteLine(builder.ToString()); - } - else + if (!mgr.TryGetSessionByUsername(args[0], out var data)) { shell.WriteLine("Can't find that mind"); + return; } + + var mind = data.ContentData()?.Mind; + + if (mind == null) + { + shell.WriteLine("Can't find that mind"); + return; + } + + var builder = new StringBuilder(); + builder.AppendFormat("player: {0}, mob: {1}\nroles: ", mind.UserId, mind.OwnedComponent?.Owner?.Uid); + foreach (var role in mind.AllRoles) + { + builder.AppendFormat("{0} ", role.Name); + } + + shell.WriteLine(builder.ToString()); } } -} \ No newline at end of file +} diff --git a/Content.Server/Commands/Mobs/RemoveRoleCommand.cs b/Content.Server/Commands/Mobs/RemoveRoleCommand.cs index 34a6800dd9..876bb16b54 100644 --- a/Content.Server/Commands/Mobs/RemoveRoleCommand.cs +++ b/Content.Server/Commands/Mobs/RemoveRoleCommand.cs @@ -30,16 +30,22 @@ namespace Content.Server.Commands.Mobs } var mgr = IoCManager.Resolve(); - if (mgr.TryGetPlayerDataByUsername(args[0], out var data)) - { - var mind = data.ContentData().Mind; - var role = new Job(mind, _prototypeManager.Index(args[1])); - mind.RemoveRole(role); - } - else + if (!mgr.TryGetPlayerDataByUsername(args[0], out var data)) { shell.WriteLine("Can't find that mind"); + return; } + + var mind = data.ContentData()?.Mind; + + if (mind == null) + { + shell.WriteLine("Can't find that mind"); + return; + } + + var role = new Job(mind, _prototypeManager.Index(args[1])); + mind.RemoveRole(role); } } -} \ No newline at end of file +} diff --git a/Content.Server/Construction/Conditions/DoorWelded.cs b/Content.Server/Construction/Conditions/DoorWelded.cs index 8d1810703e..9de8d209f7 100644 --- a/Content.Server/Construction/Conditions/DoorWelded.cs +++ b/Content.Server/Construction/Conditions/DoorWelded.cs @@ -6,6 +6,7 @@ using Robust.Shared.GameObjects; using Robust.Shared.Localization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Utility; +using static Content.Shared.GameObjects.Components.Doors.SharedDoorComponent; namespace Content.Server.Construction.Conditions { @@ -17,15 +18,15 @@ namespace Content.Server.Construction.Conditions public async Task Condition(IEntity entity) { - if (!entity.TryGetComponent(out ServerDoorComponent doorComponent)) return false; + if (!entity.TryGetComponent(out ServerDoorComponent? doorComponent)) return false; return doorComponent.IsWeldedShut == Welded; } public bool DoExamine(IEntity entity, FormattedMessage message, bool inDetailsRange) { - if (!entity.TryGetComponent(out ServerDoorComponent doorComponent)) return false; + if (!entity.TryGetComponent(out ServerDoorComponent? doorComponent)) return false; - if (doorComponent.State == ServerDoorComponent.DoorState.Closed && Welded) + if (doorComponent.State == DoorState.Closed && Welded) { message.AddMarkup(Loc.GetString("First, weld the door.\n")); return true; diff --git a/Content.Server/Construction/Conditions/EntityAnchored.cs b/Content.Server/Construction/Conditions/EntityAnchored.cs index bb1832bf67..1a35e45076 100644 --- a/Content.Server/Construction/Conditions/EntityAnchored.cs +++ b/Content.Server/Construction/Conditions/EntityAnchored.cs @@ -2,9 +2,8 @@ using Content.Shared.Construction; using JetBrains.Annotations; using Robust.Shared.GameObjects; -using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Physics; -using Robust.Shared.Serialization; +using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Utility; namespace Content.Server.Construction.Conditions @@ -17,14 +16,14 @@ namespace Content.Server.Construction.Conditions public async Task Condition(IEntity entity) { - if (!entity.TryGetComponent(out IPhysBody physics)) return false; + if (!entity.TryGetComponent(out IPhysBody? physics)) return false; return (physics.BodyType == BodyType.Static && Anchored) || (physics.BodyType != BodyType.Static && !Anchored); } public bool DoExamine(IEntity entity, FormattedMessage message, bool inDetailsRange) { - if (!entity.TryGetComponent(out IPhysBody physics)) return false; + if (!entity.TryGetComponent(out IPhysBody? physics)) return false; switch (Anchored) { diff --git a/Content.Server/Construction/Conditions/WirePanel.cs b/Content.Server/Construction/Conditions/WirePanel.cs index 6344dc0bd8..06fe6814ba 100644 --- a/Content.Server/Construction/Conditions/WirePanel.cs +++ b/Content.Server/Construction/Conditions/WirePanel.cs @@ -17,14 +17,14 @@ namespace Content.Server.Construction.Conditions public async Task Condition(IEntity entity) { - if (!entity.TryGetComponent(out WiresComponent wires)) return false; + if (!entity.TryGetComponent(out WiresComponent? wires)) return false; return wires.IsPanelOpen == Open; } public bool DoExamine(IEntity entity, FormattedMessage message, bool inDetailsRange) { - if (!entity.TryGetComponent(out WiresComponent wires)) return false; + if (!entity.TryGetComponent(out WiresComponent? wires)) return false; switch (Open) { diff --git a/Content.Server/Content.Server.csproj b/Content.Server/Content.Server.csproj index 92daac324a..33421f41bb 100644 --- a/Content.Server/Content.Server.csproj +++ b/Content.Server/Content.Server.csproj @@ -11,6 +11,7 @@ Exe 1998 nullable + enable diff --git a/Content.Server/DeviceNetwork/DeviceNetwork.cs b/Content.Server/DeviceNetwork/DeviceNetwork.cs index 3d9d1f7c93..939d9cf1da 100644 --- a/Content.Server/DeviceNetwork/DeviceNetwork.cs +++ b/Content.Server/DeviceNetwork/DeviceNetwork.cs @@ -1,7 +1,8 @@ using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using Content.Server.Interfaces; using Robust.Shared.IoC; -using System.Collections.Generic; using Robust.Shared.Random; namespace Content.Server.GameObjects.EntitySystems.DeviceNetwork @@ -21,14 +22,7 @@ namespace Content.Server.GameObjects.EntitySystems.DeviceNetwork public DeviceNetworkConnection Register(int netId, int frequency, OnReceiveNetMessage messageHandler, bool receiveAll = false) { var address = GenerateValidAddress(netId, frequency); - - var device = new NetworkDevice - { - Address = address, - Frequency = frequency, - ReceiveAll = receiveAll, - ReceiveNetMessage = messageHandler - }; + var device = new NetworkDevice(frequency, address, messageHandler, receiveAll); AddDevice(netId, device); @@ -62,16 +56,7 @@ namespace Content.Server.GameObjects.EntitySystems.DeviceNetwork if (!_devices.ContainsKey(netId)) return false; - var package = new NetworkPackage() - { - NetId = netId, - Frequency = frequency, - Address = address, - Broadcast = broadcast, - Data = data, - Sender = sender, - Metadata = metadata - }; + var package = new NetworkPackage(netId, frequency, address, broadcast, data, metadata, sender); _packages.Enqueue(package); return true; @@ -79,20 +64,28 @@ namespace Content.Server.GameObjects.EntitySystems.DeviceNetwork public void RemoveDevice(int netId, int frequency, string address) { - var device = DeviceWithAddress(netId, frequency, address); - _devices[netId].Remove(device); + if (TryDeviceWithAddress(netId, frequency, address, out var device)) + { + _devices[netId].Remove(device); + } } public void SetDeviceReceiveAll(int netId, int frequency, string address, bool receiveAll) { - var device = DeviceWithAddress(netId, frequency, address); - device.ReceiveAll = receiveAll; + if (TryDeviceWithAddress(netId, frequency, address, out var device)) + { + device.ReceiveAll = receiveAll; + } } public bool GetDeviceReceiveAll(int netId, int frequency, string address) { - var device = DeviceWithAddress(netId, frequency, address); - return device.ReceiveAll; + if (TryDeviceWithAddress(netId, frequency, address, out var device)) + { + return device.ReceiveAll; + } + + return false; } private string GenerateValidAddress(int netId, int frequency) @@ -128,7 +121,7 @@ namespace Content.Server.GameObjects.EntitySystems.DeviceNetwork return result; } - private NetworkDevice DeviceWithAddress(int netId, int frequency, string address) + private NetworkDevice? DeviceWithAddress(int netId, int frequency, string address) { var devices = DevicesForFrequency(netId, frequency); @@ -137,6 +130,12 @@ namespace Content.Server.GameObjects.EntitySystems.DeviceNetwork return device; } + private bool TryDeviceWithAddress(int netId, int frequency, string address, + [NotNullWhen(true)] out NetworkDevice? device) + { + return (device = DeviceWithAddress(netId, frequency, address)) != null; + } + private List DevicesWithReceiveAll(int netId, int frequency) { if (!_devices.ContainsKey(netId)) @@ -156,18 +155,19 @@ namespace Content.Server.GameObjects.EntitySystems.DeviceNetwork private void SendPackage(NetworkPackage package) { var devices = DevicesWithReceiveAll(package.NetId, package.Frequency); - var device = DeviceWithAddress(package.NetId, package.Frequency, package.Address); - devices.Add(device); + if (TryDeviceWithAddress(package.NetId, package.Frequency, package.Address, out var device)) + { + devices.Add(device); + } SendToDevices(devices, package, false); } private void SendToDevices(List devices, NetworkPackage package, bool broadcast) { - for (var index = 0; index < devices.Count; index++) + foreach (var device in devices) { - var device = devices[index]; if (device.Address == package.Sender) continue; @@ -177,6 +177,14 @@ namespace Content.Server.GameObjects.EntitySystems.DeviceNetwork internal class NetworkDevice { + internal NetworkDevice(int frequency, string address, OnReceiveNetMessage receiveNetMessage, bool receiveAll) + { + Frequency = frequency; + Address = address; + ReceiveNetMessage = receiveNetMessage; + ReceiveAll = receiveAll; + } + public int Frequency; public string Address; public OnReceiveNetMessage ReceiveNetMessage; @@ -185,6 +193,24 @@ namespace Content.Server.GameObjects.EntitySystems.DeviceNetwork internal class NetworkPackage { + internal NetworkPackage( + int netId, + int frequency, + string address, + bool broadcast, + IReadOnlyDictionary data, + Metadata metadata, + string sender) + { + NetId = netId; + Frequency = frequency; + Address = address; + Broadcast = broadcast; + Data = data; + Metadata = metadata; + Sender = sender; + } + public int NetId; public int Frequency; public string Address; diff --git a/Content.Server/DeviceNetwork/Metadata.cs b/Content.Server/DeviceNetwork/Metadata.cs index 1066676523..a0f1a18b3b 100644 --- a/Content.Server/DeviceNetwork/Metadata.cs +++ b/Content.Server/DeviceNetwork/Metadata.cs @@ -5,9 +5,9 @@ namespace Content.Server.GameObjects.EntitySystems.DeviceNetwork { public class Metadata : Dictionary { - public bool TryParseMetadata(string key, [NotNullWhen(true)] out T data) + public bool TryParseMetadata(string key, [NotNullWhen(true)] out T? data) { - if(TryGetValue(key, out var value) && value is T typedValue) + if (TryGetValue(key, out var value) && value is T typedValue) { data = typedValue; return true; diff --git a/Content.Server/DeviceNetwork/NetworkConnections/WiredNetworkConnection.cs b/Content.Server/DeviceNetwork/NetworkConnections/WiredNetworkConnection.cs index 046d8bc295..d313d76047 100644 --- a/Content.Server/DeviceNetwork/NetworkConnections/WiredNetworkConnection.cs +++ b/Content.Server/DeviceNetwork/NetworkConnections/WiredNetworkConnection.cs @@ -1,7 +1,8 @@ -using Content.Server.GameObjects.Components.NodeContainer; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using Content.Server.GameObjects.Components.NodeContainer; using Content.Server.GameObjects.Components.NodeContainer.NodeGroups; using Content.Server.GameObjects.Components.Power.ApcNetComponents; -using System.Collections.Generic; using Robust.Shared.GameObjects; namespace Content.Server.GameObjects.EntitySystems.DeviceNetwork @@ -62,21 +63,23 @@ namespace Content.Server.GameObjects.EntitySystems.DeviceNetwork return payload; } - private bool TryGetWireNet(PowerReceiverComponent powerReceiver, out INodeGroup net) + private bool TryGetWireNet(PowerReceiverComponent powerReceiver, [NotNullWhen(true)] out INodeGroup? net) { - if (powerReceiver.Provider is PowerProviderComponent && powerReceiver.Provider.ProviderOwner.TryGetComponent(out var nodeContainer)) + if (powerReceiver.Provider is PowerProviderComponent provider && + provider.ProviderOwner.TryGetComponent(out var nodeContainer)) { var nodes = nodeContainer.Nodes; - for (var index = 0; index < nodes.Count; index++) + + foreach (var node in nodes) { - if (nodes[index].NodeGroupID == NodeGroupID.WireNet) + if (node.NodeGroupID == NodeGroupID.WireNet) { - net = nodes[index].NodeGroup; + net = node.NodeGroup; return true; } } - } + net = default; return false; } diff --git a/Content.Server/EntryPoint.cs b/Content.Server/EntryPoint.cs index 96f18c4133..f5b0c17ef2 100644 --- a/Content.Server/EntryPoint.cs +++ b/Content.Server/EntryPoint.cs @@ -14,8 +14,8 @@ using Content.Server.Interfaces.PDA; using Content.Server.Sandbox; using Content.Server.Voting; using Content.Shared.Actions; -using Content.Shared.Kitchen; using Content.Shared.Alert; +using Content.Shared.Kitchen; using Robust.Server.Player; using Robust.Shared.ContentPack; using Robust.Shared.GameObjects; @@ -27,10 +27,10 @@ namespace Content.Server { public class EntryPoint : GameServer { - private IGameTicker _gameTicker; - private EuiManager _euiManager; - private StatusShell _statusShell; - private IVoteManager _voteManager; + private IGameTicker _gameTicker = default!; + private EuiManager _euiManager = default!; + private StatusShell _statusShell = default!; + private IVoteManager _voteManager = default!; /// public override void Init() diff --git a/Content.Server/GameObjects/Components/Access/AccessReaderComponent.cs b/Content.Server/GameObjects/Components/Access/AccessReaderComponent.cs index 7333ce0aba..dd147f9cde 100644 --- a/Content.Server/GameObjects/Components/Access/AccessReaderComponent.cs +++ b/Content.Server/GameObjects/Components/Access/AccessReaderComponent.cs @@ -97,7 +97,7 @@ namespace Content.Server.GameObjects.Components.Access if (entity.TryGetComponent(out InventoryComponent? inventoryComponent)) { if (inventoryComponent.HasSlot(EquipmentSlotDefines.Slots.IDCARD) && - inventoryComponent.TryGetSlotItem(EquipmentSlotDefines.Slots.IDCARD, out ItemComponent item) && + inventoryComponent.TryGetSlotItem(EquipmentSlotDefines.Slots.IDCARD, out ItemComponent? item) && item.Owner.TryGetComponent(out IAccess? idAccessComponent) ) { diff --git a/Content.Server/GameObjects/Components/Access/IdCardComponent.cs b/Content.Server/GameObjects/Components/Access/IdCardComponent.cs index 7a40a78631..dc3ec2ace9 100644 --- a/Content.Server/GameObjects/Components/Access/IdCardComponent.cs +++ b/Content.Server/GameObjects/Components/Access/IdCardComponent.cs @@ -1,7 +1,5 @@ using Robust.Shared.GameObjects; using Robust.Shared.Localization; -using Robust.Shared.Prototypes; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -14,12 +12,12 @@ namespace Content.Server.GameObjects.Components.Access /// See . [DataField("originalOwnerName")] - private string _ownerOriginalName; + private string _originalOwnerName = default!; [DataField("fullName")] - private string _fullName; + private string? _fullName; [ViewVariables(VVAccess.ReadWrite)] - public string FullName + public string? FullName { get => _fullName; set @@ -30,9 +28,9 @@ namespace Content.Server.GameObjects.Components.Access } [DataField("jobTitle")] - private string _jobTitle; + private string? _jobTitle; [ViewVariables(VVAccess.ReadWrite)] - public string JobTitle + public string? JobTitle { get => _jobTitle; set @@ -53,26 +51,22 @@ namespace Content.Server.GameObjects.Components.Access { if (string.IsNullOrWhiteSpace(FullName) && string.IsNullOrWhiteSpace(JobTitle)) { - Owner.Name = _ownerOriginalName; + Owner.Name = _originalOwnerName; return; } var jobSuffix = string.IsNullOrWhiteSpace(JobTitle) ? "" : $" ({JobTitle})"; - if (string.IsNullOrWhiteSpace(FullName)) - { - Owner.Name = Loc.GetString("{0}{1}", _ownerOriginalName, jobSuffix); - } - else - { - Owner.Name = Loc.GetString("{0}'s ID card{1}", FullName, jobSuffix); - } + Owner.Name = string.IsNullOrWhiteSpace(FullName) + ? Loc.GetString("{0}{1}", _originalOwnerName, jobSuffix) + : Loc.GetString("{0}'s ID card{1}", FullName, jobSuffix); } public override void Initialize() { base.Initialize(); - _ownerOriginalName ??= Owner.Name; + // ReSharper disable once ConstantNullCoalescingCondition + _originalOwnerName ??= Owner.Name; UpdateEntityName(); } } diff --git a/Content.Server/GameObjects/Components/Atmos/BarotraumaComponent.cs b/Content.Server/GameObjects/Components/Atmos/BarotraumaComponent.cs index e0388dd008..924c361db6 100644 --- a/Content.Server/GameObjects/Components/Atmos/BarotraumaComponent.cs +++ b/Content.Server/GameObjects/Components/Atmos/BarotraumaComponent.cs @@ -21,9 +21,9 @@ namespace Content.Server.GameObjects.Components.Atmos [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Update(float airPressure) { - if (!Owner.TryGetComponent(out IDamageableComponent damageable)) return; - Owner.TryGetComponent(out ServerAlertsComponent status); + if (!Owner.TryGetComponent(out IDamageableComponent? damageable)) return; + var status = Owner.GetComponentOrNull(); var highPressureMultiplier = 1f; var lowPressureMultiplier = 1f; diff --git a/Content.Server/GameObjects/Components/Atmos/FlammableComponent.cs b/Content.Server/GameObjects/Components/Atmos/FlammableComponent.cs index bde846aa6e..fd6404848d 100644 --- a/Content.Server/GameObjects/Components/Atmos/FlammableComponent.cs +++ b/Content.Server/GameObjects/Components/Atmos/FlammableComponent.cs @@ -17,10 +17,9 @@ using Content.Shared.Interfaces.GameObjects.Components; using Robust.Server.GameObjects; using Robust.Shared.GameObjects; using Robust.Shared.Localization; -using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Physics; using Robust.Shared.Physics.Collision; -using Robust.Shared.Serialization; +using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; namespace Content.Server.GameObjects.Components.Atmos @@ -84,7 +83,7 @@ namespace Content.Server.GameObjects.Components.Atmos FireStacks = MathF.Min(0, FireStacks + 1); } - Owner.TryGetComponent(out ServerAlertsComponent status); + Owner.TryGetComponent(out ServerAlertsComponent? status); if (!OnFire) { @@ -96,12 +95,12 @@ namespace Content.Server.GameObjects.Components.Atmos if (FireStacks > 0) { - if(Owner.TryGetComponent(out TemperatureComponent temp)) + if (Owner.TryGetComponent(out TemperatureComponent? temp)) { temp.ReceiveHeat(200 * FireStacks); } - if (Owner.TryGetComponent(out IDamageableComponent damageable)) + if (Owner.TryGetComponent(out IDamageableComponent? damageable)) { // TODO ATMOS Fire resistance from armor var damage = Math.Min((int) (FireStacks * 2.5f), 10); @@ -117,7 +116,7 @@ namespace Content.Server.GameObjects.Components.Atmos } // If we're in an oxygenless environment, put the fire out. - if (tile?.Air?.GetMoles(Gas.Oxygen) < 1f) + if (tile.Air?.GetMoles(Gas.Oxygen) < 1f) { Extinguish(); return; @@ -147,7 +146,7 @@ namespace Content.Server.GameObjects.Components.Atmos void IStartCollide.CollideWith(IPhysBody ourBody, IPhysBody otherBody, in Manifold manifold) { - if (!otherBody.Entity.TryGetComponent(out FlammableComponent otherFlammable)) + if (!otherBody.Entity.TryGetComponent(out FlammableComponent? otherFlammable)) return; if (!FireSpread || !otherFlammable.FireSpread) @@ -177,7 +176,7 @@ namespace Content.Server.GameObjects.Components.Atmos private void UpdateAppearance() { - if (Owner.Deleted || !Owner.TryGetComponent(out AppearanceComponent appearanceComponent)) return; + if (Owner.Deleted || !Owner.TryGetComponent(out AppearanceComponent? appearanceComponent)) return; appearanceComponent.SetData(FireVisuals.OnFire, OnFire); appearanceComponent.SetData(FireVisuals.FireStacks, FireStacks); } @@ -191,7 +190,7 @@ namespace Content.Server.GameObjects.Components.Atmos // This needs some improvements... public void Resist() { - if (!OnFire || !ActionBlockerSystem.CanInteract(Owner) || _resisting || !Owner.TryGetComponent(out StunnableComponent stunnable)) return; + if (!OnFire || !ActionBlockerSystem.CanInteract(Owner) || _resisting || !Owner.TryGetComponent(out StunnableComponent? stunnable)) return; _resisting = true; diff --git a/Content.Server/GameObjects/Components/Atmos/GasTankComponent.cs b/Content.Server/GameObjects/Components/Atmos/GasTankComponent.cs index 9533c00a90..e8be9a2a2f 100644 --- a/Content.Server/GameObjects/Components/Atmos/GasTankComponent.cs +++ b/Content.Server/GameObjects/Components/Atmos/GasTankComponent.cs @@ -1,4 +1,5 @@ #nullable enable +#nullable disable warnings using System; using Content.Server.Atmos; using Content.Server.Explosions; diff --git a/Content.Server/GameObjects/Components/AtmosPlaqueComponent.cs b/Content.Server/GameObjects/Components/AtmosPlaqueComponent.cs index ad4c3513b3..c6af05b98a 100644 --- a/Content.Server/GameObjects/Components/AtmosPlaqueComponent.cs +++ b/Content.Server/GameObjects/Components/AtmosPlaqueComponent.cs @@ -2,8 +2,6 @@ using Robust.Server.GameObjects; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Random; -using Robust.Shared.Prototypes; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -84,7 +82,7 @@ namespace Content.Server.GameObjects.Components _ => "Uhm", }; - if (Owner.TryGetComponent(out SpriteComponent sprite)) + if (Owner.TryGetComponent(out SpriteComponent? sprite)) { var state = _type == PlaqueType.Zumos ? "zumosplaque" : "atmosplaque"; diff --git a/Content.Server/GameObjects/Components/Body/Circulatory/BloodstreamComponent.cs b/Content.Server/GameObjects/Components/Body/Circulatory/BloodstreamComponent.cs index c57ac645a0..aa416c31ed 100644 --- a/Content.Server/GameObjects/Components/Body/Circulatory/BloodstreamComponent.cs +++ b/Content.Server/GameObjects/Components/Body/Circulatory/BloodstreamComponent.cs @@ -7,8 +7,6 @@ using Content.Shared.Atmos; using Content.Shared.Chemistry; using Content.Shared.GameObjects.Components.Body.Networks; using Robust.Shared.GameObjects; -using Robust.Shared.Prototypes; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -29,7 +27,7 @@ namespace Content.Server.GameObjects.Components.Body.Circulatory /// /// Internal solution for reagent storage /// - [ViewVariables] private SolutionContainerComponent _internalSolution; + [ViewVariables] private SolutionContainerComponent _internalSolution = default!; /// /// Empty volume of internal solution @@ -70,7 +68,7 @@ namespace Content.Server.GameObjects.Components.Body.Circulatory public void PumpToxins(GasMixture to) { - if (!Owner.TryGetComponent(out MetabolismComponent metabolism)) + if (!Owner.TryGetComponent(out MetabolismComponent? metabolism)) { to.Merge(Air); Air.Clear(); diff --git a/Content.Server/GameObjects/Components/Botany/PlantHolderComponent.cs b/Content.Server/GameObjects/Components/Botany/PlantHolderComponent.cs index 4caabbcc92..6a384d7d86 100644 --- a/Content.Server/GameObjects/Components/Botany/PlantHolderComponent.cs +++ b/Content.Server/GameObjects/Components/Botany/PlantHolderComponent.cs @@ -26,9 +26,8 @@ using Robust.Shared.Localization; using Robust.Shared.Maths; using Robust.Shared.Prototypes; using Robust.Shared.Random; -using Robust.Shared.Serialization; -using Robust.Shared.Timing; using Robust.Shared.Serialization.Manager.Attributes; +using Robust.Shared.Timing; using Robust.Shared.Utility; using Robust.Shared.ViewVariables; @@ -720,7 +719,12 @@ namespace Content.Server.GameObjects.Components.Botany { sprayed = true; amount = ReagentUnit.New(1); - EntitySystem.Get().PlayFromEntity(spray.SpraySound, usingItem, AudioHelpers.WithVariation(0.125f)); + + if (!string.IsNullOrEmpty(spray.SpraySound)) + { + EntitySystem.Get().PlayFromEntity(spray.SpraySound, usingItem, + AudioHelpers.WithVariation(0.125f)); + } } var split = solution.Drain(amount); diff --git a/Content.Server/GameObjects/Components/Cargo/CargoConsoleComponent.cs b/Content.Server/GameObjects/Components/Cargo/CargoConsoleComponent.cs index 20e3590618..a6d8ecffbd 100644 --- a/Content.Server/GameObjects/Components/Cargo/CargoConsoleComponent.cs +++ b/Content.Server/GameObjects/Components/Cargo/CargoConsoleComponent.cs @@ -1,4 +1,5 @@ #nullable enable +using System.Collections.Generic; using Content.Server.Cargo; using Content.Server.GameObjects.Components.Power.ApcNetComponents; using Content.Server.GameObjects.EntitySystems; @@ -6,17 +7,13 @@ using Content.Server.Utility; using Content.Shared.GameObjects.Components.Cargo; using Content.Shared.Interfaces.GameObjects.Components; using Content.Shared.Prototypes.Cargo; +using Robust.Server.GameObjects; using Robust.Shared.GameObjects; using Robust.Shared.IoC; -using Robust.Shared.Maths; -using Robust.Shared.Serialization; -using Robust.Shared.ViewVariables; -using System.Collections.Generic; -using Robust.Server.GameObjects; using Robust.Shared.Map; -using System.Linq; -using Robust.Shared.Prototypes; +using Robust.Shared.Maths; using Robust.Shared.Serialization.Manager.Attributes; +using Robust.Shared.ViewVariables; namespace Content.Server.GameObjects.Components.Cargo { @@ -100,95 +97,95 @@ namespace Content.Server.GameObjects.Components.Cargo } var message = serverMsg.Message; - if (!orders.ConnectedToDatabase) + if (orders.Database == null) return; if (!Powered) return; switch (message) { case CargoConsoleAddOrderMessage msg: + { + if (msg.Amount <= 0 || _bankAccount == null) { - if (msg.Amount <= 0 || _bankAccount == null) - { - break; - } - - _cargoConsoleSystem.AddOrder(orders.Database.Id, msg.Requester, msg.Reason, msg.ProductId, msg.Amount, _bankAccount.Id); break; } + + _cargoConsoleSystem.AddOrder(orders.Database.Id, msg.Requester, msg.Reason, msg.ProductId, msg.Amount, _bankAccount.Id); + break; + } case CargoConsoleRemoveOrderMessage msg: - { - _cargoConsoleSystem.RemoveOrder(orders.Database.Id, msg.OrderNumber); - break; - } + { + _cargoConsoleSystem.RemoveOrder(orders.Database.Id, msg.OrderNumber); + break; + } case CargoConsoleApproveOrderMessage msg: + { + if (_requestOnly || + !orders.Database.TryGetOrder(msg.OrderNumber, out var order) || + _bankAccount == null) { - if (_requestOnly || - !orders.Database.TryGetOrder(msg.OrderNumber, out var order) || - _bankAccount == null) - { - break; - } - - PrototypeManager.TryIndex(order.ProductId, out CargoProductPrototype? product); - if (product == null!) - break; - var capacity = _cargoConsoleSystem.GetCapacity(orders.Database.Id); - if (capacity.CurrentCapacity == capacity.MaxCapacity) - break; - if (!_cargoConsoleSystem.ChangeBalance(_bankAccount.Id, (-product.PointCost) * order.Amount)) - break; - _cargoConsoleSystem.ApproveOrder(orders.Database.Id, msg.OrderNumber); - UpdateUIState(); break; } + + PrototypeManager.TryIndex(order.ProductId, out CargoProductPrototype? product); + if (product == null!) + break; + var capacity = _cargoConsoleSystem.GetCapacity(orders.Database.Id); + if (capacity.CurrentCapacity == capacity.MaxCapacity) + break; + if (!_cargoConsoleSystem.ChangeBalance(_bankAccount.Id, (-product.PointCost) * order.Amount)) + break; + _cargoConsoleSystem.ApproveOrder(orders.Database.Id, msg.OrderNumber); + UpdateUIState(); + break; + } case CargoConsoleShuttleMessage _: + { + //var approvedOrders = _cargoOrderDataManager.RemoveAndGetApprovedFrom(orders.Database); + //orders.Database.ClearOrderCapacity(); + + // TODO replace with shuttle code + // TEMPORARY loop for spawning stuff on telepad (looks for a telepad adjacent to the console) + IEntity? cargoTelepad = null; + var indices = Owner.Transform.Coordinates.ToVector2i(Owner.EntityManager, _mapManager); + var offsets = new Vector2i[] { new Vector2i(0, 1), new Vector2i(1, 1), new Vector2i(1, 0), new Vector2i(1, -1), + new Vector2i(0, -1), new Vector2i(-1, -1), new Vector2i(-1, 0), new Vector2i(-1, 1), }; + var adjacentEntities = new List>(); //Probably better than IEnumerable.concat + foreach (var offset in offsets) { - //var approvedOrders = _cargoOrderDataManager.RemoveAndGetApprovedFrom(orders.Database); - //orders.Database.ClearOrderCapacity(); - - // TODO replace with shuttle code - // TEMPORARY loop for spawning stuff on telepad (looks for a telepad adjacent to the console) - IEntity? cargoTelepad = null; - var indices = Owner.Transform.Coordinates.ToVector2i(Owner.EntityManager, _mapManager); - var offsets = new Vector2i[] { new Vector2i(0, 1), new Vector2i(1, 1), new Vector2i(1, 0), new Vector2i(1, -1), - new Vector2i(0, -1), new Vector2i(-1, -1), new Vector2i(-1, 0), new Vector2i(-1, 1), }; - var adjacentEntities = new List>(); //Probably better than IEnumerable.concat - foreach (var offset in offsets) - { - adjacentEntities.Add((indices+offset).GetEntitiesInTileFast(Owner.Transform.GridID)); - } - - foreach (var enumerator in adjacentEntities) - { - foreach (IEntity entity in enumerator) - { - if (entity.HasComponent() && entity.TryGetComponent(out var powerReceiver) && powerReceiver.Powered) - { - cargoTelepad = entity; - break; - } - } - } - if (cargoTelepad != null) - { - if (cargoTelepad.TryGetComponent(out var telepadComponent)) - { - var approvedOrders = _cargoConsoleSystem.RemoveAndGetApprovedOrders(orders.Database.Id); - orders.Database.ClearOrderCapacity(); - foreach (var order in approvedOrders) - { - if (!PrototypeManager.TryIndex(order.ProductId, out CargoProductPrototype? product)) - continue; - for (var i = 0; i < order.Amount; i++) - { - telepadComponent.QueueTeleport(product); - } - } - } - } - break; + adjacentEntities.Add((indices+offset).GetEntitiesInTileFast(Owner.Transform.GridID)); } + + foreach (var enumerator in adjacentEntities) + { + foreach (IEntity entity in enumerator) + { + if (entity.HasComponent() && entity.TryGetComponent(out var powerReceiver) && powerReceiver.Powered) + { + cargoTelepad = entity; + break; + } + } + } + if (cargoTelepad != null) + { + if (cargoTelepad.TryGetComponent(out var telepadComponent)) + { + var approvedOrders = _cargoConsoleSystem.RemoveAndGetApprovedOrders(orders.Database.Id); + orders.Database.ClearOrderCapacity(); + foreach (var order in approvedOrders) + { + if (!PrototypeManager.TryIndex(order.ProductId, out CargoProductPrototype? product)) + continue; + for (var i = 0; i < order.Amount; i++) + { + telepadComponent.QueueTeleport(product); + } + } + } + } + break; + } } } diff --git a/Content.Server/GameObjects/Components/Cargo/CargoOrderDatabaseComponent.cs b/Content.Server/GameObjects/Components/Cargo/CargoOrderDatabaseComponent.cs index 235ab61f6c..d42ad09cee 100644 --- a/Content.Server/GameObjects/Components/Cargo/CargoOrderDatabaseComponent.cs +++ b/Content.Server/GameObjects/Components/Cargo/CargoOrderDatabaseComponent.cs @@ -9,7 +9,7 @@ namespace Content.Server.GameObjects.Components.Cargo [RegisterComponent] public class CargoOrderDatabaseComponent : SharedCargoOrderDatabaseComponent { - public CargoOrderDatabase Database { get; set; } + public CargoOrderDatabase? Database { get; set; } public bool ConnectedToDatabase => Database != null; public override void Initialize() @@ -23,7 +23,7 @@ namespace Content.Server.GameObjects.Components.Cargo { if (!ConnectedToDatabase) return new CargoOrderDatabaseState(null); - return new CargoOrderDatabaseState(Database.GetOrders()); + return new CargoOrderDatabaseState(Database?.GetOrders()); } } } diff --git a/Content.Server/GameObjects/Components/Chemistry/PillComponent.cs b/Content.Server/GameObjects/Components/Chemistry/PillComponent.cs index 4008cf87af..d7d4a44b12 100644 --- a/Content.Server/GameObjects/Components/Chemistry/PillComponent.cs +++ b/Content.Server/GameObjects/Components/Chemistry/PillComponent.cs @@ -27,18 +27,18 @@ namespace Content.Server.GameObjects.Components.Chemistry [ViewVariables] [DataField("useSound")] - protected override string UseSound { get; set; } = default; + protected override string? UseSound { get; set; } = default; [ViewVariables] [DataField("trash")] - protected override string TrashPrototype { get; set; } = default; + protected override string? TrashPrototype { get; set; } = default; [ViewVariables] [DataField("transferAmount")] protected override ReagentUnit TransferAmount { get; set; } = ReagentUnit.New(1000); [ViewVariables] - private SolutionContainerComponent _contents; + private SolutionContainerComponent _contents = default!; public override void Initialize() { @@ -64,7 +64,7 @@ namespace Content.Server.GameObjects.Components.Chemistry return true; } - public override bool TryUseFood(IEntity user, IEntity target, UtensilComponent utensilUsed = null) + public override bool TryUseFood(IEntity? user, IEntity? target, UtensilComponent? utensilUsed = null) { if (user == null) { @@ -73,7 +73,7 @@ namespace Content.Server.GameObjects.Components.Chemistry var trueTarget = target ?? user; - if (!trueTarget.TryGetComponent(out IBody body) || + if (!trueTarget.TryGetComponent(out IBody? body) || !body.TryGetMechanismBehaviors(out var stomachs)) { return false; diff --git a/Content.Server/GameObjects/Components/Chemistry/VaporComponent.cs b/Content.Server/GameObjects/Components/Chemistry/VaporComponent.cs index 450e0ca46f..d8e3d8b03f 100644 --- a/Content.Server/GameObjects/Components/Chemistry/VaporComponent.cs +++ b/Content.Server/GameObjects/Components/Chemistry/VaporComponent.cs @@ -10,7 +10,6 @@ using Robust.Shared.Maths; using Robust.Shared.Physics; using Robust.Shared.Physics.Collision; using Robust.Shared.Prototypes; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -48,7 +47,7 @@ namespace Content.Server.GameObjects.Components.Chemistry _target = target; _aliveTime = aliveTime; // Set Move - if (Owner.TryGetComponent(out PhysicsComponent physics)) + if (Owner.TryGetComponent(out PhysicsComponent? physics)) { physics.BodyStatus = BodyStatus.InAir; physics.ApplyLinearImpulse(dir * speed); @@ -57,7 +56,7 @@ namespace Content.Server.GameObjects.Components.Chemistry public void Update(float frameTime) { - if (!Owner.TryGetComponent(out SolutionContainerComponent contents)) + if (!Owner.TryGetComponent(out SolutionContainerComponent? contents)) return; if (!_running) @@ -100,7 +99,7 @@ namespace Content.Server.GameObjects.Components.Chemistry return false; } - if (!Owner.TryGetComponent(out SolutionContainerComponent contents)) + if (!Owner.TryGetComponent(out SolutionContainerComponent? contents)) { return false; } @@ -117,7 +116,7 @@ namespace Content.Server.GameObjects.Components.Chemistry void IStartCollide.CollideWith(IPhysBody ourBody, IPhysBody otherBody, in Manifold manifold) { - if (!Owner.TryGetComponent(out SolutionContainerComponent contents)) + if (!Owner.TryGetComponent(out SolutionContainerComponent? contents)) return; contents.Solution.DoEntityReaction(otherBody.Entity, ReactionMethod.Touch); diff --git a/Content.Server/GameObjects/Components/Command/CommunicationsConsoleComponent.cs b/Content.Server/GameObjects/Components/Command/CommunicationsConsoleComponent.cs index ecbad18a3c..d2adf34dfd 100644 --- a/Content.Server/GameObjects/Components/Command/CommunicationsConsoleComponent.cs +++ b/Content.Server/GameObjects/Components/Command/CommunicationsConsoleComponent.cs @@ -112,7 +112,7 @@ namespace Content.Server.GameObjects.Components.Command var mob = obj.Session.AttachedEntity; if (mob != null && mob.TryGetHeldId(out var id)) { - author = $"{id.FullName} ({CultureInfo.CurrentCulture.TextInfo.ToTitleCase(id.JobTitle)})"; + author = $"{id.FullName} ({CultureInfo.CurrentCulture.TextInfo.ToTitleCase(id.JobTitle ?? string.Empty)})".Trim(); } message += $"\nSent by {author}"; diff --git a/Content.Server/GameObjects/Components/ComputerComponent.cs b/Content.Server/GameObjects/Components/ComputerComponent.cs index 2c29115f14..0b88de6cfc 100644 --- a/Content.Server/GameObjects/Components/ComputerComponent.cs +++ b/Content.Server/GameObjects/Components/ComputerComponent.cs @@ -5,8 +5,6 @@ using Robust.Server.GameObjects; using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.Log; -using Robust.Shared.Prototypes; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -17,18 +15,16 @@ namespace Content.Server.GameObjects.Components { [ViewVariables] [DataField("board")] - private string _boardPrototype; + private string? _boardPrototype; public override void Initialize() { base.Initialize(); - if (Owner.TryGetComponent(out PowerReceiverComponent powerReceiver)) + if (Owner.TryGetComponent(out PowerReceiverComponent? powerReceiver) && + Owner.TryGetComponent(out AppearanceComponent? appearance)) { - if (Owner.TryGetComponent(out AppearanceComponent appearance)) - { - appearance.SetData(ComputerVisuals.Powered, powerReceiver.Powered); - } + appearance.SetData(ComputerVisuals.Powered, powerReceiver.Powered); } } @@ -39,7 +35,7 @@ namespace Content.Server.GameObjects.Components CreateComputerBoard(); } - public override void HandleMessage(ComponentMessage message, IComponent component) + public override void HandleMessage(ComponentMessage message, IComponent? component) { base.HandleMessage(message, component); switch (message) @@ -52,7 +48,7 @@ namespace Content.Server.GameObjects.Components private void PowerReceiverOnOnPowerStateChanged(PowerChangedMessage e) { - if (Owner.TryGetComponent(out AppearanceComponent appearance)) + if (Owner.TryGetComponent(out AppearanceComponent? appearance)) { appearance.SetData(ComputerVisuals.Powered, e.Powered); } @@ -66,7 +62,7 @@ namespace Content.Server.GameObjects.Components private void CreateComputerBoard() { // Ensure that the construction component is aware of the board container. - if (Owner.TryGetComponent(out ConstructionComponent construction)) + if (Owner.TryGetComponent(out ConstructionComponent? construction)) construction.AddContainer("board"); // We don't do anything if this is null or empty. diff --git a/Content.Server/GameObjects/Components/ConfigurationComponent.cs b/Content.Server/GameObjects/Components/ConfigurationComponent.cs index 0549027a81..df3e81b9a6 100644 --- a/Content.Server/GameObjects/Components/ConfigurationComponent.cs +++ b/Content.Server/GameObjects/Components/ConfigurationComponent.cs @@ -24,7 +24,7 @@ namespace Content.Server.GameObjects.Components [ComponentReference(typeof(SharedConfigurationComponent))] public class ConfigurationComponent : SharedConfigurationComponent, IInteractUsing, ISerializationHooks { - [ViewVariables] private BoundUserInterface UserInterface => Owner.GetUIOrNull(ConfigurationUiKey.Key); + [ViewVariables] private BoundUserInterface? UserInterface => Owner.GetUIOrNull(ConfigurationUiKey.Key); [DataField("keys")] private List _keys = new(); @@ -65,7 +65,7 @@ namespace Content.Server.GameObjects.Components } } - public string GetConfig(string name) + public string? GetConfig(string name) { return _config.GetValueOrDefault(name); } @@ -78,7 +78,7 @@ namespace Content.Server.GameObjects.Components async Task IInteractUsing.InteractUsing(InteractUsingEventArgs eventArgs) { - if (UserInterface == null || !eventArgs.User.TryGetComponent(out IActorComponent actor)) + if (UserInterface == null || !eventArgs.User.TryGetComponent(out IActorComponent? actor)) return false; if (!eventArgs.Using.TryGetComponent(out var tool)) @@ -110,7 +110,7 @@ namespace Content.Server.GameObjects.Components SendMessage(new ConfigUpdatedComponentMessage(config)); } - } + } private void UpdateUserInterface() { @@ -120,8 +120,8 @@ namespace Content.Server.GameObjects.Components private void OpenUserInterface(IActorComponent actor) { UpdateUserInterface(); - UserInterface.Open(actor.playerSession); - UserInterface.SendMessage(new ValidationUpdateMessage(_validation.ToString()), actor.playerSession); + UserInterface?.Open(actor.playerSession); + UserInterface?.SendMessage(new ValidationUpdateMessage(_validation.ToString()), actor.playerSession); } private static void FillConfiguration(List list, Dictionary configuration, T value){ @@ -150,7 +150,7 @@ namespace Content.Server.GameObjects.Components protected override void Activate(IEntity user, ConfigurationComponent component) { - if (user.TryGetComponent(out IActorComponent actor)) + if (user.TryGetComponent(out IActorComponent? actor)) { component.OpenUserInterface(actor); } diff --git a/Content.Server/GameObjects/Components/Construction/ComputerBoardComponent.cs b/Content.Server/GameObjects/Components/Construction/ComputerBoardComponent.cs index eb9d53813a..4e52c5cc56 100644 --- a/Content.Server/GameObjects/Components/Construction/ComputerBoardComponent.cs +++ b/Content.Server/GameObjects/Components/Construction/ComputerBoardComponent.cs @@ -1,6 +1,4 @@ using Robust.Shared.GameObjects; -using Robust.Shared.Prototypes; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -13,6 +11,6 @@ namespace Content.Server.GameObjects.Components.Construction [ViewVariables] [DataField("prototype")] - public string Prototype { get; private set; } + public string? Prototype { get; private set; } } } diff --git a/Content.Server/GameObjects/Components/Construction/MachineBoardComponent.cs b/Content.Server/GameObjects/Components/Construction/MachineBoardComponent.cs index 98a3895950..166a3ef071 100644 --- a/Content.Server/GameObjects/Components/Construction/MachineBoardComponent.cs +++ b/Content.Server/GameObjects/Components/Construction/MachineBoardComponent.cs @@ -22,27 +22,23 @@ namespace Content.Server.GameObjects.Components.Construction [ViewVariables] [DataField("requirements")] - private Dictionary _requirements = new(); + public readonly Dictionary Requirements = new(); [ViewVariables] [DataField("materialRequirements")] - private Dictionary _materialIdRequirements = new(); + public readonly Dictionary MaterialIdRequirements = new(); [ViewVariables] [DataField("tagRequirements")] - private Dictionary _tagRequirements = new(); + public readonly Dictionary TagRequirements = new(); [ViewVariables] [DataField("componentRequirements")] - private Dictionary _componentRequirements = new(); + public readonly Dictionary ComponentRequirements = new(); [ViewVariables(VVAccess.ReadWrite)] [DataField("prototype")] - public string Prototype { get; private set; } - - public IReadOnlyDictionary Requirements => _requirements; - - public IReadOnlyDictionary MaterialIdRequirements => _materialIdRequirements; + public string? Prototype { get; private set; } public IEnumerable> MaterialRequirements { @@ -56,10 +52,6 @@ namespace Content.Server.GameObjects.Components.Construction } } - public IReadOnlyDictionary ComponentRequirements => _componentRequirements; - public IReadOnlyDictionary TagRequirements => _tagRequirements; - - public void Examine(FormattedMessage message, bool inDetailsRange) { message.AddMarkup(Loc.GetString("Requires:\n")); diff --git a/Content.Server/GameObjects/Components/Construction/MachineComponent.cs b/Content.Server/GameObjects/Components/Construction/MachineComponent.cs index b7db9e9173..5499987e07 100644 --- a/Content.Server/GameObjects/Components/Construction/MachineComponent.cs +++ b/Content.Server/GameObjects/Components/Construction/MachineComponent.cs @@ -2,11 +2,8 @@ using System.Collections.Generic; using Content.Server.Construction; using Content.Server.Interfaces.GameObjects; -using Robust.Server.GameObjects; using Robust.Shared.Containers; using Robust.Shared.GameObjects; -using Robust.Shared.Prototypes; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.GameObjects.Components.Construction @@ -17,10 +14,10 @@ namespace Content.Server.GameObjects.Components.Construction public override string Name => "Machine"; [DataField("board")] - public string BoardPrototype { get; private set; } + public string? BoardPrototype { get; private set; } - private Container _boardContainer; - private Container _partContainer; + private Container _boardContainer = default!; + private Container _partContainer = default!; public override void Initialize() { diff --git a/Content.Server/GameObjects/Components/Construction/MachineFrameComponent.cs b/Content.Server/GameObjects/Components/Construction/MachineFrameComponent.cs index c7be531435..22d14bea27 100644 --- a/Content.Server/GameObjects/Components/Construction/MachineFrameComponent.cs +++ b/Content.Server/GameObjects/Components/Construction/MachineFrameComponent.cs @@ -75,28 +75,39 @@ namespace Content.Server.GameObjects.Components.Construction private readonly Dictionary _tagProgress = new(); [ViewVariables] - private Container _boardContainer; + private Dictionary _requirements = new(); [ViewVariables] - private Container _partContainer; + private Dictionary _materialRequirements = new(); [ViewVariables] - public IReadOnlyDictionary Requirements { get; private set; } + private Dictionary _componentRequirements = new(); [ViewVariables] - public IReadOnlyDictionary MaterialRequirements { get; private set; } + private Dictionary _tagRequirements = new(); [ViewVariables] - public IReadOnlyDictionary ComponentRequirements { get; private set; } + private Container _boardContainer = default!; [ViewVariables] - public IReadOnlyDictionary TagRequirements { get; private set; } + private Container _partContainer = default!; public IReadOnlyDictionary Progress => _progress; + public IReadOnlyDictionary MaterialProgress => _materialProgress; + public IReadOnlyDictionary ComponentProgress => _componentProgress; + public IReadOnlyDictionary TagProgress => _tagProgress; + public IReadOnlyDictionary Requirements => _requirements; + + public IReadOnlyDictionary MaterialRequirements => _materialRequirements; + + public IReadOnlyDictionary ComponentRequirements => _componentRequirements; + + public IReadOnlyDictionary TagRequirements => _tagRequirements; + public override void Initialize() { base.Initialize(); @@ -120,10 +131,10 @@ namespace Content.Server.GameObjects.Components.Construction private void ResetProgressAndRequirements(MachineBoardComponent machineBoard) { - Requirements = machineBoard.Requirements; - MaterialRequirements = machineBoard.MaterialIdRequirements; - ComponentRequirements = machineBoard.ComponentRequirements; - TagRequirements = machineBoard.TagRequirements; + _requirements = machineBoard.Requirements; + _materialRequirements = machineBoard.MaterialIdRequirements; + _componentRequirements = machineBoard.ComponentRequirements; + _tagRequirements = machineBoard.TagRequirements; _progress.Clear(); _materialProgress.Clear(); @@ -153,7 +164,7 @@ namespace Content.Server.GameObjects.Components.Construction public void RegenerateProgress() { - AppearanceComponent appearance; + AppearanceComponent? appearance; if (!HasBoard) { @@ -162,10 +173,10 @@ namespace Content.Server.GameObjects.Components.Construction appearance.SetData(MachineFrameVisuals.State, 1); } - Requirements = null; - MaterialRequirements = null; - ComponentRequirements = null; - TagRequirements = null; + _requirements.Clear(); + _materialRequirements.Clear(); + _componentRequirements.Clear(); + _tagRequirements.Clear(); _progress.Clear(); _materialProgress.Clear(); _componentProgress.Clear(); @@ -258,7 +269,7 @@ namespace Content.Server.GameObjects.Components.Construction appearance.SetData(MachineFrameVisuals.State, 2); } - if (Owner.TryGetComponent(out ConstructionComponent construction)) + if (Owner.TryGetComponent(out ConstructionComponent? construction)) { // So prying the components off works correctly. construction.ResetEdge(); diff --git a/Content.Server/GameObjects/Components/Culinary/SliceableFoodComponent.cs b/Content.Server/GameObjects/Components/Culinary/SliceableFoodComponent.cs index 4f9969b37a..0f5883f283 100644 --- a/Content.Server/GameObjects/Components/Culinary/SliceableFoodComponent.cs +++ b/Content.Server/GameObjects/Components/Culinary/SliceableFoodComponent.cs @@ -49,17 +49,17 @@ namespace Content.Server.GameObjects.Components.Culinary { return false; } - if (!Owner.TryGetComponent(out SolutionContainerComponent solution)) + if (!Owner.TryGetComponent(out SolutionContainerComponent? solution)) { return false; } - if (!eventArgs.Using.TryGetComponent(out UtensilComponent utensil) || !utensil.HasType(UtensilType.Knife)) + if (!eventArgs.Using.TryGetComponent(out UtensilComponent? utensil) || !utensil.HasType(UtensilType.Knife)) { return false; } var itemToSpawn = Owner.EntityManager.SpawnEntity(_slice, Owner.Transform.Coordinates); - if (eventArgs.User.TryGetComponent(out HandsComponent handsComponent)) + if (eventArgs.User.TryGetComponent(out HandsComponent? handsComponent)) { if (ContainerHelpers.IsInContainer(Owner)) { diff --git a/Content.Server/GameObjects/Components/Damage/DamageOnHighSpeedImpactComponent.cs b/Content.Server/GameObjects/Components/Damage/DamageOnHighSpeedImpactComponent.cs index b83af720fc..17a08fe73f 100644 --- a/Content.Server/GameObjects/Components/Damage/DamageOnHighSpeedImpactComponent.cs +++ b/Content.Server/GameObjects/Components/Damage/DamageOnHighSpeedImpactComponent.cs @@ -8,11 +8,9 @@ using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Physics; using Robust.Shared.Physics.Collision; -using Robust.Shared.Prototypes; using Robust.Shared.Random; -using Robust.Shared.Serialization; -using Robust.Shared.Timing; using Robust.Shared.Serialization.Manager.Attributes; +using Robust.Shared.Timing; namespace Content.Server.GameObjects.Components.Damage { @@ -46,13 +44,13 @@ namespace Content.Server.GameObjects.Components.Damage void IStartCollide.CollideWith(IPhysBody ourBody, IPhysBody otherBody, in Manifold manifold) { - if (!Owner.TryGetComponent(out IDamageableComponent damageable)) return; + if (!Owner.TryGetComponent(out IDamageableComponent? damageable)) return; var speed = ourBody.LinearVelocity.Length; if (speed < MinimumSpeed) return; - if(!string.IsNullOrEmpty(SoundHit)) + if (!string.IsNullOrEmpty(SoundHit)) EntitySystem.Get().PlayFromEntity(SoundHit, otherBody.Entity, AudioHelpers.WithVariation(0.125f).WithVolume(-0.125f)); if ((_gameTiming.CurTime - _lastHit).TotalSeconds < DamageCooldown) @@ -62,7 +60,7 @@ namespace Content.Server.GameObjects.Components.Damage var damage = (int) (BaseDamage * (speed / MinimumSpeed) * Factor); - if (Owner.TryGetComponent(out StunnableComponent stun) && _robustRandom.Prob(StunChance)) + if (Owner.TryGetComponent(out StunnableComponent? stun) && _robustRandom.Prob(StunChance)) stun.Stun(StunSeconds); damageable.ChangeDamage(Damage, damage, false, otherBody.Entity); diff --git a/Content.Server/GameObjects/Components/Damage/DamageOnLandComponent.cs b/Content.Server/GameObjects/Components/Damage/DamageOnLandComponent.cs index 7dc420dca9..83832c359f 100644 --- a/Content.Server/GameObjects/Components/Damage/DamageOnLandComponent.cs +++ b/Content.Server/GameObjects/Components/Damage/DamageOnLandComponent.cs @@ -22,7 +22,7 @@ namespace Content.Server.GameObjects.Components.Damage void ILand.Land(LandEventArgs eventArgs) { - if (!Owner.TryGetComponent(out IDamageableComponent damageable)) return; + if (!Owner.TryGetComponent(out IDamageableComponent? damageable)) return; damageable.ChangeDamage(_damageType, _amount, _ignoreResistances, eventArgs.User); } diff --git a/Content.Server/GameObjects/Components/Damage/DamageOnToolInteractComponent.cs b/Content.Server/GameObjects/Components/Damage/DamageOnToolInteractComponent.cs index b2f39bf518..782050cb44 100644 --- a/Content.Server/GameObjects/Components/Damage/DamageOnToolInteractComponent.cs +++ b/Content.Server/GameObjects/Components/Damage/DamageOnToolInteractComponent.cs @@ -29,7 +29,7 @@ namespace Content.Server.GameObjects.Components.Damage { if (tool.HasQuality(ToolQuality.Welding) && toolQuality == ToolQuality.Welding) { - if (eventArgs.Using.TryGetComponent(out WelderComponent welder)) + if (eventArgs.Using.TryGetComponent(out WelderComponent? welder)) { if (welder.WelderLit) return CallDamage(eventArgs, tool); } diff --git a/Content.Server/GameObjects/Components/Damage/DamageOtherOnHitComponent.cs b/Content.Server/GameObjects/Components/Damage/DamageOtherOnHitComponent.cs index 596fddb56b..e9ca21b4fb 100644 --- a/Content.Server/GameObjects/Components/Damage/DamageOtherOnHitComponent.cs +++ b/Content.Server/GameObjects/Components/Damage/DamageOtherOnHitComponent.cs @@ -2,8 +2,6 @@ using Content.Shared.Damage; using Content.Shared.GameObjects.Components.Damage; using Content.Shared.Interfaces.GameObjects.Components; using Robust.Shared.GameObjects; -using Robust.Shared.Prototypes; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.GameObjects.Components.Damage @@ -22,7 +20,7 @@ namespace Content.Server.GameObjects.Components.Damage void IThrowCollide.DoHit(ThrowCollideEventArgs eventArgs) { - if (!eventArgs.Target.TryGetComponent(out IDamageableComponent damageable)) return; + if (!eventArgs.Target.TryGetComponent(out IDamageableComponent? damageable)) return; damageable.ChangeDamage(_damageType, _amount, _ignoreResistances, eventArgs.User); } diff --git a/Content.Server/GameObjects/Components/Destructible/Thresholds/Behaviors/GibBehavior.cs b/Content.Server/GameObjects/Components/Destructible/Thresholds/Behaviors/GibBehavior.cs index 4138717516..cc43dfbace 100644 --- a/Content.Server/GameObjects/Components/Destructible/Thresholds/Behaviors/GibBehavior.cs +++ b/Content.Server/GameObjects/Components/Destructible/Thresholds/Behaviors/GibBehavior.cs @@ -14,7 +14,7 @@ namespace Content.Server.GameObjects.Components.Destructible.Thresholds.Behavior public void Execute(IEntity owner, DestructibleSystem system) { - if (owner.TryGetComponent(out IBody body)) + if (owner.TryGetComponent(out IBody? body)) { body.Gib(_recursive); } diff --git a/Content.Server/GameObjects/Components/Disposal/DisposalJunctionComponent.cs b/Content.Server/GameObjects/Components/Disposal/DisposalJunctionComponent.cs index cd2f4cf45f..0c1e15b16c 100644 --- a/Content.Server/GameObjects/Components/Disposal/DisposalJunctionComponent.cs +++ b/Content.Server/GameObjects/Components/Disposal/DisposalJunctionComponent.cs @@ -3,9 +3,7 @@ using System.Linq; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Maths; -using Robust.Shared.Prototypes; using Robust.Shared.Random; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -22,7 +20,7 @@ namespace Content.Server.GameObjects.Components.Disposal /// [ViewVariables] [DataField("degrees")] - private List _degrees; + private List _degrees = new(); public override string Name => "DisposalJunction"; diff --git a/Content.Server/GameObjects/Components/ExtinguisherCabinetComponent.cs b/Content.Server/GameObjects/Components/ExtinguisherCabinetComponent.cs index 06a5c63094..6fa9970403 100644 --- a/Content.Server/GameObjects/Components/ExtinguisherCabinetComponent.cs +++ b/Content.Server/GameObjects/Components/ExtinguisherCabinetComponent.cs @@ -11,14 +11,11 @@ using Robust.Server.GameObjects; using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.Localization; -using Robust.Shared.Prototypes; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; namespace Content.Server.GameObjects.Components { - [RegisterComponent] [ComponentReference(typeof(IActivate))] public class ExtinguisherCabinetComponent : Component, IInteractUsing, IInteractHand, IActivate @@ -29,7 +26,7 @@ namespace Content.Server.GameObjects.Components [DataField("doorSound")] private string _doorSound = "/Audio/Machines/machine_switch.ogg"; - [ViewVariables] protected ContainerSlot ItemContainer; + [ViewVariables] protected ContainerSlot ItemContainer = default!; [ViewVariables] public string DoorSound => _doorSound; public override void Initialize() @@ -75,7 +72,7 @@ namespace Content.Server.GameObjects.Components _opened = false; ClickLatchSound(); } - else if (eventArgs.User.TryGetComponent(out HandsComponent hands)) + else if (eventArgs.User.TryGetComponent(out HandsComponent? hands)) { Owner.PopupMessage(eventArgs.User, Loc.GetString("You take {0:extinguisherName} from the {1:cabinetName}", ItemContainer.ContainedEntity.Name, Owner.Name)); @@ -106,7 +103,7 @@ namespace Content.Server.GameObjects.Components private void UpdateVisuals() { - if (Owner.TryGetComponent(out AppearanceComponent appearance)) + if (Owner.TryGetComponent(out AppearanceComponent? appearance)) { appearance.SetData(ExtinguisherCabinetVisuals.IsOpen, _opened); appearance.SetData(ExtinguisherCabinetVisuals.ContainsExtinguisher, ItemContainer.ContainedEntity != null); diff --git a/Content.Server/GameObjects/Components/Fluids/PuddleComponent.cs b/Content.Server/GameObjects/Components/Fluids/PuddleComponent.cs index 2e6076e95c..55ca157507 100644 --- a/Content.Server/GameObjects/Components/Fluids/PuddleComponent.cs +++ b/Content.Server/GameObjects/Components/Fluids/PuddleComponent.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Content.Server.GameObjects.Components.Chemistry; -using Content.Server.GameObjects.Components.Movement; using Content.Shared.Chemistry; using Content.Shared.GameObjects.Components.Movement; using Content.Shared.GameObjects.EntitySystems; @@ -18,8 +18,6 @@ using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Physics; using Robust.Shared.Random; -using Robust.Shared.Prototypes; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Utility; using Robust.Shared.ViewVariables; @@ -48,7 +46,7 @@ namespace Content.Server.GameObjects.Components.Fluids [Dependency] private readonly IRobustRandom _random = default!; public override string Name => "Puddle"; - private CancellationTokenSource _evaporationToken; + private CancellationTokenSource? _evaporationToken; [DataField("evaporate_threshold")] private ReagentUnit _evaporateThreshold = ReagentUnit.New(20); // How few we can hold prior to self-destructing public ReagentUnit EvaporateThreshold @@ -77,8 +75,8 @@ namespace Content.Server.GameObjects.Components.Fluids /// private bool _overflown; - private SpriteComponent _spriteComponent; - private SnapGridComponent _snapGrid; + private SpriteComponent _spriteComponent = default!; + private SnapGridComponent _snapGrid = default!; public ReagentUnit MaxVolume { @@ -97,7 +95,7 @@ namespace Content.Server.GameObjects.Components.Fluids private ReagentUnit _overflowVolume = ReagentUnit.New(20); private ReagentUnit OverflowLeft => CurrentVolume - OverflowVolume; - private SolutionContainerComponent _contents; + private SolutionContainerComponent _contents = default!; public bool EmptyHolder => _contents.ReagentList.Count == 0; [DataField("variants")] private int _spriteVariants = 1; @@ -105,21 +103,13 @@ namespace Content.Server.GameObjects.Components.Fluids [DataField("recolor")] private bool _recolor = default; - private bool Slippery => Owner.TryGetComponent(out SlipperyComponent slippery) && slippery.Slippery; + private bool Slippery => Owner.TryGetComponent(out SlipperyComponent? slippery) && slippery.Slippery; public override void Initialize() { base.Initialize(); - if (Owner.TryGetComponent(out SolutionContainerComponent solutionComponent)) - { - _contents = solutionComponent; - } - else - { - _contents = Owner.AddComponent(); - } - + _contents = Owner.EnsureComponentWarn(); _snapGrid = Owner.EnsureComponent(); // Smaller than 1m^3 for now but realistically this shouldn't be hit @@ -253,7 +243,7 @@ namespace Content.Server.GameObjects.Components.Fluids private void UpdateSlip() { if ((_slipThreshold == ReagentUnit.New(-1) || CurrentVolume < _slipThreshold) && - Owner.TryGetComponent(out SlipperyComponent oldSlippery)) + Owner.TryGetComponent(out SlipperyComponent? oldSlippery)) { oldSlippery.Slippery = false; } @@ -351,7 +341,7 @@ namespace Content.Server.GameObjects.Components.Fluids /// The puddle that was found or is to be created, or null if there /// is a wall in the way /// true if a puddle was found or created, false otherwise - private bool TryGetAdjacentOverflow(Direction direction, out Func puddle) + private bool TryGetAdjacentOverflow(Direction direction, [NotNullWhen(true)] out Func? puddle) { puddle = default; @@ -370,14 +360,14 @@ namespace Content.Server.GameObjects.Components.Fluids foreach (var entity in _snapGrid.GetInDir(direction)) { - if (entity.TryGetComponent(out IPhysBody physics) && + if (entity.TryGetComponent(out IPhysBody? physics) && (physics.CollisionLayer & (int) CollisionGroup.Impassable) != 0) { puddle = default; return false; } - if (entity.TryGetComponent(out PuddleComponent existingPuddle)) + if (entity.TryGetComponent(out PuddleComponent? existingPuddle)) { if (existingPuddle._overflown) { @@ -391,7 +381,7 @@ namespace Content.Server.GameObjects.Components.Fluids if (puddle == default) { var grid = _snapGrid.DirectionToGrid(direction); - puddle = () => Owner.EntityManager.SpawnEntity(Owner.Prototype.ID, grid).GetComponent(); + puddle = () => Owner.EntityManager.SpawnEntity(Owner.Prototype?.ID, grid).GetComponent(); } return true; diff --git a/Content.Server/GameObjects/Components/Fluids/SpillableComponent.cs b/Content.Server/GameObjects/Components/Fluids/SpillableComponent.cs index cf1306980f..a3876ec309 100644 --- a/Content.Server/GameObjects/Components/Fluids/SpillableComponent.cs +++ b/Content.Server/GameObjects/Components/Fluids/SpillableComponent.cs @@ -23,7 +23,7 @@ namespace Content.Server.GameObjects.Components.Fluids protected override void GetData(IEntity user, SpillableComponent component, VerbData data) { if (!ActionBlockerSystem.CanInteract(user) || - !component.Owner.TryGetComponent(out ISolutionInteractionsComponent solutionComponent) || + !component.Owner.TryGetComponent(out ISolutionInteractionsComponent? solutionComponent) || !solutionComponent.CanDrain) { data.Visibility = VerbVisibility.Invisible; @@ -59,7 +59,7 @@ namespace Content.Server.GameObjects.Components.Fluids void IDropped.Dropped(DroppedEventArgs eventArgs) { - if (!eventArgs.Intentional && Owner.TryGetComponent(out ISolutionInteractionsComponent solutionComponent)) + if (!eventArgs.Intentional && Owner.TryGetComponent(out ISolutionInteractionsComponent? solutionComponent)) { solutionComponent.Drain(solutionComponent.DrainAvailable).SpillAt(Owner.Transform.Coordinates, "PuddleSmear"); } diff --git a/Content.Server/GameObjects/Components/Fluids/SprayComponent.cs b/Content.Server/GameObjects/Components/Fluids/SprayComponent.cs index ee5893a142..7df470b88d 100644 --- a/Content.Server/GameObjects/Components/Fluids/SprayComponent.cs +++ b/Content.Server/GameObjects/Components/Fluids/SprayComponent.cs @@ -14,10 +14,8 @@ using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Maths; -using Robust.Shared.Prototypes; -using Robust.Shared.Serialization; -using Robust.Shared.Timing; using Robust.Shared.Serialization.Manager.Attributes; +using Robust.Shared.Timing; using Robust.Shared.ViewVariables; namespace Content.Server.GameObjects.Components.Fluids @@ -33,7 +31,7 @@ namespace Content.Server.GameObjects.Components.Fluids [DataField("transferAmount")] private ReagentUnit _transferAmount = ReagentUnit.New(10); [DataField("spraySound")] - private string _spraySound; + private string? _spraySound; [DataField("sprayVelocity")] private float _sprayVelocity = 1.5f; [DataField("sprayAliveTime")] @@ -73,7 +71,7 @@ namespace Content.Server.GameObjects.Components.Fluids set => _sprayVelocity = value; } - public string SpraySound => _spraySound; + public string? SpraySound => _spraySound; public ReagentUnit CurrentVolume => Owner.GetComponentOrNull()?.CurrentVolume ?? ReagentUnit.Zero; @@ -115,7 +113,7 @@ namespace Content.Server.GameObjects.Components.Fluids if (eventArgs.ClickLocation.GetGridId(_serverEntityManager) != playerPos.GetGridId(_serverEntityManager)) return true; - if (!Owner.TryGetComponent(out SolutionContainerComponent contents)) + if (!Owner.TryGetComponent(out SolutionContainerComponent? contents)) return true; var direction = (eventArgs.ClickLocation.Position - playerPos.Position).Normalized; @@ -147,7 +145,7 @@ namespace Content.Server.GameObjects.Components.Fluids var vapor = _serverEntityManager.SpawnEntity(_vaporPrototype, playerPos.Offset(distance < 1 ? quarter : threeQuarters)); vapor.Transform.LocalRotation = rotation; - if (vapor.TryGetComponent(out AppearanceComponent appearance)) // Vapor sprite should face down. + if (vapor.TryGetComponent(out AppearanceComponent? appearance)) // Vapor sprite should face down. { appearance.SetData(VaporVisuals.Rotation, -Angle.South + rotation); appearance.SetData(VaporVisuals.Color, contents.Color.WithAlpha(1f)); @@ -162,12 +160,15 @@ namespace Content.Server.GameObjects.Components.Fluids } //Play sound - EntitySystem.Get().PlayFromEntity(_spraySound, Owner, AudioHelpers.WithVariation(0.125f)); + if (!string.IsNullOrEmpty(_spraySound)) + { + EntitySystem.Get().PlayFromEntity(_spraySound, Owner, AudioHelpers.WithVariation(0.125f)); + } _lastUseTime = curTime; _cooldownEnd = _lastUseTime + TimeSpan.FromSeconds(_cooldownTime); - if (Owner.TryGetComponent(out ItemCooldownComponent cooldown)) + if (Owner.TryGetComponent(out ItemCooldownComponent? cooldown)) { cooldown.CooldownStart = _lastUseTime; cooldown.CooldownEnd = _cooldownEnd; @@ -199,13 +200,13 @@ namespace Content.Server.GameObjects.Components.Fluids _safety = state; - if(Owner.TryGetComponent(out AppearanceComponent appearance)) + if(Owner.TryGetComponent(out AppearanceComponent? appearance)) appearance.SetData(SprayVisuals.Safety, _safety); } void IDropped.Dropped(DroppedEventArgs eventArgs) { - if(_hasSafety && Owner.TryGetComponent(out AppearanceComponent appearance)) + if(_hasSafety && Owner.TryGetComponent(out AppearanceComponent? appearance)) appearance.SetData(SprayVisuals.Safety, _safety); } } diff --git a/Content.Server/GameObjects/Components/GUI/HandsComponent.cs b/Content.Server/GameObjects/Components/GUI/HandsComponent.cs index 7f08b0dba7..83fb6f8e19 100644 --- a/Content.Server/GameObjects/Components/GUI/HandsComponent.cs +++ b/Content.Server/GameObjects/Components/GUI/HandsComponent.cs @@ -25,11 +25,9 @@ using Robust.Shared.Log; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Network; +using Robust.Shared.Physics; using Robust.Shared.Players; using Robust.Shared.ViewVariables; -using Robust.Shared.Map; -using Robust.Shared.Network; -using Robust.Shared.Physics; namespace Content.Server.GameObjects.Components.GUI { @@ -101,12 +99,12 @@ namespace Content.Server.GameObjects.Components.GUI return false; } - private Hand? GetHand(string name) + private Hand? GetHand(string? name) { return _hands.FirstOrDefault(hand => hand.Name == name); } - public ItemComponent? GetItem(string handName) + public ItemComponent? GetItem(string? handName) { return GetHand(handName)?.Entity?.GetComponent(); } @@ -758,19 +756,26 @@ namespace Content.Server.GameObjects.Components.GUI return false; var source = eventArgs.Source; + var target = eventArgs.Target; - EntitySystem.Get().PlayFromEntity("/Audio/Effects/thudswoosh.ogg", source, - AudioHelpers.WithVariation(0.025f)); + if (source != null) + { + EntitySystem.Get().PlayFromEntity("/Audio/Effects/thudswoosh.ogg", source, + AudioHelpers.WithVariation(0.025f)); - if (ActiveHand != null && Drop(ActiveHand, false)) - { - source.PopupMessageOtherClients(Loc.GetString("{0} disarms {1}!", source.Name, eventArgs.Target.Name)); - source.PopupMessageCursor(Loc.GetString("You disarm {0}!", eventArgs.Target.Name)); - } - else - { - source.PopupMessageOtherClients(Loc.GetString("{0} shoves {1}!", source.Name, eventArgs.Target.Name)); - source.PopupMessageCursor(Loc.GetString("You shove {0}!", eventArgs.Target.Name)); + if (target != null) + { + if (ActiveHand != null && Drop(ActiveHand, false)) + { + source.PopupMessageOtherClients(Loc.GetString("{0} disarms {1}!", source.Name, target.Name)); + source.PopupMessageCursor(Loc.GetString("You disarm {0}!", target.Name)); + } + else + { + source.PopupMessageOtherClients(Loc.GetString("{0} shoves {1}!", source.Name, target.Name)); + source.PopupMessageCursor(Loc.GetString("You shove {0}!", target.Name)); + } + } } return true; diff --git a/Content.Server/GameObjects/Components/GUI/HumanInventoryControllerComponent.cs b/Content.Server/GameObjects/Components/GUI/HumanInventoryControllerComponent.cs index 152ee3cec7..34b2f7eafa 100644 --- a/Content.Server/GameObjects/Components/GUI/HumanInventoryControllerComponent.cs +++ b/Content.Server/GameObjects/Components/GUI/HumanInventoryControllerComponent.cs @@ -1,5 +1,5 @@ +using System.Diagnostics.CodeAnalysis; using Content.Server.GameObjects.Components.Items.Storage; -using Robust.Server.GameObjects; using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.Localization; @@ -14,7 +14,7 @@ namespace Content.Server.GameObjects.Components.GUI { public override string Name => "HumanInventoryController"; - private InventoryComponent _inventory; + private InventoryComponent _inventory = default!; public override void Initialize() { @@ -23,7 +23,7 @@ namespace Content.Server.GameObjects.Components.GUI _inventory = Owner.EnsureComponent(); } - bool IInventoryController.CanEquip(Slots slot, IEntity entity, bool flagsCheck, out string reason) + bool IInventoryController.CanEquip(Slots slot, IEntity entity, bool flagsCheck, [NotNullWhen(false)] out string? reason) { var slotMask = SlotMasks[slot]; reason = null; @@ -59,7 +59,7 @@ namespace Content.Server.GameObjects.Components.GUI return flagsCheck; } - public override void HandleMessage(ComponentMessage message, IComponent component) + public override void HandleMessage(ComponentMessage message, IComponent? component) { base.HandleMessage(message, component); diff --git a/Content.Server/GameObjects/Components/GUI/IInventoryController.cs b/Content.Server/GameObjects/Components/GUI/IInventoryController.cs index a9d9c3075c..238d9c9267 100644 --- a/Content.Server/GameObjects/Components/GUI/IInventoryController.cs +++ b/Content.Server/GameObjects/Components/GUI/IInventoryController.cs @@ -1,3 +1,4 @@ +using System.Diagnostics.CodeAnalysis; using Robust.Shared.GameObjects; using static Content.Shared.GameObjects.Components.Inventory.EquipmentSlotDefines; @@ -16,12 +17,12 @@ namespace Content.Server.GameObjects.Components.GUI /// Whether the entity passes default slot masks & flags checks. /// The translated reason why the item cannot be equiped, if this function returns false. Can be null. /// True if the entity can be equipped, false otherwise - bool CanEquip(Slots slot, IEntity entity, bool flagsCheck, out string reason) + bool CanEquip(Slots slot, IEntity entity, bool flagsCheck, [NotNullWhen(false)] out string? reason) { reason = null; return flagsCheck; } - bool CanEquip(Slots slot, IEntity entity, bool flagsCheck) => CanEquip(slot, entity, flagsCheck, out var _); + bool CanEquip(Slots slot, IEntity entity, bool flagsCheck) => CanEquip(slot, entity, flagsCheck, out _); } } diff --git a/Content.Server/GameObjects/Components/GUI/InventoryComponent.cs b/Content.Server/GameObjects/Components/GUI/InventoryComponent.cs index b993e01071..07ba947103 100644 --- a/Content.Server/GameObjects/Components/GUI/InventoryComponent.cs +++ b/Content.Server/GameObjects/Components/GUI/InventoryComponent.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using Content.Server.Administration.Commands; using Content.Server.GameObjects.Components.Items.Clothing; @@ -42,7 +43,7 @@ namespace Content.Server.GameObjects.Components.GUI public IEnumerable Slots => _slotContainers.Keys; - public event Action OnItemChanged; + public event Action? OnItemChanged; public override void Initialize() { @@ -145,7 +146,7 @@ namespace Content.Server.GameObjects.Components.GUI bool IEffectBlocker.CanSlip() { - return !TryGetSlotItem(EquipmentSlotDefines.Slots.SHOES, out ItemComponent shoes) || EffectBlockerSystem.CanSlip(shoes.Owner); + return !TryGetSlotItem(EquipmentSlotDefines.Slots.SHOES, out ItemComponent? shoes) || EffectBlockerSystem.CanSlip(shoes.Owner); } public override void OnRemove() @@ -154,7 +155,7 @@ namespace Content.Server.GameObjects.Components.GUI foreach (var slot in slots) { - if (TryGetSlotItem(slot, out ItemComponent item)) + if (TryGetSlotItem(slot, out ItemComponent? item)) { item.Owner.Delete(); } @@ -191,18 +192,19 @@ namespace Content.Server.GameObjects.Components.GUI /// /// The slot to get the item for. /// Null if the slot is empty, otherwise the item. - public ItemComponent GetSlotItem(Slots slot) + public ItemComponent? GetSlotItem(Slots slot) { return GetSlotItem(slot); } - public IEnumerable LookupItems() where T : Component + public IEnumerable LookupItems() where T : Component { - return _slotContainers.Values.SelectMany(x => x.ContainedEntities.Select(e => e.GetComponentOrNull())) + return _slotContainers.Values + .SelectMany(x => x.ContainedEntities.Select(e => e.GetComponentOrNull())) .Where(x => x != null); } - public T GetSlotItem(Slots slot) where T : ItemComponent + public T? GetSlotItem(Slots slot) where T : ItemComponent { if (!_slotContainers.ContainsKey(slot)) { @@ -212,7 +214,7 @@ namespace Content.Server.GameObjects.Components.GUI var containedEntity = _slotContainers[slot].ContainedEntity; if (containedEntity?.Deleted == true) { - _slotContainers[slot] = null; + _slotContainers.Remove(slot); containedEntity = null; Dirty(); } @@ -220,7 +222,7 @@ namespace Content.Server.GameObjects.Components.GUI return containedEntity?.GetComponent(); } - public bool TryGetSlotItem(Slots slot, out T itemComponent) where T : ItemComponent + public bool TryGetSlotItem(Slots slot, [NotNullWhen(true)] out T? itemComponent) where T : ItemComponent { itemComponent = GetSlotItem(slot); return itemComponent != null; @@ -237,7 +239,7 @@ namespace Content.Server.GameObjects.Components.GUI /// Whether to perform an ActionBlocker check to the entity. /// The translated reason why the item cannot be equipped, if this function returns false. Can be null. /// True if the item was successfully inserted, false otherwise. - public bool Equip(Slots slot, ItemComponent item, bool mobCheck, out string reason) + public bool Equip(Slots slot, ItemComponent item, bool mobCheck, [NotNullWhen(false)] out string? reason) { if (item == null) { @@ -253,6 +255,7 @@ namespace Content.Server.GameObjects.Components.GUI var inventorySlot = _slotContainers[slot]; if (!inventorySlot.Insert(item.Owner)) { + reason = Loc.GetString("You can't equip this!"); return false; } @@ -280,13 +283,16 @@ namespace Content.Server.GameObjects.Components.GUI /// The item to check for. /// The translated reason why the item cannot be equiped, if this function returns false. Can be null. /// True if the item can be inserted into the specified slot. - public bool CanEquip(Slots slot, ItemComponent item, bool mobCheck, out string reason) + public bool CanEquip(Slots slot, ItemComponent item, bool mobCheck, [NotNullWhen(false)] out string? reason) { var pass = false; reason = null; if (mobCheck && !ActionBlockerSystem.CanEquip(Owner)) + { + reason = Loc.GetString("You can't equip this!"); return false; + } if (item is ClothingComponent clothing) { @@ -300,7 +306,7 @@ namespace Content.Server.GameObjects.Components.GUI } } - if (Owner.TryGetComponent(out IInventoryController controller)) + if (Owner.TryGetComponent(out IInventoryController? controller)) { pass = controller.CanEquip(slot, item.Owner, pass, out var controllerReason); reason = controllerReason ?? reason; @@ -311,7 +317,14 @@ namespace Content.Server.GameObjects.Components.GUI reason = Loc.GetString("You can't equip this!"); } - return pass && _slotContainers[slot].CanInsert(item.Owner); + var canEquip = pass && _slotContainers[slot].CanInsert(item.Owner); + + if (!canEquip) + { + reason = Loc.GetString("You can't equip this!"); + } + + return canEquip; } public bool CanEquip(Slots slot, ItemComponent item, bool mobCheck = true) => @@ -335,7 +348,12 @@ namespace Content.Server.GameObjects.Components.GUI var inventorySlot = _slotContainers[slot]; var entity = inventorySlot.ContainedEntity; - var item = entity.GetComponent(); + + if (entity == null) + { + return false; + } + if (!inventorySlot.Remove(entity)) { return false; @@ -357,7 +375,7 @@ namespace Content.Server.GameObjects.Components.GUI private void UpdateMovementSpeed() { - if (Owner.TryGetComponent(out MovementSpeedModifierComponent mod)) + if (Owner.TryGetComponent(out MovementSpeedModifierComponent? mod)) { mod.RefreshMovementSpeedModifiers(); } @@ -476,7 +494,7 @@ namespace Content.Server.GameObjects.Components.GUI if (container is not ContainerSlot slot || !_slotContainers.ContainsValue(slot)) return; - if (entity.TryGetComponent(out ItemComponent itemComp)) + if (entity.TryGetComponent(out ItemComponent? itemComp)) { itemComp.RemovedFromSlot(); } @@ -497,16 +515,15 @@ namespace Content.Server.GameObjects.Components.GUI case ClientInventoryUpdate.Equip: { var hands = Owner.GetComponent(); - var activeHand = hands.GetActiveHand; - if (activeHand != null && activeHand.Owner.TryGetComponent(out ItemComponent clothing)) + var activeHand = hands.ActiveHand; + var activeItem = hands.GetActiveHand; + if (activeHand != null && activeItem != null && activeItem.Owner.TryGetComponent(out ItemComponent? clothing)) { - hands.Drop(hands.ActiveHand, doDropInteraction: false); + hands.Drop(activeHand, doDropInteraction: false); if (!Equip(msg.Inventoryslot, clothing, true, out var reason)) { hands.PutInHand(clothing); - - if (reason != null) - Owner.PopupMessageCursor(reason); + Owner.PopupMessageCursor(reason); } } @@ -553,7 +570,7 @@ namespace Content.Server.GameObjects.Components.GUI } /// - public override void HandleMessage(ComponentMessage message, IComponent component) + public override void HandleMessage(ComponentMessage message, IComponent? component) { base.HandleMessage(message, component); @@ -571,7 +588,7 @@ namespace Content.Server.GameObjects.Components.GUI /// public override void HandleNetworkMessage(ComponentMessage message, INetChannel netChannel, - ICommonSession session = null) + ICommonSession? session = null) { base.HandleNetworkMessage(message, netChannel, session); @@ -593,7 +610,7 @@ namespace Content.Server.GameObjects.Components.GUI if (!HasSlot(msg.Slot)) // client input sanitization return; var item = GetSlotItem(msg.Slot); - if (item != null && item.Owner.TryGetComponent(out ServerStorageComponent storage)) + if (item != null && item.Owner.TryGetComponent(out ServerStorageComponent? storage)) storage.OpenStorageUI(Owner); break; } diff --git a/Content.Server/GameObjects/Components/GUI/StrippableComponent.cs b/Content.Server/GameObjects/Components/GUI/StrippableComponent.cs index 56875893b1..a7ce8ccf35 100644 --- a/Content.Server/GameObjects/Components/GUI/StrippableComponent.cs +++ b/Content.Server/GameObjects/Components/GUI/StrippableComponent.cs @@ -76,11 +76,6 @@ namespace Content.Server.GameObjects.Components.GUI public override bool Drop(DragDropEventArgs args) { - if (args.User == null) - { - return false; - } - if (!args.User.TryGetComponent(out IActorComponent? actor)) return false; OpenUserInterface(actor.playerSession); @@ -288,7 +283,7 @@ namespace Content.Server.GameObjects.Components.GUI if (!inventory.HasSlot(slot)) return false; - if (!inventory.TryGetSlotItem(slot, out ItemComponent itemToTake)) + if (!inventory.TryGetSlotItem(slot, out ItemComponent? itemToTake)) { user.PopupMessageCursor(Loc.GetString("{0:They} {0:have} nothing there!", Owner)); return false; @@ -319,7 +314,12 @@ namespace Content.Server.GameObjects.Components.GUI var item = inventory.GetSlotItem(slot); inventory.Unequip(slot, false); - userHands.PutInHandOrDrop(item); + + if (item != null) + { + userHands.PutInHandOrDrop(item); + } + UpdateSubscribed(); } diff --git a/Content.Server/GameObjects/Components/Headset/HeadsetComponent.cs b/Content.Server/GameObjects/Components/Headset/HeadsetComponent.cs index 318fd69906..8b7ecb2de3 100644 --- a/Content.Server/GameObjects/Components/Headset/HeadsetComponent.cs +++ b/Content.Server/GameObjects/Components/Headset/HeadsetComponent.cs @@ -9,8 +9,6 @@ using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Network; -using Robust.Shared.Prototypes; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Utility; using Robust.Shared.ViewVariables; @@ -59,7 +57,7 @@ namespace Content.Server.GameObjects.Components.Headset { if (Owner.TryGetContainer(out var container)) { - if (!container.Owner.TryGetComponent(out IActorComponent actor)) + if (!container.Owner.TryGetComponent(out IActorComponent? actor)) return; var playerChannel = actor.playerSession.ConnectedClient; diff --git a/Content.Server/GameObjects/Components/Interactable/ExpendableLightComponent.cs b/Content.Server/GameObjects/Components/Interactable/ExpendableLightComponent.cs index fc7c4d340d..02edb49d94 100644 --- a/Content.Server/GameObjects/Components/Interactable/ExpendableLightComponent.cs +++ b/Content.Server/GameObjects/Components/Interactable/ExpendableLightComponent.cs @@ -29,7 +29,7 @@ namespace Content.Server.GameObjects.Components.Interactable [ViewVariables] private float _stateExpiryTime = default; - private AppearanceComponent _appearance = default; + private AppearanceComponent? _appearance = default; bool IUse.UseEntity(UseEntityEventArgs eventArgs) { @@ -64,7 +64,7 @@ namespace Content.Server.GameObjects.Components.Interactable CurrentState = ExpendableLightState.Lit; _stateExpiryTime = GlowDuration; - + UpdateSpriteAndSounds(Activated); UpdateVisualizer(); @@ -79,25 +79,22 @@ namespace Content.Server.GameObjects.Components.Interactable switch (CurrentState) { case ExpendableLightState.Lit: - _appearance.SetData(ExpendableLightVisuals.State, TurnOnBehaviourID); + _appearance?.SetData(ExpendableLightVisuals.State, TurnOnBehaviourID); break; case ExpendableLightState.Fading: - _appearance.SetData(ExpendableLightVisuals.State, FadeOutBehaviourID); + _appearance?.SetData(ExpendableLightVisuals.State, FadeOutBehaviourID); break; case ExpendableLightState.Dead: - _appearance.SetData(ExpendableLightVisuals.State, string.Empty); - break; - - default: + _appearance?.SetData(ExpendableLightVisuals.State, string.Empty); break; } } private void UpdateSpriteAndSounds(bool on) { - if (Owner.TryGetComponent(out SpriteComponent sprite)) + if (Owner.TryGetComponent(out SpriteComponent? sprite)) { switch (CurrentState) { @@ -145,7 +142,7 @@ namespace Content.Server.GameObjects.Components.Interactable } } - if (Owner.TryGetComponent(out ClothingComponent clothing)) + if (Owner.TryGetComponent(out ClothingComponent? clothing)) { clothing.ClothingEquippedPrefix = on ? "Activated" : string.Empty; } diff --git a/Content.Server/GameObjects/Components/Interactable/MultitoolComponent.cs b/Content.Server/GameObjects/Components/Interactable/MultitoolComponent.cs index 68217c2bd7..c84c9efaf1 100644 --- a/Content.Server/GameObjects/Components/Interactable/MultitoolComponent.cs +++ b/Content.Server/GameObjects/Components/Interactable/MultitoolComponent.cs @@ -44,9 +44,9 @@ namespace Content.Server.GameObjects.Components.Interactable [DataField("tools")] private List _tools = new(); private int _currentTool = 0; - private AudioSystem _audioSystem; - private ToolComponent _tool; - private SpriteComponent _sprite; + private AudioSystem _audioSystem = default!; + private ToolComponent? _tool; + private SpriteComponent? _sprite; public override void Initialize() { @@ -99,7 +99,7 @@ namespace Content.Server.GameObjects.Components.Interactable public override ComponentState GetComponentState(ICommonSession player) { - return new MultiToolComponentState(_tool.Qualities); + return new MultiToolComponentState(_tool?.Qualities ?? ToolQuality.None); } } } diff --git a/Content.Server/GameObjects/Components/Interactable/ToolComponent.cs b/Content.Server/GameObjects/Components/Interactable/ToolComponent.cs index 42403fac5b..2becf640ab 100644 --- a/Content.Server/GameObjects/Components/Interactable/ToolComponent.cs +++ b/Content.Server/GameObjects/Components/Interactable/ToolComponent.cs @@ -42,10 +42,10 @@ namespace Content.Server.GameObjects.Components.Interactable public float SpeedModifier { get; set; } = 1; [DataField("useSound")] - public string UseSound { get; set; } + public string? UseSound { get; set; } [DataField("useSoundCollection")] - public string UseSoundCollection { get; set; } + public string? UseSoundCollection { get; set; } public void AddQuality(ToolQuality quality) { @@ -64,7 +64,7 @@ namespace Content.Server.GameObjects.Components.Interactable return _qualities.HasFlag(quality); } - public virtual async Task UseTool(IEntity user, IEntity target, float doAfterDelay, ToolQuality toolQualityNeeded, Func doAfterCheck = null) + public virtual async Task UseTool(IEntity user, IEntity? target, float doAfterDelay, ToolQuality toolQualityNeeded, Func? doAfterCheck = null) { if (!HasQuality(toolQualityNeeded) || !ActionBlockerSystem.CanInteract(user)) return false; @@ -94,8 +94,13 @@ namespace Content.Server.GameObjects.Components.Interactable return true; } - protected void PlaySoundCollection(string name, float volume=-5f) + protected void PlaySoundCollection(string? name, float volume = -5f) { + if (string.IsNullOrEmpty(name)) + { + return; + } + var file = AudioHelpers.GetRandomFileFromSoundCollection(name); EntitySystem.Get() .PlayFromEntity(file, Owner, AudioHelpers.WithVariation(0.15f).WithVolume(volume)); diff --git a/Content.Server/GameObjects/Components/Interactable/WelderComponent.cs b/Content.Server/GameObjects/Components/Interactable/WelderComponent.cs index 33f1b0ce47..c43ee1c0ef 100644 --- a/Content.Server/GameObjects/Components/Interactable/WelderComponent.cs +++ b/Content.Server/GameObjects/Components/Interactable/WelderComponent.cs @@ -100,7 +100,7 @@ namespace Content.Server.GameObjects.Components.Interactable return new WelderComponentState(FuelCapacity, Fuel, WelderLit); } - public override async Task UseTool(IEntity user, IEntity target, float doAfterDelay, ToolQuality toolQualityNeeded, Func? doAfterCheck = null) + public override async Task UseTool(IEntity user, IEntity? target, float doAfterDelay, ToolQuality toolQualityNeeded, Func? doAfterCheck = null) { bool ExtraCheck() { @@ -108,7 +108,7 @@ namespace Content.Server.GameObjects.Components.Interactable if (!CanWeld(DefaultFuelCost)) { - target.PopupMessage(user, "Can't weld!"); + target?.PopupMessage(user, "Can't weld!"); return false; } diff --git a/Content.Server/GameObjects/Components/Items/Clothing/ClothingComponent.cs b/Content.Server/GameObjects/Components/Items/Clothing/ClothingComponent.cs index d61db6cdc9..cdcd519eb4 100644 --- a/Content.Server/GameObjects/Components/Items/Clothing/ClothingComponent.cs +++ b/Content.Server/GameObjects/Components/Items/Clothing/ClothingComponent.cs @@ -37,9 +37,9 @@ namespace Content.Server.GameObjects.Components.Items.Clothing public int HeatResistance => _heatResistance; [DataField("ClothingPrefix")] - private string _clothingEquippedPrefix; + private string? _clothingEquippedPrefix; [ViewVariables(VVAccess.ReadWrite)] - public string ClothingEquippedPrefix + public string? ClothingEquippedPrefix { get => _clothingEquippedPrefix; set @@ -57,15 +57,15 @@ namespace Content.Server.GameObjects.Components.Items.Clothing bool IUse.UseEntity(UseEntityEventArgs eventArgs) { if (!_quickEquipEnabled) return false; - if (!eventArgs.User.TryGetComponent(out InventoryComponent inv) - || !eventArgs.User.TryGetComponent(out HandsComponent hands)) return false; + if (!eventArgs.User.TryGetComponent(out InventoryComponent? inv) + || !eventArgs.User.TryGetComponent(out HandsComponent? hands)) return false; foreach (var (slot, flag) in SlotMasks) { // We check if the clothing can be equipped in this slot. if ((SlotFlags & flag) == 0) continue; - if (inv.TryGetSlotItem(slot, out ItemComponent item)) + if (inv.TryGetSlotItem(slot, out ItemComponent? item)) { if (!inv.CanUnequip(slot)) continue; hands.Drop(Owner); diff --git a/Content.Server/GameObjects/Components/Items/DiceComponent.cs b/Content.Server/GameObjects/Components/Items/DiceComponent.cs index 5c2417bde1..0d29ab4508 100644 --- a/Content.Server/GameObjects/Components/Items/DiceComponent.cs +++ b/Content.Server/GameObjects/Components/Items/DiceComponent.cs @@ -8,7 +8,6 @@ using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Prototypes; using Robust.Shared.Random; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Utility; using Robust.Shared.ViewVariables; @@ -50,7 +49,7 @@ namespace Content.Server.GameObjects.Components.Items public void Roll() { _currentSide = _random.Next(1, (_sides/_step)+1) * _step; - if (!Owner.TryGetComponent(out SpriteComponent sprite)) return; + if (!Owner.TryGetComponent(out SpriteComponent? sprite)) return; sprite.LayerSetState(0, $"d{_sides}{_currentSide}"); PlayDiceEffect(); } diff --git a/Content.Server/GameObjects/Components/Items/FloorTileItemComponent.cs b/Content.Server/GameObjects/Components/Items/FloorTileItemComponent.cs index 0db674381d..c67c3b6493 100644 --- a/Content.Server/GameObjects/Components/Items/FloorTileItemComponent.cs +++ b/Content.Server/GameObjects/Components/Items/FloorTileItemComponent.cs @@ -1,17 +1,15 @@ +using System.Collections.Generic; +using System.Threading.Tasks; using Content.Server.GameObjects.Components.Stack; using Content.Shared.Audio; using Content.Shared.Interfaces.GameObjects.Components; using Content.Shared.Maps; using Content.Shared.Utility; +using Robust.Server.GameObjects; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Maths; -using Robust.Shared.Serialization; -using System.Collections.Generic; -using System.Threading.Tasks; -using Robust.Server.GameObjects; -using Robust.Shared.Prototypes; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.GameObjects.Components.Items @@ -23,7 +21,7 @@ namespace Content.Server.GameObjects.Components.Items public override string Name => "FloorTile"; [DataField("outputs")] - private List _outputTiles; + private List? _outputTiles; public override void Initialize() { @@ -55,7 +53,7 @@ namespace Content.Server.GameObjects.Components.Items if (!eventArgs.InRangeUnobstructed(ignoreInsideBlocker: true, popup: true)) return true; - if (!Owner.TryGetComponent(out StackComponent stack)) + if (!Owner.TryGetComponent(out StackComponent? stack)) return true; var mapManager = IoCManager.Resolve(); @@ -65,6 +63,10 @@ namespace Content.Server.GameObjects.Components.Items if (locationMap.MapId == MapId.Nullspace) return true; mapManager.TryGetGrid(location.GetGridId(Owner.EntityManager), out var mapGrid); + + if (_outputTiles == null) + return true; + foreach (var currentTile in _outputTiles) { var currentTileDefinition = (ContentTileDefinition) _tileDefinitionManager[currentTile]; diff --git a/Content.Server/GameObjects/Components/Items/RCD/RCDAmmoComponent.cs b/Content.Server/GameObjects/Components/Items/RCD/RCDAmmoComponent.cs index a5091e095b..d20a4377ec 100644 --- a/Content.Server/GameObjects/Components/Items/RCD/RCDAmmoComponent.cs +++ b/Content.Server/GameObjects/Components/Items/RCD/RCDAmmoComponent.cs @@ -6,8 +6,6 @@ using Content.Shared.Interfaces; using Content.Shared.Interfaces.GameObjects.Components; using Robust.Shared.GameObjects; using Robust.Shared.Localization; -using Robust.Shared.Prototypes; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Utility; using Robust.Shared.ViewVariables; @@ -29,7 +27,9 @@ namespace Content.Server.GameObjects.Components.Items.RCD async Task IAfterInteract.AfterInteract(AfterInteractEventArgs eventArgs) { - if (eventArgs.Target == null || !eventArgs.Target.TryGetComponent(out RCDComponent rcdComponent) || !eventArgs.User.TryGetComponent(out IHandsComponent hands)) + if (eventArgs.Target == null || + !eventArgs.Target.TryGetComponent(out RCDComponent? rcdComponent) || + !eventArgs.User.TryGetComponent(out IHandsComponent? hands)) { return false; } diff --git a/Content.Server/GameObjects/Components/Items/RCD/RCDComponent.cs b/Content.Server/GameObjects/Components/Items/RCD/RCDComponent.cs index 7cdc578015..b4daec9ed6 100644 --- a/Content.Server/GameObjects/Components/Items/RCD/RCDComponent.cs +++ b/Content.Server/GameObjects/Components/Items/RCD/RCDComponent.cs @@ -13,8 +13,6 @@ using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Map; using Robust.Shared.Maths; -using Robust.Shared.Prototypes; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Utility; using Robust.Shared.ViewVariables; @@ -35,8 +33,7 @@ namespace Content.Server.GameObjects.Components.Items.RCD [ViewVariables(VVAccess.ReadWrite)] [DataField("maxAmmo")] public int maxAmmo = 5; public int _ammo; //How much "ammo" we have left. You can refill this with RCD ammo. [ViewVariables(VVAccess.ReadWrite)] [DataField("delay")] private float _delay = 2f; - private DoAfterSystem doAfterSystem; - + private DoAfterSystem doAfterSystem = default!; ///Enum to store the different mode states for clarity. private enum RcdMode @@ -135,7 +132,7 @@ namespace Content.Server.GameObjects.Components.Items.RCD } else //Delete what the user targeted { - eventArgs.Target.Delete(); + eventArgs.Target?.Delete(); } break; //Walls are a special behaviour, and require us to build a new object with a transform rather than setting a grid tile, thus we early return to avoid the tile set code. @@ -201,7 +198,7 @@ namespace Content.Server.GameObjects.Components.Items.RCD return false; } //They tried to decon a non-turf but it's not in the whitelist - if (eventArgs.Target != null && !eventArgs.Target.TryGetComponent(out RCDDeconstructWhitelist rcd_decon)) + if (eventArgs.Target != null && !eventArgs.Target.TryGetComponent(out RCDDeconstructWhitelist? deCon)) { Owner.PopupMessage(eventArgs.User, Loc.GetString("You can't deconstruct that!")); return false; diff --git a/Content.Server/GameObjects/Components/Items/Storage/ItemComponent.cs b/Content.Server/GameObjects/Components/Items/Storage/ItemComponent.cs index 5f891ec71b..47ab0722c2 100644 --- a/Content.Server/GameObjects/Components/Items/Storage/ItemComponent.cs +++ b/Content.Server/GameObjects/Components/Items/Storage/ItemComponent.cs @@ -12,8 +12,8 @@ using Robust.Server.GameObjects; using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.Localization; -using Robust.Shared.Players; using Robust.Shared.Physics; +using Robust.Shared.Players; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.GameObjects.Components.Items.Storage @@ -28,14 +28,11 @@ namespace Content.Server.GameObjects.Components.Items.Storage public override uint? NetID => ContentNetIDs.ITEM; [DataField("HeldPrefix")] - private string _equippedPrefix; + private string? _equippedPrefix; - public string EquippedPrefix + public string? EquippedPrefix { - get - { - return _equippedPrefix; - } + get => _equippedPrefix; set { _equippedPrefix = value; @@ -81,7 +78,7 @@ namespace Content.Server.GameObjects.Components.Items.Storage return false; } - if (Owner.TryGetComponent(out IPhysBody physics) && + if (Owner.TryGetComponent(out IPhysBody? physics) && physics.BodyType == BodyType.Static) { return false; @@ -92,9 +89,10 @@ namespace Content.Server.GameObjects.Components.Items.Storage bool IInteractHand.InteractHand(InteractHandEventArgs eventArgs) { - if (!CanPickup(eventArgs.User)) return false; + if (!CanPickup(eventArgs.User) || + !eventArgs.User.TryGetComponent(out IHandsComponent? hands) || + hands.ActiveHand == null) return false; - var hands = eventArgs.User.GetComponent(); hands.PutInHand(this, hands.ActiveHand, false); return true; } @@ -117,7 +115,7 @@ namespace Content.Server.GameObjects.Components.Items.Storage protected override void Activate(IEntity user, ItemComponent component) { - if (user.TryGetComponent(out HandsComponent hands) && !hands.IsHolding(component.Owner)) + if (user.TryGetComponent(out HandsComponent? hands) && !hands.IsHolding(component.Owner)) { hands.PutInHand(component); } diff --git a/Content.Server/GameObjects/Components/Items/Storage/SecureEntityStorageComponent.cs b/Content.Server/GameObjects/Components/Items/Storage/SecureEntityStorageComponent.cs index 9410fcbaf1..9c3d323f15 100644 --- a/Content.Server/GameObjects/Components/Items/Storage/SecureEntityStorageComponent.cs +++ b/Content.Server/GameObjects/Components/Items/Storage/SecureEntityStorageComponent.cs @@ -8,9 +8,6 @@ using Robust.Server.GameObjects; using Robust.Shared.Audio; using Robust.Shared.GameObjects; using Robust.Shared.Localization; -using Robust.Shared.Log; -using Robust.Shared.Prototypes; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -34,7 +31,7 @@ namespace Content.Server.GameObjects.Components.Items.Storage { _locked = value; - if (Owner.TryGetComponent(out AppearanceComponent appearance)) + if (Owner.TryGetComponent(out AppearanceComponent? appearance)) { appearance.SetData(StorageVisuals.Locked, _locked); } @@ -45,7 +42,7 @@ namespace Content.Server.GameObjects.Components.Items.Storage { base.Startup(); - if (Owner.TryGetComponent(out AppearanceComponent appearance)) + if (Owner.TryGetComponent(out AppearanceComponent? appearance)) { appearance.SetData(StorageVisuals.CanLock, true); } @@ -114,7 +111,7 @@ namespace Content.Server.GameObjects.Components.Items.Storage private bool CheckAccess(IEntity user) { - if (Owner.TryGetComponent(out AccessReader reader)) + if (Owner.TryGetComponent(out AccessReader? reader)) { if (!reader.IsAllowed(user)) { diff --git a/Content.Server/GameObjects/Components/MachineLinking/SignalLinkerComponent.cs b/Content.Server/GameObjects/Components/MachineLinking/SignalLinkerComponent.cs index 9a0acd7222..58eb076211 100644 --- a/Content.Server/GameObjects/Components/MachineLinking/SignalLinkerComponent.cs +++ b/Content.Server/GameObjects/Components/MachineLinking/SignalLinkerComponent.cs @@ -9,7 +9,7 @@ namespace Content.Server.GameObjects.Components.MachineLinking public override string Name => "SignalLinker"; [ViewVariables] - public SignalTransmitterComponent Link { get; set; } + public SignalTransmitterComponent? Link { get; set; } public override void Initialize() { diff --git a/Content.Server/GameObjects/Components/MachineLinking/SignalReceiverComponent.cs b/Content.Server/GameObjects/Components/MachineLinking/SignalReceiverComponent.cs index a269b7e8da..8d9041ebbc 100644 --- a/Content.Server/GameObjects/Components/MachineLinking/SignalReceiverComponent.cs +++ b/Content.Server/GameObjects/Components/MachineLinking/SignalReceiverComponent.cs @@ -6,10 +6,7 @@ using Content.Shared.Interfaces; using Content.Shared.Interfaces.GameObjects.Components; using Robust.Shared.GameObjects; using Robust.Shared.Localization; -using Robust.Shared.Prototypes; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; -using Robust.Shared.Utility; namespace Content.Server.GameObjects.Components.MachineLinking { @@ -18,18 +15,11 @@ namespace Content.Server.GameObjects.Components.MachineLinking { public override string Name => "SignalReceiver"; - private List _transmitters; + private readonly List _transmitters = new(); [DataField("maxTransmitters")] private int? _maxTransmitters = default; - public override void Initialize() - { - base.Initialize(); - - _transmitters = new List(); - } - public void DistributeSignal(T state) { foreach (var comp in Owner.GetAllComponents>()) @@ -78,7 +68,7 @@ namespace Content.Server.GameObjects.Components.MachineLinking /// /// /// - public bool Interact(IEntity user, SignalTransmitterComponent transmitter) + public bool Interact(IEntity user, SignalTransmitterComponent? transmitter) { if (transmitter == null) { diff --git a/Content.Server/GameObjects/Components/MachineLinking/SignalTransmitterComponent.cs b/Content.Server/GameObjects/Components/MachineLinking/SignalTransmitterComponent.cs index 3472276fa0..eec7df1581 100644 --- a/Content.Server/GameObjects/Components/MachineLinking/SignalTransmitterComponent.cs +++ b/Content.Server/GameObjects/Components/MachineLinking/SignalTransmitterComponent.cs @@ -17,7 +17,7 @@ namespace Content.Server.GameObjects.Components.MachineLinking { public override string Name => "SignalTransmitter"; - private List _unresolvedReceivers; + private List? _unresolvedReceivers = new(); private List _receivers = new(); /// @@ -74,6 +74,7 @@ namespace Content.Server.GameObjects.Components.MachineLinking { receiver.Subscribe(this); } + _unresolvedReceivers = null; } } @@ -112,7 +113,7 @@ namespace Content.Server.GameObjects.Components.MachineLinking _receivers.Remove(receiver); } - public SignalTransmitterComponent GetSignal(IEntity user) + public SignalTransmitterComponent GetSignal(IEntity? user) { if (user != null) { diff --git a/Content.Server/GameObjects/Components/MagicMirrorComponent.cs b/Content.Server/GameObjects/Components/MagicMirrorComponent.cs index 8455b87c27..077f62944c 100644 --- a/Content.Server/GameObjects/Components/MagicMirrorComponent.cs +++ b/Content.Server/GameObjects/Components/MagicMirrorComponent.cs @@ -59,14 +59,9 @@ namespace Content.Server.GameObjects.Components if (!map.ContainsKey(msg.HairName)) return; - if (msg.IsFacialHair) - { - looks.Appearance = looks.Appearance.WithFacialHairStyleName(msg.HairName); - } - else - { - looks.Appearance = looks.Appearance.WithHairStyleName(msg.HairName); - } + looks.Appearance = msg.IsFacialHair + ? looks.Appearance.WithFacialHairStyleName(msg.HairName) + : looks.Appearance.WithHairStyleName(msg.HairName); break; @@ -74,14 +69,9 @@ namespace Content.Server.GameObjects.Components var (r, g, b) = msg.HairColor; var color = new Color(r, g, b); - if (msg.IsFacialHair) - { - looks.Appearance = looks.Appearance.WithFacialHairColor(color); - } - else - { - looks.Appearance = looks.Appearance.WithHairColor(color); - } + looks.Appearance = msg.IsFacialHair + ? looks.Appearance.WithFacialHairColor(color) + : looks.Appearance.WithHairColor(color); break; @@ -110,8 +100,14 @@ namespace Content.Server.GameObjects.Components UserInterface?.Toggle(actor.playerSession); - var msg = new MagicMirrorInitialDataMessage(looks.Appearance.HairColor, looks.Appearance.FacialHairColor, looks.Appearance.HairStyleName, - looks.Appearance.FacialHairStyleName, looks.Appearance.EyeColor); + var appearance = looks.Appearance; + + var msg = new MagicMirrorInitialDataMessage( + appearance.HairColor, + appearance.FacialHairColor, + appearance.HairStyleName, + appearance.FacialHairStyleName, + appearance.EyeColor); UserInterface?.SendMessage(msg, actor.playerSession); } diff --git a/Content.Server/GameObjects/Components/Markers/ConditionalSpawnerComponent.cs b/Content.Server/GameObjects/Components/Markers/ConditionalSpawnerComponent.cs index f5ed93b73e..a52b135989 100644 --- a/Content.Server/GameObjects/Components/Markers/ConditionalSpawnerComponent.cs +++ b/Content.Server/GameObjects/Components/Markers/ConditionalSpawnerComponent.cs @@ -1,15 +1,11 @@ -using System; using System.Collections.Generic; using Content.Server.GameTicking; using Content.Server.Interfaces.GameTicking; -using Robust.Server.GameObjects; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Log; -using Robust.Shared.Prototypes; using Robust.Shared.Random; using Robust.Shared.Reflection; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -36,17 +32,6 @@ namespace Content.Server.GameObjects.Components.Markers [DataField("chance")] public float Chance { get; set; } = 1.0f; - public IEnumerable GameRules - { - get - { - foreach (var rule in _gameRules) - { - yield return _reflectionManager.GetType(rule); - } - } - } - private void RuleAdded(GameRuleAddedEventArgs obj) { if(_gameRules.Contains(obj.GameRule.GetType().Name)) @@ -61,7 +46,7 @@ namespace Content.Server.GameObjects.Components.Markers return; } - foreach (var rule in GameRules) + foreach (var rule in _gameRules) { if (!_gameTicker.HasGameRule(rule)) continue; Spawn(); diff --git a/Content.Server/GameObjects/Components/Markers/SpawnPointComponent.cs b/Content.Server/GameObjects/Components/Markers/SpawnPointComponent.cs index cfaa213625..9728ccb10b 100644 --- a/Content.Server/GameObjects/Components/Markers/SpawnPointComponent.cs +++ b/Content.Server/GameObjects/Components/Markers/SpawnPointComponent.cs @@ -3,7 +3,6 @@ using Content.Shared.Roles; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Prototypes; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -15,15 +14,15 @@ namespace Content.Server.GameObjects.Components.Markers { [Dependency] private readonly IPrototypeManager _prototypeManager = default!; - [ViewVariables(VVAccess.ReadWrite)] - [DataField("spawn_type")] - private SpawnPointType _spawnType = SpawnPointType.Unset; [ViewVariables(VVAccess.ReadWrite)] [DataField("job_id")] - private string _jobId; - public SpawnPointType SpawnType => _spawnType; - public JobPrototype Job => string.IsNullOrEmpty(_jobId) ? null - : _prototypeManager.Index(_jobId); + private string? _jobId; + + [field: ViewVariables(VVAccess.ReadWrite)] + [field: DataField("spawn_type")] + public SpawnPointType SpawnType { get; } = SpawnPointType.Unset; + + public JobPrototype? Job => string.IsNullOrEmpty(_jobId) ? null : _prototypeManager.Index(_jobId); } public enum SpawnPointType diff --git a/Content.Server/GameObjects/Components/Markers/TimedSpawnerComponent.cs b/Content.Server/GameObjects/Components/Markers/TimedSpawnerComponent.cs index 36a929dddd..a0d28207de 100644 --- a/Content.Server/GameObjects/Components/Markers/TimedSpawnerComponent.cs +++ b/Content.Server/GameObjects/Components/Markers/TimedSpawnerComponent.cs @@ -37,7 +37,7 @@ namespace Content.Server.GameObjects.Components.Markers [DataField("MaximumEntitiesSpawned")] public int MaximumEntitiesSpawned { get; set; } = 1; - private CancellationTokenSource TokenSource; + private CancellationTokenSource? TokenSource; void ISerializationHooks.AfterDeserialization() { @@ -54,7 +54,7 @@ namespace Content.Server.GameObjects.Components.Markers protected override void Shutdown() { base.Shutdown(); - TokenSource.Cancel(); + TokenSource?.Cancel(); } private void SetupTimer() diff --git a/Content.Server/GameObjects/Components/Markers/WarpPointComponent.cs b/Content.Server/GameObjects/Components/Markers/WarpPointComponent.cs index 61a9f4cf74..78539dfe55 100644 --- a/Content.Server/GameObjects/Components/Markers/WarpPointComponent.cs +++ b/Content.Server/GameObjects/Components/Markers/WarpPointComponent.cs @@ -1,8 +1,6 @@ using Content.Shared.GameObjects.EntitySystems; using Robust.Shared.GameObjects; using Robust.Shared.Localization; -using Robust.Shared.Prototypes; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Utility; using Robust.Shared.ViewVariables; @@ -14,7 +12,7 @@ namespace Content.Server.GameObjects.Components.Markers { public override string Name => "WarpPoint"; - [ViewVariables(VVAccess.ReadWrite)] [DataField("location")] public string Location { get; set; } + [ViewVariables(VVAccess.ReadWrite)] [DataField("location")] public string? Location { get; set; } public void Examine(FormattedMessage message, bool inDetailsRange) { diff --git a/Content.Server/GameObjects/Components/Medical/CloningPodComponent.cs b/Content.Server/GameObjects/Components/Medical/CloningPodComponent.cs index 4f3e047eaf..d9c34ed756 100644 --- a/Content.Server/GameObjects/Components/Medical/CloningPodComponent.cs +++ b/Content.Server/GameObjects/Components/Medical/CloningPodComponent.cs @@ -19,8 +19,6 @@ using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Maths; using Robust.Shared.Network; -using Robust.Shared.Prototypes; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -157,6 +155,7 @@ namespace Content.Server.GameObjects.Components.Medical } var dead = + mind.OwnedEntity != null && mind.OwnedEntity.TryGetComponent(out var state) && state.IsDead(); if (!dead) return; diff --git a/Content.Server/GameObjects/Components/Medical/HealingComponent.cs b/Content.Server/GameObjects/Components/Medical/HealingComponent.cs index f6d7e00d9d..83c212afbb 100644 --- a/Content.Server/GameObjects/Components/Medical/HealingComponent.cs +++ b/Content.Server/GameObjects/Components/Medical/HealingComponent.cs @@ -7,8 +7,6 @@ using Content.Shared.GameObjects.EntitySystems.ActionBlocker; using Content.Shared.Interfaces.GameObjects.Components; using Content.Shared.Utility; using Robust.Shared.GameObjects; -using Robust.Shared.Prototypes; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.GameObjects.Components.Medical @@ -27,7 +25,7 @@ namespace Content.Server.GameObjects.Components.Medical return false; } - if (!eventArgs.Target.TryGetComponent(out IDamageableComponent damageable)) + if (!eventArgs.Target.TryGetComponent(out IDamageableComponent? damageable)) { return true; } @@ -43,7 +41,7 @@ namespace Content.Server.GameObjects.Components.Medical return true; } - if (Owner.TryGetComponent(out StackComponent stack) && + if (Owner.TryGetComponent(out StackComponent? stack) && !stack.Use(1)) { return true; diff --git a/Content.Server/GameObjects/Components/Medical/MedicalScannerComponent.cs b/Content.Server/GameObjects/Components/Medical/MedicalScannerComponent.cs index 279f89d85d..53c67c3eeb 100644 --- a/Content.Server/GameObjects/Components/Medical/MedicalScannerComponent.cs +++ b/Content.Server/GameObjects/Components/Medical/MedicalScannerComponent.cs @@ -272,7 +272,7 @@ namespace Content.Server.GameObjects.Components.Medical //TODO: Show a 'ERROR: Body is completely devoid of soul' if no Mind owns the entity. var cloningSystem = EntitySystem.Get(); - if (!_bodyContainer.ContainedEntity.TryGetComponent(out MindComponent? mind) || !mind.HasMind) + if (!_bodyContainer.ContainedEntity.TryGetComponent(out MindComponent? mind) || mind.Mind == null) break; cloningSystem.AddToDnaScans(mind.Mind); diff --git a/Content.Server/GameObjects/Components/Mining/AsteroidRockComponent.cs b/Content.Server/GameObjects/Components/Mining/AsteroidRockComponent.cs index c3e1f1ae9f..29aa888f70 100644 --- a/Content.Server/GameObjects/Components/Mining/AsteroidRockComponent.cs +++ b/Content.Server/GameObjects/Components/Mining/AsteroidRockComponent.cs @@ -30,11 +30,11 @@ namespace Content.Server.GameObjects.Components.Mining async Task IInteractUsing.InteractUsing(InteractUsingEventArgs eventArgs) { var item = eventArgs.Using; - if (!item.TryGetComponent(out MeleeWeaponComponent meleeWeaponComponent)) return false; + if (!item.TryGetComponent(out MeleeWeaponComponent? meleeWeaponComponent)) return false; Owner.GetComponent().ChangeDamage(DamageType.Blunt, meleeWeaponComponent.Damage, false, item); - if (!item.TryGetComponent(out PickaxeComponent pickaxeComponent)) return true; + if (!item.TryGetComponent(out PickaxeComponent? pickaxeComponent)) return true; if (!string.IsNullOrWhiteSpace(pickaxeComponent.MiningSound)) { EntitySystem.Get().PlayFromEntity(pickaxeComponent.MiningSound, Owner, AudioParams.Default); diff --git a/Content.Server/GameObjects/Components/Mobs/HeatResistanceComponent.cs b/Content.Server/GameObjects/Components/Mobs/HeatResistanceComponent.cs index c5b546e767..9a86ff0699 100644 --- a/Content.Server/GameObjects/Components/Mobs/HeatResistanceComponent.cs +++ b/Content.Server/GameObjects/Components/Mobs/HeatResistanceComponent.cs @@ -12,7 +12,7 @@ namespace Content.Server.GameObjects.Components.Mobs public int GetHeatResistance() { - if (Owner.GetComponent().TryGetSlotItem(EquipmentSlotDefines.Slots.GLOVES, itemComponent: out ClothingComponent gloves)) + if (Owner.GetComponent().TryGetSlotItem(EquipmentSlotDefines.Slots.GLOVES, out ClothingComponent? gloves)) { return gloves?.HeatResistance ?? int.MinValue; } diff --git a/Content.Server/GameObjects/Components/Mobs/HumanoidAppearanceComponent.cs b/Content.Server/GameObjects/Components/Mobs/HumanoidAppearanceComponent.cs index a3053390db..19e8af7fa4 100644 --- a/Content.Server/GameObjects/Components/Mobs/HumanoidAppearanceComponent.cs +++ b/Content.Server/GameObjects/Components/Mobs/HumanoidAppearanceComponent.cs @@ -16,11 +16,11 @@ namespace Content.Server.GameObjects.Components.Mobs { base.Appearance = value; - if (Owner.TryGetComponent(out IBody body)) + if (Owner.TryGetComponent(out IBody? body)) { foreach (var part in body.Parts.Values) { - if (!part.Owner.TryGetComponent(out SpriteComponent sprite)) + if (!part.Owner.TryGetComponent(out SpriteComponent? sprite)) { continue; } @@ -35,11 +35,11 @@ namespace Content.Server.GameObjects.Components.Mobs { base.Startup(); - if (Appearance != null && Owner.TryGetComponent(out IBody body)) + if (Appearance != null! && Owner.TryGetComponent(out IBody? body)) { foreach (var part in body.Parts.Values) { - if (!part.Owner.TryGetComponent(out SpriteComponent sprite)) + if (!part.Owner.TryGetComponent(out SpriteComponent? sprite)) { continue; } diff --git a/Content.Server/GameObjects/Components/Mobs/MindComponent.cs b/Content.Server/GameObjects/Components/Mobs/MindComponent.cs index 60bba6a664..16024481b6 100644 --- a/Content.Server/GameObjects/Components/Mobs/MindComponent.cs +++ b/Content.Server/GameObjects/Components/Mobs/MindComponent.cs @@ -9,8 +9,8 @@ using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Map; -using Robust.Shared.Timing; using Robust.Shared.Serialization.Manager.Attributes; +using Robust.Shared.Timing; using Robust.Shared.Utility; using Robust.Shared.ViewVariables; @@ -115,7 +115,7 @@ namespace Content.Server.GameObjects.Components.Mobs if (Mind != null) { - ghost.Name = Mind.CharacterName; + ghost.Name = Mind.CharacterName ?? string.Empty; Mind.TransferTo(ghost); } }); diff --git a/Content.Server/GameObjects/Components/Mobs/ServerAlertsComponent.cs b/Content.Server/GameObjects/Components/Mobs/ServerAlertsComponent.cs index ece106c60f..8ee70aa95c 100644 --- a/Content.Server/GameObjects/Components/Mobs/ServerAlertsComponent.cs +++ b/Content.Server/GameObjects/Components/Mobs/ServerAlertsComponent.cs @@ -36,13 +36,13 @@ namespace Content.Server.GameObjects.Components.Mobs } else { - Logger.WarningS("alert", "weightlesssystem not found"); + Logger.WarningS("alert", $"{nameof(WeightlessSystem)} not found"); } base.OnRemove(); } - public override void HandleNetworkMessage(ComponentMessage message, INetChannel netChannel, ICommonSession session = null) + public override void HandleNetworkMessage(ComponentMessage message, INetChannel netChannel, ICommonSession? session = null) { base.HandleNetworkMessage(message, netChannel, session); diff --git a/Content.Server/GameObjects/Components/Mobs/State/CriticalMobState.cs b/Content.Server/GameObjects/Components/Mobs/State/CriticalMobState.cs index 5ad63dc6dc..78e32b9e94 100644 --- a/Content.Server/GameObjects/Components/Mobs/State/CriticalMobState.cs +++ b/Content.Server/GameObjects/Components/Mobs/State/CriticalMobState.cs @@ -12,22 +12,17 @@ namespace Content.Server.GameObjects.Components.Mobs.State { base.EnterState(entity); - if (entity.TryGetComponent(out AppearanceComponent appearance)) + if (entity.TryGetComponent(out AppearanceComponent? appearance)) { appearance.SetData(DamageStateVisuals.State, DamageState.Critical); } - if (entity.TryGetComponent(out StunnableComponent stun)) + if (entity.TryGetComponent(out StunnableComponent? stun)) { stun.CancelAll(); } EntitySystem.Get().Down(entity); } - - public override void ExitState(IEntity entity) - { - base.ExitState(entity); - } } } diff --git a/Content.Server/GameObjects/Components/Mobs/State/DeadMobState.cs b/Content.Server/GameObjects/Components/Mobs/State/DeadMobState.cs index 723f861982..ebd5a62048 100644 --- a/Content.Server/GameObjects/Components/Mobs/State/DeadMobState.cs +++ b/Content.Server/GameObjects/Components/Mobs/State/DeadMobState.cs @@ -14,24 +14,24 @@ namespace Content.Server.GameObjects.Components.Mobs.State { base.EnterState(entity); - if (entity.TryGetComponent(out AppearanceComponent appearance)) + if (entity.TryGetComponent(out AppearanceComponent? appearance)) { appearance.SetData(DamageStateVisuals.State, DamageState.Dead); } - if (entity.TryGetComponent(out ServerAlertsComponent status)) + if (entity.TryGetComponent(out ServerAlertsComponent? status)) { status.ShowAlert(AlertType.HumanDead); } - if (entity.TryGetComponent(out StunnableComponent stun)) + if (entity.TryGetComponent(out StunnableComponent? stun)) { stun.CancelAll(); } EntitySystem.Get().Down(entity); - if (entity.TryGetComponent(out IPhysBody physics)) + if (entity.TryGetComponent(out IPhysBody? physics)) { physics.CanCollide = false; } @@ -41,7 +41,7 @@ namespace Content.Server.GameObjects.Components.Mobs.State { base.ExitState(entity); - if (entity.TryGetComponent(out IPhysBody physics)) + if (entity.TryGetComponent(out IPhysBody? physics)) { physics.CanCollide = true; } diff --git a/Content.Server/GameObjects/Components/Mobs/StunnableComponent.cs b/Content.Server/GameObjects/Components/Mobs/StunnableComponent.cs index 5178385050..4060dc0db3 100644 --- a/Content.Server/GameObjects/Components/Mobs/StunnableComponent.cs +++ b/Content.Server/GameObjects/Components/Mobs/StunnableComponent.cs @@ -2,19 +2,14 @@ using Content.Server.GameObjects.EntitySystems; using Content.Server.Interfaces.GameObjects; using Content.Server.Utility; -using Content.Shared.Alert; using Content.Shared.Audio; using Content.Shared.GameObjects.Components.Mobs; using Content.Shared.GameObjects.Components.Mobs.State; -using Content.Shared.GameObjects.Components.Movement; -using Content.Shared.GameObjects.EntitySystems.ActionBlocker; -using Content.Shared.GameObjects.EntitySystems.EffectBlocker; using Content.Shared.Interfaces; using Robust.Server.GameObjects; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; -using Robust.Shared.Players; using Robust.Shared.Random; using Robust.Shared.Timing; @@ -73,12 +68,19 @@ namespace Content.Server.GameObjects.Components.Mobs Paralyze(4f); var source = eventArgs.Source; + var target = eventArgs.Target; - EntitySystem.Get().PlayFromEntity("/Audio/Effects/thudswoosh.ogg", source, - AudioHelpers.WithVariation(0.025f)); + if (source != null) + { + EntitySystem.Get().PlayFromEntity("/Audio/Effects/thudswoosh.ogg", source, + AudioHelpers.WithVariation(0.025f)); - source.PopupMessageOtherClients(Loc.GetString("{0} pushes {1}!", source.Name, eventArgs.Target.Name)); - source.PopupMessageCursor(Loc.GetString("You push {0}!", eventArgs.Target.Name)); + if (target != null) + { + source.PopupMessageOtherClients(Loc.GetString("{0} pushes {1}!", source.Name, target.Name)); + source.PopupMessageCursor(Loc.GetString("You push {0}!", target.Name)); + } + } return true; } diff --git a/Content.Server/GameObjects/Components/Mobs/VisitingMindComponent.cs b/Content.Server/GameObjects/Components/Mobs/VisitingMindComponent.cs index 9014ef98b4..f5177b6467 100644 --- a/Content.Server/GameObjects/Components/Mobs/VisitingMindComponent.cs +++ b/Content.Server/GameObjects/Components/Mobs/VisitingMindComponent.cs @@ -9,8 +9,7 @@ namespace Content.Server.GameObjects.Components.Mobs { public override string Name => "VisitingMind"; - [ViewVariables] - public Mind Mind { get; set; } + [ViewVariables] public Mind Mind { get; set; } = default!; public override void OnRemove() { diff --git a/Content.Server/GameObjects/Components/Morgue/CrematoriumEntityStorageComponent.cs b/Content.Server/GameObjects/Components/Morgue/CrematoriumEntityStorageComponent.cs index 493cdc22f1..033e5ed132 100644 --- a/Content.Server/GameObjects/Components/Morgue/CrematoriumEntityStorageComponent.cs +++ b/Content.Server/GameObjects/Components/Morgue/CrematoriumEntityStorageComponent.cs @@ -1,7 +1,10 @@ #nullable enable +using System.Threading; using Content.Server.GameObjects.Components.Items.Storage; using Content.Server.Interfaces.Chat; using Content.Server.Interfaces.GameObjects; +using Content.Server.Interfaces.GameTicking; +using Content.Server.Players; using Content.Server.Utility; using Content.Shared.GameObjects.Components.Morgue; using Content.Shared.GameObjects.EntitySystems; @@ -9,16 +12,13 @@ using Content.Shared.GameObjects.EntitySystems.ActionBlocker; using Content.Shared.GameObjects.Verbs; using Content.Shared.Interfaces; using Content.Shared.Interfaces.GameObjects.Components; +using Robust.Server.GameObjects; +using Robust.Server.Player; using Robust.Shared.GameObjects; +using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Utility; using Robust.Shared.ViewVariables; -using System.Threading; -using Content.Server.Interfaces.GameTicking; -using Content.Server.Players; -using Robust.Server.GameObjects; -using Robust.Server.Player; -using Robust.Shared.IoC; namespace Content.Server.GameObjects.Components.Morgue { @@ -124,7 +124,7 @@ namespace Content.Server.GameObjects.Components.Morgue if (mind != null) { IoCManager.Resolve().OnGhostAttempt(mind, false); - mind.OwnedEntity.PopupMessage(Loc.GetString("You cremate yourself!")); + mind.OwnedEntity?.PopupMessage(Loc.GetString("You cremate yourself!")); } victim.PopupMessageOtherClients(Loc.GetString("{0:theName} is cremating {0:themself}!", victim)); diff --git a/Content.Server/GameObjects/Components/Morgue/MorgueTrayComponent.cs b/Content.Server/GameObjects/Components/Morgue/MorgueTrayComponent.cs index b4057a278d..e7c9d0a6a2 100644 --- a/Content.Server/GameObjects/Components/Morgue/MorgueTrayComponent.cs +++ b/Content.Server/GameObjects/Components/Morgue/MorgueTrayComponent.cs @@ -11,7 +11,7 @@ namespace Content.Server.GameObjects.Components.Morgue public override string Name => "MorgueTray"; [ViewVariables] - public IEntity Morgue { get; set; } + public IEntity? Morgue { get; set; } void IActivate.Activate(ActivateEventArgs eventArgs) { diff --git a/Content.Server/GameObjects/Components/Movement/ClimbableComponent.cs b/Content.Server/GameObjects/Components/Movement/ClimbableComponent.cs index 4e93fdde95..ccca0a69ae 100644 --- a/Content.Server/GameObjects/Components/Movement/ClimbableComponent.cs +++ b/Content.Server/GameObjects/Components/Movement/ClimbableComponent.cs @@ -14,8 +14,6 @@ using Robust.Shared.Localization; using Robust.Shared.Log; using Robust.Shared.Maths; using Robust.Shared.Serialization.Manager.Attributes; -using Robust.Shared.Physics; -using Robust.Shared.Serialization; using Robust.Shared.ViewVariables; namespace Content.Server.GameObjects.Components.Movement @@ -76,7 +74,7 @@ namespace Content.Server.GameObjects.Components.Movement } if (!user.HasComponent() || - !user.TryGetComponent(out IBody body)) + !user.TryGetComponent(out IBody? body)) { reason = Loc.GetString("comp-climbable-cant-climb"); return false; @@ -160,7 +158,7 @@ namespace Content.Server.GameObjects.Components.Movement var result = await EntitySystem.Get().DoAfter(doAfterEventArgs); - if (result != DoAfterStatus.Cancelled && entityToMove.TryGetComponent(out PhysicsComponent body) && body.Fixtures.Count >= 1) + if (result != DoAfterStatus.Cancelled && entityToMove.TryGetComponent(out PhysicsComponent? body) && body.Fixtures.Count >= 1) { var entityPos = entityToMove.Transform.WorldPosition; @@ -194,7 +192,7 @@ namespace Content.Server.GameObjects.Components.Movement private async void TryClimb(IEntity user) { - if (!user.TryGetComponent(out ClimbingComponent climbingComponent) || climbingComponent.IsClimbing) + if (!user.TryGetComponent(out ClimbingComponent? climbingComponent) || climbingComponent.IsClimbing) return; var doAfterEventArgs = new DoAfterEventArgs(user, _climbDelay, default, Owner) @@ -207,7 +205,7 @@ namespace Content.Server.GameObjects.Components.Movement var result = await EntitySystem.Get().DoAfter(doAfterEventArgs); - if (result != DoAfterStatus.Cancelled && user.TryGetComponent(out PhysicsComponent body) && body.Fixtures.Count >= 1) + if (result != DoAfterStatus.Cancelled && user.TryGetComponent(out PhysicsComponent? body) && body.Fixtures.Count >= 1) { // TODO: Remove the copy-paste code var userPos = user.Transform.WorldPosition; diff --git a/Content.Server/GameObjects/Components/Nutrition/CreamPieComponent.cs b/Content.Server/GameObjects/Components/Nutrition/CreamPieComponent.cs index 179c58615f..9272442e32 100644 --- a/Content.Server/GameObjects/Components/Nutrition/CreamPieComponent.cs +++ b/Content.Server/GameObjects/Components/Nutrition/CreamPieComponent.cs @@ -23,7 +23,7 @@ namespace Content.Server.GameObjects.Components.Nutrition { PlaySound(); - if (Owner.TryGetComponent(out SolutionContainerComponent solution)) + if (Owner.TryGetComponent(out SolutionContainerComponent? solution)) { solution.Solution.SpillAt(Owner, "PuddleSmear", false); } diff --git a/Content.Server/GameObjects/Components/Nutrition/CreamPiedComponent.cs b/Content.Server/GameObjects/Components/Nutrition/CreamPiedComponent.cs index 2e68624b5b..12ed187642 100644 --- a/Content.Server/GameObjects/Components/Nutrition/CreamPiedComponent.cs +++ b/Content.Server/GameObjects/Components/Nutrition/CreamPiedComponent.cs @@ -23,7 +23,7 @@ namespace Content.Server.GameObjects.Components.Nutrition private set { _creamPied = value; - if (Owner.TryGetComponent(out AppearanceComponent appearance)) + if (Owner.TryGetComponent(out AppearanceComponent? appearance)) { appearance.SetData(CreamPiedVisuals.Creamed, CreamPied); } @@ -57,7 +57,7 @@ namespace Content.Server.GameObjects.Components.Nutrition Owner.PopupMessage(Loc.GetString("You have been creamed by {0:theName}!", eventArgs.Thrown)); Owner.PopupMessageOtherClients(Loc.GetString("{0:theName} has been creamed by {1:theName}!", Owner, eventArgs.Thrown)); - if (Owner.TryGetComponent(out StunnableComponent stun)) + if (Owner.TryGetComponent(out StunnableComponent? stun)) { stun.Paralyze(1f); } diff --git a/Content.Server/GameObjects/Components/Nutrition/FoodComponent.cs b/Content.Server/GameObjects/Components/Nutrition/FoodComponent.cs index cadf507a7d..7de614b37d 100644 --- a/Content.Server/GameObjects/Components/Nutrition/FoodComponent.cs +++ b/Content.Server/GameObjects/Components/Nutrition/FoodComponent.cs @@ -31,7 +31,7 @@ namespace Content.Server.GameObjects.Components.Nutrition public override string Name => "Food"; - [ViewVariables] [DataField("useSound")] protected virtual string UseSound { get; set; } = "/Audio/Items/eatfood.ogg"; + [ViewVariables] [DataField("useSound")] protected virtual string? UseSound { get; set; } = "/Audio/Items/eatfood.ogg"; [ViewVariables] [DataField("trash")] protected virtual string? TrashPrototype { get; set; } @@ -161,8 +161,12 @@ namespace Content.Server.GameObjects.Components.Nutrition firstStomach.TryTransferSolution(split); - _entitySystem.GetEntitySystem() - .PlayFromEntity(UseSound, trueTarget, AudioParams.Default.WithVolume(-1f)); + if (UseSound != null) + { + _entitySystem.GetEntitySystem() + .PlayFromEntity(UseSound, trueTarget, AudioParams.Default.WithVolume(-1f)); + } + trueTarget.PopupMessage(user, Loc.GetString("Nom")); // If utensils were used diff --git a/Content.Server/GameObjects/Components/Nutrition/FoodContainerComponent.cs b/Content.Server/GameObjects/Components/Nutrition/FoodContainerComponent.cs index 6f7c430e6d..5ca2cf0593 100644 --- a/Content.Server/GameObjects/Components/Nutrition/FoodContainerComponent.cs +++ b/Content.Server/GameObjects/Components/Nutrition/FoodContainerComponent.cs @@ -8,9 +8,8 @@ using Robust.Server.GameObjects; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Random; -using Robust.Shared.Prototypes; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; +using Robust.Shared.Utility; using Robust.Shared.ViewVariables; namespace Content.Server.GameObjects.Components.Nutrition @@ -26,9 +25,9 @@ namespace Content.Server.GameObjects.Components.Nutrition [Dependency] private readonly IRobustRandom _random = default!; public override string Name => "FoodContainer"; - private AppearanceComponent _appearance; + private AppearanceComponent? _appearance; [DataField("prototypes")] - private Dictionary _prototypes = default; + private Dictionary? _prototypes = default; [DataField("capacity")] private uint _capacity = 5; @@ -49,7 +48,7 @@ namespace Content.Server.GameObjects.Components.Nutrition bool IUse.UseEntity(UseEntityEventArgs eventArgs) { - if (!eventArgs.User.TryGetComponent(out HandsComponent handsComponent)) + if (!eventArgs.User.TryGetComponent(out HandsComponent? handsComponent)) { return false; } @@ -62,18 +61,26 @@ namespace Content.Server.GameObjects.Components.Nutrition Owner.Delete(); return false; } - return true; + return true; } - - private string GetRandomPrototype() + private string? GetRandomPrototype() { - var defaultProto = _prototypes.Keys.FirstOrDefault(); - if (_prototypes.Count == 1) + var defaultProto = _prototypes?.Keys.FirstOrDefault(); + + if (defaultProto == null) + { + return null; + } + + DebugTools.AssertNotNull(_prototypes); + + if (_prototypes!.Count == 1) { return defaultProto; } + var probResult = _random.Next(0, 100); var total = 0; foreach (var item in _prototypes) diff --git a/Content.Server/GameObjects/Components/Nutrition/HungerComponent.cs b/Content.Server/GameObjects/Components/Nutrition/HungerComponent.cs index 1ee8c10809..36c3329355 100644 --- a/Content.Server/GameObjects/Components/Nutrition/HungerComponent.cs +++ b/Content.Server/GameObjects/Components/Nutrition/HungerComponent.cs @@ -12,8 +12,6 @@ using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Players; using Robust.Shared.Random; -using Robust.Shared.Prototypes; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -81,13 +79,13 @@ namespace Content.Server.GameObjects.Components.Nutrition { // Revert slow speed if required if (_lastHungerThreshold == HungerThreshold.Starving && _currentHungerThreshold != HungerThreshold.Dead && - Owner.TryGetComponent(out MovementSpeedModifierComponent movementSlowdownComponent)) + Owner.TryGetComponent(out MovementSpeedModifierComponent? movementSlowdownComponent)) { movementSlowdownComponent.RefreshMovementSpeedModifiers(); } // Update UI - Owner.TryGetComponent(out ServerAlertsComponent alertsComponent); + Owner.TryGetComponent(out ServerAlertsComponent? alertsComponent); if (HungerThresholdAlertTypes.TryGetValue(_currentHungerThreshold, out var alertId)) { @@ -119,7 +117,7 @@ namespace Content.Server.GameObjects.Components.Nutrition case HungerThreshold.Starving: // TODO: If something else bumps this could cause mega-speed. // If some form of speed update system if multiple things are touching it use that. - if (Owner.TryGetComponent(out MovementSpeedModifierComponent movementSlowdownComponent1)) + if (Owner.TryGetComponent(out MovementSpeedModifierComponent? movementSlowdownComponent1)) { movementSlowdownComponent1.RefreshMovementSpeedModifiers(); } @@ -180,10 +178,10 @@ namespace Content.Server.GameObjects.Components.Nutrition if (_currentHungerThreshold != HungerThreshold.Dead) return; - if (!Owner.TryGetComponent(out IDamageableComponent damageable)) + if (!Owner.TryGetComponent(out IDamageableComponent? damageable)) return; - if (!Owner.TryGetComponent(out IMobStateComponent mobState)) + if (!Owner.TryGetComponent(out IMobStateComponent? mobState)) return; if (!mobState.IsDead()) diff --git a/Content.Server/GameObjects/Components/Nutrition/ThirstComponent.cs b/Content.Server/GameObjects/Components/Nutrition/ThirstComponent.cs index 134d851aa8..56ce11e49a 100644 --- a/Content.Server/GameObjects/Components/Nutrition/ThirstComponent.cs +++ b/Content.Server/GameObjects/Components/Nutrition/ThirstComponent.cs @@ -12,8 +12,6 @@ using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Players; using Robust.Shared.Random; -using Robust.Shared.Prototypes; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -80,13 +78,13 @@ namespace Content.Server.GameObjects.Components.Nutrition { // Revert slow speed if required if (_lastThirstThreshold == ThirstThreshold.Parched && _currentThirstThreshold != ThirstThreshold.Dead && - Owner.TryGetComponent(out MovementSpeedModifierComponent movementSlowdownComponent)) + Owner.TryGetComponent(out MovementSpeedModifierComponent? movementSlowdownComponent)) { movementSlowdownComponent.RefreshMovementSpeedModifiers(); } // Update UI - Owner.TryGetComponent(out ServerAlertsComponent alertsComponent); + Owner.TryGetComponent(out ServerAlertsComponent? alertsComponent); if (ThirstThresholdAlertTypes.TryGetValue(_currentThirstThreshold, out var alertId)) { @@ -116,7 +114,7 @@ namespace Content.Server.GameObjects.Components.Nutrition return; case ThirstThreshold.Parched: - if (Owner.TryGetComponent(out MovementSpeedModifierComponent movementSlowdownComponent1)) + if (Owner.TryGetComponent(out MovementSpeedModifierComponent? movementSlowdownComponent1)) { movementSlowdownComponent1.RefreshMovementSpeedModifiers(); } @@ -177,10 +175,10 @@ namespace Content.Server.GameObjects.Components.Nutrition if (_currentThirstThreshold != ThirstThreshold.Dead) return; - if (!Owner.TryGetComponent(out IDamageableComponent damageable)) + if (!Owner.TryGetComponent(out IDamageableComponent? damageable)) return; - if (!Owner.TryGetComponent(out IMobStateComponent mobState)) + if (!Owner.TryGetComponent(out IMobStateComponent? mobState)) return; if (!mobState.IsDead()) diff --git a/Content.Server/GameObjects/Components/Observer/GhostComponent.cs b/Content.Server/GameObjects/Components/Observer/GhostComponent.cs index 6c324f3421..c8699c7877 100644 --- a/Content.Server/GameObjects/Components/Observer/GhostComponent.cs +++ b/Content.Server/GameObjects/Components/Observer/GhostComponent.cs @@ -158,6 +158,11 @@ namespace Content.Server.GameObjects.Components.Observer var warpName = new List(); foreach (var point in warpPoints) { + if (point.Location == null) + { + continue; + } + warpName.Add(point.Location); } SendNetworkMessage(new GhostReplyWarpPointData(warpName)); diff --git a/Content.Server/GameObjects/Components/Observer/GhostRoles/GhostRoleMobSpawnerComponent.cs b/Content.Server/GameObjects/Components/Observer/GhostRoles/GhostRoleMobSpawnerComponent.cs index 3f55db9d3e..6b4bad68f0 100644 --- a/Content.Server/GameObjects/Components/Observer/GhostRoles/GhostRoleMobSpawnerComponent.cs +++ b/Content.Server/GameObjects/Components/Observer/GhostRoles/GhostRoleMobSpawnerComponent.cs @@ -6,6 +6,7 @@ using JetBrains.Annotations; using Robust.Server.Player; using Robust.Shared.GameObjects; using Robust.Shared.Serialization.Manager.Attributes; +using Robust.Shared.Utility; using Robust.Shared.ViewVariables; namespace Content.Server.GameObjects.Components.Observer.GhostRoles @@ -33,7 +34,7 @@ namespace Content.Server.GameObjects.Components.Observer.GhostRoles [CanBeNull] [ViewVariables(VVAccess.ReadWrite)] [DataField("prototype")] - public string Prototype { get; private set; } + public string? Prototype { get; private set; } public override bool Take(IPlayerSession session) { @@ -50,7 +51,11 @@ namespace Content.Server.GameObjects.Components.Observer.GhostRoles mob.EnsureComponent(); - session.ContentData().Mind.TransferTo(mob); + var mind = session.ContentData()?.Mind; + + DebugTools.AssertNotNull(mind); + + mind!.TransferTo(mob); if (++_currentTakeovers < _availableTakeovers) return true; diff --git a/Content.Server/GameObjects/Components/Observer/GhostRoles/GhostTakeoverAvailableComponent.cs b/Content.Server/GameObjects/Components/Observer/GhostRoles/GhostTakeoverAvailableComponent.cs index 8d46baf34d..b4a331dcac 100644 --- a/Content.Server/GameObjects/Components/Observer/GhostRoles/GhostTakeoverAvailableComponent.cs +++ b/Content.Server/GameObjects/Components/Observer/GhostRoles/GhostTakeoverAvailableComponent.cs @@ -4,6 +4,7 @@ using Content.Server.GameObjects.EntitySystems; using Content.Server.Players; using Robust.Server.Player; using Robust.Shared.GameObjects; +using Robust.Shared.Utility; namespace Content.Server.GameObjects.Components.Observer.GhostRoles { @@ -24,10 +25,14 @@ namespace Content.Server.GameObjects.Components.Observer.GhostRoles var mind = Owner.EnsureComponent(); - if(mind.HasMind) + if (mind.HasMind) throw new Exception("MindComponent already has a mind!"); - session.ContentData().Mind.TransferTo(Owner); + var sessionMind = session.ContentData()?.Mind; + + DebugTools.AssertNotNull(sessionMind); + + sessionMind!.TransferTo(Owner); EntitySystem.Get().UnregisterGhostRole(this); diff --git a/Content.Server/GameObjects/Components/Projectiles/ChemicalInjectionProjectileComponent.cs b/Content.Server/GameObjects/Components/Projectiles/ChemicalInjectionProjectileComponent.cs index 60f34ee2be..54e09659d2 100644 --- a/Content.Server/GameObjects/Components/Projectiles/ChemicalInjectionProjectileComponent.cs +++ b/Content.Server/GameObjects/Components/Projectiles/ChemicalInjectionProjectileComponent.cs @@ -1,14 +1,12 @@ -using Content.Server.GameObjects.Components.Body.Circulatory; +using System; +using Content.Server.GameObjects.Components.Body.Circulatory; using Content.Server.GameObjects.Components.Chemistry; using Content.Shared.Chemistry; using Robust.Shared.GameObjects; -using Robust.Shared.Serialization; -using Robust.Shared.ViewVariables; -using System; -using Robust.Shared.Prototypes; -using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Physics; using Robust.Shared.Physics.Collision; +using Robust.Shared.Serialization.Manager.Attributes; +using Robust.Shared.ViewVariables; namespace Content.Server.GameObjects.Components.Projectiles { @@ -18,7 +16,7 @@ namespace Content.Server.GameObjects.Components.Projectiles public override string Name => "ChemicalInjectionProjectile"; [ViewVariables] - private SolutionContainerComponent _solutionContainer; + private SolutionContainerComponent _solutionContainer = default!; [ViewVariables(VVAccess.ReadWrite)] [DataField("transferAmount")] diff --git a/Content.Server/GameObjects/Components/Projectiles/ExplosiveProjectileComponent.cs b/Content.Server/GameObjects/Components/Projectiles/ExplosiveProjectileComponent.cs index 92aecd24aa..fb7acc3289 100644 --- a/Content.Server/GameObjects/Components/Projectiles/ExplosiveProjectileComponent.cs +++ b/Content.Server/GameObjects/Components/Projectiles/ExplosiveProjectileComponent.cs @@ -19,7 +19,7 @@ namespace Content.Server.GameObjects.Components.Projectiles void IStartCollide.CollideWith(IPhysBody ourBody, IPhysBody otherBody, in Manifold manifold) { - if (Owner.TryGetComponent(out ExplosiveComponent explosive)) + if (Owner.TryGetComponent(out ExplosiveComponent? explosive)) { explosive.Explosion(); } diff --git a/Content.Server/GameObjects/Components/Projectiles/HitscanComponent.cs b/Content.Server/GameObjects/Components/Projectiles/HitscanComponent.cs index d2e78de5d0..bff571c198 100644 --- a/Content.Server/GameObjects/Components/Projectiles/HitscanComponent.cs +++ b/Content.Server/GameObjects/Components/Projectiles/HitscanComponent.cs @@ -6,11 +6,8 @@ using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Maths; -using Robust.Shared.Physics; -using Robust.Shared.Physics.Dynamics; -using Robust.Shared.Serialization; -using Robust.Shared.Timing; using Robust.Shared.Serialization.Manager.Attributes; +using Robust.Shared.Timing; namespace Content.Server.GameObjects.Components.Projectiles { @@ -47,13 +44,13 @@ namespace Content.Server.GameObjects.Components.Projectiles [DataField("spriteName")] private string _spriteName = "Objects/Weapons/Guns/Projectiles/laser.png"; [DataField("muzzleFlash")] - private string _muzzleFlash; + private string? _muzzleFlash; [DataField("impactFlash")] - private string _impactFlash; + private string? _impactFlash; [DataField("soundHitWall")] private string _soundHitWall = "/Audio/Weapons/Guns/Hits/laser_sear_wall.ogg"; - public void FireEffects(IEntity user, float distance, Angle angle, IEntity hitEntity = null) + public void FireEffects(IEntity user, float distance, Angle angle, IEntity? hitEntity = null) { var effectSystem = EntitySystem.Get(); _startTime = _gameTiming.CurTime; @@ -97,7 +94,7 @@ namespace Content.Server.GameObjects.Components.Projectiles }); } - private EffectSystemMessage MuzzleFlash(EntityCoordinates grid, Angle angle) + private EffectSystemMessage? MuzzleFlash(EntityCoordinates grid, Angle angle) { if (_muzzleFlash == null) { @@ -143,7 +140,7 @@ namespace Content.Server.GameObjects.Components.Projectiles return message; } - private EffectSystemMessage ImpactFlash(float distance, Angle angle) + private EffectSystemMessage? ImpactFlash(float distance, Angle angle) { if (_impactFlash == null) { diff --git a/Content.Server/GameObjects/Components/Projectiles/ProjectileComponent.cs b/Content.Server/GameObjects/Components/Projectiles/ProjectileComponent.cs index 69d3c82f45..4b8f144f95 100644 --- a/Content.Server/GameObjects/Components/Projectiles/ProjectileComponent.cs +++ b/Content.Server/GameObjects/Components/Projectiles/ProjectileComponent.cs @@ -8,7 +8,6 @@ using Robust.Shared.GameObjects; using Robust.Shared.Physics; using Robust.Shared.Physics.Collision; using Robust.Shared.Players; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -30,15 +29,14 @@ namespace Content.Server.GameObjects.Components.Projectiles set => _damages = value; } - public bool DeleteOnCollide => _deleteOnCollide; - [DataField("delete_on_collide")] - private bool _deleteOnCollide = true; + [field: DataField("delete_on_collide")] + public bool DeleteOnCollide { get; } = true; // Get that juicy FPS hit sound [DataField("soundHit")] - private string _soundHit = default; + private string? _soundHit = default; [DataField("soundHitSpecies")] - private string _soundHitSpecies = default; + private string? _soundHitSpecies = default; private bool _damagedEntity; @@ -65,7 +63,7 @@ namespace Content.Server.GameObjects.Components.Projectiles return; } - if (otherBody.Entity.TryGetComponent(out IDamageableComponent damage) && _soundHitSpecies != null) + if (otherBody.Entity.TryGetComponent(out IDamageableComponent? damage) && _soundHitSpecies != null) { EntitySystem.Get().PlayAtCoords(_soundHitSpecies, otherBody.Entity.Transform.Coordinates); } @@ -87,7 +85,7 @@ namespace Content.Server.GameObjects.Components.Projectiles } // Damaging it can delete it - if (!otherBody.Entity.Deleted && otherBody.Entity.TryGetComponent(out CameraRecoilComponent recoilComponent)) + if (!otherBody.Entity.Deleted && otherBody.Entity.TryGetComponent(out CameraRecoilComponent? recoilComponent)) { var direction = ourBody.LinearVelocity.Normalized; recoilComponent.Kick(direction); diff --git a/Content.Server/GameObjects/Components/Projectiles/StunnableProjectileComponent.cs b/Content.Server/GameObjects/Components/Projectiles/StunnableProjectileComponent.cs index c46e5c19ac..9d33ab07cb 100644 --- a/Content.Server/GameObjects/Components/Projectiles/StunnableProjectileComponent.cs +++ b/Content.Server/GameObjects/Components/Projectiles/StunnableProjectileComponent.cs @@ -1,9 +1,8 @@ using Content.Server.GameObjects.Components.Mobs; using Robust.Shared.GameObjects; -using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Physics; using Robust.Shared.Physics.Collision; -using Robust.Shared.Serialization; +using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.GameObjects.Components.Projectiles { @@ -32,7 +31,7 @@ namespace Content.Server.GameObjects.Components.Projectiles void IStartCollide.CollideWith(IPhysBody ourBody, IPhysBody otherBody, in Manifold manifold) { - if (otherBody.Entity.TryGetComponent(out StunnableComponent stunnableComponent)) + if (otherBody.Entity.TryGetComponent(out StunnableComponent? stunnableComponent)) { stunnableComponent.Stun(_stunAmount); stunnableComponent.Knockdown(_knockdownAmount); diff --git a/Content.Server/GameObjects/Components/RandomPottedPlantComponent.cs b/Content.Server/GameObjects/Components/RandomPottedPlantComponent.cs index 7d5a6caf75..b97b00196b 100644 --- a/Content.Server/GameObjects/Components/RandomPottedPlantComponent.cs +++ b/Content.Server/GameObjects/Components/RandomPottedPlantComponent.cs @@ -3,9 +3,7 @@ using JetBrains.Annotations; using Robust.Server.GameObjects; using Robust.Shared.GameObjects; using Robust.Shared.IoC; -using Robust.Shared.Prototypes; using Robust.Shared.Random; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.GameObjects.Components @@ -19,7 +17,7 @@ namespace Content.Server.GameObjects.Components private static readonly string[] PlasticPlantStates; [DataField("selected")] - private string _selectedState; + private string? _selectedState; [DataField("plastic")] private bool _plastic; diff --git a/Content.Server/GameObjects/Components/RandomSpriteColorComponent.cs b/Content.Server/GameObjects/Components/RandomSpriteColorComponent.cs index ed4f6588b2..c1b1f30806 100644 --- a/Content.Server/GameObjects/Components/RandomSpriteColorComponent.cs +++ b/Content.Server/GameObjects/Components/RandomSpriteColorComponent.cs @@ -3,9 +3,7 @@ using Robust.Server.GameObjects; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Maths; -using Robust.Shared.Prototypes; using Robust.Shared.Random; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.GameObjects.Components @@ -16,19 +14,14 @@ namespace Content.Server.GameObjects.Components public override string Name => "RandomSpriteColor"; [DataField("selected")] - private string _selectedColor; + private string? _selectedColor; [DataField("state")] private string _baseState = "error"; - [DataField("colors")] private Dictionary _colors = new(); + [DataField("colors")] private readonly Dictionary _colors = new(); void IMapInit.MapInit() { - if (_colors == null) - { - return; - } - var random = IoCManager.Resolve(); _selectedColor = random.Pick(_colors.Keys); UpdateColor(); @@ -43,7 +36,7 @@ namespace Content.Server.GameObjects.Components private void UpdateColor() { - if (Owner.TryGetComponent(out SpriteComponent spriteComponent) && _colors != null && _selectedColor != null) + if (Owner.TryGetComponent(out SpriteComponent? spriteComponent) && _selectedColor != null) { spriteComponent.LayerSetState(0, _baseState); spriteComponent.LayerSetColor(0, _colors[_selectedColor]); diff --git a/Content.Server/GameObjects/Components/RandomSpriteStateComponent.cs b/Content.Server/GameObjects/Components/RandomSpriteStateComponent.cs index e326a58407..ce8a1b488f 100644 --- a/Content.Server/GameObjects/Components/RandomSpriteStateComponent.cs +++ b/Content.Server/GameObjects/Components/RandomSpriteStateComponent.cs @@ -2,9 +2,7 @@ using Robust.Server.GameObjects; using Robust.Shared.GameObjects; using Robust.Shared.IoC; -using Robust.Shared.Prototypes; using Robust.Shared.Random; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.GameObjects.Components @@ -16,7 +14,7 @@ namespace Content.Server.GameObjects.Components public override string Name => "RandomSpriteState"; [DataField("spriteStates")] - private List _spriteStates; + private List? _spriteStates; [DataField("spriteLayer")] private int _spriteLayer; @@ -25,7 +23,7 @@ namespace Content.Server.GameObjects.Components { base.Initialize(); if (_spriteStates == null) return; - if (!Owner.TryGetComponent(out SpriteComponent spriteComponent)) return; + if (!Owner.TryGetComponent(out SpriteComponent? spriteComponent)) return; spriteComponent.LayerSetState(_spriteLayer, _random.Pick(_spriteStates)); } } diff --git a/Content.Server/GameObjects/Components/Recycling/RecyclerComponent.cs b/Content.Server/GameObjects/Components/Recycling/RecyclerComponent.cs index 6f4ef912de..ea9c13d542 100644 --- a/Content.Server/GameObjects/Components/Recycling/RecyclerComponent.cs +++ b/Content.Server/GameObjects/Components/Recycling/RecyclerComponent.cs @@ -11,18 +11,14 @@ using Content.Server.Utility; using Content.Shared.GameObjects.Components.Body; using Content.Shared.GameObjects.Components.Recycling; using Content.Shared.Interfaces; -using Content.Shared.Physics; using Robust.Server.GameObjects; using Robust.Server.Player; using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; -using Robust.Shared.Maths; -using Robust.Shared.Prototypes; using Robust.Shared.Physics; using Robust.Shared.Physics.Collision; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -156,7 +152,7 @@ namespace Content.Server.GameObjects.Components.Recycling if (mind != null) { IoCManager.Resolve().OnGhostAttempt(mind, false); - mind.OwnedEntity.PopupMessage(Loc.GetString("You recycle yourself!")); + mind.OwnedEntity?.PopupMessage(Loc.GetString("You recycle yourself!")); } victim.PopupMessageOtherClients(Loc.GetString("{0:theName} tries to recycle {0:themself}!", victim)); diff --git a/Content.Server/GameObjects/Components/Research/ProtolatheDatabaseComponent.cs b/Content.Server/GameObjects/Components/Research/ProtolatheDatabaseComponent.cs index 049cc8a592..8765109629 100644 --- a/Content.Server/GameObjects/Components/Research/ProtolatheDatabaseComponent.cs +++ b/Content.Server/GameObjects/Components/Research/ProtolatheDatabaseComponent.cs @@ -26,7 +26,7 @@ namespace Content.Server.GameObjects.Components.Research /// public void Sync() { - if (!Owner.TryGetComponent(out TechnologyDatabaseComponent database)) return; + if (!Owner.TryGetComponent(out TechnologyDatabaseComponent? database)) return; foreach (var technology in database.Technologies) { diff --git a/Content.Server/GameObjects/Components/Research/ResearchPointSourceComponent.cs b/Content.Server/GameObjects/Components/Research/ResearchPointSourceComponent.cs index 54a816aef7..94e9047f51 100644 --- a/Content.Server/GameObjects/Components/Research/ResearchPointSourceComponent.cs +++ b/Content.Server/GameObjects/Components/Research/ResearchPointSourceComponent.cs @@ -1,8 +1,6 @@ using Content.Server.GameObjects.Components.Power.ApcNetComponents; using Content.Shared.Interfaces.GameObjects.Components; using Robust.Shared.GameObjects; -using Robust.Shared.Prototypes; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -18,7 +16,7 @@ namespace Content.Server.GameObjects.Components.Research private int _pointsPerSecond; [DataField("active")] private bool _active; - private PowerReceiverComponent _powerReceiver; + private PowerReceiverComponent? _powerReceiver; [ViewVariables(VVAccess.ReadWrite)] public int PointsPerSecond diff --git a/Content.Server/GameObjects/Components/Research/ResearchServerComponent.cs b/Content.Server/GameObjects/Components/Research/ResearchServerComponent.cs index d546dead49..683cd58e54 100644 --- a/Content.Server/GameObjects/Components/Research/ResearchServerComponent.cs +++ b/Content.Server/GameObjects/Components/Research/ResearchServerComponent.cs @@ -20,7 +20,7 @@ namespace Content.Server.GameObjects.Components.Research [DataField("servername")] private string _serverName = "RDSERVER"; private float _timer = 0f; - public TechnologyDatabaseComponent Database { get; private set; } + public TechnologyDatabaseComponent? Database { get; private set; } [ViewVariables(VVAccess.ReadWrite)] [DataField("points")] private int _points = 0; @@ -28,7 +28,7 @@ namespace Content.Server.GameObjects.Components.Research // You could optimize research by keeping a list of unlocked recipes too. [ViewVariables(VVAccess.ReadOnly)] - public IReadOnlyList UnlockedTechnologies => Database.Technologies; + public IReadOnlyList? UnlockedTechnologies => Database?.Technologies; [ViewVariables(VVAccess.ReadOnly)] public List PointSources { get; } = new(); @@ -66,7 +66,7 @@ namespace Content.Server.GameObjects.Components.Research [ViewVariables] public bool CanRun => _powerReceiver is null || _powerReceiver.Powered; - private PowerReceiverComponent _powerReceiver; + private PowerReceiverComponent? _powerReceiver; public override void Initialize() { @@ -86,8 +86,14 @@ namespace Content.Server.GameObjects.Components.Research public bool CanUnlockTechnology(TechnologyPrototype technology) { - if (!Database.CanUnlockTechnology(technology) || _points < technology.RequiredPoints || - Database.IsTechnologyUnlocked(technology)) return false; + if (Database == null) + return false; + + if (!Database.CanUnlockTechnology(technology) || + _points < technology.RequiredPoints || + Database.IsTechnologyUnlocked(technology)) + return false; + return true; } @@ -100,7 +106,7 @@ namespace Content.Server.GameObjects.Components.Research public bool UnlockTechnology(TechnologyPrototype technology) { if (!CanUnlockTechnology(technology)) return false; - var result = Database.UnlockTechnology(technology); + var result = Database?.UnlockTechnology(technology) ?? false; if (result) _points -= technology.RequiredPoints; return result; @@ -113,7 +119,7 @@ namespace Content.Server.GameObjects.Components.Research /// public bool IsTechnologyUnlocked(TechnologyPrototype technology) { - return Database.IsTechnologyUnlocked(technology); + return Database?.IsTechnologyUnlocked(technology) ?? false; } /// diff --git a/Content.Server/GameObjects/Components/Research/TechnologyDatabaseComponent.cs b/Content.Server/GameObjects/Components/Research/TechnologyDatabaseComponent.cs index df82955d9e..681e021b56 100644 --- a/Content.Server/GameObjects/Components/Research/TechnologyDatabaseComponent.cs +++ b/Content.Server/GameObjects/Components/Research/TechnologyDatabaseComponent.cs @@ -27,7 +27,7 @@ namespace Content.Server.GameObjects.Components.Research if (!IsTechnologyUnlocked(tech)) AddTechnology(tech); } - if(twoway) + if (twoway) otherDatabase.Sync(this, false); Dirty(); @@ -41,8 +41,8 @@ namespace Content.Server.GameObjects.Components.Research /// Whether it could sync or not public bool SyncWithServer() { - if (!Owner.TryGetComponent(out ResearchClientComponent client)) return false; - if (!client.ConnectedToServer) return false; + if (!Owner.TryGetComponent(out ResearchClientComponent? client)) return false; + if (client.Server?.Database == null) return false; Sync(client.Server.Database); diff --git a/Content.Server/GameObjects/Components/Rotatable/RotatableComponent.cs b/Content.Server/GameObjects/Components/Rotatable/RotatableComponent.cs index ed472ac576..380b7935a8 100644 --- a/Content.Server/GameObjects/Components/Rotatable/RotatableComponent.cs +++ b/Content.Server/GameObjects/Components/Rotatable/RotatableComponent.cs @@ -4,9 +4,7 @@ using Content.Shared.Interfaces; using Robust.Shared.GameObjects; using Robust.Shared.Localization; using Robust.Shared.Maths; -using Robust.Shared.Prototypes; using Robust.Shared.Physics; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; @@ -26,7 +24,7 @@ namespace Content.Server.GameObjects.Components.Rotatable private void TryRotate(IEntity user, Angle angle) { - if (!RotateWhileAnchored && Owner.TryGetComponent(out IPhysBody physics)) + if (!RotateWhileAnchored && Owner.TryGetComponent(out IPhysBody? physics)) { if (physics.BodyType == BodyType.Static) { @@ -43,7 +41,7 @@ namespace Content.Server.GameObjects.Components.Rotatable { protected override void GetData(IEntity user, RotatableComponent component, VerbData data) { - if (!ActionBlockerSystem.CanInteract(user) || (!component.RotateWhileAnchored && component.Owner.TryGetComponent(out IPhysBody physics) && physics.BodyType == BodyType.Static)) + if (!ActionBlockerSystem.CanInteract(user) || (!component.RotateWhileAnchored && component.Owner.TryGetComponent(out IPhysBody? physics) && physics.BodyType == BodyType.Static)) { data.Visibility = VerbVisibility.Invisible; return; @@ -65,7 +63,7 @@ namespace Content.Server.GameObjects.Components.Rotatable { protected override void GetData(IEntity user, RotatableComponent component, VerbData data) { - if (!ActionBlockerSystem.CanInteract(user) || (!component.RotateWhileAnchored && component.Owner.TryGetComponent(out IPhysBody physics) && physics.BodyType == BodyType.Static)) + if (!ActionBlockerSystem.CanInteract(user) || (!component.RotateWhileAnchored && component.Owner.TryGetComponent(out IPhysBody? physics) && physics.BodyType == BodyType.Static)) { data.Visibility = VerbVisibility.Invisible; return; diff --git a/Content.Server/GameObjects/Components/Sound/EmitSoundOnThrowComponent.cs b/Content.Server/GameObjects/Components/Sound/EmitSoundOnThrowComponent.cs index b3a7ee4644..b943db1ba5 100644 --- a/Content.Server/GameObjects/Components/Sound/EmitSoundOnThrowComponent.cs +++ b/Content.Server/GameObjects/Components/Sound/EmitSoundOnThrowComponent.cs @@ -18,7 +18,7 @@ namespace Content.Server.GameObjects.Components.Sound public override string Name => "EmitSoundOnThrow"; [DataField("sound")] - public string _soundName; + public string? _soundName; [DataField("variation")] public float _pitchVariation; diff --git a/Content.Server/GameObjects/Components/Sound/EmitSoundOnUseComponent.cs b/Content.Server/GameObjects/Components/Sound/EmitSoundOnUseComponent.cs index 8d2fe3e08a..53bd2642c7 100644 --- a/Content.Server/GameObjects/Components/Sound/EmitSoundOnUseComponent.cs +++ b/Content.Server/GameObjects/Components/Sound/EmitSoundOnUseComponent.cs @@ -18,7 +18,7 @@ namespace Content.Server.GameObjects.Components.Sound /// public override string Name => "EmitSoundOnUse"; - [ViewVariables(VVAccess.ReadWrite)] [DataField("sound")] public string _soundName; + [ViewVariables(VVAccess.ReadWrite)] [DataField("sound")] public string? _soundName; [ViewVariables(VVAccess.ReadWrite)] [DataField("variation")] public float _pitchVariation; [ViewVariables(VVAccess.ReadWrite)] [DataField("semitoneVariation")] public int _semitoneVariation; diff --git a/Content.Server/GameObjects/Components/Sound/FootstepModifierComponent.cs b/Content.Server/GameObjects/Components/Sound/FootstepModifierComponent.cs index dcbb37ac16..dc74ea7b51 100644 --- a/Content.Server/GameObjects/Components/Sound/FootstepModifierComponent.cs +++ b/Content.Server/GameObjects/Components/Sound/FootstepModifierComponent.cs @@ -5,7 +5,6 @@ using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Prototypes; using Robust.Shared.Random; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.GameObjects.Components.Sound @@ -23,7 +22,7 @@ namespace Content.Server.GameObjects.Components.Sound public override string Name => "FootstepModifier"; [DataField("footstepSoundCollection")] - public string _soundCollectionName; + public string? _soundCollectionName; public void PlayFootstep() { diff --git a/Content.Server/GameObjects/Components/Sound/LoopingLoopingSoundComponent.cs b/Content.Server/GameObjects/Components/Sound/LoopingLoopingSoundComponent.cs index 2a76ae833a..949b2cc870 100644 --- a/Content.Server/GameObjects/Components/Sound/LoopingLoopingSoundComponent.cs +++ b/Content.Server/GameObjects/Components/Sound/LoopingLoopingSoundComponent.cs @@ -12,7 +12,7 @@ namespace Content.Server.GameObjects.Components.Sound /// Stops all sounds. /// /// User that will be affected. - public void StopAllSounds(INetChannel channel) + public void StopAllSounds(INetChannel? channel) { SendNetworkMessage(new StopAllSoundsMessage(), channel); } @@ -21,16 +21,16 @@ namespace Content.Server.GameObjects.Components.Sound /// Stops a certain scheduled sound from playing. /// /// User that will be affected. - public void StopScheduledSound(string filename, INetChannel channel) + public void StopScheduledSound(string filename, INetChannel? channel) { - SendNetworkMessage(new StopSoundScheduleMessage(){Filename = filename}, channel); + SendNetworkMessage(new StopSoundScheduleMessage() {Filename = filename}, channel); } /// /// Adds an scheduled sound to be played. /// /// User that will be affected. - public void AddScheduledSound(ScheduledSound schedule, INetChannel channel) + public void AddScheduledSound(ScheduledSound schedule, INetChannel? channel) { SendNetworkMessage(new ScheduledSoundMessage() {Schedule = schedule}, channel); } @@ -55,7 +55,7 @@ namespace Content.Server.GameObjects.Components.Sound /// /// The resource path to the OGG Vorbis file to play. /// User that will be affected. - public void Play(string filename, AudioParams? audioParams = null, INetChannel channel = null) + public void Play(string filename, AudioParams? audioParams = null, INetChannel? channel = null) { AddScheduledSound(new ScheduledSound() { diff --git a/Content.Server/GameObjects/Components/StationEvents/RadiationPulseComponent.cs b/Content.Server/GameObjects/Components/StationEvents/RadiationPulseComponent.cs index 6c18dd9a50..acd298d01f 100644 --- a/Content.Server/GameObjects/Components/StationEvents/RadiationPulseComponent.cs +++ b/Content.Server/GameObjects/Components/StationEvents/RadiationPulseComponent.cs @@ -5,8 +5,8 @@ using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Players; using Robust.Shared.Random; -using Robust.Shared.Timing; using Robust.Shared.Serialization.Manager.Attributes; +using Robust.Shared.Timing; namespace Content.Server.GameObjects.Components.StationEvents { @@ -56,7 +56,7 @@ namespace Content.Server.GameObjects.Components.StationEvents } } - [DataField("sound")] public string Sound { get; set; } = "/Audio/Weapons/Guns/Gunshots/laser3.ogg"; + [DataField("sound")] public string? Sound { get; set; } = "/Audio/Weapons/Guns/Gunshots/laser3.ogg"; [DataField("range")] public override float Range diff --git a/Content.Server/GameObjects/Components/Suspicion/SuspicionRoleComponent.cs b/Content.Server/GameObjects/Components/Suspicion/SuspicionRoleComponent.cs index e916ad8b14..eecc0b3819 100644 --- a/Content.Server/GameObjects/Components/Suspicion/SuspicionRoleComponent.cs +++ b/Content.Server/GameObjects/Components/Suspicion/SuspicionRoleComponent.cs @@ -143,10 +143,24 @@ namespace Content.Server.GameObjects.Components.Suspicion public override ComponentState GetComponentState(ICommonSession player) { - return Role == null - ? new SuspicionRoleComponentState(null, null, Array.Empty<(string, EntityUid)>()) - : new SuspicionRoleComponentState(Role?.Name, Role?.Antagonist, - _allies.Select(a => (a.Role!.Mind.CharacterName, a.Owner.Uid)).ToArray()); + if (Role == null) + { + return new SuspicionRoleComponentState(null, null, Array.Empty<(string, EntityUid)>()); + } + + var allies = new List<(string name, EntityUid)>(); + + foreach (var role in _allies) + { + if (role.Role?.Mind.CharacterName == null) + { + continue; + } + + allies.Add((role.Role!.Mind.CharacterName, role.Owner.Uid)); + } + + return new SuspicionRoleComponentState(Role?.Name, Role?.Antagonist, allies.ToArray()); } public override void HandleMessage(ComponentMessage message, IComponent? component) diff --git a/Content.Server/GameObjects/Components/Temperature/TemperatureComponent.cs b/Content.Server/GameObjects/Components/Temperature/TemperatureComponent.cs index c88777e943..03ad5b4060 100644 --- a/Content.Server/GameObjects/Components/Temperature/TemperatureComponent.cs +++ b/Content.Server/GameObjects/Components/Temperature/TemperatureComponent.cs @@ -5,9 +5,8 @@ using Content.Shared.Atmos; using Content.Shared.Damage; using Content.Shared.GameObjects.Components.Damage; using Robust.Shared.GameObjects; -using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Physics; -using Robust.Shared.Serialization; +using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.ViewVariables; namespace Content.Server.GameObjects.Components.Temperature @@ -68,9 +67,9 @@ namespace Content.Server.GameObjects.Components.Temperature damageType = DamageType.Cold; } - if (Owner.TryGetComponent(out ServerAlertsComponent status)) + if (Owner.TryGetComponent(out ServerAlertsComponent? status)) { - switch(CurrentTemperature) + switch (CurrentTemperature) { // Cold strong. case var t when t <= 260: @@ -111,7 +110,7 @@ namespace Content.Server.GameObjects.Components.Temperature if (!damageType.HasValue) return; - if (!Owner.TryGetComponent(out IDamageableComponent component)) return; + if (!Owner.TryGetComponent(out IDamageableComponent? component)) return; component.ChangeDamage(damageType.Value, tempDamage, false); } diff --git a/Content.Server/GameObjects/Components/Timing/UseDelayComponent.cs b/Content.Server/GameObjects/Components/Timing/UseDelayComponent.cs index 1b1c6d301a..7af14c40c3 100644 --- a/Content.Server/GameObjects/Components/Timing/UseDelayComponent.cs +++ b/Content.Server/GameObjects/Components/Timing/UseDelayComponent.cs @@ -3,10 +3,8 @@ using System.Threading; using Content.Shared.GameObjects.Components.Items; using Robust.Shared.GameObjects; using Robust.Shared.IoC; -using Robust.Shared.Prototypes; -using Robust.Shared.Serialization; -using Robust.Shared.Timing; using Robust.Shared.Serialization.Manager.Attributes; +using Robust.Shared.Timing; using Robust.Shared.ViewVariables; namespace Content.Server.GameObjects.Components.Timing @@ -31,7 +29,7 @@ namespace Content.Server.GameObjects.Components.Timing public bool ActiveDelay{ get; private set; } - private CancellationTokenSource cancellationTokenSource; + private CancellationTokenSource? cancellationTokenSource; public void BeginDelay() { @@ -48,7 +46,7 @@ namespace Content.Server.GameObjects.Components.Timing _lastUseTime = IoCManager.Resolve().CurTime; - if (Owner.TryGetComponent(out ItemCooldownComponent cooldown)) + if (Owner.TryGetComponent(out ItemCooldownComponent? cooldown)) { cooldown.CooldownStart = _lastUseTime; cooldown.CooldownEnd = _lastUseTime + TimeSpan.FromSeconds(Delay); @@ -58,10 +56,10 @@ namespace Content.Server.GameObjects.Components.Timing public void Cancel() { - cancellationTokenSource.Cancel(); + cancellationTokenSource?.Cancel(); ActiveDelay = false; - if (Owner.TryGetComponent(out ItemCooldownComponent cooldown)) + if (Owner.TryGetComponent(out ItemCooldownComponent? cooldown)) { cooldown.CooldownEnd = IoCManager.Resolve().CurTime; } @@ -69,7 +67,7 @@ namespace Content.Server.GameObjects.Components.Timing public void Restart() { - cancellationTokenSource.Cancel(); + cancellationTokenSource?.Cancel(); ActiveDelay = false; BeginDelay(); } diff --git a/Content.Server/GameObjects/Components/Weapon/FlashableComponent.cs b/Content.Server/GameObjects/Components/Weapon/FlashableComponent.cs index e919a9350f..5c3eee0d14 100644 --- a/Content.Server/GameObjects/Components/Weapon/FlashableComponent.cs +++ b/Content.Server/GameObjects/Components/Weapon/FlashableComponent.cs @@ -30,11 +30,11 @@ namespace Content.Server.GameObjects.Components.Weapon return new FlashComponentState(_duration, _lastFlash); } - public static void FlashAreaHelper(IEntity source, float range, float duration, string sound = null) + public static void FlashAreaHelper(IEntity source, float range, float duration, string? sound = null) { foreach (var entity in source.EntityManager.GetEntitiesInRange(source.Transform.Coordinates, range)) { - if (!entity.TryGetComponent(out FlashableComponent flashable) || + if (!entity.TryGetComponent(out FlashableComponent? flashable) || !source.InRangeUnobstructed(entity, range, CollisionGroup.Opaque)) continue; flashable.Flash(duration); diff --git a/Content.Server/GameObjects/Components/Weapon/Melee/MeleeWeaponComponent.cs b/Content.Server/GameObjects/Components/Weapon/Melee/MeleeWeaponComponent.cs index d8d0b17a1d..5be0b15709 100644 --- a/Content.Server/GameObjects/Components/Weapon/Melee/MeleeWeaponComponent.cs +++ b/Content.Server/GameObjects/Components/Weapon/Melee/MeleeWeaponComponent.cs @@ -12,11 +12,9 @@ using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Maths; using Robust.Shared.Physics; -using Robust.Shared.Prototypes; using Robust.Shared.Physics.Broadphase; -using Robust.Shared.Serialization; -using Robust.Shared.Timing; using Robust.Shared.Serialization.Manager.Attributes; +using Robust.Shared.Timing; using Robust.Shared.ViewVariables; namespace Content.Server.GameObjects.Components.Weapon.Melee @@ -104,7 +102,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Melee if (!entity.Transform.IsMapTransform || entity == eventArgs.User) continue; - if (entity.TryGetComponent(out IDamageableComponent damageComponent)) + if (entity.TryGetComponent(out IDamageableComponent? damageComponent)) { damageComponent.ChangeDamage(DamageType, Damage, false, Owner); hitEntities.Add(entity); @@ -154,7 +152,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Melee return false; } - if (target.TryGetComponent(out IDamageableComponent damageComponent)) + if (target.TryGetComponent(out IDamageableComponent? damageComponent)) { damageComponent.ChangeDamage(DamageType, Damage, false, Owner); } @@ -231,7 +229,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Melee private void RefreshItemCooldown() { - if (Owner.TryGetComponent(out ItemCooldownComponent cooldown)) + if (Owner.TryGetComponent(out ItemCooldownComponent? cooldown)) { cooldown.CooldownStart = _lastAttackTime; cooldown.CooldownEnd = _cooldownEnd; diff --git a/Content.Server/GameObjects/Components/Weapon/Ranged/Ammunition/AmmoBoxComponent.cs b/Content.Server/GameObjects/Components/Weapon/Ranged/Ammunition/AmmoBoxComponent.cs index a4cf780e68..5f994ecef9 100644 --- a/Content.Server/GameObjects/Components/Weapon/Ranged/Ammunition/AmmoBoxComponent.cs +++ b/Content.Server/GameObjects/Components/Weapon/Ranged/Ammunition/AmmoBoxComponent.cs @@ -42,11 +42,11 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Ammunition public int AmmoLeft => _spawnedAmmo.Count + _unspawnedCount; private Stack _spawnedAmmo = new(); - private Container _ammoContainer; + private Container _ammoContainer = default!; private int _unspawnedCount; [DataField("fillPrototype")] - private string _fillPrototype; + private string? _fillPrototype; public override void Initialize() { @@ -73,7 +73,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Ammunition private void UpdateAppearance() { - if (Owner.TryGetComponent(out AppearanceComponent appearanceComponent)) + if (Owner.TryGetComponent(out AppearanceComponent? appearanceComponent)) { appearanceComponent.SetData(MagazineBarrelVisuals.MagLoaded, true); appearanceComponent.SetData(AmmoVisuals.AmmoCount, AmmoLeft); @@ -81,9 +81,9 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Ammunition } } - public IEntity TakeAmmo() + public IEntity? TakeAmmo() { - if (_spawnedAmmo.TryPop(out IEntity ammo)) + if (_spawnedAmmo.TryPop(out var ammo)) { _ammoContainer.Remove(ammo); return ammo; @@ -100,7 +100,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Ammunition public bool TryInsertAmmo(IEntity user, IEntity entity) { - if (!entity.TryGetComponent(out AmmoComponent ammoComponent)) + if (!entity.TryGetComponent(out AmmoComponent? ammoComponent)) { return false; } @@ -130,12 +130,17 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Ammunition return TryInsertAmmo(eventArgs.User, eventArgs.Using); } - if (eventArgs.Using.TryGetComponent(out RangedMagazineComponent rangedMagazine)) + if (eventArgs.Using.TryGetComponent(out RangedMagazineComponent? rangedMagazine)) { for (var i = 0; i < Math.Max(10, rangedMagazine.ShotsLeft); i++) { var ammo = rangedMagazine.TakeAmmo(); + if (ammo == null) + { + continue; + } + if (!TryInsertAmmo(eventArgs.User, ammo)) { rangedMagazine.TryInsertAmmo(eventArgs.User, ammo); @@ -151,21 +156,29 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Ammunition private bool TryUse(IEntity user) { - if (!user.TryGetComponent(out HandsComponent handsComponent)) + if (!user.TryGetComponent(out HandsComponent? handsComponent)) { return false; } var ammo = TakeAmmo(); - var itemComponent = ammo.GetComponent(); - if (!handsComponent.CanPutInHand(itemComponent)) + if (ammo == null) { - TryInsertAmmo(user, ammo); return false; } - handsComponent.PutInHand(itemComponent); + if (ammo.TryGetComponent(out ItemComponent? item)) + { + if (!handsComponent.CanPutInHand(item)) + { + TryInsertAmmo(user, ammo); + return false; + } + + handsComponent.PutInHand(item); + } + UpdateAppearance(); return true; } diff --git a/Content.Server/GameObjects/Components/Weapon/Ranged/Ammunition/AmmoComponent.cs b/Content.Server/GameObjects/Components/Weapon/Ranged/Ammunition/AmmoComponent.cs index b4855be939..7251396486 100644 --- a/Content.Server/GameObjects/Components/Weapon/Ranged/Ammunition/AmmoComponent.cs +++ b/Content.Server/GameObjects/Components/Weapon/Ranged/Ammunition/AmmoComponent.cs @@ -66,7 +66,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Ammunition public int ProjectilesFired { get; } = 1; [DataField("projectile")] - private string _projectileId; + private string? _projectileId; // How far apart each entity is if multiple are shot [field: DataField("ammoSpread")] @@ -82,7 +82,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Ammunition private string _muzzleFlashSprite = "Objects/Weapons/Guns/Projectiles/bullet_muzzle.png"; [field: DataField("soundCollectionEject")] - public string SoundCollectionEject { get; } = "CasingEject"; + public string? SoundCollectionEject { get; } = "CasingEject"; void ISerializationHooks.AfterDeserialization() { @@ -101,7 +101,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Ammunition } } - public IEntity TakeBullet(EntityCoordinates spawnAt) + public IEntity? TakeBullet(EntityCoordinates spawnAt) { if (_ammoIsProjectile) { @@ -114,7 +114,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Ammunition } _spent = true; - if (Owner.TryGetComponent(out AppearanceComponent appearanceComponent)) + if (Owner.TryGetComponent(out AppearanceComponent? appearanceComponent)) { appearanceComponent.SetData(AmmoVisuals.Spent, true); } diff --git a/Content.Server/GameObjects/Components/Weapon/Ranged/Ammunition/ChemicalAmmoComponent.cs b/Content.Server/GameObjects/Components/Weapon/Ranged/Ammunition/ChemicalAmmoComponent.cs index 996f7042aa..45ea80d83f 100644 --- a/Content.Server/GameObjects/Components/Weapon/Ranged/Ammunition/ChemicalAmmoComponent.cs +++ b/Content.Server/GameObjects/Components/Weapon/Ranged/Ammunition/ChemicalAmmoComponent.cs @@ -1,10 +1,8 @@ -using Content.Server.GameObjects.Components.Chemistry; +using System.Collections.Generic; +using System.Linq; +using Content.Server.GameObjects.Components.Chemistry; using Content.Server.GameObjects.Components.Weapon.Ranged.Barrels; using Robust.Shared.GameObjects; -using Robust.Shared.Serialization; -using System.Collections.Generic; -using System.Linq; -using Robust.Shared.Prototypes; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.GameObjects.Components.Weapon.Ranged.Ammunition @@ -17,7 +15,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Ammunition [DataField("fractionTransfered")] private float _fractionTransfered = 1; - public override void HandleMessage(ComponentMessage message, IComponent component) + public override void HandleMessage(ComponentMessage message, IComponent? component) { base.HandleMessage(message, component); switch (message) diff --git a/Content.Server/GameObjects/Components/Weapon/Ranged/Ammunition/RangedMagazineComponent.cs b/Content.Server/GameObjects/Components/Weapon/Ranged/Ammunition/RangedMagazineComponent.cs index 42cd9a96de..c6b10ece30 100644 --- a/Content.Server/GameObjects/Components/Weapon/Ranged/Ammunition/RangedMagazineComponent.cs +++ b/Content.Server/GameObjects/Components/Weapon/Ranged/Ammunition/RangedMagazineComponent.cs @@ -12,8 +12,6 @@ using Robust.Server.GameObjects; using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.Localization; -using Robust.Shared.Prototypes; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Utility; @@ -25,7 +23,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Ammunition public override string Name => "RangedMagazine"; private readonly Stack _spawnedAmmo = new(); - private Container _ammoContainer; + private Container _ammoContainer = default!; public int ShotsLeft => _spawnedAmmo.Count + _unspawnedCount; public int Capacity => _capacity; @@ -39,11 +37,12 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Ammunition [DataField("caliber")] private BallisticCaliber _caliber = BallisticCaliber.Unspecified; - private AppearanceComponent _appearanceComponent; + private AppearanceComponent? _appearanceComponent; // If there's anything already in the magazine [DataField("fillPrototype")] - private string _fillPrototype; + private string? _fillPrototype; + // By default the magazine won't spawn the entity until needed so we need to keep track of how many left we can spawn // Generally you probablt don't want to use this private int _unspawnedCount; @@ -76,7 +75,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Ammunition } } - if (Owner.TryGetComponent(out AppearanceComponent appearanceComponent)) + if (Owner.TryGetComponent(out AppearanceComponent? appearanceComponent)) { _appearanceComponent = appearanceComponent; } @@ -92,7 +91,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Ammunition public bool TryInsertAmmo(IEntity user, IEntity ammo) { - if (!ammo.TryGetComponent(out AmmoComponent ammoComponent)) + if (!ammo.TryGetComponent(out AmmoComponent? ammoComponent)) { return false; } @@ -115,9 +114,9 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Ammunition return true; } - public IEntity TakeAmmo() + public IEntity? TakeAmmo() { - IEntity ammo = null; + IEntity? ammo = null; // If anything's spawned use that first, otherwise use the fill prototype as a fallback (if we have spawn count left) if (_spawnedAmmo.TryPop(out var entity)) { @@ -141,7 +140,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Ammunition bool IUse.UseEntity(UseEntityEventArgs eventArgs) { - if (!eventArgs.User.TryGetComponent(out HandsComponent handsComponent)) + if (!eventArgs.User.TryGetComponent(out HandsComponent? handsComponent)) { return false; } diff --git a/Content.Server/GameObjects/Components/Weapon/Ranged/Ammunition/SpeedLoaderComponent.cs b/Content.Server/GameObjects/Components/Weapon/Ranged/Ammunition/SpeedLoaderComponent.cs index 61da797f84..365ed98ce0 100644 --- a/Content.Server/GameObjects/Components/Weapon/Ranged/Ammunition/SpeedLoaderComponent.cs +++ b/Content.Server/GameObjects/Components/Weapon/Ranged/Ammunition/SpeedLoaderComponent.cs @@ -10,8 +10,6 @@ using Robust.Server.GameObjects; using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.Localization; -using Robust.Shared.Prototypes; -using Robust.Shared.Serialization; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.GameObjects.Components.Weapon.Ranged.Ammunition @@ -29,14 +27,14 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Ammunition public int Capacity => _capacity; [DataField("capacity")] private int _capacity = 6; - private Container _ammoContainer; + private Container _ammoContainer = default!; private Stack _spawnedAmmo = new(); private int _unspawnedCount; public int AmmoLeft => _spawnedAmmo.Count + _unspawnedCount; [DataField("fillPrototype")] - private string _fillPrototype = default; + private string? _fillPrototype = default; public override void Initialize() { @@ -61,7 +59,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Ammunition private void UpdateAppearance() { - if (Owner.TryGetComponent(out AppearanceComponent appearanceComponent)) + if (Owner.TryGetComponent(out AppearanceComponent? appearanceComponent)) { appearanceComponent?.SetData(MagazineBarrelVisuals.MagLoaded, true); appearanceComponent?.SetData(AmmoVisuals.AmmoCount, AmmoLeft); @@ -71,7 +69,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Ammunition public bool TryInsertAmmo(IEntity user, IEntity entity) { - if (!entity.TryGetComponent(out AmmoComponent ammoComponent)) + if (!entity.TryGetComponent(out AmmoComponent? ammoComponent)) { return false; } @@ -97,7 +95,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Ammunition private bool UseEntity(IEntity user) { - if (!user.TryGetComponent(out HandsComponent handsComponent)) + if (!user.TryGetComponent(out HandsComponent? handsComponent)) { return false; } @@ -122,7 +120,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Ammunition return true; } - private IEntity TakeAmmo() + private IEntity? TakeAmmo() { if (_spawnedAmmo.TryPop(out var entity)) { @@ -147,9 +145,9 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Ammunition } // This area is dirty but not sure of an easier way to do it besides add an interface or somethin - bool changed = false; + var changed = false; - if (eventArgs.Target.TryGetComponent(out RevolverBarrelComponent revolverBarrel)) + if (eventArgs.Target.TryGetComponent(out RevolverBarrelComponent? revolverBarrel)) { for (var i = 0; i < Capacity; i++) { @@ -169,7 +167,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Ammunition TryInsertAmmo(eventArgs.User, ammo); break; } - } else if (eventArgs.Target.TryGetComponent(out BoltActionBarrelComponent boltActionBarrel)) + } else if (eventArgs.Target.TryGetComponent(out BoltActionBarrelComponent? boltActionBarrel)) { for (var i = 0; i < Capacity; i++) { diff --git a/Content.Server/GameObjects/Components/Weapon/Ranged/Barrels/BoltActionBarrelComponent.cs b/Content.Server/GameObjects/Components/Weapon/Ranged/Barrels/BoltActionBarrelComponent.cs index 700b358803..91091abe5d 100644 --- a/Content.Server/GameObjects/Components/Weapon/Ranged/Barrels/BoltActionBarrelComponent.cs +++ b/Content.Server/GameObjects/Components/Weapon/Ranged/Barrels/BoltActionBarrelComponent.cs @@ -45,9 +45,9 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels [DataField("capacity")] private int _capacity = 6; - private ContainerSlot _chamberContainer; - private Stack _spawnedAmmo; - private Container _ammoContainer; + private ContainerSlot _chamberContainer = default!; + private Stack _spawnedAmmo = default!; + private Container _ammoContainer = default!; [ViewVariables] [DataField("caliber")] @@ -55,7 +55,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels [ViewVariables] [DataField("fillPrototype")] - private string _fillPrototype; + private string? _fillPrototype; [ViewVariables] private int _unspawnedCount; @@ -97,7 +97,8 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels [DataField("autoCycle")] private bool _autoCycle; - private AppearanceComponent _appearanceComponent; + private AppearanceComponent? _appearanceComponent; + // Sounds [DataField("soundCycle")] private string _soundCycle = "/Audio/Weapons/Guns/Cock/sf_rifle_cock.ogg"; @@ -129,7 +130,10 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels var chamberedExists = _chamberContainer.ContainedEntity != null; // (Is one chambered?, is the bullet spend) var chamber = (chamberedExists, false); - if (chamberedExists && _chamberContainer.ContainedEntity.TryGetComponent(out var ammo)) + + DebugTools.AssertNotNull(_chamberContainer.ContainedEntity); + + if (chamberedExists && _chamberContainer.ContainedEntity!.TryGetComponent(out var ammo)) { chamber.Item2 = ammo.Spent; } @@ -159,7 +163,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels _chamberContainer = ContainerHelpers.EnsureContainer(Owner, $"{Name}-chamber-container"); - if (Owner.TryGetComponent(out AppearanceComponent appearanceComponent)) + if (Owner.TryGetComponent(out AppearanceComponent? appearanceComponent)) { _appearanceComponent = appearanceComponent; } @@ -176,12 +180,12 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels _appearanceComponent?.SetData(AmmoVisuals.AmmoMax, Capacity); } - public override IEntity PeekAmmo() + public override IEntity? PeekAmmo() { return _chamberContainer.ContainedEntity; } - public override IEntity TakeProjectile(EntityCoordinates spawnAt) + public override IEntity? TakeProjectile(EntityCoordinates spawnAt) { var chamberEntity = _chamberContainer.ContainedEntity; if (_autoCycle) @@ -193,7 +197,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels Dirty(); } - return chamberEntity?.GetComponent().TakeBullet(spawnAt); + return chamberEntity?.GetComponentOrNull()?.TakeBullet(spawnAt); } protected override bool WeaponCanFire() @@ -222,7 +226,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels } else { - if (_soundCycle != null) + if (!string.IsNullOrEmpty(_soundCycle)) { EntitySystem.Get().PlayAtCoords(_soundCycle, Owner.Transform.Coordinates, AudioParams.Default.WithVolume(-2)); } @@ -234,7 +238,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels public bool TryInsertBullet(IEntity user, IEntity ammo) { - if (!ammo.TryGetComponent(out AmmoComponent ammoComponent)) + if (!ammo.TryGetComponent(out AmmoComponent? ammoComponent)) { return false; } diff --git a/Content.Server/GameObjects/Components/Weapon/Ranged/Barrels/PumpBarrelComponent.cs b/Content.Server/GameObjects/Components/Weapon/Ranged/Barrels/PumpBarrelComponent.cs index 37b61444e3..a0805be692 100644 --- a/Content.Server/GameObjects/Components/Weapon/Ranged/Barrels/PumpBarrelComponent.cs +++ b/Content.Server/GameObjects/Components/Weapon/Ranged/Barrels/PumpBarrelComponent.cs @@ -42,9 +42,9 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels public override int Capacity { get; } = DefaultCapacity; // Even a point having a chamber? I guess it makes some of the below code cleaner - private ContainerSlot _chamberContainer; + private ContainerSlot _chamberContainer = default!; private Stack _spawnedAmmo = new (DefaultCapacity-1); - private Container _ammoContainer; + private Container _ammoContainer = default!; [ViewVariables] [DataField("caliber")] @@ -52,14 +52,14 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels [ViewVariables] [DataField("fillPrototype")] - private string _fillPrototype; + private string? _fillPrototype; [ViewVariables] private int _unspawnedCount; [DataField("manualCycle")] private bool _manualCycle = true; - private AppearanceComponent _appearanceComponent; + private AppearanceComponent? _appearanceComponent; // Sounds [DataField("soundCycle")] @@ -83,7 +83,10 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels var chamberedExists = _chamberContainer.ContainedEntity != null; // (Is one chambered?, is the bullet spend) var chamber = (chamberedExists, false); - if (chamberedExists && _chamberContainer.ContainedEntity.TryGetComponent(out var ammo)) + + DebugTools.AssertNotNull(_chamberContainer.ContainedEntity); + + if (chamberedExists && _chamberContainer.ContainedEntity!.TryGetComponent(out var ammo)) { chamber.Item2 = ammo.Spent; } @@ -122,7 +125,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels _unspawnedCount--; } - if (Owner.TryGetComponent(out AppearanceComponent appearanceComponent)) + if (Owner.TryGetComponent(out AppearanceComponent? appearanceComponent)) { _appearanceComponent = appearanceComponent; } @@ -138,12 +141,12 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels _appearanceComponent?.SetData(AmmoVisuals.AmmoMax, Capacity); } - public override IEntity PeekAmmo() + public override IEntity? PeekAmmo() { return _chamberContainer.ContainedEntity; } - public override IEntity TakeProjectile(EntityCoordinates spawnAt) + public override IEntity? TakeProjectile(EntityCoordinates spawnAt) { var chamberEntity = _chamberContainer.ContainedEntity; if (!_manualCycle) @@ -155,7 +158,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels Dirty(); } - return chamberEntity?.GetComponent().TakeBullet(spawnAt); + return chamberEntity?.GetComponentOrNull()?.TakeBullet(spawnAt); } private void Cycle(bool manual = false) @@ -186,7 +189,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels if (manual) { - if (_soundCycle != null) + if (!string.IsNullOrEmpty(_soundCycle)) { EntitySystem.Get().PlayAtCoords(_soundCycle, Owner.Transform.Coordinates, AudioParams.Default.WithVolume(-2)); } @@ -198,7 +201,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels public bool TryInsertBullet(InteractUsingEventArgs eventArgs) { - if (!eventArgs.Using.TryGetComponent(out AmmoComponent ammoComponent)) + if (!eventArgs.Using.TryGetComponent(out AmmoComponent? ammoComponent)) { return false; } diff --git a/Content.Server/GameObjects/Components/Weapon/Ranged/Barrels/RevolverBarrelComponent.cs b/Content.Server/GameObjects/Components/Weapon/Ranged/Barrels/RevolverBarrelComponent.cs index 55b8de876b..116792f51a 100644 --- a/Content.Server/GameObjects/Components/Weapon/Ranged/Barrels/RevolverBarrelComponent.cs +++ b/Content.Server/GameObjects/Components/Weapon/Ranged/Barrels/RevolverBarrelComponent.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Threading.Tasks; using Content.Server.GameObjects.Components.Weapon.Ranged.Ammunition; using Content.Shared.GameObjects; @@ -34,7 +34,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels [DataField("caliber")] private BallisticCaliber _caliber = BallisticCaliber.Unspecified; - private Container _ammoContainer; + private Container _ammoContainer = default!; [ViewVariables] private int _currentSlot; @@ -45,13 +45,13 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels private int _serializedCapacity = 6; [DataField("ammoSlots", readOnly: true)] - private IEntity[] _ammoSlots = Array.Empty(); + private IEntity?[] _ammoSlots = Array.Empty(); public override int ShotsLeft => _ammoContainer.ContainedEntities.Count; [ViewVariables] [DataField("fillPrototype")] - private string _fillPrototype; + private string? _fillPrototype; [ViewVariables] private int _unspawnedCount; @@ -82,7 +82,8 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels for (var i = 0; i < Capacity; i++) { slotsSpent[i] = null; - if (_ammoSlots[i] != null && _ammoSlots[i].TryGetComponent(out AmmoComponent ammo)) + var ammoEntity = _ammoSlots[i]; + if (ammoEntity != null && ammoEntity.TryGetComponent(out AmmoComponent? ammo)) { slotsSpent[i] = ammo.Spent; } @@ -126,7 +127,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels private void UpdateAppearance() { - if (!Owner.TryGetComponent(out AppearanceComponent appearance)) + if (!Owner.TryGetComponent(out AppearanceComponent? appearance)) { return; } @@ -139,7 +140,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels public bool TryInsertBullet(IEntity user, IEntity entity) { - if (!entity.TryGetComponent(out AmmoComponent ammoComponent)) + if (!entity.TryGetComponent(out AmmoComponent? ammoComponent)) { return false; } @@ -191,14 +192,14 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels { var random = _random.Next(_ammoSlots.Length - 1); _currentSlot = random; - if (_soundSpin != null) + if (!string.IsNullOrEmpty(_soundSpin)) { EntitySystem.Get().PlayAtCoords(_soundSpin, Owner.Transform.Coordinates, AudioParams.Default.WithVolume(-2)); } Dirty(); } - public override IEntity PeekAmmo() + public override IEntity? PeekAmmo() { return _ammoSlots[_currentSlot]; } @@ -209,10 +210,10 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels /// /// /// - public override IEntity TakeProjectile(EntityCoordinates spawnAt) + public override IEntity? TakeProjectile(EntityCoordinates spawnAt) { var ammo = _ammoSlots[_currentSlot]; - IEntity bullet = null; + IEntity? bullet = null; if (ammo != null) { var ammoComponent = ammo.GetComponent(); diff --git a/Content.Server/GameObjects/Components/Weapon/Ranged/Barrels/ServerBatteryBarrelComponent.cs b/Content.Server/GameObjects/Components/Weapon/Ranged/Barrels/ServerBatteryBarrelComponent.cs index 9f4630c517..8399f0ee12 100644 --- a/Content.Server/GameObjects/Components/Weapon/Ranged/Barrels/ServerBatteryBarrelComponent.cs +++ b/Content.Server/GameObjects/Components/Weapon/Ranged/Barrels/ServerBatteryBarrelComponent.cs @@ -36,14 +36,14 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels [ViewVariables] private int _baseFireCost = 300; // What gets fired [DataField("ammoPrototype")] - [ViewVariables] private string _ammoPrototype; + [ViewVariables] private string? _ammoPrototype; - [ViewVariables] public IEntity PowerCellEntity => _powerCellContainer.ContainedEntity; - public BatteryComponent PowerCell => _powerCellContainer.ContainedEntity?.GetComponent(); - private ContainerSlot _powerCellContainer; - private ContainerSlot _ammoContainer; + [ViewVariables] public IEntity? PowerCellEntity => _powerCellContainer.ContainedEntity; + public BatteryComponent? PowerCell => _powerCellContainer.ContainedEntity?.GetComponentOrNull(); + private ContainerSlot _powerCellContainer = default!; + private ContainerSlot _ammoContainer = default!; [DataField("powerCellPrototype")] - private string _powerCellPrototype = default; + private string? _powerCellPrototype = default; [DataField("powerCellRemovable")] [ViewVariables] private bool _powerCellRemovable = default; @@ -77,13 +77,13 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels } } - private AppearanceComponent _appearanceComponent; + private AppearanceComponent? _appearanceComponent; // Sounds [DataField("soundPowerCellInsert")] - private string _soundPowerCellInsert = default; + private string? _soundPowerCellInsert = default; [DataField("soundPowerCellEject")] - private string _soundPowerCellEject = default; + private string? _soundPowerCellEject = default; public override ComponentState GetComponentState(ICommonSession player) { @@ -109,7 +109,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels _ammoContainer = ContainerHelpers.EnsureContainer(Owner, $"{Name}-ammo-container"); } - if (Owner.TryGetComponent(out AppearanceComponent appearanceComponent)) + if (Owner.TryGetComponent(out AppearanceComponent? appearanceComponent)) { _appearanceComponent = appearanceComponent; } @@ -143,7 +143,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels return ammo; } - public override IEntity TakeProjectile(EntityCoordinates spawnAt) + public override IEntity? TakeProjectile(EntityCoordinates spawnAt) { var powerCellEntity = _powerCellContainer.ContainedEntity; @@ -180,7 +180,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels entity = Owner.EntityManager.SpawnEntity(_ammoPrototype, spawnAt); } - if (entity.TryGetComponent(out ProjectileComponent projectileComponent)) + if (entity.TryGetComponent(out ProjectileComponent? projectileComponent)) { if (energyRatio < 1.0) { @@ -192,7 +192,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels projectileComponent.Damages = newDamages; } - } else if (entity.TryGetComponent(out HitscanComponent hitscanComponent)) + } else if (entity.TryGetComponent(out HitscanComponent? hitscanComponent)) { hitscanComponent.Damage *= energyRatio; hitscanComponent.ColorModifier = energyRatio; @@ -253,7 +253,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels return false; } - if (!user.TryGetComponent(out HandsComponent hands)) + if (!user.TryGetComponent(out HandsComponent? hands)) { return false; } diff --git a/Content.Server/GameObjects/Components/Weapon/Ranged/Barrels/ServerMagazineBarrelComponent.cs b/Content.Server/GameObjects/Components/Weapon/Ranged/Barrels/ServerMagazineBarrelComponent.cs index 9d102091c5..ae618e3ab7 100644 --- a/Content.Server/GameObjects/Components/Weapon/Ranged/Barrels/ServerMagazineBarrelComponent.cs +++ b/Content.Server/GameObjects/Components/Weapon/Ranged/Barrels/ServerMagazineBarrelComponent.cs @@ -32,9 +32,9 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels public override uint? NetID => ContentNetIDs.MAGAZINE_BARREL; [ViewVariables] - private ContainerSlot _chamberContainer; + private ContainerSlot _chamberContainer = default!; [ViewVariables] public bool HasMagazine => _magazineContainer.ContainedEntity != null; - private ContainerSlot _magazineContainer; + private ContainerSlot _magazineContainer = default!; [ViewVariables] public MagazineType MagazineTypes => _magazineTypes; [DataField("magazineTypes")] @@ -80,7 +80,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels } [DataField("magFillPrototype")] - private string _magFillPrototype; + private string? _magFillPrototype; public bool BoltOpen { @@ -125,19 +125,19 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels [DataField("magNeedsOpenBolt")] private bool _magNeedsOpenBolt = default; - private AppearanceComponent _appearanceComponent; + private AppearanceComponent? _appearanceComponent; // Sounds [DataField("soundBoltOpen")] - private string _soundBoltOpen = default; + private string? _soundBoltOpen = default; [DataField("soundBoltClosed")] - private string _soundBoltClosed = default; + private string? _soundBoltClosed = default; [DataField("soundRack")] - private string _soundRack = default; + private string? _soundRack = default; [DataField("soundMagInsert")] - private string _soundMagInsert = default; + private string? _soundMagInsert = default; [DataField("soundMagEject")] - private string _soundMagEject = default; + private string? _soundMagEject = default; [DataField("soundAutoEject")] private string _soundAutoEject = "/Audio/Weapons/Guns/EmptyAlarm/smg_empty_alarm.ogg"; @@ -160,7 +160,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels { (int, int)? count = null; var magazine = _magazineContainer.ContainedEntity; - if (magazine != null && magazine.TryGetComponent(out RangedMagazineComponent rangedMagazineComponent)) + if (magazine != null && magazine.TryGetComponent(out RangedMagazineComponent? rangedMagazineComponent)) { count = (rangedMagazineComponent.ShotsLeft, rangedMagazineComponent.Capacity); } @@ -176,7 +176,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels { base.Initialize(); - if (Owner.TryGetComponent(out AppearanceComponent appearanceComponent)) + if (Owner.TryGetComponent(out AppearanceComponent? appearanceComponent)) { _appearanceComponent = appearanceComponent; } @@ -197,12 +197,12 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels UpdateAppearance(); } - public override IEntity PeekAmmo() + public override IEntity? PeekAmmo() { return BoltOpen ? null : _chamberContainer.ContainedEntity; } - public override IEntity TakeProjectile(EntityCoordinates spawnAt) + public override IEntity? TakeProjectile(EntityCoordinates spawnAt) { if (BoltOpen) { @@ -359,7 +359,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels EntitySystem.Get().PlayAtCoords(_soundMagEject, Owner.Transform.Coordinates, AudioParams.Default.WithVolume(-2)); } - if (user.TryGetComponent(out HandsComponent handsComponent)) + if (user.TryGetComponent(out HandsComponent? handsComponent)) { handsComponent.PutInHandOrDrop(mag.GetComponent()); } @@ -371,7 +371,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels public override async Task InteractUsing(InteractUsingEventArgs eventArgs) { // Insert magazine - if (eventArgs.Using.TryGetComponent(out RangedMagazineComponent magazineComponent)) + if (eventArgs.Using.TryGetComponent(out RangedMagazineComponent? magazineComponent)) { if ((MagazineTypes & magazineComponent.MagazineType) == 0) { @@ -409,7 +409,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels } // Insert 1 ammo - if (eventArgs.Using.TryGetComponent(out AmmoComponent ammoComponent)) + if (eventArgs.Using.TryGetComponent(out AmmoComponent? ammoComponent)) { if (!BoltOpen) { diff --git a/Content.Server/GameObjects/Components/Weapon/Ranged/Barrels/ServerRangedBarrelComponent.cs b/Content.Server/GameObjects/Components/Weapon/Ranged/Barrels/ServerRangedBarrelComponent.cs index eb1a0fbc10..1b8e9b5d4f 100644 --- a/Content.Server/GameObjects/Components/Weapon/Ranged/Barrels/ServerRangedBarrelComponent.cs +++ b/Content.Server/GameObjects/Components/Weapon/Ranged/Barrels/ServerRangedBarrelComponent.cs @@ -10,9 +10,6 @@ using Content.Shared.GameObjects.Components.Damage; using Content.Shared.GameObjects.Components.Weapons.Ranged; using Content.Shared.GameObjects.EntitySystems; using Content.Shared.Interfaces.GameObjects.Components; -using Content.Shared.Physics; -using Content.Shared.Utility; -using Robust.Server.GameObjects; using Robust.Shared.Audio; using Robust.Shared.GameObjects; using Robust.Shared.IoC; @@ -21,8 +18,8 @@ using Robust.Shared.Log; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Physics; -using Robust.Shared.Player; using Robust.Shared.Physics.Broadphase; +using Robust.Shared.Player; using Robust.Shared.Prototypes; using Robust.Shared.Random; using Robust.Shared.Serialization; @@ -59,8 +56,8 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels // _lastFire is when we actually fired (so if we hold the button then recoil doesn't build up if we're not firing) private TimeSpan _lastFire; - public abstract IEntity PeekAmmo(); - public abstract IEntity TakeProjectile(EntityCoordinates spawnAt); + public abstract IEntity? PeekAmmo(); + public abstract IEntity? TakeProjectile(EntityCoordinates spawnAt); // Recoil / spray control [DataField("minAngle")] @@ -100,7 +97,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels // Sounds [field: DataField("soundGunshot")] - public string SoundGunshot { get; set; } + public string? SoundGunshot { get; set; } [field: DataField("soundEmpty")] public string SoundEmpty { get; } = "/Audio/Weapons/Guns/Empty/empty.ogg"; @@ -149,7 +146,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels public override void OnRemove() { base.OnRemove(); - if (Owner.TryGetComponent(out ServerRangedWeaponComponent rangedWeaponComponent)) + if (Owner.TryGetComponent(out ServerRangedWeaponComponent? rangedWeaponComponent)) { rangedWeaponComponent.Barrel = null; rangedWeaponComponent.FireHandler -= Fire; @@ -218,21 +215,21 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels var direction = (targetPos - shooter.Transform.WorldPosition).ToAngle(); var angle = GetRecoilAngle(direction); // This should really be client-side but for now we'll just leave it here - if (shooter.TryGetComponent(out CameraRecoilComponent recoilComponent)) + if (shooter.TryGetComponent(out CameraRecoilComponent? recoilComponent)) { recoilComponent.Kick(-angle.ToVec() * 0.15f); } // This section probably needs tweaking so there can be caseless hitscan etc. - if (projectile.TryGetComponent(out HitscanComponent hitscan)) + if (projectile.TryGetComponent(out HitscanComponent? hitscan)) { FireHitscan(shooter, hitscan, angle); } - else if (projectile.HasComponent()) + else if (projectile.HasComponent() && + ammo != null && + ammo.TryGetComponent(out AmmoComponent? ammoComponent)) { - var ammoComponent = ammo.GetComponent(); - FireProjectiles(shooter, projectile, ammoComponent.ProjectilesFired, ammoComponent.EvenSpreadAngle, angle, ammoComponent.Velocity, ammo); if (CanMuzzleFlash) @@ -251,10 +248,12 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels throw new InvalidOperationException(); } - SoundSystem.Play(Filter.Broadcast(), SoundGunshot, Owner.Transform.Coordinates); - _lastFire = _gameTiming.CurTime; + if (!string.IsNullOrEmpty(SoundGunshot)) + { + SoundSystem.Play(Filter.Broadcast(), SoundGunshot, Owner.Transform.Coordinates); + } - return; + _lastFire = _gameTiming.CurTime; } /// @@ -269,19 +268,13 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels public static void EjectCasing( IEntity entity, bool playSound = true, - IRobustRandom robustRandom = null, - IPrototypeManager prototypeManager = null, - Direction[] ejectDirections = null) + IRobustRandom? robustRandom = null, + IPrototypeManager? prototypeManager = null, + Direction[]? ejectDirections = null) { - if (robustRandom == null) - { - robustRandom = IoCManager.Resolve(); - } - - if (ejectDirections == null) - { - ejectDirections = new[] {Direction.East, Direction.North, Direction.NorthWest, Direction.South, Direction.SouthEast, Direction.West}; - } + robustRandom ??= IoCManager.Resolve(); + ejectDirections ??= new[] + {Direction.East, Direction.North, Direction.NorthWest, Direction.South, Direction.SouthEast, Direction.West}; const float ejectOffset = 1.8f; var ammo = entity.GetComponent(); @@ -294,10 +287,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels return; } - if (prototypeManager == null) - { - prototypeManager = IoCManager.Resolve(); - } + prototypeManager ??= IoCManager.Resolve(); var soundCollection = prototypeManager.Index(ammo.SoundCollectionEject); var randomFile = robustRandom.Pick(soundCollection.PickFiles); @@ -334,7 +324,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels /// private void FireProjectiles(IEntity shooter, IEntity baseProjectile, int count, float evenSpreadAngle, Angle angle, float velocity, IEntity ammo) { - List sprayAngleChange = null; + List? sprayAngleChange = null; if (count > 1) { evenSpreadAngle *= SpreadRatio; @@ -353,7 +343,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels else { projectile = - Owner.EntityManager.SpawnEntity(baseProjectile.Prototype.ID, baseProjectile.Transform.Coordinates); + Owner.EntityManager.SpawnEntity(baseProjectile.Prototype?.ID, baseProjectile.Transform.Coordinates); } firedProjectiles.Add(projectile); @@ -414,7 +404,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged.Barrels var distance = result.Distance; hitscan.FireEffects(shooter, distance, angle, result.HitEntity); - if (!result.HitEntity.TryGetComponent(out IDamageableComponent damageable)) + if (!result.HitEntity.TryGetComponent(out IDamageableComponent? damageable)) return; damageable.ChangeDamage(hitscan.DamageType, (int)Math.Round(hitscan.Damage, MidpointRounding.AwayFromZero), false, Owner); diff --git a/Content.Server/GameObjects/Components/Weapon/Ranged/ServerRangedWeaponComponent.cs b/Content.Server/GameObjects/Components/Weapon/Ranged/ServerRangedWeaponComponent.cs index 296c586ede..70011581fa 100644 --- a/Content.Server/GameObjects/Components/Weapon/Ranged/ServerRangedWeaponComponent.cs +++ b/Content.Server/GameObjects/Components/Weapon/Ranged/ServerRangedWeaponComponent.cs @@ -18,8 +18,8 @@ using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Network; using Robust.Shared.Players; -using Robust.Shared.Timing; using Robust.Shared.Serialization.Manager.Attributes; +using Robust.Shared.Timing; using Robust.Shared.ViewVariables; namespace Content.Server.GameObjects.Components.Weapon.Ranged @@ -40,11 +40,11 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged [DataField("clumsyExplodeChance")] public float ClumsyExplodeChance { get; set; } = 0.5f; - public Func WeaponCanFireHandler; - public Func UserCanFireHandler; - public Action FireHandler; + public Func? WeaponCanFireHandler; + public Func? UserCanFireHandler; + public Action? FireHandler; - public ServerRangedBarrelComponent Barrel + public ServerRangedBarrelComponent? Barrel { get => _barrel; set @@ -59,7 +59,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged Dirty(); } } - private ServerRangedBarrelComponent _barrel; + private ServerRangedBarrelComponent? _barrel; private FireRateSelector FireRateSelector => _barrel?.FireRateSelector ?? FireRateSelector.Safety; @@ -74,7 +74,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged } /// - public override void HandleNetworkMessage(ComponentMessage message, INetChannel channel, ICommonSession session = null) + public override void HandleNetworkMessage(ComponentMessage message, INetChannel channel, ICommonSession? session = null) { base.HandleNetworkMessage(message, channel, session); @@ -126,12 +126,12 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged /// Target position on the map to shoot at. private void TryFire(IEntity user, Vector2 targetPos) { - if (!user.TryGetComponent(out HandsComponent hands) || hands.GetActiveHand?.Owner != Owner) + if (!user.TryGetComponent(out HandsComponent? hands) || hands.GetActiveHand?.Owner != Owner) { return; } - if(!user.TryGetComponent(out CombatModeComponent combat) || !combat.IsInCombatMode) { + if(!user.TryGetComponent(out CombatModeComponent? combat) || !combat.IsInCombatMode) { return; } @@ -142,7 +142,7 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged var curTime = _gameTiming.CurTime; var span = curTime - _lastFireTime; - if (span.TotalSeconds < 1 / _barrel.FireRate) + if (span.TotalSeconds < 1 / _barrel?.FireRate) { return; } @@ -158,13 +158,13 @@ namespace Content.Server.GameObjects.Components.Weapon.Ranged soundSystem.PlayAtCoords("/Audio/Weapons/Guns/Gunshots/bang.ogg", Owner.Transform.Coordinates, AudioParams.Default, 5); - if (user.TryGetComponent(out IDamageableComponent health)) + if (user.TryGetComponent(out IDamageableComponent? health)) { health.ChangeDamage(DamageType.Blunt, 10, false, user); health.ChangeDamage(DamageType.Heat, 5, false, user); } - if (user.TryGetComponent(out StunnableComponent stun)) + if (user.TryGetComponent(out StunnableComponent? stun)) { stun.Paralyze(3f); } diff --git a/Content.Server/GameObjects/EntitySystems/AI/LoadBalancer/AiActionRequest.cs b/Content.Server/GameObjects/EntitySystems/AI/LoadBalancer/AiActionRequest.cs index cb9b641fea..9c741edd8b 100644 --- a/Content.Server/GameObjects/EntitySystems/AI/LoadBalancer/AiActionRequest.cs +++ b/Content.Server/GameObjects/EntitySystems/AI/LoadBalancer/AiActionRequest.cs @@ -8,8 +8,8 @@ namespace Content.Server.GameObjects.EntitySystems.AI.LoadBalancer public class AiActionRequest { public EntityUid EntityUid { get; } - public Blackboard Context { get; } - public IEnumerable Actions { get; } + public Blackboard? Context { get; } + public IEnumerable? Actions { get; } public AiActionRequest(EntityUid uid, Blackboard context, IEnumerable actions) { diff --git a/Content.Server/GameObjects/EntitySystems/AI/LoadBalancer/AiActionRequestJob.cs b/Content.Server/GameObjects/EntitySystems/AI/LoadBalancer/AiActionRequestJob.cs index fda623d6e6..3208d930cf 100644 --- a/Content.Server/GameObjects/EntitySystems/AI/LoadBalancer/AiActionRequestJob.cs +++ b/Content.Server/GameObjects/EntitySystems/AI/LoadBalancer/AiActionRequestJob.cs @@ -9,13 +9,14 @@ using Content.Server.AI.WorldState.States.Utility; using Content.Server.GameObjects.Components.Movement; using Content.Server.GameObjects.EntitySystems.JobQueues; using Content.Shared.AI; +using Robust.Shared.Utility; namespace Content.Server.GameObjects.EntitySystems.AI.LoadBalancer { public class AiActionRequestJob : Job { #if DEBUG - public static event Action FoundAction; + public static event Action? FoundAction; #endif private readonly AiActionRequest _request; @@ -27,7 +28,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.LoadBalancer _request = request; } - protected override async Task Process() + protected override async Task Process() { if (_request.Context == null) { @@ -55,7 +56,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.LoadBalancer // Use last action as the basis for the cutoff var cutoff = _request.Context.GetState().GetValue(); - UtilityAction foundAction = null; + UtilityAction? foundAction = null; // To see what I was trying to do watch these 2 videos about Infinite Axis Utility System (IAUS): // Architecture Tricks: Managing Behaviors in Time, Space, and Depth @@ -83,7 +84,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.LoadBalancer { break; } - + foreach (var expanded in expandableUtilityAction.GetActions(_request.Context)) { actions.Push(expanded); @@ -116,8 +117,12 @@ namespace Content.Server.GameObjects.EntitySystems.AI.LoadBalancer #if DEBUG if (foundAction != null) { + var selfState = _request.Context.GetState().GetValue(); + + DebugTools.AssertNotNull(selfState); + FoundAction?.Invoke(new SharedAiDebug.UtilityAiDebugMessage( - _request.Context.GetState().GetValue().Uid, + selfState!.Uid, DebugTime, cutoff, foundAction.GetType().Name, diff --git a/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/Accessible/AiReachableSystem.cs b/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/Accessible/AiReachableSystem.cs index 63a04778b8..99885ff2ed 100644 --- a/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/Accessible/AiReachableSystem.cs +++ b/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/Accessible/AiReachableSystem.cs @@ -12,7 +12,6 @@ using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Physics; -using Robust.Shared.Players; using Robust.Shared.Timing; using Robust.Shared.Utility; @@ -40,7 +39,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding.Accessible [Dependency] private readonly IMapManager _mapManager = default!; [Dependency] private readonly IGameTiming _gameTiming = default!; - private PathfindingSystem _pathfindingSystem; + private PathfindingSystem _pathfindingSystem = default!; /// /// Queued region updates @@ -180,7 +179,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding.Accessible var targetNode = _pathfindingSystem.GetNode(targetTile); var collisionMask = 0; - if (entity.TryGetComponent(out IPhysBody physics)) + if (entity.TryGetComponent(out IPhysBody? physics)) { collisionMask = physics.CollisionMask; } @@ -229,7 +228,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding.Accessible var reachableArgs = ReachableArgs.GetArgs(entity); var reachableRegions = GetReachableRegions(reachableArgs, targetRegion); - return reachableRegions.Contains(entityRegion); + return entityRegion != null && reachableRegions.Contains(entityRegion); } /// @@ -238,7 +237,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding.Accessible /// /// /// - public HashSet GetReachableRegions(ReachableArgs reachableArgs, PathfindingRegion region) + public HashSet GetReachableRegions(ReachableArgs reachableArgs, PathfindingRegion? region) { // if we're on a node that's not tracked at all atm then region will be null if (region == null) @@ -276,7 +275,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding.Accessible /// private ReachableArgs GetCachedArgs(ReachableArgs accessibleArgs) { - ReachableArgs foundArgs = null; + ReachableArgs? foundArgs = null; foreach (var (cachedAccessible, _) in _cachedAccessible) { @@ -422,7 +421,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding.Accessible /// /// /// - public PathfindingRegion GetRegion(IEntity entity) + public PathfindingRegion? GetRegion(IEntity entity) { var entityTile = _mapManager.GetGrid(entity.Transform.GridID).GetTileRef(entity.Transform.Coordinates); var entityNode = _pathfindingSystem.GetNode(entityTile); @@ -434,7 +433,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding.Accessible /// /// /// - public PathfindingRegion GetRegion(PathfindingNode node) + public PathfindingRegion? GetRegion(PathfindingNode node) { // Not sure on the best way to optimise this // On the one hand, just storing each node's region is faster buuutttt muh memory @@ -469,7 +468,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding.Accessible /// This is already calculated in advance so may as well re-use it /// This is already calculated in advance so may as well re-use it /// - private PathfindingRegion CalculateNode( + private PathfindingRegion? CalculateNode( PathfindingNode node, Dictionary existingRegions, HashSet chunkRegions, @@ -499,8 +498,8 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding.Accessible // Otherwise, make our own region. var leftNeighbor = x > 0 ? parentChunk.Nodes[x - 1, y] : null; var bottomNeighbor = y > 0 ? parentChunk.Nodes[x, y - 1] : null; - PathfindingRegion leftRegion; - PathfindingRegion bottomRegion; + PathfindingRegion? leftRegion; + PathfindingRegion? bottomRegion; // We'll check if our left or down neighbors are already in a region and join them @@ -562,7 +561,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding.Accessible /// /// /// - private void MergeInto(PathfindingRegion source, PathfindingRegion target, Dictionary existingRegions = null) + private void MergeInto(PathfindingRegion source, PathfindingRegion target, Dictionary? existingRegions = null) { DebugTools.AssertNotNull(source); DebugTools.AssertNotNull(target); diff --git a/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/Accessible/PathfindingRegion.cs b/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/Accessible/PathfindingRegion.cs index 9b8e5cbee8..e78f680cbc 100644 --- a/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/Accessible/PathfindingRegion.cs +++ b/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/Accessible/PathfindingRegion.cs @@ -123,7 +123,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding.Accessible } // HashSet wasn't working correctly so uhh we got this. - public bool Equals(PathfindingRegion other) + public bool Equals(PathfindingRegion? other) { if (other == null) return false; if (ReferenceEquals(this, other)) return true; diff --git a/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/Pathfinders/AStarPathfindingJob.cs b/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/Pathfinders/AStarPathfindingJob.cs index 80ba5e19e3..e6e0d6e431 100644 --- a/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/Pathfinders/AStarPathfindingJob.cs +++ b/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/Pathfinders/AStarPathfindingJob.cs @@ -12,11 +12,11 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding.Pathfinders public class AStarPathfindingJob : Job> { #if DEBUG - public static event Action DebugRoute; + public static event Action? DebugRoute; #endif - private readonly PathfindingNode _startNode; - private PathfindingNode _endNode; + private readonly PathfindingNode? _startNode; + private PathfindingNode? _endNode; private readonly PathfindingArgs _pathfindingArgs; public AStarPathfindingJob( @@ -31,7 +31,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding.Pathfinders _pathfindingArgs = pathfindingArgs; } - protected override async Task> Process() + protected override async Task?> Process() { if (_startNode == null || _endNode == null || @@ -50,7 +50,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding.Pathfinders var costSoFar = new Dictionary(); var cameFrom = new Dictionary(); - PathfindingNode currentNode = null; + PathfindingNode? currentNode = null; frontier.Add((0.0f, _startNode)); costSoFar[_startNode] = 0.0f; var routeFound = false; @@ -121,7 +121,9 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding.Pathfinders return null; } - var route = PathfindingHelpers.ReconstructPath(cameFrom, currentNode); + DebugTools.AssertNotNull(currentNode); + + var route = PathfindingHelpers.ReconstructPath(cameFrom, currentNode!); if (route.Count == 1) { diff --git a/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/Pathfinders/JpsPathfindingJob.cs b/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/Pathfinders/JpsPathfindingJob.cs index 728004a829..d70f06436f 100644 --- a/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/Pathfinders/JpsPathfindingJob.cs +++ b/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/Pathfinders/JpsPathfindingJob.cs @@ -16,11 +16,11 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding.Pathfinders // Some of this is probably fugly due to other structural changes in pathfinding so it could do with optimisation // Realistically it's probably not getting used given it doesn't support tile costs which can be very useful #if DEBUG - public static event Action DebugRoute; + public static event Action? DebugRoute; #endif - private readonly PathfindingNode _startNode; - private PathfindingNode _endNode; + private readonly PathfindingNode? _startNode; + private PathfindingNode? _endNode; private readonly PathfindingArgs _pathfindingArgs; public JpsPathfindingJob(double maxTime, @@ -34,7 +34,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding.Pathfinders _pathfindingArgs = pathfindingArgs; } - protected override async Task> Process() + protected override async Task?> Process() { // VERY similar to A*; main difference is with the neighbor tiles you look for jump nodes instead if (_startNode == null || @@ -58,7 +58,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding.Pathfinders var jumpNodes = new HashSet(); #endif - PathfindingNode currentNode = null; + PathfindingNode? currentNode = null; openTiles.Add((0, _startNode)); gScores[_startNode] = 0.0f; var routeFound = false; @@ -123,7 +123,10 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding.Pathfinders return null; } - var route = PathfindingHelpers.ReconstructJumpPath(cameFrom, currentNode); + DebugTools.AssertNotNull(currentNode); + + var route = PathfindingHelpers.ReconstructJumpPath(cameFrom, currentNode!); + if (route.Count == 1) { return null; @@ -153,14 +156,14 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding.Pathfinders return route; } - private PathfindingNode GetJumpPoint(PathfindingNode currentNode, Direction direction, PathfindingNode endNode) + private PathfindingNode? GetJumpPoint(PathfindingNode currentNode, Direction direction, PathfindingNode endNode) { var count = 0; while (count < 1000) { count++; - PathfindingNode nextNode = null; + PathfindingNode? nextNode = null; foreach (var node in currentNode.GetNeighbors()) { if (PathfindingHelpers.RelativeDirection(node, currentNode) == direction) @@ -285,10 +288,10 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding.Pathfinders // I tried just casting direction ints and offsets to make it smaller but brain no worky. // From NorthEast we check (Closed / Open) S - SE, W - NW - PathfindingNode openNeighborOne = null; - PathfindingNode closedNeighborOne = null; - PathfindingNode openNeighborTwo = null; - PathfindingNode closedNeighborTwo = null; + PathfindingNode? openNeighborOne = null; + PathfindingNode? closedNeighborOne = null; + PathfindingNode? openNeighborTwo = null; + PathfindingNode? closedNeighborTwo = null; switch (direction) { @@ -400,10 +403,10 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding.Pathfinders /// private bool IsCardinalJumpPoint(Direction direction, PathfindingNode currentNode) { - PathfindingNode openNeighborOne = null; - PathfindingNode closedNeighborOne = null; - PathfindingNode openNeighborTwo = null; - PathfindingNode closedNeighborTwo = null; + PathfindingNode? openNeighborOne = null; + PathfindingNode? closedNeighborOne = null; + PathfindingNode? openNeighborTwo = null; + PathfindingNode? closedNeighborTwo = null; switch (direction) { diff --git a/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/PathfindingChunk.cs b/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/PathfindingChunk.cs index ca49d26a04..69032cbee3 100644 --- a/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/PathfindingChunk.cs +++ b/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/PathfindingChunk.cs @@ -177,12 +177,9 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding return _nodes[chunkX, chunkY]; } - private void CreateNode(TileRef tile, PathfindingChunk parent = null) + private void CreateNode(TileRef tile, PathfindingChunk? parent = null) { - if (parent == null) - { - parent = this; - } + parent ??= this; var node = new PathfindingNode(parent, tile); var offsetX = tile.X - Indices.X; diff --git a/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/PathfindingHelpers.cs b/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/PathfindingHelpers.cs index af3b19c996..bbf3d7e211 100644 --- a/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/PathfindingHelpers.cs +++ b/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/PathfindingHelpers.cs @@ -36,10 +36,10 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding // Given there's different collision layers stored for each node in the graph it's probably not worth it to cache this // Also this will help with corner-cutting - PathfindingNode northNeighbor = null; - PathfindingNode southNeighbor = null; - PathfindingNode eastNeighbor = null; - PathfindingNode westNeighbor = null; + PathfindingNode? northNeighbor = null; + PathfindingNode? southNeighbor = null; + PathfindingNode? eastNeighbor = null; + PathfindingNode? westNeighbor = null; foreach (var neighbor in currentNode.GetNeighbors()) { if (neighbor.TileRef.X == currentNode.TileRef.X && diff --git a/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/PathfindingNode.cs b/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/PathfindingNode.cs index 9b80c2da6b..918dec28be 100644 --- a/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/PathfindingNode.cs +++ b/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/PathfindingNode.cs @@ -58,7 +58,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding /// public IEnumerable GetNeighbors() { - List neighborChunks = null; + List? neighborChunks = null; if (ParentChunk.OnEdge(this)) { neighborChunks = ParentChunk.RelevantChunks(this).ToList(); @@ -80,7 +80,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding { DebugTools.AssertNotNull(neighborChunks); // Get the relevant chunk and then get the node on it - foreach (var neighbor in neighborChunks) + foreach (var neighbor in neighborChunks!) { // A lot of edge transitions are going to have a single neighboring chunk // (given > 1 only affects corners) @@ -96,7 +96,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding } } - public PathfindingNode GetNeighbor(Direction direction) + public PathfindingNode? GetNeighbor(Direction direction) { var chunkXOffset = TileRef.X - ParentChunk.Indices.X; var chunkYOffset = TileRef.Y - ParentChunk.Indices.Y; @@ -266,7 +266,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding // TODO: Check for powered I think (also need an event for when it's depowered // AccessReader calls this whenever opening / closing but it can seem to get called multiple times // Which may or may not be intended? - if (entity.TryGetComponent(out AccessReader accessReader) && !_accessReaders.ContainsKey(entity)) + if (entity.TryGetComponent(out AccessReader? accessReader) && !_accessReaders.ContainsKey(entity)) { _accessReaders.Add(entity, accessReader); ParentChunk.Dirty(); diff --git a/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/PathfindingSystem.cs b/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/PathfindingSystem.cs index 1077ed4fe6..23123d46af 100644 --- a/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/PathfindingSystem.cs +++ b/Content.Server/GameObjects/EntitySystems/AI/Pathfinding/PathfindingSystem.cs @@ -237,7 +237,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding } } - private void QueueGridChange(object sender, GridChangedEventArgs eventArgs) + private void QueueGridChange(object? sender, GridChangedEventArgs eventArgs) { foreach (var (position, _) in eventArgs.Modified) { @@ -245,7 +245,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding } } - private void QueueTileChange(object sender, TileChangedEventArgs eventArgs) + private void QueueTileChange(object? sender, TileChangedEventArgs eventArgs) { _tileUpdateQueue.Enqueue(eventArgs.NewTile); } @@ -264,7 +264,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding { if (entity.Deleted || _lastKnownPositions.ContainsKey(entity) || - !entity.TryGetComponent(out IPhysBody physics) || + !entity.TryGetComponent(out IPhysBody? physics) || !PathfindingNode.IsRelevant(entity, physics)) { return; @@ -303,7 +303,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding { // If we've moved to space or the likes then remove us. if (moveEvent.Sender.Deleted || - !moveEvent.Sender.TryGetComponent(out IPhysBody physics) || + !moveEvent.Sender.TryGetComponent(out IPhysBody? physics) || !PathfindingNode.IsRelevant(moveEvent.Sender, physics) || moveEvent.NewPosition.GetGridId(EntityManager) == GridId.Invalid) { @@ -368,7 +368,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Pathfinding public bool CanTraverse(IEntity entity, PathfindingNode node) { - if (entity.TryGetComponent(out IPhysBody physics) && + if (entity.TryGetComponent(out IPhysBody? physics) && (physics.CollisionMask & node.BlockedCollisionMask) != 0) { return false; diff --git a/Content.Server/GameObjects/EntitySystems/AI/Steering/AiSteeringSystem.cs b/Content.Server/GameObjects/EntitySystems/AI/Steering/AiSteeringSystem.cs index 1bc1f50131..23f6b08a4c 100644 --- a/Content.Server/GameObjects/EntitySystems/AI/Steering/AiSteeringSystem.cs +++ b/Content.Server/GameObjects/EntitySystems/AI/Steering/AiSteeringSystem.cs @@ -26,7 +26,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering [Dependency] private readonly IMapManager _mapManager = default!; [Dependency] private readonly IPauseManager _pauseManager = default!; - private PathfindingSystem _pathfindingSystem; + private PathfindingSystem _pathfindingSystem = default!; /// /// Whether we try to avoid non-blocking physics objects @@ -127,7 +127,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering /// public void Unregister(IEntity entity) { - if (entity.TryGetComponent(out AiControllerComponent controller)) + if (entity.TryGetComponent(out AiControllerComponent? controller)) { controller.VelocityDir = Vector2.Zero; } @@ -245,7 +245,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering private SteeringStatus Steer(IEntity entity, IAiSteeringRequest steeringRequest, float frameTime) { // Main optimisation to be done below is the redundant calls and adding more variables - if (entity.Deleted || !entity.TryGetComponent(out AiControllerComponent controller) || !ActionBlockerSystem.CanMove(entity)) + if (entity.Deleted || !entity.TryGetComponent(out AiControllerComponent? controller) || !ActionBlockerSystem.CanMove(entity)) { return SteeringStatus.NoPath; } @@ -414,7 +414,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering var startTile = gridManager.GetTileRef(entity.Transform.Coordinates); var endTile = gridManager.GetTileRef(steeringRequest.TargetGrid); var collisionMask = 0; - if (entity.TryGetComponent(out IPhysBody physics)) + if (entity.TryGetComponent(out IPhysBody? physics)) { collisionMask = physics.CollisionMask; } @@ -600,7 +600,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering return Vector2.Zero; } - if (target.TryGetComponent(out IPhysBody physics)) + if (target.TryGetComponent(out IPhysBody? physics)) { var targetDistance = (targetPos.Position - entityPos.Position); targetPos = targetPos.Offset(physics.LinearVelocity * targetDistance); @@ -618,7 +618,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering /// private Vector2 CollisionAvoidance(IEntity entity, Vector2 direction, ICollection ignoredTargets) { - if (direction == Vector2.Zero || !entity.TryGetComponent(out IPhysBody physics)) + if (direction == Vector2.Zero || !entity.TryGetComponent(out IPhysBody? physics)) { return Vector2.Zero; } @@ -659,7 +659,7 @@ namespace Content.Server.GameObjects.EntitySystems.AI.Steering // if we're moving in the same direction then ignore // So if 2 entities are moving towards each other and both detect a collision they'll both move in the same direction // i.e. towards the right - if (physicsEntity.TryGetComponent(out IPhysBody otherPhysics) && + if (physicsEntity.TryGetComponent(out IPhysBody? otherPhysics) && Vector2.Dot(otherPhysics.LinearVelocity, direction) > 0) { continue; diff --git a/Content.Server/GameObjects/EntitySystems/BlockGameSystem.cs b/Content.Server/GameObjects/EntitySystems/BlockGameSystem.cs index e7dd4c211e..8f42190b08 100644 --- a/Content.Server/GameObjects/EntitySystems/BlockGameSystem.cs +++ b/Content.Server/GameObjects/EntitySystems/BlockGameSystem.cs @@ -41,6 +41,9 @@ namespace Content.Server.GameObjects.EntitySystems if (highScoreEntries.Min(e => e.Score) >= entry.Score) return null; var lowestHighscore = highScoreEntries.Min(); + + if (lowestHighscore == null) return null; + highScoreEntries.Remove(lowestHighscore); highScoreEntries.Add(entry); return GetPlacement(highScoreEntries, entry); diff --git a/Content.Server/GameObjects/EntitySystems/CargoConsoleSystem.cs b/Content.Server/GameObjects/EntitySystems/CargoConsoleSystem.cs index 909619dfc0..005f894dda 100644 --- a/Content.Server/GameObjects/EntitySystems/CargoConsoleSystem.cs +++ b/Content.Server/GameObjects/EntitySystems/CargoConsoleSystem.cs @@ -1,8 +1,9 @@ using System.Collections.Generic; -using Content.Shared.Prototypes.Cargo; -using Content.Shared.GameTicking; +using System.Diagnostics.CodeAnalysis; using Content.Server.Cargo; using Content.Server.GameObjects.Components.Cargo; +using Content.Shared.GameTicking; +using Content.Shared.Prototypes.Cargo; using Robust.Shared.GameObjects; namespace Content.Server.GameObjects.EntitySystems @@ -104,12 +105,12 @@ namespace Content.Server.GameObjects.EntitySystems /// /// Returns whether the account exists, eventually passing the account in the out parameter. /// - public bool TryGetBankAccount(int id, out CargoBankAccount account) + public bool TryGetBankAccount(int id, [NotNullWhen(true)] out CargoBankAccount? account) { return _accountsDict.TryGetValue(id, out account); } - public bool TryGetOrderDatabase(int id, out CargoOrderDatabase database) + public bool TryGetOrderDatabase(int id, [NotNullWhen(true)] out CargoOrderDatabase? database) { return _databasesDict.TryGetValue(id, out database); } @@ -182,7 +183,7 @@ namespace Content.Server.GameObjects.EntitySystems { foreach (var comp in ComponentManager.EntityQuery(true)) { - if (!comp.ConnectedToDatabase || comp.Database.Id != id) + if (comp.Database == null || comp.Database.Id != id) continue; comp.Dirty(); } diff --git a/Content.Server/GameObjects/EntitySystems/Click/InteractionSystem.cs b/Content.Server/GameObjects/EntitySystems/Click/InteractionSystem.cs index d855a610ed..5f425bf83a 100644 --- a/Content.Server/GameObjects/EntitySystems/Click/InteractionSystem.cs +++ b/Content.Server/GameObjects/EntitySystems/Click/InteractionSystem.cs @@ -61,6 +61,8 @@ namespace Content.Server.GameObjects.EntitySystems.Click private void HandleDragDropMessage(DragDropMessage msg, EntitySessionEventArgs args) { var performer = args.SenderSession.AttachedEntity; + + if (performer == null) return; if (!EntityManager.TryGetEntity(msg.Dropped, out var dropped)) return; if (!EntityManager.TryGetEntity(msg.Target, out var target)) return; @@ -93,12 +95,12 @@ namespace Content.Server.GameObjects.EntitySystems.Click } } - private bool HandleActivateItemInWorld(ICommonSession session, EntityCoordinates coords, EntityUid uid) + private bool HandleActivateItemInWorld(ICommonSession? session, EntityCoordinates coords, EntityUid uid) { if (!EntityManager.TryGetEntity(uid, out var used)) return false; - var playerEnt = ((IPlayerSession) session).AttachedEntity; + var playerEnt = ((IPlayerSession?) session)?.AttachedEntity; if (playerEnt == null || !playerEnt.IsValid()) { @@ -118,7 +120,7 @@ namespace Content.Server.GameObjects.EntitySystems.Click /// Activates the IActivate behavior of an object /// Verifies that the user is capable of doing the use interaction first /// - public void TryInteractionActivate(IEntity user, IEntity used) + public void TryInteractionActivate(IEntity? user, IEntity? used) { if (user != null && used != null && ActionBlockerSystem.CanUse(user)) { @@ -135,7 +137,7 @@ namespace Content.Server.GameObjects.EntitySystems.Click return; } - if (!used.TryGetComponent(out IActivate activateComp)) + if (!used.TryGetComponent(out IActivate? activateComp)) { return; } @@ -148,7 +150,7 @@ namespace Content.Server.GameObjects.EntitySystems.Click } } - private bool HandleWideAttack(ICommonSession session, EntityCoordinates coords, EntityUid uid) + private bool HandleWideAttack(ICommonSession? session, EntityCoordinates coords, EntityUid uid) { // client sanitization if (!coords.IsValid(_entityManager)) @@ -164,14 +166,14 @@ namespace Content.Server.GameObjects.EntitySystems.Click return true; } - var userEntity = ((IPlayerSession) session).AttachedEntity; + var userEntity = ((IPlayerSession?) session)?.AttachedEntity; if (userEntity == null || !userEntity.IsValid()) { return true; } - if (userEntity.TryGetComponent(out CombatModeComponent combatMode) && combatMode.IsInCombatMode) + if (userEntity.TryGetComponent(out CombatModeComponent? combatMode) && combatMode.IsInCombatMode) { DoAttack(userEntity, coords, true); } @@ -193,7 +195,7 @@ namespace Content.Server.GameObjects.EntitySystems.Click throw new InvalidOperationException(); } - if (entity.TryGetComponent(out CombatModeComponent combatMode) && combatMode.IsInCombatMode) + if (entity.TryGetComponent(out CombatModeComponent? combatMode) && combatMode.IsInCombatMode) { DoAttack(entity, coords, false, uid); } @@ -203,7 +205,7 @@ namespace Content.Server.GameObjects.EntitySystems.Click } } - public bool HandleClientUseItemInHand(ICommonSession session, EntityCoordinates coords, EntityUid uid) + public bool HandleClientUseItemInHand(ICommonSession? session, EntityCoordinates coords, EntityUid uid) { // client sanitization if (!coords.IsValid(_entityManager)) @@ -219,14 +221,14 @@ namespace Content.Server.GameObjects.EntitySystems.Click return true; } - var userEntity = ((IPlayerSession) session).AttachedEntity; + var userEntity = ((IPlayerSession?) session)?.AttachedEntity; if (userEntity == null || !userEntity.IsValid()) { return true; } - if (userEntity.TryGetComponent(out CombatModeComponent combat) && combat.IsInCombatMode) + if (userEntity.TryGetComponent(out CombatModeComponent? combat) && combat.IsInCombatMode) DoAttack(userEntity, coords, false, uid); else UserInteraction(userEntity, coords, uid); @@ -234,7 +236,7 @@ namespace Content.Server.GameObjects.EntitySystems.Click return true; } - private bool HandleTryPullObject(ICommonSession session, EntityCoordinates coords, EntityUid uid) + private bool HandleTryPullObject(ICommonSession? session, EntityCoordinates coords, EntityUid uid) { // client sanitization if (!coords.IsValid(_entityManager)) @@ -250,7 +252,7 @@ namespace Content.Server.GameObjects.EntitySystems.Click return false; } - var player = session.AttachedEntity; + var player = session?.AttachedEntity; if (player == null) { @@ -269,7 +271,7 @@ namespace Content.Server.GameObjects.EntitySystems.Click return false; } - if (!pulledObject.TryGetComponent(out PullableComponent pull)) + if (!pulledObject.TryGetComponent(out PullableComponent? pull)) { return false; } diff --git a/Content.Server/GameObjects/EntitySystems/CloningSystem.cs b/Content.Server/GameObjects/EntitySystems/CloningSystem.cs index 83ddd8bb0a..ccea52aedd 100644 --- a/Content.Server/GameObjects/EntitySystems/CloningSystem.cs +++ b/Content.Server/GameObjects/EntitySystems/CloningSystem.cs @@ -32,7 +32,7 @@ namespace Content.Server.GameObjects.EntitySystems return Minds.ContainsValue(mind); } - public Dictionary GetIdToUser() + public Dictionary GetIdToUser() { return Minds.ToDictionary(m => m.Key, m => m.Value.CharacterName); } diff --git a/Content.Server/GameObjects/EntitySystems/DestructibleSystem.cs b/Content.Server/GameObjects/EntitySystems/DestructibleSystem.cs index 3390cee803..8753851745 100644 --- a/Content.Server/GameObjects/EntitySystems/DestructibleSystem.cs +++ b/Content.Server/GameObjects/EntitySystems/DestructibleSystem.cs @@ -12,9 +12,9 @@ namespace Content.Server.GameObjects.EntitySystems { [Dependency] public readonly IRobustRandom Random = default!; - public AudioSystem AudioSystem { get; private set; } + public AudioSystem AudioSystem { get; private set; } = default!; - public ActSystem ActSystem { get; private set; } + public ActSystem ActSystem { get; private set; } = default!; public override void Initialize() { diff --git a/Content.Server/GameObjects/EntitySystems/GravitySystem.cs b/Content.Server/GameObjects/EntitySystems/GravitySystem.cs index 5355439e79..29a7ef8fe1 100644 --- a/Content.Server/GameObjects/EntitySystems/GravitySystem.cs +++ b/Content.Server/GameObjects/EntitySystems/GravitySystem.cs @@ -129,7 +129,7 @@ namespace Content.Server.GameObjects.EntitySystems { if (player.AttachedEntity == null || player.AttachedEntity.Transform.GridID != gridId - || !player.AttachedEntity.TryGetComponent(out CameraRecoilComponent recoil)) + || !player.AttachedEntity.TryGetComponent(out CameraRecoilComponent? recoil)) { continue; } diff --git a/Content.Server/GameObjects/EntitySystems/HandsSystem.cs b/Content.Server/GameObjects/EntitySystems/HandsSystem.cs index 4461a2e73a..410c83211c 100644 --- a/Content.Server/GameObjects/EntitySystems/HandsSystem.cs +++ b/Content.Server/GameObjects/EntitySystems/HandsSystem.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics.CodeAnalysis; using System.Linq; using Content.Server.GameObjects.Components.GUI; using Content.Server.GameObjects.Components.Items; @@ -11,7 +12,6 @@ using Content.Shared.GameObjects.EntitySystems; using Content.Shared.Input; using Content.Shared.Interfaces; using JetBrains.Annotations; -using Robust.Server.GameObjects; using Robust.Server.Player; using Robust.Shared.Containers; using Robust.Shared.GameObjects; @@ -57,20 +57,20 @@ namespace Content.Server.GameObjects.EntitySystems private static void HandleContainerModified(ContainerModifiedMessage args) { - if (args.Container.Owner.TryGetComponent(out IHandsComponent handsComponent)) + if (args.Container.Owner.TryGetComponent(out IHandsComponent? handsComponent)) { handsComponent.HandleSlotModifiedMaybe(args); } } - private static bool TryGetAttachedComponent(IPlayerSession session, out T component) + private static bool TryGetAttachedComponent(IPlayerSession? session, [NotNullWhen(true)] out T? component) where T : Component { component = default; - var ent = session.AttachedEntity; + var ent = session?.AttachedEntity; - if (ent == null || !ent.IsValid() || !ent.TryGetComponent(out T comp)) + if (ent == null || !ent.IsValid() || !ent.TryGetComponent(out T? comp)) { return false; } @@ -79,9 +79,9 @@ namespace Content.Server.GameObjects.EntitySystems return true; } - private static void HandleSwapHands(ICommonSession session) + private static void HandleSwapHands(ICommonSession? session) { - if (!TryGetAttachedComponent(session as IPlayerSession, out HandsComponent handsComp)) + if (!TryGetAttachedComponent(session as IPlayerSession, out HandsComponent? handsComp)) { return; } @@ -105,14 +105,14 @@ namespace Content.Server.GameObjects.EntitySystems } } - private bool HandleDrop(ICommonSession session, EntityCoordinates coords, EntityUid uid) + private bool HandleDrop(ICommonSession? session, EntityCoordinates coords, EntityUid uid) { - var ent = ((IPlayerSession) session).AttachedEntity; + var ent = ((IPlayerSession?) session)?.AttachedEntity; if (ent == null || !ent.IsValid()) return false; - if (!ent.TryGetComponent(out HandsComponent handsComp)) + if (!ent.TryGetComponent(out HandsComponent? handsComp)) return false; if (handsComp.ActiveHand == null || handsComp.GetActiveHand == null) @@ -136,41 +136,44 @@ namespace Content.Server.GameObjects.EntitySystems return true; } - private static void HandleActivateItem(ICommonSession session) + private static void HandleActivateItem(ICommonSession? session) { - if (!TryGetAttachedComponent(session as IPlayerSession, out HandsComponent handsComp)) + if (!TryGetAttachedComponent(session as IPlayerSession, out HandsComponent? handsComp)) return; handsComp.ActivateItem(); } - private bool HandleThrowItem(ICommonSession session, EntityCoordinates coords, EntityUid uid) + private bool HandleThrowItem(ICommonSession? session, EntityCoordinates coords, EntityUid uid) { - var playerEnt = ((IPlayerSession)session).AttachedEntity; + var playerEnt = ((IPlayerSession?)session)?.AttachedEntity; if (playerEnt == null || !playerEnt.IsValid()) return false; - if (!playerEnt.TryGetComponent(out HandsComponent handsComp)) + if (!playerEnt.TryGetComponent(out HandsComponent? handsComp)) return false; - if (!handsComp.CanDrop(handsComp.ActiveHand)) + if (handsComp.ActiveHand == null || !handsComp.CanDrop(handsComp.ActiveHand)) return false; - var throwEnt = handsComp.GetItem(handsComp.ActiveHand).Owner; + var throwEnt = handsComp.GetItem(handsComp.ActiveHand)?.Owner; + + if (throwEnt == null) + return false; if (!handsComp.ThrowItem()) return false; // throw the item, split off from a stack if it's meant to be thrown individually - if (!throwEnt.TryGetComponent(out StackComponent stackComp) || stackComp.Count < 2 || !stackComp.ThrowIndividually) + if (!throwEnt.TryGetComponent(out StackComponent? stackComp) || stackComp.Count < 2 || !stackComp.ThrowIndividually) { handsComp.Drop(handsComp.ActiveHand); } else { stackComp.Use(1); - throwEnt = throwEnt.EntityManager.SpawnEntity(throwEnt.Prototype.ID, playerEnt.Transform.Coordinates); + throwEnt = throwEnt.EntityManager.SpawnEntity(throwEnt.Prototype?.ID, playerEnt.Transform.Coordinates); // can only throw one item at a time, regardless of what the prototype stack size is. if (throwEnt.TryGetComponent(out var newStackComp)) @@ -196,28 +199,28 @@ namespace Content.Server.GameObjects.EntitySystems return true; } - private void HandleSmartEquipBackpack(ICommonSession session) + private void HandleSmartEquipBackpack(ICommonSession? session) { HandleSmartEquip(session, Slots.BACKPACK); } - private void HandleSmartEquipBelt(ICommonSession session) + private void HandleSmartEquipBelt(ICommonSession? session) { HandleSmartEquip(session, Slots.BELT); } - private void HandleSmartEquip(ICommonSession session, Slots equipmentSlot) + private void HandleSmartEquip(ICommonSession? session, Slots equipmentSlot) { - var plyEnt = ((IPlayerSession) session).AttachedEntity; + var plyEnt = ((IPlayerSession?) session)?.AttachedEntity; if (plyEnt == null || !plyEnt.IsValid()) return; - if (!plyEnt.TryGetComponent(out HandsComponent handsComp) || - !plyEnt.TryGetComponent(out InventoryComponent inventoryComp)) + if (!plyEnt.TryGetComponent(out HandsComponent? handsComp) || + !plyEnt.TryGetComponent(out InventoryComponent? inventoryComp)) return; - if (!inventoryComp.TryGetSlotItem(equipmentSlot, out ItemComponent equipmentItem) + if (!inventoryComp.TryGetSlotItem(equipmentSlot, out ItemComponent? equipmentItem) || !equipmentItem.Owner.TryGetComponent(out var storageComponent)) { plyEnt.PopupMessage(Loc.GetString("You have no {0} to take something out of!", @@ -231,7 +234,7 @@ namespace Content.Server.GameObjects.EntitySystems { storageComponent.PlayerInsertHeldEntity(plyEnt); } - else + else if (storageComponent.StoredEntities != null) { if (storageComponent.StoredEntities.Count == 0) { diff --git a/Content.Server/GameObjects/EntitySystems/JobQueues/Job.cs b/Content.Server/GameObjects/EntitySystems/JobQueues/Job.cs index 08379de594..3b711ec954 100644 --- a/Content.Server/GameObjects/EntitySystems/JobQueues/Job.cs +++ b/Content.Server/GameObjects/EntitySystems/JobQueues/Job.cs @@ -23,10 +23,10 @@ namespace Content.Server.GameObjects.EntitySystems.JobQueues /// /// Represents the status of this job as a regular task. /// - public Task AsTask { get; } + public Task AsTask { get; } - public T Result { get; private set; } - public Exception Exception { get; private set; } + public T? Result { get; private set; } + public Exception? Exception { get; private set; } protected CancellationToken Cancellation { get; } public double DebugTime { get; private set; } @@ -34,11 +34,11 @@ namespace Content.Server.GameObjects.EntitySystems.JobQueues protected readonly IStopwatch StopWatch; // TCS for the Task property. - private readonly TaskCompletionSource _taskTcs; + private readonly TaskCompletionSource _taskTcs; // TCS to call to resume the suspended job. - private TaskCompletionSource _resume; - private Task _workInProgress; + private TaskCompletionSource? _resume; + private Task? _workInProgress; protected Job(double maxTime, CancellationToken cancellation = default) : this(maxTime, new Stopwatch(), cancellation) @@ -51,7 +51,7 @@ namespace Content.Server.GameObjects.EntitySystems.JobQueues StopWatch = stopwatch; Cancellation = cancellation; - _taskTcs = new TaskCompletionSource(); + _taskTcs = new TaskCompletionSource(); AsTask = _taskTcs.Task; } @@ -66,7 +66,7 @@ namespace Content.Server.GameObjects.EntitySystems.JobQueues { DebugTools.AssertNull(_resume); - _resume = new TaskCompletionSource(); + _resume = new TaskCompletionSource(); Status = JobStatus.Paused; DebugTime += StopWatch.Elapsed.TotalSeconds; return _resume.Task; @@ -99,7 +99,7 @@ namespace Content.Server.GameObjects.EntitySystems.JobQueues // Immediately block on resume so that everything stays correct. Status = JobStatus.Paused; - _resume = new TaskCompletionSource(); + _resume = new TaskCompletionSource(); await _resume.Task; @@ -119,7 +119,7 @@ namespace Content.Server.GameObjects.EntitySystems.JobQueues await task; // Immediately block on resume so that everything stays correct. - _resume = new TaskCompletionSource(); + _resume = new TaskCompletionSource(); Status = JobStatus.Paused; await _resume.Task; @@ -144,11 +144,11 @@ namespace Content.Server.GameObjects.EntitySystems.JobQueues if (Cancellation.IsCancellationRequested) { - resume.TrySetCanceled(); + resume?.TrySetCanceled(); } else { - resume.SetResult(null); + resume?.SetResult(null); } if (Status != JobStatus.Finished && Status != JobStatus.Waiting) @@ -158,7 +158,7 @@ namespace Content.Server.GameObjects.EntitySystems.JobQueues } } - protected abstract Task Process(); + protected abstract Task Process(); private async Task ProcessWrap() { diff --git a/Content.Server/GameObjects/EntitySystems/NodeContainerSystem.cs b/Content.Server/GameObjects/EntitySystems/NodeContainerSystem.cs index 130ed3b30a..4ea8dd9470 100644 --- a/Content.Server/GameObjects/EntitySystems/NodeContainerSystem.cs +++ b/Content.Server/GameObjects/EntitySystems/NodeContainerSystem.cs @@ -25,7 +25,7 @@ namespace Content.Server.GameObjects.EntitySystems private void RotateEvent(RotateEvent ev) { - if (!ev.Sender.TryGetComponent(out NodeContainerComponent container)) + if (!ev.Sender.TryGetComponent(out NodeContainerComponent? container)) { return; } diff --git a/Content.Server/GameObjects/EntitySystems/PuddleSystem.cs b/Content.Server/GameObjects/EntitySystems/PuddleSystem.cs index 803ec4cb8f..30d3b99d11 100644 --- a/Content.Server/GameObjects/EntitySystems/PuddleSystem.cs +++ b/Content.Server/GameObjects/EntitySystems/PuddleSystem.cs @@ -23,7 +23,7 @@ namespace Content.Server.GameObjects.EntitySystems mapManager.TileChanged -= HandleTileChanged; } - private void HandleTileChanged(object sender, TileChangedEventArgs eventArgs) + private void HandleTileChanged(object? sender, TileChangedEventArgs eventArgs) { // If this gets hammered you could probably queue up all the tile changes every tick but I doubt that would ever happen. foreach (var (puddle, snapGrid) in ComponentManager.EntityQuery(true)) diff --git a/Content.Server/GameObjects/EntitySystems/RadioSystem.cs b/Content.Server/GameObjects/EntitySystems/RadioSystem.cs index e79c1b633c..1465583dee 100644 --- a/Content.Server/GameObjects/EntitySystems/RadioSystem.cs +++ b/Content.Server/GameObjects/EntitySystems/RadioSystem.cs @@ -1,6 +1,6 @@ -using Content.Server.Interfaces; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; +using Content.Server.Interfaces; using JetBrains.Annotations; using Robust.Shared.GameObjects; @@ -9,14 +9,7 @@ namespace Content.Server.GameObjects.EntitySystems [UsedImplicitly] public class RadioSystem : EntitySystem { - private List _messages; - - public override void Initialize() - { - base.Initialize(); - - _messages = new List(); - } + private readonly List _messages = new(); public void SpreadMessage(IRadio source, IEntity speaker, string message, int channel) { diff --git a/Content.Server/GameObjects/EntitySystems/ResearchSystem.cs b/Content.Server/GameObjects/EntitySystems/ResearchSystem.cs index c5c78e9d2d..f09c7317d1 100644 --- a/Content.Server/GameObjects/EntitySystems/ResearchSystem.cs +++ b/Content.Server/GameObjects/EntitySystems/ResearchSystem.cs @@ -30,7 +30,7 @@ namespace Content.Server.GameObjects.EntitySystems _servers.Remove(server); } - public ResearchServerComponent GetServerById(int id) + public ResearchServerComponent? GetServerById(int id) { foreach (var server in Servers) { diff --git a/Content.Server/GameObjects/EntitySystems/RoundEndSystem.cs b/Content.Server/GameObjects/EntitySystems/RoundEndSystem.cs index 884cee1660..d756c58a26 100644 --- a/Content.Server/GameObjects/EntitySystems/RoundEndSystem.cs +++ b/Content.Server/GameObjects/EntitySystems/RoundEndSystem.cs @@ -3,7 +3,6 @@ using System.Threading; using Content.Server.Interfaces.Chat; using Content.Server.Interfaces.GameTicking; using Content.Shared.GameTicking; -using Robust.Server.GameObjects; using Robust.Shared.Audio; using Robust.Shared.GameObjects; using Robust.Shared.IoC; @@ -33,16 +32,16 @@ namespace Content.Server.GameObjects.EntitySystems public TimeSpan CallCooldown { get; } = TimeSpan.FromSeconds(30); public delegate void RoundEndCountdownStarted(); - public event RoundEndCountdownStarted OnRoundEndCountdownStarted; + public event RoundEndCountdownStarted? OnRoundEndCountdownStarted; public delegate void RoundEndCountdownCancelled(); - public event RoundEndCountdownCancelled OnRoundEndCountdownCancelled; + public event RoundEndCountdownCancelled? OnRoundEndCountdownCancelled; public delegate void RoundEndCountdownFinished(); - public event RoundEndCountdownFinished OnRoundEndCountdownFinished; + public event RoundEndCountdownFinished? OnRoundEndCountdownFinished; public delegate void CallCooldownEnded(); - public event CallCooldownEnded OnCallCooldownEnded; + public event CallCooldownEnded? OnCallCooldownEnded; void IResettingEntitySystem.Reset() { diff --git a/Content.Server/GameObjects/EntitySystems/SignalLinkerSystem.cs b/Content.Server/GameObjects/EntitySystems/SignalLinkerSystem.cs index 11e106f64b..85471eea82 100644 --- a/Content.Server/GameObjects/EntitySystems/SignalLinkerSystem.cs +++ b/Content.Server/GameObjects/EntitySystems/SignalLinkerSystem.cs @@ -12,14 +12,7 @@ namespace Content.Server.GameObjects.EntitySystems { public class SignalLinkerSystem : EntitySystem { - private Dictionary _transmitters; - - public override void Initialize() - { - base.Initialize(); - - _transmitters = new Dictionary(); - } + private readonly Dictionary _transmitters = new(); public bool SignalLinkerKeybind(NetUserId id, bool? enable) { @@ -35,7 +28,9 @@ namespace Content.Server.GameObjects.EntitySystems if (_transmitters.Count == 0) { CommandBinds.Builder - .BindBefore(EngineKeyFunctions.Use, new PointerInputCmdHandler(HandleUse), typeof(InteractionSystem)) + .BindBefore(EngineKeyFunctions.Use, + new PointerInputCmdHandler(HandleUse), + typeof(InteractionSystem)) .Register(); } @@ -59,8 +54,13 @@ namespace Content.Server.GameObjects.EntitySystems return enable.Value; } - private bool HandleUse(ICommonSession session, EntityCoordinates coords, EntityUid uid) + private bool HandleUse(ICommonSession? session, EntityCoordinates coords, EntityUid uid) { + if (session?.AttachedEntity == null) + { + return false; + } + if (!_transmitters.TryGetValue(session.UserId, out var signalTransmitter)) { return false; @@ -88,6 +88,5 @@ namespace Content.Server.GameObjects.EntitySystems return false; } - } } diff --git a/Content.Server/GameObjects/EntitySystems/StationEvents/RadiationPulseSystem.cs b/Content.Server/GameObjects/EntitySystems/StationEvents/RadiationPulseSystem.cs index a47f393ce3..b91c1aa0e7 100644 --- a/Content.Server/GameObjects/EntitySystems/StationEvents/RadiationPulseSystem.cs +++ b/Content.Server/GameObjects/EntitySystems/StationEvents/RadiationPulseSystem.cs @@ -11,7 +11,14 @@ namespace Content.Server.GameObjects.EntitySystems.StationEvents { private const string RadiationPrototype = "RadiationPulse"; - public IEntity RadiationPulse(EntityCoordinates coordinates, float range, int dps, bool decay = true, float minPulseLifespan = 0.8f, float maxPulseLifespan = 2.5f, string sound = null) + public IEntity RadiationPulse( + EntityCoordinates coordinates, + float range, + int dps, + bool decay = true, + float minPulseLifespan = 0.8f, + float maxPulseLifespan = 2.5f, + string? sound = null) { var radiationEntity = EntityManager.SpawnEntity(RadiationPrototype, coordinates); var radiation = radiationEntity.GetComponent(); diff --git a/Content.Server/GameObjects/EntitySystems/StorageSystem.cs b/Content.Server/GameObjects/EntitySystems/StorageSystem.cs index 45380254fe..5c59a3f762 100644 --- a/Content.Server/GameObjects/EntitySystems/StorageSystem.cs +++ b/Content.Server/GameObjects/EntitySystems/StorageSystem.cs @@ -2,7 +2,6 @@ using Content.Server.GameObjects.Components.Items.Storage; using Content.Server.GameObjects.EntitySystems.Click; using JetBrains.Annotations; -using Robust.Server.GameObjects; using Robust.Server.Player; using Robust.Shared.Containers; using Robust.Shared.GameObjects; @@ -34,7 +33,7 @@ namespace Content.Server.GameObjects.EntitySystems { var oldParentEntity = message.Container.Owner; - if (oldParentEntity.TryGetComponent(out ServerStorageComponent storageComp)) + if (oldParentEntity.TryGetComponent(out ServerStorageComponent? storageComp)) { storageComp.HandleEntityMaybeRemoved(message); } @@ -44,7 +43,7 @@ namespace Content.Server.GameObjects.EntitySystems { var oldParentEntity = message.Container.Owner; - if (oldParentEntity.TryGetComponent(out ServerStorageComponent storageComp)) + if (oldParentEntity.TryGetComponent(out ServerStorageComponent? storageComp)) { storageComp.HandleEntityMaybeInserted(message); } diff --git a/Content.Server/GameObjects/EntitySystems/TriggerSystem.cs b/Content.Server/GameObjects/EntitySystems/TriggerSystem.cs index 768121fd40..8348386a0d 100644 --- a/Content.Server/GameObjects/EntitySystems/TriggerSystem.cs +++ b/Content.Server/GameObjects/EntitySystems/TriggerSystem.cs @@ -19,6 +19,12 @@ namespace Content.Server.GameObjects.EntitySystems public class TimerTriggerEventArgs : EventArgs { + public TimerTriggerEventArgs(IEntity user, IEntity source) + { + User = user; + Source = source; + } + public IEntity User { get; set; } public IEntity Source { get; set; } } @@ -31,11 +37,7 @@ namespace Content.Server.GameObjects.EntitySystems Timer.Spawn(delay, () => { - var timerTriggerEventArgs = new TimerTriggerEventArgs - { - User = user, - Source = trigger - }; + var timerTriggerEventArgs = new TimerTriggerEventArgs(user, trigger); var timerTriggers = trigger.GetAllComponents().ToList(); foreach (var timerTrigger in timerTriggers) diff --git a/Content.Server/GameObjects/EntitySystems/WeightlessSystem.cs b/Content.Server/GameObjects/EntitySystems/WeightlessSystem.cs index 399c706c92..0471b95336 100644 --- a/Content.Server/GameObjects/EntitySystems/WeightlessSystem.cs +++ b/Content.Server/GameObjects/EntitySystems/WeightlessSystem.cs @@ -97,13 +97,13 @@ namespace Content.Server.GameObjects.EntitySystems private void EntParentChanged(EntParentChangedMessage ev) { - if (!ev.Entity.TryGetComponent(out ServerAlertsComponent status)) + if (!ev.Entity.TryGetComponent(out ServerAlertsComponent? status)) { return; } if (ev.OldParent != null && - ev.OldParent.TryGetComponent(out IMapGridComponent mapGrid)) + ev.OldParent.TryGetComponent(out IMapGridComponent? mapGrid)) { var oldGrid = mapGrid.GridIndex; diff --git a/Content.Server/GameObjects/EntitySystems/WireHackingSystem.cs b/Content.Server/GameObjects/EntitySystems/WireHackingSystem.cs index 3235bee8c4..67fac62474 100644 --- a/Content.Server/GameObjects/EntitySystems/WireHackingSystem.cs +++ b/Content.Server/GameObjects/EntitySystems/WireHackingSystem.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using Content.Shared.GameTicking; using Robust.Shared.GameObjects; using Robust.Shared.ViewVariables; @@ -11,7 +12,7 @@ namespace Content.Server.GameObjects.EntitySystems [ViewVariables] private readonly Dictionary _layouts = new(); - public bool TryGetLayout(string id, out WireLayout layout) + public bool TryGetLayout(string id, [NotNullWhen(true)] out WireLayout? layout) { return _layouts.TryGetValue(id, out layout); } diff --git a/Content.Server/GameTicking/GamePreset.cs b/Content.Server/GameTicking/GamePreset.cs index 273918da31..7a3ca2287a 100644 --- a/Content.Server/GameTicking/GamePreset.cs +++ b/Content.Server/GameTicking/GamePreset.cs @@ -1,16 +1,16 @@ #nullable enable annotations using System.Collections.Generic; -using Content.Shared.Preferences; using Content.Server.GameObjects.Components.Observer; using Content.Server.Interfaces.GameTicking; using Content.Server.Mobs; using Content.Shared.Damage; using Content.Shared.GameObjects.Components.Damage; using Content.Shared.GameObjects.Components.Mobs.State; +using Content.Shared.Preferences; using Robust.Server.Player; using Robust.Shared.GameObjects; -using Robust.Shared.Network; using Robust.Shared.IoC; +using Robust.Shared.Network; namespace Content.Server.GameTicking { @@ -75,7 +75,7 @@ namespace Content.Server.GameTicking var entityManager = IoCManager.Resolve(); var ghost = entityManager.SpawnEntity("MobObserver", position); - ghost.Name = mind.CharacterName; + ghost.Name = mind.CharacterName ?? string.Empty; var ghostComponent = ghost.GetComponent(); ghostComponent.CanReturnToBody = canReturn; diff --git a/Content.Server/GameTicking/GamePresets/PresetSuspicion.cs b/Content.Server/GameTicking/GamePresets/PresetSuspicion.cs index f373a4571d..decd397800 100644 --- a/Content.Server/GameTicking/GamePresets/PresetSuspicion.cs +++ b/Content.Server/GameTicking/GamePresets/PresetSuspicion.cs @@ -21,6 +21,7 @@ using Robust.Shared.Log; using Robust.Shared.Maths; using Robust.Shared.Prototypes; using Robust.Shared.Random; +using Robust.Shared.Utility; namespace Content.Server.GameTicking.GamePresets { @@ -106,19 +107,22 @@ namespace Content.Server.GameTicking.GamePresets list.Remove(traitor); Logger.InfoS("preset", "Selected a preferred traitor."); } - var mind = traitor.Data.ContentData().Mind; + var mind = traitor.Data.ContentData()?.Mind; var antagPrototype = _prototypeManager.Index(TraitorID); - var traitorRole = new SuspicionTraitorRole(mind, antagPrototype); - mind.AddRole(traitorRole); + + DebugTools.AssertNotNull(mind?.OwnedEntity); + + var traitorRole = new SuspicionTraitorRole(mind!, antagPrototype); + mind!.AddRole(traitorRole); traitors.Add(traitorRole); // creadth: we need to create uplink for the antag. // PDA should be in place already, so we just need to // initiate uplink account. var uplinkAccount = - new UplinkAccount(mind.OwnedEntity.Uid, + new UplinkAccount(mind.OwnedEntity!.Uid, TraitorStartingBalance); var inventory = mind.OwnedEntity.GetComponent(); - if (!inventory.TryGetSlotItem(EquipmentSlotDefines.Slots.IDCARD, out ItemComponent pdaItem)) + if (!inventory.TryGetSlotItem(EquipmentSlotDefines.Slots.IDCARD, out ItemComponent? pdaItem)) { continue; } @@ -137,9 +141,12 @@ namespace Content.Server.GameTicking.GamePresets foreach (var player in list) { - var mind = player.Data.ContentData().Mind; + var mind = player.Data.ContentData()?.Mind; var antagPrototype = _prototypeManager.Index(InnocentID); - mind.AddRole(new SuspicionInnocentRole(mind, antagPrototype)); + + DebugTools.AssertNotNull(mind); + + mind!.AddRole(new SuspicionInnocentRole(mind, antagPrototype)); } foreach (var traitor in traitors) diff --git a/Content.Server/GameTicking/GamePresets/PresetTraitor.cs b/Content.Server/GameTicking/GamePresets/PresetTraitor.cs index e944690a2e..a46fb48080 100644 --- a/Content.Server/GameTicking/GamePresets/PresetTraitor.cs +++ b/Content.Server/GameTicking/GamePresets/PresetTraitor.cs @@ -22,6 +22,7 @@ using Robust.Shared.Log; using Robust.Shared.Maths; using Robust.Shared.Prototypes; using Robust.Shared.Random; +using Robust.Shared.Utility; namespace Content.Server.GameTicking.GamePresets { @@ -107,7 +108,6 @@ namespace Content.Server.GameTicking.GamePresets Logger.InfoS("preset", "Selected a preferred traitor."); } var mind = traitor.Data.ContentData()?.Mind; - var traitorRole = new TraitorRole(mind); if (mind == null) { Logger.ErrorS("preset", "Failed getting mind for picked traitor."); @@ -117,9 +117,11 @@ namespace Content.Server.GameTicking.GamePresets // creadth: we need to create uplink for the antag. // PDA should be in place already, so we just need to // initiate uplink account. - var uplinkAccount = new UplinkAccount(mind.OwnedEntity.Uid, StartingBalance); + DebugTools.AssertNotNull(mind.OwnedEntity); + + var uplinkAccount = new UplinkAccount(mind.OwnedEntity!.Uid, StartingBalance); var inventory = mind.OwnedEntity.GetComponent(); - if (!inventory.TryGetSlotItem(EquipmentSlotDefines.Slots.IDCARD, out ItemComponent pdaItem)) + if (!inventory.TryGetSlotItem(EquipmentSlotDefines.Slots.IDCARD, out ItemComponent? pdaItem)) { Logger.ErrorS("preset", "Failed getting pda for picked traitor."); continue; @@ -134,6 +136,8 @@ namespace Content.Server.GameTicking.GamePresets continue; } + var traitorRole = new TraitorRole(mind); + mind.AddRole(traitorRole); _traitors.Add(traitorRole); pdaComponent.InitUplinkAccount(uplinkAccount); @@ -185,7 +189,10 @@ namespace Content.Server.GameTicking.GamePresets foreach (var traitor in _traitors) { - result += "\n"+Loc.GetString("traitor-user-was-a-traitor", ("user", traitor.Mind.Session.Name)); + if (traitor.Mind.TryGetSession(out var session)) + { + result += "\n" + Loc.GetString("traitor-user-was-a-traitor", ("user", session.Name)); + } var objectives = traitor.Mind.AllObjectives.ToArray(); if (objectives.Length == 0) diff --git a/Content.Server/GameTicking/GamePresets/PresetTraitorDeathMatch.cs b/Content.Server/GameTicking/GamePresets/PresetTraitorDeathMatch.cs index 4cdce1a01e..eea941b415 100644 --- a/Content.Server/GameTicking/GamePresets/PresetTraitorDeathMatch.cs +++ b/Content.Server/GameTicking/GamePresets/PresetTraitorDeathMatch.cs @@ -1,30 +1,30 @@ using System; using System.Collections.Generic; -using Content.Server.GameTicking.GameRules; -using Content.Server.Interfaces.GameTicking; -using Content.Server.Interfaces.Chat; +using Content.Server.Atmos; using Content.Server.GameObjects.Components.GUI; using Content.Server.GameObjects.Components.Items.Storage; -using Content.Server.GameObjects.Components.PDA; using Content.Server.GameObjects.Components.Markers; +using Content.Server.GameObjects.Components.PDA; using Content.Server.GameObjects.Components.TraitorDeathMatch; +using Content.Server.GameTicking.GameRules; +using Content.Server.Interfaces.Chat; +using Content.Server.Interfaces.GameTicking; using Content.Server.Mobs; using Content.Server.Mobs.Roles.Traitor; using Content.Server.Players; -using Content.Server.Atmos; +using Content.Shared; using Content.Shared.Damage; using Content.Shared.GameObjects.Components.Damage; using Content.Shared.GameObjects.Components.Inventory; -using Content.Shared.GameObjects.Components.PDA; using Content.Shared.GameObjects.Components.Mobs.State; -using Content.Shared; +using Content.Shared.GameObjects.Components.PDA; using Robust.Server.Player; using Robust.Shared.Configuration; -using Robust.Shared.Map; +using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; -using Robust.Shared.GameObjects; using Robust.Shared.Log; +using Robust.Shared.Map; using Robust.Shared.Random; namespace Content.Server.GameTicking.GamePresets @@ -43,7 +43,7 @@ namespace Content.Server.GameTicking.GamePresets public string BeltPrototypeName => "ClothingBeltJanitorFilled"; public string BackpackPrototypeName => "ClothingBackpackFilled"; - private RuleMaxTimeRestart _restarter; + private RuleMaxTimeRestart _restarter = default!; private bool _safeToEndRound = false; private Dictionary _allOriginalNames = new(); @@ -60,53 +60,57 @@ namespace Content.Server.GameTicking.GamePresets public override void OnSpawnPlayerCompleted(IPlayerSession session, IEntity mob, bool lateJoin) { - int startingBalance = _cfg.GetCVar(CCVars.TraitorDeathMatchStartingBalance); + var startingBalance = _cfg.GetCVar(CCVars.TraitorDeathMatchStartingBalance); // Yup, they're a traitor var mind = session.Data.ContentData()?.Mind; - var traitorRole = new TraitorRole(mind); if (mind == null) { Logger.ErrorS("preset", "Failed getting mind for TDM player."); return; } + var traitorRole = new TraitorRole(mind); mind.AddRole(traitorRole); // Delete anything that may contain "dangerous" role-specific items. // (This includes the PDA, as everybody gets the captain PDA in this mode for true-all-access reasons.) - var inventory = mind.OwnedEntity.GetComponent(); - var victimSlots = new[] {EquipmentSlotDefines.Slots.IDCARD, EquipmentSlotDefines.Slots.BELT, EquipmentSlotDefines.Slots.BACKPACK}; - foreach (var slot in victimSlots) - if (inventory.TryGetSlotItem(slot, out ItemComponent vItem)) - vItem.Owner.Delete(); + if (mind.OwnedEntity != null && mind.OwnedEntity.TryGetComponent(out InventoryComponent? inventory)) + { + var victimSlots = new[] {EquipmentSlotDefines.Slots.IDCARD, EquipmentSlotDefines.Slots.BELT, EquipmentSlotDefines.Slots.BACKPACK}; + foreach (var slot in victimSlots) + { + if (inventory.TryGetSlotItem(slot, out ItemComponent? vItem)) + vItem.Owner.Delete(); + } - // Replace their items: + // Replace their items: - // pda - var newPDA = _entityManager.SpawnEntity(PDAPrototypeName, mind.OwnedEntity.Transform.Coordinates); - inventory.Equip(EquipmentSlotDefines.Slots.IDCARD, newPDA.GetComponent()); + // pda + var newPDA = _entityManager.SpawnEntity(PDAPrototypeName, mind.OwnedEntity.Transform.Coordinates); + inventory.Equip(EquipmentSlotDefines.Slots.IDCARD, newPDA.GetComponent()); - // belt - var newTmp = _entityManager.SpawnEntity(BeltPrototypeName, mind.OwnedEntity.Transform.Coordinates); - inventory.Equip(EquipmentSlotDefines.Slots.BELT, newTmp.GetComponent()); + // belt + var newTmp = _entityManager.SpawnEntity(BeltPrototypeName, mind.OwnedEntity.Transform.Coordinates); + inventory.Equip(EquipmentSlotDefines.Slots.BELT, newTmp.GetComponent()); - // backpack - newTmp = _entityManager.SpawnEntity(BackpackPrototypeName, mind.OwnedEntity.Transform.Coordinates); - inventory.Equip(EquipmentSlotDefines.Slots.BACKPACK, newTmp.GetComponent()); + // backpack + newTmp = _entityManager.SpawnEntity(BackpackPrototypeName, mind.OwnedEntity.Transform.Coordinates); + inventory.Equip(EquipmentSlotDefines.Slots.BACKPACK, newTmp.GetComponent()); - // Like normal traitors, they need access to a traitor account. - var uplinkAccount = new UplinkAccount(mind.OwnedEntity.Uid, startingBalance); - var pdaComponent = newPDA.GetComponent(); - pdaComponent.InitUplinkAccount(uplinkAccount); - _allOriginalNames[uplinkAccount] = mind.OwnedEntity.Name; + // Like normal traitors, they need access to a traitor account. + var uplinkAccount = new UplinkAccount(mind.OwnedEntity.Uid, startingBalance); + var pdaComponent = newPDA.GetComponent(); + pdaComponent.InitUplinkAccount(uplinkAccount); + _allOriginalNames[uplinkAccount] = mind.OwnedEntity.Name; - // The PDA needs to be marked with the correct owner. - pdaComponent.SetPDAOwner(mind.OwnedEntity.Name); - newPDA.AddComponent().UserId = mind.UserId; + // The PDA needs to be marked with the correct owner. + pdaComponent.SetPDAOwner(mind.OwnedEntity.Name); + newPDA.AddComponent().UserId = mind.UserId; + } // Finally, it would be preferrable if they spawned as far away from other players as reasonably possible. - if (FindAnyIsolatedSpawnLocation(mind, out var bestTarget)) + if (mind.OwnedEntity != null && FindAnyIsolatedSpawnLocation(mind, out var bestTarget)) { mind.OwnedEntity.Transform.Coordinates = bestTarget; } @@ -136,7 +140,7 @@ namespace Content.Server.GameTicking.GamePresets var avoidMeEntity = avoidMeMind.OwnedEntity; if (avoidMeEntity == null) continue; - if (avoidMeEntity.TryGetComponent(out IMobStateComponent mobState)) + if (avoidMeEntity.TryGetComponent(out IMobStateComponent? mobState)) { // Does have mob state component; if critical or dead, they don't really matter for spawn checks if (mobState.IsCritical() || mobState.IsDead()) @@ -181,12 +185,12 @@ namespace Content.Server.GameTicking.GamePresets public override bool OnGhostAttempt(Mind mind, bool canReturnGlobal) { var entity = mind.OwnedEntity; - if ((entity != null) && (entity.TryGetComponent(out IMobStateComponent mobState))) + if ((entity != null) && (entity.TryGetComponent(out IMobStateComponent? mobState))) { if (mobState.IsCritical()) { // TODO: This is copy/pasted from ghost code. Really, IDamagableComponent needs a method to reliably kill the target. - if (entity.TryGetComponent(out IDamageableComponent damageable)) + if (entity.TryGetComponent(out IDamageableComponent? damageable)) { //todo: what if they dont breathe lol damageable.ChangeDamage(DamageType.Asphyxiation, 100, true); diff --git a/Content.Server/GameTicking/GameRules/RuleDeathMatch.cs b/Content.Server/GameTicking/GameRules/RuleDeathMatch.cs index 8332041a74..7b185178b1 100644 --- a/Content.Server/GameTicking/GameRules/RuleDeathMatch.cs +++ b/Content.Server/GameTicking/GameRules/RuleDeathMatch.cs @@ -29,7 +29,7 @@ namespace Content.Server.GameTicking.GameRules [Dependency] private readonly IGameTicker _gameTicker = default!; [Dependency] private readonly IConfigurationManager _cfg = default!; - private CancellationTokenSource _checkTimerCancel; + private CancellationTokenSource? _checkTimerCancel; public override void Added() { @@ -59,12 +59,12 @@ namespace Content.Server.GameTicking.GameRules if (!_cfg.GetCVar(CCVars.GameLobbyEnableWin)) return; - IPlayerSession winner = null; + IPlayerSession? winner = null; foreach (var playerSession in _playerManager.GetAllPlayers()) { var playerEntity = playerSession.AttachedEntity; if (playerEntity == null - || !playerEntity.TryGetComponent(out IMobStateComponent state)) + || !playerEntity.TryGetComponent(out IMobStateComponent? state)) { continue; } @@ -94,7 +94,7 @@ namespace Content.Server.GameTicking.GameRules Timer.Spawn(TimeSpan.FromSeconds(restartDelay), () => _gameTicker.RestartRound()); } - private void PlayerManagerOnPlayerStatusChanged(object sender, SessionStatusEventArgs e) + private void PlayerManagerOnPlayerStatusChanged(object? sender, SessionStatusEventArgs e) { if (e.NewStatus == SessionStatus.Disconnected) { diff --git a/Content.Server/GameTicking/GameRules/RuleSuspicion.cs b/Content.Server/GameTicking/GameRules/RuleSuspicion.cs index 7ca52223c4..be3fb1c94f 100644 --- a/Content.Server/GameTicking/GameRules/RuleSuspicion.cs +++ b/Content.Server/GameTicking/GameRules/RuleSuspicion.cs @@ -86,7 +86,7 @@ namespace Content.Server.GameTicking.GameRules foreach (var playerSession in _playerManager.GetAllPlayers()) { if (playerSession.AttachedEntity == null - || !playerSession.AttachedEntity.TryGetComponent(out IMobStateComponent mobState) + || !playerSession.AttachedEntity.TryGetComponent(out IMobStateComponent? mobState) || !playerSession.AttachedEntity.HasComponent()) { continue; diff --git a/Content.Server/GameTicking/GameTicker.JobController.cs b/Content.Server/GameTicking/GameTicker.JobController.cs index 835097fd5a..6e4b6a9d31 100644 --- a/Content.Server/GameTicking/GameTicker.JobController.cs +++ b/Content.Server/GameTicking/GameTicker.JobController.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using Content.Shared.Preferences; using Content.Shared.Roles; @@ -45,7 +46,7 @@ namespace Content.Server.GameTicking .Where(j => { var (jobId, priority) = j; - if (!_prototypeManager.TryIndex(jobId, out JobPrototype job)) + if (!_prototypeManager.TryIndex(jobId, out JobPrototype? job)) { // Job doesn't exist, probably old data? return false; @@ -145,7 +146,7 @@ namespace Content.Server.GameTicking { var available = GetAvailablePositions(); - bool TryPick(JobPriority priority, out string jobId) + bool TryPick(JobPriority priority, [NotNullWhen(true)] out string? jobId) { var filtered = profile.JobPriorities .Where(p => p.Value == priority) diff --git a/Content.Server/GameTicking/GameTicker.cs b/Content.Server/GameTicking/GameTicker.cs index 4c55238a9b..064cb2e413 100644 --- a/Content.Server/GameTicking/GameTicker.cs +++ b/Content.Server/GameTicking/GameTicker.cs @@ -15,8 +15,6 @@ using Content.Server.GameObjects.Components.Mobs.Speech; using Content.Server.GameObjects.Components.Observer; using Content.Server.GameObjects.Components.PDA; using Content.Server.GameTicking.GamePresets; -using Content.Server.Holiday; -using Content.Server.Holiday.Interfaces; using Content.Server.Interfaces; using Content.Server.Interfaces.Chat; using Content.Server.Interfaces.GameTicking; @@ -80,7 +78,7 @@ namespace Content.Server.GameTicking [ViewVariables] private bool _initialized; - [ViewVariables] private Type _presetType; + [ViewVariables] private Type? _presetType; [ViewVariables] private TimeSpan _pauseTime; [ViewVariables] private bool _roundStartCountdownHasNotStartedYetDueToNoPlayers; @@ -93,7 +91,7 @@ namespace Content.Server.GameTicking [ViewVariables] private bool LobbyEnabled => _configurationManager.GetCVar(CCVars.GameLobbyEnabled); [ViewVariables] private bool _updateOnRoundEnd; - private CancellationTokenSource _updateShutdownCts; + private CancellationTokenSource? _updateShutdownCts; [ViewVariables] public bool Paused { get; private set; } @@ -118,24 +116,24 @@ namespace Content.Server.GameTicking } [ViewVariables] - public GamePreset Preset + public GamePreset? Preset { - get => _preset == null ? MakeGamePreset(null) : _preset; + get => _preset ?? MakeGamePreset(new Dictionary()); set => _preset = value; } - public ImmutableDictionary Presets { get; private set; } + public ImmutableDictionary Presets { get; private set; } = default!; - private GamePreset _preset; + private GamePreset? _preset; - public event Action OnRunLevelChanged; - public event Action OnRuleAdded; + public event Action? OnRunLevelChanged; + public event Action? OnRuleAdded; private TimeSpan LobbyDuration => TimeSpan.FromSeconds(_configurationManager.GetCVar(CCVars.GameLobbyDuration)); private SoundCollectionPrototype _lobbyCollection = default!; - [ViewVariables] public string LobbySong { get; private set; } + [ViewVariables] public string LobbySong { get; private set; } = default!; public override void Initialize() { @@ -356,7 +354,7 @@ namespace Content.Server.GameTicking private void UpdateLateJoinStatus() { - var msg = new MsgTickerLateJoinStatus(null) {Disallowed = DisallowLateJoin}; + var msg = new MsgTickerLateJoinStatus(null!) {Disallowed = DisallowLateJoin}; _netManager.ServerSendToAll(msg); } @@ -382,8 +380,8 @@ namespace Content.Server.GameTicking //Tell every client the round has ended. var roundEndMessage = _netManager.CreateNetMessage(); - roundEndMessage.GamemodeTitle = Preset.ModeTitle; - roundEndMessage.RoundEndText = roundEndText + $"\n{Preset.GetRoundEndDescription()}"; + roundEndMessage.GamemodeTitle = Preset?.ModeTitle ?? string.Empty; + roundEndMessage.RoundEndText = roundEndText + $"\n{Preset?.GetRoundEndDescription() ?? string.Empty}"; //Get the timespan of the round. roundEndMessage.RoundDuration = IoCManager.Resolve().RealTime.Subtract(_roundStartTimeSpan); @@ -392,7 +390,8 @@ namespace Content.Server.GameTicking var listOfPlayerInfo = new List(); foreach (var ply in PlayerManager.GetAllPlayers().OrderBy(p => p.Name)) { - var mind = ply.ContentData().Mind; + var mind = ply.ContentData()?.Mind; + if (mind != null) { _playersInLobby.TryGetValue(ply, out var status); @@ -400,7 +399,7 @@ namespace Content.Server.GameTicking var playerEndRoundInfo = new RoundEndPlayerInfo() { PlayerOOCName = ply.Name, - PlayerICName = mind.CurrentEntity.Name, + PlayerICName = mind.CurrentEntity?.Name, Role = antag ? mind.AllRoles.First(role => role.Antagonist).Name : mind.AllRoles.FirstOrDefault()?.Name ?? Loc.GetString("Unknown"), @@ -417,8 +416,10 @@ namespace Content.Server.GameTicking public void Respawn(IPlayerSession targetPlayer) { - targetPlayer.AttachedEntity.TryGetComponent(out var ghost); + var ghost = targetPlayer.AttachedEntity?.GetComponentOrNull(); + targetPlayer.ContentData()?.WipeMind(); + if (ghost?.Deleted == false) ghost.Owner.Delete(); @@ -437,7 +438,7 @@ namespace Content.Server.GameTicking _netManager.ServerSendToAll(GetStatusSingle(player, PlayerStatus.Observer)); } - public void MakeJoinGame(IPlayerSession player, string jobId = null) + public void MakeJoinGame(IPlayerSession player, string? jobId = null) { if (!_playersInLobby.ContainsKey(player)) return; @@ -473,7 +474,7 @@ namespace Content.Server.GameTicking public bool OnGhostAttempt(Mind mind, bool canReturnGlobal) { - return Preset.OnGhostAttempt(mind, canReturnGlobal); + return Preset?.OnGhostAttempt(mind, canReturnGlobal) ?? false; } public T AddGameRule() where T : GameRule, new() @@ -488,14 +489,30 @@ namespace Content.Server.GameTicking return instance; } - public bool HasGameRule(Type t) + public bool HasGameRule(string? name) { - if (t == null || !typeof(GameRule).IsAssignableFrom(t)) + if (name == null) return false; foreach (var rule in _gameRules) { - if (rule.GetType().IsAssignableFrom(t)) + if (rule.GetType().Name == name) + { + return true; + } + } + + return false; + } + + public bool HasGameRule(Type? type) + { + if (type == null || !typeof(GameRule).IsAssignableFrom(type)) + return false; + + foreach (var rule in _gameRules) + { + if (rule.GetType().IsAssignableFrom(type)) return true; } @@ -513,7 +530,7 @@ namespace Content.Server.GameTicking public IEnumerable ActiveGameRules => _gameRules; - public bool TryGetPreset(string name, [NotNullWhen(true)] out Type type) + public bool TryGetPreset(string name, [NotNullWhen(true)] out Type? type) { name = name.ToLowerInvariant(); return Presets.TryGetValue(name, out type); @@ -597,12 +614,16 @@ namespace Content.Server.GameTicking return Paused; } - private IEntity _spawnPlayerMob(Job job, HumanoidCharacterProfile profile, bool lateJoin = true) + private IEntity _spawnPlayerMob(Job job, HumanoidCharacterProfile? profile, bool lateJoin = true) { var coordinates = lateJoin ? GetLateJoinSpawnPoint() : GetJobSpawnPoint(job.Prototype.ID); var entity = _entityManager.SpawnEntity(PlayerPrototypeName, coordinates); - var startingGear = _prototypeManager.Index(job.StartingGear); - EquipStartingGear(entity, startingGear, profile); + + if (job.StartingGear != null) + { + var startingGear = _prototypeManager.Index(job.StartingGear); + EquipStartingGear(entity, startingGear, profile); + } if (profile != null) { @@ -613,9 +634,9 @@ namespace Content.Server.GameTicking return entity; } - public void EquipStartingGear(IEntity entity, StartingGearPrototype startingGear, HumanoidCharacterProfile profile) + public void EquipStartingGear(IEntity entity, StartingGearPrototype startingGear, HumanoidCharacterProfile? profile) { - if (entity.TryGetComponent(out InventoryComponent inventory)) + if (entity.TryGetComponent(out InventoryComponent? inventory)) { foreach (var slot in AllSlots) { @@ -628,7 +649,7 @@ namespace Content.Server.GameTicking } } - if (entity.TryGetComponent(out HandsComponent handsComponent)) + if (entity.TryGetComponent(out HandsComponent? handsComponent)) { var inhand = startingGear.Inhand; foreach (var (hand, prototype) in inhand) @@ -669,7 +690,7 @@ namespace Content.Server.GameTicking foreach (var entity in _entityManager.GetEntities(new TypeEntityQuery(typeof(SpawnPointComponent)))) { var point = entity.GetComponent(); - if (point.SpawnType == SpawnPointType.Job && point.Job.ID == jobId) + if (point.SpawnType == SpawnPointType.Job && point.Job?.ID == jobId) possiblePoints.Add(entity.Transform.Coordinates); } @@ -754,7 +775,13 @@ namespace Content.Server.GameTicking { DefaultMap = _mapManager.CreateMap(); var startTime = _gameTiming.RealTime; - var grid = _mapLoader.LoadBlueprint(DefaultMap, GetMap()); + var map = GetMap(); + var grid = _mapLoader.LoadBlueprint(DefaultMap, map); + + if (grid == null) + { + throw new InvalidOperationException($"No grid found for map {map}"); + } DefaultGridId = grid.Index; _spawnPoint = grid.ToCoordinates(); @@ -763,7 +790,7 @@ namespace Content.Server.GameTicking Logger.InfoS("ticker", $"Loaded map in {timeSpan.TotalMilliseconds:N2}ms."); } - protected override void PlayerStatusChanged(object sender, SessionStatusEventArgs args) + protected override void PlayerStatusChanged(object? sender, SessionStatusEventArgs args) { base.PlayerStatusChanged(sender, args); @@ -794,7 +821,10 @@ namespace Content.Server.GameTicking _prefsManager.OnClientConnected(session); var data = session.ContentData(); - if (data.Mind == null) + + DebugTools.AssertNotNull(data); + + if (data!.Mind == null) { if (LobbyEnabled) { @@ -871,7 +901,7 @@ namespace Content.Server.GameTicking }, _updateShutdownCts.Token); } - private void SpawnPlayer(IPlayerSession session, string jobId = null, bool lateJoin = true) + private void SpawnPlayer(IPlayerSession session, string? jobId = null, bool lateJoin = true) { var character = GetPlayerProfile(session); @@ -881,7 +911,7 @@ namespace Content.Server.GameTicking private void SpawnPlayer(IPlayerSession session, HumanoidCharacterProfile character, - string jobId = null, + string? jobId = null, bool lateJoin = true) { if (lateJoin && DisallowLateJoin) @@ -893,17 +923,17 @@ namespace Content.Server.GameTicking _playerJoinGame(session); var data = session.ContentData(); - data.WipeMind(); + + DebugTools.AssertNotNull(data); + + data!.WipeMind(); data.Mind = new Mind(session.UserId) { CharacterName = character.Name }; - if (jobId == null) - { - // Pick best job best on prefs. - jobId = PickBestAvailableJob(character); - } + // Pick best job best on prefs. + jobId ??= PickBestAvailableJob(character); var jobPrototype = _prototypeManager.Index(jobId); var job = new Job(data.Mind, jobPrototype); @@ -931,14 +961,14 @@ namespace Content.Server.GameTicking EquipIdCard(mob, character.Name, jobPrototype); jobPrototype.Special?.AfterEquip(mob); - Preset.OnSpawnPlayerCompleted(session, mob, lateJoin); + Preset?.OnSpawnPlayerCompleted(session, mob, lateJoin); } private void EquipIdCard(IEntity mob, string characterName, JobPrototype jobPrototype) { var inventory = mob.GetComponent(); - if (!inventory.TryGetSlotItem(Slots.IDCARD, out ItemComponent pdaItem)) + if (!inventory.TryGetSlotItem(Slots.IDCARD, out ItemComponent? pdaItem)) { return; } @@ -946,7 +976,7 @@ namespace Content.Server.GameTicking var pda = pdaItem.Owner; var pdaComponent = pda.GetComponent(); - if (pdaComponent.IdSlotEmpty) + if (pdaComponent.ContainedID == null) { return; } @@ -973,7 +1003,10 @@ namespace Content.Server.GameTicking var name = GetPlayerProfile(session).Name; var data = session.ContentData(); - data.WipeMind(); + + DebugTools.AssertNotNull(data); + + data!.WipeMind(); data.Mind = new Mind(session.UserId); var mob = _spawnObserverMob(); @@ -1069,6 +1102,11 @@ namespace Content.Server.GameTicking private string GetInfoText() { + if (Preset == null) + { + return string.Empty; + } + var gmTitle = Preset.ModeTitle; var desc = Preset.Description; return Loc.GetString(@"Hi and welcome to [color=white]Space Station 14![/color] diff --git a/Content.Server/GlobalVerbs/AttachToGrandparentVerb.cs b/Content.Server/GlobalVerbs/AttachToGrandparentVerb.cs index 3faca5bf95..ba0a70acce 100644 --- a/Content.Server/GlobalVerbs/AttachToGrandparentVerb.cs +++ b/Content.Server/GlobalVerbs/AttachToGrandparentVerb.cs @@ -20,7 +20,7 @@ namespace Content.Server.GlobalVerbs return; } - if (!user.TryGetComponent(out IActorComponent actor)) + if (!user.TryGetComponent(out IActorComponent? actor)) { return; } @@ -38,7 +38,7 @@ namespace Content.Server.GlobalVerbs public override void Activate(IEntity user, IEntity target) { - if (!user.TryGetComponent(out IActorComponent actor)) + if (!user.TryGetComponent(out IActorComponent? actor)) { return; } diff --git a/Content.Server/GlobalVerbs/AttachToGridVerb.cs b/Content.Server/GlobalVerbs/AttachToGridVerb.cs index 8b6f678750..f803f9e2d3 100644 --- a/Content.Server/GlobalVerbs/AttachToGridVerb.cs +++ b/Content.Server/GlobalVerbs/AttachToGridVerb.cs @@ -19,7 +19,7 @@ namespace Content.Server.GlobalVerbs return; } - if (!user.TryGetComponent(out IActorComponent actor)) + if (!user.TryGetComponent(out IActorComponent? actor)) { return; } @@ -37,7 +37,7 @@ namespace Content.Server.GlobalVerbs public override void Activate(IEntity user, IEntity target) { - if (!user.TryGetComponent(out IActorComponent actor)) + if (!user.TryGetComponent(out IActorComponent? actor)) { return; } diff --git a/Content.Server/GlobalVerbs/AttachToSelf.cs b/Content.Server/GlobalVerbs/AttachToSelf.cs index d10fffff6d..1862621526 100644 --- a/Content.Server/GlobalVerbs/AttachToSelf.cs +++ b/Content.Server/GlobalVerbs/AttachToSelf.cs @@ -19,7 +19,7 @@ namespace Content.Server.GlobalVerbs return; } - if (!user.TryGetComponent(out IActorComponent actor)) + if (!user.TryGetComponent(out IActorComponent? actor)) { return; } @@ -37,7 +37,7 @@ namespace Content.Server.GlobalVerbs public override void Activate(IEntity user, IEntity target) { - if (!user.TryGetComponent(out IActorComponent actor)) + if (!user.TryGetComponent(out IActorComponent? actor)) { return; } diff --git a/Content.Server/GlobalVerbs/ControlMobVerb.cs b/Content.Server/GlobalVerbs/ControlMobVerb.cs index 59973d577b..c28dd69c4a 100644 --- a/Content.Server/GlobalVerbs/ControlMobVerb.cs +++ b/Content.Server/GlobalVerbs/ControlMobVerb.cs @@ -52,15 +52,15 @@ namespace Content.Server.GlobalVerbs return; } - var userMind = player.ContentData().Mind; + var userMind = player.ContentData()?.Mind; var targetMind = target.GetComponent(); - var oldEntity = userMind.CurrentEntity; + var oldEntity = userMind?.CurrentEntity; targetMind.Mind?.TransferTo(null); - userMind.TransferTo(target); + userMind?.TransferTo(target); - if (oldEntity.HasComponent()) + if (oldEntity != null && oldEntity.HasComponent()) oldEntity.Delete(); } } diff --git a/Content.Server/GlobalVerbs/InRangeUnoccludedVerb.cs b/Content.Server/GlobalVerbs/InRangeUnoccludedVerb.cs index b5776980ba..a7b2177165 100644 --- a/Content.Server/GlobalVerbs/InRangeUnoccludedVerb.cs +++ b/Content.Server/GlobalVerbs/InRangeUnoccludedVerb.cs @@ -18,7 +18,7 @@ namespace Content.Server.GlobalVerbs { data.Visibility = VerbVisibility.Invisible; - if (!user.TryGetComponent(out IActorComponent actor)) + if (!user.TryGetComponent(out IActorComponent? actor)) { return; } @@ -36,7 +36,7 @@ namespace Content.Server.GlobalVerbs public override void Activate(IEntity user, IEntity target) { - if (!user.TryGetComponent(out IActorComponent actor)) + if (!user.TryGetComponent(out IActorComponent? actor)) { return; } diff --git a/Content.Server/GlobalVerbs/PointingVerb.cs b/Content.Server/GlobalVerbs/PointingVerb.cs index af5ec92fe7..b2384cf95f 100644 --- a/Content.Server/GlobalVerbs/PointingVerb.cs +++ b/Content.Server/GlobalVerbs/PointingVerb.cs @@ -42,7 +42,7 @@ namespace Content.Server.GlobalVerbs public override void Activate(IEntity user, IEntity target) { - if (!user.TryGetComponent(out IActorComponent actor)) + if (!user.TryGetComponent(out IActorComponent? actor)) { return; } diff --git a/Content.Server/GlobalVerbs/RejuvenateVerb.cs b/Content.Server/GlobalVerbs/RejuvenateVerb.cs index ecfdbf364d..32b6c4e74c 100644 --- a/Content.Server/GlobalVerbs/RejuvenateVerb.cs +++ b/Content.Server/GlobalVerbs/RejuvenateVerb.cs @@ -57,37 +57,37 @@ namespace Content.Server.GlobalVerbs public static void PerformRejuvenate(IEntity target) { - if (target.TryGetComponent(out IDamageableComponent damage)) + if (target.TryGetComponent(out IDamageableComponent? damage)) { damage.Heal(); } - if (target.TryGetComponent(out IMobStateComponent mobState)) + if (target.TryGetComponent(out IMobStateComponent? mobState)) { mobState.UpdateState(0); } - if (target.TryGetComponent(out HungerComponent hunger)) + if (target.TryGetComponent(out HungerComponent? hunger)) { hunger.ResetFood(); } - if (target.TryGetComponent(out ThirstComponent thirst)) + if (target.TryGetComponent(out ThirstComponent? thirst)) { thirst.ResetThirst(); } - if (target.TryGetComponent(out StunnableComponent stun)) + if (target.TryGetComponent(out StunnableComponent? stun)) { stun.ResetStuns(); } - if (target.TryGetComponent(out FlammableComponent flammable)) + if (target.TryGetComponent(out FlammableComponent? flammable)) { flammable.Extinguish(); } - if (target.TryGetComponent(out CreamPiedComponent creamPied)) + if (target.TryGetComponent(out CreamPiedComponent? creamPied)) { creamPied.Wash(); } diff --git a/Content.Server/Holiday/HolidayManager.cs b/Content.Server/Holiday/HolidayManager.cs index 803a5965a6..8824a300b4 100644 --- a/Content.Server/Holiday/HolidayManager.cs +++ b/Content.Server/Holiday/HolidayManager.cs @@ -64,7 +64,7 @@ namespace Content.Server.Holiday public bool IsCurrentlyHoliday(string holiday) { - if (!_prototypeManager.TryIndex(holiday, out HolidayPrototype prototype)) + if (!_prototypeManager.TryIndex(holiday, out HolidayPrototype? prototype)) return false; return _currentHolidays.Contains(prototype); diff --git a/Content.Server/Interfaces/GameObjects/IDisarmedAct.cs b/Content.Server/Interfaces/GameObjects/IDisarmedAct.cs index f09be5245d..e54db3d6a6 100644 --- a/Content.Server/Interfaces/GameObjects/IDisarmedAct.cs +++ b/Content.Server/Interfaces/GameObjects/IDisarmedAct.cs @@ -29,12 +29,12 @@ namespace Content.Server.Interfaces.GameObjects /// /// The entity being disarmed. /// - public IEntity Target { get; init; } + public IEntity? Target { get; init; } /// /// The entity performing the disarm. /// - public IEntity Source { get; init; } + public IEntity? Source { get; init; } /// /// Probability for push/knockdown. diff --git a/Content.Server/Interfaces/GameTicking/IGameTicker.cs b/Content.Server/Interfaces/GameTicking/IGameTicker.cs index e719f55020..f72a62a6e9 100644 --- a/Content.Server/Interfaces/GameTicking/IGameTicker.cs +++ b/Content.Server/Interfaces/GameTicking/IGameTicker.cs @@ -3,8 +3,8 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Content.Server.GameTicking; using Content.Server.Mobs; -using Content.Shared.Roles; using Content.Shared.Preferences; +using Content.Shared.Roles; using Robust.Server.Player; using Robust.Shared.GameObjects; using Robust.Shared.Map; @@ -41,7 +41,7 @@ namespace Content.Server.Interfaces.GameTicking void Respawn(IPlayerSession targetPlayer); void MakeObserve(IPlayerSession player); - void MakeJoinGame(IPlayerSession player, string jobId); + void MakeJoinGame(IPlayerSession player, string? jobId = null); void ToggleReady(IPlayerSession player, bool ready); void ToggleDisallowLateJoin(bool disallowLateJoin); @@ -52,15 +52,16 @@ namespace Content.Server.Interfaces.GameTicking EntityCoordinates GetJobSpawnPoint(string jobId); EntityCoordinates GetObserverSpawnPoint(); - void EquipStartingGear(IEntity entity, StartingGearPrototype startingGear, HumanoidCharacterProfile profile); + void EquipStartingGear(IEntity entity, StartingGearPrototype startingGear, HumanoidCharacterProfile? profile); // GameRule system. T AddGameRule() where T : GameRule, new(); - bool HasGameRule(Type type); + bool HasGameRule(string? type); + bool HasGameRule(Type? type); void RemoveGameRule(GameRule rule); IEnumerable ActiveGameRules { get; } - bool TryGetPreset(string name, [NotNullWhen(true)] out Type type); + bool TryGetPreset(string name, [NotNullWhen(true)] out Type? type); void SetStartPreset(Type type, bool force = false); void SetStartPreset(string name, bool force = false); diff --git a/Content.Server/MoMMILink.cs b/Content.Server/MoMMILink.cs index d66ece3f4d..7f2a7aa062 100644 --- a/Content.Server/MoMMILink.cs +++ b/Content.Server/MoMMILink.cs @@ -87,7 +87,7 @@ namespace Content.Server return true; } - OOCPostMessage message = null; + OOCPostMessage? message = null; try { message = context.RequestBodyJson(); @@ -119,30 +119,30 @@ namespace Content.Server [JsonObject(MemberSerialization.Fields)] private class MoMMIMessageBase { - [JsonProperty("password")] public string Password; + [JsonProperty("password")] public string Password = null!; - [JsonProperty("type")] public string Type; + [JsonProperty("type")] public string Type = null!; - [JsonProperty("contents")] public object Contents; + [JsonProperty("contents")] public object Contents = null!; } [JsonObject(MemberSerialization.Fields)] private class MoMMIMessageOOC { - [JsonProperty("sender")] public string Sender; + [JsonProperty("sender")] public string Sender = null!; - [JsonProperty("contents")] public string Contents; + [JsonProperty("contents")] public string Contents = null!; } [JsonObject(MemberSerialization.Fields, ItemRequired = Required.Always)] private class OOCPostMessage { #pragma warning disable CS0649 - [JsonProperty("password")] public string Password; + [JsonProperty("password")] public string Password = null!; - [JsonProperty("sender")] public string Sender; + [JsonProperty("sender")] public string Sender = null!; - [JsonProperty("contents")] public string Contents; + [JsonProperty("contents")] public string Contents = null!; #pragma warning restore CS0649 } } diff --git a/Content.Server/Mobs/Mind.cs b/Content.Server/Mobs/Mind.cs index 36b625ef00..17db9bf2ce 100644 --- a/Content.Server/Mobs/Mind.cs +++ b/Content.Server/Mobs/Mind.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using Content.Server.GameObjects.Components.Mobs; using Content.Server.GameObjects.Components.Observer; @@ -11,6 +12,7 @@ using Robust.Server.Player; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Network; +using Robust.Shared.Utility; using Robust.Shared.ViewVariables; namespace Content.Server.Mobs @@ -51,26 +53,26 @@ namespace Content.Server.Mobs public bool IsVisitingEntity => VisitingEntity != null; [ViewVariables] - public IEntity VisitingEntity { get; private set; } + public IEntity? VisitingEntity { get; private set; } - [ViewVariables] public IEntity CurrentEntity => VisitingEntity ?? OwnedEntity; + [ViewVariables] public IEntity? CurrentEntity => VisitingEntity ?? OwnedEntity; [ViewVariables(VVAccess.ReadWrite)] - public string CharacterName { get; set; } + public string? CharacterName { get; set; } /// /// The component currently owned by this mind. /// Can be null. /// [ViewVariables] - public MindComponent OwnedComponent { get; private set; } + public MindComponent? OwnedComponent { get; private set; } /// /// The entity currently owned by this mind. /// Can be null. /// [ViewVariables] - public IEntity OwnedEntity => OwnedComponent?.Owner; + public IEntity? OwnedEntity => OwnedComponent?.Owner; /// /// An enumerable over all the roles this mind has. @@ -89,7 +91,7 @@ namespace Content.Server.Mobs /// Can be null, in which case the player is currently not logged in. /// [ViewVariables] - public IPlayerSession Session + public IPlayerSession? Session { get { @@ -193,10 +195,11 @@ namespace Content.Server.Mobs /// /// Thrown if is already owned by another mind. /// - public void TransferTo(IEntity entity) + public void TransferTo(IEntity? entity) { - MindComponent component = null; - bool alreadyAttached = false; + MindComponent? component = null; + var alreadyAttached = false; + if (entity != null) { if (!entity.TryGetComponent(out component)) @@ -209,7 +212,7 @@ namespace Content.Server.Mobs throw new ArgumentException("That entity already has a mind.", nameof(entity)); } - if (entity.TryGetComponent(out IActorComponent actor)) + if (entity.TryGetComponent(out IActorComponent? actor)) { // Happens when transferring to your currently visited entity. if (actor.playerSession != Session) @@ -244,7 +247,8 @@ namespace Content.Server.Mobs public void ChangeOwningPlayer(NetUserId? newOwner) { var playerMgr = IoCManager.Resolve(); - PlayerData newOwnerData = null; + PlayerData? newOwnerData = null; + if (newOwner.HasValue) { if (!playerMgr.TryGetPlayerData(newOwner.Value, out var uncast)) @@ -264,7 +268,9 @@ namespace Content.Server.Mobs if (UserId.HasValue) { - playerMgr.GetPlayerData(UserId.Value).ContentData().Mind = null; + var data = playerMgr.GetPlayerData(UserId.Value).ContentData(); + DebugTools.AssertNotNull(data); + data!.Mind = null; } UserId = newOwner; @@ -275,7 +281,8 @@ namespace Content.Server.Mobs // Yank new owner out of their old mind too. // Can I mention how much I love the word yank? - newOwnerData.Mind?.ChangeOwningPlayer(null); + DebugTools.AssertNotNull(newOwnerData); + newOwnerData!.Mind?.ChangeOwningPlayer(null); newOwnerData.Mind = this; } @@ -300,10 +307,17 @@ namespace Content.Server.Mobs // Null this before removing the component to avoid any infinite loops. VisitingEntity = null; - if (oldVisitingEnt.HasComponent()) + DebugTools.AssertNotNull(oldVisitingEnt); + + if (oldVisitingEnt!.HasComponent()) { oldVisitingEnt.RemoveComponent(); } } + + public bool TryGetSession([NotNullWhen(true)] out IPlayerSession? session) + { + return (session = Session) != null; + } } } diff --git a/Content.Server/Mobs/Roles/Job.cs b/Content.Server/Mobs/Roles/Job.cs index 064bb3d769..700664caa2 100644 --- a/Content.Server/Mobs/Roles/Job.cs +++ b/Content.Server/Mobs/Roles/Job.cs @@ -11,7 +11,7 @@ namespace Content.Server.Mobs.Roles public override string Name { get; } public override bool Antagonist => false; - public string StartingGear => Prototype.StartingGear; + public string? StartingGear => Prototype.StartingGear; public Job(Mind mind, JobPrototype jobPrototype) : base(mind) { @@ -23,10 +23,11 @@ namespace Content.Server.Mobs.Roles { base.Greet(); - var chat = IoCManager.Resolve(); - chat.DispatchServerMessage(Mind.Session, $"You're a new {Name}. Do your best!"); + if (Mind.TryGetSession(out var session)) + { + var chat = IoCManager.Resolve(); + chat.DispatchServerMessage(session, $"You're a new {Name}. Do your best!"); + } } } - - } diff --git a/Content.Server/Mobs/Roles/Suspicion/SuspicionInnocentRole.cs b/Content.Server/Mobs/Roles/Suspicion/SuspicionInnocentRole.cs index 0fab5b7059..1fa9fe44aa 100644 --- a/Content.Server/Mobs/Roles/Suspicion/SuspicionInnocentRole.cs +++ b/Content.Server/Mobs/Roles/Suspicion/SuspicionInnocentRole.cs @@ -24,8 +24,12 @@ namespace Content.Server.Mobs.Roles.Suspicion base.Greet(); var chat = IoCManager.Resolve(); - chat.DispatchServerMessage(Mind.Session, $"You're an {Name}!"); - chat.DispatchServerMessage(Mind.Session, $"Objective: {Objective}"); + + if (Mind.TryGetSession(out var session)) + { + chat.DispatchServerMessage(session, $"You're an {Name}!"); + chat.DispatchServerMessage(session, $"Objective: {Objective}"); + } } } } diff --git a/Content.Server/Mobs/Roles/Suspicion/SuspicionTraitorRole.cs b/Content.Server/Mobs/Roles/Suspicion/SuspicionTraitorRole.cs index eee12e1af0..f88ed3078b 100644 --- a/Content.Server/Mobs/Roles/Suspicion/SuspicionTraitorRole.cs +++ b/Content.Server/Mobs/Roles/Suspicion/SuspicionTraitorRole.cs @@ -23,18 +23,21 @@ namespace Content.Server.Mobs.Roles.Suspicion public void GreetSuspicion(List traitors, IChatManager chatMgr) { - chatMgr.DispatchServerMessage(Mind.Session, Loc.GetString("suspicion-role-greeting", ("roleName", Name))); - chatMgr.DispatchServerMessage(Mind.Session, Loc.GetString("suspicion-objective", ("objectiveText", Objective))); + if (Mind.TryGetSession(out var session)) + { + chatMgr.DispatchServerMessage(session, Loc.GetString("suspicion-role-greeting", ("roleName", Name))); + chatMgr.DispatchServerMessage(session, Loc.GetString("suspicion-objective", ("objectiveText", Objective))); - var allPartners = string.Join(", ", traitors.Where(p => p != this).Select(p => p.Mind.CharacterName)); + var allPartners = string.Join(", ", traitors.Where(p => p != this).Select(p => p.Mind.CharacterName)); - var partnerText = Loc.GetString( - "suspicion-partners-in-crime", - ("partnerCount", traitors.Count-1), - ("partnerNames", allPartners) - ); + var partnerText = Loc.GetString( + "suspicion-partners-in-crime", + ("partnerCount", traitors.Count-1), + ("partnerNames", allPartners) + ); - chatMgr.DispatchServerMessage(Mind.Session, partnerText); + chatMgr.DispatchServerMessage(session, partnerText); + } } } } diff --git a/Content.Server/Mobs/Roles/Traitor/TraitorRole.cs b/Content.Server/Mobs/Roles/Traitor/TraitorRole.cs index 0458c7ad6c..9e79da38aa 100644 --- a/Content.Server/Mobs/Roles/Traitor/TraitorRole.cs +++ b/Content.Server/Mobs/Roles/Traitor/TraitorRole.cs @@ -15,9 +15,12 @@ namespace Content.Server.Mobs.Roles.Traitor public void GreetTraitor(string[] codewords) { - var chatMgr = IoCManager.Resolve(); - chatMgr.DispatchServerMessage(Mind.Session, Loc.GetString("Hello Agent!")); - chatMgr.DispatchServerMessage(Mind.Session, Loc.GetString("Your codewords are: {0}", string.Join(", ",codewords))); + if (Mind.TryGetSession(out var session)) + { + var chatMgr = IoCManager.Resolve(); + chatMgr.DispatchServerMessage(session, Loc.GetString("Hello Agent!")); + chatMgr.DispatchServerMessage(session, Loc.GetString("Your codewords are: {0}", string.Join(", ",codewords))); + } } } } diff --git a/Content.Server/Objectives/Conditions/KillPersonCondition.cs b/Content.Server/Objectives/Conditions/KillPersonCondition.cs index 7e7bd0a76c..9848e23b1b 100644 --- a/Content.Server/Objectives/Conditions/KillPersonCondition.cs +++ b/Content.Server/Objectives/Conditions/KillPersonCondition.cs @@ -12,7 +12,7 @@ namespace Content.Server.Objectives.Conditions protected Mind? Target; public abstract IObjectiveCondition GetAssigned(Mind mind); - public string Title => Loc.GetString("Kill {0}", Target?.OwnedEntity.Name ?? ""); + public string Title => Loc.GetString("Kill {0}", Target?.OwnedEntity?.Name ?? ""); public string Description => Loc.GetString("Do it however you like, just make sure they don't last the shift."); diff --git a/Content.Server/Objectives/Interfaces/IObjectivesManager.cs b/Content.Server/Objectives/Interfaces/IObjectivesManager.cs index 84250ed956..ff17b1a432 100644 --- a/Content.Server/Objectives/Interfaces/IObjectivesManager.cs +++ b/Content.Server/Objectives/Interfaces/IObjectivesManager.cs @@ -13,6 +13,6 @@ namespace Content.Server.Objectives.Interfaces /// /// Returns a randomly picked objective the provided mind is valid for. /// - ObjectivePrototype GetRandomObjective(Mind mind); + ObjectivePrototype? GetRandomObjective(Mind mind); } } diff --git a/Content.Server/Objectives/Objective.cs b/Content.Server/Objectives/Objective.cs index 59cd15f2e5..a2ede4e756 100644 --- a/Content.Server/Objectives/Objective.cs +++ b/Content.Server/Objectives/Objective.cs @@ -26,7 +26,7 @@ namespace Content.Server.Objectives } } - public bool Equals(Objective other) + public bool Equals(Objective? other) { if (other is null) return false; if (ReferenceEquals(this, other)) return true; @@ -40,7 +40,7 @@ namespace Content.Server.Objectives return true; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; diff --git a/Content.Server/Sandbox/SandboxManager.cs b/Content.Server/Sandbox/SandboxManager.cs index 412519dbef..b147f77f99 100644 --- a/Content.Server/Sandbox/SandboxManager.cs +++ b/Content.Server/Sandbox/SandboxManager.cs @@ -83,7 +83,7 @@ namespace Content.Server.Sandbox } } - private void OnPlayerStatusChanged(object sender, SessionStatusEventArgs e) + private void OnPlayerStatusChanged(object? sender, SessionStatusEventArgs e) { if (e.NewStatus != SessionStatus.Connected || e.OldStatus != SessionStatus.Connecting) { @@ -123,14 +123,14 @@ namespace Content.Server.Sandbox .EnumeratePrototypes() .Select(p => p.ID).ToArray(); - if (player.AttachedEntity.TryGetComponent(out InventoryComponent inv) - && inv.TryGetSlotItem(Slots.IDCARD, out ItemComponent wornItem)) + if (player.AttachedEntity.TryGetComponent(out InventoryComponent? inv) + && inv.TryGetSlotItem(Slots.IDCARD, out ItemComponent? wornItem)) { if (wornItem.Owner.HasComponent()) { UpgradeId(wornItem.Owner); } - else if (wornItem.Owner.TryGetComponent(out PDAComponent pda)) + else if (wornItem.Owner.TryGetComponent(out PDAComponent? pda)) { if (pda.ContainedID == null) { @@ -156,7 +156,7 @@ namespace Content.Server.Sandbox var access = id.GetComponent(); access.SetTags(allAccess); - if (id.TryGetComponent(out SpriteComponent sprite)) + if (id.TryGetComponent(out SpriteComponent? sprite)) { sprite.LayerSetState(0, "gold"); } diff --git a/Content.Server/ServerModuleTestingCallbacks.cs b/Content.Server/ServerModuleTestingCallbacks.cs index 4777389700..c40196e8b8 100644 --- a/Content.Server/ServerModuleTestingCallbacks.cs +++ b/Content.Server/ServerModuleTestingCallbacks.cs @@ -5,6 +5,6 @@ namespace Content.Server { public sealed class ServerModuleTestingCallbacks : SharedModuleTestingCallbacks { - public Action ServerBeforeIoC { get; set; } + public Action? ServerBeforeIoC { get; set; } } } diff --git a/Content.Server/ServerNotifyManager.cs b/Content.Server/ServerNotifyManager.cs index f3772b4fde..e7a5e2e58f 100644 --- a/Content.Server/ServerNotifyManager.cs +++ b/Content.Server/ServerNotifyManager.cs @@ -28,7 +28,7 @@ namespace Content.Server public override void PopupMessage(IEntity source, IEntity viewer, string message) { - if (!viewer.TryGetComponent(out IActorComponent actor)) + if (!viewer.TryGetComponent(out IActorComponent? actor)) { return; } @@ -42,7 +42,7 @@ namespace Content.Server public override void PopupMessage(EntityCoordinates coordinates, IEntity viewer, string message) { - if (!viewer.TryGetComponent(out IActorComponent actor)) + if (!viewer.TryGetComponent(out IActorComponent? actor)) { return; } @@ -56,7 +56,7 @@ namespace Content.Server public override void PopupMessageCursor(IEntity viewer, string message) { - if (!viewer.TryGetComponent(out IActorComponent actor)) + if (!viewer.TryGetComponent(out IActorComponent? actor)) { return; } diff --git a/Content.Server/Utility/InventoryHelpers.cs b/Content.Server/Utility/InventoryHelpers.cs index 43135b9779..5e3874d725 100644 --- a/Content.Server/Utility/InventoryHelpers.cs +++ b/Content.Server/Utility/InventoryHelpers.cs @@ -37,7 +37,7 @@ namespace Content.Server.Utility } // If this doesn't have an item component, then we can't do anything with it. - if (!item.TryGetComponent(out ItemComponent itemComp)) + if (!item.TryGetComponent(out ItemComponent? itemComp)) return DeleteItem(); // We finally try to equip the item, otherwise we delete it. diff --git a/Content.Server/Utility/NotifyExtensions.cs b/Content.Server/Utility/NotifyExtensions.cs index 7fa24c95d3..3cd7eb74bf 100644 --- a/Content.Server/Utility/NotifyExtensions.cs +++ b/Content.Server/Utility/NotifyExtensions.cs @@ -20,7 +20,7 @@ namespace Content.Server.Utility /// /// The range in which to search for players, defaulting to one screen. /// - public static void PopupMessageOtherClients(this IEntity source, string message, IPlayerManager playerManager = null, int range = 15) + public static void PopupMessageOtherClients(this IEntity source, string message, IPlayerManager? playerManager = null, int range = 15) { playerManager ??= IoCManager.Resolve(); @@ -30,7 +30,7 @@ namespace Content.Server.Utility { var viewerEntity = viewer.AttachedEntity; - if (viewerEntity == null || source == viewerEntity) + if (viewerEntity == null || source == viewerEntity || viewer.AttachedEntity == null) { continue; } @@ -52,7 +52,7 @@ namespace Content.Server.Utility /// /// The range in which to search for players, defaulting to one screen. /// - public static void PopupMessageEveryone(this IEntity source, string message, IPlayerManager playerManager = null, int range = 15) + public static void PopupMessageEveryone(this IEntity source, string message, IPlayerManager? playerManager = null, int range = 15) { source.PopupMessage(message); source.PopupMessageOtherClients(message, playerManager, range); diff --git a/Content.Server/Utility/SnapgridHelper.cs b/Content.Server/Utility/SnapgridHelper.cs index e2420b4883..414c2d9a54 100644 --- a/Content.Server/Utility/SnapgridHelper.cs +++ b/Content.Server/Utility/SnapgridHelper.cs @@ -7,13 +7,13 @@ namespace Content.Server.Utility { public static class SnapgridHelper { - public static void SnapToGrid(this IEntity entity, SnapGridOffset offset = SnapGridOffset.Center, IEntityManager entityManager = null, IMapManager mapManager = null) + public static void SnapToGrid(this IEntity entity, SnapGridOffset offset = SnapGridOffset.Center, IEntityManager? entityManager = null, IMapManager? mapManager = null) { entity.Transform.Coordinates = entity.Transform.Coordinates.SnapToGrid(offset, entityManager, mapManager); } public static EntityCoordinates SnapToGrid(this EntityCoordinates coordinates, - SnapGridOffset offset = SnapGridOffset.Center, IEntityManager entityManager = null, IMapManager mapManager = null) + SnapGridOffset offset = SnapGridOffset.Center, IEntityManager? entityManager = null, IMapManager? mapManager = null) { entityManager ??= IoCManager.Resolve(); mapManager ??= IoCManager.Resolve(); diff --git a/Content.Shared/GameObjects/Components/Cargo/SharedCargoOrderDatabaseComponent.cs b/Content.Shared/GameObjects/Components/Cargo/SharedCargoOrderDatabaseComponent.cs index fa269fe624..a309ed23bb 100644 --- a/Content.Shared/GameObjects/Components/Cargo/SharedCargoOrderDatabaseComponent.cs +++ b/Content.Shared/GameObjects/Components/Cargo/SharedCargoOrderDatabaseComponent.cs @@ -16,8 +16,9 @@ namespace Content.Shared.GameObjects.Components.Cargo [NetSerializable, Serializable] public class CargoOrderDatabaseState : ComponentState { - public readonly List Orders; - public CargoOrderDatabaseState(List orders) : base(ContentNetIDs.CARGO_ORDER_DATABASE) + public readonly List? Orders; + + public CargoOrderDatabaseState(List? orders) : base(ContentNetIDs.CARGO_ORDER_DATABASE) { Orders = orders; } diff --git a/Content.Shared/GameObjects/Components/Items/ClothingComponentState.cs b/Content.Shared/GameObjects/Components/Items/ClothingComponentState.cs index 7af4fca1cf..eab5ff6d90 100644 --- a/Content.Shared/GameObjects/Components/Items/ClothingComponentState.cs +++ b/Content.Shared/GameObjects/Components/Items/ClothingComponentState.cs @@ -7,9 +7,9 @@ namespace Content.Shared.GameObjects.Components.Items [Serializable, NetSerializable] public class ClothingComponentState : ItemComponentState { - public string ClothingEquippedPrefix { get; set; } + public string? ClothingEquippedPrefix { get; set; } - public ClothingComponentState(string clothingEquippedPrefix, string equippedPrefix) : base(equippedPrefix, ContentNetIDs.CLOTHING) + public ClothingComponentState(string? clothingEquippedPrefix, string? equippedPrefix) : base(equippedPrefix, ContentNetIDs.CLOTHING) { ClothingEquippedPrefix = clothingEquippedPrefix; } diff --git a/Content.Shared/GameObjects/Components/Items/ItemComponentState.cs b/Content.Shared/GameObjects/Components/Items/ItemComponentState.cs index 329fa684be..e601c8d58b 100644 --- a/Content.Shared/GameObjects/Components/Items/ItemComponentState.cs +++ b/Content.Shared/GameObjects/Components/Items/ItemComponentState.cs @@ -8,14 +8,14 @@ namespace Content.Shared.GameObjects.Components.Items [Serializable, NetSerializable] public class ItemComponentState : ComponentState { - public string EquippedPrefix { get; set; } + public string? EquippedPrefix { get; set; } - public ItemComponentState(string equippedPrefix) : base(ContentNetIDs.ITEM) + public ItemComponentState(string? equippedPrefix) : base(ContentNetIDs.ITEM) { EquippedPrefix = equippedPrefix; } - protected ItemComponentState(string equippedPrefix, uint netId) : base(netId) + protected ItemComponentState(string? equippedPrefix, uint netId) : base(netId) { EquippedPrefix = equippedPrefix; } diff --git a/Content.Shared/GameObjects/Components/Medical/SharedCloningPodComponent.cs b/Content.Shared/GameObjects/Components/Medical/SharedCloningPodComponent.cs index f3efe7ec2d..0139e7f554 100644 --- a/Content.Shared/GameObjects/Components/Medical/SharedCloningPodComponent.cs +++ b/Content.Shared/GameObjects/Components/Medical/SharedCloningPodComponent.cs @@ -13,11 +13,11 @@ namespace Content.Shared.GameObjects.Components.Medical [Serializable, NetSerializable] public class CloningPodBoundUserInterfaceState : BoundUserInterfaceState { - public readonly Dictionary MindIdName; + public readonly Dictionary MindIdName; public readonly float Progress; public readonly bool MindPresent; - public CloningPodBoundUserInterfaceState(Dictionary mindIdName, float progress, bool mindPresent) + public CloningPodBoundUserInterfaceState(Dictionary mindIdName, float progress, bool mindPresent) { MindIdName = mindIdName; Progress = progress; diff --git a/Content.Shared/GameObjects/Components/Weapons/Ranged/Barrels/SharedBoltActionBarrelComponent.cs b/Content.Shared/GameObjects/Components/Weapons/Ranged/Barrels/SharedBoltActionBarrelComponent.cs index 0e61684769..96c4c4729e 100644 --- a/Content.Shared/GameObjects/Components/Weapons/Ranged/Barrels/SharedBoltActionBarrelComponent.cs +++ b/Content.Shared/GameObjects/Components/Weapons/Ranged/Barrels/SharedBoltActionBarrelComponent.cs @@ -11,13 +11,13 @@ namespace Content.Shared.GameObjects.Components.Weapons.Ranged.Barrels public (bool chambered, bool spent) Chamber { get; } public FireRateSelector FireRateSelector { get; } public (int count, int max)? Magazine { get; } - public string SoundGunshot { get; } + public string? SoundGunshot { get; } public BoltActionBarrelComponentState( (bool chambered, bool spent) chamber, FireRateSelector fireRateSelector, (int count, int max)? magazine, - string soundGunshot) : + string? soundGunshot) : base(ContentNetIDs.BOLTACTION_BARREL) { Chamber = chamber; diff --git a/Content.Shared/GameObjects/Components/Weapons/Ranged/Barrels/SharedMagazineBarrelComponent.cs b/Content.Shared/GameObjects/Components/Weapons/Ranged/Barrels/SharedMagazineBarrelComponent.cs index e317db57ee..c4ace6ed47 100644 --- a/Content.Shared/GameObjects/Components/Weapons/Ranged/Barrels/SharedMagazineBarrelComponent.cs +++ b/Content.Shared/GameObjects/Components/Weapons/Ranged/Barrels/SharedMagazineBarrelComponent.cs @@ -31,13 +31,13 @@ namespace Content.Shared.GameObjects.Components.Weapons.Ranged.Barrels public bool Chambered { get; } public FireRateSelector FireRateSelector { get; } public (int count, int max)? Magazine { get; } - public string SoundGunshot { get; } + public string? SoundGunshot { get; } public MagazineBarrelComponentState( bool chambered, FireRateSelector fireRateSelector, (int count, int max)? magazine, - string soundGunshot) : + string? soundGunshot) : base(ContentNetIDs.MAGAZINE_BARREL) { Chambered = chambered; diff --git a/Content.Shared/GameObjects/Components/Weapons/Ranged/Barrels/SharedPumpBarrelComponent.cs b/Content.Shared/GameObjects/Components/Weapons/Ranged/Barrels/SharedPumpBarrelComponent.cs index 30ce26a2ea..073a317cb1 100644 --- a/Content.Shared/GameObjects/Components/Weapons/Ranged/Barrels/SharedPumpBarrelComponent.cs +++ b/Content.Shared/GameObjects/Components/Weapons/Ranged/Barrels/SharedPumpBarrelComponent.cs @@ -11,13 +11,13 @@ namespace Content.Shared.GameObjects.Components.Weapons.Ranged.Barrels public (bool chambered, bool spent) Chamber { get; } public FireRateSelector FireRateSelector { get; } public (int count, int max)? Magazine { get; } - public string SoundGunshot { get; } + public string? SoundGunshot { get; } public PumpBarrelComponentState( (bool chambered, bool spent) chamber, FireRateSelector fireRateSelector, (int count, int max)? magazine, - string soundGunshot) : + string? soundGunshot) : base(ContentNetIDs.PUMP_BARREL) { Chamber = chamber; diff --git a/Content.Shared/GameObjects/Components/Weapons/Ranged/Barrels/SharedRevolverBarrelComponent.cs b/Content.Shared/GameObjects/Components/Weapons/Ranged/Barrels/SharedRevolverBarrelComponent.cs index a26e0250da..bb8921458b 100644 --- a/Content.Shared/GameObjects/Components/Weapons/Ranged/Barrels/SharedRevolverBarrelComponent.cs +++ b/Content.Shared/GameObjects/Components/Weapons/Ranged/Barrels/SharedRevolverBarrelComponent.cs @@ -11,13 +11,13 @@ namespace Content.Shared.GameObjects.Components.Weapons.Ranged.Barrels public int CurrentSlot { get; } public FireRateSelector FireRateSelector { get; } public bool?[] Bullets { get; } - public string SoundGunshot { get; } + public string? SoundGunshot { get; } public RevolverBarrelComponentState( int currentSlot, FireRateSelector fireRateSelector, bool?[] bullets, - string soundGunshot) : + string? soundGunshot) : base(ContentNetIDs.REVOLVER_BARREL) { CurrentSlot = currentSlot; diff --git a/Content.Shared/GameTicking/SharedGameTicker.cs b/Content.Shared/GameTicking/SharedGameTicker.cs index ec62578352..596cffb12d 100644 --- a/Content.Shared/GameTicking/SharedGameTicker.cs +++ b/Content.Shared/GameTicking/SharedGameTicker.cs @@ -277,7 +277,7 @@ namespace Content.Shared.GameTicking public struct RoundEndPlayerInfo { public string PlayerOOCName; - public string PlayerICName; + public string? PlayerICName; public string Role; public bool Antag; public bool Observer;