Пример #1
0
        static void Postfix(CustomPreviewBeatmapLevel __instance)
        {
#if DEBUG
            //Logger.Log($"Selected CustomLevel Path :\n {__instance.customLevelPath}", LogLevel.Notice);
#endif
            customLevelPath = __instance.customLevelPath;
        }
        public async void LoadScene()
        {
            IDifficultyBeatmap        diffBeatmap = BS_Utils.Plugin.LevelData.GameplayCoreSceneSetupData.difficultyBeatmap;
            CustomPreviewBeatmapLevel customPreviewBeatmapLevel = diffBeatmap.level as CustomPreviewBeatmapLevel;

            if (customPreviewBeatmapLevel != null)
            {
                string customLevelPath = customPreviewBeatmapLevel.customLevelPath;
                string mapFileName     = diffBeatmap.difficulty.Name();
                string filepath        = customLevelPath + "\\ExpertPlusEffect.dat";
                Logger.log.Error("custom level path = " + filepath);
                Logger.log.Error("custom level difficulty = " + mapFileName);


                player = new CutEffectPlayer();
                player.Init(gameObject);
                if (await player.TryLoadCutEffectMap(filepath))
                {
                    return;
                }
            }

            player = null;
            //string cutEffectMapPath = "D:\\ProgramFiles\\Steam\\steamapps\\common\\Beat Saber\\Beat Saber_Data\\CustomLevels\\2a7 (Night of Nights - squeaksies)\\ExpertPlusEffect.dat";
        }
Пример #3
0
        public double GetPP(CustomPreviewBeatmapLevel beatmapLevel, BeatmapDifficulty difficulty, BeatDataCharacteristics beatDataCharacteristics)
        {
            if (beatDataCharacteristics == BeatDataCharacteristics.Standard && this._downloader.Init && this._downloader.RowPPs.TryGetValue(beatmapLevel.GetHashOrLevelID().ToUpper(), out var pp))
            {
                // PP counterと同じ処理
                switch (difficulty)
                {
                case BeatmapDifficulty.Easy:
                    return(pp.EasySoloStandard);

                case BeatmapDifficulty.Normal:
                    return(pp.NormalSoloStandard);

                case BeatmapDifficulty.Hard:
                    return(pp.HardSoloStandard);

                case BeatmapDifficulty.Expert:
                    return(pp.ExpertSoloStandard);

                case BeatmapDifficulty.ExpertPlus:
                    return(pp.ExpertPlusSoloStandard);

                default:
                    break;
                }
            }
            var song = this.GetBeatStarSongDiffculityStats(beatmapLevel, difficulty, beatDataCharacteristics);

            if (song != null)
            {
                return(song.PP);
            }
            return(0);
        }
Пример #4
0
        /** If the callback is null, call the callback with the randomSongId, otherwise select the newly downloaded song */
        public async Task DownloadRandomSongAsync(RSPDownloadedCallback callback)
        {
            Beatmap mapData = await RandomSongGenerator.GenerateRandomKey();

            if (!(mapData is null))
            {
                string path;
                bool   freshDownload;
                (freshDownload, path) = await MapInstaller.InstallMap(mapData);

                Logger.log.Info("Chosen Random Song: " + path);

                path = Path.GetFullPath(path);

                if (freshDownload)
                {
                    Action OnLevelPacksRefreshed = null;
                    OnLevelPacksRefreshed = () =>
                    {
                        Loader.OnLevelPacksRefreshed -= OnLevelPacksRefreshed;
                        CustomPreviewBeatmapLevel installedMap = randomSongsFolder.Levels[path];
                        callback?.Invoke(installedMap);
                    };
                    Loader.OnLevelPacksRefreshed += OnLevelPacksRefreshed;
                    Loader.Instance.RefreshSongs(false);
                }
                else
                {
                    CustomPreviewBeatmapLevel installedMap = randomSongsFolder.Levels[path];
                    callback?.Invoke(installedMap);
                }
            }
        }
Пример #5
0
        private List <string> HandleMusicVideoData(CustomPreviewBeatmapLevel level, string videoDataFile)
        {
            var returnList = new List <string>();
            var fileData   = File.ReadAllText(videoDataFile);

            if (fileData.Substring(0, 1) == "{")
            {
                var video = JsonConvert.DeserializeObject <VideoDatas.VideoData>(fileData);
                if (!string.IsNullOrWhiteSpace(video.videoPath))
                {
                    AddIfExists(returnList, level, video.videoPath);
                }
            }
            else
            {
                var videoData = JsonConvert.DeserializeObject <VideoDatas>(fileData);
                if (videoData?.videos == null || !videoData.videos.Any())
                {
                    return(returnList);
                }

                foreach (var dataVideo in videoData.videos)
                {
                    AddIfExists(returnList, level, dataVideo.videoPath);
                }
            }

            return(returnList);
        }
