public void ArrangeBeatMapViaDifficulty() { bool audioFileFound = false; //Get Maps Difficulty First for (int i = 0; i < mapObj.mapInfos.Length; i++) { string mapPath = GetMapPath(mapObj.folderName, mapObj.mapInfos[i].mapName); Beatmap beatmap = BeatmapDecoder.Decode(mapPath); mapObj.mapInfos[i].difficulty = beatmap.DifficultySection.OverallDifficulty; //Only initialised Once if (!audioFileFound) { string audioName = beatmap.GeneralSection.AudioFilename; List <string> audioNameSplit = audioName.Split('.').ToList(); audioNameSplit.RemoveAt(audioNameSplit.Count - 1); //Remove the last index audioName = string.Join(".", audioNameSplit); mapObj.audioFile = Resources.Load <AudioClip>(string.Format("Beatmaps/{0}/{1}", mapObj.folderName, audioName)); audioFileFound = true; } } System.Array.Sort(mapObj.mapInfos, (x, y) => x.difficulty.CompareTo(y.difficulty)); }
protected override Beatmap GetBeatmap() { try { Beatmap beatmap; BeatmapDecoder decoder; using (var stream = new StreamReader(store.GetStream(getPathForFile(BeatmapInfo.Path)))) { decoder = BeatmapDecoder.GetDecoder(stream); beatmap = decoder.Decode(stream); } if (beatmap == null || BeatmapSetInfo.StoryboardFile == null) { return(beatmap); } using (var stream = new StreamReader(store.GetStream(getPathForFile(BeatmapSetInfo.StoryboardFile)))) decoder.Decode(stream, beatmap); return(beatmap); } catch { return(null); } }
public void InitialiseBeatMap(/*BeatmapData bmd, BeatmapInfo bmi*/) //BMD to Load Clips, BMI to Load Map. Currently Using Variables instead of Parameters { string mapPath = GetMapPath(OszUnpacker.bmds[bmdIndex].folderName, OszUnpacker.bmds[bmdIndex].mapInfos[bmiIndex].mapName); songPlayer.Stop(); songPlayer.loop = false; songPlayer.clip = OszUnpacker.bmds[bmdIndex].audio; beatmap = BeatmapDecoder.Decode(mapPath); beats = beatmap.HitObjects; spawnHitDist = beatHitPos.transform.position.z - beatSpawnPos.transform.position.z; bufferTime = Mathf.Abs(spawnHitDist) / scrollSpeed; startTimeOffset = trackDelayTime; float firstBeatTime = (float)beats[0].StartTime / 1000; if (firstBeatTime < bufferTime) { startTimeOffset += (bufferTime - firstBeatTime); } trackStartTime = AudioSettings.dspTime + startTimeOffset; trackEndTime = AudioSettings.dspTime + 1.5f + (float)(beats[beats.Count - 1].EndTime) / 1000; //Get the Track End Time print(trackEndTime - trackStartTime); songPlayer.PlayScheduled(trackStartTime); gameState = GameState.OnPlay; }
protected override Beatmap GetBeatmap() { try { Beatmap beatmap; using (var reader = getReader()) { BeatmapDecoder decoder; using (var stream = new StreamReader(reader.GetStream(BeatmapInfo.Path))) { decoder = BeatmapDecoder.GetDecoder(stream); beatmap = decoder?.Decode(stream); } if (WithStoryboard && beatmap != null && BeatmapSetInfo.StoryboardFile != null) { using (var stream = new StreamReader(reader.GetStream(BeatmapSetInfo.StoryboardFile))) decoder.Decode(stream, beatmap); } } return(beatmap); } catch { return(null); } }
private void Osu_Signal(string line) { var data = line.Split('|'); if (data.Length != 5) { return; } // [ time, audioPath, audioCurrentTime, audioPlaybackRate, beatmapPath ] // 재생 중인 곡이 바꼈다! if (data[1] != curAudio.Path) { using (var fs = new FileStream(data[1], FileMode.Open, FileAccess.Read)) { curAudio = AudioDecoder.GetDecoder(fs)?.Decode(fs); } curAudio.Path = data[1]; using (var sr = new StreamReader(data[4])) { curAudio.Beatmap = BeatmapDecoder.GetDecoder(sr)?.Decode(sr); } UpdateLyrics(); } curTime = DateTimeOffset.Now.Subtract( DateTimeOffset.FromFileTime(Convert.ToInt64(data[0], 16)) ).TotalSeconds + Convert.ToDouble(data[2]); _playbackRate = 1 + Convert.ToDouble(data[3]) / 100; }
public void Import(params string[] paths) { foreach (string p in paths) { var path = p; string hash = null; BeatmapMetadata metadata; using (var reader = ArchiveReader.GetReader(storage, path)) metadata = reader.ReadMetadata(); if (connection.Table <BeatmapSetInfo>().Count(b => b.BeatmapSetID == metadata.BeatmapSetID) != 0) { return; // TODO: Update this beatmap instead } if (File.Exists(path)) // Not always the case, i.e. for LegacyFilesystemReader { using (var md5 = MD5.Create()) using (var input = storage.GetStream(path)) { hash = BitConverter.ToString(md5.ComputeHash(input)).Replace("-", "").ToLowerInvariant(); input.Seek(0, SeekOrigin.Begin); path = Path.Combine(@"beatmaps", hash.Remove(1), hash.Remove(2), hash); using (var output = storage.GetStream(path, FileAccess.Write)) input.CopyTo(output); } } var beatmapSet = new BeatmapSetInfo { BeatmapSetID = metadata.BeatmapSetID, Beatmaps = new List <BeatmapInfo>(), Path = path, Hash = hash, Metadata = metadata }; using (var reader = ArchiveReader.GetReader(storage, path)) { string[] mapNames = reader.ReadBeatmaps(); foreach (var name in mapNames) { using (var stream = new StreamReader(reader.GetStream(name))) { var decoder = BeatmapDecoder.GetDecoder(stream); Beatmap beatmap = decoder.Decode(stream); beatmap.BeatmapInfo.Path = name; // TODO: Diff beatmap metadata with set metadata and leave it here if necessary beatmap.BeatmapInfo.Metadata = null; beatmapSet.Beatmaps.Add(beatmap.BeatmapInfo); } } } Import(new[] { beatmapSet }); } }
private void loadFiles() { var bmPath = Path.Combine(osuRoot, "Songs", dmp.FolderName, dmp.FileName); var rpPath = Path.Combine(osuRoot, @"Data\r", $"{dmp.MD5Hash}-{sc.ScoreTimestamp.ToFileTimeUtc()}.osr"); bm = BeatmapDecoder.Decode(bmPath); rp = ReplayDecoder.Decode(rpPath); }
protected virtual Beatmap CreateBeatmap() { Beatmap beatmap; using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(test_beatmap_data))) using (var reader = new StreamReader(stream)) beatmap = BeatmapDecoder.GetDecoder(reader).Decode(reader); return(beatmap); }
public LegacyFilesystemReader(string path) { basePath = path; beatmaps = Directory.GetFiles(basePath, @"*.osu").Select(f => Path.GetFileName(f)).ToArray(); if (beatmaps.Length == 0) { throw new FileNotFoundException(@"This directory contains no beatmaps"); } using (var stream = new StreamReader(GetStream(beatmaps[0]))) { var decoder = BeatmapDecoder.GetDecoder(stream); firstMap = decoder.Decode(stream); } }
public LegacyFilesystemReader(string path) { basePath = path; BeatmapFilenames = Directory.GetFiles(basePath, @"*.osu").Select(Path.GetFileName).ToArray(); if (BeatmapFilenames.Length == 0) { throw new FileNotFoundException(@"This directory contains no beatmaps"); } StoryboardFilename = Directory.GetFiles(basePath, @"*.osb").Select(Path.GetFileName).FirstOrDefault(); using (var stream = new StreamReader(GetStream(BeatmapFilenames[0]))) { var decoder = BeatmapDecoder.GetDecoder(stream); firstMap = decoder.Decode(stream); } }
public OszArchiveReader(Stream archiveStream) { this.archiveStream = archiveStream; archive = ZipFile.Read(archiveStream); beatmaps = archive.Entries.Where(e => e.FileName.EndsWith(@".osu")) .Select(e => e.FileName).ToArray(); if (beatmaps.Length == 0) { throw new FileNotFoundException(@"This directory contains no beatmaps"); } using (var stream = new StreamReader(GetStream(beatmaps[0]))) { var decoder = BeatmapDecoder.GetDecoder(stream); firstMap = decoder.Decode(stream); } }
bool songFlag = true; // 노래 재생 플래그 /// 게임 시작과 동시에 호출됨 /// 노트 재생 전에 필요한 작업을 처리함 void Start(int songNumber) { //파서 경로 설정 beatmap = BeatmapDecoder.Decode(Application.dataPath + "/StreamingAssets/LoveDramatic.osu"); //4레인 마니아 비트맵인지 확인 CheckBeatmap(); //기본 비트맵 데이터 얻기 velocity = (float)beatmap.DifficultySection.SliderMultiplier; GetGeneral(); GetMetadata(); //노트 생성 및 노래 재생 CreateNote(); }
public Beatmap GetBeatmap(BeatmapInfo beatmapInfo) { var beatmapSet = Query <BeatmapSetInfo>() .Where(s => s.BeatmapSetID == beatmapInfo.BeatmapSetID).FirstOrDefault(); if (beatmapSet == null) { throw new InvalidOperationException( $@"Beatmap set {beatmapInfo.BeatmapSetID} is not in the local database."); } using (var reader = GetReader(beatmapSet)) using (var stream = new StreamReader(reader.ReadFile(beatmapInfo.Path))) { var decoder = BeatmapDecoder.GetDecoder(stream); return(decoder.Decode(stream)); } }
public static IEnumerator ScanSongDirectory() { Debug.Log("Scanning song directory"); if (!isScanningSongDirectory) { isScanningSongDirectory = true; } else { yield break; } Songs.Clear(); Songs.Add(Audio.Instance.Triangles); try { osuPaths = Directory.EnumerateFiles(PlayerData.PersistentPlayerData.BeatmapLocation, "*.osu", SearchOption.AllDirectories); } catch (ArgumentException e) { Debug.Log(e.Message); } foreach (string path in osuPaths ?? Enumerable.Empty <string>()) { Beatmap beatmap = BeatmapDecoder.Decode(path); string songFolderPath = path.Substring(0, path.LastIndexOf('\\') + 1); string audioPath = songFolderPath + beatmap.GeneralSection.AudioFilename; string backgroundPath = songFolderPath + beatmap.EventsSection.BackgroundImage; try { Song song = new Song(beatmap, Audio.Mp3ToAudioClip(File.ReadAllBytes(audioPath))); song.Background.LoadImage(File.ReadAllBytes(backgroundPath)); Songs.Add(song); } catch (FileNotFoundException e) { Debug.Log(e.Message); } Debug.Log(path); yield return(null); } isScanningSongDirectory = false; SongList.Instance.UpdateSongList(); SongSelection.Instance.UpdateSongList(); }
public void ParseAll() { foreach (var file in RawFiles) { var timer = new Stopwatch(); timer.Start(); var beatmap = BeatmapDecoder.Decode(file); timer.Stop(); Maps.Add(beatmap); Trace.WriteLine(string.Format( "Beatmap parsed in {0}ms: {1} - {2} [{3}] created by {4}.", timer.Elapsed.Milliseconds, beatmap.MetadataSection.Artist, beatmap.MetadataSection.Title, beatmap.MetadataSection.Version, beatmap.MetadataSection.Creator)); } }
static void RunOptions(Options opts) { // Parse Beatmap and replay var beatmap = new Beatmap(); var replay = new Replay(); try { beatmap = BeatmapDecoder.Decode(opts.BeatmapPath); } catch (Exception) { Console.WriteLine("Can not parse Beatmap " + opts.BeatmapPath); return; } if (opts.ReplayPath != null) { try { replay = ReplayDecoder.Decode(opts.ReplayPath); if (replay.Mods == OsuParsers.Enums.Mods.Relax) { return; } } catch (Exception) { Console.WriteLine("Can not parse Replay " + opts.ReplayPath); return; } } var associated = new AssociatedBeatmap(beatmap, replay); Console.WriteLine("Aim: {0:R}", associated.GetAimPrecision()); Console.WriteLine("Acc: {0:R}", associated.GetAccPrecision()); return; }
public void TestReadMetadata() { using (var osz = Resource.OpenResource("Beatmaps.241526 Soleily - Renatus.osz")) { var reader = new OszArchiveReader(osz); BeatmapMetadata meta; using (var stream = new StreamReader(reader.GetStream("Soleily - Renatus (Deif) [Platter].osu"))) meta = BeatmapDecoder.GetDecoder(stream).Decode(stream).Metadata; Assert.AreEqual(241526, meta.OnlineBeatmapSetID); Assert.AreEqual("Soleily", meta.Artist); Assert.AreEqual("Soleily", meta.ArtistUnicode); Assert.AreEqual("03. Renatus - Soleily 192kbps.mp3", meta.AudioFile); Assert.AreEqual("Deif", meta.Author); Assert.AreEqual("machinetop_background.jpg", meta.BackgroundFile); Assert.AreEqual(164471, meta.PreviewTime); Assert.AreEqual(string.Empty, meta.Source); Assert.AreEqual("MBC7 Unisphere 地球ヤバイEP Chikyu Yabai", meta.Tags); Assert.AreEqual("Renatus", meta.Title); Assert.AreEqual("Renatus", meta.TitleUnicode); } }
private void loadPlayerFor(RulesetInfo r) { Beatmap beatmap; using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(test_beatmap_data))) using (var reader = new StreamReader(stream)) beatmap = BeatmapDecoder.GetDecoder(reader).Decode(reader); beatmap.BeatmapInfo.Ruleset = r; var instance = r.CreateInstance(); WorkingBeatmap working = new TestWorkingBeatmap(beatmap); working.Mods.Value = new[] { instance.GetAllMods().First(m => m is ModNoFail) }; if (Player != null) { Remove(Player); } Add(Player = CreatePlayer(working, instance)); }
public void InitialiseBeatMap(BeatmapObject selectedMap, int mapIndex) //By Scriptable Object. Easier for Testing { this.selectedMap = selectedMap; this.mapIndex = mapIndex; if (mapIndex >= selectedMap.mapInfos.Length) { UnityEngine.Debug.LogError("Map Index Exceeds the Length of the Beat Map. Ensure that the Map Index is within the Array Length"); return; } //SO Method string mapPath = GetMapPath(selectedMap.folderName, selectedMap.mapInfos[mapIndex].mapName); songPlayer.clip = selectedMap.audioFile; beatmap = BeatmapDecoder.Decode(mapPath); beats = beatmap.HitObjects; spawnHitDist = beatHitPos.transform.position.z - beatSpawnPos.transform.position.z; //beatMoveDir = spawnHitDist < 0 ? -1f : 1f; bufferTime = Mathf.Abs(spawnHitDist) / scrollSpeed; startTimeOffset = trackDelayTime; float firstBeatTime = (float)beats[0].StartTime / 1000; if (firstBeatTime < bufferTime) { startTimeOffset += (bufferTime - firstBeatTime); } trackStartTime = AudioSettings.dspTime + startTimeOffset; songPlayer.PlayScheduled(trackStartTime); gameState = GameState.OnPlay; }
private BeatmapSetInfo getBeatmapSet(ArchiveReader archiveReader) { BeatmapMetadata metadata; using (var stream = new StreamReader(archiveReader.GetStream(archiveReader.BeatmapFilenames[0]))) metadata = BeatmapDecoder.GetDecoder(stream).Decode(stream).Metadata; string hash; string path; using (var input = archiveReader.GetUnderlyingStream()) { hash = input.GetMd5Hash(); input.Seek(0, SeekOrigin.Begin); path = Path.Combine(@"beatmaps", hash.Remove(1), hash.Remove(2), hash); if (!Storage.Exists(path)) { using (var output = Storage.GetStream(path, FileAccess.Write)) input.CopyTo(output); } } var existing = Connection.Table <BeatmapSetInfo>().FirstOrDefault(b => b.Hash == hash); if (existing != null) { GetChildren(existing); if (existing.DeletePending) { existing.DeletePending = false; Update(existing, false); BeatmapSetAdded?.Invoke(existing); } return(existing); } var beatmapSet = new BeatmapSetInfo { OnlineBeatmapSetID = metadata.OnlineBeatmapSetID, Beatmaps = new List <BeatmapInfo>(), Path = path, Hash = hash, Metadata = metadata }; using (var archive = ArchiveReader.GetReader(Storage, path)) { string[] mapNames = archive.BeatmapFilenames; foreach (var name in mapNames) { using (var raw = archive.GetStream(name)) using (var ms = new MemoryStream()) //we need a memory stream so we can seek and shit using (var sr = new StreamReader(ms)) { raw.CopyTo(ms); ms.Position = 0; var decoder = BeatmapDecoder.GetDecoder(sr); Beatmap beatmap = decoder.Decode(sr); beatmap.BeatmapInfo.Path = name; beatmap.BeatmapInfo.Hash = ms.GetMd5Hash(); // TODO: Diff beatmap metadata with set metadata and leave it here if necessary beatmap.BeatmapInfo.Metadata = null; // TODO: this should be done in a better place once we actually need to dynamically update it. beatmap.BeatmapInfo.Ruleset = rulesets.Query <RulesetInfo>().FirstOrDefault(r => r.ID == beatmap.BeatmapInfo.RulesetID); beatmap.BeatmapInfo.StarDifficulty = rulesets.Query <RulesetInfo>().FirstOrDefault(r => r.ID == beatmap.BeatmapInfo.RulesetID)?.CreateInstance()?.CreateDifficultyCalculator(beatmap).Calculate() ?? 0; beatmapSet.Beatmaps.Add(beatmap.BeatmapInfo); } } beatmapSet.StoryboardFile = archive.StoryboardFilename; } return(beatmapSet); }
/// <summary> /// Duplicates content from <paramref name="path"/> to storage and returns a representing <see cref="BeatmapSetInfo"/>. /// </summary> /// <param name="path">Content location</param> /// <returns><see cref="BeatmapSetInfo"/></returns> private BeatmapSetInfo getBeatmapSet(string path) { string hash = null; BeatmapMetadata metadata; using (var reader = ArchiveReader.GetReader(storage, path)) metadata = reader.ReadMetadata(); if (File.Exists(path)) // Not always the case, i.e. for LegacyFilesystemReader { using (var md5 = MD5.Create()) using (var input = storage.GetStream(path)) { hash = BitConverter.ToString(md5.ComputeHash(input)).Replace("-", "").ToLowerInvariant(); input.Seek(0, SeekOrigin.Begin); path = Path.Combine(@"beatmaps", hash.Remove(1), hash.Remove(2), hash); if (!storage.Exists(path)) { using (var output = storage.GetStream(path, FileAccess.Write)) input.CopyTo(output); } } } var existing = connection.Table <BeatmapSetInfo>().FirstOrDefault(b => b.Hash == hash); if (existing != null) { if (existing.DeletePending) { existing.DeletePending = false; Update(existing, false); BeatmapSetAdded?.Invoke(existing); } return(existing); } var beatmapSet = new BeatmapSetInfo { OnlineBeatmapSetID = metadata.OnlineBeatmapSetID, Beatmaps = new List <BeatmapInfo>(), Path = path, Hash = hash, Metadata = metadata }; using (var reader = ArchiveReader.GetReader(storage, path)) { string[] mapNames = reader.BeatmapFilenames; foreach (var name in mapNames) { using (var stream = new StreamReader(reader.GetStream(name))) { var decoder = BeatmapDecoder.GetDecoder(stream); Beatmap beatmap = decoder.Decode(stream); beatmap.BeatmapInfo.Path = name; // TODO: Diff beatmap metadata with set metadata and leave it here if necessary beatmap.BeatmapInfo.Metadata = null; beatmapSet.Beatmaps.Add(beatmap.BeatmapInfo); } } beatmapSet.StoryboardFile = reader.StoryboardFilename; } return(beatmapSet); }
public OsuManiaReader(String filePath) { bm = BeatmapDecoder.Decode(filePath); }
/// <summary> /// The main entry point for the application. /// </summary> // [STAThread] static void Main() { var osuPath = @"C:\Users\sunny\Programs\osu!\"; var songsPath = Path.Join(osuPath, "Songs"); var simPath = @"C:\Users\sunny\Programs\StepMania 5.1\Songs\Test"; var osuDbPath = Path.Join(osuPath, "osu!.db"); OsuDatabase db = DatabaseDecoder.DecodeOsu(osuDbPath); var songs = Directory.GetDirectories(songsPath); Dictionary <int, List <DbBeatmap> > bms = db.Beatmaps .GroupBy(x => x.BeatmapSetId, x => x) .ToDictionary(x => x.Key, x => x.ToList()); foreach (var songPath in songs) { var songFolder = Path.GetFileName(songPath); Console.WriteLine(songFolder); var maps = Directory.GetFiles(Path.Join(songsPath, songFolder), "*.osu"); Simfile s = null; List <DbBeatmap> bs = null; foreach (var mapPath in maps) { var songName = Path.GetFileNameWithoutExtension(mapPath); Console.WriteLine(" " + songName); Beatmap beatmap = BeatmapDecoder.Decode(Path.Join(songsPath, songFolder, songName + ".osu")); if (bs == null) { bs = bms[beatmap.MetadataSection.BeatmapSetID]; bs.Sort((x, y) => x.CirclesCount .CompareTo(y.CirclesCount)); } BasicSongInfo songInfo = OsuToAlgorithm.Convert(beatmap); Random rng = new Random(beatmap.MetadataSection.BeatmapID); StepScoreGenerator sg = new StepScoreGenerator { Rng = rng, }; Algorithm a = new Algorithm { Info = songInfo, RecoveryInterval = songInfo.PPQ / 2 / 8, StepScore = sg.RandomStepScore(songInfo), }; if (s == null) { s = AlgorithmToSimfile.Convert(beatmap, songInfo, new List <Simfile.Chart>()); } var x = a.Run(); var chart = AlgorithmToSimfile.ConvertChart(beatmap, songInfo, x, diff: bs.FindIndex(y => y.BeatmapId == beatmap.MetadataSection.BeatmapID) ); s.Charts.Add(chart); } Directory.CreateDirectory(Path.Join(simPath, songFolder)); var sb = new StringBuilder(); s.Append(sb); File.WriteAllText(Path.Join(simPath, songFolder, songFolder + ".sm"), sb.ToString()); File.Copy(Path.Join(songsPath, songFolder, s.Music), Path.Join(simPath, songFolder, s.Music), true); } //Application.SetHighDpiMode(HighDpiMode.SystemAware); //Application.EnableVisualStyles(); //Application.SetCompatibleTextRenderingDefault(false); //Application.Run(new Form1()); }
/// <summary> /// Duplicates content from <paramref name="path"/> to storage and returns a representing <see cref="BeatmapSetInfo"/>. /// </summary> /// <param name="path">Content location</param> /// <returns><see cref="BeatmapSetInfo"/></returns> private BeatmapSetInfo getBeatmapSet(string path) { string hash = null; BeatmapMetadata metadata; using (var reader = ArchiveReader.GetReader(storage, path)) metadata = reader.ReadMetadata(); if (File.Exists(path)) // Not always the case, i.e. for LegacyFilesystemReader { using (var input = storage.GetStream(path)) { hash = input.GetMd5Hash(); input.Seek(0, SeekOrigin.Begin); path = Path.Combine(@"beatmaps", hash.Remove(1), hash.Remove(2), hash); if (!storage.Exists(path)) { using (var output = storage.GetStream(path, FileAccess.Write)) input.CopyTo(output); } } } var existing = connection.Table <BeatmapSetInfo>().FirstOrDefault(b => b.Hash == hash); if (existing != null) { if (existing.DeletePending) { existing.DeletePending = false; Update(existing, false); BeatmapSetAdded?.Invoke(existing); } return(existing); } var beatmapSet = new BeatmapSetInfo { OnlineBeatmapSetID = metadata.OnlineBeatmapSetID, Beatmaps = new List <BeatmapInfo>(), Path = path, Hash = hash, Metadata = metadata }; using (var archive = ArchiveReader.GetReader(storage, path)) { string[] mapNames = archive.BeatmapFilenames; foreach (var name in mapNames) { using (var raw = archive.GetStream(name)) using (var ms = new MemoryStream()) //we need a memory stream so we can seek and shit using (var sr = new StreamReader(ms)) { raw.CopyTo(ms); ms.Position = 0; var decoder = BeatmapDecoder.GetDecoder(sr); Beatmap beatmap = decoder.Decode(sr); beatmap.BeatmapInfo.Path = name; beatmap.BeatmapInfo.Hash = ms.GetMd5Hash(); // TODO: Diff beatmap metadata with set metadata and leave it here if necessary beatmap.BeatmapInfo.Metadata = null; beatmap.BeatmapInfo.StarDifficulty = beatmap.CalculateStarDifficulty(); beatmapSet.Beatmaps.Add(beatmap.BeatmapInfo); } } beatmapSet.StoryboardFile = archive.StoryboardFilename; } return(beatmapSet); }
/// <summary> /// Reads osu data an deserializes it into an <see cref="ManiaBeatMap"/>. /// </summary> /// <param name="path">The osu file path.</param> /// <returns>A <see cref="ManiaBeatMap"/>.</returns> public static ManiaBeatMap ReadFromOsuFile(string path) { Beatmap beatmap = BeatmapDecoder.Decode(path); return((ManiaBeatMap)beatmap); }
void RandomizeBeatmap() { if (Directory.Exists("RandomizedMap")) { Directory.Delete("RandomizedMap", true); } if (File.Exists("RandomizedMap.osz")) { File.Delete("RandomizedMap.osz"); } Random r = new Random(); var kmap = LoadedMaps.ElementAt(r.Next(0, LoadedMaps.Count)); var ksong = LoadedMaps.ElementAt(r.Next(0, LoadedMaps.Count)); Beatmap map = BeatmapDecoder.Decode(kmap.FullName); Beatmap song = BeatmapDecoder.Decode(kmap.FullName); while (map.GeneralSection.Mode != song.GeneralSection.Mode && (!checkedListBox1.GetItemChecked(0) && (int)map.BeatLengthAt(0) == (int)song.BeatLengthAt(0))) { kmap = LoadedMaps.ElementAt(r.Next(0, LoadedMaps.Count)); ksong = LoadedMaps.ElementAt(r.Next(0, LoadedMaps.Count)); map = BeatmapDecoder.Decode(kmap.FullName); song = BeatmapDecoder.Decode(kmap.FullName); } while (map.GeneralSection.Mode != song.GeneralSection.Mode && checkedListBox1.GetItemChecked(0)) { kmap = LoadedMaps.ElementAt(r.Next(0, LoadedMaps.Count)); ksong = LoadedMaps.ElementAt(r.Next(0, LoadedMaps.Count)); map = BeatmapDecoder.Decode(kmap.FullName); song = BeatmapDecoder.Decode(kmap.FullName); } //create map directory Directory.CreateDirectory("RandomizedMap"); map.TimingPoints = song.TimingPoints; map.GeneralSection.AudioFilename = song.GeneralSection.AudioFilename; map.GeneralSection.Length = song.GeneralSection.Length; map.EventsSection.Breaks = song.EventsSection.Breaks; //copy audio file File.Copy(Path.Combine(Path.GetDirectoryName(ksong.FullName), song.GeneralSection.AudioFilename), Path.Combine("RandomizedMap", song.GeneralSection.AudioFilename)); //video randomizer if (checkedListBox1.GetItemChecked(2)) { var kvid = LoadedMaps.ElementAt(r.Next(0, LoadedMaps.Count)); Beatmap vid = BeatmapDecoder.Decode(kvid.FullName); while (string.IsNullOrEmpty(map.EventsSection.Video)) { kvid = LoadedMaps.ElementAt(r.Next(0, LoadedMaps.Count)); vid = BeatmapDecoder.Decode(kvid.FullName); } map.EventsSection.Video = vid.EventsSection.Video; map.EventsSection.VideoOffset = vid.EventsSection.VideoOffset; //copy video File.Copy(Path.Combine(Path.GetDirectoryName(kvid.FullName), vid.EventsSection.Video), Path.Combine("RandomizedMap", vid.EventsSection.Video)); } //storyboard randomizer /* * if (checkedListBox1.GetItemChecked(3)) * { * var ksb = LoadedMaps.ElementAt(r.Next(0, LoadedMaps.Count)); * Beatmap sb = BeatmapDecoder.Decode(ksb.FullName); * while (!sb.EventsSection.Storyboard.) * { * ksb = LoadedMaps.ElementAt(r.Next(0, LoadedMaps.Count)); * sb = BeatmapDecoder.Decode(ksb.FullName); * } * map.EventsSection.Video = sb.EventsSection.Video; * map.EventsSection.VideoOffset = sb.EventsSection.VideoOffset; * //copy video * File.Copy(Path.Combine(Path.GetDirectoryName(ksb.FullName), sb.EventsSection.Video), Path.Combine("RandomizedMap", sb.EventsSection.Video)); * } */ if (checkedListBox1.GetItemChecked(4)) { map.DifficultySection.CircleSize = r.Next(0, 100) / 10f; } if (checkedListBox1.GetItemChecked(5)) { map.DifficultySection.ApproachRate = r.Next(0, 100) / 10f; } if (checkedListBox1.GetItemChecked(6)) { map.DifficultySection.OverallDifficulty = r.Next(0, 100) / 10f; } if (checkedListBox1.GetItemChecked(7)) { map.DifficultySection.HPDrainRate = r.Next(0, 100) / 10f; } map.MetadataSection.Artist = "osu!map randomizer"; map.MetadataSection.Title = "Randomized map"; map.MetadataSection.Creator = "osu!map randomizer"; //copy background File.Copy(Path.Combine(Path.GetDirectoryName(kmap.FullName), song.EventsSection.BackgroundImage), Path.Combine("RandomizedMap", song.EventsSection.BackgroundImage)); map.Save(Path.Combine("RandomizedMap", "map.osu")); ZipFile.CreateFromDirectory(Path.GetFullPath("RandomizedMap"), "RandomizedMap.osz"); Process.Start(Path.GetFullPath("RandomizedMap.osz")); }
/// <summary> /// Import a beamap into our local <see cref="FileStore"/> storage. /// If the beatmap is already imported, the existing instance will be returned. /// </summary> /// <param name="files">The store to import beatmap files to.</param> /// <param name="beatmaps">The store to import beatmaps to.</param> /// <param name="reader">The beatmap archive to be read.</param> /// <returns>The imported beatmap, or an existing instance if it is already present.</returns> private BeatmapSetInfo importToStorage(FileStore files, BeatmapStore beatmaps, ArchiveReader reader) { // let's make sure there are actually .osu files to import. string mapName = reader.Filenames.FirstOrDefault(f => f.EndsWith(".osu")); if (string.IsNullOrEmpty(mapName)) { throw new InvalidOperationException("No beatmap files found in the map folder."); } // for now, concatenate all .osu files in the set to create a unique hash. MemoryStream hashable = new MemoryStream(); foreach (string file in reader.Filenames.Where(f => f.EndsWith(".osu"))) { using (Stream s = reader.GetStream(file)) s.CopyTo(hashable); } var hash = hashable.ComputeSHA2Hash(); // check if this beatmap has already been imported and exit early if so. var beatmapSet = beatmaps.BeatmapSets.FirstOrDefault(b => b.Hash == hash); if (beatmapSet != null) { undelete(beatmaps, files, beatmapSet); // ensure all files are present and accessible foreach (var f in beatmapSet.Files) { if (!storage.Exists(f.FileInfo.StoragePath)) { using (Stream s = reader.GetStream(f.Filename)) files.Add(s, false); } } // todo: delete any files which shouldn't exist any more. return(beatmapSet); } List <BeatmapSetFileInfo> fileInfos = new List <BeatmapSetFileInfo>(); // import files to manager foreach (string file in reader.Filenames) { using (Stream s = reader.GetStream(file)) fileInfos.Add(new BeatmapSetFileInfo { Filename = file, FileInfo = files.Add(s) }); } BeatmapMetadata metadata; using (var stream = new StreamReader(reader.GetStream(mapName))) metadata = BeatmapDecoder.GetDecoder(stream).Decode(stream).Metadata; beatmapSet = new BeatmapSetInfo { OnlineBeatmapSetID = metadata.OnlineBeatmapSetID, Beatmaps = new List <BeatmapInfo>(), Hash = hash, Files = fileInfos, Metadata = metadata }; var mapNames = reader.Filenames.Where(f => f.EndsWith(".osu")); foreach (var name in mapNames) { using (var raw = reader.GetStream(name)) using (var ms = new MemoryStream()) //we need a memory stream so we can seek and shit using (var sr = new StreamReader(ms)) { raw.CopyTo(ms); ms.Position = 0; var decoder = BeatmapDecoder.GetDecoder(sr); Beatmap beatmap = decoder.Decode(sr); beatmap.BeatmapInfo.Path = name; beatmap.BeatmapInfo.Hash = ms.ComputeSHA2Hash(); beatmap.BeatmapInfo.MD5Hash = ms.ComputeMD5Hash(); // TODO: Diff beatmap metadata with set metadata and leave it here if necessary beatmap.BeatmapInfo.Metadata = null; RulesetInfo ruleset = rulesets.GetRuleset(beatmap.BeatmapInfo.RulesetID); // TODO: this should be done in a better place once we actually need to dynamically update it. beatmap.BeatmapInfo.Ruleset = ruleset; beatmap.BeatmapInfo.StarDifficulty = ruleset?.CreateInstance()?.CreateDifficultyCalculator(beatmap).Calculate() ?? 0; beatmapSet.Beatmaps.Add(beatmap.BeatmapInfo); } } return(beatmapSet); }
void UnpackOszFile(FileInfo oszFile) { //First, ensure Temp Path Directory is Created. This is where all the Contents of the Osz Files will be dumped before it is moved to the official folder //tempPath = Application.dataPath + osuDumpPath + "Temp/"; //Set Correct Path to Temp Folder if (!Directory.Exists(tempPath)) { Directory.CreateDirectory(tempPath); } ZipFile.ExtractToDirectory(oszFile.FullName, tempPath); string[] allMapPaths = GetAllMapPaths(tempPath); //Gets all Osu files per Osz dumped in the Temp Path //Create Variables that will Store the Beatmap Data that will eventually save it to a Json File string folderName = string.Empty; //Meant to Store the Name for the Folder string dumpPath = string.Empty; //The Folder to Dump the Files BeatmapData bmd = null; //Create a Beatmap Data Class that will be initialised on the first For Loop bool bmdExists = false; //To Check if the Existing BMD exists for (int i = 0; i < allMapPaths.Length; i++) { //Decode the Beatmap Beatmap beatmap = BeatmapDecoder.Decode(allMapPaths[i]); if (i == 0) //If this is the First Map that is Decoded { //Initialise the Folder Name and the Dump Path for the Beatmap folderName = string.Format("{0} - {1}", beatmap.MetadataSection.Title, beatmap.MetadataSection.BeatmapSetID); //Initialise the Folder Name dumpPath = string.Format("{0}{1}{2}/", Application.dataPath, osuDumpPath, folderName); //Set Path to Dump ONLY the required resources for this Game //Check if the a BMD has been Created for the Osz Before bmd = bmds.FirstOrDefault(x => x.folderName == folderName); if (bmd == null) { bmd = new BeatmapData(); //bmdExists remains false } else { bmdExists = true; } bmd.folderName = folderName; bmd.songName = beatmap.MetadataSection.Title; bmd.artistName = beatmap.MetadataSection.Artist; if (!Directory.Exists(dumpPath)) { Directory.CreateDirectory(dumpPath); } //Only Get Audio File if it is missing if (string.IsNullOrEmpty(bmd.audioFilePath)) { string audioName = beatmap.GeneralSection.AudioFilename; string destinationPath = string.Format("{0}{1}", dumpPath, audioName); //Only Move Audio File if it does not Exist if (!File.Exists(destinationPath)) { File.Move(tempPath + audioName, destinationPath); } audioName = GetFileNameNoExt(destinationPath); //Update Audio Name to have no Exts for Resources.Load bmd.audioFilePath = string.Format("Beatmaps/{0}/{1}", folderName, audioName); //Path is Designed for Resources.Load } if (string.IsNullOrEmpty(bmd.imgFilePath)) { string imgName = beatmap.EventsSection.BackgroundImage; string destinationPath = string.Format("{0}{1}", dumpPath, imgName); //Only Move Img File if it does not Exist if (!File.Exists(destinationPath)) { File.Move(tempPath + imgName, destinationPath); } imgName = GetFileNameNoExt(destinationPath); //Update Image Name to have no Exts for Resources.Load bmd.imgFilePath = string.Format("Beatmaps/{0}/{1}", folderName, imgName); //Path is Designed for Resources.Load } } BeatmapInfo bmi = new BeatmapInfo { mapName = GetFileNameNoExt(allMapPaths[i]), creator = beatmap.MetadataSection.Creator, difficulty = beatmap.DifficultySection.OverallDifficulty }; bmi.scores = new List <ScoreInfo>(); //Check for any missing Beatmap Info if (!bmdExists || !bmd.mapInfos.Exists(x => x.mapName == bmi.mapName)) { bmd.mapInfos.Add(bmi); } if (!File.Exists(string.Format("{0}{1}{2}", dumpPath, bmi.mapName, ".osu"))) { File.Move(allMapPaths[i], string.Format("{0}{1}{2}", dumpPath, bmi.mapName, ".osu")); } } bmd.mapInfos.Sort((x, y) => x.difficulty.CompareTo(y.difficulty)); bmd.LoadAssets(); if (!bmdExists) { bmds.Add(bmd); } if (runtimeUnpacking) { lastAddedBmd = bmds.Last(); } /*DirectoryInfo dir = new DirectoryInfo(tempPath); * foreach (FileInfo file in dir.GetFiles()) File.Delete(file.FullName);*/ Directory.Delete(tempPath, true); File.Delete(oszFile.FullName); print("Unpacking File Completed"); }
/// <summary> /// Import a beamap into our local <see cref="FileStore"/> storage. /// If the beatmap is already imported, the existing instance will be returned. /// </summary> /// <param name="reader">The beatmap archive to be read.</param> /// <returns>The imported beatmap, or an existing instance if it is already present.</returns> private BeatmapSetInfo importToStorage(ArchiveReader reader) { // for now, concatenate all .osu files in the set to create a unique hash. MemoryStream hashable = new MemoryStream(); foreach (string file in reader.Filenames.Where(f => f.EndsWith(".osu"))) { using (Stream s = reader.GetStream(file)) s.CopyTo(hashable); } var hash = hashable.ComputeSHA2Hash(); // check if this beatmap has already been imported and exit early if so. var beatmapSet = beatmaps.QueryAndPopulate <BeatmapSetInfo>().FirstOrDefault(b => b.Hash == hash); if (beatmapSet != null) { Undelete(beatmapSet); return(beatmapSet); } List <FileInfo> fileInfos = new List <FileInfo>(); // import files to manager foreach (string file in reader.Filenames) { using (Stream s = reader.GetStream(file)) fileInfos.Add(files.Add(s, file)); } BeatmapMetadata metadata; using (var stream = new StreamReader(reader.GetStream(reader.Filenames.First(f => f.EndsWith(".osu"))))) metadata = BeatmapDecoder.GetDecoder(stream).Decode(stream).Metadata; beatmapSet = new BeatmapSetInfo { OnlineBeatmapSetID = metadata.OnlineBeatmapSetID, Beatmaps = new List <BeatmapInfo>(), Hash = hash, Files = fileInfos, Metadata = metadata }; var mapNames = reader.Filenames.Where(f => f.EndsWith(".osu")); foreach (var name in mapNames) { using (var raw = reader.GetStream(name)) using (var ms = new MemoryStream()) //we need a memory stream so we can seek and shit using (var sr = new StreamReader(ms)) { raw.CopyTo(ms); ms.Position = 0; var decoder = BeatmapDecoder.GetDecoder(sr); Beatmap beatmap = decoder.Decode(sr); beatmap.BeatmapInfo.Path = name; beatmap.BeatmapInfo.Hash = ms.ComputeSHA2Hash(); // TODO: Diff beatmap metadata with set metadata and leave it here if necessary beatmap.BeatmapInfo.Metadata = null; // TODO: this should be done in a better place once we actually need to dynamically update it. beatmap.BeatmapInfo.Ruleset = rulesets.Query <RulesetInfo>().FirstOrDefault(r => r.ID == beatmap.BeatmapInfo.RulesetID); beatmap.BeatmapInfo.StarDifficulty = rulesets.Query <RulesetInfo>().FirstOrDefault(r => r.ID == beatmap.BeatmapInfo.RulesetID)?.CreateInstance()?.CreateDifficultyCalculator(beatmap) .Calculate() ?? 0; beatmapSet.Beatmaps.Add(beatmap.BeatmapInfo); } } return(beatmapSet); }
private Beatmap BuildBeatmapFromFile(string fullMapFilePath) { // TODO: REFACTOR - Build decorated custom-beatmap class object (to reduce external class coupling to BMAPI). return(BeatmapDecoder.Decode(fullMapFilePath)); }