| | 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 | | private string _defaultConfig = "7_quadcopters.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 boolean 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 to subscribe to for 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.IsTerminated()).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, LookupSubmunitionSwarmIndexInInterceptorSwarm(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(_defaultConfig); |
| 0 | 142 | | simulatorConfig = ConfigLoader.LoadSimulatorConfig(); |
| 0 | 143 | | Debug.Log(SimulationConfig); |
| 0 | 144 | | } |
| | 145 | |
|
| 0 | 146 | | void Start() { |
| 0 | 147 | | if (Instance == this) { |
| 0 | 148 | | _isSimulationPaused = false; |
| 0 | 149 | | StartSimulation(); |
| 0 | 150 | | ResumeSimulation(); |
| 0 | 151 | | } |
| 0 | 152 | | } |
| | 153 | |
|
| 0 | 154 | | void Update() {} |
| | 155 | |
|
| 0 | 156 | | public void SetTimeScale(float timeScale) { |
| 0 | 157 | | Time.timeScale = timeScale; |
| | 158 | | // Time.fixedDeltaTime is derived from simulator.json. |
| 0 | 159 | | Time.maximumDeltaTime = Time.fixedDeltaTime * 3; |
| 0 | 160 | | } |
| | 161 | |
|
| 0 | 162 | | public void StartSimulation() { |
| 0 | 163 | | InitializeSimulation(); |
| | 164 | |
|
| | 165 | | // Invoke the simulation started event to let listeners know to invoke their own handler |
| | 166 | | // behavior. |
| 0 | 167 | | UIManager.Instance.LogActionMessage("[SIM] Simulation started."); |
| 0 | 168 | | OnSimulationStarted?.Invoke(); |
| 0 | 169 | | } |
| | 170 | |
|
| 0 | 171 | | public void PauseSimulation() { |
| 0 | 172 | | SetTimeScale(0); |
| 0 | 173 | | Time.fixedDeltaTime = 0; |
| 0 | 174 | | _isSimulationPaused = true; |
| 0 | 175 | | } |
| | 176 | |
|
| 0 | 177 | | public void ResumeSimulation() { |
| 0 | 178 | | Time.fixedDeltaTime = (float)(1.0f / simulatorConfig.physicsUpdateRate); |
| 0 | 179 | | SetTimeScale(SimulationConfig.timeScale); |
| 0 | 180 | | _isSimulationPaused = false; |
| 0 | 181 | | } |
| | 182 | |
|
| 0 | 183 | | public bool IsSimulationPaused() { |
| 0 | 184 | | return _isSimulationPaused; |
| 0 | 185 | | } |
| | 186 | |
|
| 0 | 187 | | private void InitializeSimulation() { |
| 0 | 188 | | if (!IsSimulationPaused()) { |
| | 189 | | // If the simulation was not paused, we need to update the time scale. |
| 0 | 190 | | SetTimeScale(SimulationConfig.timeScale); |
| 0 | 191 | | Time.fixedDeltaTime = (float)(1.0f / simulatorConfig.physicsUpdateRate); |
| | 192 | | // If the simulation WAS paused, then ResumeSimulation will handle updating the time scale and |
| | 193 | | // fixed delta time from the newly loaded config files. |
| 0 | 194 | | } |
| | 195 | | // Create targets based on the configuration. |
| 0 | 196 | | List<Agent> targets = new List<Agent>(); |
| 0 | 197 | | foreach (var swarmConfig in SimulationConfig.threat_swarm_configs) { |
| 0 | 198 | | List<Agent> swarm = new List<Agent>(); |
| 0 | 199 | | for (int i = 0; i < swarmConfig.num_agents; ++i) { |
| 0 | 200 | | Threat threat = CreateThreat(swarmConfig.dynamic_agent_config); |
| 0 | 201 | | swarm.Add(threat); |
| 0 | 202 | | } |
| 0 | 203 | | AddThreatSwarm(swarm); |
| 0 | 204 | | } |
| 0 | 205 | | } |
| | 206 | |
|
| 0 | 207 | | public void AddInterceptorSwarm(List<Agent> swarm) { |
| 0 | 208 | | List<(Agent, bool)> swarmTuple = swarm.ConvertAll(agent => (agent, true)); |
| 0 | 209 | | _interceptorSwarms.Add(swarmTuple); |
| 0 | 210 | | foreach (var interceptor in swarm) { |
| 0 | 211 | | _interceptorSwarmMap[interceptor] = swarmTuple; |
| 0 | 212 | | } |
| 0 | 213 | | OnInterceptorSwarmChanged?.Invoke(_interceptorSwarms); |
| 0 | 214 | | } |
| | 215 | |
|
| 0 | 216 | | public void AddSubmunitionsSwarm(List<Agent> swarm) { |
| 0 | 217 | | List<(Agent, bool)> swarmTuple = swarm.ConvertAll(agent => (agent, true)); |
| 0 | 218 | | _submunitionsSwarms.Add(swarmTuple); |
| 0 | 219 | | foreach (var submunition in swarm) { |
| 0 | 220 | | _submunitionsSwarmMap[submunition] = swarmTuple; |
| 0 | 221 | | } |
| 0 | 222 | | AddInterceptorSwarm(swarm); |
| 0 | 223 | | _submunitionInterceptorSwarmMap[swarmTuple] = _interceptorSwarms[_interceptorSwarms.Count - 1]; |
| 0 | 224 | | OnSubmunitionsSwarmChanged?.Invoke(_submunitionsSwarms); |
| 0 | 225 | | } |
| | 226 | |
|
| 0 | 227 | | public int LookupSubmunitionSwarmIndexInInterceptorSwarm(List<(Agent, bool)> swarm) { |
| 0 | 228 | | if (_submunitionInterceptorSwarmMap.TryGetValue(swarm, out var interceptorSwarm)) { |
| 0 | 229 | | return _interceptorSwarms.IndexOf(interceptorSwarm); |
| | 230 | | } |
| | 231 | | // Return -1 if the swarm is not found. |
| 0 | 232 | | return -1; |
| 0 | 233 | | } |
| | 234 | |
|
| 0 | 235 | | public void AddThreatSwarm(List<Agent> swarm) { |
| 0 | 236 | | List<(Agent, bool)> swarmTuple = swarm.ConvertAll(agent => (agent, true)); |
| 0 | 237 | | _threatSwarms.Add(swarmTuple); |
| 0 | 238 | | foreach (var threat in swarm) { |
| 0 | 239 | | _threatSwarmMap[threat] = swarmTuple; |
| 0 | 240 | | } |
| 0 | 241 | | OnThreatSwarmChanged?.Invoke(_threatSwarms); |
| 0 | 242 | | } |
| | 243 | |
|
| 0 | 244 | | public Vector3 GetAllAgentsCenter() { |
| 0 | 245 | | List<Agent> allAgents = _interceptorObjects.ConvertAll(interceptor => interceptor as Agent) |
| 0 | 246 | | .Concat(_threatObjects.ConvertAll(threat => threat as Agent)) |
| | 247 | | .ToList(); |
| 0 | 248 | | return GetSwarmCenter(allAgents); |
| 0 | 249 | | } |
| | 250 | |
|
| 0 | 251 | | public Vector3 GetSwarmCenter(List<Agent> swarm) { |
| 0 | 252 | | if (swarm.Count == 0) { |
| 0 | 253 | | return Vector3.zero; |
| | 254 | | } |
| | 255 | |
|
| 0 | 256 | | Vector3 sum = Vector3.zero; |
| 0 | 257 | | int count = 0; |
| 0 | 258 | | int swarmCount = swarm.Count; |
| | 259 | |
|
| 0 | 260 | | for (int i = 0; i < swarmCount; ++i) { |
| 0 | 261 | | Agent agent = swarm[i]; |
| 0 | 262 | | if (!agent.IsTerminated()) { |
| 0 | 263 | | sum += agent.transform.position; |
| 0 | 264 | | ++count; |
| 0 | 265 | | } |
| 0 | 266 | | } |
| | 267 | |
|
| 0 | 268 | | return count > 0 ? sum / count : Vector3.zero; |
| 0 | 269 | | } |
| | 270 | |
|
| 0 | 271 | | public List<List<(Agent, bool)>> GetInterceptorSwarms() { |
| 0 | 272 | | return _interceptorSwarms; |
| 0 | 273 | | } |
| | 274 | |
|
| 0 | 275 | | public List<List<(Agent, bool)>> GetSubmunitionsSwarms() { |
| 0 | 276 | | return _submunitionsSwarms; |
| 0 | 277 | | } |
| | 278 | |
|
| 0 | 279 | | public List<List<(Agent, bool)>> GetThreatSwarms() { |
| 0 | 280 | | return _threatSwarms; |
| 0 | 281 | | } |
| | 282 | |
|
| 0 | 283 | | public void DestroyInterceptorInSwarm(Interceptor interceptor) { |
| 0 | 284 | | var swarm = _interceptorSwarmMap[interceptor]; |
| 0 | 285 | | int index = swarm.FindIndex(tuple => tuple.Item1 == interceptor); |
| 0 | 286 | | if (index != -1) { |
| 0 | 287 | | swarm[index] = (swarm[index].Item1, false); |
| 0 | 288 | | OnInterceptorSwarmChanged?.Invoke(_interceptorSwarms); |
| 0 | 289 | | } else { |
| 0 | 290 | | Debug.LogError("Interceptor not found in swarm."); |
| 0 | 291 | | } |
| 0 | 292 | | if (swarm.All(tuple => !tuple.Item2)) { |
| | 293 | | // Need to give the camera controller a way to update to the next swarm if it exists. |
| 0 | 294 | | if (CameraController.Instance.cameraMode == CameraMode.FOLLOW_INTERCEPTOR_SWARM) { |
| 0 | 295 | | CameraController.Instance.FollowNextInterceptorSwarm(); |
| 0 | 296 | | } |
| 0 | 297 | | } |
| | 298 | |
|
| | 299 | | // If this also happens to be a submunition, destroy it in the submunition swarm. |
| 0 | 300 | | if (_submunitionsSwarmMap.ContainsKey(interceptor)) { |
| 0 | 301 | | DestroySubmunitionInSwarm(interceptor); |
| 0 | 302 | | } |
| 0 | 303 | | } |
| | 304 | |
|
| 0 | 305 | | public void DestroySubmunitionInSwarm(Interceptor submunition) { |
| 0 | 306 | | var swarm = _submunitionsSwarmMap[submunition]; |
| 0 | 307 | | int index = swarm.FindIndex(tuple => tuple.Item1 == submunition); |
| 0 | 308 | | if (index != -1) { |
| 0 | 309 | | swarm[index] = (swarm[index].Item1, false); |
| 0 | 310 | | OnSubmunitionsSwarmChanged?.Invoke(_submunitionsSwarms); |
| 0 | 311 | | } |
| 0 | 312 | | } |
| | 313 | |
|
| 0 | 314 | | public void DestroyThreatInSwarm(Threat threat) { |
| 0 | 315 | | var swarm = _threatSwarmMap[threat]; |
| 0 | 316 | | int index = swarm.FindIndex(tuple => tuple.Item1 == threat); |
| 0 | 317 | | if (index != -1) { |
| 0 | 318 | | swarm[index] = (swarm[index].Item1, false); |
| 0 | 319 | | OnThreatSwarmChanged?.Invoke(_threatSwarms); |
| 0 | 320 | | } |
| 0 | 321 | | if (swarm.All(tuple => !tuple.Item2)) { |
| 0 | 322 | | _threatSwarms.Remove(swarm); |
| 0 | 323 | | if (CameraController.Instance.cameraMode == CameraMode.FOLLOW_THREAT_SWARM) { |
| 0 | 324 | | CameraController.Instance.FollowNextThreatSwarm(); |
| 0 | 325 | | } |
| 0 | 326 | | } |
| 0 | 327 | | } |
| | 328 | |
|
| 0 | 329 | | public void RegisterInterceptorHit(Interceptor interceptor, Threat threat) { |
| 0 | 330 | | _costDestroyedThreats += threat.staticAgentConfig.unitCost; |
| 0 | 331 | | if (interceptor is Interceptor missileComponent) { |
| 0 | 332 | | _activeInterceptors.Remove(missileComponent); |
| 0 | 333 | | } |
| 0 | 334 | | DestroyInterceptorInSwarm(interceptor); |
| 0 | 335 | | DestroyThreatInSwarm(threat); |
| 0 | 336 | | } |
| | 337 | |
|
| 0 | 338 | | public void RegisterInterceptorMiss(Interceptor interceptor, Threat threat) { |
| 0 | 339 | | if (interceptor is Interceptor missileComponent) { |
| 0 | 340 | | _activeInterceptors.Remove(missileComponent); |
| 0 | 341 | | } |
| 0 | 342 | | DestroyInterceptorInSwarm(interceptor); |
| 0 | 343 | | } |
| | 344 | |
|
| 0 | 345 | | public void RegisterThreatHit(Threat threat) { |
| 0 | 346 | | DestroyThreatInSwarm(threat); |
| 0 | 347 | | } |
| | 348 | |
|
| 0 | 349 | | public void RegisterThreatMiss(Threat threat) { |
| 0 | 350 | | DestroyThreatInSwarm(threat); |
| 0 | 351 | | } |
| | 352 | |
|
| 15 | 353 | | private AttackBehavior LoadAttackBehavior(DynamicAgentConfig config) { |
| 15 | 354 | | string threatBehaviorFile = config.attack_behavior; |
| 15 | 355 | | AttackBehavior attackBehavior = AttackBehavior.FromJson(threatBehaviorFile); |
| 15 | 356 | | switch (attackBehavior.attackBehaviorType) { |
| | 357 | | case AttackBehavior.AttackBehaviorType.DIRECT_ATTACK: |
| 15 | 358 | | return DirectAttackBehavior.FromJson(threatBehaviorFile); |
| | 359 | | default: |
| 0 | 360 | | Debug.LogError($"Attack behavior type '{attackBehavior.attackBehaviorType}' not found."); |
| 0 | 361 | | return null; |
| | 362 | | } |
| 15 | 363 | | } |
| | 364 | |
|
| 15 | 365 | | public Agent CreateDummyAgent(Vector3 position, Vector3 velocity) { |
| 23 | 366 | | if (_dummyAgentTable.ContainsKey((position, velocity))) { |
| 8 | 367 | | return _dummyAgentTable[(position, velocity)].GetComponent<Agent>(); |
| | 368 | | } |
| 7 | 369 | | GameObject dummyAgentPrefab = Resources.Load<GameObject>($"Prefabs/DummyAgent"); |
| 7 | 370 | | GameObject dummyAgentObject = Instantiate(dummyAgentPrefab, position, Quaternion.identity); |
| 14 | 371 | | if (!dummyAgentObject.TryGetComponent<Agent>(out _)) { |
| 7 | 372 | | dummyAgentObject.AddComponent<DummyAgent>(); |
| 7 | 373 | | } |
| 7 | 374 | | Rigidbody dummyRigidbody = dummyAgentObject.GetComponent<Rigidbody>(); |
| 7 | 375 | | dummyRigidbody.linearVelocity = velocity; |
| 7 | 376 | | _dummyAgentObjects.Add(dummyAgentObject); |
| 7 | 377 | | _dummyAgentTable[(position, velocity)] = dummyAgentObject; |
| 7 | 378 | | return dummyAgentObject.GetComponent<Agent>(); |
| 15 | 379 | | } |
| | 380 | |
|
| | 381 | | /// <summary> |
| | 382 | | /// Creates a interceptor based on the provided configuration. |
| | 383 | | /// </summary> |
| | 384 | | /// <param name="config">Configuration settings for the interceptor.</param> |
| | 385 | | /// <param name="initialState">Initial state of the interceptor.</param> |
| | 386 | | /// <returns>The created Interceptor instance, or null if creation failed.</returns> |
| 0 | 387 | | public Interceptor CreateInterceptor(DynamicAgentConfig config, InitialState initialState) { |
| 0 | 388 | | string interceptorModelFile = config.agent_model; |
| 0 | 389 | | interceptorModelFile = "Interceptors/" + interceptorModelFile; |
| 0 | 390 | | StaticAgentConfig interceptorStaticAgentConfig = |
| | 391 | | ConfigLoader.LoadStaticAgentConfig(interceptorModelFile); |
| 0 | 392 | | string agentClass = interceptorStaticAgentConfig.agentClass; |
| | 393 | | // The interceptor class corresponds to the Prefab that must exist in the Resources/Prefabs |
| | 394 | | // folder. |
| 0 | 395 | | GameObject interceptorObject = CreateAgent(config, initialState, agentClass); |
| | 396 | |
|
| 0 | 397 | | if (interceptorObject == null) |
| 0 | 398 | | return null; |
| | 399 | |
|
| | 400 | | // Interceptor-specific logic. |
| 0 | 401 | | switch (config.dynamic_config.sensor_config.type) { |
| | 402 | | case SensorType.IDEAL: |
| 0 | 403 | | interceptorObject.AddComponent<IdealSensor>(); |
| 0 | 404 | | break; |
| | 405 | | default: |
| 0 | 406 | | Debug.LogError($"Sensor type '{config.dynamic_config.sensor_config.type}' not found."); |
| 0 | 407 | | break; |
| | 408 | | } |
| | 409 | |
|
| 0 | 410 | | Interceptor interceptor = interceptorObject.GetComponent<Interceptor>(); |
| 0 | 411 | | _interceptorObjects.Add(interceptor); |
| 0 | 412 | | _activeInterceptors.Add(interceptor); |
| | 413 | |
|
| | 414 | | // Set the static agent config. |
| 0 | 415 | | interceptor.SetStaticAgentConfig(interceptorStaticAgentConfig); |
| | 416 | |
|
| | 417 | | // Subscribe events. |
| 0 | 418 | | interceptor.OnInterceptHit += RegisterInterceptorHit; |
| 0 | 419 | | interceptor.OnInterceptMiss += RegisterInterceptorMiss; |
| | 420 | |
|
| | 421 | | // Assign a unique and simple ID. |
| 0 | 422 | | int interceptorId = _interceptorObjects.Count; |
| 0 | 423 | | interceptorObject.name = $"{interceptorStaticAgentConfig.name}_Interceptor_{interceptorId}"; |
| | 424 | |
|
| | 425 | | // Add the interceptor's unit cost to the total cost. |
| 0 | 426 | | _costLaunchedInterceptors += interceptorStaticAgentConfig.unitCost; |
| | 427 | |
|
| | 428 | | // Let listeners know a new interceptor has been created. |
| 0 | 429 | | OnNewInterceptor?.Invoke(interceptor); |
| | 430 | |
|
| 0 | 431 | | return interceptor; |
| 0 | 432 | | } |
| | 433 | |
|
| | 434 | | /// <summary> |
| | 435 | | /// Creates a threat based on the provided configuration. |
| | 436 | | /// </summary> |
| | 437 | | /// <param name="config">Configuration settings for the threat.</param> |
| | 438 | | /// <returns>The created Threat instance, or null if creation failed.</returns> |
| 15 | 439 | | private Threat CreateThreat(DynamicAgentConfig config) { |
| 15 | 440 | | string threatModelFile = config.agent_model; |
| 15 | 441 | | threatModelFile = "Threats/" + threatModelFile; |
| 15 | 442 | | StaticAgentConfig threatStaticAgentConfig = ConfigLoader.LoadStaticAgentConfig(threatModelFile); |
| 15 | 443 | | string agentClass = threatStaticAgentConfig.agentClass; |
| | 444 | | // The threat class corresponds to the Prefab that must exist in the Resources/Prefabs folder. |
| 15 | 445 | | GameObject threatObject = CreateRandomAgent(config, agentClass); |
| | 446 | |
|
| 15 | 447 | | if (threatObject == null) |
| 0 | 448 | | return null; |
| | 449 | |
|
| 15 | 450 | | Threat threat = threatObject.GetComponent<Threat>(); |
| 15 | 451 | | _threatObjects.Add(threat); |
| | 452 | |
|
| | 453 | | // Set the static agent config. |
| 15 | 454 | | threat.SetStaticAgentConfig(threatStaticAgentConfig); |
| | 455 | |
|
| | 456 | | // Set the attack behavior. |
| 15 | 457 | | AttackBehavior attackBehavior = LoadAttackBehavior(config); |
| 15 | 458 | | threat.SetAttackBehavior(attackBehavior); |
| | 459 | |
|
| | 460 | | // Subscribe events. |
| 15 | 461 | | threat.OnThreatHit += RegisterThreatHit; |
| 15 | 462 | | threat.OnThreatMiss += RegisterThreatMiss; |
| | 463 | |
|
| | 464 | | // Assign a unique and simple ID. |
| 15 | 465 | | int threatId = _threatObjects.Count; |
| 15 | 466 | | threatObject.name = $"{threatStaticAgentConfig.name}_Threat_{threatId}"; |
| | 467 | |
|
| | 468 | | // Let listeners know that a new threat has been created. |
| 15 | 469 | | OnNewThreat?.Invoke(threat); |
| | 470 | |
|
| 15 | 471 | | return threatObject.GetComponent<Threat>(); |
| 15 | 472 | | } |
| | 473 | |
|
| | 474 | | /// <summary> |
| | 475 | | /// Creates a agent based on the provided configuration and prefab name. |
| | 476 | | /// </summary> |
| | 477 | | /// <param name="config">Configuration settings for the agent.</param> |
| | 478 | | /// <param name="initialState">Initial state of the agent.</param> |
| | 479 | | /// <param name="prefabName">Name of the prefab to instantiate.</param> |
| | 480 | | /// <returns>The created GameObject instance, or null if creation failed.</returns> |
| | 481 | | public GameObject CreateAgent(DynamicAgentConfig config, InitialState initialState, |
| 15 | 482 | | string prefabName) { |
| 15 | 483 | | GameObject prefab = Resources.Load<GameObject>($"Prefabs/{prefabName}"); |
| 15 | 484 | | if (prefab == null) { |
| 0 | 485 | | Debug.LogError($"Prefab '{prefabName}' not found in Resources/Prefabs folder."); |
| 0 | 486 | | return null; |
| | 487 | | } |
| | 488 | |
|
| | 489 | | // Set the position. |
| 15 | 490 | | GameObject agentObject = Instantiate(prefab, initialState.position, Quaternion.identity); |
| | 491 | |
|
| | 492 | | // Set the velocity. The rigid body is frozen while the agent is in the initialized phase. |
| 15 | 493 | | agentObject.GetComponent<Agent>().SetInitialVelocity(initialState.velocity); |
| | 494 | |
|
| | 495 | | // Set the rotation to face the initial velocity. |
| 15 | 496 | | Vector3 velocityDirection = initialState.velocity.normalized; |
| 15 | 497 | | Quaternion targetRotation = Quaternion.LookRotation(velocityDirection, Vector3.up); |
| 15 | 498 | | agentObject.transform.rotation = targetRotation; |
| | 499 | |
|
| 15 | 500 | | agentObject.GetComponent<Agent>().SetDynamicAgentConfig(config); |
| 15 | 501 | | return agentObject; |
| 15 | 502 | | } |
| | 503 | |
|
| | 504 | | /// <summary> |
| | 505 | | /// Creates a random agent based on the provided configuration and prefab name. |
| | 506 | | /// </summary> |
| | 507 | | /// <param name="config">Configuration settings for the agent.</param> |
| | 508 | | /// <param name="prefabName">Name of the prefab to instantiate.</param> |
| | 509 | | /// <returns>The created GameObject instance, or null if creation failed.</returns> |
| 15 | 510 | | public GameObject CreateRandomAgent(DynamicAgentConfig config, string prefabName) { |
| 15 | 511 | | GameObject prefab = Resources.Load<GameObject>($"Prefabs/{prefabName}"); |
| 15 | 512 | | if (prefab == null) { |
| 0 | 513 | | Debug.LogError($"Prefab '{prefabName}' not found in Resources/Prefabs folder."); |
| 0 | 514 | | return null; |
| | 515 | | } |
| | 516 | |
|
| | 517 | | // Randomize the initial state. |
| 15 | 518 | | InitialState initialState = new InitialState(); |
| | 519 | |
|
| | 520 | | // Randomize the position. |
| 15 | 521 | | Vector3 positionNoise = Utilities.GenerateRandomNoise(config.standard_deviation.position); |
| 15 | 522 | | initialState.position = config.initial_state.position + positionNoise; |
| | 523 | |
|
| | 524 | | // Randomize the velocity. |
| 15 | 525 | | Vector3 velocityNoise = Utilities.GenerateRandomNoise(config.standard_deviation.velocity); |
| 15 | 526 | | initialState.velocity = config.initial_state.velocity + velocityNoise; |
| 15 | 527 | | return CreateAgent(config, initialState, prefabName); |
| 15 | 528 | | } |
| | 529 | |
|
| 0 | 530 | | public void LoadNewConfig(string configFileName) { |
| 0 | 531 | | this.SimulationConfig = ConfigLoader.LoadSimulationConfig(configFileName); |
| | 532 | | // Reload the simulator config |
| 0 | 533 | | this.simulatorConfig = ConfigLoader.LoadSimulatorConfig(); |
| 0 | 534 | | if (SimulationConfig != null) { |
| 0 | 535 | | Debug.Log($"Loaded new configuration: {configFileName}."); |
| 0 | 536 | | RestartSimulation(); |
| 0 | 537 | | } else { |
| 0 | 538 | | Debug.LogError($"Failed to load configuration: {configFileName}."); |
| 0 | 539 | | } |
| 0 | 540 | | } |
| | 541 | |
|
| 0 | 542 | | public void RestartSimulation() { |
| 0 | 543 | | OnSimulationEnded?.Invoke(); |
| 0 | 544 | | Debug.Log("Simulation ended"); |
| 0 | 545 | | UIManager.Instance.LogActionMessage("[SIM] Simulation restarted."); |
| | 546 | | // Reset the simulation time. |
| 0 | 547 | | _elapsedSimulationTime = 0f; |
| 0 | 548 | | _isSimulationPaused = IsSimulationPaused(); |
| 0 | 549 | | _costLaunchedInterceptors = 0f; |
| 0 | 550 | | _costDestroyedThreats = 0f; |
| | 551 | |
|
| | 552 | | // Clear existing interceptors and threats. |
| 0 | 553 | | foreach (var interceptor in _interceptorObjects) { |
| 0 | 554 | | if (interceptor != null) { |
| 0 | 555 | | Destroy(interceptor.gameObject); |
| 0 | 556 | | } |
| 0 | 557 | | } |
| | 558 | |
|
| 0 | 559 | | foreach (var threat in _threatObjects) { |
| 0 | 560 | | if (threat != null) { |
| 0 | 561 | | Destroy(threat.gameObject); |
| 0 | 562 | | } |
| 0 | 563 | | } |
| | 564 | |
|
| 0 | 565 | | foreach (var dummyAgent in _dummyAgentObjects) { |
| 0 | 566 | | if (dummyAgent != null) { |
| 0 | 567 | | Destroy(dummyAgent); |
| 0 | 568 | | } |
| 0 | 569 | | } |
| | 570 | |
|
| 0 | 571 | | _interceptorObjects.Clear(); |
| 0 | 572 | | _activeInterceptors.Clear(); |
| 0 | 573 | | _threatObjects.Clear(); |
| 0 | 574 | | _dummyAgentObjects.Clear(); |
| 0 | 575 | | _dummyAgentTable.Clear(); |
| 0 | 576 | | _interceptorSwarms.Clear(); |
| 0 | 577 | | _submunitionsSwarms.Clear(); |
| 0 | 578 | | _threatSwarms.Clear(); |
| 0 | 579 | | OnInterceptorSwarmChanged?.Invoke(_interceptorSwarms); |
| 0 | 580 | | OnSubmunitionsSwarmChanged?.Invoke(_submunitionsSwarms); |
| 0 | 581 | | OnThreatSwarmChanged?.Invoke(_threatSwarms); |
| 0 | 582 | | StartSimulation(); |
| 0 | 583 | | } |
| | 584 | |
|
| 0 | 585 | | void FixedUpdate() { |
| 0 | 586 | | if (!_isSimulationPaused && _elapsedSimulationTime < SimulationConfig.endTime) { |
| 0 | 587 | | _elapsedSimulationTime += Time.deltaTime; |
| 0 | 588 | | } else if (_elapsedSimulationTime >= SimulationConfig.endTime) { |
| 0 | 589 | | RestartSimulation(); |
| 0 | 590 | | Debug.Log("Simulation completed."); |
| 0 | 591 | | } |
| 0 | 592 | | } |
| | 593 | |
|
| 0 | 594 | | public void QuitSimulation() { |
| 0 | 595 | | Application.Quit(); |
| 0 | 596 | | } |
| | 597 | | } |
| | 598 | |
|
| | 599 | | [System.Serializable] |
| | 600 | | public class SimulatorConfig { |
| | 601 | | public bool enableTelemetryLogging; |
| | 602 | | public bool enableEventLogging; |
| | 603 | | public bool enableMissileTrailEffect; |
| | 604 | | public bool enableExplosionEffect; |
| | 605 | | public int physicsUpdateRate; |
| | 606 | | public bool persistentFlightTrails; |
| | 607 | | } |