private void SetupUI()
        {
            if (initialized)
            {
                return;
            }
            _beatmapCharacteristics = Resources.FindObjectsOfTypeAll <BeatmapCharacteristicSO>();
            _lastCharacteristic     = _beatmapCharacteristics.First(x => x.characteristicName == "Standard");

            Resources.FindObjectsOfTypeAll <BeatmapCharacteristicSelectionViewController>().First().didSelectBeatmapCharacteristicEvent += (BeatmapCharacteristicSelectionViewController sender, BeatmapCharacteristicSO selected) => { _lastCharacteristic = selected; };
            if (SongLoader.AreSongsLoaded)
            {
                _levelCollection = SongLoader.CustomLevelCollectionSO;
            }
            else
            {
                SongLoader.SongsLoadedEvent += (SongLoader sender, List <CustomLevel> levels) =>
                {
                    _levelCollection = SongLoader.CustomLevelCollectionSO;
                };
            }

            _levelListViewController = Resources.FindObjectsOfTypeAll <LevelListViewController>().FirstOrDefault();

            RectTransform _tableViewRectTransform = _levelListViewController.GetComponentsInChildren <RectTransform>().First(x => x.name == "TableViewContainer");

            _tableViewRectTransform.sizeDelta = new Vector2(0f, -35f);
            //_tableViewRectTransform.anchoredPosition = new Vector2(0f, -2.5f);

            RectTransform _pageUp = _tableViewRectTransform.GetComponentsInChildren <RectTransform>(true).First(x => x.name == "PageUpButton");

            _pageUp.anchoredPosition = new Vector2(0f, -1f);

            RectTransform _pageDown = _tableViewRectTransform.GetComponentsInChildren <RectTransform>(true).First(x => x.name == "PageDownButton");

            _pageDown.anchoredPosition = new Vector2(0f, 1f);

            _requestButton = _levelListViewController.CreateUIButton("CreditsButton", new Vector2(0, 30.25f), new Vector2(20f, 6f), RequestsButtonPressed, "Requests");
            _requestButton.SetButtonTextSize(3f);
            _requestButton.ToggleWordWrapping(false);

            _detailViewController = Resources.FindObjectsOfTypeAll <StandardLevelDetailViewController>().First(x => x.name == "StandardLevelDetailViewController");

            //based on https://github.com/halsafar/BeatSaberSongBrowser/blob/master/SongBrowserPlugin/UI/Browser/SongBrowserUI.cs#L192
            var statsPanel     = _detailViewController.GetComponentsInChildren <CanvasRenderer>(true).First(x => x.name == "LevelParamsPanel");
            var statTransforms = statsPanel.GetComponentsInChildren <RectTransform>();
            var valueTexts     = statsPanel.GetComponentsInChildren <TextMeshProUGUI>().Where(x => x.name == "ValueText").ToList();

            foreach (RectTransform r in statTransforms)
            {
                if (r.name == "Separator")
                {
                    continue;
                }
                r.sizeDelta = new Vector2(r.sizeDelta.x * 0.85f, r.sizeDelta.y * 0.85f);
            }

            _levelListViewController.didSelectLevelEvent += _levelListViewController_didSelectLevelEvent;
            initialized = true;
        }
        public void LeaveRoom()
        {
            try
            {
                if (joined)
                {
                    InGameOnlineController.Instance.needToSendUpdates = false;
                    Client.Instance.LeaveRoom();
                    joined = false;
                }
                if (Client.Instance.Connected)
                {
                    Client.Instance.Disconnect();
                }
            }
            catch
            {
                Logger.Info("Unable to disconnect from ServerHub properly!");
            }

            if (songToDownload != null)
            {
                songToDownload.songQueueState          = SongQueueState.Error;
                Client.Instance.playerInfo.playerState = PlayerState.Lobby;
            }

            InGameOnlineController.Instance.DestroyAvatars();
            PreviewPlayer.CrossfadeToDefault();
            lastSelectedSong    = "";
            _lastCharacteristic = _standardCharacteristic;
            _lastSortMode       = SortMode.Default;
            _lastSearchRequest  = "";
            PopAllViewControllers(_roomNavigationController);
            didFinishEvent?.Invoke();
        }
        public static CustomLevelCollectionSO ReplaceOriginal(BeatmapLevelCollectionSO original)
        {
            var newCollection = CreateInstance <CustomLevelCollectionSO>();

            newCollection.UpdateArray();

            if (beatmapCharacteristicCollection == null)
            {
                beatmapCharacteristicCollection = Resources.FindObjectsOfTypeAll <BeatmapCharacteristicCollectionSO>().FirstOrDefault().beatmapCharacteristics;
            }

            if (_standardCharacteristic == null)
            {
                _standardCharacteristic = beatmapCharacteristicCollection[0];
            }

            if (_oneSaberCharacteristic == null)
            {
                _oneSaberCharacteristic = beatmapCharacteristicCollection[1];
            }

            if (_noArrowsCharacteristic == null)
            {
                _noArrowsCharacteristic = beatmapCharacteristicCollection[2];
            }

            return(newCollection);
        }
 //      public static OverrideClasses.CustomLevel previouslySelectedSong = null;
 static void Postfix(BeatmapCharacteristicSO __instance, ref string __result)
 {
     if (__result == null)
     {
         __result = __instance.characteristicName;
     }
 }
        /// <summary>
        /// Triggered when a player selects a song using a vanilla packet.
        /// </summary>
        public async override void HandleMenuRpcManagerSelectedBeatmap(string userId, BeatmapIdentifierNetSerializable beatmapId)
        {
            OnSelectedBeatmap(userId, beatmapId);
            string?hash = Utilities.Utils.LevelIdToHash(beatmapId.levelID);

            Plugin.Log?.Debug($"'{userId}' selected song '{hash ?? beatmapId.levelID}'.");
            if (hash != null)
            {
                BeatmapCharacteristicSO characteristic = _beatmapCharacteristicCollection.GetBeatmapCharacteristicBySerializedName(beatmapId.beatmapCharacteristicSerializedName);
                if (_playersData.Values.Any(playerData => playerData.beatmapLevel?.levelID == beatmapId.levelID))
                {
                    PreviewBeatmapStub?preview = GetExistingPreview(beatmapId.levelID);
                    HMMainThreadDispatcher.instance.Enqueue(() => base.SetPlayerBeatmapLevel(userId, preview, beatmapId.difficulty, characteristic));
                }
                else
                {
                    PreviewBeatmapStub?  preview      = null;
                    IPreviewBeatmapLevel localPreview = SongCore.Loader.GetLevelById(beatmapId.levelID);
                    if (localPreview != null)
                    {
                        preview = new PreviewBeatmapStub(hash, localPreview);
                    }
                    if (preview == null)
                    {
                        preview = await FetchBeatSaverPreview(beatmapId.levelID, hash);
                    }
                    HMMainThreadDispatcher.instance.Enqueue(() => base.SetPlayerBeatmapLevel(userId, preview, beatmapId.difficulty, characteristic));
                }
            }
            else
            {
                base.HandleMenuRpcManagerSelectedBeatmap(userId, beatmapId);
            }
        }
