SongBrowserModel.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  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. if (_directoryStack.Count < 1)
  283. {
  284. DirectoryNode currentNode = _directoryTree[CUSTOM_SONGS_DIR];
  285. _directoryStack.Push(currentNode);
  286. // Try to navigate directory path
  287. if (!String.IsNullOrEmpty(this.CurrentDirectory))
  288. {
  289. String[] paths = this.CurrentDirectory.Split('/');
  290. for (int i = 1; i < paths.Length; i++)
  291. {
  292. if (currentNode.Nodes.ContainsKey(paths[i]))
  293. {
  294. currentNode = currentNode.Nodes[paths[i]];
  295. _directoryStack.Push(currentNode);
  296. }
  297. }
  298. }
  299. }
  300. //PrintDirectory(_directoryTree[CUSTOM_SONGS_DIR], 1);
  301. }
  302. /// <summary>
  303. /// Add a song to directory tree. Determine its place in the tree by walking the split directory path.
  304. /// </summary>
  305. /// <param name="customSongDirUri"></param>
  306. /// <param name="level"></param>
  307. private void AddItemToDirectoryTree(Uri customSongDirUri, StandardLevelSO level)
  308. {
  309. //_log.Debug("Processing item into directory tree: {0}", level.levelID);
  310. DirectoryNode currentNode = _directoryTree[CUSTOM_SONGS_DIR];
  311. // Just add original songs to root and bail
  312. if (level.levelID.Length < 32)
  313. {
  314. currentNode.Levels.Add(level);
  315. return;
  316. }
  317. CustomSongInfo songInfo = _levelIdToCustomLevel[level.levelID].customSongInfo;
  318. Uri customSongUri = new Uri(songInfo.path);
  319. Uri pathDiff = customSongDirUri.MakeRelativeUri(customSongUri);
  320. string relPath = Uri.UnescapeDataString(pathDiff.OriginalString);
  321. string[] paths = relPath.Split('/');
  322. Sprite folderIcon = Base64Sprites.Base64ToSprite(Base64Sprites.Folder);
  323. // Prevent cache directory from building into the tree, will add all its leafs to root.
  324. bool forceIntoRoot = false;
  325. //_log.Debug("Processing path: {0}", songInfo.path);
  326. if (paths.Length > 2)
  327. {
  328. forceIntoRoot = paths[1].Contains(".cache");
  329. Regex r = new Regex(@"^\d{1,}-\d{1,}");
  330. if (r.Match(paths[1]).Success)
  331. {
  332. forceIntoRoot = true;
  333. }
  334. }
  335. for (int i = 1; i < paths.Length; i++)
  336. {
  337. string path = paths[i];
  338. if (path == Path.GetFileName(songInfo.path))
  339. {
  340. //_log.Debug("\tLevel Found Adding {0}->{1}", currentNode.Key, level.levelID);
  341. currentNode.Levels.Add(level);
  342. break;
  343. }
  344. else if (currentNode.Nodes.ContainsKey(path))
  345. {
  346. currentNode = currentNode.Nodes[path];
  347. }
  348. else if (!forceIntoRoot)
  349. {
  350. currentNode.Nodes[path] = new DirectoryNode(path);
  351. FolderLevel folderLevel = new FolderLevel();
  352. folderLevel.Init(relPath, path, folderIcon);
  353. //_log.Debug("\tAdding folder level {0}->{1}", currentNode.Key, path);
  354. currentNode.Levels.Add(folderLevel);
  355. _cachedLastWriteTimes[folderLevel.levelID] = (File.GetLastWriteTimeUtc(relPath) - EPOCH).TotalMilliseconds;
  356. currentNode = currentNode.Nodes[path];
  357. }
  358. }
  359. }
  360. /// <summary>
  361. /// Push a dir onto the stack.
  362. /// </summary>
  363. public void PushDirectory(IStandardLevel level)
  364. {
  365. DirectoryNode currentNode = _directoryStack.Peek();
  366. _log.Debug("Pushing directory {0}", level.songName);
  367. if (!currentNode.Nodes.ContainsKey(level.songName))
  368. {
  369. _log.Debug("Trying to push a directory that doesn't exist at this level.");
  370. return;
  371. }
  372. _directoryStack.Push(currentNode.Nodes[level.songName]);
  373. this.CurrentDirectory = level.levelID;
  374. ProcessSongList();
  375. }
  376. /// <summary>
  377. /// Pop a dir off the stack.
  378. /// </summary>
  379. public void PopDirectory()
  380. {
  381. if (_directoryStack.Count > 1)
  382. {
  383. _directoryStack.Pop();
  384. String currentDir = "";
  385. foreach (DirectoryNode node in _directoryStack)
  386. {
  387. currentDir = node.Key + "/" + currentDir;
  388. }
  389. this.CurrentDirectory = "Folder_" + currentDir;
  390. ProcessSongList();
  391. }
  392. }
  393. /// <summary>
  394. /// Print the directory structure parsed.
  395. /// </summary>
  396. /// <param name="node"></param>
  397. /// <param name="depth"></param>
  398. private void PrintDirectory(DirectoryNode node, int depth)
  399. {
  400. Console.WriteLine("Dir: {0}".PadLeft(depth*4, ' '), node.Key);
  401. node.Levels.ForEach(x => Console.WriteLine("{0}".PadLeft((depth + 1)*4, ' '), x.levelID));
  402. foreach (KeyValuePair<string, DirectoryNode> childNode in node.Nodes)
  403. {
  404. PrintDirectory(childNode.Value, depth + 1);
  405. }
  406. }
  407. /// <summary>
  408. /// Sort the song list based on the settings.
  409. /// </summary>
  410. private void ProcessSongList()
  411. {
  412. _log.Trace("ProcessSongList()");
  413. // This has come in handy many times for debugging issues with Newest.
  414. /*foreach (StandardLevelSO level in _originalSongs)
  415. {
  416. if (_levelIdToCustomLevel.ContainsKey(level.levelID))
  417. {
  418. _log.Debug("HAS KEY {0}: {1}", _levelIdToCustomLevel[level.levelID].customSongInfo.path, level.levelID);
  419. }
  420. else
  421. {
  422. _log.Debug("Missing KEY: {0}", level.levelID);
  423. }
  424. }*/
  425. Stopwatch stopwatch = Stopwatch.StartNew();
  426. List<StandardLevelSO> songList = null;
  427. if (this._settings.sortMode == SongSortMode.Playlist && this.CurrentPlaylist != null)
  428. {
  429. songList = null;
  430. }
  431. else
  432. {
  433. _log.Debug("Showing songs for directory: {0}", _directoryStack.Peek().Key);
  434. songList = _directoryStack.Peek().Levels;
  435. }
  436. switch (_settings.sortMode)
  437. {
  438. case SongSortMode.Favorites:
  439. SortFavorites(songList);
  440. break;
  441. case SongSortMode.Original:
  442. SortOriginal(songList);
  443. break;
  444. case SongSortMode.Newest:
  445. SortNewest(songList);
  446. break;
  447. case SongSortMode.Author:
  448. SortAuthor(songList);
  449. break;
  450. case SongSortMode.PlayCount:
  451. SortPlayCount(songList, _currentGamePlayMode);
  452. break;
  453. case SongSortMode.Difficulty:
  454. SortDifficulty(songList);
  455. break;
  456. case SongSortMode.Random:
  457. SortRandom(songList);
  458. break;
  459. case SongSortMode.Search:
  460. SortSearch(songList);
  461. break;
  462. case SongSortMode.Playlist:
  463. SortPlaylist();
  464. break;
  465. case SongSortMode.Default:
  466. default:
  467. SortSongName(songList);
  468. break;
  469. }
  470. if (this.InvertingResults && _settings.sortMode != SongSortMode.Random)
  471. {
  472. _sortedSongs.Reverse();
  473. }
  474. stopwatch.Stop();
  475. _log.Info("Sorting songs took {0}ms", stopwatch.ElapsedMilliseconds);
  476. }
  477. private void SortFavorites(List<StandardLevelSO> levels)
  478. {
  479. _log.Info("Sorting song list as favorites");
  480. _sortedSongs = levels
  481. .AsQueryable()
  482. .OrderBy(x => _settings.favorites.Contains(x.levelID) == false)
  483. .ThenBy(x => x.songName)
  484. .ThenBy(x => x.songAuthorName)
  485. .ToList();
  486. }
  487. private void SortOriginal(List<StandardLevelSO> levels)
  488. {
  489. _log.Info("Sorting song list as original");
  490. _sortedSongs = levels
  491. .AsQueryable()
  492. .OrderByDescending(x => _weights.ContainsKey(x.levelID) ? _weights[x.levelID] : 0)
  493. .ThenBy(x => x.songName)
  494. .ToList();
  495. }
  496. private void SortNewest(List<StandardLevelSO> levels)
  497. {
  498. _log.Info("Sorting song list as newest.");
  499. _sortedSongs = levels
  500. .AsQueryable()
  501. .OrderBy(x => _weights.ContainsKey(x.levelID) ? _weights[x.levelID] : 0)
  502. .ThenByDescending(x => x.levelID.StartsWith("Level") ? _weights[x.levelID] : _cachedLastWriteTimes[x.levelID])
  503. .ToList();
  504. }
  505. private void SortAuthor(List<StandardLevelSO> levels)
  506. {
  507. _log.Info("Sorting song list by author");
  508. _sortedSongs = levels
  509. .AsQueryable()
  510. .OrderBy(x => x.songAuthorName)
  511. .ThenBy(x => x.songName)
  512. .ToList();
  513. }
  514. private void SortPlayCount(List<StandardLevelSO> levels, GameplayMode gameplayMode)
  515. {
  516. _log.Info("Sorting song list by playcount");
  517. // Build a map of levelId to sum of all playcounts and sort.
  518. PlayerDynamicData playerData = GameDataModel.instance.gameDynamicData.GetCurrentPlayerDynamicData();
  519. IEnumerable<LevelDifficulty> difficultyIterator = Enum.GetValues(typeof(LevelDifficulty)).Cast<LevelDifficulty>();
  520. Dictionary<string, int> levelIdToPlayCount = new Dictionary<string, int>();
  521. foreach (var level in levels)
  522. {
  523. if (!levelIdToPlayCount.ContainsKey(level.levelID))
  524. {
  525. // Skip folders
  526. if (level.levelID.StartsWith("Folder_"))
  527. {
  528. levelIdToPlayCount.Add(level.levelID, 0);
  529. }
  530. else
  531. {
  532. int playCountSum = 0;
  533. foreach (LevelDifficulty difficulty in difficultyIterator)
  534. {
  535. PlayerLevelStatsData stats = playerData.GetPlayerLevelStatsData(level.levelID, difficulty, gameplayMode);
  536. playCountSum += stats.playCount;
  537. }
  538. levelIdToPlayCount.Add(level.levelID, playCountSum);
  539. }
  540. }
  541. }
  542. _sortedSongs = levels
  543. .AsQueryable()
  544. .OrderByDescending(x => levelIdToPlayCount[x.levelID])
  545. .ThenBy(x => x.songName)
  546. .ToList();
  547. }
  548. private void SortDifficulty(List<StandardLevelSO> levels)
  549. {
  550. _log.Info("Sorting song list by random");
  551. System.Random rnd = new System.Random(Guid.NewGuid().GetHashCode());
  552. Dictionary<LevelDifficulty, int> difficultyWeights = new Dictionary<LevelDifficulty, int>
  553. {
  554. [LevelDifficulty.Easy] = int.MaxValue - 4,
  555. [LevelDifficulty.Normal] = int.MaxValue - 3,
  556. [LevelDifficulty.Hard] = int.MaxValue - 2,
  557. [LevelDifficulty.Expert] = int.MaxValue - 1,
  558. [LevelDifficulty.ExpertPlus] = int.MaxValue,
  559. };
  560. IEnumerable<LevelDifficulty> difficultyIterator = Enum.GetValues(typeof(LevelDifficulty)).Cast<LevelDifficulty>();
  561. Dictionary<string, int> levelIdToDifficultyValue = new Dictionary<string, int>();
  562. foreach (var level in levels)
  563. {
  564. if (!levelIdToDifficultyValue.ContainsKey(level.levelID))
  565. {
  566. // Skip folders
  567. if (level.levelID.StartsWith("Folder_"))
  568. {
  569. levelIdToDifficultyValue.Add(level.levelID, 0);
  570. }
  571. else
  572. {
  573. int difficultyValue = 0;
  574. foreach (LevelDifficulty difficulty in difficultyIterator)
  575. {
  576. IStandardLevelDifficultyBeatmap beatmap = level.GetDifficultyLevel(difficulty);
  577. if (beatmap != null)
  578. {
  579. difficultyValue += difficultyWeights[difficulty];
  580. break;
  581. }
  582. }
  583. levelIdToDifficultyValue.Add(level.levelID, difficultyValue);
  584. }
  585. }
  586. }
  587. _sortedSongs = levels
  588. .AsQueryable()
  589. .OrderBy(x => levelIdToDifficultyValue[x.levelID])
  590. .ThenBy(x => x.songName)
  591. .ToList();
  592. }
  593. private void SortRandom(List<StandardLevelSO> levels)
  594. {
  595. _log.Info("Sorting song list by random");
  596. System.Random rnd = new System.Random(Guid.NewGuid().GetHashCode());
  597. _sortedSongs = levels
  598. .AsQueryable()
  599. .OrderBy(x => rnd.Next())
  600. .ToList();
  601. }
  602. private void SortSearch(List<StandardLevelSO> levels)
  603. {
  604. // Make sure we can actually search.
  605. if (this._settings.searchTerms.Count <= 0)
  606. {
  607. _log.Error("Tried to search for a song with no valid search terms...");
  608. SortSongName(levels);
  609. return;
  610. }
  611. string searchTerm = this._settings.searchTerms[0];
  612. if (String.IsNullOrEmpty(searchTerm))
  613. {
  614. _log.Error("Empty search term entered.");
  615. SortSongName(levels);
  616. return;
  617. }
  618. _log.Info("Sorting song list by search term: {0}", searchTerm);
  619. //_originalSongs.ForEach(x => _log.Debug($"{x.songName} {x.songSubName} {x.songAuthorName}".ToLower().Contains(searchTerm.ToLower()).ToString()));
  620. _sortedSongs = levels
  621. .AsQueryable()
  622. .Where(x => $"{x.songName} {x.songSubName} {x.songAuthorName}".ToLower().Contains(searchTerm.ToLower()))
  623. .ToList();
  624. //_sortedSongs.ForEach(x => _log.Debug(x.levelID));
  625. }
  626. private void SortSongName(List<StandardLevelSO> levels)
  627. {
  628. _log.Info("Sorting song list as default (songName)");
  629. _sortedSongs = levels
  630. .AsQueryable()
  631. .OrderBy(x => x.songName)
  632. .ThenBy(x => x.songAuthorName)
  633. .ToList();
  634. }
  635. private void SortPlaylist()
  636. {
  637. _log.Debug("Showing songs for playlist: {0}", this.CurrentPlaylist);
  638. List<String> playlistNameListOrdered = this.CurrentPlaylist.songs.Select(x => x.songName).ToList();
  639. Dictionary<String, int> songNameToIndex = playlistNameListOrdered.Select((val, index) => new { Index = index, Value = val }).ToDictionary(i => i.Value, i => i.Index);
  640. HashSet<String> songNames = new HashSet<String>(playlistNameListOrdered);
  641. SongLoaderPlugin.OverrideClasses.CustomLevelCollectionsForGameplayModes collections = SongLoaderPlugin.SongLoader.Instance.GetPrivateField<SongLoaderPlugin.OverrideClasses.CustomLevelCollectionsForGameplayModes>("_customLevelCollectionsForGameplayModes");
  642. List<StandardLevelSO> songList = collections.GetLevels(_currentGamePlayMode).Where(x => songNames.Contains(x.songName)).ToList();
  643. _sortedSongs = songList
  644. .AsQueryable()
  645. .OrderBy(x => songNameToIndex[x.songName])
  646. .ToList();
  647. }
  648. }
  649. }