Only pause game on focus lose when game session is active
[supertux.git] / src / supertux / screen_manager.cpp
1 //  SuperTux
2 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
3 //                2014 Ingo Ruhnke <grumbel@gmail.com>
4 //
5 //  This program is free software: you can redistribute it and/or modify
6 //  it under the terms of the GNU General Public License as published by
7 //  the Free Software Foundation, either version 3 of the License, or
8 //  (at your option) any later version.
9 //
10 //  This program is distributed in the hope that it will be useful,
11 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
12 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 //  GNU General Public License for more details.
14 //
15 //  You should have received a copy of the GNU General Public License
16 //  along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18 #include "supertux/screen_manager.hpp"
19
20 #include "audio/sound_manager.hpp"
21 #include "control/input_manager.hpp"
22 #include "gui/menu.hpp"
23 #include "gui/menu_manager.hpp"
24 #include "scripting/scripting.hpp"
25 #include "scripting/squirrel_util.hpp"
26 #include "scripting/time_scheduler.hpp"
27 #include "supertux/console.hpp"
28 #include "supertux/constants.hpp"
29 #include "supertux/gameconfig.hpp"
30 #include "supertux/game_session.hpp"
31 #include "supertux/globals.hpp"
32 #include "supertux/main.hpp"
33 #include "supertux/menu/menu_storage.hpp"
34 #include "supertux/player_status.hpp"
35 #include "supertux/resources.hpp"
36 #include "supertux/screen.hpp"
37 #include "supertux/screen_fade.hpp"
38 #include "supertux/timer.hpp"
39 #include "video/drawing_context.hpp"
40 #include "video/renderer.hpp"
41
42 #include <stdio.h>
43 /** ticks (as returned from SDL_GetTicks) per frame */
44 static const Uint32 TICKS_PER_FRAME = (Uint32) (1000.0 / LOGICAL_FPS);
45 /** don't skip more than every 2nd frame */
46 static const int MAX_FRAME_SKIP = 2;
47
48 ScreenManager::ScreenManager() :
49   m_waiting_threads(),
50   m_menu_storage(new MenuStorage),
51   m_menu_manager(new MenuManager),
52   m_speed(1.0),
53   m_actions(),
54   m_fps(0),
55   m_screen_fade(),
56   m_screen_stack(),
57   m_screenshot_requested(false)
58 {
59   using namespace scripting;
60   TimeScheduler::instance = new TimeScheduler();
61 }
62
63 ScreenManager::~ScreenManager()
64 {
65   using namespace scripting;
66   delete TimeScheduler::instance;
67   TimeScheduler::instance = NULL;
68 }
69
70 void
71 ScreenManager::push_screen(std::unique_ptr<Screen> screen, std::unique_ptr<ScreenFade> screen_fade)
72 {
73   log_debug << "ScreenManager::push_screen(): " << screen.get() << std::endl;
74   assert(screen);
75
76   m_screen_fade = std::move(screen_fade);
77   m_actions.push_back(Action(Action::PUSH_ACTION, std::move(screen)));
78 }
79
80 void
81 ScreenManager::pop_screen(std::unique_ptr<ScreenFade> screen_fade)
82 {
83   log_debug << "ScreenManager::pop_screen(): stack_size: " << m_screen_stack.size() << std::endl;
84
85   m_screen_fade = std::move(screen_fade);
86   m_actions.push_back(Action(Action::POP_ACTION));
87 }
88
89 void
90 ScreenManager::set_screen_fade(std::unique_ptr<ScreenFade> screen_fade)
91 {
92   m_screen_fade = std::move(screen_fade);
93 }
94
95 void
96 ScreenManager::quit(std::unique_ptr<ScreenFade> screen_fade)
97 {
98   m_screen_fade = std::move(screen_fade);
99   m_actions.push_back(Action(Action::QUIT_ACTION));
100 }
101
102 void
103 ScreenManager::set_speed(float speed)
104 {
105   m_speed = speed;
106 }
107
108 float
109 ScreenManager::get_speed() const
110 {
111   return m_speed;
112 }
113
114 void
115 ScreenManager::draw_fps(DrawingContext& context, float fps_fps)
116 {
117   char str[60];
118   snprintf(str, sizeof(str), "%3.1f", fps_fps);
119   const char* fpstext = "FPS";
120   context.draw_text(Resources::small_font, fpstext,
121                     Vector(SCREEN_WIDTH - Resources::small_font->get_text_width(fpstext) - Resources::small_font->get_text_width(" 99999") - BORDER_X,
122                            BORDER_Y + 20), ALIGN_LEFT, LAYER_HUD);
123   context.draw_text(Resources::small_font, str, Vector(SCREEN_WIDTH - BORDER_X, BORDER_Y + 20), ALIGN_RIGHT, LAYER_HUD);
124 }
125
126 void
127 ScreenManager::draw(DrawingContext& context)
128 {
129   assert(!m_screen_stack.empty());
130
131   static Uint32 fps_ticks = SDL_GetTicks();
132
133   m_screen_stack.back()->draw(context);
134   m_menu_manager->draw(context);
135
136   if (m_screen_fade)
137   {
138     m_screen_fade->draw(context);
139   }
140
141   Console::current()->draw(context);
142
143   if (g_config->show_fps)
144   {
145     draw_fps(context, m_fps);
146   }
147
148   // if a screenshot was requested, pass request on to drawing_context
149   if (m_screenshot_requested)
150   {
151     context.take_screenshot();
152     m_screenshot_requested = false;
153   }
154   context.do_drawing();
155
156   /* Calculate frames per second */
157   if (g_config->show_fps)
158   {
159     static int frame_count = 0;
160     ++frame_count;
161
162     if (SDL_GetTicks() - fps_ticks >= 500)
163     {
164       m_fps = (float) frame_count / .5;
165       frame_count = 0;
166       fps_ticks = SDL_GetTicks();
167     }
168   }
169 }
170
171 void
172 ScreenManager::update_gamelogic(float elapsed_time)
173 {
174   scripting::Scripting::current()->update_debugger();
175   scripting::TimeScheduler::instance->update(game_time);
176
177   if (!m_screen_stack.empty())
178   {
179     m_screen_stack.back()->update(elapsed_time);
180   }
181
182   m_menu_manager->process_input();
183
184   if (m_screen_fade)
185   {
186     m_screen_fade->update(elapsed_time);
187   }
188
189   Console::current()->update(elapsed_time);
190 }
191
192 void
193 ScreenManager::process_events()
194 {
195   InputManager::current()->update();
196   SDL_Event event;
197   while (SDL_PollEvent(&event))
198   {
199     InputManager::current()->process_event(event);
200
201     m_menu_manager->event(event);
202
203     switch(event.type)
204     {
205       case SDL_QUIT:
206         quit();
207         break;
208
209       case SDL_WINDOWEVENT:
210         switch(event.window.event)
211         {
212           case SDL_WINDOWEVENT_RESIZED:
213             VideoSystem::current()->resize(event.window.data1,
214                                            event.window.data2);
215             m_menu_manager->on_window_resize();
216             break;
217
218           case SDL_WINDOWEVENT_FOCUS_LOST:
219             if(GameSession::current() != NULL &&
220                GameSession::current()->is_active())
221             {
222               GameSession::current()->toggle_pause();
223             }
224             break;
225         }
226         break;
227
228       case SDL_KEYDOWN:
229         if (event.key.keysym.sym == SDLK_F10)
230         {
231           g_config->show_fps = !g_config->show_fps;
232         }
233         else if (event.key.keysym.sym == SDLK_F11)
234         {
235           g_config->use_fullscreen = !g_config->use_fullscreen;
236           VideoSystem::current()->apply_config();
237           m_menu_manager->on_window_resize();
238         }
239         else if (event.key.keysym.sym == SDLK_PRINTSCREEN ||
240                  event.key.keysym.sym == SDLK_F12)
241         {
242           take_screenshot();
243         }
244         else if (event.key.keysym.sym == SDLK_F1 &&
245                  event.key.keysym.mod & KMOD_CTRL)
246         {
247           Console::current()->toggle();
248           g_config->console_enabled = true;
249           g_config->save();
250         }
251         else if (event.key.keysym.sym == SDLK_F2 &&
252                  event.key.keysym.mod & KMOD_CTRL)
253         {
254           g_config->developer_mode = !g_config->developer_mode;
255           log_info << "developer mode: " << g_config->developer_mode << std::endl;
256         }
257         break;
258     }
259   }
260 }
261
262 bool
263 ScreenManager::has_pending_fadeout() const
264 {
265   return m_screen_fade && !m_screen_fade->done();
266 }
267
268 void
269 ScreenManager::handle_screen_switch()
270 {
271   if (has_pending_fadeout())
272   {
273     // wait till the fadeout is completed before switching screens
274   }
275   else
276   {
277     m_screen_fade.reset();
278
279     // keep track of the current screen, as only that needs a call to Screen::leave()
280     Screen* current_screen = m_screen_stack.empty() ? nullptr : m_screen_stack.back().get();
281
282     // Screen::setup() might push more screens, so loop till everything is done
283     while (!m_actions.empty())
284     {
285       // move actions to a new vector since setup() might modify it
286       auto actions = std::move(m_actions);
287
288       for(auto it = actions.begin(); it != actions.end(); ++it)
289       {
290         auto& action = *it;
291
292         switch (action.type)
293         {
294           case Action::POP_ACTION:
295             assert(!m_screen_stack.empty());
296             if (current_screen == m_screen_stack.back().get())
297             {
298               m_screen_stack.back()->leave();
299             }
300             m_screen_stack.pop_back();
301             break;
302
303           case Action::PUSH_ACTION:
304             assert(action.screen);
305
306             if (!m_screen_stack.empty())
307             {
308               if (current_screen == m_screen_stack.back().get())
309               {
310                 m_screen_stack.back()->leave();
311               }
312             }
313             m_screen_stack.push_back(std::move(action.screen));
314             break;
315
316           case Action::QUIT_ACTION:
317             m_screen_stack.clear();
318             break;
319         }
320       }
321
322       if (!m_screen_stack.empty())
323       {
324         m_screen_stack.back()->setup();
325         m_speed = 1.0;
326         m_waiting_threads.wakeup();
327       }
328     }
329   }
330 }
331
332 void
333 ScreenManager::run(DrawingContext &context)
334 {
335   Uint32 last_ticks = 0;
336   Uint32 elapsed_ticks = 0;
337
338   handle_screen_switch();
339
340   while (!m_screen_stack.empty())
341   {
342     Uint32 ticks = SDL_GetTicks();
343     elapsed_ticks += ticks - last_ticks;
344     last_ticks = ticks;
345
346     Uint32 ticks_per_frame = (Uint32) (TICKS_PER_FRAME * g_game_speed);
347
348     if (elapsed_ticks > ticks_per_frame*4)
349     {
350       // when the game loads up or levels are switched the
351       // elapsed_ticks grows extremely large, so we just ignore those
352       // large time jumps
353       elapsed_ticks = 0;
354     }
355
356     if (elapsed_ticks < ticks_per_frame)
357     {
358       Uint32 delay_ticks = ticks_per_frame - elapsed_ticks;
359       SDL_Delay(delay_ticks);
360       last_ticks += delay_ticks;
361       elapsed_ticks += delay_ticks;
362     }
363
364     int frames = 0;
365
366     while (elapsed_ticks >= ticks_per_frame && frames < MAX_FRAME_SKIP)
367     {
368       elapsed_ticks -= ticks_per_frame;
369       float timestep = 1.0 / LOGICAL_FPS;
370       real_time += timestep;
371       timestep *= m_speed;
372       game_time += timestep;
373
374       process_events();
375       update_gamelogic(timestep);
376       frames += 1;
377     }
378
379     if (!m_screen_stack.empty())
380     {
381       draw(context);
382     }
383
384     SoundManager::current()->update();
385
386     handle_screen_switch();
387   }
388 }
389
390 void
391 ScreenManager::take_screenshot()
392 {
393   m_screenshot_requested = true;
394 }
395
396 /* EOF */