Remove 700 usages of Component.Owner (#21100)

This commit is contained in:
DrSmugleaf
2023-10-19 12:34:31 -07:00
committed by Debug
parent 1561629bc2
commit 9cc8a7fc81
261 changed files with 2291 additions and 2036 deletions

View File

@@ -1,10 +1,12 @@
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;
@@ -13,7 +15,6 @@ public sealed class ExplosionDebugOverlay : Overlay
{
[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();
@@ -61,14 +62,15 @@ public sealed class ExplosionDebugOverlay : Overlay
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);
}
@@ -114,9 +116,9 @@ public sealed class ExplosionDebugOverlay : Overlay
}
}
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}";
@@ -129,14 +131,15 @@ public sealed class ExplosionDebugOverlay : Overlay
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);

View File

@@ -1,14 +1,10 @@
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
@@ -17,16 +13,29 @@ 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);
@@ -35,12 +44,8 @@ namespace Content.Client.Administration.UI.Tabs.AtmosTab
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)}");
}
}
}

View File

@@ -1,4 +1,3 @@
using System.Linq;
using Content.Client.Station;
using Robust.Client.AutoGenerated;
using Robust.Client.UserInterface;
@@ -40,13 +39,34 @@ public sealed partial class ObjectsTab : Control
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)
{

View File

@@ -47,20 +47,20 @@ public sealed class ClientAlertsSystem : AlertsSystem
}
}
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)

View File

@@ -4,10 +4,8 @@ using Content.Shared.Atmos;
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
{
@@ -19,6 +17,7 @@ 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)
{
@@ -41,10 +40,19 @@ namespace Content.Client.Atmos.Overlays
// 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) =>
{
if (!_atmosDebugOverlaySystem.HasData(mapGrid.Owner) ||
!_entManager.TryGetComponent<TransformComponent>(mapGrid.Owner, out var xform))
state.Add((uid, grid));
return true;
});
foreach (var (uid, mapGrid) in _grids)
{
if (!_atmosDebugOverlaySystem.HasData(uid) ||
!_entManager.TryGetComponent<TransformComponent>(uid, out var xform))
continue;
drawHandle.SetTransform(xform.WorldMatrix);
@@ -53,7 +61,7 @@ namespace Content.Client.Atmos.Overlays
{
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;
@@ -61,9 +69,10 @@ namespace Content.Client.Atmos.Overlays
{
// -- 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;
}
@@ -75,7 +84,7 @@ namespace Content.Client.Atmos.Overlays
total = data.Temperature;
break;
}
var interp = ((total - _atmosDebugOverlaySystem.CfgBase) / _atmosDebugOverlaySystem.CfgScale);
var interp = (total - _atmosDebugOverlaySystem.CfgBase) / _atmosDebugOverlaySystem.CfgScale;
Color res;
if (_atmosDebugOverlaySystem.CfgCBM)
{

View File

@@ -39,7 +39,7 @@ public sealed class AmbientSoundOverlay : Overlay
if (ambientSound.Enabled)
{
if (_ambient.IsActive(ambientSound))
if (_ambient.IsActive((ent, ambientSound)))
{
worldHandle.DrawCircle(xformSystem.GetWorldPosition(xform), Size, Color.LightGreen.WithAlpha(Alpha * 2f));
}

View File

@@ -1,18 +1,16 @@
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.
@@ -50,7 +48,7 @@ public sealed class AmbientSoundSystem : SharedAmbientSoundSystem
/// </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
@@ -80,7 +78,7 @@ public sealed class AmbientSoundSystem : SharedAmbientSoundSystem
/// </summary>
/// <param name="component"></param>
/// <returns></returns>
public bool IsActive(AmbientSoundComponent component)
public bool IsActive(Entity<AmbientSoundComponent> component)
{
return _playingSounds.ContainsKey(component);
}
@@ -100,7 +98,7 @@ public sealed class AmbientSoundSystem : SharedAmbientSoundSystem
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();
@@ -113,7 +111,7 @@ public sealed class AmbientSoundSystem : SharedAmbientSoundSystem
{
_ambienceVolume = value;
foreach (var (comp, values) in _playingSounds)
foreach (var ((_, comp), values) in _playingSounds)
{
if (values.Stream == null)
continue;
@@ -188,7 +186,7 @@ public sealed class AmbientSoundSystem : SharedAmbientSoundSystem
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;
@@ -226,7 +224,7 @@ public sealed class AmbientSoundSystem : SharedAmbientSoundSystem
// 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;
}
@@ -240,9 +238,10 @@ public sealed class AmbientSoundSystem : SharedAmbientSoundSystem
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.
@@ -260,7 +259,7 @@ public sealed class AmbientSoundSystem : SharedAmbientSoundSystem
}
sound.Stream?.Stop();
_playingSounds.Remove(comp);
_playingSounds.Remove((entity, comp));
_playingCount[sound.Path] -= 1;
if (_playingCount[sound.Path] == 0)
_playingCount.Remove(sound.Path);
@@ -285,11 +284,12 @@ public sealed class AmbientSoundSystem : SharedAmbientSoundSystem
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;
@@ -303,7 +303,7 @@ public sealed class AmbientSoundSystem : SharedAmbientSoundSystem
if (stream == null)
continue;
_playingSounds[comp] = (stream, comp.Sound, key);
_playingSounds[ent] = (stream, comp.Sound, key);
playingCount++;
if (_playingSounds.Count >= _maxAmbientCount)

View File

@@ -38,12 +38,16 @@ public sealed class CardboardBoxSystem : SharedCardboardBoxSystem
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.

View File

@@ -33,7 +33,7 @@ public sealed class ChasmFallingVisualsSystem : EntitySystem
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)

View File

@@ -16,18 +16,18 @@ namespace Content.Client.Commands
{
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)

View File

@@ -17,14 +17,11 @@ namespace Content.Client.Commands
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");

View File

@@ -31,11 +31,11 @@ namespace Content.Client.Decals.Overlays
// 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)
@@ -44,7 +44,7 @@ namespace Content.Client.Decals.Overlays
if (xform.MapID != args.MapId)
continue;
var (_, worldRot, worldMatrix) = xform.GetWorldPositionRotationMatrix(xformQuery);
var (_, worldRot, worldMatrix) = xformSystem.GetWorldPositionRotationMatrix(xform, xformQuery);
handle.SetTransform(worldMatrix);

View File

@@ -22,8 +22,9 @@ public sealed class DoorSystem : SharedDoorSystem
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);

View File

@@ -114,7 +114,7 @@ public sealed class ColorFlashEffectSystem : SharedColorFlashEffectSystem
var comp = EnsureComp<ColorFlashEffectComponent>(ent);
comp.NetSyncEnabled = false;
comp.Color = sprite.Color;
_animation.Play(player, animation, AnimationKey);
_animation.Play((ent, player), animation, AnimationKey);
}
}
}

