Exemplo n.º 1
0
#pragma warning restore 649

        /// <inheritdoc />
        public void SendMessageAsOther(string author, string message, string font, ulong targetSteamId = 0)
        {
            if (targetSteamId == Sync.MyId)
            {
                RaiseMessageRecieved(new TorchChatMessage(author, message, font));
                return;
            }
            if (MyMultiplayer.Static == null)
            {
                if ((targetSteamId == MyGameService.UserId || targetSteamId == 0) && HasHud)
                {
                    MyHud.Chat?.ShowMessage(author, message, font);
                }
                return;
            }
            var scripted = new ScriptedChatMsg()
            {
                Author = author ?? Torch.Config.ChatName,
                Text   = message,
                Font   = font ?? Torch.Config.ChatColor,
                Target = Sync.Players.TryGetIdentityId(targetSteamId)
            };

            _chatLog.Info($"{author} (to {GetMemberName(targetSteamId)}): {message}");
            MyMultiplayerBase.SendScriptedChatMessage(ref scripted);
        }
Exemplo n.º 2
0
 public void UnregisterChat(MyMultiplayerBase multiplayer)
 {
     multiplayer.ChatMessageReceived -= Multiplayer_ChatMessageReceived;
     MessagesQueue.Clear();
     
     SetDirty();
 }
Exemplo n.º 3
0
        public void UnregisterChat(MyMultiplayerBase multiplayer)
        {
            multiplayer.ChatMessageReceived -= Multiplayer_ChatMessageReceived;
            MessagesQueue.Clear();

            UpdateTimestamp();
        }
Exemplo n.º 4
0
        internal void UnregisterChat(MyMultiplayerBase multiplayer)
        {
            multiplayer.ChatMessageReceived -= Multiplayer_ChatMessageReceived;
            MessagesQueue.Clear();

            SetDirty();
        }
 public void RaiseJoined(Result result, LobbyEnterInfo info, MyMultiplayerBase multiplayer)
 {
     Debug.Assert(!Cancelled, "Cancelled action should not raise events");
     var handler = JoinDone;
     if (handler != null) 
         handler(result, info, multiplayer);
 }
Exemplo n.º 6
0
 public void UnregisterChat(MyMultiplayerBase multiplayer)
 {
     multiplayer.ChatMessageReceived -= Multiplayer_ChatMessageReceived;
     MessagesQueue.Clear();
     
     UpdateTimestamp();
 }
Exemplo n.º 7
0
        /// <inheritdoc />
        public void SendMessageAsSelf(string message)
        {
            if (MyMultiplayer.Static != null)
            {
                if (Sandbox.Engine.Platform.Game.IsDedicated)
                {
                    // Sending invalid color to clients will crash them. KEEEN
                    var color = Torch.Config.ChatColor;
                    if (!StringUtils.IsFontEnum(Torch.Config.ChatColor))
                    {
                        _log.Warn("Invalid chat font color! Defaulting to 'Red'");
                        color = MyFontEnum.Red;
                    }

                    var scripted = new ScriptedChatMsg()
                    {
                        Author = Torch.Config.ChatName,
                        Font   = color,
                        Text   = message,
                        Target = 0
                    };
                    MyMultiplayerBase.SendScriptedChatMessage(ref scripted);
                }
                else
                {
                    throw new NotImplementedException("Chat system changes broke this");
                }
                //MyMultiplayer.Static.SendChatMessage(message);
            }
            else if (HasHud)
            {
                MyHud.Chat.ShowMessage(MySession.Static.LocalHumanPlayer?.DisplayName ?? "Player", message);
            }
        }
 public void RaiseDone(Result result, MyMultiplayerBase multiplayer)
 {
     Debug.Assert(!Cancelled, "Action is canceled, it should not raise event");
     var handler = Done;
     if (handler != null) handler(result, multiplayer);
     m_done = true;
 }
Exemplo n.º 9
0
        private static void CheckDx11AndJoin(MyObjectBuilder_World world, MyMultiplayerBase multiplayer)
        {
            bool needsDx11 = world.Checkpoint.RequiresDX >= 11;

            if (!needsDx11 || MySandboxGame.IsDirectX11)
            {
                if (multiplayer.Battle)
                {
                    if (multiplayer.BattleCanBeJoined)
                    {
                        MySessionLoader.LoadMultiplayerBattleWorld(world, multiplayer);
                    }
                    else
                    {
                        MyLog.Default.WriteLine("World downloaded but battle game ended");
                        MySessionLoader.UnloadAndExitToMenu();
                        MyGuiSandbox.Show(MyCommonTexts.MultiplayerErrorSessionEnded);
                        multiplayer.Dispose();
                    }
                }
                else if (multiplayer.Scenario)
                {
                    MySessionLoader.LoadMultiplayerScenarioWorld(world, multiplayer);
                }
                else
                {
                    MySessionLoader.LoadMultiplayerSession(world, multiplayer);
                }
            }
            else
            {
                HandleDx11Needed();
            }
        }
Exemplo n.º 10
0
        public static void LoadMP(MyObjectBuilder_World world, MyMultiplayerBase multiplayerSession)
        {
            SeamlessClient.TryShow("Starting LoadMP!");


            //var MySessionConstructor = MySessionType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[2] { typeof(MySyncLayer), typeof(bool) }, null);
            //MySession.Static = (MySession)MySessionConstructor.Invoke(new object[] { MyMultiplayer.Static.SyncLayer, true });
            MySession.Static.Mods            = World.Checkpoint.Mods;
            MySession.Static.Settings        = World.Checkpoint.Settings;
            MySession.Static.CurrentPath     = MyLocalCache.GetSessionSavesPath(MyUtils.StripInvalidChars(world.Checkpoint.SessionName), contentFolder: false, createIfNotExists: false);
            MySession.Static.WorldBoundaries = world.Checkpoint.WorldBoundaries;
            MySession.Static.InGameTime      = MyObjectBuilder_Checkpoint.DEFAULT_DATE;



            // MySession.Static.Players.LoadConnectedPlayers(world.Checkpoint);

            //typeof(MySession).GetMethod("PrepareBaseSession", BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(MyObjectBuilder_Checkpoint), typeof(MyObjectBuilder_Sector) }, null).Invoke(MySession.Static, new object[] { world.Checkpoint, world.Sector });

            if (MyFakes.MP_SYNC_CLUSTERTREE)
            {
                SeamlessClient.TryShow("Deserializing Clusters!");
                //MyPhysics.DeserializeClusters(world.Clusters);
            }



            //_ = world.Checkpoint.ControlledObject;
            //world.Checkpoint.ControlledObject = -1L;
            LoadOnlinePlayers(world.Checkpoint);
            LoadWorld(world.Checkpoint, world.Sector);
            SeamlessClient.TryShow("Loading World Complete!");
        }
