Connect() public static method

public static Connect ( string host, int port, string password, System.Action onConnect, System.Action onAbort ) : void
host string
port int
password string
onConnect System.Action
onAbort System.Action
return void
        public DirectConnectLogic(Widget widget, Action onExit, Action openLobby, string directConnectHost, int directConnectPort)
        {
            var panel     = widget;
            var ipField   = panel.Get <TextFieldWidget>("IP");
            var portField = panel.Get <TextFieldWidget>("PORT");

            var last = Game.Settings.Player.LastServer.Split(':');

            ipField.Text   = last.Length > 1 ? last[0] : "localhost";
            portField.Text = last.Length == 2 ? last[1] : "1234";

            panel.Get <ButtonWidget>("JOIN_BUTTON").OnClick = () =>
            {
                var port = Exts.WithDefault(1234, () => Exts.ParseIntegerInvariant(portField.Text));

                Game.Settings.Player.LastServer = "{0}:{1}".F(ipField.Text, port);
                Game.Settings.Save();

                ConnectionLogic.Connect(ipField.Text, port, "", () => { Ui.CloseWindow(); openLobby(); }, DoNothing);
            };

            panel.Get <ButtonWidget>("BACK_BUTTON").OnClick = () => { Ui.CloseWindow(); onExit(); };

            if (directConnectHost != null)
            {
                // The connection window must be opened at the end of the tick for the widget hierarchy to
                // work out, but we also want to prevent the server browser from flashing visible for one tick.
                widget.Visible = false;
                Game.RunAfterTick(() =>
                {
                    ConnectionLogic.Connect(directConnectHost, directConnectPort, "", () => { Ui.CloseWindow(); openLobby(); }, DoNothing);
                    widget.Visible = true;
                });
            }
        }
Example #2
0
        public MultiplayerLogic(Widget widget, Action onStart, Action onExit, string directConnectHost, int directConnectPort)
        {
            this.onStart = onStart;
            this.onExit  = onExit;

            incompatibleVersionColor       = ChromeMetrics.Get <Color>("IncompatibleVersionColor");
            incompatibleGameColor          = ChromeMetrics.Get <Color>("IncompatibleGameColor");
            incompatibleProtectedGameColor = ChromeMetrics.Get <Color>("IncompatibleProtectedGameColor");
            protectedGameColor             = ChromeMetrics.Get <Color>("ProtectedGameColor");
            waitingGameColor             = ChromeMetrics.Get <Color>("WaitingGameColor");
            incompatibleWaitingGameColor = ChromeMetrics.Get <Color>("IncompatibleWaitingGameColor");
            gameStartedColor             = ChromeMetrics.Get <Color>("GameStartedColor");
            incompatibleGameStartedColor = ChromeMetrics.Get <Color>("IncompatibleGameStartedColor");

            LoadBrowserPanel(widget);
            LoadDirectConnectPanel(widget);
            LoadCreateServerPanel(widget);

            // Filter and refresh buttons act on the browser panel,
            // but remain visible (disabled) on the other panels
            var refreshButton = widget.Get <ButtonWidget>("REFRESH_BUTTON");

            refreshButton.IsDisabled = () => searchStatus == SearchStatus.Fetching || panel != PanelType.Browser;

            var filtersButton = widget.Get <DropDownButtonWidget>("FILTERS_DROPDOWNBUTTON");

            filtersButton.IsDisabled = () => searchStatus == SearchStatus.Fetching || panel != PanelType.Browser;

            var browserTab = widget.Get <ButtonWidget>("BROWSER_TAB");

            browserTab.IsHighlighted = () => panel == PanelType.Browser;
            browserTab.OnClick       = () => panel = PanelType.Browser;

            var directConnectTab = widget.Get <ButtonWidget>("DIRECTCONNECT_TAB");

            directConnectTab.IsHighlighted = () => panel == PanelType.DirectConnect;
            directConnectTab.OnClick       = () => panel = PanelType.DirectConnect;

            var createServerTab = widget.Get <ButtonWidget>("CREATE_TAB");

            createServerTab.IsHighlighted = () => panel == PanelType.CreateServer;
            createServerTab.OnClick       = () => panel = PanelType.CreateServer;

            widget.Get <ButtonWidget>("BACK_BUTTON").OnClick = () => { Ui.CloseWindow(); onExit(); };
            Game.LoadWidget(null, "GLOBALCHAT_PANEL", widget.Get("GLOBALCHAT_ROOT"), new WidgetArgs());

            RefreshServerList();

            if (directConnectHost != null)
            {
                // The connection window must be opened at the end of the tick for the widget hierarchy to
                // work out, but we also want to prevent the server browser from flashing visible for one tick.
                widget.Visible = false;
                Game.RunAfterTick(() =>
                {
                    ConnectionLogic.Connect(directConnectHost, directConnectPort, "", OpenLobby, DoNothing);
                    widget.Visible = true;
                });
            }
        }
Example #3
0
        void LoadDirectConnectPanel(Widget widget)
        {
            var directConnectPanel = Game.LoadWidget(null, "MULTIPLAYER_DIRECTCONNECT_PANEL",
                                                     widget.Get("TOP_PANELS_ROOT"), new WidgetArgs());

            directConnectPanel.IsVisible = () => panel == PanelType.DirectConnect;

            var ipField   = directConnectPanel.Get <TextFieldWidget>("IP");
            var portField = directConnectPanel.Get <TextFieldWidget>("PORT");

            var last = Game.Settings.Player.LastServer.Split(':');

            ipField.Text   = last.Length > 1 ? last[0] : "localhost";
            portField.Text = last.Length == 2 ? last[1] : "1234";

            directConnectPanel.Get <ButtonWidget>("JOIN_BUTTON").OnClick = () =>
            {
                var port = Exts.WithDefault(1234, () => Exts.ParseIntegerInvariant(portField.Text));

                Game.Settings.Player.LastServer = "{0}:{1}".F(ipField.Text, port);
                Game.Settings.Save();

                ConnectionLogic.Connect(ipField.Text, port, "", OpenLobby, DoNothing);
            };
        }
        // Listen for connection failures
        void ConnectionStateChanged(OrderManager om)
        {
            if (om.Connection.ConnectionState == ConnectionState.NotConnected)
            {
                // Show connection failed dialog
                Ui.CloseWindow();

                Action onConnect = () =>
                {
                    Game.OpenWindow("SERVER_LOBBY", new WidgetArgs()
                    {
                        { "onExit", onExit },
                        { "onStart", onStart },
                        { "skirmishMode", false }
                    });
                };

                Action <string> onRetry = password => ConnectionLogic.Connect(om.Host, om.Port, password, onConnect, onExit);

                var switchPanel = om.ServerExternalMod != null ? "CONNECTION_SWITCHMOD_PANEL" : "CONNECTIONFAILED_PANEL";
                Ui.OpenWindow(switchPanel, new WidgetArgs()
                {
                    { "orderManager", om },
                    { "onAbort", onExit },
                    { "onRetry", onRetry }
                });
            }
        }
Example #5
0
        // Listen for connection failures
        void ConnectionStateChanged(OrderManager om, string password, NetworkConnection connection)
        {
            if (connection.ConnectionState == ConnectionState.NotConnected)
            {
                // Show connection failed dialog
                Ui.CloseWindow();

                Action onConnect = () =>
                {
                    Game.OpenWindow("SERVER_LOBBY", new WidgetArgs()
                    {
                        { "onExit", onExit },
                        { "onStart", onStart },
                        { "skirmishMode", false }
                    });
                };

                Action <string> onRetry = pass => ConnectionLogic.Connect(connection.Target, pass, onConnect, onExit);

                var switchPanel = CurrentServerSettings.ServerExternalMod != null ? "CONNECTION_SWITCHMOD_PANEL" : "CONNECTIONFAILED_PANEL";
                Ui.OpenWindow(switchPanel, new WidgetArgs()
                {
                    { "orderManager", om },
                    { "connection", connection },
                    { "password", password },
                    { "onAbort", onExit },
                    { "onRetry", onRetry }
                });
            }
        }
