OpenTTD
sdl_v.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6  */
7 
10 #ifdef WITH_SDL
11 
12 #include "../stdafx.h"
13 #include "../openttd.h"
14 #include "../gfx_func.h"
15 #include "../rev.h"
16 #include "../blitter/factory.hpp"
17 #include "../network/network.h"
18 #include "../thread.h"
19 #include "../progress.h"
20 #include "../core/random_func.hpp"
21 #include "../core/math_func.hpp"
22 #include "../fileio_func.h"
23 #include "../framerate_type.h"
24 #include "sdl_v.h"
25 #include <SDL.h>
26 #include <mutex>
27 #include <condition_variable>
28 #include <algorithm>
29 
30 #include "../safeguards.h"
31 
32 static FVideoDriver_SDL iFVideoDriver_SDL;
33 
34 static SDL_Surface *_sdl_screen;
35 static SDL_Surface *_sdl_realscreen;
36 static bool _all_modes;
37 
39 static bool _draw_threaded;
41 static std::recursive_mutex *_draw_mutex = nullptr;
43 static std::condition_variable_any *_draw_signal = nullptr;
45 static volatile bool _draw_continue;
46 static Palette _local_palette;
47 
48 #define MAX_DIRTY_RECTS 100
49 static SDL_Rect _dirty_rects[MAX_DIRTY_RECTS];
50 static int _num_dirty_rects;
51 static int _use_hwpalette;
52 static int _requested_hwpalette; /* Did we request a HWPALETTE for the current video mode? */
53 
54 void VideoDriver_SDL::MakeDirty(int left, int top, int width, int height)
55 {
56  if (_num_dirty_rects < MAX_DIRTY_RECTS) {
57  _dirty_rects[_num_dirty_rects].x = left;
58  _dirty_rects[_num_dirty_rects].y = top;
59  _dirty_rects[_num_dirty_rects].w = width;
60  _dirty_rects[_num_dirty_rects].h = height;
61  }
62  _num_dirty_rects++;
63 }
64 
65 static void UpdatePalette(bool init = false)
66 {
67  SDL_Color pal[256];
68 
69  for (int i = 0; i != _local_palette.count_dirty; i++) {
70  pal[i].r = _local_palette.palette[_local_palette.first_dirty + i].r;
71  pal[i].g = _local_palette.palette[_local_palette.first_dirty + i].g;
72  pal[i].b = _local_palette.palette[_local_palette.first_dirty + i].b;
73  pal[i].unused = 0;
74  }
75 
76  SDL_SetColors(_sdl_screen, pal, _local_palette.first_dirty, _local_palette.count_dirty);
77 
78  if (_sdl_screen != _sdl_realscreen && init) {
79  /* When using a shadow surface, also set our palette on the real screen. This lets SDL
80  * allocate as much colors (or approximations) as
81  * possible, instead of using only the default SDL
82  * palette. This allows us to get more colors exactly
83  * right and might allow using better approximations for
84  * other colors.
85  *
86  * Note that colors allocations are tried in-order, so
87  * this favors colors further up into the palette. Also
88  * note that if two colors from the same animation
89  * sequence are approximated using the same color, that
90  * animation will stop working.
91  *
92  * Since changing the system palette causes the colours
93  * to change right away, and allocations might
94  * drastically change, we can't use this for animation,
95  * since that could cause weird coloring between the
96  * palette change and the blitting below, so we only set
97  * the real palette during initialisation.
98  */
99  SDL_SetColors(_sdl_realscreen, pal, _local_palette.first_dirty, _local_palette.count_dirty);
100  }
101 
102  if (_sdl_screen != _sdl_realscreen && !init) {
103  /* We're not using real hardware palette, but are letting SDL
104  * approximate the palette during shadow -> screen copy. To
105  * change the palette, we need to recopy the entire screen.
106  *
107  * Note that this operation can slow down the rendering
108  * considerably, especially since changing the shadow
109  * palette will need the next blit to re-detect the
110  * best mapping of shadow palette colors to real palette
111  * colors from scratch.
112  */
113  SDL_BlitSurface(_sdl_screen, nullptr, _sdl_realscreen, nullptr);
114  SDL_UpdateRect(_sdl_realscreen, 0, 0, 0, 0);
115  }
116 }
117 
118 static void InitPalette()
119 {
120  _local_palette = _cur_palette;
121  _local_palette.first_dirty = 0;
122  _local_palette.count_dirty = 256;
123  UpdatePalette(true);
124 }
125 
126 static void CheckPaletteAnim()
127 {
128  if (_cur_palette.count_dirty != 0) {
130 
131  switch (blitter->UsePaletteAnimation()) {
133  UpdatePalette();
134  break;
135 
137  blitter->PaletteAnimate(_local_palette);
138  break;
139 
141  break;
142 
143  default:
144  NOT_REACHED();
145  }
147  }
148 }
149 
150 static void DrawSurfaceToScreen()
151 {
152  PerformanceMeasurer framerate(PFE_VIDEO);
153 
154  int n = _num_dirty_rects;
155  if (n == 0) return;
156 
157  _num_dirty_rects = 0;
158  if (n > MAX_DIRTY_RECTS) {
159  if (_sdl_screen != _sdl_realscreen) {
160  SDL_BlitSurface(_sdl_screen, nullptr, _sdl_realscreen, nullptr);
161  }
162  SDL_UpdateRect(_sdl_realscreen, 0, 0, 0, 0);
163  } else {
164  if (_sdl_screen != _sdl_realscreen) {
165  for (int i = 0; i < n; i++) {
166  SDL_BlitSurface(_sdl_screen, &_dirty_rects[i], _sdl_realscreen, &_dirty_rects[i]);
167  }
168  }
169  SDL_UpdateRects(_sdl_realscreen, n, _dirty_rects);
170  }
171 }
172 
173 static void DrawSurfaceToScreenThread()
174 {
175  /* First tell the main thread we're started */
176  std::unique_lock<std::recursive_mutex> lock(*_draw_mutex);
177  _draw_signal->notify_one();
178 
179  /* Now wait for the first thing to draw! */
180  _draw_signal->wait(*_draw_mutex);
181 
182  while (_draw_continue) {
183  CheckPaletteAnim();
184  /* Then just draw and wait till we stop */
185  DrawSurfaceToScreen();
186  _draw_signal->wait(lock);
187  }
188 }
189 
190 static const Dimension _default_resolutions[] = {
191  { 640, 480},
192  { 800, 600},
193  {1024, 768},
194  {1152, 864},
195  {1280, 800},
196  {1280, 960},
197  {1280, 1024},
198  {1400, 1050},
199  {1600, 1200},
200  {1680, 1050},
201  {1920, 1200}
202 };
203 
204 static void GetVideoModes()
205 {
206  SDL_Rect **modes = SDL_ListModes(nullptr, SDL_SWSURFACE | SDL_FULLSCREEN);
207  if (modes == nullptr) usererror("sdl: no modes available");
208 
209  _resolutions.clear();
210 
211  _all_modes = (SDL_ListModes(nullptr, SDL_SWSURFACE | (_fullscreen ? SDL_FULLSCREEN : 0)) == (void*)-1);
212  if (modes == (void*)-1) {
213  for (uint i = 0; i < lengthof(_default_resolutions); i++) {
214  if (SDL_VideoModeOK(_default_resolutions[i].width, _default_resolutions[i].height, 8, SDL_FULLSCREEN) != 0) {
215  _resolutions.push_back(_default_resolutions[i]);
216  }
217  }
218  } else {
219  for (int i = 0; modes[i]; i++) {
220  uint w = modes[i]->w;
221  uint h = modes[i]->h;
222  if (w < 640 || h < 480) continue; // reject too small resolutions
223  if (std::find(_resolutions.begin(), _resolutions.end(), Dimension(w, h)) != _resolutions.end()) continue;
224  _resolutions.emplace_back(w, h);
225  }
226  if (_resolutions.empty()) usererror("No usable screen resolutions found!\n");
227  SortResolutions();
228  }
229 }
230 
231 static void GetAvailableVideoMode(uint *w, uint *h)
232 {
233  /* All modes available? */
234  if (_all_modes || _resolutions.empty()) return;
235 
236  /* Is the wanted mode among the available modes? */
237  if (std::find(_resolutions.begin(), _resolutions.end(), Dimension(*w, *h)) != _resolutions.end()) return;
238 
239  /* Use the closest possible resolution */
240  uint best = 0;
241  uint delta = Delta(_resolutions[0].width, *w) * Delta(_resolutions[0].height, *h);
242  for (uint i = 1; i != _resolutions.size(); ++i) {
243  uint newdelta = Delta(_resolutions[i].width, *w) * Delta(_resolutions[i].height, *h);
244  if (newdelta < delta) {
245  best = i;
246  delta = newdelta;
247  }
248  }
249  *w = _resolutions[best].width;
250  *h = _resolutions[best].height;
251 }
252 
253 bool VideoDriver_SDL::CreateMainSurface(uint w, uint h)
254 {
255  SDL_Surface *newscreen, *icon;
256  char caption[50];
258  bool want_hwpalette;
259 
260  GetAvailableVideoMode(&w, &h);
261 
262  DEBUG(driver, 1, "SDL: using mode %ux%ux%d", w, h, bpp);
263 
264  if (bpp == 0) usererror("Can't use a blitter that blits 0 bpp for normal visuals");
265 
266  char icon_path[MAX_PATH];
267  if (FioFindFullPath(icon_path, lastof(icon_path), BASESET_DIR, "openttd.32.bmp") != nullptr) {
268  /* Give the application an icon */
269  icon = SDL_LoadBMP(icon_path);
270  if (icon != nullptr) {
271  /* Get the colourkey, which will be magenta */
272  uint32 rgbmap = SDL_MapRGB(icon->format, 255, 0, 255);
273 
274  SDL_SetColorKey(icon, SDL_SRCCOLORKEY, rgbmap);
275  SDL_WM_SetIcon(icon, nullptr);
276  SDL_FreeSurface(icon);
277  }
278  }
279 
280  if (_use_hwpalette == 2) {
281  /* Default is to autodetect when to use SDL_HWPALETTE.
282  * In this case, SDL_HWPALETTE is only used for 8bpp
283  * blitters in fullscreen.
284  *
285  * When using an 8bpp blitter on a 8bpp system in
286  * windowed mode with SDL_HWPALETTE, OpenTTD will claim
287  * the system palette, making all other applications
288  * get the wrong colours. In this case, we're better of
289  * trying to approximate the colors we need using system
290  * colors, using a shadow surface (see below).
291  *
292  * On a 32bpp system, SDL_HWPALETTE is ignored, so it
293  * doesn't matter what we do.
294  *
295  * When using a 32bpp blitter on a 8bpp system, setting
296  * SDL_HWPALETTE messes up rendering (at least on X11),
297  * so we don't do that. In this case, SDL takes care of
298  * color approximation using its own shadow surface
299  * (which we can't force in 8bpp on 8bpp mode,
300  * unfortunately).
301  */
302  want_hwpalette = bpp == 8 && _fullscreen && _support8bpp == S8BPP_HARDWARE;
303  } else {
304  /* User specified a value manually */
305  want_hwpalette = _use_hwpalette;
306  }
307 
308  if (want_hwpalette) DEBUG(driver, 1, "SDL: requesting hardware palette");
309 
310  /* Free any previously allocated shadow surface */
311  if (_sdl_screen != nullptr && _sdl_screen != _sdl_realscreen) SDL_FreeSurface(_sdl_screen);
312 
313  if (_sdl_realscreen != nullptr) {
314  if (_requested_hwpalette != want_hwpalette) {
315  /* SDL (at least the X11 driver), reuses the
316  * same window and palette settings when the bpp
317  * (and a few flags) are the same. Since we need
318  * to hwpalette value to change (in particular
319  * when switching between fullscreen and
320  * windowed), we restart the entire video
321  * subsystem to force creating a new window.
322  */
323  DEBUG(driver, 0, "SDL: Restarting SDL video subsystem, to force hwpalette change");
324  SDL_QuitSubSystem(SDL_INIT_VIDEO);
325  SDL_InitSubSystem(SDL_INIT_VIDEO);
326  ClaimMousePointer();
327  SetupKeyboard();
328  }
329  }
330  /* Remember if we wanted a hwpalette. We can't reliably query
331  * SDL for the SDL_HWPALETTE flag, since it might get set even
332  * though we didn't ask for it (when SDL creates a shadow
333  * surface, for example). */
334  _requested_hwpalette = want_hwpalette;
335 
336  /* DO NOT CHANGE TO HWSURFACE, IT DOES NOT WORK */
337  newscreen = SDL_SetVideoMode(w, h, bpp, SDL_SWSURFACE | (want_hwpalette ? SDL_HWPALETTE : 0) | (_fullscreen ? SDL_FULLSCREEN : SDL_RESIZABLE));
338  if (newscreen == nullptr) {
339  DEBUG(driver, 0, "SDL: Couldn't allocate a window to draw on");
340  return false;
341  }
342  _sdl_realscreen = newscreen;
343 
344  if (bpp == 8 && (_sdl_realscreen->flags & SDL_HWPALETTE) != SDL_HWPALETTE) {
345  /* Using an 8bpp blitter, if we didn't get a hardware
346  * palette (most likely because we didn't request one,
347  * see above), we'll have to set up a shadow surface to
348  * render on.
349  *
350  * Our palette will be applied to this shadow surface,
351  * while the real screen surface will use the shared
352  * system palette (which will partly contain our colors,
353  * but most likely will not have enough free color cells
354  * for all of our colors). SDL can use these two
355  * palettes at blit time to approximate colors used in
356  * the shadow surface using system colors automatically.
357  *
358  * Note that when using an 8bpp blitter on a 32bpp
359  * system, SDL will create an internal shadow surface.
360  * This shadow surface will have SDL_HWPALLETE set, so
361  * we won't create a second shadow surface in this case.
362  */
363  DEBUG(driver, 1, "SDL: using shadow surface");
364  newscreen = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, bpp, 0, 0, 0, 0);
365  if (newscreen == nullptr) {
366  DEBUG(driver, 0, "SDL: Couldn't allocate a shadow surface to draw on");
367  return false;
368  }
369  }
370 
371  /* Delay drawing for this cycle; the next cycle will redraw the whole screen */
372  _num_dirty_rects = 0;
373 
374  _screen.width = newscreen->w;
375  _screen.height = newscreen->h;
376  _screen.pitch = newscreen->pitch / (bpp / 8);
377  _screen.dst_ptr = newscreen->pixels;
378  _sdl_screen = newscreen;
379 
380  /* When in full screen, we will always have the mouse cursor
381  * within the window, even though SDL does not give us the
382  * appropriate event to know this. */
383  if (_fullscreen) _cursor.in_window = true;
384 
386  blitter->PostResize();
387 
388  InitPalette();
389 
390  seprintf(caption, lastof(caption), "OpenTTD %s", _openttd_revision);
391  SDL_WM_SetCaption(caption, caption);
392 
393  GameSizeChanged();
394 
395  return true;
396 }
397 
398 bool VideoDriver_SDL::ClaimMousePointer()
399 {
400  SDL_ShowCursor(0);
401  return true;
402 }
403 
404 struct VkMapping {
405 #if SDL_VERSION_ATLEAST(1, 3, 0)
406  SDL_Keycode vk_from;
407 #else
408  uint16 vk_from;
409 #endif
410  byte vk_count;
411  byte map_to;
412 };
413 
414 #define AS(x, z) {x, 0, z}
415 #define AM(x, y, z, w) {x, (byte)(y - x), z}
416 
417 static const VkMapping _vk_mapping[] = {
418  /* Pageup stuff + up/down */
419  AM(SDLK_PAGEUP, SDLK_PAGEDOWN, WKC_PAGEUP, WKC_PAGEDOWN),
420  AS(SDLK_UP, WKC_UP),
421  AS(SDLK_DOWN, WKC_DOWN),
422  AS(SDLK_LEFT, WKC_LEFT),
423  AS(SDLK_RIGHT, WKC_RIGHT),
424 
425  AS(SDLK_HOME, WKC_HOME),
426  AS(SDLK_END, WKC_END),
427 
428  AS(SDLK_INSERT, WKC_INSERT),
429  AS(SDLK_DELETE, WKC_DELETE),
430 
431  /* Map letters & digits */
432  AM(SDLK_a, SDLK_z, 'A', 'Z'),
433  AM(SDLK_0, SDLK_9, '0', '9'),
434 
435  AS(SDLK_ESCAPE, WKC_ESC),
436  AS(SDLK_PAUSE, WKC_PAUSE),
437  AS(SDLK_BACKSPACE, WKC_BACKSPACE),
438 
439  AS(SDLK_SPACE, WKC_SPACE),
440  AS(SDLK_RETURN, WKC_RETURN),
441  AS(SDLK_TAB, WKC_TAB),
442 
443  /* Function keys */
444  AM(SDLK_F1, SDLK_F12, WKC_F1, WKC_F12),
445 
446  /* Numeric part. */
447  AM(SDLK_KP0, SDLK_KP9, '0', '9'),
448  AS(SDLK_KP_DIVIDE, WKC_NUM_DIV),
449  AS(SDLK_KP_MULTIPLY, WKC_NUM_MUL),
450  AS(SDLK_KP_MINUS, WKC_NUM_MINUS),
451  AS(SDLK_KP_PLUS, WKC_NUM_PLUS),
452  AS(SDLK_KP_ENTER, WKC_NUM_ENTER),
453  AS(SDLK_KP_PERIOD, WKC_NUM_DECIMAL),
454 
455  /* Other non-letter keys */
456  AS(SDLK_SLASH, WKC_SLASH),
457  AS(SDLK_SEMICOLON, WKC_SEMICOLON),
458  AS(SDLK_EQUALS, WKC_EQUALS),
459  AS(SDLK_LEFTBRACKET, WKC_L_BRACKET),
460  AS(SDLK_BACKSLASH, WKC_BACKSLASH),
461  AS(SDLK_RIGHTBRACKET, WKC_R_BRACKET),
462 
463  AS(SDLK_QUOTE, WKC_SINGLEQUOTE),
464  AS(SDLK_COMMA, WKC_COMMA),
465  AS(SDLK_MINUS, WKC_MINUS),
466  AS(SDLK_PERIOD, WKC_PERIOD)
467 };
468 
469 static uint ConvertSdlKeyIntoMy(SDL_keysym *sym, WChar *character)
470 {
471  const VkMapping *map;
472  uint key = 0;
473 
474  for (map = _vk_mapping; map != endof(_vk_mapping); ++map) {
475  if ((uint)(sym->sym - map->vk_from) <= map->vk_count) {
476  key = sym->sym - map->vk_from + map->map_to;
477  break;
478  }
479  }
480 
481  /* check scancode for BACKQUOTE key, because we want the key left of "1", not anything else (on non-US keyboards) */
482 #if defined(_WIN32) || defined(__OS2__)
483  if (sym->scancode == 41) key = WKC_BACKQUOTE;
484 #elif defined(__APPLE__)
485  if (sym->scancode == 10) key = WKC_BACKQUOTE;
486 #elif defined(__SVR4) && defined(__sun)
487  if (sym->scancode == 60) key = WKC_BACKQUOTE;
488  if (sym->scancode == 49) key = WKC_BACKSPACE;
489 #elif defined(__sgi__)
490  if (sym->scancode == 22) key = WKC_BACKQUOTE;
491 #else
492  if (sym->scancode == 49) key = WKC_BACKQUOTE;
493 #endif
494 
495  /* META are the command keys on mac */
496  if (sym->mod & KMOD_META) key |= WKC_META;
497  if (sym->mod & KMOD_SHIFT) key |= WKC_SHIFT;
498  if (sym->mod & KMOD_CTRL) key |= WKC_CTRL;
499  if (sym->mod & KMOD_ALT) key |= WKC_ALT;
500 
501  *character = sym->unicode;
502  return key;
503 }
504 
505 int VideoDriver_SDL::PollEvent()
506 {
507  SDL_Event ev;
508 
509  if (!SDL_PollEvent(&ev)) return -2;
510 
511  switch (ev.type) {
512  case SDL_MOUSEMOTION:
513  if (_cursor.UpdateCursorPosition(ev.motion.x, ev.motion.y, true)) {
514  SDL_WarpMouse(_cursor.pos.x, _cursor.pos.y);
515  }
517  break;
518 
519  case SDL_MOUSEBUTTONDOWN:
520  if (_rightclick_emulate && SDL_GetModState() & KMOD_CTRL) {
521  ev.button.button = SDL_BUTTON_RIGHT;
522  }
523 
524  switch (ev.button.button) {
525  case SDL_BUTTON_LEFT:
526  _left_button_down = true;
527  break;
528 
529  case SDL_BUTTON_RIGHT:
530  _right_button_down = true;
531  _right_button_clicked = true;
532  break;
533 
534  case SDL_BUTTON_WHEELUP: _cursor.wheel--; break;
535  case SDL_BUTTON_WHEELDOWN: _cursor.wheel++; break;
536 
537  default: break;
538  }
540  break;
541 
542  case SDL_MOUSEBUTTONUP:
543  if (_rightclick_emulate) {
544  _right_button_down = false;
545  _left_button_down = false;
546  _left_button_clicked = false;
547  } else if (ev.button.button == SDL_BUTTON_LEFT) {
548  _left_button_down = false;
549  _left_button_clicked = false;
550  } else if (ev.button.button == SDL_BUTTON_RIGHT) {
551  _right_button_down = false;
552  }
554  break;
555 
556  case SDL_ACTIVEEVENT:
557  if (!(ev.active.state & SDL_APPMOUSEFOCUS)) break;
558 
559  if (ev.active.gain) { // mouse entered the window, enable cursor
560  _cursor.in_window = true;
561  } else {
562  UndrawMouseCursor(); // mouse left the window, undraw cursor
563  _cursor.in_window = false;
564  }
565  break;
566 
567  case SDL_QUIT:
568  HandleExitGameRequest();
569  break;
570 
571  case SDL_KEYDOWN: // Toggle full-screen on ALT + ENTER/F
572  if ((ev.key.keysym.mod & (KMOD_ALT | KMOD_META)) &&
573  (ev.key.keysym.sym == SDLK_RETURN || ev.key.keysym.sym == SDLK_f)) {
574  ToggleFullScreen(!_fullscreen);
575  } else {
576  WChar character;
577  uint keycode = ConvertSdlKeyIntoMy(&ev.key.keysym, &character);
578  HandleKeypress(keycode, character);
579  }
580  break;
581 
582  case SDL_VIDEORESIZE: {
583  int w = max(ev.resize.w, 64);
584  int h = max(ev.resize.h, 64);
585  CreateMainSurface(w, h);
586  break;
587  }
588  case SDL_VIDEOEXPOSE: {
589  /* Force a redraw of the entire screen. Note
590  * that SDL 1.2 seems to do this automatically
591  * in most cases, but 1.3 / 2.0 does not. */
592  _num_dirty_rects = MAX_DIRTY_RECTS + 1;
593  break;
594  }
595  }
596  return -1;
597 }
598 
599 const char *VideoDriver_SDL::Start(const char * const *parm)
600 {
601  char buf[30];
602  _use_hwpalette = GetDriverParamInt(parm, "hw_palette", 2);
603 
604  /* Just on the offchance the audio subsystem started before the video system,
605  * check whether any part of SDL has been initialised before getting here.
606  * Slightly duplicated with sound/sdl_s.cpp */
607  int ret_code = 0;
608  if (SDL_WasInit(SDL_INIT_EVERYTHING) == 0) {
609  ret_code = SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE);
610  } else if (SDL_WasInit(SDL_INIT_VIDEO) == 0) {
611  ret_code = SDL_InitSubSystem(SDL_INIT_VIDEO);
612  }
613  if (ret_code == -1) return SDL_GetError();
614 
615  GetVideoModes();
616  if (!CreateMainSurface(_cur_resolution.width, _cur_resolution.height)) {
617  return SDL_GetError();
618  }
619 
620  SDL_VideoDriverName(buf, sizeof buf);
621  DEBUG(driver, 1, "SDL: using driver '%s'", buf);
622 
624  SetupKeyboard();
625 
626  _draw_threaded = GetDriverParam(parm, "no_threads") == nullptr && GetDriverParam(parm, "no_thread") == nullptr;
627 
628  return nullptr;
629 }
630 
631 void VideoDriver_SDL::SetupKeyboard()
632 {
633  SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
634  SDL_EnableUNICODE(1);
635 }
636 
638 {
639  SDL_QuitSubSystem(SDL_INIT_VIDEO);
640  if (SDL_WasInit(SDL_INIT_EVERYTHING) == 0) {
641  SDL_Quit(); // If there's nothing left, quit SDL
642  }
643 }
644 
646 {
647  uint32 cur_ticks = SDL_GetTicks();
648  uint32 last_cur_ticks = cur_ticks;
649  uint32 next_tick = cur_ticks + MILLISECONDS_PER_TICK;
650  uint32 mod;
651  int numkeys;
652  Uint8 *keys;
653 
654  CheckPaletteAnim();
655 
656  std::thread draw_thread;
657  std::unique_lock<std::recursive_mutex> draw_lock;
658  if (_draw_threaded) {
659  /* Initialise the mutex first, because that's the thing we *need*
660  * directly in the newly created thread. */
661  _draw_mutex = new std::recursive_mutex();
662  if (_draw_mutex == nullptr) {
663  _draw_threaded = false;
664  } else {
665  draw_lock = std::unique_lock<std::recursive_mutex>(*_draw_mutex);
666  _draw_signal = new std::condition_variable_any();
667  _draw_continue = true;
668 
669  _draw_threaded = StartNewThread(&draw_thread, "ottd:draw-sdl", &DrawSurfaceToScreenThread);
670 
671  /* Free the mutex if we won't be able to use it. */
672  if (!_draw_threaded) {
673  draw_lock.unlock();
674  draw_lock.release();
675  delete _draw_mutex;
676  delete _draw_signal;
677  _draw_mutex = nullptr;
678  _draw_signal = nullptr;
679  } else {
680  /* Wait till the draw mutex has started itself. */
681  _draw_signal->wait(*_draw_mutex);
682  }
683  }
684  }
685 
686  DEBUG(driver, 1, "SDL: using %sthreads", _draw_threaded ? "" : "no ");
687 
688  for (;;) {
689  uint32 prev_cur_ticks = cur_ticks; // to check for wrapping
690  InteractiveRandom(); // randomness
691 
692  while (PollEvent() == -1) {}
693  if (_exit_game) break;
694 
695  mod = SDL_GetModState();
696 #if SDL_VERSION_ATLEAST(1, 3, 0)
697  keys = SDL_GetKeyboardState(&numkeys);
698 #else
699  keys = SDL_GetKeyState(&numkeys);
700 #endif
701 #if defined(_DEBUG)
702  if (_shift_pressed)
703 #else
704  /* Speedup when pressing tab, except when using ALT+TAB
705  * to switch to another application */
706 #if SDL_VERSION_ATLEAST(1, 3, 0)
707  if (keys[SDL_SCANCODE_TAB] && (mod & KMOD_ALT) == 0)
708 #else
709  if (keys[SDLK_TAB] && (mod & KMOD_ALT) == 0)
710 #endif /* SDL_VERSION_ATLEAST(1, 3, 0) */
711 #endif /* defined(_DEBUG) */
712  {
713  if (!_networking && _game_mode != GM_MENU) _fast_forward |= 2;
714  } else if (_fast_forward & 2) {
715  _fast_forward = 0;
716  }
717 
718  cur_ticks = SDL_GetTicks();
719  if (cur_ticks >= next_tick || (_fast_forward && !_pause_mode) || cur_ticks < prev_cur_ticks) {
720  _realtime_tick += cur_ticks - last_cur_ticks;
721  last_cur_ticks = cur_ticks;
722  next_tick = cur_ticks + MILLISECONDS_PER_TICK;
723 
724  bool old_ctrl_pressed = _ctrl_pressed;
725 
726  _ctrl_pressed = !!(mod & KMOD_CTRL);
727  _shift_pressed = !!(mod & KMOD_SHIFT);
728 
729  /* determine which directional keys are down */
730  _dirkeys =
731 #if SDL_VERSION_ATLEAST(1, 3, 0)
732  (keys[SDL_SCANCODE_LEFT] ? 1 : 0) |
733  (keys[SDL_SCANCODE_UP] ? 2 : 0) |
734  (keys[SDL_SCANCODE_RIGHT] ? 4 : 0) |
735  (keys[SDL_SCANCODE_DOWN] ? 8 : 0);
736 #else
737  (keys[SDLK_LEFT] ? 1 : 0) |
738  (keys[SDLK_UP] ? 2 : 0) |
739  (keys[SDLK_RIGHT] ? 4 : 0) |
740  (keys[SDLK_DOWN] ? 8 : 0);
741 #endif
742  if (old_ctrl_pressed != _ctrl_pressed) HandleCtrlChanged();
743 
744  /* The gameloop is the part that can run asynchronously. The rest
745  * except sleeping can't. */
746  if (_draw_mutex != nullptr) draw_lock.unlock();
747 
748  GameLoop();
749 
750  if (_draw_mutex != nullptr) draw_lock.lock();
751 
752  UpdateWindows();
753  _local_palette = _cur_palette;
754  } else {
755  /* Release the thread while sleeping */
756  if (_draw_mutex != nullptr) draw_lock.unlock();
757  CSleep(1);
758  if (_draw_mutex != nullptr) draw_lock.lock();
759 
761  DrawMouseCursor();
762  }
763 
764  /* End of the critical part. */
765  if (_draw_mutex != nullptr && !HasModalProgress()) {
766  _draw_signal->notify_one();
767  } else {
768  /* Oh, we didn't have threads, then just draw unthreaded */
769  CheckPaletteAnim();
770  DrawSurfaceToScreen();
771  }
772  }
773 
774  if (_draw_mutex != nullptr) {
775  _draw_continue = false;
776  /* Sending signal if there is no thread blocked
777  * is very valid and results in noop */
778  _draw_signal->notify_one();
779  if (draw_lock.owns_lock()) draw_lock.unlock();
780  draw_lock.release();
781  draw_thread.join();
782 
783  delete _draw_mutex;
784  delete _draw_signal;
785 
786  _draw_mutex = nullptr;
787  _draw_signal = nullptr;
788  }
789 }
790 
792 {
793  std::unique_lock<std::recursive_mutex> lock;
794  if (_draw_mutex != nullptr) lock = std::unique_lock<std::recursive_mutex>(*_draw_mutex);
795 
796  return CreateMainSurface(w, h);
797 }
798 
800 {
801  std::unique_lock<std::recursive_mutex> lock;
802  if (_draw_mutex != nullptr) lock = std::unique_lock<std::recursive_mutex>(*_draw_mutex);
803 
804  _fullscreen = fullscreen;
805  GetVideoModes(); // get the list of available video modes
806  bool ret = !_resolutions.empty() && CreateMainSurface(_cur_resolution.width, _cur_resolution.height);
807 
808  if (!ret) {
809  /* switching resolution failed, put back full_screen to original status */
810  _fullscreen ^= true;
811  }
812 
813  return ret;
814 }
815 
817 {
818  return CreateMainSurface(_screen.width, _screen.height);
819 }
820 
822 {
823  if (_draw_mutex != nullptr) _draw_mutex->lock();
824 }
825 
827 {
828  if (_draw_mutex != nullptr) _draw_mutex->unlock();
829 }
830 
831 #endif /* WITH_SDL */
const char * GetDriverParam(const char *const *parm, const char *name)
Get a string parameter the list of parameters.
Definition: driver.cpp:37
bool _networking
are we in networking mode?
Definition: network.cpp:52
uint32 _realtime_tick
The real time in the game.
Definition: debug.cpp:48
Point pos
logical mouse position
Definition: gfx_type.h:117
Information about the currently used palette.
Definition: gfx_type.h:308
void AcquireBlitterLock() override
Acquire any lock(s) required to be held when changing blitters.
Definition: sdl_v.cpp:821
, Comma
Definition: gfx_type.h:102
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:407
bool _right_button_down
Is right mouse button pressed?
Definition: gfx.cpp:40
void MakeDirty(int left, int top, int width, int height) override
Mark a particular area dirty.
Definition: sdl_v.cpp:54
Colour palette[256]
Current palette. Entry 0 has to be always fully transparent!
Definition: gfx_type.h:309
= Equals
Definition: gfx_type.h:97
Base of the SDL video driver.
void Stop() override
Stop this driver.
Definition: sdl_v.cpp:637
void CSleep(int milliseconds)
Sleep on the current thread for a defined time.
Definition: thread.h:25
Dimension _cur_resolution
The current resolution.
Definition: driver.cpp:21
static volatile bool _draw_continue
Should we keep continue drawing?
Definition: sdl_v.cpp:45
#define lastof(x)
Get the last element of an fixed size array.
Definition: depend.cpp:48
No palette animation.
Definition: base.hpp:50
How all blitters should look like.
Definition: base.hpp:28
RAII class for measuring simple elements of performance.
Subdirectory for all base data (base sets, intro game)
Definition: fileio_type.h:116
static T max(const T a, const T b)
Returns the maximum of two values.
Definition: math_func.hpp:24
virtual void PostResize()
Post resize event.
Definition: base.hpp:201
Palette animation should be done by video backend (8bpp only!)
Definition: base.hpp:51
bool _left_button_clicked
Is left mouse button clicked?
Definition: gfx.cpp:39
std::vector< Dimension > _resolutions
List of resolutions.
Definition: driver.cpp:20
bool AfterBlitterChange() override
Callback invoked after the blitter was changed.
Definition: sdl_v.cpp:816
static std::condition_variable_any * _draw_signal
Signal to draw the next frame.
Definition: sdl_v.cpp:43
bool _ctrl_pressed
Is Ctrl pressed?
Definition: gfx.cpp:35
bool StartNewThread(std::thread *thr, const char *name, TFn &&_Fx, TArgs &&... _Ax)
Start a new thread.
Definition: thread.h:48
&#39; Single quote
Definition: gfx_type.h:101
bool _right_button_clicked
Is right mouse button clicked?
Definition: gfx.cpp:41
The blitter takes care of the palette animation.
Definition: base.hpp:52
char * FioFindFullPath(char *buf, const char *last, Subdirectory subdir, const char *filename)
Find a path to the filename in one of the search directories.
Definition: fileio.cpp:354
virtual void PaletteAnimate(const Palette &palette)=0
Called when the 8bpp palette is changed; you should redraw all pixels on the screen that are equal to...
bool _left_button_down
Is left mouse button pressed?
Definition: gfx.cpp:38
[ Left square bracket
Definition: gfx_type.h:98
] Right square bracket
Definition: gfx_type.h:100
std::mutex lock
synchronization for playback status fields
Definition: win32_m.cpp:34
\ Backslash
Definition: gfx_type.h:99
void CDECL usererror(const char *s,...)
Error handling for fatal user errors.
Definition: openttd.cpp:92
int wheel
mouse wheel movement
Definition: gfx_type.h:119
bool UpdateCursorPosition(int x, int y, bool queued_warp)
Update cursor position on mouse movement.
Definition: gfx.cpp:1647
/ Forward slash
Definition: gfx_type.h:95
static const uint MILLISECONDS_PER_TICK
The number of milliseconds per game tick.
Definition: gfx_type.h:305
void HandleKeypress(uint keycode, WChar key)
Handle keyboard input.
Definition: window.cpp:2670
byte _dirkeys
1 = left, 2 = up, 4 = right, 8 = down
Definition: gfx.cpp:31
void HandleMouseEvents()
Handle a mouse event from the video driver.
Definition: window.cpp:2977
#define lengthof(x)
Return the length of an fixed size array.
Definition: depend.cpp:40
bool ToggleFullscreen(bool fullscreen) override
Change the full screen setting.
Definition: sdl_v.cpp:799
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
Definition: factory.hpp:145
int first_dirty
The first dirty element.
Definition: gfx_type.h:310
PauseMode _pause_mode
The current pause mode.
Definition: gfx.cpp:47
; Semicolon
Definition: gfx_type.h:96
Palette _cur_palette
Current palette.
Definition: gfx.cpp:48
bool _shift_pressed
Is Shift pressed?
Definition: gfx.cpp:36
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:35
virtual Blitter::PaletteAnimation UsePaletteAnimation()=0
Check if the blitter uses palette animation at all.
static bool _draw_threaded
Whether the drawing is/may be done in a separate thread.
Definition: sdl_v.cpp:39
void HandleCtrlChanged()
State of CONTROL key has changed.
Definition: window.cpp:2727
void MainLoop() override
Perform the actual drawing.
Definition: sdl_v.cpp:645
Speed of painting drawn video buffer.
void NetworkDrawChatMessage()
Draw the chat message-box.
static Palette _local_palette
Local copy of the palette for use in the drawing thread.
Definition: win32_v.cpp:76
#define endof(x)
Get the end element of an fixed size array.
Definition: stdafx.h:384
bool in_window
mouse inside this window, determines drawing logic
Definition: gfx_type.h:141
bool ChangeResolution(int w, int h) override
Change the resolution of the window.
Definition: sdl_v.cpp:791
virtual uint8 GetScreenDepth()=0
Get the screen depth this blitter works for.
#define AS(ap_name, size_x, size_y, min_year, max_year, catchment, noise, maint_cost, ttdpatch_type, class_id, name, preview)
AirportSpec definition for airports with at least one depot.
void ReleaseBlitterLock() override
Release any lock(s) required to be held when changing blitters.
Definition: sdl_v.cpp:826
int GetDriverParamInt(const char *const *parm, const char *name, int def)
Get an integer parameter the list of parameters.
Definition: driver.cpp:73
static std::recursive_mutex * _draw_mutex
Mutex to keep the access to the shared memory controlled.
Definition: sdl_v.cpp:41
bool _rightclick_emulate
Whether right clicking is emulated.
Definition: driver.cpp:22
void GameSizeChanged()
Size of the application screen changed.
Definition: main_gui.cpp:594
. Period
Definition: gfx_type.h:103
Factory for the SDL video driver.
Definition: sdl2_v.h:54
int count_dirty
The number of dirty elements.
Definition: gfx_type.h:311
static T Delta(const T a, const T b)
Returns the (absolute) difference between two (scalar) variables.
Definition: math_func.hpp:230
uint32 WChar
Type for wide characters, i.e.
Definition: string_type.h:35
Dimensions (a width and height) of a rectangle in 2D.
Full 8bpp support by OS and hardware.
Definition: gfx_type.h:318
static bool HasModalProgress()
Check if we are currently in a modal progress state.
Definition: progress.h:21
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition: gfx.cpp:1462
const char * Start(const char *const *param) override
Start this driver.
Definition: sdl_v.cpp:599
void UpdateWindows()
Update the continuously changing contents of the windows, such as the viewports.
Definition: window.cpp:3128