View File

@@ -4,6 +4,7 @@ using JetBrains.Annotations;
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;
@@ -63,10 +64,10 @@ public sealed class ExplosionOverlay : Overlay
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);

View File

@@ -1,9 +1,9 @@
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;
@@ -52,7 +52,7 @@ public sealed class PuddleOverlay : Overlay
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);
@@ -60,7 +60,7 @@ public sealed class PuddleOverlay : Overlay
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;
@@ -85,14 +85,14 @@ public sealed class PuddleOverlay : Overlay
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;

View File

@@ -12,8 +12,8 @@ public sealed class HandheldGpsSystem : EntitySystem
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));
}
}

View File

@@ -9,12 +9,12 @@ namespace Content.Client.GPS.UI;
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>();
@@ -28,10 +28,10 @@ public sealed class HandheldGpsStatusControl : Control
base.FrameUpdate(args);
_updateDif += args.DeltaSeconds;
if (_updateDif < _parent.UpdateRate)
if (_updateDif < _parent.Comp.UpdateRate)
return;
_updateDif -= _parent.UpdateRate;
_updateDif -= _parent.Comp.UpdateRate;
UpdateGpsDetails();
}
@@ -39,7 +39,7 @@ public sealed class HandheldGpsStatusControl : Control
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;

View File

@@ -5,7 +5,6 @@ using System.Numerics;
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;
@@ -37,7 +36,9 @@ public sealed partial class GuideEntityEmbed : BoxContainer, IDocumentTag
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
{
@@ -127,7 +128,7 @@ public sealed partial class GuideEntityEmbed : BoxContainer, IDocumentTag
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)

View File

@@ -1,7 +1,5 @@
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;
@@ -15,7 +13,6 @@ using Robust.Client.Player;
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
@@ -416,21 +413,21 @@ 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);
}
}
}

View File

@@ -1,4 +1,3 @@
using System.Collections.Generic;
using Content.Client.HealthOverlay.UI;
using Content.Shared.Damage;
using Content.Shared.GameTicking;
@@ -6,8 +5,6 @@ using Content.Shared.Mobs.Components;
using JetBrains.Annotations;
using Robust.Client.GameObjects;
using Robust.Client.Graphics;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
namespace Content.Client.HealthOverlay
{
@@ -80,10 +77,9 @@ 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))
{

View File

@@ -70,7 +70,7 @@ namespace Content.Client.HealthOverlay.UI
Panel.Visible = val;
}
private void MoreFrameUpdate(FrameEventArgs args)
private void MoreFrameUpdate()
{
if (_entities.Deleted(Entity))
{
@@ -87,7 +87,7 @@ namespace Content.Client.HealthOverlay.UI
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))
{
@@ -101,7 +101,7 @@ namespace Content.Client.HealthOverlay.UI
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;
@@ -118,7 +118,7 @@ namespace Content.Client.HealthOverlay.UI
((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;
@@ -136,7 +136,7 @@ namespace Content.Client.HealthOverlay.UI
{
base.FrameUpdate(args);
MoreFrameUpdate(args);
MoreFrameUpdate();
if (_entities.Deleted(Entity) || _eyeManager.CurrentMap != _entities.GetComponent<TransformComponent>(Entity).MapID)
{

View File

@@ -236,6 +236,8 @@ namespace Content.Client.IconSmoothing
return;
}
var spriteEnt = (uid, sprite);
if (xform.Anchored)
{
if (!_mapManager.TryGetGrid(xform.GridUid, out grid))
@@ -248,13 +250,13 @@ namespace Content.Client.IconSmoothing
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();
@@ -262,11 +264,11 @@ namespace Content.Client.IconSmoothing
}
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;
}
@@ -289,21 +291,21 @@ namespace Content.Client.IconSmoothing
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;
}
@@ -317,7 +319,7 @@ namespace Content.Client.IconSmoothing
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;
@@ -330,7 +332,7 @@ namespace Content.Client.IconSmoothing
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)
@@ -348,7 +350,7 @@ namespace Content.Client.IconSmoothing
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)
@@ -359,6 +361,7 @@ namespace Content.Client.IconSmoothing
// 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}");
@@ -378,7 +381,7 @@ namespace Content.Client.IconSmoothing
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)

View File

@@ -22,11 +22,11 @@ namespace Content.Client.Interactable.Components
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);
@@ -34,9 +34,9 @@ namespace Content.Client.Interactable.Components
}
}
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;
@@ -47,9 +47,9 @@ namespace Content.Client.Interactable.Components
_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))
{

View File

@@ -107,7 +107,7 @@ namespace Content.Client.Inventory
private void OnShutdown(EntityUid uid, InventoryComponent component, ComponentShutdown args)
{
if (component.Owner != _playerManager.LocalPlayer?.ControlledEntity)
if (uid != _playerManager.LocalPlayer?.ControlledEntity)
return;
OnUnlinkInventory?.Invoke();

View File

@@ -408,9 +408,9 @@ namespace Content.Client.Light.Components
/// <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)
@@ -420,7 +420,7 @@ namespace Content.Client.Light.Components
}
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!");
}
}
@@ -445,7 +445,7 @@ namespace Content.Client.Light.Components
{
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);
}

View File

@@ -170,11 +170,12 @@ namespace Content.Client.Light
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)
{
@@ -196,17 +197,18 @@ namespace Content.Client.Light
}
}
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

View File

@@ -38,9 +38,10 @@ public sealed class NPCSteeringSystem : SharedNPCSteeringSystem
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);
}
}
}

View File