Пример #6
0
        public static string GetCustomLevelHash(CustomPreviewBeatmapLevel level)
        {
            if (GetCachedSongData(level.customLevelPath, out var directoryHash, out var songHash))
            {
                return(songHash);
            }

            List <byte> combinedBytes = new List <byte>();

            combinedBytes.AddRange(File.ReadAllBytes(level.customLevelPath + '/' + "info.dat"));
            for (var i = 0; i < level.standardLevelInfoSaveData.difficultyBeatmapSets.Length; i++)
            {
                for (var i2 = 0; i2 < level.standardLevelInfoSaveData.difficultyBeatmapSets[i].difficultyBeatmaps.Length; i2++)
                {
                    if (File.Exists(level.customLevelPath + '/' + level.standardLevelInfoSaveData.difficultyBeatmapSets[i].difficultyBeatmaps[i2].beatmapFilename))
                    {
                        combinedBytes.AddRange(File.ReadAllBytes(level.customLevelPath + '/' + level.standardLevelInfoSaveData.difficultyBeatmapSets[i].difficultyBeatmaps[i2].beatmapFilename));
                    }
                }
            }

            string hash = CreateSha1FromBytes(combinedBytes.ToArray());

            cachedSongHashData[level.customLevelPath] = new SongHashData(directoryHash, hash);
            return(hash);
        }
