Esempio n. 1
0
        public AddFactionSuffixLogic(Widget widget, World world)
        {
            string faction;

            if (!ChromeMetrics.TryGet("FactionSuffix-" + world.LocalPlayer.Faction.InternalName, out faction))
            {
                faction = world.LocalPlayer.Faction.InternalName;
            }
            var suffix = "-" + faction;

            if (widget is ButtonWidget)
            {
                ((ButtonWidget)widget).Background += suffix;
            }
            else if (widget is ImageWidget)
            {
                ((ImageWidget)widget).ImageCollection += suffix;
            }
            else if (widget is BackgroundWidget)
            {
                ((BackgroundWidget)widget).Background += suffix;
            }
            else if (widget is ProductionTabsWidget)
            {
                ((ProductionTabsWidget)widget).Button     += suffix;
                ((ProductionTabsWidget)widget).Background += suffix;
            }
            else
            {
                throw new InvalidOperationException("AddFactionSuffixLogic only supports ButtonWidget, ImageWidget, BackgroundWidget and ProductionTabsWidget");
            }
        }
Esempio n. 2
0
        public SidebarWidget(IngameUiWidget ingameUi)
        {
            this.IngameUi = ingameUi;
            this.Id       = SidebarWidget.Identifier;

            this.Buttons = new(this.IngameUi.World, $"sidebar-{this.IngameUi.World.LocalPlayer.Faction.InternalName}");
            this.Font    = new(this.IngameUi.World, "font");

            ChromeMetrics.TryGet($"ButtonArea-{this.IngameUi.World.LocalPlayer.Faction.InternalName}", out this.ButtonArea);

            this.AddChild(new ProductionCategoryButtonWidget(this, 0, new[] { "infantry" }, "Infantry"));
            this.AddChild(new ProductionCategoryButtonWidget(this, 1, new[] { "vehicle", "beast" }, "Vehicles"));
            this.AddChild(new ProductionCategoryButtonWidget(this, 2, new[] { "building" }, "Buildings"));
            this.AddChild(new ProductionCategoryButtonWidget(this, 3, new[] { "tower" }, "Towers"));
            this.AddChild(new ProductionCategoryButtonWidget(this, 4, new[] { "wall" }, "Walls"));

            this.AddChild(this.bomber = new(this));

            this.AddChild(this.sell     = new(this));
            this.AddChild(this.research = new(this));
            this.AddChild(this.repair   = new(this));

            this.AddChild(this.radar   = new(this));
            this.AddChild(this.options = new(this));

            this.Resize();
        }
 static TextNotificationsManager()
 {
     if (!ChromeMetrics.TryGet("SystemMessageLabel", out SystemMessageLabel))
     {
         SystemMessageLabel = "Battlefield Control";
     }
 }
Esempio n. 4
0
        public ColorPickerLogic(Widget widget, ModData modData, World world, HSLColor initialColor, Action <HSLColor> onChange, WorldRenderer worldRenderer)
        {
            string actorType;

            if (!ChromeMetrics.TryGet("ColorPickerActorType", out actorType))
            {
                actorType = "mcv";
            }

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

            if (preview != null)
            {
                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);

                    mixer.Set(new HSLColor(hue, sat, lum));
                    hueSlider.Value = hue / 255f;
                }
            }
            ;

            // 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 = initialColor.H / 255f;
            onChange(mixer.Color);
        }
        public AddFactionSuffixLogic(Widget widget, World world)
        {
            string faction;

            if (!ChromeMetrics.TryGet("FactionSuffix-" + world.LocalPlayer.Faction.InternalName, out faction))
            {
                faction = world.LocalPlayer.Faction.InternalName;
            }
            var suffix = "-" + faction;

            var buttonWidget = widget as ButtonWidget;

            if (buttonWidget != null)
            {
                buttonWidget.Background += suffix;
            }
            else
            {
                var imageWidget = widget as ImageWidget;
                if (imageWidget != null)
                {
                    imageWidget.ImageCollection += suffix;
                }
                else
                {
                    throw new InvalidOperationException("AddFactionSuffixLogic only supports ButtonWidget and ImageWidget");
                }
            }
        }