@@ -2,11 +2,13 @@ using System.Linq;
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;
@@ -20,6 +22,7 @@ namespace Content.Client.NPC
[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
{
@@ -36,7 +39,7 @@ namespace Content.Client.NPC
}
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)
@@ -136,10 +139,12 @@ namespace Content.Client.NPC
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,
@@ -147,13 +152,15 @@ namespace Content.Client.NPC
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);
}
@@ -182,11 +189,14 @@ namespace Content.Client.NPC
{
var found = false;
foreach (var grid in _mapManager.FindGridsIntersecting(mouseWorldPos.MapId, aabb))
{
var netGrid = _entManager.GetNetEntity(grid.Owner);
_grids.Clear();
_mapManager.FindGridsIntersecting(mouseWorldPos.MapId, aabb, ref _grids);
if (found || !_system.Breadcrumbs.TryGetValue(netGrid, out var crumbs) || !xformQuery.TryGetComponent(grid.Owner, out var gridXform))
foreach (var grid in _grids)
{
var netGrid = _entManager.GetNetEntity(grid);
if (found || !_system.Breadcrumbs.TryGetValue(netGrid, out var crumbs) || !xformQuery.TryGetComponent(grid, out var gridXform))
continue;
var (_, _, worldMatrix, invWorldMatrix) = gridXform.GetWorldPositionRotationMatrixWithInv();
@@ -262,7 +272,7 @@ namespace Content.Client.NPC
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;
@@ -333,12 +343,15 @@ namespace Content.Client.NPC
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;
}
@@ -392,12 +405,15 @@ namespace Content.Client.NPC
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();
@@ -428,12 +444,15 @@ namespace Content.Client.NPC
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();
@@ -484,12 +503,15 @@ namespace Content.Client.NPC
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();

View File

@@ -1,10 +1,9 @@
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;
@@ -28,24 +27,25 @@ public sealed class NetworkConfiguratorLinkOverlay : Overlay
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,
@@ -53,7 +53,7 @@ public sealed class NetworkConfiguratorLinkOverlay : Overlay
continue;
}
foreach (var device in _deviceListSystem.GetAllDevices(tracker.Owner, deviceList))
foreach (var device in _deviceListSystem.GetAllDevices(uid, deviceList))
{
if (_entityManager.Deleted(device))
{
@@ -66,7 +66,7 @@ public sealed class NetworkConfiguratorLinkOverlay : Overlay
continue;
}
args.WorldHandle.DrawLine(sourceTransform.WorldPosition, linkTransform.WorldPosition, Colors[tracker.Owner]);
args.WorldHandle.DrawLine(sourceTransform.WorldPosition, linkTransform.WorldPosition, Colors[uid]);
}
}
}

View File

@@ -1,9 +1,7 @@
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;
@@ -94,9 +92,10 @@ public sealed class NetworkConfiguratorSystem : SharedNetworkConfiguratorSystem
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);

View File

@@ -6,6 +6,7 @@ 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;
using static Content.Shared.NodeContainer.NodeVis;
@@ -22,6 +23,7 @@ namespace Content.Client.NodeContainer
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;
@@ -112,21 +114,24 @@ namespace Content.Client.NodeContainer
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)
{
@@ -141,7 +146,7 @@ namespace Content.Client.NodeContainer
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)

View File

@@ -64,7 +64,7 @@ public sealed class InteractionOutlineSystem : EntitySystem
return;
if (TryComp(_lastHoveredEntity, out InteractionOutlineComponent? outline))
outline.OnMouseLeave();
outline.OnMouseLeave(_lastHoveredEntity.Value);
}
public void SetEnabled(bool enabled)
@@ -83,7 +83,7 @@ public sealed class InteractionOutlineSystem : EntitySystem
return;
if (TryComp(_lastHoveredEntity, out InteractionOutlineComponent? outline))
outline.OnMouseLeave();
outline.OnMouseLeave(_lastHoveredEntity.Value);
}
public override void FrameUpdate(float frameTime)
@@ -146,7 +146,7 @@ public sealed class InteractionOutlineSystem : EntitySystem
{
if (entityToClick != null && TryComp(entityToClick, out outline))
{
outline.UpdateInRange(inRange, renderScale);
outline.UpdateInRange(entityToClick.Value, inRange, renderScale);
}
return;
@@ -155,14 +155,14 @@ public sealed class InteractionOutlineSystem : EntitySystem
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);
}
}
}

View File

@@ -4,6 +4,7 @@ using Robust.Client.Graphics;
using Robust.Shared.Enums;
using Robust.Shared.GameStates;
using Robust.Shared.Map;
using Robust.Shared.Map.Components;
namespace Content.Client.Pinpointer;
@@ -42,6 +43,8 @@ public sealed class NavMapOverlay : Overlay
public override OverlaySpace Space => OverlaySpace.WorldSpace;
private List<Entity<MapGridComponent>> _grids = new();
public NavMapOverlay(IEntityManager entManager, IMapManager mapManager)
{
_entManager = entManager;
@@ -54,9 +57,12 @@ public sealed class NavMapOverlay : Overlay
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
@@ -67,9 +73,9 @@ public sealed class NavMapOverlay : Overlay
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);
@@ -89,7 +95,7 @@ public sealed class NavMapOverlay : Overlay
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);
}
}
}

View File

@@ -1,4 +1,3 @@
using System.Linq;
using System.Numerics;
using Content.Shared.Radiation.Components;
using Robust.Client.Graphics;
@@ -81,11 +80,10 @@ namespace Content.Client.Radiation.Overlays
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(

View File

@@ -1,4 +1,3 @@
using System.Linq;
using Content.Shared.Movement.Components;
using Robust.Client.GameObjects;
using Robust.Shared.Map;
@@ -134,9 +133,20 @@ public sealed partial class ReplaySpectatorSystem
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)

View File

@@ -55,7 +55,7 @@ public sealed class RevenantOverloadedLightsSystem : SharedRevenantOverloadedLig
Dirty(uid, light);
}
protected override void OnZap(RevenantOverloadedLightsComponent component)
protected override void OnZap(Entity<RevenantOverloadedLightsComponent> component)
{
}

View File

@@ -77,6 +77,6 @@ public sealed class RotationVisualizerSystem : VisualizerSystem<RotationVisualsC
}
};
AnimationSystem.Play(animationComp, animation, animationKey);
AnimationSystem.Play((uid, animationComp), animation, animationKey);
}
}

View File

@@ -4,6 +4,7 @@ using Content.Shared.Shuttles.BUIStates;
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;
@@ -43,6 +44,8 @@ public class DockingControl : Control
/// </summary>
public Dictionary<NetEntity, List<DockingInterfaceState>> Docks = new();
private List<Entity<MapGridComponent>> _grids = new();
public DockingControl()
{
_entManager = IoCManager.Resolve<IEntityManager>();
@@ -147,17 +150,19 @@ public class DockingControl : Control
// 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);
@@ -204,7 +209,7 @@ public class DockingControl : Control
}
// 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)
{

View File

@@ -3,9 +3,7 @@ using Content.Client.UserInterface.Controls;
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;
@@ -13,7 +11,6 @@ using Robust.Shared.Input;
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;
@@ -57,6 +54,8 @@ public sealed class RadarControl : MapGridControl
/// </summary>
public Action<EntityCoordinates>? OnRadarClick;
private List<Entity<MapGridComponent>> _grids = new();
public RadarControl() : base(64f, 256f, 256f)
{
_transform = _entManager.System<SharedTransformSystem>();
@@ -198,9 +197,11 @@ public sealed class RadarControl : MapGridControl
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))
@@ -240,7 +241,7 @@ public sealed class RadarControl : MapGridControl
(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))

View File

@@ -77,12 +77,13 @@ public sealed class SpriteFadeSystem : EntitySystem
}
}
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);
@@ -93,7 +94,7 @@ public sealed class SpriteFadeSystem : EntitySystem
}
else
{
RemCompDeferred<FadingSpriteComponent>(comp.Owner);
RemCompDeferred<FadingSpriteComponent>(uid);
}
}

View File

