Exemplo n.º 1
0
        static void Main(string[] args)
        {
            if (args == null || args.Length < 2)
            {
                return;
            }

            // Loads texture
            //XPR2 xp = XPR2.FromFile(args[0]);
            //return;

            // Loads song resources
            SongManager sm = new SongManager(args[0]);

            // Loads single rif file
            RiffFile rif = sm.LoadRiffFile(args[1]);

            if (args.Length < 3)
            {
                return;
            }

            // Exports strings to file
            StringKey.ExportToFile(args[2]);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Loads and manages Index2, Catalog2, PackageDef objects
        /// </summary>
        /// <param name="workingDirectory"></param>
        public SongManager(string workingDirectory)
        {
            // Returns if directory doesn't exist
            if (!Directory.Exists(workingDirectory))
            {
                return;
            }
            _workingDirectory = workingDirectory;

            string[] rifFiles = Directory.GetFiles(_workingDirectory, "*.rif", SearchOption.TopDirectoryOnly);

            // Loads objects from riff files
            foreach (string rifFile in rifFiles)
            {
                RiffFile rif = new RiffFile();
                rif.Import(rifFile);

                foreach (ZObject zobj in rif.Objects)
                {
                    if (zobj is Index2)
                    {
                        _index2 = zobj as Index2;
                        LoadStringTablePaths();
                    }
                    else if (zobj is Catalog2)
                    {
                        _catalog2 = zobj as Catalog2;
                    }
                    else if (zobj is PackageDef)
                    {
                        _packageDef = zobj as PackageDef;
                    }
                }
            }

            // Look for PackageDef
            string[] packageDefs = Directory.GetFiles(Path.Combine(_workingDirectory, "packagedefs"), "packagedef.rif", SearchOption.AllDirectories);
            //packageDefs = packageDefs.OrderBy(x => x).ToArray();
            if (packageDefs.Length <= 0)
            {
                return;
            }

            RiffFile packageDef = new RiffFile();

            packageDef.Import(packageDefs[0]);

            foreach (ZObject zobj in packageDef.Objects)
            {
                if (zobj is PackageDef)
                {
                    _packageDef = zobj as PackageDef;
                    break;
                }
            }

            UpdateStringTableFromHKey(_index2.IndexKey);
            UpdateStringTableFromHKey(_catalog2.IndexKey);
            UpdateStringTableFromHKey(_packageDef.IndexKey);
        }
Exemplo n.º 3
0
        // インデックスには、データ チャンクのリストとファイル内でのその位置が含まれている。
        // インデックスは、AVIOLDINDEX 構造体で構成され、各データ チャンクのエントリが含まれている。
        // ファイルにインデックスが含まれる場合、AVIMAINHEADER 構造体の dwFlags メンバにある AVIF_HASINDEX フラグを設定する。
        private static void WriteIdx1Chunk(RiffFile riff, List <Idx1Entry> IndexList)
        {
            const int AVIIF_KEYFRAME = 0x00000010; // 前後のフレームの情報なしにこのフレームの完全な情報を含んでいる
            var       chunk          = riff.CreateChunk("idx1");

            int offset = 4;

            foreach (var item in IndexList)
            {
                int length = item.Length;

                chunk.Write(ToFourCC(item.ChunkId));
                chunk.Write(AVIIF_KEYFRAME);
                chunk.Write(offset);
                chunk.Write(length);

                offset += 8 + length; // 8は多分00dcとデータサイズ
                if (item.Padding)
                {
                    offset += 1;
                }
            }

            chunk.Close();
        }
Exemplo n.º 4
0
        public SoundclusterSfbk(RiffFile aRiffFile)
            : base()
        {
            RiffChunkListSfbk lSfbkList = ( RiffChunkListSfbk )aRiffFile.riffChunkList;

            try
            {
                List <RiffChunkList> lSdtaListList = lSfbkList.sdtaListList;

                RiffChunkListSdta[] sdtaBodyList = new RiffChunkListSdta[lSdtaListList.Count];

                for (int i = 0; i < lSdtaListList.Count; i++)
                {
                    sdtaBodyList[i] = ( RiffChunkListSdta )lSdtaListList[i];
                }

                List <RiffChunkList> pdtaListList = lSfbkList.pdtaListList;

                for (int i = 0; i < pdtaListList.Count; i++)
                {
                    RiffChunkListPdta pdtaList = ( RiffChunkListPdta )pdtaListList[i];

                    Dictionary <string, Instrument> lInstrumentDictionary = InstrumentSfbk.CreateInstrumentList(pdtaList);
                    List <InstrumentBase>           instrumentList        = CreateInstrumentList(pdtaList, sdtaBodyList, lInstrumentDictionary, aRiffFile.name);

                    PhdrData[] phdrDataArray = pdtaList.phdrBody.phdrDataArray;

                    for (int j = 0; j < phdrDataArray.Length - 1; j++)
                    {
                        int bank       = phdrDataArray[j].bank;
                        int instrument = phdrDataArray[j].preset % 128;

                        Logger.LogNormal("Name:" + phdrDataArray[j].name + "");
                        Logger.LogNormal("Bank/Preset:" + bank + "/" + instrument);

                        if (bank == 128)
                        {
                            Logger.LogWarning("Change Bank:" + bank);
                            bank = 0x7F00;
                        }

                        if (bankDictionary.ContainsKey(bank) == false)
                        {
                            Logger.LogWarning("Bank:" + bank);
                            bankDictionary.Add(bank, new BankSfbk());
                        }

                        bankDictionary[bank].AddInstrument(instrument, instrumentList[j]);
                    }
                }
            }
            catch (Exception aExpection)
            {
                Logger.LogError("Expection at RIFF Read:" + aExpection.ToString());
            }
        }
Exemplo n.º 5
0
        public SoundclusterDls(RiffFile aRiffFile)
            : base()
        {
            RiffChunkListDls_ dls_Riff = ( RiffChunkListDls_ )aRiffFile.riffChunkList;

            List <WaveformBase> lWaveformList = new List <WaveformBase>();

            try
            {
                RiffChunkListWvpl wvplList = ( RiffChunkListWvpl )dls_Riff.wvplListList;

                for (int i = 0; i < wvplList.waveListList.Count; i++)
                {
                    RiffChunkListWave lWaveList = ( RiffChunkListWave )wvplList.waveListList[i];

                    lWaveformList.Add(new WaveformDls(lWaveList, aRiffFile.name));
                }

                RiffChunkListLins linsList = ( RiffChunkListLins )dls_Riff.linsListList;

                Logger.LogWarning("linsList.ins_ListList.Count:" + linsList.ins_ListList.Count);

                for (int i = 0; i < linsList.ins_ListList.Count; i++)
                {
                    RiffChunkListIns_ ins_List = ( RiffChunkListIns_ )linsList.ins_ListList[i];

                    RiffChunkInsh inshChunk = ( RiffChunkInsh )ins_List.inshChunk;

                    int bank = ( int )inshChunk.midiLocal.bank;

                    if (( uint )bank == 0x80000000)
                    {
                        Logger.LogWarning("Change Bank:" + bank.ToString("X8"));

                        bank = 0x7F00;
                    }

                    if (bankDictionary.ContainsKey(bank) == false)
                    {
                        Logger.LogWarning("Bank:" + bank.ToString("X8"));
                        bankDictionary.Add(bank, new BankDls());
                    }

                    BankDls lDlsBank = ( BankDls )bankDictionary[bank];
                    lDlsBank.AddInstrument(ins_List, lWaveformList);
                }
            }
            catch (Exception aExpection)
            {
                Logger.LogError("Expection at RIFF Read:" + aExpection.ToString());
            }
        }
Exemplo n.º 6
0
        public AviWriter(System.IO.Stream outputAvi, string fourCC, int width, int height, float fps)
        {
            // RIFFファイルは、RIFFヘッダーとその後ろに続く 0個以上のリストとチャンクで構成されている。
            // RIFFヘッダーは、'RIFF'のFOURCC、4バイトのデータサイズ、データを識別するFOURCC、データから構成されている。
            // リストは、'LIST'のFOURCC、4バイトのデータサイズ、データを識別するFOURCC、データから構成されている。
            // チャンクは、データを識別するFOURCC、4バイトのデータサイズ、データから構成されている。
            // チャンクデータを識別するFOURCCは、2桁のストリーム番号とその後に続く2文字コード(dc=ビデオ,wb=音声,tx=字幕など)で構成されている。
            // AVIファイルは、'AVI 'のFOURCCと、2つの必須のLISTチャンク('hdrl''movi')、オプションのインデックスチャンクから構成されるRIFFファイルである。

            var riffFile = new RiffFile(outputAvi, "AVI ");

            // hdrlリストを仮のフレーム数で作成
            var hdrlList = riffFile.CreateList("hdrl");

            WriteHdrlList(hdrlList, fourCC, width, height, fps, 1);
            hdrlList.Close();

            // moviリストを作成し、OnAddImageごとにデータチャンクを追加
            var idx1List = new List <Idx1Entry>();
            var moviList = riffFile.CreateList("movi");

            this.OnAddImage += (data) =>
            {
                var idx1 = WriteMoviList(moviList, "00dc", data);
                idx1List.Add(idx1);
            };

            // ファイルをクローズ
            this.OnClose += () =>
            {
                // moviリストを閉じる
                moviList.Close();

                // idx1チャンクを作成
                WriteIdx1Chunk(riffFile, idx1List);

                // hdrlListを正しいフレーム数で上書き
                var offset = hdrlList.Offset;
                riffFile.BaseStream.Seek(offset, System.IO.SeekOrigin.Begin);        // hdrlリストの先頭まで戻る
                riffFile.BaseStream.Seek(12, System.IO.SeekOrigin.Current);          // hdrlリストのヘッダ分飛ばす
                WriteHdrlList(riffFile, fourCC, width, height, fps, idx1List.Count); // hdrlリストのデータを正しいフレーム数で上書き
                riffFile.BaseStream.Seek(0, System.IO.SeekOrigin.End);               // 元の場所に戻る

                // ファイルをクローズ
                riffFile.Close();
                outputAvi.Dispose();
            };
        }
Exemplo n.º 7
0
        public WaveformWave(RiffFile aRiffFile)
            : base()
        {
            RiffChunkListWave lWaveList = ( RiffChunkListWave )aRiffFile.riffChunkList;

            int lPosition = ( int )lWaveList.dataChunk.position;
            int lLength   = ( int )lWaveList.dataChunk.size;

            int lChannels   = lWaveList.fmt_Chunk.channels;
            int lSampleRate = ( int )lWaveList.fmt_Chunk.samplesPerSec;
            int lSampleBits = lWaveList.fmt_Chunk.bitsPerSample;
            int lSamples    = lLength / (lSampleBits / 8) / lChannels;

            format = new FormatWaweform(lChannels, lSamples, lSampleRate, lSampleBits);
            data   = new WaveformData(format, null, aRiffFile.name, lPosition);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Loads single .rif file
        /// <para>Absolute Path: c:\bandfuse_dlc\songs\adaytoremember\thedownfallofusall\fused.rif</para>
        /// <para>Relative Path: songs\adaytoremember\thedownfallofusall\fused.rif</para>
        /// </summary>
        /// <param name="rifPath">File path</param>
        /// <param name="relative">Path relative to SongManager directory?</param>
        /// <returns>Riff File</returns>
        public RiffFile LoadRiffFile(string rifPath, bool relative = true)
        {
            // Opens single rif file
            RiffFile rif = new RiffFile();

            if (relative)
            {
                // Combines working directory + input file path
                rif.Import(Path.Combine(_workingDirectory, rifPath));
            }
            else
            {
                rif.Import(rifPath);
            }

            return(rif);
        }
Exemplo n.º 9
0
			public static void AddMarkers(String WaveFile, Dictionary<double, string> Markers)
			{
				var file = new RiffFile(WaveFile, false);

				var reader = new WaveFileReader(WaveFile);
				WaveFormat fmt = reader.WaveFormat;

				string temp1name = Path.GetDirectoryName(WaveFile) + Path.GetFileNameWithoutExtension(WaveFile) + "-temp" +
								   Path.GetExtension(WaveFile);

				// find old cue chunk, or add new
				var cueChunk = file.GetChunk<CkCue>() as CkCue;
				if (cueChunk == null)
				{
					cueChunk = file.AddChunk(CkType.cue) as CkCue;
				}
				else
					cueChunk.CuePoints.Clear();

				var listChunk = file.GetChunk<CkList>() as CkList;
				if (listChunk == null || listChunk.TypeID != LiCkType.adtl)
				{
					listChunk = file.AddChunk(CkType.LIST) as CkList;
					if (listChunk != null) listChunk.TypeID = LiCkType.adtl;
				}

				if (listChunk != null) listChunk.Chunks.Clear();

				uint cueCounter = 0;

				foreach (var pair in Markers)
				{
					var samplePos = (uint)(pair.Key * fmt.SampleRate);
					var cp = new CuePoint(samplePos) { ID = ++cueCounter };
					if (cueChunk != null) cueChunk.CuePoints.Add(cp);
					var labl = new LiCkInfoLabl(cp, pair.Value);
					if (listChunk != null) listChunk.Chunks.Add(labl);
				}
				reader.Close();
				reader.Dispose();
				file.Save(temp1name);
				file.Close();

				File.Replace(temp1name, WaveFile, null);
			}
Exemplo n.º 10
0
        private void exportStringsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // This exports all strings from all rif files found
            fbd.Description = "Open Folder";
            if (!(fbd.ShowDialog() == DialogResult.OK))
            {
                return;
            }

            sfd.Title            = "Save";
            sfd.Filter           = "Text|*.txt";
            sfd.InitialDirectory = fbd.SelectedPath;

            if (!(sfd.ShowDialog() == DialogResult.OK))
            {
                return;
            }

            string[] files = Directory.GetFiles(fbd.SelectedPath, "*.rif", SearchOption.AllDirectories);

            foreach (string file in files)
            {
                RiffFile rif = new RiffFile();

                try
                {
                    // Loads strings from file
                    rif.Import(file);
                }
                catch
                {
                }
            }

            // Exports all strings
            StringKey.ExportToFile(sfd.FileName);
            MessageBox.Show("Exported strings successfully!");
        }
Exemplo n.º 11
0
			public static void StripPadding(string WaveFile, int Seconds)
			{
				var reader = new WaveFileReader(WaveFile);
				var strTarget = new BinaryWriter(new MemoryStream());
				WaveFormat fmt = reader.WaveFormat;

				string temp1name = Path.GetDirectoryName(WaveFile) + Path.DirectorySeparatorChar +
								   Path.GetFileNameWithoutExtension(WaveFile) + "-temp." + Path.GetExtension(WaveFile);
				string temp2name = Path.GetDirectoryName(WaveFile) + Path.DirectorySeparatorChar +
								   Path.GetFileNameWithoutExtension(WaveFile) + "-old." + Path.GetExtension(WaveFile);
				int samples = fmt.SampleRate * Seconds;
				int sampleSize = (fmt.BitsPerSample / 8) * fmt.Channels;
				int padBytes = samples * sampleSize;
				var bufsize = (int)(reader.Length - (padBytes * 2));
				var buf = new byte[bufsize];
				int newSampleCount = bufsize / sampleSize;

				reader.Seek(padBytes, SeekOrigin.Begin);
				strTarget.Write(reader.Read(buf, 0, buf.Length));
				reader.Close();
				reader.Dispose();

				var file = new RiffFile(WaveFile, false);
				file.GetChunk<CkData>().Data = buf;

				// adjust marker positions, remove if outside
				foreach (Chunk ch in file.Chunks)
				{
					if (ch.GetType() == typeof(CkCue))
					{
						var me = ch as CkCue;
						//foreach (CuePoint cp in me.CuePoints)
						if (me != null)
							for (int i = me.CuePoints.Count - 1; i >= 0; i--)
							{
								CuePoint cp = me.CuePoints[i];
								cp.Position -= (uint)samples;
								cp.SampleOffset -= (uint)samples;
								if (cp.Position > newSampleCount)
									me.CuePoints.Remove(cp);
							}
					}

						// trim down region lengths (ugly, but necessary due to Vegas rounding rather than truncating)
					else if (ch is CkList)
					{
						var me = ch as CkList;
						foreach (ListChunk lch in me.Chunks)
						{
							if (lch.GetType() == typeof(LiCkLtxt))
							{
								var lt = lch as LiCkLtxt;
								if (lt != null && lt.SampleLength > newSampleCount)
								{
									lt.SampleLength = (uint)newSampleCount;
								}
							}
							else if (lch.GetType() == typeof(LiCkInfoTCOD))
							{
								var tch = lch as LiCkInfoTCOD;
								if (tch != null) tch.Position += (uint)samples;
							}
							else if (lch.GetType() == typeof(LiCkInfoTCDO))
							{
								var tch = lch as LiCkInfoTCDO;
								if (tch != null) tch.Position -= (uint)samples;
							}
						}
					}
				}
				file.Save(temp1name);
				File.Move(WaveFile, temp2name);
				File.Move(temp1name, WaveFile);
				File.Delete(temp2name);
			}
Exemplo n.º 12
0
            public static void AddMarkers(String WaveFile, Dictionary <double, string> Markers)
            {
                var file = new RiffFile(WaveFile, false);

                var        reader = new WaveFileReader(WaveFile);
                WaveFormat fmt    = reader.WaveFormat;

                string temp1name = Path.GetDirectoryName(WaveFile) + Path.GetFileNameWithoutExtension(WaveFile) + "-temp" +
                                   Path.GetExtension(WaveFile);

                // find old cue chunk, or add new
                var cueChunk = file.GetChunk <CkCue>() as CkCue;

                if (cueChunk == null)
                {
                    cueChunk = file.AddChunk(CkType.cue) as CkCue;
                }
                else
                {
                    cueChunk.CuePoints.Clear();
                }

                var listChunk = file.GetChunk <CkList>() as CkList;

                if (listChunk == null || listChunk.TypeID != LiCkType.adtl)
                {
                    listChunk = file.AddChunk(CkType.LIST) as CkList;
                    if (listChunk != null)
                    {
                        listChunk.TypeID = LiCkType.adtl;
                    }
                }

                if (listChunk != null)
                {
                    listChunk.Chunks.Clear();
                }

                uint cueCounter = 0;

                foreach (var pair in Markers)
                {
                    var samplePos = (uint)(pair.Key * fmt.SampleRate);
                    var cp        = new CuePoint(samplePos)
                    {
                        ID = ++cueCounter
                    };
                    if (cueChunk != null)
                    {
                        cueChunk.CuePoints.Add(cp);
                    }
                    var labl = new LiCkInfoLabl(cp, pair.Value);
                    if (listChunk != null)
                    {
                        listChunk.Chunks.Add(labl);
                    }
                }
                reader.Close();
                reader.Dispose();
                file.Save(temp1name);
                file.Close();

                File.Replace(temp1name, WaveFile, null);
            }
Exemplo n.º 13
0
            public static void StripPadding(string WaveFile, int Seconds)
            {
                var        reader    = new WaveFileReader(WaveFile);
                var        strTarget = new BinaryWriter(new MemoryStream());
                WaveFormat fmt       = reader.WaveFormat;

                string temp1name = Path.GetDirectoryName(WaveFile) + Path.DirectorySeparatorChar +
                                   Path.GetFileNameWithoutExtension(WaveFile) + "-temp." + Path.GetExtension(WaveFile);
                string temp2name = Path.GetDirectoryName(WaveFile) + Path.DirectorySeparatorChar +
                                   Path.GetFileNameWithoutExtension(WaveFile) + "-old." + Path.GetExtension(WaveFile);
                int samples        = fmt.SampleRate * Seconds;
                int sampleSize     = (fmt.BitsPerSample / 8) * fmt.Channels;
                int padBytes       = samples * sampleSize;
                var bufsize        = (int)(reader.Length - (padBytes * 2));
                var buf            = new byte[bufsize];
                int newSampleCount = bufsize / sampleSize;

                reader.Seek(padBytes, SeekOrigin.Begin);
                strTarget.Write(reader.Read(buf, 0, buf.Length));
                reader.Close();
                reader.Dispose();

                var file = new RiffFile(WaveFile, false);

                file.GetChunk <CkData>().Data = buf;

                // adjust marker positions, remove if outside
                foreach (Chunk ch in file.Chunks)
                {
                    if (ch.GetType() == typeof(CkCue))
                    {
                        var me = ch as CkCue;
                        //foreach (CuePoint cp in me.CuePoints)
                        if (me != null)
                        {
                            for (int i = me.CuePoints.Count - 1; i >= 0; i--)
                            {
                                CuePoint cp = me.CuePoints[i];
                                cp.Position     -= (uint)samples;
                                cp.SampleOffset -= (uint)samples;
                                if (cp.Position > newSampleCount)
                                {
                                    me.CuePoints.Remove(cp);
                                }
                            }
                        }
                    }

                    // trim down region lengths (ugly, but necessary due to Vegas rounding rather than truncating)
                    else if (ch is CkList)
                    {
                        var me = ch as CkList;
                        foreach (ListChunk lch in me.Chunks)
                        {
                            if (lch.GetType() == typeof(LiCkLtxt))
                            {
                                var lt = lch as LiCkLtxt;
                                if (lt != null && lt.SampleLength > newSampleCount)
                                {
                                    lt.SampleLength = (uint)newSampleCount;
                                }
                            }
                            else if (lch.GetType() == typeof(LiCkInfoTCOD))
                            {
                                var tch = lch as LiCkInfoTCOD;
                                if (tch != null)
                                {
                                    tch.Position += (uint)samples;
                                }
                            }
                            else if (lch.GetType() == typeof(LiCkInfoTCDO))
                            {
                                var tch = lch as LiCkInfoTCDO;
                                if (tch != null)
                                {
                                    tch.Position -= (uint)samples;
                                }
                            }
                        }
                    }
                }
                file.Save(temp1name);
                File.Move(WaveFile, temp2name);
                File.Move(temp1name, WaveFile);
                File.Delete(temp2name);
            }
Exemplo n.º 14
0
        private void WriteRegionFile(string name, RegionData regionFile)
        {
            var          formatter = new BinaryFormatter();
            var          path      = Path.Combine(SaveFolder.FullName, name);
            const string fileId    = "VRGN";

            using (var mems = new MemoryStream())
            {
                using (var sw = new RiffFile(mems, fileId))
                {
                    // Region file meta
                    using (var meta = sw.CreateChunk("RMTA"))
                    {
                        // Data Version
                        meta.Write((byte)1);
                    }

                    // Tiles
                    using (var list = sw.CreateList("TILS"))
                    {
                        foreach (var tile in regionFile.tiles)
                        {
                            if (tile == null)
                            {
                                continue;
                            }

                            using (var tileList = list.CreateList("TILE"))
                            {
                                // Tile Meta
                                using (var tileMeta = tileList.CreateChunk("TMTA"))
                                {
                                    tileMeta.Write(tile._indexX);
                                    tileMeta.Write(tile._indexY);
                                    tileMeta.Write(tile._indexZ);
                                    tileMeta.Write(tile._generationState);
                                }

                                // Heightmap
                                using (var heightmap = tileList.CreateChunk("HMAP"))
                                {
                                    formatter.Serialize(heightmap, tile._heightmap);
                                }

                                // Block Data
                                using (var blockData = tileList.CreateChunk("BLKS"))
                                {
                                    formatter.Serialize(blockData, tile._gridBlock);
                                }

                                // Block Extra Data
                                if (tile._gridExtra != null)
                                {
                                    using (var extraData = tileList.CreateList("TXTA"))
                                    {
                                        foreach (var byteArray in tile._gridExtra)
                                        {
                                            using (var blockExtra = extraData.CreateChunk("BXTA"))
                                            {
                                                formatter.Serialize(blockExtra, byteArray);
                                            }
                                        }
                                    }
                                }

                                // Entities
                                if (tile._gridEntities != null)
                                {
                                    using (var entityData = tileList.CreateList("ENTS"))
                                    {
                                        foreach (var byteArray in tile._gridEntities)
                                        {
                                            using (var blockExtra = entityData.CreateChunk("ENTY"))
                                            {
                                                formatter.Serialize(blockExtra, byteArray);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                using (var fs = new GZipStream(new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None), CompressionMode.Compress))
                {
                    var b = mems.GetBuffer();
                    fs.Write(b, 0, b.Length);
                    fs.Flush();
                }
            }
        }
Exemplo n.º 15
0
        private RegionData LoadRegionFile(string name, Vector3I region)
        {
            RegionData data = null;

            lock (dataCache)
            {
                foreach (var rgn in dataCache)
                {
                    if (rgn.Region == region)
                    {
                        data = rgn;
                        break;
                    }
                }

                if (data != null)
                {
                    dataCache.Remove(data);
                    dataCache.Add(data);

                    while (dataCache.Count > 5)
                    {
                        dataCache.RemoveAt(0);
                    }

                    return(data);
                }

                data = new RegionData()
                {
                    Region = region
                };
                dataCache.Add(data);

                while (dataCache.Count > 5)
                {
                    dataCache.RemoveAt(0);
                }
            }

            lock (data)
            {
                var formatter = new BinaryFormatter();
                var path      = Path.Combine(SaveFolder.FullName, name);
                if (File.Exists(path))
                {
                    byte[] mdata;
                    using (var gzs = new GZipStream(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read), CompressionMode.Decompress))
                    {
                        using (var mems = new MemoryStream())
                        {
                            gzs.CopyTo(mems);
                            mems.Close();
                            mdata = mems.ToArray();
                        }
                    }

                    using (var sw = new RiffFile(new MemoryStream(mdata)))
                    {
                        foreach (var chunk in sw.Chunks)
                        {
                            switch (chunk.ChunkId)
                            {
                            case "RMTA": // Region file meta
                            {
                                var version = chunk.ReadByte();
                                if (version != 1)
                                {
                                    throw new NotImplementedException();
                                }
                            }
                            break;

                            case "LIST":
                            {
                                var list = chunk.ToList();
                                switch (list.ListId)
                                {
                                case "TILS":
                                    foreach (var chunk2 in list.Chunks)
                                    {
                                        switch (chunk2.ChunkId)
                                        {
                                        case "LIST":
                                        {
                                            var list2 = chunk2.ToList();
                                            switch (list2.ListId)
                                            {
                                            case "TILE":
                                            {
                                                var tileData = new RegionData.TileData();
                                                foreach (var chunk3 in list2.Chunks)
                                                {
                                                    switch (chunk3.ChunkId)
                                                    {
                                                    case "TMTA":
                                                        tileData._indexX          = chunk3.ReadInt32();
                                                        tileData._indexY          = chunk3.ReadInt32();
                                                        tileData._indexZ          = chunk3.ReadInt32();
                                                        tileData._generationState = chunk3.ReadInt32();
                                                        data.SetTile(tileData);
                                                        break;

                                                    case "HMAP":
                                                    {
                                                        var a = (int[])formatter.Deserialize(chunk);
                                                        Array.Copy(a, tileData._heightmap, a.Length);
                                                    }
                                                    break;

                                                    case "BLKS":
                                                    {
                                                        var a = (ushort[])formatter.Deserialize(chunk);
                                                        Array.Copy(a, tileData._gridBlock, a.Length);
                                                    }
                                                    break;

                                                    case "LIST":
                                                    {
                                                        var list3 = chunk3.ToList();
                                                        switch (list3.ListId)
                                                        {
                                                        case "TXTA":
                                                            break;

                                                        case "ENTS":
                                                            break;
                                                        }
                                                    }
                                                    break;
                                                    }
                                                }
                                            }
                                            break;
                                            }
                                        }
                                        break;
                                        }
                                    }
                                    break;
                                }
                            }
                            break;
                            }

                            //            // Block Extra Data
                            //            using (var extraData = tileList.CreateList("TXTA"))
                            //            {
                            //                foreach (var byteArray in tile._gridExtra)
                            //                {
                            //                    using (var blockExtra = extraData.CreateChunk("BXTA"))
                            //                    {
                            //                        formatter.Serialize(blockExtra, byteArray);
                            //                    }
                            //                }
                            //            }

                            //            // Entities
                            //            using (var entityData = tileList.CreateList("ENTS"))
                            //            {
                            //                foreach (var byteArray in tile._gridEntities)
                            //                {
                            //                    using (var blockExtra = entityData.CreateChunk("ENTY"))
                            //                    {
                            //                        formatter.Serialize(blockExtra, byteArray);
                            //                    }
                            //                }
                            //            }
                        }
                    }
                }

                return(data);
            }
        }
Exemplo n.º 16
0
        public static void Execute(FileInfo aFileInput, string aFilePathOutput, List <double> aProgressList, int aIndex)
        {
            RiffFile          lRiffFile          = ( RiffFile )PoolCollection.poolWav.Get(aFileInput.FullName);
            RiffChunkListWave lRiffChunkListWave = ( RiffChunkListWave )lRiffFile.riffChunkList;

            WaveformBase waveform = LoaderWaveform.Load(aFileInput.FullName);

            SByte[] lSampleArray = new SByte[waveform.format.samples];

            for (int i = 0; i < waveform.format.samples; i++)
            {
                lSampleArray[i] = ( SByte )(waveform.data.GetSampleData(0, i) >> 8);
            }

            List <LoopInformation> lLoopList = null;

            try
            {
                lLoopList = LoopSearchTool.Execute(lSampleArray, aProgressList, aIndex);
            }
            catch (Exception aExpection)
            {
                UnityEngine.Debug.Log(aExpection.ToString() + ":LoopTool Exception");
            }

            //for( int i = 0; i < lLoopList.Count; i++ )
            if (lLoopList.Count >= 1)
            {
                //lRiffChunkListWave.AddCuePoint( ( int )lLoopList[i].start.sample, ( int )lLoopList[i].end.sample );
                //lRiffChunkListWave.AddSampleLoop( ( int )lLoopList[i].start.sample, ( int )lLoopList[i].end.sample );
                lRiffChunkListWave.AddCuePoint(( int )lLoopList[0].start.sample, ( int )lLoopList[0].end.sample);
                lRiffChunkListWave.AddSampleLoop(( int )lLoopList[0].start.sample, ( int )lLoopList[0].end.sample);
            }

            Byte[] lDataArrayRead = null;

            using (FileStream u = new FileStream(lRiffFile.name, FileMode.Open, FileAccess.Read))
            {
                ByteArray l = new ByteArrayLittle(u);

                int bytePosition = ( int )lRiffChunkListWave.dataChunk.position;

                l.SetPosition(bytePosition);

                lDataArrayRead = l.ReadBytes(lRiffChunkListWave.dataChunk.size);
            }

            Byte[] lDataArrayWrite = lDataArrayRead;

            if (IsCutLast == true)
            {
                lDataArrayWrite = new Byte[(( int )lLoopList[0].end.sample + 1) * 4];

                for (int i = 0; i < (lLoopList[0].end.sample + 1) * 4; i++)
                {
                    lDataArrayWrite[i] = lDataArrayRead[i];
                }
            }

            for (int i = 0; i < 64; i++)
            {
                Logger.LogDebug(i.ToString() + ":" + lDataArrayWrite[i]);
            }

            lRiffChunkListWave.SetDataArray(lDataArrayWrite);

            MemoryStream    lMemoryStreamWrite = new MemoryStream(( int )lRiffChunkListWave.size + 8);
            ByteArrayLittle lByteArray         = new ByteArrayLittle(lMemoryStreamWrite);

            //lByteArrayRead.Open();
            lRiffFile.WriteByteArray(null, lByteArray);
            //lByteArrayRead.Close();

            using (FileStream u = new FileStream(aFilePathOutput, FileMode.Create, FileAccess.Write))
            {
                u.Write(lMemoryStreamWrite.GetBuffer(), 0, ( int )lMemoryStreamWrite.Length);
            }
        }
Exemplo n.º 17
0
        public MusicWave(RiffFile aRiffFile)
        {
            RiffChunkListWave lWaveRiff = ( RiffChunkListWave )aRiffFile.riffChunkList;

            nameFile     = aRiffFile.name;
            bytePosition = ( int )lWaveRiff.dataChunk.position;
            byteSize     = ( int )lWaveRiff.dataChunk.size;

            Channels     = lWaveRiff.fmt_Chunk.channels;
            SampleRate   = ( int )lWaveRiff.fmt_Chunk.samplesPerSec;
            sampleBits   = lWaveRiff.fmt_Chunk.bitsPerSample;
            SampleLength = ( int )(byteSize / (sampleBits / 8) / Channels);

            sampleArray = new float[Channels][];

            if (LENGTH_BUFFER == 0)
            {
                lengthBuffer = SampleLength;
            }
            else
            {
                lengthBuffer = LENGTH_BUFFER;
            }

            for (int i = 0; i < Channels; i++)
            {
                sampleArray[i] = new float[lengthBuffer];
            }

            startPosition = 0x7FFFFFFF;

            if (lWaveRiff.smplChunk != null)
            {
                Loop = new List <List <LoopInformation> >();

                int lIndex      = -1;
                int lLoopLength = -1;

                for (int i = 0; i < lWaveRiff.smplChunk.sampleLoops; i++)
                {
                    SampleLoop lLoop = lWaveRiff.smplChunk.sampleLoopList[i];

                    if (( int )(lLoop.end - lLoop.start) == lLoopLength)
                    {
                    }
                    else
                    {
                        Loop.Add(new List <LoopInformation>());
                        lLoopLength = ( int )(lLoop.end - lLoop.start);
                        lIndex++;
                    }

                    Loop[lIndex].Add(new LoopInformation(SampleRate, ( int )lLoop.start, ( int )lLoop.end));
                }
            }
            else
            {
                Loop = new List <List <LoopInformation> >();
                Loop.Add(new List <LoopInformation>());
                Loop[0].Add(new LoopInformation(SampleRate, 0, 0));
            }
        }