Esempio n. 6
0
        public SidebarWidget(IngameUiWidget ingameUi)
        {
            IngameUi = ingameUi;
            Id       = "KKND_SIDEBAR";

            Buttons = new Animation(IngameUi.World, "icon-" + IngameUi.World.LocalPlayer.Faction.InternalName);
            Font    = new Animation(IngameUi.World, "font");

            ChromeMetrics.TryGet("ButtonArea-" + IngameUi.World.LocalPlayer.Faction.InternalName, out ButtonArea);

            AddChild(new ProductionCategoryButtonWidget(this, 0, new[] { "infantry" }, "Infantry"));
            AddChild(new ProductionCategoryButtonWidget(this, 1, new[] { "vehicle", "beast" }, "Vehicles"));
            AddChild(new ProductionCategoryButtonWidget(this, 2, new[] { "building" }, "Buildings"));
            AddChild(new ProductionCategoryButtonWidget(this, 3, new[] { "tower" }, "Towers"));
            AddChild(new ProductionCategoryButtonWidget(this, 4, new[] { "wall" }, "Walls"));

            AddChild(bomber = new BomberButtonWidget(this));

            AddChild(sell     = new SellButtonWidget(this));
            AddChild(research = new ResearchButtonWidget(this));
            AddChild(repair   = new RepairButtonWidget(this));

            AddChild(radar   = new RadarButtonWidget(this));
            AddChild(options = new OptionsButtonWidget(this));

            Resize();
        }
Esempio n. 7
0
 static TextNotificationsManager()
 {
     ChromeMetrics.TryGet("ChatMessageColor", out chatMessageColor);
     ChromeMetrics.TryGet("SystemMessageColor", out systemMessageColor);
     if (!ChromeMetrics.TryGet("SystemMessageLabel", out systemMessageLabel))
     {
         systemMessageLabel = "Battlefield Control";
     }
 }
Esempio n. 8
0
        public ColorPickerLogic(Widget widget, World world, HSLColor initialColor, Action <HSLColor> onChange, WorldRenderer worldRenderer)
        {
            string actorType;

            if (!ChromeMetrics.TryGet <string>("ColorPickerActorType", out actorType))
            {
                actorType = "mcv";
            }

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

            var td = new TypeDictionary();

            td.Add(new HideBibPreviewInit());
            td.Add(new OwnerInit(world.WorldActor.Owner));
            td.Add(new RaceInit(world.WorldActor.Owner.PlayerReference.Faction));

            if (preview != null)
            {
                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);

                    mixer.Set(new HSLColor(hue, sat, lum));
                    hueSlider.Value = hue / 255f;
                }
            }
            ;

            // Set the initial state
            mixer.Set(initialColor);
            hueSlider.Value = initialColor.H / 255f;
            onChange(mixer.Color);
        }
Esempio n. 9
0
        public AddFactionSuffixLogic(Widget widget, World world)
        {
            if (world.LocalPlayer == null)
            {
                return;
            }

            if (!ChromeMetrics.TryGet("FactionSuffix-" + world.LocalPlayer.Faction.InternalName, out string faction))
            {
                faction = world.LocalPlayer.Faction.InternalName;
            }
            var suffix = "-" + faction;

            if (widget is ButtonWidget bw)
            {
                bw.Background += suffix;
            }
            else if (widget is ImageWidget iw)
            {
                iw.ImageCollection += suffix;
            }
            else if (widget is BackgroundWidget bgw)
            {
                bgw.Background += suffix;
            }
            else if (widget is TextFieldWidget tfw)
            {
                tfw.Background += suffix;
            }
            else if (widget is ScrollPanelWidget spw)
            {
                spw.Button              += suffix;
                spw.Background          += suffix;
                spw.ScrollBarBackground += suffix;
                spw.Decorations         += suffix;
            }
            else if (widget is ProductionTabsWidget ptw)
            {
                ptw.Button     += suffix;
                ptw.Background += suffix;
            }
            else
            {
                throw new InvalidOperationException("AddFactionSuffixLogic only supports ButtonWidget, ImageWidget, BackgroundWidget, TextFieldWidget, ScrollPanelWidget and ProductionTabsWidget");
            }
        }