Example #6
0
        void CreateAndJoin()
        {
            var name = Settings.SanitizedServerName(panel.Get <TextFieldWidget>("SERVER_NAME").Text);
            int listenPort, externalPort;

            if (!Exts.TryParseIntegerInvariant(panel.Get <TextFieldWidget>("LISTEN_PORT").Text, out listenPort))
            {
                listenPort = 1234;
            }

            if (!Exts.TryParseIntegerInvariant(panel.Get <TextFieldWidget>("EXTERNAL_PORT").Text, out externalPort))
            {
                externalPort = 1234;
            }

            var passwordField = panel.GetOrNull <PasswordFieldWidget>("PASSWORD");
            var password      = passwordField != null ? passwordField.Text : "";

            // Save new settings
            Game.Settings.Server.Name             = name;
            Game.Settings.Server.ListenPort       = listenPort;
            Game.Settings.Server.ExternalPort     = externalPort;
            Game.Settings.Server.AdvertiseOnline  = advertiseOnline;
            Game.Settings.Server.AllowPortForward = allowPortForward;
            Game.Settings.Server.Map      = preview.Uid;
            Game.Settings.Server.Password = password;
            Game.Settings.Save();

            // Take a copy so that subsequent changes don't affect the server
            var settings = Game.Settings.Server.Clone();

            // Create and join the server
            try
            {
                Game.CreateServer(settings);
            }
            catch (System.Net.Sockets.SocketException e)
            {
                var message = "Could not listen on port {0}.".F(Game.Settings.Server.ListenPort);
                if (e.ErrorCode == 10048)                   // AddressAlreadyInUse (WSAEADDRINUSE)
                {
                    message += "\nCheck if the port is already being used.";
                }
                else
                {
                    message += "\nError is: \"{0}\" ({1})".F(e.Message, e.ErrorCode);
                }

                ConfirmationDialogs.ButtonPrompt("Server Creation Failed", message, onCancel: () => { }, cancelText: "Back");
                return;
            }

            ConnectionLogic.Connect(IPAddress.Loopback.ToString(), Game.Settings.Server.ListenPort, password, onCreate, onExit);
        }
Example #7
0
        void StartSkirmishGame()
        {
            var map = Game.ModData.MapCache.ChooseInitialMap(Game.Settings.Server.Map, Game.CosmeticRandom);

            Game.Settings.Server.Map = map;
            Game.Settings.Save();

            ConnectionLogic.Connect(Game.CreateLocalServer(map),
                                    "",
                                    OpenSkirmishLobbyPanel,
                                    () => { Game.CloseServer(); SwitchMenu(MenuType.Main); });
        }
Example #8
0
        void Join(GameServer server)
        {
            if (server == null || !server.IsJoinable)
            {
                return;
            }

            var host = server.Address.Split(':')[0];
            var port = Exts.ParseIntegerInvariant(server.Address.Split(':')[1]);

            ConnectionLogic.Connect(host, port, "", OpenLobby, DoNothing);
        }
Example #9
0
        void StartSkirmishGame()
        {
            var map = WidgetUtils.ChooseInitialMap(Game.Settings.Server.Map);

            Game.Settings.Server.Map = map;
            Game.Settings.Save();

            ConnectionLogic.Connect(IPAddress.Loopback.ToString(),
                                    Game.CreateLocalServer(map),
                                    "",
                                    OpenSkirmishLobbyPanel,
                                    () => { Game.CloseServer(); menuType = MenuType.Main; });
        }
        void CreateAndJoin()
        {
            var name = Game.Settings.SanitizedServerName(panel.Get <TextFieldWidget>("SERVER_NAME").Text);

            if (!Exts.TryParseIntegerInvariant(panel.Get <TextFieldWidget>("LISTEN_PORT").Text, out var listenPort))
            {
                listenPort = 1234;
            }

            var passwordField = panel.GetOrNull <PasswordFieldWidget>("PASSWORD");
            var password      = passwordField != null ? passwordField.Text : "";

            // Save new settings
            Game.Settings.Server.Name            = name;
            Game.Settings.Server.ListenPort      = listenPort;
            Game.Settings.Server.AdvertiseOnline = advertiseOnline;
            Game.Settings.Server.Map             = preview.Uid;
            Game.Settings.Server.Password        = password;
            Game.Settings.Save();

            // Take a copy so that subsequent changes don't affect the server
            var settings = Game.Settings.Server.Clone();

            // Create and join the server
            try
            {
                var endpoint = Game.CreateServer(settings);

                Ui.CloseWindow();
                ConnectionLogic.Connect(endpoint, password, onCreate, onExit);
            }
            catch (System.Net.Sockets.SocketException e)
            {
                var message = $"Could not listen on port {Game.Settings.Server.ListenPort}.";

                // AddressAlreadyInUse (WSAEADDRINUSE)
                if (e.ErrorCode == 10048)
                {
                    message += "\nCheck if the port is already being used.";
                }
                else
                {
                    message += $"\nError is: \"{e.Message}\" ({e.ErrorCode})";
                }

                ConfirmationDialogs.ButtonPrompt("Server Creation Failed", message, onCancel: () => { }, cancelText: "Back");
            }
        }
Example #11
0
        public DirectConnectLogic(Widget widget, Action onExit, Action openLobby, ConnectionTarget directConnectEndPoint)
        {
            var panel     = widget;
            var ipField   = panel.Get <TextFieldWidget>("IP");
            var portField = panel.Get <TextFieldWidget>("PORT");

            var text = Game.Settings.Player.LastServer;
            var last = text.LastIndexOf(':');

            if (last < 0)
            {
                ipField.Text   = "localhost";
                portField.Text = "1234";
            }
            else
            {
                ipField.Text   = text.Substring(0, last);
                portField.Text = text.Substring(last + 1);
            }

            panel.Get <ButtonWidget>("JOIN_BUTTON").OnClick = () =>
            {
                var port = Exts.WithDefault(1234, () => Exts.ParseIntegerInvariant(portField.Text));

                Game.Settings.Player.LastServer = "{0}:{1}".F(ipField.Text, port);
                Game.Settings.Save();

                ConnectionLogic.Connect(new ConnectionTarget(ipField.Text, port), "", () => { Ui.CloseWindow(); openLobby(); }, DoNothing);
            };

            panel.Get <ButtonWidget>("BACK_BUTTON").OnClick = () => { Ui.CloseWindow(); onExit(); };

            if (directConnectEndPoint != null)
            {
                // The connection window must be opened at the end of the tick for the widget hierarchy to
                // work out, but we also want to prevent the server browser from flashing visible for one tick.
                widget.Visible = false;
                Game.RunAfterTick(() =>
                {
                    ConnectionLogic.Connect(directConnectEndPoint, "", () => { Ui.CloseWindow(); openLobby(); }, DoNothing);
                    widget.Visible = true;
                });
            }
        }
Example #12
0
        void CreateAndJoin()
        {
            var name = panel.Get <TextFieldWidget>("SERVER_NAME").Text;
            int listenPort, externalPort;

            if (!Exts.TryParseIntegerInvariant(panel.Get <TextFieldWidget>("LISTEN_PORT").Text, out listenPort))
            {
                listenPort = 1234;
            }

            if (!Exts.TryParseIntegerInvariant(panel.Get <TextFieldWidget>("EXTERNAL_PORT").Text, out externalPort))
            {
                externalPort = 1234;
            }

            var passwordField = panel.GetOrNull <PasswordFieldWidget>("PASSWORD");
            var password      = passwordField != null ? passwordField.Text : "";

            // Save new settings
            Game.Settings.Server.Name             = name;
            Game.Settings.Server.ListenPort       = listenPort;
            Game.Settings.Server.ExternalPort     = externalPort;
            Game.Settings.Server.AdvertiseOnline  = advertiseOnline;
            Game.Settings.Server.AllowPortForward = allowPortForward;
            Game.Settings.Server.Map      = preview.Uid;
            Game.Settings.Server.Password = password;
            Game.Settings.Save();

            // Take a copy so that subsequent changes don't affect the server
            var settings = new ServerSettings(Game.Settings.Server);

            // Create and join the server
            Game.CreateServer(settings);
            Ui.CloseWindow();
            ConnectionLogic.Connect(IPAddress.Loopback.ToString(), Game.Settings.Server.ListenPort, password, onCreate, onExit);
        }
