private void OnDestroy() { controls.Disable(); var elapsedTime = GetElapsedTime(SessionStartTime); SIM.LogSimulation(SIM.Simulation.HeadlessModeStop, value: elapsedTime, state: headless); SIM.LogSimulation(SIM.Simulation.InteractiveModeStop, value: elapsedTime, state: interactive); SIM.LogSimulation(SIM.Simulation.UsePredefinedSeedStop, state: useSeed); SIM.LogSimulation(SIM.Simulation.NPCStop, value: elapsedTime, state: npc); SIM.LogSimulation(SIM.Simulation.RandomPedestrianStop, value: elapsedTime, state: pedestrian); SIM.LogSimulation(SIM.Simulation.TimeOfDayStop, timeOfDay == "" ? string.Format("{0:hh}:{0:mm}", TimeSpan.FromHours(EnvironmentEffectsManager.currentTimeOfDay)) : timeOfDay, value: elapsedTime); SIM.LogSimulation(SIM.Simulation.RainStop, rain == 0f ? EnvironmentEffectsManager.rain.ToString() : rain.ToString(), elapsedTime); SIM.LogSimulation(SIM.Simulation.WetnessStop, wet == 0f ? EnvironmentEffectsManager.wet.ToString() : wet.ToString(), elapsedTime); SIM.LogSimulation(SIM.Simulation.FogStop, fog == 0f ? EnvironmentEffectsManager.fog.ToString() : fog.ToString(), elapsedTime); SIM.LogSimulation(SIM.Simulation.CloudinessStop, cloud == 0f ? EnvironmentEffectsManager.cloud.ToString() : cloud.ToString(), elapsedTime); SIM.LogSimulation(SIM.Simulation.MapStop, string.IsNullOrEmpty(mapName) ? UnityEngine.SceneManagement.SceneManager.GetActiveScene().name : mapName, elapsedTime); SIM.LogSimulation(SIM.Simulation.ClusterNameStop, clusterName, elapsedTime); SIM.LogSimulation(SIM.Simulation.SimulationStop, simulationName, elapsedTime); SIM.StopSession(); DestroyImmediate(ManagerHolder); if (IsAPI) { Scenario.Clear(); } }
void OnCollisionEnter(Collision collision) { if (collision.gameObject.layer == LayerMask.NameToLayer("Agent")) { ApiManager.Instance?.AddCollision(gameObject, collision.gameObject, collision); SIM.LogSimulation(SIM.Simulation.NPCCollision); } }
void OnCollisionEnter(Collision collision) { if (collision.gameObject.layer == LayerMask.GetMask("Obstacle", "Agent", "Pedestrian", "NPC")) { ApiManager.Instance?.AddCollision(gameObject, collision.gameObject, collision); SIM.LogSimulation(SIM.Simulation.EgoCollision); } }
public static void StopAsync() { Debug.Assert(Instance.CurrentSimulation != null); if (Instance.masterManager != null) { Instance.masterManager.BroadcastSimulationStop(); } Instance.Actions.Enqueue(() => { var simulation = Instance.CurrentSimulation; using (var db = DatabaseManager.Open()) { try { simulation.Status = "Stopping"; NotificationManager.SendNotification("simulation", SimulationResponse.Create(simulation), simulation.Owner); if (ApiManager.Instance != null) { SceneManager.MoveGameObjectToScene(ApiManager.Instance.gameObject, SceneManager.GetActiveScene()); } SIM.LogSimulation(SIM.Simulation.ApplicationClick, "Exit"); var loader = SceneManager.LoadSceneAsync(Instance.LoaderScene); loader.completed += op => { if (op.isDone) { AssetBundle.UnloadAllAssetBundles(false); Instance.LoaderUI.SetLoaderUIState(LoaderUI.LoaderUIStateType.START); simulation.Status = "Valid"; NotificationManager.SendNotification("simulation", SimulationResponse.Create(simulation), simulation.Owner); Instance.CurrentSimulation = null; if (Instance.masterManager != null) { Instance.masterManager.StopConnection(); } } }; } catch (Exception ex) { Debug.Log($"Failed to stop '{simulation.Name}' simulation"); Debug.LogException(ex); // NOTE: In case of failure we have to update Simulation state simulation.Status = "Invalid"; simulation.Error = ex.Message; db.Update(simulation); // TODO: take ex.Message and append it to response here NotificationManager.SendNotification("simulation", SimulationResponse.Create(simulation), simulation.Owner); } } }); }
void Start() { if (Instance != null) { Destroy(gameObject); return; } if (!Config.RunAsMaster) { // TODO: change UI and do not run rest of code var obj = new GameObject("ClientManager"); obj.AddComponent <Network.ClientManager>(); } DatabaseManager.Init(); try { var host = Config.WebHost == "*" ? "localhost" : Config.WebHost; Address = $"http://{host}:{Config.WebPort}"; var config = new HostConfiguration { RewriteLocalhost = Config.WebHost == "*" }; Server = new NancyHost(new UnityBootstrapper(), config, new Uri(Address)); Server.Start(); } catch (SocketException ex) { Debug.LogException(ex); #if UNITY_EDITOR UnityEditor.EditorApplication.isPlaying = false; #else // return non-zero exit code Application.Quit(1); #endif return; } DownloadManager.Init(); RestartPendingDownloads(); LoaderScene = SceneManager.GetActiveScene().name; var version = "Development"; var info = Resources.Load <BuildInfo>("BuildInfo"); if (info != null) { version = info.Version; } SIM.Init(version); SIM.LogSimulation(SIM.Simulation.ApplicationStart); DontDestroyOnLoad(this); Instance = this; }
public void SetupSensors(GameObject agent, string sensors, BridgeClient bridgeClient) { var available = Simulator.Web.Config.Sensors.ToDictionary(sensor => sensor.Name); var prefabs = RuntimeSettings.Instance.SensorPrefabs.ToDictionary(sensor => GetSensorType(sensor)); var parents = new Dictionary <string, GameObject>() { { string.Empty, agent }, }; var requested = JSONNode.Parse(sensors).Children.ToList(); while (requested.Count != 0) { int requestedCount = requested.Count; foreach (var parent in parents.Keys.ToArray()) { var parentObject = parents[parent]; for (int i = 0; i < requested.Count; i++) { var item = requested[i]; if (item["parent"].Value == parent) { var name = item["name"].Value; var type = item["type"].Value; SensorConfig config; if (!available.TryGetValue(type, out config)) { throw new Exception($"Unknown sensor type {type} for {gameObject.name} vehicle"); } var sensor = CreateSensor(agent, parentObject, prefabs[type].gameObject, item); sensor.GetComponent <SensorBase>().Name = name; sensor.name = name; SIM.LogSimulation(SIM.Simulation.SensorStart, name); if (bridgeClient != null) { sensor.GetComponent <SensorBase>().OnBridgeSetup(bridgeClient.Bridge); } parents.Add(name, sensor); requested.RemoveAt(i); i--; } } } if (requestedCount == requested.Count) { throw new Exception($"Failed to create {requested.Count} sensor(s), cannot determine parent-child relationship"); } } }
void OnCollisionEnter(Collision collision) { if (collision.gameObject.layer == agentLayer) { ApiManager.Instance?.AddCollision(gameObject, collision.gameObject, collision); SimulatorManager.Instance.AnalysisManager.IncrementNPCCollision(); SIM.LogSimulation(SIM.Simulation.NPCCollision); ActiveBehaviour?.OnAgentCollision(collision.gameObject); } }
private void SetMileTick() { float deltaDistance = WheelsRPM / 60.0f * (Axles[1].Left.radius * 2.0f * Mathf.PI) * Time.fixedDeltaTime; MileTicker += deltaDistance; if ((MileTicker * 0.00062137f) > 1) { MileTicker = 0; SIM.LogSimulation(SIM.Simulation.MileTick); } }
private void OnDisable() { SIM.LogSimulation(SIM.Simulation.VehicleStop, Config.Name, elapsedTime); SIM.LogSimulation(SIM.Simulation.BridgeTypeStop, Config.Bridge != null ? Config.Bridge.Name : "None", elapsedTime); var sensors = SimpleJSON.JSONNode.Parse(Config.Sensors).Children.ToList(); foreach (var sensor in sensors) { SIM.LogSimulation(SIM.Simulation.SensorStop, sensor["name"].Value, elapsedTime); } }
void OnTriggerEnter(Collider other) { if (other.gameObject.layer == agentLayer) { ApiManager.Instance?.AddCollision(rb.gameObject, other.attachedRigidbody.gameObject); SimulatorManager.Instance.AnalysisManager.IncrementNPCCollision(); SIM.LogSimulation(SIM.Simulation.NPCCollision); if (_ActiveBehaviour) { _ActiveBehaviour.OnAgentCollision(other.gameObject); } } }
private void EditorInit() { #if UNITY_EDITOR stopWatch.Start(); var info = Resources.Load <BuildInfo>("BuildInfo"); SIM.Init(info == null ? "Development" : info.Version); SIM.LogSimulation(SIM.Simulation.ApplicationStart); Instance = this; var sim = Instantiate(Instance.SimulatorManagerPrefab); sim.name = "SimulatorManager"; bool useSeed = false; int? seed = null; bool enableNPCs = false; bool enablePEDs = false; var data = UnityEditor.EditorPrefs.GetString("Simulator/DevelopmentSettings"); if (data != null) { try { var json = JSONNode.Parse(data); useSeed = json["UseSeed"]; if (useSeed) { seed = json["Seed"]; } enableNPCs = json["EnableNPCs"]; enablePEDs = json["EnablePEDs"]; } catch (System.Exception ex) { Debug.LogException(ex); } } sim.Init(seed); sim.AgentManager.SetupDevAgents(); sim.NPCManager.NPCActive = enableNPCs; sim.PedestrianManager.PedestriansActive = enablePEDs; #endif }
public GameObject SpawnAgent(AgentConfig config) { var go = Instantiate(config.Prefab); go.name = config.Name; var agentController = go.GetComponent <AgentController>(); agentController.Config = config; SIM.LogSimulation(SIM.Simulation.VehicleStart, config.Name); ActiveAgents.Add(go); agentController.GTID = ++SimulatorManager.Instance.GTIDs; BridgeClient bridgeClient = null; if (config.Bridge != null) { bridgeClient = go.AddComponent <BridgeClient>(); bridgeClient.Init(config.Bridge); if (config.Connection != null) { var split = config.Connection.Split(':'); if (split.Length != 2) { throw new Exception("Incorrect bridge connection string, expected HOSTNAME:PORT"); } bridgeClient.Connect(split[0], int.Parse(split[1])); } } SIM.LogSimulation(SIM.Simulation.BridgeTypeStart, config.Bridge != null ? config.Bridge.Name : "None"); if (!string.IsNullOrEmpty(config.Sensors)) { SetupSensors(go, config.Sensors, bridgeClient); } agentController.AgentSensors.AddRange(agentController.GetComponentsInChildren <SensorBase>(true)); go.transform.position = config.Position; go.transform.rotation = config.Rotation; agentController.Init(); return(go); }
private void OnStartButtonClick() { Application.OpenURL(Loader.Instance.Address + "/"); SIM.LogSimulation(SIM.Simulation.ApplicationClick, "Open Browser"); }
void OnApplicationQuit() { Server?.Stop(); stopWatch.Stop(); SIM.LogSimulation(SIM.Simulation.ApplicationExit, value: (long)stopWatch.Elapsed.TotalSeconds); }
void Start() { if (Instance != null) { Destroy(gameObject); return; } if (!Config.RunAsMaster) { // TODO: change UI and do not run rest of code var clientGameObject = new GameObject("ClientManager"); clientManager = clientGameObject.AddComponent <ClientManager>(); clientManager.SetSettings(NetworkSettings); clientGameObject.AddComponent <MainThreadDispatcher>(); clientManager.StartConnection(); DontDestroyOnLoad(clientGameObject); } DatabaseManager.Init(); DownloadManager.Init(); RestartPendingDownloads(); try { var host = Config.WebHost == "*" ? "localhost" : Config.WebHost; Address = $"http://{host}:{Config.WebPort}"; var config = new HostConfiguration { RewriteLocalhost = Config.WebHost == "*" }; Server = new NancyHost(new UnityBootstrapper(), config, new Uri(Address)); if (!string.IsNullOrEmpty(Config.Username)) { LoginAsync(); } else { Server.Start(); } } catch (SocketException ex) { Debug.LogException(ex); #if UNITY_EDITOR UnityEditor.EditorApplication.isPlaying = false; #else // return non-zero exit code Application.Quit(1); #endif return; } LoaderScene = SceneManager.GetActiveScene().name; SIM.LogSimulation(SIM.Simulation.ApplicationStart); DontDestroyOnLoad(this); Instance = this; }
public GameObject SpawnAgent(AgentConfig config) { var go = Instantiate(config.Prefab, transform); go.name = config.Name; var agentController = go.GetComponent <AgentController>(); agentController.SensorsChanged += AgentControllerOnSensorsChanged; agentController.Config = config; agentController.Config.AgentGO = go; SIM.LogSimulation(SIM.Simulation.VehicleStart, config.Name); ActiveAgents.Add(agentController.Config); agentController.GTID = ++SimulatorManager.Instance.GTIDs; agentController.Config.GTID = agentController.GTID; BridgeClient bridgeClient = null; if (config.Bridge != null) { bridgeClient = go.AddComponent <BridgeClient>(); bridgeClient.Init(config.Bridge); if (config.Connection != null) { var split = config.Connection.Split(':'); if (split.Length != 2) { throw new Exception("Incorrect bridge connection string, expected HOSTNAME:PORT"); } bridgeClient.Connect(split[0], int.Parse(split[1])); } } SIM.LogSimulation(SIM.Simulation.BridgeTypeStart, config.Bridge != null ? config.Bridge.Name : "None"); var sensorsController = go.AddComponent <SensorsController>(); agentController.AgentSensorsController = sensorsController; sensorsController.SetupSensors(config.Sensors); //Add required components for distributing rigidbody from master to clients var network = Loader.Instance.Network; if (network.IsClusterSimulation) { HierarchyUtilities.ChangeToUniqueName(go); if (network.IsClient) { //Disable controller and dynamics on clients so it will not interfere mocked components agentController.enabled = false; var vehicleDynamics = agentController.GetComponent <IVehicleDynamics>() as MonoBehaviour; if (vehicleDynamics != null) { vehicleDynamics.enabled = false; } } //Change the simulation type only if it's not set in the prefab var distributedRigidbody = go.GetComponent <DistributedRigidbody>(); if (distributedRigidbody == null) { distributedRigidbody = go.AddComponent <DistributedRigidbody>(); distributedRigidbody.SimulationType = DistributedRigidbody.MockingSimulationType.ExtrapolateVelocities; } //Add the rest required components for cluster simulation ClusterSimulationUtilities.AddDistributedComponents(go); } go.transform.position = config.Position; go.transform.rotation = config.Rotation; agentController.Init(); #if UNITY_EDITOR // TODO remove hack for editor opaque with alpha clipping 2019.3.3 Array.ForEach(go.GetComponentsInChildren <Renderer>(), renderer => { foreach (var m in renderer.materials) { m.shader = Shader.Find(m.shader.name); } }); Array.ForEach(go.GetComponentsInChildren <DecalProjector>(), decal => { decal.material.shader = Shader.Find(decal.material.shader.name); }); #endif return(go); }
public void FixedUpdate() { if (vehicleController != null) { SteerInput = vehicleController.SteerInput; AccellInput = vehicleController.AccelInput; } //air drag (quadratic) RB.AddForce(-airDragCoeff * RB.velocity * RB.velocity.magnitude); //downforce (quadratic) RB.AddForce(-airDownForceCoeff * RB.velocity.sqrMagnitude * transform.up); //tire drag (Linear) RB.AddForceAtPosition(-tireDragCoeff * RB.velocity, transform.position); //calc current gear ratio float gearRatio = Mathf.Lerp(gearRatios[Mathf.FloorToInt(CurrentGear) - 1], gearRatios[Mathf.CeilToInt(CurrentGear) - 1], CurrentGear - Mathf.Floor(CurrentGear)); if (Reverse) { gearRatio = -1.0f * gearRatios[0]; } //calc engine RPM from wheel rpm float wheelsRPM = (axles[1].right.rpm + axles[1].left.rpm) / 2f; if (wheelsRPM < 0) { wheelsRPM = 0; } // if the engine is on, the fuel injectors are going to be triggered at minRPM // to keep the engine running. If the engine is OFF, then the engine will eventually // go all the way down to 0, because there's nothing keeping it spinning. var minPossibleRPM = IgnitionStatus == IgnitionStatus.On ? minRPM : 0.0f; CurrentRPM = Mathf.Lerp(CurrentRPM, minPossibleRPM + (wheelsRPM * finalDriveRatio * gearRatio), Time.fixedDeltaTime * RPMSmoothness); // I don't know why, but logging RPM while engine is off and we're not moving, is showing // a constant drift between 0.0185 and 0.0192 or so .. so just clamp it down to 0 at that // point. if (CurrentRPM < 0.02f) { CurrentRPM = 0.0f; } //find out which wheels are on the ground foreach (var axle in axles) { axle.isGroundedLeft = axle.left.GetGroundHit(out axle.hitLeft); axle.isGroundedRight = axle.right.GetGroundHit(out axle.hitRight); } //convert inputs to torques float steer = maxSteeringAngle * SteerInput; currentTorque = (float.IsNaN(CurrentRPM / maxRPM)) ? 0.0f : rpmCurve.Evaluate(CurrentRPM / maxRPM) * gearRatio * finalDriveRatio * tractionControlAdjustedMaxTorque; foreach (var axle in axles) { if (axle.steering) { axle.left.steerAngle = steer; axle.right.steerAngle = steer; } } if (HandBrake) { //Make the accellInput negative so that brakes are applied in ApplyTorque() AccellInput = -1.0f; } // No autodrive while engine is off. if (IgnitionStatus == IgnitionStatus.On) { AutoSteer(); } ApplyTorque(); TractionControl(); //shift if need be. No auto shifting while engine is off. if (IgnitionStatus == IgnitionStatus.On) { AutoGearBox(); } //record current speed in MPH CurrentSpeed = RB.velocity.magnitude * 2.23693629f; float deltaDistance = wheelsRPM / 60.0f * (axles[1].left.radius * 2.0f * Mathf.PI) * Time.fixedDeltaTime; odometer += deltaDistance; mileTicker += deltaDistance; if ((mileTicker * 0.00062137f) > 1) { mileTicker = 0; SIM.LogSimulation(SIM.Simulation.MileTick); } /* * // why does this not work :( * float currentRPS = currentRPM / 60.0f; * * float accel = Mathf.Max(0.0f, accellInput); * float angularV = currentRPS * Mathf.PI * 2.0f; * * float power = currentTorque //(rpmCurve.Evaluate(currentRPM / maxRPM) * accel * maxMotorTorque) //Nm * angularV; // Watt * * float energy = power * Time.fixedDeltaTime // w/s * / 1000.0f * 3600.0f; // kw/h * * print("p:" + power + " e:" + energy); * //approximation function for * // https://en.wikipedia.org/wiki/Brake_specific_fuel_consumption#/media/File:Brake_specific_fuel_consumption.svg * // range ~ 200-400 g/kWh * float bsfc = (206.0f + Mathf.Sqrt(Mathf.Pow(currentRPM - 2200, 2.0f) + Mathf.Pow((accel - 0.9f) * 10000.0f, 2.0f)) / 80 + currentRPM / 4500); // g/kWh + + float gasolineDensity = 1f / .75f; // cm^3/g + + float deltaConsumption = bsfc * energy // g * gasolineDensity // cm^3 * / 1000.0f; // l */ // FIXME fix the more correct method above... float deltaConsumption = CurrentRPM * 0.00000001f + currentTorque * 0.000000001f * Mathf.Max(0.0f, AccellInput); // if engine is not powered up, or there's zero acceleration, AND we're not idling // the engine to keep it on, then the fuel injectors are off, and no fuel is being used // idling == non-scientific calculation of "minRPM + 25%". if (IgnitionStatus != IgnitionStatus.On || (AccellInput <= 0.0f && CurrentRPM > minRPM + (minRPM * 0.25))) { deltaConsumption = 0.0f; } consumptionDistance = deltaConsumption / deltaDistance; // l/m consumptionTime = deltaConsumption / Time.fixedDeltaTime; // l/s fuelLevel -= deltaConsumption; float engineWeight = 200.0f; // kg float energyDensity = 34.2f * 1000.0f * 1000.0f; // J/l fuel float specificHeatIron = 448.0f; // J/kg for 1K temperature increase EngineTemperatureK += (deltaConsumption * energyDensity) / (specificHeatIron * engineWeight); float coolFactor = 0.00002f; //ambient exchange if (EngineTemperatureK > ZERO_K + 90.0f && !CoolingMalfunction) { coolFactor += 0.00002f + 0.0001f * Mathf.Max(0.0f, CurrentSpeed); // working temperature reached, start cooling } EngineTemperatureK = Mathf.Lerp(EngineTemperatureK, AmbientTemperatureK, coolFactor); //find current road surface type WheelHit hit; if (axles[0].left.GetGroundHit(out hit)) { traction = hit.forwardSlip; // ground var roadObject = hit.collider.transform.parent == null ? hit.collider.transform : hit.collider.transform.parent; } else { traction = 0f; // air } CurrentSpeedMeasured = ((RB.position - lastRBPosition) / Time.fixedDeltaTime).magnitude; lastRBPosition = RB.position; }
private void InstantiateSensors(string sensors) { var available = Simulator.Web.Config.Sensors.ToDictionary(sensor => sensor.Name); var prefabs = Simulator.Web.Config.SensorPrefabs.ToDictionary(sensor => GetSensorType(sensor)); var parents = new Dictionary <string, GameObject>() { { string.Empty, gameObject }, }; var agentController = GetComponent <AgentController>(); var requested = JSONNode.Parse(sensors).Children.ToList(); while (requested.Count != 0) { int requestedCount = requested.Count; foreach (var parent in parents.Keys.ToArray()) { var parentObject = parents[parent]; for (int i = 0; i < requested.Count; i++) { var item = requested[i]; if (item["parent"].Value == parent) { var name = item["name"].Value; var type = item["type"].Value; SensorConfig config; if (!available.TryGetValue(type, out config)) { throw new Exception($"Unknown sensor type {type} for {gameObject.name} vehicle"); } var sensor = CreateSensor(gameObject, parentObject, prefabs[type].gameObject, item); var sensorBase = sensor.GetComponent <SensorBase>(); sensorBase.Name = name; sensor.name = name; SIM.LogSimulation(SIM.Simulation.SensorStart, name); if (AgentBridgeClient != null) { sensor.GetComponent <SensorBase>().OnBridgeSetup(AgentBridgeClient.Bridge); } parents.Add(name, sensor); requested.RemoveAt(i); i--; var sensorInstanceController = new SensorInstanceController(item, sensorBase); if (SimulatorManager.InstanceAvailable) { SimulatorManager.Instance.Sensors.RegisterSensor(sensorBase); } sensorInstanceController.Enable(); agentController.AgentSensors.Add(sensorBase); sensorsInstances.Add(name, sensorInstanceController); } } } if (requestedCount == requested.Count) { throw new Exception( $"Failed to create {requested.Count} sensor(s), cannot determine parent-child relationship"); } SensorsChanged?.Invoke(); } }
public void Init(int?seed = null) { if (ApiManager.Instance != null) { FixedUpdateManager = ApiManager.Instance; IsAPI = true; } else { FixedUpdateManager = Instance; IsAPI = false; } controls = new SimulatorControls(); controls.Enable(); SimulationConfig config = null; if (Loader.Instance != null) { config = Loader.Instance.SimConfig; } var masterSeed = seed ?? config?.Seed ?? new System.Random().Next(); RandomGenerator = new System.Random(masterSeed); //Calculate map bounds and limit position compression if (Loader.Instance != null && Loader.Instance.Network.IsClusterSimulation) { var mapBounds = CalculateMapBounds(); //Add margin to the bounds mapBounds.size += Vector3.one * 10; ByteCompression.SetPositionBounds(mapBounds); } ManagerHolder = new GameObject("ManagerHolder"); ManagerHolder.transform.SetParent(transform); AnalysisManager = Instantiate(analysisManagerPrefab, ManagerHolder.transform); AgentManager = Instantiate(agentManagerPrefab, ManagerHolder.transform); CameraManager = Instantiate(cameraManagerPrefab, ManagerHolder.transform); ControllableManager = Instantiate(controllableManagerPrefab, ManagerHolder.transform); MapManager = Instantiate(mapManagerPrefab, ManagerHolder.transform); NPCManager = Instantiate(npcManagerPrefab, ManagerHolder.transform); NPCManager.InitRandomGenerator(RandomGenerator.Next()); PedestrianManager = Instantiate(pedestrianManagerPrefab, ManagerHolder.transform); PedestrianManager.InitRandomGenerator(RandomGenerator.Next()); EnvironmentEffectsManager = Instantiate(environmentEffectsManagerPrefab, ManagerHolder.transform); EnvironmentEffectsManager.InitRandomGenerator(RandomGenerator.Next()); UIManager = Instantiate(uiManagerPrefab, ManagerHolder.transform); if (SystemInfo.operatingSystemFamily == OperatingSystemFamily.Linux && Application.isEditor) { // empty } else { controls.Simulator.ToggleNPCS.performed += ctx => NPCManager.NPCActive = !NPCManager.NPCActive; controls.Simulator.TogglePedestrians.performed += ctx => PedestrianManager.PedestriansActive = !PedestrianManager.PedestriansActive; controls.Simulator.ToggleAgent.performed += ctx => { if (int.TryParse(ctx.control.name, out int index)) { AgentManager.SetCurrentActiveAgent(index - 1); } }; controls.Simulator.ToggleReset.performed += ctx => AgentManager.ResetAgent(); controls.Simulator.ToggleControlsUI.performed += ctx => UIManager.UIActive = !UIManager.UIActive; } if (config != null) { simulationName = config.Name; clusterName = config.ClusterName; mapName = config.MapName; NPCManager.NPCActive = config.UseTraffic; PedestrianManager.PedestriansActive = config.UsePedestrians; if (config.Agents != null) { AgentManager.SpawnAgents(config.Agents); } apiMode = config.ApiOnly; headless = config.Headless; interactive = config.Interactive; useSeed = config.Seed.HasValue; npc = config.UseTraffic; pedestrian = config.UsePedestrians; timeOfDay = config.TimeOfDay.ToString("HH:mm"); rain = config.Rain; wet = config.Wetness; fog = config.Fog; cloud = config.Cloudiness; if (headless) { controls.Disable(); } } SIM.APIOnly = apiMode; SIM.LogSimulation(SIM.Simulation.SimulationStart, simulationName); SIM.LogSimulation(SIM.Simulation.ClusterNameStart, clusterName); SIM.LogSimulation(SIM.Simulation.MapStart, string.IsNullOrEmpty(mapName) ? UnityEngine.SceneManagement.SceneManager.GetActiveScene().name : mapName); SIM.LogSimulation(SIM.Simulation.HeadlessModeStart, state: headless); SIM.LogSimulation(SIM.Simulation.InteractiveModeStart, state: interactive); SIM.LogSimulation(SIM.Simulation.UsePredefinedSeedStart, state: useSeed); SIM.LogSimulation(SIM.Simulation.NPCStart, state: npc); SIM.LogSimulation(SIM.Simulation.RandomPedestrianStart, state: pedestrian); SIM.LogSimulation(SIM.Simulation.TimeOfDayStart, timeOfDay == "" ? string.Format("{0:hh}:{0:mm}", TimeSpan.FromHours(EnvironmentEffectsManager.currentTimeOfDay)) : timeOfDay); SIM.LogSimulation(SIM.Simulation.RainStart, rain == 0f ? EnvironmentEffectsManager.rain.ToString() : rain.ToString()); SIM.LogSimulation(SIM.Simulation.WetnessStart, wet == 0f ? EnvironmentEffectsManager.wet.ToString() : wet.ToString()); SIM.LogSimulation(SIM.Simulation.FogStart, fog == 0f ? EnvironmentEffectsManager.fog.ToString() : fog.ToString()); SIM.LogSimulation(SIM.Simulation.CloudinessStart, cloud == 0f ? EnvironmentEffectsManager.cloud.ToString() : cloud.ToString()); InitSegmenationColors(); WireframeBoxes = gameObject.AddComponent <WireframeBoxes>(); if (Loader.Instance != null) { TimeManager.Initialize(Loader.Instance.Network.MessagesManager); } Sensors.Initialize(); Loader.ResetMaterials(); // TODO remove Editor hack for 2019.3.3 bug once fixed IsInitialized = true; }
public void Init(int?seed = null) { controls = new SimulatorControls(); controls.Enable(); var config = Loader.Instance?.SimConfig; var masterSeed = seed ?? config?.Seed ?? new System.Random().Next(); System.Random rand = new System.Random(masterSeed); AgentManager = Instantiate(agentManagerPrefab, transform); CameraManager = Instantiate(cameraManagerPrefab, transform); MapManager = Instantiate(mapManagerPrefab, transform); NPCManager = Instantiate(npcManagerPrefab, transform); NPCManager.InitRandomGenerator(rand.Next()); PedestrianManager = Instantiate(pedestrianManagerPrefab, transform); PedestrianManager.InitRandomGenerator(rand.Next()); EnvironmentEffectsManager = Instantiate(environmentEffectsManagerPrefab, transform); EnvironmentEffectsManager.InitRandomGenerator(rand.Next()); UIManager = Instantiate(uiManagerPrefab, transform); if (ApiManager.Instance != null) { IsAPI = true; } if (SystemInfo.operatingSystemFamily == OperatingSystemFamily.Linux && Application.isEditor) { // empty } else { controls.Simulator.ToggleNPCS.performed += ctx => NPCManager.NPCActive = !NPCManager.NPCActive; controls.Simulator.TogglePedestrians.performed += ctx => PedestrianManager.PedestriansActive = !PedestrianManager.PedestriansActive; controls.Simulator.ToggleAgent.performed += ctx => { if (int.TryParse(ctx.control.name, out int index)) { AgentManager.SetCurrentActiveAgent(index - 1); } }; controls.Simulator.ToggleReset.performed += ctx => AgentManager.ResetAgent(); controls.Simulator.ToggleControlsUI.performed += ctx => UIManager.UIActive = !UIManager.UIActive; } if (config != null) { simulationName = config.Name; clusterName = config.ClusterName; mapName = config.MapName; NPCManager.NPCActive = config.UseTraffic; PedestrianManager.PedestriansActive = config.UsePedestrians; if (config.Agents != null) { AgentManager.SpawnAgents(config.Agents); } apiMode = config.ApiOnly; headless = config.Headless; interactive = config.Interactive; useSeed = config.Seed.HasValue; npc = config.UseTraffic; pedestrian = config.UsePedestrians; timeOfDay = config.TimeOfDay.ToString("HH:mm"); rain = config.Rain; wet = config.Wetness; fog = config.Fog; cloud = config.Cloudiness; if (headless) { controls.Disable(); } if (config.Interactive) { SetTimeScale(0.0f); } } SIM.APIOnly = apiMode; SIM.LogSimulation(SIM.Simulation.SimulationStart, simulationName); SIM.LogSimulation(SIM.Simulation.ClusterNameStart, clusterName); SIM.LogSimulation(SIM.Simulation.MapStart, string.IsNullOrEmpty(mapName) ? UnityEngine.SceneManagement.SceneManager.GetActiveScene().name : mapName); SIM.LogSimulation(SIM.Simulation.HeadlessModeStart, state: headless); SIM.LogSimulation(SIM.Simulation.InteractiveModeStart, state: interactive); SIM.LogSimulation(SIM.Simulation.UsePredefinedSeedStart, state: useSeed); SIM.LogSimulation(SIM.Simulation.NPCStart, state: npc); SIM.LogSimulation(SIM.Simulation.RandomPedestrianStart, state: pedestrian); SIM.LogSimulation(SIM.Simulation.TimeOfDayStart, timeOfDay == "" ? string.Format("{0:hh}:{0:mm}", TimeSpan.FromHours(EnvironmentEffectsManager.currentTimeOfDay)) : timeOfDay); SIM.LogSimulation(SIM.Simulation.RainStart, rain == 0f ? EnvironmentEffectsManager.rain.ToString() : rain.ToString()); SIM.LogSimulation(SIM.Simulation.WetnessStart, wet == 0f ? EnvironmentEffectsManager.wet.ToString() : wet.ToString()); SIM.LogSimulation(SIM.Simulation.FogStart, fog == 0f ? EnvironmentEffectsManager.fog.ToString() : fog.ToString()); SIM.LogSimulation(SIM.Simulation.CloudinessStart, cloud == 0f ? EnvironmentEffectsManager.cloud.ToString() : cloud.ToString()); InitSemanticTags(); WireframeBoxes = gameObject.AddComponent <WireframeBoxes>(); }
public GameObject SpawnAgent(AgentConfig config) { var go = Instantiate(config.Prefab, transform); go.name = config.Name; var agentController = go.GetComponent <AgentController>(); agentController.SensorsChanged += AgentControllerOnSensorsChanged; agentController.Config = config; agentController.Config.AgentGO = go; var lane = go.AddComponent <VehicleLane>(); var baseLink = go.GetComponentInChildren <BaseLink>(); if (baseLink == null) { baseLink = new GameObject("BaseLink").AddComponent <BaseLink>(); baseLink.transform.SetParent(go.transform, false); } SIM.LogSimulation(SIM.Simulation.VehicleStart, config.Name); ActiveAgents.Add(agentController.Config); agentController.GTID = ++SimulatorManager.Instance.GTIDs; agentController.Config.GTID = agentController.GTID; BridgeClient bridgeClient = null; if (config.Bridge != null) { bridgeClient = go.AddComponent <BridgeClient>(); bridgeClient.Init(config.Bridge); if (config.Connection != null) { bridgeClient.Connect(config.Connection); } } SIM.LogSimulation(SIM.Simulation.BridgeTypeStart, config.Bridge != null ? config.Bridge.Name : "None"); var sensorsController = go.AddComponent <SensorsController>(); agentController.AgentSensorsController = sensorsController; sensorsController.SetupSensors(config.Sensors); //Add required components for distributing rigidbody from master to clients var network = Loader.Instance.Network; if (network.IsClusterSimulation) { HierarchyUtilities.ChangeToUniqueName(go); if (network.IsClient) { //Disable controller and dynamics on clients so it will not interfere mocked components agentController.enabled = false; var vehicleDynamics = agentController.GetComponent <IVehicleDynamics>() as MonoBehaviour; if (vehicleDynamics != null) { vehicleDynamics.enabled = false; } } //Change the simulation type only if it's not set in the prefab var distributedRigidbody = go.GetComponent <DistributedRigidbody>(); if (distributedRigidbody == null) { distributedRigidbody = go.AddComponent <DistributedRigidbody>(); distributedRigidbody.SimulationType = DistributedRigidbody.MockingSimulationType.ExtrapolateVelocities; } //Add the rest required components for cluster simulation ClusterSimulationUtilities.AddDistributedComponents(go); } go.transform.position = config.Position; go.transform.rotation = config.Rotation; agentController.Init(); return(go); }
private void Init() { RenderLimiter.RenderLimitEnabled(); if (Instance != null) { Destroy(gameObject); return; } stopWatch.Start(); var info = Resources.Load <BuildInfo>("BuildInfo"); SIM.Init(info == null ? "Development" : info.Version); if (PlayerPrefs.HasKey("Salt")) { Config.salt = StringToByteArray(PlayerPrefs.GetString("Salt")); } else { Config.salt = new byte[8]; RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetBytes(Config.salt); PlayerPrefs.SetString("Salt", ByteArrayToString(Config.salt)); PlayerPrefs.Save(); } if (Config.RunAsMaster) { var masterGameObject = new GameObject("MasterManager"); Network.Master = masterGameObject.AddComponent <MasterManager>(); masterGameObject.AddComponent <MainThreadDispatcher>(); Network.Master.SetSettings(NetworkSettings); Network.Master.StartConnection(); DontDestroyOnLoad(masterGameObject); } else { var clientGameObject = new GameObject("ClientManager"); Network.Client = clientGameObject.AddComponent <ClientManager>(); clientGameObject.AddComponent <MainThreadDispatcher>(); Network.Client.SetSettings(NetworkSettings); Network.Client.StartConnection(); Network.Initialize(SimulationNetwork.ClusterNodeType.Client, NetworkSettings); DontDestroyOnLoad(clientGameObject); } DatabaseManager.Init(); DownloadManager.Init(); RestartPendingDownloads(); if (Config.RunAsMaster) { try { var host = Config.WebHost == "*" ? "localhost" : Config.WebHost; Address = $"http://{host}:{Config.WebPort}"; var config = new HostConfiguration { RewriteLocalhost = Config.WebHost == "*" }; Server = new NancyHost(new UnityBootstrapper(), config, new Uri(Address)); if (!string.IsNullOrEmpty(Config.Username)) { LoginAsync(); } else { Server.Start(); } } catch (SocketException ex) { Debug.LogException(ex); #if UNITY_EDITOR UnityEditor.EditorApplication.isPlaying = false; #else // return non-zero exit code Application.Quit(1); #endif return; } } LoaderScene = SceneManager.GetActiveScene().name; SIM.LogSimulation(SIM.Simulation.ApplicationStart); DontDestroyOnLoad(this); Instance = this; }
private static void LogPlayModeState(PlayModeStateChange state) { if (state == PlayModeStateChange.EnteredPlayMode) { Scene scene = SceneManager.GetActiveScene(); if (scene.name == "LoaderScene") { var data = EditorPrefs.GetString("Simulator/DevelopmentSettings"); if (data != null) { var json = JSONNode.Parse(data); if (json["EnableAPI"].AsBool) { var api = Object.Instantiate(Simulator.Loader.Instance.ApiManagerPrefab); api.name = "ApiManager"; Simulator.Loader.Instance.LoaderUI.SetLoaderUIState(LoaderUI.LoaderUIStateType.READY); } } } else { var simObj = AssetDatabase.LoadAssetAtPath <GameObject>("Assets/Prefabs/Managers/SimulatorManager.prefab"); if (simObj == null) { Debug.LogError("Missing SimulatorManager.prefab in Resources folder!"); return; } stopWatch.Start(); var version = "Development"; var info = Resources.Load <BuildInfo>("BuildInfo"); if (info != null) { version = info.Version; } SIM.Init(version); SIM.LogSimulation(SIM.Simulation.ApplicationStart); var sim = Object.Instantiate(simObj).GetComponent <SimulatorManager>(); sim.name = "SimulatorManager"; bool useSeed = false; int? seed = null; bool enableNPCs = false; bool enablePEDs = false; var data = EditorPrefs.GetString("Simulator/DevelopmentSettings"); if (data != null) { try { var json = JSONNode.Parse(data); useSeed = json["UseSeed"]; if (useSeed) { seed = json["Seed"]; } enableNPCs = json["EnableNPCs"]; enablePEDs = json["EnablePEDs"]; } catch (System.Exception ex) { Debug.LogException(ex); } } sim.Init(seed); sim.AgentManager.SetupDevAgents(); sim.NPCManager.NPCActive = enableNPCs; sim.PedestrianManager.PedestriansActive = enablePEDs; } } else if (state == PlayModeStateChange.ExitingPlayMode) { if (stopWatch.IsRunning) { stopWatch.Stop(); SIM.LogSimulation(SIM.Simulation.ApplicationExit, value: (long)stopWatch.Elapsed.TotalSeconds); } } }
public GameObject SpawnAgent(AgentConfig config) { var go = Instantiate(config.Prefab, transform); go.name = config.Name; var agentController = go.GetComponent <AgentController>(); agentController.SensorsChanged += AgentControllerOnSensorsChanged; agentController.Config = config; SIM.LogSimulation(SIM.Simulation.VehicleStart, config.Name); ActiveAgents.Add(go); agentController.GTID = ++SimulatorManager.Instance.GTIDs; BridgeClient bridgeClient = null; if (config.Bridge != null) { bridgeClient = go.AddComponent <BridgeClient>(); bridgeClient.Init(config.Bridge); if (config.Connection != null) { var split = config.Connection.Split(':'); if (split.Length != 2) { throw new Exception("Incorrect bridge connection string, expected HOSTNAME:PORT"); } bridgeClient.Connect(split[0], int.Parse(split[1])); } } SIM.LogSimulation(SIM.Simulation.BridgeTypeStart, config.Bridge != null ? config.Bridge.Name : "None"); var sensorsController = go.AddComponent <SensorsController>(); agentController.AgentSensorsController = sensorsController; sensorsController.SetupSensors(config.Sensors); //Add required components for distributing rigidbody from master to clients var network = SimulatorManager.Instance.Network; if (network.IsMaster) { if (go.GetComponent <DistributedObject>() == null) { go.AddComponent <DistributedObject>(); } var distributedRigidbody = go.GetComponent <DistributedRigidbody>(); if (distributedRigidbody == null) { distributedRigidbody = go.AddComponent <DistributedRigidbody>(); } distributedRigidbody.SimulationType = MockedRigidbody.MockingSimulationType.ExtrapolateVelocities; } else if (network.IsClient) { //Disable controller and dynamics on clients so it will not interfere mocked components agentController.enabled = false; var vehicleDynamics = agentController.GetComponent <VehicleDynamics>(); if (vehicleDynamics != null) { vehicleDynamics.enabled = false; } //Add mocked components if (go.GetComponent <MockedObject>() == null) { go.AddComponent <MockedObject>(); } var mockedRigidbody = go.GetComponent <MockedRigidbody>(); if (mockedRigidbody == null) { mockedRigidbody = go.AddComponent <MockedRigidbody>(); } mockedRigidbody.SimulationType = MockedRigidbody.MockingSimulationType.ExtrapolateVelocities; } go.transform.position = config.Position; go.transform.rotation = config.Rotation; agentController.Init(); return(go); }