Esempio n. 10
0
        public IngameTransientNotificationsLogic(Widget widget, OrderManager orderManager, ModData modData, Dictionary <string, MiniYaml> logicArgs)
        {
            this.orderManager = orderManager;
            modRules          = modData.DefaultRules;

            displayWidget = widget.Get <TextNotificationsDisplayWidget>("TRANSIENTS_DISPLAY");

            orderManager.AddTextNotification += AddNotificationWrapper;

            if (logicArgs.TryGetValue("TransientLineSound", out var yaml))
            {
                transientLineSound = yaml.Value;
            }
            else
            {
                ChromeMetrics.TryGet("TransientLineSound", out transientLineSound);
            }
        }
Esempio n. 11
0
        public WorldInteractionControllerWidget(World world, WorldRenderer worldRenderer)
        {
            World = world;
            this.worldRenderer = worldRenderer;
            if (!ChromeMetrics.TryGet("AltSelectionColor", out altSelectionColor))
            {
                altSelectionColor = Color.White;
            }

            if (!ChromeMetrics.TryGet("CtrlSelectionColor", out ctrlSelectionColor))
            {
                ctrlSelectionColor = Color.White;
            }

            if (!ChromeMetrics.TryGet("NormalSelectionColor", out normalSelectionColor))
            {
                normalSelectionColor = Color.White;
            }
        }
Esempio n. 12
0
        public AddRaceSuffixLogic(Widget widget, World world)
        {
            string race;

            if (!ChromeMetrics.TryGet("RaceSuffix-" + world.LocalPlayer.Faction.InternalName, out race))
            {
                race = world.LocalPlayer.Faction.InternalName;
            }
            var suffix = "-" + race;

            if (widget is ButtonWidget)
            {
                ((ButtonWidget)widget).Background += suffix;
            }
            else if (widget is ImageWidget)
            {
                ((ImageWidget)widget).ImageCollection += suffix;
            }
            else
            {
                throw new InvalidOperationException("AddRaceSuffixLogic only supports ButtonWidget and ImageWidget");
            }
        }
Esempio n. 13
0
        public override void Initialize(WidgetArgs args)
        {
            base.Initialize(args);

            hotkeys = Exts.MakeArray(HotkeyCount,
                                     i => modData.Hotkeys[HotkeyPrefix + (i + 1).ToString("D2")]);

            overlayFont = Game.Renderer.Fonts[OverlayFont];
            Game.Renderer.Fonts.TryGetValue(SymbolsFont, out symbolFont);

            iconOffset   = 0.5f * IconSize.ToFloat2() + IconSpriteOffset;
            queuedOffset = new float2(4, 2);
            holdOffset   = iconOffset - overlayFont.Measure(HoldText) / 2;
            readyOffset  = iconOffset - overlayFont.Measure(ReadyText) / 2;

            if (ChromeMetrics.TryGet("InfiniteOffset", out infiniteOffset))
            {
                infiniteOffset += queuedOffset;
            }
            else
            {
                infiniteOffset = queuedOffset;
            }
        }
Esempio n. 14
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;
                    }
                };
            }
        }
