1
0

NodeGroupFactory.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System.Reflection;
  2. using Content.Server.Power.Generation.Teg;
  3. using Robust.Shared.Reflection;
  4. namespace Content.Server.NodeContainer.NodeGroups
  5. {
  6. public interface INodeGroupFactory
  7. {
  8. /// <summary>
  9. /// Performs reflection to associate <see cref="INodeGroup"/> implementations with the
  10. /// string specified in their <see cref="NodeGroupAttribute"/>.
  11. /// </summary>
  12. void Initialize();
  13. /// <summary>
  14. /// Returns a new <see cref="INodeGroup"/> instance.
  15. /// </summary>
  16. INodeGroup MakeNodeGroup(NodeGroupID id);
  17. }
  18. public sealed class NodeGroupFactory : INodeGroupFactory
  19. {
  20. [Dependency] private readonly IReflectionManager _reflectionManager = default!;
  21. [Dependency] private readonly IDynamicTypeFactory _typeFactory = default!;
  22. private readonly Dictionary<NodeGroupID, Type> _groupTypes = new();
  23. public void Initialize()
  24. {
  25. var nodeGroupTypes = _reflectionManager.GetAllChildren<INodeGroup>();
  26. foreach (var nodeGroupType in nodeGroupTypes)
  27. {
  28. var att = nodeGroupType.GetCustomAttribute<NodeGroupAttribute>();
  29. if (att != null)
  30. {
  31. foreach (var groupID in att.NodeGroupIDs)
  32. {
  33. _groupTypes.Add(groupID, nodeGroupType);
  34. }
  35. }
  36. }
  37. }
  38. public INodeGroup MakeNodeGroup(NodeGroupID id)
  39. {
  40. if (!_groupTypes.TryGetValue(id, out var type))
  41. throw new ArgumentException($"{id} did not have an associated {nameof(INodeGroup)} implementation.");
  42. var instance = _typeFactory.CreateInstance<INodeGroup>(type);
  43. instance.Create(id);
  44. return instance;
  45. }
  46. }
  47. public enum NodeGroupID : byte
  48. {
  49. Default,
  50. HVPower,
  51. MVPower,
  52. Apc,
  53. AMEngine,
  54. Pipe,
  55. WireNet,
  56. /// <summary>
  57. /// Group used by the TEG.
  58. /// </summary>
  59. /// <seealso cref="TegSystem"/>
  60. /// <seealso cref="TegNodeGroup"/>
  61. Teg,
  62. }
  63. }