示例#6
0
        public async void SetSong(IBeatmapLevel level, BeatmapCharacteristicSO characteristic, BeatmapDifficulty difficulty)
        {
            selectedLevel = level;
            selectedBeatmapCharacteristic = characteristic;
            selectedDifficulty            = difficulty;

            songNameText.text = selectedLevel.songName;

            _playerDataModel.playerData.SetLastSelectedBeatmapCharacteristic(selectedBeatmapCharacteristic);

            var diffBeatmaps = selectedLevel.beatmapLevelData.GetDifficultyBeatmapSet(selectedBeatmapCharacteristic).difficultyBeatmaps;

            int diffIndex = CustomExtensions.GetClosestDifficultyIndex(diffBeatmaps, selectedDifficulty);

            difficultyControlRect.gameObject.SetActive(perPlayerDifficulty);
            difficultyControl.SetTexts(diffBeatmaps.Select(x => x.difficulty.ToString().Replace("Plus", "+")).ToArray());
            difficultyControl.SelectCellWithNumber(diffIndex);

            playNowButton.SetButtonText("PLAY NOW");
            playNowButtonGlow.SetGlow("#5DADE2");

            SetProgressBarState(false, 0f);

            levelCoverImage.texture = await selectedLevel.GetCoverImageTexture2DAsync(new CancellationTokenSource().Token);
        }
示例#7
0
        protected override void DidActivate(bool firstActivation, ActivationType activationType)
        {
            _beatmapCharacteristics = Resources.FindObjectsOfTypeAll <BeatmapCharacteristicSO>();
            _standardCharacteristic = _beatmapCharacteristics.First(x => x.serializedName == "Standard");

            if (firstActivation && activationType == ActivationType.AddedToHierarchy)
            {
                _lastCharacteristic = _standardCharacteristic;

                _playerManagementViewController = BeatSaberUI.CreateViewController <PlayerManagementViewController>();
                _playerManagementViewController.gameplayModifiersChanged  += UpdateLevelOptions;
                _playerManagementViewController.transferHostButtonPressed += TransferHostConfirmation;

                _simpleDialog = ReflectionUtil.GetPrivateField <SimpleDialogPromptViewController>(FindObjectOfType <MainFlowCoordinator>(), "_simpleDialogPromptViewController");
                _simpleDialog = Instantiate(_simpleDialog.gameObject, _simpleDialog.transform.parent).GetComponent <SimpleDialogPromptViewController>();

                _quickSettingsViewController = BeatSaberUI.CreateViewController <QuickSettingsViewController>();

                _roomNavigationController = BeatSaberUI.CreateViewController <RoomNavigationController>();
                _roomNavigationController.didFinishEvent += () => { LeaveRoom(); };

                _searchKeyboard = BeatSaberUI.CreateViewController <CustomKeyboardViewController>();
                _searchKeyboard.enterButtonPressed += SearchPressed;
                _searchKeyboard.backButtonPressed  += () => { DismissViewController(_searchKeyboard); };
                _searchKeyboard.allowEmptyInput     = true;
            }

            ProvideInitialViewControllers(_roomNavigationController, _playerManagementViewController, _quickSettingsViewController);
        }
        private void PlayNow_Pressed()
        {
            SongInfo       info  = roomInfo.selectedSong;
            BeatmapLevelSO level = SongLoader.CustomBeatmapLevelPackCollectionSO.beatmapLevelPacks.SelectMany(x => x.beatmapLevelCollection.beatmapLevels).FirstOrDefault(x => x.levelID.StartsWith(info.levelId)) as BeatmapLevelSO;

            if (level == null)
            {
                SongDownloader.Instance.RequestSongByLevelID(info.levelId,
                                                             (song) =>
                {
                    SongDownloader.Instance.DownloadSong(song, "MultiplayerSongs",
                                                         () =>
                    {
                        SongLoader.SongsLoadedEvent += PlayNow_SongsLoaded;
                    },
                                                         (progress) =>
                    {
                        _leaderboardViewController.SetProgressBarState((progress > 0f), progress);
                    });
                });
            }
            else
            {
                SongLoader.Instance.LoadAudioClipForLevel((CustomLevel)level,
                                                          (levelLoaded) =>
                {
                    _leaderboardViewController.SetProgressBarState(false, 0f);
                    BeatmapCharacteristicSO characteristic = Resources.FindObjectsOfTypeAll <BeatmapCharacteristicSO>().FirstOrDefault(x => x.serializedName == roomInfo.startLevelInfo.characteristicName);
                    StartLevel(levelLoaded, characteristic, roomInfo.startLevelInfo.difficulty, roomInfo.startLevelInfo.modifiers, currentTime);
                });
            }
        }
