| | | 1 | | using System.Collections.Generic; |
| | | 2 | | using UnityEngine; |
| | | 3 | | |
| | | 4 | | // The comunication manager manages the communication nodes and handles communication between |
| | | 5 | | // agents. |
| | | 6 | | public class CommsManager : MonoBehaviour { |
| | 3 | 7 | | public static CommsManager Instance { get; private set; } |
| | | 8 | | |
| | | 9 | | // Mailbox for queued messages. |
| | 0 | 10 | | private readonly Mailbox _mailbox = new Mailbox(); |
| | | 11 | | |
| | | 12 | | // Map from agent to the communication node. |
| | 0 | 13 | | private readonly HashSet<CommsNode> _nodes = new HashSet<CommsNode>(); |
| | | 14 | | |
| | | 15 | | // Add a communication node. This function should only be used by the IADS and in tests. |
| | 1 | 16 | | public void AddNode(CommsNode node) => _nodes.Add(node); |
| | | 17 | | |
| | 0 | 18 | | public bool ContainsNode(CommsNode node) => _nodes.Contains(node); |
| | | 19 | | |
| | 1 | 20 | | private void Awake() { |
| | 1 | 21 | | if (Instance != null && Instance != this) { |
| | 0 | 22 | | Destroy(gameObject); |
| | 0 | 23 | | return; |
| | | 24 | | } |
| | 1 | 25 | | Instance = this; |
| | 1 | 26 | | } |
| | | 27 | | |
| | 1 | 28 | | private void Start() { |
| | 1 | 29 | | SimManager.Instance.OnSimulationStarted += _mailbox.Clear; |
| | 1 | 30 | | SimManager.Instance.OnSimulationEnded += RegisterSimulationEnded; |
| | 1 | 31 | | SimManager.Instance.OnNewInterceptor += RegisterNewAgent; |
| | 1 | 32 | | SimManager.Instance.OnNewLauncher += RegisterNewAgent; |
| | 1 | 33 | | } |
| | | 34 | | |
| | 77 | 35 | | private void FixedUpdate() { |
| | 77 | 36 | | _mailbox.Deliver(); |
| | 77 | 37 | | } |
| | | 38 | | |
| | 0 | 39 | | public void SendMessage(Message message) { |
| | 0 | 40 | | _mailbox.Send(message); |
| | 0 | 41 | | } |
| | | 42 | | |
| | 11 | 43 | | private void RegisterSimulationEnded() { |
| | 11 | 44 | | _nodes.Clear(); |
| | 11 | 45 | | _mailbox.Clear(); |
| | 11 | 46 | | } |
| | | 47 | | |
| | 40 | 48 | | private void RegisterNewAgent(IAgent agent) { |
| | 54 | 49 | | if (agent.CommsNode != null) { |
| | 14 | 50 | | _nodes.Add(agent.CommsNode); |
| | 14 | 51 | | return; |
| | | 52 | | } |
| | | 53 | | |
| | 26 | 54 | | var commsNode = new CommsNode(agent.StaticConfig.AgentType); |
| | 26 | 55 | | agent.CommsNode = commsNode; |
| | 26 | 56 | | agent.OnTerminated += |
| | 0 | 57 | | _ => _nodes.Remove(commsNode); |
| | 26 | 58 | | _nodes.Add(commsNode); |
| | 40 | 59 | | } |
| | | 60 | | } |