Exemplo n.º 11
0
 internal void UnregisterChat(MyMultiplayerBase multiplayer)
 {
     if (MyFakes.ENABLE_GPS)
     {
         multiplayer.ChatMessageReceived -= ParseChat;
     }
 }
Exemplo n.º 12
0
 /// <inheritdoc />
 public void SendMessageAsSelf(string message)
 {
     if (MyMultiplayer.Static != null)
     {
         if (Sandbox.Engine.Platform.Game.IsDedicated)
         {
             var scripted = new ScriptedChatMsg()
             {
                 Author = "Server",
                 Font   = MyFontEnum.Red,
                 Text   = message,
                 Target = 0
             };
             MyMultiplayerBase.SendScriptedChatMessage(ref scripted);
         }
         else
         {
             MyMultiplayer.Static.SendChatMessage(message);
         }
     }
     else if (HasHud)
     {
         MyHud.Chat.ShowMessage(MySession.Static.LocalHumanPlayer?.DisplayName ?? "Player", message);
     }
 }
Exemplo n.º 13
0
        /// <inheritdoc />
        public void SendMessage(string message, string author = "Server", long playerId = 0, string font = MyFontEnum.Red)
        {
            if (string.IsNullOrEmpty(message))
            {
                return;
            }

            ChatHistory.Add(new ChatMessage(DateTime.Now, 0, author, message));
            if (_commandManager.IsCommand(message))
            {
                var response = _commandManager.HandleCommandFromServer(message);
                ChatHistory.Add(new ChatMessage(DateTime.Now, 0, author, response));
            }
            else
            {
                var msg = new ScriptedChatMsg {
                    Author = author, Font = font, Target = playerId, Text = message
                };
                MyMultiplayerBase.SendScriptedChatMessage(ref msg);
                var character = MySession.Static.Players.TryGetIdentity(playerId)?.Character;
                var steamId   = GetSteamId(playerId);
                if (character == null)
                {
                    return;
                }

                var addToGlobalHistoryMethod = typeof(MyCharacter).GetMethod("OnGlobalMessageSuccess", BindingFlags.Instance | BindingFlags.NonPublic);
                _networkManager.RaiseEvent(addToGlobalHistoryMethod, character, steamId, steamId, message);
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Send a message in chat.
        /// </summary>
        public void SendMessage(string message, string author = "Server", long playerId = 0, string font = MyFontEnum.Red)
        {
            var msg = new ScriptedChatMsg {
                Author = author, Font = font, Target = playerId, Text = message
            };

            MyMultiplayerBase.SendScriptedChatMessage(ref msg);
        }
Exemplo n.º 15
0
 public MyDownloadWorldResult(int channel, ulong sender, MyMultiplayerBase mp)
 {
     m_mp = mp;
     m_sender = sender;
     m_channel = channel;
     MyNetworkReader.SetHandler(m_channel, MyDownloadWorldResult_Received);
     SteamSDK.Peer2Peer.ConnectionFailed += Peer2Peer_ConnectionFailed;
 }
Exemplo n.º 16
0
        public static void LoadMultiplayerScenarioWorld(MyObjectBuilder_World world, MyMultiplayerBase multiplayerSession)
        {
            Debug.Assert(MySession.Static != null);

            MyLog.Default.WriteLine("LoadMultiplayerScenarioWorld() - Start");

            if (world.Checkpoint.BriefingVideo != null && world.Checkpoint.BriefingVideo.Length > 0)
            {
                MyGuiSandbox.OpenUrlWithFallback(world.Checkpoint.BriefingVideo, "Scenario briefing video", true);
            }

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

            MySteamWorkshop.DownloadModsAsync(world.Checkpoint.Mods,
                                              onFinishedCallback : delegate(bool success, string mismatchMods)
            {
                if (success)
                {
                    CheckMismatchmods(mismatchMods, callback : delegate(ResultEnum val)
                    {
                        MyScreenManager.CloseAllScreensNowExcept(null);
                        MyGuiSandbox.Update(MyEngineConstants.UPDATE_STEP_SIZE_IN_MILLISECONDS);

                        StartLoading(delegate
                        {
                            MySession.Static.LoadMultiplayerWorld(world, multiplayerSession);
                            if (ScenarioWorldLoaded != null)
                            {
                                ScenarioWorldLoaded();
                            }
                        });
                    });
                }
                else
                {
                    MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                               messageCaption : MyTexts.Get(MyCommonTexts.MessageBoxCaptionError),
                                               messageText : MyTexts.Get(MyCommonTexts.DialogTextDownloadModsFailed),
                                               buttonType : MyMessageBoxButtonsType.OK,
                                               callback : delegate(MyGuiScreenMessageBox.ResultEnum result) { MySessionLoader.UnloadAndExitToMenu(); }));
                }
                MyLog.Default.WriteLine("LoadMultiplayerScenarioWorld() - End");
            },
                                              onCancelledCallback : delegate()
            {
                MySessionLoader.UnloadAndExitToMenu();
            });
        }
        public static void LoadMultiplayerBattleWorld(MyObjectBuilder_World world, MyMultiplayerBase multiplayerSession)
        {
            MyLog.Default.WriteLine("LoadMultiplayerBattleWorld() - 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,
                                           callback : delegate(MyGuiScreenMessageBox.ResultEnum result) { MyGuiScreenMainMenu.ReturnToMainMenu(); }));
                MyLog.Default.WriteLine("LoadMultiplayerBattleWorld() - End");
                return;
            }

            MySteamWorkshop.DownloadModsAsync(world.Checkpoint.Mods,
                                              onFinishedCallback : delegate(bool success, string mismatchMods)
            {
                if (success)
                {
                    MyScreenManager.CloseAllScreensNowExcept(null);
                    MyGuiSandbox.Update(VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_MILLISECONDS);
                    CheckMismatchmods(mismatchMods, callback : delegate(VRage.Game.ModAPI.ResultEnum val)
                    {
                        MyGuiScreenGamePlay.StartLoading(delegate
                        {
                            if (MySession.Static == null)
                            {
                                MySession.CreateWithEmptyWorld(multiplayerSession);
                                MySession.Static.Settings.Battle = true;
                            }

                            MySession.Static.LoadMultiplayerWorld(world, multiplayerSession);
                            Debug.Assert(MySession.Static.Battle);
                            if (BattleWorldLoaded != null)
                            {
                                BattleWorldLoaded();
                            }
                        });
                    });
                }
                else
                {
                    MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                               messageCaption : MyTexts.Get(MyCommonTexts.MessageBoxCaptionError),
                                               messageText : MyTexts.Get(MyCommonTexts.DialogTextDownloadModsFailed),
                                               buttonType : MyMessageBoxButtonsType.OK,
                                               callback : delegate(MyGuiScreenMessageBox.ResultEnum result) { MyGuiScreenMainMenu.ReturnToMainMenu(); }));
                }
                MyLog.Default.WriteLine("LoadMultiplayerBattleWorld() - End");
            },
                                              onCancelledCallback : delegate()
            {
                MyGuiScreenMainMenu.UnloadAndExitToMenu();
            });
        }
