Skip to content

Commit

Permalink
Partial MapManager refactor (#5042)
Browse files Browse the repository at this point in the history
* MapManager rejig

* Update Tests

* A
  • Loading branch information
ElectroJr authored Apr 18, 2024
1 parent 8c61706 commit d5c4981
Show file tree
Hide file tree
Showing 91 changed files with 756 additions and 1,082 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,8 @@ public void GlobalSetup()
.InitializeInstance();

_entityManager = _simulation.Resolve<IEntityManager>();

var coords = new MapCoordinates(0, 0, new MapId(1));
_simulation.AddMap(coords.MapId);
var map = _simulation.CreateMap().Uid;
var coords = new EntityCoordinates(map, default);

for (var i = 0; i < N; i++)
{
Expand Down
4 changes: 2 additions & 2 deletions Robust.Benchmarks/EntityManager/ComponentIteratorBenchmark.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ public void GlobalSetup()

Comps = new A[N+2];

var coords = new MapCoordinates(0, 0, new MapId(1));
_simulation.AddMap(coords.MapId);
var map = _simulation.CreateMap().MapId;
var coords = new MapCoordinates(default, map);

for (var i = 0; i < N; i++)
{
Expand Down
4 changes: 2 additions & 2 deletions Robust.Benchmarks/EntityManager/GetComponentBenchmark.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ public void GlobalSetup()

Comps = new A[N+2];

var coords = new MapCoordinates(0, 0, new MapId(1));
_simulation.AddMap(coords.MapId);
var map = _simulation.CreateMap().Uid;
var coords = new EntityCoordinates(map, default);

for (var i = 0; i < N; i++)
{
Expand Down
7 changes: 3 additions & 4 deletions Robust.Benchmarks/EntityManager/SpawnDeleteEntityBenchmark.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,9 @@ public void GlobalSetup()
.InitializeInstance();

_entityManager = _simulation.Resolve<IEntityManager>();

_mapCoords = new MapCoordinates(0, 0, new MapId(1));
var uid = _simulation.AddMap(_mapCoords.MapId);
_entCoords = new EntityCoordinates(uid, 0, 0);
var (map, mapId) = _simulation.CreateMap();
_mapCoords = new MapCoordinates(default, mapId);
_entCoords = new EntityCoordinates(map, 0, 0);
}

[Benchmark(Baseline = true)]
Expand Down
3 changes: 1 addition & 2 deletions Robust.Benchmarks/Transform/RecursiveMoveBenchmark.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,7 @@ public void GlobalSetup()
// Set up map and spawn player
server.WaitPost(() =>
{
var mapId = mapMan.CreateMap();
var map = mapMan.GetMapEntityId(mapId);
var map = server.ResolveDependency<SharedMapSystem>().CreateMap(out var mapId);
var gridComp = mapMan.CreateGridEntity(mapId);
var grid = gridComp.Owner;
mapSys.SetTile(grid, gridComp, Vector2i.Zero, new Tile(1));
Expand Down
19 changes: 11 additions & 8 deletions Robust.Client/GameObjects/EntitySystems/MapSystem.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
using Robust.Client.Graphics;
using Robust.Client.Map;
using Robust.Client.Physics;
using Robust.Client.ResourceManagement;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Map;
using Robust.Shared.Map.Components;
using Robust.Shared.Physics.Dynamics;

namespace Robust.Client.GameObjects;

Expand All @@ -16,6 +13,17 @@ public sealed class MapSystem : SharedMapSystem
[Dependency] private readonly IResourceCache _resource = default!;
[Dependency] private readonly ITileDefinitionManager _tileDefinitionManager = default!;

protected override MapId GetNextMapId()
{
// Client-side map entities use negative map Ids to avoid conflict with server-side maps.
var id = new MapId(--LastMapId);
while (MapManager.MapExists(id))
{
id = new MapId(--LastMapId);
}
return id;
}

public override void Initialize()
{
base.Initialize();
Expand All @@ -27,9 +35,4 @@ public override void Shutdown()
base.Shutdown();
_overlayManager.RemoveOverlay<TileEdgeOverlay>();
}

protected override void OnMapAdd(EntityUid uid, MapComponent component, ComponentAdd args)
{
EnsureComp<PhysicsMapComponent>(uid);
}
}
19 changes: 2 additions & 17 deletions Robust.Client/GameStates/ClientGameStateManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1329,23 +1329,8 @@ private void HandleEntityState(EntityUid uid, NetEntity netEntity, MetaDataCompo

foreach (var (comp, cur, next) in _compStateWork.Values)
{
try
{
var handleState = new ComponentHandleState(cur, next);
bus.RaiseComponentEvent(comp, ref handleState);
}
#pragma warning disable CS0168 // Variable is declared but never used
catch (Exception e)
#pragma warning restore CS0168 // Variable is declared but never used
{
#if EXCEPTION_TOLERANCE
_sawmill.Error($"Failed to apply comp state: entity={_entities.ToPrettyString(uid)}, comp={comp.GetType()}");
_runtimeLog.LogException(e, $"{nameof(ClientGameStateManager)}.{nameof(HandleEntityState)}");
#else
_sawmill.Error($"Failed to apply comp state: entity={_entities.ToPrettyString(uid)}, comp={comp.GetType()}");
throw;
#endif
}
var handleState = new ComponentHandleState(cur, next);
bus.RaiseComponentEvent(comp, ref handleState);
}
}

Expand Down
2 changes: 1 addition & 1 deletion Robust.Client/Graphics/Clyde/Clyde.GridRendering.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ private void CullEmptyChunks()
{
foreach (var (grid, chunks) in _mapChunkData)
{
var gridComp = _mapManager.GetGridComp(grid);
var gridComp = _entityManager.GetComponent<MapGridComponent>(grid);
foreach (var (index, chunk) in chunks)
{
if (!chunk.Dirty || gridComp.Chunks.ContainsKey(index))
Expand Down
4 changes: 1 addition & 3 deletions Robust.Client/Graphics/Clyde/Clyde.HLR.cs
Original file line number Diff line number Diff line change
Expand Up @@ -251,10 +251,8 @@ private List<Overlay> GetOverlaysForSpace(OverlaySpace space)
private void DrawEntities(Viewport viewport, Box2Rotated worldBounds, Box2 worldAABB, IEye eye)
{
var mapId = eye.Position.MapId;
if (mapId == MapId.Nullspace || !_mapManager.HasMapEntity(mapId))
{
if (mapId == MapId.Nullspace)
return;
}

RenderOverlays(viewport, OverlaySpace.WorldSpaceBelowEntities, worldAABB, worldBounds);
var worldOverlays = GetOverlaysForSpace(OverlaySpace.WorldSpaceEntities);
Expand Down
12 changes: 5 additions & 7 deletions Robust.Server/Console/Commands/TestbedCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,11 @@ public override void Execute(IConsoleShell shell, string argStr, string[] args)
}

var mapId = new MapId(mapInt);
if (!_map.MapExists(mapId))
{
shell.WriteError($"map {args[0]} does not exist");
return;
}

if (shell.Player == null)
{
Expand Down Expand Up @@ -110,13 +115,6 @@ public override void Execute(IConsoleShell shell, string argStr, string[] args)

private void SetupPlayer(MapId mapId, IConsoleShell shell)
{
if (mapId == MapId.Nullspace) return;

if (!_map.MapExists(mapId))
{
_map.CreateMap(mapId);
}

_map.SetMapPaused(mapId, false);
var mapUid = _map.GetMapEntityIdOrThrow(mapId);
_ent.System<Gravity2DController>().SetGravity(mapUid, new Vector2(0, -9.8f));
Expand Down
46 changes: 19 additions & 27 deletions Robust.Server/GameObjects/EntitySystems/MapLoaderSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -658,11 +658,12 @@ private void SwapRootNode(MapData data)
var xformQuery = GetEntityQuery<TransformComponent>();
// We just need to cache the old mapuid and point to the new mapuid.

if (HasComp<MapComponent>(rootNode))
if (TryComp(rootNode, out MapComponent? mapComp))
{
// If map exists swap out
if (_mapManager.MapExists(data.TargetMap))
if (_mapSystem.TryGetMap(data.TargetMap, out var existing))
{
data.MapIsPaused = _mapSystem.IsPaused(existing.Value);
// Map exists but we also have a map file with stuff on it soooo swap out the old map.
if (data.Options.LoadMap)
{
Expand All @@ -675,26 +676,28 @@ private void SwapRootNode(MapData data)
data.Options.Rotation = Angle.Zero;
}

_mapManager.SetMapEntity(data.TargetMap, rootNode);
Del(existing);
EnsureComp<LoadedMapComponent>(rootNode);

mapComp.MapId = data.TargetMap;
DebugTools.Assert(mapComp.LifeStage < ComponentLifeStage.Initializing);
}
// Otherwise just ignore the map in the file.
else
{
var oldRootUid = data.Entities[0];
var newRootUid = _mapManager.GetMapEntityId(data.TargetMap);
data.Entities[0] = newRootUid;
data.Entities[0] = existing.Value;

foreach (var ent in data.Entities)
{
if (ent == newRootUid)
if (ent == existing)
continue;

var xform = xformQuery.GetComponent(ent);

if (!xform.ParentUid.IsValid() || xform.ParentUid.Equals(oldRootUid))
{
_transform.SetParent(ent, xform, newRootUid);
_transform.SetParent(ent, xform, existing.Value);
}
}

Expand All @@ -703,16 +706,8 @@ private void SwapRootNode(MapData data)
}
else
{
// If we're loading a file with a map then swap out the entityuid
// TODO: Mapmanager nonsense
var AAAAA = _mapManager.CreateMap(data.TargetMap);

if (!data.MapIsPostInit)
{
_mapManager.AddUninitializedMap(data.TargetMap);
}

_mapManager.SetMapEntity(data.TargetMap, rootNode);
mapComp.MapId = data.TargetMap;
DebugTools.Assert(mapComp.LifeStage < ComponentLifeStage.Initializing);
EnsureComp<LoadedMapComponent>(rootNode);

// Nothing should have invalid uid except for the root node.
Expand All @@ -721,17 +716,14 @@ private void SwapRootNode(MapData data)
else
{
// No map file root, in that case create a new map / get the one we're loading onto.
var mapNode = _mapManager.GetMapEntityId(data.TargetMap);

if (!mapNode.IsValid())
if (!_mapSystem.TryGetMap(data.TargetMap, out var mapNode))
{
// Map doesn't exist so we'll start it up now so we can re-attach the preinit entities to it for later.
_mapManager.CreateMap(data.TargetMap);
_mapManager.AddUninitializedMap(data.TargetMap);
mapNode = _mapManager.GetMapEntityId(data.TargetMap);
DebugTools.Assert(mapNode.IsValid());
mapNode = _mapSystem.CreateMap(data.TargetMap, false);
}

data.MapIsPaused = _mapSystem.IsPaused(mapNode.Value);

// If anything has an invalid parent (e.g. it's some form of root node) then parent it to the map.
foreach (var ent in data.Entities)
{
Expand All @@ -743,12 +735,11 @@ private void SwapRootNode(MapData data)

if (!xform.ParentUid.IsValid())
{
_transform.SetParent(ent, xform, mapNode);
_transform.SetParent(ent, xform, mapNode.Value);
}
}
}

data.MapIsPaused = _mapManager.IsMapPaused(data.TargetMap);
_logLoader.Debug($"Swapped out root node in {_stopwatch.Elapsed}");
}

Expand Down Expand Up @@ -896,6 +887,7 @@ private void StartupEntity(EntityUid uid, MetaDataComponent metadata, MapData da
{
EntityManager.SetLifeStage(metadata, EntityLifeStage.MapInitialized);
}
// TODO MAP LOAD cache this
else if (_mapManager.IsMapInitialized(data.TargetMap))
{
_serverEntityManager.RunMapInit(uid, metadata);
Expand Down Expand Up @@ -964,7 +956,7 @@ public MappingDataNode GetSaveData(EntityUid uid)
// Yes, post-init maps do not have EntityLifeStage >= EntityLifeStage.MapInitialized
bool postInit;
if (TryComp(uid, out MapComponent? mapComp))
postInit = !mapComp.MapPreInit;
postInit = mapComp.MapInitialized;
else
postInit = metadata.EntityLifeStage >= EntityLifeStage.MapInitialized;

Expand Down
17 changes: 11 additions & 6 deletions Robust.Server/GameObjects/EntitySystems/MapSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
using Robust.Shared.Configuration;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Map;
using Robust.Shared.Map.Components;
using Robust.Shared.Map.Events;
using Robust.Shared.Physics.Dynamics;

namespace Robust.Server.GameObjects
{
Expand All @@ -18,6 +18,16 @@ public sealed class MapSystem : SharedMapSystem

private bool _deleteEmptyGrids;

protected override MapId GetNextMapId()
{
var id = new MapId(++LastMapId);
while (MapManager.MapExists(id))
{
id = new MapId(++LastMapId);
}
return id;
}

protected override void UpdatePvsChunks(Entity<TransformComponent, MetaDataComponent> grid)
{
_pvs.GridParentChanged(grid);
Expand All @@ -31,11 +41,6 @@ public override void Initialize()
Subs.CVar(_cfg, CVars.GameDeleteEmptyGrids, SetGridDeletion, true);
}

protected override void OnMapAdd(EntityUid uid, MapComponent component, ComponentAdd args)
{
EnsureComp<PhysicsMapComponent>(uid);
}

private void SetGridDeletion(bool value)
{
_deleteEmptyGrids = value;
Expand Down
10 changes: 4 additions & 6 deletions Robust.Shared/Console/Commands/MapCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ namespace Robust.Shared.Console.Commands;

sealed class AddMapCommand : LocalizedCommands
{
[Dependency] private readonly IMapManager _map = default!;
[Dependency] private readonly IMapManagerInternal _map = default!;
[Dependency] private readonly IEntityManager _entMan = default!;

public override string Command => "addmap";
public override bool RequireServerOrSingleplayer => true;
Expand All @@ -24,11 +25,8 @@ public override void Execute(IConsoleShell shell, string argStr, string[] args)

if (!_map.MapExists(mapId))
{
_map.CreateMap(mapId);
if (args.Length >= 2 && args[1] == "false")
{
_map.AddUninitializedMap(mapId);
}
var init = args.Length < 2 || !bool.Parse(args[1]);
_entMan.System<SharedMapSystem>().CreateMap(mapId, runMapInit: init);

shell.WriteLine($"Map with ID {mapId} created.");
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,6 @@ public Matrix3 InvLocalMatrix
internal bool _mapIdInitialized;
internal bool _gridInitialized;

// TODO: Cache this.
/// <summary>
/// The EntityUid of the map which this object is on, if any.
/// </summary>
Expand Down
5 changes: 5 additions & 0 deletions Robust.Shared/GameObjects/EntityManager.Components.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1013,6 +1013,11 @@ public IEnumerable<IComponent> GetComponents(EntityUid uid)
}
}

/// <summary>
/// Internal variant of <see cref="GetComponents"/> that directly returns the actual component set.
/// </summary>
internal IReadOnlyCollection<IComponent> GetComponentsInternal(EntityUid uid) => _entCompIndex[uid];

/// <inheritdoc />
public int ComponentCount(EntityUid uid)
{
Expand Down
Loading

0 comments on commit d5c4981

Please sign in to comment.