public void SaveTemp(int index)
        {
            var tempName = Path.GetTempPath() + "temp_playback.xma";

            var playback = ugh.PlayBacks[snd.PlaybackIndex];
            var perm     = cache.ugh_.SoundPermutations[playback.FirstPermutation + index];
            var data     = cache.GetSoundRaw(snd.RawID, GetTotalSize(ugh, playback));

            byte[] buffer;

            if (index == -1)
            {
                buffer = data;
            }
            else
            {
                buffer = GetPermData(data, ugh, perm);
            }

            var codec = cache.ugh_.Codecs[snd.CodecIndex];
            var xma   = GetXMA(buffer, snd.SampleRate, codec.Type);

            var          fs = File.OpenWrite(tempName);
            EndianWriter sw = new EndianWriter(fs, EndianFormat.BigEndian);

            sw.Write(xma);

            sw.Close();
            sw.Dispose();

            var info = new ProcessStartInfo(towav, tempName)
            {
                CreateNoWindow   = true,
                UseShellExecute  = false,
                WorkingDirectory = Path.GetTempPath()
            };

            Process.Start(info).WaitForExit();
            if (File.Exists(tempName))
            {
                File.Delete(tempName);
            }
        }
Exemple #2
0
        // Patch Creation
        private void btnCreatePatch_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Check the user isn't completly retarded
                if (!CheckAllCreateMandatoryFields())
                {
                    return;
                }

                // Check the user isn't a skid
                if (!CheckAllCreateMetaFilesExists())
                {
                    return;
                }

                // Paths
                string cleanMapPath  = txtCreatePatchUnModifiedMap.Text;
                string moddedMapPath = txtCreatePatchModifiedMap.Text;
                string outputPath    = txtCreatePatchOutputPatch.Text;
                string previewImage  = txtCreatePatchPreviewImage.Text;

                // Details
                string author     = txtCreatePatchContentAuthor.Text;
                string desc       = txtCreatePatchContentDescription.Text;
                string name       = txtCreatePatchContentName.Text;
                string outputName = txtCreatePatchOutputName.Text;

                // Make dat patch
                var patch = new Patch
                {
                    Author      = author,
                    Description = desc,
                    Name        = name,
                    OutputName  = outputName,
                    Screenshot  = String.IsNullOrEmpty(previewImage)
                                                ? null
                                                : File.ReadAllBytes(previewImage),
                    BuildString = _buildInfo.Version,
                    PC          = String.IsNullOrEmpty(_buildInfo.GameExecutable)
                                                ? false
                                                : true
                };

                EndianReader originalReader = null;
                EndianReader newReader      = null;
                try
                {
                    originalReader = new EndianReader(File.OpenRead(cleanMapPath), Endian.BigEndian);
                    newReader      = new EndianReader(File.OpenRead(moddedMapPath), Endian.BigEndian);

                    ICacheFile originalFile = CacheFileLoader.LoadCacheFile(originalReader, cleanMapPath,
                                                                            App.AssemblyStorage.AssemblySettings.DefaultDatabase);
                    ICacheFile newFile = CacheFileLoader.LoadCacheFile(newReader, moddedMapPath, App.AssemblyStorage.AssemblySettings.DefaultDatabase);

                    if (cbCreatePatchHasCustomMeta.IsChecked != null && (bool)cbCreatePatchHasCustomMeta.IsChecked &&
                        cboxCreatePatchTargetGame.SelectedIndex < 4)
                    {
                        var      targetGame      = (TargetGame)cboxCreatePatchTargetGame.SelectedIndex;
                        byte[]   mapInfo         = File.ReadAllBytes(txtCreatePatchMapInfo.Text);
                        var      mapInfoFileInfo = new FileInfo(txtCreatePatchMapInfo.Text);
                        FileInfo blfFileInfo;

                        patch.CustomBlfContent = new BlfContent(mapInfoFileInfo.FullName, mapInfo, targetGame);

                        #region Blf Data

                        if (PatchCreationBlfOption0.Visibility == Visibility.Visible)
                        {
                            blfFileInfo = new FileInfo(txtCreatePatchblf0.Text);
                            patch.CustomBlfContent.BlfContainerEntries.Add(new BlfContainerEntry(blfFileInfo.Name,
                                                                                                 File.ReadAllBytes(blfFileInfo.FullName)));
                        }
                        if (PatchCreationBlfOption1.Visibility == Visibility.Visible)
                        {
                            blfFileInfo = new FileInfo(txtCreatePatchblf1.Text);
                            patch.CustomBlfContent.BlfContainerEntries.Add(new BlfContainerEntry(blfFileInfo.Name,
                                                                                                 File.ReadAllBytes(blfFileInfo.FullName)));
                        }
                        if (PatchCreationBlfOption2.Visibility == Visibility.Visible)
                        {
                            blfFileInfo = new FileInfo(txtCreatePatchblf2.Text);
                            patch.CustomBlfContent.BlfContainerEntries.Add(new BlfContainerEntry(blfFileInfo.Name,
                                                                                                 File.ReadAllBytes(blfFileInfo.FullName)));
                        }
                        if (PatchCreationBlfOption3.Visibility == Visibility.Visible)
                        {
                            blfFileInfo = new FileInfo(txtCreatePatchblf3.Text);
                            patch.CustomBlfContent.BlfContainerEntries.Add(new BlfContainerEntry(blfFileInfo.Name,
                                                                                                 File.ReadAllBytes(blfFileInfo.FullName)));
                        }

                        #endregion
                    }

                    PatchBuilder.BuildPatch(originalFile, originalReader, newFile, newReader, patch);
                }
                finally
                {
                    if (originalReader != null)
                    {
                        originalReader.Dispose();
                    }
                    if (newReader != null)
                    {
                        newReader.Dispose();
                    }
                }

                IWriter output = new EndianWriter(File.Open(outputPath, FileMode.Create, FileAccess.Write), Endian.BigEndian);
                AssemblyPatchWriter.WritePatch(patch, output);
                output.Dispose();

                MetroMessageBox.Show("Patch Created!",
                                     "Your patch has been created in the designated location. Happy sailing, modder!");
            }
            catch (Exception ex)
            {
                MetroException.Show(ex);
            }
        }
        /// <summary>
        /// Saves all permutations of a sound tag concatenated as a single sound file.
        /// </summary>
        /// <param name="Filename">The file to save the data to.</param>
        /// <param name="Cache">The CacheFile containing the tag.</param>
        /// <param name="Tag">The sound tag.</param>
        /// <param name="Format">The format in which to save the data.</param>
        public static void SaveAllAsSingle(string Filename, CacheBase Cache, CacheBase.IndexItem Tag, SoundFormat Format)
        {
            var snd_ = DefinitionsManager.snd_(Cache, Tag);

            #region XMA
            if (Format == SoundFormat.XMA)
            {
                var total = GetTotalSize(Cache.ugh_, Cache.ugh_.PlayBacks[snd_.PlaybackIndex]);

                byte[] buffer = Cache.GetSoundRaw(snd_.RawID, total);

                if (buffer.Length == 0)
                {
                    throw new Exception("Empty raw data.");
                }
                var codec = Cache.ugh_.Codecs[snd_.CodecIndex];
                var xma   = GetXMA(buffer, snd_.SampleRate, codec.Type);

                if (!Directory.GetParent(Filename).Exists)
                {
                    Directory.GetParent(Filename).Create();
                }

                var          fs = File.OpenWrite(Filename);
                EndianWriter sw = new EndianWriter(fs, EndianFormat.BigEndian);
                sw.Write(xma);

                sw.Close();
                sw.Dispose();
            }
            #endregion
            #region WAV
            else if (Format == SoundFormat.WAV)
            {
                var tempName = Path.GetTempFileName();

                SaveAllAsSingle(tempName, Cache, Tag, SoundFormat.XMA);

                var info = new ProcessStartInfo(towav, tempName)
                {
                    CreateNoWindow   = true,
                    UseShellExecute  = false,
                    WorkingDirectory = Directory.GetParent(tempName).FullName
                };

                Process.Start(info).WaitForExit();

                if (File.Exists(Filename))
                {
                    File.Delete(Filename);
                }
                if (!Directory.GetParent(Filename).Exists)
                {
                    Directory.GetParent(Filename).Create();
                }
                File.Move(Path.ChangeExtension(tempName, "wav"), Filename);
                if (File.Exists(tempName))
                {
                    File.Delete(tempName);
                }
            }
            #endregion
            #region RAW
            else if (Format == SoundFormat.RAW)
            {
                byte[] buffer = Cache.GetSoundRaw(snd_.RawID, GetTotalSize(Cache.ugh_, Cache.ugh_.PlayBacks[snd_.PlaybackIndex]));

                if (!Directory.GetParent(Filename).Exists)
                {
                    Directory.GetParent(Filename).Create();
                }

                var          fs = new FileStream(Filename, FileMode.Create);
                BinaryWriter sw = new BinaryWriter(fs);

                sw.Write(buffer);
                sw.Close();
                sw.Dispose();
            }
            #endregion
            #region Other
            else
            {
                throw new InvalidOperationException("Invalid sound format received.");
            }
            #endregion
        }
        public static byte[] GetXMA(byte[] buffer, SampleRate sRate, SoundType sType)
        {
            int rate;

            switch (sRate)
            {
            case SampleRate._22050Hz:
                rate = 22050;
                break;

            case SampleRate._44100Hz:
                rate = 44100;
                break;

            default:
                rate = 44100;
                break;
                //throw new Exception("Check sample rate.");
            }

            int cCount;

            switch (sType)
            {
            case SoundType.Mono:
                cCount = 1;
                break;

            case SoundType.Stereo:
                cCount = 2;
                break;

            //case SoundType.Unknown2:
            //    cCount = 2;
            //    footer = stereoFooter;
            //    break;
            //case SoundType.Unknown3:
            //    cCount = 2;
            //    footer = stereoFooter;
            //    break;
            default:
                throw new NotSupportedException("Unsupported Sound Type.");
            }

            var          ms = new MemoryStream();
            EndianWriter sw = new EndianWriter(ms, EndianFormat.BigEndian);

            sw.Write(0x52494646); // 'RIFF'
            sw.EndianType = EndianFormat.LittleEndian;
            sw.Write(buffer.Length + 0x34);
            sw.EndianType = EndianFormat.BigEndian;
            sw.Write(RIFFFormat.WAVE);

            // Generate the 'fmt ' chunk
            sw.Write(0x666D7420); // 'fmt '
            sw.EndianType = EndianFormat.LittleEndian;
            sw.Write(0x20);
            sw.Write((short)0x165);
            sw.Write((short)16);
            sw.Write((short)0);
            sw.Write((short)0);
            sw.Write((short)1);
            sw.Write((byte)0);
            sw.Write((byte)3);
            sw.Write(0);
            sw.Write(rate);
            sw.Write(0);
            sw.Write(0);
            sw.Write((byte)0);
            sw.Write((byte)cCount);
            sw.Write((short)0x0002);

            // 'data' chunk
            sw.EndianType = EndianFormat.BigEndian;
            sw.Write(0x64617461); // 'data'
            sw.EndianType = EndianFormat.LittleEndian;
            sw.Write(buffer.Length);
            sw.Write(buffer);

            sw.Close();
            sw.Dispose();

            return(ms.ToArray());
        }
        /// <summary>
        /// Saves selected permutations of a sound tag.
        /// </summary>
        /// <param name="Folder">The folder to save all files in. Each file will be named as the permutation name.</param>
        /// <param name="Cache">The CacheFile containing the tag.</param>
        /// <param name="Tag">The sound tag.</param>
        /// <param name="Format">The format in which to save the data.</param>
        /// <param name="Indices">The indices of the permutations to extract.</param>
        public static void SaveSelected(string Folder, CacheBase Cache, CacheBase.IndexItem Tag, SoundFormat Format, List <int> Indices, bool Overwrite)
        {
            var           snd_  = DefinitionsManager.snd_(Cache, Tag);
            List <byte[]> perms = new List <byte[]>();

            var ugh_     = Cache.ugh_;
            var playback = ugh_.PlayBacks[snd_.PlaybackIndex];
            var data     = Cache.GetSoundRaw(snd_.RawID, GetTotalSize(ugh_, playback));

            if (playback.PermutationCount == 1)
            {
                perms.Add(data);
            }
            else
            {
                Folder = Directory.GetParent(Folder) + "\\" + Path.GetFileNameWithoutExtension(Folder);

                for (int i = 0; i < playback.PermutationCount; i++)
                {
                    var perm = Cache.ugh_.SoundPermutations[playback.FirstPermutation + i];
                    perms.Add(GetPermData(data, ugh_, perm));
                }
            }

            #region XMA
            if (Format == SoundFormat.XMA)
            {
                foreach (int index in Indices)
                {
                    string Filename = (playback.PermutationCount == 1) ? Folder : Folder + "\\" + ugh_.SoundNames[ugh_.SoundPermutations[playback.FirstPermutation + index].NameIndex].Name + ".xma";
                    if (!Filename.EndsWith(".xma"))
                    {
                        Filename += ".xma";
                    }

                    if (File.Exists(Filename) && !Overwrite)
                    {
                        continue;
                    }

                    byte[] buffer = perms[index];
                    var    codec  = Cache.ugh_.Codecs[snd_.CodecIndex];
                    var    xma    = GetXMA(buffer, snd_.SampleRate, codec.Type);

                    if (!Directory.GetParent(Filename).Exists)
                    {
                        Directory.GetParent(Filename).Create();
                    }

                    var          fs = new FileStream(Filename, FileMode.Create);
                    EndianWriter sw = new EndianWriter(fs, EndianFormat.BigEndian);
                    sw.Write(xma);

                    sw.Close();
                    sw.Dispose();
                }
            }
            #endregion
            #region WAV
            else if (Format == SoundFormat.WAV)
            {
                foreach (int index in Indices)
                {
                    string Filename = (playback.PermutationCount == 1) ? Folder : Folder + "\\" + ugh_.SoundNames[ugh_.SoundPermutations[playback.FirstPermutation + index].NameIndex].Name + ".wav";
                    if (!Filename.EndsWith(".wav"))
                    {
                        Filename += ".wav";
                    }

                    if (File.Exists(Filename) && !Overwrite)
                    {
                        continue;
                    }

                    var tempName = Path.GetTempFileName();

                    #region Write XMA
                    var buffer = perms[index];
                    var codec  = Cache.ugh_.Codecs[snd_.CodecIndex];
                    var xma    = GetXMA(buffer, snd_.SampleRate, codec.Type);

                    var          fs = File.OpenWrite(tempName);
                    EndianWriter sw = new EndianWriter(fs, EndianFormat.BigEndian);
                    sw.Write(xma);

                    sw.Close();
                    sw.Dispose();
                    #endregion

                    var info = new ProcessStartInfo(towav, tempName)
                    {
                        CreateNoWindow   = true,
                        UseShellExecute  = false,
                        WorkingDirectory = Directory.GetParent(tempName).FullName
                    };

                    Process.Start(info).WaitForExit();

                    if (File.Exists(Filename))
                    {
                        File.Delete(Filename);
                    }
                    if (!Directory.GetParent(Filename).Exists)
                    {
                        Directory.GetParent(Filename).Create();
                    }
                    File.Move(Path.ChangeExtension(tempName, "wav"), Filename);
                    if (File.Exists(tempName))
                    {
                        File.Delete(tempName);
                    }
                }
            }
            #endregion
            #region RAW
            else if (Format == SoundFormat.RAW)
            {
                foreach (int index in Indices)
                {
                    string Filename = (playback.PermutationCount == 1) ? Folder : Folder + "\\" + ugh_.SoundNames[ugh_.SoundPermutations[playback.FirstPermutation + index].NameIndex].Name + ".bin";
                    if (!Filename.EndsWith(".bin"))
                    {
                        Filename += ".bin";
                    }

                    if (File.Exists(Filename) && !Overwrite)
                    {
                        continue;
                    }

                    byte[] buffer = perms[index];

                    if (!Directory.GetParent(Filename).Exists)
                    {
                        Directory.GetParent(Filename).Create();
                    }

                    var          fs = new FileStream(Filename, FileMode.Create);
                    BinaryWriter sw = new BinaryWriter(fs);

                    sw.Write(buffer);
                    sw.Close();
                    sw.Dispose();
                }
            }
            #endregion
        }