예제 #1
0
 public TextRenderable(SpriteFont font, WPos pos, int zOffset, Color color, string text)
     : this(font, pos, zOffset, color,
            ChromeMetrics.Get <Color>("TextContrastColorDark"),
            ChromeMetrics.Get <Color>("TextContrastColorLight"),
            text)
 {
 }
        public GlobalChatLogic(Widget widget)
        {
            historyPanel     = widget.Get <ScrollPanelWidget>("HISTORY_PANEL");
            chatTemplate     = historyPanel.Get <ContainerWidget>("CHAT_TEMPLATE");
            nicknamePanel    = widget.Get <ScrollPanelWidget>("NICKNAME_PANEL");
            nicknameTemplate = nicknamePanel.Get("NICKNAME_TEMPLATE");

            var textColor = ChromeMetrics.Get <Color>("GlobalChatTextColor");
            var textLabel = chatTemplate.Get <LabelWidget>("TEXT");

            textLabel.GetColor = () => textColor;

            historyPanel.Bind(Game.GlobalChat.History, MakeHistoryWidget, HistoryWidgetEquals, true);
            nicknamePanel.Bind(Game.GlobalChat.Users, MakeUserWidget, UserWidgetEquals, false);

            inputBox            = widget.Get <TextFieldWidget>("CHAT_TEXTFIELD");
            inputBox.IsDisabled = () => Game.GlobalChat.ConnectionStatus != ChatConnectionStatus.Joined;
            inputBox.OnEnterKey = EnterPressed;

            // IRC protocol limits messages to 510 characters + CRLF
            inputBox.MaxLength = 510;

            var nickName    = Game.GlobalChat.SanitizedName(Game.Settings.Player.Name);
            var nicknameBox = widget.Get <TextFieldWidget>("NICKNAME_TEXTFIELD");

            nicknameBox.Text         = nickName;
            nicknameBox.OnTextEdited = () =>
            {
                nicknameBox.Text = Game.GlobalChat.SanitizedName(nicknameBox.Text);
            };

            var connectPanel = widget.Get("GLOBALCHAT_CONNECT_PANEL");

            connectPanel.IsVisible = () => Game.GlobalChat.ConnectionStatus == ChatConnectionStatus.Disconnected;

            var disconnectButton = widget.Get <ButtonWidget>("DISCONNECT_BUTTON");

            disconnectButton.OnClick = Game.GlobalChat.Disconnect;

            var connectAutomaticallyCheckBox = connectPanel.Get <CheckboxWidget>("CONNECT_AUTOMATICALLY_CHECKBOX");

            connectAutomaticallyCheckBox.IsChecked = () => Game.Settings.Chat.ConnectAutomatically;
            connectAutomaticallyCheckBox.OnClick   = () => { Game.Settings.Chat.ConnectAutomatically ^= true; Game.Settings.Save(); };

            var connectButton = connectPanel.Get <ButtonWidget>("CONNECT_BUTTON");

            connectButton.IsDisabled = () => !Game.GlobalChat.IsValidNickname(nicknameBox.Text);
            connectButton.OnClick    = () => Game.GlobalChat.Connect(nicknameBox.Text);

            var mainPanel = widget.Get("GLOBALCHAT_MAIN_PANEL");

            mainPanel.IsVisible = () => Game.GlobalChat.ConnectionStatus != ChatConnectionStatus.Disconnected;

            mainPanel.Get <LabelWidget>("CHANNEL_TOPIC").GetText = () => Game.GlobalChat.Topic;

            if (Game.Settings.Chat.ConnectAutomatically)
            {
                Game.GlobalChat.Connect(nickName);
            }
        }
예제 #3
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;
                });
            }
        }
예제 #4
0
 public UITextRenderable(SpriteFont font, WPos effectiveWorldPos, int2 screenPos, int zOffset, Color color, string text)
     : this(font, effectiveWorldPos, screenPos, zOffset, color,
            ChromeMetrics.Get <Color>("TextContrastColorDark"),
            ChromeMetrics.Get <Color>("TextContrastColorLight"),
            text)
 {
 }
예제 #5
0
        public Player(World world, Session.Client client, PlayerReference pr)
        {
            string botType;

            World           = world;
            InternalName    = pr.Name;
            PlayerReference = pr;

            // Real player or host-created bot
            if (client != null)
            {
                ClientIndex    = client.Index;
                Color          = client.Color;
                PlayerName     = client.Name;
                botType        = client.Bot;
                Faction        = ChooseFaction(world, client.Faction, !pr.LockFaction);
                DisplayFaction = ChooseDisplayFaction(world, client.Faction);
            }
            else
            {
                // Map player
                ClientIndex    = 0;              // Owned by the host (TODO: fix this)
                Color          = pr.Color;
                PlayerName     = pr.Name;
                NonCombatant   = pr.NonCombatant;
                Playable       = pr.Playable;
                Spectating     = pr.Spectating;
                botType        = pr.Bot;
                Faction        = ChooseFaction(world, pr.Faction, false);
                DisplayFaction = ChooseDisplayFaction(world, pr.Faction);
            }

            PlayerActor = world.CreateActor("Player", new TypeDictionary {
                new OwnerInit(this)
            });
            Shroud = PlayerActor.Trait <Shroud>();

            fogVisibilities = PlayerActor.TraitsImplementing <IFogVisibilityModifier>().ToArray();

            // Enable the bot logic on the host
            IsBot = botType != null;
            if (IsBot && Game.IsHost)
            {
                var logic = PlayerActor.TraitsImplementing <IBot>().FirstOrDefault(b => b.Info.Name == botType);
                if (logic == null)
                {
                    Log.Write("debug", "Invalid bot type: {0}", botType);
                }
                else
                {
                    logic.Activate(this);
                }
            }

            stanceColors.Self     = ChromeMetrics.Get <Color>("PlayerStanceColorSelf");
            stanceColors.Allies   = ChromeMetrics.Get <Color>("PlayerStanceColorAllies");
            stanceColors.Enemies  = ChromeMetrics.Get <Color>("PlayerStanceColorEnemies");
            stanceColors.Neutrals = ChromeMetrics.Get <Color>("PlayerStanceColorNeutrals");
        }