Exemplo n.º 18
0
        private static void OnJoinBattleFailed(MyGuiScreenProgress progress, MyMultiplayerBase multiplayer, string status)
        {
            MyGuiScreenMainMenu.UnloadAndExitToMenu();

            progress.Cancel();
            StringBuilder error = new StringBuilder();
            //error.AppendFormat(MySpaceTexts.DialogTextJoinBattleLobbyFailed, status);

            MyGuiScreenMessageBox mb = MyGuiSandbox.CreateMessageBox(messageText: error, messageCaption: MyTexts.Get(MySpaceTexts.MessageBoxCaptionError));

            MyGuiSandbox.AddScreen(mb);
        }
Exemplo n.º 19
0
        private static bool LoadMultiplayerSession(MyObjectBuilder_World world, MyMultiplayerBase multiplayerSession)
        {
            MyLog.Default.WriteLine("LoadSession() - Start");
            if (!MyWorkshop.CheckLocalModsAllowed(world.Checkpoint.Mods, allowLocalMods: false))
            {
                MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(MyMessageBoxStyleEnum.Error, MyMessageBoxButtonsType.OK, messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionError), messageText: MyTexts.Get(MyCommonTexts.DialogTextLocalModsDisabledInMultiplayer)));
                MyLog.Default.WriteLine("LoadSession() - End");
                return(false);
            }
            MyWorkshop.DownloadModsAsync(world.Checkpoint.Mods, delegate(bool success)
            {
                if (success)
                {
                    MyScreenManager.CloseAllScreensNowExcept(null);
                    MyGuiSandbox.Update(16);
                    if (MySession.Static != null)
                    {
                        MySession.Static.Unload();
                        MySession.Static = null;
                    }

                    string CustomBackgroundImage = null;
                    GetCustomLoadingScreenPath(world.Checkpoint.Mods, out CustomBackgroundImage);

                    MySessionLoader.StartLoading(delegate
                    {
                        LoadMultiplayer.Invoke(null, new object[] { world, multiplayerSession });
                        //MySession.LoadMultiplayer(world, multiplayerSession);
                    }, null, CustomBackgroundImage, null);
                }
                else
                {
                    multiplayerSession.Dispose();
                    MySessionLoader.UnloadAndExitToMenu();
                    if (MyGameService.IsOnline)
                    {
                        MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(MyMessageBoxStyleEnum.Error, MyMessageBoxButtonsType.OK, messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionError), messageText: MyTexts.Get(MyCommonTexts.DialogTextDownloadModsFailed)));
                    }
                    else
                    {
                        MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(MyMessageBoxStyleEnum.Error, MyMessageBoxButtonsType.OK, messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionError), messageText: new StringBuilder(string.Format(MyTexts.GetString(MyCommonTexts.DialogTextDownloadModsFailedSteamOffline), MySession.GameServiceName))));
                    }
                }
                MyLog.Default.WriteLine("LoadSession() - End");
            }, delegate
            {
                multiplayerSession.Dispose();
                MySessionLoader.UnloadAndExitToMenu();
            });

            return(false);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Sends message directly through SE's API instead of Torch
        /// (current Torch public build doesn't work)
        /// </summary>
        /// <param name="author"></param>
        /// <param name="message"></param>
        /// <param name="authorColor"></param>
        public static void SendMessageNative(string author, string message, Color?authorColor = null)
        {
            var scripted = new ScriptedChatMsg()
            {
                Author = author,
                Text   = message,
                Font   = MyFontEnum.White,
                Color  = authorColor ?? Color.Red,
                Target = 0
            };

            MyMultiplayerBase.SendScriptedChatMessage(ref scripted);
        }
Exemplo n.º 21
0
        public void SendMessageTo(string authorName, string message, Color color, ulong targetSteamId)
        {
            var msg = new ScriptedChatMsg
            {
                Author = authorName,
                Text   = message,
                Font   = MyFontEnum.White,
                Color  = color,
                Target = Sync.Players.TryGetIdentityId(targetSteamId),
            };

            MyMultiplayerBase.SendScriptedChatMessage(ref msg);
        }
Exemplo n.º 22
0
        internal void RegisterClientEvents(MyMultiplayerBase multiplayer)
        {
            multiplayer.ClientJoined += multiplayer_ClientJoined;
            multiplayer.ClientLeft   += multiplayer_ClientLeft;

            foreach (var p in multiplayer.Members)
            {
                if (p != Sync.MyId)
                {
                    multiplayer_ClientJoined(p);
                }
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// Sends the specified message and prefix to the player
        /// </summary>
        /// <param name="player"></param>
        /// <param name="message"></param>
        /// <param name="prefix"></param>
        /// <param name="args"></param>
        public void Message(IMyPlayer player, string message, string prefix, params object[] args)
        {
            message = args.Length > 0 ? string.Format(Formatter.ToPlaintext(message), args) : Formatter.ToPlaintext(message);
            var msg = new ScriptedChatMsg
            {
                Text   = prefix != null ? $"{prefix} {message}" : message,
                Author = "server",
                Target = player.IdentityId,
                Font   = "Green"
            };

            MyMultiplayerBase.SendScriptedChatMessage(ref msg);
        }
Exemplo n.º 24
0
        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)
            {
                if (success)
                {
                    //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;
                    }

                    MyGuiScreenGamePlay.StartLoading(delegate { MySession.LoadMultiplayer(world, multiplayerSession); });
                }
                else
                {
                    if (MyMultiplayer.Static != null)
                    {
                        MyMultiplayer.Static.Dispose();
                    }
                    MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                               messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionError),
                                               messageText: MyTexts.Get(MyCommonTexts.DialogTextDownloadModsFailed),
                                               buttonType: MyMessageBoxButtonsType.OK));
                }
                MyLog.Default.WriteLine("LoadSession() - End");
            },
                                              onCancelledCallback : delegate()
            {
                multiplayerSession.Dispose();
            });
        }
