Пример #1
0
        public static MyObjectBuilder_World GetClientWorld(EndpointId sender)
        {
            //if (!EssentialsPlugin.Instance.Config.EnableClientTweaks)
            //    return MySession.Static.GetWorld(false);

            Log.Info($"Preparing world for {sender.Value}...");

            //var ob = MySession.Static.GetWorld(false);
            //ob.Sector = GetClientSector(sender.Value);

            //Log.Warn("Custom checkpoint generation disabled. Using vanilla system until rework is finished.");

            var ob = new MyObjectBuilder_World
            {
                Checkpoint = GetClientCheckpoint(sender.Value),
                Sector     = GetClientSector(sender.Value),
                Planets    = MySession.Static.GetPlanetObjectBuilders()
            };

            if (EssentialsPlugin.Instance.Config.PackPlanets)
            {
                Stopwatch stopwatch = Stopwatch.StartNew();
                ob.VoxelMaps = new SerializableDictionary <string, byte[]>(GetUncompressedVoxels(true));
                stopwatch.Stop();
                Log.Info($"Voxel snapshot took {stopwatch.Elapsed.TotalMilliseconds}ms");
            }
            else
            {
                ob.VoxelMaps = new SerializableDictionary <string, byte[]>();
            }

            ob.Planets = MySession.Static.GetPlanetObjectBuilders();

            return(ob);
        }
Пример #2
0
        // ReSharper disable once InconsistentNaming
        private static void SuffixGetWorld(ref MyObjectBuilder_World __result)
        {
            //copy this list so mods added here don't propagate up to the real session
            __result.Checkpoint.Mods = __result.Checkpoint.Mods.ToList();

            __result.Checkpoint.Mods.AddRange(SessionManager.OverrideMods);
        }
Пример #3
0
        // ReSharper disable once InconsistentNaming
        private static void SuffixGetWorld(ref MyObjectBuilder_World __result)
        {
            //copy this list so mods added here don't propagate up to the real session
            __result.Checkpoint.Mods = __result.Checkpoint.Mods.ToList();

            __result.Checkpoint.Mods.Add(new MyObjectBuilder_Checkpoint.ModItem(TorchModCore.MOD_ID));
        }
Пример #4
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();
            }
        }
Пример #5
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!");
        }
Пример #6
0
        private static void CleanupClientWorld(MyObjectBuilder_World worldData, ulong playerId, long senderIdentity)
        {
            /*
             * The entire client join code can be cleaned up massively to reduce server load. However, that needs to be in another plugin or keen
             *
             *
             * This is being ran directly after the original cleanup. Original removes:
             * 1. Station store items
             * 2. Player relations (keeps only theirs)
             * 3. Player Faction relations (keeps only theres)
             *
             */

            //I know ALEs stuff removes this, but lets just add it in essentials too
            foreach (var Identity in worldData.Checkpoint.Identities)
            {
                //Clear all put sender identity last death position
                if (Identity.IdentityId != senderIdentity)
                {
                    Identity.LastDeathPosition = null;
                }
            }

            //I dont trust keen to do it
            worldData.Checkpoint.Gps.Dictionary.TryGetValue(senderIdentity, out MyObjectBuilder_Gps value);
            worldData.Checkpoint.Gps.Dictionary.Clear();
            if (value != null)
            {
                worldData.Checkpoint.Gps.Dictionary.Add(senderIdentity, value);
            }

            foreach (var SessionComponent in worldData.Checkpoint.SessionComponents)
            {
                if (SessionComponent is MyObjectBuilder_SessionComponentResearch Component)
                {
                    // Remove everyone elses research shit (quick and dirty)
                    for (int i = Component.Researches.Count - 1; i >= 0; i--)
                    {
                        if (Component.Researches[i].IdentityId == senderIdentity)
                        {
                            continue;
                        }

                        Component.Researches.RemoveAt(i);
                    }
                }
            }

            foreach (var Player in worldData.Checkpoint.AllPlayersData.Dictionary)
            {
                if (Player.Value.IdentityId == senderIdentity)
                {
                    continue;
                }

                //Clear toolbar junk for other players. Seriously keen what the F**K
                Player.Value.Toolbar = null;
            }
        }