Example #13
0
        public DirectConnectLogic(Widget widget, Action onExit, Action openLobby)
        {
            var panel     = widget;
            var ipField   = panel.Get <TextFieldWidget>("IP");
            var portField = panel.Get <TextFieldWidget>("PORT");

            var last = Game.Settings.Player.LastServer.Split(':');

            ipField.Text   = last.Length > 1 ? last[0] : "localhost";
            portField.Text = last.Length == 2 ? last[1] : "1234";

            panel.Get <ButtonWidget>("JOIN_BUTTON").OnClick = () =>
            {
                var port = Exts.WithDefault(1234, () => Exts.ParseIntegerInvariant(portField.Text));

                Game.Settings.Player.LastServer = "{0}:{1}".F(ipField.Text, port);
                Game.Settings.Save();

                Ui.CloseWindow();
                ConnectionLogic.Connect(ipField.Text, port, "", openLobby, onExit);
            };

            panel.Get <ButtonWidget>("BACK_BUTTON").OnClick = () => { Ui.CloseWindow(); onExit(); };
        }
Example #14
0
        public ServerBrowserLogic(Widget widget, Action onStart, Action onExit, string directConnectHost, int directConnectPort)
        {
            panel        = widget;
            this.onStart = onStart;

            serverList     = panel.Get <ScrollPanelWidget>("SERVER_LIST");
            headerTemplate = serverList.Get <ScrollItemWidget>("HEADER_TEMPLATE");
            serverTemplate = serverList.Get <ScrollItemWidget>("SERVER_TEMPLATE");

            // Menu buttons
            var refreshButton = panel.Get <ButtonWidget>("REFRESH_BUTTON");

            refreshButton.IsDisabled = () => searchStatus == SearchStatus.Fetching;
            refreshButton.GetText    = () => searchStatus == SearchStatus.Fetching ? "Refreshing..." : "Refresh";
            refreshButton.OnClick    = RefreshServerList;

            panel.Get <ButtonWidget>("DIRECTCONNECT_BUTTON").OnClick = OpenDirectConnectPanel;
            panel.Get <ButtonWidget>("CREATE_BUTTON").OnClick        = OpenCreateServerPanel;

            var join = panel.Get <ButtonWidget>("JOIN_BUTTON");

            join.IsDisabled = () => currentServer == null || !currentServer.IsJoinable;
            join.OnClick    = () => Join(currentServer);

            panel.Get <ButtonWidget>("BACK_BUTTON").OnClick = () => { Ui.CloseWindow(); onExit(); };

            // Display the progress label over the server list
            // The text is only visible when the list is empty
            var progressText = panel.Get <LabelWidget>("PROGRESS_LABEL");

            progressText.IsVisible = () => searchStatus != SearchStatus.Hidden;
            progressText.GetText   = ProgressLabelText;

            var showWaitingCheckbox = panel.GetOrNull <CheckboxWidget>("WAITING_FOR_PLAYERS");

            if (showWaitingCheckbox != null)
            {
                showWaitingCheckbox.IsChecked = () => showWaiting;
                showWaitingCheckbox.OnClick   = () => { showWaiting ^= true; RefreshServerList(); };
            }

            var showEmptyCheckbox = panel.GetOrNull <CheckboxWidget>("EMPTY");

            if (showEmptyCheckbox != null)
            {
                showEmptyCheckbox.IsChecked = () => showEmpty;
                showEmptyCheckbox.OnClick   = () => { showEmpty ^= true; RefreshServerList(); };
            }

            var showAlreadyStartedCheckbox = panel.GetOrNull <CheckboxWidget>("ALREADY_STARTED");

            if (showAlreadyStartedCheckbox != null)
            {
                showAlreadyStartedCheckbox.IsChecked = () => showStarted;
                showAlreadyStartedCheckbox.OnClick   = () => { showStarted ^= true; RefreshServerList(); };
            }

            var showProtectedCheckbox = panel.GetOrNull <CheckboxWidget>("PASSWORD_PROTECTED");

            if (showProtectedCheckbox != null)
            {
                showProtectedCheckbox.IsChecked = () => showProtected;
                showProtectedCheckbox.OnClick   = () => { showProtected ^= true; RefreshServerList(); };
            }

            var showIncompatibleCheckbox = panel.GetOrNull <CheckboxWidget>("INCOMPATIBLE_VERSION");

            if (showIncompatibleCheckbox != null)
            {
                showIncompatibleCheckbox.IsChecked = () => showIncompatible;
                showIncompatibleCheckbox.OnClick   = () => { showIncompatible ^= true; RefreshServerList(); };
            }

            RefreshServerList();

            if (directConnectHost != null)
            {
                // The connection window must be opened at the end of the tick for the widget hierarchy to
                // work out, but we also want to prevent the server browser from flashing visible for one tick.
                widget.Visible = false;
                Game.RunAfterTick(() =>
                {
                    ConnectionLogic.Connect(directConnectHost, directConnectPort, "", OpenLobby, DoNothing);
                    widget.Visible = true;
                });
            }
        }
Example #15
0
        public MultiplayerLogic(Widget widget, ModData modData, Action onStart, Action onExit, string directConnectHost, int directConnectPort)
        {
            this.modData = modData;
            this.onStart = onStart;
            this.onExit  = onExit;

            services = modData.Manifest.Get <WebServices>();

            incompatibleVersionColor       = ChromeMetrics.Get <Color>("IncompatibleVersionColor");
            incompatibleGameColor          = ChromeMetrics.Get <Color>("IncompatibleGameColor");
            incompatibleProtectedGameColor = ChromeMetrics.Get <Color>("IncompatibleProtectedGameColor");
            protectedGameColor             = ChromeMetrics.Get <Color>("ProtectedGameColor");
            waitingGameColor             = ChromeMetrics.Get <Color>("WaitingGameColor");
            incompatibleWaitingGameColor = ChromeMetrics.Get <Color>("IncompatibleWaitingGameColor");
            gameStartedColor             = ChromeMetrics.Get <Color>("GameStartedColor");
            incompatibleGameStartedColor = ChromeMetrics.Get <Color>("IncompatibleGameStartedColor");

            LoadBrowserPanel(widget);
            LoadDirectConnectPanel(widget);
            LoadCreateServerPanel(widget);

            // Filter and refresh buttons act on the browser panel,
            // but remain visible (disabled) on the other panels
            var refreshButton = widget.Get <ButtonWidget>("REFRESH_BUTTON");

            refreshButton.IsDisabled = () => searchStatus == SearchStatus.Fetching || panel != PanelType.Browser;

            var filtersButton = widget.Get <DropDownButtonWidget>("FILTERS_DROPDOWNBUTTON");

            filtersButton.IsDisabled = () => searchStatus == SearchStatus.Fetching || panel != PanelType.Browser;

            var browserTab = widget.Get <ButtonWidget>("BROWSER_TAB");

            browserTab.IsHighlighted = () => panel == PanelType.Browser;
            browserTab.OnClick       = () => panel = PanelType.Browser;

            var directConnectTab = widget.Get <ButtonWidget>("DIRECTCONNECT_TAB");

            directConnectTab.IsHighlighted = () => panel == PanelType.DirectConnect;
            directConnectTab.OnClick       = () => panel = PanelType.DirectConnect;

            var createServerTab = widget.Get <ButtonWidget>("CREATE_TAB");

            createServerTab.IsHighlighted = () => panel == PanelType.CreateServer;
            createServerTab.OnClick       = () => panel = PanelType.CreateServer;

            widget.Get <ButtonWidget>("BACK_BUTTON").OnClick = () => { Ui.CloseWindow(); onExit(); };

            lanGameLocations = new List <BeaconLocation>();
            try
            {
                lanGameProbe = new Probe("OpenRALANGame");
                lanGameProbe.BeaconsUpdated += locations => lanGameLocations = locations;
                lanGameProbe.Start();
            }
            catch (Exception ex)
            {
                Log.Write("debug", "BeaconLib.Probe: " + ex.Message);
            }

            RefreshServerList();

            if (directConnectHost != null)
            {
                // The connection window must be opened at the end of the tick for the widget hierarchy to
                // work out, but we also want to prevent the server browser from flashing visible for one tick.
                widget.Visible = false;
                Game.RunAfterTick(() =>
                {
                    ConnectionLogic.Connect(directConnectHost, directConnectPort, "", OpenLobby, DoNothing);
                    widget.Visible = true;
                });
            }
        }
