Load audio earlier in the process. Might save us some time
[supertux.git] / src / supertux / main.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 "supertux/main.hpp"
18
19 #include <config.h>
20 #include <version.h>
21
22 #include <SDL_image.h>
23 #include <boost/format.hpp>
24 #include <boost/optional.hpp>
25 #include <iostream>
26 #include <physfs.h>
27 #include <stdio.h>
28 #include <tinygettext/log.hpp>
29 extern "C" {
30 #include <findlocale.h>
31 }
32
33 #include "addon/addon_manager.hpp"
34 #include "audio/sound_manager.hpp"
35 #include "control/input_manager.hpp"
36 #include "math/random_generator.hpp"
37 #include "physfs/ifile_stream.hpp"
38 #include "physfs/physfs_file_system.hpp"
39 #include "physfs/physfs_sdl.hpp"
40 #include "scripting/squirrel_util.hpp"
41 #include "scripting/scripting.hpp"
42 #include "sprite/sprite_manager.hpp"
43 #include "supertux/command_line_arguments.hpp"
44 #include "supertux/game_manager.hpp"
45 #include "supertux/gameconfig.hpp"
46 #include "supertux/globals.hpp"
47 #include "supertux/player_status.hpp"
48 #include "supertux/resources.hpp"
49 #include "supertux/screen_fade.hpp"
50 #include "supertux/screen_manager.hpp"
51 #include "supertux/title_screen.hpp"
52 #include "util/file_system.hpp"
53 #include "util/gettext.hpp"
54 #include "video/drawing_context.hpp"
55 #include "video/lightmap.hpp"
56 #include "video/renderer.hpp"
57 #include "worldmap/worldmap.hpp"
58
59 class ConfigSubsystem
60 {
61 public:
62   ConfigSubsystem()
63   {
64     g_config.reset(new Config);
65     try {
66       g_config->load();
67     }
68     catch(const std::exception& e)
69     {
70       log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
71     }
72
73     // init random number stuff
74     g_config->random_seed = gameRandom.srand(g_config->random_seed);
75     graphicsRandom.srand(0);
76     //const char *how = config->random_seed? ", user fixed.": ", from time().";
77     //log_info << "Using random seed " << config->random_seed << how << std::endl;
78   }
79
80   ~ConfigSubsystem()
81   {
82     if (g_config)
83     {
84       g_config->save();
85     }
86     g_config.reset();
87   }
88 };
89
90 void
91 Main::init_tinygettext()
92 {
93   g_dictionary_manager.reset(new tinygettext::DictionaryManager);
94   tinygettext::Log::set_log_info_callback(0);
95   g_dictionary_manager->set_filesystem(std::unique_ptr<tinygettext::FileSystem>(new PhysFSFileSystem));
96
97   g_dictionary_manager->add_directory("locale");
98   g_dictionary_manager->set_charset("UTF-8");
99
100   // Config setting "locale" overrides language detection
101   if (g_config->locale != "")
102   {
103     g_dictionary_manager->set_language(tinygettext::Language::from_name(g_config->locale));
104   }
105   else
106   {
107     FL_Locale *locale;
108     FL_FindLocale(&locale);
109     tinygettext::Language language = tinygettext::Language::from_spec( locale->lang?locale->lang:"", locale->country?locale->country:"", locale->variant?locale->variant:"");
110     FL_FreeLocale(&locale);
111     g_dictionary_manager->set_language(language);
112   }
113 }
114
115 class PhysfsSubsystem
116 {
117 private:
118   boost::optional<std::string> m_forced_datadir;
119   boost::optional<std::string> m_forced_userdir;
120
121 public:
122   PhysfsSubsystem(const char* argv0,
123                   boost::optional<std::string> forced_datadir,
124                   boost::optional<std::string> forced_userdir) :
125     m_forced_datadir(forced_datadir),
126     m_forced_userdir(forced_userdir)
127   {
128     if (!PHYSFS_init(argv0))
129     {
130       std::stringstream msg;
131       msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
132       throw std::runtime_error(msg.str());
133     }
134     else
135     {
136       // allow symbolic links
137       PHYSFS_permitSymbolicLinks(1);
138
139       find_userdir();
140       find_datadir();
141     }
142   }
143
144   void find_datadir()
145   {
146     std::string datadir;
147     if (m_forced_datadir)
148     {
149       datadir = *m_forced_datadir;
150     }
151     else if (const char* env_datadir = getenv("SUPERTUX2_DATA_DIR"))
152     {
153       datadir = env_datadir;
154     }
155     else
156     {
157       // check if we run from source dir
158       char* basepath_c = SDL_GetBasePath();
159       std::string basepath = basepath_c;
160       SDL_free(basepath_c);
161
162       datadir = FileSystem::join(basepath, "data");
163       std::string testfname = FileSystem::join(datadir, "credits.txt");
164       if (!FileSystem::exists(testfname))
165       {
166         // if the game is not run from the source directory, try to find
167         // the global install location
168         datadir = datadir.substr(0, datadir.rfind(INSTALL_SUBDIR_BIN));
169         datadir = FileSystem::join(datadir, INSTALL_SUBDIR_SHARE);
170       }
171     }
172
173     if (!PHYSFS_addToSearchPath(datadir.c_str(), 1))
174     {
175       log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
176     }
177   }
178
179   void find_userdir()
180   {
181     std::string userdir;
182     if (m_forced_userdir)
183     {
184       userdir = *m_forced_userdir;
185     }
186     else if (const char* env_userdir = getenv("SUPERTUX2_USER_DIR"))
187     {
188       userdir = env_userdir;
189     }
190     else
191     {
192       std::string physfs_userdir = PHYSFS_getUserDir();
193 #ifdef _WIN32
194       userdir = FileSystem::join(physfs_userdir, PACKAGE_NAME);
195 #else
196       userdir = FileSystem::join(physfs_userdir, "." PACKAGE_NAME);
197 #endif
198     }
199
200     if (!FileSystem::is_directory(userdir))
201     {
202       FileSystem::mkdir(userdir);
203       log_info << "Created SuperTux userdir: " << userdir << std::endl;
204     }
205
206     if (!PHYSFS_setWriteDir(userdir.c_str()))
207     {
208       std::ostringstream msg;
209       msg << "Failed to use userdir directory '"
210           <<  userdir << "': " << PHYSFS_getLastError();
211       throw std::runtime_error(msg.str());
212     }
213
214     PHYSFS_addToSearchPath(userdir.c_str(), 0);
215   }
216
217   void print_search_path()
218   {
219     const char* writedir = PHYSFS_getWriteDir();
220     log_info << "PhysfsWritedDir: " << (writedir ? writedir : "(null)") << std::endl;
221     log_info << "PhysfsSearchPath:" << std::endl;
222     char** searchpath = PHYSFS_getSearchPath();
223     for(char** i = searchpath; *i != NULL; ++i)
224     {
225       log_info << "  " << *i << std::endl;
226     }
227     PHYSFS_freeList(searchpath);
228   }
229
230   ~PhysfsSubsystem()
231   {
232     PHYSFS_deinit();
233   }
234 };
235
236 class SDLSubsystem
237 {
238 public:
239   SDLSubsystem()
240   {
241     if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER) < 0)
242     {
243       std::stringstream msg;
244       msg << "Couldn't initialize SDL: " << SDL_GetError();
245       throw std::runtime_error(msg.str());
246     }
247     // just to be sure
248     atexit(SDL_Quit);
249   }
250
251   ~SDLSubsystem()
252   {
253     SDL_Quit();
254   }
255 };
256
257 void
258 Main::init_video()
259 {
260   SDL_SetWindowTitle(VideoSystem::current()->get_renderer().get_window(), PACKAGE_NAME " " PACKAGE_VERSION);
261
262   const char* icon_fname = "images/engine/icons/supertux-256x256.png";
263   SDL_Surface* icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
264   if (!icon)
265   {
266     log_warning << "Couldn't load icon '" << icon_fname << "': " << SDL_GetError() << std::endl;
267   }
268   else
269   {
270     SDL_SetWindowIcon(VideoSystem::current()->get_renderer().get_window(), icon);
271     SDL_FreeSurface(icon);
272   }
273   SDL_ShowCursor(0);
274
275   log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
276            << " Window: "     << g_config->window_size
277            << " Fullscreen: " << g_config->fullscreen_size << "@" << g_config->fullscreen_refresh_rate
278            << " Area: "       << g_config->aspect_size << std::endl;
279 }
280
281 static Uint32 last_timelog_ticks = 0;
282 static const char* last_timelog_component = 0;
283
284 static inline void timelog(const char* component)
285 {
286   Uint32 current_ticks = SDL_GetTicks();
287
288   if(last_timelog_component != 0) {
289     log_info << "Component '" << last_timelog_component <<  "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
290   }
291
292   last_timelog_ticks = current_ticks;
293   last_timelog_component = component;
294 }
295
296 void
297 Main::launch_game()
298 {
299   SDLSubsystem sdl_subsystem;
300   ConsoleBuffer console_buffer;
301
302   timelog("audio");
303   SoundManager sound_manager;
304   sound_manager.enable_sound(g_config->sound_enabled);
305   sound_manager.enable_music(g_config->music_enabled);
306
307   timelog("controller");
308   InputManager input_manager(g_config->keyboard_config, g_config->joystick_config);
309
310   timelog("commandline");
311
312   timelog("video");
313   std::unique_ptr<VideoSystem> video_system = VideoSystem::create(g_config->video);
314   DrawingContext context(*video_system);
315   init_video();
316
317   Console console(console_buffer);
318
319   timelog("scripting");
320   scripting::Scripting scripting(g_config->enable_script_debugger);
321
322   timelog("resources");
323   TileManager tile_manager;
324   SpriteManager sprite_manager;
325   Resources resources;
326
327   timelog("addons");
328   AddonManager addon_manager("addons", g_config->addons);
329
330   timelog(0);
331
332   const std::unique_ptr<Savegame> default_savegame(new Savegame(std::string()));
333
334   GameManager game_manager;
335   ScreenManager screen_manager;
336
337   if(g_config->start_level != "") {
338     // we have a normal path specified at commandline, not a physfs path.
339     // So we simply mount that path here...
340     std::string dir = FileSystem::dirname(g_config->start_level);
341     std::string fileProtocol = "file://";
342     std::string::size_type position = dir.find(fileProtocol);
343     if(position != std::string::npos) {
344       dir = dir.replace(position, fileProtocol.length(), "");
345     }
346     log_debug << "Adding dir: " << dir << std::endl;
347     PHYSFS_addToSearchPath(dir.c_str(), true);
348
349     if(g_config->start_level.size() > 4 &&
350        g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0)
351     {
352       screen_manager.push_screen(std::unique_ptr<Screen>(
353                                               new worldmap::WorldMap(
354                                                 FileSystem::basename(g_config->start_level), *default_savegame)));
355     } else {
356       std::unique_ptr<GameSession> session (
357         new GameSession(FileSystem::basename(g_config->start_level), *default_savegame));
358
359       g_config->random_seed = session->get_demo_random_seed(g_config->start_demo);
360       g_config->random_seed = gameRandom.srand(g_config->random_seed);
361       graphicsRandom.srand(0);
362
363       if(g_config->start_demo != "")
364         session->play_demo(g_config->start_demo);
365
366       if(g_config->record_demo != "")
367         session->record_demo(g_config->record_demo);
368       screen_manager.push_screen(std::move(session));
369     }
370   } else {
371     screen_manager.push_screen(std::unique_ptr<Screen>(new TitleScreen(*default_savegame)));
372   }
373
374   screen_manager.run(context);
375 }
376
377 int
378 Main::run(int argc, char** argv)
379 {
380   int result = 0;
381
382   try
383   {
384     CommandLineArguments args;
385
386     try
387     {
388       args.parse_args(argc, argv);
389       g_log_level = args.get_log_level();
390     }
391     catch(const std::exception& err)
392     {
393       std::cout << "Error: " << err.what() << std::endl;
394       return EXIT_FAILURE;
395     }
396
397     PhysfsSubsystem physfs_subsystem(argv[0], args.datadir, args.userdir);
398     physfs_subsystem.print_search_path();
399
400     timelog("config");
401     ConfigSubsystem config_subsystem;
402     args.merge_into(*g_config);
403
404     timelog("tinygettext");
405     init_tinygettext();
406
407     switch (args.get_action())
408     {
409       case CommandLineArguments::PRINT_VERSION:
410         args.print_version();
411         return 0;
412
413       case CommandLineArguments::PRINT_HELP:
414         args.print_help(argv[0]);
415         return 0;
416
417       case CommandLineArguments::PRINT_DATADIR:
418         args.print_datadir();
419         return 0;
420
421       default:
422         launch_game();
423         break;
424     }
425   }
426   catch(const std::exception& e)
427   {
428     log_fatal << "Unexpected exception: " << e.what() << std::endl;
429     result = 1;
430   }
431   catch(...)
432   {
433     log_fatal << "Unexpected exception" << std::endl;
434     result = 1;
435   }
436
437   g_dictionary_manager.reset();
438
439   return result;
440 }
441
442 /* EOF */