Пример #7
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();
            });
        }
        static private void SuffixGetWorld(ref MyObjectBuilder_World __result)
        {
            //copy this list so mods added here don't propagate up to the real session
            __result.Checkpoint.Mods = __result.Checkpoint.Mods.ToList();

            if (Instance.Config.Enabled)
            {
                __result.Checkpoint.Mods.Add(new MyObjectBuilder_Checkpoint.ModItem(MOD_ID));
            }
        }
Пример #10
0
        void MyDownloadWorldResult_Received(byte[] data, int dataSize, ulong sender, TimeSpan timestamp)
        {
            ProfilerShort.Begin("DownloadWorldChunk");

            Debug.Assert(State == MyDownloadWorldStateEnum.Established || State == MyDownloadWorldStateEnum.InProgress, "This should not be called, find why it's called");
            if (m_sender == sender)
            {
                var status = m_receiveMsg.Compose(data, dataSize);
                switch (status)
                {
                case MyMultipartMessage.Status.InProgress:
                    break;

                case MyMultipartMessage.Status.Finished:
                    Deregister();

                    m_receiveMsg.Stream.Position = 0;
                    if (m_receiveMsg.Stream.Length > 0)
                    {
                        MyObjectBuilder_World worldData;
                        if (Sandbox.Common.ObjectBuilders.Serializer.MyObjectBuilderSerializer.DeserializeGZippedXML(m_receiveMsg.Stream, out worldData))
                        {
                            WorldData = worldData;
                            State     = MyDownloadWorldStateEnum.Success;

                            MySandboxGame.Log.WriteLineAndConsole(String.Format("World download progress status: {0}, {1}", State.ToString(), this.Progress));
                        }
                        else
                        {
                            MySandboxGame.Log.WriteLine("Deserialization failed during world download.");
                            State = MyDownloadWorldStateEnum.DeserializationFailed;
                        }
                    }
                    else
                    {
                        State = MyDownloadWorldStateEnum.WorldNotAvailable;
                    }
                    break;

                case MyMultipartMessage.Status.Error:
                    Deregister();
                    MySandboxGame.Log.WriteLine("Invalid packet header.");
                    State = MyDownloadWorldStateEnum.InvalidMessage;
                    break;
                }

                m_mp.SendAck(sender);

                MyTrace.Send(TraceWindow.Multiplayer, String.Format("World download progress status: {0}, {1}", State.ToString(), this.Progress));
                RaiseProgressChanged();
            }

            ProfilerShort.End();
        }
Пример #11
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);
        }
Пример #12
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();
            });
        }
Пример #13
0
        //private static void Init()
        //{
        //    MySession.Static.Factions.FactionStateChanged += (change, l, arg3, arg4, arg5) => _dirty = true;
        //    MySession.Static.Factions.FactionCreated += id => _dirty = true;
        //    MySession.Static.Factions.FactionEdited += id => _dirty = true;
        //    MySession.Static.Factions.FactionAutoAcceptChanged += (l, b, arg3) => _dirty = true;

        //    MySession.Static.ChatSystem.FactionHistoryDeleted += () => _dirty = true;
        //    MySession.Static.ChatSystem.FactionMessageReceived += id => _dirty = true;
        //    MySession.Static.ChatSystem.PlayerMessageReceived += id => _dirty = true;
        //}


        /// <summary>
        /// Main entry point to this class. Prefix on MyMultiplayerBase.OnWorldRequest.
        /// Effectively replaces all client join logic.
        /// </summary>
        /// <param name="sender"></param>
        /// <returns></returns>
        private static bool PatchGetWorld(EndpointId sender)
        {
            if (!EssentialsPlugin.Instance.Config.EnableClientTweaks)
            {
                return(true);
            }

            Log.Info($"World request received: {MyMultiplayer.Static.GetMemberName(sender.Value)}");

            if (MyMultiplayer.Static.KickedClients.ContainsKey(sender.Value) || MyMultiplayer.Static.BannedClients.Contains(sender.Value) || MySandboxGame.ConfigDedicated?.Banned.Contains(sender.Value) == true)
            {
                //a hacked client or a plugin can request world data without properly joining the server
                Log.Error("Banned client requested world. This is bad.");
                _raseClientLeft(MyMultiplayer.Static, sender.Value, MyChatMemberStateChangeEnum.Banned);
                return(false);
            }

            if (MySession.Static == null)
            {
                Log.Error("World is not loaded!");
                return(false);
            }

            //taking a session snapshot is the only thing that must be done synchronously
            MyObjectBuilder_World worldData = GetClientWorld(sender);
            Stopwatch             stopwatch = Stopwatch.StartNew();

            worldData.Checkpoint.WorkshopId = null;
            stopwatch.Stop();
            Log.Info($"World checkpoint took {stopwatch.Elapsed.TotalMilliseconds}ms");

            if (worldData.Clusters == null)
            {
                worldData.Clusters = new List <BoundingBoxD>();
            }
            worldData.Clusters.Clear();
            MyPhysics.SerializeClusters(worldData.Clusters);

            //serializing, compressing, and sending the data can all be dumped into a thread
            if (EssentialsPlugin.Instance.Config.AsyncJoin)
            {
                Task.Run(() => PackAndSend(worldData, sender));
            }
            else
            {
                PackAndSend(worldData, sender);
            }

            return(false);
        }
