示例#1
0
        /// <summary>
        /// On récupère les informations principales, dont les chemins (EBGame, TBGame)
        /// </summary>
        /// <param name="gamePath"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        /// <remarks>
        /// Si les chemins sont vides, on conserve quand même pas de tri
        /// </remarks>
        private GamePaths GetMainsInfo(string gamePath, string file)
        {
            string xmlFile = Path.Combine(gamePath, file);

            GamePaths gpX = null;

            using (XML_Games xelGames = new XML_Games(xmlFile))
            {
                var xelG = xelGames.GetGameNode();

                gpX = GamePaths.CreateBasic(xelG);
                gpX.Complete(xelGames.GetNodes(Tag.AddApp, Tag.GameId, gpX.Id));

                // Essaie de récupération des paths
                foreach (var app in gpX.Applications)
                {
                    app.CurrentPath = SimuRelativePath(gpX.Platform, app.CurrentPath);
                }

                // ---
                gpX.ManualPath     = SimuRelativePath(gpX.Platform, gpX.ManualPath);
                gpX.MusicPath      = SimuRelativePath(gpX.Platform, gpX.MusicPath);
                gpX.VideoPath      = SimuRelativePath(gpX.Platform, gpX.VideoPath);
                gpX.ThemeVideoPath = SimuRelativePath(gpX.Platform, gpX.ThemeVideoPath);
            }

            return(gpX);
        }
