This repository has been archived on 2020-09-30. You can view files and clone it, but cannot push or open issues or pull requests.
odyssey-old/Actors/Systems/Electricity/PowerNetwork.gd

84 lines
2.1 KiB
GDScript3
Raw Normal View History

2020-07-08 22:12:14 +00:00
extends Node
class_name PowerNetwork
2020-07-09 14:50:34 +00:00
const DEBUG = false
2020-07-08 22:12:14 +00:00
var nodes = []
2020-07-09 07:19:17 +00:00
var sockets = []
2020-07-08 22:12:14 +00:00
2020-07-09 14:50:34 +00:00
var total_source = 0
var total_usage = 0
2020-07-08 22:12:14 +00:00
var debugColor = Color.cyan
func _ready():
name = "PowerNetwork"
debugColor = Color.from_hsv(randf(), 0.8, 0.8)
2020-07-09 14:50:34 +00:00
func add_node(node) -> void:
2020-07-08 22:12:14 +00:00
nodes.append(node)
2020-07-09 14:50:34 +00:00
if "connections" in node:
2020-07-09 07:19:17 +00:00
sockets.append(node)
2020-07-09 14:50:34 +00:00
func remove_node(node) -> void:
2020-07-09 07:19:17 +00:00
var node_idx = nodes.find(node)
if node_idx >= 0:
nodes.remove(node_idx)
var sock_idx = sockets.find(node)
if sock_idx >= 0:
sockets.remove(sock_idx)
# Do other splitting here
node.network = null
2020-07-08 22:12:14 +00:00
2020-07-09 14:50:34 +00:00
func join(network) -> void:
2020-07-08 22:12:14 +00:00
for node in network.nodes:
nodes.append(node)
node.network = self
2020-07-09 14:50:34 +00:00
for socket in network.sockets:
sockets.append(socket)
socket.network = self
2020-07-08 22:12:14 +00:00
# Do other merging here
network.queue_free()
2020-07-09 14:50:34 +00:00
func _physics_process(_delta: float) -> void:
2020-07-09 07:19:17 +00:00
# Recalculate power availability and usage
2020-07-09 14:50:34 +00:00
total_source = 0
total_usage = 0
var sources = []
var sinks = []
# Calculate totals
2020-07-09 07:19:17 +00:00
for socket in sockets:
for connection in socket.connections:
var manager = connection as PowerManager
2020-07-09 14:50:34 +00:00
match socket.flow:
ElectricSocket.Flow.SINK:
total_usage += manager.power_usage
sinks.append(manager)
ElectricSocket.Flow.SOURCE:
total_source += manager.power_source
sources.append(manager)
ElectricSocket.Flow.BIDIRECTIONAL:
total_usage += manager.power_usage
total_source += manager.power_source
sinks.append(manager)
sources.append(manager)
# Update manager stats
var available_supply = total_source
for sink in sinks:
# Check if item can be powered this cycle
if sink.power_usage > 0:
if available_supply > sink.power_usage:
available_supply -= sink.power_usage
sink.powered = true
else:
sink.powered = false
# Update available power to sinks
for sink in sinks:
sink.available = available_supply
# Check how much we actually need to drain from sources
var remaining_drain = total_source - available_supply
for source in sources:
var source_load = source.power_source / total_source * remaining_drain
source.power_load = source_load