SongBrowserModel.cs 27 KB

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