예제 #6
0
 public MapPreviewWidget()
 {
     spawnClaimed       = ChromeProvider.GetImage("lobby-bits", "spawn-claimed");
     spawnUnclaimed     = ChromeProvider.GetImage("lobby-bits", "spawn-unclaimed");
     spawnFont          = WarGame.Renderer.Fonts[ChromeMetrics.Get <string>("SpawnFont")];
     spawnColor         = ChromeMetrics.Get <Color>("SpawnColor");
     spawnContrastColor = ChromeMetrics.Get <Color>("SpawnContrastColor");
     spawnLabelOffset   = ChromeMetrics.Get <Int2>("SpawnLabelOffset");
 }
예제 #7
0
 public CheckboxWidget(ModData modData)
     : base(modData)
 {
     GetCheckType      = () => CheckType;
     TextColor         = ChromeMetrics.Get <Color>("TextColor");
     TextColorDisabled = ChromeMetrics.Get <Color>("TextDisabledColor");
     GetColor          = () => TextColor;
     GetColorDisabled  = () => TextColorDisabled;
 }
예제 #8
0
        internal static void StartGame(string mapUID, WorldType type)
        {
            // Dispose of the old world before creating a new one.
            worldRenderer?.Dispose();

            Cursor.SetCursor(null);
            BeforeGameStart();

            Map map;

            using (new PerfTimer("PrepareMap"))
                map = ModData.PrepareMap(mapUID);

            using (new PerfTimer("NewWorld"))
            {
                OrderManager.World       = new World(ModData, map, OrderManager, type);
                OrderManager.FramesAhead = OrderManager.World.OrderLatency;
            }

            OrderManager.World.GameOver += FinishBenchmark;

            worldRenderer = new WorldRenderer(ModData, OrderManager.World);

            // Proactively collect memory during loading to reduce peak memory.
            GC.Collect();

            using (new PerfTimer("LoadComplete"))
                OrderManager.World.LoadComplete(worldRenderer);

            // Proactively collect memory during loading to reduce peak memory.
            GC.Collect();

            if (OrderManager.GameStarted)
            {
                return;
            }

            Ui.MouseFocusWidget    = null;
            Ui.KeyboardFocusWidget = null;

            OrderManager.LocalFrameNumber = 0;
            OrderManager.LastTickTime     = RunTime;
            OrderManager.StartGame();
            worldRenderer.RefreshPalette();
            Cursor.SetCursor(ChromeMetrics.Get <string>("DefaultCursor"));

            // Now loading is completed, now is the ideal time to run a GC and compact the LOH.
            // - All the temporary garbage created during loading can be collected.
            // - Live objects are likely to live for the length of the game or longer,
            //   thus promoting them into a higher generation is not an issue.
            // - We can remove any fragmentation in the LOH caused by temporary loading garbage.
            // - A loading screen is visible, so a delay won't matter to the user.
            //   Much better to clean up now then to drop frames during gameplay for GC pauses.
            GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
            GC.Collect();
        }
예제 #9
0
        void InitHotkeyRemapDialog(Widget panel)
        {
            var label = new CachedTransform <HotkeyDefinition, string>(hd => hd.Description + ":");

            panel.Get <LabelWidget>("HOTKEY_LABEL").GetText = () => label.Update(selectedHotkeyDefinition);

            var duplicateNotice = panel.Get <LabelWidget>("DUPLICATE_NOTICE");

            duplicateNotice.TextColor = ChromeMetrics.Get <Color>("NoticeErrorColor");
            duplicateNotice.IsVisible = () => !isHotkeyValid;
            var duplicateNoticeText = new CachedTransform <HotkeyDefinition, string>(hd => hd != null ? duplicateNotice.Text.F(hd.Description) : duplicateNotice.Text);

            duplicateNotice.GetText = () => duplicateNoticeText.Update(duplicateHotkeyDefinition);

            var defaultNotice = panel.Get <LabelWidget>("DEFAULT_NOTICE");

            defaultNotice.TextColor = ChromeMetrics.Get <Color>("NoticeInfoColor");
            defaultNotice.IsVisible = () => isHotkeyValid && isHotkeyDefault;

            var originalNotice = panel.Get <LabelWidget>("ORIGINAL_NOTICE");

            originalNotice.TextColor = ChromeMetrics.Get <Color>("NoticeInfoColor");
            originalNotice.IsVisible = () => isHotkeyValid && !isHotkeyDefault;
            var originalNoticeText = new CachedTransform <HotkeyDefinition, string>(hd => originalNotice.Text.F(hd.Default.DisplayString()));

            originalNotice.GetText = () => originalNoticeText.Update(selectedHotkeyDefinition);

            var resetButton = panel.Get <ButtonWidget>("RESET_HOTKEY_BUTTON");

            resetButton.IsDisabled = () => isHotkeyDefault;
            resetButton.OnClick    = ResetHotkey;

            var clearButton = panel.Get <ButtonWidget>("CLEAR_HOTKEY_BUTTON");

            clearButton.IsDisabled = () => !hotkeyEntryWidget.Key.IsValid();
            clearButton.OnClick    = ClearHotkey;

            var overrideButton = panel.Get <ButtonWidget>("OVERRIDE_HOTKEY_BUTTON");

            overrideButton.IsDisabled = () => isHotkeyValid;
            overrideButton.IsVisible  = () => !isHotkeyValid;
            overrideButton.OnClick    = OverrideHotkey;

            hotkeyEntryWidget             = panel.Get <HotkeyEntryWidget>("HOTKEY_ENTRY");
            hotkeyEntryWidget.IsValid     = () => isHotkeyValid;
            hotkeyEntryWidget.OnLoseFocus = ValidateHotkey;
            hotkeyEntryWidget.OnEscKey    = () =>
            {
                hotkeyEntryWidget.Key = modData.Hotkeys[selectedHotkeyDefinition.Name].GetValue();
            };

            validHotkeyEntryWidth   = hotkeyEntryWidget.Bounds.Width;
            invalidHotkeyEntryWidth = validHotkeyEntryWidth - (clearButton.Bounds.X - overrideButton.Bounds.X);
        }