Пример #14
0
        protected void OnWorldRequest(ref MyControlWorldRequestMsg data, ulong sender)
        {
            ProfilerShort.Begin("OnWorldRequest");

            MyTrace.Send(TraceWindow.Multiplayer, "World request received");

            MySandboxGame.Log.WriteLineAndConsole("World request received: " + GetMemberName(sender));

            if (IsClientKickedOrBanned(sender) || MySandboxGame.ConfigDedicated.Banned.Contains(sender))
            {
                MySandboxGame.Log.WriteLineAndConsole("Sending no world, because client has been kicked or banned: " + GetMemberName(sender) + " (Client is probably modified.)");
                RaiseClientLeft(sender, ChatMemberStateChangeEnum.Banned);
                return;
            }

            m_worldSendStream = new MemoryStream();

            if (IsServer && MySession.Static != null)
            {
                MySandboxGame.Log.WriteLine("...responding");

                MyObjectBuilder_World worldData = MySession.Static.GetWorld(false);
                var checkpoint = worldData.Checkpoint;
                checkpoint.WorkshopId                = null;
                checkpoint.CharacterToolbar          = null;
                checkpoint.Settings.ScenarioEditMode = checkpoint.Settings.ScenarioEditMode && !MySession.Static.LoadedAsMission;

                worldData.Clusters = new List <VRageMath.BoundingBoxD>();
                Sandbox.Engine.Physics.MyPhysics.SerializeClusters(worldData.Clusters);

                ProfilerShort.Begin("SerializeXML");
                MyObjectBuilderSerializer.SerializeXML(m_worldSendStream, worldData, MyObjectBuilderSerializer.XmlCompression.Gzip);
                ProfilerShort.BeginNextBlock("SendFlush");
                SyncLayer.TransportLayer.SendFlush(sender);
                ProfilerShort.End();
            }
            var buffer = m_worldSendStream.ToArray();
            MyMultipartSender msgSender = new MyMultipartSender(buffer, buffer.Length, sender, MyMultiplayer.WorldDownloadChannel, 1150);

            m_worldSenders[sender] = msgSender;

            ProfilerShort.End();
        }
Пример #15
0
        public void SerializeWorldData(MyObjectBuilder_World WorldData)
        {
            MethodInfo CleanupData = typeof(MyMultiplayerServerBase).GetMethod("CleanUpData", BindingFlags.Static | BindingFlags.NonPublic, null, new Type[3]
            {
                typeof(MyObjectBuilder_World),
                typeof(ulong),
                typeof(long),
            }, null);

            object[] Data = new object[] { WorldData, PlayerID, IdentityID };
            CleanupData.Invoke(null, Data);
            WorldData = (MyObjectBuilder_World)Data[0];
            using (MemoryStream memoryStream = new MemoryStream())
            {
                MyObjectBuilderSerializer.SerializeXML(memoryStream, WorldData, MyObjectBuilderSerializer.XmlCompression.Gzip);
                this.WorldData = memoryStream.ToArray();
                Log.Warn("Successfully Converted World");
            }
        }
