Пример #1
0
        /// <summary>
        /// Applies the renderer's files to the game directory.
        /// </summary>
        public void Apply()
        {
            if (!string.IsNullOrEmpty(ddrawDLLPath))
            {
                File.Copy(ProgramConstants.GetBaseResourcePath() + ddrawDLLPath,
                          ProgramConstants.GamePath + "ddraw.dll", true);
            }
            else
            {
                File.Delete(ProgramConstants.GamePath + "ddraw.dll");
            }


            if (!string.IsNullOrEmpty(ConfigFileName) && !string.IsNullOrEmpty(resConfigFileName) &&
                !File.Exists(ProgramConstants.GamePath + ConfigFileName))    // Do not overwrite settings
            {
                File.Copy(ProgramConstants.GetBaseResourcePath() + resConfigFileName,
                          ProgramConstants.GamePath + Path.GetFileName(ConfigFileName));
            }

            foreach (var file in filesToCopy)
            {
                File.Copy(ProgramConstants.GetBaseResourcePath() + file,
                          ProgramConstants.GamePath + Path.GetFileName(file), true);
            }
        }
        public void Show(Mission mission)
        {
            lblMissionName.Text = mission.GUIName.ToUpper();

            string difficultyName = ProgramConstants.DifficultyRankToName(mission.Rank);

            if (mission.DifficultyLabels != null)
            {
                difficultyName = mission.DifficultyLabels[(int)mission.Rank - 1];
            }

            if (difficultyName.Length > 1)
            {
                difficultyName = difficultyName[0].ToString() + difficultyName.ToLower().Substring(1);
            }

            lblDescription.Text = "Completed on " + difficultyName;

            starIconPanel.BackgroundTexture = rankTextures[(int)mission.Rank];

            X         = WindowManager.RenderResolutionX;
            xPos      = WindowManager.RenderResolutionX;
            lifetime  = 0.0;
            Alpha     = 1.0f;
            AlphaRate = 0f;
            WindowManager.ReorderControls();

            Enable();
        }
        private void GetRenderers()
        {
            renderers = new List <DirectDrawWrapper>();

            var renderersIni = new IniFile(ProgramConstants.GetBaseResourcePath() + RENDERERS_INI);

            var keys = renderersIni.GetSectionKeys("Renderers");

            if (keys == null)
            {
                throw new Exception("[Renderers] not found from Renderers.ini!");
            }

            foreach (string key in keys)
            {
                string internalName = renderersIni.GetStringValue("Renderers", key, string.Empty);

                var ddWrapper = new DirectDrawWrapper(internalName, renderersIni);
                renderers.Add(ddWrapper);
            }

            OSVersion osVersion = ClientConfiguration.Instance.GetOperatingSystemVersion();

            defaultRenderer = renderersIni.GetStringValue("DefaultRenderer", osVersion.ToString(), string.Empty);

            if (defaultRenderer == null)
            {
                throw new Exception("Invalid or missing default renderer for operating system: " + osVersion);
            }
        }
Пример #4
0
        private List <CnCNetGame> GetCustomGames(List <CnCNetGame> existingGames)
        {
            IniFile iniFile = new IniFile(ProgramConstants.GetBaseResourcePath() + "GameCollectionConfig.ini");

            List <CnCNetGame> customGames = new List <CnCNetGame>();

            var section = iniFile.GetSection("CustomGames");

            if (section == null)
            {
                return(customGames);
            }

            HashSet <string> customGameIDs = new HashSet <string>();

            foreach (var kvp in section.Keys)
            {
                if (!iniFile.SectionExists(kvp.Value))
                {
                    continue;
                }

                string ID = iniFile.GetStringValue(kvp.Value, "InternalName", string.Empty).ToLower();

                if (string.IsNullOrEmpty(ID))
                {
                    throw new GameCollectionConfigurationException("InternalName for game " + kvp.Value + " is not defined or set to an empty value.");
                }

                if (ID.Length > ProgramConstants.GAME_ID_MAX_LENGTH)
                {
                    throw new GameCollectionConfigurationException("InternalGame for game " + kvp.Value + " is set to a value that exceeds length limit of " +
                                                                   ProgramConstants.GAME_ID_MAX_LENGTH + " characters.");
                }

                if (existingGames.Find(g => g.InternalName == ID) != null || customGameIDs.Contains(ID))
                {
                    throw new GameCollectionConfigurationException("Game with InternalName " + ID.ToUpper() + " already exists in the game collection.");
                }

                string iconFilename = iniFile.GetStringValue(kvp.Value, "IconFilename", ID + "icon.png");
                customGames.Add(new CnCNetGame
                {
                    InternalName         = ID,
                    UIName               = iniFile.GetStringValue(kvp.Value, "UIName", ID.ToUpper()),
                    ChatChannel          = GetIRCChannelNameFromIniFile(iniFile, kvp.Value, "ChatChannel"),
                    GameBroadcastChannel = GetIRCChannelNameFromIniFile(iniFile, kvp.Value, "GameBroadcastChannel"),
                    ClientExecutableName = iniFile.GetStringValue(kvp.Value, "ClientExecutableName", string.Empty),
                    RegistryInstallPath  = iniFile.GetStringValue(kvp.Value, "RegistryInstallPath", "HKCU\\Software\\"
                                                                  + ID.ToUpper()),
                    Texture = AssetLoader.AssetExists(iconFilename) ? AssetLoader.LoadTexture(iconFilename) :
                              AssetLoader.TextureFromImage(Resources.unknownicon)
                });
                customGameIDs.Add(ID);
            }

            return(customGames);
        }
        /// <summary>
        /// Reads game commands from an INI file.
        /// </summary>
        private void ReadGameCommands()
        {
            var gameCommandsIni = new IniFile(ProgramConstants.GetBaseResourcePath() + KEYBOARD_COMMANDS_INI);

            List <string> sections = gameCommandsIni.GetSections();

            foreach (string sectionName in sections)
            {
                gameCommands.Add(new GameCommand(gameCommandsIni.GetSection(sectionName)));
            }
        }
