levelset.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // SuperTux
  2. // Copyright (C) 2014 Ingo Ruhnke <grumbel@gmail.com>
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. #include "supertux/levelset.hpp"
  17. #include <physfs.h>
  18. #include <algorithm>
  19. #include "physfs/util.hpp"
  20. #include "util/file_system.hpp"
  21. #include "util/log.hpp"
  22. #include "util/string_util.hpp"
  23. Levelset::Levelset(const std::string& basedir, bool recursively) :
  24. m_basedir(basedir),
  25. m_levels()
  26. {
  27. walk_directory(m_basedir, recursively);
  28. std::sort(m_levels.begin(), m_levels.end(), StringUtil::numeric_less);
  29. }
  30. int
  31. Levelset::get_num_levels() const
  32. {
  33. return static_cast<int>(m_levels.size());
  34. }
  35. std::string
  36. Levelset::get_level_filename(int i) const
  37. {
  38. return m_levels[i];
  39. }
  40. void
  41. Levelset::walk_directory(const std::string& directory, bool recursively)
  42. {
  43. bool is_basedir = (directory == m_basedir);
  44. bool enumerateSuccess = physfsutil::enumerate_files(directory, [directory, is_basedir, recursively, this](const auto& filename) {
  45. auto filepath = FileSystem::join(directory, filename);
  46. if (physfsutil::is_directory(filepath) && recursively)
  47. {
  48. walk_directory(filepath, true);
  49. }
  50. if (StringUtil::has_suffix(filename, ".stl"))
  51. {
  52. if (is_basedir)
  53. {
  54. m_levels.push_back(filename);
  55. }
  56. else
  57. {
  58. // Replace basedir part of file path plus slash.
  59. filepath = filepath.replace(0, m_basedir.length() + 1, "");
  60. m_levels.push_back(filepath);
  61. }
  62. }
  63. });
  64. if (!enumerateSuccess)
  65. {
  66. log_warning << "Couldn't read subset dir '" << directory << "'" << std::endl;
  67. }
  68. }
  69. /* EOF */