Пример #16
0
        private static void CheckDx11AndJoin(MyObjectBuilder_World world, MyMultiplayerBase multiplayer)
        {
            bool needsDx11 = world.Checkpoint.RequiresDX >= 11;

            if (!needsDx11 || MySandboxGame.IsDirectX11)
            {
                if (multiplayer.Scenario)
                {
                    MySessionLoader.LoadMultiplayerScenarioWorld(world, multiplayer);
                }
                else
                {
                    MySessionLoader.LoadMultiplayerSession(world, multiplayer);
                }
            }
            else
            {
                HandleDx11Needed();
            }
        }
Пример #17
0
        protected void OnWorldRequest(ref MyControlWorldRequestMsg data, ulong sender)
        {
            ProfilerShort.Begin("OnWorldRequest");

            MyTrace.Send(TraceWindow.Multiplayer, "World request received");

            MySandboxGame.Log.WriteLineAndConsole("World request received: " + GetMemberName(sender));

            if (IsClientKickedOrBanned(sender))
            {
                MySandboxGame.Log.WriteLineAndConsole("Sending no world, because client has been kicked or banned: " + GetMemberName(sender));
                return;
            }

            m_worldSendStream = new MemoryStream();

            if (IsServer && MySession.Static != null)
            {
                MySandboxGame.Log.WriteLine("...responding");

                MyMultipartMessage.SendPreemble(sender, MyMultiplayer.WorldDownloadChannel);

                MyObjectBuilder_World worldData = MySession.Static.GetWorld(false);
                var checkpoint = worldData.Checkpoint;
                checkpoint.WorkshopId                = null;
                checkpoint.CharacterToolbar          = null;
                checkpoint.Settings.ScenarioEditMode = checkpoint.Settings.ScenarioEditMode && !MySession.Static.LoadedAsMission;
                ProfilerShort.Begin("SerializeXML");
                MyObjectBuilderSerializer.SerializeXML(m_worldSendStream, worldData, MyObjectBuilderSerializer.XmlCompression.Gzip);
                ProfilerShort.BeginNextBlock("SendFlush");
                SyncLayer.TransportLayer.SendFlush(sender);
                ProfilerShort.End();
            }

            var buffer = m_worldSendStream.ToArray();
            MyMultipartSender msgSender = new MyMultipartSender(buffer, buffer.Length, sender, MyMultiplayer.WorldDownloadChannel, 1150 * 12);

            m_worldSenders[sender] = msgSender;

            ProfilerShort.End();
        }
Пример #18
0
        /// <summary>
        /// Utility to serialize, compress, and send the world data
        /// </summary>
        /// <param name="worldData"></param>
        /// <param name="sender"></param>
        private static void PackAndSend(MyObjectBuilder_World worldData, EndpointId sender)
        {
            Log.Info("Beginning world compression...");
            try
            {
                using (var worldStream = new MemoryStream())
                {
                    SerializeZipped(worldStream, worldData, EssentialsPlugin.Instance.Config.CompressionLevel, _lastSize);
                    _sendFlush(_transportLayer(MyMultiplayer.Static.SyncLayer), sender.Value);

                    Stopwatch stopwatch = Stopwatch.StartNew();
                    byte[]    buffer    = worldStream.ToArray();
                    Log.Info($"Sending {Utilities.FormatDataSize(buffer.Length)} world data...");
                    SendWorld(buffer, sender);
                    stopwatch.Stop();
                    Log.Info($"Data flush took {stopwatch.Elapsed.TotalMilliseconds}ms");
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failure during world compression!");
            }
        }
Пример #19
0
 protected void OnWorldRequest(EndpointId sender)
 {
     MySandboxGame.Log.WriteLineAndConsole("World request received: " + this.GetMemberName(sender.Value));
     if (base.IsClientKickedOrBanned(sender.Value) || ((MySandboxGame.ConfigDedicated != null) && MySandboxGame.ConfigDedicated.Banned.Contains(sender.Value)))
     {
         MySandboxGame.Log.WriteLineAndConsole("Sending no world, because client has been kicked or banned: " + this.GetMemberName(sender.Value) + " (Client is probably modified.)");
         base.RaiseClientLeft(sender.Value, MyChatMemberStateChangeEnum.Banned);
     }
     else
     {
         this.m_worldSendStream = new MemoryStream();
         if (base.IsServer && (MySession.Static != null))
         {
             MyObjectBuilder_Gps gps;
             MySandboxGame.Log.WriteLine("...responding");
             long key = MySession.Static.Players.TryGetIdentityId(sender.Value, 0);
             MyObjectBuilder_World      objectBuilder = MySession.Static.GetWorld(false);
             MyObjectBuilder_Checkpoint checkpoint    = objectBuilder.Checkpoint;
             checkpoint.WorkshopId                = null;
             checkpoint.CharacterToolbar          = null;
             checkpoint.Settings.ScenarioEditMode = checkpoint.Settings.ScenarioEditMode && !MySession.Static.LoadedAsMission;
             checkpoint.Gps.Dictionary.TryGetValue(key, out gps);
             checkpoint.Gps.Dictionary.Clear();
             if (gps != null)
             {
                 checkpoint.Gps.Dictionary.Add(key, gps);
             }
             objectBuilder.Clusters = new List <BoundingBoxD>();
             MyPhysics.SerializeClusters(objectBuilder.Clusters);
             objectBuilder.Planets = MySession.Static.GetPlanetObjectBuilders();
             MyObjectBuilderSerializer.SerializeXML(this.m_worldSendStream, objectBuilder, MyObjectBuilderSerializer.XmlCompression.Gzip, null);
             base.SyncLayer.TransportLayer.SendFlush(sender.Value);
             byte[] worldData = this.m_worldSendStream.ToArray();
             this.ReplicationLayer.SendWorld(worldData, MyEventContext.Current.Sender);
         }
     }
 }
Пример #20
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();
        }