Example #16
0
        public NewMapWithTileSelectionLogic(Action onExit, Action <string> onSelect, Widget widget, World world, ModData modData)
        {
            panel = widget;

            panel.Get <ButtonWidget>("CANCEL_BUTTON").OnClick = () => { Ui.CloseWindow(); onExit(); };

            var tileDropDown = panel.Get <DropDownButtonWidget>("TILE");

            var tileset = modData.DefaultTileSets.First().Value;

            var clearTiles = tileset.Templates.Where(t => t.Value.PickAny)
                             .Select(t => (Type: t.Value.Id, Description: t.Value.Categories.First()));

            Func <string, ScrollItemWidget, ScrollItemWidget> setupItem = (option, template) =>
            {
                var item = ScrollItemWidget.Setup(template,
                                                  () => tileDropDown.Text == option,
                                                  () => { tileDropDown.Text = option; });
                item.Get <LabelWidget>("LABEL").GetText = () => option;
                return(item);
            };

            tileDropDown.Text = clearTiles.First().Description;
            var options = clearTiles.Select(t => t.Description);

            tileDropDown.OnClick = () =>
                                   tileDropDown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 210, options, setupItem);

            var widthTextField  = panel.Get <TextFieldWidget>("WIDTH");
            var heightTextField = panel.Get <TextFieldWidget>("HEIGHT");

            panel.Get <ButtonWidget>("CREATE_BUTTON").OnClick = () =>
            {
                int.TryParse(widthTextField.Text, out int width);
                int.TryParse(heightTextField.Text, out int height);

                // Require at least a 2x2 playable area so that the
                // ground is visible through the edge shroud
                width  = Math.Max(2, width);
                height = Math.Max(2, height);

                var maxTerrainHeight = world.Map.Grid.MaximumTerrainHeight;
                var map = new Map(Game.ModData, tileset, width + 2, height + maxTerrainHeight + 2);

                var tl = new PPos(1, 1 + maxTerrainHeight);
                var br = new PPos(width, height + maxTerrainHeight);
                map.SetBounds(tl, br);

                var type = clearTiles.First(c => c.Description == tileDropDown.Text).Type;
                for (var j = map.Bounds.Top; j < map.Bounds.Bottom; j++)
                {
                    for (var i = map.Bounds.Left; i < map.Bounds.Right; i++)
                    {
                        var template = tileset.Templates[type];
                        map.Tiles[new MPos(i, j)] = new TerrainTile(type, 0);
                    }
                }

                map.PlayerDefinitions = new MapPlayers(map.Rules, 0).ToMiniYaml();
                map.FixOpenAreas();

                Action <string> afterSave = uid =>
                {
                    // HACK: Work around a synced-code change check.
                    // It's not clear why this is needed here, but not in the other places that load maps.
                    Game.RunAfterTick(() =>
                    {
                        ConnectionLogic.Connect(Game.CreateLocalServer(uid), "",
                                                () => Game.LoadEditor(uid),
                                                () => { Game.CloseServer(); onExit(); });
                    });

                    Ui.CloseWindow();
                    onSelect(uid);
                };

                Ui.OpenWindow("SAVE_MAP_PANEL", new WidgetArgs()
                {
                    { "onSave", afterSave },
                    { "onExit", () => { Ui.CloseWindow(); onExit(); } },
                    { "map", map },
                    { "playerDefinitions", map.PlayerDefinitions },
                    { "actorDefinitions", map.ActorDefinitions }
                });
            };
        }
Example #17
0
        public MainMenuLogic(Widget widget, World world)
        {
            rootMenu = widget;
            rootMenu.Get <LabelWidget>("VERSION_LABEL").Text = Game.ModData.Manifest.Mod.Version;

            // Menu buttons
            var mainMenu = widget.Get("MAIN_MENU");

            mainMenu.IsVisible = () => menuType == MenuType.Main;

            mainMenu.Get <ButtonWidget>("SINGLEPLAYER_BUTTON").OnClick = () => menuType = MenuType.Singleplayer;

            mainMenu.Get <ButtonWidget>("MULTIPLAYER_BUTTON").OnClick = () =>
            {
                menuType = MenuType.None;
                Ui.OpenWindow("SERVERBROWSER_PANEL", new WidgetArgs
                {
                    { "onStart", RemoveShellmapUI },
                    { "onExit", () => menuType = MenuType.Main },
                    { "directConnectHost", null },
                    { "directConnectPort", 0 },
                });
            };

            mainMenu.Get <ButtonWidget>("MODS_BUTTON").OnClick = () =>
            {
                Game.Settings.Game.PreviousMod = Game.ModData.Manifest.Mod.Id;
                Game.InitializeMod("modchooser", null);
            };

            mainMenu.Get <ButtonWidget>("SETTINGS_BUTTON").OnClick = () =>
            {
                menuType = MenuType.None;
                Game.OpenWindow("SETTINGS_PANEL", new WidgetArgs
                {
                    { "onExit", () => menuType = MenuType.Main }
                });
            };

            mainMenu.Get <ButtonWidget>("EXTRAS_BUTTON").OnClick = () => menuType = MenuType.Extras;

            mainMenu.Get <ButtonWidget>("QUIT_BUTTON").OnClick = Game.Exit;

            // Singleplayer menu
            var singleplayerMenu = widget.Get("SINGLEPLAYER_MENU");

            singleplayerMenu.IsVisible = () => menuType == MenuType.Singleplayer;

            var missionsButton = singleplayerMenu.Get <ButtonWidget>("MISSIONS_BUTTON");

            missionsButton.OnClick = () =>
            {
                menuType = MenuType.None;
                Game.OpenWindow("MISSIONBROWSER_PANEL", new WidgetArgs
                {
                    { "onExit", () => menuType = MenuType.Singleplayer },
                    { "onStart", RemoveShellmapUI }
                });
            };

            var hasCampaign = Game.ModData.Manifest.Missions.Any();
            var hasMissions = Game.ModData.MapCache
                              .Any(p => p.Status == MapStatus.Available && p.Map.Visibility.HasFlag(MapVisibility.MissionSelector));

            missionsButton.Disabled = !hasCampaign && !hasMissions;

            singleplayerMenu.Get <ButtonWidget>("SKIRMISH_BUTTON").OnClick = StartSkirmishGame;

            singleplayerMenu.Get <ButtonWidget>("BACK_BUTTON").OnClick = () => menuType = MenuType.Main;

            // Extras menu
            var extrasMenu = widget.Get("EXTRAS_MENU");

            extrasMenu.IsVisible = () => menuType == MenuType.Extras;

            extrasMenu.Get <ButtonWidget>("REPLAYS_BUTTON").OnClick = () =>
            {
                menuType = MenuType.None;
                Ui.OpenWindow("REPLAYBROWSER_PANEL", new WidgetArgs
                {
                    { "onExit", () => menuType = MenuType.Extras },
                    { "onStart", RemoveShellmapUI }
                });
            };

            extrasMenu.Get <ButtonWidget>("MUSIC_BUTTON").OnClick = () =>
            {
                menuType = MenuType.None;
                Ui.OpenWindow("MUSIC_PANEL", new WidgetArgs
                {
                    { "onExit", () => menuType = MenuType.Extras },
                    { "world", world }
                });
            };

            extrasMenu.Get <ButtonWidget>("MAP_EDITOR_BUTTON").OnClick = () => menuType = MenuType.MapEditor;

            var assetBrowserButton = extrasMenu.GetOrNull <ButtonWidget>("ASSETBROWSER_BUTTON");

            if (assetBrowserButton != null)
            {
                assetBrowserButton.OnClick = () =>
                {
                    menuType = MenuType.None;
                    Game.OpenWindow("ASSETBROWSER_PANEL", new WidgetArgs
                    {
                        { "onExit", () => menuType = MenuType.Extras },
                    });
                }
            }
            ;

            extrasMenu.Get <ButtonWidget>("CREDITS_BUTTON").OnClick = () =>
            {
                menuType = MenuType.None;
                Ui.OpenWindow("CREDITS_PANEL", new WidgetArgs
                {
                    { "onExit", () => menuType = MenuType.Extras },
                });
            };

            extrasMenu.Get <ButtonWidget>("BACK_BUTTON").OnClick = () => menuType = MenuType.Main;

            // Map editor menu
            var mapEditorMenu = widget.Get("MAP_EDITOR_MENU");

            mapEditorMenu.IsVisible = () => menuType == MenuType.MapEditor;

            var onSelect = new Action <string>(uid =>
            {
                RemoveShellmapUI();
                LoadMapIntoEditor(Game.ModData.MapCache[uid].Map);
            });

            var newMapButton = widget.Get <ButtonWidget>("NEW_MAP_BUTTON");

            newMapButton.OnClick = () =>
            {
                menuType = MenuType.None;
                Game.OpenWindow("NEW_MAP_BG", new WidgetArgs()
                {
                    { "onSelect", onSelect },
                    { "onExit", () => menuType = MenuType.MapEditor }
                });
            };

            var loadMapButton = widget.Get <ButtonWidget>("LOAD_MAP_BUTTON");

            loadMapButton.OnClick = () =>
            {
                menuType = MenuType.None;
                Game.OpenWindow("MAPCHOOSER_PANEL", new WidgetArgs()
                {
                    { "initialMap", null },
                    { "initialTab", MapClassification.User },
                    { "onExit", () => menuType = MenuType.MapEditor },
                    { "onSelect", onSelect },
                    { "filter", MapVisibility.Lobby | MapVisibility.Shellmap | MapVisibility.MissionSelector },
                });
            };

            mapEditorMenu.Get <ButtonWidget>("BACK_BUTTON").OnClick = () => menuType = MenuType.Extras;

            var newsBG = widget.GetOrNull("NEWS_BG");

            if (newsBG != null)
            {
                newsBG.IsVisible = () => Game.Settings.Game.FetchNews && menuType != MenuType.None;

                newsPanel    = Ui.LoadWidget <ScrollPanelWidget>("NEWS_PANEL", null, new WidgetArgs());
                newsTemplate = newsPanel.Get("NEWS_ITEM_TEMPLATE");
                newsPanel.RemoveChild(newsTemplate);

                newsStatus = newsPanel.Get <LabelWidget>("NEWS_STATUS");
                SetNewsStatus("Loading news");

                var cacheFile   = Platform.ResolvePath("^", "news.yaml");
                var currentNews = ParseNews(cacheFile);
                if (currentNews != null)
                {
                    DisplayNews(currentNews);
                }

                // Only query for new stories once per day
                var cacheValid = currentNews != null && DateTime.Today.ToUniversalTime() <= Game.Settings.Game.NewsFetchedDate;
                if (!cacheValid)
                {
                    new Download(Game.Settings.Game.NewsUrl, cacheFile, e => { }, (e, c) => NewsDownloadComplete(e, c, cacheFile, currentNews));
                }

                var newsButton = newsBG.GetOrNull <DropDownButtonWidget>("NEWS_BUTTON");
                newsButton.OnClick = () =>
                {
                    newsButton.AttachPanel(newsPanel);
                    newsHighlighted = false;
                };

                newsButton.IsHighlighted = () => newsHighlighted && Game.LocalTick % 50 < 25;
            }

            Game.OnRemoteDirectConnect += (host, port) =>
            {
                menuType = MenuType.None;
                Ui.OpenWindow("SERVERBROWSER_PANEL", new WidgetArgs
                {
                    { "onStart", RemoveShellmapUI },
                    { "onExit", () => menuType = MenuType.Main },
                    { "directConnectHost", host },
                    { "directConnectPort", port },
                });
            };
        }

        void LoadMapIntoEditor(Map map)
        {
            ConnectionLogic.Connect(System.Net.IPAddress.Loopback.ToString(),
                                    Game.CreateLocalServer(map.Uid),
                                    "",
                                    () => { Game.LoadEditor(map.Uid); },
                                    () => { Game.CloseServer(); menuType = MenuType.MapEditor; });
        }

        void SetNewsStatus(string message)
        {
            message            = WidgetUtils.WrapText(message, newsStatus.Bounds.Width, Game.Renderer.Fonts[newsStatus.Font]);
            newsStatus.GetText = () => message;
        }
