| | 1 | | using System.Collections; |
| | 2 | | using System.Collections.Generic; |
| | 3 | | using System.Linq; |
| | 4 | | using UnityEngine; |
| | 5 | |
|
| | 6 | | /// <summary> |
| | 7 | | /// Manages the simulation by handling missiles, targets, and their assignments. |
| | 8 | | /// Implements the Singleton pattern to ensure only one instance exists. |
| | 9 | | /// </summary> |
| | 10 | | public class SimManager : MonoBehaviour { |
| | 11 | | public SimulatorConfig simulatorConfig; |
| | 12 | |
|
| | 13 | | /// <summary> |
| | 14 | | /// Singleton instance of SimManager. |
| | 15 | | /// </summary> |
| 520 | 16 | | public static SimManager Instance { get; set; } |
| | 17 | |
|
| | 18 | | /// <summary> |
| | 19 | | /// Configuration settings for the simulation. |
| | 20 | | /// </summary> |
| | 21 | | [SerializeField] |
| | 22 | | public SimulationConfig simulationConfig; |
| | 23 | |
|
| 2 | 24 | | public string defaultConfig = "1_salvo_1_hydra_7_drones.json"; |
| | 25 | |
|
| 2 | 26 | | private List<Interceptor> _activeInterceptors = new List<Interceptor>(); |
| | 27 | |
|
| 2 | 28 | | private List<Interceptor> _interceptorObjects = new List<Interceptor>(); |
| 2 | 29 | | private List<Threat> _threatObjects = new List<Threat>(); |
| | 30 | |
|
| 2 | 31 | | private List<GameObject> _dummyAgentObjects = new List<GameObject>(); |
| 2 | 32 | | private Dictionary<(Vector3, Vector3), GameObject> _dummyAgentTable = |
| | 33 | | new Dictionary<(Vector3, Vector3), GameObject>(); |
| | 34 | |
|
| | 35 | | // Inclusive of ALL, including SUBMUNITIONS SWARMS |
| | 36 | | // The bool indicates whether the agent is ACTIVE (true) or INACTIVE (false) |
| 2 | 37 | | private List<List<(Agent, bool)>> _interceptorSwarms = new List<List<(Agent, bool)>>(); |
| 2 | 38 | | private List<List<(Agent, bool)>> _submunitionsSwarms = new List<List<(Agent, bool)>>(); |
| 2 | 39 | | private List<List<(Agent, bool)>> _threatSwarms = new List<List<(Agent, bool)>>(); |
| | 40 | |
|
| 2 | 41 | | private Dictionary<Agent, List<(Agent, bool)>> _interceptorSwarmMap = |
| | 42 | | new Dictionary<Agent, List<(Agent, bool)>>(); |
| | 43 | |
|
| 2 | 44 | | private Dictionary<Agent, List<(Agent, bool)>> _submunitionsSwarmMap = |
| | 45 | | new Dictionary<Agent, List<(Agent, bool)>>(); |
| 2 | 46 | | private Dictionary<Agent, List<(Agent, bool)>> _threatSwarmMap = |
| | 47 | | new Dictionary<Agent, List<(Agent, bool)>>(); |
| | 48 | |
|
| | 49 | | // Maps a submunition swarm to its corresponding interceptor swarm |
| 2 | 50 | | private Dictionary<List<(Agent, bool)>, List<(Agent, bool)>> _submunitionInterceptorSwarmMap = |
| | 51 | | new Dictionary<List<(Agent, bool)>, List<(Agent, bool)>>(); |
| | 52 | |
|
| | 53 | | // Events so people can subscribe to changes in each of the swarm tables |
| | 54 | | public delegate void SwarmEventHandler(List<List<(Agent, bool)>> swarm); |
| | 55 | | public event SwarmEventHandler OnInterceptorSwarmChanged; |
| | 56 | | public event SwarmEventHandler OnSubmunitionsSwarmChanged; |
| | 57 | | public event SwarmEventHandler OnThreatSwarmChanged; |
| | 58 | | ////////////////////////////////////////////////////////////////////// |
| | 59 | |
|
| 2 | 60 | | private float _elapsedSimulationTime = 0f; |
| 2 | 61 | | private bool _isSimulationPaused = false; |
| | 62 | |
|
| 2 | 63 | | private float _costLaunchedInterceptors = 0f; |
| 2 | 64 | | private float _costDestroyedThreats = 0f; |
| | 65 | |
|
| | 66 | | public delegate void SimulationEventHandler(); |
| | 67 | | public event SimulationEventHandler OnSimulationEnded; |
| | 68 | | public event SimulationEventHandler OnSimulationStarted; |
| | 69 | |
|
| | 70 | | public delegate void NewThreatEventHandler(Threat threat); |
| | 71 | | public event NewThreatEventHandler OnNewThreat; |
| | 72 | |
|
| | 73 | | public delegate void NewInterceptorEventHandler(Interceptor interceptor); |
| | 74 | | public event NewInterceptorEventHandler OnNewInterceptor; |
| | 75 | |
|
| | 76 | | /// <summary> |
| | 77 | | /// Gets the elapsed simulation time. |
| | 78 | | /// </summary> |
| | 79 | | /// <returns>The elapsed time in seconds.</returns> |
| 471 | 80 | | public double GetElapsedSimulationTime() { |
| 471 | 81 | | return _elapsedSimulationTime; |
| 471 | 82 | | } |
| | 83 | |
|
| | 84 | | /// <summary> |
| | 85 | | /// Gets the total cost of launched interceptors. |
| | 86 | | /// </summary> |
| | 87 | | /// <returns>The total cost of launched interceptors.</returns> |
| 5 | 88 | | public double GetCostLaunchedInterceptors() { |
| 5 | 89 | | return _costLaunchedInterceptors; |
| 5 | 90 | | } |
| | 91 | |
|
| | 92 | | /// <summary> |
| | 93 | | /// Gets the total cost of destroyed threats. |
| | 94 | | /// </summary> |
| | 95 | | /// <returns>The total cost of destroyed threats.</returns> |
| 5 | 96 | | public double GetCostDestroyedThreats() { |
| 5 | 97 | | return _costDestroyedThreats; |
| 5 | 98 | | } |
| | 99 | |
|
| 0 | 100 | | public List<Interceptor> GetActiveInterceptors() { |
| 0 | 101 | | return _activeInterceptors; |
| 0 | 102 | | } |
| | 103 | |
|
| 0 | 104 | | public List<Threat> GetActiveThreats() { |
| 0 | 105 | | return _threatObjects.Where(threat => !threat.IsHit()).ToList(); |
| 0 | 106 | | } |
| | 107 | |
|
| 0 | 108 | | public List<Agent> GetActiveAgents() { |
| 0 | 109 | | return _activeInterceptors.ConvertAll(interceptor => interceptor as Agent) |
| 0 | 110 | | .Concat(GetActiveThreats().ConvertAll(threat => threat as Agent)) |
| | 111 | | .ToList(); |
| 0 | 112 | | } |
| | 113 | |
|
| 0 | 114 | | public string GenerateSwarmTitle(List<(Agent, bool)> swarm, int index) { |
| 0 | 115 | | string swarmTitle = swarm[0].Item1.name; |
| 0 | 116 | | swarmTitle = swarmTitle.Split('_')[0]; |
| 0 | 117 | | swarmTitle += $"_{index}"; |
| 0 | 118 | | return swarmTitle; |
| 0 | 119 | | } |
| | 120 | |
|
| 0 | 121 | | public string GenerateInterceptorSwarmTitle(List<(Agent, bool)> swarm) { |
| 0 | 122 | | return GenerateSwarmTitle(swarm, _interceptorSwarms.IndexOf(swarm)); |
| 0 | 123 | | } |
| | 124 | |
|
| 0 | 125 | | public string GenerateSubmunitionsSwarmTitle(List<(Agent, bool)> swarm) { |
| 0 | 126 | | return GenerateSwarmTitle(swarm, LookupSubmunitionSwarnIndexInInterceptorSwarm(swarm)); |
| 0 | 127 | | } |
| | 128 | |
|
| 0 | 129 | | public string GenerateThreatSwarmTitle(List<(Agent, bool)> swarm) { |
| 0 | 130 | | return GenerateSwarmTitle(swarm, _threatSwarms.IndexOf(swarm)); |
| 0 | 131 | | } |
| | 132 | |
|
| 1 | 133 | | void Awake() { |
| | 134 | | // Ensure only one instance of SimManager exists |
| 2 | 135 | | if (Instance == null) { |
| 1 | 136 | | Instance = this; |
| 1 | 137 | | DontDestroyOnLoad(gameObject); |
| 1 | 138 | | } else { |
| 0 | 139 | | Destroy(gameObject); |
| 0 | 140 | | } |
| 1 | 141 | | simulationConfig = ConfigLoader.LoadSimulationConfig("1_salvo_1_hydra_7_drones.json"); |
| 1 | 142 | | simulatorConfig = ConfigLoader.LoadSimulatorConfig(); |
| 1 | 143 | | Debug.Log(simulationConfig); |
| 1 | 144 | | } |
| | 145 | |
|
| 1 | 146 | | void Start() { |
| | 147 | | // Slow down time by simulationConfig.timeScale |
| 2 | 148 | | if (Instance == this) { |
| 1 | 149 | | _isSimulationPaused = false; |
| 1 | 150 | | StartSimulation(); |
| 1 | 151 | | ResumeSimulation(); |
| 1 | 152 | | } |
| 1 | 153 | | } |
| | 154 | |
|
| 2 | 155 | | public void SetTimeScale(float timeScale) { |
| 2 | 156 | | Time.timeScale = timeScale; |
| 2 | 157 | | Time.maximumDeltaTime = Time.fixedDeltaTime * 3; |
| | 158 | |
|
| | 159 | | // Time.fixedDeltaTime is set in the simulator.json |
| 2 | 160 | | } |
| | 161 | |
|
| 1 | 162 | | public void StartSimulation() { |
| 1 | 163 | | OnSimulationStarted?.Invoke(); |
| 1 | 164 | | InitializeSimulation(); |
| 1 | 165 | | } |
| | 166 | |
|
| 0 | 167 | | public void PauseSimulation() { |
| 0 | 168 | | SetTimeScale(0); |
| 0 | 169 | | Time.fixedDeltaTime = 0; |
| 0 | 170 | | _isSimulationPaused = true; |
| 0 | 171 | | } |
| | 172 | |
|
| 1 | 173 | | public void ResumeSimulation() { |
| 1 | 174 | | Time.fixedDeltaTime = (float)(1.0f / simulatorConfig.physicsUpdateRate); |
| 1 | 175 | | SetTimeScale(simulationConfig.timeScale); |
| 1 | 176 | | _isSimulationPaused = false; |
| 1 | 177 | | } |
| | 178 | |
|
| 1 | 179 | | public bool IsSimulationPaused() { |
| 1 | 180 | | return _isSimulationPaused; |
| 1 | 181 | | } |
| | 182 | |
|
| 1 | 183 | | private void InitializeSimulation() { |
| 2 | 184 | | if (!IsSimulationPaused()) { |
| | 185 | | // If it wasn't paused, we need to update the time scales NOW |
| 1 | 186 | | SetTimeScale(simulationConfig.timeScale); |
| 1 | 187 | | Time.fixedDeltaTime = (float)(1.0f / simulatorConfig.physicsUpdateRate); |
| | 188 | | // If the simulation WAS paused, then ResumeSimulation will handle |
| | 189 | | // updating the time scale and fixed delta time from the newly loaded config files |
| 1 | 190 | | } |
| | 191 | |
|
| | 192 | | // Invoke the simulation started event to let listeners |
| | 193 | | // know to invoke their own handler behavior |
| 1 | 194 | | OnSimulationStarted?.Invoke(); |
| 1 | 195 | | List<Interceptor> missiles = new List<Interceptor>(); |
| | 196 | | // Create missiles based on config |
| 6 | 197 | | foreach (var swarmConfig in simulationConfig.interceptor_swarm_configs) { |
| 1 | 198 | | List<Agent> swarm = new List<Agent>(); |
| 5 | 199 | | for (int i = 0; i < swarmConfig.num_agents; i++) { |
| 1 | 200 | | Interceptor interceptor = CreateInterceptor(swarmConfig.dynamic_agent_config); |
| 1 | 201 | | swarm.Add(interceptor); |
| 1 | 202 | | } |
| 1 | 203 | | AddInterceptorSwarm(swarm); |
| 1 | 204 | | } |
| 1 | 205 | | IADS.Instance.RequestThreatAssignment(_interceptorObjects); |
| | 206 | |
|
| 1 | 207 | | List<Agent> targets = new List<Agent>(); |
| | 208 | | // Create targets based on config |
| 6 | 209 | | foreach (var swarmConfig in simulationConfig.threat_swarm_configs) { |
| 1 | 210 | | List<Agent> swarm = new List<Agent>(); |
| 23 | 211 | | for (int i = 0; i < swarmConfig.num_agents; i++) { |
| 7 | 212 | | Threat threat = CreateThreat(swarmConfig.dynamic_agent_config); |
| 7 | 213 | | swarm.Add(threat); |
| 7 | 214 | | } |
| 1 | 215 | | AddThreatSwarm(swarm); |
| 1 | 216 | | } |
| 1 | 217 | | } |
| | 218 | |
|
| 1 | 219 | | public void AddInterceptorSwarm(List<Agent> swarm) { |
| 2 | 220 | | List<(Agent, bool)> swarmTuple = swarm.ConvertAll(agent => (agent, true)); |
| 1 | 221 | | _interceptorSwarms.Add(swarmTuple); |
| 6 | 222 | | foreach (var interceptor in swarm) { |
| 1 | 223 | | _interceptorSwarmMap[interceptor] = swarmTuple; |
| 1 | 224 | | } |
| 1 | 225 | | OnInterceptorSwarmChanged?.Invoke(_interceptorSwarms); |
| 1 | 226 | | } |
| | 227 | |
|
| 0 | 228 | | public void AddSubmunitionsSwarm(List<Agent> swarm) { |
| 0 | 229 | | List<(Agent, bool)> swarmTuple = swarm.ConvertAll(agent => (agent, true)); |
| 0 | 230 | | _submunitionsSwarms.Add(swarmTuple); |
| 0 | 231 | | foreach (var submunition in swarm) { |
| 0 | 232 | | _submunitionsSwarmMap[submunition] = swarmTuple; |
| 0 | 233 | | } |
| 0 | 234 | | AddInterceptorSwarm(swarm); |
| 0 | 235 | | _submunitionInterceptorSwarmMap[swarmTuple] = _interceptorSwarms[_interceptorSwarms.Count - 1]; |
| 0 | 236 | | OnSubmunitionsSwarmChanged?.Invoke(_submunitionsSwarms); |
| 0 | 237 | | } |
| | 238 | |
|
| 0 | 239 | | public int LookupSubmunitionSwarnIndexInInterceptorSwarm(List<(Agent, bool)> swarm) { |
| 0 | 240 | | if (_submunitionInterceptorSwarmMap.TryGetValue(swarm, out var interceptorSwarm)) { |
| 0 | 241 | | return _interceptorSwarms.IndexOf(interceptorSwarm); |
| | 242 | | } |
| 0 | 243 | | return -1; // Return -1 if the swarm is not found |
| 0 | 244 | | } |
| | 245 | |
|
| 1 | 246 | | public void AddThreatSwarm(List<Agent> swarm) { |
| 8 | 247 | | List<(Agent, bool)> swarmTuple = swarm.ConvertAll(agent => (agent, true)); |
| 1 | 248 | | _threatSwarms.Add(swarmTuple); |
| 24 | 249 | | foreach (var threat in swarm) { |
| 7 | 250 | | _threatSwarmMap[threat] = swarmTuple; |
| 7 | 251 | | } |
| 1 | 252 | | OnThreatSwarmChanged?.Invoke(_threatSwarms); |
| 1 | 253 | | } |
| | 254 | |
|
| 0 | 255 | | public Vector3 GetAllAgentsCenter() { |
| 0 | 256 | | List<Agent> allAgents = _interceptorObjects.ConvertAll(interceptor => interceptor as Agent) |
| 0 | 257 | | .Concat(_threatObjects.ConvertAll(threat => threat as Agent)) |
| | 258 | | .ToList(); |
| 0 | 259 | | return GetSwarmCenter(allAgents); |
| 0 | 260 | | } |
| | 261 | |
|
| 0 | 262 | | public Vector3 GetSwarmCenter(List<Agent> swarm) { |
| 0 | 263 | | if (swarm.Count == 0) { |
| 0 | 264 | | return Vector3.zero; |
| | 265 | | } |
| | 266 | |
|
| 0 | 267 | | Vector3 sum = Vector3.zero; |
| 0 | 268 | | int count = 0; |
| 0 | 269 | | int swarmCount = swarm.Count; |
| | 270 | |
|
| 0 | 271 | | for (int i = 0; i < swarmCount; i++) { |
| 0 | 272 | | Agent agent = swarm[i]; |
| 0 | 273 | | if (!agent.IsHit()) { |
| 0 | 274 | | sum += agent.transform.position; |
| 0 | 275 | | count++; |
| 0 | 276 | | } |
| 0 | 277 | | } |
| | 278 | |
|
| 0 | 279 | | return count > 0 ? sum / count : Vector3.zero; |
| 0 | 280 | | } |
| | 281 | |
|
| 0 | 282 | | public List<List<(Agent, bool)>> GetInterceptorSwarms() { |
| 0 | 283 | | return _interceptorSwarms; |
| 0 | 284 | | } |
| | 285 | |
|
| 0 | 286 | | public List<List<(Agent, bool)>> GetSubmunitionsSwarms() { |
| 0 | 287 | | return _submunitionsSwarms; |
| 0 | 288 | | } |
| | 289 | |
|
| 0 | 290 | | public List<List<(Agent, bool)>> GetThreatSwarms() { |
| 0 | 291 | | return _threatSwarms; |
| 0 | 292 | | } |
| | 293 | |
|
| 0 | 294 | | public void AssignInterceptorsToThreats() { |
| 0 | 295 | | IADS.Instance.AssignInterceptorsToThreats(_interceptorObjects); |
| 0 | 296 | | } |
| | 297 | |
|
| 0 | 298 | | public void DestroyInterceptorInSwarm(Interceptor interceptor) { |
| 0 | 299 | | var swarm = _interceptorSwarmMap[interceptor]; |
| 0 | 300 | | int index = swarm.FindIndex(tuple => tuple.Item1 == interceptor); |
| 0 | 301 | | if (index != -1) { |
| 0 | 302 | | swarm[index] = (swarm[index].Item1, false); |
| 0 | 303 | | OnInterceptorSwarmChanged?.Invoke(_interceptorSwarms); |
| 0 | 304 | | } else { |
| 0 | 305 | | Debug.LogError("Interceptor not found in swarm"); |
| 0 | 306 | | } |
| 0 | 307 | | if (swarm.All(tuple => !tuple.Item2)) { |
| | 308 | | // Need to give the CameraController a way to update |
| | 309 | | // to the next swarm if it exists |
| 0 | 310 | | if (CameraController.Instance.cameraMode == CameraMode.FOLLOW_INTERCEPTOR_SWARM) { |
| 0 | 311 | | CameraController.Instance.FollowNextInterceptorSwarm(); |
| 0 | 312 | | } |
| 0 | 313 | | } |
| | 314 | |
|
| | 315 | | // If this also happens to be a submunition, destroy it in the submunition swarm |
| 0 | 316 | | if (_submunitionsSwarmMap.ContainsKey(interceptor)) { |
| 0 | 317 | | DestroySubmunitionInSwarm(interceptor); |
| 0 | 318 | | } |
| 0 | 319 | | } |
| | 320 | |
|
| 0 | 321 | | public void DestroySubmunitionInSwarm(Interceptor submunition) { |
| 0 | 322 | | var swarm = _submunitionsSwarmMap[submunition]; |
| 0 | 323 | | int index = swarm.FindIndex(tuple => tuple.Item1 == submunition); |
| 0 | 324 | | if (index != -1) { |
| 0 | 325 | | swarm[index] = (swarm[index].Item1, false); |
| 0 | 326 | | OnSubmunitionsSwarmChanged?.Invoke(_submunitionsSwarms); |
| 0 | 327 | | } |
| 0 | 328 | | } |
| | 329 | |
|
| 0 | 330 | | public void DestroyThreatInSwarm(Threat threat) { |
| 0 | 331 | | var swarm = _threatSwarmMap[threat]; |
| 0 | 332 | | int index = swarm.FindIndex(tuple => tuple.Item1 == threat); |
| 0 | 333 | | if (index != -1) { |
| 0 | 334 | | swarm[index] = (swarm[index].Item1, false); |
| 0 | 335 | | OnThreatSwarmChanged?.Invoke(_threatSwarms); |
| 0 | 336 | | } |
| 0 | 337 | | if (swarm.All(tuple => !tuple.Item2)) { |
| 0 | 338 | | _threatSwarms.Remove(swarm); |
| 0 | 339 | | if (CameraController.Instance.cameraMode == CameraMode.FOLLOW_THREAT_SWARM) { |
| 0 | 340 | | CameraController.Instance.FollowNextThreatSwarm(); |
| 0 | 341 | | } |
| 0 | 342 | | } |
| 0 | 343 | | } |
| | 344 | |
|
| 0 | 345 | | public void RegisterInterceptorHit(Interceptor interceptor, Threat threat) { |
| 0 | 346 | | _costDestroyedThreats += threat.staticAgentConfig.unitCost; |
| 0 | 347 | | if (interceptor is Interceptor missileComponent) { |
| 0 | 348 | | _activeInterceptors.Remove(missileComponent); |
| 0 | 349 | | } |
| 0 | 350 | | DestroyInterceptorInSwarm(interceptor); |
| 0 | 351 | | DestroyThreatInSwarm(threat); |
| 0 | 352 | | } |
| | 353 | |
|
| 0 | 354 | | public void RegisterInterceptorMiss(Interceptor interceptor, Threat threat) { |
| 0 | 355 | | if (interceptor is Interceptor missileComponent) { |
| 0 | 356 | | _activeInterceptors.Remove(missileComponent); |
| 0 | 357 | | } |
| 0 | 358 | | DestroyInterceptorInSwarm(interceptor); |
| 0 | 359 | | } |
| | 360 | |
|
| 0 | 361 | | public void RegisterThreatHit(Threat threat) { |
| 0 | 362 | | DestroyThreatInSwarm(threat); |
| 0 | 363 | | } |
| | 364 | |
|
| 0 | 365 | | public void RegisterThreatMiss(Threat threat) { |
| 0 | 366 | | DestroyThreatInSwarm(threat); |
| 0 | 367 | | } |
| | 368 | |
|
| 7 | 369 | | private AttackBehavior LoadAttackBehavior(DynamicAgentConfig config) { |
| 7 | 370 | | string threatBehaviorFile = config.attack_behavior; |
| 7 | 371 | | AttackBehavior attackBehavior = AttackBehavior.FromJson(threatBehaviorFile); |
| 7 | 372 | | switch (attackBehavior.attackBehaviorType) { |
| | 373 | | case AttackBehavior.AttackBehaviorType.DIRECT_ATTACK: |
| 7 | 374 | | return DirectAttackBehavior.FromJson(threatBehaviorFile); |
| | 375 | | default: |
| 0 | 376 | | Debug.LogError($"Attack behavior type '{attackBehavior.attackBehaviorType}' not found."); |
| 0 | 377 | | return null; |
| | 378 | | } |
| 7 | 379 | | } |
| | 380 | |
|
| 9 | 381 | | public Agent CreateDummyAgent(Vector3 position, Vector3 velocity) { |
| 16 | 382 | | if (_dummyAgentTable.ContainsKey((position, velocity))) { |
| 7 | 383 | | return _dummyAgentTable[(position, velocity)].GetComponent<Agent>(); |
| | 384 | | } |
| 2 | 385 | | GameObject dummyAgentPrefab = Resources.Load<GameObject>($"Prefabs/DummyAgent"); |
| 2 | 386 | | GameObject dummyAgentObject = Instantiate(dummyAgentPrefab, position, Quaternion.identity); |
| 4 | 387 | | if (!dummyAgentObject.TryGetComponent<Agent>(out _)) { |
| 2 | 388 | | dummyAgentObject.AddComponent<DummyAgent>(); |
| 2 | 389 | | } |
| 2 | 390 | | Rigidbody dummyRigidbody = dummyAgentObject.GetComponent<Rigidbody>(); |
| 2 | 391 | | dummyRigidbody.linearVelocity = velocity; |
| 2 | 392 | | _dummyAgentObjects.Add(dummyAgentObject); |
| 2 | 393 | | _dummyAgentTable[(position, velocity)] = dummyAgentObject; |
| 2 | 394 | | return dummyAgentObject.GetComponent<Agent>(); |
| 9 | 395 | | } |
| | 396 | |
|
| | 397 | | /// <summary> |
| | 398 | | /// Creates a interceptor based on the provided configuration. |
| | 399 | | /// </summary> |
| | 400 | | /// <param name="config">Configuration settings for the interceptor.</param> |
| | 401 | | /// <returns>The created Interceptor instance, or null if creation failed.</returns> |
| 1 | 402 | | public Interceptor CreateInterceptor(DynamicAgentConfig config) { |
| 1 | 403 | | string interceptorModelFile = config.agent_model; |
| 1 | 404 | | interceptorModelFile = "Interceptors/" + interceptorModelFile; |
| 1 | 405 | | StaticAgentConfig interceptorStaticAgentConfig = |
| | 406 | | ConfigLoader.LoadStaticAgentConfig(interceptorModelFile); |
| 1 | 407 | | string agentClass = interceptorStaticAgentConfig.agentClass; |
| | 408 | | // The interceptor class corresponds to the Prefab that must |
| | 409 | | // exist in the Resources/Prefabs folder |
| 1 | 410 | | GameObject interceptorObject = CreateAgent(config, agentClass); |
| | 411 | |
|
| 1 | 412 | | if (interceptorObject == null) |
| 0 | 413 | | return null; |
| | 414 | |
|
| | 415 | | // Interceptor-specific logic |
| 1 | 416 | | switch (config.dynamic_config.sensor_config.type) { |
| | 417 | | case SensorType.IDEAL: |
| 1 | 418 | | interceptorObject.AddComponent<IdealSensor>(); |
| 1 | 419 | | break; |
| | 420 | | default: |
| 0 | 421 | | Debug.LogError($"Sensor type '{config.dynamic_config.sensor_config.type}' not found."); |
| 0 | 422 | | break; |
| | 423 | | } |
| | 424 | |
|
| 1 | 425 | | Interceptor interceptor = interceptorObject.GetComponent<Interceptor>(); |
| 1 | 426 | | _interceptorObjects.Add(interceptor); |
| 1 | 427 | | _activeInterceptors.Add(interceptor); |
| | 428 | |
|
| | 429 | | // Set the static agent config |
| 1 | 430 | | interceptor.SetStaticAgentConfig(interceptorStaticAgentConfig); |
| | 431 | |
|
| | 432 | | // Subscribe events |
| 1 | 433 | | interceptor.OnInterceptHit += RegisterInterceptorHit; |
| 1 | 434 | | interceptor.OnInterceptMiss += RegisterInterceptorMiss; |
| | 435 | |
|
| | 436 | | // Assign a unique and simple ID |
| 1 | 437 | | int interceptorId = _interceptorObjects.Count; |
| 1 | 438 | | interceptorObject.name = $"{interceptorStaticAgentConfig.name}_Interceptor_{interceptorId}"; |
| | 439 | |
|
| | 440 | | // Add the interceptor's unit cost to the total cost |
| 1 | 441 | | _costLaunchedInterceptors += interceptorStaticAgentConfig.unitCost; |
| | 442 | |
|
| | 443 | | // Let listeners know a new interceptor has been created |
| 1 | 444 | | OnNewInterceptor?.Invoke(interceptor); |
| | 445 | |
|
| 1 | 446 | | return interceptor; |
| 1 | 447 | | } |
| | 448 | |
|
| | 449 | | /// <summary> |
| | 450 | | /// Creates a threat based on the provided configuration. |
| | 451 | | /// </summary> |
| | 452 | | /// <param name="config">Configuration settings for the threat.</param> |
| | 453 | | /// <returns>The created Threat instance, or null if creation failed.</returns> |
| 7 | 454 | | private Threat CreateThreat(DynamicAgentConfig config) { |
| 7 | 455 | | string threatModelFile = config.agent_model; |
| 7 | 456 | | threatModelFile = "Threats/" + threatModelFile; |
| 7 | 457 | | StaticAgentConfig threatStaticAgentConfig = ConfigLoader.LoadStaticAgentConfig(threatModelFile); |
| 7 | 458 | | string agentClass = threatStaticAgentConfig.agentClass; |
| | 459 | | // The threat class corresponds to the Prefab that must |
| | 460 | | // exist in the Resources/Prefabs folder |
| 7 | 461 | | GameObject threatObject = CreateAgent(config, agentClass); |
| | 462 | |
|
| 7 | 463 | | if (threatObject == null) |
| 0 | 464 | | return null; |
| | 465 | |
|
| 7 | 466 | | Threat threat = threatObject.GetComponent<Threat>(); |
| 7 | 467 | | _threatObjects.Add(threat); |
| | 468 | |
|
| | 469 | | // Set the static agent config |
| 7 | 470 | | threat.SetStaticAgentConfig(threatStaticAgentConfig); |
| | 471 | |
|
| | 472 | | // Set the attack behavior |
| 7 | 473 | | AttackBehavior attackBehavior = LoadAttackBehavior(config); |
| 7 | 474 | | threat.SetAttackBehavior(attackBehavior); |
| | 475 | |
|
| | 476 | | // Subscribe events |
| 7 | 477 | | threat.OnThreatHit += RegisterThreatHit; |
| 7 | 478 | | threat.OnThreatMiss += RegisterThreatMiss; |
| | 479 | |
|
| | 480 | | // Assign a unique and simple ID |
| 7 | 481 | | int threatId = _threatObjects.Count; |
| 7 | 482 | | threatObject.name = $"{threatStaticAgentConfig.name}_Threat_{threatId}"; |
| | 483 | |
|
| | 484 | | // Threats always start in midcourse |
| 7 | 485 | | threat.SetFlightPhase(Agent.FlightPhase.MIDCOURSE); |
| | 486 | |
|
| | 487 | | // Let listeners know a new threat has been created |
| 7 | 488 | | OnNewThreat?.Invoke(threat); |
| | 489 | |
|
| 7 | 490 | | return threatObject.GetComponent<Threat>(); |
| 7 | 491 | | } |
| | 492 | |
|
| | 493 | | /// <summary> |
| | 494 | | /// Creates an agent (interceptor or threat) based on the provided configuration and prefab name. |
| | 495 | | /// </summary> |
| | 496 | | /// <param name="config">Configuration settings for the agent.</param> |
| | 497 | | /// <param name="prefabName">Name of the prefab to instantiate.</param> |
| | 498 | | /// <returns>The created GameObject instance, or null if creation failed.</returns> |
| 8 | 499 | | public GameObject CreateAgent(DynamicAgentConfig config, string prefabName) { |
| 8 | 500 | | GameObject prefab = Resources.Load<GameObject>($"Prefabs/{prefabName}"); |
| 8 | 501 | | if (prefab == null) { |
| 0 | 502 | | Debug.LogError($"Prefab '{prefabName}' not found in Resources/Prefabs folder."); |
| 0 | 503 | | return null; |
| | 504 | | } |
| | 505 | |
|
| 8 | 506 | | Vector3 noiseOffset = Utilities.GenerateRandomNoise(config.standard_deviation.position); |
| 8 | 507 | | Vector3 noisyPosition = config.initial_state.position + noiseOffset; |
| | 508 | |
|
| 8 | 509 | | GameObject agentObject = Instantiate(prefab, noisyPosition, Quaternion.identity); |
| | 510 | |
|
| 8 | 511 | | Rigidbody agentRigidbody = agentObject.GetComponent<Rigidbody>(); |
| 8 | 512 | | Vector3 velocityNoise = Utilities.GenerateRandomNoise(config.standard_deviation.velocity); |
| 8 | 513 | | Vector3 noisyVelocity = config.initial_state.velocity + velocityNoise; |
| 8 | 514 | | agentRigidbody.linearVelocity = noisyVelocity; |
| 8 | 515 | | agentObject.GetComponent<Agent>().SetInitialVelocity(noisyVelocity); |
| | 516 | | // Set rotation to face the initial velocity with noise |
| 8 | 517 | | Vector3 velocityDirection = noisyVelocity.normalized; |
| 8 | 518 | | Quaternion targetRotation = Quaternion.LookRotation(velocityDirection, Vector3.up); |
| 8 | 519 | | agentObject.transform.rotation = targetRotation; |
| | 520 | |
|
| 8 | 521 | | agentObject.GetComponent<Agent>().SetDynamicAgentConfig(config); |
| | 522 | |
|
| 8 | 523 | | return agentObject; |
| 8 | 524 | | } |
| | 525 | |
|
| 0 | 526 | | public void LoadNewConfig(string configFileName) { |
| 0 | 527 | | this.simulationConfig = ConfigLoader.LoadSimulationConfig(configFileName); |
| | 528 | | // Reload the simulator config |
| 0 | 529 | | this.simulatorConfig = ConfigLoader.LoadSimulatorConfig(); |
| 0 | 530 | | if (simulationConfig != null) { |
| 0 | 531 | | Debug.Log($"Loaded new configuration: {configFileName}"); |
| 0 | 532 | | RestartSimulation(); |
| 0 | 533 | | } else { |
| 0 | 534 | | Debug.LogError($"Failed to load configuration: {configFileName}"); |
| 0 | 535 | | } |
| 0 | 536 | | } |
| | 537 | |
|
| 0 | 538 | | public void RestartSimulation() { |
| 0 | 539 | | OnSimulationEnded?.Invoke(); |
| 0 | 540 | | Debug.Log("Simulation ended"); |
| 0 | 541 | | UIManager.Instance.LogActionMessage("[SIM] Simulation restarted"); |
| | 542 | | // Reset simulation time |
| 0 | 543 | | _elapsedSimulationTime = 0f; |
| 0 | 544 | | _isSimulationPaused = IsSimulationPaused(); |
| 0 | 545 | | _costLaunchedInterceptors = 0f; |
| 0 | 546 | | _costDestroyedThreats = 0f; |
| | 547 | |
|
| | 548 | | // Clear existing interceptors and threats |
| 0 | 549 | | foreach (var interceptor in _interceptorObjects) { |
| 0 | 550 | | if (interceptor != null) { |
| 0 | 551 | | Destroy(interceptor.gameObject); |
| 0 | 552 | | } |
| 0 | 553 | | } |
| | 554 | |
|
| 0 | 555 | | foreach (var threat in _threatObjects) { |
| 0 | 556 | | if (threat != null) { |
| 0 | 557 | | Destroy(threat.gameObject); |
| 0 | 558 | | } |
| 0 | 559 | | } |
| | 560 | |
|
| 0 | 561 | | foreach (var dummyAgent in _dummyAgentObjects) { |
| 0 | 562 | | if (dummyAgent != null) { |
| 0 | 563 | | Destroy(dummyAgent); |
| 0 | 564 | | } |
| 0 | 565 | | } |
| | 566 | |
|
| 0 | 567 | | _interceptorObjects.Clear(); |
| 0 | 568 | | _activeInterceptors.Clear(); |
| 0 | 569 | | _threatObjects.Clear(); |
| 0 | 570 | | _dummyAgentObjects.Clear(); |
| 0 | 571 | | _dummyAgentTable.Clear(); |
| 0 | 572 | | _interceptorSwarms.Clear(); |
| 0 | 573 | | _submunitionsSwarms.Clear(); |
| 0 | 574 | | _threatSwarms.Clear(); |
| 0 | 575 | | OnInterceptorSwarmChanged?.Invoke(_interceptorSwarms); |
| 0 | 576 | | OnSubmunitionsSwarmChanged?.Invoke(_submunitionsSwarms); |
| 0 | 577 | | OnThreatSwarmChanged?.Invoke(_threatSwarms); |
| 0 | 578 | | StartSimulation(); |
| 0 | 579 | | } |
| | 580 | |
|
| 5 | 581 | | void Update() { |
| | 582 | | // Check if all missiles have terminated |
| 5 | 583 | | bool allInterceptorsTerminated = true; |
| 25 | 584 | | foreach (var interceptor in _interceptorObjects) { |
| 10 | 585 | | if (interceptor != null && interceptor.GetFlightPhase() != Agent.FlightPhase.TERMINATED) { |
| 5 | 586 | | allInterceptorsTerminated = false; |
| 5 | 587 | | break; |
| | 588 | | } |
| 0 | 589 | | } |
| | 590 | | // If all missiles have terminated, restart the simulation |
| 5 | 591 | | if (allInterceptorsTerminated) { |
| 0 | 592 | | RestartSimulation(); |
| 0 | 593 | | } |
| 5 | 594 | | } |
| | 595 | |
|
| 51 | 596 | | void FixedUpdate() { |
| 102 | 597 | | if (!_isSimulationPaused && _elapsedSimulationTime < simulationConfig.endTime) { |
| 51 | 598 | | _elapsedSimulationTime += Time.deltaTime; |
| 51 | 599 | | } else if (_elapsedSimulationTime >= simulationConfig.endTime) { |
| 0 | 600 | | RestartSimulation(); |
| 0 | 601 | | Debug.Log("Simulation completed."); |
| 0 | 602 | | } |
| 51 | 603 | | } |
| | 604 | | } |
| | 605 | |
|
| | 606 | | [System.Serializable] |
| | 607 | | public class SimulatorConfig { |
| | 608 | | public bool enableTelemetryLogging; |
| | 609 | | public bool enableEventLogging; |
| | 610 | | public bool enableMissileTrailEffect; |
| | 611 | | public bool enableExplosionEffect; |
| | 612 | | public int physicsUpdateRate; |
| | 613 | | public bool persistentFlightTrails; |
| | 614 | | } |