private int ApplyPackageDD(string srcPath, int phraseLen, bool removeSus, string rampPath, string cfgPath, out string consoleOutput, bool overWrite = false, bool keepLog = false)
        {
            int            result = 0; // Ends normally with no error
            DLCPackageData packageData;

            consoleOutput = String.Empty;

            try
            {
                using (var psarcOld = new PsarcPackager())
                    packageData = psarcOld.ReadPackage(srcPath);
            }
            catch (Exception ex)
            {
                consoleOutput = "Error Reading : " + srcPath + Environment.NewLine + ex.Message;
                return(-1); // Read Error
            }

            // Update arrangement song info
            foreach (Arrangement arr in packageData.Arrangements)
            {
                if (chkGenArrIds.Checked)
                {
                    // generate new AggregateGraph
                    arr.SongFile = new RocksmithToolkitLib.DLCPackage.AggregateGraph.SongFile()
                    {
                        File = ""
                    };

                    // generate new Arrangement IDs
                    arr.Id       = IdGenerator.Guid();
                    arr.MasterId = RandomGenerator.NextInt();
                }

                // skip vocal and showlight arrangements
                if (arr.ArrangementType == ArrangementType.Vocal || arr.ArrangementType == ArrangementType.ShowLight)
                {
                    continue;
                }

                // validate (QC) RS2014 packageData
                if (packageData.GameVersion == GameVersion.RS2014)
                {
                    // validate existing SongInfo
                    var songXml = Song2014.LoadFromFile(arr.SongXml.File);
                    songXml.ArtistName     = packageData.SongInfo.Artist.GetValidAtaSpaceName();
                    songXml.Title          = packageData.SongInfo.SongDisplayName.GetValidAtaSpaceName();
                    songXml.AlbumName      = packageData.SongInfo.Album.GetValidAtaSpaceName();
                    songXml.ArtistNameSort = packageData.SongInfo.ArtistSort.GetValidSortableName();
                    songXml.SongNameSort   = packageData.SongInfo.SongDisplayNameSort.GetValidSortableName();
                    songXml.AlbumNameSort  = packageData.SongInfo.AlbumSort.GetValidSortableName();
                    songXml.AverageTempo   = Convert.ToSingle(packageData.SongInfo.AverageTempo.ToString().GetValidTempo());
                    songXml.AlbumYear      = packageData.SongInfo.SongYear.ToString().GetValidYear();

                    // update packageData with validated SongInfo
                    packageData.SongInfo.Artist              = songXml.ArtistName;
                    packageData.SongInfo.SongDisplayName     = songXml.Title;
                    packageData.SongInfo.Album               = songXml.AlbumName;
                    packageData.SongInfo.ArtistSort          = songXml.ArtistNameSort;
                    packageData.SongInfo.SongDisplayNameSort = songXml.SongNameSort;
                    packageData.SongInfo.AlbumSort           = songXml.AlbumNameSort;
                    packageData.SongInfo.AverageTempo        = (int)songXml.AverageTempo;
                    packageData.SongInfo.SongYear            = Convert.ToInt32(songXml.AlbumYear);

                    // write updated xml arrangement
                    using (var stream = File.Open(arr.SongXml.File, FileMode.Create))
                        songXml.Serialize(stream, false);

                    // restore arrangment comments
                    Song2014.WriteXmlComments(arr.SongXml.File, arr.XmlComments);
                }

                // apply DD to xml arrangments... 0 = Ends normally with no error
                result = DDCreator.ApplyDD(arr.SongXml.File, phraseLen, removeSus, rampPath, cfgPath, out consoleOutput, true, keepLog);
                if (result == 0)      // Ends normally with no error
                {                     /* DO NOTHING */
                }
                else if (result == 1) // Ends with system error
                {
                    consoleOutput = "DDC System Error: " + Environment.NewLine +
                                    "Arrangment file: " + Path.GetFileName(arr.SongXml.File) + Environment.NewLine +
                                    "CDLC file: " + srcPath;
                    return(result);
                }
                else if (result == 2) // Ends with application error
                {
                    consoleOutput = "DDC Application Error: " + Environment.NewLine +
                                    "Arrangment file: " + Path.GetFileName(arr.SongXml.File) + Environment.NewLine +
                                    "CDLC file: " + srcPath;
                    return(result);
                }

                if (keepLog)
                {
                    var unpackedDir = Path.GetDirectoryName(Path.GetDirectoryName(arr.SongXml.File));
                    var logFiles    = Directory.EnumerateFiles(unpackedDir, "*.log", SearchOption.AllDirectories);
                    var clogDir     = Path.Combine(Path.GetDirectoryName(srcPath), "DDC_Log");
                    var plogDir     = Path.Combine(clogDir, Path.GetFileNameWithoutExtension(srcPath).StripPlatformEndName().Replace("_DD", "").Replace("_NDD", ""));

                    if (!Directory.Exists(clogDir))
                    {
                        Directory.CreateDirectory(clogDir);
                    }

                    IOExtension.DeleteDirectory(plogDir);
                    Directory.CreateDirectory(plogDir);

                    foreach (var logFile in logFiles)
                    {
                        File.Copy(logFile, Path.Combine(plogDir, Path.GetFileName(logFile)));
                    }
                }

                // put arrangment comments in correct order
                Song2014.WriteXmlComments(arr.SongXml.File);
            }

            if (chkGenArrIds.Checked)
            {
                // add comment to ToolkitInfo to identify CDLC
                var arrIdComment = packageData.ToolkitInfo.PackageComment;
                if (String.IsNullOrEmpty(arrIdComment))
                {
                    arrIdComment = TKI_ARRID;
                }
                else if (!arrIdComment.Contains(TKI_ARRID))
                {
                    arrIdComment = arrIdComment + " " + TKI_ARRID;
                }

                packageData.ToolkitInfo.PackageComment = arrIdComment;
            }

            // add comment to ToolkitInfo to identify CDLC
            var remasterComment = packageData.ToolkitInfo.PackageComment;

            if (String.IsNullOrEmpty(remasterComment))
            {
                remasterComment = TKI_REMASTER;
            }
            else if (!remasterComment.Contains(TKI_REMASTER))
            {
                remasterComment = remasterComment + " " + TKI_REMASTER;
            }

            packageData.ToolkitInfo.PackageComment = remasterComment;

            // add default package version if missing
            if (String.IsNullOrEmpty(packageData.ToolkitInfo.PackageVersion))
            {
                packageData.ToolkitInfo.PackageVersion = "1";
            }
            else
            {
                packageData.ToolkitInfo.PackageVersion = packageData.ToolkitInfo.PackageVersion.GetValidVersion();
            }

            // validate packageData (important)
            packageData.Name = packageData.Name.GetValidKey(); // DLC Key

            var destPath = srcPath;

            if (!overWrite)
            {
                destPath = GenerateDdcFilePath(srcPath);
            }

            try
            {
                // regenerates the archive with DDC changes and repairs
                using (var psarcNew = new PsarcPackager(true))
                    psarcNew.WritePackage(destPath, packageData, srcPath);
            }
            catch (Exception ex)
            {
                consoleOutput = "Error Writing: " + srcPath + Environment.NewLine + ex.Message;
                result        = -2; // Write Error
            }

            return(result);
        }
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            ProcessOutput = String.Empty;
            var rampPath = String.Empty;
            var cfgPath  = String.Empty;

            this.Invoke(new MethodInvoker(() =>
            {
                rampPath = GetRampUpMdl();
                cfgPath  = GetConfig();
            }));

            var errorsFound  = new StringBuilder();
            var totalCount   = FilesDb.Count;
            var currentCount = 0;
            var errorCount   = 0;
            // TODO: change progress reporting method so it is responsive for a single file
            var step     = (int)Math.Round(1.0 / FilesDb.Count * 100, 0);
            var progress = 0;

            bw.ReportProgress(progress);

            foreach (var file in FilesDb)
            {
                var consoleOutput = String.Empty;
                currentCount++;
                int count = currentCount;
                GeneralExtension.InvokeIfRequired(lblStatus, delegate
                {
                    lblStatus.Text = String.Format("Processing file {0} of {1} ... Please wait.", count, totalCount);
                });

                switch (Path.GetExtension(file.Value))
                {
                case ".xml":       // Arrangement
                    DDCreator.ApplyDD(file.Value, (int)cmbPhraseLen.Value, chkRemoveSustains.Checked, rampPath, cfgPath, out consoleOutput, chkOverwrite.Checked, chkGenLogFile.Checked);
                    break;

                case ".psarc":     // PC / Mac (RS2014)
                case ".dat":       // PC (RS1)
                case ".edat":      // PS3
                case "":           // XBox 360
                    ApplyPackageDD(file.Value, (int)cmbPhraseLen.Value, chkRemoveSustains.Checked, rampPath, cfgPath, out consoleOutput, chkOverwrite.Checked, chkGenLogFile.Checked);
                    break;
                }

                if (!String.IsNullOrEmpty(consoleOutput))
                {
                    errorsFound.AppendLine(consoleOutput);
                    errorCount++;
                }

                progress += step;
                bw.ReportProgress(progress);
            }

            if (!String.IsNullOrEmpty(errorsFound.ToString()))
            {
                ProcessOutput = errorsFound.ToString();
            }

            GeneralExtension.InvokeIfRequired(lblStatus, delegate
            {
                lblStatus.Text = String.Format("Sucessfully processed {0} of {1} files ...", totalCount - errorCount, totalCount);
            });

            e.Result = errorCount; // No Errors = 0
        }