Пример #7
0
        public void FilterSongList(ref List <BeatmapDetails> detailsList)
        {
            if (!_isInitialized || (!_oneSaberAppliedValue && !_lightshowAppliedValue && _mappingExtensionsAppliedValue == SongRequirement.Off))
            {
                return;
            }

            for (int i = 0; i < detailsList.Count;)
            {
                BeatmapDetails beatmap = detailsList[i];
                List <CustomPreviewBeatmapLevel> customLevels = null;
                if (_mappingExtensionsAppliedValue != SongRequirement.Off)
                {
                    customLevels = Loader.CustomLevels.Values.ToList();
                }

                if (_lightshowAppliedValue &&
                    !beatmap.DifficultyBeatmapSets.Any(diffSet => diffSet.DifficultyBeatmaps.Any(diff => diff.NotesCount == 0)))
                {
                    detailsList.RemoveAt(i);
                }
                else if (_oneSaberAppliedValue && !beatmap.DifficultyBeatmapSets.Any(diffSet => diffSet.CharacteristicName == "OneSaber"))
                {
                    detailsList.RemoveAt(i);
                }
                else if (_mappingExtensionsAppliedValue != SongRequirement.Off && !beatmap.IsOST)
                {
                    // remove songs that somehow aren't OST, but also aren't custom levels handled by SongCore
                    CustomPreviewBeatmapLevel customLevel = customLevels.FirstOrDefault(x => x.levelID == beatmap.LevelID);
                    if (customLevel == null)
                    {
                        detailsList.RemoveAt(i);
                        continue;
                    }

                    ExtraSongData songData = Collections.RetrieveExtraSongData(Hashing.GetCustomLevelHash(customLevel), customLevel.customLevelPath);
                    if (songData == null)
                    {
                        detailsList.RemoveAt(i);
                        continue;
                    }

                    bool required = songData._difficulties?.Any(x => x.additionalDifficultyData?._requirements?.Any(y => y == "Mapping Extensions") == true) == true;
                    if ((_mappingExtensionsAppliedValue == SongRequirement.Required && !required) ||
                        (_mappingExtensionsAppliedValue == SongRequirement.NotRequired && required))
                    {
                        detailsList.RemoveAt(i);
                        continue;
                    }

                    // passes check, requires mapping extensions
                    ++i;
                }
                else
                {
                    ++i;
                }
            }
        }
 static bool Prefix(MissionLevelDetailViewController __instance, MissionNode ____missionNode, TextMeshProUGUI ____missionText, TextMeshProUGUI ____songNameText, TextMeshProUGUI ____difficultyText, TextMeshProUGUI ____characteristicsText, ObjectiveListItemsList ____objectiveListItems, GameplayModifiersModelSO ____gameplayModifiersModel, GameObject ____modifiersPanelGO, GameplayModifierInfoListItemsList ____gameplayModifierInfoListItemsList)
 {
     if (____missionNode.missionData is CustomMissionDataSO)
     {
         CustomMissionDataSO       missionData = (____missionNode.missionData as CustomMissionDataSO);
         CustomPreviewBeatmapLevel level       = missionData.customLevel;
         ____missionText.text = Localization.Get("CAMPAIGN_MISSION") + " " + ____missionNode.formattedMissionNodeName;
         if (level == null)
         {
             ____songNameText.text        = string.Format(Localization.Get("CAMPAIGN_SONG"), "SONG NOT FOUND");
             ____difficultyText.text      = string.Format(Localization.Get("CAMPAIGN_DIFFICULTY"), "NOT FOUND");
             ____characteristicsText.text = string.Format(Localization.Get("CAMPAIGN_TYPE"), "NOT FOUND");
         }
         else
         {
             ____songNameText.text        = string.Format(Localization.Get("CAMPAIGN_SONG"), level.songName);
             ____difficultyText.text      = string.Format(Localization.Get("CAMPAIGN_DIFFICULTY"), BeatmapDifficultyMethods.Name(missionData.beatmapDifficulty));
             ____characteristicsText.text = string.Format(Localization.Get("CAMPAIGN_TYPE"), Localization.Get(missionData.beatmapCharacteristic.characteristicNameLocalizationKey));
         }
         MissionObjective[] missionObjectives = missionData.missionObjectives;
         ____objectiveListItems.SetData((missionObjectives.Length == 0) ? 1 : missionObjectives.Length, delegate(int idx, ObjectiveListItem objectiveListItem)
         {
             if (idx == 0 && missionObjectives.Length == 0)
             {
                 objectiveListItem.title         = Localization.Get("CAMPAIGN_FINISH_LEVEL");
                 objectiveListItem.conditionText = "";
                 objectiveListItem.hideCondition = true;
             }
             else
             {
                 MissionObjective missionObjective = missionObjectives[idx];
                 if (missionObjective.type.noConditionValue)
                 {
                     objectiveListItem.title         = missionObjective.type.objectiveNameLocalized.Replace(" ", "\n");
                     objectiveListItem.hideCondition = true;
                 }
                 else
                 {
                     objectiveListItem.title         = missionObjective.type.objectiveNameLocalized;
                     objectiveListItem.hideCondition = false;
                     ObjectiveValueFormatterSO objectiveValueFormater = missionObjective.type.objectiveValueFormater;
                     objectiveListItem.conditionText = $"{MissionDataExtensions.Name(missionObjective.referenceValueComparisonType)} {objectiveValueFormater.FormatValue(missionObjective.referenceValue)}";
                 }
             }
         });
         List <GameplayModifierParamsSO> modifierParamsList = ____gameplayModifiersModel.GetModifierParams(missionData.gameplayModifiers);
         ____modifiersPanelGO.SetActive(modifierParamsList.Count > 0);
         ____gameplayModifierInfoListItemsList.SetData(modifierParamsList.Count, delegate(int idx, GameplayModifierInfoListItem gameplayModifierInfoListItem)
         {
             GameplayModifierParamsSO gameplayModifierParamsSO = modifierParamsList[idx];
             gameplayModifierInfoListItem.modifierIcon         = gameplayModifierParamsSO.icon;
             gameplayModifierInfoListItem.modifierName         = Localization.Get(gameplayModifierParamsSO.modifierNameLocalizationKey);
             gameplayModifierInfoListItem.modifierDescription  = Localization.Get(gameplayModifierParamsSO.descriptionLocalizationKey);
             gameplayModifierInfoListItem.showSeparator        = (idx != modifierParamsList.Count - 1);
         });
         return(false);
     }
     return(true);
 }
Пример #9
0
        internal void EnvironmentButtonPressed()
        {
            CustomPreviewBeatmapLevel level                 = SongCore.Loader.GetLevelByHash(LEVEL_HASH);
            BeatmapDifficulty         beatmapDifficulty     = level.previewDifficultyBeatmapSets[0].beatmapDifficulties[0];
            BeatmapCharacteristicSO   beatmapCharacteristic = level.previewDifficultyBeatmapSets[0].beatmapCharacteristic;

            Utils.PlaySong(level, beatmapCharacteristic, beatmapDifficulty);
        }
