| | 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> |
| 25 | 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 | |
|
| 10 | 24 | | public string defaultConfig = "1_salvo_1_hydra_7_drones.json"; |
| | 25 | |
|
| 10 | 26 | | private List<Interceptor> _activeInterceptors = new List<Interceptor>(); |
| | 27 | |
|
| 10 | 28 | | private List<Interceptor> _interceptorObjects = new List<Interceptor>(); |
| 10 | 29 | | private List<Threat> _threatObjects = new List<Threat>(); |
| | 30 | |
|
| 10 | 31 | | private List<GameObject> _dummyAgentObjects = new List<GameObject>(); |
| 10 | 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) |
| 10 | 37 | | private List<List<(Agent, bool)>> _interceptorSwarms = new List<List<(Agent, bool)>>(); |
| 10 | 38 | | private List<List<(Agent, bool)>> _submunitionsSwarms = new List<List<(Agent, bool)>>(); |
| 10 | 39 | | private List<List<(Agent, bool)>> _threatSwarms = new List<List<(Agent, bool)>>(); |
| | 40 | |
|
| 10 | 41 | | private Dictionary<Agent, List<(Agent, bool)>> _interceptorSwarmMap = |
| | 42 | | new Dictionary<Agent, List<(Agent, bool)>>(); |
| | 43 | |
|
| 10 | 44 | | private Dictionary<Agent, List<(Agent, bool)>> _submunitionsSwarmMap = |
| | 45 | | new Dictionary<Agent, List<(Agent, bool)>>(); |
| 10 | 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 |
| 10 | 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 | |
|
| 10 | 60 | | private float _elapsedSimulationTime = 0f; |
| 10 | 61 | | private bool _isSimulationPaused = false; |
| | 62 | |
|
| 10 | 63 | | private float _costLaunchedInterceptors = 0f; |
| 10 | 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> |
| 0 | 80 | | public double GetElapsedSimulationTime() { |
| 0 | 81 | | return _elapsedSimulationTime; |
| 0 | 82 | | } |
| | 83 | |
|
| | 84 | | /// <summary> |
| | 85 | | /// Gets the total cost of launched interceptors. |
| | 86 | | /// </summary> |
| | 87 | | /// <returns>The total cost of launched interceptors.</returns> |
| 0 | 88 | | public double GetCostLaunchedInterceptors() { |
| 0 | 89 | | return _costLaunchedInterceptors; |
| 0 | 90 | | } |
| | 91 | |
|
| | 92 | | /// <summary> |
| | 93 | | /// Gets the total cost of destroyed threats. |
| | 94 | | /// </summary> |
| | 95 | | /// <returns>The total cost of destroyed threats.</returns> |
| 0 | 96 | | public double GetCostDestroyedThreats() { |
| 0 | 97 | | return _costDestroyedThreats; |
| 0 | 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 | |
|
| 0 | 133 | | void Awake() { |
| | 134 | | // Ensure only one instance of SimManager exists |
| 0 | 135 | | if (Instance == null) { |
| 0 | 136 | | Instance = this; |
| 0 | 137 | | DontDestroyOnLoad(gameObject); |
| 0 | 138 | | } else { |
| 0 | 139 | | Destroy(gameObject); |
| 0 | 140 | | } |
| 0 | 141 | | simulationConfig = ConfigLoader.LoadSimulationConfig("1_salvo_1_hydra_7_drones.json"); |
| 0 | 142 | | simulatorConfig = ConfigLoader.LoadSimulatorConfig(); |
| 0 | 143 | | Debug.Log(simulationConfig); |
| 0 | 144 | | } |
| | 145 | |
|
| 0 | 146 | | void Start() { |
| | 147 | | // Slow down time by simulationConfig.timeScale |
| 0 | 148 | | if (Instance == this) { |
| 0 | 149 | | _isSimulationPaused = false; |
| 0 | 150 | | StartSimulation(); |
| 0 | 151 | | ResumeSimulation(); |
| 0 | 152 | | } |
| 0 | 153 | | } |
| | 154 | |
|
| 0 | 155 | | public void SetTimeScale(float timeScale) { |
| 0 | 156 | | Time.timeScale = timeScale; |
| 0 | 157 | | Time.maximumDeltaTime = Time.fixedDeltaTime * 3; |
| | 158 | |
|
| | 159 | | // Time.fixedDeltaTime is set in the simulator.json |
| 0 | 160 | | } |
| | 161 | |
|
| 0 | 162 | | public void StartSimulation() { |
| 0 | 163 | | OnSimulationStarted?.Invoke(); |
| 0 | 164 | | InitializeSimulation(); |
| 0 | 165 | | } |
| | 166 | |
|
| 0 | 167 | | public void PauseSimulation() { |
| 0 | 168 | | SetTimeScale(0); |
| 0 | 169 | | Time.fixedDeltaTime = 0; |
| 0 | 170 | | _isSimulationPaused = true; |
| 0 | 171 | | } |
| | 172 | |
|
| 0 | 173 | | public void ResumeSimulation() { |
| 0 | 174 | | Time.fixedDeltaTime = (float)(1.0f / simulatorConfig.physicsUpdateRate); |
| 0 | 175 | | SetTimeScale(simulationConfig.timeScale); |
| 0 | 176 | | _isSimulationPaused = false; |
| 0 | 177 | | } |
| | 178 | |
|
| 0 | 179 | | public bool IsSimulationPaused() { |
| 0 | 180 | | return _isSimulationPaused; |
| 0 | 181 | | } |
| | 182 | |
|
| 0 | 183 | | private void InitializeSimulation() { |
| 0 | 184 | | if (!IsSimulationPaused()) { |
| | 185 | | // If it wasn't paused, we need to update the time scales NOW |
| 0 | 186 | | SetTimeScale(simulationConfig.timeScale); |
| 0 | 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 |
| 0 | 190 | | } |
| | 191 | |
|
| | 192 | | // Invoke the simulation started event to let listeners |
| | 193 | | // know to invoke their own handler behavior |
| 0 | 194 | | OnSimulationStarted?.Invoke(); |
| 0 | 195 | | List<Interceptor> missiles = new List<Interceptor>(); |
| | 196 | | // Create missiles based on config |
| 0 | 197 | | foreach (var swarmConfig in simulationConfig.interceptor_swarm_configs) { |
| 0 | 198 | | List<Agent> swarm = new List<Agent>(); |
| 0 | 199 | | for (int i = 0; i < swarmConfig.num_agents; i++) { |
| 0 | 200 | | Interceptor interceptor = CreateInterceptor(swarmConfig.dynamic_agent_config); |
| 0 | 201 | | swarm.Add(interceptor); |
| 0 | 202 | | } |
| 0 | 203 | | AddInterceptorSwarm(swarm); |
| 0 | 204 | | } |
| 0 | 205 | | IADS.Instance.RequestThreatAssignment(_interceptorObjects); |
| | 206 | |
|
| 0 | 207 | | List<Agent> targets = new List<Agent>(); |
| | 208 | | // Create targets based on config |
| 0 | 209 | | foreach (var swarmConfig in simulationConfig.threat_swarm_configs) { |
| 0 | 210 | | List<Agent> swarm = new List<Agent>(); |
| 0 | 211 | | for (int i = 0; i < swarmConfig.num_agents; i++) { |
| 0 | 212 | | Threat threat = CreateThreat(swarmConfig.dynamic_agent_config); |
| 0 | 213 | | swarm.Add(threat); |
| 0 | 214 | | } |
| 0 | 215 | | AddThreatSwarm(swarm); |
| 0 | 216 | | } |
| 0 | 217 | | } |
| | 218 | |
|
| 0 | 219 | | public void AddInterceptorSwarm(List<Agent> swarm) { |
| 0 | 220 | | List<(Agent, bool)> swarmTuple = swarm.ConvertAll(agent => (agent, true)); |
| 0 | 221 | | _interceptorSwarms.Add(swarmTuple); |
| 0 | 222 | | foreach (var interceptor in swarm) { |
| 0 | 223 | | _interceptorSwarmMap[interceptor] = swarmTuple; |
| 0 | 224 | | } |
| 0 | 225 | | OnInterceptorSwarmChanged?.Invoke(_interceptorSwarms); |
| 0 | 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 | |
|
| 0 | 246 | | public void AddThreatSwarm(List<Agent> swarm) { |
| 0 | 247 | | List<(Agent, bool)> swarmTuple = swarm.ConvertAll(agent => (agent, true)); |
| 0 | 248 | | _threatSwarms.Add(swarmTuple); |
| 0 | 249 | | foreach (var threat in swarm) { |
| 0 | 250 | | _threatSwarmMap[threat] = swarmTuple; |
| 0 | 251 | | } |
| 0 | 252 | | OnThreatSwarmChanged?.Invoke(_threatSwarms); |
| 0 | 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 | |
|
| 15 | 369 | | private AttackBehavior LoadAttackBehavior(DynamicAgentConfig config) { |
| 15 | 370 | | string threatBehaviorFile = config.attack_behavior; |
| 15 | 371 | | AttackBehavior attackBehavior = AttackBehavior.FromJson(threatBehaviorFile); |
| 15 | 372 | | switch (attackBehavior.attackBehaviorType) { |
| | 373 | | case AttackBehavior.AttackBehaviorType.DIRECT_ATTACK: |
| 15 | 374 | | return DirectAttackBehavior.FromJson(threatBehaviorFile); |
| | 375 | | default: |
| 0 | 376 | | Debug.LogError($"Attack behavior type '{attackBehavior.attackBehaviorType}' not found."); |
| 0 | 377 | | return null; |
| | 378 | | } |
| 15 | 379 | | } |
| | 380 | |
|
| 15 | 381 | | public Agent CreateDummyAgent(Vector3 position, Vector3 velocity) { |
| 23 | 382 | | if (_dummyAgentTable.ContainsKey((position, velocity))) { |
| 8 | 383 | | return _dummyAgentTable[(position, velocity)].GetComponent<Agent>(); |
| | 384 | | } |
| 7 | 385 | | GameObject dummyAgentPrefab = Resources.Load<GameObject>($"Prefabs/DummyAgent"); |
| 7 | 386 | | GameObject dummyAgentObject = Instantiate(dummyAgentPrefab, position, Quaternion.identity); |
| 14 | 387 | | if (!dummyAgentObject.TryGetComponent<Agent>(out _)) { |
| 7 | 388 | | dummyAgentObject.AddComponent<DummyAgent>(); |
| 7 | 389 | | } |
| 7 | 390 | | Rigidbody dummyRigidbody = dummyAgentObject.GetComponent<Rigidbody>(); |
| 7 | 391 | | dummyRigidbody.linearVelocity = velocity; |
| 7 | 392 | | _dummyAgentObjects.Add(dummyAgentObject); |
| 7 | 393 | | _dummyAgentTable[(position, velocity)] = dummyAgentObject; |
| 7 | 394 | | return dummyAgentObject.GetComponent<Agent>(); |
| 15 | 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> |
| 0 | 402 | | public Interceptor CreateInterceptor(DynamicAgentConfig config) { |
| 0 | 403 | | string interceptorModelFile = config.agent_model; |
| 0 | 404 | | interceptorModelFile = "Interceptors/" + interceptorModelFile; |
| 0 | 405 | | StaticAgentConfig interceptorStaticAgentConfig = |
| | 406 | | ConfigLoader.LoadStaticAgentConfig(interceptorModelFile); |
| 0 | 407 | | string agentClass = interceptorStaticAgentConfig.agentClass; |
| | 408 | | // The interceptor class corresponds to the Prefab that must |
| | 409 | | // exist in the Resources/Prefabs folder |
| 0 | 410 | | GameObject interceptorObject = CreateAgent(config, agentClass); |
| | 411 | |
|
| 0 | 412 | | if (interceptorObject == null) |
| 0 | 413 | | return null; |
| | 414 | |
|
| | 415 | | // Interceptor-specific logic |
| 0 | 416 | | switch (config.dynamic_config.sensor_config.type) { |
| | 417 | | case SensorType.IDEAL: |
| 0 | 418 | | interceptorObject.AddComponent<IdealSensor>(); |
| 0 | 419 | | break; |
| | 420 | | default: |
| 0 | 421 | | Debug.LogError($"Sensor type '{config.dynamic_config.sensor_config.type}' not found."); |
| 0 | 422 | | break; |
| | 423 | | } |
| | 424 | |
|
| 0 | 425 | | Interceptor interceptor = interceptorObject.GetComponent<Interceptor>(); |
| 0 | 426 | | _interceptorObjects.Add(interceptor); |
| 0 | 427 | | _activeInterceptors.Add(interceptor); |
| | 428 | |
|
| | 429 | | // Set the static agent config |
| 0 | 430 | | interceptor.SetStaticAgentConfig(interceptorStaticAgentConfig); |
| | 431 | |
|
| | 432 | | // Subscribe events |
| 0 | 433 | | interceptor.OnInterceptHit += RegisterInterceptorHit; |
| 0 | 434 | | interceptor.OnInterceptMiss += RegisterInterceptorMiss; |
| | 435 | |
|
| | 436 | | // Assign a unique and simple ID |
| 0 | 437 | | int interceptorId = _interceptorObjects.Count; |
| 0 | 438 | | interceptorObject.name = $"{interceptorStaticAgentConfig.name}_Interceptor_{interceptorId}"; |
| | 439 | |
|
| | 440 | | // Add the interceptor's unit cost to the total cost |
| 0 | 441 | | _costLaunchedInterceptors += interceptorStaticAgentConfig.unitCost; |
| | 442 | |
|
| | 443 | | // Let listeners know a new interceptor has been created |
| 0 | 444 | | OnNewInterceptor?.Invoke(interceptor); |
| | 445 | |
|
| 0 | 446 | | return interceptor; |
| 0 | 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> |
| 15 | 454 | | private Threat CreateThreat(DynamicAgentConfig config) { |
| 15 | 455 | | string threatModelFile = config.agent_model; |
| 15 | 456 | | threatModelFile = "Threats/" + threatModelFile; |
| 15 | 457 | | StaticAgentConfig threatStaticAgentConfig = ConfigLoader.LoadStaticAgentConfig(threatModelFile); |
| 15 | 458 | | string agentClass = threatStaticAgentConfig.agentClass; |
| | 459 | | // The threat class corresponds to the Prefab that must |
| | 460 | | // exist in the Resources/Prefabs folder |
| 15 | 461 | | GameObject threatObject = CreateAgent(config, agentClass); |
| | 462 | |
|
| 15 | 463 | | if (threatObject == null) |
| 0 | 464 | | return null; |
| | 465 | |
|
| 15 | 466 | | Threat threat = threatObject.GetComponent<Threat>(); |
| 15 | 467 | | _threatObjects.Add(threat); |
| | 468 | |
|
| | 469 | | // Set the static agent config |
| 15 | 470 | | threat.SetStaticAgentConfig(threatStaticAgentConfig); |
| | 471 | |
|
| | 472 | | // Set the attack behavior |
| 15 | 473 | | AttackBehavior attackBehavior = LoadAttackBehavior(config); |
| 15 | 474 | | threat.SetAttackBehavior(attackBehavior); |
| | 475 | |
|
| | 476 | | // Subscribe events |
| 15 | 477 | | threat.OnThreatHit += RegisterThreatHit; |
| 15 | 478 | | threat.OnThreatMiss += RegisterThreatMiss; |
| | 479 | |
|
| | 480 | | // Assign a unique and simple ID |
| 15 | 481 | | int threatId = _threatObjects.Count; |
| 15 | 482 | | threatObject.name = $"{threatStaticAgentConfig.name}_Threat_{threatId}"; |
| | 483 | |
|
| | 484 | | // Threats always start in midcourse |
| 15 | 485 | | threat.SetFlightPhase(Agent.FlightPhase.MIDCOURSE); |
| | 486 | |
|
| | 487 | | // Let listeners know a new threat has been created |
| 15 | 488 | | OnNewThreat?.Invoke(threat); |
| | 489 | |
|
| 15 | 490 | | return threatObject.GetComponent<Threat>(); |
| 15 | 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> |
| 15 | 499 | | public GameObject CreateAgent(DynamicAgentConfig config, string prefabName) { |
| 15 | 500 | | GameObject prefab = Resources.Load<GameObject>($"Prefabs/{prefabName}"); |
| 15 | 501 | | if (prefab == null) { |
| 0 | 502 | | Debug.LogError($"Prefab '{prefabName}' not found in Resources/Prefabs folder."); |
| 0 | 503 | | return null; |
| | 504 | | } |
| | 505 | |
|
| 15 | 506 | | Vector3 noiseOffset = Utilities.GenerateRandomNoise(config.standard_deviation.position); |
| 15 | 507 | | Vector3 noisyPosition = config.initial_state.position + noiseOffset; |
| | 508 | |
|
| 15 | 509 | | GameObject agentObject = Instantiate(prefab, noisyPosition, Quaternion.identity); |
| | 510 | |
|
| 15 | 511 | | Rigidbody agentRigidbody = agentObject.GetComponent<Rigidbody>(); |
| 15 | 512 | | Vector3 velocityNoise = Utilities.GenerateRandomNoise(config.standard_deviation.velocity); |
| 15 | 513 | | Vector3 noisyVelocity = config.initial_state.velocity + velocityNoise; |
| 15 | 514 | | agentRigidbody.linearVelocity = noisyVelocity; |
| 15 | 515 | | agentObject.GetComponent<Agent>().SetInitialVelocity(noisyVelocity); |
| | 516 | | // Set rotation to face the initial velocity with noise |
| 15 | 517 | | Vector3 velocityDirection = noisyVelocity.normalized; |
| 15 | 518 | | Quaternion targetRotation = Quaternion.LookRotation(velocityDirection, Vector3.up); |
| 15 | 519 | | agentObject.transform.rotation = targetRotation; |
| | 520 | |
|
| 15 | 521 | | agentObject.GetComponent<Agent>().SetDynamicAgentConfig(config); |
| | 522 | |
|
| 15 | 523 | | return agentObject; |
| 15 | 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 | |
|
| 0 | 581 | | void Update() { |
| | 582 | | // Check if all missiles have terminated |
| 0 | 583 | | bool allInterceptorsTerminated = true; |
| 0 | 584 | | foreach (var interceptor in _interceptorObjects) { |
| 0 | 585 | | if (interceptor != null && interceptor.GetFlightPhase() != Agent.FlightPhase.TERMINATED) { |
| 0 | 586 | | allInterceptorsTerminated = false; |
| 0 | 587 | | break; |
| | 588 | | } |
| 0 | 589 | | } |
| | 590 | | // If all missiles have terminated, restart the simulation |
| 0 | 591 | | if (allInterceptorsTerminated) { |
| 0 | 592 | | RestartSimulation(); |
| 0 | 593 | | } |
| 0 | 594 | | } |
| | 595 | |
|
| 0 | 596 | | void FixedUpdate() { |
| 0 | 597 | | if (!_isSimulationPaused && _elapsedSimulationTime < simulationConfig.endTime) { |
| 0 | 598 | | _elapsedSimulationTime += Time.deltaTime; |
| 0 | 599 | | } else if (_elapsedSimulationTime >= simulationConfig.endTime) { |
| 0 | 600 | | RestartSimulation(); |
| 0 | 601 | | Debug.Log("Simulation completed."); |
| 0 | 602 | | } |
| 0 | 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 | | } |