示例#9
0
        protected override void Client_PlaySong(IPreviewBeatmapLevel desiredLevel, BeatmapCharacteristicSO desiredCharacteristic, BeatmapDifficulty desiredDifficulty, GameplayModifiers gameplayModifiers, PlayerSpecificSettings playerSpecificSettings, OverrideEnvironmentSettings overrideEnvironmentSettings, ColorScheme colorScheme, bool useFloatingScoreboard = false, bool useSync = false, bool disablePause = false, bool disableFail = false)
        {
            base.Client_PlaySong(desiredLevel, desiredCharacteristic, desiredDifficulty, gameplayModifiers, playerSpecificSettings, overrideEnvironmentSettings, colorScheme, useFloatingScoreboard, useSync, disablePause, disableFail);

            //Set up per-play settings
            Plugin.UseSync = useSync;
            Plugin.UseFloatingScoreboard = useFloatingScoreboard;
            Plugin.DisablePause          = disablePause;
            Plugin.DisableFail           = disableFail;

            //Reset score
            (Plugin.client.Self as Player).Score    = 0;
            (Plugin.client.Self as Player).Accuracy = 0;
            var playerUpdate = new Event();

            playerUpdate.Type          = Event.EventType.PlayerUpdated;
            playerUpdate.ChangedObject = Plugin.client.Self;
            Plugin.client.Send(new Packet(playerUpdate));

            UnityMainThreadDispatcher.Instance().Enqueue(() =>
            {
                //If the player is still on the results screen, go ahead and boot them out
                if (_resultsViewController.isInViewControllerHierarchy)
                {
                    resultsViewController_continueButtonPressedEvent(null);
                }

                SongUtils.PlaySong(desiredLevel, desiredCharacteristic, desiredDifficulty, overrideEnvironmentSettings, colorScheme, gameplayModifiers, playerSpecificSettings, SongFinished);
            });
        }
        public static CustomLevelCollectionSO ReplaceOriginal(LevelCollectionSO original)
        {
            var newCollection = CreateInstance <CustomLevelCollectionSO>();

            newCollection._levelList.AddRange(original.levels);
            newCollection.UpdateArray();

            newCollection.ReplaceReferences();

            foreach (var originalLevel in original.levels)
            {
                if (_standardCharacteristic == null)
                {
                    _standardCharacteristic = originalLevel.beatmapCharacteristics.FirstOrDefault(x => x.characteristicName == "Standard");
                }

                if (_oneSaberCharacteristic == null)
                {
                    _oneSaberCharacteristic = originalLevel.beatmapCharacteristics.FirstOrDefault(x => x.characteristicName == "One Saber");
                }

                if (_noArrowsCharacteristic == null)
                {
                    _noArrowsCharacteristic = originalLevel.beatmapCharacteristics.FirstOrDefault(x => x.characteristicName == "No Arrows");
                }
            }

            return(newCollection);
        }
示例#11
0
        public override void HandleMenuRpcManagerSelectedBeatmap(string userId, BeatmapIdentifierNetSerializable beatmapId)
        {
            if (beatmapId != null)
            {
                string?hash = Utilities.Utils.LevelIdToHash(beatmapId.levelID);
                if (hash != null)
                {
                    Plugin.Log?.Debug($"'{userId}' selected song '{hash}'.");
                    BeatmapCharacteristicSO characteristic = _beatmapCharacteristicCollection.GetBeatmapCharacteristicBySerializedName(beatmapId.beatmapCharacteristicSerializedName);
                    PreviewBeatmapManager.GetPopulatedPreview(beatmapId.levelID).ContinueWith(r =>
                    {
                        PreviewBeatmapStub preview = r.Result;

                        Plugin.Log?.Info($"user: {userId} | hostuser: {base.hostUserId}");
                        Plugin.Log?.Info($"local: {preview.isDownloaded} | cloud: {preview.isDownloadable}");

                        if (userId == base.hostUserId)
                        {
                            _sessionManager.SetLocalPlayerState("bmlocal", preview.isDownloaded);
                            _sessionManager.SetLocalPlayerState("bmcloud", preview.isDownloadable);
                        }

                        HMMainThreadDispatcher.instance.Enqueue(() =>
                        {
                            base.SetPlayerBeatmapLevel(userId, preview, beatmapId.difficulty, characteristic);
                        });
                    });

                    return;
                }
            }

            base.HandleMenuRpcManagerSelectedBeatmap(userId, beatmapId);
        }