Пример #10
0
        public static async Task <IPreviewBeatmapLevel?> DownloadSong(string levelId, CancellationToken cancellationToken)
        {
            string hash = levelId.Replace("custom_level_", "");
            var    bm   = await BeatSaverSharp.BeatSaver.Client.Hash(hash, cancellationToken);

            string folderPath = GetSongDirectoryName(bm.Key, bm.Metadata.SongName, bm.Metadata.LevelAuthorName);

            folderPath = Path.Combine(CustomLevelsFolder, folderPath);
            if (bm == null)
            {
                Plugin.Log?.Warn($"Could not find song '{hash}' on Beat Saver.");
                return(null);
            }
            byte[] beatmapBytes = await bm.DownloadZip(false, cancellationToken);

            using (var ms = new MemoryStream(beatmapBytes))
            {
                var result = await ExtractZip(ms, folderPath);

                if (folderPath != result.OutputDirectory)
                {
                    folderPath = result.OutputDirectory ?? throw new Exception("Zip extract failed, no output directory.");
                }
                if (result.Exception != null)
                {
                    throw result.Exception;
                }
            }
            Plugin.Log.Info($"Downloaded song to '{folderPath}'");

            using (var awaiter = new EventAwaiter <SongCore.Loader, Dictionary <string, CustomPreviewBeatmapLevel> >(cancellationToken))
            {
                try
                {
                    SongCore.Loader.SongsLoadedEvent += awaiter.OnEvent;

                    SongCore.Collections.AddSong($"custom_level_{hash}", folderPath);
                    SongCore.Loader.Instance.RefreshSongs(false);
                    await awaiter.Task;
                }
                catch (OperationCanceledException)
                { }
                catch (Exception e)
                {
                    Plugin.Log?.Error($"Error waiting for songs to load: {e.Message}");
                    Plugin.Log?.Debug(e);
                    throw;
                }
                finally
                {
                    SongCore.Loader.SongsLoadedEvent -= awaiter.OnEvent;
                }
            }

            CustomPreviewBeatmapLevel beatmap = SongCore.Loader.GetLevelByHash(hash);

            return(beatmap);
        }
Пример #11
0
        private async Task <CustomBeatmapLevel> LoadCustomBeatmapLevelAsync(CustomPreviewBeatmapLevel level, CancellationToken token)
        {
            CustomBeatmapLevel customLevel = new CustomBeatmapLevel(level, null, null);
            BeatmapLevelData   beatmapData = await _customLevelLoader.LoadBeatmapLevelDataAsync(level.customLevelPath, customLevel, level.standardLevelInfoSaveData, token).ConfigureAwait(false);

            customLevel.SetBeatmapLevelData(beatmapData);

            return(customLevel);
        }
 public Song(CustomPreviewBeatmapLevel _data)
 {
     songName        = _data.songName;
     songSubName     = _data.songSubName;
     songAuthorName  = _data.songAuthorName;
     levelAuthorName = _data.levelAuthorName;
     path            = _data.customLevelPath;
     hash            = SongCore.Collections.hashForLevelID(_data.levelID).ToLower();
 }
Пример #13
0
        public BeatSongDataDifficultyStats GetBeatStarSongDiffculityStats(CustomPreviewBeatmapLevel beatmapLevel, BeatmapDifficulty difficulty, BeatDataCharacteristics beatDataCharacteristics)
        {
            var song = this.GetBeatStarSong(beatmapLevel);

            if (song == null)
            {
                return(null);
            }
            return(this.GetBeatStarSongDiffculityStats(song, difficulty, beatDataCharacteristics));
        }
Пример #14
0
        /// <summary>
        /// Song date is stored in SongMetadata config file to be preserved after moving files to a different location.
        /// Initial date is loaded from file date.
        /// </summary>
        /// <param name="level"></param>
        /// <returns></returns>
        private DateTime GetSongUserDate(CustomPreviewBeatmapLevel level)
        {
            var metadata = SongMetadataStore.Instance.GetMetadataForLevelID(level.levelID);

            if (metadata.AddedAt == null)
            {
                metadata.AddedAt = GetSongUserDateFromFilesystem(level);
            }
            return(metadata.AddedAt.Value);
        }
Пример #15
0
        /// <summary>
        /// Get the BeatmapDetails associated with a specific levelID from data retrieved by SongDataCore.BeatSaver.
        /// </summary>
        /// <param name="level">The song's associated preview beatmap level.</param>
        /// <param name="beatmapDetails">The returned BeatmapDetails object, or null if it could not be retrieved.</param>
        /// <returns>An enum representing success or what went wrong.</returns>
        public static SongDataCoreDataStatus GetBeatmapDetails(CustomPreviewBeatmapLevel level, out BeatmapDetails beatmapDetails)
        {
            if (!IsModAvailable)
            {
                beatmapDetails = null;
                return(SongDataCoreDataStatus.NoData);
            }

            return(_GetBeatmapDetails(level, out beatmapDetails));
        }