Exemplo n.º 25
0
        public static void SendMessage(string author, string message, Color color, ulong steamID)
        {
            Logger          _chatLog         = LogManager.GetLogger("Chat");
            ScriptedChatMsg scriptedChatMsg1 = new ScriptedChatMsg();

            scriptedChatMsg1.Author = author;
            scriptedChatMsg1.Text   = message;
            scriptedChatMsg1.Font   = "White";
            scriptedChatMsg1.Color  = color;
            scriptedChatMsg1.Target = Sync.Players.TryGetIdentityId(steamID);
            ScriptedChatMsg scriptedChatMsg2 = scriptedChatMsg1;

            MyMultiplayerBase.SendScriptedChatMessage(ref scriptedChatMsg2);
        }
Exemplo n.º 26
0
        public static MyMultiplayerBase GetNetworkManager( )
        {
            try
            {
                MyMultiplayerBase networkManager = MyMultiplayer.Static;

                return(networkManager);
            }
            catch (Exception ex)
            {
                ApplicationLog.BaseLog.Error(ex);
                return(null);
            }
        }
Exemplo n.º 27
0
        public static void Send(string response, ulong Target)
        {
            var scripted = new ScriptedChatMsg()
            {
                Author = Author,
                Text   = response,
                Font   = MyFontEnum.White,
                Color  = ChatColor,
                Target = Sync.Players.TryGetIdentityId(Target)
            };

            Log.Info($"{Author} (to {Torch.Managers.ChatManager.ChatManagerServer.GetMemberName(Target)}): {response}");
            MyMultiplayerBase.SendScriptedChatMessage(ref scripted);
        }
Exemplo n.º 28
0
        /// <summary>
        /// Sends a chat message to the player
        /// </summary>
        /// <param name="player"></param>
        /// <param name="message"></param>
        /// <param name="prefix"></param>
        public void Message(IMyPlayer player, string message, string prefix = null)
        {
            if (string.IsNullOrEmpty(message))
            {
                return;
            }

            var msg = new ChatMsg
            {
                Text   = string.IsNullOrEmpty(prefix) ? message : (string.IsNullOrEmpty(message) ? prefix : $"{prefix}: {message}"),
                Author = Sync.ServerId
            };

            MyMultiplayerBase.SendChatMessage(ref msg);
        }
Exemplo n.º 29
0
        public static void DownloadBattleWorld(MyMultiplayerBase multiplayer)
        {
            StringBuilder text = MyTexts.Get(MySpaceTexts.MultiplayerStateConnectingToServer);

            MyGuiScreenProgress progress = new MyGuiScreenProgress(text, MySpaceTexts.Cancel);

            MyGuiSandbox.AddScreen(progress);

            progress.ProgressCancelled += () =>
            {
                MyGuiScreenMainMenu.ReturnToMainMenu();
            };

            DownloadWorld(progress, multiplayer);
        }
Exemplo n.º 30
0
        public static void SendMessageTemp(string author, string message, Color color)
        {
            Logger          _chatLog         = LogManager.GetLogger("Chat");
            ScriptedChatMsg scriptedChatMsg1 = new ScriptedChatMsg();

            scriptedChatMsg1.Author = author;
            scriptedChatMsg1.Text   = message;
            scriptedChatMsg1.Font   = "White";
            scriptedChatMsg1.Color  = color;
            scriptedChatMsg1.Target = 0L;
            ScriptedChatMsg scriptedChatMsg2 = scriptedChatMsg1;

            MyMultiplayerBase.SendScriptedChatMessage(ref scriptedChatMsg2);
            _chatLog.Info($"{author} (to {ChatManagerServer.GetMemberName(0)}): {message}");
        }
Exemplo n.º 31
0
        private static void OnJoinBattleFailed(MyGuiScreenProgress progress, MyMultiplayerBase multiplayer, string status)
        {
            if (multiplayer != null)
            {
                multiplayer.Dispose();
            }
            progress.Cancel();
            StringBuilder error = new StringBuilder();

            error.AppendFormat(MySpaceTexts.DialogTextJoinBattleLobbyFailed, status);

            MyGuiScreenMessageBox mb = MyGuiSandbox.CreateMessageBox(messageText: error, messageCaption: MyTexts.Get(MySpaceTexts.MessageBoxCaptionError));

            MyGuiSandbox.AddScreen(mb);
        }
 public void KickPlayer(ulong remoteUserId)
 {
     try
     {
         MyMultiplayerBase steamServerManager = GetNetworkManager( );
         MySandboxGame.Static.Invoke(() =>
         {
             MyMultiplayer.Static.KickClient(remoteUserId);
             BaseObject.InvokeEntityMethod(steamServerManager, ServerNetworkManagerDisconnectPlayerMethod, new object[] { remoteUserId, ChatMemberStateChangeEnum.Kicked });
         });
     }
     catch (Exception ex)
     {
         ApplicationLog.BaseLog.Error(ex);
     }
 }
Exemplo n.º 33
0
        public static void DownloadBattleWorld(MyMultiplayerBase multiplayer)
        {
            StringBuilder text = MyTexts.Get(MySpaceTexts.MultiplayerStateConnectingToServer);

            MyGuiScreenProgress progress = new MyGuiScreenProgress(text, MySpaceTexts.Cancel);

            MyGuiSandbox.AddScreen(progress);
            // Set focus to different control than Cancel button (because focused Cancel button can be unexpectedly pressed when sending a chat message - in case server has just started game).
            progress.FocusedControl = progress.RotatingWheel;

            progress.ProgressCancelled += () =>
            {
                MyGuiScreenMainMenu.UnloadAndExitToMenu();
            };

            DownloadWorld(progress, multiplayer);
        }
Exemplo n.º 34
0
        /// <summary>
        /// Sends a chat message to the player
        /// </summary>
        /// <param name="player"></param>
        /// <param name="message"></param>
        /// <param name="prefix"></param>
        public void Message(IMyPlayer player, string message, string prefix = null)
        {
            if (string.IsNullOrEmpty(message))
            {
                return;
            }

            var msg = new ScriptedChatMsg
            {
                Text   = string.IsNullOrEmpty(prefix) ? message : (string.IsNullOrEmpty(message) ? prefix : $"{prefix}: {message}"),
                Author = "server",
                Target = player.IdentityId,
                Font   = "Green"
            };

            MyMultiplayerBase.SendScriptedChatMessage(ref msg);
        }