Esempio n. 15
0
        public static void InitializeMod(string mod, Arguments args)
        {
            // Clear static state if we have switched mods
            LobbyInfoChanged       = () => { };
            ConnectionStateChanged = om => { };
            BeforeGameStart        = () => { };
            OnRemoteDirectConnect  = endpoint => { };
            delayedActions         = new ActionQueue();

            Ui.ResetAll();

            worldRenderer?.Dispose();
            worldRenderer = null;
            server?.Shutdown();
            OrderManager?.Dispose();

            if (ModData != null)
            {
                ModData.ModFiles.UnmountAll();
                ModData.Dispose();
            }

            ModData = null;

            if (mod == null)
            {
                throw new InvalidOperationException("Game.Mod argument missing.");
            }

            if (!Mods.ContainsKey(mod))
            {
                throw new InvalidOperationException($"Unknown or invalid mod '{mod}'.");
            }

            Console.WriteLine("Loading mod: {0}", mod);

            Sound.StopVideo();

            ModData = new ModData(Mods[mod], Mods, true);

            LocalPlayerProfile = new LocalPlayerProfile(Path.Combine(Platform.SupportDir, Settings.Game.AuthProfile), ModData.Manifest.Get <PlayerDatabase>());

            if (!ModData.LoadScreen.BeforeLoad())
            {
                return;
            }

            ModData.InitializeLoaders(ModData.DefaultFileSystem);
            Renderer.InitializeFonts(ModData);

            using (new PerfTimer("LoadMaps"))
                ModData.MapCache.LoadMaps();

            var grid = ModData.Manifest.Contains <MapGrid>() ? ModData.Manifest.Get <MapGrid>() : null;

            Renderer.InitializeDepthBuffer(grid);

            Cursor?.Dispose();

            Cursor = new CursorManager(ModData.CursorProvider);

            PerfHistory.Items["render"].HasNormalTick           = false;
            PerfHistory.Items["batches"].HasNormalTick          = false;
            PerfHistory.Items["render_world"].HasNormalTick     = false;
            PerfHistory.Items["render_widgets"].HasNormalTick   = false;
            PerfHistory.Items["render_flip"].HasNormalTick      = false;
            PerfHistory.Items["terrain_lighting"].HasNormalTick = false;

            JoinLocal();

            ChromeMetrics.TryGet("ChatMessageColor", out chatMessageColor);
            ChromeMetrics.TryGet("SystemMessageColor", out systemMessageColor);
            if (!ChromeMetrics.TryGet("SystemMessageLabel", out systemMessageLabel))
            {
                systemMessageLabel = "Battlefield Control";
            }

            ModData.LoadScreen.StartGame(args);
        }