示例#2
0
        public void DebugLoadFileShape(string shapeFilePath)
        {
            var output        = @"G:\NickProd\Farming Simulator 19\Temp";
            var gameDirectory = GamePaths.GetGamePath(FarmSimulatorVersion.FarmingSimulator2017);
            var realtive      = Path.GetRelativePath(gameDirectory, shapeFilePath);
            var shapeFile     = new ShapeFile(shapeFilePath);
            var index         = 0;

            try
            {
                shapeFile.ReadKnowTypes()
                .ForEach((v, i) => index = i);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            //shapeFile.ReadRawNamedShape()
            //         .ForEach(
            //             v =>
            //             {
            //                 var dirOutName = Path.Combine(output, realtive);
            //                 if (!Directory.Exists(dirOutName))
            //                 {
            //                     Directory.CreateDirectory(dirOutName);
            //                 }
            //                 File.WriteAllBytes(Path.Combine(dirOutName, $"[{v.Id}]_{FileTools.CleanFileName(v.Name)}.bin"), v.RawData);
            //             });
        }
        public void ExportShapePathTests(FarmSimulatorVersion version, string shapeFileName)
        {
            var gameMapPath = GamePaths.GetGameMapsPath(version);

            if (!Directory.Exists(gameMapPath))
            {
                var message = $"Game map path not found: \"{version}\".";
                Trace.WriteLine(message);
                Assert.Inconclusive(message);
            }

            var mapPath = Path.Combine(gameMapPath, shapeFileName);

            if (!File.Exists(mapPath))
            {
                var message = $"Map not found \"{version}\": \"{mapPath}\".";
                Trace.WriteLine(message);
                Assert.Inconclusive(message);
            }

            var xmlMapFilePath = mapPath.Replace(GameConstants.SchapesFileExtension, GameConstants.XmlMapFileExtension);
            var mapFile        = MapFile.Load(xmlMapFilePath);
            var shapePaths     = FindShapePath(mapFile)
                                 .OrderBy(v => v.Id)
                                 .ToArray();

            File.WriteAllLines(Path.Combine(Output, version.ToString(), "shapes.path"), shapePaths.Select(v => v.ToString()));
        }
示例#4
0
        public string getMapDbFilePath()
        {
            string path = Path.Combine(GamePaths.DataPath, "Maps");

            GamePaths.EnsurePathExists(path);

            return(Path.Combine(path, api.World.SavegameIdentifier + ".db"));
        }
            public void ShouldBuildStringCorrectly(GameFolder folder, string expectedEndPart)
            {
                var localAppDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                var expectedResult   = Path.Combine(localAppDataPath, expectedEndPart);

                var result = GamePaths.GetModFolderPath(folder);

                result.Should().Be(expectedResult);
            }
示例#6
0
        public void GetGameSavePathTest(FarmSimulatorVersion version)
        {
            var path = GamePaths.GetSavesPath(version);

            if (!Directory.Exists(path))
            {
                Assert.Inconclusive($"{FarmSimulatorVersion.FarmingSimulator2019} not exist.");
            }
            Assert.IsTrue(Directory.Exists(path));
        }
示例#7
0
        public void GenerateCsCode()
        {
            var mapsPath    = GamePaths.GetGameMapsPath(FarmSimulatorVersion.FarmingSimulator2019);
            var mapFilePath = Path.Combine(mapsPath, "mapUS.i3d");
            var xml         = new XmlDocument();

            using var stream = File.OpenRead(mapFilePath);
            xml.Load(stream);
            var codeClases = ExportCodeClasses(xml.DocumentElement);
            var code       = string.Join("\n", codeClases.Select(v => GenerateCsCode(v.Value)));
            var names      = string.Join("\n", codeClases.Select(v => $"typeof({UpFirstChar(v.Value.Name)}),"));
        }
示例#8
0
        private void ManageDefaultFiles(LBGame lbGame, string gamePath, Folder tree)
        {
            GamePaths gp = (GamePaths)lbGame;

            gp.ApplicationPath = ManageRomPath(lbGame.ApplicationPath, tree.Children[Common.Games]);
            gp.ManualPath      = ManageDefaultFile(lbGame.ManualPath, tree.Children[Common.Manuals], "Manual");
            gp.MusicPath       = ManageDefaultFile(lbGame.MusicPath, tree.Children[Common.Musics], "Music");
            //gp.VideoPath = ManageDefaultFile(lbGame.VideoPath, tree.Children[Common.Videos]);
            //gp.ThemeVideoPath = ManageDefaultFile(lbGame.ThemeVideoPath, tree.Children[Common.]);

            gp.WriteToJson(Path.Combine(gamePath, "DPGame.json"));
        }
示例#9
0
        internal bool MakeDPG(string gamePath, ArchiveMode mode, string archiveLink)
        {
            GamePaths gpX = null;

            // Lecture des fichiers
            if (File.Exists(Path.Combine(gamePath, "DPGame.json")))
            {
                HeTrace.WriteLine("DPG Found");
                gpX = GamePaths.ReadFromJson(Path.Combine(gamePath, "DPGame.json"));
            }
            else if (File.Exists(Path.Combine(gamePath, "EBGame.xml")))
            {
                HeTrace.WriteLine("DPG Missing, work with EBGame");
                gpX = GetMainsInfo(gamePath, "EBGame.xml");
            }
            else if (File.Exists(Path.Combine(gamePath, "TBGame.xml")))
            {
                HeTrace.WriteLine("DPG Missing, work with TBGame");
                gpX = GetMainsInfo(gamePath, "TBGame.xml");
            }
            else if (File.Exists(Path.Combine(gamePath, "NBGame.xml")))
            {
                HeTrace.WriteLine("DPG Missing, work with NBGame");
                gpX = GetMainsInfo(gamePath, "NBGame.xml");
            }

            if (gpX == null)
            {
                throw new Exception("Impossible to continue, no data file available");
            }

            GameDataCont gpC = (GameDataCont)gpX;

            GameDataCompletion(gpC, mode, archiveLink);

            if (gpC.Applications.Count <= 0)
            {
                throw new Exception("No game to inject");
            }

            // Affichage
            IHMStatic.ShowDPG(gpC, gpX, gamePath);

            // Sauvegarde
            gpX.WriteToJson(Path.Combine(gamePath, "DPGame.json"));

            HeTrace.WriteLine("DPG Done");

            return(true);
        }
        public CursorSpriteDataLoader()
        {
            defaultSprite = Resources.Load <Sprite> (GamePaths.CursorSprite("Default"));
            emptySprite   = Resources.Load <Sprite> (GamePaths.TileCursorSprite("Empty"));

            tileBuildSprite         = Resources.Load <Sprite> (GamePaths.TileCursorSprite("Build"));
            tileRemoveSprite        = Resources.Load <Sprite> (GamePaths.TileCursorSprite("BuildInverse"));
            tileBuildOverTileSprite = Resources.Load <Sprite> (GamePaths.TileCursorSprite("BuildOverTile"));
            tileRemoveOnEmptySprite = Resources.Load <Sprite> (GamePaths.TileCursorSprite("BuildInverseOnEmpty"));

            wallMainSprite     = Resources.Load <Sprite>(GamePaths.WallCursorSprite("Main"));
            wallBuildSprite    = Resources.Load <Sprite>(GamePaths.WallCursorSprite("Build"));
            wallBulldozeSprite = Resources.Load <Sprite>(GamePaths.WallCursorSprite("Bulldoze"));
        }
        public static string GetCourseplayDirectory(FarmSimulatorVersion version)
        {
            var gameDirectory = GamePaths.GetSavesPath(version);

            if (gameDirectory == null)
            {
                return(null);
            }
            var coursePlayDirectory = Path.Combine(gameDirectory, CourseplayConstants.CourseplayDirectory);

            if (!Directory.Exists(coursePlayDirectory))
            {
                return(null);
            }
            return(coursePlayDirectory);
        }
示例#12
0
 internal static void ShowDPG(GameDataCont gpC, GamePaths gpx, string gamePath)
 {
     Application.Current.Dispatcher?.Invoke
     (
         () =>
     {
         W_DPGMaker winDPG = new W_DPGMaker()
         {
             Model = new M_DPGMaker(gpC, gpx, gamePath),
         };
         if (winDPG.ShowDialog() == true)
         {
             // ...
         }
     }
     );
 }
示例#13
0
        public static bool TryDiscoverGame(ZloBFGame game, out string path)
        {
            //first check cache
            if (GamePaths.TryGetValue(game, out var p))
            {
                if (File.Exists(p))
                {
                    path = p;
                    return(true);
                }
            }


            //then check local folder
            //then check paths in 'DiscoveryPaths'
            //then check registry

            path = null;
            return(false);
        }
示例#14
0
        private GamePaths MakeGamePaths(LBGame lbGame, GameDataCont gdC, Folder tree)
        {
            GamePaths gpX = GamePaths.CreateBasic(lbGame);

            //  gpX.ApplicationPath = AssignDefaultPath(tree.Children[Common.Games].Path, gdC.DefaultApp);
            gpX.SetApplications = gdC.Applications.Select(x =>
                                                          new DataPlus()
            {
                Id          = x.Id,
                Name        = x.Name,
                CurrentPath = x.Name,
                IsSelected  = x.IsSelected,
            });

            gpX.ManualPath     = AssignDefaultPath(tree.Children[Common.Manuals].Path, gdC.DefaultManual);
            gpX.MusicPath      = AssignDefaultPath(tree.Children[Common.Musics].Path, gdC.DefaultMusic);
            gpX.VideoPath      = AssignDefaultPath(tree.Children[Common.Videos].Path, gdC.DefaultVideo);
            gpX.ThemeVideoPath = AssignDefaultPath(tree.Children[Common.Videos].Path, gdC.DefaultThemeVideo);
            return(gpX);
        }
示例#15
0
        public void OpenXmlFileMapTest(FarmSimulatorVersion version, string fileName)
        {
            var mapsPath = GamePaths.GetGameMapsPath(version);

            if (mapsPath == null)
            {
                Assert.Inconclusive("Maps path by \"{0}\" not found.", version);
            }

            var mapFilePath = Path.Combine(mapsPath, fileName);

            if (!File.Exists(mapFilePath))
            {
                Assert.Inconclusive("Map file \"{0}\" by \"{1}\" not found.", fileName, version);
            }

            using (var stream = File.OpenRead(mapFilePath))
            {
                var mapFile = MapFile.Serializer.Deserialize(stream) as MapFile;
                Assert.IsNotNull(mapFile);
            }
        }
        public ConfigStore(
            string modFolderName,
            string configFileName = DefaultConfigFileName,
            IXmlFileSystem <ModConfiguration> fileSystemWrapper = null)
        {
            this.fileSystemWrapper = fileSystemWrapper ?? new XmlFileSystem <ModConfiguration>(new FileSystemWrapper());

            var modFolderPath = GamePaths.GetModFolderPath(GameFolder.Configs);

            modFolderPath = Path.Combine(modFolderPath, modFolderName);

            this.fileSystemWrapper.CreateDirectory(modFolderPath);

            ConfigFileInfo = new FileInfo(Path.Combine(modFolderPath, configFileName));

            if (!this.fileSystemWrapper.FileExists(ConfigFileInfo))
            {
                SaveConfigToFile(new ModConfiguration());
            }

            cachedConfigs = LoadConfigFromFile();
        }
示例#17
0
        // ---

        /// <summary>
        /// Travail pour un jeu
        /// </summary>
        /// <param name="shGame"></param>
        public void PackMe(ShortGame shGame)
        {
            TempDecision = MemorizedDecision;

            // Verif
            if (shGame == null || string.IsNullOrEmpty(shGame.Id))
            {
                HeTrace.WriteLine("Game property: null");
                return;
            }


            // Dossiers
            string gamePath = Path.Combine(_SystemPath, $"{shGame.ExploitableFileName}");             // New Working Folder

            //Compress_ZipMode(gamePath, shGame.Title);
            // Compress_7ZipMode(gamePath, shGame.Title);
            // Contrôle de collisions pour les dossiers
            if (Directory.Exists(gamePath))
            {
                HeTrace.WriteLine($"Directory Exists '{gamePath}'", this);
                // Demande à l'utilisateur si aucune précédente
                if (MemorizedDecision == E_Decision.None)
                {
                    Application.Current.Dispatcher?.Invoke(() =>
                                                           TempDecision = MBDecision.ShowDial(null, gamePath, LanguageManager.Instance.Lang.Folder_Ex, E_DxConfB.Trash | E_DxConfB.OverWrite));

                    switch (TempDecision)
                    {
                    /*   // Gestion des stops
                     * case E_Decision.Stop:
                     *     HeTrace.WriteLine("Stopped by user", this);
                     *     HeTrace.RemoveLogger("game");
                     *     return;
                     * case E_Decision.StopAll:
                     *     HeTrace.WriteLine("Stopped by user", this);
                     *     HeTrace.RemoveLogger("game");
                     *     throw new OperationCanceledException("Stopped by user");
                     */
                    case E_Decision.OverWriteAll:
                    case E_Decision.TrashAll:
                        MemorizedDecision = TempDecision;
                        break;
                    }

                    switch (TempDecision)
                    {
                    case E_Decision.Trash:
                    case E_Decision.TrashAll:
                        HeTrace.WriteLine($"Trash existing folder: '{gamePath}'", this);
                        OpFolders.Trash(@gamePath);
                        break;
                    }
                }
            }
            // --- On part du principe que tout peut être overwritté à partir de là.

            // Construction de la structure
            var tree = MakeStructure(gamePath);

            // ---

            #region Original Backup Game - Before all modifications
            if (Config.CreateTBGame)
            {
                XML_Games.TrueBackup(_XMLPlatformFile, shGame.Id, gamePath);
            }
            else
            {
                HeTrace.WriteLine("[Run] Original Backup Game disabled");
            }
            #endregion

            #region Backup without paths
            XML_Games.NPBackup(_XMLPlatformFile, shGame.Id, gamePath);

            #endregion

            // Récupération du jeu
            LBGame lbGame = XML_Games.Scrap_LBGame <LBGame>(_XMLPlatformFile, "ID", shGame.Id);

            // Récupération des clones


            HeTrace.WriteLine("Alarms about not managed field are not important except if it's about a path containing datas");
            HeTrace.WriteLine("EBGames and TBGames don't use a class they copy directly from xml to xml");

            #region Creation of the Infos.xml (on ne récupère que ce que l'on veut)
            if (Config.CreateInfos)
            {
                // --- Get game from Launchbox (on a besoin que jusqu'au game info)
                XML_Custom.Make_InfoGame(gamePath, lbGame);
            }
            else
            {
                HeTrace.WriteLine("[Run] Make info disabled", this);
            }
            #endregion


            // --- Récupération des fichiers
            GameDataCont gdC = new GameDataCont(lbGame.Title, lbGame.Platform);

            GetFiles(lbGame, gdC);

            if (PackMe_IHM.LaunchBoxCore_Prev(gamePath, _ZePlatform, gdC) != true)
            {
                throw new Exception("Stopped by user");
            }

            // --- Prepare files;
            PrepareList(gdC.Applications, tree, Config.KeepGameStruct, "Game");
            PrepareList(gdC.CheatCodes, tree, Config.KeepCheatStruct, "CheatCode");
            PrepareList(gdC.Manuals, tree, Config.KeepManualStruct, "Manual");
            PrepareList(gdC.Musics, tree, Config.KeepMusicStruct, "Music");
            PrepareList(gdC.Videos, tree, true, "Video");
            PrepareImages(gdC.Images, tree.Children[Common.Images].Path);

            // --- Copie des fichiers
            CopyFiles(gdC, tree);

            // --- Récapitulatif permettant de rajouter ou lever des fichiers au pack
            if (PackMe_IHM.LaunchBoxCore_Recap(gamePath, _ZePlatform, gdC) != true)
            {
                throw new Exception("Stopped by user");
            }

            // --- GamePaths ---
            GamePaths gpX = MakeGamePaths(lbGame, gdC, tree);


            #region Serialization / improved backup of Launchbox datas (with found medias missing)

            /* - En théorie on est toujours sur du relative path
             * - On a fait un assign sur les dossiers spécifiques
             * - On va récupérer la structure exacte sans aucune interprétation et modifier ce que l'on veut
             *      - Les Paths
             */
            if (Config.CreateEBGame)
            {
                Make_EnhanceBackup(gdC, lbGame, gamePath);
            }
            else
            {
                HeTrace.WriteLine($"[Run] Enhanced Backup Game disabled", this);
            }

            #endregion

            // --- Création d'un fichier conservant les fichiers par défaut définis par l'utilisateur en vue de réutilisation plus tard

            gpX.WriteToJson(Path.Combine(gamePath, "DPGame.json"));


            // --- On complète l'arborescence
            FoncSchem.MakeListFolder(tree.Children[Common.Manuals]);
            FoncSchem.MakeListFolder(tree.Children[Common.Images]);
            FoncSchem.MakeListFolder(tree.Children[Common.Musics]);
            FoncSchem.MakeListFolder(tree.Children[Common.Videos]);

            #region Save Struct
            if (Config.CreateTreeV)
            {
                FoncSchem.MakeStruct(tree, gamePath);
            }
            else
            {
                HeTrace.WriteLine($"[Run] Save Struct disabled", this);
            }
            #endregion

            #region 2020 choix du nom
            string name = PackMe_IHM.AskName(shGame.ExploitableFileName, _SystemPath);


            // Changement de nom du dossier <= Pour le moment ça ne fait que vérifier s'il peut écrire
            //si un dossier a le même nom ça ne pourra pas le renommer
            ushort i = 0;

            string destFolder = Path.Combine(_SystemPath, name);

            if (!gamePath.Equals(destFolder))
            {
                while (i < 10)
                {
                    try
                    {
                        Directory.Move(gamePath, destFolder);
                        HeTrace.WriteLine("Folder successfully renamed");

                        // Attribution du résultat
                        gamePath = destFolder;

                        // Sortie
                        break;
                    }
                    catch (IOException ioe)
                    {
                        HeTrace.WriteLine($"Try {i}: {ioe}");
                        Thread.Sleep(10);
                        i++;
                    }
                }
            }

            gamePath = destFolder;

            #endregion

            #region Compression
            // Zip
            if (Config.ZipCompression)
            {
                Compress_ZipMode(gamePath);
            }
            else
            {
                HeTrace.WriteLine($"[Run] Zip Compression disabled", this);
            }

            // 7zip
            if (Config.SevZipCompression)
            {
                Compress_7ZipMode(gamePath);
            }
            else
            {
                HeTrace.WriteLine($"[Run] 7Zip Compression disabled", this);
            }
            #endregion

            #region suppression du dossier de travail
            if (SafeBoxes.Dispatch_Mbox(this, "Would you want to ERASE the temp folder", "Erase", E_DxButtons.No | E_DxButtons.Yes, optMessage: shGame.ExploitableFileName) == true)
            {
                // Erase the temp folder
                try
                {
                    Directory.SetCurrentDirectory(_WFolder);
                    Directory.Delete(gamePath, true);
                    HeTrace.WriteLine($"[Run] folder {gamePath} erased", this);
                }
                catch (Exception exc)
                {
                    HeTrace.WriteLine($"[Run] Error when Erasing temp folder {gamePath}\n{exc.Message }", this);
                }
            }
            #endregion

            SetStatus(this, new StateArg($"Finished: {lbGame.Title}", CancelFlag));
        }
示例#18
0
        public void LoadTypedShape <T>(FarmSimulatorVersion version, string shapeFileName, int rawType, Func <BinaryReader, int, T> loadShape)
        {
            var gameMapPath = GamePaths.GetGameMapsPath(version);

            if (!Directory.Exists(gameMapPath))
            {
                var message = $"Game map path not found: \"{version}\".";
                Trace.WriteLine(message);
                Assert.Inconclusive(message);
            }

            var mapPath = Path.Combine(gameMapPath, shapeFileName);

            if (!File.Exists(mapPath))
            {
                var message = $"Map not found \"{version}\": \"{mapPath}\".";
                Trace.WriteLine(message);
                Assert.Inconclusive(message);
            }

            // Clear directory by error shapes
            var errorOutputPath = Path.Combine(OutputErrorShapes, version.ToString(), shapeFileName);

            if (Directory.Exists(errorOutputPath))
            {
                Directory.Delete(errorOutputPath, true);
            }

            var fileContainer = new FileContainer(mapPath);
            var entities      = fileContainer.GetEntities();
            var error         = false;

            fileContainer.ReadRawData(entities)
            .Where(v => v.Entity.Type == rawType)
            .ForEach(
                v =>
            {
                try
                {
                    using var stream = new MemoryStream(v.RawData);
                    using var reader = new EndianBinaryReader(stream, fileContainer.Endian);
                    var shape        = loadShape(reader, fileContainer.Header.Version);
                }
                catch (Exception ex)
                {
                    error            = true;
                    using var stream = new MemoryStream(v.RawData);
                    using var reader = new EndianBinaryReader(stream, fileContainer.Endian);
                    Trace.WriteLine($"Error load shape.");
                    var errorShape2 = new ReverseEngineeringNamedShape1Object(
                        v.Entity.Type,
                        reader,
                        fileContainer.Endian
                        );
                    Save(errorOutputPath, version, errorShape2, v.RawData);
                }
            }
                );

            if (error)
            {
                Assert.Fail();
            }
        }
示例#19
0
        public void ReadAllShapes(FarmSimulatorVersion version)
        {
            var hasError = false;
            var gamePath = GamePaths.GetGamePath(version);

            if (gamePath == null || !Directory.Exists(gamePath))
            {
                Assert.Inconclusive($"Game path not found: {version}");
            }

            var shapeFiles = Directory.GetFiles(gamePath, $"*{GameConstants.SchapesFileExtension}", SearchOption.AllDirectories);

            shapeFiles
            .AsParallel()
            .WithDegreeOfParallelism(Environment.ProcessorCount)
            .ForEach(
                filePath =>
            {
                try
                {
                    var container = new FileContainer(filePath);
                    var entities  = container.GetEntities();
                    foreach (var valueTuple in container.ReadRawData(entities))
                    {
                        using (var stream = new MemoryStream(valueTuple.RawData))
                        {
                            try
                            {
                                using (var reader = new EndianBinaryReader(stream, container.Endian, true))
                                {
                                    switch (valueTuple.Entity.Type)
                                    {
                                    case 1:
                                        var shape = new Shape(reader, container.Header.Version);
                                        break;

                                    case 2:
                                        var spline = new Spline(reader);
                                        break;

                                    case 3:
                                        var mesh = new NavMesh(reader);
                                        break;
                                    }
                                }
                            }
                            catch
                            {
                                hasError = true;
                                stream.Seek(0, SeekOrigin.Begin);
                                using (var reader = new EndianBinaryReader(stream, container.Endian))
                                {
                                    SaveErrorShape(
                                        version,
                                        container.Header.Version,
                                        filePath,
                                        new RawNamedShapeObject(valueTuple.Entity.Type, reader, container.Endian)
                                        );
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    hasError = true;
                }
            }
                );

            Assert.IsFalse(hasError);
        }
示例#20
0
        public void ReadAllShapes()
        {
            var versions = new[]
            {
                FarmSimulatorVersion.FarmingSimulator2013,
                FarmSimulatorVersion.FarmingSimulator2015,
                FarmSimulatorVersion.FarmingSimulator2017,
                FarmSimulatorVersion.FarmingSimulator2019,
            };
            var hasError = false;

            versions
            .Select(version => (Version: version, Path: GamePaths.GetGamePath(version)))
            .Where(v => v.Path != null)
            .SelectMany(
                v =>
            {
                var shapeFiles = Directory.GetFiles(v.Path, $"*{GameConstants.SchapesFileExtension}", SearchOption.AllDirectories);
                return(shapeFiles.Select(file => (Version: v.Version, FilePath: file)));
            }
                )
            .AsParallel()
            .WithDegreeOfParallelism(Environment.ProcessorCount)
            .ForEach(
                v =>
            {
                try
                {
                    var container = new FileContainer(v.FilePath);
                    var entities  = container.GetEntities();
                    foreach (var valueTuple in container.ReadRawData(entities))
                    {
                        using (var stream = new MemoryStream(valueTuple.RawData))
                        {
                            try
                            {
                                using (var reader = new EndianBinaryReader(stream, container.Endian, true))
                                {
                                    switch (valueTuple.Entity.Type)
                                    {
                                    case 1:
                                        var shape = new Shape(reader, container.Header.Version);
                                        break;

                                    case 2:
                                        var spline = new Spline(reader);
                                        break;

                                    case 3:
                                        var mesh = new NavMesh(reader);
                                        break;
                                    }
                                }
                            }
                            catch
                            {
                                hasError = true;
                                stream.Seek(0, SeekOrigin.Begin);
                                using (var reader = new EndianBinaryReader(stream, container.Endian))
                                {
                                    SaveErrorShape(
                                        v.Version,
                                        v.FilePath,
                                        new RawNamedShapeObject(valueTuple.Entity.Type, reader, container.Endian)
                                        );
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    hasError = true;
                }
            }
                );

            Assert.False(hasError);
        }
示例#21
0
        private GameDataCont PrepareGDC(string root, GamePaths gpX)
        {
            HeTrace.WriteLine($"[{nameof(PrepareGDC)}]");

            GameDataCont gdc = new GameDataCont(gpX.Title, gpX.Platform);

            string tmp = string.Empty;

            HeTrace.WriteLine($"\tGames: {Config.Games}");
            // Games
            tmp = Path.Combine(root, Config.Games);
            gdc.SetApplications = gpX.Applications.Select(x =>
                                                          new DataPlus()
            {
                Id          = x.Id,
                Name        = x.Name,
                CurrentPath = Path.GetFullPath(x.CurrentPath, tmp),
                IsSelected  = x.IsSelected,
            });

            if (Directory.Exists(tmp))
            {
                gdc.SSetApplications = Directory.GetFiles(tmp, "*.*", SearchOption.AllDirectories);
            }

            /*gdc.SetDefaultApplication = gpX.ApplicationPath == null ? null : Path.GetFullPath(gpX.ApplicationPath, tmp);
             * gdc.SetApplications = Directory.GetFiles(tmp, "*.*", SearchOption.AllDirectories).ToList();*/

            // Manuals
            HeTrace.WriteLine($"\tManuals: {Config.Manuals}");
            tmp = Path.Combine(root, Config.Manuals);
            gdc.SetDefaultManual = string.IsNullOrEmpty(gpX.ManualPath)? null : Path.GetFullPath(gpX.ManualPath, tmp);
            if (Directory.Exists(tmp))
            {
                gdc.AddSManuals = Directory.GetFiles(Path.Combine(tmp), "*.*", SearchOption.AllDirectories).ToList();
            }

            // Musics
            HeTrace.WriteLine($"\tMusics: {Config.Musics}");
            tmp = Path.Combine(root, Config.Musics);
            gdc.SetDefaultMusic = string.IsNullOrEmpty(gpX.MusicPath) ? null : Path.GetFullPath(gpX.MusicPath, tmp);
            if (Directory.Exists(tmp))
            {
                gdc.AddSMusics = Directory.GetFiles(tmp, "*.*", SearchOption.AllDirectories).ToList();
            }

            // Videos
            HeTrace.WriteLine($"\tVideos: {Config.Videos}");
            tmp = Path.Combine(root, Config.Videos);
            gdc.SetDefaultVideo      = string.IsNullOrEmpty(gpX.VideoPath) ? null : Path.GetFullPath(gpX.VideoPath, tmp);
            gdc.SetDefaultThemeVideo = string.IsNullOrEmpty(gpX.ThemeVideoPath) ? null : Path.GetFullPath(gpX.ThemeVideoPath, tmp);
            if (Directory.Exists(tmp))
            {
                gdc.AddSVideos = Directory.GetFiles(tmp, "*.*", SearchOption.AllDirectories);
            }

            // Cheat Codes
            HeTrace.WriteLine($"\tCheatCodes: {Config.CheatCodes}");
            tmp = Path.Combine(root, Config.CheatCodes);
            if (Directory.Exists(tmp))
            {
                gdc.SetSCheatCodes = Directory.GetFiles(tmp, "*.*", SearchOption.AllDirectories).ToList();
            }

            // Images
            HeTrace.WriteLine("\tImages");
            tmp = Path.Combine(root, Config.Images);
            if (Directory.Exists(tmp))
            {
                gdc.Images = PrepareImages(tmp);
            }


            return(gdc);
        }
示例#22
0
        public GameDataCont InjectGame(string gamePath)
        {
            HeTrace.WriteLine("Dpg Step");

            string dpgFile = Path.Combine(gamePath, "DPGame.json");

            // Check if DPG file exists
            if (!File.Exists(dpgFile))
            {
                DPGMakerCore dpgMaker = new DPGMakerCore();
                dpgMaker.MakeDPG_Folder(gamePath);
            }

            GamePaths gpX = GamePaths.ReadFromJson(dpgFile);

            HeTrace.WriteLine($"Platform Step for '{gpX.Platform}'");
            string platformsFile = Path.Combine(Config.HLaunchBoxPath, Config.PlatformsFile);

            bool CheckIfInjectionNeeded = !XML_Custom.TestPresence(platformsFile, Tag.Platform, Tag.Name, gpX.Platform);

            if (CheckIfInjectionNeeded)
            {
                HeTrace.WriteLine($"Backup of platforms file");
                // Backup du fichier de la plateforme;
                BackupFile(platformsFile, _BackupFolder);

                string newPFile = IHMStatic.GetAFile(Config.LastTargetPath, $"Platform '{gpX.Platform}' doesn't exist. Select the xml file to inject for this platform", "xml");
                if (string.IsNullOrEmpty(newPFile))
                {
                    throw new Exception("File for injection is not filled");
                }

                // Vérification que c'est la bonne plateforme
                if (!XML_Custom.TestPresence(newPFile, Tag.Platform, Tag.Name, gpX.Platform))
                {
                    throw new Exception("File doesn't contain the good platform");
                }

                HeTrace.WriteLine($"Injecting {gpX.Platform} in platforms file for {gpX.Platform}");
                InjectPlatform(gpX.Platform, newPFile);
            }

            ContPlatFolders zePlatform = XML_Platforms.GetPlatformPaths(platformsFile, gpX.Platform);

            HeTrace.WriteLine("Preparing files");
            // Préparation des fichiers
            GameDataCont gdC = PrepareGDC(gamePath, gpX);

            // Manipulation des fichiers
            AssignTargets(gdC, gamePath, zePlatform);

            // --- Lecture de la plateforme
            string machineXMLFile = Path.Combine(Config.HLaunchBoxPath, Config.PlatformsFolder, $"{gpX.Platform}.xml");

            if (!File.Exists(machineXMLFile))
            {
                XML_Games.NewPlatform(machineXMLFile);
            }

            // Backup platform file
            BackupFile(machineXMLFile, _BackupFolder);
            HeTrace.WriteLine($"Backup of '{machineXMLFile}'");

            InjectInXMLFile(gamePath, gdC, machineXMLFile, zePlatform.FolderPath);

            HeTrace.WriteLine($"Game injected: {gdC.Title}");

            return(gdC);
        }