Example #18
0
        public NewMapLogic(Action onExit, Action <string> onSelect, Widget widget, World world, ModData modData)
        {
            panel = widget;

            panel.Get <ButtonWidget>("CANCEL_BUTTON").OnClick = () => { Ui.CloseWindow(); onExit(); };

            var tilesetDropDown = panel.Get <DropDownButtonWidget>("TILESET");
            var tilesets        = modData.DefaultTileSets.Select(t => t.Key).ToList();
            Func <string, ScrollItemWidget, ScrollItemWidget> setupItem = (option, template) =>
            {
                var item = ScrollItemWidget.Setup(template,
                                                  () => tilesetDropDown.Text == option,
                                                  () => { tilesetDropDown.Text = option; });
                item.Get <LabelWidget>("LABEL").GetText = () => option;
                return(item);
            };

            tilesetDropDown.Text    = tilesets.First();
            tilesetDropDown.OnClick = () =>
                                      tilesetDropDown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 210, tilesets, setupItem);

            var widthTextField  = panel.Get <TextFieldWidget>("WIDTH");
            var heightTextField = panel.Get <TextFieldWidget>("HEIGHT");

            panel.Get <ButtonWidget>("CREATE_BUTTON").OnClick = () =>
            {
                int width, height;
                int.TryParse(widthTextField.Text, out width);
                int.TryParse(heightTextField.Text, out height);

                // Require at least a 2x2 playable area so that the
                // ground is visible through the edge shroud
                width  = Math.Max(2, width);
                height = Math.Max(2, height);

                var maxTerrainHeight = world.Map.Grid.MaximumTerrainHeight;
                var tileset          = modData.DefaultTileSets[tilesetDropDown.Text];
                var map = new Map(Game.ModData, tileset, width + 2, height + maxTerrainHeight + 2);

                var tl = new PPos(1, 1 + maxTerrainHeight);
                var br = new PPos(width, height + maxTerrainHeight);
                map.SetBounds(tl, br);

                map.PlayerDefinitions = new MapPlayers(map.Rules, 0).ToMiniYaml();
                map.FixOpenAreas();

                Action <string> afterSave = uid =>
                {
                    // HACK: Work around a synced-code change check.
                    // It's not clear why this is needed here, but not in the other places that load maps.
                    Game.RunAfterTick(() =>
                    {
                        ConnectionLogic.Connect(System.Net.IPAddress.Loopback.ToString(),
                                                Game.CreateLocalServer(uid), "",
                                                () => Game.LoadEditor(uid),
                                                () => { Game.CloseServer(); onExit(); });
                    });

                    Ui.CloseWindow();
                    onSelect(uid);
                };

                Ui.OpenWindow("SAVE_MAP_PANEL", new WidgetArgs()
                {
                    { "onSave", afterSave },
                    { "onExit", () => { Ui.CloseWindow(); onExit(); } },
                    { "map", map },
                    { "playerDefinitions", map.PlayerDefinitions },
                    { "actorDefinitions", map.ActorDefinitions }
                });
            };
        }