示例#12
0
        static bool Prefix(string levelId, BeatmapDifficulty beatmapDifficulty, BeatmapCharacteristicSO characteristic, LobbyPlayersDataModel __instance)
        {
            if (Utilities.Utilities.LevelIdToHash(levelId) != null)
            {
                Plugin.Log?.Debug($"Local user selected song '{levelId}'.");
                if (SongCore.Loader.GetLevelById(levelId) != null)
                {
                    Plugin.Log?.Debug($"Custom song '{levelId}' loaded.");
                    return(true);
                }

                Plugin.Log?.Debug("Updating RPC");
                var menuRpcManager = __instance.GetField <IMenuRpcManager, LobbyPlayersDataModel>("_menuRpcManager");
                menuRpcManager.SelectBeatmap(new BeatmapIdentifierNetSerializable(levelId, characteristic.serializedName, beatmapDifficulty));

                Plugin.Log?.Debug("Setting song preview");
                var beatmap = BeatSaver.Client.Hash(Utilities.Utilities.LevelIdToHash(levelId));
                beatmap.ContinueWith(r =>
                {
                    HMMainThreadDispatcher.instance.Enqueue(() =>
                    {
                        __instance.SetPlayerBeatmapLevel(__instance.localUserId, new PreviewBeatmapLevelStub(levelId, r.Result), beatmapDifficulty, characteristic);
                    });
                });

                return(false);
            }
            return(true);
        }
示例#13
0
        public static async void LoadBeatmapLevelAsync(
            BeatmapCharacteristicSO characteristic, IPreviewBeatmapLevel selectedLevel, BeatmapDifficulty difficulty,
            Action <AdditionalContentModel.EntitlementStatus, bool, IBeatmapLevel> callback)
        {
            _beatmapLevelsModel     = Resources.FindObjectsOfTypeAll <BeatmapLevelsModel>().FirstOrDefault();
            _contentModelSO         = Resources.FindObjectsOfTypeAll <AdditionalContentModel>().FirstOrDefault();
            _beatmapCharacteristics = Resources.FindObjectsOfTypeAll <BeatmapCharacteristicSO>();

            var token = new CancellationTokenSource();

            Plugin.log.Info("Checking entitlement");

            var entitlementStatus =
                await _contentModelSO.GetLevelEntitlementStatusAsync(selectedLevel.levelID, token.Token);

            if (entitlementStatus == AdditionalContentModel.EntitlementStatus.Owned)
            {
                Plugin.log.Info("Level owned. Loading...");

                var getBeatmapLevelResult =
                    await _beatmapLevelsModel.GetBeatmapLevelAsync(selectedLevel.levelID, token.Token);

                callback?.Invoke(entitlementStatus, !getBeatmapLevelResult.isError, getBeatmapLevelResult.beatmapLevel);

                Plugin.log.Info("Starting...");
                StartLevel(getBeatmapLevelResult.beatmapLevel, characteristic, difficulty,
                           GameplayModifiers.defaultModifiers);
            }
            else
            {
                callback?.Invoke(entitlementStatus, false, null);
            }
        }
示例#14
0
        public static BeatmapCharacteristicSO GetCustomGameMode(string serializedName, Sprite icon, string name, string description, bool requires360Movement = true, bool containsRotationEvents = true, int numberOfColors = 2)
        {
            if (customGamesModes.TryGetValue(serializedName, out BeatmapCharacteristicSO bcso))
            {
                return(bcso);
            }

            if (icon == null)
            {
                Texture2D tex = new Texture2D(50, 50);
                icon = Sprite.Create(tex, new Rect(0f, 0f, tex.width, tex.height), new Vector2(0.5f, 0.5f));
            }

            BeatmapCharacteristicSO customGameMode = BeatmapCharacteristicSO.CreateInstance <BeatmapCharacteristicSO>();

            FieldHelper.Set(customGameMode, "_icon", icon);
            FieldHelper.Set(customGameMode, "_characteristicNameLocalizationKey", name);
            FieldHelper.Set(customGameMode, "_descriptionLocalizationKey", description);
            FieldHelper.Set(customGameMode, "_serializedName", serializedName);
            FieldHelper.Set(customGameMode, "_compoundIdPartName", serializedName); // What is _compoundIdPartName?
            FieldHelper.Set(customGameMode, "_sortingOrder", 100);
            FieldHelper.Set(customGameMode, "_containsRotationEvents", containsRotationEvents);
            FieldHelper.Set(customGameMode, "_requires360Movement", requires360Movement);
            FieldHelper.Set(customGameMode, "_numberOfColors", numberOfColors);
            return(customGameMode);
        }