Пример #16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="installedMap"></param>
        private void OnLevelPacksRefreshedSelect(CustomPreviewBeatmapLevel installedMap)
        {
            int installedLevelIndex = Array.FindIndex(randomSongsFolder.LevelPack.beatmapLevelCollection.beatmapLevels, x => (x.levelID == installedMap.levelID));

            LevelCollectionTableView levelCollectionTable = Resources.FindObjectsOfTypeAll <LevelCollectionTableView>().First();
            var tableView = levelCollectionTable.GetPrivateField <HMUI.TableView>("_tableView");

            tableView.ScrollToCellWithIdx(installedLevelIndex + 1, HMUI.TableView.ScrollPositionType.Center, true);
            tableView.SelectCellWithIdx(installedLevelIndex + 1, true);
        }
 static bool Prefix(MissionLevelDetailViewController __instance, MissionNode ____missionNode, LevelBar ____levelBar, ObjectiveListItemsList ____objectiveListItems, GameplayModifiersModelSO ____gameplayModifiersModel, GameObject ____modifiersPanelGO, GameplayModifierInfoListItemsList ____gameplayModifierInfoListItemsList)
 {
     if (____missionNode.missionData is CustomMissionDataSO)
     {
         CustomMissionDataSO       missionData = (____missionNode.missionData as CustomMissionDataSO);
         CustomPreviewBeatmapLevel level       = missionData.customLevel;
         if (level == null)
         {
             // TODO: Localization?
             ____levelBar.GetPrivateField <TextMeshProUGUI>("_songNameText").text   = "SONG NOT FOUND";
             ____levelBar.GetPrivateField <TextMeshProUGUI>("_difficultyText").text = "SONG NOT FOUND";
             ____levelBar.GetPrivateField <TextMeshProUGUI>("_authorNameText").text = "SONG NOT FOUND";
         }
         else
         {
             ____levelBar.Setup(level, missionData.beatmapCharacteristic, missionData.beatmapDifficulty);
         }
         MissionObjective[] missionObjectives = missionData.missionObjectives;
         ____objectiveListItems.SetData((missionObjectives.Length == 0) ? 1 : missionObjectives.Length, delegate(int idx, ObjectiveListItem objectiveListItem)
         {
             if (idx == 0 && missionObjectives.Length == 0)
             {
                 objectiveListItem.title         = Localization.Get("CAMPAIGN_FINISH_LEVEL");
                 objectiveListItem.conditionText = "";
                 objectiveListItem.hideCondition = true;
             }
             else
             {
                 MissionObjective missionObjective = missionObjectives[idx];
                 if (missionObjective.type.noConditionValue)
                 {
                     objectiveListItem.title         = missionObjective.type.objectiveNameLocalized.Replace(" ", "\n");
                     objectiveListItem.hideCondition = true;
                 }
                 else
                 {
                     objectiveListItem.title         = missionObjective.type.objectiveNameLocalized;
                     objectiveListItem.hideCondition = false;
                     ObjectiveValueFormatterSO objectiveValueFormater = missionObjective.type.objectiveValueFormater;
                     objectiveListItem.conditionText = $"{MissionDataExtensions.Name(missionObjective.referenceValueComparisonType)} {objectiveValueFormater.FormatValue(missionObjective.referenceValue)}";
                 }
             }
         });
         List <GameplayModifierParamsSO> modifierParamsList = ____gameplayModifiersModel.GetModifierParams(missionData.gameplayModifiers);
         ____modifiersPanelGO.SetActive(modifierParamsList.Count > 0);
         ____gameplayModifierInfoListItemsList.SetData(modifierParamsList.Count, delegate(int idx, GameplayModifierInfoListItem gameplayModifierInfoListItem)
         {
             GameplayModifierParamsSO gameplayModifierParamsSO = modifierParamsList[idx];
             gameplayModifierInfoListItem.modifierIcon         = gameplayModifierParamsSO.icon;
             gameplayModifierInfoListItem.hoverHintText        = Localization.Get(gameplayModifierParamsSO.modifierNameLocalizationKey) + " - " + Localization.Get(gameplayModifierParamsSO.descriptionLocalizationKey);
         });
         return(false);
     }
     return(true);
 }
Пример #18
0
 public CustomPreviewBeatmapLevel FindSong()
 {
     try
     {
         CustomPreviewBeatmapLevel level = Loader.CustomLevels.Values.First(x => x.customLevelPath.Contains("\\" + songid + (customDownloadURL == "" ? " " : ""))); //Including the space is to ensure that if they have a map with an old style beatsaver id it won't be falsely detected
         return(level);
     } catch
     {
         return(null);
     }
 }
