public void LoadMap(int indexToLoad, int difficultyIndex) { if (indexToLoad >= availableMaps.Count) { throw new ArgumentException("Invalid map index"); } string toLoadFrom = availableMaps[indexToLoad].directory + System.IO.Path.DirectorySeparatorChar + availableMaps[indexToLoad].index.difficulties[difficultyIndex].name + ".txt"; string loadedString = System.IO.File.ReadAllText(toLoadFrom); if (loaded != null) { ClearLoaded(); } loaded = (LoadedSong)ScriptableObject.CreateInstance("LoadedSong"); loaded.beatsPerMeasure = availableMaps[indexToLoad].index.beatsPerMeasure; loaded.bpm = availableMaps[indexToLoad].index.bpm; loaded.name = availableMaps[indexToLoad].index.name; loaded.offset = availableMaps[indexToLoad].index.offset; loaded = LoadSongFromFile.LoadSong(loadedString, loaded); SongfileImporter.instance.LoadSong(availableMaps[indexToLoad].directory + System.IO.Path.DirectorySeparatorChar + availableMaps[indexToLoad].index.songfile); loaded.SongIsLoading(); Debug.Log("Successful Load Map"); }
} // RemoveSongs /// <summary> /// Remove songs from the playlist. /// </summary> /// <remarks> /// If a content manager is unload and this content manager was used to load songs then this method is very useful for remove all the songs loaded in there. /// </remarks> public static void RemoveSongs(AssetContentManager contentManager) { // First we count how much elements the new playlist will have. int elementCount = 0; for (int i = 0; i < playlist.Length; i++) { if (playlist[i].Asset.ContentManager == contentManager) { // If we want to remove the current song we have to stop it first. if (currentIndex == i) { Stop(); } } else { elementCount++; } } // Then we create the new playlist. LoadedSong[] newPlaylist = new LoadedSong[elementCount]; int k = 0; for (int i = 0; i < playlist.Length; i++) { if (playlist[i].Asset.ContentManager != contentManager) { newPlaylist[k] = playlist[i]; k++; } } playlist = newPlaylist; } // RemoveSongs
} // LoadAllSong /// <summary> /// Load a list of songs into the playlist. /// </summary> /// <remarks> /// If you don’t want to waste valuable space you can load the songs one at a time but the songs will be loaded in game, /// that means a noticeable slow down every time a song is loaded. /// However, the music system allows you to load a chunk of songs at the same time. But be careful of the memory allocation. /// This is the default behavior and it is controled with the preload value. /// </remarks> public static void LoadSongs(string[] songsFilename, bool preload = true) { if (songsFilename == null) { throw new ArgumentNullException("songsFilename"); } List <LoadedSong> playlistTemp = new List <LoadedSong>(); foreach (var songFilename in songsFilename) { try { bool songExist = false; for (int j = 0; j < playlist.Length; j++) { songExist = songExist || playlist[j].Filename == songFilename; } if (!songExist) { playlistTemp.Add(new LoadedSong { Filename = songFilename, Asset = preload ? new Song(songFilename) : null }); } } catch (Exception e) { throw new InvalidOperationException("Music Manager: Failed to load song: " + songFilename, e); } } LoadedSong[] newPlayList = new LoadedSong[playlist.Length + playlistTemp.Count]; playlist.CopyTo(newPlayList, 0); playlistTemp.CopyTo(newPlayList, playlist.Length); playlist = newPlayList; } // LoadAllSong
// Use this for initialization void Start() { try { if (MapLoader.instance.loaded == null) { MapLoader.instance.LoadMap(0, 0); } LoadedSong initSong = MapLoader.instance.loaded; if (initSong != null) { timekeeper.SetBPM(initSong.bpm); StartCoroutine(PlaySong(initSong)); } PauseManager.PausableUpdate += PausableUpdate; } catch (ArgumentException e) { Abort(); Debug.Log(e); } ScoreManager.instance.ResetScore(); }
IEnumerator PlaySong(LoadedSong song) { //This will wait for songfile to load, if possible yield return(song.PrepForPlaying()); if (song.song == null) { Abort(); yield break; } this.song = song; AddCursor(loader); AddCursor(timing); actualOffset = -1 * (totalOffset + song.offset); if (actualOffset > 0) { player.Play(song, 0); StartCoroutine(StartAfterDelay(actualOffset / 1000.0f)); } else { player.Play(song, (-1 * actualOffset) / 1000.0f); StartCoroutine(StartAfterDelay(0)); } }
} // Previous #endregion #region Playlist Order /// <summary> /// Swap playlist elements. /// </summary> /// <param name="index1">The index of the first element.</param> /// <param name="index2">The index of the second element.</param> public static void SwapPlaylistElements(int index1, int index2) { LoadedSong temp = playlist[index1 - 1]; playlist[index1 - 1] = playlist[index2 - 1]; playlist[index2 - 1] = temp; } // SwapPlaylistElements
public void ClearLoaded() { if (loaded != null && !loaded.Equals(null)) { Destroy(loaded); } loaded = null; }
public void Play(LoadedSong song, float delay) { source.clip = song.song; if (delay < 0) { throw new System.ArgumentException("Delay cannot be negative", "delay"); } else { StartCoroutine(PlayAfterDelay(delay)); } }
private void Client_PacketRecieved(Packet packet) { if (packet.Type == PacketType.PlaySong) { PlaySong playSong = packet.SpecificPacket as PlaySong; var desiredLevel = Plugin.masterLevelList.First(x => x.levelID == playSong.levelId); var desiredCharacteristic = desiredLevel.previewDifficultyBeatmapSets.GetBeatmapCharacteristics().First(x => x.serializedName == playSong.characteristic.SerializedName); var desiredDifficulty = (BeatmapDifficulty)playSong.difficulty; SaberUtilities.PlaySong(desiredLevel, desiredCharacteristic, desiredDifficulty, playSong); } else if (packet.Type == PacketType.LoadSong) { LoadSong loadSong = packet.SpecificPacket as LoadSong; Action <IBeatmapLevel> SongLoaded = (loadedLevel) => { var loadedSong = new LoadedSong(); var beatmapLevel = new PreviewBeatmapLevel(); beatmapLevel.Characteristics = loadedLevel.beatmapLevelData.difficultyBeatmapSets.ToList().Select(x => { var characteristic = new Characteristic(); characteristic.SerializedName = x.beatmapCharacteristic.serializedName; characteristic.difficulties = loadedLevel.beatmapLevelData.difficultyBeatmapSets .First(y => y.beatmapCharacteristic.serializedName == x.beatmapCharacteristic.serializedName) .difficultyBeatmaps.Select(y => (Characteristic.BeatmapDifficulty)y.difficulty).ToArray(); return(characteristic); }).ToArray(); beatmapLevel.LevelId = loadedLevel.levelID; beatmapLevel.Name = loadedLevel.songName; beatmapLevel.Loaded = true; loadedSong.level = beatmapLevel; client.Send(new Packet(loadedSong).ToBytes()); }; LoadSong(loadSong.levelId, SongLoaded); } else if (packet.Type == PacketType.Command) { Command command = packet.SpecificPacket as Command; if (command.commandType == Command.CommandType.ReturnToMenu) { SaberUtilities.ReturnToMenu(); } } }
private void Server_PacketRecieved(NetworkPlayer player, Packet packet) { if (packet.Type == PacketType.SongList) { SongList masterLevelCollection = packet.SpecificPacket as SongList; panel.PopulatePartyPanel(masterLevelCollection.Levels.ToList()); } else if (packet.Type == PacketType.LoadedSong) { LoadedSong loadedSong = packet.SpecificPacket as LoadedSong; panel.SongLoaded(loadedSong.level); } }
} // Initialize #endregion #region Load Songs /// <summary> /// Load all songs of the music directoy into the playlist. /// </summary> /// <remarks> /// If you don’t want to waste valuable space you can load the songs one at a time but the songs will be loaded in game, /// that means a noticeable slow down every time a song is loaded. /// However, the music system allows you to load a chunk of songs at the same time. But be careful of the memory allocation. /// This is the default behavior and it is controled with the preload value. /// </remarks> public static void LoadAllSong(bool preload = true) { playlist = new LoadedSong[SongsFilename.Length]; int i = 0; foreach (var songFilename in SongsFilename) { try { playlist[i] = new LoadedSong { Filename = songFilename, Asset = preload ? new Song(songFilename) : null }; i++; } catch (Exception e) { throw new InvalidOperationException("Music Manager: Failed to load song: " + songFilename, e); } } } // LoadAllSong
} // RemoveAllSong /// <summary> /// Remove songs from the playlist. /// </summary> public static void RemoveSongs(string[] songsFilename) { // First we count how much elements the new playlist will have. int elementCount = 0; for (int i = 0; i < playlist.Length; i++) { for (int j = 0; j < songsFilename.Length; j++) { if (playlist[i].Filename == songsFilename[j]) { // If we want to remove the current song we have to stop it first. if (currentIndex == i) { Stop(); } } else { elementCount++; } } } // Then we create the new playlist. LoadedSong[] newPlaylist = new LoadedSong[elementCount]; int k = 0; for (int i = 0; i < playlist.Length; i++) { for (int j = 0; j < songsFilename.Length; j++) { if (playlist[i].Filename != songsFilename[j]) { newPlaylist[k] = playlist[i]; k++; } } } playlist = newPlaylist; } // RemoveSongs
public static LoadedSong LoadSong(string toLoad, LoadedSong toPopulate) { toPopulate.notes = new List <Note>(); StringReader reader = new StringReader(toLoad); Timestamp lastTime = new Timestamp(0, 0, 0); while (reader.Peek() > -1) { string line = reader.ReadLine(); if (line.Length < 1) { continue; } if (line[0] == COMMENT) { continue; } if (line[0] == NOTE) { Note toAdd = ParseNote(line); toPopulate.notes.Add(toAdd); lastTime = toAdd.timing; } else if (line[0] == NOTE_RELATIVE) { Note toAdd = ParseNote(line); toAdd.timing.addTicks(toPopulate.beatsPerMeasure, lastTime.getTicks(toPopulate.beatsPerMeasure)); toPopulate.notes.Add(toAdd); lastTime = toAdd.timing; } else if (line.Contains(VALUE_DELIM.ToString())) { // Currently no values are allowed in difficulty file } } return(toPopulate); }
protected override void Client_PacketReceived(Packet packet) { base.Client_PacketReceived(packet); if (packet.Type == PacketType.PlaySong) { PlaySong playSong = packet.SpecificPacket as PlaySong; var desiredLevel = SongUtils.masterLevelList.First(x => x.levelID == playSong.GameplayParameters.Beatmap.LevelId); var desiredCharacteristic = desiredLevel.previewDifficultyBeatmapSets.FirstOrDefault(x => x.beatmapCharacteristic.serializedName == playSong.GameplayParameters.Beatmap.Characteristic.SerializedName).beatmapCharacteristic ?? desiredLevel.previewDifficultyBeatmapSets.First().beatmapCharacteristic; var desiredDifficulty = (BeatmapDifficulty)playSong.GameplayParameters.Beatmap.Difficulty; var playerData = Resources.FindObjectsOfTypeAll <PlayerDataModel>().First().playerData; var playerSettings = playerData.playerSpecificSettings; //Override defaults if we have forced options enabled if (playSong.GameplayParameters.PlayerSettings.Options != PlayerOptions.None) { playerSettings = new PlayerSpecificSettings( playSong.GameplayParameters.PlayerSettings.Options.HasFlag(PlayerOptions.StaticLights), playSong.GameplayParameters.PlayerSettings.Options.HasFlag(PlayerOptions.LeftHanded), playSong.GameplayParameters.PlayerSettings.PlayerHeight, playSong.GameplayParameters.PlayerSettings.Options.HasFlag(PlayerOptions.AutoPlayerHeight), playSong.GameplayParameters.PlayerSettings.SfxVolume, playSong.GameplayParameters.PlayerSettings.Options.HasFlag(PlayerOptions.ReduceDebris), playSong.GameplayParameters.PlayerSettings.Options.HasFlag(PlayerOptions.NoHud), playSong.GameplayParameters.PlayerSettings.Options.HasFlag(PlayerOptions.NoFailEffects), playSong.GameplayParameters.PlayerSettings.Options.HasFlag(PlayerOptions.AdvancedHud), playSong.GameplayParameters.PlayerSettings.Options.HasFlag(PlayerOptions.AutoRestart), playSong.GameplayParameters.PlayerSettings.SaberTrailIntensity, playSong.GameplayParameters.PlayerSettings.NoteJumpStartBeatOffset, playSong.GameplayParameters.PlayerSettings.Options.HasFlag(PlayerOptions.HideNoteSpawnEffect), playSong.GameplayParameters.PlayerSettings.Options.HasFlag(PlayerOptions.AdaptiveSfx) ); } var songSpeed = GameplayModifiers.SongSpeed.Normal; if (playSong.GameplayParameters.GameplayModifiers.Options.HasFlag(GameOptions.SlowSong)) { songSpeed = GameplayModifiers.SongSpeed.Slower; } if (playSong.GameplayParameters.GameplayModifiers.Options.HasFlag(GameOptions.FastSong)) { songSpeed = GameplayModifiers.SongSpeed.Faster; } var gameplayModifiers = new GameplayModifiers( playSong.GameplayParameters.GameplayModifiers.Options.HasFlag(GameOptions.DemoNoFail), playSong.GameplayParameters.GameplayModifiers.Options.HasFlag(GameOptions.DemoNoObstacles), playSong.GameplayParameters.GameplayModifiers.Options.HasFlag(GameOptions.BatteryEnergy) ? GameplayModifiers.EnergyType.Battery : GameplayModifiers.EnergyType.Bar, playSong.GameplayParameters.GameplayModifiers.Options.HasFlag(GameOptions.NoFail), playSong.GameplayParameters.GameplayModifiers.Options.HasFlag(GameOptions.InstaFail), playSong.GameplayParameters.GameplayModifiers.Options.HasFlag(GameOptions.FailOnClash), playSong.GameplayParameters.GameplayModifiers.Options.HasFlag(GameOptions.NoObstacles) ? GameplayModifiers.EnabledObstacleType.NoObstacles : GameplayModifiers.EnabledObstacleType.All, playSong.GameplayParameters.GameplayModifiers.Options.HasFlag(GameOptions.NoBombs), playSong.GameplayParameters.GameplayModifiers.Options.HasFlag(GameOptions.FastNotes), playSong.GameplayParameters.GameplayModifiers.Options.HasFlag(GameOptions.StrictAngles), playSong.GameplayParameters.GameplayModifiers.Options.HasFlag(GameOptions.DisappearingArrows), songSpeed, playSong.GameplayParameters.GameplayModifiers.Options.HasFlag(GameOptions.NoArrows), playSong.GameplayParameters.GameplayModifiers.Options.HasFlag(GameOptions.GhostNotes) ); var colorScheme = playerData.colorSchemesSettings.overrideDefaultColors ? playerData.colorSchemesSettings.GetSelectedColorScheme() : null; //Disable score submission if nofail is on. This is specifically for Hidden Sabers, though it may stay longer if (playSong.DisableScoresaberSubmission) { BS_Utils.Gameplay.ScoreSubmission.DisableSubmission(SharedConstructs.Name); } if (playSong.ShowNormalNotesOnStream) { var customNotes = IPA.Loader.PluginManager.GetPluginFromId("CustomNotes"); if (customNotes != null) { EnableHMDOnly(); } } PlaySong?.Invoke(desiredLevel, desiredCharacteristic, desiredDifficulty, gameplayModifiers, playerSettings, playerData.overrideEnvironmentSettings, colorScheme, playSong.FloatingScoreboard, playSong.StreamSync, playSong.DisablePause, playSong.DisableFail); } else if (packet.Type == PacketType.Command) { Command command = packet.SpecificPacket as Command; if (command.CommandType == Command.CommandTypes.ReturnToMenu) { if (SyncHandler.Instance != null) { ScreenOverlay.Instance.Clear(); } if ((Self as Player).PlayState == Player.PlayStates.InGame) { PlayerUtils.ReturnToMenu(); } } else if (command.CommandType == Command.CommandTypes.ScreenOverlay_ShowPng) { ScreenOverlay.Instance.ShowPng(); } else if (command.CommandType == Command.CommandTypes.DelayTest_Finish) { UnityMainThreadDispatcher.Instance().Enqueue(() => { ScreenOverlay.Instance.Clear(); SyncHandler.Instance.Resume(); SyncHandler.Destroy(); }); } } else if (packet.Type == PacketType.LoadSong) { LoadSong loadSong = packet.SpecificPacket as LoadSong; Action <IBeatmapLevel> SongLoaded = (loadedLevel) => { //Send updated download status (Self as Player).DownloadState = Player.DownloadStates.Downloaded; var playerUpdate = new Event(); playerUpdate.Type = Event.EventType.PlayerUpdated; playerUpdate.ChangedObject = Self; Send(new Packet(playerUpdate)); //Notify any listeners of the client that a song has been loaded LoadedSong?.Invoke(loadedLevel); }; if (OstHelper.IsOst(loadSong.LevelId)) { SongLoaded?.Invoke(SongUtils.masterLevelList.First(x => x.levelID == loadSong.LevelId) as BeatmapLevelSO); } else { if (SongUtils.masterLevelList.Any(x => x.levelID == loadSong.LevelId)) { SongUtils.LoadSong(loadSong.LevelId, SongLoaded); } else { Action <string, bool> loadSongAction = (hash, succeeded) => { if (succeeded) { SongUtils.LoadSong(loadSong.LevelId, SongLoaded); } else { (Self as Player).DownloadState = Player.DownloadStates.DownloadError; var playerUpdated = new Event(); playerUpdated.Type = Event.EventType.PlayerUpdated; playerUpdated.ChangedObject = Self; Send(new Packet(playerUpdated)); } }; (Self as Player).DownloadState = Player.DownloadStates.Downloading; var playerUpdate = new Event(); playerUpdate.Type = Event.EventType.PlayerUpdated; playerUpdate.ChangedObject = Self; Send(new Packet(playerUpdate)); SongDownloader.DownloadSong(loadSong.LevelId, songDownloaded: loadSongAction, downloadProgressChanged: (hash, progress) => Logger.Debug($"DOWNLOAD PROGRESS ({hash}): {progress}"), customHostUrl: loadSong.CustomHostUrl); } } } else if (packet.Type == PacketType.File) { File file = packet.SpecificPacket as File; if (file.Intent == File.Intentions.SetPngToShowWhenTriggered) { var pngBytes = file.Compressed ? CompressionUtils.Decompress(file.Data) : file.Data; ScreenOverlay.Instance.SetPngBytes(pngBytes); } else if (file.Intent == File.Intentions.ShowPngImmediately) { var pngBytes = file.Compressed ? CompressionUtils.Decompress(file.Data) : file.Data; ScreenOverlay.Instance.SetPngBytes(pngBytes); ScreenOverlay.Instance.ShowPng(); } Send(packet.From, new Packet(new Acknowledgement() { PacketId = packet.Id, Type = Acknowledgement.AcknowledgementType.FileDownloaded })); } }
private void Server_PacketRecieved(ConnectedClient player, Packet packet) { #region LOGGING string secondaryInfo = string.Empty; if (packet.Type == PacketType.PlaySong) { secondaryInfo = (packet.SpecificPacket as PlaySong).Beatmap.LevelId + " : " + (packet.SpecificPacket as PlaySong).Beatmap.Difficulty; } else if (packet.Type == PacketType.LoadSong) { secondaryInfo = (packet.SpecificPacket as LoadSong).LevelId; } else if (packet.Type == PacketType.Command) { secondaryInfo = (packet.SpecificPacket as Command).CommandType.ToString(); } else if (packet.Type == PacketType.Event) { secondaryInfo = (packet.SpecificPacket as Event).Type.ToString(); if ((packet.SpecificPacket as Event).Type == Event.EventType.PlayerUpdated) { secondaryInfo = $"{secondaryInfo} from ({((packet.SpecificPacket as Event).ChangedObject as Player).Name} : {((packet.SpecificPacket as Event).ChangedObject as Player).DownloadState}) : ({((packet.SpecificPacket as Event).ChangedObject as Player).PlayState} : {((packet.SpecificPacket as Event).ChangedObject as Player).Score} : {((packet.SpecificPacket as Event).ChangedObject as Player).StreamDelayMs})"; } else if ((packet.SpecificPacket as Event).Type == Event.EventType.MatchUpdated) { secondaryInfo = $"{secondaryInfo} ({((packet.SpecificPacket as Event).ChangedObject as Match).SelectedDifficulty})"; } } else if (packet.Type == PacketType.ForwardingPacket) { secondaryInfo = $"{(packet.SpecificPacket as ForwardingPacket).SpecificPacket.GetType()}"; } Logger.Debug($"Recieved {packet.ToBytes().Length} bytes: ({packet.Type}) ({secondaryInfo})"); #endregion LOGGING SendToOverlay(packet); //Ready to go, only disabled since it is currently unusued /*if (packet.Type != PacketType.Acknowledgement) * { * Send(packet.From, new Packet(new Acknowledgement() * { * PacketId = packet.Id * })); * }*/ if (packet.Type == PacketType.Acknowledgement) { Acknowledgement acknowledgement = packet.SpecificPacket as Acknowledgement; AckReceived?.Invoke(acknowledgement, packet.From); } else if (packet.Type == PacketType.SongList) { SongList songList = packet.SpecificPacket as SongList; } else if (packet.Type == PacketType.LoadedSong) { LoadedSong loadedSong = packet.SpecificPacket as LoadedSong; } else if (packet.Type == PacketType.Connect) { Connect connect = packet.SpecificPacket as Connect; if (connect.ClientVersion != SharedConstructs.VersionCode) { Send(player.id, new Packet(new ConnectResponse() { Type = ConnectResponse.ResponseType.Fail, Self = null, State = null, Message = $"Version mismatch, this server is on version {SharedConstructs.Version}", ServerVersion = SharedConstructs.VersionCode })); } else if (connect.ClientType == Connect.ConnectTypes.Player) { var newPlayer = new Player() { Id = player.id, Name = connect.Name, UserId = connect.UserId, Team = new Team() { Id = Guid.Empty, Name = "None" } }; AddPlayer(newPlayer); //Give the newly connected player their Self and State Send(player.id, new Packet(new ConnectResponse() { Type = ConnectResponse.ResponseType.Success, Self = newPlayer, State = State, Message = $"Connected to {serverName}!", ServerVersion = SharedConstructs.VersionCode })); } else if (connect.ClientType == Connect.ConnectTypes.Coordinator) { var coordinator = new MatchCoordinator() { Id = player.id, Name = connect.Name }; AddCoordinator(coordinator); //Give the newly connected coordinator their Self and State Send(player.id, new Packet(new ConnectResponse() { Type = ConnectResponse.ResponseType.Success, Self = coordinator, State = State, Message = $"Connected to {serverName}!", ServerVersion = SharedConstructs.VersionCode })); } } else if (packet.Type == PacketType.Event) { Event @event = packet.SpecificPacket as Event; switch (@event.Type) { case Event.EventType.CoordinatorAdded: AddCoordinator(@event.ChangedObject as MatchCoordinator); break; case Event.EventType.CoordinatorLeft: RemoveCoordinator(@event.ChangedObject as MatchCoordinator); break; case Event.EventType.MatchCreated: CreateMatch(@event.ChangedObject as Match); break; case Event.EventType.MatchUpdated: UpdateMatch(@event.ChangedObject as Match); break; case Event.EventType.MatchDeleted: DeleteMatch(@event.ChangedObject as Match); break; case Event.EventType.PlayerAdded: AddPlayer(@event.ChangedObject as Player); break; case Event.EventType.PlayerUpdated: UpdatePlayer(@event.ChangedObject as Player); break; case Event.EventType.PlayerLeft: RemovePlayer(@event.ChangedObject as Player); break; default: Logger.Error($"Unknown command recieved from {player.id}!"); break; } } else if (packet.Type == PacketType.SongFinished) { BroadcastToAllClients(packet); PlayerFinishedSong?.Invoke(packet.SpecificPacket as SongFinished); } else if (packet.Type == PacketType.ForwardingPacket) { var forwardingPacket = packet.SpecificPacket as ForwardingPacket; var forwardedPacket = new Packet(forwardingPacket.SpecificPacket); ForwardTo(forwardingPacket.ForwardTo, packet.From, forwardedPacket); } }
protected override void Client_PacketRecieved(Packet packet) { base.Client_PacketRecieved(packet); if (packet.Type == PacketType.PlaySong) { PlaySong playSong = packet.SpecificPacket as PlaySong; var desiredLevel = SongUtils.masterLevelList.First(x => x.levelID == playSong.Beatmap.LevelId); var desiredCharacteristic = desiredLevel.previewDifficultyBeatmapSets.FirstOrDefault(x => x.beatmapCharacteristic.serializedName == playSong.Beatmap.Characteristic.SerializedName).beatmapCharacteristic ?? desiredLevel.previewDifficultyBeatmapSets.First().beatmapCharacteristic; var desiredDifficulty = (BeatmapDifficulty)playSong.Beatmap.Difficulty; var playerData = Resources.FindObjectsOfTypeAll <PlayerDataModel>().First().playerData; var playerSettings = playerData.playerSpecificSettings; //Override defaults if we have forced options enabled if (playSong.PlayerSettings.Options != PlayerOptions.None) { playerSettings = new PlayerSpecificSettings(); playerSettings.leftHanded = playSong.PlayerSettings.Options.HasFlag(PlayerOptions.LeftHanded); playerSettings.staticLights = playSong.PlayerSettings.Options.HasFlag(PlayerOptions.StaticLights); playerSettings.noTextsAndHuds = playSong.PlayerSettings.Options.HasFlag(PlayerOptions.NoHud); playerSettings.advancedHud = playSong.PlayerSettings.Options.HasFlag(PlayerOptions.AdvancedHud); playerSettings.reduceDebris = playSong.PlayerSettings.Options.HasFlag(PlayerOptions.ReduceDebris); } var gameplayModifiers = new GameplayModifiers(); gameplayModifiers.batteryEnergy = playSong.GameplayModifiers.Options.HasFlag(GameOptions.BatteryEnergy); gameplayModifiers.disappearingArrows = playSong.GameplayModifiers.Options.HasFlag(GameOptions.DisappearingArrows); gameplayModifiers.failOnSaberClash = playSong.GameplayModifiers.Options.HasFlag(GameOptions.FailOnClash); gameplayModifiers.fastNotes = playSong.GameplayModifiers.Options.HasFlag(GameOptions.FastNotes); gameplayModifiers.ghostNotes = playSong.GameplayModifiers.Options.HasFlag(GameOptions.GhostNotes); gameplayModifiers.instaFail = playSong.GameplayModifiers.Options.HasFlag(GameOptions.InstaFail); gameplayModifiers.noBombs = playSong.GameplayModifiers.Options.HasFlag(GameOptions.NoBombs); gameplayModifiers.noFail = playSong.GameplayModifiers.Options.HasFlag(GameOptions.NoFail); gameplayModifiers.noObstacles = playSong.GameplayModifiers.Options.HasFlag(GameOptions.NoObstacles); gameplayModifiers.noArrows = playSong.GameplayModifiers.Options.HasFlag(GameOptions.NoArrows); if (playSong.GameplayModifiers.Options.HasFlag(GameOptions.SlowSong)) { gameplayModifiers.songSpeed = GameplayModifiers.SongSpeed.Slower; } if (playSong.GameplayModifiers.Options.HasFlag(GameOptions.FastSong)) { gameplayModifiers.songSpeed = GameplayModifiers.SongSpeed.Faster; } var colorScheme = playerData.colorSchemesSettings.overrideDefaultColors ? playerData.colorSchemesSettings.GetSelectedColorScheme() : null; PlaySong?.Invoke(desiredLevel, desiredCharacteristic, desiredDifficulty, gameplayModifiers, playerSettings, playerData.overrideEnvironmentSettings, colorScheme, playSong.FloatingScoreboard, playSong.StreamSync, playSong.DisablePause, playSong.DisableFail); } else if (packet.Type == PacketType.Command) { Command command = packet.SpecificPacket as Command; if (command.CommandType == Command.CommandTypes.ReturnToMenu) { if (SyncHandler.Instance != null) { ScreenOverlay.Instance.Clear(); } if ((Self as Player).PlayState == Player.PlayStates.InGame) { PlayerUtils.ReturnToMenu(); } } else if (command.CommandType == Command.CommandTypes.ScreenOverlay_ShowPng) { ScreenOverlay.Instance.ShowPng(); } else if (command.CommandType == Command.CommandTypes.DelayTest_Finish) { UnityMainThreadDispatcher.Instance().Enqueue(() => { ScreenOverlay.Instance.Clear(); SyncHandler.Instance.Resume(); SyncHandler.Destroy(); }); } } else if (packet.Type == PacketType.LoadSong) { LoadSong loadSong = packet.SpecificPacket as LoadSong; Action <IBeatmapLevel> SongLoaded = (loadedLevel) => { //Send updated download status (Self as Player).DownloadState = Player.DownloadStates.Downloaded; var playerUpdate = new Event(); playerUpdate.Type = Event.EventType.PlayerUpdated; playerUpdate.ChangedObject = Self; Send(new Packet(playerUpdate)); //Notify any listeners of the client that a song has been loaded LoadedSong?.Invoke(loadedLevel); Logger.Debug($"SENT DOWNLOADED SIGNAL {(playerUpdate.ChangedObject as Player).DownloadState}"); }; if (OstHelper.IsOst(loadSong.LevelId)) { SongLoaded?.Invoke(SongUtils.masterLevelList.First(x => x.levelID == loadSong.LevelId) as BeatmapLevelSO); } else { if (SongUtils.masterLevelList.Any(x => x.levelID == loadSong.LevelId)) { SongUtils.LoadSong(loadSong.LevelId, SongLoaded); } else { Action <bool> loadSongAction = (succeeded) => { if (succeeded) { SongUtils.LoadSong(loadSong.LevelId, SongLoaded); } else { (Self as Player).DownloadState = Player.DownloadStates.DownloadError; var playerUpdated = new Event(); playerUpdated.Type = Event.EventType.PlayerUpdated; playerUpdated.ChangedObject = Self; Send(new Packet(playerUpdated)); Logger.Debug($"SENT DOWNLOADED SIGNAL {(playerUpdated.ChangedObject as Player).DownloadState}"); } }; (Self as Player).DownloadState = Player.DownloadStates.Downloading; var playerUpdate = new Event(); playerUpdate.Type = Event.EventType.PlayerUpdated; playerUpdate.ChangedObject = Self; Send(new Packet(playerUpdate)); Logger.Debug($"SENT DOWNLOAD SIGNAL {(playerUpdate.ChangedObject as Player).DownloadState}"); SongDownloader.DownloadSong(loadSong.LevelId, songDownloaded: loadSongAction, downloadProgressChanged: (progress) => Logger.Debug($"DOWNLOAD PROGRESS: {progress}")); } } } else if (packet.Type == PacketType.File) { File file = packet.SpecificPacket as File; if (file.Intention == File.Intentions.SetPngToShowWhenTriggered) { var pngBytes = file.Compressed ? CompressionUtils.Decompress(file.Data) : file.Data; ScreenOverlay.Instance.SetPngBytes(pngBytes); } else if (file.Intention == File.Intentions.ShowPngImmediately) { var pngBytes = file.Compressed ? CompressionUtils.Decompress(file.Data) : file.Data; ScreenOverlay.Instance.SetPngBytes(pngBytes); ScreenOverlay.Instance.ShowPng(); } Send(packet.From, new Packet(new Acknowledgement() { PacketId = packet.Id, Type = Acknowledgement.AcknowledgementType.FileDownloaded })); } }
protected override void Client_PacketRecieved(Packet packet) { base.Client_PacketRecieved(packet); if (packet.Type == PacketType.PlaySong) { PlaySong playSong = packet.SpecificPacket as PlaySong; PlaySong?.Invoke(playSong.Beatmap); } else if (packet.Type == PacketType.Command) { Command command = packet.SpecificPacket as Command; if (command.CommandType == Command.CommandTypes.ReturnToMenu) { if ((Self as Player).PlayState == Player.PlayStates.InGame) { ReturnToMenu?.Invoke(); } } } else if (packet.Type == PacketType.LoadSong) { LoadSong loadSong = packet.SpecificPacket as LoadSong; //Send updated download status (Self as Player).DownloadState = Player.DownloadStates.Downloading; var playerUpdate = new Event(); playerUpdate.Type = Event.EventType.PlayerUpdated; playerUpdate.ChangedObject = Self; Send(new Packet(playerUpdate)); var hash = HashFromLevelId(loadSong.LevelId); BeatSaverDownloader.DownloadSongInfoThreaded(hash, (successfulDownload) => { if (successfulDownload) { var song = new DownloadedSong(hash); var mapFormattedLevelId = $"custom_level_{hash.ToUpper()}"; var matchMap = new PreviewBeatmapLevel() { LevelId = mapFormattedLevelId, Name = song.Name }; List <Characteristic> characteristics = new List <Characteristic>(); foreach (var characteristic in song.Characteristics) { characteristics.Add(new Characteristic() { SerializedName = characteristic, Difficulties = song.GetBeatmapDifficulties(characteristic) }); } matchMap.Characteristics = characteristics.ToArray(); //Send updated download status (Self as Player).DownloadState = Player.DownloadStates.Downloaded; playerUpdate = new Event(); playerUpdate.Type = Event.EventType.PlayerUpdated; playerUpdate.ChangedObject = Self; Send(new Packet(playerUpdate)); LoadedSong?.Invoke(matchMap); Logger.Debug($"SENT DOWNLOADED SIGNAL {(playerUpdate.ChangedObject as Player).DownloadState}"); } else { //Send updated download status (Self as Player).DownloadState = Player.DownloadStates.DownloadError; playerUpdate = new Event(); playerUpdate.Type = Event.EventType.PlayerUpdated; playerUpdate.ChangedObject = Self; Send(new Packet(playerUpdate)); } } ); } }
private void Client_PacketRecieved(Packet packet) { if (packet.Type == PacketType.PlaySong) { PlaySong playSong = packet.SpecificPacket as PlaySong; var desiredLevel = Plugin.masterLevelList.First(x => x.levelID == playSong.levelId); var desiredCharacteristic = desiredLevel.beatmapCharacteristics.First(x => x.serializedName == playSong.characteristic.SerializedName); var desiredDifficulty = (BeatmapDifficulty)playSong.difficulty; var playerSpecificSettings = new PlayerSpecificSettings(); playerSpecificSettings.advancedHud = playSong.playerSettings.advancedHud; playerSpecificSettings.leftHanded = playSong.playerSettings.leftHanded; playerSpecificSettings.noTextsAndHuds = playSong.playerSettings.noTextsAndHuds; playerSpecificSettings.reduceDebris = playSong.playerSettings.reduceDebris; playerSpecificSettings.staticLights = playSong.playerSettings.staticLights; var gameplayModifiers = new GameplayModifiers(); gameplayModifiers.batteryEnergy = playSong.gameplayModifiers.batteryEnergy; gameplayModifiers.disappearingArrows = playSong.gameplayModifiers.disappearingArrows; gameplayModifiers.failOnSaberClash = playSong.gameplayModifiers.failOnSaberClash; gameplayModifiers.fastNotes = playSong.gameplayModifiers.fastNotes; gameplayModifiers.ghostNotes = playSong.gameplayModifiers.ghostNotes; gameplayModifiers.instaFail = playSong.gameplayModifiers.instaFail; gameplayModifiers.noBombs = playSong.gameplayModifiers.noBombs; gameplayModifiers.noFail = playSong.gameplayModifiers.noFail; gameplayModifiers.noObstacles = playSong.gameplayModifiers.noObstacles; gameplayModifiers.songSpeed = (GameplayModifiers.SongSpeed)playSong.gameplayModifiers.songSpeed; SaberUtilities.PlaySong(desiredLevel, desiredCharacteristic, desiredDifficulty, gameplayModifiers, playerSpecificSettings); } else if (packet.Type == PacketType.LoadSong) { LoadSong loadSong = packet.SpecificPacket as LoadSong; Action <IBeatmapLevel> SongLoaded = (loadedLevel) => { var loadedSong = new LoadedSong(); var beatmapLevel = new PreviewBeatmapLevel(); beatmapLevel.Characteristics = loadedLevel.beatmapCharacteristics.ToList().Select(x => { var characteristic = new Characteristic(); characteristic.SerializedName = x.serializedName; characteristic.difficulties = loadedLevel.beatmapLevelData.difficultyBeatmapSets .First(y => y.beatmapCharacteristic.serializedName == x.serializedName) .difficultyBeatmaps.Select(y => (Characteristic.BeatmapDifficulty)y.difficulty).ToArray(); return(characteristic); }).ToArray(); beatmapLevel.LevelId = loadedLevel.levelID; beatmapLevel.Name = loadedLevel.songName; beatmapLevel.Loaded = true; loadedSong.level = beatmapLevel; client.Send(new Packet(loadedSong).ToBytes()); }; LoadSong(loadSong.levelId, SongLoaded); } else if (packet.Type == PacketType.Command) { Command command = packet.SpecificPacket as Command; if (command.commandType == Command.CommandType.ReturnToMenu) { SaberUtilities.ReturnToMenu(); } } }