예제 #10
0
        public MapPreviewWidget()
        {
            tooltipContainer = Exts.Lazy(() => Ui.Root.Get <TooltipContainerWidget>(TooltipContainer));

            spawnClaimed       = ChromeProvider.GetImage("lobby-bits", "spawn-claimed");
            spawnUnclaimed     = ChromeProvider.GetImage("lobby-bits", "spawn-unclaimed");
            spawnFont          = Game.Renderer.Fonts[ChromeMetrics.Get <string>("SpawnFont")];
            spawnColor         = ChromeMetrics.Get <Color>("SpawnColor");
            spawnContrastColor = ChromeMetrics.Get <Color>("SpawnContrastColor");
            spawnLabelOffset   = ChromeMetrics.Get <int2>("SpawnLabelOffset");
        }
예제 #11
0
        Widget MakeHistoryWidget(object o)
        {
            var message = (ChatMessage)o;
            var from    = message.Type == ChatMessageType.Notification ? "Battlefield Control" : message.Nick;
            var color   = message.Type == ChatMessageType.Notification ? ChromeMetrics.Get <Color>("GlobalChatNotificationColor")
                                : ChromeMetrics.Get <Color>("GlobalChatPlayerNameColor");
            var template = (ContainerWidget)chatTemplate.Clone();

            LobbyUtils.SetupChatLine(template, color, message.Time, from, message.Message);

            template.Id = message.UID;
            return(template);
        }
예제 #12
0
        public SupportPowerTimerWidget(World world)
        {
            powers = world.ActorsWithTrait <SupportPowerManager>()
                     .Where(p => !p.Actor.IsDead && !p.Actor.Owner.NonCombatant)
                     .SelectMany(s => s.Trait.Powers.Values)
                     .Where(p => p.Instances.Any() && p.Info.DisplayTimerStances != Stance.None && !p.Disabled);

            // Timers in replays should be synced to the effective game time, not the playback time.
            timestep = world.Timestep;
            if (world.IsReplay)
            {
                timestep = world.WorldActor.Trait <MapOptions>().GameSpeed.Timestep;
            }

            bgDark  = ChromeMetrics.Get <Color>("TextContrastColorDark");
            bgLight = ChromeMetrics.Get <Color>("TextContrastColorLight");
        }
예제 #13
0
        Widget MakeHistoryWidget(object o)
        {
            var message = (ChatMessage)o;
            var widget  = (LabelWidget)historyTemplate.Clone();
            var font    = Game.Renderer.Fonts[widget.Font];

            var color = message.Type == ChatMessageType.Notification ?
                        ChromeMetrics.Get <Color>("GlobalChatNotificationColor") :
                        ChromeMetrics.Get <Color>("GlobalChatTextColor");

            var display = WidgetUtils.WrapText(message.ToString(), widget.Bounds.Width, font);

            widget.Bounds.Height = font.Measure(display).Y;
            widget.GetText       = () => display;
            widget.GetColor      = () => color;
            widget.Id            = message.UID;
            return(widget);
        }
예제 #14
0
        protected MapPreviewWidget(MapPreviewWidget other)
            : base(other)
        {
            Preview = other.Preview;

            IgnoreMouseInput = other.IgnoreMouseInput;
            ShowSpawnPoints  = other.ShowSpawnPoints;
            TooltipTemplate  = other.TooltipTemplate;
            TooltipContainer = other.TooltipContainer;
            SpawnOccupants   = other.SpawnOccupants;


            spawnClaimed       = ChromeProvider.GetImage("lobby-bits", "spawn-claimed");
            spawnUnclaimed     = ChromeProvider.GetImage("lobby-bits", "spawn-unclaimed");
            spawnFont          = WarGame.Renderer.Fonts[ChromeMetrics.Get <string>("SpawnFont")];
            spawnColor         = ChromeMetrics.Get <Color>("SpawnColor");
            spawnContrastColor = ChromeMetrics.Get <Color>("SpawnContrastColor");
            spawnLabelOffset   = ChromeMetrics.Get <Int2>("SpawnLabelOffset");
        }
        void BindHotkeyPref(HotkeyDefinition hd, Widget template, Widget parent)
        {
            var key = template.Clone() as Widget;

            key.Id        = hd.Name;
            key.IsVisible = () => true;

            key.Get <LabelWidget>("FUNCTION").GetText = () => hd.Description + ":";

            var remapButton = key.Get <ButtonWidget>("HOTKEY");

            WidgetUtils.TruncateButtonToTooltip(remapButton, modData.Hotkeys[hd.Name].GetValue().DisplayString());

            remapButton.IsHighlighted = () => selectedHotkeyDefinition == hd;

            var hotkeyValidColor   = ChromeMetrics.Get <Color>("HotkeyColor");
            var hotkeyInvalidColor = ChromeMetrics.Get <Color>("HotkeyColorInvalid");

            remapButton.GetColor = () =>
            {
                return(modData.Hotkeys.GetFirstDuplicate(hd.Name, modData.Hotkeys[hd.Name].GetValue(), hd) != null ?
                       hotkeyInvalidColor :
                       hotkeyValidColor);
            };

            if (selectedHotkeyDefinition == hd)
            {
                selectedHotkeyButton  = remapButton;
                hotkeyEntryWidget.Key = modData.Hotkeys[hd.Name].GetValue();
                ValidateHotkey();
            }

            remapButton.OnClick = () =>
            {
                selectedHotkeyDefinition = hd;
                selectedHotkeyButton     = remapButton;
                hotkeyEntryWidget.Key    = modData.Hotkeys[hd.Name].GetValue();
                ValidateHotkey();
                hotkeyEntryWidget.TakeKeyboardFocus();
            };

            parent.AddChild(key);
        }