Exemplo n.º 35
0
        private static void OnJoinBattleFailed(MyGuiScreenProgress progress, MyMultiplayerBase multiplayer, string status, bool statusFullMessage = false)
        {
            MySessionLoader.UnloadAndExitToMenu();

            progress.Cancel();
            StringBuilder error = new StringBuilder();

            if (statusFullMessage)
            {
                error.Append(status);
            }
            else
            {
                error.AppendFormat(MySpaceTexts.DialogTextJoinBattleFailed, status);
            }

            MyGuiScreenMessageBox mb = MyGuiSandbox.CreateMessageBox(messageText: error, messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionError));

            MyGuiSandbox.AddScreen(mb);
        }
Exemplo n.º 36
0
        public static MyMultiplayerHostResult HostLobby(LobbyTypeEnum lobbyType, int maxPlayers, MySyncLayer syncLayer)
        {
            System.Diagnostics.Debug.Assert(syncLayer != null);
            MyTrace.Send(TraceWindow.Multiplayer, "Host game");

            MyMultiplayerHostResult ret = new MyMultiplayerHostResult();
            SteamSDK.Lobby.Create(lobbyType, maxPlayers, (lobby, result) =>
            {
                if (!ret.Cancelled)
                {
                    if (result == Result.OK && lobby.GetOwner() != MySteam.UserId)
                    {
                        result = Result.Fail;
                        lobby.Leave();
                    }

                    MyTrace.Send(TraceWindow.Multiplayer, "Lobby created");
                    lobby.SetLobbyType(lobbyType);
                    ret.RaiseDone(result, result == Result.OK ? MyMultiplayer.Static = new MyMultiplayerLobby(lobby, syncLayer) : null);
                }
            });
            return ret;
        }
Exemplo n.º 37
0
        public static void DownloadBattleWorld(MyMultiplayerBase multiplayer)
        {
            StringBuilder text = MyTexts.Get(MyCommonTexts.MultiplayerStateConnectingToServer);

            MyGuiScreenProgress progress = new MyGuiScreenProgress(text, MyCommonTexts.Cancel);
            MyGuiSandbox.AddScreen(progress);
            // Set focus to different control than Cancel button (because focused Cancel button can be unexpectedly pressed when sending a chat message - in case server has just started game).
            progress.FocusedControl = progress.RotatingWheel;

            progress.ProgressCancelled += () =>
            {
                MySessionLoader.UnloadAndExitToMenu();
            };

            DownloadWorld(progress, multiplayer);
        }
 public MyMultiplayerBattleData(MyMultiplayerBase multiplayer)
 {
     m_multiplayer = multiplayer;
     m_multiplayer.RegisterControlMessage<KeyValueDataMsg>(MyControlMessageEnum.BattleKeyValue, OnKeyValueChanged);
 }
Exemplo n.º 39
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();
        }
Exemplo n.º 40
0
        /// <summary>
        /// Starts multiplayer server with current world
        /// </summary>
        internal void StartServer(MyMultiplayerBase multiplayer)
        {
            //Debug.Assert(multiplayer == null, "You've forgot to call UnloadMultiplayer() first");
            multiplayer.WorldName = Name;
            multiplayer.GameMode = Settings.GameMode;
            multiplayer.WorldSize = WorldSizeInBytes;
            multiplayer.AppVersion = MyFinalBuildConstants.APP_VERSION;
            multiplayer.DataHash = MyDataIntegrityChecker.GetHashBase64();
            multiplayer.InventoryMultiplier = Settings.InventorySizeMultiplier;
            multiplayer.AssemblerMultiplier = Settings.AssemblerEfficiencyMultiplier;
            multiplayer.RefineryMultiplier = Settings.RefinerySpeedMultiplier;
            multiplayer.WelderMultiplier = Settings.WelderSpeedMultiplier;
            multiplayer.GrinderMultiplier = Settings.GrinderSpeedMultiplier;
            multiplayer.MemberLimit = Settings.MaxPlayers;
            multiplayer.Mods = Mods;
            multiplayer.ViewDistance = Settings.ViewDistance;
            multiplayer.Battle = Battle;
            multiplayer.Scenario = IsScenario;

            if (Engine.Platform.Game.IsDedicated)
                (multiplayer as MyDedicatedServerBase).SendGameTagsToSteam();

            MyHud.Chat.RegisterChat(multiplayer);
            Static.Gpss.RegisterChat(multiplayer);
        }
Exemplo n.º 41
0
        private static void DownloadWorld(MyGuiScreenProgress progress, MyMultiplayerBase multiplayer)
        {
            if (progress.Text != null)
            {
                progress.Text.Clear();
                progress.Text.Append(MyTexts.Get(MyCommonTexts.MultiplayerStateConnectingToServer));
            }

            MyLog.Default.WriteLine("World requested");

            const float worldRequestTimeout = 40; // in seconds
            Stopwatch worldRequestTime = Stopwatch.StartNew();

            ulong serverId = multiplayer.GetOwner();
            bool connected = false;
            progress.Tick += () =>
            {
                P2PSessionState state = default(P2PSessionState);
                Peer2Peer.GetSessionState(multiplayer.ServerId, ref state);

                if (!connected && state.ConnectionActive)
                {
                    MyLog.Default.WriteLine("World requested - connection alive");
                    connected = true;
                    if (progress.Text != null)
                    {
                        progress.Text.Clear();
                        progress.Text.Append(MyTexts.Get(MyCommonTexts.MultiplayerStateWaitingForServer));
                    }
                }

                //progress.Text.Clear();
                //progress.Text.AppendLine("Connecting: " + state.Connecting);
                //progress.Text.AppendLine("ConnectionActive: " + state.ConnectionActive);
                //progress.Text.AppendLine("Relayed: " + state.UsingRelay);
                //progress.Text.AppendLine("Bytes queued: " + state.BytesQueuedForSend);
                //progress.Text.AppendLine("Packets queued: " + state.PacketsQueuedForSend);
                //progress.Text.AppendLine("Last session error: " + state.LastSessionError);
                //progress.Text.AppendLine("Original server: " + serverId);
                //progress.Text.AppendLine("Current server: " + multiplayer.Lobby.GetOwner());
                //progress.Text.AppendLine("Game version: " + multiplayer.AppVersion);

                if (serverId != multiplayer.GetOwner())
                {
                    MyLog.Default.WriteLine("World requested - failed, server changed");
                    progress.Cancel();
                    MyGuiSandbox.Show(MyCommonTexts.MultiplayerErrorServerHasLeft);
                    multiplayer.Dispose();
                }

                if (worldRequestTime.IsRunning && worldRequestTime.Elapsed.TotalSeconds > worldRequestTimeout)
                {
                    MyLog.Default.WriteLine("World requested - failed, server changed");
                    progress.Cancel();
                    MyGuiSandbox.Show(MyCommonTexts.MultiplaterJoin_ServerIsNotResponding);
                    multiplayer.Dispose();
                }
            };

            var downloadResult = multiplayer.DownloadWorld();
            downloadResult.ProgressChanged += (result) =>
            {
                worldRequestTime.Stop();
                OnDownloadProgressChanged(progress, result, multiplayer);
            };

            progress.ProgressCancelled += () =>
            {
                downloadResult.Cancel();
                multiplayer.Dispose();
                //var joinScreen = MyScreenManager.GetScreenWithFocus() as MyGuiScreenJoinGame;
                //if (joinScreen != null)
                //  joinScreen.ReloadList();
            };
        }