@@ -21,26 +21,27 @@ public sealed class ItemMapperSystem : SharedItemMapperSystem
{
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);
@@ -53,9 +54,10 @@ public sealed class ItemMapperSystem : SharedItemMapperSystem
}
}
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)

View File

@@ -1,4 +1,3 @@
using Content.Client.Hands;
using Content.Shared.Hands.EntitySystems;
using Content.Shared.Inventory;
using Content.Shared.SubFloor;
@@ -41,7 +40,7 @@ public sealed class TrayScannerSystem : SharedTrayScannerSystem
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
@@ -73,23 +72,20 @@ public sealed class TrayScannerSystem : SharedTrayScannerSystem
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>();
@@ -102,7 +98,7 @@ public sealed class TrayScannerSystem : SharedTrayScannerSystem
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) &&

View File

@@ -188,10 +188,10 @@ namespace Content.Client.UserInterface.Controls
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);

View File

@@ -7,9 +7,9 @@ using Robust.Client.Graphics;
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;
@@ -99,13 +99,17 @@ public sealed class WeatherOverlay : Overlay
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))
@@ -113,8 +117,8 @@ public sealed class WeatherOverlay : Overlay
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);
}

View File

@@ -18,6 +18,7 @@ public sealed class WeatherSystem : SharedWeatherSystem
[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!;
@@ -76,8 +77,9 @@ public sealed class WeatherSystem : SharedWeatherSystem
// 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.
@@ -107,7 +109,7 @@ public sealed class WeatherSystem : SharedWeatherSystem
continue;
}
frontier.Enqueue(grid.GetTileRef(new Vector2i(x, y) + node.GridIndices));
frontier.Enqueue(_mapSystem.GetTileRef(gridId, grid, new Vector2i(x, y) + node.GridIndices));
}
}

View File

@@ -23,8 +23,9 @@ public sealed partial class TestPair
{
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);

View File

@@ -17,11 +17,16 @@ namespace Content.IntegrationTests.Tests.Fluids;
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;
@@ -48,19 +53,19 @@ public sealed class FluidSpill
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)));
});
@@ -82,12 +87,11 @@ public sealed class FluidSpill
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++)

View File

@@ -13,9 +13,7 @@ using Content.Server.Gravity;
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;
@@ -708,8 +706,9 @@ public abstract partial class InteractionTest
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);

View File

@@ -1,10 +1,10 @@
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;
@@ -13,12 +13,11 @@ using Robust.Server.GameObjects;
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
{
@@ -186,7 +185,7 @@ 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();
@@ -196,7 +195,7 @@ namespace Content.IntegrationTests.Tests
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)
{

View File

@@ -1,3 +1,4 @@
using System.Linq;
using Content.Server.Administration.Logs;
using Content.Server.Kitchen.Components;
using Content.Server.Popups;
@@ -9,7 +10,6 @@ using Content.Shared.Popups;
using Content.Shared.StatusIcon;
using Robust.Shared.Prototypes;
using Robust.Shared.Random;
using System.Linq;
namespace Content.Server.Access.Systems
{
@@ -132,12 +132,12 @@ 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;
@@ -181,7 +181,7 @@ namespace Content.Server.Access.Systems
}
/// <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.

View File

@@ -38,7 +38,7 @@ namespace Content.Server.Administration.Commands
if (_entManager.TryGetComponent<EntityStorageComponent>(parent, out var storage))
{
entstorage.Remove(entityUid.Value, storage.Owner, storage);
entstorage.Remove(entityUid.Value, parent, storage);
}
else
{

View File

@@ -337,7 +337,7 @@ public sealed partial class AdminVerbSystem
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;

View File

@@ -12,7 +12,8 @@ public sealed class BufferingSystem : EntitySystem
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)
{
@@ -21,7 +22,7 @@ public sealed class BufferingSystem : EntitySystem
continue;
Del(buffering.BufferingIcon.Value);
RemComp<AdminFrozenComponent>(buffering.Owner);
RemComp<AdminFrozenComponent>(uid);
buffering.TimeTilNextBuffer = _random.NextFloat(buffering.MinimumTimeTilNextBuffer, buffering.MaximumTimeTilNextBuffer);
buffering.BufferingIcon = null;
}
@@ -32,8 +33,8 @@ public sealed class BufferingSystem : EntitySystem
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);
}
}
}

View File

@@ -1,7 +1,6 @@
using Content.Server.Power.Components;
using Content.Server.Station.Systems;
using Content.Shared.AlertLevel;
using Robust.Server.GameObjects;
namespace Content.Server.AlertLevel;
@@ -19,9 +18,10 @@ public sealed class AlertLevelDisplaySystem : EntitySystem
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);
}
}

View File

@@ -2,7 +2,6 @@ using System.Linq;
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;
@@ -83,7 +82,8 @@ public sealed class AlertLevelSystem : EntitySystem
return;
}
foreach (var comp in EntityQuery<AlertLevelComponent>())
var query = EntityQueryEnumerator<AlertLevelComponent>();
while (query.MoveNext(out var uid, out var comp))
{
comp.AlertLevels = alerts;
@@ -95,7 +95,7 @@ public sealed class AlertLevelSystem : EntitySystem
defaultLevel = comp.AlertLevels.Levels.Keys.First();
}
SetLevel(comp.Owner, defaultLevel, true, true, true);
SetLevel(uid, defaultLevel, true, true, true);
}
}

View File

@@ -1,9 +1,6 @@
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;
@@ -32,9 +29,11 @@ namespace Content.Server.Animals.Systems
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;
@@ -43,19 +42,19 @@ namespace Content.Server.Animals.Systems
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);
}
}

View File

@@ -28,9 +28,9 @@ public sealed class BluespaceAnomalySystem : EntitySystem
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)
{
@@ -51,7 +51,9 @@ public sealed class BluespaceAnomalySystem : EntitySystem
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);

View File

@@ -1,5 +1,5 @@
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;
@@ -31,9 +31,8 @@ public sealed class ElectricityAnomalySystem : EntitySystem
{
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);
}
}
@@ -66,14 +65,13 @@ public sealed class ElectricityAnomalySystem : EntitySystem
{
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;
@@ -81,11 +79,9 @@ public sealed class ElectricityAnomalySystem : EntitySystem
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);
}
}
}

View File

@@ -1,8 +1,8 @@
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>
@@ -44,7 +44,7 @@ public sealed class InjectionAnomalySystem : EntitySystem
//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

View File

@@ -36,7 +36,10 @@ public sealed class PyroclasticAnomalySystem : EntitySystem
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);

View File

@@ -3,7 +3,7 @@ using Content.Server.Atmos.EntitySystems;
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
{
@@ -11,7 +11,6 @@ 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.";
@@ -30,7 +29,7 @@ namespace Content.Server.Atmos.Commands
return;
}
if (!_mapManager.TryGetGrid(gridId, out var grid))
if (!_entManager.HasComponent<MapGridComponent>(gridId))
{
shell.WriteLine("Invalid grid ID.");
return;
@@ -38,7 +37,7 @@ namespace Content.Server.Atmos.Commands
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);
}