Пример #19
0
        private static void StartLevel(IBeatmapLevel beatmapLevel, CustomPreviewBeatmapLevel beatmap, BeatmapDifficulty difficulty)
        {
            Logger.log.Info("Starting level");

            MenuTransitionsHelper menuSceneSetupData = Resources.FindObjectsOfTypeAll <MenuTransitionsHelper>().FirstOrDefault();
            PlayerData            playerSettings     = Resources.FindObjectsOfTypeAll <PlayerDataModel>().FirstOrDefault().playerData;

            var gamePlayModifiers = new GameplayModifiers();

            gamePlayModifiers.IsWithoutModifiers();

            IBeatmapLevel           level           = beatmapLevel;
            BeatmapCharacteristicSO characteristics = beatmap.previewDifficultyBeatmapSets[0].beatmapCharacteristic;
            IDifficultyBeatmap      levelDifficulty = BeatmapLevelDataExtensions.GetDifficultyBeatmap(level.beatmapLevelData, characteristics, difficulty);

            menuSceneSetupData.StartStandardLevel(levelDifficulty,
                                                  playerSettings.overrideEnvironmentSettings.overrideEnvironments ? playerSettings.overrideEnvironmentSettings : null,
                                                  playerSettings.colorSchemesSettings.overrideDefaultColors ? playerSettings.colorSchemesSettings.GetSelectedColorScheme() : null,
                                                  gamePlayModifiers,
                                                  playerSettings.playerSpecificSettings,
                                                  playerSettings.practiceSettings, "Exit", false, () => { }, (StandardLevelScenesTransitionSetupDataSO sceneTransition, LevelCompletionResults results) =>
            {
                bool newHighScore = false;

                var mainFlowCoordinator       = Resources.FindObjectsOfTypeAll <MainFlowCoordinator>().First();
                RandomSongMenu randomSongMenu = BeatSaberUI.CreateFlowCoordinator <RandomSongMenu>();

                if (results.levelEndAction == LevelCompletionResults.LevelEndAction.Restart)
                {
                    Logger.log.Info("Restarting level");
                    return;
                }

                switch (results.levelEndStateType)
                {
                case LevelCompletionResults.LevelEndStateType.None:
                    break;

                case LevelCompletionResults.LevelEndStateType.Cleared:
                    UploadScore(levelDifficulty, results, out newHighScore);
                    randomSongMenu.Show(beatmap, difficulty, levelDifficulty, results, newHighScore);
                    Logger.log.Info("Showing menu");
                    break;

                case LevelCompletionResults.LevelEndStateType.Failed:
                    Logger.log.Info("Showing menu");
                    randomSongMenu.Show(beatmap, difficulty, levelDifficulty, results, newHighScore);
                    break;

                default:
                    break;
                }
            });
        }
Пример #20
0
        public void Show(CustomPreviewBeatmapLevel customPreviewBeatmapLevel, BeatmapDifficulty difficulty, IDifficultyBeatmap levelDifficulty, LevelCompletionResults results, bool newHighScore)
        {
            this.beatmap                = customPreviewBeatmapLevel;
            this.difficulty             = difficulty;
            this.levelDifficulty        = levelDifficulty;
            this.levelCompletionResults = results;
            this.newHighScore           = newHighScore;

            mainFlowCoordinator = Resources.FindObjectsOfTypeAll <MainFlowCoordinator>().First();
            BeatSaberUI.PresentFlowCoordinator(mainFlowCoordinator, this);
        }