Exemplo n.º 42
0
 public void RegisterChat(MyMultiplayerBase multiplayer)
 {
     multiplayer.ChatMessageReceived += Multiplayer_ChatMessageReceived;
 }
Exemplo n.º 43
0
        private static void OnDownloadProgressChanged(MyGuiScreenProgress progress, MyDownloadWorldResult result, MyMultiplayerBase multiplayer)
        {
            switch (result.State)
            {
                case MyDownloadWorldStateEnum.Success:
                    progress.CloseScreen();
                    var world = multiplayer.ProcessWorldDownloadResult(result);

                    CheckDx11AndJoin(world, multiplayer);
                    break;

                case MyDownloadWorldStateEnum.InProgress:
                    if (result.ReceivedBlockCount == 1)
                        MyLog.Default.WriteLine("First world part received");
                    string percent = (result.Progress * 100).ToString("0.");
                    float size = result.ReceivedDatalength;
                    string prefix = MyUtils.FormatByteSizePrefix(ref size);
                    string worldSize = size.ToString("0.") + " " + prefix + "B";
                    if (progress.Text != null)
                        progress.Text.Clear();
                    if (float.IsNaN(result.Progress))
                    {
                        MyLog.Default.WriteLine("World requested - preemble received");
                        if (progress.Text != null)
                            progress.Text.Append(MyTexts.Get(MyCommonTexts.DialogWaitingForWorldData));
                    }
                    else
                    {
                        if (progress.Text != null)
                            progress.Text.AppendFormat(MyTexts.GetString(MyCommonTexts.DialogTextDownloadingWorld), percent, worldSize);
                    }
                    break;

                case MyDownloadWorldStateEnum.WorldNotAvailable:
                    MyLog.Default.WriteLine("World requested - world not available");
                    progress.Cancel();
                    MyGuiSandbox.Show(MyCommonTexts.DialogDownloadWorld_WorldDoesNotExists);
                    multiplayer.Dispose();
                    break;

                case MyDownloadWorldStateEnum.ConnectionFailed:
                    MyLog.Default.WriteLine("World requested - connection failed");
                    progress.Cancel();
                    MyGuiSandbox.Show(MyTexts.AppendFormat(new StringBuilder(), MyCommonTexts.MultiplayerErrorConnectionFailed, result.ConnectionError));
                    multiplayer.Dispose();
                    break;

                case MyDownloadWorldStateEnum.DeserializationFailed:
                case MyDownloadWorldStateEnum.InvalidMessage:
                    MyLog.Default.WriteLine("World requested - message invalid (wrong version?)");
                    progress.Cancel();
                    MyGuiSandbox.Show(MyCommonTexts.DialogTextDownloadWorldFailed);
                    multiplayer.Dispose();
                    break;

                default:
                    throw new InvalidBranchException();
            }
        }
        public static void LoadMultiplayerBattleWorld(MyObjectBuilder_World world, MyMultiplayerBase multiplayerSession)
        {
            MyLog.Default.WriteLine("LoadMultiplayerBattleWorld() - 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,
                    callback: delegate(MyGuiScreenMessageBox.ResultEnum result) { MyGuiScreenMainMenu.ReturnToMainMenu(); }));
                MyLog.Default.WriteLine("LoadMultiplayerBattleWorld() - End");
                return;
            }

            MySteamWorkshop.DownloadModsAsync(world.Checkpoint.Mods,
                onFinishedCallback: delegate(bool success,string mismatchMods)
                {
                    if (success)
                    {
                        MyScreenManager.CloseAllScreensNowExcept(null);
                        MyGuiSandbox.Update(VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_MILLISECONDS);
                        CheckMismatchmods(mismatchMods, callback: delegate(VRage.Game.ModAPI.ResultEnum val)
                        {
                            MyGuiScreenGamePlay.StartLoading(delegate
                            {
                                if (MySession.Static == null)
                                {
                                    MySession.CreateWithEmptyWorld(multiplayerSession);
                                    MySession.Static.Settings.Battle = true;
                                }

                                MySession.Static.LoadMultiplayerWorld(world, multiplayerSession);
                                Debug.Assert(MySession.Static.Battle);
                                if (BattleWorldLoaded != null)
                                    BattleWorldLoaded();
                            });
                        });
                    }
                    else
                    {
                        MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                            messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionError),
                            messageText: MyTexts.Get(MyCommonTexts.DialogTextDownloadModsFailed),
                            buttonType: MyMessageBoxButtonsType.OK,
                            callback: delegate(MyGuiScreenMessageBox.ResultEnum result) { MyGuiScreenMainMenu.ReturnToMainMenu(); }));
                    }
                    MyLog.Default.WriteLine("LoadMultiplayerBattleWorld() - End");
                },
                onCancelledCallback: delegate()
                {
                    MyGuiScreenMainMenu.UnloadAndExitToMenu();
                });
        }
        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;
                                }

                                MyGuiScreenGamePlay.StartLoading(delegate { MySession.LoadMultiplayer(world, multiplayerSession); });
                            }
                            else
                            {
                                MyGuiScreenMainMenu.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();
                });
        }