Пример #21
0
        public MyObjectBuilder_World GetWorld(bool includeEntities = true)
        {
            ProfilerShort.Begin("GetWorld");

            var ob = new MyObjectBuilder_World()
            {
                Checkpoint = GetCheckpoint(Name),
                Sector = GetSector(includeEntities),
                VoxelMaps = new SerializableDictionary<string, byte[]>(Static.GetVoxelMapsArray(includeEntities))
            };

            ProfilerShort.End();

            return ob;
        }
Пример #22
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);
 }
Пример #23
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();
        }
        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) { MyGuiScreenMainMenu.ReturnToMainMenu(); }));
                MyLog.Default.WriteLine("LoadMultiplayerScenarioWorld() - End");
                return;
            }

            MySteamWorkshop.DownloadModsAsync(world.Checkpoint.Mods,
                onFinishedCallback: delegate(bool success)
                {
                    if (success)
                    {
                        MyScreenManager.CloseAllScreensNowExcept(null);
                        MyGuiSandbox.Update(VRage.Game.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(MyCommonTexts.MessageBoxCaptionError),
                            messageText: MyTexts.Get(MyCommonTexts.DialogTextDownloadModsFailed),
                            buttonType: MyMessageBoxButtonsType.OK,
                            callback: delegate(MyGuiScreenMessageBox.ResultEnum result) { MyGuiScreenMainMenu.ReturnToMainMenu(); }));
                    }
                    MyLog.Default.WriteLine("LoadMultiplayerScenarioWorld() - End");
                },
                onCancelledCallback: delegate()
                {
                    MyGuiScreenMainMenu.UnloadAndExitToMenu();
                });
        }
