Warning fixes (#4160)

Co-authored-by: metalgearsloth <comedian_vs_clown@hotmail.com>
This commit is contained in:
Pieter-Jan Briers
2023-07-01 14:02:12 +02:00
committed by GitHub
parent b82d246988
commit e71f1cc8a5
56 changed files with 254 additions and 192 deletions

View File

@@ -39,7 +39,7 @@ END TEMPLATE-->
### New features
*None yet*
* `Robust.Shared.Physics.Events.CollisionChangeEvent` now has the `EntityUid` of the physics body.
### Bugfixes

View File

@@ -200,7 +200,7 @@ namespace Robust.Client
// Setup main loop
if (_mainLoop == null)
{
_mainLoop = new GameLoop(_gameTiming, _runtimeLog, _prof)
_mainLoop = new GameLoop(_gameTiming, _runtimeLog, _prof, _logManager.GetSawmill("eng"))
{
SleepMode = displayMode == DisplayMode.Headless ? SleepMode.Delay : SleepMode.None
};

View File

@@ -510,7 +510,7 @@ namespace Robust.Server
{
if (_mainLoop == null)
{
_mainLoop = new GameLoop(_time, _runtimeLog, _prof)
_mainLoop = new GameLoop(_time, _runtimeLog, _prof, _log.GetSawmill("eng"))
{
SleepMode = SleepMode.Delay,
DetectSoftLock = true,

View File

@@ -8,7 +8,7 @@ namespace Robust.Server.Containers
{
protected override void ValidateMissingEntity(EntityUid uid, IContainer cont, EntityUid missing)
{
Logger.Error($"Missing entity for container {ToPrettyString(uid)}. Missing uid: {missing}");
Log.Error($"Missing entity for container {ToPrettyString(uid)}. Missing uid: {missing}");
//cont.InternalRemove(ent);
}
}

View File

@@ -18,14 +18,18 @@ internal sealed partial class MetricsManager : IMetricsManager, IDisposable
{
[Dependency] private readonly IConfigurationManager _cfg = default!;
[Dependency] private readonly IEntitySystemManager _entitySystemManager = default!;
[Dependency] private readonly ILogManager _logManager = default!;
private bool _initialized;
private ManagedHttpListenerMetricsServer? _metricServer;
private IDisposable? _runtimeCollector;
private ISawmill _sawmill = default!;
public void Initialize()
{
_sawmill = _logManager.GetSawmill("metrics");
_initialized = true;
ValueChanged(CVars.MetricsEnabled);
@@ -58,7 +62,7 @@ internal sealed partial class MetricsManager : IMetricsManager, IDisposable
return;
}
Logger.InfoS("metrics", "Shutting down metrics.");
_sawmill.Info("Shutting down metrics.");
await _metricServer.StopAsync();
_metricServer = null;
_runtimeCollector?.Dispose();
@@ -92,14 +96,14 @@ internal sealed partial class MetricsManager : IMetricsManager, IDisposable
var host = _cfg.GetCVar(CVars.MetricsHost);
var port = _cfg.GetCVar(CVars.MetricsPort);
Logger.InfoS("metrics", "Prometheus metrics enabled, host: {1} port: {0}", port, host);
_sawmill.Info("Prometheus metrics enabled, host: {1} port: {0}", port, host);
var sawmill = Logger.GetSawmill("metrics.server");
_metricServer = new ManagedHttpListenerMetricsServer(sawmill, host, port);
_metricServer.Start();
if (_cfg.GetCVar(CVars.MetricsRuntime))
{
Logger.DebugS("metrics", "Enabling runtime metrics");
_sawmill.Debug("Enabling runtime metrics");
_runtimeCollector = BuildRuntimeStats().StartCollecting();
}
}

View File

@@ -3,6 +3,7 @@ using System.Linq;
using JetBrains.Annotations;
using Robust.Shared.Audio;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Map;
using Robust.Shared.Player;
using Robust.Shared.Players;
@@ -11,6 +12,9 @@ namespace Robust.Server.GameObjects;
[UsedImplicitly]
public sealed class AudioSystem : SharedAudioSystem
{
[Dependency] private readonly TransformSystem _transform = default!;
private uint _streamIndex;
private sealed class AudioSourceServer : IPlayingAudioStream
@@ -99,7 +103,7 @@ public sealed class AudioSystem : SharedAudioSystem
{
var id = CacheIdentifier();
var fallbackCoordinates = GetFallbackCoordinates(coordinates.ToMap(EntityManager));
var fallbackCoordinates = GetFallbackCoordinates(coordinates.ToMap(EntityManager, _transform));
var msg = new PlayAudioPositionalMessage
{

View File

@@ -807,7 +807,7 @@ public sealed class MapLoaderSystem : EntitySystem
if (xformQuery.TryGetComponent(rootEntity, out var xform) && IsRoot(xform, mapQuery) && !HasComp<MapComponent>(rootEntity))
{
xform.LocalPosition = data.Options.TransformMatrix.Transform(xform.LocalPosition);
_transform.SetLocalPosition(xform, data.Options.TransformMatrix.Transform(xform.LocalPosition));
xform.LocalRotation += data.Options.Rotation;
}
}
@@ -1143,7 +1143,7 @@ public sealed class MapLoaderSystem : EntitySystem
var xform = Transform(entityUid);
if (xform.NoLocalRotation && xform.LocalRotation != 0)
{
Logger.Error($"Encountered a no-rotation entity with non-zero local rotation: {ToPrettyString(entityUid)}");
Log.Error($"Encountered a no-rotation entity with non-zero local rotation: {ToPrettyString(entityUid)}");
xform._localRotation = 0;
}

View File

@@ -1,6 +1,6 @@
using System.Collections.Generic;
using System.Linq;
using Robust.Shared;
using Robust.Shared.Collections;
using Robust.Shared.Configuration;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
@@ -36,17 +36,18 @@ namespace Robust.Server.GameObjects
// If we have any existing empty ones then cull them on setting the cvar
if (_deleteEmptyGrids)
{
var toDelete = new List<MapGridComponent>();
var toDelete = new ValueList<EntityUid>();
foreach (var grid in MapManager.GetAllGrids())
var query = AllEntityQuery<MapGridComponent>();
while (query.MoveNext(out var uid, out var grid))
{
if (!GridEmpty(grid)) continue;
toDelete.Add(grid);
toDelete.Add(uid);
}
foreach (var grid in toDelete)
foreach (var uid in toDelete)
{
MapManager.DeleteGrid(grid.Owner);
MapManager.DeleteGrid(uid);
}
}
}

View File

@@ -7,7 +7,6 @@ using Robust.Server.Player;
using Robust.Shared.Enums;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Log;
using Robust.Shared.Utility;
namespace Robust.Server.GameObjects
@@ -61,7 +60,7 @@ namespace Robust.Server.GameObjects
foreach (var bui in activeUis.Interfaces)
{
DeactivateInterface(bui, activeUis);
DeactivateInterface(uid, bui, activeUis);
}
}
@@ -76,13 +75,13 @@ namespace Robust.Server.GameObjects
if (!uiComp._interfaces.TryGetValue(msg.UiKey, out var ui))
{
Logger.DebugS("go.comp.ui", "Got BoundInterfaceMessageWrapMessage for unknown UI key: {0}", msg.UiKey);
Log.Debug("Got BoundInterfaceMessageWrapMessage for unknown UI key: {0}", msg.UiKey);
return;
}
if (!ui.SubscribedSessions.Contains(session))
{
Logger.DebugS("go.comp.ui", $"UI {msg.UiKey} got BoundInterfaceMessageWrapMessage from a client who was not subscribed: {session}", msg.UiKey);
Log.Debug($"UI {msg.UiKey} got BoundInterfaceMessageWrapMessage from a client who was not subscribed: {session}", msg.UiKey);
return;
}
@@ -182,14 +181,15 @@ namespace Robust.Server.GameObjects
}
}
private void DeactivateInterface(BoundUserInterface ui, ActiveUserInterfaceComponent? activeUis = null)
private void DeactivateInterface(EntityUid entityUid, BoundUserInterface ui,
ActiveUserInterfaceComponent? activeUis = null)
{
if (!Resolve(ui.Component.Owner, ref activeUis, false))
if (!Resolve(entityUid, ref activeUis, false))
return;
activeUis.Interfaces.Remove(ui);
if (activeUis.Interfaces.Count == 0)
RemCompDeferred(activeUis.Owner, activeUis);
RemCompDeferred(entityUid, activeUis);
}
private void ActivateInterface(BoundUserInterface ui)
@@ -404,7 +404,7 @@ namespace Robust.Server.GameObjects
RaiseLocalEvent(owner, new BoundUIClosedEvent(bui.UiKey, owner, session));
if (bui._subscribedSessions.Count == 0)
DeactivateInterface(bui, activeUis);
DeactivateInterface(bui.Component.Owner, bui, activeUis);
}
/// <summary>

View File

@@ -1,12 +1,13 @@
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Log;
using Robust.Shared.Reflection;
namespace Robust.Server.GameObjects;
internal sealed class ServerComponentFactory : ComponentFactory
{
public ServerComponentFactory(IDynamicTypeFactoryInternal typeFactory, IReflectionManager reflectionManager) : base(typeFactory, reflectionManager)
public ServerComponentFactory(IDynamicTypeFactoryInternal typeFactory, IReflectionManager reflectionManager, ILogManager logManager) : base(typeFactory, reflectionManager, logManager)
{
RegisterIgnore("Input");
RegisterIgnore("AnimationPlayer");

View File

@@ -40,10 +40,14 @@ namespace Robust.Server.GameObjects
[Dependency] private readonly IRuntimeLog _runtimeLog = default!;
#endif
private ISawmill _netEntSawmill = default!;
protected override int NextEntityUid { get; set; } = (int) EntityUid.FirstUid;
public override void Initialize()
{
_netEntSawmill = LogManager.GetSawmill("net.ent");
SetupNetworking();
ReceivedSystemMessage += (_, systemMsg) => EventBus.RaiseEvent(EventSource.Network, systemMsg);
@@ -199,7 +203,7 @@ namespace Robust.Server.GameObjects
{
if (msgT < cT && _logLateMsgs)
{
Logger.WarningS("net.ent", "Got late MsgEntity! Diff: {0}, msgT: {2}, cT: {3}, player: {1}",
_netEntSawmill.Warning("Got late MsgEntity! Diff: {0}, msgT: {2}, cT: {3}, player: {1}",
(int) msgT.Value - (int) cT.Value, message.MsgChannel.UserName, msgT, cT);
}

View File

@@ -1208,7 +1208,7 @@ internal sealed partial class PvsSystem : EntitySystem
private (Vector2 worldPos, float range, MapId mapId) CalcViewBounds(in EntityUid euid, EntityQuery<TransformComponent> transformQuery)
{
var xform = transformQuery.GetComponent(euid);
return (xform.WorldPosition, _viewSize / 2f, xform.MapID);
return (_transform.GetWorldPosition(xform, transformQuery), _viewSize / 2f, xform.MapID);
}
public sealed class TreePolicy<T> : PooledObjectPolicy<RobustTree<T>> where T : notnull

View File

@@ -26,6 +26,7 @@ namespace Robust.Server.Placement
[Dependency] private readonly IPrototypeManager _prototype = default!;
[Dependency] private readonly IServerEntityManager _entityManager = default!;
[Dependency] private readonly IMapManager _mapManager = default!;
[Dependency] private readonly ILogManager _logManager = default!;
//TO-DO: Expand for multiple permission per mob?
// Add support for multi-use placeables (tiles etc.).
@@ -35,10 +36,14 @@ namespace Robust.Server.Placement
public Func<MsgPlacement, bool>? AllowPlacementFunc { get; set; }
private ISawmill _sawmill = default!;
#region IPlacementManager Members
public void Initialize()
{
_sawmill = _logManager.GetSawmill("placement");
_networkManager.RegisterNetMessage<MsgPlacement>(HandleNetMessage);
}
@@ -96,8 +101,7 @@ namespace Robust.Server.Placement
if (!coordinates.IsValid(_entityManager))
{
Logger.WarningS("placement",
$"{session} tried to place {msg.ObjType} at invalid coordinate {coordinates}");
_sawmill.Warning($"{session} tried to place {msg.ObjType} at invalid coordinate {coordinates}");
return;
}

View File

@@ -45,7 +45,7 @@ namespace Robust.Server.Prototypes
ReloadPrototypes(msg.Paths);
Logger.Info($"Reloaded prototypes in {sw.ElapsedMilliseconds} ms");
Sawmill.Info($"Reloaded prototypes in {sw.ElapsedMilliseconds} ms");
#endif
}

View File

@@ -36,12 +36,17 @@ namespace Robust.Server.Scripting
[Dependency] private readonly IPlayerManager _playerManager = default!;
[Dependency] private readonly IReflectionManager _reflectionManager = default!;
[Dependency] private readonly IDependencyCollection _dependencyCollection = default!;
[Dependency] private readonly ILogManager _logManager = default!;
readonly Dictionary<IPlayerSession, Dictionary<int, ScriptInstance>> _instances =
new();
private ISawmill _sawmill = default!;
public void Initialize()
{
_sawmill = _logManager.GetSawmill("script");
_netManager.RegisterNetMessage<MsgScriptStop>(ReceiveScriptEnd);
_netManager.RegisterNetMessage<MsgScriptEval>(ReceiveScriptEval);
_netManager.RegisterNetMessage<MsgScriptStart>(ReceiveScriptStart);
@@ -87,7 +92,7 @@ namespace Robust.Server.Scripting
if (!_conGroupController.CanScript(session))
{
Logger.WarningS("script", "Client {0} tried to access Scripting without permissions.", session);
_sawmill.Warning("Client {0} tried to access Scripting without permissions.", session);
_netManager.ServerSendMessage(reply, message.MsgChannel);
return;
}
@@ -119,7 +124,7 @@ namespace Robust.Server.Scripting
if (!_conGroupController.CanScript(session))
{
Logger.WarningS("script", "Client {0} tried to access Scripting without permissions.", session);
_sawmill.Warning("Client {0} tried to access Scripting without permissions.", session);
return;
}
@@ -252,7 +257,7 @@ namespace Robust.Server.Scripting
if (!_conGroupController.CanScript(session))
{
Logger.WarningS("script", "Client {0} tried to access Scripting without permissions.", session);
_sawmill.Warning("Client {0} tried to access Scripting without permissions.", session);
return;
}

View File

@@ -156,7 +156,7 @@ namespace Robust.Server.ServerStatus
}
catch (HttpRequestException e)
{
Logger.WarningS("watchdogApi", "Failed to send ping to watchdog:\n{0}", e);
_sawmill.Warning("Failed to send ping to watchdog:\n{0}", e);
}
}

View File

@@ -15,10 +15,16 @@ public sealed class GamePrototypeLoadManager : SharedPrototypeLoadManager
[Dependency] private readonly IServerNetManager _netManager = default!;
[Dependency] private readonly IPlayerManager _playerManager = default!;
[Dependency] private readonly IConGroupController _controller = default!;
[Dependency] private readonly ILogManager _logManager = default!;
private ISawmill _sawmill = default!;
public override void Initialize()
{
base.Initialize();
_sawmill = _logManager.GetSawmill("adminbus");
_netManager.Connected += NetManagerOnConnected;
}
@@ -36,7 +42,7 @@ public sealed class GamePrototypeLoadManager : SharedPrototypeLoadManager
{
base.LoadPrototypeData(message);
_netManager.ServerSendToAll(message); // everyone load it up!
Logger.InfoS("adminbus", $"Loaded adminbus prototype data from {player.Name}.");
_sawmill.Info($"Loaded adminbus prototype data from {player.Name}.");
}
else
{

View File

@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Text;
using JetBrains.Annotations;
@@ -48,12 +47,7 @@ namespace Robust.Shared.Scripting
public EntityCoordinates gpos(double x, double y, EntityUid gridId)
{
if (!map.TryGetGrid(gridId, out var grid))
{
return new EntityCoordinates(EntityUid.Invalid, ((float) x, (float) y));
}
return new EntityCoordinates(grid.Owner, ((float) x, (float) y));
return new EntityCoordinates(gridId, ((float) x, (float) y));
}
public EntityUid eid(int i)
@@ -168,7 +162,7 @@ namespace Robust.Shared.Scripting
#region EntityManager proxy methods
public T Comp<T>(EntityUid uid)
=> ent.GetComponent<T>(uid);
public bool TryComp<T>(EntityUid uid, out T? comp)
=> ent.TryGetComponent(uid, out comp);
@@ -195,7 +189,7 @@ namespace Robust.Shared.Scripting
public EntityPrototype? Prototype(EntityUid uid)
=> ent.GetComponent<MetaDataComponent>(uid).EntityPrototype;
public EntityStringRepresentation ToPrettyString(EntityUid uid)
=> ent.ToPrettyString(uid);

View File

@@ -80,7 +80,7 @@ namespace Robust.Shared.Configuration
catch (Exception e)
{
loaded.Clear();
Logger.WarningS("cfg", "Unable to load configuration from stream:\n{0}", e);
_sawmill.Warning("Unable to load configuration from stream:\n{0}", e);
}
return loaded;
@@ -130,12 +130,12 @@ namespace Robust.Shared.Configuration
using var file = File.OpenRead(configFile);
var result = LoadFromTomlStream(file);
_configFile = configFile;
Logger.InfoS("cfg", $"Configuration Loaded from '{Path.GetFullPath(configFile)}'");
_sawmill.Info($"Configuration Loaded from '{Path.GetFullPath(configFile)}'");
return result;
}
catch (Exception e)
{
Logger.WarningS("cfg", "Unable to load configuration file:\n{0}", e);
_sawmill.Warning("Unable to load configuration file:\n{0}", e);
return new HashSet<string>(0);
}
}
@@ -182,8 +182,7 @@ namespace Robust.Shared.Configuration
if (value == null)
{
Logger.ErrorS("cfg",
$"CVar {name} has no value or default value, was the default value registered as null?");
_sawmill.Error($"CVar {name} has no value or default value, was the default value registered as null?");
continue;
}
@@ -229,7 +228,7 @@ namespace Robust.Shared.Configuration
table.Add(keyName, val);
break;
default:
Logger.WarningS("cfg", $"Cannot serialize '{name}', unsupported type.");
_sawmill.Warning($"Cannot serialize '{name}', unsupported type.");
break;
}
}
@@ -243,7 +242,7 @@ namespace Robust.Shared.Configuration
{
if (_configFile == null)
{
Logger.WarningS("cfg", "Cannot save the config file, because one was never loaded.");
_sawmill.Warning("Cannot save the config file, because one was never loaded.");
return;
}
@@ -262,11 +261,11 @@ namespace Robust.Shared.Configuration
memoryStream.Position = 0;
using var file = File.Create(_configFile);
memoryStream.CopyTo(file);
Logger.InfoS("cfg", $"config saved to '{_configFile}'.");
_sawmill.Info($"config saved to '{_configFile}'.");
}
catch (Exception e)
{
Logger.WarningS("cfg", $"Cannot save the config file '{_configFile}'.\n {e}");
_sawmill.Warning($"Cannot save the config file '{_configFile}'.\n {e}");
}
}
@@ -298,7 +297,7 @@ namespace Robust.Shared.Configuration
if (_configVars.TryGetValue(name, out var cVar))
{
if (cVar.Registered)
Logger.ErrorS("cfg", $"The variable '{name}' has already been registered.");
_sawmill.Error($"The variable '{name}' has already been registered.");
if (!type.IsEnum && cVar.Value != null && !type.IsAssignableFrom(cVar.Value.GetType()))
{
@@ -309,7 +308,7 @@ namespace Robust.Shared.Configuration
}
catch
{
Logger.Error($"TOML parsed cvar does not match registered cvar type. Name: {name}. Code Type: {type.Name}. Toml type: {cVar.Value.GetType().Name}");
_sawmill.Error($"TOML parsed cvar does not match registered cvar type. Name: {name}. Code Type: {type.Name}. Toml type: {cVar.Value.GetType().Name}");
return;
}
}

View File

@@ -83,7 +83,7 @@ internal sealed class TestLog : LocalizedCommands
var level = result;
Logger.LogS(level, name, message);
_logManager.GetSawmill(name).Log(level, message);
}
public override CompletionResult GetCompletion(IConsoleShell shell, string[] args)

