diff --git a/PartyModes/PartyModeChallenge/PartyModeChallenge.cs b/PartyModes/PartyModeChallenge/PartyModeChallenge.cs index 5903495d..2725a680 100644 --- a/PartyModes/PartyModeChallenge/PartyModeChallenge.cs +++ b/PartyModes/PartyModeChallenge/PartyModeChallenge.cs @@ -1,11 +1,15 @@ using System; using System.Collections.Generic; +using System.Runtime.InteropServices; using VocaluxeLib.Menu; -[assembly: System.Runtime.InteropServices.ComVisible(false)] +[assembly: ComVisible(false)] + namespace VocaluxeLib.PartyModes.Challenge { + #region Communication + #region ToScreen public struct DataToScreenConfig { @@ -51,9 +55,7 @@ namespace VocaluxeLib.PartyModes.Challenge { res = row.NumSingPoints.CompareTo(NumSingPoints); if (res == 0) - { res = row.NumWon.CompareTo(NumWon); - } } return res; } @@ -61,7 +63,6 @@ namespace VocaluxeLib.PartyModes.Challenge throw new ArgumentException("object is not a ResultTableRow"); } } - #endregion ToScreen #region FromScreen @@ -92,6 +93,7 @@ namespace VocaluxeLib.PartyModes.Challenge public bool FadeToNameSelection; } #endregion FromScreen + #endregion Communication public sealed class PartyModeChallenge : CPartyMode @@ -102,7 +104,7 @@ namespace VocaluxeLib.PartyModes.Challenge private const int MinTeams = 0; private const int MaxNumRounds = 100; - enum EStage + private enum EStage { NotStarted, Config, @@ -111,7 +113,7 @@ namespace VocaluxeLib.PartyModes.Challenge Singing } - struct Data + private struct Data { public int NumPlayer; public int NumPlayerAtOnce; @@ -127,7 +129,7 @@ namespace VocaluxeLib.PartyModes.Challenge public int[] CatSongIndices; } - struct Stats + private struct Stats { public int ProfileID; public int SingPoints; @@ -147,13 +149,13 @@ namespace VocaluxeLib.PartyModes.Challenge _ScreenSongOptions.Selection.RandomOnly = false; _ScreenSongOptions.Selection.PartyMode = true; _ScreenSongOptions.Selection.CategoryChangeAllowed = true; - _ScreenSongOptions.Selection.NumJokers = new int[] { 5, 5 }; - _ScreenSongOptions.Selection.TeamNames = new string[] { "foo", "bar" }; + _ScreenSongOptions.Selection.NumJokers = new[] {5, 5}; + _ScreenSongOptions.Selection.TeamNames = new[] {"foo", "bar"}; _ScreenSongOptions.Sorting.SearchString = String.Empty; _ScreenSongOptions.Sorting.SearchActive = false; _ScreenSongOptions.Sorting.DuetOptions = EDuetOptions.NoDuets; - + _Stage = EStage.NotStarted; ToScreenConfig = new DataToScreenConfig(); @@ -194,7 +196,7 @@ namespace VocaluxeLib.PartyModes.Challenge switch (ScreenName) { case "PartyScreenChallengeConfig": - + try { data = (DataFromScreen)Data; @@ -327,7 +329,7 @@ namespace VocaluxeLib.PartyModes.Challenge } break; } - + return Screen; } @@ -438,7 +440,6 @@ namespace VocaluxeLib.PartyModes.Challenge public override void SongSelected(int SongID) { - EGameMode gm = EGameMode.TR_GAMEMODE_NORMAL; CBase.Game.Reset(); @@ -500,30 +501,30 @@ namespace VocaluxeLib.PartyModes.Challenge switch (GameData.NumPlayerAtOnce) { case 1: - _ScreenSongOptions.Selection.NumJokers = new int[] { 10 }; + _ScreenSongOptions.Selection.NumJokers = new[] {10}; break; case 2: - _ScreenSongOptions.Selection.NumJokers = new int[] { 5, 5 }; + _ScreenSongOptions.Selection.NumJokers = new[] {5, 5}; break; case 3: - _ScreenSongOptions.Selection.NumJokers = new int[] { 4, 4, 4 }; + _ScreenSongOptions.Selection.NumJokers = new[] {4, 4, 4}; break; case 4: - _ScreenSongOptions.Selection.NumJokers = new int[] { 3, 3, 3, 3 }; + _ScreenSongOptions.Selection.NumJokers = new[] {3, 3, 3, 3}; break; case 5: - _ScreenSongOptions.Selection.NumJokers = new int[] { 2, 2, 2, 2, 2 }; + _ScreenSongOptions.Selection.NumJokers = new[] {2, 2, 2, 2, 2}; break; case 6: - _ScreenSongOptions.Selection.NumJokers = new int[] { 2, 2, 2, 2, 2, 2 }; + _ScreenSongOptions.Selection.NumJokers = new[] {2, 2, 2, 2, 2, 2}; break; default: - _ScreenSongOptions.Selection.NumJokers = new int[] { 5, 5 }; + _ScreenSongOptions.Selection.NumJokers = new[] {5, 5}; break; } } @@ -534,16 +535,16 @@ namespace VocaluxeLib.PartyModes.Challenge if (profiles == null) { - _ScreenSongOptions.Selection.TeamNames = new string[] { "foo", "bar" }; + _ScreenSongOptions.Selection.TeamNames = new[] {"foo", "bar"}; return; } if (GameData.NumPlayerAtOnce < 1 || GameData.ProfileIDs.Count < GameData.NumPlayerAtOnce || profiles.Length < GameData.NumPlayerAtOnce) { - _ScreenSongOptions.Selection.TeamNames = new string[] { "foo", "bar" }; + _ScreenSongOptions.Selection.TeamNames = new[] {"foo", "bar"}; return; } - + _ScreenSongOptions.Selection.TeamNames = new string[GameData.NumPlayerAtOnce]; Combination c = GameData.Rounds.GetRound(GameData.CurrentRoundNr - 1); @@ -577,13 +578,11 @@ namespace VocaluxeLib.PartyModes.Challenge GameData.ResultTable.Add(row); } - GameData.Results = new int[GameData.NumRounds, GameData.NumPlayerAtOnce]; + GameData.Results = new int[GameData.NumRounds,GameData.NumPlayerAtOnce]; for (int i = 0; i < GameData.NumRounds; i++) { for (int j = 0; j < GameData.NumPlayerAtOnce; j++) - { GameData.Results[i, j] = 0; - } } } else @@ -596,9 +595,7 @@ namespace VocaluxeLib.PartyModes.Challenge return; for (int j = 0; j < GameData.NumPlayerAtOnce; j++) - { GameData.Results[GameData.CurrentRoundNr - 2, j] = (int)Math.Round(results[j].Points); - } List points = GetPointsForPlayer(results); @@ -606,13 +603,13 @@ namespace VocaluxeLib.PartyModes.Challenge { int index = -1; for (int j = 0; j < GameData.ResultTable.Count; j++) - { + { if (points[i].ProfileID == GameData.ResultTable[j].PlayerID) { index = j; break; } - } + } if (index != -1) { @@ -635,7 +632,7 @@ namespace VocaluxeLib.PartyModes.Challenge int pos = 1; int lastPoints = 0; int lastSingPoints = 0; - for (int i = 0; i < GameData.ResultTable.Count; i++ ) + for (int i = 0; i < GameData.ResultTable.Count; i++) { if (lastPoints > GameData.ResultTable[i].NumGamePoints || lastSingPoints > GameData.ResultTable[i].NumSingPoints) pos++; @@ -648,7 +645,7 @@ namespace VocaluxeLib.PartyModes.Challenge private List GetPointsForPlayer(SPlayer[] Results) { List result = new List(); - for(int i = 0; i < GameData.NumPlayerAtOnce; i++) + for (int i = 0; i < GameData.NumPlayerAtOnce; i++) { Stats stat = new Stats(); stat.ProfileID = Results[i].ProfileID; @@ -695,7 +692,6 @@ namespace VocaluxeLib.PartyModes.Challenge } - return result; } @@ -705,11 +701,9 @@ namespace VocaluxeLib.PartyModes.Challenge { GameData.CatSongIndices = new int[CBase.Songs.GetNumCategories()]; for (int i = 0; i < GameData.CatSongIndices.Length; i++) - { GameData.CatSongIndices[i] = -1; - } } - + if (CBase.Songs.GetNumCategories() == 0 || _ScreenSongOptions.Sorting.Tabs == EOffOn.TR_CONFIG_OFF) GameData.CatSongIndices = null; } diff --git a/Vocaluxe/Base/CBackgroundMusic.cs b/Vocaluxe/Base/CBackgroundMusic.cs index c397db2e..0b868ee5 100644 --- a/Vocaluxe/Base/CBackgroundMusic.cs +++ b/Vocaluxe/Base/CBackgroundMusic.cs @@ -11,19 +11,19 @@ namespace Vocaluxe.Base static class CBackgroundMusic { private static int _CurrentMusicStream = -1; - private static int _PreviousMusicIndex = 0; + private static int _PreviousMusicIndex; private static PlaylistElement _CurrentPlaylistElement = new PlaylistElement(); - private static List _AllFileNames = new List(); - private static List _NotPlayedFileNames = new List(); - private static List _BGMusicFileNames = new List(); - private static List _PreviousFileNames = new List(); + private static readonly List _AllFileNames = new List(); + private static readonly List _NotPlayedFileNames = new List(); + private static readonly List _BGMusicFileNames = new List(); + private static readonly List _PreviousFileNames = new List(); private static int _Video = -1; private static STexture _CurrentVideoTexture = new STexture(-1); - private static Stopwatch _FadeTimer = new Stopwatch(); + private static readonly Stopwatch _FadeTimer = new Stopwatch(); private static bool _VideoEnabled; - + private static bool _OwnMusicAdded; private static bool _BackgroundMusicAdded; private static bool _Playing; @@ -33,17 +33,14 @@ namespace Vocaluxe.Base public static bool VideoEnabled { - get - { - return _VideoEnabled; - } + get { return _VideoEnabled; } set { if (_VideoEnabled && value) return; if (!_VideoEnabled && !value) return; - if(_VideoEnabled && !value) + if (_VideoEnabled && !value) ToggleVideo(); if (!_VideoEnabled && value) ToggleVideo(); @@ -53,23 +50,13 @@ namespace Vocaluxe.Base public static bool CanSing { - get - { - return _CanSing; - } - - set - { - _CanSing = value; - } + get { return _CanSing; } + set { _CanSing = value; } } public static bool Disabled { - get - { - return _Disabled; - } + get { return _Disabled; } set { _Disabled = value; @@ -82,46 +69,28 @@ namespace Vocaluxe.Base public static bool RepeatSong { - get - { - return _RepeatSong; - } - set - { - _RepeatSong = value; - } + get { return _RepeatSong; } + set { _RepeatSong = value; } } public static int SongID { - get - { - return _CurrentPlaylistElement.SongID; - } + get { return _CurrentPlaylistElement.SongID; } } public static bool Duet { - get - { - return _CurrentPlaylistElement.Duet; - } + get { return _CurrentPlaylistElement.Duet; } } public static bool SongHasVideo { - get - { - return File.Exists(_CurrentPlaylistElement.VideoFilePath); - } + get { return File.Exists(_CurrentPlaylistElement.VideoFilePath); } } public static bool Playing { - get - { - return _Playing; - } + get { return _Playing; } } public static string ArtistAndTitle @@ -137,27 +106,20 @@ namespace Vocaluxe.Base public static STexture Cover { - get - { - return _CurrentPlaylistElement.Cover; - } + get { return _CurrentPlaylistElement.Cover; } } public static void Init() { List templist = new List(); - foreach(string ending in CSettings.MusicFileTypes) - { + foreach (string ending in CSettings.MusicFileTypes) templist.AddRange(CHelper.ListFiles(CSettings.sFolderBackgroundMusic, ending, true, true)); - } foreach (string path in templist) - { _BGMusicFileNames.Add(new PlaylistElement(path)); - } - if(CConfig.BackgroundMusicSource != EBackgroundMusicSource.TR_CONFIG_ONLY_OWN_MUSIC) + if (CConfig.BackgroundMusicSource != EBackgroundMusicSource.TR_CONFIG_ONLY_OWN_MUSIC) AddBackgroundMusic(); if (CConfig.VideoBackgrounds == EOffOn.TR_CONFIG_ON) _VideoEnabled = true; @@ -230,7 +192,7 @@ namespace Vocaluxe.Base if (_AllFileNames.Count > 0 && _CurrentMusicStream != -1) { float timeToPlay; - if(_CurrentPlaylistElement.Finish == 0f) //No End-Tag defined + if (_CurrentPlaylistElement.Finish == 0f) //No End-Tag defined timeToPlay = CSound.GetLength(_CurrentMusicStream) - CSound.GetPosition(_CurrentMusicStream); else //End-Tag found timeToPlay = _CurrentPlaylistElement.Finish - CSound.GetPosition(_CurrentMusicStream); @@ -246,10 +208,12 @@ namespace Vocaluxe.Base else CSound.SetPosition(_CurrentMusicStream, 0); if (_VideoEnabled && _Video != -1) + { if (_CurrentPlaylistElement.Start != 0f && CConfig.BackgroundMusicUseStart == EOffOn.TR_CONFIG_ON) CVideo.VdSkip(_Video, _CurrentPlaylistElement.Start, _CurrentPlaylistElement.VideoGap); else CVideo.VdSkip(_Video, 0f, _CurrentPlaylistElement.VideoGap); + } } else Next(); @@ -273,7 +237,7 @@ namespace Vocaluxe.Base _PreviousFileNames.Add(_CurrentPlaylistElement); _PreviousMusicIndex = _PreviousFileNames.Count - 1; } - else if(_PreviousFileNames.Count > 0) //We are in the previous list + else if (_PreviousFileNames.Count > 0) //We are in the previous list { Stop(); _PreviousMusicIndex++; @@ -309,10 +273,12 @@ namespace Vocaluxe.Base else CSound.SetPosition(_CurrentMusicStream, 0); if (_VideoEnabled && _Video != -1) + { if (_CurrentPlaylistElement.Start != 0f && CConfig.BackgroundMusicUseStart == EOffOn.TR_CONFIG_ON) CVideo.VdSkip(_Video, _CurrentPlaylistElement.Start, _CurrentPlaylistElement.VideoGap); else CVideo.VdSkip(_Video, 0f, _CurrentPlaylistElement.VideoGap); + } } else { @@ -339,16 +305,18 @@ namespace Vocaluxe.Base else CSound.SetPosition(_CurrentMusicStream, 0); if (_VideoEnabled && _Video != -1) + { if (_CurrentPlaylistElement.Start != 0f && CConfig.BackgroundMusicUseStart == EOffOn.TR_CONFIG_ON) CVideo.VdSkip(_Video, _CurrentPlaylistElement.Start, _CurrentPlaylistElement.VideoGap); else CVideo.VdSkip(_Video, 0f, _CurrentPlaylistElement.VideoGap); + } } } public static void ApplyVolume() { - CSound.SetStreamVolumeMax(_CurrentMusicStream, CConfig.BackgroundMusicVolume); + CSound.SetStreamVolumeMax(_CurrentMusicStream, CConfig.BackgroundMusicVolume); } public static void AddOwnMusic() @@ -485,9 +453,7 @@ namespace Vocaluxe.Base float vtime = 0f; CVideo.VdGetFrame(_Video, ref _CurrentVideoTexture, CSound.GetPosition(_CurrentMusicStream), ref vtime); if (_FadeTimer.ElapsedMilliseconds <= 3000L) - { _CurrentVideoTexture.color.A = (_FadeTimer.ElapsedMilliseconds / 3000f); - } else { _CurrentVideoTexture.color.A = 1f; @@ -527,9 +493,9 @@ namespace Vocaluxe.Base class PlaylistElement { - private CSong _Song = null; + private readonly CSong _Song; - private int _SongID; + private readonly int _SongID; public int SongID { get { return _SongID; } @@ -543,14 +509,11 @@ class PlaylistElement { if (_Song != null) return _Song.GetMP3(); - + return _MusicFilePath; } - set - { - _MusicFilePath = value; - } + set { _MusicFilePath = value; } } public string VideoFilePath @@ -559,7 +522,7 @@ class PlaylistElement { if (_Song != null) return _Song.GetVideo(); - + return string.Empty; } } @@ -570,7 +533,7 @@ class PlaylistElement { if (_Song != null) return _Song.Title; - + return ""; } } @@ -581,7 +544,7 @@ class PlaylistElement { if (_Song != null) return _Song.Artist; - + return ""; } } @@ -614,7 +577,7 @@ class PlaylistElement { if (_Song != null) return _Song.CoverTextureSmall; - + return CCover.NoCover; } } @@ -625,7 +588,7 @@ class PlaylistElement { if (_Song != null) return _Song.VideoGap; - + return 0; } } @@ -636,7 +599,7 @@ class PlaylistElement { if (_Song != null) return _Song.IsDuet; - + return false; } } @@ -660,4 +623,4 @@ class PlaylistElement MusicFilePath = string.Empty; _SongID = -1; } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CConfig.cs b/Vocaluxe/Base/CConfig.cs index 1823555f..6bfffb82 100644 --- a/Vocaluxe/Base/CConfig.cs +++ b/Vocaluxe/Base/CConfig.cs @@ -5,8 +5,6 @@ using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; using System.Xml; - - using Vocaluxe.Lib.Sound; using Vocaluxe.Lib.Webcam; using VocaluxeLib.Menu; @@ -15,11 +13,11 @@ namespace Vocaluxe.Base { static class CConfig { - private static XmlWriterSettings _settings = new XmlWriterSettings(); - + private static readonly XmlWriterSettings _settings = new XmlWriterSettings(); + // Debug public static EDebugLevel DebugLevel = EDebugLevel.TR_CONFIG_OFF; - + // Graphics #if WIN public static ERenderer Renderer = ERenderer.TR_CONFIG_DIRECT3D; @@ -80,7 +78,7 @@ namespace Vocaluxe.Base public static string[] Players = new string[CSettings.MaxNumPlayer]; public static float MinLineBreakTime = 0.1f; //Minimum time to show the text before it is (to be) sung (if possible) - + // Video public static EVideoDecoder VideoDecoder = EVideoDecoder.FFmpeg; public static EOffOn VideoBackgrounds = EOffOn.TR_CONFIG_ON; @@ -90,16 +88,16 @@ namespace Vocaluxe.Base // Record public static SMicConfig[] MicConfig; - public static int MicDelay = 300; //[ms] + public static int MicDelay = 300; //[ms] public static EWebcamLib WebcamLib = EWebcamLib.OpenCV; public static SWebcamConfig WebcamConfig; //Lists to save parameters and values - private static List _Params = new List(); - private static List _Values = new List(); + private static readonly List _Params = new List(); + private static readonly List _Values = new List(); //Variables to save old values for commandline-parameters - private static List SongFolderOld = new List(); + private static readonly List SongFolderOld = new List(); public static void Init() { @@ -112,9 +110,9 @@ namespace Vocaluxe.Base MicConfig = new SMicConfig[CSettings.MaxNumPlayer]; // Init config file - if (!File.Exists(CSettings.sFileConfig)) + if (!File.Exists(CSettings.sFileConfig)) SaveConfig(); - + LoadConfig(); } @@ -127,21 +125,21 @@ namespace Vocaluxe.Base string value = string.Empty; #region Debug - xmlReader.TryGetEnumValue("//root/Debug/DebugLevel", ref DebugLevel); + xmlReader.TryGetEnumValue("//root/Debug/DebugLevel", ref DebugLevel); #endregion Debug #region Graphics - xmlReader.TryGetEnumValue("//root/Graphics/Renderer", ref Renderer); - xmlReader.TryGetEnumValue("//root/Graphics/TextureQuality", ref TextureQuality); + xmlReader.TryGetEnumValue("//root/Graphics/Renderer", ref Renderer); + xmlReader.TryGetEnumValue("//root/Graphics/TextureQuality", ref TextureQuality); xmlReader.TryGetIntValueRange("//root/Graphics/CoverSize", ref CoverSize, 32, 1024); xmlReader.TryGetIntValue("//root/Graphics/ScreenW", ref ScreenW); xmlReader.TryGetIntValue("//root/Graphics/ScreenH", ref ScreenH); - xmlReader.TryGetEnumValue("//root/Graphics/AAMode", ref AAMode); - xmlReader.TryGetEnumValue("//root/Graphics/Colors", ref Colors); + xmlReader.TryGetEnumValue("//root/Graphics/AAMode", ref AAMode); + xmlReader.TryGetEnumValue("//root/Graphics/Colors", ref Colors); xmlReader.TryGetFloatValue("//root/Graphics/MaxFPS", ref MaxFPS); - xmlReader.TryGetEnumValue("//root/Graphics/VSync", ref VSync); - xmlReader.TryGetEnumValue("//root/Graphics/FullScreen", ref FullScreen); + xmlReader.TryGetEnumValue("//root/Graphics/VSync", ref VSync); + xmlReader.TryGetEnumValue("//root/Graphics/FullScreen", ref FullScreen); xmlReader.TryGetFloatValue("//root/Graphics/FadeTime", ref FadeTime); #endregion Graphics @@ -159,16 +157,16 @@ namespace Vocaluxe.Base #endregion Theme #region Sound - xmlReader.TryGetEnumValue("//root/Sound/PlayBackLib", ref PlayBackLib); - xmlReader.TryGetEnumValue("//root/Sound/RecordLib", ref RecordLib); - xmlReader.TryGetEnumValue("//root/Sound/AudioBufferSize", ref AudioBufferSize); + xmlReader.TryGetEnumValue("//root/Sound/PlayBackLib", ref PlayBackLib); + xmlReader.TryGetEnumValue("//root/Sound/RecordLib", ref RecordLib); + xmlReader.TryGetEnumValue("//root/Sound/AudioBufferSize", ref AudioBufferSize); xmlReader.TryGetIntValueRange("//root/Sound/AudioLatency", ref AudioLatency, -500, 500); xmlReader.TryGetEnumValue("//root/Sound/BackgroundMusic", ref BackgroundMusic); xmlReader.TryGetIntValueRange("//root/Sound/BackgroundMusicVolume", ref BackgroundMusicVolume); xmlReader.TryGetEnumValue("//root/Sound/BackgroundMusicSource", ref BackgroundMusicSource); - xmlReader.TryGetEnumValue("//root/Sound/BackgroundMusicUseStart", ref BackgroundMusicUseStart); + xmlReader.TryGetEnumValue("//root/Sound/BackgroundMusicUseStart", ref BackgroundMusicUseStart); xmlReader.TryGetIntValueRange("//root/Sound/PreviewMusicVolume", ref PreviewMusicVolume); xmlReader.TryGetIntValueRange("//root/Sound/GameMusicVolume", ref GameMusicVolume); #endregion Sound @@ -187,21 +185,19 @@ namespace Vocaluxe.Base i++; } - xmlReader.TryGetEnumValue("//root/Game/SongMenu", ref SongMenu); - xmlReader.TryGetEnumValue("//root/Game/SongSorting", ref SongSorting); - xmlReader.TryGetEnumValue("//root/Game/IgnoreArticles", ref IgnoreArticles); + xmlReader.TryGetEnumValue("//root/Game/SongMenu", ref SongMenu); + xmlReader.TryGetEnumValue("//root/Game/SongSorting", ref SongSorting); + xmlReader.TryGetEnumValue("//root/Game/IgnoreArticles", ref IgnoreArticles); xmlReader.TryGetFloatValue("//root/Game/ScoreAnimationTime", ref ScoreAnimationTime); - xmlReader.TryGetEnumValue("//root/Game/TimerMode", ref TimerMode); + xmlReader.TryGetEnumValue("//root/Game/TimerMode", ref TimerMode); xmlReader.TryGetIntValue("//root/Game/NumPlayer", ref NumPlayer); xmlReader.TryGetEnumValue("//root/Game/Tabs", ref Tabs); xmlReader.GetValue("//root/Game/Language", ref Language, Language); - xmlReader.TryGetEnumValue("//root/Game/LyricsOnTop", ref LyricsOnTop); + xmlReader.TryGetEnumValue("//root/Game/LyricsOnTop", ref LyricsOnTop); xmlReader.TryGetFloatValue("//root/Game/MinLineBreakTime", ref MinLineBreakTime); if ((ScoreAnimationTime > 0 && ScoreAnimationTime < 1) || ScoreAnimationTime < 0) - { ScoreAnimationTime = 1; - } if (MinLineBreakTime < 0) MinLineBreakTime = 0.1f; @@ -212,27 +208,22 @@ namespace Vocaluxe.Base bool _LangExists = CLanguage.SetLanguage(Language); //TODO: What should we do, if English not exists? - if(_LangExists == false){ + if (_LangExists == false) Language = "English"; - - } - + //Read players from config for (i = 1; i <= CSettings.MaxNumPlayer; i++) - { xmlReader.GetValue("//root/Game/Players/Player" + i.ToString(), ref Players[i - 1], string.Empty); - } - #endregion Game #region Video - xmlReader.TryGetEnumValue("//root/Video/VideoDecoder", ref VideoDecoder); - xmlReader.TryGetEnumValue("//root/Video/VideoBackgrounds", ref VideoBackgrounds); - xmlReader.TryGetEnumValue("//root/Video/VideoPreview", ref VideoPreview); - xmlReader.TryGetEnumValue("//root/Video/VideosInSongs", ref VideosInSongs); - xmlReader.TryGetEnumValue("//root/Video/VideosToBackground", ref VideosToBackground); + xmlReader.TryGetEnumValue("//root/Video/VideoDecoder", ref VideoDecoder); + xmlReader.TryGetEnumValue("//root/Video/VideoBackgrounds", ref VideoBackgrounds); + xmlReader.TryGetEnumValue("//root/Video/VideoPreview", ref VideoPreview); + xmlReader.TryGetEnumValue("//root/Video/VideosInSongs", ref VideosInSongs); + xmlReader.TryGetEnumValue("//root/Video/VideosToBackground", ref VideosToBackground); - xmlReader.TryGetEnumValue("//root/Video/WebcamLib", ref WebcamLib); + xmlReader.TryGetEnumValue("//root/Video/WebcamLib", ref WebcamLib); WebcamConfig = new SWebcamConfig(); xmlReader.GetValue("//root/Video/WebcamConfig/MonikerString", ref WebcamConfig.MonikerString, String.Empty); xmlReader.TryGetIntValue("//root/Video/WebcamConfig/Framerate", ref WebcamConfig.Framerate); @@ -261,7 +252,6 @@ namespace Vocaluxe.Base public static bool SaveConfig() { - XmlWriter writer = null; try { @@ -273,15 +263,15 @@ namespace Vocaluxe.Base writer.WriteStartElement("Info"); writer.WriteElementString("Version", CSettings.GetFullVersionText()); - writer.WriteElementString("Time", System.DateTime.Now.ToString()); - writer.WriteElementString("Platform", System.Environment.OSVersion.Platform.ToString()); - writer.WriteElementString("OSVersion", System.Environment.OSVersion.ToString()); - writer.WriteElementString("ProcessorCount", System.Environment.ProcessorCount.ToString()); + writer.WriteElementString("Time", DateTime.Now.ToString()); + writer.WriteElementString("Platform", Environment.OSVersion.Platform.ToString()); + writer.WriteElementString("OSVersion", Environment.OSVersion.ToString()); + writer.WriteElementString("ProcessorCount", Environment.ProcessorCount.ToString()); writer.WriteElementString("Screens", Screen.AllScreens.Length.ToString()); writer.WriteElementString("PrimaryScreenResolution", Screen.PrimaryScreen.Bounds.Size.ToString()); - writer.WriteElementString("Directory", System.Environment.CurrentDirectory.ToString()); + writer.WriteElementString("Directory", Environment.CurrentDirectory); writer.WriteEndElement(); #endregion Info @@ -419,18 +409,14 @@ namespace Vocaluxe.Base //Write "old" song-folders to config. writer.WriteComment("SongFolder: SongFolder1, SongFolder2, SongFolder3, ..."); for (int i = 0; i < SongFolderOld.Count; i++) - { writer.WriteElementString("SongFolder" + (i + 1).ToString(), SongFolderOld[i]); - } } else { //Write "normal" song-folders to config. writer.WriteComment("SongFolder: SongFolder1, SongFolder2, SongFolder3, ..."); for (int i = 0; i < SongFolder.Count; i++) - { writer.WriteElementString("SongFolder" + (i + 1).ToString(), SongFolder[i]); - } } writer.WriteComment("SongMenu: " + CHelper.ListStrings(Enum.GetNames(typeof(ESongMenu)))); @@ -463,9 +449,7 @@ namespace Vocaluxe.Base writer.WriteComment("Default profile for players 1..." + CSettings.MaxNumPlayer.ToString() + ":"); writer.WriteStartElement("Players"); for (int i = 1; i <= CSettings.MaxNumPlayer; i++) - { writer.WriteElementString("Player" + i.ToString(), Path.GetFileName(Players[i - 1])); - } writer.WriteEndElement(); writer.WriteEndElement(); @@ -543,77 +527,73 @@ namespace Vocaluxe.Base } return true; } - - /// - /// Calculates the maximum cycle time to reach the MaxFPS value. - /// + + /// + /// Calculates the maximum cycle time to reach the MaxFPS value. + /// public static float CalcCycleTime() { - return (1f / MaxFPS)*1000f; + return (1f / MaxFPS) * 1000f; } /// - /// Checks, if there is a mic-configuration + /// Checks, if there is a mic-configuration /// /// public static bool IsMicConfig() { SRecordDevice[] Devices = CSound.RecordGetDevices(); - if (Devices == null) - return false; - + if (Devices == null) + return false; + for (int dev = 0; dev < Devices.Length; dev++) { for (int inp = 0; inp < Devices[dev].Inputs.Count; inp++) { if (Devices[dev].Inputs[inp].PlayerChannel1 != 0 || Devices[dev].Inputs[inp].PlayerChannel2 != 0) - { return true; - } } - } + } return false; } /// - /// Checks, if there is a mic-configuration + /// Checks, if there is a mic-configuration /// /// Player-Number /// public static bool IsMicConfig(int player) { SRecordDevice[] Devices = CSound.RecordGetDevices(); - if (Devices == null) - return false; - - if (Devices != null) - { - for (int dev = 0; dev < Devices.Length; dev++) - { - for (int inp = 0; inp < Devices[dev].Inputs.Count; inp++) - { - if (Devices[dev].Inputs[inp].PlayerChannel1 == player || Devices[dev].Inputs[inp].PlayerChannel2 == player) - { - return true; - } - } - } - return false; - } + if (Devices == null) + return false; + + if (Devices != null) + { + for (int dev = 0; dev < Devices.Length; dev++) + { + for (int inp = 0; inp < Devices[dev].Inputs.Count; inp++) + { + if (Devices[dev].Inputs[inp].PlayerChannel1 == player || Devices[dev].Inputs[inp].PlayerChannel2 == player) + return true; + } + } + return false; + } return false; } /// - /// Try to assign automatically player 1 and 2 to usb-mics. + /// Try to assign automatically player 1 and 2 to usb-mics. /// public static bool AutoAssignMics() { //Look for (usb-)mic //SRecordDevice[] Devices = new SRecordDevice[CSound.RecordGetDevices().Length]; SRecordDevice[] Devices = CSound.RecordGetDevices(); - if (Devices == null) - return false; - + if (Devices == null) + return false; + for (int dev = 0; dev < Devices.Length; dev++) { //Has Device some signal-names in name -> This could be a (usb-)mic @@ -678,7 +658,7 @@ namespace Vocaluxe.Base } /// - /// Load command-line-parameters and their values to lists. + /// Load command-line-parameters and their values to lists. /// /// Parameters public static void LoadCommandLineParams(string[] args) @@ -688,9 +668,7 @@ namespace Vocaluxe.Base //Complete argument string string arguments = string.Empty; foreach (string arg in args) - { arguments += arg + " "; - } args = SpliterParam.Split(arguments); @@ -706,8 +684,7 @@ namespace Vocaluxe.Base switch (parts.Length) { - - //Only found a parameter + //Only found a parameter case 1: if (!Regex.IsMatch(parts[0], @"\s") && parts[0].Length > 0) { @@ -719,8 +696,8 @@ namespace Vocaluxe.Base } break; - - //Found parameter and value + + //Found parameter and value case 2: if (!Regex.IsMatch(parts[0], @"\s") && parts[0].Length > 0) { @@ -736,10 +713,10 @@ namespace Vocaluxe.Base } /// - /// Apply command-line-parameters (before reading config.xml) + /// Apply command-line-parameters (before reading config.xml) /// - public static void UseCommandLineParamsBefore(){ - + public static void UseCommandLineParamsBefore() + { //Check each parameter for (int i = 0; i < _Params.Count; i++) { @@ -755,17 +732,13 @@ namespace Vocaluxe.Base case "configfile": //Check if value is valid if (CheckFile(value)) - { CSettings.sFileConfig = value; - } break; case "scorefile": //Check if value is valid if (CheckFile(value)) - { CSettings.sFileHighscoreDB = value; - } break; case "playlistfolder": @@ -782,11 +755,10 @@ namespace Vocaluxe.Base } /// - /// Apply command-line-parameters (after reading config.xml) + /// Apply command-line-parameters (after reading config.xml) /// public static void UseCommandLineParamsAfter() { - //Check each parameter for (int i = 0; i < _Params.Count; i++) { @@ -817,27 +789,23 @@ namespace Vocaluxe.Base private static bool CheckFile(string value) { - char [] chars = Path.GetInvalidPathChars(); - for(int i=0; i - /// Use saved players from config now for games + /// Use saved players from config now for games /// - public static void UsePlayers() + public static void UsePlayers() { for (int i = 0; i < CProfiles.Profiles.Length; i++) { @@ -854,11 +822,9 @@ namespace Vocaluxe.Base } } else - { CGame.Player[j].ProfileID = -1; - } } } } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CCover.cs b/Vocaluxe/Base/CCover.cs index 4316a6ef..52c34c19 100644 --- a/Vocaluxe/Base/CCover.cs +++ b/Vocaluxe/Base/CCover.cs @@ -23,12 +23,12 @@ namespace Vocaluxe.Base abstract class CCover { - private static XmlWriterSettings _settings = new XmlWriterSettings(); - private static List _Cover = new List(); - private static List _CoverThemes = new List(); + private static readonly XmlWriterSettings _settings = new XmlWriterSettings(); + private static readonly List _Cover = new List(); + private static readonly List _CoverThemes = new List(); private static STexture _NoCover = new STexture(-1); - private static Object _MutexCover = new Object(); + private static readonly Object _MutexCover = new Object(); public static STexture NoCover { @@ -46,7 +46,7 @@ namespace Vocaluxe.Base } /// - /// Returns an array of CoverThemes-Names + /// Returns an array of CoverThemes-Names /// public static string[] CoverThemes { @@ -54,16 +54,14 @@ namespace Vocaluxe.Base { List CoverThemes = new List(); for (int i = 0; i < _CoverThemes.Count; i++) - { CoverThemes.Add(_CoverThemes[i].Name); - } return CoverThemes.ToArray(); } } /// - /// Returns the current cover theme index + /// Returns the current cover theme index /// /// public static int GetCoverThemeIndex() @@ -71,16 +69,14 @@ namespace Vocaluxe.Base for (int i = 0; i < _CoverThemes.Count; i++) { if (_CoverThemes[i].Name == CConfig.CoverTheme) - { return i; - } } return -1; } - /// - /// Returns a STexture for a given cover name. Returns "NoCover" if the cover does not exist. - /// + /// + /// Returns a STexture for a given cover name. Returns "NoCover" if the cover does not exist. + /// public static STexture Cover(string Name) { STexture cov = _NoCover; @@ -99,7 +95,7 @@ namespace Vocaluxe.Base } /// - /// Returns true if a cover with the given name exists. + /// Returns true if a cover with the given name exists. /// public static bool CoverExists(string Name) { @@ -109,16 +105,14 @@ namespace Vocaluxe.Base foreach (SCover cover in _Cover) { if (cover.Name == Name) - { return true; - } } } return false; } /// - /// Reloads cover to use a new cover-theme + /// Reloads cover to use a new cover-theme /// public static void ReloadCover() { @@ -132,7 +126,7 @@ namespace Vocaluxe.Base } /// - /// Returns a SCoverTheme by cover-theme-name + /// Returns a SCoverTheme by cover-theme-name /// private static SCoverTheme CoverTheme(string coverThemeName) { @@ -149,7 +143,7 @@ namespace Vocaluxe.Base } /// - /// Loads all cover-themes to list. + /// Loads all cover-themes to list. /// private static void LoadCoverThemes() { @@ -178,10 +172,10 @@ namespace Vocaluxe.Base } } } - - /// - /// Loads all cover which are defined in the cover config file. - /// + + /// + /// Loads all cover which are defined in the cover config file. + /// private static void LoadCover(string coverThemeName) { SCoverTheme coverTheme = new SCoverTheme(); @@ -190,7 +184,6 @@ namespace Vocaluxe.Base if (coverTheme.Name.Length > 0) { - CXMLReader xmlReader = CXMLReader.OpenFile((Path.Combine(CSettings.sFolderCover, coverTheme.File))); if (xmlReader != null) @@ -207,22 +200,16 @@ namespace Vocaluxe.Base xmlReader.GetValue("//root/Cover/" + cover[i] + "/Name", ref name, String.Empty); xmlReader.GetValue("//root/Cover/" + cover[i] + "/Path", ref value, String.Empty); sk.Name = name; - sk.Value = Path.Combine(coverTheme.Folder,value); + sk.Value = Path.Combine(coverTheme.Folder, value); if (File.Exists(Path.Combine(CSettings.sFolderCover, Path.Combine(coverTheme.Folder, value)))) - { sk.Texture = CDraw.AddTexture(Path.Combine(CSettings.sFolderCover, Path.Combine(coverTheme.Folder, value))); - } else - { sk.Texture = _NoCover; - } _Cover.Add(sk); if (sk.Name == "NoCover") - { _NoCover = sk.Texture; - } } } } @@ -246,7 +233,7 @@ namespace Vocaluxe.Base string value = String.Empty; sk.Name = name; - sk.Value = Path.Combine(coverTheme.Folder,Path.GetFileName(file)); + sk.Value = Path.Combine(coverTheme.Folder, Path.GetFileName(file)); sk.Texture = CDraw.AddTexture(Path.Combine(CSettings.sFolderCover, sk.Value)); @@ -256,4 +243,4 @@ namespace Vocaluxe.Base } } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CDraw.cs b/Vocaluxe/Base/CDraw.cs index fc68852a..46dac4cd 100644 --- a/Vocaluxe/Base/CDraw.cs +++ b/Vocaluxe/Base/CDraw.cs @@ -1,7 +1,7 @@ using System; using System.Drawing; +using System.IO; using System.Windows.Forms; - using Vocaluxe.Lib.Draw; using VocaluxeLib.Menu; @@ -9,8 +9,8 @@ namespace Vocaluxe.Base { static class CDraw { - private static IDraw _Draw = null; - + private static IDraw _Draw; + public static void InitDraw() { switch (CConfig.Renderer) @@ -27,9 +27,9 @@ namespace Vocaluxe.Base catch (Exception e) { MessageBox.Show(e.Message + " - Error in initializing of OpenGL. Please check whether" + - " your graphic card drivers are up to date."); + " your graphic card drivers are up to date."); CLog.LogError(e.Message + " - Error in initializing of OpenGL. Please check whether" + - " your graphic card drivers are up to date."); + " your graphic card drivers are up to date."); Environment.Exit(Environment.ExitCode); } break; @@ -43,12 +43,12 @@ namespace Vocaluxe.Base catch (Exception e) { MessageBox.Show(e.Message + " - Error in initializing of Direct3D. Please check if " + - "your DirectX redistributables and graphic card drivers are up to date. You can " + - "download the DirectX runtimes at http://www.microsoft.com/download/en/details.aspx?id=8109", - CSettings.sProgramName, MessageBoxButtons.OK, MessageBoxIcon.Error); + "your DirectX redistributables and graphic card drivers are up to date. You can " + + "download the DirectX runtimes at http://www.microsoft.com/download/en/details.aspx?id=8109", + CSettings.sProgramName, MessageBoxButtons.OK, MessageBoxIcon.Error); CLog.LogError(e.Message + " - Error in initializing of Direct3D. Please check if " + - "your DirectX redistributables and graphic card drivers are up to date. You can " + - "download the DirectX runtimes at http://www.microsoft.com/download/en/details.aspx?id=8109"); + "your DirectX redistributables and graphic card drivers are up to date. You can " + + "download the DirectX runtimes at http://www.microsoft.com/download/en/details.aspx?id=8109"); Environment.Exit(Environment.ExitCode); } break; @@ -139,7 +139,7 @@ namespace Vocaluxe.Base { _Draw.MakeScreenShot(); } - + // Draw Basic Text (must be deleted later) public static void DrawText(string Text, int x, int y, int h) { @@ -161,7 +161,7 @@ namespace Vocaluxe.Base if (MaxSize == 0) return _Draw.AddTexture(TexturePath); - if (!System.IO.File.Exists(TexturePath)) + if (!File.Exists(TexturePath)) return new STexture(-1); using (Bitmap origin = new Bitmap(TexturePath)) @@ -257,7 +257,7 @@ namespace Vocaluxe.Base CHelper.SetRect(bounds, ref rect, rect.Width / rect.Height, Aspect); DrawTexture(Texture, new SRectF(rect.X, rect.Y, rect.Width, rect.Height, StaticBounds.Rect.Z), - Texture.color, new SRectF(bounds.X, bounds.Y, bounds.Width, bounds.Height, 0f), false); + Texture.color, new SRectF(bounds.X, bounds.Y, bounds.Width, bounds.Height, 0f), false); } public static void DrawTextureReflection(STexture Texture, SRectF rect, SColorF color, SRectF bounds, float space, float height) @@ -270,4 +270,4 @@ namespace Vocaluxe.Base return _Draw.TextureCount(); } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CFont.cs b/Vocaluxe/Base/CFont.cs index c3f4c96e..3a511cc2 100644 --- a/Vocaluxe/Base/CFont.cs +++ b/Vocaluxe/Base/CFont.cs @@ -4,15 +4,16 @@ using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Text; using System.IO; +using System.Text; using System.Windows.Forms; using System.Xml; using VocaluxeLib.Menu; namespace Vocaluxe.Base -{ +{ class CGlyph { - private float _SIZEh = 50f; + private readonly float _SIZEh = 50f; public float SIZEh { get { return _SIZEh; } @@ -21,11 +22,11 @@ namespace Vocaluxe.Base public STexture Texture; public char Chr; public int width; - + public CGlyph(char chr, float MaxHigh) { _SIZEh = MaxHigh; - + float outline = CFonts.Outline; TextFormatFlags flags = TextFormatFlags.NoPadding | TextFormatFlags.NoPrefix; @@ -34,7 +35,8 @@ namespace Vocaluxe.Base Font fo; Size sizeB; SizeF size; - using(Graphics g=Graphics.FromHwnd(IntPtr.Zero)){ + using (Graphics g = Graphics.FromHwnd(IntPtr.Zero)) + { fo = CFonts.GetFont(); sizeB = TextRenderer.MeasureText(g, chr.ToString(), fo, new Size(int.MaxValue, int.MaxValue), flags); @@ -43,18 +45,18 @@ namespace Vocaluxe.Base using (Bitmap bmp = new Bitmap((int)(sizeB.Width * 2f), sizeB.Height)) { - Graphics g = System.Drawing.Graphics.FromImage(bmp); - g.Clear(System.Drawing.Color.Transparent); + Graphics g = Graphics.FromImage(bmp); + g.Clear(Color.Transparent); g.SmoothingMode = SmoothingMode.AntiAlias; g.InterpolationMode = InterpolationMode.HighQualityBicubic; - g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; + g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; CFonts.Height = SIZEh; fo = CFonts.GetFont(); PointF point = new PointF( - outline * Math.Abs(sizeB.Width - size.Width) + (sizeB.Width - size.Width) / 2f + SIZEh / 5f, - (sizeB.Height - size.Height - (size.Height + SIZEh / 4f) * (1f - factor)) / 2f); + outline * Math.Abs(sizeB.Width - size.Width) + (sizeB.Width - size.Width) / 2f + SIZEh / 5f, + (sizeB.Height - size.Height - (size.Height + SIZEh / 4f) * (1f - factor)) / 2f); using (GraphicsPath path = new GraphicsPath()) { @@ -74,7 +76,6 @@ namespace Vocaluxe.Base (int)CFonts.OutlineColor.B * 255), SIZEh * outline)) { - pen.LineJoin = LineJoin.Round; g.DrawPath(pen, path); g.FillPath(Brushes.White, path); @@ -94,7 +95,7 @@ namespace Vocaluxe.Base Chr = chr; width = (int)((1f + outline / 2f) * sizeB.Width * Texture.width / factor / bmp.Width); g.Dispose(); - } + } fo.Dispose(); } @@ -132,15 +133,15 @@ namespace Vocaluxe.Base } } - class CFont:IDisposable + class CFont : IDisposable { - private Dictionary _Glyphs; - private PrivateFontCollection fonts = null; + private readonly Dictionary _Glyphs; + private PrivateFontCollection fonts; private FontFamily family; - private float SIZEh; - + private readonly float SIZEh; + public string FilePath; - + public CFont(string File) { FilePath = File; @@ -259,9 +260,7 @@ namespace Vocaluxe.Base public void UnloadAllGlyphs() { foreach (CGlyph glyph in _Glyphs.Values) - { glyph.UnloadTexture(); - } _Glyphs.Clear(); } @@ -291,7 +290,7 @@ namespace Vocaluxe.Base public string FileBold; public string FileBoldItalic; - public float Outline; //0..1, 0=not outline 1=100% outline + public float Outline; //0..1, 0=not outline 1=100% outline public SColorF OutlineColor; public CFont Normal; @@ -302,14 +301,13 @@ namespace Vocaluxe.Base static class CFonts { - private static XmlWriterSettings _settings = new XmlWriterSettings(); - + private static readonly XmlWriterSettings _settings = new XmlWriterSettings(); + private static List _Fonts; private static int _CurrentFont; private static float _Height = 1f; - public static int PartyModeID - { get; set; } + public static int PartyModeID { get; set; } public static EStyle Style = EStyle.Normal; @@ -361,14 +359,14 @@ namespace Vocaluxe.Base public static void Init() { _settings.Indent = true; - _settings.Encoding = System.Text.Encoding.UTF8; + _settings.Encoding = Encoding.UTF8; _settings.ConformanceLevel = ConformanceLevel.Document; _CurrentFont = 0; PartyModeID = -1; BuildFonts(); } - + public static void BuildFonts() { _Fonts = new List(); @@ -507,8 +505,8 @@ namespace Vocaluxe.Base } } - public static void SetFont(string FontName) - { + public static void SetFont(string FontName) + { int Index = -1; if (PartyModeID != -1) @@ -538,7 +536,7 @@ namespace Vocaluxe.Base return; } } - } + } public static RectangleF GetTextBounds(CText text) { @@ -548,7 +546,8 @@ namespace Vocaluxe.Base public static RectangleF GetTextBounds(CText text, float height) { Height = height; - return new RectangleF(text.X, text.Y, GetTextWidth(CLanguage.Translate(text.Text, text.TranslationID)), GetTextHeight(CLanguage.Translate(text.Text, text.TranslationID))); + return new RectangleF(text.X, text.Y, GetTextWidth(CLanguage.Translate(text.Text, text.TranslationID)), + GetTextHeight(CLanguage.Translate(text.Text, text.TranslationID))); } public static float GetTextWidth(string text) @@ -556,9 +555,7 @@ namespace Vocaluxe.Base float dx = 0; CFont Font = _GetCurrentFont(); foreach (char chr in text) - { dx += Font.GetWidth(chr); - } return dx; } @@ -570,20 +567,21 @@ namespace Vocaluxe.Base foreach (char chr in text) { float hh = Font.GetHeight(chr); - if (hh>h) + if (hh > h) h = hh; } return h; } - private static void _LoadFontFiles(CXMLReader xmlReader, string FontFolder, string ThemeName="", int PartyModeId=-1){ + private static void _LoadFontFiles(CXMLReader xmlReader, string FontFolder, string ThemeName = "", int PartyModeId = -1) + { string value = string.Empty; int i = 1; while (xmlReader.GetValue("//root/Fonts/Font" + i.ToString() + "/Folder", ref value, value)) { SFont sf = new SFont(); sf.Folder = value; - sf.IsThemeFont = ThemeName.Length>0; + sf.IsThemeFont = ThemeName.Length > 0; sf.ThemeName = ThemeName; sf.PartyModeID = PartyModeId; @@ -598,7 +596,7 @@ namespace Vocaluxe.Base value = Path.Combine(FontFolder, Path.Combine(sf.Folder, value)); CFont f = new CFont(value); sf.Normal = f; - + ok &= xmlReader.GetValue("//root/Fonts/Font" + i.ToString() + "/FileItalic", ref value, value); sf.FileItalic = value; value = Path.Combine(FontFolder, Path.Combine(sf.Folder, value)); @@ -637,19 +635,19 @@ namespace Vocaluxe.Base fontTypes = "theme fonts for theme \"" + ThemeName + "\""; else fontTypes = "basic fonts"; - CLog.LogError("Error loading "+fontTypes+": Error in Font" + i.ToString()); + CLog.LogError("Error loading " + fontTypes + ": Error in Font" + i.ToString()); } i++; } } /// - /// Load default fonts + /// Load default fonts /// /// private static bool LoadFontList() { - CXMLReader xmlReader = CXMLReader.OpenFile(System.IO.Path.Combine(CSettings.sFolderFonts, CSettings.sFileFonts)); + CXMLReader xmlReader = CXMLReader.OpenFile(Path.Combine(CSettings.sFolderFonts, CSettings.sFileFonts)); if (xmlReader == null) return false; @@ -660,7 +658,7 @@ namespace Vocaluxe.Base } /// - /// Loads theme fonts from skin file + /// Loads theme fonts from skin file /// public static void LoadThemeFonts(string ThemeName, string FontFolder, CXMLReader xmlReader) { @@ -671,7 +669,7 @@ namespace Vocaluxe.Base } /// - /// Loads party mode fonts from skin file + /// Loads party mode fonts from skin file /// public static void LoadPartyModeFonts(int PartyModeID, string FontFolder, CXMLReader xmlReader) { @@ -680,7 +678,7 @@ namespace Vocaluxe.Base BuildGlyphs(); CLog.StopBenchmark(1, "BuildGlyphs"); } - + public static void SaveThemeFonts(string ThemeName, XmlWriter writer) { if (_Fonts.Count == 0) @@ -797,7 +795,6 @@ namespace Vocaluxe.Base } Style = EStyle.Normal; SetFont("Normal"); - } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CGame.cs b/Vocaluxe/Base/CGame.cs index f050f4d5..fd6b6917 100644 --- a/Vocaluxe/Base/CGame.cs +++ b/Vocaluxe/Base/CGame.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Vocaluxe.GameModes; using VocaluxeLib.Menu; using VocaluxeLib.Menu.SingNotes; @@ -14,13 +13,13 @@ namespace Vocaluxe.Base private static SPlayer[] _Player; private static int _NumPlayer = CConfig.NumPlayer; - private static float _Beat = 0f; - private static int _CurrentBeat = 0; + private static float _Beat; + private static int _CurrentBeat; - private static float _MidBeatD = 0f; - private static int _CurrentBeatD = 0; - private static int _OldBeatD = 0; - private static Random _Rand = new Random(); + private static float _MidBeatD; + private static int _CurrentBeatD; + private static int _OldBeatD; + private static readonly Random _Rand = new Random(); public static Random Rand { @@ -217,26 +216,23 @@ namespace Vocaluxe.Base _Beat = b; _CurrentBeat = (int)Math.Floor(_Beat); - _MidBeatD = -0.5f + GetBeatFromTime(Time, song.BPM, song.Gap + CConfig.MicDelay/1000f); + _MidBeatD = -0.5f + GetBeatFromTime(Time, song.BPM, song.Gap + CConfig.MicDelay / 1000f); _CurrentBeatD = (int)Math.Floor(_MidBeatD); for (int p = 0; p < _NumPlayer; p++) - { CSound.AnalyzeBuffer(p); - } if (_OldBeatD >= _CurrentBeatD) return; for (int p = 0; p < _NumPlayer; p++) { - for (int beat = _OldBeatD + 1; beat <= _CurrentBeatD; beat++) { if ((_GameMode.GetCurrentGameMode() == EGameMode.TR_GAMEMODE_MEDLEY && song.Medley.EndBeat == beat) || (_GameMode.GetCurrentGameMode() == EGameMode.TR_GAMEMODE_SHORTSONG && song.ShortEnd == beat)) _Player[p].SongFinished = true; - + CLine[] lines = song.Notes.GetLines(_Player[p].LineNr).Line; int Line = -1; @@ -257,9 +253,7 @@ namespace Vocaluxe.Base _Player[p].CurrentLine = Line; while (_Player[p].SingLine.Count <= Line) - { _Player[p].SingLine.Add(new CLine()); - } CNote[] notes = lines[Line].Notes; int Note = -1; @@ -300,12 +294,13 @@ namespace Vocaluxe.Base TonePlayer = Tone; _Player[p].NoteDiff = Math.Abs(Tone - TonePlayer); - bool Hit=_Player[p].NoteDiff <= (2 - (int)_Player[p].Difficulty); + bool Hit = _Player[p].NoteDiff <= (2 - (int)_Player[p].Difficulty); if (Hit) { // valid //CSound.RecordSetTone(p, Tone); - double points = (CSettings.MaxScore - CSettings.LinebonusScore) * (double)notes[Note].PointsForBeat / (double)song.Notes.GetLines(_Player[p].LineNr).Points; + double points = (CSettings.MaxScore - CSettings.LinebonusScore) * (double)notes[Note].PointsForBeat / + song.Notes.GetLines(_Player[p].LineNr).Points; if (notes[Note].NoteType == ENoteType.Golden) _Player[p].PointsGoldenNotes += points; @@ -318,14 +313,10 @@ namespace Vocaluxe.Base if (notes[Note].StartBeat == beat || nt.EndBeat + 1 != beat || nt.Tone != Tone || !nt.Hit) _Player[p].SingLine[Line].AddNote(new CNote(beat, 1, Tone, String.Empty, true, notes[Note].NoteType)); else - { _Player[p].SingLine[Line].IncLastNoteLength(); - } } else - { _Player[p].SingLine[Line].AddNote(new CNote(beat, 1, Tone, String.Empty, true, notes[Note].NoteType)); - } _Player[p].SingLine[Line].LastNote.IsPerfect(notes[Note]); _Player[p].SingLine[Line].IsPerfect(lines[Line]); @@ -336,19 +327,12 @@ namespace Vocaluxe.Base { CNote nt = _Player[p].SingLine[Line].LastNote; if (nt.Tone == TonePlayer && nt.EndBeat + 1 == beat && !nt.Hit) - { _Player[p].SingLine[Line].IncLastNoteLength(); - } else - { _Player[p].SingLine[Line].AddNote(new CNote(beat, 1, TonePlayer, String.Empty, false, ENoteType.Freestyle)); - } } else - { _Player[p].SingLine[Line].AddNote(new CNote(beat, 1, TonePlayer, String.Empty, false, ENoteType.Freestyle)); - } - } } @@ -358,7 +342,7 @@ namespace Vocaluxe.Base { if (notes[Note].EndBeat == beat && lines[Line].Points > 0f) { - double factor = (double)_Player[p].SingLine[Line].Points / (double)lines[Line].Points; + double factor = _Player[p].SingLine[Line].Points / (double)lines[Line].Points; if (factor < 0.4) factor = 0.0; else if (factor > 0.9) @@ -370,17 +354,16 @@ namespace Vocaluxe.Base factor *= factor; } - double points = CSettings.LinebonusScore * factor * 1f / NumLinesWithPoints; + double points = CSettings.LinebonusScore * factor * 1f / NumLinesWithPoints; _Player[p].Points += points; _Player[p].PointsLineBonus += points; } } } } - } } _OldBeatD = _CurrentBeatD; } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CGraphics.cs b/Vocaluxe/Base/CGraphics.cs index e84fdc70..c27f0cc2 100644 --- a/Vocaluxe/Base/CGraphics.cs +++ b/Vocaluxe/Base/CGraphics.cs @@ -19,19 +19,19 @@ namespace Vocaluxe.Base class CCursor { - private Stopwatch _CursorFadingTimer; + private readonly Stopwatch _CursorFadingTimer; private float _CursorTargetAlpha; private float _CursorStartAlpha; private float _CursorFadingTime; private STexture _Cursor; - private string _CursorName = String.Empty; + private readonly string _CursorName = String.Empty; - private Stopwatch _Movetimer; + private readonly Stopwatch _Movetimer; public bool ShowCursor; public bool Visible = true; public bool CursorVisible = true; - + public int X { get { return (int)_Cursor.rect.X; } @@ -160,7 +160,7 @@ namespace Vocaluxe.Base static class CGraphics { - private static bool _Fading = false; + private static bool _Fading; private static Stopwatch _FadingTimer; private static CCursor _Cursor; private static float _GlobalAlpha; @@ -171,11 +171,11 @@ namespace Vocaluxe.Base private static EScreens _NextScreen; private static EPopupScreens _CurrentPopupScreen; - private static List _Screens = new List(); - private static List _PopupScreens = new List(); + private static readonly List _Screens = new List(); + private static readonly List _PopupScreens = new List(); private static Stopwatch _VolumePopupTimer; - private static bool CursorOverVolumeControl = false; + private static bool CursorOverVolumeControl; public static float GlobalAlpha { @@ -222,13 +222,13 @@ namespace Vocaluxe.Base _PopupScreens.Add(new CPopupScreenVolumeControl()); CLog.StopBenchmark(1, "Build Screen List"); - + _CurrentScreen = EScreens.ScreenLoad; _NextScreen = EScreens.ScreenNull; _CurrentPopupScreen = EPopupScreens.NoPopup; _FadingTimer = new Stopwatch(); _VolumePopupTimer = new Stopwatch(); - + _GlobalAlpha = 1f; _ZOffset = 0f; @@ -255,52 +255,40 @@ namespace Vocaluxe.Base } for (int i = 0; i < _PopupScreens.Count; i++) - { + { _PopupScreens[i].Init(); _PopupScreens[i].LoadTheme(CTheme.GetThemeScreensPath(-1)); - } + } } public static void ReloadTheme() { ReloadCursor(); for (int i = 0; i < _Screens.Count; i++) - { _Screens[i].ReloadTheme(CTheme.GetThemeScreensPath(-1)); - } for (int i = 0; i < _PopupScreens.Count; i++) - { _PopupScreens[i].ReloadTheme(CTheme.GetThemeScreensPath(-1)); - } } public static void ReloadSkin() { ReloadCursor(); for (int i = 0; i < _Screens.Count; i++) - { _Screens[i].ReloadTextures(); - } for (int i = 0; i < _PopupScreens.Count; i++) - { - _PopupScreens[i].ReloadTextures(); - } + _PopupScreens[i].ReloadTextures(); } public static void SaveTheme() { CTheme.SaveTheme(); for (int i = 0; i < _Screens.Count; i++) - { _Screens[i].SaveTheme(); - } for (int i = 0; i < _PopupScreens.Count; i++) - { _PopupScreens[i].SaveTheme(); - } } public static void InitFirstScreen() @@ -372,8 +360,8 @@ namespace Vocaluxe.Base float factor = (float)ms / FadeTime; - _GlobalAlpha = 1f;// -factor / 100f; - _ZOffset = CSettings.zFar/2; + _GlobalAlpha = 1f; // -factor / 100f; + _ZOffset = CSettings.zFar / 2; if (_CurrentScreen == EScreens.ScreenPartyDummy) { @@ -405,7 +393,7 @@ namespace Vocaluxe.Base GC.Collect(); _CurrentScreen = _NextScreen; _NextScreen = EScreens.ScreenNull; - if(CBackgroundMusic.Playing) + if (CBackgroundMusic.Playing) CBackgroundMusic.Play(); _Screens[(int)_CurrentScreen].OnShowFinish(); _Screens[(int)_CurrentScreen].ProcessMouseMove(_Cursor.X, _Cursor.Y); @@ -438,9 +426,7 @@ namespace Vocaluxe.Base } for (int i = 0; i < _PopupScreens.Count; i++) - { _PopupScreens[i].Draw(); - } _Cursor.Draw(); DrawDebugInfos(); @@ -461,10 +447,10 @@ namespace Vocaluxe.Base } _Screens[(int)EScreens.ScreenPartyDummy] = scr; } - + _NextScreen = Screen; } - + public static void ShowPopup(EPopupScreens PopupScreen) { _PopupScreens[(int)PopupScreen].OnShow(); @@ -490,7 +476,6 @@ namespace Vocaluxe.Base { _Cursor.ShowCursor = true; } - #endregion public methods #region private stuff @@ -502,12 +487,13 @@ namespace Vocaluxe.Base MouseEvent InputMouseEvent = new MouseEvent(); bool PopupPlayerControlAllowed = _CurrentScreen != EScreens.ScreenOptionsRecord && _CurrentScreen != EScreens.ScreenSing && - (_CurrentScreen != EScreens.ScreenSong || (_CurrentScreen == EScreens.ScreenSong && !CSongs.IsInCategory && CConfig.Tabs ==EOffOn.TR_CONFIG_ON)) - && _CurrentScreen != EScreens.ScreenCredits && !CBackgroundMusic.Disabled; + (_CurrentScreen != EScreens.ScreenSong || + (_CurrentScreen == EScreens.ScreenSong && !CSongs.IsInCategory && CConfig.Tabs == EOffOn.TR_CONFIG_ON)) + && _CurrentScreen != EScreens.ScreenCredits && !CBackgroundMusic.Disabled; bool PopupVolumeControlAllowed = _CurrentScreen != EScreens.ScreenCredits && _CurrentScreen != EScreens.ScreenOptionsRecord; //Hide volume control for bg-music if bg-music is disabled - if (PopupVolumeControlAllowed && (_CurrentScreen != EScreens.ScreenSong || (_CurrentScreen == EScreens.ScreenSong && CSongs.Category == -1)) + if (PopupVolumeControlAllowed && (_CurrentScreen != EScreens.ScreenSong || (_CurrentScreen == EScreens.ScreenSong && CSongs.Category == -1)) && _CurrentScreen != EScreens.ScreenSing && CConfig.BackgroundMusic == EOffOn.TR_CONFIG_OFF) PopupVolumeControlAllowed = false; @@ -526,7 +512,7 @@ namespace Vocaluxe.Base CSettings.MouseInactive(); _Cursor.FadeOut(); } - + if (PopupPlayerControlAllowed && KeyEvent.Key == Keys.Tab) { if (_CurrentPopupScreen == EPopupScreens.NoPopup && CConfig.BackgroundMusic == EOffOn.TR_CONFIG_ON) @@ -555,12 +541,13 @@ namespace Vocaluxe.Base int Diff = 0; if ((KeyEvent.ModSHIFT && (KeyEvent.Key == Keys.Add || KeyEvent.Key == Keys.PageUp)) || (KeyEvent.Sender == ESender.WiiMote && KeyEvent.Key == Keys.Add)) Diff = 5; - else if ((KeyEvent.ModSHIFT && (KeyEvent.Key == Keys.Subtract || KeyEvent.Key == Keys.PageDown)) || (KeyEvent.Sender == ESender.WiiMote && KeyEvent.Key == Keys.Subtract)) + else if ((KeyEvent.ModSHIFT && (KeyEvent.Key == Keys.Subtract || KeyEvent.Key == Keys.PageDown)) || + (KeyEvent.Sender == ESender.WiiMote && KeyEvent.Key == Keys.Subtract)) Diff = -5; if (Diff != 0) { - switch (CGraphics.CurrentScreen) + switch (CurrentScreen) { case EScreens.ScreenSong: if (CSongs.IsInCategory) @@ -599,17 +586,11 @@ namespace Vocaluxe.Base } if (KeyEvent.ModSHIFT && (KeyEvent.Key == Keys.F1)) - { CSettings.GameState = EGameState.EditTheme; - } - else if (KeyEvent.ModALT && (KeyEvent.Key == Keys.Enter )) - { + else if (KeyEvent.ModALT && (KeyEvent.Key == Keys.Enter)) CSettings.bFullScreen = !CSettings.bFullScreen; - } else if (KeyEvent.ModALT && (KeyEvent.Key == Keys.P)) - { CDraw.MakeScreenShot(); - } else { if (!_Fading) @@ -617,7 +598,7 @@ namespace Vocaluxe.Base bool handled = false; if (_CurrentPopupScreen != EPopupScreens.NoPopup) handled = _PopupScreens[(int)_CurrentPopupScreen].HandleInput(KeyEvent); - + if (!handled) Resume &= _Screens[(int)_CurrentScreen].HandleInput(KeyEvent); } @@ -648,7 +629,7 @@ namespace Vocaluxe.Base if (_CurrentPopupScreen == EPopupScreens.NoPopup && CConfig.BackgroundMusic == EOffOn.TR_CONFIG_ON) ShowPopup(EPopupScreens.PopupPlayerControl); } - + if (!isOverPopupPlayerControl && _CurrentPopupScreen == EPopupScreens.PopupPlayerControl) HidePopup(EPopupScreens.PopupPlayerControl); @@ -682,8 +663,8 @@ namespace Vocaluxe.Base _Screens[(int)_CurrentScreen].ApplyVolume(); if (!handled && !_Fading && (_Cursor.IsActive || MouseEvent.LB || MouseEvent.RB || MouseEvent.MB)) - Resume &= _Screens[(int)_CurrentScreen].HandleMouse(MouseEvent); - + Resume &= _Screens[(int)_CurrentScreen].HandleMouse(MouseEvent); + if (!EventsAvailable) InputEventsAvailable = CInput.PollMouseEvent(ref InputMouseEvent); } @@ -703,13 +684,9 @@ namespace Vocaluxe.Base _Screens[(int)_CurrentScreen].NextInteraction(); } else if (KeyEvent.ModALT && (KeyEvent.Key == Keys.Enter)) - { CSettings.bFullScreen = !CSettings.bFullScreen; - } else if (KeyEvent.ModALT && (KeyEvent.Key == Keys.P)) - { CDraw.MakeScreenShot(); - } else { if (!_Fading) @@ -722,7 +699,7 @@ namespace Vocaluxe.Base if (!_Fading) _Screens[(int)_CurrentScreen].HandleMouseThemeEditor(MouseEvent); - UpdateMousePosition(MouseEvent.X, MouseEvent.Y); + UpdateMousePosition(MouseEvent.X, MouseEvent.Y); } return true; } @@ -734,16 +711,14 @@ namespace Vocaluxe.Base private static bool Update() { - if(_VolumePopupTimer.IsRunning && _VolumePopupTimer.ElapsedMilliseconds >= 1500 && _CurrentPopupScreen == EPopupScreens.PopupVolumeControl) + if (_VolumePopupTimer.IsRunning && _VolumePopupTimer.ElapsedMilliseconds >= 1500 && _CurrentPopupScreen == EPopupScreens.PopupVolumeControl) { _VolumePopupTimer.Reset(); HidePopup(EPopupScreens.PopupVolumeControl); } if (_VolumePopupTimer.IsRunning) - { _Cursor.FadeIn(); - } if (_CurrentPopupScreen != EPopupScreens.NoPopup) _PopupScreens[(int)_CurrentPopupScreen].UpdateGame(); @@ -752,7 +727,6 @@ namespace Vocaluxe.Base private static void DrawDebugInfos() { - string txt = String.Empty; CFonts.Style = EStyle.Normal; CFonts.SetFont("Normal"); @@ -898,4 +872,4 @@ namespace Vocaluxe.Base } #endregion private stuff } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CInput.cs b/Vocaluxe/Base/CInput.cs index 3c97e644..380d9cee 100644 --- a/Vocaluxe/Base/CInput.cs +++ b/Vocaluxe/Base/CInput.cs @@ -1,5 +1,4 @@ - -using Vocaluxe.Lib.Input; +using Vocaluxe.Lib.Input; using Vocaluxe.Lib.Input.WiiMote; using VocaluxeLib.Menu; @@ -7,7 +6,7 @@ namespace Vocaluxe.Base { static class CInput { - static IInput _Input; + private static IInput _Input; public static void Init() { @@ -57,4 +56,4 @@ namespace Vocaluxe.Base _Input.SetRumble(Duration); } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CLanguage.cs b/Vocaluxe/Base/CLanguage.cs index 34e3bb79..b7800ab7 100644 --- a/Vocaluxe/Base/CLanguage.cs +++ b/Vocaluxe/Base/CLanguage.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Text; using System.Xml; using VocaluxeLib.Menu; @@ -23,10 +24,10 @@ namespace Vocaluxe.Base static class CLanguage { - private static XmlWriterSettings _settings = new XmlWriterSettings(); + private static readonly XmlWriterSettings _settings = new XmlWriterSettings(); private static List _Languages; - private static int _CurrentLanguage = 0; - private static int _FallbackLanguage = 0; + private static int _CurrentLanguage; + private static int _FallbackLanguage; public static int LanguageId { @@ -48,9 +49,7 @@ namespace Vocaluxe.Base string[] Languages = new string[_Languages.Count]; for (int i = 0; i < _Languages.Count; i++) - { - Languages[i]=_Languages[i].Name; - } + Languages[i] = _Languages[i].Name; return Languages; } @@ -59,16 +58,14 @@ namespace Vocaluxe.Base { _Languages = new List(); _settings.Indent = true; - _settings.Encoding = System.Text.Encoding.UTF8; + _settings.Encoding = Encoding.UTF8; _settings.ConformanceLevel = ConformanceLevel.Document; List files = new List(); files.AddRange(CHelper.ListFiles(CSettings.sFolderLanguages, "*.xml", true, true)); - + foreach (string file in files) - { - LoadLanguageFile(file); - } + LoadLanguageFile(file); } public static bool SetLanguage(string Language) @@ -102,7 +99,7 @@ namespace Vocaluxe.Base if (KeyWord == null) return "Error"; - if (KeyWord.Length < 3 || KeyWord.Substring(0, 3) != "TR_") + if (KeyWord.Length < 3 || KeyWord.Substring(0, 3) != "TR_") return KeyWord; string result; @@ -170,7 +167,7 @@ namespace Vocaluxe.Base Texts = new Dictionary(); List names = xmlReader.GetAttributes("resources", "name"); string value = string.Empty; - foreach(string name in names) + foreach (string name in names) { if (xmlReader.GetValue("//resources/string[@name='" + name + "']", ref value, "")) { @@ -206,7 +203,7 @@ namespace Vocaluxe.Base lang.PartyModeID = PartyModeID; if (!_LoadLanguageEntries(xmlReader, ref lang.Texts)) return false; - + _Languages[nr].PartyModeTexts.Add(lang); return true; } @@ -245,11 +242,11 @@ namespace Vocaluxe.Base private static int GetPartyModeNr(int PartyModeID, int Language) { for (int i = 0; i < _Languages[Language].PartyModeTexts.Count; i++) - { + { if (_Languages[Language].PartyModeTexts[i].PartyModeID == PartyModeID) return i; - } + } return -1; } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CLog.cs b/Vocaluxe/Base/CLog.cs index e7f3ea91..c78005f3 100644 --- a/Vocaluxe/Base/CLog.cs +++ b/Vocaluxe/Base/CLog.cs @@ -5,11 +5,11 @@ using System.Text; namespace Vocaluxe.Base { - class Log:IDisposable + class Log : IDisposable { - private string _LogFileName; - private string _LogName; - private StreamWriter _LogFile = null; + private readonly string _LogFileName; + private readonly string _LogName; + private StreamWriter _LogFile; public Log(string FileName, string LogName) { @@ -26,9 +26,7 @@ namespace Vocaluxe.Base _LogFile.Flush(); _LogFile.Close(); } - catch (Exception) - { - } + catch (Exception) {} } } @@ -42,9 +40,7 @@ namespace Vocaluxe.Base _LogFile.WriteLine(Text); _LogFile.Flush(); } - catch (Exception) - { - } + catch (Exception) {} } private void Open() @@ -77,8 +73,8 @@ namespace Vocaluxe.Base private static int _NumErrors; private static Stopwatch[] _BenchmarkTimer; - private static double nanosecPerTick = (1000.0 * 1000.0 * 1000.0) / Stopwatch.Frequency; - + private static readonly double nanosecPerTick = (1000.0 * 1000.0 * 1000.0) / Stopwatch.Frequency; + public static void Init() { _ErrorLog = new Log(CSettings.sFileErrorLog, "ErrorLog"); @@ -88,9 +84,7 @@ namespace Vocaluxe.Base _NumErrors = 0; _BenchmarkTimer = new Stopwatch[MAXBenchmarks]; for (int i = 0; i < _BenchmarkTimer.Length; i++) - { _BenchmarkTimer[i] = new Stopwatch(); - } } public static void CloseAll() @@ -128,9 +122,7 @@ namespace Vocaluxe.Base string space = String.Empty; for (int i = 0; i < BenchmarkNr; i++) - { - space += " "; - } + space += " "; _BenchmarkLog.Add(space + "Start " + Text); _BenchmarkTimer[BenchmarkNr].Start(); @@ -145,15 +137,13 @@ namespace Vocaluxe.Base string space = String.Empty; for (int i = 0; i < BenchmarkNr; i++) - { space += " "; - } float ms; if (Stopwatch.IsHighResolution && nanosecPerTick != 0.0) ms = (float)((nanosecPerTick * _BenchmarkTimer[BenchmarkNr].ElapsedTicks) / (1000.0 * 1000.0)); else - ms = (float)_BenchmarkTimer[BenchmarkNr].ElapsedMilliseconds; + ms = _BenchmarkTimer[BenchmarkNr].ElapsedMilliseconds; _BenchmarkLog.Add(space + "Stop " + Text + ", Elapsed Time: " + ms.ToString("0.000") + "ms"); _BenchmarkLog.Add(String.Empty); @@ -161,4 +151,4 @@ namespace Vocaluxe.Base } #endregion LogBenchmark } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CMain.cs b/Vocaluxe/Base/CMain.cs index 0783b788..6f4b41b9 100644 --- a/Vocaluxe/Base/CMain.cs +++ b/Vocaluxe/Base/CMain.cs @@ -32,7 +32,7 @@ namespace Vocaluxe.Base public static void Init() { CBase.Assign(Config, Settings, Theme, Helper, Log, BackgroundMusic, Draw, Graphics, Fonts, Language, - Game, Profiles, Record, Songs, Video, Sound, Cover, DataBase, Input, Playlist); + Game, Profiles, Record, Songs, Video, Sound, Cover, DataBase, Input, Playlist); } } @@ -273,12 +273,9 @@ namespace Vocaluxe.Base { CTheme.LoadTheme(); } - } - class BHelper : IHelper - { - } + class BHelper : IHelper {} class BBackgroundMusic : IBackgroundMusic { @@ -327,7 +324,6 @@ namespace Vocaluxe.Base CBackgroundMusic.Play(); } - public void ApplyVolume() { CBackgroundMusic.ApplyVolume(); @@ -685,7 +681,6 @@ namespace Vocaluxe.Base { return CVideo.VdClose(VideoStream); } - } class BSound : ISound @@ -797,8 +792,6 @@ namespace Vocaluxe.Base return CPlaylists.NumPlaylists; } - - public void AddPlaylistSong(int PlaylistID, int SongID) { CPlaylists.AddPlaylistSong(PlaylistID, SongID); @@ -844,4 +837,4 @@ namespace Vocaluxe.Base return CPlaylists.GetPlaylistSong(PlaylistID, SongIndex); } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CObservable.cs b/Vocaluxe/Base/CObservable.cs index 60bfc1bb..d548e92e 100644 --- a/Vocaluxe/Base/CObservable.cs +++ b/Vocaluxe/Base/CObservable.cs @@ -18,4 +18,4 @@ namespace Vocaluxe.Base NotifyObservers(); } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CParty.cs b/Vocaluxe/Base/CParty.cs index fd69469b..0c27c84a 100644 --- a/Vocaluxe/Base/CParty.cs +++ b/Vocaluxe/Base/CParty.cs @@ -8,6 +8,7 @@ using VocaluxeLib.PartyModes; namespace Vocaluxe.Base { + #region Structs struct SPartyMode { @@ -27,10 +28,9 @@ namespace Vocaluxe.Base } #endregion Structs - static class CParty { - const int PartyModeSystemVersion = 1; + private const int PartyModeSystemVersion = 1; private static Dictionary _PartyModes; private static Queue _IDs; @@ -81,7 +81,7 @@ namespace Vocaluxe.Base { List infos = new List(); - int[] UsedKeys = new int[_PartyModes.Count]; + int[] UsedKeys = new int[_PartyModes.Count]; _PartyModes.Keys.CopyTo(UsedKeys, 0); for (int i = 0; i < UsedKeys.Length; i++) @@ -115,7 +115,7 @@ namespace Vocaluxe.Base } return infos; } - + public static void SetNormalGameMode() { CSongs.ResetPartySongSung(); @@ -164,7 +164,7 @@ namespace Vocaluxe.Base public static void OnCategoryChange(int CategoryIndex, ref ScreenSongOptions ScreenSongOptions) { - _CurrentPartyMode.PartyMode.OnCategoryChange(CategoryIndex, ref ScreenSongOptions); + _CurrentPartyMode.PartyMode.OnCategoryChange(CategoryIndex, ref ScreenSongOptions); } public static void SetSearchString(string SearchString, bool Visible) @@ -213,7 +213,7 @@ namespace Vocaluxe.Base private static SPartyMode LoadPartyMode(string file) { - SPartyMode pm = new SPartyMode(); + SPartyMode pm = new SPartyMode(); pm.PartyModeID = _IDs.Dequeue(); pm.ScreenFiles = new List(); pm.NoErrors = false; @@ -226,7 +226,7 @@ namespace Vocaluxe.Base bool loaded = true; - loaded &= xmlReader.TryGetIntValue("//root/PartyModeSystemVersion", ref pm.PartyModeSystemVersion); + loaded &= xmlReader.TryGetIntValue("//root/PartyModeSystemVersion", ref pm.PartyModeSystemVersion); loaded &= xmlReader.GetValue("//root/Info/Name", ref pm.Name, "ERROR Name"); loaded &= xmlReader.GetValue("//root/Info/Description", ref pm.Description, "ERROR Description"); loaded &= xmlReader.GetValue("//root/Info/Author", ref pm.Author, "ERROR Author"); @@ -259,7 +259,7 @@ namespace Vocaluxe.Base List FilesToCompile = new List(); FilesToCompile.AddRange(CHelper.ListFiles(PathToCode, "*.cs", false, true)); - + Assembly Output = CompileFiles(FilesToCompile.ToArray()); if (Output == null) return pm; @@ -355,9 +355,7 @@ namespace Vocaluxe.Base if (CompileResult.Errors.Count > 0) { foreach (CompilerError e in CompileResult.Errors) - { - CLog.LogError("Error Compiling Source (" + CHelper.ListStrings(files) + "): " + e.ErrorText+" in '"+e.FileName+"' ("+e.Line+")"); - } + CLog.LogError("Error Compiling Source (" + CHelper.ListStrings(files) + "): " + e.ErrorText + " in '" + e.FileName + "' (" + e.Line + ")"); return null; } return CompileResult.CompiledAssembly; @@ -390,4 +388,4 @@ namespace Vocaluxe.Base } #endregion private stuff } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CPlaylists.cs b/Vocaluxe/Base/CPlaylists.cs index 6d3fa4df..0913e081 100644 --- a/Vocaluxe/Base/CPlaylists.cs +++ b/Vocaluxe/Base/CPlaylists.cs @@ -2,14 +2,12 @@ using System.Collections.Generic; using System.IO; using System.Text; - using Vocaluxe.Lib.Playlist; using VocaluxeLib.Menu; using VocaluxeLib.Menu.SongMenu; namespace Vocaluxe.Base { - static class CPlaylists { private static List _Playlists; @@ -21,13 +19,11 @@ namespace Vocaluxe.Base public static string[] PlaylistNames { - get + get { List names = new List(); - for (int i = 0; i < _Playlists.Count; i++) - { + for (int i = 0; i < _Playlists.Count; i++) names.Add(_Playlists[i].PlaylistName); - } return names.ToArray(); } } @@ -84,9 +80,7 @@ namespace Vocaluxe.Base List result = new List(); foreach (CPlaylistFile playlist in _Playlists) - { - result.Add(playlist.PlaylistName); - } + result.Add(playlist.PlaylistName); return result.ToArray(); } @@ -132,8 +126,6 @@ namespace Vocaluxe.Base return (_Playlists.Count - 1); } - - public static void AddPlaylistSong(int PlaylistID, int SongID) { if (PlaylistID >= _Playlists.Count || PlaylistID < 0) @@ -230,10 +222,8 @@ namespace Vocaluxe.Base StreamReader sr; try { - using (sr = new StreamReader(file, Encoding.Default, true)) { - int pos = -1; string line; while ((line = sr.ReadLine()) != null) @@ -247,11 +237,9 @@ namespace Vocaluxe.Base string Identifier = line.Substring(1, pos - 1).Trim(); string Value = line.Substring(pos + 1, line.Length - pos - 1).Trim(); if (Identifier.ToUpper() == "NAME") - { pl.PlaylistName = Value; - } } - //Song + //Song else { string Artist = line.Substring(0, pos - 1).Trim(); @@ -277,10 +265,10 @@ namespace Vocaluxe.Base catch { return null; - } + } return pl; } #endregion } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CProfiles.cs b/Vocaluxe/Base/CProfiles.cs index 790cfff4..93d4d657 100644 --- a/Vocaluxe/Base/CProfiles.cs +++ b/Vocaluxe/Base/CProfiles.cs @@ -1,16 +1,17 @@ using System; using System.Collections.Generic; using System.IO; +using System.Text; using System.Xml; using VocaluxeLib.Menu; namespace Vocaluxe.Base -{ +{ static class CProfiles { - private static XmlWriterSettings _settings = new XmlWriterSettings(); + private static readonly XmlWriterSettings _settings = new XmlWriterSettings(); private static List _Profiles; - private static List _Avatars = new List(); + private static readonly List _Avatars = new List(); public static SProfile[] Profiles { @@ -31,11 +32,11 @@ namespace Vocaluxe.Base { get { return _Avatars.Count; } } - + public static void Init() { _settings.Indent = true; - _settings.Encoding = System.Text.Encoding.UTF8; + _settings.Encoding = Encoding.UTF8; _settings.ConformanceLevel = ConformanceLevel.Document; LoadAvatars(); @@ -64,7 +65,7 @@ namespace Vocaluxe.Base if (File.Exists(profile.ProfileFile)) return -1; - + _Profiles.Add(profile); return _Profiles.Count - 1; } @@ -72,9 +73,7 @@ namespace Vocaluxe.Base public static void SaveProfiles() { for (int i = 0; i < _Profiles.Count; i++) - { SaveProfile(i); - } LoadProfiles(); } @@ -85,9 +84,7 @@ namespace Vocaluxe.Base files.AddRange(CHelper.ListFiles(CSettings.sFolderProfiles, "*.xml", true, true)); foreach (string file in files) - { LoadProfile(file); - } SortProfilesByName(); } @@ -210,7 +207,7 @@ namespace Vocaluxe.Base public static bool IsGuestProfile(int ProfileNr) { if (ProfileNr < 0 || ProfileNr >= _Profiles.Count) - return true; // this will prevent from saving dummy profiles to highscore db + return true; // this will prevent from saving dummy profiles to highscore db return _Profiles[ProfileNr].GuestProfile == EOffOn.TR_CONFIG_ON; } @@ -303,13 +300,11 @@ namespace Vocaluxe.Base filename = "1"; int i = 0; - while(File.Exists(Path.Combine(CSettings.sFolderProfiles, filename + ".xml"))) + while (File.Exists(Path.Combine(CSettings.sFolderProfiles, filename + ".xml"))) { i++; - if(!File.Exists(Path.Combine(CSettings.sFolderProfiles, filename + i + ".xml"))) - { + if (!File.Exists(Path.Combine(CSettings.sFolderProfiles, filename + i + ".xml"))) filename += i; - } } SProfile profile = _Profiles[ProfileID]; @@ -329,7 +324,6 @@ namespace Vocaluxe.Base } try { - writer.WriteStartDocument(); writer.WriteStartElement("root"); @@ -368,27 +362,23 @@ namespace Vocaluxe.Base profile.PlayerName = value; profile.Difficulty = EGameDifficulty.TR_CONFIG_EASY; - xmlReader.TryGetEnumValue("//root/Info/Difficulty", ref profile.Difficulty); + xmlReader.TryGetEnumValue("//root/Info/Difficulty", ref profile.Difficulty); profile.Avatar = new SAvatar(-1); if (xmlReader.GetValue("//root/Info/Avatar", ref value, value)) - { profile.Avatar = GetAvatar(value); - } profile.GuestProfile = EOffOn.TR_CONFIG_OFF; - xmlReader.TryGetEnumValue("//root/Info/GuestProfile", ref profile.GuestProfile); + xmlReader.TryGetEnumValue("//root/Info/GuestProfile", ref profile.GuestProfile); profile.Active = EOffOn.TR_CONFIG_ON; - xmlReader.TryGetEnumValue("//root/Info/Active", ref profile.Active); + xmlReader.TryGetEnumValue("//root/Info/Active", ref profile.Active); _Profiles.Add(profile); } else - { CLog.LogError("Can't find PlayerName in Profile File: " + FileName); - } } #endregion private methods } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CSettings.cs b/Vocaluxe/Base/CSettings.cs index 4670feda..fe6a1e7a 100644 --- a/Vocaluxe/Base/CSettings.cs +++ b/Vocaluxe/Base/CSettings.cs @@ -29,23 +29,21 @@ namespace Vocaluxe.Base public const EArch ARCH = EArch.x64; #endif - public static EGameState GameState = EGameState.Start; public const string sProgramName = "Vocaluxe"; public const string sProgramCodeName = "Shining Heaven"; public const int iVersionMajor = 0; - public const int iVersionMinor = 3; // milestones - public const int iVersionSub = 0; // patches + public const int iVersionMinor = 3; // milestones + public const int iVersionSub = 0; // patches public const ERevision VersionRevision = ERevision.Alpha; - public const int iBuild = 76; // Increase on every published version! Never Reset! + public const int iBuild = 76; // Increase on every published version! Never Reset! public const int iDatabaseHighscoreVersion = 2; public const int iDatabaseCoverVersion = 1; public const int iDatabaseCreditsRessourcesVersion = 1; - public static int iRenderW = 1280; public static int iRenderH = 720; @@ -89,7 +87,6 @@ namespace Vocaluxe.Base public const string sFolderBackgroundMusic = "BackgroundMusic"; public static string sFolderPlaylists = "Playlists"; - public static string sFolderPartyModes = "PartyModes"; public const string sFolderPartyModeCode = "Code"; public const string sFolderPartyModeScreens = "Screens"; @@ -103,7 +100,7 @@ namespace Vocaluxe.Base public const int NumNoteLines = 11; public static int MouseMoveDiffMin = 2; public const float MouseMoveOffTime = 3f; - + public const int MaxNumPlayer = 6; public const int MaxScore = 10000; public const int LinebonusScore = 1000; @@ -122,17 +119,20 @@ namespace Vocaluxe.Base public const float BackgroundMusicFadeTime = 0.5f; - public static List MusicFileTypes = new List() - { - "*.mp3","*.wma","*.ogg","*.wav" - }; - + public static List MusicFileTypes = new List + { + "*.mp3", + "*.wma", + "*.ogg", + "*.wav" + }; + public static string GetVersionText() { string sVersion = "v" + iVersionMajor.ToString() + "." + - iVersionMinor.ToString() + "." + - iVersionSub.ToString() + " (" + Enum.GetName(typeof(EArch), ARCH) + ")"; - + iVersionMinor.ToString() + "." + + iVersionSub.ToString() + " (" + Enum.GetName(typeof(EArch), ARCH) + ")"; + if (VersionRevision != ERevision.Release) sVersion += " " + GetVersionStatus() + String.Format(" ({0:0000)}", iBuild); @@ -161,7 +161,7 @@ namespace Vocaluxe.Base public static float GetRenderAspect() { - return (float)iRenderW / (float)iRenderH; + return iRenderW / (float)iRenderH; } public static void MouseInactive() @@ -190,14 +190,14 @@ namespace Vocaluxe.Base foreach (string folder in Folders) { string path = Path.Combine(Environment.CurrentDirectory, folder); - CreateFolder(path); - } + CreateFolder(path); + } } public static void CreateFolder(string path) { if (!Directory.Exists(path)) - Directory.CreateDirectory(path); + Directory.CreateDirectory(path); } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CSongCategorizer.cs b/Vocaluxe/Base/CSongCategorizer.cs index 635a9db7..8ac25804 100644 --- a/Vocaluxe/Base/CSongCategorizer.cs +++ b/Vocaluxe/Base/CSongCategorizer.cs @@ -8,7 +8,7 @@ namespace Vocaluxe.Base { class CSongCategorizer : CObservable { - private List _Categories = new List(); + private readonly List _Categories = new List(); private EOffOn _Tabs = CConfig.Tabs; public CSongCategorizer() @@ -18,7 +18,11 @@ namespace Vocaluxe.Base public List Categories { - get { _FillCategories(); return _Categories; } + get + { + _FillCategories(); + return _Categories; + } } public EOffOn Tabs @@ -48,9 +52,7 @@ namespace Vocaluxe.Base Char firstLetter = Char.ToUpper(CSongs.Sorter.SortedSongs[i].SortString.Normalize(NormalizationForm.FormD)[0]); if (!Char.IsLetter(firstLetter)) - { firstLetter = '#'; - } if (firstLetter.ToString() != category) { if (firstLetter != '#' || NotLetterCat == -1) @@ -97,7 +99,6 @@ namespace Vocaluxe.Base CSongs.Sorter.SortedSongs[i].CatIndex = NoCategoryIndex; } } - } private void _CreateCategories() @@ -130,6 +131,7 @@ namespace Vocaluxe.Base else { if (Sorting == ESongSorting.TR_CONFIG_DECADE) + { for (int i = 0; i < CSongs.Sorter.SortedSongs.Length; i++) { string Year = CSongs.Sorter.SortedSongs[i].SortString; @@ -139,6 +141,7 @@ namespace Vocaluxe.Base CSongs.Sorter.SortedSongs[i].SortString = Year + "0 - " + Year + "9"; } } + } _CreateCategoriesNormal(NoCategoryName); } } @@ -155,18 +158,14 @@ namespace Vocaluxe.Base //No categories. So don't create them! _Categories.Add(new CCategory("")); for (int i = 0; i < CSongs.Sorter.SortedSongs.Length; i++) - { CSongs.Sorter.SortedSongs[i].CatIndex = 0; - } } else _CreateCategories(); foreach (CCategory cat in _Categories) - { cat.CoverTextureSmall = CCover.Cover(cat.Name); - } _Changed = false; } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CSongFilter.cs b/Vocaluxe/Base/CSongFilter.cs index 2aa92656..9777661f 100644 --- a/Vocaluxe/Base/CSongFilter.cs +++ b/Vocaluxe/Base/CSongFilter.cs @@ -14,7 +14,11 @@ namespace Vocaluxe.Base public List FilteredSongs { - get { _FilterSongs(); return _FilteredSongs; } + get + { + _FilterSongs(); + return _FilteredSongs; + } } public String SearchString @@ -62,7 +66,7 @@ namespace Vocaluxe.Base string[] searchStrings = null; if (_SearchString.Length > 0) - searchStrings = _SearchString.ToUpper().Split(new char[] { ' ' }); + searchStrings = _SearchString.ToUpper().Split(new[] {' '}); foreach (CSong song in CSongs.Songs) { @@ -77,9 +81,7 @@ namespace Vocaluxe.Base bool contains = true; foreach (string str in searchStrings) - { contains &= search.Contains(str); - } if (contains) _FilteredSongs.Add(song); } @@ -87,6 +89,5 @@ namespace Vocaluxe.Base } _Changed = false; } - } } \ No newline at end of file diff --git a/Vocaluxe/Base/CSongSorter.cs b/Vocaluxe/Base/CSongSorter.cs index 27233e97..170fac5c 100644 --- a/Vocaluxe/Base/CSongSorter.cs +++ b/Vocaluxe/Base/CSongSorter.cs @@ -6,7 +6,7 @@ using VocaluxeLib.Menu.SongMenu; namespace Vocaluxe.Base { - class CSongSorter:CObservable + class CSongSorter : CObservable { private SongPointer[] _SortedSongs = new SongPointer[0]; private EOffOn _IgnoreArticles = CConfig.IgnoreArticles; @@ -19,7 +19,11 @@ namespace Vocaluxe.Base public SongPointer[] SortedSongs { - get { _SortSongs(); return _SortedSongs; } + get + { + _SortSongs(); + return _SortedSongs; + } } public EOffOn IgnoreArticles @@ -72,18 +76,14 @@ namespace Vocaluxe.Base { res = CSongs.Songs[s1.SongID].ArtistSorting.ToUpper().CompareTo(CSongs.Songs[s2.SongID].ArtistSorting.ToUpper()); if (res == 0) - { return CSongs.Songs[s1.SongID].TitleSorting.ToUpper().CompareTo(CSongs.Songs[s2.SongID].TitleSorting.ToUpper()); - } return res; } else { res = CSongs.Songs[s1.SongID].Artist.ToUpper().CompareTo(CSongs.Songs[s2.SongID].Artist.ToUpper()); if (res == 0) - { return CSongs.Songs[s1.SongID].Title.ToUpper().CompareTo(CSongs.Songs[s2.SongID].Title.ToUpper()); - } return res; } } @@ -110,7 +110,8 @@ namespace Vocaluxe.Base List SortList = new List(); if (fieldName.Length == 0) CSongs.Filter.FilteredSongs.ForEach((song) => SortList.Add(new SongPointer(song.ID, ""))); - else{ + else + { field = Type.GetType("Vocaluxe.Menu.SongMenu.CSong,VocaluxeLib").GetField(fieldName, BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public); isString = field.FieldType == typeof(string); if (!isString && field.FieldType != typeof(List)) @@ -124,15 +125,11 @@ namespace Vocaluxe.Base { List values = (List)value; if (values.Count == 0) - { SortList.Add(new SongPointer(song.ID, "")); - } else { foreach (String sortString in (List)value) - { SortList.Add(new SongPointer(song.ID, sortString)); - } } } } diff --git a/Vocaluxe/Base/CSongs.cs b/Vocaluxe/Base/CSongs.cs index 6128add2..55924525 100644 --- a/Vocaluxe/Base/CSongs.cs +++ b/Vocaluxe/Base/CSongs.cs @@ -27,16 +27,16 @@ namespace Vocaluxe.Base static class CSongs { - private static List _Songs = new List(); - private static List _SongsForRandom = new List(); + private static readonly List _Songs = new List(); + private static readonly List _SongsForRandom = new List(); - private static bool _SongsLoaded = false; - private static bool _CoverLoaded = false; - private static int _CoverLoadIndex = 0; + private static bool _SongsLoaded; + private static bool _CoverLoaded; + private static int _CoverLoadIndex; private static int _CatIndex = -1; - private static List _CategoriesForRandom = new List(); + private static readonly List _CategoriesForRandom = new List(); - private static Stopwatch _CoverLoadTimer = new Stopwatch(); + private static readonly Stopwatch _CoverLoadTimer = new Stopwatch(); public static CSongFilter Filter = new CSongFilter(); public static CSongSorter Sorter = new CSongSorter(); @@ -54,7 +54,7 @@ namespace Vocaluxe.Base public static bool CoverLoaded { - get + get { if (_SongsLoaded && NumAllSongs == 0) _CoverLoaded = true; @@ -96,9 +96,7 @@ namespace Vocaluxe.Base _CatIndex = value; for (int i = 0; i < Sorter.SortedSongs.Length; i++) - { Sorter.SortedSongs[i].Visible = (Sorter.SortedSongs[i].CatIndex == _CatIndex && !Sorter.SortedSongs[i].PartyHidden); - } } } } @@ -109,7 +107,7 @@ namespace Vocaluxe.Base } /// - /// Returns the number of song in the category specified with CatIndex + /// Returns the number of song in the category specified with CatIndex /// /// Category index /// @@ -134,6 +132,7 @@ namespace Vocaluxe.Base else Category++; } + public static void PrevCategory() { if (Category == 0) @@ -156,6 +155,7 @@ namespace Vocaluxe.Base return -2; } + public static int NumSongsWithCoverLoaded { get { return _CoverLoadIndex; } @@ -168,8 +168,8 @@ namespace Vocaluxe.Base if (SongIndex < _Songs.Count) _Songs[SongIndex].CoverTextureSmall = Texture; - } + public static void SetCoverBig(int SongIndex, STexture Texture) { if (!_SongsLoaded) @@ -177,7 +177,6 @@ namespace Vocaluxe.Base if (SongIndex < _Songs.Count) _Songs[SongIndex].CoverTextureBig = Texture; - } public static string GetCurrentCategoryName() @@ -255,14 +254,12 @@ namespace Vocaluxe.Base public static int GetRandomSong() { if (_SongsForRandom.Count == 0) - { UpdateRandomSongList(); - } if (_SongsForRandom.Count == 0) return -1; - CSong song = _SongsForRandom[CGame.Rand.Next(0, _SongsForRandom.Count-1)]; + CSong song = _SongsForRandom[CGame.Rand.Next(0, _SongsForRandom.Count - 1)]; _SongsForRandom.Remove(song); return GetVisibleSongNumber(song.ID); } @@ -309,7 +306,7 @@ namespace Vocaluxe.Base public static CSong[] SongsNotSung { - get + get { List songs = new List(); foreach (SongPointer sp in Sorter.SortedSongs) @@ -456,7 +453,7 @@ namespace Vocaluxe.Base private static void _LoadCoverAndNotes() { - foreach(CSong song in _Songs) + foreach (CSong song in _Songs) { song.ReadNotes(); song.LoadSmallCover(); @@ -467,4 +464,4 @@ namespace Vocaluxe.Base CDataBase.CommitCovers(); } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CSound.cs b/Vocaluxe/Base/CSound.cs index 6d4d6691..c25f5cfb 100644 --- a/Vocaluxe/Base/CSound.cs +++ b/Vocaluxe/Base/CSound.cs @@ -1,7 +1,6 @@ using System; using System.Diagnostics; using System.IO; - using Vocaluxe.Lib.Sound; using VocaluxeLib.Menu; @@ -15,7 +14,7 @@ namespace Vocaluxe.Base static class CSound { #region Playback - private static IPlayback _Playback = null; + private static IPlayback _Playback; public static bool PlaybackInit() { @@ -150,8 +149,8 @@ namespace Vocaluxe.Base { _Playback.SetPosition(Stream, Position); } - #endregion Stream Handling + #endregion Playback #region Sounds @@ -168,16 +167,16 @@ namespace Vocaluxe.Base if (file.Length == 0) return -1; - int stream = CSound.Load(file); - float length = CSound.GetLength(stream); - CSound.Play(stream); - CSound.FadeAndStop(stream, 100f, length); + int stream = Load(file); + float length = GetLength(stream); + Play(stream); + FadeAndStop(stream, 100f, length); return stream; } #endregion Sounds #region Record - private static IRecord _Record = null; + private static IRecord _Record; public static bool RecordInit() { @@ -197,7 +196,7 @@ namespace Vocaluxe.Base _Record = new CPortAudioRecord(); break; } - + return true; } @@ -209,7 +208,7 @@ namespace Vocaluxe.Base public static bool RecordStart() { SRecordDevice[] devices = RecordGetDevices(); - + return _Record.Start(devices); } @@ -261,23 +260,23 @@ namespace Vocaluxe.Base public static SRecordDevice[] RecordGetDevices() { SRecordDevice[] devices = _Record.RecordDevices(); - - if (devices != null) - { - for (int dev = 0; dev < devices.Length; dev++) - { - for (int inp = 0; inp < devices[dev].Inputs.Count; inp++) - { - SInput input = devices[dev].Inputs[inp]; - - input.PlayerChannel1 = GetPlayerFromMicConfig(devices[dev].Name, devices[dev].Driver, input.Name, 1); - input.PlayerChannel2 = GetPlayerFromMicConfig(devices[dev].Name, devices[dev].Driver, input.Name, 2); - - devices[dev].Inputs[inp] = input; - } - } - return devices; - } + + if (devices != null) + { + for (int dev = 0; dev < devices.Length; dev++) + { + for (int inp = 0; inp < devices[dev].Inputs.Count; inp++) + { + SInput input = devices[dev].Inputs[inp]; + + input.PlayerChannel1 = GetPlayerFromMicConfig(devices[dev].Name, devices[dev].Driver, input.Name, 1); + input.PlayerChannel2 = GetPlayerFromMicConfig(devices[dev].Name, devices[dev].Driver, input.Name, 2); + + devices[dev].Inputs[inp] = input; + } + } + return devices; + } return null; } @@ -291,9 +290,7 @@ namespace Vocaluxe.Base CConfig.MicConfig[p].DeviceDriver == devicedriver && CConfig.MicConfig[p].InputName == input && CConfig.MicConfig[p].Channel == channel) - { return p + 1; - } } return 0; } @@ -305,25 +302,23 @@ namespace Vocaluxe.Base private const double _BaseToneFreq = 65.4064; private const int _NumHalfTones = 47; - private float[] _ToneWeigth; + private readonly float[] _ToneWeigth; private Int16[] _AnalysisBuffer = new Int16[4096]; - private Object _AnalysisBufferLock = new Object(); + private readonly Object _AnalysisBufferLock = new Object(); - private bool _ToneValid = false; - private int _Tone = 0; - private int _ToneAbs = 0; - private double _MaxVolume = 0.0; + private bool _ToneValid; + private int _Tone; + private int _ToneAbs; + private double _MaxVolume; private bool _NewSamples; - private MemoryStream _Stream = null; // full buffer + private MemoryStream _Stream; // full buffer public CBuffer() { _ToneWeigth = new float[_NumHalfTones]; for (int i = 0; i < _ToneWeigth.Length; i++) - { _ToneWeigth[i] = 0.99f; - } _Stream = new MemoryStream(); _NewSamples = false; } @@ -335,12 +330,12 @@ namespace Vocaluxe.Base public int ToneAbs { - get + get { lock (_AnalysisBufferLock) { - return _ToneAbs; - } + return _ToneAbs; + } } } @@ -422,7 +417,6 @@ namespace Vocaluxe.Base public void ProcessNewBuffer(byte[] buffer) { - // apply software boost //BoostBuffer(Buffer, BufferSize); @@ -469,7 +463,7 @@ namespace Vocaluxe.Base _MaxVolume = 0; for (int i = 0; i < _AnalysisBuffer.Length / 4; i++) { - float Volume = Math.Abs((float)_AnalysisBuffer[i]) / (float)Int16.MaxValue; + float Volume = Math.Abs((float)_AnalysisBuffer[i]) / Int16.MaxValue; if (Volume > MaxVolume) _MaxVolume = Volume; } @@ -478,12 +472,8 @@ namespace Vocaluxe.Base AnalyzeByAutocorrelation(true); else AnalyzeByAutocorrelation(false); - - } - catch (Exception) - { - } + catch (Exception) {} } private void AnalyzeByAutocorrelation(bool valid) @@ -521,9 +511,7 @@ namespace Vocaluxe.Base if (valid && MaxWeight - MinWeight > 0.01) { for (int i = 0; i < Weigth.Length; i++) - { _ToneWeigth[i] = Weigth[i]; - } _ToneAbs = MaxTone; _Tone = MaxTone % 12; @@ -535,18 +523,18 @@ namespace Vocaluxe.Base private double AnalyzeAutocorrelationFreq(double Freq) { - int SampleIndex = 0; // index of sample to analyze - int SamplesPerPeriod = (int)Math.Round(44100.0 / Freq); // samples in one period - int CorrelatingSampleIndex = SampleIndex + SamplesPerPeriod; // index of sample one period ahead + int SampleIndex = 0; // index of sample to analyze + int SamplesPerPeriod = (int)Math.Round(44100.0 / Freq); // samples in one period + int CorrelatingSampleIndex = SampleIndex + SamplesPerPeriod; // index of sample one period ahead - double AccumDist = 0.0; // accumulated distances + double AccumDist = 0.0; // accumulated distances // compare correlating samples while (CorrelatingSampleIndex < _AnalysisBuffer.Length) { // calc distance (correlation: 1-dist) to corresponding sample in next period // distance (0=equal .. 1=totally different) between correlated samples - double Dist = Math.Abs((double)_AnalysisBuffer[SampleIndex] - _AnalysisBuffer[CorrelatingSampleIndex]) / (double)Int16.MaxValue; + double Dist = Math.Abs((double)_AnalysisBuffer[SampleIndex] - _AnalysisBuffer[CorrelatingSampleIndex]) / Int16.MaxValue; AccumDist += Dist; SampleIndex++; CorrelatingSampleIndex++; @@ -568,10 +556,10 @@ namespace Vocaluxe.Base class CSyncTimer { - private PT1 _ExternTime; - private Stopwatch _Timer; + private readonly PT1 _ExternTime; + private readonly Stopwatch _Timer; private float _SetValue; - + public float Time { get @@ -648,9 +636,9 @@ namespace Vocaluxe.Base private float _CurrentTime; private float _OldTime; - private Stopwatch _STimer; - private float _K; - private float _T; + private readonly Stopwatch _STimer; + private readonly float _K; + private readonly float _T; public float Time { @@ -698,7 +686,7 @@ namespace Vocaluxe.Base if (Stopwatch.IsHighResolution && ticks != 0) dt = (float)(ticks * nanosecPerTick / 1000000000.0); - + float Ts = 0f; if (dt > 0) Ts = 1 / (_T / dt + 1); @@ -722,4 +710,4 @@ namespace Vocaluxe.Base _STimer.Start(); } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CTheme.cs b/Vocaluxe/Base/CTheme.cs index 99f8853c..97826aee 100644 --- a/Vocaluxe/Base/CTheme.cs +++ b/Vocaluxe/Base/CTheme.cs @@ -8,6 +8,7 @@ using VocaluxeLib.Menu; namespace Vocaluxe.Base { + #region Structs struct Theme { @@ -79,15 +80,15 @@ namespace Vocaluxe.Base static class CTheme { // Version number for main theme and skin files. Increment it, if you've changed something on the theme files! - const int ThemeSystemVersion = 5; - const int SkinSystemVersion = 3; + private const int ThemeSystemVersion = 5; + private const int SkinSystemVersion = 3; #region Vars - private static XmlWriterSettings _settings = new XmlWriterSettings(); - private static List _Themes = new List(); + private static readonly XmlWriterSettings _settings = new XmlWriterSettings(); + private static readonly List _Themes = new List(); public static string[] ThemeNames { - get + get { List names = new List(); foreach (Theme th in _Themes) @@ -99,7 +100,7 @@ namespace Vocaluxe.Base } } - private static List _Skins = new List(); + private static readonly List _Skins = new List(); public static string[] SkinNames { get @@ -120,7 +121,7 @@ namespace Vocaluxe.Base #region Theme and Skin loading and writing public static void InitTheme() { - _settings.Indent = true; + _settings.Indent = true; _settings.Encoding = Encoding.UTF8; _settings.ConformanceLevel = ConformanceLevel.Document; @@ -272,8 +273,8 @@ namespace Vocaluxe.Base else { CFonts.LoadPartyModeFonts(_Themes[ThemeIndex].PartyModeID, - Path.Combine(_Themes[ThemeIndex].Path, CSettings.sFolderPartyModeFonts), - xmlReader); + Path.Combine(_Themes[ThemeIndex].Path, CSettings.sFolderPartyModeFonts), + xmlReader); } return true; } @@ -286,7 +287,7 @@ namespace Vocaluxe.Base { if (_Themes[i].Name == CConfig.Theme && _Themes[i].PartyModeID == -1 || _Themes[i].PartyModeID != -1) SaveTheme(i); - } + } } private static void SaveTheme(int ThemeIndex) @@ -360,9 +361,7 @@ namespace Vocaluxe.Base writer.WriteStartElement("Skins"); foreach (SkinElement element in _Skins[SkinIndex].SkinList.Values) - { writer.WriteElementString(element.Name, element.Value); - } writer.WriteEndElement(); #endregion Skins @@ -370,9 +369,7 @@ namespace Vocaluxe.Base writer.WriteStartElement("Videos"); foreach (SkinElement element in _Skins[SkinIndex].VideoList) - { writer.WriteElementString(element.Name, element.Value); - } writer.WriteEndElement(); #endregion Videos @@ -393,9 +390,7 @@ namespace Vocaluxe.Base List files = CHelper.ListFiles(path, "*.xml", false); foreach (string file in files) - { AddTheme(Path.Combine(path, file), -1); - } } public static bool AddTheme(string FilePath, int PartyModeID) @@ -433,7 +428,7 @@ namespace Vocaluxe.Base else msg += "the file is for newer program versions! "; - msg += "Current ThemeSystemVersion is " + ThemeSystemVersion.ToString()+ " but found " + version; + msg += "Current ThemeSystemVersion is " + ThemeSystemVersion.ToString() + " but found " + version; CLog.LogError(msg); } return true; @@ -449,7 +444,7 @@ namespace Vocaluxe.Base CLog.LogError("Error List Skins. Can't find Theme: " + CConfig.Theme); return; } - ListSkins(themeIndex); + ListSkins(themeIndex); } public static void ListSkins(int ThemeIndex) @@ -533,15 +528,11 @@ namespace Vocaluxe.Base for (int i = 0; i < _Skins.Count; i++) { if (PartyModeID != -1 && _Skins[i].PartyModeID == PartyModeID) - { return i; - } else if (PartyModeID == -1 && _Skins[i].Name == CConfig.Skin) - { return i; - } } - + return -1; } @@ -550,13 +541,9 @@ namespace Vocaluxe.Base for (int i = 0; i < _Themes.Count; i++) { if (PartyModeID != -1 && _Themes[i].PartyModeID == PartyModeID) - { return i; - } else if (PartyModeID == -1 && _Themes[i].Name == CConfig.Theme) - { return i; - } } return -1; @@ -582,9 +569,7 @@ namespace Vocaluxe.Base { int SkinIndex = GetSkinIndex(PartyModeID); if (SkinIndex != -1 && TextureName != null && _Skins[SkinIndex].SkinList.ContainsKey(TextureName)) - { return _Skins[SkinIndex].SkinList[TextureName].Texture; - } return new STexture(-1); } @@ -763,7 +748,7 @@ namespace Vocaluxe.Base { string value = String.Empty; xmlReader.GetValue("//root/Cursor/Skin", ref Cursor.SkinName, value); - + xmlReader.TryGetFloatValue("//root/Cursor/W", ref Cursor.w); xmlReader.TryGetFloatValue("//root/Cursor/H", ref Cursor.h); @@ -832,9 +817,7 @@ namespace Vocaluxe.Base writer.WriteElementString("H", Cursor.h.ToString("#0.000")); if (Cursor.color.Length > 0) - { writer.WriteElementString("Color", Cursor.color); - } else { writer.WriteElementString("R", Cursor.r.ToString("#0.000")); @@ -922,4 +905,4 @@ namespace Vocaluxe.Base } #endregion Color Handling } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CUtility.cs b/Vocaluxe/Base/CUtility.cs index a136e6cf..da8f9034 100644 --- a/Vocaluxe/Base/CUtility.cs +++ b/Vocaluxe/Base/CUtility.cs @@ -8,9 +8,9 @@ namespace Vocaluxe.Base { static class CTime { - private static Stopwatch _Stopwatch = new Stopwatch(); - private static float _fps = 0.0f; - private static double nanosecPerTick = (1000.0 * 1000.0 * 1000.0) / Stopwatch.Frequency; + private static readonly Stopwatch _Stopwatch = new Stopwatch(); + private static float _fps; + private static readonly double nanosecPerTick = (1000.0 * 1000.0 * 1000.0) / Stopwatch.Frequency; public static void Reset() { @@ -22,7 +22,6 @@ namespace Vocaluxe.Base _Stopwatch.Start(); } - public static void Restart() { Reset(); @@ -42,7 +41,7 @@ namespace Vocaluxe.Base if (Stopwatch.IsHighResolution && ticks != 0) return (float)((nanosecPerTick * ticks) / (1000.0 * 1000.0)); else - return (float)_Stopwatch.ElapsedMilliseconds; + return _Stopwatch.ElapsedMilliseconds; } else return 0f; @@ -53,14 +52,11 @@ namespace Vocaluxe.Base float ms = GetMilliseconds(); if (ms > 0) - { _fps = 1 / ms; - } return _fps * 1000f; } - public static double GetFPS() { return _fps * 1000f; @@ -69,10 +65,10 @@ namespace Vocaluxe.Base class CKeys { - private List _KeysPool; - private List _ActualPool; + private readonly List _KeysPool; + private readonly List _ActualPool; - private Object _CopyLock = new Object(); + private readonly Object _CopyLock = new Object(); private bool _ModALT; private bool _ModCTRL; @@ -80,8 +76,7 @@ namespace Vocaluxe.Base private bool _KeyPressed; private Keys _Keys; private Char _char; - private System.Diagnostics.Stopwatch _timer; - + private readonly Stopwatch _timer; public CKeys() { @@ -94,7 +89,7 @@ namespace Vocaluxe.Base _KeysPool = new List(); _ActualPool = new List(); - _timer = new System.Diagnostics.Stopwatch(); + _timer = new Stopwatch(); } private void Add(bool alt, bool shift, bool ctrl, bool pressed, char unicode, Keys key) @@ -115,12 +110,9 @@ namespace Vocaluxe.Base { _KeysPool.Add(pool); } - catch (Exception) - { - - } + catch (Exception) {} } - + _timer.Reset(); _timer.Start(); } @@ -139,7 +131,6 @@ namespace Vocaluxe.Base _ModALT = ((keys & Keys.Alt) == Keys.Alt); _ModCTRL = ((keys & Keys.Control) == Keys.Control); } - public void KeyDown(KeyEventArgs e) { @@ -162,7 +153,7 @@ namespace Vocaluxe.Base public void KeyPress(KeyPressEventArgs e) { CheckModifiers(); - + Add(_ModALT, _ModSHIFT, _ModCTRL, true, e.KeyChar, Keys.None); _char = e.KeyChar; _KeyPressed = true; @@ -182,7 +173,8 @@ namespace Vocaluxe.Base Del(0); return true; } - else return false; + else + return false; } public void CopyEvents() @@ -190,30 +182,27 @@ namespace Vocaluxe.Base lock (_CopyLock) { foreach (KeyEvent e in _KeysPool) - { _ActualPool.Add(e); - } _KeysPool.Clear(); } } - } class CMouse { - private List _EventsPool; - private List _CurrentPool; + private readonly List _EventsPool; + private readonly List _CurrentPool; - private int _x = 0; - private int _y = 0; - - private Object _CopyLock = new Object(); + private int _x; + private int _y; + + private readonly Object _CopyLock = new Object(); private bool _ModALT; private bool _ModCTRL; private bool _ModSHIFT; - private System.Diagnostics.Stopwatch _timer; + private readonly Stopwatch _timer; public int X { @@ -236,19 +225,19 @@ namespace Vocaluxe.Base _EventsPool = new List(); _CurrentPool = new List(); - _timer = new System.Diagnostics.Stopwatch(); + _timer = new Stopwatch(); } private void Add(bool alt, bool shift, bool ctrl, int x, int y, bool lb, bool ld, bool rb, int wheel, bool lbh, bool rbh, bool mb, bool mbh) { - x = (int)((float)x * (float)CSettings.iRenderW / (float)CDraw.GetScreenWidth()); - y = (int)((float)y * (float)CSettings.iRenderH / (float)CDraw.GetScreenHeight()); + x = (int)(x * (float)CSettings.iRenderW / CDraw.GetScreenWidth()); + y = (int)(y * (float)CSettings.iRenderH / CDraw.GetScreenHeight()); MouseEvent pool = new MouseEvent(ESender.Mouse, alt, shift, ctrl, x, y, lb, ld, rb, -wheel / 120, lbh, rbh, mb, mbh); lock (_CopyLock) { - _EventsPool.Add(pool); + _EventsPool.Add(pool); } _x = x; _y = y; @@ -302,9 +291,7 @@ namespace Vocaluxe.Base } } else - { _timer.Reset(); - } Add(_ModALT, _ModSHIFT, _ModCTRL, e.X, e.Y, lb, ld, e.Button == MouseButtons.Right, e.Delta, false, false, e.Button == MouseButtons.Middle, false); @@ -324,7 +311,8 @@ namespace Vocaluxe.Base Del(0); return true; } - else return false; + else + return false; } public void CopyEvents() @@ -332,12 +320,9 @@ namespace Vocaluxe.Base lock (_CopyLock) { foreach (MouseEvent e in _EventsPool) - { _CurrentPool.Add(e); - } _EventsPool.Clear(); } } - } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CVideo.cs b/Vocaluxe/Base/CVideo.cs index e3c012d6..d3167b0b 100644 --- a/Vocaluxe/Base/CVideo.cs +++ b/Vocaluxe/Base/CVideo.cs @@ -95,7 +95,6 @@ namespace Vocaluxe.Base { _VideoDecoder.Update(); } - #endregion Interface #endregion VideoDecoder @@ -105,7 +104,7 @@ namespace Vocaluxe.Base { private STexture _VideoTexture; private int _VideoStream; - private Stopwatch _VideoTimer; + private readonly Stopwatch _VideoTimer; private bool _Finished; private bool _Loaded; @@ -155,7 +154,6 @@ namespace Vocaluxe.Base { if (!_Finished) { - float VideoTime = _VideoTimer.ElapsedMilliseconds / 1000f; _Finished = CVideo.VdFinished(_VideoStream); @@ -196,4 +194,4 @@ namespace Vocaluxe.Base _VideoTimer.Reset(); } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CWebcam.cs b/Vocaluxe/Base/CWebcam.cs index e80bbaff..8d481d65 100644 --- a/Vocaluxe/Base/CWebcam.cs +++ b/Vocaluxe/Base/CWebcam.cs @@ -1,5 +1,4 @@ using System.Drawing; - using Vocaluxe.Lib.Webcam; using VocaluxeLib.Menu; @@ -69,4 +68,4 @@ namespace Vocaluxe.Base return _Webcam.GetDevices(); } } -} +} \ No newline at end of file diff --git a/Vocaluxe/GameModes/CGameMode.cs b/Vocaluxe/GameModes/CGameMode.cs index 2e922ad3..4726ff73 100644 --- a/Vocaluxe/GameModes/CGameMode.cs +++ b/Vocaluxe/GameModes/CGameMode.cs @@ -1,5 +1,4 @@ using System.Collections.Generic; - using Vocaluxe.Base; using VocaluxeLib.Menu; using VocaluxeLib.Menu.SongMenu; @@ -35,9 +34,7 @@ namespace Vocaluxe.GameModes public virtual EGameMode GetCurrentGameMode() { if (_CurrentSong >= 0 && _CurrentSong < _SongQueque.Count) - { return _SongQueque[_CurrentSong].GameMode; - } return EGameMode.TR_GAMEMODE_NORMAL; } @@ -208,7 +205,7 @@ namespace Vocaluxe.GameModes public virtual EGameMode GetGameMode(int Num) { - if(Num - 1 < _SongQueque.Count && Num > -1) + if (Num - 1 < _SongQueque.Count && Num > -1) return _SongQueque[Num].GameMode; return EGameMode.TR_GAMEMODE_NORMAL; @@ -220,8 +217,6 @@ namespace Vocaluxe.GameModes } #endregion Implementation - protected virtual void SongManipulation(int SongIndex) - { - } + protected virtual void SongManipulation(int SongIndex) {} } -} +} \ No newline at end of file diff --git a/Vocaluxe/GameModes/CGameModeNormal.cs b/Vocaluxe/GameModes/CGameModeNormal.cs index 9151290f..0178569b 100644 --- a/Vocaluxe/GameModes/CGameModeNormal.cs +++ b/Vocaluxe/GameModes/CGameModeNormal.cs @@ -1,5 +1,4 @@ - -namespace Vocaluxe.GameModes +namespace Vocaluxe.GameModes { // Nomal singing class CGameModeNormal : CGameMode @@ -11,4 +10,4 @@ namespace Vocaluxe.GameModes _Initialized = true; } } -} +} \ No newline at end of file diff --git a/Vocaluxe/GameModes/IGameMode.cs b/Vocaluxe/GameModes/IGameMode.cs index 72057f55..c581f2ce 100644 --- a/Vocaluxe/GameModes/IGameMode.cs +++ b/Vocaluxe/GameModes/IGameMode.cs @@ -20,7 +20,7 @@ namespace Vocaluxe.GameModes void NextRound(SPlayer[] Player); bool IsFinished(); int GetCurrentRoundNr(); - + CPoints GetPoints(); int GetNumSongs(); @@ -28,4 +28,4 @@ namespace Vocaluxe.GameModes CSong GetSong(int Num); EGameMode GetGameMode(int Num); } -} +} \ No newline at end of file diff --git a/Vocaluxe/GlobalSuppressions.cs b/Vocaluxe/GlobalSuppressions.cs index f07fdadf..5f370c52 100644 --- a/Vocaluxe/GlobalSuppressions.cs +++ b/Vocaluxe/GlobalSuppressions.cs @@ -8,23 +8,53 @@ // "Meldung(en) unterdrücken", und klicken Sie auf "In Projektunterdrückungsdatei". // Sie müssen dieser Datei nicht manuell Unterdrückungen hinzufügen. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom", Scope = "member", Target = "Vocaluxe.MainProgram.#AssemblyResolver(System.Object,System.ResolveEventArgs)")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Objekte verwerfen, bevor Bereich verloren geht", Scope = "member", Target = "Vocaluxe.Lib.Draw.CDrawWinForm.#ColorizeBitmap(System.Drawing.Bitmap,Vocaluxe.Menu.SColorF)")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Objekte verwerfen, bevor Bereich verloren geht", Scope = "member", Target = "Vocaluxe.Lib.Draw.CDrawWinForm.#CopyScreen(Vocaluxe.Menu.STexture&)")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Objekte verwerfen, bevor Bereich verloren geht", Scope = "member", Target = "Vocaluxe.Base.CGlyph.#.ctor(System.Char,System.Single)")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Objekte verwerfen, bevor Bereich verloren geht", Scope = "member", Target = "Vocaluxe.Lib.Draw.CDirect3D.#AddTexture(System.Drawing.Bitmap,System.String)")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Objekte verwerfen, bevor Bereich verloren geht", Scope = "member", Target = "Vocaluxe.Lib.Draw.CDirect3D.#AddTexture(System.Int32,System.Int32,System.Byte[]&)")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Objekte verwerfen, bevor Bereich verloren geht", Scope = "member", Target = "Vocaluxe.Lib.Draw.CDirect3D.#CopyScreen()")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Scope = "type", Target = "Vocaluxe.Lib.Input.WiiMote.InputReport")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Scope = "type", Target = "PortAudioSharp.PortAudio+PaDeviceIndex")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Scope = "type", Target = "PortAudioSharp.PortAudio+PaSampleFormat")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Scope = "type", Target = "PortAudioSharp.PortAudio+PaStreamCallbackFlags")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "Vocaluxe.Lib.Video.Gstreamer.CGstreamerVideoWrapper.#GetFrame(System.Int32,System.Single)")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "Vocaluxe.Lib.Input.CHIDAPI.#ReadTimeout(System.IntPtr,System.Byte[]&,System.Int32,System.Int32)")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "Vocaluxe.Lib.Input.CHIDAPI.#Read(System.IntPtr,System.Byte[]&,System.Int32)")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "PortAudioSharp.PortAudio.#Pa_GetVersionText()")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "PortAudioSharp.PortAudio.#Pa_GetErrorText(PortAudioSharp.PortAudio+PaError)")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "PortAudioSharp.PortAudio.#Pa_GetHostApiInfo(System.Int32)")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "PortAudioSharp.PortAudio.#Pa_GetLastHostErrorInfo()")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "PortAudioSharp.PortAudio.#Pa_GetDeviceInfo(System.Int32)")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "PortAudioSharp.PortAudio.#Pa_GetStreamInfo(System.IntPtr)")] +using System.Diagnostics.CodeAnalysis; + +[assembly: + SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom", Scope = "member", + Target = "Vocaluxe.MainProgram.#AssemblyResolver(System.Object,System.ResolveEventArgs)")] +[assembly: + SuppressMessage("Microsoft.Reliability", "CA2000:Objekte verwerfen, bevor Bereich verloren geht", Scope = "member", + Target = "Vocaluxe.Lib.Draw.CDrawWinForm.#ColorizeBitmap(System.Drawing.Bitmap,Vocaluxe.Menu.SColorF)")] +[assembly: + SuppressMessage("Microsoft.Reliability", "CA2000:Objekte verwerfen, bevor Bereich verloren geht", Scope = "member", + Target = "Vocaluxe.Lib.Draw.CDrawWinForm.#CopyScreen(Vocaluxe.Menu.STexture&)")] +[assembly: + SuppressMessage("Microsoft.Reliability", "CA2000:Objekte verwerfen, bevor Bereich verloren geht", Scope = "member", + Target = "Vocaluxe.Base.CGlyph.#.ctor(System.Char,System.Single)")] +[assembly: + SuppressMessage("Microsoft.Reliability", "CA2000:Objekte verwerfen, bevor Bereich verloren geht", Scope = "member", + Target = "Vocaluxe.Lib.Draw.CDirect3D.#AddTexture(System.Drawing.Bitmap,System.String)")] +[assembly: + SuppressMessage("Microsoft.Reliability", "CA2000:Objekte verwerfen, bevor Bereich verloren geht", Scope = "member", + Target = "Vocaluxe.Lib.Draw.CDirect3D.#AddTexture(System.Int32,System.Int32,System.Byte[]&)")] +[assembly: SuppressMessage("Microsoft.Reliability", "CA2000:Objekte verwerfen, bevor Bereich verloren geht", Scope = "member", Target = "Vocaluxe.Lib.Draw.CDirect3D.#CopyScreen()") +] +[assembly: SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Scope = "type", Target = "Vocaluxe.Lib.Input.WiiMote.InputReport")] +[assembly: SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Scope = "type", Target = "PortAudioSharp.PortAudio+PaDeviceIndex")] +[assembly: SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Scope = "type", Target = "PortAudioSharp.PortAudio+PaSampleFormat")] +[assembly: SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Scope = "type", Target = "PortAudioSharp.PortAudio+PaStreamCallbackFlags")] +[assembly: + SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", + Target = "Vocaluxe.Lib.Video.Gstreamer.CGstreamerVideoWrapper.#GetFrame(System.Int32,System.Single)")] +[assembly: + SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", + Target = "Vocaluxe.Lib.Input.CHIDAPI.#ReadTimeout(System.IntPtr,System.Byte[]&,System.Int32,System.Int32)")] +[assembly: + SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", + Target = "Vocaluxe.Lib.Input.CHIDAPI.#Read(System.IntPtr,System.Byte[]&,System.Int32)")] +[assembly: SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "PortAudioSharp.PortAudio.#Pa_GetVersionText()")] +[assembly: + SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", + Target = "PortAudioSharp.PortAudio.#Pa_GetErrorText(PortAudioSharp.PortAudio+PaError)")] +[assembly: + SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", + Target = "PortAudioSharp.PortAudio.#Pa_GetHostApiInfo(System.Int32)")] +[assembly: + SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "PortAudioSharp.PortAudio.#Pa_GetLastHostErrorInfo()")] +[assembly: + SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", + Target = "PortAudioSharp.PortAudio.#Pa_GetDeviceInfo(System.Int32)")] +[assembly: + SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", + Target = "PortAudioSharp.PortAudio.#Pa_GetStreamInfo(System.IntPtr)")] \ No newline at end of file diff --git a/Vocaluxe/Lib/Draw/CDirect3D.cs b/Vocaluxe/Lib/Draw/CDirect3D.cs index ce9bd0b5..949b780b 100644 --- a/Vocaluxe/Lib/Draw/CDirect3D.cs +++ b/Vocaluxe/Lib/Draw/CDirect3D.cs @@ -1,4 +1,6 @@ -using SlimDX; +using System.Drawing.Drawing2D; +using System.Threading; +using SlimDX; using SlimDX.Direct3D9; using System; using System.Collections.Generic; @@ -16,50 +18,48 @@ namespace Vocaluxe.Lib.Draw class CDirect3D : Form, IDraw { #region private vars - - private CKeys _Keys; - private CMouse _Mouse; + private readonly CKeys _Keys; + private readonly CMouse _Mouse; private bool _Run; - private Direct3D _D3D; - private Device _Device = null; - private PresentParameters _PresentParameters; + private readonly Direct3D _D3D; + private readonly Device _Device; + private readonly PresentParameters _PresentParameters; - private bool _fullscreen = false; + private bool _fullscreen; private Size _OldSize; private Size _SizeBeforeMinimize; - private Dictionary _Textures; - private Dictionary _D3DTextures; - private List _Queque; - private Queue _IDs; + private readonly Dictionary _Textures; + private readonly Dictionary _D3DTextures; + private readonly List _Queque; + private readonly Queue _IDs; - private Object MutexTexture = new Object(); + private readonly Object MutexTexture = new Object(); private VertexBuffer _VertexBuffer; private IndexBuffer _IndexBuffer; private int h = 1; private int w = 1; - private int y = 0; - private int x = 0; + private int y; + private int x; private STexture _BlankTexture; - private Queue _Vertices; - private Queue _VerticesTextures; - private Queue _VerticesRotationMatrices; - - private bool _NonPowerOf2TextureSupported; + private readonly Queue _Vertices; + private readonly Queue _VerticesTextures; + private readonly Queue _VerticesRotationMatrices; + private readonly bool _NonPowerOf2TextureSupported; #endregion private vars /// - /// Creates a new Instance of the CDirect3D Class + /// Creates a new Instance of the CDirect3D Class /// public CDirect3D() { - this.Icon = new System.Drawing.Icon(Path.Combine(System.Environment.CurrentDirectory, CSettings.sIcon)); + Icon = new Icon(Path.Combine(Environment.CurrentDirectory, CSettings.sIcon)); _Textures = new Dictionary(); _D3DTextures = new Dictionary(); _Queque = new List(); @@ -71,7 +71,7 @@ namespace Vocaluxe.Lib.Draw _Vertices = new Queue(); _VerticesTextures = new Queue(); - _VerticesRotationMatrices = new Queue(); + _VerticesRotationMatrices = new Queue(); _Keys = new CKeys(); try @@ -81,30 +81,30 @@ namespace Vocaluxe.Lib.Draw catch (Direct3D9NotFoundException e) { MessageBox.Show("No DirectX runtimes were found, please download and install them " + - "from http://www.microsoft.com/download/en/details.aspx?id=8109", - CSettings.sProgramName, MessageBoxButtons.OK, MessageBoxIcon.Error); + "from http://www.microsoft.com/download/en/details.aspx?id=8109", + CSettings.sProgramName, MessageBoxButtons.OK, MessageBoxIcon.Error); CLog.LogError(e.Message + " - No DirectX runtimes were found, please download and install them from http://www.microsoft.com/download/en/details.aspx?id=8109"); Environment.Exit(Environment.ExitCode); } - this.Paint += new PaintEventHandler(this.OnPaintEvent); - this.Closing += new CancelEventHandler(this.OnClosingEvent); - this.Resize += new EventHandler(this.OnResizeEvent); + Paint += OnPaintEvent; + Closing += OnClosingEvent; + Resize += OnResizeEvent; - this.KeyDown += new KeyEventHandler(this.OnKeyDown); - this.PreviewKeyDown += new PreviewKeyDownEventHandler(this.OnPreviewKeyDown); - this.KeyPress += new KeyPressEventHandler(this.OnKeyPress); - this.KeyUp += new KeyEventHandler(this.OnKeyUp); + KeyDown += OnKeyDown; + PreviewKeyDown += OnPreviewKeyDown; + KeyPress += OnKeyPress; + KeyUp += OnKeyUp; _Mouse = new CMouse(); - this.MouseMove += new MouseEventHandler(this.OnMouseMove); - this.MouseWheel += new MouseEventHandler(this.OnMouseWheel); - this.MouseDown += new MouseEventHandler(this.OnMouseDown); - this.MouseUp += new MouseEventHandler(this.OnMouseUp); - this.MouseLeave += new EventHandler(this.OnMouseLeave); - this.MouseEnter += new EventHandler(this.OnMouseEnter); + MouseMove += OnMouseMove; + MouseWheel += OnMouseWheel; + MouseDown += OnMouseDown; + MouseUp += OnMouseUp; + MouseLeave += OnMouseLeave; + MouseEnter += OnMouseEnter; - this.ClientSize = new Size(CConfig.ScreenW, CConfig.ScreenH); + ClientSize = new Size(CConfig.ScreenW, CConfig.ScreenH); _SizeBeforeMinimize = ClientSize; _PresentParameters = new PresentParameters(); @@ -117,6 +117,7 @@ namespace Vocaluxe.Lib.Draw _PresentParameters.MultisampleQuality = 0; //Apply antialiasing and check if antialiasing mode is supported + #region Antialiasing int quality = 1; MultisampleType msType; @@ -132,7 +133,7 @@ namespace Vocaluxe.Lib.Draw msType = MultisampleType.EightSamples; break; case EAntiAliasingModes.x16: - case EAntiAliasingModes.x32://x32 is not supported, fallback to x16 + case EAntiAliasingModes.x32: //x32 is not supported, fallback to x16 msType = MultisampleType.SixteenSamples; break; default: @@ -140,12 +141,14 @@ namespace Vocaluxe.Lib.Draw break; } - if (!_D3D.CheckDeviceMultisampleType(_D3D.Adapters.DefaultAdapter.Adapter, DeviceType.Hardware, _D3D.Adapters.DefaultAdapter.CurrentDisplayMode.Format, false, msType, out quality)) + if ( + !_D3D.CheckDeviceMultisampleType(_D3D.Adapters.DefaultAdapter.Adapter, DeviceType.Hardware, _D3D.Adapters.DefaultAdapter.CurrentDisplayMode.Format, false, msType, + out quality)) { CLog.LogError("[Direct3D] This AAMode is not supported by this device or driver, fallback to no AA"); msType = MultisampleType.None; quality = 1; - } + } _PresentParameters.Multisample = msType; _PresentParameters.MultisampleQuality = quality - 1; @@ -180,26 +183,21 @@ namespace Vocaluxe.Lib.Draw if (_Device == null || _Device.Disposed) { MessageBox.Show("Something went wrong during device creating, please check if your DirectX redistributables " + - "and graphic card drivers are up to date. You can download the DirectX runtimes at http://www.microsoft.com/download/en/details.aspx?id=8109", - CSettings.sProgramName, MessageBoxButtons.OK, MessageBoxIcon.Error); - CLog.LogError("Something went wrong during device creating, please check if your DirectX redistributables and grafic card drivers are up to date. You can download the DirectX runtimes at http://www.microsoft.com/download/en/details.aspx?id=8109"); + "and graphic card drivers are up to date. You can download the DirectX runtimes at http://www.microsoft.com/download/en/details.aspx?id=8109", + CSettings.sProgramName, MessageBoxButtons.OK, MessageBoxIcon.Error); + CLog.LogError( + "Something went wrong during device creating, please check if your DirectX redistributables and grafic card drivers are up to date. You can download the DirectX runtimes at http://www.microsoft.com/download/en/details.aspx?id=8109"); Environment.Exit(Environment.ExitCode); } } - this.CenterToScreen(); + CenterToScreen(); } #region form events - private void OnPaintEvent(object sender, PaintEventArgs e) - { + private void OnPaintEvent(object sender, PaintEventArgs e) {} - } - - private void OnResizeEvent(object sender, EventArgs e) - { - - } + private void OnResizeEvent(object sender, EventArgs e) {} private void OnClosingEvent(object sender, CancelEventArgs e) { @@ -241,15 +239,13 @@ namespace Vocaluxe.Lib.Draw #region resize /// - /// Resizes the viewport + /// Resizes the viewport /// private void RResize() { // The window was minimized, so restore it to the last known size if (ClientSize.Width == 0 || ClientSize.Height == 0) - { ClientSize = _SizeBeforeMinimize; - } if (_Run) { h = ClientSize.Height; @@ -257,16 +253,16 @@ namespace Vocaluxe.Lib.Draw y = 0; x = 0; - if ((float)w / (float)h > CSettings.GetRenderAspect()) + if (w / (float)h > CSettings.GetRenderAspect()) { //The windows's width is too big - w = (int)Math.Round((float)h * CSettings.GetRenderAspect()); + w = (int)Math.Round(h * CSettings.GetRenderAspect()); x = (ClientSize.Width - w) / 2; } else { //The windows's height is too big - h = (int)Math.Round((float)w / CSettings.GetRenderAspect()); + h = (int)Math.Round(w / CSettings.GetRenderAspect()); y = (ClientSize.Height - h) / 2; } @@ -287,47 +283,48 @@ namespace Vocaluxe.Lib.Draw } /// - /// Triggers the Fullscreen mode + /// Triggers the Fullscreen mode /// private void EnterFullScreen() { //This currently not using real fullscreen mode but a borderless window //Real fullscreen could be gained setting _PresentParameters.Windowed = true //And calling Reset() and Init() after - _OldSize = this.ClientSize; + _OldSize = ClientSize; int ScreenNr = 0; for (int i = 0; i < Screen.AllScreens.Length; i++) { Screen scr = Screen.AllScreens[i]; - if (scr.Bounds.Top <= this.Top && scr.Bounds.Left <= this.Left) + if (scr.Bounds.Top <= Top && scr.Bounds.Left <= Left) ScreenNr = i; } - this.ClientSize = new Size(Screen.AllScreens[ScreenNr].Bounds.Width, Screen.AllScreens[ScreenNr].Bounds.Height); - this.FormBorderStyle = FormBorderStyle.None; + ClientSize = new Size(Screen.AllScreens[ScreenNr].Bounds.Width, Screen.AllScreens[ScreenNr].Bounds.Height); + FormBorderStyle = FormBorderStyle.None; CenterToScreen(); _fullscreen = true; CConfig.FullScreen = EOffOn.TR_CONFIG_ON; - if (this.WindowState == FormWindowState.Maximized) + if (WindowState == FormWindowState.Maximized) { - this.WindowState = FormWindowState.Normal; + WindowState = FormWindowState.Normal; RResize(); - this.WindowState = FormWindowState.Maximized; + WindowState = FormWindowState.Maximized; } else RResize(); CConfig.SaveConfig(); } + /// - /// Triggers the windowed mode + /// Triggers the windowed mode /// private void LeaveFullScreen() { - this.ClientSize = _OldSize; - this.FormBorderStyle = FormBorderStyle.Sizable; + ClientSize = _OldSize; + FormBorderStyle = FormBorderStyle.Sizable; CenterToScreen(); _fullscreen = false; CConfig.FullScreen = EOffOn.TR_CONFIG_OFF; @@ -371,81 +368,82 @@ namespace Vocaluxe.Lib.Draw #endregion #region keyboard event handlers - - private void OnPreviewKeyDown(object sender, System.Windows.Forms.PreviewKeyDownEventArgs e) + private void OnPreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { OnKeyDown(sender, new KeyEventArgs(e.KeyData)); } - private void OnKeyDown(object sender, System.Windows.Forms.KeyEventArgs e) + private void OnKeyDown(object sender, KeyEventArgs e) { _Keys.KeyDown(e); } - - private void OnKeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) + private void OnKeyPress(object sender, KeyPressEventArgs e) { _Keys.KeyPress(e); } - private void OnKeyUp(object sender, System.Windows.Forms.KeyEventArgs e) + private void OnKeyUp(object sender, KeyEventArgs e) { _Keys.KeyUp(e); } #endregion keyboard event handlers #region implementation + #region main stuff /// - /// Inits the Device + /// Inits the Device /// /// True if it succeeded else false public bool Init() { if (!_Device.Disposed) { - this.Text = CSettings.GetFullVersionText(); - Matrix translate = Matrix.Translation(new Vector3(-CSettings.iRenderW / 2, CSettings.iRenderH / 2, 0)); - Matrix projection = Matrix.OrthoOffCenterLH(-CSettings.iRenderW / 2, CSettings.iRenderW / 2, -CSettings.iRenderH / 2, CSettings.iRenderH / 2, CSettings.zNear, CSettings.zFar); - _VertexBuffer = new VertexBuffer(_Device, CSettings.iVertexBufferElements * (4 * Marshal.SizeOf(typeof(TexturedColoredVertex))), Usage.WriteOnly | Usage.Dynamic, VertexFormat.Position | VertexFormat.Texture1 | VertexFormat.Diffuse, Pool.Default); + Text = CSettings.GetFullVersionText(); + SlimDX.Matrix translate = SlimDX.Matrix.Translation(new Vector3(-CSettings.iRenderW / 2, CSettings.iRenderH / 2, 0)); + SlimDX.Matrix projection = SlimDX.Matrix.OrthoOffCenterLH(-CSettings.iRenderW / 2, CSettings.iRenderW / 2, -CSettings.iRenderH / 2, CSettings.iRenderH / 2, + CSettings.zNear, CSettings.zFar); + _VertexBuffer = new VertexBuffer(_Device, CSettings.iVertexBufferElements * (4 * Marshal.SizeOf(typeof(TexturedColoredVertex))), Usage.WriteOnly | Usage.Dynamic, + VertexFormat.Position | VertexFormat.Texture1 | VertexFormat.Diffuse, Pool.Default); if (_Device.SetStreamSource(0, _VertexBuffer, 0, Marshal.SizeOf(typeof(TexturedColoredVertex))).IsFailure) CLog.LogError("Failed to set stream source"); _Device.VertexDeclaration = TexturedColoredVertex.GetDeclaration(_Device); - if(_Device.SetTransform(TransformState.Projection, projection).IsFailure) + if (_Device.SetTransform(TransformState.Projection, projection).IsFailure) CLog.LogError("Failed to set orthogonal matrix"); - if(_Device.SetTransform(TransformState.World, translate).IsFailure) + if (_Device.SetTransform(TransformState.World, translate).IsFailure) CLog.LogError("Failed to set translation matrix"); - if(_Device.SetRenderState(RenderState.CullMode, Cull.None).IsFailure) + if (_Device.SetRenderState(RenderState.CullMode, Cull.None).IsFailure) CLog.LogError("Failed to set cull mode"); - if(_Device.SetRenderState(RenderState.AlphaBlendEnable, true).IsFailure) + if (_Device.SetRenderState(RenderState.AlphaBlendEnable, true).IsFailure) CLog.LogError("Failed to enable alpha blending"); - if(_Device.SetRenderState(RenderState.Lighting, false).IsFailure) + if (_Device.SetRenderState(RenderState.Lighting, false).IsFailure) CLog.LogError("Failed to disable lighting"); - if(_Device.SetRenderState(RenderState.DestinationBlend, Blend.InverseSourceAlpha).IsFailure) + if (_Device.SetRenderState(RenderState.DestinationBlend, SlimDX.Direct3D9.Blend.InverseSourceAlpha).IsFailure) CLog.LogError("Failed to set destination blend"); - if(_Device.SetRenderState(RenderState.SourceBlend, Blend.SourceAlpha).IsFailure) + if (_Device.SetRenderState(RenderState.SourceBlend, SlimDX.Direct3D9.Blend.SourceAlpha).IsFailure) CLog.LogError("Failed to set source blend"); if (_PresentParameters.Multisample != MultisampleType.None) { - if(_Device.SetRenderState(RenderState.MultisampleAntialias, true).IsFailure) + if (_Device.SetRenderState(RenderState.MultisampleAntialias, true).IsFailure) CLog.LogError("Failed to set antialiasing"); } - if(_Device.SetSamplerState(0, SamplerState.MinFilter, TextureFilter.Linear).IsFailure) + if (_Device.SetSamplerState(0, SamplerState.MinFilter, TextureFilter.Linear).IsFailure) CLog.LogError("Failed to set min filter"); - if(_Device.SetSamplerState(0, SamplerState.MagFilter, TextureFilter.Linear).IsFailure) + if (_Device.SetSamplerState(0, SamplerState.MagFilter, TextureFilter.Linear).IsFailure) CLog.LogError("Failed to set mag filter"); - if(_Device.SetSamplerState(0, SamplerState.MipFilter, TextureFilter.Linear).IsFailure) + if (_Device.SetSamplerState(0, SamplerState.MipFilter, TextureFilter.Linear).IsFailure) CLog.LogError("Failed to set mip filter"); - if(_Device.SetSamplerState(0, SamplerState.AddressU, TextureAddress.Clamp).IsFailure) + if (_Device.SetSamplerState(0, SamplerState.AddressU, TextureAddress.Clamp).IsFailure) CLog.LogError("Failed to set clamping on u"); - if(_Device.SetSamplerState(0, SamplerState.AddressV, TextureAddress.Clamp).IsFailure) + if (_Device.SetSamplerState(0, SamplerState.AddressV, TextureAddress.Clamp).IsFailure) CLog.LogError("Failed to set claming on v"); - if(_Device.SetTextureStageState(0, TextureStage.AlphaArg1, TextureArgument.Texture).IsFailure) + if (_Device.SetTextureStageState(0, TextureStage.AlphaArg1, TextureArgument.Texture).IsFailure) CLog.LogError("Failed to set alpha argument 1"); - if(_Device.SetTextureStageState(0, TextureStage.AlphaArg2, TextureArgument.Diffuse).IsFailure) + if (_Device.SetTextureStageState(0, TextureStage.AlphaArg2, TextureArgument.Diffuse).IsFailure) CLog.LogError("Failed to set alpha argument 2"); - if(_Device.SetTextureStageState(0, TextureStage.AlphaOperation, TextureOperation.Modulate).IsFailure) + if (_Device.SetTextureStageState(0, TextureStage.AlphaOperation, TextureOperation.Modulate).IsFailure) CLog.LogError("Failed to set alpha operation"); Int16[] indices = new Int16[6]; @@ -471,21 +469,21 @@ namespace Vocaluxe.Lib.Draw g.Clear(Color.White); g.Dispose(); _BlankTexture = AddTexture(blankMap); - } return true; } else return false; } + /// - /// Starts the rendering + /// Starts the rendering /// public void MainLoop() { _Run = true; int delay = 0; - this.Show(); + Show(); if (CConfig.FullScreen == EOffOn.TR_CONFIG_ON) { @@ -494,7 +492,7 @@ namespace Vocaluxe.Lib.Draw } //Resize window if aspect ratio is incorrect - if ((float)w / (float)h != CSettings.GetRenderAspect()) + if (w / (float)h != CSettings.GetRenderAspect()) RResize(); while (_Run) @@ -544,17 +542,17 @@ namespace Vocaluxe.Lib.Draw delay = (int)Math.Floor(CConfig.CalcCycleTime() - CTime.GetMilliseconds()); if (delay >= 1 && CConfig.VSync == EOffOn.TR_CONFIG_OFF) - System.Threading.Thread.Sleep(delay); + Thread.Sleep(delay); //Calculate the FPS Rate and restart the timer after a frame CTime.CalculateFPS(); CTime.Restart(); - } + } } - this.Close(); + Close(); } /// - /// Resets the device, all objects in the Direct3D default pool get flushed and need to be recreated + /// Resets the device, all objects in the Direct3D default pool get flushed and need to be recreated /// public void Reset() { @@ -567,7 +565,7 @@ namespace Vocaluxe.Lib.Draw } /// - /// Unloads all Textures and other objects used by Direct3D for rendering + /// Unloads all Textures and other objects used by Direct3D for rendering /// /// public bool Unload() @@ -576,9 +574,7 @@ namespace Vocaluxe.Lib.Draw foreach (KeyValuePair p in _D3DTextures) { if (p.Value != null) - { p.Value.Dispose(); - } } TexturedColoredVertex.GetDeclaration(_Device).Dispose(); @@ -590,7 +586,7 @@ namespace Vocaluxe.Lib.Draw } /// - /// Gets the current viewport width + /// Gets the current viewport width /// /// The current viewport width public int GetScreenWidth() @@ -599,7 +595,7 @@ namespace Vocaluxe.Lib.Draw } /// - /// Gets the current viewport height + /// Gets the current viewport height /// /// The current viewport height public int GetScreenHeight() @@ -608,7 +604,7 @@ namespace Vocaluxe.Lib.Draw } /// - /// Calculates the bounds for a CText object + /// Calculates the bounds for a CText object /// /// The CText object of which the bounds should be calculated for /// RectangleF object containing the bounds @@ -618,7 +614,7 @@ namespace Vocaluxe.Lib.Draw } /// - /// Calculates the bounds for a CText object + /// Calculates the bounds for a CText object /// /// The CText object of which the bounds should be calculated for /// The height of the CText object @@ -632,12 +628,12 @@ namespace Vocaluxe.Lib.Draw } /// - /// Adds a quad a list which will be added and rendered to the vertexbuffer when calling RenderToVertexBuffer to reduce vertexbuffer calls each frame to a minimum + /// Adds a quad a list which will be added and rendered to the vertexbuffer when calling RenderToVertexBuffer to reduce vertexbuffer calls each frame to a minimum /// /// A TexturedColoredVertex array containg 4 vertices /// The texture the vertex should be textured with /// The vertices' rotation - private void AddToVertexBuffer(TexturedColoredVertex[] vertices, Texture tex, Matrix rotation) + private void AddToVertexBuffer(TexturedColoredVertex[] vertices, Texture tex, SlimDX.Matrix rotation) { //The vertexbuffer is full, so we need to flush it before we can continue if (_Vertices.Count >= CSettings.iVertexBufferElements) @@ -651,7 +647,7 @@ namespace Vocaluxe.Lib.Draw } /// - /// Renders the vertex buffer + /// Renders the vertex buffer /// private void RenderVertexBuffer() { @@ -659,7 +655,7 @@ namespace Vocaluxe.Lib.Draw { //The vertex buffer locks are slow actions, its better to lock once per frame and write all vertices to the buffer at once DataStream stream = _VertexBuffer.Lock(0, _Vertices.Count * Marshal.SizeOf(typeof(TexturedColoredVertex)), LockFlags.Discard); - stream.WriteRange(_Vertices.ToArray()); + stream.WriteRange(_Vertices.ToArray()); _VertexBuffer.Unlock(); stream.Dispose(); @@ -681,12 +677,11 @@ namespace Vocaluxe.Lib.Draw _VerticesRotationMatrices.Clear(); } } -#endregion main stuff + #endregion main stuff #region Basic Draw Methods - /// - /// Removes all textures from the screen + /// Removes all textures from the screen /// public void ClearScreen() { @@ -695,8 +690,8 @@ namespace Vocaluxe.Lib.Draw } /// - /// Copies the current frame into a texture - /// A texture holding the current frame + /// Copies the current frame into a texture + /// A texture holding the current frame public STexture CopyScreen() { STexture texture = new STexture(-1); @@ -724,7 +719,7 @@ namespace Vocaluxe.Lib.Draw } /// - /// Copies the current frame into a texture + /// Copies the current frame into a texture /// /// The texture in which the frame is copied to public void CopyScreen(ref STexture Texture) @@ -743,7 +738,7 @@ namespace Vocaluxe.Lib.Draw } /// - /// Creates a Screenshot of the current frame + /// Creates a Screenshot of the current frame /// public void MakeScreenShot() { @@ -766,7 +761,7 @@ namespace Vocaluxe.Lib.Draw } /// - /// Draws a line + /// Draws a line /// /// The alpha value from 0-255 /// The red value from 0-255 @@ -784,7 +779,7 @@ namespace Vocaluxe.Lib.Draw } /// - /// Draws a text string + /// Draws a text string /// /// The text to be drawn /// The text's x-position @@ -796,7 +791,7 @@ namespace Vocaluxe.Lib.Draw } /// - /// Draws a text string + /// Draws a text string /// /// The text to be drawn /// The text's x-position @@ -809,7 +804,7 @@ namespace Vocaluxe.Lib.Draw } /// - /// Draws a colored rectangle + /// Draws a colored rectangle /// /// The color in which the rectangle will be drawn in /// The coordinates in a SRectF struct @@ -819,7 +814,7 @@ namespace Vocaluxe.Lib.Draw } /// - /// Draws reflection of a colored rectangle + /// Draws reflection of a colored rectangle /// /// The color in which the rectangle will be drawn in /// The coordinates in a SRectF struct @@ -829,19 +824,19 @@ namespace Vocaluxe.Lib.Draw { DrawTextureReflection(_BlankTexture, rect, color, rect, space, height); } - #endregion Basic Draw Methods - #region Textures - #region adding + #region Textures + + #region adding /// - /// Adds a texture and stores it in the VRam + /// Adds a texture and stores it in the VRam /// /// The texture's filepath /// A STexture object containing the added texture public STexture AddTexture(string TexturePath) { - if (System.IO.File.Exists(TexturePath)) + if (File.Exists(TexturePath)) { Bitmap bmp; try @@ -869,7 +864,7 @@ namespace Vocaluxe.Lib.Draw } /// - /// Adds a texture and stores it in the Vram + /// Adds a texture and stores it in the Vram /// /// The Bitmap of which the texure will be created from /// The path to the texture @@ -925,22 +920,21 @@ namespace Vocaluxe.Lib.Draw byte[] Data; try { - if (w != bmp.Width || h != bmp.Height) { //Create a new Bitmap with the new sizes bmp2 = new Bitmap(w, h); //Scale the texture Graphics g = Graphics.FromImage(bmp2); - g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; - g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; + g.InterpolationMode = InterpolationMode.HighQualityBicubic; + g.SmoothingMode = SmoothingMode.HighQuality; g.DrawImage(bmp, new Rectangle(0, 0, bmp2.Width, bmp2.Height)); g.Dispose(); bmp = bmp2; } //Fill the new Bitmap with the texture data - BitmapData bmp_data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); + BitmapData bmp_data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); Data = new byte[4 * w * h]; Marshal.Copy(bmp_data.Scan0, Data, 0, Data.Length); bmp.UnlockBits(bmp_data); @@ -955,7 +949,7 @@ namespace Vocaluxe.Lib.Draw } /// - /// Adds a texture and stores it in the Vram + /// Adds a texture and stores it in the Vram /// /// The Bitmap of which the texure will be created from /// A STexture object containing the added texture @@ -971,7 +965,7 @@ namespace Vocaluxe.Lib.Draw return AddTexture(W, H, ref PointerData); } - public STexture AddTexture(int W, int H, ref byte[] Data) + public STexture AddTexture(int W, int H, ref byte[] Data) { STexture texture = new STexture(-1); @@ -1045,12 +1039,11 @@ namespace Vocaluxe.Lib.Draw } return texture; } - #endregion adding #region updating /// - /// Updates the data of a texture + /// Updates the data of a texture /// /// The texture to update /// A Pointer containing the data of which the texture should be updated @@ -1064,7 +1057,7 @@ namespace Vocaluxe.Lib.Draw } /// - /// Updates the data of a texture + /// Updates the data of a texture /// /// The texture to update /// A byte array containing the new texture's data @@ -1114,7 +1107,7 @@ namespace Vocaluxe.Lib.Draw #endregion updating /// - /// Checks if a texture exists + /// Checks if a texture exists /// /// The texture to check /// True if the texture exists @@ -1135,7 +1128,7 @@ namespace Vocaluxe.Lib.Draw } /// - /// Removes a texture from the Vram + /// Removes a texture from the Vram /// /// The texture to be removed public void RemoveTexture(ref STexture Texture) @@ -1156,7 +1149,7 @@ namespace Vocaluxe.Lib.Draw #region drawing /// - /// Draws a texture + /// Draws a texture /// /// The texture to be drawn public void DrawTexture(STexture Texture) @@ -1165,7 +1158,7 @@ namespace Vocaluxe.Lib.Draw } /// - /// Draws a texture + /// Draws a texture /// /// The texture to be drawn /// A SRectF struct containing the destination coordinates @@ -1175,7 +1168,7 @@ namespace Vocaluxe.Lib.Draw } /// - /// Draws a texture + /// Draws a texture /// /// The texture to be drawn /// A SRectF struct containing the destination coordinates @@ -1186,7 +1179,7 @@ namespace Vocaluxe.Lib.Draw } /// - /// Draws a texture + /// Draws a texture /// /// The texture to be drawn /// A SRectF struct containing the destination coordinates @@ -1198,7 +1191,7 @@ namespace Vocaluxe.Lib.Draw } /// - /// Draws a texture + /// Draws a texture /// /// The texture to be drawn /// A SRectF struct containing the destination coordinates @@ -1210,7 +1203,7 @@ namespace Vocaluxe.Lib.Draw } /// - /// Draws a texture + /// Draws a texture /// /// The texture to be drawn /// A SRectF struct containing the destination coordinates @@ -1299,14 +1292,13 @@ namespace Vocaluxe.Lib.Draw } /// - /// Draws a texture + /// Draws a texture /// /// The texture to be drawn /// A SRectF struct containing the destination coordinates /// A SColorF struct containing a color which the texture will be colored in /// A Value ranging from 0 to 1 containing the beginning of the texture /// A Value ranging from 0 to 1 containing the ending of the texture - public void DrawTexture(STexture Texture, SRectF rect, SColorF color, float begin, float end) { if (_TextureExists(ref Texture)) @@ -1342,7 +1334,7 @@ namespace Vocaluxe.Lib.Draw } /// - /// Draws a reflection of a texture + /// Draws a reflection of a texture /// /// The texture of which a reflection should be drawn /// A SRectF struct containing the destination coordinates @@ -1449,7 +1441,7 @@ namespace Vocaluxe.Lib.Draw } /// - /// Gets the count of current textures + /// Gets the count of current textures /// /// The amount of textures public int TextureCount() @@ -1457,11 +1449,12 @@ namespace Vocaluxe.Lib.Draw return _Textures.Count; } #endregion Textures + #endregion implementation #region utility /// - /// Calculates the next power of two if the device has the POW2 flag set + /// Calculates the next power of two if the device has the POW2 flag set /// /// The value of which the next power of two will be calculated /// The next power of two @@ -1469,30 +1462,32 @@ namespace Vocaluxe.Lib.Draw { if (!_NonPowerOf2TextureSupported) { - if (n < 0) throw new ArgumentOutOfRangeException("n", "Must be positive."); - return (float)System.Math.Pow(2, System.Math.Ceiling(System.Math.Log((double)n, 2))); + if (n < 0) + throw new ArgumentOutOfRangeException("n", "Must be positive."); + return (float)Math.Pow(2, Math.Ceiling(Math.Log(n, 2))); } - else return n; + else + return n; } - private Matrix CalculateRotationMatrix(float rot, float rx1, float rx2, float ry1, float ry2) + private SlimDX.Matrix CalculateRotationMatrix(float rot, float rx1, float rx2, float ry1, float ry2) { - Matrix originTranslation = Matrix.Translation(new Vector3(-CSettings.iRenderW / 2, CSettings.iRenderH / 2, 0)); + SlimDX.Matrix originTranslation = SlimDX.Matrix.Translation(new Vector3(-CSettings.iRenderW / 2, CSettings.iRenderH / 2, 0)); if (rot != 0) { float rotation = rot * (float)Math.PI / 180; float centerX = (rx1 + rx2) / 2f; float centerY = -(ry1 + ry2) / 2f; - Matrix translationA = Matrix.Translation(-centerX, -centerY, 0); - Matrix rotationMat = Matrix.RotationZ(-rotation); - Matrix translationB = Matrix.Translation(centerX, centerY, 0); + SlimDX.Matrix translationA = SlimDX.Matrix.Translation(-centerX, -centerY, 0); + SlimDX.Matrix rotationMat = SlimDX.Matrix.RotationZ(-rotation); + SlimDX.Matrix translationB = SlimDX.Matrix.Translation(centerX, centerY, 0); //Multiplicate the matrices to get the real world matrix, //First shift the texture into the center //Rotate it and shift it back to the origin position //Apply the originTranslation after - Matrix result = translationA * rotationMat * translationB * originTranslation; + SlimDX.Matrix result = translationA * rotationMat * translationB * originTranslation; return result; } return originTranslation; @@ -1504,12 +1499,12 @@ namespace Vocaluxe.Lib.Draw { private static VertexDeclaration sDeclaration; public static VertexElement[] Elements = - { - new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0), - new VertexElement(0, sizeof(float) *3, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0), - new VertexElement(0, sizeof(float) * 3 + sizeof(float)*2, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0), - VertexElement.VertexDeclarationEnd - }; + { + new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0), + new VertexElement(0, sizeof(float) * 3, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0), + new VertexElement(0, sizeof(float) * 3 + sizeof(float) * 2, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0), + VertexElement.VertexDeclarationEnd + }; public Vector3 Position; public Vector2 Texture; @@ -1517,21 +1512,19 @@ namespace Vocaluxe.Lib.Draw public TexturedColoredVertex(Vector3 position, Vector2 texture, int color) { - this.Position = position; - this.Texture = texture; - this.Color = color; + Position = position; + Texture = texture; + Color = color; } public static VertexDeclaration GetDeclaration(Device device) { if (sDeclaration == null || sDeclaration.Disposed) - { sDeclaration = new VertexDeclaration(device, Elements); - } return sDeclaration; } } #endregion TexturedColoredVertex } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Draw/CDrawWinForm.cs b/Vocaluxe/Lib/Draw/CDrawWinForm.cs index debcc28d..fef172ef 100644 --- a/Vocaluxe/Lib/Draw/CDrawWinForm.cs +++ b/Vocaluxe/Lib/Draw/CDrawWinForm.cs @@ -5,6 +5,7 @@ using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Runtime.InteropServices; +using System.Threading; using System.Windows.Forms; using Vocaluxe.Base; using VocaluxeLib.Menu; @@ -14,50 +15,50 @@ namespace Vocaluxe.Lib.Draw class CDrawWinForm : Form, IDraw { private bool _Run; - private Bitmap _backbuffer; - private Graphics _g; - private bool _fullscreen = false; - - private CKeys _Keys; - private CMouse _Mouse; + private readonly Bitmap _backbuffer; + private readonly Graphics _g; + private bool _fullscreen; + + private readonly CKeys _Keys; + private readonly CMouse _Mouse; private FormBorderStyle _brdStyle; private bool _topMost; private Rectangle _bounds; - - private List _Textures; - private List _Bitmaps; - private Color ClearColor = Color.DarkBlue; + private readonly List _Textures; + private readonly List _Bitmaps; + + private readonly Color ClearColor = Color.DarkBlue; public CDrawWinForm() { - this.Icon = new System.Drawing.Icon(Path.Combine(System.Environment.CurrentDirectory, CSettings.sIcon)); + Icon = new Icon(Path.Combine(Environment.CurrentDirectory, CSettings.sIcon)); _Textures = new List(); _Bitmaps = new List(); _Keys = new CKeys(); _Mouse = new CMouse(); - this.ClientSize = new Size(1280, 720); + ClientSize = new Size(1280, 720); - this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.Opaque, true); + SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.Opaque, true); // Create the backbuffer _backbuffer = new Bitmap(CSettings.iRenderW, CSettings.iRenderH); _g = Graphics.FromImage(_backbuffer); _g.Clear(Color.DarkBlue); - this.Paint += new PaintEventHandler(this.OnPaintEvent); - this.Closing += new CancelEventHandler(this.OnClosingEvent); - this.KeyDown += new KeyEventHandler(this.OnKeyDownEvent); - this.KeyPress += new KeyPressEventHandler(this.OnKeyPressEvent); - this.KeyUp += new KeyEventHandler(this.OnKeyUpEvent); - this.Resize += new EventHandler(this.OnResizeEvent); + Paint += OnPaintEvent; + Closing += OnClosingEvent; + KeyDown += OnKeyDownEvent; + KeyPress += OnKeyPressEvent; + KeyUp += OnKeyUpEvent; + Resize += OnResizeEvent; - this.MouseMove += new MouseEventHandler(this.OnMouseMove); - this.MouseDown += new MouseEventHandler(this.OnMouseDown); - this.MouseUp += new MouseEventHandler(this.OnMouseUp); + MouseMove += OnMouseMove; + MouseDown += OnMouseDown; + MouseUp += OnMouseUp; FlipBuffer(); Cursor.Show(); @@ -71,33 +72,29 @@ namespace Vocaluxe.Lib.Draw private void DrawBuffer() { - Graphics gFrontBuffer = Graphics.FromHwnd(this.Handle); - int h = this.ClientSize.Height; - int w = this.ClientSize.Width; + Graphics gFrontBuffer = Graphics.FromHwnd(Handle); + int h = ClientSize.Height; + int w = ClientSize.Width; int y = 0; int x = 0; - if ((float)this.ClientSize.Width / (float)this.ClientSize.Height > CSettings.GetRenderAspect()) + if (ClientSize.Width / (float)ClientSize.Height > CSettings.GetRenderAspect()) { - w = (int)Math.Round((float)this.ClientSize.Height * CSettings.GetRenderAspect()); - x = (this.ClientSize.Width - w) / 2; + w = (int)Math.Round(ClientSize.Height * CSettings.GetRenderAspect()); + x = (ClientSize.Width - w) / 2; } else { - h = (int)Math.Round((float)this.ClientSize.Width / CSettings.GetRenderAspect()); - y = (this.ClientSize.Height - h) / 2; + h = (int)Math.Round(ClientSize.Width / CSettings.GetRenderAspect()); + y = (ClientSize.Height - h) / 2; } gFrontBuffer.DrawImage(_backbuffer, new Rectangle(x, y, w, h), new Rectangle(0, 0, _backbuffer.Width, _backbuffer.Height), GraphicsUnit.Pixel); } - private void OnPaintEvent(object sender, PaintEventArgs e) - { - - } + private void OnPaintEvent(object sender, PaintEventArgs e) {} #region FullScreenStuff - private void ToggleFullScreen() { if (!_fullscreen) @@ -142,7 +139,7 @@ namespace Vocaluxe.Lib.Draw private void OnResizeEvent(object sender, EventArgs e) { - Graphics gFrontBuffer = Graphics.FromHwnd(this.Handle); + Graphics gFrontBuffer = Graphics.FromHwnd(Handle); gFrontBuffer.Clear(Color.Black); } @@ -172,17 +169,17 @@ namespace Vocaluxe.Lib.Draw } } - private void OnKeyDownEvent(object sender, System.Windows.Forms.KeyEventArgs e) + private void OnKeyDownEvent(object sender, KeyEventArgs e) { _Keys.KeyDown(e); } - private void OnKeyPressEvent(object sender, System.Windows.Forms.KeyPressEventArgs e) + private void OnKeyPressEvent(object sender, KeyPressEventArgs e) { _Keys.KeyPress(e); } - private void OnKeyUpEvent(object sender, System.Windows.Forms.KeyEventArgs e) + private void OnKeyUpEvent(object sender, KeyEventArgs e) { _Keys.KeyUp(e); } @@ -206,7 +203,7 @@ namespace Vocaluxe.Lib.Draw public bool Init() { - this.Text = CSettings.GetFullVersionText(); + Text = CSettings.GetFullVersionText(); return true; } @@ -214,7 +211,7 @@ namespace Vocaluxe.Lib.Draw { _Run = true; int delay = 0; - this.Show(); + Show(); if (CConfig.FullScreen == EOffOn.TR_CONFIG_ON) { @@ -230,7 +227,7 @@ namespace Vocaluxe.Lib.Draw { _Run = _Run && CGraphics.Draw(); _Run = CGraphics.UpdateGameLogic(_Keys, _Mouse); - FlipBuffer(); + FlipBuffer(); if ((CSettings.bFullScreen && !_fullscreen) || (!CSettings.bFullScreen && _fullscreen)) ToggleFullScreen(); @@ -239,29 +236,29 @@ namespace Vocaluxe.Lib.Draw delay = (int)Math.Floor(CConfig.CalcCycleTime() - CTime.GetMilliseconds()); if (delay >= 1) - System.Threading.Thread.Sleep(delay); + Thread.Sleep(delay); CTime.CalculateFPS(); CTime.Restart(); } } - this.Close(); + Close(); } public bool Unload() { - this.Dispose(); + Dispose(); return true; } public int GetScreenWidth() { - return this.ClientSize.Width; + return ClientSize.Width; } public int GetScreenHeight() { - return this.ClientSize.Height; + return ClientSize.Height; } public RectangleF GetTextBounds(CText text) @@ -309,16 +306,14 @@ namespace Vocaluxe.Lib.Draw Texture = CopyScreen(); } else - { _Bitmaps[Texture.index] = new Bitmap(_backbuffer); - } } public void MakeScreenShot() { string file = "Screenshot_"; string path = Path.Combine(Environment.CurrentDirectory, CSettings.sFolderScreenshots); - + int i = 0; while (File.Exists(Path.Combine(path, file + i.ToString("00000") + ".png"))) i++; @@ -343,16 +338,9 @@ namespace Vocaluxe.Lib.Draw CFonts.DrawText(Text, h, x, y, z, new SColorF(1, 1, 1, 1)); } + public void DrawColor(SColorF color, SRectF rect) {} - public void DrawColor(SColorF color, SRectF rect) - { - - } - - public void DrawColorReflection(SColorF color, SRectF rect, float space, float height) - { - - } + public void DrawColorReflection(SColorF color, SRectF rect, float space, float height) {} public STexture AddTexture(Bitmap bmp) { @@ -378,10 +366,10 @@ namespace Vocaluxe.Lib.Draw public STexture AddTexture(string TexturePath) { STexture texture = new STexture(); - if (System.IO.File.Exists(TexturePath)) + if (File.Exists(TexturePath)) { bool found = false; - foreach(STexture tex in _Textures) + foreach (STexture tex in _Textures) { if (tex.TexturePath == TexturePath) { @@ -394,12 +382,10 @@ namespace Vocaluxe.Lib.Draw if (!found) { using (Bitmap bmp = new Bitmap(TexturePath)) - { return AddTexture(bmp); - } } } - + return texture; } @@ -434,7 +420,7 @@ namespace Vocaluxe.Lib.Draw { using (Bitmap bmp = new Bitmap(W, H)) { - BitmapData bmp_data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppArgb); + BitmapData bmp_data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); Marshal.Copy(Data, 0, bmp_data.Scan0, Data.Length); bmp.UnlockBits(bmp_data); return AddTexture(bmp); @@ -451,7 +437,7 @@ namespace Vocaluxe.Lib.Draw if ((Texture.index >= 0) && (_Textures.Count > 0) && (_Bitmaps.Count > Texture.index)) { BitmapData bmp_data = _Bitmaps[Texture.index].LockBits(new Rectangle(0, 0, _Bitmaps[Texture.index].Width, _Bitmaps[Texture.index].Height), - ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppArgb); + ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); Marshal.Copy(Data, 0, bmp_data.Scan0, Data.Length); _Bitmaps[Texture.index].UnlockBits(bmp_data); } @@ -461,41 +447,31 @@ namespace Vocaluxe.Lib.Draw public void DrawTexture(STexture Texture) { if ((Texture.index >= 0) && (_Textures.Count > 0) && (_Bitmaps.Count > Texture.index)) - { - DrawTexture(Texture, Texture.rect, Texture.color); - } + DrawTexture(Texture, Texture.rect, Texture.color); } public void DrawTexture(STexture Texture, SRectF rect) { if ((Texture.index >= 0) && (_Textures.Count > 0) && (_Bitmaps.Count > Texture.index)) - { DrawTexture(Texture, rect, Texture.color); - } } public void DrawTexture(STexture Texture, SRectF rect, SColorF color) { if ((Texture.index >= 0) && (_Textures.Count > 0) && (_Bitmaps.Count > Texture.index)) - { - DrawTexture(Texture, rect, color, rect, false); - } + DrawTexture(Texture, rect, color, rect, false); } public void DrawTexture(STexture Texture, SRectF rect, SColorF color, SRectF bounds) { if ((Texture.index >= 0) && (_Textures.Count > 0) && (_Bitmaps.Count > Texture.index)) - { DrawTexture(Texture, rect, color, bounds, false); - } } public void DrawTexture(STexture Texture, SRectF rect, SColorF color, bool mirrored) { if ((Texture.index >= 0) && (_Textures.Count > 0) && (_Bitmaps.Count > Texture.index)) - { DrawTexture(Texture, rect, color, rect, mirrored); - } } public void DrawTexture(STexture Texture, SRectF rect, SColorF color, SRectF bounds, bool mirrored) @@ -508,14 +484,9 @@ namespace Vocaluxe.Lib.Draw } } - public void DrawTexture(STexture Texture, SRectF rect, SColorF color, float begin, float end) - { + public void DrawTexture(STexture Texture, SRectF rect, SColorF color, float begin, float end) {} - } - - public void DrawTextureReflection(STexture Texture, SRectF rect, SColorF color, SRectF bounds, float space, float height) - { - } + public void DrawTextureReflection(STexture Texture, SRectF rect, SColorF color, SRectF bounds, float space, float height) {} public int TextureCount() { @@ -528,7 +499,6 @@ namespace Vocaluxe.Lib.Draw using (Graphics g = Graphics.FromImage(newBitmap)) { - ColorMatrix cm = new ColorMatrix(); cm.Matrix33 = color.A; cm.Matrix00 = color.R; @@ -541,12 +511,11 @@ namespace Vocaluxe.Lib.Draw ia.SetColorMatrix(cm); g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height), - 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, ia); - + 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, ia); } } return newBitmap; } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Draw/COpenGL.cs b/Vocaluxe/Lib/Draw/COpenGL.cs index 49aba1c5..29e51047 100644 --- a/Vocaluxe/Lib/Draw/COpenGL.cs +++ b/Vocaluxe/Lib/Draw/COpenGL.cs @@ -1,4 +1,7 @@ -using OpenTK; +using System.Drawing.Drawing2D; +using System.Threading; +using OpenTK; +using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using System; using System.Collections.Generic; @@ -27,59 +30,55 @@ namespace Vocaluxe.Lib.Draw public int height; public byte[] data; } - + class COpenGL : Form, IDraw { #region private vars - - private CKeys _Keys; - private CMouse _Mouse; + private readonly CKeys _Keys; + private readonly CMouse _Mouse; private bool _Run; - - GLControl control = null; + + private readonly GLControl control; private SClientRect _restore; - private bool _fullscreen = false; + private bool _fullscreen; - private Dictionary _Textures; - private Queue _IDs; - private List _Queque; + private readonly Dictionary _Textures; + private readonly Queue _IDs; + private readonly List _Queque; - private Object MutexTexture = new Object(); + private readonly Object MutexTexture = new Object(); private int h = 1; private int w = 1; - private int y = 0; - private int x = 0; + private int y; + private int x; - private bool _UsePBO = false; - + private bool _UsePBO; #endregion private vars public COpenGL() { - this.Icon = new System.Drawing.Icon(Path.Combine(System.Environment.CurrentDirectory, CSettings.sIcon)); + Icon = new Icon(Path.Combine(Environment.CurrentDirectory, CSettings.sIcon)); _Textures = new Dictionary(); _Queque = new List(); _IDs = new Queue(1000000); for (int i = 1; i < 1000000; i++) - { _IDs.Enqueue(i); - } //Check AA Mode CConfig.AAMode = (EAntiAliasingModes)CheckAntiAliasingMode((int)CConfig.AAMode); - OpenTK.Graphics.ColorFormat cf = new OpenTK.Graphics.ColorFormat(32); - OpenTK.Graphics.GraphicsMode gm; + ColorFormat cf = new ColorFormat(32); + GraphicsMode gm; bool ok = false; try { - gm = new OpenTK.Graphics.GraphicsMode(cf, 24, 0, (int)CConfig.AAMode); - control = new GLControl(gm, 2, 1, OpenTK.Graphics.GraphicsContextFlags.Default); + gm = new GraphicsMode(cf, 24, 0, (int)CConfig.AAMode); + control = new GLControl(gm, 2, 1, GraphicsContextFlags.Default); if (control.GraphicsMode != null) ok = true; } @@ -94,43 +93,43 @@ namespace Vocaluxe.Lib.Draw control.MakeCurrent(); control.VSync = (CConfig.VSync == EOffOn.TR_CONFIG_ON); - this.Controls.Add(control); - - - _Keys = new CKeys(); - this.Paint += new PaintEventHandler(this.OnPaintEvent); - this.Closing += new CancelEventHandler(this.OnClosingEvent); - this.Resize += new EventHandler(this.OnResizeEvent); - - control.KeyDown += new KeyEventHandler(this.OnKeyDownEvent); - control.PreviewKeyDown += new PreviewKeyDownEventHandler(this.OnPreviewKeyDownEvent); - control.KeyPress += new KeyPressEventHandler(this.OnKeyPressEvent); - control.KeyUp += new KeyEventHandler(this.OnKeyUpEvent); - - _Mouse = new CMouse(); - control.MouseMove += new MouseEventHandler(this.OnMouseMove); - control.MouseWheel += new MouseEventHandler(this.OnMouseWheel); - control.MouseDown += new MouseEventHandler(this.OnMouseDown); - control.MouseUp += new MouseEventHandler(this.OnMouseUp); - control.MouseLeave += new EventHandler(this.OnMouseLeave); - control.MouseEnter += new EventHandler(this.OnMouseEnter); + Controls.Add(control); - this.ClientSize = new Size(CConfig.ScreenW, CConfig.ScreenH); - this.CenterToScreen(); + + _Keys = new CKeys(); + Paint += OnPaintEvent; + Closing += OnClosingEvent; + Resize += OnResizeEvent; + + control.KeyDown += OnKeyDownEvent; + control.PreviewKeyDown += OnPreviewKeyDownEvent; + control.KeyPress += OnKeyPressEvent; + control.KeyUp += OnKeyUpEvent; + + _Mouse = new CMouse(); + control.MouseMove += OnMouseMove; + control.MouseWheel += OnMouseWheel; + control.MouseDown += OnMouseDown; + control.MouseUp += OnMouseUp; + control.MouseLeave += OnMouseLeave; + control.MouseEnter += OnMouseEnter; + + ClientSize = new Size(CConfig.ScreenW, CConfig.ScreenH); + CenterToScreen(); } #region Helpers private int CheckAntiAliasingMode(int SetValue) { int _Result = 0; - OpenTK.Graphics.GraphicsMode _mode = null; + GraphicsMode _mode = null; bool _done = false; while (!_done && (_Result <= 32)) { try { - _mode = new OpenTK.Graphics.GraphicsMode(16, 0, 0, _Result); + _mode = new GraphicsMode(16, 0, 0, _Result); } catch (Exception) { @@ -164,9 +163,8 @@ namespace Vocaluxe.Lib.Draw _done = true; _Result /= 2; if (_Result == 1) - _Result = 0; + _Result = 0; } - } else { @@ -175,7 +173,6 @@ namespace Vocaluxe.Lib.Draw if (_Result == 1) _Result = 0; } - } if (_Result > 64) @@ -190,14 +187,14 @@ namespace Vocaluxe.Lib.Draw private int CheckColorDeep(int SetValue) { int _Result = 8; - OpenTK.Graphics.GraphicsMode _mode = null; + GraphicsMode _mode = null; bool _done = false; while (!_done && (_Result <= 32)) { try { - _mode = new OpenTK.Graphics.GraphicsMode(_Result, 0, 0, 0); + _mode = new GraphicsMode(_Result, 0, 0, 0); } catch (Exception) { @@ -212,9 +209,7 @@ namespace Vocaluxe.Lib.Draw try { if (_mode.ColorFormat == _Result) - { _Result += 8; - } else { _done = true; @@ -230,7 +225,6 @@ namespace Vocaluxe.Lib.Draw if (_Result == 0) _Result = 8; } - } else { @@ -263,28 +257,28 @@ namespace Vocaluxe.Lib.Draw _fullscreen = true; CConfig.FullScreen = EOffOn.TR_CONFIG_ON; - _restore.location = this.Location; - _restore.width = this.Width; - _restore.height = this.Height; + _restore.location = Location; + _restore.width = Width; + _restore.height = Height; - this.FormBorderStyle = FormBorderStyle.None; + FormBorderStyle = FormBorderStyle.None; int ScreenNr = 0; for (int i = 0; i < Screen.AllScreens.Length; i++) { Screen scr = Screen.AllScreens[i]; - if (scr.Bounds.Top <= this.Top && scr.Bounds.Left <= this.Left) + if (scr.Bounds.Top <= Top && scr.Bounds.Left <= Left) ScreenNr = i; } - this.DesktopBounds = new Rectangle(Screen.AllScreens[ScreenNr].Bounds.Location, - new Size(Screen.AllScreens[ScreenNr].Bounds.Width, Screen.AllScreens[ScreenNr].Bounds.Height)); + DesktopBounds = new Rectangle(Screen.AllScreens[ScreenNr].Bounds.Location, + new Size(Screen.AllScreens[ScreenNr].Bounds.Width, Screen.AllScreens[ScreenNr].Bounds.Height)); - if (this.WindowState == FormWindowState.Maximized) + if (WindowState == FormWindowState.Maximized) { - this.WindowState = FormWindowState.Normal; + WindowState = FormWindowState.Normal; RResize(); - this.WindowState = FormWindowState.Maximized; + WindowState = FormWindowState.Maximized; } else RResize(); @@ -297,23 +291,17 @@ namespace Vocaluxe.Lib.Draw _fullscreen = false; CConfig.FullScreen = EOffOn.TR_CONFIG_OFF; - this.FormBorderStyle = FormBorderStyle.Sizable; - this.DesktopBounds = new Rectangle(_restore.location, new Size(_restore.width, _restore.height)); + FormBorderStyle = FormBorderStyle.Sizable; + DesktopBounds = new Rectangle(_restore.location, new Size(_restore.width, _restore.height)); CConfig.SaveConfig(); } #endregion Helpers #region form events - private void OnPaintEvent(object sender, PaintEventArgs e) - { + private void OnPaintEvent(object sender, PaintEventArgs e) {} - } - - private void OnResizeEvent(object sender, EventArgs e) - { - - } + private void OnResizeEvent(object sender, EventArgs e) {} private void OnClosingEvent(object sender, CancelEventArgs e) { @@ -322,14 +310,14 @@ namespace Vocaluxe.Lib.Draw protected override void OnLoad(EventArgs e) { - GL.ClearColor(Color.Black); + OpenTK.Graphics.OpenGL.GL.ClearColor(Color.Black); } protected override void OnResize(EventArgs e) { base.OnResize(e); - control.ClientSize = this.ClientSize; + control.ClientSize = ClientSize; RResize(); } @@ -390,69 +378,68 @@ namespace Vocaluxe.Lib.Draw #endregion #region keyboard event handlers - private void OnPreviewKeyDownEvent(object sender, System.Windows.Forms.PreviewKeyDownEventArgs e) - { - OnKeyDownEvent(sender, new KeyEventArgs(e.KeyData)); - } - - private void OnKeyDownEvent(object sender, System.Windows.Forms.KeyEventArgs e) + private void OnPreviewKeyDownEvent(object sender, PreviewKeyDownEventArgs e) + { + OnKeyDownEvent(sender, new KeyEventArgs(e.KeyData)); + } + + private void OnKeyDownEvent(object sender, KeyEventArgs e) { _Keys.KeyDown(e); } - private void OnKeyPressEvent(object sender, System.Windows.Forms.KeyPressEventArgs e) { _Keys.KeyPress(e); } - private void OnKeyUpEvent(object sender, System.Windows.Forms.KeyEventArgs e) + private void OnKeyUpEvent(object sender, KeyEventArgs e) { _Keys.KeyUp(e); } #endregion keyboard event handlers - + private void RResize() - { + { h = control.Height; w = control.Width; y = 0; x = 0; - if ((float)w / (float)h > CSettings.GetRenderAspect()) + if (w / (float)h > CSettings.GetRenderAspect()) { - w = (int)Math.Round((float)h * CSettings.GetRenderAspect()); + w = (int)Math.Round(h * CSettings.GetRenderAspect()); x = (control.Width - w) / 2; } else { - h = (int)Math.Round((float)w / CSettings.GetRenderAspect()); + h = (int)Math.Round(w / CSettings.GetRenderAspect()); y = (control.Height - h) / 2; } - - GL.MatrixMode(MatrixMode.Projection); - GL.LoadIdentity(); - GL.Ortho(0, CSettings.iRenderW, CSettings.iRenderH, 0, (double)CSettings.zNear, (double)CSettings.zFar); - GL.Viewport(x, y, w, h); + + OpenTK.Graphics.OpenGL.GL.MatrixMode(OpenTK.Graphics.OpenGL.MatrixMode.Projection); + OpenTK.Graphics.OpenGL.GL.LoadIdentity(); + OpenTK.Graphics.OpenGL.GL.Ortho(0, CSettings.iRenderW, CSettings.iRenderH, 0, CSettings.zNear, CSettings.zFar); + OpenTK.Graphics.OpenGL.GL.Viewport(x, y, w, h); } - #region implementation + #region main stuff public bool Init() { - this.Text = CSettings.GetFullVersionText(); - - // Init Texturing - GL.Enable(EnableCap.Texture2D); - - GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha); - GL.PixelStore(PixelStoreParameter.UnpackAlignment, 1); + Text = CSettings.GetFullVersionText(); - GL.DepthRange(CSettings.zFar, CSettings.zNear); - GL.DepthFunc(DepthFunction.Lequal); - GL.Enable(EnableCap.DepthTest); + // Init Texturing + OpenTK.Graphics.OpenGL.GL.Enable(OpenTK.Graphics.OpenGL.EnableCap.Texture2D); + + OpenTK.Graphics.OpenGL.GL.BlendFunc(OpenTK.Graphics.OpenGL.BlendingFactorSrc.SrcAlpha, OpenTK.Graphics.OpenGL.BlendingFactorDest.OneMinusSrcAlpha); + OpenTK.Graphics.OpenGL.GL.PixelStore(OpenTK.Graphics.OpenGL.PixelStoreParameter.UnpackAlignment, 1); + + OpenTK.Graphics.OpenGL.GL.DepthRange(CSettings.zFar, CSettings.zNear); + OpenTK.Graphics.OpenGL.GL.DepthFunc(OpenTK.Graphics.OpenGL.DepthFunction.Lequal); + OpenTK.Graphics.OpenGL.GL.Enable(OpenTK.Graphics.OpenGL.EnableCap.DepthTest); return true; } @@ -461,7 +448,7 @@ namespace Vocaluxe.Lib.Draw { _Run = true; int delay = 0; - this.Show(); + Show(); if (CConfig.FullScreen == EOffOn.TR_CONFIG_ON) { @@ -490,24 +477,22 @@ namespace Vocaluxe.Lib.Draw delay = (int)Math.Floor(CConfig.CalcCycleTime() - CTime.GetMilliseconds()); if (delay >= 1 && CConfig.VSync == EOffOn.TR_CONFIG_OFF) - System.Threading.Thread.Sleep(delay); + Thread.Sleep(delay); CTime.CalculateFPS(); CTime.Restart(); } } - this.Close(); + Close(); } public bool Unload() { STexture[] textures = new STexture[_Textures.Count]; _Textures.Values.CopyTo(textures, 0); - for (int i = 0; i < _Textures.Count; i++ ) - { + for (int i = 0; i < _Textures.Count; i++) RemoveTexture(ref textures[i]); - } - + return true; } @@ -538,35 +523,38 @@ namespace Vocaluxe.Lib.Draw #region Basic Draw Methods public void ClearScreen() { - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); + OpenTK.Graphics.OpenGL.GL.Clear(OpenTK.Graphics.OpenGL.ClearBufferMask.ColorBufferBit | OpenTK.Graphics.OpenGL.ClearBufferMask.DepthBufferBit); } public STexture CopyScreen() { STexture texture = new STexture(-1); - int id = GL.GenTexture(); - GL.BindTexture(TextureTarget.Texture2D, id); + int id = OpenTK.Graphics.OpenGL.GL.GenTexture(); + OpenTK.Graphics.OpenGL.GL.BindTexture(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, id); texture.ID = id; texture.width = w; texture.height = h; - texture.w2 = (float)MathHelper.NextPowerOfTwo(texture.width); - texture.h2 = (float)MathHelper.NextPowerOfTwo(texture.height); + texture.w2 = MathHelper.NextPowerOfTwo(texture.width); + texture.h2 = MathHelper.NextPowerOfTwo(texture.height); texture.width_ratio = texture.width / texture.w2; texture.height_ratio = texture.height / texture.h2; - GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, (int)texture.w2, (int)texture.h2, 0, - OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, IntPtr.Zero); + OpenTK.Graphics.OpenGL.GL.TexImage2D(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, 0, OpenTK.Graphics.OpenGL.PixelInternalFormat.Rgba, (int)texture.w2, + (int)texture.h2, 0, + OpenTK.Graphics.OpenGL.PixelFormat.Bgra, OpenTK.Graphics.OpenGL.PixelType.UnsignedByte, IntPtr.Zero); - GL.CopyTexSubImage2D(TextureTarget.Texture2D, 0, 0, 0, x, y, - (int)texture.width, (int)texture.height); + OpenTK.Graphics.OpenGL.GL.CopyTexSubImage2D(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, 0, 0, 0, x, y, + (int)texture.width, (int)texture.height); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); + OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMagFilter, + (int)OpenTK.Graphics.OpenGL.TextureMagFilter.Linear); + OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMinFilter, + (int)OpenTK.Graphics.OpenGL.TextureMinFilter.Linear); - GL.BindTexture(TextureTarget.Texture2D, 0); + OpenTK.Graphics.OpenGL.GL.BindTexture(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, 0); // Add to Texture List texture.color = new SColorF(1f, 1f, 1f, 1f); @@ -590,12 +578,12 @@ namespace Vocaluxe.Lib.Draw } else { - GL.BindTexture(TextureTarget.Texture2D, Texture.ID); + OpenTK.Graphics.OpenGL.GL.BindTexture(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, Texture.ID); - GL.CopyTexSubImage2D(TextureTarget.Texture2D, 0, 0, 0, 0, 0, - (int)Texture.width, (int)Texture.height); + OpenTK.Graphics.OpenGL.GL.CopyTexSubImage2D(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, 0, 0, 0, 0, 0, + (int)Texture.width, (int)Texture.height); - GL.BindTexture(TextureTarget.Texture2D, 0); + OpenTK.Graphics.OpenGL.GL.BindTexture(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, 0); } } @@ -603,7 +591,7 @@ namespace Vocaluxe.Lib.Draw { string file = "Screenshot_"; string path = Path.Combine(Environment.CurrentDirectory, CSettings.sFolderScreenshots); - + int i = 0; while (File.Exists(Path.Combine(path, file + i.ToString("00000") + ".bmp"))) i++; @@ -613,11 +601,9 @@ namespace Vocaluxe.Lib.Draw using (Bitmap screen = new Bitmap(width, height)) { - - BitmapData bmp_data = screen.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); - GL.ReadPixels(0, 0, width, height, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bmp_data.Scan0); + OpenTK.Graphics.OpenGL.GL.ReadPixels(0, 0, width, height, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, OpenTK.Graphics.OpenGL.PixelType.UnsignedByte, bmp_data.Scan0); screen.UnlockBits(bmp_data); screen.RotateFlip(RotateFlipType.RotateNoneFlipY); @@ -625,10 +611,7 @@ namespace Vocaluxe.Lib.Draw } } - public void DrawLine(int a, int r, int g, int b, int w, int x1, int y1, int x2, int y2) - { - - } + public void DrawLine(int a, int r, int g, int b, int w, int x1, int y1, int x2, int y2) {} // Draw Basic Text (must be deleted later) public void DrawText(string Text, int x, int y, int h) @@ -643,22 +626,21 @@ namespace Vocaluxe.Lib.Draw public void DrawColor(SColorF color, SRectF rect) { - GL.Enable(EnableCap.Blend); - GL.Color4(color.R, color.G, color.B, color.A * CGraphics.GlobalAlpha); + OpenTK.Graphics.OpenGL.GL.Enable(OpenTK.Graphics.OpenGL.EnableCap.Blend); + OpenTK.Graphics.OpenGL.GL.Color4(color.R, color.G, color.B, color.A * CGraphics.GlobalAlpha); - GL.Begin(BeginMode.Quads); - GL.Vertex3(rect.X, rect.Y, rect.Z + CGraphics.ZOffset); - GL.Vertex3(rect.X, rect.Y + rect.H, rect.Z + CGraphics.ZOffset); - GL.Vertex3(rect.X + rect.W, rect.Y + rect.H, rect.Z + CGraphics.ZOffset); - GL.Vertex3(rect.X + rect.W, rect.Y, rect.Z + CGraphics.ZOffset); - GL.End(); + OpenTK.Graphics.OpenGL.GL.Begin(OpenTK.Graphics.OpenGL.BeginMode.Quads); + OpenTK.Graphics.OpenGL.GL.Vertex3(rect.X, rect.Y, rect.Z + CGraphics.ZOffset); + OpenTK.Graphics.OpenGL.GL.Vertex3(rect.X, rect.Y + rect.H, rect.Z + CGraphics.ZOffset); + OpenTK.Graphics.OpenGL.GL.Vertex3(rect.X + rect.W, rect.Y + rect.H, rect.Z + CGraphics.ZOffset); + OpenTK.Graphics.OpenGL.GL.Vertex3(rect.X + rect.W, rect.Y, rect.Z + CGraphics.ZOffset); + OpenTK.Graphics.OpenGL.GL.End(); - GL.Disable(EnableCap.Blend); + OpenTK.Graphics.OpenGL.GL.Disable(OpenTK.Graphics.OpenGL.EnableCap.Blend); } public void DrawColorReflection(SColorF color, SRectF rect, float space, float height) { - if (rect.H < height) height = rect.H; @@ -680,35 +662,33 @@ namespace Vocaluxe.Lib.Draw ry2 = rect.Y + rect.H + space + height; - GL.Enable(EnableCap.Blend); + OpenTK.Graphics.OpenGL.GL.Enable(OpenTK.Graphics.OpenGL.EnableCap.Blend); if (rect.Rotation != 0f) { - GL.Translate(0.5f, 0.5f, 0); - GL.Rotate(-rect.Rotation, 0f, 0f, 1f); - GL.Translate(-0.5f, -0.5f, 0); + OpenTK.Graphics.OpenGL.GL.Translate(0.5f, 0.5f, 0); + OpenTK.Graphics.OpenGL.GL.Rotate(-rect.Rotation, 0f, 0f, 1f); + OpenTK.Graphics.OpenGL.GL.Translate(-0.5f, -0.5f, 0); } - GL.Begin(BeginMode.Quads); + OpenTK.Graphics.OpenGL.GL.Begin(OpenTK.Graphics.OpenGL.BeginMode.Quads); - GL.Color4(color.R, color.G, color.B, color.A * CGraphics.GlobalAlpha); - GL.Vertex3(rx2, ry1, rect.Z + CGraphics.ZOffset); + OpenTK.Graphics.OpenGL.GL.Color4(color.R, color.G, color.B, color.A * CGraphics.GlobalAlpha); + OpenTK.Graphics.OpenGL.GL.Vertex3(rx2, ry1, rect.Z + CGraphics.ZOffset); - GL.Color4(color.R, color.G, color.B, 0f); - GL.Vertex3(rx2, ry2, rect.Z + CGraphics.ZOffset); + OpenTK.Graphics.OpenGL.GL.Color4(color.R, color.G, color.B, 0f); + OpenTK.Graphics.OpenGL.GL.Vertex3(rx2, ry2, rect.Z + CGraphics.ZOffset); - GL.Color4(color.R, color.G, color.B, 0f); - GL.Vertex3(rx1, ry2, rect.Z + CGraphics.ZOffset); + OpenTK.Graphics.OpenGL.GL.Color4(color.R, color.G, color.B, 0f); + OpenTK.Graphics.OpenGL.GL.Vertex3(rx1, ry2, rect.Z + CGraphics.ZOffset); - GL.Color4(color.R, color.G, color.B, color.A * CGraphics.GlobalAlpha); - GL.Vertex3(rx1, ry1, rect.Z + CGraphics.ZOffset); + OpenTK.Graphics.OpenGL.GL.Color4(color.R, color.G, color.B, color.A * CGraphics.GlobalAlpha); + OpenTK.Graphics.OpenGL.GL.Vertex3(rx1, ry1, rect.Z + CGraphics.ZOffset); - GL.End(); - - GL.Disable(EnableCap.Blend); + OpenTK.Graphics.OpenGL.GL.End(); + OpenTK.Graphics.OpenGL.GL.Disable(OpenTK.Graphics.OpenGL.EnableCap.Blend); } - #endregion Basic Draw Methods #region Textures @@ -716,7 +696,7 @@ namespace Vocaluxe.Lib.Draw #region adding public STexture AddTexture(string TexturePath) { - if (System.IO.File.Exists(TexturePath)) + if (File.Exists(TexturePath)) { Bitmap bmp; try @@ -724,7 +704,7 @@ namespace Vocaluxe.Lib.Draw bmp = new Bitmap(TexturePath); } catch (Exception) - { + { CLog.LogError("Error loading Texture: " + TexturePath); return new STexture(-1); } @@ -791,21 +771,21 @@ namespace Vocaluxe.Lib.Draw h = MaxSize; } - int id = GL.GenTexture(); - GL.BindTexture(TextureTarget.Texture2D, id); + int id = OpenTK.Graphics.OpenGL.GL.GenTexture(); + OpenTK.Graphics.OpenGL.GL.BindTexture(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, id); texture.ID = id; texture.width = w; texture.height = h; - texture.w2 = (float)MathHelper.NextPowerOfTwo(w); - texture.h2 = (float)MathHelper.NextPowerOfTwo(h); + texture.w2 = MathHelper.NextPowerOfTwo(w); + texture.h2 = MathHelper.NextPowerOfTwo(h); using (Bitmap bmp2 = new Bitmap((int)texture.w2, (int)texture.h2)) { Graphics g = Graphics.FromImage(bmp2); - g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; - g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; + g.InterpolationMode = InterpolationMode.HighQualityBicubic; + g.SmoothingMode = SmoothingMode.HighQuality; g.DrawImage(bmp, new Rectangle(0, 0, bmp2.Width, bmp2.Height)); g.Dispose(); @@ -815,25 +795,31 @@ namespace Vocaluxe.Lib.Draw BitmapData bmp_data = bmp2.LockBits(new Rectangle(0, 0, bmp2.Width, bmp2.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); - GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, (int)texture.w2, (int)texture.h2, 0, - OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, IntPtr.Zero); + OpenTK.Graphics.OpenGL.GL.TexImage2D(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, 0, OpenTK.Graphics.OpenGL.PixelInternalFormat.Rgba, (int)texture.w2, + (int)texture.h2, 0, + OpenTK.Graphics.OpenGL.PixelFormat.Bgra, OpenTK.Graphics.OpenGL.PixelType.UnsignedByte, IntPtr.Zero); - GL.TexSubImage2D(TextureTarget.Texture2D, 0, 0, 0, bmp_data.Width, bmp_data.Height, - OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bmp_data.Scan0); + OpenTK.Graphics.OpenGL.GL.TexSubImage2D(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, 0, 0, 0, bmp_data.Width, bmp_data.Height, + OpenTK.Graphics.OpenGL.PixelFormat.Bgra, OpenTK.Graphics.OpenGL.PixelType.UnsignedByte, bmp_data.Scan0); bmp2.UnlockBits(bmp_data); } - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureParameterName.ClampToEdge); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureParameterName.ClampToEdge); + OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureWrapS, + (int)OpenTK.Graphics.OpenGL.TextureParameterName.ClampToEdge); + OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureWrapT, + (int)OpenTK.Graphics.OpenGL.TextureParameterName.ClampToEdge); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); + OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMagFilter, + (int)OpenTK.Graphics.OpenGL.TextureMagFilter.Linear); + OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMinFilter, + (int)OpenTK.Graphics.OpenGL.TextureMinFilter.Linear); + + OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMinFilter, + (int)OpenTK.Graphics.OpenGL.TextureMinFilter.LinearMipmapLinear); + //GL.GenerateMipmap(GenerateMipmapTarget.Texture2D); + OpenTK.Graphics.OpenGL.GL.Ext.GenerateMipmap(OpenTK.Graphics.OpenGL.GenerateMipmapTarget.Texture2D); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear); - //GL.GenerateMipmap(GenerateMipmapTarget.Texture2D); - GL.Ext.GenerateMipmap(GenerateMipmapTarget.Texture2D); - // Add to Texture List texture.color = new SColorF(1f, 1f, 1f, 1f); @@ -857,10 +843,11 @@ namespace Vocaluxe.Lib.Draw { try { - GL.GenBuffers(1, out texture.PBO); - GL.BindBuffer(BufferTarget.PixelUnpackBuffer, texture.PBO); - GL.BufferData(BufferTarget.PixelUnpackBuffer, (IntPtr)(W * H * 4), IntPtr.Zero, BufferUsageHint.StreamDraw); - GL.BindBuffer(BufferTarget.PixelUnpackBuffer, 0); + OpenTK.Graphics.OpenGL.GL.GenBuffers(1, out texture.PBO); + OpenTK.Graphics.OpenGL.GL.BindBuffer(OpenTK.Graphics.OpenGL.BufferTarget.PixelUnpackBuffer, texture.PBO); + OpenTK.Graphics.OpenGL.GL.BufferData(OpenTK.Graphics.OpenGL.BufferTarget.PixelUnpackBuffer, (IntPtr)(W * H * 4), IntPtr.Zero, + OpenTK.Graphics.OpenGL.BufferUsageHint.StreamDraw); + OpenTK.Graphics.OpenGL.GL.BindBuffer(OpenTK.Graphics.OpenGL.BufferTarget.PixelUnpackBuffer, 0); } catch (Exception) { @@ -868,36 +855,39 @@ namespace Vocaluxe.Lib.Draw } } - int id = GL.GenTexture(); - GL.BindTexture(TextureTarget.Texture2D, id); + int id = OpenTK.Graphics.OpenGL.GL.GenTexture(); + OpenTK.Graphics.OpenGL.GL.BindTexture(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, id); texture.ID = id; texture.width = W; texture.height = H; - texture.w2 = (float)MathHelper.NextPowerOfTwo(texture.width); - texture.h2 = (float)MathHelper.NextPowerOfTwo(texture.height); + texture.w2 = MathHelper.NextPowerOfTwo(texture.width); + texture.h2 = MathHelper.NextPowerOfTwo(texture.height); texture.width_ratio = texture.width / texture.w2; texture.height_ratio = texture.height / texture.h2; - GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, (int)texture.w2, (int)texture.h2, 0, - OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, IntPtr.Zero); + OpenTK.Graphics.OpenGL.GL.TexImage2D(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, 0, OpenTK.Graphics.OpenGL.PixelInternalFormat.Rgba, (int)texture.w2, + (int)texture.h2, 0, + OpenTK.Graphics.OpenGL.PixelFormat.Bgra, OpenTK.Graphics.OpenGL.PixelType.UnsignedByte, IntPtr.Zero); - GL.TexSubImage2D(TextureTarget.Texture2D, 0, 0, 0, W, H, - OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, Data); + OpenTK.Graphics.OpenGL.GL.TexSubImage2D(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, 0, 0, 0, W, H, + OpenTK.Graphics.OpenGL.PixelFormat.Bgra, OpenTK.Graphics.OpenGL.PixelType.UnsignedByte, Data); //GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureParameterName.ClampToEdge); //GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureParameterName.ClampToEdge); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); + OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMagFilter, + (int)OpenTK.Graphics.OpenGL.TextureMagFilter.Linear); + OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMinFilter, + (int)OpenTK.Graphics.OpenGL.TextureMinFilter.Linear); //GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear); //GL.GenerateMipmap(GenerateMipmapTarget.Texture2D); //GL.Ext.GenerateMipmap(GenerateMipmapTarget.Texture2D); - GL.BindTexture(TextureTarget.Texture2D, 0); + OpenTK.Graphics.OpenGL.GL.BindTexture(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, 0); // Add to Texture List texture.color = new SColorF(1f, 1f, 1f, 1f); @@ -909,7 +899,7 @@ namespace Vocaluxe.Lib.Draw texture.index = _IDs.Dequeue(); _Textures[texture.index] = texture; } - + return texture; } @@ -921,10 +911,11 @@ namespace Vocaluxe.Lib.Draw { try { - GL.GenBuffers(1, out texture.PBO); - GL.BindBuffer(BufferTarget.PixelUnpackBuffer, texture.PBO); - GL.BufferData(BufferTarget.PixelUnpackBuffer, (IntPtr)Data.Length, IntPtr.Zero, BufferUsageHint.StreamDraw); - GL.BindBuffer(BufferTarget.PixelUnpackBuffer, 0); + OpenTK.Graphics.OpenGL.GL.GenBuffers(1, out texture.PBO); + OpenTK.Graphics.OpenGL.GL.BindBuffer(OpenTK.Graphics.OpenGL.BufferTarget.PixelUnpackBuffer, texture.PBO); + OpenTK.Graphics.OpenGL.GL.BufferData(OpenTK.Graphics.OpenGL.BufferTarget.PixelUnpackBuffer, (IntPtr)Data.Length, IntPtr.Zero, + OpenTK.Graphics.OpenGL.BufferUsageHint.StreamDraw); + OpenTK.Graphics.OpenGL.GL.BindBuffer(OpenTK.Graphics.OpenGL.BufferTarget.PixelUnpackBuffer, 0); } catch (Exception) { @@ -933,36 +924,39 @@ namespace Vocaluxe.Lib.Draw } } - int id = GL.GenTexture(); - GL.BindTexture(TextureTarget.Texture2D, id); + int id = OpenTK.Graphics.OpenGL.GL.GenTexture(); + OpenTK.Graphics.OpenGL.GL.BindTexture(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, id); texture.ID = id; texture.width = W; texture.height = H; - texture.w2 = (float)MathHelper.NextPowerOfTwo(texture.width); - texture.h2 = (float)MathHelper.NextPowerOfTwo(texture.height); + texture.w2 = MathHelper.NextPowerOfTwo(texture.width); + texture.h2 = MathHelper.NextPowerOfTwo(texture.height); texture.width_ratio = texture.width / texture.w2; texture.height_ratio = texture.height / texture.h2; - GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, (int)texture.w2, (int)texture.h2, 0, - OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, IntPtr.Zero); + OpenTK.Graphics.OpenGL.GL.TexImage2D(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, 0, OpenTK.Graphics.OpenGL.PixelInternalFormat.Rgba, (int)texture.w2, + (int)texture.h2, 0, + OpenTK.Graphics.OpenGL.PixelFormat.Bgra, OpenTK.Graphics.OpenGL.PixelType.UnsignedByte, IntPtr.Zero); - GL.TexSubImage2D(TextureTarget.Texture2D, 0, 0, 0, W, H, - OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, Data); + OpenTK.Graphics.OpenGL.GL.TexSubImage2D(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, 0, 0, 0, W, H, + OpenTK.Graphics.OpenGL.PixelFormat.Bgra, OpenTK.Graphics.OpenGL.PixelType.UnsignedByte, Data); //GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureParameterName.ClampToEdge); //GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureParameterName.ClampToEdge); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); + OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMagFilter, + (int)OpenTK.Graphics.OpenGL.TextureMagFilter.Linear); + OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMinFilter, + (int)OpenTK.Graphics.OpenGL.TextureMinFilter.Linear); //GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear); //GL.GenerateMipmap(GenerateMipmapTarget.Texture2D); //GL.Ext.GenerateMipmap(GenerateMipmapTarget.Texture2D); - GL.BindTexture(TextureTarget.Texture2D, 0); + OpenTK.Graphics.OpenGL.GL.BindTexture(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, 0); // Add to Texture List texture.color = new SColorF(1f, 1f, 1f, 1f); @@ -974,7 +968,7 @@ namespace Vocaluxe.Lib.Draw texture.index = _IDs.Dequeue(); _Textures[texture.index] = texture; } - + return texture; } @@ -990,13 +984,13 @@ namespace Vocaluxe.Lib.Draw texture.width = W; lock (MutexTexture) - { + { texture.index = _IDs.Dequeue(); queque.ID = texture.index; _Queque.Add(queque); _Textures[texture.index] = texture; - } - + } + return texture; } #endregion adding @@ -1010,22 +1004,22 @@ namespace Vocaluxe.Lib.Draw { try { - GL.BindBuffer(BufferTarget.PixelUnpackBuffer, Texture.PBO); - - IntPtr Buffer = GL.MapBuffer(BufferTarget.PixelUnpackBuffer, BufferAccess.WriteOnly); + OpenTK.Graphics.OpenGL.GL.BindBuffer(OpenTK.Graphics.OpenGL.BufferTarget.PixelUnpackBuffer, Texture.PBO); + + IntPtr Buffer = OpenTK.Graphics.OpenGL.GL.MapBuffer(OpenTK.Graphics.OpenGL.BufferTarget.PixelUnpackBuffer, OpenTK.Graphics.OpenGL.BufferAccess.WriteOnly); byte[] d = new byte[(int)Texture.height * (int)Texture.width * 4]; Marshal.Copy(Data, d, 0, (int)Texture.height * (int)Texture.width * 4); Marshal.Copy(d, 0, Buffer, (int)Texture.height * (int)Texture.width * 4); - - GL.UnmapBuffer(BufferTarget.PixelUnpackBuffer); - GL.BindTexture(TextureTarget.Texture2D, Texture.ID); - GL.TexSubImage2D(TextureTarget.Texture2D, 0, 0, 0, (int)Texture.width, (int)Texture.height, - OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, IntPtr.Zero); + OpenTK.Graphics.OpenGL.GL.UnmapBuffer(OpenTK.Graphics.OpenGL.BufferTarget.PixelUnpackBuffer); - GL.BindTexture(TextureTarget.Texture2D, 0); - GL.BindBuffer(BufferTarget.PixelUnpackBuffer, 0); + OpenTK.Graphics.OpenGL.GL.BindTexture(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, Texture.ID); + OpenTK.Graphics.OpenGL.GL.TexSubImage2D(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, 0, 0, 0, (int)Texture.width, (int)Texture.height, + OpenTK.Graphics.OpenGL.PixelFormat.Bgra, OpenTK.Graphics.OpenGL.PixelType.UnsignedByte, IntPtr.Zero); + + OpenTK.Graphics.OpenGL.GL.BindTexture(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, 0); + OpenTK.Graphics.OpenGL.GL.BindBuffer(OpenTK.Graphics.OpenGL.BufferTarget.PixelUnpackBuffer, 0); return true; } @@ -1035,25 +1029,29 @@ namespace Vocaluxe.Lib.Draw } } - GL.BindTexture(TextureTarget.Texture2D, Texture.ID); + OpenTK.Graphics.OpenGL.GL.BindTexture(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, Texture.ID); - GL.TexSubImage2D(TextureTarget.Texture2D, 0, 0, 0, (int)Texture.width, (int)Texture.height, - OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, Data); + OpenTK.Graphics.OpenGL.GL.TexSubImage2D(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, 0, 0, 0, (int)Texture.width, (int)Texture.height, + OpenTK.Graphics.OpenGL.PixelFormat.Bgra, OpenTK.Graphics.OpenGL.PixelType.UnsignedByte, Data); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureParameterName.ClampToEdge); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureParameterName.ClampToEdge); + OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureWrapS, + (int)OpenTK.Graphics.OpenGL.TextureParameterName.ClampToEdge); + OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureWrapT, + (int)OpenTK.Graphics.OpenGL.TextureParameterName.ClampToEdge); //GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); + OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMinFilter, + (int)OpenTK.Graphics.OpenGL.TextureMinFilter.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear); + OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMinFilter, + (int)OpenTK.Graphics.OpenGL.TextureMinFilter.LinearMipmapLinear); //GL.GenerateMipmap(GenerateMipmapTarget.Texture2D); - GL.Ext.GenerateMipmap(GenerateMipmapTarget.Texture2D); + OpenTK.Graphics.OpenGL.GL.Ext.GenerateMipmap(OpenTK.Graphics.OpenGL.GenerateMipmapTarget.Texture2D); - GL.BindTexture(TextureTarget.Texture2D, 0); + OpenTK.Graphics.OpenGL.GL.BindTexture(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, 0); return true; - } + } return false; } @@ -1065,19 +1063,19 @@ namespace Vocaluxe.Lib.Draw { try { - GL.BindBuffer(BufferTarget.PixelUnpackBuffer, Texture.PBO); - - IntPtr Buffer = GL.MapBuffer(BufferTarget.PixelUnpackBuffer, BufferAccess.WriteOnly); + OpenTK.Graphics.OpenGL.GL.BindBuffer(OpenTK.Graphics.OpenGL.BufferTarget.PixelUnpackBuffer, Texture.PBO); + + IntPtr Buffer = OpenTK.Graphics.OpenGL.GL.MapBuffer(OpenTK.Graphics.OpenGL.BufferTarget.PixelUnpackBuffer, OpenTK.Graphics.OpenGL.BufferAccess.WriteOnly); Marshal.Copy(Data, 0, Buffer, Data.Length); - GL.UnmapBuffer(BufferTarget.PixelUnpackBuffer); + OpenTK.Graphics.OpenGL.GL.UnmapBuffer(OpenTK.Graphics.OpenGL.BufferTarget.PixelUnpackBuffer); - GL.BindTexture(TextureTarget.Texture2D, Texture.ID); - GL.TexSubImage2D(TextureTarget.Texture2D, 0, 0, 0, (int)Texture.width, (int)Texture.height, - OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, IntPtr.Zero); + OpenTK.Graphics.OpenGL.GL.BindTexture(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, Texture.ID); + OpenTK.Graphics.OpenGL.GL.TexSubImage2D(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, 0, 0, 0, (int)Texture.width, (int)Texture.height, + OpenTK.Graphics.OpenGL.PixelFormat.Bgra, OpenTK.Graphics.OpenGL.PixelType.UnsignedByte, IntPtr.Zero); - GL.BindTexture(TextureTarget.Texture2D, 0); - GL.BindBuffer(BufferTarget.PixelUnpackBuffer, 0); + OpenTK.Graphics.OpenGL.GL.BindTexture(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, 0); + OpenTK.Graphics.OpenGL.GL.BindBuffer(OpenTK.Graphics.OpenGL.BufferTarget.PixelUnpackBuffer, 0); return true; } @@ -1088,22 +1086,24 @@ namespace Vocaluxe.Lib.Draw } } - GL.BindTexture(TextureTarget.Texture2D, Texture.ID); + OpenTK.Graphics.OpenGL.GL.BindTexture(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, Texture.ID); - GL.TexSubImage2D(TextureTarget.Texture2D, 0, 0, 0, (int)Texture.width, (int)Texture.height, - OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, Data); + OpenTK.Graphics.OpenGL.GL.TexSubImage2D(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, 0, 0, 0, (int)Texture.width, (int)Texture.height, + OpenTK.Graphics.OpenGL.PixelFormat.Bgra, OpenTK.Graphics.OpenGL.PixelType.UnsignedByte, Data); //GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureParameterName.ClampToEdge); //GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureParameterName.ClampToEdge); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); + OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMagFilter, + (int)OpenTK.Graphics.OpenGL.TextureMagFilter.Linear); + OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMinFilter, + (int)OpenTK.Graphics.OpenGL.TextureMinFilter.Linear); //GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear); //GL.GenerateMipmap(GenerateMipmapTarget.Texture2D); //GL.Ext.GenerateMipmap(GenerateMipmapTarget.Texture2D); - GL.BindTexture(TextureTarget.Texture2D, 0); + OpenTK.Graphics.OpenGL.GL.BindTexture(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, 0); return true; } @@ -1118,9 +1118,9 @@ namespace Vocaluxe.Lib.Draw lock (MutexTexture) { _IDs.Enqueue(Texture.index); - GL.DeleteTexture(Texture.ID); + OpenTK.Graphics.OpenGL.GL.DeleteTexture(Texture.ID); if (Texture.PBO > 0) - GL.DeleteBuffers(1, ref Texture.PBO); + OpenTK.Graphics.OpenGL.GL.DeleteBuffers(1, ref Texture.PBO); _Textures.Remove(Texture.index); Texture.index = -1; Texture.ID = -1; @@ -1132,9 +1132,9 @@ namespace Vocaluxe.Lib.Draw { lock (MutexTexture) { - if(_Textures.ContainsKey((Texture.index))) + if (_Textures.ContainsKey((Texture.index))) { - if(_Textures[Texture.index].ID > 0) + if (_Textures[Texture.index].ID > 0) { Texture = _Textures[Texture.index]; return true; @@ -1183,7 +1183,7 @@ namespace Vocaluxe.Lib.Draw if (_TextureExists(ref Texture)) { - GL.BindTexture(TextureTarget.Texture2D, Texture.ID); + OpenTK.Graphics.OpenGL.GL.BindTexture(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, Texture.ID); float x1 = (bounds.X - rect.X) / rect.W * Texture.width_ratio; float x2 = (bounds.X + bounds.W - rect.X) / rect.W * Texture.width_ratio; @@ -1220,60 +1220,60 @@ namespace Vocaluxe.Lib.Draw if (ry2 > bounds.Y + bounds.H) ry2 = bounds.Y + bounds.H; - GL.Enable(EnableCap.Blend); - GL.Color4(color.R, color.G, color.B, color.A * CGraphics.GlobalAlpha); + OpenTK.Graphics.OpenGL.GL.Enable(OpenTK.Graphics.OpenGL.EnableCap.Blend); + OpenTK.Graphics.OpenGL.GL.Color4(color.R, color.G, color.B, color.A * CGraphics.GlobalAlpha); - GL.MatrixMode(MatrixMode.Texture); - GL.PushMatrix(); + OpenTK.Graphics.OpenGL.GL.MatrixMode(OpenTK.Graphics.OpenGL.MatrixMode.Texture); + OpenTK.Graphics.OpenGL.GL.PushMatrix(); if (rect.Rotation != 0f) { - GL.Translate(0.5f, 0.5f, 0); - GL.Rotate(-rect.Rotation, 0f, 0f, 1f); - GL.Translate(-0.5f, -0.5f, 0); + OpenTK.Graphics.OpenGL.GL.Translate(0.5f, 0.5f, 0); + OpenTK.Graphics.OpenGL.GL.Rotate(-rect.Rotation, 0f, 0f, 1f); + OpenTK.Graphics.OpenGL.GL.Translate(-0.5f, -0.5f, 0); } if (!mirrored) { - GL.Begin(BeginMode.Quads); + OpenTK.Graphics.OpenGL.GL.Begin(OpenTK.Graphics.OpenGL.BeginMode.Quads); - GL.TexCoord2(x1, y1); - GL.Vertex3(rx1, ry1, rect.Z + CGraphics.ZOffset); + OpenTK.Graphics.OpenGL.GL.TexCoord2(x1, y1); + OpenTK.Graphics.OpenGL.GL.Vertex3(rx1, ry1, rect.Z + CGraphics.ZOffset); - GL.TexCoord2(x1, y2); - GL.Vertex3(rx1, ry2, rect.Z + CGraphics.ZOffset); + OpenTK.Graphics.OpenGL.GL.TexCoord2(x1, y2); + OpenTK.Graphics.OpenGL.GL.Vertex3(rx1, ry2, rect.Z + CGraphics.ZOffset); - GL.TexCoord2(x2, y2); - GL.Vertex3(rx2, ry2, rect.Z + CGraphics.ZOffset); + OpenTK.Graphics.OpenGL.GL.TexCoord2(x2, y2); + OpenTK.Graphics.OpenGL.GL.Vertex3(rx2, ry2, rect.Z + CGraphics.ZOffset); - GL.TexCoord2(x2, y1); - GL.Vertex3(rx2, ry1, rect.Z + CGraphics.ZOffset); + OpenTK.Graphics.OpenGL.GL.TexCoord2(x2, y1); + OpenTK.Graphics.OpenGL.GL.Vertex3(rx2, ry1, rect.Z + CGraphics.ZOffset); - GL.End(); + OpenTK.Graphics.OpenGL.GL.End(); } else { - GL.Begin(BeginMode.Quads); + OpenTK.Graphics.OpenGL.GL.Begin(OpenTK.Graphics.OpenGL.BeginMode.Quads); - GL.TexCoord2(x2, y2); - GL.Vertex3(rx2, ry1, rect.Z + CGraphics.ZOffset); + OpenTK.Graphics.OpenGL.GL.TexCoord2(x2, y2); + OpenTK.Graphics.OpenGL.GL.Vertex3(rx2, ry1, rect.Z + CGraphics.ZOffset); - GL.TexCoord2(x2, y1); - GL.Vertex3(rx2, ry2, rect.Z + CGraphics.ZOffset); + OpenTK.Graphics.OpenGL.GL.TexCoord2(x2, y1); + OpenTK.Graphics.OpenGL.GL.Vertex3(rx2, ry2, rect.Z + CGraphics.ZOffset); - GL.TexCoord2(x1, y1); - GL.Vertex3(rx1, ry2, rect.Z + CGraphics.ZOffset); + OpenTK.Graphics.OpenGL.GL.TexCoord2(x1, y1); + OpenTK.Graphics.OpenGL.GL.Vertex3(rx1, ry2, rect.Z + CGraphics.ZOffset); - GL.TexCoord2(x1, y2); - GL.Vertex3(rx1, ry1, rect.Z + CGraphics.ZOffset); + OpenTK.Graphics.OpenGL.GL.TexCoord2(x1, y2); + OpenTK.Graphics.OpenGL.GL.Vertex3(rx1, ry1, rect.Z + CGraphics.ZOffset); - GL.End(); + OpenTK.Graphics.OpenGL.GL.End(); } - GL.PopMatrix(); + OpenTK.Graphics.OpenGL.GL.PopMatrix(); - GL.Disable(EnableCap.Blend); - GL.BindTexture(TextureTarget.Texture2D, 0); + OpenTK.Graphics.OpenGL.GL.Disable(OpenTK.Graphics.OpenGL.EnableCap.Blend); + OpenTK.Graphics.OpenGL.GL.BindTexture(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, 0); } } @@ -1281,31 +1281,31 @@ namespace Vocaluxe.Lib.Draw { if (_TextureExists(ref Texture)) { - GL.BindTexture(TextureTarget.Texture2D, Texture.ID); + OpenTK.Graphics.OpenGL.GL.BindTexture(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, Texture.ID); - GL.Enable(EnableCap.Blend); - GL.Color4(color.R, color.G, color.B, color.A * CGraphics.GlobalAlpha); + OpenTK.Graphics.OpenGL.GL.Enable(OpenTK.Graphics.OpenGL.EnableCap.Blend); + OpenTK.Graphics.OpenGL.GL.Color4(color.R, color.G, color.B, color.A * CGraphics.GlobalAlpha); - GL.Begin(BeginMode.Quads); + OpenTK.Graphics.OpenGL.GL.Begin(OpenTK.Graphics.OpenGL.BeginMode.Quads); - GL.TexCoord2(0f + begin * Texture.width_ratio, 0f); - GL.Vertex3(rect.X + begin * rect.W, rect.Y, rect.Z + CGraphics.ZOffset); + OpenTK.Graphics.OpenGL.GL.TexCoord2(0f + begin * Texture.width_ratio, 0f); + OpenTK.Graphics.OpenGL.GL.Vertex3(rect.X + begin * rect.W, rect.Y, rect.Z + CGraphics.ZOffset); - GL.TexCoord2(0f + begin * Texture.width_ratio, Texture.height_ratio); - GL.Vertex3(rect.X + begin * rect.W, rect.Y + rect.H, rect.Z + CGraphics.ZOffset); + OpenTK.Graphics.OpenGL.GL.TexCoord2(0f + begin * Texture.width_ratio, Texture.height_ratio); + OpenTK.Graphics.OpenGL.GL.Vertex3(rect.X + begin * rect.W, rect.Y + rect.H, rect.Z + CGraphics.ZOffset); - GL.TexCoord2(Texture.width_ratio * end, Texture.height_ratio); - GL.Vertex3(rect.X + end * rect.W, rect.Y + rect.H, rect.Z + CGraphics.ZOffset); + OpenTK.Graphics.OpenGL.GL.TexCoord2(Texture.width_ratio * end, Texture.height_ratio); + OpenTK.Graphics.OpenGL.GL.Vertex3(rect.X + end * rect.W, rect.Y + rect.H, rect.Z + CGraphics.ZOffset); - GL.TexCoord2(Texture.width_ratio * end, 0f); - GL.Vertex3(rect.X + end * rect.W, rect.Y, rect.Z + CGraphics.ZOffset); + OpenTK.Graphics.OpenGL.GL.TexCoord2(Texture.width_ratio * end, 0f); + OpenTK.Graphics.OpenGL.GL.Vertex3(rect.X + end * rect.W, rect.Y, rect.Z + CGraphics.ZOffset); - GL.End(); + OpenTK.Graphics.OpenGL.GL.End(); - GL.Disable(EnableCap.Blend); - GL.BindTexture(TextureTarget.Texture2D, 0); + OpenTK.Graphics.OpenGL.GL.Disable(OpenTK.Graphics.OpenGL.EnableCap.Blend); + OpenTK.Graphics.OpenGL.GL.BindTexture(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, 0); } } @@ -1313,7 +1313,7 @@ namespace Vocaluxe.Lib.Draw { if (rect.W == 0f || rect.H == 0f || bounds.H == 0f || bounds.W == 0f || color.A == 0f || height <= 0f) return; - + if (bounds.X > rect.X + rect.W || bounds.X + bounds.W < rect.X) return; @@ -1325,7 +1325,7 @@ namespace Vocaluxe.Lib.Draw if (_TextureExists(ref Texture)) { - GL.BindTexture(TextureTarget.Texture2D, Texture.ID); + OpenTK.Graphics.OpenGL.GL.BindTexture(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, Texture.ID); float x1 = (bounds.X - rect.X) / rect.W * Texture.width_ratio; float x2 = (bounds.X + bounds.W - rect.X) / rect.W * Texture.width_ratio; @@ -1362,44 +1362,44 @@ namespace Vocaluxe.Lib.Draw if (ry2 > bounds.Y + bounds.H + space + height) ry2 = bounds.Y + bounds.H + space + height; - GL.Enable(EnableCap.Blend); + OpenTK.Graphics.OpenGL.GL.Enable(OpenTK.Graphics.OpenGL.EnableCap.Blend); - GL.MatrixMode(MatrixMode.Texture); - GL.PushMatrix(); + OpenTK.Graphics.OpenGL.GL.MatrixMode(OpenTK.Graphics.OpenGL.MatrixMode.Texture); + OpenTK.Graphics.OpenGL.GL.PushMatrix(); if (rect.Rotation != 0f) { - GL.Translate(0.5f, 0.5f, 0); - GL.Rotate(-rect.Rotation, 0f, 0f, 1f); - GL.Translate(-0.5f, -0.5f, 0); + OpenTK.Graphics.OpenGL.GL.Translate(0.5f, 0.5f, 0); + OpenTK.Graphics.OpenGL.GL.Rotate(-rect.Rotation, 0f, 0f, 1f); + OpenTK.Graphics.OpenGL.GL.Translate(-0.5f, -0.5f, 0); } - GL.Begin(BeginMode.Quads); + OpenTK.Graphics.OpenGL.GL.Begin(OpenTK.Graphics.OpenGL.BeginMode.Quads); - GL.Color4(color.R, color.G, color.B, color.A * CGraphics.GlobalAlpha); - GL.TexCoord2(x2, y2); - GL.Vertex3(rx2, ry1, rect.Z + CGraphics.ZOffset); + OpenTK.Graphics.OpenGL.GL.Color4(color.R, color.G, color.B, color.A * CGraphics.GlobalAlpha); + OpenTK.Graphics.OpenGL.GL.TexCoord2(x2, y2); + OpenTK.Graphics.OpenGL.GL.Vertex3(rx2, ry1, rect.Z + CGraphics.ZOffset); - GL.Color4(color.R, color.G, color.B, 0f); - GL.TexCoord2(x2, y1); - GL.Vertex3(rx2, ry2, rect.Z + CGraphics.ZOffset); + OpenTK.Graphics.OpenGL.GL.Color4(color.R, color.G, color.B, 0f); + OpenTK.Graphics.OpenGL.GL.TexCoord2(x2, y1); + OpenTK.Graphics.OpenGL.GL.Vertex3(rx2, ry2, rect.Z + CGraphics.ZOffset); - GL.Color4(color.R, color.G, color.B, 0f); - GL.TexCoord2(x1, y1); - GL.Vertex3(rx1, ry2, rect.Z + CGraphics.ZOffset); + OpenTK.Graphics.OpenGL.GL.Color4(color.R, color.G, color.B, 0f); + OpenTK.Graphics.OpenGL.GL.TexCoord2(x1, y1); + OpenTK.Graphics.OpenGL.GL.Vertex3(rx1, ry2, rect.Z + CGraphics.ZOffset); - GL.Color4(color.R, color.G, color.B, color.A * CGraphics.GlobalAlpha); - GL.TexCoord2(x1, y2); - GL.Vertex3(rx1, ry1, rect.Z + CGraphics.ZOffset); + OpenTK.Graphics.OpenGL.GL.Color4(color.R, color.G, color.B, color.A * CGraphics.GlobalAlpha); + OpenTK.Graphics.OpenGL.GL.TexCoord2(x1, y2); + OpenTK.Graphics.OpenGL.GL.Vertex3(rx1, ry1, rect.Z + CGraphics.ZOffset); - GL.End(); + OpenTK.Graphics.OpenGL.GL.End(); - GL.PopMatrix(); + OpenTK.Graphics.OpenGL.GL.PopMatrix(); - GL.Disable(EnableCap.Blend); - GL.BindTexture(TextureTarget.Texture2D, 0); + OpenTK.Graphics.OpenGL.GL.Disable(OpenTK.Graphics.OpenGL.EnableCap.Blend); + OpenTK.Graphics.OpenGL.GL.BindTexture(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, 0); } } #endregion drawing @@ -1419,9 +1419,7 @@ namespace Vocaluxe.Lib.Draw STextureQueque q = _Queque[0]; STexture texture = new STexture(-1); if (_Textures.ContainsKey(q.ID)) - { texture = _Textures[q.ID]; - } if (texture.index < 1) return; @@ -1430,10 +1428,11 @@ namespace Vocaluxe.Lib.Draw { try { - GL.GenBuffers(1, out texture.PBO); - GL.BindBuffer(BufferTarget.PixelUnpackBuffer, texture.PBO); - GL.BufferData(BufferTarget.PixelUnpackBuffer, (IntPtr)q.data.Length, IntPtr.Zero, BufferUsageHint.StreamDraw); - GL.BindBuffer(BufferTarget.PixelUnpackBuffer, 0); + OpenTK.Graphics.OpenGL.GL.GenBuffers(1, out texture.PBO); + OpenTK.Graphics.OpenGL.GL.BindBuffer(OpenTK.Graphics.OpenGL.BufferTarget.PixelUnpackBuffer, texture.PBO); + OpenTK.Graphics.OpenGL.GL.BufferData(OpenTK.Graphics.OpenGL.BufferTarget.PixelUnpackBuffer, (IntPtr)q.data.Length, IntPtr.Zero, + OpenTK.Graphics.OpenGL.BufferUsageHint.StreamDraw); + OpenTK.Graphics.OpenGL.GL.BindBuffer(OpenTK.Graphics.OpenGL.BufferTarget.PixelUnpackBuffer, 0); } catch (Exception) { @@ -1442,34 +1441,40 @@ namespace Vocaluxe.Lib.Draw } } - int id = GL.GenTexture(); - GL.BindTexture(TextureTarget.Texture2D, id); + int id = OpenTK.Graphics.OpenGL.GL.GenTexture(); + OpenTK.Graphics.OpenGL.GL.BindTexture(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, id); texture.ID = id; texture.width = q.width; texture.height = q.height; - texture.w2 = (float)MathHelper.NextPowerOfTwo(texture.width); - texture.h2 = (float)MathHelper.NextPowerOfTwo(texture.height); + texture.w2 = MathHelper.NextPowerOfTwo(texture.width); + texture.h2 = MathHelper.NextPowerOfTwo(texture.height); texture.width_ratio = texture.width / texture.w2; texture.height_ratio = texture.height / texture.h2; - GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, (int)texture.w2, (int)texture.h2, 0, - OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, IntPtr.Zero); + OpenTK.Graphics.OpenGL.GL.TexImage2D(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, 0, OpenTK.Graphics.OpenGL.PixelInternalFormat.Rgba, (int)texture.w2, + (int)texture.h2, 0, + OpenTK.Graphics.OpenGL.PixelFormat.Bgra, OpenTK.Graphics.OpenGL.PixelType.UnsignedByte, IntPtr.Zero); - GL.TexSubImage2D(TextureTarget.Texture2D, 0, 0, 0, q.width, q.height, - OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, q.data); + OpenTK.Graphics.OpenGL.GL.TexSubImage2D(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, 0, 0, 0, q.width, q.height, + OpenTK.Graphics.OpenGL.PixelFormat.Bgra, OpenTK.Graphics.OpenGL.PixelType.UnsignedByte, q.data); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureParameterName.ClampToEdge); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureParameterName.ClampToEdge); + OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureWrapS, + (int)OpenTK.Graphics.OpenGL.TextureParameterName.ClampToEdge); + OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureWrapT, + (int)OpenTK.Graphics.OpenGL.TextureParameterName.ClampToEdge); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); + OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMagFilter, + (int)OpenTK.Graphics.OpenGL.TextureMagFilter.Linear); + OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMinFilter, + (int)OpenTK.Graphics.OpenGL.TextureMinFilter.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear); - GL.Ext.GenerateMipmap(GenerateMipmapTarget.Texture2D); + OpenTK.Graphics.OpenGL.GL.TexParameter(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, OpenTK.Graphics.OpenGL.TextureParameterName.TextureMinFilter, + (int)OpenTK.Graphics.OpenGL.TextureMinFilter.LinearMipmapLinear); + OpenTK.Graphics.OpenGL.GL.Ext.GenerateMipmap(OpenTK.Graphics.OpenGL.GenerateMipmapTarget.Texture2D); - GL.BindTexture(TextureTarget.Texture2D, 0); + OpenTK.Graphics.OpenGL.GL.BindTexture(OpenTK.Graphics.OpenGL.TextureTarget.Texture2D, 0); // Add to Texture List texture.color = new SColorF(1f, 1f, 1f, 1f); @@ -1485,4 +1490,4 @@ namespace Vocaluxe.Lib.Draw #endregion implementation } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Draw/IDraw.cs b/Vocaluxe/Lib/Draw/IDraw.cs index f610bf7c..1a0d6cb9 100644 --- a/Vocaluxe/Lib/Draw/IDraw.cs +++ b/Vocaluxe/Lib/Draw/IDraw.cs @@ -15,7 +15,7 @@ namespace Vocaluxe.Lib.Draw RectangleF GetTextBounds(CText text); RectangleF GetTextBounds(CText text, float Height); - + // Basic Draw Methods void DrawLine(int a, int r, int g, int b, int w, int x1, int y1, int x2, int y2); void DrawColor(SColorF color, SRectF rect); @@ -36,7 +36,7 @@ namespace Vocaluxe.Lib.Draw STexture QuequeTexture(int W, int H, ref byte[] Data); bool UpdateTexture(ref STexture Texture, ref byte[] Data); bool UpdateTexture(ref STexture Texture, IntPtr Data); - + void RemoveTexture(ref STexture Texture); void DrawTexture(STexture Texture); void DrawTexture(STexture Texture, SRectF rect); @@ -51,4 +51,4 @@ namespace Vocaluxe.Lib.Draw int TextureCount(); } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Input/CHIDAPI.cs b/Vocaluxe/Lib/Input/CHIDAPI.cs index 9c5fceef..26a818e5 100644 --- a/Vocaluxe/Lib/Input/CHIDAPI.cs +++ b/Vocaluxe/Lib/Input/CHIDAPI.cs @@ -1,6 +1,5 @@ using System; using System.Runtime.InteropServices; - using Vocaluxe.Base; namespace Vocaluxe.Lib.Input @@ -8,8 +7,7 @@ namespace Vocaluxe.Lib.Input [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct HIDDeviceInfo { - [MarshalAsAttribute(UnmanagedType.LPTStr)] - public String Path; + [MarshalAs(UnmanagedType.LPTStr)] public String Path; public ushort VendorString; public ushort ProductID; public String SerialNumber; @@ -21,6 +19,7 @@ namespace Vocaluxe.Lib.Input public int InterfaceNumber; internal IntPtr Next; } + public static class CHIDAPI { #if ARCH_X86 @@ -43,9 +42,9 @@ namespace Vocaluxe.Lib.Input #endif #endif - [DllImport(HIDapiDll, ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, EntryPoint = "hid_init", CharSet = CharSet.Unicode)] private static extern int hid_init(); + public static bool Init() { int result = -1; @@ -53,12 +52,12 @@ namespace Vocaluxe.Lib.Input { result = hid_init(); } - catch(Exception e) + catch (Exception e) { - CLog.LogError("Error CHIDAPI.Init(): " + e.ToString()); + CLog.LogError("Error CHIDAPI.Init(): " + e); return false; } - + if (result == 0) return true; @@ -67,6 +66,7 @@ namespace Vocaluxe.Lib.Input [DllImport(HIDapiDll, ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, EntryPoint = "hid_exit", CharSet = CharSet.Unicode)] private static extern int hid_exit(); + public static bool Exit() { int result = -1; @@ -76,7 +76,7 @@ namespace Vocaluxe.Lib.Input } catch (Exception e) { - CLog.LogError("Error CHIDAPI.Exit(): " + e.ToString()); + CLog.LogError("Error CHIDAPI.Exit(): " + e); return false; } @@ -85,8 +85,11 @@ namespace Vocaluxe.Lib.Input return false; } + [DllImport(HIDapiDll, ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, EntryPoint = "hid_enumerate", CharSet = CharSet.Ansi)] - private static extern IntPtr hid_enumerate(ushort VendorID, ushort ProductID); //HIDDeviceInfo + private static extern IntPtr hid_enumerate(ushort VendorID, ushort ProductID); + + //HIDDeviceInfo public static IntPtr Enumerate(ushort VendorID, ushort ProductID) //HIDDeviceInfo { return hid_enumerate(VendorID, ProductID); @@ -94,6 +97,7 @@ namespace Vocaluxe.Lib.Input [DllImport(HIDapiDll, ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, EntryPoint = "hid_free_enumeration", CharSet = CharSet.Unicode)] private static extern void hid_free_enumeration(HIDDeviceInfo devs); + public static void FreeEnumeration(HIDDeviceInfo devs) { hid_free_enumeration(devs); @@ -101,6 +105,7 @@ namespace Vocaluxe.Lib.Input [DllImport(HIDapiDll, ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, EntryPoint = "hid_open", CharSet = CharSet.Unicode)] private static extern IntPtr hid_open(ushort VendorID, ushort ProductID, IntPtr SerialNumber); + public static bool Open(ushort VendorID, ushort ProductID, out IntPtr Handle) { Handle = IntPtr.Zero; @@ -110,7 +115,7 @@ namespace Vocaluxe.Lib.Input } catch (Exception e) { - CLog.LogError("Error CHIDAPI.Open(): " + e.ToString()); + CLog.LogError("Error CHIDAPI.Open(): " + e); return false; } @@ -118,11 +123,11 @@ namespace Vocaluxe.Lib.Input return true; return false; - } [DllImport(HIDapiDll, ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, EntryPoint = "hid_open_path", CharSet = CharSet.Unicode)] private static extern IntPtr hid_open_path(string Path); + public static IntPtr OpenPath(string Path) { return hid_open_path(Path); @@ -130,6 +135,7 @@ namespace Vocaluxe.Lib.Input [DllImport(HIDapiDll, ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, EntryPoint = "hid_write", CharSet = CharSet.Unicode)] private static extern int hid_write(IntPtr device, byte[] data, int length); + public static int Write(IntPtr Device, byte[] Data) { return hid_write(Device, Data, Data.Length); @@ -137,6 +143,7 @@ namespace Vocaluxe.Lib.Input [DllImport(HIDapiDll, ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, EntryPoint = "hid_read_timeout", CharSet = CharSet.Unicode)] private static extern int hid_read_timeout(IntPtr device, IntPtr data, int length, int milliseconds); + public static int ReadTimeout(IntPtr Device, out byte[] Data, int length, int milliseconds) { Data = new byte[length]; @@ -150,7 +157,7 @@ namespace Vocaluxe.Lib.Input catch (Exception e) { result = -1; - CLog.LogError("Error CHIDAPI.ReadTimeout(): " + e.ToString()); + CLog.LogError("Error CHIDAPI.ReadTimeout(): " + e); } if (result != -1) @@ -164,6 +171,7 @@ namespace Vocaluxe.Lib.Input [DllImport(HIDapiDll, ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, EntryPoint = "hid_read", CharSet = CharSet.Unicode)] private static extern int hid_read(IntPtr device, IntPtr data, int length); + public static int Read(IntPtr Device, out byte[] Data, int length) { Data = new byte[length]; @@ -177,7 +185,7 @@ namespace Vocaluxe.Lib.Input catch (Exception e) { result = -1; - CLog.LogError("Error CHIDAPI.Read(): " + e.ToString()); + CLog.LogError("Error CHIDAPI.Read(): " + e); } if (result != -1) @@ -191,6 +199,7 @@ namespace Vocaluxe.Lib.Input [DllImport(HIDapiDll, ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, EntryPoint = "hid_set_nonblocking", CharSet = CharSet.Unicode)] private static extern int hid_set_nonblocking(IntPtr device, bool nonblock); + public static int Read(IntPtr Device, bool Nonblocking) { return hid_set_nonblocking(Device, Nonblocking); @@ -198,6 +207,7 @@ namespace Vocaluxe.Lib.Input [DllImport(HIDapiDll, ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, EntryPoint = "hid_send_feature_report", CharSet = CharSet.Unicode)] private static extern int hid_send_feature_report(IntPtr device, string data, int length); + public static int SendFeatureReport(IntPtr Device, string Data) { return hid_send_feature_report(Device, Data, Data.Length); @@ -205,6 +215,7 @@ namespace Vocaluxe.Lib.Input [DllImport(HIDapiDll, ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, EntryPoint = "hid_get_feature_report", CharSet = CharSet.Unicode)] private static extern int hid_get_feature_report(IntPtr device, string Data, int length); + public static int GetFeatureReport(IntPtr Device, string Data) { return hid_get_feature_report(Device, Data, Data.Length); @@ -212,6 +223,7 @@ namespace Vocaluxe.Lib.Input [DllImport(HIDapiDll, ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, EntryPoint = "hid_close", CharSet = CharSet.Unicode)] private static extern void hid_close(IntPtr device); + public static bool Close(IntPtr Device) { try @@ -220,7 +232,7 @@ namespace Vocaluxe.Lib.Input } catch (Exception e) { - CLog.LogError("Error CHIDAPI.Close(): " + e.ToString()); + CLog.LogError("Error CHIDAPI.Close(): " + e); return false; } return true; @@ -228,6 +240,7 @@ namespace Vocaluxe.Lib.Input [DllImport(HIDapiDll, ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, EntryPoint = "hid_get_manufacturer_string", CharSet = CharSet.Unicode)] private static extern int hid_get_manufacturer_string(IntPtr device, string Data, int maxlength); + public static int GetManufacturerString(IntPtr Device, string Data, int MaxLength) { return hid_get_manufacturer_string(Device, Data, MaxLength); @@ -235,6 +248,7 @@ namespace Vocaluxe.Lib.Input [DllImport(HIDapiDll, ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, EntryPoint = "hid_get_product_string", CharSet = CharSet.Unicode)] private static extern int hid_get_product_string(IntPtr device, string Data, int maxlength); + public static int GetProductString(IntPtr Device, string Data, int MaxLength) { return hid_get_product_string(Device, Data, MaxLength); @@ -242,6 +256,7 @@ namespace Vocaluxe.Lib.Input [DllImport(HIDapiDll, ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, EntryPoint = "hid_get_serial_number_string", CharSet = CharSet.Unicode)] private static extern int hid_get_serial_number_string(IntPtr device, string Data, int maxlength); + public static int GetSerialNumberString(IntPtr Device, string Data, int MaxLength) { return hid_get_serial_number_string(Device, Data, MaxLength); @@ -249,6 +264,7 @@ namespace Vocaluxe.Lib.Input [DllImport(HIDapiDll, ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, EntryPoint = "hid_get_indexed_string", CharSet = CharSet.Unicode)] private static extern int hid_get_indexed_string(IntPtr device, string Data, int maxlength); + public static int GetIndexedString(IntPtr Device, string Data, int MaxLength) { return hid_get_indexed_string(Device, Data, MaxLength); @@ -256,9 +272,10 @@ namespace Vocaluxe.Lib.Input [DllImport(HIDapiDll, ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, EntryPoint = "hid_error", CharSet = CharSet.Unicode)] private static extern string hid_error(IntPtr device); + public static string Error(IntPtr Device) { return hid_error(Device); } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Input/IInput.cs b/Vocaluxe/Lib/Input/IInput.cs index bbbd23bd..f725c4fd 100644 --- a/Vocaluxe/Lib/Input/IInput.cs +++ b/Vocaluxe/Lib/Input/IInput.cs @@ -31,7 +31,7 @@ namespace Vocaluxe.Lib.Input class RumbleTimer { - private Stopwatch _timer; + private readonly Stopwatch _timer; private float _duration; public bool ShouldStart @@ -86,8 +86,8 @@ namespace Vocaluxe.Lib.Input class CGesture { - Point _Begin; - bool _locked; + private Point _Begin; + private bool _locked; public CGesture() { @@ -139,4 +139,4 @@ namespace Vocaluxe.Lib.Input return EGesture.None; } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Input/WiiMote/CWiiMote.cs b/Vocaluxe/Lib/Input/WiiMote/CWiiMote.cs index 981f447b..cfe83fd6 100644 --- a/Vocaluxe/Lib/Input/WiiMote/CWiiMote.cs +++ b/Vocaluxe/Lib/Input/WiiMote/CWiiMote.cs @@ -8,17 +8,17 @@ using VocaluxeLib.Menu; namespace Vocaluxe.Lib.Input.WiiMote { - class CWiiMote : IInput, IDisposable + class CWiiMote : IInput, IDisposable { - WiiMoteLib _WiiMote = null; + private WiiMoteLib _WiiMote; private List _KeysPool; private List _CurrentKeysPool; - private Object _KeyCopyLock = new Object(); + private readonly Object _KeyCopyLock = new Object(); private List _MousePool; private List _CurrentMousePool; - private Object _MouseCopyLock = new Object(); + private readonly Object _MouseCopyLock = new Object(); private bool[] _ButtonStates; private Point _OldPosition; @@ -69,7 +69,6 @@ namespace Vocaluxe.Lib.Input.WiiMote } return true; } - public bool Disconnect() { @@ -95,7 +94,8 @@ namespace Vocaluxe.Lib.Input.WiiMote _CurrentKeysPool.RemoveAt(0); return true; } - else return false; + else + return false; } public bool PollMouseEvent(ref MouseEvent MouseEvent) @@ -106,7 +106,8 @@ namespace Vocaluxe.Lib.Input.WiiMote _CurrentMousePool.RemoveAt(0); return true; } - else return false; + else + return false; } public void SetRumble(float Duration) @@ -116,7 +117,7 @@ namespace Vocaluxe.Lib.Input.WiiMote _RumbleTimer.Set(Duration); } } - + private void MainLoop() { _WiiMote = new WiiMoteLib(); @@ -163,7 +164,8 @@ namespace Vocaluxe.Lib.Input.WiiMote } catch { - return false; ; + return false; + ; } _WiiMote.SetReportType(InputReport.IRAccel, IRSensitivity.Max, false); @@ -190,7 +192,7 @@ namespace Vocaluxe.Lib.Input.WiiMote Point p = ws.IRState.Position; p.X = 1023 - p.X; - + //key events bool alt = false; bool shift = false; @@ -255,13 +257,13 @@ namespace Vocaluxe.Lib.Input.WiiMote //mouse events float reducing = 0.15f; float factor = 1f / (1f - reducing * 2f); - float rx = (((float)p.X / 1024f) - reducing) * factor; - float ry = (((float)p.Y / 768f) - reducing) * factor; + float rx = ((p.X / 1024f) - reducing) * factor; + float ry = ((p.Y / 768f) - reducing) * factor; + + int x = (int)(rx * CSettings.iRenderW); + int y = (int)(ry * CSettings.iRenderH); - int x = (int)(rx * (float)CSettings.iRenderW); - int y = (int)(ry * (float)CSettings.iRenderH); - bool ld = false; bool lbh = !lb && ws.ButtonState.A; bool rbh = false; @@ -306,18 +308,14 @@ namespace Vocaluxe.Lib.Input.WiiMote lock (_KeyCopyLock) { foreach (KeyEvent e in _KeysPool) - { _CurrentKeysPool.Add(e); - } _KeysPool.Clear(); } lock (_MouseCopyLock) { foreach (MouseEvent e in _MousePool) - { _CurrentMousePool.Add(e); - } _MousePool.Clear(); } } @@ -332,4 +330,4 @@ namespace Vocaluxe.Lib.Input.WiiMote GC.SuppressFinalize(this); } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Input/WiiMote/WiiMoteLib.cs b/Vocaluxe/Lib/Input/WiiMote/WiiMoteLib.cs index 8595b876..a0a91ad8 100644 --- a/Vocaluxe/Lib/Input/WiiMote/WiiMoteLib.cs +++ b/Vocaluxe/Lib/Input/WiiMote/WiiMoteLib.cs @@ -1,34 +1,34 @@ using System; using System.Drawing; using System.Threading; - using Vocaluxe.Base; using VocaluxeLib.Menu; namespace Vocaluxe.Lib.Input.WiiMote { + #region DataTypes - public class WiiMoteStatus - { - public AccelCalibrationInfo AccelCalibrationInfo = new AccelCalibrationInfo(); + public class WiiMoteStatus + { + public AccelCalibrationInfo AccelCalibrationInfo = new AccelCalibrationInfo(); - public AccelStatus AccelState = new AccelStatus(); + public AccelStatus AccelState = new AccelStatus(); - public Buttons ButtonState = new Buttons(); + public Buttons ButtonState = new Buttons(); - public IRState IRState = new IRState(); + public IRState IRState = new IRState(); - public byte Battery; + public byte Battery; - public bool Rumble; - - public LEDStatus LEDState; + public bool Rumble; - public WiiMoteStatus() - { - IRState.Sensors = new IR[4]; - } - } + public LEDStatus LEDState; + + public WiiMoteStatus() + { + IRState.Sensors = new IR[4]; + } + } public struct LEDStatus { @@ -41,84 +41,84 @@ namespace Vocaluxe.Lib.Input.WiiMote public enum IRMode : byte { Off = 0x00, - Basic = 0x01, // 10 bytes + Basic = 0x01, // 10 bytes Extended = 0x03 // 12 bytes }; public struct IR { public bool Active; - public Point Position; // X: 0-1023; Y: 0-767 - public int Width; // 0-15 + public Point Position; // X: 0-1023; Y: 0-767 + public int Width; // 0-15 } - public struct IRState - { - public IRMode Mode; - public IR[] Sensors; - public Point Position; //0..1023, 0..767 - public Point Distance; //between Point 0 and Point 1 - } + public struct IRState + { + public IRMode Mode; + public IR[] Sensors; + public Point Position; //0..1023, 0..767 + public Point Distance; //between Point 0 and Point 1 + } - public struct AccelStatus - { - public SPoint3 RawValues; //0-255 - public SPoint3f Values; //0-3 - } + public struct AccelStatus + { + public SPoint3 RawValues; //0-255 + public SPoint3f Values; //0-3 + } - public struct AccelCalibrationInfo - { - public byte X0, Y0, Z0; //zero point - public byte XG, YG, ZG; //gravity - } + public struct AccelCalibrationInfo + { + public byte X0, Y0, Z0; //zero point + public byte XG, YG, ZG; //gravity + } - public struct Buttons - { + public struct Buttons + { public bool Up, Down, Left, Right, A, B, Plus, Minus, One, Two, Home; - } + } - public enum InputReport : byte - { - Status = 0x20, - ReadData = 0x21, - Ack = 0x22, - Buttons = 0x30, - ButtonsAccel = 0x31, - Buttons8Bytes = 0x32, - IRAccel = 0x33, - ButtonsExtension = 0x34, - ExtensionAccel = 0x35, - IRExtensionAccel = 0x37, - }; + public enum InputReport : byte + { + Status = 0x20, + ReadData = 0x21, + Ack = 0x22, + Buttons = 0x30, + ButtonsAccel = 0x31, + Buttons8Bytes = 0x32, + IRAccel = 0x33, + ButtonsExtension = 0x34, + ExtensionAccel = 0x35, + IRExtensionAccel = 0x37, + }; - public enum IRSensitivity - { - Level1, - Level2, - Level3, - Level4, - Level5, - Max - } + public enum IRSensitivity + { + Level1, + Level2, + Level3, + Level4, + Level5, + Max + } #endregion DataTypes #region Events - public class WiiMoteChangedEventArgs: EventArgs - { - public WiiMoteStatus WiiMoteState; + public class WiiMoteChangedEventArgs : EventArgs + { + public WiiMoteStatus WiiMoteState; - public WiiMoteChangedEventArgs(WiiMoteStatus ws) - { - WiiMoteState = ws; - } - } + public WiiMoteChangedEventArgs(WiiMoteStatus ws) + { + WiiMoteState = ws; + } + } #endregion Events - public class WiiMoteLib : IDisposable - { + public class WiiMoteLib : IDisposable + { private const ushort VID = 0x057e; - private const ushort PID = 0x0306; //Wiimotion - private const ushort PIDPlus = 0x0330; //Wiimotion Plus + private const ushort PID = 0x0306; //Wiimotion + private const ushort PIDPlus = 0x0330; //Wiimotion Plus // registers private const int REGISTER_IR = 0x04b00030; @@ -126,65 +126,62 @@ namespace Vocaluxe.Lib.Input.WiiMote private const int REGISTER_IR_SENSITIVITY_2 = 0x04b0001a; private const int REGISTER_IR_MODE = 0x04b00033; - private const int REPORT_LENGTH = 22; + private const int REPORT_LENGTH = 22; + + // output commands + private enum OutputReport : byte + { + LEDs = 0x11, + Type = 0x12, + IR = 0x13, + Status = 0x15, + WriteMemory = 0x16, + ReadMemory = 0x17, + SpeakerData = 0x18, + SpeakerMute = 0x19, + IR2 = 0x1a, + }; - // output commands - private enum OutputReport : byte - { - LEDs = 0x11, - Type = 0x12, - IR = 0x13, - Status = 0x15, - WriteMemory = 0x16, - ReadMemory = 0x17, - SpeakerData = 0x18, - SpeakerMute = 0x19, - IR2 = 0x1a, - }; - // data handling private IntPtr _Handle; - private readonly byte[] _Buff = new byte[REPORT_LENGTH]; - private byte[] _ReadBuff; - private int _Address; - private short _Size; + private readonly byte[] _Buff = new byte[REPORT_LENGTH]; + private byte[] _ReadBuff; + private int _Address; + private short _Size; - private Thread _Reader; + private readonly Thread _Reader; private bool _Active; private bool _Error; private bool _Connected; public bool Connected { - get - { - return _Connected; - } + get { return _Connected; } } - private readonly WiiMoteStatus _WiiMoteState = new WiiMoteStatus(); - private readonly AutoResetEvent _ReadDone = new AutoResetEvent(false); + private readonly WiiMoteStatus _WiiMoteState = new WiiMoteStatus(); + private readonly AutoResetEvent _ReadDone = new AutoResetEvent(false); public event EventHandler WiiMoteChanged; #region Interface public WiiMoteLib() - { + { _Connected = false; _Active = true; _Error = false; _Reader = new Thread(ReaderLoop); _Reader.Start(); - } + } - public bool Connect() - { + public bool Connect() + { _Connected = false; if (_Error) return false; CHIDAPI.Exit(); - + if (!CHIDAPI.Init()) { CLog.LogError("WiiMoteLib: Can't initialize HID API"); @@ -205,7 +202,7 @@ namespace Vocaluxe.Lib.Input.WiiMote if (_Connected) return true; - + //Try WiiMotion Plus if (_Connected = CHIDAPI.Open(VID, PIDPlus, out _Handle)) { @@ -213,15 +210,15 @@ namespace Vocaluxe.Lib.Input.WiiMote CHIDAPI.Close(_Handle); } - return _Connected; - } + return _Connected; + } - public void Disconnect() - { + public void Disconnect() + { _Connected = false; _Active = false; - CHIDAPI.Exit(); - } + CHIDAPI.Exit(); + } public void SetReportType(InputReport type, IRSensitivity irSensitivity, bool continuous) { @@ -260,11 +257,11 @@ namespace Vocaluxe.Lib.Input.WiiMote _Buff[0] = (byte)OutputReport.LEDs; _Buff[1] = (byte)( - (led1 ? 0x10 : 0x00) | - (led2 ? 0x20 : 0x00) | - (led3 ? 0x40 : 0x00) | - (led4 ? 0x80 : 0x00) | - RumbleBit); + (led1 ? 0x10 : 0x00) | + (led2 ? 0x20 : 0x00) | + (led3 ? 0x40 : 0x00) | + (led4 ? 0x80 : 0x00) | + RumbleBit); CHIDAPI.Write(_Handle, _Buff); } @@ -303,7 +300,7 @@ namespace Vocaluxe.Lib.Input.WiiMote } catch (Exception e) { - CLog.LogError("(WiiMoteLib) Error reading from device: " + e.ToString()); + CLog.LogError("(WiiMoteLib) Error reading from device: " + e); } if (ParseInputReport(buff)) @@ -315,62 +312,62 @@ namespace Vocaluxe.Lib.Input.WiiMote } } - private bool ParseInputReport(byte[] buff) - { + private bool ParseInputReport(byte[] buff) + { if (buff == null) { _Connected = false; return false; } - InputReport type = (InputReport)buff[0]; + InputReport type = (InputReport)buff[0]; - switch(type) - { - case InputReport.Buttons: - ParseButtons(buff); - break; + switch (type) + { + case InputReport.Buttons: + ParseButtons(buff); + break; - case InputReport.ButtonsAccel: - ParseButtons(buff); - ParseAccel(buff); - break; + case InputReport.ButtonsAccel: + ParseButtons(buff); + ParseAccel(buff); + break; - case InputReport.IRAccel: - ParseButtons(buff); - ParseAccel(buff); - ParseIR(buff); - break; + case InputReport.IRAccel: + ParseButtons(buff); + ParseAccel(buff); + ParseIR(buff); + break; - case InputReport.ButtonsExtension: - ParseButtons(buff); - break; + case InputReport.ButtonsExtension: + ParseButtons(buff); + break; - case InputReport.ExtensionAccel: - ParseButtons(buff); - ParseAccel(buff); - break; + case InputReport.ExtensionAccel: + ParseButtons(buff); + ParseAccel(buff); + break; - case InputReport.IRExtensionAccel: - ParseButtons(buff); - ParseAccel(buff); - ParseIR(buff); - break; + case InputReport.IRExtensionAccel: + ParseButtons(buff); + ParseAccel(buff); + ParseIR(buff); + break; - case InputReport.Status: - ParseButtons(buff); - _WiiMoteState.Battery = buff[6]; + case InputReport.Status: + ParseButtons(buff); + _WiiMoteState.Battery = buff[6]; - _WiiMoteState.LEDState.LED1 = (buff[3] & 0x10) != 0; - _WiiMoteState.LEDState.LED2 = (buff[3] & 0x20) != 0; - _WiiMoteState.LEDState.LED3 = (buff[3] & 0x40) != 0; - _WiiMoteState.LEDState.LED4 = (buff[3] & 0x80) != 0; - break; + _WiiMoteState.LEDState.LED1 = (buff[3] & 0x10) != 0; + _WiiMoteState.LEDState.LED2 = (buff[3] & 0x20) != 0; + _WiiMoteState.LEDState.LED3 = (buff[3] & 0x40) != 0; + _WiiMoteState.LEDState.LED4 = (buff[3] & 0x80) != 0; + break; - case InputReport.ReadData: - ParseButtons(buff); - ParseReadData(buff); - break; + case InputReport.ReadData: + ParseButtons(buff); + ParseReadData(buff); + break; case InputReport.Ack: return false; @@ -378,56 +375,56 @@ namespace Vocaluxe.Lib.Input.WiiMote case InputReport.Buttons8Bytes: break; - default: - //CLog.LogError("(WiiMoteLib) Unknown report type: " + type.ToString("x")); - return false; - } + default: + //CLog.LogError("(WiiMoteLib) Unknown report type: " + type.ToString("x")); + return false; + } - return true; - } + return true; + } - private byte[] DecryptBuffer(byte[] buff) - { - for(int i = 0; i < buff.Length; i++) - buff[i] = (byte)(((buff[i] ^ 0x17) + 0x17) & 0xff); + private byte[] DecryptBuffer(byte[] buff) + { + for (int i = 0; i < buff.Length; i++) + buff[i] = (byte)(((buff[i] ^ 0x17) + 0x17) & 0xff); - return buff; - } + return buff; + } - private void ParseButtons(byte[] buff) - { - _WiiMoteState.ButtonState.A = (buff[2] & 0x08) != 0; - _WiiMoteState.ButtonState.B = (buff[2] & 0x04) != 0; - _WiiMoteState.ButtonState.Minus = (buff[2] & 0x10) != 0; - _WiiMoteState.ButtonState.Home = (buff[2] & 0x80) != 0; - _WiiMoteState.ButtonState.Plus = (buff[1] & 0x10) != 0; - _WiiMoteState.ButtonState.One = (buff[2] & 0x02) != 0; - _WiiMoteState.ButtonState.Two = (buff[2] & 0x01) != 0; - _WiiMoteState.ButtonState.Up = (buff[1] & 0x08) != 0; - _WiiMoteState.ButtonState.Down = (buff[1] & 0x04) != 0; - _WiiMoteState.ButtonState.Left = (buff[1] & 0x01) != 0; - _WiiMoteState.ButtonState.Right = (buff[1] & 0x02) != 0; - } + private void ParseButtons(byte[] buff) + { + _WiiMoteState.ButtonState.A = (buff[2] & 0x08) != 0; + _WiiMoteState.ButtonState.B = (buff[2] & 0x04) != 0; + _WiiMoteState.ButtonState.Minus = (buff[2] & 0x10) != 0; + _WiiMoteState.ButtonState.Home = (buff[2] & 0x80) != 0; + _WiiMoteState.ButtonState.Plus = (buff[1] & 0x10) != 0; + _WiiMoteState.ButtonState.One = (buff[2] & 0x02) != 0; + _WiiMoteState.ButtonState.Two = (buff[2] & 0x01) != 0; + _WiiMoteState.ButtonState.Up = (buff[1] & 0x08) != 0; + _WiiMoteState.ButtonState.Down = (buff[1] & 0x04) != 0; + _WiiMoteState.ButtonState.Left = (buff[1] & 0x01) != 0; + _WiiMoteState.ButtonState.Right = (buff[1] & 0x02) != 0; + } - private void ParseAccel(byte[] buff) - { - _WiiMoteState.AccelState.RawValues.X = buff[3]; - _WiiMoteState.AccelState.RawValues.Y = buff[4]; - _WiiMoteState.AccelState.RawValues.Z = buff[5]; + private void ParseAccel(byte[] buff) + { + _WiiMoteState.AccelState.RawValues.X = buff[3]; + _WiiMoteState.AccelState.RawValues.Y = buff[4]; + _WiiMoteState.AccelState.RawValues.Z = buff[5]; - _WiiMoteState.AccelState.Values.X = (float)((float)_WiiMoteState.AccelState.RawValues.X - _WiiMoteState.AccelCalibrationInfo.X0) / - ((float)_WiiMoteState.AccelCalibrationInfo.XG - _WiiMoteState.AccelCalibrationInfo.X0); - _WiiMoteState.AccelState.Values.Y = (float)((float)_WiiMoteState.AccelState.RawValues.Y - _WiiMoteState.AccelCalibrationInfo.Y0) / - ((float)_WiiMoteState.AccelCalibrationInfo.YG - _WiiMoteState.AccelCalibrationInfo.Y0); - _WiiMoteState.AccelState.Values.Z = (float)((float)_WiiMoteState.AccelState.RawValues.Z - _WiiMoteState.AccelCalibrationInfo.Z0) / - ((float)_WiiMoteState.AccelCalibrationInfo.ZG - _WiiMoteState.AccelCalibrationInfo.Z0); - } + _WiiMoteState.AccelState.Values.X = ((float)_WiiMoteState.AccelState.RawValues.X - _WiiMoteState.AccelCalibrationInfo.X0) / + ((float)_WiiMoteState.AccelCalibrationInfo.XG - _WiiMoteState.AccelCalibrationInfo.X0); + _WiiMoteState.AccelState.Values.Y = ((float)_WiiMoteState.AccelState.RawValues.Y - _WiiMoteState.AccelCalibrationInfo.Y0) / + ((float)_WiiMoteState.AccelCalibrationInfo.YG - _WiiMoteState.AccelCalibrationInfo.Y0); + _WiiMoteState.AccelState.Values.Z = ((float)_WiiMoteState.AccelState.RawValues.Z - _WiiMoteState.AccelCalibrationInfo.Z0) / + ((float)_WiiMoteState.AccelCalibrationInfo.ZG - _WiiMoteState.AccelCalibrationInfo.Z0); + } - private void ParseIR(byte[] buff) - { - switch(_WiiMoteState.IRState.Mode) - { - case IRMode.Basic: + private void ParseIR(byte[] buff) + { + switch (_WiiMoteState.IRState.Mode) + { + case IRMode.Basic: if (_WiiMoteState.IRState.Sensors[0].Active = !(buff[6] == 0xff && buff[7] == 0xff)) { _WiiMoteState.IRState.Sensors[0].Position.X = buff[6] | ((buff[8] >> 4) & 0x03) << 8; @@ -441,8 +438,8 @@ namespace Vocaluxe.Lib.Input.WiiMote _WiiMoteState.IRState.Sensors[1].Position.Y = buff[10] | ((buff[8] >> 2) & 0x03) << 8; _WiiMoteState.IRState.Sensors[1].Width = 0; } - break; - case IRMode.Extended: + break; + case IRMode.Extended: for (int i = 0; i < 4; i++) { if (_WiiMoteState.IRState.Sensors[i].Active = !(buff[6 + i * 3] == 0xff && buff[7 + i * 3] == 0xff && buff[8 + i * 3] == 0xff)) @@ -452,8 +449,8 @@ namespace Vocaluxe.Lib.Input.WiiMote _WiiMoteState.IRState.Sensors[i].Width = buff[8 + i * 3] & 0x0f; } } - break; - } + break; + } if (_WiiMoteState.IRState.Sensors[0].Active && _WiiMoteState.IRState.Sensors[1].Active) { @@ -475,11 +472,10 @@ namespace Vocaluxe.Lib.Input.WiiMote else _WiiMoteState.IRState.Position.Y = _WiiMoteState.IRState.Sensors[0].Position.Y + _WiiMoteState.IRState.Distance.Y / 2; } + } - } - - private void ParseReadData(byte[] buff) - { + private void ParseReadData(byte[] buff) + { if ((buff[3] & 0x08) != 0) { CLog.LogError("Error reading data from WiiMote: Bytes do not exist"); @@ -492,137 +488,137 @@ namespace Vocaluxe.Lib.Input.WiiMote _Connected = false; } - int size = (buff[3] >> 4) + 1; - int offset = (buff[4] << 8 | buff[5]); + int size = (buff[3] >> 4) + 1; + int offset = (buff[4] << 8 | buff[5]); - Array.Copy(buff, 6, _ReadBuff, offset - _Address, size); + Array.Copy(buff, 6, _ReadBuff, offset - _Address, size); - if(_Address + _Size == offset + size) - _ReadDone.Set(); - } + if (_Address + _Size == offset + size) + _ReadDone.Set(); + } - private byte RumbleBit - { + private byte RumbleBit + { get { if (_WiiMoteState.Rumble) - return (byte)0x1; - return (byte)0x0; + return 0x1; + return 0x0; } - } + } - private bool ReadCalibration() - { - // this appears to change the report type to 0x31 - byte[] buff = ReadData(0x0016, 7); + private bool ReadCalibration() + { + // this appears to change the report type to 0x31 + byte[] buff = ReadData(0x0016, 7); if (buff == null) return false; - _WiiMoteState.AccelCalibrationInfo.X0 = buff[0]; - _WiiMoteState.AccelCalibrationInfo.Y0 = buff[1]; - _WiiMoteState.AccelCalibrationInfo.Z0 = buff[2]; - _WiiMoteState.AccelCalibrationInfo.XG = buff[4]; - _WiiMoteState.AccelCalibrationInfo.YG = buff[5]; - _WiiMoteState.AccelCalibrationInfo.ZG = buff[6]; + _WiiMoteState.AccelCalibrationInfo.X0 = buff[0]; + _WiiMoteState.AccelCalibrationInfo.Y0 = buff[1]; + _WiiMoteState.AccelCalibrationInfo.Z0 = buff[2]; + _WiiMoteState.AccelCalibrationInfo.XG = buff[4]; + _WiiMoteState.AccelCalibrationInfo.YG = buff[5]; + _WiiMoteState.AccelCalibrationInfo.ZG = buff[6]; return true; - } - - private void EnableIR(IRMode mode, IRSensitivity Sensitivity) - { - _WiiMoteState.IRState.Mode = mode; + } - ClearReport(); - _Buff[0] = (byte)OutputReport.IR; - _Buff[1] = (byte)(0x04 | RumbleBit); + private void EnableIR(IRMode mode, IRSensitivity Sensitivity) + { + _WiiMoteState.IRState.Mode = mode; + + ClearReport(); + _Buff[0] = (byte)OutputReport.IR; + _Buff[1] = (byte)(0x04 | RumbleBit); CHIDAPI.Write(_Handle, _Buff); Thread.Sleep(50); - ClearReport(); - _Buff[0] = (byte)OutputReport.IR2; - _Buff[1] = (byte)(0x04 | RumbleBit); + ClearReport(); + _Buff[0] = (byte)OutputReport.IR2; + _Buff[1] = (byte)(0x04 | RumbleBit); CHIDAPI.Write(_Handle, _Buff); Thread.Sleep(50); - WriteData(REGISTER_IR, 0x08); + WriteData(REGISTER_IR, 0x08); Thread.Sleep(50); - switch(Sensitivity) - { - case IRSensitivity.Level1: - WriteData(REGISTER_IR_SENSITIVITY_1, 9, new byte[] {0x02, 0x00, 0x00, 0x71, 0x01, 0x00, 0x64, 0x00, 0xfe}); + switch (Sensitivity) + { + case IRSensitivity.Level1: + WriteData(REGISTER_IR_SENSITIVITY_1, 9, new byte[] {0x02, 0x00, 0x00, 0x71, 0x01, 0x00, 0x64, 0x00, 0xfe}); Thread.Sleep(50); WriteData(REGISTER_IR_SENSITIVITY_2, 2, new byte[] {0xfd, 0x05}); - break; - case IRSensitivity.Level2: - WriteData(REGISTER_IR_SENSITIVITY_1, 9, new byte[] {0x02, 0x00, 0x00, 0x71, 0x01, 0x00, 0x96, 0x00, 0xb4}); + break; + case IRSensitivity.Level2: + WriteData(REGISTER_IR_SENSITIVITY_1, 9, new byte[] {0x02, 0x00, 0x00, 0x71, 0x01, 0x00, 0x96, 0x00, 0xb4}); Thread.Sleep(50); WriteData(REGISTER_IR_SENSITIVITY_2, 2, new byte[] {0xb3, 0x04}); - break; - case IRSensitivity.Level3: - WriteData(REGISTER_IR_SENSITIVITY_1, 9, new byte[] {0x02, 0x00, 0x00, 0x71, 0x01, 0x00, 0xaa, 0x00, 0x64}); + break; + case IRSensitivity.Level3: + WriteData(REGISTER_IR_SENSITIVITY_1, 9, new byte[] {0x02, 0x00, 0x00, 0x71, 0x01, 0x00, 0xaa, 0x00, 0x64}); Thread.Sleep(50); WriteData(REGISTER_IR_SENSITIVITY_2, 2, new byte[] {0x63, 0x03}); - break; - case IRSensitivity.Level4: - WriteData(REGISTER_IR_SENSITIVITY_1, 9, new byte[] {0x02, 0x00, 0x00, 0x71, 0x01, 0x00, 0xc8, 0x00, 0x36}); + break; + case IRSensitivity.Level4: + WriteData(REGISTER_IR_SENSITIVITY_1, 9, new byte[] {0x02, 0x00, 0x00, 0x71, 0x01, 0x00, 0xc8, 0x00, 0x36}); Thread.Sleep(50); WriteData(REGISTER_IR_SENSITIVITY_2, 2, new byte[] {0x35, 0x03}); - break; - case IRSensitivity.Level5: - WriteData(REGISTER_IR_SENSITIVITY_1, 9, new byte[] {0x07, 0x00, 0x00, 0x71, 0x01, 0x00, 0x72, 0x00, 0x20}); + break; + case IRSensitivity.Level5: + WriteData(REGISTER_IR_SENSITIVITY_1, 9, new byte[] {0x07, 0x00, 0x00, 0x71, 0x01, 0x00, 0x72, 0x00, 0x20}); Thread.Sleep(50); WriteData(REGISTER_IR_SENSITIVITY_2, 2, new byte[] {0x1, 0x03}); - break; - case IRSensitivity.Max: - WriteData(REGISTER_IR_SENSITIVITY_1, 9, new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x00, 0x41}); + break; + case IRSensitivity.Max: + WriteData(REGISTER_IR_SENSITIVITY_1, 9, new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x00, 0x41}); Thread.Sleep(50); WriteData(REGISTER_IR_SENSITIVITY_2, 2, new byte[] {0x40, 0x00}); - break; - } + break; + } Thread.Sleep(50); - WriteData(REGISTER_IR_MODE, (byte)mode); + WriteData(REGISTER_IR_MODE, (byte)mode); Thread.Sleep(50); - WriteData(REGISTER_IR, 0x08); + WriteData(REGISTER_IR, 0x08); Thread.Sleep(50); - } + } - private void DisableIR() - { - _WiiMoteState.IRState.Mode = IRMode.Off; + private void DisableIR() + { + _WiiMoteState.IRState.Mode = IRMode.Off; - ClearReport(); - _Buff[0] = (byte)OutputReport.IR; - _Buff[1] = RumbleBit; + ClearReport(); + _Buff[0] = (byte)OutputReport.IR; + _Buff[1] = RumbleBit; CHIDAPI.Write(_Handle, _Buff); - ClearReport(); - _Buff[0] = (byte)OutputReport.IR2; - _Buff[1] = RumbleBit; + ClearReport(); + _Buff[0] = (byte)OutputReport.IR2; + _Buff[1] = RumbleBit; CHIDAPI.Write(_Handle, _Buff); - } + } - private void ClearReport() - { - Array.Clear(_Buff, 0, REPORT_LENGTH); - } + private void ClearReport() + { + Array.Clear(_Buff, 0, REPORT_LENGTH); + } - private byte[] ReadData(int address, short size) - { - ClearReport(); + private byte[] ReadData(int address, short size) + { + ClearReport(); - _ReadBuff = new byte[size]; - _Address = address & 0xffff; - _Size = size; + _ReadBuff = new byte[size]; + _Address = address & 0xffff; + _Size = size; - _Buff[0] = (byte)OutputReport.ReadMemory; - _Buff[1] = (byte)(((address & 0xff000000) >> 24) | RumbleBit); - _Buff[2] = (byte)((address & 0x00ff0000) >> 16); - _Buff[3] = (byte)((address & 0x0000ff00) >> 8); - _Buff[4] = (byte)(address & 0x000000ff); + _Buff[0] = (byte)OutputReport.ReadMemory; + _Buff[1] = (byte)(((address & 0xff000000) >> 24) | RumbleBit); + _Buff[2] = (byte)((address & 0x00ff0000) >> 16); + _Buff[3] = (byte)((address & 0x0000ff00) >> 8); + _Buff[4] = (byte)(address & 0x000000ff); - _Buff[5] = (byte)((size & 0xff00) >> 8); - _Buff[6] = (byte)(size & 0xff); + _Buff[5] = (byte)((size & 0xff00) >> 8); + _Buff[6] = (byte)(size & 0xff); CHIDAPI.Write(_Handle, _Buff); @@ -632,47 +628,47 @@ namespace Vocaluxe.Lib.Input.WiiMote return null; } - return _ReadBuff; - } - - private void WriteData(int address, byte data) - { - WriteData(address, 1, new byte[] { data }); - } + return _ReadBuff; + } - private void WriteData(int address, byte size, byte[] buff) - { - ClearReport(); + private void WriteData(int address, byte data) + { + WriteData(address, 1, new[] {data}); + } - _Buff[0] = (byte)OutputReport.WriteMemory; - _Buff[1] = (byte)(((address & 0xff000000) >> 24) | RumbleBit); - _Buff[2] = (byte)((address & 0x00ff0000) >> 16); - _Buff[3] = (byte)((address & 0x0000ff00) >> 8); - _Buff[4] = (byte)(address & 0x000000ff); - _Buff[5] = size; - Array.Copy(buff, 0, _Buff, 6, size); + private void WriteData(int address, byte size, byte[] buff) + { + ClearReport(); + + _Buff[0] = (byte)OutputReport.WriteMemory; + _Buff[1] = (byte)(((address & 0xff000000) >> 24) | RumbleBit); + _Buff[2] = (byte)((address & 0x00ff0000) >> 16); + _Buff[3] = (byte)((address & 0x0000ff00) >> 8); + _Buff[4] = (byte)(address & 0x000000ff); + _Buff[5] = size; + Array.Copy(buff, 0, _Buff, 6, size); CHIDAPI.Write(_Handle, _Buff); - Thread.Sleep(100); - } + Thread.Sleep(100); + } #endregion Private stuff #region IDisposable Members public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } + { + Dispose(true); + GC.SuppressFinalize(this); + } - protected virtual void Dispose(bool disposing) - { + protected virtual void Dispose(bool disposing) + { if (disposing) { Disconnect(); _ReadDone.Close(); } - } - #endregion - } + } + #endregion + } } \ No newline at end of file diff --git a/Vocaluxe/Lib/Playlist/CPlaylistFile.cs b/Vocaluxe/Lib/Playlist/CPlaylistFile.cs index 3e799c76..218bd83b 100644 --- a/Vocaluxe/Lib/Playlist/CPlaylistFile.cs +++ b/Vocaluxe/Lib/Playlist/CPlaylistFile.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using System.IO; +using System.Text; using System.Xml; - using Vocaluxe.Base; using VocaluxeLib.Menu; using VocaluxeLib.Menu.SongMenu; @@ -11,13 +11,13 @@ namespace Vocaluxe.Lib.Playlist { public class CPlaylistFile { - private static XmlWriterSettings _settings = new XmlWriterSettings(); + private static readonly XmlWriterSettings _settings = new XmlWriterSettings(); public string PlaylistName; public string PlaylistFile; public List Songs = new List(); - public CPlaylistFile() + public CPlaylistFile() { Init(); PlaylistName = string.Empty; @@ -34,11 +34,10 @@ namespace Vocaluxe.Lib.Playlist private void Init() { _settings.Indent = true; - _settings.Encoding = System.Text.Encoding.UTF8; + _settings.Encoding = Encoding.UTF8; _settings.ConformanceLevel = ConformanceLevel.Document; } - public void SavePlaylist() { if (PlaylistFile.Length == 0) @@ -58,9 +57,7 @@ namespace Vocaluxe.Lib.Playlist { i++; if (!File.Exists(Path.Combine(CSettings.sFolderPlaylists, filename + i + ".xml"))) - { filename += i; - } } PlaylistFile = Path.Combine(CSettings.sFolderPlaylists, filename + ".xml"); @@ -105,9 +102,7 @@ namespace Vocaluxe.Lib.Playlist writer.WriteEndElement(); } else - { CLog.LogError("Playlist.SavePlaylist(): Can't find Song. This should never happen!"); - } } writer.WriteEndElement(); @@ -144,7 +139,7 @@ namespace Vocaluxe.Lib.Playlist { xmlReader.GetValue("//root/Songs/" + songs[i] + "/Artist", ref artist, String.Empty); xmlReader.GetValue("//root/Songs/" + songs[i] + "/Title", ref title, String.Empty); - xmlReader.TryGetEnumValue("//root/Songs/" + songs[i] + "/GameMode", ref gm); + xmlReader.TryGetEnumValue("//root/Songs/" + songs[i] + "/GameMode", ref gm); CPlaylistSong song = new CPlaylistSong(); song.SongID = -1; @@ -165,15 +160,11 @@ namespace Vocaluxe.Lib.Playlist Songs.Add(song); } else - { CLog.LogError("Can't find song '" + title + "' from '" + artist + "' in playlist file: " + PlaylistFile); - } } } else - { CLog.LogError("Can't find PlaylistName in Playlist File: " + PlaylistFile); - } } public void AddSong(int SongID) @@ -185,7 +176,7 @@ namespace Vocaluxe.Lib.Playlist else song.GameMode = EGameMode.TR_GAMEMODE_NORMAL; - Songs.Add(song); + Songs.Add(song); } public void AddSong(int SongID, EGameMode gm) @@ -194,7 +185,7 @@ namespace Vocaluxe.Lib.Playlist song.SongID = SongID; song.GameMode = gm; - Songs.Add(song); + Songs.Add(song); } public void DeleteSong(int SongNr) @@ -205,17 +196,13 @@ namespace Vocaluxe.Lib.Playlist public void SongUp(int SongNr) { if (SongNr < Songs.Count - 1 && SongNr > 0) - { Songs.Reverse(SongNr - 1, 2); - } } public void SongDown(int SongNr) { if (SongNr < Songs.Count - 1 && SongNr >= 0) - { Songs.Reverse(SongNr, 2); - } } public void SongMove(int SourceNr, int DestNr) @@ -237,4 +224,4 @@ namespace Vocaluxe.Lib.Playlist Songs.Insert(DestNr, ps); } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Sound/CDirectSoundRecord.cs b/Vocaluxe/Lib/Sound/CDirectSoundRecord.cs index 1ea60f68..b6eab72d 100644 --- a/Vocaluxe/Lib/Sound/CDirectSoundRecord.cs +++ b/Vocaluxe/Lib/Sound/CDirectSoundRecord.cs @@ -9,20 +9,18 @@ namespace Vocaluxe.Lib.Sound { class CDirectSoundRecord : IRecord { - private bool _initialized = false; - private List _Devices = null; - private SRecordDevice[] _DeviceConfig = null; - private List _Sources = null; + private bool _initialized; + private List _Devices; + private SRecordDevice[] _DeviceConfig; + private List _Sources; - private CBuffer[] _Buffer; + private readonly CBuffer[] _Buffer; public CDirectSoundRecord() { _Buffer = new CBuffer[CSettings.MaxNumPlayer]; for (int i = 0; i < _Buffer.Length; i++) - { _Buffer[i] = new CBuffer(); - } Init(); } @@ -38,7 +36,6 @@ namespace Vocaluxe.Lib.Sound { using (DirectSoundCapture ds = new DirectSoundCapture(dev.DriverGuid)) { - SRecordDevice device = new SRecordDevice(); device.Driver = dev.DriverGuid.ToString(); device.ID = id; @@ -81,9 +78,7 @@ namespace Vocaluxe.Lib.Sound return false; for (int i = 0; i < _Buffer.Length; i++) - { _Buffer[i].Reset(); - } _DeviceConfig = DeviceConfig; bool[] active = new bool[DeviceConfig.Length]; @@ -108,11 +103,10 @@ namespace Vocaluxe.Lib.Sound { SoundCardSource source = new SoundCardSource(guid[i], channels[i]); source.SampleRateKHz = 44.1; - source.SampleDataReady += this.OnDataReady; + source.SampleDataReady += OnDataReady; source.Start(); _Sources.Add(source); - } } @@ -134,6 +128,7 @@ namespace Vocaluxe.Lib.Sound return true; } + public void AnalyzeBuffer(int Player) { if (!_initialized) @@ -243,8 +238,8 @@ namespace Vocaluxe.Lib.Sound { public SampleDataEventArgs(byte[] data, Guid guid) { - this.Data = data; - this.Guid = guid; + Data = data; + Guid = guid; } public byte[] Data { get; private set; } @@ -254,167 +249,154 @@ namespace Vocaluxe.Lib.Sound public class SoundCardSource : IDisposable { private volatile bool running; - private int bufferSize; + private readonly int bufferSize; private CaptureBuffer buffer; private CaptureBufferDescription bufferDescription; private DirectSoundCapture captureDevice; - private WaveFormat waveFormat; + private readonly WaveFormat waveFormat; private Thread captureThread; private List notifications; private int bufferPortionCount; private int bufferPortionSize; private WaitHandle[] waitHandles; private double sampleRate; - private Guid guid; - private short channels; + private readonly Guid guid; + private readonly short channels; public SoundCardSource(Guid guid, short channels) { this.guid = guid; this.channels = channels; - this.waveFormat = new WaveFormat(); - this.SampleRateKHz = 44.1; - this.bufferSize = 2048; + waveFormat = new WaveFormat(); + SampleRateKHz = 44.1; + bufferSize = 2048; } public event EventHandler SampleDataReady = delegate { }; public double SampleRateKHz { - get - { - return this.sampleRate; - } + get { return sampleRate; } set { - this.sampleRate = value; + sampleRate = value; - if (this.running) - { - this.Restart(); - } + if (running) + Restart(); } } public void Start() { - if (this.running) - { + if (running) throw new InvalidOperationException(); - } - if (this.captureDevice == null) - { - this.captureDevice = new DirectSoundCapture(guid); - } + if (captureDevice == null) + captureDevice = new DirectSoundCapture(guid); - this.waveFormat.FormatTag = WaveFormatTag.Pcm; // Change to WaveFormatTag.IeeeFloat for float - this.waveFormat.BitsPerSample = 16; // Set this to 32 for float - this.waveFormat.BlockAlignment = (short)(channels * (waveFormat.BitsPerSample / 8)); - this.waveFormat.Channels = this.channels; - this.waveFormat.SamplesPerSecond = (int)(this.SampleRateKHz * 1000D); - this.waveFormat.AverageBytesPerSecond = - this.waveFormat.SamplesPerSecond * - this.waveFormat.BlockAlignment; + waveFormat.FormatTag = WaveFormatTag.Pcm; // Change to WaveFormatTag.IeeeFloat for float + waveFormat.BitsPerSample = 16; // Set this to 32 for float + waveFormat.BlockAlignment = (short)(channels * (waveFormat.BitsPerSample / 8)); + waveFormat.Channels = channels; + waveFormat.SamplesPerSecond = (int)(SampleRateKHz * 1000D); + waveFormat.AverageBytesPerSecond = + waveFormat.SamplesPerSecond * + waveFormat.BlockAlignment; - this.bufferPortionCount = 2; + bufferPortionCount = 2; - this.bufferDescription.BufferBytes = this.bufferSize * sizeof(short) * bufferPortionCount * this.channels; - this.bufferDescription.Format = this.waveFormat; - this.bufferDescription.WaveMapped = false; + bufferDescription.BufferBytes = bufferSize * sizeof(short) * bufferPortionCount * channels; + bufferDescription.Format = waveFormat; + bufferDescription.WaveMapped = false; - this.buffer = new CaptureBuffer(this.captureDevice, this.bufferDescription); + buffer = new CaptureBuffer(captureDevice, bufferDescription); - this.bufferPortionSize = this.buffer.SizeInBytes / this.bufferPortionCount; - this.notifications = new List(); + bufferPortionSize = buffer.SizeInBytes / bufferPortionCount; + notifications = new List(); - for (int i = 0; i < this.bufferPortionCount; i++) + for (int i = 0; i < bufferPortionCount; i++) { NotificationPosition notification = new NotificationPosition(); - notification.Offset = this.bufferPortionCount - 1 + (bufferPortionSize * i); + notification.Offset = bufferPortionCount - 1 + (bufferPortionSize * i); notification.Event = new AutoResetEvent(false); - this.notifications.Add(notification); + notifications.Add(notification); } - this.buffer.SetNotificationPositions(this.notifications.ToArray()); - this.waitHandles = new WaitHandle[this.notifications.Count]; + buffer.SetNotificationPositions(notifications.ToArray()); + waitHandles = new WaitHandle[notifications.Count]; - for (int i = 0; i < this.notifications.Count; i++) - { - this.waitHandles[i] = this.notifications[i].Event; - } + for (int i = 0; i < notifications.Count; i++) + waitHandles[i] = notifications[i].Event; - this.captureThread = new Thread(new ThreadStart(this.CaptureThread)); - this.captureThread.IsBackground = true; + captureThread = new Thread(CaptureThread); + captureThread.IsBackground = true; - this.running = true; - this.captureThread.Start(); + running = true; + captureThread.Start(); } public void Stop() { - this.running = false; + running = false; - if (this.captureThread != null) + if (captureThread != null) { - this.captureThread.Join(); - this.captureThread = null; + captureThread.Join(); + captureThread = null; } - if (this.buffer != null) + if (buffer != null) { - this.buffer.Dispose(); - this.buffer = null; + buffer.Dispose(); + buffer = null; } - if (this.notifications != null) + if (notifications != null) { - for (int i = 0; i < this.notifications.Count; i++) - { - this.notifications[i].Event.Close(); - } + for (int i = 0; i < notifications.Count; i++) + notifications[i].Event.Close(); - this.notifications.Clear(); - this.notifications = null; + notifications.Clear(); + notifications = null; } } public void Restart() { - this.Stop(); - this.Start(); + Stop(); + Start(); } private void CaptureThread() { - int bufferPortionSamples = this.bufferPortionSize / sizeof(byte); + int bufferPortionSamples = bufferPortionSize / sizeof(byte); // Buffer type must match this.waveFormat.FormatTag and this.waveFormat.BitsPerSample byte[] bufferPortion = new byte[bufferPortionSamples]; int bufferPortionIndex; - this.buffer.Start(true); + buffer.Start(true); - while (this.running) + while (running) { - bufferPortionIndex = WaitHandle.WaitAny(this.waitHandles); + bufferPortionIndex = WaitHandle.WaitAny(waitHandles); - this.buffer.Read( + buffer.Read( bufferPortion, 0, bufferPortionSamples, bufferPortionSize * Math.Abs((bufferPortionIndex - 1) % bufferPortionCount)); - this.SampleDataReady(this, new SampleDataEventArgs(bufferPortion, guid)); + SampleDataReady(this, new SampleDataEventArgs(bufferPortion, guid)); } - this.buffer.Stop(); + buffer.Stop(); } public void Dispose() { - this.Dispose(true); + Dispose(true); GC.SuppressFinalize(this); } @@ -422,16 +404,15 @@ namespace Vocaluxe.Lib.Sound { if (disposing) { - this.Stop(); + Stop(); - if (this.captureDevice != null) + if (captureDevice != null) { - this.captureDevice.Dispose(); - this.captureDevice = null; + captureDevice.Dispose(); + captureDevice = null; } } } } - } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Sound/CGstreamerAudio.cs b/Vocaluxe/Lib/Sound/CGstreamerAudio.cs index dde88c3a..f14a923a 100644 --- a/Vocaluxe/Lib/Sound/CGstreamerAudio.cs +++ b/Vocaluxe/Lib/Sound/CGstreamerAudio.cs @@ -7,6 +7,7 @@ namespace Vocaluxe.Lib.Sound class CGstreamerAudio : IPlayback { //static float LastPosition; + #region log public CGstreamerAudioWrapper.LogCallback Log; @@ -19,7 +20,7 @@ namespace Vocaluxe.Lib.Sound public CGstreamerAudio() { Init(); - Log = new CGstreamerAudioWrapper.LogCallback(LogHandler); + Log = LogHandler; //Is this really needed? CodaAnalyzer complains about it... //GC.SuppressFinalize(Log); CGstreamerAudioWrapper.SetLogCallback(Log); @@ -144,4 +145,4 @@ namespace Vocaluxe.Lib.Sound CGstreamerAudioWrapper.Update(); } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Sound/COpenALPlay.cs b/Vocaluxe/Lib/Sound/COpenALPlay.cs index 090fbf3d..325e513f 100644 --- a/Vocaluxe/Lib/Sound/COpenALPlay.cs +++ b/Vocaluxe/Lib/Sound/COpenALPlay.cs @@ -11,16 +11,15 @@ namespace Vocaluxe.Lib.Sound { class COpenALPlay : IPlayback, IDisposable { - private bool _Initialized = false; - private List _Decoder = new List(); + private bool _Initialized; + private readonly List _Decoder = new List(); private CLOSEPROC closeproc; private int _Count = 1; private AudioContext AC; - private Object MutexDecoder = new Object(); + private readonly Object MutexDecoder = new Object(); private List _Streams; - public COpenALPlay() { @@ -33,11 +32,11 @@ namespace Vocaluxe.Lib.Sound CloseAll(); AC = new AudioContext(); - - AC.MakeCurrent(); - - closeproc = new CLOSEPROC(close_proc); + AC.MakeCurrent(); + + + closeproc = close_proc; _Initialized = true; _Streams = new List(); @@ -49,10 +48,8 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { for (int i = 0; i < _Decoder.Count; i++) - { _Decoder[i].Free(closeproc, i + 1, MutexDecoder); - } - } + } } public void SetGlobalVolume(float Volume) @@ -81,11 +78,8 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { foreach (OpenAlStream stream in _Decoder) - { stream.UploadData(); - } } - } } @@ -110,7 +104,6 @@ namespace Vocaluxe.Lib.Sound _Streams.Add(stream); return stream.handle; } - } return 0; } @@ -122,11 +115,8 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { if (AlreadyAdded(Stream)) - { _Decoder[GetStreamIndex(Stream)].Free(closeproc, Stream, MutexDecoder); - } } - } } @@ -144,10 +134,9 @@ namespace Vocaluxe.Lib.Sound if (AlreadyAdded(Stream)) { _Decoder[GetStreamIndex(Stream)].Loop = Loop; - _Decoder[GetStreamIndex(Stream)].Play(); + _Decoder[GetStreamIndex(Stream)].Play(); } } - } } @@ -158,11 +147,8 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { if (AlreadyAdded(Stream)) - { _Decoder[GetStreamIndex(Stream)].Paused = true; - } } - } } @@ -178,11 +164,8 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { if (AlreadyAdded(Stream)) - { _Decoder[GetStreamIndex(Stream)].Fade(TargetVolume, Seconds); - } } - } } @@ -193,11 +176,8 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { if (AlreadyAdded(Stream)) - { _Decoder[GetStreamIndex(Stream)].FadeAndPause(TargetVolume, Seconds); - } } - } } @@ -208,11 +188,8 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { if (AlreadyAdded(Stream)) - { _Decoder[GetStreamIndex(Stream)].FadeAndStop(TargetVolume, Seconds, closeproc, Stream); - } } - } } @@ -223,11 +200,8 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { if (AlreadyAdded(Stream)) - { _Decoder[GetStreamIndex(Stream)].Volume = Volume; - } } - } } @@ -238,11 +212,8 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { if (AlreadyAdded(Stream)) - { _Decoder[GetStreamIndex(Stream)].VolumeMax = Volume; - } } - } } @@ -253,11 +224,8 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { if (AlreadyAdded(Stream)) - { return _Decoder[GetStreamIndex(Stream)].Length; - } } - } return 0f; } @@ -269,9 +237,7 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { if (AlreadyAdded(Stream)) - { return _Decoder[GetStreamIndex(Stream)].Position; - } } return 0f; @@ -286,11 +252,8 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { if (AlreadyAdded(Stream)) - { return !_Decoder[GetStreamIndex(Stream)].Paused && !_Decoder[GetStreamIndex(Stream)].Finished; - } } - } return false; } @@ -302,11 +265,8 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { if (AlreadyAdded(Stream)) - { return _Decoder[GetStreamIndex(Stream)].Paused; - } } - } return false; } @@ -318,11 +278,8 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { if (AlreadyAdded(Stream)) - { return _Decoder[GetStreamIndex(Stream)].Finished; - } } - } return true; } @@ -334,24 +291,18 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { if (AlreadyAdded(Stream)) - { _Decoder[GetStreamIndex(Stream)].Skip(Position); - } } - } } #endregion Stream Handling - private bool AlreadyAdded(int Stream) { foreach (AudioStreams st in _Streams) { if (st.handle == Stream) - { return true; - } } return false; } @@ -371,9 +322,7 @@ namespace Vocaluxe.Lib.Sound if (_Initialized) { if (AlreadyAdded(Stream)) - { Close(Stream); - } } } @@ -390,7 +339,6 @@ namespace Vocaluxe.Lib.Sound _Streams.RemoveAt(Index); } } - } } @@ -401,70 +349,68 @@ namespace Vocaluxe.Lib.Sound } } - class OpenAlStream: IDisposable + class OpenAlStream : IDisposable { - const int buffer_size = 2048; - const int buffer_count = 5; - const long BUFSIZE = 50000L; + private const int buffer_size = 2048; + private const int buffer_count = 5; + private const long BUFSIZE = 50000L; - Object CloseMutex; + private Object CloseMutex; private int[] _buffers; private int _state; private int _source; private FormatInfo _format; - + private bool _Initialized; private int _ByteCount = 4; private float _Volume = 1f; private float _VolumeMax = 1f; - private Stopwatch _fadeTimer = new Stopwatch(); + private readonly Stopwatch _fadeTimer = new Stopwatch(); - private float _fadeTime = 0f; + private float _fadeTime; private float _targetVolume = 1f; private float _startVolume = 1f; - private bool _closeStreamAfterFade = false; - private bool _pauseStreamAfterFade = false; - private bool _fading = false; - + private bool _closeStreamAfterFade; + private bool _pauseStreamAfterFade; + private bool _fading; private Stopwatch _FadeTimer = new Stopwatch(); - private Stopwatch _Timer = new Stopwatch(); + private readonly Stopwatch _Timer = new Stopwatch(); private CLOSEPROC _Closeproc; private int _StreamID; private string _FileName; private IAudioDecoder _Decoder; private float _BytesPerSecond; - private bool _NoMoreData = false; - + private bool _NoMoreData; - private bool _FileOpened = false; + private bool _FileOpened; - private bool _waiting = false; - private bool _skip = false; - - private bool _Loop = false; - private float _Duration = 0f; - private float _CurrentTime = 0f; - private float _TimeCode = 0f; - - private bool _Paused = false; + private bool _waiting; + private bool _skip; + + private bool _Loop; + private float _Duration; + private float _CurrentTime; + private float _TimeCode; + + private bool _Paused; private RingBuffer _data; - private float _SetStart = 0f; - private float _Start = 0f; - private bool _SetLoop = false; - private bool _SetSkip = false; - private bool _terminated = false; + private float _SetStart; + private float _Start; + private bool _SetLoop; + private bool _SetSkip; + private bool _terminated; - private Thread _DecoderThread; + private readonly Thread _DecoderThread; - AutoResetEvent EventDecode = new AutoResetEvent(false); - - Object MutexData = new Object(); - Object MutexSyncSignals = new Object(); + private AutoResetEvent EventDecode = new AutoResetEvent(false); + + private readonly Object MutexData = new Object(); + private readonly Object MutexSyncSignals = new Object(); public OpenAlStream() { @@ -571,7 +517,7 @@ namespace Vocaluxe.Lib.Sound } public void Fade(float TargetVolume, float FadeTime) - { + { _fading = true; _fadeTimer.Stop(); _fadeTimer.Reset(); @@ -619,7 +565,7 @@ namespace Vocaluxe.Lib.Sound if (_FileOpened) return -1; - if (!System.IO.File.Exists(FileName)) + if (!File.Exists(FileName)) return -1; if (_FileOpened) @@ -633,10 +579,8 @@ namespace Vocaluxe.Lib.Sound _source = AL.GenSource(); _buffers = new int[buffer_count]; for (int i = 0; i < buffer_count; i++) - { _buffers[i] = AL.GenBuffer(); - } - + _state = 0; //AL.SourceQueueBuffers(_source, _buffers.Length, _buffers); } @@ -647,7 +591,7 @@ namespace Vocaluxe.Lib.Sound CLog.LogError("Error Init OpenAL Playback"); return -1; } - + _FileName = FileName; _Decoder.Open(FileName); _Duration = _Decoder.GetLength(); @@ -676,7 +620,6 @@ namespace Vocaluxe.Lib.Sound return -1; } - public bool Skip(float Time) { lock (MutexSyncSignals) @@ -719,7 +662,6 @@ namespace Vocaluxe.Lib.Sound } DoDecode(); - } if (!_terminated) { @@ -729,12 +671,11 @@ namespace Vocaluxe.Lib.Sound _skip = true; _SetSkip = false; - + _Start = _SetStart; _Loop = _SetLoop; } } - } DoFree(); @@ -779,9 +720,7 @@ namespace Vocaluxe.Lib.Sound DoSkip(); } else - { _NoMoreData = true; - } return; } @@ -801,7 +740,7 @@ namespace Vocaluxe.Lib.Sound Stop(); AL.DeleteSource(_source); AL.DeleteBuffers(_buffers); - } + } } _Closeproc(_StreamID); @@ -812,7 +751,7 @@ namespace Vocaluxe.Lib.Sound { if (_fading) { - if ((float)_fadeTimer.ElapsedMilliseconds / 1000f < _fadeTime) + if (_fadeTimer.ElapsedMilliseconds / 1000f < _fadeTime) _Volume = _startVolume + (_targetVolume - _startVolume) * ((_fadeTimer.ElapsedMilliseconds / 1000f) / _fadeTime); else { @@ -860,28 +799,28 @@ namespace Vocaluxe.Lib.Sound { _data.Read(ref buf); - - byte[] b = new byte[2]; - for (int i = 0; i < buf.Length; i += _ByteCount) + + byte[] b = new byte[2]; + for (int i = 0; i < buf.Length; i += _ByteCount) + { + b[0] = buf[i]; + b[1] = buf[i + 1]; + + b = BitConverter.GetBytes((Int16)(BitConverter.ToInt16(b, 0) * _Volume * _VolumeMax)); + buf[i] = b[0]; + buf[i + 1] = b[1]; + + if (_ByteCount == 4) { - b[0] = buf[i]; - b[1] = buf[i + 1]; + b[0] = buf[i + 2]; + b[1] = buf[i + 3]; b = BitConverter.GetBytes((Int16)(BitConverter.ToInt16(b, 0) * _Volume * _VolumeMax)); - buf[i] = b[0]; - buf[i + 1] = b[1]; - - if (_ByteCount == 4) - { - b[0] = buf[i + 2]; - b[1] = buf[i + 3]; - - b = BitConverter.GetBytes((Int16)(BitConverter.ToInt16(b, 0) * _Volume * _VolumeMax)); - buf[i + 2] = b[0]; - buf[i + 3] = b[1]; - } + buf[i + 2] = b[0]; + buf[i + 3] = b[1]; } - + } + int buffer = 0; if (!doit) @@ -906,9 +845,7 @@ namespace Vocaluxe.Lib.Sound } AL.GetSource(_source, ALGetSourcei.SourceState, out _state); if ((ALSourceState)_state != ALSourceState.Playing) - { AL.SourcePlay(_source); - } } _CurrentTime = _TimeCode - _data.BytesNotRead / _BytesPerSecond - 0.1f; @@ -922,5 +859,4 @@ namespace Vocaluxe.Lib.Sound EventDecode = null; } } -} - +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Sound/COpenALRecord.cs b/Vocaluxe/Lib/Sound/COpenALRecord.cs index 379e3ce1..16afc859 100644 --- a/Vocaluxe/Lib/Sound/COpenALRecord.cs +++ b/Vocaluxe/Lib/Sound/COpenALRecord.cs @@ -1,7 +1,4 @@ - -namespace Vocaluxe.Lib.Sound +namespace Vocaluxe.Lib.Sound { - class COpenALRecord - { - } -} + class COpenALRecord {} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Sound/CPortAudioPlay.cs b/Vocaluxe/Lib/Sound/CPortAudioPlay.cs index eba6f00f..3355559e 100644 --- a/Vocaluxe/Lib/Sound/CPortAudioPlay.cs +++ b/Vocaluxe/Lib/Sound/CPortAudioPlay.cs @@ -12,15 +12,14 @@ namespace Vocaluxe.Lib.Sound { class CPortAudioPlay : IPlayback { - private bool _Initialized = false; - private List _Decoder = new List(); + private bool _Initialized; + private readonly List _Decoder = new List(); private CLOSEPROC closeproc; private int _Count = 1; - private Object MutexDecoder = new Object(); + private readonly Object MutexDecoder = new Object(); private List _Streams; - public CPortAudioPlay() { @@ -32,7 +31,7 @@ namespace Vocaluxe.Lib.Sound if (_Initialized) CloseAll(); - closeproc = new CLOSEPROC(close_proc); + closeproc = close_proc; _Initialized = true; _Streams = new List(); @@ -44,10 +43,8 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { for (int i = 0; i < _Decoder.Count; i++) - { _Decoder[i].Free(closeproc, i + 1); - } - } + } } public void SetGlobalVolume(float Volume) @@ -69,9 +66,7 @@ namespace Vocaluxe.Lib.Sound } } - public void Update() - { - } + public void Update() {} #region Stream Handling public int Load(string Media) @@ -94,7 +89,6 @@ namespace Vocaluxe.Lib.Sound _Streams.Add(stream); return stream.handle; } - } return 0; } @@ -106,11 +100,8 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { if (AlreadyAdded(Stream)) - { _Decoder[GetStreamIndex(Stream)].Free(closeproc, Stream); - } } - } } @@ -128,10 +119,9 @@ namespace Vocaluxe.Lib.Sound if (AlreadyAdded(Stream)) { _Decoder[GetStreamIndex(Stream)].Loop = Loop; - _Decoder[GetStreamIndex(Stream)].Play(); + _Decoder[GetStreamIndex(Stream)].Play(); } } - } } @@ -142,11 +132,8 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { if (AlreadyAdded(Stream)) - { _Decoder[GetStreamIndex(Stream)].Paused = true; - } } - } } @@ -162,11 +149,8 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { if (AlreadyAdded(Stream)) - { _Decoder[GetStreamIndex(Stream)].Fade(TargetVolume, Seconds); - } } - } } @@ -177,11 +161,8 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { if (AlreadyAdded(Stream)) - { _Decoder[GetStreamIndex(Stream)].FadeAndPause(TargetVolume, Seconds); - } } - } } @@ -192,11 +173,8 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { if (AlreadyAdded(Stream)) - { _Decoder[GetStreamIndex(Stream)].FadeAndStop(TargetVolume, Seconds, closeproc, Stream); - } } - } } @@ -207,11 +185,8 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { if (AlreadyAdded(Stream)) - { _Decoder[GetStreamIndex(Stream)].Volume = Volume; - } } - } } @@ -222,11 +197,8 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { if (AlreadyAdded(Stream)) - { _Decoder[GetStreamIndex(Stream)].VolumeMax = Volume; - } } - } } @@ -237,11 +209,8 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { if (AlreadyAdded(Stream)) - { return _Decoder[GetStreamIndex(Stream)].Length; - } } - } return 0f; } @@ -253,9 +222,7 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { if (AlreadyAdded(Stream)) - { return _Decoder[GetStreamIndex(Stream)].Position; - } } return 0f; @@ -270,11 +237,8 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { if (AlreadyAdded(Stream)) - { return !_Decoder[GetStreamIndex(Stream)].Paused && !_Decoder[GetStreamIndex(Stream)].Finished; - } } - } return false; } @@ -286,11 +250,8 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { if (AlreadyAdded(Stream)) - { return _Decoder[GetStreamIndex(Stream)].Paused; - } } - } return false; } @@ -302,11 +263,8 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { if (AlreadyAdded(Stream)) - { return _Decoder[GetStreamIndex(Stream)].Finished; - } } - } return true; } @@ -318,24 +276,18 @@ namespace Vocaluxe.Lib.Sound lock (MutexDecoder) { if (AlreadyAdded(Stream)) - { _Decoder[GetStreamIndex(Stream)].Skip(Position); - } } - } } #endregion Stream Handling - private bool AlreadyAdded(int Stream) { foreach (AudioStreams st in _Streams) { if (st.handle == Stream) - { return true; - } } return false; } @@ -355,9 +307,7 @@ namespace Vocaluxe.Lib.Sound if (_Initialized) { if (AlreadyAdded(Stream)) - { Close(Stream); - } } } @@ -374,33 +324,31 @@ namespace Vocaluxe.Lib.Sound _Streams.RemoveAt(Index); } } - } } } - class PortAudioStream: IDisposable + class PortAudioStream : IDisposable { - const long BUFSIZE = 1000000L; - const long BEGINREFILL = 800000L; + private const long BUFSIZE = 1000000L; + private const long BEGINREFILL = 800000L; - private CSyncTimer _SyncTimer; - private static bool _Initialized = false; - private static int _NumStreams = 0; - private static Object _Mutex = new object(); + private readonly CSyncTimer _SyncTimer; + private static bool _Initialized; + private static int _NumStreams; + private static readonly Object _Mutex = new object(); private int _ByteCount = 4; private float _Volume = 1f; private float _VolumeMax = 1f; - - private Stopwatch _fadeTimer = new Stopwatch(); - private float _fadeTime = 0f; + private readonly Stopwatch _fadeTimer = new Stopwatch(); + + private float _fadeTime; private float _targetVolume = 1f; private float _startVolume = 1f; - private bool _closeStreamAfterFade = false; - private bool _pauseStreamAfterFade = false; - private bool _fading = false; - + private bool _closeStreamAfterFade; + private bool _pauseStreamAfterFade; + private bool _fading; private static PortAudio.PaHostApiInfo _apiInfo; private static PortAudio.PaDeviceInfo _outputDeviceInfo; @@ -414,34 +362,33 @@ namespace Vocaluxe.Lib.Sound private string _FileName; private IAudioDecoder _Decoder; private float _BytesPerSecond; - private bool _NoMoreData = false; - + private bool _NoMoreData; - private bool _FileOpened = false; + private bool _FileOpened; - private bool _waiting = false; - private bool _skip = false; - - private bool _Loop = false; - private float _Duration = 0f; - private float _CurrentTime = 0f; - private float _TimeCode = 0f; - - private bool _Paused = false; + private bool _waiting; + private bool _skip; + + private bool _Loop; + private float _Duration; + private float _CurrentTime; + private float _TimeCode; + + private bool _Paused; private RingBuffer _data; - private float _SetStart = 0f; - private float _Start = 0f; - private bool _SetLoop = false; - private bool _SetSkip = false; - private bool _terminated = false; + private float _SetStart; + private float _Start; + private bool _SetLoop; + private bool _SetSkip; + private bool _terminated; - private Thread _DecoderThread; + private readonly Thread _DecoderThread; private AutoResetEvent EventDecode = new AutoResetEvent(false); - - private Object _LockData = new Object(); - private Object _LockSyncSignals = new Object(); + + private readonly Object _LockData = new Object(); + private readonly Object _LockSyncSignals = new Object(); public PortAudioStream() { @@ -527,7 +474,7 @@ namespace Vocaluxe.Lib.Sound _SyncTimer.Pause(); return _SyncTimer.Time; - } + } } } @@ -551,7 +498,7 @@ namespace Vocaluxe.Lib.Sound } public void Fade(float TargetVolume, float FadeTime) - { + { _fading = true; _fadeTimer.Stop(); _fadeTimer.Reset(); @@ -607,7 +554,7 @@ namespace Vocaluxe.Lib.Sound if (_FileOpened) return -1; - if (!System.IO.File.Exists(FileName)) + if (!File.Exists(FileName)) return -1; if (_FileOpened) @@ -634,7 +581,7 @@ namespace Vocaluxe.Lib.Sound } } - _paStreamCallback = new PortAudio.PaStreamCallbackDelegate(_PaStreamCallback); + _paStreamCallback = _PaStreamCallback; } catch (Exception) @@ -643,7 +590,7 @@ namespace Vocaluxe.Lib.Sound CLog.LogError("Error Init PortAudio Playback"); return -1; } - + _FileName = FileName; _Decoder.Open(FileName); _Duration = _Decoder.GetLength(); @@ -658,7 +605,7 @@ namespace Vocaluxe.Lib.Sound _SyncTimer.Time = _CurrentTime; AudioStreams stream = new AudioStreams(0); - + IntPtr data = new IntPtr(0); PortAudio.PaStreamParameters outputParams = new PortAudio.PaStreamParameters(); @@ -694,7 +641,7 @@ namespace Vocaluxe.Lib.Sound _DecoderThread.Priority = ThreadPriority.Normal; _DecoderThread.Name = Path.GetFileName(FileName); _DecoderThread.Start(); - + return stream.handle; } return -1; @@ -805,9 +752,7 @@ namespace Vocaluxe.Lib.Sound DoSkip(); } else - { _NoMoreData = true; - } return; } @@ -905,13 +850,13 @@ namespace Vocaluxe.Lib.Sound else _waiting = true; - float latency = buf.Length / _BytesPerSecond + CConfig.AudioLatency/1000f; + float latency = buf.Length / _BytesPerSecond + CConfig.AudioLatency / 1000f; float time = _TimeCode - _data.BytesNotRead / _BytesPerSecond - latency; if (!_NoMoreData) _CurrentTime = _SyncTimer.Update(time); } - + try { Marshal.Copy(buf, 0, output, (int)frameCount * _ByteCount); @@ -967,7 +912,7 @@ namespace Vocaluxe.Lib.Sound { if (_fading) { - if ((float)_fadeTimer.ElapsedMilliseconds / 1000f < _fadeTime) + if (_fadeTimer.ElapsedMilliseconds / 1000f < _fadeTime) _Volume = _startVolume + (_targetVolume - _startVolume) * ((_fadeTimer.ElapsedMilliseconds / 1000f) / _fadeTime); else { @@ -994,4 +939,4 @@ namespace Vocaluxe.Lib.Sound } } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Sound/CPortAudioRecord.cs b/Vocaluxe/Lib/Sound/CPortAudioRecord.cs index 5e6367e3..0825ad79 100644 --- a/Vocaluxe/Lib/Sound/CPortAudioRecord.cs +++ b/Vocaluxe/Lib/Sound/CPortAudioRecord.cs @@ -1,4 +1,5 @@ -using PortAudioSharp; +using System.Threading; +using PortAudioSharp; using System; using System.Collections.Generic; using System.Runtime.InteropServices; @@ -8,15 +9,14 @@ namespace Vocaluxe.Lib.Sound { class CPortAudioRecord : IRecord { - private bool _initialized = false; - private List _Devices = null; + private bool _initialized; + private List _Devices; private SRecordDevice[] _DeviceConfig; private PortAudio.PaStreamCallbackDelegate _myRecProc; private IntPtr[] _recHandle; - private CBuffer[] _Buffer; - + private readonly CBuffer[] _Buffer; public CPortAudioRecord() { @@ -24,15 +24,13 @@ namespace Vocaluxe.Lib.Sound _Buffer = new CBuffer[CSettings.MaxNumPlayer]; for (int i = 0; i < _Buffer.Length; i++) - { _Buffer[i] = new CBuffer(); - } Init(); } /// - /// Init PortAudio and list record devices + /// Init PortAudio and list record devices /// /// true if success public bool Init() @@ -76,7 +74,7 @@ namespace Vocaluxe.Lib.Sound } _recHandle = new IntPtr[_Devices.Count]; - _myRecProc = new PortAudio.PaStreamCallbackDelegate(myPaStreamCallback); + _myRecProc = myPaStreamCallback; _DeviceConfig = _Devices.ToArray(); } @@ -91,7 +89,7 @@ namespace Vocaluxe.Lib.Sound } /// - /// Start Voice Capturing + /// Start Voice Capturing /// /// /// @@ -110,24 +108,20 @@ namespace Vocaluxe.Lib.Sound return false; for (int i = 0; i < _Buffer.Length; i++) - { _Buffer[i].Reset(); - } for (int i = 0; i < _recHandle.Length; i++) { int waitcount = 0; while (waitcount < 5 && PortAudio.Pa_IsStreamStopped(_recHandle[i]) == PortAudio.PaError.paStreamIsNotStopped) { - System.Threading.Thread.Sleep(1); + Thread.Sleep(1); waitcount++; } } for (int i = 0; i < _recHandle.Length; i++) - { _recHandle[i] = IntPtr.Zero; - } _DeviceConfig = DeviceConfig; bool[] active = new bool[DeviceConfig.Length]; @@ -172,7 +166,7 @@ namespace Vocaluxe.Lib.Sound } /// - /// Stop Voice Capturing + /// Stop Voice Capturing /// /// public bool Stop() @@ -181,14 +175,12 @@ namespace Vocaluxe.Lib.Sound return false; for (int i = 0; i < _recHandle.Length; i++) - { PortAudio.Pa_StopStream(_recHandle[i]); - } return true; } /// - /// Stop all voice capturing streams and terminate PortAudio + /// Stop all voice capturing streams and terminate PortAudio /// public void CloseAll() { @@ -204,7 +196,7 @@ namespace Vocaluxe.Lib.Sound } /// - /// Detect Pitch and Volume of the newest voice buffer + /// Detect Pitch and Volume of the newest voice buffer /// /// public void AnalyzeBuffer(int Player) @@ -326,7 +318,7 @@ namespace Vocaluxe.Lib.Sound } catch (Exception e) { - CLog.LogError("Error on Stream Callback (rec): " + e.ToString()); + CLog.LogError("Error on Stream Callback (rec): " + e); } return PortAudio.PaStreamCallbackResult.paContinue; @@ -346,7 +338,7 @@ namespace Vocaluxe.Lib.Sound } return true; } - + return false; } @@ -367,4 +359,4 @@ namespace Vocaluxe.Lib.Sound return selectedHostApi; } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Sound/Decoder/CAudioDecoder.cs b/Vocaluxe/Lib/Sound/Decoder/CAudioDecoder.cs index 0249cf9f..7ce3f152 100644 --- a/Vocaluxe/Lib/Sound/Decoder/CAudioDecoder.cs +++ b/Vocaluxe/Lib/Sound/Decoder/CAudioDecoder.cs @@ -1,26 +1,19 @@ - -namespace Vocaluxe.Lib.Sound.Decoder +namespace Vocaluxe.Lib.Sound.Decoder { - abstract class CAudioDecoder: IAudioDecoder + abstract class CAudioDecoder : IAudioDecoder { protected bool _Initialized; - public virtual void Init() - { - } + public virtual void Init() {} - public virtual void Close() - { - } + public virtual void Close() {} public void Open(string FileName) { Open(FileName, false); } - public virtual void Open(string FileName, bool Loop) - { - } + public virtual void Open(string FileName, bool Loop) {} public virtual FormatInfo GetFormatInfo() { @@ -32,9 +25,7 @@ namespace Vocaluxe.Lib.Sound.Decoder return 0f; } - public virtual void SetPosition(float Time) - { - } + public virtual void SetPosition(float Time) {} public virtual float GetPosition() { @@ -47,4 +38,4 @@ namespace Vocaluxe.Lib.Sound.Decoder TimeStamp = 0f; } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Sound/Decoder/CAudioDecoderFFmpeg.cs b/Vocaluxe/Lib/Sound/Decoder/CAudioDecoderFFmpeg.cs index a4bc58c9..4495e2df 100644 --- a/Vocaluxe/Lib/Sound/Decoder/CAudioDecoderFFmpeg.cs +++ b/Vocaluxe/Lib/Sound/Decoder/CAudioDecoderFFmpeg.cs @@ -1,13 +1,12 @@ using System; using System.IO; using System.Runtime.InteropServices; - using Vocaluxe.Base; using Vocaluxe.Lib.Video.Acinerella; namespace Vocaluxe.Lib.Sound.Decoder { - class CAudioDecoderFFmpeg: CAudioDecoder, IDisposable + class CAudioDecoderFFmpeg : CAudioDecoder, IDisposable { private TAc_read_callback _rc; private TAc_seek_callback _sc; @@ -15,18 +14,18 @@ namespace Vocaluxe.Lib.Sound.Decoder private IntPtr _instance = IntPtr.Zero; private IntPtr _audiodecoder = IntPtr.Zero; - + private TAc_instance _Instance; private FormatInfo _FormatInfo; private float _CurrentTime; private string _FileName; - private bool _FileOpened = false; + private bool _FileOpened; public override void Init() { - _rc = new TAc_read_callback(read_proc); - _sc = new TAc_seek_callback(seek_proc); + _rc = read_proc; + _sc = seek_proc; _FileOpened = false; @@ -67,9 +66,9 @@ namespace Vocaluxe.Lib.Sound.Decoder } catch (Exception) { - return; + return; } - + AudioStreamIndex = i; break; } @@ -134,7 +133,7 @@ namespace Vocaluxe.Lib.Sound.Decoder if (!_Initialized && !_FileOpened) return 0f; - return (float)_Instance.info.duration / 1000f; + return _Instance.info.duration / 1000f; } public override void SetPosition(float Time) @@ -187,12 +186,12 @@ namespace Vocaluxe.Lib.Sound.Decoder TimeStamp = (float)Decoder.timecode; _CurrentTime = TimeStamp; //Console.WriteLine(_CurrentTime.ToString("#0.000") + " Buffer size: " + Decoder.buffer_size.ToString()); - + Buffer = new byte[Decoder.buffer_size]; if (Decoder.buffer_size > 0) Marshal.Copy(Decoder.buffer, Buffer, 0, Buffer.Length); - + return; } @@ -214,7 +213,7 @@ namespace Vocaluxe.Lib.Sound.Decoder private Int64 seek_proc(IntPtr sender, Int64 pos, Int32 whence) { - return (Int64)_fs.Seek((long)pos, (SeekOrigin)whence); + return _fs.Seek(pos, (SeekOrigin)whence); } #endregion Callbacks @@ -224,4 +223,4 @@ namespace Vocaluxe.Lib.Sound.Decoder _fs = null; } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Sound/Decoder/IAudioDecoder.cs b/Vocaluxe/Lib/Sound/Decoder/IAudioDecoder.cs index a6f5fdb7..36ec5152 100644 --- a/Vocaluxe/Lib/Sound/Decoder/IAudioDecoder.cs +++ b/Vocaluxe/Lib/Sound/Decoder/IAudioDecoder.cs @@ -1,5 +1,4 @@ - -namespace Vocaluxe.Lib.Sound.Decoder +namespace Vocaluxe.Lib.Sound.Decoder { struct FormatInfo { @@ -24,4 +23,4 @@ namespace Vocaluxe.Lib.Sound.Decoder void Decode(out byte[] Buffer, out float TimeStamp); } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Sound/Gstreamer/CGstreamerAudioWrapper.cs b/Vocaluxe/Lib/Sound/Gstreamer/CGstreamerAudioWrapper.cs index e43ef8f2..b356492d 100644 --- a/Vocaluxe/Lib/Sound/Gstreamer/CGstreamerAudioWrapper.cs +++ b/Vocaluxe/Lib/Sound/Gstreamer/CGstreamerAudioWrapper.cs @@ -17,8 +17,10 @@ namespace Vocaluxe.Lib.Sound.Gstreamer #endif #endif #endregion arch + public delegate void LogCallback(string message); - [DllImport (Dll)] + + [DllImport(Dll)] public static extern void SetLogCallback(LogCallback c); [DllImport(Dll)] @@ -37,9 +39,9 @@ namespace Vocaluxe.Lib.Sound.Gstreamer [DllImport(Dll)] public static extern int Load(string Media); - [DllImport(Dll, EntryPoint="LoadPrescan")] + [DllImport(Dll, EntryPoint = "LoadPrescan")] public static extern int Load(string Media, - [MarshalAs(UnmanagedType.U1)] bool Prescan); + [MarshalAs(UnmanagedType.U1)] bool Prescan); [DllImport(Dll)] public static extern void Close(int Stream); @@ -47,9 +49,9 @@ namespace Vocaluxe.Lib.Sound.Gstreamer [DllImport(Dll)] public static extern void Play(int Stream); - [DllImport(Dll, EntryPoint="PlayLoop")] + [DllImport(Dll, EntryPoint = "PlayLoop")] public static extern void Play(int Stream, - [MarshalAs(UnmanagedType.U1)] bool Loop); + [MarshalAs(UnmanagedType.U1)] bool Loop); [DllImport(Dll)] public static extern void Pause(int Stream); @@ -96,4 +98,4 @@ namespace Vocaluxe.Lib.Sound.Gstreamer [DllImport(Dll)] public static extern void Update(); } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Sound/IPlayback.cs b/Vocaluxe/Lib/Sound/IPlayback.cs index 3938804b..df269238 100644 --- a/Vocaluxe/Lib/Sound/IPlayback.cs +++ b/Vocaluxe/Lib/Sound/IPlayback.cs @@ -53,18 +53,15 @@ namespace Vocaluxe.Lib.Sound class RingBuffer { - private byte[] _data; - private long _size; + private readonly byte[] _data; + private readonly long _size; private long _readPos; private long _writePos; private long _bytesNotRead; public long BytesNotRead { - get - { - return _bytesNotRead; - } + get { return _bytesNotRead; } } public RingBuffer(long size) @@ -106,4 +103,4 @@ namespace Vocaluxe.Lib.Sound } } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Sound/IRecord.cs b/Vocaluxe/Lib/Sound/IRecord.cs index 759fc397..2db59a6c 100644 --- a/Vocaluxe/Lib/Sound/IRecord.cs +++ b/Vocaluxe/Lib/Sound/IRecord.cs @@ -55,4 +55,4 @@ namespace Vocaluxe.Lib.Sound SRecordDevice[] RecordDevices(); } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Sound/Portaudio/PortAudio.cs b/Vocaluxe/Lib/Sound/Portaudio/PortAudio.cs index a63e2a47..20ed2234 100644 --- a/Vocaluxe/Lib/Sound/Portaudio/PortAudio.cs +++ b/Vocaluxe/Lib/Sound/Portaudio/PortAudio.cs @@ -1,4 +1,4 @@ - /* +/* * PortAudioSharp - PortAudio bindings for .NET * Copyright 2006-2011 Riccardo Gerosa and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a @@ -23,258 +23,256 @@ using System; using System.Runtime.InteropServices; - -namespace PortAudioSharp { - - /** +namespace PortAudioSharp +{ + /** PortAudio v.19 bindings for .NET */ - public partial class PortAudio - { - #region **** PORTAUDIO CALLBACKS **** - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + + public partial class PortAudio + { + #region **** PORTAUDIO CALLBACKS **** + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate PaStreamCallbackResult PaStreamCallbackDelegate( - IntPtr input, - IntPtr output, - uint frameCount, - ref PaStreamCallbackTimeInfo timeInfo, - PaStreamCallbackFlags statusFlags, - IntPtr userData); - - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - public delegate void PaStreamFinishedCallbackDelegate(IntPtr userData); - - #endregion - - #region **** PORTAUDIO DATA STRUCTURES **** - - [StructLayout (LayoutKind.Sequential)] - public struct PaDeviceInfo { - - public int structVersion; - [MarshalAs (UnmanagedType.LPStr)] - public string name; - public int hostApi; - public int maxInputChannels; - public int maxOutputChannels; - public double defaultLowInputLatency; - public double defaultLowOutputLatency; - public double defaultHighInputLatency; - public double defaultHighOutputLatency; - public double defaultSampleRate; - - public override string ToString() { - return "[" + this.GetType().Name + "]" + "\n" - + "name: " + name + "\n" - + "hostApi: " + hostApi + "\n" - + "maxInputChannels: " + maxInputChannels + "\n" - + "maxOutputChannels: " + maxOutputChannels + "\n" - + "defaultLowInputLatency: " + defaultLowInputLatency + "\n" - + "defaultLowOutputLatency: " + defaultLowOutputLatency + "\n" - + "defaultHighInputLatency: " + defaultHighInputLatency + "\n" - + "defaultHighOutputLatency: " + defaultHighOutputLatency + "\n" - + "defaultSampleRate: " + defaultSampleRate; - } - } - - [StructLayout (LayoutKind.Sequential)] - public struct PaHostApiInfo { - - public int structVersion; - public PaHostApiTypeId type; - [MarshalAs (UnmanagedType.LPStr)] - public string name; - public int deviceCount; - public int defaultInputDevice; - public int defaultOutputDevice; - - public override string ToString() { - return "[" + this.GetType().Name + "]" + "\n" - + "structVersion: " + structVersion + "\n" - + "type: " + type + "\n" - + "name: " + name + "\n" - + "deviceCount: " + deviceCount + "\n" - + "defaultInputDevice: " + defaultInputDevice + "\n" - + "defaultOutputDevice: " + defaultOutputDevice; - } - } - - [StructLayout (LayoutKind.Sequential)] - public struct PaHostErrorInfo { - - public PaHostApiTypeId hostApiType; - public int errorCode; - [MarshalAs (UnmanagedType.LPStr)] - public string errorText; - - public override string ToString() { - return "[" + this.GetType().Name + "]" + "\n" - + "hostApiType: " + hostApiType + "\n" - + "errorCode: " + errorCode + "\n" - + "errorText: " + errorText; - } - } - - [StructLayout (LayoutKind.Sequential)] - public struct PaStreamCallbackTimeInfo { - - public double inputBufferAdcTime; - public double currentTime; - public double outputBufferDacTime; - - public override string ToString() { - return "[" + this.GetType().Name + "]" + "\n" - + "currentTime: " + currentTime + "\n" - + "inputBufferAdcTime: " + inputBufferAdcTime + "\n" - + "outputBufferDacTime: " + outputBufferDacTime; - } - } - - [StructLayout (LayoutKind.Sequential)] - public struct PaStreamInfo { - - public int structVersion; - public double inputLatency; - public double outputLatency; - public double sampleRate; - - public override string ToString() { - return "[" + this.GetType().Name + "]" + "\n" - + "structVersion: " + structVersion + "\n" - + "inputLatency: " + inputLatency + "\n" - + "outputLatency: " + outputLatency + "\n" - + "sampleRate: " + sampleRate; - } - } - - [StructLayout (LayoutKind.Sequential)] - public struct PaStreamParameters { - - public int device; - public int channelCount; - public PaSampleFormat sampleFormat; - public double suggestedLatency; - internal IntPtr hostApiSpecificStreamInfo; - - public override string ToString() { - return "[" + this.GetType().Name + "]" + "\n" - + "device: " + device + "\n" - + "channelCount: " + channelCount + "\n" - + "sampleFormat: " + sampleFormat + "\n" - + "suggestedLatency: " + suggestedLatency; - } - } - - #endregion - - #region **** PORTAUDIO DEFINES **** - - public enum PaDeviceIndex: int - { - paNoDevice = -1, - paUseHostApiSpecificDeviceSpecification = -2 - } + IntPtr input, + IntPtr output, + uint frameCount, + ref PaStreamCallbackTimeInfo timeInfo, + PaStreamCallbackFlags statusFlags, + IntPtr userData); - public enum PaSampleFormat: uint - { - paFloat32 = 0x00000001, - paInt32 = 0x00000002, - paInt24 = 0x00000004, - paInt16 = 0x00000008, - paInt8 = 0x00000010, - paUInt8 = 0x00000020, - paCustomFormat = 0x00010000, - paNonInterleaved = 0x80000000, - } + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void PaStreamFinishedCallbackDelegate(IntPtr userData); + #endregion - public const int paFormatIsSupported = 0; - public const int paFramesPerBufferUnspecified = 0; - - public enum PaStreamFlags: uint - { - paNoFlag = 0, - paClipOff = 0x00000001, - paDitherOff = 0x00000002, - paNeverDropInput = 0x00000004, - paPrimeOutputBuffersUsingStreamCallback = 0x00000008, - paPlatformSpecificFlags = 0xFFFF0000 - } - - public enum PaStreamCallbackFlags: uint - { - paInputUnderflow = 0x00000001, - paInputOverflow = 0x00000002, - paOutputUnderflow = 0x00000004, - paOutputOverflow = 0x00000008, - paPrimingOutput = 0x00000010 - } - - #endregion - - #region **** PORTAUDIO ENUMERATIONS **** - - public enum PaError : int { - paNoError = 0, - paNotInitialized = -10000, - paUnanticipatedHostError, - paInvalidChannelCount, - paInvalidSampleRate, - paInvalidDevice, - paInvalidFlag, - paSampleFormatNotSupported, - paBadIODeviceCombination, - paInsufficientMemory, - paBufferTooBig, - paBufferTooSmall, - paNullCallback, - paBadStreamPtr, - paTimedOut, - paInternalError, - paDeviceUnavailable, - paIncompatibleHostApiSpecificStreamInfo, - paStreamIsStopped, - paStreamIsNotStopped, - paInputOverflowed, - paOutputUnderflowed, - paHostApiNotFound, - paInvalidHostApi, - paCanNotReadFromACallbackStream, - paCanNotWriteToACallbackStream, - paCanNotReadFromAnOutputOnlyStream, - paCanNotWriteToAnInputOnlyStream, - paIncompatibleStreamHostApi, - paBadBufferPtr - } - - public enum PaHostApiTypeId : uint { - paInDevelopment=0, - paDirectSound=1, - paMME=2, - paASIO=3, - paSoundManager=4, - paCoreAudio=5, - paOSS=7, - paALSA=8, - paAL=9, - paBeOS=10, - paWDMKS=11, - paJACK=12, - paWASAPI=13, - paAudioScienceHPI=14 - } - - public enum PaStreamCallbackResult : uint { - paContinue = 0, - paComplete = 1, - paAbort = 2 - } - - #endregion - - #region **** PORTAUDIO FUNCTIONS **** + #region **** PORTAUDIO DATA STRUCTURES **** + [StructLayout(LayoutKind.Sequential)] + public struct PaDeviceInfo + { + public int structVersion; + [MarshalAs(UnmanagedType.LPStr)] public string name; + public int hostApi; + public int maxInputChannels; + public int maxOutputChannels; + public double defaultLowInputLatency; + public double defaultLowOutputLatency; + public double defaultHighInputLatency; + public double defaultHighOutputLatency; + public double defaultSampleRate; + + public override string ToString() + { + return "[" + GetType().Name + "]" + "\n" + + "name: " + name + "\n" + + "hostApi: " + hostApi + "\n" + + "maxInputChannels: " + maxInputChannels + "\n" + + "maxOutputChannels: " + maxOutputChannels + "\n" + + "defaultLowInputLatency: " + defaultLowInputLatency + "\n" + + "defaultLowOutputLatency: " + defaultLowOutputLatency + "\n" + + "defaultHighInputLatency: " + defaultHighInputLatency + "\n" + + "defaultHighOutputLatency: " + defaultHighOutputLatency + "\n" + + "defaultSampleRate: " + defaultSampleRate; + } + } + + [StructLayout(LayoutKind.Sequential)] + public struct PaHostApiInfo + { + public int structVersion; + public PaHostApiTypeId type; + [MarshalAs(UnmanagedType.LPStr)] public string name; + public int deviceCount; + public int defaultInputDevice; + public int defaultOutputDevice; + + public override string ToString() + { + return "[" + GetType().Name + "]" + "\n" + + "structVersion: " + structVersion + "\n" + + "type: " + type + "\n" + + "name: " + name + "\n" + + "deviceCount: " + deviceCount + "\n" + + "defaultInputDevice: " + defaultInputDevice + "\n" + + "defaultOutputDevice: " + defaultOutputDevice; + } + } + + [StructLayout(LayoutKind.Sequential)] + public struct PaHostErrorInfo + { + public PaHostApiTypeId hostApiType; + public int errorCode; + [MarshalAs(UnmanagedType.LPStr)] public string errorText; + + public override string ToString() + { + return "[" + GetType().Name + "]" + "\n" + + "hostApiType: " + hostApiType + "\n" + + "errorCode: " + errorCode + "\n" + + "errorText: " + errorText; + } + } + + [StructLayout(LayoutKind.Sequential)] + public struct PaStreamCallbackTimeInfo + { + public double inputBufferAdcTime; + public double currentTime; + public double outputBufferDacTime; + + public override string ToString() + { + return "[" + GetType().Name + "]" + "\n" + + "currentTime: " + currentTime + "\n" + + "inputBufferAdcTime: " + inputBufferAdcTime + "\n" + + "outputBufferDacTime: " + outputBufferDacTime; + } + } + + [StructLayout(LayoutKind.Sequential)] + public struct PaStreamInfo + { + public int structVersion; + public double inputLatency; + public double outputLatency; + public double sampleRate; + + public override string ToString() + { + return "[" + GetType().Name + "]" + "\n" + + "structVersion: " + structVersion + "\n" + + "inputLatency: " + inputLatency + "\n" + + "outputLatency: " + outputLatency + "\n" + + "sampleRate: " + sampleRate; + } + } + + [StructLayout(LayoutKind.Sequential)] + public struct PaStreamParameters + { + public int device; + public int channelCount; + public PaSampleFormat sampleFormat; + public double suggestedLatency; + internal IntPtr hostApiSpecificStreamInfo; + + public override string ToString() + { + return "[" + GetType().Name + "]" + "\n" + + "device: " + device + "\n" + + "channelCount: " + channelCount + "\n" + + "sampleFormat: " + sampleFormat + "\n" + + "suggestedLatency: " + suggestedLatency; + } + } + #endregion + + #region **** PORTAUDIO DEFINES **** + public enum PaDeviceIndex + { + paNoDevice = -1, + paUseHostApiSpecificDeviceSpecification = -2 + } + + public enum PaSampleFormat : uint + { + paFloat32 = 0x00000001, + paInt32 = 0x00000002, + paInt24 = 0x00000004, + paInt16 = 0x00000008, + paInt8 = 0x00000010, + paUInt8 = 0x00000020, + paCustomFormat = 0x00010000, + paNonInterleaved = 0x80000000, + } + + public const int paFormatIsSupported = 0; + public const int paFramesPerBufferUnspecified = 0; + + public enum PaStreamFlags : uint + { + paNoFlag = 0, + paClipOff = 0x00000001, + paDitherOff = 0x00000002, + paNeverDropInput = 0x00000004, + paPrimeOutputBuffersUsingStreamCallback = 0x00000008, + paPlatformSpecificFlags = 0xFFFF0000 + } + + public enum PaStreamCallbackFlags : uint + { + paInputUnderflow = 0x00000001, + paInputOverflow = 0x00000002, + paOutputUnderflow = 0x00000004, + paOutputOverflow = 0x00000008, + paPrimingOutput = 0x00000010 + } + #endregion + + #region **** PORTAUDIO ENUMERATIONS **** + public enum PaError + { + paNoError = 0, + paNotInitialized = -10000, + paUnanticipatedHostError, + paInvalidChannelCount, + paInvalidSampleRate, + paInvalidDevice, + paInvalidFlag, + paSampleFormatNotSupported, + paBadIODeviceCombination, + paInsufficientMemory, + paBufferTooBig, + paBufferTooSmall, + paNullCallback, + paBadStreamPtr, + paTimedOut, + paInternalError, + paDeviceUnavailable, + paIncompatibleHostApiSpecificStreamInfo, + paStreamIsStopped, + paStreamIsNotStopped, + paInputOverflowed, + paOutputUnderflowed, + paHostApiNotFound, + paInvalidHostApi, + paCanNotReadFromACallbackStream, + paCanNotWriteToACallbackStream, + paCanNotReadFromAnOutputOnlyStream, + paCanNotWriteToAnInputOnlyStream, + paIncompatibleStreamHostApi, + paBadBufferPtr + } + + public enum PaHostApiTypeId : uint + { + paInDevelopment = 0, + paDirectSound = 1, + paMME = 2, + paASIO = 3, + paSoundManager = 4, + paCoreAudio = 5, + paOSS = 7, + paALSA = 8, + paAL = 9, + paBeOS = 10, + paWDMKS = 11, + paJACK = 12, + paWASAPI = 13, + paAudioScienceHPI = 14 + } + + public enum PaStreamCallbackResult : uint + { + paContinue = 0, + paComplete = 1, + paAbort = 2 + } + #endregion + + #region **** PORTAUDIO FUNCTIONS **** #if ARCH_X86 #if WIN private const string PaDll = "x86\\portaudio_x86.dll"; @@ -295,92 +293,97 @@ namespace PortAudioSharp { #endif #endif - [DllImport (PaDll)] - public static extern int Pa_GetVersion(); - - [DllImport (PaDll,EntryPoint="Pa_GetVersionText")] - private static extern IntPtr IntPtr_Pa_GetVersionText(); - - public static string Pa_GetVersionText() { - IntPtr strptr = IntPtr_Pa_GetVersionText(); - return Marshal.PtrToStringAnsi(strptr); - } - - [DllImport (PaDll,EntryPoint="Pa_GetErrorText")] - public static extern IntPtr IntPtr_Pa_GetErrorText(PaError errorCode); - - public static string Pa_GetErrorText(PaError errorCode) { - IntPtr strptr = IntPtr_Pa_GetErrorText(errorCode); - return Marshal.PtrToStringAnsi(strptr); - } - - [DllImport (PaDll)] - public static extern PaError Pa_Initialize(); - - [DllImport (PaDll)] - public static extern PaError Pa_Terminate(); - - [DllImport (PaDll)] - public static extern int Pa_GetHostApiCount(); + [DllImport(PaDll)] + public static extern int Pa_GetVersion(); - [DllImport (PaDll)] - public static extern int Pa_GetDefaultHostApi(); + [DllImport(PaDll, EntryPoint = "Pa_GetVersionText")] + private static extern IntPtr IntPtr_Pa_GetVersionText(); - [DllImport (PaDll,EntryPoint="Pa_GetHostApiInfo")] - public static extern IntPtr IntPtr_Pa_GetHostApiInfo(int hostApi); - - public static PaHostApiInfo Pa_GetHostApiInfo(int hostApi) { - IntPtr structptr = IntPtr_Pa_GetHostApiInfo(hostApi); - return (PaHostApiInfo) Marshal.PtrToStructure(structptr, typeof(PaHostApiInfo)); - } - - [DllImport (PaDll)] - public static extern int Pa_HostApiTypeIdToHostApiIndex(PaHostApiTypeId type); + public static string Pa_GetVersionText() + { + IntPtr strptr = IntPtr_Pa_GetVersionText(); + return Marshal.PtrToStringAnsi(strptr); + } - [DllImport (PaDll)] - public static extern int Pa_HostApiDeviceIndexToDeviceIndex(int hostApi, int hostApiDeviceIndex); + [DllImport(PaDll, EntryPoint = "Pa_GetErrorText")] + public static extern IntPtr IntPtr_Pa_GetErrorText(PaError errorCode); - [DllImport (PaDll,EntryPoint="Pa_GetLastHostErrorInfo")] - public static extern IntPtr IntPtr_Pa_GetLastHostErrorInfo(); - - public static PaHostErrorInfo Pa_GetLastHostErrorInfo() { - IntPtr structptr = IntPtr_Pa_GetLastHostErrorInfo(); - return (PaHostErrorInfo) Marshal.PtrToStructure(structptr, typeof(PaHostErrorInfo)); - } + public static string Pa_GetErrorText(PaError errorCode) + { + IntPtr strptr = IntPtr_Pa_GetErrorText(errorCode); + return Marshal.PtrToStringAnsi(strptr); + } - [DllImport (PaDll)] - public static extern int Pa_GetDeviceCount(); - - [DllImport (PaDll)] - public static extern int Pa_GetDefaultInputDevice(); + [DllImport(PaDll)] + public static extern PaError Pa_Initialize(); - [DllImport (PaDll)] - public static extern int Pa_GetDefaultOutputDevice(); - - [DllImport (PaDll,EntryPoint="Pa_GetDeviceInfo")] - public static extern IntPtr IntPtr_Pa_GetDeviceInfo(int device); - - public static PaDeviceInfo Pa_GetDeviceInfo(int device) { - IntPtr structptr = IntPtr_Pa_GetDeviceInfo(device); - return (PaDeviceInfo) Marshal.PtrToStructure(structptr, typeof(PaDeviceInfo)); - } - - [DllImport (PaDll)] - public static extern PaError Pa_IsFormatSupported( - ref PaStreamParameters inputParameters, - ref PaStreamParameters outputParameters, - double sampleRate); - - [DllImport (PaDll)] - public static extern PaError Pa_OpenStream( - out IntPtr stream, - ref PaStreamParameters inputParameters, - ref PaStreamParameters outputParameters, - double sampleRate, - uint framesPerBuffer, - PaStreamFlags streamFlags, - PaStreamCallbackDelegate streamCallback, - IntPtr userData); + [DllImport(PaDll)] + public static extern PaError Pa_Terminate(); + + [DllImport(PaDll)] + public static extern int Pa_GetHostApiCount(); + + [DllImport(PaDll)] + public static extern int Pa_GetDefaultHostApi(); + + [DllImport(PaDll, EntryPoint = "Pa_GetHostApiInfo")] + public static extern IntPtr IntPtr_Pa_GetHostApiInfo(int hostApi); + + public static PaHostApiInfo Pa_GetHostApiInfo(int hostApi) + { + IntPtr structptr = IntPtr_Pa_GetHostApiInfo(hostApi); + return (PaHostApiInfo)Marshal.PtrToStructure(structptr, typeof(PaHostApiInfo)); + } + + [DllImport(PaDll)] + public static extern int Pa_HostApiTypeIdToHostApiIndex(PaHostApiTypeId type); + + [DllImport(PaDll)] + public static extern int Pa_HostApiDeviceIndexToDeviceIndex(int hostApi, int hostApiDeviceIndex); + + [DllImport(PaDll, EntryPoint = "Pa_GetLastHostErrorInfo")] + public static extern IntPtr IntPtr_Pa_GetLastHostErrorInfo(); + + public static PaHostErrorInfo Pa_GetLastHostErrorInfo() + { + IntPtr structptr = IntPtr_Pa_GetLastHostErrorInfo(); + return (PaHostErrorInfo)Marshal.PtrToStructure(structptr, typeof(PaHostErrorInfo)); + } + + [DllImport(PaDll)] + public static extern int Pa_GetDeviceCount(); + + [DllImport(PaDll)] + public static extern int Pa_GetDefaultInputDevice(); + + [DllImport(PaDll)] + public static extern int Pa_GetDefaultOutputDevice(); + + [DllImport(PaDll, EntryPoint = "Pa_GetDeviceInfo")] + public static extern IntPtr IntPtr_Pa_GetDeviceInfo(int device); + + public static PaDeviceInfo Pa_GetDeviceInfo(int device) + { + IntPtr structptr = IntPtr_Pa_GetDeviceInfo(device); + return (PaDeviceInfo)Marshal.PtrToStructure(structptr, typeof(PaDeviceInfo)); + } + + [DllImport(PaDll)] + public static extern PaError Pa_IsFormatSupported( + ref PaStreamParameters inputParameters, + ref PaStreamParameters outputParameters, + double sampleRate); + + [DllImport(PaDll)] + public static extern PaError Pa_OpenStream( + out IntPtr stream, + ref PaStreamParameters inputParameters, + ref PaStreamParameters outputParameters, + double sampleRate, + uint framesPerBuffer, + PaStreamFlags streamFlags, + PaStreamCallbackDelegate streamCallback, + IntPtr userData); [DllImport(PaDll)] public static extern PaError Pa_OpenStream( @@ -404,156 +407,155 @@ namespace PortAudioSharp { PaStreamCallbackDelegate streamCallback, IntPtr userData); - [DllImport (PaDll)] - public static extern PaError Pa_OpenDefaultStream( - out IntPtr stream, - int numInputChannels, - int numOutputChannels, - uint sampleFormat, - double sampleRate, - uint framesPerBuffer, - PaStreamCallbackDelegate streamCallback, - IntPtr userData); - - [DllImport (PaDll)] - public static extern PaError Pa_CloseStream(IntPtr stream); - - [DllImport (PaDll)] - public static extern PaError Pa_SetStreamFinishedCallback( - ref IntPtr stream, - [MarshalAs(UnmanagedType.FunctionPtr)]PaStreamFinishedCallbackDelegate streamFinishedCallback); - - [DllImport (PaDll)] - public static extern PaError Pa_StartStream(IntPtr stream); - - [DllImport (PaDll)] - public static extern PaError Pa_StopStream(IntPtr stream); - - [DllImport (PaDll)] - public static extern PaError Pa_AbortStream(IntPtr stream); - - [DllImport (PaDll)] - public static extern PaError Pa_IsStreamStopped(IntPtr stream); - - [DllImport (PaDll)] - public static extern PaError Pa_IsStreamActive(IntPtr stream); - - [DllImport (PaDll,EntryPoint="Pa_GetStreamInfo")] - public static extern IntPtr IntPtr_Pa_GetStreamInfo(IntPtr stream); - - public static PaStreamInfo Pa_GetStreamInfo(IntPtr stream) { - IntPtr structptr = IntPtr_Pa_GetStreamInfo(stream); - return (PaStreamInfo) Marshal.PtrToStructure(structptr,typeof(PaStreamInfo)); - } - - [DllImport (PaDll)] - public static extern double Pa_GetStreamTime(IntPtr stream); - - [DllImport (PaDll)] - public static extern double Pa_GetStreamCpuLoad(IntPtr stream); - - [DllImport (PaDll)] - public static extern PaError Pa_ReadStream( - IntPtr stream, - [Out]float[] buffer, - uint frames); - - [DllImport (PaDll)] - public static extern PaError Pa_ReadStream( - IntPtr stream, - [Out]byte[] buffer, - uint frames); - - [DllImport (PaDll)] - public static extern PaError Pa_ReadStream( - IntPtr stream, - [Out]sbyte[] buffer, - uint frames); - - [DllImport (PaDll)] - public static extern PaError Pa_ReadStream( - IntPtr stream, - [Out]ushort[] buffer, - uint frames); - - [DllImport (PaDll)] - public static extern PaError Pa_ReadStream( - IntPtr stream, - [Out]short[] buffer, - uint frames); - - [DllImport (PaDll)] - public static extern PaError Pa_ReadStream( - IntPtr stream, - [Out]uint[] buffer, - uint frames); - - [DllImport (PaDll)] - public static extern PaError Pa_ReadStream( - IntPtr stream, - [Out]int[] buffer, - uint frames); - - [DllImport (PaDll)] - public static extern PaError Pa_WriteStream( - IntPtr stream, - [In]float[] buffer, - uint frames); - - [DllImport (PaDll)] - public static extern PaError Pa_WriteStream( - IntPtr stream, - [In]byte[] buffer, - uint frames); - - [DllImport (PaDll)] - public static extern PaError Pa_WriteStream( - IntPtr stream, - [In]sbyte[] buffer, - uint frames); - - [DllImport (PaDll)] - public static extern PaError Pa_WriteStream( - IntPtr stream, - [In]ushort[] buffer, - uint frames); - - [DllImport (PaDll)] - public static extern PaError Pa_WriteStream( - IntPtr stream, - [In]short[] buffer, - uint frames); - - [DllImport (PaDll)] - public static extern PaError Pa_WriteStream( - IntPtr stream, - [In]uint[] buffer, - uint frames); - - [DllImport (PaDll)] - public static extern PaError Pa_WriteStream( - IntPtr stream, - [In]int[] buffer, - uint frames); - - [DllImport (PaDll)] - public static extern int Pa_GetStreamReadAvailable(IntPtr stream); - - [DllImport (PaDll)] - public static extern int Pa_GetStreamWriteAvailable(IntPtr stream); - - [DllImport (PaDll)] - public static extern PaError Pa_GetSampleSize(PaSampleFormat format); - - [DllImport (PaDll)] - public static extern void Pa_Sleep(int msec); - - #endregion - - private PortAudio() { - // This is a static class - } - - } - - } + [DllImport(PaDll)] + public static extern PaError Pa_OpenDefaultStream( + out IntPtr stream, + int numInputChannels, + int numOutputChannels, + uint sampleFormat, + double sampleRate, + uint framesPerBuffer, + PaStreamCallbackDelegate streamCallback, + IntPtr userData); + + [DllImport(PaDll)] + public static extern PaError Pa_CloseStream(IntPtr stream); + + [DllImport(PaDll)] + public static extern PaError Pa_SetStreamFinishedCallback( + ref IntPtr stream, + [MarshalAs(UnmanagedType.FunctionPtr)] PaStreamFinishedCallbackDelegate streamFinishedCallback); + + [DllImport(PaDll)] + public static extern PaError Pa_StartStream(IntPtr stream); + + [DllImport(PaDll)] + public static extern PaError Pa_StopStream(IntPtr stream); + + [DllImport(PaDll)] + public static extern PaError Pa_AbortStream(IntPtr stream); + + [DllImport(PaDll)] + public static extern PaError Pa_IsStreamStopped(IntPtr stream); + + [DllImport(PaDll)] + public static extern PaError Pa_IsStreamActive(IntPtr stream); + + [DllImport(PaDll, EntryPoint = "Pa_GetStreamInfo")] + public static extern IntPtr IntPtr_Pa_GetStreamInfo(IntPtr stream); + + public static PaStreamInfo Pa_GetStreamInfo(IntPtr stream) + { + IntPtr structptr = IntPtr_Pa_GetStreamInfo(stream); + return (PaStreamInfo)Marshal.PtrToStructure(structptr, typeof(PaStreamInfo)); + } + + [DllImport(PaDll)] + public static extern double Pa_GetStreamTime(IntPtr stream); + + [DllImport(PaDll)] + public static extern double Pa_GetStreamCpuLoad(IntPtr stream); + + [DllImport(PaDll)] + public static extern PaError Pa_ReadStream( + IntPtr stream, + [Out] float[] buffer, + uint frames); + + [DllImport(PaDll)] + public static extern PaError Pa_ReadStream( + IntPtr stream, + [Out] byte[] buffer, + uint frames); + + [DllImport(PaDll)] + public static extern PaError Pa_ReadStream( + IntPtr stream, + [Out] sbyte[] buffer, + uint frames); + + [DllImport(PaDll)] + public static extern PaError Pa_ReadStream( + IntPtr stream, + [Out] ushort[] buffer, + uint frames); + + [DllImport(PaDll)] + public static extern PaError Pa_ReadStream( + IntPtr stream, + [Out] short[] buffer, + uint frames); + + [DllImport(PaDll)] + public static extern PaError Pa_ReadStream( + IntPtr stream, + [Out] uint[] buffer, + uint frames); + + [DllImport(PaDll)] + public static extern PaError Pa_ReadStream( + IntPtr stream, + [Out] int[] buffer, + uint frames); + + [DllImport(PaDll)] + public static extern PaError Pa_WriteStream( + IntPtr stream, + [In] float[] buffer, + uint frames); + + [DllImport(PaDll)] + public static extern PaError Pa_WriteStream( + IntPtr stream, + [In] byte[] buffer, + uint frames); + + [DllImport(PaDll)] + public static extern PaError Pa_WriteStream( + IntPtr stream, + [In] sbyte[] buffer, + uint frames); + + [DllImport(PaDll)] + public static extern PaError Pa_WriteStream( + IntPtr stream, + [In] ushort[] buffer, + uint frames); + + [DllImport(PaDll)] + public static extern PaError Pa_WriteStream( + IntPtr stream, + [In] short[] buffer, + uint frames); + + [DllImport(PaDll)] + public static extern PaError Pa_WriteStream( + IntPtr stream, + [In] uint[] buffer, + uint frames); + + [DllImport(PaDll)] + public static extern PaError Pa_WriteStream( + IntPtr stream, + [In] int[] buffer, + uint frames); + + [DllImport(PaDll)] + public static extern int Pa_GetStreamReadAvailable(IntPtr stream); + + [DllImport(PaDll)] + public static extern int Pa_GetStreamWriteAvailable(IntPtr stream); + + [DllImport(PaDll)] + public static extern PaError Pa_GetSampleSize(PaSampleFormat format); + + [DllImport(PaDll)] + public static extern void Pa_Sleep(int msec); + #endregion + + private PortAudio() + { + // This is a static class + } + } +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Sound/Portaudio/PortAudioASIO.cs b/Vocaluxe/Lib/Sound/Portaudio/PortAudioASIO.cs index d4c75cf4..f3270268 100644 --- a/Vocaluxe/Lib/Sound/Portaudio/PortAudioASIO.cs +++ b/Vocaluxe/Lib/Sound/Portaudio/PortAudioASIO.cs @@ -1,4 +1,4 @@ - /* +/* * PortAudioSharp - PortAudio bindings for .NET * Copyright 2006-2011 Riccardo Gerosa and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a @@ -23,50 +23,44 @@ using System; using System.Runtime.InteropServices; -namespace PortAudioSharp { +namespace PortAudioSharp +{ + /// PortAudio v.19 bindings for .NET - ASIO bindings + public partial class PortAudio + { + #region **** PORTAUDIO CALLBACKS **** + #endregion - /// PortAudio v.19 bindings for .NET - ASIO bindings - public partial class PortAudio - { - #region **** PORTAUDIO CALLBACKS **** - - #endregion - - #region **** PORTAUDIO DATA STRUCTURES **** - - [StructLayout (LayoutKind.Sequential)] - public struct PaAsioStreamInfo { - public ulong size; /**< sizeof(PaAsioStreamInfo) */ - public int hostApiType; /**< paASIO */ - public ulong version; /**< 1 */ - public ulong flags; - - /// Support for opening only specific channels of an ASIO device. - /// If the paAsioUseChannelSelectors flag is set, channelSelectors is a - /// pointer to an array of integers specifying the device channels to use. - /// When used, the length of the channelSelectors array must match the - /// corresponding channelCount parameter to Pa_OpenStream() otherwise a - /// crash may result. - /// The values in the selectors array must specify channels within the - /// range of supported channels for the device or paInvalidChannelCount will - /// result. - IntPtr channelSelectors; - } - - #endregion - - #region **** PORTAUDIO DEFINES **** - - public const int paAsioUseChannelSelectors = 0x01; - - #endregion - - #region **** PORTAUDIO ENUMERATIONS **** - - #endregion - - #region **** PORTAUDIO FUNCTIONS **** - + #region **** PORTAUDIO DATA STRUCTURES **** + [StructLayout(LayoutKind.Sequential)] + public struct PaAsioStreamInfo + { + public ulong size; /**< sizeof(PaAsioStreamInfo) */ + public int hostApiType; /**< paASIO */ + public ulong version; /**< 1 */ + public ulong flags; + + /// Support for opening only specific channels of an ASIO device. + /// If the paAsioUseChannelSelectors flag is set, channelSelectors is a + /// pointer to an array of integers specifying the device channels to use. + /// When used, the length of the channelSelectors array must match the + /// corresponding channelCount parameter to Pa_OpenStream() otherwise a + /// crash may result. + /// The values in the selectors array must specify channels within the + /// range of supported channels for the device or paInvalidChannelCount will + /// result. + private readonly IntPtr channelSelectors; + } + #endregion + + #region **** PORTAUDIO DEFINES **** + public const int paAsioUseChannelSelectors = 0x01; + #endregion + + #region **** PORTAUDIO ENUMERATIONS **** + #endregion + + #region **** PORTAUDIO FUNCTIONS **** // /// Retrieve legal latency settings for the specificed device, in samples. // /// The global index of the device about which the query is being made. // /// A pointer to the location which will recieve the minimum latency value. @@ -79,35 +73,35 @@ namespace PortAudioSharp { // PaError PaAsio_GetAvailableLatencyValues( PaDeviceIndex device, long *minLatency, long *maxLatency, // long *preferredLatency, long *granularity ); - /// Display the ASIO control panel for the specified device. - /// The global index of the device whose control panel is to be displayed. - /// On Windows, the calling application's main window handle, - /// on Macintosh this value should be zero. - [DllImport ("PortAudio.dll")] - public static extern PortAudio.PaError PaAsio_ShowControlPanel(int device, IntPtr systemSpecific); - + /// Display the ASIO control panel for the specified device. + /// The global index of the device whose control panel is to be displayed. + /// + /// On Windows, the calling application's main window handle, + /// on Macintosh this value should be zero. + /// + [DllImport("PortAudio.dll")] + public static extern PaError PaAsio_ShowControlPanel(int device, IntPtr systemSpecific); + // /// Retrieve a pointer to a string containing the name of the specified input channel. // /// The string is valid until Pa_Terminate is called. // /// The string will be no longer than 32 characters including the null terminator. // PaError PaAsio_GetInputChannelName(PaDeviceIndex device, int channelIndex, const char** channelName ); - + // /// Retrieve a pointer to a string containing the name of the specified input channel. // /// The string is valid until Pa_Terminate is called. // /// The string will be no longer than 32 characters including the null terminator. // PaError PaAsio_GetOutputChannelName( PaDeviceIndex device, int channelIndex, const char** channelName ); - - /// Set the sample rate of an open paASIO stream. - /// stream The stream to operate on. - /// The new sample rate. - /// Note that this function may fail if the stream is alredy running and the - /// ASIO driver does not support switching the sample rate of a running stream. - /// paIncompatibleStreamHostApi if stream is not a paASIO stream. - [DllImport ("PortAudio.dll")] - public static extern PortAudio.PaError PaAsio_SetStreamSampleRate(IntPtr stream, double sampleRate); - - #endregion - - } - -} - \ No newline at end of file + + /// Set the sample rate of an open paASIO stream. + /// stream + /// The stream to operate on. + /// + /// The new sample rate. + /// Note that this function may fail if the stream is alredy running and the + /// ASIO driver does not support switching the sample rate of a running stream. + /// paIncompatibleStreamHostApi if stream is not a paASIO stream. + [DllImport("PortAudio.dll")] + public static extern PaError PaAsio_SetStreamSampleRate(IntPtr stream, double sampleRate); + #endregion + } +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Video/Acinerella/CAcinerella.cs b/Vocaluxe/Lib/Video/Acinerella/CAcinerella.cs index 8e3d7008..c5a74cbc 100644 --- a/Vocaluxe/Lib/Video/Acinerella/CAcinerella.cs +++ b/Vocaluxe/Lib/Video/Acinerella/CAcinerella.cs @@ -1,7 +1,6 @@ using System; using System.Runtime.InteropServices; - namespace Vocaluxe.Lib.Video.Acinerella { public enum TAc_stream_type : sbyte @@ -33,7 +32,6 @@ namespace Vocaluxe.Lib.Video.Acinerella AC_OUTPUT_BGRA32 = 3 } - // Contains information about the whole file/stream that has been opened. Default // values are "" for strings and -1 for integer values. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] @@ -93,16 +91,15 @@ namespace Vocaluxe.Lib.Video.Acinerella public TAc_stream_type stream_type; //Additional info about the stream public TAc_audio_stream_info audio_info; - public TAc_video_stream_info video_info; + public TAc_video_stream_info video_info; } - // Contains information about an Acinerella video/audio decoder. [StructLayout(LayoutKind.Sequential)] public struct TAc_decoder { //Pointer on the Acinerella instance - private IntPtr pAcInstance; + private readonly IntPtr pAcInstance; //Contains the type of the decoder. public TAc_decoder_type dec_type; @@ -130,7 +127,6 @@ namespace Vocaluxe.Lib.Video.Acinerella public Int32 stream_index; } - // Callback function used to ask the application to read data. Should return // the number of bytes read or an value smaller than zero if an error occured. //TAc_read_callback = function(sender: Pointer; byte[] buf, int size): integer; cdecl; @@ -153,7 +149,6 @@ namespace Vocaluxe.Lib.Video.Acinerella [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate Int32 TAc_openclose_callback(IntPtr sender); - public static class CAcinerella { #if ARCH_X86 @@ -176,7 +171,7 @@ namespace Vocaluxe.Lib.Video.Acinerella #endif #endif - private static Object _lock = new Object(); + private static readonly Object _lock = new Object(); // Defines the type of an Acinerella media stream. Currently only video and // audio streams are supported, subtitle and data streams will be marked as @@ -225,6 +220,7 @@ namespace Vocaluxe.Lib.Video.Acinerella close_proc: TAc_openclose_callback; proberesult: PAc_proberesult): integer; cdecl; external ac_dll; */ + [DllImport(AcDll, EntryPoint = "ac_open", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)] private static extern Int32 _ac_open( IntPtr PAc_instance, @@ -251,7 +247,7 @@ namespace Vocaluxe.Lib.Video.Acinerella return _ac_open(PAc_instance, sender, open_proc, read_proc, seek_proc, close_proc, proberesult); } } - + // Closes an opened media file. //procedure ac_close(inst: PAc_instance);cdecl; external ac_dll; [DllImport(AcDll, EntryPoint = "ac_close", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)] @@ -264,7 +260,7 @@ namespace Vocaluxe.Lib.Video.Acinerella _ac_close(PAc_instance); } } - + // Stores information in "pInfo" about stream number "nb". //procedure ac_get_stream_info( //inst: PAc_instance; nb: integer; pinfo: PAc_stream_info); cdecl; external ac_dll; @@ -314,7 +310,7 @@ namespace Vocaluxe.Lib.Video.Acinerella return _ac_create_decoder(PAc_instance, nb); } } - + // Frees an created decoder. //procedure ac_free_decoder(pDecoder: PAc_decoder); cdecl; external ac_dll; [DllImport(AcDll, EntryPoint = "ac_free_decoder", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)] @@ -356,7 +352,6 @@ namespace Vocaluxe.Lib.Video.Acinerella [DllImport(AcDll, EntryPoint = "ac_get_frame", ExactSpelling = true, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)] private static extern Int32 _ac_get_frame(IntPtr PAcInstance, IntPtr PAc_decoder); - public static Int32 ac_get_frame(IntPtr PAcInstance, IntPtr PAc_decoder) { lock (_lock) @@ -364,6 +359,7 @@ namespace Vocaluxe.Lib.Video.Acinerella return _ac_get_frame(PAcInstance, PAc_decoder); } } + [DllImport(AcDll, EntryPoint = "ac_skip_frames", ExactSpelling = true, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)] private static extern Int32 _ac_skip_frames(IntPtr PAcInstance, IntPtr PAc_decoder, Int32 num); @@ -401,4 +397,4 @@ namespace Vocaluxe.Lib.Video.Acinerella out Int32 score_max ); } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Video/CVideoDecoder.cs b/Vocaluxe/Lib/Video/CVideoDecoder.cs index ad31604a..98a0cec4 100644 --- a/Vocaluxe/Lib/Video/CVideoDecoder.cs +++ b/Vocaluxe/Lib/Video/CVideoDecoder.cs @@ -22,7 +22,7 @@ namespace Vocaluxe.Lib.Video { return _Streams.Count; } - + public virtual int Load(string VideoFileName) { return 0; @@ -48,35 +48,25 @@ namespace Vocaluxe.Lib.Video return true; } - public virtual void SetLoop(int StreamID, bool Loop) - { - } + public virtual void SetLoop(int StreamID, bool Loop) {} - public virtual void Pause(int StreamID) - { - } + public virtual void Pause(int StreamID) {} - public virtual void Resume(int StreamID) - { - } + public virtual void Resume(int StreamID) {} public virtual bool Finished(int StreamID) { return false; } - public virtual void Update() - { - } + public virtual void Update() {} protected bool AlreadyAdded(int StreamID) { foreach (VideoStreams st in _Streams) { if (st.handle == StreamID) - { return true; - } } return false; } @@ -91,4 +81,4 @@ namespace Vocaluxe.Lib.Video return -1; } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Video/CVideoDecoderFFmpeg.cs b/Vocaluxe/Lib/Video/CVideoDecoderFFmpeg.cs index dd04cde2..9473421a 100644 --- a/Vocaluxe/Lib/Video/CVideoDecoderFFmpeg.cs +++ b/Vocaluxe/Lib/Video/CVideoDecoderFFmpeg.cs @@ -4,7 +4,6 @@ using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Threading; - using Vocaluxe.Base; using Vocaluxe.Lib.Video.Acinerella; using VocaluxeLib.Menu; @@ -15,18 +14,17 @@ namespace Vocaluxe.Lib.Video class CVideoDecoderFFmpeg : CVideoDecoder { - private List _Decoder = new List(); + private readonly List _Decoder = new List(); private CLOSEPROC closeproc; private int _Count = 1; - private Object MutexDecoder = new Object(); - - + private readonly Object MutexDecoder = new Object(); + public override bool Init() { - closeproc = new CLOSEPROC(close_proc); + closeproc = close_proc; CloseAll(); - + return base.Init(); } @@ -35,9 +33,7 @@ namespace Vocaluxe.Lib.Video lock (MutexDecoder) { for (int i = 0; i < _Decoder.Count; i++) - { - _Decoder[i].Free(closeproc, i+1); - } + _Decoder[i].Free(closeproc, i + 1); } } @@ -56,7 +52,6 @@ namespace Vocaluxe.Lib.Video _Streams.Add(stream); return stream.handle; } - } return -1; } @@ -73,7 +68,6 @@ namespace Vocaluxe.Lib.Video return true; } } - } return false; } @@ -85,11 +79,8 @@ namespace Vocaluxe.Lib.Video lock (MutexDecoder) { if (AlreadyAdded(StreamID)) - { return _Decoder[GetStreamIndex(StreamID)].GetFrame(ref Frame, Time, ref VideoTime); - } } - } return false; } @@ -101,11 +92,8 @@ namespace Vocaluxe.Lib.Video lock (MutexDecoder) { if (AlreadyAdded(StreamID)) - { return _Decoder[GetStreamIndex(StreamID)].Length; - } } - } return 0f; } @@ -117,11 +105,8 @@ namespace Vocaluxe.Lib.Video lock (MutexDecoder) { if (AlreadyAdded(StreamID)) - { return _Decoder[GetStreamIndex(StreamID)].Skip(Start, Gap); - } } - } return false; } @@ -133,11 +118,8 @@ namespace Vocaluxe.Lib.Video lock (MutexDecoder) { if (AlreadyAdded(StreamID)) - { _Decoder[GetStreamIndex(StreamID)].Loop = Loop; - } } - } } @@ -148,11 +130,8 @@ namespace Vocaluxe.Lib.Video lock (MutexDecoder) { if (AlreadyAdded(StreamID)) - { _Decoder[GetStreamIndex(StreamID)].Paused = true; - } } - } } @@ -163,11 +142,8 @@ namespace Vocaluxe.Lib.Video lock (MutexDecoder) { if (AlreadyAdded(StreamID)) - { _Decoder[GetStreamIndex(StreamID)].Paused = false; - } } - } } @@ -178,9 +154,7 @@ namespace Vocaluxe.Lib.Video lock (MutexDecoder) { if (AlreadyAdded(StreamID)) - { return _Decoder[GetStreamIndex(StreamID)].Finished; - } } } return true; @@ -199,7 +173,6 @@ namespace Vocaluxe.Lib.Video _Streams.RemoveAt(Index); } } - } } } @@ -211,62 +184,61 @@ namespace Vocaluxe.Lib.Video public bool displayed; } - class Decoder: IDisposable + class Decoder : IDisposable { - private IntPtr _instance = IntPtr.Zero; // acinerella instance + private IntPtr _instance = IntPtr.Zero; // acinerella instance private IntPtr _videodecoder = IntPtr.Zero; // acinerella video decoder instance - - private Stopwatch _LoopTimer = new Stopwatch(); - private CLOSEPROC _Closeproc; // delegate for stream closing - private int _StreamID; // stream ID for stream closing - private string _FileName; // current video file name - - private FileStream _fs; // video file stream - private TAc_read_callback _rc; // read callback for acinerella - private TAc_seek_callback _sc; // seek callback for acinerella - - private bool _FileOpened = false; - - private float _VideoTimeBase = 0f; // frame time - private float _VideoDecoderTime = 0f; // time of last decoded frame - private float _CurrentVideoTime = 0f; // current video position - private bool _BufferFull = false; // buffer is full, waiting for free frame slot - private bool _skip = false; // do skip - private float _Time = 0f; - private float _Gap = 0f; - private float _Start = 0f; - private bool _Loop = false; - private float _Duration = 0f; - private float _VideoSkipTime = 0f; // = VideoGap - private float _SkipTime = 0f; // = Start + VideoGap - - private bool _Paused = false; - private bool _NoMoreFrames = false; - private bool _Finished = false; - private bool _BeforeLoop = false; - - - private int _Width = 0; - private int _Height = 0; - private float _SetTime = 0f; - private float _SetGap = 0f; - private float _SetStart = 0f; - private bool _SetLoop = false; - private bool _SetSkip = false; - private bool _terminated = false; - - private Thread _thread; + private readonly Stopwatch _LoopTimer = new Stopwatch(); + private CLOSEPROC _Closeproc; // delegate for stream closing + private int _StreamID; // stream ID for stream closing + private string _FileName; // current video file name + + private FileStream _fs; // video file stream + private readonly TAc_read_callback _rc; // read callback for acinerella + private readonly TAc_seek_callback _sc; // seek callback for acinerella + + private bool _FileOpened; + + private float _VideoTimeBase; // frame time + private float _VideoDecoderTime; // time of last decoded frame + private float _CurrentVideoTime; // current video position + private bool _BufferFull; // buffer is full, waiting for free frame slot + + private bool _skip; // do skip + private float _Time; + private float _Gap; + private float _Start; + private bool _Loop; + private float _Duration; + private float _VideoSkipTime; // = VideoGap + private float _SkipTime; // = Start + VideoGap + + private bool _Paused; + private bool _NoMoreFrames; + private bool _Finished; + private bool _BeforeLoop; + + private int _Width; + private int _Height; + private float _SetTime; + private float _SetGap; + private float _SetStart; + private bool _SetLoop; + private bool _SetSkip; + private bool _terminated; + + private readonly Thread _thread; //AutoResetEvent EventDecode = new AutoResetEvent(false); - SFrameBuffer[] _FrameBuffer = new SFrameBuffer[5]; - private bool _NewFrame = false; - Object MutexFramebuffer = new Object(); - Object MutexSyncSignals = new Object(); + private readonly SFrameBuffer[] _FrameBuffer = new SFrameBuffer[5]; + private bool _NewFrame; + private readonly Object MutexFramebuffer = new Object(); + private readonly Object MutexSyncSignals = new Object(); public Decoder() { - _rc = new TAc_read_callback(read_proc); - _sc = new TAc_seek_callback(seek_proc); + _rc = read_proc; + _sc = seek_proc; _thread = new Thread(Execute); } @@ -274,7 +246,7 @@ namespace Vocaluxe.Lib.Video { _Closeproc = close_proc; _StreamID = StreamID; - _terminated = true; + _terminated = true; } public float Length @@ -291,19 +263,15 @@ namespace Vocaluxe.Lib.Video public bool Paused { get { return _Paused; } - set - { + set + { lock (MutexSyncSignals) { _Paused = value; if (_Paused) - { _LoopTimer.Stop(); - } else - { _LoopTimer.Start(); - } } } } @@ -316,10 +284,7 @@ namespace Vocaluxe.Lib.Video public bool Finished { - get - { - return _Finished; - } + get { return _Finished; } } public bool Open(string FileName) @@ -327,7 +292,7 @@ namespace Vocaluxe.Lib.Video if (_FileOpened) return false; - if (!System.IO.File.Exists(FileName)) + if (!File.Exists(FileName)) return false; _FileName = FileName; @@ -336,7 +301,7 @@ namespace Vocaluxe.Lib.Video _thread.Start(); return true; } - + public bool GetFrame(ref STexture frame, float Time, ref float VideoTime) { if (!_FileOpened) @@ -348,7 +313,7 @@ namespace Vocaluxe.Lib.Video if (_SetLoop) { lock (MutexSyncSignals) - { + { _SetTime += _LoopTimer.ElapsedMilliseconds / 1000f; VideoTime = _SetTime; @@ -357,7 +322,7 @@ namespace Vocaluxe.Lib.Video _LoopTimer.Start(); } - + UploadNewFrame(ref frame); //EventDecode.Set(); return true; @@ -367,7 +332,7 @@ namespace Vocaluxe.Lib.Video { lock (MutexSyncSignals) { - _SetTime = Time; + _SetTime = Time; } UploadNewFrame(ref frame); VideoTime = _CurrentVideoTime; @@ -394,10 +359,10 @@ namespace Vocaluxe.Lib.Video #region Threading private void DoSkip() - { + { _VideoSkipTime = _Gap; _SkipTime = _Start + _Gap; - _BeforeLoop = false; + _BeforeLoop = false; if (_SkipTime > 0) { @@ -407,29 +372,28 @@ namespace Vocaluxe.Lib.Video CAcinerella.ac_seek(_videodecoder, -1, (Int64)(_SkipTime * 1000f)); } catch (Exception e) - { + { CLog.LogError("Error seeking video file \"" + _FileName + "\": " + e.Message); } - } else { _VideoDecoderTime = 0f; - try - { - CAcinerella.ac_seek(_videodecoder, -1, (Int64)0); - } - catch (Exception e) - { + try + { + CAcinerella.ac_seek(_videodecoder, -1, 0); + } + catch (Exception e) + { CLog.LogError("Error seeking video file \"" + _FileName + "\": " + e.Message); - } + } } lock (MutexSyncSignals) { _CurrentVideoTime = _VideoDecoderTime; } - + lock (MutexFramebuffer) { for (int i = 0; i < _FrameBuffer.Length; i++) @@ -438,7 +402,7 @@ namespace Vocaluxe.Lib.Video _FrameBuffer[i].time = -1f; } } - + _BufferFull = false; _skip = false; _NewFrame = false; @@ -478,7 +442,7 @@ namespace Vocaluxe.Lib.Video } } - DoFree(); + DoFree(); } private void DoOpen() @@ -501,7 +465,7 @@ namespace Vocaluxe.Lib.Video CLog.LogError("Error opening video file: " + _FileName); ok = false; } - + if (!Instance.opened || !ok) { @@ -509,7 +473,7 @@ namespace Vocaluxe.Lib.Video return; } - _Duration = (float)Instance.info.duration / 1000f; + _Duration = Instance.info.duration / 1000f; int VideoStreamIndex = -1; @@ -521,7 +485,7 @@ namespace Vocaluxe.Lib.Video if (Info.stream_type == TAc_stream_type.AC_STREAM_TYPE_VIDEO) { _videodecoder = CAcinerella.ac_create_decoder(_instance, i); - + VideoStreamIndex = i; break; } @@ -587,7 +551,6 @@ namespace Vocaluxe.Lib.Video { CLog.LogError("Error AcSkipFrame " + _FileName); } - } if (!_BeforeLoop && (!DropFrame || FrameFinished != 0)) @@ -638,9 +601,7 @@ namespace Vocaluxe.Lib.Video DoSkip(); } else - { _NoMoreFrames = true; - } return; } else @@ -656,7 +617,7 @@ namespace Vocaluxe.Lib.Video return; int num = -1; - + lock (MutexFramebuffer) { for (int i = 0; i < _FrameBuffer.Length; i++) @@ -669,9 +630,7 @@ namespace Vocaluxe.Lib.Video } if (num == -1) - { _BufferFull = true; - } else { TAc_decoder Videodecoder = (TAc_decoder)Marshal.PtrToStructure(_videodecoder, typeof(TAc_decoder)); @@ -721,9 +680,7 @@ namespace Vocaluxe.Lib.Video frame = CDraw.AddTexture(_Width, _Height, ref _FrameBuffer[num].data); } else - { CDraw.UpdateTexture(ref frame, ref _FrameBuffer[num].data); - } lock (MutexSyncSignals) { @@ -750,9 +707,7 @@ namespace Vocaluxe.Lib.Video float td = _SetTime + _VideoSkipTime - _FrameBuffer[i].time; if (td > _VideoTimeBase * 2f) - { _FrameBuffer[i].displayed = true; - } if (!_FrameBuffer[i].displayed && (td < diff) && (td > _VideoTimeBase)) { @@ -799,7 +754,7 @@ namespace Vocaluxe.Lib.Video private Int64 seek_proc(IntPtr sender, Int64 pos, Int32 whence) { - return (Int64)_fs.Seek((long)pos, (SeekOrigin)whence); + return _fs.Seek(pos, (SeekOrigin)whence); } #endregion Callbacks @@ -809,4 +764,4 @@ namespace Vocaluxe.Lib.Video _fs = null; } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Video/CVideoDecoderGstreamer.cs b/Vocaluxe/Lib/Video/CVideoDecoderGstreamer.cs index 1dbde802..620490c0 100644 --- a/Vocaluxe/Lib/Video/CVideoDecoderGstreamer.cs +++ b/Vocaluxe/Lib/Video/CVideoDecoderGstreamer.cs @@ -13,14 +13,13 @@ namespace Vocaluxe.Lib.Video private void LogHandler(string text) { CLog.LogError(text); - } #endregion log public bool Init() { bool retval = CGstreamerVideoWrapper.InitVideo(); - Log = new CGstreamerVideoWrapper.LogCallback(LogHandler); + Log = LogHandler; //Really needed? CodeAnalysis complains //GC.SuppressFinalize(Log); CGstreamerVideoWrapper.SetVideoLogCallback(Log); @@ -41,7 +40,7 @@ namespace Vocaluxe.Lib.Video i = CGstreamerVideoWrapper.LoadVideo(u.AbsoluteUri); return i; } - catch (Exception) { } + catch (Exception) {} return i; } @@ -109,11 +108,9 @@ namespace Vocaluxe.Lib.Video frame = CDraw.AddTexture(Width, Height, ref Data); } else - { CDraw.UpdateTexture(ref frame, ref Data); - } Data = null; } } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Video/Gstreamer/CGstreamerVideoWrapper.cs b/Vocaluxe/Lib/Video/Gstreamer/CGstreamerVideoWrapper.cs index c44a874f..e1f82d89 100644 --- a/Vocaluxe/Lib/Video/Gstreamer/CGstreamerVideoWrapper.cs +++ b/Vocaluxe/Lib/Video/Gstreamer/CGstreamerVideoWrapper.cs @@ -3,7 +3,8 @@ using System.Runtime.InteropServices; namespace Vocaluxe.Lib.Video.Gstreamer { - public struct NativeFrame { + public struct NativeFrame + { internal IntPtr buffer; public int Size; public int Width; @@ -22,7 +23,7 @@ namespace Vocaluxe.Lib.Video.Gstreamer public static class CGstreamerVideoWrapper { -#region arch + #region arch #if ARCH_X86 #if WIN private const string Dll = "x86\\gstreamerhelper.dll"; @@ -34,7 +35,8 @@ namespace Vocaluxe.Lib.Video.Gstreamer private const string Dll = "x64\\gstreamer\\gstreamerhelper.dll"; #endif #endif -#endregion arch + #endregion arch + public delegate void LogCallback(string message); [DllImport(Dll)] @@ -60,7 +62,7 @@ namespace Vocaluxe.Lib.Video.Gstreamer [DllImport(Dll)] public static extern float GetVideoLength(int StreamID); - [DllImport(Dll, EntryPoint="GetFrame")] + [DllImport(Dll, EntryPoint = "GetFrame")] public static extern NativeFrame GetFrameNative(int StreamID, float Time); public static ManagedFrame GetFrame(int StreamID, float Time) @@ -82,7 +84,6 @@ namespace Vocaluxe.Lib.Video.Gstreamer m.Videotime = f.Videotime; m.Width = f.Width; return m; - } [DllImport(Dll)] @@ -91,7 +92,7 @@ namespace Vocaluxe.Lib.Video.Gstreamer [DllImport(Dll)] public static extern void SetVideoLoop(int StreamID, - [MarshalAs(UnmanagedType.U1)] bool Loop); + [MarshalAs(UnmanagedType.U1)] bool Loop); [DllImport(Dll)] public static extern void PauseVideo(int StreamID); @@ -106,6 +107,5 @@ namespace Vocaluxe.Lib.Video.Gstreamer [DllImport(Dll)] [return: MarshalAs(UnmanagedType.U1)] public static extern bool UpdateVideo(); - } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Video/IVideoDecoder.cs b/Vocaluxe/Lib/Video/IVideoDecoder.cs index 82ca0547..0dbb2af9 100644 --- a/Vocaluxe/Lib/Video/IVideoDecoder.cs +++ b/Vocaluxe/Lib/Video/IVideoDecoder.cs @@ -7,7 +7,7 @@ namespace Vocaluxe.Lib.Video { public int handle; public string file; - + public VideoStreams(int stream) { handle = stream; @@ -35,4 +35,4 @@ namespace Vocaluxe.Lib.Video void Update(); } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Webcam/CAForgeNet.cs b/Vocaluxe/Lib/Webcam/CAForgeNet.cs index d9160549..2a3dd7af 100644 --- a/Vocaluxe/Lib/Webcam/CAForgeNet.cs +++ b/Vocaluxe/Lib/Webcam/CAForgeNet.cs @@ -11,14 +11,14 @@ namespace Vocaluxe.Lib.Webcam { class CAForgeNet : IWebcam { - private List _Devices = new List(); + private readonly List _Devices = new List(); private bool _Paused; private VideoCaptureDevice _Webcam; private FilterInfoCollection _WebcamDevices; private SWebcamConfig _Config; private byte[] data = new byte[1]; - private static object _mutexData = new object(); - int _Width, _Height; + private static readonly object _mutexData = new object(); + private int _Width, _Height; public void Close() { @@ -26,7 +26,7 @@ namespace Vocaluxe.Lib.Webcam { _Webcam.SignalToStop(); _Webcam.WaitForStop(); - _Webcam.NewFrame -= new NewFrameEventHandler(OnFrame); + _Webcam.NewFrame -= OnFrame; data = new byte[1]; } } @@ -43,9 +43,7 @@ namespace Vocaluxe.Lib.Webcam Frame = CDraw.AddTexture(_Width, _Height, ref data); } else - { CDraw.UpdateTexture(ref Frame, ref data); - } } } return false; @@ -74,23 +72,24 @@ namespace Vocaluxe.Lib.Webcam int num = 0; foreach (FilterInfo info in _WebcamDevices) { - SWebcamDevice device = new SWebcamDevice { - ID = num, - Name = info.Name, - MonikerString = info.MonikerString, - Capabilities = new List() - }; + SWebcamDevice device = new SWebcamDevice + { + ID = num, + Name = info.Name, + MonikerString = info.MonikerString, + Capabilities = new List() + }; num++; VideoCaptureDevice tmpdev = new VideoCaptureDevice(info.MonikerString); - for (int i = 0; i < tmpdev.VideoCapabilities.Length; i++ ) + for (int i = 0; i < tmpdev.VideoCapabilities.Length; i++) { SCapabilities item = new SCapabilities - { - Framerate = tmpdev.VideoCapabilities[i].FrameRate, - Height = tmpdev.VideoCapabilities[i].FrameSize.Height, - Width = tmpdev.VideoCapabilities[i].FrameSize.Width - }; + { + Framerate = tmpdev.VideoCapabilities[i].FrameRate, + Height = tmpdev.VideoCapabilities[i].FrameSize.Height, + Width = tmpdev.VideoCapabilities[i].FrameSize.Width + }; device.Capabilities.Add(item); } _Devices.Add(device); @@ -119,18 +118,16 @@ namespace Vocaluxe.Lib.Webcam public void Pause() { if (_Webcam != null) - { _Paused = true; - } } public void Start() { if (_Webcam != null) { - _Webcam.NewFrame -= new NewFrameEventHandler(OnFrame); + _Webcam.NewFrame -= OnFrame; //Subscribe to NewFrame event - _Webcam.NewFrame += new NewFrameEventHandler(OnFrame); + _Webcam.NewFrame += OnFrame; _Webcam.Start(); _Paused = false; } @@ -139,9 +136,7 @@ namespace Vocaluxe.Lib.Webcam public void Stop() { if (_Webcam != null) - { _Webcam.SignalToStop(); - } } public SWebcamDevice[] GetDevices() @@ -187,4 +182,4 @@ namespace Vocaluxe.Lib.Webcam return _Config; } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Webcam/IWebcam.cs b/Vocaluxe/Lib/Webcam/IWebcam.cs index e25725a4..f5bc183c 100644 --- a/Vocaluxe/Lib/Webcam/IWebcam.cs +++ b/Vocaluxe/Lib/Webcam/IWebcam.cs @@ -43,4 +43,4 @@ namespace Vocaluxe.Lib.Webcam bool Select(SWebcamConfig sWebcamConfig); } -} +} \ No newline at end of file diff --git a/Vocaluxe/Program.cs b/Vocaluxe/Program.cs index 813916b5..9d87b376 100644 --- a/Vocaluxe/Program.cs +++ b/Vocaluxe/Program.cs @@ -11,12 +11,12 @@ namespace Vocaluxe // just a small comment for the new develop branch static class MainProgram { - static SplashScreen _SplashScreen; - + private static SplashScreen _SplashScreen; + [STAThread] - static void Main(string[] args) + private static void Main(string[] args) { - AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(AssemblyResolver); + AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolver; // Close program if there is another instance running if (!EnsureSingleInstance()) @@ -180,7 +180,7 @@ namespace Vocaluxe CloseProgram(); } - static void CloseProgram() + private static void CloseProgram() { // Unloading try @@ -194,15 +194,12 @@ namespace Vocaluxe CDataBase.CloseConnections(); CWebcam.Close(); } - catch (Exception) - { - } - + catch (Exception) {} } - static Assembly AssemblyResolver(Object sender, ResolveEventArgs args) + private static Assembly AssemblyResolver(Object sender, ResolveEventArgs args) { - string[] arr = args.Name.Split(new Char[] { ',' }); + string[] arr = args.Name.Split(new[] {','}); if (arr != null) { #if ARCH_X86 @@ -218,7 +215,7 @@ namespace Vocaluxe return null; } - static bool EnsureSingleInstance() + private static bool EnsureSingleInstance() { Process currentProcess = Process.GetCurrentProcess(); Process[] processes = Process.GetProcesses(); @@ -238,7 +235,7 @@ namespace Vocaluxe class SplashScreen : Form { - Bitmap logo; + private readonly Bitmap logo; public SplashScreen() { @@ -248,52 +245,49 @@ namespace Vocaluxe try { logo = new Bitmap(path); - this.ClientSize = new Size(logo.Width, logo.Height); + ClientSize = new Size(logo.Width, logo.Height); } catch (Exception e) { CLog.LogError("Error loading logo: " + e.Message); } - } else CLog.LogError("Can't find " + path); - path = Path.Combine(System.Environment.CurrentDirectory, CSettings.sIcon); + path = Path.Combine(Environment.CurrentDirectory, CSettings.sIcon); if (File.Exists(path)) { try { - this.Icon = new System.Drawing.Icon(path); + Icon = new Icon(path); } catch (Exception e) { - CLog.LogError("Error loading icon: " + e.Message); + CLog.LogError("Error loading icon: " + e.Message); } } else CLog.LogError("Can't find " + path); SetStyle(ControlStyles.SupportsTransparentBackColor, true); - this.BackColor = Color.Transparent; + BackColor = Color.Transparent; - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; - this.Text = CSettings.sProgramName; - this.CenterToScreen(); - this.Show(); - } - - protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) - { + FormBorderStyle = FormBorderStyle.None; + Text = CSettings.sProgramName; + CenterToScreen(); + Show(); } - protected override void OnPaintBackground(System.Windows.Forms.PaintEventArgs e) + protected override void OnPaint(PaintEventArgs e) {} + + protected override void OnPaintBackground(PaintEventArgs e) { if (logo == null) return; Graphics g = e.Graphics; - g.DrawImage(logo, new Rectangle(0, 0, this.Width, this.Height)); - } + g.DrawImage(logo, new Rectangle(0, 0, Width, Height)); + } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Properties/AssemblyInfo.cs b/Vocaluxe/Properties/AssemblyInfo.cs index 08268525..7c2f042d 100644 --- a/Vocaluxe/Properties/AssemblyInfo.cs +++ b/Vocaluxe/Properties/AssemblyInfo.cs @@ -4,6 +4,7 @@ using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die mit einer Assembly verknüpft sind. + [assembly: AssemblyTitle("Vocaluxe.Properties")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] @@ -16,9 +17,11 @@ using System.Runtime.InteropServices; // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. + [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird + [assembly: Guid("da631594-f891-4994-9869-c37e626e44f9")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: @@ -28,5 +31,6 @@ using System.Runtime.InteropServices; // Buildnummer // Revision // + [assembly: AssemblyVersion("0.3.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file diff --git a/Vocaluxe/Screens/CPopupScreenPlayerControl.cs b/Vocaluxe/Screens/CPopupScreenPlayerControl.cs index ebf030dc..ee7d8c51 100644 --- a/Vocaluxe/Screens/CPopupScreenPlayerControl.cs +++ b/Vocaluxe/Screens/CPopupScreenPlayerControl.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Windows.Forms; - using Vocaluxe.Base; using VocaluxeLib.Menu; @@ -10,7 +9,10 @@ namespace Vocaluxe.Screens class CPopupScreenPlayerControl : CMenu { // Version number for theme files. Increment it, if you've changed something on the theme files! - protected override int _ScreenVersion { get { return 1; } } + protected override int _ScreenVersion + { + get { return 1; } + } private const string StaticBG = "StaticBG"; private const string StaticCover = "StaticCover"; @@ -25,14 +27,11 @@ namespace Vocaluxe.Screens private const string ButtonToBackgroundVideo = "ButtonToBackgroundVideo"; private const string TextCurrentSong = "TextCurrentSong"; - private bool _VideoPreview = false; + private bool _VideoPreview; private bool VideoPreview { - get - { - return _VideoPreview; - } + get { return _VideoPreview; } set { _VideoPreview = value; @@ -45,10 +44,7 @@ namespace Vocaluxe.Screens private bool VideoBackground { - get - { - return CConfig.VideosToBackground == EOffOn.TR_CONFIG_ON; - } + get { return CConfig.VideosToBackground == EOffOn.TR_CONFIG_ON; } set { if (!value) @@ -69,16 +65,12 @@ namespace Vocaluxe.Screens } } - public CPopupScreenPlayerControl() - { - } - public override void Init() { base.Init(); - _ThemeStatics = new string[] { StaticBG, StaticCover }; - _ThemeTexts = new string[] { TextCurrentSong }; + _ThemeStatics = new[] {StaticBG, StaticCover}; + _ThemeTexts = new[] {TextCurrentSong}; List buttons = new List(); buttons.Add(ButtonPlay); @@ -102,10 +94,7 @@ namespace Vocaluxe.Screens public override bool HandleInput(KeyEvent KeyEvent) { base.HandleInput(KeyEvent); - if (KeyEvent.KeyPressed && !Char.IsControl(KeyEvent.Unicode)) - { - - } + if (KeyEvent.KeyPressed && !Char.IsControl(KeyEvent.Unicode)) {} else { switch (KeyEvent.Key) @@ -160,11 +149,13 @@ namespace Vocaluxe.Screens StartSong(CBackgroundMusic.SongID, CBackgroundMusic.Duet); if (Buttons[ButtonToBackgroundVideo].Selected) VideoBackground = !VideoBackground; - } else if (MouseEvent.LB) + } + else if (MouseEvent.LB) { //CGraphics.HidePopup(EPopupScreens.PopupPlayerControl); return false; - } else if (MouseEvent.RB) + } + else if (MouseEvent.RB) { //CGraphics.HidePopup(EPopupScreens.PopupPlayerControl); return false; @@ -174,7 +165,6 @@ namespace Vocaluxe.Screens public override bool UpdateGame() { - Statics[StaticCover].Visible = !_VideoPreview || !CBackgroundMusic.SongHasVideo; Buttons[ButtonToBackgroundVideo].Pressed = VideoBackground; Buttons[ButtonShowVideo].Pressed = _VideoPreview; @@ -193,7 +183,7 @@ namespace Vocaluxe.Screens Buttons[ButtonPause].Visible = CBackgroundMusic.Playing; Buttons[ButtonPlay].Visible = !CBackgroundMusic.Playing; Texts[TextCurrentSong].Text = CBackgroundMusic.ArtistAndTitle; - + return base.Draw(); } @@ -214,4 +204,4 @@ namespace Vocaluxe.Screens } } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CPopupScreenVolumeControl.cs b/Vocaluxe/Screens/CPopupScreenVolumeControl.cs index 4672659b..0fa14620 100644 --- a/Vocaluxe/Screens/CPopupScreenVolumeControl.cs +++ b/Vocaluxe/Screens/CPopupScreenVolumeControl.cs @@ -1,5 +1,4 @@ - -using Vocaluxe.Base; +using Vocaluxe.Base; using VocaluxeLib.Menu; namespace Vocaluxe.Screens @@ -7,24 +6,21 @@ namespace Vocaluxe.Screens class CPopupScreenVolumeControl : CMenu { // Version number for theme files. Increment it, if you've changed something on the theme files! - protected override int _ScreenVersion { get { return 1; } } + protected override int _ScreenVersion + { + get { return 1; } + } private const string StaticBG = "StaticBG"; private const string SelectSlideVolume = "SelectSlideVolume"; - - public CPopupScreenVolumeControl() - { - } - public override void Init() { base.Init(); - _ThemeStatics = new string[] { StaticBG }; - _ThemeSelectSlides = new string[] { SelectSlideVolume }; - + _ThemeStatics = new[] {StaticBG}; + _ThemeSelectSlides = new[] {SelectSlideVolume}; } public override void LoadTheme(string XmlPath) @@ -32,7 +28,8 @@ namespace Vocaluxe.Screens base.LoadTheme(XmlPath); _ScreenArea = Statics[StaticBG].Rect; - SelectSlides[SelectSlideVolume].AddValues(new string[] { "0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100" }); + SelectSlides[SelectSlideVolume].AddValues(new[] + {"0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"}); } public override bool HandleInput(KeyEvent KeyEvent) @@ -68,9 +65,7 @@ namespace Vocaluxe.Screens return true; } else if (MouseEvent.RB) - { return false; - } return true; } @@ -125,20 +120,20 @@ namespace Vocaluxe.Screens switch (CGraphics.CurrentScreen) { case EScreens.ScreenSong: - if(CSongs.IsInCategory) - SelectSlides[SelectSlideVolume].Selection = (int)(CConfig.PreviewMusicVolume / 5); + if (CSongs.IsInCategory) + SelectSlides[SelectSlideVolume].Selection = (CConfig.PreviewMusicVolume / 5); else - SelectSlides[SelectSlideVolume].Selection = ((int)CConfig.BackgroundMusicVolume / 5); + SelectSlides[SelectSlideVolume].Selection = (CConfig.BackgroundMusicVolume / 5); break; case EScreens.ScreenSing: - SelectSlides[SelectSlideVolume].Selection = ((int)CConfig.GameMusicVolume / 5); + SelectSlides[SelectSlideVolume].Selection = (CConfig.GameMusicVolume / 5); break; default: - SelectSlides[SelectSlideVolume].Selection = ((int)CConfig.BackgroundMusicVolume / 5); + SelectSlides[SelectSlideVolume].Selection = (CConfig.BackgroundMusicVolume / 5); break; } } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenCredits.cs b/Vocaluxe/Screens/CScreenCredits.cs index cd7a3862..821cfe78 100644 --- a/Vocaluxe/Screens/CScreenCredits.cs +++ b/Vocaluxe/Screens/CScreenCredits.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Diagnostics; using System.Windows.Forms; - using Vocaluxe.Base; using VocaluxeLib.Menu; @@ -15,11 +14,11 @@ enum EDirection class CCreditName { - private CStatic _Image; - private CStatic _ImgDot; - private CParticleEffect _Particle; - private int _ParticleOffsetX; - private int _ParticleOffsetY; + private readonly CStatic _Image; + private readonly CStatic _ImgDot; + private readonly CParticleEffect _Particle; + private readonly int _ParticleOffsetX; + private readonly int _ParticleOffsetY; public EDirection Direction; public float StartTimeUp; public bool Active; @@ -29,17 +28,14 @@ class CCreditName _Image = Image; _ImgDot = ImgDot; _Particle = Particle; - _ParticleOffsetX = (int)Math.Round(ParticleOffsetX * (float)Image.Rect.W / Image.Texture.w2 - Particle.Rect.W / 2); - _ParticleOffsetY = (int)Math.Round(ParticleOffsetY * (float)Image.Rect.H / Image.Texture.h2 - Particle.Rect.H / 2); + _ParticleOffsetX = (int)Math.Round(ParticleOffsetX * Image.Rect.W / Image.Texture.w2 - Particle.Rect.W / 2); + _ParticleOffsetY = (int)Math.Round(ParticleOffsetY * Image.Rect.H / Image.Texture.h2 - Particle.Rect.H / 2); Active = true; } public float X { - get - { - return _Image.Rect.X; - } + get { return _Image.Rect.X; } set { _Image.Rect.X = value; @@ -49,10 +45,7 @@ class CCreditName } public float Y { - get - { - return _Image.Rect.Y; - } + get { return _Image.Rect.Y; } set { _Image.Rect.Y = value; @@ -61,8 +54,14 @@ class CCreditName } } - public float W { get { return _Image.Rect.W; } } - public float H { get { return _Image.Rect.H; } } + public float W + { + get { return _Image.Rect.W; } + } + public float H + { + get { return _Image.Rect.H; } + } public float Alpha { @@ -90,7 +89,10 @@ namespace Vocaluxe.Screens class CScreenCredits : CMenu { // Version number for theme files. Increment it, if you've changed something on the theme files! - protected override int _ScreenVersion { get { return 1; } } + protected override int _ScreenVersion + { + get { return 1; } + } private CStatic logo; private CParticleEffect starsRed; @@ -119,10 +121,6 @@ namespace Vocaluxe.Screens private STexture _TexNamePantero; private STexture _TexNamePinky007; - public CScreenCredits() - { - } - public override void Init() { base.Init(); @@ -139,29 +137,29 @@ namespace Vocaluxe.Screens string[] words; paragraph = "Inspired by the achievements of UltraStar Deluxe and its variants and pursuing the goal of making " + - "a good thing even better, we ended up rewriting the game from scratch. And a new implementation in a new " + - "programming language called for a new name - and VOCALUXE [ˈvoʊˈkəˈlʌks] it is!"; - words = paragraph.Split(new Char[] { ' ' }); + "a good thing even better, we ended up rewriting the game from scratch. And a new implementation in a new " + + "programming language called for a new name - and VOCALUXE [ˈvoʊˈkəˈlʌks] it is!"; + words = paragraph.Split(new[] {' '}); paragraphs.Add(words); paragraph = "This first public version has already implemented many of the original features and it is fully " + - "compatible with all the song files in your existing song collection. The code design allows a much faster " + - "implementation of new features, thus the roadmap for the next few stable releases is packed and we expect much " + - "shorter release cycles than ever before. And, of course, our and your ideas may be the features of tomorrow."; - words = paragraph.Split(new Char[] { ' ' }); + "compatible with all the song files in your existing song collection. The code design allows a much faster " + + "implementation of new features, thus the roadmap for the next few stable releases is packed and we expect much " + + "shorter release cycles than ever before. And, of course, our and your ideas may be the features of tomorrow."; + words = paragraph.Split(new[] {' '}); paragraphs.Add(words); paragraph = "We appreciate the feedback in the beta release phase and are, of course, always open for bug reports, " + - "suggestions for improvements and ideas for new features. We would also like to thank the translators who make " + - "Vocaluxe an international experience from the very beginning and all those diligent song makers out there - " + - "there's something for everyone in the huge collection of available songs! Last but not least, thanks to " + - "Kosal Sen's Philly Sans type used in the Vocaluxe Logo."; - words = paragraph.Split(new Char[] { ' ' }); + "suggestions for improvements and ideas for new features. We would also like to thank the translators who make " + + "Vocaluxe an international experience from the very beginning and all those diligent song makers out there - " + + "there's something for everyone in the huge collection of available songs! Last but not least, thanks to " + + "Kosal Sen's Philly Sans type used in the Vocaluxe Logo."; + words = paragraph.Split(new[] {' '}); paragraphs.Add(words); paragraph = "Go ahead and grab your mics, crank up your stereo, warm up your voice and get ready to sing to the best " + - "of your abilities!"; - words = paragraph.Split(new Char[] { ' ' }); + "of your abilities!"; + words = paragraph.Split(new[] {' '}); paragraphs.Add(words); } @@ -218,16 +216,15 @@ namespace Vocaluxe.Screens } } } - } - public override void ReloadTheme(string XmlPath) { } + public override void ReloadTheme(string XmlPath) {} - public override void SaveTheme() { } + public override void SaveTheme() {} - public override void UnloadTextures() { } + public override void UnloadTextures() {} - public override void ReloadTextures() { } + public override void ReloadTextures() {} public override bool HandleInput(KeyEvent KeyEvent) { @@ -249,18 +246,14 @@ namespace Vocaluxe.Screens public override bool HandleMouse(MouseEvent MouseEvent) { if (MouseEvent.LB || MouseEvent.RB) - { CGraphics.FadeTo(EScreens.ScreenMain); - } return true; } public override bool UpdateGame() { if (!animation()) - { CGraphics.FadeTo(EScreens.ScreenMain); - } return true; } @@ -297,13 +290,11 @@ namespace Vocaluxe.Screens { credit.X = -450; credit.Direction = EDirection.Left; - } credit.Y = 580; _CreditNames.Add(credit); } - public override void OnShow() { base.OnShow(); @@ -356,17 +347,13 @@ namespace Vocaluxe.Screens //Draw credit-entries foreach (CCreditName cn in _CreditNames) - { cn.Draw(); - } //Draw Text if (TextTimer.IsRunning) { for (int i = 0; i < paragraphTexts.Count; i++) - { paragraphTexts[i].Draw(); - } } return true; } @@ -382,9 +369,7 @@ namespace Vocaluxe.Screens starsRed.Rect.Y = logo.Rect.Y; starsBlue.Rect.Y = logo.Rect.Y; if (LogoTimer.ElapsedMilliseconds >= 2000 && !CreditsTimer.IsRunning) - { CreditsTimer.Start(); - } if (LogoTimer.ElapsedMilliseconds >= 3000) { LogoTimer.Stop(); @@ -413,14 +398,14 @@ namespace Vocaluxe.Screens _CreditNames[i].Direction = EDirection.Up; _CreditNames[i].StartTimeUp = CreditsTimer.ElapsedMilliseconds; } - } break; case EDirection.Left: if (i * 4000f <= CreditsTimer.ElapsedMilliseconds) { - _CreditNames[i].X = CSettings.iRenderW - (((CSettings.iRenderW - _CreditNames[i].W) / 2) / 3000f) * (CreditsTimer.ElapsedMilliseconds - (i * 4000f)); + _CreditNames[i].X = CSettings.iRenderW - + (((CSettings.iRenderW - _CreditNames[i].W) / 2) / 3000f) * (CreditsTimer.ElapsedMilliseconds - (i * 4000f)); //Check if name is in middle of screen and should go up if (_CreditNames[i].X <= (CSettings.iRenderW - _CreditNames[i].W) / 2) @@ -428,7 +413,6 @@ namespace Vocaluxe.Screens _CreditNames[i].Direction = EDirection.Up; _CreditNames[i].StartTimeUp = CreditsTimer.ElapsedMilliseconds; } - } break; @@ -457,13 +441,9 @@ namespace Vocaluxe.Screens float alpha = ((360 - _CreditNames[i].Y) / 200); //Catch some bad alpha-values if (alpha > 1) - { alpha = 1; - } else if (alpha < 0) - { alpha = 0; - } _CreditNames[i].Alpha = 1 - alpha; } @@ -474,11 +454,9 @@ namespace Vocaluxe.Screens } if (TextTimer.IsRunning) - { active = TextTimer.ElapsedMilliseconds <= 60000; - } return active; } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenHighscore.cs b/Vocaluxe/Screens/CScreenHighscore.cs index 23c38a57..5b6b5a62 100644 --- a/Vocaluxe/Screens/CScreenHighscore.cs +++ b/Vocaluxe/Screens/CScreenHighscore.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Windows.Forms; - using Vocaluxe.Base; using VocaluxeLib.Menu; using VocaluxeLib.Menu.SongMenu; @@ -11,7 +10,10 @@ namespace Vocaluxe.Screens class CScreenHighscore : CMenu { // Version number for theme files. Increment it, if you've changed something on the theme files! - protected override int _ScreenVersion { get { return 2; } } + protected override int _ScreenVersion + { + get { return 2; } + } private const int NumEntrys = 10; private const string TextSongName = "TextSongName"; @@ -28,10 +30,6 @@ namespace Vocaluxe.Screens private int _Pos; private bool _IsDuet; - public CScreenHighscore() - { - } - public override void Init() { base.Init(); @@ -70,9 +68,7 @@ namespace Vocaluxe.Screens ParticleEffectNew = new string[NumEntrys]; for (int i = 0; i < NumEntrys; i++) - { ParticleEffectNew[i] = "ParticleEffectNew" + (i + 1).ToString(); - } _ThemeTexts = texts.ToArray(); _ThemeParticleEffects = ParticleEffectNew; @@ -82,10 +78,7 @@ namespace Vocaluxe.Screens public override bool HandleInput(KeyEvent KeyEvent) { - if (KeyEvent.KeyPressed && !Char.IsControl(KeyEvent.Unicode)) - { - - } + if (KeyEvent.KeyPressed && !Char.IsControl(KeyEvent.Unicode)) {} else { switch (KeyEvent.Key) @@ -119,20 +112,13 @@ namespace Vocaluxe.Screens public override bool HandleMouse(MouseEvent MouseEvent) { - if (MouseEvent.LB && IsMouseOver(MouseEvent)) - { - - } + if (MouseEvent.LB && IsMouseOver(MouseEvent)) {} if (MouseEvent.LB) - { LeaveScreen(); - } if (MouseEvent.RB) - { LeaveScreen(); - } if (MouseEvent.MB) { @@ -171,14 +157,10 @@ namespace Vocaluxe.Screens Texts[TextScore[p]].Text = _Scores[_Round][_Pos + p].Score.ToString("00000"); Texts[TextDate[p]].Text = _Scores[_Round][_Pos + p].Date; - if (isNewEntry(_Scores[_Round][_Pos + p].ID) == true) - { + if (isNewEntry(_Scores[_Round][_Pos + p].ID)) ParticleEffects[ParticleEffectNew[p]].Visible = true; - } else - { ParticleEffects[ParticleEffectNew[p]].Visible = false; - } } else { @@ -188,7 +170,7 @@ namespace Vocaluxe.Screens Texts[TextDate[p]].Visible = false; ParticleEffects[ParticleEffectNew[p]].Visible = false; } - } + } return true; } @@ -200,9 +182,7 @@ namespace Vocaluxe.Screens CPoints _Points = CGame.GetPoints(); _Scores = new List[_Points.NumRounds]; for (int i = 0; i < _Scores.Length; i++) - { _Scores[i] = new List(); - } _NewEntryIDs.Clear(); AddScoresToDB(); LoadScores(); @@ -218,12 +198,10 @@ namespace Vocaluxe.Screens private bool isNewEntry(int id) { - for(int i=0; i<_NewEntryIDs.Count; i++) + for (int i = 0; i < _NewEntryIDs.Count; i++) { if (_NewEntryIDs[i] == id) - { return true; - } } return false; @@ -253,7 +231,7 @@ namespace Vocaluxe.Screens if (points == null) return; - _Pos = 0; + _Pos = 0; for (int round = 0; round < points.NumRounds; round++) { SPlayer player = points.GetPlayer(round, CGame.NumPlayer)[0]; @@ -266,15 +244,13 @@ namespace Vocaluxe.Screens _IsDuet = false; CPoints points = CGame.GetPoints(); SPlayer player = points.GetPlayer(_Round, CGame.NumPlayer)[0]; - CSong song = CGame.GetSong(_Round+1); + CSong song = CGame.GetSong(_Round + 1); if (song == null) return; Texts[TextSongName].Text = song.Artist + " - " + song.Title; if (points.NumRounds > 1) - { - Texts[TextSongName].Text += " (" + (_Round+1) + "/" + points.NumRounds + ")"; - } + Texts[TextSongName].Text += " (" + (_Round + 1) + "/" + points.NumRounds + ")"; switch (CGame.GetGameMode(_Round)) { @@ -335,4 +311,4 @@ namespace Vocaluxe.Screens CParty.LeavingHighscore(); } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenLoad.cs b/Vocaluxe/Screens/CScreenLoad.cs index 63a7c3bf..fcb4c137 100644 --- a/Vocaluxe/Screens/CScreenLoad.cs +++ b/Vocaluxe/Screens/CScreenLoad.cs @@ -1,22 +1,24 @@ using System.Diagnostics; using System.Threading; using System.Windows.Forms; - using Vocaluxe.Base; using VocaluxeLib.Menu; namespace Vocaluxe.Screens { - class CScreenLoad: CMenu + class CScreenLoad : CMenu { // Version number for theme files. Increment it, if you've changed something on the theme files! - protected override int _ScreenVersion { get { return 1; } } - const float WaitTime = 0.5f; //wait time before starting first video + protected override int _ScreenVersion + { + get { return 1; } + } + private const float WaitTime = 0.5f; //wait time before starting first video - const string TextStatus = "TextStatus"; + private const string TextStatus = "TextStatus"; + + private readonly string[] IntroVideo = new[] {"IntroIn", "IntroMid", "IntroOut"}; - private readonly string[] IntroVideo = new string[] { "IntroIn", "IntroMid", "IntroOut" }; - private Thread _SongLoaderThread; private Stopwatch _timer; private bool _SkipIntro; @@ -25,22 +27,15 @@ namespace Vocaluxe.Screens private VideoPlayer[] _Intros; private bool _BGMusicStartet; - - - public CScreenLoad() - { - } public override void Init() { base.Init(); - _ThemeTexts = new string[] { TextStatus }; + _ThemeTexts = new[] {TextStatus}; _Intros = new VideoPlayer[IntroVideo.Length]; for (int i = 0; i < _Intros.Length; i++) - { _Intros[i] = new VideoPlayer(); - } _timer = new Stopwatch(); } @@ -48,10 +43,7 @@ namespace Vocaluxe.Screens { base.HandleInput(KeyEvent); - if (KeyEvent.KeyPressed) - { - - } + if (KeyEvent.KeyPressed) {} else { switch (KeyEvent.Key) @@ -72,9 +64,7 @@ namespace Vocaluxe.Screens base.HandleMouse(MouseEvent); if (MouseEvent.LB || MouseEvent.RB) - { _SkipIntro = true; - } return true; } @@ -93,13 +83,13 @@ namespace Vocaluxe.Screens CConfig.SaveConfig(); } } - - _SongLoaderThread = new Thread(new ThreadStart(CSongs.LoadSongs)); + + _SongLoaderThread = new Thread(CSongs.LoadSongs); _SongLoaderThread.Name = "SongLoader"; Texts[TextStatus].Text = CLanguage.Translate("TR_SCREENLOAD_TOTAL") + ": 0 " + - CLanguage.Translate("TR_SCREENLOAD_SONGS") + " (0 " + - CLanguage.Translate("TR_SCREENLOAD_LOADED") + ")"; + CLanguage.Translate("TR_SCREENLOAD_SONGS") + " (0 " + + CLanguage.Translate("TR_SCREENLOAD_LOADED") + ")"; _SkipIntro = false; _CurrentIntroVideoNr = -1; @@ -108,9 +98,7 @@ namespace Vocaluxe.Screens if (CConfig.VideoBackgrounds == EOffOn.TR_CONFIG_ON) { for (int i = 0; i < _Intros.Length; i++) - { _Intros[i].Load(IntroVideo[i]); - } } _BGMusicStartet = false; @@ -123,9 +111,7 @@ namespace Vocaluxe.Screens if (CConfig.VideoBackgrounds == EOffOn.TR_CONFIG_ON) { for (int i = 0; i < _Intros.Length; i++) - { _Intros[i].PreLoad(); - } } CLog.StartBenchmark(0, "Load Songs Full"); @@ -154,14 +140,12 @@ namespace Vocaluxe.Screens if (CSettings.GameState == EGameState.EditTheme) _timer.Stop(); else - _timer.Start(); + _timer.Start(); bool next = (CConfig.CoverLoading != ECoverLoading.TR_CONFIG_COVERLOADING_ATSTART || CSongs.CoverLoaded); if ((_IntroOutPlayed || _SkipIntro) && next && CSettings.GameState != EGameState.EditTheme && CSongs.SongsLoaded) - { CSettings.GameState = EGameState.Normal; - } if (CSettings.GameState == EGameState.Normal) CGraphics.FadeTo(EScreens.ScreenMain); @@ -181,7 +165,7 @@ namespace Vocaluxe.Screens _BGMusicStartet = true; } - + return true; } @@ -190,9 +174,7 @@ namespace Vocaluxe.Screens DrawBG(); for (int i = 0; i < _Intros.Length; i++) - { _Intros[i].Draw(); - } DrawFG(); return true; @@ -205,9 +187,7 @@ namespace Vocaluxe.Screens _timer.Reset(); for (int i = 0; i < _Intros.Length; i++) - { _Intros[i].Close(); - } CBackgroundMusic.CanSing = true; @@ -234,18 +214,21 @@ namespace Vocaluxe.Screens { _CurrentIntroVideoNr = 0; _Intros[0].Start(); - }else if (_CurrentIntroVideoNr == 0 && _Intros[0].IsFinished && CConfig.CoverLoading == ECoverLoading.TR_CONFIG_COVERLOADING_ATSTART) + } + else if (_CurrentIntroVideoNr == 0 && _Intros[0].IsFinished && CConfig.CoverLoading == ECoverLoading.TR_CONFIG_COVERLOADING_ATSTART) { _CurrentIntroVideoNr = 1; _Intros[1].Loop = true; _Intros[1].Start(); - }else if ((_CurrentIntroVideoNr == 1 && CSongs.CoverLoaded) || - (_CurrentIntroVideoNr == 0 && _Intros[0].IsFinished)) + } + else if ((_CurrentIntroVideoNr == 1 && CSongs.CoverLoaded) || + (_CurrentIntroVideoNr == 0 && _Intros[0].IsFinished)) { _CurrentIntroVideoNr = 2; _Intros[2].Start(); - }else if (_CurrentIntroVideoNr == 2 && _Intros[2].IsFinished) + } + else if (_CurrentIntroVideoNr == 2 && _Intros[2].IsFinished) _IntroOutPlayed = true; } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenMain.cs b/Vocaluxe/Screens/CScreenMain.cs index fd00e3a4..9df2e644 100644 --- a/Vocaluxe/Screens/CScreenMain.cs +++ b/Vocaluxe/Screens/CScreenMain.cs @@ -1,48 +1,43 @@ using System.Windows.Forms; - using Vocaluxe.Base; using VocaluxeLib.Menu; namespace Vocaluxe.Screens { - class CScreenMain: CMenu + class CScreenMain : CMenu { // Version number for theme files. Increment it, if you've changed something on the theme files! - protected override int _ScreenVersion { get { return 1; } } + protected override int _ScreenVersion + { + get { return 1; } + } - const string ButtonSing = "ButtonSing"; - const string ButtonParty = "ButtonParty"; - const string ButtonOptions = "ButtonOptions"; - const string ButtonProfiles = "ButtonProfiles"; - const string ButtonExit = "ButtonExit"; + private const string ButtonSing = "ButtonSing"; + private const string ButtonParty = "ButtonParty"; + private const string ButtonOptions = "ButtonOptions"; + private const string ButtonProfiles = "ButtonProfiles"; + private const string ButtonExit = "ButtonExit"; //CParticleEffect Snowflakes; - - public CScreenMain() - { - } public override void Init() { base.Init(); - _ThemeStatics = new string[] { "StaticMenuBar" }; - _ThemeButtons = new string[] { ButtonSing, ButtonParty, ButtonOptions, ButtonProfiles, ButtonExit }; + _ThemeStatics = new[] {"StaticMenuBar"}; + _ThemeButtons = new[] {ButtonSing, ButtonParty, ButtonOptions, ButtonProfiles, ButtonExit}; } public override void LoadTheme(string XmlPath) { - base.LoadTheme(XmlPath); + base.LoadTheme(XmlPath); } public override bool HandleInput(KeyEvent KeyEvent) { base.HandleInput(KeyEvent); - if (KeyEvent.KeyPressed) - { - - } + if (KeyEvent.KeyPressed) {} else { switch (KeyEvent.Key) @@ -84,7 +79,7 @@ namespace Vocaluxe.Screens break; } - } + } return true; } @@ -112,7 +107,7 @@ namespace Vocaluxe.Screens if (Buttons[ButtonExit].Selected) return false; } - + return true; } @@ -159,4 +154,4 @@ namespace Vocaluxe.Screens // Snowflakes.Pause(); } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenNames.cs b/Vocaluxe/Screens/CScreenNames.cs index 4c83f087..9d2d132c 100644 --- a/Vocaluxe/Screens/CScreenNames.cs +++ b/Vocaluxe/Screens/CScreenNames.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Windows.Forms; - using Vocaluxe.Base; using VocaluxeLib.Menu; @@ -10,7 +9,10 @@ namespace Vocaluxe.Screens class CScreenNames : CMenu { // Version number for theme files. Increment it, if you've changed something on the theme files! - protected override int _ScreenVersion { get { return 3; } } + protected override int _ScreenVersion + { + get { return 3; } + } private CStatic chooseAvatarStatic; private int OldMouseX; @@ -24,37 +26,32 @@ namespace Vocaluxe.Screens private const string StaticWarningMics = "StaticWarningMics"; private const string TextWarningProfiles = "TextWarningProfiles"; private const string StaticWarningProfiles = "StaticWarningProfiles"; - private readonly string[] StaticPlayer = new string[] { "StaticPlayer1", "StaticPlayer2", "StaticPlayer3", "StaticPlayer4", "StaticPlayer5", "StaticPlayer6" }; - private readonly string[] StaticPlayerAvatar = new string[] { "StaticPlayerAvatar1", "StaticPlayerAvatar2", "StaticPlayerAvatar3", "StaticPlayerAvatar4", "StaticPlayerAvatar5", "StaticPlayerAvatar6" }; - private readonly string[] TextPlayer = new string[] { "TextPlayer1", "TextPlayer2", "TextPlayer3", "TextPlayer4", "TextPlayer5", "TextPlayer6" }; - private readonly string[] EqualizerPlayer = new string[] { "EqualizerPlayer1", "EqualizerPlayer2", "EqualizerPlayer3", "EqualizerPlayer4", "EqualizerPlayer5", "EqualizerPlayer6" }; - private readonly string[] SelectSlideDuetPlayer = new string[] { "SelectSlideDuetPlayer1", "SelectSlideDuetPlayer2", "SelectSlideDuetPlayer3", "SelectSlideDuetPlayer4", "SelectSlideDuetPlayer5", "SelectSlideDuetPlayer6" }; - private STexture[] OriginalPlayerAvatarTextures = new STexture[CSettings.MaxNumPlayer]; + private readonly string[] StaticPlayer = new[] {"StaticPlayer1", "StaticPlayer2", "StaticPlayer3", "StaticPlayer4", "StaticPlayer5", "StaticPlayer6"}; + private readonly string[] StaticPlayerAvatar = new[] + {"StaticPlayerAvatar1", "StaticPlayerAvatar2", "StaticPlayerAvatar3", "StaticPlayerAvatar4", "StaticPlayerAvatar5", "StaticPlayerAvatar6"}; + private readonly string[] TextPlayer = new[] {"TextPlayer1", "TextPlayer2", "TextPlayer3", "TextPlayer4", "TextPlayer5", "TextPlayer6"}; + private readonly string[] EqualizerPlayer = new[] {"EqualizerPlayer1", "EqualizerPlayer2", "EqualizerPlayer3", "EqualizerPlayer4", "EqualizerPlayer5", "EqualizerPlayer6"}; + private readonly string[] SelectSlideDuetPlayer = new[] + {"SelectSlideDuetPlayer1", "SelectSlideDuetPlayer2", "SelectSlideDuetPlayer3", "SelectSlideDuetPlayer4", "SelectSlideDuetPlayer5", "SelectSlideDuetPlayer6"}; + private readonly STexture[] OriginalPlayerAvatarTextures = new STexture[CSettings.MaxNumPlayer]; - private bool selectingMouseActive = false; - private bool selectingKeyboardActive = false; - private bool selectingKeyboardUnendless = false; - private int selectingKeyboardPlayerNr = 0; + private bool selectingMouseActive; + private bool selectingKeyboardActive; + private bool selectingKeyboardUnendless; + private int selectingKeyboardPlayerNr; private int SelectedPlayerNr; - + private int[] _PlayerNr; - - public CScreenNames() - { - } public override void Init() { base.Init(); List statics = new List(); - foreach(string text in StaticPlayer){ + foreach (string text in StaticPlayer) statics.Add(text); - } foreach (string text in StaticPlayerAvatar) - { statics.Add(text); - } statics.Add(StaticWarningMics); statics.Add(StaticWarningProfiles); _ThemeStatics = statics.ToArray(); @@ -67,9 +64,8 @@ namespace Vocaluxe.Screens texts.Clear(); texts.Add(TextWarningMics); texts.Add(TextWarningProfiles); - foreach(string text in TextPlayer){ + foreach (string text in TextPlayer) texts.Add(text); - } _ThemeTexts = texts.ToArray(); texts.Clear(); @@ -93,22 +89,16 @@ namespace Vocaluxe.Screens public override void LoadTheme(string XmlPath) { base.LoadTheme(XmlPath); - + _PlayerNr = new int[CSettings.MaxNumPlayer]; for (int i = 0; i < _PlayerNr.Length; i++) - { _PlayerNr[i] = i; - } for (int i = 0; i < CSettings.MaxNumPlayer; i++) - { OriginalPlayerAvatarTextures[i] = Statics[StaticPlayerAvatar[i]].Texture; - } for (int i = 1; i <= CSettings.MaxNumPlayer; i++) - { Equalizers["EqualizerPlayer" + i].ScreenHandles = true; - } } public override bool HandleInput(KeyEvent KeyEvent) @@ -164,15 +154,15 @@ namespace Vocaluxe.Screens { SelectedPlayerNr = NameSelections[NameSelection].Selection; //Update Game-infos with new player - CGame.Player[selectingKeyboardPlayerNr-1].Name = CProfiles.Profiles[SelectedPlayerNr].PlayerName; - CGame.Player[selectingKeyboardPlayerNr-1].Difficulty = CProfiles.Profiles[SelectedPlayerNr].Difficulty; - CGame.Player[selectingKeyboardPlayerNr-1].ProfileID = SelectedPlayerNr; + CGame.Player[selectingKeyboardPlayerNr - 1].Name = CProfiles.Profiles[SelectedPlayerNr].PlayerName; + CGame.Player[selectingKeyboardPlayerNr - 1].Difficulty = CProfiles.Profiles[SelectedPlayerNr].Difficulty; + CGame.Player[selectingKeyboardPlayerNr - 1].ProfileID = SelectedPlayerNr; //Update config for default players. CConfig.Players[selectingKeyboardPlayerNr - 1] = CProfiles.Profiles[SelectedPlayerNr].ProfileFile; CConfig.SaveConfig(); //Update texture and name - Statics[StaticPlayerAvatar[selectingKeyboardPlayerNr-1]].Texture = CProfiles.Profiles[SelectedPlayerNr].Avatar.Texture; - Texts[TextPlayer[selectingKeyboardPlayerNr-1]].Text = CProfiles.Profiles[SelectedPlayerNr].PlayerName; + Statics[StaticPlayerAvatar[selectingKeyboardPlayerNr - 1]].Texture = CProfiles.Profiles[SelectedPlayerNr].Avatar.Texture; + Texts[TextPlayer[selectingKeyboardPlayerNr - 1]].Text = CProfiles.Profiles[SelectedPlayerNr].PlayerName; //Update profile-warning CheckPlayers(); //Update Tiles-List @@ -308,12 +298,12 @@ namespace Vocaluxe.Screens selectingKeyboardUnendless = false; NameSelections[NameSelection].KeyboardSelection(false, -1); break; - + case Keys.Delete: - //Delete profile-selection - CGame.Player[selectingKeyboardPlayerNr-1].ProfileID = -1; - CGame.Player[selectingKeyboardPlayerNr-1].Name = String.Empty; - CGame.Player[selectingKeyboardPlayerNr-1].Difficulty = EGameDifficulty.TR_CONFIG_EASY; + //Delete profile-selection + CGame.Player[selectingKeyboardPlayerNr - 1].ProfileID = -1; + CGame.Player[selectingKeyboardPlayerNr - 1].Name = String.Empty; + CGame.Player[selectingKeyboardPlayerNr - 1].Difficulty = EGameDifficulty.TR_CONFIG_EASY; //Update config for default players. CConfig.Players[selectingKeyboardPlayerNr - 1] = String.Empty; CConfig.SaveConfig(); @@ -329,7 +319,7 @@ namespace Vocaluxe.Screens //Update Tiles-List NameSelections[NameSelection].UpdateList(); break; - + case Keys.F10: if (CGame.GetNumSongs() == 1 && CGame.GetSong(1).IsDuet) { @@ -345,10 +335,9 @@ namespace Vocaluxe.Screens SetInteractionToButton(Buttons[ButtonStart]); } break; - } } - //Normal Keyboard handling + //Normal Keyboard handling else { base.HandleInput(KeyEvent); @@ -460,7 +449,7 @@ namespace Vocaluxe.Screens OldMouseX = MouseEvent.X; OldMouseY = MouseEvent.Y; } - // LeftButton isn't hold anymore, but Selec-Mode is still active -> "Drop" of Avatar + // LeftButton isn't hold anymore, but Selec-Mode is still active -> "Drop" of Avatar else if (selectingMouseActive) { //Check if really a player was selected @@ -470,7 +459,7 @@ namespace Vocaluxe.Screens for (int i = 0; i < StaticPlayer.Length; i++) { //Check first, if area is "active" - if (Statics[StaticPlayer[i]].Visible == true) + if (Statics[StaticPlayer[i]].Visible) { //Check if Mouse is in area if (CHelper.IsInBounds(Statics[StaticPlayer[i]].Rect, MouseEvent)) @@ -499,10 +488,7 @@ namespace Vocaluxe.Screens chooseAvatarStatic.Visible = false; } - if (MouseEvent.LB && IsMouseOver(MouseEvent)) - { - - } + if (MouseEvent.LB && IsMouseOver(MouseEvent)) {} if (MouseEvent.LB && IsMouseOver(MouseEvent)) { @@ -522,13 +508,12 @@ namespace Vocaluxe.Screens if (!processed) UpdatePlayerNumber(); - //Update Tiles-List - NameSelections[NameSelection].UpdateList(); + //Update Tiles-List + NameSelections[NameSelection].UpdateList(); } if (MouseEvent.RB) { - bool exit = true; //Remove profile-selection for (int i = 0; i < CConfig.NumPlayer; i++) @@ -543,7 +528,7 @@ namespace Vocaluxe.Screens CConfig.SaveConfig(); //Update texture and name Statics[StaticPlayerAvatar[i]].Texture = OriginalPlayerAvatarTextures[i]; - Texts[TextPlayer[i]].Text = CLanguage.Translate("TR_SCREENNAMES_PLAYER") + " " + (i+1).ToString(); + Texts[TextPlayer[i]].Text = CLanguage.Translate("TR_SCREENNAMES_PLAYER") + " " + (i + 1).ToString(); //Update profile-warning CheckPlayers(); //Update Tiles-List @@ -551,7 +536,7 @@ namespace Vocaluxe.Screens exit = false; } } - if(exit) + if (exit) CGraphics.FadeTo(EScreens.ScreenSong); } @@ -571,8 +556,8 @@ namespace Vocaluxe.Screens { for (int i = 1; i <= CGame.NumPlayer; i++) { - CSound.AnalyzeBuffer((i-1)); - Equalizers["EqualizerPlayer" + i].Update(CSound.ToneWeigth((i-1))); + CSound.AnalyzeBuffer((i - 1)); + Equalizers["EqualizerPlayer" + i].Update(CSound.ToneWeigth((i - 1))); } return true; } @@ -629,14 +614,10 @@ namespace Vocaluxe.Screens base.Draw(); if (chooseAvatarStatic.Visible) - { chooseAvatarStatic.Draw(); - } for (int i = 1; i <= CGame.NumPlayer; i++) - { Equalizers["EqualizerPlayer" + i].Draw(); - } - return true; + return true; } private void StartSong() @@ -645,7 +626,7 @@ namespace Vocaluxe.Screens { if (CGame.Player[i].ProfileID < 0) { - CGame.Player[i].Name = "Player " + (i+1).ToString(); + CGame.Player[i].Name = "Player " + (i + 1).ToString(); CGame.Player[i].Difficulty = EGameDifficulty.TR_CONFIG_EASY; CGame.Player[i].ProfileID = -1; } @@ -653,14 +634,10 @@ namespace Vocaluxe.Screens { //Just a work-around for not crashing the game if (CGame.Player[i].Name == null) - { CGame.Player[i].Name = ""; - } } if (CGame.GetNumSongs() == 1 && CGame.GetSong(1).IsDuet) - { CGame.Player[i].LineNr = SelectSlides[SelectSlideDuetPlayer[i]].Selection; - } } CGraphics.FadeTo(EScreens.ScreenSing); @@ -670,16 +647,14 @@ namespace Vocaluxe.Screens { SelectSlides[SelectSlidePlayerNumber].Clear(); for (int i = 1; i <= CSettings.MaxNumPlayer; i++) - { SelectSlides[SelectSlidePlayerNumber].AddValue(CLanguage.Translate("TR_SCREENNAMES_" + i + "PLAYER")); - } SelectSlides[SelectSlidePlayerNumber].Selection = CConfig.NumPlayer - 1; } private void UpdatePlayerNumber() { - CConfig.NumPlayer = (int)SelectSlides[SelectSlidePlayerNumber].Selection + 1; - CGame.NumPlayer = (int)SelectSlides[SelectSlidePlayerNumber].Selection + 1; + CConfig.NumPlayer = SelectSlides[SelectSlidePlayerNumber].Selection + 1; + CGame.NumPlayer = SelectSlides[SelectSlidePlayerNumber].Selection + 1; for (int i = 1; i <= CSettings.MaxNumPlayer; i++) { if (i <= CGame.NumPlayer) @@ -688,9 +663,7 @@ namespace Vocaluxe.Screens Statics["StaticPlayerAvatar" + i].Visible = true; Texts["TextPlayer" + i].Visible = true; if (Texts["TextPlayer" + i].Text.Length == 0) - { Texts["TextPlayer" + i].Text = CLanguage.Translate("TR_SCREENNAMES_PLAYER") + " " + i.ToString(); - } Equalizers["EqualizerPlayer" + i].Visible = true; if (CGame.GetNumSongs() == 1 && CGame.GetSong(1).IsDuet) SelectSlides["SelectSlideDuetPlayer" + i].Visible = true; @@ -715,9 +688,7 @@ namespace Vocaluxe.Screens for (int player = 0; player < CConfig.NumPlayer; player++) { if (!CConfig.IsMicConfig(player + 1)) - { _PlayerWithoutMicro.Add(player + 1); - } } if (_PlayerWithoutMicro.Count > 0) { @@ -730,25 +701,17 @@ namespace Vocaluxe.Screens for (int i = 0; i < _PlayerWithoutMicro.Count; i++) { if (_PlayerWithoutMicro.Count - 1 == i) - { PlayerNums += _PlayerWithoutMicro[i].ToString(); - } else if (_PlayerWithoutMicro.Count - 2 == i) - { PlayerNums += _PlayerWithoutMicro[i].ToString() + " " + CLanguage.Translate("TR_GENERAL_AND") + " "; - } else - { PlayerNums += _PlayerWithoutMicro[i].ToString() + ", "; - } } Texts[TextWarningMics].Text = CLanguage.Translate("TR_SCREENNAMES_WARNING_MICS_PL").Replace("%v", PlayerNums); } else - { Texts[TextWarningMics].Text = CLanguage.Translate("TR_SCREENNAMES_WARNING_MICS_SG").Replace("%v", _PlayerWithoutMicro[0].ToString()); - } } else { @@ -763,9 +726,7 @@ namespace Vocaluxe.Screens for (int player = 0; player < CConfig.NumPlayer; player++) { if (CGame.Player[player].ProfileID < 0) - { _PlayerWithoutProfile.Add(player + 1); - } } if (_PlayerWithoutProfile.Count > 0) @@ -779,25 +740,17 @@ namespace Vocaluxe.Screens for (int i = 0; i < _PlayerWithoutProfile.Count; i++) { if (_PlayerWithoutProfile.Count - 1 == i) - { PlayerNums += _PlayerWithoutProfile[i].ToString(); - } else if (_PlayerWithoutProfile.Count - 2 == i) - { PlayerNums += _PlayerWithoutProfile[i].ToString() + " " + CLanguage.Translate("TR_GENERAL_AND") + " "; - } else - { PlayerNums += _PlayerWithoutProfile[i].ToString() + ", "; - } } Texts[TextWarningProfiles].Text = CLanguage.Translate("TR_SCREENNAMES_WARNING_PROFILES_PL").Replace("%v", PlayerNums); } else - { Texts[TextWarningProfiles].Text = CLanguage.Translate("TR_SCREENNAMES_WARNING_PROFILES_SG").Replace("%v", _PlayerWithoutProfile[0].ToString()); - } } else { @@ -806,4 +759,4 @@ namespace Vocaluxe.Screens } } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenOptions.cs b/Vocaluxe/Screens/CScreenOptions.cs index 44b5f8e9..96f9b49e 100644 --- a/Vocaluxe/Screens/CScreenOptions.cs +++ b/Vocaluxe/Screens/CScreenOptions.cs @@ -1,5 +1,4 @@ using System.Windows.Forms; - using Vocaluxe.Base; using VocaluxeLib.Menu; @@ -8,7 +7,10 @@ namespace Vocaluxe.Screens class CScreenOptions : CMenu { // Version number for theme files. Increment it, if you've changed something on the theme files! - protected override int _ScreenVersion { get { return 1; } } + protected override int _ScreenVersion + { + get { return 1; } + } private const string ButtonOptionsGame = "ButtonOptionsGame"; private const string ButtonOptionsSound = "ButtonOptionsSound"; @@ -17,25 +19,18 @@ namespace Vocaluxe.Screens private const string ButtonOptionsLyrics = "ButtonOptionsLyrics"; private const string ButtonOptionsTheme = "ButtonOptionsTheme"; - public CScreenOptions() - { - } - public override void Init() { base.Init(); - _ThemeButtons = new string[] { ButtonOptionsGame, ButtonOptionsSound, ButtonOptionsRecord, ButtonOptionsVideo, ButtonOptionsLyrics, ButtonOptionsTheme }; + _ThemeButtons = new[] {ButtonOptionsGame, ButtonOptionsSound, ButtonOptionsRecord, ButtonOptionsVideo, ButtonOptionsLyrics, ButtonOptionsTheme}; } public override bool HandleInput(KeyEvent KeyEvent) { base.HandleInput(KeyEvent); - if (KeyEvent.KeyPressed) - { - - } + if (KeyEvent.KeyPressed) {} else { switch (KeyEvent.Key) @@ -101,9 +96,7 @@ namespace Vocaluxe.Screens } if (MouseEvent.RB) - { CGraphics.FadeTo(EScreens.ScreenMain); - } return true; } @@ -118,4 +111,4 @@ namespace Vocaluxe.Screens return true; } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenOptionsGame.cs b/Vocaluxe/Screens/CScreenOptionsGame.cs index d22e23ca..f43567b0 100644 --- a/Vocaluxe/Screens/CScreenOptionsGame.cs +++ b/Vocaluxe/Screens/CScreenOptionsGame.cs @@ -1,5 +1,4 @@ using System.Windows.Forms; - using Vocaluxe.Base; using VocaluxeLib.Menu; @@ -8,7 +7,10 @@ namespace Vocaluxe.Screens class CScreenOptionsGame : CMenu { // Version number for theme files. Increment it, if you've changed something on the theme files! - protected override int _ScreenVersion { get { return 1; } } + protected override int _ScreenVersion + { + get { return 1; } + } private const string SelectSlideLanguage = "SelectSlideLanguage"; private const string SelectSlideDebugLevel = "SelectSlideDebugLevel"; @@ -19,16 +21,12 @@ namespace Vocaluxe.Screens private const string ButtonExit = "ButtonExit"; - public CScreenOptionsGame() - { - } - public override void Init() { base.Init(); - _ThemeButtons = new string[] { ButtonExit }; - _ThemeSelectSlides = new string[] { SelectSlideLanguage, SelectSlideDebugLevel, SelectSlideSongMenu, SelectSlideSongSorting, SelectSlideTabs, SelectSlideTimerMode }; + _ThemeButtons = new[] {ButtonExit}; + _ThemeSelectSlides = new[] {SelectSlideLanguage, SelectSlideDebugLevel, SelectSlideSongMenu, SelectSlideSongSorting, SelectSlideTabs, SelectSlideTimerMode}; } public override void LoadTheme(string XmlPath) @@ -43,13 +41,12 @@ namespace Vocaluxe.Screens SelectSlides[SelectSlideSongSorting].SetValues((int)CConfig.SongSorting); SelectSlides[SelectSlideTabs].SetValues((int)CConfig.Tabs); SelectSlides[SelectSlideTimerMode].SetValues((int)CConfig.TimerMode); - } public override bool HandleInput(KeyEvent KeyEvent) { base.HandleInput(KeyEvent); - + if (!KeyEvent.KeyPressed) { switch (KeyEvent.Key) @@ -70,9 +67,9 @@ namespace Vocaluxe.Screens { SaveConfig(); CGraphics.FadeTo(EScreens.ScreenOptions); - } + } break; - + case Keys.Left: SaveConfig(); break; @@ -99,9 +96,7 @@ namespace Vocaluxe.Screens { SaveConfig(); if (Buttons[ButtonExit].Selected) - { CGraphics.FadeTo(EScreens.ScreenOptions); - } } return true; } @@ -131,7 +126,6 @@ namespace Vocaluxe.Screens CSongs.Sorter.SongSorting = CConfig.SongSorting; CSongs.Categorizer.Tabs = CConfig.Tabs; - } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenOptionsLyrics.cs b/Vocaluxe/Screens/CScreenOptionsLyrics.cs index af68949e..ea97ee27 100644 --- a/Vocaluxe/Screens/CScreenOptionsLyrics.cs +++ b/Vocaluxe/Screens/CScreenOptionsLyrics.cs @@ -1,5 +1,4 @@ using System.Windows.Forms; - using Vocaluxe.Base; using VocaluxeLib.Menu; @@ -8,23 +7,22 @@ namespace Vocaluxe.Screens class CScreenOptionsLyrics : CMenu { // Version number for theme files. Increment it, if you've changed something on the theme files! - protected override int _ScreenVersion { get { return 1; } } + protected override int _ScreenVersion + { + get { return 1; } + } private const string SelectSlideLyricStyle = "SelectSlideLyricStyle"; private const string SelectSlideLyricsOnTop = "SelectSlideLyricsOnTop"; private const string ButtonExit = "ButtonExit"; - public CScreenOptionsLyrics() - { - } - public override void Init() { base.Init(); - _ThemeButtons = new string[] { ButtonExit }; - _ThemeSelectSlides = new string[] { SelectSlideLyricStyle, SelectSlideLyricsOnTop }; + _ThemeButtons = new[] {ButtonExit}; + _ThemeSelectSlides = new[] {SelectSlideLyricStyle, SelectSlideLyricsOnTop}; } public override void LoadTheme(string XmlPath) @@ -38,10 +36,7 @@ namespace Vocaluxe.Screens { base.HandleInput(KeyEvent); - if (KeyEvent.KeyPressed) - { - - } + if (KeyEvent.KeyPressed) {} else { switch (KeyEvent.Key) @@ -90,9 +85,7 @@ namespace Vocaluxe.Screens { SaveConfig(); if (Buttons[ButtonExit].Selected) - { CGraphics.FadeTo(EScreens.ScreenOptions); - } } return true; } @@ -115,4 +108,4 @@ namespace Vocaluxe.Screens CConfig.SaveConfig(); } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenOptionsRecord.cs b/Vocaluxe/Screens/CScreenOptionsRecord.cs index e0afd9e3..ffb2c176 100644 --- a/Vocaluxe/Screens/CScreenOptionsRecord.cs +++ b/Vocaluxe/Screens/CScreenOptionsRecord.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using System.Diagnostics; using System.Windows.Forms; - using Vocaluxe.Base; using Vocaluxe.Lib.Sound; using VocaluxeLib.Menu; @@ -17,7 +16,10 @@ namespace Vocaluxe.Screens class CScreenOptionsRecord : CMenu { // Version number for theme files. Increment it, if you've changed something on the theme files! - protected override int _ScreenVersion { get { return 2; } } + protected override int _ScreenVersion + { + get { return 2; } + } private const float MaxDelayTime = 1f; private const string SelectSlideRecordDevices = "SelectSlideRecordDevices"; @@ -39,7 +41,7 @@ namespace Vocaluxe.Screens private const string EqualizerChannel1 = "EqualizerChannel1"; private const string EqualizerChannel2 = "EqualizerChannel2"; - private readonly string[] StaticEnergyChannel = new string[] { "StaticEnergyChannel1", "StaticEnergyChannel2" }; + private readonly string[] StaticEnergyChannel = new[] {"StaticEnergyChannel1", "StaticEnergyChannel2"}; private float[] ChannelEnergy; private SRecordDevice[] _devices; @@ -50,10 +52,6 @@ namespace Vocaluxe.Screens private bool _DelayTestRunning; private int _DelaySound; - public CScreenOptionsRecord() - { - } - public override void Init() { base.Init(); @@ -63,10 +61,10 @@ namespace Vocaluxe.Screens values.AddRange(StaticEnergyChannel); _ThemeStatics = values.ToArray(); - _ThemeTexts = new string[] { TextWarning, TextDelayChannel1, TextDelayChannel2 }; - _ThemeButtons = new string[] { ButtonExit, ButtonDelayTest }; - _ThemeSelectSlides = new string[] { SelectSlideRecordDevices, SelectSlideRecordInputs, SelectSlideRecordChannel1, SelectSlideRecordChannel2, SelectSlideDelay }; - _ThemeEqualizers = new string[] { EqualizerChannel1, EqualizerChannel2 }; + _ThemeTexts = new[] {TextWarning, TextDelayChannel1, TextDelayChannel2}; + _ThemeButtons = new[] {ButtonExit, ButtonDelayTest}; + _ThemeSelectSlides = new[] {SelectSlideRecordDevices, SelectSlideRecordInputs, SelectSlideRecordChannel1, SelectSlideRecordChannel2, SelectSlideDelay}; + _ThemeEqualizers = new[] {EqualizerChannel1, EqualizerChannel2}; } public override void LoadTheme(string XmlPath) @@ -90,9 +88,7 @@ namespace Vocaluxe.Screens } for (int i = 0; i < 26; i++) - { SelectSlides[SelectSlideDelay].AddValue((i * 20).ToString() + " ms"); - } ChannelEnergy = new float[StaticEnergyChannel.Length]; @@ -110,10 +106,7 @@ namespace Vocaluxe.Screens { base.HandleInput(KeyEvent); - if (KeyEvent.KeyPressed) - { - - } + if (KeyEvent.KeyPressed) {} else { switch (KeyEvent.Key) @@ -135,12 +128,10 @@ namespace Vocaluxe.Screens SaveMicConfig(); CGraphics.FadeTo(EScreens.ScreenOptions); } - + if (Buttons[ButtonDelayTest].Selected) - { TestDelay(); - } - + break; case Keys.D: @@ -213,9 +204,7 @@ namespace Vocaluxe.Screens } if (Buttons[ButtonDelayTest].Selected) - { TestDelay(); - } } return true; } @@ -223,9 +212,7 @@ namespace Vocaluxe.Screens public override bool UpdateGame() { for (int i = 0; i < CSettings.MaxNumPlayer; i++) - { CSound.AnalyzeBuffer(i); - } if (_DelayTest != null) { @@ -255,7 +242,7 @@ namespace Vocaluxe.Screens _DelayTestRunning = false; } else if (CSound.RecordGetMaxVolume(player - 1) > 0.1f && - (CSound.RecordGetToneAbs(player - 1) == 9 || CSound.RecordGetToneAbs(player - 1) == 21 || CSound.RecordGetToneAbs(player - 1) == 33)) + (CSound.RecordGetToneAbs(player - 1) == 9 || CSound.RecordGetToneAbs(player - 1) == 21 || CSound.RecordGetToneAbs(player - 1) == 33)) { _DelayTest[i].Delay = _DelayTest[i].Timer.ElapsedMilliseconds; _DelayTest[i].Timer.Stop(); @@ -293,9 +280,7 @@ namespace Vocaluxe.Screens else { for (int i = 0; i < ChannelEnergy.Length; i++) - { ChannelEnergy[i] = 0f; - } Equalizers[EqualizerChannel1].Reset(); Equalizers[EqualizerChannel2].Reset(); } @@ -311,9 +296,7 @@ namespace Vocaluxe.Screens SelectSlides[SelectSlideRecordInputs].Clear(); for (int i = 0; i < ChannelEnergy.Length; i++) - { ChannelEnergy[i] = 0f; - } _DeviceNr = -1; _InputNr = -1; @@ -326,22 +309,18 @@ namespace Vocaluxe.Screens GetFirstConfiguredRecordDevice(ref _DeviceNr, ref _InputNr); for (int dev = 0; dev < _devices.Length; dev++) - { SelectSlides[SelectSlideRecordDevices].AddValue(_devices[dev].Name); - } SelectSlides[SelectSlideRecordDevices].Selection = _DeviceNr; for (int inp = 0; inp < _devices[0].Inputs.Count; inp++) - { SelectSlides[SelectSlideRecordInputs].AddValue(_devices[0].Inputs[inp].Name); - } SelectSlides[SelectSlideRecordInputs].Selection = _InputNr; UpdateChannels(); } SelectSlides[SelectSlideRecordChannel1].Visible = (_devices != null); SelectSlides[SelectSlideRecordChannel2].Visible = (_devices != null); - + Statics[StaticWarning].Visible = false; Texts[TextWarning].Visible = false; @@ -356,7 +335,7 @@ namespace Vocaluxe.Screens } } - SelectSlides[SelectSlideDelay].Selection = (int)(CConfig.MicDelay / 20); + SelectSlides[SelectSlideDelay].Selection = (CConfig.MicDelay / 20); _DelayTestRunning = false; _DelaySound = -1; @@ -388,13 +367,13 @@ namespace Vocaluxe.Screens if (ChannelEnergy[i] > 0f) { SRectF rect = new SRectF(Statics[StaticEnergyChannel[i]].Rect.X, - Statics[StaticEnergyChannel[i]].Rect.Y, - Statics[StaticEnergyChannel[i]].Rect.W * ChannelEnergy[i], - Statics[StaticEnergyChannel[i]].Rect.H, - Statics[StaticEnergyChannel[i]].Rect.Z); + Statics[StaticEnergyChannel[i]].Rect.Y, + Statics[StaticEnergyChannel[i]].Rect.W * ChannelEnergy[i], + Statics[StaticEnergyChannel[i]].Rect.H, + Statics[StaticEnergyChannel[i]].Rect.Z); CDraw.DrawTexture(Statics[StaticEnergyChannel[i]].Texture, Statics[StaticEnergyChannel[i]].Rect, - new SColorF(1f, 1f, 1f, 1f), rect); + new SColorF(1f, 1f, 1f, 1f), rect); } } @@ -424,9 +403,7 @@ namespace Vocaluxe.Screens _InputNr = 0; for (int inp = 0; inp < _devices[_DeviceNr].Inputs.Count; inp++) - { SelectSlides[SelectSlideRecordInputs].AddValue(_devices[_DeviceNr].Inputs[inp].Name); - } _InputNr = 0; SelectSlides[SelectSlideRecordInputs].Selection = 0; UpdateChannels(); @@ -439,7 +416,7 @@ namespace Vocaluxe.Screens { _InputNr = SelectSlides[SelectSlideRecordInputs].Selection; - UpdateChannels(); + UpdateChannels(); } } @@ -448,21 +425,19 @@ namespace Vocaluxe.Screens CConfig.MicDelay = SelectSlides[SelectSlideDelay].Selection * 20; CConfig.SaveConfig(); } - + private void SaveMicConfig() { - if (_devices == null) - return; - + if (_devices == null) + return; + CSound.RecordStop(); SetMicConfig(); if (CheckMicConfig()) { for (int p = 0; p < CSettings.MaxNumPlayer; p++) - { CConfig.MicConfig[p].Channel = 0; - } for (int dev = 0; dev < _devices.Length; dev++) { @@ -483,7 +458,6 @@ namespace Vocaluxe.Screens CConfig.MicConfig[_devices[dev].Inputs[inp].PlayerChannel2 - 1].DeviceDriver = _devices[dev].Driver; CConfig.MicConfig[_devices[dev].Inputs[inp].PlayerChannel2 - 1].InputName = _devices[dev].Inputs[inp].Name; } - } } CConfig.SaveConfig(); @@ -513,13 +487,11 @@ namespace Vocaluxe.Screens { bool[] IsSet = new bool[CSettings.MaxNumPlayer]; for (int i = 0; i < CSettings.MaxNumPlayer; i++) - { - IsSet[i] = false; - } + IsSet[i] = false; if (_devices == null) - return true; - + return true; + for (int dev = 0; dev < _devices.Length; dev++) { for (int inp = 0; inp < _devices[dev].Inputs.Count; inp++) @@ -539,7 +511,6 @@ namespace Vocaluxe.Screens IsSet[_devices[dev].Inputs[inp].PlayerChannel2 - 1] = true; } - } } return true; @@ -553,7 +524,7 @@ namespace Vocaluxe.Screens return; _DelaySound = CSound.PlaySound(ESounds.T440); - _DelayTestRunning = true; + _DelayTestRunning = true; } private void GetFirstConfiguredRecordDevice(ref int Device, ref int Input) @@ -563,7 +534,7 @@ namespace Vocaluxe.Screens if (CConfig.MicConfig == null) return; - + for (int i = 0; i < _devices.Length; i++) { if (_devices[i].Name == CConfig.MicConfig[0].DeviceName && _devices[i].Driver == CConfig.MicConfig[0].DeviceDriver) @@ -584,4 +555,4 @@ namespace Vocaluxe.Screens } } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenOptionsSound.cs b/Vocaluxe/Screens/CScreenOptionsSound.cs index 25ce2dd5..65a65c07 100644 --- a/Vocaluxe/Screens/CScreenOptionsSound.cs +++ b/Vocaluxe/Screens/CScreenOptionsSound.cs @@ -1,5 +1,4 @@ using System.Windows.Forms; - using Vocaluxe.Base; using VocaluxeLib.Menu; @@ -8,7 +7,10 @@ namespace Vocaluxe.Screens class CScreenOptionsSound : CMenu { // Version number for theme files. Increment it, if you've changed something on the theme files! - protected override int _ScreenVersion { get { return 3; } } + protected override int _ScreenVersion + { + get { return 3; } + } private const string SelectSlideBackgroundMusic = "SelectSlideBackgroundMusic"; private const string SelectSlideBackgroundMusicVolume = "SelectSlideBackgroundMusicVolume"; @@ -21,41 +23,37 @@ namespace Vocaluxe.Screens private int _BackgroundMusicVolume; private EOffOn _BackgroundMusic; - public CScreenOptionsSound() - { - } - public override void Init() { base.Init(); - _ThemeButtons = new string[] { ButtonExit }; - _ThemeSelectSlides = new string[] { SelectSlideBackgroundMusic, SelectSlideBackgroundMusicVolume, SelectSlideBackgroundMusicSource, SelectSlidePreviewMusicVolume, SelectSlideGameMusicVolume }; + _ThemeButtons = new[] {ButtonExit}; + _ThemeSelectSlides = new[] + {SelectSlideBackgroundMusic, SelectSlideBackgroundMusicVolume, SelectSlideBackgroundMusicSource, SelectSlidePreviewMusicVolume, SelectSlideGameMusicVolume}; } public override void LoadTheme(string XmlPath) { base.LoadTheme(XmlPath); SelectSlides[SelectSlideBackgroundMusic].SetValues((int)CConfig.BackgroundMusic); - SelectSlides[SelectSlideBackgroundMusicVolume].AddValues(new string[] { "0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"}); + SelectSlides[SelectSlideBackgroundMusicVolume].AddValues(new[] + {"0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"}); SelectSlides[SelectSlideBackgroundMusicVolume].Selection = CConfig.BackgroundMusicVolume / 5; SelectSlides[SelectSlideBackgroundMusicSource].SetValues((int)CConfig.BackgroundMusicSource); SelectSlides[SelectSlideBackgroundMusicSource].Selection = (int)CConfig.BackgroundMusicSource; - SelectSlides[SelectSlidePreviewMusicVolume].AddValues(new string[] { "0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100" }); + SelectSlides[SelectSlidePreviewMusicVolume].AddValues(new[] + {"0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"}); SelectSlides[SelectSlidePreviewMusicVolume].Selection = CConfig.PreviewMusicVolume / 5; - SelectSlides[SelectSlideGameMusicVolume].AddValues(new string[] { "0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100" }); + SelectSlides[SelectSlideGameMusicVolume].AddValues(new[] + {"0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"}); SelectSlides[SelectSlideGameMusicVolume].Selection = CConfig.GameMusicVolume / 5; - } public override bool HandleInput(KeyEvent KeyEvent) { base.HandleInput(KeyEvent); - if (KeyEvent.KeyPressed) - { - - } + if (KeyEvent.KeyPressed) {} else { switch (KeyEvent.Key) @@ -76,7 +74,7 @@ namespace Vocaluxe.Screens { SaveConfig(); CGraphics.FadeTo(EScreens.ScreenOptions); - } + } break; case Keys.Left: @@ -104,9 +102,7 @@ namespace Vocaluxe.Screens { SaveConfig(); if (Buttons[ButtonExit].Selected) - { CGraphics.FadeTo(EScreens.ScreenOptions); - } } return true; } @@ -114,9 +110,7 @@ namespace Vocaluxe.Screens public override bool UpdateGame() { if (_BackgroundMusicVolume != CConfig.BackgroundMusicVolume) - { SelectSlides[SelectSlideBackgroundMusicVolume].Selection = CConfig.BackgroundMusicVolume / 5; - } return true; } @@ -135,6 +129,7 @@ namespace Vocaluxe.Screens SelectSlides[SelectSlideGameMusicVolume].Selection = CConfig.GameMusicVolume / 5; SelectSlides[SelectSlidePreviewMusicVolume].Selection = CConfig.PreviewMusicVolume / 5; } + private void SaveConfig() { CConfig.GameMusicVolume = SelectSlides[SelectSlideGameMusicVolume].Selection * 5; @@ -148,4 +143,4 @@ namespace Vocaluxe.Screens CBackgroundMusic.CheckAndApplyConfig(NewOffOn, NewSource, NewVolume); } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenOptionsTheme.cs b/Vocaluxe/Screens/CScreenOptionsTheme.cs index 132ff01a..61258873 100644 --- a/Vocaluxe/Screens/CScreenOptionsTheme.cs +++ b/Vocaluxe/Screens/CScreenOptionsTheme.cs @@ -1,6 +1,5 @@ using System; using System.Windows.Forms; - using Vocaluxe.Base; using VocaluxeLib.Menu; @@ -9,7 +8,10 @@ namespace Vocaluxe.Screens class CScreenOptionsTheme : CMenu { // Version number for theme files. Increment it, if you've changed something on the theme files! - protected override int _ScreenVersion { get { return 3; } } + protected override int _ScreenVersion + { + get { return 3; } + } private const string SelectSlideTheme = "SelectSlideTheme"; private const string SelectSlideSkin = "SelectSlideSkin"; @@ -28,25 +30,22 @@ namespace Vocaluxe.Screens private int _TempSkin; - public CScreenOptionsTheme() - { - } - public override void Init() { base.Init(); - _ThemeButtons = new string[] { ButtonExit }; - _ThemeSelectSlides = new string[] { - SelectSlideTheme, - SelectSlideSkin, - SelectSlideCover, - SelectSlideNoteLines, - SelectSlideToneHelper, - SelectSlideTimerLook, - SelectSlideFadeInfo, - SelectSlideCoverLoading - }; + _ThemeButtons = new[] {ButtonExit}; + _ThemeSelectSlides = new[] + { + SelectSlideTheme, + SelectSlideSkin, + SelectSlideCover, + SelectSlideNoteLines, + SelectSlideToneHelper, + SelectSlideTimerLook, + SelectSlideFadeInfo, + SelectSlideCoverLoading + }; } public override void LoadTheme(string XmlPath) @@ -72,10 +71,7 @@ namespace Vocaluxe.Screens { base.HandleInput(KeyEvent); - if (KeyEvent.KeyPressed) - { - - } + if (KeyEvent.KeyPressed) {} else { switch (KeyEvent.Key) @@ -92,9 +88,7 @@ namespace Vocaluxe.Screens case Keys.Enter: if (Buttons[ButtonExit].Selected) - { Close(); - } break; case Keys.Left: @@ -114,16 +108,12 @@ namespace Vocaluxe.Screens base.HandleMouse(MouseEvent); if (MouseEvent.RB) - { Close(); - } if (MouseEvent.LB && IsMouseOver(MouseEvent)) { if (Buttons[ButtonExit].Selected) - { Close(); - } else OnChange(); } @@ -212,7 +202,7 @@ namespace Vocaluxe.Screens CConfig.Skin = CTheme.SkinNames[0]; _OldSkin = 0; _TempSkin = _OldSkin; - + CConfig.SaveConfig(); CTheme.LoadSkins(); @@ -240,4 +230,4 @@ namespace Vocaluxe.Screens _Active = true; } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenOptionsVideo.cs b/Vocaluxe/Screens/CScreenOptionsVideo.cs index c226ad07..bf65cd58 100644 --- a/Vocaluxe/Screens/CScreenOptionsVideo.cs +++ b/Vocaluxe/Screens/CScreenOptionsVideo.cs @@ -9,7 +9,10 @@ namespace Vocaluxe.Screens class CScreenOptionsVideo : CMenu { // Version number for theme files. Increment it, if you've changed something on the theme files! - protected override int _ScreenVersion { get { return 3; } } + protected override int _ScreenVersion + { + get { return 3; } + } private const string SelectSlideVideoBackgrounds = "SelectSlideVideoBackgrounds"; private const string SelectSlideVideoPreview = "SelectSlideVideoPreview"; @@ -23,21 +26,21 @@ namespace Vocaluxe.Screens private const string ButtonExit = "ButtonExit"; private SWebcamConfig _Config; - STexture _WebcamTexture = new STexture(-1); + private STexture _WebcamTexture = new STexture(-1); private int _DeviceNr; private int _CapabilityNr; - public CScreenOptionsVideo() - { - } - public override void Init() { base.Init(); - _ThemeStatics = new string[] { StaticWebcamOutput }; - _ThemeButtons = new string[] { ButtonExit }; - _ThemeSelectSlides = new string[] { SelectSlideVideoBackgrounds, SelectSlideVideoPreview, SelectSlideVideosInSongs, SelectSlideVideosToBackground, SelectSlideWebcamDevices, SelectSlideWebcamCapabilities }; + _ThemeStatics = new[] {StaticWebcamOutput}; + _ThemeButtons = new[] {ButtonExit}; + _ThemeSelectSlides = new[] + { + SelectSlideVideoBackgrounds, SelectSlideVideoPreview, SelectSlideVideosInSongs, SelectSlideVideosToBackground, SelectSlideWebcamDevices, + SelectSlideWebcamCapabilities + }; } public override void LoadTheme(string XmlPath) @@ -54,10 +57,7 @@ namespace Vocaluxe.Screens { base.HandleInput(KeyEvent); - if (KeyEvent.KeyPressed) - { - - } + if (KeyEvent.KeyPressed) {} else { switch (KeyEvent.Key) @@ -119,9 +119,7 @@ namespace Vocaluxe.Screens OnCapabilitiesEvent(); SaveConfig(); if (Buttons[ButtonExit].Selected) - { CGraphics.FadeTo(EScreens.ScreenOptions); - } } return true; } @@ -137,7 +135,7 @@ namespace Vocaluxe.Screens public override bool Draw() { base.Draw(); - + return true; } @@ -169,15 +167,11 @@ namespace Vocaluxe.Screens GetFirstConfiguredWebcamDevice(ref _DeviceNr, ref _CapabilityNr); foreach (SWebcamDevice d in devices) - { SelectSlides[SelectSlideWebcamDevices].AddValue(d.Name); - } SelectSlides[SelectSlideWebcamDevices].Selection = _DeviceNr; foreach (SCapabilities c in devices[_DeviceNr].Capabilities) - { SelectSlides[SelectSlideWebcamCapabilities].AddValue(c.Width.ToString() + " x " + c.Height.ToString() + " @ " + c.Framerate.ToString() + " FPS "); - } _Config.MonikerString = devices[SelectSlides[SelectSlideWebcamDevices].Selection].MonikerString; _Config.Width = devices[SelectSlides[SelectSlideWebcamDevices].Selection].Capabilities[SelectSlides[SelectSlideWebcamCapabilities].Selection].Width; _Config.Height = devices[SelectSlides[SelectSlideWebcamDevices].Selection].Capabilities[SelectSlides[SelectSlideWebcamCapabilities].Selection].Height; @@ -193,7 +187,7 @@ namespace Vocaluxe.Screens CLog.LogError("Error on listing webcam capabilities: " + e.Message); devices = null; } - + SelectSlides[SelectSlideWebcamDevices].Visible = (devices != null && devices.Length > 0); SelectSlides[SelectSlideWebcamCapabilities].Visible = (devices != null && devices.Length > 0); Statics[StaticWebcamOutput].Visible = (devices != null && devices.Length > 0); @@ -223,7 +217,8 @@ namespace Vocaluxe.Screens SWebcamDevice[] d = CWebcam.GetDevices(); for (int i = 0; i < d[SelectSlides[SelectSlideWebcamDevices].Selection].Capabilities.Count; i++) { - SelectSlides[SelectSlideWebcamCapabilities].AddValue(d[_DeviceNr].Capabilities[i].Width.ToString() + " x " + d[_DeviceNr].Capabilities[i].Height.ToString() + " @ " + d[_DeviceNr].Capabilities[i].Framerate.ToString() + "FPS"); + SelectSlides[SelectSlideWebcamCapabilities].AddValue(d[_DeviceNr].Capabilities[i].Width.ToString() + " x " + d[_DeviceNr].Capabilities[i].Height.ToString() + + " @ " + d[_DeviceNr].Capabilities[i].Framerate.ToString() + "FPS"); } SelectSlides[SelectSlideWebcamCapabilities].Selection = 0; @@ -269,7 +264,8 @@ namespace Vocaluxe.Screens { for (int j = 0; j < devices[i].Capabilities.Count; j++) { - if (devices[i].Capabilities[j].Framerate == CConfig.WebcamConfig.Framerate && devices[i].Capabilities[j].Width == CConfig.WebcamConfig.Width && devices[i].Capabilities[j].Height == CConfig.WebcamConfig.Height) + if (devices[i].Capabilities[j].Framerate == CConfig.WebcamConfig.Framerate && devices[i].Capabilities[j].Width == CConfig.WebcamConfig.Width && + devices[i].Capabilities[j].Height == CConfig.WebcamConfig.Height) { Device = i; Capabilities = j; @@ -280,4 +276,4 @@ namespace Vocaluxe.Screens } } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenParty.cs b/Vocaluxe/Screens/CScreenParty.cs index f2188bee..2e6eba2b 100644 --- a/Vocaluxe/Screens/CScreenParty.cs +++ b/Vocaluxe/Screens/CScreenParty.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using System.Windows.Forms; - using Vocaluxe.Base; using VocaluxeLib.Menu; @@ -9,32 +8,31 @@ namespace Vocaluxe.Screens class CScreenParty : CMenu { // Version number for theme files. Increment it, if you've changed something on the theme files! - protected override int _ScreenVersion { get { return 1; } } + protected override int _ScreenVersion + { + get { return 1; } + } - const string TextDescription = "TextDescription"; - const string TextTargetAudience = "TextTargetAudience"; - const string TextNumTeams = "TextNumTeams"; - const string TextNumPlayers = "TextNumPlayers"; - const string TextAuthor = "TextAuthor"; - const string TextVersion = "TextVersion"; - const string TextError = "TextError"; - const string ButtonStart = "ButtonStart"; - const string ButtonExit = "ButtonExit"; - const string SelectSlideModes = "SelectSlideModes"; + private const string TextDescription = "TextDescription"; + private const string TextTargetAudience = "TextTargetAudience"; + private const string TextNumTeams = "TextNumTeams"; + private const string TextNumPlayers = "TextNumPlayers"; + private const string TextAuthor = "TextAuthor"; + private const string TextVersion = "TextVersion"; + private const string TextError = "TextError"; + private const string ButtonStart = "ButtonStart"; + private const string ButtonExit = "ButtonExit"; + private const string SelectSlideModes = "SelectSlideModes"; private List _PartyModeInfos; - public CScreenParty() - { - } - public override void Init() { base.Init(); - _ThemeTexts = new string[] { TextDescription, TextTargetAudience, TextNumTeams, TextNumPlayers, TextAuthor, TextVersion, TextError }; - _ThemeButtons = new string[] { ButtonStart, ButtonExit }; - _ThemeSelectSlides = new string[] { SelectSlideModes }; + _ThemeTexts = new[] {TextDescription, TextTargetAudience, TextNumTeams, TextNumPlayers, TextAuthor, TextVersion, TextError}; + _ThemeButtons = new[] {ButtonStart, ButtonExit}; + _ThemeSelectSlides = new[] {SelectSlideModes}; } public override void LoadTheme(string XmlPath) @@ -46,10 +44,7 @@ namespace Vocaluxe.Screens { base.HandleInput(KeyEvent); - if (KeyEvent.KeyPressed) - { - - } + if (KeyEvent.KeyPressed) {} else { switch (KeyEvent.Key) @@ -73,7 +68,7 @@ namespace Vocaluxe.Screens UpdateSelection(); break; } - } + } return true; } @@ -94,10 +89,8 @@ namespace Vocaluxe.Screens } if (MouseEvent.RB) - { CGraphics.FadeTo(EScreens.ScreenMain); - } - + return true; } @@ -109,9 +102,7 @@ namespace Vocaluxe.Screens SelectSlides[SelectSlideModes].Clear(); foreach (SPartyModeInfos info in _PartyModeInfos) - { SelectSlides[SelectSlideModes].AddValue(info.Name, info.PartyModeID); - } SelectSlides[SelectSlideModes].Selection = 0; UpdateSelection(); @@ -201,4 +192,4 @@ namespace Vocaluxe.Screens //TODO: else Message! } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenProfiles.cs b/Vocaluxe/Screens/CScreenProfiles.cs index fc583134..ee29716f 100644 --- a/Vocaluxe/Screens/CScreenProfiles.cs +++ b/Vocaluxe/Screens/CScreenProfiles.cs @@ -1,5 +1,6 @@ using System; using System.Drawing; +using System.Drawing.Imaging; using System.IO; using System.Windows.Forms; using Vocaluxe.Base; @@ -16,7 +17,10 @@ namespace Vocaluxe.Screens class CScreenProfiles : CMenu { // Version number for theme files. Increment it, if you've changed something on the theme files! - protected override int _ScreenVersion { get { return 2; } } + protected override int _ScreenVersion + { + get { return 2; } + } private const string SelectSlideProfiles = "SelectSlideProfiles"; private const string SelectSlideDifficulty = "SelectSlideDifficulty"; @@ -38,19 +42,15 @@ namespace Vocaluxe.Screens private EEditMode _EditMode; private STexture _WebcamTexture = new STexture(-1); - private Bitmap _Snapshot = null; - - public CScreenProfiles() - { - } + private Bitmap _Snapshot; public override void Init() { base.Init(); - _ThemeButtons = new string[] { ButtonPlayerName, ButtonExit, ButtonSave, ButtonNew, ButtonDelete, ButtonWebcam, ButtonSaveSnapshot, ButtonDiscardSnapshot, ButtonTakeSnapshot }; - _ThemeSelectSlides = new string[] { SelectSlideProfiles, SelectSlideDifficulty, SelectSlideAvatars, SelectSlideGuestProfile, SelectSlideActive }; - _ThemeStatics = new string[] { StaticAvatar }; + _ThemeButtons = new[] {ButtonPlayerName, ButtonExit, ButtonSave, ButtonNew, ButtonDelete, ButtonWebcam, ButtonSaveSnapshot, ButtonDiscardSnapshot, ButtonTakeSnapshot}; + _ThemeSelectSlides = new[] {SelectSlideProfiles, SelectSlideDifficulty, SelectSlideAvatars, SelectSlideGuestProfile, SelectSlideActive}; + _ThemeStatics = new[] {StaticAvatar}; _EditMode = EEditMode.None; } @@ -69,7 +69,6 @@ namespace Vocaluxe.Screens SelectSlides[SelectSlideDifficulty].SetValues(0); SelectSlides[SelectSlideGuestProfile].SetValues(0); SelectSlides[SelectSlideActive].SetValues(0); - } public override bool HandleInput(KeyEvent KeyEvent) @@ -96,39 +95,31 @@ namespace Vocaluxe.Screens case Keys.Escape: CGraphics.FadeTo(EScreens.ScreenMain); break; - + case Keys.Enter: if (Buttons[ButtonExit].Selected) - { CGraphics.FadeTo(EScreens.ScreenMain); - } else if (Buttons[ButtonSave].Selected) - { + else if (Buttons[ButtonSave].Selected) SaveProfiles(); - } else if (Buttons[ButtonNew].Selected) - { + else if (Buttons[ButtonNew].Selected) NewProfile(); - } else if (Buttons[ButtonPlayerName].Selected) + else if (Buttons[ButtonPlayerName].Selected) { if (CProfiles.NumProfiles > 0 && _EditMode != EEditMode.PlayerName) _EditMode = EEditMode.PlayerName; else _EditMode = EEditMode.None; - } else if (Buttons[ButtonDelete].Selected) - { - DeleteProfile(); - } else if (Buttons[ButtonWebcam].Selected && CWebcam.GetDevices().Length > 0) - { - OnWebcam(); - } else if (Buttons[ButtonSaveSnapshot].Selected && CWebcam.GetDevices().Length > 0) - { - OnSaveSnapshot(); - } else if (Buttons[ButtonDiscardSnapshot].Selected && CWebcam.GetDevices().Length > 0) - { - OnDiscardSnapshot(); - } else if (Buttons[ButtonTakeSnapshot].Selected && CWebcam.GetDevices().Length > 0) - { - OnTakeSnapshot(); } + else if (Buttons[ButtonDelete].Selected) + DeleteProfile(); + else if (Buttons[ButtonWebcam].Selected && CWebcam.GetDevices().Length > 0) + OnWebcam(); + else if (Buttons[ButtonSaveSnapshot].Selected && CWebcam.GetDevices().Length > 0) + OnSaveSnapshot(); + else if (Buttons[ButtonDiscardSnapshot].Selected && CWebcam.GetDevices().Length > 0) + OnDiscardSnapshot(); + else if (Buttons[ButtonTakeSnapshot].Selected && CWebcam.GetDevices().Length > 0) + OnTakeSnapshot(); break; case Keys.Back: @@ -148,19 +139,22 @@ namespace Vocaluxe.Screens if (SelectSlides[SelectSlideDifficulty].Selected) { CProfiles.SetDifficulty(SelectSlides[SelectSlideProfiles].Selection, - (EGameDifficulty)SelectSlides[SelectSlideDifficulty].Selection); - } else if (SelectSlides[SelectSlideAvatars].Selected) + (EGameDifficulty)SelectSlides[SelectSlideDifficulty].Selection); + } + else if (SelectSlides[SelectSlideAvatars].Selected) { CProfiles.SetAvatar(SelectSlides[SelectSlideProfiles].Selection, - SelectSlides[SelectSlideAvatars].Selection); - } else if (SelectSlides[SelectSlideGuestProfile].Selected) + SelectSlides[SelectSlideAvatars].Selection); + } + else if (SelectSlides[SelectSlideGuestProfile].Selected) { CProfiles.SetGuestProfile(SelectSlides[SelectSlideProfiles].Selection, - (EOffOn)SelectSlides[SelectSlideGuestProfile].Selection); - } else if (SelectSlides[SelectSlideActive].Selected) + (EOffOn)SelectSlides[SelectSlideGuestProfile].Selection); + } + else if (SelectSlides[SelectSlideActive].Selected) { CProfiles.SetActive(SelectSlides[SelectSlideProfiles].Selection, - (EOffOn)SelectSlides[SelectSlideActive].Selection); + (EOffOn)SelectSlides[SelectSlideActive].Selection); } } @@ -175,59 +169,54 @@ namespace Vocaluxe.Screens if (MouseEvent.LB && IsMouseOver(MouseEvent)) { if (Buttons[ButtonExit].Selected) - { CGraphics.FadeTo(EScreens.ScreenMain); - } else if (Buttons[ButtonSave].Selected) - { + else if (Buttons[ButtonSave].Selected) SaveProfiles(); - } else if (Buttons[ButtonNew].Selected) - { + else if (Buttons[ButtonNew].Selected) NewProfile(); - } else if (Buttons[ButtonDelete].Selected) { + else if (Buttons[ButtonDelete].Selected) DeleteProfile(); - } else if (Buttons[ButtonPlayerName].Selected) + else if (Buttons[ButtonPlayerName].Selected) { if (CProfiles.NumProfiles > 0 && _EditMode != EEditMode.PlayerName) _EditMode = EEditMode.PlayerName; else _EditMode = EEditMode.None; - } else if (SelectSlides[SelectSlideDifficulty].Selected) + } + else if (SelectSlides[SelectSlideDifficulty].Selected) { CProfiles.SetDifficulty(SelectSlides[SelectSlideProfiles].Selection, - (EGameDifficulty)SelectSlides[SelectSlideDifficulty].Selection); - } else if (SelectSlides[SelectSlideAvatars].Selected) + (EGameDifficulty)SelectSlides[SelectSlideDifficulty].Selection); + } + else if (SelectSlides[SelectSlideAvatars].Selected) { CProfiles.SetAvatar(SelectSlides[SelectSlideProfiles].Selection, - SelectSlides[SelectSlideAvatars].Selection); + SelectSlides[SelectSlideAvatars].Selection); if (CWebcam.GetDevices().Length > 0 && _WebcamTexture.index > 0) OnDiscardSnapshot(); - } else if (SelectSlides[SelectSlideGuestProfile].Selected) + } + else if (SelectSlides[SelectSlideGuestProfile].Selected) { CProfiles.SetGuestProfile(SelectSlides[SelectSlideProfiles].Selection, - (EOffOn)SelectSlides[SelectSlideGuestProfile].Selection); - } else if (SelectSlides[SelectSlideActive].Selected) + (EOffOn)SelectSlides[SelectSlideGuestProfile].Selection); + } + else if (SelectSlides[SelectSlideActive].Selected) { CProfiles.SetActive(SelectSlides[SelectSlideProfiles].Selection, - (EOffOn)SelectSlides[SelectSlideActive].Selection); - } else if (Buttons[ButtonWebcam].Selected && CWebcam.GetDevices().Length > 0) - { - OnWebcam(); - } else if (Buttons[ButtonSaveSnapshot].Selected && CWebcam.GetDevices().Length > 0) - { - OnSaveSnapshot(); - } else if (Buttons[ButtonDiscardSnapshot].Selected && CWebcam.GetDevices().Length > 0) - { - OnDiscardSnapshot(); - } else if (Buttons[ButtonTakeSnapshot].Selected && CWebcam.GetDevices().Length > 0) - { - OnTakeSnapshot(); + (EOffOn)SelectSlides[SelectSlideActive].Selection); } + else if (Buttons[ButtonWebcam].Selected && CWebcam.GetDevices().Length > 0) + OnWebcam(); + else if (Buttons[ButtonSaveSnapshot].Selected && CWebcam.GetDevices().Length > 0) + OnSaveSnapshot(); + else if (Buttons[ButtonDiscardSnapshot].Selected && CWebcam.GetDevices().Length > 0) + OnDiscardSnapshot(); + else if (Buttons[ButtonTakeSnapshot].Selected && CWebcam.GetDevices().Length > 0) + OnTakeSnapshot(); } if (MouseEvent.RB) - { CGraphics.FadeTo(EScreens.ScreenMain); - } return true; } @@ -256,10 +245,8 @@ namespace Vocaluxe.Screens string filename = "snapshot"; int i = 0; while (File.Exists(Path.Combine(CSettings.sFolderProfiles, filename + i + ".png"))) - { i++; - } - _Snapshot.Save(Path.Combine(CSettings.sFolderProfiles, filename + i + ".png"), System.Drawing.Imaging.ImageFormat.Png); + _Snapshot.Save(Path.Combine(CSettings.sFolderProfiles, filename + i + ".png"), ImageFormat.Png); CProfiles.LoadAvatars(); LoadAvatars(); _Snapshot = null; @@ -273,7 +260,6 @@ namespace Vocaluxe.Screens CProfiles.SetAvatar(SelectSlides[SelectSlideProfiles].Selection, j); break; } - } Buttons[ButtonSaveSnapshot].Visible = false; @@ -309,7 +295,7 @@ namespace Vocaluxe.Screens SelectSlides[SelectSlideAvatars].Selection = avatarNr; if (CWebcam.GetDevices().Length > 0 && _WebcamTexture.index > 0) { - if(_Snapshot == null) + if (_Snapshot == null) CWebcam.GetFrame(ref _WebcamTexture); Statics[StaticAvatar].Texture = _WebcamTexture; @@ -320,7 +306,7 @@ namespace Vocaluxe.Screens else Statics[StaticAvatar].Texture = CProfiles.Avatars[avatarNr].Texture; } - + return true; } @@ -365,11 +351,9 @@ namespace Vocaluxe.Screens { _EditMode = EEditMode.None; SelectSlides[SelectSlideProfiles].Clear(); - + for (int i = 0; i < CProfiles.NumProfiles; i++) - { SelectSlides[SelectSlideProfiles].AddValue(CProfiles.GetPlayerName(i)); - } if (CProfiles.NumProfiles > 0 && CProfiles.NumAvatars > 0) { @@ -384,9 +368,7 @@ namespace Vocaluxe.Screens { SelectSlides[SelectSlideAvatars].Clear(); for (int i = 0; i < CProfiles.NumAvatars; i++) - { SelectSlides[SelectSlideAvatars].AddValue(CProfiles.Avatars[i].FileName); - } } private void NewProfile() @@ -395,12 +377,12 @@ namespace Vocaluxe.Screens CProfiles.NewProfile(); LoadProfiles(); SelectSlides[SelectSlideProfiles].LastValue(); - + CProfiles.SetAvatar(SelectSlides[SelectSlideProfiles].Selection, - SelectSlides[SelectSlideAvatars].Selection); + SelectSlides[SelectSlideAvatars].Selection); SetInteractionToButton(Buttons[ButtonPlayerName]); _EditMode = EEditMode.PlayerName; - } + } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenScore.cs b/Vocaluxe/Screens/CScreenScore.cs index 7f5dcc3a..409e99ef 100644 --- a/Vocaluxe/Screens/CScreenScore.cs +++ b/Vocaluxe/Screens/CScreenScore.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Diagnostics; using System.Windows.Forms; - using Vocaluxe.Base; using VocaluxeLib.Menu; using VocaluxeLib.Menu.SongMenu; @@ -12,7 +11,10 @@ namespace Vocaluxe.Screens class CScreenScore : CMenu { // Version number for theme files. Increment it, if you've changed something on the theme files! - protected override int _ScreenVersion { get { return 3; } } + protected override int _ScreenVersion + { + get { return 3; } + } private const string TextSong = "TextSong"; @@ -33,10 +35,6 @@ namespace Vocaluxe.Screens private CPoints _Points; private Stopwatch timer; - public CScreenScore() - { - } - public override void Init() { base.Init(); @@ -53,16 +51,14 @@ namespace Vocaluxe.Screens _ThemeStatics = statics.ToArray(); - _ThemeScreenSettings = new string[] { ScreenSettingShortScore, ScreenSettingShortRating, ScreenSettingShortDifficulty, ScreenSettingAnimationDirection }; + _ThemeScreenSettings = new[] {ScreenSettingShortScore, ScreenSettingShortRating, ScreenSettingShortDifficulty, ScreenSettingAnimationDirection}; StaticPointsBarDrawnPoints = new double[CSettings.MaxNumPlayer]; } public override bool HandleInput(KeyEvent KeyEvent) { - if (KeyEvent.KeyPressed) - { - } + if (KeyEvent.KeyPressed) {} else { switch (KeyEvent.Key) @@ -90,19 +86,13 @@ namespace Vocaluxe.Screens base.HandleMouse(MouseEvent); if (MouseEvent.Wheel != 0) - { ChangeRound(MouseEvent.Wheel); - } if (MouseEvent.LB) - { LeaveScreen(); - } if (MouseEvent.RB) - { LeaveScreen(); - } return true; } @@ -125,19 +115,16 @@ namespace Vocaluxe.Screens SPlayer[] player = new SPlayer[CGame.NumPlayer]; if (_Round != 0) player = _Points.GetPlayer(_Round - 1, CGame.NumPlayer); - else { + else + { for (int i = 0; i < CGame.NumRounds; i++) { SPlayer[] points = _Points.GetPlayer(i, CGame.NumPlayer); for (int p = 0; p < player.Length; p++) - { player[p].Points += points[p].Points; - } } for (int p = 0; p < player.Length; p++) - { - player[p].Points = (int)(player[p].Points/CGame.NumRounds); - } + player[p].Points = (int)(player[p].Points / CGame.NumRounds); } for (int p = 0; p < player.Length; p++) { @@ -149,18 +136,20 @@ namespace Vocaluxe.Screens if (StaticPointsBarDrawnPoints[p] > player[p].Points) - { StaticPointsBarDrawnPoints[p] = player[p].Points; - } - string direction = (string) ScreenSettings[ScreenSettingAnimationDirection].GetValue(); + string direction = (string)ScreenSettings[ScreenSettingAnimationDirection].GetValue(); if (direction.ToLower() == "vertical") { - Statics[StaticPointsBar[p, CGame.NumPlayer - 1]].Rect.W = ((float)StaticPointsBarDrawnPoints[p]) * (Statics[StaticPointsBarBG[p, CGame.NumPlayer - 1]].Rect.W / 10000); + Statics[StaticPointsBar[p, CGame.NumPlayer - 1]].Rect.W = ((float)StaticPointsBarDrawnPoints[p]) * + (Statics[StaticPointsBarBG[p, CGame.NumPlayer - 1]].Rect.W / 10000); } else { - Statics[StaticPointsBar[p, CGame.NumPlayer - 1]].Rect.H = ((float)StaticPointsBarDrawnPoints[p]) * (Statics[StaticPointsBarBG[p, CGame.NumPlayer - 1]].Rect.H / 10000); - Statics[StaticPointsBar[p, CGame.NumPlayer - 1]].Rect.Y = Statics[StaticPointsBarBG[p, CGame.NumPlayer - 1]].Rect.H + Statics[StaticPointsBarBG[p, CGame.NumPlayer - 1]].Rect.Y - Statics[StaticPointsBar[p, CGame.NumPlayer - 1]].Rect.H; + Statics[StaticPointsBar[p, CGame.NumPlayer - 1]].Rect.H = ((float)StaticPointsBarDrawnPoints[p]) * + (Statics[StaticPointsBarBG[p, CGame.NumPlayer - 1]].Rect.H / 10000); + Statics[StaticPointsBar[p, CGame.NumPlayer - 1]].Rect.Y = Statics[StaticPointsBarBG[p, CGame.NumPlayer - 1]].Rect.H + + Statics[StaticPointsBarBG[p, CGame.NumPlayer - 1]].Rect.Y - + Statics[StaticPointsBar[p, CGame.NumPlayer - 1]].Rect.H; } } } @@ -184,43 +173,29 @@ namespace Vocaluxe.Screens rating = "TR_RATING_VOCAL_HERO"; } else if (points < 9800 && points >= 8400) - { rating = "TR_RATING_SUPERSTAR"; - } else if (points < 8400 && points >= 7000) - { rating = "TR_RATING_LEAD_SINGER"; - } else if (points < 7000 && points >= 5600) - { rating = "TR_RATING_RISING_STAR"; - } else if (points < 5600 && points >= 4200) - { rating = "TR_RATING_HOPEFUL"; - } else if (points < 4200 && points >= 2800) - { rating = "TR_RATING_WANNABE"; - } else if (points < 2800 && points >= 1400) - { rating = "TR_RATING_AMATEUR"; - } else if (points < 1400) - { rating = "TR_RATING_TONE_DEAF"; - } return rating; } private void BuildTextStrings(ref List texts) { - TextNames = new string[CSettings.MaxNumPlayer, CSettings.MaxNumPlayer]; - TextScores = new string[CSettings.MaxNumPlayer, CSettings.MaxNumPlayer]; - TextRatings = new string[CSettings.MaxNumPlayer, CSettings.MaxNumPlayer]; - TextDifficulty = new string[CSettings.MaxNumPlayer, CSettings.MaxNumPlayer]; + TextNames = new string[CSettings.MaxNumPlayer,CSettings.MaxNumPlayer]; + TextScores = new string[CSettings.MaxNumPlayer,CSettings.MaxNumPlayer]; + TextRatings = new string[CSettings.MaxNumPlayer,CSettings.MaxNumPlayer]; + TextDifficulty = new string[CSettings.MaxNumPlayer,CSettings.MaxNumPlayer]; for (int numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) { @@ -245,9 +220,9 @@ namespace Vocaluxe.Screens private void BuildStaticStrings(ref List statics) { - StaticPointsBar = new string[CSettings.MaxNumPlayer, CSettings.MaxNumPlayer]; - StaticPointsBarBG = new string[CSettings.MaxNumPlayer, CSettings.MaxNumPlayer]; - StaticAvatar = new string[CSettings.MaxNumPlayer, CSettings.MaxNumPlayer]; + StaticPointsBar = new string[CSettings.MaxNumPlayer,CSettings.MaxNumPlayer]; + StaticPointsBarBG = new string[CSettings.MaxNumPlayer,CSettings.MaxNumPlayer]; + StaticAvatar = new string[CSettings.MaxNumPlayer,CSettings.MaxNumPlayer]; for (int numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) { @@ -263,7 +238,6 @@ namespace Vocaluxe.Screens statics.Add(StaticPointsBarBG[player, numplayer]); statics.Add(StaticPointsBar[player, numplayer]); statics.Add(StaticAvatar[player, numplayer]); - } } } @@ -281,12 +255,10 @@ namespace Vocaluxe.Screens Texts[TextSong].Text = song.Artist + " - " + song.Title; if (_Points.NumRounds > 1) - { Texts[TextSong].Text += " (" + _Round + "/" + _Points.NumRounds + ")"; - } player = _Points.GetPlayer(_Round - 1, CGame.NumPlayer); } - else + else { Texts[TextSong].Text = "TR_SCREENSCORE_OVERALLSCORE"; for (int i = 0; i < CGame.NumRounds; i++) @@ -304,9 +276,7 @@ namespace Vocaluxe.Screens } } for (int p = 0; p < player.Length; p++) - { player[p].Points = (int)Math.Round((player[p].Points / CGame.NumRounds)); - } } for (int p = 0; p < player.Length; p++) @@ -315,13 +285,12 @@ namespace Vocaluxe.Screens { if (!song.IsDuet) Texts[TextNames[p, CGame.NumPlayer - 1]].Text = player[p].Name; + else if (player[p].LineNr == 0 && song.DuetPart1 != "Part 1") + Texts[TextNames[p, CGame.NumPlayer - 1]].Text = player[p].Name + " (" + song.DuetPart1 + ")"; + else if (player[p].LineNr == 1 && song.DuetPart2 != "Part 2") + Texts[TextNames[p, CGame.NumPlayer - 1]].Text = player[p].Name + " (" + song.DuetPart2 + ")"; else - if (player[p].LineNr == 0 && song.DuetPart1 != "Part 1") - Texts[TextNames[p, CGame.NumPlayer - 1]].Text = player[p].Name + " (" + song.DuetPart1 + ")"; - else if (player[p].LineNr == 1 && song.DuetPart2 != "Part 2") - Texts[TextNames[p, CGame.NumPlayer - 1]].Text = player[p].Name + " (" + song.DuetPart2 + ")"; - else - Texts[TextNames[p, CGame.NumPlayer - 1]].Text = player[p].Name; + Texts[TextNames[p, CGame.NumPlayer - 1]].Text = player[p].Name; } else Texts[TextNames[p, CGame.NumPlayer - 1]].Text = player[p].Name; @@ -331,24 +300,30 @@ namespace Vocaluxe.Screens else Texts[TextScores[p, CGame.NumPlayer - 1]].Text = ((int)Math.Round(player[p].Points)).ToString("0000"); if (CGame.NumPlayer < (int)ScreenSettings[ScreenSettingShortDifficulty].GetValue()) - Texts[TextDifficulty[p, CGame.NumPlayer - 1]].Text = CLanguage.Translate("TR_SCREENSCORE_GAMEDIFFICULTY") + ": " + CLanguage.Translate(player[p].Difficulty.ToString()); + { + Texts[TextDifficulty[p, CGame.NumPlayer - 1]].Text = CLanguage.Translate("TR_SCREENSCORE_GAMEDIFFICULTY") + ": " + + CLanguage.Translate(player[p].Difficulty.ToString()); + } else Texts[TextDifficulty[p, CGame.NumPlayer - 1]].Text = CLanguage.Translate(player[p].Difficulty.ToString()); if (CGame.NumPlayer < (int)ScreenSettings[ScreenSettingShortRating].GetValue()) - Texts[TextRatings[p, CGame.NumPlayer - 1]].Text = CLanguage.Translate("TR_SCREENSCORE_RATING") + ": " + CLanguage.Translate(GetRating((int)Math.Round(player[p].Points))); + { + Texts[TextRatings[p, CGame.NumPlayer - 1]].Text = CLanguage.Translate("TR_SCREENSCORE_RATING") + ": " + + CLanguage.Translate(GetRating((int)Math.Round(player[p].Points))); + } else Texts[TextRatings[p, CGame.NumPlayer - 1]].Text = CLanguage.Translate(GetRating((int)Math.Round(player[p].Points))); - + StaticPointsBarDrawnPoints[p] = 0.0; string direction = (string)ScreenSettings[ScreenSettingAnimationDirection].GetValue(); if (direction.ToLower() == "vertical") - { Statics[StaticPointsBar[p, CGame.NumPlayer - 1]].Rect.W = 0; - } else { Statics[StaticPointsBar[p, CGame.NumPlayer - 1]].Rect.H = 0; - Statics[StaticPointsBar[p, CGame.NumPlayer - 1]].Rect.Y = Statics[StaticPointsBarBG[p, CGame.NumPlayer - 1]].Rect.H + Statics[StaticPointsBarBG[p, CGame.NumPlayer - 1]].Rect.Y - Statics[StaticPointsBar[p, CGame.NumPlayer - 1]].Rect.H; + Statics[StaticPointsBar[p, CGame.NumPlayer - 1]].Rect.Y = Statics[StaticPointsBarBG[p, CGame.NumPlayer - 1]].Rect.H + + Statics[StaticPointsBarBG[p, CGame.NumPlayer - 1]].Rect.Y - + Statics[StaticPointsBar[p, CGame.NumPlayer - 1]].Rect.H; } if (player[p].ProfileID >= 0 && player[p].ProfileID < CProfiles.NumProfiles) Statics[StaticAvatar[p, CGame.NumPlayer - 1]].Texture = CProfiles.Profiles[player[p].ProfileID].Avatar.Texture; @@ -359,7 +334,9 @@ namespace Vocaluxe.Screens for (int p = 0; p < CGame.NumPlayer; p++) { Statics[StaticPointsBar[p, CGame.NumPlayer - 1]].Rect.H = ((float)player[p].Points) * (Statics[StaticPointsBarBG[p, CGame.NumPlayer - 1]].Rect.H / 10000); - Statics[StaticPointsBar[p, CGame.NumPlayer - 1]].Rect.Y = Statics[StaticPointsBarBG[p, CGame.NumPlayer - 1]].Rect.H + Statics[StaticPointsBarBG[p, CGame.NumPlayer - 1]].Rect.Y - Statics[StaticPointsBar[p, CGame.NumPlayer - 1]].Rect.H; + Statics[StaticPointsBar[p, CGame.NumPlayer - 1]].Rect.Y = Statics[StaticPointsBarBG[p, CGame.NumPlayer - 1]].Rect.H + + Statics[StaticPointsBarBG[p, CGame.NumPlayer - 1]].Rect.Y - + Statics[StaticPointsBar[p, CGame.NumPlayer - 1]].Rect.H; StaticPointsBarDrawnPoints[p] = player[p].Points; } } @@ -367,7 +344,7 @@ namespace Vocaluxe.Screens timer = new Stopwatch(); timer.Start(); } - + private void SetVisuability() { for (int numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) @@ -392,12 +369,12 @@ namespace Vocaluxe.Screens private void ChangeRound(int Num) { - if((_Round + Num) <= _Points.NumRounds && (_Round + Num > 0)) + if ((_Round + Num) <= _Points.NumRounds && (_Round + Num > 0)) { _Round += Num; UpdateRatings(); } - else if(Num < 0 && _Round == 1 && CGame.NumRounds > 1) + else if (Num < 0 && _Round == 1 && CGame.NumRounds > 1) { _Round = 0; UpdateRatings(); diff --git a/Vocaluxe/Screens/CScreenSing.cs b/Vocaluxe/Screens/CScreenSing.cs index 59114aa9..10c6f6ab 100644 --- a/Vocaluxe/Screens/CScreenSing.cs +++ b/Vocaluxe/Screens/CScreenSing.cs @@ -4,7 +4,6 @@ using System.Diagnostics; using System.Drawing; using System.IO; using System.Windows.Forms; - using Vocaluxe.Base; using VocaluxeLib.Menu; using VocaluxeLib.Menu.SingNotes; @@ -15,15 +14,18 @@ namespace Vocaluxe.Screens class CScreenSing : CMenu { // Version number for theme files. Increment it, if you've changed something on the theme files! - protected override int _ScreenVersion { get { return 6; } } + protected override int _ScreenVersion + { + get { return 6; } + } - struct TimeRect + private struct TimeRect { public CStatic rect; public float startBeat; public float endBeat; } - + private const string TextSongName = "TextSongName"; private const string TextTime = "TextTime"; private const string TextPause = "TextPause"; @@ -64,7 +66,7 @@ namespace Vocaluxe.Screens private SRectF _TimeLineRect; private List _TimeRects; - private bool _FadeOut = false; + private bool _FadeOut; private int _CurrentBeat; private int _CurrentStream = -1; @@ -76,15 +78,15 @@ namespace Vocaluxe.Screens private STexture _CurrentWebcamFrameTexture = new STexture(-1); private STexture _Background = new STexture(-1); - private float _CurrentTime = 0f; - private float _FinishTime = 0f; + private float _CurrentTime; + private float _FinishTime; - private float _TimeToFirstNote = 0f; - private float _RemainingTimeToFirstNote = 0f; - private float _TimeToFirstNoteDuet = 0f; - private float _RemainingTimeToFirstNoteDuet = 0f; + private float _TimeToFirstNote; + private float _RemainingTimeToFirstNote; + private float _TimeToFirstNoteDuet; + private float _RemainingTimeToFirstNoteDuet; - private int[] NoteLines = new int[CSettings.MaxNumPlayer]; + private readonly int[] NoteLines = new int[CSettings.MaxNumPlayer]; private Stopwatch _TimerSongText; private Stopwatch _TimerDuetText1; @@ -93,10 +95,6 @@ namespace Vocaluxe.Screens private bool _Pause; private bool _Webcam; - public CScreenSing() - { - } - public override void Init() { base.Init(); @@ -133,8 +131,8 @@ namespace Vocaluxe.Screens buttons.Add(ButtonSkip); _ThemeButtons = buttons.ToArray(); - _ThemeLyrics = new string[] { LyricMain, LyricSub, LyricMainDuet, LyricSubDuet, LyricMainTop, LyricSubTop }; - _ThemeSingNotes = new string[] { SingBars }; + _ThemeLyrics = new[] {LyricMain, LyricSub, LyricMainDuet, LyricSubDuet, LyricMainTop, LyricSubTop}; + _ThemeSingNotes = new[] {SingBars}; _TimeRects = new List(); _TimerSongText = new Stopwatch(); @@ -188,9 +186,7 @@ namespace Vocaluxe.Screens mode++; if (mode > Enum.GetNames(typeof(ETimerMode)).Length - 1) - { mode = 0; - } CConfig.TimerMode = (ETimerMode)mode; break; @@ -199,9 +195,7 @@ namespace Vocaluxe.Screens mode++; if (mode > Enum.GetNames(typeof(EPlayerInfo)).Length - 1) - { mode = 0; - } CConfig.PlayerInfo = (EPlayerInfo)mode; CConfig.SaveConfig(); SetVisibility(); @@ -210,9 +204,11 @@ namespace Vocaluxe.Screens break; case Keys.S: - if(CGame.NumRounds > CGame.RoundNr) - if(KeyEvent.ModCTRL) + if (CGame.NumRounds > CGame.RoundNr) + { + if (KeyEvent.ModCTRL) LoadNextSong(); + } break; case Keys.W: if (CWebcam.GetDevices().Length > 0) @@ -309,9 +305,7 @@ namespace Vocaluxe.Screens Finish = true; if (Finish) - { LoadNextSong(); - } UpdateSongText(); UpdateDuetText(); @@ -365,7 +359,7 @@ namespace Vocaluxe.Screens Lyrics[LyricMain].Alpha = Alpha[2]; Lyrics[LyricSub].Alpha = Alpha[3]; - + Statics[StaticLyrics].Alpha = Alpha[2]; Statics[StaticLyricHelper].Alpha = Alpha[2]; } @@ -375,13 +369,9 @@ namespace Vocaluxe.Screens for (int p = 0; p < CGame.NumPlayer; p++) { if (CGame.Player[p].Points < 10000) - { Texts[TextScores[p, CGame.NumPlayer - 1]].Text = CGame.Player[p].Points.ToString("0000"); - } else - { Texts[TextScores[p, CGame.NumPlayer - 1]].Text = CGame.Player[p].Points.ToString("00000"); - } } if (_CurrentVideo != -1 && !_FadeOut && CConfig.VideosInSongs == EOffOn.TR_CONFIG_ON) @@ -416,19 +406,13 @@ namespace Vocaluxe.Screens SingNotes[SingBars].Reset(); for (int i = 0; i < CSettings.MaxNumPlayer; i++) - { NoteLines[i] = -1; - } - foreach(CLyric lyric in Lyrics) - { + foreach (CLyric lyric in Lyrics) lyric.LyricStyle = CConfig.LyricStyle; - } for (int p = 0; p < CGame.NumPlayer; p++) - { Statics[StaticAvatars[p, CGame.NumPlayer - 1]].Aspect = EAspect.Crop; - } SetVisibility(); UpdateAvatars(); @@ -458,7 +442,7 @@ namespace Vocaluxe.Screens CHelper.SetRect(bounds, ref rect, rect.Width / rect.Height, _VideoAspect); CDraw.DrawTexture(_CurrentVideoTexture, new SRectF(rect.X, rect.Y, rect.Width, rect.Height, 0f), - _CurrentVideoTexture.color, new SRectF(bounds.X, bounds.Y, bounds.Width, bounds.Height, 0f), false); + _CurrentVideoTexture.color, new SRectF(bounds.X, bounds.Y, bounds.Width, bounds.Height, 0f), false); } else if (_Webcam) { @@ -467,16 +451,17 @@ namespace Vocaluxe.Screens CHelper.SetRect(bounds, ref rect, rect.Width / rect.Height, _VideoAspect); CDraw.DrawTexture(_CurrentWebcamFrameTexture, new SRectF(rect.X, rect.Y, rect.Width, rect.Height, 0f), - _CurrentVideoTexture.color, new SRectF(bounds.X, bounds.Y, bounds.Width, bounds.Height, 0f), false); + _CurrentVideoTexture.color, new SRectF(bounds.X, bounds.Y, bounds.Width, bounds.Height, 0f), false); } else - { // Draw Background + { + // Draw Background RectangleF bounds = new RectangleF(0, 0, CSettings.iRenderW, CSettings.iRenderH); RectangleF rect = new RectangleF(0f, 0f, _Background.width, _Background.height); CHelper.SetRect(bounds, ref rect, rect.Width / rect.Height, EAspect.Crop); CDraw.DrawTexture(_Background, new SRectF(rect.X, rect.Y, rect.Width, rect.Height, 0f), - _Background.color, new SRectF(bounds.X, bounds.Y, bounds.Width, bounds.Height, 0f), false); + _Background.color, new SRectF(bounds.X, bounds.Y, bounds.Width, bounds.Height, 0f), false); } } @@ -495,9 +480,7 @@ namespace Vocaluxe.Screens break; case ETimerLook.TR_CONFIG_TIMERLOOK_EXPANDED: for (int i = 0; i < _TimeRects.Count; i++) - { CDraw.DrawTexture(_TimeRects[i].rect.Texture, Statics[StaticTimeLine].Rect, _TimeRects[i].rect.Color, _TimeRects[i].rect.Rect); - } break; } @@ -512,9 +495,7 @@ namespace Vocaluxe.Screens for (int i = 0; i < CGame.NumPlayer; i++) - { SingNotes[SingBars].Draw(NoteLines[i], CGame.Player[i].SingLine, i); - } DrawLyricHelper(); @@ -611,9 +592,7 @@ namespace Vocaluxe.Screens { //Save duet-assignment before resetting for (int i = 0; i < duet_player.Length; i++) - { duet_player[i] = CGame.Player[i].LineNr; - } } CGame.ResetPlayer(); @@ -632,7 +611,7 @@ namespace Vocaluxe.Screens SingNotes[SingBars].Reset(); - + if (song.IsDuet) { Texts[TextDuetName1].Text = song.DuetPart1; @@ -652,11 +631,8 @@ namespace Vocaluxe.Screens else { for (int i = 0; i < CGame.NumPlayer; i++) - { CGame.Player[i].LineNr = duet_player[i]; - } } - } SetDuetLyricsVisibility(song.IsDuet); @@ -686,9 +662,7 @@ namespace Vocaluxe.Screens _TimerDuetText2.Reset(); if (song.Notes.Lines.Length != 2) - { _TimerSongText.Start(); - } StartSong(); } @@ -719,14 +693,14 @@ namespace Vocaluxe.Screens PrepareTimeLine(); CSound.Play(_CurrentStream); CSound.RecordStart(); - if(_Webcam) + if (_Webcam) CWebcam.Start(); } private void Stop() { //Need this to set other songs to points-var - while(!CGame.IsFinished()) + while (!CGame.IsFinished()) CGame.NextRound(); FinishedSinging(); @@ -753,10 +727,12 @@ namespace Vocaluxe.Screens if (FirstNoteTime <= CurrentTime + 10f) { //First line has no predecessor or line has to be shown - if(j == 0 || FirstNoteTime - CConfig.MinLineBreakTime <= CurrentTime) return j; - float LastNoteTime = CGame.GetTimeFromBeats(line[j-1].LastNoteBeat, song.BPM); + if (j == 0 || FirstNoteTime - CConfig.MinLineBreakTime <= CurrentTime) + return j; + float LastNoteTime = CGame.GetTimeFromBeats(line[j - 1].LastNoteBeat, song.BPM); //No line break if last line is not fully evaluated (with 50% tolerance -> tested so notes are drawn) - if(LastNoteTime + CConfig.MicDelay/1000f * 1.5f >= CurrentTime) return j-1; + if (LastNoteTime + CConfig.MicDelay / 1000f * 1.5f >= CurrentTime) + return j - 1; return j; } } @@ -856,8 +832,9 @@ namespace Vocaluxe.Screens Buttons[ButtonSkip].Visible = true; else Buttons[ButtonSkip].Visible = false; - CSound.Pause(_CurrentStream); - }else + CSound.Pause(_CurrentStream); + } + else { Buttons[ButtonCancel].Visible = false; Buttons[ButtonContinue].Visible = false; @@ -869,8 +846,8 @@ namespace Vocaluxe.Screens private void BuildTextStrings(ref List texts) { - TextScores = new string[CSettings.MaxNumPlayer, CSettings.MaxNumPlayer]; - TextNames = new string[CSettings.MaxNumPlayer, CSettings.MaxNumPlayer]; + TextScores = new string[CSettings.MaxNumPlayer,CSettings.MaxNumPlayer]; + TextNames = new string[CSettings.MaxNumPlayer,CSettings.MaxNumPlayer]; for (int numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) { @@ -891,8 +868,8 @@ namespace Vocaluxe.Screens private void BuildStaticStrings(ref List statics) { - StaticScores = new string[CSettings.MaxNumPlayer, CSettings.MaxNumPlayer]; - StaticAvatars = new string[CSettings.MaxNumPlayer, CSettings.MaxNumPlayer]; + StaticScores = new string[CSettings.MaxNumPlayer,CSettings.MaxNumPlayer]; + StaticAvatars = new string[CSettings.MaxNumPlayer,CSettings.MaxNumPlayer]; for (int numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) { @@ -933,10 +910,14 @@ namespace Vocaluxe.Screens { Texts[TextScores[player, numplayer]].Visible = (numplayer + 1 == CGame.NumPlayer); Texts[TextNames[player, numplayer]].Visible = ((numplayer + 1 == CGame.NumPlayer) - && (CConfig.PlayerInfo == EPlayerInfo.TR_CONFIG_PLAYERINFO_BOTH || CConfig.PlayerInfo == EPlayerInfo.TR_CONFIG_PLAYERINFO_NAME)); + && + (CConfig.PlayerInfo == EPlayerInfo.TR_CONFIG_PLAYERINFO_BOTH || + CConfig.PlayerInfo == EPlayerInfo.TR_CONFIG_PLAYERINFO_NAME)); Statics[StaticScores[player, numplayer]].Visible = (numplayer + 1 == CGame.NumPlayer); Statics[StaticAvatars[player, numplayer]].Visible = ((numplayer + 1 == CGame.NumPlayer) - && (CConfig.PlayerInfo == EPlayerInfo.TR_CONFIG_PLAYERINFO_BOTH || CConfig.PlayerInfo == EPlayerInfo.TR_CONFIG_PLAYERINFO_AVATAR)); + && + (CConfig.PlayerInfo == EPlayerInfo.TR_CONFIG_PLAYERINFO_BOTH || + CConfig.PlayerInfo == EPlayerInfo.TR_CONFIG_PLAYERINFO_AVATAR)); } } } @@ -958,7 +939,6 @@ namespace Vocaluxe.Screens Statics[StaticLyricsDuet].Alpha = 0f; Statics[StaticLyricHelperDuet].Alpha = 0f; - } private void DrawLyricHelper() @@ -996,7 +976,7 @@ namespace Vocaluxe.Screens float distance = Lyrics[LyricMain].GetCurrentLyricPosX() - Rect.X - Rect.W; CDraw.DrawTexture(Statics[StaticLyricHelper].Texture, - new SRectF(Rect.X + distance * (1f - time / totaltime), Rect.Y, Rect.W, Rect.H, Rect.Z), Color); + new SRectF(Rect.X + distance * (1f - time / totaltime), Rect.Y, Rect.W, Rect.H, Rect.Z), Color); if (Statics[StaticLyricsTop].Visible) { @@ -1009,7 +989,7 @@ namespace Vocaluxe.Screens distance = Lyrics[LyricMainTop].GetCurrentLyricPosX() - Rect.X - Rect.W; CDraw.DrawTexture(Statics[StaticLyricHelperTop].Texture, - new SRectF(Rect.X + distance * (1f - time / totaltime), Rect.Y, Rect.W, Rect.H, Rect.Z), Color); + new SRectF(Rect.X + distance * (1f - time / totaltime), Rect.Y, Rect.W, Rect.H, Rect.Z), Color); } } @@ -1036,8 +1016,8 @@ namespace Vocaluxe.Screens float distance = Lyrics[LyricMainDuet].GetCurrentLyricPosX() - Rect.X - Rect.W; CDraw.DrawTexture(Statics[StaticLyricHelperDuet].Texture, - new SRectF(Rect.X + distance * (1f - time / totaltime), Rect.Y, Rect.W, Rect.H, Rect.Z), - Color); + new SRectF(Rect.X + distance * (1f - time / totaltime), Rect.Y, Rect.W, Rect.H, Rect.Z), + Color); } } } @@ -1069,9 +1049,7 @@ namespace Vocaluxe.Screens for (int j = 0; j < line.Length; j++) { if (line[j].FirstNoteBeat <= _CurrentBeat) - { CurrentLine = j; - } } // default values @@ -1085,18 +1063,16 @@ namespace Vocaluxe.Screens // => fade in float diff = CGame.GetTimeFromBeats(line[CurrentLine].FirstNoteBeat, Song.BPM) - CurrentTime; if (diff > dt) - { Alpha[i * 2] = 1f - (diff - dt) / rt; - } } else if (CurrentLine < line.Length - 1 && CGame.GetTimeFromBeats(line[CurrentLine].LastNoteBeat, Song.BPM) < CurrentTime && - CGame.GetTimeFromBeats(line[CurrentLine + 1].FirstNoteBeat, Song.BPM) > CurrentTime) + CGame.GetTimeFromBeats(line[CurrentLine + 1].FirstNoteBeat, Song.BPM) > CurrentTime) { // current position is between two lines // time between the to lines float diff = CGame.GetTimeFromBeats(line[CurrentLine + 1].FirstNoteBeat, Song.BPM) - - CGame.GetTimeFromBeats(line[CurrentLine].LastNoteBeat, Song.BPM); + CGame.GetTimeFromBeats(line[CurrentLine].LastNoteBeat, Song.BPM); // fade only if there is enough time for fading if (diff > 3.3f * dt) @@ -1135,9 +1111,7 @@ namespace Vocaluxe.Screens diff = CGame.GetTimeFromBeats(line[CurrentLineSub + 1].FirstNoteBeat, Song.BPM) - CurrentTime; if (diff > dt) - { Alpha[i * 2 + 1] = 1f - (diff - dt) / rt; - } } if (Alpha[i * 2] < 0f) @@ -1198,17 +1172,11 @@ namespace Vocaluxe.Screens Texts[TextDuetName1].Visible = true; if (t < 3f) - { Texts[TextDuetName1].Color.A = (3f - (3f - t)) / 3f; - } else if (t < 7f) - { Texts[TextDuetName1].Color.A = 1f; - } else - { Texts[TextDuetName1].Color.A = (3f - (t - 7f)) / 3f; - } } else { @@ -1219,9 +1187,7 @@ namespace Vocaluxe.Screens else if (!_TimerDuetText1.IsRunning && _TimerDuetText1.ElapsedMilliseconds == 0 && Lyrics[LyricMainDuet].Alpha > 0 && CGame.GetSong().IsDuet) _TimerDuetText1.Start(); else - { Texts[TextDuetName1].Visible = false; - } //Timer for second duet-part if (_TimerDuetText2.IsRunning) { @@ -1231,17 +1197,11 @@ namespace Vocaluxe.Screens Texts[TextDuetName2].Visible = true; if (t < 3f) - { Texts[TextDuetName2].Color.A = (3f - (3f - t)) / 3f; - } else if (t < 7f) - { Texts[TextDuetName2].Color.A = 1f; - } else - { Texts[TextDuetName2].Color.A = (3f - (t - 7f)) / 3f; - } } else { @@ -1252,9 +1212,7 @@ namespace Vocaluxe.Screens else if (!_TimerDuetText2.IsRunning && _TimerDuetText2.ElapsedMilliseconds == 0 && Lyrics[LyricMain].Alpha > 0 && CGame.GetSong().IsDuet) _TimerDuetText2.Start(); else - { Texts[TextDuetName2].Visible = false; - } } } @@ -1319,7 +1277,6 @@ namespace Vocaluxe.Screens _TimeRects[i].rect.Texture = Statics[StaticTimeLineExpandedNormal].Texture; _TimeRects[i].rect.Color = Statics[StaticTimeLineExpandedNormal].Color; } - } Statics[StaticTimePointer].Rect.X = stat.Rect.X + stat.Rect.W * (CurrentTime / TotalTime); break; @@ -1367,17 +1324,17 @@ namespace Vocaluxe.Screens trect.startBeat = Line[j].FirstNoteBeat; trect.endBeat = Line[j].EndBeat; trect.rect = GetNewStatic(new STexture(-1), - new SColorF(1f, 1f, 1f, 1f), - new SRectF(stat.Rect.X + stat.Rect.W * ((CGame.GetTimeFromBeats(trect.startBeat, song.BPM) + song.Gap - song.Start) / TotalTime), - stat.Rect.Y, - stat.Rect.W * (CGame.GetTimeFromBeats((trect.endBeat - trect.startBeat), song.BPM) / TotalTime), - stat.Rect.H, - stat.Rect.Z)); + new SColorF(1f, 1f, 1f, 1f), + new SRectF( + stat.Rect.X + stat.Rect.W * ((CGame.GetTimeFromBeats(trect.startBeat, song.BPM) + song.Gap - song.Start) / TotalTime), + stat.Rect.Y, + stat.Rect.W * (CGame.GetTimeFromBeats((trect.endBeat - trect.startBeat), song.BPM) / TotalTime), + stat.Rect.H, + stat.Rect.Z)); _TimeRects.Add(trect); } } - } break; } @@ -1388,13 +1345,9 @@ namespace Vocaluxe.Screens for (int i = 0; i < CGame.NumPlayer; i++) { if (CGame.Player[i].ProfileID > -1) - { Statics[StaticAvatars[i, CGame.NumPlayer - 1]].Texture = CProfiles.Profiles[CGame.Player[i].ProfileID].Avatar.Texture; - } else - { Statics[StaticAvatars[i, CGame.NumPlayer - 1]].Visible = false; - } } } @@ -1403,14 +1356,10 @@ namespace Vocaluxe.Screens for (int i = 0; i < CGame.NumPlayer; i++) { if (CGame.Player[i].ProfileID > -1) - { Texts[TextNames[i, CGame.NumPlayer - 1]].Text = CProfiles.Profiles[CGame.Player[i].ProfileID].PlayerName; - } else - { Texts[TextNames[i, CGame.NumPlayer - 1]].Visible = false; - } } } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenSong.cs b/Vocaluxe/Screens/CScreenSong.cs index 9e4f788d..66c19bfb 100644 --- a/Vocaluxe/Screens/CScreenSong.cs +++ b/Vocaluxe/Screens/CScreenSong.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Windows.Forms; - using Vocaluxe.Base; using VocaluxeLib.Menu; using VocaluxeLib.Menu.SongMenu; @@ -11,7 +10,7 @@ namespace Vocaluxe.Screens { class CScreenSong : CMenu { - enum ESongOptionsView + private enum ESongOptionsView { None, Song, @@ -20,7 +19,10 @@ namespace Vocaluxe.Screens } // Version number for theme files. Increment it, if you've changed something on the theme files! - protected override int _ScreenVersion { get { return 5; } } + protected override int _ScreenVersion + { + get { return 5; } + } private const string TextCategory = "TextCategory"; private const string TextSelection = "TextSelection"; @@ -52,13 +54,13 @@ namespace Vocaluxe.Screens private const string Playlist = "Playlist"; private string _SearchText = String.Empty; - private bool _SearchActive = false; + private bool _SearchActive; private readonly List ButtonsJoker = new List(); - private List TextsPlayer = new List(); - private bool _SongOptionsActive = false; - private bool _PlaylistActive = false; - private List _AvailableGameModes; + private readonly List TextsPlayer = new List(); + private bool _SongOptionsActive; + private bool _PlaylistActive; + private readonly List _AvailableGameModes; private ScreenSongOptions _sso; private CStatic DragAndDropCover; @@ -80,9 +82,7 @@ namespace Vocaluxe.Screens ButtonsJoker.Clear(); for (int i = 0; i < CMain.Settings.GetMaxNumPlayer(); i++) - { ButtonsJoker.Add("ButtonJoker" + (i + 1)); - } List blist = new List(); blist.AddRange(ButtonsJoker); blist.Add(ButtonOptionsClose); @@ -100,9 +100,7 @@ namespace Vocaluxe.Screens TextsPlayer.Clear(); for (int i = 0; i < CMain.Settings.GetMaxNumPlayer(); i++) - { TextsPlayer.Add("TextPlayer" + (i + 1)); - } List tlist = new List(); tlist.AddRange(TextsPlayer); tlist.Add(TextCategory); @@ -111,12 +109,12 @@ namespace Vocaluxe.Screens tlist.Add(TextSearchBar); tlist.Add(TextOptionsTitle); - _ThemeStatics = new string[] { StaticSearchBar, StaticOptionsBG }; + _ThemeStatics = new[] {StaticSearchBar, StaticOptionsBG}; _ThemeTexts = tlist.ToArray(); _ThemeButtons = blist.ToArray(); - _ThemeSelectSlides = new string[] { SelectSlideOptionsMode, SelectSlideOptionsPlaylistAdd, SelectSlideOptionsPlaylistOpen, SelectSlideOptionsNumMedleySongs }; - _ThemeSongMenus = new string[] { SongMenu }; - _ThemePlaylists = new string[] { Playlist }; + _ThemeSelectSlides = new[] {SelectSlideOptionsMode, SelectSlideOptionsPlaylistAdd, SelectSlideOptionsPlaylistOpen, SelectSlideOptionsNumMedleySongs}; + _ThemeSongMenus = new[] {SongMenu}; + _ThemePlaylists = new[] {Playlist}; } public override void LoadTheme(string XmlPath) @@ -194,9 +192,7 @@ namespace Vocaluxe.Screens } } if (Buttons[ButtonStart].Selected) - { HandlePartySongSelection(SongMenus[SongMenu].GetSelectedSong()); - } } if (CSongs.NumVisibleSongs > 0 && !_sso.Selection.PartyMode) { @@ -219,14 +215,10 @@ namespace Vocaluxe.Screens case Keys.Back: if (_SearchActive && _SearchText.Length > 0) - { ApplyNewSearchFilter(_SearchText.Remove(_SearchText.Length - 1)); - } if ((CSongs.Category < 0 || _sso.Sorting.Tabs == EOffOn.TR_CONFIG_OFF) && !_sso.Selection.PartyMode && !_SearchActive) - { CGraphics.FadeTo(EScreens.ScreenMain); - } break; @@ -241,7 +233,8 @@ namespace Vocaluxe.Screens _SearchActive = true; break; } - if(!_SearchActive){ + if (!_SearchActive) + { switch (KeyEvent.Key) { case Keys.Space: @@ -301,9 +294,7 @@ namespace Vocaluxe.Screens { case Keys.Enter: if (Buttons[ButtonOptionsClose].Selected) - { ToggleSongOptions(ESongOptionsView.None); - } else if (Buttons[ButtonOptionsSing].Selected) { ToggleSongOptions(ESongOptionsView.None); @@ -320,27 +311,17 @@ namespace Vocaluxe.Screens SongMenus[SongMenu].SetSelectedSong(CSongs.GetRandomSong()); else SongMenus[SongMenu].SetSelectedCategory(CSongs.GetRandomCategory()); - } + } else if (Buttons[ButtonOptionsSingAll].Selected) - { StartRandomAllSongs(); - } else if (Buttons[ButtonOptionsSingAllVisible].Selected) - { StartRandomVisibleSongs(); - } else if (Buttons[ButtonOptionsOpenSelectedItem].Selected) - { _HandleSelectButton(); - } else if (SelectSlides[SelectSlideOptionsPlaylistOpen].Selected) - { OpenPlaylistAction(); - } else if (Buttons[ButtonOptionsRandomMedley].Selected) - { ToggleSongOptions(ESongOptionsView.Medley); - } else if (Buttons[ButtonOptionsStartMedley].Selected) { ToggleSongOptions(ESongOptionsView.None); @@ -383,7 +364,7 @@ namespace Vocaluxe.Screens if (DragAndDropActive) { DragAndDropCover.Rect.X += MouseEvent.X - OldMousePosX; - DragAndDropCover.Rect.Y += MouseEvent.Y - OldMousePosY; + DragAndDropCover.Rect.Y += MouseEvent.Y - OldMousePosY; } OldMousePosX = MouseEvent.X; OldMousePosY = MouseEvent.Y; @@ -406,9 +387,7 @@ namespace Vocaluxe.Screens if (Playlists[Playlist].Visible && _PlaylistActive) { if (Playlists[Playlist].HandleMouse(MouseEvent)) - { return true; - } } @@ -436,9 +415,7 @@ namespace Vocaluxe.Screens } if (MouseEvent.MB && !_sso.Selection.PartyMode) - { return SelectNextRandom(-1); - } if (MouseEvent.LD && !_sso.Selection.PartyMode) { @@ -466,11 +443,13 @@ namespace Vocaluxe.Screens { ToggleSongOptions(ESongOptionsView.General); return true; - } else if (Buttons[ButtonOptionsClose].Selected) + } + else if (Buttons[ButtonOptionsClose].Selected) { ToggleSongOptions(ESongOptionsView.None); return true; - } else if (Buttons[ButtonOptionsSing].Selected) + } + else if (Buttons[ButtonOptionsSing].Selected) { ToggleSongOptions(ESongOptionsView.None); StartSong(SongMenus[SongMenu].GetSelectedSong()); @@ -538,7 +517,7 @@ namespace Vocaluxe.Screens HandlePartySongSelection(SongMenus[SongMenu].GetSelectedSong()); return true; } - + for (int i = 0; i < ButtonsJoker.Count; i++) { if (i < _sso.Selection.NumJokers.Length) @@ -593,11 +572,12 @@ namespace Vocaluxe.Screens private void _HandleSelectButton() { - if (CSongs.IsInCategory) { - if(!_sso.Selection.PartyMode) + if (CSongs.IsInCategory) + { + if (!_sso.Selection.PartyMode) ToggleSongOptions(ESongOptionsView.Song); } - else if(_sso.Selection.CategoryChangeAllowed) + else if (_sso.Selection.CategoryChangeAllowed) { ToggleSongOptions(ESongOptionsView.None); SongMenus[SongMenu].EnterCurrentCategory(); @@ -627,7 +607,7 @@ namespace Vocaluxe.Screens SongMenus[SongMenu].SetActive(!_PlaylistActive); SongMenus[SongMenu].SetSmallView(Playlists[Playlist].Visible); - + if (Playlists[Playlist].ActivePlaylistID != -1) Playlists[Playlist].LoadPlaylist(Playlists[Playlist].ActivePlaylistID); @@ -651,13 +631,9 @@ namespace Vocaluxe.Screens int song = SongMenus[SongMenu].GetActualSelection(); if ((CSongs.Category >= 0 || CConfig.Tabs == EOffOn.TR_CONFIG_OFF) && song >= 0 && song < CSongs.VisibleSongs.Length) - { - Texts[TextSelection].Text = CSongs.VisibleSongs[song].Artist + " - " + CSongs.VisibleSongs[song].Title; - } + Texts[TextSelection].Text = CSongs.VisibleSongs[song].Artist + " - " + CSongs.VisibleSongs[song].Title; else if (!CSongs.IsInCategory && song >= 0 && song < CSongs.Categories.Length) - { - Texts[TextSelection].Text = CSongs.Categories[song].Name; - } + Texts[TextSelection].Text = CSongs.Categories[song].Name; else Texts[TextSelection].Text = String.Empty; @@ -710,9 +686,7 @@ namespace Vocaluxe.Screens { CSong song = CSongs.VisibleSongs[SongNr]; if (song != null) - { CParty.SongSelected(song.ID); - } } } @@ -740,7 +714,7 @@ namespace Vocaluxe.Screens } _sso = CParty.GetSongSelectionOptions(); - + if (_sso.Selection.PartyMode) { @@ -810,15 +784,13 @@ namespace Vocaluxe.Screens { EGameMode gm; if (_AvailableGameModes.Count >= SelectSlides[SelectSlideOptionsMode].Selection) - { gm = _AvailableGameModes[SelectSlides[SelectSlideOptionsMode].Selection]; - } else { if (CSongs.VisibleSongs[SongNr].IsDuet) - gm = EGameMode.TR_GAMEMODE_DUET; + gm = EGameMode.TR_GAMEMODE_DUET; else - gm = EGameMode.TR_GAMEMODE_NORMAL; + gm = EGameMode.TR_GAMEMODE_NORMAL; } CGame.Reset(); @@ -874,9 +846,7 @@ namespace Vocaluxe.Screens List IDs = new List(); for (int i = 0; i < CSongs.AllSongs.Length; i++) - { IDs.Add(i); - } while (IDs.Count > 0) { @@ -888,7 +858,7 @@ namespace Vocaluxe.Screens CGame.AddSong(SongNr, gm); - IDs.Remove(SongNr); + IDs.Remove(SongNr); } if (CGame.GetNumSongs() > 0) @@ -902,9 +872,7 @@ namespace Vocaluxe.Screens List IDs = new List(); for (int i = 0; i < CSongs.VisibleSongs.Length; i++) - { IDs.Add(CSongs.VisibleSongs[i].ID); - } while (IDs.Count > 0) { @@ -932,16 +900,12 @@ namespace Vocaluxe.Screens if (AllSongs) { for (int i = 0; i < CSongs.AllSongs.Length; i++) - { IDs.Add(i); - } } else { for (int i = 0; i < CSongs.VisibleSongs.Length; i++) - { IDs.Add(CSongs.VisibleSongs[i].ID); - } } int s = 0; while (s < NumSongs && IDs.Count > 0) @@ -966,7 +930,7 @@ namespace Vocaluxe.Screens } private bool SelectNextRandom(int TeamNr) - { + { if (TeamNr != -1 && _sso.Selection.RandomOnly && _sso.Selection.NumJokers != null) { bool result = false; @@ -1025,9 +989,9 @@ namespace Vocaluxe.Screens if (CurrentSong != null && CurrentSong.Artist.StartsWith(Letter.ToString(), StringComparison.OrdinalIgnoreCase)) start = curSelected + 1; } - int visibleID = Array.FindIndex(Songs, start, ct - start, element => element.Artist.StartsWith(Letter.ToString(), StringComparison.OrdinalIgnoreCase)); + int visibleID = Array.FindIndex(Songs, start, ct - start, element => element.Artist.StartsWith(Letter.ToString(), StringComparison.OrdinalIgnoreCase)); if (visibleID < 0 && start > 1) - visibleID = Array.FindIndex(Songs, 0, start - 1, element => element.Artist.StartsWith(Letter.ToString(), StringComparison.OrdinalIgnoreCase)); + visibleID = Array.FindIndex(Songs, 0, start - 1, element => element.Artist.StartsWith(Letter.ToString(), StringComparison.OrdinalIgnoreCase)); if (visibleID > -1) SongMenus[SongMenu].SetSelectedSong(visibleID); } @@ -1037,12 +1001,11 @@ namespace Vocaluxe.Screens int ct = Categories.Length; if (curSelected >= 0 && curSelected < ct - 1 && Categories[curSelected].Name.StartsWith(Letter.ToString(), StringComparison.OrdinalIgnoreCase)) start = curSelected + 1; - int visibleID = Array.FindIndex(Categories, start, ct - start, element => element.Name.StartsWith(Letter.ToString(), StringComparison.OrdinalIgnoreCase)); + int visibleID = Array.FindIndex(Categories, start, ct - start, element => element.Name.StartsWith(Letter.ToString(), StringComparison.OrdinalIgnoreCase)); if (visibleID < 0 && start > 1) - visibleID = Array.FindIndex(Categories, 0, start - 1, element => element.Name.StartsWith(Letter.ToString(), StringComparison.OrdinalIgnoreCase)); + visibleID = Array.FindIndex(Categories, 0, start - 1, element => element.Name.StartsWith(Letter.ToString(), StringComparison.OrdinalIgnoreCase)); if (visibleID > -1) SongMenus[SongMenu].SetSelectedCategory(visibleID); - } } @@ -1050,16 +1013,14 @@ namespace Vocaluxe.Screens { CParty.SetSearchString(NewFilterString, _SearchActive); _sso = CParty.GetSongSelectionOptions(); - + bool refresh = false; _SearchText = NewFilterString; int SongIndex = SongMenus[SongMenu].GetSelectedSong(); int SongID = -1; if (SongIndex != -1 && CSongs.NumVisibleSongs > 0 && CSongs.NumVisibleSongs > SongIndex) - { SongID = CSongs.VisibleSongs[SongIndex].ID; - } if (NewFilterString.Length == 0 && _sso.Sorting.Tabs == EOffOn.TR_CONFIG_ON) { @@ -1177,7 +1138,7 @@ namespace Vocaluxe.Screens if (SelectSlides[SelectSlideOptionsPlaylistOpen].NumValues > 0) SelectSlides[SelectSlideOptionsPlaylistOpen].Visible = true; - + if (Buttons[ButtonOptionsRandom].Visible) SetInteractionToButton(Buttons[ButtonOptionsRandom]); else @@ -1192,16 +1153,12 @@ namespace Vocaluxe.Screens if (CSongs.IsInCategory) { for (int i = 1; i <= CSongs.VisibleSongs.Length; i++) - { SelectSlides[SelectSlideOptionsNumMedleySongs].AddValue(i.ToString()); - } } else { for (int i = 1; i <= CSongs.AllSongs.Length; i++) - { SelectSlides[SelectSlideOptionsNumMedleySongs].AddValue(i.ToString()); - } } if (SelectSlides[SelectSlideOptionsNumMedleySongs].NumValues >= 5) SelectSlides[SelectSlideOptionsNumMedleySongs].SetSelectionByValueIndex(4); @@ -1264,18 +1221,18 @@ namespace Vocaluxe.Screens private void OpenAndAddPlaylistAction() { //Open an existing playlist and add song - if (Playlists[Playlist].ActivePlaylistID != (SelectSlides[SelectSlideOptionsPlaylistAdd].Selection - 1) && (SelectSlides[SelectSlideOptionsPlaylistAdd].Selection - 1) != -1) + if (Playlists[Playlist].ActivePlaylistID != (SelectSlides[SelectSlideOptionsPlaylistAdd].Selection - 1) && + (SelectSlides[SelectSlideOptionsPlaylistAdd].Selection - 1) != -1) { //Check selected game-mode EGameMode gm; if (_AvailableGameModes.Count >= SelectSlides[SelectSlideOptionsMode].Selection) gm = _AvailableGameModes[SelectSlides[SelectSlideOptionsMode].Selection]; + else if (CSongs.VisibleSongs[SongMenus[SongMenu].GetSelectedSong()].IsDuet) + gm = EGameMode.TR_GAMEMODE_DUET; else - if (CSongs.VisibleSongs[SongMenus[SongMenu].GetSelectedSong()].IsDuet) - gm = EGameMode.TR_GAMEMODE_DUET; - else - gm = EGameMode.TR_GAMEMODE_NORMAL; - + gm = EGameMode.TR_GAMEMODE_NORMAL; + //Check if Playlist really exists if (SelectSlides[SelectSlideOptionsPlaylistAdd].Selection - 1 >= 0) { @@ -1291,47 +1248,44 @@ namespace Vocaluxe.Screens Playlists[Playlist].ScrollToBottom(); } } - //Create a new playlist and add song + //Create a new playlist and add song else if ((SelectSlides[SelectSlideOptionsPlaylistAdd].Selection - 1) == -1) { //Check selected game-mode EGameMode gm; if (_AvailableGameModes.Count >= SelectSlides[SelectSlideOptionsMode].Selection) gm = _AvailableGameModes[SelectSlides[SelectSlideOptionsMode].Selection]; + else if (CSongs.VisibleSongs[SongMenus[SongMenu].GetSelectedSong()].IsDuet) + gm = EGameMode.TR_GAMEMODE_DUET; else - if (CSongs.VisibleSongs[SongMenus[SongMenu].GetSelectedSong()].IsDuet) - gm = EGameMode.TR_GAMEMODE_DUET; - else - gm = EGameMode.TR_GAMEMODE_NORMAL; - + gm = EGameMode.TR_GAMEMODE_NORMAL; + //Create new playlist Playlists[Playlist].ActivePlaylistID = CPlaylists.NewPlaylist(); - + //Add song to playlist CPlaylists.Playlists[Playlists[Playlist].ActivePlaylistID].AddSong(CSongs.VisibleSongs[SongMenus[SongMenu].GetSelectedSong()].ID, gm); - + //Open playlist OpenPlaylist(Playlists[Playlist].ActivePlaylistID); - + //Add new playlist to select-slide SelectSlides[SelectSlideOptionsPlaylistAdd].AddValue(CPlaylists.Playlists[Playlists[Playlist].ActivePlaylistID].PlaylistName); SelectSlides[SelectSlideOptionsPlaylistOpen].AddValue(CPlaylists.Playlists[Playlists[Playlist].ActivePlaylistID].PlaylistName); SetSelectSlidePlaylistToCurrentPlaylist(); - } - //Add song to loaded playlist + //Add song to loaded playlist else { //Check selected game-mode EGameMode gm; if (_AvailableGameModes.Count >= SelectSlides[SelectSlideOptionsMode].Selection) gm = _AvailableGameModes[SelectSlides[SelectSlideOptionsMode].Selection]; + else if (CSongs.VisibleSongs[SongMenus[SongMenu].GetSelectedSong()].IsDuet) + gm = EGameMode.TR_GAMEMODE_DUET; else - if (CSongs.VisibleSongs[SongMenus[SongMenu].GetSelectedSong()].IsDuet) - gm = EGameMode.TR_GAMEMODE_DUET; - else - gm = EGameMode.TR_GAMEMODE_NORMAL; + gm = EGameMode.TR_GAMEMODE_NORMAL; CPlaylists.Playlists[Playlists[Playlist].ActivePlaylistID].AddSong(CSongs.VisibleSongs[SongMenus[SongMenu].GetSelectedSong()].ID, gm); Playlists[Playlist].UpdatePlaylist(); Playlists[Playlist].ScrollToBottom(); @@ -1347,4 +1301,4 @@ namespace Vocaluxe.Screens } #endregion Playlist Actions } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenTest.cs b/Vocaluxe/Screens/CScreenTest.cs index fd0c8c21..6449cf33 100644 --- a/Vocaluxe/Screens/CScreenTest.cs +++ b/Vocaluxe/Screens/CScreenTest.cs @@ -1,7 +1,6 @@ using System; using System.IO; using System.Windows.Forms; - using Vocaluxe.Base; using VocaluxeLib.Menu; @@ -10,20 +9,16 @@ namespace Vocaluxe.Screens class CScreenTest : CMenu { // Version number for theme files. Increment it, if you've changed something on the theme files! - protected override int _ScreenVersion { get { return 1; } } + protected override int _ScreenVersion + { + get { return 1; } + } private int _TestMusic = -1; - public CScreenTest() - { - } - public override bool HandleInput(KeyEvent KeyEvent) { - if (KeyEvent.KeyPressed && !Char.IsControl(KeyEvent.Unicode)) - { - - } + if (KeyEvent.KeyPressed && !Char.IsControl(KeyEvent.Unicode)) {} else { switch (KeyEvent.Key) @@ -36,7 +31,7 @@ namespace Vocaluxe.Screens case Keys.Enter: CGraphics.FadeTo(EScreens.ScreenMain); break; - + case Keys.F: //FadeAndPause(); break; @@ -56,26 +51,18 @@ namespace Vocaluxe.Screens public override bool HandleMouse(MouseEvent MouseEvent) { - if (MouseEvent.LB && IsMouseOver(MouseEvent)) - { - - } + if (MouseEvent.LB && IsMouseOver(MouseEvent)) {} if (MouseEvent.LB) - { CGraphics.FadeTo(EScreens.ScreenMain); - } if (MouseEvent.RB) - { CGraphics.FadeTo(EScreens.ScreenMain); - } return true; } public override bool UpdateGame() { - return true; } @@ -103,4 +90,4 @@ namespace Vocaluxe.Screens CSound.FadeAndPause(_TestMusic, 0f, 2f); } } -} +} \ No newline at end of file