Пример #25
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 static void SendWorldData(ulong steamId)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                if (MyAPIGateway.Session != null)
                {
                    DateTime start = DateTime.Now;
                    LogManager.APILog.WriteLineAndConsole(string.Format("...responding to user: {0}", steamId));
                    SendPreemble(steamId, 1);
                    SendFlush(steamId);

                    // Let's sleep for 5 seconds and let plugins know we're online -- let's not after all, causing sync issues
                    //Thread.Sleep(5000);
                    MyObjectBuilder_World myObjectBuilderWorld = null;
                    lock (m_inGame)
                    {
                        if (!m_inGame.Contains(steamId))
                        {
                            LogManager.APILog.WriteLineAndConsole(string.Format("Cancelled send to user: {0}", steamId));
                            return;
                        }
                    }

                    // This is probably safe to do outside of the game instance, but let's just make sure.
                    SandboxGameAssemblyWrapper.Instance.GameAction(() =>
                    {
                        myObjectBuilderWorld = MyAPIGateway.Session.GetWorld();
                    });

                    if (replaceData)
                    {
                        for (int r = myObjectBuilderWorld.Sector.SectorObjects.Count - 1; r >= 0; r--)
                        {
                            MyObjectBuilder_EntityBase entity = (MyObjectBuilder_EntityBase)myObjectBuilderWorld.Sector.SectorObjects[r];
                            if (!(entity is MyObjectBuilder_CubeGrid) && !(entity is MyObjectBuilder_VoxelMap))
                            {
                                continue;
                            }

                            if ((entity is MyObjectBuilder_CubeGrid) && (entity.PersistentFlags & MyPersistentEntityFlags2.InScene) == MyPersistentEntityFlags2.InScene)
                            {
                                continue;
                            }

                            myObjectBuilderWorld.Sector.SectorObjects.RemoveAt(r);
                        }

                        myObjectBuilderWorld.VoxelMaps.Dictionary.Clear();
                    }

                    MyObjectBuilder_Checkpoint checkpoint = myObjectBuilderWorld.Checkpoint;
                    checkpoint.WorkshopId       = null;
                    checkpoint.CharacterToolbar = null;
                    DateTime cs = DateTime.Now;
                    MyObjectBuilderSerializer.SerializeXML(ms, myObjectBuilderWorld, MyObjectBuilderSerializer.XmlCompression.Gzip, null);
                    LogManager.APILog.WriteLineAndConsole(string.Format("...response construction took {0}ms (cp - {1}ms)", (DateTime.Now - start).TotalMilliseconds, (DateTime.Now - cs).TotalMilliseconds));
                }

                TransferWorld(ms, steamId);
            }
            catch (Exception ex)
            {
                LogManager.APILog.WriteLineAndConsole(string.Format("SendWorldData Error: {0}", ex.ToString()));
            }
        }