예제 #16
0
        public HotkeyDialogLogic(Widget widget, Action onSave, HotkeyDefinition hotkeyDefinition, HotkeyManager hotkeyManager)
        {
            panel           = widget;
            this.onSave     = onSave;
            definition      = hotkeyDefinition;
            manager         = hotkeyManager;
            currentHotkey   = manager[definition.Name].GetValue();
            hotkeyEntry     = panel.Get <HotkeyEntryWidget>("HOTKEY_ENTRY");
            resetButton     = panel.Get <ButtonWidget>("RESET_BUTTON");
            clearButton     = panel.Get <ButtonWidget>("CLEAR_BUTTON");
            cancelButton    = panel.Get <ButtonWidget>("CANCEL_BUTTON");
            duplicateNotice = panel.Get <LabelWidget>("DUPLICATE_NOTICE");
            defaultNotice   = panel.Get <LabelWidget>("DEFAULT_NOTICE");
            originalNotice  = panel.Get <LabelWidget>("ORIGINAL_NOTICE");

            panel.Get <LabelWidget>("HOTKEY_LABEL").GetText = () => hotkeyDefinition.Description + ":";

            duplicateNotice.TextColor = ChromeMetrics.Get <Color>("NoticeErrorColor");
            duplicateNotice.GetText   = () =>
            {
                return((duplicateHotkey != null) ? duplicateNotice.Text.F(duplicateHotkey.Description) : duplicateNotice.Text);
            };
            defaultNotice.TextColor  = ChromeMetrics.Get <Color>("NoticeInfoColor");
            originalNotice.TextColor = ChromeMetrics.Get <Color>("NoticeInfoColor");
            originalNotice.Text      = originalNotice.Text.F(hotkeyDefinition.Default.DisplayString());

            resetButton.OnClick  = Reset;
            clearButton.OnClick  = Clear;
            cancelButton.OnClick = Cancel;

            hotkeyEntry.Key         = currentHotkey;
            hotkeyEntry.IsValid     = () => isValid;
            hotkeyEntry.OnTakeFocus = OnHotkeyEntryTakeFocus;
            hotkeyEntry.OnLoseFocus = OnHotkeyEntryLoseFocus;
            hotkeyEntry.OnEscape    = Cancel;
            hotkeyEntry.OnReturn    = Cancel;
            hotkeyEntry.TakeKeyboardFocus();

            Validate();
            isFirstValidation = false;
        }
        void BuildNotices()
        {
            if (noticesLabelA == null || noticesLabelB == null || noticesLabelC == null)
            {
                return;
            }

            if (advertiseOnline)
            {
                noticesLabelA.Text = "Internet Server (UPnP ";
                var aWidth = Game.Renderer.Fonts[noticesLabelA.Font].Measure(noticesLabelA.Text).X;
                noticesLabelA.Bounds.Width = aWidth;

                var status = UPnP.Status;
                noticesLabelB.Text = status == UPnPStatus.Enabled ? "Enabled" :
                                     status == UPnPStatus.NotSupported ? "Not Supported" : "Disabled";

                noticesLabelB.TextColor = status == UPnPStatus.Enabled ? ChromeMetrics.Get <Color>("UPnPEnabledColor") :
                                          status == UPnPStatus.NotSupported ? ChromeMetrics.Get <Color>("UPnPNotSupportedColor") :
                                          ChromeMetrics.Get <Color>("UPnPDisabledColor");

                var bWidth = Game.Renderer.Fonts[noticesLabelB.Font].Measure(noticesLabelB.Text).X;
                noticesLabelB.Bounds.X     = noticesLabelA.Bounds.Right;
                noticesLabelB.Bounds.Width = bWidth;
                noticesLabelB.Visible      = true;

                noticesLabelC.Text     = "):";
                noticesLabelC.Bounds.X = noticesLabelB.Bounds.Right;
                noticesLabelC.Visible  = true;
            }
            else
            {
                noticesLabelA.Text    = "Local Server:";
                noticesLabelB.Visible = false;
                noticesLabelC.Visible = false;
            }
        }
예제 #18
0
        static void BindHotkeyPref(HotkeyDefinition hd, HotkeyManager manager, Widget template, Widget parent, Widget remapDialogRoot, Widget remapDialogPlaceholder)
        {
            var key = template.Clone() as Widget;

            key.Id        = hd.Name;
            key.IsVisible = () => true;

            key.Get <LabelWidget>("FUNCTION").GetText = () => hd.Description + ":";

            var remapButton = key.Get <ButtonWidget>("HOTKEY");

            remapButton.GetText = () => manager[hd.Name].GetValue().DisplayString();

            if (manager.GetFirstDuplicate(hd.Name, manager[hd.Name].GetValue(), hd) != null)
            {
                remapButton.GetColor = () => ChromeMetrics.Get <Color>("HotkeyColorInvalid");
            }

            remapButton.OnClick = () =>
            {
                remapDialogRoot.RemoveChildren();

                if (remapButton.IsHighlighted())
                {
                    remapButton.IsHighlighted = () => false;

                    if (remapDialogPlaceholder != null)
                    {
                        remapDialogPlaceholder.Visible = true;
                    }

                    return;
                }

                if (remapDialogPlaceholder != null)
                {
                    remapDialogPlaceholder.Visible = false;
                }

                var siblings = parent.Children;
                foreach (var sibling in siblings)
                {
                    var button = sibling.GetOrNull <ButtonWidget>("HOTKEY");
                    if (button != null)
                    {
                        button.IsHighlighted = () => false;
                    }
                }

                remapButton.IsHighlighted = () => true;

                Ui.LoadWidget("HOTKEY_DIALOG", remapDialogRoot, new WidgetArgs
                {
                    {
                        "onSave", () =>
                        {
                            remapButton.GetText  = () => manager[hd.Name].GetValue().DisplayString();
                            remapButton.GetColor = () => ChromeMetrics.Get <Color>("ButtonTextColor");
                        }
                    },
                    { "hotkeyDefinition", hd },
                    { "hotkeyManager", manager },
                });
            };

            parent.AddChild(key);
        }