Example #19
0
        public MainMenuLogic(Widget widget, World world, ModData modData)
        {
            rootMenu = widget;
            rootMenu.Get <LabelWidget>("VERSION_LABEL").Text = modData.Manifest.Metadata.Version;

            // Menu buttons
            var mainMenu = widget.Get("MAIN_MENU");

            mainMenu.IsVisible = () => menuType == MenuType.Main;

            mainMenu.Get <ButtonWidget>("SINGLEPLAYER_BUTTON").OnClick = () => SwitchMenu(MenuType.Singleplayer);

            mainMenu.Get <ButtonWidget>("MULTIPLAYER_BUTTON").OnClick = OpenMultiplayerPanel;

            mainMenu.Get <ButtonWidget>("CONTENT_BUTTON").OnClick = () =>
            {
                // Switching mods changes the world state (by disposing it),
                // so we can't do this inside the input handler.
                Game.RunAfterTick(() =>
                {
                    var content = modData.Manifest.Get <ModContent>();
                    Game.InitializeMod(content.ContentInstallerMod, new Arguments(new[] { "Content.Mod=" + modData.Manifest.Id }));
                });
            };

            mainMenu.Get <ButtonWidget>("SETTINGS_BUTTON").OnClick = () =>
            {
                SwitchMenu(MenuType.None);
                Game.OpenWindow("SETTINGS_PANEL", new WidgetArgs
                {
                    { "onExit", () => SwitchMenu(MenuType.Main) }
                });
            };

            mainMenu.Get <ButtonWidget>("EXTRAS_BUTTON").OnClick = () => SwitchMenu(MenuType.Extras);

            mainMenu.Get <ButtonWidget>("QUIT_BUTTON").OnClick = Game.Exit;

            // Singleplayer menu
            var singleplayerMenu = widget.Get("SINGLEPLAYER_MENU");

            singleplayerMenu.IsVisible = () => menuType == MenuType.Singleplayer;

            var missionsButton = singleplayerMenu.Get <ButtonWidget>("MISSIONS_BUTTON");

            missionsButton.OnClick = OpenMissionBrowserPanel;

            var hasCampaign = modData.Manifest.Missions.Any();
            var hasMissions = modData.MapCache
                              .Any(p => p.Status == MapStatus.Available && p.Visibility.HasFlag(MapVisibility.MissionSelector));

            missionsButton.Disabled = !hasCampaign && !hasMissions;

            var hasMaps        = modData.MapCache.Any(p => p.Visibility.HasFlag(MapVisibility.Lobby));
            var skirmishButton = singleplayerMenu.Get <ButtonWidget>("SKIRMISH_BUTTON");

            skirmishButton.OnClick  = StartSkirmishGame;
            skirmishButton.Disabled = !hasMaps;

            var loadButton = singleplayerMenu.Get <ButtonWidget>("LOAD_BUTTON");

            loadButton.IsDisabled = () => !GameSaveBrowserLogic.IsLoadPanelEnabled(modData.Manifest);
            loadButton.OnClick    = OpenGameSaveBrowserPanel;

            singleplayerMenu.Get <ButtonWidget>("BACK_BUTTON").OnClick = () => SwitchMenu(MenuType.Main);

            // Extras menu
            var extrasMenu = widget.Get("EXTRAS_MENU");

            extrasMenu.IsVisible = () => menuType == MenuType.Extras;

            extrasMenu.Get <ButtonWidget>("REPLAYS_BUTTON").OnClick = OpenReplayBrowserPanel;

            extrasMenu.Get <ButtonWidget>("MUSIC_BUTTON").OnClick = () =>
            {
                SwitchMenu(MenuType.None);
                Ui.OpenWindow("MUSIC_PANEL", new WidgetArgs
                {
                    { "onExit", () => SwitchMenu(MenuType.Extras) },
                    { "world", world }
                });
            };

            extrasMenu.Get <ButtonWidget>("MAP_EDITOR_BUTTON").OnClick = () => SwitchMenu(MenuType.MapEditor);

            var assetBrowserButton = extrasMenu.GetOrNull <ButtonWidget>("ASSETBROWSER_BUTTON");

            if (assetBrowserButton != null)
            {
                assetBrowserButton.OnClick = () =>
                {
                    SwitchMenu(MenuType.None);
                    Game.OpenWindow("ASSETBROWSER_PANEL", new WidgetArgs
                    {
                        { "onExit", () => SwitchMenu(MenuType.Extras) },
                    });
                }
            }
            ;

            extrasMenu.Get <ButtonWidget>("CREDITS_BUTTON").OnClick = () =>
            {
                SwitchMenu(MenuType.None);
                Ui.OpenWindow("CREDITS_PANEL", new WidgetArgs
                {
                    { "onExit", () => SwitchMenu(MenuType.Extras) },
                });
            };

            extrasMenu.Get <ButtonWidget>("BACK_BUTTON").OnClick = () => SwitchMenu(MenuType.Main);

            // Map editor menu
            var mapEditorMenu = widget.Get("MAP_EDITOR_MENU");

            mapEditorMenu.IsVisible = () => menuType == MenuType.MapEditor;

            // Loading into the map editor
            Game.BeforeGameStart += RemoveShellmapUI;

            var onSelect = new Action <string>(uid => LoadMapIntoEditor(modData.MapCache[uid].Uid));

            var newMapButton = widget.Get <ButtonWidget>("NEW_MAP_BUTTON");

            newMapButton.OnClick = () =>
            {
                SwitchMenu(MenuType.None);
                Game.OpenWindow("NEW_MAP_BG", new WidgetArgs()
                {
                    { "onSelect", onSelect },
                    { "onExit", () => SwitchMenu(MenuType.MapEditor) }
                });
            };

            var loadMapButton = widget.Get <ButtonWidget>("LOAD_MAP_BUTTON");

            loadMapButton.OnClick = () =>
            {
                SwitchMenu(MenuType.None);
                Game.OpenWindow("MAPCHOOSER_PANEL", new WidgetArgs()
                {
                    { "initialMap", null },
                    { "initialTab", MapClassification.User },
                    { "onExit", () => SwitchMenu(MenuType.MapEditor) },
                    { "onSelect", onSelect },
                    { "filter", MapVisibility.Lobby | MapVisibility.Shellmap | MapVisibility.MissionSelector },
                });
            };

            loadMapButton.Disabled = !hasMaps;

            mapEditorMenu.Get <ButtonWidget>("BACK_BUTTON").OnClick = () => SwitchMenu(MenuType.Extras);

            var newsBG = widget.GetOrNull("NEWS_BG");

            if (newsBG != null)
            {
                newsBG.IsVisible = () => Game.Settings.Game.FetchNews && menuType != MenuType.None && menuType != MenuType.StartupPrompts;

                newsPanel    = Ui.LoadWidget <ScrollPanelWidget>("NEWS_PANEL", null, new WidgetArgs());
                newsTemplate = newsPanel.Get("NEWS_ITEM_TEMPLATE");
                newsPanel.RemoveChild(newsTemplate);

                newsStatus = newsPanel.Get <LabelWidget>("NEWS_STATUS");
                SetNewsStatus("Loading news");
            }

            Game.OnRemoteDirectConnect += OnRemoteDirectConnect;

            // Check for updates in the background
            var webServices = modData.Manifest.Get <WebServices>();

            if (Game.Settings.Debug.CheckVersion)
            {
                webServices.CheckModVersion();
            }

            var updateLabel = rootMenu.GetOrNull("UPDATE_NOTICE");

            if (updateLabel != null)
            {
                updateLabel.IsVisible = () => !newsOpen && menuType != MenuType.None &&
                                        menuType != MenuType.StartupPrompts &&
                                        webServices.ModVersionStatus == ModVersionStatus.Outdated;
            }

            var playerProfile = widget.GetOrNull("PLAYER_PROFILE_CONTAINER");

            if (playerProfile != null)
            {
                Func <bool> minimalProfile = () => Ui.CurrentWindow() != null;
                Game.LoadWidget(world, "LOCAL_PROFILE_PANEL", playerProfile, new WidgetArgs()
                {
                    { "minimalProfile", minimalProfile }
                });
            }

            menuType = MenuType.StartupPrompts;

            Action onIntroductionComplete = () =>
            {
                Action onSysInfoComplete = () =>
                {
                    LoadAndDisplayNews(webServices.GameNews, newsBG);
                    SwitchMenu(MenuType.Main);
                };

                if (SystemInfoPromptLogic.ShouldShowPrompt())
                {
                    Ui.OpenWindow("MAINMENU_SYSTEM_INFO_PROMPT", new WidgetArgs
                    {
                        { "onComplete", onSysInfoComplete }
                    });
                }
                else
                {
                    onSysInfoComplete();
                }
            };

            if (IntroductionPromptLogic.ShouldShowPrompt())
            {
                Game.OpenWindow("MAINMENU_INTRODUCTION_PROMPT", new WidgetArgs
                {
                    { "onComplete", onIntroductionComplete }
                });
            }
            else
            {
                onIntroductionComplete();
            }

            Game.OnShellmapLoaded += OpenMenuBasedOnLastGame;
        }

        void LoadAndDisplayNews(string newsURL, Widget newsBG)
        {
            if (newsBG != null && Game.Settings.Game.FetchNews)
            {
                var cacheFile   = Platform.ResolvePath(Platform.SupportDirPrefix, "news.yaml");
                var currentNews = ParseNews(cacheFile);
                if (currentNews != null)
                {
                    DisplayNews(currentNews);
                }

                var newsButton = newsBG.GetOrNull <DropDownButtonWidget>("NEWS_BUTTON");
                if (newsButton != null)
                {
                    if (!fetchedNews)
                    {
                        // Send the mod and engine version to support version-filtered news (update prompts)
                        newsURL += "?version={0}&mod={1}&modversion={2}".F(
                            Uri.EscapeUriString(Game.EngineVersion),
                            Uri.EscapeUriString(Game.ModData.Manifest.Id),
                            Uri.EscapeUriString(Game.ModData.Manifest.Metadata.Version));

                        // Parameter string is blank if the player has opted out
                        newsURL += SystemInfoPromptLogic.CreateParameterString();

                        new Download(newsURL, cacheFile, e => { },
                                     e => NewsDownloadComplete(e, cacheFile, currentNews,
                                                               () => OpenNewsPanel(newsButton)));
                    }

                    newsButton.OnClick = () => OpenNewsPanel(newsButton);
                }
            }
        }

        void OpenNewsPanel(DropDownButtonWidget button)
        {
            newsOpen = true;
            button.AttachPanel(newsPanel, () => newsOpen = false);
        }

        void OnRemoteDirectConnect(ConnectionTarget endpoint)
        {
            SwitchMenu(MenuType.None);
            Ui.OpenWindow("MULTIPLAYER_PANEL", new WidgetArgs
            {
                { "onStart", RemoveShellmapUI },
                { "onExit", () => SwitchMenu(MenuType.Main) },
                { "directConnectEndPoint", endpoint },
            });
        }

        void LoadMapIntoEditor(string uid)
        {
            ConnectionLogic.Connect(Game.CreateLocalServer(uid),
                                    "",
                                    () => { Game.LoadEditor(uid); },
                                    () => { Game.CloseServer(); SwitchMenu(MenuType.MapEditor); });

            lastGameState = MenuPanel.MapEditor;
        }

        void SetNewsStatus(string message)
        {
            message            = WidgetUtils.WrapText(message, newsStatus.Bounds.Width, Game.Renderer.Fonts[newsStatus.Font]);
            newsStatus.GetText = () => message;
        }