Пример #21
0
 //bananbread api
 public Song(CustomPreviewBeatmapLevel _data)
 {
     songName        = _data.songName;
     songSubName     = _data.songSubName;
     songAuthorName  = _data.songAuthorName;
     levelAuthorName = _data.levelAuthorName;
     //   difficultyLevels = ConvertDifficultyLevels(_data.standardLevelInfoSaveData.difficultyBeatmapSets.SelectMany(x => x.difficultyBeatmaps).ToArray());
     path = _data.customLevelPath;
     //bananabread id hash
     hash = SongCore.Collections.hashForLevelID(_data.levelID).ToLower();
     //  hash = SongCore.Utilities.Utils.GetCustomLevelHash(_data);
 }
        private void Setup()
        {
            Plugin.Log.Debug($"Setup start.");
            if (this.pauseController != null)
            {
                this.pauseController.didResumeEvent += OnGameResume;
            }
            if (ScoreDataBase.Instance.Init)
            {
                this.relativeScoreAndImmediateRankCounter.relativeScoreOrImmediateRankDidChangeEvent += this.RelativeScoreAndImmediateRankCounter_relativeScoreOrImmediateRankDidChangeEvent;
            }
            var beatmapLevel = CurrentData.difficultyBeatmap.level;

            this._currentBeatmapDifficulty = CurrentData.difficultyBeatmap.difficulty;
            var levelID = beatmapLevel.levelID;

            this._currentCustomBeatmapLevel = Loader.GetLevelByHash(levelID.Split('_').Last());
            this.songRawPP = ScoreDataBase.Instance.Init ? PPCounterUtil.GetPP(_currentCustomBeatmapLevel, _currentBeatmapDifficulty) : 0;
            if (_currentCustomBeatmapLevel != null)
            {
                HMMainThreadDispatcher.instance.Enqueue(this.SetCustomLabel(_currentCustomBeatmapLevel, _currentBeatmapDifficulty));
            }
            this._currentStarSong     = SongDataCoreUtil.GetBeatStarSong(_currentCustomBeatmapLevel);
            this._currentStarSongDiff = SongDataCoreUtil.GetBeatStarSongDiffculityStats(_currentCustomBeatmapLevel, _currentBeatmapDifficulty);

            if (this.statusManager.StatusJSON["beatmap"] == null)
            {
                this.statusManager.StatusJSON["beatmap"] = new JSONObject();
            }
            var beatmapJson = this.statusManager.StatusJSON["beatmap"].AsObject;

            if (this._currentStarSong != null && this._currentStarSongDiff != null)
            {
                var multiplier = this.statusManager.GameStatus.songSpeedMultiplier;
                if (ScoreDataBase.Instance.Init)
                {
                    if (multiplier == 1 || !PPCounterUtil.AllowedPositiveModifiers(levelID))
                    {
                        beatmapJson["pp"] = new JSONNumber(this.songRawPP * 1.12);
                    }
                    else
                    {
                        beatmapJson["pp"] = new JSONNumber(PPCounterUtil.CalculatePP(this.songRawPP, multiplier));
                    }
                }
                beatmapJson["star"]          = new JSONNumber(this._currentStarSongDiff.star);
                beatmapJson["downloadCount"] = new JSONNumber(this._currentStarSong.downloadCount);
                beatmapJson["upVotes"]       = new JSONNumber(this._currentStarSong.upVotes);
                beatmapJson["downVotes"]     = new JSONNumber(this._currentStarSong.downVotes);
                beatmapJson["rating"]        = new JSONNumber(this._currentStarSong.rating);
            }
            HMMainThreadDispatcher.instance.Enqueue(this.SongStartWait(this._currentStarSong != null && this._currentStarSongDiff != null));
        }
Пример #23
0
        internal static BeatSaver_CustomBeatmapLevel FromBeatSaver(Beatmap p_BeatMap)
        {
            List <PreviewDifficultyBeatmapSet> l_PreviewDifficultyBeatmapSet = new List <PreviewDifficultyBeatmapSet>();

            foreach (var l_Current in p_BeatMap.Metadata.Characteristics)
            {
                if (l_Current.Difficulties.Count == 0)
                {
                    continue;
                }

                var l_Difficulties = new List <BeatmapDifficulty>();
                foreach (var l_CurrentDiff in l_Current.Difficulties.Where(x => x.Value.HasValue).ToList())
                {
                    if (!l_CurrentDiff.Value.HasValue)
                    {
                        continue;
                    }

                    l_Difficulties.Add(Utils.Songs.SerializedToDifficulty(l_CurrentDiff.Key));
                }

                l_PreviewDifficultyBeatmapSet.Add(new PreviewDifficultyBeatmapSet(
                                                      SongCore.Loader.beatmapCharacteristicCollection.GetBeatmapCharacteristicBySerializedName(l_Current.Name),
                                                      l_Difficulties.ToArray()
                                                      ));
            }

            var l_CustomPreviewBeatmapLevel = new CustomPreviewBeatmapLevel(
                null,
                null,
                "",
                null,
                null,
                "custom_level_" + p_BeatMap.Hash.ToUpper(),
                p_BeatMap.Metadata.SongName,
                p_BeatMap.Metadata.SongSubName,
                p_BeatMap.Metadata.SongAuthorName,
                p_BeatMap.Metadata.LevelAuthorName,
                p_BeatMap.Metadata.BPM,
                0f,    ///< todo
                0f,    ///< todo
                0f,    ///< todo
                0f,    ///< todo
                p_BeatMap.Metadata.Duration,
                null,
                null,
                l_PreviewDifficultyBeatmapSet.ToArray()
                );

            return(new BeatSaver_CustomBeatmapLevel(p_BeatMap, l_CustomPreviewBeatmapLevel, null));
        }
        static void Postfix(CustomPreviewBeatmapLevel __instance)
        {
#if DEBUG
            Logger.log.Notice($"Selected CustomLevel Path :\n {__instance.customLevelPath}");
#endif
            if (File.Exists(Path.Combine(__instance.customLevelPath, "SongScript.json")))
            {
                customLevelPath = Path.Combine(__instance.customLevelPath, "SongScript.json");
            }
            else
            {
                customLevelPath = string.Empty;
            }
        }
 static bool Prefix(MissionNodeVisualController missionNodeVisualController, MissionSelectionMapViewController __instance, SongPreviewPlayer ____songPreviewPlayer)
 {
     if (missionNodeVisualController.missionNode.missionData is CustomMissionDataSO)
     {
         __instance.SetPrivateField("_selectedMissionNode", missionNodeVisualController.missionNode);
         CustomPreviewBeatmapLevel level = (missionNodeVisualController.missionNode.missionData as CustomMissionDataSO).customLevel;
         if (level != null)
         {
             ____songPreviewPlayer.CrossfadeTo(level.GetPreviewAudioClipAsync(CancellationToken.None).Result, level.previewStartTime, level.previewDuration);
         }
         __instance.GetPrivateField <Action <MissionSelectionMapViewController, MissionNode> >("didSelectMissionLevelEvent")(__instance, missionNodeVisualController.missionNode);
         return(false);
     }
     return(true);
 }