예제 #19
0
파일: Player.cs 프로젝트: sg6162eq/OpenRA
        public Player(World world, Session.Client client, PlayerReference pr, MersenneTwister playerRandom)
        {
            World           = world;
            InternalName    = pr.Name;
            PlayerReference = pr;

            inMissionMap = world.Map.Visibility.HasFlag(MapVisibility.MissionSelector);

            // Real player or host-created bot
            if (client != null)
            {
                ClientIndex = client.Index;
                Color       = client.Color;
                PlayerName  = ResolvePlayerName(client, world.LobbyInfo.Clients, world.Map.Rules.Actors["player"].TraitInfos <IBotInfo>());

                BotType        = client.Bot;
                Faction        = ResolveFaction(world, client.Faction, playerRandom, !pr.LockFaction);
                DisplayFaction = ResolveDisplayFaction(world, client.Faction);

                var assignSpawnPoints = world.WorldActor.TraitOrDefault <IAssignSpawnPoints>();
                HomeLocation      = assignSpawnPoints?.AssignHomeLocation(world, client, playerRandom) ?? pr.HomeLocation;
                SpawnPoint        = assignSpawnPoints?.SpawnPointForPlayer(this) ?? client.SpawnPoint;
                DisplaySpawnPoint = client.SpawnPoint;

                Handicap = client.Handicap;
            }
            else
            {
                // Map player
                ClientIndex    = 0;              // Owned by the host (TODO: fix this)
                Color          = pr.Color;
                PlayerName     = pr.Name;
                NonCombatant   = pr.NonCombatant;
                Playable       = pr.Playable;
                spectating     = pr.Spectating;
                BotType        = pr.Bot;
                Faction        = ResolveFaction(world, pr.Faction, playerRandom, false);
                DisplayFaction = ResolveDisplayFaction(world, pr.Faction);
                HomeLocation   = pr.HomeLocation;
                SpawnPoint     = DisplaySpawnPoint = 0;
                Handicap       = pr.Handicap;
            }

            if (!spectating)
            {
                PlayerMask = new LongBitSet <PlayerBitMask>(InternalName);
            }

            // Set this property before running any Created callbacks on the player actor
            IsBot = BotType != null;

            // Special case handling is required for the Player actor:
            // Since Actor.Created would be called before PlayerActor is assigned here
            // querying player traits in INotifyCreated.Created would crash.
            // Therefore assign the uninitialized actor and run the Created callbacks
            // by calling Initialize ourselves.
            var playerActorType = world.Type == WorldType.Editor ? EditorPlayerActorType : PlayerActorType;

            PlayerActor = new Actor(world, playerActorType, new TypeDictionary {
                new OwnerInit(this)
            });
            PlayerActor.Initialize(true);

            Shroud           = PlayerActor.Trait <Shroud>();
            FrozenActorLayer = PlayerActor.TraitOrDefault <FrozenActorLayer>();

            // Enable the bot logic on the host
            if (IsBot && Game.IsHost)
            {
                var logic = PlayerActor.TraitsImplementing <IBot>().FirstOrDefault(b => b.Info.Type == BotType);
                if (logic == null)
                {
                    Log.Write("debug", "Invalid bot type: {0}", BotType);
                }
                else
                {
                    logic.Activate(this);
                }
            }

            stanceColors.Self     = ChromeMetrics.Get <Color>("PlayerStanceColorSelf");
            stanceColors.Allies   = ChromeMetrics.Get <Color>("PlayerStanceColorAllies");
            stanceColors.Enemies  = ChromeMetrics.Get <Color>("PlayerStanceColorEnemies");
            stanceColors.Neutrals = ChromeMetrics.Get <Color>("PlayerStanceColorNeutrals");

            unlockRenderPlayer = PlayerActor.TraitsImplementing <IUnlocksRenderPlayer>().ToArray();
        }