Example #20
0
        public MainMenuLogic(Widget widget, World world, ModData modData)
        {
            rootMenu = widget;
            rootMenu.Get <LabelWidget>("VERSION_LABEL").Text = modData.Manifest.Metadata.Version;

            // Menu buttons
            var mainMenu = widget.Get("MAIN_MENU");

            mainMenu.IsVisible = () => menuType == MenuType.Main;

            mainMenu.Get <ButtonWidget>("SINGLEPLAYER_BUTTON").OnClick = () => SwitchMenu(MenuType.Singleplayer);

            mainMenu.Get <ButtonWidget>("MULTIPLAYER_BUTTON").OnClick = () =>
            {
                SwitchMenu(MenuType.None);
                Ui.OpenWindow("MULTIPLAYER_PANEL", new WidgetArgs
                {
                    { "onStart", RemoveShellmapUI },
                    { "onExit", () => SwitchMenu(MenuType.Main) },
                    { "directConnectHost", null },
                    { "directConnectPort", 0 },
                });
            };

            mainMenu.Get <ButtonWidget>("CONTENT_BUTTON").OnClick = () =>
            {
                // Switching mods changes the world state (by disposing it),
                // so we can't do this inside the input handler.
                Game.RunAfterTick(() =>
                {
                    Game.InitializeMod("modcontent", new Arguments(new[] { "Content.Mod=" + modData.Manifest.Id }));
                });
            };

            mainMenu.Get <ButtonWidget>("SETTINGS_BUTTON").OnClick = () =>
            {
                SwitchMenu(MenuType.None);
                Game.OpenWindow("SETTINGS_PANEL", new WidgetArgs
                {
                    { "onExit", () => SwitchMenu(MenuType.Main) }
                });
            };

            mainMenu.Get <ButtonWidget>("EXTRAS_BUTTON").OnClick = () => SwitchMenu(MenuType.Extras);

            mainMenu.Get <ButtonWidget>("QUIT_BUTTON").OnClick = Game.Exit;

            // Singleplayer menu
            var singleplayerMenu = widget.Get("SINGLEPLAYER_MENU");

            singleplayerMenu.IsVisible = () => menuType == MenuType.Singleplayer;

            var missionsButton = singleplayerMenu.Get <ButtonWidget>("MISSIONS_BUTTON");

            missionsButton.OnClick = () =>
            {
                SwitchMenu(MenuType.None);
                Game.OpenWindow("MISSIONBROWSER_PANEL", new WidgetArgs
                {
                    { "onExit", () => SwitchMenu(MenuType.Singleplayer) },
                    { "onStart", RemoveShellmapUI }
                });
            };

            var hasCampaign = modData.Manifest.Missions.Any();
            var hasMissions = modData.MapCache
                              .Any(p => p.Status == MapStatus.Available && p.Visibility.HasFlag(MapVisibility.MissionSelector));

            missionsButton.Disabled = !hasCampaign && !hasMissions;

            singleplayerMenu.Get <ButtonWidget>("SKIRMISH_BUTTON").OnClick = StartSkirmishGame;

            singleplayerMenu.Get <ButtonWidget>("BACK_BUTTON").OnClick = () => SwitchMenu(MenuType.Main);

            // Extras menu
            var extrasMenu = widget.Get("EXTRAS_MENU");

            extrasMenu.IsVisible = () => menuType == MenuType.Extras;

            extrasMenu.Get <ButtonWidget>("REPLAYS_BUTTON").OnClick = () =>
            {
                SwitchMenu(MenuType.None);
                Ui.OpenWindow("REPLAYBROWSER_PANEL", new WidgetArgs
                {
                    { "onExit", () => SwitchMenu(MenuType.Extras) },
                    { "onStart", RemoveShellmapUI }
                });
            };

            extrasMenu.Get <ButtonWidget>("MUSIC_BUTTON").OnClick = () =>
            {
                SwitchMenu(MenuType.None);
                Ui.OpenWindow("MUSIC_PANEL", new WidgetArgs
                {
                    { "onExit", () => SwitchMenu(MenuType.Extras) },
                    { "world", world }
                });
            };

            extrasMenu.Get <ButtonWidget>("MAP_EDITOR_BUTTON").OnClick = () => SwitchMenu(MenuType.MapEditor);

            var assetBrowserButton = extrasMenu.GetOrNull <ButtonWidget>("ASSETBROWSER_BUTTON");

            if (assetBrowserButton != null)
            {
                assetBrowserButton.OnClick = () =>
                {
                    SwitchMenu(MenuType.None);
                    Game.OpenWindow("ASSETBROWSER_PANEL", new WidgetArgs
                    {
                        { "onExit", () => SwitchMenu(MenuType.Extras) },
                    });
                }
            }
            ;

            extrasMenu.Get <ButtonWidget>("CREDITS_BUTTON").OnClick = () =>
            {
                SwitchMenu(MenuType.None);
                Ui.OpenWindow("CREDITS_PANEL", new WidgetArgs
                {
                    { "onExit", () => SwitchMenu(MenuType.Extras) },
                });
            };

            extrasMenu.Get <ButtonWidget>("BACK_BUTTON").OnClick = () => SwitchMenu(MenuType.Main);

            // Map editor menu
            var mapEditorMenu = widget.Get("MAP_EDITOR_MENU");

            mapEditorMenu.IsVisible = () => menuType == MenuType.MapEditor;

            // Loading into the map editor
            Game.BeforeGameStart += RemoveShellmapUI;

            var onSelect = new Action <string>(uid => LoadMapIntoEditor(modData.MapCache[uid].Uid));

            var newMapButton = widget.Get <ButtonWidget>("NEW_MAP_BUTTON");

            newMapButton.OnClick = () =>
            {
                SwitchMenu(MenuType.None);
                Game.OpenWindow("NEW_MAP_BG", new WidgetArgs()
                {
                    { "onSelect", onSelect },
                    { "onExit", () => SwitchMenu(MenuType.MapEditor) }
                });
            };

            var loadMapButton = widget.Get <ButtonWidget>("LOAD_MAP_BUTTON");

            loadMapButton.OnClick = () =>
            {
                SwitchMenu(MenuType.None);
                Game.OpenWindow("MAPCHOOSER_PANEL", new WidgetArgs()
                {
                    { "initialMap", null },
                    { "initialTab", MapClassification.User },
                    { "onExit", () => SwitchMenu(MenuType.MapEditor) },
                    { "onSelect", onSelect },
                    { "filter", MapVisibility.Lobby | MapVisibility.Shellmap | MapVisibility.MissionSelector },
                });
            };

            mapEditorMenu.Get <ButtonWidget>("BACK_BUTTON").OnClick = () => SwitchMenu(MenuType.Extras);

            var newsBG = widget.GetOrNull("NEWS_BG");

            if (newsBG != null)
            {
                newsBG.IsVisible = () => Game.Settings.Game.FetchNews && menuType != MenuType.None && menuType != MenuType.SystemInfoPrompt;

                newsPanel    = Ui.LoadWidget <ScrollPanelWidget>("NEWS_PANEL", null, new WidgetArgs());
                newsTemplate = newsPanel.Get("NEWS_ITEM_TEMPLATE");
                newsPanel.RemoveChild(newsTemplate);

                newsStatus = newsPanel.Get <LabelWidget>("NEWS_STATUS");
                SetNewsStatus("Loading news");
            }

            Game.OnRemoteDirectConnect += OnRemoteDirectConnect;

            var newsURL = modData.Manifest.Get <WebServices>().GameNews;

            // System information opt-out prompt
            var sysInfoPrompt = widget.Get("SYSTEM_INFO_PROMPT");

            sysInfoPrompt.IsVisible = () => menuType == MenuType.SystemInfoPrompt;
            if (Game.Settings.Debug.SystemInformationVersionPrompt < SystemInformationVersion)
            {
                menuType = MenuType.SystemInfoPrompt;

                var sysInfoCheckbox = sysInfoPrompt.Get <CheckboxWidget>("SYSINFO_CHECKBOX");
                sysInfoCheckbox.IsChecked = () => Game.Settings.Debug.SendSystemInformation;
                sysInfoCheckbox.OnClick   = () => Game.Settings.Debug.SendSystemInformation ^= true;

                var sysInfoData = sysInfoPrompt.Get <ScrollPanelWidget>("SYSINFO_DATA");
                var template    = sysInfoData.Get <LabelWidget>("DATA_TEMPLATE");
                sysInfoData.RemoveChildren();

                foreach (var info in GetSystemInformation().Values)
                {
                    var label = template.Clone() as LabelWidget;
                    var text  = info.First + ": " + info.Second;
                    label.GetText = () => text;
                    sysInfoData.AddChild(label);
                }

                sysInfoPrompt.Get <ButtonWidget>("BACK_BUTTON").OnClick = () =>
                {
                    Game.Settings.Debug.SystemInformationVersionPrompt = SystemInformationVersion;
                    Game.Settings.Save();
                    SwitchMenu(MenuType.Main);
                    LoadAndDisplayNews(newsURL, newsBG);
                };
            }
            else
            {
                LoadAndDisplayNews(newsURL, newsBG);
            }
        }

        void LoadAndDisplayNews(string newsURL, Widget newsBG)
        {
            if (newsBG != null)
            {
                var cacheFile   = Platform.ResolvePath("^", "news.yaml");
                var currentNews = ParseNews(cacheFile);
                if (currentNews != null)
                {
                    DisplayNews(currentNews);
                }

                var newsButton = newsBG.GetOrNull <DropDownButtonWidget>("NEWS_BUTTON");
                if (newsButton != null)
                {
                    if (!fetchedNews)
                    {
                        // Send the mod and engine version to support version-filtered news (update prompts)
                        newsURL += "?version={0}&mod={1}&modversion={2}".F(
                            Uri.EscapeUriString(Game.Mods["modcontent"].Metadata.Version),
                            Uri.EscapeUriString(Game.ModData.Manifest.Id),
                            Uri.EscapeUriString(Game.ModData.Manifest.Metadata.Version));

                        // Append system profile data if the player has opted in
                        if (Game.Settings.Debug.SendSystemInformation)
                        {
                            newsURL += "&sysinfoversion={0}&".F(SystemInformationVersion)
                                       + GetSystemInformation()
                                       .Select(kv => kv.Key + "=" + Uri.EscapeUriString(kv.Value.Second))
                                       .JoinWith("&");
                        }

                        new Download(newsURL, cacheFile, e => { },
                                     e => NewsDownloadComplete(e, cacheFile, currentNews,
                                                               () => newsButton.AttachPanel(newsPanel)));
                    }

                    newsButton.OnClick = () => newsButton.AttachPanel(newsPanel);
                }
            }
        }

        void OnRemoteDirectConnect(string host, int port)
        {
            SwitchMenu(MenuType.None);
            Ui.OpenWindow("MULTIPLAYER_PANEL", new WidgetArgs
            {
                { "onStart", RemoveShellmapUI },
                { "onExit", () => SwitchMenu(MenuType.Main) },
                { "directConnectHost", host },
                { "directConnectPort", port },
            });
        }

        void LoadMapIntoEditor(string uid)
        {
            ConnectionLogic.Connect(IPAddress.Loopback.ToString(),
                                    Game.CreateLocalServer(uid),
                                    "",
                                    () => { Game.LoadEditor(uid); },
                                    () => { Game.CloseServer(); SwitchMenu(MenuType.MapEditor); });
        }

        void SetNewsStatus(string message)
        {
            message            = WidgetUtils.WrapText(message, newsStatus.Bounds.Width, Game.Renderer.Fonts[newsStatus.Font]);
            newsStatus.GetText = () => message;
        }
