Esempio n. 1
0
        internal static void LoadMultiplayer(MyObjectBuilder_World world, MyMultiplayerBase multiplayerSession)
        {
            //MyAudio.Static.Mute = true;
            Static = new MySession(multiplayerSession.SyncLayer);
            Static.Mods = world.Checkpoint.Mods;
            Static.Settings = world.Checkpoint.Settings;
            Static.CurrentPath = MyLocalCache.GetSessionSavesPath(MyUtils.StripInvalidChars(world.Checkpoint.SessionName), false, false);
            if (!MyDefinitionManager.Static.TryGetDefinition<MyScenarioDefinition>(world.Checkpoint.Scenario, out Static.Scenario))
                Static.Scenario = MyDefinitionManager.Static.GetScenarioDefinitions().FirstOrDefault();
            FixIncorrectSettings(Static.Settings);

            Static.InGameTime = MyObjectBuilder_Checkpoint.DEFAULT_DATE;

            Static.LoadMembersFromWorld(world, multiplayerSession);

            MySandboxGame.Static.SessionCompatHelper.FixSessionComponentObjectBuilders(world.Checkpoint, world.Sector);

            Static.PrepareBaseSession(world.Checkpoint, world.Sector);

            // No controlled object
            long hostObj = world.Checkpoint.ControlledObject;
            world.Checkpoint.ControlledObject = -1;

            if (multiplayerSession != null)
            {
                MyHud.Chat.RegisterChat(multiplayerSession);
                Static.Gpss.RegisterChat(multiplayerSession);
            }

            Static.CameraController = MySpectatorCameraController.Static;

            Static.LoadWorld(world.Checkpoint, world.Sector);

            if (Sync.IsServer)
            {
                Static.InitializeFactions();
            }

            Static.Settings.AutoSaveInMinutes = 0;

            Static.IsCameraAwaitingEntity = true;

            multiplayerSession.StartProcessingClientMessages();

            MyLocalCache.ClearLastSessionInfo();

            MyNetworkStats.Static.ClearStats();
            Sync.Layer.TransportLayer.ClearStats();

            Static.BeforeStartComponents();
        }
Esempio n. 2
0
        internal static void CreateWithEmptyWorld(MyMultiplayerBase multiplayerSession)
        {
            Debug.Assert(!Sync.IsServer);

            Static = new MySession(multiplayerSession.SyncLayer, false);
            Static.InGameTime = MyObjectBuilder_Checkpoint.DEFAULT_DATE;

            MyHud.Chat.RegisterChat(multiplayerSession);
            Static.Gpss.RegisterChat(multiplayerSession);

            Static.CameraController = MySpectatorCameraController.Static;

            Static.Settings = new MyObjectBuilder_SessionSettings();
            Static.Settings.Battle = true;
            Static.Settings.AutoSaveInMinutes = 0;

            Static.IsCameraAwaitingEntity = true;

            Static.PrepareBaseSession(new List<MyObjectBuilder_Checkpoint.ModItem>());

            multiplayerSession.StartProcessingClientMessagesWithEmptyWorld();

            if (Sync.IsServer)
            {
                Static.InitializeFactions();
            }

            MyLocalCache.ClearLastSessionInfo();

            // Player must be created for selection in factions.
            if (!Engine.Platform.Game.IsDedicated && Static.LocalHumanPlayer == null)
            {
                Sync.Players.RequestNewPlayer(0, MySteam.UserName, null);
            }

            MyNetworkStats.Static.ClearStats();
            Sync.Layer.TransportLayer.ClearStats();
        }