Exemplo n.º 46
0
        public static void OnJoinScenario(MyGuiScreenProgress progress, Result joinResult, LobbyEnterInfo enterInfo, MyMultiplayerBase multiplayer)
        {
            MyLog.Default.WriteLine(String.Format("Lobby join response: {0}, enter state: {1}", joinResult.ToString(), enterInfo.EnterState));
          
            if (joinResult == Result.OK && enterInfo.EnterState == LobbyEnterResponseEnum.Success && multiplayer.GetOwner() != Sync.MyId)
            {
                // Create session with empty world
                if (MySession.Static != null)
                {
                    MySession.Static.Unload();
                    MySession.Static = null;
                }

                MySession.CreateWithEmptyWorld(multiplayer);

                progress.CloseScreen();

                MyScreenManager.CloseAllScreensNowExcept(null);
                MyLog.Default.WriteLine("Scenario lobby joined");

                if (MyPerGameSettings.GUI.ScenarioLobbyClientScreen != null)
                    MyGuiSandbox.AddScreen(MyGuiSandbox.CreateScreen(MyPerGameSettings.GUI.ScenarioLobbyClientScreen));
                else
                    Debug.Fail("No scenario lobby client screen");
            }
            else
            {
                string status = "ServerHasLeft";
                if (joinResult != Result.OK)
                {
                    status = joinResult.ToString();
                }
                else if (enterInfo.EnterState != LobbyEnterResponseEnum.Success)
                {
                    status = enterInfo.EnterState.ToString();
                }

                OnJoinBattleFailed(progress, multiplayer, status);
            }
        }
Exemplo n.º 47
0
        public static void DownloadBattleWorld(MyMultiplayerBase multiplayer)
        {
            StringBuilder text = MyTexts.Get(MySpaceTexts.MultiplayerStateConnectingToServer);

            MyGuiScreenProgress progress = new MyGuiScreenProgress(text, MySpaceTexts.Cancel);
            MyGuiSandbox.AddScreen(progress);

            progress.ProgressCancelled += () =>
            {
                MyGuiScreenMainMenu.ReturnToMainMenu();
            };

            DownloadWorld(progress, multiplayer);
        }
Exemplo n.º 48
0
        public static void OnJoin(MyGuiScreenProgress progress, Result joinResult, LobbyEnterInfo enterInfo, MyMultiplayerBase multiplayer)
        {
            // HACK: To hide multiplayer from ME
            //if (!MySandboxGame.Services.SteamService.IsActive || MySandboxGame.Services.SteamService.AppId * 2 == 667900)
            //    return;

            MyLog.Default.WriteLine(String.Format("Lobby join response: {0}, enter state: {1}", joinResult.ToString(), enterInfo.EnterState));

            if (joinResult == Result.OK && enterInfo.EnterState == LobbyEnterResponseEnum.Success && multiplayer.GetOwner() != Sync.MyId)
            {
                DownloadWorld(progress, multiplayer);
            }
            else
            {
                string status = "ServerHasLeft";
                if (joinResult != Result.OK)
                {
                    status = joinResult.ToString();
                }
                else if (enterInfo.EnterState != LobbyEnterResponseEnum.Success)
                {
                    status = enterInfo.EnterState.ToString();
                }

                OnJoinFailed(progress, multiplayer, status);
            }
        }
Exemplo n.º 49
0
        private static void OnJoinFailed(MyGuiScreenProgress progress, MyMultiplayerBase multiplayer, string status)
        {
            if (multiplayer != null)
            {
                multiplayer.Dispose();
            }
            progress.Cancel();
            StringBuilder error = new StringBuilder();
            error.AppendFormat(MyCommonTexts.DialogTextJoinWorldFailed, status);

            MyGuiScreenMessageBox mb = MyGuiSandbox.CreateMessageBox(messageText: error, messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionError));
            MyGuiSandbox.AddScreen(mb);
        }
Exemplo n.º 50
0
        internal void LoadMultiplayerWorld(MyObjectBuilder_World world, MyMultiplayerBase multiplayerSession)
        {
            Static.UnloadDataComponents(true);

            MyDefinitionManager.Static.UnloadData();

            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;

            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;

            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;

            MyLocalCache.ClearLastSessionInfo();

            Static.BeforeStartComponents();
        }
Exemplo n.º 51
0
        private static void OnJoinBattleFailed(MyGuiScreenProgress progress, MyMultiplayerBase multiplayer, string status, bool statusFullMessage = false)
        {
            MySessionLoader.UnloadAndExitToMenu();

            progress.Cancel();
            StringBuilder error = new StringBuilder();
            if (statusFullMessage)
                error.Append(status);
            else
                error.AppendFormat(MySpaceTexts.DialogTextJoinBattleFailed, status);

            MyGuiScreenMessageBox mb = MyGuiSandbox.CreateMessageBox(messageText: error, messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionError));
            MyGuiSandbox.AddScreen(mb);
        }
Exemplo n.º 52
0
 private void LoadMembersFromWorld(MyObjectBuilder_World world, MyMultiplayerBase multiplayerSession)
 {
     // CH: This only makes sense on MyMultiplayerClient, because MyMultiplayerLobby takes the connected members from SteamSDK
     if (multiplayerSession is MyMultiplayerClient)
         (multiplayerSession as MyMultiplayerClient).LoadMembersFromWorld(world.Checkpoint.Clients);
 }
Exemplo n.º 53
0
        public static MyMultiplayerJoinResult JoinLobby(ulong lobbyId)
        {
            MyTrace.Send(TraceWindow.Multiplayer, "Join game");
            MyMultiplayerJoinResult ret = new MyMultiplayerJoinResult();
            Lobby.Join(lobbyId, (info, result) =>
            {
                if (!ret.Cancelled)
                {
                    if (result == Result.OK && info.EnterState == LobbyEnterResponseEnum.Success && info.Lobby.GetOwner() == MySteam.UserId)
                    {
                        // Joining lobby as server is dead-end, nobody has world. It's considered doesn't exists
                        info.EnterState = LobbyEnterResponseEnum.DoesntExist;
                        info.Lobby.Leave();
                    }

                    MyTrace.Send(TraceWindow.Multiplayer, "Lobby joined");
                    bool success = result == Result.OK && info.EnterState == LobbyEnterResponseEnum.Success;
                    ret.RaiseJoined(result, info, success ? MyMultiplayer.Static = new MyMultiplayerLobby(info.Lobby, new MySyncLayer(new MyTransportLayer(MyMultiplayer.GameEventChannel))) : null);
                }
            });
            return ret;
        }
Exemplo n.º 54
0
 private static void OnMultiplayerHost(Result hostResult, MyMultiplayerBase multiplayer)
 {
     if (hostResult == Result.OK)
     {
         Static.StartServer(multiplayer);
     }
     else
     {
         var notification = new MyHudNotification(MyCommonTexts.MultiplayerErrorStartingServer, 10000, MyFontEnum.Red);
         notification.SetTextFormatArguments(hostResult.ToString());
         MyHud.Notifications.Add(notification);
     }
 }