Example #21
0
        public NewMapLogic(Action onExit, Action <string> onSelect, Ruleset modRules, Widget widget, World world)
        {
            panel = widget;

            panel.Get <ButtonWidget>("CANCEL_BUTTON").OnClick = () => { Ui.CloseWindow(); onExit(); };

            var tilesetDropDown = panel.Get <DropDownButtonWidget>("TILESET");
            var tilesets        = modRules.TileSets.Select(t => t.Key).ToList();
            Func <string, ScrollItemWidget, ScrollItemWidget> setupItem = (option, template) =>
            {
                var item = ScrollItemWidget.Setup(template,
                                                  () => tilesetDropDown.Text == option,
                                                  () => { tilesetDropDown.Text = option; });
                item.Get <LabelWidget>("LABEL").GetText = () => option;
                return(item);
            };

            tilesetDropDown.Text    = tilesets.First();
            tilesetDropDown.OnClick = () =>
                                      tilesetDropDown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 210, tilesets, setupItem);

            var widthTextField  = panel.Get <TextFieldWidget>("WIDTH");
            var heightTextField = panel.Get <TextFieldWidget>("HEIGHT");

            panel.Get <ButtonWidget>("CREATE_BUTTON").OnClick = () =>
            {
                var tileset = modRules.TileSets[tilesetDropDown.Text];
                var map     = Map.FromTileset(tileset);

                int width, height;
                int.TryParse(widthTextField.Text, out width);
                int.TryParse(heightTextField.Text, out height);

                // Require at least a 2x2 playable area so that the
                // ground is visible through the edge shroud
                width  = Math.Max(2, width);
                height = Math.Max(2, height);

                map.Resize(width + 2, height + tileset.MaxGroundHeight + 2);
                map.ResizeCordon(1, 1, width + 1, height + tileset.MaxGroundHeight + 1);
                map.PlayerDefinitions = new MapPlayers(map.Rules, map.SpawnPoints.Value.Length).ToMiniYaml();
                map.FixOpenAreas(modRules);

                var userMapFolder = Game.ModData.Manifest.MapFolders.First(f => f.Value == "User").Key;

                // Ignore optional flag
                if (userMapFolder.StartsWith("~"))
                {
                    userMapFolder = userMapFolder.Substring(1);
                }

                var mapDir = Platform.ResolvePath(userMapFolder);
                Directory.CreateDirectory(mapDir);
                var tempLocation = Path.Combine(mapDir, "temp") + ".oramap";
                map.Save(tempLocation);                 // TODO: load it right away and save later properly

                var newMap = new Map(tempLocation);
                Game.ModData.MapCache[newMap.Uid].UpdateFromMap(newMap, MapClassification.User);

                ConnectionLogic.Connect(System.Net.IPAddress.Loopback.ToString(),
                                        Game.CreateLocalServer(newMap.Uid),
                                        "",
                                        () => { Game.LoadEditor(newMap.Uid); },
                                        () => { Game.CloseServer(); onExit(); });
                onSelect(newMap.Uid);
            };
        }