SongBrowserModel.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. using SongBrowserPlugin.DataAccess;
  2. using SongBrowserPlugin.UI;
  3. using SongLoaderPlugin;
  4. using SongLoaderPlugin.OverrideClasses;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Text.RegularExpressions;
  11. using UnityEngine;
  12. namespace SongBrowserPlugin
  13. {
  14. class FolderBeatMapData : BeatmapData
  15. {
  16. public FolderBeatMapData(BeatmapLineData[] beatmapLinesData, BeatmapEventData[] beatmapEventData) :
  17. base(beatmapLinesData, beatmapEventData)
  18. {
  19. }
  20. }
  21. class FolderBeatMapDataSO : BeatmapDataSO
  22. {
  23. public FolderBeatMapDataSO()
  24. {
  25. BeatmapLineData lineData = new BeatmapLineData();
  26. lineData.beatmapObjectsData = new BeatmapObjectData[0];
  27. this._beatmapData = new FolderBeatMapData(
  28. new BeatmapLineData[1]
  29. {
  30. lineData
  31. },
  32. new BeatmapEventData[1]
  33. {
  34. new BeatmapEventData(0, BeatmapEventType.Event0, 0)
  35. });
  36. }
  37. }
  38. class FolderLevel : StandardLevelSO
  39. {
  40. public void Init(String relativePath, String name, Sprite coverImage)
  41. {
  42. _songName = name;
  43. _songSubName = "";
  44. _songAuthorName = "Folder";
  45. _levelID = $"Folder_{relativePath}";
  46. var beatmapData = new FolderBeatMapDataSO();
  47. var difficultyBeatmaps = new List<CustomLevel.CustomDifficultyBeatmap>();
  48. var newDiffBeatmap = new CustomLevel.CustomDifficultyBeatmap(this, LevelDifficulty.Easy, 0, 0, beatmapData);
  49. difficultyBeatmaps.Add(newDiffBeatmap);
  50. var sceneInfo = Resources.Load<SceneInfo>("SceneInfo/" + "DefaultEnvironment" + "SceneInfo");
  51. this.InitFull(_levelID, _songName, _songSubName, _songAuthorName, SongLoaderPlugin.SongLoader.TemporaryAudioClip, 1, 1, 1, 1, 1, 1, 1, coverImage, difficultyBeatmaps.ToArray(), sceneInfo);
  52. this.InitData();
  53. }
  54. }
  55. class DirectoryNode
  56. {
  57. public string Key { get; private set; }
  58. public Dictionary<String, DirectoryNode> Nodes;
  59. public List<StandardLevelSO> Levels;
  60. public DirectoryNode(String key)
  61. {
  62. Key = key;
  63. Nodes = new Dictionary<string, DirectoryNode>();
  64. Levels = new List<StandardLevelSO>();
  65. }
  66. }
  67. public class SongBrowserModel
  68. {
  69. private const String CUSTOM_SONGS_DIR = "CustomSongs";
  70. private DateTime EPOCH = new DateTime(1970, 1, 1);
  71. private Logger _log = new Logger("SongBrowserModel");
  72. // song_browser_settings.xml
  73. private SongBrowserSettings _settings;
  74. // song list management
  75. private List<StandardLevelSO> _sortedSongs;
  76. private List<StandardLevelSO> _originalSongs;
  77. private Dictionary<String, SongLoaderPlugin.OverrideClasses.CustomLevel> _levelIdToCustomLevel;
  78. private SongLoaderPlugin.OverrideClasses.CustomLevelCollectionSO _gameplayModeCollection;
  79. private Dictionary<String, double> _cachedLastWriteTimes;
  80. private Dictionary<string, int> _weights;
  81. private Dictionary<String, DirectoryNode> _directoryTree;
  82. private Stack<DirectoryNode> _directoryStack = new Stack<DirectoryNode>();
  83. private GameplayMode _currentGamePlayMode;
  84. /// <summary>
  85. /// Toggle whether inverting the results.
  86. /// </summary>
  87. public bool InvertingResults { get; private set; }
  88. /// <summary>
  89. /// Get the settings the model is using.
  90. /// </summary>
  91. public SongBrowserSettings Settings
  92. {
  93. get
  94. {
  95. return _settings;
  96. }
  97. }
  98. /// <summary>
  99. /// Get the sorted song list for the current working directory.
  100. /// </summary>
  101. public List<StandardLevelSO> SortedSongList
  102. {
  103. get
  104. {
  105. return _sortedSongs;
  106. }
  107. }
  108. /// <summary>
  109. /// Map LevelID to Custom Level info.
  110. /// </summary>
  111. public Dictionary<String, SongLoaderPlugin.OverrideClasses.CustomLevel> LevelIdToCustomSongInfos
  112. {
  113. get
  114. {
  115. return _levelIdToCustomLevel;
  116. }
  117. }
  118. /// <summary>
  119. /// How deep is the directory stack.
  120. /// </summary>
  121. public int DirStackSize
  122. {
  123. get
  124. {
  125. return _directoryStack.Count;
  126. }
  127. }
  128. /// <summary>
  129. /// Get the last selected (stored in settings) level id.
  130. /// </summary>
  131. public String LastSelectedLevelId
  132. {
  133. get
  134. {
  135. return _settings.currentLevelId;
  136. }
  137. set
  138. {
  139. _settings.currentLevelId = value;
  140. _settings.Save();
  141. }
  142. }
  143. /// <summary>
  144. /// Get the last known directory the user visited.
  145. /// </summary>
  146. public String CurrentDirectory
  147. {
  148. get
  149. {
  150. return _settings.currentDirectory;
  151. }
  152. set
  153. {
  154. _settings.currentDirectory = value;
  155. _settings.Save();
  156. }
  157. }
  158. private Playlist _currentPlaylist;
  159. /// <summary>
  160. /// Manage the current playlist if one exists.
  161. /// </summary>
  162. public Playlist CurrentPlaylist
  163. {
  164. get
  165. {
  166. if (_currentPlaylist == null)
  167. {
  168. _currentPlaylist = PlaylistsReader.ParsePlaylist(this._settings.currentPlaylistFile);
  169. }
  170. return _currentPlaylist;
  171. }
  172. set
  173. {
  174. _settings.currentPlaylistFile = value.playlistPath;
  175. _currentPlaylist = value;
  176. }
  177. }
  178. /// <summary>
  179. /// Constructor.
  180. /// </summary>
  181. public SongBrowserModel()
  182. {
  183. _cachedLastWriteTimes = new Dictionary<String, double>();
  184. // Weights used for keeping the original songs in order
  185. // Invert the weights from the game so we can order by descending and make LINQ work with us...
  186. /* Level4, Level2, Level9, Level5, Level10, Level6, Level7, Level1, Level3, Level8, Level11 */
  187. _weights = new Dictionary<string, int>
  188. {
  189. ["Level4"] = 11,
  190. ["Level2"] = 10,
  191. ["Level9"] = 9,
  192. ["Level5"] = 8,
  193. ["Level10"] = 7,
  194. ["Level6"] = 6,
  195. ["Level7"] = 5,
  196. ["Level1"] = 4,
  197. ["Level3"] = 3,
  198. ["Level8"] = 2,
  199. ["Level11"] = 1
  200. };
  201. }
  202. /// <summary>
  203. /// Init this model.
  204. /// </summary>
  205. /// <param name="songSelectionMasterView"></param>
  206. /// <param name="songListViewController"></param>
  207. public void Init()
  208. {
  209. _settings = SongBrowserSettings.Load();
  210. _log.Info("Settings loaded, sorting mode is: {0}", _settings.sortMode);
  211. }
  212. /// <summary>
  213. /// Easy invert of toggling.
  214. /// </summary>
  215. public void ToggleInverting()
  216. {
  217. this.InvertingResults = !this.InvertingResults;
  218. }
  219. /// <summary>
  220. /// Get the song cache from the game.
  221. /// TODO: This might not even be necessary anymore. Need to test interactions with BeatSaverDownloader.
  222. /// </summary>
  223. public void UpdateSongLists(GameplayMode gameplayMode)
  224. {
  225. _currentGamePlayMode = gameplayMode;
  226. String customSongsPath = Path.Combine(Environment.CurrentDirectory, CUSTOM_SONGS_DIR);
  227. String cachedSongsPath = Path.Combine(customSongsPath, ".cache");
  228. DateTime currentLastWriteTIme = File.GetLastWriteTimeUtc(customSongsPath);
  229. IEnumerable<string> directories = Directory.EnumerateDirectories(customSongsPath, "*.*", SearchOption.AllDirectories);
  230. // Get LastWriteTimes
  231. foreach (var level in SongLoader.CustomLevels)
  232. {
  233. //_log.Debug("Fetching LastWriteTime for {0}", slashed_dir);
  234. _cachedLastWriteTimes[level.levelID] = (File.GetLastWriteTimeUtc(level.customSongInfo.path) - EPOCH).TotalMilliseconds;
  235. }
  236. // Update song Infos, directory tree, and sort
  237. this.UpdateSongInfos(_currentGamePlayMode);
  238. this.UpdateDirectoryTree(customSongsPath);
  239. this.ProcessSongList();
  240. }
  241. /// <summary>
  242. /// Get the song infos from SongLoaderPluging
  243. /// </summary>
  244. private void UpdateSongInfos(GameplayMode gameplayMode)
  245. {
  246. _log.Trace("UpdateSongInfos for Gameplay Mode {0}", gameplayMode);
  247. // Get the level collection from song loader
  248. SongLoaderPlugin.OverrideClasses.CustomLevelCollectionsForGameplayModes collections = SongLoaderPlugin.SongLoader.Instance.GetPrivateField<SongLoaderPlugin.OverrideClasses.CustomLevelCollectionsForGameplayModes>("_customLevelCollectionsForGameplayModes");
  249. _gameplayModeCollection = collections.GetCollection(gameplayMode) as SongLoaderPlugin.OverrideClasses.CustomLevelCollectionSO;
  250. _originalSongs = collections.GetLevels(gameplayMode).ToList();
  251. _sortedSongs = _originalSongs;
  252. _levelIdToCustomLevel = new Dictionary<string, SongLoaderPlugin.OverrideClasses.CustomLevel>();
  253. foreach (var level in SongLoader.CustomLevels)
  254. {
  255. if (!_levelIdToCustomLevel.Keys.Contains(level.levelID))
  256. _levelIdToCustomLevel.Add(level.levelID, level);
  257. }
  258. _log.Debug("Song Browser knows about {0} songs from SongLoader...", _sortedSongs.Count);
  259. }
  260. /// <summary>
  261. /// Make the directory tree.
  262. /// </summary>
  263. /// <param name="customSongsPath"></param>
  264. private void UpdateDirectoryTree(String customSongsPath)
  265. {
  266. // Determine folder mapping
  267. Uri customSongDirUri = new Uri(customSongsPath);
  268. _directoryTree = new Dictionary<string, DirectoryNode>();
  269. _directoryTree[CUSTOM_SONGS_DIR] = new DirectoryNode(CUSTOM_SONGS_DIR);
  270. if (_settings.folderSupportEnabled)
  271. {
  272. foreach (StandardLevelSO level in _originalSongs)
  273. {
  274. AddItemToDirectoryTree(customSongDirUri, level);
  275. }
  276. }
  277. else
  278. {
  279. _directoryTree[CUSTOM_SONGS_DIR].Levels = _originalSongs;
  280. }
  281. // Determine starting location
  282. DirectoryNode currentNode = _directoryTree[CUSTOM_SONGS_DIR];
  283. _directoryStack.Push(currentNode);
  284. // Try to navigate directory path
  285. if (!String.IsNullOrEmpty(this.CurrentDirectory))
  286. {
  287. String[] paths = this.CurrentDirectory.Split('/');
  288. for (int i = 1; i < paths.Length; i++)
  289. {
  290. if (currentNode.Nodes.ContainsKey(paths[i]))
  291. {
  292. currentNode = currentNode.Nodes[paths[i]];
  293. _directoryStack.Push(currentNode);
  294. }
  295. }
  296. }
  297. //PrintDirectory(_directoryTree[CUSTOM_SONGS_DIR], 1);
  298. }
  299. /// <summary>
  300. /// Add a song to directory tree. Determine its place in the tree by walking the split directory path.
  301. /// </summary>
  302. /// <param name="customSongDirUri"></param>
  303. /// <param name="level"></param>
  304. private void AddItemToDirectoryTree(Uri customSongDirUri, StandardLevelSO level)
  305. {
  306. //_log.Debug("Processing item into directory tree: {0}", level.levelID);
  307. DirectoryNode currentNode = _directoryTree[CUSTOM_SONGS_DIR];
  308. // Just add original songs to root and bail
  309. if (level.levelID.Length < 32)
  310. {
  311. currentNode.Levels.Add(level);
  312. return;
  313. }
  314. CustomSongInfo songInfo = _levelIdToCustomLevel[level.levelID].customSongInfo;
  315. Uri customSongUri = new Uri(songInfo.path);
  316. Uri pathDiff = customSongDirUri.MakeRelativeUri(customSongUri);
  317. string relPath = Uri.UnescapeDataString(pathDiff.OriginalString);
  318. string[] paths = relPath.Split('/');
  319. Sprite folderIcon = Base64Sprites.Base64ToSprite(Base64Sprites.FolderIcon);
  320. // Prevent cache directory from building into the tree, will add all its leafs to root.
  321. bool forceIntoRoot = false;
  322. //_log.Debug("Processing path: {0}", songInfo.path);
  323. if (paths.Length > 2)
  324. {
  325. forceIntoRoot = paths[1].Contains(".cache");
  326. Regex r = new Regex(@"^\d{1,}-\d{1,}");
  327. if (r.Match(paths[1]).Success)
  328. {
  329. forceIntoRoot = true;
  330. }
  331. }
  332. for (int i = 1; i < paths.Length; i++)
  333. {
  334. string path = paths[i];
  335. if (path == Path.GetFileName(songInfo.path))
  336. {
  337. //_log.Debug("\tLevel Found Adding {0}->{1}", currentNode.Key, level.levelID);
  338. currentNode.Levels.Add(level);
  339. break;
  340. }
  341. else if (currentNode.Nodes.ContainsKey(path))
  342. {
  343. currentNode = currentNode.Nodes[path];
  344. }
  345. else if (!forceIntoRoot)
  346. {
  347. currentNode.Nodes[path] = new DirectoryNode(path);
  348. FolderLevel folderLevel = new FolderLevel();
  349. folderLevel.Init(relPath, path, folderIcon);
  350. //_log.Debug("\tAdding folder level {0}->{1}", currentNode.Key, path);
  351. currentNode.Levels.Add(folderLevel);
  352. _cachedLastWriteTimes[folderLevel.levelID] = (File.GetLastWriteTimeUtc(relPath) - EPOCH).TotalMilliseconds;
  353. currentNode = currentNode.Nodes[path];
  354. }
  355. }
  356. }
  357. /// <summary>
  358. /// Push a dir onto the stack.
  359. /// </summary>
  360. public void PushDirectory(IStandardLevel level)
  361. {
  362. DirectoryNode currentNode = _directoryStack.Peek();
  363. _log.Debug("Pushing directory {0}", level.songName);
  364. if (!currentNode.Nodes.ContainsKey(level.songName))
  365. {
  366. _log.Debug("Trying to push a directory that doesn't exist at this level.");
  367. return;
  368. }
  369. _directoryStack.Push(currentNode.Nodes[level.songName]);
  370. this.CurrentDirectory = level.levelID;
  371. ProcessSongList();
  372. }
  373. /// <summary>
  374. /// Pop a dir off the stack.
  375. /// </summary>
  376. public void PopDirectory()
  377. {
  378. if (_directoryStack.Count > 1)
  379. {
  380. _directoryStack.Pop();
  381. String currentDir = "";
  382. foreach (DirectoryNode node in _directoryStack)
  383. {
  384. currentDir = node.Key + "/" + currentDir;
  385. }
  386. this.CurrentDirectory = "Folder_" + currentDir;
  387. ProcessSongList();
  388. }
  389. }
  390. /// <summary>
  391. /// Print the directory structure parsed.
  392. /// </summary>
  393. /// <param name="node"></param>
  394. /// <param name="depth"></param>
  395. private void PrintDirectory(DirectoryNode node, int depth)
  396. {
  397. Console.WriteLine("Dir: {0}".PadLeft(depth*4, ' '), node.Key);
  398. node.Levels.ForEach(x => Console.WriteLine("{0}".PadLeft((depth + 1)*4, ' '), x.levelID));
  399. foreach (KeyValuePair<string, DirectoryNode> childNode in node.Nodes)
  400. {
  401. PrintDirectory(childNode.Value, depth + 1);
  402. }
  403. }
  404. /// <summary>
  405. /// Sort the song list based on the settings.
  406. /// </summary>
  407. private void ProcessSongList()
  408. {
  409. _log.Trace("ProcessSongList()");
  410. // This has come in handy many times for debugging issues with Newest.
  411. /*foreach (StandardLevelSO level in _originalSongs)
  412. {
  413. if (_levelIdToCustomLevel.ContainsKey(level.levelID))
  414. {
  415. _log.Debug("HAS KEY {0}: {1}", _levelIdToCustomLevel[level.levelID].customSongInfo.path, level.levelID);
  416. }
  417. else
  418. {
  419. _log.Debug("Missing KEY: {0}", level.levelID);
  420. }
  421. }*/
  422. Stopwatch stopwatch = Stopwatch.StartNew();
  423. List<StandardLevelSO> songList = null;
  424. if (this._settings.sortMode == SongSortMode.Playlist && this.CurrentPlaylist != null)
  425. {
  426. songList = null;
  427. }
  428. else
  429. {
  430. _log.Debug("Showing songs for directory: {0}", _directoryStack.Peek().Key);
  431. songList = _directoryStack.Peek().Levels;
  432. }
  433. switch (_settings.sortMode)
  434. {
  435. case SongSortMode.Favorites:
  436. SortFavorites(songList);
  437. break;
  438. case SongSortMode.Original:
  439. SortOriginal(songList);
  440. break;
  441. case SongSortMode.Newest:
  442. SortNewest(songList);
  443. break;
  444. case SongSortMode.Author:
  445. SortAuthor(songList);
  446. break;
  447. case SongSortMode.PlayCount:
  448. SortPlayCount(songList, _currentGamePlayMode);
  449. break;
  450. case SongSortMode.Difficulty:
  451. SortDifficulty(songList);
  452. break;
  453. case SongSortMode.Random:
  454. SortRandom(songList);
  455. break;
  456. case SongSortMode.Search:
  457. SortSearch(songList);
  458. break;
  459. case SongSortMode.Playlist:
  460. SortPlaylist();
  461. break;
  462. case SongSortMode.Default:
  463. default:
  464. SortSongName(songList);
  465. break;
  466. }
  467. if (this.InvertingResults && _settings.sortMode != SongSortMode.Random)
  468. {
  469. _sortedSongs.Reverse();
  470. }
  471. stopwatch.Stop();
  472. _log.Info("Sorting songs took {0}ms", stopwatch.ElapsedMilliseconds);
  473. }
  474. private void SortFavorites(List<StandardLevelSO> levels)
  475. {
  476. _log.Info("Sorting song list as favorites");
  477. _sortedSongs = levels
  478. .AsQueryable()
  479. .OrderBy(x => _settings.Favorites.Contains(x.levelID) == false)
  480. .ThenBy(x => x.songName)
  481. .ThenBy(x => x.songAuthorName)
  482. .ToList();
  483. }
  484. private void SortOriginal(List<StandardLevelSO> levels)
  485. {
  486. _log.Info("Sorting song list as original");
  487. _sortedSongs = levels
  488. .AsQueryable()
  489. .OrderByDescending(x => _weights.ContainsKey(x.levelID) ? _weights[x.levelID] : 0)
  490. .ThenBy(x => x.songName)
  491. .ToList();
  492. }
  493. private void SortNewest(List<StandardLevelSO> levels)
  494. {
  495. _log.Info("Sorting song list as newest.");
  496. _sortedSongs = levels
  497. .AsQueryable()
  498. .OrderBy(x => _weights.ContainsKey(x.levelID) ? _weights[x.levelID] : 0)
  499. .ThenByDescending(x => x.levelID.StartsWith("Level") ? _weights[x.levelID] : _cachedLastWriteTimes[x.levelID])
  500. .ToList();
  501. }
  502. private void SortAuthor(List<StandardLevelSO> levels)
  503. {
  504. _log.Info("Sorting song list by author");
  505. _sortedSongs = levels
  506. .AsQueryable()
  507. .OrderBy(x => x.songAuthorName)
  508. .ThenBy(x => x.songName)
  509. .ToList();
  510. }
  511. private void SortPlayCount(List<StandardLevelSO> levels, GameplayMode gameplayMode)
  512. {
  513. _log.Info("Sorting song list by playcount");
  514. // Build a map of levelId to sum of all playcounts and sort.
  515. PlayerDynamicData playerData = GameDataModel.instance.gameDynamicData.GetCurrentPlayerDynamicData();
  516. IEnumerable<LevelDifficulty> difficultyIterator = Enum.GetValues(typeof(LevelDifficulty)).Cast<LevelDifficulty>();
  517. Dictionary<string, int> levelIdToPlayCount = new Dictionary<string, int>();
  518. foreach (var level in levels)
  519. {
  520. if (!levelIdToPlayCount.ContainsKey(level.levelID))
  521. {
  522. // Skip folders
  523. if (level.levelID.StartsWith("Folder_"))
  524. {
  525. levelIdToPlayCount.Add(level.levelID, 0);
  526. }
  527. else
  528. {
  529. int playCountSum = 0;
  530. foreach (LevelDifficulty difficulty in difficultyIterator)
  531. {
  532. PlayerLevelStatsData stats = playerData.GetPlayerLevelStatsData(level.levelID, difficulty, gameplayMode);
  533. playCountSum += stats.playCount;
  534. }
  535. levelIdToPlayCount.Add(level.levelID, playCountSum);
  536. }
  537. }
  538. }
  539. _sortedSongs = levels
  540. .AsQueryable()
  541. .OrderByDescending(x => levelIdToPlayCount[x.levelID])
  542. .ThenBy(x => x.songName)
  543. .ToList();
  544. }
  545. private void SortDifficulty(List<StandardLevelSO> levels)
  546. {
  547. _log.Info("Sorting song list by random");
  548. System.Random rnd = new System.Random(Guid.NewGuid().GetHashCode());
  549. Dictionary<LevelDifficulty, int> difficultyWeights = new Dictionary<LevelDifficulty, int>
  550. {
  551. [LevelDifficulty.Easy] = int.MaxValue - 4,
  552. [LevelDifficulty.Normal] = int.MaxValue - 3,
  553. [LevelDifficulty.Hard] = int.MaxValue - 2,
  554. [LevelDifficulty.Expert] = int.MaxValue - 1,
  555. [LevelDifficulty.ExpertPlus] = int.MaxValue,
  556. };
  557. IEnumerable<LevelDifficulty> difficultyIterator = Enum.GetValues(typeof(LevelDifficulty)).Cast<LevelDifficulty>();
  558. Dictionary<string, int> levelIdToDifficultyValue = new Dictionary<string, int>();
  559. foreach (var level in levels)
  560. {
  561. if (!levelIdToDifficultyValue.ContainsKey(level.levelID))
  562. {
  563. // Skip folders
  564. if (level.levelID.StartsWith("Folder_"))
  565. {
  566. levelIdToDifficultyValue.Add(level.levelID, 0);
  567. }
  568. else
  569. {
  570. int difficultyValue = 0;
  571. foreach (LevelDifficulty difficulty in difficultyIterator)
  572. {
  573. IStandardLevelDifficultyBeatmap beatmap = level.GetDifficultyLevel(difficulty);
  574. if (beatmap != null)
  575. {
  576. difficultyValue += difficultyWeights[difficulty];
  577. break;
  578. }
  579. }
  580. levelIdToDifficultyValue.Add(level.levelID, difficultyValue);
  581. }
  582. }
  583. }
  584. _sortedSongs = levels
  585. .AsQueryable()
  586. .OrderBy(x => levelIdToDifficultyValue[x.levelID])
  587. .ThenBy(x => x.songName)
  588. .ToList();
  589. }
  590. private void SortRandom(List<StandardLevelSO> levels)
  591. {
  592. _log.Info("Sorting song list by random");
  593. System.Random rnd = new System.Random(Guid.NewGuid().GetHashCode());
  594. _sortedSongs = levels
  595. .AsQueryable()
  596. .OrderBy(x => rnd.Next())
  597. .ToList();
  598. }
  599. private void SortSearch(List<StandardLevelSO> levels)
  600. {
  601. // Make sure we can actually search.
  602. if (this._settings.searchTerms.Count <= 0)
  603. {
  604. _log.Error("Tried to search for a song with no valid search terms...");
  605. SortSongName(levels);
  606. return;
  607. }
  608. string searchTerm = this._settings.searchTerms[0];
  609. if (String.IsNullOrEmpty(searchTerm))
  610. {
  611. _log.Error("Empty search term entered.");
  612. SortSongName(levels);
  613. return;
  614. }
  615. _log.Info("Sorting song list by search term: {0}", searchTerm);
  616. //_originalSongs.ForEach(x => _log.Debug($"{x.songName} {x.songSubName} {x.songAuthorName}".ToLower().Contains(searchTerm.ToLower()).ToString()));
  617. _sortedSongs = levels
  618. .AsQueryable()
  619. .Where(x => $"{x.songName} {x.songSubName} {x.songAuthorName}".ToLower().Contains(searchTerm.ToLower()))
  620. .ToList();
  621. //_sortedSongs.ForEach(x => _log.Debug(x.levelID));
  622. }
  623. private void SortSongName(List<StandardLevelSO> levels)
  624. {
  625. _log.Info("Sorting song list as default (songName)");
  626. _sortedSongs = levels
  627. .AsQueryable()
  628. .OrderBy(x => x.songName)
  629. .ThenBy(x => x.songAuthorName)
  630. .ToList();
  631. }
  632. private void SortPlaylist()
  633. {
  634. _log.Debug("Showing songs for playlist: {0}", this.CurrentPlaylist);
  635. List<String> playlistNameListOrdered = this.CurrentPlaylist.songs.Select(x => x.songName).Distinct().ToList();
  636. Dictionary<String, int> songNameToIndex = playlistNameListOrdered.Select((val, index) => new { Index = index, Value = val }).ToDictionary(i => i.Value, i => i.Index);
  637. HashSet<String> songNames = new HashSet<String>(playlistNameListOrdered);
  638. SongLoaderPlugin.OverrideClasses.CustomLevelCollectionsForGameplayModes collections = SongLoaderPlugin.SongLoader.Instance.GetPrivateField<SongLoaderPlugin.OverrideClasses.CustomLevelCollectionsForGameplayModes>("_customLevelCollectionsForGameplayModes");
  639. List<StandardLevelSO> songList = collections.GetLevels(_currentGamePlayMode).Where(x => songNames.Contains(x.songName)).ToList();
  640. _log.Debug("\tMatching songs found for playlist: {0}", songList.Count);
  641. _sortedSongs = songList
  642. .AsQueryable()
  643. .OrderBy(x => songNameToIndex[x.songName])
  644. .ToList();
  645. }
  646. }
  647. }