Exemplo n.º 55
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();
        }
Exemplo n.º 56
0
        public static void OnJoinBattle(MyGuiScreenProgress progress, Result joinResult, LobbyEnterInfo enterInfo, MyMultiplayerBase multiplayer)
        {
            MyLog.Default.WriteLine(String.Format("Battle lobby join response: {0}, enter state: {1}", joinResult.ToString(), enterInfo.EnterState));

            bool battleCanBeJoined = multiplayer != null && multiplayer.BattleCanBeJoined;
            if (joinResult == Result.OK && enterInfo.EnterState == LobbyEnterResponseEnum.Success && battleCanBeJoined && multiplayer.GetOwner() != Sync.MyId)
            {
                // Create session with empty world
                Debug.Assert(MySession.Static == null);

                MySession.CreateWithEmptyWorld(multiplayer);
                MySession.Static.Settings.Battle = true;

                progress.CloseScreen();

                MyLog.Default.WriteLine("Battle lobby joined");

                if (MyPerGameSettings.GUI.BattleLobbyClientScreen != null)
                    MyGuiSandbox.AddScreen(MyGuiSandbox.CreateScreen(MyPerGameSettings.GUI.BattleLobbyClientScreen));
                else
                    Debug.Fail("No battle lobby client screen");
            }
            else
            {
                bool statusFullMessage = true;
                string status = MyTexts.GetString(MyCommonTexts.MultiplayerErrorServerHasLeft);

                if (joinResult != Result.OK)
                {
                    status = joinResult.ToString();
                    statusFullMessage = false;
                }
                else if (enterInfo.EnterState != LobbyEnterResponseEnum.Success)
                {
                    status = enterInfo.EnterState.ToString();
                    statusFullMessage = false;
                }
                else if (!battleCanBeJoined)
                {
                    if (MyFakes.ENABLE_JOIN_STARTED_BATTLE)
                    {
                        status = status = MyTexts.GetString(MyCommonTexts.MultiplayerErrorSessionEnded);
                        statusFullMessage = true;
                    }
                    else
                    {
                        status = "GameStarted";
                        statusFullMessage = false;
                    }
                }

                MyLog.Default.WriteLine("Battle join failed: " + status);

                OnJoinBattleFailed(progress, multiplayer, status, statusFullMessage: statusFullMessage);
            }
        }
Exemplo n.º 57
0
 internal void UnregisterChat(MyMultiplayerBase multiplayer)
 {
     if (MyFakes.ENABLE_GPS)
         multiplayer.ChatMessageReceived -= ParseChat;
 }
Exemplo n.º 58
0
 private static void CheckDx11AndJoin(MyObjectBuilder_World world, MyMultiplayerBase multiplayer)
 {
     bool needsDx11 = world.Checkpoint.RequiresDX >= 11;
     if (!needsDx11 || MySandboxGame.IsDirectX11)
     {
         if (multiplayer.Battle)
         {
             if (multiplayer.BattleCanBeJoined)
             {
                 MySessionLoader.LoadMultiplayerBattleWorld(world, multiplayer);
             }
             else
             {
                 MyLog.Default.WriteLine("World downloaded but battle game ended");
                 MySessionLoader.UnloadAndExitToMenu();
                 MyGuiSandbox.Show(MyCommonTexts.MultiplayerErrorSessionEnded);
                 multiplayer.Dispose();
             }
         }
         else if (multiplayer.Scenario)
         {
             MySessionLoader.LoadMultiplayerScenarioWorld(world, multiplayer);
         }
         else
         {
             MySessionLoader.LoadMultiplayerSession(world, multiplayer);
         }
     }
     else
     {
         HandleDx11Needed();
     }
 }
 public MyMultiplayerBattleData(MyMultiplayerBase multiplayer)
 {
     m_multiplayer = multiplayer;
     m_multiplayer.RegisterControlMessage<KeyValueDataMsg>(MyControlMessageEnum.BattleKeyValue, OnKeyValueChanged, MyMessagePermissions.FromServer);
 }
Exemplo n.º 60
0
        public static void LoadMultiplayerScenarioWorld(MyObjectBuilder_World world, MyMultiplayerBase multiplayerSession)
        {
            Debug.Assert(MySession.Static != null);

            MyLog.Default.WriteLine("LoadMultiplayerScenarioWorld() - Start");

            if (world.Checkpoint.BriefingVideo != null && world.Checkpoint.BriefingVideo.Length > 0)
                MyGuiSandbox.OpenUrlWithFallback(world.Checkpoint.BriefingVideo, "Scenario briefing video", true);

            if (!MySteamWorkshop.CheckLocalModsAllowed(world.Checkpoint.Mods, false))
            {
                MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                    messageCaption: MyTexts.Get(MySpaceTexts.MessageBoxCaptionError),
                    messageText: MyTexts.Get(MySpaceTexts.DialogTextLocalModsDisabledInMultiplayer),
                    buttonType: MyMessageBoxButtonsType.OK,
                    callback: delegate(MyGuiScreenMessageBox.ResultEnum result) { MyGuiScreenMainMenu.ReturnToMainMenu(); }));
                MyLog.Default.WriteLine("LoadMultiplayerScenarioWorld() - End");
                return;
            }

            MySteamWorkshop.DownloadModsAsync(world.Checkpoint.Mods,
                onFinishedCallback: delegate(bool success)
                {
                    if (success)
                    {
                        MyScreenManager.CloseAllScreensNowExcept(null);
                        MyGuiSandbox.Update(MyEngineConstants.UPDATE_STEP_SIZE_IN_MILLISECONDS);

                        MyGuiScreenGamePlay.StartLoading(delegate
                        {
                            MySession.Static.LoadMultiplayerWorld(world, multiplayerSession);
                            if (ScenarioWorldLoaded != null)
                                ScenarioWorldLoaded();
                        });
                    }
                    else
                    {
                        MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                            messageCaption: MyTexts.Get(MySpaceTexts.MessageBoxCaptionError),
                            messageText: MyTexts.Get(MySpaceTexts.DialogTextDownloadModsFailed),
                            buttonType: MyMessageBoxButtonsType.OK,
                            callback: delegate(MyGuiScreenMessageBox.ResultEnum result) { MyGuiScreenMainMenu.ReturnToMainMenu(); }));
                    }
                    MyLog.Default.WriteLine("LoadMultiplayerScenarioWorld() - End");
                },
                onCancelledCallback: delegate()
                {
                    MyGuiScreenMainMenu.UnloadAndExitToMenu();
                });
        }