Пример #6
0
        public override void Initialize()
        {
            if (_initialized)
            {
                throw new InvalidOperationException("INItializableWindow cannot be initialized twice.");
            }

            string iniFileName = string.IsNullOrWhiteSpace(IniNameOverride) ? Name : IniNameOverride;

            var    dsc           = Path.DirectorySeparatorChar;
            string configIniPath = ProgramConstants.GetResourcePath() + iniFileName + ".ini";

            if (!File.Exists(configIniPath))
            {
                configIniPath = ProgramConstants.GetBaseResourcePath() + iniFileName + ".ini";

                if (!File.Exists(configIniPath))
                {
                    base.Initialize();
                    return;
                    // throw new FileNotFoundException("Config INI not found: " + configIniPath);
                }
            }

            ConfigIni = new CCIniFile(configIniPath);

            if (Parser.Instance == null)
            {
                new Parser(WindowManager);
            }

            Parser.Instance.SetPrimaryControl(this);
            ReadINIForControl(this);
            ReadLateAttributesForControl(this);

            ParseExtraControls();

            base.Initialize();

            // if (hasCloseButton)
            // {
            //     var closeButton = new EditorButton(WindowManager);
            //     closeButton.Name = "btnCloseX";
            //     closeButton.Width = Constants.UIButtonHeight;
            //     closeButton.Height = Constants.UIButtonHeight;
            //     closeButton.Text = "X";
            //     closeButton.X = Width - closeButton.Width;
            //     closeButton.Y = 0;
            //     AddChild(closeButton);
            //     closeButton.LeftClick += (s, e) => Hide();
            // }

            _initialized = true;
        }
        private void GetFileListFromConfig()
        {
            IniFile       filenamesconfig = new IniFile(ProgramConstants.GetBaseResourcePath() + CONFIGNAME);
            List <string> filenames       = filenamesconfig.GetSectionKeys("FilenameList");

            if (filenames == null || filenames.Count < 1)
            {
                return;
            }
            filenames.Add("INI\\GlobalCode.ini");
            filenames.Add(ProgramConstants.BASE_RESOURCE_PATH + CONFIGNAME);
            fileNamesToCheck = filenames.ToArray();
        }
        public void CalculateHashes(List <GameMode> gameModes)
        {
            fh = new FileHashes
            {
                GameOptionsHash = Utilities.CalculateSHA1ForFile(ProgramConstants.GamePath + ProgramConstants.BASE_RESOURCE_PATH + "GameOptions.ini"),
                ClientDXHash    = Utilities.CalculateSHA1ForFile(ProgramConstants.GetBaseResourcePath() + "clientdx.exe"),
                ClientXNAHash   = Utilities.CalculateSHA1ForFile(ProgramConstants.GetBaseResourcePath() + "clientxna.exe"),
                ClientOGLHash   = Utilities.CalculateSHA1ForFile(ProgramConstants.GetBaseResourcePath() + "clientogl.exe"),
                MainExeHash     = Utilities.CalculateSHA1ForFile(ProgramConstants.GamePath + ClientConfiguration.Instance.GetGameExecutableName()),
                LauncherExeHash = Utilities.CalculateSHA1ForFile(ProgramConstants.GamePath + ClientConfiguration.Instance.GetGameLauncherExecutableName),
                MPMapsHash      = Utilities.CalculateSHA1ForFile(ProgramConstants.GamePath + ClientConfiguration.Instance.MPMapsIniPath),
                INIHashes       = string.Empty
            };

            foreach (string filePath in fileNamesToCheck)
            {
                fh.INIHashes = AddToStringIfFileExists(fh.INIHashes, filePath);
                Logger.Log("Hash for " + filePath + ": " +
                           Utilities.CalculateSHA1ForFile(ProgramConstants.GamePath + filePath));
            }

            #if !YR
            if (Directory.Exists(ProgramConstants.GamePath + "INI\\Map Code"))
            {
                foreach (GameMode gameMode in gameModes)
                {
                    fh.INIHashes = AddToStringIfFileExists(fh.INIHashes, "INI\\Map Code\\" + gameMode.Name + ".ini");
                    Logger.Log("Hash for INI\\Map Code\\" + gameMode.Name + ".ini :" +
                               Utilities.CalculateSHA1ForFile(ProgramConstants.GamePath + "INI\\Map Code\\" + gameMode.Name + ".ini"));
                }
            }
            #endif

            if (Directory.Exists(ProgramConstants.GamePath + "INI\\Game Options"))
            {
                List <string> files = Directory.GetFiles(
                    ProgramConstants.GamePath + "INI\\Game Options",
                    "*", SearchOption.AllDirectories).ToList();

                files.Sort();

                foreach (string fileName in files)
                {
                    fh.INIHashes = fh.INIHashes + Utilities.CalculateSHA1ForFile(fileName);
                    Logger.Log("Hash for " + fileName + ": " +
                               Utilities.CalculateSHA1ForFile(fileName));
                }
            }

            fh.INIHashes = Utilities.CalculateSHA1ForString(fh.INIHashes);
        }
        private void GetRenderers()
        {
            renderers = new List <DirectDrawWrapper>();

            var renderersIni = new IniFile(ProgramConstants.GetBaseResourcePath() + RENDERERS_INI);

            var keys = renderersIni.GetSectionKeys("Renderers");

            if (keys == null)
            {
                throw new Exception("[Renderers] not found from Renderers.ini!");
            }

            foreach (string key in keys)
            {
                string internalName = renderersIni.GetStringValue("Renderers", key, string.Empty);

                var ddWrapper = new DirectDrawWrapper(internalName, renderersIni);
                renderers.Add(ddWrapper);
            }

            OSVersion osVersion = ClientConfiguration.Instance.GetOperatingSystemVersion();

            defaultRenderer = renderersIni.GetStringValue("DefaultRenderer", osVersion.ToString(), string.Empty);

            if (defaultRenderer == null)
            {
                throw new Exception("Invalid or missing default renderer for operating system: " + osVersion);
            }


            string renderer = UserINISettings.Instance.Renderer;

            selectedRenderer = renderers.Find(r => r.InternalName == renderer);

            if (selectedRenderer == null)
            {
                selectedRenderer = renderers.Find(r => r.InternalName == defaultRenderer);
            }

            if (selectedRenderer == null)
            {
                throw new Exception("Missing renderer: " + renderer);
            }

            GameProcessLogic.UseQres            = selectedRenderer.UseQres;
            GameProcessLogic.SingleCoreAffinity = selectedRenderer.SingleCoreAffinity;
        }
        private void ParseConfigFile()
        {
            IniFile config = new IniFile(ProgramConstants.GetBaseResourcePath() + CONFIGNAME);
            calculateGameExeHash = config.GetBooleanValue("Settings", "CalculateGameExeHash", true);

            List<string> keys = config.GetSectionKeys("FilenameList");
            if (keys == null || keys.Count < 1)
                return;

            List<string> filenames = new List<string>();
            foreach (string key in keys)
            {
                string value = config.GetStringValue("FilenameList", key, string.Empty);
                filenames.Add(value == string.Empty ? key : value);
            }

            fileNamesToCheck = filenames.ToArray();
        }
