Compare commits

..

25 Commits

Author SHA1 Message Date
Pieter-Jan Briers
ab99d5be07 Version: 219.2.2 2024-08-11 19:32:35 +02:00
Pieter-Jan Briers
11c05509cb Compile compat fixes
(cherry picked from commit 025d90d281)
(cherry picked from commit 799702b814)
(cherry picked from commit 4600ee8e5788891f1b610e2d5141fb4e1228d323)
2024-08-11 19:32:35 +02:00
Pieter-Jan Briers
e1120b0d4c Version: 219.2.1 2024-08-11 17:56:08 +02:00
Pieter-Jan Briers
73c22ff6ac Security updates (#5353)
* Fix security bug in WritableDirProvider.OpenOsWindow()

Reported by @NarryG and @nyeogmi

* Sandbox updates

* Update ImageSharp again

(cherry picked from commit 7d778248ee)
(cherry picked from commit f66cda74e95619ddba2221bda644bf4394619805)
(cherry picked from commit db8ba83866c523e08e4fba0b80cd954f4f190613)
2024-08-11 17:56:08 +02:00
metalgearsloth
eb63809999 Version: 219.2.0 2024-04-25 00:31:04 +10:00
Leon Friedrich
4c3c74865c Fix yaml linter & improve validation of static fields (#5056) 2024-04-25 00:27:02 +10:00
Nemanja
b624f5b70f Add SetMapCoordinates (#5065)
* add set map coordinates function

* mmmmmmm yes

* Update Robust.Shared/GameObjects/Systems/SharedTransformSystem.Component.cs

---------

Co-authored-by: metalgearsloth <31366439+metalgearsloth@users.noreply.github.com>
2024-04-24 22:55:58 +10:00
Pieter-Jan Briers
6566a7658a Fix DebugCoordsPanel freezing when hovering a UI control.
It would bail out of the entire update logic if you aren't hovering over a map position, which isn't great when the control displays far more than in-simulation mouse position info.
2024-04-23 20:34:29 +02:00
metalgearsloth
9e3e1cc929 Optimise physics networking a lot (#5064)
Avoids unnecessarily dirtying every single tick when a mob is moving. Also avoids the getcomponent every time which is nice.
2024-04-23 22:36:40 +10:00
ElectroJr
4e87d93009 Version: 219.1.3 2024-04-23 00:26:17 -04:00
Leon Friedrich
1031ae4cc5 Fix mapping not pausing maps (#5063) 2024-04-23 14:25:40 +10:00
ElectroJr
73da147b88 Version: 219.1.2 2024-04-21 04:58:44 -04:00
Leon Friedrich
0ab59d70b1 More mapinit fixes (#5058) 2024-04-21 18:57:20 +10:00
ElectroJr
8e8470ac7e Version: 219.1.1 2024-04-21 02:50:34 -04:00
Leon Friedrich
15f94bd094 Fix mapinit persistence when overwriting existing maps (#5057)
* Fix mapinit persistence when overwriting existing maps

* Hours wasted chasing fucking chickens in a crate
2024-04-21 16:48:39 +10:00
DrSmugleaf
68888c4370 Make remaining IPrototypes partial (#5053) 2024-04-21 07:39:54 +10:00
ElectroJr
19f87dfbb3 Version: 219.1.0 2024-04-20 16:52:47 -04:00
Leon Friedrich
68e5b6924d Add ComponentRegistry overrides to more entity spawn methods (#5051) 2024-04-19 13:16:17 +10:00
Leon Friedrich
9f913cd2d9 Fix RecursiveMapInit (#5052)
* Fix RecursiveMapInit

* re-use sawmill
2024-04-19 13:15:42 +10:00
Vasilis
ec37d1c137 Auth is now required by default (#5050) 2024-04-18 17:51:25 +02:00
metalgearsloth
ea58924495 Audio stuff (#5048)
Better overlay debug and uses the adjusted distance for cutoff instead.
2024-04-18 14:36:29 +10:00
keronshb
c5aa735506 Adds rotation to Map Position spawns (#5047)
* add angle to rotation

* fixes inheritance

* proxy

* Fixes maprot

* changes angle to default and uses set coords overload
2024-04-18 14:25:07 +10:00
metalgearsloth
f5a6e52c7f Version: 219.0.0 2024-04-18 14:16:40 +10:00
Leon Friedrich
d5c4981648 Partial MapManager refactor (#5042)
* MapManager rejig

* Update Tests

* A
2024-04-18 14:05:02 +10:00
Pieter-Jan Briers
8c6170661d Die 2024-04-18 03:11:24 +02:00
125 changed files with 1397 additions and 1313 deletions

View File

@@ -33,10 +33,10 @@ jobs:
mkdir "release/${{ steps.parse_version.outputs.version }}"
mv release/*.zip "release/${{ steps.parse_version.outputs.version }}"
- name: Upload files to centcomm
- name: Upload files to Suns
uses: appleboy/scp-action@master
with:
host: centcomm.spacestation14.io
host: suns.spacestation14.com
username: robust-build-push
key: ${{ secrets.CENTCOMM_ROBUST_BUILDS_PUSH_KEY }}
source: "release/${{ steps.parse_version.outputs.version }}"
@@ -46,7 +46,7 @@ jobs:
- name: Update manifest JSON
uses: appleboy/ssh-action@master
with:
host: centcomm.spacestation14.io
host: suns.spacestation14.com
username: robust-build-push
key: ${{ secrets.CENTCOMM_ROBUST_BUILDS_PUSH_KEY }}
script: /home/robust-build-push/push.ps1 ${{ steps.parse_version.outputs.version }}

View File

@@ -1,4 +1,14 @@
<Project>
<PropertyGroup>
<!--
We actually set ManagePackageVersionsCentrally manually in another import file.
Since .NET SDK 8.0.300, ManagePackageVersionsCentrally is automatically set if Directory.Packages.props exists.
https://github.com/NuGet/NuGet.Client/pull/5572
We actively negate this here, as we have some packages in tree we don't want such automatic behavior for.
We use Directory.Build.props to get copy the state *after* our MSBuild config but before Nuget's config.
-->
<ManagePackageVersionsCentrally />
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="BenchmarkDotNet" Version="0.13.12" />
<PackageVersion Include="DiscordRichPresence" Version="1.2.1.24" />
@@ -45,7 +55,7 @@
<PackageVersion Include="Serilog" Version="3.1.1" />
<PackageVersion Include="Serilog.Sinks.Loki" Version="4.0.0-beta3" />
<PackageVersion Include="SharpZstd.Interop" Version="1.5.2-beta2" />
<PackageVersion Include="SixLabors.ImageSharp" Version="3.1.3" />
<PackageVersion Include="SixLabors.ImageSharp" Version="3.1.5" />
<PackageVersion Include="SpaceWizards.HttpListener" Version="0.1.0" />
<PackageVersion Include="SpaceWizards.NFluidsynth" Version="0.1.1" />
<PackageVersion Include="SpaceWizards.SharpFont" Version="1.0.2" />

View File

@@ -1,4 +1,4 @@
<Project>
<!-- This file automatically reset by Tools/version.py -->
<!-- This file automatically reset by Tools/version.py -->

View File

@@ -54,6 +54,71 @@ END TEMPLATE-->
*None yet*
## 219.2.2
## 219.2.1
## 219.2.0
### New features
* Add SetMapCoordinates to TransformSystem.
* Improve YAML Linter and validation of static fields.
### Bugfixes
* Fix DebugCoordsPanel freezing when hovering a control.
### Other
* Optimise physics networking to not dirty every tick of movement.
## 219.1.3
### Bugfixes
* Fix map-loader not pausing pre-init maps when not actively overwriting an existing map.
## 219.1.2
### Bugfixes
* Fix map-loader not map-initialising grids when loading into a post-init map.
## 219.1.1
### Bugfixes
* Fix map-loader not map-initialising maps when overwriting a post-init map.
## 219.1.0
### New features
* Added a new optional arguments to various entity spawning methods, including a new argument to set the entity's rotation.
### Bugfixes
* Fixes map initialisation not always initialising all entities on a map.
### Other
* The default value of the `auth.mode` cvar has changed
## 219.0.0
### Breaking changes
* Move most IMapManager functionality to SharedMapSystem.
## 218.2.0
### New features

View File

@@ -26,9 +26,8 @@ public partial class AddRemoveComponentBenchmark
.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++)
{

View File

@@ -29,8 +29,8 @@ public partial class ComponentIteratorBenchmark
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++)
{

View File

@@ -31,8 +31,8 @@ public partial class GetComponentBenchmark
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++)
{

View File

@@ -29,10 +29,9 @@ public partial class SpawnDeleteEntityBenchmark
.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)]

View File

@@ -91,8 +91,7 @@ public class RecursiveMoveBenchmark : RobustIntegrationTest
// 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));

View File

@@ -74,11 +74,13 @@ public sealed class AudioOverlay : Overlay
output.Clear();
output.AppendLine("Audio Source");
output.AppendLine("Runtime:");
output.AppendLine($"- Distance: {_audio.GetAudioDistance(distance.Length()):0.00}");
output.AppendLine($"- Occlusion: {posOcclusion:0.0000}");
output.AppendLine("Params:");
output.AppendLine($"- RolloffFactor: {comp.RolloffFactor:0.0000}");
output.AppendLine($"- Volume: {comp.Volume:0.0000}");
output.AppendLine($"- Reference distance: {comp.ReferenceDistance}");
output.AppendLine($"- Max distance: {comp.MaxDistance}");
output.AppendLine($"- Reference distance: {comp.ReferenceDistance:0.00}");
output.AppendLine($"- Max distance: {comp.MaxDistance:0.00}");
var outputText = output.ToString().Trim();
var dimensions = screenHandle.GetDimensions(_font, outputText, 1f);
var buffer = new Vector2(3f, 3f);

View File

@@ -388,7 +388,7 @@ public sealed partial class AudioSystem : SharedAudioSystem
var distance = delta.Length();
// Out of range so just clip it for us.
if (distance > component.MaxDistance)
if (GetAudioDistance(distance) > component.MaxDistance)
{
// Still keeps the source playing, just with no volume.
component.Gain = 0f;

View File

@@ -285,6 +285,7 @@ namespace Robust.Client
/// <summary>
/// Enumeration of the run levels of the BaseClient.
/// </summary>
/// <seealso cref="ClientRunLevelExt"/>
public enum ClientRunLevel : byte
{
Error = 0,
@@ -315,6 +316,21 @@ namespace Robust.Client
SinglePlayerGame,
}
/// <summary>
/// Helper functions for working with <see cref="ClientRunLevel"/>.
/// </summary>
public static class ClientRunLevelExt
{
/// <summary>
/// Check if a <see cref="ClientRunLevel"/> is <see cref="ClientRunLevel.InGame"/>
/// or <see cref="ClientRunLevel.SinglePlayerGame"/>.
/// </summary>
public static bool IsInGameLike(this ClientRunLevel runLevel)
{
return runLevel is ClientRunLevel.InGame or ClientRunLevel.SinglePlayerGame;
}
}
/// <summary>
/// Event arguments for when something changed with the player.
/// </summary>

View File

@@ -11,7 +11,7 @@ namespace Robust.Client.Console.Commands
public override void Execute(IConsoleShell shell, string argStr, string[] args)
{
var type = Type.GetType(args[0]);
var type = GetType(args[0]);
if (type == null)
{
@@ -25,6 +25,17 @@ namespace Robust.Client.Console.Commands
shell.WriteLine(sig);
}
}
private Type? GetType(string name)
{
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
if (assembly.GetType(name) is { } type)
return type;
}
return null;
}
}
#endif
}

View File

@@ -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;
@@ -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();
@@ -27,9 +35,4 @@ public sealed class MapSystem : SharedMapSystem
base.Shutdown();
_overlayManager.RemoveOverlay<TileEdgeOverlay>();
}
protected override void OnMapAdd(EntityUid uid, MapComponent component, ComponentAdd args)
{
EnsureComp<PhysicsMapComponent>(uid);
}
}

View File

@@ -1329,23 +1329,8 @@ namespace Robust.Client.GameStates
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);
}
}

View File

@@ -124,7 +124,7 @@ namespace Robust.Client.Graphics.Clyde
{
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))

View File

@@ -251,10 +251,8 @@ namespace Robust.Client.Graphics.Clyde
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);

View File

@@ -17,7 +17,7 @@ using Vector4 = Robust.Shared.Maths.Vector4;
namespace Robust.Client.Graphics
{
[Prototype("shader")]
public sealed class ShaderPrototype : IPrototype, ISerializationHooks
public sealed partial class ShaderPrototype : IPrototype, ISerializationHooks
{
[ViewVariables]
[IdDataField]

View File

@@ -5,7 +5,6 @@ using Robust.Shared.Timing;
namespace Robust.Client.UserInterface.Controllers;
// Notices your UIController, *UwU Whats this?*
/// <summary>
/// Each <see cref="UIController"/> is instantiated as a singleton by <see cref="UserInterfaceManager"/>
/// <see cref="UIController"/> can use <see cref="DependencyAttribute"/> for regular IoC dependencies

View File

@@ -20,6 +20,7 @@ namespace Robust.Client.UserInterface.CustomControls.DebugMonitorControls
[Dependency] private readonly IEntityManager _entityManager = default!;
[Dependency] private readonly IClyde _displayManager = default!;
[Dependency] private readonly IMapManager _mapManager = default!;
[Dependency] private readonly IBaseClient _baseClient = default!;
private readonly StringBuilder _textBuilder = new();
private readonly char[] _textBuffer = new char[1024];
@@ -58,30 +59,36 @@ namespace Robust.Client.UserInterface.CustomControls.DebugMonitorControls
_textBuilder.Clear();
var isInGame = _baseClient.RunLevel.IsInGameLike();
var mouseScreenPos = _inputManager.MouseScreenPosition;
var screenSize = _displayManager.ScreenSize;
var screenScale = _displayManager.MainWindow.ContentScale;
EntityCoordinates mouseGridPos;
TileRef tile;
EntityCoordinates mouseGridPos = default;
TileRef tile = default;
MapCoordinates mouseWorldMap = default;
var mouseWorldMap = _eyeManager.PixelToMap(mouseScreenPos);
if (mouseWorldMap == MapCoordinates.Nullspace)
return;
var mapSystem = _entityManager.System<SharedMapSystem>();
var xformSystem = _entityManager.System<SharedTransformSystem>();
if (_mapManager.TryFindGridAt(mouseWorldMap, out var mouseGridUid, out var mouseGrid))
if (isInGame)
{
mouseGridPos = mapSystem.MapToGrid(mouseGridUid, mouseWorldMap);
tile = mapSystem.GetTileRef(mouseGridUid, mouseGrid, mouseGridPos);
}
else
{
mouseGridPos = new EntityCoordinates(_mapManager.GetMapEntityId(mouseWorldMap.MapId),
mouseWorldMap.Position);
tile = new TileRef(EntityUid.Invalid, mouseGridPos.ToVector2i(_entityManager, _mapManager, xformSystem), Tile.Empty);
mouseWorldMap = _eyeManager.PixelToMap(mouseScreenPos);
if (mouseWorldMap != MapCoordinates.Nullspace)
{
var mapSystem = _entityManager.System<SharedMapSystem>();
var xformSystem = _entityManager.System<SharedTransformSystem>();
if (_mapManager.TryFindGridAt(mouseWorldMap, out var mouseGridUid, out var mouseGrid))
{
mouseGridPos = mapSystem.MapToGrid(mouseGridUid, mouseWorldMap);
tile = mapSystem.GetTileRef(mouseGridUid, mouseGrid, mouseGridPos);
}
else
{
mouseGridPos = new EntityCoordinates(_mapManager.GetMapEntityId(mouseWorldMap.MapId),
mouseWorldMap.Position);
tile = new TileRef(EntityUid.Invalid,
mouseGridPos.ToVector2i(_entityManager, _mapManager, xformSystem), Tile.Empty);
}
}
}
var controlHovered = UserInterfaceManager.CurrentlyHovered;
@@ -95,32 +102,37 @@ Mouse Pos:
{tile}
GUI: {controlHovered}");
_textBuilder.AppendLine("\nAttached NetEntity:");
var controlledEntity = _playerManager.LocalSession?.AttachedEntity ?? EntityUid.Invalid;
if (controlledEntity == EntityUid.Invalid)
if (isInGame)
{
_textBuilder.AppendLine("No attached netentity.");
}
else
{
var entityTransform = _entityManager.GetComponent<TransformComponent>(controlledEntity);
var playerWorldOffset = xformSystem.GetMapCoordinates(entityTransform);
var playerScreen = _eyeManager.WorldToScreen(playerWorldOffset.Position);
var xformSystem = _entityManager.System<SharedTransformSystem>();
var playerCoordinates = entityTransform.Coordinates;
var playerRotation = xformSystem.GetWorldRotation(entityTransform);
var gridRotation = entityTransform.GridUid != null
? xformSystem.GetWorldRotation(entityTransform.GridUid.Value)
: Angle.Zero;
_textBuilder.AppendLine("\nAttached NetEntity:");
var controlledEntity = _playerManager.LocalSession?.AttachedEntity ?? EntityUid.Invalid;
_textBuilder.Append($@" Screen: {playerScreen}
if (controlledEntity == EntityUid.Invalid)
{
_textBuilder.AppendLine("No attached netentity.");
}
else
{
var entityTransform = _entityManager.GetComponent<TransformComponent>(controlledEntity);
var playerWorldOffset = xformSystem.GetMapCoordinates(entityTransform);
var playerScreen = _eyeManager.WorldToScreen(playerWorldOffset.Position);
var playerCoordinates = entityTransform.Coordinates;
var playerRotation = xformSystem.GetWorldRotation(entityTransform);
var gridRotation = entityTransform.GridUid != null
? xformSystem.GetWorldRotation(entityTransform.GridUid.Value)
: Angle.Zero;
_textBuilder.Append($@" Screen: {playerScreen}
{playerWorldOffset}
{_entityManager.GetNetCoordinates(playerCoordinates)}
Rotation: {playerRotation.Degrees:F2}°
NEntId: {_entityManager.GetNetEntity(controlledEntity)}
Grid NEntId: {_entityManager.GetNetEntity(entityTransform.GridUid)}
Grid Rotation: {gridRotation.Degrees:F2}°");
}
}
_contents.TextMemory = FormatHelpers.BuilderToMemory(_textBuilder, _textBuffer);

View File

@@ -5,7 +5,7 @@ using Robust.Shared.Utility;
namespace Robust.Client.UserInterface.RichText;
[Prototype("font")]
public sealed class FontPrototype : IPrototype
public sealed partial class FontPrototype : IPrototype
{
[IdDataField]
public string ID { get; private set; } = default!;

View File

@@ -1,12 +1,10 @@
using System;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Robust.Client.Graphics;
using Robust.Client.ResourceManagement;
using Robust.Shared.ContentPack;
using Robust.Shared.Graphics;
using Robust.Shared.IoC;
using Robust.Shared.Log;
using Robust.Shared.Maths;
@@ -18,7 +16,7 @@ using Robust.Shared.ViewVariables;
namespace Robust.Client.UserInterface.Themes;
[Prototype("uiTheme")]
public sealed class UITheme : IPrototype
public sealed partial class UITheme : IPrototype
{
private IResourceCache? _cache;
private IUserInterfaceManager? _uiMan;

View File

@@ -70,6 +70,11 @@ namespace Robust.Server.Console.Commands
}
var mapId = new MapId(mapInt);
if (!_map.MapExists(mapId))
{
shell.WriteError($"map {args[0]} does not exist");
return;
}
if (shell.Player == null)
{
@@ -110,13 +115,6 @@ namespace Robust.Server.Console.Commands
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));

View File

@@ -49,7 +49,6 @@ public sealed class MapLoaderSystem : EntitySystem
private ISawmill _logLoader = default!;
private ISawmill _logWriter = default!;
private static readonly MapLoadOptions DefaultLoadOptions = new();
private const int MapFormatVersion = 6;
private const int BackwardsVersion = 2;
@@ -132,7 +131,7 @@ public sealed class MapLoaderSystem : EntitySystem
public bool TryLoad(MapId mapId, string path, [NotNullWhen(true)] out IReadOnlyList<EntityUid>? rootUids,
MapLoadOptions? options = null)
{
options ??= DefaultLoadOptions;
options ??= new();
var resPath = new ResPath(path).ToRootedPath();
@@ -658,11 +657,13 @@ public sealed class MapLoaderSystem : EntitySystem
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.Options.DoMapInit |= _mapSystem.IsInitialized(data.TargetMap);
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)
{
@@ -675,26 +676,28 @@ public sealed class MapLoaderSystem : EntitySystem
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);
}
}
@@ -703,16 +706,9 @@ public sealed class MapLoaderSystem : EntitySystem
}
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);
data.MapIsPaused = !data.MapIsPostInit;
mapComp.MapId = data.TargetMap;
DebugTools.Assert(mapComp.LifeStage < ComponentLifeStage.Initializing);
EnsureComp<LoadedMapComponent>(rootNode);
// Nothing should have invalid uid except for the root node.
@@ -721,17 +717,15 @@ public sealed class MapLoaderSystem : EntitySystem
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.Options.DoMapInit |= _mapSystem.IsInitialized(data.TargetMap);
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)
{
@@ -743,12 +737,11 @@ public sealed class MapLoaderSystem : EntitySystem
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}");
}
@@ -896,7 +889,7 @@ public sealed class MapLoaderSystem : EntitySystem
{
EntityManager.SetLifeStage(metadata, EntityLifeStage.MapInitialized);
}
else if (_mapManager.IsMapInitialized(data.TargetMap))
else if (data.Options.DoMapInit)
{
_serverEntityManager.RunMapInit(uid, metadata);
}
@@ -964,7 +957,7 @@ public sealed class MapLoaderSystem : EntitySystem
// 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;
@@ -1098,17 +1091,17 @@ public sealed class MapLoaderSystem : EntitySystem
}
}
private bool IsSaveable(EntityUid uid, EntityQuery<MetaDataComponent> metaQuery, EntityQuery<TransformComponent> transformQuery)
private bool IsSaveable(EntityUid uid)
{
// Don't serialize things parented to un savable things.
// For example clothes inside a person.
while (uid.IsValid())
{
var meta = metaQuery.GetComponent(uid);
var meta = MetaData(uid);
if (meta.EntityDeleted || meta.EntityPrototype?.MapSavable == false) break;
uid = transformQuery.GetComponent(uid).ParentUid;
uid = Transform(uid).ParentUid;
}
// If we manage to get up to the map (root node) then it's saveable.
@@ -1123,7 +1116,7 @@ public sealed class MapLoaderSystem : EntitySystem
EntityQuery<TransformComponent> transformQuery,
EntityQuery<MapSaveIdComponent> saveCompQuery)
{
if (!IsSaveable(uid, metaQuery, transformQuery))
if (!IsSaveable(uid))
return;
entities.Add(uid);

View File

@@ -5,9 +5,9 @@ using Robust.Shared.Collections;
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
{
@@ -18,6 +18,16 @@ namespace Robust.Server.GameObjects
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);
@@ -31,11 +41,6 @@ namespace Robust.Server.GameObjects
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;

View File

@@ -53,5 +53,7 @@ namespace Robust.Server.Maps
/// This should be set to false if you want to load a map file onto an existing map and do not wish to overwrite the existing entity.
/// </remarks>
public bool LoadMap { get; set; } = true;
public bool DoMapInit = false;
}
}

View File

@@ -10,7 +10,7 @@ namespace Robust.Shared.Audio;
/// to allow the server to know audio lengths without shipping the large audio files themselves.
/// </summary>
[Prototype(ProtoName)]
public sealed class AudioMetadataPrototype : IPrototype
public sealed partial class AudioMetadataPrototype : IPrototype
{
public const string ProtoName = "audioMetadata";

View File

@@ -9,7 +9,7 @@ namespace Robust.Shared.Audio;
/// This can be used by <see cref="Content.Shared.Audio.SharedContentAudioSystem"/> to apply an audio preset.
/// </summary>
[Prototype("audioPreset")]
public sealed class AudioPresetPrototype : IPrototype
public sealed partial class AudioPresetPrototype : IPrototype
{
[IdDataField]
public string ID { get; } = default!;

View File

@@ -1,13 +1,13 @@
using System.Collections.Generic;
using Robust.Shared.Prototypes;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.Utility;
using Robust.Shared.ViewVariables;
using System.Collections.Generic;
namespace Robust.Shared.Audio;
[Prototype("soundCollection")]
public sealed class SoundCollectionPrototype : IPrototype
public sealed partial class SoundCollectionPrototype : IPrototype
{
[ViewVariables]
[IdDataField]

View File

@@ -851,7 +851,7 @@ namespace Robust.Shared
/// See the documentation of the <see cref="Network.AuthMode"/> enum for values.
/// </summary>
public static readonly CVarDef<int> AuthMode =
CVarDef.Create("auth.mode", (int) Network.AuthMode.Optional, CVar.SERVERONLY);
CVarDef.Create("auth.mode", (int) Network.AuthMode.Required, CVar.SERVERONLY);
/// <summary>
/// Allow unauthenticated localhost connections, even if the auth mode is set to required.

View File

@@ -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;
@@ -24,11 +25,8 @@ sealed class AddMapCommand : LocalizedCommands
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;

View File

@@ -32,7 +32,7 @@ namespace Robust.Shared.ContentPack
String("short").ThenReturn(PrimitiveTypeCode.Int16);
private static readonly Parser<char, PrimitiveTypeCode> UInt16TypeParser =
String("ushort").ThenReturn(PrimitiveTypeCode.UInt32);
String("ushort").ThenReturn(PrimitiveTypeCode.UInt16);
private static readonly Parser<char, PrimitiveTypeCode> Int32TypeParser =
String("int").ThenReturn(PrimitiveTypeCode.Int32);

View File

@@ -84,12 +84,146 @@ Types:
- "bool get_HasContents()"
Lidgren.Network:
NetBuffer:
All: True
Methods:
- "byte[] get_Data()"
- "void set_Data(byte[])"
- "int get_LengthBytes()"
- "void set_LengthBytes(int)"
- "int get_LengthBits()"
- "void set_LengthBits(int)"
- "long get_Position()"
- "void set_Position(long)"
- "int get_PositionInBytes()"
- "byte[] PeekDataBuffer()"
- "bool PeekBoolean()"
- "byte PeekByte()"
- "sbyte PeekSByte()"
- "byte PeekByte(int)"
- "System.Span`1<byte> PeekBytes(System.Span`1<byte>)"
- "byte[] PeekBytes(int)"
- "void PeekBytes(byte[], int, int)"
- "short PeekInt16()"
- "ushort PeekUInt16()"
- "int PeekInt32()"
- "int PeekInt32(int)"
- "uint PeekUInt32()"
- "uint PeekUInt32(int)"
- "ulong PeekUInt64()"
- "long PeekInt64()"
- "ulong PeekUInt64(int)"
- "long PeekInt64(int)"
- "float PeekFloat()"
- "System.Half PeekHalf()"
- "float PeekSingle()"
- "double PeekDouble()"
- "string PeekString()"
- "int PeekStringSize()"
- "bool ReadBoolean()"
- "byte ReadByte()"
- "bool ReadByte(ref byte)"
- "sbyte ReadSByte()"
- "byte ReadByte(int)"
- "System.Span`1<byte> ReadBytes(System.Span`1<byte>)"
- "byte[] ReadBytes(int)"
- "bool ReadBytes(int, ref byte[])"
- "bool TryReadBytes(System.Span`1<byte>)"
- "void ReadBytes(byte[], int, int)"
- "void ReadBits(System.Span`1<byte>, int)"
- "void ReadBits(byte[], int, int)"
- "short ReadInt16()"
- "ushort ReadUInt16()"
- "int ReadInt32()"
- "bool ReadInt32(ref int)"
- "int ReadInt32(int)"
- "uint ReadUInt32()"
- "bool ReadUInt32(ref uint)"
- "uint ReadUInt32(int)"
- "ulong ReadUInt64()"
- "long ReadInt64()"
- "ulong ReadUInt64(int)"
- "long ReadInt64(int)"
- "float ReadFloat()"
- "System.Half ReadHalf()"
- "float ReadSingle()"
- "bool ReadSingle(ref float)"
- "double ReadDouble()"
- "uint ReadVariableUInt32()"
- "bool ReadVariableUInt32(ref uint)"
- "int ReadVariableInt32()"
- "long ReadVariableInt64()"
- "ulong ReadVariableUInt64()"
- "float ReadSignedSingle(int)"
- "float ReadUnitSingle(int)"
- "float ReadRangedSingle(float, float, int)"
- "int ReadRangedInteger(int, int)"
- "long ReadRangedInteger(long, long)"
- "string ReadString()"
- "bool ReadString(ref string)"
- "double ReadTime(Lidgren.Network.NetConnection, bool)"
- "System.Net.IPEndPoint ReadIPEndPoint()"
- "void SkipPadBits()"
- "void ReadPadBits()"
- "void SkipPadBits(int)"
- "void EnsureBufferSize(int)"
- "void Write(bool)"
- "void Write(byte)"
- "void WriteAt(int, byte)"
- "void Write(sbyte)"
- "void Write(byte, int)"
- "void Write(byte[])"
- "void Write(System.ReadOnlySpan`1<byte>)"
- "void Write(byte[], int, int)"
- "void Write(ushort)"
- "void WriteAt(int, ushort)"
- "void Write(ushort, int)"
- "void Write(short)"
- "void WriteAt(int, short)"
- "void Write(int)"
- "void WriteAt(int, int)"
- "void Write(uint)"
- "void WriteAt(int, uint)"
- "void Write(uint, int)"
- "void Write(int, int)"
- "void Write(ulong)"
- "void WriteAt(int, ulong)"
- "void Write(ulong, int)"
- "void Write(long)"
- "void Write(long, int)"
- "void Write(System.Half)"
- "void Write(float)"
- "void Write(double)"
- "int WriteVariableUInt32(uint)"
- "int WriteVariableInt32(int)"
- "int WriteVariableInt64(long)"
- "int WriteVariableUInt64(ulong)"
- "void WriteSignedSingle(float, int)"
- "void WriteUnitSingle(float, int)"
- "void WriteRangedSingle(float, float, float, int)"
- "int WriteRangedInteger(int, int, int)"
- "int WriteRangedInteger(long, long, long)"
- "void Write(string)"
- "void Write(System.Net.IPEndPoint)"
- "void WriteTime(bool)"
- "void WriteTime(double, bool)"
- "void WritePadBits()"
- "void WritePadBits(int)"
- "void Write(Lidgren.Network.NetBuffer)"
- "void Zero(int)"
- "void .ctor()"
NetDeliveryMethod: { }
NetIncomingMessage:
All: True
Methods:
- "Lidgren.Network.NetIncomingMessageType get_MessageType()"
- "Lidgren.Network.NetDeliveryMethod get_DeliveryMethod()"
- "int get_SequenceChannel()"
- "System.Net.IPEndPoint get_SenderEndPoint()"
- "Lidgren.Network.NetConnection get_SenderConnection()"
- "double get_ReceiveTime()"
- "double ReadTime(bool)"
- "string ToString()"
NetOutgoingMessage:
All: True
Methods:
- "string ToString()"
Nett:
CommentLocation: { } # Enum
Toml:

View File

@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using Robust.Shared.Utility;
namespace Robust.Shared.ContentPack
@@ -135,11 +136,37 @@ namespace Robust.Shared.ContentPack
path = path.Directory;
var fullPath = GetFullPath(path);
Process.Start(new ProcessStartInfo
if (OperatingSystem.IsWindows())
{
UseShellExecute = true,
FileName = fullPath,
});
Process.Start(new ProcessStartInfo
{
FileName = "explorer.exe",
Arguments = ".",
WorkingDirectory = fullPath,
});
}
else if (OperatingSystem.IsMacOS())
{
Process.Start(new ProcessStartInfo
{
FileName = "open",
Arguments = ".",
WorkingDirectory = fullPath,
});
}
else if (OperatingSystem.IsLinux() || OperatingSystem.IsFreeBSD())
{
Process.Start(new ProcessStartInfo
{
FileName = "xdg-open",
Arguments = ".",
WorkingDirectory = fullPath,
});
}
else
{
throw new NotSupportedException("Opening OS windows not supported on this OS");
}
}
#endregion

View File

@@ -101,7 +101,6 @@ namespace Robust.Shared.GameObjects
internal bool _mapIdInitialized;
internal bool _gridInitialized;
// TODO: Cache this.
/// <summary>
/// The EntityUid of the map which this object is on, if any.
/// </summary>

View File

@@ -1013,6 +1013,11 @@ namespace Robust.Shared.GameObjects
}
}
/// <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)
{

View File

@@ -5,16 +5,17 @@ using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using Robust.Shared.Containers;
using Robust.Shared.Maths;
namespace Robust.Shared.GameObjects;
public partial class EntityManager
{
// This method will soon be marked as obsolete.
// This method will soon(TM) be marked as obsolete.
public EntityUid SpawnEntity(string? protoName, EntityCoordinates coordinates, ComponentRegistry? overrides = null)
=> SpawnAttachedTo(protoName, coordinates, overrides);
// This method will soon be marked as obsolete.
// This method will soon(TM) be marked as obsolete.
public EntityUid SpawnEntity(string? protoName, MapCoordinates coordinates, ComponentRegistry? overrides = null)
=> Spawn(protoName, coordinates, overrides);
@@ -83,12 +84,16 @@ public partial class EntityManager
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public EntityUid Spawn(string? protoName = null, ComponentRegistry? overrides = null)
=> Spawn(protoName, MapCoordinates.Nullspace, overrides);
public virtual EntityUid Spawn(string? protoName, MapCoordinates coordinates, ComponentRegistry? overrides = null)
public EntityUid Spawn(string? protoName = null, ComponentRegistry? overrides = null, bool doMapInit = true)
{
var entity = CreateEntityUninitialized(protoName, coordinates, overrides);
var entity = CreateEntityUninitialized(protoName, MapCoordinates.Nullspace, overrides);
InitializeAndStartEntity(entity, doMapInit);
return entity;
}
public virtual EntityUid Spawn(string? protoName, MapCoordinates coordinates, ComponentRegistry? overrides = null, Angle rotation = default!)
{
var entity = CreateEntityUninitialized(protoName, coordinates, overrides, rotation);
InitializeAndStartEntity(entity, coordinates.MapId);
return entity;
}
@@ -117,7 +122,8 @@ public partial class EntityManager
return true;
}
uid = Spawn(protoName, overrides);
var doMapInit = _mapSystem.IsInitialized(xform.MapUid);
uid = Spawn(protoName, overrides, doMapInit);
if (_containers.Insert(uid.Value, container))
return true;
@@ -141,7 +147,8 @@ public partial class EntityManager
if (!containerComp.Containers.TryGetValue(containerId, out var container))
return false;
uid = Spawn(protoName, overrides);
var doMapInit = _mapSystem.IsInitialized(TransformQuery.GetComponent(containerUid).MapUid);
uid = Spawn(protoName, overrides, doMapInit);
if (_containers.Insert(uid.Value, container))
return true;
@@ -157,7 +164,8 @@ public partial class EntityManager
if (!xform.ParentUid.IsValid())
return Spawn(protoName);
var uid = Spawn(protoName, overrides);
var doMapInit = _mapSystem.IsInitialized(xform.MapUid);
var uid = Spawn(protoName, overrides, doMapInit);
_xforms.DropNextTo(uid, target);
return uid;
}
@@ -182,16 +190,16 @@ public partial class EntityManager
ContainerManagerComponent? containerComp = null,
ComponentRegistry? overrides = null)
{
var uid = Spawn(protoName, overrides);
inserted = true;
xform ??= TransformQuery.GetComponent(containerUid);
var doMapInit = _mapSystem.IsInitialized(xform.MapUid);
var uid = Spawn(protoName, overrides, doMapInit);
if ((containerComp == null && !TryGetComponent(containerUid, out containerComp))
|| !containerComp.Containers.TryGetValue(containerId, out var container)
|| !_containers.Insert(uid, container))
{
inserted = false;
xform ??= TransformQuery.GetComponent(containerUid);
if (xform.ParentUid.IsValid())
_xforms.DropNextTo(uid, (containerUid, xform));
}

View File

@@ -9,6 +9,7 @@ using Robust.Shared.GameStates;
using Robust.Shared.Log;
using Robust.Shared.Map;
using Robust.Shared.Map.Components;
using Robust.Shared.Maths;
using Robust.Shared.Network;
using Robust.Shared.Player;
using Robust.Shared.Profiling;
@@ -297,14 +298,13 @@ namespace Robust.Shared.GameObjects
}
/// <inheritdoc />
public virtual EntityUid CreateEntityUninitialized(string? prototypeName, MapCoordinates coordinates, ComponentRegistry? overrides = null)
public virtual EntityUid CreateEntityUninitialized(string? prototypeName, MapCoordinates coordinates, ComponentRegistry? overrides = null, Angle rotation = default!)
{
var newEntity = CreateEntity(prototypeName, out _, overrides);
var transform = TransformQuery.GetComponent(newEntity);
if (coordinates.MapId == MapId.Nullspace)
{
DebugTools.Assert(_mapManager.GetMapEntityId(coordinates.MapId) == EntityUid.Invalid);
transform._parent = EntityUid.Invalid;
transform.Anchored = false;
return newEntity;
@@ -323,7 +323,7 @@ namespace Robust.Shared.GameObjects
else
{
coords = new EntityCoordinates(mapEnt, coordinates.Position);
_xforms.SetCoordinates(newEntity, transform, coords, null, newParent: mapXform);
_xforms.SetCoordinates(newEntity, transform, coords, rotation, newParent: mapXform);
}
return newEntity;
@@ -821,15 +821,22 @@ namespace Robust.Shared.GameObjects
public void InitializeAndStartEntity(EntityUid entity, MapId? mapId = null)
{
var doMapInit = _mapManager.IsMapInitialized(mapId ?? TransformQuery.GetComponent(entity).MapID);
InitializeAndStartEntity(entity, doMapInit);
}
public void InitializeAndStartEntity(Entity<MetaDataComponent?> entity, bool doMapInit)
{
if (!MetaQuery.Resolve(entity.Owner, ref entity.Comp))
return;
try
{
var meta = MetaQuery.GetComponent(entity);
InitializeEntity(entity, meta);
StartEntity(entity);
InitializeEntity(entity.Owner, entity.Comp);
StartEntity(entity.Owner);
// If the map we're initializing the entity on is initialized, run map init on it.
if (_mapManager.IsMapInitialized(mapId ?? TransformQuery.GetComponent(entity).MapID))
RunMapInit(entity, meta);
if (doMapInit)
RunMapInit(entity.Owner, entity.Comp);
}
catch (Exception e)
{
@@ -859,7 +866,7 @@ namespace Robust.Shared.GameObjects
DebugTools.Assert(meta.EntityLifeStage == EntityLifeStage.Initialized, $"Expected entity {ToPrettyString(entity)} to be initialized, was {meta.EntityLifeStage}");
SetLifeStage(meta, EntityLifeStage.MapInitialized);
EventBus.RaiseLocalEvent(entity, MapInitEventInstance, false);
EventBus.RaiseLocalEvent(entity, MapInitEventInstance);
}
/// <inheritdoc />

View File

@@ -5,8 +5,10 @@ using System.Runtime.CompilerServices;
using JetBrains.Annotations;
using Robust.Shared.Containers;
using Robust.Shared.Map;
using Robust.Shared.Maths;
using Robust.Shared.Prototypes;
using Robust.Shared.Timing;
using TerraFX.Interop.Windows;
namespace Robust.Shared.GameObjects;
@@ -699,32 +701,32 @@ public partial class EntitySystem
#region Entity Spawning
// This method will be obsoleted soon.
// This method will be obsoleted soon(TM).
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected EntityUid Spawn(string? prototype, EntityCoordinates coordinates)
{
return ((IEntityManager)EntityManager).SpawnEntity(prototype, coordinates);
}
/// <inheritdoc cref="IEntityManager.Spawn(string?, MapCoordinates, ComponentRegistry?)" />
/// <inheritdoc cref="IEntityManager.Spawn(string?, MapCoordinates, ComponentRegistry?, Angle)" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected EntityUid Spawn(string? prototype, MapCoordinates coordinates)
=> EntityManager.Spawn(prototype, coordinates);
protected EntityUid Spawn(string? prototype, MapCoordinates coordinates, ComponentRegistry? overrides = null, Angle rotation = default)
=> EntityManager.Spawn(prototype, coordinates, overrides, rotation);
/// <inheritdoc cref="IEntityManager.Spawn(string?, ComponentRegistry?)" />
/// <inheritdoc cref="IEntityManager.Spawn(string?, ComponentRegistry?, bool)" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected EntityUid Spawn(string? prototype = null)
=> EntityManager.Spawn(prototype);
protected EntityUid Spawn(string? prototype = null, ComponentRegistry? overrides = null, bool doMapInit = true)
=> EntityManager.Spawn(prototype, overrides, doMapInit);
/// <inheritdoc cref="IEntityManager.SpawnAttachedTo" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected EntityUid SpawnAttachedTo(string? prototype, EntityCoordinates coordinates)
=> EntityManager.SpawnAttachedTo(prototype, coordinates);
protected EntityUid SpawnAttachedTo(string? prototype, EntityCoordinates coordinates, ComponentRegistry? overrides = null)
=> EntityManager.SpawnAttachedTo(prototype, coordinates, overrides);
/// <inheritdoc cref="IEntityManager.SpawnAtPosition" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected EntityUid SpawnAtPosition(string? prototype, EntityCoordinates coordinates)
=> EntityManager.SpawnAtPosition(prototype, coordinates);
protected EntityUid SpawnAtPosition(string? prototype, EntityCoordinates coordinates, ComponentRegistry? overrides = null)
=> EntityManager.SpawnAtPosition(prototype, coordinates, overrides);
/// <inheritdoc cref="IEntityManager.TrySpawnInContainer" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]

View File

@@ -2,6 +2,7 @@ using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Robust.Shared.Containers;
using Robust.Shared.Map;
using Robust.Shared.Maths;
using Robust.Shared.Prototypes;
namespace Robust.Shared.GameObjects;
@@ -27,12 +28,12 @@ public partial interface IEntityManager
/// <summary>
/// Spawns an entity in nullspace.
/// </summary>
EntityUid Spawn(string? protoName = null, ComponentRegistry? overrides = null);
EntityUid Spawn(string? protoName = null, ComponentRegistry? overrides = null, bool doMapInit = true);
/// <summary>
/// Spawns an entity at a specific world position. The entity will either be parented to the map or a grid.
/// </summary>
EntityUid Spawn(string? protoName, MapCoordinates coordinates, ComponentRegistry? overrides = null);
EntityUid Spawn(string? protoName, MapCoordinates coordinates, ComponentRegistry? overrides = null, Angle rotation = default!);
/// <summary>
/// Spawns an entity and then parents it to the entity that the given entity coordinates are relative to.

View File

@@ -4,6 +4,7 @@ using System.Diagnostics.CodeAnalysis;
using JetBrains.Annotations;
using Prometheus;
using Robust.Shared.Map;
using Robust.Shared.Maths;
using Robust.Shared.Prototypes;
using Robust.Shared.Timing;
@@ -76,10 +77,12 @@ namespace Robust.Shared.GameObjects
EntityUid CreateEntityUninitialized(string? prototypeName, EntityCoordinates coordinates, ComponentRegistry? overrides = null);
EntityUid CreateEntityUninitialized(string? prototypeName, MapCoordinates coordinates, ComponentRegistry? overrides = null);
EntityUid CreateEntityUninitialized(string? prototypeName, MapCoordinates coordinates, ComponentRegistry? overrides = null, Angle rotation = default!);
void InitializeAndStartEntity(EntityUid entity, MapId? mapId = null);
void InitializeAndStartEntity(Entity<MetaDataComponent?> entity, bool doMapInit);
void InitializeEntity(EntityUid entity, MetaDataComponent? meta = null);
void StartEntity(EntityUid entity);

View File

@@ -1,68 +1,188 @@
using System;
using System.Diagnostics.CodeAnalysis;
using Robust.Shared.GameStates;
using Robust.Shared.Log;
using Robust.Shared.Map;
using Robust.Shared.Map.Components;
using Robust.Shared.Physics.Dynamics;
using Robust.Shared.Utility;
namespace Robust.Shared.GameObjects;
public abstract partial class SharedMapSystem
{
protected int LastMapId;
private void InitializeMap()
{
SubscribeLocalEvent<MapComponent, ComponentAdd>(OnMapAdd);
SubscribeLocalEvent<MapComponent, ComponentInit>(OnMapInit);
SubscribeLocalEvent<MapComponent, ComponentAdd>(OnComponentAdd);
SubscribeLocalEvent<MapComponent, ComponentInit>(OnCompInit);
SubscribeLocalEvent<MapComponent, ComponentStartup>(OnCompStartup);
SubscribeLocalEvent<MapComponent, MapInitEvent>(OnMapInit);
SubscribeLocalEvent<MapComponent, ComponentShutdown>(OnMapRemoved);
SubscribeLocalEvent<MapComponent, ComponentHandleState>(OnMapHandleState);
SubscribeLocalEvent<MapComponent, ComponentGetState>(OnMapGetState);
}
public bool MapExists([NotNullWhen(true)] MapId? mapId)
{
return mapId != null && Maps.ContainsKey(mapId.Value);
}
public EntityUid GetMap(MapId mapId)
{
return Maps[mapId];
}
public bool TryGetMap([NotNullWhen(true)] MapId? mapId, [NotNullWhen(true)] out EntityUid? uid)
{
if (mapId == null || !Maps.TryGetValue(mapId.Value, out var map))
{
uid = null;
return false;
}
uid = map;
return true;
}
private void OnMapHandleState(EntityUid uid, MapComponent component, ref ComponentHandleState args)
{
if (args.Current is not MapComponentState state)
return;
component.MapId = state.MapId;
if (!MapManager.MapExists(state.MapId))
if (component.MapId == MapId.Nullspace)
{
var mapInternal = (IMapManagerInternal)MapManager;
mapInternal.CreateMap(state.MapId, uid);
if (state.MapId == MapId.Nullspace)
throw new Exception($"Received invalid map state? {ToPrettyString(uid)}");
component.MapId = state.MapId;
Maps.Add(component.MapId, uid);
RecursiveMapIdUpdate(uid, uid, component.MapId);
}
DebugTools.AssertEqual(component.MapId, state.MapId);
component.LightingEnabled = state.LightingEnabled;
var xformQuery = GetEntityQuery<TransformComponent>();
component.MapInitialized = state.Initialized;
xformQuery.GetComponent(uid).ChangeMapId(state.MapId, xformQuery);
if (LifeStage(uid) >= EntityLifeStage.Initialized)
SetPaused(uid, state.MapPaused);
else
component.MapPaused = state.MapPaused;
}
MapManager.SetMapPaused(state.MapId, state.MapPaused);
private void RecursiveMapIdUpdate(EntityUid uid, EntityUid mapUid, MapId mapId)
{
// This is required only in the event where an entity becomes a map AFTER children have already been attached to it.
// AFAIK, this currently only happens when the client applies entity states out of order (i.e., ignoring transform hierarchy),
// which itself only happens if PVS is disabled.
// TODO MAPS remove this
var xform = Transform(uid);
xform.MapUid = mapUid;
xform.MapID = mapId;
xform._mapIdInitialized = true;
foreach (var child in xform._children)
{
RecursiveMapIdUpdate(child, mapUid, mapId);
}
}
private void OnMapGetState(EntityUid uid, MapComponent component, ref ComponentGetState args)
{
args.State = new MapComponentState(component.MapId, component.LightingEnabled, component.MapPaused);
args.State = new MapComponentState(component.MapId, component.LightingEnabled, component.MapPaused, component.MapInitialized);
}
protected abstract void OnMapAdd(EntityUid uid, MapComponent component, ComponentAdd args);
protected abstract MapId GetNextMapId();
private void OnMapInit(EntityUid uid, MapComponent component, ComponentInit args)
private void OnComponentAdd(EntityUid uid, MapComponent component, ComponentAdd args)
{
// ordered startups when
EnsureComp<PhysicsMapComponent>(uid);
EnsureComp<GridTreeComponent>(uid);
EnsureComp<MovedGridsComponent>(uid);
}
private void OnCompInit(EntityUid uid, MapComponent component, ComponentInit args)
{
if (component.MapId == MapId.Nullspace)
component.MapId = GetNextMapId();
DebugTools.AssertEqual(component.MapId.IsClientSide, IsClientSide(uid));
if (!Maps.TryAdd(component.MapId, uid))
{
if (Maps[component.MapId] != uid)
throw new Exception($"Attempted to initialize a map {ToPrettyString(uid)} with a duplicate map id {component.MapId}");
}
var msg = new MapChangedEvent(uid, component.MapId, true);
RaiseLocalEvent(uid, msg, true);
}
private void OnCompStartup(EntityUid uid, MapComponent component, ComponentStartup args)
{
if (component.MapPaused)
RecursiveSetPaused(uid, true);
}
private void OnMapRemoved(EntityUid uid, MapComponent component, ComponentShutdown args)
{
DebugTools.Assert(component.MapId != MapId.Nullspace);
Log.Info($"Deleting map {component.MapId}");
var iMap = (IMapManagerInternal)MapManager;
iMap.RemoveMapId(component.MapId);
Maps.Remove(component.MapId);
var msg = new MapChangedEvent(uid, component.MapId, false);
RaiseLocalEvent(uid, msg, true);
}
/// <summary>
/// Creates a new map, automatically assigning a map id.
/// </summary>
public EntityUid CreateMap(out MapId mapId, bool runMapInit = true)
{
mapId = GetNextMapId();
var uid = CreateMap(mapId, runMapInit);
return uid;
}
/// <inheritdoc cref="CreateMap(out Robust.Shared.Map.MapId,bool)"/>
public EntityUid CreateMap(bool runMapInit = true) => CreateMap(out _, runMapInit);
/// <summary>
/// Creates a new map with the specified map id.
/// </summary>
/// <exception cref="ArgumentException">Throws if an invalid or already existing map id is provided.</exception>
public EntityUid CreateMap(MapId mapId, bool runMapInit = true)
{
if (Maps.ContainsKey(mapId))
throw new ArgumentException($"Map with id {mapId} already exists");
if (mapId == MapId.Nullspace)
throw new ArgumentException($"Cannot create a null-space map");
if (_netManager.IsServer && mapId.IsClientSide)
throw new ArgumentException($"Attempted to create a client-side map on the server?");
if (_netManager.IsClient && _netManager.IsConnected && !mapId.IsClientSide)
throw new ArgumentException($"Attempted to create a client-side map entity with a non client-side map ID?");
var uid = EntityManager.CreateEntityUninitialized(null);
var map = _factory.GetComponent<MapComponent>();
map.MapId = mapId;
AddComp(uid, map);
// Give the entity a name, mainly for debugging. Content can always override this with a localized name.
var meta = MetaData(uid);
_meta.SetEntityName(uid, $"Map Entity", meta);
// Initialize components. this should add the map id to the collections.
EntityManager.InitializeComponents(uid, meta);
EntityManager.StartComponents(uid);
DebugTools.Assert(Maps[mapId] == uid);
if (runMapInit)
InitializeMap((uid, map));
else
SetPaused((uid, map), true);
return uid;
}
}

View File

@@ -0,0 +1,83 @@
using System;
using System.Collections.Generic;
using Robust.Shared.Map;
using Robust.Shared.Map.Components;
using Robust.Shared.Utility;
namespace Robust.Shared.GameObjects;
public abstract partial class SharedMapSystem
{
public bool IsInitialized(MapId mapId)
{
if (mapId == MapId.Nullspace)
return true; // Nullspace is always initialized
if(!Maps.TryGetValue(mapId, out var uid))
throw new ArgumentException($"Map {mapId} does not exist.");
return IsInitialized(uid);
}
public bool IsInitialized(EntityUid? map)
{
if (map == null)
return true; // Nullspace is always initialized
return IsInitialized(map.Value);
}
public bool IsInitialized(Entity<MapComponent?> map)
{
if (!_mapQuery.Resolve(map, ref map.Comp))
return false;
return map.Comp.MapInitialized;
}
private void OnMapInit(EntityUid uid, MapComponent component, MapInitEvent args)
{
DebugTools.Assert(!component.MapInitialized);
component.MapInitialized = true;
EntityManager.Dirty(uid, component);
}
public void InitializeMap(MapId mapId, bool unpause = true)
{
if(!Maps.TryGetValue(mapId, out var uid))
throw new ArgumentException($"Map {mapId} does not exist.");
InitializeMap(uid, unpause);
}
public void InitializeMap(Entity<MapComponent?> map, bool unpause = true)
{
if (!_mapQuery.Resolve(map, ref map.Comp))
return;
if (map.Comp.MapInitialized)
throw new ArgumentException($"Map {ToPrettyString(map)} is already initialized.");
RecursiveMapInit(map.Owner);
if (unpause)
SetPaused(map, false);
}
private void RecursiveMapInit(EntityUid entity)
{
var toInitialize = new List<EntityUid> {entity};
for (var i = 0; i < toInitialize.Count; i++)
{
var uid = toInitialize[i];
// toInitialize might contain deleted entities.
if(!_metaQuery.TryComp(uid, out var meta))
continue;
if (meta.EntityLifeStage == EntityLifeStage.MapInitialized)
continue;
toInitialize.AddRange(Transform(uid)._children);
EntityManager.RunMapInit(uid, meta);
}
}
}

View File

@@ -0,0 +1,60 @@
using System;
using Robust.Shared.Map;
using Robust.Shared.Map.Components;
namespace Robust.Shared.GameObjects;
public abstract partial class SharedMapSystem
{
public bool IsPaused(MapId mapId)
{
if (mapId == MapId.Nullspace)
return false;
if(!Maps.TryGetValue(mapId, out var uid))
throw new ArgumentException($"Map {mapId} does not exist.");
return IsPaused(uid);
}
public bool IsPaused(Entity<MapComponent?> map)
{
if (!_mapQuery.Resolve(map, ref map.Comp))
return false;
return map.Comp.MapPaused;
}
public void SetPaused(MapId mapId, bool paused)
{
if(!Maps.TryGetValue(mapId, out var uid))
throw new ArgumentException($"Map {mapId} does not exist.");
SetPaused(uid, paused);
}
public void SetPaused(Entity<MapComponent?> map, bool paused)
{
if (!_mapQuery.Resolve(map, ref map.Comp))
return;
if (map.Comp.MapPaused == paused)
return;
map.Comp.MapPaused = paused;
if (map.Comp.LifeStage < ComponentLifeStage.Initializing)
return;
Dirty(map);
RecursiveSetPaused(map, paused);
}
private void RecursiveSetPaused(EntityUid entity, bool paused)
{
_meta.SetEntityPaused(entity, paused);
foreach (var child in Transform(entity)._children)
{
RecursiveSetPaused(child, paused);
}
}
}

View File

@@ -20,17 +20,23 @@ namespace Robust.Shared.GameObjects
[Dependency] private readonly FixtureSystem _fixtures = default!;
[Dependency] private readonly SharedPhysicsSystem _physics = default!;
[Dependency] private readonly SharedTransformSystem _transform = default!;
[Dependency] private readonly IComponentFactory _factory = default!;
[Dependency] private readonly MetaDataSystem _meta = default!;
private EntityQuery<MapComponent> _mapQuery;
private EntityQuery<MapGridComponent> _gridQuery;
private EntityQuery<MetaDataComponent> _metaQuery;
private EntityQuery<TransformComponent> _xformQuery;
internal Dictionary<MapId, EntityUid> Maps { get; } = new();
public override void Initialize()
{
base.Initialize();
_mapQuery = GetEntityQuery<MapComponent>();
_gridQuery = GetEntityQuery<MapGridComponent>();
_metaQuery = GetEntityQuery<MetaDataComponent>();
_xformQuery = GetEntityQuery<TransformComponent>();
InitializeMap();

View File

@@ -199,47 +199,34 @@ public abstract partial class SharedTransformSystem
#region Component Lifetime
private (EntityUid?, MapId) InitializeMapUid(EntityUid uid, TransformComponent xform)
{
if (xform._mapIdInitialized)
return (xform.MapUid, xform.MapID);
if (xform.ParentUid.IsValid())
{
(xform.MapUid, xform.MapID) = InitializeMapUid(xform.ParentUid, Transform(xform.ParentUid));
}
else if (_mapQuery.TryComp(uid, out var mapComp))
{
DebugTools.AssertNotEqual(mapComp.MapId, MapId.Nullspace);
xform.MapUid = uid;
xform.MapID = mapComp.MapId;
}
else
{
xform.MapUid = null;
xform.MapID = MapId.Nullspace;
}
xform._mapIdInitialized = true;
return (xform.MapUid, xform.MapID);
}
private void OnCompInit(EntityUid uid, TransformComponent component, ComponentInit args)
{
// Children MAY be initialized here before their parents are.
// We do this whole dance to handle this recursively,
// setting _mapIdInitialized along the way to avoid going to the MapComponent every iteration.
static MapId FindMapIdAndSet(EntityUid uid, TransformComponent xform, IEntityManager entMan, EntityQuery<TransformComponent> xformQuery, IMapManager mapManager)
{
if (xform._mapIdInitialized)
return xform.MapID;
MapId value;
if (xform.ParentUid.IsValid())
{
value = FindMapIdAndSet(xform.ParentUid, xformQuery.GetComponent(xform.ParentUid), entMan, xformQuery, mapManager);
}
else
{
// second level node, terminates recursion up the branch of the tree
if (entMan.TryGetComponent(uid, out MapComponent? mapComp))
{
value = mapComp.MapId;
}
else
{
// We allow entities to be spawned directly into null-space.
value = MapId.Nullspace;
}
}
xform.MapUid = value == MapId.Nullspace ? null : mapManager.GetMapEntityId(value);
xform.MapID = value;
xform._mapIdInitialized = true;
return value;
}
if (!component._mapIdInitialized)
{
FindMapIdAndSet(uid, component, EntityManager, XformQuery, _mapManager);
component._mapIdInitialized = true;
}
InitializeMapUid(uid, component);
// Has to be done if _parent is set from ExposeData.
if (component.ParentUid.IsValid())
@@ -522,6 +509,8 @@ public abstract partial class SharedTransformSystem
throw new InvalidOperationException($"Attempted to re-parent to a terminating object. Entity: {ToPrettyString(uid)}, new parent: {ToPrettyString(value.EntityId)}");
}
InitializeMapUid(value.EntityId, newParent);
// Check for recursive/circular transform hierarchies.
if (xform.MapUid == newParent.MapUid)
{
@@ -881,6 +870,28 @@ public abstract partial class SharedTransformSystem
return GetMapCoordinates(entity.Comp);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetMapCoordinates(EntityUid entity, MapCoordinates coordinates)
{
var xform = XformQuery.GetComponent(entity);
SetMapCoordinates((entity, xform), coordinates);
}
public void SetMapCoordinates(Entity<TransformComponent> entity, MapCoordinates coordinates)
{
var mapUid = _map.GetMap(coordinates.MapId);
if (!_gridQuery.HasComponent(entity) &&
_mapManager.TryFindGridAt(mapUid, coordinates.Position, out var targetGrid, out _))
{
var invWorldMatrix = GetInvWorldMatrix(targetGrid);
SetCoordinates(entity, new EntityCoordinates(targetGrid, invWorldMatrix.Transform(coordinates.Position)));
}
else
{
SetCoordinates(entity, new EntityCoordinates(mapUid, coordinates.Position));
}
}
[Pure]
public (Vector2 WorldPosition, Angle WorldRotation) GetWorldPositionRotation(EntityUid uid)
{

View File

@@ -26,6 +26,7 @@ namespace Robust.Shared.GameObjects
[Dependency] private readonly INetManager _netMan = default!;
[Dependency] private readonly SharedContainerSystem _container = default!;
private EntityQuery<MapComponent> _mapQuery;
private EntityQuery<MapGridComponent> _gridQuery;
private EntityQuery<MetaDataComponent> _metaQuery;
protected EntityQuery<TransformComponent> XformQuery;
@@ -50,6 +51,7 @@ namespace Robust.Shared.GameObjects
UpdatesOutsidePrediction = true;
_mapQuery = GetEntityQuery<MapComponent>();
_gridQuery = GetEntityQuery<MapGridComponent>();
_metaQuery = GetEntityQuery<MetaDataComponent>();
XformQuery = GetEntityQuery<TransformComponent>();

View File

@@ -12,35 +12,29 @@ namespace Robust.Shared.Map.Components
public sealed partial class MapComponent : Component
{
[ViewVariables(VVAccess.ReadWrite)]
[DataField("lightingEnabled")]
[DataField]
public bool LightingEnabled { get; set; } = true;
[ViewVariables(VVAccess.ReadOnly)]
public MapId MapId { get; internal set; } = MapId.Nullspace;
[ViewVariables(VVAccess.ReadOnly)]
public bool MapPaused { get; set; } = false;
[DataField, Access(typeof(SharedMapSystem), typeof(MapManager))]
public bool MapPaused;
//TODO replace MapPreInit with the map's entity life stage
[ViewVariables(VVAccess.ReadOnly)]
public bool MapPreInit { get; set; } = false;
[DataField, Access(typeof(SharedMapSystem), typeof(MapManager))]
public bool MapInitialized;
}
/// <summary>
/// Serialized state of a <see cref="MapGridComponentState"/>.
/// </summary>
[Serializable, NetSerializable]
public sealed class MapComponentState : ComponentState
public sealed class MapComponentState(MapId mapId, bool lightingEnabled, bool paused, bool init)
: ComponentState
{
public MapId MapId;
public bool LightingEnabled;
public bool MapPaused;
public MapComponentState(MapId mapId, bool lightingEnabled, bool paused)
{
MapId = mapId;
LightingEnabled = lightingEnabled;
MapPaused = paused;
}
public MapId MapId = mapId;
public bool LightingEnabled = lightingEnabled;
public bool MapPaused = paused;
public bool Initialized = init;
}
}

View File

@@ -23,9 +23,6 @@ namespace Robust.Shared.Map
public const bool Approximate = false;
public const bool IncludeMap = true;
[Obsolete("Use EntityQuery<MapGridComponent>")]
IEnumerable<MapGridComponent> GetAllGrids();
/// <summary>
/// Should the OnTileChanged event be suppressed? This is useful for initially loading the map
/// so that you don't spam an event for each of the million station tiles.
@@ -42,16 +39,7 @@ namespace Robust.Shared.Map
void Restart();
/// <summary>
/// Creates a new map.
/// </summary>
/// <param name="mapId">
/// If provided, the new map will use this ID. If not provided, a new ID will be selected automatically.
/// </param>
/// <returns>The new map.</returns>
/// <exception cref="InvalidOperationException">
/// Throw if an explicit ID for the map or default grid is passed and a map or grid with the specified ID already exists, respectively.
/// </exception>
[Obsolete("Use MapSystem")]
MapId CreateMap(MapId? mapId = null);
/// <summary>
@@ -59,24 +47,12 @@ namespace Robust.Shared.Map
/// </summary>
/// <param name="mapId">The map ID to check existence of.</param>
/// <returns>True if the map exists, false otherwise.</returns>
bool MapExists(MapId mapId);
bool MapExists([NotNullWhen(true)] MapId? mapId);
/// <summary>
/// Creates a new entity, then sets it as the map entity.
/// </summary>
/// <returns>Newly created entity.</returns>
EntityUid CreateNewMapEntity(MapId mapId);
/// <summary>
/// Sets the MapEntity(root node) for a given map. If an entity is already set, it will be deleted
/// before the new one is set.
/// </summary>
/// <param name="updateChildren">Should we re-parent children from the old map to the new one, or delete them.</param>
void SetMapEntity(MapId mapId, EntityUid newMapEntityId, bool updateChildren = true);
/// <summary>
/// Returns the map entity ID for a given map.
/// Returns the map entity ID for a given map, or an invalid entity Id if the map does not exist.
/// </summary>
[Obsolete("Use TryGetMap")]
EntityUid GetMapEntityId(MapId mapId);
/// <summary>
@@ -93,6 +69,7 @@ namespace Robust.Shared.Map
MapGridComponent CreateGrid(MapId currentMapId, in GridCreateOptions options);
MapGridComponent CreateGrid(MapId currentMapId);
Entity<MapGridComponent> CreateGridEntity(MapId currentMapId, GridCreateOptions? options = null);
Entity<MapGridComponent> CreateGridEntity(EntityUid map, GridCreateOptions? options = null);
[Obsolete("Use GetComponent<MapGridComponent>(uid)")]
MapGridComponent GetGrid(EntityUid gridId);
@@ -233,17 +210,13 @@ namespace Robust.Shared.Map
#endregion
void DeleteGrid(EntityUid euid);
bool HasMapEntity(MapId mapId);
[Obsolete("Just delete the grid entity")]
void DeleteGrid(EntityUid euid);
bool IsGrid(EntityUid uid);
bool IsMap(EntityUid uid);
[Obsolete("Whatever this is used for, it is a terrible idea. Create a new map and get it's MapId.")]
MapId NextMapId();
MapGridComponent GetGridComp(EntityUid euid);
//
// Pausing functions
//
@@ -252,14 +225,15 @@ namespace Robust.Shared.Map
void DoMapInitialize(MapId mapId);
// TODO rename this to actually be descriptive or just remove it.
[Obsolete("Use CreateMap's runMapInit argument")]
void AddUninitializedMap(MapId mapId);
[Pure]
[Obsolete("Use MapSystem")]
bool IsMapPaused(MapId mapId);
[Pure]
[Obsolete("Use MapSystem")]
bool IsMapInitialized(MapId mapId);
}
public struct GridCreateOptions

View File

@@ -1,23 +1,15 @@
using Robust.Shared.GameObjects;
using Robust.Shared.Maths;
using Robust.Shared.Timing;
namespace Robust.Shared.Map
{
/// <inheritdoc />
internal interface IMapManagerInternal : IMapManager
{
IGameTiming GameTiming { get; }
/// <summary>
/// Raises the OnTileChanged event.
/// </summary>
/// <param name="tileRef">A reference to the new tile.</param>
/// <param name="oldTile">The old tile that got replaced.</param>
void RaiseOnTileChanged(TileRef tileRef, Tile oldTile, Vector2i chunk);
MapId CreateMap(MapId? mapId, EntityUid euid);
void RemoveMapId(MapId mapId);
}
}

View File

@@ -53,5 +53,7 @@ namespace Robust.Shared.Map
{
return Value.ToString();
}
public bool IsClientSide => Value < 0;
}
}

View File

@@ -12,32 +12,15 @@ using Robust.Shared.Utility;
namespace Robust.Shared.Map;
internal partial class MapManager
{
[Obsolete("Use GetComponent<MapGridComponent>(uid)")]
public MapGridComponent GetGridComp(EntityUid euid)
{
return EntityManager.GetComponent<MapGridComponent>(euid);
}
[Obsolete("Use EntityQuery instead.")]
public IEnumerable<MapGridComponent> GetAllGrids()
{
var compQuery = EntityManager.AllEntityQueryEnumerator<MapGridComponent>();
while (compQuery.MoveNext(out var comp))
{
yield return comp;
}
}
// ReSharper disable once MethodOverloadWithOptionalParameter
public MapGridComponent CreateGrid(MapId currentMapId, ushort chunkSize = 16)
{
return CreateGrid(currentMapId, chunkSize, default);
return CreateGrid(GetMapEntityIdOrThrow(currentMapId), chunkSize, default);
}
public MapGridComponent CreateGrid(MapId currentMapId, in GridCreateOptions options)
{
return CreateGrid(currentMapId, options.ChunkSize, default);
return CreateGrid(GetMapEntityIdOrThrow(currentMapId), options.ChunkSize, default);
}
public MapGridComponent CreateGrid(MapId currentMapId)
@@ -46,18 +29,19 @@ internal partial class MapManager
}
public Entity<MapGridComponent> CreateGridEntity(MapId currentMapId, GridCreateOptions? options = null)
{
return CreateGridEntity(GetMapEntityIdOrThrow(currentMapId), options);
}
public Entity<MapGridComponent> CreateGridEntity(EntityUid map, GridCreateOptions? options = null)
{
options ??= GridCreateOptions.Default;
return CreateGrid(currentMapId, options.Value.ChunkSize, default);
return CreateGrid(map, options.Value.ChunkSize, default);
}
[Obsolete("Use GetComponent<MapGridComponent>(uid)")]
public MapGridComponent GetGrid(EntityUid gridId)
{
DebugTools.Assert(gridId.IsValid());
return GetGridComp(gridId);
}
=> EntityManager.GetComponent<MapGridComponent>(gridId);
[Obsolete("Use HasComponent<MapGridComponent>(uid)")]
public bool IsGrid(EntityUid uid)
@@ -108,10 +92,6 @@ internal partial class MapManager
public virtual void DeleteGrid(EntityUid euid)
{
#if DEBUG
DebugTools.Assert(_dbgGuardRunning);
#endif
// Possible the grid was already deleted / is invalid
if (!EntityManager.TryGetComponent<MapGridComponent>(euid, out var iGrid))
{
@@ -141,10 +121,6 @@ internal partial class MapManager
/// <param name="oldTile">The old tile that got replaced.</param>
public void RaiseOnTileChanged(TileRef tileRef, Tile oldTile, Vector2i chunk)
{
#if DEBUG
DebugTools.Assert(_dbgGuardRunning);
#endif
if (SuppressOnTileChanged)
return;
@@ -153,7 +129,7 @@ internal partial class MapManager
EntityManager.EventBus.RaiseLocalEvent(euid, ref ev, true);
}
protected Entity<MapGridComponent> CreateGrid(MapId currentMapId, ushort chunkSize, EntityUid forcedGridEuid)
protected Entity<MapGridComponent> CreateGrid(EntityUid map, ushort chunkSize, EntityUid forcedGridEuid)
{
var gridEnt = EntityManager.CreateEntityUninitialized(null, forcedGridEuid);
@@ -166,8 +142,7 @@ internal partial class MapManager
//are applied. After they are applied the parent may be different, but the MapId will
//be the same. This causes TransformComponent.ParentUid of a grid to be unsafe to
//use in transform states anytime before the state parent is properly set.
var fallbackParentEuid = GetMapEntityIdOrThrow(currentMapId);
EntityManager.GetComponent<TransformComponent>(gridEnt).AttachParent(fallbackParentEuid);
EntityManager.GetComponent<TransformComponent>(gridEnt).AttachParent(map);
var meta = EntityManager.GetComponent<MetaDataComponent>(gridEnt);
EntityManager.System<MetaDataSystem>().SetEntityName(gridEnt, $"grid", meta);

View File

@@ -1,12 +0,0 @@
namespace Robust.Shared.Map;
internal partial class MapManager
{
public void RemoveMapId(MapId mapId)
{
if (mapId == MapId.Nullspace)
return;
_mapEntities.Remove(mapId);
}
}

View File

@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Robust.Shared.GameObjects;
using Robust.Shared.Map.Components;
using Robust.Shared.Utility;
@@ -27,131 +28,42 @@ public sealed class MapEventArgs : EventArgs
internal partial class MapManager
{
private readonly Dictionary<MapId, EntityUid> _mapEntities = new();
private MapId _highestMapId = MapId.Nullspace;
private Dictionary<MapId, EntityUid> _mapEntities => _mapSystem.Maps;
/// <inheritdoc />
public virtual void DeleteMap(MapId mapId)
{
#if DEBUG
DebugTools.Assert(_dbgGuardRunning);
#endif
if (!_mapEntities.TryGetValue(mapId, out var ent) || !ent.IsValid())
throw new InvalidOperationException($"Attempted to delete nonexistent map '{mapId}'");
EntityManager.DeleteEntity(ent);
DebugTools.Assert(!_mapEntities.ContainsKey(mapId));
}
/// <inheritdoc />
public MapId CreateMap(MapId? mapId = null)
{
return ((IMapManagerInternal) this).CreateMap(mapId, default);
if (mapId != null)
{
_mapSystem.CreateMap(mapId.Value);
return mapId.Value;
}
_mapSystem.CreateMap(out var map);
return map;
}
/// <inheritdoc />
public bool MapExists(MapId mapId)
public bool MapExists([NotNullWhen(true)] MapId? mapId)
{
return _mapEntities.ContainsKey(mapId);
}
/// <inheritdoc />
public EntityUid CreateNewMapEntity(MapId mapId)
{
DebugTools.Assert(mapId != MapId.Nullspace);
#if DEBUG
DebugTools.Assert(_dbgGuardRunning);
#endif
var newEntity = EntityManager.CreateEntityUninitialized(null);
SetMapEntity(mapId, newEntity);
EntityManager.InitializeComponents(newEntity);
EntityManager.StartComponents(newEntity);
return newEntity;
}
/// <inheritdoc />
public void SetMapEntity(MapId mapId, EntityUid newMapEntity, bool updateChildren = true)
{
#if DEBUG
DebugTools.Assert(_dbgGuardRunning);
#endif
if (!_mapEntities.ContainsKey(mapId))
throw new InvalidOperationException($"Map {mapId} does not exist.");
foreach (var kvEntity in _mapEntities)
{
if (kvEntity.Value == newMapEntity)
{
if (mapId == kvEntity.Key)
return;
throw new InvalidOperationException(
$"Entity {newMapEntity} is already the root node of another map {kvEntity.Key}.");
}
}
MapComponent? mapComp;
// If this is being done as part of maploader then we want to copy the preinit state across mainly.
bool preInit = false;
bool paused = false;
// remove existing graph
if (_mapEntities.TryGetValue(mapId, out var oldEntId))
{
if (EntityManager.TryGetComponent(oldEntId, out mapComp))
{
preInit = mapComp.MapPreInit;
paused = mapComp.MapPaused;
}
EntityManager.System<SharedTransformSystem>().ReparentChildren(oldEntId, newMapEntity);
//Note: EntityUid.Invalid gets passed in here
//Note: This prevents setting a subgraph as the root, since the subgraph will be deleted
EntityManager.DeleteEntity(oldEntId);
}
var raiseEvent = false;
// re-use or add map component
if (!EntityManager.TryGetComponent(newMapEntity, out mapComp))
mapComp = EntityManager.AddComponent<MapComponent>(newMapEntity);
else
{
raiseEvent = true;
if (mapComp.MapId != mapId)
{
_sawmill.Warning($"Setting map {mapId} root to entity {newMapEntity}, but entity thinks it is root node of map {mapComp.MapId}.");
}
}
_sawmill.Debug($"Setting map {mapId} entity to {newMapEntity}");
// set as new map entity
mapComp.MapPreInit = preInit;
mapComp.MapPaused = paused;
mapComp.MapId = mapId;
_mapEntities[mapId] = newMapEntity;
// Yeah this sucks but I just want to save maps for now, deal.
if (raiseEvent)
{
var ev = new MapChangedEvent(newMapEntity, mapId, true);
EntityManager.EventBus.RaiseLocalEvent(newMapEntity, ev, true);
}
return _mapSystem.MapExists(mapId);
}
/// <inheritdoc />
public EntityUid GetMapEntityId(MapId mapId)
{
if (_mapEntities.TryGetValue(mapId, out var entId))
return entId;
if (_mapSystem.TryGetMap(mapId, out var entId))
return entId.Value;
return EntityUid.Invalid;
}
@@ -161,13 +73,12 @@ internal partial class MapManager
/// </summary>
public EntityUid GetMapEntityIdOrThrow(MapId mapId)
{
return _mapEntities[mapId];
return _mapSystem.GetMap(mapId);
}
/// <inheritdoc />
public bool HasMapEntity(MapId mapId)
public bool TryGetMap([NotNullWhen(true)] MapId? mapId, [NotNullWhen(true)] out EntityUid? uid)
{
return _mapEntities.ContainsKey(mapId);
return _mapSystem.TryGetMap(mapId, out uid);
}
/// <inheritdoc />
@@ -181,67 +92,4 @@ internal partial class MapManager
{
return EntityManager.HasComponent<MapComponent>(uid);
}
/// <inheritdoc />
public MapId NextMapId()
{
return _highestMapId = new MapId(_highestMapId.Value + 1);
}
MapId IMapManagerInternal.CreateMap(MapId? mapId, EntityUid entityUid)
{
if (mapId == MapId.Nullspace)
throw new InvalidOperationException("Attempted to create a null-space map.");
#if DEBUG
DebugTools.Assert(_dbgGuardRunning);
#endif
var actualId = mapId ?? new MapId(_highestMapId.Value + 1);
if (MapExists(actualId))
throw new InvalidOperationException($"A map with ID {actualId} already exists");
if (_highestMapId.Value < actualId.Value)
_highestMapId = actualId;
_sawmill.Info($"Creating new map {actualId}");
if (actualId != MapId.Nullspace) // nullspace isn't bound to an entity
{
Entity<MapComponent> result = default;
var query = EntityManager.AllEntityQueryEnumerator<MapComponent>();
while (query.MoveNext(out var uid, out var map))
{
if (map.MapId != actualId)
continue;
result = (uid, map);
break;
}
if (result != default)
{
DebugTools.Assert(mapId != null);
_mapEntities.Add(actualId, result);
_sawmill.Debug($"Rebinding map {actualId} to entity {result.Owner}");
}
else
{
var newEnt = EntityManager.CreateEntityUninitialized(null, entityUid);
_mapEntities.Add(actualId, newEnt);
var mapComp = EntityManager.AddComponent<MapComponent>(newEnt);
mapComp.MapId = actualId;
var meta = EntityManager.GetComponent<MetaDataComponent>(newEnt);
EntityManager.System<MetaDataSystem>().SetEntityName(newEnt, $"map {actualId}", meta);
EntityManager.Dirty(newEnt, mapComp, meta);
EntityManager.InitializeComponents(newEnt, meta);
EntityManager.StartComponents(newEnt);
_sawmill.Debug($"Binding map {actualId} to entity {newEnt}");
}
}
return actualId;
}
}

View File

@@ -1,6 +1,5 @@
using System;
using System.Globalization;
using System.Linq;
using Robust.Shared.GameObjects;
using Robust.Shared.Map.Components;
@@ -8,145 +7,44 @@ namespace Robust.Shared.Map
{
internal partial class MapManager
{
/// <inheritdoc />
public void SetMapPaused(MapId mapId, bool paused)
{
if(mapId == MapId.Nullspace)
return;
if(!MapExists(mapId))
throw new ArgumentException("That map does not exist.");
var mapUid = GetMapEntityId(mapId);
var mapComp = EntityManager.GetComponent<MapComponent>(mapUid);
if (mapComp.MapPaused == paused)
return;
mapComp.MapPaused = paused;
EntityManager.Dirty(mapUid, mapComp);
var xformQuery = EntityManager.GetEntityQuery<TransformComponent>();
var metaQuery = EntityManager.GetEntityQuery<MetaDataComponent>();
var metaSystem = EntityManager.EntitySysManager.GetEntitySystem<MetaDataSystem>();
RecursiveSetPaused(mapUid, paused, in xformQuery, in metaQuery, in metaSystem);
_mapSystem.SetPaused(mapId, paused);
}
private static void RecursiveSetPaused(EntityUid entity, bool paused,
in EntityQuery<TransformComponent> xformQuery,
in EntityQuery<MetaDataComponent> metaQuery,
in MetaDataSystem system)
public void SetMapPaused(EntityUid uid, bool paused)
{
system.SetEntityPaused(entity, paused, metaQuery.GetComponent(entity));
var xform = xformQuery.GetComponent(entity);
foreach (var child in xform._children)
{
RecursiveSetPaused(child, paused, in xformQuery, in metaQuery, in system);
}
_mapSystem.SetPaused(uid, paused);
}
/// <inheritdoc />
public void DoMapInitialize(MapId mapId)
{
if(!MapExists(mapId))
throw new ArgumentException("That map does not exist.");
if (IsMapInitialized(mapId))
throw new ArgumentException("That map is already initialized.");
var mapEnt = GetMapEntityId(mapId);
var mapComp = EntityManager.GetComponent<MapComponent>(mapEnt);
var xformQuery = EntityManager.GetEntityQuery<TransformComponent>();
var metaQuery = EntityManager.GetEntityQuery<MetaDataComponent>();
var metaSystem = EntityManager.EntitySysManager.GetEntitySystem<MetaDataSystem>();
mapComp.MapPreInit = false;
mapComp.MapPaused = false;
EntityManager.Dirty(mapEnt, mapComp);
RecursiveDoMapInit(mapEnt, in xformQuery, in metaQuery, in metaSystem);
_mapSystem.InitializeMap(mapId);
}
private void RecursiveDoMapInit(EntityUid entity,
in EntityQuery<TransformComponent> xformQuery,
in EntityQuery<MetaDataComponent> metaQuery,
in MetaDataSystem system)
public bool IsMapInitialized(MapId mapId)
{
// RunMapInit can modify the TransformTree
// ToArray caches deleted euids, we check here if they still exist.
if(!metaQuery.TryGetComponent(entity, out var meta))
return;
EntityManager.RunMapInit(entity, meta);
system.SetEntityPaused(entity, false, meta);
foreach (var child in xformQuery.GetComponent(entity)._children.ToArray())
{
RecursiveDoMapInit(child, in xformQuery, in metaQuery, in system);
}
return _mapSystem.IsInitialized(mapId);
}
/// <inheritdoc />
public void AddUninitializedMap(MapId mapId)
{
SetMapPreInit(mapId);
}
private bool CheckMapPause(MapId mapId)
{
if(mapId == MapId.Nullspace)
return false;
var mapEuid = GetMapEntityId(mapId);
if (!EntityManager.TryGetComponent<MapComponent>(mapEuid, out var map))
return false;
return map.MapPaused;
}
private void SetMapPreInit(MapId mapId)
{
if(mapId == MapId.Nullspace)
return;
var mapEuid = GetMapEntityId(mapId);
var mapComp = EntityManager.GetComponent<MapComponent>(mapEuid);
mapComp.MapPreInit = true;
}
private bool CheckMapPreInit(MapId mapId)
{
if(mapId == MapId.Nullspace)
return false;
var mapEuid = GetMapEntityId(mapId);
if (!EntityManager.TryGetComponent<MapComponent>(mapEuid, out var map))
return false;
return map.MapPreInit;
var ent = GetMapEntityId(mapId);
EntityManager.GetComponent<MapComponent>(ent).MapInitialized = false;
var meta = EntityManager.GetComponent<MetaDataComponent>(ent);
((EntityManager)EntityManager).SetLifeStage(meta, EntityLifeStage.Initialized);
}
/// <inheritdoc />
public bool IsMapPaused(MapId mapId)
{
if(mapId == MapId.Nullspace)
return false;
var mapEuid = GetMapEntityId(mapId);
if (!EntityManager.TryGetComponent<MapComponent>(mapEuid, out var map))
return false;
return map.MapPaused || map.MapPreInit;
return _mapSystem.IsPaused(mapId);
}
/// <inheritdoc />
public bool IsMapInitialized(MapId mapId)
public bool IsMapPaused(EntityUid uid)
{
return !CheckMapPreInit(mapId);
return _mapSystem.IsPaused(uid);
}
/// <summary>

View File

@@ -3,13 +3,9 @@ using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Log;
using Robust.Shared.Map.Components;
using Robust.Shared.Maths;
using Robust.Shared.Physics;
using Robust.Shared.Physics.Collision;
using Robust.Shared.Physics.Components;
using Robust.Shared.Physics.Systems;
using Robust.Shared.Timing;
using Robust.Shared.Utility;
namespace Robust.Shared.Map;
@@ -23,60 +19,36 @@ internal partial class MapManager : IMapManagerInternal, IEntityEventSubscriber
[Dependency] private readonly IConsoleHost _conhost = default!;
private ISawmill _sawmill = default!;
private ISawmill _sawmill => _mapSystem.Log;
private FixtureSystem _fixtureSystem = default!;
private SharedMapSystem _mapSystem = default!;
private SharedPhysicsSystem _physics = default!;
private SharedTransformSystem _transformSystem = default!;
private EntityQuery<FixturesComponent> _fixturesQuery;
private EntityQuery<GridTreeComponent> _gridTreeQuery;
private EntityQuery<MapGridComponent> _gridQuery;
private EntityQuery<PhysicsComponent> _physicsQuery;
private EntityQuery<TransformComponent> _xformQuery;
/// <inheritdoc />
public void Initialize()
{
_fixturesQuery = EntityManager.GetEntityQuery<FixturesComponent>();
_gridTreeQuery = EntityManager.GetEntityQuery<GridTreeComponent>();
_gridQuery = EntityManager.GetEntityQuery<MapGridComponent>();
_physicsQuery = EntityManager.GetEntityQuery<PhysicsComponent>();
_xformQuery = EntityManager.GetEntityQuery<TransformComponent>();
_sawmill = Logger.GetSawmill("map");
#if DEBUG
DebugTools.Assert(!_dbgGuardInit);
DebugTools.Assert(!_dbgGuardRunning);
_dbgGuardInit = true;
#endif
InitializeMapPausing();
}
/// <inheritdoc />
public void Startup()
{
_fixtureSystem = EntityManager.System<FixtureSystem>();
_physics = EntityManager.System<SharedPhysicsSystem>();
_transformSystem = EntityManager.System<SharedTransformSystem>();
_mapSystem = EntityManager.System<SharedMapSystem>();
#if DEBUG
DebugTools.Assert(_dbgGuardInit);
_dbgGuardRunning = true;
#endif
_sawmill.Debug("Starting...");
}
/// <inheritdoc />
public void Shutdown()
{
#if DEBUG
DebugTools.Assert(_dbgGuardInit);
#endif
_sawmill.Debug("Stopping...");
// TODO: AllEntityQuery instead???
@@ -102,9 +74,4 @@ internal partial class MapManager : IMapManagerInternal, IEntityEventSubscriber
EntityManager.DeleteEntity(uid);
}
}
#if DEBUG
private bool _dbgGuardInit;
private bool _dbgGuardRunning;
#endif
}

View File

@@ -313,55 +313,60 @@ public partial class SharedPhysicsSystem
Dirty(uid, body);
}
public void SetAngularVelocity(EntityUid uid, float value, bool dirty = true, FixturesComponent? manager = null, PhysicsComponent? body = null)
public bool SetAngularVelocity(EntityUid uid, float value, bool dirty = true, FixturesComponent? manager = null, PhysicsComponent? body = null)
{
if (!Resolve(uid, ref body))
return;
return false;
if (body.BodyType == BodyType.Static)
return;
return false;
if (value * value > 0.0f)
{
if (!WakeBody(uid, manager: manager, body: body))
return;
return false;
}
// CloseToPercent tolerance needs to be small enough such that an angular velocity just above
// sleep-tolerance can damp down to sleeping.
if (MathHelper.CloseToPercent(body.AngularVelocity, value, 0.00001f))
return;
return false;
body.AngularVelocity = value;
if (dirty)
Dirty(uid, body);
return true;
}
/// <summary>
/// Attempts to set the body to collidable, wake it, then move it.
/// </summary>
public void SetLinearVelocity(EntityUid uid, Vector2 velocity, bool dirty = true, bool wakeBody = true, FixturesComponent? manager = null, PhysicsComponent? body = null)
public bool SetLinearVelocity(EntityUid uid, Vector2 velocity, bool dirty = true, bool wakeBody = true, FixturesComponent? manager = null, PhysicsComponent? body = null)
{
if (!Resolve(uid, ref body))
return;
return false;
if (body.BodyType == BodyType.Static) return;
if (body.BodyType == BodyType.Static)
return false;
if (wakeBody && Vector2.Dot(velocity, velocity) > 0.0f)
{
if (!WakeBody(uid, manager: manager, body: body))
return;
return false;
}
if (body.LinearVelocity.EqualsApprox(velocity, 0.0000001f))
return;
return false;
body.LinearVelocity = velocity;
if (dirty)
Dirty(uid, body);
return true;
}
public void SetAngularDamping(EntityUid uid, PhysicsComponent body, float value, bool dirty = true)

View File

@@ -660,13 +660,11 @@ public abstract partial class SharedPhysicsSystem
});
// Update data sequentially
var metaQuery = GetEntityQuery<MetaDataComponent>();
for (var i = 0; i < actualIslands.Length; i++)
{
var island = actualIslands[i];
UpdateBodies(in island, solvedPositions, solvedAngles, linearVelocities, angularVelocities, xformQuery, metaQuery);
UpdateBodies(in island, solvedPositions, solvedAngles, linearVelocities, angularVelocities, xformQuery);
SleepBodies(in island, sleepStatus);
}
@@ -1001,8 +999,7 @@ public abstract partial class SharedPhysicsSystem
float[] angles,
Vector2[] linearVelocities,
float[] angularVelocities,
EntityQuery<TransformComponent> xformQuery,
EntityQuery<MetaDataComponent> metaQuery)
EntityQuery<TransformComponent> xformQuery)
{
foreach (var (joint, error) in island.BrokenJoints)
{
@@ -1035,21 +1032,22 @@ public abstract partial class SharedPhysicsSystem
}
var linVelocity = linearVelocities[offset + i];
var physicsDirtied = false;
if (!float.IsNaN(linVelocity.X) && !float.IsNaN(linVelocity.Y))
{
SetLinearVelocity(uid, linVelocity, false, body: body);
physicsDirtied |= SetLinearVelocity(uid, linVelocity, false, body: body);
}
var angVelocity = angularVelocities[offset + i];
if (!float.IsNaN(angVelocity))
{
SetAngularVelocity(uid, angVelocity, false, body: body);
physicsDirtied |= SetAngularVelocity(uid, angVelocity, false, body: body);
}
// TODO: Should check if the values update.
Dirty(uid, body, metaQuery.GetComponent(uid));
if (physicsDirtied)
Dirty(uid, body);
}
}

View File

@@ -6,7 +6,7 @@ namespace Robust.Shared.Prototypes;
/// Prototype that represents game entities.
/// </summary>
[Prototype("entityCategory")]
public sealed class EntityCategoryPrototype : IPrototype
public sealed partial class EntityCategoryPrototype : IPrototype
{
[IdDataField]
public string ID { get; private set; } = default!;
@@ -22,4 +22,4 @@ public sealed class EntityCategoryPrototype : IPrototype
/// </summary>
[DataField("description")]
public string? Description { get; private set; }
}
}

View File

@@ -4,6 +4,7 @@ using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using Robust.Shared.Random;
using Robust.Shared.Reflection;
using Robust.Shared.Serialization.Manager;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.Serialization.Markdown;
@@ -272,7 +273,8 @@ public interface IPrototypeManager
out Dictionary<Type, HashSet<string>> prototypes);
/// <summary>
/// This method uses reflection to validate that prototype id fields correspond to valid prototypes.
/// This method uses reflection to validate that all static prototype id fields correspond to valid prototypes.
/// This will validate all known to <see cref="IReflectionManager"/>
/// </summary>
/// <remarks>
/// This will validate any field that has either a <see cref="ValidatePrototypeIdAttribute{T}"/> attribute, or a
@@ -280,7 +282,12 @@ public interface IPrototypeManager
/// </remarks>
/// <param name="prototypes">A collection prototypes to use for validation. Any prototype not in this collection
/// will be considered invalid.</param>
List<string> ValidateFields(Dictionary<Type, HashSet<string>> prototypes);
List<string> ValidateStaticFields(Dictionary<Type, HashSet<string>> prototypes);
/// <summary>
/// This is a variant of <see cref="ValidateStaticFields(System.Collections.Generic.Dictionary{System.Type,System.Collections.Generic.HashSet{string}})"/> that only validates a single type.
/// </summary>
List<string> ValidateStaticFields(Type type, Dictionary<Type, HashSet<string>> prototypes);
/// <summary>
/// This method will serialize all loaded prototypes into yaml and then validate them. This can be used to ensure

View File

@@ -4,7 +4,6 @@ using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype;
using Robust.Shared.Utility;
using BindingFlags = System.Reflection.BindingFlags;
@@ -13,35 +12,41 @@ namespace Robust.Shared.Prototypes;
public partial class PrototypeManager
{
/// <inheritdoc/>
public List<string> ValidateFields(Dictionary<Type, HashSet<string>> prototypes)
public List<string> ValidateStaticFields(Dictionary<Type, HashSet<string>> prototypes)
{
var errors = new List<string>();
foreach (var type in _reflectionManager.FindAllTypes())
{
// TODO validate public static fields on abstract classes that have no implementations?
if (!type.IsAbstract)
ValidateType(type, errors, prototypes);
ValidateStaticFieldsInternal(type, errors, prototypes);
}
return errors;
}
/// <summary>
/// Validate all fields defined on this type and all base types.
/// </summary>
private void ValidateType(Type type, List<string> errors, Dictionary<Type, HashSet<string>> prototypes)
/// <inheritdoc/>
public List<string> ValidateStaticFields(Type type, Dictionary<Type, HashSet<string>> prototypes)
{
object? instance = null;
Type? baseType = type;
var errors = new List<string>();
ValidateStaticFieldsInternal(type, errors, prototypes);
return errors;
}
var flags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public |
BindingFlags.DeclaredOnly;
/// <summary>
/// Validate all static fields defined on this type and all base types.
/// </summary>
private void ValidateStaticFieldsInternal(Type type, List<string> errors, Dictionary<Type, HashSet<string>> prototypes)
{
var baseType = type;
var flags = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly;
while (baseType != null)
{
foreach (var field in baseType.GetFields(flags))
{
ValidateField(field, type, ref instance, errors, prototypes);
DebugTools.Assert(field.IsStatic);
ValidateStaticField(field, type, errors, prototypes);
}
// We need to get the fields on the base type separately in order to get the private fields
@@ -49,92 +54,110 @@ public partial class PrototypeManager
}
}
private void ValidateField(
private void ValidateStaticField(
FieldInfo field,
Type type,
ref object? instance,
List<string> errors,
Dictionary<Type, HashSet<string>> prototypes)
{
DebugTools.Assert(field.IsStatic);
DebugTools.Assert(!field.HasCustomAttribute<DataFieldAttribute>(), "Datafields should not be static");
// Is this even a prototype id related field?
if (!TryGetFieldPrototype(field, out var proto, out var canBeNull, out var canBeEmpty))
if (!TryGetFieldPrototype(field, out var proto))
return;
if (!TryGetFieldValue(field, type, ref instance, errors, out var value))
return;
var id = value?.ToString();
if (id == null)
if (!prototypes.TryGetValue(proto, out var validIds))
{
if (!canBeNull)
errors.Add($"Prototype id field failed validation. Fields should not be null. Field: {field.Name} in {type.FullName}");
errors.Add($"Prototype id field failed validation. Unknown prototype kind {proto.Name}. Field: {field.Name} in {type.FullName}");
return;
}
if (string.IsNullOrWhiteSpace(id))
if (!TryGetIds(field, proto, out var ids))
{
if (!canBeEmpty)
errors.Add($"Prototype id field failed validation. Non-optional non-nullable data-fields must have a default value. Field: {field.Name} in {type.FullName}");
TryGetIds(field, proto, out _);
DebugTools.Assert($"Failed to get ids, despite resolving the field into a prototype kind?");
return;
}
if (!prototypes.TryGetValue(proto, out var ids))
foreach (var id in ids)
{
errors.Add($"Prototype id field failed validation. Unknown prototype kind. Field: {field.Name} in {type.FullName}");
return;
}
if (!ids.Contains(id))
{
errors.Add($"Prototype id field failed validation. Unknown prototype: {id}. Field: {field.Name} in {type.FullName}");
if (!validIds.Contains(id))
errors.Add($"Prototype id field failed validation. Unknown prototype: {id} of type {proto.Name}. Field: {field.Name} in {type.FullName}");
}
}
/// <summary>
/// Get the value of some field. If this is not a static field, this will create instance of the object in order to
/// validate default field values.
/// Extract prototype ids from a string, IEnumerable{string}, EntProtoId, IEnumerable{EntProtoId}, ProtoId{T}, or IEnumerable{ProtoId{T}} field.
/// </summary>
private bool TryGetFieldValue(FieldInfo field, Type type, ref object? instance, List<string> errors, out object? value)
private bool TryGetIds(FieldInfo field, Type proto, [NotNullWhen(true)] out string[]? ids)
{
value = null;
ids = null;
var value = field.GetValue(null);
if (value == null)
return false;
if (field.IsStatic || instance != null)
if (value is string str)
{
value = field.GetValue(instance);
ids = [str];
return true;
}
var constructor = type.GetConstructor(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
Type.EmptyTypes);
// TODO handle parameterless record constructors.
// Figure out how ISerializationManager does it, or just re-use that code somehow.
// In the meantime, record data fields need an explicit parameterless ctor.
if (constructor == null)
if (value is IEnumerable<string> strEnum)
{
errors.Add($"Prototype id field failed validation. Could not create instance to validate default value. Field: {field.Name} in {type.FullName}");
return false;
ids = strEnum.ToArray();
return true;
}
instance = constructor.Invoke(Array.Empty<object>());
value = field.GetValue(instance);
if (value is EntProtoId protoId)
{
ids = [protoId];
return true;
}
return true;
if (value is IEnumerable<EntProtoId> protoIdEnum)
{
ids = protoIdEnum.Select(x=> x.Id).ToArray();
return true;
}
if (field.FieldType.IsGenericType && field.FieldType.GetGenericTypeDefinition() == typeof(ProtoId<>))
{
ids = [value.ToString()!];
return true;
}
foreach (var iface in field.FieldType.GetInterfaces())
{
if (!iface.IsGenericType)
continue;
if (iface.GetGenericTypeDefinition() != typeof(IEnumerable<>))
continue;
var enumType = iface.GetGenericArguments().Single();
if (!enumType.IsGenericType)
continue;
if (enumType.GetGenericTypeDefinition() != typeof(ProtoId<>))
continue;
ids = GetIdsMethod.MakeGenericMethod(proto).Invoke(null, [value]) as string[];
return ids != null;
}
return false;
}
private bool TryGetFieldPrototype(
FieldInfo field,
[NotNullWhen(true)] out Type? proto,
out bool canBeNull,
out bool canBeEmpty)
private static MethodInfo GetIdsMethod = typeof(PrototypeManager).GetMethod(nameof(GetIds), BindingFlags.NonPublic | BindingFlags.Static)!;
private static string[] GetIds<T>(IEnumerable<ProtoId<T>> enumerable) where T : class, IPrototype
{
proto = null;
canBeNull = false;
canBeEmpty = false;
return enumerable.Select(x => x.Id).ToArray();
}
private bool TryGetFieldPrototype(FieldInfo field, [NotNullWhen(true)] out Type? proto)
{
// Validate anything with the attribute
var attrib = field.GetCustomAttribute(typeof(ValidatePrototypeIdAttribute<>), false);
if (attrib != null)
{
@@ -142,46 +165,40 @@ public partial class PrototypeManager
return true;
}
if (!field.TryGetCustomAttribute(out DataFieldAttribute? dataField))
return false;
if (TryGetPrototypeFromType(field.FieldType, out proto))
return true;
var fieldType = field.FieldType;
canBeEmpty = dataField.Required;
DebugTools.Assert(!field.IsStatic);
// Resolve nullable structs
if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof(Nullable<>))
// Allow validating arrays or lists.
foreach (var iface in field.FieldType.GetInterfaces().Where(x => x.IsGenericType))
{
fieldType = fieldType.GetGenericArguments().Single();
canBeNull = true;
if (iface.GetGenericTypeDefinition() != typeof(IEnumerable<>))
continue;
var enumType = iface.GetGenericArguments().Single();
if (TryGetPrototypeFromType(enumType, out proto))
return true;
}
if (fieldType == typeof(EntProtoId))
proto = null;
return false;
}
private bool TryGetPrototypeFromType(Type type, [NotNullWhen(true)] out Type? proto)
{
if (type == typeof(EntProtoId))
{
proto = typeof(EntityPrototype);
return true;
}
if (fieldType.IsGenericType && field.FieldType.GetGenericTypeDefinition() == typeof(ProtoId<>))
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ProtoId<>))
{
proto = field.FieldType.GetGenericArguments().Single();
proto = type.GetGenericArguments().Single();
DebugTools.Assert(proto != typeof(EntityPrototype), "Use EntProtoId instead of ProtoId<EntityPrototype>");
return true;
}
// As far as I know there is no way to check for the nullability of a string field, so we will assume that null
// values imply that the field itself is properly marked as nullable.
canBeNull = true;
if (dataField.CustomTypeSerializer == null)
return false;
if (!dataField.CustomTypeSerializer.IsGenericType)
return false;
if (dataField.CustomTypeSerializer.GetGenericTypeDefinition() != typeof(PrototypeIdSerializer<>))
return false;
proto = dataField.CustomTypeSerializer.GetGenericArguments().First();
return true;
proto = null;
return false;
}
}

View File

@@ -53,7 +53,7 @@ public partial class PrototypeManager
var mapping = node.ToDataNodeCast<MappingDataNode>();
var id = mapping.Get<ValueDataNode>("id").Value;
var data = new PrototypeValidationData(mapping, resourcePath.ToString());
var data = new PrototypeValidationData(id, mapping, resourcePath.ToString());
mapping.Remove("type");
if (prototypes.GetOrNew(type).TryAdd(id, data))
@@ -65,10 +65,14 @@ public partial class PrototypeManager
}
}
var ctx = new YamlValidationContext();
var errors = new List<ErrorNode>();
foreach (var (type, instances) in prototypes)
{
foreach (var data in instances.Values)
var defaultErrorOccurred = false;
foreach (var (id, data) in instances)
{
errors.Clear();
EnsurePushed(data, instances, type);
if (data.Mapping.TryGet("abstract", out ValueDataNode? abstractNode)
&& bool.Parse(abstractNode.Value))
@@ -76,9 +80,25 @@ public partial class PrototypeManager
continue;
}
var result = _serializationManager.ValidateNode(type, data.Mapping).GetErrors().ToHashSet();
if (result.Count > 0)
dict.GetOrNew(data.File).UnionWith(result);
// Validate yaml directly
errors.AddRange(_serializationManager.ValidateNode(type, data.Mapping).GetErrors());
if (errors.Count > 0)
dict.GetOrNew(data.File).UnionWith(errors);
// Create instance & re-serialize it, to validate the default values of data-fields. We still validate
// the yaml directly just in case reading & writing the fields somehow modifies their values.
try
{
var instance = _serializationManager.Read(type, data.Mapping, ctx);
var mapping = _serializationManager.WriteValue(type, instance, alwaysWrite: true, ctx);
errors.AddRange(_serializationManager.ValidateNode(type, mapping, ctx).GetErrors());
if (errors.Count > 0)
dict.GetOrNew(data.File).UnionWith(errors);
}
catch (Exception ex)
{
errors.Add(new ErrorNode(new ValueDataNode(), $"Caught Exception while validating {type} prototype {id}. Exception: {ex}"));
}
}
}
@@ -152,12 +172,17 @@ public partial class PrototypeManager
private sealed class PrototypeValidationData
{
public readonly string Id;
public MappingDataNode Mapping;
public readonly string File;
public bool Pushed;
public PrototypeValidationData(MappingDataNode mapping, string file)
public string[]? Parents;
public MappingDataNode[]? ParentMappings;
public PrototypeValidationData(string id, MappingDataNode mapping, string file)
{
Id = id;
File = file;
Mapping = mapping;
}
@@ -176,23 +201,22 @@ public partial class PrototypeManager
if (!data.Mapping.TryGet(ParentDataFieldAttribute.Name, out var parentNode))
return;
var parents = _serializationManager.Read<string[]>(parentNode, notNullableOverride: true);
var parentNodes = new MappingDataNode[parents.Length];
DebugTools.AssertNull(data.Parents);
DebugTools.AssertNull(data.ParentMappings);
data.Parents = _serializationManager.Read<string[]>(parentNode, notNullableOverride: true);
data.ParentMappings = new MappingDataNode[data.Parents.Length];
foreach (var parentId in parents)
var i = 0;
foreach (var parentId in data.Parents)
{
var parent = prototypes[parentId];
EnsurePushed(parent, prototypes, type);
for (var i = 0; i < parents.Length; i++)
{
parentNodes[i] = parent.Mapping;
}
data.ParentMappings[i++] = parent.Mapping;
}
data.Mapping = _serializationManager.PushCompositionWithGenericNode(
type,
parentNodes,
data.ParentMappings,
data.Mapping);
}
}

View File

@@ -8,7 +8,7 @@ namespace Robust.Shared.Prototypes;
/// Tile alias prototypes, unlike tile prototypes, are implemented here, as they're really just fed to TileDefinitionManager.
/// </summary>
[Prototype("tileAlias")]
public sealed class TileAliasPrototype : IPrototype
public sealed partial class TileAliasPrototype : IPrototype
{
/// <summary>
/// The target tile ID to alias to.

View File

@@ -0,0 +1,62 @@
using System.Globalization;
using JetBrains.Annotations;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Serialization;
using Robust.Shared.Serialization.Manager;
using Robust.Shared.Serialization.Markdown;
using Robust.Shared.Serialization.Markdown.Validation;
using Robust.Shared.Serialization.Markdown.Value;
using Robust.Shared.Serialization.TypeSerializers.Interfaces;
namespace Robust.Shared.Prototypes;
internal sealed class YamlValidationContext : ISerializationContext, ITypeSerializer<EntityUid, ValueDataNode>
{
public SerializationManager.SerializerProvider SerializerProvider { get; } = new();
public bool WritingReadingPrototypes => true;
public YamlValidationContext()
{
SerializerProvider.RegisterSerializer(this);
}
ValidationNode ITypeValidator<EntityUid, ValueDataNode>.Validate(ISerializationManager serializationManager,
ValueDataNode node, IDependencyCollection dependencies, ISerializationContext? context)
{
if (node.Value == "null" || node.Value == "invalid")
return new ValidatedValueNode(node);
return new ErrorNode(node, "Prototypes should not contain EntityUids", true);
}
public DataNode Write(ISerializationManager serializationManager, EntityUid value,
IDependencyCollection dependencies, bool alwaysWrite = false,
ISerializationContext? context = null)
{
if (!value.Valid)
return new ValueDataNode("invalid");
return new ValueDataNode(value.Id.ToString(CultureInfo.InvariantCulture));
}
EntityUid ITypeReader<EntityUid, ValueDataNode>.Read(ISerializationManager serializationManager,
ValueDataNode node,
IDependencyCollection dependencies,
SerializationHookContext hookCtx,
ISerializationContext? context, ISerializationManager.InstantiationDelegate<EntityUid>? _)
{
if (node.Value == "invalid")
return EntityUid.Invalid;
return EntityUid.Parse(node.Value);
}
[MustUseReturnValue]
public EntityUid Copy(ISerializationManager serializationManager, EntityUid source, EntityUid target,
bool skipHook,
ISerializationContext? context = null)
{
return new((int)source);
}
}

View File

@@ -4,8 +4,9 @@ using Robust.Shared.Prototypes;
namespace Robust.Shared.Serialization.Manager.Attributes;
/// <summary>
/// This attribute should be used on string fields to validate that they correspond to a valid YAML prototype id.
/// If the field needs to be have a default value.
/// This attribute should be used on static string or string collection fields to validate that they correspond to
/// valid YAML prototype ids. This attribute is not required for static <see cref="ProtoId{T}"/> and
/// <see cref="EntProtoId"/> fields, as they automatically get validated.
/// </summary>
[AttributeUsage(AttributeTargets.Field)]
public sealed class ValidatePrototypeIdAttribute<T> : Attribute where T : IPrototype

View File

@@ -143,7 +143,7 @@ namespace Robust.Shared.Serialization.Manager.Definition
nodeVariable),
call,
dfa.Required
? ExpressionUtils.ThrowExpression<RequiredFieldNotMappedException>(fieldDefinition.FieldType, tagConst)
? ExpressionUtils.ThrowExpression<RequiredFieldNotMappedException>(fieldDefinition.FieldType, tagConst, typeof(T))
: AssignIfNotDefaultExpression(i, targetParam, Expression.Constant(DefaultValues[i], fieldDefinition.FieldType))
)));
}

View File

@@ -4,7 +4,7 @@ namespace Robust.Shared.Serialization.Manager.Exceptions;
public sealed class RequiredFieldNotMappedException : Exception
{
public RequiredFieldNotMappedException(Type type, string field) : base($"Required field {field} of type {type} wasn't mapped.")
public RequiredFieldNotMappedException(Type type, string field, Type dataDef) : base($"Required field {field} of type {type} in {dataDef} wasn't mapped.")
{
}
}

View File

@@ -21,7 +21,7 @@ namespace Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Pro
/// <summary>
/// Checks that a string corresponds to a valid prototype id. Note that any data fields using this serializer will
/// also be validated by <see cref="IPrototypeManager.ValidateFields"/>
/// also be validated by <see cref="IPrototypeManager.ValidateStaticFields"/>
/// </summary>
[Virtual]
public class PrototypeIdSerializer<TPrototype> : ITypeValidator<string, ValueDataNode> where TPrototype : class, IPrototype

View File

@@ -13,22 +13,18 @@ namespace Robust.UnitTesting.Client.GameObjects.Components
[TestOf(typeof(TransformComponent))]
public sealed class TransformComponentTests
{
private static readonly MapId TestMapId = new(1);
private static (ISimulation, EntityUid gridA, EntityUid gridB) SimulationFactory()
{
var sim = RobustServerSimulation
.NewSimulation()
.InitializeInstance();
var mapId = sim.Resolve<IEntityManager>().System<SharedMapSystem>().CreateMap();
var mapManager = sim.Resolve<IMapManager>();
// Adds the map with id 1, and spawns entity 1 as the map entity.
mapManager.CreateMap(TestMapId);
// Adds two grids to use in tests.
var gridA = mapManager.CreateGridEntity(TestMapId);
var gridB = mapManager.CreateGridEntity(TestMapId);
var gridA = mapManager.CreateGridEntity(mapId);
var gridB = mapManager.CreateGridEntity(mapId);
return (sim, gridA, gridB);
}

View File

@@ -27,7 +27,7 @@ public sealed partial class ComponentMapInitTest
var sim = simFactory.InitializeInstance();
var entManager = sim.Resolve<IEntityManager>();
var mapManager = sim.Resolve<IMapManager>();
var mapId = mapManager.CreateMap();
sim.Resolve<IEntityManager>().System<SharedMapSystem>().CreateMap(out var mapId);
var ent = entManager.SpawnEntity(null, new MapCoordinates(Vector2.Zero, mapId));
Assert.That(entManager.GetComponent<MetaDataComponent>(ent).EntityLifeStage, Is.EqualTo(EntityLifeStage.MapInitialized));

View File

@@ -1,6 +1,5 @@
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using NUnit.Framework;
using Robust.Server.Containers;
using Robust.Shared.Containers;
@@ -19,14 +18,15 @@ namespace Robust.UnitTesting.Server.GameObjects.Components
[TestFixture, Parallelizable]
public sealed partial class ContainerTest
{
private static EntityCoordinates _coords;
private static ISimulation SimulationFactory()
{
var sim = RobustServerSimulation
.NewSimulation()
.InitializeInstance();
// Adds the map with id 1, and spawns entity 1 as the map entity.
sim.AddMap(1);
var map = sim.CreateMap();
_coords = new EntityCoordinates(map.Item1, default);
return sim;
}
@@ -37,8 +37,7 @@ namespace Robust.UnitTesting.Server.GameObjects.Components
var sim = SimulationFactory();
var entManager = sim.Resolve<IEntityManager>();
var containerSys = sim.Resolve<IEntitySystemManager>().GetEntitySystem<ContainerSystem>();
var entity = sim.SpawnEntity(null, new EntityCoordinates(EntityUid.FirstUid, new Vector2(0, 0)));
var entity = sim.SpawnEntity(null,_coords);
var container = containerSys.MakeContainer<Container>(entity, "dummy");
@@ -74,9 +73,8 @@ namespace Robust.UnitTesting.Server.GameObjects.Components
var sim = SimulationFactory();
var entManager = sim.Resolve<IEntityManager>();
var containerSys = sim.Resolve<IEntitySystemManager>().GetEntitySystem<ContainerSystem>();
var owner = sim.SpawnEntity(null, new EntityCoordinates(EntityUid.FirstUid, new Vector2(0, 0)));
var inserted = sim.SpawnEntity(null, new EntityCoordinates(EntityUid.FirstUid, new Vector2(0, 0)));
var owner = sim.SpawnEntity(null,_coords);
var inserted = sim.SpawnEntity(null,_coords);
var transform = entManager.GetComponent<TransformComponent>(inserted);
var container = containerSys.MakeContainer<Container>(owner, "dummy");
@@ -104,11 +102,10 @@ namespace Robust.UnitTesting.Server.GameObjects.Components
var sim = SimulationFactory();
var entManager = sim.Resolve<IEntityManager>();
var containerSys = sim.Resolve<IEntitySystemManager>().GetEntitySystem<ContainerSystem>();
var owner = sim.SpawnEntity(null, new EntityCoordinates(EntityUid.FirstUid, new Vector2(0, 0)));
var inserted = sim.SpawnEntity(null, new EntityCoordinates(EntityUid.FirstUid, new Vector2(0, 0)));
var owner = sim.SpawnEntity(null,_coords);
var inserted = sim.SpawnEntity(null,_coords);
var transform = entManager.GetComponent<TransformComponent>(inserted);
var entity = sim.SpawnEntity(null, new EntityCoordinates(EntityUid.FirstUid, new Vector2(0, 0)));
var entity = sim.SpawnEntity(null,_coords);
var container = containerSys.MakeContainer<Container>(owner, "dummy");
Assert.That(containerSys.Insert(inserted, container), Is.True);
@@ -132,8 +129,7 @@ namespace Robust.UnitTesting.Server.GameObjects.Components
var sim = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
var containerSys = sim.Resolve<IEntitySystemManager>().GetEntitySystem<ContainerSystem>();
var coordinates = new EntityCoordinates(EntityUid.FirstUid, new Vector2(0, 0));
var coordinates =_coords;
var entityOne = sim.SpawnEntity(null, coordinates);
var entityTwo = sim.SpawnEntity(null, coordinates);
var entityThree = sim.SpawnEntity(null, coordinates);
@@ -165,8 +161,7 @@ namespace Robust.UnitTesting.Server.GameObjects.Components
{
var sim = SimulationFactory();
var containerSys = sim.Resolve<IEntitySystemManager>().GetEntitySystem<ContainerSystem>();
var entity = sim.SpawnEntity(null, new EntityCoordinates(EntityUid.FirstUid, new Vector2(0, 0)));
var entity = sim.SpawnEntity(null,_coords);
var container = containerSys.MakeContainer<Container>(entity, "dummy");
Assert.That(containerSys.Insert(entity, container), Is.False);
@@ -178,9 +173,8 @@ namespace Robust.UnitTesting.Server.GameObjects.Components
{
var sim = SimulationFactory();
var containerSys = sim.Resolve<IEntitySystemManager>().GetEntitySystem<ContainerSystem>();
var mapEnt = EntityUid.FirstUid;
var entity = sim.SpawnEntity(null, new EntityCoordinates(EntityUid.FirstUid, new Vector2(0, 0)));
var mapEnt = new EntityUid(1);
var entity = sim.SpawnEntity(null,_coords);
var container = containerSys.MakeContainer<Container>(entity, "dummy");
Assert.That(containerSys.Insert(mapEnt, container), Is.False);
@@ -194,7 +188,7 @@ namespace Robust.UnitTesting.Server.GameObjects.Components
var containerSys = sim.Resolve<IEntitySystemManager>().GetEntitySystem<ContainerSystem>();
var grid = sim.Resolve<IMapManager>().CreateGridEntity(new MapId(1)).Owner;
var entity = sim.SpawnEntity(null, new EntityCoordinates(EntityUid.FirstUid, new Vector2(0, 0)));
var entity = sim.SpawnEntity(null,_coords);
var container = containerSys.MakeContainer<Container>(entity, "dummy");
Assert.That(containerSys.Insert(grid, container), Is.False);
@@ -207,10 +201,9 @@ namespace Robust.UnitTesting.Server.GameObjects.Components
var sim = SimulationFactory();
var entManager = sim.Resolve<IEntityManager>();
var containerSys = sim.Resolve<IEntitySystemManager>().GetEntitySystem<ContainerSystem>();
var containerEntity = sim.SpawnEntity(null, new EntityCoordinates(EntityUid.FirstUid, new Vector2(0, 0)));
var containerEntity = sim.SpawnEntity(null,_coords);
var container = containerSys.MakeContainer<Container>(containerEntity, "dummy");
var insertEntity = sim.SpawnEntity(null, new EntityCoordinates(EntityUid.FirstUid, new Vector2(0, 0)));
var insertEntity = sim.SpawnEntity(null,_coords);
var result = containerSys.Insert(insertEntity, container);
@@ -230,10 +223,9 @@ namespace Robust.UnitTesting.Server.GameObjects.Components
{
var sim = SimulationFactory();
var containerSys = sim.Resolve<IEntitySystemManager>().GetEntitySystem<ContainerSystem>();
var containerEntity = sim.SpawnEntity(null, new EntityCoordinates(EntityUid.FirstUid, new Vector2(0, 0)));
var containerEntity = sim.SpawnEntity(null,_coords);
var container = containerSys.MakeContainer<Container>(containerEntity, "dummy");
var insertEntity = sim.SpawnEntity(null, new EntityCoordinates(EntityUid.FirstUid, new Vector2(0, 0)));
var insertEntity = sim.SpawnEntity(null,_coords);
var result = containerSys.Remove(insertEntity, container);
@@ -245,12 +237,11 @@ namespace Robust.UnitTesting.Server.GameObjects.Components
{
var sim = SimulationFactory();
var containerSys = sim.Resolve<IEntitySystemManager>().GetEntitySystem<ContainerSystem>();
var entity1 = sim.SpawnEntity(null, new EntityCoordinates(EntityUid.FirstUid, new Vector2(0, 0)));
var entity1 = sim.SpawnEntity(null,_coords);
var container1 = containerSys.MakeContainer<Container>(entity1, "dummy");
var entity2 = sim.SpawnEntity(null, new EntityCoordinates(EntityUid.FirstUid, new Vector2(0, 0)));
var entity2 = sim.SpawnEntity(null,_coords);
var container2 = containerSys.MakeContainer<Container>(entity2, "dummy");
var transferEntity = sim.SpawnEntity(null, new EntityCoordinates(EntityUid.FirstUid, new Vector2(0, 0)));
var transferEntity = sim.SpawnEntity(null,_coords);
containerSys.Insert(transferEntity, container1);
var result = containerSys.Insert(transferEntity, container2);
@@ -266,10 +257,9 @@ namespace Robust.UnitTesting.Server.GameObjects.Components
var sim = SimulationFactory();
var entManager = sim.Resolve<IEntityManager>();
var containerSys = entManager.System<ContainerSystem>();
var entity = sim.SpawnEntity(null, new EntityCoordinates(EntityUid.FirstUid, new Vector2(0, 0)));
var entity = sim.SpawnEntity(null,_coords);
var container = containerSys.MakeContainer<Container>(entity, "dummy");
var childEnt = sim.SpawnEntity(null, new EntityCoordinates(EntityUid.FirstUid, new Vector2(0, 0)));
var childEnt = sim.SpawnEntity(null,_coords);
container.OccludesLight = true;
container.ShowContents = true;

View File

@@ -20,12 +20,9 @@ public sealed class TransformIntegration_Test
var sim = factory.InitializeInstance();
var entManager = sim.Resolve<IEntityManager>();
var mapManager = sim.Resolve<IMapManager>();
var containerSystem = entManager.System<SharedContainerSystem>();
var xformSystem = entManager.System<SharedTransformSystem>();
var map1Id = mapManager.CreateMap();
var map1 = mapManager.GetMapEntityId(map1Id);
var map1 = sim.CreateMap().Uid;
var ent1 = entManager.SpawnEntity(null, new EntityCoordinates(map1, Vector2.Zero));
var ent2 = entManager.SpawnEntity(null, new EntityCoordinates(map1, Vector2.Zero));

View File

@@ -49,7 +49,6 @@ namespace Robust.UnitTesting.Server.GameObjects.Components
EntityManager = IoCManager.Resolve<IServerEntityManagerInternal>();
MapManager = IoCManager.Resolve<IMapManager>();
MapManager.CreateMap();
IoCManager.Resolve<ISerializationManager>().Initialize();
var manager = IoCManager.Resolve<IPrototypeManager>();
@@ -57,11 +56,12 @@ namespace Robust.UnitTesting.Server.GameObjects.Components
manager.LoadFromStream(new StringReader(Prototypes));
manager.ResolveResults();
var mapSys = EntityManager.System<SharedMapSystem>();
// build the net dream
MapA = MapManager.CreateMap();
GridA = MapManager.CreateGridEntity(MapA);
mapSys.CreateMap(out MapA);
mapSys.CreateMap(out MapB);
MapB = MapManager.CreateMap();
GridA = MapManager.CreateGridEntity(MapA);
GridB = MapManager.CreateGridEntity(MapB);
//NOTE: The grids have not moved, so we can assert worldpos == localpos for the test

View File

@@ -37,8 +37,6 @@ namespace Robust.UnitTesting.Server.GameObjects
.RegisterEntitySystems(f => f.LoadExtraSystemType<DebugExceptionSystem>())
.RegisterPrototypes(protoMan => protoMan.LoadString(PROTOTYPES))
.InitializeInstance();
_sim.AddMap(1);
}
[TestCase("throwInAdd")]
@@ -47,8 +45,9 @@ namespace Robust.UnitTesting.Server.GameObjects
public void Test(string prototypeName)
{
var entMan = _sim.Resolve<IEntityManager>();
_sim.Resolve<IEntityManager>().System<SharedMapSystem>().CreateMap(out var map);
Assert.That(() => entMan.SpawnEntity(prototypeName, new MapCoordinates(0, 0, new MapId(1))),
Assert.That(() => entMan.SpawnEntity(prototypeName, new MapCoordinates(0, 0, map)),
Throws.TypeOf<EntityCreationException>());
Assert.That(entMan.GetEntities().Where(p => entMan.GetComponent<MetaDataComponent>(p).EntityPrototype?.ID == prototypeName), Is.Empty);

View File

@@ -75,8 +75,7 @@ public sealed class DefaultEntityTest : RobustIntegrationTest
EntityCoordinates coords = default!;
await server.WaitPost(() =>
{
var mapId = mapMan.CreateMap();
var map = mapMan.GetMapEntityId(mapId);
var map = server.System<SharedMapSystem>().CreateMap();
coords = new(map, default);
var playerUid = sEntMan.SpawnEntity(null, coords);
player = sEntMan.GetNetEntity(playerUid);

View File

@@ -71,15 +71,13 @@ public sealed class MissingParentTest : RobustIntegrationTest
}
// Set up map and spawn player
EntityUid map = default;
NetEntity player = default;
NetEntity entity = default;
EntityCoordinates coords = default;
NetCoordinates nCoords = default;
await server.WaitPost(() =>
{
var mapId = mapMan.CreateMap();
map = mapMan.GetMapEntityId(mapId);
var map = server.System<SharedMapSystem>().CreateMap();
coords = new(map, default);
var playerUid = sEntMan.SpawnEntity(null, coords);

View File

@@ -69,14 +69,11 @@ public sealed class PvsChunkTest : RobustIntegrationTest
EntityCoordinates mapCoords = default;
await server.WaitPost(() =>
{
var mapId = mapMan.CreateMap();
map1 = mapMan.GetMapEntityId(mapId);
map1 = server.System<SharedMapSystem>().CreateMap();
mapCoords = new(map1, default);
var map2Id = mapMan.CreateMap();
map2 = mapMan.GetMapEntityId(map2Id);
var gridComp = mapMan.CreateGridEntity(map2Id);
map2 = server.System<SharedMapSystem>().CreateMap();
var gridComp = mapMan.CreateGridEntity(map2);
grid = gridComp.Owner;
mapSys.SetTile(grid, gridComp, Vector2i.Zero, new Tile(1));
var gridCoords = new EntityCoordinates(grid, .5f, .5f);

View File

@@ -74,8 +74,7 @@ public sealed class PvsReEntryTest : RobustIntegrationTest
EntityCoordinates coords = default;
await server.WaitPost(() =>
{
var mapId = mapMan.CreateMap();
map = mapMan.GetMapEntityId(mapId);
map = server.System<SharedMapSystem>().CreateMap();
coords = new(map, default);
var playerUid = sEntMan.SpawnEntity(null, coords);

View File

@@ -50,8 +50,7 @@ public sealed class PvsSystemTests : RobustIntegrationTest
EntityUid map = default;
await server.WaitPost(() =>
{
var mapId = mapMan.CreateMap();
map = mapMan.GetMapEntityId(mapId);
map = server.System<SharedMapSystem>().CreateMap(out var mapId);
var gridComp = mapMan.CreateGridEntity(mapId);
gridComp.Comp.SetTile(Vector2i.Zero, new Tile(1));
grid = gridComp.Owner;

View File

@@ -11,6 +11,7 @@ using Robust.Shared.Physics.Dynamics;
using Robust.Shared.Prototypes;
using Robust.Shared.Serialization.Manager;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.Utility;
namespace Robust.UnitTesting.Server.Maps
{
@@ -78,15 +79,10 @@ entities:
public void TestDataLoadPriority()
{
// TODO: Fix after serv3
var map = IoCManager.Resolve<IMapManager>();
// fix what?
var entMan = IoCManager.Resolve<IEntityManager>();
var mapId = map.CreateMap();
// Yay test bullshit
var mapUid = map.GetMapEntityId(mapId);
entMan.EnsureComponent<PhysicsMapComponent>(mapUid);
entMan.EnsureComponent<BroadphaseComponent>(mapUid);
entMan.System<SharedMapSystem>().CreateMap(out var mapId);
var traversal = entMan.System<SharedGridTraversalSystem>();
traversal.Enabled = false;

View File

@@ -71,8 +71,7 @@ namespace Robust.UnitTesting.Server
/// <summary>
/// Adds a new map directly to the map manager.
/// </summary>
EntityUid AddMap(int mapId);
EntityUid AddMap(MapId mapId);
(EntityUid Uid, MapId MapId) CreateMap();
EntityUid SpawnEntity(string? protoId, EntityCoordinates coordinates);
EntityUid SpawnEntity(string? protoId, MapCoordinates coordinates);
}
@@ -99,18 +98,10 @@ namespace Robust.UnitTesting.Server
return Collection.Resolve<T>();
}
public EntityUid AddMap(int mapId)
public (EntityUid Uid, MapId MapId) CreateMap()
{
var mapMan = Collection.Resolve<IMapManager>();
mapMan.CreateMap(new MapId(mapId));
return mapMan.GetMapEntityId(new MapId(mapId));
}
public EntityUid AddMap(MapId mapId)
{
var mapMan = Collection.Resolve<IMapManager>();
mapMan.CreateMap(mapId);
return mapMan.GetMapEntityId(mapId);
var uid = Collection.Resolve<IEntityManager>().System<SharedMapSystem>().CreateMap(out var mapId);
return (uid, mapId);
}
public EntityUid SpawnEntity(string? protoId, EntityCoordinates coordinates)

View File

@@ -21,7 +21,7 @@ namespace Robust.UnitTesting.Shared
var entManager = server.Resolve<IEntityManager>();
var mapManager = server.Resolve<IMapManager>();
var mapId = mapManager.CreateMap();
var mapId = server.CreateMap().MapId;
var theMapSpotBeingUsed = new Box2(Vector2.Zero, Vector2.One);
@@ -43,7 +43,7 @@ namespace Robust.UnitTesting.Shared
var entManager = server.Resolve<IEntityManager>();
var mapManager = server.Resolve<IMapManager>();
var mapId = mapManager.CreateMap();
var mapId = server.CreateMap().MapId;
var grid = mapManager.CreateGridEntity(mapId);
var theMapSpotBeingUsed = new Box2(Vector2.Zero, Vector2.One);

View File

@@ -62,7 +62,7 @@ namespace Robust.UnitTesting.Shared.GameObjects
await server.WaitAssertion(() =>
{
mapId = sMapManager.CreateMap();
sEntManager.System<SharedMapSystem>().CreateMap(out mapId);
mapPos = new MapCoordinates(new Vector2(0, 0), mapId);
entityUid = sEntManager.SpawnEntity(null, mapPos);
@@ -190,7 +190,7 @@ namespace Robust.UnitTesting.Shared.GameObjects
await server.WaitAssertion(() =>
{
mapId = sMapManager.CreateMap();
sEntManager.System<SharedMapSystem>().CreateMap(out mapId);
mapPos = new MapCoordinates(new Vector2(0, 0), mapId);
sEntityUid = sEntManager.SpawnEntity(null, mapPos);
@@ -300,7 +300,7 @@ namespace Robust.UnitTesting.Shared.GameObjects
await server.WaitAssertion(() =>
{
// build the map
var mapIdOne = mapManager.CreateMap();
sEntManager.System<SharedMapSystem>().CreateMap(out var mapIdOne);
Assert.That(mapManager.IsMapInitialized(mapIdOne), Is.True);
var containerEnt = sEntManager.SpawnEntity(null, new MapCoordinates(1, 1, mapIdOne));
@@ -327,7 +327,7 @@ namespace Robust.UnitTesting.Shared.GameObjects
await server.WaitAssertion(() =>
{
var mapLoader = sEntManager.System<MapLoaderSystem>();
var mapIdTwo = mapManager.CreateMap();
sEntManager.System<SharedMapSystem>().CreateMap(out var mapIdTwo);
// load the map
mapLoader.Load(mapIdTwo, "container_test.yml");

View File

@@ -30,8 +30,7 @@ public sealed partial class EntityEventBusTests
.RegisterComponents(factory => factory.RegisterClass<FooComponent>())
.InitializeInstance();
var map = new MapId(1);
simulation.AddMap(map);
var map = simulation.CreateMap().MapId;
var entity = simulation.SpawnEntity(null, new MapCoordinates(0, 0, map));
simulation.Resolve<IEntityManager>().AddComponent<FooComponent>(entity);

View File

@@ -20,9 +20,7 @@ namespace Robust.UnitTesting.Shared.GameObjects
.RegisterEntitySystems(factory => factory.LoadExtraSystemType<SubscribeCompRefDirectedEventSystem>())
.InitializeInstance();
var map = new MapId(1);
simulation.AddMap(map);
var map = simulation.CreateMap().MapId;
var entity = simulation.SpawnEntity(null, new MapCoordinates(0, 0, map));
IoCManager.Resolve<IEntityManager>().AddComponent<DummyComponent>(entity);
@@ -86,9 +84,7 @@ namespace Robust.UnitTesting.Shared.GameObjects
})
.InitializeInstance();
var map = new MapId(1);
simulation.AddMap(map);
var map = simulation.CreateMap().MapId;
var entity = simulation.SpawnEntity(null, new MapCoordinates(0, 0, map));
IoCManager.Resolve<IEntityManager>().AddComponent<OrderAComponent>(entity);
IoCManager.Resolve<IEntityManager>().AddComponent<OrderBComponent>(entity);

View File

@@ -16,8 +16,6 @@ namespace Robust.UnitTesting.Shared.GameObjects
[TestFixture, Parallelizable ,TestOf(typeof(EntityManager))]
public sealed partial class EntityManager_Components_Tests
{
private static readonly EntityCoordinates DefaultCoords = new(EntityUid.FirstUid, Vector2.Zero);
private const string DummyLoad = @"
- type: entity
id: DummyLoad
@@ -35,12 +33,12 @@ namespace Robust.UnitTesting.Shared.GameObjects
.RegisterPrototypes(fac => fac.LoadString(DummyLoad))
.InitializeInstance();
sim.AddMap(1);
var entMan = sim.Resolve<IEntityManager>();
var protoManager = sim.Resolve<IPrototypeManager>();
var entity = entMan.SpawnEntity(null, DefaultCoords);
var map = sim.CreateMap().Uid;
var coords = new EntityCoordinates(map, default);
var entity = entMan.SpawnEntity(null, coords);
Assert.That(!entMan.HasComponent<PhysicsComponent>(entity));
var proto = protoManager.Index<EntityPrototype>("DummyLoad");
@@ -60,12 +58,12 @@ namespace Robust.UnitTesting.Shared.GameObjects
.RegisterPrototypes(fac => fac.LoadString(DummyLoad))
.InitializeInstance();
sim.AddMap(1);
var entMan = sim.Resolve<IEntityManager>();
var protoManager = sim.Resolve<IPrototypeManager>();
var entity = entMan.SpawnEntity("DummyLoad", DefaultCoords);
var map = sim.CreateMap().Uid;
var coords = new EntityCoordinates(map, default);
var entity = entMan.SpawnEntity("DummyLoad", coords);
var proto = protoManager.Index<EntityPrototype>("DummyLoad");
entMan.RemoveComponents(entity, proto);
@@ -80,9 +78,9 @@ namespace Robust.UnitTesting.Shared.GameObjects
public void AddComponentTest()
{
// Arrange
var sim = SimulationFactory();
var (sim, coords) = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
var entity = entMan.SpawnEntity(null, DefaultCoords);
var entity = entMan.SpawnEntity(null, coords);
var component = new DummyComponent()
{
Owner = entity
@@ -100,9 +98,9 @@ namespace Robust.UnitTesting.Shared.GameObjects
public void AddComponentOverwriteTest()
{
// Arrange
var sim = SimulationFactory();
var (sim, coords) = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
var entity = entMan.SpawnEntity(null, DefaultCoords);
var entity = entMan.SpawnEntity(null, coords);
var component = new DummyComponent()
{
Owner = entity
@@ -120,9 +118,9 @@ namespace Robust.UnitTesting.Shared.GameObjects
public void AddComponent_ExistingDeleted()
{
// Arrange
var sim = SimulationFactory();
var (sim, coords) = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
var entity = entMan.SpawnEntity(null, DefaultCoords);
var entity = entMan.SpawnEntity(null, coords);
var firstComp = new DummyComponent {Owner = entity};
entMan.AddComponent(entity, firstComp);
entMan.RemoveComponent<DummyComponent>(entity);
@@ -140,9 +138,9 @@ namespace Robust.UnitTesting.Shared.GameObjects
public void HasComponentTest()
{
// Arrange
var sim = SimulationFactory();
var (sim, coords) = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
var entity = entMan.SpawnEntity(null, DefaultCoords);
var entity = entMan.SpawnEntity(null, coords);
entMan.AddComponent<DummyComponent>(entity);
// Act
@@ -156,9 +154,9 @@ namespace Robust.UnitTesting.Shared.GameObjects
public void HasComponentNoGenericTest()
{
// Arrange
var sim = SimulationFactory();
var (sim, coords) = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
var entity = entMan.SpawnEntity(null, DefaultCoords);
var entity = entMan.SpawnEntity(null, coords);
entMan.AddComponent<DummyComponent>(entity);
// Act
@@ -172,13 +170,13 @@ namespace Robust.UnitTesting.Shared.GameObjects
public void HasNetComponentTest()
{
// Arrange
var sim = SimulationFactory();
var (sim, coords) = SimulationFactory();
var factory = sim.Resolve<IComponentFactory>();
var netId = factory.GetRegistration<DummyComponent>().NetID!;
var entMan = sim.Resolve<IEntityManager>();
var entity = entMan.SpawnEntity(null, DefaultCoords);
var entity = entMan.SpawnEntity(null, coords);
entMan.AddComponent<DummyComponent>(entity);
// Act
@@ -192,13 +190,13 @@ namespace Robust.UnitTesting.Shared.GameObjects
public void GetNetComponentTest()
{
// Arrange
var sim = SimulationFactory();
var (sim, coords) = SimulationFactory();
var factory = sim.Resolve<IComponentFactory>();
var netId = factory.GetRegistration<DummyComponent>().NetID!;
var entMan = sim.Resolve<IEntityManager>();
var entity = entMan.SpawnEntity(null, DefaultCoords);
var entity = entMan.SpawnEntity(null, coords);
var component = entMan.AddComponent<DummyComponent>(entity);
// Act
@@ -212,9 +210,9 @@ namespace Robust.UnitTesting.Shared.GameObjects
public void TryGetComponentTest()
{
// Arrange
var sim = SimulationFactory();
var (sim, coords) = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
var entity = entMan.SpawnEntity(null, DefaultCoords);
var entity = entMan.SpawnEntity(null, coords);
var component = entMan.AddComponent<DummyComponent>(entity);
// Act
@@ -229,13 +227,13 @@ namespace Robust.UnitTesting.Shared.GameObjects
public void TryGetNetComponentTest()
{
// Arrange
var sim = SimulationFactory();
var (sim, coords) = SimulationFactory();
var factory = sim.Resolve<IComponentFactory>();
var netId = factory.GetRegistration<DummyComponent>().NetID!;
var entMan = sim.Resolve<IEntityManager>();
var entity = entMan.SpawnEntity(null, DefaultCoords);
var entity = entMan.SpawnEntity(null, coords);
var component = entMan.AddComponent<DummyComponent>(entity);
// Act
@@ -250,9 +248,9 @@ namespace Robust.UnitTesting.Shared.GameObjects
public void RemoveComponentTest()
{
// Arrange
var sim = SimulationFactory();
var (sim, coords) = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
var entity = entMan.SpawnEntity(null, DefaultCoords);
var entity = entMan.SpawnEntity(null, coords);
var component = entMan.AddComponent<DummyComponent>(entity);
// Act
@@ -266,9 +264,9 @@ namespace Robust.UnitTesting.Shared.GameObjects
[Test]
public void EnsureQueuedComponentDeletion()
{
var sim = SimulationFactory();
var (sim, coords) = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
var entity = entMan.SpawnEntity(null, DefaultCoords);
var entity = entMan.SpawnEntity(null, coords);
var component = entMan.AddComponent<DummyComponent>(entity);
Assert.That(component.LifeStage, Is.LessThanOrEqualTo(ComponentLifeStage.Running));
@@ -284,13 +282,13 @@ namespace Robust.UnitTesting.Shared.GameObjects
public void RemoveNetComponentTest()
{
// Arrange
var sim = SimulationFactory();
var (sim, coords) = SimulationFactory();
var factory = sim.Resolve<IComponentFactory>();
var netId = factory.GetRegistration<DummyComponent>().NetID!;
var entMan = sim.Resolve<IEntityManager>();
var entity = entMan.SpawnEntity(null, DefaultCoords);
var entity = entMan.SpawnEntity(null, coords);
var component = entMan.AddComponent<DummyComponent>(entity);
// Act
@@ -305,9 +303,9 @@ namespace Robust.UnitTesting.Shared.GameObjects
public void GetComponentsTest()
{
// Arrange
var sim = SimulationFactory();
var (sim, coords) = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
var entity = entMan.SpawnEntity(null, DefaultCoords);
var entity = entMan.SpawnEntity(null, coords);
var component = entMan.AddComponent<DummyComponent>(entity);
// Act
@@ -323,9 +321,9 @@ namespace Robust.UnitTesting.Shared.GameObjects
public void GetAllComponentsTest()
{
// Arrange
var sim = SimulationFactory();
var (sim, coords) = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
var entity = entMan.SpawnEntity(null, DefaultCoords);
var entity = entMan.SpawnEntity(null, coords);
var component = entMan.AddComponent<DummyComponent>(entity);
// Act
@@ -341,10 +339,10 @@ namespace Robust.UnitTesting.Shared.GameObjects
public void GetAllComponentInstances()
{
// Arrange
var sim = SimulationFactory();
var (sim, coords) = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
var fac = sim.Resolve<IComponentFactory>();
var entity = entMan.SpawnEntity(null, DefaultCoords);
var entity = entMan.SpawnEntity(null, coords);
var component = entMan.AddComponent<DummyComponent>(entity);
// Act
@@ -356,17 +354,16 @@ namespace Robust.UnitTesting.Shared.GameObjects
Assert.That(list[0], Is.EqualTo(component));
}
private static ISimulation SimulationFactory()
private static (ISimulation, EntityCoordinates) SimulationFactory()
{
var sim = RobustServerSimulation
.NewSimulation()
.RegisterComponents(factory => factory.RegisterClass<DummyComponent>())
.InitializeInstance();
// Adds the map with id 1, and spawns entity 1 as the map entity.
sim.AddMap(1);
return sim;
var map = sim.CreateMap().Uid;
var coords = new EntityCoordinates(map, default);
return (sim, coords);
}
[NetworkedComponent()]

View File

@@ -1,7 +1,6 @@
using NUnit.Framework;
using Robust.Shared.GameObjects;
using Robust.Shared.Map;
using Robust.Shared.Maths;
using Robust.UnitTesting.Server;
namespace Robust.UnitTesting.Shared.GameObjects
@@ -9,19 +8,12 @@ namespace Robust.UnitTesting.Shared.GameObjects
[TestFixture, Parallelizable]
sealed class EntityManagerTests
{
private static readonly MapId TestMapId = new(1);
private static ISimulation SimulationFactory()
{
var sim = RobustServerSimulation
.NewSimulation()
.InitializeInstance();
var mapManager = sim.Resolve<IMapManager>();
// Adds the map with id 1, and spawns entity 1 as the map entity.
mapManager.CreateMap(TestMapId);
return sim;
}
@@ -32,9 +24,10 @@ namespace Robust.UnitTesting.Shared.GameObjects
public void SpawnEntity_PrototypeTransform_Works()
{
var sim = SimulationFactory();
var map = sim.CreateMap().MapId;
var entMan = sim.Resolve<IEntityManager>();
var newEnt = entMan.SpawnEntity(null, new MapCoordinates(0, 0, TestMapId));
var newEnt = entMan.SpawnEntity(null, new MapCoordinates(0, 0, map));
Assert.That(newEnt, Is.Not.EqualTo(EntityUid.Invalid));
}
@@ -48,7 +41,7 @@ namespace Robust.UnitTesting.Shared.GameObjects
Assert.That(entManager.Count<TransformComponent>(), Is.EqualTo(0));
var mapId = mapManager.CreateMap();
var mapId = sim.CreateMap().MapId;
Assert.That(entManager.Count<TransformComponent>(), Is.EqualTo(1));
mapManager.DeleteMap(mapId);
Assert.That(entManager.Count<TransformComponent>(), Is.EqualTo(0));

View File

@@ -20,8 +20,6 @@ namespace Robust.UnitTesting.Shared.GameObjects.Systems
[TestFixture, Parallelizable]
public sealed partial class AnchoredSystemTests
{
private static readonly MapId TestMapId = new(1);
private sealed class Subscriber : IEntityEventSubscriber { }
private const string Prototypes = @"
@@ -32,7 +30,7 @@ namespace Robust.UnitTesting.Shared.GameObjects.Systems
- type: Transform
anchored: true";
private static (ISimulation, EntityUid gridId) SimulationFactory()
private static (ISimulation, EntityUid gridId, MapCoordinates) SimulationFactory()
{
var sim = RobustServerSimulation
.NewSimulation()
@@ -46,12 +44,12 @@ namespace Robust.UnitTesting.Shared.GameObjects.Systems
var mapManager = sim.Resolve<IMapManager>();
// Adds the map with id 1, and spawns entity 1 as the map entity.
mapManager.CreateMap(TestMapId);
var testMapId = sim.CreateMap().MapId;
var coords = new MapCoordinates(new Vector2(7, 7), testMapId);
// Add grid 1, as the default grid to anchor things to.
var grid = mapManager.CreateGridEntity(TestMapId);
var grid = mapManager.CreateGridEntity(testMapId);
return (sim, grid);
return (sim, grid, coords);
}
// An entity is anchored to the tile it is over on the target grid.
@@ -70,11 +68,9 @@ namespace Robust.UnitTesting.Shared.GameObjects.Systems
[Test]
public void OnAnchored_WorldPosition_TileCenter()
{
var (sim, gridId) = SimulationFactory();
var (sim, gridId, coordinates) = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
var coordinates = new MapCoordinates(new Vector2(7, 7), TestMapId);
// can only be anchored to a tile
var grid = entMan.GetComponent<MapGridComponent>(gridId);
grid.SetTile(grid.TileIndicesFor(coordinates), new Tile(1));
@@ -169,9 +165,9 @@ namespace Robust.UnitTesting.Shared.GameObjects.Systems
var entMan = sim.Resolve<IEntityManager>();
var mapMan = sim.Resolve<IMapManager>();
mapMan.CreateMap(TestMapId);
var grid = mapMan.CreateGrid(TestMapId);
var coordinates = new MapCoordinates(new Vector2(7, 7), TestMapId);
var mapId = sim.CreateMap().MapId;
var grid = mapMan.CreateGrid(mapId);
var coordinates = new MapCoordinates(new Vector2(7, 7), mapId);
var pos = grid.TileIndicesFor(coordinates);
grid.SetTile(pos, new Tile(1));
@@ -194,11 +190,9 @@ namespace Robust.UnitTesting.Shared.GameObjects.Systems
[Test]
public void OnAnchored_Parent_SetToGrid()
{
var (sim, gridId) = SimulationFactory();
var (sim, gridId, coordinates) = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
var coordinates = new MapCoordinates(new Vector2(7, 7), TestMapId);
// can only be anchored to a tile
var grid = entMan.GetComponent<MapGridComponent>(gridId);
grid.SetTile(grid.TileIndicesFor(coordinates), new Tile(1));
@@ -221,11 +215,11 @@ namespace Robust.UnitTesting.Shared.GameObjects.Systems
[Test]
public void OnAnchored_EmptyTile_Nop()
{
var (sim, gridId) = SimulationFactory();
var (sim, gridId, coords) = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
var grid = entMan.GetComponent<MapGridComponent>(gridId);
var ent1 = entMan.SpawnEntity(null, new MapCoordinates(new Vector2(7, 7), TestMapId));
var ent1 = entMan.SpawnEntity(null, coords);
var tileIndices = grid.TileIndicesFor(entMan.GetComponent<TransformComponent>(ent1).Coordinates);
grid.SetTile(tileIndices, Tile.Empty);
@@ -243,11 +237,11 @@ namespace Robust.UnitTesting.Shared.GameObjects.Systems
[Test]
public void OnAnchored_NonEmptyTile_Anchors()
{
var (sim, gridId) = SimulationFactory();
var (sim, gridId, coords) = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
var grid = entMan.GetComponent<MapGridComponent>(gridId);
var ent1 = entMan.SpawnEntity(null, new MapCoordinates(new Vector2(7, 7), TestMapId));
var ent1 = entMan.SpawnEntity(null, coords);
var tileIndices = grid.TileIndicesFor(entMan.GetComponent<TransformComponent>(ent1).Coordinates);
grid.SetTile(tileIndices, new Tile(1));
@@ -269,11 +263,11 @@ namespace Robust.UnitTesting.Shared.GameObjects.Systems
[Test]
public void Anchored_SetPosition_Nop()
{
var (sim, gridId) = SimulationFactory();
var (sim, gridId, coordinates) = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
// coordinates are already tile centered to prevent snapping and MoveEvent
var coordinates = new MapCoordinates(new Vector2(7.5f, 7.5f), TestMapId);
coordinates = coordinates.Offset(new Vector2(0.5f, 0.5f));
// can only be anchored to a tile
var grid = entMan.GetComponent<MapGridComponent>(gridId);
@@ -297,12 +291,10 @@ namespace Robust.UnitTesting.Shared.GameObjects.Systems
[Test]
public void Anchored_ChangeParent_Unanchors()
{
var (sim, gridId) = SimulationFactory();
var (sim, gridId, coordinates) = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
var mapMan = sim.Resolve<IMapManager>();
var coordinates = new MapCoordinates(new Vector2(7, 7), TestMapId);
var grid = entMan.GetComponent<MapGridComponent>(gridId);
var ent1 = entMan.SpawnEntity(null, coordinates);
@@ -311,7 +303,7 @@ namespace Robust.UnitTesting.Shared.GameObjects.Systems
entMan.GetComponent<TransformComponent>(ent1).Anchored = true;
// Act
entMan.EntitySysManager.GetEntitySystem<SharedTransformSystem>().SetParent(ent1, mapMan.GetMapEntityId(TestMapId));
entMan.EntitySysManager.GetEntitySystem<SharedTransformSystem>().SetParent(ent1, mapMan.GetMapEntityId(coordinates.MapId));
Assert.That(entMan.GetComponent<TransformComponent>(ent1).Anchored, Is.False);
Assert.That(grid.GetAnchoredEntities(tileIndices).Count(), Is.EqualTo(0));
@@ -326,11 +318,11 @@ namespace Robust.UnitTesting.Shared.GameObjects.Systems
[Test]
public void Anchored_SetParentSame_Nop()
{
var (sim, gridId) = SimulationFactory();
var (sim, gridId, coords) = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
var grid = entMan.GetComponent<MapGridComponent>(gridId);
var ent1 = entMan.SpawnEntity(null, new MapCoordinates(new Vector2(7, 7), TestMapId));
var ent1 = entMan.SpawnEntity(null, coords);
var tileIndices = grid.TileIndicesFor(entMan.GetComponent<TransformComponent>(ent1).Coordinates);
grid.SetTile(tileIndices, new Tile(1));
entMan.GetComponent<TransformComponent>(ent1).Anchored = true;
@@ -348,11 +340,11 @@ namespace Robust.UnitTesting.Shared.GameObjects.Systems
[Test]
public void Anchored_TileToSpace_Unanchors()
{
var (sim, gridId) = SimulationFactory();
var (sim, gridId, coords) = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
var grid = entMan.GetComponent<MapGridComponent>(gridId);
var ent1 = entMan.SpawnEntity(null, new MapCoordinates(new Vector2(7, 7), TestMapId));
var ent1 = entMan.SpawnEntity(null, coords);
var tileIndices = grid.TileIndicesFor(entMan.GetComponent<TransformComponent>(ent1).Coordinates);
grid.SetTile(tileIndices, new Tile(1));
grid.SetTile(new Vector2i(100, 100), new Tile(1)); // Prevents the grid from being deleted when the Act happens
@@ -376,11 +368,11 @@ namespace Robust.UnitTesting.Shared.GameObjects.Systems
[Test]
public void Anchored_AddToContainer_Unanchors()
{
var (sim, gridId) = SimulationFactory();
var (sim, gridId, coords) = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
var grid = entMan.GetComponent<MapGridComponent>(gridId);
var ent1 = entMan.SpawnEntity(null, new MapCoordinates(new Vector2(7, 7), TestMapId));
var ent1 = entMan.SpawnEntity(null, coords);
var tileIndices = grid.TileIndicesFor(entMan.GetComponent<TransformComponent>(ent1).Coordinates);
grid.SetTile(tileIndices, new Tile(1));
entMan.GetComponent<TransformComponent>(ent1).Anchored = true;
@@ -404,11 +396,11 @@ namespace Robust.UnitTesting.Shared.GameObjects.Systems
[Test]
public void Anchored_AddPhysComp_IsStaticBody()
{
var (sim, gridId) = SimulationFactory();
var (sim, gridId, coords) = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
var grid = entMan.GetComponent<MapGridComponent>(gridId);
var ent1 = entMan.SpawnEntity(null, new MapCoordinates(new Vector2(7, 7), TestMapId));
var ent1 = entMan.SpawnEntity(null, coords);
var tileIndices = grid.TileIndicesFor(entMan.GetComponent<TransformComponent>(ent1).Coordinates);
grid.SetTile(tileIndices, new Tile(1));
entMan.GetComponent<TransformComponent>(ent1).Anchored = true;
@@ -426,12 +418,10 @@ namespace Robust.UnitTesting.Shared.GameObjects.Systems
[Test]
public void OnAnchored_HasPhysicsComp_IsStaticBody()
{
var (sim, gridId) = SimulationFactory();
var (sim, gridId, coordinates) = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
var physSystem = sim.Resolve<IEntitySystemManager>().GetEntitySystem<SharedPhysicsSystem>();
var coordinates = new MapCoordinates(new Vector2(7, 7), TestMapId);
// can only be anchored to a tile
var grid = entMan.GetComponent<MapGridComponent>(gridId);
grid.SetTile(grid.TileIndicesFor(coordinates), new Tile(1));
@@ -452,11 +442,11 @@ namespace Robust.UnitTesting.Shared.GameObjects.Systems
[Test]
public void OnUnanchored_HasPhysicsComp_IsDynamicBody()
{
var (sim, gridId) = SimulationFactory();
var (sim, gridId, coords) = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
var grid = entMan.GetComponent<MapGridComponent>(gridId);
var ent1 = entMan.SpawnEntity(null, new MapCoordinates(new Vector2(7, 7), TestMapId));
var ent1 = entMan.SpawnEntity(null, coords);
var tileIndices = grid.TileIndicesFor(entMan.GetComponent<TransformComponent>(ent1).Coordinates);
grid.SetTile(tileIndices, new Tile(1));
var physComp = entMan.AddComponent<PhysicsComponent>(ent1);
@@ -474,13 +464,13 @@ namespace Robust.UnitTesting.Shared.GameObjects.Systems
[Test]
public void SpawnAnchored_EmptyTile_Unanchors()
{
var (sim, gridId) = SimulationFactory();
var (sim, gridId, coords) = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
var grid = entMan.GetComponent<MapGridComponent>(gridId);
// Act
var ent1 = entMan.SpawnEntity("anchoredEnt", new MapCoordinates(new Vector2(7, 7), TestMapId));
var ent1 = entMan.SpawnEntity("anchoredEnt", coords);
var tileIndices = grid.TileIndicesFor(entMan.GetComponent<TransformComponent>(ent1).Coordinates);
Assert.That(grid.GetAnchoredEntities(tileIndices).Count(), Is.EqualTo(0));
@@ -494,11 +484,11 @@ namespace Robust.UnitTesting.Shared.GameObjects.Systems
[Test]
public void OnAnchored_InContainer_Nop()
{
var (sim, gridId) = SimulationFactory();
var (sim, gridId, coords) = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
var grid = entMan.GetComponent<MapGridComponent>(gridId);
var ent1 = entMan.SpawnEntity(null, new MapCoordinates(new Vector2(7, 7), TestMapId));
var ent1 = entMan.SpawnEntity(null, coords);
var tileIndices = grid.TileIndicesFor(entMan.GetComponent<TransformComponent>(ent1).Coordinates);
grid.SetTile(tileIndices, new Tile(1));
@@ -522,12 +512,10 @@ namespace Robust.UnitTesting.Shared.GameObjects.Systems
[Test]
public void Unanchored_Unanchor_Nop()
{
var (sim, gridId) = SimulationFactory();
var (sim, gridId, coordinates) = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
var mapMan = sim.Resolve<IMapManager>();
var coordinates = new MapCoordinates(new Vector2(7, 7), TestMapId);
// can only be anchored to a tile
var grid = entMan.GetComponent<MapGridComponent>(gridId);
grid.SetTile(grid.TileIndicesFor(coordinates), new Tile(1));
@@ -539,7 +527,7 @@ namespace Robust.UnitTesting.Shared.GameObjects.Systems
// Act
entMan.System<MoveEventTestSystem>().FailOnMove = true;
entMan.GetComponent<TransformComponent>(ent1).Anchored = false;
Assert.That(entMan.GetComponent<TransformComponent>(ent1).ParentUid, Is.EqualTo(mapMan.GetMapEntityId(TestMapId)));
Assert.That(entMan.GetComponent<TransformComponent>(ent1).ParentUid, Is.EqualTo(mapMan.GetMapEntityId(coordinates.MapId)));
entMan.System<MoveEventTestSystem>().FailOnMove = false;
traversal.Enabled = true;
}
@@ -550,11 +538,9 @@ namespace Robust.UnitTesting.Shared.GameObjects.Systems
[Test]
public void Anchored_Unanchored_ParentUnchanged()
{
var (sim, gridId) = SimulationFactory();
var (sim, gridId, coordinates) = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
var coordinates = new MapCoordinates(new Vector2(7, 7), TestMapId);
// can only be anchored to a tile
var grid = entMan.GetComponent<MapGridComponent>(gridId);
grid.SetTile(grid.TileIndicesFor(coordinates), new Tile(1));

View File

@@ -17,9 +17,6 @@ namespace Robust.UnitTesting.Shared.GameObjects.Systems
.RegisterEntitySystems(f => f.LoadExtraSystemType<AnchoredSystemTests.MoveEventTestSystem>())
.InitializeInstance();
// Adds the map with id 1, and spawns entity 1 as the map entity.
sim.AddMap(1);
return sim;
}
@@ -31,7 +28,8 @@ namespace Robust.UnitTesting.Shared.GameObjects.Systems
{
var sim = SimulationFactory();
var entMan = sim.Resolve<IEntityManager>();
var ent1 = entMan.SpawnEntity(null, new MapCoordinates(Vector2.Zero, new MapId(1)));
var map = sim.CreateMap().MapId;
var ent1 = entMan.SpawnEntity(null, new MapCoordinates(Vector2.Zero, map));
entMan.System<AnchoredSystemTests.MoveEventTestSystem>().ResetCounters();
IoCManager.Resolve<IEntityManager>().GetComponent<TransformComponent>(ent1).LocalPosition = Vector2.One;
@@ -47,7 +45,7 @@ namespace Robust.UnitTesting.Shared.GameObjects.Systems
var sim = SimulationFactory();
var entManager = sim.Resolve<IEntityManager>();
var xformSystem = sim.Resolve<IEntitySystemManager>().GetEntitySystem<SharedTransformSystem>();
var mapId = new MapId(1);
var mapId = sim.CreateMap().MapId;
var parent = entManager.SpawnEntity(null, new MapCoordinates(Vector2.One, mapId));
var parentXform = entManager.GetComponent<TransformComponent>(parent);
@@ -83,7 +81,7 @@ namespace Robust.UnitTesting.Shared.GameObjects.Systems
var sim = SimulationFactory();
var entManager = sim.Resolve<IEntityManager>();
var xformSystem = sim.Resolve<IEntitySystemManager>().GetEntitySystem<SharedTransformSystem>();
var mapId = new MapId(1);
var mapId = sim.CreateMap().MapId;
var parent = entManager.SpawnEntity(null, new MapCoordinates(Vector2.One, mapId));
var parentXform = entManager.GetComponent<TransformComponent>(parent);

View File

@@ -20,9 +20,7 @@ namespace Robust.UnitTesting.Shared.GameObjects
var server = RobustServerSimulation.NewSimulation().InitializeInstance();
var entManager = server.Resolve<IEntityManager>();
var mapManager = server.Resolve<IMapManager>();
var mapId = mapManager.CreateMap();
entManager.System<SharedMapSystem>().CreateMap(out var mapId);
var ent1 = entManager.SpawnEntity(null, new MapCoordinates(Vector2.Zero, mapId));
var ent2 = entManager.SpawnEntity(null, new MapCoordinates(new Vector2(100f, 0f), mapId));
@@ -56,7 +54,7 @@ namespace Robust.UnitTesting.Shared.GameObjects
var entManager = server.Resolve<IEntityManager>();
var mapManager = server.Resolve<IMapManager>();
var mapId = mapManager.CreateMap();
entManager.System<SharedMapSystem>().CreateMap(out var mapId);
var grid = mapManager.CreateGridEntity(mapId);
grid.Comp.SetTile(new Vector2i(0, 0), new Tile(1));
var gridXform = entManager.GetComponent<TransformComponent>(grid);

View File

@@ -38,12 +38,7 @@ public sealed partial class ComponentStateTests : RobustIntegrationTest
server.Post(() => server.CfgMan.SetCVar(CVars.NetPVS, true));
// Set up map.
EntityUid map = default;
await server.WaitPost(() =>
{
var mapId = server.MapMan.CreateMap();
map = server.MapMan.GetMapEntityId(mapId);
});
var map = server.System<SharedMapSystem>().CreateMap();
await RunTicks();
@@ -162,12 +157,7 @@ public sealed partial class ComponentStateTests : RobustIntegrationTest
server.Post(() => server.CfgMan.SetCVar(CVars.NetPVS, true));
// Set up map.
EntityUid map = default;
await server.WaitPost(() =>
{
var mapId = server.MapMan.CreateMap();
map = server.MapMan.GetMapEntityId(mapId);
});
var map = server.System<SharedMapSystem>().CreateMap();
await RunTicks();

View File

@@ -58,11 +58,10 @@ public sealed class DeletionNetworkingTests : RobustIntegrationTest
EntityUid grid2 = default;
NetEntity grid1Net = default;
NetEntity grid2Net = default;
server.System<SharedMapSystem>().CreateMap(out var mapId);
await server.WaitPost(() =>
{
var mapId = mapMan.CreateMap();
mapMan.GetMapEntityId(mapId);
var gridComp = mapMan.CreateGridEntity(mapId);
gridComp.Comp.SetTile(Vector2i.Zero, new Tile(1));
grid1 = gridComp.Owner;

View File

@@ -37,12 +37,7 @@ public sealed partial class NoSharedReferencesTest : RobustIntegrationTest
client.Post(() => netMan.ClientConnect(null!, 0, null!));
// Set up map.
EntityUid map = default;
await server.WaitPost(() =>
{
var mapId = server.MapMan.CreateMap();
map = server.MapMan.GetMapEntityId(mapId);
});
var map = server.System<SharedMapSystem>().CreateMap();
await RunTicks();

View File

@@ -48,8 +48,7 @@ namespace Robust.UnitTesting.Shared.Map
var entityManager = IoCManager.Resolve<IEntityManager>();
var mapManager = IoCManager.Resolve<IMapManager>();
var mapId = mapManager.CreateMap();
var mapEntity = mapManager.CreateNewMapEntity(mapId);
var mapEntity = entityManager.System<SharedMapSystem>().CreateMap(out var mapId);
var newEnt = entityManager.CreateEntityUninitialized(null, new MapCoordinates(Vector2.Zero, mapId));
var coords = IoCManager.Resolve<IEntityManager>().GetComponent<TransformComponent>(newEnt).Coordinates;
@@ -74,10 +73,7 @@ namespace Robust.UnitTesting.Shared.Map
public void IsValid_NonFiniteVector_False(float x, float y)
{
var entityManager = IoCManager.Resolve<IEntityManager>();
var mapManager = IoCManager.Resolve<IMapManager>();
var mapId = mapManager.CreateMap();
var mapEntity = mapManager.CreateNewMapEntity(mapId);
entityManager.System<SharedMapSystem>().CreateMap(out var mapId);
var newEnt = entityManager.CreateEntityUninitialized(null, new MapCoordinates(new Vector2(x, y), mapId));
var coords = IoCManager.Resolve<IEntityManager>().GetComponent<TransformComponent>(newEnt).Coordinates;
@@ -88,11 +84,7 @@ namespace Robust.UnitTesting.Shared.Map
[Test]
public void EntityCoordinates_Map()
{
var mapManager = IoCManager.Resolve<IMapManager>();
var mapId = mapManager.CreateMap();
var mapEntity = mapManager.CreateNewMapEntity(mapId);
var mapEntity = IoCManager.Resolve<IEntityManager>().System<SharedMapSystem>().CreateMap();
Assert.That(IoCManager.Resolve<IEntityManager>().GetComponent<TransformComponent>(mapEntity).ParentUid.IsValid(), Is.False);
Assert.That(IoCManager.Resolve<IEntityManager>().GetComponent<TransformComponent>(mapEntity).Coordinates.EntityId, Is.EqualTo(mapEntity));
}
@@ -104,12 +96,10 @@ namespace Robust.UnitTesting.Shared.Map
[Test]
public void NoParent_OffsetZero()
{
var mapManager = IoCManager.Resolve<IMapManager>();
var entMan = IoCManager.Resolve<IEntityManager>();
var uid = entMan.SpawnEntity(null, MapCoordinates.Nullspace);
var xform = entMan.GetComponent<TransformComponent>(uid);
Assert.That(xform.Coordinates.Position, Is.EqualTo(Vector2.Zero));
xform.LocalPosition = Vector2.One;
Assert.That(xform.Coordinates.Position, Is.EqualTo(Vector2.Zero));
}
@@ -120,8 +110,7 @@ namespace Robust.UnitTesting.Shared.Map
var entityManager = IoCManager.Resolve<IEntityManager>();
var mapManager = IoCManager.Resolve<IMapManager>();
var mapId = mapManager.CreateMap();
var mapEnt = mapManager.CreateNewMapEntity(mapId);
var mapEnt = entityManager.System<SharedMapSystem>().CreateMap(out var mapId);
var newEnt = entityManager.CreateEntityUninitialized(null, new MapCoordinates(Vector2.Zero, mapId));
Assert.That(IoCManager.Resolve<IEntityManager>().GetComponent<TransformComponent>(mapEnt).Coordinates.GetGridUid(entityManager), Is.Null);
@@ -135,7 +124,7 @@ namespace Robust.UnitTesting.Shared.Map
var entityManager = IoCManager.Resolve<IEntityManager>();
var mapManager = IoCManager.Resolve<IMapManager>();
var mapId = mapManager.CreateMap();
entityManager.System<SharedMapSystem>().CreateMap(out var mapId);
var grid = mapManager.CreateGridEntity(mapId);
var gridEnt = grid.Owner;
var newEnt = entityManager.CreateEntityUninitialized(null, new EntityCoordinates(gridEnt, Vector2.Zero));
@@ -152,8 +141,7 @@ namespace Robust.UnitTesting.Shared.Map
var entityManager = IoCManager.Resolve<IEntityManager>();
var mapManager = IoCManager.Resolve<IMapManager>();
var mapId = mapManager.CreateMap();
var mapEnt = mapManager.CreateNewMapEntity(mapId);
var mapEnt = entityManager.System<SharedMapSystem>().CreateMap(out var mapId);
var newEnt = entityManager.CreateEntityUninitialized(null, new MapCoordinates(Vector2.Zero, mapId));
Assert.That(IoCManager.Resolve<IEntityManager>().GetComponent<TransformComponent>(mapEnt).Coordinates.GetMapId(entityManager), Is.EqualTo(mapId));
@@ -166,7 +154,7 @@ namespace Robust.UnitTesting.Shared.Map
var entityManager = IoCManager.Resolve<IEntityManager>();
var mapManager = IoCManager.Resolve<IMapManager>();
var mapId = mapManager.CreateMap();
entityManager.System<SharedMapSystem>().CreateMap(out var mapId);
var grid = mapManager.CreateGridEntity(mapId);
var gridEnt = grid.Owner;
var newEnt = entityManager.CreateEntityUninitialized(null, new EntityCoordinates(gridEnt, Vector2.Zero));
@@ -181,9 +169,8 @@ namespace Robust.UnitTesting.Shared.Map
var entityManager = IoCManager.Resolve<IEntityManager>();
var mapManager = IoCManager.Resolve<IMapManager>();
var mapId = mapManager.CreateMap();
var mapEnt = entityManager.System<SharedMapSystem>().CreateMap(out var mapId);
var grid = mapManager.CreateGridEntity(mapId);
var mapEnt = mapManager.GetMapEntityId(mapId);
var gridEnt = grid.Owner;
var newEnt = entityManager.CreateEntityUninitialized(null, new EntityCoordinates(grid, Vector2.Zero));
@@ -203,9 +190,8 @@ namespace Robust.UnitTesting.Shared.Map
var entityManager = IoCManager.Resolve<IEntityManager>();
var mapManager = IoCManager.Resolve<IMapManager>();
var mapId = mapManager.CreateMap();
var mapEnt = entityManager.System<SharedMapSystem>().CreateMap(out var mapId);
var grid = mapManager.CreateGridEntity(mapId);
var mapEnt = mapManager.GetMapEntityId(mapId);
var gridEnt = grid.Owner;
var newEnt = entityManager.CreateEntityUninitialized(null, new EntityCoordinates(grid, Vector2.Zero));
@@ -256,7 +242,7 @@ namespace Robust.UnitTesting.Shared.Map
var transformSystem = entityManager.System<SharedTransformSystem>();
var mapId = mapManager.CreateMap();
entityManager.System<SharedMapSystem>().CreateMap(out var mapId);
var grid = mapManager.CreateGridEntity(mapId);
var gridEnt = grid.Owner;
var newEnt = entityManager.CreateEntityUninitialized(null, new EntityCoordinates(grid, entPos));
@@ -274,8 +260,7 @@ namespace Robust.UnitTesting.Shared.Map
var entityManager = IoCManager.Resolve<IEntityManager>();
var mapManager = IoCManager.Resolve<IMapManager>();
var mapId = mapManager.CreateMap();
var mapEnt = mapManager.GetMapEntityId(mapId);
var mapEnt = entityManager.System<SharedMapSystem>().CreateMap(out var mapId);
var grid = mapManager.CreateGridEntity(mapId);
var gridEnt = grid.Owner;
var newEnt = entityManager.CreateEntityUninitialized(null, new EntityCoordinates(grid, Vector2.Zero));

View File

@@ -33,7 +33,7 @@ namespace Robust.UnitTesting.Shared.Map
await server.WaitPost(() =>
{
mapId = mapManager.CreateMap();
entManager.System<SharedMapSystem>().CreateMap(out mapId);
gridId1 = mapManager.CreateGridEntity(mapId);
gridId2 = mapManager.CreateGridEntity(mapId);
gridEnt1 = gridId1.Value.Owner;

View File

@@ -21,7 +21,7 @@ namespace Robust.UnitTesting.Shared.Map
await server.WaitAssertion(() =>
{
var mapId = mapManager.CreateMap();
entManager.System<SharedMapSystem>().CreateMap(out var mapId);
var grid = mapManager.CreateGridEntity(mapId);
var gridEntity = grid.Owner;
@@ -59,7 +59,7 @@ namespace Robust.UnitTesting.Shared.Map
await server.WaitAssertion(() =>
{
var mapId = mapManager.CreateMap();
entManager.System<SharedMapSystem>().CreateMap(out var mapId);
var grid = mapManager.CreateGridEntity(mapId);
for (var i = 0; i < 10; i++)

View File

@@ -30,7 +30,7 @@ namespace Robust.UnitTesting.Shared.Map
await server.WaitAssertion(() =>
{
var mapId = mapManager.CreateMap();
entManager.System<SharedMapSystem>().CreateMap(out var mapId);
var grid = mapManager.CreateGridEntity(mapId);
// Should be nothing if grid empty

View File

@@ -45,7 +45,7 @@ public sealed class GridMerge_Tests
var mapSystem = entMan.System<SharedMapSystem>();
var gridFixtures = entMan.System<GridFixtureSystem>();
var mapId = mapManager.CreateMap();
var mapId = sim.CreateMap().MapId;
var grid1 = mapManager.CreateGridEntity(mapId);
var grid2 = mapManager.CreateGridEntity(mapId);
var tiles = new List<(Vector2i, Tile)>();

View File

@@ -28,7 +28,7 @@ namespace Robust.UnitTesting.Shared.Map
await server.WaitAssertion(() =>
{
var mapId = mapMan.CreateMap();
entMan.System<SharedMapSystem>().CreateMap(out var mapId);
var grid = mapMan.CreateGridEntity(mapId);
var gridEnt = grid.Owner;
var coordinates = new EntityCoordinates(gridEnt, new Vector2(10, 0));
@@ -67,7 +67,7 @@ namespace Robust.UnitTesting.Shared.Map
await server.WaitAssertion(() =>
{
var mapId = mapMan.CreateMap();
entMan.System<SharedMapSystem>().CreateMap(out var mapId);
var grid = mapMan.CreateGridEntity(mapId);
var gridEnt = grid.Owner;

View File

@@ -34,7 +34,7 @@ public sealed class GridSplit_Tests
var mapManager = sim.Resolve<IMapManager>();
var mapSystem = sim.Resolve<IEntityManager>().System<SharedMapSystem>();
var mapId = mapManager.CreateMap();
var mapId = sim.CreateMap().MapId;
var gridEnt = mapManager.CreateGridEntity(mapId);
var grid = gridEnt.Comp;
grid.CanSplit = false;
@@ -62,7 +62,7 @@ public sealed class GridSplit_Tests
var sim = GetSim();
var mapManager = sim.Resolve<IMapManager>();
var mapSystem = sim.Resolve<IEntityManager>().System<SharedMapSystem>();
var mapId = mapManager.CreateMap();
var mapId = sim.CreateMap().MapId;
var gridEnt = mapManager.CreateGridEntity(mapId);
for (var x = 0; x < 3; x++)
@@ -84,7 +84,7 @@ public sealed class GridSplit_Tests
var sim = GetSim();
var mapManager = sim.Resolve<IMapManager>();
var mapSystem = sim.Resolve<IEntityManager>().System<SharedMapSystem>();
var mapId = mapManager.CreateMap();
var mapId = sim.CreateMap().MapId;
var gridEnt = mapManager.CreateGridEntity(mapId);
for (var x = 0; x < 3; x++)
@@ -115,7 +115,7 @@ public sealed class GridSplit_Tests
var sim = GetSim();
var mapManager = sim.Resolve<IMapManager>();
var mapSystem = sim.Resolve<IEntityManager>().System<SharedMapSystem>();
var mapId = mapManager.CreateMap();
var mapId = sim.CreateMap().MapId;
var gridEnt = mapManager.CreateGridEntity(mapId);
for (var x = 0; x < 3; x++)
@@ -143,7 +143,7 @@ public sealed class GridSplit_Tests
var entManager = sim.Resolve<IEntityManager>();
var mapManager = sim.Resolve<IMapManager>();
var mapSystem = sim.Resolve<IEntityManager>().System<SharedMapSystem>();
var mapId = mapManager.CreateMap();
var mapId = sim.CreateMap().MapId;
var gridEnt = mapManager.CreateGridEntity(mapId);
var grid = gridEnt.Comp;

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