| | | 1 | | using System; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.Linq; |
| | | 4 | | using UnityEngine; |
| | | 5 | | |
| | | 6 | | // The simulation manager handles the creation of all agents. |
| | | 7 | | // It implements the singleton pattern to ensure that only one instance exists. |
| | | 8 | | public class SimManager : MonoBehaviour { |
| | | 9 | | // Simulation events. |
| | | 10 | | public delegate void SimulationEventHandler(); |
| | | 11 | | public event SimulationEventHandler OnSimulationStarted; |
| | | 12 | | public event SimulationEventHandler OnSimulationEnded; |
| | | 13 | | |
| | | 14 | | // Interceptor events. |
| | | 15 | | public delegate void NewInterceptorEventHandler(IInterceptor interceptor); |
| | | 16 | | public event NewInterceptorEventHandler OnNewInterceptor; |
| | | 17 | | public delegate void NewLauncherEventHandler(IInterceptor launcher); |
| | | 18 | | public event NewLauncherEventHandler OnNewLauncher; |
| | | 19 | | |
| | | 20 | | // Threat events. |
| | | 21 | | public delegate void NewThreatEventHandler(IThreat threat); |
| | | 22 | | public event NewThreatEventHandler OnNewThreat; |
| | | 23 | | |
| | | 24 | | // Default simulation configuration file. |
| | | 25 | | private const string _defaultSimulationConfigFile = "7_quadcopters.pbtxt"; |
| | | 26 | | |
| | | 27 | | // Default simulator configuration file. |
| | | 28 | | private const string _defaultSimulatorConfigFile = "simulator.pbtxt"; |
| | | 29 | | |
| | | 30 | | // Map from the agent type to the prefab class name. |
| | | 31 | | // The prefab class must exist in the Resources/Prefabs directory. |
| | 0 | 32 | | private static readonly Dictionary<Configs.AgentType, string> _agentTypePrefabMap = new() { |
| | | 33 | | { Configs.AgentType.Vessel, "Vessel" }, |
| | | 34 | | { Configs.AgentType.ShoreBattery, "ShoreBattery" }, |
| | | 35 | | { Configs.AgentType.CarrierInterceptor, "CarrierInterceptor" }, |
| | | 36 | | { Configs.AgentType.MissileInterceptor, "MissileInterceptor" }, |
| | | 37 | | { Configs.AgentType.FixedWingThreat, "FixedWingThreat" }, |
| | | 38 | | { Configs.AgentType.RotaryWingThreat, "RotaryWingThreat" }, |
| | | 39 | | }; |
| | | 40 | | |
| | 0 | 41 | | public static SimManager Instance { get; private set; } |
| | | 42 | | |
| | | 43 | | // Simulation configuration. |
| | 0 | 44 | | public Configs.SimulationConfig SimulationConfig { get; set; } |
| | | 45 | | |
| | | 46 | | // Simulator configuration. |
| | 0 | 47 | | public Configs.SimulatorConfig SimulatorConfig { get; set; } |
| | | 48 | | |
| | | 49 | | // Simulation time. |
| | 0 | 50 | | public float ElapsedTime { get; private set; } = 0f; |
| | 0 | 51 | | public bool IsPaused { get; private set; } = false; |
| | | 52 | | |
| | | 53 | | // If true, the simulation is currently running. |
| | 0 | 54 | | public bool IsRunning { get; private set; } = false; |
| | | 55 | | |
| | | 56 | | // If true, automatically restart the simulation. |
| | 0 | 57 | | public bool AutoRestartOnEnd { get; set; } = true; |
| | | 58 | | |
| | 0 | 59 | | public string Timestamp { get; private set; } = ""; |
| | | 60 | | |
| | | 61 | | // Lists of all agents in the simulation. |
| | 0 | 62 | | private List<IAgent> _interceptors = new List<IAgent>(); |
| | 0 | 63 | | private List<IAgent> _threats = new List<IAgent>(); |
| | 0 | 64 | | private List<IAgent> _dummyAgents = new List<IAgent>(); |
| | | 65 | | |
| | 0 | 66 | | public IReadOnlyList<IAgent> Interceptors => _interceptors.AsReadOnly(); |
| | 0 | 67 | | public IReadOnlyList<IAgent> Threats => _threats.AsReadOnly(); |
| | 0 | 68 | | public IReadOnlyList<IAgent> Agents => Interceptors.Concat(Threats).ToList().AsReadOnly(); |
| | | 69 | | |
| | | 70 | | // Interceptor and threat costs. |
| | 0 | 71 | | public float CostLaunchedInterceptors { get; private set; } = 0f; |
| | 0 | 72 | | public float CostDestroyedThreats { get; private set; } = 0f; |
| | | 73 | | |
| | | 74 | | // Track the number of interceptors and threats spawned and terminated. |
| | 0 | 75 | | private int _numInterceptorsSpawned = 0; |
| | 0 | 76 | | private int _numThreatsSpawned = 0; |
| | 0 | 77 | | private int _numThreatsTerminated = 0; |
| | | 78 | | |
| | 0 | 79 | | public void StartSimulation() { |
| | 0 | 80 | | IsRunning = true; |
| | 0 | 81 | | OnSimulationStarted?.Invoke(); |
| | 0 | 82 | | Debug.Log("Simulation started."); |
| | 0 | 83 | | UIManager.Instance.LogActionMessage("[SIM] Simulation started."); |
| | | 84 | | |
| | 0 | 85 | | InitializeLaunchers(); |
| | 0 | 86 | | InitializeThreats(); |
| | 0 | 87 | | } |
| | | 88 | | |
| | 0 | 89 | | public void EndSimulation() { |
| | 0 | 90 | | IsRunning = false; |
| | 0 | 91 | | OnSimulationEnded?.Invoke(); |
| | 0 | 92 | | Debug.Log("Simulation ended."); |
| | 0 | 93 | | UIManager.Instance.LogActionMessage("[SIM] Simulation ended."); |
| | | 94 | | |
| | | 95 | | // Clear existing interceptors and threats. |
| | 0 | 96 | | foreach (var interceptor in _interceptors) { |
| | 0 | 97 | | if (interceptor as MonoBehaviour != null) { |
| | 0 | 98 | | Destroy(interceptor.gameObject); |
| | 0 | 99 | | } |
| | 0 | 100 | | } |
| | 0 | 101 | | foreach (var threat in _threats) { |
| | 0 | 102 | | if (threat as MonoBehaviour != null) { |
| | 0 | 103 | | Destroy(threat.gameObject); |
| | 0 | 104 | | } |
| | 0 | 105 | | } |
| | 0 | 106 | | foreach (var dummyAgent in _dummyAgents) { |
| | 0 | 107 | | if (dummyAgent as MonoBehaviour != null) { |
| | 0 | 108 | | Destroy(dummyAgent.gameObject); |
| | 0 | 109 | | } |
| | 0 | 110 | | } |
| | | 111 | | |
| | 0 | 112 | | _interceptors.Clear(); |
| | 0 | 113 | | _threats.Clear(); |
| | 0 | 114 | | _dummyAgents.Clear(); |
| | 0 | 115 | | } |
| | | 116 | | |
| | 0 | 117 | | public void PostSimulation() { |
| | 0 | 118 | | if (AutoRestartOnEnd) { |
| | 0 | 119 | | ResetAndStartSimulation(); |
| | 0 | 120 | | } |
| | 0 | 121 | | } |
| | | 122 | | |
| | 0 | 123 | | public void PauseSimulation() { |
| | 0 | 124 | | IsPaused = true; |
| | 0 | 125 | | SetGameSpeed(); |
| | 0 | 126 | | } |
| | | 127 | | |
| | 0 | 128 | | public void ResumeSimulation() { |
| | 0 | 129 | | IsPaused = false; |
| | 0 | 130 | | SetGameSpeed(); |
| | 0 | 131 | | } |
| | | 132 | | |
| | 0 | 133 | | public void QuitSimulation() { |
| | 0 | 134 | | Application.Quit(); |
| | 0 | 135 | | } |
| | | 136 | | |
| | 0 | 137 | | public void ResetAndStartSimulation() { |
| | 0 | 138 | | ElapsedTime = 0f; |
| | 0 | 139 | | CostLaunchedInterceptors = 0f; |
| | 0 | 140 | | CostDestroyedThreats = 0f; |
| | | 141 | | |
| | 0 | 142 | | _numInterceptorsSpawned = 0; |
| | 0 | 143 | | _numThreatsSpawned = 0; |
| | 0 | 144 | | _numThreatsTerminated = 0; |
| | | 145 | | |
| | 0 | 146 | | StartSimulation(); |
| | 0 | 147 | | } |
| | | 148 | | |
| | 0 | 149 | | public void LoadNewSimulationConfig(string simulationConfigFile) { |
| | 0 | 150 | | if (IsRunning) { |
| | 0 | 151 | | EndSimulation(); |
| | 0 | 152 | | } |
| | 0 | 153 | | LoadSimConfigs(simulationConfigFile); |
| | 0 | 154 | | SetGameSpeed(); |
| | | 155 | | |
| | 0 | 156 | | if (SimulationConfig != null) { |
| | 0 | 157 | | Debug.Log($"Loaded new simulation configuration: {simulationConfigFile}."); |
| | 0 | 158 | | ResetAndStartSimulation(); |
| | 0 | 159 | | } else { |
| | 0 | 160 | | Debug.LogError($"Failed to load simulation configuration: {simulationConfigFile}."); |
| | 0 | 161 | | } |
| | 0 | 162 | | } |
| | | 163 | | |
| | | 164 | | // Create an interceptor based on the provided configuration. |
| | 0 | 165 | | public IInterceptor CreateInterceptor(Configs.AgentConfig config, Simulation.State initialState) { |
| | 0 | 166 | | if (config == null) { |
| | 0 | 167 | | return null; |
| | | 168 | | } |
| | | 169 | | |
| | | 170 | | // Load the static configuration. |
| | 0 | 171 | | Configs.StaticConfig staticConfig = ConfigLoader.LoadStaticConfig(config.ConfigFile); |
| | 0 | 172 | | if (staticConfig == null) { |
| | 0 | 173 | | return null; |
| | | 174 | | } |
| | | 175 | | |
| | 0 | 176 | | GameObject interceptorObject = null; |
| | 0 | 177 | | if (_agentTypePrefabMap.TryGetValue(staticConfig.AgentType, out var prefab)) { |
| | 0 | 178 | | interceptorObject = CreateAgent(config, initialState, prefab); |
| | 0 | 179 | | } |
| | 0 | 180 | | if (interceptorObject == null) { |
| | 0 | 181 | | return null; |
| | | 182 | | } |
| | | 183 | | |
| | 0 | 184 | | IInterceptor interceptor = interceptorObject.GetComponent<IInterceptor>(); |
| | 0 | 185 | | interceptor.HierarchicalAgent = new HierarchicalAgent(interceptor); |
| | 0 | 186 | | interceptor.StaticConfig = staticConfig; |
| | 0 | 187 | | interceptor.OnTerminated += (interceptor) => _interceptors.Remove(interceptor); |
| | 0 | 188 | | _interceptors.Add(interceptor); |
| | 0 | 189 | | ++_numInterceptorsSpawned; |
| | | 190 | | |
| | | 191 | | // Assign a unique and simple ID. |
| | 0 | 192 | | interceptorObject.name = $"{staticConfig.Name}_Interceptor_{_numInterceptorsSpawned}"; |
| | | 193 | | |
| | | 194 | | // Add the interceptor's unit cost to the total cost. |
| | 0 | 195 | | CostLaunchedInterceptors += staticConfig.Cost; |
| | | 196 | | |
| | 0 | 197 | | OnNewInterceptor?.Invoke(interceptor); |
| | 0 | 198 | | return interceptor; |
| | 0 | 199 | | } |
| | | 200 | | |
| | | 201 | | // Create a threat based on the provided configuration. |
| | | 202 | | // Returns the created threat instance, or null if creation failed. |
| | 0 | 203 | | public IThreat CreateThreat(Configs.AgentConfig config) { |
| | 0 | 204 | | if (config == null) { |
| | 0 | 205 | | return null; |
| | | 206 | | } |
| | | 207 | | |
| | | 208 | | // Load the static configuration. |
| | 0 | 209 | | Configs.StaticConfig staticConfig = ConfigLoader.LoadStaticConfig(config.ConfigFile); |
| | 0 | 210 | | if (staticConfig == null) { |
| | 0 | 211 | | return null; |
| | | 212 | | } |
| | | 213 | | |
| | 0 | 214 | | GameObject threatObject = null; |
| | 0 | 215 | | if (_agentTypePrefabMap.TryGetValue(staticConfig.AgentType, out var prefab)) { |
| | 0 | 216 | | threatObject = CreateRandomAgent(config, prefab); |
| | 0 | 217 | | } |
| | 0 | 218 | | if (threatObject == null) { |
| | 0 | 219 | | return null; |
| | | 220 | | } |
| | | 221 | | |
| | 0 | 222 | | IThreat threat = threatObject.GetComponent<IThreat>(); |
| | 0 | 223 | | threat.HierarchicalAgent = new HierarchicalAgent(threat); |
| | 0 | 224 | | threat.StaticConfig = staticConfig; |
| | 0 | 225 | | threat.OnMiss += RegisterThreatMiss; |
| | 0 | 226 | | threat.OnTerminated += RegisterThreatTerminated; |
| | 0 | 227 | | _threats.Add(threat); |
| | 0 | 228 | | ++_numThreatsSpawned; |
| | | 229 | | |
| | | 230 | | // Assign a unique name. |
| | 0 | 231 | | threatObject.name = $"{staticConfig.Name}_Threat_{_numThreatsSpawned}"; |
| | | 232 | | |
| | 0 | 233 | | OnNewThreat?.Invoke(threat); |
| | 0 | 234 | | return threat; |
| | 0 | 235 | | } |
| | | 236 | | |
| | 0 | 237 | | public IAgent CreateDummyAgent(in Vector3 position, in Vector3 velocity) { |
| | 0 | 238 | | GameObject dummyAgentPrefab = Resources.Load<GameObject>($"Prefabs/DummyAgent"); |
| | 0 | 239 | | GameObject dummyAgentObject = Instantiate(dummyAgentPrefab, position, Quaternion.identity); |
| | 0 | 240 | | var dummyAgent = dummyAgentObject.GetComponent<IAgent>(); |
| | 0 | 241 | | dummyAgent.Velocity = velocity; |
| | 0 | 242 | | _dummyAgents.Add(dummyAgent); |
| | 0 | 243 | | dummyAgent.OnTerminated += (agent) => _dummyAgents.Remove(agent); |
| | 0 | 244 | | return dummyAgent; |
| | 0 | 245 | | } |
| | | 246 | | |
| | 0 | 247 | | public void DestroyDummyAgent(IAgent dummyAgent) { |
| | 0 | 248 | | dummyAgent.Terminate(); |
| | 0 | 249 | | } |
| | | 250 | | |
| | | 251 | | // Create an agent based on the provided configuration and prefab name. |
| | | 252 | | private GameObject CreateAgent(Configs.AgentConfig config, Simulation.State initialState, |
| | 0 | 253 | | string prefabName) { |
| | 0 | 254 | | GameObject prefab = Resources.Load<GameObject>($"Prefabs/{prefabName}"); |
| | 0 | 255 | | if (prefab == null) { |
| | 0 | 256 | | Debug.LogError($"Prefab {prefabName} not found in Resources/Prefabs directory."); |
| | 0 | 257 | | return null; |
| | | 258 | | } |
| | | 259 | | |
| | 0 | 260 | | GameObject agentObject = |
| | | 261 | | Instantiate(prefab, Coordinates3.FromProto(initialState.Position), Quaternion.identity); |
| | 0 | 262 | | IAgent agent = agentObject.GetComponent<IAgent>(); |
| | 0 | 263 | | agent.AgentConfig = config; |
| | 0 | 264 | | Vector3 velocity = Coordinates3.FromProto(initialState.Velocity); |
| | 0 | 265 | | agent.Velocity = velocity; |
| | | 266 | | |
| | | 267 | | // Set the rotation to face the initial velocity. |
| | 0 | 268 | | Quaternion targetRotation = Quaternion.LookRotation(velocity, Vector3.up); |
| | 0 | 269 | | agentObject.transform.rotation = targetRotation; |
| | 0 | 270 | | return agentObject; |
| | 0 | 271 | | } |
| | | 272 | | |
| | | 273 | | // Create a random agent based on the provided configuration and prefab name. |
| | 0 | 274 | | private GameObject CreateRandomAgent(Configs.AgentConfig config, string prefabName) { |
| | | 275 | | // Randomize the position and the velocity. |
| | 0 | 276 | | Vector3 positionNoise = Utilities.GenerateRandomNoise(config.StandardDeviation.Position); |
| | 0 | 277 | | Vector3 velocityNoise = Utilities.GenerateRandomNoise(config.StandardDeviation.Velocity); |
| | 0 | 278 | | var initialState = new Simulation.State() { |
| | | 279 | | Position = Coordinates3.ToProto(Coordinates3.FromProto(config.InitialState.Position) + |
| | | 280 | | positionNoise), |
| | | 281 | | Velocity = Coordinates3.ToProto(Coordinates3.FromProto(config.InitialState.Velocity) + |
| | | 282 | | velocityNoise), |
| | | 283 | | }; |
| | 0 | 284 | | return CreateAgent(config, initialState, prefabName); |
| | 0 | 285 | | } |
| | | 286 | | |
| | 0 | 287 | | private void Awake() { |
| | 0 | 288 | | if (Instance != null && Instance != this) { |
| | 0 | 289 | | Destroy(gameObject); |
| | 0 | 290 | | return; |
| | | 291 | | } |
| | 0 | 292 | | Instance = this; |
| | 0 | 293 | | DontDestroyOnLoad(gameObject); |
| | | 294 | | |
| | 0 | 295 | | LoadSimConfigs(_defaultSimulationConfigFile); |
| | 0 | 296 | | Timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss"); |
| | 0 | 297 | | } |
| | | 298 | | |
| | 0 | 299 | | private void Start() { |
| | 0 | 300 | | IsPaused = false; |
| | 0 | 301 | | if (!RunManager.Instance.HasRunConfig()) { |
| | 0 | 302 | | StartSimulation(); |
| | 0 | 303 | | ResumeSimulation(); |
| | 0 | 304 | | } |
| | 0 | 305 | | } |
| | | 306 | | |
| | 0 | 307 | | private void FixedUpdate() { |
| | 0 | 308 | | if (IsRunning && !IsPaused && ElapsedTime < SimulationConfig.EndTime) { |
| | 0 | 309 | | ElapsedTime += Time.fixedDeltaTime; |
| | 0 | 310 | | } |
| | 0 | 311 | | } |
| | | 312 | | |
| | 0 | 313 | | private void LateUpdate() { |
| | 0 | 314 | | if (ShouldEndSimulation()) { |
| | 0 | 315 | | EndSimulation(); |
| | 0 | 316 | | PostSimulation(); |
| | 0 | 317 | | } |
| | 0 | 318 | | } |
| | | 319 | | |
| | 0 | 320 | | private void InitializeLaunchers() { |
| | 0 | 321 | | foreach (var swarmConfig in SimulationConfig.InterceptorSwarmConfigs) { |
| | 0 | 322 | | IInterceptor launcher = |
| | | 323 | | CreateInterceptor(swarmConfig.AgentConfig, swarmConfig.AgentConfig.InitialState); |
| | 0 | 324 | | OnNewLauncher?.Invoke(launcher); |
| | 0 | 325 | | } |
| | 0 | 326 | | } |
| | | 327 | | |
| | 0 | 328 | | private void InitializeThreats() { |
| | 0 | 329 | | foreach (var swarmConfig in SimulationConfig.ThreatSwarmConfigs) { |
| | 0 | 330 | | for (int i = 0; i < swarmConfig.NumAgents; ++i) { |
| | 0 | 331 | | CreateThreat(swarmConfig.AgentConfig); |
| | 0 | 332 | | } |
| | 0 | 333 | | } |
| | 0 | 334 | | } |
| | | 335 | | |
| | 0 | 336 | | private void LoadSimConfigs(string simulationConfigFile) { |
| | 0 | 337 | | SimulatorConfig = ConfigLoader.LoadSimulatorConfig(_defaultSimulatorConfigFile); |
| | | 338 | | // If a run configuration is provided, enable telemetry logging and event logging. |
| | 0 | 339 | | if (RunManager.Instance.HasRunConfig()) { |
| | 0 | 340 | | SimulatorConfig.EnableTelemetryLogging = true; |
| | 0 | 341 | | SimulatorConfig.EnableEventLogging = true; |
| | 0 | 342 | | } |
| | 0 | 343 | | SimulationConfig = ConfigLoader.LoadSimulationConfig(simulationConfigFile); |
| | 0 | 344 | | } |
| | | 345 | | |
| | 0 | 346 | | private void SetGameSpeed() { |
| | 0 | 347 | | if (IsPaused) { |
| | 0 | 348 | | Time.fixedDeltaTime = 0; |
| | 0 | 349 | | SetTimeScale(timeScale: 0); |
| | 0 | 350 | | } else { |
| | 0 | 351 | | Time.fixedDeltaTime = 1.0f / SimulatorConfig.PhysicsUpdateRate; |
| | 0 | 352 | | SetTimeScale(SimulationConfig.TimeScale); |
| | 0 | 353 | | } |
| | 0 | 354 | | } |
| | | 355 | | |
| | 0 | 356 | | private void SetTimeScale(float timeScale) { |
| | 0 | 357 | | Time.timeScale = timeScale; |
| | | 358 | | // Time.fixedDeltaTime is derived from the simulator configuration. |
| | 0 | 359 | | Time.maximumDeltaTime = Time.fixedDeltaTime * 3; |
| | 0 | 360 | | } |
| | | 361 | | |
| | 0 | 362 | | private void RegisterThreatMiss(IThreat threat) { |
| | 0 | 363 | | CostDestroyedThreats += threat.StaticConfig.Cost; |
| | 0 | 364 | | } |
| | | 365 | | |
| | 0 | 366 | | private void RegisterThreatTerminated(IAgent threat) { |
| | 0 | 367 | | _threats.Remove(threat); |
| | 0 | 368 | | ++_numThreatsTerminated; |
| | 0 | 369 | | } |
| | | 370 | | |
| | 0 | 371 | | private bool ShouldEndSimulation() { |
| | 0 | 372 | | if (IsRunning && ElapsedTime >= SimulationConfig.EndTime) { |
| | 0 | 373 | | return true; |
| | | 374 | | } |
| | | 375 | | // The simulation can be ended before the actual end time if there is a run configuration and |
| | | 376 | | // all spawned threats have been terminated. |
| | 0 | 377 | | if (RunManager.Instance.HasRunConfig() && _numThreatsSpawned > 0 && |
| | 0 | 378 | | _numThreatsTerminated >= _numThreatsSpawned) { |
| | 0 | 379 | | return true; |
| | | 380 | | } |
| | 0 | 381 | | return false; |
| | 0 | 382 | | } |
| | | 383 | | } |