예제 #20
0
        public ColorPickerLogic(Widget widget, ModData modData, World world, Color initialColor, string initialFaction, Action <Color> onChange,
                                Dictionary <string, MiniYaml> logicArgs)
        {
            if (initialFaction == null || !ChromeMetrics.TryGet("ColorPickerActorType-" + initialFaction, out string actorType))
            {
                actorType = ChromeMetrics.Get <string>("ColorPickerActorType");
            }

            var preview = widget.GetOrNull <ActorPreviewWidget>("PREVIEW");
            var actor   = world.Map.Rules.Actors[actorType];

            var td = new TypeDictionary();

            td.Add(new OwnerInit(world.WorldActor.Owner));
            td.Add(new FactionInit(world.WorldActor.Owner.PlayerReference.Faction));
            foreach (var api in actor.TraitInfos <IActorPreviewInitInfo>())
            {
                foreach (var o in api.ActorPreviewInits(actor, ActorPreviewType.ColorPicker))
                {
                    td.Add(o);
                }
            }

            preview?.SetPreview(actor, td);

            var hueSlider    = widget.Get <SliderWidget>("HUE");
            var mixer        = widget.Get <ColorMixerWidget>("MIXER");
            var randomButton = widget.GetOrNull <ButtonWidget>("RANDOM_BUTTON");

            hueSlider.OnChange += _ => mixer.Set(hueSlider.Value);
            mixer.OnChange     += () => onChange(mixer.Color);

            if (randomButton != null)
            {
                randomButton.OnClick = () =>
                {
                    // Avoid colors with low sat or lum
                    var hue   = (byte)Game.CosmeticRandom.Next(255);
                    var sat   = (byte)Game.CosmeticRandom.Next(70, 255);
                    var lum   = (byte)Game.CosmeticRandom.Next(70, 255);
                    var color = Color.FromAhsl(hue, sat, lum);

                    mixer.Set(color);
                    hueSlider.Value = HueFromColor(color);
                };
            }

            // Set the initial state
            var validator = modData.Manifest.Get <ColorValidator>();

            mixer.SetPaletteRange(validator.HsvSaturationRange[0], validator.HsvSaturationRange[1], validator.HsvValueRange[0], validator.HsvValueRange[1]);
            mixer.Set(initialColor);
            hueSlider.Value = HueFromColor(initialColor);

            // HACK: the value returned from the color mixer will generally not
            // be equal to the given initialColor due to its internal RGB -> HSL -> RGB
            // conversion. This conversion can sometimes convert a valid initial value
            // into an invalid (too close to terrain / another player) color.
            // We use the original colour here instead of the mixer color to make sure
            // that we keep the player's previous colour value if they don't change anything
            onChange(initialColor);

            // Setup tab controls
            var mixerTab            = widget.Get("MIXER_TAB");
            var paletteTab          = widget.Get("PALETTE_TAB");
            var paletteTabPanel     = widget.Get("PALETTE_TAB_PANEL");
            var mixerTabButton      = widget.Get <ButtonWidget>("MIXER_TAB_BUTTON");
            var paletteTabButton    = widget.Get <ButtonWidget>("PALETTE_TAB_BUTTON");
            var presetArea          = paletteTabPanel.Get <ContainerWidget>("PRESET_AREA");
            var customArea          = paletteTabPanel.Get <ContainerWidget>("CUSTOM_AREA");
            var presetColorTemplate = paletteTabPanel.Get <ColorBlockWidget>("COLORPRESET");
            var customColorTemplate = paletteTabPanel.Get <ColorBlockWidget>("COLORCUSTOM");

            mixerTab.IsVisible           = () => !paletteTabOpenedLast;
            mixerTabButton.OnClick       = () => paletteTabOpenedLast = false;
            mixerTabButton.IsHighlighted = mixerTab.IsVisible;

            paletteTab.IsVisible           = () => paletteTabOpenedLast;
            paletteTabButton.OnClick       = () => paletteTabOpenedLast = true;
            paletteTabButton.IsHighlighted = () => paletteTab.IsVisible() || paletteTabHighlighted > 0;

            var paletteCols       = 8;
            var palettePresetRows = 2;
            var paletteCustomRows = 1;

            if (logicArgs.TryGetValue("PaletteColumns", out var yaml))
            {
                if (!int.TryParse(yaml.Value, out paletteCols))
                {
                    throw new YamlException("Invalid value for PaletteColumns: {0}".F(yaml.Value));
                }
            }
            if (logicArgs.TryGetValue("PalettePresetRows", out yaml))
            {
                if (!int.TryParse(yaml.Value, out palettePresetRows))
                {
                    throw new YamlException("Invalid value for PalettePresetRows: {0}".F(yaml.Value));
                }
            }
            if (logicArgs.TryGetValue("PaletteCustomRows", out yaml))
            {
                if (!int.TryParse(yaml.Value, out paletteCustomRows))
                {
                    throw new YamlException("Invalid value for PaletteCustomRows: {0}".F(yaml.Value));
                }
            }

            for (var j = 0; j < palettePresetRows; j++)
            {
                for (var i = 0; i < paletteCols; i++)
                {
                    var colorIndex = j * paletteCols + i;
                    if (colorIndex >= validator.TeamColorPresets.Length)
                    {
                        break;
                    }

                    var color = validator.TeamColorPresets[colorIndex];

                    var newSwatch = (ColorBlockWidget)presetColorTemplate.Clone();
                    newSwatch.GetColor  = () => color;
                    newSwatch.IsVisible = () => true;
                    newSwatch.Bounds.X  = i * newSwatch.Bounds.Width;
                    newSwatch.Bounds.Y  = j * newSwatch.Bounds.Height;
                    newSwatch.OnMouseUp = m =>
                    {
                        mixer.Set(color);
                        hueSlider.Value = HueFromColor(color);
                        onChange(color);
                    };

                    presetArea.AddChild(newSwatch);
                }
            }

            for (var j = 0; j < paletteCustomRows; j++)
            {
                for (var i = 0; i < paletteCols; i++)
                {
                    var colorIndex = j * paletteCols + i;

                    var newSwatch = (ColorBlockWidget)customColorTemplate.Clone();
                    newSwatch.GetColor  = () => Game.Settings.Player.CustomColors[colorIndex];
                    newSwatch.IsVisible = () => Game.Settings.Player.CustomColors.Length > colorIndex;
                    newSwatch.Bounds.X  = i * newSwatch.Bounds.Width;
                    newSwatch.Bounds.Y  = j * newSwatch.Bounds.Height;
                    newSwatch.OnMouseUp = m =>
                    {
                        var color = Game.Settings.Player.CustomColors[colorIndex];
                        mixer.Set(color);
                        hueSlider.Value = HueFromColor(color);
                        onChange(color);
                    };

                    customArea.AddChild(newSwatch);
                }
            }

            // Store color button
            var storeButton = widget.Get <ButtonWidget>("STORE_BUTTON");

            if (storeButton != null)
            {
                storeButton.OnClick = () =>
                {
                    // Update the custom color list:
                    //  - Remove any duplicates of the new color
                    //  - Add the new color to the end
                    //  - Save the last N colors
                    Game.Settings.Player.CustomColors = Game.Settings.Player.CustomColors
                                                        .Where(c => c != mixer.Color)
                                                        .Append(mixer.Color)
                                                        .Reverse().Take(paletteCustomRows * paletteCols).Reverse()
                                                        .ToArray();
                    Game.Settings.Save();

                    // Flash the palette tab to show players that something has happened
                    if (!paletteTabOpenedLast)
                    {
                        paletteTabHighlighted = 4;
                    }
                };
            }
        }
예제 #21
0
        public Player(World world, Session.Client client, PlayerReference pr)
        {
            World           = world;
            InternalName    = pr.Name;
            PlayerReference = pr;

            inMissionMap = world.Map.Visibility.HasFlag(MapVisibility.MissionSelector);

            // Real player or host-created bot
            if (client != null)
            {
                ClientIndex = client.Index;
                Color       = client.Color;
                if (client.Bot != null)
                {
                    var botInfo        = world.Map.Rules.Actors["player"].TraitInfos <IBotInfo>().First(b => b.Type == client.Bot);
                    var botsOfSameType = world.LobbyInfo.Clients.Where(c => c.Bot == client.Bot).ToArray();
                    PlayerName = botsOfSameType.Length == 1 ? botInfo.Name : "{0} {1}".F(botInfo.Name, botsOfSameType.IndexOf(client) + 1);
                }
                else
                {
                    PlayerName = client.Name;
                }

                BotType        = client.Bot;
                Faction        = ChooseFaction(world, client.Faction, !pr.LockFaction);
                DisplayFaction = ChooseDisplayFaction(world, client.Faction);
            }
            else
            {
                // Map player
                ClientIndex    = 0;              // Owned by the host (TODO: fix this)
                Color          = pr.Color;
                PlayerName     = pr.Name;
                NonCombatant   = pr.NonCombatant;
                Playable       = pr.Playable;
                Spectating     = pr.Spectating;
                BotType        = pr.Bot;
                Faction        = ChooseFaction(world, pr.Faction, false);
                DisplayFaction = ChooseDisplayFaction(world, pr.Faction);
            }

            var playerActorType = world.Type == WorldType.Editor ? "EditorPlayer" : "Player";

            PlayerActor = world.CreateActor(playerActorType, new TypeDictionary {
                new OwnerInit(this)
            });
            Shroud = PlayerActor.Trait <Shroud>();

            // Enable the bot logic on the host
            IsBot = BotType != null;
            if (IsBot && Game.IsHost)
            {
                var logic = PlayerActor.TraitsImplementing <IBot>().FirstOrDefault(b => b.Info.Type == BotType);
                if (logic == null)
                {
                    Log.Write("debug", "Invalid bot type: {0}", BotType);
                }
                else
                {
                    logic.Activate(this);
                }
            }

            stanceColors.Self     = ChromeMetrics.Get <Color>("PlayerStanceColorSelf");
            stanceColors.Allies   = ChromeMetrics.Get <Color>("PlayerStanceColorAllies");
            stanceColors.Enemies  = ChromeMetrics.Get <Color>("PlayerStanceColorEnemies");
            stanceColors.Neutrals = ChromeMetrics.Get <Color>("PlayerStanceColorNeutrals");

            unlockRenderPlayer = PlayerActor.TraitsImplementing <IUnlocksRenderPlayer>().ToArray();
        }