View File

@@ -3,7 +3,7 @@ using Content.Server.Atmos.EntitySystems;
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
{
@@ -11,7 +11,6 @@ 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).";
@@ -34,7 +33,7 @@ namespace Content.Server.Atmos.Commands
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;
@@ -43,7 +42,7 @@ namespace Content.Server.Atmos.Commands
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;

View File

@@ -2,11 +2,8 @@ using Content.Server.Administration;
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
{
@@ -14,7 +11,6 @@ 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).";
@@ -40,7 +36,7 @@ namespace Content.Server.Atmos.Commands
return;
}
if (!_mapManager.TryGetGrid(gridId, out var grid))
if (!_entities.HasComponent<MapGridComponent>(gridId))
{
shell.WriteError("Invalid grid.");
return;
@@ -49,7 +45,7 @@ namespace Content.Server.Atmos.Commands
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)
{

View File

@@ -62,7 +62,7 @@ namespace Content.Server.Atmos.Components
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();
@@ -74,7 +74,7 @@ namespace Content.Server.Atmos.Components
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);

View File

@@ -4,7 +4,6 @@ using Content.Shared.Atmos;
using JetBrains.Annotations;
using Robust.Shared.Map;
using Robust.Shared.Map.Components;
using Content.Shared.Destructible;
namespace Content.Server.Atmos.EntitySystems
{
@@ -24,31 +23,32 @@ 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)
@@ -78,44 +78,47 @@ namespace Content.Server.Atmos.EntitySystems
}
}
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));
@@ -124,15 +127,13 @@ namespace Content.Server.Atmos.EntitySystems
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)
@@ -146,7 +147,8 @@ namespace Content.Server.Atmos.EntitySystems
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();

View File

@@ -4,10 +4,12 @@ using Content.Shared.Atmos;
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
{
@@ -18,6 +20,7 @@ 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.
@@ -31,6 +34,8 @@ namespace Content.Server.Atmos.EntitySystems
/// </summary>
private float _updateCooldown;
private List<Entity<MapGridComponent>> _grids = new();
public override void Initialize()
{
base.Initialize();
@@ -137,7 +142,10 @@ namespace Content.Server.Atmos.EntitySystems
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;
@@ -147,7 +155,7 @@ namespace Content.Server.Atmos.EntitySystems
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];
@@ -161,7 +169,7 @@ namespace Content.Server.Atmos.EntitySystems
}
}
RaiseNetworkEvent(new AtmosDebugOverlayMessage(GetNetEntity(grid.Owner), baseTile, debugOverlayContent), session.ConnectedClient);
RaiseNetworkEvent(new AtmosDebugOverlayMessage(GetNetEntity(grid), baseTile, debugOverlayContent), session.ConnectedClient);
}
}
}

View File

@@ -22,7 +22,7 @@ public sealed partial class AtmosphereSystem
if (TryComp<InternalsComponent>(old, out var internalsComponent))
{
_internals.DisconnectBreathTool(internalsComponent);
_internals.DisconnectBreathTool((old.Value, internalsComponent));
}
component.IsFunctional = false;

View File

@@ -3,7 +3,6 @@ using Content.Server.Administration;
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;
@@ -128,12 +127,13 @@ public sealed partial class AtmosphereSystem
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);

View File

@@ -3,7 +3,6 @@ using Content.Server.Atmos.Components;
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;
@@ -57,7 +56,7 @@ public sealed partial class AtmosphereSystem
tile.GridIndex = uid;
}
GridRepopulateTiles(mapGrid, gridAtmosphere);
GridRepopulateTiles((uid, mapGrid, gridAtmosphere));
}
private void OnGridSplit(EntityUid uid, GridAtmosphereComponent originalGridAtmos, ref GridSplitEvent args)
@@ -65,14 +64,12 @@ public sealed partial class AtmosphereSystem
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();
@@ -505,16 +502,15 @@ public sealed partial class AtmosphereSystem
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;
}
@@ -525,7 +521,7 @@ public sealed partial class AtmosphereSystem
if (args.Handled)
return;
if (!component.AtmosDevices.Remove(args.Device))
if (!component.AtmosDevices.Remove((args.Device.Owner, args.Device)))
return;
args.Device.JoinedGrid = null;
@@ -538,8 +534,9 @@ public sealed partial class AtmosphereSystem
/// </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())
@@ -551,16 +548,14 @@ public sealed partial class AtmosphereSystem
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);
}
}
}

View File

@@ -22,32 +22,34 @@ namespace Content.Server.Atmos.EntitySystems
[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))
@@ -86,10 +88,10 @@ namespace Content.Server.Atmos.EntitySystems
// 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
@@ -118,7 +120,7 @@ namespace Content.Server.Atmos.EntitySystems
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)
@@ -151,12 +153,12 @@ namespace Content.Server.Atmos.EntitySystems
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,
@@ -180,7 +182,7 @@ namespace Content.Server.Atmos.EntitySystems
}
public void ExperiencePressureDifference(
MovedByPressureComponent component,
Entity<MovedByPressureComponent> ent,
int cycle,
float pressureDifference,
AtmosDirection direction,
@@ -190,12 +192,12 @@ namespace Content.Server.Atmos.EntitySystems
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?

View File

@@ -1,16 +1,15 @@
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
{
@@ -28,7 +27,7 @@ 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.
@@ -57,6 +56,7 @@ namespace Content.Server.Atmos.EntitySystems
return;
}
var (_, mapGrid, gridAtmosphere) = ent;
var queueCycle = ++gridAtmosphere.EqualizationQueueCycleControl;
var totalMoles = 0f;
_equalizeTiles[0] = tile;
@@ -91,7 +91,7 @@ namespace Content.Server.Atmos.EntitySystems
{
// Looks like someone opened an airlock to space!
ExplosivelyDepressurize(mapGrid, gridAtmosphere, tile, cycleNum, visuals);
ExplosivelyDepressurize(ent, tile, cycleNum, visuals);
return;
}
}
@@ -359,7 +359,7 @@ namespace Content.Server.Atmos.EntitySystems
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)
@@ -368,6 +368,7 @@ namespace Content.Server.Atmos.EntitySystems
const int limit = Atmospherics.MonstermosHardTileLimit;
var totalMolesRemoved = 0f;
var (owner, mapGrid, gridAtmosphere) = ent;
var queueCycle = ++gridAtmosphere.EqualizationQueueCycleControl;
var tileCount = 0;
@@ -394,7 +395,7 @@ namespace Content.Server.Atmos.EntitySystems
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;
@@ -527,11 +528,11 @@ namespace Content.Server.Atmos.EntitySystems
{
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)
@@ -543,7 +544,7 @@ namespace Content.Server.Atmos.EntitySystems
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;
@@ -566,10 +567,11 @@ namespace Content.Server.Atmos.EntitySystems
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);
}

