1
0

BaseNetConnectorComponent.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. using System.Diagnostics.CodeAnalysis;
  2. using System.Linq;
  3. using Content.Server.NodeContainer;
  4. using Content.Server.NodeContainer.NodeGroups;
  5. namespace Content.Server.Power.Components
  6. {
  7. // TODO find a way to just remove this or turn it into one component.
  8. // Component interface queries require enumerating over ALL of an entities components.
  9. // So BaseNetConnectorNodeGroup<TNetType> is slow as shit.
  10. public interface IBaseNetConnectorComponent<in TNetType>
  11. {
  12. public TNetType? Net { set; }
  13. public Voltage Voltage { get; }
  14. public string? NodeId { get; }
  15. }
  16. public abstract partial class BaseNetConnectorComponent<TNetType> : Component, IBaseNetConnectorComponent<TNetType>
  17. where TNetType : class
  18. {
  19. [Dependency] private readonly IEntityManager _entMan = default!;
  20. [ViewVariables(VVAccess.ReadWrite)]
  21. public Voltage Voltage { get => _voltage; set => SetVoltage(value); }
  22. [DataField("voltage")]
  23. private Voltage _voltage = Voltage.High;
  24. [ViewVariables]
  25. public TNetType? Net { get => _net; set => SetNet(value); }
  26. private TNetType? _net;
  27. [ViewVariables] public bool NeedsNet => _net != null;
  28. [DataField("node")] public string? NodeId { get; set; }
  29. public void TryFindAndSetNet()
  30. {
  31. if (TryFindNet(out var net))
  32. {
  33. Net = net;
  34. }
  35. }
  36. public void ClearNet()
  37. {
  38. if (_net != null)
  39. {
  40. RemoveSelfFromNet(_net);
  41. _net = null;
  42. }
  43. }
  44. protected abstract void AddSelfToNet(TNetType net);
  45. protected abstract void RemoveSelfFromNet(TNetType net);
  46. private bool TryFindNet([NotNullWhen(true)] out TNetType? foundNet)
  47. {
  48. if (_entMan.TryGetComponent(Owner, out NodeContainerComponent? container))
  49. {
  50. var compatibleNet = container.Nodes.Values
  51. .Where(node => (NodeId == null || NodeId == node.Name) && node.NodeGroupID == (NodeGroupID) Voltage)
  52. .Select(node => node.NodeGroup)
  53. .OfType<TNetType>()
  54. .FirstOrDefault();
  55. if (compatibleNet != null)
  56. {
  57. foundNet = compatibleNet;
  58. return true;
  59. }
  60. }
  61. foundNet = default;
  62. return false;
  63. }
  64. private void SetNet(TNetType? newNet)
  65. {
  66. if (_net != null)
  67. RemoveSelfFromNet(_net);
  68. if (newNet != null)
  69. AddSelfToNet(newNet);
  70. _net = newNet;
  71. }
  72. private void SetVoltage(Voltage newVoltage)
  73. {
  74. ClearNet();
  75. _voltage = newVoltage;
  76. TryFindAndSetNet();
  77. }
  78. }
  79. public enum Voltage
  80. {
  81. High = NodeGroupID.HVPower,
  82. Medium = NodeGroupID.MVPower,
  83. Apc = NodeGroupID.Apc,
  84. }
  85. }