예제 #22
0
        public ServerListLogic(Widget widget, ModData modData, Action <GameServer> onJoin)
        {
            this.modData = modData;
            this.onJoin  = onJoin;

            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");

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

            noticeContainer = widget.GetOrNull("NOTICE_CONTAINER");
            if (noticeContainer != null)
            {
                noticeContainer.IsVisible = () => showNotices;
                noticeContainer.Get("OUTDATED_VERSION_LABEL").IsVisible   = () => services.ModVersionStatus == ModVersionStatus.Outdated;
                noticeContainer.Get("UNKNOWN_VERSION_LABEL").IsVisible    = () => services.ModVersionStatus == ModVersionStatus.Unknown;
                noticeContainer.Get("PLAYTEST_AVAILABLE_LABEL").IsVisible = () => services.ModVersionStatus == ModVersionStatus.PlaytestAvailable;
            }

            var noticeWatcher = widget.Get <LogicTickerWidget>("NOTICE_WATCHER");

            if (noticeWatcher != null && noticeContainer != null)
            {
                var containerHeight = noticeContainer.Bounds.Height;
                noticeWatcher.OnTick = () =>
                {
                    var show = services.ModVersionStatus != ModVersionStatus.NotChecked && services.ModVersionStatus != ModVersionStatus.Latest;
                    if (show != showNotices)
                    {
                        var dir = show ? 1 : -1;
                        serverList.Bounds.Y      += dir * containerHeight;
                        serverList.Bounds.Height -= dir * containerHeight;
                        showNotices = show;
                    }
                };
            }

            joinButton = widget.GetOrNull <ButtonWidget>("JOIN_BUTTON");
            if (joinButton != null)
            {
                joinButton.IsVisible  = () => currentServer != null;
                joinButton.IsDisabled = () => !currentServer.IsJoinable;
                joinButton.OnClick    = () => onJoin(currentServer);
                joinButtonY           = joinButton.Bounds.Y;
            }

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

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

            var gs = Game.Settings.Game;
            Action <MPGameFilters> toggleFilterFlag = f =>
            {
                gs.MPGameFilters ^= f;
                Game.Settings.Save();
                RefreshServerList();
            };

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

            if (filtersButton != null)
            {
                // HACK: MULTIPLAYER_FILTER_PANEL doesn't follow our normal procedure for dropdown creation
                // but we still need to be able to set the dropdown width based on the parent
                // The yaml should use PARENT_RIGHT instead of DROPDOWN_WIDTH
                var filtersPanel = Ui.LoadWidget("MULTIPLAYER_FILTER_PANEL", filtersButton, new WidgetArgs());
                filtersButton.Children.Remove(filtersPanel);

                var showWaitingCheckbox = filtersPanel.GetOrNull <CheckboxWidget>("WAITING_FOR_PLAYERS");
                if (showWaitingCheckbox != null)
                {
                    showWaitingCheckbox.IsChecked = () => gs.MPGameFilters.HasFlag(MPGameFilters.Waiting);
                    showWaitingCheckbox.OnClick   = () => toggleFilterFlag(MPGameFilters.Waiting);
                }

                var showEmptyCheckbox = filtersPanel.GetOrNull <CheckboxWidget>("EMPTY");
                if (showEmptyCheckbox != null)
                {
                    showEmptyCheckbox.IsChecked = () => gs.MPGameFilters.HasFlag(MPGameFilters.Empty);
                    showEmptyCheckbox.OnClick   = () => toggleFilterFlag(MPGameFilters.Empty);
                }

                var showAlreadyStartedCheckbox = filtersPanel.GetOrNull <CheckboxWidget>("ALREADY_STARTED");
                if (showAlreadyStartedCheckbox != null)
                {
                    showAlreadyStartedCheckbox.IsChecked = () => gs.MPGameFilters.HasFlag(MPGameFilters.Started);
                    showAlreadyStartedCheckbox.OnClick   = () => toggleFilterFlag(MPGameFilters.Started);
                }

                var showProtectedCheckbox = filtersPanel.GetOrNull <CheckboxWidget>("PASSWORD_PROTECTED");
                if (showProtectedCheckbox != null)
                {
                    showProtectedCheckbox.IsChecked = () => gs.MPGameFilters.HasFlag(MPGameFilters.Protected);
                    showProtectedCheckbox.OnClick   = () => toggleFilterFlag(MPGameFilters.Protected);
                }

                var showIncompatibleCheckbox = filtersPanel.GetOrNull <CheckboxWidget>("INCOMPATIBLE_VERSION");
                if (showIncompatibleCheckbox != null)
                {
                    showIncompatibleCheckbox.IsChecked = () => gs.MPGameFilters.HasFlag(MPGameFilters.Incompatible);
                    showIncompatibleCheckbox.OnClick   = () => toggleFilterFlag(MPGameFilters.Incompatible);
                }

                filtersButton.IsDisabled  = () => searchStatus == SearchStatus.Fetching;
                filtersButton.OnMouseDown = _ =>
                {
                    filtersButton.RemovePanel();
                    filtersButton.AttachPanel(filtersPanel);
                };
            }

            var reloadButton = widget.GetOrNull <ButtonWidget>("RELOAD_BUTTON");

            if (reloadButton != null)
            {
                reloadButton.IsDisabled = () => searchStatus == SearchStatus.Fetching;
                reloadButton.OnClick    = RefreshServerList;

                var reloadIcon = reloadButton.GetOrNull <ImageWidget>("IMAGE_RELOAD");
                if (reloadIcon != null)
                {
                    var disabledFrame = 0;
                    var disabledImage = "disabled-" + disabledFrame.ToString();
                    reloadIcon.GetImageName = () => searchStatus == SearchStatus.Fetching ? disabledImage : reloadIcon.ImageName;

                    var reloadTicker = reloadIcon.Get <LogicTickerWidget>("ANIMATION");
                    if (reloadTicker != null)
                    {
                        reloadTicker.OnTick = () =>
                        {
                            disabledFrame = searchStatus == SearchStatus.Fetching ? (disabledFrame + 1) % 12 : 0;
                            disabledImage = "disabled-" + disabledFrame.ToString();
                        };
                    }
                }
            }

            var playersLabel = widget.GetOrNull <LabelWidget>("PLAYER_COUNT");

            if (playersLabel != null)
            {
                var playersText = new CachedTransform <int, string>(c => c == 1 ? "1 Player Online" : c.ToString() + " Players Online");
                playersLabel.IsVisible = () => playerCount != 0;
                playersLabel.GetText   = () => playersText.Update(playerCount);
            }

            mapPreview = widget.GetOrNull <MapPreviewWidget>("SELECTED_MAP_PREVIEW");
            if (mapPreview != null)
            {
                mapPreview.Preview = () => currentMap;
            }

            var mapTitle = widget.GetOrNull <LabelWidget>("SELECTED_MAP");

            if (mapTitle != null)
            {
                var font  = Game.Renderer.Fonts[mapTitle.Font];
                var title = new CachedTransform <MapPreview, string>(m => m == null ? "No Server Selected" :
                                                                     WidgetUtils.TruncateText(m.Title, mapTitle.Bounds.Width, font));
                mapTitle.GetText = () => title.Update(currentMap);
            }

            var ip = widget.GetOrNull <LabelWidget>("SELECTED_IP");

            if (ip != null)
            {
                ip.IsVisible = () => currentServer != null;
                ip.GetText   = () => currentServer.Address;
            }

            var status = widget.GetOrNull <LabelWidget>("SELECTED_STATUS");

            if (status != null)
            {
                status.IsVisible = () => currentServer != null;
                status.GetText   = () => GetStateLabel(currentServer);
                status.GetColor  = () => GetStateColor(currentServer, status);
            }

            var modVersion = widget.GetOrNull <LabelWidget>("SELECTED_MOD_VERSION");

            if (modVersion != null)
            {
                modVersion.IsVisible = () => currentServer != null;
                modVersion.GetColor  = () => currentServer.IsCompatible ? modVersion.TextColor : incompatibleVersionColor;

                var font    = Game.Renderer.Fonts[modVersion.Font];
                var version = new CachedTransform <GameServer, string>(s => WidgetUtils.TruncateText(s.ModLabel, modVersion.Bounds.Width, font));
                modVersion.GetText = () => version.Update(currentServer);
            }

            var players = widget.GetOrNull <LabelWidget>("SELECTED_PLAYERS");

            if (players != null)
            {
                players.IsVisible = () => currentServer != null && (clientContainer == null || !currentServer.Clients.Any());
                players.GetText   = () => PlayersLabel(currentServer);
            }

            clientContainer = widget.GetOrNull("CLIENT_LIST_CONTAINER");
            if (clientContainer != null)
            {
                clientList           = Ui.LoadWidget("MULTIPLAYER_CLIENT_LIST", clientContainer, new WidgetArgs()) as ScrollPanelWidget;
                clientList.IsVisible = () => currentServer != null && currentServer.Clients.Any();
                clientHeader         = clientList.Get <ScrollItemWidget>("HEADER");
                clientTemplate       = clientList.Get <ScrollItemWidget>("TEMPLATE");
                clientList.RemoveChildren();
            }

            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();
        }