示例#15
0
        // Yoinked from TournamentAssistant
        public static async void PlaySong(IPreviewBeatmapLevel level, BeatmapCharacteristicSO characteristic, BeatmapDifficulty difficulty, OverrideEnvironmentSettings overrideEnvironmentSettings = null, ColorScheme colorScheme = null, GameplayModifiers gameplayModifiers = null, PlayerSpecificSettings playerSettings = null, Action <StandardLevelScenesTransitionSetupDataSO, LevelCompletionResults> songFinishedCallback = null)
        {
            Action <IBeatmapLevel> SongLoaded = (loadedLevel) =>
            {
                MenuTransitionsHelper _menuSceneSetupData = Resources.FindObjectsOfTypeAll <MenuTransitionsHelper>().First();
                _menuSceneSetupData.StartStandardLevel(
                    loadedLevel.beatmapLevelData.GetDifficultyBeatmap(characteristic, difficulty),
                    overrideEnvironmentSettings,
                    colorScheme,
                    gameplayModifiers ?? new GameplayModifiers(),
                    playerSettings ?? new PlayerSpecificSettings(),
                    null,
                    "Menu",
                    false,
                    null,
                    (standardLevelScenesTransitionSetupData, results) => songFinishedCallback?.Invoke(standardLevelScenesTransitionSetupData, results)
                    );
            };
            BeatmapLevelsModel beatmapLevelsModel = Resources.FindObjectsOfTypeAll <BeatmapLevelsModel>().FirstOrDefault();
            var result = await GetLevelFromPreview(level);

            if (result != null && !(result?.isError == true))
            {
                //HTTPstatus requires cover texture to be applied in here, and due to a fluke
                //of beat saber, it's not applied when the level is loaded, but it *is*
                //applied to the previewlevel it's loaded from
                var loadedLevel = result?.beatmapLevel;
                loadedLevel.SetField("_coverImageTexture2D", level.GetField <Texture2D>("_coverImageTexture2D"));
                SongLoaded(loadedLevel);
            }
        }
        protected override void DidActivate(bool firstActivation, ActivationType activationType)
        {
            _beatmapCharacteristics = Resources.FindObjectsOfTypeAll <BeatmapCharacteristicSO>();
            _standardCharacteristic = _beatmapCharacteristics.First(x => x.characteristicName == "Standard");

            if (firstActivation && activationType == ActivationType.AddedToHierarchy)
            {
                _lastCharacteristic = _standardCharacteristic;

                _playerManagementViewController = BeatSaberUI.CreateViewController <PlayerManagementViewController>();
                _playerManagementViewController.gameplayModifiersChanged += UpdateLevelOptions;

                _quickSettingsViewController = BeatSaberUI.CreateViewController <QuickSettingsViewController>();

                _roomNavigationController = BeatSaberUI.CreateViewController <RoomNavigationController>();
                _roomNavigationController.didFinishEvent += () => { LeaveRoom(); };

                _searchKeyboard = BeatSaberUI.CreateViewController <CustomKeyboardViewController>();
                _searchKeyboard.enterButtonPressed += SearchPressed;
                _searchKeyboard.backButtonPressed  += () => { DismissViewController(_searchKeyboard); };
                _searchKeyboard.allowEmptyInput     = true;
            }

            ProvideInitialViewControllers(_roomNavigationController, _playerManagementViewController, _quickSettingsViewController);
        }
示例#17
0
        public void SetLevels(BeatmapCharacteristicSO characteristic, SortMode sortMode, string searchRequest)
        {
            LevelSO[] levels = null;
            if (lastPlaylist != null)
            {
                levels = lastPlaylist.songs.Where(x => x.level != null && x.level.beatmapCharacteristics.Contains(characteristic)).Select(x => x.level).ToArray();
            }
            else
            {
                levels = _levelCollection.GetLevelsWithBeatmapCharacteristic(characteristic);
            }

            if (string.IsNullOrEmpty(searchRequest))
            {
                switch (sortMode)
                {
                case SortMode.Newest: { levels = SortLevelsByCreationTime(levels); }; break;

                case SortMode.Difficulty: {
                    levels = levels.AsParallel().OrderBy(x => { int index = ScrappedData.Songs.FindIndex(y => x.levelID.StartsWith(y.Hash)); return(index == -1 ? (x.levelID.Length < 32 ? int.MaxValue : int.MaxValue - 1) : index); }).ToArray();
                }; break;
                }
            }
            else
            {
                levels = levels.Where(x => ($"{x.songName} {x.songSubName} {x.levelAuthorName} {x.songAuthorName}".ToLower().Contains(searchRequest))).ToArray();
            }

            _levelListViewController.SetLevels(levels);
            PopDifficultyAndDetails();
        }
示例#18
0
        public void SongFinished(StandardLevelScenesTransitionSetupDataSO sender, LevelCompletionResults levelCompletionResults, IDifficultyBeatmap difficultyBeatmap, GameplayModifiers gameplayModifiers, bool practice)
        {
            if (Client.Instance.InRadioMode)
            {
                PluginUI.instance.radioFlowCoordinator.lastDifficulty = difficultyBeatmap;
                PluginUI.instance.radioFlowCoordinator.lastResults    = levelCompletionResults;
            }

            if (Config.Instance.SpectatorMode || Client.disableScoreSubmission || ScoreSubmission.Disabled || ScoreSubmission.ProlongedDisabled)
            {
                List <string> reasons = new List <string>();

                if (Config.Instance.SpectatorMode)
                {
                    reasons.Add("Spectator mode");
                }
                if (Client.disableScoreSubmission)
                {
                    reasons.Add("Multiplayer score submission disabled by another mod");
                }
                if (ScoreSubmission.Disabled)
                {
                    reasons.Add("Score submission is disabled by " + ScoreSubmission.ModString);
                }
                if (ScoreSubmission.ProlongedDisabled)
                {
                    reasons.Add("Score submission is disabled for a prolonged time by " + ScoreSubmission.ProlongedModString);
                }

                Misc.Logger.Warning("\nScore submission is disabled! Reason:\n" + string.Join(",\n", reasons));
                return;
            }

            PlayerDataModelSO _playerDataModel = Resources.FindObjectsOfTypeAll <PlayerDataModelSO>().First();

            _playerDataModel.currentLocalPlayer.playerAllOverallStatsData.soloFreePlayOverallStatsData.UpdateWithLevelCompletionResults(levelCompletionResults);
            _playerDataModel.Save();
            if (levelCompletionResults.levelEndStateType != LevelCompletionResults.LevelEndStateType.Failed && levelCompletionResults.levelEndStateType != LevelCompletionResults.LevelEndStateType.Cleared)
            {
                return;
            }

            PlayerDataModelSO.LocalPlayer currentLocalPlayer = _playerDataModel.currentLocalPlayer;
            bool                    cleared               = levelCompletionResults.levelEndStateType == LevelCompletionResults.LevelEndStateType.Cleared;
            string                  levelID               = difficultyBeatmap.level.levelID;
            BeatmapDifficulty       difficulty            = difficultyBeatmap.difficulty;
            BeatmapCharacteristicSO beatmapCharacteristic = difficultyBeatmap.parentDifficultyBeatmapSet.beatmapCharacteristic;
            PlayerLevelStatsData    playerLevelStatsData  = currentLocalPlayer.GetPlayerLevelStatsData(levelID, difficulty, beatmapCharacteristic);
            bool                    newHighScore          = playerLevelStatsData.highScore < levelCompletionResults.score;

            playerLevelStatsData.IncreaseNumberOfGameplays();
            if (cleared)
            {
                Misc.Logger.Info("Submitting score...");
                playerLevelStatsData.UpdateScoreData(levelCompletionResults.score, levelCompletionResults.maxCombo, levelCompletionResults.fullCombo, levelCompletionResults.rank);
                Resources.FindObjectsOfTypeAll <PlatformLeaderboardsModel>().First().AddScore(difficultyBeatmap, levelCompletionResults.unmodifiedScore, gameplayModifiers);
                Misc.Logger.Info("Score submitted!");
            }
        }