Пример #11
0
        /// <summary>
        /// Reads the properties of this DirectDrawWrapper from an INI section.
        /// </summary>
        /// <param name="section">The INI section.</param>
        private void Parse(IniSection section)
        {
            if (section == null)
            {
                throw new ArgumentException("Configuration for renderer '" + InternalName + "' not found!");
            }

            UIName         = section.GetStringValue("UIName", "Unnamed renderer");
            IsDxWnd        = section.GetBooleanValue("IsDxWnd", false);
            ddrawDLLPath   = section.GetStringValue("DLLName", string.Empty);
            configFileName = section.GetStringValue("ConfigFileName", string.Empty);

            filesToCopy = section.GetStringValue("AdditionalFiles", string.Empty).Split(
                new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();

            string[] disallowedOSs = section.GetStringValue("DisallowedOperatingSystems", string.Empty).Split(
                new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (string os in disallowedOSs)
            {
                OSVersion disallowedOS = (OSVersion)Enum.Parse(typeof(OSVersion), os.Trim());
                disallowedOSList.Add(disallowedOS);
            }

            if (!string.IsNullOrEmpty(ddrawDLLPath) &&
                !File.Exists(ProgramConstants.GetBaseResourcePath() + ddrawDLLPath))
            {
                throw new FileNotFoundException("File specified in DLLPath= for renderer '" + InternalName + "' does not exist!");
            }

            if (!string.IsNullOrEmpty(configFileName) &&
                !File.Exists(ProgramConstants.GetBaseResourcePath() + configFileName))
            {
                throw new FileNotFoundException("File specified in ConfigFileName= for renderer '" + InternalName + "' does not exist!");
            }

            foreach (var file in filesToCopy)
            {
                if (!File.Exists(ProgramConstants.GetBaseResourcePath() + file))
                {
                    throw new FileNotFoundException("Additional file '" + file + "' for renderer '" + InternalName + "' does not exist!");
                }
            }
        }
Пример #12
0
 protected virtual void SetAttributesFromIni()
 {
     if (File.Exists(ProgramConstants.GetResourcePath() + Name + ".ini"))
     {
         GetINIAttributes(new CCIniFile(ProgramConstants.GetResourcePath() + Name + ".ini"));
     }
     else if (File.Exists(ProgramConstants.GetBaseResourcePath() + Name + ".ini"))
     {
         GetINIAttributes(new CCIniFile(ProgramConstants.GetBaseResourcePath() + Name + ".ini"));
     }
     else if (File.Exists(ProgramConstants.GetResourcePath() + GENERIC_WINDOW_INI))
     {
         GetINIAttributes(new CCIniFile(ProgramConstants.GetResourcePath() + GENERIC_WINDOW_INI));
     }
     else
     {
         GetINIAttributes(new CCIniFile(ProgramConstants.GetBaseResourcePath() + GENERIC_WINDOW_INI));
     }
 }
        private List <CnCNetGame> GetCustomGames(List <CnCNetGame> existingGames)
        {
            IniFile iniFile = new IniFile(ProgramConstants.GetBaseResourcePath() + "GameCollectionConfig.ini");

            List <CnCNetGame> customGames = new List <CnCNetGame>();

            var section = iniFile.GetSection("CustomGames");

            if (section == null)
            {
                return(customGames);
            }

            HashSet <string> customGameIDs = new HashSet <string>();

            foreach (var kvp in section.Keys)
            {
                string ID = iniFile.GetStringValue(kvp.Value, "InternalName", string.Empty).ToLower();
                if (string.IsNullOrEmpty(ID) || existingGames.Find(g => g.InternalName == ID) != null ||
                    customGameIDs.Contains(ID))
                {
                    continue;
                }
                string iconFilename = iniFile.GetStringValue(kvp.Value, "IconFilename", ID + "icon.png");
                customGames.Add(new CnCNetGame
                {
                    InternalName         = ID,
                    UIName               = iniFile.GetStringValue(kvp.Value, "UIName", ID.ToUpper()),
                    ChatChannel          = iniFile.GetStringValue(kvp.Value, "ChatChannel", string.Empty),
                    GameBroadcastChannel = iniFile.GetStringValue(kvp.Value, "GameBroadcastChannel", string.Empty),
                    ClientExecutableName = iniFile.GetStringValue(kvp.Value, "ClientExecutableName", string.Empty),
                    RegistryInstallPath  = iniFile.GetStringValue(kvp.Value, "RegistryInstallPath", "HKCU\\Software\\"
                                                                  + ID.ToUpper()),
                    Texture = AssetLoader.AssetExists(iconFilename) ? AssetLoader.LoadTexture(iconFilename) :
                              AssetLoader.TextureFromImage(Resources.unknownicon)
                });
                customGameIDs.Add(ID);
            }

            return(customGames);
        }
Пример #14
0
        /// <summary>
        /// Returns the available multiplayer colors.
        /// </summary>
        public static List <MultiplayerColor> LoadColors()
        {
            if (colorList != null)
            {
                return(new List <MultiplayerColor>(colorList));
            }

            IniFile gameOptionsIni = new IniFile(ProgramConstants.GetBaseResourcePath() + "GameOptions.ini");

            List <MultiplayerColor> mpColors = new List <MultiplayerColor>();

            List <string> colorKeys = gameOptionsIni.GetSectionKeys("MPColors");

            if (colorKeys == null)
            {
                throw new InvalidINIFileException("[MPColors] not found in GameOptions.ini!");
            }

            foreach (string key in colorKeys)
            {
                string[] values = gameOptionsIni.GetStringValue("MPColors", key, "255,255,255,0").Split(',');

                try
                {
                    MultiplayerColor mpColor = MultiplayerColor.CreateFromStringArray(key, values);

                    mpColors.Add(mpColor);
                }
                catch
                {
                    throw new Exception("Invalid MPColor specified in GameOptions.ini: " + key);
                }
            }

            colorList = mpColors;
            return(new List <MultiplayerColor>(colorList));
        }
Пример #15
0
        /// <summary>
        /// Reads the properties of this DirectDrawWrapper from an INI section.
        /// </summary>
        /// <param name="section">The INI section.</param>
        private void Parse(IniSection section)
        {
            if (section == null)
            {
                Logger.Log("DirectDrawWrapper: Configuration for renderer '" + InternalName + "' not found!");
                return;
            }

            UIName = section.GetStringValue("UIName", "Unnamed renderer");

            if (section.GetBooleanValue("IsDxWnd", false))
            {
                // For backwards compatibility with previous client versions
                WindowedModeSection       = "DxWnd";
                WindowedModeKey           = "RunInWindow";
                BorderlessWindowedModeKey = "NoWindowFrame";
            }

            WindowedModeSection                 = section.GetStringValue("WindowedModeSection", WindowedModeSection);
            WindowedModeKey                     = section.GetStringValue("WindowedModeKey", WindowedModeKey);
            BorderlessWindowedModeKey           = section.GetStringValue("BorderlessWindowedModeKey", BorderlessWindowedModeKey);
            IsBorderlessWindowedModeKeyReversed = section.GetBooleanValue("IsBorderlessWindowedModeKeyReversed",
                                                                          IsBorderlessWindowedModeKeyReversed);

            if (BorderlessWindowedModeKey != null && WindowedModeSection == null)
            {
                throw new DirectDrawWrapperConfigurationException(
                          "BorderlessWindowedModeKey= is defined for renderer" +
                          $" {InternalName} but WindowedModeSection= is not!");
            }

            Hidden             = section.GetBooleanValue("Hidden", false);
            UseQres            = section.GetBooleanValue("UseQres", UseQres);
            SingleCoreAffinity = section.GetBooleanValue("SingleCoreAffinity", SingleCoreAffinity);
            ddrawDLLPath       = section.GetStringValue("DLLName", string.Empty);
            ConfigFileName     = section.GetStringValue("ConfigFileName", string.Empty);
            resConfigFileName  = section.GetStringValue("ResConfigFileName", ConfigFileName);

            filesToCopy = section.GetStringValue("AdditionalFiles", string.Empty).Split(
                new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();

            string[] disallowedOSs = section.GetStringValue("DisallowedOperatingSystems", string.Empty).Split(
                new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (string os in disallowedOSs)
            {
                OSVersion disallowedOS = (OSVersion)Enum.Parse(typeof(OSVersion), os.Trim());
                disallowedOSList.Add(disallowedOS);
            }

            if (!string.IsNullOrEmpty(ddrawDLLPath) &&
                !File.Exists(ProgramConstants.GetBaseResourcePath() + ddrawDLLPath))
            {
                Logger.Log("DirectDrawWrapper: File specified in DLLPath= for renderer '" + InternalName + "' does not exist!");
            }

            if (!string.IsNullOrEmpty(resConfigFileName) &&
                !File.Exists(ProgramConstants.GetBaseResourcePath() + resConfigFileName))
            {
                Logger.Log("DirectDrawWrapper: File specified in ConfigFileName= for renderer '" + InternalName + "' does not exist!");
            }

            foreach (var file in filesToCopy)
            {
                if (!File.Exists(ProgramConstants.GetBaseResourcePath() + file))
                {
                    Logger.Log("DirectDrawWrapper: Additional file '" + file + "' for renderer '" + InternalName + "' does not exist!");
                }
            }
        }
        private void LbGameList_SelectedIndexChanged(object sender, EventArgs e)
        {
            lbGameStatistics.ClearItems();

            if (lbGameList.SelectedIndex == -1)
            {
                return;
            }

            MatchStatistics ms = sm.GetMatchByIndex(listedGameIndexes[lbGameList.SelectedIndex]);

            List <PlayerStatistics> players = new List <PlayerStatistics>();

            for (int i = 0; i < ms.GetPlayerCount(); i++)
            {
                players.Add(ms.GetPlayer(i));
            }

            players = players.OrderBy(p => p.Score).Reverse().ToList();

            Color textColor = UISettings.ActiveSettings.AltColor;

            for (int i = 0; i < ms.GetPlayerCount(); i++)
            {
                PlayerStatistics ps = players[i];

                //List<string> items = new List<string>();
                List <XNAListBoxItem> items = new List <XNAListBoxItem>();

                if (ps.Color > -1 && ps.Color < mpColors.Count)
                {
                    textColor = mpColors[ps.Color].XnaColor;
                }

                if (ps.IsAI)
                {
                    items.Add(new XNAListBoxItem(ProgramConstants.GetAILevelName(ps.AILevel), textColor));
                }
                else
                {
                    items.Add(new XNAListBoxItem(ps.Name, textColor));
                }

                if (ps.WasSpectator)
                {
                    // Player was a spectator
                    items.Add(new XNAListBoxItem("-", textColor));
                    items.Add(new XNAListBoxItem("-", textColor));
                    items.Add(new XNAListBoxItem("-", textColor));
                    items.Add(new XNAListBoxItem("-", textColor));
                    items.Add(new XNAListBoxItem("-", textColor));
                    XNAListBoxItem spectatorItem = new XNAListBoxItem();
                    spectatorItem.Text      = "Spectator";
                    spectatorItem.TextColor = textColor;
                    spectatorItem.Texture   = sideTextures[sideTextures.Length - 1];
                    items.Add(spectatorItem);
                    items.Add(new XNAListBoxItem("-", textColor));
                }
                else
                {
                    if (!ms.SawCompletion)
                    {
                        // The game wasn't completed - we don't know the stats
                        items.Add(new XNAListBoxItem("-", textColor));
                        items.Add(new XNAListBoxItem("-", textColor));
                        items.Add(new XNAListBoxItem("-", textColor));
                        items.Add(new XNAListBoxItem("-", textColor));
                        items.Add(new XNAListBoxItem("-", textColor));
                    }
                    else
                    {
                        // The game was completed and the player was actually playing
                        items.Add(new XNAListBoxItem(ps.Kills.ToString(), textColor));
                        items.Add(new XNAListBoxItem(ps.Losses.ToString(), textColor));
                        items.Add(new XNAListBoxItem(ps.Economy.ToString(), textColor));
                        items.Add(new XNAListBoxItem(ps.Score.ToString(), textColor));
                        items.Add(new XNAListBoxItem(
                                      Conversions.BooleanToString(ps.Won, BooleanStringStyle.YESNO), textColor));
                    }

                    if (ps.Side == 0 || ps.Side > sides.Length)
                    {
                        items.Add(new XNAListBoxItem("Unknown", textColor));
                    }
                    else
                    {
                        XNAListBoxItem sideItem = new XNAListBoxItem();
                        sideItem.Text      = sides[ps.Side - 1];
                        sideItem.TextColor = textColor;
                        sideItem.Texture   = sideTextures[ps.Side - 1];
                        items.Add(sideItem);
                    }

                    items.Add(new XNAListBoxItem(TeamIndexToString(ps.Team), textColor));
                }

                if (!ps.IsLocalPlayer)
                {
                    lbGameStatistics.AddItem(items);

                    items.ForEach(item => item.Selectable = false);
                }
                else
                {
                    lbGameStatistics.AddItem(items);
                    lbGameStatistics.SelectedIndex = i;
                }
            }
        }
Пример #17
0
        protected override void Initialize()
        {
            Logger.Log("Initializing GameClass.");

            base.Initialize();

            string primaryNativeCursorPath     = ProgramConstants.GetResourcePath() + "cursor.cur";
            string alternativeNativeCursorPath = ProgramConstants.GetBaseResourcePath() + "cursor.cur";

            AssetLoader.Initialize(GraphicsDevice, content);
            AssetLoader.AssetSearchPaths.Add(ProgramConstants.GetResourcePath());
            AssetLoader.AssetSearchPaths.Add(ProgramConstants.GetBaseResourcePath());
            AssetLoader.AssetSearchPaths.Add(ProgramConstants.GamePath);

            InitializeUISettings();

            WindowManager wm = new WindowManager(this, graphics);

            wm.Initialize(content, ProgramConstants.GetBaseResourcePath());

            int windowWidth  = UserINISettings.Instance.ClientResolutionX;
            int windowHeight = UserINISettings.Instance.ClientResolutionY;

            if (Screen.PrimaryScreen.Bounds.Width >= windowWidth && Screen.PrimaryScreen.Bounds.Height >= windowHeight)
            {
                if (!wm.InitGraphicsMode(windowWidth, windowHeight, false))
                {
                    throw new Exception("Setting graphics mode failed! " + windowWidth + "x" + windowHeight);
                }
            }
            else
            {
                if (!wm.InitGraphicsMode(1024, 600, false))
                {
                    throw new Exception("Setting default graphics mode failed!");
                }
            }

            int renderResolutionX = Math.Max(windowWidth, ClientConfiguration.Instance.MinimumRenderWidth);
            int renderResolutionY = Math.Max(windowHeight, ClientConfiguration.Instance.MinimumRenderHeight);

            renderResolutionX = Math.Min(renderResolutionX, ClientConfiguration.Instance.MaximumRenderWidth);
            renderResolutionY = Math.Min(renderResolutionY, ClientConfiguration.Instance.MaximumRenderHeight);

            wm.SetBorderlessMode(UserINISettings.Instance.BorderlessWindowedClient);
            wm.CenterOnScreen();
            wm.SetRenderResolution(renderResolutionX, renderResolutionY);
            wm.SetIcon(ProgramConstants.GetBaseResourcePath() + "clienticon.ico");

            wm.SetControlBox(true);

            wm.Cursor.Textures = new Texture2D[]
            {
                AssetLoader.LoadTexture("cursor.png"),
                AssetLoader.LoadTexture("waitCursor.png")
            };

            if (File.Exists(primaryNativeCursorPath))
            {
                wm.Cursor.LoadNativeCursor(primaryNativeCursorPath);
            }
            else if (File.Exists(alternativeNativeCursorPath))
            {
                wm.Cursor.LoadNativeCursor(alternativeNativeCursorPath);
            }

            Components.Add(wm);

            string playerName = UserINISettings.Instance.PlayerName.Value.Trim();

            if (UserINISettings.Instance.AutoRemoveUnderscoresFromName)
            {
                while (playerName.EndsWith("_"))
                {
                    playerName = playerName.Substring(0, playerName.Length - 1);
                }
            }

            if (string.IsNullOrEmpty(playerName))
            {
                playerName = WindowsIdentity.GetCurrent().Name;

                playerName = playerName.Substring(playerName.IndexOf("\\") + 1);
            }

            playerName = playerName.Replace(",", string.Empty);
            playerName = Renderer.GetSafeString(playerName, 0);
            playerName.Trim();
            int maxNameLength = ClientConfiguration.Instance.MaxNameLength;

            if (playerName.Length > maxNameLength)
            {
                playerName = playerName.Substring(0, maxNameLength);
            }

            ProgramConstants.PLAYERNAME = playerName;
            UserINISettings.Instance.PlayerName.Value = playerName;

            LoadingScreen ls = new LoadingScreen(wm);

            wm.AddAndInitializeControl(ls);
            ls.ClientRectangle = new Rectangle((renderResolutionX - ls.ClientRectangle.Width) / 2,
                                               (renderResolutionY - ls.ClientRectangle.Height) / 2, ls.ClientRectangle.Width, ls.ClientRectangle.Height);
        }
        private void ListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lbSaveGameList.SelectedIndex == -1)
            {
                btnLaunch.AllowClick = false;
                btnDelete.AllowClick = false;
                ClearSaveInformation(string.Empty);
                return;
            }

            btnLaunch.AllowClick = true;
            btnDelete.AllowClick = true;

            SavedGame sg = savedGames[lbSaveGameList.SelectedIndex];

            if (sg.SessionInfo == null)
            {
                ClearSaveInformation(string.Empty);
                lblSessionTypeValue.Text = "Unknown";
                return;
            }

            switch (sg.SessionInfo.SessionType)
            {
            case GameSessionType.SKIRMISH:
                ClearSaveInformation(string.Empty);
                lblSessionTypeValue.Text = "Skirmish";
                break;

            case GameSessionType.MULTIPLAYER:
                ClearSaveInformation(string.Empty);
                lblSessionTypeValue.Text = "Multiplayer";
                break;

            case GameSessionType.SINGLEPLAYER:
                var mission = CampaignHandler.Instance.Missions.Find(m => m.InternalName == sg.SessionInfo.MissionInternalName);
                if (mission == null)
                {
                    ClearSaveInformation("Unknown");
                }
                else
                {
                    string difficultyName = ProgramConstants.DifficultyRankToName(sg.SessionInfo.Difficulty);
                    if (mission.DifficultyLabels != null)
                    {
                        difficultyName = mission.DifficultyLabels[(int)sg.SessionInfo.Difficulty - 1];
                    }

                    if (difficultyName.Length > 1)
                    {
                        difficultyName = difficultyName[0].ToString() + difficultyName.ToLower().Substring(1);
                    }

                    string globalFlagInfo;

                    if (sg.SessionInfo.GlobalFlagValues != null)
                    {
                        globalFlagInfo = string.Empty;

                        foreach (var kvp in sg.SessionInfo.GlobalFlagValues)
                        {
                            int  globalFlagIndex = kvp.Key;
                            bool enabled         = kvp.Value;

                            if (CampaignHandler.Instance.GlobalVariables.Count > globalFlagIndex)
                            {
                                var globalVariable = CampaignHandler.Instance.GlobalVariables[globalFlagIndex];
                                globalFlagInfo += globalVariable.UIName + ": " + (enabled ? "Yes" : "No");
                            }
                            else
                            {
                                globalFlagInfo += "(Unknown variable) " + globalFlagIndex + ": " + (enabled ? "Yes" : "No");
                            }

                            globalFlagInfo += Environment.NewLine;
                        }
                    }
                    else
                    {
                        globalFlagInfo = "None";
                    }

                    lblMissionNameValue.Text     = mission.GUIName;
                    lblDifficultyLevelValue.Text = difficultyName;
                    lblGlobalFlagsValue.Text     = globalFlagInfo;
                }

                lblSessionTypeValue.Text = "Singleplayer";

                break;
            }
        }
Пример #19
0
        public void CalculateHashes(List <GameMode> gameModes)
        {
            fh = new FileHashes
            {
                GameOptionsHash = Utilities.CalculateSHA1ForFile(ProgramConstants.GamePath + ProgramConstants.BASE_RESOURCE_PATH + "GameOptions.ini"),
                ClientDXHash    = Utilities.CalculateSHA1ForFile(ProgramConstants.GetBaseResourcePath() + "clientdx.exe"),
                ClientXNAHash   = Utilities.CalculateSHA1ForFile(ProgramConstants.GetBaseResourcePath() + "clientxna.exe"),
                ClientOGLHash   = Utilities.CalculateSHA1ForFile(ProgramConstants.GetBaseResourcePath() + "clientogl.exe"),
                GameExeHash     = calculateGameExeHash ?
                                  Utilities.CalculateSHA1ForFile(ProgramConstants.GamePath + ClientConfiguration.Instance.GetGameExecutableName()) : string.Empty,
                LauncherExeHash = Utilities.CalculateSHA1ForFile(ProgramConstants.GamePath + ClientConfiguration.Instance.GameLauncherExecutableName),
                MPMapsHash      = Utilities.CalculateSHA1ForFile(ProgramConstants.GamePath + ClientConfiguration.Instance.MPMapsIniPath),
                FHCConfigHash   = Utilities.CalculateSHA1ForFile(ProgramConstants.BASE_RESOURCE_PATH + CONFIGNAME),
                INIHashes       = string.Empty
            };

            Logger.Log("Hash for " + ProgramConstants.BASE_RESOURCE_PATH + CONFIGNAME + ": " + fh.FHCConfigHash);
            Logger.Log("Hash for " + ProgramConstants.BASE_RESOURCE_PATH + "GameOptions.ini: " + fh.GameOptionsHash);
            Logger.Log("Hash for " + ProgramConstants.BASE_RESOURCE_PATH + "clientdx.exe: " + fh.ClientDXHash);
            Logger.Log("Hash for " + ProgramConstants.BASE_RESOURCE_PATH + "clientxna.exe: " + fh.ClientXNAHash);
            Logger.Log("Hash for " + ProgramConstants.BASE_RESOURCE_PATH + "clientogl.exe: " + fh.ClientOGLHash);
            Logger.Log("Hash for " + ClientConfiguration.Instance.MPMapsIniPath + ": " + fh.MPMapsHash);
            if (calculateGameExeHash)
            {
                Logger.Log("Hash for " + ClientConfiguration.Instance.GetGameExecutableName() + ": " + fh.GameExeHash);
            }
            if (!string.IsNullOrEmpty(ClientConfiguration.Instance.GameLauncherExecutableName))
            {
                Logger.Log("Hash for " + ClientConfiguration.Instance.GameLauncherExecutableName + ": " + fh.LauncherExeHash);
            }

            foreach (string filePath in fileNamesToCheck)
            {
                fh.INIHashes = AddToStringIfFileExists(fh.INIHashes, filePath);
                Logger.Log("Hash for " + filePath + ": " +
                           Utilities.CalculateSHA1ForFile(ProgramConstants.GamePath + filePath));
            }

            string[] iniPaths = new string[]
            {
#if !YR
                ProgramConstants.GamePath + "INI/Map Code",
#endif
                ProgramConstants.GamePath + "INI/Game Options"
            };

            foreach (string path in iniPaths)
            {
                if (!string.IsNullOrEmpty(path) && Directory.Exists(path))
                {
                    List <string> files = Directory.GetFiles(path, "*", SearchOption.AllDirectories).
                                          Select(s => s.Replace(ProgramConstants.GamePath, "").Replace("\\", "/")).ToList();

                    files.Sort();

                    foreach (string filename in files)
                    {
                        string sha1 = Utilities.CalculateSHA1ForFile(ProgramConstants.GamePath + filename);
                        fh.INIHashes += sha1;
                        Logger.Log("Hash for " + filename + ": " + sha1);
                    }
                }
            }

            fh.INIHashes = Utilities.CalculateSHA1ForString(fh.INIHashes);
        }
Пример #20
0
        protected override void Initialize()
        {
            Logger.Log("Initializing GameClass.");

            string windowTitle = ClientConfiguration.Instance.WindowTitle;

            Window.Title = string.IsNullOrEmpty(windowTitle) ?
                           string.Format("{0} Client", MainClientConstants.GAME_NAME_SHORT) : windowTitle;

            base.Initialize();

            string primaryNativeCursorPath     = ProgramConstants.GetResourcePath() + "cursor.cur";
            string alternativeNativeCursorPath = ProgramConstants.GetBaseResourcePath() + "cursor.cur";

            AssetLoader.Initialize(GraphicsDevice, content);
            AssetLoader.AssetSearchPaths.Add(ProgramConstants.GetResourcePath());
            AssetLoader.AssetSearchPaths.Add(ProgramConstants.GetBaseResourcePath());
            AssetLoader.AssetSearchPaths.Add(ProgramConstants.GamePath);

#if !XNA && !WINDOWSGL
            // Try to create and load a texture to check for MonoGame 3.7.1 compatibility
            try
            {
                Texture2D texture    = new Texture2D(GraphicsDevice, 100, 100, false, SurfaceFormat.Color);
                Color[]   colorArray = new Color[100 * 100];
                texture.SetData(colorArray);

                UISettings.ActiveSettings.CheckBoxClearTexture = AssetLoader.LoadTextureUncached("checkBoxClear.png");
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("DeviceRemoved"))
                {
                    Logger.Log("Creating texture on startup failed! Creating .dxfail file and re-launching client launcher.");

                    if (!Directory.Exists(ProgramConstants.GamePath + "Client"))
                    {
                        Directory.CreateDirectory(ProgramConstants.GamePath + "Client");
                    }

                    // Create .dxfail file that the launcher can check for this error
                    // and handle it by redirecting the user to the XNA version instead

                    File.WriteAllBytes(ProgramConstants.GamePath + "Client" + Path.DirectorySeparatorChar + ".dxfail",
                                       new byte[] { 1 });

                    string launcherExe = ClientConfiguration.Instance.LauncherExe;
                    if (string.IsNullOrEmpty(launcherExe))
                    {
                        // LauncherExe is unspecified, just throw the exception forward
                        // because we can't handle it

                        Logger.Log("No LauncherExe= specified in ClientDefinitions.ini! " +
                                   "Forwarding exception to regular exception handler.");

                        throw ex;
                    }
                    else
                    {
                        Logger.Log("Starting " + launcherExe + " and exiting.");

                        Process.Start(ProgramConstants.GamePath + launcherExe);
                        Environment.Exit(0);
                    }
                }
            }
#endif

            InitializeUISettings();

            WindowManager wm = new WindowManager(this, graphics);
            wm.Initialize(content, ProgramConstants.GetBaseResourcePath());

            SetGraphicsMode(wm);

            wm.SetIcon(ProgramConstants.GetBaseResourcePath() + "clienticon.ico");

            wm.SetControlBox(true);

            wm.Cursor.Textures = new Texture2D[]
            {
                AssetLoader.LoadTexture("cursor.png"),
                AssetLoader.LoadTexture("waitCursor.png")
            };

            if (File.Exists(primaryNativeCursorPath))
            {
                wm.Cursor.LoadNativeCursor(primaryNativeCursorPath);
            }
            else if (File.Exists(alternativeNativeCursorPath))
            {
                wm.Cursor.LoadNativeCursor(alternativeNativeCursorPath);
            }

            Components.Add(wm);

            string playerName = UserINISettings.Instance.PlayerName.Value.Trim();

            if (UserINISettings.Instance.AutoRemoveUnderscoresFromName)
            {
                while (playerName.EndsWith("_"))
                {
                    playerName = playerName.Substring(0, playerName.Length - 1);
                }
            }

            if (string.IsNullOrEmpty(playerName))
            {
                playerName = WindowsIdentity.GetCurrent().Name;

                playerName = playerName.Substring(playerName.IndexOf("\\") + 1);
            }

            playerName = Renderer.GetSafeString(NameValidator.GetValidOfflineName(playerName), 0);

            ProgramConstants.PLAYERNAME = playerName;
            UserINISettings.Instance.PlayerName.Value = playerName;

            LoadingScreen ls = new LoadingScreen(wm);
            wm.AddAndInitializeControl(ls);
            ls.ClientRectangle = new Rectangle((wm.RenderResolutionX - ls.Width) / 2,
                                               (wm.RenderResolutionY - ls.Height) / 2, ls.Width, ls.Height);
        }