return;
component.Actions.Clear();
- component.Actions.UnionWith(state.Actions);
+ component.Actions.UnionWith(GetEntitySet(state.Actions));
_actionHoldersQueue.Enqueue(uid);
}
- protected override void AddActionInternal(EntityUid holderId, EntityUid actionId, IContainer container, ActionsComponent holder)
+ protected override void AddActionInternal(EntityUid holderId, EntityUid actionId, BaseContainer container, ActionsComponent holder)
{
// Sometimes the client receives actions from the server, before predicting that newly added components will add
// their own shared actions. Just in case those systems ever decided to directly access action properties (e.g.,
}
}
- public override void AddAction(EntityUid holderId, EntityUid actionId, EntityUid? provider, ActionsComponent? holder = null, BaseActionComponent? action = null, bool dirty = true, IContainer? actionContainer = null)
+ public override void AddAction(EntityUid holderId, EntityUid actionId, EntityUid? provider, ActionsComponent? holder = null, BaseActionComponent? action = null, bool dirty = true, BaseContainer? actionContainer = null)
{
if (!Resolve(holderId, ref holder, false))
return;
}
else
{
- var request = new RequestPerformActionEvent(actionId);
+ var request = new RequestPerformActionEvent(GetNetEntity(actionId));
EntityManager.RaisePredictiveEvent(request);
}
}
foreach (var playerInfo in _system.PlayerList)
{
+ var entity = _entityManager.GetEntity(playerInfo.NetEntity);
+
// Otherwise the entity can not exist yet
- if (!_entityManager.EntityExists(playerInfo.EntityUid))
+ if (entity == null || !_entityManager.EntityExists(entity))
{
continue;
}
- var entity = playerInfo.EntityUid.Value;
// if not on the same map, continue
- if (_entityManager.GetComponent<TransformComponent>(entity).MapID != _eyeManager.CurrentMap)
+ if (_entityManager.GetComponent<TransformComponent>(entity.Value).MapID != _eyeManager.CurrentMap)
{
continue;
}
- var aabb = _entityLookup.GetWorldAABB(entity);
+ var aabb = _entityLookup.GetWorldAABB(entity.Value);
// if not on screen, continue
if (!aabb.Intersects(in viewport))
// View variables verbs
if (_clientConGroupController.CanViewVar())
{
- Verb verb = new();
- verb.Category = VerbCategory.Debug;
- verb.Text = "View Variables";
- verb.Icon = new SpriteSpecifier.Texture(new ("/Textures/Interface/VerbIcons/vv.svg.192dpi.png"));
- verb.Act = () => _clientConsoleHost.ExecuteCommand($"vv {args.Target}");
- verb.ClientExclusive = true; // opening VV window is client-side. Don't ask server to run this verb.
+ Verb verb = new()
+ {
+ Category = VerbCategory.Debug,
+ Text = "View Variables",
+ Icon = new SpriteSpecifier.Texture(new ("/Textures/Interface/VerbIcons/vv.svg.192dpi.png")),
+ Act = () => _clientConsoleHost.ExecuteCommand($"vv {GetNetEntity(args.Target)}"),
+ ClientExclusive = true // opening VV window is client-side. Don't ask server to run this verb.
+ };
args.Verbs.Add(verb);
}
}
public sealed partial class PlayerListControl : BoxContainer
{
private readonly AdminSystem _adminSystem;
- private readonly VerbSystem _verbSystem;
private List<PlayerInfo> _playerList = new();
private readonly List<PlayerInfo> _sortedPlayerList = new();
public Func<PlayerInfo, string, string>? OverrideText;
public Comparison<PlayerInfo>? Comparison;
+ private IEntityManager _entManager;
+ private IUserInterfaceManager _uiManager;
+
public PlayerListControl()
{
- _adminSystem = EntitySystem.Get<AdminSystem>();
- _verbSystem = EntitySystem.Get<VerbSystem>();
- IoCManager.InjectDependencies(this);
+ _entManager = IoCManager.Resolve<IEntityManager>();
+ _uiManager = IoCManager.Resolve<IUserInterfaceManager>();
+ _adminSystem = _entManager.System<AdminSystem>();
RobustXamlLoader.Load(this);
// Fill the Option data
PlayerListContainer.ItemPressed += PlayerListItemPressed;
if (OverrideText != null && args.Button.Children.FirstOrDefault()?.Children?.FirstOrDefault() is Label label)
label.Text = GetText(selectedPlayer);
}
- else if (args.Event.Function == EngineKeyFunctions.UseSecondary && selectedPlayer.EntityUid != null)
+ else if (args.Event.Function == EngineKeyFunctions.UseSecondary && selectedPlayer.NetEntity != null)
{
- IoCManager.Resolve<IUserInterfaceManager>().GetUIController<VerbMenuUIController>().OpenVerbMenu(selectedPlayer.EntityUid.Value);
+ _uiManager.GetUIController<VerbMenuUIController>().OpenVerbMenu(_entManager.GetEntity(selectedPlayer.NetEntity.Value));
}
}
public sealed class EditSolutionsEui : BaseEui
{
private readonly EditSolutionsWindow _window;
+ private IEntityManager _entManager;
public EditSolutionsEui()
{
+ _entManager = IoCManager.Resolve<IEntityManager>();
_window = new EditSolutionsWindow();
_window.OnClose += () => SendMessage(new CloseEuiMessage());
}
public override void HandleState(EuiStateBase baseState)
{
var state = (EditSolutionsEuiState) baseState;
- _window.SetTargetEntity(state.Target);
+ _window.SetTargetEntity(_entManager.GetEntity(state.Target));
_window.UpdateSolutions(state.Solutions);
_window.UpdateReagents();
}
public sealed class SetOutfitEui : BaseEui
{
private readonly SetOutfitMenu _window;
+ private IEntityManager _entManager;
+
public SetOutfitEui()
{
+ _entManager = IoCManager.Resolve<IEntityManager>();
_window = new SetOutfitMenu();
_window.OnClose += OnClosed;
}
public override void HandleState(EuiStateBase state)
{
var outfitState = (SetOutfitEuiState) state;
- _window.TargetEntityId = outfitState.TargetEntityId;
+ _window.TargetEntityId = _entManager.GetEntity(outfitState.TargetNetEntity);
}
}
[UsedImplicitly]
public sealed class SpawnExplosionEui : BaseEui
{
+ [Dependency] private readonly EntityManager _entManager = default!;
[Dependency] private readonly IOverlayManager _overlayManager = default!;
private readonly SpawnExplosionWindow _window;
_overlayManager.AddOverlay(_debugOverlay);
}
- _debugOverlay.Tiles = data.Explosion.Tiles;
+ var tiles = new Dictionary<EntityUid, Dictionary<int, List<Vector2i>>>();
+ _debugOverlay.Tiles.Clear();
+
+ foreach (var (nent, det) in data.Explosion.Tiles)
+ {
+ tiles[_entManager.GetEntity(nent)] = det;
+ }
+
_debugOverlay.SpaceTiles = data.Explosion.SpaceTiles;
_debugOverlay.Intensity = data.Explosion.Intensity;
_debugOverlay.Slope = data.Slope;
private void OnTeleportButtonPressed(BaseButton.ButtonEventArgs obj)
{
IoCManager.Resolve<IClientConsoleHost>().ExecuteCommand(
- $"tp {XCoordinate.Value} {YCoordinate.Value} {MapOptions.SelectedId}");
+ $"tp {XCoordinate.Value} {YCoordinate.Value} {new NetEntity(MapOptions.SelectedId)}");
}
private void OnSubmitButtonPressed(BaseButton.ButtonEventArgs obj)
if (MapPath.Text.Length == 0) return;
IoCManager.Resolve<IClientConsoleHost>().ExecuteCommand(
- $"loadbp {MapOptions.SelectedId} \"{MapPath.Text}\" {XCoordinate.Value} {YCoordinate.Value} {RotationSpin.Value}");
+ $"loadbp {new NetEntity(MapOptions.SelectedId)} \"{MapPath.Text}\" {XCoordinate.Value} {YCoordinate.Value} {RotationSpin.Value}");
}
}
}
if (_data == null)
return;
var dataList = _data.ToList();
+ var entManager = IoCManager.Resolve<IEntityManager>();
var selectedGrid = dataList[GridOptions.SelectedId].Owner;
- IoCManager.Resolve<IClientConsoleHost>().ExecuteCommand($"addatmos {selectedGrid}");
+ IoCManager.Resolve<IClientConsoleHost>().ExecuteCommand($"addatmos {entManager.GetNetEntity(selectedGrid)}");
}
}
}
var selectedGrid = _data[GridOptions.SelectedId];
IoCManager.Resolve<IClientConsoleHost>()
- .ExecuteCommand($"settemp {TileXSpin.Value} {TileYSpin.Value} {selectedGrid} {TemperatureSpin.Value}");
+ .ExecuteCommand($"settemp {TileXSpin.Value} {TileYSpin.Value} {IoCManager.Resolve<IEntityManager>().GetNetEntity(selectedGrid)} {TemperatureSpin.Value}");
}
}
}
private const string ArrowDown = "↓";
private readonly Color _altColor = Color.FromHex("#292B38");
private readonly Color _defaultColor = Color.FromHex("#2F2F3B");
+ private IEntityManager _entManager;
private readonly AdminSystem _adminSystem;
private IReadOnlyList<PlayerInfo> _players = new List<PlayerInfo>();
public PlayerTab()
{
- _adminSystem = EntitySystem.Get<AdminSystem>();
+ _entManager = IoCManager.Resolve<IEntityManager>();
+ _adminSystem = _entManager.System<AdminSystem>();
RobustXamlLoader.Load(this);
RefreshPlayerList(_adminSystem.PlayerList);
player.Antag ? "YES" : "NO",
new StyleBoxFlat(useAltColor ? _altColor : _defaultColor),
player.Connected);
- entry.PlayerUid = player.EntityUid;
+ entry.PlayerUid = _entManager.GetEntity(player.NetEntity);
entry.OnPressed += args => OnEntryPressed?.Invoke(args);
PlayerList.AddChild(entry);
private void HandleAtmosDebugOverlayMessage(AtmosDebugOverlayMessage message)
{
- _tileData[message.GridId] = message;
+ _tileData[GetEntity(message.GridId)] = message;
}
private void HandleAtmosDebugOverlayDisableMessage(AtmosDebugOverlayDisableMessage ev)
private void HandleGasOverlayUpdate(GasOverlayUpdateEvent ev)
{
- foreach (var (grid, removedIndicies) in ev.RemovedChunks)
+ foreach (var (nent, removedIndicies) in ev.RemovedChunks)
{
+ var grid = GetEntity(nent);
+
if (!TryComp(grid, out GasTileOverlayComponent? comp))
continue;
}
}
- foreach (var (grid, gridData) in ev.UpdatedChunks)
+ foreach (var (nent, gridData) in ev.UpdatedChunks)
{
+ var grid = GetEntity(nent);
+
if (!TryComp(grid, out GasTileOverlayComponent? comp))
continue;
_ => GridIcon.OverrideDirection
};
- GridIcon.SetEntity(msg.DeviceUid);
+ GridIcon.SetEntity(IoCManager.Resolve<IEntityManager>().GetEntity(msg.DeviceUid));
LeftPanel.RemoveAllChildren();
MiddlePanel.RemoveAllChildren();
RightPanel.RemoveAllChildren();
//TODO: Sometime in the future this needs to be replaced with tiled sprites
private void BeamVisualizerMessage(BeamVisualizerEvent args)
{
- if (TryComp<SpriteComponent>(args.Beam, out var sprites))
+ var beam = GetEntity(args.Beam);
+
+ if (TryComp<SpriteComponent>(beam, out var sprites))
{
sprites.Rotation = args.UserAngle;
protected override Vector2 ContentsMinimumSize => new(500, 700);
- public void Update((string name, EntityUid entity)[] entities)
+ public void Update((string name, NetEntity entity)[] entities)
{
StatusLabel.Text = _loc.GetString("ui-bql-results-status", ("count", entities.Length));
ItemList.RemoveAllChildren();
return;
component.Buckled = state.Buckled;
- component.BuckledTo = state.BuckledTo;
- component.LastEntityBuckledTo = state.LastEntityBuckledTo;
+ component.BuckledTo = EnsureEntity<BuckleComponent>(state.BuckledTo, uid);
+ component.LastEntityBuckledTo = EnsureEntity<BuckleComponent>(state.LastEntityBuckledTo, uid);
component.DontCollide = state.DontCollide;
ActionBlockerSystem.UpdateCanMove(uid);
private void OnCameraKick(CameraKickEvent ev)
{
- KickCamera(ev.Euid, ev.Recoil);
+ KickCamera(GetEntity(ev.NetEntity), ev.Recoil);
}
public override void KickCamera(EntityUid uid, Vector2 recoil, CameraRecoilComponent? component = null)
private void OnBoxEffect(PlayBoxEffectMessage msg)
{
- if (!TryComp<CardboardBoxComponent>(msg.Source, out var box))
+ var source = GetEntity(msg.Source);
+
+ if (!TryComp<CardboardBoxComponent>(source, out var box))
return;
var xformQuery = GetEntityQuery<TransformComponent>();
- if (!xformQuery.TryGetComponent(msg.Source, out var xform))
+ if (!xformQuery.TryGetComponent(source, out var xform))
return;
var sourcePos = xform.MapPosition;
//Any mob that can move should be surprised?
//God mind rework needs to come faster so it can just check for mind
//TODO: Replace with Mind Query when mind rework is in.
- var mobMoverEntities = new HashSet<EntityUid>();
+ var mobMoverEntities = new List<EntityUid>();
+ var mover = GetEntity(msg.Mover);
//Filter out entities in range to see that they're a mob and add them to the mobMoverEntities hash for faster lookup
foreach (var moverComp in _entityLookup.GetComponentsInRange<MobMoverComponent>(xform.Coordinates, box.Distance))
{
- if (moverComp.Owner == msg.Mover)
+ if (moverComp.Owner == mover)
continue;
mobMoverEntities.Add(moverComp.Owner);
sprite.Offset = new Vector2(0, 1);
entTransform.AttachParent(mob);
}
+
}
}
[ViewVariables]
private Control? _activeUiFragment;
+ private IEntityManager _entManager;
+
protected CartridgeLoaderBoundUserInterface(EntityUid owner, Enum uiKey) : base(owner, uiKey)
{
+ _entManager = IoCManager.Resolve<IEntityManager>();
}
protected override void UpdateState(BoundUserInterfaceState state)
return;
}
- var programs = GetCartridgeComponents(loaderUiState.Programs);
+ // TODO move this to a component state and ensure the net ids.
+ var programs = GetCartridgeComponents(_entManager.GetEntityList(loaderUiState.Programs));
UpdateAvailablePrograms(programs);
- _activeProgram = loaderUiState.ActiveUI;
+ var activeUI = _entManager.GetEntity(loaderUiState.ActiveUI);
+
+ _activeProgram = activeUI;
- var ui = RetrieveCartridgeUI(loaderUiState.ActiveUI);
- var comp = RetrieveCartridgeComponent(loaderUiState.ActiveUI);
+ var ui = RetrieveCartridgeUI(activeUI);
+ var comp = RetrieveCartridgeComponent(activeUI);
var control = ui?.GetUIFragmentRoot();
//Prevent the same UI fragment from getting disposed and attached multiple times
protected void ActivateCartridge(EntityUid cartridgeUid)
{
- var message = new CartridgeLoaderUiMessage(cartridgeUid, CartridgeUiMessageAction.Activate);
+ var message = new CartridgeLoaderUiMessage(_entManager.GetNetEntity(cartridgeUid), CartridgeUiMessageAction.Activate);
SendMessage(message);
}
if (!_activeProgram.HasValue)
return;
- var message = new CartridgeLoaderUiMessage(_activeProgram.Value, CartridgeUiMessageAction.Deactivate);
+ var message = new CartridgeLoaderUiMessage(_entManager.GetNetEntity(_activeProgram.Value), CartridgeUiMessageAction.Deactivate);
SendMessage(message);
}
protected void InstallCartridge(EntityUid cartridgeUid)
{
- var message = new CartridgeLoaderUiMessage(cartridgeUid, CartridgeUiMessageAction.Install);
+ var message = new CartridgeLoaderUiMessage(_entManager.GetNetEntity(cartridgeUid), CartridgeUiMessageAction.Install);
SendMessage(message);
}
protected void UninstallCartridge(EntityUid cartridgeUid)
{
- var message = new CartridgeLoaderUiMessage(cartridgeUid, CartridgeUiMessageAction.Uninstall);
+ var message = new CartridgeLoaderUiMessage(_entManager.GetNetEntity(cartridgeUid), CartridgeUiMessageAction.Uninstall);
SendMessage(message);
}
private void SendCartridgeUiReadyEvent(EntityUid cartridgeUid)
{
- var message = new CartridgeLoaderUiMessage(cartridgeUid, CartridgeUiMessageAction.UIReady);
+ var message = new CartridgeLoaderUiMessage(_entManager.GetNetEntity(cartridgeUid), CartridgeUiMessageAction.UIReady);
SendMessage(message);
}
return;
}
- RaiseNetworkEvent(new RequestCharacterInfoEvent(entity.Value));
+ RaiseNetworkEvent(new RequestCharacterInfoEvent(GetNetEntity(entity.Value)));
}
private void OnPlayerAttached(PlayerAttachSysMessage msg)
private void OnCharacterInfoEvent(CharacterInfoEvent msg, EntitySessionEventArgs args)
{
- var data = new CharacterData(msg.EntityUid, msg.JobTitle, msg.Objectives, msg.Briefing, Name(msg.EntityUid));
+ var entity = GetEntity(msg.NetEntity);
+ var data = new CharacterData(entity, msg.JobTitle, msg.Objectives, msg.Briefing, Name(entity));
+
OnCharacterUpdate?.Invoke(data);
}
private void OnVisualsChanged(EntityUid uid, InventoryComponent component, VisualsChangedEvent args)
{
- if (!TryComp(args.Item, out ClothingComponent? clothing) || clothing.InSlot == null)
+ var item = GetEntity(args.Item);
+
+ if (!TryComp(item, out ClothingComponent? clothing) || clothing.InSlot == null)
return;
- RenderEquipment(uid, args.Item, clothing.InSlot, component, null, clothing);
+ RenderEquipment(uid, item, clothing.InSlot, component, null, clothing);
}
private void OnDidUnequip(EntityUid uid, SpriteComponent component, DidUnequipEvent args)
public sealed partial class ConstructionGhostComponent : Component
{
[ViewVariables] public ConstructionPrototype? Prototype { get; set; }
- [ViewVariables] public int GhostId { get; set; }
}
}
-using System.Collections.Generic;
-using System.Linq;
-using Content.Shared.Construction;
+using System.Linq;
using Content.Shared.Construction.Prototypes;
-using Robust.Client.Graphics;
using Robust.Client.Placement;
using Robust.Client.Utility;
-using Robust.Shared.GameObjects;
-using Robust.Shared.IoC;
using Robust.Shared.Map;
namespace Content.Client.Construction
/// <inheritdoc />
public override bool HijackDeletion(EntityUid entity)
{
- if (IoCManager.Resolve<IEntityManager>().TryGetComponent(entity, out ConstructionGhostComponent? ghost))
+ if (IoCManager.Resolve<IEntityManager>().HasComponent<ConstructionGhostComponent>(entity))
{
- _constructionSystem.ClearGhost(ghost.GhostId);
+ _constructionSystem.ClearGhost(entity.GetHashCode());
}
return true;
}
[Dependency] private readonly SharedInteractionSystem _interactionSystem = default!;
[Dependency] private readonly PopupSystem _popupSystem = default!;
- private readonly Dictionary<int, ConstructionGhostComponent> _ghosts = new();
+ private readonly Dictionary<int, EntityUid> _ghosts = new();
private readonly Dictionary<string, ConstructionGuide> _guideCache = new();
- private int _nextId;
-
public bool CraftingEnabled { get; private set; }
/// <inheritdoc />
{
base.Initialize();
+ UpdatesOutsidePrediction = true;
SubscribeLocalEvent<PlayerAttachSysMessage>(HandlePlayerAttached);
SubscribeNetworkEvent<AckStructureConstructionMessage>(HandleAckStructure);
SubscribeNetworkEvent<ResponseConstructionGuide>(OnConstructionGuideReceived);
private void HandleAckStructure(AckStructureConstructionMessage msg)
{
+ // We get sent a NetEntity but it actually corresponds to our local Entity.
ClearGhost(msg.GhostId);
}
private bool HandleUse(in PointerInputCmdHandler.PointerInputCmdArgs args)
{
- if (!args.EntityUid.IsValid() || !args.EntityUid.IsClientSide())
+ if (!args.EntityUid.IsValid() || !IsClientSide(args.EntityUid))
return false;
- if (!EntityManager.TryGetComponent<ConstructionGhostComponent?>(args.EntityUid, out var ghostComp))
+ if (!HasComp<ConstructionGhostComponent>(args.EntityUid))
return false;
- TryStartConstruction(ghostComp.GhostId);
+ TryStartConstruction(args.EntityUid);
return true;
}
ghost = EntityManager.SpawnEntity("constructionghost", loc);
var comp = EntityManager.GetComponent<ConstructionGhostComponent>(ghost.Value);
comp.Prototype = prototype;
- comp.GhostId = _nextId++;
EntityManager.GetComponent<TransformComponent>(ghost.Value).LocalRotation = dir.ToAngle();
- _ghosts.Add(comp.GhostId, comp);
+ _ghosts.Add(ghost.Value.Id, ghost.Value);
var sprite = EntityManager.GetComponent<SpriteComponent>(ghost.Value);
sprite.Color = new Color(48, 255, 48, 128);
{
foreach (var ghost in _ghosts)
{
- if (EntityManager.GetComponent<TransformComponent>(ghost.Value.Owner).Coordinates.Equals(loc)) return true;
+ if (EntityManager.GetComponent<TransformComponent>(ghost.Value).Coordinates.Equals(loc))
+ return true;
}
return false;
}
- public void TryStartConstruction(int ghostId)
+ public void TryStartConstruction(EntityUid ghostId, ConstructionGhostComponent? ghostComp = null)
{
- var ghost = _ghosts[ghostId];
+ if (!Resolve(ghostId, ref ghostComp))
+ return;
- if (ghost.Prototype == null)
+ if (ghostComp.Prototype == null)
{
throw new ArgumentException($"Can't start construction for a ghost with no prototype. Ghost id: {ghostId}");
}
- var transform = EntityManager.GetComponent<TransformComponent>(ghost.Owner);
- var msg = new TryStartStructureConstructionMessage(transform.Coordinates, ghost.Prototype.ID, transform.LocalRotation, ghostId);
+ var transform = EntityManager.GetComponent<TransformComponent>(ghostId);
+ var msg = new TryStartStructureConstructionMessage(GetNetCoordinates(transform.Coordinates), ghostComp.Prototype.ID, transform.LocalRotation, ghostId.Id);
RaiseNetworkEvent(msg);
}
/// </summary>
public void ClearGhost(int ghostId)
{
- if (_ghosts.TryGetValue(ghostId, out var ghost))
- {
- EntityManager.QueueDeleteEntity(ghost.Owner);
- _ghosts.Remove(ghostId);
- }
+ if (!_ghosts.TryGetValue(ghostId, out var ghost))
+ return;
+
+ EntityManager.QueueDeleteEntity(ghost);
+ _ghosts.Remove(ghostId);
}
/// <summary>
/// </summary>
public void ClearAllGhosts()
{
- foreach (var (_, ghost) in _ghosts)
+ foreach (var ghost in _ghosts.Values)
{
- EntityManager.QueueDeleteEntity(ghost.Owner);
+ EntityManager.QueueDeleteEntity(ghost);
}
_ghosts.Clear();
private string? SearchPlayerName(EntityUid entity)
{
- return _adminSystem.PlayerList.FirstOrDefault(player => player.EntityUid == entity)?.Username;
+ var netEntity = _entityManager.GetNetEntity(entity);
+ return _adminSystem.PlayerList.FirstOrDefault(player => player.NetEntity == netEntity)?.Username;
}
/// <summary>
var representation = _entityManager.ToPrettyString(entity);
var name = representation.Name;
- var id = representation.Uid;
+ var id = representation.Uid.ToString();
var prototype = representation.Prototype;
var playerName = representation.Session?.Name ?? SearchPlayerName(entity);
var deleted = representation.Deleted;
- return $"{name} ({id}{(prototype != null ? $", {prototype}" : "")}{(playerName != null ? $", {playerName}" : "")}){(deleted ? "D" : "")}";
+ return $"{name} ({id} / {_entityManager.GetNetEntity(entity).ToString()}{(prototype != null ? $", {prototype}" : "")}{(playerName != null ? $", {playerName}" : "")}){(deleted ? "D" : "")}";
}
private string GetEntityDescription(EntityUid entity)
var func = args.Function;
var funcId = _inputManager.NetworkBindMap.KeyFunctionID(func);
- var message = new FullInputCmdMessage(_gameTiming.CurTick, _gameTiming.TickFraction, funcId,
- BoundKeyState.Down, _entityManager.GetComponent<TransformComponent>(entity.Value).Coordinates, args.PointerLocation, entity.Value);
+ var message = new ClientFullInputCmdMessage(
+ _gameTiming.CurTick,
+ _gameTiming.TickFraction,
+ funcId)
+ {
+ State = BoundKeyState.Down,
+ Coordinates = _entityManager.GetComponent<TransformComponent>(entity.Value).Coordinates,
+ ScreenCoordinates = args.PointerLocation,
+ Uid = entity.Value,
+ };
var session = _playerManager.LocalPlayer?.Session;
if (session != null)
/// <summary>
/// Requests a crew manifest from the server.
/// </summary>
- /// <param name="uid">EntityUid of the entity we're requesting the crew manifest from.</param>
- public void RequestCrewManifest(EntityUid uid)
+ /// <param name="netEntity">EntityUid of the entity we're requesting the crew manifest from.</param>
+ public void RequestCrewManifest(NetEntity netEntity)
{
- RaiseNetworkEvent(new RequestCrewManifestMessage(uid));
+ RaiseNetworkEvent(new RequestCrewManifestMessage(netEntity));
}
private void OnPrototypesReload(PrototypesReloadedEventArgs _)
return false;
var decal = new Decal(coords.Position, _decalId, _decalColor, _decalAngle, _zIndex, _cleanable);
- RaiseNetworkEvent(new RequestDecalPlacementEvent(decal, coords));
+ RaiseNetworkEvent(new RequestDecalPlacementEvent(decal, GetNetCoordinates(coords)));
return true;
},
_erasing = true;
- RaiseNetworkEvent(new RequestDecalRemovalEvent(coords));
+ RaiseNetworkEvent(new RequestDecalRemovalEvent(GetNetCoordinates(coords)));
return true;
}, (session, coords, uid) =>
args.Target = args.Target.Offset(new Vector2(-0.5f, -0.5f));
var decal = new Decal(args.Target.Position, args.DecalId, args.Color, Angle.FromDegrees(args.Rotation), args.ZIndex, args.Cleanable);
- RaiseNetworkEvent(new RequestDecalPlacementEvent(decal, args.Target));
+ RaiseNetworkEvent(new RequestDecalPlacementEvent(decal, GetNetCoordinates(args.Target)));
}
private void OnFillSlot(FillActionSlotEvent ev)
private void OnChunkUpdate(DecalChunkUpdateEvent ev)
{
- foreach (var (gridId, updatedGridChunks) in ev.Data)
+ foreach (var (netGrid, updatedGridChunks) in ev.Data)
{
- if (updatedGridChunks.Count == 0) continue;
+ if (updatedGridChunks.Count == 0)
+ continue;
+
+ var gridId = GetEntity(netGrid);
if (!TryComp(gridId, out DecalGridComponent? gridComp))
{
- Logger.Error($"Received decal information for an entity without a decal component: {ToPrettyString(gridId)}");
+ Log.Error($"Received decal information for an entity without a decal component: {ToPrettyString(gridId)}");
continue;
}
}
// Now we'll cull old chunks out of range as the server will send them to us anyway.
- foreach (var (gridId, chunks) in ev.RemovedChunks)
+ foreach (var (netGrid, chunks) in ev.RemovedChunks)
{
- if (chunks.Count == 0) continue;
+ if (chunks.Count == 0)
+ continue;
+
+ var gridId = GetEntity(netGrid);
if (!TryComp(gridId, out DecalGridComponent? gridComp))
{
- Logger.Error($"Received decal information for an entity without a decal component: {ToPrettyString(gridId)}");
+ Log.Error($"Received decal information for an entity without a decal component: {ToPrettyString(gridId)}");
continue;
}
component.Powered = state.Powered;
component.Engaged = state.Engaged;
component.RecentlyEjected.Clear();
- component.RecentlyEjected.AddRange(state.RecentlyEjected);
+ component.RecentlyEjected.AddRange(EnsureEntityList<DisposalUnitComponent>(state.RecentlyEjected, uid));
}
public override bool HasDisposals(EntityUid? uid)
// the mouse, canceling the drag, but just being cautious)
EndDrag();
+ var entity = args.EntityUid;
+
// possibly initiating a drag
// check if the clicked entity is draggable
- if (!Exists(args.EntityUid))
+ if (!Exists(entity))
{
return false;
}
// check if the entity is reachable
- if (!_interactionSystem.InRangeUnobstructed(dragger, args.EntityUid))
+ if (!_interactionSystem.InRangeUnobstructed(dragger, entity))
{
return false;
}
var ev = new CanDragEvent();
- RaiseLocalEvent(args.EntityUid, ref ev);
+ RaiseLocalEvent(entity, ref ev);
if (ev.Handled != true)
return false;
- _draggedEntity = args.EntityUid;
+ _draggedEntity = entity;
_state = DragState.MouseDown;
_mouseDownScreenPos = _inputManager.MouseScreenPosition;
_mouseDownTime = 0;
// adjust the timing info based on the current tick so it appears as if it happened now
var replayMsg = savedValue.OriginalMessage;
- var adjustedInputMsg = new FullInputCmdMessage(args.OriginalMessage.Tick,
- args.OriginalMessage.SubTick,
- replayMsg.InputFunctionId, replayMsg.State, replayMsg.Coordinates, replayMsg.ScreenCoordinates,
- replayMsg.Uid);
+ switch (replayMsg)
+ {
+ case ClientFullInputCmdMessage clientInput:
+ replayMsg = new ClientFullInputCmdMessage(args.OriginalMessage.Tick,
+ args.OriginalMessage.SubTick,
+ replayMsg.InputFunctionId)
+ {
+ State = replayMsg.State,
+ Coordinates = clientInput.Coordinates,
+ ScreenCoordinates = clientInput.ScreenCoordinates,
+ Uid = clientInput.Uid,
+ };
+ break;
+ case FullInputCmdMessage fullInput:
+ replayMsg = new FullInputCmdMessage(args.OriginalMessage.Tick,
+ args.OriginalMessage.SubTick,
+ replayMsg.InputFunctionId, replayMsg.State, fullInput.Coordinates, fullInput.ScreenCoordinates,
+ fullInput.Uid);
+ break;
+ default:
+ throw new ArgumentOutOfRangeException();
+ }
if (savedValue.Session != null)
{
- _inputSystem.HandleInputCommand(savedValue.Session, EngineKeyFunctions.Use, adjustedInputMsg,
+ _inputSystem.HandleInputCommand(savedValue.Session, EngineKeyFunctions.Use, replayMsg,
true);
}
}
IEnumerable<EntityUid> entities;
+ var coords = args.Coordinates;
if (_stateManager.CurrentState is GameplayState screen)
{
- entities = screen.GetClickableEntities(args.Coordinates);
+ entities = screen.GetClickableEntities(coords);
}
else
{
}
// tell the server about the drop attempt
- RaiseNetworkEvent(new DragDropRequestEvent(_draggedEntity.Value, entity));
+ RaiseNetworkEvent(new DragDropRequestEvent(GetNetEntity(_draggedEntity.Value), GetNetEntity(entity)));
EndDrag();
return true;
}
if (!_timing.IsFirstTimePredicted)
return;
- OnColorFlashEffect(new ColorFlashEffectEvent(color, entities));
+ OnColorFlashEffect(new ColorFlashEffectEvent(color, GetNetEntityList(entities)));
}
private void OnEffectAnimationCompleted(EntityUid uid, ColorFlashEffectComponent component, AnimationCompletedEvent args)
{
var color = ev.Color;
- foreach (var ent in ev.Entities)
+ foreach (var nent in ev.Entities)
{
+ var ent = GetEntity(nent);
+
if (Deleted(ent))
{
continue;
private bool HandleExamine(in PointerInputCmdHandler.PointerInputCmdArgs args)
{
- if (!args.EntityUid.IsValid() || !EntityManager.EntityExists(args.EntityUid))
+ var entity = args.EntityUid;
+
+ if (!args.EntityUid.IsValid() || !EntityManager.EntityExists(entity))
{
return false;
}
_playerEntity = _playerManager.LocalPlayer?.ControlledEntity ?? default;
- if (_playerEntity == default || !CanExamine(_playerEntity, args.EntityUid))
+ if (_playerEntity == default || !CanExamine(_playerEntity, entity))
{
return false;
}
- DoExamine(args.EntityUid);
+ DoExamine(entity);
return true;
}
// Tooltips coming in from the server generally prioritize
// opening at the old tooltip rather than the cursor/another entity,
// since there's probably one open already if it's coming in from the server.
- OpenTooltip(player.Value, ev.EntityUid, ev.CenterAtCursor, ev.OpenAtOldTooltip, ev.KnowTarget);
- UpdateTooltipInfo(player.Value, ev.EntityUid, ev.Message, ev.Verbs);
+ var entity = GetEntity(ev.EntityUid);
+
+ OpenTooltip(player.Value, entity, ev.CenterAtCursor, ev.OpenAtOldTooltip, ev.KnowTarget);
+ UpdateTooltipInfo(player.Value, entity, ev.Message, ev.Verbs);
}
public override void SendExamineTooltip(EntityUid player, EntityUid target, FormattedMessage message, bool getVerbs, bool centerAtCursor)
FormattedMessage message;
// Basically this just predicts that we can't make out the entity if we have poor vision.
- var canSeeClearly = true;
- if (HasComp<BlurryVisionComponent>(playerEnt))
- canSeeClearly = false;
+ var canSeeClearly = !HasComp<BlurryVisionComponent>(playerEnt);
OpenTooltip(playerEnt.Value, entity, centeredOnCursor, false, knowTarget: canSeeClearly);
- if (entity.IsClientSide()
+ if (IsClientSide(entity)
|| _client.RunLevel == ClientRunLevel.SinglePlayerGame) // i.e. a replay
{
message = GetExamineText(entity, playerEnt);
_idCounter += 1;
if (_idCounter == int.MaxValue)
_idCounter = 0;
- RaiseNetworkEvent(new ExamineSystemMessages.RequestExamineInfoMessage(entity, _idCounter, true));
+ RaiseNetworkEvent(new ExamineSystemMessages.RequestExamineInfoMessage(GetNetEntity(entity), _idCounter, true));
}
RaiseLocalEvent(entity, new ClientExaminedEvent(entity, playerEnt.Value));
using Robust.Client.ResourceManagement;
using Robust.Shared.GameStates;
using Robust.Shared.Prototypes;
+using Robust.Shared.Utility;
namespace Content.Client.Explosion;
component.Epicenter = state.Epicenter;
component.SpaceTiles = state.SpaceTiles;
- component.Tiles = state.Tiles;
+ component.Tiles.Clear();
+
+ foreach (var (nent, data) in state.Tiles)
+ {
+ component.Tiles[GetEntity(nent)] = data;
+ }
+
component.Intensity = state.Intensity;
component.ExplosionType = state.ExplosionType;
component.SpaceMatrix = state.SpaceMatrix;
[UsedImplicitly]
public sealed class AdminFaxEui : BaseEui
{
+ private IEntityManager _entManager;
private readonly AdminFaxWindow _window;
public AdminFaxEui()
{
+ _entManager = IoCManager.Resolve<IEntityManager>();
_window = new AdminFaxWindow();
_window.OnClose += () => SendMessage(new AdminFaxEuiMsg.Close());
- _window.OnFollowFax += uid => SendMessage(new AdminFaxEuiMsg.Follow(uid));
- _window.OnMessageSend += args => SendMessage(new AdminFaxEuiMsg.Send(args.uid, args.title,
+ _window.OnFollowFax += uid => SendMessage(new AdminFaxEuiMsg.Follow(_entManager.GetNetEntity(uid)));
+ _window.OnMessageSend += args => SendMessage(new AdminFaxEuiMsg.Send(_entManager.GetNetEntity(args.uid), args.title,
args.stampedBy, args.message, args.stampSprite, args.stampColor));
}
private void RenderDebugData(PuddleOverlayDebugMessage message)
{
- TileData[message.GridUid] = message;
+ TileData[GetEntity(message.GridUid)] = message;
if (_overlay != null)
return;
[Dependency] private readonly SharedAudioSystem _audio = default!;
[ViewVariables] private bool _initialized;
- private Dictionary<EntityUid, Dictionary<string, uint?>> _jobsAvailable = new();
- private Dictionary<EntityUid, string> _stationNames = new();
+ private Dictionary<NetEntity, Dictionary<string, uint?>> _jobsAvailable = new();
+ private Dictionary<NetEntity, string> _stationNames = new();
/// <summary>
/// The current round-end window. Could be used to support re-opening the window after closing it.
[ViewVariables] public TimeSpan RoundStartTimeSpan { get; private set; }
[ViewVariables] public new bool Paused { get; private set; }
- [ViewVariables] public IReadOnlyDictionary<EntityUid, Dictionary<string, uint?>> JobsAvailable => _jobsAvailable;
- [ViewVariables] public IReadOnlyDictionary<EntityUid, string> StationNames => _stationNames;
+ [ViewVariables] public IReadOnlyDictionary<NetEntity, Dictionary<string, uint?>> JobsAvailable => _jobsAvailable;
+ [ViewVariables] public IReadOnlyDictionary<NetEntity, string> StationNames => _stationNames;
public event Action? InfoBlobUpdated;
public event Action? LobbyStatusUpdated;
public event Action? LobbySongUpdated;
public event Action? LobbyLateJoinStatusUpdated;
- public event Action<IReadOnlyDictionary<EntityUid, Dictionary<string, uint?>>>? LobbyJobsAvailableUpdated;
+ public event Action<IReadOnlyDictionary<NetEntity, Dictionary<string, uint?>>>? LobbyJobsAvailableUpdated;
public override void Initialize()
{
private void UpdateJobsAvailable(TickerJobsAvailableEvent message)
{
- _jobsAvailable = message.JobsAvailableByStation;
- _stationNames = message.StationNames;
+ foreach (var (job, data) in message.JobsAvailableByStation)
+ {
+ _jobsAvailable.Clear();
+ _jobsAvailable[job] = data;
+ }
+
+ _stationNames.Clear();
+ foreach (var weh in message.StationNames)
+ {
+ _stationNames[weh.Key] = weh.Value;
+ }
+
LobbyJobsAvailableUpdated?.Invoke(JobsAvailable);
}
EntityCoordinates.FromMap(_mapManager, mousePosWorld);
}
- var message = new FullInputCmdMessage(_timing.CurTick, _timing.TickFraction, funcId, kArgs.State,
- coordinates , kArgs.PointerLocation,
- entityToClick ?? default); // TODO make entityUid nullable
+ var message = new ClientFullInputCmdMessage(_timing.CurTick, _timing.TickFraction, funcId)
+ {
+ State = kArgs.State,
+ Coordinates = coordinates,
+ ScreenCoordinates = kArgs.PointerLocation,
+ Uid = entityToClick ?? default,
+ }; // TODO make entityUid nullable
// client side command handlers will always be sent the local player session.
var session = _playerManager.LocalPlayer?.Session;
_window = new GatewayWindow();
_window.OpenPortal += destination =>
{
- SendMessage(new GatewayOpenPortalMessage(destination));
+ SendMessage(new GatewayOpenPortalMessage(EntMan.GetNetEntity(destination)));
};
_window.OnClose += Close;
_window?.OpenCentered();
public sealed partial class GatewayWindow : FancyWindow,
IComputerWindow<EmergencyConsoleBoundUserInterfaceState>
{
+ private readonly IEntityManager _entManager;
private readonly IGameTiming _timing;
public event Action<EntityUid>? OpenPortal;
- private List<(EntityUid, string, TimeSpan, bool)> _destinations = default!;
+ private List<(NetEntity, string, TimeSpan, bool)> _destinations = default!;
private EntityUid? _current;
private TimeSpan _nextClose;
private TimeSpan _lastOpen;
public GatewayWindow()
{
RobustXamlLoader.Load(this);
- _timing = IoCManager.Resolve<IGameTiming>();
+ var dependencies = IoCManager.Instance!;
+ _entManager = dependencies.Resolve<IEntityManager>();
+ _timing = dependencies.Resolve<IGameTiming>();
}
public void UpdateState(GatewayBoundUserInterfaceState state)
{
_destinations = state.Destinations;
- _current = state.Current;
+ _current = _entManager.GetEntity(state.Current);
_nextClose = state.NextClose;
_lastOpen = state.LastOpen;
var now = _timing.CurTime;
foreach (var dest in _destinations)
{
- var uid = dest.Item1;
+ var uid = _entManager.GetEntity(dest.Item1);
var name = dest.Item2;
var nextReady = dest.Item3;
var busy = dest.Item4;
OpenPortal?.Invoke(uid);
};
- if (uid == state.Current)
+ if (uid == _entManager.GetEntity(state.Current))
{
openButton.AddStyleClass(StyleBase.ButtonCaution);
}
#region PickupAnimation
private void HandlePickupAnimation(PickupAnimationEvent msg)
{
- PickupAnimation(msg.ItemUid, msg.InitialPosition, msg.FinalPosition, msg.InitialAngle);
+ PickupAnimation(GetEntity(msg.ItemUid), GetCoordinates(msg.InitialPosition), msg.FinalPosition, msg.InitialAngle);
}
public override void PickupAnimation(EntityUid item, EntityCoordinates initialPosition, Vector2 finalPosition, Angle initialAngle,
// update hands visuals if this item is in a hand (rather then inventory or other container).
if (component.Hands.TryGetValue(args.ContainerId, out var hand))
{
- UpdateHandVisuals(uid, args.Item, hand, component);
+ UpdateHandVisuals(uid, GetEntity(args.Item), hand, component);
}
}
#endregion
{
var text = new StringBuilder();
var entities = IoCManager.Resolve<IEntityManager>();
+ var target = entities.GetEntity(msg.TargetEntity);
- if (msg.TargetEntity != null && entities.TryGetComponent<DamageableComponent>(msg.TargetEntity, out var damageable))
+ if (msg.TargetEntity != null && entities.TryGetComponent<DamageableComponent>(target, out var damageable))
{
string entityName = "Unknown";
if (msg.TargetEntity != null &&
- entities.TryGetComponent<MetaDataComponent>(msg.TargetEntity.Value, out var metaData))
- entityName = Identity.Name(msg.TargetEntity.Value, entities);
+ entities.HasComponent<MetaDataComponent>(target.Value))
+ {
+ entityName = Identity.Name(target.Value, entities);
+ }
IReadOnlyDictionary<string, FixedPoint2> damagePerGroup = damageable.DamagePerGroup;
IReadOnlyDictionary<string, FixedPoint2> damagePerType = damageable.Damage.DamageDict;
profile.Appearance.EyeColor,
_markingManager);
- DebugTools.Assert(uid.IsClientSide());
+ DebugTools.Assert(IsClientSide(uid));
var state = new HumanoidAppearanceState(markings,
new(),
public void SetMaster(EntityUid uid, EntityUid? masterUid)
{
- if (!TryComp(uid, out InstrumentComponent? instrument))
+ if (!HasComp<InstrumentComponent>(uid))
return;
- RaiseNetworkEvent(new InstrumentSetMasterEvent(uid, masterUid));
+ RaiseNetworkEvent(new InstrumentSetMasterEvent(GetNetEntity(uid), GetNetEntity(masterUid)));
}
public void SetFilteredChannel(EntityUid uid, int channel, bool value)
if(value)
instrument.Renderer?.SendMidiEvent(RobustMidiEvent.AllNotesOff((byte)channel, 0), false);
- RaiseNetworkEvent(new InstrumentSetFilteredChannelEvent(uid, channel, value));
+ RaiseNetworkEvent(new InstrumentSetFilteredChannelEvent(GetNetEntity(uid), channel, value));
}
public override void SetupRenderer(EntityUid uid, bool fromStateChange, SharedInstrumentComponent? component = null)
if (!fromStateChange)
{
- RaiseNetworkEvent(new InstrumentStartMidiEvent(uid));
+ RaiseNetworkEvent(new InstrumentStartMidiEvent(GetNetEntity(uid)));
}
}
if (!fromStateChange && _netManager.IsConnected)
{
- RaiseNetworkEvent(new InstrumentStopMidiEvent(uid));
+ RaiseNetworkEvent(new InstrumentStopMidiEvent(GetNetEntity(uid)));
}
}
private void OnMidiEventRx(InstrumentMidiEventEvent midiEv)
{
- var uid = midiEv.Uid;
+ var uid = GetEntity(midiEv.Uid);
if (!TryComp(uid, out InstrumentComponent? instrument))
return;
private void OnMidiStart(InstrumentStartMidiEvent ev)
{
- SetupRenderer(ev.Uid, true);
+ SetupRenderer(GetEntity(ev.Uid), true);
}
private void OnMidiStop(InstrumentStopMidiEvent ev)
{
- EndRenderer(ev.Uid, true);
+ EndRenderer(GetEntity(ev.Uid), true);
}
public override void Update(float frameTime)
if (eventCount == 0)
continue;
- RaiseNetworkEvent(new InstrumentMidiEventEvent(uid, events));
+ RaiseNetworkEvent(new InstrumentMidiEventEvent(GetNetEntity(uid), events));
instrument.SentWithinASec += eventCount;
Timer.Spawn(0, Close);
}
- public void Populate((EntityUid, string)[] nearby)
+ public void Populate((NetEntity, string)[] nearby, IEntityManager entManager)
{
BandList.Clear();
- foreach (var (uid, name) in nearby)
+ foreach (var (nent, name) in nearby)
{
+ var uid = entManager.GetEntity(nent);
var item = BandList.AddItem(name, null, true, uid);
item.Selected = _owner.Instrument?.Master == uid;
}
{
public sealed class InstrumentBoundUserInterface : BoundUserInterface
{
- [Dependency] public readonly IEntityManager Entities = default!;
+ public IEntityManager Entities => EntMan;
[Dependency] public readonly IMidiManager MidiManager = default!;
[Dependency] public readonly IFileDialogManager FileDialogManager = default!;
[Dependency] public readonly IPlayerManager PlayerManager = default!;
[Dependency] public readonly ILocalizationManager Loc = default!;
- public readonly InstrumentSystem Instruments = default!;
- public readonly ActionBlockerSystem ActionBlocker = default!;
- public readonly SharedInteractionSystem Interactions = default!;
+ public readonly InstrumentSystem Instruments;
+ public readonly ActionBlockerSystem ActionBlocker;
+ public readonly SharedInteractionSystem Interactions;
[ViewVariables] private InstrumentMenu? _instrumentMenu;
[ViewVariables] private BandMenu? _bandMenu;
switch (message)
{
case InstrumentBandResponseBuiMessage bandRx:
- _bandMenu?.Populate(bandRx.Nearby);
+ _bandMenu?.Populate(bandRx.Nearby, EntMan);
break;
default:
break;
return;
EntityManager.RaisePredictiveEvent(
- new InteractInventorySlotEvent(item.Value, altInteract: false));
+ new InteractInventorySlotEvent(GetNetEntity(item.Value), altInteract: false));
}
public void UIInventoryAltActivateItem(string slot, EntityUid uid)
if (!TryGetSlotEntity(uid, slot, out var item))
return;
- EntityManager.RaisePredictiveEvent(new InteractInventorySlotEvent(item.Value, altInteract: true));
+ EntityManager.RaisePredictiveEvent(new InteractInventorySlotEvent(GetNetEntity(item.Value), altInteract: true));
}
public sealed class SlotData
{
// if the item is in a container, it might be equipped to hands or inventory slots --> update visuals.
if (Container.TryGetContainingContainer(uid, out var container))
- RaiseLocalEvent(container.Owner, new VisualsChangedEvent(uid, container.ID));
+ RaiseLocalEvent(container.Owner, new VisualsChangedEvent(GetNetEntity(uid), container.ID));
}
/// <summary>
ChamberContentBox.EjectButton.Disabled = state.ChamberContents.Length <= 0;
GrindButton.Disabled = !state.CanGrind || !state.Powered;
JuiceButton.Disabled = !state.CanJuice || !state.Powered;
- RefreshContentsDisplay(state.ReagentQuantities, state.ChamberContents, state.HasBeakerIn);
+
+ // TODO move this to a component state and ensure the net ids.
+ RefreshContentsDisplay(state.ReagentQuantities, _entityManager.GetEntityArray(state.ChamberContents), state.HasBeakerIn);
}
public void HandleMessage(BoundUserInterfaceMessage message)
[ViewVariables]
private readonly Dictionary<int, ReagentQuantity> _reagents = new();
+ private IEntityManager _entManager;
+
public MicrowaveBoundUserInterface(EntityUid owner, Enum uiKey) : base(owner, uiKey)
{
+ _entManager = IoCManager.Resolve<IEntityManager>();
}
protected override void Open()
_menu.EjectButton.OnPressed += _ => SendMessage(new MicrowaveEjectMessage());
_menu.IngredientsList.OnItemSelected += args =>
{
- SendMessage(new MicrowaveEjectSolidIndexedMessage(_solids[args.ItemIndex]));
+ SendMessage(new MicrowaveEjectSolidIndexedMessage(EntMan.GetNetEntity(_solids[args.ItemIndex])));
};
_menu.OnCookTimeSelected += (args, buttonIndex) =>
_menu?.Dispose();
}
-
protected override void UpdateState(BoundUserInterfaceState state)
{
base.UpdateState(state);
}
_menu?.ToggleBusyDisableOverlayPanel(cState.IsMicrowaveBusy);
- RefreshContentsDisplay(cState.ContainedSolids);
+
+ // TODO move this to a component state and ensure the net ids.
+ RefreshContentsDisplay(_entManager.GetEntityArray(cState.ContainedSolids));
if (_menu == null) return;
public void EjectChamberContent(EntityUid uid)
{
- SendMessage(new ReagentGrinderEjectChamberContentMessage(uid));
+ SendMessage(new ReagentGrinderEjectChamberContentMessage(EntMan.GetNetEntity(uid)));
}
}
}
[Dependency] private readonly IPrototypeManager _prototypeManager = default!;
[Dependency] private readonly IClientConsoleHost _consoleHost = default!;
[Dependency] private readonly IConfigurationManager _configManager = default!;
+ [Dependency] private readonly IEntityManager _entManager = default!;
[Dependency] private readonly IEntitySystemManager _entitySystem = default!;
[Dependency] private readonly JobRequirementsManager _jobRequirements = default!;
- public event Action<(EntityUid, string)> SelectedId;
+ public event Action<(NetEntity, string)> SelectedId;
private readonly ClientGameTicker _gameTicker;
private readonly SpriteSystem _sprites;
private readonly CrewManifestSystem _crewManifest;
- private readonly Dictionary<EntityUid, Dictionary<string, JobButton>> _jobButtons = new();
- private readonly Dictionary<EntityUid, Dictionary<string, BoxContainer>> _jobCategories = new();
+ private readonly Dictionary<NetEntity, Dictionary<string, JobButton>> _jobButtons = new();
+ private readonly Dictionary<NetEntity, Dictionary<string, BoxContainer>> _jobCategories = new();
private readonly List<ScrollContainer> _jobLists = new();
private readonly Control _base;
}
}
- private void JobsAvailableUpdated(IReadOnlyDictionary<EntityUid, Dictionary<string, uint?>> _)
+ private void JobsAvailableUpdated(IReadOnlyDictionary<NetEntity, Dictionary<string, uint?>> _)
{
RebuildUI();
}
public static Color GetCurrentRgbColor(TimeSpan curTime, TimeSpan offset, RgbLightControllerComponent rgb)
{
return Color.FromHsv(new Vector4(
- (float) (((curTime.TotalSeconds - offset.TotalSeconds) * rgb.CycleRate + Math.Abs(rgb.Owner.GetHashCode() * 0.1)) % 1),
+ (float) (((curTime.TotalSeconds - offset.TotalSeconds) * rgb.CycleRate + Math.Abs(rgb.Owner.Id * 0.1)) % 1),
1.0f,
1.0f,
1.0f
_dragging = grid;
_localPosition = localPosition;
- if (TryComp<PhysicsComponent>(grid, out var body))
+ if (HasComp<PhysicsComponent>(grid))
{
RaiseNetworkEvent(new GridDragVelocityRequest()
{
- Grid = grid,
+ Grid = GetNetEntity(grid),
LinearVelocity = Vector2.Zero
});
}
var distance = _lastMousePosition.Value.Position - xform.WorldPosition;
RaiseNetworkEvent(new GridDragVelocityRequest()
{
- Grid = _dragging.Value,
+ Grid = GetNetEntity(_dragging.Value),
LinearVelocity = distance.LengthSquared() > 0f ? (distance / (float) tickTime.TotalSeconds) * 0.25f : Vector2.Zero,
});
}
RaiseNetworkEvent(new GridDragRequestPosition()
{
- Grid = _dragging.Value,
+ Grid = GetNetEntity(_dragging.Value),
WorldPosition = requestedGridOrigin,
});
}
var stringContent = Rope.Collapse(_menu.ContentInput.TextRope);
- if (stringContent == null || stringContent.Length == 0) return;
- if (_gameTicker == null) return;
+ if (stringContent == null || stringContent.Length == 0)
+ return;
- NewsArticle article = new NewsArticle();
var stringName = _menu.NameInput.Text;
var name = (stringName.Length <= 25 ? stringName.Trim() : $"{stringName.Trim().Substring(0, 25)}...");
- article.Name = name;
- article.Content = stringContent;
- article.ShareTime = _gameTiming.CurTime.Subtract(_gameTicker.RoundStartTimeSpan);
-
_menu.ContentInput.TextRope = new Rope.Leaf(string.Empty);
_menu.NameInput.Text = string.Empty;
-
- SendMessage(new NewsWriteShareMessage(article));
+ SendMessage(new NewsWriteShareMessage(name, stringContent));
}
private void OnDeleteButtonPressed(int articleNum)
return;
_fragment = new MechGrabberUiFragment();
+
_fragment.OnEjectAction += e =>
{
- userInterface.SendMessage(new MechGrabberEjectMessage(fragmentOwner.Value, e));
+ var entManager = IoCManager.Resolve<IEntityManager>();
+ userInterface.SendMessage(new MechGrabberEjectMessage(entManager.GetNetEntity(fragmentOwner.Value), entManager.GetNetEntity(e)));
};
}
SpaceLabel.Text = $"{state.Contents.Count}/{state.MaxContents}";
for (var i = 0; i < state.Contents.Count; i++)
{
- var ent = state.Contents[i];
+ var ent = _entity.GetEntity(state.Contents[i]);
if (!_entity.TryGetComponent<MetaDataComponent>(ent, out var meta))
continue;
_fragment = new MechSoundboardUiFragment();
_fragment.OnPlayAction += sound =>
{
- userInterface.SendMessage(new MechSoundboardPlayMessage(fragmentOwner.Value, sound));
+ // TODO: IDK dog
+ userInterface.SendMessage(new MechSoundboardPlayMessage(IoCManager.Resolve<IEntityManager>().GetNetEntity(fragmentOwner.Value), sound));
};
}
_menu.OnRemoveButtonPressed += uid =>
{
- SendMessage(new MechEquipmentRemoveMessage(uid));
+ SendMessage(new MechEquipmentRemoveMessage(EntMan.GetNetEntity(uid)));
};
}
continue;
foreach (var (attached, estate) in state.EquipmentStates)
{
- if (ent == attached)
+ if (ent == EntMan.GetEntity(attached))
ui.UpdateState(estate);
}
}
// add a row for each sensor
foreach (var sensor in stSensors.OrderBy(a => a.Name))
{
+ var sensorEntity = _entManager.GetEntity(sensor.SuitSensorUid);
+ var coordinates = _entManager.GetCoordinates(sensor.Coordinates);
+
// add button with username
var nameButton = new CrewMonitoringButton()
{
- SuitSensorUid = sensor.SuitSensorUid,
- Coordinates = sensor.Coordinates,
+ SuitSensorUid = sensorEntity,
+ Coordinates = coordinates,
Text = sensor.Name,
Margin = new Thickness(5f, 5f),
};
- if (sensor.SuitSensorUid == _trackedButton?.SuitSensorUid)
+ if (sensorEntity == _trackedButton?.SuitSensorUid)
nameButton.AddStyleClass(StyleNano.StyleClassButtonColorGreen);
SetColorLabel(nameButton.Label, sensor.TotalDamage, sensor.IsAlive);
SensorsTable.AddChild(nameButton);
SensorsTable.AddChild(box);
_rowsContent.Add(box);
- if (sensor.Coordinates != null && NavMap.Visible)
+ if (coordinates != null && NavMap.Visible)
{
- NavMap.TrackedCoordinates.TryAdd(sensor.Coordinates.Value,
- (true, sensor.SuitSensorUid == _trackedButton?.SuitSensorUid ? StyleNano.PointGreen : StyleNano.PointRed));
+ NavMap.TrackedCoordinates.TryAdd(coordinates.Value,
+ (true, sensorEntity == _trackedButton?.SuitSensorUid ? StyleNano.PointGreen : StyleNano.PointRed));
nameButton.OnButtonUp += args =>
{
//Make previous point red
NavMap.TrackedCoordinates[_trackedButton.Coordinates.Value] = (true, StyleNano.PointRed);
- NavMap.TrackedCoordinates[sensor.Coordinates.Value] = (true, StyleNano.PointGreen);
- NavMap.CenterToCoordinates(sensor.Coordinates.Value);
+ NavMap.TrackedCoordinates[coordinates.Value] = (true, StyleNano.PointGreen);
+ NavMap.CenterToCoordinates(coordinates.Value);
nameButton.AddStyleClass(StyleNano.StyleClassButtonColorGreen);
if (_trackedButton != null)
private BoxContainer GetPositionBox(SuitSensorStatus sensor, Vector2 monitorCoordsInStationSpace, bool snap, float precision)
{
- EntityCoordinates? coordinates = sensor.Coordinates;
+ EntityCoordinates? coordinates = _entManager.GetCoordinates(sensor.Coordinates);
var box = new BoxContainer() { Orientation = LayoutOrientation.Horizontal };
if (coordinates == null || _stationUid == null)
private void OnHTNMessage(HTNMessage ev)
{
- if (!TryComp<HTNComponent>(ev.Uid, out var htn))
+ if (!TryComp<HTNComponent>(GetEntity(ev.Uid), out var htn))
return;
htn.DebugText = ev.Text;
foreach (var data in ev.Data)
{
- if (!Exists(data.EntityUid))
+ var entity = GetEntity(data.EntityUid);
+
+ if (!Exists(entity))
continue;
- var comp = EnsureComp<NPCSteeringComponent>(data.EntityUid);
+ var comp = EnsureComp<NPCSteeringComponent>(entity);
comp.Direction = data.Direction;
comp.DangerMap = data.Danger;
comp.InterestMap = data.Interest;
private PathfindingDebugMode _modes = PathfindingDebugMode.None;
// It's debug data IDC if it doesn't support snapshots I just want something fast.
- public Dictionary<EntityUid, Dictionary<Vector2i, List<PathfindingBreadcrumb>>> Breadcrumbs = new();
- public Dictionary<EntityUid, Dictionary<Vector2i, Dictionary<Vector2i, List<DebugPathPoly>>>> Polys = new();
+ public Dictionary<NetEntity, Dictionary<Vector2i, List<PathfindingBreadcrumb>>> Breadcrumbs = new();
+ public Dictionary<NetEntity, Dictionary<Vector2i, Dictionary<Vector2i, List<DebugPathPoly>>>> Polys = new();
public readonly List<(TimeSpan Time, PathRouteMessage Message)> Routes = new();
public override void Initialize()
foreach (var grid in _mapManager.FindGridsIntersecting(mouseWorldPos.MapId, aabb))
{
- if (found || !_system.Breadcrumbs.TryGetValue(grid.Owner, out var crumbs) || !xformQuery.TryGetComponent(grid.Owner, out var gridXform))
+ var netGrid = _entManager.GetNetEntity(grid.Owner);
+
+ if (found || !_system.Breadcrumbs.TryGetValue(netGrid, out var crumbs) || !xformQuery.TryGetComponent(grid.Owner, out var gridXform))
continue;
var (_, _, worldMatrix, invWorldMatrix) = gridXform.GetWorldPositionRotationMatrixWithInv();
if (!_mapManager.TryFindGridAt(mouseWorldPos, out var gridUid, out var grid) || !xformQuery.TryGetComponent(gridUid, out var gridXform))
return;
- if (!_system.Polys.TryGetValue(gridUid, out var data))
+ if (!_system.Polys.TryGetValue(_entManager.GetNetEntity(gridUid), out var data))
return;
var tileRef = grid.GetTileRef(mouseWorldPos);
{
foreach (var grid in _mapManager.FindGridsIntersecting(mouseWorldPos.MapId, aabb))
{
- if (!_system.Breadcrumbs.TryGetValue(grid.Owner, out var crumbs) ||
+ var netGrid = _entManager.GetNetEntity(grid.Owner);
+
+ if (!_system.Breadcrumbs.TryGetValue(netGrid, out var crumbs) ||
!xformQuery.TryGetComponent(grid.Owner, out var gridXform))
{
continue;
{
foreach (var grid in _mapManager.FindGridsIntersecting(args.MapId, aabb))
{
- if (!_system.Polys.TryGetValue(grid.Owner, out var data) ||
+ var netGrid = _entManager.GetNetEntity(grid.Owner);
+
+ if (!_system.Polys.TryGetValue(netGrid, out var data) ||
!xformQuery.TryGetComponent(grid.Owner, out var gridXform))
continue;
{
foreach (var grid in _mapManager.FindGridsIntersecting(args.MapId, aabb))
{
- if (!_system.Polys.TryGetValue(grid.Owner, out var data) ||
+ var netGrid = _entManager.GetNetEntity(grid.Owner);
+
+ if (!_system.Polys.TryGetValue(netGrid, out var data) ||
!xformQuery.TryGetComponent(grid.Owner, out var gridXform))
continue;
Color color;
Vector2 neighborPos;
- if (neighborPoly.EntityId != poly.GraphUid)
+ if (neighborPoly.NetEntity != poly.GraphUid)
{
color = Color.Green;
- var neighborMap = neighborPoly.ToMap(_entManager);
+ var neighborMap = _entManager.GetCoordinates(neighborPoly).ToMap(_entManager);
if (neighborMap.MapId != args.MapId)
continue;
{
foreach (var grid in _mapManager.FindGridsIntersecting(args.MapId, args.WorldBounds))
{
- if (!_system.Breadcrumbs.TryGetValue(grid.Owner, out var crumbs) ||
+ var netGrid = _entManager.GetNetEntity(grid.Owner);
+
+ if (!_system.Breadcrumbs.TryGetValue(netGrid, out var crumbs) ||
!xformQuery.TryGetComponent(grid.Owner, out var gridXform))
continue;
{
foreach (var node in route.Message.Path)
{
- if (!_entManager.TryGetComponent<TransformComponent>(node.GraphUid, out var graphXform))
+ if (!_entManager.TryGetComponent<TransformComponent>(_entManager.GetEntity(node.GraphUid), out var graphXform))
continue;
worldHandle.SetTransform(graphXform.WorldMatrix);
foreach (var (node, cost) in route.Message.Costs)
{
- if (matrix != node.GraphUid)
+ var graph = _entManager.GetEntity(node.GraphUid);
+
+ if (matrix != graph)
{
- if (!_entManager.TryGetComponent<TransformComponent>(node.GraphUid, out var graphXform))
+ if (!_entManager.TryGetComponent<TransformComponent>(graph, out var graphXform))
continue;
- matrix = node.GraphUid;
+ matrix = graph;
worldHandle.SetTransform(graphXform.WorldMatrix);
}
Entities = Groups.Values
.SelectMany(g => g.Nodes, (data, nodeData) => (data, nodeData))
- .GroupBy(n => n.nodeData.Entity)
+ .GroupBy(n => GetEntity(n.nodeData.Entity))
.ToDictionary(g => g.Key, g => g.ToArray());
NodeLookup = Groups.Values
var node = _system.NodeLookup[(groupId, nodeId)];
- var xform = _entityManager.GetComponent<TransformComponent>(node.Entity);
+ var xform = _entityManager.GetComponent<TransformComponent>(_entityManager.GetEntity(node.Entity));
if (!_mapManager.TryGetGrid(xform.GridUid, out var grid))
return;
var gridTile = grid.TileIndicesFor(xform.Coordinates);
private void AddPointingVerb(GetVerbsEvent<Verb> args)
{
- if (args.Target.IsClientSide())
+ if (IsClientSide(args.Target))
return;
// Really this could probably be a properly predicted event, but that requires reworking pointing. For now
Text = Loc.GetString("pointing-verb-get-data-text"),
Icon = new SpriteSpecifier.Texture(new ("/Textures/Interface/VerbIcons/point.svg.192dpi.png")),
ClientExclusive = true,
- Act = () => RaiseNetworkEvent(new PointingAttemptEvent(args.Target))
+ Act = () => RaiseNetworkEvent(new PointingAttemptEvent(GetNetEntity(args.Target)))
};
args.Verbs.Add(verb);
if (recordReplay && _replayRecording.IsRecording)
{
if (entity != null)
- _replayRecording.RecordClientMessage(new PopupEntityEvent(message, type, entity.Value));
+ _replayRecording.RecordClientMessage(new PopupEntityEvent(message, type, GetNetEntity(entity.Value)));
else
- _replayRecording.RecordClientMessage(new PopupCoordinatesEvent(message, type, coordinates));
+ _replayRecording.RecordClientMessage(new PopupCoordinatesEvent(message, type, GetNetCoordinates(coordinates)));
}
var label = new WorldPopupLabel(coordinates)
private void OnPopupCoordinatesEvent(PopupCoordinatesEvent ev)
{
- PopupMessage(ev.Message, ev.Type, ev.Coordinates, null, false);
+ PopupMessage(ev.Message, ev.Type, GetCoordinates(ev.Coordinates), null, false);
}
private void OnPopupEntityEvent(PopupEntityEvent ev)
{
- if (TryComp(ev.Uid, out TransformComponent? transform))
- PopupMessage(ev.Message, ev.Type, transform.Coordinates, ev.Uid, false);
+ var entity = GetEntity(ev.Uid);
+
+ if (TryComp(entity, out TransformComponent? transform))
+ PopupMessage(ev.Message, ev.Type, transform.Coordinates, entity, false);
}
private void OnRoundRestart(RoundRestartCleanupEvent ev)
private void OnProjectileImpact(ImpactEffectEvent ev)
{
- if (Deleted(ev.Coordinates.EntityId))
+ var coords = GetCoordinates(ev.Coordinates);
+
+ if (Deleted(coords.EntityId))
return;
- var ent = Spawn(ev.Prototype, ev.Coordinates);
+ var ent = Spawn(ev.Prototype, coords);
if (TryComp<SpriteComponent>(ent, out var sprite))
{
handle.DrawString(_font, screenCenter, ray.Rads.ToString("F2"), 2f, Color.White);
}
- foreach (var (gridUid, blockers) in ray.Blockers)
+ foreach (var (netGrid, blockers) in ray.Blockers)
{
+ var gridUid = _entityManager.GetEntity(netGrid);
+
if (!_mapManager.TryGetGrid(gridUid, out var grid))
continue;
var handle = args.ScreenHandle;
var query = _entityManager.GetEntityQuery<TransformComponent>();
- foreach (var (gridUid, resMap) in resistance)
+ foreach (var (netGrid, resMap) in resistance)
{
+ var gridUid = _entityManager.GetEntity(netGrid);
+
if (!_mapManager.TryGetGrid(gridUid, out var grid))
continue;
if (query.TryGetComponent(gridUid, out var trs) && trs.MapID != args.MapId)
continue;
}
- foreach (var (gridUid, blockers) in ray.Blockers)
+ foreach (var (netGrid, blockers) in ray.Blockers)
{
+ var gridUid = _entityManager.GetEntity(netGrid);
+
if (!_mapManager.TryGetGrid(gridUid, out var grid))
continue;
var (destTile, _) = blockers.Last();
component.CurrentRadiation = state.CurrentRadiation;
component.DangerLevel = state.DangerLevel;
component.IsEnabled = state.IsEnabled;
- component.User = state.User;
+ component.User = EnsureEntity<GeigerComponent>(state.User, uid);
component.UiUpdateNeeded = true;
}
[Dependency] private readonly IOverlayManager _overlayMan = default!;
public List<RadiationRay>? Rays;
- public Dictionary<EntityUid, Dictionary<Vector2i, float>>? ResistanceGrids;
+ public Dictionary<NetEntity, Dictionary<Vector2i, float>>? ResistanceGrids;
public override void Initialize()
{
var str = $"Radiation update: {ev.ElapsedTimeMs}ms with. Receivers: {ev.ReceiversCount}, " +
$"Sources: {ev.SourcesCount}, Rays: {ev.Rays.Count}";
- Logger.Info(str);
+ Log.Info(str);
Rays = ev.Rays;
}
private void OnResistanceUpdate(OnRadiationOverlayResistanceUpdateEvent ev)
{
- if (!_overlayMan.TryGetOverlay(out RadiationDebugOverlay? overlay))
- return;
ResistanceGrids = ev.Grids;
}
}
return;
}
- if (!player.IsClientSide() || !HasComp<ReplaySpectatorComponent>(player))
+ if (!IsClientSide(player) || !HasComp<ReplaySpectatorComponent>(player))
{
// Player is trying to move -> behave like the ghost-on-move component.
SpawnSpectatorGhost(new EntityCoordinates(player, default), true);
_dir = dir;
}
- public override bool HandleCmdMessage(ICommonSession? session, InputCmdMessage message)
+ public override bool HandleCmdMessage(IEntityManager entManager, ICommonSession? session, IFullInputCmdMessage message)
{
- if (message is not FullInputCmdMessage full)
- return false;
-
- if (full.State == BoundKeyState.Down)
+ if (message.State == BoundKeyState.Down)
_sys.Direction |= _dir;
else
_sys.Direction &= ~_dir;
private void OnDetached(EntityUid uid, ReplaySpectatorComponent component, PlayerDetachedEvent args)
{
- if (uid.IsClientSide())
+ if (IsClientSide(uid))
QueueDel(uid);
else
RemCompDeferred(uid, component);
if (old == null)
return;
- if (old.Value.IsClientSide())
+ if (IsClientSide(old.Value))
Del(old.Value);
else
RemComp<ReplaySpectatorComponent>(old.Value);
if (old != null)
{
- if (old.Value.IsClientSide())
+ if (IsClientSide(old.Value))
QueueDel(old.Value);
else
RemComp<ReplaySpectatorComponent>(old.Value);
return;
}
- if (!EntityUid.TryParse(args[0], out var uid))
+ if (!NetEntity.TryParse(args[0], out var netEntity))
{
shell.WriteError(Loc.GetString("cmd-parse-failure-uid", ("arg", args[0])));
return;
}
+ var uid = GetEntity(netEntity);
+
if (!Exists(uid))
{
shell.WriteError(Loc.GetString("cmd-parse-failure-entity-exist", ("arg", args[0])));
if (args.Length != 1)
return CompletionResult.Empty;
- return CompletionResult.FromHintOptions(CompletionHelper.EntityUids(args[0],
+ return CompletionResult.FromHintOptions(CompletionHelper.NetEntities(args[0],
EntityManager), Loc.GetString("cmd-replay-spectate-hint"));
}
}
VerticalExpand = true,
};
- if (_entityManager.HasComponent<SpriteComponent>(playerInfo.PlayerEntityUid))
+ var playerUid = _entityManager.GetEntity(playerInfo.PlayerNetEntity);
+
+ if (_entityManager.HasComponent<SpriteComponent>(playerUid))
{
var spriteView = new SpriteView
{
SetSize = new Vector2(32, 32),
VerticalExpand = true,
};
- spriteView.SetEntity(playerInfo.PlayerEntityUid);
+ spriteView.SetEntity(playerUid);
hBox.AddChild(spriteView);
}
private void OnFultonMessage(FultonAnimationMessage ev)
{
- if (Deleted(ev.Entity) || !TryComp<SpriteComponent>(ev.Entity, out var entSprite))
+ var entity = GetEntity(ev.Entity);
+ var coordinates = GetCoordinates(ev.Coordinates);
+
+ if (Deleted(entity) || !TryComp<SpriteComponent>(entity, out var entSprite))
return;
- var animationEnt = Spawn(null, ev.Coordinates);
+ var animationEnt = Spawn(null, coordinates);
// TODO: Spawn fulton layer
var sprite = AddComp<SpriteComponent>(animationEnt);
_serManager.CopyTo(entSprite, ref sprite, notNullableOverride: true);
- if (TryComp<AppearanceComponent>(ev.Entity, out var entAppearance))
+ if (TryComp<AppearanceComponent>(entity, out var entAppearance))
{
var appearance = AddComp<AppearanceComponent>(animationEnt);
_serManager.CopyTo(entAppearance, ref appearance, notNullableOverride: true);
base.UpdateState(state);
if (state is not RadarConsoleBoundInterfaceState cState) return;
- _window?.SetMatrix(cState.Coordinates, cState.Angle);
+ _window?.SetMatrix(EntMan.GetCoordinates(cState.Coordinates), cState.Angle);
_window?.UpdateState(cState);
}
}
_window.OnClose += OnClose;
}
- private void OnDestinationPressed(EntityUid obj)
+ private void OnDestinationPressed(NetEntity obj)
{
SendMessage(new ShuttleConsoleFTLRequestMessage()
{
}
}
- private void OnStopAutodockPressed(EntityUid obj)
+ private void OnStopAutodockPressed(NetEntity obj)
{
SendMessage(new StopAutodockRequestMessage() { DockEntity = obj });
}
- private void OnAutodockPressed(EntityUid obj)
+ private void OnAutodockPressed(NetEntity obj)
{
SendMessage(new AutodockRequestMessage() { DockEntity = obj });
}
- private void OnUndockPressed(EntityUid obj)
+ private void OnUndockPressed(NetEntity obj)
{
SendMessage(new UndockRequestMessage() { DockEntity = obj });
}
base.UpdateState(state);
if (state is not ShuttleConsoleBoundInterfaceState cState) return;
- _window?.SetMatrix(cState.Coordinates, cState.Angle);
+ _window?.SetMatrix(EntMan.GetCoordinates(cState.Coordinates), cState.Angle);
_window?.UpdateState(cState);
}
}
{
if (args.Current is not PilotComponentState state) return;
- var console = state.Console.GetValueOrDefault();
- if (!console.IsValid())
+ var console = EnsureEntity<PilotComponent>(state.Console, uid);
+
+ if (console == null)
{
component.Console = null;
_input.Contexts.SetActiveContext("human");
{
if (_overlay == null) return;
- _overlay.StationUid = ev.StationUid;
+ _overlay.StationUid = GetEntity(ev.StationUid);
_overlay.Position = ev.Position;
}
}
private int ScaledMinimapRadius => (int) (MapGridControl.UIDisplayRadius * UIScale);
private float MinimapScale => _range != 0 ? ScaledMinimapRadius / _range : 0f;
- public EntityUid? ViewedDock;
+ public NetEntity? ViewedDock;
public EntityUid? GridEntity;
public EntityCoordinates? Coordinates;
/// <summary>
/// Stored by GridID then by docks
/// </summary>
- public Dictionary<EntityUid, List<DockingInterfaceState>> Docks = new();
+ public Dictionary<NetEntity, List<DockingInterfaceState>> Docks = new();
public DockingControl()
{
}
// Draw any docks on that grid
- if (Docks.TryGetValue(grid.Owner, out var gridDocks))
+ if (Docks.TryGetValue(_entManager.GetNetEntity(grid.Owner), out var gridDocks))
{
foreach (var dock in gridDocks)
{
foreach (var state in ls.Docks)
{
var coordinates = state.Coordinates;
- var grid = _docks.GetOrNew(coordinates.EntityId);
+ var grid = _docks.GetOrNew(_entManager.GetEntity(coordinates.NetEntity));
grid.Add(state);
}
}
{
foreach (var state in docks)
{
- var ent = state.Entity;
+ var ent = _entManager.GetEntity(state.Entity);
var position = state.Coordinates.Position;
var uiPosition = matrix.Transform(position);
private readonly IEntityManager _entManager;
private readonly IGameTiming _timing;
- private EntityUid? _shuttleUid;
+ private EntityUid? _shuttleEntity;
/// <summary>
/// Currently selected dock button for camera.
/// <summary>
/// Stored by grid entityid then by states
/// </summary>
- private readonly Dictionary<EntityUid, List<DockingInterfaceState>> _docks = new();
+ private readonly Dictionary<NetEntity, List<DockingInterfaceState>> _docks = new();
- private readonly Dictionary<BaseButton, EntityUid> _destinations = new();
+ private readonly Dictionary<BaseButton, NetEntity> _destinations = new();
/// <summary>
/// Next FTL state change.
/// </summary>
public TimeSpan FTLTime;
- public Action<EntityUid>? UndockPressed;
- public Action<EntityUid>? StartAutodockPressed;
- public Action<EntityUid>? StopAutodockPressed;
- public Action<EntityUid>? DestinationPressed;
+ public Action<NetEntity>? UndockPressed;
+ public Action<NetEntity>? StartAutodockPressed;
+ public Action<NetEntity>? StopAutodockPressed;
+ public Action<NetEntity>? DestinationPressed;
public ShuttleConsoleWindow()
{
public void SetMatrix(EntityCoordinates? coordinates, Angle? angle)
{
- _shuttleUid = coordinates?.EntityId;
+ _shuttleEntity = coordinates?.EntityId;
RadarScreen.SetMatrix(coordinates, angle);
}
MaxRadarRange.Text = $"{scc.MaxRange:0}";
}
- private void UpdateFTL(List<(EntityUid Entity, string Destination, bool Enabled)> destinations, FTLState state, TimeSpan time)
+ private void UpdateFTL(List<(NetEntity Entity, string Destination, bool Enabled)> destinations, FTLState state, TimeSpan time)
{
HyperspaceDestinations.DisposeAllChildren();
_destinations.Clear();
foreach (var dock in docks)
{
- var grid = _docks.GetOrNew(dock.Coordinates.EntityId);
+ var grid = _docks.GetOrNew(dock.Coordinates.NetEntity);
grid.Add(dock);
}
DockPorts.DisposeAllChildren();
DockingScreen.Docks = _docks;
+ var shuttleNetEntity = _entManager.GetNetEntity(_shuttleEntity);
- if (_shuttleUid != null && _docks.TryGetValue(_shuttleUid.Value, out var gridDocks))
+ if (shuttleNetEntity != null && _docks.TryGetValue(shuttleNetEntity.Value, out var gridDocks))
{
var index = 1;
private void OnDockMouseEntered(GUIMouseHoverEventArgs obj, DockingInterfaceState state)
{
- RadarScreen.HighlightedDock = state.Entity;
+ RadarScreen.HighlightedDock = _entManager.GetEntity(state.Entity);
}
private void OnDockMouseExited(GUIMouseHoverEventArgs obj, DockingInterfaceState state)
/// </summary>
private void OnDockToggled(BaseButton.ButtonEventArgs obj, DockingInterfaceState state)
{
- var ent = state.Entity;
-
if (_selectedDock != null)
{
// If it got untoggled via other means then we'll stop viewing the old dock.
}
else
{
- if (_shuttleUid != null)
+ if (_shuttleEntity != null)
{
- DockingScreen.Coordinates = state.Coordinates;
+ DockingScreen.Coordinates = _entManager.GetCoordinates(state.Coordinates);
DockingScreen.Angle = state.Angle;
}
else
UndockButton.Disabled = false;
RadarScreen.Visible = false;
DockingScreen.Visible = true;
- DockingScreen.ViewedDock = ent;
- StartAutodockPressed?.Invoke(ent);
- DockingScreen.GridEntity = _shuttleUid;
+ DockingScreen.ViewedDock = state.Entity;
+ StartAutodockPressed?.Invoke(state.Entity);
+ DockingScreen.GridEntity = _shuttleEntity;
_selectedDock = obj.Button;
}
}
{
base.Draw(handle);
- if (!_entManager.TryGetComponent<PhysicsComponent>(_shuttleUid, out var gridBody) ||
- !_entManager.TryGetComponent<TransformComponent>(_shuttleUid, out var gridXform))
+ if (!_entManager.TryGetComponent<PhysicsComponent>(_shuttleEntity, out var gridBody) ||
+ !_entManager.TryGetComponent<TransformComponent>(_shuttleEntity, out var gridXform))
{
return;
}
- if (_entManager.TryGetComponent<MetaDataComponent>(_shuttleUid, out var metadata) && metadata.EntityPaused)
+ if (_entManager.TryGetComponent<MetaDataComponent>(_shuttleEntity, out var metadata) && metadata.EntityPaused)
{
FTLTime += _timing.FrameTime;
}
_menu.RemoveModuleButtonPressed += module =>
{
- SendMessage(new BorgRemoveModuleBuiMessage(module));
+ SendMessage(new BorgRemoveModuleBuiMessage(EntMan.GetNetEntity(module)));
};
_menu.OnClose += Close;
{
protected override bool CanDelete(EntityUid uid)
{
- return uid.IsClientSide();
+ return IsClientSide(uid);
}
}
private void StationsUpdated(StationsUpdatedEvent ev)
{
_stations.Clear();
- _stations.UnionWith(ev.Stations);
+ // TODO this needs to be dona in component states and with the Ensure() methods
+ _stations.UnionWith(GetEntitySet(ev.Stations));
}
}
private void OnKeySelected(StationRecordKey? key)
{
- SendMessage(new SelectGeneralStationRecord(key));
+ SendMessage(new SelectGeneralStationRecord(EntMan.System<SharedStationRecordsSystem>().Convert(key)));
}
private void OnFiltersChanged(
RecordContainer.RemoveAllChildren();
}
}
- private void PopulateRecordListing(Dictionary<StationRecordKey, string> listing, StationRecordKey? selected)
+ private void PopulateRecordListing(Dictionary<(NetEntity, uint), string> listing, (NetEntity, uint)? selected)
{
RecordListing.Clear();
RecordListing.ClearSelected();
{
var item = RecordListing.AddItem(name);
item.Metadata = key;
- if (selected != null && key.ID == selected.Value.ID)
+ if (selected != null && key.Item1 == selected.Value.Item1 && key.Item2 == selected.Value.Item2)
{
item.Selected = true;
}
--- /dev/null
+using Content.Shared.StationRecords;
+
+namespace Content.Client.StationRecords;
+
+public sealed class StationRecordsSystem : SharedStationRecordsSystem
+{
+}
if (args.Event.Function == EngineKeyFunctions.UIClick)
{
- SendMessage(new StorageInteractWithItemEvent(entity));
+ SendMessage(new StorageInteractWithItemEvent(EntMan.GetNetEntity(entity)));
}
else if (EntMan.EntityExists(entity))
{
else if (args.Function == ContentKeyFunctions.ActivateItemInWorld)
{
EntMan.EntityNetManager?.SendSystemNetworkMessage(
- new InteractInventorySlotEvent(entity, altInteract: false));
+ new InteractInventorySlotEvent(EntMan.GetNetEntity(entity), altInteract: false));
}
else if (args.Function == ContentKeyFunctions.AltActivateItemInWorld)
{
- EntMan.RaisePredictiveEvent(new InteractInventorySlotEvent(entity, altInteract: true));
+ EntMan.RaisePredictiveEvent(new InteractInventorySlotEvent(EntMan.GetNetEntity(entity), altInteract: true));
}
else
{
/// <param name="msg"></param>
public void HandleAnimatingInsertingEntities(AnimateInsertingEntitiesEvent msg)
{
- if (!TryComp(msg.Storage, out ClientStorageComponent? storage))
+ var store = GetEntity(msg.Storage);
+
+ if (!HasComp<ClientStorageComponent>(store))
return;
- TryComp(msg.Storage, out TransformComponent? transformComp);
+ TryComp(store, out TransformComponent? transformComp);
for (var i = 0; msg.StoredEntities.Count > i; i++)
{
- var entity = msg.StoredEntities[i];
+ var entity = GetEntity(msg.StoredEntities[i]);
var initialPosition = msg.EntityPositions[i];
if (EntityManager.EntityExists(entity) && transformComp != null)
{
- ReusableAnimations.AnimateEntityPickup(entity, initialPosition, transformComp.LocalPosition, msg.EntityAngles[i], EntityManager);
+ ReusableAnimations.AnimateEntityPickup(entity, GetCoordinates(initialPosition), transformComp.LocalPosition, msg.EntityAngles[i], EntityManager);
}
}
}
/// </summary>
public void BuildEntityList(StorageBoundUserInterfaceState state)
{
- var list = state.StoredEntities.ConvertAll(uid => new EntityListData(uid));
+ var list = state.StoredEntities.ConvertAll(nent => new EntityListData(_entityManager.GetEntity(nent)));
EntityList.PopulateList(list);
//Sets information about entire storage container current capacity
return;
}
- if (cast.ActiveCamera == null)
+ var active = EntMan.GetEntity(cast.ActiveCamera);
+
+ if (active == null)
{
_window.UpdateState(null, cast.Subnets, cast.ActiveAddress, cast.ActiveSubnet, cast.Cameras);
{
if (_currentCamera == null)
{
- _eyeLerpingSystem.AddEye(cast.ActiveCamera.Value);
- _currentCamera = cast.ActiveCamera;
+ _eyeLerpingSystem.AddEye(active.Value);
+ _currentCamera = active;
}
- else if (_currentCamera != cast.ActiveCamera)
+ else if (_currentCamera != active)
{
_eyeLerpingSystem.RemoveEye(_currentCamera.Value);
- _eyeLerpingSystem.AddEye(cast.ActiveCamera.Value);
- _currentCamera = cast.ActiveCamera;
+ _eyeLerpingSystem.AddEye(active.Value);
+ _currentCamera = active;
}
- if (EntMan.TryGetComponent<EyeComponent>(cast.ActiveCamera, out var eye))
+ if (EntMan.TryGetComponent<EyeComponent>(active, out var eye))
{
_window.UpdateState(eye.Eye, cast.Subnets, cast.ActiveAddress, cast.ActiveSubnet, cast.Cameras);
}
// Only send new position to server when Delay is reached
if (_timePassed >= Delay && _table != null)
{
- RaisePredictiveEvent(new TabletopMoveEvent(_draggedEntity.Value, clampedCoords, _table.Value));
+ RaisePredictiveEvent(new TabletopMoveEvent(GetNetEntity(_draggedEntity.Value), clampedCoords, GetNetEntity(_table.Value)));
_timePassed -= Delay;
}
}
// Close the currently opened window, if it exists
_window?.Close();
- _table = msg.TableUid;
+ _table = GetEntity(msg.TableUid);
// Get the camera entity that the server has created for us
- var camera = msg.CameraUid;
+ var camera = GetEntity(msg.CameraUid);
if (!EntityManager.TryGetComponent<EyeComponent>(camera, out var eyeComponent))
{
// If there is no eye, print error and do not open any window
- Logger.Error("Camera entity does not have eye component!");
+ Log.Error("Camera entity does not have eye component!");
return;
}
{
if (_table != null)
{
- RaiseNetworkEvent(new TabletopStopPlayingEvent(_table.Value));
+ RaiseNetworkEvent(new TabletopStopPlayingEvent(GetNetEntity(_table.Value)));
}
StopDragging();
{
if (_draggedEntity != null && _table != null)
{
- var ev = new TabletopRequestTakeOut();
- ev.Entity = _draggedEntity.Value;
- ev.TableUid = _table.Value;
+ var ev = new TabletopRequestTakeOut
+ {
+ Entity = GetNetEntity(_draggedEntity.Value),
+ TableUid = GetNetEntity(_table.Value)
+ };
RaiseNetworkEvent(ev);
}
return false;
if (_playerManager.LocalPlayer is not {ControlledEntity: { } playerEntity})
return false;
+ var entity = args.EntityUid;
+
// Return if can not see table or stunned/no hands
- if (!CanSeeTable(playerEntity, _table) || !CanDrag(playerEntity, args.EntityUid, out _))
+ if (!CanSeeTable(playerEntity, _table) || !CanDrag(playerEntity, entity, out _))
{
return false;
}
return false;
}
- StartDragging(args.EntityUid, viewport);
+ StartDragging(entity, viewport);
return true;
}
/// <param name="viewport">The viewport in which we are dragging.</param>
private void StartDragging(EntityUid draggedEntity, ScalingViewport viewport)
{
- RaisePredictiveEvent(new TabletopDraggingPlayerChangedEvent(draggedEntity, true));
+ RaisePredictiveEvent(new TabletopDraggingPlayerChangedEvent(GetNetEntity(draggedEntity), true));
_draggedEntity = draggedEntity;
_viewport = viewport;
// Set the dragging player on the component to noone
if (broadcast && _draggedEntity != null && EntityManager.HasComponent<TabletopDraggableComponent>(_draggedEntity.Value))
{
- RaisePredictiveEvent(new TabletopMoveEvent(_draggedEntity.Value, Transform(_draggedEntity.Value).MapPosition, _table!.Value));
- RaisePredictiveEvent(new TabletopDraggingPlayerChangedEvent(_draggedEntity.Value, false));
+ RaisePredictiveEvent(new TabletopMoveEvent(GetNetEntity(_draggedEntity.Value), Transform(_draggedEntity.Value).MapPosition, GetNetEntity(_table!.Value)));
+ RaisePredictiveEvent(new TabletopDraggingPlayerChangedEvent(GetNetEntity(_draggedEntity.Value), false));
}
_draggedEntity = null;
_actionsSystem.PerformAction(user, actionComp, actionId, action, action.Event, _timing.CurTime);
}
else
- EntityManager.RaisePredictiveEvent(new RequestPerformActionEvent(actionId, coords));
+ EntityManager.RaisePredictiveEvent(new RequestPerformActionEvent(EntityManager.GetNetEntity(actionId), EntityManager.GetNetCoordinates(coords)));
if (!action.Repeat)
StopTargeting();
if (_actionsSystem == null)
return false;
- if (!_actionsSystem.ValidateEntityTarget(user, args.EntityUid, action))
+ var entity = args.EntityUid;
+
+ if (!_actionsSystem.ValidateEntityTarget(user, entity, action))
{
if (action.DeselectOnMiss)
StopTargeting();
{
if (action.Event != null)
{
- action.Event.Target = args.EntityUid;
+ action.Event.Target = entity;
action.Event.Performer = user;
}
_actionsSystem.PerformAction(user, actionComp, actionId, action, action.Event, _timing.CurTime);
}
else
- EntityManager.RaisePredictiveEvent(new RequestPerformActionEvent(actionId, args.EntityUid));
+ EntityManager.RaisePredictiveEvent(new RequestPerformActionEvent(EntityManager.GetNetEntity(actionId), EntityManager.GetNetEntity(args.EntityUid)));
if (!action.Repeat)
StopTargeting();
{
if (_actionsSystem != null && _actionsSystem.TryGetActionData(_menuDragHelper.Dragged?.ActionId, out var action))
{
- if (action.EntityIcon != null)
+ var entIcon = action.EntityIcon;
+
+ if (entIcon != null)
{
- _dragShadow.Texture = EntityManager.GetComponent<SpriteComponent>(action.EntityIcon.Value).Icon?
+ _dragShadow.Texture = EntityManager.GetComponent<SpriteComponent>(entIcon.Value).Icon?
.GetFrame(RSI.State.Direction.South, 0);
}
else if (action.Icon != null)
SelectingTargetFor = actionId;
// override "held-item" overlay
+ var provider = action.Provider;
+
if (action.TargetingIndicator && _overlays.TryGetOverlay<ShowHandItemOverlay>(out var handOverlay))
{
if (action.ItemIconStyle == ItemActionIconStyle.BigItem && action.Provider != null)
{
- handOverlay.EntityOverride = action.Provider;
+ handOverlay.EntityOverride = provider;
}
else if (action.Toggled && action.IconOn != null)
handOverlay.IconOverride = _spriteSystem.Frame0(action.IconOn);
return;
Func<EntityUid, bool>? predicate = null;
+ var attachedEnt = entityAction.AttachedEntity;
if (!entityAction.CanTargetSelf)
- predicate = e => e != entityAction.AttachedEntity;
+ predicate = e => e != attachedEnt;
var range = entityAction.CheckCanAccess ? action.Range : -1;
[Dependency] private readonly IClientAdminManager _admin = default!;
[Dependency] private readonly IChatManager _manager = default!;
[Dependency] private readonly IConfigurationManager _config = default!;
- [Dependency] private readonly IEntityManager _entities = default!;
[Dependency] private readonly IEyeManager _eye = default!;
[Dependency] private readonly IInputManager _input = default!;
[Dependency] private readonly IClientNetManager _net = default!;
private void AddSpeechBubble(ChatMessage msg, SpeechBubble.SpeechType speechType)
{
- if (!_entities.EntityExists(msg.SenderEntity))
+ var ent = EntityManager.GetEntity(msg.SenderEntity);
+
+ if (!EntityManager.EntityExists(ent))
{
_sawmill.Debug("Got local chat message with invalid sender entity: {0}", msg.SenderEntity);
return;
foreach (var message in messages)
{
- EnqueueSpeechBubble(msg.SenderEntity, message, speechType);
+ EnqueueSpeechBubble(ent, message, speechType);
}
}
private void CreateSpeechBubble(EntityUid entity, SpeechBubbleData speechData)
{
var bubble =
- SpeechBubble.CreateSpeechBubble(speechData.Type, speechData.Message, entity, _eye, _manager, _entities);
+ SpeechBubble.CreateSpeechBubble(speechData.Type, speechData.Message, entity, _eye, _manager, EntityManager);
bubble.OnDied += SpeechBubbleDied;
private void EnqueueSpeechBubble(EntityUid entity, string contents, SpeechBubble.SpeechType speechType)
{
// Don't enqueue speech bubbles for other maps. TODO: Support multiple viewports/maps?
- if (_entities.GetComponent<TransformComponent>(entity).MapID != _eye.CurrentMap)
+ if (EntityManager.GetComponent<TransformComponent>(entity).MapID != _eye.CurrentMap)
return;
if (!_queuedSpeechBubbles.TryGetValue(entity, out var queueData))
foreach (var (entity, queueData) in _queuedSpeechBubbles.ShallowClone())
{
- if (!_entities.EntityExists(entity))
+ if (!EntityManager.EntityExists(entity))
{
_queuedSpeechBubbles.Remove(entity);
continue;
var predicate = static (EntityUid uid, (EntityUid compOwner, EntityUid? attachedEntity) data)
=> uid == data.compOwner || uid == data.attachedEntity;
var playerPos = player != null
- ? _entities.GetComponent<TransformComponent>(player.Value).MapPosition
+ ? EntityManager.GetComponent<TransformComponent>(player.Value).MapPosition
: MapCoordinates.Nullspace;
var occluded = player != null && _examine.IsOccluded(player.Value);
foreach (var (ent, bubs) in _activeSpeechBubbles)
{
- if (_entities.Deleted(ent))
+ if (EntityManager.Deleted(ent))
{
SetBubbles(bubs, false);
continue;
continue;
}
- var otherPos = _entities.GetComponent<TransformComponent>(ent).MapPosition;
+ var otherPos = EntityManager.GetComponent<TransformComponent>(ent).MapPosition;
if (occluded && !ExamineSystemShared.InRangeUnOccluded(
playerPos,
RobustXamlLoader.Load(this);
}
- public void UpdateWarps(IEnumerable<GhostWarp> warps)
+ public void UpdateWarps(IEnumerable<GhostWarp> warps, IEntityManager entManager)
{
// Server COULD send these sorted but how about we just use the client to do it instead
_warps = warps
? Loc.GetString("ghost-target-window-current-button", ("name", w.DisplayName))
: w.DisplayName;
- return (name, w.Entity);
+ return (name, entManager.GetEntity(w.Entity));
})
.ToList();
}
[UsedImplicitly]
public sealed class MakeGhostRoleEui : BaseEui
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
[Dependency] private readonly IPlayerManager _playerManager = default!;
[Dependency] private readonly IClientConsoleHost _consoleHost = default!;
return;
}
- _window.SetEntity(uiState.EntityUid);
+ _window.SetEntity(_entManager.GetEntity(uiState.EntityUid));
}
public override void Opened()
if (Gui?.TargetWindow is not { } window)
return;
- window.UpdateWarps(msg.Warps);
+ window.UpdateWarps(msg.Warps, EntityManager);
window.Populate();
}
private void OnWarpClicked(EntityUid player)
{
- var msg = new GhostWarpToTargetRequestEvent(player);
+ var msg = new GhostWarpToTargetRequestEvent(EntityManager.GetNetEntity(player));
_net.SendSystemNetworkMessage(msg);
}
[UISystemDependency] private readonly ClientInventorySystem _inventorySystem = default!;
[UISystemDependency] private readonly HandsSystem _handsSystem = default!;
+ [UISystemDependency] private readonly ContainerSystem _container = default!;
private EntityUid? _playerUid;
private InventorySlotsComponent? _playerInventory;
var hoverEntity = _entities.SpawnEntity("hoverentity", MapCoordinates.Nullspace);
var hoverSprite = _entities.GetComponent<SpriteComponent>(hoverEntity);
var fits = _inventorySystem.CanEquip(player.Value, held, control.SlotName, out _, slotDef) &&
- container.CanInsert(held, _entities);
+ _container.CanInsert(held, container);
hoverSprite.CopyFrom(sprite);
hoverSprite.Color = fits ? new Color(0, 255, 0, 127) : new Color(255, 0, 0, 127);
if (args.Current is not RiderComponentState state)
return;
+ var entity = EnsureEntity<RiderComponent>(state.Entity, uid);
+
if (TryComp(uid, out EyeComponent? eyeComp) && eyeComp.Target == component.Vehicle)
- eyeComp.Target = state.Entity;
+ eyeComp.Target = entity;
- component.Vehicle = state.Entity;
+ component.Vehicle = entity;
}
private void OnVehicleAppearanceChange(EntityUid uid, VehicleComponent component, ref AppearanceChangeEvent args)
OverrideDirection = Direction.South,
SetSize = new Vector2(ElementHeight, ElementHeight),
};
- spriteView.SetEntity(verb.IconEntity.Value);
+ spriteView.SetEntity(entManager.GetEntity(verb.IconEntity.Value));
Icon.AddChild(spriteView);
return;
// Add indicator that some verbs may be missing.
// I long for the day when verbs will all be predicted and this becomes unnecessary.
- if (!target.IsClientSide())
+ if (!EntityManager.IsClientSide(target))
{
_context.AddElement(menu, new ContextMenuElement(Loc.GetString("verb-system-waiting-on-server-text")));
}
private void HandleVerbsResponse(VerbsResponseEvent msg)
{
- if (OpenMenu == null || !OpenMenu.Visible || CurrentTarget != msg.Entity)
+ if (OpenMenu == null || !OpenMenu.Visible || CurrentTarget != EntityManager.GetEntity(msg.Entity))
return;
AddServerVerbs(msg.Verbs, OpenMenu);
public SortedSet<Verb> GetVerbs(EntityUid target, EntityUid user, List<Type> verbTypes,
bool force = false)
{
- if (!target.IsClientSide())
+ if (!IsClientSide(target))
{
- RaiseNetworkEvent(new RequestServerVerbsEvent(target, verbTypes, adminRequest: force));
+ RaiseNetworkEvent(new RequestServerVerbsEvent(GetNetEntity(target), verbTypes, adminRequest: force));
}
// Some admin menu interactions will try get verbs for entities that have not yet been sent to the player.
return;
}
- if (verb.ClientExclusive || target.IsClientSide())
+ if (verb.ClientExclusive || IsClientSide(target))
// is this a client exclusive (gui) verb?
ExecuteVerb(verb, user.Value, target);
else
- EntityManager.RaisePredictiveEvent(new ExecuteVerbEvent(target, verb));
+ EntityManager.RaisePredictiveEvent(new ExecuteVerbEvent(GetNetEntity(target), verb));
}
private void HandleVerbResponse(VerbsResponseEvent msg)
{
if (weapon.Attacking)
{
- RaisePredictiveEvent(new StopAttackEvent(weaponUid));
+ RaisePredictiveEvent(new StopAttackEvent(GetNetEntity(weaponUid)));
}
}
target = screen.GetClickedEntity(mousePos);
}
- EntityManager.RaisePredictiveEvent(new DisarmAttackEvent(target, coordinates));
+ EntityManager.RaisePredictiveEvent(new DisarmAttackEvent(GetNetEntity(target), GetNetCoordinates(coordinates)));
return;
}
target = screen.GetClickedEntity(mousePos);
}
- RaisePredictiveEvent(new LightAttackEvent(target, weaponUid, coordinates));
+ RaisePredictiveEvent(new LightAttackEvent(GetNetEntity(target), GetNetEntity(weaponUid), GetNetCoordinates(coordinates)));
}
}
return false;
}
+ var target = GetEntity(ev.Target);
+
// They need to either have hands...
- if (!HasComp<HandsComponent>(ev.Target!.Value))
+ if (!HasComp<HandsComponent>(target!.Value))
{
// or just be able to be shoved over.
- if (TryComp<StatusEffectsComponent>(ev.Target!.Value, out var status) && status.AllowedEffects.Contains("KnockedDown"))
+ if (TryComp<StatusEffectsComponent>(target, out var status) && status.AllowedEffects.Contains("KnockedDown"))
return true;
- if (Timing.IsFirstTimePredicted && HasComp<MobStateComponent>(ev.Target.Value))
- PopupSystem.PopupEntity(Loc.GetString("disarm-action-disarmable", ("targetName", ev.Target.Value)), ev.Target.Value);
+ if (Timing.IsFirstTimePredicted && HasComp<MobStateComponent>(target.Value))
+ PopupSystem.PopupEntity(Loc.GetString("disarm-action-disarmable", ("targetName", target.Value)), target.Value);
return false;
}
// This should really be improved. GetEntitiesInArc uses pos instead of bounding boxes.
// Server will validate it with InRangeUnobstructed.
- var entities = ArcRayCast(userPos, direction.ToWorldAngle(), component.Angle, distance, userXform.MapID, user).ToList();
- RaisePredictiveEvent(new HeavyAttackEvent(meleeUid, entities.GetRange(0, Math.Min(MaxTargets, entities.Count)), coordinates));
+ var entities = GetNetEntityList(ArcRayCast(userPos, direction.ToWorldAngle(), component.Angle, distance, userXform.MapID, user).ToList());
+ RaisePredictiveEvent(new HeavyAttackEvent(GetNetEntity(meleeUid), entities.GetRange(0, Math.Min(MaxTargets, entities.Count)), GetNetCoordinates(coordinates)));
}
private void OnMeleeLunge(MeleeLungeEvent ev)
{
+ var ent = GetEntity(ev.Entity);
+
// Entity might not have been sent by PVS.
- if (Exists(ev.Entity))
- DoLunge(ev.Entity, ev.Angle, ev.LocalPos, ev.Animation);
+ if (Exists(ent))
+ DoLunge(ent, ev.Angle, ev.LocalPos, ev.Animation);
}
}
RaisePredictiveEvent(new RequestTetherMoveEvent()
{
- Coordinates = coords
+ Coordinates = GetNetCoordinates(coords)
});
}
EnsureShootable(ent.Value);
}
- if (ent != null && ent.Value.IsClientSide())
+ if (ent != null && IsClientSide(ent.Value))
Del(ent.Value);
var cycledEvent = new GunCycledEvent();
// This is dirty af. Prediction moment.
// We may be predicting spawning entities and the engine just removes them from the container so we'll just delete them.
- if (removedArgs.Entity.IsClientSide())
+ if (IsClientSide(removedArgs.Entity))
QueueDel(args.Entity);
// AFAIK the only main alternative is having some client-specific handling via a bool or otherwise for the state.
private void OnRevolverEntRemove(EntityUid uid, RevolverAmmoProviderComponent component, EntRemovedFromContainerMessage args)
{
- if (args.Container.ID != RevolverContainer) return;
+ if (args.Container.ID != RevolverContainer)
+ return;
// See ChamberMagazineAmmoProvider
- if (!args.Entity.IsClientSide()) return;
+ if (!IsClientSide(args.Entity))
+ return;
QueueDel(args.Entity);
}
using Robust.Shared.Animations;
using Robust.Shared.Input;
using Robust.Shared.Map;
+using Robust.Shared.Prototypes;
using Robust.Shared.Utility;
using SharedGunSystem = Content.Shared.Weapons.Ranged.Systems.SharedGunSystem;
[Dependency] private readonly InputSystem _inputSystem = default!;
[Dependency] private readonly SharedCameraRecoilSystem _recoil = default!;
+ [ValidatePrototypeId<EntityPrototype>]
+ public const string HitscanProto = "HitscanEffect";
+
public bool SpreadOverlay
{
get => _spreadOverlay;
private void OnMuzzleFlash(MuzzleFlashEvent args)
{
- CreateEffect(args.Uid, args);
+ CreateEffect(GetEntity(args.Uid), args);
}
private void OnHitscan(HitscanEvent ev)
// ALL I WANT IS AN ANIMATED EFFECT
foreach (var a in ev.Sprites)
{
- if (a.Sprite is not SpriteSpecifier.Rsi rsi ||
- Deleted(a.coordinates.EntityId))
- {
+ if (a.Sprite is not SpriteSpecifier.Rsi rsi)
+ continue;
+
+ var coords = GetCoordinates(a.coordinates);
+
+ if (Deleted(coords.EntityId))
continue;
- }
- var ent = Spawn("HitscanEffect", a.coordinates);
+ var ent = Spawn(HitscanProto, coords);
var sprite = Comp<SpriteComponent>(ent);
var xform = Transform(ent);
xform.LocalRotation = a.angle;
if (_inputSystem.CmdStates.GetState(useKey) != BoundKeyState.Down)
{
if (gun.ShotCounter != 0)
- EntityManager.RaisePredictiveEvent(new RequestStopShootEvent { Gun = gunUid });
+ EntityManager.RaisePredictiveEvent(new RequestStopShootEvent { Gun = GetNetEntity(gunUid) });
return;
}
if (mousePos.MapId == MapId.Nullspace)
{
if (gun.ShotCounter != 0)
- EntityManager.RaisePredictiveEvent(new RequestStopShootEvent { Gun = gunUid });
+ EntityManager.RaisePredictiveEvent(new RequestStopShootEvent { Gun = GetNetEntity(gunUid) });
return;
}
EntityManager.RaisePredictiveEvent(new RequestShootEvent
{
- Coordinates = coordinates,
- Gun = gunUid,
+ Coordinates = GetNetCoordinates(coordinates),
+ Gun = GetNetEntity(gunUid),
});
}
if (throwItems)
{
Recoil(user, direction, gun.CameraRecoilScalar);
- if (ent!.Value.IsClientSide())
+ if (IsClientSide(ent!.Value))
Del(ent.Value);
else
RemoveShootable(ent.Value);
Audio.PlayPredicted(gun.SoundEmpty, gunUid, user);
}
- if (ent!.Value.IsClientSide())
+ if (IsClientSide(ent!.Value))
Del(ent.Value);
break;
MuzzleFlash(gunUid, newAmmo, user);
Audio.PlayPredicted(gun.SoundGunshot, gunUid, user);
Recoil(user, direction, gun.CameraRecoilScalar);
- if (ent!.Value.IsClientSide())
+ if (IsClientSide(ent!.Value))
Del(ent.Value);
else
RemoveShootable(ent.Value);
return;
}
- UpdateArtifactIcon(state.Artifact);
+ UpdateArtifactIcon(_ent.GetEntity(state.Artifact));
if (state.ScanReport == null)
{
public EntityCoordinates GridCoords { get; set; }
public MapCoordinates MapCoords { get; set; }
public TileRef Tile { get; set; }
+
+ // Client-side uids
+ public EntityUid CMapUid { get; set; }
+ public EntityUid CGridUid { get; set; }
+ public EntityCoordinates CGridCoords { get; set; }
}
\ No newline at end of file
#nullable enable
using System.Linq;
+using Robust.Shared.GameObjects;
using Robust.Shared.Map;
+using Robust.UnitTesting;
namespace Content.IntegrationTests.Pair;
var tileDefinitionManager = Server.ResolveDependency<ITileDefinitionManager>();
var mapData = new TestMapData();
+ TestMap = mapData;
await Server.WaitPost(() =>
{
mapData.MapId = Server.MapMan.CreateMap();
mapData.MapCoords = new MapCoordinates(0, 0, mapData.MapId);
mapData.Tile = mapData.MapGrid.GetAllTiles().First();
});
-
- if (Settings.Connected)
- await RunTicksSync(10);
- TestMap = mapData;
+ if (!Settings.Connected)
+ return mapData;
+
+ await RunTicksSync(10);
+ mapData.CMapUid = ToClientUid(mapData.MapUid);
+ mapData.CGridUid = ToClientUid(mapData.GridUid);
+ mapData.CGridCoords = new EntityCoordinates(mapData.CGridUid, 0, 0);
+
return mapData;
}
-}
\ No newline at end of file
+
+ /// <summary>
+ /// Convert a client-side uid into a server-side uid
+ /// </summary>
+ public EntityUid ToServerUid(EntityUid uid) => ConvertUid(uid, Client, Server);
+
+ /// <summary>
+ /// Convert a server-side uid into a client-side uid
+ /// </summary>
+ public EntityUid ToClientUid(EntityUid uid) => ConvertUid(uid, Server, Client);
+
+ private static EntityUid ConvertUid(
+ EntityUid uid,
+ RobustIntegrationTest.IntegrationInstance source,
+ RobustIntegrationTest.IntegrationInstance destination)
+ {
+ if (!uid.IsValid())
+ return EntityUid.Invalid;
+
+ if (!source.EntMan.TryGetComponent<MetaDataComponent>(uid, out var meta))
+ {
+ Assert.Fail($"Failed to resolve MetaData while converting the EntityUid for entity {uid}");
+ return EntityUid.Invalid;
+ }
+
+ if (!destination.EntMan.TryGetEntity(meta.NetEntity, out var otherUid))
+ {
+ Assert.Fail($"Failed to resolve net ID while converting the EntityUid entity {source.EntMan.ToPrettyString(uid)}");
+ return EntityUid.Invalid;
+ }
+
+ return otherUid.Value;
+ }
+}
using Content.Shared.CombatMode;
using Robust.Server.Player;
using Robust.Shared.GameObjects;
+using Robust.Shared.Players;
+using PlayerManager = Robust.Client.Player.PlayerManager;
namespace Content.IntegrationTests.Tests.Actions;
var client = pair.Client;
var sEntMan = server.ResolveDependency<IEntityManager>();
var cEntMan = client.ResolveDependency<IEntityManager>();
- var session = server.ResolveDependency<IPlayerManager>().ServerSessions.Single();
+ var clientSession = client.ResolveDependency<Robust.Client.Player.IPlayerManager>().LocalPlayer?.Session;
+ var serverSession = server.ResolveDependency<IPlayerManager>().ServerSessions.Single();
var sActionSystem = server.System<SharedActionsSystem>();
var cActionSystem = client.System<SharedActionsSystem>();
// Dummy ticker is disabled - client should be in control of a normal mob.
- Assert.NotNull(session.AttachedEntity);
- var ent = session.AttachedEntity!.Value;
- Assert.That(sEntMan.EntityExists(ent));
- Assert.That(cEntMan.EntityExists(ent));
- Assert.That(sEntMan.HasComponent<ActionsComponent>(ent));
- Assert.That(cEntMan.HasComponent<ActionsComponent>(ent));
- Assert.That(sEntMan.HasComponent<CombatModeComponent>(ent));
- Assert.That(cEntMan.HasComponent<CombatModeComponent>(ent));
+ Assert.NotNull(serverSession.AttachedEntity);
+ var serverEnt = serverSession.AttachedEntity!.Value;
+ var clientEnt = clientSession!.AttachedEntity!.Value;
+ Assert.That(sEntMan.EntityExists(serverEnt));
+ Assert.That(cEntMan.EntityExists(clientEnt));
+ Assert.That(sEntMan.HasComponent<ActionsComponent>(serverEnt));
+ Assert.That(cEntMan.HasComponent<ActionsComponent>(clientEnt));
+ Assert.That(sEntMan.HasComponent<CombatModeComponent>(serverEnt));
+ Assert.That(cEntMan.HasComponent<CombatModeComponent>(clientEnt));
- var sComp = sEntMan.GetComponent<ActionsComponent>(ent);
- var cComp = cEntMan.GetComponent<ActionsComponent>(ent);
+ var sComp = sEntMan.GetComponent<ActionsComponent>(serverEnt);
+ var cComp = cEntMan.GetComponent<ActionsComponent>(clientEnt);
// Mob should have a combat-mode action.
// This action should have a non-null event both on the server & client.
var evType = typeof(ToggleCombatActionEvent);
- var sActions = sActionSystem.GetActions(ent).Where(
+ var sActions = sActionSystem.GetActions(serverEnt).Where(
x => x.Comp is InstantActionComponent act && act.Event?.GetType() == evType).ToArray();
- var cActions = cActionSystem.GetActions(ent).Where(
+ var cActions = cActionSystem.GetActions(clientEnt).Where(
x => x.Comp is InstantActionComponent act && act.Event?.GetType() == evType).ToArray();
Assert.That(sActions.Length, Is.EqualTo(1));
// Beaker is back in the player's hands
Assert.That(Hands.ActiveHandEntity, Is.Not.Null);
- AssertPrototype("Beaker", Hands.ActiveHandEntity);
+ AssertPrototype("Beaker", SEntMan.GetNetEntity(Hands.ActiveHandEntity));
// Re-insert the beaker
await Interact();
await ClickControl<ReagentDispenserWindow>(nameof(ReagentDispenserWindow.EjectButton));
await RunTicks(5);
Assert.That(Hands.ActiveHandEntity, Is.Not.Null);
- AssertPrototype("Beaker", Hands.ActiveHandEntity);
+ AssertPrototype("Beaker", SEntMan.GetNetEntity(Hands.ActiveHandEntity));
}
}
await using var pair = await PoolManager.GetServerClient(new PoolSettings { Connected = true });
var server = pair.Server;
var client = pair.Client;
- EntityUid entity = default;
+
var clientEntManager = client.ResolveDependency<IEntityManager>();
var serverEntManager = server.ResolveDependency<IEntityManager>();
var eyeManager = client.ResolveDependency<IEyeManager>();
var eye = client.ResolveDependency<IEyeManager>().CurrentEye;
var testMap = await pair.CreateTestMap();
+
+ EntityUid serverEnt = default;
+
await server.WaitPost(() =>
{
- var ent = serverEntManager.SpawnEntity(prototype, testMap.GridCoords);
- serverEntManager.System<SharedTransformSystem>().SetWorldRotation(ent, angle);
- entity = ent;
+ serverEnt = serverEntManager.SpawnEntity(prototype, testMap.GridCoords);
+ serverEntManager.System<SharedTransformSystem>().SetWorldRotation(serverEnt, angle);
});
// Let client sync up.
await pair.RunTicksSync(5);
var hit = false;
+ var clientEnt = clientEntManager.GetEntity(serverEntManager.GetNetEntity(serverEnt));
await client.WaitPost(() =>
{
- var sprite = spriteQuery.GetComponent(entity);
+ var sprite = spriteQuery.GetComponent(clientEnt);
sprite.Scale = new Vector2(scale, scale);
// these tests currently all assume player eye is 0
eyeManager.CurrentEye.Rotation = 0;
- var pos = clientEntManager.System<SharedTransformSystem>().GetWorldPosition(entity);
- var clickable = clientEntManager.GetComponent<ClickableComponent>(entity);
+ var pos = clientEntManager.System<SharedTransformSystem>().GetWorldPosition(clientEnt);
+ var clickable = clientEntManager.GetComponent<ClickableComponent>(clientEnt);
- hit = clickable.CheckClick(sprite, xformQuery.GetComponent(entity), xformQuery, new Vector2(clickPosX, clickPosY) + pos, eye, out _, out _, out _);
+ hit = clickable.CheckClick(sprite, xformQuery.GetComponent(clientEnt), xformQuery, new Vector2(clickPosX, clickPosY) + pos, eye, out _, out _, out _);
});
await server.WaitPost(() =>
{
- serverEntManager.DeleteEntity(entity);
+ serverEntManager.DeleteEntity(serverEnt);
});
await pair.CleanReturnAsync();
// Try to start climbing
var sys = SEntMan.System<ClimbSystem>();
- await Server.WaitPost(() => sys.TryClimb(Player, Player, Target.Value, out _));
+ await Server.WaitPost(() => sys.TryClimb(SEntMan.GetEntity(Player), SEntMan.GetEntity(Player), SEntMan.GetEntity(Target.Value), out _));
await AwaitDoAfters();
// Player should now be climbing
Assert.That(Delta(), Is.LessThan(0));
// Start climbing
- await Server.WaitPost(() => sys.TryClimb(Player, Player, Target.Value, out _));
+ await Server.WaitPost(() => sys.TryClimb(SEntMan.GetEntity(Player), SEntMan.GetEntity(Player), SEntMan.GetEntity(Target.Value), out _));
await AwaitDoAfters();
Assert.Multiple(() =>
// Initial interaction (ghost turns into real entity)
await Interact(Steel, 5);
- AssertPrototype(ComputerFrame);
+ ClientAssertPrototype(ComputerFrame, ClientTarget);
+ Target = CTestSystem.Ghosts[ClientTarget!.Value.GetHashCode()];
+ ClientTarget = null;
// Perform construction steps
await Interact(
Screw);
// Construction finished, target entity was replaced with a new one:
- AssertPrototype(ComputerId);
+ AssertPrototype(ComputerId, Target);
}
[Test]
using System.Linq;
using Content.IntegrationTests.Tests.Interaction;
+using Content.Shared.DoAfter;
using Content.Shared.Stacks;
using Robust.Shared.Containers;
{
// Spawn a full tack of rods in the user's hands.
await PlaceInHands(Rod, 10);
- await SpawnEntity((Cable, 10), PlayerCoords);
+ await SpawnEntity((Cable, 10), SEntMan.GetCoordinates(PlayerCoords));
// Attempt (and fail) to craft without glass.
await CraftItem(Spear, shouldSucceed: false);
[Test]
public async Task CancelCraft()
{
- var rods = await SpawnEntity((Rod, 10), TargetCoords);
- var wires = await SpawnEntity((Cable, 10), TargetCoords);
- var shard = await SpawnEntity(ShardGlass, TargetCoords);
+ var serverTargetCoords = SEntMan.GetCoordinates(TargetCoords);
+ var rods = await SpawnEntity((Rod, 10), serverTargetCoords);
+ var wires = await SpawnEntity((Cable, 10), serverTargetCoords);
+ var shard = await SpawnEntity(ShardGlass, serverTargetCoords);
var rodStack = SEntMan.GetComponent<StackComponent>(rods);
var wireStack = SEntMan.GetComponent<StackComponent>(wires);
});
#pragma warning disable CS4014 // Legacy construction code uses DoAfterAwait. If we await it we will be waiting forever.
- await Server.WaitPost(() => SConstruction.TryStartItemConstruction(Spear, Player));
+ await Server.WaitPost(() => SConstruction.TryStartItemConstruction(Spear, SEntMan.GetEntity(Player)));
#pragma warning restore CS4014
await RunTicks(1);
// Re-attempt the do-after
#pragma warning disable CS4014 // Legacy construction code uses DoAfterAwait. See above.
- await Server.WaitPost(() => SConstruction.TryStartItemConstruction(Spear, Player));
+ await Server.WaitPost(() => SConstruction.TryStartItemConstruction(Spear, SEntMan.GetEntity(Player)));
#pragma warning restore CS4014
await RunTicks(1);
// Construct Grille
await StartConstruction(Grille);
await Interact(Rod, 10);
- AssertPrototype(Grille);
+ ClientAssertPrototype(Grille, ClientTarget);
+ Target = CTestSystem.Ghosts[ClientTarget!.Value.GetHashCode()];
var grille = Target;
// Construct Window
await StartConstruction(Window);
await Interact(Glass, 10);
- AssertPrototype(Window);
+ ClientAssertPrototype(Window, ClientTarget);
+ Target = CTestSystem.Ghosts[ClientTarget!.Value.GetHashCode()];
// Deconstruct Window
await Interact(Screw, Wrench);
await Client.WaitPost(() =>
{
var proto = ProtoMan.Index<ConstructionPrototype>(second);
- Assert.That(CConSys.TrySpawnGhost(proto, TargetCoords, Direction.South, out _), Is.False);
+ Assert.That(CConSys.TrySpawnGhost(proto, CEntMan.GetCoordinates(TargetCoords), Direction.South, out _), Is.False);
});
}
}
{
await StartConstruction(MachineFrame);
await Interact(Steel, 5);
- AssertPrototype(Unfinished);
+ ClientAssertPrototype(Unfinished, ClientTarget);
+ Target = CTestSystem.Ghosts[ClientTarget!.Value.GetHashCode()];
await Interact(Wrench, Cable);
AssertPrototype(MachineFrame);
await Interact(ProtolatheBoard, Bin1, Bin1, Manipulator1, Manipulator1, Beaker, Beaker, Screw);
{
// Partially deconstruct a protolathe.
await SpawnTarget(Protolathe);
+ var serverTarget = SEntMan.GetEntity(Target!.Value);
// Initially has all quality-1 parts.
- foreach (var part in SConstruction.GetAllParts(Target!.Value))
+ foreach (var part in SConstruction.GetAllParts(serverTarget))
{
Assert.That(part.Rating, Is.EqualTo(1));
}
AssertPrototype(Protolathe);
// Query now returns higher quality parts.
- foreach (var part in SConstruction.GetAllParts(Target!.Value))
+ foreach (var part in SConstruction.GetAllParts(SEntMan.GetEntity(Target!.Value)))
{
Assert.That(part.Rating, Is.EqualTo(4));
}
+using System.Linq;
using Content.IntegrationTests.Tests.Interaction;
+using Content.Shared.DoAfter;
using Content.Shared.Wires;
namespace Content.IntegrationTests.Tests.Construction.Interaction;
await StartConstruction(Wall);
await Interact(Steel, 2);
Assert.That(Hands.ActiveHandEntity, Is.Null);
- AssertPrototype(Girder);
+ ClientAssertPrototype(Girder, ClientTarget);
+ Target = CTestSystem.Ghosts[ClientTarget!.Value.GetHashCode()];
await Interact(Steel, 2);
Assert.That(Hands.ActiveHandEntity, Is.Null);
AssertPrototype(WallSolid);
{
await StartConstruction(Window);
await Interact(Glass, 5);
- AssertPrototype(Window);
+ ClientAssertPrototype(Window, ClientTarget);
}
[Test]
{
await StartConstruction(RWindow);
await Interact(RGlass, 5);
- AssertPrototype(RWindow);
+ ClientAssertPrototype(RWindow, ClientTarget);
}
[Test]
var damageType = Server.ResolveDependency<IPrototypeManager>().Index<DamageTypePrototype>("Blunt");
var damage = new DamageSpecifier(damageType, FixedPoint2.New(10));
Assert.That(comp.Damage.Total, Is.EqualTo(FixedPoint2.Zero));
- await Server.WaitPost(() => sys.TryChangeDamage(Target, damage, ignoreResistances: true));
+ await Server.WaitPost(() => sys.TryChangeDamage(SEntMan.GetEntity(Target), damage, ignoreResistances: true));
await RunTicks(5);
Assert.That(comp.Damage.Total, Is.GreaterThan(FixedPoint2.Zero));
public async Task TestA()
{
await using var pair = await PoolManager.GetServerClient(new PoolSettings { Connected = true });
- var s = pair.Server;
- var c = pair.Client;
+ var server = pair.Server;
+ var client = pair.Client;
- var cEntities = c.ResolveDependency<IEntityManager>();
- var ent = s.ResolveDependency<IEntityManager>();
+ var clientEntManager = client.ResolveDependency<IEntityManager>();
+ var serverEntManager = server.ResolveDependency<IEntityManager>();
EntityUid dummy = default;
- var mapManager = s.ResolveDependency<IMapManager>();
+ var mapManager = server.ResolveDependency<IMapManager>();
var mapId = mapManager.CreateMap();
- await s.WaitPost(() =>
+ await server.WaitPost(() =>
{
var pos = new MapCoordinates(Vector2.Zero, mapId);
- var entStorage = ent.EntitySysManager.GetEntitySystem<EntityStorageSystem>();
- var container = ent.SpawnEntity("ContainerOcclusionA", pos);
- dummy = ent.SpawnEntity("ContainerOcclusionDummy", pos);
+ var entStorage = serverEntManager.EntitySysManager.GetEntitySystem<EntityStorageSystem>();
+ var container = serverEntManager.SpawnEntity("ContainerOcclusionA", pos);
+ dummy = serverEntManager.SpawnEntity("ContainerOcclusionDummy", pos);
entStorage.Insert(dummy, container);
});
await pair.RunTicksSync(5);
- await c.WaitAssertion(() =>
+ var clientEnt = clientEntManager.GetEntity(serverEntManager.GetNetEntity(dummy));
+
+ await client.WaitAssertion(() =>
{
- var sprite = cEntities.GetComponent<SpriteComponent>(dummy);
- var light = cEntities.GetComponent<PointLightComponent>(dummy);
+ var sprite = clientEntManager.GetComponent<SpriteComponent>(clientEnt);
+ var light = clientEntManager.GetComponent<PointLightComponent>(clientEnt);
Assert.Multiple(() =>
{
Assert.That(sprite.ContainerOccluded);
public async Task TestB()
{
await using var pair = await PoolManager.GetServerClient(new PoolSettings { Connected = true });
- var s = pair.Server;
- var c = pair.Client;
+ var server = pair.Server;
+ var client = pair.Client;
- var cEntities = c.ResolveDependency<IEntityManager>();
- var ent = s.ResolveDependency<IEntityManager>();
+ var clientEntManager = client.ResolveDependency<IEntityManager>();
+ var serverEntManager = server.ResolveDependency<IEntityManager>();
EntityUid dummy = default;
- var mapManager = s.ResolveDependency<IMapManager>();
+ var mapManager = server.ResolveDependency<IMapManager>();
var mapId = mapManager.CreateMap();
- await s.WaitPost(() =>
+ await server.WaitPost(() =>
{
var pos = new MapCoordinates(Vector2.Zero, mapId);
- var entStorage = ent.EntitySysManager.GetEntitySystem<EntityStorageSystem>();
- var container = ent.SpawnEntity("ContainerOcclusionB", pos);
- dummy = ent.SpawnEntity("ContainerOcclusionDummy", pos);
+ var entStorage = serverEntManager.EntitySysManager.GetEntitySystem<EntityStorageSystem>();
+ var container = serverEntManager.SpawnEntity("ContainerOcclusionB", pos);
+ dummy = serverEntManager.SpawnEntity("ContainerOcclusionDummy", pos);
entStorage.Insert(dummy, container);
});
await pair.RunTicksSync(5);
- await c.WaitAssertion(() =>
+ var clientEnt = clientEntManager.GetEntity(serverEntManager.GetNetEntity(dummy));
+
+ await client.WaitAssertion(() =>
{
- var sprite = cEntities.GetComponent<SpriteComponent>(dummy);
- var light = cEntities.GetComponent<PointLightComponent>(dummy);
+ var sprite = clientEntManager.GetComponent<SpriteComponent>(clientEnt);
+ var light = clientEntManager.GetComponent<PointLightComponent>(clientEnt);
Assert.Multiple(() =>
{
Assert.That(sprite.ContainerOccluded, Is.False);
public async Task TestAb()
{
await using var pair = await PoolManager.GetServerClient(new PoolSettings { Connected = true });
- var s = pair.Server;
- var c = pair.Client;
+ var server = pair.Server;
+ var client = pair.Client;
- var cEntities = c.ResolveDependency<IEntityManager>();
- var ent = s.ResolveDependency<IEntityManager>();
+ var clientEntManager = client.ResolveDependency<IEntityManager>();
+ var serverEntManager = server.ResolveDependency<IEntityManager>();
EntityUid dummy = default;
- var mapManager = s.ResolveDependency<IMapManager>();
+ var mapManager = server.ResolveDependency<IMapManager>();
var mapId = mapManager.CreateMap();
- await s.WaitPost(() =>
+ await server.WaitPost(() =>
{
var pos = new MapCoordinates(Vector2.Zero, mapId);
- var entStorage = ent.EntitySysManager.GetEntitySystem<EntityStorageSystem>();
- var containerA = ent.SpawnEntity("ContainerOcclusionA", pos);
- var containerB = ent.SpawnEntity("ContainerOcclusionB", pos);
- dummy = ent.SpawnEntity("ContainerOcclusionDummy", pos);
+ var entStorage = serverEntManager.EntitySysManager.GetEntitySystem<EntityStorageSystem>();
+ var containerA = serverEntManager.SpawnEntity("ContainerOcclusionA", pos);
+ var containerB = serverEntManager.SpawnEntity("ContainerOcclusionB", pos);
+ dummy = serverEntManager.SpawnEntity("ContainerOcclusionDummy", pos);
entStorage.Insert(containerB, containerA);
entStorage.Insert(dummy, containerB);
await pair.RunTicksSync(5);
- await c.WaitAssertion(() =>
+ var clientEnt = clientEntManager.GetEntity(serverEntManager.GetNetEntity(dummy));
+
+ await client.WaitAssertion(() =>
{
- var sprite = cEntities.GetComponent<SpriteComponent>(dummy);
- var light = cEntities.GetComponent<PointLightComponent>(dummy);
+ var sprite = clientEntManager.GetComponent<SpriteComponent>(clientEnt);
+ var light = clientEntManager.GetComponent<PointLightComponent>(clientEnt);
Assert.Multiple(() =>
{
Assert.That(sprite.ContainerOccluded);
using Content.IntegrationTests.Tests.Interaction;
using Content.IntegrationTests.Tests.Weldable;
using Content.Shared.Tools.Components;
+using Content.Server.Tools.Components;
+using Content.Shared.DoAfter;
namespace Content.IntegrationTests.Tests.DoAfter;
await StartConstruction(WallConstruction.Wall);
await Interact(Steel, 5, awaitDoAfters: false);
await CancelDoAfters();
- Assert.That(Target.HasValue && Target.Value.IsClientSide());
await Interact(Steel, 5);
- AssertPrototype(WallConstruction.Girder);
+ ClientAssertPrototype(WallConstruction.Girder, ClientTarget);
+ Target = CTestSystem.Ghosts[ClientTarget!.Value.GetHashCode()];
await Interact(Steel, 5, awaitDoAfters: false);
await CancelDoAfters();
AssertPrototype(WallConstruction.Girder);
await AssertTile(Floor);
// Second DoAfter cancels the first.
- await Server.WaitPost(() => InteractSys.UserInteraction(Player, TargetCoords, Target));
+ await Server.WaitPost(() => InteractSys.UserInteraction(SEntMan.GetEntity(Player), SEntMan.GetCoordinates(TargetCoords), SEntMan.GetEntity(Target)));
Assert.That(ActiveDoAfters.Count(), Is.EqualTo(0));
await AssertTile(Floor);
// Second DoAfter cancels the first.
// Not using helper, because it runs too many ticks & causes the do-after to finish.
- await Server.WaitPost(() => InteractSys.UserInteraction(Player, TargetCoords, Target));
+ await Server.WaitPost(() => InteractSys.UserInteraction(SEntMan.GetEntity(Player), SEntMan.GetCoordinates(TargetCoords), SEntMan.GetEntity(Target)));
Assert.Multiple(() =>
{
Assert.That(ActiveDoAfters.Count(), Is.EqualTo(0));
Assert.That(ActiveDoAfters.Count(), Is.EqualTo(1));
Assert.That(comp.IsWelded, Is.True);
});
- await Server.WaitPost(() => InteractSys.UserInteraction(Player, TargetCoords, Target));
+ await Server.WaitPost(() => InteractSys.UserInteraction(SEntMan.GetEntity(Player), SEntMan.GetCoordinates(TargetCoords), SEntMan.GetEntity(Target)));
Assert.Multiple(() =>
{
Assert.That(ActiveDoAfters.Count(), Is.EqualTo(0));
{
var tickTime = 1.0f / timing.TickRate;
var mob = entityManager.SpawnEntity("DoAfterDummy", MapCoordinates.Nullspace);
- var args = new DoAfterArgs(mob, tickTime / 2, ev, null) { Broadcast = true };
+ var args = new DoAfterArgs(entityManager, mob, tickTime / 2, ev, null) { Broadcast = true };
#pragma warning disable NUnit2045 // Interdependent assertions.
Assert.That(doAfterSystem.TryStartDoAfter(args));
Assert.That(ev.Cancelled, Is.False);
var tickTime = 1.0f / timing.TickRate;
var mob = entityManager.SpawnEntity("DoAfterDummy", MapCoordinates.Nullspace);
- var args = new DoAfterArgs(mob, tickTime * 2, ev, null) { Broadcast = true };
+ var args = new DoAfterArgs(entityManager, mob, tickTime * 2, ev, null) { Broadcast = true };
if (!doAfterSystem.TryStartDoAfter(args, out var id))
{
{
var mapId = mapManager.CreateMap();
var grid = mapManager.CreateGrid(mapId);
+ // TODO: Fix this better in engine.
+ grid.SetTile(Vector2i.Zero, new Tile(1));
var coord = new EntityCoordinates(grid.Owner, 0, 0);
entityMan.SpawnEntity(protoId, coord);
}
var query = entityMan.AllEntityQueryEnumerator<TComp>();
while (query.MoveNext(out var uid, out var meta))
yield return (uid, meta);
- };
+ }
var entityMetas = Query<MetaDataComponent>(entityMan).ToList();
foreach (var (uid, meta) in entityMetas)
Assert.That(cuffed.CuffedHandCount, Is.GreaterThan(0), "Handcuffing a player did not result in their hands being cuffed");
// Test to ensure a player with 4 hands will still only have 2 hands cuffed
- AddHand(human, host);
- AddHand(human, host);
+ AddHand(entityManager.GetNetEntity(human), host);
+ AddHand(entityManager.GetNetEntity(human), host);
Assert.Multiple(() =>
{
await pair.CleanReturnAsync();
}
- private static void AddHand(EntityUid to, IServerConsoleHost host)
+ private static void AddHand(NetEntity to, IServerConsoleHost host)
{
host.ExecuteCommand(null, $"addhand {to}");
}
EntityUid target = default;
EntityUid item = default;
EntityUid containerEntity = default;
- IContainer container = null;
+ BaseContainer container = null;
await server.WaitAssertion(() =>
{
using Content.Server.Power.Components;
using Content.Server.Tools.Components;
using Content.Shared.Atmos;
+using Content.Shared.Construction;
using Content.Shared.Construction.Prototypes;
+using Content.Shared.DoAfter;
using Content.Shared.Gravity;
using Content.Shared.Item;
using Robust.Client.GameObjects;
await Client.WaitPost(() =>
{
- Assert.That(CConSys.TrySpawnGhost(proto, TargetCoords, Direction.South, out Target),
+ Assert.That(CConSys.TrySpawnGhost(proto, CEntMan.GetCoordinates(TargetCoords), Direction.South, out var clientTarget),
Is.EqualTo(shouldSucceed));
if (!shouldSucceed)
return;
- var comp = CEntMan.GetComponent<ConstructionGhostComponent>(Target!.Value);
- ConstructionGhostId = comp.GhostId;
+
+ var comp = CEntMan.GetComponent<ConstructionGhostComponent>(clientTarget!.Value);
+ ClientTarget = clientTarget;
+ ConstructionGhostId = comp.Owner.Id;
});
await RunTicks(1);
// Please someone purge async construction code
Task<bool> task = default!;
- await Server.WaitPost(() => task = SConstruction.TryStartItemConstruction(prototype, Player));
+ await Server.WaitPost(() => task = SConstruction.TryStartItemConstruction(prototype, SEntMan.GetEntity(Player)));
Task? tickTask = null;
while (!task.IsCompleted)
[MemberNotNull(nameof(Target))]
protected async Task SpawnTarget(string prototype)
{
- Target = EntityUid.Invalid;
+ Target = NetEntity.Invalid;
await Server.WaitPost(() =>
{
- Target = SEntMan.SpawnEntity(prototype, TargetCoords);
+ Target = SEntMan.GetNetEntity(SEntMan.SpawnEntity(prototype, SEntMan.GetCoordinates(TargetCoords)));
});
await RunTicks(5);
protected async Task StartDeconstruction(string prototype)
{
await SpawnTarget(prototype);
- Assert.That(SEntMan.TryGetComponent(Target, out ConstructionComponent? comp));
- await Server.WaitPost(() => SConstruction.SetPathfindingTarget(Target!.Value, comp!.DeconstructionNode, comp));
+ var serverTarget = SEntMan.GetEntity(Target);
+ Assert.That(SEntMan.TryGetComponent(serverTarget, out ConstructionComponent? comp));
+ await Server.WaitPost(() => SConstruction.SetPathfindingTarget(serverTarget!.Value, comp!.DeconstructionNode, comp));
await RunTicks(5);
}
{
await Server.WaitPost(() =>
{
- Assert.That(HandSys.TryDrop(Player, null, false, true, Hands));
+ Assert.That(HandSys.TryDrop(SEntMan.GetEntity(Player), null, false, true, Hands));
SEntMan.DeleteEntity(held);
SLogger.Debug($"Deleting held entity");
});
}
// spawn and pick up the new item
- var item = await SpawnEntity(entity, PlayerCoords);
+ var item = await SpawnEntity(entity, SEntMan.GetCoordinates(PlayerCoords));
WelderComponent? welder = null;
await Server.WaitPost(() =>
{
- Assert.That(HandSys.TryPickup(Player, item, Hands.ActiveHand, false, false, false, Hands));
+ var playerEnt = SEntMan.GetEntity(Player);
+
+ Assert.That(HandSys.TryPickup(playerEnt, item, Hands.ActiveHand, false, false, false, Hands));
// turn on welders
if (enableWelder && SEntMan.TryGetComponent(item, out welder) && !welder.Lit)
- Assert.That(ToolSys.TryTurnWelderOn(item, Player, welder));
+ Assert.That(ToolSys.TryTurnWelderOn(item, playerEnt, welder));
});
await RunTicks(1);
/// <summary>
/// Pick up an entity. Defaults to just deleting the previously held entity.
/// </summary>
- protected async Task Pickup(EntityUid? uid = null, bool deleteHeld = true)
+ protected async Task Pickup(NetEntity? entity = null, bool deleteHeld = true)
{
- uid ??= Target;
+ entity ??= Target;
if (Hands.ActiveHand == null)
{
if (deleteHeld)
await DeleteHeldEntity();
+ var uid = SEntMan.GetEntity(entity);
+
if (!SEntMan.TryGetComponent(uid, out ItemComponent? item))
{
- Assert.Fail($"Entity {uid} is not an item");
+ Assert.Fail($"Entity {entity} is not an item");
return;
}
await Server.WaitPost(() =>
{
- Assert.That(HandSys.TryPickup(Player, uid!.Value, Hands.ActiveHand, false, false, false, Hands, item));
+ Assert.That(HandSys.TryPickup(SEntMan.GetEntity(Player), uid.Value, Hands.ActiveHand, false, false, false, Hands, item));
});
await RunTicks(1);
await Server.WaitPost(() =>
{
- Assert.That(HandSys.TryDrop(Player, handsComp: Hands));
+ Assert.That(HandSys.TryDrop(SEntMan.GetEntity(Player), handsComp: Hands));
});
await RunTicks(1);
await Server.WaitPost(() =>
{
- InteractSys.UserInteraction(Player, SEntMan.GetComponent<TransformComponent>(target).Coordinates, target);
+ InteractSys.UserInteraction(SEntMan.GetEntity(Player), SEntMan.GetComponent<TransformComponent>(target).Coordinates, target);
});
}
// (e.g., servers attempt to assemble construction examine hints).
if (Target != null)
{
- await Client.WaitPost(() => ExamineSys.DoExamine(Target.Value));
+ await Client.WaitPost(() => ExamineSys.DoExamine(CEntMan.GetEntity(Target.Value)));
}
await PlaceInHands(entity);
/// </summary>
protected async Task Interact(bool shouldSucceed = true, bool awaitDoAfters = true)
{
- if (Target == null || !Target.Value.IsClientSide())
+ var clientTarget = ClientTarget;
+
+ if ((clientTarget?.IsValid() != true || CEntMan.Deleted(clientTarget)) && (Target == null || Target.Value.IsValid()))
{
- await Server.WaitPost(() => InteractSys.UserInteraction(Player, TargetCoords, Target));
+ await Server.WaitPost(() => InteractSys.UserInteraction(SEntMan.GetEntity(Player), SEntMan.GetCoordinates(TargetCoords), SEntMan.GetEntity(Target)));
await RunTicks(1);
}
else
{
// The entity is client-side, so attempt to start construction
- var ghost = CEntMan.GetComponent<ConstructionGhostComponent>(Target.Value);
- await Client.WaitPost(() => CConSys.TryStartConstruction(ghost.GhostId));
+ var clientEnt = ClientTarget ?? CEntMan.GetEntity(Target);
+
+ await Client.WaitPost(() => CConSys.TryStartConstruction(clientEnt!.Value));
await RunTicks(5);
}
{
foreach (var doAfter in doAfters)
{
- DoAfterSys.Cancel(Player, doAfter.Index, DoAfters);
+ DoAfterSys.Cancel(SEntMan.GetEntity(Player), doAfter.Index, DoAfters);
}
});
/// </summary>
protected async Task CheckTargetChange(bool shouldSucceed)
{
- EntityUid newTarget = default;
if (Target == null)
return;
- var target = Target.Value;
+ var target = Target.Value;
await RunTicks(5);
- if (target.IsClientSide())
+ if (ClientTarget != null && CEntMan.IsClientSide(ClientTarget.Value))
{
- Assert.That(CEntMan.Deleted(target), Is.EqualTo(shouldSucceed),
+ Assert.That(CEntMan.Deleted(ClientTarget.Value), Is.EqualTo(shouldSucceed),
$"Construction ghost was {(shouldSucceed ? "not deleted" : "deleted")}.");
if (shouldSucceed)
{
- Assert.That(CTestSystem.Ghosts.TryGetValue(ConstructionGhostId, out newTarget),
+ Assert.That(CTestSystem.Ghosts.TryGetValue(ConstructionGhostId, out var newWeh),
$"Failed to get construction entity from ghost Id");
- await Client.WaitPost(() => CLogger.Debug($"Construction ghost {ConstructionGhostId} became entity {newTarget}"));
- Target = newTarget;
+ await Client.WaitPost(() => CLogger.Debug($"Construction ghost {ConstructionGhostId} became entity {newWeh}"));
+ Target = newWeh;
}
}
- if (STestSystem.EntChanges.TryGetValue(Target.Value, out newTarget))
+ if (STestSystem.EntChanges.TryGetValue(Target.Value, out var newServerWeh))
{
await Server.WaitPost(
- () => SLogger.Debug($"Construction entity {Target.Value} changed to {newTarget}"));
+ () => SLogger.Debug($"Construction entity {Target.Value} changed to {newServerWeh}"));
- Target = newTarget;
+ Target = newServerWeh;
}
if (Target != target)
#region Asserts
- protected void AssertPrototype(string? prototype, EntityUid? target = null)
+ protected void ClientAssertPrototype(string? prototype, NetEntity? target = null)
{
target ??= Target;
if (target == null)
return;
}
- var meta = SEntMan.GetComponent<MetaDataComponent>(target.Value);
+ var meta = SEntMan.GetComponent<MetaDataComponent>(SEntMan.GetEntity(target.Value));
Assert.That(meta.EntityPrototype?.ID, Is.EqualTo(prototype));
}
- protected void AssertAnchored(bool anchored = true, EntityUid? target = null)
+ protected void ClientAssertPrototype(string? prototype, EntityUid? target)
+ {
+ var netEnt = CTestSystem.Ghosts[target.GetHashCode()];
+ AssertPrototype(prototype, netEnt);
+ }
+
+ protected void AssertPrototype(string? prototype, NetEntity? target = null)
{
target ??= Target;
if (target == null)
return;
}
- var sXform = SEntMan.GetComponent<TransformComponent>(target.Value);
- var cXform = CEntMan.GetComponent<TransformComponent>(target.Value);
+ var meta = SEntMan.GetComponent<MetaDataComponent>(SEntMan.GetEntity(target.Value));
+ Assert.That(meta.EntityPrototype?.ID, Is.EqualTo(prototype));
+ }
+
+ protected void AssertAnchored(bool anchored = true, NetEntity? target = null)
+ {
+ target ??= Target;
+ if (target == null)
+ {
+ Assert.Fail("No target specified");
+ return;
+ }
+
+ var sXform = SEntMan.GetComponent<TransformComponent>(SEntMan.GetEntity(target.Value));
+ var cXform = CEntMan.GetComponent<TransformComponent>(CEntMan.GetEntity(target.Value));
Assert.Multiple(() =>
{
});
}
- protected void AssertDeleted(bool deleted = true, EntityUid? target = null)
+ protected void AssertDeleted(bool deleted = true, NetEntity? target = null)
{
target ??= Target;
if (target == null)
Assert.Multiple(() =>
{
- Assert.That(SEntMan.Deleted(target), Is.EqualTo(deleted));
- Assert.That(CEntMan.Deleted(target), Is.EqualTo(deleted));
+ Assert.That(SEntMan.Deleted(SEntMan.GetEntity(target)), Is.EqualTo(deleted));
+ Assert.That(CEntMan.Deleted(CEntMan.GetEntity(target)), Is.EqualTo(deleted));
});
}
/// <summary>
/// Assert whether or not the target has the given component.
/// </summary>
- protected void AssertComp<T>(bool hasComp = true, EntityUid? target = null)
+ protected void AssertComp<T>(bool hasComp = true, NetEntity? target = null)
{
target ??= Target;
if (target == null)
return;
}
- Assert.That(SEntMan.HasComponent<T>(target), Is.EqualTo(hasComp));
+ Assert.That(SEntMan.HasComponent<T>(SEntMan.GetEntity(target)), Is.EqualTo(hasComp));
}
/// <summary>
/// Check that the tile at the target position matches some prototype.
/// </summary>
- protected async Task AssertTile(string? proto, EntityCoordinates? coords = null)
+ protected async Task AssertTile(string? proto, NetCoordinates? coords = null)
{
var targetTile = proto == null
? Tile.Empty
: new Tile(TileMan[proto].TileId);
var tile = Tile.Empty;
- var pos = (coords ?? TargetCoords).ToMap(SEntMan, Transform);
+ var serverCoords = SEntMan.GetCoordinates(coords ?? TargetCoords);
+ var pos = serverCoords.ToMap(SEntMan, Transform);
await Server.WaitPost(() =>
{
if (MapMan.TryFindGridAt(pos, out _, out var grid))
- tile = grid.GetTileRef(coords ?? TargetCoords).Tile;
+ tile = grid.GetTileRef(serverCoords).Tile;
});
Assert.That(tile.TypeId, Is.EqualTo(targetTile.TypeId));
foreach (var ent in entities)
{
var transform = xformQuery.GetComponent(ent);
+ var netEnt = SEntMan.GetNetEntity(ent);
if (ent == transform.MapUid
|| ent == transform.GridUid
- || ent == Player
- || ent == Target)
+ || netEnt == Player
+ || netEnt == Target)
{
toRemove.Add(ent);
}
/// <summary>
/// Convenience method to get components on the target. Returns SERVER-SIDE components.
/// </summary>
- protected T Comp<T>(EntityUid? target = null) where T : IComponent
+ protected T Comp<T>(NetEntity? target = null) where T : IComponent
{
target ??= Target;
if (target == null)
Assert.Fail("No target specified");
- return SEntMan.GetComponent<T>(target!.Value);
+ return SEntMan.GetComponent<T>(SEntMan.GetEntity(target!.Value));
}
/// <summary>
/// Set the tile at the target position to some prototype.
/// </summary>
- protected async Task SetTile(string? proto, EntityCoordinates? coords = null, MapGridComponent? grid = null)
+ protected async Task SetTile(string? proto, NetCoordinates? coords = null, MapGridComponent? grid = null)
{
var tile = proto == null
? Tile.Empty
: new Tile(TileMan[proto].TileId);
- var pos = (coords ?? TargetCoords).ToMap(SEntMan, Transform);
+ var pos = SEntMan.GetCoordinates(coords ?? TargetCoords).ToMap(SEntMan, Transform);
await Server.WaitPost(() =>
{
if (grid != null || MapMan.TryFindGridAt(pos, out var gridUid, out grid))
{
- grid.SetTile(coords ?? TargetCoords, tile);
+ grid.SetTile(SEntMan.GetCoordinates(coords ?? TargetCoords), tile);
return;
}
gridUid = grid.Owner;
var gridXform = SEntMan.GetComponent<TransformComponent>(gridUid);
Transform.SetWorldPosition(gridXform, pos.Position);
- grid.SetTile(coords ?? TargetCoords, tile);
+ grid.SetTile(SEntMan.GetCoordinates(coords ?? TargetCoords), tile);
if (!MapMan.TryFindGridAt(pos, out _, out grid))
Assert.Fail("Failed to create grid?");
await RunTicks(15);
}
- protected bool TryGetBui(Enum key, [NotNullWhen(true)] out BoundUserInterface? bui, EntityUid? target = null, bool shouldSucceed = true)
+ protected bool TryGetBui(Enum key, [NotNullWhen(true)] out BoundUserInterface? bui, NetEntity? target = null, bool shouldSucceed = true)
{
bui = null;
target ??= Target;
return false;
}
- if (!CEntMan.TryGetComponent<ClientUserInterfaceComponent>(target, out var ui))
+ var clientTarget = CEntMan.GetEntity(target);
+
+ if (!CEntMan.TryGetComponent<ClientUserInterfaceComponent>(clientTarget, out var ui))
{
if (shouldSucceed)
- Assert.Fail($"Entity {SEntMan.ToPrettyString(target.Value)} does not have a bui component");
+ Assert.Fail($"Entity {SEntMan.ToPrettyString(SEntMan.GetEntity(target.Value))} does not have a bui component");
return false;
}
if (!ui.OpenInterfaces.TryGetValue(key, out bui))
{
if (shouldSucceed)
- Assert.Fail($"Entity {SEntMan.ToPrettyString(target.Value)} does not have an open bui with key {key.GetType()}.{key}.");
+ Assert.Fail($"Entity {SEntMan.ToPrettyString(SEntMan.GetEntity(target.Value))} does not have an open bui with key {key.GetType()}.{key}.");
return false;
}
#region Power
- protected void ToggleNeedPower(EntityUid? target = null)
+ protected void ToggleNeedPower(NetEntity? target = null)
{
var comp = Comp<ApcPowerReceiverComponent>(target);
comp.NeedsPower = !comp.NeedsPower;
protected async Task PressKey(
BoundKeyFunction key,
int ticks = 1,
- EntityCoordinates? coordinates = null,
- EntityUid cursorEntity = default)
+ NetCoordinates? coordinates = null,
+ NetEntity cursorEntity = default)
{
await SetKey(key, BoundKeyState.Down, coordinates, cursorEntity);
await RunTicks(ticks);
protected async Task SetKey(
BoundKeyFunction key,
BoundKeyState state,
- EntityCoordinates? coordinates = null,
- EntityUid cursorEntity = default)
+ NetCoordinates? coordinates = null,
+ NetEntity cursorEntity = default)
{
var coords = coordinates ?? TargetCoords;
ScreenCoordinates screen = default;
var funcId = InputManager.NetworkBindMap.KeyFunctionID(key);
- var message = new FullInputCmdMessage(CTiming.CurTick, CTiming.TickFraction, funcId, state,
- coords, screen, cursorEntity);
+ var message = new ClientFullInputCmdMessage(CTiming.CurTick, CTiming.TickFraction, funcId)
+ {
+ State = state,
+ Coordinates = CEntMan.GetCoordinates(coords),
+ ScreenCoordinates = screen,
+ Uid = CEntMan.GetEntity(cursorEntity),
+ };
await Client.WaitPost(() => InputSystem.HandleInputCommand(ClientSession, key, message));
}
/// Target coordinates. Note that this does not necessarily correspond to the position of the <see cref="Target"/>
/// entity.
/// </summary>
- protected EntityCoordinates TargetCoords;
+ protected NetCoordinates TargetCoords;
/// <summary>
/// Initial player coordinates. Note that this does not necessarily correspond to the position of the
/// <see cref="Player"/> entity.
/// </summary>
- protected EntityCoordinates PlayerCoords;
+ protected NetCoordinates PlayerCoords;
/// <summary>
/// The player entity that performs all these interactions. Defaults to an admin-observer with 1 hand.
/// </summary>
- protected EntityUid Player;
+ protected NetEntity Player;
protected ICommonSession ClientSession = default!;
protected IPlayerSession ServerSession = default!;
+ public EntityUid? ClientTarget;
+
/// <summary>
/// The current target entity. This is the default entity for various helper functions.
/// </summary>
/// interactions often swap out entities, and there are helper methods that attempt to automatically upddate
/// the target entity. See <see cref="CheckTargetChange"/>
/// </remarks>
- protected EntityUid? Target;
+ protected NetEntity? Target;
/// <summary>
/// When attempting to start construction, this is the client-side ID of the construction ghost.
// Setup map.
await Pair.CreateTestMap();
- PlayerCoords = MapData.GridCoords.Offset(new Vector2(0.5f, 0.5f)).WithEntityId(MapData.MapUid, Transform, SEntMan);
- TargetCoords = MapData.GridCoords.Offset(new Vector2(1.5f, 0.5f)).WithEntityId(MapData.MapUid, Transform, SEntMan);
+ PlayerCoords = SEntMan.GetNetCoordinates(MapData.GridCoords.Offset(new Vector2(0.5f, 0.5f)).WithEntityId(MapData.MapUid, Transform, SEntMan));
+ TargetCoords = SEntMan.GetNetCoordinates(MapData.GridCoords.Offset(new Vector2(1.5f, 0.5f)).WithEntityId(MapData.MapUid, Transform, SEntMan));
await SetTile(Plating, grid: MapData.MapGrid);
// Get player data
SEntMan.System<SharedMindSystem>().WipeMind(ServerSession.ContentData()?.Mind);
old = cPlayerMan.LocalPlayer.ControlledEntity;
- Player = SEntMan.SpawnEntity(PlayerPrototype, PlayerCoords);
- Actor.Attach(Player, ServerSession);
- Hands = SEntMan.GetComponent<HandsComponent>(Player);
- DoAfters = SEntMan.GetComponent<DoAfterComponent>(Player);
+ Player = SEntMan.GetNetEntity(SEntMan.SpawnEntity(PlayerPrototype, SEntMan.GetCoordinates(PlayerCoords)));
+ var serverPlayerEnt = SEntMan.GetEntity(Player);
+ Actor.Attach(serverPlayerEnt, ServerSession);
+ Hands = SEntMan.GetComponent<HandsComponent>(serverPlayerEnt);
+ DoAfters = SEntMan.GetComponent<DoAfterComponent>(serverPlayerEnt);
});
// Check player got attached.
await RunTicks(5);
- Assert.That(cPlayerMan.LocalPlayer.ControlledEntity, Is.EqualTo(Player));
+ Assert.That(CEntMan.GetNetEntity(cPlayerMan.LocalPlayer.ControlledEntity), Is.EqualTo(Player));
// Delete old player entity.
await Server.WaitPost(() =>
await Server.WaitPost(() =>
{
var bodySystem = SEntMan.System<BodySystem>();
- var hands = bodySystem.GetBodyChildrenOfType(Player, BodyPartType.Hand).ToArray();
+ var hands = bodySystem.GetBodyChildrenOfType(SEntMan.GetEntity(Player), BodyPartType.Hand).ToArray();
for (var i = 1; i < hands.Length; i++)
{
await Pair.ReallyBeIdle(5);
Assert.Multiple(() =>
{
- Assert.That(cPlayerMan.LocalPlayer.ControlledEntity, Is.EqualTo(Player));
- Assert.That(sPlayerMan.GetSessionByUserId(ClientSession.UserId).AttachedEntity, Is.EqualTo(Player));
+ Assert.That(CEntMan.GetNetEntity(cPlayerMan.LocalPlayer.ControlledEntity), Is.EqualTo(Player));
+ Assert.That(sPlayerMan.GetSessionByUserId(ClientSession.UserId).AttachedEntity, Is.EqualTo(SEntMan.GetEntity(Player)));
});
}
/// </summary>
public sealed class InteractionTestSystem : EntitySystem
{
- public Dictionary<int, EntityUid> Ghosts = new();
- public Dictionary<EntityUid, EntityUid> EntChanges = new();
+ public Dictionary<int, NetEntity> Ghosts = new();
+ public Dictionary<NetEntity, NetEntity> EntChanges = new();
public override void Initialize()
{
private void OnEntChange(ConstructionChangeEntityEvent ev)
{
- EntChanges[ev.Old] = ev.New;
+ Assert.That(!IsClientSide(ev.Old) && !IsClientSide(ev.New));
+ EntChanges[GetNetEntity(ev.Old)] = GetNetEntity(ev.New);
}
private void OnAck(AckStructureConstructionMessage ev)
public override async Task Setup()
{
await base.Setup();
+ var pCoords = SEntMan.GetCoordinates(PlayerCoords);
+
for (var i = -Tiles; i <= Tiles; i++)
{
- await SetTile(Plating, PlayerCoords.Offset(new Vector2(i, 0)), MapData.MapGrid);
+ await SetTile(Plating, SEntMan.GetNetCoordinates(pCoords.Offset(new Vector2(i, 0))), MapData.MapGrid);
}
AssertGridCount(1);
if (AddWalls)
{
- await SpawnEntity("WallSolid", PlayerCoords.Offset(new Vector2(-Tiles, 0)));
- await SpawnEntity("WallSolid", PlayerCoords.Offset(new Vector2(Tiles, 0)));
+ await SpawnEntity("WallSolid", pCoords.Offset(new Vector2(-Tiles, 0)));
+ await SpawnEntity("WallSolid", pCoords.Offset(new Vector2(Tiles, 0)));
}
await AddGravity();
/// <summary>
/// Get the relative horizontal between two entities. Defaults to using the target & player entity.
/// </summary>
- protected float Delta(EntityUid? target = null, EntityUid? other = null)
+ protected float Delta(NetEntity? target = null, NetEntity? other = null)
{
target ??= Target;
if (target == null)
return 0;
}
- var delta = Transform.GetWorldPosition(target.Value) - Transform.GetWorldPosition(other ?? Player);
+ var delta = Transform.GetWorldPosition(SEntMan.GetEntity(target.Value)) - Transform.GetWorldPosition(SEntMan.GetEntity(other ?? Player));
return delta.X;
}
}
await client.WaitPost(() =>
{
- clientComponent = cEntityManager.GetComponent<PredictionTestComponent>(serverEnt);
+ clientComponent = cEntityManager.GetComponent<PredictionTestComponent>(cEntityManager.GetEntity(sEntityManager.GetNetEntity(serverEnt)));
});
var baseTick = sGameTiming.CurTick.Value;
Assert.That(clientComponent.Foo, Is.False);
await client.WaitPost(() =>
{
- cEntityManager.RaisePredictiveEvent(new SetFooMessage(serverEnt, true));
+ cEntityManager.RaisePredictiveEvent(new SetFooMessage(sEntityManager.GetNetEntity(serverEnt), true));
});
Assert.That(clientComponent.Foo, Is.True);
// Send event to server to change flag again, this time to disable it..
await client.WaitPost(() =>
{
- cEntityManager.RaisePredictiveEvent(new SetFooMessage(serverEnt, false));
+ cEntityManager.RaisePredictiveEvent(new SetFooMessage(sEntityManager.GetNetEntity(serverEnt), false));
Assert.That(clientComponent.Foo, Is.False);
});
// Send first event to disable the flag (reminder: it never got accepted by the server).
await client.WaitPost(() =>
{
- cEntityManager.RaisePredictiveEvent(new SetFooMessage(serverEnt, false));
+ cEntityManager.RaisePredictiveEvent(new SetFooMessage(sEntityManager.GetNetEntity(serverEnt), false));
Assert.That(clientComponent.Foo, Is.False);
});
// Send another event, to re-enable it.
await client.WaitPost(() =>
{
- cEntityManager.RaisePredictiveEvent(new SetFooMessage(serverEnt, true));
+ cEntityManager.RaisePredictiveEvent(new SetFooMessage(sEntityManager.GetNetEntity(serverEnt), true));
Assert.That(clientComponent.Foo, Is.True);
});
private void HandleMessage(SetFooMessage message, EntitySessionEventArgs args)
{
- var component = EntityManager.GetComponent<PredictionTestComponent>(message.Uid);
+ var uid = GetEntity(message.Uid);
+
+ var component = EntityManager.GetComponent<PredictionTestComponent>(uid);
var old = component.Foo;
if (Allow)
{
component.Foo = message.NewFoo;
- Dirty(message.Uid, component);
+ Dirty(uid, component);
}
EventTriggerList.Add((_gameTiming.CurTick, _gameTiming.IsFirstTimePredicted, old, component.Foo, message.NewFoo));
public sealed class SetFooMessage : EntityEventArgs
{
- public SetFooMessage(EntityUid uid, bool newFoo)
+ public SetFooMessage(NetEntity uid, bool newFoo)
{
Uid = uid;
NewFoo = newFoo;
}
- public EntityUid Uid { get; }
+ public NetEntity Uid { get; }
public bool NewFoo { get; }
}
}
{
await PlaceInHands(Steel, 5);
await CraftItem("ModularGrenadeRecipe");
- Target = await FindEntity("ModularGrenade");
+ Target = SEntMan.GetNetEntity(await FindEntity("ModularGrenade"));
await Drop();
await Interact(Cable);
// Player is to the left of the banana peel and has not slipped.
#pragma warning disable NUnit2045
Assert.That(Delta(), Is.GreaterThan(0.5f));
- Assert.That(sys.Slipped, Does.Not.Contain(Player));
+ Assert.That(sys.Slipped, Does.Not.Contain(SEntMan.GetEntity(Player)));
#pragma warning restore NUnit2045
// Walking over the banana slowly does not trigger a slip.
await Move(DirectionFlag.East, 1f);
#pragma warning disable NUnit2045
Assert.That(Delta(), Is.LessThan(0.5f));
- Assert.That(sys.Slipped, Does.Not.Contain(Player));
+ Assert.That(sys.Slipped, Does.Not.Contain(SEntMan.GetEntity(Player)));
#pragma warning restore NUnit2045
AssertComp<KnockedDownComponent>(false, Player);
// Moving at normal speeds does trigger a slip.
await SetKey(EngineKeyFunctions.Walk, BoundKeyState.Up);
await Move(DirectionFlag.West, 1f);
- Assert.That(sys.Slipped, Does.Contain(Player));
+ Assert.That(sys.Slipped, Does.Contain(SEntMan.GetEntity(Player)));
AssertComp<KnockedDownComponent>(true, Player);
}
}
// Place Lattice
var oldPos = TargetCoords;
- TargetCoords = new EntityCoordinates(MapData.MapUid, 1, 0);
+ TargetCoords = SEntMan.GetNetCoordinates(new EntityCoordinates(MapData.MapUid, 1, 0));
await Interact(Rod);
TargetCoords = oldPos;
await AssertTile(Lattice);
// Space -> Lattice
var oldPos = TargetCoords;
- TargetCoords = new EntityCoordinates(MapData.MapUid, 1, 0);
+ TargetCoords = SEntMan.GetNetCoordinates(new EntityCoordinates(MapData.MapUid, 1, 0));
await Interact(Rod);
TargetCoords = oldPos;
await AssertTile(Lattice);
if (!_interactionSystem.InRangeUnobstructed(args.User, (EntityUid) args.Target))
return;
- var doAfterEventArgs = new DoAfterArgs(args.User, component.DoAfterTime, new AccessOverriderDoAfterEvent(), uid, target: args.Target, used: uid)
+ var doAfterEventArgs = new DoAfterArgs(EntityManager, args.User, component.DoAfterTime, new AccessOverriderDoAfterEvent(), uid, target: args.Target, used: uid)
{
BreakOnTargetMove = true,
BreakOnUserMove = true,
return;
var state = new AgentIDCardBoundUserInterfaceState(idCard.FullName ?? "", idCard.JobTitle ?? "", component.Icons);
- UserInterfaceSystem.SetUiState(ui, state, args.Session);
+ _uiSystem.SetUiState(ui, state, args.Session);
}
private void OnJobChanged(EntityUid uid, AgentIDCardComponent comp, AgentIDCardJobChangedMessage args)
[AdminCommand(AdminFlags.Admin)]
public sealed class AddBodyPartCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+
public string Command => "addbodypart";
public string Description => "Adds a given entity to a containing body.";
public string Help => "Usage: addbodypart <entity uid> <body uid> <part slot>";
return;
}
- if (!EntityUid.TryParse(args[0], out var childId))
+ if (!NetEntity.TryParse(args[0], out var childNetId))
{
shell.WriteError(Loc.GetString("shell-entity-uid-must-be-number"));
return;
}
- if (!EntityUid.TryParse(args[1], out var parentId))
+ if (!NetEntity.TryParse(args[1], out var parentNetId))
{
shell.WriteError(Loc.GetString("shell-entity-uid-must-be-number"));
return;
}
- var entityManager = IoCManager.Resolve<IEntityManager>();
- var bodySystem = entityManager.System<BodySystem>();
+ var childId = _entManager.GetEntity(childNetId);
+ var parentId = _entManager.GetEntity(parentNetId);
+ var bodySystem = _entManager.System<BodySystem>();
if (bodySystem.TryCreatePartSlotAndAttach(parentId, args[2], childId))
{
[AdminCommand(AdminFlags.Admin)]
public sealed class AddEntityStorageCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+
public string Command => "addstorage";
public string Description => "Adds a given entity to a containing storage.";
public string Help => "Usage: addstorage <entity uid> <storage uid>";
return;
}
- if (!EntityUid.TryParse(args[0], out var entityUid))
+ if (!NetEntity.TryParse(args[0], out var entityUidNet) || !_entManager.TryGetEntity(entityUidNet, out var entityUid))
{
shell.WriteError(Loc.GetString("shell-entity-uid-must-be-number"));
return;
}
- if (!EntityUid.TryParse(args[1], out var storageUid))
+ if (!NetEntity.TryParse(args[1], out var storageUidNet) || !_entManager.TryGetEntity(storageUidNet, out var storageUid))
{
shell.WriteError(Loc.GetString("shell-entity-uid-must-be-number"));
return;
}
- var entityManager = IoCManager.Resolve<IEntityManager>();
-
- if (entityManager.HasComponent<EntityStorageComponent>(storageUid) &&
- entityManager.EntitySysManager.TryGetEntitySystem<EntityStorageSystem>(out var storageSys))
+ if (_entManager.HasComponent<EntityStorageComponent>(storageUid) &&
+ _entManager.EntitySysManager.TryGetEntitySystem<EntityStorageSystem>(out var storageSys))
{
- storageSys.Insert(entityUid, storageUid);
+ storageSys.Insert(entityUid.Value, storageUid.Value);
}
else
{
[AdminCommand(AdminFlags.Admin)]
public sealed class AddMechanismCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+
public string Command => "addmechanism";
public string Description => "Adds a given entity to a containing body.";
public string Help => "Usage: addmechanism <entity uid> <bodypart uid>";
return;
}
- if (!EntityUid.TryParse(args[0], out var organId))
+ if (!NetEntity.TryParse(args[0], out var organIdNet) || !_entManager.TryGetEntity(organIdNet, out var organId))
{
shell.WriteError(Loc.GetString("shell-entity-uid-must-be-number"));
return;
}
- if (!EntityUid.TryParse(args[1], out var partId))
+ if (!NetEntity.TryParse(args[1], out var partIdNet) || !_entManager.TryGetEntity(partIdNet, out var partId))
{
shell.WriteError(Loc.GetString("shell-entity-uid-must-be-number"));
return;
}
- var entityManager = IoCManager.Resolve<IEntityManager>();
- var bodySystem = entityManager.System<BodySystem>();
+ var bodySystem = _entManager.System<BodySystem>();
if (bodySystem.AddOrganToFirstValidSlot(organId, partId))
{
[AdminCommand(AdminFlags.Fun)]
public sealed class AddPolymorphActionCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entityManager = default!;
+
public string Command => "addpolymorphaction";
public string Description => Loc.GetString("add-polymorph-action-command-description");
return;
}
- if (!EntityUid.TryParse(args[0], out var entityUid))
+ if (!NetEntity.TryParse(args[0], out var entityUidNet) || !_entityManager.TryGetEntity(entityUidNet, out var entityUid))
{
shell.WriteError(Loc.GetString("shell-entity-uid-must-be-number"));
return;
}
- var entityManager = IoCManager.Resolve<IEntityManager>();
- var polySystem = entityManager.EntitySysManager.GetEntitySystem<PolymorphSystem>();
+ var polySystem = _entityManager.EntitySysManager.GetEntitySystem<PolymorphSystem>();
- entityManager.EnsureComponent<PolymorphableComponent>(entityUid);
- polySystem.CreatePolymorphAction(args[1], entityUid);
+ _entityManager.EnsureComponent<PolymorphableComponent>(entityUid.Value);
+ polySystem.CreatePolymorphAction(args[1], entityUid.Value);
}
}
[AdminCommand(AdminFlags.Admin)]
public sealed class AddReagent : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+ [Dependency] private readonly IPrototypeManager _protomanager = default!;
+
public string Command => "addreagent";
public string Description => "Add (or remove) some amount of reagent from some solution.";
public string Help => $"Usage: {Command} <target> <solution> <reagent> <quantity>";
return;
}
- if (!EntityUid.TryParse(args[0], out var uid))
+ if (!NetEntity.TryParse(args[0], out var uidNet) || !_entManager.TryGetEntity(uidNet, out var uid))
{
shell.WriteLine($"Invalid entity id.");
return;
}
- if (!IoCManager.Resolve<IEntityManager>().TryGetComponent(uid, out SolutionContainerManagerComponent? man))
+ if (!_entManager.TryGetComponent(uid, out SolutionContainerManagerComponent? man))
{
shell.WriteLine($"Entity does not have any solutions.");
return;
}
var solution = man.Solutions[args[1]];
- if (!IoCManager.Resolve<IPrototypeManager>().HasIndex<ReagentPrototype>(args[2]))
+ if (!_protomanager.HasIndex<ReagentPrototype>(args[2]))
{
shell.WriteLine($"Unknown reagent prototype");
return;
var quantity = FixedPoint2.New(MathF.Abs(quantityFloat));
if (quantityFloat > 0)
- EntitySystem.Get<SolutionContainerSystem>().TryAddReagent(uid, solution, args[2], quantity, out var _);
+ _entManager.System<SolutionContainerSystem>().TryAddReagent(uid.Value, solution, args[2], quantity, out _);
else
- EntitySystem.Get<SolutionContainerSystem>().RemoveReagent(uid, solution, args[2], quantity);
+ _entManager.System<SolutionContainerSystem>().RemoveReagent(uid.Value, solution, args[2], quantity);
}
}
}
[AdminCommand(AdminFlags.Admin)]
public sealed class ClearBluespaceLockerLinks : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entityManager = default!;
+
public string Command => "clearbluespacelockerlinks";
public string Description => "Removes the bluespace links of the given uid. Does not remove links this uid is the target of.";
public string Help => "Usage: clearbluespacelockerlinks <storage uid>";
return;
}
- if (!EntityUid.TryParse(args[0], out var entityUid))
+ if (!NetEntity.TryParse(args[0], out var entityUidNet) || !_entityManager.TryGetEntity(entityUidNet, out var entityUid))
{
shell.WriteError(Loc.GetString("shell-entity-uid-must-be-number"));
return;
}
- var entityManager = IoCManager.Resolve<IEntityManager>();
-
- if (entityManager.TryGetComponent<BluespaceLockerComponent>(entityUid, out var originComponent))
- entityManager.RemoveComponent(entityUid, originComponent);
+ _entityManager.RemoveComponent<BluespaceLockerComponent>(entityUid.Value);
}
}
[AdminCommand(AdminFlags.Debug)]
public sealed class DirtyCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+
public string Command => "dirty";
public string Description => "Marks all components on an entity as dirty, if not specified, dirties everything";
public string Help => $"Usage: {Command} [entityUid]";
public async void Execute(IConsoleShell shell, string argStr, string[] args)
{
- var entityManager = IoCManager.Resolve<IEntityManager>();
switch (args.Length)
{
case 0:
- foreach (var entity in entityManager.GetEntities())
+ foreach (var entity in _entManager.GetEntities())
{
- DirtyAll(entityManager, entity);
+ DirtyAll(_entManager, entity);
}
break;
case 1:
- if (!EntityUid.TryParse(args[0], out var parsedTarget))
+ if (!NetEntity.TryParse(args[0], out var parsedTarget))
{
shell.WriteError(Loc.GetString("shell-entity-uid-must-be-number"));
return;
}
- DirtyAll(entityManager, parsedTarget);
+ DirtyAll(_entManager, _entManager.GetEntity(parsedTarget));
break;
default:
shell.WriteLine(Loc.GetString("shell-wrong-arguments-number"));
[AdminCommand(AdminFlags.Admin)]
public sealed class LinkBluespaceLocker : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+
public string Command => "linkbluespacelocker";
public string Description => "Links an entity, the target, to another as a bluespace locker target.";
public string Help => "Usage: linkbluespacelocker <two-way link> <origin storage uid> <target storage uid>";
return;
}
- if (!Boolean.TryParse(args[0], out var bidirectional))
+ if (!bool.TryParse(args[0], out var bidirectional))
{
shell.WriteError(Loc.GetString("shell-invalid-bool"));
return;
}
- if (!EntityUid.TryParse(args[1], out var originUid))
+ if (!NetEntity.TryParse(args[1], out var originUidNet) || !_entManager.TryGetEntity(originUidNet, out var originUid))
{
shell.WriteError(Loc.GetString("shell-entity-uid-must-be-number"));
return;
}
- if (!EntityUid.TryParse(args[2], out var targetUid))
+ if (!NetEntity.TryParse(args[2], out var targetUidNet) || !_entManager.TryGetEntity(targetUidNet, out var targetUid))
{
shell.WriteError(Loc.GetString("shell-entity-uid-must-be-number"));
return;
}
- var entityManager = IoCManager.Resolve<IEntityManager>();
-
- if (!entityManager.TryGetComponent<EntityStorageComponent>(originUid, out var originComponent))
+ if (!_entManager.HasComponent<EntityStorageComponent>(originUid))
{
shell.WriteError(Loc.GetString("shell-entity-with-uid-lacks-component", ("uid", originUid), ("componentName", nameof(EntityStorageComponent))));
return;
}
- if (!entityManager.TryGetComponent<EntityStorageComponent>(targetUid, out var targetComponent))
+ if (!_entManager.HasComponent<EntityStorageComponent>(targetUid))
{
shell.WriteError(Loc.GetString("shell-entity-with-uid-lacks-component", ("uid", targetUid), ("componentName", nameof(EntityStorageComponent))));
return;
}
- entityManager.EnsureComponent<BluespaceLockerComponent>(originUid, out var originBluespaceComponent);
- originBluespaceComponent.BluespaceLinks.Add(targetUid);
- entityManager.EnsureComponent<BluespaceLockerComponent>(targetUid, out var targetBluespaceComponent);
+ _entManager.EnsureComponent<BluespaceLockerComponent>(originUid.Value, out var originBluespaceComponent);
+ originBluespaceComponent.BluespaceLinks.Add(targetUid.Value);
+ _entManager.EnsureComponent<BluespaceLockerComponent>(targetUid.Value, out var targetBluespaceComponent);
if (bidirectional)
{
- targetBluespaceComponent.BluespaceLinks.Add(originUid);
+ targetBluespaceComponent.BluespaceLinks.Add(originUid.Value);
}
else if (targetBluespaceComponent.BluespaceLinks.Count == 0)
{
var chatType = (InGameICChatType) Enum.Parse(typeof(InGameICChatType), args[1]);
- if (!EntityUid.TryParse(args[0], out var source) || !_entityManager.EntityExists(source))
+ if (!NetEntity.TryParse(args[0], out var sourceNet) || !_entityManager.TryGetEntity(sourceNet, out var source) || !_entityManager.EntityExists(source))
{
shell.WriteLine(Loc.GetString("osay-command-error-euid", ("arg", args[0])));
return;
if (string.IsNullOrEmpty(message))
return;
- _entityManager.System<ChatSystem>().TrySendInGameICMessage(source, message, chatType, false);
- _adminLogger.Add(LogType.Action, LogImpact.Low, $"{(shell.Player != null ? shell.Player.Name : "An administrator")} forced {_entityManager.ToPrettyString(source)} to {args[1]}: {message}");
+ _entityManager.System<ChatSystem>().TrySendInGameICMessage(source.Value, message, chatType, false);
+ _adminLogger.Add(LogType.Action, LogImpact.Low, $"{(shell.Player != null ? shell.Player.Name : "An administrator")} forced {_entityManager.ToPrettyString(source.Value)} to {args[1]}: {message}");
}
}
[AdminCommand(AdminFlags.Admin)]
public sealed class RemoveBodyPartCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+
public string Command => "rmbodypart";
public string Description => "Removes a given entity from it's containing body, if any.";
public string Help => "Usage: rmbodypart <uid>";
return;
}
- if (!EntityUid.TryParse(args[0], out var entityUid))
+ if (!NetEntity.TryParse(args[0], out var entityUidNet) || !_entManager.TryGetEntity(entityUidNet, out var entityUid))
{
shell.WriteError(Loc.GetString("shell-entity-uid-must-be-number"));
return;
}
- var entityManager = IoCManager.Resolve<IEntityManager>();
- var bodySystem = entityManager.System<BodySystem>();
+ var bodySystem = _entManager.System<BodySystem>();
if (bodySystem.DropPart(entityUid))
{
- shell.WriteLine($"Removed body part {entityManager.ToPrettyString(entityUid)}.");
+ shell.WriteLine($"Removed body part {_entManager.ToPrettyString(entityUid.Value)}.");
}
else
{
[AdminCommand(AdminFlags.Admin)]
public sealed class RemoveEntityStorageCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+
public string Command => "rmstorage";
public string Description => "Removes a given entity from it's containing storage, if any.";
public string Help => "Usage: rmstorage <uid>";
return;
}
- if (!EntityUid.TryParse(args[0], out var entityUid))
+ if (!NetEntity.TryParse(args[0], out var entityNet) || !_entManager.TryGetEntity(entityNet, out var entityUid))
{
shell.WriteError(Loc.GetString("shell-entity-uid-must-be-number"));
return;
}
- var entityManager = IoCManager.Resolve<IEntityManager>();
+ if (!_entManager.EntitySysManager.TryGetEntitySystem<EntityStorageSystem>(out var entstorage))
+ return;
- if (!entityManager.EntitySysManager.TryGetEntitySystem<EntityStorageSystem>(out var entstorage)) return;
- if (!entityManager.TryGetComponent<TransformComponent>(entityUid, out var transform)) return;
+ if (!_entManager.TryGetComponent<TransformComponent>(entityUid, out var transform))
+ return;
var parent = transform.ParentUid;
- if (entityManager.TryGetComponent<EntityStorageComponent>(parent, out var storage))
+ if (_entManager.TryGetComponent<EntityStorageComponent>(parent, out var storage))
{
- entstorage.Remove(entityUid, storage.Owner, storage);
+ entstorage.Remove(entityUid.Value, storage.Owner, storage);
}
else
{
[AdminCommand(AdminFlags.Admin)]
public sealed class RemoveMechanismCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+
public string Command => "rmmechanism";
public string Description => "Removes a given entity from it's containing bodypart, if any.";
public string Help => "Usage: rmmechanism <uid>";
return;
}
- if (!EntityUid.TryParse(args[0], out var entityUid))
+ if (!NetEntity.TryParse(args[0], out var entityNet) || !_entManager.TryGetEntity(entityNet, out var entityUid))
{
shell.WriteError(Loc.GetString("shell-entity-uid-must-be-number"));
return;
}
- var entityManager = IoCManager.Resolve<IEntityManager>();
- var bodySystem = entityManager.System<BodySystem>();
+ var bodySystem = _entManager.System<BodySystem>();
if (bodySystem.DropOrgan(entityUid))
{
- shell.WriteLine($"Removed organ {entityManager.ToPrettyString(entityUid)}");
+ shell.WriteLine($"Removed organ {_entManager.ToPrettyString(entityUid.Value)}");
}
else
{
[AdminCommand(AdminFlags.Fun)]
public sealed class SetSolutionCapacity : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+
public string Command => "setsolutioncapacity";
public string Description => "Set the capacity (maximum volume) of some solution.";
public string Help => $"Usage: {Command} <target> <solution> <new capacity>";
return;
}
- if (!EntityUid.TryParse(args[0], out var uid))
+ if (!NetEntity.TryParse(args[0], out var uidNet))
{
shell.WriteLine($"Invalid entity id.");
return;
}
- if (!IoCManager.Resolve<IEntityManager>().TryGetComponent(uid, out SolutionContainerManagerComponent? man))
+ if (!_entManager.TryGetEntity(uidNet, out var uid) || !_entManager.TryGetComponent(uid, out SolutionContainerManagerComponent? man))
{
shell.WriteLine($"Entity does not have any solutions.");
return;
}
var quantity = FixedPoint2.New(quantityFloat);
- EntitySystem.Get<SolutionContainerSystem>().SetCapacity(uid, solution, quantity);
+ _entManager.System<SolutionContainerSystem>().SetCapacity(uid.Value, solution, quantity);
}
}
}
[AdminCommand(AdminFlags.Fun)]
public sealed class SetSolutionTemperature : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+
public string Command => "setsolutiontemperature";
public string Description => "Set the temperature of some solution.";
public string Help => $"Usage: {Command} <target> <solution> <new temperature>";
return;
}
- if (!EntityUid.TryParse(args[0], out var uid))
+ if (!NetEntity.TryParse(args[0], out var uidNet) || !_entManager.TryGetEntity(uidNet, out var uid))
{
shell.WriteLine($"Invalid entity id.");
return;
}
- if (!IoCManager.Resolve<IEntityManager>().TryGetComponent(uid, out SolutionContainerManagerComponent? man))
+ if (!_entManager.TryGetComponent(uid, out SolutionContainerManagerComponent? man))
{
shell.WriteLine($"Entity does not have any solutions.");
return;
return;
}
- EntitySystem.Get<SolutionContainerSystem>().SetTemperature(uid, solution, quantity);
+ _entManager.System<SolutionContainerSystem>().SetTemperature(uid.Value, solution, quantity);
}
}
}
[AdminCommand(AdminFlags.Fun)]
public sealed class SetSolutionThermalEnergy : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+
public string Command => "setsolutionthermalenergy";
public string Description => "Set the thermal energy of some solution.";
public string Help => $"Usage: {Command} <target> <solution> <new thermal energy>";
return;
}
- if (!EntityUid.TryParse(args[0], out var uid))
+ if (!NetEntity.TryParse(args[0], out var uidNet) || !_entManager.TryGetEntity(uidNet, out var uid))
{
shell.WriteLine($"Invalid entity id.");
return;
}
- if (!IoCManager.Resolve<IEntityManager>().TryGetComponent(uid, out SolutionContainerManagerComponent? man))
+ if (!_entManager.TryGetComponent(uid, out SolutionContainerManagerComponent? man))
{
shell.WriteLine($"Entity does not have any solutions.");
return;
shell.WriteLine($"Cannot set the thermal energy of a solution with 0 heat capacity to a non-zero number.");
return;
}
- } else if(quantity <= 0.0f)
+ }
+ else if(quantity <= 0.0f)
{
shell.WriteLine($"Cannot set the thermal energy of a solution with heat capacity to a non-positive number.");
return;
}
- EntitySystem.Get<SolutionContainerSystem>().SetThermalEnergy(uid, solution, quantity);
+ _entManager.System<SolutionContainerSystem>().SetThermalEnergy(uid.Value, solution, quantity);
}
}
}
[AdminCommand(AdminFlags.Mapping)]
public sealed class VariantizeCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+ [Dependency] private readonly IRobustRandom _random = default!;
+
public string Command => "variantize";
public string Description => Loc.GetString("variantize-command-description");
return;
}
- var entMan = IoCManager.Resolve<IEntityManager>();
- var random = IoCManager.Resolve<IRobustRandom>();
-
- if (!EntityUid.TryParse(args[0], out var euid))
+ if (!NetEntity.TryParse(args[0], out var euidNet) || !_entManager.TryGetEntity(euidNet, out var euid))
{
shell.WriteError($"Failed to parse euid '{args[0]}'.");
return;
}
- if (!entMan.TryGetComponent(euid, out MapGridComponent? gridComp))
+ if (!_entManager.TryGetComponent(euid, out MapGridComponent? gridComp))
{
shell.WriteError($"Euid '{euid}' does not exist or is not a grid.");
return;
foreach (var tile in gridComp.GetAllTiles())
{
var def = tile.GetContentTileDefinition();
- var newTile = new Tile(tile.Tile.TypeId, tile.Tile.Flags, def.PickVariant(random));
+ var newTile = new Tile(tile.Tile.TypeId, tile.Tile.Flags, def.PickVariant(_random));
gridComp.SetTile(tile.GridIndices, newTile);
}
}
var connected = session != null && session.Status is SessionStatus.Connected or SessionStatus.InGame;
- return new PlayerInfo(name, entityName, identityName, startingRole, antag, session?.AttachedEntity, data.UserId,
+ return new PlayerInfo(name, entityName, identityName, startingRole, antag, GetNetEntity(session?.AttachedEntity), data.UserId,
connected, _roundActivePlayers.Contains(data.UserId));
}
}
+using Content.Server.Administration.Systems;
using Content.Server.Chemistry.Components.SolutionManager;
using Content.Server.EUI;
using Content.Shared.Administration;
public override void Closed()
{
base.Closed();
- EntitySystem.Get<Systems.AdminVerbSystem>().OnEditSolutionsEuiClosed(Player);
+ _entityManager.System<AdminVerbSystem>().OnEditSolutionsEuiClosed(Player);
}
public override EuiStateBase GetNewState()
{
var solutions = _entityManager.GetComponentOrNull<SolutionContainerManagerComponent>(Target)?.Solutions;
- return new EditSolutionsEuiState(Target, solutions);
+ return new EditSolutionsEuiState(_entityManager.GetNetEntity(Target), solutions);
}
}
}
public sealed class SetOutfitEui : BaseEui
{
[Dependency] private readonly IAdminManager _adminManager = default!;
+ [Dependency] private readonly IEntityManager _entManager = default!;
private readonly EntityUid _target;
public SetOutfitEui(EntityUid entity)
{
return new SetOutfitEuiState
{
- TargetEntityId = _target
+ TargetNetEntity = _entManager.GetNetEntity(_target)
};
}
return;
var state = GetUiState(uid, controller);
- UserInterfaceSystem.SetUiState(bui, state);
+ _userInterfaceSystem.SetUiState(bui, state);
}
private AmeControllerBoundUserInterfaceState GetUiState(EntityUid uid, AmeControllerComponent controller)
if (!Resolve(uid, ref udder))
return;
- var doargs = new DoAfterArgs(userUid, 5, new MilkingDoAfterEvent(), uid, uid, used: containerUid)
+ var doargs = new DoAfterArgs(EntityManager, userUid, 5, new MilkingDoAfterEvent(), uid, uid, used: containerUid)
{
BreakOnUserMove = true,
BreakOnDamage = true,
if (args.Length != 1)
shell.WriteError("Argument length must be 1");
- if (!EntityUid.TryParse(args[0], out var uid))
+ if (!NetEntity.TryParse(args[0], out var uidNet) || !TryGetEntity(uidNet, out var uid))
return;
if (!TryComp<AnomalyComponent>(uid, out var anomaly))
return;
- DoAnomalyPulse(uid, anomaly);
+ DoAnomalyPulse(uid.Value, anomaly);
}
[AdminCommand(AdminFlags.Fun)]
if (args.Length != 1)
shell.WriteError("Argument length must be 1");
- if (!EntityUid.TryParse(args[0], out var uid))
+ if (!NetEntity.TryParse(args[0], out var uidNet) || !TryGetEntity(uidNet, out var uid))
return;
if (!HasComp<AnomalyComponent>(uid))
return;
- StartSupercriticalEvent(uid);
+ StartSupercriticalEvent(uid.Value);
}
private CompletionResult GetAnomalyCompletion(IConsoleShell shell, string[] args)
if (!HasComp<AnomalyComponent>(target))
return;
- _doAfter.TryStartDoAfter(new DoAfterArgs(args.User, component.ScanDoAfterDuration, new ScannerDoAfterEvent(), uid, target: target, used: uid)
+ _doAfter.TryStartDoAfter(new DoAfterArgs(EntityManager, args.User, component.ScanDoAfterDuration, new ScannerDoAfterEvent(), uid, target: target, used: uid)
{
DistanceThreshold = 2f
});
return;
}
- var entMan = IoCManager.Resolve<IEntityManager>();
-
- if (!EntityUid.TryParse(args[0], out var euid))
+ if (!NetEntity.TryParse(args[0], out var eNet) || !_entities.TryGetEntity(eNet, out var euid))
{
shell.WriteError($"Failed to parse euid '{args[0]}'.");
return;
}
- if (!entMan.HasComponent<MapGridComponent>(euid))
+ if (!_entities.HasComponent<MapGridComponent>(euid))
{
shell.WriteError($"Euid '{euid}' does not exist or is not a grid.");
return;
}
- var atmos = entMan.EntitySysManager.GetEntitySystem<AtmosphereSystem>();
+ var atmos = _entities.EntitySysManager.GetEntitySystem<AtmosphereSystem>();
- if (atmos.HasAtmosphere(euid))
+ if (atmos.HasAtmosphere(euid.Value))
{
shell.WriteLine("Grid already has an atmosphere.");
return;
}
- _entities.AddComponent<GridAtmosphereComponent>(euid);
+ _entities.AddComponent<GridAtmosphereComponent>(euid.Value);
shell.WriteLine($"Added atmosphere to grid {euid}.");
}
[AdminCommand(AdminFlags.Debug)]
public sealed class AddGasCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+
public string Command => "addgas";
public string Description => "Adds gas at a certain position.";
public string Help => "addgas <X> <Y> <GridEid> <Gas> <moles>";
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
- if (args.Length < 5) return;
+ if (args.Length < 5)
+ return;
- if(!int.TryParse(args[0], out var x)
- || !int.TryParse(args[1], out var y)
- || !EntityUid.TryParse(args[2], out var euid)
- || !(AtmosCommandUtils.TryParseGasID(args[3], out var gasId))
- || !float.TryParse(args[4], out var moles)) return;
+ if (!int.TryParse(args[0], out var x)
+ || !int.TryParse(args[1], out var y)
+ || !NetEntity.TryParse(args[2], out var netEnt)
+ || !_entManager.TryGetEntity(netEnt, out var euid)
+ || !(AtmosCommandUtils.TryParseGasID(args[3], out var gasId))
+ || !float.TryParse(args[4], out var moles))
+ {
+ return;
+ }
- var entMan = IoCManager.Resolve<IEntityManager>();
- if (!entMan.HasComponent<MapGridComponent>(euid))
+ if (!_entManager.HasComponent<MapGridComponent>(euid))
{
shell.WriteError($"Euid '{euid}' does not exist or is not a grid.");
return;
}
- var atmosphereSystem = entMan.EntitySysManager.GetEntitySystem<AtmosphereSystem>();
+ var atmosphereSystem = _entManager.EntitySysManager.GetEntitySystem<AtmosphereSystem>();
var indices = new Vector2i(x, y);
var tile = atmosphereSystem.GetTileMixture(euid, null, indices, true);
[AdminCommand(AdminFlags.Debug)]
public sealed class DeleteGasCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+ [Dependency] private readonly IMapManager _mapManager = default!;
+
public string Command => "deletegas";
public string Description => "Removes all gases from a grid, or just of one type if specified.";
public string Help => $"Usage: {Command} <GridId> <Gas> / {Command} <GridId> / {Command} <Gas> / {Command}";
EntityUid? gridId;
Gas? gas = null;
- var entMan = IoCManager.Resolve<IEntityManager>();
-
switch (args.Length)
{
case 0:
return;
}
- gridId = entMan.GetComponent<TransformComponent>(playerEntity).GridUid;
+ gridId = _entManager.GetComponent<TransformComponent>(playerEntity).GridUid;
if (gridId == null)
{
}
case 1:
{
- if (!EntityUid.TryParse(args[0], out var number))
+ if (!NetEntity.TryParse(args[0], out var numberEnt) || !_entManager.TryGetEntity(numberEnt, out var number))
{
// Argument is a gas
if (player == null)
return;
}
- gridId = entMan.GetComponent<TransformComponent>(playerEntity).GridUid;
+ gridId = _entManager.GetComponent<TransformComponent>(playerEntity).GridUid;
if (gridId == null)
{
}
case 2:
{
- if (!EntityUid.TryParse(args[0], out var first))
+ if (!NetEntity.TryParse(args[0], out var firstNet) || !_entManager.TryGetEntity(firstNet, out var first))
{
shell.WriteLine($"{args[0]} is not a valid integer for a grid id.");
return;
return;
}
- var mapManager = IoCManager.Resolve<IMapManager>();
-
- if (!mapManager.TryGetGrid(gridId, out _))
+ if (!_mapManager.TryGetGrid(gridId, out _))
{
shell.WriteLine($"No grid exists with id {gridId}");
return;
}
- var atmosphereSystem = EntitySystem.Get<AtmosphereSystem>();
+ var atmosphereSystem = _entManager.System<AtmosphereSystem>();
var tiles = 0;
var moles = 0f;
{
foreach (var tile in atmosphereSystem.GetAllMixtures(gridId.Value, true))
{
- if (tile.Immutable) continue;
+ if (tile.Immutable)
+ continue;
tiles++;
moles += tile.TotalMoles;
{
foreach (var tile in atmosphereSystem.GetAllMixtures(gridId.Value, true))
{
- if (tile.Immutable) continue;
+ if (tile.Immutable)
+ continue;
tiles++;
moles += tile.TotalMoles;
[AdminCommand(AdminFlags.Debug)]
public sealed class FillGas : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+ [Dependency] private readonly IMapManager _mapManager = default!;
+
public string Command => "fillgas";
public string Description => "Adds gas to all tiles in a grid.";
public string Help => "fillgas <GridEid> <Gas> <moles>";
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
- if (args.Length < 3) return;
- if(!EntityUid.TryParse(args[0], out var gridId)
- || !(AtmosCommandUtils.TryParseGasID(args[1], out var gasId))
- || !float.TryParse(args[2], out var moles)) return;
+ if (args.Length < 3)
+ return;
- var mapMan = IoCManager.Resolve<IMapManager>();
+ if (!NetEntity.TryParse(args[0], out var gridIdNet)
+ || !_entManager.TryGetEntity(gridIdNet, out var gridId)
+ || !(AtmosCommandUtils.TryParseGasID(args[1], out var gasId))
+ || !float.TryParse(args[2], out var moles))
+ {
+ return;
+ }
- if (!mapMan.TryGetGrid(gridId, out var grid))
+ if (!_mapManager.TryGetGrid(gridId, out var grid))
{
shell.WriteLine("Invalid grid ID.");
return;
}
- var atmosphereSystem = EntitySystem.Get<AtmosphereSystem>();
+ var atmosphereSystem = _entManager.System<AtmosphereSystem>();
foreach (var tile in atmosphereSystem.GetAllMixtures(grid.Owner, true))
{
[AdminCommand(AdminFlags.Debug)]
public sealed class RemoveGasCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+
public string Command => "removegas";
public string Description => "Removes an amount of gases.";
public string Help => "removegas <X> <Y> <GridId> <amount> <ratio>\nIf <ratio> is true, amount will be treated as the ratio of gas to be removed.";
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
- if (args.Length < 5) return;
- if(!int.TryParse(args[0], out var x)
+ if (args.Length < 5)
+ return;
+
+ if (!int.TryParse(args[0], out var x)
|| !int.TryParse(args[1], out var y)
- || !EntityUid.TryParse(args[2], out var id)
+ || !NetEntity.TryParse(args[2], out var idNet)
+ || !_entManager.TryGetEntity(idNet, out var id)
|| !float.TryParse(args[3], out var amount)
- || !bool.TryParse(args[4], out var ratio)) return;
+ || !bool.TryParse(args[4], out var ratio))
+ {
+ return;
+ }
- var atmosphereSystem = EntitySystem.Get<AtmosphereSystem>();
+ var atmosphereSystem = _entManager.System<AtmosphereSystem>();
var indices = new Vector2i(x, y);
var tile = atmosphereSystem.GetTileMixture(id, null, indices, true);
[AdminCommand(AdminFlags.Debug)]
public sealed class SetAtmosTemperatureCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+ [Dependency] private readonly IMapManager _mapManager = default!;
+
public string Command => "setatmostemp";
public string Description => "Sets a grid's temperature (in kelvin).";
public string Help => "Usage: setatmostemp <GridId> <Temperature>";
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
- if (args.Length < 2) return;
- if(!EntityUid.TryParse(args[0], out var gridId)
- || !float.TryParse(args[1], out var temperature)) return;
+ if (args.Length < 2)
+ return;
- var mapMan = IoCManager.Resolve<IMapManager>();
+ if (!_entManager.TryParseNetEntity(args[0], out var gridId)
+ || !float.TryParse(args[1], out var temperature))
+ {
+ return;
+ }
if (temperature < Atmospherics.TCMB)
{
return;
}
- if (!gridId.IsValid() || !mapMan.TryGetGrid(gridId, out var gridComp))
+ if (!gridId.Value.IsValid() || !_mapManager.TryGetGrid(gridId, out var gridComp))
{
shell.WriteLine("Invalid grid ID.");
return;
}
- var atmosphereSystem = EntitySystem.Get<AtmosphereSystem>();
+ var atmosphereSystem = _entManager.System<AtmosphereSystem>();
var tiles = 0;
foreach (var tile in atmosphereSystem.GetAllMixtures(gridComp.Owner, true))
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
- if (args.Length < 4) return;
- if(!int.TryParse(args[0], out var x)
- || !int.TryParse(args[1], out var y)
- || !EntityUid.TryParse(args[2], out var gridId)
- || !float.TryParse(args[3], out var temperature)) return;
+ if (args.Length < 4)
+ return;
+
+ if (!int.TryParse(args[0], out var x)
+ || !int.TryParse(args[1], out var y)
+ || !NetEntity.TryParse(args[2], out var gridIdNet)
+ || !_entities.TryGetEntity(gridIdNet, out var gridId)
+ || !float.TryParse(args[3], out var temperature))
+ {
+ return;
+ }
if (temperature < Atmospherics.TCMB)
{
}
}
- RaiseNetworkEvent(new AtmosDebugOverlayMessage(grid.Owner, baseTile, debugOverlayContent), session.ConnectedClient);
+ RaiseNetworkEvent(new AtmosDebugOverlayMessage(GetNetEntity(grid.Owner), baseTile, debugOverlayContent), session.ConnectedClient);
}
}
}
foreach (var arg in args)
{
- if(!EntityUid.TryParse(arg, out var euid))
+ if (!NetEntity.TryParse(arg, out var netEntity) || !TryGetEntity(netEntity, out var euid))
{
shell.WriteError($"Failed to parse euid '{arg}'.");
return;
continue;
}
- var transform = Transform(euid);
+ var transform = Transform(euid.Value);
foreach (var (indices, tileMain) in gridAtmosphere.Tiles)
{
_userInterface.TrySendUiMessage(uid, GasAnalyzerUiKey.Key,
new GasAnalyzerUserMessage(gasMixList.ToArray(),
component.Target != null ? Name(component.Target.Value) : string.Empty,
- component.Target ?? EntityUid.Invalid,
+ GetNetEntity(component.Target) ?? NetEntity.Invalid,
deviceFlipped));
return true;
}
public void UpdateUserInterface(GasTankComponent component, bool initialUpdate = false)
{
- var internals = GetInternalsComponent(component);
_ui.TrySetUiState(component.Owner, SharedGasTankUiKey.Key,
new GasTankBoundUserInterfaceState
{
using Robust.Shared;
using Robust.Shared.Configuration;
using Robust.Shared.Enums;
-using Robust.Shared.GameStates;
using Robust.Shared.Map;
using Robust.Shared.Threading;
using Robust.Shared.Timing;
[Robust.Shared.IoC.Dependency] private readonly AtmosphereSystem _atmosphereSystem = default!;
[Robust.Shared.IoC.Dependency] private readonly ChunkingSystem _chunkingSys = default!;
- private readonly Dictionary<IPlayerSession, Dictionary<EntityUid, HashSet<Vector2i>>> _lastSentChunks = new();
+ private readonly Dictionary<IPlayerSession, Dictionary<NetEntity, HashSet<Vector2i>>> _lastSentChunks = new();
// Oh look its more duplicated decal system code!
private ObjectPool<HashSet<Vector2i>> _chunkIndexPool =
new DefaultObjectPool<HashSet<Vector2i>>(
new DefaultPooledObjectPolicy<HashSet<Vector2i>>(), 64);
- private ObjectPool<Dictionary<EntityUid, HashSet<Vector2i>>> _chunkViewerPool =
- new DefaultObjectPool<Dictionary<EntityUid, HashSet<Vector2i>>>(
- new DefaultPooledObjectPolicy<Dictionary<EntityUid, HashSet<Vector2i>>>(), 64);
+ private ObjectPool<Dictionary<NetEntity, HashSet<Vector2i>>> _chunkViewerPool =
+ new DefaultObjectPool<Dictionary<NetEntity, HashSet<Vector2i>>>(
+ new DefaultPooledObjectPolicy<Dictionary<NetEntity, HashSet<Vector2i>>>(), 64);
/// <summary>
/// Overlay update interval, in seconds.
private void UpdatePlayer(IPlayerSession playerSession, GameTick curTick)
{
- var xformQuery = GetEntityQuery<TransformComponent>();
- var chunksInRange = _chunkingSys.GetChunksForSession(playerSession, ChunkSize, xformQuery, _chunkIndexPool, _chunkViewerPool);
+ var chunksInRange = _chunkingSys.GetChunksForSession(playerSession, ChunkSize, _chunkIndexPool, _chunkViewerPool);
var previouslySent = _lastSentChunks[playerSession];
var ev = new GasOverlayUpdateEvent();
- foreach (var (grid, oldIndices) in previouslySent)
+ foreach (var (netGrid, oldIndices) in previouslySent)
{
// Mark the whole grid as stale and flag for removal.
- if (!chunksInRange.TryGetValue(grid, out var chunks))
+ if (!chunksInRange.TryGetValue(netGrid, out var chunks))
{
- previouslySent.Remove(grid);
+ previouslySent.Remove(netGrid);
// If grid was deleted then don't worry about sending it to the client.
- if (_mapManager.IsGrid(grid))
- ev.RemovedChunks[grid] = oldIndices;
+ if (!TryGetEntity(netGrid, out var gridId) || !_mapManager.IsGrid(gridId.Value))
+ ev.RemovedChunks[netGrid] = oldIndices;
else
{
oldIndices.Clear();
if (old.Count == 0)
_chunkIndexPool.Return(old);
else
- ev.RemovedChunks.Add(grid, old);
+ ev.RemovedChunks.Add(netGrid, old);
}
- foreach (var (grid, gridChunks) in chunksInRange)
+ foreach (var (netGrid, gridChunks) in chunksInRange)
{
// Not all grids have atmospheres.
- if (!TryComp(grid, out GasTileOverlayComponent? overlay))
+ if (!TryGetEntity(netGrid, out var grid) || !TryComp(grid, out GasTileOverlayComponent? overlay))
continue;
List<GasOverlayChunk> dataToSend = new();
- ev.UpdatedChunks[grid] = dataToSend;
+ ev.UpdatedChunks[netGrid] = dataToSend;
- previouslySent.TryGetValue(grid, out var previousChunks);
+ previouslySent.TryGetValue(netGrid, out var previousChunks);
foreach (var index in gridChunks)
{
dataToSend.Add(value);
}
- previouslySent[grid] = gridChunks;
+ previouslySent[netGrid] = gridChunks;
if (previousChunks != null)
{
previousChunks.Clear();
var distanceLength = distanceCorrection.Length();
- var beamVisualizerEvent = new BeamVisualizerEvent(ent, distanceLength, userAngle, bodyState, shader);
+ var beamVisualizerEvent = new BeamVisualizerEvent(GetNetEntity(ent), distanceLength, userAngle, bodyState, shader);
RaiseNetworkEvent(beamVisualizerEvent);
if (controller != null)
beamSpawnPos = beamSpawnPos.Offset(calculatedDistance.Normalized());
var newEnt = Spawn(prototype, beamSpawnPos);
- var ev = new BeamVisualizerEvent(newEnt, distanceLength, userAngle, bodyState, shader);
+ var ev = new BeamVisualizerEvent(GetNetEntity(newEnt), distanceLength, userAngle, bodyState, shader);
RaiseNetworkEvent(ev);
}
[AdminCommand(AdminFlags.Fun)]
sealed class AddHandCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+ [Dependency] private readonly IPrototypeManager _protoManager = default!;
+ [Dependency] private readonly IRobustRandom _random = default!;
+
[ValidatePrototypeId<EntityPrototype>]
public const string DefaultHandPrototype = "LeftHandHuman";
{
var player = shell.Player as IPlayerSession;
- var entityManager = IoCManager.Resolve<IEntityManager>();
- var prototypeManager = IoCManager.Resolve<IPrototypeManager>();
-
EntityUid entity;
EntityUid hand;
}
entity = player.AttachedEntity.Value;
- hand = entityManager.SpawnEntity(DefaultHandPrototype, entityManager.GetComponent<TransformComponent>(entity).Coordinates);
+ hand = _entManager.SpawnEntity(DefaultHandPrototype, _entManager.GetComponent<TransformComponent>(entity).Coordinates);
break;
}
case 1:
{
- if (EntityUid.TryParse(args[0], out var uid))
+ if (NetEntity.TryParse(args[0], out var uidNet) && _entManager.TryGetEntity(uidNet, out var uid))
{
- if (!entityManager.EntityExists(uid))
+ if (!_entManager.EntityExists(uid))
{
shell.WriteLine($"No entity found with uid {uid}");
return;
}
- entity = uid;
- hand = entityManager.SpawnEntity(DefaultHandPrototype, entityManager.GetComponent<TransformComponent>(entity).Coordinates);
+ entity = uid.Value;
+ hand = _entManager.SpawnEntity(DefaultHandPrototype, _entManager.GetComponent<TransformComponent>(entity).Coordinates);
}
else
{
}
entity = player.AttachedEntity.Value;
- hand = entityManager.SpawnEntity(args[0], entityManager.GetComponent<TransformComponent>(entity).Coordinates);
+ hand = _entManager.SpawnEntity(args[0], _entManager.GetComponent<TransformComponent>(entity).Coordinates);
}
break;
}
case 2:
{
- if (!EntityUid.TryParse(args[0], out var uid))
+ if (!NetEntity.TryParse(args[0], out var netEnt) || !_entManager.TryGetEntity(netEnt, out var uid))
{
shell.WriteLine($"{args[0]} is not a valid entity uid.");
return;
}
- if (!entityManager.EntityExists(uid))
+ if (!_entManager.EntityExists(uid))
{
shell.WriteLine($"No entity exists with uid {uid}.");
return;
}
- entity = uid;
+ entity = uid.Value;
- if (!prototypeManager.HasIndex<EntityPrototype>(args[1]))
+ if (!_protoManager.HasIndex<EntityPrototype>(args[1]))
{
shell.WriteLine($"No hand entity exists with id {args[1]}.");
return;
}
- hand = entityManager.SpawnEntity(args[1], entityManager.GetComponent<TransformComponent>(entity).Coordinates);
+ hand = _entManager.SpawnEntity(args[1], _entManager.GetComponent<TransformComponent>(entity).Coordinates);
break;
}
}
}
- if (!entityManager.TryGetComponent(entity, out BodyComponent? body) || body.Root == null)
+ if (!_entManager.TryGetComponent(entity, out BodyComponent? body) || body.Root == null)
{
- var random = IoCManager.Resolve<IRobustRandom>();
- var text = $"You have no body{(random.Prob(0.2f) ? " and you must scream." : ".")}";
+ var text = $"You have no body{(_random.Prob(0.2f) ? " and you must scream." : ".")}";
shell.WriteLine(text);
return;
}
- if (!entityManager.TryGetComponent(hand, out BodyPartComponent? part))
+ if (!_entManager.TryGetComponent(hand, out BodyPartComponent? part))
{
shell.WriteLine($"Hand entity {hand} does not have a {nameof(BodyPartComponent)} component.");
return;
}
- var bodySystem = entityManager.System<BodySystem>();
+ var bodySystem = _entManager.System<BodySystem>();
var attachAt = bodySystem.GetBodyChildrenOfType(entity, BodyPartType.Arm, body).FirstOrDefault();
if (attachAt == default)
if (!bodySystem.TryCreatePartSlotAndAttach(attachAt.Id, slotId, hand, attachAt.Component, part))
{
- shell.WriteError($"Couldn't create a slot with id {slotId} on entity {entityManager.ToPrettyString(entity)}");
+ shell.WriteError($"Couldn't create a slot with id {slotId} on entity {_entManager.ToPrettyString(entity)}");
return;
}
- shell.WriteLine($"Added hand to entity {entityManager.GetComponent<MetaDataComponent>(entity).EntityName}");
+ shell.WriteLine($"Added hand to entity {_entManager.GetComponent<MetaDataComponent>(entity).EntityName}");
}
}
}
[AdminCommand(AdminFlags.Fun)]
public sealed class AttachBodyPartCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+
public string Command => "attachbodypart";
public string Description => "Attaches a body part to you or someone else.";
public string Help => $"{Command} <partEntityUid> / {Command} <entityUid> <partEntityUid>";
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
var player = shell.Player as IPlayerSession;
- var entityManager = IoCManager.Resolve<IEntityManager>();
EntityUid bodyId;
- EntityUid partUid;
+ EntityUid? partUid;
switch (args.Length)
{
return;
}
- if (!EntityUid.TryParse(args[0], out partUid))
+ if (!NetEntity.TryParse(args[0], out var partNet) || !_entManager.TryGetEntity(partNet, out partUid))
{
shell.WriteLine($"{args[0]} is not a valid entity uid.");
return;
break;
case 2:
- if (!EntityUid.TryParse(args[0], out var entityUid))
+ if (!NetEntity.TryParse(args[0], out var entityNet) || !_entManager.TryGetEntity(entityNet, out var entityUid))
{
shell.WriteLine($"{args[0]} is not a valid entity uid.");
return;
}
- if (!EntityUid.TryParse(args[1], out partUid))
+ if (!NetEntity.TryParse(args[1], out partNet) || !_entManager.TryGetEntity(partNet, out partUid))
{
shell.WriteLine($"{args[1]} is not a valid entity uid.");
return;
}
- if (!entityManager.EntityExists(entityUid))
+ if (!_entManager.EntityExists(entityUid))
{
shell.WriteLine($"{entityUid} is not a valid entity.");
return;
}
- bodyId = entityUid;
+ bodyId = entityUid.Value;
break;
default:
shell.WriteLine(Help);
return;
}
- if (!entityManager.TryGetComponent(bodyId, out BodyComponent? body))
+ if (!_entManager.TryGetComponent(bodyId, out BodyComponent? body))
{
- shell.WriteLine($"Entity {entityManager.GetComponent<MetaDataComponent>(bodyId).EntityName} with uid {bodyId} does not have a {nameof(BodyComponent)}.");
+ shell.WriteLine($"Entity {_entManager.GetComponent<MetaDataComponent>(bodyId).EntityName} with uid {bodyId} does not have a {nameof(BodyComponent)}.");
return;
}
- if (!entityManager.EntityExists(partUid))
+ if (!_entManager.EntityExists(partUid))
{
shell.WriteLine($"{partUid} is not a valid entity.");
return;
}
- if (!entityManager.TryGetComponent(partUid, out BodyPartComponent? part))
+ if (!_entManager.TryGetComponent(partUid, out BodyPartComponent? part))
{
- shell.WriteLine($"Entity {entityManager.GetComponent<MetaDataComponent>(partUid).EntityName} with uid {args[0]} does not have a {nameof(BodyPartComponent)}.");
+ shell.WriteLine($"Entity {_entManager.GetComponent<MetaDataComponent>(partUid.Value).EntityName} with uid {args[0]} does not have a {nameof(BodyPartComponent)}.");
return;
}
- var bodySystem = entityManager.System<BodySystem>();
+ var bodySystem = _entManager.System<BodySystem>();
if (bodySystem.BodyHasChild(bodyId, partUid, body, part))
{
- shell.WriteLine($"Body part {entityManager.GetComponent<MetaDataComponent>(partUid).EntityName} with uid {partUid} is already attached to entity {entityManager.GetComponent<MetaDataComponent>(bodyId).EntityName} with uid {bodyId}");
+ shell.WriteLine($"Body part {_entManager.GetComponent<MetaDataComponent>(partUid.Value).EntityName} with uid {partUid} is already attached to entity {_entManager.GetComponent<MetaDataComponent>(bodyId).EntityName} with uid {bodyId}");
return;
}
if (!bodySystem.TryCreatePartSlotAndAttach(attachAt.Id, slotId, partUid, attachAt.Component, part))
{
- shell.WriteError($"Could not create slot {slotId} on entity {entityManager.ToPrettyString(bodyId)}");
+ shell.WriteError($"Could not create slot {slotId} on entity {_entManager.ToPrettyString(bodyId)}");
return;
}
}
- shell.WriteLine($"Attached part {entityManager.ToPrettyString(partUid)} to {entityManager.ToPrettyString(bodyId)}");
+ shell.WriteLine($"Attached part {_entManager.ToPrettyString(partUid.Value)} to {_entManager.ToPrettyString(bodyId)}");
}
}
}
var isUser = user == target;
var delay = !isUser ? internals.Delay : 1.0f;
- _doAfter.TryStartDoAfter(new DoAfterArgs(user, delay, new InternalsDoAfterEvent(), target, target: target)
+ _doAfter.TryStartDoAfter(new DoAfterArgs(EntityManager, user, delay, new InternalsDoAfterEvent(), target, target: target)
{
BreakOnUserMove = true,
BreakOnDamage = true,
if (args.Target == null || !args.CanReach || !HasComp<PlantHolderComponent>(args.Target))
return;
- _doAfterSystem.TryStartDoAfter(new DoAfterArgs(args.User, swab.SwabDelay, new BotanySwabDoAfterEvent(), uid, target: args.Target, used: uid)
+ _doAfterSystem.TryStartDoAfter(new DoAfterArgs(EntityManager, args.User, swab.SwabDelay, new BotanySwabDoAfterEvent(), uid, target: args.Target, used: uid)
{
Broadcast = true,
BreakOnTargetMove = true,
{
public override void KickCamera(EntityUid euid, Vector2 kickback, CameraRecoilComponent? component = null)
{
- if (!Resolve(euid, ref component, false)) return;
+ if (!Resolve(euid, ref component, false))
+ return;
- RaiseNetworkEvent(new CameraKickEvent(euid, kickback), euid);
+ RaiseNetworkEvent(new CameraKickEvent(GetNetEntity(euid), kickback), euid);
}
}
{
if (_timing.CurTime > component.EffectCooldown)
{
- RaiseNetworkEvent(new PlayBoxEffectMessage(uid, component.Mover.Value));
+ RaiseNetworkEvent(new PlayBoxEffectMessage(GetNetEntity(uid), GetNetEntity(component.Mover.Value)));
_audio.PlayPvs(component.EffectSound, uid);
component.EffectCooldown = _timing.CurTime + component.CooldownDuration;
}
!TryComp<StationBankAccountComponent>(station, out var bankAccount)) return;
if (_uiSystem.TryGetUi(consoleUid, CargoConsoleUiKey.Orders, out var bui))
- UserInterfaceSystem.SetUiState(bui, new CargoConsoleInterfaceState(
+ {
+ _uiSystem.SetUiState(bui, new CargoConsoleInterfaceState(
MetaData(station.Value).EntityName,
GetOutstandingOrderCount(orderDatabase),
orderDatabase.Capacity,
bankAccount.Balance,
orderDatabase.Orders
));
+ }
}
private void ConsolePopup(ICommonSession session, string text)
var bui = _uiSystem.GetUi(uid, CargoPalletConsoleUiKey.Sale);
if (Transform(uid).GridUid is not EntityUid gridUid)
{
- UserInterfaceSystem.SetUiState(bui,
+ _uiSystem.SetUiState(bui,
new CargoPalletConsoleInterfaceState(0, 0, false));
return;
}
GetPalletGoods(gridUid, out var toSell, out var amount);
- UserInterfaceSystem.SetUiState(bui,
+ _uiSystem.SetUiState(bui,
new CargoPalletConsoleInterfaceState((int) amount, toSell.Count, true));
}
var shuttleName = orderDatabase?.Shuttle != null ? MetaData(orderDatabase.Shuttle.Value).EntityName : string.Empty;
if (_uiSystem.TryGetUi(uid, CargoConsoleUiKey.Shuttle, out var bui))
- UserInterfaceSystem.SetUiState(bui, new CargoShuttleConsoleBoundUserInterfaceState(
+ _uiSystem.SetUiState(bui, new CargoShuttleConsoleBoundUserInterfaceState(
station != null ? MetaData(station.Value).EntityName : Loc.GetString("cargo-shuttle-console-station-unknown"),
string.IsNullOrEmpty(shuttleName) ? Loc.GetString("cargo-shuttle-console-shuttle-not-found") : shuttleName,
orders
var bui = _uiSystem.GetUi(uid, CargoPalletConsoleUiKey.Sale);
if (Transform(uid).GridUid is not EntityUid gridUid)
{
- UserInterfaceSystem.SetUiState(bui,
+ _uiSystem.SetUiState(bui,
new CargoPalletConsoleInterfaceState(0, 0, false));
return;
}
foreach (var gid in args)
{
- if (!EntityUid.TryParse(gid, out var gridId) || !gridId.IsValid())
+ if (!EntityManager.TryParseNetEntity(gid, out var gridId) || !gridId.Value.IsValid())
{
shell.WriteError($"Invalid grid ID \"{gid}\".");
continue;
if (!TryComp<BodyComponent>(uid, out var body) || !TryComp<MobStateComponent>(uid, out var state))
{
- Logger.ErrorS("pricing", $"Tried to get the mob price of {ToPrettyString(uid)}, which has no {nameof(BodyComponent)} and no {nameof(MobStateComponent)}.");
+ Log.Error($"Tried to get the mob price of {ToPrettyString(uid)}, which has no {nameof(BodyComponent)} and no {nameof(MobStateComponent)}.");
return;
}
-using Content.Server.DeviceNetwork.Systems;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using Content.Server.DeviceNetwork.Systems;
+using Content.Server.PDA;
using Content.Shared.CartridgeLoader;
using Content.Shared.Interaction;
using Robust.Server.Containers;
using Robust.Server.Player;
using Robust.Shared.Containers;
using Robust.Shared.Map;
-using System.Diagnostics.CodeAnalysis;
namespace Content.Server.CartridgeLoader;
{
[Dependency] private readonly ContainerSystem _containerSystem = default!;
[Dependency] private readonly UserInterfaceSystem _userInterfaceSystem = default!;
-
- private const string ContainerName = "program-container";
+ [Dependency] private readonly PdaSystem _pda = default!;
public override void Initialize()
{
SubscribeLocalEvent<CartridgeLoaderComponent, CartridgeUiMessage>(OnUiMessage);
}
+ public IReadOnlyList<EntityUid> GetInstalled(EntityUid uid, ContainerManagerComponent? comp = null)
+ {
+ if (_containerSystem.TryGetContainer(uid, InstalledContainerId, out var container, comp))
+ return container.ContainedEntities;
+
+ return Array.Empty<EntityUid>();
+ }
+
+ public bool TryGetProgram<T>(
+ EntityUid uid,
+ [NotNullWhen(true)] out EntityUid? programUid,
+ [NotNullWhen(true)] out T? program,
+ bool installedOnly = false,
+ CartridgeLoaderComponent? loader = null,
+ ContainerManagerComponent? containerManager = null)
+ {
+ program = default;
+ programUid = null;
+
+ if (!_containerSystem.TryGetContainer(uid, InstalledContainerId, out var container, containerManager))
+ return false;
+
+ foreach (var prog in container.ContainedEntities)
+ {
+ if (!TryComp(prog, out program))
+ continue;
+
+ programUid = prog;
+ return true;
+ }
+
+ if (installedOnly)
+ return false;
+
+ if (!Resolve(uid, ref loader) || !TryComp(loader.CartridgeSlot.Item, out program))
+ return false;
+
+ programUid = loader.CartridgeSlot.Item;
+ return true;
+ }
+
+ public bool TryGetProgram<T>(
+ EntityUid uid,
+ [NotNullWhen(true)] out EntityUid? programUid,
+ bool installedOnly = false,
+ CartridgeLoaderComponent? loader = null,
+ ContainerManagerComponent? containerManager = null)
+ {
+ return TryGetProgram<T>(uid, out programUid, out _, installedOnly, loader, containerManager);
+ }
+
+ public bool HasProgram<T>(
+ EntityUid uid,
+ bool installedOnly = false,
+ CartridgeLoaderComponent? loader = null,
+ ContainerManagerComponent? containerManager = null)
+ {
+ return TryGetProgram<T>(uid, out _, out _, installedOnly, loader, containerManager);
+ }
+
/// <summary>
/// Updates the cartridge loaders ui state.
/// </summary>
/// and use this method to update its state so the cartridge loaders state can be added to it.
/// </remarks>
/// <seealso cref="PDA.PdaSystem.UpdatePdaUserInterface"/>
- public void UpdateUiState(EntityUid loaderUid, CartridgeLoaderUiState state, IPlayerSession? session = default!, CartridgeLoaderComponent? loader = default!)
+ public void UpdateUiState(EntityUid loaderUid, IPlayerSession? session, CartridgeLoaderComponent? loader)
{
if (!Resolve(loaderUid, ref loader))
return;
- state.ActiveUI = loader.ActiveProgram;
- state.Programs = GetAvailablePrograms(loaderUid, loader);
+ if (!_userInterfaceSystem.TryGetUi(loaderUid, loader.UiKey, out var ui))
+ return;
- if (_userInterfaceSystem.TryGetUi(loaderUid, loader.UiKey, out var ui))
- UserInterfaceSystem.SetUiState(ui, state, session);
+ var programs = GetAvailablePrograms(loaderUid, loader);
+ var state = new CartridgeLoaderUiState(programs, GetNetEntity(loader.ActiveProgram));
+ _userInterfaceSystem.SetUiState(ui, state, session);
}
/// <summary>
return;
if (_userInterfaceSystem.TryGetUi(loaderUid, loader.UiKey, out var ui))
- UserInterfaceSystem.SetUiState(ui, state, session);
+ _userInterfaceSystem.SetUiState(ui, state, session);
}
/// <summary>
/// <param name="uid">The cartridge loaders uid</param>
/// <param name="loader">The cartridge loader component</param>
/// <returns>A list of all the available program entity ids</returns>
- public List<EntityUid> GetAvailablePrograms(EntityUid uid, CartridgeLoaderComponent? loader = default!)
+ public List<NetEntity> GetAvailablePrograms(EntityUid uid, CartridgeLoaderComponent? loader = default!)
{
if (!Resolve(uid, ref loader))
- return new List<EntityUid>();
-
- //Don't count a cartridge that has already been installed as available to avoid confusion
- if (loader.CartridgeSlot.HasItem && TryFindInstalled(Prototype(loader.CartridgeSlot.Item!.Value)?.ID, loader, out _))
- return loader.InstalledPrograms;
+ return new List<NetEntity>();
- var available = new List<EntityUid>();
- available.AddRange(loader.InstalledPrograms);
+ var available = GetNetEntityList(GetInstalled(uid));
- if (loader.CartridgeSlot.HasItem)
- available.Add(loader.CartridgeSlot.Item!.Value);
+ if (loader.CartridgeSlot.Item is not { } cartridge)
+ return available;
+ // TODO exclude duplicate programs. Or something I dunno I CBF fixing this mess.
+ available.Add(GetNetEntity(cartridge));
return available;
}
/// <returns>Whether installing the cartridge was successful</returns>
public bool InstallCartridge(EntityUid loaderUid, EntityUid cartridgeUid, CartridgeLoaderComponent? loader = default!)
{
- if (!Resolve(loaderUid, ref loader) || loader.InstalledPrograms.Count >= loader.DiskSpace)
+ if (!Resolve(loaderUid, ref loader))
return false;
//This will eventually be replaced by serializing and deserializing the cartridge to copy it when something needs
//the data on the cartridge to carry over when installing
+
+ // For anyone stumbling onto this: Do not do this or I will cut you.
var prototypeId = Prototype(cartridgeUid)?.ID;
return prototypeId != null && InstallProgram(loaderUid, prototypeId, loader: loader);
}
/// <returns>Whether installing the cartridge was successful</returns>
public bool InstallProgram(EntityUid loaderUid, string prototype, bool deinstallable = true, CartridgeLoaderComponent? loader = default!)
{
- if (!Resolve(loaderUid, ref loader) || loader.InstalledPrograms.Count >= loader.DiskSpace)
+ if (!Resolve(loaderUid, ref loader))
return false;
- if (!_containerSystem.TryGetContainer(loaderUid, ContainerName, out var container))
+ if (!_containerSystem.TryGetContainer(loaderUid, InstalledContainerId, out var container))
return false;
- //Prevent installing cartridges that have already been installed
- if (TryFindInstalled(prototype, loader, out _))
+ if (container.Count >= loader.DiskSpace)
return false;
+ // TODO cancel duplicate program installations
var ev = new ProgramInstallationAttempt(loaderUid, prototype);
RaiseLocalEvent(ref ev);
return false;
var installedProgram = Spawn(prototype, new EntityCoordinates(loaderUid, 0, 0));
- container?.Insert(installedProgram);
+ container.Insert(installedProgram);
UpdateCartridgeInstallationStatus(installedProgram, deinstallable ? InstallationStatus.Installed : InstallationStatus.Readonly);
- loader.InstalledPrograms.Add(installedProgram);
RaiseLocalEvent(installedProgram, new CartridgeAddedEvent(loaderUid));
UpdateUserInterfaceState(loaderUid, loader);
return true;
}
- /// <summary>
- /// Uninstalls a program using its prototype
- /// </summary>
- /// <param name="loaderUid">The cartridge loader uid</param>
- /// <param name="prototype">The prototype name of the program to be uninstalled</param>
- /// <param name="loader">The cartridge loader component</param>
- /// <returns>Whether uninstalling the program was successful</returns>
- public bool UninstallProgram(EntityUid loaderUid, string prototype, CartridgeLoaderComponent? loader = default!)
- {
- if (!Resolve(loaderUid, ref loader))
- return false;
-
- return TryFindInstalled(prototype, loader, out var programUid) &&
- UninstallProgram(loaderUid, programUid.Value, loader);
- }
-
/// <summary>
/// Uninstalls a program using its uid
/// </summary>
/// <returns>Whether uninstalling the program was successful</returns>
public bool UninstallProgram(EntityUid loaderUid, EntityUid programUid, CartridgeLoaderComponent? loader = default!)
{
- if (!Resolve(loaderUid, ref loader) || !ContainsCartridge(programUid, loader, true))
+ if (!Resolve(loaderUid, ref loader))
+ return false;
+
+ if (!GetInstalled(loaderUid).Contains(programUid))
return false;
if (loader.ActiveProgram == programUid)
loader.ActiveProgram = null;
loader.BackgroundPrograms.Remove(programUid);
- loader.InstalledPrograms.Remove(programUid);
EntityManager.QueueDeleteEntity(programUid);
UpdateUserInterfaceState(loaderUid, loader);
return true;
if (!Resolve(loaderUid, ref loader))
return;
- if (!ContainsCartridge(programUid, loader))
+ if (!HasProgram(loaderUid, programUid, loader))
return;
if (loader.ActiveProgram.HasValue)
if (!Resolve(loaderUid, ref loader))
return;
- if (!ContainsCartridge(programUid, loader) || loader.ActiveProgram != programUid)
+ if (!HasProgram(loaderUid, programUid, loader) || loader.ActiveProgram != programUid)
return;
if (!loader.BackgroundPrograms.Contains(programUid))
if (!Resolve(loaderUid, ref loader))
return;
- if (!ContainsCartridge(cartridgeUid, loader))
+ if (!HasProgram(loaderUid, cartridgeUid, loader))
return;
if (loader.ActiveProgram != cartridgeUid)
if (!Resolve(loaderUid, ref loader))
return;
- if (!ContainsCartridge(cartridgeUid, loader))
+ if (!HasProgram(loaderUid, cartridgeUid, loader))
return;
if (loader.ActiveProgram != cartridgeUid)
protected override void OnItemInserted(EntityUid uid, CartridgeLoaderComponent loader, EntInsertedIntoContainerMessage args)
{
+ if (args.Container.ID != InstalledContainerId && args.Container.ID != loader.CartridgeSlot.ID)
+ return;
+
RaiseLocalEvent(args.Entity, new CartridgeAddedEvent(uid));
base.OnItemInserted(uid, loader, args);
}
protected override void OnItemRemoved(EntityUid uid, CartridgeLoaderComponent loader, EntRemovedFromContainerMessage args)
{
+ if (args.Container.ID != InstalledContainerId && args.Container.ID != loader.CartridgeSlot.ID)
+ return;
+
var deactivate = loader.BackgroundPrograms.Remove(args.Entity);
if (loader.ActiveProgram == args.Entity)
RaiseLocalEvent(args.Entity, new CartridgeRemovedEvent(uid));
base.OnItemRemoved(uid, loader, args);
+
+ _pda.UpdatePdaUi(uid);
}
/// <summary>
/// </summary>
private void OnMapInit(EntityUid uid, CartridgeLoaderComponent component, MapInitEvent args)
{
+ // TODO remove this and use container fill.
foreach (var prototype in component.PreinstalledPrograms)
{
InstallProgram(uid, prototype, deinstallable: false);
private void OnLoaderUiMessage(EntityUid loaderUid, CartridgeLoaderComponent component, CartridgeLoaderUiMessage message)
{
+ var cartridge = GetEntity(message.CartridgeUid);
+
switch (message.Action)
{
case CartridgeUiMessageAction.Activate:
- ActivateProgram(loaderUid, message.CartridgeUid, component);
+ ActivateProgram(loaderUid, cartridge, component);
break;
case CartridgeUiMessageAction.Deactivate:
- DeactivateProgram(loaderUid, message.CartridgeUid, component);
+ DeactivateProgram(loaderUid, cartridge, component);
break;
case CartridgeUiMessageAction.Install:
- InstallCartridge(loaderUid, message.CartridgeUid, component);
+ InstallCartridge(loaderUid, cartridge, component);
break;
case CartridgeUiMessageAction.Uninstall:
- UninstallProgram(loaderUid, message.CartridgeUid, component);
+ UninstallProgram(loaderUid, cartridge, component);
break;
case CartridgeUiMessageAction.UIReady:
if (component.ActiveProgram.HasValue)
private void OnUiMessage(EntityUid uid, CartridgeLoaderComponent component, CartridgeUiMessage args)
{
var cartridgeEvent = args.MessageEvent;
- cartridgeEvent.LoaderUid = uid;
+ cartridgeEvent.LoaderUid = GetNetEntity(uid);
RelayEvent(component, cartridgeEvent, true);
}
}
}
- /// <summary>
- /// Searches for a program by its prototype name in the list of installed programs
- /// </summary>
- private bool TryFindInstalled(string? prototype, CartridgeLoaderComponent loader, [NotNullWhen(true)] out EntityUid? programUid)
- {
- foreach (var program in loader.InstalledPrograms)
- {
- if (Prototype(program)?.ID == prototype)
- {
- programUid = program;
- return true;
- }
- }
-
- programUid = default;
- return false;
- }
-
/// <summary>
/// Shortcut for updating the loaders user interface state without passing in a subtype of <see cref="CartridgeLoaderUiState"/>
/// like the <see cref="PDA.PdaSystem"/> does when updating its ui state
/// <seealso cref="PDA.PdaSystem.UpdatePdaUserInterface"/>
private void UpdateUserInterfaceState(EntityUid loaderUid, CartridgeLoaderComponent loader)
{
- UpdateUiState(loaderUid, new CartridgeLoaderUiState(), null, loader);
+ UpdateUiState(loaderUid, null, loader);
}
private void UpdateCartridgeInstallationStatus(EntityUid cartridgeUid, InstallationStatus installationStatus, CartridgeComponent? cartridgeComponent = default!)
if (Resolve(cartridgeUid, ref cartridgeComponent))
{
cartridgeComponent.InstallationStatus = installationStatus;
- Dirty(cartridgeComponent);
+ Dirty(cartridgeUid, cartridgeComponent);
}
}
- private static bool ContainsCartridge(EntityUid cartridgeUid, CartridgeLoaderComponent loader, bool onlyInstalled = false)
+ private bool HasProgram(EntityUid loader, EntityUid program, CartridgeLoaderComponent component)
{
- return !onlyInstalled && loader.CartridgeSlot.Item?.Equals(cartridgeUid) == true || loader.InstalledPrograms.Contains(cartridgeUid);
+ return component.CartridgeSlot.Item == program || GetInstalled(loader).Contains(program);
}
}
using Content.Shared.CartridgeLoader.Cartridges;
using Content.Shared.CCVar;
using Robust.Shared.Configuration;
+using Robust.Shared.Containers;
using Robust.Shared.Prototypes;
namespace Content.Server.CartridgeLoader.Cartridges;
/// </remarks>
private void OnUiMessage(EntityUid uid, CrewManifestCartridgeComponent component, CartridgeMessageEvent args)
{
- UpdateUiState(uid, args.LoaderUid, component);
+ UpdateUiState(uid, GetEntity(args.LoaderUid), component);
}
/// <summary>
{
_unsecureViewersAllowed = unsecureViewersAllowed;
- var allCartridgeLoaders = AllEntityQuery<CartridgeLoaderComponent>();
-
- while (allCartridgeLoaders.MoveNext(out EntityUid loaderUid, out CartridgeLoaderComponent? comp))
+ var allCartridgeLoaders = AllEntityQuery<CartridgeLoaderComponent, ContainerManagerComponent>();
+ while (allCartridgeLoaders.MoveNext(out var loaderUid, out var comp, out var cont))
{
if (_unsecureViewersAllowed)
- _cartridgeLoader?.InstallProgram(loaderUid, CartridgePrototypeName, false, comp);
- else
- _cartridgeLoader?.UninstallProgram(loaderUid, CartridgePrototypeName, comp);
+ {
+ _cartridgeLoader.InstallProgram(loaderUid, CartridgePrototypeName, false, comp);
+ return;
+ }
+
+ if (_cartridgeLoader.TryGetProgram<CrewManifestCartridgeComponent>(loaderUid, out var program, true, comp, cont))
+ _cartridgeLoader.UninstallProgram(loaderUid, program.Value, comp);
}
}
component.Notes.Remove(message.Note);
}
- UpdateUiState(uid, args.LoaderUid, component);
+ UpdateUiState(uid, GetEntity(args.LoaderUid), component);
}
private void OnRequestCharacterInfoEvent(RequestCharacterInfoEvent msg, EntitySessionEventArgs args)
{
if (!args.SenderSession.AttachedEntity.HasValue
- || args.SenderSession.AttachedEntity != msg.EntityUid)
+ || args.SenderSession.AttachedEntity != GetEntity(msg.NetEntity))
return;
var entity = args.SenderSession.AttachedEntity.Value;
briefing = _roles.MindGetBriefing(mindId);
}
- RaiseNetworkEvent(new CharacterInfoEvent(entity, jobTitle, conditions, briefing), args.SenderSession);
+ RaiseNetworkEvent(new CharacterInfoEvent(GetNetEntity(entity), jobTitle, conditions, briefing), args.SenderSession);
}
}
public void ChatMessageToOne(ChatChannel channel, string message, string wrappedMessage, EntityUid source, bool hideChat, INetChannel client, Color? colorOverride = null, bool recordReplay = false, string? audioPath = null, float audioVolume = 0)
{
- var msg = new ChatMessage(channel, message, wrappedMessage, source, hideChat, colorOverride, audioPath, audioVolume);
+ var msg = new ChatMessage(channel, message, wrappedMessage, _entityManager.GetNetEntity(source), hideChat, colorOverride, audioPath, audioVolume);
_netManager.ServerSendMessage(new MsgChatMessage() { Message = msg }, client);
if (!recordReplay)
public void ChatMessageToMany(ChatChannel channel, string message, string wrappedMessage, EntityUid source, bool hideChat, bool recordReplay, List<INetChannel> clients, Color? colorOverride = null, string? audioPath = null, float audioVolume = 0)
{
- var msg = new ChatMessage(channel, message, wrappedMessage, source, hideChat, colorOverride, audioPath, audioVolume);
+ var msg = new ChatMessage(channel, message, wrappedMessage, _entityManager.GetNetEntity(source), hideChat, colorOverride, audioPath, audioVolume);
_netManager.ServerSendToMany(new MsgChatMessage() { Message = msg }, clients);
if (!recordReplay)
public void ChatMessageToAll(ChatChannel channel, string message, string wrappedMessage, EntityUid source, bool hideChat, bool recordReplay, Color? colorOverride = null, string? audioPath = null, float audioVolume = 0)
{
- var msg = new ChatMessage(channel, message, wrappedMessage, source, hideChat, colorOverride, audioPath, audioVolume);
+ var msg = new ChatMessage(channel, message, wrappedMessage, _entityManager.GetNetEntity(source), hideChat, colorOverride, audioPath, audioVolume);
_netManager.ServerSendToAll(new MsgChatMessage() { Message = msg });
if (!recordReplay)
_chatManager.ChatMessageToOne(ChatChannel.Whisper, obfuscatedMessage, wrappedUnknownMessage, source, false, session.ConnectedClient);
}
- _replay.RecordServerMessage(new ChatMessage(ChatChannel.Whisper, message, wrappedMessage, source, MessageRangeHideChatForReplay(range)));
+ _replay.RecordServerMessage(new ChatMessage(ChatChannel.Whisper, message, wrappedMessage, GetNetEntity(source), MessageRangeHideChatForReplay(range)));
var ev = new EntitySpokeEvent(source, message, channel, obfuscatedMessage);
RaiseLocalEvent(source, ev, true);
_chatManager.ChatMessageToOne(channel, message, wrappedMessage, source, entHideChat, session.ConnectedClient);
}
- _replay.RecordServerMessage(new ChatMessage(channel, message, wrappedMessage, source, MessageRangeHideChatForReplay(range)));
+ _replay.RecordServerMessage(new ChatMessage(channel, message, wrappedMessage, GetNetEntity(source), MessageRangeHideChatForReplay(range)));
}
/// <summary>
_adminLogger.Add(LogType.Ingestion, $"{EntityManager.ToPrettyString(user):user} is attempting to inject themselves with a solution {SolutionContainerSystem.ToPrettyString(solution):solution}.");
}
- _doAfter.TryStartDoAfter(new DoAfterArgs(user, actualDelay, new InjectorDoAfterEvent(), injector, target: target, used: injector)
+ _doAfter.TryStartDoAfter(new DoAfterArgs(EntityManager, user, actualDelay, new InjectorDoAfterEvent(), injector, target: target, used: injector)
{
BreakOnUserMove = true,
BreakOnDamage = true,
[Dependency] private readonly IMapManager _mapManager = default!;
[Dependency] private readonly SharedTransformSystem _transform = default!;
+ private EntityQuery<TransformComponent> _xformQuery;
+
private Box2 _baseViewBounds;
public override void Initialize()
{
base.Initialize();
+ _xformQuery = GetEntityQuery<TransformComponent>();
_configurationManager.OnValueChanged(CVars.NetMaxUpdateRange, OnPvsRangeChanged, true);
}
private void OnPvsRangeChanged(float value) => _baseViewBounds = Box2.UnitCentered.Scale(value);
- public Dictionary<EntityUid, HashSet<Vector2i>> GetChunksForSession(
+ public Dictionary<NetEntity, HashSet<Vector2i>> GetChunksForSession(
IPlayerSession session,
int chunkSize,
- EntityQuery<TransformComponent> xformQuery,
ObjectPool<HashSet<Vector2i>> indexPool,
- ObjectPool<Dictionary<EntityUid, HashSet<Vector2i>>> viewerPool,
+ ObjectPool<Dictionary<NetEntity, HashSet<Vector2i>>> viewerPool,
float? viewEnlargement = null)
{
var viewers = GetSessionViewers(session);
- var chunks = GetChunksForViewers(viewers, chunkSize, indexPool, viewerPool, viewEnlargement ?? chunkSize, xformQuery);
+ var chunks = GetChunksForViewers(viewers, chunkSize, indexPool, viewerPool, viewEnlargement ?? chunkSize);
return chunks;
}
return viewers;
}
- private Dictionary<EntityUid, HashSet<Vector2i>> GetChunksForViewers(
+ private Dictionary<NetEntity, HashSet<Vector2i>> GetChunksForViewers(
HashSet<EntityUid> viewers,
int chunkSize,
ObjectPool<HashSet<Vector2i>> indexPool,
- ObjectPool<Dictionary<EntityUid, HashSet<Vector2i>>> viewerPool,
- float viewEnlargement,
- EntityQuery<TransformComponent> xformQuery)
+ ObjectPool<Dictionary<NetEntity, HashSet<Vector2i>>> viewerPool,
+ float viewEnlargement)
{
- Dictionary<EntityUid, HashSet<Vector2i>> chunks = viewerPool.Get();
+ var chunks = viewerPool.Get();
DebugTools.Assert(chunks.Count == 0);
foreach (var viewerUid in viewers)
{
- if (!xformQuery.TryGetComponent(viewerUid, out var xform))
+ if (!_xformQuery.TryGetComponent(viewerUid, out var xform))
{
- Log.Error($"Player has deleted viewer entities? Viewers: {string.Join(", ", viewers.Select(x => ToPrettyString(x)))}");
+ Log.Error($"Player has deleted viewer entities? Viewers: {string.Join(", ", viewers.Select(ToPrettyString))}");
continue;
}
- var pos = _transform.GetWorldPosition(xform, xformQuery);
+ var pos = _transform.GetWorldPosition(xform);
var bounds = _baseViewBounds.Translated(pos).Enlarged(viewEnlargement);
foreach (var grid in _mapManager.FindGridsIntersecting(xform.MapID, bounds, true))
{
- if (!chunks.TryGetValue(grid.Owner, out var set))
+ var netGrid = GetNetEntity(grid.Owner);
+
+ if (!chunks.TryGetValue(netGrid, out var set))
{
- chunks[grid.Owner] = set = indexPool.Get();
+ chunks[netGrid] = set = indexPool.Get();
DebugTools.Assert(set.Count == 0);
}
- var enumerator = new ChunkIndicesEnumerator(_transform.GetInvWorldMatrix(grid.Owner, xformQuery).TransformBox(bounds), chunkSize);
+ var enumerator = new ChunkIndicesEnumerator(_transform.GetInvWorldMatrix(grid.Owner).TransformBox(bounds), chunkSize);
while (enumerator.MoveNext(out var indices))
{
if (climbing.IsClimbing)
return true;
- var args = new DoAfterArgs(user, comp.ClimbDelay, new ClimbDoAfterEvent(), entityToMove, target: climbable, used: entityToMove)
+ var args = new DoAfterArgs(EntityManager, user, comp.ClimbDelay, new ClimbDoAfterEvent(), entityToMove, target: climbable, used: entityToMove)
{
BreakOnTargetMove = true,
BreakOnUserMove = true,
}
var newState = GetUserInterfaceState(consoleComponent);
- UserInterfaceSystem.SetUiState(ui, newState);
+ _uiSystem.SetUiState(ui, newState);
}
public void TryClone(EntityUid uid, EntityUid cloningPodUid, EntityUid scannerUid, CloningPodComponent? cloningPod = null, MedicalScannerComponent? scannerComp = null, CloningConsoleComponent? consoleComponent = null)
if (!_gloves.AbilityCheck(uid, args, out var target))
return;
- var doAfterArgs = new DoAfterArgs(uid, comp.Delay, new TerrorDoAfterEvent(), target: target, used: uid, eventTarget: uid)
+ var doAfterArgs = new DoAfterArgs(EntityManager, uid, comp.Delay, new TerrorDoAfterEvent(), target: target, used: uid, eventTarget: uid)
{
BreakOnDamage = true,
BreakOnUserMove = true,
[Dependency] private readonly PopupSystem _popupSystem = default!;
[Dependency] private readonly RoundEndSystem _roundEndSystem = default!;
[Dependency] private readonly StationSystem _stationSystem = default!;
+ [Dependency] private readonly UserInterfaceSystem _uiSystem = default!;
[Dependency] private readonly IConfigurationManager _cfg = default!;
[Dependency] private readonly IAdminLogManager _adminLogger = default!;
}
if (comp.UserInterface is not null)
- UserInterfaceSystem.SetUiState(comp.UserInterface, new CommunicationsConsoleInterfaceState(
+ _uiSystem.SetUiState(comp.UserInterface, new CommunicationsConsoleInterfaceState(
CanAnnounce(comp),
CanCallOrRecall(comp),
levels,
private void UpdateUi(EntityUid uid, ConfigurationComponent component)
{
if (_uiSystem.TryGetUi(uid, ConfigurationUiKey.Key, out var ui))
- UserInterfaceSystem.SetUiState(ui, new ConfigurationBoundUserInterfaceState(component.Config));
+ _uiSystem.SetUiState(ui, new ConfigurationBoundUserInterfaceState(component.Config));
}
private void OnUpdate(EntityUid uid, ConfigurationComponent component, ConfigurationUpdatedMessage args)
namespace Content.Server.Construction.Commands
{
[AdminCommand(AdminFlags.Mapping)]
- sealed class FixRotationsCommand : IConsoleCommand
+ public sealed class FixRotationsCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+ [Dependency] private readonly IMapManager _mapManager = default!;
+
// ReSharper disable once StringLiteralTypo
public string Command => "fixrotations";
public string Description => "Sets the rotation of all occluders, low walls and windows to south.";
public void Execute(IConsoleShell shell, string argsOther, string[] args)
{
var player = shell.Player as IPlayerSession;
- var entityManager = IoCManager.Resolve<IEntityManager>();
EntityUid? gridId;
- var xformQuery = entityManager.GetEntityQuery<TransformComponent>();
+ var xformQuery = _entManager.GetEntityQuery<TransformComponent>();
switch (args.Length)
{
gridId = xformQuery.GetComponent(playerEntity).GridUid;
break;
case 1:
- if (!EntityUid.TryParse(args[0], out var id))
+ if (!NetEntity.TryParse(args[0], out var idNet) || !_entManager.TryGetEntity(idNet, out var id))
{
shell.WriteError($"{args[0]} is not a valid entity.");
return;
return;
}
- var mapManager = IoCManager.Resolve<IMapManager>();
- if (!mapManager.TryGetGrid(gridId, out var grid))
+ if (!_mapManager.TryGetGrid(gridId, out var grid))
{
shell.WriteError($"No grid exists with id {gridId}");
return;
}
- if (!entityManager.EntityExists(grid.Owner))
+ if (!_entManager.EntityExists(grid.Owner))
{
shell.WriteError($"Grid {gridId} doesn't have an associated grid entity.");
return;
}
var changed = 0;
- var tagSystem = entityManager.EntitySysManager.GetEntitySystem<TagSystem>();
+ var tagSystem = _entManager.EntitySysManager.GetEntitySystem<TagSystem>();
foreach (var child in xformQuery.GetComponent(grid.Owner).ChildEntities)
{
- if (!entityManager.EntityExists(child))
+ if (!_entManager.EntityExists(child))
{
continue;
}
// Occluders should only count if the state of it right now is enabled.
// This prevents issues with edge firelocks.
- if (entityManager.TryGetComponent<OccluderComponent>(child, out var occluder))
+ if (_entManager.TryGetComponent<OccluderComponent>(child, out var occluder))
{
valid |= occluder.Enabled;
}
// low walls & grilles
- valid |= entityManager.HasComponent<SharedCanBuildWindowOnTopComponent>(child);
+ valid |= _entManager.HasComponent<SharedCanBuildWindowOnTopComponent>(child);
// cables
- valid |= entityManager.HasComponent<CableComponent>(child);
+ valid |= _entManager.HasComponent<CableComponent>(child);
// anything else that might need this forced
valid |= tagSystem.HasTag(child, "ForceFixRotations");
// override
[AdminCommand(AdminFlags.Mapping)]
sealed class TileReplaceCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+ [Dependency] private readonly IMapManager _mapManager = default!;
+ [Dependency] private readonly ITileDefinitionManager _tileDef = default!;
+
// ReSharper disable once StringLiteralTypo
public string Command => "tilereplace";
public string Description => "Replaces one tile with another.";
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
var player = shell.Player as IPlayerSession;
- var entityManager = IoCManager.Resolve<IEntityManager>();
EntityUid? gridId;
string tileIdA;
string tileIdB;
return;
}
- gridId = entityManager.GetComponent<TransformComponent>(playerEntity).GridUid;
+ gridId = _entManager.GetComponent<TransformComponent>(playerEntity).GridUid;
tileIdA = args[0];
tileIdB = args[1];
break;
case 3:
- if (!EntityUid.TryParse(args[0], out var id))
+ if (!NetEntity.TryParse(args[0], out var idNet) ||
+ !_entManager.TryGetEntity(idNet, out var id))
{
shell.WriteLine($"{args[0]} is not a valid entity.");
return;
return;
}
- var tileDefinitionManager = IoCManager.Resolve<ITileDefinitionManager>();
- var tileA = tileDefinitionManager[tileIdA];
- var tileB = tileDefinitionManager[tileIdB];
+ var tileA = _tileDef[tileIdA];
+ var tileB = _tileDef[tileIdB];
- var mapManager = IoCManager.Resolve<IMapManager>();
- if (!mapManager.TryGetGrid(gridId, out var grid))
+ if (!_mapManager.TryGetGrid(gridId, out var grid))
{
shell.WriteLine($"No grid exists with id {gridId}");
return;
}
- if (!entityManager.EntityExists(grid.Owner))
+ if (!_entManager.EntityExists(grid.Owner))
{
shell.WriteLine($"Grid {gridId} doesn't have an associated grid entity.");
return;
[AdminCommand(AdminFlags.Mapping)]
sealed class TileWallsCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+ [Dependency] private readonly IMapManager _mapManager = default!;
+ [Dependency] private readonly ITileDefinitionManager _tileDefManager = default!;
+
// ReSharper disable once StringLiteralTypo
public string Command => "tilewalls";
public string Description => "Puts an underplating tile below every wall on a grid.";
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
var player = shell.Player as IPlayerSession;
- var entityManager = IoCManager.Resolve<IEntityManager>();
EntityUid? gridId;
switch (args.Length)
return;
}
- gridId = entityManager.GetComponent<TransformComponent>(playerEntity).GridUid;
+ gridId = _entManager.GetComponent<TransformComponent>(playerEntity).GridUid;
break;
case 1:
- if (!EntityUid.TryParse(args[0], out var id))
+ if (!NetEntity.TryParse(args[0], out var idNet) || !_entManager.TryGetEntity(idNet, out var id))
{
shell.WriteLine($"{args[0]} is not a valid entity.");
return;
return;
}
- var mapManager = IoCManager.Resolve<IMapManager>();
- if (!mapManager.TryGetGrid(gridId, out var grid))
+ if (!_mapManager.TryGetGrid(gridId, out var grid))
{
shell.WriteLine($"No grid exists with id {gridId}");
return;
}
- if (!entityManager.EntityExists(grid.Owner))
+ if (!_entManager.EntityExists(grid.Owner))
{
shell.WriteLine($"Grid {gridId} doesn't have an associated grid entity.");
return;
}
- var tileDefinitionManager = IoCManager.Resolve<ITileDefinitionManager>();
- var tagSystem = entityManager.EntitySysManager.GetEntitySystem<TagSystem>();
- var underplating = tileDefinitionManager[TilePrototypeId];
+ var tagSystem = _entManager.EntitySysManager.GetEntitySystem<TagSystem>();
+ var underplating = _tileDefManager[TilePrototypeId];
var underplatingTile = new Tile(underplating.TileId);
var changed = 0;
- foreach (var child in entityManager.GetComponent<TransformComponent>(grid.Owner).ChildEntities)
+ foreach (var child in _entManager.GetComponent<TransformComponent>(grid.Owner).ChildEntities)
{
- if (!entityManager.EntityExists(child))
+ if (!_entManager.EntityExists(child))
{
continue;
}
continue;
}
- var childTransform = entityManager.GetComponent<TransformComponent>(child);
+ var childTransform = _entManager.GetComponent<TransformComponent>(child);
if (!childTransform.Anchored)
{
}
var tile = grid.GetTileRef(childTransform.Coordinates);
- var tileDef = (ContentTileDefinition) tileDefinitionManager[tile.Tile.TypeId];
+ var tileDef = (ContentTileDefinition) _tileDefManager[tile.Tile.TypeId];
if (tileDef.ID == TilePrototypeId)
{
return null;
}
- var doAfterArgs = new DoAfterArgs(user, doAfterTime, new AwaitedDoAfterEvent(), null)
+ var doAfterArgs = new DoAfterArgs(EntityManager, user, doAfterTime, new AwaitedDoAfterEvent(), null)
{
BreakOnDamage = true,
BreakOnTargetMove = false,
_beingBuilt[args.SenderSession] = newSet;
}
+ var location = GetCoordinates(ev.Location);
+
foreach (var condition in constructionPrototype.Conditions)
{
- if (!condition.Condition(user, ev.Location, ev.Angle.GetCardinalDir()))
+ if (!condition.Condition(user, location, ev.Angle.GetCardinalDir()))
{
Cleanup();
return;
return;
}
- var mapPos = ev.Location.ToMap(EntityManager);
+ var mapPos = location.ToMap(EntityManager);
var predicate = GetPredicate(constructionPrototype.CanBuildInImpassable, mapPos);
if (!_interactionSystem.InRangeUnobstructed(user, mapPos, predicate: predicate))
var xform = Transform(structure);
var wasAnchored = xform.Anchored;
xform.Anchored = false;
- xform.Coordinates = ev.Location;
+ xform.Coordinates = GetCoordinates(ev.Location);
xform.LocalRotation = constructionPrototype.CanRotate ? ev.Angle : Angle.Zero;
xform.Anchored = wasAnchored;
- RaiseNetworkEvent(new AckStructureConstructionMessage(ev.Ack, structure));
+ RaiseNetworkEvent(new AckStructureConstructionMessage(ev.Ack, GetNetEntity(structure)));
_adminLogger.Add(LogType.Construction, LogImpact.Low, $"{ToPrettyString(user):player} has turned a {ev.PrototypeName} construction ghost into {ToPrettyString(structure)} at {Transform(structure).Coordinates}");
Cleanup();
}
interactDoAfter.User,
interactDoAfter.Used!.Value,
uid,
- interactDoAfter.ClickLocation);
+ GetCoordinates(interactDoAfter.ClickLocation));
doAfterState = DoAfterState.Completed;
}
// If we still haven't completed this step's DoAfter...
if (doAfterState == DoAfterState.None && insertStep.DoAfter > 0)
{
- var doAfterEv = new ConstructionInteractDoAfterEvent(interactUsing);
+ var doAfterEv = new ConstructionInteractDoAfterEvent(EntityManager, interactUsing);
- var doAfterEventArgs = new DoAfterArgs(interactUsing.User, step.DoAfter, doAfterEv, uid, uid, interactUsing.Used)
+ var doAfterEventArgs = new DoAfterArgs(EntityManager, interactUsing.User, step.DoAfter, doAfterEv, uid, uid, interactUsing.Used)
{
BreakOnDamage = false,
BreakOnTargetMove = true,
uid,
TimeSpan.FromSeconds(toolInsertStep.DoAfter),
new [] { toolInsertStep.Tool },
- new ConstructionInteractDoAfterEvent(interactUsing),
+ new ConstructionInteractDoAfterEvent(EntityManager, interactUsing),
out var doAfter);
return result && doAfter != null ? HandleResult.DoAfter : HandleResult.False;
component.AudioStream = _audio.PlayPvs(component.ExchangeSound, uid);
- _doAfter.TryStartDoAfter(new DoAfterArgs(args.User, component.ExchangeDuration, new ExchangerDoAfterEvent(), uid, target: args.Target, used: uid)
+ _doAfter.TryStartDoAfter(new DoAfterArgs(EntityManager, args.User, component.ExchangeDuration, new ExchangerDoAfterEvent(), uid, target: args.Target, used: uid)
{
BreakOnDamage = true,
BreakOnUserMove = true
if (component.UserInterface?.SubscribedSessions.Contains(actor.PlayerSession) == true)
{
// Tell the user interface the selected stuff
- UserInterfaceSystem.SetUiState(component.UserInterface, new CrayonBoundUserInterfaceState(component.SelectedState, component.SelectableColor, component.Color));
+ _uiSystem.SetUiState(component.UserInterface, new CrayonBoundUserInterfaceState(component.SelectedState, component.SelectableColor, component.Color));
}
args.Handled = true;
return;
}
- OpenEui(message.Id, sessionCast);
+ OpenEui(GetEntity(message.Id), sessionCast);
}
// Not a big fan of this one. Rebuilds the crew manifest every time
}
entries.Entries = entries.Entries.OrderBy(e => e.JobTitle).ThenBy(e => e.Name).ToList();
-
- if (_cachedEntries.ContainsKey(station))
- {
- _cachedEntries[station] = entries;
- }
- else
- {
- _cachedEntries.Add(station, entries);
- }
+ _cachedEntries[station] = entries;
}
}
return;
}
- if (!EntityUid.TryParse(args[0], out var uid))
+ if (!NetEntity.TryParse(args[0], out var uidNet) || !_entityManager.TryGetEntity(uidNet, out var uid))
{
shell.WriteLine($"{args[0]} is not a valid entity UID.");
return;
var crewManifestSystem = _entityManager.System<CrewManifestSystem>();
- crewManifestSystem.OpenEui(uid, session);
+ crewManifestSystem.OpenEui(uid.Value, session);
}
public CompletionResult GetCompletion(IConsoleShell shell, string[] args)
[AdminCommand(AdminFlags.Admin)]
public sealed class GodModeCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+
public string Command => "godmode";
public string Description => "Makes your entity or another invulnerable to almost anything. May have irreversible changes.";
public string Help => $"Usage: {Command} / {Command} <entityUid>";
var player = shell.Player as IPlayerSession;
EntityUid entity;
- var entityManager = IoCManager.Resolve<IEntityManager>();
-
switch (args.Length)
{
case 0:
entity = player.AttachedEntity.Value;
break;
case 1:
- if (!EntityUid.TryParse(args[0], out var id))
+ if (!NetEntity.TryParse(args[0], out var idNet) || !_entManager.TryGetEntity(idNet, out var id))
{
shell.WriteLine($"{args[0]} isn't a valid entity id.");
return;
}
- if (!entityManager.EntityExists(id))
+ if (!_entManager.EntityExists(id))
{
shell.WriteLine($"No entity found with id {id}.");
return;
}
- entity = id;
+ entity = id.Value;
break;
default:
shell.WriteLine(Help);
return;
}
- var godmodeSystem = EntitySystem.Get<SharedGodmodeSystem>();
+ var godmodeSystem = _entManager.System<SharedGodmodeSystem>();
var enabled = godmodeSystem.ToggleGodmode(entity);
- var name = entityManager.GetComponent<MetaDataComponent>(entity).EntityName;
+ var name = _entManager.GetComponent<MetaDataComponent>(entity).EntityName;
shell.WriteLine(enabled
? $"Enabled godmode for entity {name} with id {entity}"
[AdminCommand(AdminFlags.Fun)]
sealed class DamageCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+ [Dependency] private readonly IPrototypeManager _prototypeManager = default!;
+
public string Command => "damage";
public string Description => Loc.GetString("damage-command-description");
public string Help => Loc.GetString("damage-command-help", ("command", Command));
- private readonly IPrototypeManager _prototypeManager = default!;
- public DamageCommand() {
- _prototypeManager = IoCManager.Resolve<IPrototypeManager>();
- }
-
public CompletionResult GetCompletion(IConsoleShell shell, string[] args)
{
if (args.Length == 1)
func = (entity, ignoreResistances) =>
{
var damage = new DamageSpecifier(damageGroup, amount);
- EntitySystem.Get<DamageableSystem>().TryChangeDamage(entity, damage, ignoreResistances);
+ _entManager.System<DamageableSystem>().TryChangeDamage(entity, damage, ignoreResistances);
};
return true;
}
// Fall back to DamageType
- else if (_prototypeManager.TryIndex<DamageTypePrototype>(args[0], out var damageType))
+
+ if (_prototypeManager.TryIndex<DamageTypePrototype>(args[0], out var damageType))
{
func = (entity, ignoreResistances) =>
{
var damage = new DamageSpecifier(damageType, amount);
- EntitySystem.Get<DamageableSystem>().TryChangeDamage(entity, damage, ignoreResistances);
+ _entManager.System<DamageableSystem>().TryChangeDamage(entity, damage, ignoreResistances);
};
return true;
}
- else
- {
- shell.WriteLine(Loc.GetString("damage-command-error-type", ("arg", args[0])));
- func = null;
- return false;
- }
+
+ shell.WriteLine(Loc.GetString("damage-command-error-type", ("arg", args[0])));
+ func = null;
+ return false;
}
public void Execute(IConsoleShell shell, string argStr, string[] args)
return;
}
- EntityUid target;
- var entMan = IoCManager.Resolve<IEntityManager>();
+ EntityUid? target;
+
if (args.Length == 4)
{
- if (!EntityUid.TryParse(args[3], out target) || !entMan.EntityExists(target))
+ if (!_entManager.TryParseNetEntity(args[3], out target) || !_entManager.EntityExists(target))
{
shell.WriteLine(Loc.GetString("damage-command-error-euid", ("arg", args[3])));
return;
return;
}
- if (!TryParseDamageArgs(shell, target, args, out var damageFunc))
+ if (!TryParseDamageArgs(shell, target.Value, args, out var damageFunc))
return;
bool ignoreResistances;
ignoreResistances = false;
}
- damageFunc(target, ignoreResistances);
+ damageFunc(target.Value, ignoreResistances);
}
}
}
[AdminCommand(AdminFlags.Mapping)]
public sealed class AddDecalCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+ [Dependency] private readonly IMapManager _mapManager = default!;
+ [Dependency] private readonly IPrototypeManager _protoManager = default!;
+
public string Command => "adddecal";
public string Description => "Creates a decal on the map";
public string Help => $"{Command} <id> <x position> <y position> <gridId> [angle=<angle> zIndex=<zIndex> color=<color>]";
return;
}
- if (!IoCManager.Resolve<IPrototypeManager>().HasIndex<DecalPrototype>(args[0]))
+ if (!_protoManager.HasIndex<DecalPrototype>(args[0]))
{
shell.WriteError($"Cannot find decalprototype '{args[0]}'.");
}
return;
}
- var mapManager = IoCManager.Resolve<IMapManager>();
- if (!EntityUid.TryParse(args[3], out var gridIdRaw) || !mapManager.TryGetGrid(gridIdRaw, out var grid))
+ if (!NetEntity.TryParse(args[3], out var gridIdNet) ||
+ !_entManager.TryGetEntity(gridIdNet, out var gridIdRaw) ||
+ !_mapManager.TryGetGrid(gridIdRaw, out var grid))
{
shell.WriteError($"Failed parsing gridId '{args[3]}'.");
return;
}
}
- if(EntitySystem.Get<DecalSystem>().TryAddDecal(args[0], coordinates, out var uid, color, rotation, zIndex))
+ if (_entManager.System<DecalSystem>().TryAddDecal(args[0], coordinates, out var uid, color, rotation, zIndex))
{
shell.WriteLine($"Successfully created decal {uid}.");
}
[AdminCommand(AdminFlags.Mapping)]
public sealed class EditDecalCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+ [Dependency] private readonly IMapManager _mapManager = default!;
+
public string Command => "editdecal";
public string Description => "Edits a decal.";
public string Help => $@"{Command} <gridId> <uid> <mode>\n
return;
}
- if (!EntityUid.TryParse(args[0], out var gridId))
+ if (!NetEntity.TryParse(args[0], out var gridIdNet) || !_entManager.TryGetEntity(gridIdNet, out var gridId))
{
shell.WriteError($"Failed parsing gridId '{args[3]}'.");
return;
return;
}
- if (!IoCManager.Resolve<IMapManager>().GridExists(gridId))
+ if (!_mapManager.GridExists(gridId))
{
shell.WriteError($"No grid with gridId {gridId} exists.");
return;
}
- var decalSystem = EntitySystem.Get<DecalSystem>();
+ var decalSystem = _entManager.System<DecalSystem>();
switch (args[2].ToLower())
{
case "position":
return;
}
- if (!decalSystem.SetDecalPosition(gridId, uid, new(gridId, new Vector2(x, y))))
+ if (!decalSystem.SetDecalPosition(gridId.Value, uid, new(gridId.Value, new Vector2(x, y))))
{
shell.WriteError("Failed changing decalposition.");
}
return;
}
- if (!decalSystem.SetDecalColor(gridId, uid, color))
+ if (!decalSystem.SetDecalColor(gridId.Value, uid, color))
{
shell.WriteError("Failed changing decal color.");
}
return;
}
- if (!decalSystem.SetDecalId(gridId, uid, args[3]))
+ if (!decalSystem.SetDecalId(gridId.Value, uid, args[3]))
{
shell.WriteError("Failed changing decal id.");
}
return;
}
- if (!decalSystem.SetDecalRotation(gridId, uid, Angle.FromDegrees(degrees)))
+ if (!decalSystem.SetDecalRotation(gridId.Value, uid, Angle.FromDegrees(degrees)))
{
shell.WriteError("Failed changing decal rotation.");
}
return;
}
- if (!decalSystem.SetDecalZIndex(gridId, uid, zIndex))
+ if (!decalSystem.SetDecalZIndex(gridId.Value, uid, zIndex))
{
shell.WriteError("Failed changing decal zIndex.");
}
return;
}
- if (!decalSystem.SetDecalCleanable(gridId, uid, cleanable))
+ if (!decalSystem.SetDecalCleanable(gridId.Value, uid, cleanable))
{
shell.WriteError("Failed changing decal cleanable flag.");
}
using Content.Shared.Administration;
using Robust.Shared.Console;
using Robust.Shared.Map;
+using SQLitePCL;
namespace Content.Server.Decals.Commands
{
[AdminCommand(AdminFlags.Mapping)]
public sealed class RemoveDecalCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+ [Dependency] private readonly IMapManager _mapManager = default!;
+
public string Command => "rmdecal";
public string Description => "removes a decal";
public string Help => $"{Command} <uid> <gridId>";
return;
}
- if (!EntityUid.TryParse(args[1], out var rawGridId) ||
- !IoCManager.Resolve<IMapManager>().GridExists(rawGridId))
+ if (!NetEntity.TryParse(args[1], out var rawGridIdNet) ||
+ !_entManager.TryGetEntity(rawGridIdNet, out var rawGridId) ||
+ !_mapManager.GridExists(rawGridId))
{
shell.WriteError("Failed parsing gridId.");
+ return;
}
- var decalSystem = EntitySystem.Get<DecalSystem>();
- if (decalSystem.RemoveDecal(rawGridId, uid))
+ var decalSystem = _entManager.System<DecalSystem>();
+ if (decalSystem.RemoveDecal(rawGridId.Value, uid))
{
shell.WriteLine($"Successfully removed decal {uid}.");
return;
-using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Numerics;
using System.Threading.Tasks;
using Robust.Shared;
using Robust.Shared.Configuration;
using Robust.Shared.Enums;
-using Robust.Shared.GameStates;
using Robust.Shared.Map;
using Robust.Shared.Threading;
using Robust.Shared.Timing;
[Dependency] private readonly IGameTiming _timing = default!;
[Dependency] private readonly IAdminLogManager _adminLogger = default!;
- private readonly Dictionary<EntityUid, HashSet<Vector2i>> _dirtyChunks = new();
- private readonly Dictionary<IPlayerSession, Dictionary<EntityUid, HashSet<Vector2i>>> _previousSentChunks = new();
+ private readonly Dictionary<NetEntity, HashSet<Vector2i>> _dirtyChunks = new();
+ private readonly Dictionary<IPlayerSession, Dictionary<NetEntity, HashSet<Vector2i>>> _previousSentChunks = new();
private static readonly Vector2 _boundsMinExpansion = new(0.01f, 0.01f);
private static readonly Vector2 _boundsMaxExpansion = new(1.01f, 1.01f);
new DefaultObjectPool<HashSet<Vector2i>>(
new DefaultPooledObjectPolicy<HashSet<Vector2i>>(), 64);
- private ObjectPool<Dictionary<EntityUid, HashSet<Vector2i>>> _chunkViewerPool =
- new DefaultObjectPool<Dictionary<EntityUid, HashSet<Vector2i>>>(
- new DefaultPooledObjectPolicy<Dictionary<EntityUid, HashSet<Vector2i>>>(), 64);
+ private ObjectPool<Dictionary<NetEntity, HashSet<Vector2i>>> _chunkViewerPool =
+ new DefaultObjectPool<Dictionary<NetEntity, HashSet<Vector2i>>>(
+ new DefaultPooledObjectPolicy<Dictionary<NetEntity, HashSet<Vector2i>>>(), 64);
public override void Initialize()
{
if (!_adminManager.HasAdminFlag(session, AdminFlags.Spawn))
return;
- if (!ev.Coordinates.IsValid(EntityManager))
+ var coordinates = GetCoordinates(ev.Coordinates);
+
+ if (!coordinates.IsValid(EntityManager))
return;
- if (!TryAddDecal(ev.Decal, ev.Coordinates, out _))
+ if (!TryAddDecal(ev.Decal, coordinates, out _))
return;
if (eventArgs.SenderSession.AttachedEntity != null)
if (!_adminManager.HasAdminFlag(session, AdminFlags.Spawn))
return;
- if (!ev.Coordinates.IsValid(EntityManager))
+ var coordinates = GetCoordinates(ev.Coordinates);
+
+ if (!coordinates.IsValid(EntityManager))
return;
- var gridId = ev.Coordinates.GetGridUid(EntityManager);
+ var gridId = coordinates.GetGridUid(EntityManager);
if (gridId == null)
return;
}
}
- protected override void DirtyChunk(EntityUid id, Vector2i chunkIndices, DecalChunk chunk)
+ protected override void DirtyChunk(EntityUid uid, Vector2i chunkIndices, DecalChunk chunk)
{
+ var id = GetNetEntity(uid);
chunk.LastModified = _timing.CurTick;
if(!_dirtyChunks.ContainsKey(id))
_dirtyChunks[id] = new HashSet<Vector2i>();
foreach (var ent in _dirtyChunks.Keys)
{
- if (TryComp(ent, out DecalGridComponent? decals))
- Dirty(decals);
+ if (TryGetEntity(ent, out var uid) && TryComp(uid, out DecalGridComponent? decals))
+ Dirty(uid.Value, decals);
}
if (!PvsEnabled)
public void UpdatePlayer(IPlayerSession player)
{
- var xformQuery = GetEntityQuery<TransformComponent>();
- var chunksInRange = _chunking.GetChunksForSession(player, ChunkSize, xformQuery, _chunkIndexPool, _chunkViewerPool);
+ var chunksInRange = _chunking.GetChunksForSession(player, ChunkSize, _chunkIndexPool, _chunkViewerPool);
var staleChunks = _chunkViewerPool.Get();
var previouslySent = _previousSentChunks[player];
// Then, remove them from previousSentChunks (for stuff like grids out of range)
// and also mark them as stale for networking.
- foreach (var (gridId, oldIndices) in previouslySent)
+ foreach (var (netGrid, oldIndices) in previouslySent)
{
// Mark the whole grid as stale and flag for removal.
- if (!chunksInRange.TryGetValue(gridId, out var chunks))
+ if (!chunksInRange.TryGetValue(netGrid, out var chunks))
{
- previouslySent.Remove(gridId);
+ previouslySent.Remove(netGrid);
// Was the grid deleted?
- if (MapManager.IsGrid(gridId))
- staleChunks[gridId] = oldIndices;
+ if (!TryGetEntity(netGrid, out var gridId) || !MapManager.IsGrid(gridId.Value))
+ staleChunks[netGrid] = oldIndices;
else
{
// If grid was deleted then don't worry about telling the client to delete the chunk.
// Get individual stale chunks.
foreach (var chunk in oldIndices)
{
- if (chunks.Contains(chunk)) continue;
+ if (chunks.Contains(chunk))
+ continue;
+
elmo.Add(chunk);
}
continue;
}
- staleChunks.Add(gridId, elmo);
+ staleChunks.Add(netGrid, elmo);
}
var updatedChunks = _chunkViewerPool.Get();
- foreach (var (gridId, gridChunks) in chunksInRange)
+ foreach (var (netGrid, gridChunks) in chunksInRange)
{
var newChunks = _chunkIndexPool.Get();
- _dirtyChunks.TryGetValue(gridId, out var dirtyChunks);
+ _dirtyChunks.TryGetValue(netGrid, out var dirtyChunks);
- if (!previouslySent.TryGetValue(gridId, out var previousChunks))
+ if (!previouslySent.TryGetValue(netGrid, out var previousChunks))
newChunks.UnionWith(gridChunks);
else
{
_chunkIndexPool.Return(previousChunks);
}
- previouslySent[gridId] = gridChunks;
+ previouslySent[netGrid] = gridChunks;
if (newChunks.Count == 0)
_chunkIndexPool.Return(newChunks);
else
- updatedChunks[gridId] = newChunks;
+ updatedChunks[netGrid] = newChunks;
}
//send all gridChunks to client
SendChunkUpdates(player, updatedChunks, staleChunks);
}
- private void ReturnToPool(Dictionary<EntityUid, HashSet<Vector2i>> chunks)
+ private void ReturnToPool(Dictionary<NetEntity, HashSet<Vector2i>> chunks)
{
foreach (var (_, previous) in chunks)
{
private void SendChunkUpdates(
IPlayerSession session,
- Dictionary<EntityUid, HashSet<Vector2i>> updatedChunks,
- Dictionary<EntityUid, HashSet<Vector2i>> staleChunks)
+ Dictionary<NetEntity, HashSet<Vector2i>> updatedChunks,
+ Dictionary<NetEntity, HashSet<Vector2i>> staleChunks)
{
- var updatedDecals = new Dictionary<EntityUid, Dictionary<Vector2i, DecalChunk>>();
- foreach (var (gridId, chunks) in updatedChunks)
+ var updatedDecals = new Dictionary<NetEntity, Dictionary<Vector2i, DecalChunk>>();
+ foreach (var (netGrid, chunks) in updatedChunks)
{
+ var gridId = GetEntity(netGrid);
+
var collection = ChunkCollection(gridId);
if (collection == null)
continue;
? chunk
: new());
}
- updatedDecals[gridId] = gridChunks;
+ updatedDecals[netGrid] = gridChunks;
}
if (updatedDecals.Count != 0 || staleChunks.Count != 0)
if (_ui.TryGetUi(uid, SignalTimerUiKey.Key, out var bui))
{
- UserInterfaceSystem.SetUiState(bui, new SignalTimerBoundUserInterfaceState(component.Label,
+ _ui.SetUiState(bui, new SignalTimerBoundUserInterfaceState(component.Label,
TimeSpan.FromSeconds(component.Delay).Minutes.ToString("D2"),
TimeSpan.FromSeconds(component.Delay).Seconds.ToString("D2"),
component.CanEditLabel,
if (_ui.TryGetUi(uid, SignalTimerUiKey.Key, out var bui))
{
- UserInterfaceSystem.SetUiState(bui, new SignalTimerBoundUserInterfaceState(signalTimer.Label,
+ _ui.SetUiState(bui, new SignalTimerBoundUserInterfaceState(signalTimer.Label,
TimeSpan.FromSeconds(signalTimer.Delay).Minutes.ToString("D2"),
TimeSpan.FromSeconds(signalTimer.Delay).Seconds.ToString("D2"),
signalTimer.CanEditLabel,
return;
if (_uiSystem.OpenUi(bui, actor.PlayerSession))
- UserInterfaceSystem.SetUiState(bui, new DeviceListUserInterfaceState(
+ _uiSystem.SetUiState(bui, new DeviceListUserInterfaceState(
_deviceListSystem.GetDeviceList(configurator.ActiveDeviceList.Value)
.Select(v => (v.Key, MetaData(v.Value).EntityName)).ToHashSet()
));
}
if (_uiSystem.TryGetUi(uid, NetworkConfiguratorUiKey.List, out var bui))
- UserInterfaceSystem.SetUiState(bui, new NetworkConfiguratorUserInterfaceState(devices));
+ _uiSystem.SetUiState(bui, new NetworkConfiguratorUserInterfaceState(devices));
}
/// <summary>
var state = new MailingUnitBoundUserInterfaceState(component.DisposalUnitInterfaceState, component.Target, component.TargetList, component.Tag);
if (_userInterfaceSystem.TryGetUi(uid, MailingUnitUiKey.Key, out var bui))
- UserInterfaceSystem.SetUiState(bui, state);
+ _userInterfaceSystem.SetUiState(bui, state);
}
private void OnTargetSelected(EntityUid uid, MailingUnitComponent component, TargetSelectedMessage args)
args.Cancel();
}
- if (_uiSystem.TryGetUi(uid, SharedDisposalTaggerComponent.DisposalTaggerUiKey.Key, out var bui))
- UserInterfaceSystem.SetUiState(bui, new SharedDisposalTaggerComponent.DisposalTaggerUserInterfaceState(tagger.Tag));
+ if (_uiSystem.TryGetUi(uid, DisposalTaggerUiKey.Key, out var bui))
+ _uiSystem.SetUiState(bui,
+ new DisposalTaggerUserInterfaceState(tagger.Tag));
}
/// <summary>
/// <returns>Returns a <see cref="SharedDisposalRouterComponent.DisposalRouterUserInterfaceState"/></returns>
private void UpdateRouterUserInterface(EntityUid uid, DisposalRouterComponent router)
{
- var bui = _uiSystem.GetUiOrNull(uid, SharedDisposalTaggerComponent.DisposalTaggerUiKey.Key);
+ var bui = _uiSystem.GetUiOrNull(uid, DisposalTaggerUiKey.Key);
if (router.Tags.Count <= 0)
{
if (bui is not null)
- UserInterfaceSystem.SetUiState(bui, new SharedDisposalTaggerComponent.DisposalTaggerUserInterfaceState(""));
+ _uiSystem.SetUiState(bui, new DisposalTaggerUserInterfaceState(""));
return;
}
taglist.Remove(taglist.Length - 2, 2);
if (bui is not null)
- UserInterfaceSystem.SetUiState(bui, new SharedDisposalTaggerComponent.DisposalTaggerUserInterfaceState(taglist.ToString()));
+ _uiSystem.SetUiState(bui, new DisposalTaggerUserInterfaceState(taglist.ToString()));
}
private void OnAnchorChange(EntityUid uid, DisposalTubeComponent component, ref AnchorStateChangedEvent args)
return;
}
- if (!EntityUid.TryParse(args[0], out var id))
+ if (!NetEntity.TryParse(args[0], out var idNet) || !_entities.TryGetEntity(idNet, out var id))
{
shell.WriteLine(Loc.GetString("shell-invalid-entity-uid",("uid", args[0])));
return;
return;
}
- _entities.System<DisposalTubeSystem>().PopupDirections(id, tube, player.AttachedEntity.Value);
+ _entities.System<DisposalTubeSystem>().PopupDirections(id.Value, tube, player.AttachedEntity.Value);
}
}
}
if (!Resolve(uid, ref holder))
return false;
- if (!holder.Container.CanInsert(toInsert))
+ if (!_containerSystem.CanInsert(toInsert, holder.Container))
{
return false;
}
component.NextFlush,
component.Powered,
component.Engaged,
- component.RecentlyEjected);
+ GetNetEntityList(component.RecentlyEjected));
}
private void OnUnpaused(EntityUid uid, SharedDisposalUnitComponent component, ref EntityUnpausedEvent args)
// Can't check if our target AND disposals moves currently so we'll just check target.
// if you really want to check if disposals moves then add a predicate.
- var doAfterArgs = new DoAfterArgs(userId.Value, delay, new DisposalDoAfterEvent(), unitId, target: toInsertId, used: unitId)
+ var doAfterArgs = new DoAfterArgs(EntityManager, userId.Value, delay, new DisposalDoAfterEvent(), unitId, target: toInsertId, used: unitId)
{
BreakOnDamage = true,
BreakOnTargetMove = true,
public override bool CanInsert(EntityUid uid, SharedDisposalUnitComponent component, EntityUid entity)
{
- if (!base.CanInsert(uid, component, entity) || component is not SharedDisposalUnitComponent serverComp)
+ if (!base.CanInsert(uid, component, entity))
return false;
- return serverComp.Container.CanInsert(entity);
+ return _containerSystem.CanInsert(entity, component.Container);
}
/// <summary>
{
public override void RaiseEffect(Color color, List<EntityUid> entities, Filter filter)
{
- RaiseNetworkEvent(new ColorFlashEffectEvent(color, entities), filter);
+ RaiseNetworkEvent(new ColorFlashEffectEvent(color, GetNetEntityList(entities)), filter);
}
}
[AdminCommand(AdminFlags.Fun)]
public sealed class ElectrocuteCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+
public string Command => "electrocute";
public string Description => Loc.GetString("electrocute-command-description");
public string Help => $"{Command} <uid> <seconds> <damage>";
return;
}
- var entityManager = IoCManager.Resolve<IEntityManager>();
-
- if (!EntityUid.TryParse(args[0], out var uid) || !entityManager.EntityExists(uid))
+ if (!NetEntity.TryParse(args[0], out var uidNet) ||
+ !_entManager.TryGetEntity(uidNet, out var uid) ||
+ !_entManager.EntityExists(uid))
{
shell.WriteError($"Invalid entity specified!");
return;
}
- if (!entityManager.EntitySysManager.GetEntitySystem<StatusEffectsSystem>().CanApplyEffect(uid, ElectrocutionStatusEffect))
+ if (!_entManager.EntitySysManager.GetEntitySystem<StatusEffectsSystem>().CanApplyEffect(uid.Value, ElectrocutionStatusEffect))
{
shell.WriteError(Loc.GetString("electrocute-command-entity-cannot-be-electrocuted"));
return;
damage = 10;
}
- entityManager.EntitySysManager.GetEntitySystem<ElectrocutionSystem>()
- .TryDoElectrocution(uid, null, damage, TimeSpan.FromSeconds(seconds), refresh: true, ignoreInsulation: true);
+ _entManager.EntitySysManager.GetEntitySystem<ElectrocutionSystem>()
+ .TryDoElectrocution(uid.Value, null, damage, TimeSpan.FromSeconds(seconds), refresh: true, ignoreInsulation: true);
}
}
}
if (component.DoAfterTime > 0 && TryGet<SharedDoAfterSystem>(out var doAfterSystem))
{
- var doAfterArgs = new DoAfterArgs(user, component.DoAfterTime, new AwaitedDoAfterEvent(), null)
+ var doAfterArgs = new DoAfterArgs(EntityManager, user, component.DoAfterTime, new AwaitedDoAfterEvent(), null)
{
BreakOnUserMove = true,
};
if (component.DoAfterTime > 0)
{
- var doAfterArgs = new DoAfterArgs(args.User, component.DoAfterTime, new AwaitedDoAfterEvent(), null)
+ var doAfterArgs = new DoAfterArgs(EntityManager, args.User, component.DoAfterTime, new AwaitedDoAfterEvent(), null)
{
BreakOnUserMove = true,
};
var freeTime = user == target ? component.BreakoutTime : component.FreeTime;
var breakOnMove = !component.CanMoveBreakout;
- var doAfterEventArgs = new DoAfterArgs(user, freeTime, new EnsnareableDoAfterEvent(), target, target: target, used: ensnare)
+ var doAfterEventArgs = new DoAfterArgs(EntityManager, user, freeTime, new EnsnareableDoAfterEvent(), target, target: target, used: ensnare)
{
BreakOnUserMove = breakOnMove,
BreakOnTargetMove = breakOnMove,
verbs = _verbSystem.GetLocalVerbs(target, player, typeof(ExamineVerb));
var ev = new ExamineSystemMessages.ExamineInfoResponseMessage(
- target, 0, message, verbs?.ToList(), centerAtCursor
+ GetNetEntity(target), 0, message, verbs?.ToList(), centerAtCursor
);
RaiseNetworkEvent(ev, session.ConnectedClient);
var player = (IPlayerSession) eventArgs.SenderSession;
var session = eventArgs.SenderSession;
var channel = player.ConnectedClient;
+ var entity = GetEntity(request.NetEntity);
if (session.AttachedEntity is not {Valid: true} playerEnt
- || !EntityManager.EntityExists(request.EntityUid))
+ || !EntityManager.EntityExists(entity))
{
RaiseNetworkEvent(new ExamineSystemMessages.ExamineInfoResponseMessage(
- request.EntityUid, request.Id, _entityNotFoundMessage), channel);
+ request.NetEntity, request.Id, _entityNotFoundMessage), channel);
return;
}
- if (!CanExamine(playerEnt, request.EntityUid))
+ if (!CanExamine(playerEnt, entity))
{
RaiseNetworkEvent(new ExamineSystemMessages.ExamineInfoResponseMessage(
- request.EntityUid, request.Id, _entityOutOfRangeMessage, knowTarget: false), channel);
+ request.NetEntity, request.Id, _entityOutOfRangeMessage, knowTarget: false), channel);
return;
}
SortedSet<Verb>? verbs = null;
if (request.GetVerbs)
- verbs = _verbSystem.GetLocalVerbs(request.EntityUid, playerEnt, typeof(ExamineVerb));
+ verbs = _verbSystem.GetLocalVerbs(entity, playerEnt, typeof(ExamineVerb));
- var text = GetExamineText(request.EntityUid, player.AttachedEntity);
+ var text = GetExamineText(entity, player.AttachedEntity);
RaiseNetworkEvent(new ExamineSystemMessages.ExamineInfoResponseMessage(
- request.EntityUid, request.Id, text, verbs?.ToList()), channel);
+ request.NetEntity, request.Id, text, verbs?.ToList()), channel);
}
}
}
var (area, iterationIntensity, spaceData, gridData, spaceMatrix) = results.Value;
- Logger.Info($"Generated explosion preview with {area} tiles in {stopwatch.Elapsed.TotalMilliseconds}ms");
+ Log.Info($"Generated explosion preview with {area} tiles in {stopwatch.Elapsed.TotalMilliseconds}ms");
- Dictionary<EntityUid, Dictionary<int, List<Vector2i>>> tileLists = new();
+ Dictionary<NetEntity, Dictionary<int, List<Vector2i>>> tileLists = new();
foreach (var (grid, data) in gridData)
{
- tileLists.Add(grid, data.TileLists);
+ tileLists.Add(GetNetEntity(grid), data.TileLists);
}
return new ExplosionVisualsState(
private void OnGetState(EntityUid uid, ExplosionVisualsComponent component, ref ComponentGetState args)
{
+ Dictionary<NetEntity, Dictionary<int, List<Vector2i>>> tileLists = new();
+ foreach (var (grid, data) in component.Tiles)
+ {
+ tileLists.Add(GetNetEntity(grid), data);
+ }
+
args.State = new ExplosionVisualsState(
component.Epicenter,
component.ExplosionType,
component.Intensity,
component.SpaceTiles,
- component.Tiles,
+ tileLists,
component.SpaceMatrix,
component.SpaceTileSize);
}
if (user != null)
{
// Check if entity is bomb/mod. grenade/etc
- if (_container.TryGetContainer(uid, "payload", out IContainer? container) &&
+ if (_container.TryGetContainer(uid, "payload", out BaseContainer? container) &&
container.ContainedEntities.Count > 0 &&
TryComp(container.ContainedEntities[0], out ChemicalPayloadComponent? chemicalPayloadComponent))
{
var entries = new List<AdminFaxEntry>();
while (faxes.MoveNext(out var uid, out var fax, out var device))
{
- entries.Add(new AdminFaxEntry(uid, fax.FaxName, device.Address));
+ entries.Add(new AdminFaxEntry(_entityManager.GetNetEntity(uid), fax.FaxName, device.Address));
}
return new AdminFaxEuiState(entries);
}
!_entityManager.HasComponent<GhostComponent>(Player.AttachedEntity.Value))
return;
- _followerSystem.StartFollowingEntity(Player.AttachedEntity.Value, followData.TargetFax);
+ _followerSystem.StartFollowingEntity(Player.AttachedEntity.Value, _entityManager.GetEntity(followData.TargetFax));
break;
}
case AdminFaxEuiMsg.Send sendData:
{
var printout = new FaxPrintout(sendData.Content, sendData.Title, null, sendData.StampState,
new() { new StampDisplayInfo { StampedName = sendData.From, StampedColor = sendData.StampColor } });
- _faxSystem.Receive(sendData.Target, printout);
+ _faxSystem.Receive(_entityManager.GetEntity(sendData.Target), printout);
break;
}
}
_audioSystem.PlayPvs(component.PlungerSound, uid);
- var doAfterArgs = new DoAfterArgs(args.User, component.UnclogDuration, new DrainDoAfterEvent(),uid, args.Target, args.Used)
+ var doAfterArgs = new DoAfterArgs(EntityManager, args.User, component.UnclogDuration, new DrainDoAfterEvent(),uid, args.Target, args.Used)
{
BreakOnTargetMove = true,
BreakOnUserMove = true,
data.Add(new PuddleDebugOverlayData(pos, vol));
}
- RaiseNetworkEvent(new PuddleOverlayDebugMessage(gridUid, data.ToArray()));
+ RaiseNetworkEvent(new PuddleOverlayDebugMessage(GetNetEntity(gridUid), data.ToArray()));
}
}
{
verb.Act = () =>
{
- _doAfterSystem.TryStartDoAfter(new DoAfterArgs(args.User, component.SpillDelay ?? 0, new SpillDoAfterEvent(), uid, target: uid)
+ _doAfterSystem.TryStartDoAfter(new DoAfterArgs(EntityManager, args.User, component.SpillDelay ?? 0, new SpillDoAfterEvent(), uid, target: uid)
{
BreakOnTargetMove = true,
BreakOnUserMove = true,
{
var ev = new ForensicPadDoAfterEvent(sample);
- var doAfterEventArgs = new DoAfterArgs(user, pad.ScanDelay, ev, used, target: target, used: used)
+ var doAfterEventArgs = new DoAfterArgs(EntityManager, user, pad.ScanDelay, ev, used, target: target, used: used)
{
BreakOnTargetMove = true,
BreakOnUserMove = true,
/// </remarks>
private void StartScan(EntityUid uid, ForensicScannerComponent component, EntityUid user, EntityUid target)
{
- _doAfterSystem.TryStartDoAfter(new DoAfterArgs(user, component.ScanDelay, new ForensicScannerDoAfterEvent(), uid, target: target, used: uid)
+ _doAfterSystem.TryStartDoAfter(new DoAfterArgs(EntityManager, user, component.ScanDelay, new ForensicScannerDoAfterEvent(), uid, target: target, used: uid)
{
BreakOnTargetMove = true,
BreakOnUserMove = true,
var verb = new UtilityVerb()
{
Act = () => StartScan(uid, component, args.User, args.Target),
- IconEntity = uid,
+ IconEntity = GetNetEntity(uid),
Text = Loc.GetString("forensic-scanner-verb-text"),
Message = Loc.GetString("forensic-scanner-verb-message")
};
[AnyCommand]
sealed class JoinGameCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
[Dependency] private readonly IPrototypeManager _prototypeManager = default!;
public string Command => "joingame";
return;
}
- var ticker = EntitySystem.Get<GameTicker>();
- var stationSystem = EntitySystem.Get<StationSystem>();
- var stationJobs = EntitySystem.Get<StationJobsSystem>();
+ var ticker = _entManager.System<GameTicker>();
+ var stationJobs = _entManager.System<StationJobsSystem>();
if (ticker.PlayerGameStatuses.TryGetValue(player.UserId, out var status) && status == PlayerGameStatus.JoinedGame)
{
shell.WriteError(Loc.GetString("shell-argument-must-be-number"));
}
- var station = new EntityUid(sid);
+ var station = _entManager.GetEntity(new NetEntity(sid));
var jobPrototype = _prototypeManager.Index<JobPrototype>(id);
if(stationJobs.TryGetJobSlot(station, jobPrototype, out var slots) == false || slots == 0)
{
foreach (var rule in args)
{
- if (!EntityUid.TryParse(rule, out var ruleEnt))
+ if (!NetEntity.TryParse(rule, out var ruleEntNet) || !TryGetEntity(ruleEntNet, out var ruleEnt))
continue;
- EndGameRule(ruleEnt);
+ EndGameRule(ruleEnt.Value);
}
}
PlayerOOCName = contentPlayerData?.Name ?? "(IMPOSSIBLE: REGISTERED MIND WITH NO OWNER)",
// Character name takes precedence over current entity name
PlayerICName = playerIcName,
- PlayerEntityUid = entity,
+ PlayerNetEntity = GetNetEntity(entity),
Role = antag
? roles.First(role => role.Antagonist).Name
: roles.FirstOrDefault().Name ?? Loc.GetString("game-ticker-unknown-role"),
private void UpdateUserInterface(EntityUid uid, GatewayComponent comp)
{
- var destinations = new List<(EntityUid, String, TimeSpan, bool)>();
+ var destinations = new List<(NetEntity, String, TimeSpan, bool)>();
foreach (var destUid in comp.Destinations)
{
var dest = Comp<GatewayDestinationComponent>(destUid);
if (!dest.Enabled)
continue;
- destinations.Add((destUid, dest.Name, dest.NextReady, HasComp<PortalComponent>(destUid)));
+ destinations.Add((GetNetEntity(destUid), dest.Name, dest.NextReady, HasComp<PortalComponent>(destUid)));
}
GetDestination(uid, out var current);
- var state = new GatewayBoundUserInterfaceState(destinations, current, comp.NextClose, comp.LastOpen);
+ var state = new GatewayBoundUserInterfaceState(destinations, GetNetEntity(current), comp.NextClose, comp.LastOpen);
_ui.TrySetUiState(uid, GatewayUiKey.Key, state);
}
private void OnOpenPortal(EntityUid uid, GatewayComponent comp, GatewayOpenPortalMessage args)
{
// can't link if portal is already open on either side, the destination is invalid or on cooldown
+ var desto = GetEntity(args.Destination);
+
if (HasComp<PortalComponent>(uid) ||
- HasComp<PortalComponent>(args.Destination) ||
- !TryComp<GatewayDestinationComponent>(args.Destination, out var dest) ||
+ HasComp<PortalComponent>(desto) ||
+ !TryComp<GatewayDestinationComponent>(desto, out var dest) ||
!dest.Enabled ||
_timing.CurTime < dest.NextReady)
return;
// TODO: admin log???
- OpenPortal(uid, comp, args.Destination, dest);
+ OpenPortal(uid, comp, desto, dest);
}
private void OpenPortal(EntityUid uid, GatewayComponent comp, EntityUid dest, GatewayDestinationComponent destComp)
if (args.SenderSession.AttachedEntity is not {Valid: true} entity ||
!EntityManager.HasComponent<GhostComponent>(entity))
{
- Logger.Warning($"User {args.SenderSession.Name} sent a {nameof(GhostWarpsRequestEvent)} without being a ghost.");
+ Log.Warning($"User {args.SenderSession.Name} sent a {nameof(GhostWarpsRequestEvent)} without being a ghost.");
return;
}
!ghost.CanReturnToBody ||
!EntityManager.TryGetComponent(attached, out ActorComponent? actor))
{
- Logger.Warning($"User {args.SenderSession.Name} sent an invalid {nameof(GhostReturnToBodyRequest)}");
+ Log.Warning($"User {args.SenderSession.Name} sent an invalid {nameof(GhostReturnToBodyRequest)}");
return;
}
if (args.SenderSession.AttachedEntity is not {Valid: true} attached ||
!EntityManager.TryGetComponent(attached, out GhostComponent? ghost))
{
- Logger.Warning($"User {args.SenderSession.Name} tried to warp to {msg.Target} without being a ghost.");
+ Log.Warning($"User {args.SenderSession.Name} tried to warp to {msg.Target} without being a ghost.");
return;
}
- if (!EntityManager.EntityExists(msg.Target))
+ var target = GetEntity(msg.Target);
+
+ if (!EntityManager.EntityExists(target))
{
- Logger.Warning($"User {args.SenderSession.Name} tried to warp to an invalid entity id: {msg.Target}");
+ Log.Warning($"User {args.SenderSession.Name} tried to warp to an invalid entity id: {msg.Target}");
return;
}
- if (TryComp(msg.Target, out WarpPointComponent? warp) && warp.Follow
- || HasComp<MobStateComponent>(msg.Target))
+ if (TryComp(target, out WarpPointComponent? warp) && warp.Follow
+ || HasComp<MobStateComponent>(target))
{
- _followerSystem.StartFollowingEntity(ghost.Owner, msg.Target);
+ _followerSystem.StartFollowingEntity(attached, target);
return;
}
- var xform = Transform(ghost.Owner);
- xform.Coordinates = Transform(msg.Target).Coordinates;
+ var xform = Transform(attached);
+ xform.Coordinates = Transform(target).Coordinates;
xform.AttachToGridOrMap();
if (TryComp(attached, out PhysicsComponent? physics))
_physics.SetLinearVelocity(attached, Vector2.Zero, body: physics);
private IEnumerable<GhostWarp> GetLocationWarps()
{
- foreach (var warp in EntityManager.EntityQuery<WarpPointComponent>(true))
+ var allQuery = AllEntityQuery<WarpPointComponent>();
+
+ while (allQuery.MoveNext(out var uid, out var warp))
{
if (warp.Location != null)
{
- yield return new GhostWarp(warp.Owner, warp.Location, true);
+ yield return new GhostWarp(GetNetEntity(uid), warp.Location, true);
}
}
}
var playerInfo = $"{EntityManager.GetComponent<MetaDataComponent>(attached).EntityName} ({jobName})";
if (_mobState.IsAlive(attached) || _mobState.IsCritical(attached))
- yield return new GhostWarp(attached, playerInfo, false);
+ yield return new GhostWarp(GetNetEntity(attached), playerInfo, false);
}
}
}
[AdminCommand(AdminFlags.Admin)]
public sealed class MakeGhostRoleCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+
public string Command => "makeghostrole";
public string Description => "Turns an entity into a ghost role.";
public string Help => $"Usage: {Command} <entity uid> <name> <description> [<rules>]";
return;
}
- var entityManager = IoCManager.Resolve<IEntityManager>();
-
- if (!EntityUid.TryParse(args[0], out var uid))
+ if (!NetEntity.TryParse(args[0], out var uidNet) || !_entManager.TryGetEntity(uidNet, out var uid))
{
shell.WriteLine($"{args[0]} is not a valid entity uid.");
return;
}
- if (!entityManager.TryGetComponent(uid, out MetaDataComponent? metaData))
+ if (!_entManager.TryGetComponent(uid, out MetaDataComponent? metaData))
{
shell.WriteLine($"No entity found with uid {uid}");
return;
}
- if (entityManager.TryGetComponent(uid, out MindContainerComponent? mind) &&
+ if (_entManager.TryGetComponent(uid, out MindContainerComponent? mind) &&
mind.HasMind)
{
shell.WriteLine($"Entity {metaData.EntityName} with id {uid} already has a mind.");
var description = args[2];
var rules = args.Length >= 4 ? args[3] : Loc.GetString("ghost-role-component-default-rules");
- if (entityManager.TryGetComponent(uid, out GhostRoleComponent? ghostRole))
+ if (_entManager.TryGetComponent(uid, out GhostRoleComponent? ghostRole))
{
shell.WriteLine($"Entity {metaData.EntityName} with id {uid} already has a {nameof(GhostRoleComponent)}");
return;
}
- if (entityManager.TryGetComponent(uid, out GhostTakeoverAvailableComponent? takeOver))
+ if (_entManager.HasComponent<GhostTakeoverAvailableComponent>(uid))
{
shell.WriteLine($"Entity {metaData.EntityName} with id {uid} already has a {nameof(GhostTakeoverAvailableComponent)}");
return;
}
- ghostRole = entityManager.AddComponent<GhostRoleComponent>(uid);
- entityManager.AddComponent<GhostTakeoverAvailableComponent>(uid);
+ ghostRole = _entManager.AddComponent<GhostRoleComponent>(uid.Value);
+ _entManager.AddComponent<GhostTakeoverAvailableComponent>(uid.Value);
ghostRole.RoleName = name;
ghostRole.RoleDescription = description;
ghostRole.RoleRules = rules;
{
public sealed class MakeGhostRoleEui : BaseEui
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+
public MakeGhostRoleEui(EntityUid entityUid)
{
EntityUid = entityUid;
public override EuiStateBase GetNewState()
{
- return new MakeGhostRoleEuiState(EntityUid);
+ return new MakeGhostRoleEuiState(_entManager.GetNetEntity(EntityUid));
}
public override void Closed()
{
base.Closed();
- EntitySystem.Get<GhostRoleSystem>().CloseMakeGhostRoleEui(Player);
+ _entManager.System<GhostRoleSystem>().CloseMakeGhostRoleEui(Player);
}
}
}
return;
}
- _doAfterSystem.TryStartDoAfter(new DoAfterArgs(user, component.InjectionDelay, new GuardianCreatorDoAfterEvent(), injector, target: target, used: injector)
+ _doAfterSystem.TryStartDoAfter(new DoAfterArgs(EntityManager, user, component.InjectionDelay, new GuardianCreatorDoAfterEvent(), injector, target: target, used: injector)
{
BreakOnTargetMove = true,
BreakOnUserMove = true
if (exclude != null)
filter = filter.RemoveWhereAttachedEntity(entity => entity == exclude);
- RaiseNetworkEvent(new PickupAnimationEvent(item, initialPosition, finalPosition, initialAngle), filter);
+ RaiseNetworkEvent(new PickupAnimationEvent(GetNetEntity(item), GetNetCoordinates(initialPosition), finalPosition, initialAngle), filter);
}
protected override void HandleEntityRemoved(EntityUid uid, HandsComponent hands, EntRemovedFromContainerMessage args)
#endregion
#region interactions
- private bool HandleThrowItem(ICommonSession? session, EntityCoordinates coords, EntityUid uid)
+ private bool HandleThrowItem(ICommonSession? session, EntityCoordinates coordinates, EntityUid entity)
{
if (session is not IPlayerSession playerSession)
return false;
throwEnt = splitStack.Value;
}
- var direction = coords.ToMapPos(EntityManager) - Transform(player).WorldPosition;
+ var direction = coordinates.ToMapPos(EntityManager) - Transform(player).WorldPosition;
if (direction == Vector2.Zero)
return true;
/// <param name="implanter">The implanter being used</param>
public void TryImplant(ImplanterComponent component, EntityUid user, EntityUid target, EntityUid implanter)
{
- var args = new DoAfterArgs(user, component.ImplantTime, new ImplantEvent(), implanter, target: target, used: implanter)
+ var args = new DoAfterArgs(EntityManager, user, component.ImplantTime, new ImplantEvent(), implanter, target: target, used: implanter)
{
BreakOnUserMove = true,
BreakOnTargetMove = true,
//TODO: Remove when surgery is in
public void TryDraw(ImplanterComponent component, EntityUid user, EntityUid target, EntityUid implanter)
{
- var args = new DoAfterArgs(user, component.DrawTime, new DrawEvent(), implanter, target: target, used: implanter)
+ var args = new DoAfterArgs(EntityManager, user, component.DrawTime, new DrawEvent(), implanter, target: target, used: implanter)
{
BreakOnUserMove = true,
BreakOnTargetMove = true,
[AdminCommand(AdminFlags.Fun)]
private void AddToBandCommand(IConsoleShell shell, string _, string[] args)
{
- if (!EntityUid.TryParse(args[0], out var firstUid))
+ if (!NetEntity.TryParse(args[0], out var firstUidNet) || !TryGetEntity(firstUidNet, out var firstUid))
{
shell.WriteError($"Cannot parse first Uid");
return;
}
- if (!EntityUid.TryParse(args[1], out var secondUid))
+ if (!NetEntity.TryParse(args[1], out var secondUidNet) || !TryGetEntity(secondUidNet, out var secondUid))
{
shell.WriteError($"Cannot parse second Uid");
return;
return;
}
- var otherInstrument = Comp<InstrumentComponent>(secondUid);
+ var otherInstrument = Comp<InstrumentComponent>(secondUid.Value);
otherInstrument.Playing = true;
otherInstrument.Master = firstUid;
- Dirty(secondUid, otherInstrument);
+ Dirty(secondUid.Value, otherInstrument);
}
private void OnMidiStart(InstrumentStartMidiEvent msg, EntitySessionEventArgs args)
{
- var uid = msg.Uid;
+ var uid = GetEntity(msg.Uid);
if (!TryComp(uid, out InstrumentComponent? instrument))
return;
private void OnMidiStop(InstrumentStopMidiEvent msg, EntitySessionEventArgs args)
{
- var uid = msg.Uid;
+ var uid = GetEntity(msg.Uid);
if (!TryComp(uid, out InstrumentComponent? instrument))
return;
private void OnMidiSetMaster(InstrumentSetMasterEvent msg, EntitySessionEventArgs args)
{
- var uid = msg.Uid;
- var master = msg.Master;
+ var uid = GetEntity(msg.Uid);
+ var master = GetEntity(msg.Master);
if (!HasComp<ActiveInstrumentComponent>(uid))
return;
private void OnMidiSetFilteredChannel(InstrumentSetFilteredChannelEvent msg, EntitySessionEventArgs args)
{
- var uid = msg.Uid;
+ var uid = GetEntity(msg.Uid);
if (!TryComp(uid, out InstrumentComponent? instrument))
return;
if (msg.Value)
{
// Prevent stuck notes when turning off a channel... Shrimple.
- RaiseNetworkEvent(new InstrumentMidiEventEvent(uid, new []{RobustMidiEvent.AllNotesOff((byte)msg.Channel, 0)}));
+ RaiseNetworkEvent(new InstrumentMidiEventEvent(msg.Uid, new []{RobustMidiEvent.AllNotesOff((byte)msg.Channel, 0)}));
}
Dirty(uid, instrument);
_bandRequestQueue.Add(args);
}
- public (EntityUid, string)[] GetBands(EntityUid uid)
+ public (NetEntity, string)[] GetBands(EntityUid uid)
{
var metadataQuery = EntityManager.GetEntityQuery<MetaDataComponent>();
if (Deleted(uid, metadataQuery))
- return Array.Empty<(EntityUid, string)>();
+ return Array.Empty<(NetEntity, string)>();
- var list = new ValueList<(EntityUid, string)>();
+ var list = new ValueList<(NetEntity, string)>();
var instrumentQuery = EntityManager.GetEntityQuery<InstrumentComponent>();
if (!TryComp(uid, out InstrumentComponent? originInstrument)
|| originInstrument.InstrumentPlayer?.AttachedEntity is not {} originPlayer)
- return Array.Empty<(EntityUid, string)>();
+ return Array.Empty<(NetEntity, string)>();
// It's probably faster to get all possible active instruments than all entities in range
var activeEnumerator = EntityManager.EntityQueryEnumerator<ActiveInstrumentComponent>();
|| !metadataQuery.TryGetComponent(entity, out var metadata))
continue;
- list.Add((entity, $"{playerMetadata.EntityName} - {metadata.EntityName}"));
+ list.Add((GetNetEntity(entity), $"{playerMetadata.EntityName} - {metadata.EntityName}"));
}
return list.ToArray();
if (instrument.Playing)
{
+ var netUid = GetNetEntity(uid);
+
// Reset puppet instruments too.
- RaiseNetworkEvent(new InstrumentMidiEventEvent(uid, new[]{RobustMidiEvent.SystemReset(0)}));
+ RaiseNetworkEvent(new InstrumentMidiEventEvent(netUid, new[]{RobustMidiEvent.SystemReset(0)}));
- RaiseNetworkEvent(new InstrumentStopMidiEvent(uid));
+ RaiseNetworkEvent(new InstrumentStopMidiEvent(netUid));
}
instrument.Playing = false;
private void OnMidiEventRx(InstrumentMidiEventEvent msg, EntitySessionEventArgs args)
{
- var uid = msg.Uid;
+ var uid = GetEntity(msg.Uid);
if (!TryComp(uid, out InstrumentComponent? instrument))
return;
if (!instrument.Playing
|| args.SenderSession != instrument.InstrumentPlayer
|| instrument.InstrumentPlayer == null
- || args.SenderSession.AttachedEntity is not {} attached)
+ || args.SenderSession.AttachedEntity is not { } attached)
+ {
return;
+ }
var send = true;
foreach (var request in _bandRequestQueue)
{
- var nearby = GetBands(request.Entity);
- _bui.TrySendUiMessage(request.Entity, request.UiKey, new InstrumentBandResponseBuiMessage(nearby),
+ var entity = GetEntity(request.Entity);
+
+ var nearby = GetBands(entity);
+ _bui.TrySendUiMessage(entity, request.UiKey, new InstrumentBandResponseBuiMessage(nearby),
(IPlayerSession)request.Session);
}
private void HandleDragDropRequestEvent(DragDropRequestEvent msg, EntitySessionEventArgs args)
{
- if (Deleted(msg.Dragged) || Deleted(msg.Target))
+ var dragged = GetEntity(msg.Dragged);
+ var target = GetEntity(msg.Target);
+
+ if (Deleted(dragged) || Deleted(target))
return;
var user = args.SenderSession.AttachedEntity;
- if (user == null || !_actionBlockerSystem.CanInteract(user.Value, msg.Target))
+ if (user == null || !_actionBlockerSystem.CanInteract(user.Value, target))
return;
// must be in range of both the target and the object they are drag / dropping
// Client also does this check but ya know we gotta validate it.
- if (!InRangeUnobstructed(user.Value, msg.Dragged, popup: true)
- || !InRangeUnobstructed(user.Value, msg.Target, popup: true))
+ if (!InRangeUnobstructed(user.Value, dragged, popup: true)
+ || !InRangeUnobstructed(user.Value, target, popup: true))
{
return;
}
- var dragArgs = new DragDropDraggedEvent(user.Value, msg.Target);
+ var dragArgs = new DragDropDraggedEvent(user.Value, target);
// trigger dragdrops on the dropped entity
- RaiseLocalEvent(msg.Dragged, ref dragArgs);
+ RaiseLocalEvent(dragged, ref dragArgs);
if (dragArgs.Handled)
return;
- var dropArgs = new DragDropTargetEvent(user.Value, msg.Dragged);
+ var dropArgs = new DragDropTargetEvent(user.Value, dragged);
// trigger dragdrops on the target entity (what you are dropping onto)
- RaiseLocalEvent(msg.Target, ref dropArgs);
+ RaiseLocalEvent(GetEntity(msg.Target), ref dropArgs);
}
#endregion
butcherable.BeingButchered = true;
component.InUse = true;
- var doAfterArgs = new DoAfterArgs(userUid, component.SpikeDelay + butcherable.ButcherDelay, new SpikeDoAfterEvent(), uid, target: victimUid, used: uid)
+ var doAfterArgs = new DoAfterArgs(EntityManager, userUid, component.SpikeDelay + butcherable.ButcherDelay, new SpikeDoAfterEvent(), uid, target: victimUid, used: uid)
{
BreakOnTargetMove = true,
BreakOnUserMove = true,
if (ui == null)
return;
- UserInterfaceSystem.SetUiState(ui, new MicrowaveUpdateUserInterfaceState(
- component.Storage.ContainedEntities.ToArray(),
+ _userInterface.SetUiState(ui, new MicrowaveUpdateUserInterfaceState(
+ GetNetEntityArray(component.Storage.ContainedEntities.ToArray()),
HasComp<ActiveMicrowaveComponent>(uid),
component.CurrentCookTimeButtonIndex,
component.CurrentCookTimerTime
if (!HasContents(component) || HasComp<ActiveMicrowaveComponent>(uid))
return;
- component.Storage.Remove(args.EntityID);
+ component.Storage.Remove(EntityManager.GetEntity(args.EntityID));
UpdateUserInterfaceState(uid, component);
}
this.IsPowered(uid, EntityManager),
canJuice,
canGrind,
- inputContainer.ContainedEntities.Select(item => item).ToArray(),
+ GetNetEntityArray(inputContainer.ContainedEntities.ToArray()),
containerSolution?.Contents.ToArray()
);
_userInterfaceSystem.TrySetUiState(uid, ReagentGrinderUiKey.Key, state);
return;
var inputContainer = _containerSystem.EnsureContainer<Container>(uid, SharedReagentGrinder.InputContainerId);
+ var ent = GetEntity(message.EntityId);
- if (inputContainer.Remove(message.EntityId))
+ if (inputContainer.Remove(ent))
{
- message.EntityId.RandomOffset(0.4f);
+ ent.RandomOffset(0.4f);
ClickSound(uid, reagentGrinder);
UpdateUiState(uid);
}
return;
var doAfter =
- new DoAfterArgs(user, sharp.ButcherDelayModifier * butcher.ButcherDelay, new SharpDoAfterEvent(), knife, target: target, used: knife)
+ new DoAfterArgs(EntityManager, user, sharp.ButcherDelayModifier * butcher.ButcherDelay, new SharpDoAfterEvent(), knife, target: target, used: knife)
{
BreakOnTargetMove = true,
BreakOnUserMove = true,
var producing = component.CurrentRecipe ?? component.Queue.FirstOrDefault();
var state = new LatheUpdateState(GetAvailableRecipes(uid, component), component.Queue, producing);
- UserInterfaceSystem.SetUiState(ui, state);
+ _uiSys.SetUiState(ui, state);
}
private void OnGetRecipes(EntityUid uid, TechnologyDatabaseComponent component, LatheGetRecipesEvent args)
}
// removing a working bulb, so require a delay
- _doAfterSystem.TryStartDoAfter(new DoAfterArgs(userUid, light.EjectBulbDelay, new PoweredLightDoAfterEvent(), uid, target: uid)
+ _doAfterSystem.TryStartDoAfter(new DoAfterArgs(EntityManager, userUid, light.EjectBulbDelay, new PoweredLightDoAfterEvent(), uid, target: uid)
{
BreakOnUserMove = true,
BreakOnDamage = true,
private void AttemptLearn(EntityUid uid, SpellbookComponent component, UseInHandEvent args)
{
- var doAfterEventArgs = new DoAfterArgs(args.User, component.LearnTime, new SpellbookDoAfterEvent(), uid, target: uid)
+ var doAfterEventArgs = new DoAfterArgs(EntityManager, args.User, component.LearnTime, new SpellbookDoAfterEvent(), uid, target: uid)
{
BreakOnTargetMove = true,
BreakOnUserMove = true,
private void OnRequestVelocity(GridDragVelocityRequest ev, EntitySessionEventArgs args)
{
+ var grid = GetEntity(ev.Grid);
+
if (args.SenderSession is not IPlayerSession playerSession ||
!_admin.CanCommand(playerSession, CommandName) ||
- !Exists(ev.Grid) ||
- Deleted(ev.Grid)) return;
+ !Exists(grid) ||
+ Deleted(grid))
+ {
+ return;
+ }
- var gridBody = Comp<PhysicsComponent>(ev.Grid);
- _physics.SetLinearVelocity(ev.Grid, ev.LinearVelocity, body: gridBody);
- _physics.SetAngularVelocity(ev.Grid, 0f, body: gridBody);
+ var gridBody = Comp<PhysicsComponent>(grid);
+ _physics.SetLinearVelocity(grid, ev.LinearVelocity, body: gridBody);
+ _physics.SetAngularVelocity(grid, 0f, body: gridBody);
}
private void OnRequestDrag(GridDragRequestPosition msg, EntitySessionEventArgs args)
{
+ var grid = GetEntity(msg.Grid);
+
if (args.SenderSession is not IPlayerSession playerSession ||
!_admin.CanCommand(playerSession, CommandName) ||
- !Exists(msg.Grid) ||
- Deleted(msg.Grid)) return;
+ !Exists(grid) ||
+ Deleted(grid))
+ {
+ return;
+ }
- var gridXform = Transform(msg.Grid);
+ var gridXform = Transform(grid);
gridXform.WorldPosition = msg.WorldPosition;
}
using Content.Shared.CartridgeLoader;
using Content.Shared.CartridgeLoader.Cartridges;
using Content.Server.CartridgeLoader;
+using Content.Server.GameTicking;
using Robust.Shared.Timing;
using Content.Server.Popups;
+using Content.Server.StationRecords.Systems;
using Content.Shared.Database;
+using Robust.Shared.Containers;
+using Robust.Shared.Utility;
namespace Content.Server.MassMedia.Systems;
[Dependency] private readonly IGameTiming _timing = default!;
[Dependency] private readonly UserInterfaceSystem _ui = default!;
[Dependency] private readonly RingerSystem _ringer = default!;
- [Dependency] private readonly CartridgeLoaderSystem? _cartridgeLoaderSystem = default!;
+ [Dependency] private readonly CartridgeLoaderSystem _cartridgeLoaderSystem = default!;
[Dependency] private readonly SharedAudioSystem _audio = default!;
[Dependency] private readonly PopupSystem _popup = default!;
[Dependency] private readonly IAdminLogManager _adminLogger = default!;
-
+ [Dependency] private readonly GameTicker _ticker = default!;
[Dependency] private readonly AccessReaderSystem _accessReader = default!;
+ [Dependency] private readonly StationRecordsSystem _stationRecords = default!;
-
+ // TODO remove this. Dont store data on systems
private readonly List<NewsArticle> _articles = new List<NewsArticle>();
public override void Initialize()
if (message.Action == NewsReadUiAction.NotificationSwith)
component.NotificationOn = !component.NotificationOn;
- UpdateReadUi(uid, args.LoaderUid, component);
+ UpdateReadUi(uid, GetEntity(args.LoaderUid), component);
}
public void OnWriteUiShareMessage(EntityUid uid, NewsWriteComponent component, NewsWriteShareMessage msg)
{
- var article = msg.Article;
+ // dont blindly trust input from clients.
+ if (msg.Session.AttachedEntity is not {} author)
+ return;
+
+ if (!_accessReader.FindAccessItemsInventory(author, out var items))
+ return;
- var author = msg.Session.AttachedEntity;
- if (author.HasValue
- && _accessReader.FindAccessItemsInventory(author.Value, out var items)
- && _accessReader.FindStationRecordKeys(author.Value, out var stationRecordKeys, items))
+ if (!_accessReader.FindStationRecordKeys(author, out var stationRecordKeys, items))
+ return;
+
+ string? authorName = null;
+ foreach (var item in items)
{
- article.AuthorStationRecordKeyIds = stationRecordKeys;
+ // ID Card
+ if (TryComp(item, out IdCardComponent? id))
+ {
+ authorName = id.FullName;
+ break;
+ }
- foreach (var item in items)
+ if (TryComp(item, out PdaComponent? pda)
+ && pda.ContainedId != null
+ && TryComp(pda.ContainedId, out id))
{
- // ID Card
- if (TryComp(item, out IdCardComponent? id))
- {
- article.Author = id.FullName;
- break;
- }
- // PDA
- else if (TryComp(item, out PdaComponent? pda)
- && pda.ContainedId != null
- && TryComp(pda.ContainedId, out id))
- {
- article.Author = id.FullName;
- break;
- }
+ authorName = id.FullName;
+ break;
}
}
- _audio.PlayPvs(component.ConfirmSound, uid);
+ NewsArticle article = new NewsArticle
+ {
+ Author = authorName,
+ Name = (msg.Name.Length <= 25 ? msg.Name.Trim() : $"{msg.Name.Trim().Substring(0, 25)}..."),
+ Content = msg.Content,
+ ShareTime = _ticker.RoundDuration()
- if (author != null)
- _adminLogger.Add(LogType.Chat, LogImpact.Medium, $"{ToPrettyString(author.Value):actor} created news article {article.Name} by {article.Author}: {article.Content}");
- else
- _adminLogger.Add(LogType.Chat, LogImpact.Medium, $"{msg.Session.Name:actor} created news article {article.Name}: {article.Content}");
+ };
+
+ _audio.PlayPvs(component.ConfirmSound, uid);
+ _adminLogger.Add(LogType.Chat, LogImpact.Medium, $"{ToPrettyString(author):actor} created news article {article.Name} by {article.Author}: {article.Content}");
_articles.Add(article);
component.ShareAvalible = false;
private void TryNotify()
{
- var query = EntityQueryEnumerator<CartridgeLoaderComponent, RingerComponent>();
+ var query = EntityQueryEnumerator<CartridgeLoaderComponent, RingerComponent, ContainerManagerComponent>();
- while (query.MoveNext(out var owner, out var comp, out var ringer))
+ while (query.MoveNext(out var uid, out var comp, out var ringer, out var cont))
{
- foreach (var app in comp.InstalledPrograms)
- {
- if (EntityManager.TryGetComponent<NewsReadCartridgeComponent>(app, out var cartridge) && cartridge.NotificationOn)
- {
- _ringer.RingerPlayRingtone(owner, ringer);
- break;
- }
- }
+ if (!_cartridgeLoaderSystem.HasProgram<NewsReadCartridgeComponent>(uid, false, comp, cont))
+ continue;
+
+ _ringer.RingerPlayRingtone(uid, ringer);
+ break;
}
}
{
return true;
}
+
+ var conv = _stationRecords.Convert(articleToDelete.AuthorStationRecordKeyIds);
if (user.HasValue
&& _accessReader.FindStationRecordKeys(user.Value, out var recordKeys)
- && recordKeys.Intersect(articleToDelete.AuthorStationRecordKeyIds).Any())
+ && recordKeys.Intersect(conv).Any())
{
return true;
}
if (!_interaction.InRangeUnobstructed(mech, targetCoords))
return;
- if (!component.ItemContainer.Contains(msg.Item))
+ var item = GetEntity(msg.Item);
+
+ if (!component.ItemContainer.Contains(item))
return;
- RemoveItem(uid, mech, msg.Item, component);
+ RemoveItem(uid, mech, item, component);
}
/// <summary>
component.ItemContainer.Remove(toRemove);
var mechxform = Transform(mech);
var xform = Transform(toRemove);
- xform.AttachToGridOrMap();
+ _transform.AttachToGridOrMap(toRemove, xform);
+ var (mechPos, mechRot) = _transform.GetWorldPositionRotation(mechxform);
- var offset = _transform.GetWorldPosition(mechxform) + _transform.GetWorldRotation(mechxform).RotateVec(component.DepositOffset);
- _transform.SetWorldPosition(xform, offset);
- _transform.SetWorldRotation(xform, Angle.Zero);
+ var offset = mechPos + mechRot.RotateVec(component.DepositOffset);
+ _transform.SetWorldPositionRotation(xform, offset, Angle.Zero);
_mech.UpdateUserInterface(mech);
}
{
var state = new MechGrabberUiState
{
- Contents = component.ItemContainer.ContainedEntities.ToList(),
+ Contents = GetNetEntityList(component.ItemContainer.ContainedEntities.ToList()),
MaxContents = component.MaxContents
};
- args.States.Add(uid, state);
+ args.States.Add(GetNetEntity(uid), state);
}
private void OnInteract(EntityUid uid, MechGrabberComponent component, InteractNoHandEvent args)
args.Handled = true;
component.AudioStream = _audio.PlayPvs(component.GrabSound, uid);
- _doAfter.TryStartDoAfter(new DoAfterArgs(args.User, component.GrabDelay, new GrabberDoAfterEvent(), uid, target: target, used: uid)
+ _doAfter.TryStartDoAfter(new DoAfterArgs(EntityManager, args.User, component.GrabDelay, new GrabberDoAfterEvent(), uid, target: target, used: uid)
{
BreakOnTargetMove = true,
BreakOnUserMove = true
_popup.PopupEntity(Loc.GetString("mech-equipment-begin-install", ("item", uid)), mech);
- var doAfterEventArgs = new DoAfterArgs(args.User, component.InstallDuration, new InsertEquipmentEvent(), uid, target: mech, used: uid)
+ var doAfterEventArgs = new DoAfterArgs(EntityManager, args.User, component.InstallDuration, new InsertEquipmentEvent(), uid, target: mech, used: uid)
{
BreakOnTargetMove = true,
BreakOnUserMove = true
if (TryComp<ToolComponent>(args.Used, out var tool) && tool.Qualities.Contains("Prying") && component.BatterySlot.ContainedEntity != null)
{
- var doAfterEventArgs = new DoAfterArgs(args.User, component.BatteryRemovalDelay, new RemoveBatteryEvent(), uid, target: uid, used: args.Target)
+ var doAfterEventArgs = new DoAfterArgs(EntityManager, args.User, component.BatteryRemovalDelay, new RemoveBatteryEvent(), uid, target: uid, used: args.Target)
{
BreakOnTargetMove = true,
BreakOnUserMove = true,
private void OnRemoveEquipmentMessage(EntityUid uid, MechComponent component, MechEquipmentRemoveMessage args)
{
- if (!Exists(args.Equipment) || Deleted(args.Equipment))
+ var equip = GetEntity(args.Equipment);
+
+ if (!Exists(equip) || Deleted(equip))
return;
- if (!component.EquipmentContainer.ContainedEntities.Contains(args.Equipment))
+ if (!component.EquipmentContainer.ContainedEntities.Contains(equip))
return;
- RemoveEquipment(uid, args.Equipment, component);
+ RemoveEquipment(uid, equip, component);
}
private void OnOpenUi(EntityUid uid, MechComponent component, MechOpenUiEvent args)
Text = Loc.GetString("mech-verb-enter"),
Act = () =>
{
- var doAfterEventArgs = new DoAfterArgs(args.User, component.EntryDelay, new MechEntryEvent(), uid, target: uid)
+ var doAfterEventArgs = new DoAfterArgs(EntityManager, args.User, component.EntryDelay, new MechEntryEvent(), uid, target: uid)
{
BreakOnUserMove = true,
};
return;
}
- var doAfterEventArgs = new DoAfterArgs(args.User, component.ExitDelay, new MechExitEvent(), uid, target: uid)
+ var doAfterEventArgs = new DoAfterArgs(EntityManager, args.User, component.ExitDelay, new MechExitEvent(), uid, target: uid)
{
BreakOnUserMove = true,
BreakOnTargetMove = true,
{
var ev = new MechEquipmentUiMessageRelayEvent(args);
var allEquipment = new List<EntityUid>(component.EquipmentContainer.ContainedEntities);
+ var argEquip = GetEntity(args.Equipment);
+
foreach (var equipment in allEquipment)
{
- if (args.Equipment == equipment)
+ if (argEquip == equipment)
RaiseLocalEvent(equipment, ev);
}
}
EquipmentStates = ev.States
};
var ui = _ui.GetUi(uid, MechUiKey.Key);
- UserInterfaceSystem.SetUiState(ui, state);
+ _ui.SetUiState(ui, state);
}
public override void BreakMech(EntityUid uid, MechComponent? component = null)
if (!HasComp<MobStateComponent>(args.Used) || !CanGib(uid, args.Used, component))
return;
- _doAfterSystem.TryStartDoAfter(new DoAfterArgs(args.User, 7f, new ReclaimerDoAfterEvent(), uid, target: args.Target, used: args.Used)
+ _doAfterSystem.TryStartDoAfter(new DoAfterArgs(EntityManager, args.User, 7f, new ReclaimerDoAfterEvent(), uid, target: args.Target, used: args.Used)
{
BreakOnTargetMove = true,
BreakOnUserMove = true,
// update all sensors info
var allSensors = component.ConnectedSensors.Values.ToList();
- UserInterfaceSystem.SetUiState(bui, new CrewMonitoringState(allSensors, component.Snap, component.Precision));
+ _uiSystem.SetUiState(bui, new CrewMonitoringState(allSensors, component.Snap, component.Precision));
}
}
}
if (cryoPodComponent.BodyContainer.ContainedEntity != null)
return;
- var doAfterArgs = new DoAfterArgs(args.User, cryoPodComponent.EntryDelay, new CryoPodDragFinished(), uid, target: args.Dragged, used: uid)
+ var doAfterArgs = new DoAfterArgs(EntityManager, args.User, cryoPodComponent.EntryDelay, new CryoPodDragFinished(), uid, target: args.Dragged, used: uid)
{
BreakOnDamage = true,
BreakOnTargetMove = true,
_userInterfaceSystem.TrySendUiMessage(
uid,
HealthAnalyzerUiKey.Key,
- new HealthAnalyzerScannedUserMessage(cryoPodComponent.BodyContainer.ContainedEntity,
- temp != null ? temp.CurrentTemperature : 0, bloodstream != null ? bloodstream.BloodSolution.FillFraction : 0));
+ new HealthAnalyzerScannedUserMessage(GetNetEntity(cryoPodComponent.BodyContainer.ContainedEntity),
+ temp?.CurrentTemperature ?? 0, bloodstream != null ? bloodstream.BloodSolution.FillFraction : 0));
}
private void OnInteractUsing(EntityUid uid, CryoPodComponent cryoPodComponent, InteractUsingEvent args)
return false;
_audio.PlayPvs(component.ChargeSound, uid);
- return _doAfter.TryStartDoAfter(new DoAfterArgs(user, component.DoAfterDuration, new DefibrillatorZapDoAfterEvent(),
+ return _doAfter.TryStartDoAfter(new DoAfterArgs(EntityManager, user, component.DoAfterDuration, new DefibrillatorZapDoAfterEvent(),
uid, target, uid)
{
BlockDuplicate = true,
: component.Delay * GetScaledHealingPenalty(user, component);
var doAfterEventArgs =
- new DoAfterArgs(user, delay, new HealingDoAfterEvent(), target, target: target, used: uid)
+ new DoAfterArgs(EntityManager, user, delay, new HealingDoAfterEvent(), target, target: target, used: uid)
{
//Raise the event on the target if it's not self, otherwise raise it on self.
BreakOnUserMove = true,
_audio.PlayPvs(healthAnalyzer.ScanningBeginSound, uid);
- _doAfterSystem.TryStartDoAfter(new DoAfterArgs(args.User, healthAnalyzer.ScanDelay, new HealthAnalyzerDoAfterEvent(), uid, target: args.Target, used: uid)
+ _doAfterSystem.TryStartDoAfter(new DoAfterArgs(EntityManager, args.User, healthAnalyzer.ScanDelay, new HealthAnalyzerDoAfterEvent(), uid, target: args.Target, used: uid)
{
BreakOnTargetMove = true,
BreakOnUserMove = true,
OpenUserInterface(user, healthAnalyzer);
- _uiSystem.SendUiMessage(healthAnalyzer.UserInterface, new HealthAnalyzerScannedUserMessage(target, temp != null ? temp.CurrentTemperature : float.NaN,
+ _uiSystem.SendUiMessage(healthAnalyzer.UserInterface, new HealthAnalyzerScannedUserMessage(GetNetEntity(target), temp != null ? temp.CurrentTemperature : float.NaN,
bloodstream != null ? bloodstream.BloodSolution.FillFraction : float.NaN));
}
}
// construct the doafter and start it
private void StartListening(EntityUid scope, EntityUid user, EntityUid target, StethoscopeComponent comp)
{
- _doAfterSystem.TryStartDoAfter(new DoAfterArgs(user, comp.Delay, new StethoscopeDoAfterEvent(), scope, target: target, used: scope)
+ _doAfterSystem.TryStartDoAfter(new DoAfterArgs(EntityManager, user, comp.Delay, new StethoscopeDoAfterEvent(), scope, target: target, used: scope)
{
BreakOnTargetMove = true,
BreakOnUserMove = true,
totalDamage = damageable.TotalDamage.Int();
// finally, form suit sensor status
- var status = new SuitSensorStatus(uid, userName, userJob);
+ var status = new SuitSensorStatus(GetNetEntity(uid), userName, userJob);
switch (sensor.Mode)
{
case SuitSensorMode.SensorBinary:
coordinates = EntityCoordinates.Invalid;
}
- status.Coordinates = coordinates;
+ status.Coordinates = GetNetCoordinates(coordinates);
break;
}
payload.TryGetValue(SuitSensorConstants.NET_TOTAL_DAMAGE, out int? totalDamage);
payload.TryGetValue(SuitSensorConstants.NET_COORDINATES, out EntityCoordinates? cords);
- var status = new SuitSensorStatus(suitSensorUid, name, job)
+ var status = new SuitSensorStatus(GetNetEntity(suitSensorUid), name, job)
{
IsAlive = isAlive.Value,
TotalDamage = totalDamage,
- Coordinates = cords,
+ Coordinates = GetNetCoordinates(cords),
};
return status;
}
[AdminCommand(AdminFlags.Admin)]
public sealed class MakeSentientCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+
public string Command => "makesentient";
public string Description => "Makes an entity sentient (able to be controlled by a player)";
public string Help => "makesentient <entity id>";
return;
}
- if (!EntityUid.TryParse(args[0], out var entId))
+ if (!NetEntity.TryParse(args[0], out var entNet) || !_entManager.TryGetEntity(entNet, out var entId))
{
shell.WriteLine("Invalid argument.");
return;
}
- var entityManager = IoCManager.Resolve<IEntityManager>();
-
- if (!entityManager.EntityExists(entId))
+ if (!_entManager.EntityExists(entId))
{
shell.WriteLine("Invalid entity specified!");
return;
}
- MakeSentient(entId, entityManager, true, true);
+ MakeSentient(entId.Value, _entManager, true, true);
}
public static void MakeSentient(EntityUid uid, IEntityManager entityManager, bool allowMovement = true, bool allowSpeech = true)
+using System.Diagnostics.CodeAnalysis;
using Content.Server.Access.Systems;
using Content.Server.Administration;
using Content.Server.Administration.Systems;
[AdminCommand(AdminFlags.VarEdit)]
public sealed class RenameCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+ [Dependency] private readonly IPlayerManager _playerManager = default!;
+
public string Command => "rename";
public string Description => "Renames an entity and its cloner entries, ID cards, and PDAs.";
public string Help => "rename <Username|EntityUid> <New character name>";
return;
}
- var entMan = IoCManager.Resolve<IEntityManager>();
-
- if (!TryParseUid(args[0], shell, entMan, out var entityUid))
+ if (!TryParseUid(args[0], shell, _entManager, out var entityUid))
return;
// Metadata
- var metadata = entMan.GetComponent<MetaDataComponent>(entityUid);
+ var metadata = _entManager.GetComponent<MetaDataComponent>(entityUid.Value);
var oldName = metadata.EntityName;
- entMan.System<MetaDataSystem>().SetEntityName(entityUid, name, metadata);
+ _entManager.System<MetaDataSystem>().SetEntityName(entityUid.Value, name, metadata);
- var minds = entMan.System<SharedMindSystem>();
+ var minds = _entManager.System<SharedMindSystem>();
- if (minds.TryGetMind(entityUid, out var mindId, out var mind))
+ if (minds.TryGetMind(entityUid.Value, out var mindId, out var mind))
{
// Mind
mind.CharacterName = name;
}
// Id Cards
- if (entMan.TrySystem<IdCardSystem>(out var idCardSystem))
+ if (_entManager.TrySystem<IdCardSystem>(out var idCardSystem))
{
- if (idCardSystem.TryFindIdCard(entityUid, out var idCard))
+ if (idCardSystem.TryFindIdCard(entityUid.Value, out var idCard))
{
idCardSystem.TryChangeFullName(idCard.Owner, name, idCard);
// Records
// This is done here because ID cards are linked to station records
- if (entMan.TrySystem<StationRecordsSystem>(out var recordsSystem)
- && entMan.TryGetComponent(idCard.Owner, out StationRecordKeyStorageComponent? keyStorage)
+ if (_entManager.TrySystem<StationRecordsSystem>(out var recordsSystem)
+ && _entManager.TryGetComponent(idCard.Owner, out StationRecordKeyStorageComponent? keyStorage)
&& keyStorage.Key != null)
{
- if (recordsSystem.TryGetRecord<GeneralStationRecord>(keyStorage.Key.Value.OriginStation,
+ var origin = keyStorage.Key.Value.OriginStation;
+
+ if (recordsSystem.TryGetRecord<GeneralStationRecord>(origin,
keyStorage.Key.Value,
out var generalRecord))
{
generalRecord.Name = name;
}
- recordsSystem.Synchronize(keyStorage.Key.Value.OriginStation);
+ recordsSystem.Synchronize(origin);
}
}
}
// PDAs
- if (entMan.TrySystem<PdaSystem>(out var pdaSystem))
+ if (_entManager.TrySystem<PdaSystem>(out var pdaSystem))
{
- var query = entMan.EntityQueryEnumerator<PdaComponent>();
+ var query = _entManager.EntityQueryEnumerator<PdaComponent>();
while (query.MoveNext(out var uid, out var pda))
{
if (pda.OwnerName == oldName)
}
// Admin Overlay
- if (entMan.TrySystem<AdminSystem>(out var adminSystem)
- && entMan.TryGetComponent<ActorComponent>(entityUid, out var actorComp))
+ if (_entManager.TrySystem<AdminSystem>(out var adminSystem)
+ && _entManager.TryGetComponent<ActorComponent>(entityUid, out var actorComp))
{
adminSystem.UpdatePlayerList(actorComp.PlayerSession);
}
}
- private static bool TryParseUid(string str, IConsoleShell shell,
- IEntityManager entMan, out EntityUid entityUid)
+ private bool TryParseUid(string str, IConsoleShell shell,
+ IEntityManager entMan, [NotNullWhen(true)] out EntityUid? entityUid)
{
- if (EntityUid.TryParse(str, out entityUid) && entMan.EntityExists(entityUid))
+ if (NetEntity.TryParse(str, out var entityUidNet) && _entManager.TryGetEntity(entityUidNet, out entityUid) && entMan.EntityExists(entityUid))
return true;
- var playerMan = IoCManager.Resolve<IPlayerManager>();
- if (playerMan.TryGetSessionByUsername(str, out var session) && session.AttachedEntity.HasValue)
+ if (_playerManager.TryGetSessionByUsername(str, out var session) && session.AttachedEntity.HasValue)
{
entityUid = session.AttachedEntity.Value;
return true;
shell.WriteError("Can't find username/uid: " + str);
else
shell.WriteError(str + " does not have an entity.");
+
+ entityUid = EntityUid.Invalid;
return false;
}
}
RaiseNetworkEvent(new HTNMessage()
{
- Uid = uid,
+ Uid = GetNetEntity(uid),
Text = text.ToString(),
}, session.ConnectedClient);
}
continue;
}
+ var xform = xformQuery.GetComponent(ent);
+
+ if (xform.ParentUid != grid.Owner ||
+ grid.LocalToTile(xform.Coordinates) != tilePos)
+ {
+ continue;
+ }
+
tileEntities.Add(ent);
}
private DebugPathPoly GetDebugPoly(PathPoly poly)
{
// Create fake neighbors for it
- var neighbors = new List<EntityCoordinates>(poly.Neighbors.Count);
+ var neighbors = new List<NetCoordinates>(poly.Neighbors.Count);
foreach (var neighbor in poly.Neighbors)
{
- neighbors.Add(neighbor.Coordinates);
+ neighbors.Add(GetNetCoordinates(neighbor.Coordinates));
}
return new DebugPathPoly()
{
- GraphUid = poly.GraphUid,
+ GraphUid = GetNetEntity(poly.GraphUid),
ChunkOrigin = poly.ChunkOrigin,
TileIndex = poly.TileIndex,
Box = poly.Box,
foreach (var comp in EntityQuery<GridPathfindingComponent>(true))
{
- msg.Breadcrumbs.Add(comp.Owner, new Dictionary<Vector2i, List<PathfindingBreadcrumb>>(comp.Chunks.Count));
+ var netGrid = GetNetEntity(comp.Owner);
+
+ msg.Breadcrumbs.Add(netGrid, new Dictionary<Vector2i, List<PathfindingBreadcrumb>>(comp.Chunks.Count));
foreach (var chunk in comp.Chunks)
{
var data = GetCrumbs(chunk.Value);
- msg.Breadcrumbs[comp.Owner].Add(chunk.Key, data);
+ msg.Breadcrumbs[netGrid].Add(chunk.Key, data);
}
}
foreach (var comp in EntityQuery<GridPathfindingComponent>(true))
{
- msg.Polys.Add(comp.Owner, new Dictionary<Vector2i, Dictionary<Vector2i, List<DebugPathPoly>>>(comp.Chunks.Count));
+ var netGrid = GetNetEntity(comp.Owner);
+
+ msg.Polys.Add(netGrid, new Dictionary<Vector2i, Dictionary<Vector2i, List<DebugPathPoly>>>(comp.Chunks.Count));
foreach (var chunk in comp.Chunks)
{
var data = GetPolys(chunk.Value);
- msg.Polys[comp.Owner].Add(chunk.Key, data);
+ msg.Polys[netGrid].Add(chunk.Key, data);
}
}
var msg = new PathBreadcrumbsRefreshMessage()
{
Origin = chunk.Origin,
- GridUid = gridUid,
+ GridUid = GetNetEntity(gridUid),
Data = GetCrumbs(chunk),
};
var msg = new PathPolysRefreshMessage()
{
Origin = chunk.Origin,
- GridUid = gridUid,
+ GridUid = GetNetEntity(gridUid),
Polys = data,
};
var (uid, steering, mover, _) = npcs[i];
data.Add(new NPCSteeringDebugData(
- uid,
+ GetNetEntity(uid),
mover.CurTickSprintMovement,
steering.Interest,
steering.Danger,
return;
}
- var doAfterArgs = new DoAfterArgs(uid, comp.DrainTime, new DrainDoAfterEvent(), target: target, eventTarget: uid)
+ var doAfterArgs = new DoAfterArgs(EntityManager, uid, comp.DrainTime, new DrainDoAfterEvent(), target: target, eventTarget: uid)
{
BreakOnUserMove = true,
MovementThreshold = 0.5f,
RaiseNetworkEvent(msg, player.ConnectedClient);
}
- private static NodeVis.GroupData VisMakeGroupState(BaseNodeGroup group)
+ private NodeVis.GroupData VisMakeGroupState(BaseNodeGroup group)
{
return new()
{
Name = n.Name,
NetId = n.NetId,
Reachable = n.ReachableNodes.Select(r => r.NetId).ToArray(),
- Entity = n.Owner,
+ Entity = GetNetEntity(n.Owner),
Type = n.GetType().Name
}).ToArray(),
DebugData = group.GetDebugData()
[Dependency] private readonly IEntityManager _entityManager = default!;
- public SendNukeCodesCommand()
- {
- IoCManager.InjectDependencies(this);
- }
-
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
if (args.Length != 1)
return;
}
- if (!EntityUid.TryParse(args[0], out var uid))
+ if (!NetEntity.TryParse(args[0], out var uidNet) || !_entityManager.TryGetEntity(uidNet, out var uid))
{
shell.WriteError(Loc.GetString("shell-entity-uid-must-be-number"));
return;
}
- _entityManager.System<NukeCodePaperSystem>().SendNukeCodes(uid);
+ _entityManager.System<NukeCodePaperSystem>().SendNukeCodes(uid.Value);
}
public CompletionResult GetCompletion(IConsoleShell shell, string[] args)
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
- EntityUid bombUid;
+ EntityUid? bombUid = null;
NukeComponent? bomb = null;
if (args.Length >= 2)
{
- if (!EntityUid.TryParse(args[1], out bombUid))
+ if (!_entManager.TryParseNetEntity(args[1], out bombUid))
{
shell.WriteError(Loc.GetString("shell-entity-uid-must-be-number"));
return;
{
var query = _entManager.EntityQueryEnumerator<NukeComponent>();
- while (query.MoveNext(out bombUid, out bomb))
+ while (query.MoveNext(out var bomba, out bomb))
{
+ bombUid = bomba;
break;
}
- if (bomb == null)
+ if (bombUid == null)
{
shell.WriteError(Loc.GetString("cmd-nukearm-not-found"));
return;
return;
}
- nukeSys.SetRemainingTime(bombUid, timer, bomb);
+ nukeSys.SetRemainingTime(bombUid.Value, timer, bomb);
}
- nukeSys.ToggleBomb(bombUid, bomb);
+ nukeSys.ToggleBomb(bombUid.Value, bomb);
}
public override CompletionResult GetCompletion(IConsoleShell shell, string[] args)
CooldownTime = (int) component.CooldownTime
};
- UserInterfaceSystem.SetUiState(ui, state);
+ _ui.SetUiState(ui, state);
}
private void PlayNukeKeypadSound(EntityUid uid, int number, NukeComponent? component = null)
private void DisarmBombDoafter(EntityUid uid, EntityUid user, NukeComponent nuke)
{
- var doAfter = new DoAfterArgs(user, nuke.DisarmDoafterLength, new NukeDisarmDoAfterEvent(), uid, target: uid)
+ var doAfter = new DoAfterArgs(EntityManager, user, nuke.DisarmDoafterLength, new NukeDisarmDoAfterEvent(), uid, target: uid)
{
BreakOnDamage = true,
BreakOnTargetMove = true,
var flavors = _flavorProfile.GetLocalizedFlavorsMessage(user, drinkSolution);
- var doAfterEventArgs = new DoAfterArgs(
+ var doAfterEventArgs = new DoAfterArgs(EntityManager,
user,
forceDrink ? drink.ForceFeedDelay : drink.Delay,
new ConsumeDoAfterEvent(drinkSolution.Name, flavors),
_adminLogger.Add(LogType.Ingestion, LogImpact.Low, $"{ToPrettyString(target):target} is eating {ToPrettyString(food):food} {SolutionContainerSystem.ToPrettyString(foodSolution)}");
}
- var doAfterArgs = new DoAfterArgs(
+ var doAfterArgs = new DoAfterArgs(EntityManager,
user,
forceFeed ? foodComp.ForceFeedDelay : foodComp.Delay,
new ConsumeDoAfterEvent(foodSolution.Name, flavors),
if (!exploded)
{
var vapeDoAfterEvent = new VapeDoAfterEvent(solution, forced);
- _doAfterSystem.TryStartDoAfter(new DoAfterArgs(args.User, delay, vapeDoAfterEvent, uid, target: args.Target, used: uid)
+ _doAfterSystem.TryStartDoAfter(new DoAfterArgs(EntityManager, args.User, delay, vapeDoAfterEvent, uid, target: args.Target, used: uid)
{
BreakOnTargetMove = true,
BreakOnUserMove = false,
using Content.Server.Store.Components;
using Content.Server.Store.Systems;
using Content.Shared.Access.Components;
+using Content.Shared.CartridgeLoader;
using Content.Shared.Light.Components;
using Content.Shared.PDA;
using Robust.Server.GameObjects;
protected override void OnItemRemoved(EntityUid uid, PdaComponent pda, EntRemovedFromContainerMessage args)
{
+ if (args.Container.ID != pda.IdSlot.ID && args.Container.ID != pda.PenSlot.ID)
+ return;
+
+ // TODO: This is super cursed just use compstates please.
+ if (MetaData(uid).EntityLifeStage >= EntityLifeStage.Terminating)
+ return;
+
base.OnItemRemoved(uid, pda, args);
UpdatePdaUi(uid, pda);
}
/// <summary>
/// Send new UI state to clients, call if you modify something like uplink.
/// </summary>
- public void UpdatePdaUi(EntityUid uid, PdaComponent pda)
+ public void UpdatePdaUi(EntityUid uid, PdaComponent? pda = null)
{
- if (!_ui.TryGetUi(uid, PdaUiKey.Key, out _))
+ if (!Resolve(uid, ref pda, false))
+ return;
+
+ if (!_ui.TryGetUi(uid, PdaUiKey.Key, out var ui))
return;
var address = GetDeviceNetAddress(uid);
// TODO: Update the level and name of the station with each call to UpdatePdaUi is only needed for latejoin players.
// TODO: If someone can implement changing the level and name of the station when changing the PDA grid, this can be removed.
+ // TODO don't make this depend on cartridge loader!?!?
+ if (!TryComp(uid, out CartridgeLoaderComponent? loader))
+ return;
+
+ var programs = _cartridgeLoader.GetAvailablePrograms(uid, loader);
var id = CompOrNull<IdCardComponent>(pda.ContainedId);
var state = new PdaUpdateState(
+ programs,
+ GetNetEntity(loader.ActiveProgram),
pda.FlashlightOn,
pda.PenSlot.HasItem,
new PdaIdInfoText
hasInstrument,
address);
- _cartridgeLoader?.UpdateUiState(uid, state);
+ _ui.SetUiState(ui, state);
}
private void OnUiMessage(EntityUid uid, PdaComponent pda, PdaRequestUpdateInterfaceMessage msg)
private void UpdateRingerUserInterface(EntityUid uid, RingerComponent ringer)
{
if (_ui.TryGetUi(uid, RingerUiKey.Key, out var bui))
- UserInterfaceSystem.SetUiState(bui, new RingerUpdateState(HasComp<ActiveRingerComponent>(uid), ringer.Ringtone));
+ _ui.SetUiState(bui, new RingerUpdateState(HasComp<ActiveRingerComponent>(uid), ringer.Ringtone));
}
public bool ToggleRingerUI(EntityUid uid, IPlayerSession session)
return;
if (_uiSystem.TryGetUi(uid, PaperUiKey.Key, out var bui))
- UserInterfaceSystem.SetUiState(bui, new PaperBoundUserInterfaceState(paperComp.Content, paperComp.StampedBy, paperComp.Mode), session);
+ _uiSystem.SetUiState(bui, new PaperBoundUserInterfaceState(paperComp.Content, paperComp.StampedBy, paperComp.Mode), session);
}
}
receive = powerConsumer.ReceivedPower;
}
- UserInterfaceSystem.SetUiState(bui, new ParticleAcceleratorUIState(
+ _uiSystem.SetUiState(bui, new ParticleAcceleratorUIState(
comp.Assembled,
comp.Enabled,
comp.SelectedStrength,
private void SendMessage(EntityUid source, IEnumerable<ICommonSession> viewers, EntityUid pointed, string selfMessage,
string viewerMessage, string? viewerPointedAtMessage = null)
{
+ var netSource = GetNetEntity(source);
+
foreach (var viewer in viewers)
{
if (viewer.AttachedEntity is not {Valid: true} viewerEntity)
? viewerPointedAtMessage
: viewerMessage;
- RaiseNetworkEvent(new PopupEntityEvent(message, PopupType.Small, source), viewerEntity);
+ RaiseNetworkEvent(new PopupEntityEvent(message, PopupType.Small, netSource), viewerEntity);
}
- _replay.RecordServerMessage(new PopupEntityEvent(viewerMessage, PopupType.Small, source));
+ _replay.RecordServerMessage(new PopupEntityEvent(viewerMessage, PopupType.Small, netSource));
}
public bool InRange(EntityUid pointer, EntityCoordinates coordinates)
{
if (session?.AttachedEntity is not { } player)
{
- Logger.Warning($"Player {session} attempted to point without any attached entity");
+ Log.Warning($"Player {session} attempted to point without any attached entity");
return false;
}
if (!coords.IsValid(EntityManager))
{
- Logger.Warning($"Player {ToPrettyString(player)} attempted to point at invalid coordinates: {coords}");
+ Log.Warning($"Player {ToPrettyString(player)} attempted to point at invalid coordinates: {coords}");
return false;
}
private void OnPointAttempt(PointingAttemptEvent ev, EntitySessionEventArgs args)
{
- if (TryComp(ev.Target, out TransformComponent? xform))
- TryPoint(args.SenderSession, xform.Coordinates, ev.Target);
+ var target = GetEntity(ev.Target);
+
+ if (TryComp(target, out TransformComponent? xform))
+ TryPoint(args.SenderSession, xform.Coordinates, target);
else
- Logger.Warning($"User {args.SenderSession} attempted to point at a non-existent entity uid: {ev.Target}");
+ Log.Warning($"User {args.SenderSession} attempted to point at a non-existent entity uid: {ev.Target}");
}
public override void Shutdown()
public override void PopupCoordinates(string message, EntityCoordinates coordinates, Filter filter, bool replayRecord, PopupType type = PopupType.Small)
{
- RaiseNetworkEvent(new PopupCoordinatesEvent(message, type, coordinates), filter, replayRecord);
+ RaiseNetworkEvent(new PopupCoordinatesEvent(message, type, GetNetCoordinates(coordinates)), filter, replayRecord);
}
public override void PopupCoordinates(string message, EntityCoordinates coordinates, PopupType type = PopupType.Small)
{
var mapPos = coordinates.ToMap(EntityManager);
var filter = Filter.Empty().AddPlayersByPvs(mapPos, entManager: EntityManager, playerMan: _player, cfgMan: _cfg);
- RaiseNetworkEvent(new PopupCoordinatesEvent(message, type, coordinates), filter);
+ RaiseNetworkEvent(new PopupCoordinatesEvent(message, type, GetNetCoordinates(coordinates)), filter);
}
public override void PopupCoordinates(string message, EntityCoordinates coordinates, ICommonSession recipient, PopupType type = PopupType.Small)
{
- RaiseNetworkEvent(new PopupCoordinatesEvent(message, type, coordinates), recipient);
+ RaiseNetworkEvent(new PopupCoordinatesEvent(message, type, GetNetCoordinates(coordinates)), recipient);
}
public override void PopupCoordinates(string message, EntityCoordinates coordinates, EntityUid recipient, PopupType type = PopupType.Small)
{
if (TryComp(recipient, out ActorComponent? actor))
- RaiseNetworkEvent(new PopupCoordinatesEvent(message, type, coordinates), actor.PlayerSession);
+ RaiseNetworkEvent(new PopupCoordinatesEvent(message, type, GetNetCoordinates(coordinates)), actor.PlayerSession);
}
public override void PopupEntity(string message, EntityUid uid, PopupType type = PopupType.Small)
{
var filter = Filter.Empty().AddPlayersByPvs(uid, entityManager:EntityManager, playerMan: _player, cfgMan: _cfg);
- RaiseNetworkEvent(new PopupEntityEvent(message, type, uid), filter);
+ RaiseNetworkEvent(new PopupEntityEvent(message, type, GetNetEntity(uid)), filter);
}
public override void PopupEntity(string message, EntityUid uid, EntityUid recipient, PopupType type=PopupType.Small)
{
if (TryComp(recipient, out ActorComponent? actor))
- RaiseNetworkEvent(new PopupEntityEvent(message, type, uid), actor.PlayerSession);
+ RaiseNetworkEvent(new PopupEntityEvent(message, type, GetNetEntity(uid)), actor.PlayerSession);
}
public override void PopupClient(string message, EntityUid uid, EntityUid recipient, PopupType type = PopupType.Small)
public override void PopupEntity(string message, EntityUid uid, ICommonSession recipient, PopupType type = PopupType.Small)
{
- RaiseNetworkEvent(new PopupEntityEvent(message, type, uid), recipient);
+ RaiseNetworkEvent(new PopupEntityEvent(message, type, GetNetEntity(uid)), recipient);
}
public override void PopupEntity(string message, EntityUid uid, Filter filter, bool recordReplay, PopupType type = PopupType.Small)
{
- RaiseNetworkEvent(new PopupEntityEvent(message, type, uid), filter, recordReplay);
+ RaiseNetworkEvent(new PopupEntityEvent(message, type, GetNetEntity(uid)), filter, recordReplay);
}
}
}
// Actually set state.
if (_userInterfaceSystem.TryGetUi(target, PowerMonitoringConsoleUiKey.Key, out var bui))
- UserInterfaceSystem.SetUiState(bui, new PowerMonitoringConsoleBoundInterfaceState(totalSources, totalLoads, sources.ToArray(), loads.ToArray()));
+ _userInterfaceSystem.SetUiState(bui, new PowerMonitoringConsoleBoundInterfaceState(totalSources, totalLoads, sources.ToArray(), loads.ToArray()));
}
private int CompareLoadOrSources(PowerMonitoringConsoleEntry x, PowerMonitoringConsoleEntry y)
if (fuelGenerator.On || !Transform(uid).Anchored)
return;
- _doAfter.TryStartDoAfter(new DoAfterArgs(user, component.StartTime, new GeneratorStartedEvent(), uid, uid)
+ _doAfter.TryStartDoAfter(new DoAfterArgs(EntityManager, user, component.StartTime, new GeneratorStartedEvent(), uid, uid)
{
BreakOnDamage = true, BreakOnTargetMove = true, BreakOnUserMove = true, RequireCanInteract = true,
NeedHand = true
[AdminCommand(AdminFlags.Debug)]
public sealed class SetBatteryPercentCommand : IConsoleCommand
{
+ [Dependency] private readonly IEntityManager _entManager = default!;
+
public string Command => "setbatterypercent";
public string Description => "Drains or recharges a battery by entity uid and percentage, i.e.: forall with Battery do setbatterypercent $ID 0";
public string Help => $"{Command} <id> <percent>";
return;
}
- if (!EntityUid.TryParse(args[0], out var id))
+ if (!NetEntity.TryParse(args[0], out var netEnt) || !_entManager.TryGetEntity(netEnt, out var id))
{
shell.WriteLine($"{args[0]} is not a valid entity id.");
return;
return;
}
- var entityManager = IoCManager.Resolve<IEntityManager>();
-
- if (!entityManager.TryGetComponent<BatteryComponent>(id, out var battery))
+ if (!_entManager.TryGetComponent<BatteryComponent>(id, out var battery))
{
shell.WriteLine($"No battery found with id {id}.");
return;
if (component.ImpactEffect != null && TryComp<TransformComponent>(uid, out var xform))
{
- RaiseNetworkEvent(new ImpactEffectEvent(component.ImpactEffect, xform.Coordinates), Filter.Pvs(xform.Coordinates, entityMan: EntityManager));
+ RaiseNetworkEvent(new ImpactEffectEvent(component.ImpactEffect, GetNetCoordinates(xform.Coordinates)), Filter.Pvs(xform.Coordinates, entityMan: EntityManager));
}
}
}
CurrentRadiation = component.CurrentRadiation,
DangerLevel = component.DangerLevel,
IsEnabled = component.IsEnabled,
- User = component.User
+ User = GetNetEntity(component.User)
};
}
if (_debugSessions.Count == 0)
return;
- var query = GetEntityQuery<RadiationGridResistanceComponent>();
- var dict = new Dictionary<EntityUid, Dictionary<Vector2i, float>>();
+ var dict = new Dictionary<NetEntity, Dictionary<Vector2i, float>>();
- var gridQuery = AllEntityQuery<MapGridComponent>();
+ var gridQuery = AllEntityQuery<MapGridComponent, RadiationGridResistanceComponent>();
- while (gridQuery.MoveNext(out var gridUid, out var grid))
+ while (gridQuery.MoveNext(out var gridUid, out _, out var resistance))
{
- if (!query.TryGetComponent(gridUid, out var resistance))
- continue;
-
var resMap = resistance.ResistancePerTile;
- dict.Add(gridUid, resMap);
+ dict.Add(GetNetEntity(gridUid), resMap);
}
var ev = new OnRadiationOverlayResistanceUpdateEvent(dict);
// create a new radiation ray from source to destination
// at first we assume that it doesn't hit any radiation blockers
// and has only distance penalty
- var ray = new RadiationRay(mapId, sourceUid, sourceWorld, destUid, destWorld, rads);
+ var ray = new RadiationRay(mapId, GetNetEntity(sourceUid), sourceWorld, GetNetEntity(destUid), destWorld, rads);
// if source and destination on the same grid it's possible that
// between them can be another grid (ie. shuttle in center of donut station)
// save data for debug if needed
if (saveVisitedTiles && blockers.Count > 0)
- ray.Blockers.Add(gridUid, blockers);
+ ray.Blockers.Add(GetNetEntity(gridUid), blockers);
return ray;
}
ChatChannel.Radio,
message,
wrappedMessage,
- EntityUid.Invalid);
+ NetEntity.Invalid);
var chatMsg = new MsgChatMessage { Message = chat };
var ev = new RadioReceiveEvent(message, messageSource, channel, chatMsg);
if (component.IsEscaping)
return;
- var doAfterEventArgs = new DoAfterArgs(user, component.BaseResistTime * multiplier, new EscapeInventoryEvent(), user, target: container)
+ var doAfterEventArgs = new DoAfterArgs(EntityManager, user, component.BaseResistTime * multiplier, new EscapeInventoryEvent(), user, target: container)
{
BreakOnTargetMove = false,
BreakOnUserMove = true,
if (!Resolve(target, ref storageComponent, ref resistLockerComponent))
return;
- var doAfterEventArgs = new DoAfterArgs(user, resistLockerComponent.ResistTime, new ResistLockerDoAfterEvent(), target, target: target)
+ var doAfterEventArgs = new DoAfterArgs(EntityManager, user, resistLockerComponent.ResistTime, new ResistLockerDoAfterEvent(), target, target: target)
{
BreakOnTargetMove = false,
BreakOnUserMove = true,
private void BeginSoulSearchDoAfter(EntityUid uid, EntityUid target, RevenantComponent revenant)
{
- var searchDoAfter = new DoAfterArgs(uid, revenant.SoulSearchDuration, new SoulEvent(), uid, target: target)
+ var searchDoAfter = new DoAfterArgs(EntityManager, uid, revenant.SoulSearchDuration, new SoulEvent(), uid, target: target)
{
BreakOnUserMove = true,
BreakOnDamage = true,
return;
}
- var doAfter = new DoAfterArgs(uid, revenant.HarvestDebuffs.X, new HarvestEvent(), uid, target: target)
+ var doAfter = new DoAfterArgs(EntityManager, uid, revenant.HarvestDebuffs.X, new HarvestEvent(), uid, target: target)
{
DistanceThreshold = 2,
BreakOnUserMove = true,
!_container.IsEntityOrParentInContainer(component.Beacon.Value, xform: beaconXform))
{
var xform = Transform(uid);
+ var metadata = MetaData(uid);
var oldCoords = xform.Coordinates;
var offset = _random.NextVector2(1.5f);
var localPos = TransformSystem.GetInvWorldMatrix(beaconXform.ParentUid)
RaiseNetworkEvent(new FultonAnimationMessage()
{
- Entity = uid,
- Coordinates = oldCoords,
+ Entity = GetNetEntity(uid, metadata),
+ Coordinates = GetNetCoordinates(oldCoords, metadata),
});
}
else
{
fullState ??= CalculateFullState();
- UserInterfaceSystem.SetUiState(ui, fullState, session);
+ _userInterface.SetUiState(ui, fullState, session);
comp.InitialUIStateSent.Add(session);
}
}
return;
}
- var doAfter = new DoAfterArgs(uid, comp.ProductionLength, new SericultureDoAfterEvent(), uid)
+ var doAfter = new DoAfterArgs(EntityManager, uid, comp.ProductionLength, new SericultureDoAfterEvent(), uid)
{
BreakOnUserMove = true,
BlockDuplicate = true,
return;
}
- if (!EntityUid.TryParse(args[0], out var airlock1))
+ if (!NetEntity.TryParse(args[0], out var airlock1Net) || !_entManager.TryGetEntity(airlock1Net, out var airlock1))
{
shell.WriteError(Loc.GetString("cmd-dock-invalid", ("entity", args[0])));
return;
}
- if (!EntityUid.TryParse(args[1], out var airlock2))
+ if (!NetEntity.TryParse(args[1], out var airlock2Net) || !_entManager.TryGetEntity(airlock2Net, out var airlock2))
{
shell.WriteError(Loc.GetString("cmd-dock-invalid", ("entity", args[1])));
return;
}
var dockSystem = _entManager.System<DockingSystem>();
- dockSystem.Dock(airlock1, dock1, airlock2, dock2);
+ dockSystem.Dock(airlock1.Value, dock1, airlock2.Value, dock2);
if (dock1.DockedWith == airlock2)
{
if ((worldPos - otherWorldPos).Length() < comp.Radius)
continue;
- _sawmill.Debug($"Removed RecentlyDocked from {ToPrettyString(uid)} and {ToPrettyString(comp.LastDocked)}");
+ Log.Debug($"Removed RecentlyDocked from {ToPrettyString(uid)} and {ToPrettyString(comp.LastDocked)}");
RemComp<RecentlyDockedComponent>(uid);
RemComp<RecentlyDockedComponent>(comp.LastDocked);
}
private void OnRequestUndock(EntityUid uid, ShuttleConsoleComponent component, UndockRequestMessage args)
{
- _sawmill.Debug($"Received undock request for {ToPrettyString(args.DockEntity)}");
+ var dork = GetEntity(args.DockEntity);
+
+ Log.Debug($"Received undock request for {ToPrettyString(dork)}");
// TODO: Validation
- if (!TryComp<DockingComponent>(args.DockEntity, out var dock) ||
+ if (!TryComp<DockingComponent>(dork, out var dock) ||
!dock.Docked ||
HasComp<PreventPilotComponent>(Transform(uid).GridUid))
{
return;
}
- Undock(args.DockEntity, dock);
+ Undock(dork, dock);
}
private void OnRequestAutodock(EntityUid uid, ShuttleConsoleComponent component, AutodockRequestMessage args)
{
- _sawmill.Debug($"Received autodock request for {ToPrettyString(args.DockEntity)}");
+ var dork = GetEntity(args.DockEntity);
+ Log.Debug($"Received autodock request for {ToPrettyString(dork)}");
var player = args.Session.AttachedEntity;
if (player == null ||
- !HasComp<DockingComponent>(args.DockEntity) ||
+ !HasComp<DockingComponent>(dork) ||
HasComp<PreventPilotComponent>(Transform(uid).GridUid))
{
return;
}
// TODO: Validation
- var comp = EnsureComp<AutoDockComponent>(args.DockEntity);
+ var comp = EnsureComp<AutoDockComponent>(dork);
comp.Requesters.Add(player.Value);
}
private void OnRequestStopAutodock(EntityUid uid, ShuttleConsoleComponent component, StopAutodockRequestMessage args)
{
- _sawmill.Debug($"Received stop autodock request for {ToPrettyString(args.DockEntity)}");
+ var dork = GetEntity(args.DockEntity);
+ Log.Debug($"Received stop autodock request for {ToPrettyString(dork)}");
var player = args.Session.AttachedEntity;
// TODO: Validation
- if (player == null || !TryComp<AutoDockComponent>(args.DockEntity, out var comp)) return;
+ if (player == null || !TryComp<AutoDockComponent>(dork, out var comp)) return;
comp.Requesters.Remove(player.Value);
if (comp.Requesters.Count == 0)
- RemComp<AutoDockComponent>(args.DockEntity);
+ RemComp<AutoDockComponent>(dork);
}
}
[Dependency] private readonly SharedPhysicsSystem _physics = default!;
[Dependency] private readonly SharedTransformSystem _transform = default!;
- private ISawmill _sawmill = default!;
private const string DockingFixture = "docking";
private const string DockingJoint = "docking";
private const float DockingRadius = 0.20f;
public override void Initialize()
{
base.Initialize();
- _sawmill = Logger.GetSawmill("docking");
SubscribeLocalEvent<DockingComponent, ComponentStartup>(OnStartup);
SubscribeLocalEvent<DockingComponent, ComponentShutdown>(OnShutdown);
SubscribeLocalEvent<DockingComponent, AnchorStateChangedEvent>(OnAnchorChange);
if (otherDockingFixture == null)
{
DebugTools.Assert(false);
- _sawmill.Error($"Found null docking fixture on {ent}");
+ Log.Error($"Found null docking fixture on {ent}");
continue;
}
!TryComp(dockBUid, out DockingComponent? dockB))
{
DebugTools.Assert(false);
- _sawmill.Error($"Tried to cleanup {dockAUid} but not docked?");
+ Log.Error($"Tried to cleanup {dockAUid} but not docked?");
dockA.DockedWith = null;
if (dockA.DockJoint != null)
(dockAUid, dockBUid) = (dockBUid, dockAUid);
}
- _sawmill.Debug($"Docking between {dockAUid} and {dockBUid}");
+ Log.Debug($"Docking between {dockAUid} and {dockBUid}");
// https://gamedev.stackexchange.com/questions/98772/b2distancejoint-with-frequency-equal-to-0-vs-b2weldjoint
}
if (_uiSystem.TryGetUi(uid, EmergencyConsoleUiKey.Key, out var bui))
- UserInterfaceSystem.SetUiState(
+ _uiSystem.SetUiState(
bui,
new EmergencyConsoleBoundUserInterfaceState()
{
RaiseNetworkEvent(new EmergencyShuttlePositionMessage()
{
- StationUid = targetGrid,
+ StationUid = GetNetEntity(targetGrid),
Position = config.Area,
});
}
}
if (_uiSystem.TryGetUi(uid, RadarConsoleUiKey.Key, out var bui))
- UserInterfaceSystem.SetUiState(bui, new RadarConsoleBoundInterfaceState(
+ _uiSystem.SetUiState(bui, new RadarConsoleBoundInterfaceState(
component.MaxRange,
- coordinates,
+ GetNetCoordinates(coordinates),
angle,
new List<DockingInterfaceState>()
));
private void OnDestinationMessage(EntityUid uid, ShuttleConsoleComponent component,
ShuttleConsoleFTLRequestMessage args)
{
- if (!TryComp<FTLDestinationComponent>(args.Destination, out var dest))
+ var destination = GetEntity(args.Destination);
+
+ if (!TryComp<FTLDestinationComponent>(destination, out var dest))
{
return;
}
return;
}
- var dock = HasComp<MapComponent>(args.Destination) && HasComp<MapGridComponent>(args.Destination);
+ var dock = HasComp<MapComponent>(destination) && HasComp<MapGridComponent>(destination);
var tagEv = new FTLTagEvent();
RaiseLocalEvent(xform.GridUid.Value, ref tagEv);
var ev = new ShuttleConsoleFTLTravelStartEvent(uid);
RaiseLocalEvent(ref ev);
- _shuttle.FTLTravel(xform.GridUid.Value, shuttle, args.Destination, dock: dock, priorityTag: tagEv.Tag);
+ _shuttle.FTLTravel(xform.GridUid.Value, shuttle, destination, dock: dock, priorityTag: tagEv.Tag);
}
private void OnDock(DockEvent ev)
private void OnGetState(EntityUid uid, PilotComponent component, ref ComponentGetState args)
{
- args.State = new PilotComponentState(component.Console);
+ args.State = new PilotComponentState(GetNetEntity(component.Console));
}
/// <summary>
var state = new DockingInterfaceState()
{
- Coordinates = xform.Coordinates,
+ Coordinates = GetNetCoordinates(xform.Coordinates),
Angle = xform.LocalRotation,
- Entity = uid,
+ Entity = GetNetEntity(uid),
Connected = comp.Docked,
Color = comp.RadarColor,
HighlightedColor = comp.HighlightedRadarColor,
var shuttleGridUid = consoleXform?.GridUid;
- var destinations = new List<(EntityUid, string, bool)>();
+ var destinations = new List<(NetEntity, string, bool)>();
var ftlState = FTLState.Available;
var ftlTime = TimeSpan.Zero;
canTravel = false;
}
- destinations.Add((destUid, name, canTravel));
+ destinations.Add((GetNetEntity(destUid), name, canTravel));
}
}
docks ??= GetAllDocks();
if (_ui.TryGetUi(consoleUid, ShuttleConsoleUiKey.Key, out var bui))
- UserInterfaceSystem.SetUiState(bui, new ShuttleConsoleBoundInterfaceState(
+ {
+ _ui.SetUiState(bui, new ShuttleConsoleBoundInterfaceState(
ftlState,
ftlTime,
destinations,
range,
- consoleXform?.Coordinates,
+ GetNetCoordinates(consoleXform?.Coordinates),
consoleXform?.LocalRotation,
docks
));
+ }
}
public override void Update(float frameTime)
if (args.Session.AttachedEntity is not { } attachedEntity)
return;
- if (!component.ModuleContainer.Contains(args.Module))
+ var module = GetEntity(args.Module);
+
+ if (!component.ModuleContainer.Contains(module))
return;
_adminLog.Add(LogType.Action, LogImpact.Medium,
- $"{ToPrettyString(attachedEntity):player} removed module {ToPrettyString(args.Module)} from borg {ToPrettyString(uid)}");
- component.ModuleContainer.Remove(args.Module);
- _hands.TryPickupAnyHand(attachedEntity, args.Module);
+ $"{ToPrettyString(attachedEntity):player} removed module {ToPrettyString(module)} from borg {ToPrettyString(uid)}");
+ component.ModuleContainer.Remove(module);
+ _hands.TryPickupAnyHand(attachedEntity, module);
UpdateUI(uid, component);
}
/// <summary>
/// Makes an event horizon consume a given entity.
/// </summary>
- public void ConsumeEntity(EntityUid hungry, EntityUid morsel, EventHorizonComponent eventHorizon, IContainer? outerContainer = null)
+ public void ConsumeEntity(EntityUid hungry, EntityUid morsel, EventHorizonComponent eventHorizon, BaseContainer? outerContainer = null)
{
if (!EntityManager.IsQueuedForDeletion(morsel) // I saw it log twice a few times for some reason?
&& (HasComp<MindContainerComponent>(morsel)
/// <summary>
/// Makes an event horizon attempt to consume a given entity.
/// </summary>
- public bool AttemptConsumeEntity(EntityUid hungry, EntityUid morsel, EventHorizonComponent eventHorizon, IContainer? outerContainer = null)
+ public bool AttemptConsumeEntity(EntityUid hungry, EntityUid morsel, EventHorizonComponent eventHorizon, BaseContainer? outerContainer = null)
{
if (!CanConsumeEntity(hungry, morsel, eventHorizon))
return false;
/// Excludes the event horizon itself.
/// All immune entities within the container will be dumped to a given container or the map/grid if that is impossible.
/// </summary>
- public void ConsumeEntitiesInContainer(EntityUid hungry, IContainer container, EventHorizonComponent eventHorizon, IContainer? outerContainer = null)
+ public void ConsumeEntitiesInContainer(EntityUid hungry, BaseContainer container, EventHorizonComponent eventHorizon, BaseContainer? outerContainer = null)
{
// Removing the immune entities from the container needs to be deferred until after iteration or the iterator raises an error.
List<EntityUid> immune = new();
/// </summary>
[ByRefEvent]
public readonly record struct EntityConsumedByEventHorizonEvent
-(EntityUid entity, EntityUid eventHorizonUid, EventHorizonComponent eventHorizon, IContainer? container)
+(EntityUid entity, EntityUid eventHorizonUid, EventHorizonComponent eventHorizon, BaseContainer? container)
{
/// <summary>
/// The entity being consumed by the event horizon.
/// The innermost container of the entity being consumed by the event horizon that is not also in the process of being consumed by the event horizon.
/// Used to correctly dump out the contents containers that are consumed by the event horizon.
/// </summary>
- public readonly IContainer? Container = container;
+ public readonly BaseContainer? Container = container;
}
/// </summary>
[ByRefEvent]
public readonly record struct EventHorizonConsumedEntityEvent
-(EntityUid entity, EntityUid eventHorizonUid, EventHorizonComponent eventHorizon, IContainer? container)
+(EntityUid entity, EntityUid eventHorizonUid, EventHorizonComponent eventHorizon, BaseContainer? container)
{
/// <summary>
/// The entity being consumed by the event horizon.
/// The innermost container of the entity being consumed by the event horizon that is not also in the process of being consumed by the event horizon.
/// Used to correctly dump out the contents containers that are consumed by the event horizon.
/// </summary>
- public readonly IContainer? Container = container;
+ public readonly BaseContainer? Container = container;
}
}
component.IsSpraying = true;
- var doAfterEventArgs = new DoAfterArgs(args.User, component.AirlockSprayTime, new SprayPainterDoAfterEvent(sprite, null), uid, target: target, used: uid)
+ var doAfterEventArgs = new DoAfterArgs(EntityManager, args.User, component.AirlockSprayTime, new SprayPainterDoAfterEvent(sprite, null), uid, target: target, used: uid)
{
BreakOnTargetMove = true,
BreakOnUserMove = true,
if(!component.ColorPalette.TryGetValue(component.PickedColor, out var color))
return;
- var doAfterEventArgs = new DoAfterArgs(args.User, component.PipeSprayTime, new SprayPainterDoAfterEvent(null, color), uid, target, uid)
+ var doAfterEventArgs = new DoAfterArgs(EntityManager, args.User, component.PipeSprayTime, new SprayPainterDoAfterEvent(null, color), uid, target, uid)
{
BreakOnTargetMove = true,
BreakOnUserMove = true,
private bool _availableJobsDirty;
- private TickerJobsAvailableEvent _cachedAvailableJobs = new (new Dictionary<EntityUid, string>(), new Dictionary<EntityUid, Dictionary<string, uint?>>());
+ private TickerJobsAvailableEvent _cachedAvailableJobs = new (new Dictionary<NetEntity, string>(), new Dictionary<NetEntity, Dictionary<string, uint?>>());
/// <summary>
/// Assembles an event from the current available-to-play jobs.
{
// If late join is disallowed, return no available jobs.
if (_gameTicker.DisallowLateJoin)
- return new TickerJobsAvailableEvent(new Dictionary<EntityUid, string>(), new Dictionary<EntityUid, Dictionary<string, uint?>>());
+ return new TickerJobsAvailableEvent(new Dictionary<NetEntity, string>(), new Dictionary<NetEntity, Dictionary<string, uint?>>());
- var jobs = new Dictionary<EntityUid, Dictionary<string, uint?>>();
- var stationNames = new Dictionary<EntityUid, string>();
+ var jobs = new Dictionary<NetEntity, Dictionary<string, uint?>>();
+ var stationNames = new Dictionary<NetEntity, string>();
var query = EntityQueryEnumerator<StationJobsComponent>();
while (query.MoveNext(out var station, out var comp))
{
+ var netStation = GetNetEntity(station);
var list = comp.JobList.ToDictionary(x => x.Key, x => x.Value);
- jobs.Add(station, list);
- stationNames.Add(station, Name(station));
+ jobs.Add(netStation, list);
+ stationNames.Add(netStation, Name(station));
}
return new TickerJobsAvailableEvent(stationNames, jobs);
}
{
if (e.NewStatus == SessionStatus.Connected)
{
- RaiseNetworkEvent(new StationsUpdatedEvent(GetStationsSet()), e.Session);
+ RaiseNetworkEvent(new StationsUpdatedEvent(GetNetEntitySet(GetStationsSet())), e.Session);
}
}
private void OnStationAdd(EntityUid uid, StationDataComponent component, ComponentStartup args)
{
- RaiseNetworkEvent(new StationsUpdatedEvent(GetStationsSet()), Filter.Broadcast());
+ RaiseNetworkEvent(new StationsUpdatedEvent(GetNetEntitySet(GetStationsSet())), Filter.Broadcast());
var metaData = MetaData(uid);
RaiseLocalEvent(new StationInitializedEvent(uid));
RemComp<StationMemberComponent>(grid);
}
- RaiseNetworkEvent(new StationsUpdatedEvent(GetStationsSet()), Filter.Broadcast());
+ RaiseNetworkEvent(new StationsUpdatedEvent(GetNetEntitySet(GetStationsSet())), Filter.Broadcast());
}
private void OnPreGameMapLoad(PreGameMapLoad ev)
[RegisterComponent]
public sealed partial class GeneralStationRecordConsoleComponent : Component
{
- public StationRecordKey? ActiveKey { get; set; }
+ public (NetEntity, uint)? ActiveKey { get; set; }
public GeneralStationRecordsFilter? Filter { get; set; }
}
// Every single record in this station, by key.
// Essentially a columnar database, but I really suck
// at implementing that so
- [ViewVariables] public readonly StationRecordSet Records = new();
+ [IncludeDataField]
+ public StationRecordSet Records = new();
}
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Content.Shared.StationRecords;
+using Robust.Shared.Utility;
namespace Content.Server.StationRecords;
/// Keyed by StationRecordKey, which should be obtained from
/// an entity that stores a reference to it.
/// </summary>
-public sealed class StationRecordSet
+[DataDefinition]
+public sealed partial class StationRecordSet
{
+ [DataField("currentRecordId")]
private uint _currentRecordId;
- private HashSet<StationRecordKey> _keys = new();
+ // TODO add custom type serializer so that keys don't have to be written twice.
+ [DataField("keys")]
+ public HashSet<StationRecordKey> Keys = new();
+ [DataField("recentlyAccessed")]
private HashSet<StationRecordKey> _recentlyAccessed = new();
- [ViewVariables]
+ [DataField("tables")] // TODO ensure all of this data is serializable.
private Dictionary<Type, Dictionary<StationRecordKey, object>> _tables = new();
/// <summary>
}
/// <summary>
- /// Add a new record into this set of entries.
+ /// Add an entry into a record.
/// </summary>
- /// <param name="station">Station that we're adding the record for.</param>
- /// <returns>A key that represents the record in this set.</returns>
- public StationRecordKey AddRecord(EntityUid station)
+ /// <param name="entry">Entry to add.</param>
+ /// <typeparam name="T">Type of the entry that's being added.</typeparam>
+ public StationRecordKey AddRecordEntry<T>(EntityUid station, T entry)
{
- var key = new StationRecordKey(_currentRecordId++, station);
-
- _keys.Add(key);
+ if (entry == null)
+ return StationRecordKey.Invalid;
+ var key = new StationRecordKey(_currentRecordId++, station);
+ AddRecordEntry(key, entry);
return key;
}
/// <typeparam name="T">Type of the entry that's being added.</typeparam>
public void AddRecordEntry<T>(StationRecordKey key, T entry)
{
- if (!_keys.Contains(key) || entry == null)
- {
+ if (entry == null)
return;
- }
-
- if (!_tables.TryGetValue(typeof(T), out var table))
- {
- table = new();
- _tables.Add(typeof(T), table);
- }
- table.Add(key, entry);
+ if (Keys.Add(key))
+ _tables.GetOrNew(typeof(T))[key] = entry;
}
/// <summary>
{
entry = default;
- if (!_keys.Contains(key)
+ if (!Keys.Contains(key)
|| !_tables.TryGetValue(typeof(T), out var table)
|| !table.TryGetValue(key, out var entryObject))
{
/// <returns>True if the entry exists, false otherwise.</returns>
public bool HasRecordEntry<T>(StationRecordKey key)
{
- return _keys.Contains(key)
+ return Keys.Contains(key)
&& _tables.TryGetValue(typeof(T), out var table)
&& table.ContainsKey(key);
}
/// <returns>True if successful, false otherwise.</returns>
public bool RemoveAllRecords(StationRecordKey key)
{
- if (!_keys.Remove(key))
+ if (!Keys.Remove(key))
{
return false;
}
var consoleRecords =
_stationRecordsSystem.GetRecordsOfType<GeneralStationRecord>(owningStation.Value, stationRecordsComponent);
- var listing = new Dictionary<StationRecordKey, string>();
+ var listing = new Dictionary<(NetEntity, uint), string>();
foreach (var pair in consoleRecords)
{
continue;
}
- listing.Add(pair.Item1, pair.Item2.Name);
+ listing.Add(_stationRecordsSystem.Convert(pair.Item1), pair.Item2.Name);
}
if (listing.Count == 0)
GeneralStationRecord? record = null;
if (console.ActiveKey != null)
{
- _stationRecordsSystem.TryGetRecord(owningStation.Value, console.ActiveKey.Value, out record,
+ _stationRecordsSystem.TryGetRecord(owningStation.Value, _stationRecordsSystem.Convert(console.ActiveKey.Value), out record,
stationRecordsComponent);
}
using System.Diagnostics.CodeAnalysis;
-using System.Linq;
using Content.Server.GameTicking;
-using Content.Server.Station.Systems;
-using Content.Shared.Access.Components;
using Content.Server.Forensics;
using Content.Shared.Inventory;
-using Content.Shared.Nuke;
using Content.Shared.PDA;
using Content.Shared.Preferences;
using Content.Shared.Roles;
/// depend on this general record being created. This is subject
/// to change.
/// </summary>
-public sealed class StationRecordsSystem : EntitySystem
+public sealed class StationRecordsSystem : SharedStationRecordsSystem
{
[Dependency] private readonly InventorySystem _inventorySystem = default!;
[Dependency] private readonly StationRecordKeyStorageSystem _keyStorageSystem = default!;
DNA = dna
};
- var key = AddRecord(station, records);
- AddRecordEntry(key, record, records);
+ var key = AddRecordEntry(station, record);
+ if (!key.IsValid())
+ return;
if (idUid != null)
{
}
}
- RaiseLocalEvent(new AfterGeneralRecordCreatedEvent(key, record, profile));
+ RaiseLocalEvent(new AfterGeneralRecordCreatedEvent(station, key, record, profile));
}
/// <summary>
/// <returns>True if the record was removed, false otherwise.</returns>
public bool RemoveRecord(EntityUid station, StationRecordKey key, StationRecordsComponent? records = null)
{
- if (station != key.OriginStation || !Resolve(station, ref records))
- {
+ if (!Resolve(station, ref records))
return false;
- }
-
- RaiseLocalEvent(new RecordRemovedEvent(key));
+ RaiseLocalEvent(new RecordRemovedEvent(station, key));
return records.Records.RemoveAllRecords(key);
}
{
entry = default;
- if (key.OriginStation != station || !Resolve(station, ref records))
- {
+ if (!Resolve(station, ref records))
return false;
- }
return records.Records.TryGetRecordEntry(key, out entry);
}
return records.Records.GetRecordsOfType<T>();
}
- /// <summary>
- /// Adds a record to a station's record set.
- /// </summary>
- /// <param name="station">The station to add a record to.</param>
- /// <param name="records">Station records component.</param>
- /// <returns>
- /// A station record key, which can be used to add and get records.
- /// </returns>
- /// <exception cref="ArgumentException">
- /// Occurs when the entity given does not have a station records component.
- /// </exception>
- public StationRecordKey AddRecord(EntityUid station, StationRecordsComponent? records)
- {
- if (!Resolve(station, ref records))
- {
- throw new ArgumentException($"Could not retrieve a {nameof(StationRecordsComponent)} from entity {station}");
- }
-
- return records.Records.AddRecord(station);
- }
-
/// <summary>
/// Adds a record entry to a station's record set.
/// </summary>
- /// <param name="key">The key to add the record to.</param>
+ /// <param name="station">The station to add the record to.</param>
/// <param name="record">The record to add.</param>
/// <param name="records">Station records component.</param>
/// <typeparam name="T">The type of record to add.</typeparam>
- public void AddRecordEntry<T>(StationRecordKey key, T record,
+ public StationRecordKey AddRecordEntry<T>(EntityUid station, T record,
StationRecordsComponent? records = null)
{
- if (!Resolve(key.OriginStation, ref records))
- {
- return;
- }
+ if (!Resolve(station, ref records))
+ return StationRecordKey.Invalid;
- records.Records.AddRecordEntry(key, record);
+ return records.Records.AddRecordEntry(station, record);
}
/// <summary>
foreach (var key in records.Records.GetRecentlyAccessed())
{
- RaiseLocalEvent(new RecordModifiedEvent(key));
+ RaiseLocalEvent(new RecordModifiedEvent(station, key));
}
records.Records.ClearRecentlyAccessed();
/// </summary>
public sealed class AfterGeneralRecordCreatedEvent : EntityEventArgs
{
+ public readonly EntityUid Station;
public StationRecordKey Key { get; }
public GeneralStationRecord Record { get; }
/// <summary>
/// </summary>
public HumanoidCharacterProfile? Profile { get; }
- public AfterGeneralRecordCreatedEvent(StationRecordKey key, GeneralStationRecord record, HumanoidCharacterProfile? profile)
+ public AfterGeneralRecordCreatedEvent(EntityUid station, StationRecordKey key, GeneralStationRecord record,
+ HumanoidCharacterProfile? profile)
{
+ Station = station;
Key = key;
Record = record;
Profile = profile;
/// </summary>
public sealed class RecordRemovedEvent : EntityEventArgs
{
+ public readonly EntityUid Station;
public StationRecordKey Key { get; }
- public RecordRemovedEvent(StationRecordKey key)
+ public RecordRemovedEvent(EntityUid station, StationRecordKey key)
{
+ Station = station;
Key = key;
}
}
/// </summary>
public sealed class RecordModifiedEvent : EntityEventArgs
{
+ public readonly EntityUid Station;
public StationRecordKey Key { get; }
- public RecordModifiedEvent(StationRecordKey key)
+ public RecordModifiedEvent(EntityUid station, StationRecordKey key)
{
+ Station = station;
Key = key;
}
}
component.Stick = true;
// start sticking object to target
- _doAfterSystem.TryStartDoAfter(new DoAfterArgs(user, delay, new StickyDoAfterEvent(), uid, target: target, used: uid)
+ _doAfterSystem.TryStartDoAfter(new DoAfterArgs(EntityManager, user, delay, new StickyDoAfterEvent(), uid, target: target, used: uid)
{
BreakOnTargetMove = true,
BreakOnUserMove = true,
component.Stick = false;
// start unsticking object
- _doAfterSystem.TryStartDoAfter(new DoAfterArgs(user, delay, new StickyDoAfterEvent(), uid, target: uid)
+ _doAfterSystem.TryStartDoAfter(new DoAfterArgs(EntityManager, user, delay, new StickyDoAfterEvent(), uid, target: uid)
{
BreakOnTargetMove = true,
BreakOnUserMove = true,
{
EnsureComp<DoAfterComponent>(uid);
- _doAfterSystem.TryStartDoAfter(new DoAfterArgs(uid, component.BehaviorProperties.Delay, new BluespaceLockerDoAfterEvent(), uid));
+ _doAfterSystem.TryStartDoAfter(new DoAfterArgs(EntityManager, uid, component.BehaviorProperties.Delay, new BluespaceLockerDoAfterEvent(), uid));
return;
}
UtilityVerb verb = new()
{
Text = Loc.GetString("storage-component-transfer-verb"),
- IconEntity = args.Using,
+ IconEntity = GetNetEntity(args.Using),
Act = () => TransferEntities(uid, args.Target, component, lockComponent, targetStorage, targetLock)
};
// The last half of the if is because carpets exist and this is terrible
if (storageComp.AreaInsert && (args.Target == null || !HasComp<ItemComponent>(args.Target.Value)))
{
- var validStorables = new List<EntityUid>();
+ var validStorables = new List<NetEntity>();
var itemQuery = GetEntityQuery<ItemComponent>();
foreach (var entity in _entityLookupSystem.GetEntitiesInRange(args.ClickLocation, storageComp.AreaInsertRadius, LookupFlags.Dynamic | LookupFlags.Sundries))
continue;
}
- validStorables.Add(entity);
+ validStorables.Add(GetNetEntity(entity));
}
//If there's only one then let's be generous
if (validStorables.Count > 1)
{
- var doAfterArgs = new DoAfterArgs(args.User, 0.2f * validStorables.Count, new AreaPickupDoAfterEvent(validStorables), uid, target: uid)
+ var doAfterArgs = new DoAfterArgs(EntityManager, args.User, 0.2f * validStorables.Count, new AreaPickupDoAfterEvent(validStorables), uid, target: uid)
{
BreakOnDamage = true,
BreakOnUserMove = true,
if (PlayerInsertEntityInWorld(uid, args.User, target, storageComp))
{
- RaiseNetworkEvent(new AnimateInsertingEntitiesEvent(uid,
- new List<EntityUid> { target },
- new List<EntityCoordinates> { position },
+ RaiseNetworkEvent(new AnimateInsertingEntitiesEvent(GetNetEntity(uid),
+ new List<NetEntity> { GetNetEntity(target) },
+ new List<NetCoordinates> { GetNetCoordinates(position) },
new List<Angle> { transformOwner.LocalRotation }));
}
}
var xformQuery = GetEntityQuery<TransformComponent>();
xformQuery.TryGetComponent(uid, out var xform);
- foreach (var entity in args.Entities)
+ foreach (var nent in args.Entities)
{
+ var entity = GetEntity(nent);
+
// Check again, situation may have changed for some entities, but we'll still pick up any that are valid
if (_containerSystem.IsEntityInContainer(entity)
|| entity == args.Args.User
if (successfullyInserted.Count > 0)
{
_audio.PlayPvs(component.StorageInsertSound, uid);
- RaiseNetworkEvent(new AnimateInsertingEntitiesEvent(uid, successfullyInserted, successfullyInsertedPositions, successfullyInsertedAngles));
+ RaiseNetworkEvent(new AnimateInsertingEntitiesEvent(GetNetEntity(uid), GetNetEntityList(successfullyInserted), GetNetCoordinatesList(successfullyInsertedPositions), successfullyInsertedAngles));
}
args.Handled = true;
if (args.Session.AttachedEntity is not EntityUid player)
return;
- if (!Exists(args.InteractedItemUID))
+ var interacted = GetEntity(args.InteractedItemUID);
+
+ if (!Exists(interacted))
{
- Log.Error($"Player {args.Session} interacted with non-existent item {args.InteractedItemUID} stored in {ToPrettyString(uid)}");
+ Log.Error($"Player {args.Session} interacted with non-existent item {interacted} stored in {ToPrettyString(uid)}");
return;
}
- if (!_actionBlockerSystem.CanInteract(player, args.InteractedItemUID) || storageComp.Storage == null || !storageComp.Storage.Contains(args.InteractedItemUID))
+ if (!_actionBlockerSystem.CanInteract(player, interacted) || storageComp.Storage == null || !storageComp.Storage.Contains(interacted))
return;
// Does the player have hands?
// If the user's active hand is empty, try pick up the item.
if (hands.ActiveHandEntity == null)
{
- if (_sharedHandsSystem.TryPickupAnyHand(player, args.InteractedItemUID, handsComp: hands)
+ if (_sharedHandsSystem.TryPickupAnyHand(player, interacted, handsComp: hands)
&& storageComp.StorageRemoveSound != null)
_audio.Play(storageComp.StorageRemoveSound, Filter.Pvs(uid, entityManager: EntityManager), uid, true, AudioParams.Default);
return;
}
// Else, interact using the held item
- _interactionSystem.InteractUsing(player, hands.ActiveHandEntity.Value, args.InteractedItemUID, Transform(args.InteractedItemUID).Coordinates, checkCanInteract: false);
+ _interactionSystem.InteractUsing(player, hands.ActiveHandEntity.Value, interacted, Transform(interacted).Coordinates, checkCanInteract: false);
}
private void OnInsertItemMessage(EntityUid uid, ServerStorageComponent storageComp, StorageInsertItemMessage args)
if (storageComp.Storage == null)
return;
- var state = new StorageBoundUserInterfaceState((List<EntityUid>) storageComp.Storage.ContainedEntities, storageComp.StorageUsed, storageComp.StorageCapacityMax);
+ var state = new StorageBoundUserInterfaceState(GetNetEntityList(storageComp.Storage.ContainedEntities.ToList()), storageComp.StorageUsed, storageComp.StorageCapacityMax);
var bui = _uiSystem.GetUiOrNull(uid, StorageUiKey.Key);
if (bui != null)
- UserInterfaceSystem.SetUiState(bui, state);
+ _uiSystem.SetUiState(bui, state);
}
private void Popup(EntityUid _, EntityUid player, string message, ServerStorageComponent storageComp)
return;
}
- if (!EntityUid.TryParse(args[0], out var uid) || !float.TryParse(args[2], out var id))
+ if (!NetEntity.TryParse(args[0], out var uidNet) || !TryGetEntity(uidNet, out var uid) || !float.TryParse(args[2], out var id))
+ {
return;
+ }
if (!TryComp<StoreComponent>(uid, out var store))
return;
{ args[1], id }
};
- TryAddCurrency(currency, uid, store);
+ TryAddCurrency(currency, uid.Value, store);
}
private CompletionResult AddCurrencyCommandCompletions(IConsoleShell shell, string[] args)
return CompletionResult.FromHintOptions(allStores, "<uid>");
}
- if (args.Length == 2 && EntityUid.TryParse(args[0], out var uid))
+ if (args.Length == 2 && NetEntity.TryParse(args[0], out var uidNet) && TryGetEntity(uidNet, out var uid))
{
if (TryComp<StoreComponent>(uid, out var store))
return CompletionResult.FromHintOptions(store.CurrencyWhitelist, "<currency prototype>");
// only tell operatives to lock their uplink if it can be locked
var showFooter = HasComp<RingerUplinkComponent>(store);
var state = new StoreUpdateState(component.LastAvailableListings, allCurrency, showFooter);
- UserInterfaceSystem.SetUiState(ui, state);
+ _ui.SetUiState(ui, state);
}
private void OnRequestUpdate(EntityUid uid, StoreComponent component, StoreRequestUpdateInterfaceMessage args)
{
- UpdateUserInterface(args.Session.AttachedEntity, args.Entity, component);
+ UpdateUserInterface(args.Session.AttachedEntity, GetEntity(args.Entity), component);
}
private void BeforeActivatableUiOpen(EntityUid uid, StoreComponent component, BeforeActivatableUIOpenEvent args)
var ui = _ui.GetUiOrNull(uid, StoreUiKey.Key);
if (ui != null)
{
- UserInterfaceSystem.SetUiState(ui, new StoreInitializeState(preset.StoreName));
+ _ui.SetUiState(ui, new StoreInitializeState(preset.StoreName));
}
}
}
var ev = new BeforeGettingStrippedEvent(userEv.Time, userEv.Stealth);
RaiseLocalEvent(target, ev);
- var doAfterArgs = new DoAfterArgs(user, ev.Time, new AwaitedDoAfterEvent(), null, target: target, used: held)
+ var doAfterArgs = new DoAfterArgs(EntityManager, user, ev.Time, new AwaitedDoAfterEvent(), null, target: target, used: held)
{
ExtraCheck = Check,
AttemptFrequency = AttemptFrequency.EveryTick,
var ev = new BeforeGettingStrippedEvent(userEv.Time, userEv.Stealth);
RaiseLocalEvent(target, ev);
- var doAfterArgs = new DoAfterArgs(user, ev.Time, new AwaitedDoAfterEvent(), null, target: target, used: held)
+ var doAfterArgs = new DoAfterArgs(EntityManager, user, ev.Time, new AwaitedDoAfterEvent(), null, target: target, used: held)
{
ExtraCheck = Check,
AttemptFrequency = AttemptFrequency.EveryTick,
var ev = new BeforeGettingStrippedEvent(userEv.Time, userEv.Stealth);
RaiseLocalEvent(target, ev);
- var doAfterArgs = new DoAfterArgs(user, ev.Time, new AwaitedDoAfterEvent(), null, target: target, used: item)
+ var doAfterArgs = new DoAfterArgs(EntityManager, user, ev.Time, new AwaitedDoAfterEvent(), null, target: target, used: item)
{
ExtraCheck = Check,
AttemptFrequency = AttemptFrequency.EveryTick,
var ev = new BeforeGettingStrippedEvent(userEv.Time, userEv.Stealth);
RaiseLocalEvent(target, ev);
- var doAfterArgs = new DoAfterArgs(user, ev.Time, new AwaitedDoAfterEvent(), null, target: target, used: item)
+ var doAfterArgs = new DoAfterArgs(EntityManager, user, ev.Time, new AwaitedDoAfterEvent(), null, target: target, used: item)
{
ExtraCheck = Check,
AttemptFrequency = AttemptFrequency.EveryTick,
return;
}
- IPlayerSession? session = null;
- if (player != null
- && TryComp(player, out ActorComponent? actor))
- {
- session = actor.PlayerSession;
- }
-
- var state = new SurveillanceCameraMonitorUiState(monitor.ActiveCamera, monitor.KnownSubnets.Keys.ToHashSet(), monitor.ActiveCameraAddress, monitor.ActiveSubnet, monitor.KnownCameras);
+ var state = new SurveillanceCameraMonitorUiState(GetNetEntity(monitor.ActiveCamera), monitor.KnownSubnets.Keys.ToHashSet(), monitor.ActiveCameraAddress, monitor.ActiveSubnet, monitor.KnownCameras);
_userInterface.TrySetUiState(uid, SurveillanceCameraMonitorUiKey.Key, state);
}
}
session.Players[player] = new TabletopSessionPlayerData { Camera = camera };
// Tell the gamer to open a viewport for the tabletop game
- RaiseNetworkEvent(new TabletopPlayEvent(uid, camera, Loc.GetString(tabletop.BoardName), tabletop.Size), player.ConnectedClient);
+ RaiseNetworkEvent(new TabletopPlayEvent(GetNetEntity(uid), GetNetEntity(camera), Loc.GetString(tabletop.BoardName), tabletop.Size), player.ConnectedClient);
}
/// <summary>
if (args.SenderSession is not IPlayerSession playerSession)
return;
- if (!TryComp(msg.TableUid, out TabletopGameComponent? tabletop) || tabletop.Session is not { } session)
- return;
+ var table = GetEntity(msg.TableUid);
+ if (!TryComp(table, out TabletopGameComponent? tabletop) || tabletop.Session is not { } session)
+ return;
if (!msg.Entity.IsValid())
return;
- if (!TryComp(msg.Entity, out TabletopHologramComponent? hologram))
+ var entity = GetEntity(msg.Entity);
+
+ if (!TryComp(entity, out TabletopHologramComponent? hologram))
{
- _popupSystem.PopupEntity(Loc.GetString("tabletop-error-remove-non-hologram"), msg.TableUid, args.SenderSession);
+ _popupSystem.PopupEntity(Loc.GetString("tabletop-error-remove-non-hologram"), table, args.SenderSession);
return;
}
return;
// Find the entity, remove it from the session and set it's position to the tabletop
- session.Entities.TryGetValue(msg.Entity, out var result);
+ session.Entities.TryGetValue(entity, out var result);
session.Entities.Remove(result);
_entityManager.QueueDeleteEntity(result);
}
if (args.SenderSession is not IPlayerSession playerSession)
return;
- if (!TryComp(msg.TableUid, out TabletopGameComponent? tabletop) || tabletop.Session is not { } session)
+ if (!TryComp(GetEntity(msg.TableUid), out TabletopGameComponent? tabletop) || tabletop.Session is not { } session)
return;
// Check if player is actually playing at this table
private void OnStopPlaying(TabletopStopPlayingEvent msg, EntitySessionEventArgs args)
{
- CloseSessionFor((IPlayerSession)args.SenderSession, msg.TableUid);
+ CloseSessionFor((IPlayerSession)args.SenderSession, GetEntity(msg.TableUid));
}
private void OnPlayerDetached(EntityUid uid, TabletopGamerComponent component, PlayerDetachedEvent args)
if (xform.ParentUid != xform.GridUid)
return;
- var doafterArgs = new DoAfterArgs(args.User, component.PortalCreationDelay, new TeleporterDoAfterEvent(), uid, used: uid)
+ var doafterArgs = new DoAfterArgs(EntityManager, args.User, component.PortalCreationDelay, new TeleporterDoAfterEvent(), uid, used: uid)
{
BreakOnDamage = true,
BreakOnUserMove = true,
if (args.Cancelled)
return;
- var gridUid = args.Coordinates.GetGridUid(EntityManager);
+ var coords = GetCoordinates(args.Coordinates);
+ var gridUid = coords.GetGridUid(EntityManager);
if (gridUid == null)
return;
var grid = _mapManager.GetGrid(gridUid.Value);
- var tile = grid.GetTileRef(args.Coordinates);
+ var tile = grid.GetTileRef(coords);
if (_tileDefinitionManager[tile.Tile.TypeId] is not ContentTileDefinition tileDef
|| !tileDef.CanWirecutter
|| string.IsNullOrEmpty(tileDef.BaseTurf)
|| _tileDefinitionManager[tileDef.BaseTurf] is not ContentTileDefinition newDef
|| tile.IsBlockedTurf(true))
+ {
return false;
+ }
- var ev = new LatticeCuttingCompleteEvent(coordinates);
+ var ev = new LatticeCuttingCompleteEvent(GetNetCoordinates(coordinates));
return UseTool(toolEntity, user, toolEntity, component.Delay, component.QualityNeeded, ev);
}
}
if (args.Cancelled)
return;
- var gridUid = args.Coordinates.GetGridUid(EntityManager);
+ var coords = GetCoordinates(args.Coordinates);
+ var gridUid = coords.GetGridUid(EntityManager);
if (!_mapManager.TryGetGrid(gridUid, out var grid))
{
Log.Error("Attempted to pry from a non-existent grid?");
return;
}
- var tile = grid.GetTileRef(args.Coordinates);
+ var tile = grid.GetTileRef(coords);
var center = _turf.GetTileCenter(tile);
if (args.Used != null)
{
if (!tileDef.CanCrowbar && !(tileDef.CanAxe && component.Advanced))
return false;
- var ev = new TilePryingDoAfterEvent(coordinates);
+ var ev = new TilePryingDoAfterEvent(GetNetCoordinates(coordinates));
return UseTool(toolEntity, user, toolEntity, component.Delay, component.QualityNeeded, ev, toolComponent: tool);
}
private SharedVerbSystem? _verb;
[CommandImplementation]
- public IEnumerable<EntityUid> RunVerbAs(
+ public IEnumerable<NetEntity> RunVerbAs(
[CommandInvocationContext] IInvocationContext ctx,
- [PipedArgument] IEnumerable<EntityUid> input,
- [CommandArgument] ValueRef<EntityUid> runner,
+ [PipedArgument] IEnumerable<NetEntity> input,
+ [CommandArgument] ValueRef<NetEntity> runner,
[CommandArgument] string verb
)
{
foreach (var i in input)
{
- var runnerEid = runner.Evaluate(ctx);
+ var runnerNet = runner.Evaluate(ctx);
+ var runnerEid = EntityManager.GetEntity(runnerNet);
-
- if (EntityManager.Deleted(runnerEid) && runnerEid != default)
+ if (EntityManager.Deleted(runnerEid) && runnerEid.IsValid())
ctx.ReportError(new DeadEntity(runnerEid));
if (ctx.GetErrors().Any())
yield break;
- var verbs = _verb.GetLocalVerbs(i, runnerEid, Verb.VerbTypes, true);
+ var eId = EntityManager.GetEntity(i);
+ var verbs = _verb.GetLocalVerbs(eId, runnerEid, Verb.VerbTypes, true);
// if the "verb name" is actually a verb-type, try run any verb of that type.
var verbType = Verb.VerbTypes.FirstOrDefault(x => x.Name == verb);
var verbTy = verbs.FirstOrDefault(v => v.GetType() == verbType);
if (verbTy != null)
{
- _verb.ExecuteVerb(verbTy, runnerEid, i, forced: true);
+ _verb.ExecuteVerb(verbTy, runnerEid, eId, forced: true);
yield return i;
}
}
{
if (verbTy.Text.ToLowerInvariant() == verb)
{
- _verb.ExecuteVerb(verbTy, runnerEid, i, forced: true);
+ _verb.ExecuteVerb(verbTy, runnerEid, eId, forced: true);
yield return i;
}
}
}
var ui = new ToolshedVisualizeEui(
- input.Select(e => (EntName(e), e)).ToArray()
+ input.Select(e => (EntName(e), EntityManager.GetNetEntity(e))).ToArray()
);
_euiManager.OpenEui(ui, (IPlayerSession) ctx.Session);
_euiManager.QueueStateUpdate(ui);
}
internal sealed class ToolshedVisualizeEui : BaseEui
{
- private readonly (string name, EntityUid entity)[] _entities;
+ private readonly (string name, NetEntity entity)[] _entities;
- public ToolshedVisualizeEui((string name, EntityUid entity)[] entities)
+ public ToolshedVisualizeEui((string name, NetEntity entity)[] entities)
{
_entities = entities;
}
{
var player = (IPlayerSession) eventArgs.SenderSession;
- if (!EntityManager.EntityExists(args.EntityUid))
+ if (!EntityManager.EntityExists(GetEntity(args.EntityUid)))
{
- Logger.Warning($"{nameof(HandleVerbRequest)} called on a non-existent entity with id {args.EntityUid} by player {player}.");
+ Log.Warning($"{nameof(HandleVerbRequest)} called on a non-existent entity with id {args.EntityUid} by player {player}.");
return;
}
if (player.AttachedEntity is not {} attached)
{
- Logger.Warning($"{nameof(HandleVerbRequest)} called by player {player} with no attached entity.");
+ Log.Warning($"{nameof(HandleVerbRequest)} called by player {player} with no attached entity.");
return;
}
if (type != null)
verbTypes.Add(type);
else
- Logger.Error($"Unknown verb type received: {key}");
+ Log.Error($"Unknown verb type received: {key}");
}
var response =
- new VerbsResponseEvent(args.EntityUid, GetLocalVerbs(args.EntityUid, attached, verbTypes, force));
+ new VerbsResponseEvent(args.EntityUid, GetLocalVerbs(GetEntity(args.EntityUid), attached, verbTypes, force));
RaiseNetworkEvent(response, player.ConnectedClient);
}
}
if (_uiSystem.TryGetUi(owner, VoiceMaskUIKey.Key, out var bui))
- UserInterfaceSystem.SetUiState(bui, new VoiceMaskBuiState(component.VoiceName));
+ _uiSystem.SetUiState(bui, new VoiceMaskBuiState(component.VoiceName));
}
}
return false;
}
- var target = ev.Target!.Value;
+ var target = GetEntity(ev.Target!.Value);
- if (!TryComp<HandsComponent>(ev.Target.Value, out var targetHandsComponent))
+ if (!TryComp<HandsComponent>(target, out var targetHandsComponent))
{
- if (!TryComp<StatusEffectsComponent>(ev.Target!.Value, out var status) || !status.AllowedEffects.Contains("KnockedDown"))
+ if (!TryComp<StatusEffectsComponent>(target, out var status) || !status.AllowedEffects.Contains("KnockedDown"))
return false;
}
- if (!InRange(user, ev.Target.Value, component.Range, session))
+ if (!InRange(user, target, component.Range, session))
{
return false;
}
inTargetHand = targetHandsComponent.ActiveHand.HeldEntity!.Value;
}
- Interaction.DoContactInteraction(user, ev.Target);
+ Interaction.DoContactInteraction(user, target);
var attemptEvent = new DisarmAttemptEvent(target, user, inTargetHand);
filter = Filter.Pvs(user, entityManager: EntityManager);
}
- RaiseNetworkEvent(new MeleeLungeEvent(user, angle, localPos, animation), filter);
+ RaiseNetworkEvent(new MeleeLungeEvent(GetNetEntity(user), angle, localPos, animation), filter);
}
private void OnSpeechHit(EntityUid owner, MeleeSpeechComponent comp, MeleeHitEvent args)
// Lord
// Forgive me for the shitcode I am about to do
// Effects tempt me not
- var sprites = new List<(EntityCoordinates coordinates, Angle angle, SpriteSpecifier sprite, float scale)>();
+ var sprites = new List<(NetCoordinates coordinates, Angle angle, SpriteSpecifier sprite, float scale)>();
var gridUid = fromCoordinates.GetGridUid(EntityManager);
var angle = mapDirection;
{
if (hitscan.MuzzleFlash != null)
{
- sprites.Add((fromCoordinates.Offset(angle.ToVec().Normalized() / 2), angle, hitscan.MuzzleFlash, 1f));
+ var coords = fromCoordinates.Offset(angle.ToVec().Normalized() / 2);
+ var netCoords = GetNetCoordinates(coords);
+
+ sprites.Add((netCoords, angle, hitscan.MuzzleFlash, 1f));
}
if (hitscan.TravelFlash != null)
{
- sprites.Add((fromCoordinates.Offset(angle.ToVec() * (distance + 0.5f) / 2), angle, hitscan.TravelFlash, distance - 1.5f));
+ var coords = fromCoordinates.Offset(angle.ToVec() * (distance + 0.5f) / 2);
+ var netCoords = GetNetCoordinates(coords);
+
+ sprites.Add((netCoords, angle, hitscan.TravelFlash, distance - 1.5f));
}
}
if (hitscan.ImpactFlash != null)
{
- sprites.Add((fromCoordinates.Offset(angle.ToVec() * distance), angle.FlipPositive(), hitscan.ImpactFlash, 1f));
+ var coords = fromCoordinates.Offset(angle.ToVec() * distance);
+ var netCoords = GetNetCoordinates(coords);
+
+ sprites.Add((netCoords, angle.FlipPositive(), hitscan.ImpactFlash, 1f));
}
if (sprites.Count > 0)
if (_toolTime > 0f)
{
- var args = new DoAfterArgs(user, _toolTime, new WireDoAfterEvent(action, id), target, target: target, used: toolEntity)
+ var args = new DoAfterArgs(EntityManager, user, _toolTime, new WireDoAfterEvent(action, id), target, target: target, used: toolEntity)
{
NeedHand = true,
BreakOnDamage = true,
var scanning = TryComp<ActiveArtifactAnalyzerComponent>(component.AnalyzerEntity, out var active);
var remaining = active != null ? _timing.CurTime - active.StartTime : TimeSpan.Zero;
- var state = new AnalysisConsoleScanUpdateState(artifact, analyzerConnected, serverConnected,
+ var state = new AnalysisConsoleScanUpdateState(GetNetEntity(artifact), analyzerConnected, serverConnected,
canScan, canPrint, msg, scanning, remaining, totalTime, points);
var bui = _ui.GetUi(uid, ArtifactAnalzyerUiKey.Key);
- UserInterfaceSystem.SetUiState(bui, state);
+ _ui.SetUiState(bui, state);
}
/// <summary>
if (args.Length != 2)
shell.WriteError("Argument length must be 2");
- if (!EntityUid.TryParse(args[0], out var uid) || ! int.TryParse(args[1], out var id))
+ if (!NetEntity.TryParse(args[0], out var uidNet) || !TryGetEntity(uidNet, out var uid) || !int.TryParse(args[1], out var id))
return;
if (!TryComp<ArtifactComponent>(uid, out var artifact))
if (artifact.NodeTree.FirstOrDefault(n => n.Id == id) is { } node)
{
- EnterNode(uid, ref node);
+ EnterNode(uid.Value, ref node);
}
}
private CompletionResult ForceArtifactNodeCompletions(IConsoleShell shell, string[] args)
{
- if (args.Length == 2 && EntityUid.TryParse(args[0], out var uid))
+ if (args.Length == 2 && NetEntity.TryParse(args[0], out var uidNet) && TryGetEntity(uidNet, out var uid))
{
if (TryComp<ArtifactComponent>(uid, out var artifact))
{
if (args.Length != 1)
shell.WriteError("Argument length must be 1");
- if (!EntityUid.TryParse(args[0], out var uid))
+ if (!NetEntity.TryParse(args[0], out var uidNet) || !TryGetEntity(uidNet, out var uid))
return;
if (!TryComp<ArtifactComponent>(uid, out var artifact))
return;
- var pointSum = GetResearchPointValue(uid, artifact, true);
- shell.WriteLine($"Max point value for {ToPrettyString(uid)} with {artifact.NodeTree.Count} nodes: {pointSum}");
+ var pointSum = GetResearchPointValue(uid.Value, artifact, true);
+ shell.WriteLine($"Max point value for {ToPrettyString(uid.Value)} with {artifact.NodeTree.Count} nodes: {pointSum}");
}
}
public List<HashSet<string>> AccessLists;
- public HashSet<StationRecordKey> AccessKeys;
+ public List<(NetEntity, uint)> AccessKeys;
- public AccessReaderComponentState(bool enabled, HashSet<string> denyTags, List<HashSet<string>> accessLists, HashSet<StationRecordKey> accessKeys)
+ public AccessReaderComponentState(bool enabled, HashSet<string> denyTags, List<HashSet<string>> accessLists, List<(NetEntity, uint)> accessKeys)
{
Enabled = enabled;
DenyTags = denyTags;
[Dependency] private readonly InventorySystem _inventorySystem = default!;
[Dependency] private readonly SharedHandsSystem _handsSystem = default!;
[Dependency] private readonly SharedContainerSystem _containerSystem = default!;
+ [Dependency] private readonly SharedStationRecordsSystem _records = default!;
public override void Initialize()
{
private void OnGetState(EntityUid uid, AccessReaderComponent component, ref ComponentGetState args)
{
args.State = new AccessReaderComponentState(component.Enabled, component.DenyTags, component.AccessLists,
- component.AccessKeys);
+ _records.Convert(component.AccessKeys));
}
private void OnHandleState(EntityUid uid, AccessReaderComponent component, ref ComponentHandleState args)
if (args.Current is not AccessReaderComponentState state)
return;
component.Enabled = state.Enabled;
- component.AccessKeys = new(state.AccessKeys);
+ component.AccessKeys.Clear();
+ foreach (var key in state.AccessKeys)
+ {
+ var id = EnsureEntity<AccessReaderComponent>(key.Item1, uid);
+ if (!id.IsValid())
+ continue;
+
+ component.AccessKeys.Add(new StationRecordKey(key.Item2, id));
+ }
+
component.AccessLists = new(state.AccessLists);
component.DenyTags = new(state.DenyTags);
}
[Serializable, NetSerializable]
public sealed class RequestPerformActionEvent : EntityEventArgs
{
- public readonly EntityUid Action;
- public readonly EntityUid? EntityTarget;
- public readonly EntityCoordinates? EntityCoordinatesTarget;
+ public readonly NetEntity Action;
+ public readonly NetEntity? EntityTarget;
+ public readonly NetCoordinates? EntityCoordinatesTarget;
- public RequestPerformActionEvent(EntityUid action)
+ public RequestPerformActionEvent(NetEntity action)
{
Action = action;
}
- public RequestPerformActionEvent(EntityUid action, EntityUid entityTarget)
+ public RequestPerformActionEvent(NetEntity action, NetEntity entityTarget)
{
Action = action;
EntityTarget = entityTarget;
}
- public RequestPerformActionEvent(EntityUid action, EntityCoordinates entityCoordinatesTarget)
+ public RequestPerformActionEvent(NetEntity action, NetCoordinates entityCoordinatesTarget)
{
Action = action;
EntityCoordinatesTarget = entityCoordinatesTarget;
[Serializable, NetSerializable]
public sealed class ActionsComponentState : ComponentState
{
- public readonly HashSet<EntityUid> Actions;
+ public readonly HashSet<NetEntity> Actions;
- public ActionsComponentState(HashSet<EntityUid> actions)
+ public ActionsComponentState(HashSet<NetEntity> actions)
{
Actions = actions;
}
public (TimeSpan Start, TimeSpan End)? Cooldown;
public TimeSpan? UseDelay;
public int? Charges;
- public EntityUid? Provider;
- public EntityUid? EntityIcon;
+ public NetEntity? Provider;
+ public NetEntity? EntityIcon;
public bool CheckCanInteract;
public bool ClientExclusive;
public int Priority;
- public EntityUid? AttachedEntity;
+ public NetEntity? AttachedEntity;
public bool AutoPopulate;
public bool AutoRemove;
public bool Temporary;
public ItemActionIconStyle ItemIconStyle;
public SoundSpecifier? Sound;
- protected BaseActionComponentState(BaseActionComponent component)
+ protected BaseActionComponentState(BaseActionComponent component, IEntityManager entManager)
{
Icon = component.Icon;
IconOn = component.IconOn;
Cooldown = component.Cooldown;
UseDelay = component.UseDelay;
Charges = component.Charges;
- Provider = component.Provider;
- EntityIcon = component.EntityIcon;
+
+ // TODO ACTION REFACTOR fix bugs
+ if (entManager.TryGetNetEntity(component.Provider, out var provider))
+ Provider = provider;
+ if (entManager.TryGetNetEntity(component.EntityIcon, out var icon))
+ EntityIcon = icon;
+ if (entManager.TryGetNetEntity(component.AttachedEntity, out var attached))
+ AttachedEntity = attached;
+
CheckCanInteract = component.CheckCanInteract;
ClientExclusive = component.ClientExclusive;
Priority = component.Priority;
- AttachedEntity = component.AttachedEntity;
AutoPopulate = component.AutoPopulate;
AutoRemove = component.AutoRemove;
Temporary = component.Temporary;
public EntityWhitelist? Whitelist;
public bool CanTargetSelf;
- public EntityTargetActionComponentState(EntityTargetActionComponent component) : base(component)
+ public EntityTargetActionComponentState(EntityTargetActionComponent component, IEntityManager entManager) : base(component, entManager)
{
Whitelist = component.Whitelist;
CanTargetSelf = component.CanTargetSelf;
[Serializable, NetSerializable]
public sealed class InstantActionComponentState : BaseActionComponentState
{
- public InstantActionComponentState(InstantActionComponent component) : base(component)
+ public InstantActionComponentState(InstantActionComponent component, IEntityManager entManager) : base(component, entManager)
{
}
}
private void OnInstantGetState(EntityUid uid, InstantActionComponent component, ref ComponentGetState args)
{
- args.State = new InstantActionComponentState(component);
+ args.State = new InstantActionComponentState(component, EntityManager);
}
private void OnEntityTargetGetState(EntityUid uid, EntityTargetActionComponent component, ref ComponentGetState args)
{
- args.State = new EntityTargetActionComponentState(component);
+ args.State = new EntityTargetActionComponentState(component, EntityManager);
}
private void OnWorldTargetGetState(EntityUid uid, WorldTargetActionComponent component, ref ComponentGetState args)
{
- args.State = new WorldTargetActionComponentState(component);
+ args.State = new WorldTargetActionComponentState(component, EntityManager);
}
- private void BaseHandleState(BaseActionComponent component, BaseActionComponentState state)
+ private void BaseHandleState<T>(EntityUid uid, BaseActionComponent component, BaseActionComponentState state) where T : BaseActionComponent
{
component.Icon = state.Icon;
component.IconOn = state.IconOn;
component.Cooldown = state.Cooldown;
component.UseDelay = state.UseDelay;
component.Charges = state.Charges;
- component.Provider = state.Provider;
- component.EntityIcon = state.EntityIcon;
+ component.Provider = EnsureEntity<T>(state.Provider, uid);
+ component.EntityIcon = EnsureEntity<T>(state.EntityIcon, uid);
component.CheckCanInteract = state.CheckCanInteract;
component.ClientExclusive = state.ClientExclusive;
component.Priority = state.Priority;
- component.AttachedEntity = state.AttachedEntity;
+ component.AttachedEntity = EnsureEntity<T>(state.AttachedEntity, uid);
component.AutoPopulate = state.AutoPopulate;
component.AutoRemove = state.AutoRemove;
component.Temporary = state.Temporary;
if (args.Current is not InstantActionComponentState state)
return;
- BaseHandleState(component, state);
+ BaseHandleState<InstantActionComponent>(uid, component, state);
}
private void OnEntityTargetHandleState(EntityUid uid, EntityTargetActionComponent component, ref ComponentHandleState args)
if (args.Current is not EntityTargetActionComponentState state)
return;
- BaseHandleState(component, state);
+ BaseHandleState<EntityTargetActionComponent>(uid, component, state);
component.Whitelist = state.Whitelist;
component.CanTargetSelf = state.CanTargetSelf;
}
if (args.Current is not WorldTargetActionComponentState state)
return;
- BaseHandleState(component, state);
+ BaseHandleState<WorldTargetActionComponent>(uid, component, state);
}
private void OnGetActionData<T>(EntityUid uid, T component, ref GetActionDataEvent args) where T : BaseActionComponent
protected bool TryGetContainer(
EntityUid holderId,
- [NotNullWhen(true)] out IContainer? container,
+ [NotNullWhen(true)] out BaseContainer? container,
ContainerManagerComponent? containerManager = null)
{
return _containerSystem.TryGetContainer(holderId, ActionContainerId, out container, containerManager);
protected bool TryGetProvidedContainer(
EntityUid providerId,
- [NotNullWhen(true)] out IContainer? container,
+ [NotNullWhen(true)] out BaseContainer? container,
ContainerManagerComponent? containerManager = null)
{
return _containerSystem.TryGetContainer(providerId, ProvidedActionContainerId, out container, containerManager);
if (action.AttachedEntity == null)
return;
- if (!TryComp(action.AttachedEntity, out ActionsComponent? comp))
+ var ent = action.AttachedEntity;
+
+ if (!TryComp(ent, out ActionsComponent? comp))
{
action.AttachedEntity = null;
return;
private void OnActionsGetState(EntityUid uid, ActionsComponent component, ref ComponentGetState args)
{
- args.State = new ActionsComponentState(component.Actions);
+ args.State = new ActionsComponentState(GetNetEntitySet(component.Actions));
}
private void OnActionsShutdown(EntityUid uid, ActionsComponent component, ComponentShutdown args)
if (!TryComp(user, out ActionsComponent? component))
return;
- if (!TryComp(ev.Action, out MetaDataComponent? metaData))
+ var actionEnt = GetEntity(ev.Action);
+
+ if (!TryComp(actionEnt, out MetaDataComponent? metaData))
return;
- var name = Name(ev.Action, metaData);
+ var name = Name(actionEnt, metaData);
// Does the user actually have the requested action?
- if (!component.Actions.Contains(ev.Action))
+ if (!component.Actions.Contains(actionEnt))
{
_adminLogger.Add(LogType.Action,
$"{ToPrettyString(user):user} attempted to perform an action that they do not have: {name}.");
return;
}
- var action = GetActionData(ev.Action);
+ var action = GetActionData(actionEnt);
if (action == null || !action.Enabled)
return;
switch (action)
{
case EntityTargetActionComponent entityAction:
- if (ev.EntityTarget is not { Valid: true } entityTarget)
+ if (ev.EntityTarget is not { Valid: true } netTarget)
{
Log.Error($"Attempted to perform an entity-targeted action without a target! Action: {name}");
return;
}
+ var entityTarget = GetEntity(netTarget);
+
var targetWorldPos = _transformSystem.GetWorldPosition(entityTarget);
_rotateToFaceSystem.TryFaceCoordinates(user, targetWorldPos);
if (entityAction.Event != null)
{
entityAction.Event.Target = entityTarget;
- Dirty(ev.Action, entityAction);
+ Dirty(actionEnt, entityAction);
performEvent = entityAction.Event;
}
break;
case WorldTargetActionComponent worldAction:
- if (ev.EntityCoordinatesTarget is not { } entityCoordinatesTarget)
+ if (ev.EntityCoordinatesTarget is not { } netCoordinatesTarget)
{
Log.Error($"Attempted to perform a world-targeted action without a target! Action: {name}");
return;
}
+ var entityCoordinatesTarget = GetCoordinates(netCoordinatesTarget);
_rotateToFaceSystem.TryFaceCoordinates(user, entityCoordinatesTarget.Position);
if (!ValidateWorldTarget(user, entityCoordinatesTarget, worldAction))
if (worldAction.Event != null)
{
worldAction.Event.Target = entityCoordinatesTarget;
- Dirty(ev.Action, worldAction);
+ Dirty(actionEnt, worldAction);
performEvent = worldAction.Event;
}
performEvent.Performer = user;
// All checks passed. Perform the action!
- PerformAction(user, component, ev.Action, action, performEvent, curTime);
+ PerformAction(user, component, actionEnt, action, performEvent, curTime);
}
public bool ValidateEntityTarget(EntityUid user, EntityUid target, EntityTargetActionComponent action)
{
// This here is required because of client-side prediction (RaisePredictiveEvent results in event re-use).
actionEvent.Handled = false;
+ var provider = action.Provider;
- if (action.Provider == null)
+ if (provider == null)
RaiseLocalEvent(performer, (object) actionEvent, broadcast: true);
else
- RaiseLocalEvent(action.Provider.Value, (object) actionEvent, broadcast: true);
+ RaiseLocalEvent(provider.Value, (object) actionEvent, broadcast: true);
handled = actionEvent.Handled;
}
/// <param name="holder">Component of <see cref="holderId"/></param>
/// <param name="action">Component of <see cref="actionId"/></param>
/// <param name="actionContainer">Action container of <see cref="holderId"/></param>
- public virtual void AddAction(EntityUid holderId, EntityUid actionId, EntityUid? provider, ActionsComponent? holder = null, BaseActionComponent? action = null, bool dirty = true, IContainer? actionContainer = null)
+ public virtual void AddAction(EntityUid holderId, EntityUid actionId, EntityUid? provider, ActionsComponent? holder = null, BaseActionComponent? action = null, bool dirty = true, BaseContainer? actionContainer = null)
{
action ??= GetActionData(actionId);
// TODO remove when action subscriptions are split up
Dirty(holderId, holder);
}
- protected virtual void AddActionInternal(EntityUid holderId, EntityUid actionId, IContainer container, ActionsComponent holder)
+ protected virtual void AddActionInternal(EntityUid holderId, EntityUid actionId, BaseContainer container, ActionsComponent holder)
{
container.Insert(actionId);
holder.Actions.Add(actionId);
[Serializable, NetSerializable]
public sealed class WorldTargetActionComponentState : BaseActionComponentState
{
- public WorldTargetActionComponentState(WorldTargetActionComponent component) : base(component)
+ public WorldTargetActionComponentState(WorldTargetActionComponent component, IEntityManager entManager) : base(component, entManager)
{
}
}
[Serializable, NetSerializable]
public sealed class EditSolutionsEuiState : EuiStateBase
{
- public readonly EntityUid Target;
+ public readonly NetEntity Target;
public readonly Dictionary<string, Solution>? Solutions;
- public EditSolutionsEuiState(EntityUid target, Dictionary<string, Solution>? solutions)
+ public EditSolutionsEuiState(NetEntity target, Dictionary<string, Solution>? solutions)
{
Target = target;
Solutions = solutions;
string IdentityName,
string StartingJob,
bool Antag,
- EntityUid? EntityUid,
+ NetEntity? NetEntity,
NetUserId SessionId,
bool Connected,
bool ActiveThisRound);
[Serializable, NetSerializable]
public sealed class SetOutfitEuiState : EuiStateBase
{
- public EntityUid TargetEntityId;
+ public NetEntity TargetNetEntity;
}
}
public sealed class GasAnalyzerUserMessage : BoundUserInterfaceMessage
{
public string DeviceName;
- public EntityUid DeviceUid;
+ public NetEntity DeviceUid;
public bool DeviceFlipped;
public string? Error;
public GasMixEntry[] NodeGasMixes;
- public GasAnalyzerUserMessage(GasMixEntry[] nodeGasMixes, string deviceName, EntityUid deviceUid, bool deviceFlipped, string? error = null)
+ public GasAnalyzerUserMessage(GasMixEntry[] nodeGasMixes, string deviceName, NetEntity deviceUid, bool deviceFlipped, string? error = null)
{
NodeGasMixes = nodeGasMixes;
DeviceName = deviceName;
[Serializable, NetSerializable]
public sealed class AtmosDebugOverlayMessage : EntityEventArgs
{
- public EntityUid GridId { get; }
+ public NetEntity GridId { get; }
public Vector2i BaseIdx { get; }
// LocalViewRange*LocalViewRange
public AtmosDebugOverlayData[] OverlayData { get; }
- public AtmosDebugOverlayMessage(EntityUid gridIndices, Vector2i baseIdx, AtmosDebugOverlayData[] overlayData)
+ public AtmosDebugOverlayMessage(NetEntity gridIndices, Vector2i baseIdx, AtmosDebugOverlayData[] overlayData)
{
GridId = gridIndices;
BaseIdx = baseIdx;
[Serializable, NetSerializable]
public sealed class GasOverlayUpdateEvent : EntityEventArgs
{
- public Dictionary<EntityUid, List<GasOverlayChunk>> UpdatedChunks = new();
- public Dictionary<EntityUid, HashSet<Vector2i>> RemovedChunks = new();
+ public Dictionary<NetEntity, List<GasOverlayChunk>> UpdatedChunks = new();
+ public Dictionary<NetEntity, HashSet<Vector2i>> RemovedChunks = new();
}
}
}
[Serializable, NetSerializable]
public sealed class BeamVisualizerEvent : EntityEventArgs
{
- public readonly EntityUid Beam;
+ public readonly NetEntity Beam;
public readonly float DistanceLength;
public readonly Angle UserAngle;
public readonly string? BodyState;
public readonly string Shader = "unshaded";
- public BeamVisualizerEvent(EntityUid beam, float distanceLength, Angle userAngle, string? bodyState = null, string shader = "unshaded")
+ public BeamVisualizerEvent(NetEntity beam, float distanceLength, Angle userAngle, string? bodyState = null, string shader = "unshaded")
{
Beam = beam;
DistanceLength = distanceLength;
[Serializable, NetSerializable]
public sealed class OrganComponentState : ComponentState
{
- public readonly EntityUid? Body;
+ public readonly NetEntity? Body;
public readonly OrganSlot? Parent;
- public OrganComponentState(EntityUid? body, OrganSlot? parent)
+ public OrganComponentState(NetEntity? body, OrganSlot? parent)
{
Body = body;
Parent = parent;
[Serializable, NetSerializable]
[Access(typeof(SharedBodySystem))]
-[DataRecord]
-public sealed record OrganSlot(string Id, EntityUid Parent)
+[DataDefinition]
+public sealed partial record OrganSlot
{
- public EntityUid? Child { get; set; }
+ [DataField("id")]
+ public string Id = string.Empty;
+
+ [NonSerialized]
+ [DataField("parent")]
+ public EntityUid Parent;
+
+ public NetEntity NetParent;
+
+ [NonSerialized]
+ [DataField("child")]
+ public EntityUid? Child;
+
+ public NetEntity? NetChild;
// Rider doesn't suggest explicit properties during deconstruction without this
public void Deconstruct(out EntityUid? child, out string id, out EntityUid parent)
[Serializable, NetSerializable]
public sealed class BodyPartComponentState : ComponentState
{
- public readonly EntityUid? Body;
+ public readonly NetEntity? Body;
public readonly BodyPartSlot? ParentSlot;
public readonly Dictionary<string, BodyPartSlot> Children;
public readonly Dictionary<string, OrganSlot> Organs;
public readonly BodyPartSymmetry Symmetry;
public BodyPartComponentState(
- EntityUid? body,
+ NetEntity? body,
BodyPartSlot? parentSlot,
Dictionary<string, BodyPartSlot> children,
Dictionary<string, OrganSlot> organs,
[Serializable, NetSerializable]
[Access(typeof(SharedBodySystem))]
-[DataRecord]
-public sealed record BodyPartSlot(string Id, EntityUid Parent, BodyPartType? Type)
+[DataDefinition]
+public sealed partial record BodyPartSlot
{
- public EntityUid? Child { get; set; }
+ [DataField("id")]
+ public string Id = string.Empty;
+
+ [DataField("type")]
+ public BodyPartType? Type;
+
+ [NonSerialized]
+ [DataField("parent")]
+ public EntityUid Parent;
+
+ public NetEntity NetParent;
+
+ [NonSerialized]
+ [DataField("child")]
+ public EntityUid? Child;
+
+ public NetEntity? NetChild;
+
+ public void SetChild(EntityUid? child, NetEntity? netChild)
+ {
+ Child = child;
+ NetChild = netChild;
+ }
// Rider doesn't suggest explicit properties during deconstruction without this
public void Deconstruct(out EntityUid? child, out string id, out EntityUid parent, out BodyPartType? type)
var prototype = Prototypes.Index<BodyPrototype>(body.Prototype);
- if (!_netManager.IsClient || bodyId.IsClientSide())
+ if (!_netManager.IsClient || IsClientSide(bodyId))
InitBody(body, prototype);
Dirty(body); // Client doesn't actually spawn the body, need to sync it
body.Root != null)
return false;
- slot = new BodyPartSlot(slotId, bodyId.Value, null);
+ slot = new BodyPartSlot
+ {
+ Id = slotId,
+ Parent = bodyId.Value,
+ NetParent = GetNetEntity(bodyId.Value),
+ };
body.Root = slot;
return true;
return;
var bodyId = Spawn(root.Part, body.Owner.ToCoordinates());
var partComponent = Comp<BodyPartComponent>(bodyId);
- var slot = new BodyPartSlot(root.Part, body.Owner, partComponent.PartType);
+ var slot = new BodyPartSlot
+ {
+ Id = root.Part,
+ Type = partComponent.PartType,
+ Parent = body.Owner,
+ NetParent = GetNetEntity(body.Owner),
+ };
body.Root = slot;
partComponent.Body = bodyId;
public partial class SharedBodySystem
{
+ [Dependency] private readonly SharedContainerSystem _container = default!;
+
private void InitializeOrgans()
{
SubscribeLocalEvent<OrganComponent, ComponentGetState>(OnOrganGetState);
if (!Resolve(parent, ref part, false))
return null;
- var slot = new OrganSlot(slotId, parent);
+ var slot = new OrganSlot()
+ {
+ Id = slotId,
+ Parent = parent,
+ NetParent = GetNetEntity(parent),
+ };
part.Organs.Add(slotId, slot);
return slot;
slot.Child == null &&
Resolve(organId.Value, ref organ, false) &&
Containers.TryGetContainer(slot.Parent, BodyContainerId, out var container) &&
- container.CanInsert(organId.Value);
+ _container.CanInsert(organId.Value, container);
}
private void OnOrganGetState(EntityUid uid, OrganComponent organ, ref ComponentGetState args)
{
- args.State = new OrganComponentState(organ.Body, organ.ParentSlot);
+ args.State = new OrganComponentState(GetNetEntity(organ.Body), organ.ParentSlot);
}
private void OnOrganHandleState(EntityUid uid, OrganComponent organ, ref ComponentHandleState args)
if (args.Current is not OrganComponentState state)
return;
- organ.Body = state.Body;
+ organ.Body = EnsureEntity<OrganComponent>(state.Body, uid);
organ.ParentSlot = state.Parent;
}
private void OnPartGetState(EntityUid uid, BodyPartComponent part, ref ComponentGetState args)
{
args.State = new BodyPartComponentState(
- part.Body,
+ GetNetEntity(part.Body),
part.ParentSlot,
part.Children,
part.Organs,
if (args.Current is not BodyPartComponentState state)
return;
- part.Body = state.Body;
+ part.Body = EnsureEntity<BodyPartComponent>(state.Body, uid);
part.ParentSlot = state.ParentSlot; // TODO use containers. This is broken and does not work.
part.Children = state.Children; // TODO use containers. This is broken and does not work.
part.Organs = state.Organs; // TODO end my suffering.
{
if (part.ParentSlot is { } slot)
{
- slot.Child = null;
+ slot.SetChild(null, GetNetEntity(null));
DirtyAllComponents(slot.Parent);
}
if (!Resolve(parent, ref part, false))
return null;
- var slot = new BodyPartSlot(slotId, parent, partType);
+ var slot = new BodyPartSlot
+ {
+ Id = slotId,
+ Type = partType,
+ Parent = parent,
+ NetParent = GetNetEntity(parent),
+ };
part.Children.Add(slotId, slot);
return slot;
!Resolve(parentId.Value, ref parent, false))
return false;
- slot = new BodyPartSlot(id, parentId.Value, null);
+ slot = new BodyPartSlot
+ {
+ Id = id,
+ Parent = parentId.Value,
+ NetParent = GetNetEntity(parentId.Value),
+ };
if (!parent.Children.TryAdd(id, slot))
{
slot = null;
Resolve(partId.Value, ref part, false) &&
(slot.Type == null || slot.Type == part.PartType) &&
Containers.TryGetContainer(slot.Parent, BodyContainerId, out var container) &&
- container.CanInsert(partId.Value);
+ _container.CanInsert(partId.Value, container);
}
public virtual bool AttachPart(
if (!container.Insert(partId.Value))
return false;
- slot.Child = partId;
+ slot.SetChild(partId, GetNetEntity(partId));
part.ParentSlot = slot;
if (TryComp(slot.Parent, out BodyPartComponent? parentPart))
var oldBodyNullable = part.Body;
- slot.Child = null;
+ slot.SetChild(null, null);
part.ParentSlot = null;
part.Body = null;
[Serializable, NetSerializable]
public sealed class ToolshedVisualizeEuiState : EuiStateBase
{
- public readonly (string name, EntityUid entity)[] Entities;
+ public readonly (string name, NetEntity entity)[] Entities;
- public ToolshedVisualizeEuiState((string name, EntityUid entity)[] entities)
+ public ToolshedVisualizeEuiState((string name, NetEntity entity)[] entities)
{
Entities = entities;
}
[Serializable, NetSerializable]
public sealed class BuckleComponentState : ComponentState
{
- public BuckleComponentState(bool buckled, EntityUid? buckledTo, EntityUid? lastEntityBuckledTo,
+ public BuckleComponentState(bool buckled, NetEntity? buckledTo, NetEntity? lastEntityBuckledTo,
bool dontCollide)
{
Buckled = buckled;
}
public readonly bool Buckled;
- public readonly EntityUid? BuckledTo;
- public readonly EntityUid? LastEntityBuckledTo;
+ public readonly NetEntity? BuckledTo;
+ public readonly NetEntity? LastEntityBuckledTo;
public readonly bool DontCollide;
}
public readonly StrapPosition Position;
public readonly float MaxBuckleDistance;
public readonly Vector2 BuckleOffsetClamped;
- public readonly HashSet<EntityUid> BuckledEntities;
+ public readonly HashSet<NetEntity> BuckledEntities;
public readonly int OccupiedSize;
- public StrapComponentState(StrapPosition position, Vector2 offset, HashSet<EntityUid> buckled,
+ public StrapComponentState(StrapPosition position, Vector2 offset, HashSet<NetEntity> buckled,
float maxBuckleDistance, int occupiedSize)
{
Position = position;
private void OnBuckleComponentGetState(EntityUid uid, BuckleComponent component, ref ComponentGetState args)
{
- args.State = new BuckleComponentState(component.Buckled, component.BuckledTo, component.LastEntityBuckledTo, component.DontCollide);
+ args.State = new BuckleComponentState(component.Buckled, GetNetEntity(component.BuckledTo), GetNetEntity(component.LastEntityBuckledTo), component.DontCollide);
}
private void OnBuckleMove(EntityUid uid, BuckleComponent component, ref MoveEvent ev)
private void OnStrapGetState(EntityUid uid, StrapComponent component, ref ComponentGetState args)
{
- args.State = new StrapComponentState(component.Position, component.BuckleOffset, component.BuckledEntities, component.MaxBuckleDistance, component.OccupiedSize);
+ args.State = new StrapComponentState(component.Position, component.BuckleOffset, GetNetEntitySet(component.BuckledEntities), component.MaxBuckleDistance, component.OccupiedSize);
}
private void OnStrapHandleState(EntityUid uid, StrapComponent component, ref ComponentHandleState args)
component.Position = state.Position;
component.BuckleOffsetUnclamped = state.BuckleOffsetClamped;
component.BuckledEntities.Clear();
- component.BuckledEntities.UnionWith(state.BuckledEntities);
+ component.BuckledEntities.UnionWith(EnsureEntitySet<StrapComponent>(state.BuckledEntities, uid));
component.MaxBuckleDistance = state.MaxBuckleDistance;
component.OccupiedSize = state.OccupiedSize;
}
[NetSerializable]
public sealed class CameraKickEvent : EntityEventArgs
{
- public readonly EntityUid Euid;
+ public readonly NetEntity NetEntity;
public readonly Vector2 Recoil;
- public CameraKickEvent(EntityUid euid, Vector2 recoil)
+ public CameraKickEvent(NetEntity netEntity, Vector2 recoil)
{
Recoil = recoil;
- Euid = euid;
+ NetEntity = netEntity;
}
}
[Serializable, NetSerializable]
public sealed class PlayBoxEffectMessage : EntityEventArgs
{
- public EntityUid Source;
- public EntityUid Mover;
+ public NetEntity Source;
+ public NetEntity Mover;
- public PlayBoxEffectMessage(EntityUid source, EntityUid mover)
+ public PlayBoxEffectMessage(NetEntity source, NetEntity mover)
{
Source = source;
Mover = mover;
/// <summary>
/// List of programs that come preinstalled with this cartridge loader
/// </summary>
- [DataField("preinstalled")]
+ [DataField("preinstalled")] // TODO remove this and use container fill.
public List<string> PreinstalledPrograms = new();
/// <summary>
[ViewVariables]
public readonly List<EntityUid> BackgroundPrograms = new();
- /// <summary>
- /// The list of program entities that are spawned into the cartridge loaders program container
- /// </summary>
- [DataField("installedCartridges")]
- public List<EntityUid> InstalledPrograms = new();
-
/// <summary>
/// The maximum amount of programs that can be installed on the cartridge loader entity
/// </summary>
[Serializable, NetSerializable]
public sealed class CartridgeLoaderUiMessage : BoundUserInterfaceMessage
{
- public readonly EntityUid CartridgeUid;
+ public readonly NetEntity CartridgeUid;
public readonly CartridgeUiMessageAction Action;
- public CartridgeLoaderUiMessage(EntityUid cartridgeUid, CartridgeUiMessageAction action)
+ public CartridgeLoaderUiMessage(NetEntity cartridgeUid, CartridgeUiMessageAction action)
{
CartridgeUid = cartridgeUid;
Action = action;
[Serializable, NetSerializable]
public class CartridgeLoaderUiState : BoundUserInterfaceState
{
- public EntityUid? ActiveUI;
- public List<EntityUid> Programs = new();
+ public NetEntity? ActiveUI;
+ public List<NetEntity> Programs;
+
+ public CartridgeLoaderUiState(List<NetEntity> programs, NetEntity? activeUI)
+ {
+ Programs = programs;
+ ActiveUI = activeUI;
+ }
}
[Serializable, NetSerializable]
public abstract class CartridgeMessageEvent : EntityEventArgs
{
- public EntityUid LoaderUid;
+ public NetEntity LoaderUid;
}
[Serializable, NetSerializable]
public sealed class NotekeeperUiState : BoundUserInterfaceState
{
- public List<String> Notes;
+ public List<string> Notes;
public NotekeeperUiState(List<string> notes)
{
using Robust.Shared.Containers;
using Robust.Shared.GameStates;
using Robust.Shared.Map;
+using Robust.Shared.Network;
namespace Content.Shared.CartridgeLoader;
public abstract class SharedCartridgeLoaderSystem : EntitySystem
{
+ public const string InstalledContainerId = "program-container";
+
[Dependency] private readonly ItemSlotsSystem _itemSlotsSystem = default!;
[Dependency] private readonly SharedAppearanceSystem _appearanceSystem = default!;
+ [Dependency] private readonly SharedContainerSystem _container = default!;
+ [Dependency] private readonly INetManager _netMan = default!;
public override void Initialize()
{
private void OnComponentRemove(EntityUid uid, CartridgeLoaderComponent loader, ComponentRemove args)
{
_itemSlotsSystem.RemoveItemSlot(uid, loader.CartridgeSlot);
-
- foreach (var program in loader.InstalledPrograms)
- {
- EntityManager.QueueDeleteEntity(program);
- }
+ if (_container.TryGetContainer(uid, InstalledContainerId, out var cont))
+ cont.Shutdown(EntityManager, _netMan);
}
protected virtual void OnItemInserted(EntityUid uid, CartridgeLoaderComponent loader, EntInsertedIntoContainerMessage args)
[Serializable, NetSerializable]
public sealed class RequestCharacterInfoEvent : EntityEventArgs
{
- public readonly EntityUid EntityUid;
+ public readonly NetEntity NetEntity;
- public RequestCharacterInfoEvent(EntityUid entityUid)
+ public RequestCharacterInfoEvent(NetEntity netEntity)
{
- EntityUid = entityUid;
+ NetEntity = netEntity;
}
}
[Serializable, NetSerializable]
public sealed class CharacterInfoEvent : EntityEventArgs
{
- public readonly EntityUid EntityUid;
+ public readonly NetEntity NetEntity;
public readonly string JobTitle;
public readonly Dictionary<string, List<ConditionInfo>> Objectives;
public readonly string? Briefing;
- public CharacterInfoEvent(EntityUid entityUid, string jobTitle, Dictionary<string, List<ConditionInfo>> objectives, string? briefing)
+ public CharacterInfoEvent(NetEntity netEntity, string jobTitle, Dictionary<string, List<ConditionInfo>> objectives, string? briefing)
{
- EntityUid = entityUid;
+ NetEntity = netEntity;
JobTitle = jobTitle;
Objectives = objectives;
Briefing = briefing;
public ChatChannel Channel;
public string Message;
public string WrappedMessage;
- public EntityUid SenderEntity;
+ public NetEntity SenderEntity;
public bool HideChat;
public Color? MessageColorOverride;
public string? AudioPath;
[NonSerialized]
public bool Read;
- public ChatMessage(ChatChannel channel, string message, string wrappedMessage, EntityUid source, bool hideChat = false, Color? colorOverride = null, string? audioPath = null, float audioVolume = 0)
+ public ChatMessage(ChatChannel channel, string message, string wrappedMessage, NetEntity source, bool hideChat = false, Color? colorOverride = null, string? audioPath = null, float audioVolume = 0)
{
Channel = channel;
Message = message;
if (args.Handled || !HasComp<ClumsyComponent>(args.Dragged))
return;
- var doAfterArgs = new DoAfterArgs(args.Dragged, component.BonkDelay, new BonkDoAfterEvent(), uid, target: uid)
+ var doAfterArgs = new DoAfterArgs(EntityManager, args.Dragged, component.BonkDelay, new BonkDoAfterEvent(), uid, target: uid)
{
BreakOnTargetMove = true,
BreakOnUserMove = true,
var (time, stealth) = _strippable.GetStripTimeModifiers(user, wearer, (float) component.StripDelay.Value.TotalSeconds);
- var args = new DoAfterArgs(user, time, new ToggleClothingDoAfterEvent(), item, wearer, item)
+ var args = new DoAfterArgs(EntityManager, user, time, new ToggleClothingDoAfterEvent(), item, wearer, item)
{
BreakOnDamage = true,
BreakOnTargetMove = true,
/// <summary>
/// Position to start building.
/// </summary>
- public readonly EntityCoordinates Location;
+ public readonly NetCoordinates Location;
/// <summary>
/// The construction prototype to start building.
/// <summary>
/// Identifier to be sent back in the acknowledgement so that the client can clean up its ghost.
/// </summary>
+ /// <remarks>
+ /// So essentially the client is sending its own entity to the server so it knows to delete it when it gets server
+ /// response back.
+ /// </remarks>
public readonly int Ack;
- public TryStartStructureConstructionMessage(EntityCoordinates loc, string prototypeName, Angle angle, int ack)
+ public TryStartStructureConstructionMessage(NetCoordinates loc, string prototypeName, Angle angle, int ack)
{
Location = loc;
PrototypeName = prototypeName;
/// <summary>
/// The entity that is now being constructed, if any.
/// </summary>
- public readonly EntityUid? Uid;
+ public readonly NetEntity? Uid;
- public AckStructureConstructionMessage(int ghostId, EntityUid? uid = null)
+ public AckStructureConstructionMessage(int ghostId, NetEntity? uid = null)
{
GhostId = ghostId;
Uid = uid;
public sealed partial class ConstructionInteractDoAfterEvent : DoAfterEvent
{
[DataField("clickLocation")]
- public EntityCoordinates ClickLocation;
+ public NetCoordinates ClickLocation;
private ConstructionInteractDoAfterEvent()
{
}
- public ConstructionInteractDoAfterEvent(InteractUsingEvent ev)
+ public ConstructionInteractDoAfterEvent(IEntityManager entManager, InteractUsingEvent ev)
{
- ClickLocation = ev.ClickLocation;
+ ClickLocation = entManager.GetNetCoordinates(ev.ClickLocation);
}
public override DoAfterEvent Clone() => this;
/// </remarks>
public bool CanInsert(EntityUid uid, EntityUid usedUid, EntityUid? user, ItemSlot slot, bool swap = false, EntityUid? popup = null)
{
+ if (slot.ContainerSlot == null)
+ return false;
+
if (slot.Locked)
return false;
if (ev.Cancelled)
return false;
- return slot.ContainerSlot?.CanInsertIfEmpty(usedUid, EntityManager) ?? false;
+ return _containers.CanInsert(usedUid, slot.ContainerSlot, assumeEmpty: true);
}
/// <summary>
public bool CanEject(EntityUid uid, EntityUid? user, ItemSlot slot)
{
- if (slot.Locked || slot.Item == null)
+ if (slot.Locked || slot.ContainerSlot?.ContainedEntity is not {} item)
return false;
- var ev = new ItemSlotEjectAttemptEvent(uid, slot.Item.Value, user, slot);
+ var ev = new ItemSlotEjectAttemptEvent(uid, item, user, slot);
RaiseLocalEvent(uid, ref ev);
- RaiseLocalEvent(slot.Item.Value, ref ev);
+ RaiseLocalEvent(item, ref ev);
if (ev.Cancelled)
return false;
- return slot.ContainerSlot?.CanRemove(slot.Item.Value, EntityManager) ?? false;
+ return _containers.CanRemove(item, slot.ContainerSlot);
}
/// <summary>
var verbSubject = slot.Name != string.Empty
? Loc.GetString(slot.Name)
- : Name(args.Using.Value) ?? string.Empty;
+ : Name(args.Using.Value);
- AlternativeVerb verb = new();
- verb.IconEntity = args.Using;
- verb.Act = () => Insert(uid, slot, args.Using.Value, args.User, excludeUserAudio: true);
+ AlternativeVerb verb = new()
+ {
+ IconEntity = GetNetEntity(args.Using),
+ Act = () => Insert(uid, slot, args.Using.Value, args.User, excludeUserAudio: true)
+ };
if (slot.InsertVerbText != null)
{
AlternativeVerb verb = new()
{
- IconEntity = slot.Item,
+ IconEntity = GetNetEntity(slot.Item),
Act = () => TryEjectToHands(uid, slot, args.User, excludeUserAudio: true)
};
? Loc.GetString(slot.Name)
: Name(slot.Item!.Value);
- InteractionVerb takeVerb = new();
- takeVerb.IconEntity = slot.Item;
- takeVerb.Act = () => TryEjectToHands(uid, slot, args.User, excludeUserAudio: true);
+ InteractionVerb takeVerb = new()
+ {
+ IconEntity = GetNetEntity(slot.Item),
+ Act = () => TryEjectToHands(uid, slot, args.User, excludeUserAudio: true)
+ };
if (slot.EjectVerbText == null)
takeVerb.Text = Loc.GetString("take-item-verb-text", ("subject", verbSubject));
InteractionVerb insertVerb = new()
{
- IconEntity = args.Using,
+ IconEntity = GetNetEntity(args.Using),
Act = () => Insert(uid, slot, args.Using.Value, args.User, excludeUserAudio: true)
};
[Serializable, NetSerializable]
public sealed class RequestCrewManifestMessage : EntityEventArgs
{
- public EntityUid Id { get; }
+ public NetEntity Id { get; }
- public RequestCrewManifestMessage(EntityUid id)
+ public RequestCrewManifestMessage(NetEntity id)
{
Id = id;
}
if (HasComp<DisarmProneComponent>(target))
cuffTime = 0.0f; // cuff them instantly.
- var doAfterEventArgs = new DoAfterArgs(user, cuffTime, new AddCuffDoAfterEvent(), handcuff, target, handcuff)
+ var doAfterEventArgs = new DoAfterArgs(EntityManager, user, cuffTime, new AddCuffDoAfterEvent(), handcuff, target, handcuff)
{
BreakOnTargetMove = true,
BreakOnUserMove = true,
}
var uncuffTime = isOwner ? cuff.BreakoutTime : cuff.UncuffTime;
- var doAfterEventArgs = new DoAfterArgs(user, uncuffTime, new UnCuffDoAfterEvent(), target, target, cuffsToRemove)
+ var doAfterEventArgs = new DoAfterArgs(EntityManager, user, uncuffTime, new UnCuffDoAfterEvent(), target, target, cuffsToRemove)
{
BreakOnUserMove = true,
BreakOnTargetMove = true,
[Serializable, NetSerializable]
public sealed class DecalChunkUpdateEvent : EntityEventArgs
{
- public Dictionary<EntityUid, Dictionary<Vector2i, DecalChunk>> Data = new();
- public Dictionary<EntityUid, HashSet<Vector2i>> RemovedChunks = new();
+ public Dictionary<NetEntity, Dictionary<Vector2i, DecalChunk>> Data = new();
+ public Dictionary<NetEntity, HashSet<Vector2i>> RemovedChunks = new();
}
}
public sealed class RequestDecalPlacementEvent : EntityEventArgs
{
public Decal Decal;
- public EntityCoordinates Coordinates;
+ public NetCoordinates Coordinates;
- public RequestDecalPlacementEvent(Decal decal, EntityCoordinates coordinates)
+ public RequestDecalPlacementEvent(Decal decal, NetCoordinates coordinates)
{
Decal = decal;
Coordinates = coordinates;
[Serializable, NetSerializable]
public sealed class RequestDecalRemovalEvent : EntityEventArgs
{
- public EntityCoordinates Coordinates;
+ public NetCoordinates Coordinates;
- public RequestDecalRemovalEvent(EntityCoordinates coordinates)
+ public RequestDecalRemovalEvent(NetCoordinates coordinates)
{
Coordinates = coordinates;
}
[Serializable, NetSerializable]
public sealed class DeviceListComponentState : ComponentState
{
- public readonly HashSet<EntityUid> Devices;
+ public readonly HashSet<NetEntity> Devices;
public readonly bool IsAllowList;
public readonly bool HandleIncomingPackets;
- public DeviceListComponentState(HashSet<EntityUid> devices, bool isAllowList, bool handleIncomingPackets)
+ public DeviceListComponentState(HashSet<NetEntity> devices, bool isAllowList, bool handleIncomingPackets)
{
Devices = devices;
IsAllowList = isAllowList;
[Serializable, NetSerializable]
public sealed class NetworkConfiguratorComponentState : ComponentState
{
- public readonly EntityUid? ActiveDeviceList;
+ public readonly NetEntity? ActiveDeviceList;
public readonly bool LinkModeActive;
- public NetworkConfiguratorComponentState(EntityUid? activeDeviceList, bool linkModeActive)
+ public NetworkConfiguratorComponentState(NetEntity? activeDeviceList, bool linkModeActive)
{
ActiveDeviceList = activeDeviceList;
LinkModeActive = linkModeActive;
private void GetDeviceListState(EntityUid uid, DeviceListComponent comp, ref ComponentGetState args)
{
- args.State = new DeviceListComponentState(comp.Devices, comp.IsAllowList, comp.HandleIncomingPackets);
+ args.State = new DeviceListComponentState(GetNetEntitySet(comp.Devices), comp.IsAllowList, comp.HandleIncomingPackets);
}
private void HandleDeviceListState(EntityUid uid, DeviceListComponent comp, ref ComponentHandleState args)
return;
}
- comp.Devices = state.Devices;
+ comp.Devices = EnsureEntitySet<DeviceListComponent>(state.Devices, uid);
comp.HandleIncomingPackets = state.HandleIncomingPackets;
comp.IsAllowList = state.IsAllowList;
}
private void GetNetworkConfiguratorState(EntityUid uid, NetworkConfiguratorComponent comp,
ref ComponentGetState args)
{
- args.State = new NetworkConfiguratorComponentState(comp.ActiveDeviceList, comp.LinkModeActive);
+ args.State = new NetworkConfiguratorComponentState(GetNetEntity(comp.ActiveDeviceList), comp.LinkModeActive);
}
private void HandleNetworkConfiguratorState(EntityUid uid, NetworkConfiguratorComponent comp,
return;
}
- comp.ActiveDeviceList = state.ActiveDeviceList;
+ comp.ActiveDeviceList = EnsureEntity<NetworkConfiguratorComponent>(state.ActiveDeviceList, uid);
comp.LinkModeActive = state.LinkModeActive;
}
}
case MobState.Critical:
case MobState.Dead:
- _doAfterSystem.TryStartDoAfter(new DoAfterArgs(uid, component.DevourTime, new DevourDoAfterEvent(), uid, target: target, used: uid)
+ _doAfterSystem.TryStartDoAfter(new DoAfterArgs(EntityManager, uid, component.DevourTime, new DevourDoAfterEvent(), uid, target: target, used: uid)
{
BreakOnTargetMove = true,
BreakOnUserMove = true,
if (component.SoundStructureDevour != null)
_audioSystem.PlayPredicted(component.SoundStructureDevour, uid, uid, component.SoundStructureDevour.Params);
- _doAfterSystem.TryStartDoAfter(new DoAfterArgs(uid, component.StructureDevourTime, new DevourDoAfterEvent(), uid, target: target, used: uid)
+ _doAfterSystem.TryStartDoAfter(new DoAfterArgs(EntityManager, uid, component.StructureDevourTime, new DevourDoAfterEvent(), uid, target: target, used: uid)
{
BreakOnTargetMove = true,
BreakOnUserMove = true,
public TimeSpan? NextFlush;
public bool Powered;
public bool Engaged;
- public List<EntityUid> RecentlyEjected;
+ public List<NetEntity> RecentlyEjected;
- public DisposalUnitComponentState(SoundSpecifier? flushSound, DisposalsPressureState state, TimeSpan nextPressurized, TimeSpan automaticEngageTime, TimeSpan? nextFlush, bool powered, bool engaged, List<EntityUid> recentlyEjected)
+ public DisposalUnitComponentState(SoundSpecifier? flushSound, DisposalsPressureState state, TimeSpan nextPressurized, TimeSpan automaticEngageTime, TimeSpan? nextFlush, bool powered, bool engaged, List<NetEntity> recentlyEjected)
{
FlushSound = flushSound;
State = state;
/// <summary>
/// Position of the user relative to their parent when the do after was started.
/// </summary>
+ [NonSerialized]
[DataField("userPosition")]
public EntityCoordinates UserPosition;
+ public NetCoordinates NetUserPosition;
+
/// <summary>
/// Distance from the user to the target when the do after was started.
/// </summary>
/// <summary>
/// If <see cref="NeedHand"/> is true, this is the entity that was in the active hand when the doafter started.
/// </summary>
+ [NonSerialized]
[DataField("activeItem")]
public EntityUid? InitialItem;
+ public NetEntity? NetInitialItem;
+
// cached attempt event for the sake of avoiding unnecessary reflection every time this needs to be raised.
[NonSerialized] public object? AttemptEvent;
StartTime = startTime;
}
- public DoAfter(DoAfter other)
+ public DoAfter(IEntityManager entManager, DoAfter other)
{
Index = other.Index;
Args = new(other.Args);
TargetDistance = other.TargetDistance;
InitialHand = other.InitialHand;
InitialItem = other.InitialItem;
+
+ NetUserPosition = other.NetUserPosition;
+ NetInitialItem = other.NetInitialItem;
}
}
/// <summary>
/// The entity invoking do_after
/// </summary>
+ [NonSerialized]
[DataField("user", required: true)]
public EntityUid User;
+ public NetEntity NetUser;
+
/// <summary>
/// How long does the do_after require to complete
/// </summary>
/// <summary>
/// Applicable target (if relevant)
/// </summary>
+ [NonSerialized]
[DataField("target")]
public EntityUid? Target;
+ public NetEntity? NetTarget;
+
/// <summary>
/// Entity used by the User on the Target.
/// </summary>
+ [NonSerialized]
[DataField("using")]
public EntityUid? Used;
+ public NetEntity? NetUsed;
+
#region Event options
/// <summary>
/// The event that will get raised when the DoAfter has finished. If null, this will simply raise a <see cref="SimpleDoAfterEvent"/>
/// <summary>
/// Entity which will receive the directed event. If null, no directed event will be raised.
/// </summary>
+ [NonSerialized]
[DataField("eventTarget")]
public EntityUid? EventTarget;
+ public NetEntity? NetEventTarget;
+
/// <summary>
/// Should the DoAfter event broadcast? If this is false, then <see cref="EventTarget"/> should be a valid entity.
/// </summary>
/// <param name="target">The entity being targeted by the DoAFter. Not the same as <see cref="EventTarget"/></param>.
/// <param name="used">The entity being used during the DoAfter. E.g., a tool</param>
public DoAfterArgs(
+ IEntityManager entManager,
EntityUid user,
TimeSpan delay,
DoAfterEvent @event,
Used = used;
EventTarget = eventTarget;
Event = @event;
+
+ NetUser = entManager.GetNetEntity(User);
+ NetTarget = entManager.GetNetEntity(Target);
+ NetUsed = entManager.GetNetEntity(Used);
}
private DoAfterArgs()
/// <param name="target">The entity being targeted by the DoAfter. Not the same as <see cref="EventTarget"/></param>.
/// <param name="used">The entity being used during the DoAfter. E.g., a tool</param>
public DoAfterArgs(
+ IEntityManager entManager,
EntityUid user,
float seconds,
DoAfterEvent @event,
EntityUid? eventTarget,
EntityUid? target = null,
EntityUid? used = null)
- : this(user, TimeSpan.FromSeconds(seconds), @event, eventTarget, target, used)
+ : this(entManager, user, TimeSpan.FromSeconds(seconds), @event, eventTarget, target, used)
{
}
CancelDuplicate = other.CancelDuplicate;
DuplicateCondition = other.DuplicateCondition;
+ // Networked
+ NetUser = other.NetUser;
+ NetTarget = other.NetTarget;
+ NetUsed = other.NetUsed;
+ NetEventTarget = other.NetEventTarget;
+
Event = other.Event.Clone();
}
}
public readonly ushort NextId;
public readonly Dictionary<ushort, DoAfter> DoAfters;
- public DoAfterComponentState(DoAfterComponent component)
+ public DoAfterComponentState(IEntityManager entManager, DoAfterComponent component)
{
NextId = component.NextId;
DoAfters = component.DoAfters;
#else
DoAfters = new();
- foreach (var (id, doafter) in component.DoAfters)
+ foreach (var (id, doAfter) in component.DoAfters)
{
- DoAfters.Add(id, new DoAfter(doafter));
+ var newDoAfter = new DoAfter(entManager, doAfter);
+ DoAfters.Add(id, newDoAfter);
}
#endif
}
}
if (dirty)
- Dirty(comp);
+ Dirty(uid, comp);
if (comp.DoAfters.Count == 0)
RemCompDeferred(uid, active);
private void OnDoAfterGetState(EntityUid uid, DoAfterComponent comp, ref ComponentGetState args)
{
- args.State = new DoAfterComponentState(comp);
+ args.State = new DoAfterComponentState(EntityManager, comp);
}
private void OnDoAfterHandleState(EntityUid uid, DoAfterComponent comp, ref ComponentHandleState args)
comp.DoAfters.Clear();
foreach (var (id, doAfter) in state.DoAfters)
{
- comp.DoAfters.Add(id, new(doAfter));
+ var newDoAfter = new DoAfter(EntityManager, doAfter);
+ comp.DoAfters.Add(id, newDoAfter);
+
+ // Networking yay (if you have an easier way dear god please).
+ newDoAfter.UserPosition = EnsureCoordinates<DoAfterComponent>(newDoAfter.NetUserPosition, uid);
+ newDoAfter.InitialItem = EnsureEntity<DoAfterComponent>(newDoAfter.NetInitialItem, uid);
+
+ var doAfterArgs = newDoAfter.Args;
+ doAfterArgs.Target = EnsureEntity<DoAfterComponent>(doAfterArgs.NetTarget, uid);
+ doAfterArgs.Used = EnsureEntity<DoAfterComponent>(doAfterArgs.NetUsed, uid);
+ doAfterArgs.User = EnsureEntity<DoAfterComponent>(doAfterArgs.NetUser, uid);
+ doAfterArgs.EventTarget = EnsureEntity<DoAfterComponent>(doAfterArgs.NetEventTarget, uid);
}
comp.NextId = state.NextId;
id = new DoAfterId(args.User, comp.NextId++);
var doAfter = new DoAfter(id.Value.Index, args, GameTiming.CurTime);
+ // Networking yay
+ doAfter.NetUserPosition = GetNetCoordinates(doAfter.UserPosition);
+ doAfter.NetInitialItem = GetNetEntity(doAfter.InitialItem);
+
+ // Networking yay
+ args.NetTarget = GetNetEntity(args.Target);
+ args.NetUsed = GetNetEntity(args.Used);
+ args.NetUser = GetNetEntity(args.User);
+ args.NetEventTarget = GetNetEntity(args.EventTarget);
+
if (args.BreakOnUserMove || args.BreakOnTargetMove)
doAfter.UserPosition = Transform(args.User).Coordinates;
}
InternalCancel(doAfter, comp);
- Dirty(comp);
+ Dirty(entity, comp);
}
private void InternalCancel(DoAfter doAfter, DoAfterComponent component)
public sealed class DoorComponentState : ComponentState
{
public readonly DoorState DoorState;
- public readonly HashSet<EntityUid> CurrentlyCrushing;
+ public readonly HashSet<NetEntity> CurrentlyCrushing;
public readonly TimeSpan? NextStateChange;
public readonly bool Partial;
- public DoorComponentState(DoorComponent door)
+ public DoorComponentState(DoorComponent door, HashSet<NetEntity> currentlyCrushing)
{
DoorState = door.State;
- CurrentlyCrushing = door.CurrentlyCrushing;
+ CurrentlyCrushing = currentlyCrushing;
NextStateChange = door.NextStateChange;
Partial = door.Partial;
}
#region StateManagement
private void OnGetState(EntityUid uid, DoorComponent door, ref ComponentGetState args)
{
- args.State = new DoorComponentState(door);
+ args.State = new DoorComponentState(door, GetNetEntitySet(door.CurrentlyCrushing));
}
private void OnHandleState(EntityUid uid, DoorComponent door, ref ComponentHandleState args)
if (args.Current is not DoorComponentState state)
return;
- if (!door.CurrentlyCrushing.SetEquals(state.CurrentlyCrushing))
- {
- door.CurrentlyCrushing.Clear();
- door.CurrentlyCrushing.UnionWith(state.CurrentlyCrushing);
- }
+ door.CurrentlyCrushing.Clear();
+ door.CurrentlyCrushing.UnionWith(EnsureEntitySet<DoorComponent>(state.CurrentlyCrushing, uid));
door.State = state.DoorState;
door.NextStateChange = state.NextStateChange;
/// <summary>
/// Entity that was dragged and dropped.
/// </summary>
- public EntityUid Dragged { get; }
+ public NetEntity Dragged { get; }
/// <summary>
/// Entity that was drag dropped on.
/// </summary>
- public EntityUid Target { get; }
+ public NetEntity Target { get; }
- public DragDropRequestEvent(EntityUid dragged, EntityUid target)
+ public DragDropRequestEvent(NetEntity dragged, NetEntity target)
{
Dragged = dragged;
Target = target;
/// </summary>
public Color Color;
- public List<EntityUid> Entities;
+ public List<NetEntity> Entities;
- public ColorFlashEffectEvent(Color color, List<EntityUid> entities)
+ public ColorFlashEffectEvent(Color color, List<NetEntity> entities)
{
Color = color;
Entities = entities;
[Serializable, NetSerializable]
public sealed class RequestExamineInfoMessage : EntityEventArgs
{
- public readonly EntityUid EntityUid;
-
+ public readonly NetEntity NetEntity;
+
public readonly int Id;
public readonly bool GetVerbs;
- public RequestExamineInfoMessage(EntityUid entityUid, int id, bool getVerbs=false)
+ public RequestExamineInfoMessage(NetEntity netEntity, int id, bool getVerbs=false)
{
- EntityUid = entityUid;
+ NetEntity = netEntity;
Id = id;
GetVerbs = getVerbs;
}
[Serializable, NetSerializable]
public sealed class ExamineInfoResponseMessage : EntityEventArgs
{
- public readonly EntityUid EntityUid;
+ public readonly NetEntity EntityUid;
public readonly int Id;
public readonly FormattedMessage Message;
public readonly bool KnowTarget;
- public ExamineInfoResponseMessage(EntityUid entityUid, int id, FormattedMessage message, List<Verb>? verbs=null,
+ public ExamineInfoResponseMessage(NetEntity entityUid, int id, FormattedMessage message, List<Verb>? verbs=null,
bool centerAtCursor=true, bool openAtOldTooltip=true, bool knowTarget = true)
{
EntityUid = entityUid;
public bool IsInDetailsRange(EntityUid examiner, EntityUid entity)
{
- if (entity.IsClientSide())
+ if (IsClientSide(entity))
return true;
// check if the mob is in critical or dead
public bool CanExamine(EntityUid examiner, EntityUid examined)
{
// special check for client-side entities stored in null-space for some UI guff.
- if (examined.IsClientSide())
+ if (IsClientSide(examined))
return true;
return !Deleted(examined) && CanExamine(examiner, EntityManager.GetComponent<TransformComponent>(examined).MapPosition,
{
public MapCoordinates Epicenter;
public Dictionary<int, List<Vector2i>>? SpaceTiles;
- public Dictionary<EntityUid, Dictionary<int, List<Vector2i>>> Tiles;
+ public Dictionary<NetEntity, Dictionary<int, List<Vector2i>>> Tiles;
public List<float> Intensity;
public string ExplosionType = string.Empty;
public Matrix3 SpaceMatrix;
string typeID,
List<float> intensity,
Dictionary<int, List<Vector2i>>? spaceTiles,
- Dictionary<EntityUid, Dictionary<int, List<Vector2i>>> tiles,
+ Dictionary<NetEntity, Dictionary<int, List<Vector2i>>> tiles,
Matrix3 spaceMatrix,
ushort spaceTileSize)
{
[Serializable, NetSerializable]
public sealed class AdminFaxEntry
{
- public EntityUid Uid { get; }
+ public NetEntity Uid { get; }
public string Name { get; }
public string Address { get; }
- public AdminFaxEntry(EntityUid uid, string name, string address)
+ public AdminFaxEntry(NetEntity uid, string name, string address)
{
Uid = uid;
Name = name;
[Serializable, NetSerializable]
public sealed class Follow : EuiMessageBase
{
- public EntityUid TargetFax { get; }
+ public NetEntity TargetFax { get; }
- public Follow(EntityUid targetFax)
+ public Follow(NetEntity targetFax)
{
TargetFax = targetFax;
}
[Serializable, NetSerializable]
public sealed class Send : EuiMessageBase
{
- public EntityUid Target { get; }
+ public NetEntity Target { get; }
public string Title { get; }
public string From { get; }
public string Content { get; }
public string StampState { get; }
public Color StampColor { get; }
- public Send(EntityUid target, string title, string from, string content, string stamp, Color stampColor)
+ public Send(NetEntity target, string title, string from, string content, string stamp, Color stampColor)
{
Target = target;
Title = title;
{
public PuddleDebugOverlayData[] OverlayData { get; }
- public EntityUid GridUid { get; }
+ public NetEntity GridUid { get; }
- public PuddleOverlayDebugMessage(EntityUid gridUid, PuddleDebugOverlayData[] overlayData)
+ public PuddleOverlayDebugMessage(NetEntity gridUid, PuddleDebugOverlayData[] overlayData)
{
GridUid = gridUid;
OverlayData = overlayData;
/// Attached to entities that are currently being followed by a ghost.
/// </summary>
[RegisterComponent, Access(typeof(FollowerSystem))]
-[NetworkedComponent, AutoGenerateComponentState]
+[NetworkedComponent]
public sealed partial class FollowedComponent : Component
{
- [AutoNetworkedField(true), DataField("following")]
+ [DataField("following")]
public HashSet<EntityUid> Following = new();
}
using Content.Shared.Tag;
using Content.Shared.Verbs;
using Robust.Shared.Containers;
+using Robust.Shared.GameStates;
using Robust.Shared.Map;
using Robust.Shared.Map.Events;
using Robust.Shared.Network;
using Robust.Shared.Utility;
using Robust.Shared.Physics;
using Robust.Shared.Physics.Systems;
+using Robust.Shared.Serialization;
namespace Content.Shared.Follower;
SubscribeLocalEvent<FollowerComponent, GotEquippedHandEvent>(OnGotEquippedHand);
SubscribeLocalEvent<FollowedComponent, EntityTerminatingEvent>(OnFollowedTerminating);
SubscribeLocalEvent<BeforeSaveEvent>(OnBeforeSave);
+
+ SubscribeLocalEvent<FollowedComponent, ComponentGetState>(OnFollowedGetState);
+ SubscribeLocalEvent<FollowedComponent, ComponentHandleState>(OnFollowedHandleState);
+ }
+
+ private void OnFollowedGetState(EntityUid uid, FollowedComponent component, ref ComponentGetState args)
+ {
+ args.State = new FollowedComponentState()
+ {
+ Following = GetNetEntitySet(component.Following),
+ };
+ }
+
+ private void OnFollowedHandleState(EntityUid uid, FollowedComponent component, ref ComponentHandleState args)
+ {
+ if (args.Current is not FollowedComponentState state)
+ return;
+
+ component.Following = EnsureEntitySet<FollowedComponent>(state.Following, uid);
}
private void OnBeforeSave(BeforeSaveEvent ev)
private void OnGetAlternativeVerbs(GetVerbsEvent<AlternativeVerb> ev)
{
- if (ev.User == ev.Target || ev.Target.IsClientSide())
+ if (ev.User == ev.Target || IsClientSide(ev.Target))
return;
if (HasComp<GhostComponent>(ev.User))
StopFollowingEntity(player, uid, followed);
}
}
+
+ [Serializable, NetSerializable]
+ private sealed class FollowedComponentState : ComponentState
+ {
+ public HashSet<NetEntity> Following = new();
+ }
}
public abstract class FollowEvent : EntityEventArgs
/// <summary>
/// The Status of the Player in the lobby (ready, observer, ...)
/// </summary>
- public Dictionary<EntityUid, Dictionary<string, uint?>> JobsAvailableByStation { get; }
- public Dictionary<EntityUid, string> StationNames { get; }
+ public Dictionary<NetEntity, Dictionary<string, uint?>> JobsAvailableByStation { get; }
+ public Dictionary<NetEntity, string> StationNames { get; }
- public TickerJobsAvailableEvent(Dictionary<EntityUid, string> stationNames, Dictionary<EntityUid, Dictionary<string, uint?>> jobsAvailableByStation)
+ public TickerJobsAvailableEvent(Dictionary<NetEntity, string> stationNames, Dictionary<NetEntity, Dictionary<string, uint?>> jobsAvailableByStation)
{
StationNames = stationNames;
JobsAvailableByStation = jobsAvailableByStation;
public string PlayerOOCName;
public string? PlayerICName;
public string Role;
- public EntityUid? PlayerEntityUid;
+ public NetEntity? PlayerNetEntity;
public bool Antag;
public bool Observer;
public bool Connected;
/// <summary>
/// List of enabled destinations and information about them.
/// </summary>
- public readonly List<(EntityUid, string, TimeSpan, bool)> Destinations;
+ public readonly List<(NetEntity, string, TimeSpan, bool)> Destinations;
/// <summary>
/// Which destination it is currently linked to, if any.
/// </summary>
- public readonly EntityUid? Current;
+ public readonly NetEntity? Current;
/// <summary>
/// Time the portal will close at.
/// </summary>
public readonly TimeSpan LastOpen;
- public GatewayBoundUserInterfaceState(List<(EntityUid, string, TimeSpan, bool)> destinations,
- EntityUid? current, TimeSpan nextClose, TimeSpan lastOpen)
+ public GatewayBoundUserInterfaceState(List<(NetEntity, string, TimeSpan, bool)> destinations,
+ NetEntity? current, TimeSpan nextClose, TimeSpan lastOpen)
{
Destinations = destinations;
Current = current;
[Serializable, NetSerializable]
public sealed class GatewayOpenPortalMessage : BoundUserInterfaceMessage
{
- public EntityUid Destination;
+ public NetEntity Destination;
- public GatewayOpenPortalMessage(EntityUid destination)
+ public GatewayOpenPortalMessage(NetEntity destination)
{
Destination = destination;
}
[Serializable, NetSerializable]
public sealed class MakeGhostRoleEuiState : EuiStateBase
{
- public MakeGhostRoleEuiState(EntityUid entityUid)
+ public MakeGhostRoleEuiState(NetEntity entityUid)
{
EntityUid = entityUid;
}
- public EntityUid EntityUid { get; }
+ public NetEntity EntityUid { get; }
}
}
{
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
- public EntityUid Id;
+ public NetEntity Id;
}
}
[Serializable, NetSerializable]
public struct GhostWarp
{
- public GhostWarp(EntityUid entity, string displayName, bool isWarpPoint)
+ public GhostWarp(NetEntity entity, string displayName, bool isWarpPoint)
{
Entity = entity;
DisplayName = displayName;
/// The entity representing the warp point.
/// This is passed back to the server in <see cref="GhostWarpToTargetRequestEvent"/>
/// </summary>
- public EntityUid Entity { get; }
+ public NetEntity Entity { get; }
+
/// <summary>
/// The display name to be surfaced in the ghost warps menu
/// </summary>
public string DisplayName { get; }
+
/// <summary>
/// Whether this warp represents a warp point or a player
/// </summary>
[Serializable, NetSerializable]
public sealed class GhostWarpToTargetRequestEvent : EntityEventArgs
{
- public EntityUid Target { get; }
+ public NetEntity Target { get; }
- public GhostWarpToTargetRequestEvent(EntityUid target)
+ public GhostWarpToTargetRequestEvent(NetEntity target)
{
Target = target;
}
public abstract partial class SharedHandsSystem : EntitySystem
{
+ [Dependency] private readonly SharedContainerSystem _container = default!;
+
private void InitializeDrop()
{
SubscribeLocalEvent<HandsComponent, EntRemovedFromContainerMessage>(HandleEntityRemoved);
/// </summary>
public bool CanDropHeld(EntityUid uid, Hand hand, bool checkActionBlocker = true)
{
- if (hand.HeldEntity == null)
+ if (hand.Container?.ContainedEntity is not {} held)
return false;
- if (!hand.Container!.CanRemove(hand.HeldEntity.Value, EntityManager))
+ if (!_container.CanRemove(held, hand.Container))
return false;
if (checkActionBlocker && !_actionBlocker.CanDrop(uid))
/// <summary>
/// Attempts to move a held item from a hand into a container that is not another hand, without dropping it on the floor in-between.
/// </summary>
- public bool TryDropIntoContainer(EntityUid uid, EntityUid entity, IContainer targetContainer, bool checkActionBlocker = true, HandsComponent? handsComp = null)
+ public bool TryDropIntoContainer(EntityUid uid, EntityUid entity, BaseContainer targetContainer, bool checkActionBlocker = true, HandsComponent? handsComp = null)
{
if (!Resolve(uid, ref handsComp))
return false;
if (!CanDropHeld(uid, hand, checkActionBlocker))
return false;
- if (!targetContainer.CanInsert(entity, EntityManager))
+ if (!_container.CanInsert(entity, targetContainer))
return false;
DoDrop(uid, hand, false, handsComp);
var newActiveIndex = component.SortedHands.IndexOf(component.ActiveHand.Name) + 1;
var nextHand = component.SortedHands[newActiveIndex % component.Hands.Count];
- TrySetActiveHand(component.Owner, nextHand, component);
+ TrySetActiveHand(session.AttachedEntity.Value, nextHand, component);
}
- private bool DropPressed(ICommonSession? session, EntityCoordinates coords, EntityUid uid)
+ private bool DropPressed(ICommonSession? session, EntityCoordinates coords, EntityUid netEntity)
{
if (TryComp(session?.AttachedEntity, out HandsComponent? hands) && hands.ActiveHand != null)
- TryDrop(session.AttachedEntity!.Value, hands.ActiveHand, coords, handsComp: hands);
+ TryDrop(session.AttachedEntity.Value, hands.ActiveHand, coords, handsComp: hands);
// always send to server.
return false;
return false;
// check can insert (including raising attempt events).
- return handContainer.CanInsert(entity, EntityManager);
+ return _containerSystem.CanInsert(entity, handContainer);
}
/// <summary>
[Serializable, NetSerializable]
public sealed class PickupAnimationEvent : EntityEventArgs
{
- public EntityUid ItemUid { get; }
- public EntityCoordinates InitialPosition { get; }
+ public NetEntity ItemUid { get; }
+ public NetCoordinates InitialPosition { get; }
public Vector2 FinalPosition { get; }
public Angle InitialAngle { get; }
- public PickupAnimationEvent(EntityUid itemUid, EntityCoordinates initialPosition,
+ public PickupAnimationEvent(NetEntity itemUid, NetCoordinates initialPosition,
Vector2 finalPosition, Angle initialAngle)
{
ItemUid = itemUid;
private void OnInit(EntityUid uid, HumanoidAppearanceComponent humanoid, ComponentInit args)
{
- if (string.IsNullOrEmpty(humanoid.Species) || _netManager.IsClient && !uid.IsClientSide())
+ if (string.IsNullOrEmpty(humanoid.Species) || _netManager.IsClient && !IsClientSide(uid))
{
return;
}
continue;
//Don't remove a permanent implant and look for the next that can be drawn
- if (!implantContainer.CanRemove(implant))
+ if (!_container.CanRemove(implant, implantContainer))
{
var implantName = Identity.Entity(implant, EntityManager);
var targetName = Identity.Entity(target, EntityManager);
[Serializable, NetSerializable]
public sealed class InstrumentStopMidiEvent : EntityEventArgs
{
- public EntityUid Uid { get; }
+ public NetEntity Uid { get; }
- public InstrumentStopMidiEvent(EntityUid uid)
+ public InstrumentStopMidiEvent(NetEntity uid)
{
Uid = uid;
}
[Serializable, NetSerializable]
public sealed class InstrumentSetMasterEvent : EntityEventArgs
{
- public EntityUid Uid { get; }
- public EntityUid? Master { get; }
+ public NetEntity Uid { get; }
+ public NetEntity? Master { get; }
- public InstrumentSetMasterEvent(EntityUid uid, EntityUid? master)
+ public InstrumentSetMasterEvent(NetEntity uid, NetEntity? master)
{
Uid = uid;
Master = master;
[Serializable, NetSerializable]
public sealed class InstrumentSetFilteredChannelEvent : EntityEventArgs
{
- public EntityUid Uid { get; }
+ public NetEntity Uid { get; }
public int Channel { get; }
public bool Value { get; }
- public InstrumentSetFilteredChannelEvent(EntityUid uid, int channel, bool value)
+ public InstrumentSetFilteredChannelEvent(NetEntity uid, int channel, bool value)
{
Uid = uid;
Channel = channel;
[Serializable, NetSerializable]
public sealed class InstrumentStartMidiEvent : EntityEventArgs
{
- public EntityUid Uid { get; }
+ public NetEntity Uid { get; }
- public InstrumentStartMidiEvent(EntityUid uid)
+ public InstrumentStartMidiEvent(NetEntity uid)
{
Uid = uid;
}
[Serializable, NetSerializable]
public sealed class InstrumentMidiEventEvent : EntityEventArgs
{
- public EntityUid Uid { get; }
+ public NetEntity Uid { get; }
public RobustMidiEvent[] MidiEvent { get; }
- public InstrumentMidiEventEvent(EntityUid uid, RobustMidiEvent[] midiEvent)
+ public InstrumentMidiEventEvent(NetEntity uid, RobustMidiEvent[] midiEvent)
{
Uid = uid;
MidiEvent = midiEvent;
[Serializable, NetSerializable]
public sealed class InstrumentBandResponseBuiMessage : BoundUserInterfaceMessage
{
- public (EntityUid, string)[] Nearby { get; set; }
+ public (NetEntity, string)[] Nearby { get; set; }
- public InstrumentBandResponseBuiMessage((EntityUid, string)[] nearby)
+ public InstrumentBandResponseBuiMessage((NetEntity, string)[] nearby)
{
Nearby = nearby;
}
[Serializable, NetSerializable]
public sealed class InteractionRelayComponentState : ComponentState
{
- public EntityUid? RelayEntity;
+ public NetEntity? RelayEntity;
- public InteractionRelayComponentState(EntityUid? relayEntity)
+ public InteractionRelayComponentState(NetEntity? relayEntity)
{
RelayEntity = relayEntity;
}
public static bool InRangeUnOccluded(
this EntityUid origin,
- IContainer other,
+ BaseContainer other,
float range = InteractionRange,
Ignored? predicate = null,
bool ignoreInsideBlocker = true)
public static bool InRangeUnOccluded(
this IComponent origin,
- IContainer other,
+ BaseContainer other,
float range = InteractionRange,
Ignored? predicate = null,
bool ignoreInsideBlocker = true)
#region Containers
public static bool InRangeUnOccluded(
- this IContainer origin,
+ this BaseContainer origin,
EntityUid other,
float range = InteractionRange,
Ignored? predicate = null,
}
public static bool InRangeUnOccluded(
- this IContainer origin,
+ this BaseContainer origin,
IComponent other,
float range = InteractionRange,
Ignored? predicate = null,
}
public static bool InRangeUnOccluded(
- this IContainer origin,
- IContainer other,
+ this BaseContainer origin,
+ BaseContainer other,
float range = InteractionRange,
Ignored? predicate = null,
bool ignoreInsideBlocker = true)
}
public static bool InRangeUnOccluded(
- this IContainer origin,
+ this BaseContainer origin,
EntityCoordinates other,
float range = InteractionRange,
Ignored? predicate = null,
}
public static bool InRangeUnOccluded(
- this IContainer origin,
+ this BaseContainer origin,
MapCoordinates other,
float range = InteractionRange,
Ignored? predicate = null,
public static bool InRangeUnOccluded(
this EntityCoordinates origin,
- IContainer other,
+ BaseContainer other,
float range = InteractionRange,
Ignored? predicate = null,
bool ignoreInsideBlocker = true)
public static bool InRangeUnOccluded(
this MapCoordinates origin,
- IContainer other,
+ BaseContainer other,
float range = InteractionRange,
Ignored? predicate = null,
bool ignoreInsideBlocker = true)
private void OnGetState(EntityUid uid, InteractionRelayComponent component, ref ComponentGetState args)
{
- args.State = new InteractionRelayComponentState(component.RelayEntity);
+ args.State = new InteractionRelayComponentState(GetNetEntity(component.RelayEntity));
}
private void OnHandleState(EntityUid uid, InteractionRelayComponent component, ref ComponentHandleState args)
if (args.Current is not InteractionRelayComponentState state)
return;
- component.RelayEntity = state.RelayEntity;
+ component.RelayEntity = EnsureEntity<InteractionRelayComponent>(state.RelayEntity, uid);
}
public void SetRelay(EntityUid uid, EntityUid? relayEntity, InteractionRelayComponent? component = null)
/// </summary>
private void HandleInteractInventorySlotEvent(InteractInventorySlotEvent msg, EntitySessionEventArgs args)
{
+ var item = GetEntity(msg.ItemUid);
+
// client sanitization
- if (!TryComp(msg.ItemUid, out TransformComponent? itemXform) || !ValidateClientInput(args.SenderSession, itemXform.Coordinates, msg.ItemUid, out var user))
+ if (!TryComp(item, out TransformComponent? itemXform) || !ValidateClientInput(args.SenderSession, itemXform.Coordinates, item, out var user))
{
Logger.InfoS("system.interaction", $"Inventory interaction validation failed. Session={args.SenderSession}");
return;
if (msg.AltInteract)
// Use 'UserInteraction' function - behaves as if the user alt-clicked the item in the world.
- UserInteraction(user.Value, itemXform.Coordinates, msg.ItemUid, msg.AltInteract);
+ UserInteraction(user.Value, itemXform.Coordinates, item, msg.AltInteract);
else
// User used 'E'. We want to activate it, not simulate clicking on the item
- InteractionActivate(user.Value, msg.ItemUid);
+ InteractionActivate(user.Value, item);
}
public bool HandleAltUseInteraction(ICommonSession? session, EntityCoordinates coords, EntityUid uid)
return false;
}
- if (uid.IsClientSide())
+ if (IsClientSide(uid))
{
Logger.WarningS("system.interaction",
$"Client sent interaction with client-side entity. Session={session}, Uid={uid}");
/// <summary>
/// Entity that was interacted with.
/// </summary>
- public EntityUid ItemUid { get; }
+ public NetEntity ItemUid { get; }
/// <summary>
/// Whether the interaction used the alt-modifier to trigger alternative interactions.
/// </summary>
public bool AltInteract { get; }
- public InteractInventorySlotEvent(EntityUid itemUid, bool altInteract = false)
+ public InteractInventorySlotEvent(NetEntity itemUid, bool altInteract = false)
{
ItemUid = itemUid;
AltInteract = altInteract;
[NetSerializable, Serializable]
public sealed class InventoryEquipActEvent : EntityEventArgs
{
- public readonly EntityUid Uid;
- public readonly EntityUid ItemUid;
+ public readonly NetEntity Uid;
+ public readonly NetEntity ItemUid;
public readonly string Slot;
public readonly bool Silent;
public readonly bool Force;
- public InventoryEquipActEvent(EntityUid uid, EntityUid itemUid, string slot, bool silent = false, bool force = false)
+ public InventoryEquipActEvent(NetEntity uid, NetEntity itemUid, string slot, bool silent = false, bool force = false)
{
Uid = uid;
ItemUid = itemUid;
}
//we need to do this to make sure we are 100% removing this entity, since we are now dropping dependant slots
- if (!force && !slotContainer.CanRemove(removedItem.Value))
+ if (!force && !_containerSystem.CanRemove(removedItem.Value, slotContainer))
return false;
foreach (var slotDef in GetSlots(target, inventory))
if ((containerSlot == null || slotDefinition == null) && !TryGetSlotContainer(target, slot, out containerSlot, out slotDefinition, inventory))
return false;
- if (containerSlot.ContainedEntity == null)
+ if (containerSlot.ContainedEntity is not {} itemUid)
return false;
- if (!containerSlot.ContainedEntity.HasValue || !containerSlot.CanRemove(containerSlot.ContainedEntity.Value))
+ if (!_containerSystem.CanRemove(itemUid, containerSlot))
return false;
- var itemUid = containerSlot.ContainedEntity.Value;
-
// make sure the user can actually reach the target
if (!CanAccess(actor, target, itemUid))
{
[Serializable, NetSerializable]
public sealed class VisualsChangedEvent : EntityEventArgs
{
- public readonly EntityUid Item;
+ public readonly NetEntity Item;
public readonly string ContainerId;
- public VisualsChangedEvent(EntityUid item, string containerId)
+ public VisualsChangedEvent(NetEntity item, string containerId)
{
Item = item;
ContainerId = containerId;
[Serializable, NetSerializable]
public sealed class MicrowaveEjectSolidIndexedMessage : BoundUserInterfaceMessage
{
- public EntityUid EntityID;
- public MicrowaveEjectSolidIndexedMessage(EntityUid entityId)
+ public NetEntity EntityID;
+ public MicrowaveEjectSolidIndexedMessage(NetEntity entityId)
{
EntityID = entityId;
}
[NetSerializable, Serializable]
public sealed class MicrowaveUpdateUserInterfaceState : BoundUserInterfaceState
{
- public EntityUid[] ContainedSolids;
+ public NetEntity[] ContainedSolids;
public bool IsMicrowaveBusy;
public int ActiveButtonIndex;
public uint CurrentCookTime;
- public MicrowaveUpdateUserInterfaceState(EntityUid[] containedSolids,
+ public MicrowaveUpdateUserInterfaceState(NetEntity[] containedSolids,
bool isMicrowaveBusy, int activeButtonIndex, uint currentCookTime)
{
ContainedSolids = containedSolids;
[Serializable, NetSerializable]
public sealed class ReagentGrinderEjectChamberContentMessage : BoundUserInterfaceMessage
{
- public EntityUid EntityId;
- public ReagentGrinderEjectChamberContentMessage(EntityUid entityId)
+ public NetEntity EntityId;
+ public ReagentGrinderEjectChamberContentMessage(NetEntity entityId)
{
EntityId = entityId;
}
public bool Powered;
public bool CanJuice;
public bool CanGrind;
- public EntityUid[] ChamberContents;
+ public NetEntity[] ChamberContents;
public ReagentQuantity[]? ReagentQuantities;
- public ReagentGrinderInterfaceState(bool isBusy, bool hasBeaker, bool powered, bool canJuice, bool canGrind, EntityUid[] chamberContents, ReagentQuantity[]? heldBeakerContents)
+ public ReagentGrinderInterfaceState(bool isBusy, bool hasBeaker, bool powered, bool canJuice, bool canGrind, NetEntity[] chamberContents, ReagentQuantity[]? heldBeakerContents)
{
IsBusy = isBusy;
HasBeakerIn = hasBeaker;
[Serializable, NetSerializable]
public sealed class GridDragRequestPosition : EntityEventArgs
{
- public EntityUid Grid;
+ public NetEntity Grid;
public Vector2 WorldPosition;
}
[Serializable, NetSerializable]
public sealed class GridDragVelocityRequest : EntityEventArgs
{
- public EntityUid Grid;
+ public NetEntity Grid;
public Vector2 LinearVelocity;
}
[Serializable, NetSerializable]
public sealed class NewsWriteShareMessage : BoundUserInterfaceMessage
{
- public NewsArticle Article;
-
- public NewsWriteShareMessage(NewsArticle article)
+ public readonly string Name;
+ public readonly string Content;
+ public NewsWriteShareMessage(string name, string content)
{
- Article = article;
+ Name = name;
+ Content = content;
}
}
-using Content.Shared.StationRecords;
+using Robust.Shared.Serialization;
namespace Content.Shared.MassMedia.Systems;
-[Serializable]
+[Serializable, NetSerializable]
public struct NewsArticle
{
public string Name;
public string Content;
public string? Author;
- public ICollection<StationRecordKey>? AuthorStationRecordKeyIds;
+ public ICollection<(NetEntity, uint)>? AuthorStationRecordKeyIds;
public TimeSpan ShareTime;
}
public FixedPoint2 MaxIntegrity;
public FixedPoint2 Energy;
public FixedPoint2 MaxEnergy;
- public EntityUid? CurrentSelectedEquipment;
+ public NetEntity? CurrentSelectedEquipment;
public bool Broken;
}
[Serializable, NetSerializable]
public sealed class MechPilotComponentState : ComponentState
{
- public EntityUid Mech;
+ public NetEntity Mech;
}
MaxIntegrity = component.MaxIntegrity,
Energy = component.Energy,
MaxEnergy = component.MaxEnergy,
- CurrentSelectedEquipment = component.CurrentSelectedEquipment,
+ CurrentSelectedEquipment = GetNetEntity(component.CurrentSelectedEquipment),
Broken = component.Broken
};
}
component.MaxIntegrity = state.MaxIntegrity;
component.Energy = state.Energy;
component.MaxEnergy = state.MaxEnergy;
- component.CurrentSelectedEquipment = state.CurrentSelectedEquipment;
+ component.CurrentSelectedEquipment = EnsureEntity<MechComponent>(state.CurrentSelectedEquipment, uid);
component.Broken = state.Broken;
}
{
args.State = new MechPilotComponentState
{
- Mech = component.Mech
+ Mech = GetNetEntity(component.Mech)
};
}
if (args.Current is not MechPilotComponentState state)
return;
- component.Mech = state.Mech;
+ component.Mech = EnsureEntity<MechPilotComponent>(state.Mech, uid);
}
#endregion
{
Sounds = sounds.ToList()
};
- args.States.Add(uid, state);
+ args.States.Add(GetNetEntity(uid), state);
}
private void OnSoundboardMessage(EntityUid uid, MechSoundboardComponent comp, MechEquipmentUiMessageRelayEvent args)
/// </summary>
public sealed class MechEquipmentUiStateReadyEvent : EntityEventArgs
{
- public Dictionary<EntityUid, BoundUserInterfaceState> States = new();
+ public Dictionary<NetEntity, BoundUserInterfaceState> States = new();
}
/// <summary>
[Serializable, NetSerializable]
public sealed class MechEquipmentRemoveMessage : BoundUserInterfaceMessage
{
- public EntityUid Equipment;
+ public NetEntity Equipment;
- public MechEquipmentRemoveMessage(EntityUid equipment)
+ public MechEquipmentRemoveMessage(NetEntity equipment)
{
Equipment = equipment;
}
[Serializable, NetSerializable]
public abstract class MechEquipmentUiMessage : BoundUserInterfaceMessage
{
- public EntityUid Equipment;
+ public NetEntity Equipment;
}
/// <summary>
[Serializable, NetSerializable]
public sealed class MechGrabberEjectMessage : MechEquipmentUiMessage
{
- public EntityUid Item;
+ public NetEntity Item;
- public MechGrabberEjectMessage(EntityUid equipment, EntityUid uid)
+ public MechGrabberEjectMessage(NetEntity equipment, NetEntity uid)
{
Equipment = equipment;
Item = uid;
{
public int Sound;
- public MechSoundboardPlayMessage(EntityUid equipment, int sound)
+ public MechSoundboardPlayMessage(NetEntity equipment, int sound)
{
Equipment = equipment;
Sound = sound;
[Serializable, NetSerializable]
public sealed class MechBoundUiState : BoundUserInterfaceState
{
- public Dictionary<EntityUid, BoundUserInterfaceState> EquipmentStates = new();
+ public Dictionary<NetEntity, BoundUserInterfaceState> EquipmentStates = new();
}
[Serializable, NetSerializable]
public sealed class MechGrabberUiState : BoundUserInterfaceState
{
- public List<EntityUid> Contents = new();
+ public List<NetEntity> Contents = new();
public int MaxContents;
}
[Serializable, NetSerializable]
public sealed class SuitSensorStatus
{
- public SuitSensorStatus(EntityUid suitSensorUid, string name, string job)
+ public SuitSensorStatus(NetEntity suitSensorUid, string name, string job)
{
SuitSensorUid = suitSensorUid;
Name = name;
}
public TimeSpan Timestamp;
- public EntityUid SuitSensorUid;
+ public NetEntity SuitSensorUid;
public string Name;
public string Job;
public bool IsAlive;
public int? TotalDamage;
- public EntityCoordinates? Coordinates;
+ public NetCoordinates? Coordinates;
}
[Serializable, NetSerializable]
[Serializable, NetSerializable]
public sealed class HealthAnalyzerScannedUserMessage : BoundUserInterfaceMessage
{
- public readonly EntityUid? TargetEntity;
+ public readonly NetEntity? TargetEntity;
public float Temperature;
public float BloodLevel;
- public HealthAnalyzerScannedUserMessage(EntityUid? targetEntity, float temperature, float bloodLevel)
+ public HealthAnalyzerScannedUserMessage(NetEntity? targetEntity, float temperature, float bloodLevel)
{
TargetEntity = targetEntity;
Temperature = temperature;
if (args.Current is not JetpackUserComponentState state)
return;
- component.Jetpack = state.Jetpack;
+ component.Jetpack = EnsureEntity<JetpackUserComponent>(state.Jetpack, uid);
}
private void OnJetpackUserGetState(EntityUid uid, JetpackUserComponent component, ref ComponentGetState args)
{
args.State = new JetpackUserComponentState()
{
- Jetpack = component.Jetpack,
+ Jetpack = GetNetEntity(component.Jetpack),
};
}
[Serializable, NetSerializable]
protected sealed class JetpackUserComponentState : ComponentState
{
- public EntityUid Jetpack;
+ public NetEntity Jetpack;
}
}
component.RelativeRotation = state.RelativeRotation;
component.TargetRelativeRotation = state.TargetRelativeRotation;
- component.RelativeEntity = state.RelativeEntity;
+ component.RelativeEntity = EnsureEntity<InputMoverComponent>(state.RelativeEntity, uid);
component.LerpTarget = state.LerpAccumulator;
}
component.CanMove,
component.RelativeRotation,
component.TargetRelativeRotation,
- component.RelativeEntity,
+ GetNetEntity(component.RelativeEntity),
component.LerpTarget);
}
_angle = direction.ToAngle();
}
- public override bool HandleCmdMessage(ICommonSession? session, InputCmdMessage message)
+ public override bool HandleCmdMessage(IEntityManager entManager, ICommonSession? session, IFullInputCmdMessage message)
{
- if (message is not FullInputCmdMessage full || session?.AttachedEntity == null) return false;
+ if (session?.AttachedEntity == null) return false;
- if (full.State != BoundKeyState.Up)
+ if (message.State != BoundKeyState.Up)
return false;
_controller.RotateCamera(session.AttachedEntity.Value, _angle);
_controller = controller;
}
- public override bool HandleCmdMessage(ICommonSession? session, InputCmdMessage message)
+ public override bool HandleCmdMessage(IEntityManager entManager, ICommonSession? session, IFullInputCmdMessage message)
{
- if (message is not FullInputCmdMessage full || session?.AttachedEntity == null) return false;
+ if (session?.AttachedEntity == null) return false;
- if (full.State != BoundKeyState.Up)
+ if (message.State != BoundKeyState.Up)
return false;
_controller.ResetCamera(session.AttachedEntity.Value);
_dir = dir;
}
- public override bool HandleCmdMessage(ICommonSession? session, InputCmdMessage message)
+ public override bool HandleCmdMessage(IEntityManager entManager, ICommonSession? session, IFullInputCmdMessage message)
{
- if (message is not FullInputCmdMessage full || session?.AttachedEntity == null) return false;
+ if (session?.AttachedEntity == null) return false;
- _controller.HandleDirChange(session.AttachedEntity.Value, _dir, message.SubTick, full.State == BoundKeyState.Down);
+ _controller.HandleDirChange(session.AttachedEntity.Value, _dir, message.SubTick, message.State == BoundKeyState.Down);
return false;
}
}
_controller = controller;
}
- public override bool HandleCmdMessage(ICommonSession? session, InputCmdMessage message)
+ public override bool HandleCmdMessage(IEntityManager entManager, ICommonSession? session, IFullInputCmdMessage message)
{
- if (message is not FullInputCmdMessage full || session?.AttachedEntity == null) return false;
+ if (session?.AttachedEntity == null) return false;
- _controller.HandleRunChange(session.AttachedEntity.Value, full.SubTick, full.State == BoundKeyState.Down);
+ _controller.HandleRunChange(session.AttachedEntity.Value, message.SubTick, message.State == BoundKeyState.Down);
return false;
}
}
/// Target rotation relative to the <see cref="RelativeEntity"/>. Typically 0
/// </summary>
public Angle TargetRelativeRotation;
- public EntityUid? RelativeEntity;
+ public NetEntity? RelativeEntity;
public TimeSpan LerpAccumulator;
- public InputMoverComponentState(MoveButtons buttons, bool canMove, Angle relativeRotation, Angle targetRelativeRotation, EntityUid? relativeEntity, TimeSpan lerpTarget)
+ public InputMoverComponentState(MoveButtons buttons, bool canMove, Angle relativeRotation, Angle targetRelativeRotation, NetEntity? relativeEntity, TimeSpan lerpTarget)
{
Buttons = buttons;
CanMove = canMove;
_button = button;
}
- public override bool HandleCmdMessage(ICommonSession? session, InputCmdMessage message)
+ public override bool HandleCmdMessage(IEntityManager entManager, ICommonSession? session, IFullInputCmdMessage message)
{
- if (message is not FullInputCmdMessage full || session?.AttachedEntity == null) return false;
+ if (session?.AttachedEntity == null) return false;
- _controller.HandleShuttleInput(session.AttachedEntity.Value, _button, full.SubTick, full.State == BoundKeyState.Down);
+ _controller.HandleShuttleInput(session.AttachedEntity.Value, _button, message.SubTick, message.State == BoundKeyState.Down);
return false;
}
}
[Serializable, NetSerializable]
public sealed class HTNMessage : EntityEventArgs
{
- public EntityUid Uid;
+ public NetEntity Uid;
public string Text = string.Empty;
}
[Serializable, NetSerializable]
public readonly record struct NPCSteeringDebugData(
- EntityUid EntityUid,
+ NetEntity EntityUid,
Vector2 Direction,
float[] Interest,
float[] Danger,
List<Vector2> DangerPoints)
{
- public readonly EntityUid EntityUid = EntityUid;
+ public readonly NetEntity EntityUid = EntityUid;
public readonly Vector2 Direction = Direction;
public readonly float[] Interest = Interest;
public readonly float[] Danger = Danger;
[Serializable, NetSerializable]
public sealed class PathBreadcrumbsMessage : EntityEventArgs
{
- public Dictionary<EntityUid, Dictionary<Vector2i, List<PathfindingBreadcrumb>>> Breadcrumbs = new();
+ public Dictionary<NetEntity, Dictionary<Vector2i, List<PathfindingBreadcrumb>>> Breadcrumbs = new();
}
[Serializable, NetSerializable]
public sealed class PathBreadcrumbsRefreshMessage : EntityEventArgs
{
- public EntityUid GridUid;
+ public NetEntity GridUid;
public Vector2i Origin;
public List<PathfindingBreadcrumb> Data = new();
}
[Serializable, NetSerializable]
public sealed class PathPolysMessage : EntityEventArgs
{
- public Dictionary<EntityUid, Dictionary<Vector2i, Dictionary<Vector2i, List<DebugPathPoly>>>> Polys = new();
+ public Dictionary<NetEntity, Dictionary<Vector2i, Dictionary<Vector2i, List<DebugPathPoly>>>> Polys = new();
}
[Serializable, NetSerializable]
public sealed class PathPolysRefreshMessage : EntityEventArgs
{
- public EntityUid GridUid;
+ public NetEntity GridUid;
public Vector2i Origin;
/// <summary>
[Serializable, NetSerializable]
public sealed class DebugPathPoly
{
- public EntityUid GraphUid;
+ public NetEntity GraphUid;
public Vector2i ChunkOrigin;
public byte TileIndex;
public Box2 Box;
public PathfindingData Data;
- public List<EntityCoordinates> Neighbors = default!;
+ public List<NetCoordinates> Neighbors = default!;
}
[Serializable, NetSerializable]
public sealed class DebugPathPolyNeighbor
{
- public EntityCoordinates Coordinates;
+ public NetCoordinates Coordinates;
}
[Serializable, NetSerializable]
public sealed class NodeDatum
{
- public EntityUid Entity;
+ public NetEntity Entity;
public int NetId;
public int[] Reachable = Array.Empty<int>();
public string Name = "";
namespace Content.Shared.PDA
{
[Serializable, NetSerializable]
- public sealed class PdaUpdateState : CartridgeLoaderUiState
+ public sealed class PdaUpdateState : CartridgeLoaderUiState // WTF is this. what. I ... fuck me I just want net entities to work
+ // TODO purge this shit
+ //AAAAAAAAAAAAAAAA
{
public bool FlashlightEnabled;
public bool HasPen;
public bool CanPlayMusic;
public string? Address;
- public PdaUpdateState(bool flashlightEnabled, bool hasPen, PdaIdInfoText pdaOwnerInfo,
- string? stationName, bool hasUplink = false,
- bool canPlayMusic = false, string? address = null)
+ public PdaUpdateState(
+ List<NetEntity> programs,
+ NetEntity? activeUI,
+ bool flashlightEnabled,
+ bool hasPen,
+ PdaIdInfoText pdaOwnerInfo,
+ string? stationName,
+ bool hasUplink = false,
+ bool canPlayMusic = false,
+ string? address = null)
+ : base(programs, activeUI)
{
FlashlightEnabled = flashlightEnabled;
HasPen = hasPen;
[Serializable, NetSerializable]
public sealed class PreventCollideComponentState : ComponentState
{
- public EntityUid Uid;
+ public NetEntity Uid;
- public PreventCollideComponentState(PreventCollideComponent component)
+ public PreventCollideComponentState(NetEntity netEntity)
{
- Uid = component.Uid;
+ Uid = netEntity;
}
}
private void OnGetState(EntityUid uid, PreventCollideComponent component, ref ComponentGetState args)
{
- args.State = new PreventCollideComponentState(component);
+ args.State = new PreventCollideComponentState(GetNetEntity(component.Uid));
}
private void OnHandleState(EntityUid uid, PreventCollideComponent component, ref ComponentHandleState args)
if (args.Current is not PreventCollideComponentState state)
return;
- component.Uid = state.Uid;
+ component.Uid = EnsureEntity<PreventCollideComponent>(state.Uid, uid);
}
private void OnPreventCollide(EntityUid uid, PreventCollideComponent component, ref PreventCollideEvent args)
/// <summary>
/// Detects items placed on it that match a whitelist.
/// </summary>
-[RegisterComponent, NetworkedComponent, AutoGenerateComponentState, Access(typeof(ItemPlacerSystem))]
+[RegisterComponent, NetworkedComponent, Access(typeof(ItemPlacerSystem))]
public sealed partial class ItemPlacerComponent : Component
{
/// <summary>
/// The entities that are currently on top of the placer.
- /// Guaranteed to have less than <see cref="MaxEntities"/> enitites if it is set.
- /// <summary>
- [DataField("placedEntities"), AutoNetworkedField]
+ /// Guaranteed to have less than <see cref="MaxEntities"/> enitities if it is set.
+ /// </summary>
+ [DataField("placedEntities")]
public HashSet<EntityUid> PlacedEntities = new();
/// <summary>
/// The max amount of entities that can be placed at the same time.
/// If 0, there is no limit.
/// </summary>
- [ViewVariables(VVAccess.ReadWrite), DataField("maxEntities"), AutoNetworkedField]
+ [ViewVariables(VVAccess.ReadWrite), DataField("maxEntities")]
public uint MaxEntities = 1;
}
using Robust.Shared.Physics.Events;
using Robust.Shared.Physics.Systems;
using System.Linq;
+using Robust.Shared.GameStates;
+using Robust.Shared.Serialization;
namespace Content.Shared.Placeable;
SubscribeLocalEvent<ItemPlacerComponent, StartCollideEvent>(OnStartCollide);
SubscribeLocalEvent<ItemPlacerComponent, EndCollideEvent>(OnEndCollide);
+ SubscribeLocalEvent<ItemPlacerComponent, ComponentGetState>(OnPlacerGetState);
+ SubscribeLocalEvent<ItemPlacerComponent, ComponentHandleState>(OnPlacerHandleState);
+ }
+
+ private void OnPlacerHandleState(EntityUid uid, ItemPlacerComponent component, ref ComponentHandleState args)
+ {
+ if (args.Current is not ItemPlacerComponentState state)
+ return;
+
+ component.MaxEntities = state.MaxEntities;
+ component.PlacedEntities.Clear();
+ var ents = EnsureEntitySet<ItemPlacerComponent>(state.Entities, uid);
+ component.PlacedEntities.UnionWith(ents);
+ }
+
+ private void OnPlacerGetState(EntityUid uid, ItemPlacerComponent component, ref ComponentGetState args)
+ {
+ args.State = new ItemPlacerComponentState()
+ {
+ MaxEntities = component.MaxEntities,
+ Entities = GetNetEntitySet(component.PlacedEntities),
+ };
}
private void OnStartCollide(EntityUid uid, ItemPlacerComponent comp, ref StartCollideEvent args)
_placeableSurface.SetPlaceable(uid, true);
}
+
+ [Serializable, NetSerializable]
+ private sealed class ItemPlacerComponentState : ComponentState
+ {
+ public uint MaxEntities;
+ public HashSet<NetEntity> Entities = default!;
+ }
}
/// <summary>
/// Raised on the <see cref="ItemPlacer"/> when an item is placed and it is under the item limit.
/// </summary>
[ByRefEvent]
-public record struct ItemPlacedEvent(EntityUid OtherEntity);
+public readonly record struct ItemPlacedEvent(EntityUid OtherEntity);
/// <summary>
/// Raised on the <see cref="ItemPlacer"/> when an item is removed from it.
/// </summary>
[ByRefEvent]
-public record struct ItemRemovedEvent(EntityUid OtherEntity);
+public readonly record struct ItemRemovedEvent(EntityUid OtherEntity);
namespace Content.Shared.Pointing;
// TODO just make pointing properly predicted?
+// So true
/// <summary>
/// Event raised when someone runs the client-side pointing verb.
/// </summary>
[Serializable, NetSerializable]
public sealed class PointingAttemptEvent : EntityEventArgs
{
- public EntityUid Target;
+ public NetEntity Target;
- public PointingAttemptEvent(EntityUid target)
+ public PointingAttemptEvent(NetEntity target)
{
Target = target;
}
[Serializable, NetSerializable]
public sealed class PopupCoordinatesEvent : PopupEvent
{
- public EntityCoordinates Coordinates { get; }
+ public NetCoordinates Coordinates { get; }
- public PopupCoordinatesEvent(string message, PopupType type, EntityCoordinates coordinates) : base(message, type)
+ public PopupCoordinatesEvent(string message, PopupType type, NetCoordinates coordinates) : base(message, type)
{
Coordinates = coordinates;
}
[Serializable, NetSerializable]
public sealed class PopupEntityEvent : PopupEvent
{
- public EntityUid Uid { get; }
+ public NetEntity Uid { get; }
- public PopupEntityEvent(string message, PopupType type, EntityUid uid) : base(message, type)
+ public PopupEntityEvent(string message, PopupType type, NetEntity uid) : base(message, type)
{
Uid = uid;
}
args.Handled = true;
- _doAfter.TryStartDoAfter(new DoAfterArgs(args.User, component.RemovalTime.Value,
+ _doAfter.TryStartDoAfter(new DoAfterArgs(EntityManager, args.User, component.RemovalTime.Value,
new RemoveEmbeddedProjectileEvent(), eventTarget: uid, target: uid)
{
DistanceThreshold = SharedInteractionSystem.InteractionRange,
public sealed class ImpactEffectEvent : EntityEventArgs
{
public string Prototype;
- public EntityCoordinates Coordinates;
+ public NetCoordinates Coordinates;
- public ImpactEffectEvent(string prototype, EntityCoordinates coordinates)
+ public ImpactEffectEvent(string prototype, NetCoordinates coordinates)
{
Prototype = prototype;
Coordinates = coordinates;
[Serializable, NetSerializable]
public sealed class PullableComponentState : ComponentState
{
- public readonly EntityUid? Puller;
+ public readonly NetEntity? Puller;
- public PullableComponentState(EntityUid? puller)
+ public PullableComponentState(NetEntity? puller)
{
Puller = puller;
}
private void OnGetState(EntityUid uid, SharedPullableComponent component, ref ComponentGetState args)
{
- args.State = new PullableComponentState(component.Puller);
+ args.State = new PullableComponentState(GetNetEntity(component.Puller));
}
private void OnHandleState(EntityUid uid, SharedPullableComponent component, ref ComponentHandleState args)
if (args.Current is not PullableComponentState state)
return;
- if (!state.Puller.HasValue)
+ var puller = EnsureEntity<SharedPullableComponent>(state.Puller, uid);
+
+ if (!puller.HasValue)
{
ForceDisconnectPullable(component);
return;
}
- if (component.Puller == state.Puller)
+ if (component.Puller == puller)
{
// don't disconnect and reconnect a puller for no reason
return;
}
- if (!TryComp<SharedPullerComponent?>(state.Puller.Value, out var comp))
+ if (!TryComp<SharedPullerComponent>(puller, out var comp))
{
- Log.Error($"Pullable state for entity {ToPrettyString(uid)} had invalid puller entity {ToPrettyString(state.Puller.Value)}");
+ Log.Error($"Pullable state for entity {ToPrettyString(uid)} had invalid puller entity {ToPrettyString(puller.Value)}");
// ensure it disconnects from any different puller, still
ForceDisconnectPullable(component);
return;
return;
}
- var doAfterArgs = new DoAfterArgs(user, comp.Delay, new RCDDoAfterEvent(location, comp.Mode), uid, target: args.Target, used: uid)
+ var doAfterArgs = new DoAfterArgs(EntityManager, user, comp.Delay, new RCDDoAfterEvent(GetNetCoordinates(location), comp.Mode), uid, target: args.Target, used: uid)
{
BreakOnDamage = true,
NeedHand = true,
if (args.Event?.DoAfter?.Args == null)
return;
- var location = args.Event.Location;
+ var location = GetCoordinates(args.Event.Location);
var gridId = location.GetGridUid(EntityManager);
if (!HasComp<MapGridComponent>(gridId))
return;
var user = args.User;
- var location = args.Location;
+ var location = GetCoordinates(args.Location);
var gridId = location.GetGridUid(EntityManager);
if (!HasComp<MapGridComponent>(gridId))
public sealed partial class RCDDoAfterEvent : DoAfterEvent
{
[DataField("location", required: true)]
- public EntityCoordinates Location = default!;
+ public NetCoordinates Location = default!;
[DataField("startingMode", required: true)]
public RcdMode StartingMode = default!;
{
}
- public RCDDoAfterEvent(EntityCoordinates location, RcdMode startingMode)
+ public RCDDoAfterEvent(NetCoordinates location, RcdMode startingMode)
{
Location = location;
StartingMode = startingMode;
public float CurrentRadiation;
public GeigerDangerLevel DangerLevel;
public bool IsEnabled;
- public EntityUid? User;
+ public NetEntity? User;
}
[Serializable, NetSerializable]
/// <summary>
/// Key is grids uid. Values are tiles with their rad resistance.
/// </summary>
- public readonly Dictionary<EntityUid, Dictionary<Vector2i, float>> Grids;
+ public readonly Dictionary<NetEntity, Dictionary<Vector2i, float>> Grids;
- public OnRadiationOverlayResistanceUpdateEvent(Dictionary<EntityUid, Dictionary<Vector2i, float>> grids)
+ public OnRadiationOverlayResistanceUpdateEvent(Dictionary<NetEntity, Dictionary<Vector2i, float>> grids)
{
Grids = grids;
}
/// <summary>
/// Uid of entity with <see cref="RadiationSourceComponent"/>.
/// </summary>
- public EntityUid SourceUid;
+ public NetEntity SourceUid;
/// <summary>
/// World coordinates of radiation source.
/// </summary>
/// <summary>
/// Uid of entity with radiation receiver component.
/// </summary>
- public EntityUid DestinationUid;
+ public NetEntity DestinationUid;
/// <summary>
/// World coordinates of radiation receiver.
/// </summary>
/// Last tile may have negative value if ray has lost all intensity.
/// Grid traversal order isn't guaranteed.
/// </remarks>
- public Dictionary<EntityUid, List<(Vector2i, float)>> Blockers = new();
+ public Dictionary<NetEntity, List<(Vector2i, float)>> Blockers = new();
- public RadiationRay(MapId mapId, EntityUid sourceUid, Vector2 source,
- EntityUid destinationUid, Vector2 destination, float rads)
+ public RadiationRay(MapId mapId, NetEntity sourceUid, Vector2 source,
+ NetEntity destinationUid, Vector2 destination, float rads)
{
MapId = mapId;
SourceUid = sourceUid;
return;
}
- var doAfterArgs = new DoAfterArgs(uid, comp.Delay, new ResearchStealDoAfterEvent(), target: target, used: uid, eventTarget: uid)
+ var doAfterArgs = new DoAfterArgs(EntityManager, uid, comp.Delay, new ResearchStealDoAfterEvent(), target: target, used: uid, eventTarget: uid)
{
BreakOnDamage = true,
BreakOnUserMove = true,
var ev = new FultonedDoAfterEvent();
_doAfter.TryStartDoAfter(
- new DoAfterArgs(args.User, component.ApplyFultonDuration, ev, args.Target, args.Target, args.Used)
+ new DoAfterArgs(EntityManager, args.User, component.ApplyFultonDuration, ev, args.Target, args.Target, args.Used)
{
CancelDuplicate = true,
MovementThreshold = 0.5f,
[Serializable, NetSerializable]
protected sealed class FultonAnimationMessage : EntityEventArgs
{
- public EntityUid Entity;
- public EntityCoordinates Coordinates;
+ public NetEntity Entity;
+ public NetCoordinates Coordinates;
}
}
/// <summary>
/// The relevant coordinates to base the radar around.
/// </summary>
- public EntityCoordinates? Coordinates;
+ public NetCoordinates? Coordinates;
/// <summary>
/// The relevant rotation to rotate the angle around.
public RadarConsoleBoundInterfaceState(
float maxRange,
- EntityCoordinates? coordinates,
+ NetCoordinates? coordinates,
Angle? angle,
List<DockingInterfaceState> docks)
{
[Serializable, NetSerializable]
public sealed class DockingInterfaceState
{
- public EntityCoordinates Coordinates;
+ public NetCoordinates Coordinates;
public Angle Angle;
- public EntityUid Entity;
+ public NetEntity Entity;
public bool Connected;
public Color Color;
public Color HighlightedColor;
/// </summary>
public readonly TimeSpan FTLTime;
- public List<(EntityUid Entity, string Destination, bool Enabled)> Destinations;
+ public List<(NetEntity Entity, string Destination, bool Enabled)> Destinations;
public ShuttleConsoleBoundInterfaceState(
FTLState ftlState,
TimeSpan ftlTime,
- List<(EntityUid Entity, string Destination, bool Enabled)> destinations,
+ List<(NetEntity Entity, string Destination, bool Enabled)> destinations,
float maxRange,
- EntityCoordinates? coordinates,
+ NetCoordinates? coordinates,
Angle? angle,
List<DockingInterfaceState> docks) : base(maxRange, coordinates, angle, docks)
{
[Serializable, NetSerializable]
public sealed class AutodockRequestMessage : BoundUserInterfaceMessage
{
- public EntityUid DockEntity;
+ public NetEntity DockEntity;
}
[Serializable, NetSerializable]
public sealed class EmergencyShuttlePositionMessage : EntityEventArgs
{
- public EntityUid? StationUid;
+ public NetEntity? StationUid;
public Box2? Position;
}
[Serializable, NetSerializable]
public sealed class ShuttleConsoleFTLRequestMessage : BoundUserInterfaceMessage
{
- public EntityUid Destination;
+ public NetEntity Destination;
}
[Serializable, NetSerializable]
public sealed class StopAutodockRequestMessage : BoundUserInterfaceMessage
{
- public EntityUid DockEntity;
+ public NetEntity DockEntity;
}
[Serializable, NetSerializable]
public sealed class UndockRequestMessage : BoundUserInterfaceMessage
{
- public EntityUid DockEntity;
+ public NetEntity DockEntity;
}
[Serializable, NetSerializable]
protected sealed class PilotComponentState : ComponentState
{
- public EntityUid? Console { get; }
+ public NetEntity? Console { get; }
- public PilotComponentState(EntityUid? uid)
+ public PilotComponentState(NetEntity? uid)
{
Console = uid;
}
[Serializable, NetSerializable]
public sealed class BorgRemoveModuleBuiMessage : BoundUserInterfaceMessage
{
- public EntityUid Module;
+ public NetEntity Module;
- public BorgRemoveModuleBuiMessage(EntityUid module)
+ public BorgRemoveModuleBuiMessage(NetEntity module)
{
Module = module;
}
public string BrainContainerId = "borg_brain";
[ViewVariables(VVAccess.ReadWrite)]
- public ContainerSlot BrainContainer = new();
+ public ContainerSlot BrainContainer = default!;
public EntityUid? BrainEntity => BrainContainer.ContainedEntity;
#endregion
[NetSerializable, Serializable]
public sealed class StationsUpdatedEvent : EntityEventArgs
{
- public readonly HashSet<EntityUid> Stations;
+ public readonly HashSet<NetEntity> Stations;
- public StationsUpdatedEvent(HashSet<EntityUid> stations)
+ public StationsUpdatedEvent(HashSet<NetEntity> stations)
{
Stations = stations;
}
/// <summary>
/// Current selected key.
/// </summary>
- public StationRecordKey? SelectedKey { get; }
+ public (NetEntity, uint)? SelectedKey { get; }
public GeneralStationRecord? Record { get; }
- public Dictionary<StationRecordKey, string>? RecordListing { get; }
+ public Dictionary<(NetEntity, uint), string>? RecordListing { get; }
public GeneralStationRecordsFilter? Filter { get; }
- public GeneralStationRecordConsoleState(StationRecordKey? key, GeneralStationRecord? record,
- Dictionary<StationRecordKey, string>? recordListing, GeneralStationRecordsFilter? newFilter)
+ public GeneralStationRecordConsoleState((NetEntity, uint)? key, GeneralStationRecord? record,
+ Dictionary<(NetEntity, uint), string>? recordListing, GeneralStationRecordsFilter? newFilter)
{
SelectedKey = key;
Record = record;
[Serializable, NetSerializable]
public sealed class SelectGeneralStationRecord : BoundUserInterfaceMessage
{
- public StationRecordKey? SelectedKey { get; }
+ public (NetEntity, uint)? SelectedKey { get; }
- public SelectGeneralStationRecord(StationRecordKey? selectedKey)
+ public SelectGeneralStationRecord((NetEntity, uint)? selectedKey)
{
SelectedKey = selectedKey;
}
--- /dev/null
+namespace Content.Shared.StationRecords;
+
+public abstract class SharedStationRecordsSystem : EntitySystem
+{
+ public StationRecordKey? Convert((NetEntity, uint)? input)
+ {
+ return input == null ? null : Convert(input.Value);
+ }
+
+ public (NetEntity, uint)? Convert(StationRecordKey? input)
+ {
+ return input == null ? null : Convert(input.Value);
+ }
+
+ public StationRecordKey Convert((NetEntity, uint) input)
+ {
+ return new StationRecordKey(input.Item2, GetEntity(input.Item1));
+ }
+ public (NetEntity, uint) Convert(StationRecordKey input)
+ {
+ return (GetNetEntity(input.OriginStation), input.Id);
+ }
+
+ public List<(NetEntity, uint)> Convert(ICollection<StationRecordKey> input)
+ {
+ var result = new List<(NetEntity, uint)>(input.Count);
+ foreach (var entry in input)
+ {
+ result.Add(Convert(entry));
+ }
+ return result;
+ }
+
+ public List<StationRecordKey> Convert(ICollection<(NetEntity, uint)> input)
+ {
+ var result = new List<StationRecordKey>(input.Count);
+ foreach (var entry in input)
+ {
+ result.Add(Convert(entry));
+ }
+ return result;
+ }
+}
-using Robust.Shared.Serialization;
-
namespace Content.Shared.StationRecords;
// Station record keys. These should be stored somewhere,
// preferably within an ID card.
-[Serializable, NetSerializable]
-public readonly struct StationRecordKey
+public readonly struct StationRecordKey : IEquatable<StationRecordKey>
{
- [ViewVariables]
- public uint ID { get; }
+ [DataField("id")]
+ public readonly uint Id;
+
+ [DataField("station")]
+ public readonly EntityUid OriginStation;
- [ViewVariables]
- public EntityUid OriginStation { get; }
+ public static StationRecordKey Invalid = default;
public StationRecordKey(uint id, EntityUid originStation)
{
- ID = id;
+ Id = id;
OriginStation = originStation;
}
+
+ public bool Equals(StationRecordKey other)
+ {
+ return Id == other.Id && OriginStation.Id == other.OriginStation.Id;
+ }
+
+ public override bool Equals(object? obj)
+ {
+ return obj is StationRecordKey other && Equals(other);
+ }
+
+ public override int GetHashCode()
+ {
+ return HashCode.Combine(Id, OriginStation);
+ }
+
+ public bool IsValid() => OriginStation.IsValid();
}
[Serializable, NetSerializable]
public sealed class StationRecordKeyStorageComponentState : ComponentState
{
- public StationRecordKey? Key;
+ public (NetEntity, uint)? Key;
- public StationRecordKeyStorageComponentState(StationRecordKey? key)
+ public StationRecordKeyStorageComponentState((NetEntity, uint)? key)
{
Key = key;
}
public sealed class StationRecordKeyStorageSystem : EntitySystem
{
+ [Dependency] private readonly SharedStationRecordsSystem _records = default!;
+
public override void Initialize()
{
base.Initialize();
private void OnGetState(EntityUid uid, StationRecordKeyStorageComponent component, ref ComponentGetState args)
{
- args.State = new StationRecordKeyStorageComponentState(component.Key);
+ args.State = new StationRecordKeyStorageComponentState(_records.Convert(component.Key));
}
private void OnHandleState(EntityUid uid, StationRecordKeyStorageComponent component, ref ComponentHandleState args)
{
if (args.Current is not StationRecordKeyStorageComponentState state)
return;
- component.Key = state.Key;
+ component.Key = _records.Convert(state.Key);
}
/// <summary>
}
keyStorage.Key = key;
- Dirty(keyStorage);
+ Dirty(uid, keyStorage);
}
/// <summary>
{
public float IntersectRatio { get; }
public float RequiredTriggerSpeed { get; }
- public readonly HashSet<EntityUid> CurrentlySteppedOn;
- public readonly HashSet<EntityUid> Colliding;
+ public readonly HashSet<NetEntity> CurrentlySteppedOn;
+ public readonly HashSet<NetEntity> Colliding;
public readonly bool Active;
- public StepTriggerComponentState(float intersectRatio, HashSet<EntityUid> currentlySteppedOn, HashSet<EntityUid> colliding, float requiredTriggerSpeed, bool active)
+ public StepTriggerComponentState(float intersectRatio, HashSet<NetEntity> currentlySteppedOn, HashSet<NetEntity> colliding, float requiredTriggerSpeed, bool active)
{
IntersectRatio = intersectRatio;
CurrentlySteppedOn = currentlySteppedOn;
component.RequiredTriggerSpeed = state.RequiredTriggerSpeed;
component.IntersectRatio = state.IntersectRatio;
component.Active = state.Active;
+ var stepped = EnsureEntitySet<StepTriggerComponent>(state.CurrentlySteppedOn, uid);
+ var colliding = EnsureEntitySet<StepTriggerComponent>(state.CurrentlySteppedOn, uid);
- if (!component.CurrentlySteppedOn.SetEquals(state.CurrentlySteppedOn))
- {
- component.CurrentlySteppedOn.Clear();
- component.CurrentlySteppedOn.UnionWith(state.CurrentlySteppedOn);
- }
+ component.CurrentlySteppedOn.Clear();
+ component.CurrentlySteppedOn.UnionWith(stepped);
- if (!component.Colliding.SetEquals(state.Colliding))
- {
- component.Colliding.Clear();
- component.Colliding.UnionWith(state.Colliding);
- }
+ component.Colliding.Clear();
+ component.Colliding.UnionWith(colliding);
if (component.Colliding.Count > 0)
{
}
}
- private static void TriggerGetState(EntityUid uid, StepTriggerComponent component, ref ComponentGetState args)
+ private void TriggerGetState(EntityUid uid, StepTriggerComponent component, ref ComponentGetState args)
{
args.State = new StepTriggerComponentState(
component.IntersectRatio,
- component.CurrentlySteppedOn,
- component.Colliding,
+ GetNetEntitySet(component.CurrentlySteppedOn),
+ GetNetEntitySet(component.Colliding),
component.RequiredTriggerSpeed,
component.Active);
}
[Serializable, NetSerializable]
public sealed class BinComponentState : ComponentState
{
- public List<EntityUid> Items;
+ public List<NetEntity> Items;
public EntityWhitelist? Whitelist;
public int MaxItems;
- public BinComponentState(List<EntityUid> items, EntityWhitelist? whitelist, int maxItems)
+ public BinComponentState(List<NetEntity> items, EntityWhitelist? whitelist, int maxItems)
{
Items = items;
Whitelist = whitelist;
private void OnGetState(EntityUid uid, BinComponent component, ref ComponentGetState args)
{
- args.State = new BinComponentState(component.Items, component.Whitelist, component.MaxItems);
+ args.State = new BinComponentState(GetNetEntityList(component.Items), component.Whitelist, component.MaxItems);
}
private void OnHandleState(EntityUid uid, BinComponent component, ref ComponentHandleState args)
if (args.Current is not BinComponentState state)
return;
- component.Items = new List<EntityUid>(state.Items);
+ component.Items = EnsureEntityList<BinComponent>(state.Items, uid);
component.Whitelist = state.Whitelist;
component.MaxItems = state.MaxItems;
}
StartDoAfter(uid, args.Target, args.User, dumpable);
},
Text = Loc.GetString("dump-disposal-verb-name", ("unit", args.Target)),
- IconEntity = uid
+ IconEntity = GetNetEntity(uid)
};
args.Verbs.Add(verb);
}
StartDoAfter(uid, args.Target, args.User, dumpable);
},
Text = Loc.GetString("dump-placeable-verb-name", ("surface", args.Target)),
- IconEntity = uid
+ IconEntity = GetNetEntity(uid)
};
args.Verbs.Add(verb);
}
float delay = storage.StoredEntities.Count * (float) dumpable.DelayPerItem.TotalSeconds * dumpable.Multiplier;
- _doAfterSystem.TryStartDoAfter(new DoAfterArgs(userUid, delay, new DumpableDoAfterEvent(), storageUid, target: targetUid, used: storageUid)
+ _doAfterSystem.TryStartDoAfter(new DoAfterArgs(EntityManager, userUid, delay, new DumpableDoAfterEvent(), storageUid, target: targetUid, used: storageUid)
{
BreakOnTargetMove = true,
BreakOnUserMove = true,
public sealed partial class AreaPickupDoAfterEvent : DoAfterEvent
{
[DataField("entities", required: true)]
- public IReadOnlyList<EntityUid> Entities = default!;
+ public IReadOnlyList<NetEntity> Entities = default!;
private AreaPickupDoAfterEvent()
{
}
- public AreaPickupDoAfterEvent(List<EntityUid> entities)
+ public AreaPickupDoAfterEvent(List<NetEntity> entities)
{
Entities = entities;
}
[Serializable, NetSerializable]
public sealed class StorageBoundUserInterfaceState : BoundUserInterfaceState
{
- public readonly List<EntityUid> StoredEntities;
+ public readonly List<NetEntity> StoredEntities;
public readonly int StorageSizeUsed;
public readonly int StorageCapacityMax;
- public StorageBoundUserInterfaceState(List<EntityUid> storedEntities, int storageSizeUsed, int storageCapacityMax)
+ public StorageBoundUserInterfaceState(List<NetEntity> storedEntities, int storageSizeUsed, int storageCapacityMax)
{
StoredEntities = storedEntities;
StorageSizeUsed = storageSizeUsed;
[Serializable, NetSerializable]
public sealed class StorageInteractWithItemEvent : BoundUserInterfaceMessage
{
- public readonly EntityUid InteractedItemUID;
- public StorageInteractWithItemEvent(EntityUid interactedItemUID)
+ public readonly NetEntity InteractedItemUID;
+ public StorageInteractWithItemEvent(NetEntity interactedItemUID)
{
InteractedItemUID = interactedItemUID;
}
[Serializable, NetSerializable]
public sealed class AnimateInsertingEntitiesEvent : EntityEventArgs
{
- public readonly EntityUid Storage;
- public readonly List<EntityUid> StoredEntities;
- public readonly List<EntityCoordinates> EntityPositions;
+ public readonly NetEntity Storage;
+ public readonly List<NetEntity> StoredEntities;
+ public readonly List<NetCoordinates> EntityPositions;
public readonly List<Angle> EntityAngles;
- public AnimateInsertingEntitiesEvent(EntityUid storage, List<EntityUid> storedEntities, List<EntityCoordinates> entityPositions, List<Angle> entityAngles)
+ public AnimateInsertingEntitiesEvent(NetEntity storage, List<NetEntity> storedEntities, List<NetCoordinates> entityPositions, List<Angle> entityAngles)
{
Storage = storage;
StoredEntities = storedEntities;
{
// The active camera on the monitor. If this is null, the part of the UI
// that contains the monitor should clear.
- public EntityUid? ActiveCamera { get; }
+ public NetEntity? ActiveCamera { get; }
// Currently available subnets. Does not send the entirety of the possible
// cameras to view because that could be really, really large
// Known cameras, by address and name.
public Dictionary<string, string> Cameras { get; }
- public SurveillanceCameraMonitorUiState(EntityUid? activeCamera, HashSet<string> subnets, string activeAddress, string activeSubnet, Dictionary<string, string> cameras)
+ public SurveillanceCameraMonitorUiState(NetEntity? activeCamera, HashSet<string> subnets, string activeAddress, string activeSubnet, Dictionary<string, string> cameras)
{
ActiveCamera = activeCamera;
Subnets = subnets;
/// <summary>
/// The UID of the entity being dragged.
/// </summary>
- public EntityUid DraggedEntityUid;
+ public NetEntity DraggedEntityUid;
public bool IsDragging;
- public TabletopDraggingPlayerChangedEvent(EntityUid draggedEntityUid, bool isDragging)
+ public TabletopDraggingPlayerChangedEvent(NetEntity draggedEntityUid, bool isDragging)
{
DraggedEntityUid = draggedEntityUid;
IsDragging = isDragging;
/// <summary>
/// The UID of the entity being moved.
/// </summary>
- public EntityUid MovedEntityUid { get; }
+ public NetEntity MovedEntityUid { get; }
/// <summary>
/// The new coordinates of the entity being moved.
/// <summary>
/// The UID of the table the entity is being moved on.
/// </summary>
- public EntityUid TableUid { get; }
+ public NetEntity TableUid { get; }
- public TabletopMoveEvent(EntityUid movedEntityUid, MapCoordinates coordinates, EntityUid tableUid)
+ public TabletopMoveEvent(NetEntity movedEntityUid, MapCoordinates coordinates, NetEntity tableUid)
{
MovedEntityUid = movedEntityUid;
Coordinates = coordinates;
[Serializable, NetSerializable]
public sealed class TabletopPlayEvent : EntityEventArgs
{
- public EntityUid TableUid;
- public EntityUid CameraUid;
+ public NetEntity TableUid;
+ public NetEntity CameraUid;
public string Title;
public Vector2i Size;
- public TabletopPlayEvent(EntityUid tableUid, EntityUid cameraUid, string title, Vector2i size)
+ public TabletopPlayEvent(NetEntity tableUid, NetEntity cameraUid, string title, Vector2i size)
{
TableUid = tableUid;
CameraUid = cameraUid;
/// <summary>
/// The entity UID of the table associated with this tabletop game.
/// </summary>
- public EntityUid TableUid;
+ public NetEntity TableUid;
- public TabletopStopPlayingEvent(EntityUid tableUid)
+ public TabletopStopPlayingEvent(NetEntity tableUid)
{
TableUid = tableUid;
}
if (args.SenderSession is not { AttachedEntity: { } playerEntity } playerSession)
return;
- if (!CanSeeTable(playerEntity, msg.TableUid) || !CanDrag(playerEntity, msg.MovedEntityUid, out _))
+ var table = GetEntity(msg.TableUid);
+ var moved = GetEntity(msg.MovedEntityUid);
+
+ if (!CanSeeTable(playerEntity, table) || !CanDrag(playerEntity, moved, out _))
return;
// Move the entity and dirty it (we use the map ID from the entity so noone can try to be funny and move the item to another map)
- var transform = EntityManager.GetComponent<TransformComponent>(msg.MovedEntityUid);
- _transforms.SetParent(msg.MovedEntityUid, transform, _mapMan.GetMapEntityId(transform.MapID));
+ var transform = EntityManager.GetComponent<TransformComponent>(moved);
+ _transforms.SetParent(moved, transform, _mapMan.GetMapEntityId(transform.MapID));
_transforms.SetLocalPositionNoLerp(transform, msg.Coordinates.Position);
}
private void OnDraggingPlayerChanged(TabletopDraggingPlayerChangedEvent msg, EntitySessionEventArgs args)
{
- var dragged = msg.DraggedEntityUid;
+ var dragged = GetEntity(msg.DraggedEntityUid);
if (!TryComp(dragged, out TabletopDraggableComponent? draggableComponent))
return;
draggableComponent.DraggingPlayer = msg.IsDragging ? args.SenderSession.UserId : null;
- Dirty(draggableComponent);
+ Dirty(dragged, draggableComponent);
if (!TryComp(dragged, out AppearanceComponent? appearance))
return;
[Serializable, NetSerializable]
public sealed class TabletopRequestTakeOut : EntityEventArgs
{
- public EntityUid Entity;
- public EntityUid TableUid;
+ public NetEntity Entity;
+ public NetEntity TableUid;
}
#region Utility
[Serializable, NetSerializable]
public sealed class LinkedEntityComponentState : ComponentState
{
- public HashSet<EntityUid> LinkedEntities;
+ public HashSet<NetEntity> LinkedEntities;
- public LinkedEntityComponentState(HashSet<EntityUid> linkedEntities)
+ public LinkedEntityComponentState(HashSet<NetEntity> linkedEntities)
{
LinkedEntities = linkedEntities;
}
[Serializable, NetSerializable]
public sealed class PortalTimeoutComponentState : ComponentState
{
- public EntityUid? EnteredPortal;
+ public NetEntity? EnteredPortal;
- public PortalTimeoutComponentState(EntityUid? enteredPortal)
+ public PortalTimeoutComponentState(NetEntity? enteredPortal)
{
EnteredPortal = enteredPortal;
}
private void OnGetState(EntityUid uid, LinkedEntityComponent component, ref ComponentGetState args)
{
- args.State = new LinkedEntityComponentState(component.LinkedEntities);
+ args.State = new LinkedEntityComponentState(GetNetEntitySet(component.LinkedEntities));
}
private void OnHandleState(EntityUid uid, LinkedEntityComponent component, ref ComponentHandleState args)
{
if (args.Current is LinkedEntityComponentState state)
- component.LinkedEntities = state.LinkedEntities;
+ {
+ component.LinkedEntities = EnsureEntitySet<LinkedEntityComponent>(state.LinkedEntities, uid);
+ }
}
private void OnLinkShutdown(EntityUid uid, LinkedEntityComponent component, ComponentShutdown args)
private void OnGetState(EntityUid uid, PortalTimeoutComponent component, ref ComponentGetState args)
{
- args.State = new PortalTimeoutComponentState(component.EnteredPortal);
+ args.State = new PortalTimeoutComponentState(GetNetEntity(component.EnteredPortal));
}
private void OnHandleState(EntityUid uid, PortalTimeoutComponent component, ref ComponentHandleState args)
{
if (args.Current is PortalTimeoutComponentState state)
- component.EnteredPortal = state.EnteredPortal;
+ component.EnteredPortal = EnsureEntity<PortalTimeoutComponent>(state.EnteredPortal, uid);
}
private bool ShouldCollide(string ourId, string otherId, Fixture our, Fixture other)
[RegisterComponent, NetworkedComponent]
public sealed partial class ThrownItemComponent : Component
{
+ [ViewVariables(VVAccess.ReadWrite), DataField("thrower")]
public EntityUid? Thrower { get; set; }
}
[Serializable, NetSerializable]
public sealed class ThrownItemComponentState : ComponentState
{
- public EntityUid? Thrower { get; }
+ public NetEntity? Thrower { get; }
- public ThrownItemComponentState(EntityUid? thrower)
+ public ThrownItemComponentState(NetEntity? thrower)
{
Thrower = thrower;
}
private void OnGetState(EntityUid uid, ThrownItemComponent component, ref ComponentGetState args)
{
- args.State = new ThrownItemComponentState(component.Thrower);
+ args.State = new ThrownItemComponentState(GetNetEntity(component.Thrower));
}
private void OnHandleState(EntityUid uid, ThrownItemComponent component, ref ComponentHandleState args)
return;
}
- component.Thrower = state.Thrower.Value;
+ component.Thrower = EnsureEntity<ThrownItemComponent>(state.Thrower.Value, uid);
}
private void ThrowItem(EntityUid uid, ThrownItemComponent component, ThrownEvent args)
ev.DoAfter = args.DoAfter;
if (args.OriginalTarget != null)
- RaiseLocalEvent(args.OriginalTarget.Value, (object) ev);
+ RaiseLocalEvent(GetEntity(args.OriginalTarget.Value), (object) ev);
else
RaiseLocalEvent((object) ev);
}
if (!CanStartToolUse(tool, user, target, toolQualitiesNeeded, toolComponent))
return false;
- var toolEvent = new ToolDoAfterEvent(doAfterEv, target);
- var doAfterArgs = new DoAfterArgs(user, delay / toolComponent.SpeedModifier, toolEvent, tool, target: target, used: tool)
+ var toolEvent = new ToolDoAfterEvent(doAfterEv, GetNetEntity(target));
+ var doAfterArgs = new DoAfterArgs(EntityManager, user, delay / toolComponent.SpeedModifier, toolEvent, tool, target: target, used: tool)
{
BreakOnDamage = true,
BreakOnTargetMove = true,
/// Entity that the wrapped do after event will get directed at. If null, event will be broadcast.
/// </summary>
[DataField("target")]
- public EntityUid? OriginalTarget;
+ public NetEntity? OriginalTarget;
[DataField("wrappedEvent")]
public DoAfterEvent WrappedEvent = default!;
{
}
- public ToolDoAfterEvent(DoAfterEvent wrappedEvent, EntityUid? originalTarget)
+ public ToolDoAfterEvent(DoAfterEvent wrappedEvent, NetEntity? originalTarget)
{
DebugTools.Assert(wrappedEvent.GetType().HasCustomAttribute<NetSerializableAttribute>(), "Tool event is not serializable");
protected sealed partial class LatticeCuttingCompleteEvent : DoAfterEvent
{
[DataField("coordinates", required:true)]
- public EntityCoordinates Coordinates;
+ public NetCoordinates Coordinates;
private LatticeCuttingCompleteEvent()
{
}
- public LatticeCuttingCompleteEvent(EntityCoordinates coordinates)
+ public LatticeCuttingCompleteEvent(NetCoordinates coordinates)
{
Coordinates = coordinates;
}
[Serializable, NetSerializable]
protected sealed partial class TilePryingDoAfterEvent : DoAfterEvent
{
- [DataField("coordinates", required:true)]
- public EntityCoordinates Coordinates;
+ [DataField("coordinates", required: true)]
+ public NetCoordinates Coordinates;
private TilePryingDoAfterEvent()
{
}
- public TilePryingDoAfterEvent(EntityCoordinates coordinates)
+ public TilePryingDoAfterEvent(NetCoordinates coordinates)
{
Coordinates = coordinates;
}
[Serializable, NetSerializable]
public sealed class RiderComponentState : ComponentState
{
- public EntityUid? Entity;
+ public NetEntity? Entity;
}
{
args.State = new RiderComponentState()
{
- Entity = component.Vehicle,
+ Entity = GetNetEntity(component.Vehicle),
};
}
args.Handled = true;
- var doAfterArgs = new DoAfterArgs(args.User, (float) component.RestockDelay.TotalSeconds, new RestockDoAfterEvent(), target,
+ var doAfterArgs = new DoAfterArgs(EntityManager, args.User, (float) component.RestockDelay.TotalSeconds, new RestockDoAfterEvent(), target,
target: target, used: uid)
{
BreakOnTargetMove = true,
if (user == null)
return;
+ var target = GetEntity(args.Target);
+
// It is possible that client-side prediction can cause this event to be raised after the target entity has
// been deleted. So we need to check that the entity still exists.
- if (Deleted(args.Target) || Deleted(user))
+ if (Deleted(target) || Deleted(user))
return;
// Get the list of verbs. This effectively also checks that the requested verb is in fact a valid verb that
// the user can perform.
- var verbs = GetLocalVerbs(args.Target, user.Value, args.RequestedVerb.GetType());
+ var verbs = GetLocalVerbs(target, user.Value, args.RequestedVerb.GetType());
// Note that GetLocalVerbs might waste time checking & preparing unrelated verbs even though we know
// precisely which one we want to run. However, MOST entities will only have 1 or 2 verbs of a given type.
// Find the requested verb.
if (verbs.TryGetValue(args.RequestedVerb, out var verb))
- ExecuteVerb(verb, user.Value, args.Target);
+ ExecuteVerb(verb, user.Value, target);
}
/// <summary>
/// If this is not null, and no icon or icon texture were specified, a sprite view of this entity will be
/// used as the icon for this verb.
/// </summary>
- public EntityUid? IconEntity;
+ public NetEntity? IconEntity;
/// <summary>
/// Whether or not to close the context menu after using it to run this verb.
typeof(AlternativeVerb),
typeof(ActivationVerb),
typeof(ExamineVerb),
- typeof(EquipmentVerb)
+ typeof(EquipmentVerb)
};
}
[Serializable, NetSerializable]
public sealed class RequestServerVerbsEvent : EntityEventArgs
{
- public readonly EntityUid EntityUid;
+ public readonly NetEntity EntityUid;
public readonly List<string> VerbTypes = new();
/// If the target item is inside of some storage (e.g., backpack), this is the entity that owns that item
/// slot. Needed for validating that the user can access the target item.
/// </summary>
- public readonly EntityUid? SlotOwner;
+ public readonly NetEntity? SlotOwner;
public readonly bool AdminRequest;
- public RequestServerVerbsEvent(EntityUid entityUid, IEnumerable<Type> verbTypes, EntityUid? slotOwner = null, bool adminRequest = false)
+ public RequestServerVerbsEvent(NetEntity entityUid, IEnumerable<Type> verbTypes, NetEntity? slotOwner = null, bool adminRequest = false)
{
EntityUid = entityUid;
SlotOwner = slotOwner;
public sealed class VerbsResponseEvent : EntityEventArgs
{
public readonly List<Verb>? Verbs;
- public readonly EntityUid Entity;
+ public readonly NetEntity Entity;
- public VerbsResponseEvent(EntityUid entity, SortedSet<Verb>? verbs)
+ public VerbsResponseEvent(NetEntity entity, SortedSet<Verb>? verbs)
{
Entity = entity;
[Serializable, NetSerializable]
public sealed class ExecuteVerbEvent : EntityEventArgs
{
- public readonly EntityUid Target;
+ public readonly NetEntity Target;
public readonly Verb RequestedVerb;
- public ExecuteVerbEvent(EntityUid target, Verb requestedVerb)
+ public ExecuteVerbEvent(NetEntity target, Verb requestedVerb)
{
Target = target;
RequestedVerb = requestedVerb;
/// <summary>
/// Coordinates being attacked.
/// </summary>
- public readonly EntityCoordinates Coordinates;
+ public readonly NetCoordinates Coordinates;
- protected AttackEvent(EntityCoordinates coordinates)
+ protected AttackEvent(NetCoordinates coordinates)
{
Coordinates = coordinates;
}
[Serializable, NetSerializable]
public sealed class DisarmAttackEvent : AttackEvent
{
- public EntityUid? Target;
+ public NetEntity? Target;
- public DisarmAttackEvent(EntityUid? target, EntityCoordinates coordinates) : base(coordinates)
+ public DisarmAttackEvent(NetEntity? target, NetCoordinates coordinates) : base(coordinates)
{
Target = target;
}
[Serializable, NetSerializable]
public sealed class HeavyAttackEvent : AttackEvent
{
- public readonly EntityUid Weapon;
+ public readonly NetEntity Weapon;
/// <summary>
/// As what the client swung at will not match server we'll have them tell us what they hit so we can verify.
/// </summary>
- public List<EntityUid> Entities;
+ public List<NetEntity> Entities;
- public HeavyAttackEvent(EntityUid weapon, List<EntityUid> entities, EntityCoordinates coordinates) : base(coordinates)
+ public HeavyAttackEvent(NetEntity weapon, List<NetEntity> entities, NetCoordinates coordinates) : base(coordinates)
{
Weapon = weapon;
Entities = entities;
[Serializable, NetSerializable]
public sealed class LightAttackEvent : AttackEvent
{
- public readonly EntityUid? Target;
- public readonly EntityUid Weapon;
+ public readonly NetEntity? Target;
+ public readonly NetEntity Weapon;
- public LightAttackEvent(EntityUid? target, EntityUid weapon, EntityCoordinates coordinates) : base(coordinates)
+ public LightAttackEvent(NetEntity? target, NetEntity weapon, NetCoordinates coordinates) : base(coordinates)
{
Target = target;
Weapon = weapon;
[Serializable, NetSerializable]
public sealed class MeleeLungeEvent : EntityEventArgs
{
- public EntityUid Entity;
+ public NetEntity Entity;
/// <summary>
/// Width of the attack angle.
/// </summary>
public string? Animation;
- public MeleeLungeEvent(EntityUid uid, Angle angle, Vector2 localPos, string? animation)
+ public MeleeLungeEvent(NetEntity entity, Angle angle, Vector2 localPos, string? animation)
{
- Entity = uid;
+ Entity = entity;
Angle = angle;
LocalPos = localPos;
Animation = animation;
[Serializable, NetSerializable]
public sealed class StopAttackEvent : EntityEventArgs
{
- public readonly EntityUid Weapon;
+ public readonly NetEntity Weapon;
- public StopAttackEvent(EntityUid weapon)
+ public StopAttackEvent(NetEntity weapon)
{
Weapon = weapon;
}
return;
if (!TryGetWeapon(user.Value, out var weaponUid, out var weapon) ||
- weaponUid != msg.Weapon)
+ weaponUid != GetEntity(msg.Weapon))
{
return;
}
return;
if (!TryGetWeapon(user.Value, out var weaponUid, out var weapon) ||
- weaponUid != msg.Weapon)
+ weaponUid != GetEntity(msg.Weapon))
{
return;
}
- AttemptAttack(args.SenderSession.AttachedEntity!.Value, msg.Weapon, weapon, msg, args.SenderSession);
+ AttemptAttack(args.SenderSession.AttachedEntity!.Value, weaponUid, weapon, msg, args.SenderSession);
}
private void OnHeavyAttack(HeavyAttackEvent msg, EntitySessionEventArgs args)
}
if (!TryGetWeapon(args.SenderSession.AttachedEntity.Value, out var weaponUid, out var weapon) ||
- weaponUid != msg.Weapon)
+ weaponUid != GetEntity(msg.Weapon))
{
return;
}
- AttemptAttack(args.SenderSession.AttachedEntity.Value, msg.Weapon, weapon, msg, args.SenderSession);
+ AttemptAttack(args.SenderSession.AttachedEntity.Value, weaponUid, weapon, msg, args.SenderSession);
}
private void OnDisarmAttack(DisarmAttackEvent msg, EntitySessionEventArgs args)
public void AttemptLightAttackMiss(EntityUid user, EntityUid weaponUid, MeleeWeaponComponent weapon, EntityCoordinates coordinates)
{
- AttemptAttack(user, weaponUid, weapon, new LightAttackEvent(null, weaponUid, coordinates), null);
+ AttemptAttack(user, weaponUid, weapon, new LightAttackEvent(null, GetNetEntity(weaponUid), GetNetCoordinates(coordinates)), null);
}
public bool AttemptLightAttack(EntityUid user, EntityUid weaponUid, MeleeWeaponComponent weapon, EntityUid target)
if (!TryComp<TransformComponent>(target, out var targetXform))
return false;
- return AttemptAttack(user, weaponUid, weapon, new LightAttackEvent(target, weaponUid, targetXform.Coordinates), null);
+ return AttemptAttack(user, weaponUid, weapon, new LightAttackEvent(GetNetEntity(target), GetNetEntity(weaponUid), GetNetCoordinates(targetXform.Coordinates)), null);
}
public bool AttemptDisarmAttack(EntityUid user, EntityUid weaponUid, MeleeWeaponComponent weapon, EntityUid target)
if (!TryComp<TransformComponent>(target, out var targetXform))
return false;
- return AttemptAttack(user, weaponUid, weapon, new DisarmAttackEvent(target, targetXform.Coordinates), null);
+ return AttemptAttack(user, weaponUid, weapon, new DisarmAttackEvent(GetNetEntity(target), GetNetCoordinates(targetXform.Coordinates)), null);
}
/// <summary>
switch (attack)
{
case LightAttackEvent light:
- if (!Blocker.CanAttack(user, light.Target))
+ var lightTarget = GetEntity(light.Target);
+
+ if (!Blocker.CanAttack(user, lightTarget))
return false;
// Can't self-attack if you're the weapon
- if (weaponUid == light.Target)
+ if (weaponUid == lightTarget)
return false;
break;
case DisarmAttackEvent disarm:
- if (!Blocker.CanAttack(user, disarm.Target))
+ var disarmTarget = GetEntity(disarm.Target);
+
+ if (!Blocker.CanAttack(user, disarmTarget))
return false;
break;
default:
throw new NotImplementedException();
}
- DoLungeAnimation(user, weapon.Angle, attack.Coordinates.ToMap(EntityManager, TransformSystem), weapon.Range, animation);
+ DoLungeAnimation(user, weapon.Angle, GetCoordinates(attack.Coordinates).ToMap(EntityManager, TransformSystem), weapon.Range, animation);
}
weapon.Attacking = true;
{
// If I do not come back later to fix Light Attacks being Heavy Attacks you can throw me in the spider pit -Errant
var damage = GetDamage(meleeUid, user, component) * GetHeavyDamageModifier(meleeUid, user, component);
+ var target = GetEntity(ev.Target);
// For consistency with wide attacks stuff needs damageable.
- if (Deleted(ev.Target) ||
- !HasComp<DamageableComponent>(ev.Target) ||
- !TryComp<TransformComponent>(ev.Target, out var targetXform) ||
+ if (Deleted(target) ||
+ !HasComp<DamageableComponent>(target) ||
+ !TryComp<TransformComponent>(target, out var targetXform) ||
// Not in LOS.
- !InRange(user, ev.Target.Value, component.Range, session))
+ !InRange(user, target.Value, component.Range, session))
{
// Leave IsHit set to true, because the only time it's set to false
// is when a melee weapon is examined. Misses are inferred from an
// Sawmill.Debug($"Melee damage is {damage.Total} out of {component.Damage.Total}");
// Raise event before doing damage so we can cancel damage if the event is handled
- var hitEvent = new MeleeHitEvent(new List<EntityUid> { ev.Target.Value }, user, meleeUid, damage);
+ var hitEvent = new MeleeHitEvent(new List<EntityUid> { target.Value }, user, meleeUid, damage);
RaiseLocalEvent(meleeUid, hitEvent);
if (hitEvent.Handled)
var targets = new List<EntityUid>(1)
{
- ev.Target.Value
+ target.Value
};
- Interaction.DoContactInteraction(ev.Weapon, ev.Target);
- Interaction.DoContactInteraction(user, ev.Weapon);
+ var weapon = GetEntity(ev.Weapon);
+
+ Interaction.DoContactInteraction(weapon, target);
+ Interaction.DoContactInteraction(user, weapon);
// If the user is using a long-range weapon, this probably shouldn't be happening? But I'll interpret melee as a
// somewhat messy scuffle. See also, heavy attacks.
- Interaction.DoContactInteraction(user, ev.Target);
+ Interaction.DoContactInteraction(user, target);
// For stuff that cares about it being attacked.
var attackedEvent = new AttackedEvent(meleeUid, user, targetXform.Coordinates);
- RaiseLocalEvent(ev.Target.Value, attackedEvent);
+ RaiseLocalEvent(target.Value, attackedEvent);
var modifiedDamage = DamageSpecifier.ApplyModifierSets(damage + hitEvent.BonusDamage + attackedEvent.BonusDamage, hitEvent.ModifiersList);
- var damageResult = Damageable.TryChangeDamage(ev.Target, modifiedDamage, origin:user);
+ var damageResult = Damageable.TryChangeDamage(target, modifiedDamage, origin:user);
if (damageResult != null && damageResult.Total > FixedPoint2.Zero)
{
// If the target has stamina and is taking blunt damage, they should also take stamina damage based on their blunt to stamina factor
if (damageResult.DamageDict.TryGetValue("Blunt", out var bluntDamage))
{
- _stamina.TakeStaminaDamage(ev.Target.Value, (bluntDamage * component.BluntStaminaDamageFactor).Float(), visual: false, source: user, with: meleeUid == user ? null : meleeUid);
+ _stamina.TakeStaminaDamage(target.Value, (bluntDamage * component.BluntStaminaDamageFactor).Float(), visual: false, source: user, with: meleeUid == user ? null : meleeUid);
}
if (meleeUid == user)
{
AdminLogger.Add(LogType.MeleeHit, LogImpact.Medium,
- $"{ToPrettyString(user):actor} melee attacked (light) {ToPrettyString(ev.Target.Value):subject} using their hands and dealt {damageResult.Total:damage} damage");
+ $"{ToPrettyString(user):actor} melee attacked (light) {ToPrettyString(target.Value):subject} using their hands and dealt {damageResult.Total:damage} damage");
}
else
{
AdminLogger.Add(LogType.MeleeHit, LogImpact.Medium,
- $"{ToPrettyString(user):actor} melee attacked (light) {ToPrettyString(ev.Target.Value):subject} using {ToPrettyString(meleeUid):tool} and dealt {damageResult.Total:damage} damage");
+ $"{ToPrettyString(user):actor} melee attacked (light) {ToPrettyString(target.Value):subject} using {ToPrettyString(meleeUid):tool} and dealt {damageResult.Total:damage} damage");
}
- PlayHitSound(ev.Target.Value, user, GetHighestDamageSound(modifiedDamage, _protoManager), hitEvent.HitSoundOverride, component.HitSound);
+ PlayHitSound(target.Value, user, GetHighestDamageSound(modifiedDamage, _protoManager), hitEvent.HitSoundOverride, component.HitSound);
}
else
{
if (!TryComp<TransformComponent>(user, out var userXform))
return false;
- var targetMap = ev.Coordinates.ToMap(EntityManager, TransformSystem);
+ var targetMap = GetCoordinates(ev.Coordinates).ToMap(EntityManager, TransformSystem);
if (targetMap.MapId != userXform.MapID)
return false;
var distance = Math.Min(component.Range, direction.Length());
var damage = GetDamage(meleeUid, user, component);
- var entities = ev.Entities;
+ var entities = GetEntityList(ev.Entities);
if (entities.Count == 0)
{
if (hitEvent.Handled)
return true;
- Interaction.DoContactInteraction(user, ev.Weapon);
+ var weapon = GetEntity(ev.Weapon);
+
+ Interaction.DoContactInteraction(user, weapon);
// For stuff that cares about it being attacked.
foreach (var target in targets)
{
- Interaction.DoContactInteraction(ev.Weapon, target);
+ Interaction.DoContactInteraction(weapon, target);
// If the user is using a long-range weapon, this probably shouldn't be happening? But I'll interpret melee as a
// somewhat messy scuffle. See also, light attacks.
foreach (var entity in targets)
{
- var attackedEvent = new AttackedEvent(meleeUid, user, ev.Coordinates);
+ var attackedEvent = new AttackedEvent(meleeUid, user, GetCoordinates(ev.Coordinates));
RaiseLocalEvent(entity, attackedEvent);
var modifiedDamage = DamageSpecifier.ApplyModifierSets(damage + hitEvent.BonusDamage + attackedEvent.BonusDamage, hitEvent.ModifiersList);
protected virtual bool DoDisarm(EntityUid user, DisarmAttackEvent ev, EntityUid meleeUid, MeleeWeaponComponent component, ICommonSession? session)
{
- if (Deleted(ev.Target) ||
- user == ev.Target)
+ var target = GetEntity(ev.Target);
+
+ if (Deleted(target) ||
+ user == target)
+ {
return false;
+ }
// Play a sound to give instant feedback; same with playing the animations
Audio.PlayPredicted(component.SwingSound, meleeUid, user);
return;
}
- if (!msg.Coordinates.TryDistance(EntityManager, TransformSystem, Transform(gunUid.Value).Coordinates,
+ var coords = GetCoordinates(msg.Coordinates);
+
+ if (!coords.TryDistance(EntityManager, TransformSystem, Transform(gunUid.Value).Coordinates,
out var distance) ||
distance > gun.MaxDistance)
{
return;
}
- TransformSystem.SetCoordinates(gun.TetherEntity.Value, msg.Coordinates);
+ TransformSystem.SetCoordinates(gun.TetherEntity.Value, coords);
}
private void OnTetherRanged(EntityUid uid, TetherGunComponent component, AfterInteractEvent args)
[Serializable, NetSerializable]
protected sealed class RequestTetherMoveEvent : EntityEventArgs
{
- public EntityCoordinates Coordinates;
+ public NetCoordinates Coordinates;
}
[Serializable, NetSerializable]
namespace Content.Shared.Weapons.Ranged.Components;
-[RegisterComponent, NetworkedComponent, AutoGenerateComponentState]
+[RegisterComponent, NetworkedComponent]
public sealed partial class BallisticAmmoProviderComponent : Component
{
[ViewVariables(VVAccess.ReadWrite), DataField("soundRack")]
public int Count => UnspawnedCount + Container.ContainedEntities.Count;
[ViewVariables(VVAccess.ReadWrite), DataField("unspawnedCount")]
- [AutoNetworkedField]
public int UnspawnedCount;
[ViewVariables(VVAccess.ReadWrite), DataField("whitelist")]
// TODO: Make this use stacks when the typeserializer is done.
[DataField("entities")]
- [AutoNetworkedField(true)]
public List<EntityUid> Entities = new();
/// <summary>
/// Set to false for entities like turrets to avoid users being able to cycle them.
/// </remarks>
[ViewVariables(VVAccess.ReadWrite), DataField("cycleable")]
- [AutoNetworkedField]
public bool Cycleable = true;
/// <summary>
[Serializable, NetSerializable]
public sealed class MuzzleFlashEvent : EntityEventArgs
{
- public EntityUid Uid;
+ public NetEntity Uid;
public string Prototype;
/// <summary>
/// </summary>
public bool MatchRotation;
- public MuzzleFlashEvent(EntityUid uid, string prototype, bool matchRotation = false)
+ public MuzzleFlashEvent(NetEntity uid, string prototype, bool matchRotation = false)
{
Uid = uid;
Prototype = prototype;
[Serializable, NetSerializable]
public sealed class RequestShootEvent : EntityEventArgs
{
- public EntityUid Gun;
- public EntityCoordinates Coordinates;
-}
\ No newline at end of file
+ public NetEntity Gun;
+ public NetCoordinates Coordinates;
+}
[Serializable, NetSerializable]
public sealed class RequestStopShootEvent : EntityEventArgs
{
- public EntityUid Gun;
-}
\ No newline at end of file
+ public NetEntity Gun;
+}
SubscribeLocalEvent<BallisticAmmoProviderComponent, AfterInteractEvent>(OnBallisticAfterInteract);
SubscribeLocalEvent<BallisticAmmoProviderComponent, AmmoFillDoAfterEvent>(OnBallisticAmmoFillDoAfter);
SubscribeLocalEvent<BallisticAmmoProviderComponent, UseInHandEvent>(OnBallisticUse);
+
+ SubscribeLocalEvent<BallisticAmmoProviderComponent, ComponentGetState>(OnBallisticGetState);
+ SubscribeLocalEvent<BallisticAmmoProviderComponent, ComponentHandleState>(OnBallisticHandleState);
+ }
+
+ private void OnBallisticGetState(EntityUid uid, BallisticAmmoProviderComponent component, ref ComponentGetState args)
+ {
+ args.State = new BallisticAmmoProviderComponentState()
+ {
+ UnspawnedCount = component.UnspawnedCount,
+ Cycleable = component.Cycleable,
+ Entities = GetNetEntityList(component.Entities),
+ };
+ }
+
+ private void OnBallisticHandleState(EntityUid uid, BallisticAmmoProviderComponent component, ref ComponentHandleState args)
+ {
+ if (args.Current is not BallisticAmmoProviderComponentState state)
+ return;
+
+ component.UnspawnedCount = state.UnspawnedCount;
+ component.Cycleable = state.Cycleable;
+ component.Entities = EnsureEntityList<BallisticAmmoProviderComponent>(state.Entities, uid);
}
private void OnBallisticUse(EntityUid uid, BallisticAmmoProviderComponent component, UseInHandEvent args)
args.Handled = true;
- _doAfter.TryStartDoAfter(new DoAfterArgs(args.User, component.FillDelay, new AmmoFillDoAfterEvent(), used: uid, target: args.Target, eventTarget: uid)
+ _doAfter.TryStartDoAfter(new DoAfterArgs(EntityManager, args.User, component.FillDelay, new AmmoFillDoAfterEvent(), used: uid, target: args.Target, eventTarget: uid)
{
BreakOnTargetMove = true,
BreakOnUserMove = true,
SimulateInsertAmmo(ent.Value, args.Target.Value, Transform(args.Target.Value).Coordinates);
}
- if (ent.Value.IsClientSide())
+ if (IsClientSide(ent.Value))
Del(ent.Value);
}
Appearance.SetData(uid, AmmoVisuals.AmmoCount, GetBallisticShots(component), appearance);
Appearance.SetData(uid, AmmoVisuals.AmmoMax, component.Capacity, appearance);
}
+
+ [Serializable, NetSerializable]
+ private sealed class BallisticAmmoProviderComponentState : ComponentState
+ {
+ public int UnspawnedCount;
+ public List<NetEntity> Entities = new();
+ public bool Cycleable = true;
+ }
}
/// <summary>
args.State = new RevolverAmmoProviderComponentState
{
CurrentIndex = component.CurrentIndex,
- AmmoSlots = component.AmmoSlots,
+ AmmoSlots = GetNetEntityList(component.AmmoSlots),
Chambers = component.Chambers,
};
}
// Need to copy across the state rather than the ref.
for (var i = 0; i < component.AmmoSlots.Count; i++)
{
- component.AmmoSlots[i] = state.AmmoSlots[i];
+ component.AmmoSlots[i] = EnsureEntity<RevolverAmmoProviderComponent>(state.AmmoSlots[i], uid);
component.Chambers[i] = state.Chambers[i];
}
protected sealed class RevolverAmmoProviderComponentState : ComponentState
{
public int CurrentIndex;
- public List<EntityUid?> AmmoSlots = default!;
+ public List<NetEntity?> AmmoSlots = default!;
public bool?[] Chambers = default!;
}
return;
}
- if (ent != msg.Gun)
+ if (ent != GetEntity(msg.Gun))
return;
- gun.ShootCoordinates = msg.Coordinates;
+ gun.ShootCoordinates = GetCoordinates(msg.Coordinates);
Log.Debug($"Set shoot coordinates to {gun.ShootCoordinates}");
AttemptShoot(user.Value, ent, gun);
}
private void OnStopShootRequest(RequestStopShootEvent ev, EntitySessionEventArgs args)
{
+ var gunUid = GetEntity(ev.Gun);
+
if (args.SenderSession.AttachedEntity == null ||
- !TryComp<GunComponent>(ev.Gun, out var gun) ||
+ !TryComp<GunComponent>(gunUid, out var gun) ||
!TryGetGun(args.SenderSession.AttachedEntity.Value, out _, out var userGun))
{
return;
if (userGun != gun)
return;
- StopShooting(ev.Gun, gun);
+ StopShooting(gunUid, gun);
}
public bool CanShoot(GunComponent component)
if (sprite == null)
return;
- var ev = new MuzzleFlashEvent(gun, sprite, user == gun);
+ var ev = new MuzzleFlashEvent(GetNetEntity(gun), sprite, user == gun);
CreateEffect(gun, ev, user);
}
[Serializable, NetSerializable]
public sealed class HitscanEvent : EntityEventArgs
{
- public List<(EntityCoordinates coordinates, Angle angle, SpriteSpecifier Sprite, float Distance)> Sprites = new();
+ public List<(NetCoordinates coordinates, Angle angle, SpriteSpecifier Sprite, float Distance)> Sprites = new();
}
}
if (ev.Cancelled)
return false;
- var doargs = new DoAfterArgs(user, component.WieldTime, new WieldableDoAfterEvent(), used, used: used)
+ var doargs = new DoAfterArgs(EntityManager, user, component.WieldTime, new WieldableDoAfterEvent(), used, used: used)
{
BreakOnUserMove = false,
BreakOnDamage = true
[Serializable, NetSerializable]
public sealed class AnalysisConsoleScanUpdateState : BoundUserInterfaceState
{
- public EntityUid? Artifact;
+ public NetEntity? Artifact;
public bool AnalyzerConnected;
public int PointAmount;
- public AnalysisConsoleScanUpdateState(EntityUid? artifact, bool analyzerConnected, bool serverConnected, bool canScan, bool canPrint,
+ public AnalysisConsoleScanUpdateState(NetEntity? artifact, bool analyzerConnected, bool serverConnected, bool canScan, bool canPrint,
FormattedMessage? scanReport, bool scanning, TimeSpan timeRemaining, TimeSpan totalTime, int pointAmount)
{
Artifact = artifact;