예제 #23
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;
                });
            }
        }
예제 #24
0
        public ServerBrowserLogic(Widget widget, Action onStart, Action onExit, string directConnectHost, int directConnectPort)
        {
            panel        = widget;
            this.onStart = onStart;

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

            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;
                });
            }
        }
예제 #25
0
        public Player(World world, Session.Client client, PlayerReference pr)
        {
            World           = world;
            InternalName    = pr.Name;
            PlayerReference = pr;

            //Real player or host-created bot
            if (client != null)
            {
                ClientIndex = client.Index;
                Color       = client.Color;

                if (client.Bot != null)
                {
                    var botInfo        = world.Map.Rules.Actors["player"].TraitInfos <IBotInfo>().First(b => b.Type == client.Bot);
                    var botsOfSameType = world.LobbyInfo.Clients.Where(c => c.Bot == client.Bot).ToArray();
                    PlayerName = botsOfSameType.Length == 1 ? botInfo.Name : "{0} {1}".F(botInfo.Name, botsOfSameType.IndexOf(client) + 1);
                }
                else
                {
                    PlayerName = client.Name;
                }
                BotType = client.Bot;
                Faction = ChooseFaction(world, client.Faction, !pr.LockFaction);
                //DisplayFaction = ChooseDisplayFaction(world, client.Faction);
            }
            else
            {
                //Map player
                ClientIndex    = 0;
                Color          = pr.Color;
                PlayerName     = pr.Name;
                NonCombatant   = pr.NonCombatant;
                Playable       = pr.Playable;
                Spectating     = pr.Spectating;
                BotType        = pr.Bot;
                Faction        = ChooseFaction(world, pr.Faction, false);
                DisplayFaction = ChooseDisplayFaction(world, pr.Faction);
            }

            PlayerActor = world.CreateActor("Player", new TypeDictionary()
            {
                new OwnerInit(this)
            });
            Shroud = PlayerActor.Trait <Shroud>();
            //fogVisibilities = PlayerActor.TraitsImplementing<IFogVisibilityModifier>().ToArray();
            IsBot = BotType != null;

            //Enable the bot logic on the host
            if (IsBot && WarGame.IsHost)
            {
                var logic = PlayerActor.TraitsImplementing <IBot>().FirstOrDefault(b => b.Info.Type == BotType);
                if (logic == null)
                {
                }
                else
                {
                    logic.Activate(this);
                }
            }
            stanceColors.Self     = ChromeMetrics.Get <Color>("PlayerStanceColorSelf");
            stanceColors.Allies   = ChromeMetrics.Get <Color>("PlayerStanceColorAllies");
            stanceColors.Enemies  = ChromeMetrics.Get <Color>("PlayerStanceColorEnemies");
            stanceColors.Neutrals = ChromeMetrics.Get <Color>("PlayerStanceColorNeutrals");
        }