05acd7390ba1b4c6404761a512a46031f39c2601
[supertux.git] / src / supertux / world.cpp
1 //  SuperTux
2 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
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 <algorithm>
18
19 #include "lisp/parser.hpp"
20 #include "lisp/writer.hpp"
21 #include "physfs/ifile_streambuf.hpp"
22 #include "scripting/serialize.hpp"
23 #include "scripting/squirrel_util.hpp"
24 #include "supertux/globals.hpp"
25 #include "supertux/screen_fade.hpp"
26 #include "supertux/screen_manager.hpp"
27 #include "supertux/player_status.hpp"
28 #include "supertux/world.hpp"
29 #include "util/file_system.hpp"
30 #include "util/reader.hpp"
31 #include "util/string_util.hpp"
32 #include "worldmap/worldmap.hpp"
33
34 World::World() :
35   m_worldmap_filename(),
36   levels(),
37   basedir(),
38   savegame_filename(),
39   world_thread(),
40   title(),
41   description(),
42   player_status(),
43   hide_from_contribs(),
44   is_levelset()
45 {
46   player_status.reset(new PlayerStatus());
47
48   is_levelset = true;
49   hide_from_contribs = false;
50   sq_resetobject(&world_thread);
51 }
52
53 World::~World()
54 {
55   sq_release(scripting::global_vm, &world_thread);
56 }
57
58 void
59 World::set_savegame_filename(const std::string& filename)
60 {
61   this->savegame_filename = filename;
62   // make sure the savegame directory exists
63   std::string dirname = FileSystem::dirname(filename);
64   if(!PHYSFS_exists(dirname.c_str())) {
65     if(!PHYSFS_mkdir(dirname.c_str())) {
66       std::ostringstream msg;
67       msg << "Couldn't create directory for savegames '"
68           << dirname << "': " <<PHYSFS_getLastError();
69       throw std::runtime_error(msg.str());
70     }
71   }
72
73   if(!PHYSFS_isDirectory(dirname.c_str())) {
74     std::ostringstream msg;
75     msg << "Savegame path '" << dirname << "' is not a directory";
76     throw std::runtime_error(msg.str());
77   }
78 }
79
80 void
81 World::load(const std::string& filename)
82 {
83   basedir = FileSystem::dirname(filename);
84   m_worldmap_filename = basedir + "worldmap.stwm";
85
86   lisp::Parser parser;
87   const lisp::Lisp* root = parser.parse(filename);
88
89   const lisp::Lisp* info = root->get_lisp("supertux-world");
90   if(info == NULL)
91     info = root->get_lisp("supertux-level-subset");
92   if(info == NULL)
93     throw std::runtime_error("File is not a world or levelsubset file");
94
95   hide_from_contribs = false;
96   is_levelset = true;
97
98   info->get("title", title);
99   info->get("description", description);
100   info->get("levelset", is_levelset);
101   info->get("hide-from-contribs", hide_from_contribs);
102
103   // Level info file doesn't define any levels, so read the
104   // directory to see what we can find
105
106   std::string path = basedir;
107   char** files = PHYSFS_enumerateFiles(path.c_str());
108   if(!files) {
109     log_warning << "Couldn't read subset dir '" << path << "'" << std::endl;
110     return;
111   }
112
113   for(const char* const* filename = files; *filename != 0; ++filename) {
114     if(StringUtil::has_suffix(*filename, ".stl")) {
115       Level level;
116       level.fullpath = path + *filename;
117       level.name = *filename;
118       levels.push_back(level);
119     }
120   }
121   PHYSFS_freeList(files);
122
123   std::sort(levels.begin(), levels.end(),
124             [](const Level& lhs, const Level& rhs)
125             {
126               return StringUtil::numeric_less(lhs.fullpath, rhs.fullpath);
127             });
128 }
129
130 void
131 World::run()
132 {
133   // create new squirrel table for persistent game state
134   HSQUIRRELVM vm = scripting::global_vm;
135
136   sq_pushroottable(vm);
137   sq_pushstring(vm, "state", -1);
138   sq_newtable(vm);
139   if(SQ_FAILED(sq_createslot(vm, -3)))
140     throw scripting::SquirrelError(vm, "Couldn't create state table");
141   sq_pop(vm, 1);
142
143   load_state();
144
145   std::string filename = basedir + "/world.nut";
146   try {
147     IFileStreambuf ins(filename);
148     std::istream in(&ins);
149
150     sq_release(scripting::global_vm, &world_thread);
151     world_thread = scripting::create_thread(scripting::global_vm);
152     scripting::compile_and_run(scripting::object_to_vm(world_thread), in, filename);
153   } catch(std::exception& ) {
154     // fallback: try to load worldmap worldmap.stwm
155     using namespace worldmap;
156     g_screen_manager->push_screen(std::unique_ptr<Screen>(new WorldMap(basedir + "worldmap.stwm", get_player_status())));
157   }
158 }
159
160 void
161 World::save_state()
162 {
163   using namespace scripting;
164
165   lisp::Writer writer(savegame_filename);
166
167   writer.start_list("supertux-savegame");
168   writer.write("version", 1);
169
170   using namespace worldmap;
171   if(WorldMap::current() != NULL) {
172     std::ostringstream title;
173     title << WorldMap::current()->get_title();
174     title << " (" << WorldMap::current()->solved_level_count()
175           << "/" << WorldMap::current()->level_count() << ")";
176     writer.write("title", title.str());
177   }
178
179   writer.start_list("tux");
180   player_status->write(writer);
181   writer.end_list("tux");
182
183   writer.start_list("state");
184
185   sq_pushroottable(global_vm);
186   sq_pushstring(global_vm, "state", -1);
187   if(SQ_SUCCEEDED(sq_get(global_vm, -2))) {
188     scripting::save_squirrel_table(global_vm, -1, writer);
189     sq_pop(global_vm, 1);
190   }
191   sq_pop(global_vm, 1);
192   writer.end_list("state");
193
194   writer.end_list("supertux-savegame");
195 }
196
197 void
198 World::load_state()
199 {
200   using namespace scripting;
201
202   if(!PHYSFS_exists(savegame_filename.c_str()))
203   {
204     log_info << savegame_filename << ": doesn't exist, not loading state" << std::endl;
205   }
206   else
207   {
208     try {
209       lisp::Parser parser;
210       const lisp::Lisp* root = parser.parse(savegame_filename);
211
212       const lisp::Lisp* lisp = root->get_lisp("supertux-savegame");
213       if(lisp == NULL)
214         throw std::runtime_error("file is not a supertux-savegame file");
215
216       int version = 1;
217       lisp->get("version", version);
218       if(version != 1)
219         throw std::runtime_error("incompatible savegame version");
220
221       const lisp::Lisp* tux = lisp->get_lisp("tux");
222       if(tux == NULL)
223         throw std::runtime_error("No tux section in savegame");
224       player_status->read(*tux);
225
226       const lisp::Lisp* state = lisp->get_lisp("state");
227       if(state == NULL)
228         throw std::runtime_error("No state section in savegame");
229
230       sq_pushroottable(global_vm);
231       sq_pushstring(global_vm, "state", -1);
232       if(SQ_FAILED(sq_deleteslot(global_vm, -2, SQFalse)))
233         sq_pop(global_vm, 1);
234
235       sq_pushstring(global_vm, "state", -1);
236       sq_newtable(global_vm);
237       load_squirrel_table(global_vm, -1, *state);
238       if(SQ_FAILED(sq_createslot(global_vm, -3)))
239         throw std::runtime_error("Couldn't create state table");
240       sq_pop(global_vm, 1);
241     } catch(std::exception& e) {
242       log_fatal << "Couldn't load savegame: " << e.what() << std::endl;
243     }
244   }
245 }
246
247 const std::string&
248 World::get_level_filename(unsigned int i) const
249 {
250   return levels[i].fullpath;
251 }
252
253 unsigned int
254 World::get_num_levels() const
255 {
256   return levels.size();
257 }
258
259 int
260 World::get_num_solved_levels() const
261 {
262   int num_solved_levels = 0;
263
264   HSQUIRRELVM vm = scripting::global_vm;
265   int oldtop = sq_gettop(vm);
266
267   sq_pushroottable(vm);
268   sq_pushstring(vm, "state", -1);
269   if(SQ_FAILED(sq_get(vm, -2)))
270   {
271     log_warning << "failed to get 'state' table" << std::endl;
272   }
273   else
274   {
275     sq_pushstring(vm, "worlds", -1);
276     if(SQ_FAILED(sq_get(vm, -2)))
277     {
278       log_warning << "failed to get 'state.worlds' table" << std::endl;
279     }
280     else
281     {
282       sq_pushstring(vm, m_worldmap_filename.c_str(), -1);
283       if(SQ_FAILED(sq_get(vm, -2)))
284       {
285         log_warning << "failed to get state.worlds['" << m_worldmap_filename << "']" << std::endl;
286       }
287       else
288       {
289         sq_pushstring(vm, "levels", -1);
290         if(SQ_FAILED(sq_get(vm, -2)))
291         {
292           log_warning << "failed to get state.worlds['" << m_worldmap_filename << "'].levels" << std::endl;
293         }
294         else
295         {
296           for(auto level : levels)
297           {
298             sq_pushstring(vm, level.name.c_str(), -1);
299             if(SQ_FAILED(sq_get(vm, -2)))
300             {
301               log_warning << "failed to get state.worlds['" << m_worldmap_filename << "'].levels['"
302                           << level.name << "']" << std::endl;
303             }
304             else
305             {
306               bool solved = scripting::read_bool(vm, "solved");
307               if (solved)
308               {
309                 num_solved_levels += 1;
310               }
311               sq_pop(vm, 1);
312             }
313           }
314         }
315       }
316     }
317   }
318
319   sq_settop(vm, oldtop);
320
321   return num_solved_levels;
322 }
323
324 const std::string&
325 World::get_basedir() const
326 {
327   return basedir;
328 }
329
330 const std::string&
331 World::get_title() const
332 {
333   return title;
334 }
335
336 /* EOF */