Пример #27
0
        private static void SendWorldData(ulong steamId)
        {
            try
            {
                MemoryStream ms = new MemoryStream( );
                if (MyAPIGateway.Session != null)
                {
                    DateTime start = DateTime.Now;
                    ApplicationLog.BaseLog.Info("...responding to user: {0}", steamId);
                    SendPreamble(steamId, 1);
                    SendFlush(steamId);

                    // Let's sleep for 5 seconds and let plugins know we're online -- let's not after all, causing sync issues
                    //Thread.Sleep(5000);
                    MyObjectBuilder_World myObjectBuilderWorld = null;
                    lock ( m_inGame )
                    {
                        if (!m_inGame.Contains(steamId))
                        {
                            ApplicationLog.BaseLog.Info("Cancelled send to user: {0}", steamId);
                            return;
                        }
                    }

                    // This is probably safe to do outside of the game instance, but let's just make sure.
                    SandboxGameAssemblyWrapper.Instance.GameAction(() =>
                    {
                        myObjectBuilderWorld = MyAPIGateway.Session.GetWorld( );
                    });

                    if (replaceData)
                    {
                        for (int r = myObjectBuilderWorld.Sector.SectorObjects.Count - 1; r >= 0; r--)
                        {
                            MyObjectBuilder_EntityBase entity = (MyObjectBuilder_EntityBase)myObjectBuilderWorld.Sector.SectorObjects[r];

                            if (!(entity is MyObjectBuilder_CubeGrid) && !(entity is MyObjectBuilder_VoxelMap) && !(entity is MyObjectBuilder_Character))
                            {
                                continue;
                            }

                            if ((entity is MyObjectBuilder_CubeGrid) && ((MyObjectBuilder_CubeGrid)entity).DisplayName.Contains("CommRelay"))
                            {
                                continue;
                            }

                            /*
                             * if (!(entity is MyObjectBuilder_CubeGrid))
                             *      continue;
                             *
                             * if ((entity.PersistentFlags & MyPersistentEntityFlags2.InScene) == MyPersistentEntityFlags2.InScene)
                             *      continue;
                             */

                            myObjectBuilderWorld.Sector.SectorObjects.RemoveAt(r);
                        }

                        myObjectBuilderWorld.Sector.Encounters = null;

                        myObjectBuilderWorld.VoxelMaps.Dictionary.Clear( );
                        myObjectBuilderWorld.Checkpoint.Settings.ProceduralDensity = 0f;
                        myObjectBuilderWorld.Checkpoint.Settings.ProceduralSeed    = 0;

                        // Check if this is OK?
                        //myObjectBuilderWorld.Checkpoint.ConnectedPlayers.Dictionary.Clear();
                        myObjectBuilderWorld.Checkpoint.DisconnectedPlayers.Dictionary.Clear( );

                        long playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId(steamId);

                        MyObjectBuilder_Toolbar blankToolbar = new MyObjectBuilder_Toolbar( );
                        foreach (KeyValuePair <MyObjectBuilder_Checkpoint.PlayerId, MyObjectBuilder_Player> p in myObjectBuilderWorld.Checkpoint.AllPlayersData.Dictionary)
                        {
                            if (p.Value.EntityCameraData != null)
                            {
                                p.Value.EntityCameraData.Clear( );
                            }

                            if (p.Value.CameraData != null)
                            {
                                p.Value.CameraData.Dictionary.Clear( );
                            }

                            if (p.Key.ClientId == steamId)
                            {
                                continue;
                            }

                            p.Value.Toolbar             = null;
                            p.Value.CharacterCameraData = null;
                        }

                        for (int r = myObjectBuilderWorld.Checkpoint.Gps.Dictionary.Count - 1; r >= 0; r--)
                        {
                            KeyValuePair <long, MyObjectBuilder_Gps> p = myObjectBuilderWorld.Checkpoint.Gps.Dictionary.ElementAt(r);

                            if (p.Key == playerId)
                            {
                                continue;
                            }

                            myObjectBuilderWorld.Checkpoint.Gps.Dictionary.Remove(p.Key);
                        }

                        myObjectBuilderWorld.Checkpoint.ChatHistory.RemoveAll(x => x.IdentityId != playerId);

                        long factionId = 0;
                        if (myObjectBuilderWorld.Checkpoint.Factions.Players.Dictionary.ContainsKey(playerId))
                        {
                            factionId = myObjectBuilderWorld.Checkpoint.Factions.Players.Dictionary[playerId];
                            myObjectBuilderWorld.Checkpoint.FactionChatHistory.RemoveAll(x => x.FactionId1 != factionId && x.FactionId2 != factionId);
                            myObjectBuilderWorld.Checkpoint.Factions.Requests.RemoveAll(x => x.FactionId != factionId);
                        }
                        else
                        {
                            myObjectBuilderWorld.Checkpoint.FactionChatHistory.Clear( );
                            myObjectBuilderWorld.Checkpoint.Factions.Requests.Clear( );
                        }

                        foreach (MyObjectBuilder_Faction faction in myObjectBuilderWorld.Checkpoint.Factions.Factions)
                        {
                            if (faction.FactionId != factionId)
                            {
                                faction.PrivateInfo = "";
                            }
                        }
                    }

                    // This will modify the world data to remove voxels and turn off procedural for the player.  The
                    // server controls procedural anyway, and doesn't require the user to know about it.  If we don't
                    // turn it off, the objects will still generate on the server.  Possible issue: turning on voxel
                    // management + procedural encounters may be an issue, as I don't think the server sends procedural
                    // encounters to the client.  This may be a gotcha issue when it comes to using this option
                    if (WorldVoxelModify)
                    {
                        for (int r = myObjectBuilderWorld.Sector.SectorObjects.Count - 1; r >= 0; r--)
                        {
                            MyObjectBuilder_EntityBase entity = (MyObjectBuilder_EntityBase)myObjectBuilderWorld.Sector.SectorObjects[r];

                            if (!(entity is MyObjectBuilder_VoxelMap))
                            {
                                continue;
                            }

                            myObjectBuilderWorld.Sector.SectorObjects.RemoveAt(r);
                        }

                        myObjectBuilderWorld.Sector.Encounters = null;

                        myObjectBuilderWorld.VoxelMaps.Dictionary.Clear();
                        myObjectBuilderWorld.Checkpoint.Settings.ProceduralDensity = 0f;
                        myObjectBuilderWorld.Checkpoint.Settings.ProceduralSeed    = 0;
                    }

                    MyObjectBuilder_Checkpoint checkpoint = myObjectBuilderWorld.Checkpoint;
                    checkpoint.WorkshopId       = null;
                    checkpoint.CharacterToolbar = null;
                    DateTime cs = DateTime.Now;
                    MyObjectBuilderSerializer.SerializeXML(ms, myObjectBuilderWorld, MyObjectBuilderSerializer.XmlCompression.Gzip, null);

                    /*
                     * MemoryStream vms = new MemoryStream();
                     * MyObjectBuilderSerializer.SerializeXML(vms, myObjectBuilderWorld, MyObjectBuilderSerializer.XmlCompression.Uncompressed, null);
                     * FileStream file = new FileStream("e:\\temp\\test.txt", FileMode.Create);
                     * vms.WriteTo(file);
                     * file.Close();
                     */

                    ApplicationLog.BaseLog.Info("...response construction took {0}ms (cp - {1}ms) size - {2} bytes", (DateTime.Now - start).TotalMilliseconds, (DateTime.Now - cs).TotalMilliseconds, ms.Length);
                }

                TransferWorld(ms, steamId);
            }
            catch (Exception ex)
            {
                ApplicationLog.BaseLog.Error(ex, "SendWorldData Error: {0}", ex);
            }
        }