Esempio n. 3
0
        /// <summary>
        /// Initializes a new single player session and start new game with parameters
        /// </summary>
        public static void Start(
            string name,
            string description,
            string password,
            MyObjectBuilder_SessionSettings settings,
            List<MyObjectBuilder_Checkpoint.ModItem> mods,
            MyWorldGenerator.Args generationArgs)
        {
            MyLog.Default.WriteLineAndConsole("Starting world " + name);

            MyEntityContainerEventExtensions.InitEntityEvents();

            Static = new MySession();
            Static.Name = name;
            Static.Mods = mods;
            Static.Description = description;
            Static.Password = password;
            Static.Settings = settings;
            Static.Scenario = generationArgs.Scenario;
            FixIncorrectSettings(Static.Settings);

            double radius = settings.WorldSizeKm * 500; //half size
            if (radius > 0)
            {
                Static.WorldBoundaries = new BoundingBoxD(new Vector3D(-radius, -radius, -radius), new Vector3D(radius, radius, radius));
            }

            Static.InGameTime = generationArgs.Scenario.GameDate;//MyObjectBuilder_Checkpoint.DEFAULT_DATE;
            Static.RequiresDX = generationArgs.Scenario.HasPlanets ? 11 : 9;

            if (Static.OnlineMode != MyOnlineModeEnum.OFFLINE)
                StartServerRequest();

            Static.IsCameraAwaitingEntity = true;

            // Find new non existing folder. The game folder name may be different from game name, so we have to
            // make sure we don't overwrite another save
            string safeName = MyUtils.StripInvalidChars(name);
            Static.CurrentPath = MyLocalCache.GetSessionSavesPath(safeName, false, false);

            while (Directory.Exists(Static.CurrentPath))
            {
                Static.CurrentPath = MyLocalCache.GetSessionSavesPath(safeName + MyUtils.GetRandomInt(int.MaxValue).ToString("########"), false, false);
            }

            Static.PrepareBaseSession(mods, generationArgs.Scenario);

            MySector.EnvironmentDefinition = MyDefinitionManager.Static.GetDefinition<MyEnvironmentDefinition>(generationArgs.Scenario.Environment);

            MyWorldGenerator.GenerateWorld(generationArgs);

            if (Sync.IsServer)
            {
                // Factions have to be initialized before world is generated/loaded.
                Static.InitializeFactions();
            }

            if (!Engine.Platform.Game.IsDedicated)
            {
                var playerId = new MyPlayer.PlayerId(Sync.MyId, 0);
                MyToolBarCollection.RequestCreateToolbar(playerId);
            }

            Static.SendSessionStartStats();
            var scenarioName = generationArgs.Scenario.DisplayNameText.ToString();
            Static.LogSettings(scenarioName, generationArgs.AsteroidAmount);

            if (generationArgs.Scenario.SunDirection.IsValid())
            {
                MySector.SunProperties.SunDirectionNormalized = Vector3.Normalize(generationArgs.Scenario.SunDirection);
                MySector.SunProperties.BaseSunDirectionNormalized = Vector3.Normalize(generationArgs.Scenario.SunDirection);
            }

            //Because blocks fills SubBlocks in this method..
            //TODO: Create LoadPhase2
            
            MyEntities.UpdateOnceBeforeFrame();
            Static.BeforeStartComponents();

            Static.Save();
            MyLocalCache.SaveLastLoadedTime(Static.CurrentPath, DateTime.Now);

            // Initialize Spectator light
            MySpectatorCameraController.Static.InitLight(false);
        }
Esempio n. 4
0
        public static void Load(string sessionPath, MyObjectBuilder_Checkpoint checkpoint, ulong checkpointSizeInBytes)
        {
            ProfilerShort.Begin("MySession.Static.Load");

            MyLog.Default.WriteLineAndConsole("Loading session: " + sessionPath);

            //MyAudio.Static.Mute = true;

            MyLocalCache.SaveLastLoadedTime(sessionPath, DateTime.Now);

            MyEntityIdentifier.Reset();

            ulong sectorSizeInBytes;
            ProfilerShort.Begin("MyLocalCache.LoadSector");

            var sector = MyLocalCache.LoadSector(sessionPath, checkpoint.CurrentSector, out sectorSizeInBytes);
            ProfilerShort.End();
            if (sector == null)
            {
                //TODO:  If game - show error messagebox and return to menu
                //       If DS console - write error to console and exit DS
                //       If DS service - pop up silent exception (dont send report)
                throw new ApplicationException("Sector could not be loaded");
            }

            ulong voxelsSizeInBytes = GetVoxelsSizeInBytes(sessionPath);

#if false
            if ( MyFakes.DEBUG_AVOID_RANDOM_AI )
                MyBBSetSampler.ResetRandomSeed();
#endif

            MyCubeGrid.Preload();

            Static = new MySession();

            Static.Mods = checkpoint.Mods;
            Static.Settings = checkpoint.Settings;
            Static.CurrentPath = sessionPath;
            
            if (Static.OnlineMode != MyOnlineModeEnum.OFFLINE)
                StartServerRequest();

            MySandboxGame.Static.SessionCompatHelper.FixSessionComponentObjectBuilders(checkpoint, sector);

            Static.PrepareBaseSession(checkpoint, sector);

            ProfilerShort.Begin("MySession.Static.LoadWorld");
            Static.LoadWorld(checkpoint, sector);
            ProfilerShort.End();

            if (Sync.IsServer)
            {
                Static.InitializeFactions();
            }

            Static.WorldSizeInBytes = checkpointSizeInBytes + sectorSizeInBytes + voxelsSizeInBytes;

            // CH: I don't think it's needed. If there are problems with missing characters, look at it
            //FixMissingCharacter();

            MyLocalCache.SaveLastSessionInfo(sessionPath);

            Static.SendSessionStartStats();
            Static.LogSettings();

            MyHud.Notifications.Get(MyNotificationSingletons.WorldLoaded).SetTextFormatArguments(Static.Name);
            MyHud.Notifications.Add(MyNotificationSingletons.WorldLoaded);

            if (MyFakes.LOAD_UNCONTROLLED_CHARACTERS == false)
                Static.RemoveUncontrolledCharacters();

            MyNetworkStats.Static.ClearStats();
            Sync.Layer.TransportLayer.ClearStats();

            Static.BeforeStartComponents();
            
            MyLog.Default.WriteLineAndConsole("Session loaded");
            ProfilerShort.End();
        }