示例#19
0
        public void StartLevel(BeatmapLevelSO level, BeatmapCharacteristicSO characteristic, BeatmapDifficulty difficulty, GameplayModifiers modifiers, float startTime = 0f)
        {
            Client.Instance.playerInfo.playerComboBlocks = 0;
            Client.Instance.playerInfo.playerCutBlocks   = 0;
            Client.Instance.playerInfo.playerTotalBlocks = 0;
            Client.Instance.playerInfo.playerEnergy      = 0f;
            Client.Instance.playerInfo.playerScore       = 0;

            MenuTransitionsHelperSO menuSceneSetupData = Resources.FindObjectsOfTypeAll <MenuTransitionsHelperSO>().FirstOrDefault();

            if (_playerManagementViewController != null)
            {
                _playerManagementViewController.SetGameplayModifiers(modifiers);
            }

            if (menuSceneSetupData != null)
            {
                if (Config.Instance.SpectatorMode)
                {
                    Client.Instance.playerInfo.playerState = PlayerState.Spectating;
                    modifiers.noFail = true;
                }
                else
                {
                    Client.Instance.playerInfo.playerState = PlayerState.Game;
                }

                PlayerSpecificSettings playerSettings = Resources.FindObjectsOfTypeAll <PlayerDataModelSO>().FirstOrDefault().currentLocalPlayer.playerSpecificSettings;

                roomInfo.roomState = RoomState.InGame;

                IDifficultyBeatmap difficultyBeatmap = level.GetDifficultyBeatmap(characteristic, difficulty, true);

#if DEBUG
                Logger.Info($"Starting song: name={level.songName}, levelId={level.levelID}, difficulty={difficulty}");
#endif

                Client.Instance.MessageReceived -= PacketReceived;

                try
                {
                    BS_Utils.Gameplay.Gamemode.NextLevelIsIsolated("Beat Saber Multiplayer");
                }
                catch
                {
                }

                PracticeSettings practiceSettings = new PracticeSettings(PracticeSettings.defaultPracticeSettings);
                practiceSettings.startSongTime = startTime + 1.5f;
                practiceSettings.songSpeedMul  = modifiers.songSpeedMul;

                menuSceneSetupData.StartStandardLevel(difficultyBeatmap, modifiers, playerSettings, (startTime > 1f ? practiceSettings : null), false, () => {}, (StandardLevelScenesTransitionSetupDataSO sender, LevelCompletionResults levelCompletionResults) => { InGameOnlineController.Instance.SongFinished(sender, levelCompletionResults, difficultyBeatmap, modifiers, false); });
                return;
            }
            else
            {
                Logger.Error("SceneSetupData is null!");
            }
        }
示例#20
0
        private static void StartLevel(IBeatmapLevel level, BeatmapCharacteristicSO characteristic,
                                       BeatmapDifficulty difficulty, GameplayModifiers modifiers, float startTime = 0f)
        {
            var menuSceneSetupData = Resources.FindObjectsOfTypeAll <MenuTransitionsHelper>().FirstOrDefault();


            if (menuSceneSetupData != null)
            {
                var playerData = Resources.FindObjectsOfTypeAll <PlayerDataModel>().FirstOrDefault().playerData;

                var playerSettings = playerData.playerSpecificSettings;
                var environmentOverrideSettings = playerData.overrideEnvironmentSettings;

                var colorSchemesSettings = playerData.colorSchemesSettings.overrideDefaultColors
                    ? playerData.colorSchemesSettings.GetColorSchemeForId(playerData.colorSchemesSettings
                                                                          .selectedColorSchemeId)
                    : null;


                var difficultyBeatmap = level.GetDifficultyBeatmap(characteristic, difficulty, false);

                try
                {
                    BS_Utils.Gameplay.Gamemode.NextLevelIsIsolated("TestMod");
                }
                catch
                {
                }

                PracticeSettings practiceSettings = null;
                if (startTime > 1f)
                {
                    practiceSettings = new PracticeSettings(PracticeSettings.defaultPracticeSettings);
                    if (startTime > 1f)
                    {
                        practiceSettings.startSongTime = startTime + 1.5f;
                        practiceSettings.startInAdvanceAndClearNotes = true;
                    }

                    practiceSettings.songSpeedMul = modifiers.songSpeedMul;
                }

                menuSceneSetupData.StartStandardLevel(
                    difficultyBeatmap,
                    environmentOverrideSettings,
                    colorSchemesSettings,
                    modifiers,
                    playerSettings,
                    practiceSettings,
                    "Menu",
                    false,
                    () => { },
                    (manager, result) => { });
            }
            else
            {
                Plugin.log.Error("SceneSetupData is null!");
            }
        }