View File

@@ -37,7 +37,7 @@ internal sealed class TeleportCommand : LocalizedCommands
var transform = _entityManager.GetComponent<TransformComponent>(entity);
var position = new Vector2(posX, posY);
transform.AttachToGridOrMap();
xformSystem.AttachToGridOrMap(entity, transform);
MapId mapId;
if (args.Length == 3 && int.TryParse(args[2], out var intMapId))
@@ -148,7 +148,7 @@ public sealed class TeleportToCommand : LocalizedCommands
{
if (args.Length == 0)
return CompletionResult.Empty;
var last = args[^1];
var users = _players.Sessions

View File

@@ -13,7 +13,7 @@ namespace Robust.Shared.ContentPack
{
internal sealed partial class AssemblyTypeChecker
{
private static SandboxConfig LoadConfig()
private static SandboxConfig LoadConfig(ISawmill sawmill)
{
using var stream = typeof(AssemblyTypeChecker).Assembly
.GetManifestResourceStream("Robust.Shared.ContentPack.Sandbox.yml")!;
@@ -22,13 +22,13 @@ namespace Robust.Shared.ContentPack
var cfg = new Deserializer().Deserialize<SandboxConfig>(new StreamReader(stream, Encoding.UTF8));
foreach (var typeCfg in cfg.Types.Values.SelectMany(p => p.Values))
{
ParseTypeConfig(typeCfg);
ParseTypeConfig(typeCfg, sawmill);
}
return cfg;
}
private static void ParseTypeConfig(TypeConfig cfg)
private static void ParseTypeConfig(TypeConfig cfg, ISawmill sawmill)
{
if (cfg.Methods != null)
{
@@ -41,7 +41,7 @@ namespace Robust.Shared.ContentPack
}
catch (ParseException e)
{
Logger.ErrorS("res.typecheck", $"Parse exception for '{m}': {e}");
sawmill.Error($"Parse exception for '{m}': {e}");
}
}
@@ -63,7 +63,7 @@ namespace Robust.Shared.ContentPack
}
catch (ParseException e)
{
Logger.ErrorS("res.typecheck", $"Parse exception for '{f}': {e}");
sawmill.Error($"Parse exception for '{f}': {e}");
}
}
@@ -78,7 +78,7 @@ namespace Robust.Shared.ContentPack
{
foreach (var nested in cfg.NestedTypes.Values)
{
ParseTypeConfig(nested);
ParseTypeConfig(nested, sawmill);
}
}
}

