+using System.Linq;
+using System.Numerics;
using JetBrains.Annotations;
+using Robust.Client.GameObjects;
using Robust.Client.Graphics;
using Robust.Client.ResourceManagement;
using Robust.Shared.Enums;
using Robust.Shared.Map;
-using System.Linq;
-using System.Numerics;
+using Robust.Shared.Map.Components;
namespace Content.Client.Administration.UI.SpawnExplosion;
{
[Dependency] private readonly IEntityManager _entityManager = default!;
[Dependency] private readonly IEyeManager _eyeManager = default!;
- [Dependency] private readonly IMapManager _mapManager = default!;
public Dictionary<int, List<Vector2i>>? SpaceTiles;
public Dictionary<EntityUid, Dictionary<int, List<Vector2i>>> Tiles = new();
var handle = args.ScreenHandle;
Box2 gridBounds;
var xformQuery = _entityManager.GetEntityQuery<TransformComponent>();
+ var xformSystem = _entityManager.System<TransformSystem>();
foreach (var (gridId, tileSets) in Tiles)
{
- if (!_mapManager.TryGetGrid(gridId, out var grid))
+ if (!_entityManager.TryGetComponent(gridId, out MapGridComponent? grid))
continue;
- var gridXform = xformQuery.GetComponent(grid.Owner);
- var (_, _, matrix, invMatrix) = gridXform.GetWorldPositionRotationMatrixWithInv(xformQuery);
+ var gridXform = xformQuery.GetComponent(gridId);
+ var (_, _, matrix, invMatrix) = xformSystem.GetWorldPositionRotationMatrixWithInv(gridXform, xformQuery);
gridBounds = invMatrix.TransformBox(args.WorldBounds).Enlarged(grid.TileSize * 2);
DrawText(handle, gridBounds, matrix, tileSets, grid.TileSize);
}
}
}
- if (tileSets.ContainsKey(0))
+ if (tileSets.TryGetValue(0, out var set))
{
- var epicenter = tileSets[0].First();
+ var epicenter = set.First();
var worldCenter = transform.Transform((epicenter + Vector2Helpers.Half) * tileSize);
var screenCenter = _eyeManager.WorldToScreen(worldCenter) + new Vector2(-24, -24);
var text = $"{Intensity[0]:F2}\nΣ={TotalIntensity:F1}\nΔ={Slope:F1}";
var handle = args.WorldHandle;
Box2 gridBounds;
var xformQuery = _entityManager.GetEntityQuery<TransformComponent>();
+ var xformSystem = _entityManager.System<TransformSystem>();
foreach (var (gridId, tileSets) in Tiles)
{
- if (!_mapManager.TryGetGrid(gridId, out var grid))
+ if (!_entityManager.TryGetComponent(gridId, out MapGridComponent? grid))
continue;
- var gridXform = xformQuery.GetComponent(grid.Owner);
- var (_, _, worldMatrix, invWorldMatrix) = gridXform.GetWorldPositionRotationMatrixWithInv(xformQuery);
+ var gridXform = xformQuery.GetComponent(gridId);
+ var (_, _, worldMatrix, invWorldMatrix) = xformSystem.GetWorldPositionRotationMatrixWithInv(gridXform, xformQuery);
gridBounds = invWorldMatrix.TransformBox(args.WorldBounds).Enlarged(grid.TileSize * 2);
handle.SetTransform(worldMatrix);
DrawTiles(handle, gridBounds, tileSets, SpaceTileSize);
-using System.Collections.Generic;
-using System.Linq;
using JetBrains.Annotations;
using Robust.Client.AutoGenerated;
using Robust.Client.Console;
using Robust.Client.Player;
using Robust.Client.UserInterface.Controls;
using Robust.Client.UserInterface.CustomControls;
-using Robust.Shared.GameObjects;
-using Robust.Shared.IoC;
-using Robust.Shared.Map;
+using Robust.Client.UserInterface.XAML;
using Robust.Shared.Map.Components;
namespace Content.Client.Administration.UI.Tabs.AtmosTab
[UsedImplicitly]
public sealed partial class AddAtmosWindow : DefaultWindow
{
- private IEnumerable<MapGridComponent>? _data;
+ [Dependency] private readonly IPlayerManager _players = default!;
+ [Dependency] private readonly IEntityManager _entities = default!;
+
+ private readonly List<Entity<MapGridComponent>> _data = new();
+
+ public AddAtmosWindow()
+ {
+ RobustXamlLoader.Load(this);
+ IoCManager.InjectDependencies(this);
+ }
protected override void EnteredTree()
{
- _data = IoCManager.Resolve<IMapManager>().GetAllGrids().Where(g => (int) g.Owner != 0);
- foreach (var grid in _data)
+ _data.Clear();
+
+ var player = _players.LocalPlayer?.ControlledEntity;
+ var playerGrid = _entities.GetComponentOrNull<TransformComponent>(player)?.GridUid;
+ var query = IoCManager.Resolve<IEntityManager>().AllEntityQueryEnumerator<MapGridComponent>();
+
+ while (query.MoveNext(out var uid, out var grid))
{
- var player = IoCManager.Resolve<IPlayerManager>().LocalPlayer?.ControlledEntity;
- var playerGrid = IoCManager.Resolve<IEntityManager>().GetComponentOrNull<TransformComponent>(player)?.GridUid;
- GridOptions.AddItem($"{grid.Owner} {(playerGrid == grid.Owner ? " (Current)" : "")}");
+ _data.Add((uid, grid));
+ GridOptions.AddItem($"{uid} {(playerGrid == uid ? " (Current)" : "")}");
}
GridOptions.OnItemSelected += eventArgs => GridOptions.SelectId(eventArgs.Id);
private void SubmitButtonOnOnPressed(BaseButton.ButtonEventArgs obj)
{
- if (_data == null)
- return;
- var dataList = _data.ToList();
- var entManager = IoCManager.Resolve<IEntityManager>();
- var selectedGrid = dataList[GridOptions.SelectedId].Owner;
- IoCManager.Resolve<IClientConsoleHost>().ExecuteCommand($"addatmos {entManager.GetNetEntity(selectedGrid)}");
+ var selectedGrid = _data[GridOptions.SelectedId].Owner;
+ IoCManager.Resolve<IClientConsoleHost>().ExecuteCommand($"addatmos {_entities.GetNetEntity(selectedGrid)}");
}
}
}
-using System.Linq;
using Content.Client.Station;
using Robust.Client.AutoGenerated;
using Robust.Client.UserInterface;
private void RefreshObjectList(ObjectsTabSelection selection)
{
- var entities = selection switch
+ var entities = new List<EntityUid>();
+ switch (selection)
{
- ObjectsTabSelection.Stations => _entityManager.EntitySysManager.GetEntitySystem<StationSystem>().Stations.ToList(),
- ObjectsTabSelection.Grids => _entityManager.EntityQuery<MapGridComponent>(true).Select(x => x.Owner).ToList(),
- ObjectsTabSelection.Maps => _entityManager.EntityQuery<MapComponent>(true).Select(x => x.Owner).ToList(),
- _ => throw new ArgumentOutOfRangeException(nameof(selection), selection, null),
- };
+ case ObjectsTabSelection.Stations:
+ entities.AddRange(_entityManager.EntitySysManager.GetEntitySystem<StationSystem>().Stations);
+ break;
+ case ObjectsTabSelection.Grids:
+ {
+ var query = _entityManager.AllEntityQueryEnumerator<MapGridComponent>();
+ while (query.MoveNext(out var uid, out _))
+ {
+ entities.Add(uid);
+ }
+
+ break;
+ }
+ case ObjectsTabSelection.Maps:
+ {
+ var query = _entityManager.AllEntityQueryEnumerator<MapComponent>();
+ while (query.MoveNext(out var uid, out _))
+ {
+ entities.Add(uid);
+ }
+ break;
+ }
+ default:
+ throw new ArgumentOutOfRangeException(nameof(selection), selection, null);
+ }
foreach (var control in _objects)
{
}
}
- protected override void AfterShowAlert(AlertsComponent alertsComponent)
+ protected override void AfterShowAlert(Entity<AlertsComponent> alerts)
{
- if (_playerManager.LocalPlayer?.ControlledEntity != alertsComponent.Owner)
+ if (_playerManager.LocalPlayer?.ControlledEntity != alerts.Owner)
return;
- SyncAlerts?.Invoke(this, alertsComponent.Alerts);
+ SyncAlerts?.Invoke(this, alerts.Comp.Alerts);
}
- protected override void AfterClearAlert(AlertsComponent alertsComponent)
+ protected override void AfterClearAlert(Entity<AlertsComponent> alertsComponent)
{
if (_playerManager.LocalPlayer?.ControlledEntity != alertsComponent.Owner)
return;
- SyncAlerts?.Invoke(this, alertsComponent.Alerts);
+ SyncAlerts?.Invoke(this, alertsComponent.Comp.Alerts);
}
private void ClientAlertsHandleState(EntityUid uid, AlertsComponent component, ref AfterAutoHandleStateEvent args)
using Content.Shared.Atmos.EntitySystems;
using Robust.Client.Graphics;
using Robust.Shared.Enums;
-using Robust.Shared.GameObjects;
-using Robust.Shared.IoC;
using Robust.Shared.Map;
-using Robust.Shared.Maths;
+using Robust.Shared.Map.Components;
namespace Content.Client.Atmos.Overlays
{
[Dependency] private readonly IMapManager _mapManager = default!;
public override OverlaySpace Space => OverlaySpace.WorldSpace;
+ private List<Entity<MapGridComponent>> _grids = new();
internal AtmosDebugOverlay(AtmosDebugOverlaySystem system)
{
// 3. "Is this going to make it harder for atmos programmers to add data that may not be chunk-friendly into the atmos debugger?"
// Nanotrasen needs YOU! to avoid premature optimization in critical debugging tools - 20kdc
- foreach (var mapGrid in _mapManager.FindGridsIntersecting(mapId, worldBounds))
+ _grids.Clear();
+
+ _mapManager.FindGridsIntersecting(mapId, worldBounds, ref _grids, (EntityUid uid, MapGridComponent grid,
+ ref List<Entity<MapGridComponent>> state) =>
+ {
+ state.Add((uid, grid));
+ return true;
+ });
+
+ foreach (var (uid, mapGrid) in _grids)
{
- if (!_atmosDebugOverlaySystem.HasData(mapGrid.Owner) ||
- !_entManager.TryGetComponent<TransformComponent>(mapGrid.Owner, out var xform))
+ if (!_atmosDebugOverlaySystem.HasData(uid) ||
+ !_entManager.TryGetComponent<TransformComponent>(uid, out var xform))
continue;
drawHandle.SetTransform(xform.WorldMatrix);
{
foreach (var tile in mapGrid.GetTilesIntersecting(worldBounds))
{
- var dataMaybeNull = _atmosDebugOverlaySystem.GetData(mapGrid.Owner, tile.GridIndices);
+ var dataMaybeNull = _atmosDebugOverlaySystem.GetData(uid, tile.GridIndices);
if (dataMaybeNull != null)
{
var data = (SharedAtmosDebugOverlaySystem.AtmosDebugOverlayData) dataMaybeNull;
{
// -- Mole Count --
float total = 0;
- switch (_atmosDebugOverlaySystem.CfgMode) {
+ switch (_atmosDebugOverlaySystem.CfgMode)
+ {
case AtmosDebugOverlayMode.TotalMoles:
- foreach (float f in data.Moles)
+ foreach (var f in data.Moles)
{
total += f;
}
total = data.Temperature;
break;
}
- var interp = ((total - _atmosDebugOverlaySystem.CfgBase) / _atmosDebugOverlaySystem.CfgScale);
+ var interp = (total - _atmosDebugOverlaySystem.CfgBase) / _atmosDebugOverlaySystem.CfgScale;
Color res;
if (_atmosDebugOverlaySystem.CfgCBM)
{
if (ambientSound.Enabled)
{
- if (_ambient.IsActive(ambientSound))
+ if (_ambient.IsActive((ent, ambientSound)))
{
worldHandle.DrawCircle(xformSystem.GetWorldPosition(xform), Size, Color.LightGreen.WithAlpha(Alpha * 2f));
}
+using System.Linq;
+using System.Numerics;
using Content.Shared.Audio;
using Content.Shared.CCVar;
+using Robust.Client.GameObjects;
using Robust.Client.Graphics;
using Robust.Client.Player;
using Robust.Shared.Audio;
-using Robust.Shared.Log;
using Robust.Shared.Configuration;
-using Robust.Shared.Map;
using Robust.Shared.Physics;
using Robust.Shared.Random;
using Robust.Shared.Timing;
using Robust.Shared.Utility;
-using System.Linq;
-using System.Numerics;
-using Robust.Client.GameObjects;
namespace Content.Client.Audio;
//TODO: This is using a incomplete version of the whole "only play nearest sounds" algo, that breaks down a bit should the ambient sound cap get hit.
/// </summary>
private int MaxSingleSound => (int) (_maxAmbientCount / (16.0f / 6.0f));
- private readonly Dictionary<AmbientSoundComponent, (IPlayingAudioStream? Stream, SoundSpecifier Sound, string Path)> _playingSounds = new();
+ private readonly Dictionary<Entity<AmbientSoundComponent>, (IPlayingAudioStream? Stream, SoundSpecifier Sound, string Path)> _playingSounds = new();
private readonly Dictionary<string, int> _playingCount = new();
public bool OverlayEnabled
/// </summary>
/// <param name="component"></param>
/// <returns></returns>
- public bool IsActive(AmbientSoundComponent component)
+ public bool IsActive(Entity<AmbientSoundComponent> component)
{
return _playingSounds.ContainsKey(component);
}
private void OnShutdown(EntityUid uid, AmbientSoundComponent component, ComponentShutdown args)
{
- if (!_playingSounds.Remove(component, out var sound))
+ if (!_playingSounds.Remove((uid, component), out var sound))
return;
sound.Stream?.Stop();
{
_ambienceVolume = value;
- foreach (var (comp, values) in _playingSounds)
+ foreach (var ((_, comp), values) in _playingSounds)
{
if (values.Stream == null)
continue;
private readonly struct QueryState
{
- public readonly Dictionary<string, List<(float Importance, AmbientSoundComponent)>> SourceDict = new();
+ public readonly Dictionary<string, List<(float Importance, Entity<AmbientSoundComponent>)>> SourceDict = new();
public readonly Vector2 MapPos;
public readonly TransformComponent Player;
public readonly EntityQuery<TransformComponent> Query;
// Prioritize far away & loud sounds.
var importance = range * (ambientComp.Volume + 32);
- state.SourceDict.GetOrNew(key).Add((importance, ambientComp));
+ state.SourceDict.GetOrNew(key).Add((importance, (ambientComp.Owner, ambientComp)));
return true;
}
var mapPos = playerXform.MapPosition;
// Remove out-of-range ambiences
- foreach (var (comp, sound) in _playingSounds)
+ foreach (var (ent, sound) in _playingSounds)
{
- var entity = comp.Owner;
+ var entity = ent.Owner;
+ var comp = ent.Comp;
if (comp.Enabled &&
// Don't keep playing sounds that have changed since.
}
sound.Stream?.Stop();
- _playingSounds.Remove(comp);
+ _playingSounds.Remove((entity, comp));
_playingCount[sound.Path] -= 1;
if (_playingCount[sound.Path] == 0)
_playingCount.Remove(sound.Path);
sources.Sort(static (a, b) => b.Importance.CompareTo(a.Importance));
- foreach (var (_, comp) in sources)
+ foreach (var (_, ent) in sources)
{
- var uid = comp.Owner;
+ var uid = ent.Owner;
+ var comp = ent.Comp;
- if (_playingSounds.ContainsKey(comp) ||
+ if (_playingSounds.ContainsKey(ent) ||
metaQuery.GetComponent(uid).EntityPaused)
continue;
if (stream == null)
continue;
- _playingSounds[comp] = (stream, comp.Sound, key);
+ _playingSounds[ent] = (stream, comp.Sound, key);
playingCount++;
if (_playingSounds.Count >= _maxAmbientCount)
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))
+ var movers = new HashSet<Entity<MobMoverComponent>>();
+ _entityLookup.GetEntitiesInRange(xform.Coordinates, box.Distance, movers);
+
+ foreach (var moverComp in movers)
{
- if (moverComp.Owner == mover)
+ var uid = moverComp.Owner;
+ if (uid == mover)
continue;
- mobMoverEntities.Add(moverComp.Owner);
+ mobMoverEntities.Add(uid);
}
//Play the effect for the mobs as long as they can see the box and are in range.
if (_anim.HasRunningAnimation(player, _chasmFallAnimationKey))
return;
- _anim.Play(player, GetFallingAnimation(component), _chasmFallAnimationKey);
+ _anim.Play((uid, player), GetFallingAnimation(component), _chasmFallAnimationKey);
}
private void OnComponentRemove(EntityUid uid, ChasmFallingComponent component, ComponentRemove args)
{
var entityManager = IoCManager.Resolve<IEntityManager>();
var containerSys = entityManager.System<SharedContainerSystem>();
- var organs = entityManager.EntityQuery<OrganComponent>(true);
+ var query = entityManager.AllEntityQueryEnumerator<OrganComponent>();
- foreach (var part in organs)
+ while (query.MoveNext(out var uid, out _))
{
- if (!entityManager.TryGetComponent(part.Owner, out SpriteComponent? sprite))
+ if (!entityManager.TryGetComponent(uid, out SpriteComponent? sprite))
{
continue;
}
sprite.ContainerOccluded = false;
- var tempParent = part.Owner;
+ var tempParent = uid;
while (containerSys.TryGetContainingContainer(tempParent, out var container))
{
if (!container.ShowContents)
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
var entityManager = IoCManager.Resolve<IEntityManager>();
- var organs = entityManager.EntityQuery<OrganComponent>(true);
+ var query = entityManager.AllEntityQueryEnumerator<OrganComponent, SpriteComponent>();
- foreach (var mechanism in organs)
+ while (query.MoveNext(out _, out var sprite))
{
- if (entityManager.TryGetComponent(mechanism.Owner, out SpriteComponent? sprite))
- {
- sprite.ContainerOccluded = false;
- }
+ sprite.ContainerOccluded = false;
}
IoCManager.Resolve<IClientConsoleHost>().ExecuteCommand("showcontainedcontext");
// Shouldn't need to clear cached textures unless the prototypes get reloaded.
var handle = args.WorldHandle;
var xformQuery = _entManager.GetEntityQuery<TransformComponent>();
+ var xformSystem = _entManager.System<TransformSystem>();
var eyeAngle = args.Viewport.Eye?.Rotation ?? Angle.Zero;
foreach (var (decalGrid, xform) in _entManager.EntityQuery<DecalGridComponent, TransformComponent>(true))
{
- var gridId = decalGrid.Owner;
var zIndexDictionary = decalGrid.DecalRenderIndex;
if (zIndexDictionary.Count == 0)
if (xform.MapID != args.MapId)
continue;
- var (_, worldRot, worldMatrix) = xform.GetWorldPositionRotationMatrix(xformQuery);
+ var (_, worldRot, worldMatrix) = xformSystem.GetWorldPositionRotationMatrix(xform, xformQuery);
handle.SetTransform(worldMatrix);
SubscribeLocalEvent<DoorComponent, AppearanceChangeEvent>(OnAppearanceChange);
}
- protected override void OnComponentInit(EntityUid uid, DoorComponent comp, ComponentInit args)
+ protected override void OnComponentInit(Entity<DoorComponent> ent, ref ComponentInit args)
{
+ var comp = ent.Comp;
comp.OpenSpriteStates = new(2);
comp.ClosedSpriteStates = new(2);
var comp = EnsureComp<ColorFlashEffectComponent>(ent);
comp.NetSyncEnabled = false;
comp.Color = sprite.Color;
- _animation.Play(player, animation, AnimationKey);
+ _animation.Play((ent, player), animation, AnimationKey);
}
}
}
using Robust.Client.Graphics;
using Robust.Shared.Enums;
using Robust.Shared.Map;
+using Robust.Shared.Map.Components;
using Robust.Shared.Prototypes;
using Robust.Shared.Random;
Box2 gridBounds;
foreach (var (gridId, tiles) in visuals.Tiles)
{
- if (!_mapManager.TryGetGrid(gridId, out var grid))
+ if (!_entMan.TryGetComponent(gridId, out MapGridComponent? grid))
continue;
- var xform = xforms.GetComponent(grid.Owner);
+ var xform = xforms.GetComponent(gridId);
var (_, _, worldMatrix, invWorldMatrix) = xform.GetWorldPositionRotationMatrixWithInv(xforms);
gridBounds = invWorldMatrix.TransformBox(worldBounds).Enlarged(grid.TileSize * 2);
-using System.Numerics;
-using Content.Shared.FixedPoint;
+using Content.Shared.FixedPoint;
using Robust.Client.Graphics;
using Robust.Client.ResourceManagement;
using Robust.Shared.Enums;
using Robust.Shared.Map;
+using Robust.Shared.Map.Components;
namespace Content.Client.Fluids;
foreach (var gridId in _debugOverlaySystem.TileData.Keys)
{
- if (!_mapManager.TryGetGrid(gridId, out var mapGrid))
+ if (!_entityManager.TryGetComponent(gridId, out MapGridComponent? mapGrid))
continue;
var gridXform = xformQuery.GetComponent(gridId);
gridBounds = invWorldMatrix.TransformBox(args.WorldBounds).Enlarged(mapGrid.TileSize * 2);
drawHandle.SetTransform(worldMatrix);
- foreach (var debugOverlayData in _debugOverlaySystem.GetData(mapGrid.Owner))
+ foreach (var debugOverlayData in _debugOverlaySystem.GetData(gridId))
{
var centre = (debugOverlayData.Pos + Vector2Helpers.Half) * mapGrid.TileSize;
foreach (var gridId in _debugOverlaySystem.TileData.Keys)
{
- if (!_mapManager.TryGetGrid(gridId, out var mapGrid))
+ if (!_entityManager.TryGetComponent(gridId, out MapGridComponent? mapGrid))
continue;
var gridXform = xformQuery.GetComponent(gridId);
var (_, _, matrix, invMatrix) = gridXform.GetWorldPositionRotationMatrixWithInv(xformQuery);
var gridBounds = invMatrix.TransformBox(args.WorldBounds).Enlarged(mapGrid.TileSize * 2);
- foreach (var debugOverlayData in _debugOverlaySystem.GetData(mapGrid.Owner))
+ foreach (var debugOverlayData in _debugOverlaySystem.GetData(gridId))
{
var centre = (debugOverlayData.Pos + Vector2Helpers.Half) * mapGrid.TileSize;
SubscribeLocalEvent<HandheldGPSComponent, ItemStatusCollectMessage>(OnItemStatus);
}
- private void OnItemStatus(EntityUid uid, HandheldGPSComponent component, ItemStatusCollectMessage args)
+ private void OnItemStatus(Entity<HandheldGPSComponent> ent, ref ItemStatusCollectMessage args)
{
- args.Controls.Add(new HandheldGpsStatusControl(component));
+ args.Controls.Add(new HandheldGpsStatusControl(ent));
}
}
public sealed class HandheldGpsStatusControl : Control
{
- private readonly HandheldGPSComponent _parent;
+ private readonly Entity<HandheldGPSComponent> _parent;
private readonly RichTextLabel _label;
private float _updateDif;
private readonly IEntityManager _entMan;
- public HandheldGpsStatusControl(HandheldGPSComponent parent)
+ public HandheldGpsStatusControl(Entity<HandheldGPSComponent> parent)
{
_parent = parent;
_entMan = IoCManager.Resolve<IEntityManager>();
base.FrameUpdate(args);
_updateDif += args.DeltaSeconds;
- if (_updateDif < _parent.UpdateRate)
+ if (_updateDif < _parent.Comp.UpdateRate)
return;
- _updateDif -= _parent.UpdateRate;
+ _updateDif -= _parent.Comp.UpdateRate;
UpdateGpsDetails();
}
private void UpdateGpsDetails()
{
var posText = "Error";
- if (_entMan.TryGetComponent(_parent.Owner, out TransformComponent? transComp))
+ if (_entMan.TryGetComponent(_parent, out TransformComponent? transComp))
{
var pos = transComp.MapPosition;
var x = (int) pos.X;
using Content.Client.ContextMenu.UI;
using Content.Client.Examine;
using Content.Client.Guidebook.Richtext;
-using Content.Client.Verbs;
using Content.Client.Verbs.UI;
using Content.Shared.Input;
using Content.Shared.Tag;
public bool Interactive;
- public SpriteComponent? Sprite => View.Sprite;
+ public Entity<SpriteComponent>? Sprite => View.Entity == null || View.Sprite == null
+ ? null
+ : (View.Entity.Value, View.Sprite);
public Vector2 Scale
{
base.Dispose(disposing);
if (Sprite is not null)
- _entityManager.DeleteEntity(Sprite.Owner);
+ _entityManager.DeleteEntity(Sprite);
}
public bool TryParseTag(Dictionary<string, string> args, [NotNullWhen(true)] out Control? control)
using System.Diagnostics.CodeAnalysis;
using System.Linq;
-using System.Numerics;
-using Content.Client.Animations;
using Content.Client.Examine;
using Content.Client.Strip;
using Content.Client.Verbs.UI;
using Robust.Client.UserInterface;
using Robust.Shared.Containers;
using Robust.Shared.GameStates;
-using Robust.Shared.Map;
using Robust.Shared.Timing;
namespace Content.Client.Hands.Systems
base.RemoveHand(uid, handName, handsComp);
}
- private void OnHandActivated(HandsComponent? handsComponent)
+ private void OnHandActivated(Entity<HandsComponent>? ent)
{
- if (handsComponent == null)
+ if (ent is not { } hand)
return;
- if (_playerManager.LocalPlayer?.ControlledEntity != handsComponent.Owner)
+ if (_playerManager.LocalPlayer?.ControlledEntity != hand.Owner)
return;
- if (handsComponent.ActiveHand == null)
+ if (hand.Comp.ActiveHand == null)
{
OnPlayerSetActiveHand?.Invoke(null);
return;
}
- OnPlayerSetActiveHand?.Invoke(handsComponent.ActiveHand.Name);
+ OnPlayerSetActiveHand?.Invoke(hand.Comp.ActiveHand.Name);
}
}
}
-using System.Collections.Generic;
using Content.Client.HealthOverlay.UI;
using Content.Shared.Damage;
using Content.Shared.GameTicking;
using JetBrains.Annotations;
using Robust.Client.GameObjects;
using Robust.Client.Graphics;
-using Robust.Shared.GameObjects;
-using Robust.Shared.IoC;
namespace Content.Client.HealthOverlay
{
var viewBox = _eyeManager.GetWorldViewport().Enlarged(2.0f);
- foreach (var (mobState, _) in EntityManager.EntityQuery<MobStateComponent, DamageableComponent>())
+ var query = EntityQueryEnumerator<MobStateComponent, DamageableComponent>();
+ while (query.MoveNext(out var entity, out var mobState, out _))
{
- var entity = mobState.Owner;
-
if (_entities.GetComponent<TransformComponent>(ent).MapID != _entities.GetComponent<TransformComponent>(entity).MapID ||
!viewBox.Contains(_entities.GetComponent<TransformComponent>(entity).WorldPosition))
{
Panel.Visible = val;
}
- private void MoreFrameUpdate(FrameEventArgs args)
+ private void MoreFrameUpdate()
{
if (_entities.Deleted(Entity))
{
var mobStateSystem = _entities.EntitySysManager.GetEntitySystem<MobStateSystem>();
var mobThresholdSystem = _entities.EntitySysManager.GetEntitySystem<MobThresholdSystem>();
- if (mobStateSystem.IsAlive(mobState.Owner, mobState))
+ if (mobStateSystem.IsAlive(Entity, mobState))
{
if (!mobThresholdSystem.TryGetThresholdForState(Entity,MobState.Critical, out var threshold))
{
HealthBar.Ratio = 1 - ((FixedPoint2)(damageable.TotalDamage / threshold)).Float();
HealthBar.Visible = true;
}
- else if (mobStateSystem.IsCritical(mobState.Owner, mobState))
+ else if (mobStateSystem.IsCritical(Entity, mobState))
{
HealthBar.Ratio = 0;
HealthBar.Visible = false;
((damageable.TotalDamage - critThreshold) /
(deadThreshold - critThreshold)).Value.Float();
}
- else if (mobStateSystem.IsDead(mobState.Owner, mobState))
+ else if (mobStateSystem.IsDead(Entity, mobState))
{
CritBar.Ratio = 0;
CritBar.Visible = false;
{
base.FrameUpdate(args);
- MoreFrameUpdate(args);
+ MoreFrameUpdate();
if (_entities.Deleted(Entity) || _eyeManager.CurrentMap != _entities.GetComponent<TransformComponent>(Entity).MapID)
{
return;
}
+ var spriteEnt = (uid, sprite);
+
if (xform.Anchored)
{
if (!_mapManager.TryGetGrid(xform.GridUid, out grid))
switch (smooth.Mode)
{
case IconSmoothingMode.Corners:
- CalculateNewSpriteCorners(grid, smooth, sprite, xform, smoothQuery);
+ CalculateNewSpriteCorners(grid, smooth, spriteEnt, xform, smoothQuery);
break;
case IconSmoothingMode.CardinalFlags:
- CalculateNewSpriteCardinal(grid, smooth, sprite, xform, smoothQuery);
+ CalculateNewSpriteCardinal(grid, smooth, spriteEnt, xform, smoothQuery);
break;
case IconSmoothingMode.Diagonal:
- CalculateNewSpriteDiagonal(grid, smooth, sprite, xform, smoothQuery);
+ CalculateNewSpriteDiagonal(grid, smooth, spriteEnt, xform, smoothQuery);
break;
default:
throw new ArgumentOutOfRangeException();
}
private void CalculateNewSpriteDiagonal(MapGridComponent? grid, IconSmoothComponent smooth,
- SpriteComponent sprite, TransformComponent xform, EntityQuery<IconSmoothComponent> smoothQuery)
+ Entity<SpriteComponent> sprite, TransformComponent xform, EntityQuery<IconSmoothComponent> smoothQuery)
{
if (grid == null)
{
- sprite.LayerSetState(0, $"{smooth.StateBase}0");
+ sprite.Comp.LayerSetState(0, $"{smooth.StateBase}0");
return;
}
if (matching)
{
- sprite.LayerSetState(0, $"{smooth.StateBase}1");
+ sprite.Comp.LayerSetState(0, $"{smooth.StateBase}1");
}
else
{
- sprite.LayerSetState(0, $"{smooth.StateBase}0");
+ sprite.Comp.LayerSetState(0, $"{smooth.StateBase}0");
}
}
- private void CalculateNewSpriteCardinal(MapGridComponent? grid, IconSmoothComponent smooth, SpriteComponent sprite, TransformComponent xform, EntityQuery<IconSmoothComponent> smoothQuery)
+ private void CalculateNewSpriteCardinal(MapGridComponent? grid, IconSmoothComponent smooth, Entity<SpriteComponent> sprite, TransformComponent xform, EntityQuery<IconSmoothComponent> smoothQuery)
{
var dirs = CardinalConnectDirs.None;
if (grid == null)
{
- sprite.LayerSetState(0, $"{smooth.StateBase}{(int) dirs}");
+ sprite.Comp.LayerSetState(0, $"{smooth.StateBase}{(int) dirs}");
return;
}
if (MatchingEntity(smooth, grid.GetAnchoredEntitiesEnumerator(pos.Offset(Direction.West)), smoothQuery))
dirs |= CardinalConnectDirs.West;
- sprite.LayerSetState(0, $"{smooth.StateBase}{(int) dirs}");
+ sprite.Comp.LayerSetState(0, $"{smooth.StateBase}{(int) dirs}");
var directions = DirectionFlag.None;
if ((dirs & CardinalConnectDirs.West) != 0x0)
directions |= DirectionFlag.West;
- CalculateEdge(sprite.Owner, directions, sprite);
+ CalculateEdge(sprite, directions, sprite);
}
private bool MatchingEntity(IconSmoothComponent smooth, AnchoredEntitiesEnumerator candidates, EntityQuery<IconSmoothComponent> smoothQuery)
return false;
}
- private void CalculateNewSpriteCorners(MapGridComponent? grid, IconSmoothComponent smooth, SpriteComponent sprite, TransformComponent xform, EntityQuery<IconSmoothComponent> smoothQuery)
+ private void CalculateNewSpriteCorners(MapGridComponent? grid, IconSmoothComponent smooth, Entity<SpriteComponent> spriteEnt, TransformComponent xform, EntityQuery<IconSmoothComponent> smoothQuery)
{
var (cornerNE, cornerNW, cornerSW, cornerSE) = grid == null
? (CornerFill.None, CornerFill.None, CornerFill.None, CornerFill.None)
// It will also result in 4-8 sprite update events being raised when it only needs to be 1-2.
// At the very least each event currently only queues a sprite for updating.
// Oh god sprite component is a mess.
+ var sprite = spriteEnt.Comp;
sprite.LayerSetState(CornerLayers.NE, $"{smooth.StateBase}{(int) cornerNE}");
sprite.LayerSetState(CornerLayers.SE, $"{smooth.StateBase}{(int) cornerSE}");
sprite.LayerSetState(CornerLayers.SW, $"{smooth.StateBase}{(int) cornerSW}");
if ((cornerNW & cornerSW) != CornerFill.None)
directions |= DirectionFlag.West;
- CalculateEdge(sprite.Owner, directions, sprite);
+ CalculateEdge(spriteEnt, directions, sprite);
}
private (CornerFill ne, CornerFill nw, CornerFill sw, CornerFill se) CalculateCornerFill(MapGridComponent grid, IconSmoothComponent smooth, TransformComponent xform, EntityQuery<IconSmoothComponent> smoothQuery)
private ShaderInstance? _shader;
private int _lastRenderScale;
- public void OnMouseEnter(bool inInteractionRange, int renderScale)
+ public void OnMouseEnter(EntityUid uid, bool inInteractionRange, int renderScale)
{
_lastRenderScale = renderScale;
_inRange = inInteractionRange;
- if (_entMan.TryGetComponent(Owner, out SpriteComponent? sprite) && sprite.PostShader == null)
+ if (_entMan.TryGetComponent(uid, out SpriteComponent? sprite) && sprite.PostShader == null)
{
// TODO why is this creating a new instance of the outline shader every time the mouse enters???
_shader = MakeNewShader(inInteractionRange, renderScale);
}
}
- public void OnMouseLeave()
+ public void OnMouseLeave(EntityUid uid)
{
- if (_entMan.TryGetComponent(Owner, out SpriteComponent? sprite))
+ if (_entMan.TryGetComponent(uid, out SpriteComponent? sprite))
{
if (sprite.PostShader == _shader)
sprite.PostShader = null;
_shader = null;
}
- public void UpdateInRange(bool inInteractionRange, int renderScale)
+ public void UpdateInRange(EntityUid uid, bool inInteractionRange, int renderScale)
{
- if (_entMan.TryGetComponent(Owner, out SpriteComponent? sprite)
+ if (_entMan.TryGetComponent(uid, out SpriteComponent? sprite)
&& sprite.PostShader == _shader
&& (inInteractionRange != _inRange || _lastRenderScale != renderScale))
{
private void OnShutdown(EntityUid uid, InventoryComponent component, ComponentShutdown args)
{
- if (component.Owner != _playerManager.LocalPlayer?.ControlledEntity)
+ if (uid != _playerManager.LocalPlayer?.ControlledEntity)
return;
OnUnlinkInventory?.Invoke();
/// <summary>
/// If we disable all the light behaviours we want to be able to revert the light to its original state.
/// </summary>
- private void CopyLightSettings(string property)
+ private void CopyLightSettings(EntityUid uid, string property)
{
- if (_entMan.TryGetComponent(Owner, out PointLightComponent? light))
+ if (_entMan.TryGetComponent(uid, out PointLightComponent? light))
{
var propertyValue = AnimationHelper.GetAnimatableProperty(light, property);
if (propertyValue != null)
}
else
{
- Logger.Warning($"{_entMan.GetComponent<MetaDataComponent>(Owner).EntityName} has a {nameof(LightBehaviourComponent)} but it has no {nameof(PointLightComponent)}! Check the prototype!");
+ Logger.Warning($"{_entMan.GetComponent<MetaDataComponent>(uid).EntityName} has a {nameof(LightBehaviourComponent)} but it has no {nameof(PointLightComponent)}! Check the prototype!");
}
}
{
if (!animations.HasRunningAnimation(uid, animation, KeyPrefix + container.Key))
{
- CopyLightSettings(container.LightBehaviour.Property);
+ CopyLightSettings(uid, container.LightBehaviour.Property);
container.LightBehaviour.UpdatePlaybackValues(container.Animation);
animations.Play(uid, animation, container.Animation, KeyPrefix + container.Key);
}
public override void FrameUpdate(float frameTime)
{
- foreach (var (rgb, light, sprite) in EntityManager.EntityQuery<RgbLightControllerComponent, PointLightComponent, SpriteComponent>())
+ var lightQuery = EntityQueryEnumerator<RgbLightControllerComponent, PointLightComponent, SpriteComponent>();
+ while (lightQuery.MoveNext(out var uid, out var rgb, out var light, out var sprite))
{
- var color = GetCurrentRgbColor(_gameTiming.RealTime, rgb.CreationTick.Value * _gameTiming.TickPeriod, rgb);
+ var color = GetCurrentRgbColor(_gameTiming.RealTime, rgb.CreationTick.Value * _gameTiming.TickPeriod, (uid, rgb));
- _lights.SetColor(light.Owner, color, light);
+ _lights.SetColor(uid, color, light);
if (rgb.Layers != null)
{
}
}
- foreach (var (map, rgb) in EntityQuery<MapLightComponent, RgbLightControllerComponent>())
+ var mapQuery = EntityQueryEnumerator<MapLightComponent, RgbLightControllerComponent>();
+ while (mapQuery.MoveNext(out var uid, out var map, out var rgb))
{
- var color = GetCurrentRgbColor(_gameTiming.RealTime, rgb.CreationTick.Value * _gameTiming.TickPeriod, rgb);
+ var color = GetCurrentRgbColor(_gameTiming.RealTime, rgb.CreationTick.Value * _gameTiming.TickPeriod, (uid, rgb));
map.AmbientLightColor = color;
}
}
- public static Color GetCurrentRgbColor(TimeSpan curTime, TimeSpan offset, RgbLightControllerComponent rgb)
+ public static Color GetCurrentRgbColor(TimeSpan curTime, TimeSpan offset, Entity<RgbLightControllerComponent> rgb)
{
return Color.FromHsv(new Vector4(
- (float) (((curTime.TotalSeconds - offset.TotalSeconds) * rgb.CycleRate + Math.Abs(rgb.Owner.Id * 0.1)) % 1),
+ (float) (((curTime.TotalSeconds - offset.TotalSeconds) * rgb.Comp.CycleRate + Math.Abs(rgb.Owner.Id * 0.1)) % 1),
1.0f,
1.0f,
1.0f
Enabled = false
});
- foreach (var comp in EntityQuery<NPCSteeringComponent>(true))
+ var query = AllEntityQuery<NPCSteeringComponent>();
+ while (query.MoveNext(out var uid, out var npc))
{
- RemCompDeferred<NPCSteeringComponent>(comp.Owner);
+ RemCompDeferred<NPCSteeringComponent>(uid);
}
}
}
using System.Numerics;
using System.Text;
using Content.Shared.NPC;
+using Robust.Client.GameObjects;
using Robust.Client.Graphics;
using Robust.Client.Input;
using Robust.Client.ResourceManagement;
using Robust.Shared.Enums;
using Robust.Shared.Map;
+using Robust.Shared.Map.Components;
using Robust.Shared.Timing;
using Robust.Shared.Utility;
[Dependency] private readonly IMapManager _mapManager = default!;
[Dependency] private readonly IResourceCache _cache = default!;
[Dependency] private readonly NPCSteeringSystem _steering = default!;
+ [Dependency] private readonly MapSystem _mapSystem = default!;
public PathfindingDebugMode Modes
{
}
else if (!overlayManager.HasOverlay<PathfindingOverlay>())
{
- overlayManager.AddOverlay(new PathfindingOverlay(EntityManager, _eyeManager, _inputManager, _mapManager, _cache, this));
+ overlayManager.AddOverlay(new PathfindingOverlay(EntityManager, _eyeManager, _inputManager, _mapManager, _cache, this, _mapSystem));
}
if ((value & PathfindingDebugMode.Steering) != 0x0)
private readonly IInputManager _inputManager;
private readonly IMapManager _mapManager;
private readonly PathfindingSystem _system;
+ private readonly MapSystem _mapSystem;
public override OverlaySpace Space => OverlaySpace.ScreenSpace | OverlaySpace.WorldSpace;
private readonly Font _font;
+ private List<Entity<MapGridComponent>> _grids = new();
public PathfindingOverlay(
IEntityManager entManager,
IInputManager inputManager,
IMapManager mapManager,
IResourceCache cache,
- PathfindingSystem system)
+ PathfindingSystem system,
+ MapSystem mapSystem)
{
_entManager = entManager;
_eyeManager = eyeManager;
_inputManager = inputManager;
_mapManager = mapManager;
_system = system;
+ _mapSystem = mapSystem;
_font = new VectorFont(cache.GetResource<FontResource>("/Fonts/NotoSans/NotoSans-Regular.ttf"), 10);
}
{
var found = false;
- foreach (var grid in _mapManager.FindGridsIntersecting(mouseWorldPos.MapId, aabb))
+ _grids.Clear();
+ _mapManager.FindGridsIntersecting(mouseWorldPos.MapId, aabb, ref _grids);
+
+ foreach (var grid in _grids)
{
- var netGrid = _entManager.GetNetEntity(grid.Owner);
+ var netGrid = _entManager.GetNetEntity(grid);
- if (found || !_system.Breadcrumbs.TryGetValue(netGrid, out var crumbs) || !xformQuery.TryGetComponent(grid.Owner, out var gridXform))
+ if (found || !_system.Breadcrumbs.TryGetValue(netGrid, out var crumbs) || !xformQuery.TryGetComponent(grid, out var gridXform))
continue;
var (_, _, worldMatrix, invWorldMatrix) = gridXform.GetWorldPositionRotationMatrixWithInv();
if (!_system.Polys.TryGetValue(_entManager.GetNetEntity(gridUid), out var data))
return;
- var tileRef = grid.GetTileRef(mouseWorldPos);
+ var tileRef = _mapSystem.GetTileRef(gridUid, grid, mouseWorldPos);
var localPos = tileRef.GridIndices;
var chunkOrigin = localPos / SharedPathfindingSystem.ChunkSize;
if ((_system.Modes & PathfindingDebugMode.Breadcrumbs) != 0x0 &&
mouseWorldPos.MapId == args.MapId)
{
- foreach (var grid in _mapManager.FindGridsIntersecting(mouseWorldPos.MapId, aabb))
+ _grids.Clear();
+ _mapManager.FindGridsIntersecting(mouseWorldPos.MapId, aabb, ref _grids);
+
+ foreach (var grid in _grids)
{
- var netGrid = _entManager.GetNetEntity(grid.Owner);
+ var netGrid = _entManager.GetNetEntity(grid);
if (!_system.Breadcrumbs.TryGetValue(netGrid, out var crumbs) ||
- !xformQuery.TryGetComponent(grid.Owner, out var gridXform))
+ !xformQuery.TryGetComponent(grid, out var gridXform))
{
continue;
}
if ((_system.Modes & PathfindingDebugMode.Polys) != 0x0 &&
mouseWorldPos.MapId == args.MapId)
{
- foreach (var grid in _mapManager.FindGridsIntersecting(args.MapId, aabb))
+ _grids.Clear();
+ _mapManager.FindGridsIntersecting(args.MapId, aabb, ref _grids);
+
+ foreach (var grid in _grids)
{
- var netGrid = _entManager.GetNetEntity(grid.Owner);
+ var netGrid = _entManager.GetNetEntity(grid);
if (!_system.Polys.TryGetValue(netGrid, out var data) ||
- !xformQuery.TryGetComponent(grid.Owner, out var gridXform))
+ !xformQuery.TryGetComponent(grid, out var gridXform))
continue;
var (_, _, worldMatrix, invWorldMatrix) = gridXform.GetWorldPositionRotationMatrixWithInv();
if ((_system.Modes & PathfindingDebugMode.PolyNeighbors) != 0x0 &&
mouseWorldPos.MapId == args.MapId)
{
- foreach (var grid in _mapManager.FindGridsIntersecting(args.MapId, aabb))
+ _grids.Clear();
+ _mapManager.FindGridsIntersecting(args.MapId, aabb, ref _grids);
+
+ foreach (var grid in _grids)
{
- var netGrid = _entManager.GetNetEntity(grid.Owner);
+ var netGrid = _entManager.GetNetEntity(grid);
if (!_system.Polys.TryGetValue(netGrid, out var data) ||
- !xformQuery.TryGetComponent(grid.Owner, out var gridXform))
+ !xformQuery.TryGetComponent(grid, out var gridXform))
continue;
var (_, _, worldMatrix, invMatrix) = gridXform.GetWorldPositionRotationMatrixWithInv();
if ((_system.Modes & PathfindingDebugMode.Chunks) != 0x0)
{
- foreach (var grid in _mapManager.FindGridsIntersecting(args.MapId, args.WorldBounds))
+ _grids.Clear();
+ _mapManager.FindGridsIntersecting(args.MapId, args.WorldBounds, ref _grids);
+
+ foreach (var grid in _grids)
{
- var netGrid = _entManager.GetNetEntity(grid.Owner);
+ var netGrid = _entManager.GetNetEntity(grid);
if (!_system.Breadcrumbs.TryGetValue(netGrid, out var crumbs) ||
- !xformQuery.TryGetComponent(grid.Owner, out var gridXform))
+ !xformQuery.TryGetComponent(grid, out var gridXform))
continue;
var (_, _, worldMatrix, invWorldMatrix) = gridXform.GetWorldPositionRotationMatrixWithInv();
using Content.Client.NetworkConfigurator.Systems;
-using Content.Shared.DeviceNetwork;
using Content.Shared.DeviceNetwork.Components;
using Robust.Client.Graphics;
using Robust.Shared.Enums;
-using Robust.Shared.Random;
using Robust.Shared.Map;
+using Robust.Shared.Random;
namespace Content.Client.NetworkConfigurator;
protected override void Draw(in OverlayDrawArgs args)
{
- foreach (var tracker in _entityManager.EntityQuery<NetworkConfiguratorActiveLinkOverlayComponent>())
+ var query = _entityManager.EntityQueryEnumerator<NetworkConfiguratorActiveLinkOverlayComponent>();
+ while (query.MoveNext(out var uid, out _))
{
- if (_entityManager.Deleted(tracker.Owner) || !_entityManager.TryGetComponent(tracker.Owner, out DeviceListComponent? deviceList))
+ if (_entityManager.Deleted(uid) || !_entityManager.TryGetComponent(uid, out DeviceListComponent? deviceList))
{
- _entityManager.RemoveComponentDeferred<NetworkConfiguratorActiveLinkOverlayComponent>(tracker.Owner);
+ _entityManager.RemoveComponentDeferred<NetworkConfiguratorActiveLinkOverlayComponent>(uid);
continue;
}
- if (!Colors.TryGetValue(tracker.Owner, out var color))
+ if (!Colors.TryGetValue(uid, out var color))
{
color = new Color(
_random.Next(0, 255),
_random.Next(0, 255),
_random.Next(0, 255));
- Colors.Add(tracker.Owner, color);
+ Colors.Add(uid, color);
}
- var sourceTransform = _entityManager.GetComponent<TransformComponent>(tracker.Owner);
+ var sourceTransform = _entityManager.GetComponent<TransformComponent>(uid);
if (sourceTransform.MapID == MapId.Nullspace)
{
// Can happen if the item is outside the client's view. In that case,
continue;
}
- foreach (var device in _deviceListSystem.GetAllDevices(tracker.Owner, deviceList))
+ foreach (var device in _deviceListSystem.GetAllDevices(uid, deviceList))
{
if (_entityManager.Deleted(device))
{
continue;
}
- args.WorldHandle.DrawLine(sourceTransform.WorldPosition, linkTransform.WorldPosition, Colors[tracker.Owner]);
+ args.WorldHandle.DrawLine(sourceTransform.WorldPosition, linkTransform.WorldPosition, Colors[uid]);
}
}
}
-using System.Linq;
using Content.Client.Actions;
using Content.Client.Items;
using Content.Client.Message;
using Content.Client.Stylesheets;
-using Content.Shared.Actions;
using Content.Shared.DeviceNetwork.Components;
using Content.Shared.DeviceNetwork.Systems;
using Content.Shared.Input;
return;
}
- foreach (var tracker in EntityQuery<NetworkConfiguratorActiveLinkOverlayComponent>())
+ var query = EntityQueryEnumerator<NetworkConfiguratorActiveLinkOverlayComponent>();
+ while (query.MoveNext(out var uid, out _))
{
- RemCompDeferred<NetworkConfiguratorActiveLinkOverlayComponent>(tracker.Owner);
+ RemCompDeferred<NetworkConfiguratorActiveLinkOverlayComponent>(uid);
}
_actions.RemoveAction(overlay.Action);
using Robust.Client.ResourceManagement;
using Robust.Shared.Enums;
using Robust.Shared.Map;
+using Robust.Shared.Map.Components;
using Robust.Shared.Timing;
using Robust.Shared.Utility;
using static Content.Shared.NodeContainer.NodeVis;
private readonly Dictionary<(int, int), NodeRenderData> _nodeIndex = new();
private readonly Dictionary<EntityUid, Dictionary<Vector2i, List<(GroupData, NodeDatum)>>> _gridIndex = new ();
+ private List<Entity<MapGridComponent>> _grids = new();
private readonly Font _font;
var worldAABB = overlayDrawArgs.WorldAABB;
var xformQuery = _entityManager.GetEntityQuery<TransformComponent>();
- foreach (var grid in _mapManager.FindGridsIntersecting(map, worldAABB))
+ _grids.Clear();
+ _mapManager.FindGridsIntersecting(map, worldAABB, ref _grids);
+
+ foreach (var grid in _grids)
{
- foreach (var entity in _lookup.GetEntitiesIntersecting(grid.Owner, worldAABB))
+ foreach (var entity in _lookup.GetEntitiesIntersecting(grid, worldAABB))
{
if (!_system.Entities.TryGetValue(entity, out var nodeData))
continue;
- var gridDict = _gridIndex.GetOrNew(grid.Owner);
+ var gridDict = _gridIndex.GetOrNew(grid);
var coords = xformQuery.GetComponent(entity).Coordinates;
// TODO: This probably shouldn't be capable of returning NaN...
if (float.IsNaN(coords.Position.X) || float.IsNaN(coords.Position.Y))
continue;
- var tile = gridDict.GetOrNew(grid.TileIndicesFor(coords));
+ var tile = gridDict.GetOrNew(grid.Comp.TileIndicesFor(coords));
foreach (var (group, nodeDatum) in nodeData)
{
foreach (var (gridId, gridDict) in _gridIndex)
{
var grid = _mapManager.GetGrid(gridId);
- var (_, _, worldMatrix, invMatrix) = _entityManager.GetComponent<TransformComponent>(grid.Owner).GetWorldPositionRotationMatrixWithInv();
+ var (_, _, worldMatrix, invMatrix) = _entityManager.GetComponent<TransformComponent>(gridId).GetWorldPositionRotationMatrixWithInv();
var lCursorBox = invMatrix.TransformBox(cursorBox);
foreach (var (pos, list) in gridDict)
return;
if (TryComp(_lastHoveredEntity, out InteractionOutlineComponent? outline))
- outline.OnMouseLeave();
+ outline.OnMouseLeave(_lastHoveredEntity.Value);
}
public void SetEnabled(bool enabled)
return;
if (TryComp(_lastHoveredEntity, out InteractionOutlineComponent? outline))
- outline.OnMouseLeave();
+ outline.OnMouseLeave(_lastHoveredEntity.Value);
}
public override void FrameUpdate(float frameTime)
{
if (entityToClick != null && TryComp(entityToClick, out outline))
{
- outline.UpdateInRange(inRange, renderScale);
+ outline.UpdateInRange(entityToClick.Value, inRange, renderScale);
}
return;
if (_lastHoveredEntity != null && !Deleted(_lastHoveredEntity) &&
TryComp(_lastHoveredEntity, out outline))
{
- outline.OnMouseLeave();
+ outline.OnMouseLeave(_lastHoveredEntity.Value);
}
_lastHoveredEntity = entityToClick;
if (_lastHoveredEntity != null && TryComp(_lastHoveredEntity, out outline))
{
- outline.OnMouseEnter(inRange, renderScale);
+ outline.OnMouseEnter(_lastHoveredEntity.Value, inRange, renderScale);
}
}
}
using Robust.Shared.Enums;
using Robust.Shared.GameStates;
using Robust.Shared.Map;
+using Robust.Shared.Map.Components;
namespace Content.Client.Pinpointer;
public override OverlaySpace Space => OverlaySpace.WorldSpace;
+ private List<Entity<MapGridComponent>> _grids = new();
+
public NavMapOverlay(IEntityManager entManager, IMapManager mapManager)
{
_entManager = entManager;
var xformQuery = _entManager.GetEntityQuery<TransformComponent>();
var scale = Matrix3.CreateScale(new Vector2(1f, 1f));
- foreach (var grid in _mapManager.FindGridsIntersecting(args.MapId, args.WorldBounds))
+ _grids.Clear();
+ _mapManager.FindGridsIntersecting(args.MapId, args.WorldBounds, ref _grids);
+
+ foreach (var grid in _grids)
{
- if (!query.TryGetComponent(grid.Owner, out var navMap) || !xformQuery.TryGetComponent(grid.Owner, out var xform))
+ if (!query.TryGetComponent(grid, out var navMap) || !xformQuery.TryGetComponent(grid.Owner, out var xform))
continue;
// TODO: Faster helper method
args.WorldHandle.SetTransform(matty);
- for (var x = Math.Floor(localAABB.Left); x <= Math.Ceiling(localAABB.Right); x += SharedNavMapSystem.ChunkSize * grid.TileSize)
+ for (var x = Math.Floor(localAABB.Left); x <= Math.Ceiling(localAABB.Right); x += SharedNavMapSystem.ChunkSize * grid.Comp.TileSize)
{
- for (var y = Math.Floor(localAABB.Bottom); y <= Math.Ceiling(localAABB.Top); y += SharedNavMapSystem.ChunkSize * grid.TileSize)
+ for (var y = Math.Floor(localAABB.Bottom); y <= Math.Ceiling(localAABB.Top); y += SharedNavMapSystem.ChunkSize * grid.Comp.TileSize)
{
var floored = new Vector2i((int) x, (int) y);
continue;
var tile = chunk.Origin * SharedNavMapSystem.ChunkSize + SharedNavMapSystem.GetTile(mask);
- args.WorldHandle.DrawRect(new Box2(tile * grid.TileSize, (tile + 1) * grid.TileSize), Color.Aqua, false);
+ args.WorldHandle.DrawRect(new Box2(tile * grid.Comp.TileSize, (tile + 1) * grid.Comp.TileSize), Color.Aqua, false);
}
}
}
-using System.Linq;
using System.Numerics;
using Content.Shared.Radiation.Components;
using Robust.Client.Graphics;
var currentEyeLoc = currentEye.Position;
- var pulses = _entityManager.EntityQuery<RadiationPulseComponent>();
- foreach (var pulse in pulses) //Add all pulses that are not added yet but qualify
+ var pulses = _entityManager.EntityQueryEnumerator<RadiationPulseComponent>();
+ //Add all pulses that are not added yet but qualify
+ while (pulses.MoveNext(out var pulseEntity, out var pulse))
{
- var pulseEntity = pulse.Owner;
-
if (!_pulses.ContainsKey(pulseEntity) && PulseQualifies(pulseEntity, currentEyeLoc))
{
_pulses.Add(
-using System.Linq;
using Content.Shared.Movement.Components;
using Robust.Client.GameObjects;
using Robust.Shared.Map;
return true;
}
- var uid = EntityQuery<MapGridComponent>().MaxBy(x => x.LocalAABB.Size.LengthSquared())?.Owner;
- coords = new EntityCoordinates(uid ?? default, default);
- return uid != null;
+ Entity<MapGridComponent>? maxUid = null;
+ float? maxSize = null;
+ while (EntityQueryEnumerator<MapGridComponent>().MoveNext(out var uid, out var grid))
+ {
+ var size = grid.LocalAABB.Size.LengthSquared();
+ if (maxSize == null || size > maxSize)
+ {
+ maxUid = (uid, grid);
+ maxSize = size;
+ }
+ }
+
+ coords = new EntityCoordinates(maxUid ?? default, default);
+ return maxUid != null;
}
private void OnTerminating(EntityUid uid, ReplaySpectatorComponent component, ref EntityTerminatingEvent args)
Dirty(uid, light);
}
- protected override void OnZap(RevenantOverloadedLightsComponent component)
+ protected override void OnZap(Entity<RevenantOverloadedLightsComponent> component)
{
}
}
};
- AnimationSystem.Play(animationComp, animation, animationKey);
+ AnimationSystem.Play((uid, animationComp), animation, animationKey);
}
}
using Robust.Client.Graphics;
using Robust.Client.UserInterface;
using Robust.Shared.Map;
+using Robust.Shared.Map.Components;
using Robust.Shared.Physics;
using Robust.Shared.Physics.Collision.Shapes;
/// </summary>
public Dictionary<NetEntity, List<DockingInterfaceState>> Docks = new();
+ private List<Entity<MapGridComponent>> _grids = new();
+
public DockingControl()
{
_entManager = IoCManager.Resolve<IEntityManager>();
// TODO: Getting some overdraw so need to fix that.
var xformQuery = _entManager.GetEntityQuery<TransformComponent>();
- foreach (var grid in _mapManager.FindGridsIntersecting(gridXform.MapID,
- new Box2(worldPos - RangeVector, worldPos + RangeVector)))
+ _grids.Clear();
+ _mapManager.FindGridsIntersecting(gridXform.MapID, new Box2(worldPos - RangeVector, worldPos + RangeVector));
+
+ foreach (var grid in _grids)
{
if (grid.Owner == GridEntity)
continue;
// Draw the fixtures before drawing any docks in range.
- if (!_entManager.TryGetComponent<FixturesComponent>(grid.Owner, out var gridFixtures))
+ if (!_entManager.TryGetComponent<FixturesComponent>(grid, out var gridFixtures))
continue;
- var gridMatrix = xformQuery.GetComponent(grid.Owner).WorldMatrix;
+ var gridMatrix = xformQuery.GetComponent(grid).WorldMatrix;
Matrix3.Multiply(in gridMatrix, in invMatrix, out var matty);
}
// Draw any docks on that grid
- if (Docks.TryGetValue(_entManager.GetNetEntity(grid.Owner), out var gridDocks))
+ if (Docks.TryGetValue(_entManager.GetNetEntity(grid), out var gridDocks))
{
foreach (var dock in gridDocks)
{
using Content.Shared.Shuttles.BUIStates;
using Content.Shared.Shuttles.Components;
using JetBrains.Annotations;
-using Content.Shared.Shuttles.Systems;
using Robust.Client.Graphics;
-using Robust.Client.Input;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controls;
using Robust.Shared.Collections;
using Robust.Shared.Map;
using Robust.Shared.Map.Components;
using Robust.Shared.Physics;
-using Robust.Shared.Physics.Collision.Shapes;
using Robust.Shared.Physics.Components;
using Robust.Shared.Utility;
/// </summary>
public Action<EntityCoordinates>? OnRadarClick;
+ private List<Entity<MapGridComponent>> _grids = new();
+
public RadarControl() : base(64f, 256f, 256f)
{
_transform = _entManager.System<SharedTransformSystem>();
var shown = new HashSet<EntityUid>();
+ _grids.Clear();
+ _mapManager.FindGridsIntersecting(xform.MapID, new Box2(pos - MaxRadarRangeVector, pos + MaxRadarRangeVector), ref _grids);
+
// Draw other grids... differently
- foreach (var grid in _mapManager.FindGridsIntersecting(xform.MapID,
- new Box2(pos - MaxRadarRangeVector, pos + MaxRadarRangeVector)))
+ foreach (var grid in _grids)
{
var gUid = grid.Owner;
if (gUid == ourGridId || !fixturesQuery.HasComponent(gUid))
(iff == null && IFFComponent.ShowIFFDefault ||
(iff.Flags & IFFFlags.HideLabel) == 0x0))
{
- var gridBounds = grid.LocalAABB;
+ var gridBounds = grid.Comp.LocalAABB;
Label label;
if (!_iffControls.TryGetValue(gUid, out var control))
}
}
- foreach (var comp in EntityQuery<FadingSpriteComponent>(true))
+ var query = AllEntityQuery<FadingSpriteComponent>();
+ while (query.MoveNext(out var uid, out var comp))
{
if (_comps.Contains(comp))
continue;
- if (!spriteQuery.TryGetComponent(comp.Owner, out var sprite))
+ if (!spriteQuery.TryGetComponent(uid, out var sprite))
continue;
var newColor = Math.Min(sprite.Color.A + change, comp.OriginalAlpha);
}
else
{
- RemCompDeferred<FadingSpriteComponent>(comp.Owner);
+ RemCompDeferred<FadingSpriteComponent>(uid);
}
}
{
if (TryComp<SpriteComponent>(uid, out var sprite))
{
- component.RSIPath ??= sprite.BaseRSI!.Path!;
+ component.RSIPath ??= sprite.BaseRSI!.Path;
}
}
private void OnAppearance(EntityUid uid, ItemMapperComponent component, ref AppearanceChangeEvent args)
{
- if (TryComp<SpriteComponent>(component.Owner, out var spriteComponent))
+ if (TryComp<SpriteComponent>(uid, out var spriteComponent))
{
if (component.SpriteLayers.Count == 0)
{
- InitLayers(component, spriteComponent, args.Component);
+ InitLayers((uid, component, spriteComponent, args.Component));
}
- EnableLayers(component, spriteComponent, args.Component);
+ EnableLayers((uid, component, spriteComponent, args.Component));
}
}
- private void InitLayers(ItemMapperComponent component, SpriteComponent spriteComponent, AppearanceComponent appearance)
+ private void InitLayers(Entity<ItemMapperComponent, SpriteComponent, AppearanceComponent> ent)
{
- if (!_appearance.TryGetData<ShowLayerData>(appearance.Owner, StorageMapVisuals.InitLayers, out var wrapper, appearance))
+ var (owner, component, spriteComponent, appearance) = ent;
+ if (!_appearance.TryGetData<ShowLayerData>(owner, StorageMapVisuals.InitLayers, out var wrapper, appearance))
return;
component.SpriteLayers.AddRange(wrapper.QueuedEntities);
}
}
- private void EnableLayers(ItemMapperComponent component, SpriteComponent spriteComponent, AppearanceComponent appearance)
+ private void EnableLayers(Entity<ItemMapperComponent, SpriteComponent, AppearanceComponent> ent)
{
- if (!_appearance.TryGetData<ShowLayerData>(appearance.Owner, StorageMapVisuals.LayerChanged, out var wrapper, appearance))
+ var (owner, component, spriteComponent, appearance) = ent;
+ if (!_appearance.TryGetData<ShowLayerData>(owner, StorageMapVisuals.LayerChanged, out var wrapper, appearance))
return;
foreach (var layerName in component.SpriteLayers)
-using Content.Client.Hands;
using Content.Shared.Hands.EntitySystems;
using Content.Shared.Inventory;
using Content.Shared.SubFloor;
var playerPos = _transform.GetWorldPosition(playerXform, xformQuery);
var playerMap = playerXform.MapID;
var range = 0f;
- HashSet<SubFloorHideComponent> inRange;
+ HashSet<Entity<SubFloorHideComponent>> inRange;
var scannerQuery = GetEntityQuery<TrayScannerComponent>();
// TODO: Should probably sub to player attached changes / inventory changes but inventory's
canSee = true;
}
+ inRange = new HashSet<Entity<SubFloorHideComponent>>();
+
if (canSee)
{
- inRange = _lookup.GetComponentsInRange<SubFloorHideComponent>(playerMap, playerPos, range);
+ _lookup.GetEntitiesInRange(playerMap, playerPos, range, inRange);
- foreach (var comp in inRange)
+ foreach (var (uid, comp) in inRange)
{
- var uid = comp.Owner;
if (!comp.IsUnderCover || !comp.BlockAmbience | !comp.BlockInteractions)
continue;
EnsureComp<TrayRevealedComponent>(uid);
}
}
- else
- {
- inRange = new HashSet<SubFloorHideComponent>();
- }
var revealedQuery = AllEntityQuery<TrayRevealedComponent, SpriteComponent, TransformComponent>();
var subfloorQuery = GetEntityQuery<SubFloorHideComponent>();
xform.MapID != MapId.Nullspace &&
xform.MapID == playerMap &&
xform.Anchored &&
- inRange.Contains(subfloor))
+ inRange.Contains((uid, subfloor)))
{
// Due to the fact client is predicting this server states will reset it constantly
if ((!_appearance.TryGetData(uid, SubFloorVisuals.ScannerRevealed, out bool value) || !value) &&
if (!EntityHover)
return;
- var tempQualifier = HoverSpriteView.Sprite;
+ var tempQualifier = HoverSpriteView.Ent;
if (tempQualifier != null)
{
- IoCManager.Resolve<IEntityManager>().QueueDeleteEntity(tempQualifier.Owner);
+ IoCManager.Resolve<IEntityManager>().QueueDeleteEntity(tempQualifier);
}
HoverSpriteView.SetEntity(null);
using Robust.Client.ResourceManagement;
using Robust.Client.Utility;
using Robust.Shared.Enums;
-using Robust.Shared.Graphics;
using Robust.Shared.Graphics.RSI;
using Robust.Shared.Map;
+using Robust.Shared.Map.Components;
using Robust.Shared.Physics.Components;
using Robust.Shared.Prototypes;
using Robust.Shared.Timing;
var xformQuery = _entManager.GetEntityQuery<TransformComponent>();
var weatherIgnoreQuery = _entManager.GetEntityQuery<IgnoreWeatherComponent>();
- foreach (var grid in _mapManager.FindGridsIntersecting(mapId, worldAABB))
+ // idk if this is safe to cache in a field and clear sloth help
+ var grids = new List<Entity<MapGridComponent>>();
+ _mapManager.FindGridsIntersecting(mapId, worldAABB, ref grids);
+
+ foreach (var grid in grids)
{
- var matrix = _transform.GetWorldMatrix(grid.Owner, xformQuery);
+ var matrix = _transform.GetWorldMatrix(grid, xformQuery);
Matrix3.Multiply(in matrix, in invMatrix, out var matty);
worldHandle.SetTransform(matty);
- foreach (var tile in grid.GetTilesIntersecting(worldAABB))
+ foreach (var tile in grid.Comp.GetTilesIntersecting(worldAABB))
{
// Ignored tiles for stencil
if (_weather.CanWeatherAffect(grid, tile, weatherIgnoreQuery, bodyQuery))
continue;
}
- var gridTile = new Box2(tile.GridIndices * grid.TileSize,
- (tile.GridIndices + Vector2i.One) * grid.TileSize);
+ var gridTile = new Box2(tile.GridIndices * grid.Comp.TileSize,
+ (tile.GridIndices + Vector2i.One) * grid.Comp.TileSize);
worldHandle.DrawRect(gridTile, Color.White);
}
[Dependency] private readonly IOverlayManager _overlayManager = default!;
[Dependency] private readonly IPlayerManager _playerManager = default!;
[Dependency] private readonly AudioSystem _audio = default!;
+ [Dependency] private readonly MapSystem _mapSystem = default!;
[Dependency] private readonly SharedPhysicsSystem _physics = default!;
[Dependency] private readonly SharedTransformSystem _transform = default!;
// Work out tiles nearby to determine volume.
if (TryComp<MapGridComponent>(entXform.GridUid, out var grid))
{
+ var gridId = entXform.GridUid.Value;
// Floodfill to the nearest tile and use that for audio.
- var seed = grid.GetTileRef(entXform.Coordinates);
+ var seed = _mapSystem.GetTileRef(gridId, grid, entXform.Coordinates);
var frontier = new Queue<TileRef>();
frontier.Enqueue(seed);
// If we don't have a nearest node don't play any sound.
continue;
}
- frontier.Enqueue(grid.GetTileRef(new Vector2i(x, y) + node.GridIndices));
+ frontier.Enqueue(_mapSystem.GetTileRef(gridId, grid, new Vector2i(x, y) + node.GridIndices));
}
}
{
mapData.MapId = Server.MapMan.CreateMap();
mapData.MapUid = Server.MapMan.GetMapEntityId(mapData.MapId);
- mapData.MapGrid = Server.MapMan.CreateGrid(mapData.MapId);
- mapData.GridUid = mapData.MapGrid.Owner; // Fixing this requires an engine PR.
+ var mapGrid = Server.MapMan.CreateGridEntity(mapData.MapId);
+ mapData.MapGrid = mapGrid;
+ mapData.GridUid = mapGrid.Owner; // Fixing this requires an engine PR.
mapData.GridCoords = new EntityCoordinates(mapData.GridUid, 0, 0);
var plating = tileDefinitionManager["Plating"];
var platingTile = new Tile(plating.TileId);
public sealed class FluidSpill
{
private static PuddleComponent? GetPuddle(IEntityManager entityManager, MapGridComponent mapGrid, Vector2i pos)
+ {
+ return GetPuddleEntity(entityManager, mapGrid, pos)?.Comp;
+ }
+
+ private static Entity<PuddleComponent>? GetPuddleEntity(IEntityManager entityManager, MapGridComponent mapGrid, Vector2i pos)
{
foreach (var uid in mapGrid.GetAnchoredEntities(pos))
{
if (entityManager.TryGetComponent(uid, out PuddleComponent? puddleComponent))
- return puddleComponent;
+ return (uid, puddleComponent);
}
return null;
await server.WaitPost(() =>
{
mapId = mapManager.CreateMap();
- var grid = mapManager.CreateGrid(mapId);
+ var grid = mapManager.CreateGridEntity(mapId);
gridId = grid.Owner;
for (var x = 0; x < 3; x++)
{
for (var y = 0; y < 3; y++)
{
- grid.SetTile(new Vector2i(x, y), new Tile(1));
+ grid.Comp.SetTile(new Vector2i(x, y), new Tile(1));
}
}
- entityManager.SpawnEntity("WallReinforced", grid.GridTileToLocal(new Vector2i(0, 1)));
- entityManager.SpawnEntity("WallReinforced", grid.GridTileToLocal(new Vector2i(1, 0)));
+ entityManager.SpawnEntity("WallReinforced", grid.Comp.GridTileToLocal(new Vector2i(0, 1)));
+ entityManager.SpawnEntity("WallReinforced", grid.Comp.GridTileToLocal(new Vector2i(1, 0)));
});
await server.WaitAssertion(() =>
{
var grid = mapManager.GetGrid(gridId);
- var puddle = GetPuddle(entityManager, grid, puddleOrigin);
-
+ var puddle = GetPuddleEntity(entityManager, grid, puddleOrigin);
#pragma warning disable NUnit2045 // Interdependent tests
Assert.That(puddle, Is.Not.Null);
- Assert.That(puddleSystem.CurrentVolume(puddle!.Owner, puddle), Is.EqualTo(FixedPoint2.New(100)));
+ Assert.That(puddleSystem.CurrentVolume(puddle!.Value.Owner, puddle), Is.EqualTo(FixedPoint2.New(100)));
#pragma warning restore NUnit2045
for (var x = 0; x < 3; x++)
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.UserInterface;
if (proto == null)
return;
- grid = MapMan.CreateGrid(MapData.MapId);
- gridUid = grid.Owner;
+ var gridEnt = MapMan.CreateGridEntity(MapData.MapId);
+ grid = gridEnt;
+ gridUid = gridEnt;
var gridXform = SEntMan.GetComponent<TransformComponent>(gridUid);
Transform.SetWorldPosition(gridXform, pos.Position);
grid.SetTile(SEntMan.GetCoordinates(coords ?? TargetCoords), tile);
using System.Collections.Generic;
using System.IO;
using System.Linq;
-using System.Threading;
using Content.Server.GameTicking;
using Content.Server.Maps;
using Content.Server.Shuttles.Components;
+using Content.Server.Shuttles.Systems;
using Content.Server.Spawners.Components;
using Content.Server.Station.Components;
using Content.Shared.CCVar;
using Robust.Shared.Configuration;
using Robust.Shared.ContentPack;
using Robust.Shared.GameObjects;
-using Robust.Shared.Utility;
using Robust.Shared.Map;
using Robust.Shared.Map.Components;
using Robust.Shared.Prototypes;
+using Robust.Shared.Utility;
using YamlDotNet.RepresentationModel;
-using ShuttleSystem = Content.Server.Shuttles.Systems.ShuttleSystem;
namespace Content.IntegrationTests.Tests
{
EntityUid? targetGrid = null;
var memberQuery = entManager.GetEntityQuery<StationMemberComponent>();
- var grids = mapManager.GetAllMapGrids(mapId).ToList();
+ var grids = mapManager.GetAllGrids(mapId).ToList();
var gridUids = grids.Select(o => o.Owner).ToList();
targetGrid = gridUids.First();
if (!memberQuery.HasComponent(gridEnt))
continue;
- var area = grid.LocalAABB.Width * grid.LocalAABB.Height;
+ var area = grid.Comp.LocalAABB.Width * grid.Comp.LocalAABB.Height;
if (area > largest)
{
+using System.Linq;
using Content.Server.Administration.Logs;
using Content.Server.Kitchen.Components;
using Content.Server.Popups;
using Content.Shared.StatusIcon;
using Robust.Shared.Prototypes;
using Robust.Shared.Random;
-using System.Linq;
namespace Content.Server.Access.Systems
{
}
id.JobIcon = jobIcon.ID;
- Dirty(id);
+ Dirty(uid, id);
if (player != null)
{
_adminLogger.Add(LogType.Identity, LogImpact.Low,
- $"{ToPrettyString(player.Value):player} has changed the job icon of {ToPrettyString(id.Owner):entity} to {jobIcon} ");
+ $"{ToPrettyString(player.Value):player} has changed the job icon of {ToPrettyString(uid):entity} to {jobIcon} ");
}
return true;
}
/// <summary>
- /// Changes the <see cref="Entity.Name"/> of <see cref="Component.Owner"/>.
+ /// Changes the name of the id's owner.
/// </summary>
/// <remarks>
/// If either <see cref="FullName"/> or <see cref="JobTitle"/> is empty, it's replaced by placeholders.
if (_entManager.TryGetComponent<EntityStorageComponent>(parent, out var storage))
{
- entstorage.Remove(entityUid.Value, storage.Owner, storage);
+ entstorage.Remove(entityUid.Value, parent, storage);
}
else
{
Act = () =>
{
var baseXform = Transform(args.Target);
- foreach (var part in _bodySystem.GetBodyChildrenOfType(body.Owner, BodyPartType.Hand, body))
+ foreach (var part in _bodySystem.GetBodyChildrenOfType(args.Target, BodyPartType.Hand, body))
{
_transformSystem.AttachToGridOrMap(part.Id);
break;
public override void Update(float frameTime)
{
- foreach (var buffering in EntityQuery<BufferingComponent>())
+ var query = EntityQueryEnumerator<BufferingComponent>();
+ while (query.MoveNext(out var uid, out var buffering))
{
if (buffering.BufferingIcon is not null)
{
continue;
Del(buffering.BufferingIcon.Value);
- RemComp<AdminFrozenComponent>(buffering.Owner);
+ RemComp<AdminFrozenComponent>(uid);
buffering.TimeTilNextBuffer = _random.NextFloat(buffering.MinimumTimeTilNextBuffer, buffering.MaximumTimeTilNextBuffer);
buffering.BufferingIcon = null;
}
continue;
buffering.BufferingTimer = _random.NextFloat(buffering.MinimumBufferTime, buffering.MaximumBufferTime);
- buffering.BufferingIcon = Spawn("BufferingIcon", new EntityCoordinates(buffering.Owner, Vector2.Zero));
- EnsureComp<AdminFrozenComponent>(buffering.Owner);
+ buffering.BufferingIcon = Spawn("BufferingIcon", new EntityCoordinates(uid, Vector2.Zero));
+ EnsureComp<AdminFrozenComponent>(uid);
}
}
}
using Content.Server.Power.Components;
using Content.Server.Station.Systems;
using Content.Shared.AlertLevel;
-using Robust.Server.GameObjects;
namespace Content.Server.AlertLevel;
private void OnAlertChanged(AlertLevelChangedEvent args)
{
- foreach (var (_, appearance) in EntityManager.EntityQuery<AlertLevelDisplayComponent, AppearanceComponent>())
+ var query = EntityQueryEnumerator<AlertLevelDisplayComponent, AppearanceComponent>();
+ while (query.MoveNext(out var uid, out _, out var appearance))
{
- _appearance.SetData(appearance.Owner, AlertLevelDisplay.CurrentLevel, args.AlertLevel, appearance);
+ _appearance.SetData(uid, AlertLevelDisplay.CurrentLevel, args.AlertLevel, appearance);
}
}
using Content.Server.Chat.Systems;
using Content.Server.Station.Systems;
using Content.Shared.CCVar;
-using Content.Shared.PDA;
using Robust.Shared.Audio;
using Robust.Shared.Configuration;
using Robust.Shared.Prototypes;
return;
}
- foreach (var comp in EntityQuery<AlertLevelComponent>())
+ var query = EntityQueryEnumerator<AlertLevelComponent>();
+ while (query.MoveNext(out var uid, out var comp))
{
comp.AlertLevels = alerts;
defaultLevel = comp.AlertLevels.Levels.Keys.First();
}
- SetLevel(comp.Owner, defaultLevel, true, true, true);
+ SetLevel(uid, defaultLevel, true, true, true);
}
}
using Content.Server.Animals.Components;
-using Content.Server.DoAfter;
-using Content.Server.Nutrition.Components;
using Content.Server.Popups;
using Content.Shared.Chemistry.Components;
-using Content.Shared.Chemistry.Components.SolutionManager;
using Content.Shared.Chemistry.EntitySystems;
using Content.Shared.DoAfter;
using Content.Shared.IdentityManagement;
SubscribeLocalEvent<UdderComponent, GetVerbsEvent<AlternativeVerb>>(AddMilkVerb);
SubscribeLocalEvent<UdderComponent, MilkingDoAfterEvent>(OnDoAfter);
}
+
public override void Update(float frameTime)
{
- foreach (var udder in EntityManager.EntityQuery<UdderComponent>(false))
+ var query = EntityQueryEnumerator<UdderComponent>();
+ while (query.MoveNext(out var uid, out var udder))
{
udder.AccumulatedFrameTime += frameTime;
udder.AccumulatedFrameTime -= udder.UpdateRate;
// Actually there is food digestion so no problem with instant reagent generation "OnFeed"
- if (EntityManager.TryGetComponent(udder.Owner, out HungerComponent? hunger))
+ if (EntityManager.TryGetComponent(uid, out HungerComponent? hunger))
{
// Is there enough nutrition to produce reagent?
if (_hunger.GetHungerThreshold(hunger) < HungerThreshold.Peckish)
continue;
}
- if (!_solutionContainerSystem.TryGetSolution(udder.Owner, udder.TargetSolutionName,
+ if (!_solutionContainerSystem.TryGetSolution(uid, udder.TargetSolutionName,
out var solution))
continue;
//TODO: toxins from bloodstream !?
- _solutionContainerSystem.TryAddReagent(udder.Owner, solution, udder.ReagentId,
+ _solutionContainerSystem.TryAddReagent(uid, solution, udder.ReagentId,
udder.QuantityPerUpdate, out var accepted);
}
}
var xformQuery = GetEntityQuery<TransformComponent>();
var xform = xformQuery.GetComponent(uid);
var range = component.MaxShuffleRadius * args.Severity;
- var allEnts = _lookup.GetComponentsInRange<MobStateComponent>(xform.Coordinates, range)
- .Select(x => x.Owner).ToList();
- allEnts.Add(uid);
+ var mobs = new HashSet<Entity<MobStateComponent>>();
+ _lookup.GetEntitiesInRange(xform.Coordinates, range, mobs);
+ var allEnts = new List<EntityUid>(mobs.Select(m => m.Owner)) { uid };
var coords = new List<Vector2>();
foreach (var ent in allEnts)
{
var mapPos = _xform.GetWorldPosition(xform);
var radius = component.SupercriticalTeleportRadius;
var gridBounds = new Box2(mapPos - new Vector2(radius, radius), mapPos + new Vector2(radius, radius));
- foreach (var comp in _lookup.GetComponentsInRange<MobStateComponent>(xform.Coordinates, component.MaxShuffleRadius))
+ var mobs = new HashSet<Entity<MobStateComponent>>();
+ _lookup.GetEntitiesInRange(xform.Coordinates, component.MaxShuffleRadius, mobs);
+ foreach (var comp in mobs)
{
var ent = comp.Owner;
var randomX = _random.NextFloat(gridBounds.Left, gridBounds.Right);
using Content.Server.Electrocution;
-using Content.Server.Emp;
+using Content.Server.Emp;
using Content.Server.Lightning;
using Content.Server.Power.Components;
using Content.Shared.Anomaly.Components;
{
var range = component.MaxElectrocuteRange * args.Stability;
var xform = Transform(uid);
- foreach (var comp in _lookup.GetComponentsInRange<MobStateComponent>(xform.MapPosition, range))
+ foreach (var (ent, comp) in _lookup.GetEntitiesInRange<MobStateComponent>(xform.MapPosition, range))
{
- var ent = comp.Owner;
_lightning.ShootLightning(uid, ent);
}
}
{
base.Update(frameTime);
- foreach (var (elec, anom, xform) in EntityQuery<ElectricityAnomalyComponent, AnomalyComponent, TransformComponent>())
+ var query = EntityQueryEnumerator<ElectricityAnomalyComponent, AnomalyComponent, TransformComponent>();
+ while (query.MoveNext(out var uid, out var elec, out var anom, out var xform))
{
if (_timing.CurTime < elec.NextSecond)
continue;
elec.NextSecond = _timing.CurTime + TimeSpan.FromSeconds(1);
- var owner = xform.Owner;
-
if (!_random.Prob(elec.PassiveElectrocutionChance * anom.Stability))
continue;
var damage = (int) (elec.MaxElectrocuteDamage * anom.Severity);
var duration = elec.MaxElectrocuteDuration * anom.Severity;
- foreach (var comp in _lookup.GetComponentsInRange<StatusEffectsComponent>(xform.MapPosition, range))
+ foreach (var (ent, comp) in _lookup.GetEntitiesInRange<StatusEffectsComponent>(xform.MapPosition, range))
{
- var ent = comp.Owner;
-
- _electrocution.TryDoElectrocution(ent, owner, damage, duration, true, statusEffects: comp, ignoreInsulation: true);
+ _electrocution.TryDoElectrocution(ent, uid, damage, duration, true, statusEffects: comp, ignoreInsulation: true);
}
}
}
using System.Linq;
using Content.Server.Anomaly.Components;
+using Content.Shared.Anomaly.Components;
using Content.Shared.Chemistry.Components.SolutionManager;
using Content.Shared.Chemistry.EntitySystems;
-using Content.Shared.Anomaly.Components;
namespace Content.Server.Anomaly.Effects;
/// <summary>
//We get all the entity in the radius into which the reagent will be injected.
var xformQuery = GetEntityQuery<TransformComponent>();
var xform = xformQuery.GetComponent(uid);
- var allEnts = _lookup.GetComponentsInRange<InjectableSolutionComponent>(xform.MapPosition, injectRadius)
+ var allEnts = _lookup.GetEntitiesInRange<InjectableSolutionComponent>(xform.MapPosition, injectRadius)
.Select(x => x.Owner).ToList();
//for each matching entity found
public void IgniteNearby(EntityUid uid, EntityCoordinates coordinates, float severity, float radius)
{
- foreach (var flammable in _lookup.GetComponentsInRange<FlammableComponent>(coordinates, radius))
+ var flammables = new HashSet<Entity<FlammableComponent>>();
+ _lookup.GetEntitiesInRange(coordinates, radius, flammables);
+
+ foreach (var flammable in flammables)
{
var ent = flammable.Owner;
var stackAmount = 1 + (int) (severity / 0.15f);
using Content.Shared.Administration;
using Content.Shared.Atmos;
using Robust.Shared.Console;
-using Robust.Shared.Map;
+using Robust.Shared.Map.Components;
namespace Content.Server.Atmos.Commands
{
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.";
return;
}
- if (!_mapManager.TryGetGrid(gridId, out var grid))
+ if (!_entManager.HasComponent<MapGridComponent>(gridId))
{
shell.WriteLine("Invalid grid ID.");
return;
var atmosphereSystem = _entManager.System<AtmosphereSystem>();
- foreach (var tile in atmosphereSystem.GetAllMixtures(grid.Owner, true))
+ foreach (var tile in atmosphereSystem.GetAllMixtures(gridId.Value, true))
{
tile.AdjustMoles(gasId, moles);
}
using Content.Shared.Administration;
using Content.Shared.Atmos;
using Robust.Shared.Console;
-using Robust.Shared.Map;
+using Robust.Shared.Map.Components;
namespace Content.Server.Atmos.Commands
{
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).";
return;
}
- if (!gridId.Value.IsValid() || !_mapManager.TryGetGrid(gridId, out var gridComp))
+ if (!gridId.Value.IsValid() || !_entManager.HasComponent<MapGridComponent>(gridId))
{
shell.WriteLine("Invalid grid ID.");
return;
var atmosphereSystem = _entManager.System<AtmosphereSystem>();
var tiles = 0;
- foreach (var tile in atmosphereSystem.GetAllMixtures(gridComp.Owner, true))
+ foreach (var tile in atmosphereSystem.GetAllMixtures(gridId.Value, true))
{
tiles++;
tile.Temperature = temperature;
using Content.Server.Atmos.EntitySystems;
using Content.Shared.Administration;
using Content.Shared.Atmos;
-using Robust.Server.GameObjects;
using Robust.Shared.Console;
-using Robust.Shared.GameObjects;
-using Robust.Shared.Map;
-using Robust.Shared.Maths;
+using Robust.Shared.Map.Components;
namespace Content.Server.Atmos.Commands
{
public sealed class SetTemperatureCommand : IConsoleCommand
{
[Dependency] private readonly IEntityManager _entities = default!;
- [Dependency] private readonly IMapManager _mapManager = default!;
public string Command => "settemp";
public string Description => "Sets a tile's temperature (in kelvin).";
return;
}
- if (!_mapManager.TryGetGrid(gridId, out var grid))
+ if (!_entities.HasComponent<MapGridComponent>(gridId))
{
shell.WriteError("Invalid grid.");
return;
var atmospheres = _entities.EntitySysManager.GetEntitySystem<AtmosphereSystem>();
var indices = new Vector2i(x, y);
- var tile = atmospheres.GetTileMixture(grid.Owner, null, indices, true);
+ var tile = atmospheres.GetTileMixture(gridId, null, indices, true);
if (tile == null)
{
public readonly HashSet<IPipeNet> PipeNets = new();
[ViewVariables]
- public readonly HashSet<AtmosDeviceComponent> AtmosDevices = new();
+ public readonly HashSet<Entity<AtmosDeviceComponent>> AtmosDevices = new();
[ViewVariables]
public Queue<TileAtmosphere> CurrentRunTiles = new();
public Queue<IPipeNet> CurrentRunPipeNet = new();
[ViewVariables]
- public Queue<AtmosDeviceComponent> CurrentRunAtmosDevices = new();
+ public Queue<Entity<AtmosDeviceComponent>> CurrentRunAtmosDevices = new();
[ViewVariables]
public readonly HashSet<Vector2i> InvalidatedCoords = new(1000);
using JetBrains.Annotations;
using Robust.Shared.Map;
using Robust.Shared.Map.Components;
-using Content.Shared.Destructible;
namespace Content.Server.Atmos.EntitySystems
{
SubscribeLocalEvent<AirtightComponent, MoveEvent>(OnAirtightMoved);
}
- private void OnAirtightInit(EntityUid uid, AirtightComponent airtight, ComponentInit args)
+ private void OnAirtightInit(Entity<AirtightComponent> airtight, ref ComponentInit args)
{
- var xform = EntityManager.GetComponent<TransformComponent>(uid);
+ var xform = EntityManager.GetComponent<TransformComponent>(airtight);
- if (airtight.FixAirBlockedDirectionInitialize)
+ if (airtight.Comp.FixAirBlockedDirectionInitialize)
{
- var moveEvent = new MoveEvent(uid, default, default, Angle.Zero, xform.LocalRotation, xform, false);
- if (AirtightMove(uid, airtight, ref moveEvent))
+ var moveEvent = new MoveEvent(airtight, default, default, Angle.Zero, xform.LocalRotation, xform, false);
+ if (AirtightMove(airtight, ref moveEvent))
return;
}
UpdatePosition(airtight);
}
- private void OnAirtightShutdown(EntityUid uid, AirtightComponent airtight, ComponentShutdown args)
+ private void OnAirtightShutdown(Entity<AirtightComponent> airtight, ref ComponentShutdown args)
{
- var xform = Transform(uid);
+ var xform = Transform(airtight);
// If the grid is deleting no point updating atmos.
- if (_mapManager.TryGetGrid(xform.GridUid, out var grid))
+ if (HasComp<MapGridComponent>(xform.GridUid) &&
+ MetaData(xform.GridUid.Value).EntityLifeStage > EntityLifeStage.MapInitialized)
{
- if (MetaData(grid.Owner).EntityLifeStage > EntityLifeStage.MapInitialized) return;
+ return;
}
- SetAirblocked(uid, airtight, false, xform);
+ SetAirblocked(airtight, false, xform);
}
private void OnAirtightPositionChanged(EntityUid uid, AirtightComponent airtight, ref AnchorStateChangedEvent args)
}
}
- private void OnAirtightMoved(EntityUid uid, AirtightComponent airtight, ref MoveEvent ev)
+ private void OnAirtightMoved(Entity<AirtightComponent> airtight, ref MoveEvent ev)
{
- AirtightMove(uid, airtight, ref ev);
+ AirtightMove(airtight, ref ev);
}
- private bool AirtightMove(EntityUid uid, AirtightComponent airtight, ref MoveEvent ev)
+ private bool AirtightMove(Entity<AirtightComponent> ent, ref MoveEvent ev)
{
+ var (owner, airtight) = ent;
if (!airtight.RotateAirBlocked || airtight.InitialAirBlockedDirection == (int)AtmosDirection.Invalid)
return false;
airtight.CurrentAirBlockedDirection = (int) Rotate((AtmosDirection)airtight.InitialAirBlockedDirection, ev.NewRotation);
var pos = airtight.LastPosition;
- UpdatePosition(airtight, ev.Component);
- var airtightEv = new AirtightChanged(uid, airtight, pos);
- RaiseLocalEvent(uid, ref airtightEv, true);
+ UpdatePosition(ent, ev.Component);
+ var airtightEv = new AirtightChanged(owner, airtight, pos);
+ RaiseLocalEvent(owner, ref airtightEv, true);
return true;
}
- public void SetAirblocked(EntityUid uid, AirtightComponent airtight, bool airblocked, TransformComponent? xform = null)
+ public void SetAirblocked(Entity<AirtightComponent> airtight, bool airblocked, TransformComponent? xform = null)
{
- if (airtight.AirBlocked == airblocked)
+ if (airtight.Comp.AirBlocked == airblocked)
return;
- if (!Resolve(uid, ref xform))
+ if (!Resolve(airtight, ref xform))
return;
- var pos = airtight.LastPosition;
- airtight.AirBlocked = airblocked;
+ var pos = airtight.Comp.LastPosition;
+ airtight.Comp.AirBlocked = airblocked;
UpdatePosition(airtight, xform);
- var airtightEv = new AirtightChanged(uid, airtight, pos);
- RaiseLocalEvent(uid, ref airtightEv, true);
+ var airtightEv = new AirtightChanged(airtight, airtight, pos);
+ RaiseLocalEvent(airtight, ref airtightEv, true);
}
- public void UpdatePosition(AirtightComponent airtight, TransformComponent? xform = null)
+ public void UpdatePosition(Entity<AirtightComponent> ent, TransformComponent? xform = null)
{
- if (!Resolve(airtight.Owner, ref xform)) return;
+ var (owner, airtight) = ent;
+ if (!Resolve(owner, ref xform))
+ return;
- if (!xform.Anchored || !_mapManager.TryGetGrid(xform.GridUid, out var grid))
+ if (!xform.Anchored || !TryComp(xform.GridUid, out MapGridComponent? grid))
return;
airtight.LastPosition = (xform.GridUid.Value, grid.TileIndicesFor(xform.Coordinates));
public void InvalidatePosition(EntityUid gridId, Vector2i pos, bool fixVacuum = false)
{
- if (!_mapManager.TryGetGrid(gridId, out var grid))
+ if (!TryComp(gridId, out MapGridComponent? grid))
return;
- var gridUid = grid.Owner;
-
var query = EntityManager.GetEntityQuery<AirtightComponent>();
_explosionSystem.UpdateAirtightMap(gridId, pos, grid, query);
// TODO make atmos system use query
- _atmosphereSystem.InvalidateTile(gridUid, pos);
+ _atmosphereSystem.InvalidateTile(gridId, pos);
}
private AtmosDirection Rotate(AtmosDirection myDirection, Angle myAngle)
for (var i = 0; i < Atmospherics.Directions; i++)
{
var direction = (AtmosDirection) (1 << i);
- if (!myDirection.IsFlagSet(direction)) continue;
+ if (!myDirection.IsFlagSet(direction))
+ continue;
var angle = direction.ToAngle();
angle += myAngle;
newAirBlockedDirs |= angle.ToAtmosDirectionCardinal();
using Content.Shared.Atmos.EntitySystems;
using Content.Shared.CCVar;
using JetBrains.Annotations;
+using Robust.Server.GameObjects;
using Robust.Server.Player;
using Robust.Shared.Configuration;
using Robust.Shared.Enums;
using Robust.Shared.Map;
+using Robust.Shared.Map.Components;
namespace Content.Server.Atmos.EntitySystems
{
[Dependency] private readonly IMapManager _mapManager = default!;
[Dependency] private readonly IConfigurationManager _configManager = default!;
[Dependency] private readonly AtmosphereSystem _atmosphereSystem = default!;
+ [Dependency] private readonly MapSystem _mapSystem = default!;
/// <summary>
/// Players allowed to see the atmos debug overlay.
/// </summary>
private float _updateCooldown;
+ private List<Entity<MapGridComponent>> _grids = new();
+
public override void Initialize()
{
base.Initialize();
var worldBounds = Box2.CenteredAround(transform.WorldPosition,
new Vector2(LocalViewRange, LocalViewRange));
- foreach (var grid in _mapManager.FindGridsIntersecting(transform.MapID, worldBounds))
+ _grids.Clear();
+ _mapManager.FindGridsIntersecting(transform.MapID, worldBounds, ref _grids);
+
+ foreach (var grid in _grids)
{
var uid = grid.Owner;
if (!TryComp(uid, out GridAtmosphereComponent? gridAtmos))
continue;
- var entityTile = grid.GetTileRef(transform.Coordinates).GridIndices;
+ var entityTile = _mapSystem.GetTileRef(grid, grid, transform.Coordinates).GridIndices;
var baseTile = new Vector2i(entityTile.X - (LocalViewRange / 2), entityTile.Y - (LocalViewRange / 2));
var debugOverlayContent = new AtmosDebugOverlayData[LocalViewRange * LocalViewRange];
}
}
- RaiseNetworkEvent(new AtmosDebugOverlayMessage(GetNetEntity(grid.Owner), baseTile, debugOverlayContent), session.ConnectedClient);
+ RaiseNetworkEvent(new AtmosDebugOverlayMessage(GetNetEntity(grid), baseTile, debugOverlayContent), session.ConnectedClient);
}
}
}
if (TryComp<InternalsComponent>(old, out var internalsComponent))
{
- _internals.DisconnectBreathTool(internalsComponent);
+ _internals.DisconnectBreathTool((old.Value, internalsComponent));
}
component.IsFunctional = false;
using Content.Server.Atmos.Components;
using Content.Shared.Administration;
using Content.Shared.Atmos;
-using Content.Shared.Maps;
using Robust.Shared.Console;
using Robust.Shared.Map;
using Robust.Shared.Map.Components;
if (playerMap == null)
return CompletionResult.FromOptions(options);
- foreach (var grid in _mapManager.GetAllMapGrids(playerMap.Value).OrderBy(o => o.Owner))
+ foreach (var grid in _mapManager.GetAllGrids(playerMap.Value).OrderBy(o => o.Owner))
{
- if (!TryComp<TransformComponent>(grid.Owner, out var gridXform))
+ var uid = grid.Owner;
+ if (!TryComp<TransformComponent>(uid, out var gridXform))
continue;
- options.Add(new CompletionOption(grid.Owner.ToString(), $"{MetaData(grid.Owner).EntityName} - Map {gridXform.MapID}"));
+ options.Add(new CompletionOption(uid.ToString(), $"{MetaData(uid).EntityName} - Map {gridXform.MapID}"));
}
return CompletionResult.FromOptions(options);
using Content.Server.Atmos.Reactions;
using Content.Shared.Atmos;
using Content.Shared.Atmos.Components;
-using Robust.Shared.Map;
using Robust.Shared.Map.Components;
using Robust.Shared.Utility;
tile.GridIndex = uid;
}
- GridRepopulateTiles(mapGrid, gridAtmosphere);
+ GridRepopulateTiles((uid, mapGrid, gridAtmosphere));
}
private void OnGridSplit(EntityUid uid, GridAtmosphereComponent originalGridAtmos, ref GridSplitEvent args)
foreach (var newGrid in args.NewGrids)
{
// Make extra sure this is a valid grid.
- if (!_mapManager.TryGetGrid(newGrid, out var mapGrid))
+ if (!TryComp(newGrid, out MapGridComponent? mapGrid))
continue;
- var entity = mapGrid.Owner;
-
// If the new split grid has an atmosphere already somehow, use that. Otherwise, add a new one.
- if (!TryComp(entity, out GridAtmosphereComponent? newGridAtmos))
- newGridAtmos = AddComp<GridAtmosphereComponent>(entity);
+ if (!TryComp(newGrid, out GridAtmosphereComponent? newGridAtmos))
+ newGridAtmos = AddComp<GridAtmosphereComponent>(newGrid);
// We assume the tiles on the new grid have the same coordinates as they did on the old grid...
var enumerator = mapGrid.GetAllTilesEnumerator();
args.Handled = component.PipeNets.Remove(args.PipeNet);
}
- private void GridAddAtmosDevice(EntityUid uid, GridAtmosphereComponent component,
- ref AddAtmosDeviceMethodEvent args)
+ private void GridAddAtmosDevice(Entity<GridAtmosphereComponent> grid, ref AddAtmosDeviceMethodEvent args)
{
if (args.Handled)
return;
- if (!component.AtmosDevices.Add(args.Device))
+ if (!grid.Comp.AtmosDevices.Add((args.Device.Owner, args.Device)))
return;
- args.Device.JoinedGrid = uid;
+ args.Device.JoinedGrid = grid;
args.Handled = true;
args.Result = true;
}
if (args.Handled)
return;
- if (!component.AtmosDevices.Remove(args.Device))
+ if (!component.AtmosDevices.Remove((args.Device.Owner, args.Device)))
return;
args.Device.JoinedGrid = null;
/// </summary>
/// <param name="mapGrid">The grid where to get all valid tiles from.</param>
/// <param name="gridAtmosphere">The grid atmosphere where the tiles will be repopulated.</param>
- private void GridRepopulateTiles(MapGridComponent mapGrid, GridAtmosphereComponent gridAtmosphere)
+ private void GridRepopulateTiles(Entity<MapGridComponent, GridAtmosphereComponent> grid)
{
+ var (uid, mapGrid, gridAtmosphere) = grid;
var volume = GetVolumeForTiles(mapGrid, 1);
foreach (var tile in mapGrid.GetAllTiles())
gridAtmosphere.InvalidatedCoords.Add(tile.GridIndices);
}
- var uid = gridAtmosphere.Owner;
-
- TryComp(gridAtmosphere.Owner, out GasTileOverlayComponent? overlay);
+ TryComp(uid, out GasTileOverlayComponent? overlay);
// Gotta do this afterwards so we can properly update adjacent tiles.
foreach (var (position, _) in gridAtmosphere.Tiles.ToArray())
{
var ev = new UpdateAdjacentMethodEvent(uid, position);
GridUpdateAdjacent(uid, gridAtmosphere, ref ev);
- InvalidateVisuals(mapGrid.Owner, position, overlay);
+ InvalidateVisuals(uid, position, overlay);
}
}
}
[ViewVariables(VVAccess.ReadWrite)]
public string? SpaceWindSound { get; private set; } = "/Audio/Effects/space_wind.ogg";
- private HashSet<MovedByPressureComponent> _activePressures = new(8);
+ private readonly HashSet<Entity<MovedByPressureComponent>> _activePressures = new(8);
private void UpdateHighPressure(float frameTime)
{
- var toRemove = new RemQueue<MovedByPressureComponent>();
+ var toRemove = new RemQueue<Entity<MovedByPressureComponent>>();
- foreach (var comp in _activePressures)
+ foreach (var ent in _activePressures)
{
- var uid = comp.Owner;
+ var (uid, comp) = ent;
MetaDataComponent? metadata = null;
if (Deleted(uid, metadata))
{
- toRemove.Add(comp);
+ toRemove.Add((uid, comp));
continue;
}
- if (Paused(uid, metadata)) continue;
+ if (Paused(uid, metadata))
+ continue;
comp.Accumulator += frameTime;
- if (comp.Accumulator < 2f) continue;
+ if (comp.Accumulator < 2f)
+ continue;
// Reset it just for VV reasons even though it doesn't matter
comp.Accumulator = 0f;
- toRemove.Add(comp);
+ toRemove.Add(ent);
if (HasComp<MobStateComponent>(uid) &&
TryComp<PhysicsComponent>(uid, out var body))
// idk it's hard.
component.Accumulator = 0f;
- _activePressures.Add(component);
+ _activePressures.Add((uid, component));
}
- private void HighPressureMovements(GridAtmosphereComponent gridAtmosphere, TileAtmosphere tile, EntityQuery<PhysicsComponent> bodies, EntityQuery<TransformComponent> xforms, EntityQuery<MovedByPressureComponent> pressureQuery, EntityQuery<MetaDataComponent> metas)
+ private void HighPressureMovements(Entity<GridAtmosphereComponent> gridAtmosphere, TileAtmosphere tile, EntityQuery<PhysicsComponent> bodies, EntityQuery<TransformComponent> xforms, EntityQuery<MovedByPressureComponent> pressureQuery, EntityQuery<MetaDataComponent> metas)
{
// TODO ATMOS finish this
return;
// Used by ExperiencePressureDifference to correct push/throw directions from tile-relative to physics world.
- var gridWorldRotation = xforms.GetComponent(gridAtmosphere.Owner).WorldRotation;
+ var gridWorldRotation = xforms.GetComponent(gridAtmosphere).WorldRotation;
// If we're using monstermos, smooth out the yeet direction to follow the flow
if (MonstermosEqualization)
if (_containers.IsEntityInContainer(entity, metas.GetComponent(entity))) continue;
var pressureMovements = EnsureComp<MovedByPressureComponent>(entity);
- if (pressure.LastHighPressureMovementAirCycle < gridAtmosphere.UpdateCounter)
+ if (pressure.LastHighPressureMovementAirCycle < gridAtmosphere.Comp.UpdateCounter)
{
// tl;dr YEET
ExperiencePressureDifference(
- pressureMovements,
- gridAtmosphere.UpdateCounter,
+ (entity, pressureMovements),
+ gridAtmosphere.Comp.UpdateCounter,
tile.PressureDifference,
tile.PressureDirection, 0,
tile.PressureSpecificTarget?.GridIndices.ToEntityCoordinates(tile.GridIndex, _mapManager) ?? EntityCoordinates.Invalid,
}
public void ExperiencePressureDifference(
- MovedByPressureComponent component,
+ Entity<MovedByPressureComponent> ent,
int cycle,
float pressureDifference,
AtmosDirection direction,
TransformComponent? xform = null,
PhysicsComponent? physics = null)
{
- var uid = component.Owner;
-
+ var (uid, component) = ent;
if (!Resolve(uid, ref physics, false))
return;
- if (!Resolve(uid, ref xform)) return;
+ if (!Resolve(uid, ref xform))
+ return;
// TODO ATMOS stuns?
+using System.Linq;
+using System.Numerics;
using Content.Server.Atmos.Components;
using Content.Server.Doors.Systems;
-using Content.Shared.Doors.Components;
using Content.Shared.Atmos;
using Content.Shared.Atmos.Components;
using Content.Shared.Database;
-using Robust.Shared.Map;
+using Content.Shared.Doors.Components;
using Robust.Shared.Map.Components;
using Robust.Shared.Physics.Components;
using Robust.Shared.Random;
using Robust.Shared.Utility;
-using System.Linq;
-using System.Numerics;
namespace Content.Server.Atmos.EntitySystems
{
private readonly TileAtmosphere[] _depressurizeSpaceTiles = new TileAtmosphere[Atmospherics.MonstermosHardTileLimit];
private readonly TileAtmosphere[] _depressurizeProgressionOrder = new TileAtmosphere[Atmospherics.MonstermosHardTileLimit * 2];
- private void EqualizePressureInZone(MapGridComponent mapGrid, GridAtmosphereComponent gridAtmosphere, TileAtmosphere tile, int cycleNum, GasTileOverlayComponent? visuals)
+ private void EqualizePressureInZone(Entity<MapGridComponent, GridAtmosphereComponent> ent, TileAtmosphere tile, int cycleNum, GasTileOverlayComponent? visuals)
{
if (tile.Air == null || (tile.MonstermosInfo.LastCycle >= cycleNum))
return; // Already done.
return;
}
+ var (_, mapGrid, gridAtmosphere) = ent;
var queueCycle = ++gridAtmosphere.EqualizationQueueCycleControl;
var totalMoles = 0f;
_equalizeTiles[0] = tile;
{
// Looks like someone opened an airlock to space!
- ExplosivelyDepressurize(mapGrid, gridAtmosphere, tile, cycleNum, visuals);
+ ExplosivelyDepressurize(ent, tile, cycleNum, visuals);
return;
}
}
Array.Clear(_equalizeQueue, 0, Atmospherics.MonstermosTileLimit);
}
- private void ExplosivelyDepressurize(MapGridComponent mapGrid, GridAtmosphereComponent gridAtmosphere, TileAtmosphere tile, int cycleNum, GasTileOverlayComponent? visuals)
+ private void ExplosivelyDepressurize(Entity<MapGridComponent, GridAtmosphereComponent> ent, TileAtmosphere tile, int cycleNum, GasTileOverlayComponent? visuals)
{
// Check if explosive depressurization is enabled and if the tile is valid.
if (!MonstermosDepressurization || tile.Air == null)
const int limit = Atmospherics.MonstermosHardTileLimit;
var totalMolesRemoved = 0f;
+ var (owner, mapGrid, gridAtmosphere) = ent;
var queueCycle = ++gridAtmosphere.EqualizationQueueCycleControl;
var tileCount = 0;
DebugTools.Assert(otherTile2.AdjacentBits.IsFlagSet(direction.GetOpposite()));
if (otherTile2.MonstermosInfo.LastQueueCycle == queueCycle) continue;
- ConsiderFirelocks(gridAtmosphere, otherTile, otherTile2, visuals, mapGrid);
+ ConsiderFirelocks((owner, gridAtmosphere), otherTile, otherTile2, visuals, mapGrid);
// The firelocks might have closed on us.
if (!otherTile.AdjacentBits.IsFlagSet(direction)) continue;
{
var direction = ((Vector2)_depressurizeTiles[tileCount - 1].GridIndices - tile.GridIndices).Normalized();
- var gridPhysics = Comp<PhysicsComponent>(mapGrid.Owner);
+ var gridPhysics = Comp<PhysicsComponent>(owner);
// TODO ATMOS: Come up with better values for these.
- _physics.ApplyLinearImpulse(mapGrid.Owner, direction * totalMolesRemoved * gridPhysics.Mass, body: gridPhysics);
- _physics.ApplyAngularImpulse(mapGrid.Owner, Vector2Helpers.Cross(tile.GridIndices - gridPhysics.LocalCenter, direction) * totalMolesRemoved, body: gridPhysics);
+ _physics.ApplyLinearImpulse(owner, direction * totalMolesRemoved * gridPhysics.Mass, body: gridPhysics);
+ _physics.ApplyAngularImpulse(owner, Vector2Helpers.Cross(tile.GridIndices - gridPhysics.LocalCenter, direction) * totalMolesRemoved, body: gridPhysics);
}
if(tileCount > 10 && (totalMolesRemoved / tileCount) > 10)
Array.Clear(_depressurizeProgressionOrder, 0, Atmospherics.MonstermosHardTileLimit * 2);
}
- private void ConsiderFirelocks(GridAtmosphereComponent gridAtmosphere, TileAtmosphere tile, TileAtmosphere other, GasTileOverlayComponent? visuals, MapGridComponent mapGrid)
+ private void ConsiderFirelocks(Entity<GridAtmosphereComponent> ent, TileAtmosphere tile, TileAtmosphere other, GasTileOverlayComponent? visuals, MapGridComponent mapGrid)
{
var reconsiderAdjacent = false;
if (!reconsiderAdjacent)
return;
- var tileEv = new UpdateAdjacentMethodEvent(mapGrid.Owner, tile.GridIndices);
- var otherEv = new UpdateAdjacentMethodEvent(mapGrid.Owner, other.GridIndices);
- GridUpdateAdjacent(mapGrid.Owner, gridAtmosphere, ref tileEv);
- GridUpdateAdjacent(mapGrid.Owner, gridAtmosphere, ref otherEv);
+ var (owner, gridAtmosphere) = ent;
+ var tileEv = new UpdateAdjacentMethodEvent(owner, tile.GridIndices);
+ var otherEv = new UpdateAdjacentMethodEvent(owner, other.GridIndices);
+ GridUpdateAdjacent(owner, gridAtmosphere, ref tileEv);
+ GridUpdateAdjacent(owner, gridAtmosphere, ref otherEv);
InvalidateVisuals(tile.GridIndex, tile.GridIndices, visuals);
InvalidateVisuals(other.GridIndex, other.GridIndices, visuals);
}
/// </summary>
private const int InvalidCoordinatesLagCheckIterations = 50;
- private int _currentRunAtmosphereIndex = 0;
- private bool _simulationPaused = false;
+ private int _currentRunAtmosphereIndex;
+ private bool _simulationPaused;
- private readonly List<GridAtmosphereComponent> _currentRunAtmosphere = new();
+ private readonly List<Entity<GridAtmosphereComponent>> _currentRunAtmosphere = new();
/// <summary>
/// Revalidates all invalid coordinates in a grid atmosphere.
/// </summary>
- /// <param name="atmosphere">The grid atmosphere in question.</param>
+ /// <param name="ent">The grid atmosphere in question.</param>
/// <returns>Whether the process succeeded or got paused due to time constrains.</returns>
- private bool ProcessRevalidate(GridAtmosphereComponent atmosphere, GasTileOverlayComponent? visuals)
+ private bool ProcessRevalidate(Entity<GridAtmosphereComponent> ent, GasTileOverlayComponent? visuals)
{
+ var (owner, atmosphere) = ent;
if (!atmosphere.ProcessingPaused)
{
atmosphere.CurrentRunInvalidatedCoordinates = new Queue<Vector2i>(atmosphere.InvalidatedCoords);
atmosphere.InvalidatedCoords.Clear();
}
- var uid = atmosphere.Owner;
-
- if (!TryComp(uid, out MapGridComponent? mapGridComp))
+ if (!TryComp(owner, out MapGridComponent? mapGridComp))
return true;
- var mapUid = _mapManager.GetMapEntityIdOrThrow(Transform(mapGridComp.Owner).MapID);
+ var mapUid = _mapManager.GetMapEntityIdOrThrow(Transform(owner).MapID);
- var volume = GetVolumeForTiles(mapGridComp, 1);
+ var volume = GetVolumeForTiles(mapGridComp);
var number = 0;
while (atmosphere.CurrentRunInvalidatedCoordinates.TryDequeue(out var indices))
{
if (!atmosphere.Tiles.TryGetValue(indices, out var tile))
{
- tile = new TileAtmosphere(mapGridComp.Owner, indices,
+ tile = new TileAtmosphere(owner, indices,
new GasMixture(volume) { Temperature = Atmospherics.T20C });
atmosphere.Tiles[indices] = tile;
}
- var airBlockedEv = new IsTileAirBlockedMethodEvent(uid, indices, MapGridComponent:mapGridComp);
- GridIsTileAirBlocked(uid, atmosphere, ref airBlockedEv);
+ var airBlockedEv = new IsTileAirBlockedMethodEvent(owner, indices, MapGridComponent:mapGridComp);
+ GridIsTileAirBlocked(owner, atmosphere, ref airBlockedEv);
var isAirBlocked = airBlockedEv.Result;
var oldBlocked = tile.BlockedAirflow;
- var updateAdjacentEv = new UpdateAdjacentMethodEvent(uid, indices, mapGridComp);
- GridUpdateAdjacent(uid, atmosphere, ref updateAdjacentEv);
+ var updateAdjacentEv = new UpdateAdjacentMethodEvent(owner, indices, mapGridComp);
+ GridUpdateAdjacent(owner, atmosphere, ref updateAdjacentEv);
// Blocked airflow changed, rebuild excited groups!
if (tile.Excited && tile.BlockedAirflow != oldBlocked)
{
if (tile.Air == null && NeedsVacuumFixing(mapGridComp, indices))
{
- var vacuumEv = new FixTileVacuumMethodEvent(uid, indices);
- GridFixTileVacuum(uid, atmosphere, ref vacuumEv);
+ var vacuumEv = new FixTileVacuumMethodEvent(owner, indices);
+ GridFixTileVacuum(owner, atmosphere, ref vacuumEv);
}
// Tile used to be space, but isn't anymore.
// TODO ATMOS: Query all the contents of this tile (like walls) and calculate the correct thermal conductivity and heat capacity
var tileDef = mapGridComp.TryGetTileRef(indices, out var tileRef)
- ? tileRef.GetContentTileDefinition(_tileDefinitionManager) : null;
+ ? tileRef.GetContentTileDefinition(_tileDefinitionManager)
+ : null;
tile.ThermalConductivity = tileDef?.ThermalConductivity ?? 0.5f;
tile.HeatCapacity = tileDef?.HeatCapacity ?? float.PositiveInfinity;
- InvalidateVisuals(mapGridComp.Owner, indices, visuals);
+ InvalidateVisuals(owner, indices, visuals);
for (var i = 0; i < Atmospherics.Directions; i++)
{
AddActiveTile(atmosphere, otherTile);
}
- if (number++ < InvalidCoordinatesLagCheckIterations) continue;
+ if (number++ < InvalidCoordinatesLagCheckIterations)
+ continue;
+
number = 0;
// Process the rest next time.
if (_simulationStopwatch.Elapsed.TotalMilliseconds >= AtmosMaxProcessTime)
return true;
}
- private bool ProcessTileEqualize(GridAtmosphereComponent atmosphere, GasTileOverlayComponent? visuals)
+ private bool ProcessTileEqualize(Entity<GridAtmosphereComponent> ent, GasTileOverlayComponent? visuals)
{
- if(!atmosphere.ProcessingPaused)
+ var (uid, atmosphere) = ent;
+ if (!atmosphere.ProcessingPaused)
atmosphere.CurrentRunTiles = new Queue<TileAtmosphere>(atmosphere.ActiveTiles);
- var uid = atmosphere.Owner;
-
if (!TryComp(uid, out MapGridComponent? mapGridComp))
throw new Exception("Tried to process a grid atmosphere on an entity that isn't a grid!");
var number = 0;
while (atmosphere.CurrentRunTiles.TryDequeue(out var tile))
{
- EqualizePressureInZone(mapGridComp, atmosphere, tile, atmosphere.UpdateCounter, visuals);
+ EqualizePressureInZone((uid, mapGridComp, atmosphere), tile, atmosphere.UpdateCounter, visuals);
+
+ if (number++ < LagCheckIterations)
+ continue;
- if (number++ < LagCheckIterations) continue;
number = 0;
// Process the rest next time.
if (_simulationStopwatch.Elapsed.TotalMilliseconds >= AtmosMaxProcessTime)
{
ProcessCell(atmosphere, tile, atmosphere.UpdateCounter, visuals);
- if (number++ < LagCheckIterations) continue;
+ if (number++ < LagCheckIterations)
+ continue;
+
number = 0;
// Process the rest next time.
if (_simulationStopwatch.Elapsed.TotalMilliseconds >= AtmosMaxProcessTime)
else if(excitedGroup.DismantleCooldown > Atmospherics.ExcitedGroupsDismantleCycles)
ExcitedGroupDismantle(gridAtmosphere, excitedGroup);
- if (number++ < LagCheckIterations) continue;
+ if (number++ < LagCheckIterations)
+ continue;
+
number = 0;
// Process the rest next time.
if (_simulationStopwatch.Elapsed.TotalMilliseconds >= AtmosMaxProcessTime)
return true;
}
- private bool ProcessHighPressureDelta(GridAtmosphereComponent atmosphere)
+ private bool ProcessHighPressureDelta(Entity<GridAtmosphereComponent> ent)
{
- if(!atmosphere.ProcessingPaused)
+ var atmosphere = ent.Comp;
+ if (!atmosphere.ProcessingPaused)
atmosphere.CurrentRunTiles = new Queue<TileAtmosphere>(atmosphere.HighPressureDelta);
// Note: This is still processed even if space wind is turned off since this handles playing the sounds.
while (atmosphere.CurrentRunTiles.TryDequeue(out var tile))
{
- HighPressureMovements(atmosphere, tile, bodies, xforms, pressureQuery, metas);
+ HighPressureMovements(ent, tile, bodies, xforms, pressureQuery, metas);
tile.PressureDifference = 0f;
tile.LastPressureDirection = tile.PressureDirection;
tile.PressureDirection = AtmosDirection.Invalid;
tile.PressureSpecificTarget = null;
atmosphere.HighPressureDelta.Remove(tile);
- if (number++ < LagCheckIterations) continue;
+ if (number++ < LagCheckIterations)
+ continue;
number = 0;
// Process the rest next time.
if (_simulationStopwatch.Elapsed.TotalMilliseconds >= AtmosMaxProcessTime)
{
ProcessHotspot(atmosphere, hotspot);
- if (number++ < LagCheckIterations) continue;
+ if (number++ < LagCheckIterations)
+ continue;
+
number = 0;
// Process the rest next time.
if (_simulationStopwatch.Elapsed.TotalMilliseconds >= AtmosMaxProcessTime)
{
Superconduct(atmosphere, superconductivity);
- if (number++ < LagCheckIterations) continue;
+ if (number++ < LagCheckIterations)
+ continue;
+
number = 0;
// Process the rest next time.
if (_simulationStopwatch.Elapsed.TotalMilliseconds >= AtmosMaxProcessTime)
{
pipenet.Update();
- if (number++ < LagCheckIterations) continue;
+ if (number++ < LagCheckIterations)
+ continue;
+
number = 0;
// Process the rest next time.
if (_simulationStopwatch.Elapsed.TotalMilliseconds >= AtmosMaxProcessTime)
private bool ProcessAtmosDevices(GridAtmosphereComponent atmosphere)
{
- if(!atmosphere.ProcessingPaused)
- atmosphere.CurrentRunAtmosDevices = new Queue<AtmosDeviceComponent>(atmosphere.AtmosDevices);
+ if (!atmosphere.ProcessingPaused)
+ atmosphere.CurrentRunAtmosDevices = new Queue<Entity<AtmosDeviceComponent>>(atmosphere.AtmosDevices);
var time = _gameTiming.CurTime;
var number = 0;
while (atmosphere.CurrentRunAtmosDevices.TryDequeue(out var device))
{
- RaiseLocalEvent(device.Owner, new AtmosDeviceUpdateEvent(RealAtmosTime()), false);
- device.LastProcess = time;
+ RaiseLocalEvent(device, new AtmosDeviceUpdateEvent(RealAtmosTime()));
+ device.Comp.LastProcess = time;
+
+ if (number++ < LagCheckIterations)
+ continue;
- if (number++ < LagCheckIterations) continue;
number = 0;
// Process the rest next time.
if (_simulationStopwatch.Elapsed.TotalMilliseconds >= AtmosMaxProcessTime)
{
_currentRunAtmosphereIndex = 0;
_currentRunAtmosphere.Clear();
- _currentRunAtmosphere.AddRange(EntityManager.EntityQuery<GridAtmosphereComponent>());
+
+ var query = EntityQueryEnumerator<GridAtmosphereComponent>();
+ while (query.MoveNext(out var uid, out var grid))
+ {
+ _currentRunAtmosphere.Add((uid, grid));
+ }
}
// We set this to true just in case we have to stop processing due to time constraints.
for (; _currentRunAtmosphereIndex < _currentRunAtmosphere.Count; _currentRunAtmosphereIndex++)
{
- var atmosphere = _currentRunAtmosphere[_currentRunAtmosphereIndex];
- TryComp(atmosphere.Owner, out GasTileOverlayComponent? visuals);
+ var ent = _currentRunAtmosphere[_currentRunAtmosphereIndex];
+ var (owner, atmosphere) = ent;
+ TryComp(owner, out GasTileOverlayComponent? visuals);
- if (atmosphere.LifeStage >= ComponentLifeStage.Stopping || Paused(atmosphere.Owner) || !atmosphere.Simulated)
+ if (atmosphere.LifeStage >= ComponentLifeStage.Stopping || Paused(owner) || !atmosphere.Simulated)
continue;
atmosphere.Timer += frameTime;
switch (atmosphere.State)
{
case AtmosphereProcessingState.Revalidate:
- if (!ProcessRevalidate(atmosphere, visuals))
+ if (!ProcessRevalidate(ent, visuals))
{
atmosphere.ProcessingPaused = true;
return;
: AtmosphereProcessingState.ActiveTiles;
continue;
case AtmosphereProcessingState.TileEqualize:
- if (!ProcessTileEqualize(atmosphere, visuals))
+ if (!ProcessTileEqualize(ent, visuals))
{
atmosphere.ProcessingPaused = true;
return;
atmosphere.State = AtmosphereProcessingState.HighPressureDelta;
continue;
case AtmosphereProcessingState.HighPressureDelta:
- if (!ProcessHighPressureDelta(atmosphere))
+ if (!ProcessHighPressureDelta(ent))
{
atmosphere.ProcessingPaused = true;
return;
using Content.Server.Maps;
using Content.Server.NodeContainer.EntitySystems;
using Content.Shared.Atmos.EntitySystems;
-using Content.Shared.Maps;
using JetBrains.Annotations;
using Robust.Server.GameObjects;
using Robust.Shared.Containers;
if (_exposedTimer < ExposedUpdateDelay)
return;
- foreach (var (exposed, transform) in EntityManager.EntityQuery<AtmosExposedComponent, TransformComponent>())
+ var query = EntityQueryEnumerator<AtmosExposedComponent, TransformComponent>();
+ while (query.MoveNext(out var uid, out var exposed, out var transform))
{
- var air = GetContainingMixture(exposed.Owner, transform:transform);
+ var air = GetContainingMixture(uid, transform:transform);
if (air == null)
continue;
var updateEvent = new AtmosExposedUpdateEvent(transform.Coordinates, air, transform);
- RaiseLocalEvent(exposed.Owner, ref updateEvent);
+ RaiseLocalEvent(uid, ref updateEvent);
}
_exposedTimer -= ExposedUpdateDelay;
using Content.Shared.Throwing;
using Content.Shared.Weapons.Melee.Events;
using Robust.Server.GameObjects;
-using Robust.Shared.Physics;
using Robust.Shared.Physics.Components;
-using Robust.Shared.Physics.Dynamics;
using Robust.Shared.Physics.Events;
using Robust.Shared.Physics.Systems;
private float _timer;
- private Dictionary<FlammableComponent, float> _fireEvents = new();
+ private readonly Dictionary<Entity<FlammableComponent>, float> _fireEvents = new();
public override void Initialize()
{
args.IsHot = flammable.OnFire;
}
- private void OnTileFire(EntityUid uid, FlammableComponent flammable, ref TileFireEvent args)
+ private void OnTileFire(Entity<FlammableComponent> ent, ref TileFireEvent args)
{
var tempDelta = args.Temperature - MinIgnitionTemperature;
- _fireEvents.TryGetValue(flammable, out var maxTemp);
+ _fireEvents.TryGetValue(ent, out var maxTemp);
if (tempDelta > maxTemp)
- _fireEvents[flammable] = tempDelta;
+ _fireEvents[ent] = tempDelta;
}
private void OnRejuvenate(EntityUid uid, FlammableComponent component, RejuvenateEvent args)
{
// 100 -> 1, 200 -> 2, 400 -> 3...
var fireStackMod = Math.Max(MathF.Log2(deltaTemp / 100) + 1, 0);
- var fireStackDelta = fireStackMod - flammable.FireStacks;
+ var fireStackDelta = fireStackMod - flammable.Comp.FireStacks;
var flammableEntity = flammable.Owner;
if (fireStackDelta > 0)
{
_timer -= UpdateTime;
// TODO: This needs cleanup to take off the crust from TemperatureComponent and shit.
- foreach (var (flammable, transform) in EntityManager.EntityQuery<FlammableComponent, TransformComponent>())
+ var query = EntityQueryEnumerator<FlammableComponent, TransformComponent>();
+ while (query.MoveNext(out var uid, out var flammable, out var transform))
{
- var uid = flammable.Owner;
-
// Slowly dry ourselves off if wet.
if (flammable.FireStacks < 0)
{
SubscribeLocalEvent<GasTankComponent, GetVerbsEvent<AlternativeVerb>>(OnGetAlternativeVerb);
}
- private void OnGasShutdown(EntityUid uid, GasTankComponent component, ComponentShutdown args)
+ private void OnGasShutdown(Entity<GasTankComponent> gasTank, ref ComponentShutdown args)
{
- DisconnectFromInternals(component);
+ DisconnectFromInternals(gasTank);
}
- private void OnGasTankToggleInternals(EntityUid uid, GasTankComponent component, GasTankToggleInternalsMessage args)
+ private void OnGasTankToggleInternals(Entity<GasTankComponent> ent, ref GasTankToggleInternalsMessage args)
{
if (args.Session is not IPlayerSession playerSession ||
- playerSession.AttachedEntity is not {} player) return;
+ playerSession.AttachedEntity == null)
+ {
+ return;
+ }
- ToggleInternals(component);
+ ToggleInternals(ent);
}
- private void OnGasTankSetPressure(EntityUid uid, GasTankComponent component, GasTankSetPressureMessage args)
+ private void OnGasTankSetPressure(Entity<GasTankComponent> ent, ref GasTankSetPressureMessage args)
{
- var pressure = Math.Min(args.Pressure, component.MaxOutputPressure);
+ var pressure = Math.Min(args.Pressure, ent.Comp.MaxOutputPressure);
- component.OutputPressure = pressure;
+ ent.Comp.OutputPressure = pressure;
- UpdateUserInterface(component, true);
+ UpdateUserInterface(ent, true);
}
- public void UpdateUserInterface(GasTankComponent component, bool initialUpdate = false)
+ public void UpdateUserInterface(Entity<GasTankComponent> ent, bool initialUpdate = false)
{
- _ui.TrySetUiState(component.Owner, SharedGasTankUiKey.Key,
+ var (owner, component) = ent;
+ _ui.TrySetUiState(owner, SharedGasTankUiKey.Key,
new GasTankBoundUserInterfaceState
{
TankPressure = component.Air?.Pressure ?? 0,
});
}
- private void BeforeUiOpen(EntityUid uid, GasTankComponent component, BeforeActivatableUIOpenEvent args)
+ private void BeforeUiOpen(Entity<GasTankComponent> ent, ref BeforeActivatableUIOpenEvent args)
{
// Only initial update includes output pressure information, to avoid overwriting client-input as the updates come in.
- UpdateUserInterface(component, true);
+ UpdateUserInterface(ent, true);
}
private void OnParentChange(EntityUid uid, GasTankComponent component, ref EntParentChangedMessage args)
args.PushMarkup(Loc.GetString(component.IsValveOpen ? "comp-gas-tank-examine-open-valve" : "comp-gas-tank-examine-closed-valve"));
}
- private void OnActionToggle(EntityUid uid, GasTankComponent component, ToggleActionEvent args)
+ private void OnActionToggle(Entity<GasTankComponent> gasTank, ref ToggleActionEvent args)
{
if (args.Handled)
return;
- ToggleInternals(component);
+ ToggleInternals(gasTank);
args.Handled = true;
}
_timer += frameTime;
- if (_timer < TimerDelay) return;
+ if (_timer < TimerDelay)
+ return;
+
_timer -= TimerDelay;
var query = EntityQueryEnumerator<GasTankComponent>();
- while (query.MoveNext(out var uid, out var gasTank))
+ while (query.MoveNext(out var uid, out var comp))
{
- if (gasTank.IsValveOpen && !gasTank.IsLowPressure)
+ var gasTank = (uid, comp);
+ if (comp.IsValveOpen && !comp.IsLowPressure)
{
- ReleaseGas(uid, gasTank);
+ ReleaseGas(gasTank);
}
- if (gasTank.CheckUser)
+ if (comp.CheckUser)
{
- gasTank.CheckUser = false;
- if (Transform(uid).ParentUid != gasTank.User)
+ comp.CheckUser = false;
+ if (Transform(uid).ParentUid != comp.User)
{
DisconnectFromInternals(gasTank);
continue;
}
}
- if (gasTank.Air != null)
+ if (comp.Air != null)
{
- _atmosphereSystem.React(gasTank.Air, gasTank);
+ _atmosphereSystem.React(comp.Air, comp);
}
CheckStatus(gasTank);
if (_ui.IsUiOpen(uid, SharedGasTankUiKey.Key))
}
}
- private void ReleaseGas(EntityUid uid, GasTankComponent component)
+ private void ReleaseGas(Entity<GasTankComponent> gasTank)
{
- var removed = RemoveAirVolume(component, component.ValveOutputRate * TimerDelay);
- var environment = _atmosphereSystem.GetContainingMixture(uid, false, true);
+ var removed = RemoveAirVolume(gasTank, gasTank.Comp.ValveOutputRate * TimerDelay);
+ var environment = _atmosphereSystem.GetContainingMixture(gasTank, false, true);
if (environment != null)
{
_atmosphereSystem.Merge(environment, removed);
}
var impulse = removed.TotalMoles * removed.Temperature;
- _physics.ApplyLinearImpulse(uid, _random.NextAngle().ToWorldVec() * impulse);
- _physics.ApplyAngularImpulse(uid, _random.NextFloat(-3f, 3f));
- _audioSys.PlayPvs(component.RuptureSound, uid);
+ _physics.ApplyLinearImpulse(gasTank, _random.NextAngle().ToWorldVec() * impulse);
+ _physics.ApplyAngularImpulse(gasTank, _random.NextFloat(-3f, 3f));
+ _audioSys.PlayPvs(gasTank.Comp.RuptureSound, gasTank);
}
- private void ToggleInternals(GasTankComponent component)
+ private void ToggleInternals(Entity<GasTankComponent> ent)
{
- if (component.IsConnected)
+ if (ent.Comp.IsConnected)
{
- DisconnectFromInternals(component);
+ DisconnectFromInternals(ent);
}
else
{
- ConnectToInternals(component);
+ ConnectToInternals(ent);
}
}
- public GasMixture? RemoveAir(GasTankComponent component, float amount)
+ public GasMixture? RemoveAir(Entity<GasTankComponent> gasTank, float amount)
{
- var gas = component.Air?.Remove(amount);
- CheckStatus(component);
+ var gas = gasTank.Comp.Air?.Remove(amount);
+ CheckStatus(gasTank);
return gas;
}
- public GasMixture RemoveAirVolume(GasTankComponent component, float volume)
+ public GasMixture RemoveAirVolume(Entity<GasTankComponent> gasTank, float volume)
{
+ var component = gasTank.Comp;
if (component.Air == null)
return new GasMixture(volume);
var molesNeeded = component.OutputPressure * volume / (Atmospherics.R * component.Air.Temperature);
- var air = RemoveAir(component, molesNeeded);
+ var air = RemoveAir(gasTank, molesNeeded);
if (air != null)
air.Volume = volume;
public bool CanConnectToInternals(GasTankComponent component)
{
- var internals = GetInternalsComponent(component);
+ var internals = GetInternalsComponent(component, component.User);
return internals != null && internals.BreathToolEntity != null && !component.IsValveOpen;
}
- public void ConnectToInternals(GasTankComponent component)
+ public void ConnectToInternals(Entity<GasTankComponent> ent)
{
+ var (owner, component) = ent;
if (component.IsConnected || !CanConnectToInternals(component))
return;
if (internals == null)
return;
- if (_internals.TryConnectTank(internals, component.Owner))
+ if (_internals.TryConnectTank((internals.Owner, internals), owner))
component.User = internals.Owner;
_actions.SetToggled(component.ToggleActionEntity, component.IsConnected);
component.ConnectStream?.Stop();
if (component.ConnectSound != null)
- component.ConnectStream = _audioSys.PlayPvs(component.ConnectSound, component.Owner);
+ component.ConnectStream = _audioSys.PlayPvs(component.ConnectSound, owner);
- UpdateUserInterface(component);
+ UpdateUserInterface(ent);
}
- public void DisconnectFromInternals(GasTankComponent component)
+ public void DisconnectFromInternals(Entity<GasTankComponent> ent)
{
+ var (owner, component) = ent;
if (component.User == null)
return;
component.DisconnectStream?.Stop();
if (component.DisconnectSound != null)
- component.DisconnectStream = _audioSys.PlayPvs(component.DisconnectSound, component.Owner);
+ component.DisconnectStream = _audioSys.PlayPvs(component.DisconnectSound, owner);
- UpdateUserInterface(component);
+ UpdateUserInterface(ent);
}
private InternalsComponent? GetInternalsComponent(GasTankComponent component, EntityUid? owner = null)
{
owner ??= component.User;
- if (Deleted(component.Owner)) return null;
+ if (Deleted(component.Owner))return null;
if (owner != null) return CompOrNull<InternalsComponent>(owner.Value);
return _containers.TryGetContainingContainer(component.Owner, out var container)
? CompOrNull<InternalsComponent>(container.Owner)
: null;
}
- public void AssumeAir(GasTankComponent component, GasMixture giver)
+ public void AssumeAir(Entity<GasTankComponent> ent, GasMixture giver)
{
- _atmosphereSystem.Merge(component.Air, giver);
- CheckStatus(component);
+ _atmosphereSystem.Merge(ent.Comp.Air, giver);
+ CheckStatus(ent);
}
- public void CheckStatus(GasTankComponent component)
+ public void CheckStatus(Entity<GasTankComponent> ent)
{
+ var (owner, component) = ent;
if (component.Air == null)
return;
range = GasTankComponent.MaxExplosionRange;
}
- _explosions.TriggerExplosive(component.Owner, radius: range);
+ _explosions.TriggerExplosive(owner, radius: range);
return;
}
{
if (component.Integrity <= 0)
{
- var environment = _atmosphereSystem.GetContainingMixture(component.Owner, false, true);
+ var environment = _atmosphereSystem.GetContainingMixture(owner, false, true);
if(environment != null)
_atmosphereSystem.Merge(environment, component.Air);
- _audioSys.Play(component.RuptureSound, Filter.Pvs(component.Owner), Transform(component.Owner).Coordinates, true, AudioParams.Default.WithVariation(0.125f));
+ _audioSys.Play(component.RuptureSound, Filter.Pvs(owner), Transform(owner).Coordinates, true, AudioParams.Default.WithVariation(0.125f));
- QueueDel(component.Owner);
+ QueueDel(owner);
return;
}
{
if (component.Integrity <= 0)
{
- var environment = _atmosphereSystem.GetContainingMixture(component.Owner, false, true);
+ var environment = _atmosphereSystem.GetContainingMixture(owner, false, true);
if (environment == null)
return;
-using System.Linq;
-using Content.Server.Atmos.Monitor.Components;
using Content.Server.Atmos.EntitySystems;
-using Content.Server.Atmos.Piping.EntitySystems;
+using Content.Server.Atmos.Monitor.Components;
using Content.Server.Atmos.Piping.Components;
+using Content.Server.Atmos.Piping.EntitySystems;
using Content.Server.DeviceNetwork;
using Content.Server.DeviceNetwork.Systems;
using Content.Server.Power.Components;
if (!HasComp<ApcPowerReceiverComponent>(uid)
&& TryComp<AtmosDeviceComponent>(uid, out var atmosDeviceComponent))
{
- _atmosDeviceSystem.LeaveAtmosphere(atmosDeviceComponent);
+ _atmosDeviceSystem.LeaveAtmosphere((uid, atmosDeviceComponent));
}
}
}
}
- private void OnPowerChangedEvent(EntityUid uid, AtmosMonitorComponent component, ref PowerChangedEvent args)
+ private void OnPowerChangedEvent(Entity<AtmosMonitorComponent> ent, ref PowerChangedEvent args)
{
- if (TryComp<AtmosDeviceComponent>(uid, out var atmosDeviceComponent))
+ if (TryComp<AtmosDeviceComponent>(ent, out var atmosDeviceComponent))
{
if (!args.Powered)
{
- _atmosDeviceSystem.LeaveAtmosphere(atmosDeviceComponent);
+ _atmosDeviceSystem.LeaveAtmosphere((ent, atmosDeviceComponent));
}
else
{
- _atmosDeviceSystem.JoinAtmosphere(atmosDeviceComponent);
- Alert(uid, component.LastAlarmState);
+ _atmosDeviceSystem.JoinAtmosphere((ent, atmosDeviceComponent));
+ Alert(ent, ent.Comp.LastAlarmState);
}
}
}
/// <param name="alarms">The alarms that caused this alarm state.</param>
public void Alert(EntityUid uid, AtmosAlarmType state, HashSet<AtmosMonitorThresholdType>? alarms = null, AtmosMonitorComponent? monitor = null)
{
- if (!Resolve(uid, ref monitor)) return;
+ if (!Resolve(uid, ref monitor))
+ return;
monitor.LastAlarmState = state;
monitor.TrippedThresholds = alarms ?? monitor.TrippedThresholds;
- BroadcastAlertPacket(monitor);
+ BroadcastAlertPacket((uid, monitor));
// TODO: Central system that grabs *all* alarms from wired network
}
/// is synced between monitors the moment a monitor sends out an alarm,
/// or if it is explicitly synced (see ResetAll/Sync).
/// </remarks>
- private void BroadcastAlertPacket(AtmosMonitorComponent monitor, TagComponent? tags = null)
+ private void BroadcastAlertPacket(Entity<AtmosMonitorComponent> ent, TagComponent? tags = null)
{
- if (!monitor.NetEnabled) return;
+ var (owner, monitor) = ent;
+ if (!monitor.NetEnabled)
+ return;
- if (!Resolve(monitor.Owner, ref tags, false))
+ if (!Resolve(owner, ref tags, false))
{
return;
}
foreach (var addr in monitor.RegisteredDevices)
{
- _deviceNetSystem.QueuePacket(monitor.Owner, addr, payload);
+ _deviceNetSystem.QueuePacket(owner, addr, payload);
}
}
/// <param name="gas">Gas, if applicable.</param>
public void SetThreshold(EntityUid uid, AtmosMonitorThresholdType type, AtmosAlarmThreshold threshold, Gas? gas = null, AtmosMonitorComponent? monitor = null)
{
- if (!Resolve(uid, ref monitor)) return;
+ if (!Resolve(uid, ref monitor))
+ return;
switch (type)
{
monitor.TemperatureThreshold = threshold;
break;
case AtmosMonitorThresholdType.Gas:
- if (gas == null || monitor.GasThresholds == null) return;
+ if (gas == null || monitor.GasThresholds == null)
+ return;
monitor.GasThresholds[(Gas) gas] = threshold;
break;
}
gate.FlowRate = a*dV/tau + (1-a)*gate.FlowRate; // in L/sec
}
- private void OnExamined(EntityUid uid, GasPassiveGateComponent gate, ExaminedEvent args)
+ private void OnExamined(Entity<GasPassiveGateComponent> gate, ref ExaminedEvent args)
{
- if (!EntityManager.GetComponent<TransformComponent>(gate.Owner).Anchored || !args.IsInDetailsRange) // Not anchored? Out of range? No status.
+ if (!Comp<TransformComponent>(gate).Anchored || !args.IsInDetailsRange) // Not anchored? Out of range? No status.
return;
- var str = Loc.GetString("gas-passive-gate-examined", ("flowRate", $"{gate.FlowRate:0.#}"));
+ var str = Loc.GetString("gas-passive-gate-examined", ("flowRate", $"{gate.Comp.FlowRate:0.#}"));
args.PushMarkup(str);
}
}
using Content.Server.Atmos.EntitySystems;
-using Content.Shared.Atmos.Piping;
using Content.Server.Atmos.Piping.Binary.Components;
using Content.Server.Atmos.Piping.Components;
using Content.Server.Construction;
using Content.Server.NodeContainer.EntitySystems;
using Content.Server.NodeContainer.Nodes;
using Content.Shared.Atmos;
+using Content.Shared.Atmos.Piping;
using Content.Shared.Audio;
using Content.Shared.Examine;
using JetBrains.Annotations;
UpdateAppearance(uid, comp);
}
- private void OnExamined(EntityUid uid, GasRecyclerComponent comp, ExaminedEvent args)
+ private void OnExamined(Entity<GasRecyclerComponent> ent, ref ExaminedEvent args)
{
- if (!EntityManager.GetComponent<TransformComponent>(comp.Owner).Anchored || !args.IsInDetailsRange) // Not anchored? Out of range? No status.
+ var comp = ent.Comp;
+ if (!EntityManager.GetComponent<TransformComponent>(ent).Anchored || !args.IsInDetailsRange) // Not anchored? Out of range? No status.
return;
- if (!EntityManager.TryGetComponent(uid, out NodeContainerComponent? nodeContainer)
+ if (!EntityManager.TryGetComponent(ent, out NodeContainerComponent? nodeContainer)
|| !_nodeContainer.TryGetNode(nodeContainer, comp.InletName, out PipeNode? inlet)
|| !_nodeContainer.TryGetNode(nodeContainer, comp.OutletName, out PipeNode? _))
{
}
}
- private void OnUpdate(EntityUid uid, GasRecyclerComponent comp, AtmosDeviceUpdateEvent args)
+ private void OnUpdate(Entity<GasRecyclerComponent> ent, ref AtmosDeviceUpdateEvent args)
{
- if (!EntityManager.TryGetComponent(uid, out NodeContainerComponent? nodeContainer)
+ var comp = ent.Comp;
+ if (!EntityManager.TryGetComponent(ent, out NodeContainerComponent? nodeContainer)
|| !_nodeContainer.TryGetNode(nodeContainer, comp.InletName, out PipeNode? inlet)
|| !_nodeContainer.TryGetNode(nodeContainer, comp.OutletName, out PipeNode? outlet))
{
- _ambientSoundSystem.SetAmbience(comp.Owner, false);
+ _ambientSoundSystem.SetAmbience(ent, false);
return;
}
}
_atmosphereSystem.Merge(outlet.Air, removed);
- UpdateAppearance(uid, comp);
- _ambientSoundSystem.SetAmbience(comp.Owner, true);
+ UpdateAppearance(ent, comp);
+ _ambientSoundSystem.SetAmbience(ent, true);
}
public float PassiveTransferVol(GasMixture inlet, GasMixture outlet)
using Content.Shared.Examine;
using Content.Shared.Interaction;
using JetBrains.Annotations;
-using Robust.Server.GameObjects;
using Robust.Shared.Audio;
using Robust.Shared.Player;
SubscribeLocalEvent<GasValveComponent, ExaminedEvent>(OnExamined);
}
- private void OnExamined(EntityUid uid, GasValveComponent valve, ExaminedEvent args)
+ private void OnExamined(Entity<GasValveComponent> ent, ref ExaminedEvent args)
{
- if (!Comp<TransformComponent>(valve.Owner).Anchored || !args.IsInDetailsRange) // Not anchored? Out of range? No status.
+ var valve = ent.Comp;
+ if (!Comp<TransformComponent>(ent).Anchored || !args.IsInDetailsRange) // Not anchored? Out of range? No status.
return;
if (Loc.TryGetString("gas-valve-system-examined", out var str,
private void OnActivate(EntityUid uid, GasValveComponent component, ActivateInWorldEvent args)
{
Toggle(uid, component);
- SoundSystem.Play(component.ValveSound.GetSound(), Filter.Pvs(component.Owner), component.Owner, AudioHelpers.WithVariation(0.25f));
+ SoundSystem.Play(component.ValveSound.GetSound(), Filter.Pvs(uid), uid, AudioHelpers.WithVariation(0.25f));
}
public void Set(EntityUid uid, GasValveComponent component, bool value)
&& _nodeContainer.TryGetNode(nodeContainer, component.InletName, out PipeNode? inlet)
&& _nodeContainer.TryGetNode(nodeContainer, component.OutletName, out PipeNode? outlet))
{
- if (TryComp<AppearanceComponent>(component.Owner,out var appearance))
+ if (TryComp<AppearanceComponent>(uid, out var appearance))
{
_appearance.SetData(uid, FilterVisuals.Enabled, component.Open, appearance);
}
{
inlet.AddAlwaysReachable(outlet);
outlet.AddAlwaysReachable(inlet);
- _ambientSoundSystem.SetAmbience(component.Owner, true);
+ _ambientSoundSystem.SetAmbience(uid, true);
}
else
{
inlet.RemoveAlwaysReachable(outlet);
outlet.RemoveAlwaysReachable(inlet);
- _ambientSoundSystem.SetAmbience(component.Owner, false);
+ _ambientSoundSystem.SetAmbience(uid, false);
}
}
}
[Dependency] private readonly IGameTiming _gameTiming = default!;
[Dependency] private readonly AtmosphereSystem _atmosphereSystem = default!;
- private float _timer = 0f;
+ private float _timer;
// Set of atmos devices that are off-grid but have JoinSystem set.
- private readonly HashSet<AtmosDeviceComponent> _joinedDevices = new();
+ private readonly HashSet<Entity<AtmosDeviceComponent>> _joinedDevices = new();
public override void Initialize()
{
SubscribeLocalEvent<AtmosDeviceComponent, AnchorStateChangedEvent>(OnDeviceAnchorChanged);
}
- public void JoinAtmosphere(AtmosDeviceComponent component)
+ public void JoinAtmosphere(Entity<AtmosDeviceComponent> ent)
{
- var transform = Transform(component.Owner);
+ var component = ent.Comp;
+ var transform = Transform(ent);
if (component.RequireAnchored && !transform.Anchored)
return;
if (!onGrid && component.JoinSystem)
{
- _joinedDevices.Add(component);
+ _joinedDevices.Add(ent);
component.JoinedSystem = true;
}
component.LastProcess = _gameTiming.CurTime;
- RaiseLocalEvent(component.Owner, new AtmosDeviceEnabledEvent(), false);
+ RaiseLocalEvent(ent, new AtmosDeviceEnabledEvent());
}
- public void LeaveAtmosphere(AtmosDeviceComponent component)
+ public void LeaveAtmosphere(Entity<AtmosDeviceComponent> ent)
{
+ var component = ent.Comp;
// Try to remove the component from an atmosphere, and if not
if (component.JoinedGrid != null && !_atmosphereSystem.RemoveAtmosDevice(component.JoinedGrid.Value, component))
{
if (component.JoinedSystem)
{
- _joinedDevices.Remove(component);
+ _joinedDevices.Remove(ent);
component.JoinedSystem = false;
}
component.LastProcess = TimeSpan.Zero;
- RaiseLocalEvent(component.Owner, new AtmosDeviceDisabledEvent(), false);
+ RaiseLocalEvent(ent, new AtmosDeviceDisabledEvent());
}
- public void RejoinAtmosphere(AtmosDeviceComponent component)
+ public void RejoinAtmosphere(Entity<AtmosDeviceComponent> component)
{
LeaveAtmosphere(component);
JoinAtmosphere(component);
}
- private void OnDeviceInitialize(EntityUid uid, AtmosDeviceComponent component, ComponentInit args)
+ private void OnDeviceInitialize(Entity<AtmosDeviceComponent> ent, ref ComponentInit args)
{
- JoinAtmosphere(component);
+ JoinAtmosphere(ent);
}
- private void OnDeviceShutdown(EntityUid uid, AtmosDeviceComponent component, ComponentShutdown args)
+ private void OnDeviceShutdown(Entity<AtmosDeviceComponent> ent, ref ComponentShutdown args)
{
- LeaveAtmosphere(component);
+ LeaveAtmosphere(ent);
}
- private void OnDeviceAnchorChanged(EntityUid uid, AtmosDeviceComponent component, ref AnchorStateChangedEvent args)
+ private void OnDeviceAnchorChanged(Entity<AtmosDeviceComponent> ent, ref AnchorStateChangedEvent args)
{
// Do nothing if the component doesn't require being anchored to function.
- if (!component.RequireAnchored)
+ if (!ent.Comp.RequireAnchored)
return;
if (args.Anchored)
- JoinAtmosphere(component);
+ JoinAtmosphere(ent);
else
- LeaveAtmosphere(component);
+ LeaveAtmosphere(ent);
}
- private void OnDeviceParentChanged(EntityUid uid, AtmosDeviceComponent component, ref EntParentChangedMessage args)
+ private void OnDeviceParentChanged(Entity<AtmosDeviceComponent> ent, ref EntParentChangedMessage args)
{
- RejoinAtmosphere(component);
+ RejoinAtmosphere(ent);
}
/// <summary>
var time = _gameTiming.CurTime;
foreach (var device in _joinedDevices)
{
- RaiseLocalEvent(device.Owner, new AtmosDeviceUpdateEvent(_atmosphereSystem.AtmosTime), false);
- device.LastProcess = time;
+ RaiseLocalEvent(device, new AtmosDeviceUpdateEvent(_atmosphereSystem.AtmosTime));
+ device.Comp.LastProcess = time;
}
}
}
using System.Diagnostics.CodeAnalysis;
-using Content.Server.Atmos.Components;
using Content.Server.Atmos.EntitySystems;
using Content.Server.Atmos.Piping.Components;
using Content.Server.Atmos.Piping.Other.Components;
using Content.Shared.Atmos;
using JetBrains.Annotations;
using Robust.Server.GameObjects;
-using Robust.Shared.GameObjects;
-using Robust.Shared.IoC;
namespace Content.Server.Atmos.Piping.Other.EntitySystems
{
SubscribeLocalEvent<GasMinerComponent, AtmosDeviceUpdateEvent>(OnMinerUpdated);
}
- private void OnMinerUpdated(EntityUid uid, GasMinerComponent miner, AtmosDeviceUpdateEvent args)
+ private void OnMinerUpdated(Entity<GasMinerComponent> ent, ref AtmosDeviceUpdateEvent args)
{
- if (!CheckMinerOperation(miner, out var environment) || !miner.Enabled || !miner.SpawnGas.HasValue || miner.SpawnAmount <= 0f)
+ var miner = ent.Comp;
+ if (!CheckMinerOperation(ent, out var environment) || !miner.Enabled || !miner.SpawnGas.HasValue || miner.SpawnAmount <= 0f)
return;
// Time to mine some gas.
_atmosphereSystem.Merge(environment, merger);
}
- private bool CheckMinerOperation(GasMinerComponent miner, [NotNullWhen(true)] out GasMixture? environment)
+ private bool CheckMinerOperation(Entity<GasMinerComponent> ent, [NotNullWhen(true)] out GasMixture? environment)
{
- var uid = miner.Owner;
+ var (uid, miner) = ent;
environment = _atmosphereSystem.GetContainingMixture(uid, true, true);
var transform = Transform(uid);
using Content.Shared.Popups;
using JetBrains.Annotations;
using Robust.Server.GameObjects;
-using Robust.Shared.Player;
namespace Content.Server.Atmos.Piping.Trinary.EntitySystems
{
|| !_nodeContainer.TryGetNode(nodeContainer, filter.OutletName, out PipeNode? outletNode)
|| outletNode.Air.Pressure >= Atmospherics.MaxOutputPressure) // No need to transfer if target is full.
{
- _ambientSoundSystem.SetAmbience(filter.Owner, false);
+ _ambientSoundSystem.SetAmbience(uid, false);
return;
}
// We multiply the transfer rate in L/s by the seconds passed since the last process to get the liters.
- var transferVol = (float)(filter.TransferRate * args.dt);
+ var transferVol = filter.TransferRate * args.dt;
if (transferVol <= 0)
{
- _ambientSoundSystem.SetAmbience(filter.Owner, false);
+ _ambientSoundSystem.SetAmbience(uid, false);
return;
}
var target = filterNode.Air.Pressure < Atmospherics.MaxOutputPressure ? filterNode : inletNode;
_atmosphereSystem.Merge(target.Air, filteredOut);
- _ambientSoundSystem.SetAmbience(filter.Owner, filteredOut.TotalMoles > 0f);
+ _ambientSoundSystem.SetAmbience(uid, filteredOut.TotalMoles > 0f);
}
_atmosphereSystem.Merge(outletNode.Air, removed);
filter.Enabled = false;
UpdateAppearance(uid, filter);
- _ambientSoundSystem.SetAmbience(filter.Owner, false);
+ _ambientSoundSystem.SetAmbience(uid, false);
DirtyUI(uid, filter);
_userInterfaceSystem.TryCloseAll(uid, GasFilterUiKey.Key);
if (!EntityManager.TryGetComponent(args.User, out ActorComponent? actor))
return;
- if (EntityManager.GetComponent<TransformComponent>(filter.Owner).Anchored)
+ if (EntityManager.GetComponent<TransformComponent>(uid).Anchored)
{
_userInterfaceSystem.TryOpen(uid, GasFilterUiKey.Key, actor.PlayerSession);
DirtyUI(uid, filter);
return;
_userInterfaceSystem.TrySetUiState(uid, GasFilterUiKey.Key,
- new GasFilterBoundUserInterfaceState(EntityManager.GetComponent<MetaDataComponent>(filter.Owner).EntityName, filter.TransferRate, filter.Enabled, filter.FilteredGas));
+ new GasFilterBoundUserInterfaceState(MetaData(uid).EntityName, filter.TransferRate, filter.Enabled, filter.FilteredGas));
}
private void UpdateAppearance(EntityUid uid, GasFilterComponent? filter = null)
using Content.Shared.Atmos.Piping;
using Content.Shared.Audio;
using JetBrains.Annotations;
-using Robust.Server.GameObjects;
namespace Content.Server.Atmos.Piping.Trinary.EntitySystems
{
|| !_nodeContainer.TryGetNode(nodeContainer, comp.ControlName, out PipeNode? controlNode)
|| !_nodeContainer.TryGetNode(nodeContainer, comp.OutletName, out PipeNode? outletNode))
{
- _ambientSoundSystem.SetAmbience(comp.Owner, false);
+ _ambientSoundSystem.SetAmbience(uid, false);
comp.Enabled = false;
return;
}
UpdateAppearance(uid, comp);
// We multiply the transfer rate in L/s by the seconds passed since the last process to get the liters.
- var transferVolume = (float)(transferRate * args.dt);
+ var transferVolume = transferRate * args.dt;
if (transferVolume <= 0)
{
- _ambientSoundSystem.SetAmbience(comp.Owner, false);
+ _ambientSoundSystem.SetAmbience(uid, false);
return;
}
- _ambientSoundSystem.SetAmbience(comp.Owner, true);
+ _ambientSoundSystem.SetAmbience(uid, true);
var removed = inletNode.Air.RemoveVolume(transferVolume);
_atmosphereSystem.Merge(outletNode.Air, removed);
}
{
comp.Enabled = false;
UpdateAppearance(uid, comp);
- _ambientSoundSystem.SetAmbience(comp.Owner, false);
+ _ambientSoundSystem.SetAmbience(uid, false);
}
private void UpdateAppearance(EntityUid uid, PressureControlledValveComponent? comp = null, AppearanceComponent? appearance = null)
using Content.Shared.Atmos.Piping;
using Content.Shared.Interaction;
using JetBrains.Annotations;
-using Robust.Server.GameObjects;
namespace Content.Server.Atmos.Piping.Unary.EntitySystems
{
public void UpdateAppearance(EntityUid uid, GasOutletInjectorComponent component, AppearanceComponent? appearance = null)
{
- if (!Resolve(component.Owner, ref appearance, false))
+ if (!Resolve(uid, ref appearance, false))
return;
_appearance.SetData(uid, OutletInjectorVisuals.Enabled, component.Enabled, appearance);
{
base.Update(frameTime);
- foreach (var (_, bedComponent, strapComponent) in EntityQuery<HealOnBuckleHealingComponent, HealOnBuckleComponent, StrapComponent>())
+ var query = EntityQueryEnumerator<HealOnBuckleHealingComponent, HealOnBuckleComponent, StrapComponent>();
+ while (query.MoveNext(out var uid, out _, out var bedComponent, out var strapComponent))
{
if (_timing.CurTime < bedComponent.NextHealTime)
continue;
bedComponent.NextHealTime += TimeSpan.FromSeconds(bedComponent.HealTime);
- if (strapComponent.BuckledEntities.Count == 0) continue;
+ if (strapComponent.BuckledEntities.Count == 0)
+ continue;
foreach (var healedEntity in strapComponent.BuckledEntities)
{
if (HasComp<SleepingComponent>(healedEntity))
damage *= bedComponent.SleepMultiplier;
- _damageableSystem.TryChangeDamage(healedEntity, damage, true, origin: bedComponent.Owner);
+ _damageableSystem.TryChangeDamage(healedEntity, damage, true, origin: uid);
}
}
}
}
_remQueue.Clear();
- foreach (var (respawning, summonableComp) in EntityQuery<SummonableRespawningComponent, SummonableComponent>())
+ var query = EntityQueryEnumerator<SummonableRespawningComponent, SummonableComponent>();
+ while (query.MoveNext(out var uid, out var respawning, out var summonableComp))
{
summonableComp.Accumulator += frameTime;
if (summonableComp.Accumulator < summonableComp.RespawnTime)
summonableComp.Summon = null;
}
summonableComp.AlreadySummoned = false;
- _popupSystem.PopupEntity(Loc.GetString("bible-summon-respawn-ready", ("book", summonableComp.Owner)), summonableComp.Owner, PopupType.Medium);
- SoundSystem.Play("/Audio/Effects/radpulse9.ogg", Filter.Pvs(summonableComp.Owner), summonableComp.Owner, AudioParams.Default.WithVolume(-4f));
+ _popupSystem.PopupEntity(Loc.GetString("bible-summon-respawn-ready", ("book", uid)), uid, PopupType.Medium);
+ SoundSystem.Play("/Audio/Effects/radpulse9.ogg", Filter.Pvs(uid), uid, AudioParams.Default.WithVolume(-4f));
// Clean up the accumulator and respawn tracking component
summonableComp.Accumulator = 0;
- _remQueue.Enqueue(respawning.Owner);
+ _remQueue.Enqueue(uid);
}
}
{
if (!TryComp<TransformComponent>(args.User, out var userXform)) return;
- AttemptSummon(component, args.User, userXform);
+ AttemptSummon((uid, component), args.User, userXform);
},
Text = Loc.GetString("bible-summon-verb"),
Priority = 2
args.AddAction(ref component.SummonActionEntity, component.SummonAction);
}
- private void OnSummon(EntityUid uid, SummonableComponent component, SummonActionEvent args)
+ private void OnSummon(Entity<SummonableComponent> ent, ref SummonActionEvent args)
{
- AttemptSummon(component, args.Performer, Transform(args.Performer));
+ AttemptSummon(ent, args.Performer, Transform(args.Performer));
}
/// <summary>
return;
var source = component.Source;
- if (source != null && TryComp<SummonableComponent>(source, out var summonable))
+ if (source != null && HasComp<SummonableComponent>(source))
{
- _addQueue.Enqueue(summonable.Owner);
+ _addQueue.Enqueue(source.Value);
}
}
/// </summary>
private void OnSpawned(EntityUid uid, FamiliarComponent component, GhostRoleSpawnerUsedEvent args)
{
- if (!TryComp<SummonableComponent>(Transform(args.Spawner).ParentUid, out var summonable))
+ var parent = Transform(args.Spawner).ParentUid;
+ if (!TryComp<SummonableComponent>(parent, out var summonable))
return;
- component.Source = summonable.Owner;
+ component.Source = parent;
summonable.Summon = uid;
}
- private void AttemptSummon(SummonableComponent component, EntityUid user, TransformComponent? position)
+ private void AttemptSummon(Entity<SummonableComponent> ent, EntityUid user, TransformComponent? position)
{
+ var (uid, component) = ent;
if (component.AlreadySummoned || component.SpecialItemPrototype == null)
return;
if (component.RequiresBibleUser && !HasComp<BibleUserComponent>(user))
return;
if (!Resolve(user, ref position))
return;
- if (component.Deleted || Deleted(component.Owner))
+ if (component.Deleted || Deleted(uid))
return;
- if (!_blocker.CanInteract(user, component.Owner))
+ if (!_blocker.CanInteract(user, uid))
return;
// Make this familiar the component's summon
if (HasComp<GhostRoleMobSpawnerComponent>(familiar))
{
_popupSystem.PopupEntity(Loc.GetString("bible-summon-requested"), user, PopupType.Medium);
- Transform(familiar).AttachParent(component.Owner);
+ Transform(familiar).AttachParent(uid);
}
component.AlreadySummoned = true;
_actionsSystem.RemoveAction(user, component.SummonActionEntity);
var mechanismName = string.Join(" ", args).ToLowerInvariant();
var bodySystem = entityManager.System<BodySystem>();
- foreach (var organ in bodySystem.GetBodyOrgans(body.Owner, body))
+ foreach (var organ in bodySystem.GetBodyOrgans(attached, body))
{
if (fac.GetComponentName(organ.Component.GetType()).ToLowerInvariant() == mechanismName)
{
return;
}
- var tank = FindBestGasTank(uid ,internals);
+ var tank = FindBestGasTank(uid, internals);
if (tank == null)
{
return;
}
- _gasTank.ConnectToInternals(tank);
+ _gasTank.ConnectToInternals(tank.Value);
}
private void StartToggleInternalsDoAfter(EntityUid user, EntityUid target, InternalsComponent internals)
if (AreInternalsWorking(component))
{
var gasTank = Comp<GasTankComponent>(component.GasTankEntity!.Value);
- args.Gas = _gasTank.RemoveAirVolume(gasTank, Atmospherics.BreathVolume);
+ args.Gas = _gasTank.RemoveAirVolume((component.GasTankEntity.Value, gasTank), Atmospherics.BreathVolume);
// TODO: Should listen to gas tank updates instead I guess?
_alerts.ShowAlert(uid, AlertType.Internals, GetSeverity(component));
}
}
- public void DisconnectBreathTool(InternalsComponent component)
+ public void DisconnectBreathTool(Entity<InternalsComponent> ent)
{
+ var (owner, component) = ent;
var old = component.BreathToolEntity;
component.BreathToolEntity = null;
if (TryComp(old, out BreathToolComponent? breathTool) )
{
_atmos.DisconnectInternals(breathTool);
- DisconnectTank(component);
+ DisconnectTank(ent);
}
- _alerts.ShowAlert(component.Owner, AlertType.Internals, GetSeverity(component));
+ _alerts.ShowAlert(owner, AlertType.Internals, GetSeverity(component));
}
- public void ConnectBreathTool(InternalsComponent component, EntityUid toolEntity)
+ public void ConnectBreathTool(Entity<InternalsComponent> ent, EntityUid toolEntity)
{
+ var (owner, component) = ent;
if (TryComp(component.BreathToolEntity, out BreathToolComponent? tool))
{
_atmos.DisconnectInternals(tool);
}
component.BreathToolEntity = toolEntity;
- _alerts.ShowAlert(component.Owner, AlertType.Internals, GetSeverity(component));
+ _alerts.ShowAlert(owner, AlertType.Internals, GetSeverity(component));
}
public void DisconnectTank(InternalsComponent? component)
return;
if (TryComp(component.GasTankEntity, out GasTankComponent? tank))
- _gasTank.DisconnectFromInternals(tank);
+ _gasTank.DisconnectFromInternals((component.GasTankEntity.Value, tank));
component.GasTankEntity = null;
_alerts.ShowAlert(component.Owner, AlertType.Internals, GetSeverity(component));
}
- public bool TryConnectTank(InternalsComponent component, EntityUid tankEntity)
+ public bool TryConnectTank(Entity<InternalsComponent> ent, EntityUid tankEntity)
{
+ var component = ent.Comp;
if (component.BreathToolEntity == null)
return false;
if (TryComp(component.GasTankEntity, out GasTankComponent? tank))
- _gasTank.DisconnectFromInternals(tank);
+ _gasTank.DisconnectFromInternals((component.GasTankEntity.Value, tank));
component.GasTankEntity = tankEntity;
- _alerts.ShowAlert(component.Owner, AlertType.Internals, GetSeverity(component));
+ _alerts.ShowAlert(ent, AlertType.Internals, GetSeverity(component));
return true;
}
return 1;
}
- public GasTankComponent? FindBestGasTank(EntityUid internalsOwner, InternalsComponent component)
+ public Entity<GasTankComponent>? FindBestGasTank(EntityUid internalsOwner, InternalsComponent component)
{
// Prioritise
// 1. back equipped tanks
TryComp<GasTankComponent>(backEntity, out var backGasTank) &&
_gasTank.CanConnectToInternals(backGasTank))
{
- return backGasTank;
+ return (backEntity.Value, backGasTank);
}
if (_inventory.TryGetSlotEntity(internalsOwner, "suitstorage", out var entity, inventory, containerManager) &&
TryComp<GasTankComponent>(entity, out var gasTank) &&
_gasTank.CanConnectToInternals(gasTank))
{
- return gasTank;
+ return (entity.Value, gasTank);
}
- var tanks = new List<GasTankComponent>();
+ var tanks = new List<Entity<GasTankComponent>>();
foreach (var hand in _hands.EnumerateHands(internalsOwner))
{
if (TryComp(hand.HeldEntity, out gasTank) && _gasTank.CanConnectToInternals(gasTank))
- tanks.Add(gasTank);
+ tanks.Add((hand.HeldEntity.Value, gasTank));
}
if (tanks.Count > 0)
{
- tanks.Sort((x, y) => y.Air.TotalMoles.CompareTo(x.Air.TotalMoles));
+ tanks.Sort((x, y) => y.Comp.Air.TotalMoles.CompareTo(x.Comp.Air.TotalMoles));
return tanks[0];
}
while (enumerator.MoveNext(out var container))
{
if (TryComp(container.ContainedEntity, out gasTank) && _gasTank.CanConnectToInternals(gasTank))
- tanks.Add(gasTank);
+ tanks.Add((container.ContainedEntity.Value, gasTank));
}
if (tanks.Count > 0)
{
- tanks.Sort((x, y) => y.Air.TotalMoles.CompareTo(x.Air.TotalMoles));
+ tanks.Sort((x, y) => y.Comp.Air.TotalMoles.CompareTo(x.Comp.Air.TotalMoles));
return tanks[0];
}
}
if (TryComp(args.Equipee, out InternalsComponent? internals))
{
component.ConnectedInternalsEntity = args.Equipee;
- _internals.ConnectBreathTool(internals, uid);
+ _internals.ConnectBreathTool((args.Equipee, internals), uid);
}
}
using Content.Shared.Database;
using Content.Shared.Mobs.Systems;
using JetBrains.Annotations;
-using Robust.Shared.Player;
using Robust.Shared.Timing;
namespace Content.Server.Body.Systems
{
base.Update(frameTime);
- foreach (var (respirator, body) in EntityManager.EntityQuery<RespiratorComponent, BodyComponent>())
+ var query = EntityQueryEnumerator<RespiratorComponent, BodyComponent>();
+ while (query.MoveNext(out var uid, out var respirator, out var body))
{
- var uid = respirator.Owner;
-
if (_mobState.IsDead(uid))
{
continue;
if (respirator.AccumulatedFrametime < respirator.CycleDelay)
continue;
respirator.AccumulatedFrametime -= respirator.CycleDelay;
- UpdateSaturation(respirator.Owner, -respirator.CycleDelay, respirator);
+ UpdateSaturation(uid, -respirator.CycleDelay, respirator);
if (!_mobState.IsIncapacitated(uid)) // cannot breathe in crit.
{
// Inhale gas
var ev = new InhaleLocationEvent();
- RaiseLocalEvent(uid, ev, false);
+ RaiseLocalEvent(uid, ev);
ev.Gas ??= _atmosSys.GetContainingMixture(uid, false, true);
public override void Update(float frameTime)
{
- foreach (var (stomach, organ, sol)in EntityManager.EntityQuery<StomachComponent, OrganComponent, SolutionContainerManagerComponent>())
+ var query = EntityQueryEnumerator<StomachComponent, OrganComponent, SolutionContainerManagerComponent>();
+ while (query.MoveNext(out var uid, out var stomach, out var organ, out var sol))
{
stomach.AccumulatedFrameTime += frameTime;
stomach.AccumulatedFrameTime -= stomach.UpdateInterval;
// Get our solutions
- if (!_solutionContainerSystem.TryGetSolution(stomach.Owner, DefaultSolutionName,
+ if (!_solutionContainerSystem.TryGetSolution(uid, DefaultSolutionName,
out var stomachSolution, sol))
continue;
if (reagent.Quantity > delta.ReagentQuantity.Quantity)
reagent = new(reagent.Reagent, delta.ReagentQuantity.Quantity);
- _solutionContainerSystem.RemoveReagent((stomach).Owner, stomachSolution, reagent);
+ _solutionContainerSystem.RemoveReagent(uid, stomachSolution, reagent);
transferSolution.AddReagent(reagent);
}
public override void Update(float frameTime)
{
- foreach (var regulator in EntityManager.EntityQuery<ThermalRegulatorComponent>())
+ var query = EntityQueryEnumerator<ThermalRegulatorComponent>();
+ while (query.MoveNext(out var uid, out var regulator))
{
regulator.AccumulatedFrametime += frameTime;
if (regulator.AccumulatedFrametime < 1)
continue;
regulator.AccumulatedFrametime -= 1;
- ProcessThermalRegulation(regulator.Owner, regulator);
+ ProcessThermalRegulation(uid, regulator);
}
}
using Content.Shared.Hands.EntitySystems;
using Content.Shared.Interaction;
using Content.Shared.Random;
-using Content.Shared.Random.Helpers;
using Robust.Shared.Containers;
namespace Content.Server.Botany.Systems;
else
{
var xform = Transform(plank);
- _containerSystem.AttachParentToContainerOrGrid(xform);
+ _containerSystem.AttachParentToContainerOrGrid((plank, xform));
xform.LocalRotation = 0;
_randomHelper.RandomOffset(plank, 0.25f);
}
{
base.Update(frameTime);
- foreach (var plantHolder in EntityQuery<PlantHolderComponent>())
+ var query = EntityQueryEnumerator<PlantHolderComponent>();
+ while (query.MoveNext(out var uid, out var plantHolder))
{
if (plantHolder.NextUpdate > _gameTiming.CurTime)
continue;
plantHolder.NextUpdate = _gameTiming.CurTime + plantHolder.UpdateDelay;
- Update(plantHolder.Owner, plantHolder);
+ Update(uid, plantHolder);
}
}
using System.Diagnostics.CodeAnalysis;
using Content.Server.Cargo.Components;
using Content.Server.Labels.Components;
+using Content.Server.Paper;
using Content.Shared.Cargo;
using Content.Shared.Cargo.BUI;
using Content.Shared.Cargo.Events;
using Content.Shared.Cargo.Prototypes;
using Content.Shared.Database;
-using Content.Shared.GameTicking;
-using Content.Server.Paper;
-using Robust.Server.GameObjects;
using Robust.Shared.Map;
using Robust.Shared.Players;
using Robust.Shared.Prototypes;
}
_idCardSystem.TryFindIdCard(player, out var idCard);
- order.SetApproverData(idCard?.FullName, idCard?.JobTitle);
+ // ReSharper disable once ConditionalAccessQualifierIsNonNullableAccordingToAPIContract
+ order.SetApproverData(idCard.Comp?.FullName, idCard.Comp?.JobTitle);
_audio.PlayPvs(_audio.GetSound(component.ConfirmSound), uid);
// Log order approval
using Robust.Shared.Console;
using Robust.Shared.Containers;
using Robust.Shared.Map;
+using Robust.Shared.Map.Components;
using Robust.Shared.Prototypes;
using Robust.Shared.Utility;
continue;
}
- if (!_mapManager.TryGetGrid(gridId, out var mapGrid))
+ if (!TryComp(gridId, out MapGridComponent? mapGrid))
{
shell.WriteError($"Grid \"{gridId}\" doesn't exist.");
continue;
List<(double, EntityUid)> mostValuable = new();
- var value = AppraiseGrid(mapGrid.Owner, null, (uid, price) =>
+ var value = AppraiseGrid(gridId.Value, null, (uid, price) =>
{
mostValuable.Add((price, uid));
mostValuable.Sort((i1, i2) => i2.Item1.CompareTo(i1.Item1));
-namespace Content.Server.Chat.Systems;
-
using System.Linq;
using Content.Shared.Chat.Prototypes;
using Robust.Shared.Prototypes;
using Robust.Shared.Timing;
using Robust.Shared.Utility;
+namespace Content.Server.Chat.Systems;
+
public sealed class AutoEmoteSystem : EntitySystem
{
[Dependency] private readonly IGameTiming _gameTiming = default!;
base.Update(frameTime);
var curTime = _gameTiming.CurTime;
- foreach (var autoEmote in EntityQuery<AutoEmoteComponent>())
+ var query = EntityQueryEnumerator<AutoEmoteComponent>();
+ while (query.MoveNext(out var uid, out var autoEmote))
{
- var uid = autoEmote.Owner;
-
if (autoEmote.NextEmoteTime > curTime)
continue;
- foreach ((var key, var time) in autoEmote.EmoteTimers)
+ foreach (var (key, time) in autoEmote.EmoteTimers)
{
if (time > curTime)
continue;
{
base.Initialize();
- SubscribeLocalEvent<ChemMasterComponent, ComponentStartup>((_, comp, _) => UpdateUiState(comp));
- SubscribeLocalEvent<ChemMasterComponent, SolutionChangedEvent>((_, comp, _) => UpdateUiState(comp));
- SubscribeLocalEvent<ChemMasterComponent, EntInsertedIntoContainerMessage>((_, comp, _) => UpdateUiState(comp));
- SubscribeLocalEvent<ChemMasterComponent, EntRemovedFromContainerMessage>((_, comp, _) => UpdateUiState(comp));
- SubscribeLocalEvent<ChemMasterComponent, BoundUIOpenedEvent>((_, comp, _) => UpdateUiState(comp));
+ SubscribeLocalEvent<ChemMasterComponent, ComponentStartup>(SubscribeUpdateUiState);
+ SubscribeLocalEvent<ChemMasterComponent, SolutionChangedEvent>(SubscribeUpdateUiState);
+ SubscribeLocalEvent<ChemMasterComponent, EntInsertedIntoContainerMessage>(SubscribeUpdateUiState);
+ SubscribeLocalEvent<ChemMasterComponent, EntRemovedFromContainerMessage>(SubscribeUpdateUiState);
+ SubscribeLocalEvent<ChemMasterComponent, BoundUIOpenedEvent>(SubscribeUpdateUiState);
SubscribeLocalEvent<ChemMasterComponent, ChemMasterSetModeMessage>(OnSetModeMessage);
SubscribeLocalEvent<ChemMasterComponent, ChemMasterSetPillTypeMessage>(OnSetPillTypeMessage);
SubscribeLocalEvent<ChemMasterComponent, ChemMasterOutputToBottleMessage>(OnOutputToBottleMessage);
}
- private void UpdateUiState(ChemMasterComponent chemMaster, bool updateLabel = false)
+ private void SubscribeUpdateUiState<T>(Entity<ChemMasterComponent> ent, ref T ev)
{
- if (!_solutionContainerSystem.TryGetSolution(chemMaster.Owner, SharedChemMaster.BufferSolutionName, out var bufferSolution))
+ UpdateUiState(ent);
+ }
+
+ private void UpdateUiState(Entity<ChemMasterComponent> ent, bool updateLabel = false)
+ {
+ var (owner, chemMaster) = ent;
+ if (!_solutionContainerSystem.TryGetSolution(owner, SharedChemMaster.BufferSolutionName, out var bufferSolution))
return;
- var inputContainer = _itemSlotsSystem.GetItemOrNull(chemMaster.Owner, SharedChemMaster.InputSlotName);
- var outputContainer = _itemSlotsSystem.GetItemOrNull(chemMaster.Owner, SharedChemMaster.OutputSlotName);
+ var inputContainer = _itemSlotsSystem.GetItemOrNull(owner, SharedChemMaster.InputSlotName);
+ var outputContainer = _itemSlotsSystem.GetItemOrNull(owner, SharedChemMaster.OutputSlotName);
var bufferReagents = bufferSolution.Contents;
var bufferCurrentVolume = bufferSolution.Volume;
chemMaster.Mode, BuildInputContainerInfo(inputContainer), BuildOutputContainerInfo(outputContainer),
bufferReagents, bufferCurrentVolume, chemMaster.PillType, chemMaster.PillDosageLimit, updateLabel);
- _userInterfaceSystem.TrySetUiState(chemMaster.Owner, ChemMasterUiKey.Key, state);
+ _userInterfaceSystem.TrySetUiState(owner, ChemMasterUiKey.Key, state);
}
- private void OnSetModeMessage(EntityUid uid, ChemMasterComponent chemMaster, ChemMasterSetModeMessage message)
+ private void OnSetModeMessage(Entity<ChemMasterComponent> chemMaster, ref ChemMasterSetModeMessage message)
{
// Ensure the mode is valid, either Transfer or Discard.
if (!Enum.IsDefined(typeof(ChemMasterMode), message.ChemMasterMode))
return;
- chemMaster.Mode = message.ChemMasterMode;
+ chemMaster.Comp.Mode = message.ChemMasterMode;
UpdateUiState(chemMaster);
ClickSound(chemMaster);
}
- private void OnSetPillTypeMessage(EntityUid uid, ChemMasterComponent chemMaster, ChemMasterSetPillTypeMessage message)
+ private void OnSetPillTypeMessage(Entity<ChemMasterComponent> chemMaster, ref ChemMasterSetPillTypeMessage message)
{
// Ensure valid pill type. There are 20 pills selectable, 0-19.
if (message.PillType > SharedChemMaster.PillTypes - 1)
return;
- chemMaster.PillType = message.PillType;
+ chemMaster.Comp.PillType = message.PillType;
UpdateUiState(chemMaster);
ClickSound(chemMaster);
}
- private void OnReagentButtonMessage(EntityUid uid, ChemMasterComponent chemMaster, ChemMasterReagentAmountButtonMessage message)
+ private void OnReagentButtonMessage(Entity<ChemMasterComponent> chemMaster, ref ChemMasterReagentAmountButtonMessage message)
{
// Ensure the amount corresponds to one of the reagent amount buttons.
if (!Enum.IsDefined(typeof(ChemMasterReagentAmount), message.Amount))
return;
- switch (chemMaster.Mode)
+ switch (chemMaster.Comp.Mode)
{
case ChemMasterMode.Transfer:
TransferReagents(chemMaster, message.ReagentId, message.Amount.GetFixedPoint(), message.FromBuffer);
ClickSound(chemMaster);
}
- private void TransferReagents(ChemMasterComponent chemMaster, ReagentId id, FixedPoint2 amount, bool fromBuffer)
+ private void TransferReagents(Entity<ChemMasterComponent> chemMaster, ReagentId id, FixedPoint2 amount, bool fromBuffer)
{
- var container = _itemSlotsSystem.GetItemOrNull(chemMaster.Owner, SharedChemMaster.InputSlotName);
+ var container = _itemSlotsSystem.GetItemOrNull(chemMaster, SharedChemMaster.InputSlotName);
if (container is null ||
!_solutionContainerSystem.TryGetFitsInDispenser(container.Value, out var containerSolution) ||
- !_solutionContainerSystem.TryGetSolution(chemMaster.Owner, SharedChemMaster.BufferSolutionName, out var bufferSolution))
+ !_solutionContainerSystem.TryGetSolution(chemMaster, SharedChemMaster.BufferSolutionName, out var bufferSolution))
{
return;
}
UpdateUiState(chemMaster, updateLabel: true);
}
- private void DiscardReagents(ChemMasterComponent chemMaster, ReagentId id, FixedPoint2 amount, bool fromBuffer)
+ private void DiscardReagents(Entity<ChemMasterComponent> chemMaster, ReagentId id, FixedPoint2 amount, bool fromBuffer)
{
-
if (fromBuffer)
{
- if (_solutionContainerSystem.TryGetSolution(chemMaster.Owner, SharedChemMaster.BufferSolutionName, out var bufferSolution))
+ if (_solutionContainerSystem.TryGetSolution(chemMaster, SharedChemMaster.BufferSolutionName, out var bufferSolution))
bufferSolution.RemoveReagent(id, amount);
else
return;
}
else
{
- var container = _itemSlotsSystem.GetItemOrNull(chemMaster.Owner, SharedChemMaster.InputSlotName);
+ var container = _itemSlotsSystem.GetItemOrNull(chemMaster, SharedChemMaster.InputSlotName);
if (container is not null &&
_solutionContainerSystem.TryGetFitsInDispenser(container.Value, out var containerSolution))
{
UpdateUiState(chemMaster, updateLabel: fromBuffer);
}
- private void OnCreatePillsMessage(EntityUid uid, ChemMasterComponent chemMaster, ChemMasterCreatePillsMessage message)
+ private void OnCreatePillsMessage(Entity<ChemMasterComponent> chemMaster, ref ChemMasterCreatePillsMessage message)
{
var user = message.Session.AttachedEntity;
- var maybeContainer = _itemSlotsSystem.GetItemOrNull(chemMaster.Owner, SharedChemMaster.OutputSlotName);
+ var maybeContainer = _itemSlotsSystem.GetItemOrNull(chemMaster, SharedChemMaster.OutputSlotName);
if (maybeContainer is not { Valid: true } container
|| !TryComp(container, out StorageComponent? storage)
|| storage.Container is null)
return;
// Ensure the amount is valid.
- if (message.Dosage == 0 || message.Dosage > chemMaster.PillDosageLimit)
+ if (message.Dosage == 0 || message.Dosage > chemMaster.Comp.PillDosageLimit)
return;
// Ensure label length is within the character limit.
item, itemSolution, withdrawal.SplitSolution(message.Dosage));
var pill = EnsureComp<PillComponent>(item);
- pill.PillType = chemMaster.PillType;
- Dirty(pill);
+ pill.PillType = chemMaster.Comp.PillType;
+ Dirty(item, pill);
if (user.HasValue)
{
ClickSound(chemMaster);
}
- private void OnOutputToBottleMessage(
- EntityUid uid, ChemMasterComponent chemMaster, ChemMasterOutputToBottleMessage message)
+ private void OnOutputToBottleMessage(Entity<ChemMasterComponent> chemMaster, ref ChemMasterOutputToBottleMessage message)
{
var user = message.Session.AttachedEntity;
- var maybeContainer = _itemSlotsSystem.GetItemOrNull(chemMaster.Owner, SharedChemMaster.OutputSlotName);
+ var maybeContainer = _itemSlotsSystem.GetItemOrNull(chemMaster, SharedChemMaster.OutputSlotName);
if (maybeContainer is not { Valid: true } container
|| !_solutionContainerSystem.TryGetSolution(
container, SharedChemMaster.BottleSolutionName, out var solution))
}
private bool WithdrawFromBuffer(
- IComponent chemMaster,
+ Entity<ChemMasterComponent> chemMaster,
FixedPoint2 neededVolume, EntityUid? user,
[NotNullWhen(returnValue: true)] out Solution? outputSolution)
{
outputSolution = null;
if (!_solutionContainerSystem.TryGetSolution(
- chemMaster.Owner, SharedChemMaster.BufferSolutionName, out var solution))
+ chemMaster, SharedChemMaster.BufferSolutionName, out var solution))
{
return false;
}
return true;
}
- private void ClickSound(ChemMasterComponent chemMaster)
+ private void ClickSound(Entity<ChemMasterComponent> chemMaster)
{
- _audioSystem.PlayPvs(chemMaster.ClickSound, chemMaster.Owner, AudioParams.Default.WithVolume(-2f));
+ _audioSystem.PlayPvs(chemMaster.Comp.ClickSound, chemMaster, AudioParams.Default.WithVolume(-2f));
}
private ContainerInfo? BuildInputContainerInfo(EntityUid? container)
{
base.Initialize();
- SubscribeLocalEvent<ReagentDispenserComponent, ComponentStartup>((_, comp, _) => UpdateUiState(comp));
- SubscribeLocalEvent<ReagentDispenserComponent, SolutionChangedEvent>((_, comp, _) => UpdateUiState(comp));
- SubscribeLocalEvent<ReagentDispenserComponent, EntInsertedIntoContainerMessage>((_, comp, _) => UpdateUiState(comp));
- SubscribeLocalEvent<ReagentDispenserComponent, EntRemovedFromContainerMessage>((_, comp, _) => UpdateUiState(comp));
- SubscribeLocalEvent<ReagentDispenserComponent, BoundUIOpenedEvent>((_, comp, _) => UpdateUiState(comp));
+ SubscribeLocalEvent<ReagentDispenserComponent, ComponentStartup>(SubscribeUpdateUiState);
+ SubscribeLocalEvent<ReagentDispenserComponent, SolutionChangedEvent>(SubscribeUpdateUiState);
+ SubscribeLocalEvent<ReagentDispenserComponent, EntInsertedIntoContainerMessage>(SubscribeUpdateUiState);
+ SubscribeLocalEvent<ReagentDispenserComponent, EntRemovedFromContainerMessage>(SubscribeUpdateUiState);
+ SubscribeLocalEvent<ReagentDispenserComponent, BoundUIOpenedEvent>(SubscribeUpdateUiState);
SubscribeLocalEvent<ReagentDispenserComponent, GotEmaggedEvent>(OnEmagged);
SubscribeLocalEvent<ReagentDispenserComponent, ReagentDispenserSetDispenseAmountMessage>(OnSetDispenseAmountMessage);
SubscribeLocalEvent<ReagentDispenserComponent, ReagentDispenserClearContainerSolutionMessage>(OnClearContainerSolutionMessage);
}
- private void UpdateUiState(ReagentDispenserComponent reagentDispenser)
+ private void SubscribeUpdateUiState<T>(Entity<ReagentDispenserComponent> ent, ref T ev)
{
- var outputContainer = _itemSlotsSystem.GetItemOrNull(reagentDispenser.Owner, SharedReagentDispenser.OutputSlotName);
+ UpdateUiState(ent);
+ }
+
+ private void UpdateUiState(Entity<ReagentDispenserComponent> reagentDispenser)
+ {
+ var outputContainer = _itemSlotsSystem.GetItemOrNull(reagentDispenser, SharedReagentDispenser.OutputSlotName);
var outputContainerInfo = BuildOutputContainerInfo(outputContainer);
var inventory = GetInventory(reagentDispenser);
- var state = new ReagentDispenserBoundUserInterfaceState(outputContainerInfo, inventory, reagentDispenser.DispenseAmount);
- _userInterfaceSystem.TrySetUiState(reagentDispenser.Owner, ReagentDispenserUiKey.Key, state);
+ var state = new ReagentDispenserBoundUserInterfaceState(outputContainerInfo, inventory, reagentDispenser.Comp.DispenseAmount);
+ _userInterfaceSystem.TrySetUiState(reagentDispenser, ReagentDispenserUiKey.Key, state);
}
private ContainerInfo? BuildOutputContainerInfo(EntityUid? container)
return null;
}
- private List<ReagentId> GetInventory(ReagentDispenserComponent reagentDispenser)
+ private List<ReagentId> GetInventory(Entity<ReagentDispenserComponent> ent)
{
+ var reagentDispenser = ent.Comp;
var inventory = new List<ReagentId>();
if (reagentDispenser.PackPrototypeId is not null
inventory.AddRange(packPrototype.Inventory.Select(x => new ReagentId(x, null)));
}
- if (HasComp<EmaggedComponent>(reagentDispenser.Owner)
+ if (HasComp<EmaggedComponent>(ent)
&& reagentDispenser.EmagPackPrototypeId is not null
&& _prototypeManager.TryIndex(reagentDispenser.EmagPackPrototypeId, out ReagentDispenserInventoryPrototype? emagPackPrototype))
{
return inventory;
}
- private void OnEmagged(EntityUid uid, ReagentDispenserComponent reagentDispenser, ref GotEmaggedEvent args)
+ private void OnEmagged(Entity<ReagentDispenserComponent> reagentDispenser, ref GotEmaggedEvent args)
{
// adding component manually to have correct state
- EntityManager.AddComponent<EmaggedComponent>(uid);
+ EntityManager.AddComponent<EmaggedComponent>(reagentDispenser);
UpdateUiState(reagentDispenser);
args.Handled = true;
}
- private void OnSetDispenseAmountMessage(EntityUid uid, ReagentDispenserComponent reagentDispenser, ReagentDispenserSetDispenseAmountMessage message)
+ private void OnSetDispenseAmountMessage(Entity<ReagentDispenserComponent> reagentDispenser, ref ReagentDispenserSetDispenseAmountMessage message)
{
- reagentDispenser.DispenseAmount = message.ReagentDispenserDispenseAmount;
+ reagentDispenser.Comp.DispenseAmount = message.ReagentDispenserDispenseAmount;
UpdateUiState(reagentDispenser);
ClickSound(reagentDispenser);
}
- private void OnDispenseReagentMessage(EntityUid uid, ReagentDispenserComponent reagentDispenser, ReagentDispenserDispenseReagentMessage message)
+ private void OnDispenseReagentMessage(Entity<ReagentDispenserComponent> reagentDispenser, ref ReagentDispenserDispenseReagentMessage message)
{
// Ensure that the reagent is something this reagent dispenser can dispense.
if (!GetInventory(reagentDispenser).Contains(message.ReagentId))
return;
- var outputContainer = _itemSlotsSystem.GetItemOrNull(reagentDispenser.Owner, SharedReagentDispenser.OutputSlotName);
+ var outputContainer = _itemSlotsSystem.GetItemOrNull(reagentDispenser, SharedReagentDispenser.OutputSlotName);
if (outputContainer is not {Valid: true} || !_solutionContainerSystem.TryGetFitsInDispenser(outputContainer.Value, out var solution))
return;
- if (_solutionContainerSystem.TryAddReagent(outputContainer.Value, solution, message.ReagentId, (int)reagentDispenser.DispenseAmount, out var dispensedAmount)
+ if (_solutionContainerSystem.TryAddReagent(outputContainer.Value, solution, message.ReagentId, (int)reagentDispenser.Comp.DispenseAmount, out var dispensedAmount)
&& message.Session.AttachedEntity is not null)
{
_adminLogger.Add(LogType.ChemicalReaction, LogImpact.Medium,
ClickSound(reagentDispenser);
}
- private void OnClearContainerSolutionMessage(EntityUid uid, ReagentDispenserComponent reagentDispenser, ReagentDispenserClearContainerSolutionMessage message)
+ private void OnClearContainerSolutionMessage(Entity<ReagentDispenserComponent> reagentDispenser, ref ReagentDispenserClearContainerSolutionMessage message)
{
- var outputContainer = _itemSlotsSystem.GetItemOrNull(reagentDispenser.Owner, SharedReagentDispenser.OutputSlotName);
+ var outputContainer = _itemSlotsSystem.GetItemOrNull(reagentDispenser, SharedReagentDispenser.OutputSlotName);
if (outputContainer is not {Valid: true} || !_solutionContainerSystem.TryGetFitsInDispenser(outputContainer.Value, out var solution))
return;
ClickSound(reagentDispenser);
}
- private void ClickSound(ReagentDispenserComponent reagentDispenser)
+ private void ClickSound(Entity<ReagentDispenserComponent> reagentDispenser)
{
- _audioSystem.PlayPvs(reagentDispenser.ClickSound, reagentDispenser.Owner, AudioParams.Default.WithVolume(-2f));
+ _audioSystem.PlayPvs(reagentDispenser.Comp.ClickSound, reagentDispenser, AudioParams.Default.WithVolume(-2f));
}
}
}
using Content.Server.Body.Components;
using Content.Server.Body.Systems;
using Content.Server.Chemistry.Components;
-using Content.Shared.Chemistry.Components.SolutionManager;
using Content.Shared.Chemistry.EntitySystems;
using Content.Shared.Inventory;
using JetBrains.Annotations;
-using Robust.Shared.Physics.Dynamics;
using Robust.Shared.Physics.Events;
using Robust.Shared.Prototypes;
-
namespace Content.Server.Chemistry.EntitySystems
{
[UsedImplicitly]
SubscribeLocalEvent<SolutionInjectOnCollideComponent, StartCollideEvent>(HandleInjection);
}
- private void HandleInjection(EntityUid uid, SolutionInjectOnCollideComponent component, ref StartCollideEvent args)
+ private void HandleInjection(Entity<SolutionInjectOnCollideComponent> ent, ref StartCollideEvent args)
{
+ var component = ent.Comp;
var target = args.OtherEntity;
if (!args.OtherBody.Hard ||
!EntityManager.TryGetComponent<BloodstreamComponent>(target, out var bloodstream) ||
- !_solutionsSystem.TryGetInjectableSolution(component.Owner, out var solution)) return;
+ !_solutionsSystem.TryGetInjectableSolution(ent, out var solution))
+ {
+ return;
+ }
if (component.BlockSlots != 0x0 && TryComp<InventoryComponent>(target, out var inventory))
{
using Content.Shared.Chemistry.Reagent;
using Content.Shared.FixedPoint;
using Content.Shared.Physics;
-using Robust.Shared.Spawners;
using Content.Shared.Throwing;
using JetBrains.Annotations;
using Robust.Shared.Map;
using Robust.Shared.Physics.Events;
using Robust.Shared.Physics.Systems;
using Robust.Shared.Prototypes;
-using TimedDespawnComponent = Robust.Shared.Spawners.TimedDespawnComponent;
+using Robust.Shared.Spawners;
namespace Content.Server.Chemistry.EntitySystems
{
}
}
- public void Start(VaporComponent vapor, TransformComponent vaporXform, Vector2 dir, float speed, MapCoordinates target, float aliveTime, EntityUid? user = null)
+ public void Start(Entity<VaporComponent> vapor, TransformComponent vaporXform, Vector2 dir, float speed, MapCoordinates target, float aliveTime, EntityUid? user = null)
{
- vapor.Active = true;
- var despawn = EnsureComp<TimedDespawnComponent>(vapor.Owner);
+ vapor.Comp.Active = true;
+ var despawn = EnsureComp<TimedDespawnComponent>(vapor);
despawn.Lifetime = aliveTime;
// Set Move
- if (EntityManager.TryGetComponent(vapor.Owner, out PhysicsComponent? physics))
+ if (EntityManager.TryGetComponent(vapor, out PhysicsComponent? physics))
{
_physics.SetLinearDamping(physics, 0f);
_physics.SetAngularDamping(physics, 0f);
- _throwing.TryThrow(vapor.Owner, dir, speed, user: user);
+ _throwing.TryThrow(vapor, dir, speed, user: user);
var distance = (target.Position - vaporXform.WorldPosition).Length();
var time = (distance / physics.LinearVelocity.Length());
}
}
- internal bool TryAddSolution(VaporComponent vapor, Solution solution)
+ internal bool TryAddSolution(Entity<VaporComponent> vapor, Solution solution)
{
if (solution.Volume == 0)
{
return false;
}
- if (!_solutionContainerSystem.TryGetSolution(vapor.Owner, VaporComponent.SolutionName,
+ if (!_solutionContainerSystem.TryGetSolution(vapor, VaporComponent.SolutionName,
out var vaporSolution))
{
return false;
}
- return _solutionContainerSystem.TryAddSolution(vapor.Owner, vaporSolution, solution);
+ return _solutionContainerSystem.TryAddSolution(vapor, vaporSolution, solution);
}
public override void Update(float frameTime)
{
- foreach (var (vaporComp, solution, xform) in EntityManager
- .EntityQuery<VaporComponent, SolutionContainerManagerComponent, TransformComponent>())
+ var query = EntityQueryEnumerator<VaporComponent, SolutionContainerManagerComponent, TransformComponent>();
+ while (query.MoveNext(out var uid, out var vaporComp, out var solution, out var xform))
{
foreach (var (_, value) in solution.Solutions)
{
- Update(frameTime, vaporComp, value, xform);
+ Update(frameTime, (uid, vaporComp), value, xform);
}
}
}
- private void Update(float frameTime, VaporComponent vapor, Solution contents, TransformComponent xform)
+ private void Update(float frameTime, Entity<VaporComponent> ent, Solution contents, TransformComponent xform)
{
+ var (entity, vapor) = ent;
if (!vapor.Active)
return;
- var entity = vapor.Owner;
-
vapor.ReactTimer += frameTime;
if (vapor.ReactTimer >= ReactTime && TryComp(xform.GridUid, out MapGridComponent? gridComp))
reaction = reagentQuantity.Quantity;
}
- _solutionContainerSystem.RemoveReagent(vapor.Owner, contents, reagentQuantity.Reagent, reaction);
+ _solutionContainerSystem.RemoveReagent(entity, contents, reagentQuantity.Reagent, reaction);
}
}
if (args.EntityManager.TryGetComponent<RespiratorComponent>(args.SolutionEntity, out var resp))
{
var respSys = EntitySystem.Get<RespiratorSystem>();
- respSys.UpdateSaturation(resp.Owner, args.Quantity.Float() * Factor, resp);
+ respSys.UpdateSaturation(args.SolutionEntity, args.Quantity.Float() * Factor, resp);
}
}
}
+using System.Linq;
using Content.Shared.Decals;
using Microsoft.Extensions.ObjectPool;
using Robust.Server.Player;
using Robust.Shared.Configuration;
using Robust.Shared.Enums;
using Robust.Shared.Map;
+using Robust.Shared.Map.Components;
using Robust.Shared.Utility;
-using System.Linq;
namespace Content.Shared.Chunking;
var pos = _transform.GetWorldPosition(xform);
var bounds = _baseViewBounds.Translated(pos).Enlarged(viewEnlargement);
+ var grids = new List<Entity<MapGridComponent>>();
+ _mapManager.FindGridsIntersecting(xform.MapID, bounds, ref grids, true);
- foreach (var grid in _mapManager.FindGridsIntersecting(xform.MapID, bounds, true))
+ foreach (var grid in grids)
{
- var netGrid = GetNetEntity(grid.Owner);
+ var netGrid = GetNetEntity(grid);
if (!chunks.TryGetValue(netGrid, out var set))
{
DebugTools.Assert(set.Count == 0);
}
- var enumerator = new ChunkIndicesEnumerator(_transform.GetInvWorldMatrix(grid.Owner).TransformBox(bounds), chunkSize);
+ var enumerator = new ChunkIndicesEnumerator(_transform.GetInvWorldMatrix(grid).TransformBox(bounds), chunkSize);
while (enumerator.MoveNext(out var indices))
{
if (mind.UserId.HasValue == false || mind.Session == null)
return;
- if (_cloningSystem.TryCloning(cloningPodUid, body.Value, mind, cloningPod, scannerComp.CloningFailChanceMultiplier))
+ if (_cloningSystem.TryCloning(cloningPodUid, body.Value, (mindId, mind), cloningPod, scannerComp.CloningFailChanceMultiplier))
_adminLogger.Add(LogType.Action, LogImpact.Medium, $"{ToPrettyString(uid)} successfully cloned {ToPrettyString(body.Value)}.");
}
using Content.Shared.Examine;
using Content.Shared.GameTicking;
using Content.Shared.Humanoid;
-using Content.Shared.Humanoid.Prototypes;
using Content.Shared.Mind;
using Content.Shared.Mind.Components;
using Content.Shared.Mobs.Systems;
args.PushMarkup(Loc.GetString("cloning-pod-biomass", ("number", _material.GetMaterialAmount(uid, component.RequiredMaterial))));
}
- public bool TryCloning(EntityUid uid, EntityUid bodyToClone, MindComponent mind, CloningPodComponent? clonePod, float failChanceModifier = 1)
+ public bool TryCloning(EntityUid uid, EntityUid bodyToClone, Entity<MindComponent> mindEnt, CloningPodComponent? clonePod, float failChanceModifier = 1)
{
if (!Resolve(uid, ref clonePod))
return false;
if (HasComp<ActiveCloningPodComponent>(uid))
return false;
+ var mind = mindEnt.Comp;
if (ClonesWaitingForMind.TryGetValue(mind, out var clone))
{
if (EntityManager.EntityExists(clone) &&
!_mobStateSystem.IsDead(clone) &&
TryComp<MindContainerComponent>(clone, out var cloneMindComp) &&
- (cloneMindComp.Mind == null || cloneMindComp.Mind == mind.Owner))
+ (cloneMindComp.Mind == null || cloneMindComp.Mind == mindEnt))
return false; // Mind already has clone
ClonesWaitingForMind.Remove(mind);
if (!TryComp<HumanoidAppearanceComponent>(bodyToClone, out var humanoid))
return false; // whatever body was to be cloned, was not a humanoid
- if (!_prototype.TryIndex<SpeciesPrototype>(humanoid.Species, out var speciesPrototype))
+ if (!_prototype.TryIndex(humanoid.Species, out var speciesPrototype))
return false;
if (!TryComp<PhysicsComponent>(bodyToClone, out var physics))
if (TryComp<UncloneableComponent>(bodyToClone, out _))
{
if (clonePod.ConnectedConsole != null)
+ {
_chatSystem.TrySendInGameICMessage(clonePod.ConnectedConsole.Value,
Loc.GetString("cloning-console-uncloneable-trait-error"),
InGameICChatType.Speak, false);
+ }
+
return false;
}
clonePod.BodyContainer.Insert(mob);
ClonesWaitingForMind.Add(mind, mob);
UpdateStatus(uid, CloningPodStatus.NoMind, clonePod);
- var mindId = mind.Owner;
- _euiManager.OpenEui(new AcceptCloningEui(mindId, mind, this), client);
+ _euiManager.OpenEui(new AcceptCloningEui(mindEnt, mind, this), client);
AddComp<ActiveCloningPodComponent>(uid);
// TODO: Ideally, components like this should be components on the mind entity so this isn't necessary.
// Add on special job components to the mob.
- if (_jobs.MindTryGetJob(mindId, out _, out var prototype))
+ if (_jobs.MindTryGetJob(mindEnt, out _, out var prototype))
{
foreach (var special in prototype.Special)
{
args.AddAction(ref component.ToggleActionEntity, component.ToggleAction);
}
- private void OnToggleMask(EntityUid uid, MaskComponent mask, ToggleMaskEvent args)
+ private void OnToggleMask(Entity<MaskComponent> ent, ref ToggleMaskEvent args)
{
+ var (uid, mask) = ent;
if (mask.ToggleActionEntity == null)
return;
- if (!_inventorySystem.TryGetSlotEntity(args.Performer, "mask", out var existing) || !mask.Owner.Equals(existing))
+ if (!_inventorySystem.TryGetSlotEntity(args.Performer, "mask", out var existing) || !uid.Equals(existing))
return;
mask.IsToggled ^= true;
_identity.QueueIdentityUpdate(args.Performer);
if (mask.IsToggled)
- _popupSystem.PopupEntity(Loc.GetString("action-mask-pull-down-popup-message", ("mask", mask.Owner)), args.Performer, args.Performer);
+ _popupSystem.PopupEntity(Loc.GetString("action-mask-pull-down-popup-message", ("mask", uid)), args.Performer, args.Performer);
else
- _popupSystem.PopupEntity(Loc.GetString("action-mask-pull-up-popup-message", ("mask", mask.Owner)), args.Performer, args.Performer);
+ _popupSystem.PopupEntity(Loc.GetString("action-mask-pull-up-popup-message", ("mask", uid)), args.Performer, args.Performer);
ToggleMaskComponents(uid, mask, args.Performer);
}
if (TryComp(wearer, out InternalsComponent? internals))
{
breathTool.ConnectedInternalsEntity = wearer;
- _internals.ConnectBreathTool(internals, uid);
+ _internals.ConnectBreathTool((wearer, internals), uid);
}
}
}
if (_idCardSystem.TryFindIdCard(mob, out var id))
{
- author = $"{id.FullName} ({CultureInfo.CurrentCulture.TextInfo.ToTitleCase(id.JobTitle ?? string.Empty)})".Trim();
+ author = $"{id.Comp.FullName} ({CultureInfo.CurrentCulture.TextInfo.ToTitleCase(id.Comp.JobTitle ?? string.Empty)})".Trim();
}
}
using Content.Shared.Tag;
using Robust.Server.Player;
using Robust.Shared.Console;
-using Robust.Shared.Map;
+using Robust.Shared.Map.Components;
namespace Content.Server.Construction.Commands
{
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";
return;
}
- if (!_mapManager.TryGetGrid(gridId, out var grid))
+ if (!_entManager.TryGetComponent(gridId, out MapGridComponent? grid))
{
shell.WriteError($"No grid exists with id {gridId}");
return;
}
- if (!_entManager.EntityExists(grid.Owner))
+ if (!_entManager.EntityExists(gridId))
{
shell.WriteError($"Grid {gridId} doesn't have an associated grid entity.");
return;
var changed = 0;
var tagSystem = _entManager.EntitySysManager.GetEntitySystem<TagSystem>();
- foreach (var child in xformQuery.GetComponent(grid.Owner).ChildEntities)
+ foreach (var child in xformQuery.GetComponent(gridId.Value).ChildEntities)
{
if (!_entManager.EntityExists(child))
{
using Robust.Server.Player;
using Robust.Shared.Console;
using Robust.Shared.Map;
+using Robust.Shared.Map.Components;
namespace Content.Server.Construction.Commands;
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
var tileA = _tileDef[tileIdA];
var tileB = _tileDef[tileIdB];
- if (!_mapManager.TryGetGrid(gridId, out var grid))
+ if (!_entManager.TryGetComponent(gridId, out MapGridComponent? grid))
{
shell.WriteLine($"No grid exists with id {gridId}");
return;
}
- if (!_entManager.EntityExists(grid.Owner))
+ if (!_entManager.EntityExists(gridId))
{
shell.WriteLine($"Grid {gridId} doesn't have an associated grid entity.");
return;
using Content.Shared.Administration;
using Content.Shared.Maps;
using Content.Shared.Tag;
+using Robust.Server.GameObjects;
using Robust.Server.Player;
using Robust.Shared.Console;
using Robust.Shared.Map;
+using Robust.Shared.Map.Components;
namespace Content.Server.Construction.Commands
{
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
return;
}
- if (!_mapManager.TryGetGrid(gridId, out var grid))
+ if (!_entManager.TryGetComponent(gridId, out MapGridComponent? grid))
{
shell.WriteLine($"No grid exists with id {gridId}");
return;
}
- if (!_entManager.EntityExists(grid.Owner))
+ if (!_entManager.EntityExists(gridId))
{
shell.WriteLine($"Grid {gridId} doesn't have an associated grid entity.");
return;
var underplating = _tileDefManager[TilePrototypeId];
var underplatingTile = new Tile(underplating.TileId);
var changed = 0;
- foreach (var child in _entManager.GetComponent<TransformComponent>(grid.Owner).ChildEntities)
+ foreach (var child in _entManager.GetComponent<TransformComponent>(gridId.Value).ChildEntities)
{
if (!_entManager.EntityExists(child))
{
continue;
}
- var tile = grid.GetTileRef(childTransform.Coordinates);
+ var mapSystem = _entManager.System<MapSystem>();
+ var tile = mapSystem.GetTileRef(gridId.Value, grid, childTransform.Coordinates);
var tileDef = (ContentTileDefinition) _tileDefManager[tile.Tile.TypeId];
if (tileDef.ID == TilePrototypeId)
}
}
- private void OnCompMapInit(EntityUid uid, ComputerComponent component, MapInitEvent args)
+ private void OnCompMapInit(Entity<ComputerComponent> component, ref MapInitEvent args)
{
CreateComputerBoard(component);
}
/// This exists so when you deconstruct computers that were serialized with the map,
/// you can retrieve the computer board.
/// </summary>
- private void CreateComputerBoard(ComputerComponent component)
+ private void CreateComputerBoard(Entity<ComputerComponent> ent)
{
+ var component = ent.Comp;
// Ensure that the construction component is aware of the board container.
- if (TryComp<ConstructionComponent>(component.Owner, out var construction))
- AddContainer(component.Owner, "board", construction);
+ if (TryComp<ConstructionComponent>(ent, out var construction))
+ AddContainer(ent, "board", construction);
// We don't do anything if this is null or empty.
if (string.IsNullOrEmpty(component.BoardPrototype))
return;
- var container = _container.EnsureContainer<Container>(component.Owner, "board");
+ var container = _container.EnsureContainer<Container>(ent, "board");
// We already contain a board. Note: We don't check if it's the right one!
if (container.ContainedEntities.Count != 0)
return;
- var board = EntityManager.SpawnEntity(component.BoardPrototype, Transform(component.Owner).Coordinates);
+ var board = EntityManager.SpawnEntity(component.BoardPrototype, Transform(ent).Coordinates);
- if(!container.Insert(board))
- Logger.Warning($"Couldn't insert board {board} to computer {component.Owner}!");
+ if (!container.Insert(board))
+ Log.Warning($"Couldn't insert board {board} to computer {ent}!");
}
}
SubscribeLocalEvent<ConstructionComponent, ComponentStartup>(OnConstructionStartup);
}
- private void OnConstructionInit(EntityUid uid, ConstructionComponent construction, ComponentInit args)
+ private void OnConstructionInit(Entity<ConstructionComponent> ent, ref ComponentInit args)
{
- if (GetCurrentGraph(uid, construction) is not {} graph)
+ var construction = ent.Comp;
+ if (GetCurrentGraph(ent, construction) is not {} graph)
{
- _sawmill.Warning($"Prototype {EntityManager.GetComponent<MetaDataComponent>(construction.Owner).EntityPrototype?.ID}'s construction component has an invalid graph specified.");
+ _sawmill.Warning($"Prototype {EntityManager.GetComponent<MetaDataComponent>(ent).EntityPrototype?.ID}'s construction component has an invalid graph specified.");
return;
}
if (GetNodeFromGraph(graph, construction.Node) is not {} node)
{
- _sawmill.Warning($"Prototype {EntityManager.GetComponent<MetaDataComponent>(construction.Owner).EntityPrototype?.ID}'s construction component has an invalid node specified.");
+ _sawmill.Warning($"Prototype {EntityManager.GetComponent<MetaDataComponent>(ent).EntityPrototype?.ID}'s construction component has an invalid node specified.");
return;
}
{
if (GetEdgeFromNode(node, edgeIndex) is not {} currentEdge)
{
- _sawmill.Warning($"Prototype {EntityManager.GetComponent<MetaDataComponent>(construction.Owner).EntityPrototype?.ID}'s construction component has an invalid edge index specified.");
+ _sawmill.Warning($"Prototype {EntityManager.GetComponent<MetaDataComponent>(ent).EntityPrototype?.ID}'s construction component has an invalid edge index specified.");
return;
}
{
if (GetNodeFromGraph(graph, targetNodeId) is not { } targetNode)
{
- _sawmill.Warning($"Prototype {EntityManager.GetComponent<MetaDataComponent>(construction.Owner).EntityPrototype?.ID}'s construction component has an invalid target node specified.");
+ _sawmill.Warning($"Prototype {EntityManager.GetComponent<MetaDataComponent>(ent).EntityPrototype?.ID}'s construction component has an invalid target node specified.");
return;
}
- UpdatePathfinding(uid, graph, node, targetNode, edge, construction);
+ UpdatePathfinding(ent, graph, node, targetNode, edge, construction);
}
}
return CompletionResult.Empty;
}
- var stations = _entityManager
- .EntityQuery<StationDataComponent>()
- .Select(stationData =>
- {
- var meta = _entityManager.GetComponent<MetaDataComponent>(stationData.Owner);
-
- return new CompletionOption(stationData.Owner.ToString(), meta.EntityName);
- });
+ var stations = new List<CompletionOption>();
+ var query = _entityManager.EntityQueryEnumerator<StationDataComponent>();
+ while (query.MoveNext(out var uid, out _))
+ {
+ var meta = _entityManager.GetComponent<MetaDataComponent>(uid);
+ stations.Add(new CompletionOption(uid.ToString(), meta.EntityName));
+ }
return CompletionResult.FromHintOptions(stations, null);
}
using Content.Shared.Administration;
using Content.Shared.Decals;
using Content.Shared.Maps;
+using Robust.Server.GameObjects;
using Robust.Shared.Console;
using Robust.Shared.Map;
+using Robust.Shared.Map.Components;
using Robust.Shared.Prototypes;
namespace Content.Server.Decals.Commands
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";
if (!NetEntity.TryParse(args[3], out var gridIdNet) ||
!_entManager.TryGetEntity(gridIdNet, out var gridIdRaw) ||
- !_mapManager.TryGetGrid(gridIdRaw, out var grid))
+ !_entManager.TryGetComponent(gridIdRaw, out MapGridComponent? grid))
{
shell.WriteError($"Failed parsing gridId '{args[3]}'.");
return;
}
- var coordinates = new EntityCoordinates(grid.Owner, new Vector2(x, y));
- if (grid.GetTileRef(coordinates).IsSpace())
+ var mapSystem = _entManager.System<MapSystem>();
+ var coordinates = new EntityCoordinates(gridIdRaw.Value, new Vector2(x, y));
+ if (mapSystem.GetTileRef(gridIdRaw.Value, grid, coordinates).IsSpace())
{
shell.WriteError($"Cannot create decal on space tile at {coordinates}.");
return;
using Content.Shared.Decals;
using Content.Shared.Maps;
using Microsoft.Extensions.ObjectPool;
+using Robust.Server.GameObjects;
using Robust.Server.Player;
using Robust.Shared;
using Robust.Shared.Configuration;
using Robust.Shared.Enums;
using Robust.Shared.Map;
+using Robust.Shared.Map.Components;
using Robust.Shared.Threading;
using Robust.Shared.Timing;
using Robust.Shared.Utility;
[Dependency] private readonly IConfigurationManager _conf = default!;
[Dependency] private readonly IGameTiming _timing = default!;
[Dependency] private readonly IAdminLogManager _adminLogger = default!;
+ [Dependency] private readonly MapSystem _mapSystem = default!;
private readonly Dictionary<NetEntity, HashSet<Vector2i>> _dirtyChunks = new();
private readonly Dictionary<IPlayerSession, Dictionary<NetEntity, HashSet<Vector2i>>> _previousSentChunks = new();
return false;
var gridId = coordinates.GetGridUid(EntityManager);
- if (!MapManager.TryGetGrid(gridId, out var grid))
+ if (!TryComp(gridId, out MapGridComponent? grid))
return false;
- if (grid.GetTileRef(coordinates).IsSpace(_tileDefMan))
+ if (_mapSystem.GetTileRef(gridId.Value, grid, coordinates).IsSpace(_tileDefMan))
return false;
if (!TryComp(gridId, out DecalGridComponent? comp))
{
var xform = Transform(uid);
- foreach (var receiver in EntityQuery<AutoLinkReceiverComponent>())
+ var query = EntityQueryEnumerator<AutoLinkReceiverComponent>();
+ while (query.MoveNext(out var receiverUid, out var receiver))
{
if (receiver.AutoLinkChannel != component.AutoLinkChannel)
continue; // Not ours.
- var rxXform = Transform(receiver.Owner);
+ var rxXform = Transform(receiverUid);
if (rxXform.GridUid != xform.GridUid)
continue;
- _deviceLinkSystem.LinkDefaults(null, uid, receiver.Owner);
+ _deviceLinkSystem.LinkDefaults(null, uid, receiverUid);
}
}
}
return;
if (door.ChangeAirtight && TryComp(uid, out AirtightComponent? airtight))
- _airtightSystem.SetAirblocked(uid, airtight, collidable);
+ _airtightSystem.SetAirblocked((uid, airtight), collidable);
// Pathfinding / AI stuff.
RaiseLocalEvent(new AccessReaderChangeEvent(uid, collidable));
}
}
- protected override void CheckDoorBump(DoorComponent component, PhysicsComponent body)
+ protected override void CheckDoorBump(Entity<DoorComponent, PhysicsComponent> ent)
{
- var uid = body.Owner;
- if (component.BumpOpen)
+ var (uid, door, physics) = ent;
+ if (door.BumpOpen)
{
- foreach (var other in PhysicsSystem.GetContactingEntities(uid, body, approximate: true))
+ foreach (var other in PhysicsSystem.GetContactingEntities(uid, physics, approximate: true))
{
- if (Tags.HasTag(other, "DoorBumpOpener") && TryOpen(uid, component, other, false, quiet: true))
+ if (Tags.HasTag(other, "DoorBumpOpener") && TryOpen(uid, door, other, quiet: true))
break;
}
}
using Content.Server.Popups;
using Content.Server.Power.Components;
using Content.Server.Power.EntitySystems;
-using Content.Server.Remotes;
using Content.Server.Shuttles.Components;
-using Content.Shared.Access.Components;
using Content.Shared.Access.Systems;
using Content.Shared.Atmos;
using Content.Shared.Atmos.Monitor;
using Content.Shared.Doors.Components;
using Content.Shared.Doors.Systems;
using Content.Shared.Popups;
-using Microsoft.Extensions.Options;
-using Robust.Server.GameObjects;
-using Robust.Shared.Map.Components;
-using Robust.Shared.Player;
using Content.Shared.Prying.Components;
+using Robust.Shared.Map.Components;
namespace Content.Server.Doors.Systems
{
var appearanceQuery = GetEntityQuery<AppearanceComponent>();
var xformQuery = GetEntityQuery<TransformComponent>();
- foreach (var (firelock, door) in EntityQuery<FirelockComponent, DoorComponent>())
+ var query = EntityQueryEnumerator<FirelockComponent, DoorComponent>();
+ while (query.MoveNext(out var uid, out var firelock, out var door))
{
// only bother to check pressure on doors that are some variation of closed.
if (door.State != DoorState.Closed
continue;
}
- var uid = door.Owner;
if (airtightQuery.TryGetComponent(uid, out var airtight)
&& xformQuery.TryGetComponent(uid, out var xform)
&& appearanceQuery.TryGetComponent(uid, out var appearance))
if (door.State == DoorState.Open)
{
- if (_doorSystem.TryClose(door.Owner, door))
+ if (_doorSystem.TryClose(uid, door))
{
- return _doorSystem.OnPartialClose(door.Owner, door);
+ return _doorSystem.OnPartialClose(uid, door);
}
}
return false;
if (airtight.AirBlockedDirection != AtmosDirection.All)
tiles.Add(pos);
- var gasses = _atmosSystem.GetTileMixtures(gridAtmosphere.Owner, xform.MapUid, tiles);
+ var gasses = _atmosSystem.GetTileMixtures(xform.ParentUid, xform.MapUid, tiles);
if (gasses == null)
return (false, false);
using Content.Shared.Hands.EntitySystems;
using Content.Shared.Verbs;
using JetBrains.Annotations;
+
namespace Content.Server.Engineering.EntitySystems
{
[UsedImplicitly]
return;
}
- if (component.Deleted || Deleted(component.Owner))
+ if (component.Deleted || Deleted(uid))
return;
- if (!TryComp<TransformComponent>(component.Owner, out var transformComp))
+ if (!TryComp<TransformComponent>(uid, out var transformComp))
return;
var entity = EntityManager.SpawnEntity(component.Prototype, transformComp.Coordinates);
_handsSystem.TryPickup(user, entity);
- EntityManager.DeleteEntity(component.Owner);
+ EntityManager.DeleteEntity(uid);
}
}
}
-using Content.Shared.Coordinates.Helpers;
using Content.Server.Engineering.Components;
using Content.Server.Stack;
+using Content.Shared.Coordinates.Helpers;
using Content.Shared.DoAfter;
using Content.Shared.Interaction;
using Content.Shared.Maps;
if (component.Deleted || !IsTileClear())
return;
- if (EntityManager.TryGetComponent(component.Owner, out StackComponent? stackComp)
+ if (EntityManager.TryGetComponent(uid, out StackComponent? stackComp)
&& component.RemoveOnInteract && !_stackSystem.Use(uid, 1, stackComp))
{
return;
EntityManager.SpawnEntity(component.Prototype, args.ClickLocation.SnapToGrid(grid));
- if (component.RemoveOnInteract && stackComp == null && !((!EntityManager.EntityExists(component.Owner) ? EntityLifeStage.Deleted : EntityManager.GetComponent<MetaDataComponent>(component.Owner).EntityLifeStage) >= EntityLifeStage.Deleted))
- EntityManager.DeleteEntity(component.Owner);
+ if (component.RemoveOnInteract && stackComp == null && !((!EntityManager.EntityExists(uid) ? EntityLifeStage.Deleted : EntityManager.GetComponent<MetaDataComponent>(component.Owner).EntityLifeStage) >= EntityLifeStage.Deleted))
+ EntityManager.DeleteEntity(uid);
}
}
}
using Content.Shared.Interaction;
using Content.Shared.Interaction.Events;
using Content.Shared.Throwing;
-using Robust.Server.GameObjects;
using Robust.Shared.Containers;
using Robust.Shared.Random;
component.GrenadesContainer = _container.EnsureContainer<Container>(uid, "cluster-flash");
}
- private void OnClugStartup(EntityUid uid, ClusterGrenadeComponent component, ComponentStartup args)
+ private void OnClugStartup(Entity<ClusterGrenadeComponent> clug, ref ComponentStartup args)
{
+ var component = clug.Comp;
if (component.FillPrototype != null)
{
component.UnspawnedCount = Math.Max(0, component.MaxGrenades - component.GrenadesContainer.ContainedEntities.Count);
- UpdateAppearance(uid, component);
+ UpdateAppearance(clug);
}
}
- private void OnClugUsing(EntityUid uid, ClusterGrenadeComponent component, InteractUsingEvent args)
+ private void OnClugUsing(Entity<ClusterGrenadeComponent> clug, ref InteractUsingEvent args)
{
- if (args.Handled) return;
+ if (args.Handled)
+ return;
+
+ var component = clug.Comp;
// TODO: Should use whitelist.
if (component.GrenadesContainer.ContainedEntities.Count >= component.MaxGrenades ||
return;
component.GrenadesContainer.Insert(args.Used);
- UpdateAppearance(uid, component);
+ UpdateAppearance(clug);
args.Handled = true;
}
// TODO: Should be an Update loop
uid.SpawnTimer((int) (component.Delay * 1000), () =>
{
- if (Deleted(component.Owner))
+ if (Deleted(uid))
return;
component.CountDown = true;
var grenadesInserted = component.GrenadesContainer.ContainedEntities.Count + component.UnspawnedCount;
var thrownCount = 0;
var segmentAngle = 360 / grenadesInserted;
- while (TryGetGrenade(component, out var grenade))
+ while (TryGetGrenade((uid, component), out var grenade))
{
var angleMin = segmentAngle * thrownCount;
var angleMax = segmentAngle * (thrownCount + 1);
args.Handled = true;
}
- private bool TryGetGrenade(ClusterGrenadeComponent component, out EntityUid grenade)
+ private bool TryGetGrenade(Entity<ClusterGrenadeComponent> ent, out EntityUid grenade)
{
grenade = default;
+ var component = ent.Comp;
if (component.UnspawnedCount > 0)
{
component.UnspawnedCount--;
- grenade = EntityManager.SpawnEntity(component.FillPrototype, Transform(component.Owner).MapPosition);
+ grenade = EntityManager.SpawnEntity(component.FillPrototype, Transform(ent).MapPosition);
return true;
}
return false;
}
- private void UpdateAppearance(EntityUid uid, ClusterGrenadeComponent component)
+ private void UpdateAppearance(Entity<ClusterGrenadeComponent> ent)
{
- if (!TryComp<AppearanceComponent>(component.Owner, out var appearance)) return;
+ var component = ent.Comp;
+ if (!TryComp<AppearanceComponent>(ent, out var appearance))
+ return;
- _appearance.SetData(uid, ClusterGrenadeVisuals.GrenadesCounter, component.GrenadesContainer.ContainedEntities.Count + component.UnspawnedCount, appearance);
+ _appearance.SetData(ent, ClusterGrenadeVisuals.GrenadesCounter, component.GrenadesContainer.ContainedEntities.Count + component.UnspawnedCount, appearance);
}
}
// if the explosion is centered on some grid (and not just space), get the transforms.
if (referenceGrid != null)
{
- var targetGrid = _mapManager.GetGrid(referenceGrid.Value);
- var xform = Transform(targetGrid.Owner);
+ var targetGrid = Comp<MapGridComponent>(referenceGrid.Value);
+ var xform = Transform(referenceGrid.Value);
targetAngle = xform.WorldRotation;
targetMatrix = xform.InvWorldMatrix;
tileSize = targetGrid.TileSize;
if (!_gridEdges.TryGetValue(gridToTransform, out var edges))
continue;
- if (!_mapManager.TryGetGrid(gridToTransform, out var grid))
+ if (!TryComp(gridToTransform, out MapGridComponent? grid))
continue;
if (grid.TileSize != tileSize)
{
- Logger.Error($"Explosions do not support grids with different grid sizes. GridIds: {gridToTransform} and {referenceGrid}");
+ Log.Error($"Explosions do not support grids with different grid sizes. GridIds: {gridToTransform} and {referenceGrid}");
continue;
}
var xforms = EntityManager.GetEntityQuery<TransformComponent>();
- var xform = xforms.GetComponent(grid.Owner);
+ var xform = xforms.GetComponent(gridToTransform);
var (_, gridWorldRotation, gridWorldMatrix, invGridWorldMatrid) = xform.GetWorldPositionRotationMatrixWithInv(xforms);
var localEpicentre = (Vector2i) invGridWorldMatrid.Transform(epicentre.Position);
if (!ev.NewTile.Tile.IsEmpty && !ev.OldTile.IsEmpty)
return;
- if (!_mapManager.TryGetGrid(ev.Entity, out var grid))
+ if (!TryComp(ev.Entity, out MapGridComponent? grid))
return;
var tileRef = ev.NewTile;
using Content.Shared.Database;
using Content.Shared.Examine;
using Content.Shared.Verbs;
-using Robust.Shared.Player;
namespace Content.Server.Explosion.EntitySystems
{
RemCompDeferred<ActiveListenerComponent>(uid);
}
- private void OnListen(EntityUid uid, TriggerOnVoiceComponent component, ListenEvent args)
+ private void OnListen(Entity<TriggerOnVoiceComponent> ent, ref ListenEvent args)
{
+ var component = ent.Comp;
var message = args.Message.Trim();
if (component.IsRecording)
{
if (message.Length >= component.MinLength || message.Length <= component.MaxLength)
- FinishRecording(component, args.Source, args.Message);
+ FinishRecording(ent, args.Source, args.Message);
return;
}
if (!string.IsNullOrWhiteSpace(component.KeyPhrase) && message.Contains(component.KeyPhrase, StringComparison.InvariantCultureIgnoreCase))
{
_adminLogger.Add(LogType.Trigger, LogImpact.High,
- $"A voice-trigger on {ToPrettyString(uid):entity} was triggered by {ToPrettyString(args.Source):speaker} speaking the key-phrase {component.KeyPhrase}.");
- Trigger(uid, args.Source);
+ $"A voice-trigger on {ToPrettyString(ent):entity} was triggered by {ToPrettyString(args.Source):speaker} speaking the key-phrase {component.KeyPhrase}.");
+ Trigger(ent, args.Source);
}
}
- private void OnVoiceGetAltVerbs(EntityUid uid, TriggerOnVoiceComponent component, GetVerbsEvent<AlternativeVerb> args)
+ private void OnVoiceGetAltVerbs(Entity<TriggerOnVoiceComponent> ent, ref GetVerbsEvent<AlternativeVerb> args)
{
if (!args.CanInteract || !args.CanAccess)
return;
+ var component = ent.Comp;
+
+ var @event = args;
args.Verbs.Add(new AlternativeVerb()
{
Text = Loc.GetString(component.IsRecording ? "verb-trigger-voice-record-stop" : "verb-trigger-voice-record"),
Act = () =>
{
if (component.IsRecording)
- StopRecording(component);
+ StopRecording(ent);
else
- StartRecording(component, args.User);
+ StartRecording(ent, @event.User);
},
Priority = 1
});
{
component.KeyPhrase = null;
component.IsRecording = false;
- RemComp<ActiveListenerComponent>(uid);
+ RemComp<ActiveListenerComponent>(ent);
}
});
}
- public void StartRecording(TriggerOnVoiceComponent component, EntityUid user)
+ public void StartRecording(Entity<TriggerOnVoiceComponent> ent, EntityUid user)
{
+ var component = ent.Comp;
component.IsRecording = true;
- EnsureComp<ActiveListenerComponent>(component.Owner).Range = component.ListenRange;
+ EnsureComp<ActiveListenerComponent>(ent).Range = component.ListenRange;
_adminLogger.Add(LogType.Trigger, LogImpact.Low,
- $"A voice-trigger on {ToPrettyString(component.Owner):entity} has started recording. User: {ToPrettyString(user):user}");
+ $"A voice-trigger on {ToPrettyString(ent):entity} has started recording. User: {ToPrettyString(user):user}");
- _popupSystem.PopupEntity(Loc.GetString("popup-trigger-voice-start-recording"), component.Owner);
+ _popupSystem.PopupEntity(Loc.GetString("popup-trigger-voice-start-recording"), ent);
}
- public void StopRecording(TriggerOnVoiceComponent component)
+ public void StopRecording(Entity<TriggerOnVoiceComponent> ent)
{
+ var component = ent.Comp;
component.IsRecording = false;
if (string.IsNullOrWhiteSpace(component.KeyPhrase))
- RemComp<ActiveListenerComponent>(component.Owner);
+ RemComp<ActiveListenerComponent>(ent);
- _popupSystem.PopupEntity(Loc.GetString("popup-trigger-voice-stop-recording"), component.Owner);
+ _popupSystem.PopupEntity(Loc.GetString("popup-trigger-voice-stop-recording"), ent);
}
- public void FinishRecording(TriggerOnVoiceComponent component, EntityUid source, string message)
+ public void FinishRecording(Entity<TriggerOnVoiceComponent> ent, EntityUid source, string message)
{
+ var component = ent.Comp;
component.KeyPhrase = message;
component.IsRecording = false;
_adminLogger.Add(LogType.Trigger, LogImpact.Low,
- $"A voice-trigger on {ToPrettyString(component.Owner):entity} has recorded a new keyphrase: '{component.KeyPhrase}'. Recorded from {ToPrettyString(source):speaker}");
+ $"A voice-trigger on {ToPrettyString(ent):entity} has recorded a new keyphrase: '{component.KeyPhrase}'. Recorded from {ToPrettyString(source):speaker}");
- _popupSystem.PopupEntity(Loc.GetString("popup-trigger-voice-recorded", ("keyphrase", component.KeyPhrase!)), component.Owner);
+ _popupSystem.PopupEntity(Loc.GetString("popup-trigger-voice-recorded", ("keyphrase", component.KeyPhrase!)), ent);
}
private void OnVoiceExamine(EntityUid uid, TriggerOnVoiceComponent component, ExaminedEvent args)
-using Content.Server.Fluids.Components;
-using Content.Server.Chemistry.EntitySystems;
using Content.Server.DoAfter;
+using Content.Server.Fluids.Components;
using Content.Server.Popups;
-using Content.Shared.FixedPoint;
using Content.Shared.Audio;
using Content.Shared.Chemistry.Components.SolutionManager;
using Content.Shared.Chemistry.EntitySystems;
using Content.Shared.Database;
using Content.Shared.DoAfter;
using Content.Shared.Examine;
+using Content.Shared.FixedPoint;
using Content.Shared.Fluids;
+using Content.Shared.Fluids.Components;
using Content.Shared.Interaction;
using Content.Shared.Tag;
using Content.Shared.Verbs;
-using Content.Shared.Fluids.Components;
using Robust.Shared.Collections;
using Robust.Shared.Random;
using Robust.Shared.Utility;
if (drainSolution.MaxVolume == drainSolution.Volume)
{
- _puddleSystem.TrySpillAt(Transform(target).Coordinates, containerSolution, out var puddle);
+ _puddleSystem.TrySpillAt(Transform(target).Coordinates, containerSolution, out _);
_popupSystem.PopupEntity(
Loc.GetString("drain-component-empty-verb-target-is-full-message", ("object", target)),
container);
var puddleQuery = GetEntityQuery<PuddleComponent>();
var puddles = new ValueList<(EntityUid Entity, string Solution)>();
- foreach (var drain in EntityQuery<DrainComponent>())
+ var query = EntityQueryEnumerator<DrainComponent>();
+ while (query.MoveNext(out var uid, out var drain))
{
drain.Accumulator += frameTime;
if (drain.Accumulator < drain.DrainFrequency)
// Disable ambient sound from emptying manually
if (!drain.AutoDrain)
{
- _ambientSoundSystem.SetAmbience(drain.Owner, false);
+ _ambientSoundSystem.SetAmbience(uid, false);
continue;
}
- if (!managerQuery.TryGetComponent(drain.Owner, out var manager))
+ if (!managerQuery.TryGetComponent(uid, out var manager))
continue;
// Best to do this one every second rather than once every tick...
- _solutionSystem.TryGetSolution(drain.Owner, DrainComponent.SolutionName, out var drainSolution, manager);
+ _solutionSystem.TryGetSolution(uid, DrainComponent.SolutionName, out var drainSolution, manager);
if (drainSolution is null)
continue;
if (drainSolution.AvailableVolume <= 0)
{
- _ambientSoundSystem.SetAmbience(drain.Owner, false);
+ _ambientSoundSystem.SetAmbience(uid, false);
continue;
}
// Remove a bit from the buffer
- _solutionSystem.SplitSolution(drain.Owner, drainSolution, (drain.UnitsDestroyedPerSecond * drain.DrainFrequency));
+ _solutionSystem.SplitSolution(uid, drainSolution, (drain.UnitsDestroyedPerSecond * drain.DrainFrequency));
// This will ensure that UnitsPerSecond is per second...
var amount = drain.UnitsPerSecond * drain.DrainFrequency;
- if (!xformQuery.TryGetComponent(drain.Owner, out var xform))
+ if (!xformQuery.TryGetComponent(uid, out var xform))
continue;
puddles.Clear();
if (puddles.Count == 0)
{
- _ambientSoundSystem.SetAmbience(drain.Owner, false);
+ _ambientSoundSystem.SetAmbience(uid, false);
continue;
}
- _ambientSoundSystem.SetAmbience(drain.Owner, true);
+ _ambientSoundSystem.SetAmbience(uid, true);
amount /= puddles.Count;
var transferSolution = _solutionSystem.SplitSolution(puddle, puddleSolution,
FixedPoint2.Min(FixedPoint2.New(amount), puddleSolution.Volume, drainSolution.AvailableVolume));
- _solutionSystem.TryAddSolution(drain.Owner, drainSolution, transferSolution);
+ _solutionSystem.TryAddSolution(uid, drainSolution, transferSolution);
if (puddleSolution.Volume <= 0)
{
private void OnExamined(EntityUid uid, DrainComponent component, ExaminedEvent args)
{
if (!args.IsInDetailsRange ||
- !TryComp(uid, out SolutionContainerManagerComponent? solutionComp) ||
+ !HasComp<SolutionContainerManagerComponent>(uid) ||
!_solutionSystem.TryGetSolution(uid, DrainComponent.SolutionName, out var drainSolution))
- { return; }
+ {
+ return;
+ }
- var text = drainSolution.AvailableVolume != 0 ?
- Loc.GetString("drain-component-examine-volume", ("volume", drainSolution.AvailableVolume)) :
- Loc.GetString("drain-component-examine-hint-full");
+ var text = drainSolution.AvailableVolume != 0
+ ? Loc.GetString("drain-component-examine-volume", ("volume", drainSolution.AvailableVolume))
+ : Loc.GetString("drain-component-examine-hint-full");
args.Message.AddMarkup($"\n\n{text}");
}
if (!args.CanReach || args.Target == null ||
!_tagSystem.HasTag(args.Used, DrainComponent.PlungerTag) ||
!_solutionSystem.TryGetSolution(args.Target.Value, DrainComponent.SolutionName, out var drainSolution))
- { return; }
+ {
+ return;
+ }
if (drainSolution.AvailableVolume > 0)
{
using System.Numerics;
-using Content.Server.Fluids.Components;
using Content.Shared.Fluids;
using Content.Shared.Fluids.Components;
using Robust.Server.Player;
using Robust.Shared.Map;
+using Robust.Shared.Map.Components;
using Robust.Shared.Timing;
namespace Content.Server.Fluids.EntitySystems;
[Dependency] private readonly PuddleSystem _puddle = default!;
private readonly HashSet<IPlayerSession> _playerObservers = new();
-
+ private List<Entity<MapGridComponent>> _grids = new();
public bool ToggleObserver(IPlayerSession observer)
{
var worldBounds = Box2.CenteredAround(transform.WorldPosition,
new Vector2(LocalViewRange, LocalViewRange));
+ _grids.Clear();
+ _mapManager.FindGridsIntersecting(transform.MapID, worldBounds, ref _grids);
- foreach (var grid in _mapManager.FindGridsIntersecting(transform.MapID, worldBounds))
+ foreach (var grid in _grids)
{
var data = new List<PuddleDebugOverlayData>();
var gridUid = grid.Owner;
if (!Exists(gridUid))
continue;
- foreach (var uid in grid.GetAnchoredEntities(worldBounds))
+ foreach (var uid in grid.Comp.GetAnchoredEntities(worldBounds))
{
PuddleComponent? puddle = null;
TransformComponent? xform = null;
using Content.Server.Administration.Logs;
using Content.Server.DoAfter;
using Content.Server.Fluids.Components;
-using Content.Shared.Chemistry;
-using Content.Shared.Chemistry.Reaction;
using Content.Server.Spreader;
+using Content.Shared.Chemistry;
+using Content.Shared.Chemistry.Components;
using Content.Shared.Chemistry.EntitySystems;
+using Content.Shared.Chemistry.Reaction;
using Content.Shared.Chemistry.Reagent;
using Content.Shared.Database;
+using Content.Shared.Effects;
using Content.Shared.Examine;
using Content.Shared.FixedPoint;
using Content.Shared.Fluids;
-using Content.Shared.Popups;
-using Content.Shared.Slippery;
using Content.Shared.Fluids.Components;
using Content.Shared.Friction;
using Content.Shared.IdentityManagement;
+using Content.Shared.Maps;
+using Content.Shared.Movement.Components;
+using Content.Shared.Movement.Systems;
+using Content.Shared.Popups;
+using Content.Shared.Slippery;
using Content.Shared.StepTrigger.Components;
using Content.Shared.StepTrigger.Systems;
using Robust.Server.GameObjects;
using Robust.Shared.Map;
using Robust.Shared.Map.Components;
using Robust.Shared.Player;
-using Solution = Content.Shared.Chemistry.Components.Solution;
using Robust.Shared.Prototypes;
using Robust.Shared.Random;
using Robust.Shared.Timing;
-using Content.Shared.Movement.Components;
-using Content.Shared.Movement.Systems;
-using Content.Shared.Maps;
-using Content.Shared.Effects;
namespace Content.Server.Fluids.EntitySystems;
return false;
var targets = new List<EntityUid>();
+ var reactive = new HashSet<Entity<ReactiveComponent>>();
+ _lookup.GetEntitiesInRange(coordinates, 1.0f, reactive);
+
// Get reactive entities nearby--if there are some, it'll spill a bit on them instead.
- foreach (var ent in _lookup.GetComponentsInRange<ReactiveComponent>(coordinates, 1.0f))
+ foreach (var ent in reactive)
{
// sorry! no overload for returning uid, so .owner must be used
var owner = ent.Owner;
// Add the solution to the vapor and actually send the thing
var vaporComponent = Comp<VaporComponent>(vapor);
- _vapor.TryAddSolution(vaporComponent, newSolution);
+ var ent = (vapor, vaporComponent);
+ _vapor.TryAddSolution(ent, newSolution);
// impulse direction is defined in world-coordinates, not local coordinates
var impulseDirection = rotation.ToVec();
var time = diffLength / component.SprayVelocity;
cooldownTime = MathF.Max(time, cooldownTime);
- _vapor.Start(vaporComponent, vaporXform, impulseDirection * diffLength, component.SprayVelocity, target, time, args.User);
+ _vapor.Start(ent, vaporXform, impulseDirection * diffLength, component.SprayVelocity, target, time, args.User);
if (TryComp<PhysicsComponent>(args.User, out var body))
{
using System.Linq;
-using System.Text; // todo: remove this stinky LINQy
-using Robust.Server.GameObjects;
-using Robust.Shared.Audio;
-using Robust.Shared.Timing;
+using System.Text;
using Content.Server.Paper;
using Content.Server.Popups;
using Content.Server.UserInterface;
using Content.Shared.Hands.EntitySystems;
using Content.Shared.Interaction;
using Content.Shared.Verbs;
+using Robust.Server.GameObjects;
+using Robust.Shared.Audio;
+using Robust.Shared.Timing;
+// todo: remove this stinky LINQy
namespace Content.Server.Forensics
{
scanner.LastScannedName = MetaData(args.Args.Target.Value).EntityName;
}
- OpenUserInterface(args.Args.User, scanner);
+ OpenUserInterface(args.Args.User, (uid, scanner));
}
/// <remarks>
UpdateUserInterface(uid, component);
}
- private void OpenUserInterface(EntityUid user, ForensicScannerComponent component)
+ private void OpenUserInterface(EntityUid user, Entity<ForensicScannerComponent> scanner)
{
if (!TryComp<ActorComponent>(user, out var actor))
return;
- UpdateUserInterface(component.Owner, component);
+ UpdateUserInterface(scanner, scanner.Comp);
- _uiSystem.TryOpen(component.Owner, ForensicScannerUiKey.Key, actor.PlayerSession);
+ _uiSystem.TryOpen(scanner, ForensicScannerUiKey.Key, actor.PlayerSession);
}
private void OnPrint(EntityUid uid, ForensicScannerComponent component, ForensicScannerPrintMessage args)
var printed = EntityManager.SpawnEntity(component.MachineOutput, Transform(uid).Coordinates);
_handsSystem.PickupOrDrop(args.Session.AttachedEntity, printed, checkActionBlocker: false);
- if (!TryComp<PaperComponent>(printed, out var paper))
+ if (!HasComp<PaperComponent>(printed))
{
_sawmill.Error("Printed paper did not have PaperComponent.");
return;
using JetBrains.Annotations;
using Robust.Server.Player;
using Robust.Shared.Map;
+using Robust.Shared.Map.Components;
using Robust.Shared.Network;
using Robust.Shared.Prototypes;
using Robust.Shared.Random;
/// How many players have joined the round through normal methods.
/// Useful for game rules to look at. Doesn't count observers, people in lobby, etc.
/// </summary>
- public int PlayersJoinedRoundNormally = 0;
+ public int PlayersJoinedRoundNormally;
// Mainly to avoid allocations.
private readonly List<EntityCoordinates> _possiblePositions = new();
+ private List<EntityUid> GetSpawnableStations()
+ {
+ var spawnableStations = new List<EntityUid>();
+ var query = EntityQueryEnumerator<StationJobsComponent, StationSpawningComponent>();
+ while (query.MoveNext(out var uid, out _, out _))
+ {
+ spawnableStations.Add(uid);
+ }
+
+ return spawnableStations;
+ }
+
private void SpawnPlayers(List<IPlayerSession> readyPlayers, Dictionary<NetUserId, HumanoidCharacterProfile> profiles, bool force)
{
// Allow game rules to spawn players by themselves if needed. (For example, nuke ops or wizard)
}
}
- var spawnableStations = EntityQuery<StationJobsComponent, StationSpawningComponent>().Select(x => x.Item1.Owner).ToList();
-
+ var spawnableStations = GetSpawnableStations();
var assignedJobs = _stationJobs.AssignJobs(profiles, spawnableStations);
_stationJobs.AssignOverflowJobs(ref assignedJobs, playerNetIds, profiles, spawnableStations);
if (station == EntityUid.Invalid)
{
- var stations = EntityQuery<StationJobsComponent, StationSpawningComponent>().Select(x => x.Item1.Owner).ToList();
+ var stations = GetSpawnableStations();
_robustRandom.Shuffle(stations);
if (stations.Count == 0)
station = EntityUid.Invalid;
restrictedRoles.UnionWith(getDisallowed);
var jobBans = _banManager.GetJobBans(player.UserId);
- if(jobBans != null) restrictedRoles.UnionWith(jobBans);
+ if (jobBans != null)
+ restrictedRoles.UnionWith(jobBans);
// Pick best job best on prefs.
jobId ??= _stationJobs.PickBestAvailableJobWithPriority(station, character.JobPriorities, true,
// Fallback to a random grid.
if (_possiblePositions.Count == 0)
{
- foreach (var grid in _mapManager.GetAllGrids())
+ var query = AllEntityQuery<MapGridComponent>();
+ while (query.MoveNext(out var uid, out var grid))
{
- if (!metaQuery.TryGetComponent(grid.Owner, out var meta) ||
+ if (!metaQuery.TryGetComponent(uid, out var meta) ||
meta.EntityPaused)
{
continue;
}
- _possiblePositions.Add(new EntityCoordinates(grid.Owner, Vector2.Zero));
+ _possiblePositions.Add(new EntityCoordinates(uid, Vector2.Zero));
}
}
// we can only currently guarantee that NT stations are the only station to
// exist in the base game.
- var eligible = EntityQuery<StationEventEligibleComponent, NpcFactionMemberComponent>()
- .Where(x =>
- _npcFaction.IsFactionHostile(component.Faction, x.Item2.Owner, x.Item2))
- .Select(x => x.Item1.Owner)
- .ToList();
+ var eligible = new List<Entity<StationEventEligibleComponent, NpcFactionMemberComponent>>();
+ var eligibleQuery = EntityQueryEnumerator<StationEventEligibleComponent, NpcFactionMemberComponent>();
+ while (eligibleQuery.MoveNext(out var eligibleUid, out var eligibleComp, out var member))
+ {
+ if (!_npcFaction.IsFactionFriendly(component.Faction, eligibleUid, member))
+ continue;
+
+ eligible.Add((eligibleUid, eligibleComp, member));
+ }
- if (!eligible.Any())
+ if (eligible.Count == 0)
return;
component.TargetStation = _random.Pick(eligible);
private uint _nextRoleIdentifier;
private bool _needsUpdateGhostRoleCount = true;
- private readonly Dictionary<uint, GhostRoleComponent> _ghostRoles = new();
+ private readonly Dictionary<uint, Entity<GhostRoleComponent>> _ghostRoles = new();
private readonly Dictionary<ICommonSession, GhostRolesEui> _openUis = new();
private readonly Dictionary<ICommonSession, MakeGhostRoleEui> _openMakeGhostRoleUis = new();
[ViewVariables]
- public IReadOnlyCollection<GhostRoleComponent> GhostRoles => _ghostRoles.Values;
+ public IReadOnlyCollection<Entity<GhostRoleComponent>> GhostRoles => _ghostRoles.Values;
public override void Initialize()
{
_playerManager.PlayerStatusChanged += PlayerStatusChanged;
}
- private void OnMobStateChanged(EntityUid uid, GhostTakeoverAvailableComponent component, MobStateChangedEvent args)
+ private void OnMobStateChanged(Entity<GhostTakeoverAvailableComponent> component, ref MobStateChangedEvent args)
{
- if (!TryComp(uid, out GhostRoleComponent? ghostRole))
+ if (!TryComp(component, out GhostRoleComponent? ghostRole))
return;
switch (args.NewMobState)
case MobState.Alive:
{
if (!ghostRole.Taken)
- RegisterGhostRole(ghostRole);
+ RegisterGhostRole((component, ghostRole));
break;
}
case MobState.Critical:
case MobState.Dead:
- UnregisterGhostRole(ghostRole);
+ UnregisterGhostRole((component, ghostRole));
break;
}
}
public void CloseEui(ICommonSession session)
{
- if (!_openUis.ContainsKey(session)) return;
+ if (!_openUis.ContainsKey(session))
+ return;
_openUis.Remove(session, out var eui);
}
}
- public void RegisterGhostRole(GhostRoleComponent role)
+ public void RegisterGhostRole(Entity<GhostRoleComponent> role)
{
- if (_ghostRoles.ContainsValue(role)) return;
- _ghostRoles[role.Identifier = GetNextRoleIdentifier()] = role;
- UpdateAllEui();
+ if (_ghostRoles.ContainsValue(role))
+ return;
+ _ghostRoles[role.Comp.Identifier = GetNextRoleIdentifier()] = role;
+ UpdateAllEui();
}
- public void UnregisterGhostRole(GhostRoleComponent role)
+ public void UnregisterGhostRole(Entity<GhostRoleComponent> role)
{
- if (!_ghostRoles.ContainsKey(role.Identifier) || _ghostRoles[role.Identifier] != role) return;
- _ghostRoles.Remove(role.Identifier);
+ var comp = role.Comp;
+ if (!_ghostRoles.ContainsKey(comp.Identifier) || _ghostRoles[comp.Identifier] != role)
+ return;
+
+ _ghostRoles.Remove(comp.Identifier);
UpdateAllEui();
}
public void Takeover(ICommonSession player, uint identifier)
{
- if (!_ghostRoles.TryGetValue(identifier, out var role)) return;
+ if (!_ghostRoles.TryGetValue(identifier, out var role))
+ return;
var ev = new TakeGhostRoleEvent(player);
- RaiseLocalEvent(role.Owner, ref ev);
+ RaiseLocalEvent(role, ref ev);
- if (!ev.TookRole) return;
+ if (!ev.TookRole)
+ return;
if (player.AttachedEntity != null)
- _adminLogger.Add(LogType.GhostRoleTaken, LogImpact.Low, $"{player:player} took the {role.RoleName:roleName} ghost role {ToPrettyString(player.AttachedEntity.Value):entity}");
+ _adminLogger.Add(LogType.GhostRoleTaken, LogImpact.Low, $"{player:player} took the {role.Comp.RoleName:roleName} ghost role {ToPrettyString(player.AttachedEntity.Value):entity}");
CloseEui(player);
}
public void Follow(ICommonSession player, uint identifier)
{
- if (!_ghostRoles.TryGetValue(identifier, out var role)) return;
- if (player.AttachedEntity == null) return;
+ if (!_ghostRoles.TryGetValue(identifier, out var role))
+ return;
+
+ if (player.AttachedEntity == null)
+ return;
- _followerSystem.StartFollowingEntity(player.AttachedEntity.Value, role.Owner);
+ _followerSystem.StartFollowingEntity(player.AttachedEntity.Value, role);
}
public void GhostRoleInternalCreateMindAndTransfer(ICommonSession player, EntityUid roleUid, EntityUid mob, GhostRoleComponent? role = null)
{
- if (!Resolve(roleUid, ref role)) return;
+ if (!Resolve(roleUid, ref role))
+ return;
DebugTools.AssertNotNull(player.ContentData());
var roles = new List<GhostRoleInfo>();
var metaQuery = GetEntityQuery<MetaDataComponent>();
- foreach (var (id, role) in _ghostRoles)
+ foreach (var (id, (uid, role)) in _ghostRoles)
{
- var uid = role.Owner;
-
if (metaQuery.GetComponent(uid).EntityPaused)
continue;
private void OnPlayerAttached(PlayerAttachedEvent message)
{
// Close the session of any player that has a ghost roles window open and isn't a ghost anymore.
- if (!_openUis.ContainsKey(message.Player)) return;
- if (EntityManager.HasComponent<GhostComponent>(message.Entity)) return;
+ if (!_openUis.ContainsKey(message.Player))
+ return;
+
+ if (HasComp<GhostComponent>(message.Entity))
+ return;
+
CloseEui(message.Player);
}
return;
ghostRole.Taken = true;
- UnregisterGhostRole(ghostRole);
+ UnregisterGhostRole((uid, ghostRole));
}
private void OnMindRemoved(EntityUid uid, GhostTakeoverAvailableComponent component, MindRemovedMessage args)
return;
ghostRole.Taken = false;
- RegisterGhostRole(ghostRole);
+ RegisterGhostRole((uid, ghostRole));
}
public void Reset(RoundRestartCleanupEvent ev)
UpdateAllEui();
}
- private void OnInit(EntityUid uid, GhostRoleComponent role, ComponentInit args)
+ private void OnInit(Entity<GhostRoleComponent> ent, ref ComponentInit args)
{
+ var role = ent.Comp;
if (role.Probability < 1f && !_random.Prob(role.Probability))
{
- RemComp<GhostRoleComponent>(uid);
+ RemComp<GhostRoleComponent>(ent);
return;
}
if (role.RoleRules == "")
role.RoleRules = Loc.GetString("ghost-role-component-default-rules");
- RegisterGhostRole(role);
+ RegisterGhostRole(ent);
}
- private void OnShutdown(EntityUid uid, GhostRoleComponent role, ComponentShutdown args)
+ private void OnShutdown(Entity<GhostRoleComponent> role, ref ComponentShutdown args)
{
UnregisterGhostRole(role);
}
MakeSentientCommand.MakeSentient(uid, EntityManager, ghostRole.AllowMovement, ghostRole.AllowSpeech);
GhostRoleInternalCreateMindAndTransfer(args.Player, uid, uid, ghostRole);
- UnregisterGhostRole(ghostRole);
+ UnregisterGhostRole((uid, ghostRole));
args.TookRole = true;
}
using Content.Server.Administration.Logs;
using Content.Server.Audio;
+using Content.Server.Construction;
using Content.Server.Power.Components;
using Content.Shared.Database;
using Content.Shared.Gravity;
using Content.Shared.Interaction;
using Robust.Server.GameObjects;
-using Robust.Server.Player;
using Robust.Shared.Players;
-using Content.Server.Construction;
namespace Content.Server.Gravity
{
{
base.Update(frameTime);
- foreach (var (gravGen, powerReceiver) in EntityManager
- .EntityQuery<GravityGeneratorComponent, ApcPowerReceiverComponent>())
+ var query = EntityQueryEnumerator<GravityGeneratorComponent, ApcPowerReceiverComponent>();
+ while (query.MoveNext(out var uid, out var gravGen, out var powerReceiver))
{
+ var ent = (uid, gravGen, powerReceiver);
if (!gravGen.Intact)
continue;
var updateUI = gravGen.NeedUIUpdate;
if (!MathHelper.CloseTo(lastCharge, gravGen.Charge))
{
- UpdateState(gravGen, powerReceiver);
+ UpdateState(ent);
updateUI = true;
}
if (updateUI)
- UpdateUI(gravGen, powerReceiver, chargeRate);
+ UpdateUI(ent, chargeRate);
if (active != gravGen.GravityActive &&
- TryComp<TransformComponent>(gravGen.Owner, out var xform) &&
+ TryComp<TransformComponent>(uid, out var xform) &&
TryComp<GravityComponent>(xform.ParentUid, out var gravity))
{
// Force it on in the faster path.
powerReceiver.Load = component.SwitchedOn ? component.ActivePowerUse : component.IdlePowerUse;
}
- private void UpdateUI(
- GravityGeneratorComponent component,
- ApcPowerReceiverComponent powerReceiver,
- float chargeRate)
+ private void UpdateUI(Entity<GravityGeneratorComponent, ApcPowerReceiverComponent> ent, float chargeRate)
{
- if (!_uiSystem.IsUiOpen(component.Owner, SharedGravityGeneratorComponent.GravityGeneratorUiKey.Key))
+ var (_, component, powerReceiver) = ent;
+ if (!_uiSystem.IsUiOpen(ent, SharedGravityGeneratorComponent.GravityGeneratorUiKey.Key))
return;
var chargeTarget = chargeRate < 0 ? 0 : component.MaxCharge;
);
_uiSystem.TrySetUiState(
- component.Owner,
+ ent,
SharedGravityGeneratorComponent.GravityGeneratorUiKey.Key,
state);
component.NeedUIUpdate = false;
}
- private void OnCompInit(EntityUid uid, GravityGeneratorComponent component, ComponentInit args)
+ private void OnCompInit(Entity<GravityGeneratorComponent> ent, ref ComponentInit args)
{
ApcPowerReceiverComponent? powerReceiver = null;
- if (!Resolve(uid, ref powerReceiver, false))
+ if (!Resolve(ent, ref powerReceiver, false))
return;
- UpdatePowerState(component, powerReceiver);
- UpdateState(component, powerReceiver);
+ UpdatePowerState(ent, powerReceiver);
+ UpdateState((ent, ent.Comp, powerReceiver));
}
private void OnInteractHand(EntityUid uid, GravityGeneratorComponent component, InteractHandEvent args)
component.NeedUIUpdate = true;
}
- public void UpdateState(GravityGeneratorComponent grav, ApcPowerReceiverComponent powerReceiver)
+ public void UpdateState(Entity<GravityGeneratorComponent, ApcPowerReceiverComponent> ent)
{
- var uid = grav.Owner;
+ var (uid, grav, powerReceiver) = ent;
var appearance = EntityManager.GetComponentOrNull<AppearanceComponent>(uid);
_appearance.SetData(uid, GravityGeneratorVisuals.Charge, grav.Charge, appearance);
if (!grav.Intact)
{
- MakeBroken(uid, grav, appearance);
+ MakeBroken((uid, grav), appearance);
}
else if (powerReceiver.PowerReceived < grav.IdlePowerUse)
{
- MakeUnpowered(uid, grav, appearance);
+ MakeUnpowered((uid, grav), appearance);
}
else if (!grav.SwitchedOn)
{
- MakeOff(uid, grav, appearance);
+ MakeOff((uid, grav), appearance);
}
else
{
- MakeOn(uid, grav, appearance);
+ MakeOn((uid, grav), appearance);
}
}
component.MaxCharge = maxChargeMultipler * 1;
}
- private void MakeBroken(EntityUid uid, GravityGeneratorComponent component, AppearanceComponent? appearance)
+ private void MakeBroken(Entity<GravityGeneratorComponent> ent, AppearanceComponent? appearance)
{
- _ambientSoundSystem.SetAmbience(component.Owner, false);
+ _ambientSoundSystem.SetAmbience(ent, false);
- _appearance.SetData(uid, GravityGeneratorVisuals.State, GravityGeneratorStatus.Broken);
+ _appearance.SetData(ent, GravityGeneratorVisuals.State, GravityGeneratorStatus.Broken);
}
- private void MakeUnpowered(EntityUid uid, GravityGeneratorComponent component, AppearanceComponent? appearance)
+ private void MakeUnpowered(Entity<GravityGeneratorComponent> ent, AppearanceComponent? appearance)
{
- _ambientSoundSystem.SetAmbience(component.Owner, false);
+ _ambientSoundSystem.SetAmbience(ent, false);
- _appearance.SetData(uid, GravityGeneratorVisuals.State, GravityGeneratorStatus.Unpowered, appearance);
+ _appearance.SetData(ent, GravityGeneratorVisuals.State, GravityGeneratorStatus.Unpowered, appearance);
}
- private void MakeOff(EntityUid uid, GravityGeneratorComponent component, AppearanceComponent? appearance)
+ private void MakeOff(Entity<GravityGeneratorComponent> ent, AppearanceComponent? appearance)
{
- _ambientSoundSystem.SetAmbience(component.Owner, false);
+ _ambientSoundSystem.SetAmbience(ent, false);
- _appearance.SetData(uid, GravityGeneratorVisuals.State, GravityGeneratorStatus.Off, appearance);
+ _appearance.SetData(ent, GravityGeneratorVisuals.State, GravityGeneratorStatus.Off, appearance);
}
- private void MakeOn(EntityUid uid, GravityGeneratorComponent component, AppearanceComponent? appearance)
+ private void MakeOn(Entity<GravityGeneratorComponent> ent, AppearanceComponent? appearance)
{
- _ambientSoundSystem.SetAmbience(component.Owner, true);
+ _ambientSoundSystem.SetAmbience(ent, true);
- _appearance.SetData(uid, GravityGeneratorVisuals.State, GravityGeneratorStatus.On, appearance);
+ _appearance.SetData(ent, GravityGeneratorVisuals.State, GravityGeneratorStatus.On, appearance);
}
private void OnSwitchGenerator(
using Content.Shared.Stacks;
using Content.Shared.Storage;
using Content.Shared.Throwing;
-using JetBrains.Annotations;
using Robust.Server.Player;
-using Robust.Shared.Configuration;
using Robust.Shared.Containers;
using Robust.Shared.GameStates;
using Robust.Shared.Input.Binding;
using Robust.Shared.Map;
-using Robust.Shared.Player;
using Robust.Shared.Players;
using Robust.Shared.Utility;
base.HandleEntityRemoved(uid, hands, args);
if (!Deleted(args.Entity) && TryComp(args.Entity, out HandVirtualItemComponent? @virtual))
- _virtualSystem.Delete(@virtual, uid);
+ _virtualSystem.Delete((args.Entity, @virtual), uid);
}
private void HandleBodyPartAdded(EntityUid uid, HandsComponent component, ref BodyPartAddedEvent args)
var coords = Transform(args.User).Coordinates;
var handsEnt = Spawn(component.SelectedEntity, coords);
- _adminLogger.Add(LogType.EntitySpawn, LogImpact.Low, $"{ToPrettyString(args.User)} used {ToPrettyString(component.Owner)} which spawned {ToPrettyString(handsEnt)}");
+ _adminLogger.Add(LogType.EntitySpawn, LogImpact.Low, $"{ToPrettyString(args.User)} used {ToPrettyString(uid)} which spawned {ToPrettyString(handsEnt)}");
EnsureComp<ItemComponent>(handsEnt); // For insane mode.
if (component.Wrapper is not null)
Spawn(component.Wrapper, coords);
using Content.Shared.Database;
using Content.Shared.Hands;
using Content.Shared.Humanoid;
-using Content.Shared.Humanoid.Prototypes;
using Content.Shared.IdentityManagement;
using Content.Shared.IdentityManagement.Components;
using Content.Shared.Inventory;
using Content.Shared.Inventory.Events;
using Robust.Shared.Enums;
using Robust.Shared.GameObjects.Components.Localization;
-using Robust.Shared.Prototypes;
namespace Content.Server.IdentityManagement;
// Get their name and job from their ID for their presumed name.
if (_idCard.TryFindIdCard(target, out var id))
{
- presumedName = string.IsNullOrWhiteSpace(id.FullName) ? null : id.FullName;
- presumedJob = id.JobTitle?.ToLowerInvariant();
+ presumedName = string.IsNullOrWhiteSpace(id.Comp.FullName) ? null : id.Comp.FullName;
+ presumedJob = id.Comp.JobTitle?.ToLowerInvariant();
}
// If it didn't find a job, that's fine.
{
base.Update(frameTime);
- foreach (var (component,transform) in EntityQuery<IgnitionSourceComponent,TransformComponent>())
+ var query = EntityQueryEnumerator<IgnitionSourceComponent, TransformComponent>();
+ while (query.MoveNext(out var source, out var component, out var transform))
{
- var source = component.Owner;
if (!component.Ignited)
continue;
using Content.Shared.Kitchen;
using Content.Shared.Popups;
using Content.Shared.Random;
-using Content.Shared.Random.Helpers;
using Content.Shared.Stacks;
using JetBrains.Annotations;
using Robust.Server.GameObjects;
{
base.Update(frameTime);
- foreach (var (active, reagentGrinder) in EntityQuery<ActiveReagentGrinderComponent, ReagentGrinderComponent>())
+ var query = EntityQueryEnumerator<ActiveReagentGrinderComponent, ReagentGrinderComponent>();
+ while (query.MoveNext(out var uid, out var active, out var reagentGrinder))
{
- var uid = reagentGrinder.Owner;
-
if (active.EndTime > _timing.CurTime)
continue;
using Content.Shared.Verbs;
using JetBrains.Annotations;
using Robust.Server.GameObjects;
-using Robust.Shared.Audio;
-using Robust.Shared.Player;
using Robust.Shared.Utility;
namespace Content.Server.Light.EntitySystems
public override void Update(float frameTime)
{
- foreach (var light in EntityManager.EntityQuery<ExpendableLightComponent>())
+ var query = EntityQueryEnumerator<ExpendableLightComponent>();
+ while (query.MoveNext(out var uid, out var light))
{
- UpdateLight(light, frameTime);
+ UpdateLight((uid, light), frameTime);
}
}
- private void UpdateLight(ExpendableLightComponent component, float frameTime)
+ private void UpdateLight(Entity<ExpendableLightComponent> ent, float frameTime)
{
- if (!component.Activated) return;
+ var component = ent.Comp;
+ if (!component.Activated)
+ return;
component.StateExpiryTime -= frameTime;
component.CurrentState = ExpendableLightState.Fading;
component.StateExpiryTime = component.FadeOutDuration;
- UpdateVisualizer(component);
+ UpdateVisualizer(ent);
break;
default:
case ExpendableLightState.Fading:
component.CurrentState = ExpendableLightState.Dead;
- var meta = MetaData(component.Owner);
- _metaData.SetEntityName(component.Owner, Loc.GetString(component.SpentName), meta);
- _metaData.SetEntityDescription(component.Owner, Loc.GetString(component.SpentDesc), meta);
+ var meta = MetaData(ent);
+ _metaData.SetEntityName(ent, Loc.GetString(component.SpentName), meta);
+ _metaData.SetEntityDescription(ent, Loc.GetString(component.SpentDesc), meta);
- _tagSystem.AddTag(component.Owner, "Trash");
+ _tagSystem.AddTag(ent, "Trash");
- UpdateSounds(component);
- UpdateVisualizer(component);
+ UpdateSounds(ent);
+ UpdateVisualizer(ent);
- if (TryComp<ItemComponent>(component.Owner, out var item))
+ if (TryComp<ItemComponent>(ent, out var item))
{
- _item.SetHeldPrefix(component.Owner, "unlit", item);
+ _item.SetHeldPrefix(ent, "unlit", item);
}
break;
/// <summary>
/// Enables the light if it is not active. Once active it cannot be turned off.
/// </summary>
- public bool TryActivate(ExpendableLightComponent component)
+ public bool TryActivate(Entity<ExpendableLightComponent> ent)
{
+ var component = ent.Comp;
if (!component.Activated && component.CurrentState == ExpendableLightState.BrandNew)
{
- if (TryComp<ItemComponent>(component.Owner, out var item))
+ if (TryComp<ItemComponent>(ent, out var item))
{
- _item.SetHeldPrefix(component.Owner, "lit", item);
+ _item.SetHeldPrefix(ent, "lit", item);
}
component.CurrentState = ExpendableLightState.Lit;
component.StateExpiryTime = component.GlowDuration;
- UpdateSounds(component);
- UpdateVisualizer(component);
+ UpdateSounds(ent);
+ UpdateVisualizer(ent);
return true;
}
return false;
}
- private void UpdateVisualizer(ExpendableLightComponent component, AppearanceComponent? appearance = null)
+ private void UpdateVisualizer(Entity<ExpendableLightComponent> ent, AppearanceComponent? appearance = null)
{
- if (!Resolve(component.Owner, ref appearance, false)) return;
+ var component = ent.Comp;
+ if (!Resolve(ent, ref appearance, false))
+ return;
- _appearance.SetData(appearance.Owner, ExpendableLightVisuals.State, component.CurrentState, appearance);
+ _appearance.SetData(ent, ExpendableLightVisuals.State, component.CurrentState, appearance);
switch (component.CurrentState)
{
case ExpendableLightState.Lit:
- _appearance.SetData(appearance.Owner, ExpendableLightVisuals.Behavior, component.TurnOnBehaviourID, appearance);
+ _appearance.SetData(ent, ExpendableLightVisuals.Behavior, component.TurnOnBehaviourID, appearance);
break;
case ExpendableLightState.Fading:
- _appearance.SetData(appearance.Owner, ExpendableLightVisuals.Behavior, component.FadeOutBehaviourID, appearance);
+ _appearance.SetData(ent, ExpendableLightVisuals.Behavior, component.FadeOutBehaviourID, appearance);
break;
case ExpendableLightState.Dead:
- _appearance.SetData(appearance.Owner, ExpendableLightVisuals.Behavior, string.Empty, appearance);
+ _appearance.SetData(ent, ExpendableLightVisuals.Behavior, string.Empty, appearance);
var isHotEvent = new IsHotEvent() {IsHot = true};
- RaiseLocalEvent(component.Owner, isHotEvent);
+ RaiseLocalEvent(ent, isHotEvent);
break;
}
}
- private void UpdateSounds(ExpendableLightComponent component)
+ private void UpdateSounds(Entity<ExpendableLightComponent> ent)
{
- var uid = component.Owner;
+ var component = ent.Comp;
switch (component.CurrentState)
{
case ExpendableLightState.Lit:
- _audio.PlayPvs(component.LitSound, uid);
+ _audio.PlayPvs(component.LitSound, ent);
break;
case ExpendableLightState.Fading:
break;
default:
- _audio.PlayPvs(component.DieSound, uid);
+ _audio.PlayPvs(component.DieSound, ent);
break;
}
- if (TryComp<ClothingComponent>(uid, out var clothing))
+ if (TryComp<ClothingComponent>(ent, out var clothing))
{
- _clothing.SetEquippedPrefix(uid, component.Activated ? "Activated" : string.Empty, clothing);
+ _clothing.SetEquippedPrefix(ent, component.Activated ? "Activated" : string.Empty, clothing);
}
}
EntityManager.EnsureComponent<PointLightComponent>(uid);
}
- private void OnExpLightUse(EntityUid uid, ExpendableLightComponent component, UseInHandEvent args)
+ private void OnExpLightUse(Entity<ExpendableLightComponent> ent, ref UseInHandEvent args)
{
- if (args.Handled) return;
+ if (args.Handled)
+ return;
+
var isHotEvent = new IsHotEvent() {IsHot = true};
- RaiseLocalEvent(uid, isHotEvent);
- if (TryActivate(component))
+ RaiseLocalEvent(ent, isHotEvent);
+ if (TryActivate(ent))
args.Handled = true;
}
- private void AddIgniteVerb(EntityUid uid, ExpendableLightComponent component, GetVerbsEvent<ActivationVerb> args)
+ private void AddIgniteVerb(Entity<ExpendableLightComponent> ent, ref GetVerbsEvent<ActivationVerb> args)
{
if (!args.CanAccess || !args.CanInteract)
return;
- if (component.CurrentState != ExpendableLightState.BrandNew)
+ if (ent.Comp.CurrentState != ExpendableLightState.BrandNew)
return;
// Ignite the flare or make the glowstick glow.
{
Text = Loc.GetString("expendable-light-start-verb"),
Icon = new SpriteSpecifier.Texture(new ("/Textures/Interface/VerbIcons/light.svg.192dpi.png")),
- Act = () => TryActivate(component)
+ Act = () => TryActivate(ent)
};
args.Verbs.Add(verb);
}
using Content.Shared.Rounding;
using Content.Shared.Toggleable;
using Content.Shared.Verbs;
-using JetBrains.Annotations;
-using Robust.Server.GameObjects;
using Robust.Shared.Containers;
using Robust.Shared.GameStates;
-using Robust.Shared.Prototypes;
using Robust.Shared.Utility;
namespace Content.Server.Light.EntitySystems
{
public sealed class HandheldLightSystem : SharedHandheldLightSystem
{
- [Dependency] private readonly IPrototypeManager _proto = default!;
[Dependency] private readonly ActionsSystem _actions = default!;
[Dependency] private readonly ActionContainerSystem _actionContainer = default!;
[Dependency] private readonly PopupSystem _popup = default!;
// TODO: Ideally you'd be able to subscribe to power stuff to get events at certain percentages.. or something?
// But for now this will be better anyway.
- private readonly HashSet<HandheldLightComponent> _activeLights = new();
+ private readonly HashSet<Entity<HandheldLightComponent>> _activeLights = new();
public override void Initialize()
{
SubscribeLocalEvent<HandheldLightComponent, EntRemovedFromContainerMessage>(OnEntRemoved);
}
- private void OnEntInserted(
- EntityUid uid,
- HandheldLightComponent component,
- EntInsertedIntoContainerMessage args)
+ private void OnEntInserted(Entity<HandheldLightComponent> ent, ref EntInsertedIntoContainerMessage args)
{
// Not guaranteed to be the correct container for our slot, I don't care.
- UpdateLevel(uid, component);
+ UpdateLevel(ent);
}
- private void OnEntRemoved(
- EntityUid uid,
- HandheldLightComponent component,
- EntRemovedFromContainerMessage args)
+ private void OnEntRemoved(Entity<HandheldLightComponent> ent, ref EntRemovedFromContainerMessage args)
{
// Ditto above
- UpdateLevel(uid, component);
+ UpdateLevel(ent);
}
private void OnGetActions(EntityUid uid, HandheldLightComponent component, GetItemActionsEvent args)
args.AddAction(ref component.ToggleActionEntity, component.ToggleAction);
}
- private void OnToggleAction(EntityUid uid, HandheldLightComponent component, ToggleActionEvent args)
+ private void OnToggleAction(Entity<HandheldLightComponent> ent, ref ToggleActionEvent args)
{
if (args.Handled)
return;
- if (component.Activated)
- TurnOff(uid, component);
+ if (ent.Comp.Activated)
+ TurnOff(ent);
else
- TurnOn(args.Performer, uid, component);
+ TurnOn(args.Performer, ent);
args.Handled = true;
}
- private void OnGetState(EntityUid uid, HandheldLightComponent component, ref ComponentGetState args)
+ private void OnGetState(Entity<HandheldLightComponent> ent, ref ComponentGetState args)
{
- args.State = new HandheldLightComponent.HandheldLightComponentState(component.Activated, GetLevel(uid, component));
+ args.State = new HandheldLightComponent.HandheldLightComponentState(ent.Comp.Activated, GetLevel(ent));
}
- private void OnMapInit(EntityUid uid, HandheldLightComponent component, MapInitEvent args)
+ private void OnMapInit(Entity<HandheldLightComponent> ent, ref MapInitEvent args)
{
- _actionContainer.EnsureAction(uid, ref component.ToggleActionEntity, component.ToggleAction);
- _actions.AddAction(uid, ref component.SelfToggleActionEntity, component.ToggleAction);
+ var component = ent.Comp;
+ _actionContainer.EnsureAction(ent, ref component.ToggleActionEntity, component.ToggleAction);
+ _actions.AddAction(ent, ref component.SelfToggleActionEntity, component.ToggleAction);
}
private void OnShutdown(EntityUid uid, HandheldLightComponent component, ComponentShutdown args)
_actions.RemoveAction(uid, component.SelfToggleActionEntity);
}
- private byte? GetLevel(EntityUid uid, HandheldLightComponent component)
+ private byte? GetLevel(Entity<HandheldLightComponent> ent)
{
// Curently every single flashlight has the same number of levels for status and that's all it uses the charge for
// Thus we'll just check if the level changes.
- if (!_powerCell.TryGetBatteryFromSlot(uid, out var battery))
+ if (!_powerCell.TryGetBatteryFromSlot(ent, out var battery))
return null;
- if (MathHelper.CloseToPercent(battery.CurrentCharge, 0) || component.Wattage > battery.CurrentCharge)
+ if (MathHelper.CloseToPercent(battery.CurrentCharge, 0) || ent.Comp.Wattage > battery.CurrentCharge)
return 0;
return (byte?) ContentHelpers.RoundToNearestLevels(battery.CurrentCharge / battery.MaxCharge * 255, 255, HandheldLightComponent.StatusLevels);
}
- private void OnRemove(EntityUid uid, HandheldLightComponent component, ComponentRemove args)
+ private void OnRemove(Entity<HandheldLightComponent> ent, ref ComponentRemove args)
{
- _activeLights.Remove(component);
+ _activeLights.Remove(ent);
}
- private void OnActivate(EntityUid uid, HandheldLightComponent component, ActivateInWorldEvent args)
+ private void OnActivate(Entity<HandheldLightComponent> ent, ref ActivateInWorldEvent args)
{
- if (args.Handled || !component.ToggleOnInteract)
+ if (args.Handled || !ent.Comp.ToggleOnInteract)
return;
- if (ToggleStatus(args.User, uid, component))
+ if (ToggleStatus(args.User, ent))
args.Handled = true;
}
/// Illuminates the light if it is not active, extinguishes it if it is active.
/// </summary>
/// <returns>True if the light's status was toggled, false otherwise.</returns>
- public bool ToggleStatus(EntityUid user, EntityUid uid, HandheldLightComponent component)
+ public bool ToggleStatus(EntityUid user, Entity<HandheldLightComponent> ent)
{
- return component.Activated ? TurnOff(uid, component) : TurnOn(user, uid, component);
+ return ent.Comp.Activated ? TurnOff(ent) : TurnOn(user, ent);
}
private void OnExamine(EntityUid uid, HandheldLightComponent component, ExaminedEvent args)
public override void Update(float frameTime)
{
- var toRemove = new RemQueue<HandheldLightComponent>();
+ var toRemove = new RemQueue<Entity<HandheldLightComponent>>();
foreach (var handheld in _activeLights)
{
- var uid = handheld.Owner;
-
- if (handheld.Deleted)
+ if (handheld.Comp.Deleted)
{
toRemove.Add(handheld);
continue;
}
- if (Paused(uid)) continue;
- TryUpdate(uid, handheld, frameTime);
+ if (Paused(handheld))
+ continue;
+
+ TryUpdate(handheld, frameTime);
}
foreach (var light in toRemove)
}
}
- private void AddToggleLightVerb(EntityUid uid, HandheldLightComponent component, GetVerbsEvent<ActivationVerb> args)
+ private void AddToggleLightVerb(Entity<HandheldLightComponent> ent, ref GetVerbsEvent<ActivationVerb> args)
{
- if (!args.CanAccess || !args.CanInteract || !component.ToggleOnInteract)
+ if (!args.CanAccess || !args.CanInteract || !ent.Comp.ToggleOnInteract)
return;
+ var @event = args;
ActivationVerb verb = new()
{
Text = Loc.GetString("verb-common-toggle-light"),
Icon = new SpriteSpecifier.Texture(new ("/Textures/Interface/VerbIcons/light.svg.192dpi.png")),
- Act = component.Activated
- ? () => TurnOff(uid, component)
- : () => TurnOn(args.User, uid, component)
+ Act = ent.Comp.Activated
+ ? () => TurnOff(ent)
+ : () => TurnOn(@event.User, ent)
};
args.Verbs.Add(verb);
}
- public bool TurnOff(EntityUid uid, HandheldLightComponent component, bool makeNoise = true)
+ public bool TurnOff(Entity<HandheldLightComponent> ent, bool makeNoise = true)
{
- if (!component.Activated || !_lights.TryGetLight(uid, out var pointLightComponent))
+ if (!ent.Comp.Activated || !_lights.TryGetLight(ent, out var pointLightComponent))
{
return false;
}
- _lights.SetEnabled(uid, false, pointLightComponent);
- SetActivated(uid, false, component, makeNoise);
- component.Level = null;
- _activeLights.Remove(component);
+ _lights.SetEnabled(ent, false, pointLightComponent);
+ SetActivated(ent, false, ent, makeNoise);
+ ent.Comp.Level = null;
+ _activeLights.Remove(ent);
return true;
}
- public bool TurnOn(EntityUid user, EntityUid uid, HandheldLightComponent component)
+ public bool TurnOn(EntityUid user, Entity<HandheldLightComponent> uid)
{
+ var component = uid.Comp;
if (component.Activated || !_lights.TryGetLight(uid, out var pointLightComponent))
{
return false;
_lights.SetEnabled(uid, true, pointLightComponent);
SetActivated(uid, true, component, true);
- _activeLights.Add(component);
+ _activeLights.Add(uid);
return true;
}
- public void TryUpdate(EntityUid uid, HandheldLightComponent component, float frameTime)
+ public void TryUpdate(Entity<HandheldLightComponent> uid, float frameTime)
{
+ var component = uid.Comp;
if (!_powerCell.TryGetBatteryFromSlot(uid, out var battery) &&
!TryComp(uid, out battery))
{
- TurnOff(uid, component, false);
+ TurnOff(uid, false);
return;
}
}
if (component.Activated && !battery.TryUseCharge(component.Wattage * frameTime))
- TurnOff(uid, component, false);
+ TurnOff(uid, false);
- UpdateLevel(uid, component);
+ UpdateLevel(uid);
}
- private void UpdateLevel(EntityUid uid, HandheldLightComponent comp)
+ private void UpdateLevel(Entity<HandheldLightComponent> ent)
{
- var level = GetLevel(uid, comp);
+ var level = GetLevel(ent);
- if (level == comp.Level)
+ if (level == ent.Comp.Level)
return;
- comp.Level = level;
- Dirty(comp);
+ ent.Comp.Level = level;
+ Dirty(ent);
}
}
}
&& EntityManager.TryGetComponent(args.Used, out MatchstickComponent? matchstick)
&& matchstick.CurrentState == SmokableState.Unlit)
{
- _stickSystem.Ignite(args.Used, matchstick, args.User);
+ _stickSystem.Ignite((args.Used, matchstick), args.User);
args.Handled = true;
}
}
[Dependency] private readonly SharedPointLightSystem _lights = default!;
[Dependency] private readonly TransformSystem _transformSystem = default!;
- private HashSet<MatchstickComponent> _litMatches = new();
+ private readonly HashSet<Entity<MatchstickComponent>> _litMatches = new();
public override void Initialize()
{
SubscribeLocalEvent<MatchstickComponent, ComponentShutdown>(OnShutdown);
}
- private void OnShutdown(EntityUid uid, MatchstickComponent component, ComponentShutdown args)
+ private void OnShutdown(Entity<MatchstickComponent> ent, ref ComponentShutdown args)
{
- _litMatches.Remove(component);
+ _litMatches.Remove(ent);
}
public override void Update(float frameTime)
{
base.Update(frameTime);
+
foreach (var match in _litMatches)
{
- if (match.CurrentState != SmokableState.Lit || Paused(match.Owner) || match.Deleted)
+ if (match.Comp.CurrentState != SmokableState.Lit || Paused(match) || match.Comp.Deleted)
continue;
- var xform = Transform(match.Owner);
+ var xform = Transform(match);
if (xform.GridUid is not {} gridUid)
return;
- var position = _transformSystem.GetGridOrMapTilePosition(match.Owner, xform);
+ var position = _transformSystem.GetGridOrMapTilePosition(match, xform);
- _atmosphereSystem.HotspotExpose(gridUid, position, 400, 50, match.Owner, true);
+ _atmosphereSystem.HotspotExpose(gridUid, position, 400, 50, match, true);
}
}
- private void OnInteractUsing(EntityUid uid, MatchstickComponent component, InteractUsingEvent args)
+ private void OnInteractUsing(Entity<MatchstickComponent> ent, ref InteractUsingEvent args)
{
- if (args.Handled || component.CurrentState != SmokableState.Unlit)
+ if (args.Handled || ent.Comp.CurrentState != SmokableState.Unlit)
return;
var isHotEvent = new IsHotEvent();
- RaiseLocalEvent(args.Used, isHotEvent, false);
+ RaiseLocalEvent(args.Used, isHotEvent);
if (!isHotEvent.IsHot)
return;
- Ignite(uid, component, args.User);
+ Ignite(ent, args.User);
args.Handled = true;
}
args.IsHot = component.CurrentState == SmokableState.Lit;
}
- public void Ignite(EntityUid uid, MatchstickComponent component, EntityUid user)
+ public void Ignite(Entity<MatchstickComponent> matchstick, EntityUid user)
{
+ var component = matchstick.Comp;
+
// Play Sound
- SoundSystem.Play(component.IgniteSound.GetSound(), Filter.Pvs(component.Owner),
- component.Owner, AudioHelpers.WithVariation(0.125f).WithVolume(-0.125f));
+ SoundSystem.Play(component.IgniteSound.GetSound(), Filter.Pvs(matchstick),
+ matchstick, AudioHelpers.WithVariation(0.125f).WithVolume(-0.125f));
// Change state
- SetState(uid, component, SmokableState.Lit);
- _litMatches.Add(component);
- component.Owner.SpawnTimer(component.Duration * 1000, delegate
+ SetState(matchstick, component, SmokableState.Lit);
+ _litMatches.Add(matchstick);
+ matchstick.Owner.SpawnTimer(component.Duration * 1000, delegate
{
- SetState(uid, component, SmokableState.Burnt);
- _litMatches.Remove(component);
+ SetState(matchstick, component, SmokableState.Burnt);
+ _litMatches.Remove(matchstick);
});
}
using Content.Server.Administration.Logs;
using Content.Server.Clothing.Components;
+using Content.Server.DeviceLinking.Events;
+using Content.Server.DeviceLinking.Systems;
using Content.Server.DeviceNetwork;
using Content.Server.DeviceNetwork.Systems;
+using Content.Server.Emp;
using Content.Server.Ghost;
using Content.Server.Light.Components;
using Content.Server.Power.Components;
-using Content.Server.Temperature.Components;
using Content.Shared.Audio;
using Content.Shared.Damage;
using Content.Shared.Database;
+using Content.Shared.DoAfter;
using Content.Shared.Hands.EntitySystems;
using Content.Shared.Interaction;
+using Content.Shared.Inventory;
using Content.Shared.Light;
using Content.Shared.Light.Components;
using Content.Shared.Popups;
using Robust.Shared.Containers;
using Robust.Shared.Player;
using Robust.Shared.Timing;
-using Content.Shared.DoAfter;
-using Content.Server.Emp;
-using Content.Server.DeviceLinking.Events;
-using Content.Server.DeviceLinking.Systems;
-using Content.Shared.Inventory;
namespace Content.Server.Light.EntitySystems
{
light.LastGhostBlink = time;
ToggleBlinkingLight(uid, light, true);
- light.Owner.SpawnTimer(light.GhostBlinkingTime, () =>
+ uid.SpawnTimer(light.GhostBlinkingTime, () =>
{
ToggleBlinkingLight(uid, light, false);
});
using Content.Shared.Magic.Events;
using Content.Shared.Maps;
using Content.Shared.Physics;
-using Robust.Shared.Spawners;
using Content.Shared.Storage;
using Robust.Server.GameObjects;
using Robust.Shared.Audio;
using Robust.Shared.Map;
using Robust.Shared.Random;
using Robust.Shared.Serialization.Manager;
+using Robust.Shared.Spawners;
namespace Content.Server.Magic;
_boltsSystem.SetBoltsDown(entity, bolts, false);
if (TryComp<DoorComponent>(entity, out var doorComp) && doorComp.State is not DoorState.Open)
- _doorSystem.StartOpening(doorComp.Owner);
+ _doorSystem.StartOpening(entity);
}
}
+using System.Linq;
+using Content.Server.Administration.Logs;
+using Content.Server.CartridgeLoader;
+using Content.Server.CartridgeLoader.Cartridges;
+using Content.Server.GameTicking;
using Content.Server.MassMedia.Components;
using Content.Server.PDA.Ringer;
+using Content.Server.Popups;
+using Content.Server.StationRecords.Systems;
using Content.Shared.Access.Components;
using Content.Shared.Access.Systems;
+using Content.Shared.CartridgeLoader;
+using Content.Shared.CartridgeLoader.Cartridges;
+using Content.Shared.Database;
using Content.Shared.GameTicking;
using Content.Shared.MassMedia.Components;
using Content.Shared.MassMedia.Systems;
using Content.Shared.PDA;
using Robust.Server.GameObjects;
-using System.Linq;
-using Content.Server.Administration.Logs;
-using Content.Server.CartridgeLoader.Cartridges;
-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;
+using Robust.Shared.Timing;
namespace Content.Server.MassMedia.Systems;
while (query.MoveNext(out var owner, out var comp))
{
if (EntityManager.TryGetComponent<NewsReadCartridgeComponent>(comp.ActiveProgram, out var cartridge))
- UpdateReadUi(cartridge.Owner, comp.Owner, cartridge);
+ UpdateReadUi(comp.ActiveProgram.Value, owner, cartridge);
}
}
base.Update(frameTime);
var query = EntityQueryEnumerator<NewsWriteComponent>();
- while (query.MoveNext(out var comp))
+ while (query.MoveNext(out var uid, out var comp))
{
if (comp.ShareAvalible || _timing.CurTime < comp.NextShare)
continue;
comp.ShareAvalible = true;
- UpdateWriteUi(comp.Owner, comp);
+ UpdateWriteUi(uid, comp);
}
}
}
using Content.Server.Mech.Components;
using Content.Shared.Atmos;
using Content.Shared.Mech.Components;
-using Robust.Shared.GameObjects;
namespace Content.Server.Mech.Systems;
var coordinates = Transform(uid).MapPosition;
GasMixture? destination = null;
- if (_map.TryFindGridAt(coordinates, out _, out var grid))
+ if (_map.TryFindGridAt(coordinates, out var gridId, out var grid))
{
- var tile = grid.GetTileRef(coordinates);
+ var tile = _mapSystem.GetTileRef(gridId, grid, coordinates);
destination = _atmosphere.GetTileMixture(tile.GridUid, null, tile.GridIndices, true);
}
[Dependency] private readonly ContainerSystem _container = default!;
[Dependency] private readonly DamageableSystem _damageable = default!;
[Dependency] private readonly IMapManager _map = default!;
+ [Dependency] private readonly MapSystem _mapSystem = default!;
[Dependency] private readonly SharedDoAfterSystem _doAfter = default!;
[Dependency] private readonly SharedPopupSystem _popup = default!;
[Dependency] private readonly UserInterfaceSystem _ui = default!;
{
base.Update(frameTime);
- foreach (var (_, reclaimer) in EntityQuery<ActiveBiomassReclaimerComponent, BiomassReclaimerComponent>())
+ var query = EntityQueryEnumerator<ActiveBiomassReclaimerComponent, BiomassReclaimerComponent>();
+ while (query.MoveNext(out var uid, out var _, out var reclaimer))
{
reclaimer.ProcessingTimer -= frameTime;
reclaimer.RandomMessTimer -= frameTime;
{
Solution blood = new();
blood.AddReagent(reclaimer.BloodReagent, 50);
- _puddleSystem.TrySpillAt(reclaimer.Owner, blood, out _);
+ _puddleSystem.TrySpillAt(uid, blood, out _);
}
if (_robustRandom.Prob(0.03f) && reclaimer.SpawnedEntities.Count > 0)
{
- var thrown = Spawn(_robustRandom.Pick(reclaimer.SpawnedEntities).PrototypeId, Transform(reclaimer.Owner).Coordinates);
+ var thrown = Spawn(_robustRandom.Pick(reclaimer.SpawnedEntities).PrototypeId, Transform(uid).Coordinates);
var direction = new Vector2(_robustRandom.Next(-30, 30), _robustRandom.Next(-30, 30));
_throwing.TryThrow(thrown, direction, _robustRandom.Next(1, 10));
}
continue;
}
- _material.SpawnMultipleFromMaterial(reclaimer.CurrentExpectedYield, "Biomass", Transform(reclaimer.Owner).Coordinates);
+ _material.SpawnMultipleFromMaterial(reclaimer.CurrentExpectedYield, "Biomass", Transform(uid).Coordinates);
reclaimer.BloodReagent = null;
reclaimer.SpawnedEntities.Clear();
- RemCompDeferred<ActiveBiomassReclaimerComponent>(reclaimer.Owner);
+ RemCompDeferred<ActiveBiomassReclaimerComponent>(uid);
}
}
public override void Initialize()
SubscribeLocalEvent<BiomassReclaimerComponent, ReclaimerDoAfterEvent>(OnDoAfter);
}
- private void OnSuicide(EntityUid uid, BiomassReclaimerComponent component, SuicideEvent args)
+ private void OnSuicide(Entity<BiomassReclaimerComponent> ent, ref SuicideEvent args)
{
if (args.Handled)
return;
- if (HasComp<ActiveBiomassReclaimerComponent>(uid))
+ if (HasComp<ActiveBiomassReclaimerComponent>(ent))
return;
- if (TryComp<ApcPowerReceiverComponent>(uid, out var power) && !power.Powered)
+ if (TryComp<ApcPowerReceiverComponent>(ent, out var power) && !power.Powered)
return;
- _popup.PopupEntity(Loc.GetString("biomass-reclaimer-suicide-others", ("victim", args.Victim)), uid, PopupType.LargeCaution);
- StartProcessing(args.Victim, component);
+ _popup.PopupEntity(Loc.GetString("biomass-reclaimer-suicide-others", ("victim", args.Victim)), ent, PopupType.LargeCaution);
+ StartProcessing(args.Victim, ent);
args.SetHandled(SuicideKind.Blunt);
}
EnsureComp<ActiveBiomassReclaimerComponent>(uid);
}
else
- RemComp<ActiveBiomassReclaimerComponent>(component.Owner);
+ RemComp<ActiveBiomassReclaimerComponent>(uid);
}
private void OnUnanchorAttempt(EntityUid uid, ActiveBiomassReclaimerComponent component, UnanchorAttemptEvent args)
{
args.Cancel();
}
- private void OnAfterInteractUsing(EntityUid uid, BiomassReclaimerComponent component, AfterInteractUsingEvent args)
+ private void OnAfterInteractUsing(Entity<BiomassReclaimerComponent> reclaimer, ref AfterInteractUsingEvent args)
{
if (!args.CanReach || args.Target == null)
return;
- if (!HasComp<MobStateComponent>(args.Used) || !CanGib(uid, args.Used, component))
+ if (!HasComp<MobStateComponent>(args.Used) || !CanGib(reclaimer, args.Used))
return;
- _doAfterSystem.TryStartDoAfter(new DoAfterArgs(EntityManager, args.User, 7f, new ReclaimerDoAfterEvent(), uid, target: args.Target, used: args.Used)
+ _doAfterSystem.TryStartDoAfter(new DoAfterArgs(EntityManager, args.User, 7f, new ReclaimerDoAfterEvent(), reclaimer, target: args.Target, used: args.Used)
{
BreakOnTargetMove = true,
BreakOnUserMove = true,
});
}
- private void OnClimbedOn(EntityUid uid, BiomassReclaimerComponent component, ref ClimbedOnEvent args)
+ private void OnClimbedOn(Entity<BiomassReclaimerComponent> reclaimer, ref ClimbedOnEvent args)
{
- if (!CanGib(uid, args.Climber, component))
+ if (!CanGib(reclaimer, args.Climber))
{
var direction = new Vector2(_robustRandom.Next(-2, 2), _robustRandom.Next(-2, 2));
_throwing.TryThrow(args.Climber, direction, 0.5f);
return;
}
- _adminLogger.Add(LogType.Action, LogImpact.Extreme, $"{ToPrettyString(args.Instigator):player} used a biomass reclaimer to gib {ToPrettyString(args.Climber):target} in {ToPrettyString(uid):reclaimer}");
+ _adminLogger.Add(LogType.Action, LogImpact.Extreme, $"{ToPrettyString(args.Instigator):player} used a biomass reclaimer to gib {ToPrettyString(args.Climber):target} in {ToPrettyString(reclaimer):reclaimer}");
- StartProcessing(args.Climber, component);
+ StartProcessing(args.Climber, reclaimer);
}
private void OnRefreshParts(EntityUid uid, BiomassReclaimerComponent component, RefreshPartsEvent args)
args.AddPercentageUpgrade("biomass-reclaimer-component-upgrade-biomass-yield", component.YieldPerUnitMass / component.BaseYieldPerUnitMass);
}
- private void OnDoAfter(EntityUid uid, BiomassReclaimerComponent component, DoAfterEvent args)
+ private void OnDoAfter(Entity<BiomassReclaimerComponent> reclaimer, ref ReclaimerDoAfterEvent args)
{
if (args.Handled || args.Cancelled || args.Args.Target == null || HasComp<BiomassReclaimerComponent>(args.Args.Target.Value))
return;
- _adminLogger.Add(LogType.Action, LogImpact.Extreme, $"{ToPrettyString(args.Args.User):player} used a biomass reclaimer to gib {ToPrettyString(args.Args.Target.Value):target} in {ToPrettyString(uid):reclaimer}");
- StartProcessing(args.Args.Target.Value, component);
+ _adminLogger.Add(LogType.Action, LogImpact.Extreme, $"{ToPrettyString(args.Args.User):player} used a biomass reclaimer to gib {ToPrettyString(args.Args.Target.Value):target} in {ToPrettyString(reclaimer):reclaimer}");
+ StartProcessing(args.Args.Target.Value, reclaimer);
args.Handled = true;
}
- private void StartProcessing(EntityUid toProcess, BiomassReclaimerComponent component, PhysicsComponent? physics = null)
+ private void StartProcessing(EntityUid toProcess, Entity<BiomassReclaimerComponent> ent, PhysicsComponent? physics = null)
{
if (!Resolve(toProcess, ref physics))
return;
- AddComp<ActiveBiomassReclaimerComponent>(component.Owner);
+ var component = ent.Comp;
+ AddComp<ActiveBiomassReclaimerComponent>(ent);
if (TryComp<BloodstreamComponent>(toProcess, out var stream))
{
QueueDel(toProcess);
}
- private bool CanGib(EntityUid uid, EntityUid dragged, BiomassReclaimerComponent component)
+ private bool CanGib(Entity<BiomassReclaimerComponent> reclaimer, EntityUid dragged)
{
- if (HasComp<ActiveBiomassReclaimerComponent>(uid))
+ if (HasComp<ActiveBiomassReclaimerComponent>(reclaimer))
return false;
if (!HasComp<MobStateComponent>(dragged))
return false;
- if (!Transform(uid).Anchored)
+ if (!Transform(reclaimer).Anchored)
return false;
- if (TryComp<ApcPowerReceiverComponent>(uid, out var power) && !power.Powered)
+ if (TryComp<ApcPowerReceiverComponent>(reclaimer, out var power) && !power.Powered)
return false;
- if (component.SafetyEnabled && !_mobState.IsDead(dragged))
+ if (reclaimer.Comp.SafetyEnabled && !_mobState.IsDead(dragged))
return false;
// Reject souled bodies in easy mode.
using Content.Server.NodeContainer.NodeGroups;
using Content.Server.NodeContainer.Nodes;
using Content.Server.Power.Components;
+using Content.Server.Temperature.Components;
using Content.Server.UserInterface;
using Content.Shared.Chemistry;
using Content.Shared.Chemistry.Components;
using Content.Shared.Chemistry.Components.SolutionManager;
using Content.Shared.Chemistry.EntitySystems;
using Content.Shared.Chemistry.Reagent;
+using Content.Shared.Climbing.Systems;
using Content.Shared.Containers.ItemSlots;
using Content.Shared.Database;
using Content.Shared.DoAfter;
using Content.Shared.Verbs;
using Robust.Server.GameObjects;
using Robust.Shared.Timing;
-using Content.Server.Temperature.Components;
-using Content.Shared.Climbing.Systems;
namespace Content.Server.Medical;
var itemSlotsQuery = GetEntityQuery<ItemSlotsComponent>();
var fitsInDispenserQuery = GetEntityQuery<FitsInDispenserComponent>();
var solutionContainerManagerQuery = GetEntityQuery<SolutionContainerManagerComponent>();
- foreach (var (_, cryoPod) in EntityQuery<ActiveCryoPodComponent, CryoPodComponent>())
+ var query = EntityQueryEnumerator<ActiveCryoPodComponent, CryoPodComponent>();
+
+ while (query.MoveNext(out var uid, out _, out var cryoPod))
{
- metaDataQuery.TryGetComponent(cryoPod.Owner, out var metaDataComponent);
- if (curTime < cryoPod.NextInjectionTime + _metaDataSystem.GetPauseTime(cryoPod.Owner, metaDataComponent))
+ metaDataQuery.TryGetComponent(uid, out var metaDataComponent);
+ if (curTime < cryoPod.NextInjectionTime + _metaDataSystem.GetPauseTime(uid, metaDataComponent))
continue;
cryoPod.NextInjectionTime = curTime + TimeSpan.FromSeconds(cryoPod.BeakerTransferTime);
- if (!itemSlotsQuery.TryGetComponent(cryoPod.Owner, out var itemSlotsComponent))
+ if (!itemSlotsQuery.TryGetComponent(uid, out var itemSlotsComponent))
{
continue;
}
- var container = _itemSlotsSystem.GetItemOrNull(cryoPod.Owner, cryoPod.SolutionContainerName, itemSlotsComponent);
+ var container = _itemSlotsSystem.GetItemOrNull(uid, cryoPod.SolutionContainerName, itemSlotsComponent);
var patient = cryoPod.BodyContainer.ContainedEntity;
if (container != null
&& container.Value.Valid
var userJob = Loc.GetString("suit-sensor-component-unknown-job");
if (_idCardSystem.TryFindIdCard(sensor.User.Value, out var card))
{
- if (card.FullName != null)
- userName = card.FullName;
- if (card.JobTitle != null)
- userJob = card.JobTitle;
+ if (card.Comp.FullName != null)
+ userName = card.Comp.FullName;
+ if (card.Comp.JobTitle != null)
+ userJob = card.Comp.JobTitle;
}
// get health mob state
{
if (idCardSystem.TryFindIdCard(entityUid.Value, out var idCard))
{
- idCardSystem.TryChangeFullName(idCard.Owner, name, idCard);
+ idCardSystem.TryChangeFullName(idCard, name, idCard);
// Records
// This is done here because ID cards are linked to station records
if (_entManager.TrySystem<StationRecordsSystem>(out var recordsSystem)
- && _entManager.TryGetComponent(idCard.Owner, out StationRecordKeyStorageComponent? keyStorage)
+ && _entManager.TryGetComponent(idCard, out StationRecordKeyStorageComponent? keyStorage)
&& keyStorage.Key != null)
{
var origin = keyStorage.Key.Value.OriginStation;
{
base.Update(frameTime);
- foreach (var (act, crem) in EntityQuery<ActiveCrematoriumComponent, CrematoriumComponent>())
+ var query = EntityQueryEnumerator<ActiveCrematoriumComponent, CrematoriumComponent>();
+ while (query.MoveNext(out var uid, out var act, out var crem))
{
act.Accumulator += frameTime;
if (act.Accumulator >= crem.CookTime)
- FinishCooking(act.Owner, crem);
+ FinishCooking(uid, crem);
}
}
}
-using Content.Server.Morgue.Components;
using Content.Server.Storage.Components;
using Content.Shared.Body.Components;
using Content.Shared.Examine;
{
base.Update(frameTime);
- foreach (var (comp, storage, appearance) in EntityQuery<MorgueComponent, EntityStorageComponent, AppearanceComponent>())
+ var query = EntityQueryEnumerator<MorgueComponent, EntityStorageComponent, AppearanceComponent>();
+ while (query.MoveNext(out var uid, out var comp, out var storage, out var appearance))
{
comp.AccumulatedFrameTime += frameTime;
- CheckContents(comp.Owner, comp, storage);
+ CheckContents(uid, comp, storage);
if (comp.AccumulatedFrameTime < comp.BeepTime)
continue;
comp.AccumulatedFrameTime -= comp.BeepTime;
- if (comp.DoSoulBeep && _appearance.TryGetData<MorgueContents>(appearance.Owner, MorgueVisuals.Contents, out var contents, appearance) && contents == MorgueContents.HasSoul)
+ if (comp.DoSoulBeep && _appearance.TryGetData<MorgueContents>(uid, MorgueVisuals.Contents, out var contents, appearance) && contents == MorgueContents.HasSoul)
{
- _audio.PlayPvs(comp.OccupantHasSoulAlarmSound, comp.Owner);
+ _audio.PlayPvs(comp.OccupantHasSoulAlarmSound, uid);
}
}
}
var toDisable = new ValueList<(EntityUid Uid, JetpackComponent Component)>();
var query = EntityQueryEnumerator<ActiveJetpackComponent, JetpackComponent, GasTankComponent>();
- while (query.MoveNext(out var uid, out var active, out var comp, out var gasTank))
+ while (query.MoveNext(out var uid, out var active, out var comp, out var gasTankComp))
{
if (_timing.CurTime < active.TargetTime)
continue;
+ var gasTank = (uid, gasTankComp);
active.TargetTime = _timing.CurTime + TimeSpan.FromSeconds(active.EffectCooldown);
var usedAir = _gasTank.RemoveAir(gasTank, comp.MoleUsage);
using System.Diagnostics.CodeAnalysis;
-using System.Linq;
using System.Numerics;
using System.Threading;
using System.Threading.Tasks;
using Content.Server.Destructible;
using Content.Shared.Access.Components;
-using Content.Shared.Climbing;
+using Content.Shared.Climbing.Components;
using Content.Shared.Doors.Components;
using Content.Shared.NPC;
using Content.Shared.Physics;
-using Microsoft.Extensions.ObjectPool;
using Robust.Shared.Collections;
using Robust.Shared.Map;
using Robust.Shared.Map.Components;
using Robust.Shared.Physics;
-using Robust.Shared.Physics.Components;
using Robust.Shared.Physics.Events;
using Robust.Shared.Timing;
using Robust.Shared.Utility;
-using ClimbableComponent = Content.Shared.Climbing.Components.ClimbableComponent;
namespace Content.Server.NPC.Pathfinding;
while (query.MoveNext(out var uid, out var comp))
{
+ var pathfinding = new Entity<GridPathfindingComponent>(uid, comp);
// TODO: Dump all this shit and just do it live it's probably fast enough.
if (comp.DirtyChunks.Count == 0 ||
curTime < comp.NextUpdate ||
foreach (var origin in comp.DirtyChunks)
{
- var chunk = GetChunk(origin, uid, comp);
+ var chunk = GetChunk(origin, uid, pathfinding);
dirt[idx] = chunk;
idx++;
}
var climbableQuery = GetEntityQuery<ClimbableComponent>();
var fixturesQuery = GetEntityQuery<FixturesComponent>();
var xformQuery = GetEntityQuery<TransformComponent>();
- BuildBreadcrumbs(dirt[i], mapGridComp, accessQuery, destructibleQuery, doorQuery, climbableQuery,
+ BuildBreadcrumbs(dirt[i], (uid, mapGridComp), accessQuery, destructibleQuery, doorQuery, climbableQuery,
fixturesQuery, xformQuery);
});
if (index != it1)
return;
- BuildNavmesh(chunk, comp);
+ BuildNavmesh(chunk, pathfinding);
#if DEBUG
Interlocked.Increment(ref updateCount);
#endif
private void OnCollisionChange(ref CollisionChangeEvent ev)
{
- var xform = Transform(ev.Body.Owner);
+ var xform = Transform(ev.BodyUid);
if (xform.GridUid == null)
return;
// This will also rebuild on door open / closes which I think is good?
- var aabb = _lookup.GetAABBNoContainer(ev.Body.Owner, xform.Coordinates.Position, xform.LocalRotation);
+ var aabb = _lookup.GetAABBNoContainer(ev.BodyUid, xform.Coordinates.Position, xform.LocalRotation);
DirtyChunkArea(xform.GridUid.Value, aabb);
}
private void OnCollisionLayerChange(ref CollisionLayerChangeEvent ev)
{
- var xform = Transform(ev.Body.Owner);
+ var xform = Transform(ev.Body);
if (xform.GridUid == null)
return;
- var aabb = _lookup.GetAABBNoContainer(ev.Body.Owner, xform.Coordinates.Position, xform.LocalRotation);
+ var aabb = _lookup.GetAABBNoContainer(ev.Body, xform.Coordinates.Position, xform.LocalRotation);
DirtyChunkArea(xform.GridUid.Value, aabb);
}
}
private void BuildBreadcrumbs(GridPathfindingChunk chunk,
- MapGridComponent grid,
+ Entity<MapGridComponent> grid,
EntityQuery<AccessReaderComponent> accessQuery,
EntityQuery<DestructibleComponent> destructibleQuery,
EntityQuery<DoorComponent> doorQuery,
var tilePos = new Vector2i(x, y) + gridOrigin;
tilePolys.Clear();
- var tile = grid.GetTileRef(tilePos);
+ var tile = grid.Comp.GetTileRef(tilePos);
var flags = tile.Tile.IsEmpty ? PathfindingBreadcrumbFlag.Space : PathfindingBreadcrumbFlag.None;
// var isBorder = x < 0 || y < 0 || x == ChunkSize - 1 || y == ChunkSize - 1;
var xform = xformQuery.GetComponent(ent);
if (xform.ParentUid != grid.Owner ||
- grid.LocalToTile(xform.Coordinates) != tilePos)
+ grid.Comp.LocalToTile(xform.Coordinates) != tilePos)
{
continue;
}
var polyData = points[x * SubStep + poly.Left, y * SubStep + poly.Bottom].Data;
var neighbors = new HashSet<PathPoly>();
- tilePoly.Add(new PathPoly(grid.Owner, chunk.Origin, GetIndex(x, y), box, polyData, neighbors));
+ tilePoly.Add(new PathPoly(grid, chunk.Origin, GetIndex(x, y), box, polyData, neighbors));
}
}
}
// Log.Debug($"Built breadcrumbs in {sw.Elapsed.TotalMilliseconds}ms");
- SendBreadcrumbs(chunk, grid.Owner);
+ SendBreadcrumbs(chunk, grid);
}
/// <summary>
}
}
- private void BuildNavmesh(GridPathfindingChunk chunk, GridPathfindingComponent component)
+ private void BuildNavmesh(GridPathfindingChunk chunk, Entity<GridPathfindingComponent> pathfinding)
{
var sw = new Stopwatch();
sw.Start();
var chunkPolys = chunk.Polygons;
+ var component = pathfinding.Comp;
component.Chunks.TryGetValue(chunk.Origin + new Vector2i(-1, 0), out var leftChunk);
component.Chunks.TryGetValue(chunk.Origin + new Vector2i(0, -1), out var bottomChunk);
component.Chunks.TryGetValue(chunk.Origin + new Vector2i(1, 0), out var rightChunk);
}
// Log.Debug($"Built navmesh in {sw.Elapsed.TotalMilliseconds}ms");
- SendPolys(chunk, component.Owner, chunkPolys);
+ SendPolys(chunk, pathfinding, chunkPolys);
}
private void AddNeighbors(PathPoly polyA, PathPoly polyB)
using System.Threading.Tasks;
using Content.Server.Administration.Managers;
using Content.Server.Destructible;
-using Content.Server.NPC.HTN;
using Content.Server.NPC.Systems;
using Content.Shared.Administration;
using Content.Shared.NPC;
{
var msg = new PathBreadcrumbsMessage();
- foreach (var comp in EntityQuery<GridPathfindingComponent>(true))
+ var query = AllEntityQuery<GridPathfindingComponent>();
+ while (query.MoveNext(out var uid, out var comp))
{
- var netGrid = GetNetEntity(comp.Owner);
+ var netGrid = GetNetEntity(uid);
msg.Breadcrumbs.Add(netGrid, new Dictionary<Vector2i, List<PathfindingBreadcrumb>>(comp.Chunks.Count));
{
var msg = new PathPolysMessage();
- foreach (var comp in EntityQuery<GridPathfindingComponent>(true))
+ var query = AllEntityQuery<GridPathfindingComponent>();
+ while (query.MoveNext(out var uid, out var comp))
{
- var netGrid = GetNetEntity(comp.Owner);
+ var netGrid = GetNetEntity(uid);
msg.Polys.Add(netGrid, new Dictionary<Vector2i, Dictionary<Vector2i, List<DebugPathPoly>>>(comp.Chunks.Count));
/// <param name="frameTime"></param>
private void UpdateRecentlyInjected(float frameTime)
{
- foreach (var entity in EntityQuery<NPCRecentlyInjectedComponent>())
+ var query = EntityQueryEnumerator<NPCRecentlyInjectedComponent>();
+ while (query.MoveNext(out var uid, out var entity))
{
entity.Accumulator += frameTime;
if (entity.Accumulator < entity.RemoveTime.TotalSeconds)
continue;
entity.Accumulator = 0;
- RemComp<NPCRecentlyInjectedComponent>(entity.Owner);
+ RemComp<NPCRecentlyInjectedComponent>(uid);
}
}
}
var compZero = comps[0];
comps.RemoveAt(0);
- foreach (var comp in _lookup.GetComponentsInRange(compZero.Component.GetType(), mapPos, vision))
+ foreach (var comp in _lookup.GetEntitiesInRange(compZero.Component.GetType(), mapPos, vision))
{
var ent = comp.Owner;
-using Content.Server.NPC.Components;
-using Robust.Shared.Prototypes;
using System.Linq;
+using Content.Server.NPC.Components;
using JetBrains.Annotations;
+using Robust.Shared.Prototypes;
namespace Content.Server.NPC.Systems;
if (!xformQuery.TryGetComponent(entity, out var entityXform))
yield break;
- foreach (var comp in _lookup.GetComponentsInRange<NpcFactionMemberComponent>(entityXform.MapPosition, range))
+ foreach (var ent in _lookup.GetEntitiesInRange<NpcFactionMemberComponent>(entityXform.MapPosition, range))
{
- if (comp.Owner == entity)
+ if (ent.Owner == entity)
continue;
- if (!factions.Overlaps(comp.Factions))
+ if (!factions.Overlaps(ent.Comp.Factions))
continue;
- yield return comp.Owner;
+ yield return ent.Owner;
}
}
-using Content.Server.NodeContainer.Nodes;
+using System.Diagnostics.CodeAnalysis;
using Content.Server.NodeContainer.NodeGroups;
+using Content.Server.NodeContainer.Nodes;
using Content.Shared.Examine;
using JetBrains.Annotations;
-using System.Diagnostics.CodeAnalysis;
namespace Content.Server.NodeContainer.EntitySystems
{
foreach (var (key, node) in component.Nodes)
{
node.Name = key;
- node.Initialize(component.Owner, EntityManager);
+ node.Initialize(uid, EntityManager);
}
}
-using System.Linq;
-using Content.Server.Administration;
+using Content.Server.Administration;
using Content.Server.Station.Components;
-using Content.Server.Station.Systems;
using Content.Shared.Administration;
using JetBrains.Annotations;
using Robust.Shared.Console;
return CompletionResult.Empty;
}
- var stations = _entityManager
- .EntityQuery<StationDataComponent>()
- .Select(stationData =>
- {
- var meta = _entityManager.GetComponent<MetaDataComponent>(stationData.Owner);
+ var stations = new List<CompletionOption>();
+ var query = _entityManager.EntityQueryEnumerator<StationDataComponent>();
+ while (query.MoveNext(out var uid, out var stationData))
+ {
+ var meta = _entityManager.GetComponent<MetaDataComponent>(uid);
- return new CompletionOption(stationData.Owner.ToString(), meta.EntityName);
- });
+ stations.Add(new CompletionOption(uid.ToString(), meta.EntityName));
+ }
return CompletionResult.FromHintOptions(stations, null);
}
using System.Diagnostics.CodeAnalysis;
-using System.Linq;
using Content.Server.Chat.Systems;
using Content.Server.Fax;
using Content.Server.Paper;
var codesMessage = new FormattedMessage();
// Find the first nuke that matches the passed location.
- var query = EntityQuery<NukeComponent>().ToList();
- _random.Shuffle(query);
- foreach (var nuke in query)
+ var nukes = new List<Entity<NukeComponent>>();
+ var query = EntityQueryEnumerator<NukeComponent>();
+ while (query.MoveNext(out var nukeUid, out var nuke))
+ {
+ nukes.Add((nukeUid, nuke));
+ }
+
+ _random.Shuffle(nukes);
+
+ foreach (var (nukeUid, nuke) in nukes)
{
if (!onlyCurrentStation &&
(owningStation == null &&
}
codesMessage.PushNewline();
- codesMessage.AddMarkup(Loc.GetString("nuke-codes-list", ("name", MetaData(nuke.Owner).EntityName), ("code", nuke.Code)));
+ codesMessage.AddMarkup(Loc.GetString("nuke-codes-list", ("name", MetaData(nukeUid).EntityName), ("code", nuke.Code)));
break;
}
using Content.Server.Administration.Logs;
using Content.Server.Interaction.Components;
-using Content.Server.Nutrition.Components;
using Content.Server.Popups;
using Content.Shared.Database;
using Content.Shared.IdentityManagement;
var xform = Transform(uid);
- var partners = _entityLookup.GetComponentsInRange<ReproductivePartnerComponent>(xform.Coordinates, component.BreedRange);
+ var partners = new HashSet<Entity<ReproductivePartnerComponent>>();
+ _entityLookup.GetEntitiesInRange(xform.Coordinates, component.BreedRange, partners);
if (partners.Count >= component.Capacity)
return false;
-using Content.Server.Chemistry.EntitySystems;
-using Content.Server.Nutrition;
using Content.Server.Nutrition.Components;
using Content.Shared.Chemistry.Components;
using Content.Shared.Chemistry.Components.SolutionManager;
using Content.Shared.FixedPoint;
using Content.Shared.Hands.EntitySystems;
using Content.Shared.Interaction;
-using Content.Shared.Item;
using Robust.Shared.Audio;
using Robust.Shared.Containers;
using Robust.Shared.Player;
else
{
var xform = Transform(sliceUid);
- _containerSystem.AttachParentToContainerOrGrid(xform);
+ _containerSystem.AttachParentToContainerOrGrid((sliceUid, xform));
xform.LocalRotation = 0;
}
else
{
var xform = Transform(sliceUid);
- _containerSystem.AttachParentToContainerOrGrid(xform);
+ _containerSystem.AttachParentToContainerOrGrid((sliceUid, xform));
xform.LocalRotation = 0;
}
if (_componentFactory.GetComponent(registration.Type) is not Component component)
continue;
- component.Owner = uid;
-
var temp = (object) component;
_serializationManager.CopyTo(data.Component, ref temp);
EntityManager.AddComponent(uid, (Component)temp!);
+using Content.Server.Physics.Components;
+using Content.Shared.Follower.Components;
+using Content.Shared.Throwing;
using Robust.Server.GameObjects;
using Robust.Shared.Physics.Components;
using Robust.Shared.Physics.Controllers;
using Robust.Shared.Random;
using Robust.Shared.Timing;
-using Content.Server.Physics.Components;
-using Content.Shared.Follower.Components;
-using Content.Shared.Throwing;
-
namespace Content.Server.Physics.Controllers;
/// <summary>
{
base.UpdateBeforeSolve(prediction, frameTime);
- foreach(var (randomWalk, physics) in EntityManager.EntityQuery<RandomWalkComponent, PhysicsComponent>())
+ var query = EntityQueryEnumerator<RandomWalkComponent, PhysicsComponent>();
+ while (query.MoveNext(out var uid, out var randomWalk, out var physics))
{
- if (EntityManager.HasComponent<ActorComponent>(randomWalk.Owner)
- || EntityManager.HasComponent<ThrownItemComponent>(randomWalk.Owner)
- || EntityManager.HasComponent<FollowerComponent>(randomWalk.Owner))
+ if (EntityManager.HasComponent<ActorComponent>(uid)
+ || EntityManager.HasComponent<ThrownItemComponent>(uid)
+ || EntityManager.HasComponent<FollowerComponent>(uid))
continue;
var curTime = _timing.CurTime;
if (randomWalk.NextStepTime <= curTime)
- Update(randomWalk.Owner, randomWalk, physics);
+ Update(uid, randomWalk, physics);
}
}
var curTime = _timing.CurTime;
randomWalk.NextStepTime = curTime + TimeSpan.FromSeconds(_random.NextDouble(randomWalk.MinStepCooldown.TotalSeconds, randomWalk.MaxStepCooldown.TotalSeconds));
- if(!Resolve(randomWalk.Owner, ref physics))
+ if(!Resolve(uid, ref physics))
return;
var pushAngle = _random.NextAngle();
var xform = xformQuery.GetComponent(uid);
var compType = EntityManager.ComponentFactory.GetRegistration(component.Component).Type;
float? closestDistance = null;
- foreach (var comp in _entityLookup.GetComponentsInRange(compType, xform.MapPosition, component.MaximumDistance))
+ foreach (var ent in _entityLookup.GetEntitiesInRange(compType, xform.MapPosition, component.MaximumDistance))
{
- // forgive me father, for i have sinned.
- var ent = comp.Owner;
-
var dist = (_transform.GetWorldPosition(xform, xformQuery) - _transform.GetWorldPosition(ent, xformQuery)).Length();
if (dist >= (closestDistance ?? float.MaxValue))
continue;
args.Cancel();
}
- private void OnShoot(EntityUid uid, PneumaticCannonComponent component, ref GunShotEvent args)
+ private void OnShoot(Entity<PneumaticCannonComponent> cannon, ref GunShotEvent args)
{
+ var (uid, component) = cannon;
// require a gas tank if it uses gas
- var gas = GetGas(uid);
+ var gas = GetGas(cannon);
if (gas == null && component.GasUsage > 0f)
return;
{
_stun.TryParalyze(args.User, TimeSpan.FromSeconds(component.HighPowerStunTime), true, status);
Popup.PopupEntity(Loc.GetString("pneumatic-cannon-component-power-stun",
- ("cannon", component.Owner)), uid, args.User);
+ ("cannon", uid)), cannon, args.User);
}
// ignore gas stuff if the cannon doesn't use any
return;
// this should always be possible, as we'll eject the gas tank when it no longer is
- var environment = _atmos.GetContainingMixture(component.Owner, false, true);
- var removed = _gasTank.RemoveAir(gas, component.GasUsage);
+ var environment = _atmos.GetContainingMixture(cannon, false, true);
+ var removed = _gasTank.RemoveAir(gas.Value, component.GasUsage);
if (environment != null && removed != null)
{
_atmos.Merge(environment, removed);
}
- if (gas.Air.TotalMoles >= component.GasUsage)
+ if (gas.Value.Comp.Air.TotalMoles >= component.GasUsage)
return;
// eject gas tank
/// <summary>
/// Returns whether the pneumatic cannon has enough gas to shoot an item, as well as the tank itself.
/// </summary>
- private GasTankComponent? GetGas(EntityUid uid)
+ private Entity<GasTankComponent>? GetGas(EntityUid uid)
{
if (!Container.TryGetContainer(uid, PneumaticCannonComponent.TankSlotId, out var container) ||
container is not ContainerSlot slot || slot.ContainedEntity is not {} contained)
return null;
- return TryComp<GasTankComponent>(contained, out var gasTank) ? gasTank : null;
+ return TryComp<GasTankComponent>(contained, out var gasTank) ? (contained, gasTank) : null;
}
private float GetProjectileSpeedFromPower(PneumaticCannonComponent component)
{
var arrowVisibility = EntityManager.EnsureComponent<VisibilityComponent>(arrow);
layer = playerVisibility.Layer;
- _visibilitySystem.SetLayer(arrowVisibility, layer);
+ _visibilitySystem.SetLayer(arrow, arrowVisibility, layer);
}
// Get players that are in range and whose visibility layer matches the arrow's.
{
var currentTime = _gameTiming.CurTime;
- foreach (var component in EntityQuery<PointingArrowComponent>(true))
+ var query = AllEntityQuery<PointingArrowComponent>();
+ while (query.MoveNext(out var uid, out var component))
{
- Update(component, currentTime);
+ Update((uid, component), currentTime);
}
}
- private void Update(PointingArrowComponent component, TimeSpan currentTime)
+ private void Update(Entity<PointingArrowComponent> pointing, TimeSpan currentTime)
{
// TODO: That pause PR
+ var component = pointing.Comp;
if (component.EndTime > currentTime)
return;
if (component.Rogue)
{
- RemComp<PointingArrowComponent>(component.Owner);
- EnsureComp<RoguePointingArrowComponent>(component.Owner);
+ RemComp<PointingArrowComponent>(pointing);
+ EnsureComp<RoguePointingArrowComponent>(pointing);
return;
}
- Del(component.Owner);
+ Del(pointing);
}
}
}
-using System.Linq;
using Content.Server.Explosion.EntitySystems;
using Content.Server.Pointing.Components;
using Content.Shared.Pointing.Components;
using JetBrains.Annotations;
-using Robust.Server.GameObjects;
-using Robust.Shared.Player;
using Robust.Shared.Random;
-using DrawDepth = Content.Shared.DrawDepth.DrawDepth;
namespace Content.Server.Pointing.EntitySystems
{
if (!Resolve(uid, ref component, ref transform))
return null;
- var targets = EntityQuery<PointingArrowAngeringComponent>().ToList();
+ var targets = new List<Entity<PointingArrowAngeringComponent>>();
+ var query = EntityQueryEnumerator<PointingArrowAngeringComponent>();
+ while (query.MoveNext(out var angeringUid, out var angeringComp))
+ {
+ targets.Add((angeringUid, angeringComp));
+ }
if (targets.Count == 0)
return null;
var angering = _random.Pick(targets);
- angering.RemainingAnger -= 1;
- if (angering.RemainingAnger <= 0)
+ angering.Comp.RemainingAnger -= 1;
+ if (angering.Comp.RemainingAnger <= 0)
RemComp<PointingArrowAngeringComponent>(uid);
return angering.Owner;
public override void Update(float frameTime)
{
- foreach (var (component, transform) in EntityManager.EntityQuery<RoguePointingArrowComponent, TransformComponent>())
+ var query = EntityQueryEnumerator<RoguePointingArrowComponent, TransformComponent>();
+ while (query.MoveNext(out var uid, out var component, out var transform))
{
- var uid = component.Owner;
component.Chasing ??= RandomNearbyPlayer(uid, component, transform);
if (component.Chasing is not {Valid: true} chasing || Deleted(chasing))
if (component.TurningDelay > 0)
{
- var difference = EntityManager.GetComponent<TransformComponent>(chasing).WorldPosition - transform.WorldPosition;
+ var difference = Comp<TransformComponent>(chasing).WorldPosition - transform.WorldPosition;
var angle = difference.ToAngle();
var adjusted = angle.Degrees + 90;
var newAngle = Angle.FromDegrees(adjusted);
UpdateAppearance(uid, component, transform);
- var toChased = EntityManager.GetComponent<TransformComponent>(chasing).WorldPosition - transform.WorldPosition;
+ var toChased = Comp<TransformComponent>(chasing).WorldPosition - transform.WorldPosition;
transform.WorldPosition += toChased * frameTime * component.ChasingSpeed;
-using System.Linq;
using Content.Server.Actions;
using Content.Server.Humanoid;
using Content.Server.Inventory;
MakeSentientCommand.MakeSentient(child, EntityManager);
var comp = _compFact.GetComponent<PolymorphedEntityComponent>();
- comp.Owner = child;
comp.Parent = uid;
comp.Prototype = proto.ID;
- EntityManager.AddComponent(child, comp);
+ AddComp(child, comp);
var childXform = Transform(child);
childXform.LocalRotation = targetTransformComp.LocalRotation;
using Content.Server.Administration.Logs;
using Content.Server.Power.Components;
-using Content.Server.Stack;
using Content.Shared.Database;
using Content.Shared.Interaction;
using Content.Shared.Maps;
using Content.Shared.Stacks;
-using Robust.Shared.Map;
namespace Content.Server.Power.EntitySystems;
SubscribeLocalEvent<CablePlacerComponent, AfterInteractEvent>(OnCablePlacerAfterInteract);
}
- private void OnCablePlacerAfterInteract(EntityUid uid, CablePlacerComponent component, AfterInteractEvent args)
+ private void OnCablePlacerAfterInteract(Entity<CablePlacerComponent> placer, ref AfterInteractEvent args)
{
- if (args.Handled || !args.CanReach) return;
+ if (args.Handled || !args.CanReach)
+ return;
- if (component.CablePrototypeId == null) return;
+ var component = placer.Comp;
+ if (component.CablePrototypeId == null)
+ return;
if(!_mapManager.TryGetGrid(args.ClickLocation.GetGridUid(EntityManager), out var grid))
return;
return;
}
- if (TryComp<StackComponent>(component.Owner, out var stack) && !_stack.Use(component.Owner, 1, stack))
+ if (TryComp<StackComponent>(placer, out var stack) && !_stack.Use(placer, 1, stack))
return;
var newCable = EntityManager.SpawnEntity(component.CablePrototypeId, grid.GridTileToLocal(snapPos));
using System.Diagnostics.CodeAnalysis;
-using System.Linq;
using Content.Server.Power.Components;
using Robust.Shared.Map;
+using Robust.Shared.Map.Components;
using Robust.Shared.Physics;
using Robust.Shared.Physics.Components;
var xform = Transform(uid);
// If grid deleting no need to update power.
- if (_mapManager.TryGetGrid(xform.GridUid, out var grid))
+ if (HasComp<MapGridComponent>(xform.GridUid) &&
+ MetaData(xform.GridUid.Value).EntityLifeStage > EntityLifeStage.MapInitialized)
{
- if (MetaData(grid.Owner).EntityLifeStage > EntityLifeStage.MapInitialized) return;
+ return;
}
Disconnect(uid, provider);
foreach (var receiver in FindAvailableReceivers(uid, provider.TransferRange))
{
- receiver.Provider?.LinkedReceivers.Remove(receiver);
- receiver.Provider = provider;
+ receiver.Comp.Provider?.LinkedReceivers.Remove(receiver);
+ receiver.Comp.Provider = provider;
provider.LinkedReceivers.Add(receiver);
- RaiseLocalEvent(receiver.Owner, new ProviderConnectedEvent(provider), broadcast: false);
+ RaiseLocalEvent(receiver, new ProviderConnectedEvent(provider), broadcast: false);
RaiseLocalEvent(uid, new ReceiverConnectedEvent(receiver), broadcast: false);
}
}
private void ResetReceivers(ExtensionCableProviderComponent provider)
{
+ var providerId = provider.Owner;
var receivers = provider.LinkedReceivers.ToArray();
provider.LinkedReceivers.Clear();
foreach (var receiver in receivers)
{
+ var receiverId = receiver.Owner;
receiver.Provider = null;
- RaiseLocalEvent(receiver.Owner, new ProviderDisconnectedEvent(provider), broadcast: false);
- RaiseLocalEvent(provider.Owner, new ReceiverDisconnectedEvent(receiver), broadcast: false);
+ RaiseLocalEvent(receiverId, new ProviderDisconnectedEvent(provider), broadcast: false);
+ RaiseLocalEvent(providerId, new ReceiverDisconnectedEvent((receiverId, receiver)), broadcast: false);
}
foreach (var receiver in receivers)
{
// No point resetting what the receiver is doing if it's deleting, plus significant perf savings
// in not doing needless lookups
- if (!EntityManager.IsQueuedForDeletion(receiver.Owner)
- && MetaData(receiver.Owner).EntityLifeStage <= EntityLifeStage.MapInitialized)
+ var receiverId = receiver.Owner;
+ if (!EntityManager.IsQueuedForDeletion(receiverId)
+ && MetaData(receiverId).EntityLifeStage <= EntityLifeStage.MapInitialized)
{
TryFindAndSetProvider(receiver);
}
}
}
- private IEnumerable<ExtensionCableReceiverComponent> FindAvailableReceivers(EntityUid owner, float range)
+ private IEnumerable<Entity<ExtensionCableReceiverComponent>> FindAvailableReceivers(EntityUid owner, float range)
{
var xform = Transform(owner);
var coordinates = xform.Coordinates;
- if (!_mapManager.TryGetGrid(xform.GridUid, out var grid))
+ if (!TryComp(xform.GridUid, out MapGridComponent? grid))
yield break;
var nearbyEntities = grid.GetCellsInSquareArea(coordinates, (int) Math.Ceiling(range / grid.TileSize));
continue;
if ((Transform(entity).LocalPosition - xform.LocalPosition).Length() < Math.Min(range, receiver.ReceptionRange))
- yield return receiver;
+ yield return (entity, receiver);
}
}
if (provider != null)
{
- RaiseLocalEvent(provider.Owner, new ReceiverDisconnectedEvent(receiver), broadcast: false);
+ RaiseLocalEvent(provider.Owner, new ReceiverDisconnectedEvent((uid, receiver)), broadcast: false);
provider.LinkedReceivers.Remove(receiver);
}
RaiseLocalEvent(uid, new ProviderDisconnectedEvent(receiver.Provider), broadcast: false);
if (receiver.Provider != null)
{
- RaiseLocalEvent(receiver.Provider.Owner, new ReceiverDisconnectedEvent(receiver), broadcast: false);
+ RaiseLocalEvent(receiver.Provider.Owner, new ReceiverDisconnectedEvent((uid, receiver)), broadcast: false);
receiver.Provider.LinkedReceivers.Remove(receiver);
}
private void TryFindAndSetProvider(ExtensionCableReceiverComponent receiver, TransformComponent? xform = null)
{
- if (!receiver.Connectable) return;
+ var uid = receiver.Owner;
+ if (!receiver.Connectable)
+ return;
- if (!TryFindAvailableProvider(receiver.Owner, receiver.ReceptionRange, out var provider, xform)) return;
+ if (!TryFindAvailableProvider(uid, receiver.ReceptionRange, out var provider, xform))
+ return;
receiver.Provider = provider;
provider.LinkedReceivers.Add(receiver);
- RaiseLocalEvent(receiver.Owner, new ProviderConnectedEvent(provider), broadcast: false);
- RaiseLocalEvent(provider.Owner, new ReceiverConnectedEvent(receiver), broadcast: false);
+ RaiseLocalEvent(uid, new ProviderConnectedEvent(provider), broadcast: false);
+ RaiseLocalEvent(provider.Owner, new ReceiverConnectedEvent((uid, receiver)), broadcast: false);
}
private bool TryFindAvailableProvider(EntityUid owner, float range, [NotNullWhen(true)] out ExtensionCableProviderComponent? foundProvider, TransformComponent? xform = null)
{
- if (!Resolve(owner, ref xform) || !_mapManager.TryGetGrid(xform.GridUid, out var grid))
+ if (!Resolve(owner, ref xform) || !TryComp(xform.GridUid, out MapGridComponent? grid))
{
foundProvider = null;
return false;
/// <summary>
/// The <see cref="ExtensionCableReceiverComponent"/> that connected.
/// </summary>
- public ExtensionCableReceiverComponent Receiver;
+ public Entity<ExtensionCableReceiverComponent> Receiver;
- public ReceiverConnectedEvent(ExtensionCableReceiverComponent receiver)
+ public ReceiverConnectedEvent(Entity<ExtensionCableReceiverComponent> receiver)
{
Receiver = receiver;
}
/// <summary>
/// The <see cref="ExtensionCableReceiverComponent"/> that disconnected.
/// </summary>
- public ExtensionCableReceiverComponent Receiver;
+ public Entity<ExtensionCableReceiverComponent> Receiver;
- public ReceiverDisconnectedEvent(ExtensionCableReceiverComponent receiver)
+ public ReceiverDisconnectedEvent(Entity<ExtensionCableReceiverComponent> receiver)
{
Receiver = receiver;
}
apcReceiver.PoweredLastUpdate = powered;
var ev = new PowerChangedEvent(apcReceiver.Powered, apcReceiver.NetworkLoad.ReceivingPower);
- RaiseLocalEvent(apcReceiver.Owner, ref ev);
+ RaiseLocalEvent(uid, ref ev);
if (appearanceQuery.TryGetComponent(uid, out var appearance))
_appearance.SetData(uid, PowerDeviceVisuals.Powered, powered, appearance);
private void UpdateNetworkBattery()
{
var enumerator = EntityQueryEnumerator<PowerNetworkBatteryComponent>();
- while (enumerator.MoveNext(out var powerNetBattery))
+ while (enumerator.MoveNext(out var uid, out var powerNetBattery))
{
var lastSupply = powerNetBattery.LastSupply;
var currentSupply = powerNetBattery.CurrentSupply;
if (lastSupply == 0f && currentSupply != 0f)
{
var ev = new PowerNetBatterySupplyEvent(true);
- RaiseLocalEvent(powerNetBattery.Owner, ref ev);
+ RaiseLocalEvent(uid, ref ev);
}
else if (lastSupply > 0f && currentSupply == 0f)
{
var ev = new PowerNetBatterySupplyEvent(false);
- RaiseLocalEvent(powerNetBattery.Owner, ref ev);
+ RaiseLocalEvent(uid, ref ev);
}
powerNetBattery.LastSupply = currentSupply;
component.LinkedReceivers.Clear();
}
- private void OnProviderConnected(EntityUid uid, ApcPowerReceiverComponent receiver, ExtensionCableSystem.ProviderConnectedEvent args)
+ private void OnProviderConnected(Entity<ApcPowerReceiverComponent> receiver, ref ExtensionCableSystem.ProviderConnectedEvent args)
{
var providerUid = args.Provider.Owner;
if (!EntityManager.TryGetComponent<ApcPowerProviderComponent>(providerUid, out var provider))
return;
- receiver.Provider = provider;
+ receiver.Comp.Provider = provider;
ProviderChanged(receiver);
}
- private void OnProviderDisconnected(EntityUid uid, ApcPowerReceiverComponent receiver, ExtensionCableSystem.ProviderDisconnectedEvent args)
+ private void OnProviderDisconnected(Entity<ApcPowerReceiverComponent> receiver, ref ExtensionCableSystem.ProviderDisconnectedEvent args)
{
- receiver.Provider = null;
+ receiver.Comp.Provider = null;
ProviderChanged(receiver);
}
- private void OnReceiverConnected(EntityUid uid, ApcPowerProviderComponent provider, ExtensionCableSystem.ReceiverConnectedEvent args)
+ private void OnReceiverConnected(Entity<ApcPowerProviderComponent> provider, ref ExtensionCableSystem.ReceiverConnectedEvent args)
{
- if (EntityManager.TryGetComponent(args.Receiver.Owner, out ApcPowerReceiverComponent? receiver))
+ if (EntityManager.TryGetComponent(args.Receiver, out ApcPowerReceiverComponent? receiver))
{
- provider.AddReceiver(receiver);
+ provider.Comp.AddReceiver(receiver);
}
}
private void OnReceiverDisconnected(EntityUid uid, ApcPowerProviderComponent provider, ExtensionCableSystem.ReceiverDisconnectedEvent args)
{
- if (EntityManager.TryGetComponent(args.Receiver.Owner, out ApcPowerReceiverComponent? receiver))
+ if (EntityManager.TryGetComponent(args.Receiver, out ApcPowerReceiverComponent? receiver))
{
provider.RemoveReceiver(receiver);
}
args.Verbs.Add(verb);
}
- private void ProviderChanged(ApcPowerReceiverComponent receiver)
+ private void ProviderChanged(Entity<ApcPowerReceiverComponent> receiver)
{
- receiver.NetworkLoad.LinkedNetwork = default;
- var ev = new PowerChangedEvent(receiver.Powered, receiver.NetworkLoad.ReceivingPower);
+ var comp = receiver.Comp;
+ comp.NetworkLoad.LinkedNetwork = default;
+ var ev = new PowerChangedEvent(comp.Powered, comp.NetworkLoad.ReceivingPower);
- RaiseLocalEvent(receiver.Owner, ref ev);
- _appearance.SetData(receiver.Owner, PowerDeviceVisuals.Powered, receiver.Powered);
+ RaiseLocalEvent(receiver, ref ev);
+ _appearance.SetData(receiver, PowerDeviceVisuals.Powered, comp.Powered);
}
/// <summary>
SubscribeLocalEvent<RadiationSystemUpdatedEvent>(OnUpdate);
}
- private void OnActivate(EntityUid uid, GeigerComponent component, ActivateInWorldEvent args)
+ private void OnActivate(Entity<GeigerComponent> geiger, ref ActivateInWorldEvent args)
{
- if (args.Handled || component.AttachedToSuit)
+ if (args.Handled || geiger.Comp.AttachedToSuit)
return;
args.Handled = true;
- SetEnabled(uid, component, !component.IsEnabled);
+ SetEnabled(geiger, !geiger.Comp.IsEnabled);
}
- private void OnEquipped(EntityUid uid, GeigerComponent component, GotEquippedEvent args)
+ private void OnEquipped(Entity<GeigerComponent> geiger, ref GotEquippedEvent args)
{
- if (component.AttachedToSuit)
- SetEnabled(uid, component, true);
- SetUser(component, args.Equipee);
+ if (geiger.Comp.AttachedToSuit)
+ SetEnabled(geiger, true);
+ SetUser(geiger, args.Equipee);
}
- private void OnEquippedHand(EntityUid uid, GeigerComponent component, GotEquippedHandEvent args)
+ private void OnEquippedHand(Entity<GeigerComponent> geiger, ref GotEquippedHandEvent args)
{
- if (component.AttachedToSuit)
+ if (geiger.Comp.AttachedToSuit)
return;
- SetUser(component, args.User);
+ SetUser(geiger, args.User);
}
- private void OnUnequipped(EntityUid uid, GeigerComponent component, GotUnequippedEvent args)
+ private void OnUnequipped(Entity<GeigerComponent> geiger, ref GotUnequippedEvent args)
{
- if (component.AttachedToSuit)
- SetEnabled(uid, component, false);
- SetUser(component, null);
+ if (geiger.Comp.AttachedToSuit)
+ SetEnabled(geiger, false);
+ SetUser(geiger, null);
}
- private void OnUnequippedHand(EntityUid uid, GeigerComponent component, GotUnequippedHandEvent args)
+ private void OnUnequippedHand(Entity<GeigerComponent> geiger, ref GotUnequippedHandEvent args)
{
- if (component.AttachedToSuit)
+ if (geiger.Comp.AttachedToSuit)
return;
- SetUser(component, null);
+ SetUser(geiger, null);
}
private void OnUpdate(RadiationSystemUpdatedEvent ev)
{
// update only active geiger counters
// deactivated shouldn't have rad receiver component
- var query = EntityQuery<GeigerComponent, RadiationReceiverComponent>();
- foreach (var (geiger, receiver) in query)
+ var query = EntityQueryEnumerator<GeigerComponent, RadiationReceiverComponent>();
+ while (query.MoveNext(out var uid, out var geiger, out var receiver))
{
var rads = receiver.CurrentRadiation;
- SetCurrentRadiation(geiger.Owner, geiger, rads);
+ SetCurrentRadiation(uid, geiger, rads);
}
}
UpdateSound(uid, component);
}
- Dirty(component);
+ Dirty(uid, component);
}
- private void SetUser(GeigerComponent component, EntityUid? user)
+ private void SetUser(Entity<GeigerComponent> component, EntityUid? user)
{
- if (component.User == user)
+ if (component.Comp.User == user)
return;
- component.User = user;
+ component.Comp.User = user;
Dirty(component);
- UpdateSound(component.Owner, component);
+ UpdateSound(component, component);
}
- private void SetEnabled(EntityUid uid, GeigerComponent component, bool isEnabled)
+ private void SetEnabled(Entity<GeigerComponent> geiger, bool isEnabled)
{
+ var component = geiger.Comp;
if (component.IsEnabled == isEnabled)
return;
component.DangerLevel = GeigerDangerLevel.None;
}
- _radiation.SetCanReceive(uid, isEnabled);
+ _radiation.SetCanReceive(geiger, isEnabled);
- UpdateAppearance(uid, component);
- UpdateSound(uid, component);
- Dirty(component);
+ UpdateAppearance(geiger, component);
+ UpdateSound(geiger, component);
+ Dirty(geiger, component);
}
private void UpdateAppearance(EntityUid uid, GeigerComponent? component = null,
+using System.Linq;
using System.Numerics;
using Content.Server.Radiation.Components;
using Content.Server.Radiation.Events;
using Robust.Shared.Map.Components;
using Robust.Shared.Timing;
using Robust.Shared.Utility;
-using System.Linq;
namespace Content.Server.Radiation.Systems;
stopwatch.Start();
var sources = EntityQueryEnumerator<RadiationSourceComponent, TransformComponent>();
- var destinations = EntityQuery<RadiationReceiverComponent, TransformComponent>();
+ var destinations = EntityQueryEnumerator<RadiationReceiverComponent, TransformComponent>();
var resistanceQuery = GetEntityQuery<RadiationGridResistanceComponent>();
var transformQuery = GetEntityQuery<TransformComponent>();
var gridQuery = GetEntityQuery<MapGridComponent>();
// trace all rays from rad source to rad receivers
var rays = new List<RadiationRay>();
- var receiversTotalRads = new ValueList<(RadiationReceiverComponent, float)>();
- foreach (var (dest, destTrs) in destinations)
+ var receiversTotalRads = new ValueList<(Entity<RadiationReceiverComponent>, float)>();
+ while (destinations.MoveNext(out var destUid, out var dest, out var destTrs))
{
var destWorld = _transform.GetWorldPosition(destTrs, transformQuery);
// send ray towards destination entity
var ray = Irradiate(uid, sourceTrs, sourceWorld,
- destTrs.Owner, destTrs, destWorld,
+ destUid, destTrs, destWorld,
intensity, source.Slope, saveVisitedTiles, resistanceQuery, transformQuery, gridQuery);
if (ray == null)
continue;
}
// Apply modifier if the destination entity is hidden within a radiation blocking container
- rads = GetAdjustedRadiationIntensity(dest.Owner, rads);
+ rads = GetAdjustedRadiationIntensity(destUid, rads);
- receiversTotalRads.Add((dest, rads));
+ receiversTotalRads.Add(((destUid, dest), rads));
}
// update information for debug overlay
{
// update radiation value of receiver
// if no radiation rays reached target, that will set it to 0
- receiver.CurrentRadiation = rads;
+ receiver.Comp.CurrentRadiation = rads;
// also send an event with combination of total rad
if (rads > 0)
- IrradiateEntity(receiver.Owner, rads, GridcastUpdateRate);
+ IrradiateEntity(receiver, rads, GridcastUpdateRate);
}
// raise broadcast event that radiation system has updated
{
if (!gridQuery.TryGetComponent(sourceTrs.GridUid.Value, out var gridComponent))
return ray;
- return Gridcast(gridComponent, ray, saveVisitedTiles, resistanceQuery, sourceTrs, destTrs, transformQuery.GetComponent(sourceTrs.GridUid.Value));
+ return Gridcast((sourceTrs.GridUid.Value, gridComponent), ray, saveVisitedTiles, resistanceQuery, sourceTrs, destTrs, transformQuery.GetComponent(sourceTrs.GridUid.Value));
}
// lets check how many grids are between source and destination
// do a box intersection test between target and destination
// it's not very precise, but really cheap
var box = Box2.FromTwoPoints(sourceWorld, destWorld);
- var grids = _mapManager.FindGridsIntersecting(mapId, box, true);
+ var grids = new List<Entity<MapGridComponent>>();
+ _mapManager.FindGridsIntersecting(mapId, box, ref grids, true);
// gridcast through each grid and try to hit some radiation blockers
// the ray will be updated with each grid that has some blockers
foreach (var grid in grids)
{
- ray = Gridcast(grid, ray, saveVisitedTiles, resistanceQuery, sourceTrs, destTrs, transformQuery.GetComponent(grid.Owner));
+ ray = Gridcast(grid, ray, saveVisitedTiles, resistanceQuery, sourceTrs, destTrs, transformQuery.GetComponent(grid));
// looks like last grid blocked all radiation
// we can return right now
return ray;
}
- private RadiationRay Gridcast(MapGridComponent grid, RadiationRay ray, bool saveVisitedTiles,
+ private RadiationRay Gridcast(Entity<MapGridComponent> grid, RadiationRay ray, bool saveVisitedTiles,
EntityQuery<RadiationGridResistanceComponent> resistanceQuery,
TransformComponent sourceTrs,
TransformComponent destTrs,
: gridTrs.InvLocalMatrix.Transform(ray.Destination);
Vector2i sourceGrid = new(
- (int) Math.Floor(srcLocal.X / grid.TileSize),
- (int) Math.Floor(srcLocal.Y / grid.TileSize));
+ (int) Math.Floor(srcLocal.X / grid.Comp.TileSize),
+ (int) Math.Floor(srcLocal.Y / grid.Comp.TileSize));
Vector2i destGrid = new(
- (int) Math.Floor(dstLocal.X / grid.TileSize),
- (int) Math.Floor(dstLocal.Y / grid.TileSize));
+ (int) Math.Floor(dstLocal.X / grid.Comp.TileSize),
+ (int) Math.Floor(dstLocal.Y / grid.Comp.TileSize));
// iterate tiles in grid line from source to destination
var line = new GridLineEnumerator(sourceGrid, destGrid);
using System.Diagnostics.CodeAnalysis;
-using System.Linq;
using Content.Server.Power.EntitySystems;
using Content.Shared.Research.Components;
using Robust.Server.Player;
private void OnClientMapInit(EntityUid uid, ResearchClientComponent component, MapInitEvent args)
{
- var allServers = EntityQuery<ResearchServerComponent>(true).ToArray();
- if (allServers.Length > 0)
- RegisterClient(uid, allServers[0].Owner, component, allServers[0]);
+ var allServers = new List<Entity<ResearchServerComponent>>();
+ var query = AllEntityQuery<ResearchServerComponent>();
+ while (query.MoveNext(out var serverUid, out var serverComp))
+ {
+ allServers.Add((serverUid, serverComp));
+ }
+
+ if (allServers.Count > 0)
+ RegisterClient(uid, allServers[0], component, allServers[0]);
}
private void OnClientShutdown(EntityUid uid, ResearchClientComponent component, ComponentShutdown args)
SubscribeLocalEvent<ResearchPointSourceComponent, ResearchServerGetPointsPerSecondEvent>(OnGetPointsPerSecond);
}
- private void OnGetPointsPerSecond(EntityUid uid, ResearchPointSourceComponent component, ref ResearchServerGetPointsPerSecondEvent args)
+ private void OnGetPointsPerSecond(Entity<ResearchPointSourceComponent> source, ref ResearchServerGetPointsPerSecondEvent args)
{
- if (CanProduce(component))
- args.Points += component.PointsPerSecond;
+ if (CanProduce(source))
+ args.Points += source.Comp.PointsPerSecond;
}
- public bool CanProduce(ResearchPointSourceComponent component)
+ public bool CanProduce(Entity<ResearchPointSourceComponent> source)
{
- return component.Active && this.IsPowered(component.Owner, EntityManager);
+ return source.Comp.Active && this.IsPowered(source, EntityManager);
}
}
{
serverUid = null;
serverComponent = null;
- foreach (var server in EntityQuery<ResearchServerComponent>())
+
+ var query = EntityQueryEnumerator<ResearchServerComponent>();
+ while (query.MoveNext(out var uid, out var server))
{
if (server.Id != id)
continue;
- serverUid = server.Owner;
+ serverUid = uid;
serverComponent = server;
return true;
}
public override void Update(float frameTime)
{
- foreach (var server in EntityQuery<ResearchServerComponent>())
+ var query = EntityQueryEnumerator<ResearchServerComponent>();
+ while (query.MoveNext(out var uid, out var server))
{
if (server.NextUpdateTime > _timing.CurTime)
continue;
server.NextUpdateTime = _timing.CurTime + server.ResearchConsoleUpdateTime;
- UpdateServer(server.Owner, (int) server.ResearchConsoleUpdateTime.TotalSeconds, server);
+ UpdateServer(uid, (int) server.ResearchConsoleUpdateTime.TotalSeconds, server);
}
}
}
using Content.Server.Contests;
-using Robust.Shared.Containers;
using Content.Server.Popups;
-using Content.Shared.Storage;
-using Content.Shared.Inventory;
-using Content.Shared.Hands.EntitySystems;
+using Content.Server.Storage.Components;
using Content.Shared.ActionBlocker;
using Content.Shared.DoAfter;
-using Content.Shared.Movement.Events;
+using Content.Shared.Hands.EntitySystems;
using Content.Shared.Interaction.Events;
+using Content.Shared.Inventory;
+using Content.Shared.Movement.Events;
using Content.Shared.Resist;
-using Content.Server.Storage.Components;
+using Content.Shared.Storage;
+using Robust.Shared.Containers;
namespace Content.Server.Resist;
if (args.Handled || args.Cancelled)
return;
- _containerSystem.AttachParentToContainerOrGrid(Transform(uid));
+ _containerSystem.AttachParentToContainerOrGrid((uid, Transform(uid)));
args.Handled = true;
}
if (TryComp<VisibilityComponent>(uid, out var visibility))
{
- _visibilitySystem.RemoveLayer(visibility, (int) VisibilityFlags.Ghost, false);
- _visibilitySystem.AddLayer(visibility, (int) VisibilityFlags.Normal, false);
- _visibilitySystem.RefreshVisibility(visibility);
+ _visibilitySystem.RemoveLayer(uid, visibility, (int) VisibilityFlags.Ghost, false);
+ _visibilitySystem.AddLayer(uid, visibility, (int) VisibilityFlags.Normal, false);
+ _visibilitySystem.RefreshVisibility(uid, visibility);
}
}
if (TryComp<VisibilityComponent>(uid, out var visibility) && _ticker.RunLevel != GameRunLevel.PostRound)
{
- _visibilitySystem.AddLayer(visibility, (int) VisibilityFlags.Ghost, false);
- _visibilitySystem.RemoveLayer(visibility, (int) VisibilityFlags.Normal, false);
- _visibilitySystem.RefreshVisibility(visibility);
+ _visibilitySystem.AddLayer(uid, visibility, (int) VisibilityFlags.Ghost, false);
+ _visibilitySystem.RemoveLayer(uid, visibility, (int) VisibilityFlags.Normal, false);
+ _visibilitySystem.RefreshVisibility(uid, visibility);
}
}
}
{
[Dependency] private readonly BeamSystem _beam = default!;
- protected override void OnZap(RevenantOverloadedLightsComponent component)
+ protected override void OnZap(Entity<RevenantOverloadedLightsComponent> lights)
{
+ var component = lights.Comp;
if (component.Target == null)
return;
- var lxform = Transform(component.Owner);
+ var lxform = Transform(lights);
var txform = Transform(component.Target.Value);
if (!lxform.Coordinates.TryDistance(EntityManager, txform.Coordinates, out var distance))
if (distance > component.ZapRange)
return;
- _beam.TryCreateBeam(component.Owner, component.Target.Value, component.ZapBeamEntityId);
+ _beam.TryCreateBeam(lights, component.Target.Value, component.ZapBeamEntityId);
}
}
if (_ticker.RunLevel == GameRunLevel.PostRound && TryComp<VisibilityComponent>(uid, out var visibility))
{
- _visibility.AddLayer(visibility, (int) VisibilityFlags.Ghost, false);
- _visibility.RemoveLayer(visibility, (int) VisibilityFlags.Normal, false);
- _visibility.RefreshVisibility(visibility);
+ _visibility.AddLayer(uid, visibility, (int) VisibilityFlags.Ghost, false);
+ _visibility.RemoveLayer(uid, visibility, (int) VisibilityFlags.Normal, false);
+ _visibility.RefreshVisibility(uid, visibility);
}
//ghost vision
public void MakeVisible(bool visible)
{
- foreach (var (_, vis) in EntityQuery<RevenantComponent, VisibilityComponent>())
+ var query = EntityQueryEnumerator<RevenantComponent, VisibilityComponent>();
+ while (query.MoveNext(out var uid, out _, out var vis))
{
if (visible)
{
- _visibility.AddLayer(vis, (int) VisibilityFlags.Normal, false);
- _visibility.RemoveLayer(vis, (int) VisibilityFlags.Ghost, false);
+ _visibility.AddLayer(uid, vis, (int) VisibilityFlags.Normal, false);
+ _visibility.RemoveLayer(uid, vis, (int) VisibilityFlags.Ghost, false);
}
else
{
- _visibility.AddLayer(vis, (int) VisibilityFlags.Ghost, false);
- _visibility.RemoveLayer(vis, (int) VisibilityFlags.Normal, false);
+ _visibility.AddLayer(uid, vis, (int) VisibilityFlags.Ghost, false);
+ _visibility.RemoveLayer(uid, vis, (int) VisibilityFlags.Normal, false);
}
- _visibility.RefreshVisibility(vis);
+ _visibility.RefreshVisibility(uid, vis);
}
}
{
base.Update(frameTime);
- foreach (var rev in EntityQuery<RevenantComponent>())
+ var query = EntityQueryEnumerator<RevenantComponent>();
+ while (query.MoveNext(out var uid, out var rev))
{
rev.Accumulator += frameTime;
if (rev.Essence < rev.EssenceRegenCap)
{
- ChangeEssenceAmount(rev.Owner, rev.EssencePerSecond, rev, regenCap: true);
+ ChangeEssenceAmount(uid, rev.EssencePerSecond, rev, regenCap: true);
}
}
}
-using Content.Server.Preferences.Managers;
using Content.Server.Administration;
using Content.Shared.Administration;
-using Content.Shared.Preferences;
-using Content.Shared.Roles;
-using Robust.Server.GameObjects;
using Robust.Server.Player;
using Robust.Shared.Console;
using Robust.Shared.Map;
-using Robust.Shared.IoC;
namespace Content.Server.Salvage;
var entityTransform = _entities.GetComponent<TransformComponent>(entity.Value);
var total = Box2.UnitCentered;
var first = true;
- foreach (var mapGrid in _maps.GetAllMapGrids(entityTransform.MapID))
+ foreach (var mapGrid in _maps.GetAllGrids(entityTransform.MapID))
{
- var aabb = _entities.GetComponent<TransformComponent>(mapGrid.Owner).WorldMatrix.TransformBox(mapGrid.LocalAABB);
+ var aabb = _entities.GetComponent<TransformComponent>(mapGrid).WorldMatrix.TransformBox(mapGrid.Comp.LocalAABB);
if (first)
{
total = aabb;
using Content.Shared.Procedural;
-using Content.Shared.Salvage;
using Content.Shared.Salvage.Expeditions;
namespace Content.Server.Salvage;
UpdateConsoles(data);
}
- private void OnSalvageConsoleInit(EntityUid uid, SalvageExpeditionConsoleComponent component, ComponentInit args)
+ private void OnSalvageConsoleInit(Entity<SalvageExpeditionConsoleComponent> console, ref ComponentInit args)
{
- UpdateConsole(component);
+ UpdateConsole(console);
}
- private void OnSalvageConsoleParent(EntityUid uid, SalvageExpeditionConsoleComponent component, ref EntParentChangedMessage args)
+ private void OnSalvageConsoleParent(Entity<SalvageExpeditionConsoleComponent> console, ref EntParentChangedMessage args)
{
- UpdateConsole(component);
+ UpdateConsole(console);
}
private void UpdateConsoles(SalvageExpeditionDataComponent component)
{
var state = GetState(component);
- foreach (var (console, xform, uiComp) in EntityQuery<SalvageExpeditionConsoleComponent, TransformComponent, UserInterfaceComponent>(true))
+ var query = AllEntityQuery<SalvageExpeditionConsoleComponent, UserInterfaceComponent, TransformComponent>();
+ while (query.MoveNext(out var uid, out _, out var uiComp, out var xform))
{
- var station = _station.GetOwningStation(console.Owner, xform);
+ var station = _station.GetOwningStation(uid, xform);
- if (station != component.Owner)
+ if (station != uid)
continue;
- _ui.TrySetUiState(console.Owner, SalvageConsoleUiKey.Expedition, state, ui: uiComp);
+ _ui.TrySetUiState(uid, SalvageConsoleUiKey.Expedition, state, ui: uiComp);
}
}
- private void UpdateConsole(SalvageExpeditionConsoleComponent component)
+ private void UpdateConsole(Entity<SalvageExpeditionConsoleComponent> component)
{
- var station = _station.GetOwningStation(component.Owner);
+ var station = _station.GetOwningStation(component);
SalvageExpeditionConsoleState state;
if (TryComp<SalvageExpeditionDataComponent>(station, out var dataComponent))
state = new SalvageExpeditionConsoleState(TimeSpan.Zero, false, true, 0, new List<SalvageMissionParams>());
}
- _ui.TrySetUiState(component.Owner, SalvageConsoleUiKey.Expedition, state);
+ _ui.TrySetUiState(component, SalvageConsoleUiKey.Expedition, state);
}
}
/// <summary>
/// Whether the thruster has been force to be enabled / disabled (e.g. VV, interaction, etc.)
/// </summary>
- [ViewVariables(VVAccess.ReadWrite)]
- public bool Enabled
- {
- get => _enabled;
- [Obsolete("Use the system method")]
- set
- {
- if (_enabled == value) return;
- _enabled = value;
-
- var system = EntitySystem.Get<ThrusterSystem>();
-
- if (!_enabled)
- {
- system.DisableThruster(Owner, this);
- }
- else if (system.CanEnable(Owner, this))
- {
- system.EnableThruster(Owner, this);
- }
- }
- }
-
- [DataField("enabled")]
- private bool _enabled = true;
+ [DataField, ViewVariables(VVAccess.ReadWrite)]
+ public bool Enabled { get; set; }
/// <summary>
/// This determines whether the thruster is actually enabled for the purposes of thrust
using Content.Server.Shuttles.Components;
using Content.Shared.Shuttles.Components;
using Content.Shared.Shuttles.Events;
-using Robust.Shared.Physics.Components;
-using Robust.Shared.Players;
-using Robust.Shared.Utility;
namespace Content.Server.Shuttles.Systems;
if (dockable == null)
continue;
- TryDock(dockUid, dock, dockable.Owner, dockable);
+ TryDock(dockUid, dock, dockable.Value);
}
// Work out recent docks that have gone past their designated threshold.
var player = args.Session.AttachedEntity;
// TODO: Validation
- if (player == null || !TryComp<AutoDockComponent>(dork, out var comp)) return;
+ if (player == null || !TryComp<AutoDockComponent>(dork, out var comp))
+ return;
comp.Requesters.Remove(player.Value);
-using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Numerics;
using Content.Server.Shuttles.Components;
var isMap = HasComp<MapComponent>(targetGrid);
var validDockConfigs = new List<DockingConfig>();
+ var grids = new List<Entity<MapGridComponent>>();
if (shuttleDocks.Count > 0)
{
// We'll try all combinations of shuttle docks and see which one is most suitable
var dockedBounds = new Box2Rotated(shuttleAABB.Translated(spawnPosition.Position), targetAngle, spawnPosition.Position);
// Check if there's no intersecting grids (AKA oh god it's docking at cargo).
- if (_mapManager.FindGridsIntersecting(targetGridXform.MapID,
- dockedBounds).Any(o => o.Owner != targetGrid))
+ grids.Clear();
+ _mapManager.FindGridsIntersecting(targetGridXform.MapID, dockedBounds, ref grids);
+ if (grids.Any(o => o.Owner != targetGrid))
{
continue;
}
using Content.Shared.Doors.Components;
using Content.Shared.Shuttles.Events;
using Robust.Shared.Map;
+using Robust.Shared.Map.Components;
using Robust.Shared.Physics;
using Robust.Shared.Physics.Collision.Shapes;
using Robust.Shared.Physics.Components;
args.Cancel();
}
- private DockingComponent? GetDockable(EntityUid uid, TransformComponent dockingXform)
+ private Entity<DockingComponent>? GetDockable(EntityUid uid, TransformComponent dockingXform)
{
// Did you know Saltern is the most dockable station?
var enlargedAABB = aabb.Value.Enlarged(DockingRadius * 1.5f);
// Get any docking ports in range on other grids.
- foreach (var otherGrid in _mapManager.FindGridsIntersecting(dockingXform.MapID, enlargedAABB))
+ var grids = new List<Entity<MapGridComponent>>();
+ _mapManager.FindGridsIntersecting(dockingXform.MapID, enlargedAABB, ref grids);
+ foreach (var otherGrid in grids)
{
if (otherGrid.Owner == dockingXform.GridUid)
continue;
- foreach (var ent in otherGrid.GetAnchoredEntities(enlargedAABB))
+ foreach (var ent in otherGrid.Comp.GetAnchoredEntities(enlargedAABB))
{
if (!TryComp(ent, out DockingComponent? otherDocking) ||
!otherDocking.Enabled ||
// TODO: Need CollisionManager's GJK for accurate bounds
// Realistically I want 2 fixtures anyway but I'll deal with that later.
- return otherDocking;
+ return (ent, otherDocking);
}
}
}
/// <summary>
/// Attempts to dock 2 ports together and will return early if it's not possible.
/// </summary>
- private void TryDock(EntityUid dockAUid, DockingComponent dockA, EntityUid dockBUid, DockingComponent dockB)
+ private void TryDock(EntityUid dockAUid, DockingComponent dockA, Entity<DockingComponent> dockB)
{
- if (!CanDock(dockAUid, dockBUid, dockA, dockB))
+ if (!CanDock(dockAUid, dockB, dockA, dockB))
return;
- Dock(dockAUid, dockA, dockBUid, dockB);
+ Dock(dockAUid, dockA, dockB, dockB);
}
public void Undock(EntityUid dockUid, DockingComponent dock)
using Content.Shared.Shuttles.BUIStates;
using Content.Shared.Shuttles.Events;
using Content.Shared.Shuttles.Systems;
-using Robust.Server.GameObjects;
using Robust.Shared.Map;
using Robust.Shared.Player;
using Timer = Robust.Shared.Timing.Timer;
private void OnEmergencyRepeal(EntityUid uid, EmergencyShuttleConsoleComponent component, EmergencyShuttleRepealMessage args)
{
var player = args.Session.AttachedEntity;
- if (player == null) return;
+ if (player == null)
+ return;
- if (!_idSystem.TryFindIdCard(player.Value, out var idCard) || !_reader.IsAllowed(idCard.Owner, uid))
+ if (!_idSystem.TryFindIdCard(player.Value, out var idCard) || !_reader.IsAllowed(idCard, uid))
{
_popup.PopupCursor(Loc.GetString("emergency-shuttle-console-denied"), player.Value, PopupType.Medium);
return;
}
// TODO: This is fucking bad
- if (!component.AuthorizedEntities.Remove(MetaData(idCard.Owner).EntityName))
+ if (!component.AuthorizedEntities.Remove(MetaData(idCard).EntityName))
return;
_logger.Add(LogType.EmergencyShuttle, LogImpact.High, $"Emergency shuttle early launch REPEAL by {args.Session:user}");
if (player == null)
return;
- if (!_idSystem.TryFindIdCard(player.Value, out var idCard) || !_reader.IsAllowed(idCard.Owner, uid))
+ if (!_idSystem.TryFindIdCard(player.Value, out var idCard) || !_reader.IsAllowed(idCard, uid))
{
_popup.PopupCursor(Loc.GetString("emergency-shuttle-console-denied"), args.Session, PopupType.Medium);
return;
}
// TODO: This is fucking bad
- if (!component.AuthorizedEntities.Add(MetaData(idCard.Owner).EntityName))
+ if (!component.AuthorizedEntities.Add(MetaData(idCard).EntityName))
return;
_logger.Add(LogType.EmergencyShuttle, LogImpact.High, $"Emergency shuttle early launch AUTH by {args.Session:user}");
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Numerics;
using Content.Server.Shuttles.Components;
+using Content.Server.Shuttles.Events;
using Content.Server.Station.Systems;
using Content.Shared.Body.Components;
+using Content.Shared.Buckle.Components;
+using Content.Shared.Doors.Components;
using Content.Shared.Maps;
using Content.Shared.Parallax;
+using Content.Shared.Shuttles.Components;
using Content.Shared.Shuttles.Systems;
using Content.Shared.StatusEffect;
+using JetBrains.Annotations;
using Robust.Shared.Audio;
using Robust.Shared.Collections;
using Robust.Shared.Map;
-using Robust.Shared.Player;
-using Robust.Shared.Utility;
-using System.Diagnostics.CodeAnalysis;
-using System.Numerics;
-using System.Linq;
-using Content.Server.Shuttles.Events;
-using Content.Shared.Body.Components;
-using Content.Shared.Buckle.Components;
-using Content.Shared.Doors.Components;
-using Content.Shared.Mobs.Components;
-using Content.Shared.Shuttles.Components;
-using Content.Shared.Throwing;
-using JetBrains.Annotations;
using Robust.Shared.Map.Components;
using Robust.Shared.Physics;
using Robust.Shared.Physics.Components;
+using Robust.Shared.Player;
+using Robust.Shared.Utility;
namespace Content.Server.Shuttles.Systems;
component = AddComp<FTLComponent>(uid);
component.State = FTLState.Starting;
// TODO: Need BroadcastGrid to not be bad.
- SoundSystem.Play(_startupSound.GetSound(), Filter.Empty().AddInRange(Transform(uid).MapPosition, GetSoundRange(component.Owner)), _startupSound.Params);
+ SoundSystem.Play(_startupSound.GetSound(), Filter.Empty().AddInRange(Transform(uid).MapPosition, GetSoundRange(uid)), _startupSound.Params);
// Make sure the map is setup before we leave to avoid pop-in (e.g. parallax).
SetupHyperspace();
return true;
var iteration = 0;
var lastCount = nearbyGrids.Count;
var mapId = targetXform.MapID;
+ var grids = new List<Entity<MapGridComponent>>();
while (iteration < FTLProximityIterations)
{
- foreach (var grid in _mapManager.FindGridsIntersecting(mapId, targetAABB))
+ grids.Clear();
+ _mapManager.FindGridsIntersecting(mapId, targetAABB, ref grids);
+
+ foreach (var grid in grids)
{
- if (!nearbyGrids.Add(grid.Owner))
+ if (!nearbyGrids.Add(grid))
continue;
- targetAABB = targetAABB.Union(_transform.GetWorldMatrix(grid.Owner, xformQuery)
- .TransformBox(Comp<MapGridComponent>(grid.Owner).LocalAABB));
+ targetAABB = targetAABB.Union(_transform.GetWorldMatrix(grid, xformQuery)
+ .TransformBox(Comp<MapGridComponent>(grid).LocalAABB));
}
// Can do proximity
if (iteration != FTLProximityIterations)
continue;
- foreach (var grid in _mapManager.GetAllGrids())
+ var query = AllEntityQuery<MapGridComponent>();
+ while (query.MoveNext(out var uid, out var grid))
{
// Don't add anymore as it is irrelevant, but that doesn't mean we need to re-do existing work.
- if (nearbyGrids.Contains(grid.Owner))
+ if (nearbyGrids.Contains(uid))
continue;
- targetAABB = targetAABB.Union(_transform.GetWorldMatrix(grid.Owner, xformQuery)
- .TransformBox(Comp<MapGridComponent>(grid.Owner).LocalAABB));
+ targetAABB = targetAABB.Union(_transform.GetWorldMatrix(uid, xformQuery)
+ .TransformBox(Comp<MapGridComponent>(uid).LocalAABB));
}
break;
protected override void UpdateIFFInterfaces(EntityUid gridUid, IFFComponent component)
{
base.UpdateIFFInterfaces(gridUid, component);
- foreach (var (comp, xform) in EntityQuery<IFFConsoleComponent, TransformComponent>(true))
+
+ var query = AllEntityQuery<IFFConsoleComponent, TransformComponent>();
+ while (query.MoveNext(out var uid, out var comp, out var xform))
{
if (xform.GridUid != gridUid)
continue;
- _uiSystem.TrySetUiState(comp.Owner, IFFConsoleUiKey.Key, new IFFConsoleBoundUserInterfaceState()
+ _uiSystem.TrySetUiState(uid, IFFConsoleUiKey.Key, new IFFConsoleBoundUserInterfaceState()
{
AllowedFlags = comp.AllowedFlags,
Flags = component.Flags,
private void OnActivateThruster(EntityUid uid, ThrusterComponent component, ActivateInWorldEvent args)
{
component.Enabled ^= true;
+
+ if (!component.Enabled)
+ {
+ DisableThruster(uid, component);
+ }
+ else if (CanEnable(uid, component))
+ {
+ EnableThruster(uid, component);
+ }
}
/// <summary>
using Content.Server.Administration.Logs;
-using Content.Server.Singularity.Events;
-using Content.Shared.Singularity.Components;
-using Content.Shared.Tag;
-using Robust.Server.GameObjects;
-using Robust.Shared.Physics;
using Content.Server.Popups;
+using Content.Server.Singularity.Events;
using Content.Shared.Construction.Components;
using Content.Shared.Database;
using Content.Shared.Examine;
using Content.Shared.Interaction;
using Content.Shared.Popups;
+using Content.Shared.Singularity.Components;
+using Content.Shared.Tag;
+using Robust.Server.GameObjects;
+using Robust.Shared.Physics;
using Robust.Shared.Physics.Components;
using Robust.Shared.Physics.Events;
if (generator.Accumulator >= generator.Threshold)
{
- LosePower(uid, generator.PowerLoss, generator);
+ LosePower((uid, generator), generator.PowerLoss);
generator.Accumulator -= generator.Threshold;
}
}
/// <summary>
/// A generator receives power from a source colliding with it.
/// </summary>
- private void HandleGeneratorCollide(EntityUid uid, ContainmentFieldGeneratorComponent component, ref StartCollideEvent args)
+ private void HandleGeneratorCollide(Entity<ContainmentFieldGeneratorComponent> generator, ref StartCollideEvent args)
{
- if (_tags.HasTag(args.OtherEntity, component.IDTag))
+ if (_tags.HasTag(args.OtherEntity, generator.Comp.IDTag))
{
- ReceivePower(component.PowerReceived, component);
- component.Accumulator = 0f;
+ ReceivePower(generator.Comp.PowerReceived, generator);
+ generator.Comp.Accumulator = 0f;
}
}
args.PushMarkup(Loc.GetString("comp-containment-off"));
}
- private void OnInteract(EntityUid uid, ContainmentFieldGeneratorComponent component, InteractHandEvent args)
+ private void OnInteract(Entity<ContainmentFieldGeneratorComponent> generator, ref InteractHandEvent args)
{
if (args.Handled)
return;
- if (TryComp(component.Owner, out TransformComponent? transformComp) && transformComp.Anchored)
+ if (TryComp(generator, out TransformComponent? transformComp) && transformComp.Anchored)
{
- if (!component.Enabled)
- TurnOn(component);
- else if (component.Enabled && component.IsConnected)
+ if (!generator.Comp.Enabled)
+ TurnOn(generator);
+ else if (generator.Comp.Enabled && generator.Comp.IsConnected)
{
_popupSystem.PopupEntity(Loc.GetString("comp-containment-toggle-warning"), args.User, args.User, PopupType.LargeCaution);
return;
}
else
- TurnOff(component);
+ TurnOff(generator);
}
args.Handled = true;
}
- private void OnAnchorChanged(EntityUid uid, ContainmentFieldGeneratorComponent component, ref AnchorStateChangedEvent args)
+ private void OnAnchorChanged(Entity<ContainmentFieldGeneratorComponent> generator, ref AnchorStateChangedEvent args)
{
if (!args.Anchored)
- RemoveConnections(uid, component);
+ RemoveConnections(generator);
}
- private void OnReanchorEvent(EntityUid uid, ContainmentFieldGeneratorComponent component, ref ReAnchorEvent args)
+ private void OnReanchorEvent(Entity<ContainmentFieldGeneratorComponent> generator, ref ReAnchorEvent args)
{
- GridCheck(uid, component);
+ GridCheck(generator);
}
private void OnUnanchorAttempt(EntityUid uid, ContainmentFieldGeneratorComponent component,
}
}
- private void TurnOn(ContainmentFieldGeneratorComponent component)
+ private void TurnOn(Entity<ContainmentFieldGeneratorComponent> generator)
{
- component.Enabled = true;
- ChangeFieldVisualizer(component);
- _popupSystem.PopupEntity(Loc.GetString("comp-containment-turned-on"), component.Owner);
+ generator.Comp.Enabled = true;
+ ChangeFieldVisualizer(generator);
+ _popupSystem.PopupEntity(Loc.GetString("comp-containment-turned-on"), generator);
}
- private void TurnOff(ContainmentFieldGeneratorComponent component)
+ private void TurnOff(Entity<ContainmentFieldGeneratorComponent> generator)
{
- component.Enabled = false;
- ChangeFieldVisualizer(component);
- _popupSystem.PopupEntity(Loc.GetString("comp-containment-turned-off"), component.Owner);
+ generator.Comp.Enabled = false;
+ ChangeFieldVisualizer(generator);
+ _popupSystem.PopupEntity(Loc.GetString("comp-containment-turned-off"), generator);
}
- private void OnComponentRemoved(EntityUid uid, ContainmentFieldGeneratorComponent component, ComponentRemove args)
+ private void OnComponentRemoved(Entity<ContainmentFieldGeneratorComponent> generator, ref ComponentRemove args)
{
- RemoveConnections(uid, component);
+ RemoveConnections(generator);
}
/// <summary>
/// Deletes the fields and removes the respective connections for the generators.
/// </summary>
- private void RemoveConnections(EntityUid uid, ContainmentFieldGeneratorComponent component)
+ private void RemoveConnections(Entity<ContainmentFieldGeneratorComponent> generator)
{
+ var (uid, component) = generator;
foreach (var (direction, value) in component.Connections)
{
foreach (var field in value.Item2)
{
QueueDel(field);
}
- value.Item1.Connections.Remove(direction.GetOpposite());
+ value.Item1.Comp.Connections.Remove(direction.GetOpposite());
- if (value.Item1.Connections.Count == 0) //Change isconnected only if there's no more connections
+ if (value.Item1.Comp.Connections.Count == 0) //Change isconnected only if there's no more connections
{
- value.Item1.IsConnected = false;
+ value.Item1.Comp.IsConnected = false;
ChangeOnLightVisualizer(value.Item1);
}
}
component.Connections.Clear();
component.IsConnected = false;
- ChangeOnLightVisualizer(component);
- ChangeFieldVisualizer(component);
+ ChangeOnLightVisualizer(generator);
+ ChangeFieldVisualizer(generator);
_adminLogger.Add(LogType.FieldGeneration, LogImpact.Medium, $"{ToPrettyString(uid)} lost field connections"); // Ideally LogImpact would depend on if there is a singulo nearby
- _popupSystem.PopupEntity(Loc.GetString("comp-containment-disconnected"), component.Owner, PopupType.LargeCaution);
+ _popupSystem.PopupEntity(Loc.GetString("comp-containment-disconnected"), uid, PopupType.LargeCaution);
}
#endregion
/// Stores power in the generator. If it hits the threshold, it tries to establish a connection.
/// </summary>
/// <param name="power">The power that this generator received from the collision in <see cref="HandleGeneratorCollide"/></param>
- public void ReceivePower(int power, ContainmentFieldGeneratorComponent component)
+ public void ReceivePower(int power, Entity<ContainmentFieldGeneratorComponent> generator)
{
+ var component = generator.Comp;
component.PowerBuffer += power;
- var genXForm = Transform(component.Owner);
+ var genXForm = Transform(generator);
if (component.PowerBuffer >= component.PowerMinimum)
{
if (component.Connections.ContainsKey(dir))
continue; // This direction already has an active connection
- TryGenerateFieldConnection(dir, component, genXForm);
+ TryGenerateFieldConnection(dir, generator, genXForm);
}
}
- ChangePowerVisualizer(power, component);
+ ChangePowerVisualizer(power, generator);
}
- public void LosePower(EntityUid uid, int power, ContainmentFieldGeneratorComponent component)
+ public void LosePower(Entity<ContainmentFieldGeneratorComponent> generator, int power)
{
+ var component = generator.Comp;
component.PowerBuffer -= power;
if (component.PowerBuffer < component.PowerMinimum && component.Connections.Count != 0)
{
- RemoveConnections(uid, component);
+ RemoveConnections(generator);
}
- ChangePowerVisualizer(power, component);
+ ChangePowerVisualizer(power, generator);
}
/// <summary>
/// If all the checks pass and fields spawn, it will store this connection on each respective generator.
/// </summary>
/// <param name="dir">The field generator establishes a connection in this direction.</param>
- /// <param name="component">The field generator component</param>
+ /// <param name="generator">The field generator component</param>
/// <param name="gen1XForm">The transform component for the first generator</param>
/// <returns></returns>
- private bool TryGenerateFieldConnection(Direction dir, ContainmentFieldGeneratorComponent component, TransformComponent gen1XForm)
+ private bool TryGenerateFieldConnection(Direction dir, Entity<ContainmentFieldGeneratorComponent> generator, TransformComponent gen1XForm)
{
+ var component = generator.Comp;
if (!component.Enabled)
return false;
var dirRad = dir.ToAngle() + genWorldPosRot.WorldRotation; //needs to be like this for the raycast to work properly
var ray = new CollisionRay(genWorldPosRot.WorldPosition, dirRad.ToVec(), component.CollisionMask);
- var rayCastResults = _physics.IntersectRay(gen1XForm.MapID, ray, component.MaxLength, component.Owner, false);
+ var rayCastResults = _physics.IntersectRay(gen1XForm.MapID, ray, component.MaxLength, generator, false);
var genQuery = GetEntityQuery<ContainmentFieldGeneratorComponent>();
RayCastResults? closestResult = null;
otherFieldGeneratorComponent == component ||
!TryComp<PhysicsComponent>(ent, out var collidableComponent) ||
collidableComponent.BodyType != BodyType.Static ||
- gen1XForm.ParentUid != Transform(otherFieldGeneratorComponent.Owner).ParentUid)
+ gen1XForm.ParentUid != Transform(ent).ParentUid)
{
return false;
}
- var fields = GenerateFieldConnection(component, otherFieldGeneratorComponent);
+ var otherFieldGenerator = (ent, otherFieldGeneratorComponent);
+ var fields = GenerateFieldConnection(generator, otherFieldGenerator);
- component.Connections[dir] = (otherFieldGeneratorComponent, fields);
- otherFieldGeneratorComponent.Connections[dir.GetOpposite()] = (component, fields);
- ChangeFieldVisualizer(otherFieldGeneratorComponent);
+ component.Connections[dir] = (otherFieldGenerator, fields);
+ otherFieldGeneratorComponent.Connections[dir.GetOpposite()] = (generator, fields);
+ ChangeFieldVisualizer(otherFieldGenerator);
if (!component.IsConnected)
{
component.IsConnected = true;
- ChangeOnLightVisualizer(component);
+ ChangeOnLightVisualizer(generator);
}
if (!otherFieldGeneratorComponent.IsConnected)
{
otherFieldGeneratorComponent.IsConnected = true;
- ChangeOnLightVisualizer(otherFieldGeneratorComponent);
+ ChangeOnLightVisualizer(otherFieldGenerator);
}
- ChangeFieldVisualizer(component);
- UpdateConnectionLights(component);
- _popupSystem.PopupEntity(Loc.GetString("comp-containment-connected"), component.Owner);
+ ChangeFieldVisualizer(generator);
+ UpdateConnectionLights(generator);
+ _popupSystem.PopupEntity(Loc.GetString("comp-containment-connected"), generator);
return true;
}
/// <summary>
/// Spawns fields between two generators if the <see cref="TryGenerateFieldConnection"/> finds two generators to connect.
/// </summary>
- /// <param name="firstGenComp">The source field generator</param>
- /// <param name="secondGenComp">The second generator that the source is connected to</param>
+ /// <param name="firstGen">The source field generator</param>
+ /// <param name="secondGen">The second generator that the source is connected to</param>
/// <returns></returns>
- private List<EntityUid> GenerateFieldConnection(ContainmentFieldGeneratorComponent firstGenComp, ContainmentFieldGeneratorComponent secondGenComp)
+ private List<EntityUid> GenerateFieldConnection(Entity<ContainmentFieldGeneratorComponent> firstGen, Entity<ContainmentFieldGeneratorComponent> secondGen)
{
var fieldList = new List<EntityUid>();
- var gen1Coords = Transform(firstGenComp.Owner).Coordinates;
- var gen2Coords = Transform(secondGenComp.Owner).Coordinates;
+ var gen1Coords = Transform(firstGen).Coordinates;
+ var gen2Coords = Transform(secondGen).Coordinates;
var delta = (gen2Coords - gen1Coords).Position;
var dirVec = delta.Normalized();
while (currentOffset.Length() < stopDist)
{
var currentCoords = gen1Coords.Offset(currentOffset);
- var newField = Spawn(firstGenComp.CreatedField, currentCoords);
+ var newField = Spawn(firstGen.Comp.CreatedField, currentCoords);
var fieldXForm = Transform(newField);
- fieldXForm.AttachParent(firstGenComp.Owner);
+ fieldXForm.AttachParent(firstGen);
if (dirVec.GetDir() == Direction.East || dirVec.GetDir() == Direction.West)
{
var angle = fieldXForm.LocalPosition.ToAngle();
/// <summary>
/// Creates a light component for the spawned fields.
/// </summary>
- public void UpdateConnectionLights(ContainmentFieldGeneratorComponent component)
+ public void UpdateConnectionLights(Entity<ContainmentFieldGeneratorComponent> generator)
{
- if (_light.TryGetLight(component.Owner, out var pointLightComponent))
+ if (_light.TryGetLight(generator, out var pointLightComponent))
{
- _light.SetEnabled(component.Owner, component.Connections.Count > 0, pointLightComponent);
+ _light.SetEnabled(generator, generator.Comp.Connections.Count > 0, pointLightComponent);
}
}
/// <summary>
/// Checks to see if this or the other gens connected to a new grid. If they did, remove connection.
/// </summary>
- public void GridCheck(EntityUid uid, ContainmentFieldGeneratorComponent component)
+ public void GridCheck(Entity<ContainmentFieldGeneratorComponent> generator)
{
var xFormQuery = GetEntityQuery<TransformComponent>();
- foreach (var (_, generators) in component.Connections)
+ foreach (var (_, generators) in generator.Comp.Connections)
{
- var gen1ParentGrid = xFormQuery.GetComponent(component.Owner).ParentUid;
- var gent2ParentGrid = xFormQuery.GetComponent(generators.Item1.Owner).ParentUid;
+ var gen1ParentGrid = xFormQuery.GetComponent(generator).ParentUid;
+ var gent2ParentGrid = xFormQuery.GetComponent(generators.Item1).ParentUid;
if (gen1ParentGrid != gent2ParentGrid)
- RemoveConnections(uid, component);
+ RemoveConnections(generator);
}
}
/// Check if a fields power falls between certain ranges to update the field gen visual for power.
/// </summary>
/// <param name="power"></param>
- /// <param name="component"></param>
- private void ChangePowerVisualizer(int power, ContainmentFieldGeneratorComponent component)
+ /// <param name="generator"></param>
+ private void ChangePowerVisualizer(int power, Entity<ContainmentFieldGeneratorComponent> generator)
{
- _visualizer.SetData(component.Owner, ContainmentFieldGeneratorVisuals.PowerLight, component.PowerBuffer switch {
- <=0 => PowerLevelVisuals.NoPower,
- >=25 => PowerLevelVisuals.HighPower,
- _ => (component.PowerBuffer < component.PowerMinimum) ? PowerLevelVisuals.LowPower : PowerLevelVisuals.MediumPower
+ var component = generator.Comp;
+ _visualizer.SetData(generator, ContainmentFieldGeneratorVisuals.PowerLight, component.PowerBuffer switch
+ {
+ <= 0 => PowerLevelVisuals.NoPower,
+ >= 25 => PowerLevelVisuals.HighPower,
+ _ => (component.PowerBuffer < component.PowerMinimum)
+ ? PowerLevelVisuals.LowPower
+ : PowerLevelVisuals.MediumPower
});
}
/// <summary>
/// Check if a field has any or no connections and if it's enabled to toggle the field level light
/// </summary>
- /// <param name="component"></param>
- private void ChangeFieldVisualizer(ContainmentFieldGeneratorComponent component)
+ /// <param name="generator"></param>
+ private void ChangeFieldVisualizer(Entity<ContainmentFieldGeneratorComponent> generator)
{
- _visualizer.SetData(component.Owner, ContainmentFieldGeneratorVisuals.FieldLight, component.Connections.Count switch {
+ _visualizer.SetData(generator, ContainmentFieldGeneratorVisuals.FieldLight, generator.Comp.Connections.Count switch
+ {
>1 => FieldLevelVisuals.MultipleFields,
1 => FieldLevelVisuals.OneField,
- _ => component.Enabled ? FieldLevelVisuals.On : FieldLevelVisuals.NoLevel
+ _ => generator.Comp.Enabled ? FieldLevelVisuals.On : FieldLevelVisuals.NoLevel
});
}
- private void ChangeOnLightVisualizer(ContainmentFieldGeneratorComponent component)
+ private void ChangeOnLightVisualizer(Entity<ContainmentFieldGeneratorComponent> generator)
{
- _visualizer.SetData(component.Owner, ContainmentFieldGeneratorVisuals.OnLight, component.IsConnected);
+ _visualizer.SetData(generator, ContainmentFieldGeneratorVisuals.OnLight, generator.Comp.IsConnected);
}
#endregion
{
var otherBody = args.OtherEntity;
- if (TryComp<SpaceGarbageComponent>(otherBody, out var garbage))
+ if (HasComp<SpaceGarbageComponent>(otherBody))
{
- _popupSystem.PopupEntity(Loc.GetString("comp-field-vaporized", ("entity", otherBody)), component.Owner, PopupType.LargeCaution);
- QueueDel(garbage.Owner);
+ _popupSystem.PopupEntity(Loc.GetString("comp-field-vaporized", ("entity", otherBody)), uid, PopupType.LargeCaution);
+ QueueDel(otherBody);
}
if (TryComp<PhysicsComponent>(otherBody, out var physics) && physics.Mass <= component.MaxMass && physics.Hard)
{
- var fieldDir = Transform(component.Owner).WorldPosition;
+ var fieldDir = Transform(uid).WorldPosition;
var playerDir = Transform(otherBody).WorldPosition;
_throwing.TryThrow(otherBody, playerDir-fieldDir, strength: component.ThrowForce);
var mapPos = xform.MapPosition;
var box = Box2.CenteredAround(mapPos.Position, new Vector2(range, range));
var circle = new Circle(mapPos.Position, range);
- foreach (var grid in _mapMan.FindGridsIntersecting(mapPos.MapId, box))
- { // TODO: Remover grid.Owner when this iterator returns entityuids as well.
- AttemptConsumeTiles(uid, grid.GetTilesIntersecting(circle), grid.Owner, grid, eventHorizon);
+ var grids = new List<Entity<MapGridComponent>>();
+ _mapMan.FindGridsIntersecting(mapPos.MapId, box, ref grids);
+
+ foreach (var grid in grids)
+ {
+ // TODO: Remover grid.Owner when this iterator returns entityuids as well.
+ AttemptConsumeTiles(uid, grid.Comp.GetTilesIntersecting(circle), grid, grid, eventHorizon);
}
}
+using Content.Server.Singularity.Components;
+using Content.Shared.Ghost;
+using Content.Shared.Singularity.EntitySystems;
using Robust.Shared.Map;
using Robust.Shared.Map.Components;
using Robust.Shared.Physics;
using Robust.Shared.Physics.Systems;
using Robust.Shared.Timing;
-using Content.Shared.Singularity.EntitySystems;
-using Content.Server.Singularity.Components;
-using Content.Shared.Ghost;
-
namespace Content.Server.Singularity.EntitySystems;
/// <summary>
if(!_timing.IsFirstTimePredicted)
return;
- foreach(var (gravWell, xform) in EntityManager.EntityQuery<GravityWellComponent, TransformComponent>())
+ var query = EntityQueryEnumerator<GravityWellComponent, TransformComponent>();
+ while (query.MoveNext(out var uid, out var gravWell, out var xform))
{
var curTime = _timing.CurTime;
if (gravWell.NextPulseTime <= curTime)
- Update(gravWell.Owner, curTime - gravWell.LastPulseTime, gravWell, xform);
+ Update(uid, curTime - gravWell.LastPulseTime, gravWell, xform);
}
}
-using Robust.Shared.GameStates;
-using Robust.Shared.Player;
-using Robust.Shared.Timing;
-using Robust.Server.GameStates;
-
-using Content.Shared.Singularity.Components;
-using Content.Shared.Singularity.EntitySystems;
-using Content.Shared.Singularity.Events;
-
using Content.Server.Physics.Components;
using Content.Server.Singularity.Components;
using Content.Server.Singularity.Events;
+using Content.Shared.Singularity.Components;
+using Content.Shared.Singularity.EntitySystems;
+using Content.Shared.Singularity.Events;
+using Robust.Server.GameStates;
+using Robust.Shared.GameStates;
+using Robust.Shared.Player;
+using Robust.Shared.Timing;
namespace Content.Server.Singularity.EntitySystems;
if(!_timing.IsFirstTimePredicted)
return;
- foreach(var singularity in EntityManager.EntityQuery<SingularityComponent>())
+ var query = EntityQueryEnumerator<SingularityComponent>();
+ while (query.MoveNext(out var uid, out var singularity))
{
var curTime = _timing.CurTime;
if (singularity.NextUpdateTime <= curTime)
- Update(singularity.Owner, curTime - singularity.LastUpdateTime, singularity);
+ Update(uid, curTime - singularity.LastUpdateTime, singularity);
}
}
return;
singularity.Energy = value;
- SetLevel(uid, value switch {
- >= 2400 => 6,
- >= 1600 => 5,
- >= 900 => 4,
- >= 300 => 3,
- >= 200 => 2,
- > 0 => 1,
- _ => 0
+ SetLevel(uid, value switch
+ {
+ >= 2400 => 6,
+ >= 1600 => 5,
+ >= 900 => 4,
+ >= 300 => 3,
+ >= 200 => 2,
+ > 0 => 1,
+ _ => 0
}, singularity);
}
MetaDataComponent? metaData = null;
if (Resolve(uid, ref metaData) && metaData.EntityLifeStage <= EntityLifeStage.Initializing)
- _audio.Play(comp.FormationSound, Filter.Pvs(comp.Owner), comp.Owner, true);
+ _audio.Play(comp.FormationSound, Filter.Pvs(uid), uid, true);
- comp.AmbientSoundStream = _audio.Play(comp.AmbientSound, Filter.Pvs(comp.Owner), comp.Owner, true);
+ comp.AmbientSoundStream = _audio.Play(comp.AmbientSound, Filter.Pvs(uid), uid, true);
UpdateSingularityLevel(uid, comp);
}
MetaDataComponent? metaData = null;
if (Resolve(uid, ref metaData) && metaData.EntityLifeStage >= EntityLifeStage.Terminating)
- _audio.Play(comp.DissipationSound, Filter.Pvs(comp.Owner), comp.Owner, true);
+ _audio.Play(comp.DissipationSound, Filter.Pvs(uid), uid, true);
}
/// <summary>
// Should be slightly more efficient than checking literally everything we consume for a singularity component and doing the reverse.
if (EntityManager.TryGetComponent<SingularityComponent>(args.EventHorizonUid, out var singulo))
{
- AdjustEnergy(singulo.Owner, comp.Energy, singularity: singulo);
+ AdjustEnergy(uid, comp.Energy, singularity: singulo);
SetEnergy(uid, 0.0f, comp);
}
}
/// <summary>
/// Queue of panels to update each cycle.
/// </summary>
- private readonly Queue<SolarPanelComponent> _updateQueue = new();
-
+ private readonly Queue<Entity<SolarPanelComponent>> _updateQueue = new();
public override void Initialize()
{
if (_updateQueue.Count > 0)
{
var panel = _updateQueue.Dequeue();
- if (panel.Running)
+ if (panel.Comp.Running)
UpdatePanelCoverage(panel);
}
else
{
TotalPanelPower = 0;
- foreach (var (panel, xform) in EntityManager.EntityQuery<SolarPanelComponent, TransformComponent>())
+
+ var query = EntityQueryEnumerator<SolarPanelComponent, TransformComponent>();
+ while (query.MoveNext(out var uid, out var panel, out var xform))
{
TotalPanelPower += panel.MaxSupply * panel.Coverage;
xform.WorldRotation = TargetPanelRotation;
- _updateQueue.Enqueue(panel);
+ _updateQueue.Enqueue((uid, panel));
}
}
}
- private void UpdatePanelCoverage(SolarPanelComponent panel)
+ private void UpdatePanelCoverage(Entity<SolarPanelComponent> panel)
{
- EntityUid entity = panel.Owner;
+ var entity = panel.Owner;
var xform = EntityManager.GetComponent<TransformComponent>(entity);
// So apparently, and yes, I *did* only find this out later,
}
// Total coverage calculated; apply it to the panel.
- panel.Coverage = coverage;
- UpdateSupply((panel).Owner, panel);
+ panel.Comp.Coverage = coverage;
+ UpdateSupply(panel, panel);
}
public void UpdateSupply(
// check if entity was actually used as clothing
// not just taken in pockets or something
var isCorrectSlot = clothing.Slots.HasFlag(args.SlotFlags);
- if (!isCorrectSlot) return;
+ if (!isCorrectSlot)
+ return;
// does the user already has this accent?
var componentType = _componentFactory.GetRegistration(component.Accent).Type;
- if (EntityManager.HasComponent(args.Equipee, componentType)) return;
+ if (HasComp(args.Equipee, componentType))
+ return;
// add accent to the user
var accentComponent = (Component) _componentFactory.GetComponent(componentType);
- accentComponent.Owner = args.Equipee;
- EntityManager.AddComponent(args.Equipee, accentComponent);
+ AddComp(args.Equipee, accentComponent);
// snowflake case for replacement accent
if (accentComponent is ReplacementAccentComponent rep)
foreach (var gridUid in dataComponent.Grids)
{
- if (!_mapManager.TryGetGrid(gridUid, out var grid) ||
+ if (!TryComp(gridUid, out MapGridComponent? grid) ||
!xformQuery.TryGetComponent(gridUid, out var xform))
continue;
if (xform.GridUid == EntityUid.Invalid)
{
- Logger.Debug("A");
+ Log.Debug("A");
return null;
}
public List<EntityUid> GetStations()
{
- return EntityQuery<StationDataComponent>().Select(x => x.Owner).ToList();
+ var stations = new List<EntityUid>();
+ var query = EntityQueryEnumerator<StationDataComponent>();
+ while (query.MoveNext(out var uid, out _))
+ {
+ stations.Add(uid);
+ }
+
+ return stations;
}
public HashSet<EntityUid> GetStationsSet()
{
- return EntityQuery<StationDataComponent>().Select(x => x.Owner).ToHashSet();
+ var stations = new HashSet<EntityUid>();
+ var query = EntityQueryEnumerator<StationDataComponent>();
+ while (query.MoveNext(out var uid, out _))
+ {
+ stations.Add(uid);
+ }
+
+ return stations;
}
/// <summary>
-using System.Linq;
-using Content.Server.GameTicking.Rules.Components;
+using Content.Server.GameTicking.Rules.Components;
using Content.Server.Resist;
using Content.Server.Station.Components;
using Content.Server.StationEvents.Components;
{
base.Started(uid, component, gameRule, args);
- var targets = EntityQuery<EntityStorageComponent, ResistLockerComponent>().ToList();
+ var targets = new List<EntityUid>();
+ var query = EntityQueryEnumerator<EntityStorageComponent, ResistLockerComponent>();
+ while (query.MoveNext(out var storageUid, out _, out _))
+ {
+ targets.Add(storageUid);
+ }
+
RobustRandom.Shuffle(targets);
- foreach (var target in targets)
+ foreach (var potentialLink in targets)
{
- var potentialLink = target.Item1.Owner;
-
if (HasComp<AccessReaderComponent>(potentialLink) ||
HasComp<BluespaceLockerComponent>(potentialLink) ||
!HasComp<StationMemberComponent>(potentialLink.ToCoordinates().GetGridUid(EntityManager)))
-using System.Linq;
-using Content.Server.GameTicking.Rules.Components;
+using Content.Server.GameTicking.Rules.Components;
using Content.Server.Power.Components;
using Content.Server.Power.EntitySystems;
using Content.Server.Station.Components;
using Content.Server.StationEvents.Components;
using JetBrains.Annotations;
-using Robust.Shared.Random;
namespace Content.Server.StationEvents.Events;
if (!TryGetRandomStation(out var chosenStation))
return;
- var stationApcs = new List<ApcComponent>();
- foreach (var (apc, transform) in EntityQuery<ApcComponent, TransformComponent>())
+ var stationApcs = new List<Entity<ApcComponent>>();
+ var query = EntityQueryEnumerator<ApcComponent, TransformComponent>();
+ while (query.MoveNext(out var apcUid, out var apc, out var xform))
{
- if (apc.MainBreakerEnabled && CompOrNull<StationMemberComponent>(transform.GridUid)?.Station == chosenStation)
+ if (apc.MainBreakerEnabled && CompOrNull<StationMemberComponent>(xform.GridUid)?.Station == chosenStation)
{
- stationApcs.Add(apc);
+ stationApcs.Add((apcUid, apc));
}
}
for (var i = 0; i < toDisable; i++)
{
- _apcSystem.ApcToggleBreaker(stationApcs[i].Owner, stationApcs[i]);
+ _apcSystem.ApcToggleBreaker(stationApcs[i], stationApcs[i]);
}
}
}
using System.Numerics;
using Content.Server.GameTicking.Rules.Components;
using Content.Server.StationEvents.Components;
-using Robust.Shared.Spawners;
using Robust.Shared.Map;
+using Robust.Shared.Map.Components;
using Robust.Shared.Physics.Components;
using Robust.Shared.Physics.Systems;
-using TimedDespawnComponent = Robust.Shared.Spawners.TimedDespawnComponent;
+using Robust.Shared.Spawners;
namespace Content.Server.StationEvents.Events
{
Box2? playableArea = null;
var mapId = GameTicker.DefaultMap;
- foreach (var grid in MapManager.GetAllMapGrids(mapId))
+ var query = AllEntityQuery<MapGridComponent, TransformComponent>();
+ while (query.MoveNext(out var gridId, out _, out var xform))
{
- var aabb = _physics.GetWorldAABB(grid.Owner);
+ if (xform.MapID != mapId)
+ continue;
+
+ var aabb = _physics.GetWorldAABB(gridId);
playableArea = playableArea?.Union(aabb) ?? aabb;
}
+using System.Threading;
+using Content.Server.GameTicking.Rules.Components;
using Content.Server.Power.Components;
+using Content.Server.Power.EntitySystems;
+using Content.Server.Station.Components;
+using Content.Server.StationEvents.Components;
using JetBrains.Annotations;
using Robust.Shared.Audio;
using Robust.Shared.Player;
using Robust.Shared.Utility;
-using System.Threading;
-using Content.Server.Power.EntitySystems;
using Timer = Robust.Shared.Timing.Timer;
-using System.Linq;
-using Content.Server.GameTicking.Rules.Components;
-using Robust.Shared.Random;
-using Content.Server.Station.Components;
-using Content.Server.StationEvents.Components;
namespace Content.Server.StationEvents.Events
{
if (!TryGetRandomStation(out var chosenStation))
return;
- foreach (var (apc, transform) in EntityQuery<ApcComponent, TransformComponent>(true))
+ var query = AllEntityQuery<ApcComponent, TransformComponent>();
+ while (query.MoveNext(out var apcUid ,out var apc, out var transform))
{
if (apc.MainBreakerEnabled && CompOrNull<StationMemberComponent>(transform.GridUid)?.Station == chosenStation)
- component.Powered.Add(apc.Owner);
+ component.Powered.Add(apcUid);
}
RobustRandom.Shuffle(component.Powered);
using System.Linq;
-using Content.Server.Chat.Systems;
using Content.Server.GameTicking.Rules.Components;
using Content.Server.Ghost.Roles.Components;
-using Content.Server.Station.Systems;
using Content.Server.StationEvents.Components;
namespace Content.Server.StationEvents.Events;
HashSet<EntityUid> stationsToNotify = new();
var mod = GetSeverityModifier();
- var targetList = EntityQuery<SentienceTargetComponent>().ToList();
+ var targetList = new List<Entity<SentienceTargetComponent>>();
+ var query = EntityQueryEnumerator<SentienceTargetComponent>();
+ while (query.MoveNext(out var targetUid, out var target))
+ {
+ targetList.Add((targetUid, target));
+ }
+
RobustRandom.Shuffle(targetList);
var toMakeSentient = (int) (RobustRandom.Next(2, 5) * Math.Sqrt(mod));
if (toMakeSentient-- == 0)
break;
- RemComp<SentienceTargetComponent>(target.Owner);
- var ghostRole = EnsureComp<GhostRoleComponent>(target.Owner);
- EnsureComp<GhostTakeoverAvailableComponent>(target.Owner);
- ghostRole.RoleName = MetaData(target.Owner).EntityName;
+ RemComp<SentienceTargetComponent>(target);
+ var ghostRole = EnsureComp<GhostRoleComponent>(target);
+ EnsureComp<GhostTakeoverAvailableComponent>(target);
+ ghostRole.RoleName = MetaData(target).EntityName;
ghostRole.RoleDescription = Loc.GetString("station-event-random-sentience-role-description", ("name", ghostRole.RoleName));
- groups.Add(Loc.GetString(target.FlavorKind));
+ groups.Add(Loc.GetString(target.Comp.FlavorKind));
}
if (groups.Count == 0)
foreach (var target in targetList)
{
- var station = StationSystem.GetOwningStation(target.Owner);
- if(station == null) continue;
+ var station = StationSystem.GetOwningStation(target);
+ if(station == null)
+ continue;
stationsToNotify.Add((EntityUid) station);
}
foreach (var station in stationsToNotify)
if (component.BluespaceLinks.Count < component.MinBluespaceLinks)
{
// Get an shuffle the list of all EntityStorages
- var storages = EntityQuery<EntityStorageComponent>().ToArray();
+ var storages = new List<Entity<EntityStorageComponent>>();
+ var query = EntityQueryEnumerator<EntityStorageComponent>();
+ while (query.MoveNext(out var uid, out var storage))
+ {
+ storages.Add((uid, storage));
+ }
+
_robustRandom.Shuffle(storages);
// Add valid candidates till MinBluespaceLinks is met
+using System.Linq;
using Content.Server.Storage.Components;
using Content.Shared.Audio;
+using Content.Shared.Storage.Components;
using Robust.Shared.Audio;
using Robust.Shared.Player;
using Robust.Shared.Random;
-using System.Linq;
-using Content.Shared.Storage.Components;
namespace Content.Server.Storage.EntitySystems;
if (storage.Open || storage.Contents.ContainedEntities.Count <= 0)
return;
- var lockerQuery = EntityQuery<EntityStorageComponent>().ToList();
- lockerQuery.Remove(storage);
+ var lockers = new List<Entity<EntityStorageComponent>>();
+ var query = EntityQueryEnumerator<EntityStorageComponent>();
+ while (query.MoveNext(out var storageUid, out var storageComp))
+ {
+ lockers.Add((storageUid, storageComp));
+ }
+
+ lockers.RemoveAll(e => e.Owner == uid);
- if (lockerQuery.Count == 0)
+ if (lockers.Count == 0)
return;
- var lockerEnt = _random.Pick(lockerQuery).Owner;
+ var lockerEnt = _random.Pick(lockers).Owner;
foreach (var entity in storage.Contents.ContainedEntities.ToArray())
{
using Content.Shared.Storage.EntitySystems;
using Content.Shared.Tools.Systems;
using Content.Shared.Verbs;
+using Robust.Server.GameObjects;
using Robust.Shared.Containers;
using Robust.Shared.GameStates;
using Robust.Shared.Map;
[Dependency] private readonly ConstructionSystem _construction = default!;
[Dependency] private readonly AtmosphereSystem _atmos = default!;
[Dependency] private readonly IMapManager _map = default!;
+ [Dependency] private readonly MapSystem _mapSystem = default!;
public override void Initialize()
{
{
var targetCoordinates = new EntityCoordinates(uid, component.EnteringOffset).ToMap(EntityManager, TransformSystem);
- if (_map.TryFindGridAt(targetCoordinates, out _, out var grid))
+ if (_map.TryFindGridAt(targetCoordinates, out var gridId, out var grid))
{
- return grid.GetTileRef(targetCoordinates);
+ return _mapSystem.GetTileRef(gridId, grid, targetCoordinates);
}
return null;
+using System.Linq;
using Content.Server.Storage.Components;
using Content.Shared.Database;
using Content.Shared.Hands.EntitySystems;
+using Content.Shared.Storage;
using Content.Shared.Verbs;
using Robust.Shared.Containers;
using Robust.Shared.Random;
-using System.Linq;
-using Content.Shared.Storage;
namespace Content.Server.Storage.EntitySystems;
var picked = _random.Pick(entities);
// if it fails to go into a hand of the user, will be on the storage
- _container.AttachParentToContainerOrGrid(Transform(picked));
+ _container.AttachParentToContainerOrGrid((picked, Transform(picked)));
// TODO: try to put in hands, failing that put it on the storage
_hands.TryPickupAnyHand(user, picked);
using Content.Shared.Database;
using Content.Shared.Hands.EntitySystems;
using Content.Shared.Interaction.Events;
-using Content.Shared.Storage;
using Robust.Shared.Audio;
using Robust.Shared.Map;
using Robust.Shared.Player;
foreach (var proto in spawnEntities)
{
entityToPlaceInHands = Spawn(proto, coords);
- _adminLogger.Add(LogType.EntitySpawn, LogImpact.Low, $"{ToPrettyString(args.User)} used {ToPrettyString(component.Owner)} which spawned {ToPrettyString(entityToPlaceInHands.Value)}");
+ _adminLogger.Add(LogType.EntitySpawn, LogImpact.Low, $"{ToPrettyString(args.User)} used {ToPrettyString(uid)} which spawned {ToPrettyString(entityToPlaceInHands.Value)}");
}
if (component.Sound != null)
}
}
- private void OnStripButtonPressed(EntityUid target, StrippableComponent component, StrippingSlotButtonPressed args)
+ private void OnStripButtonPressed(Entity<StrippableComponent> strippable, ref StrippingSlotButtonPressed args)
{
if (args.Session.AttachedEntity is not {Valid: true} user ||
!TryComp<HandsComponent>(user, out var userHands))
if (args.IsHand)
{
- StripHand(target, user, args.Slot, component, userHands);
+ StripHand(user, args.Slot, strippable, userHands);
return;
}
- if (!TryComp<InventoryComponent>(target, out var inventory))
+ if (!TryComp<InventoryComponent>(strippable, out var inventory))
return;
- var hasEnt = _inventorySystem.TryGetSlotEntity(target, args.Slot, out var held, inventory);
+ var hasEnt = _inventorySystem.TryGetSlotEntity(strippable, args.Slot, out var held, inventory);
if (userHands.ActiveHandEntity != null && !hasEnt)
- PlaceActiveHandItemInInventory(user, target, userHands.ActiveHandEntity.Value, args.Slot, component);
+ PlaceActiveHandItemInInventory(user, strippable, userHands.ActiveHandEntity.Value, args.Slot, strippable);
else if (userHands.ActiveHandEntity == null && hasEnt)
- TakeItemFromInventory(user, target, held!.Value, args.Slot, component);
+ TakeItemFromInventory(user, strippable, held!.Value, args.Slot, strippable);
}
- private void StripHand(EntityUid target, EntityUid user, string handId, StrippableComponent component, HandsComponent userHands)
+ private void StripHand(EntityUid user, string handId, Entity<StrippableComponent> target, HandsComponent userHands)
{
if (!_handsSystem.TryGetHand(target, handId, out var hand))
return;
}
if (userHands.ActiveHandEntity != null && hand.HeldEntity == null)
- PlaceActiveHandItemInHands(user, target, userHands.ActiveHandEntity.Value, handId, component);
+ PlaceActiveHandItemInHands(user, target, userHands.ActiveHandEntity.Value, handId, target);
else if (userHands.ActiveHandEntity == null && hand.HeldEntity != null)
- TakeItemFromHands(user,target, hand.HeldEntity.Value, handId, component);
+ TakeItemFromHands(user, target, hand.HeldEntity.Value, handId, target);
}
- public override void StartOpeningStripper(EntityUid user, StrippableComponent component, bool openInCombat = false)
+ public override void StartOpeningStripper(EntityUid user, Entity<StrippableComponent> strippable, bool openInCombat = false)
{
- base.StartOpeningStripper(user, component, openInCombat);
+ base.StartOpeningStripper(user, strippable, openInCombat);
if (TryComp<CombatModeComponent>(user, out var mode) && mode.IsInCombatMode && !openInCombat)
return;
if (TryComp<ActorComponent>(user, out var actor))
{
- if (_userInterfaceSystem.SessionHasOpenUi(component.Owner, StrippingUiKey.Key, actor.PlayerSession))
+ if (_userInterfaceSystem.SessionHasOpenUi(strippable, StrippingUiKey.Key, actor.PlayerSession))
return;
- _userInterfaceSystem.TryOpen(component.Owner, StrippingUiKey.Key, actor.PlayerSession);
+ _userInterfaceSystem.TryOpen(strippable, StrippingUiKey.Key, actor.PlayerSession);
}
}
if (args.Hands == null || !args.CanAccess || !args.CanInteract || args.Target == args.User)
return;
- if (!EntityManager.TryGetComponent(args.User, out ActorComponent? actor))
+ if (!HasComp<ActorComponent>(args.User))
return;
Verb verb = new()
{
Text = Loc.GetString("strip-verb-get-data-text"),
Icon = new SpriteSpecifier.Texture(new ("/Textures/Interface/VerbIcons/outfit.svg.192dpi.png")),
- Act = () => StartOpeningStripper(args.User, component, true),
+ Act = () => StartOpeningStripper(args.User, (uid, component), true),
};
args.Verbs.Add(verb);
}
{
Text = Loc.GetString("strip-verb-get-data-text"),
Icon = new SpriteSpecifier.Texture(new ("/Textures/Interface/VerbIcons/outfit.svg.192dpi.png")),
- Act = () => StartOpeningStripper(args.User, component, true),
+ Act = () => StartOpeningStripper(args.User, (uid, component), true),
Category = VerbCategory.Examine,
};
if (args.Target == args.User)
return;
- if (!TryComp<ActorComponent>(args.User, out var actor))
+ if (!HasComp<ActorComponent>(args.User))
return;
- StartOpeningStripper(args.User, component);
+ StartOpeningStripper(args.User, (uid, component));
}
/// <summary>
_adminLogger.Add(LogType.Stripping, LogImpact.Low, $"{ToPrettyString(user):user} is trying to place the item {ToPrettyString(held):item} in {ToPrettyString(target):target}'s {slot} slot");
var result = await _doAfter.WaitDoAfter(doAfterArgs);
- if (result != DoAfterStatus.Finished) return;
+ if (result != DoAfterStatus.Finished)
+ return;
DebugTools.Assert(userHands.ActiveHand?.HeldEntity == held);
EntityUid target,
EntityUid item,
string slot,
- StrippableComponent component)
+ Entity<StrippableComponent> strippable)
{
bool Check()
{
_popup.PopupEntity(Loc.GetString("strippable-component-alert-owner-hidden", ("slot", slot)), target,
target, PopupType.Large);
}
- else if (_inventorySystem.TryGetSlotEntity(component.Owner, slot, out var slotItem))
+ else if (_inventorySystem.TryGetSlotEntity(strippable, slot, out var slotItem))
{
_popup.PopupEntity(Loc.GetString("strippable-component-alert-owner", ("user", Identity.Entity(user, EntityManager)), ("item", slotItem)), target,
target, PopupType.Large);
_adminLogger.Add(LogType.Stripping, LogImpact.Low, $"{ToPrettyString(user):user} is trying to strip the item {ToPrettyString(item):item} from {ToPrettyString(target):target}");
var result = await _doAfter.WaitDoAfter(doAfterArgs);
- if (result != DoAfterStatus.Finished) return;
+ if (result != DoAfterStatus.Finished)
+ return;
- if (!_inventorySystem.TryUnequip(user, component.Owner, slot))
+ if (!_inventorySystem.TryUnequip(user, strippable, slot))
return;
// Raise a dropped event, so that things like gas tank internals properly deactivate when stripping
/// <summary>
/// Takes an item from a hand and places it in the user's active hand.
/// </summary>
- private async void TakeItemFromHands(EntityUid user, EntityUid target, EntityUid item, string handName, StrippableComponent component)
+ private async void TakeItemFromHands(EntityUid user, EntityUid target, EntityUid item, string handName, Entity<StrippableComponent> strippable)
{
var hands = Comp<HandsComponent>(target);
var userHands = Comp<HandsComponent>(user);
return true;
}
- var userEv = new BeforeStripEvent(component.HandStripDelay);
+ var userEv = new BeforeStripEvent(strippable.Comp.HandStripDelay);
RaiseLocalEvent(user, userEv);
var ev = new BeforeGettingStrippedEvent(userEv.Time, userEv.Stealth);
RaiseLocalEvent(target, ev);
_popup.PopupEntity(
Loc.GetString("strippable-component-alert-owner",
("user", Identity.Entity(user, EntityManager)), ("item", item)),
- component.Owner,
- component.Owner);
+ strippable.Owner,
+ strippable.Owner);
}
_adminLogger.Add(LogType.Stripping, LogImpact.Low,
$"{ToPrettyString(user):user} is trying to strip the item {ToPrettyString(item):item} from {ToPrettyString(target):target}");
var result = await _doAfter.WaitDoAfter(doAfterArgs);
- if (result != DoAfterStatus.Finished) return;
+ if (result != DoAfterStatus.Finished)
+ return;
_handsSystem.TryDrop(target, item, checkActionBlocker: false, handsComp: hands);
_handsSystem.PickupOrDrop(user, item, handsComp: userHands);
using System.Linq;
-using Content.Server.Chat.Systems;
using Content.Server.DeviceNetwork;
using Content.Server.DeviceNetwork.Systems;
using Content.Server.Power.Components;
using Content.Server.UserInterface;
-using Content.Server.Wires;
-using Content.Shared.Interaction;
-using Content.Shared.Speech;
using Content.Shared.SurveillanceCamera;
using Robust.Server.GameObjects;
-using Robust.Server.Player;
-using Robust.Shared.Prototypes;
-using Robust.Shared.Random;
-using Robust.Shared.Timing;
namespace Content.Server.SurveillanceCamera;
public override void Update(float frameTime)
{
- foreach (var (_, monitor) in EntityQuery<ActiveSurveillanceCameraMonitorComponent, SurveillanceCameraMonitorComponent>())
+ var query = EntityQueryEnumerator<ActiveSurveillanceCameraMonitorComponent, SurveillanceCameraMonitorComponent>();
+ while (query.MoveNext(out var uid, out _, out var monitor))
{
- if (Paused(monitor.Owner))
+ if (Paused(uid))
{
continue;
}
monitor.LastHeartbeatSent += frameTime;
- SendHeartbeat(monitor.Owner, monitor);
+ SendHeartbeat(uid, monitor);
monitor.LastHeartbeat += frameTime;
if (monitor.LastHeartbeat > _maxHeartbeatTime)
{
- DisconnectCamera(monitor.Owner, true, monitor);
- EntityManager.RemoveComponent<ActiveSurveillanceCameraMonitorComponent>(monitor.Owner);
+ DisconnectCamera(uid, true, monitor);
+ EntityManager.RemoveComponent<ActiveSurveillanceCameraMonitorComponent>(uid);
}
}
}
using Content.Server.Popups;
using Content.Server.Tabletop.Components;
-using Content.Shared.Examine;
using Content.Shared.Hands.Components;
using Content.Shared.Interaction;
using Content.Shared.Item;
{
base.Update(frameTime);
- foreach (var gamer in EntityManager.EntityQuery<TabletopGamerComponent>())
+ var query = EntityQueryEnumerator<TabletopGamerComponent>();
+ while (query.MoveNext(out var uid, out var gamer))
{
- if (!EntityManager.EntityExists(gamer.Tabletop))
+ if (!Exists(gamer.Tabletop))
continue;
- if (!EntityManager.TryGetComponent(gamer.Owner, out ActorComponent? actor))
+ if (!TryComp(uid, out ActorComponent? actor))
{
- EntityManager.RemoveComponent<TabletopGamerComponent>(gamer.Owner);
+ EntityManager.RemoveComponent<TabletopGamerComponent>(uid);
return;
}
- var gamerUid = (gamer).Owner;
-
- if (actor.PlayerSession.Status != SessionStatus.InGame || !CanSeeTable(gamerUid, gamer.Tabletop))
+ if (actor.PlayerSession.Status != SessionStatus.InGame || !CanSeeTable(uid, gamer.Tabletop))
CloseSessionFor(actor.PlayerSession, gamer.Tabletop);
}
}
+using System.Linq;
using Content.Server.Administration.Logs;
using Content.Server.Atmos.Components;
using Content.Server.Atmos.EntitySystems;
using Content.Shared.Rejuvenate;
using Content.Shared.Temperature;
using Robust.Server.GameObjects;
-using System.Linq;
namespace Content.Server.Temperature.Systems;
/// This is done because both AtmosExposed and Flammable call ChangeHeat in the same tick, meaning
/// that we need some mechanism to ensure it doesn't double dip on damage for both calls.
/// </summary>
- public HashSet<TemperatureComponent> ShouldUpdateDamage = new();
+ public HashSet<Entity<TemperatureComponent>> ShouldUpdateDamage = new();
public float UpdateInterval = 1.0f;
if (!ignoreHeatResistance)
{
var ev = new ModifyChangedTemperatureEvent(heatAmount);
- RaiseLocalEvent(uid, ev, false);
+ RaiseLocalEvent(uid, ev);
heatAmount = ev.TemperatureDelta;
}
}
}
- private void EnqueueDamage(EntityUid uid, TemperatureComponent component, OnTemperatureChangeEvent args)
+ private void EnqueueDamage(Entity<TemperatureComponent> temperature, ref OnTemperatureChangeEvent args)
{
- ShouldUpdateDamage.Add(component);
+ ShouldUpdateDamage.Add(temperature);
}
private void ChangeDamage(EntityUid uid, TemperatureComponent temperature)
using Content.Shared.Weapons.Melee.Events;
using Robust.Shared.Audio;
using Robust.Shared.GameStates;
-using Robust.Shared.Utility;
namespace Content.Server.Tools
{
private readonly HashSet<EntityUid> _activeWelders = new();
private const float WelderUpdateTimer = 1f;
- private float _welderTimer = 0f;
+ private float _welderTimer;
public void InitializeWelders()
{
_adminLogger.Add(LogType.Action, LogImpact.Low, $"{ToPrettyString(uid):welder} toggled on");
var ev = new WelderToggledEvent(true);
- RaiseLocalEvent(welder.Owner, ev, false);
+ RaiseLocalEvent(uid, ev);
var hotEvent = new IsHotEvent() {IsHot = true};
RaiseLocalEvent(uid, hotEvent);
_adminLogger.Add(LogType.Action, LogImpact.Low, $"{ToPrettyString(uid):welder} toggled off");
var ev = new WelderToggledEvent(false);
- RaiseLocalEvent(uid, ev, false);
+ RaiseLocalEvent(uid, ev);
var hotEvent = new IsHotEvent() {IsHot = false};
RaiseLocalEvent(uid, hotEvent);
private void OnWelderStartup(EntityUid uid, WelderComponent welder, ComponentStartup args)
{
// TODO: Delete this shit what
- Dirty(welder);
+ Dirty(uid, welder);
}
private void OnWelderIsHotEvent(EntityUid uid, WelderComponent welder, IsHotEvent args)
{
// TODO what
// ????
- Dirty(welder);
+ Dirty(uid, welder);
}
private void OnWelderActivate(EntityUid uid, WelderComponent welder, ActivateInWorldEvent args)
if (solution.GetTotalPrototypeQuantity(welder.FuelReagent) <= FixedPoint2.Zero)
TryTurnWelderOff(tool, null, welder);
- Dirty(welder);
+ Dirty(tool, welder);
}
_welderTimer -= WelderUpdateTimer;
using System.Linq;
-using Content.Server.Store.Systems;
using Content.Server.Storage.EntitySystems;
-using Content.Shared.Store;
+using Content.Server.Store.Systems;
using Content.Shared.FixedPoint;
+using Content.Shared.Store;
using Robust.Shared.Prototypes;
using Robust.Shared.Random;
foreach (var item in content)
{
var ent = EntityManager.SpawnEntity(item.ProductEntity, cords);
- _entityStorage.Insert(ent, component.Owner);
+ _entityStorage.Insert(ent, uid);
}
}
{
base.Update(frameTime);
- foreach (var narcolepsy in EntityQuery<NarcolepsyComponent>())
+ var query = EntityQueryEnumerator<NarcolepsyComponent>();
+ while (query.MoveNext(out var uid, out var narcolepsy))
{
narcolepsy.NextIncidentTime -= frameTime;
// Make sure the sleep time doesn't cut into the time to next incident.
narcolepsy.NextIncidentTime += duration;
- _statusEffects.TryAddStatusEffect<ForcedSleepingComponent>(narcolepsy.Owner, StatusEffectKey,
+ _statusEffects.TryAddStatusEffect<ForcedSleepingComponent>(uid, StatusEffectKey,
TimeSpan.FromSeconds(duration), false);
}
}
+using Content.Server.Polymorph.Systems;
using Content.Server.Xenoarchaeology.XenoArtifacts.Effects.Components;
using Content.Server.Xenoarchaeology.XenoArtifacts.Events;
using Content.Shared.Humanoid;
-using Content.Server.Polymorph.Systems;
using Content.Shared.Mobs.Systems;
-using Content.Shared.Polymorph;
namespace Content.Server.Xenoarchaeology.XenoArtifacts.Effects.Systems;
private void OnActivate(EntityUid uid, PolyArtifactComponent component, ArtifactActivatedEvent args)
{
var xform = Transform(uid);
- foreach (var comp in _lookup.GetComponentsInRange<HumanoidAppearanceComponent>(xform.Coordinates, component.Range))
+ var humanoids = new HashSet<Entity<HumanoidAppearanceComponent>>();
+ _lookup.GetEntitiesInRange(xform.Coordinates, component.Range, humanoids);
+
+ foreach (var comp in humanoids)
{
var target = comp.Owner;
if (_mob.IsAlive(target))
var mobState = GetEntityQuery<MobStateComponent>();
List<EntityCoordinates> allCoords = new();
- List<TransformComponent> toShuffle = new();
+ List<Entity<TransformComponent>> toShuffle = new();
foreach (var ent in _lookup.GetEntitiesInRange(uid, component.Radius, LookupFlags.Dynamic | LookupFlags.Sundries))
{
var xform = Transform(ent);
- toShuffle.Add(xform);
+ toShuffle.Add((ent, xform));
allCoords.Add(xform.Coordinates);
}
public override void Update(float frameTime)
{
base.Update(frameTime);
- var query = EntityManager.EntityQuery<RandomArtifactSpriteComponent, AppearanceComponent>();
- foreach (var (component, appearance) in query)
+
+ var query = EntityQueryEnumerator<RandomArtifactSpriteComponent, AppearanceComponent>();
+ while (query.MoveNext(out var uid, out var component, out var appearance))
{
if (component.ActivationStart == null)
continue;
var timeDif = _time.CurTime - component.ActivationStart.Value;
if (timeDif.Seconds >= component.ActivationTime)
{
- _appearance.SetData(appearance.Owner, SharedArtifactsVisuals.IsActivated, false, appearance);
+ _appearance.SetData(uid, SharedArtifactsVisuals.IsActivated, false, appearance);
component.ActivationStart = null;
}
}
var deathXform = Transform(ev.Target);
- var toActivate = new List<ArtifactDeathTriggerComponent>();
- foreach (var (trigger, xform) in EntityQuery<ArtifactDeathTriggerComponent, TransformComponent>())
+ var toActivate = new List<Entity<ArtifactDeathTriggerComponent>>();
+ var query = EntityQueryEnumerator<ArtifactDeathTriggerComponent, TransformComponent>();
+ while (query.MoveNext(out var uid, out var trigger, out var xform))
{
if (!deathXform.Coordinates.TryDistance(EntityManager, xform.Coordinates, out var distance))
continue;
if (distance > trigger.Range)
continue;
- toActivate.Add(trigger);
+ toActivate.Add((uid, trigger));
}
foreach (var a in toActivate)
{
- _artifact.TryActivateArtifact(a.Owner);
+ _artifact.TryActivateArtifact(a);
}
}
}
public override void Update(float frameTime)
{
base.Update(frameTime);
- List<ArtifactComponent> toUpdate = new();
- foreach (var (trigger, power, artifact) in EntityQuery<ArtifactElectricityTriggerComponent, PowerConsumerComponent, ArtifactComponent>())
+
+ List<Entity<ArtifactComponent>> toUpdate = new();
+ var query = EntityQueryEnumerator<ArtifactElectricityTriggerComponent, PowerConsumerComponent, ArtifactComponent>();
+ while (query.MoveNext(out var uid, out var trigger, out var power, out var artifact))
{
if (power.ReceivedPower <= trigger.MinPower)
continue;
- toUpdate.Add(artifact);
+ toUpdate.Add((uid, artifact));
}
foreach (var a in toUpdate)
{
- _artifactSystem.TryActivateArtifact(a.Owner, null, a);
+ _artifactSystem.TryActivateArtifact(a, null, a);
}
}
{
base.Update(frameTime);
- List<ArtifactComponent> toUpdate = new();
- foreach (var (trigger, artifact, transform) in EntityQuery<ArtifactGasTriggerComponent, ArtifactComponent, TransformComponent>())
+ List<Entity<ArtifactComponent>> toUpdate = new();
+ var query = EntityQueryEnumerator<ArtifactGasTriggerComponent, ArtifactComponent, TransformComponent>();
+ while (query.MoveNext(out var uid, out var trigger, out var artifact, out var transform))
{
- var uid = trigger.Owner;
-
if (trigger.ActivationGas == null)
continue;
if (moles < trigger.ActivationMoles)
continue;
- toUpdate.Add(artifact);
+ toUpdate.Add((uid, artifact));
}
foreach (var a in toUpdate)
{
- _artifactSystem.TryActivateArtifact(a.Owner, null, a);
+ _artifactSystem.TryActivateArtifact(a, null, a);
}
}
}
{
base.Update(frameTime);
- List<ArtifactComponent> toUpdate = new();
- foreach (var (trigger, transform, artifact) in EntityQuery<ArtifactHeatTriggerComponent, TransformComponent, ArtifactComponent>())
+ List<Entity<ArtifactComponent>> toUpdate = new();
+ var query = EntityQueryEnumerator<ArtifactHeatTriggerComponent, TransformComponent, ArtifactComponent>();
+ while (query.MoveNext(out var uid, out var trigger, out var transform, out var artifact))
{
- var uid = trigger.Owner;
var environment = _atmosphereSystem.GetTileMixture(transform.GridUid, transform.MapUid,
_transformSystem.GetGridOrMapTilePosition(uid, transform));
if (environment == null)
if (environment.Temperature < trigger.ActivationTemperature)
continue;
- toUpdate.Add(artifact);
+ toUpdate.Add((uid, artifact));
}
foreach (var a in toUpdate)
{
- _artifactSystem.TryActivateArtifact(a.Owner, null, a);
+ _artifactSystem.TryActivateArtifact(a, null, a);
}
}
List<EntityUid> toActivate = new();
//assume that there's more instruments than artifacts
- foreach (var magboot in EntityQuery<MagbootsComponent>())
+ var query = EntityQueryEnumerator<MagbootsComponent, TransformComponent>();
+ while (query.MoveNext(out var uid, out var magboot, out var magXform))
{
if (!magboot.On)
continue;
- var magXform = Transform(magboot.Owner);
-
foreach (var (trigger, xform) in artifactQuery)
{
if (!magXform.Coordinates.TryDistance(EntityManager, xform.Coordinates, out var distance))
if (distance > trigger.Range)
continue;
- toActivate.Add(trigger.Owner);
+ toActivate.Add(uid);
}
}
var magXform = Transform(ev.Magnet);
var toActivate = new List<EntityUid>();
- foreach (var (artifact, xform) in EntityQuery<ArtifactMagnetTriggerComponent, TransformComponent>())
+ var query = EntityQueryEnumerator<ArtifactMagnetTriggerComponent, TransformComponent>();
+ while (query.MoveNext(out var uid, out var artifact, out var xform))
{
if (!magXform.Coordinates.TryDistance(EntityManager, xform.Coordinates, out var distance))
continue;
if (distance > artifact.Range)
continue;
- toActivate.Add(artifact.Owner);
+ toActivate.Add(uid);
}
foreach (var a in toActivate)
{
[Dependency] private readonly ArtifactSystem _artifact = default!;
+ private readonly List<Entity<ArtifactMusicTriggerComponent, TransformComponent>> _artifacts = new();
+
public override void Update(float frameTime)
{
base.Update(frameTime);
- var artifactQuery = EntityQuery<ArtifactMusicTriggerComponent, TransformComponent>().ToArray();
- if (!artifactQuery.Any())
+ _artifacts.Clear();
+ var artifactQuery = EntityQueryEnumerator<ArtifactMusicTriggerComponent, TransformComponent>();
+ while (artifactQuery.MoveNext(out var uid, out var trigger, out var xform))
+ {
+ _artifacts.Add((uid, trigger, xform));
+ }
+
+ if (!_artifacts.Any())
return;
List<EntityUid> toActivate = new();
+ var query = EntityQueryEnumerator<ActiveInstrumentComponent, TransformComponent>();
//assume that there's more instruments than artifacts
- foreach (var activeinstrument in EntityQuery<ActiveInstrumentComponent>())
+ while (query.MoveNext(out _, out var instXform))
{
- var instXform = Transform(activeinstrument.Owner);
-
- foreach (var (trigger, xform) in artifactQuery)
+ foreach (var (uid, trigger, xform) in _artifacts)
{
if (!instXform.Coordinates.TryDistance(EntityManager, xform.Coordinates, out var distance))
continue;
if (distance > trigger.Range)
continue;
- toActivate.Add(trigger.Owner);
+ toActivate.Add(uid);
}
}
{
base.Update(frameTime);
- List<ArtifactComponent> toUpdate = new();
- foreach (var (trigger, artifact, transform) in EntityQuery<ArtifactPressureTriggerComponent, ArtifactComponent, TransformComponent>())
+ List<Entity<ArtifactComponent>> toUpdate = new();
+ var query = EntityQueryEnumerator<ArtifactPressureTriggerComponent, ArtifactComponent, TransformComponent>();
+ while (query.MoveNext(out var uid, out var trigger, out var artifact, out var transform))
{
- var uid = trigger.Owner;
var environment = _atmosphereSystem.GetTileMixture(transform.GridUid, transform.MapUid,
_transformSystem.GetGridOrMapTilePosition(uid, transform));
var pressure = environment.Pressure;
if (pressure >= trigger.MaxPressureThreshold || pressure <= trigger.MinPressureThreshold)
- toUpdate.Add(artifact);
+ toUpdate.Add((uid, artifact));
}
foreach (var a in toUpdate)
{
- _artifactSystem.TryActivateArtifact(a.Owner, null, a);
+ _artifactSystem.TryActivateArtifact(a, null, a);
}
}
}
{
base.Update(frameTime);
- List<ArtifactComponent> toUpdate = new();
- foreach (var (trigger, artifact) in EntityQuery<ArtifactTimerTriggerComponent, ArtifactComponent>())
+ List<Entity<ArtifactComponent>> toUpdate = new();
+ var query = EntityQueryEnumerator<ArtifactTimerTriggerComponent, ArtifactComponent>();
+ while (query.MoveNext(out var uid, out var trigger, out var artifact))
{
var timeDif = _time.CurTime - trigger.LastActivation;
if (timeDif <= trigger.ActivationRate)
continue;
- toUpdate.Add(artifact);
+ toUpdate.Add((uid, artifact));
trigger.LastActivation = _time.CurTime;
}
foreach (var a in toUpdate)
{
- _artifactSystem.TryActivateArtifact(a.Owner, null, a);
+ _artifactSystem.TryActivateArtifact(a, null, a);
}
}
}
-using System.Diagnostics.CodeAnalysis;
using Content.Shared.Access.Components;
using Content.Shared.Hands.Components;
using Content.Shared.Inventory;
/// Attempt to find an ID card on an entity. This will look in the entity itself, in the entity's hands, and
/// in the entity's inventory.
/// </summary>
- public bool TryFindIdCard(EntityUid uid, [NotNullWhen(true)] out IdCardComponent? idCard)
+ public bool TryFindIdCard(EntityUid uid, out Entity<IdCardComponent> idCard)
{
// check held item?
if (TryComp(uid, out HandsComponent? hands) &&
/// Attempt to get an id card component from an entity, either by getting it directly from the entity, or by
/// getting the contained id from a <see cref="PdaComponent"/>.
/// </summary>
- public bool TryGetIdCard(EntityUid uid, [NotNullWhen(true)] out IdCardComponent? idCard)
+ public bool TryGetIdCard(EntityUid uid, out Entity<IdCardComponent> idCard)
{
- if (TryComp(uid, out idCard))
+ if (TryComp(uid, out IdCardComponent? idCardComp))
+ {
+ idCard = (uid, idCardComp);
return true;
+ }
if (TryComp(uid, out PdaComponent? pda)
- && TryComp(pda.ContainedId, out idCard))
+ && TryComp(pda.ContainedId, out idCardComp))
{
+ idCard = (pda.ContainedId.Value, idCardComp);
return true;
}
+ idCard = default;
return false;
}
}
{
action = null;
- DebugTools.Assert(comp == null || comp.Owner == uid);
+ DebugTools.AssertOwner(uid, comp);
comp ??= EnsureComp<ActionsContainerComponent>(uid);
if (Exists(actionId))
if (action.Container != null)
RemoveAction(actionId, action);
- DebugTools.Assert(comp == null || comp.Owner == uid);
+ DebugTools.AssertOwner(uid, comp);
comp ??= EnsureComp<ActionsContainerComponent>(uid);
if (!comp.Container.Insert(actionId))
{
{
if (result != null)
{
- DebugTools.Assert(result.Owner == uid);
+ DebugTools.AssertOwner(uid, result);
return true;
}
(TryComp(action.Container, out ActionsContainerComponent? containerComp)
&& containerComp.Container.Contains(actionId)));
- DebugTools.Assert(comp == null || comp.Owner == performer);
+ DebugTools.AssertOwner(performer, comp);
comp ??= EnsureComp<ActionsComponent>(performer);
action.AttachedEntity = performer;
comp.Actions.Add(actionId);
if (!Resolve(container, ref containerComp))
return;
- DebugTools.Assert(comp == null || comp.Owner == performer);
+ DebugTools.AssertOwner(performer, comp);
comp ??= EnsureComp<ActionsComponent>(performer);
foreach (var actionId in actions)
/// be erased if there is currently a cooldown for the alert)</param>
public void ShowAlert(EntityUid euid, AlertType alertType, short? severity = null, (TimeSpan, TimeSpan)? cooldown = null)
{
- if (!EntityManager.TryGetComponent(euid, out AlertsComponent? alertsComponent))
+ if (!TryComp(euid, out AlertsComponent? alertsComponent))
return;
if (TryGet(alertType, out var alert))
alertsComponent.Alerts[alert.AlertKey] = new AlertState
{ Cooldown = cooldown, Severity = severity, Type = alertType };
- AfterShowAlert(alertsComponent);
+ AfterShowAlert((euid, alertsComponent));
- Dirty(alertsComponent);
+ Dirty(euid, alertsComponent);
}
else
{
/// </summary>
public void ClearAlertCategory(EntityUid euid, AlertCategory category)
{
- if(!EntityManager.TryGetComponent(euid, out AlertsComponent? alertsComponent))
+ if(!TryComp(euid, out AlertsComponent? alertsComponent))
return;
var key = AlertKey.ForCategory(category);
return;
}
- AfterClearAlert(alertsComponent);
+ AfterClearAlert((euid, alertsComponent));
- Dirty(alertsComponent);
+ Dirty(euid, alertsComponent);
}
/// <summary>
return;
}
- AfterClearAlert(alertsComponent);
+ AfterClearAlert((euid, alertsComponent));
- Dirty(alertsComponent);
+ Dirty(euid, alertsComponent);
}
else
{
/// <summary>
/// Invoked after showing an alert prior to dirtying the component
/// </summary>
- /// <param name="alertsComponent"></param>
- protected virtual void AfterShowAlert(AlertsComponent alertsComponent) { }
+ protected virtual void AfterShowAlert(Entity<AlertsComponent> alerts) { }
/// <summary>
/// Invoked after clearing an alert prior to dirtying the component
/// </summary>
- /// <param name="alertsComponent"></param>
- protected virtual void AfterClearAlert(AlertsComponent alertsComponent) { }
+ protected virtual void AfterClearAlert(Entity<AlertsComponent> alerts) { }
public override void Initialize()
{
if (buckleXform.ParentUid == strapUid && !Terminating(buckleXform.ParentUid))
{
- _container.AttachParentToContainerOrGrid(buckleXform);
+ _container.AttachParentToContainerOrGrid((buckleUid, buckleXform));
var oldBuckledToWorldRot = _transform.GetWorldRotation(strapUid);
_transform.SetWorldRotation(buckleXform, oldBuckledToWorldRot);
[Dependency] private readonly IGameTiming _gameTiming = default!;
[Dependency] private readonly MovementSpeedModifierSystem _movespeed = default!;
- private readonly List<MovespeedModifierMetabolismComponent> _components = new();
+ private readonly List<Entity<MovespeedModifierMetabolismComponent>> _components = new();
public override void Initialize()
{
args.ModifySpeed(component.WalkSpeedModifier, component.SprintSpeedModifier);
}
- private void AddComponent(EntityUid uid, MovespeedModifierMetabolismComponent component, ComponentStartup args)
+ private void AddComponent(Entity<MovespeedModifierMetabolismComponent> metabolism, ref ComponentStartup args)
{
- _components.Add(component);
+ _components.Add(metabolism);
}
public override void Update(float frameTime)
for (var i = _components.Count - 1; i >= 0; i--)
{
- var component = _components[i];
+ var metabolism = _components[i];
- if (component.Deleted)
+ if (metabolism.Comp.Deleted)
{
_components.RemoveAt(i);
continue;
}
- if (component.ModifierTimer > currentTime) continue;
+ if (metabolism.Comp.ModifierTimer > currentTime)
+ continue;
_components.RemoveAt(i);
- EntityManager.RemoveComponent<MovespeedModifierMetabolismComponent>(component.Owner);
+ EntityManager.RemoveComponent<MovespeedModifierMetabolismComponent>(metabolism);
- _movespeed.RefreshMovementSpeedModifiers(component.Owner);
+ _movespeed.RefreshMovementSpeedModifiers(metabolism);
}
}
}
public void AddItemSlot(EntityUid uid, string id, ItemSlot slot, ItemSlotsComponent? itemSlots = null)
{
itemSlots ??= EntityManager.EnsureComponent<ItemSlotsComponent>(uid);
- DebugTools.Assert(itemSlots.Owner == uid);
+ DebugTools.AssertOwner(uid, itemSlots);
if (itemSlots.Slots.TryGetValue(id, out var existing))
{
return new EntityCoordinates(id, x, y);
}
- public static EntityCoordinates ToCoordinates(this MapGridComponent grid, Vector2 offset)
- {
- return ToCoordinates(grid.Owner, offset);
- }
-
public static EntityCoordinates ToCoordinates(this MapGridComponent grid, float x, float y)
{
return ToCoordinates(grid.Owner, x, y);
using Content.Shared.Access.Components;
using Content.Shared.Access.Systems;
using Content.Shared.Damage;
-using Content.Shared.DoAfter;
using Content.Shared.Doors.Components;
using Content.Shared.Hands.Components;
using Content.Shared.Interaction;
using Content.Shared.Physics;
+using Content.Shared.Prying.Components;
using Content.Shared.Stunnable;
using Content.Shared.Tag;
using Robust.Shared.Audio;
using Robust.Shared.Physics.Components;
using Robust.Shared.Physics.Events;
using Robust.Shared.Physics.Systems;
-using Robust.Shared.Serialization;
using Robust.Shared.Timing;
-using Content.Shared.Prying.Components;
namespace Content.Shared.Doors.Systems;
-public abstract partial class SharedDoorSystem : EntitySystem
+public abstract class SharedDoorSystem : EntitySystem
{
[Dependency] protected readonly IGameTiming GameTiming = default!;
[Dependency] protected readonly SharedPhysicsSystem PhysicsSystem = default!;
/// <summary>
/// A set of doors that are currently opening, closing, or just queued to open/close after some delay.
/// </summary>
- private readonly HashSet<DoorComponent> _activeDoors = new();
+ private readonly HashSet<Entity<DoorComponent>> _activeDoors = new();
public override void Initialize()
{
}
- protected virtual void OnComponentInit(EntityUid uid, DoorComponent door, ComponentInit args)
+ protected virtual void OnComponentInit(Entity<DoorComponent> ent, ref ComponentInit args)
{
+ var door = ent.Comp;
if (door.NextStateChange != null)
- _activeDoors.Add(door);
+ _activeDoors.Add(ent);
else
{
// Make sure doors are not perpetually stuck opening or closing.
|| door.State == DoorState.Closing && door.Partial
|| door.State == DoorState.Opening && !door.Partial;
- SetCollidable(uid, collidable, door);
- AppearanceSystem.SetData(uid, DoorVisuals.State, door.State);
+ SetCollidable(ent, collidable, door);
+ AppearanceSystem.SetData(ent, DoorVisuals.State, door.State);
}
- private void OnRemove(EntityUid uid, DoorComponent door, ComponentRemove args)
+ private void OnRemove(Entity<DoorComponent> door, ref ComponentRemove args)
{
_activeDoors.Remove(door);
}
#region StateManagement
- private void OnHandleState(EntityUid uid, DoorComponent door, ref AfterAutoHandleStateEvent args)
+ private void OnHandleState(Entity<DoorComponent> ent, ref AfterAutoHandleStateEvent args)
{
+ var door = ent.Comp;
if (door.NextStateChange == null)
- _activeDoors.Remove(door);
+ _activeDoors.Remove(ent);
else
- _activeDoors.Add(door);
+ _activeDoors.Add(ent);
- RaiseLocalEvent(uid, new DoorStateChangedEvent(door.State));
- AppearanceSystem.SetData(uid, DoorVisuals.State, door.State);
+ RaiseLocalEvent(ent, new DoorStateChangedEvent(door.State));
+ AppearanceSystem.SetData(ent, DoorVisuals.State, door.State);
}
protected void SetState(EntityUid uid, DoorState state, DoorComponent? door = null)
switch (state)
{
case DoorState.Opening:
- _activeDoors.Add(door);
+ _activeDoors.Add((uid, door));
door.NextStateChange = GameTiming.CurTime + door.OpenTimeOne;
break;
case DoorState.Closing:
- _activeDoors.Add(door);
+ _activeDoors.Add((uid, door));
door.NextStateChange = GameTiming.CurTime + door.CloseTimeOne;
break;
case DoorState.Denying:
- _activeDoors.Add(door);
+ _activeDoors.Add((uid, door));
door.NextStateChange = GameTiming.CurTime + door.DenyDuration;
break;
case DoorState.Emagging:
- _activeDoors.Add(door);
+ _activeDoors.Add((uid, door));
door.NextStateChange = GameTiming.CurTime + door.EmagDuration;
break;
case DoorState.Open:
door.Partial = false;
if (door.NextStateChange == null)
- _activeDoors.Remove(door);
+ _activeDoors.Remove((uid, door));
break;
case DoorState.Closed:
// May want to keep the door around to re-check for opening if we got a contact during closing.
}
door.State = state;
- Dirty(door);
- RaiseLocalEvent(uid, new DoorStateChangedEvent(state), false);
+ Dirty(uid, door);
+ RaiseLocalEvent(uid, new DoorStateChangedEvent(state));
AppearanceSystem.SetData(uid, DoorVisuals.State, door.State);
}
// might not be able to deny without power or some other blocker.
var ev = new BeforeDoorDeniedEvent();
- RaiseLocalEvent(uid, ev, false);
+ RaiseLocalEvent(uid, ev);
if (ev.Cancelled)
return;
return false;
var ev = new BeforeDoorOpenedEvent() { User = user };
- RaiseLocalEvent(uid, ev, false);
+ RaiseLocalEvent(uid, ev);
if (ev.Cancelled)
return false;
SetCollidable(uid, false, door);
door.Partial = true;
door.NextStateChange = GameTiming.CurTime + door.CloseTimeTwo;
- _activeDoors.Add(door);
- Dirty(door);
+ _activeDoors.Add((uid, door));
+ Dirty(uid, door);
}
#endregion
return false;
door.Partial = true;
- Dirty(door);
+ Dirty(uid, door);
// Make sure no entity waled into the airlock when it started closing.
if (!CanClose(uid, door))
SetCollidable(uid, true, door, physics);
door.NextStateChange = GameTiming.CurTime + door.CloseTimeTwo;
- _activeDoors.Add(door);
+ _activeDoors.Add((uid, door));
// Crush any entities. Note that we don't check airlock safety here. This should have been checked before
// the door closed.
if (delay == null || delay.Value <= TimeSpan.Zero)
{
door.NextStateChange = null;
- _activeDoors.Remove(door);
+ _activeDoors.Remove((uid, door));
return;
}
door.NextStateChange = GameTiming.CurTime + delay.Value;
- _activeDoors.Add(door);
+ _activeDoors.Add((uid, door));
}
/// <summary>
{
var time = GameTiming.CurTime;
- foreach (var door in _activeDoors.ToList())
+ foreach (var ent in _activeDoors.ToList())
{
+ var door = ent.Comp;
if (door.Deleted || door.NextStateChange == null)
{
- _activeDoors.Remove(door);
+ _activeDoors.Remove(ent);
continue;
}
- if (Paused(door.Owner))
+ if (Paused(ent))
continue;
if (door.NextStateChange.Value < time)
- NextState(door, time);
+ NextState(ent, time);
if (door.State == DoorState.Closed &&
- TryComp<PhysicsComponent>(door.Owner, out var doorBody))
+ TryComp<PhysicsComponent>(ent, out var doorBody))
{
// If something bumped into us during closing then start to re-open, otherwise, remove it from active.
- _activeDoors.Remove(door);
- CheckDoorBump(door, doorBody);
+ _activeDoors.Remove(ent);
+ CheckDoorBump((ent, door, doorBody));
}
}
}
- protected virtual void CheckDoorBump(DoorComponent component, PhysicsComponent body) { }
+ protected virtual void CheckDoorBump(Entity<DoorComponent, PhysicsComponent> ent) { }
/// <summary>
/// Makes a door proceed to the next state (if applicable).
/// </summary>
- private void NextState(DoorComponent door, TimeSpan time)
+ private void NextState(Entity<DoorComponent> ent, TimeSpan time)
{
+ var door = ent.Comp;
door.NextStateChange = null;
if (door.CurrentlyCrushing.Count > 0)
// This is a closed door that is crushing people and needs to auto-open. Note that we don't check "can open"
// here. The door never actually finished closing and we don't want people to get stuck inside of doors.
- StartOpening(door.Owner, door, predicted: true);
+ StartOpening(ent, door, predicted: true);
switch (door.State)
{
case DoorState.Opening:
// Either fully or partially open this door.
if (door.Partial)
- SetState(door.Owner, DoorState.Open, door);
+ SetState(ent, DoorState.Open, door);
else
- OnPartialOpen(door.Owner, door);
+ OnPartialOpen(ent, door);
break;
case DoorState.Closing:
// Either fully or partially close this door.
if (door.Partial)
- SetState(door.Owner, DoorState.Closed, door);
+ SetState(ent, DoorState.Closed, door);
else
- OnPartialClose(door.Owner, door);
+ OnPartialClose(ent, door);
break;
case DoorState.Denying:
// Finish denying entry and return to the closed state.
- SetState(door.Owner, DoorState.Closed, door);
+ SetState(ent, DoorState.Closed, door);
break;
case DoorState.Emagging:
- StartOpening(door.Owner, door);
+ StartOpening(ent, door);
break;
case DoorState.Open:
// This door is open, and queued for an auto-close.
- if (!TryClose(door.Owner, door, predicted: true))
+ if (!TryClose(ent, door, predicted: true))
{
// The door failed to close (blocked?). Try again in one second.
door.NextStateChange = time + TimeSpan.FromSeconds(1);
case DoorState.Welded:
// A welded door? This should never have been active in the first place.
- Log.Error($"Welded door was in the list of active doors. Door: {ToPrettyString(door.Owner)}");
+ Log.Error($"Welded door was in the list of active doors. Door: {ToPrettyString(ent)}");
break;
}
}
using System.Linq;
-using Content.Shared.DragDrop;
-using Content.Shared.Interaction;
-using Content.Shared.Eye.Blinding;
using Content.Shared.Eye.Blinding.Components;
+using Content.Shared.Interaction;
using Content.Shared.Mobs.Components;
using Content.Shared.Mobs.Systems;
using JetBrains.Annotations;
using Robust.Shared.Containers;
using Robust.Shared.Map;
-using Robust.Shared.Network;
using Robust.Shared.Physics;
using Robust.Shared.Utility;
using static Content.Shared.Interaction.SharedInteractionSystem;
}
var bBox = o.BoundingBox;
- bBox = bBox.Translated(entMan.GetComponent<TransformComponent>(o.Owner).WorldPosition);
+ bBox = bBox.Translated(entMan.GetComponent<TransformComponent>(result.HitEntity).WorldPosition);
if (bBox.Contains(origin.Position) || bBox.Contains(other.Position))
{
return InRangeUnOccluded(originPos, otherPos, range, predicate, ignoreInsideBlocker);
}
- public static bool InRangeUnOccluded(EntityUid origin, IComponent other, float range = ExamineRange, Ignored? predicate = null, bool ignoreInsideBlocker = true)
- {
- var entMan = IoCManager.Resolve<IEntityManager>();
- var originPos = entMan.GetComponent<TransformComponent>(origin).MapPosition;
- var otherPos = entMan.GetComponent<TransformComponent>(other.Owner).MapPosition;
-
- return InRangeUnOccluded(originPos, otherPos, range, predicate, ignoreInsideBlocker);
- }
-
public static bool InRangeUnOccluded(EntityUid origin, EntityCoordinates other, float range = ExamineRange, Ignored? predicate = null, bool ignoreInsideBlocker = true)
{
var entMan = IoCManager.Resolve<IEntityManager>();
{
followerComp = AddComp<FollowerComponent>(follower);
}
-
+
followerComp.Following = entity;
var followedComp = EnsureComp<FollowedComponent>(entity);
_physicsSystem.SetLinearVelocity(follower, Vector2.Zero);
var xform = Transform(follower);
- _containerSystem.AttachParentToContainerOrGrid(xform);
+ _containerSystem.AttachParentToContainerOrGrid((follower, xform));
// If we didn't get to parent's container.
if (xform.ParentUid != Transform(xform.ParentUid).ParentUid)
using Content.Shared.Pulling.Components;
using JetBrains.Annotations;
using Robust.Shared.Configuration;
-using Robust.Shared.GameStates;
using Robust.Shared.Map;
using Robust.Shared.Map.Components;
using Robust.Shared.Physics.Components;
using Robust.Shared.Physics.Controllers;
using Robust.Shared.Physics.Dynamics;
using Robust.Shared.Physics.Systems;
-using Robust.Shared.Serialization;
-using Robust.Shared.Utility;
-
namespace Content.Shared.Friction
{
// Only apply friction when it's not a mob (or the mob doesn't have control)
if (prediction && !body.Predict ||
body.BodyStatus == BodyStatus.InAir ||
- _mover.UseMobMovement(body.Owner))
+ _mover.UseMobMovement(uid))
{
continue;
}
if (!xformQuery.TryGetComponent(uid, out var xform))
{
- Log.Error($"Unable to get transform for {ToPrettyString(body.Owner)} in tilefrictioncontroller");
+ Log.Error($"Unable to get transform for {ToPrettyString(uid)} in tilefrictioncontroller");
continue;
}
private void OnGravityChanged(ref GravityChangedEvent args)
{
- foreach (var (floating, transform) in EntityQuery<FloatingVisualsComponent, TransformComponent>(true))
+ var query = EntityQueryEnumerator<FloatingVisualsComponent, TransformComponent>();
+ while (query.MoveNext(out var uid, out var floating, out var transform))
{
if (transform.MapID == MapId.Nullspace)
continue;
continue;
floating.CanFloat = !args.HasGravity;
- Dirty(floating);
+ Dirty(uid, floating);
- var uid = floating.Owner;
if (!args.HasGravity)
FloatAnimation(uid, floating.Offset, floating.AnimationKey, floating.AnimationTime);
}
-using System.Numerics;
using Content.Shared.Database;
using Content.Shared.Hands.Components;
using Content.Shared.Item;
{
// TODO make this check upwards for any container, and parent to that.
// Currently this just checks the direct parent, so items can still teleport through containers.
- ContainerSystem.AttachParentToContainerOrGrid(Transform(entity));
+ ContainerSystem.AttachParentToContainerOrGrid((entity, Transform(entity)));
}
}
[Dependency] private readonly SharedStorageSystem _storage = default!;
[Dependency] protected readonly SharedTransformSystem TransformSystem = default!;
- protected event Action<HandsComponent?>? OnHandSetActive;
+ protected event Action<Entity<HandsComponent>?>? OnHandSetActive;
public override void Initialize()
{
}
handComp.ActiveHand = hand;
- OnHandSetActive?.Invoke(handComp);
+ OnHandSetActive?.Invoke((uid, handComp));
if (hand.HeldEntity != null)
RaiseLocalEvent(hand.HeldEntity.Value, new HandSelectedEvent(uid));
{
if (TryComp(hand.HeldEntity, out HandVirtualItemComponent? virt) && virt.BlockingEntity == matching)
{
- Delete(virt, user);
+ Delete((hand.HeldEntity.Value, virt), user);
}
}
}
/// <summary>
/// Queues a deletion for a virtual item and notifies the blocking entity and user.
/// </summary>
- public void Delete(HandVirtualItemComponent comp, EntityUid user)
+ public void Delete(Entity<HandVirtualItemComponent> item, EntityUid user)
{
if (_net.IsClient)
return;
- var userEv = new VirtualItemDeletedEvent(comp.BlockingEntity, user);
+ var userEv = new VirtualItemDeletedEvent(item.Comp.BlockingEntity, user);
RaiseLocalEvent(user, userEv);
- var targEv = new VirtualItemDeletedEvent(comp.BlockingEntity, user);
- RaiseLocalEvent(comp.BlockingEntity, targEv);
+ var targEv = new VirtualItemDeletedEvent(item.Comp.BlockingEntity, user);
+ RaiseLocalEvent(item.Comp.BlockingEntity, targEv);
- QueueDel(comp.Owner);
+ QueueDel(item);
}
}
{
var adjustedAmount = AdjustMaterial(needed, recipe.ApplyMaterialDiscount, component.MaterialUseMultiplier);
- if (_materialStorage.GetMaterialAmount(component.Owner, material) < adjustedAmount * amount)
+ if (_materialStorage.GetMaterialAmount(uid, material) < adjustedAmount * amount)
return false;
}
return true;
if (makeNoise)
{
var sound = component.Activated ? component.TurnOnSound : component.TurnOffSound;
- _audio.PlayPvs(sound, component.Owner);
+ _audio.PlayPvs(sound, uid);
}
- Dirty(component);
+ Dirty(uid, component);
UpdateVisuals(uid, component);
}
+using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
-using System.Diagnostics.CodeAnalysis;
-using Content.Shared.Decals;
using Content.Shared.Physics;
using Robust.Shared.Map;
-using Robust.Shared.Physics;
-using Robust.Shared.Physics.Components;
using Robust.Shared.Random;
namespace Content.Shared.Maps
if (map.TryGetGrid(turf.GridUid, out var tileGrid))
{
- var gridRot = entManager.GetComponent<TransformComponent>(tileGrid.Owner).WorldRotation;
+ var gridRot = entManager.GetComponent<TransformComponent>(turf.GridUid).WorldRotation;
// This is scaled to 90 % so it doesn't encompass walls on other tiles.
var tileBox = Box2.UnitCentered.Scale(0.9f);
OnStateChanged(target, component, oldState, newState);
RaiseLocalEvent(target, ev, true);
_adminLogger.Add(LogType.Damaged, oldState == MobState.Alive ? LogImpact.Low : LogImpact.Medium,
- $"{ToPrettyString(component.Owner):user} state changed from {oldState} to {newState}");
- Dirty(component);
+ $"{ToPrettyString(target):user} state changed from {oldState} to {newState}");
+ Dirty(target, component);
}
#endregion
foreach (var entity in comp.Intersecting)
{
- if (!xformQuery.TryGetComponent(entity, out var entityXform) || entityXform.ParentUid != grid.Owner)
+ if (!xformQuery.TryGetComponent(entity, out var entityXform) || entityXform.ParentUid != xform.GridUid!.Value)
continue;
if (!bodyQuery.TryGetComponent(entity, out var physics) || physics.BodyType == BodyType.Static || physics.BodyStatus == BodyStatus.InAir || _gravity.IsWeightless(entity, physics, entityXform))
public bool IsTrue(EntityUid uid, RulesPrototype rules)
{
+ var inRange = new HashSet<Entity<IComponent>>();
foreach (var rule in rules.Rules)
{
switch (rule)
var count = 0;
// TODO: Update this when we get the callback version
- foreach (var comp in _lookup.GetComponentsInRange<AccessReaderComponent>(xform.MapID,
- worldPos, access.Range))
+ var entities = new HashSet<Entity<AccessReaderComponent>>();
+ _lookup.GetEntitiesInRange(xform.MapID, worldPos, access.Range, entities);
+ foreach (var comp in entities)
{
if (!_reader.AreAccessTagsAllowed(access.Access, comp) ||
access.Anchored &&
- (!xformQuery.TryGetComponent(comp.Owner, out var compXform) ||
+ (!xformQuery.TryGetComponent(comp, out var compXform) ||
!compXform.Anchored))
{
continue;
foreach (var compType in nearbyComps.Components.Values)
{
- // TODO: Update this when we get the callback version
- foreach (var comp in _lookup.GetComponentsInRange(compType.Component.GetType(), xform.MapID,
- worldPos, nearbyComps.Range))
+ inRange.Clear();
+ _lookup.GetEntitiesInRange(compType.Component.GetType(), xform.MapID, worldPos, nearbyComps.Range, inRange);
+ foreach (var comp in inRange)
{
if (nearbyComps.Anchored &&
- (!xformQuery.TryGetComponent(comp.Owner, out var compXform) ||
+ (!xformQuery.TryGetComponent(comp, out var compXform) ||
!compXform.Anchored))
{
continue;
if (comp.Accumulator < comp.ZapDelay)
continue;
- OnZap(comp);
+ OnZap((uid, comp));
RemCompDeferred(uid, comp);
}
}
- protected abstract void OnZap(RevenantOverloadedLightsComponent component);
+ protected abstract void OnZap(Entity<RevenantOverloadedLightsComponent> component);
}
/// Stores a list of fields connected between generators in this direction.
/// </summary>
[ViewVariables]
- public Dictionary<Direction, (ContainmentFieldGeneratorComponent, List<EntityUid>)> Connections = new();
+ public Dictionary<Direction, (Entity<ContainmentFieldGeneratorComponent>, List<EntityUid>)> Connections = new();
/// <summary>
/// What fields should this spawn?
using System.Numerics;
+using Content.Shared.Radiation.Components;
+using Content.Shared.Singularity.Components;
+using Content.Shared.Singularity.Events;
using Robust.Shared.Containers;
using Robust.Shared.Physics.Components;
using Robust.Shared.Physics.Systems;
using Robust.Shared.Serialization;
-using Content.Shared.Radiation.Components;
-using Content.Shared.Singularity.Components;
-using Content.Shared.Singularity.Events;
-
namespace Content.Shared.Singularity.EntitySystems;
/// <summary>
singularity.Level = value;
UpdateSingularityLevel(uid, oldValue, singularity);
- if(!EntityManager.Deleted(singularity.Owner))
- EntityManager.Dirty(singularity);
+ if (!Deleted(uid))
+ Dirty(uid, singularity);
}
/// <summary>
using System.Numerics;
using Content.Shared.Examine;
-using Content.Shared.Hands;
using Content.Shared.Hands.Components;
using Content.Shared.Hands.EntitySystems;
using Content.Shared.Interaction;
var map = xform.MapID;
var bounds = _physics.GetWorldAABB(uid);
- var intersecting = _entityLookup.GetComponentsIntersecting<StackComponent>(map, bounds,
- LookupFlags.Dynamic | LookupFlags.Sundries);
+ var intersecting = new HashSet<Entity<StackComponent>>();
+ _entityLookup.GetEntitiesIntersecting(map, bounds, intersecting, LookupFlags.Dynamic | LookupFlags.Sundries);
var merged = false;
foreach (var otherStack in intersecting)
var curTime = _gameTiming.CurTime;
var enumerator = EntityQueryEnumerator<ActiveStatusEffectsComponent, StatusEffectsComponent>();
- while (enumerator.MoveNext(out _, out var status))
+ while (enumerator.MoveNext(out var uid, out _, out var status))
{
foreach (var state in status.ActiveEffects.ToArray())
{
// if we're past the end point of the effect
if (curTime > state.Value.Cooldown.Item2)
{
- TryRemoveStatusEffect(status.Owner, state.Key, status);
+ TryRemoveStatusEffect(uid, state.Key, status);
}
}
}
// If they already have the comp, we just won't bother updating anything.
if (!EntityManager.HasComponent(uid, _componentFactory.GetRegistration(component).Type))
{
- // Fuck this shit I hate it
var newComponent = (Component) _componentFactory.GetComponent(component);
- newComponent.Owner = uid;
-
EntityManager.AddComponent(uid, newComponent);
status.ActiveEffects[key].RelevantComponent = component;
}
foreach (var entity in dumpQueue)
{
var transform = Transform(entity);
- _container.AttachParentToContainerOrGrid(transform);
+ _container.AttachParentToContainerOrGrid((entity, transform));
_transformSystem.SetLocalPositionRotation(transform, transform.LocalPosition + _random.NextVector2Box() / 2, _random.NextAngle());
}
if (args.Handled || args.Target != args.User)
return;
- StartOpeningStripper(args.User, component);
+ StartOpeningStripper(args.User, (uid, component));
args.Handled = true;
}
- public virtual void StartOpeningStripper(EntityUid user, StrippableComponent component, bool openInCombat = false)
+ public virtual void StartOpeningStripper(EntityUid user, Entity<StrippableComponent> component, bool openInCombat = false)
{
}
var curTime = Timing.CurTime;
- foreach (var comp in EntityQuery<WeatherComponent>())
+ var query = EntityQueryEnumerator<WeatherComponent>();
+ while (query.MoveNext(out var uid, out var comp))
{
if (comp.Weather.Count == 0)
continue;
- var uid = comp.Owner;
-
foreach (var (proto, weather) in comp.Weather)
{
var endTime = weather.EndTime;
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/INVOCABLE_DECLARATION_BRACES/@EntryValue">NEXT_LINE</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/OTHER_BRACES/@EntryValue">NEXT_LINE</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/TYPE_DECLARATION_BRACES/@EntryValue">NEXT_LINE</s:String>
+ <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=AABB/@EntryIndexedValue">AABB</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=AL/@EntryIndexedValue">AL</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=BB/@EntryIndexedValue">BB</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=CC/@EntryIndexedValue">CC</s:String>
<s:Boolean x:Key="/Default/PatternsAndTemplates/LiveTemplates/QuickList/=F0CA621CDF5AB24282D8CDC11C520997/Entry/=142539C9975BA84BA1996ADB02B1E422/@KeyIndexDefined">True</s:Boolean>
<s:String x:Key="/Default/PatternsAndTemplates/LiveTemplates/QuickList/=F0CA621CDF5AB24282D8CDC11C520997/Entry/=142539C9975BA84BA1996ADB02B1E422/EntryName/@EntryValue">Entity Component</s:String>
<s:Int64 x:Key="/Default/PatternsAndTemplates/LiveTemplates/QuickList/=F0CA621CDF5AB24282D8CDC11C520997/Entry/=142539C9975BA84BA1996ADB02B1E422/Position/@EntryValue">1</s:Int64>
-
+
<s:Int64 x:Key="/Default/PatternsAndTemplates/LiveTemplates/QuickList/=F0CA621CDF5AB24282D8CDC11C520997/Entry/=2CBD6971A7955044AD2624B84FB49E38/Position/@EntryValue">9</s:Int64>
<s:Int64 x:Key="/Default/PatternsAndTemplates/LiveTemplates/QuickList/=F0CA621CDF5AB24282D8CDC11C520997/Entry/=567DCF4B487C244A9F6BB46E4E9F3B84/Position/@EntryValue">6</s:Int64>
<s:Boolean x:Key="/Default/PatternsAndTemplates/LiveTemplates/QuickList/=F0CA621CDF5AB24282D8CDC11C520997/Entry/=652E0DBD3559BD4EA35305A83762B0C8/@KeyIndexDefined">True</s:Boolean>
<s:String x:Key="/Default/PatternsAndTemplates/LiveTemplates/QuickList/=F0CA621CDF5AB24282D8CDC11C520997/Entry/=652E0DBD3559BD4EA35305A83762B0C8/EntryName/@EntryValue">XAML Control</s:String>
-
+
<s:Boolean x:Key="/Default/PatternsAndTemplates/LiveTemplates/QuickList/=F0CA621CDF5AB24282D8CDC11C520997/Entry/=7C233DA875A1B54AB9906002129B9E8C/@KeyIndexDefined">True</s:Boolean>
<s:String x:Key="/Default/PatternsAndTemplates/LiveTemplates/QuickList/=F0CA621CDF5AB24282D8CDC11C520997/Entry/=7C233DA875A1B54AB9906002129B9E8C/EntryName/@EntryValue">Client/Server Net Entity System</s:String>
<s:Int64 x:Key="/Default/PatternsAndTemplates/LiveTemplates/QuickList/=F0CA621CDF5AB24282D8CDC11C520997/Entry/=7C233DA875A1B54AB9906002129B9E8C/Position/@EntryValue">8</s:Int64>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Gibs/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=godmode/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=gridcast/@EntryIndexedValue">True</s:Boolean>
-
+
<s:Boolean x:Key="/Default/UserDictionary/Words/=Grindable/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=hardcode/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=hbox/@EntryIndexedValue">True</s:Boolean>