View File

@@ -26,50 +26,49 @@ namespace Content.Server.Atmos.EntitySystems
/// </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)
@@ -99,8 +98,8 @@ namespace Content.Server.Atmos.EntitySystems
{
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.
@@ -122,11 +121,12 @@ namespace Content.Server.Atmos.EntitySystems
// 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++)
{
@@ -137,7 +137,9 @@ namespace Content.Server.Atmos.EntitySystems
AddActiveTile(atmosphere, otherTile);
}
if (number++ < InvalidCoordinatesLagCheckIterations) continue;
if (number++ < InvalidCoordinatesLagCheckIterations)
continue;
number = 0;
// Process the rest next time.
if (_simulationStopwatch.Elapsed.TotalMilliseconds >= AtmosMaxProcessTime)
@@ -149,22 +151,23 @@ namespace Content.Server.Atmos.EntitySystems
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)
@@ -186,7 +189,9 @@ namespace Content.Server.Atmos.EntitySystems
{
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)
@@ -215,7 +220,9 @@ namespace Content.Server.Atmos.EntitySystems
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)
@@ -227,9 +234,10 @@ namespace Content.Server.Atmos.EntitySystems
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.
@@ -242,14 +250,15 @@ namespace Content.Server.Atmos.EntitySystems
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)
@@ -271,7 +280,9 @@ namespace Content.Server.Atmos.EntitySystems
{
ProcessHotspot(atmosphere, hotspot);
if (number++ < LagCheckIterations) continue;
if (number++ < LagCheckIterations)
continue;
number = 0;
// Process the rest next time.
if (_simulationStopwatch.Elapsed.TotalMilliseconds >= AtmosMaxProcessTime)
@@ -293,7 +304,9 @@ namespace Content.Server.Atmos.EntitySystems
{
Superconduct(atmosphere, superconductivity);
if (number++ < LagCheckIterations) continue;
if (number++ < LagCheckIterations)
continue;
number = 0;
// Process the rest next time.
if (_simulationStopwatch.Elapsed.TotalMilliseconds >= AtmosMaxProcessTime)
@@ -315,7 +328,9 @@ namespace Content.Server.Atmos.EntitySystems
{
pipenet.Update();
if (number++ < LagCheckIterations) continue;
if (number++ < LagCheckIterations)
continue;
number = 0;
// Process the rest next time.
if (_simulationStopwatch.Elapsed.TotalMilliseconds >= AtmosMaxProcessTime)
@@ -346,17 +361,19 @@ namespace Content.Server.Atmos.EntitySystems
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)
@@ -376,7 +393,12 @@ namespace Content.Server.Atmos.EntitySystems
{
_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.
@@ -384,10 +406,11 @@ namespace Content.Server.Atmos.EntitySystems
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;
@@ -401,7 +424,7 @@ namespace Content.Server.Atmos.EntitySystems
switch (atmosphere.State)
{
case AtmosphereProcessingState.Revalidate:
if (!ProcessRevalidate(atmosphere, visuals))
if (!ProcessRevalidate(ent, visuals))
{
atmosphere.ProcessingPaused = true;
return;
@@ -416,7 +439,7 @@ namespace Content.Server.Atmos.EntitySystems
: AtmosphereProcessingState.ActiveTiles;
continue;
case AtmosphereProcessingState.TileEqualize:
if (!ProcessTileEqualize(atmosphere, visuals))
if (!ProcessTileEqualize(ent, visuals))
{
atmosphere.ProcessingPaused = true;
return;
@@ -447,7 +470,7 @@ namespace Content.Server.Atmos.EntitySystems
atmosphere.State = AtmosphereProcessingState.HighPressureDelta;
continue;
case AtmosphereProcessingState.HighPressureDelta:
if (!ProcessHighPressureDelta(atmosphere))
if (!ProcessHighPressureDelta(ent))
{
atmosphere.ProcessingPaused = true;
return;

View File

@@ -4,7 +4,6 @@ using Content.Server.Body.Systems;
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;
@@ -76,15 +75,16 @@ public sealed partial class AtmosphereSystem : SharedAtmosphereSystem
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;

View File

@@ -16,9 +16,7 @@ using Content.Shared.Temperature;
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;
@@ -48,7 +46,7 @@ namespace Content.Server.Atmos.EntitySystems
private float _timer;
private Dictionary<FlammableComponent, float> _fireEvents = new();
private readonly Dictionary<Entity<FlammableComponent>, float> _fireEvents = new();
public override void Initialize()
{
@@ -188,14 +186,14 @@ namespace Content.Server.Atmos.EntitySystems
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)
@@ -295,7 +293,7 @@ namespace Content.Server.Atmos.EntitySystems
{
// 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)
{
@@ -313,10 +311,9 @@ namespace Content.Server.Atmos.EntitySystems
_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)
{

View File

@@ -53,31 +53,35 @@ namespace Content.Server.Atmos.EntitySystems
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,
@@ -87,10 +91,10 @@ namespace Content.Server.Atmos.EntitySystems
});
}
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)
@@ -115,12 +119,12 @@ namespace Content.Server.Atmos.EntitySystems
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;
}
@@ -130,30 +134,33 @@ namespace Content.Server.Atmos.EntitySystems
_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))
@@ -163,47 +170,48 @@ namespace Content.Server.Atmos.EntitySystems
}
}
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;
@@ -215,12 +223,13 @@ namespace Content.Server.Atmos.EntitySystems
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;
@@ -228,7 +237,7 @@ namespace Content.Server.Atmos.EntitySystems
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);
@@ -240,13 +249,14 @@ namespace Content.Server.Atmos.EntitySystems
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;
@@ -259,29 +269,30 @@ namespace Content.Server.Atmos.EntitySystems
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;
@@ -305,7 +316,7 @@ namespace Content.Server.Atmos.EntitySystems
range = GasTankComponent.MaxExplosionRange;
}
_explosions.TriggerExplosive(component.Owner, radius: range);
_explosions.TriggerExplosive(owner, radius: range);
return;
}
@@ -314,13 +325,13 @@ namespace Content.Server.Atmos.EntitySystems
{
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;
}
@@ -332,7 +343,7 @@ namespace Content.Server.Atmos.EntitySystems
{
if (component.Integrity <= 0)
{
var environment = _atmosphereSystem.GetContainingMixture(component.Owner, false, true);
var environment = _atmosphereSystem.GetContainingMixture(owner, false, true);
if (environment == null)
return;

View File

@@ -1,8 +1,7 @@
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;
@@ -87,7 +86,7 @@ public sealed class AtmosMonitorSystem : EntitySystem
if (!HasComp<ApcPowerReceiverComponent>(uid)
&& TryComp<AtmosDeviceComponent>(uid, out var atmosDeviceComponent))
{
_atmosDeviceSystem.LeaveAtmosphere(atmosDeviceComponent);
_atmosDeviceSystem.LeaveAtmosphere((uid, atmosDeviceComponent));
}
}
@@ -155,18 +154,18 @@ public sealed class AtmosMonitorSystem : EntitySystem
}
}
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);
}
}
}
@@ -305,12 +304,13 @@ public sealed class AtmosMonitorSystem : EntitySystem
/// <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
}
@@ -336,11 +336,13 @@ public sealed class AtmosMonitorSystem : EntitySystem
/// 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;
}
@@ -355,7 +357,7 @@ public sealed class AtmosMonitorSystem : EntitySystem
foreach (var addr in monitor.RegisteredDevices)
{
_deviceNetSystem.QueuePacket(monitor.Owner, addr, payload);
_deviceNetSystem.QueuePacket(owner, addr, payload);
}
}
@@ -367,7 +369,8 @@ public sealed class AtmosMonitorSystem : EntitySystem
/// <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)
{
@@ -378,7 +381,8 @@ public sealed class AtmosMonitorSystem : EntitySystem
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;
}