Пример #26
0
        public static void AddLevelToPlaylist(Playlist playlist, CustomPreviewBeatmapLevel level)
        {
            string hash = SongCore.Utilities.Hashing.GetCustomLevelHash(level);

            if (playlist.songs.Any(x => string.Equals(x.hash, hash, StringComparison.OrdinalIgnoreCase)))
            {
                return;
            }
            PlaylistSong song = new PlaylistSong();

            song.hash     = hash;
            song.level    = level;
            song.levelId  = level.levelID;
            song.songName = level.songName + " - " + level.levelAuthorName;
            playlist.songs.Add(song);
            playlist.SavePlaylist();
        }
Пример #27
0
        private void AddIfExists(List <string> whiteListedFiles, CustomPreviewBeatmapLevel level, string file, Func <CustomPreviewBeatmapLevel, string, List <string> > callbackOnFound = null)
        {
            // this check is necessary for performance on comparing file lists
            var path = Path.Combine(level.customLevelPath, file);

            if (!File.Exists(path))
            {
                return;
            }

            //Log.Debug($"found {file}");
            whiteListedFiles.Add(file);

            if (callbackOnFound != null)
            {
                whiteListedFiles.AddRange(callbackOnFound.Invoke(level, path));
            }
        }
Пример #28
0
            ////////////////////////////////////////////////////////////////////////////
            ////////////////////////////////////////////////////////////////////////////

            /// <summary>
            /// Init the entry
            /// </summary>
            public void Init()
            {
                if (m_WasInit)
                {
                    return;
                }

                if (CustomLevel == null && BeatSaver_Map != null && !BeatSaver_Map.Partial)
                {
                    var l_LocalLevel = SongCore.Loader.GetLevelByHash(BeatSaver_Map.Hash.ToUpper());
                    if (l_LocalLevel != null && SongCore.Loader.CustomLevels.ContainsKey(l_LocalLevel.customLevelPath))
                    {
                        CustomLevel = l_LocalLevel;
                    }
                }

                m_WasInit = true;
            }
Пример #29
0
 internal static void PlayLevel(CustomPreviewBeatmapLevel beatmap, BeatmapDifficulty difficulty)
 {
     try
     {
         LoadBeatmapLevelAsync(beatmap, (success, beatmapLevel) =>
         {
             Logger.log.Log(IPALogger.Level.Info, "Loading Beatmap level Success:" + success);
             if (success)
             {
                 StartLevel(beatmapLevel, beatmap, difficulty);
             }
         });
     }
     catch (Exception ex)
     {
         Logger.log.Log(IPALogger.Level.Critical, ex);
     }
 }
        /// <summary>
        /// Try to get the date from the cover file, likely the most reliable.
        /// Fall back on the folders creation date.
        /// </summary>
        /// <param name="level"></param>
        /// <returns></returns>
        private double GetSongUserDate(CustomPreviewBeatmapLevel level)
        {
            var coverPath = Path.Combine(level.customLevelPath, level.standardLevelInfoSaveData.coverImageFilename);
            var lastTime  = EPOCH;

            if (File.Exists(coverPath))
            {
                var lastWriteTime  = File.GetLastWriteTimeUtc(coverPath);
                var lastCreateTime = File.GetCreationTimeUtc(coverPath);
                lastTime = lastWriteTime > lastCreateTime ? lastWriteTime : lastCreateTime;
            }
            else
            {
                var lastCreateTime = File.GetCreationTimeUtc(level.customLevelPath);
                lastTime = lastCreateTime;
            }

            return((lastTime - EPOCH).TotalMilliseconds);
        }