示例#21
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);
        }
示例#22
0
        private static void StartLevel(IBeatmapLevel beatmapLevel, SongInfo songInfo)
        {
            MenuTransitionsHelper menuSceneSetupData = Resources.FindObjectsOfTypeAll <MenuTransitionsHelper>().FirstOrDefault();
            PlayerData            playerSettings     = Resources.FindObjectsOfTypeAll <PlayerDataModel>().First().playerData;

            playerSettings.playerSpecificSettings.leftHanded = songInfo.leftHanded;
            playerSettings.practiceSettings.songSpeedMul     = 1.0f;
            songInfo.modifiers.noFail = true;
            IBeatmapLevel level = beatmapLevel;

            PreviewDifficultyBeatmapSet[] sets            = songInfo.beatmap.previewDifficultyBeatmapSets;
            BeatmapCharacteristicSO       characteristics = null;

            foreach (PreviewDifficultyBeatmapSet set in sets)
            {
                if (("Mode" + set.beatmapCharacteristic.compoundIdPartName) == Convert.ToString(songInfo.mode))
                {
                    characteristics = set.beatmapCharacteristic;
                }
            }
            //BeatmapCharacteristicSO characteristics = songInfo.beatmap.previewDifficultyBeatmapSets[0].beatmapCharacteristic;
            IDifficultyBeatmap levelDifficulty = BeatmapLevelDataExtensions.GetDifficultyBeatmap(level.beatmapLevelData, characteristics, songInfo.difficulty);

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

                var mainFlowCoordinator = Resources.FindObjectsOfTypeAll <MainFlowCoordinator>().First();

                if (results.levelEndAction == LevelCompletionResults.LevelEndAction.Restart)
                {
                    return;
                }

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

                case LevelCompletionResults.LevelEndStateType.Cleared:
                    Logger.log.Info("Showing menu");
                    break;

                case LevelCompletionResults.LevelEndStateType.Failed:
                    Logger.log.Info("Showing menu");
                    break;

                default:
                    break;
                }
            });
        }
        public void AddCustomLevel(CustomLevel customLevel)
        {
            var characteristics = new List <BeatmapCharacteristicSO>();

            foreach (CustomSongInfo.DifficultyLevel diffLevel in customLevel.customSongInfo.difficultyLevels)
            {
                switch (diffLevel.characteristic)
                {
                case "":
                    if (!characteristics.Contains(_standardCharacteristic))
                    {
                        characteristics.Add(_standardCharacteristic);
                    }
                    break;

                case "Standard":
                    if (!characteristics.Contains(_standardCharacteristic))
                    {
                        characteristics.Add(_standardCharacteristic);
                    }
                    break;

                case "One Saber":
                    if (!characteristics.Contains(_oneSaberCharacteristic))
                    {
                        characteristics.Add(_oneSaberCharacteristic);
                    }
                    break;

                case "No Arrows":
                    if (!characteristics.Contains(_noArrowsCharacteristic))
                    {
                        characteristics.Add(_noArrowsCharacteristic);
                    }
                    break;

                default:
                    BeatmapCharacteristicSO characteristic = SongLoader.customCharacteristics.FirstOrDefault(x => x.characteristicName == diffLevel.characteristic);
                    if (characteristic != null)
                    {
                        characteristics.Add(characteristic);
                    }
                    else
                    if (!characteristics.Contains(SongLoader.customCharacteristics.First(x => x.characteristicName == "Missing Characteristic")))
                    {
                        characteristics.Add(SongLoader.customCharacteristics.First(x => x.characteristicName == "Missing Characteristic"));
                    }
                    break;
                }
            }
            customLevel.SetBeatmapCharacteristics(characteristics.ToArray());
            //     customLevel.SetDifficultyBeatmaps(_beatmapLevels, characteristics[0]);
            _levelList.Add(customLevel);

            UpdateArray();
        }
        public void SetBeatmapCharacteristic(BeatmapCharacteristicSO characteristic)
        {
            if (_selectedSong.beatmapCharacteristics.Contains(characteristic))
            {
                int charIndex = Array.IndexOf(_selectedSong.beatmapCharacteristics, characteristic);

                _characteristicControl.SelectCellWithNumber(charIndex);
                _characteristicControl_didSelectCellEvent(charIndex);
            }
        }
示例#25
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;
                }
            });
        }
        public void HandlePreviewBeatmapPacket(PreviewBeatmapPacket packet, IConnectedPlayer player)
        {
            string?hash = Utilities.Utils.LevelIdToHash(packet.levelId);

            if (hash != null)
            {
                Plugin.Log?.Debug($"'{player.userId}' selected song '{hash}'.");
                BeatmapCharacteristicSO characteristic = _beatmapCharacteristicCollection.GetBeatmapCharacteristicBySerializedName(packet.characteristic);
                PreviewBeatmapStub      preview        = new PreviewBeatmapStub(packet);
                HMMainThreadDispatcher.instance.Enqueue(() => base.SetPlayerBeatmapLevel(player.userId, preview, packet.difficulty, characteristic));
            }
        }
