Esempio n. 1
0
 /// <summary>
 /// Initializes the simulation, adds <see cref="ClientObjectsRoot"/> component to the root game object
 /// </summary>
 /// <param name="rootGameObject">Root game object where new component will be added</param>
 public void InitializeSimulationScene(GameObject rootGameObject)
 {
     objectsRoot = rootGameObject.AddComponent <ClientObjectsRoot>();
     ObjectsRoot.SetMessagesManager(MessagesManager);
     ObjectsRoot.SetSettings(settings);
     Log.Info($"{GetType().Name} initialized the simulation.");
     SendLoadedCommand();
     State = SimulationState.Running;
 }
Esempio n. 2
0
 /// <summary>
 /// Initializes the simulation, adds <see cref="ClientObjectsRoot"/> component to the root game object
 /// </summary>
 /// <param name="rootGameObject">Root game object where new component will be added</param>
 public void InitializeSimulation(GameObject rootGameObject)
 {
     objectsRoot = rootGameObject.AddComponent <ClientObjectsRoot>();
     ObjectsRoot.SetMessagesManager(MessagesManager);
     ObjectsRoot.SetSettings(settings);
 }
Esempio n. 3
0
        /// <summary>
        /// Download required for the simulation vehicle bundles from the server
        /// </summary>
        /// <param name="load">Load command from the server</param>
        /// <param name="mapBundlePath">Path where the map bundle will be saved</param>
        private void LoadMapBundle(Commands.Load load, string mapBundlePath)
        {
            var vehicleBundles = new List <string>();

            DownloadVehicleBundles(load, vehicleBundles, () =>
            {
                if (MasterPeer == null)
                {
                    Debug.LogWarning("Master peer has disconnected while loading the simulation scene.");
                    Loader.ResetLoaderScene();
                    return;
                }
                var zip = new ZipFile(mapBundlePath);
                {
                    string manfile;
                    ZipEntry entry = zip.GetEntry("manifest");
                    using (var ms = zip.GetInputStream(entry))
                    {
                        int streamSize = (int)entry.Size;
                        byte[] buffer  = new byte[streamSize];
                        streamSize     = ms.Read(buffer, 0, streamSize);
                        manfile        = Encoding.UTF8.GetString(buffer);
                    }

                    Manifest manifest = new Deserializer().Deserialize <Manifest>(manfile);

                    AssetBundle textureBundle = null;

                    if (zip.FindEntry(($"{manifest.bundleGuid}_environment_textures"), false) != -1)
                    {
                        var texStream = zip.GetInputStream(zip.GetEntry($"{manifest.bundleGuid}_environment_textures"));
                        textureBundle = AssetBundle.LoadFromStream(texStream, 0, 1 << 20);
                    }

                    string platform = SystemInfo.operatingSystemFamily == OperatingSystemFamily.Windows
                        ? "windows"
                        : "linux";
                    var mapStream =
                        zip.GetInputStream(zip.GetEntry($"{manifest.bundleGuid}_environment_main_{platform}"));
                    var mapBundle = AssetBundle.LoadFromStream(mapStream, 0, 1 << 20);

                    if (mapBundle == null)
                    {
                        throw new Exception($"Failed to load environment from '{load.MapName}' asset bundle");
                    }

                    textureBundle?.LoadAllAssets();

                    var scenes = mapBundle.GetAllScenePaths();
                    if (scenes.Length != 1)
                    {
                        throw new Exception(
                            $"Unsupported environment in '{load.MapName}' asset bundle, only 1 scene expected");
                    }

                    var sceneName = Path.GetFileNameWithoutExtension(scenes[0]);

                    var loader        = SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive);
                    loader.completed += op =>
                    {
                        if (op.isDone)
                        {
                            SceneManager.SetActiveScene(SceneManager.GetSceneByName(sceneName));
                            textureBundle?.Unload(false);
                            mapBundle.Unload(false);
                            zip.Close();

                            try
                            {
                                var prefabs = LoadVehicleBundles(vehicleBundles);

                                Loader.Instance.SimConfig = new SimulationConfig()
                                {
                                    Name           = load.Name,
                                    ApiOnly        = load.ApiOnly,
                                    Headless       = load.Headless,
                                    Interactive    = load.Interactive,
                                    TimeOfDay      = DateTime.ParseExact(load.TimeOfDay, "o", CultureInfo.InvariantCulture),
                                    Rain           = load.Rain,
                                    Fog            = load.Fog,
                                    Wetness        = load.Wetness,
                                    Cloudiness     = load.Cloudiness,
                                    UseTraffic     = load.UseTraffic,
                                    UsePedestrians = load.UsePedestrians,
                                    Agents         = load.Agents.Zip(prefabs, (agent, prefab) =>
                                    {
                                        var config = new AgentConfig()
                                        {
                                            Name       = agent.Name,
                                            Prefab     = prefab,
                                            Connection = agent.Connection,
                                            Sensors    = agent.Sensors,
                                        };

                                        if (!string.IsNullOrEmpty(agent.Bridge))
                                        {
                                            config.Bridge =
                                                Web.Config.Bridges.Find(bridge => bridge.Name == agent.Bridge);
                                            if (config.Bridge == null)
                                            {
                                                throw new Exception($"Bridge {agent.Bridge} not found");
                                            }
                                        }

                                        return(config);
                                    }).ToArray(),
                                };

                                Loader.Instance.CurrentSimulation        = CreateSimulationModel(Loader.Instance.SimConfig);
                                Loader.Instance.CurrentSimulation.Status = "Running";
                                Loader.CreateSimulationManager();
                                objectsRoot = SimulatorManager.Instance.gameObject.AddComponent <ClientObjectsRoot>();
                                objectsRoot.SetMessagesManager(MessagesManager);
                                objectsRoot.SetSettings(settings);

                                // Notify WebUI simulation is running
                                NotificationManager.SendNotification("simulation",
                                                                     SimulationResponse.Create(Loader.Instance.CurrentSimulation),
                                                                     Loader.Instance.CurrentSimulation.Owner);

                                Debug.Log($"Client ready to start");

                                var result = new Commands.LoadResult()
                                {
                                    Success = true,
                                };

                                Loader.Instance.LoaderUI.SetLoaderUIState(LoaderUI.LoaderUIStateType.READY);
                                if (MasterPeer == null)
                                {
                                    Debug.LogWarning("Master peer has disconnected while loading the simulation scene.");
                                    Loader.ResetLoaderScene();
                                    return;
                                }
                                UnicastMessage(MasterPeer.PeerEndPoint, new Message(Key,
                                                                                    new BytesStack(PacketsProcessor.Write(result), false),
                                                                                    MessageType.ReliableOrdered));

                                State = SimulationState.Ready;
                            }
                            catch (Exception ex)
                            {
                                Debug.LogException(ex);

                                var err = new Commands.LoadResult()
                                {
                                    Success      = false,
                                    ErrorMessage = ex.ToString(),
                                };
                                UnicastMessage(MasterPeer.PeerEndPoint, new Message(Key,
                                                                                    new BytesStack(PacketsProcessor.Write(err), false),
                                                                                    MessageType.ReliableOrdered));

                                Loader.ResetLoaderScene();
                            }
                        }
                    };
                }
            });
        }