View File

@@ -56,7 +56,7 @@ namespace Robust.Shared.ContentPack
// Config is huge and YAML is slow so config loading is delayed.
// This means we can parallelize config loading with IL verification
// (first time we need the config is when we print verifier errors).
_config = Task.Run(LoadConfig);
_config = Task.Run(() => LoadConfig(sawmill));
}
private Resolver CreateResolver()

View File

@@ -9,9 +9,10 @@ using Robust.Shared.Timing;
namespace Robust.Shared.ContentPack
{
public abstract class BaseModLoader
internal abstract class BaseModLoader : IPostInjectInit
{
[Dependency] protected readonly IReflectionManager ReflectionManager = default!;
[Dependency] protected readonly ILogManager LogManager = default!;
[Dependency] private readonly IDependencyCollection _dependencies = default!;
private readonly List<ModuleTestingCallbacks> _testingCallbacks = new();
@@ -21,6 +22,8 @@ namespace Robust.Shared.ContentPack
/// </summary>
protected readonly List<ModInfo> Mods = new();
protected ISawmill Sawmill { get; private set; } = default!;
public IEnumerable<Assembly> LoadedModules => Mods.Select(p => p.GameAssembly);
public Assembly GetAssembly(string name)
@@ -82,7 +85,7 @@ namespace Robust.Shared.ContentPack
entry.PostInit();
break;
default:
Logger.ErrorS("res.mod", $"Unknown RunLevel: {level}");
Sawmill.Error($"Unknown RunLevel: {level}");
break;
}
}
@@ -121,6 +124,11 @@ namespace Robust.Shared.ContentPack
}
}
void IPostInjectInit.PostInject()
{
Sawmill = LogManager.GetSawmill("res.mod");
}
/// <summary>
/// Holds info about a loaded assembly.
/// </summary>

View File