示例#27
0
        public void StartLevel(IBeatmapLevel level, BeatmapCharacteristicSO characteristic, BeatmapDifficulty difficulty, GameplayModifiers modifiers, float startTime = 0f)
        {
            Client.Instance.playerInfo.updateInfo.playerComboBlocks  = 0;
            Client.Instance.playerInfo.updateInfo.playerCutBlocks    = 0;
            Client.Instance.playerInfo.updateInfo.playerTotalBlocks  = 0;
            Client.Instance.playerInfo.updateInfo.playerEnergy       = 0f;
            Client.Instance.playerInfo.updateInfo.playerScore        = 0;
            Client.Instance.playerInfo.updateInfo.playerLevelOptions = new LevelOptionsInfo(difficulty, modifiers, characteristic.serializedName);

            MenuTransitionsHelperSO menuSceneSetupData = Resources.FindObjectsOfTypeAll <MenuTransitionsHelperSO>().FirstOrDefault();

            if (_playerManagementViewController != null)
            {
                _playerManagementViewController.SetGameplayModifiers(modifiers);
            }

            if (menuSceneSetupData != null)
            {
                Client.Instance.playerInfo.updateInfo.playerState = Config.Instance.SpectatorMode ? PlayerState.Spectating : PlayerState.Game;

                PlayerSpecificSettings playerSettings = Resources.FindObjectsOfTypeAll <PlayerDataModelSO>().FirstOrDefault().playerData.playerSpecificSettings;

                roomInfo.roomState = RoomState.InGame;

                IDifficultyBeatmap difficultyBeatmap = level.GetDifficultyBeatmap(characteristic, difficulty, false);

                Plugin.log.Debug($"Starting song: name={level.songName}, levelId={level.levelID}, difficulty={difficulty}");

                Client.Instance.MessageReceived -= PacketReceived;

                try
                {
                    BS_Utils.Gameplay.Gamemode.NextLevelIsIsolated("Beat Saber Multiplayer");
                }
                catch
                {
                }

                PracticeSettings practiceSettings = new PracticeSettings(PracticeSettings.defaultPracticeSettings);
                practiceSettings.startSongTime = startTime + 1.5f;
                practiceSettings.songSpeedMul  = modifiers.songSpeedMul;
                practiceSettings.startInAdvanceAndClearNotes = true;

                menuSceneSetupData.StartStandardLevel(difficultyBeatmap, new OverrideEnvironmentSettings()
                {
                    overrideEnvironments = false
                }, null, modifiers, playerSettings, (startTime > 1f ? practiceSettings : null), "Lobby", false, () => { }, (StandardLevelScenesTransitionSetupDataSO sender, LevelCompletionResults levelCompletionResults) => { InGameOnlineController.Instance.SongFinished(levelCompletionResults, difficultyBeatmap, modifiers, startTime > 1f); });
            }
            else
            {
                Plugin.log.Error("SceneSetupData is null!");
            }
        }
        public async override void HandleMenuRpcManagerSelectedBeatmap(string userId, BeatmapIdentifierNetSerializable beatmapId)
        {
            if (beatmapId != null)
            {
                string?hash = Utilities.Utils.LevelIdToHash(beatmapId.levelID);
                if (hash != null)
                {
                    Plugin.Log?.Debug($"'{userId}' selected song '{hash}'.");
                    BeatmapCharacteristicSO characteristic = _beatmapCharacteristicCollection.GetBeatmapCharacteristicBySerializedName(beatmapId.beatmapCharacteristicSerializedName);
                    PreviewBeatmapStub?     preview        = null;

                    if (_playersData.Values.Any(playerData => playerData.beatmapLevel?.levelID == beatmapId.levelID))
                    {
                        IPreviewBeatmapLevel playerPreview = _playersData.Values.Where(playerData => playerData.beatmapLevel?.levelID == beatmapId.levelID).First().beatmapLevel;
                        if (playerPreview is PreviewBeatmapStub playerPreviewStub)
                        {
                            preview = playerPreviewStub;
                        }
                    }

                    IPreviewBeatmapLevel localPreview = SongCore.Loader.GetLevelById(beatmapId.levelID);
                    if (localPreview != null)
                    {
                        preview = new PreviewBeatmapStub(hash, localPreview);
                    }

                    if (preview == null)
                    {
                        try
                        {
                            Beatmap bm = await Plugin.BeatSaver.Hash(hash);

                            preview = new PreviewBeatmapStub(bm);
                        }
                        catch
                        {
                            return;
                        }
                    }

                    if (userId == base.hostUserId)
                    {
                        _sessionManager.SetLocalPlayerState("beatmap_downloaded", preview.isDownloaded);
                    }

                    HMMainThreadDispatcher.instance.Enqueue(() => base.SetPlayerBeatmapLevel(userId, preview, beatmapId.difficulty, characteristic));
                    return;
                }
            }

            base.HandleMenuRpcManagerSelectedBeatmap(userId, beatmapId);
        }
示例#29
0
        public static void HandleSongSelected(IPreviewBeatmapLevel previewBeatmapLevel, BeatmapDifficulty beatmapDifficulty,
                                              BeatmapCharacteristicSO beatmapCharacteristic, GameplayModifiers gameplayModifiers)
        {
            if (!MpLobbyConnectionTypePatch.IsPartyHost)
            {
                return;
            }

            _level      = previewBeatmapLevel;
            _difficulty = beatmapDifficulty;

            HandleUpdate();
        }
示例#30
0
 //      public static OverrideClasses.CustomLevel previouslySelectedSong = null;
 private static void Postfix(string serializedName, ref BeatmapCharacteristicSO __result)
 {
     if (__result == null)
     {
         if (Collections.customCharacteristics.Any(x => x.serializedName == serializedName))
         {
             __result = Collections.customCharacteristics.FirstOrDefault(x => x.serializedName == serializedName);
         }
         else
         {
             __result = Collections.customCharacteristics.FirstOrDefault(x => x.serializedName == "MissingCharacteristic");
         }
     }
 }