Exemplo n.º 3
0
        public static string DoLikeSongPack(string srcPath, string appId = "248750")
        {
            // create SongPack directory structure
            var dlcName              = Path.GetFileName(srcPath).ToLower();
            var songPackDir          = Path.Combine(Path.GetTempPath(), String.Format("{0}_songpack_p_Pc", dlcName));
            var audioWindowDir       = Path.Combine(songPackDir, "audio", "windows");
            var flatmodelsRsDir      = Path.Combine(songPackDir, "flatmodels", "rs");
            var gamexblocksNsongsDir = Path.Combine(songPackDir, "gamexblocks", "nsongs");
            var gfxassetsAlbumArtDir = Path.Combine(songPackDir, "gfxassets", "album_art");
            var manifestSongsDir     = Path.Combine(songPackDir, "manifests", String.Format("songs_dlc_{0}", dlcName));
            var songsArrDir          = Path.Combine(songPackDir, "songs", "arr");
            var binGenericDir        = Path.Combine(songPackDir, "songs", "bin", "generic");

            if (Directory.Exists(songPackDir))
            {
                IOExtension.DeleteDirectory(songPackDir);
            }

            Directory.CreateDirectory(songPackDir);
            Directory.CreateDirectory(audioWindowDir);
            Directory.CreateDirectory(flatmodelsRsDir);
            Directory.CreateDirectory(gamexblocksNsongsDir);
            Directory.CreateDirectory(gfxassetsAlbumArtDir);
            Directory.CreateDirectory(manifestSongsDir);
            Directory.CreateDirectory(songsArrDir);
            Directory.CreateDirectory(binGenericDir);

            // populate SongPack temporary directory
            var audioWemFiles = Directory.EnumerateFiles(srcPath, "*.wem", SearchOption.AllDirectories).ToArray();

            foreach (var wem in audioWemFiles)
            {
                File.Copy(wem, Path.Combine(audioWindowDir, Path.GetFileName(wem)));
            }

            var audioBnkFiles = Directory.EnumerateFiles(srcPath, "*.bnk", SearchOption.AllDirectories).ToArray();

            foreach (var bnk in audioBnkFiles)
            {
                File.Copy(bnk, Path.Combine(audioWindowDir, Path.GetFileName(bnk)));
            }

            var xblockFiles = Directory.EnumerateFiles(srcPath, "*.xblock", SearchOption.AllDirectories).ToArray();

            foreach (var xblock in xblockFiles)
            {
                File.Copy(xblock, Path.Combine(gamexblocksNsongsDir, Path.GetFileName(xblock)));
            }

            var albumArtFiles = Directory.EnumerateFiles(srcPath, "*.dds", SearchOption.AllDirectories).ToArray();

            foreach (var albumArt in albumArtFiles)
            {
                File.Copy(albumArt, Path.Combine(gfxassetsAlbumArtDir, Path.GetFileName(albumArt)));
            }

            var jsonFiles = Directory.EnumerateFiles(srcPath, "*.json", SearchOption.AllDirectories).ToArray();

            foreach (var json in jsonFiles)
            {
                File.Copy(json, Path.Combine(manifestSongsDir, Path.GetFileName(json)));
            }

            var hsanFiles = Directory.EnumerateFiles(srcPath, "*.hsan", SearchOption.AllDirectories).ToArray();

            foreach (var hsan in hsanFiles)
            {
                File.Copy(hsan, Path.Combine(manifestSongsDir, Path.GetFileName(hsan)));
            }

            var sngFiles = Directory.EnumerateFiles(srcPath, "*.sng", SearchOption.AllDirectories).ToArray();

            foreach (var sng in sngFiles)
            {
                File.Copy(sng, Path.Combine(binGenericDir, Path.GetFileName(sng)));
            }

            // declare variables one time for use in DDC generation
            DDCSettings.Instance.LoadConfigXml();
            var phraseLen = DDCSettings.Instance.PhraseLen;
            // removeSus may be depricated in latest DDC but left here for comptiblity
            var removeSus = DDCSettings.Instance.RemoveSus;
            var rampPath  = DDCSettings.Instance.RampPath;
            var cfgPath   = DDCSettings.Instance.CfgPath;

            // generate SongPack comment
            var spComment = "(Remastered by SongPack Maker)";
            var addDD     = false;

            if (ConfigRepository.Instance().GetBoolean("ddc_autogen"))
            {
                addDD      = true;
                spComment += " " + "(DDC by SongPack Maker)";
            }

            var xmlFiles = Directory.EnumerateFiles(srcPath, "*.xml", SearchOption.AllDirectories).ToArray();

            foreach (var xml in xmlFiles)
            {
                // completely skip dlc.xml template files
                if (xml.EndsWith("_RS2014.dlc.xml"))
                {
                    continue;
                }

                var xmlSongPack = Path.Combine(songsArrDir, Path.GetFileName(xml));
                File.Copy(xml, xmlSongPack);

                // skip vocal and showlight xml files
                if (xml.EndsWith("_vocals.xml") || xml.EndsWith("_showlights.xml"))
                {
                    continue;
                }

                // add DDC to xml arrangement
                if (addDD)
                {
                    // check if arrangment has pre existing DD and do not overwrite
                    var songXml = Song2014.LoadFromFile(xml);
                    var mf      = new ManifestFunctions(GameVersion.RS2014);
                    if (mf.GetMaxDifficulty(songXml) == 0)
                    {
                        var consoleOutput = String.Empty;
                        // apply DD to xml arrangments... 0 = Ends normally with no error
                        var result = DDCreator.ApplyDD(xmlSongPack, phraseLen, removeSus, rampPath, cfgPath, out consoleOutput, true);
                        if (result == 1)
                        {
                            Debug.WriteLine(String.Format("Arrangement file '{0}' => {1}", Path.GetFileNameWithoutExtension(xml), "DDC ended with system error " + consoleOutput));
                        }
                        else if (result == 2)
                        {
                            Debug.WriteLine(String.Format("Arrangement file '{0}' => {1}", Path.GetFileNameWithoutExtension(xml), "DDC ended with application error " + consoleOutput));
                        }
                    }
                }
            }

            // generate new Aggregate Graph
            var aggGraphPack = new AggregateGraph2014();

            aggGraphPack.JsonDB        = new List <GraphItem>();
            aggGraphPack.HsonDB        = new List <GraphItem>(); // used for consoles ONLY
            aggGraphPack.HsanDB        = new GraphItem();
            aggGraphPack.MusicgameSong = new List <GraphItemLLID>();
            aggGraphPack.SongXml       = new List <GraphItemLLID>();
            aggGraphPack.ShowlightXml  = new List <GraphItemLLID>();
            aggGraphPack.ImageArt      = new List <GraphItemLLID>();
            aggGraphPack.Soundbank     = new List <GraphItemLLID>();
            aggGraphPack.GameXblock    = new List <GraphItem>();

            // fix aggregate graph entries, reusing existing Persistent ID
            var currentPlatform     = new Platform(GamePlatform.Pc, GameVersion.RS2014);
            var aggregateGraphFiles = Directory.EnumerateFiles(srcPath, "*.nt", SearchOption.AllDirectories).ToArray();

            foreach (var aggGraph in aggregateGraphFiles)
            {
                var agg = LoadFromFile(aggGraph);

                foreach (var json in agg.JsonDB)
                {
                    json.Canonical        = String.Format(CANONICAL_MANIFEST_PC, dlcName);
                    json.RelPathDirectory = json.Canonical;
                    json.Tag = new List <string>();
                    json.Tag.Add(TagValue.Database.GetDescription());
                    json.Tag.Add(TagValue.JsonDB.GetDescription());
                    json.UUID        = IdGenerator.Guid();
                    json.RelPathFile = String.Format("{0}.json", json.Name);
                }

                aggGraphPack.JsonDB.AddRange(agg.JsonDB);
                aggGraphPack.MusicgameSong.AddRange(agg.MusicgameSong);
                aggGraphPack.SongXml.AddRange(agg.SongXml);
                aggGraphPack.ShowlightXml.AddRange(agg.ShowlightXml);
                aggGraphPack.ImageArt.AddRange(agg.ImageArt);
                aggGraphPack.Soundbank.AddRange(agg.Soundbank);

                aggGraphPack.GameXblock.AddRange(agg.GameXblock);
            }

            // create a single hsanDB entry
            aggGraphPack.HsanDB.Name             = String.Format("songs_dlc_{0}", dlcName);
            aggGraphPack.HsanDB.Canonical        = String.Format(CANONICAL_MANIFEST_PC, dlcName);
            aggGraphPack.HsanDB.RelPathDirectory = aggGraphPack.HsanDB.Canonical;
            aggGraphPack.HsanDB.Tag = new List <string>();
            aggGraphPack.HsanDB.Tag.Add(TagValue.Database.GetDescription());
            aggGraphPack.HsanDB.Tag.Add(TagValue.HsanDB.GetDescription());
            aggGraphPack.HsanDB.UUID        = IdGenerator.Guid();
            aggGraphPack.HsanDB.RelPathFile = String.Format("{0}.hsan", aggGraphPack.HsanDB.Name);

            var aggregateGraphFileName = Path.Combine(songPackDir, String.Format("{0}_aggregategraph.nt", dlcName));

            using (var fs = new FileStream(aggregateGraphFileName, FileMode.Create))
                using (var ms = new MemoryStream())
                {
                    aggGraphPack.Serialize(ms);
                    ms.Flush();
                    ms.Seek(0, SeekOrigin.Begin);
                    ms.CopyTo(fs);
                }

            MergeHsanFiles(songPackDir, dlcName, manifestSongsDir);

            var appIdFile = Path.Combine(songPackDir, "appid.appid");

            File.WriteAllText(appIdFile, appId);

            var toolkitVersionFile = Path.Combine(songPackDir, "toolkit.version");

            using (var fs = new FileStream(toolkitVersionFile, FileMode.Create))
                using (var ms = new MemoryStream())
                {
                    DLCPackageCreator.GenerateToolkitVersion(ms, packageVersion: "SongPack Maker v1.2", packageComment: spComment);
                    ms.Flush();
                    ms.Seek(0, SeekOrigin.Begin);
                    ms.CopyTo(fs);
                }

            var rootFlatFile = Path.Combine(flatmodelsRsDir, "rsenumerable_root.flat");

            using (var fs = new FileStream(rootFlatFile, FileMode.Create))
                using (var ms = new MemoryStream(Resources.rsenumerable_root))
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    ms.CopyTo(fs);
                }

            var songFlatFile = Path.Combine(flatmodelsRsDir, "rsenumerable_song.flat");

            using (var fs = new FileStream(songFlatFile, FileMode.Create))
                using (var ms = new MemoryStream(Resources.rsenumerable_song))
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    ms.CopyTo(fs);
                }

            return(songPackDir);
        }