Esempio n. 16
0
        public static void InitializeMod(string mod, Arguments args)
        {
            // Clear static state if we have switched mods
            LobbyInfoChanged       = () => { };
            ConnectionStateChanged = om => { };
            BeforeGameStart        = () => { };
            OnRemoteDirectConnect  = (a, b) => { };
            delayedActions         = new ActionQueue();

            Ui.ResetAll();

            if (worldRenderer != null)
            {
                worldRenderer.Dispose();
            }
            worldRenderer = null;
            if (server != null)
            {
                server.Shutdown();
            }
            if (OrderManager != null)
            {
                OrderManager.Dispose();
            }

            if (ModData != null)
            {
                ModData.ModFiles.UnmountAll();
                ModData.Dispose();
            }

            ModData = null;

            if (mod == null)
            {
                throw new InvalidOperationException("Game.Mod argument missing.");
            }

            if (!Mods.ContainsKey(mod))
            {
                throw new InvalidOperationException("Unknown or invalid mod '{0}'.".F(mod));
            }

            Console.WriteLine("Loading mod: {0}", mod);

            Sound.StopVideo();

            ModData = new ModData(Mods[mod], Mods, true);

            LocalPlayerProfile = new LocalPlayerProfile(Platform.ResolvePath(Path.Combine("^", Settings.Game.AuthProfile)), ModData.Manifest.Get <PlayerDatabase>());

            if (!ModData.LoadScreen.BeforeLoad())
            {
                return;
            }

            using (new PerfTimer("LoadMaps"))
                ModData.MapCache.LoadMaps();

            ModData.InitializeLoaders(ModData.DefaultFileSystem);
            Renderer.InitializeFonts(ModData);

            var grid = ModData.Manifest.Contains <MapGrid>() ? ModData.Manifest.Get <MapGrid>() : null;

            Renderer.InitializeDepthBuffer(grid);

            if (Cursor != null)
            {
                Cursor.Dispose();
            }

            if (Settings.Graphics.HardwareCursors)
            {
                try
                {
                    Cursor = new HardwareCursor(ModData.CursorProvider);
                }
                catch (Exception e)
                {
                    Log.Write("debug", "Failed to initialize hardware cursors. Falling back to software cursors.");
                    Log.Write("debug", "Error was: " + e.Message);

                    Console.WriteLine("Failed to initialize hardware cursors. Falling back to software cursors.");
                    Console.WriteLine("Error was: " + e.Message);

                    Cursor = new SoftwareCursor(ModData.CursorProvider);
                }
            }
            else
            {
                Cursor = new SoftwareCursor(ModData.CursorProvider);
            }

            PerfHistory.Items["render"].HasNormalTick         = false;
            PerfHistory.Items["batches"].HasNormalTick        = false;
            PerfHistory.Items["render_widgets"].HasNormalTick = false;
            PerfHistory.Items["render_flip"].HasNormalTick    = false;

            JoinLocal();

            try
            {
                if (discoverNat != null)
                {
                    discoverNat.Wait();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("NAT discovery failed: {0}", e.Message);
                Log.Write("nat", e.ToString());
            }

            ChromeMetrics.TryGet("ChatMessageColor", out chatMessageColor);
            ChromeMetrics.TryGet("SystemMessageColor", out systemMessageColor);

            ModData.LoadScreen.StartGame(args);
        }
        public override void Draw()
        {
            var iconOffset = 0.5f * IconSize.ToFloat2() + IconSpriteOffset;

            timeOffset   = iconOffset - overlayFont.Measure(WidgetUtils.FormatTime(0, World.Timestep)) / 2;
            queuedOffset = new float2(4, 2);
            holdOffset   = iconOffset - overlayFont.Measure(HoldText) / 2;
            readyOffset  = iconOffset - overlayFont.Measure(ReadyText) / 2;

            if (ChromeMetrics.TryGet("InfiniteOffset", out infiniteOffset))
            {
                infiniteOffset += queuedOffset;
            }
            else
            {
                infiniteOffset = queuedOffset;
            }

            if (CurrentQueue == null)
            {
                return;
            }

            var buildableItems = CurrentQueue.BuildableItems();

            var pios = currentQueue.Actor.Owner.PlayerActor.TraitsImplementing <IProductionIconOverlay>();

            // Icons
            Game.Renderer.EnableAntialiasingFilter();
            foreach (var icon in icons.Values)
            {
                WidgetUtils.DrawSHPCentered(icon.Sprite, icon.Pos + iconOffset, icon.Palette);

                // Draw the ProductionIconOverlay's sprite
                var pio = pios.FirstOrDefault(p => p.IsOverlayActive(icon.Actor));
                if (pio != null)
                {
                    WidgetUtils.DrawSHPCentered(pio.Sprite, icon.Pos + iconOffset + pio.Offset(IconSize), worldRenderer.Palette(pio.Palette), 1f);
                }

                // Build progress
                if (icon.Queued.Count > 0)
                {
                    var first = icon.Queued[0];
                    clock.PlayFetchIndex(ClockSequence,
                                         () => (first.TotalTime - first.RemainingTime)
                                         * (clock.CurrentSequence.Length - 1) / first.TotalTime);
                    clock.Tick();

                    WidgetUtils.DrawSHPCentered(clock.Image, icon.Pos + iconOffset, icon.IconClockPalette);
                }
                else if (!buildableItems.Any(a => a.Name == icon.Name))
                {
                    WidgetUtils.DrawSHPCentered(cantBuild.Image, icon.Pos + iconOffset, icon.IconDarkenPalette);
                }
            }

            Game.Renderer.DisableAntialiasingFilter();

            // Overlays
            foreach (var icon in icons.Values)
            {
                var total = icon.Queued.Count;
                if (total > 0)
                {
                    var first   = icon.Queued[0];
                    var waiting = !CurrentQueue.IsProducing(first) && !first.Done;
                    if (first.Done)
                    {
                        if (ReadyTextStyle == ReadyTextStyleOptions.Solid || orderManager.LocalFrameNumber * worldRenderer.World.Timestep / 360 % 2 == 0)
                        {
                            overlayFont.DrawTextWithContrast(ReadyText, icon.Pos + readyOffset, Color.White, Color.Black, 1);
                        }
                        else if (ReadyTextStyle == ReadyTextStyleOptions.AlternatingColor)
                        {
                            overlayFont.DrawTextWithContrast(ReadyText, icon.Pos + readyOffset, ReadyTextAltColor, Color.Black, 1);
                        }
                    }
                    else if (first.Paused)
                    {
                        overlayFont.DrawTextWithContrast(HoldText,
                                                         icon.Pos + holdOffset,
                                                         Color.White, Color.Black, 1);
                    }
                    else if (!waiting && DrawTime)
                    {
                        overlayFont.DrawTextWithContrast(WidgetUtils.FormatTime(first.Queue.RemainingTimeActual(first), World.Timestep),
                                                         icon.Pos + timeOffset,
                                                         Color.White, Color.Black, 1);
                    }

                    if (first.Infinite && symbolFont != null)
                    {
                        symbolFont.DrawTextWithContrast(InfiniteSymbol,
                                                        icon.Pos + infiniteOffset,
                                                        Color.White, Color.Black, 1);
                    }
                    else if (total > 1 || waiting)
                    {
                        overlayFont.DrawTextWithContrast(total.ToString(),
                                                         icon.Pos + queuedOffset,
                                                         Color.White, Color.Black, 1);
                    }
                }
            }
        }
Esempio n. 18
0
        public ColorPickerLogic(Widget widget, ModData modData, World world, HSLColor initialColor, Action <HSLColor> onChange, Dictionary <string, MiniYaml> logicArgs)
        {
            string actorType;

            if (!ChromeMetrics.TryGet("ColorPickerActorType", out actorType))
            {
                actorType = "mcv";
            }

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

            if (preview != null)
            {
                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);

                    mixer.Set(new HSLColor(hue, sat, lum));
                    hueSlider.Value = hue / 255f;
                };
            }

            // 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 = initialColor.H / 255f;
            onChange(mixer.Color);

            // 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;

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

            MiniYaml yaml;

            if (logicArgs.TryGetValue("PaletteColumns", out 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 rgbColor = color.RGB;

                    var newSwatch = (ColorBlockWidget)presetColorTemplate.Clone();
                    newSwatch.GetColor  = () => rgbColor;
                    newSwatch.IsVisible = () => true;
                    newSwatch.Bounds.X  = i * newSwatch.Bounds.Width;
                    newSwatch.Bounds.Y  = j * newSwatch.Bounds.Height;
                    newSwatch.OnMouseUp = m =>
                    {
                        mixer.Set(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].RGB;
                    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);
                        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();
                };
            }
        }
        public override void Draw()
        {
            var iconOffsetToCenter = 0.5f * IconSize.ToFloat2() + IconSpriteOffset;

            timeOffset   = iconOffsetToCenter - overlayFont.Measure(WidgetUtils.FormatTime(0, World.Timestep)) / 2;
            queuedOffset = new float2(4, 2);
            holdOffset   = iconOffsetToCenter - overlayFont.Measure(HoldText) / 2;
            readyOffset  = iconOffsetToCenter - overlayFont.Measure(ReadyText) / 2;

            if (ChromeMetrics.TryGet("InfiniteOffset", out infiniteOffset))
            {
                infiniteOffset += queuedOffset;
            }
            else
            {
                infiniteOffset = queuedOffset;
            }

            if (CurrentQueue == null)
            {
                return;
            }

            var buildableItems = CurrentQueue.BuildableItems();

            var pios = currentQueue.Actor.Owner.PlayerActor.TraitsImplementing <IProductionIconOverlay>();

            // Icons
            foreach (ProductionIcon icon in icons.Values)
            {
                WidgetUtils.DrawSHPCentered(icon.Sprite, icon.Pos + iconOffsetToCenter, icon.Palette, icon.RenderSize);                 //этот метод использует размер от icon.Sprite.Size для размера в FastQuad

                // Draw the ProductionIconOverlay's sprite
                var pio = pios.FirstOrDefault(p => p.IsOverlayActive(icon.Actor));
                if (pio != null)
                {
                    WidgetUtils.DrawSHPCentered(pio.Sprite, icon.Pos + iconOffsetToCenter + pio.Offset(IconSize), worldRenderer.Palette(pio.Palette), 1f);
                }

                // Build progress
                if (icon.Queued.Count > 0)
                {
                    var first = icon.Queued[0];
                    if (1 == 2)
                    {
                        clock.PlayFetchIndex(ClockSequence,
                                             () => (first.TotalTime - first.RemainingTime) * (clock.CurrentSequence.Length - 1) / first.TotalTime);
                        clock.Tick();

                        WidgetUtils.DrawSHPCentered(clock.Image, icon.Pos + iconOffsetToCenter, icon.IconClockPalette, icon.RenderSize);
                    }
                    else
                    {
                        int    currentframe = (first.TotalTime - first.RemainingTime) * (59) / first.TotalTime;
                        float3 offs         = iconOffsetToCenter - 0.5f * icon.RenderSize.ToFloat2(); // из-за  icon.Pos + iconOffsetToCenter и DrawSHPCentered
                        Game.Renderer.Flush();                                                        // делаем, это  тут, так как рисуем вне очереди, то управляем очередью.
                        Game.Renderer.sproc.AddCommand(1, currentframe, 59, 0, 0, new int2(0, 0), icon.Pos + offs, icon.RenderSize, icon.Sprite, icon.Palette);
                        Game.Renderer.sproc.ExecCommandBuffer();
                    }
                }
                else if (!buildableItems.Any(a => a.Name == icon.Name))
                {
                    WidgetUtils.DrawSHPCentered(cantBuild.Image, icon.Pos + iconOffsetToCenter, icon.IconDarkenPalette, icon.RenderSize);
                }
            }

            // Overlays
            foreach (ProductionIcon icon in icons.Values)
            {
                var total = icon.Queued.Count;
                if (total > 0)
                {
                    var first   = icon.Queued[0];
                    var waiting = !CurrentQueue.IsProducing(first) && !first.Done;
                    if (first.Done)
                    {
                        if (ReadyTextStyle == ReadyTextStyleOptions.Solid || orderManager.LocalFrameNumber * worldRenderer.World.Timestep / 360 % 2 == 0)
                        {
                            overlayFont.DrawTextWithContrast(ReadyText, icon.Pos + readyOffset, Color.White, Color.Black, 1);
                        }
                        else if (ReadyTextStyle == ReadyTextStyleOptions.AlternatingColor)
                        {
                            overlayFont.DrawTextWithContrast(ReadyText, icon.Pos + readyOffset, ReadyTextAltColor, Color.Black, 1);
                        }
                    }
                    else if (first.Paused)
                    {
                        overlayFont.DrawTextWithContrast(HoldText,
                                                         icon.Pos + holdOffset,
                                                         Color.White, Color.Black, 1);
                    }
                    else if (!waiting && DrawTime)
                    {
                        overlayFont.DrawTextWithContrast(WidgetUtils.FormatTime(first.Queue.RemainingTimeActual(first), World.Timestep),
                                                         icon.Pos + timeOffset,
                                                         Color.White, Color.Black, 1);
                    }

                    if (first.Infinite)
                    {
                        symbolFont.DrawTextWithContrast(InfiniteSymbol,
                                                        icon.Pos + infiniteOffset,
                                                        Color.White, Color.Black, 1);
                    }
                    else if (total > 1 || waiting)
                    {
                        overlayFont.DrawTextWithContrast(total.ToString(),
                                                         icon.Pos + queuedOffset,
                                                         Color.White, Color.Black, 1);
                    }
                }
            }
        }