Power Rework (#863)

Co-authored-by: py01 <pyronetics01@gmail.com>
This commit is contained in:
py01
2020-06-28 09:23:26 -06:00
committed by GitHub
parent ffe25de723
commit 23cc6b1d4e
154 changed files with 11253 additions and 3913 deletions

View File

@@ -0,0 +1,122 @@
using Content.Server.GameObjects.Components.Power;
using Content.Server.GameObjects.Components.Power.ApcNetComponents;
using Robust.Shared.ViewVariables;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Content.Server.GameObjects.Components.NodeContainer.NodeGroups
{
public interface IApcNet
{
void AddApc(ApcComponent apc);
void RemoveApc(ApcComponent apc);
void AddPowerProvider(PowerProviderComponent provider);
void RemovePowerProvider(PowerProviderComponent provider);
void UpdatePowerProviderReceivers(PowerProviderComponent provider);
void Update(float frameTime);
}
[NodeGroup(NodeGroupID.Apc)]
public class ApcNetNodeGroup : BaseNetConnectorNodeGroup<BaseApcNetComponent, IApcNet>, IApcNet
{
[ViewVariables]
private readonly Dictionary<ApcComponent, BatteryComponent> _apcBatteries = new Dictionary<ApcComponent, BatteryComponent>();
[ViewVariables]
private readonly Dictionary<PowerProviderComponent, List<PowerReceiverComponent>> _providerReceivers = new Dictionary<PowerProviderComponent, List<PowerReceiverComponent>>();
//Debug property
[ViewVariables]
private int TotalReceivers => _providerReceivers.SelectMany(kvp => kvp.Value).Count();
private IEnumerable<BatteryComponent> AvailableBatteries => _apcBatteries.Where(kvp => kvp.Key.MainBreakerEnabled).Select(kvp => kvp.Value);
public static readonly IApcNet NullNet = new NullApcNet();
#region IApcNet Methods
protected override void SetNetConnectorNet(BaseApcNetComponent netConnectorComponent)
{
netConnectorComponent.Net = this;
}
public void AddApc(ApcComponent apc)
{
_apcBatteries.Add(apc, apc.Battery);
}
public void RemoveApc(ApcComponent apc)
{
_apcBatteries.Remove(apc);
if (!_apcBatteries.Any())
{
foreach (var receiver in _providerReceivers.SelectMany(kvp => kvp.Value))
{
receiver.HasApcPower = false;
}
}
}
public void AddPowerProvider(PowerProviderComponent provider)
{
_providerReceivers.Add(provider, provider.LinkedReceivers.ToList());
}
public void RemovePowerProvider(PowerProviderComponent provider)
{
_providerReceivers.Remove(provider);
}
public void UpdatePowerProviderReceivers(PowerProviderComponent provider)
{
Debug.Assert(_providerReceivers.ContainsKey(provider));
_providerReceivers[provider] = provider.LinkedReceivers.ToList();
}
public void Update(float frameTime)
{
var totalCharge = 0.0;
var totalMaxCharge = 0;
foreach (var battery in AvailableBatteries)
{
totalCharge += battery.CurrentCharge;
totalMaxCharge += battery.MaxCharge;
}
var availablePowerFraction = totalCharge / totalMaxCharge;
foreach (var receiver in _providerReceivers.SelectMany(kvp => kvp.Value))
{
receiver.HasApcPower = TryUsePower(receiver.Load * frameTime);
}
}
private bool TryUsePower(float neededCharge)
{
foreach (var battery in AvailableBatteries)
{
if (battery.TryUseCharge(neededCharge)) //simplification - all power needed must come from one battery
{
return true;
}
}
return false;
}
#endregion
private class NullApcNet : IApcNet
{
public void AddApc(ApcComponent apc) { }
public void AddPowerProvider(PowerProviderComponent provider) { }
public void RemoveApc(ApcComponent apc) { }
public void RemovePowerProvider(PowerProviderComponent provider) { }
public void UpdatePowerProviderReceivers(PowerProviderComponent provider) { }
public void Update(float frameTime) { }
}
}
}

View File

@@ -0,0 +1,36 @@
using Content.Server.GameObjects.Components.Power;
using Content.Server.GameObjects.Components.NodeContainer.Nodes;
using System.Collections.Generic;
using System.Linq;
namespace Content.Server.GameObjects.Components.NodeContainer.NodeGroups
{
public abstract class BaseNetConnectorNodeGroup<TNetConnector, TNetType> : BaseNodeGroup where TNetConnector : BaseNetConnectorComponent<TNetType>
{
private readonly Dictionary<Node, List<TNetConnector>> _netConnectorComponents = new Dictionary<Node, List<TNetConnector>>();
protected override void OnAddNode(Node node)
{
var newNetConnectorComponents = node.Owner
.GetAllComponents<TNetConnector>()
.Where(powerComp => (NodeGroupID) powerComp.Voltage == node.NodeGroupID)
.ToList();
_netConnectorComponents.Add(node, newNetConnectorComponents);
foreach (var netConnectorComponent in newNetConnectorComponents)
{
SetNetConnectorNet(netConnectorComponent);
}
}
protected abstract void SetNetConnectorNet(TNetConnector netConnectorComponent);
protected override void OnRemoveNode(Node node)
{
foreach (var netConnectorComponent in _netConnectorComponents[node])
{
netConnectorComponent.ClearNet();
}
_netConnectorComponents.Remove(node);
}
}
}

View File

@@ -0,0 +1,121 @@
using Content.Server.GameObjects.Components.NodeContainer.Nodes;
using Robust.Shared.ViewVariables;
using System.Collections.Generic;
namespace Content.Server.GameObjects.Components.NodeContainer.NodeGroups
{
/// <summary>
/// Maintains a collection of <see cref="Node"/>s, and performs operations requiring a list of
/// all connected <see cref="Node"/>s.
/// </summary>
public interface INodeGroup
{
public IReadOnlyList<Node> Nodes { get; }
void AddNode(Node node);
void RemoveNode(Node node);
void CombineGroup(INodeGroup newGroup);
void BeforeCombine();
void AfterCombine();
void BeforeRemakeSpread();
void AfterRemakeSpread();
}
[NodeGroup(NodeGroupID.Default)]
public class BaseNodeGroup : INodeGroup
{
[ViewVariables]
public IReadOnlyList<Node> Nodes => _nodes;
private readonly List<Node> _nodes = new List<Node>();
[ViewVariables]
public int NodeCount => Nodes.Count;
public static readonly INodeGroup NullGroup = new NullNodeGroup();
public void AddNode(Node node)
{
_nodes.Add(node);
OnAddNode(node);
}
public void RemoveNode(Node node)
{
_nodes.Remove(node);
OnRemoveNode(node);
RemakeGroup();
}
public void CombineGroup(INodeGroup newGroup)
{
if (newGroup.Nodes.Count < Nodes.Count)
{
newGroup.CombineGroup(this);
return;
}
BeforeCombine();
newGroup.BeforeCombine();
foreach (var node in Nodes)
{
node.NodeGroup = newGroup;
}
AfterCombine();
newGroup.AfterCombine();
}
/// <summary>
/// Causes all <see cref="Node"/>s to remake their groups. Called when a <see cref="Node"/> is removed
/// and may have split a group in two, so multiple new groups may need to be formed.
/// </summary>
private void RemakeGroup()
{
BeforeRemake();
foreach (var node in Nodes)
{
node.ClearNodeGroup();
}
foreach (var node in Nodes)
{
if (node.TryAssignGroupIfNeeded())
{
node.StartSpreadingGroup();
}
}
}
protected virtual void OnAddNode(Node node) { }
protected virtual void OnRemoveNode(Node node) { }
protected virtual void BeforeRemake() { }
protected virtual void AfterRemake() { }
public virtual void BeforeCombine() { }
public virtual void AfterCombine() { }
public virtual void BeforeRemakeSpread() { }
public virtual void AfterRemakeSpread() { }
private class NullNodeGroup : INodeGroup
{
public IReadOnlyList<Node> Nodes => _nodes;
private readonly List<Node> _nodes = new List<Node>();
public void AddNode(Node node) { }
public void CombineGroup(INodeGroup newGroup) { }
public void RemoveNode(Node node) { }
public void BeforeCombine() { }
public void AfterCombine() { }
public void BeforeRemakeSpread() { }
public void AfterRemakeSpread() { }
}
}
}

View File

@@ -0,0 +1,20 @@
using System;
namespace Content.Server.GameObjects.Components.NodeContainer.NodeGroups
{
/// <summary>
/// Associates a <see cref="INodeGroup"/> implementation with a <see cref="NodeGroupID"/>.
/// This is used to gurantee all <see cref="INode"/>s of the same <see cref="INode.NodeGroupID"/>
/// have the same type of <see cref="INodeGroup"/>. Used by <see cref="INodeGroupFactory"/>.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class NodeGroupAttribute : Attribute
{
public NodeGroupID[] NodeGroupIDs { get; }
public NodeGroupAttribute(params NodeGroupID[] nodeGroupTypes)
{
NodeGroupIDs = nodeGroupTypes;
}
}
}

View File

@@ -0,0 +1,65 @@
using Robust.Shared.Interfaces.Reflection;
using Robust.Shared.IoC;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Content.Server.GameObjects.Components.NodeContainer.NodeGroups
{
public interface INodeGroupFactory
{
/// <summary>
/// Performs reflection to associate <see cref="INodeGroup"/> implementations with the
/// string specified in their <see cref="NodeGroupAttribute"/>.
/// </summary>
void Initialize();
/// <summary>
/// Returns a new <see cref="INodeGroup"/> instance.
/// </summary>
INodeGroup MakeNodeGroup(NodeGroupID nodeGroupType);
}
public class NodeGroupFactory : INodeGroupFactory
{
private readonly Dictionary<NodeGroupID, Type> _groupTypes = new Dictionary<NodeGroupID, Type>();
#pragma warning disable 649
[Dependency] private readonly IReflectionManager _reflectionManager;
[Dependency] private readonly IDynamicTypeFactory _typeFactory;
#pragma warning restore 649
public void Initialize()
{
var nodeGroupTypes = _reflectionManager.GetAllChildren<BaseNodeGroup>();
foreach (var nodeGroupType in nodeGroupTypes)
{
var att = nodeGroupType.GetCustomAttribute<NodeGroupAttribute>();
if (att != null)
{
foreach (var groupID in att.NodeGroupIDs)
{
_groupTypes.Add(groupID, nodeGroupType);
}
}
}
}
public INodeGroup MakeNodeGroup(NodeGroupID nodeGroupType)
{
if (_groupTypes.TryGetValue(nodeGroupType, out var type))
{
return _typeFactory.CreateInstance<INodeGroup>(type);
}
throw new ArgumentException($"{nodeGroupType} did not have an associated {nameof(INodeGroup)}.");
}
}
public enum NodeGroupID
{
Default,
HVPower,
MVPower,
Apc,
}
}

View File

@@ -0,0 +1,192 @@
using Content.Server.GameObjects.Components.Power.PowerNetComponents;
using Robust.Shared.ViewVariables;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Content.Server.GameObjects.Components.NodeContainer.NodeGroups
{
public interface IPowerNet
{
void AddSupplier(PowerSupplierComponent supplier);
void RemoveSupplier(PowerSupplierComponent supplier);
void UpdateSupplierSupply(PowerSupplierComponent supplier, int oldSupplyRate, int newSupplyRate);
void AddConsumer(PowerConsumerComponent consumer);
void RemoveConsumer(PowerConsumerComponent consumer);
void UpdateConsumerDraw(PowerConsumerComponent consumer, int oldDrawRate, int newDrawRate);
void UpdateConsumerPriority(PowerConsumerComponent consumer, Priority oldPriority, Priority newPriority);
}
[NodeGroup(NodeGroupID.HVPower, NodeGroupID.MVPower)]
public class PowerNetNodeGroup : BaseNetConnectorNodeGroup<BasePowerNetComponent, IPowerNet>, IPowerNet
{
[ViewVariables]
private readonly List<PowerSupplierComponent> _suppliers = new List<PowerSupplierComponent>();
[ViewVariables]
private int _totalSupply = 0;
[ViewVariables]
private readonly Dictionary<Priority, List<PowerConsumerComponent>> _consumersByPriority = new Dictionary<Priority, List<PowerConsumerComponent>>();
[ViewVariables]
private readonly Dictionary<Priority, int> _drawByPriority = new Dictionary<Priority, int>();
[ViewVariables]
private bool _supressPowerRecalculation = false;
public static readonly IPowerNet NullNet = new NullPowerNet();
public PowerNetNodeGroup()
{
foreach(Priority priority in Enum.GetValues(typeof(Priority)))
{
_consumersByPriority.Add(priority, new List<PowerConsumerComponent>());
_drawByPriority.Add(priority, 0);
}
}
#region BaseNodeGroup Overrides
protected override void SetNetConnectorNet(BasePowerNetComponent netConnectorComponent)
{
netConnectorComponent.Net = this;
}
public override void BeforeCombine()
{
_supressPowerRecalculation = true;
}
public override void AfterCombine()
{
_supressPowerRecalculation = false;
UpdateConsumerReceivedPower();
}
protected override void BeforeRemake()
{
_supressPowerRecalculation = true;
}
public override void BeforeRemakeSpread()
{
_supressPowerRecalculation = true;
}
public override void AfterRemakeSpread()
{
_supressPowerRecalculation = false;
UpdateConsumerReceivedPower();
}
#endregion
#region IPowerNet Methods
public void AddSupplier(PowerSupplierComponent supplier)
{
_suppliers.Add(supplier);
_totalSupply += supplier.SupplyRate;
UpdateConsumerReceivedPower();
}
public void RemoveSupplier(PowerSupplierComponent supplier)
{
Debug.Assert(_suppliers.Contains(supplier));
_suppliers.Remove(supplier);
_totalSupply -= supplier.SupplyRate;
UpdateConsumerReceivedPower();
}
public void UpdateSupplierSupply(PowerSupplierComponent supplier, int oldSupplyRate, int newSupplyRate)
{
Debug.Assert(_suppliers.Contains(supplier));
_totalSupply -= oldSupplyRate;
_totalSupply += newSupplyRate;
UpdateConsumerReceivedPower();
}
public void AddConsumer(PowerConsumerComponent consumer)
{
_consumersByPriority[consumer.Priority].Add(consumer);
_drawByPriority[consumer.Priority] += consumer.DrawRate;
UpdateConsumerReceivedPower();
}
public void RemoveConsumer(PowerConsumerComponent consumer)
{
Debug.Assert(_consumersByPriority[consumer.Priority].Contains(consumer));
_consumersByPriority[consumer.Priority].Add(consumer);
_drawByPriority[consumer.Priority] -= consumer.DrawRate;
UpdateConsumerReceivedPower();
}
public void UpdateConsumerDraw(PowerConsumerComponent consumer, int oldDrawRate, int newDrawRate)
{
Debug.Assert(_consumersByPriority[consumer.Priority].Contains(consumer));
_drawByPriority[consumer.Priority] -= oldDrawRate;
_drawByPriority[consumer.Priority] += newDrawRate;
UpdateConsumerReceivedPower();
}
public void UpdateConsumerPriority(PowerConsumerComponent consumer, Priority oldPriority, Priority newPriority)
{
Debug.Assert(_consumersByPriority[oldPriority].Contains(consumer));
_consumersByPriority[oldPriority].Remove(consumer);
_drawByPriority[oldPriority] -= consumer.DrawRate;
_consumersByPriority[newPriority].Add(consumer);
_drawByPriority[newPriority] += consumer.DrawRate;
UpdateConsumerReceivedPower();
}
private void UpdateConsumerReceivedPower()
{
if (_supressPowerRecalculation)
{
return;
}
var remainingSupply = _totalSupply;
foreach (Priority priority in Enum.GetValues(typeof(Priority)))
{
var categoryPowerDemand = _drawByPriority[priority];
if (remainingSupply - categoryPowerDemand >= 0) //can fully power all in category
{
remainingSupply -= categoryPowerDemand;
foreach (var consumer in _consumersByPriority[priority])
{
consumer.ReceivedPower = consumer.DrawRate;
}
}
else if (remainingSupply - categoryPowerDemand < 0) //cannot fully power all, split power
{
var availiablePowerFraction = (float) remainingSupply / categoryPowerDemand;
remainingSupply = 0;
foreach (var consumer in _consumersByPriority[priority])
{
consumer.ReceivedPower = (int) (consumer.DrawRate * availiablePowerFraction); //give each consumer a fraction of what they requested (rounded down to nearest int)
}
}
}
}
#endregion
private class NullPowerNet : IPowerNet
{
public void AddConsumer(PowerConsumerComponent consumer) { }
public void AddSupplier(PowerSupplierComponent supplier) { }
public void UpdateSupplierSupply(PowerSupplierComponent supplier, int oldSupplyRate, int newSupplyRate) { }
public void RemoveConsumer(PowerConsumerComponent consumer) { }
public void RemoveSupplier(PowerSupplierComponent supplier) { }
public void UpdateConsumerDraw(PowerConsumerComponent consumer, int oldDrawRate, int newDrawRate) { }
public void UpdateConsumerPriority(PowerConsumerComponent consumer, Priority oldPriority, Priority newPriority) { }
}
}
}