View File

@@ -79,12 +79,12 @@ namespace Content.Server.Atmos.Piping.Binary.EntitySystems
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);
}
}

View File

@@ -1,5 +1,4 @@
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;
@@ -7,6 +6,7 @@ using Content.Server.NodeContainer;
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;
@@ -38,12 +38,13 @@ namespace Content.Server.Atmos.Piping.Binary.EntitySystems
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? _))
{
@@ -68,13 +69,14 @@ namespace Content.Server.Atmos.Piping.Binary.EntitySystems
}
}
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;
}
@@ -92,8 +94,8 @@ namespace Content.Server.Atmos.Piping.Binary.EntitySystems
}
_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)

View File

@@ -7,7 +7,6 @@ using Content.Shared.Audio;
using Content.Shared.Examine;
using Content.Shared.Interaction;
using JetBrains.Annotations;
using Robust.Server.GameObjects;
using Robust.Shared.Audio;
using Robust.Shared.Player;
@@ -29,9 +28,10 @@ namespace Content.Server.Atmos.Piping.Binary.EntitySystems
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,
@@ -50,7 +50,7 @@ namespace Content.Server.Atmos.Piping.Binary.EntitySystems
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)
@@ -60,7 +60,7 @@ namespace Content.Server.Atmos.Piping.Binary.EntitySystems
&& _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);
}
@@ -68,13 +68,13 @@ namespace Content.Server.Atmos.Piping.Binary.EntitySystems
{
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);
}
}
}

View File

@@ -11,10 +11,10 @@ namespace Content.Server.Atmos.Piping.EntitySystems
[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()
{
@@ -27,9 +27,10 @@ namespace Content.Server.Atmos.Piping.EntitySystems
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;
@@ -39,16 +40,17 @@ namespace Content.Server.Atmos.Piping.EntitySystems
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))
{
@@ -59,45 +61,45 @@ namespace Content.Server.Atmos.Piping.EntitySystems
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>
@@ -116,8 +118,8 @@ namespace Content.Server.Atmos.Piping.EntitySystems
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;
}
}
}

View File

@@ -1,13 +1,10 @@
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
{
@@ -24,9 +21,10 @@ 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.
@@ -37,9 +35,9 @@ namespace Content.Server.Atmos.Piping.Other.EntitySystems
_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);

View File

@@ -14,7 +14,6 @@ using Content.Shared.Interaction;
using Content.Shared.Popups;
using JetBrains.Annotations;
using Robust.Server.GameObjects;
using Robust.Shared.Player;
namespace Content.Server.Atmos.Piping.Trinary.EntitySystems
{
@@ -60,16 +59,16 @@ 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;
}
@@ -84,7 +83,7 @@ namespace Content.Server.Atmos.Piping.Trinary.EntitySystems
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);
@@ -95,7 +94,7 @@ namespace Content.Server.Atmos.Piping.Trinary.EntitySystems
filter.Enabled = false;
UpdateAppearance(uid, filter);
_ambientSoundSystem.SetAmbience(filter.Owner, false);
_ambientSoundSystem.SetAmbience(uid, false);
DirtyUI(uid, filter);
_userInterfaceSystem.TryCloseAll(uid, GasFilterUiKey.Key);
@@ -106,7 +105,7 @@ namespace Content.Server.Atmos.Piping.Trinary.EntitySystems
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);
@@ -125,7 +124,7 @@ namespace Content.Server.Atmos.Piping.Trinary.EntitySystems
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)

View File

@@ -7,7 +7,6 @@ using Content.Server.NodeContainer.Nodes;
using Content.Shared.Atmos.Piping;
using Content.Shared.Audio;
using JetBrains.Annotations;
using Robust.Server.GameObjects;
namespace Content.Server.Atmos.Piping.Trinary.EntitySystems
{
@@ -40,7 +39,7 @@ 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;
}
@@ -68,14 +67,14 @@ namespace Content.Server.Atmos.Piping.Trinary.EntitySystems
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);
}
@@ -84,7 +83,7 @@ namespace Content.Server.Atmos.Piping.Trinary.EntitySystems
{
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)

View File

@@ -7,7 +7,6 @@ using Content.Server.NodeContainer.Nodes;
using Content.Shared.Atmos.Piping;
using Content.Shared.Interaction;
using JetBrains.Annotations;
using Robust.Server.GameObjects;
namespace Content.Server.Atmos.Piping.Unary.EntitySystems
{
@@ -40,7 +39,7 @@ 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);

View File

@@ -57,14 +57,16 @@ namespace Content.Server.Bed
{
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)
{
@@ -76,7 +78,7 @@ namespace Content.Server.Bed
if (HasComp<SleepingComponent>(healedEntity))
damage *= bedComponent.SleepMultiplier;
_damageableSystem.TryChangeDamage(healedEntity, damage, true, origin: bedComponent.Owner);
_damageableSystem.TryChangeDamage(healedEntity, damage, true, origin: uid);
}
}
}

View File

@@ -65,7 +65,8 @@ namespace Content.Server.Bible
}
_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)
@@ -79,11 +80,11 @@ namespace Content.Server.Bible
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);
}
}
@@ -167,7 +168,7 @@ namespace Content.Server.Bible
{
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
@@ -183,9 +184,9 @@ namespace Content.Server.Bible
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>
@@ -198,9 +199,9 @@ namespace Content.Server.Bible
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);
}
}
@@ -209,24 +210,26 @@ namespace Content.Server.Bible
/// </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
@@ -237,7 +240,7 @@ namespace Content.Server.Bible
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);

View File