@@ -11,7 +11,6 @@ using System.Runtime.Loader;
using System.Threading;
using System.Threading.Tasks;
using Robust.Shared.IoC;
using Robust.Shared.Log;
using Robust.Shared.Utility;
namespace Robust.Shared.ContentPack
@@ -19,10 +18,9 @@ namespace Robust.Shared.ContentPack
/// <summary>
/// Class for managing the loading of assemblies into the engine.
/// </summary>
internal sealed class ModLoader : BaseModLoader, IModLoaderInternal, IDisposable, IPostInjectInit
internal sealed class ModLoader : BaseModLoader, IModLoaderInternal, IDisposable
{
[Dependency] private readonly IResourceManagerInternal _res = default!;
[Dependency] private readonly ILogManager _logManager = default!;
// List of extra assemblies side-loaded from the /Assemblies/ mounted path.
private readonly List<Assembly> _sideModules = new();
@@ -39,8 +37,6 @@ namespace Robust.Shared.ContentPack
private readonly List<string> _engineModuleDirectories = new();
private readonly List<ExtraModuleLoad> _extraModuleLoads = new();
private ISawmill _sawmillResMod = default!;
public event ExtraModuleLoad ExtraModuleLoaders
{
add => _extraModuleLoads.Add(value);
@@ -57,21 +53,16 @@ namespace Robust.Shared.ContentPack
AssemblyLoadContext.Default.Resolving += DefaultOnResolving;
}
void IPostInjectInit.PostInject()
{
_sawmillResMod = _logManager.GetSawmill("res.mod");
}
public void SetUseLoadContext(bool useLoadContext)
{
_useLoadContext = useLoadContext;
Logger.DebugS("res", "{0} assembly load context", useLoadContext ? "ENABLING" : "DISABLING");
Sawmill.Debug("{0} assembly load context", useLoadContext ? "ENABLING" : "DISABLING");
}
public void SetEnableSandboxing(bool sandboxing)
{
_sandboxingEnabled = sandboxing;
Logger.DebugS("res", "{0} sandboxing", sandboxing ? "ENABLING" : "DISABLING");
Sawmill.Debug("{0} sandboxing", sandboxing ? "ENABLING" : "DISABLING");
}
public Func<string, Stream?>? VerifierExtraLoadHandler { get; set; }
@@ -90,7 +81,7 @@ namespace Robust.Shared.ContentPack
p.Extension == "dll"))
{
var fullPath = mountPath / filePath;
_sawmillResMod.Debug($"Found module '{fullPath}'");
Sawmill.Debug($"Found module '{fullPath}'");
paths.Add(fullPath);
}
@@ -101,7 +92,7 @@ namespace Robust.Shared.ContentPack
public bool TryLoadModules(IEnumerable<ResPath> paths)
{
var sw = Stopwatch.StartNew();
Logger.DebugS("res.mod", "LOADING modules");
Sawmill.Debug("LOADING modules");
var files = new Dictionary<string, (ResPath Path, string[] references)>();
// Find all modules we want to load.
@@ -116,8 +107,8 @@ namespace Robust.Shared.ContentPack
if (!files.TryAdd(asmName, (fullPath, asmRefs)))
{
Logger.ErrorS("res.mod", "Found multiple modules with the same assembly name " +
$"'{asmName}', A: {files[asmName].Path}, B: {fullPath}.");
Sawmill.Error("Found multiple modules with the same assembly name " +
$"'{asmName}', A: {files[asmName].Path}, B: {fullPath}.");
return false;
}
}
@@ -139,7 +130,7 @@ namespace Robust.Shared.ContentPack
}
});
Logger.DebugS("res.mod", $"Verified assemblies in {checkerSw.ElapsedMilliseconds}ms");
Sawmill.Debug($"Verified assemblies in {checkerSw.ElapsedMilliseconds}ms");
}
var nodes = TopologicalSort.FromBeforeAfter(
@@ -153,7 +144,7 @@ namespace Robust.Shared.ContentPack
// Actually load them in the order they depend on each other.
foreach (var path in TopologicalSort.Sort(nodes))
{
Logger.DebugS("res.mod", $"Loading module: '{path}'");
Sawmill.Debug($"Loading module: '{path}'");
try
{
// If possible, load from disk path instead.
@@ -171,11 +162,11 @@ namespace Robust.Shared.ContentPack
}
catch (Exception e)
{
Logger.ErrorS("srv", $"Exception loading module '{path}':\n{e.ToStringBetter()}");
Sawmill.Error($"Exception loading module '{path}':\n{e.ToStringBetter()}");
return false;
}
}
Logger.DebugS("res.mod", $"DONE loading modules: {sw.Elapsed}");
Sawmill.Debug($"DONE loading modules: {sw.Elapsed}");
return true;
}
@@ -191,7 +182,7 @@ namespace Robust.Shared.ContentPack
if (_sandboxingEnabled && TryFindSkipIfSandboxed(metaReader))
{
Logger.DebugS("res.mod", "Module {ModuleName} has SkipIfSandboxedAttribute, ignoring.", name);
Sawmill.Debug("Module {ModuleName} has SkipIfSandboxedAttribute, ignoring.", name);
return null;
}
@@ -270,7 +261,7 @@ namespace Robust.Shared.ContentPack
// To prevent breaking debugging on Rider, try to load from disk if possible.
if (_res.TryGetDiskFilePath(dllPath, out var path))
{
Logger.DebugS("srv", $"Loading {assemblyName} DLL");
Sawmill.Debug( $"Loading {assemblyName} DLL");
try
{
LoadGameAssembly(path, skipVerify: false);
@@ -278,7 +269,7 @@ namespace Robust.Shared.ContentPack
}
catch (Exception e)
{
Logger.ErrorS("srv", $"Exception loading DLL {assemblyName}.dll: {e.ToStringBetter()}");
Sawmill.Error($"Exception loading DLL {assemblyName}.dll: {e.ToStringBetter()}");
return false;
}
}
@@ -287,7 +278,7 @@ namespace Robust.Shared.ContentPack
{
using (gameDll)
{
Logger.DebugS("srv", $"Loading {assemblyName} DLL");
Sawmill.Debug($"Loading {assemblyName} DLL");
// see if debug info is present
if (_res.TryContentFileRead(new ResPath($@"/Assemblies/{assemblyName}.pdb"),
@@ -303,7 +294,7 @@ namespace Robust.Shared.ContentPack
}
catch (Exception e)
{
Logger.ErrorS("srv", $"Exception loading DLL {assemblyName}.dll: {e.ToStringBetter()}");
Sawmill.Error($"Exception loading DLL {assemblyName}.dll: {e.ToStringBetter()}");
return false;
}
}
@@ -317,13 +308,13 @@ namespace Robust.Shared.ContentPack
}
catch (Exception e)
{
Logger.ErrorS("srv", $"Exception loading DLL {assemblyName}.dll: {e.ToStringBetter()}");
Sawmill.Error($"Exception loading DLL {assemblyName}.dll: {e.ToStringBetter()}");
return false;
}
}
}
Logger.WarningS("eng", $"Could not load {assemblyName} DLL: {dllPath} does not exist in the VFS.");
Sawmill.Warning($"Could not load {assemblyName} DLL: {dllPath} does not exist in the VFS.");
return false;
}
@@ -333,7 +324,7 @@ namespace Robust.Shared.ContentPack
{
lock (_lock)
{
_logManager.GetSawmill("res").Debug("ResolvingAssembly {0}", name);
Sawmill.Debug("ResolvingAssembly {0}", name);
// Try main modules.
foreach (var mod in Mods)
@@ -372,7 +363,7 @@ namespace Robust.Shared.ContentPack
}
catch (Exception e)
{
_logManager.GetSawmill("res").Error("Exception in ResolvingAssembly: {0}", e);
Sawmill.Error("Exception in ResolvingAssembly: {0}", e);
ExceptionDispatchInfo.Capture(e).Throw();
throw null; // Unreachable.
}
@@ -389,7 +380,7 @@ namespace Robust.Shared.ContentPack
// Otherwise it would load the assemblies a second time which is an amazing way to have everything break.
if (_useLoadContext)
{
_logManager.GetSawmill("res.mod").Debug($"RESOLVING DEFAULT: {name}");
Sawmill.Debug($"RESOLVING DEFAULT: {name}");
foreach (var module in LoadedModules)
{
if (module.GetName().Name == name.Name)
@@ -426,7 +417,7 @@ namespace Robust.Shared.ContentPack
private AssemblyTypeChecker MakeTypeChecker()
{
return new(_res, Logger.GetSawmill("res.typecheck"))
return new(_res, LogManager.GetSawmill("res.typecheck"))
{
VerifyIL = _sandboxingEnabled,
DisableTypeCheck = !_sandboxingEnabled,

View File

@@ -15,6 +15,7 @@ namespace Robust.Shared.ContentPack
sealed class PackLoader : IContentRoot
{
private readonly FileInfo? _pack;
private readonly ISawmill _sawmill;
private readonly Stream? _stream;
private ZipArchive _zip = default!;
@@ -22,14 +23,17 @@ namespace Robust.Shared.ContentPack
/// Constructor.
/// </summary>
/// <param name="pack">The zip file to mount in the VFS.</param>
public PackLoader(FileInfo pack)
/// <param name="sawmill">Sawmill to use for logging.</param>
public PackLoader(FileInfo pack, ISawmill sawmill)
{
_pack = pack;
_sawmill = sawmill;
}
public PackLoader(Stream stream)
public PackLoader(Stream stream, ISawmill sawmill)
{
_stream = stream;
_sawmill = sawmill;
}
/// <inheritdoc />
@@ -37,7 +41,7 @@ namespace Robust.Shared.ContentPack
{
if (_pack != null)
{
Logger.InfoS("res", $"Loading ContentPack: {_pack.FullName}...");
_sawmill.Info($"Loading ContentPack: {_pack.FullName}...");
_zip = ZipFile.OpenRead(_pack.FullName);
}

View File

@@ -17,6 +17,7 @@ namespace Robust.Shared.ContentPack
internal partial class ResourceManager : IResourceManagerInternal
{
[Dependency] private readonly IConfigurationManager _config = default!;
[Dependency] private readonly ILogManager _logManager = default!;
private (ResPath prefix, IContentRoot root)[] _contentRoots =
new (ResPath prefix, IContentRoot root)[0];
@@ -32,12 +33,16 @@ namespace Robust.Shared.ContentPack
private static readonly Regex BadPathCharacterRegex =
new("[<>:\"|?*\0\\x01-\\x1f]", RegexOptions.IgnoreCase);
private ISawmill _sawmill = default!;
/// <inheritdoc />
public IWritableDirProvider UserData { get; private set; } = default!;
/// <inheritdoc />
public void Initialize(string? userData)
{
_sawmill = _logManager.GetSawmill("res");
if (userData != null)
{
UserData = new WritableDirProvider(Directory.CreateDirectory(userData));
@@ -60,7 +65,7 @@ namespace Robust.Shared.ContentPack
// no pack in config
if (string.IsNullOrWhiteSpace(zipPath))
{
Logger.WarningS("res", "No default ContentPack to load in configuration.");
_sawmill.Warning("No default ContentPack to load in configuration.");
return;
}
@@ -84,7 +89,7 @@ namespace Robust.Shared.ContentPack
//create new PackLoader
var loader = new PackLoader(packInfo);
var loader = new PackLoader(packInfo, _sawmill);
AddRoot(prefix.Value, loader);
}
@@ -92,7 +97,7 @@ namespace Robust.Shared.ContentPack
{
prefix = SanitizePrefix(prefix);
var loader = new PackLoader(zipStream);
var loader = new PackLoader(zipStream, _sawmill);
AddRoot(prefix.Value, loader);
}
@@ -140,7 +145,7 @@ namespace Robust.Shared.ContentPack
throw new DirectoryNotFoundException("Specified directory does not exist: " + pathInfo.FullName);
}
var loader = new DirLoader(pathInfo, Logger.GetSawmill("res"), _config.GetCVar(CVars.ResCheckPathCasing));
var loader = new DirLoader(pathInfo, _logManager.GetSawmill("res"), _config.GetCVar(CVars.ResCheckPathCasing));
AddRoot(prefix.Value, loader);
}

View File

@@ -4,13 +4,17 @@ using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using Robust.Shared.IoC;
using Robust.Shared.Log;
namespace Robust.Shared.Exceptions
{
internal sealed class RuntimeLog : IRuntimeLog
internal sealed class RuntimeLog : IRuntimeLog, IPostInjectInit
{
[Dependency] private readonly ILogManager _logManager = default!;
private readonly Dictionary<Type, List<LoggedException>> exceptions = new();
private ISawmill _sawmill = default!;
public int ExceptionCount => exceptions.Values.Sum(l => l.Count);
@@ -26,11 +30,11 @@ namespace Robust.Shared.Exceptions
if (catcher != null)
{
Logger.ErrorS("runtime", exception, "Caught exception in {Catcher}", catcher);
_sawmill.Log(LogLevel.Error, exception, "Caught exception in {Catcher}", catcher);
}
else
{
Logger.ErrorS("runtime", exception, "Caught exception");
_sawmill.Log(LogLevel.Error, exception, "Caught exception");
}
}
@@ -64,6 +68,11 @@ namespace Robust.Shared.Exceptions
return ret.ToString();
}
void IPostInjectInit.PostInject()
{
_sawmill = _logManager.GetSawmill("runtime");
}
private sealed class LoggedException
{
public Exception Exception { get; }

View File

@@ -17,6 +17,7 @@ namespace Robust.Shared.GameObjects
{
private readonly IDynamicTypeFactoryInternal _typeFactory;
private readonly IReflectionManager _reflectionManager;
private readonly ISawmill _sawmill;
// Bunch of dictionaries to allow lookups in all directions.
/// <summary>
@@ -71,10 +72,11 @@ namespace Robust.Shared.GameObjects
private IEnumerable<ComponentRegistration> AllRegistrations => types.Values;
public ComponentFactory(IDynamicTypeFactoryInternal typeFactory, IReflectionManager reflectionManager)
public ComponentFactory(IDynamicTypeFactoryInternal typeFactory, IReflectionManager reflectionManager, ILogManager logManager)
{
_typeFactory = typeFactory;
_reflectionManager = reflectionManager;
_sawmill = logManager.GetSawmill("ent.componentFactory");
}
private void Register(Type type, bool overwrite = false)
@@ -435,21 +437,23 @@ namespace Robust.Shared.GameObjects
{
if (!typeof(IComponent).IsAssignableFrom(type))
{
Logger.Error("Type {0} has RegisterComponentAttribute but does not implement IComponent.", type);
_sawmill.Error("Type {0} has RegisterComponentAttribute but does not implement IComponent.", type);
return;
}
Register(type);
#pragma warning disable CS0618
foreach (var attribute in Attribute.GetCustomAttributes(type, typeof(ComponentReferenceAttribute)))
{
var cast = (ComponentReferenceAttribute) attribute;
#pragma warning restore CS0618
var refType = cast.ReferenceType;
if (!refType.IsAssignableFrom(type))
{
Logger.Error("Type {0} has reference for type it does not implement: {1}.", type, refType);
_sawmill.Error("Type {0} has reference for type it does not implement: {1}.", type, refType);
continue;
}

View File

@@ -308,7 +308,7 @@ public sealed partial class EntityLookupSystem
float arcWidth,
LookupFlags flags = DefaultFlags)
{
var position = coordinates.ToMap(EntityManager);
var position = coordinates.ToMap(EntityManager, _transform);
return GetEntitiesInArc(position, range, direction, arcWidth, flags);
}
@@ -324,7 +324,7 @@ public sealed partial class EntityLookupSystem
foreach (var entity in GetEntitiesInRange(coordinates, range * 2, flags))
{
var angle = new Angle(xformQuery.GetComponent(entity).WorldPosition - coordinates.Position);
var angle = new Angle(_transform.GetWorldPosition(entity, xformQuery) - coordinates.Position);
if (angle.Degrees < direction.Degrees + arcWidth / 2 &&
angle.Degrees > direction.Degrees - arcWidth / 2)
yield return entity;
@@ -508,7 +508,7 @@ public sealed partial class EntityLookupSystem
{
if (!coordinates.IsValid(EntityManager)) return false;
var mapPos = coordinates.ToMap(EntityManager);
var mapPos = coordinates.ToMap(EntityManager, _transform);
return AnyEntitiesIntersecting(mapPos, flags);
}
@@ -516,19 +516,19 @@ public sealed partial class EntityLookupSystem
{
if (!coordinates.IsValid(EntityManager)) return false;
var mapPos = coordinates.ToMap(EntityManager);
var mapPos = coordinates.ToMap(EntityManager, _transform);
return AnyEntitiesInRange(mapPos, range, flags);
}
public HashSet<EntityUid> GetEntitiesIntersecting(EntityCoordinates coordinates, LookupFlags flags = DefaultFlags)
{
var mapPos = coordinates.ToMap(EntityManager);
var mapPos = coordinates.ToMap(EntityManager, _transform);
return GetEntitiesIntersecting(mapPos, flags);
}
public HashSet<EntityUid> GetEntitiesInRange(EntityCoordinates coordinates, float range, LookupFlags flags = DefaultFlags)
{
var mapPos = coordinates.ToMap(EntityManager);
var mapPos = coordinates.ToMap(EntityManager, _transform);
return GetEntitiesInRange(mapPos, range, flags);
}
@@ -594,7 +594,7 @@ public sealed partial class EntityLookupSystem
// Technically this doesn't consider anything overlapping from outside the grid but is this an issue?
if (!_mapManager.TryGetGrid(gridId, out var grid)) return new HashSet<EntityUid>();
var lookup = Comp<BroadphaseComponent>(grid.Owner);
var lookup = Comp<BroadphaseComponent>(gridId);
var intersecting = new HashSet<EntityUid>();
var tileSize = grid.TileSize;
@@ -650,7 +650,7 @@ public sealed partial class EntityLookupSystem
{
// Technically this doesn't consider anything overlapping from outside the grid but is this an issue?
if (!_mapManager.TryGetGrid(gridId, out var grid)) return new HashSet<EntityUid>();
var lookup = Comp<BroadphaseComponent>(grid.Owner);
var lookup = Comp<BroadphaseComponent>(gridId);
var tileSize = grid.TileSize;
var aabb = GetLocalBounds(gridIndices, tileSize);
return GetEntitiesIntersecting(lookup, aabb, flags);
@@ -708,7 +708,7 @@ public sealed partial class EntityLookupSystem
public HashSet<EntityUid> GetEntitiesIntersecting(EntityUid gridId, Box2 worldAABB, LookupFlags flags = DefaultFlags)
{
if (!_mapManager.TryGetGrid(gridId, out var grid)) return new HashSet<EntityUid>();
if (!_mapManager.GridExists(gridId)) return new HashSet<EntityUid>();
var lookupQuery = GetEntityQuery<BroadphaseComponent>();
var xformQuery = GetEntityQuery<TransformComponent>();
@@ -722,13 +722,13 @@ public sealed partial class EntityLookupSystem
public HashSet<EntityUid> GetEntitiesIntersecting(EntityUid gridId, Box2Rotated worldBounds, LookupFlags flags = DefaultFlags)
{
if (!_mapManager.TryGetGrid(gridId, out var grid)) return new HashSet<EntityUid>();
if (!_mapManager.GridExists(gridId)) return new HashSet<EntityUid>();
var lookupQuery = GetEntityQuery<BroadphaseComponent>();
var xformQuery = GetEntityQuery<TransformComponent>();
var intersecting = new HashSet<EntityUid>();
AddEntitiesIntersecting(grid.Owner, intersecting, worldBounds, flags, lookupQuery, xformQuery);
AddEntitiesIntersecting(gridId, intersecting, worldBounds, flags, lookupQuery, xformQuery);
AddContained(intersecting, flags, xformQuery);
return intersecting;
@@ -897,7 +897,7 @@ public sealed partial class EntityLookupSystem
if (worldMatrix == null || angle == null)
{
var gridXform = Transform(grid.Owner);
var gridXform = Transform(tileRef.GridUid);
var (_, wAng, wMat) = gridXform.GetWorldPositionRotationMatrix();
worldMatrix = wMat;
angle = wAng;

View File

@@ -281,7 +281,7 @@ public sealed partial class EntityLookupSystem
public HashSet<T> GetComponentsInRange<T>(EntityCoordinates coordinates, float range) where T : Component
{
var mapPos = coordinates.ToMap(EntityManager);
var mapPos = coordinates.ToMap(EntityManager, _transform);
return GetComponentsInRange<T>(mapPos, range);
}
#endregion

View File

@@ -177,9 +177,9 @@ namespace Robust.Shared.GameObjects
component.DynamicTree = new DynamicTreeBroadPhase();
component.StaticTree = new DynamicTreeBroadPhase();
component.StaticSundriesTree = new DynamicTree<EntityUid>(
(in EntityUid value) => GetTreeAABB(value, component.Owner));
(in EntityUid value) => GetTreeAABB(value, uid));
component.SundriesTree = new DynamicTree<EntityUid>(
(in EntityUid value) => GetTreeAABB(value, component.Owner));
(in EntityUid value) => GetTreeAABB(value, uid));
}
private Box2 GetTreeAABB(EntityUid entity, EntityUid tree)
@@ -188,7 +188,7 @@ namespace Robust.Shared.GameObjects
if (!xformQuery.TryGetComponent(entity, out var xform))
{
Logger.Error($"Entity tree contains a deleted entity? Tree: {ToPrettyString(tree)}, entity: {entity}");
Log.Error($"Entity tree contains a deleted entity? Tree: {ToPrettyString(tree)}, entity: {entity}");
return default;
}
@@ -197,11 +197,11 @@ namespace Robust.Shared.GameObjects
if (!xformQuery.TryGetComponent(tree, out var treeXform))
{
Logger.Error($"Entity tree has no transform? Tree Uid: {tree}");
Log.Error($"Entity tree has no transform? Tree Uid: {tree}");
return default;
}
return treeXform.InvWorldMatrix.TransformBox(GetWorldAABB(entity, xform));
return _transform.GetInvWorldMatrix(treeXform, xformQuery).TransformBox(GetWorldAABB(entity, xform));
}
internal void CreateProxies(EntityUid uid, TransformComponent xform, Fixture fixture, PhysicsComponent body)
@@ -216,7 +216,7 @@ namespace Robust.Shared.GameObjects
var (worldPos, worldRot) = _transform.GetWorldPositionRotation(xform, xformQuery);
var mapTransform = new Transform(worldPos, worldRot);
var (_, broadWorldRot, _, broadInvMatrix) = xformQuery.GetComponent(broadphase.Owner).GetWorldPositionRotationMatrixWithInv();
var (_, broadWorldRot, _, broadInvMatrix) = _transform.GetWorldPositionRotationMatrixWithInv(broadphase.Owner);
var broadphaseTransform = new Transform(broadInvMatrix.Transform(mapTransform.Position), mapTransform.Quaternion2D.Angle - broadWorldRot);
var tree = body.BodyType == BodyType.Static ? broadphase.StaticTree : broadphase.DynamicTree;
DebugTools.Assert(fixture.ProxyCount == 0);
@@ -234,7 +234,7 @@ namespace Robust.Shared.GameObjects
if (fixture.ProxyCount == 0)
{
Logger.Warning($"Tried to destroy fixture {fixture.ID} on {ToPrettyString(uid)} that already has no proxies?");
Log.Warning($"Tried to destroy fixture {fixture.ID} on {ToPrettyString(uid)} that already has no proxies?");
return;
}
@@ -248,8 +248,8 @@ namespace Robust.Shared.GameObjects
private void OnPhysicsUpdate(ref CollisionChangeEvent ev)
{
var xform = Transform(ev.Body.Owner);
UpdatePhysicsBroadphase(ev.Body.Owner, xform, ev.Body);
var xform = Transform(ev.BodyUid);
UpdatePhysicsBroadphase(ev.BodyUid, xform, ev.Body);
// ensure that the cached broadphase is correct.
DebugTools.Assert(_timing.ApplyingState
@@ -812,7 +812,7 @@ namespace Robust.Shared.GameObjects
if (old.PhysicsMap.IsValid() && physicsMap?.Owner != old.PhysicsMap)
{
if (!TryComp(old.PhysicsMap, out physicsMap))
Logger.Error($"Entity {ToPrettyString(uid)} has missing physics map?");
Log.Error($"Entity {ToPrettyString(uid)} has missing physics map?");
}
if (old.CanCollide)
@@ -978,7 +978,7 @@ namespace Robust.Shared.GameObjects
{
var xformQuery = GetEntityQuery<TransformComponent>();
xform ??= xformQuery.GetComponent(uid);
var (worldPos, worldRot) = xform.GetWorldPositionRotation(xformQuery);
var (worldPos, worldRot) = _transform.GetWorldPositionRotation(xform, xformQuery);
return GetAABB(uid, worldPos, worldRot, xform, xformQuery);
}

View File

@@ -141,7 +141,7 @@ public abstract class MetaDataSystem : EntitySystem
return;
var ev = new MetaFlagRemoveAttemptEvent(toRemove);
EntityManager.EventBus.RaiseLocalEvent(component.Owner, ref ev, true);
EntityManager.EventBus.RaiseLocalEvent(uid, ref ev, true);
component.Flags &= ~ev.ToRemove;
}

View File

@@ -31,7 +31,7 @@ public abstract class SharedAudioSystem : EntitySystem
switch (specifier)
{
case SoundPathSpecifier path:
return path.Path == null ? string.Empty : path.Path.ToString();
return path.Path == default ? string.Empty : path.Path.ToString();
case SoundCollectionSpecifier collection:
{

View File

@@ -134,12 +134,14 @@ namespace Robust.Shared.GameObjects
poly.Set(vertices, 4);
#pragma warning disable CS0618
var newFixture = new Fixture(
$"grid_chunk-{bounds.Left}-{bounds.Bottom}",
poly,
MapGridHelpers.CollisionGroup,
MapGridHelpers.CollisionGroup,
true) { Body = body};
#pragma warning restore CS0618
newFixtures.Add(newFixture);
}

View File

@@ -136,7 +136,7 @@ public abstract partial class SharedTransformSystem
//TODO: make grid components the actual grid
// I have NFI what the comment above is on about, but this doesn't seem good, so lets log an error if it happens.
Logger.Error($"Missing grid while unanchoring {ToPrettyString(uid)}");
Log.Error($"Missing grid while unanchoring {ToPrettyString(uid)}");
}
if (!xform.Running)
@@ -515,7 +515,7 @@ public abstract partial class SharedTransformSystem
// E.g., client is holding a foldable bed and predicts dropping & sitting in it -> reset to holding it -> bed is parent of player and vice versa.
// Even though its temporary, this can still cause the client to get stuck in infinite loops while applying the game state.
// So we will just break the loop by detaching to null and just trusting that the loop wasn't actually a real feature of the server state.
Logger.Warning($"Encountered circular transform hierarchy while applying state for entity: {ToPrettyString(uid)}. Detaching child to null: {ToPrettyString(recursiveUid)}");
Log.Warning($"Encountered circular transform hierarchy while applying state for entity: {ToPrettyString(uid)}. Detaching child to null: {ToPrettyString(recursiveUid)}");
DetachParentToNull(recursiveUid, recursiveXform);
break;
}
@@ -876,7 +876,7 @@ public abstract partial class SharedTransformSystem
}
// Entity was not actually in the transform hierarchy. This is probably a sign that something is wrong, or that the function is being misused.
Logger.Warning($"Target entity ({ToPrettyString(relative)}) not in transform hierarchy while calling {nameof(GetRelativePositionRotation)}.");
Log.Warning($"Target entity ({ToPrettyString(relative)}) not in transform hierarchy while calling {nameof(GetRelativePositionRotation)}.");
var relXform = query.GetComponent(relative);
pos = relXform.InvWorldMatrix.Transform(pos);
rot = rot - GetWorldRotation(relXform, query);
@@ -907,7 +907,7 @@ public abstract partial class SharedTransformSystem
}
// Entity was not actually in the transform hierarchy. This is probably a sign that something is wrong, or that the function is being misused.
Logger.Warning($"Target entity ({ToPrettyString(relative)}) not in transform hierarchy while calling {nameof(GetRelativePositionRotation)}.");
Log.Warning($"Target entity ({ToPrettyString(relative)}) not in transform hierarchy while calling {nameof(GetRelativePositionRotation)}.");
var relXform = query.GetComponent(relative);
pos = relXform.InvWorldMatrix.Transform(pos);
break;

View File

@@ -40,9 +40,7 @@ internal partial class MapManager : IMapManagerInternal, IEntityEventSubscriber
_dbgGuardRunning = true;
#endif
Logger.DebugS("map", "Starting...");
DebugTools.Assert(!GridExists(EntityUid.Invalid));
_sawmill.Debug("Starting...");
}
/// <inheritdoc />
@@ -51,23 +49,18 @@ internal partial class MapManager : IMapManagerInternal, IEntityEventSubscriber
#if DEBUG
DebugTools.Assert(_dbgGuardInit);
#endif
Logger.DebugS("map", "Stopping...");
_sawmill.Debug("Stopping...");
foreach (var mapComp in EntityManager.EntityQuery<MapComponent>())
{
EntityManager.DeleteEntity(mapComp.Owner);
}
#if DEBUG
DebugTools.Assert(!GridExists(EntityUid.Invalid));
_dbgGuardRunning = false;
#endif
}
/// <inheritdoc />
public void Restart()
{
Logger.DebugS("map", "Restarting...");
_sawmill.Debug("Restarting...");
// Don't just call Shutdown / Startup because we don't want to touch the subscriptions on gridtrees
// Restart can be called any time during a game, whereas shutdown / startup are typically called upon connection.

View File

@@ -245,6 +245,8 @@ namespace Robust.Shared.Network
throw new InvalidOperationException("NetManager has already been initialized.");
}
_strings.Sawmill = _logger;
HttpClientUserAgent.AddUserAgent(_httpClient);
SynchronizeNetTime();

View File

@@ -23,7 +23,7 @@ namespace Robust.Shared.Network
/// <summary>
/// Contains a networked mapping of IDs -> Strings.
/// </summary>
public sealed class StringTable
internal sealed class StringTable
{
/// <summary>
/// The ID of the <see cref="MsgStringTableEntries"/> packet.
@@ -38,6 +38,8 @@ namespace Robust.Shared.Network
private InitCallback? _callback;
private StringTableUpdateCallback? _updateCallback;
public ISawmill Sawmill = default!;
/// <summary>
/// Default constructor.
/// </summary>
@@ -72,7 +74,7 @@ namespace Robust.Shared.Network
{
DebugTools.Assert(_network.IsClient);
Logger.InfoS("net", $"Received message name string table.");
Sawmill.Info($"Received message name string table.");
foreach (var entry in message.Entries)
{
@@ -269,7 +271,7 @@ namespace Robust.Shared.Network
}
Logger.InfoS("net",$"Sending message name string table to {channel.RemoteEndPoint.Address}.");
Sawmill.Info($"Sending message name string table to {channel.RemoteEndPoint.Address}.");
_network.ServerSendMessage(message, channel);
}
}

View File

@@ -9,12 +9,15 @@ namespace Robust.Shared.Physics.Events
[ByRefEvent]
public readonly struct CollisionChangeEvent
{
public readonly EntityUid BodyUid;
public readonly PhysicsComponent Body;
public readonly bool CanCollide;
public CollisionChangeEvent(PhysicsComponent body, bool canCollide)
public CollisionChangeEvent(EntityUid bodyUid, PhysicsComponent body, bool canCollide)
{
BodyUid = bodyUid;
Body = body;
CanCollide = canCollide;
}

View File

@@ -174,7 +174,7 @@ namespace Robust.Shared.Physics.Systems
if (!manager.Fixtures.Remove(fixture.ID))
{
Logger.ErrorS("fixtures", $"Tried to remove fixture from {ToPrettyString(uid)} that was already removed.");
Log.Error($"Tried to remove fixture from {ToPrettyString(uid)} that was already removed.");
return;
}
@@ -214,7 +214,9 @@ namespace Robust.Shared.Physics.Systems
throw new InvalidOperationException($"Tried to setup fixture on init for {ToPrettyString(uid)} with no ID!");
}
#pragma warning disable CS0618
fixture.Body = body;
#pragma warning restore CS0618
}
// Make sure all the right stuff is set on the body
@@ -236,7 +238,7 @@ namespace Robust.Shared.Physics.Systems
if (!EntityManager.TryGetComponent(uid, out PhysicsComponent? physics))
{
Logger.ErrorS("physics", $"Tried to apply fixture state for an entity without physics: {ToPrettyString(uid)}");
Log.Error($"Tried to apply fixture state for an entity without physics: {ToPrettyString(uid)}");
return;
}
@@ -245,7 +247,9 @@ namespace Robust.Shared.Physics.Systems
foreach (var (id, fixture) in component.Fixtures)
{
DebugTools.Assert(id == fixture.ID);
#pragma warning disable CS0618
fixture.Body = physics;
#pragma warning restore CS0618
}
var toAddFixtures = new ValueList<Fixture>();
@@ -260,7 +264,9 @@ namespace Robust.Shared.Physics.Systems
var fixture = state.Fixtures[i];
var newFixture = new Fixture();
fixture.CopyTo(newFixture);
#pragma warning disable CS0618
newFixture.Body = physics;
#pragma warning restore CS0618
newFixtures.Add(newFixture.ID, newFixture);
}

View File

@@ -492,7 +492,7 @@ namespace Robust.Shared.Physics.Systems
// TODO: The below is slow and should just query the map's broadphase directly. The problem is that
// there's some ordering stuff going on where the broadphase has queued all of its updates but hasn't applied
// them yet so this query will fail on initialization which chains into a whole lot of issues.
internal IEnumerable<BroadphaseComponent> GetBroadphases(MapId mapId, Box2 aabb)
internal IEnumerable<(EntityUid uid, BroadphaseComponent comp)> GetBroadphases(MapId mapId, Box2 aabb)
{
// TODO Okay so problem: If we just do Encloses that's a lot faster BUT it also means we don't return the
// map's broadphase which avoids us iterating over it for 99% of bodies.
@@ -507,7 +507,7 @@ namespace Robust.Shared.Physics.Systems
if (!EntityManager.TryGetComponent(bUid, out MapGridComponent? mapGrid))
{
yield return broadphase;
yield return (bUid, broadphase);
continue;
}
@@ -516,7 +516,7 @@ namespace Robust.Shared.Physics.Systems
if (chunkEnumerator.MoveNext(out _))
{
yield return broadphase;
yield return (bUid, broadphase);
}
}
}

View File

@@ -67,7 +67,7 @@ public partial class SharedPhysicsSystem
if (manager.FixtureCount == 0)
component.CanCollide = false;
var ev = new CollisionChangeEvent(component, component.CanCollide);
var ev = new CollisionChangeEvent(uid, component, component.CanCollide);
RaiseLocalEvent(ref ev);
}
@@ -502,7 +502,7 @@ public partial class SharedPhysicsSystem
if (body.Initialized)
{
var ev = new CollisionChangeEvent(body, value);
var ev = new CollisionChangeEvent(uid, body, value);
RaiseLocalEvent(ref ev);
}

View File

@@ -31,9 +31,9 @@ namespace Robust.Shared.Physics.Systems
{
var state = (collider, mapId, found: false);
foreach (var broadphase in _broadphase.GetBroadphases(mapId, collider))
foreach (var (uid, broadphase) in _broadphase.GetBroadphases(mapId, collider))
{
var gridCollider = EntityManager.GetComponent<TransformComponent>(broadphase.Owner).InvWorldMatrix.TransformBox(collider);
var gridCollider = _transform.GetInvWorldMatrix(uid).TransformBox(collider);
broadphase.StaticTree.QueryAabb(ref state, (ref (Box2 collider, MapId map, bool found) state, in FixtureProxy proxy) =>
{
@@ -128,9 +128,9 @@ namespace Robust.Shared.Physics.Systems
var bodies = new HashSet<PhysicsComponent>();
foreach (var broadphase in _broadphase.GetBroadphases(mapId, worldAABB))
foreach (var (uid, broadphase) in _broadphase.GetBroadphases(mapId, worldAABB))
{
var gridAABB = EntityManager.GetComponent<TransformComponent>(broadphase.Owner).InvWorldMatrix.TransformBox(worldAABB);
var gridAABB = _transform.GetInvWorldMatrix(uid).TransformBox(worldAABB);
foreach (var proxy in broadphase.StaticTree.QueryAabb(gridAABB, false))
{
@@ -155,9 +155,9 @@ namespace Robust.Shared.Physics.Systems
var bodies = new HashSet<PhysicsComponent>();
foreach (var broadphase in _broadphase.GetBroadphases(mapId, worldBounds.CalcBoundingBox()))
foreach (var (uid, broadphase) in _broadphase.GetBroadphases(mapId, worldBounds.CalcBoundingBox()))
{
var gridAABB = EntityManager.GetComponent<TransformComponent>(broadphase.Owner).InvWorldMatrix.TransformBox(worldBounds);
var gridAABB = _transform.GetInvWorldMatrix(uid).TransformBox(worldBounds);
foreach (var proxy in broadphase.StaticTree.QueryAabb(gridAABB, false))
{
@@ -265,9 +265,9 @@ namespace Robust.Shared.Physics.Systems
var rayBox = new Box2(Vector2.ComponentMin(ray.Position, endPoint),
Vector2.ComponentMax(ray.Position, endPoint));
foreach (var broadphase in _broadphase.GetBroadphases(mapId, rayBox))
foreach (var (uid, broadphase) in _broadphase.GetBroadphases(mapId, rayBox))
{
var (_, rot, matrix, invMatrix) = Transform(broadphase.Owner).GetWorldPositionRotationMatrixWithInv();
var (_, rot, matrix, invMatrix) = _transform.GetWorldPositionRotationMatrixWithInv(uid);
var position = invMatrix.Transform(ray.Position);
var gridRot = new Angle(-rot.Theta);
@@ -370,9 +370,9 @@ namespace Robust.Shared.Physics.Systems
var rayBox = new Box2(Vector2.ComponentMin(ray.Position, endPoint),
Vector2.ComponentMax(ray.Position, endPoint));
foreach (var broadphase in _broadphase.GetBroadphases(mapId, rayBox))
foreach (var (uid, broadphase) in _broadphase.GetBroadphases(mapId, rayBox))
{
var (_, rot, invMatrix) = Transform(broadphase.Owner).GetWorldPositionRotationInvMatrix();
var (_, rot, invMatrix) = _transform.GetWorldPositionRotationInvMatrix(uid);
var position = invMatrix.Transform(ray.Position);
var gridRot = new Angle(-rot.Theta);

View File

@@ -195,7 +195,7 @@ public abstract partial class SharedPhysicsSystem
}
TransformComponent? parentXform = xformQuery.GetComponent(parent);
var localPos = parentXform.InvWorldMatrix.Transform(xform.WorldPosition);
var localPos = _transform.GetInvWorldMatrix(parentXform).Transform(_transform.GetWorldPosition(xform));
var oldLinear = physics.LinearVelocity;
var oldAngular = physics.AngularVelocity;

View File

@@ -101,7 +101,7 @@ namespace Robust.Shared.Physics.Systems
private void OnCollisionChange(ref CollisionChangeEvent ev)
{
var uid = ev.Body.Owner;
var uid = ev.BodyUid;
var mapId = Transform(uid).MapID;
if (mapId == MapId.Nullspace)

View File

@@ -17,6 +17,7 @@ namespace Robust.Shared.Profiling;
public sealed class ProfManager
{
[IoC.Dependency] private readonly IConfigurationManager _cfg = default!;
[IoC.Dependency] private readonly ILogManager _logManager = default!;
/// <summary>
/// Proxy to <c>prof.enabled</c> CVar.
@@ -29,13 +30,17 @@ public sealed class ProfManager
public ProfBuffer Buffer;
private ISawmill? _sawmill = default!;
internal void Initialize()
{
_sawmill = _logManager.GetSawmill("prof");
_cfg.OnValueChanged(CVars.ProfIndexSize, i =>
{
if (!BitOperations.IsPow2(i))
{
Logger.WarningS("prof", "Rounding prof.index_size to next POT");
_sawmill.Warning("Rounding prof.index_size to next POT");
i = BufferHelpers.FittingPowerOfTwo(i);
}
@@ -47,7 +52,7 @@ public sealed class ProfManager
{
if (!BitOperations.IsPow2(i))
{
Logger.WarningS("prof", "Rounding prof.buffer_size to next POT");
_sawmill.Warning("Rounding prof.buffer_size to next POT");
i = BufferHelpers.FittingPowerOfTwo(i);
}

View File

@@ -102,7 +102,7 @@ public partial class PrototypeManager
throw;
}
_sawmill.Error($"Error reloading prototypes in file {file}:\n{e}");
Sawmill.Error($"Error reloading prototypes in file {file}:\n{e}");
return null;
}
@@ -140,7 +140,7 @@ public partial class PrototypeManager
}
catch (Exception e)
{
_sawmill.Error($"Exception whilst loading prototypes from {file}#{i}:\n{e}");
Sawmill.Error($"Exception whilst loading prototypes from {file}#{i}:\n{e}");
}
i += 1;
@@ -148,7 +148,7 @@ public partial class PrototypeManager
}
catch (Exception e)
{
_sawmill.Error("YamlException whilst loading prototypes from {0}: {1}", file, e.Message);
Sawmill.Error("YamlException whilst loading prototypes from {0}: {1}", file, e.Message);
}
}

View File

@@ -33,7 +33,7 @@ namespace Robust.Shared.Prototypes
private readonly Dictionary<string, Type> _kindNames = new();
private readonly Dictionary<Type, int> _kindPriorities = new();
private ISawmill _sawmill = default!;
protected ISawmill Sawmill = default!;
private bool _initialized;
private bool _hasEverBeenReloaded;
@@ -51,7 +51,7 @@ namespace Robust.Shared.Prototypes
throw new InvalidOperationException($"{nameof(PrototypeManager)} has already been initialized.");
}
_sawmill = _logManager.GetSawmill("proto");
Sawmill = _logManager.GetSawmill("proto");
_initialized = true;
ReloadPrototypeKinds();
@@ -473,7 +473,7 @@ namespace Robust.Shared.Prototypes
}
catch (Exception e)
{
_sawmill.Error($"Reading {kind}({id}) threw the following exception: {e}");
Sawmill.Error($"Reading {kind}({id}) threw the following exception: {e}");
return null;
}
}

View File

@@ -98,6 +98,7 @@ namespace Robust.Shared.Timing
// ReSharper disable once NotAccessedField.Local
private readonly IRuntimeLog _runtimeLog;
private readonly ProfManager _prof;
private readonly ISawmill _sawmill;
#if EXCEPTION_TOLERANCE
private int _tickExceptions;
@@ -105,11 +106,12 @@ namespace Robust.Shared.Timing
private const int MaxSoftLockExceptions = 10;
#endif
public GameLoop(IGameTiming timing, IRuntimeLog runtimeLog, ProfManager prof)
public GameLoop(IGameTiming timing, IRuntimeLog runtimeLog, ProfManager prof, ISawmill sawmill)
{
_timing = timing;
_runtimeLog = runtimeLog;
_prof = prof;
_sawmill = sawmill;
}
/// <summary>
@@ -154,7 +156,7 @@ namespace Robust.Shared.Timing
// announce we are falling behind
if ((_timing.RealTime - _lastKeepUp).TotalSeconds >= 15.0)
{
Logger.WarningS("eng", "MainLoop: Cannot keep up!");
_sawmill.Warning("MainLoop: Cannot keep up!");
_lastKeepUp = _timing.RealTime;
}
}
@@ -227,7 +229,7 @@ namespace Robust.Shared.Timing
if (_tickExceptions > MaxSoftLockExceptions && DetectSoftLock)
{
Logger.FatalS("eng",
_sawmill.Fatal(
"MainLoop: 10 consecutive exceptions inside GameLoop Tick, shutting down!");
Running = false;
}

View File

@@ -170,7 +170,7 @@ internal abstract partial class ViewVariablesManager
var kind = segments[0];
var id = segments[1];
if (!_protoMan.TryGetVariantType(kind, out var kindType)
if (!_protoMan.TryGetKindType(kind, out var kindType)
|| !_protoMan.TryIndex(kindType, id, out var prototype))
return EmptyResolve;
@@ -186,10 +186,10 @@ internal abstract partial class ViewVariablesManager
var kind = segments[0];
var prototype = segments.Length == 1 ? string.Empty : segments[1];
if(!_protoMan.HasVariant(kind))
if(!_protoMan.HasKind(kind))
goto case 0;
if (_protoMan.TryIndex(_protoMan.GetVariantType(kind), prototype, out _))
if (_protoMan.TryIndex(_protoMan.GetKindType(kind), prototype, out _))
goto case default;
return _protoMan.EnumeratePrototypes(kind)

View File

@@ -738,6 +738,8 @@ namespace Robust.UnitTesting
{
var modLoader = new ModLoader();
IoCManager.InjectDependencies(modLoader);
var cast = (IPostInjectInit) modLoader;
cast.PostInject();
modLoader.SetEnableSandboxing(true);
modLoader.LoadGameAssembly(assembly.Location);
});

View File

@@ -3,6 +3,7 @@ using Moq;
using NUnit.Framework;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Log;
using Robust.Shared.Reflection;
using Robust.UnitTesting.Shared.Reflection;
@@ -13,7 +14,7 @@ namespace Robust.UnitTesting.Shared.GameObjects
[Test]
public void SubscribeCompEvent()
{
var compFactory = new ComponentFactory(new DynamicTypeFactory(), new ReflectionManagerTest());
var compFactory = new ComponentFactory(new DynamicTypeFactory(), new ReflectionManagerTest(), new LogManager());
// Arrange
var entUid = new EntityUid(7);

View File

@@ -62,7 +62,7 @@ namespace Robust.UnitTesting.Shared.GameObjects
#pragma warning disable RA0013
SubscribeLocalEvent<TestStructEvent>(MyRefHandler);
SubscribeLocalEvent<TestStructEvent>(MyValueHandler);
#pragma warning enable RA0013
#pragma warning restore RA0013
}
private void MyValueHandler(TestStructEvent args) { }

View File

@@ -79,7 +79,7 @@ namespace Robust.UnitTesting.Shared.GameObjects
SubscribeLocalEvent<DummyComponent, TestStructEvent>(MyRefHandler);
#pragma warning disable RA0013
SubscribeLocalEvent<DummyTwoComponent, TestStructEvent>(MyValueHandler);
#pragma warning enable RA0013
#pragma warning restore RA0013
}
private void MyValueHandler(EntityUid uid, DummyTwoComponent component, TestStructEvent args) { }

View File

@@ -3,6 +3,7 @@ using System.Reflection;
using Moq;
using NUnit.Framework;
using Robust.Shared.Exceptions;
using Robust.Shared.Log;
using Robust.Shared.Profiling;
using Robust.Shared.Timing;
@@ -28,7 +29,7 @@ namespace Robust.UnitTesting.Shared.Timing
newStopwatch.SetupGet(p => p.Elapsed).Returns(elapsedVal);
var gameTiming = GameTimingFactory(newStopwatch.Object);
gameTiming.Paused = false;
var loop = new GameLoop(gameTiming, new RuntimeLog(), new ProfManager());
var loop = new GameLoop(gameTiming, new RuntimeLog(), new ProfManager(), new LogManager().RootSawmill);
var callCount = 0;
loop.Tick += (sender, args) => callCount++;