Пример #28
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;
            }


            var customLoadingScreenPath = GetCustomLoadingScreenImagePath(world.Checkpoint.CustomLoadingScreenImage);

            MySteamWorkshop.DownloadModsAsync(world.Checkpoint.Mods,
                                              onFinishedCallback :
                                              delegate(bool success, string mismatchMods)
            {
                if (success)
                {
                    CheckMismatchmods(mismatchMods, delegate(ResultEnum val)
                    {
                        if (val == ResultEnum.OK)
                        {
                            //Sandbox.Audio.MyAudio.Static.Mute = true;
                            MyScreenManager.CloseAllScreensNowExcept(null);
                            MyGuiSandbox.Update(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); }, customLoadingScreenPath, world.Checkpoint.CustomLoadingScreenText);
                        }
                        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();
            });
        }
        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();
                });
        }
Пример #30
0
 public static void LoadWorldData(MyGameServerItem TargetServer, MyObjectBuilder_World TargetWorld)
 {
     Server = TargetServer;
     World  = TargetWorld;
 }
Пример #31
0
        void MyDownloadWorldResult_Received(byte[] data, int dataSize, ulong sender, TimeSpan timestamp)
        {
            ProfilerShort.Begin("DownloadWorldChunk");

            Debug.Assert(State == MyDownloadWorldStateEnum.Established || State == MyDownloadWorldStateEnum.InProgress, "This should not be called, find why it's called");
            if (m_sender == sender)
            {
                var status = m_receiveMsg.Compose(data, dataSize);
                switch (status)
                {
                    case MyMultipartMessage.Status.InProgress:
                        break;

                    case MyMultipartMessage.Status.Finished:
                        Deregister();

                        m_receiveMsg.Stream.Position = 0;
                        if (m_receiveMsg.Stream.Length > 0)
                        {
                            MyObjectBuilder_World worldData;
                            if (MyObjectBuilderSerializer.DeserializeGZippedXML(m_receiveMsg.Stream, out worldData))
                            {
                                WorldData = worldData;
                                State = MyDownloadWorldStateEnum.Success;

                                MySandboxGame.Log.WriteLineAndConsole(String.Format("World download progress status: {0}, {1}", State.ToString(), this.Progress));
                            }
                            else
                            {
                                MySandboxGame.Log.WriteLine("Deserialization failed during world download.");
                                State = MyDownloadWorldStateEnum.DeserializationFailed;
                            }
                        }
                        else
                        {
                            State = MyDownloadWorldStateEnum.WorldNotAvailable;
                        }
                        break;

                    case MyMultipartMessage.Status.Error:
                        Deregister();
                        MySandboxGame.Log.WriteLine("Invalid packet header.");
                        State = MyDownloadWorldStateEnum.InvalidMessage;
                        break;
                }

                m_mp.SendAck(sender);

                MyTrace.Send(TraceWindow.Multiplayer, String.Format("World download progress status: {0}, {1}", State.ToString(), this.Progress));
                RaiseProgressChanged();
            }

            ProfilerShort.End();
        }
Пример #32
0
 public static void SuffixGetWorld(ref MyObjectBuilder_World __result)
 {
     __result.Checkpoint.Mods = __result.Checkpoint.Mods.ToList();
     __result.Checkpoint.Mods.Add(new MyObjectBuilder_Checkpoint.ModItem(1470445959UL));
 }
        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();
                });
        }
 public SwitchServers(MyGameServerItem TargetServer, MyObjectBuilder_World TargetWorld)
 {
     this.TargetServer = TargetServer;
     this.TargetWorld  = TargetWorld;
 }