@@ -51,7 +51,7 @@ namespace Content.Server.Body.Commands
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)
{

View File

@@ -81,7 +81,7 @@ public sealed class InternalsSystem : EntitySystem
return;
}
var tank = FindBestGasTank(uid ,internals);
var tank = FindBestGasTank(uid, internals);
if (tank == null)
{
@@ -95,7 +95,7 @@ public sealed class InternalsSystem : EntitySystem
return;
}
_gasTank.ConnectToInternals(tank);
_gasTank.ConnectToInternals(tank.Value);
}
private void StartToggleInternalsDoAfter(EntityUid user, EntityUid target, InternalsComponent internals)
@@ -139,34 +139,36 @@ public sealed class InternalsSystem : EntitySystem
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)
@@ -175,22 +177,23 @@ public sealed class InternalsSystem : EntitySystem
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;
}
@@ -213,7 +216,7 @@ public sealed class InternalsSystem : EntitySystem
return 1;
}
public GasTankComponent? FindBestGasTank(EntityUid internalsOwner, InternalsComponent component)
public Entity<GasTankComponent>? FindBestGasTank(EntityUid internalsOwner, InternalsComponent component)
{
// Prioritise
// 1. back equipped tanks
@@ -227,27 +230,27 @@ public sealed class InternalsSystem : EntitySystem
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];
}
@@ -258,12 +261,12 @@ public sealed class InternalsSystem : EntitySystem
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];
}
}

View File

@@ -37,7 +37,7 @@ public sealed class LungSystem : EntitySystem
if (TryComp(args.Equipee, out InternalsComponent? internals))
{
component.ConnectedInternalsEntity = args.Equipee;
_internals.ConnectBreathTool(internals, uid);
_internals.ConnectBreathTool((args.Equipee, internals), uid);
}
}

View File

@@ -10,7 +10,6 @@ using Content.Shared.Damage;
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
@@ -41,10 +40,9 @@ 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;
@@ -55,7 +53,7 @@ namespace Content.Server.Body.Systems
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.
{
@@ -99,7 +97,7 @@ namespace Content.Server.Body.Systems
// Inhale gas
var ev = new InhaleLocationEvent();
RaiseLocalEvent(uid, ev, false);
RaiseLocalEvent(uid, ev);
ev.Gas ??= _atmosSys.GetContainingMixture(uid, false, true);

View File

@@ -20,7 +20,8 @@ namespace Content.Server.Body.Systems
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;
@@ -30,7 +31,7 @@ namespace Content.Server.Body.Systems
stomach.AccumulatedFrameTime -= stomach.UpdateInterval;
// Get our solutions
if (!_solutionContainerSystem.TryGetSolution(stomach.Owner, DefaultSolutionName,
if (!_solutionContainerSystem.TryGetSolution(uid, DefaultSolutionName,
out var stomachSolution, sol))
continue;
@@ -50,7 +51,7 @@ namespace Content.Server.Body.Systems
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);
}

View File

@@ -12,14 +12,15 @@ public sealed class ThermalRegulatorSystem : EntitySystem
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);
}
}

View File

@@ -3,7 +3,6 @@ using Content.Server.Kitchen.Components;
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;
@@ -39,7 +38,7 @@ public sealed class LogSystem : EntitySystem
else
{
var xform = Transform(plank);
_containerSystem.AttachParentToContainerOrGrid(xform);
_containerSystem.AttachParentToContainerOrGrid((plank, xform));
xform.LocalRotation = 0;
_randomHelper.RandomOffset(plank, 0.25f);
}

View File

@@ -58,13 +58,14 @@ public sealed class PlantHolderSystem : EntitySystem
{
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);
}
}

View File

@@ -1,14 +1,12 @@
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;
@@ -146,7 +144,8 @@ namespace Content.Server.Cargo.Systems
}
_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

View File

@@ -13,6 +13,7 @@ using Content.Shared.Stacks;
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;
@@ -57,7 +58,7 @@ public sealed class PricingSystem : EntitySystem
continue;
}
if (!_mapManager.TryGetGrid(gridId, out var mapGrid))
if (!TryComp(gridId, out MapGridComponent? mapGrid))
{
shell.WriteError($"Grid \"{gridId}\" doesn't exist.");
continue;
@@ -65,7 +66,7 @@ public sealed class PricingSystem : EntitySystem
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));

View File

@@ -1,5 +1,3 @@
namespace Content.Server.Chat.Systems;
using System.Linq;
using Content.Shared.Chat.Prototypes;
using Robust.Shared.Prototypes;
@@ -7,6 +5,8 @@ using Robust.Shared.Random;
using Robust.Shared.Timing;
using Robust.Shared.Utility;
namespace Content.Server.Chat.Systems;
public sealed class AutoEmoteSystem : EntitySystem
{
[Dependency] private readonly IGameTiming _gameTiming = default!;
@@ -27,14 +27,13 @@ public sealed class AutoEmoteSystem : EntitySystem
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;

View File

@@ -45,11 +45,11 @@ namespace Content.Server.Chemistry.EntitySystems
{
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);
@@ -58,12 +58,18 @@ namespace Content.Server.Chemistry.EntitySystems
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;
@@ -72,38 +78,38 @@ namespace Content.Server.Chemistry.EntitySystems
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);
@@ -119,12 +125,12 @@ namespace Content.Server.Chemistry.EntitySystems
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;
}
@@ -145,19 +151,18 @@ namespace Content.Server.Chemistry.EntitySystems
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))
{
@@ -170,10 +175,10 @@ namespace Content.Server.Chemistry.EntitySystems
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)
@@ -186,7 +191,7 @@ namespace Content.Server.Chemistry.EntitySystems
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.
@@ -211,8 +216,8 @@ namespace Content.Server.Chemistry.EntitySystems
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)
{
@@ -232,11 +237,10 @@ namespace Content.Server.Chemistry.EntitySystems
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))
@@ -277,14 +281,14 @@ namespace Content.Server.Chemistry.EntitySystems
}
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;
}
@@ -308,9 +312,9 @@ namespace Content.Server.Chemistry.EntitySystems
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)

View File

@@ -34,11 +34,11 @@ namespace Content.Server.Chemistry.EntitySystems
{
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);
@@ -46,15 +46,20 @@ namespace Content.Server.Chemistry.EntitySystems
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)
@@ -73,8 +78,9 @@ namespace Content.Server.Chemistry.EntitySystems
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
@@ -83,7 +89,7 @@ namespace Content.Server.Chemistry.EntitySystems
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))
{
@@ -93,32 +99,32 @@ namespace Content.Server.Chemistry.EntitySystems
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,
@@ -129,9 +135,9 @@ namespace Content.Server.Chemistry.EntitySystems
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;
@@ -140,9 +146,9 @@ namespace Content.Server.Chemistry.EntitySystems
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));
}
}
}

Some files were not shown because too many files have changed in this diff Show More