Esempio n. 5
0
        public void TakeControl(IMyControllableEntity entity)
        {
            if (ControlledEntity == entity)
            {
                return;
            }

            if (entity != null && entity.ControllerInfo.Controller != null)
            {
                Debug.Fail("Entity controlled by another controller, release it first");
                return;
            }

            var old = ControlledEntity;

            if (old != null)
            {
                var entityCameraSettings = old.GetCameraEntitySettings();

                float headLocalXAngle = old.HeadLocalXAngle;
                float headLocalYAngle = old.HeadLocalYAngle;

                old.Entity.OnClosing         -= m_controlledEntityClosing;
                ControlledEntity              = null;
                old.ControllerInfo.Controller = null; // This will call OnControlReleased

                bool firstPerson = entityCameraSettings != null? entityCameraSettings.IsFirstPerson : (MySession.GetCameraControllerEnum() != MyCameraControllerEnum.ThirdPersonSpectator);

                if (!MySandboxGame.IsDedicated)
                {
                    MySession.Static.Cameras.SaveEntityCameraSettings(
                        Player.Id,
                        old.Entity.EntityId,
                        firstPerson,
                        MyThirdPersonSpectator.Static.GetDistance(),
                        headLocalXAngle,
                        headLocalYAngle);
                }
            }
            if (entity != null)
            {
                ControlledEntity = entity;
                ControlledEntity.Entity.OnClosing         += m_controlledEntityClosing;
                ControlledEntity.ControllerInfo.Controller = this; // This will call OnControlAcquired

                if (!MySandboxGame.IsDedicated && ControlledEntity.Entity is Sandbox.ModAPI.Interfaces.IMyCameraController)
                {
                    MySession.SetEntityCameraPosition(Player.Id, ControlledEntity.Entity);
                }
            }

            if (old != entity)
            {
                RaiseControlledEntityChanged(old, entity);
            }
        }
        /// <summary>
        /// Starts new session and unloads outdated if theres any.
        /// </summary>
        /// <param name="sessionName">Created session name.</param>
        /// <param name="settings">Session settings OB.</param>
        /// <param name="mods">Mod selection.</param>
        /// <param name="scenarioDefinition">World generator argument.</param>
        /// <param name="asteroidAmount">Hostility settings.</param>
        /// <param name="description">Session description.</param>
        /// <param name="passwd">Session password.</param>
        public static void StartNewSession(string sessionName,
                                           MyObjectBuilder_SessionSettings settings,
                                           List <MyObjectBuilder_Checkpoint.ModItem> mods,
                                           MyScenarioDefinition scenarioDefinition = null,
                                           int asteroidAmount = 0,
                                           string description = "",
                                           string passwd      = "")
        {
            MyLog.Default.WriteLine("StartNewSandbox - Start");

            if (!MySteamWorkshop.CheckLocalModsAllowed(mods, settings.OnlineMode == MyOnlineModeEnum.OFFLINE))
            {
                MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                           messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionError),
                                           messageText: MyTexts.Get(MyCommonTexts.DialogTextLocalModsDisabledInMultiplayer),
                                           buttonType: MyMessageBoxButtonsType.OK));
                MyLog.Default.WriteLine("LoadSession() - End");
                return;
            }

            MySteamWorkshop.DownloadModsAsync(mods, delegate(bool success, string mismatchMods)
            {
                if (success || (settings.OnlineMode == MyOnlineModeEnum.OFFLINE) && MySteamWorkshop.CanRunOffline(mods))
                {
                    CheckMismatchmods(mismatchMods, callback : delegate(ResultEnum val)
                    {
                        MyScreenManager.RemoveAllScreensExcept(null);

                        if (asteroidAmount < 0)
                        {
                            MyWorldGenerator.SetProceduralSettings(asteroidAmount, settings);
                            asteroidAmount = 0;
                        }

                        MyAnalyticsHelper.SetEntry(MyGameEntryEnum.Custom);

                        StartLoading(delegate
                        {
                            MyAnalyticsHelper.SetEntry(MyGameEntryEnum.Custom);

                            MySession.Start(
                                sessionName,
                                description,
                                passwd,
                                settings,
                                mods,
                                new MyWorldGenerator.Args()
                            {
                                AsteroidAmount = asteroidAmount,
                                Scenario       = scenarioDefinition
                            }
                                );
                        });
                    });
                }
                else
                {
                    if (MySteam.IsOnline)
                    {
                        MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                                   messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionError),
                                                   messageText: MyTexts.Get(MyCommonTexts.DialogTextDownloadModsFailed),
                                                   buttonType: MyMessageBoxButtonsType.OK));
                    }
                    else
                    {
                        MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                                   messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionError),
                                                   messageText: MyTexts.Get(MyCommonTexts.DialogTextDownloadModsFailedSteamOffline),
                                                   buttonType: MyMessageBoxButtonsType.OK));
                    }
                }
                MyLog.Default.WriteLine("StartNewSandbox - End");
            });
        }
        public static void LoadSingleplayerSession(MyObjectBuilder_Checkpoint checkpoint, string sessionPath, ulong checkpointSizeInBytes, Action afterLoad = null)
        {
            if (!MySession.IsCompatibleVersion(checkpoint))
            {
                MyLog.Default.WriteLine(MyTexts.Get(MyCommonTexts.DialogTextIncompatibleWorldVersion).ToString());
                MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                           messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionError),
                                           messageText: MyTexts.Get(MyCommonTexts.DialogTextIncompatibleWorldVersion),
                                           buttonType: MyMessageBoxButtonsType.OK));
                MyLog.Default.WriteLine("LoadSession() - End");
                return;
            }

            if (!MySteamWorkshop.CheckLocalModsAllowed(checkpoint.Mods, checkpoint.Settings.OnlineMode == MyOnlineModeEnum.OFFLINE))
            {
                MyLog.Default.WriteLine(MyTexts.Get(MyCommonTexts.DialogTextLocalModsDisabledInMultiplayer).ToString());
                MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                           messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionError),
                                           messageText: MyTexts.Get(MyCommonTexts.DialogTextLocalModsDisabledInMultiplayer),
                                           buttonType: MyMessageBoxButtonsType.OK));
                MyLog.Default.WriteLine("LoadSession() - End");
                return;
            }

            var customLoadingScreenPath = GetCustomLoadingScreenImagePath(checkpoint.CustomLoadingScreenImage);

            MySteamWorkshop.DownloadModsAsync(checkpoint.Mods, delegate(bool success, string mismatchMods)
            {
                if (success || (checkpoint.Settings.OnlineMode == MyOnlineModeEnum.OFFLINE) && MySteamWorkshop.CanRunOffline(checkpoint.Mods))
                {
                    //Sandbox.Audio.MyAudio.Static.Mute = true;
                    MyScreenManager.CloseAllScreensNowExcept(null);
                    MyGuiSandbox.Update(MyEngineConstants.UPDATE_STEP_SIZE_IN_MILLISECONDS);
                    CheckMismatchmods(mismatchMods, callback : delegate(ResultEnum val)
                    {
                        if (val == ResultEnum.OK)
                        {
                            // May be called from gameplay, so we must make sure we unload the current game
                            if (MySession.Static != null)
                            {
                                MySession.Static.Unload();
                                MySession.Static = null;
                            }
                            StartLoading(delegate
                            {
                                MyAnalyticsHelper.SetEntry(MyGameEntryEnum.Load);
                                MySession.Load(sessionPath, checkpoint, checkpointSizeInBytes);
                                if (afterLoad != null)
                                {
                                    afterLoad();
                                }
                            }, customLoadingScreenPath, checkpoint.CustomLoadingScreenText);
                        }
                        else
                        {
                            MySessionLoader.UnloadAndExitToMenu();
                        }
                    });
                }
                else
                {
                    MyLog.Default.WriteLine(MyTexts.Get(MyCommonTexts.DialogTextDownloadModsFailed).ToString());

                    if (MySteam.IsOnline)
                    {
                        MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                                   messageCaption : MyTexts.Get(MyCommonTexts.MessageBoxCaptionError),
                                                   messageText : MyTexts.Get(MyCommonTexts.DialogTextDownloadModsFailed),
                                                   buttonType : MyMessageBoxButtonsType.OK, callback : delegate(MyGuiScreenMessageBox.ResultEnum result)
                        {
                            if (MyFakes.QUICK_LAUNCH != null)
                            {
                                MySessionLoader.UnloadAndExitToMenu();
                            }
                        }));
                    }
                    else
                    {
                        MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                                   messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionError),
                                                   messageText: MyTexts.Get(MyCommonTexts.DialogTextDownloadModsFailedSteamOffline),
                                                   buttonType: MyMessageBoxButtonsType.OK));
                    }
                }
                MyLog.Default.WriteLine("LoadSession() - End");
            });
        }
        public static void LoadMultiplayerSession(MyObjectBuilder_World world, MyMultiplayerBase multiplayerSession)
        {
            MyLog.Default.WriteLine("LoadSession() - Start");

            if (!MySteamWorkshop.CheckLocalModsAllowed(world.Checkpoint.Mods, false))
            {
                MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                           messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionError),
                                           messageText: MyTexts.Get(MyCommonTexts.DialogTextLocalModsDisabledInMultiplayer),
                                           buttonType: MyMessageBoxButtonsType.OK));
                MyLog.Default.WriteLine("LoadSession() - End");
                return;
            }

            MySteamWorkshop.DownloadModsAsync(world.Checkpoint.Mods,
                                              onFinishedCallback :
                                              delegate(bool success, string mismatchMods)
            {
                if (success)
                {
                    CheckMismatchmods(mismatchMods, delegate(VRage.Game.ModAPI.ResultEnum val)
                    {
                        if (val == VRage.Game.ModAPI.ResultEnum.OK)
                        {
                            //Sandbox.Audio.MyAudio.Static.Mute = true;
                            MyScreenManager.CloseAllScreensNowExcept(null);
                            MyGuiSandbox.Update(VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_MILLISECONDS);

                            // May be called from gameplay, so we must make sure we unload the current game
                            if (MySession.Static != null)
                            {
                                MySession.Static.Unload();
                                MySession.Static = null;
                            }

                            StartLoading(delegate { MySession.LoadMultiplayer(world, multiplayerSession); });
                        }
                        else
                        {
                            MySessionLoader.UnloadAndExitToMenu();
                        }
                    });
                }
                else
                {
                    if (MyMultiplayer.Static != null)
                    {
                        MyMultiplayer.Static.Dispose();
                    }

                    if (MySteam.IsOnline)
                    {
                        MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                                   messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionError),
                                                   messageText: MyTexts.Get(MyCommonTexts.DialogTextDownloadModsFailed),
                                                   buttonType: MyMessageBoxButtonsType.OK));
                    }
                    else
                    {
                        MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                                   messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionError),
                                                   messageText: MyTexts.Get(MyCommonTexts.DialogTextDownloadModsFailedSteamOffline),
                                                   buttonType: MyMessageBoxButtonsType.OK));
                    }
                }
                MyLog.Default.WriteLine("LoadSession() - End");
            },
                                              onCancelledCallback : delegate()
            {
                multiplayerSession.Dispose();
            });
        }