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
17#include "supertux/levelset.hpp"
18
19#include <physfs.h>
20#include <algorithm>
21
22#include "physfs/util.hpp"
23#include "util/file_system.hpp"
24#include "util/log.hpp"
25#include "util/string_util.hpp"
26
27Levelset::Levelset(const std::string& basedir, bool recursively) :
28 m_basedir(basedir),
29 m_levels()
30{
31 walk_directory(m_basedir, recursively);
32 std::sort(m_levels.begin(), m_levels.end(), StringUtil::numeric_less);
33}
34
35int
36Levelset::get_num_levels() const
37{
38 return static_cast<int>(m_levels.size());
39}
40
41std::string
42Levelset::get_level_filename(int i) const
43{
44 return m_levels[i];
45}
46
47void
48Levelset::walk_directory(const std::string& directory, bool recursively)
49{
50 bool is_basedir = (directory == m_basedir);
51 char** files = PHYSFS_enumerateFiles(directory.c_str());
52 if (!files)
53 {
54 log_warning << "Couldn't read subset dir '" << directory << "'" << std::endl;
55 return;
56 }
57
58 for (const char* const* filename = files; *filename != nullptr; ++filename)
59 {
60 auto filepath = FileSystem::join(directory.c_str(), *filename);
61 if (physfsutil::is_directory(filepath) && recursively)
62 {
63 walk_directory(filepath, true);
64 }
65 if (StringUtil::has_suffix(*filename, ".stl"))
66 {
67 if (is_basedir)
68 {
69 m_levels.push_back(*filename);
70 }
71 else
72 {
73 // Replace basedir part of file path plus slash.
74 filepath = filepath.replace(0, m_basedir.length() + 1, "");
75 m_levels.push_back(filepath);
76 }
77 }
78 }
79 PHYSFS_freeList(files);
80}
81
82/* EOF */
83