Update: Translations from eints
[openttd-github.git] / src / video / sdl2_v.cpp
blob08723ef3b6d31e1c08ff2f6ffea946b3497f671e
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 */
8 /** @file sdl2_v.cpp Implementation of the SDL2 video driver. */
10 #include "../stdafx.h"
11 #include "../openttd.h"
12 #include "../gfx_func.h"
13 #include "../blitter/factory.hpp"
14 #include "../thread.h"
15 #include "../progress.h"
16 #include "../core/random_func.hpp"
17 #include "../core/math_func.hpp"
18 #include "../core/mem_func.hpp"
19 #include "../core/geometry_func.hpp"
20 #include "../fileio_func.h"
21 #include "../framerate_type.h"
22 #include "../window_func.h"
23 #include "sdl2_v.h"
24 #include <SDL.h>
25 #ifdef __EMSCRIPTEN__
26 # include <emscripten.h>
27 # include <emscripten/html5.h>
28 #endif
30 #include "../safeguards.h"
32 void VideoDriver_SDL_Base::MakeDirty(int left, int top, int width, int height)
34 Rect r = {left, top, left + width, top + height};
35 this->dirty_rect = BoundingRect(this->dirty_rect, r);
38 void VideoDriver_SDL_Base::CheckPaletteAnim()
40 if (!CopyPalette(this->local_palette)) return;
41 this->MakeDirty(0, 0, _screen.width, _screen.height);
44 static const Dimension default_resolutions[] = {
45 { 640, 480 },
46 { 800, 600 },
47 { 1024, 768 },
48 { 1152, 864 },
49 { 1280, 800 },
50 { 1280, 960 },
51 { 1280, 1024 },
52 { 1400, 1050 },
53 { 1600, 1200 },
54 { 1680, 1050 },
55 { 1920, 1200 }
58 static void FindResolutions()
60 _resolutions.clear();
62 for (int display = 0; display < SDL_GetNumVideoDisplays(); display++) {
63 for (int i = 0; i < SDL_GetNumDisplayModes(display); i++) {
64 SDL_DisplayMode mode;
65 SDL_GetDisplayMode(display, i, &mode);
67 if (mode.w < 640 || mode.h < 480) continue;
68 if (std::find(_resolutions.begin(), _resolutions.end(), Dimension(mode.w, mode.h)) != _resolutions.end()) continue;
69 _resolutions.emplace_back(mode.w, mode.h);
73 /* We have found no resolutions, show the default list */
74 if (_resolutions.empty()) {
75 _resolutions.assign(std::begin(default_resolutions), std::end(default_resolutions));
78 SortResolutions();
81 static void GetAvailableVideoMode(uint *w, uint *h)
83 /* All modes available? */
84 if (!_fullscreen || _resolutions.empty()) return;
86 /* Is the wanted mode among the available modes? */
87 if (std::find(_resolutions.begin(), _resolutions.end(), Dimension(*w, *h)) != _resolutions.end()) return;
89 /* Use the closest possible resolution */
90 uint best = 0;
91 uint delta = Delta(_resolutions[0].width, *w) * Delta(_resolutions[0].height, *h);
92 for (uint i = 1; i != _resolutions.size(); ++i) {
93 uint newdelta = Delta(_resolutions[i].width, *w) * Delta(_resolutions[i].height, *h);
94 if (newdelta < delta) {
95 best = i;
96 delta = newdelta;
99 *w = _resolutions[best].width;
100 *h = _resolutions[best].height;
103 static uint FindStartupDisplay(uint startup_display)
105 int num_displays = SDL_GetNumVideoDisplays();
107 /* If the user indicated a valid monitor, use that. */
108 if (IsInsideBS(startup_display, 0, num_displays)) return startup_display;
110 /* Mouse position decides which display to use. */
111 int mx, my;
112 SDL_GetGlobalMouseState(&mx, &my);
113 for (int display = 0; display < num_displays; ++display) {
114 SDL_Rect r;
115 if (SDL_GetDisplayBounds(display, &r) == 0 && IsInsideBS(mx, r.x, r.w) && IsInsideBS(my, r.y, r.h)) {
116 Debug(driver, 1, "SDL2: Mouse is at ({}, {}), use display {} ({}, {}, {}, {})", mx, my, display, r.x, r.y, r.w, r.h);
117 return display;
121 return 0;
124 void VideoDriver_SDL_Base::ClientSizeChanged(int w, int h, bool force)
126 /* Allocate backing store of the new size. */
127 if (this->AllocateBackingStore(w, h, force)) {
128 CopyPalette(this->local_palette, true);
130 BlitterFactory::GetCurrentBlitter()->PostResize();
132 GameSizeChanged();
136 bool VideoDriver_SDL_Base::CreateMainWindow(uint w, uint h, uint flags)
138 if (this->sdl_window != nullptr) return true;
140 flags |= SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE;
142 if (_fullscreen) {
143 flags |= SDL_WINDOW_FULLSCREEN;
146 int x = SDL_WINDOWPOS_UNDEFINED, y = SDL_WINDOWPOS_UNDEFINED;
147 SDL_Rect r;
148 if (SDL_GetDisplayBounds(this->startup_display, &r) == 0) {
149 x = r.x + std::max(0, r.w - static_cast<int>(w)) / 2;
150 y = r.y + std::max(0, r.h - static_cast<int>(h)) / 4; // decent desktops have taskbars at the bottom
153 std::string caption = VideoDriver::GetCaption();
154 this->sdl_window = SDL_CreateWindow(
155 caption.c_str(),
156 x, y,
157 w, h,
158 flags);
160 if (this->sdl_window == nullptr) {
161 Debug(driver, 0, "SDL2: Couldn't allocate a window to draw on: {}", SDL_GetError());
162 return false;
165 std::string icon_path = FioFindFullPath(BASESET_DIR, "openttd.32.bmp");
166 if (!icon_path.empty()) {
167 /* Give the application an icon */
168 SDL_Surface *icon = SDL_LoadBMP(icon_path.c_str());
169 if (icon != nullptr) {
170 /* Get the colourkey, which will be magenta */
171 uint32_t rgbmap = SDL_MapRGB(icon->format, 255, 0, 255);
173 SDL_SetColorKey(icon, SDL_TRUE, rgbmap);
174 SDL_SetWindowIcon(this->sdl_window, icon);
175 SDL_FreeSurface(icon);
179 return true;
182 bool VideoDriver_SDL_Base::CreateMainSurface(uint w, uint h, bool resize)
184 GetAvailableVideoMode(&w, &h);
185 Debug(driver, 1, "SDL2: using mode {}x{}", w, h);
187 if (!this->CreateMainWindow(w, h)) return false;
188 if (resize) SDL_SetWindowSize(this->sdl_window, w, h);
189 this->ClientSizeChanged(w, h, true);
191 /* When in full screen, we will always have the mouse cursor
192 * within the window, even though SDL does not give us the
193 * appropriate event to know this. */
194 if (_fullscreen) _cursor.in_window = true;
196 return true;
199 bool VideoDriver_SDL_Base::ClaimMousePointer()
201 /* Emscripten never claims the pointer, so we do not need to change the cursor visibility. */
202 #ifndef __EMSCRIPTEN__
203 SDL_ShowCursor(0);
204 #endif
205 return true;
209 * This is called to indicate that an edit box has gained focus, text input mode should be enabled.
211 void VideoDriver_SDL_Base::EditBoxGainedFocus()
213 if (!this->edit_box_focused) {
214 SDL_StartTextInput();
215 this->edit_box_focused = true;
220 * This is called to indicate that an edit box has lost focus, text input mode should be disabled.
222 void VideoDriver_SDL_Base::EditBoxLostFocus()
224 if (this->edit_box_focused) {
225 SDL_StopTextInput();
226 this->edit_box_focused = false;
230 std::vector<int> VideoDriver_SDL_Base::GetListOfMonitorRefreshRates()
232 std::vector<int> rates = {};
233 for (int i = 0; i < SDL_GetNumVideoDisplays(); i++) {
234 SDL_DisplayMode mode = {};
235 if (SDL_GetDisplayMode(i, 0, &mode) != 0) continue;
236 if (mode.refresh_rate != 0) rates.push_back(mode.refresh_rate);
238 return rates;
242 struct SDLVkMapping {
243 const SDL_Keycode vk_from;
244 const uint8_t vk_count;
245 const uint8_t map_to;
246 const bool unprintable;
248 constexpr SDLVkMapping(SDL_Keycode vk_first, SDL_Keycode vk_last, uint8_t map_first, [[maybe_unused]] uint8_t map_last, bool unprintable)
249 : vk_from(vk_first), vk_count(vk_last - vk_first + 1), map_to(map_first), unprintable(unprintable)
251 assert((vk_last - vk_first) == (map_last - map_first));
255 #define AS(x, z) {x, x, z, z, false}
256 #define AM(x, y, z, w) {x, y, z, w, false}
257 #define AS_UP(x, z) {x, x, z, z, true}
258 #define AM_UP(x, y, z, w) {x, y, z, w, true}
260 static constexpr SDLVkMapping _vk_mapping[] = {
261 /* Pageup stuff + up/down */
262 AS_UP(SDLK_PAGEUP, WKC_PAGEUP),
263 AS_UP(SDLK_PAGEDOWN, WKC_PAGEDOWN),
264 AS_UP(SDLK_UP, WKC_UP),
265 AS_UP(SDLK_DOWN, WKC_DOWN),
266 AS_UP(SDLK_LEFT, WKC_LEFT),
267 AS_UP(SDLK_RIGHT, WKC_RIGHT),
269 AS_UP(SDLK_HOME, WKC_HOME),
270 AS_UP(SDLK_END, WKC_END),
272 AS_UP(SDLK_INSERT, WKC_INSERT),
273 AS_UP(SDLK_DELETE, WKC_DELETE),
275 /* Map letters & digits */
276 AM(SDLK_a, SDLK_z, 'A', 'Z'),
277 AM(SDLK_0, SDLK_9, '0', '9'),
279 AS_UP(SDLK_ESCAPE, WKC_ESC),
280 AS_UP(SDLK_PAUSE, WKC_PAUSE),
281 AS_UP(SDLK_BACKSPACE, WKC_BACKSPACE),
283 AS(SDLK_SPACE, WKC_SPACE),
284 AS(SDLK_RETURN, WKC_RETURN),
285 AS(SDLK_TAB, WKC_TAB),
287 /* Function keys */
288 AM_UP(SDLK_F1, SDLK_F12, WKC_F1, WKC_F12),
290 /* Numeric part. */
291 AS(SDLK_KP_1, '1'),
292 AS(SDLK_KP_2, '2'),
293 AS(SDLK_KP_3, '3'),
294 AS(SDLK_KP_4, '4'),
295 AS(SDLK_KP_5, '5'),
296 AS(SDLK_KP_6, '6'),
297 AS(SDLK_KP_7, '7'),
298 AS(SDLK_KP_8, '8'),
299 AS(SDLK_KP_9, '9'),
300 AS(SDLK_KP_0, '0'),
301 AS(SDLK_KP_DIVIDE, WKC_NUM_DIV),
302 AS(SDLK_KP_MULTIPLY, WKC_NUM_MUL),
303 AS(SDLK_KP_MINUS, WKC_NUM_MINUS),
304 AS(SDLK_KP_PLUS, WKC_NUM_PLUS),
305 AS(SDLK_KP_ENTER, WKC_NUM_ENTER),
306 AS(SDLK_KP_PERIOD, WKC_NUM_DECIMAL),
308 /* Other non-letter keys */
309 AS(SDLK_SLASH, WKC_SLASH),
310 AS(SDLK_SEMICOLON, WKC_SEMICOLON),
311 AS(SDLK_EQUALS, WKC_EQUALS),
312 AS(SDLK_LEFTBRACKET, WKC_L_BRACKET),
313 AS(SDLK_BACKSLASH, WKC_BACKSLASH),
314 AS(SDLK_RIGHTBRACKET, WKC_R_BRACKET),
316 AS(SDLK_QUOTE, WKC_SINGLEQUOTE),
317 AS(SDLK_COMMA, WKC_COMMA),
318 AS(SDLK_MINUS, WKC_MINUS),
319 AS(SDLK_PERIOD, WKC_PERIOD)
322 static uint ConvertSdlKeyIntoMy(SDL_Keysym *sym, char32_t *character)
324 uint key = 0;
325 bool unprintable = false;
327 for (const auto &map : _vk_mapping) {
328 if (IsInsideBS(sym->sym, map.vk_from, map.vk_count)) {
329 key = sym->sym - map.vk_from + map.map_to;
330 unprintable = map.unprintable;
331 break;
335 /* check scancode for BACKQUOTE key, because we want the key left of "1", not anything else (on non-US keyboards) */
336 if (sym->scancode == SDL_SCANCODE_GRAVE) key = WKC_BACKQUOTE;
338 /* META are the command keys on mac */
339 if (sym->mod & KMOD_GUI) key |= WKC_META;
340 if (sym->mod & KMOD_SHIFT) key |= WKC_SHIFT;
341 if (sym->mod & KMOD_CTRL) key |= WKC_CTRL;
342 if (sym->mod & KMOD_ALT) key |= WKC_ALT;
344 /* The mod keys have no character. Prevent '?' */
345 if (sym->mod & KMOD_GUI ||
346 sym->mod & KMOD_CTRL ||
347 sym->mod & KMOD_ALT ||
348 unprintable) {
349 *character = WKC_NONE;
350 } else {
351 *character = sym->sym;
354 return key;
358 * Like ConvertSdlKeyIntoMy(), but takes an SDL_Keycode as input
359 * instead of an SDL_Keysym.
361 static uint ConvertSdlKeycodeIntoMy(SDL_Keycode kc)
363 uint key = 0;
365 for (const auto &map : _vk_mapping) {
366 if (IsInsideBS(kc, map.vk_from, map.vk_count)) {
367 key = kc - map.vk_from + map.map_to;
368 break;
372 /* check scancode for BACKQUOTE key, because we want the key left
373 * of "1", not anything else (on non-US keyboards) */
374 SDL_Scancode sc = SDL_GetScancodeFromKey(kc);
375 if (sc == SDL_SCANCODE_GRAVE) key = WKC_BACKQUOTE;
377 return key;
380 bool VideoDriver_SDL_Base::PollEvent()
382 SDL_Event ev;
384 if (!SDL_PollEvent(&ev)) return false;
386 switch (ev.type) {
387 case SDL_MOUSEMOTION: {
388 int32_t x = ev.motion.x;
389 int32_t y = ev.motion.y;
391 if (_cursor.fix_at) {
392 /* Get all queued mouse events now in case we have to warp the cursor. In the
393 * end, we only care about the current mouse position and not bygone events. */
394 while (SDL_PeepEvents(&ev, 1, SDL_GETEVENT, SDL_MOUSEMOTION, SDL_MOUSEMOTION)) {
395 x = ev.motion.x;
396 y = ev.motion.y;
400 if (_cursor.UpdateCursorPosition(x, y)) {
401 SDL_WarpMouseInWindow(this->sdl_window, _cursor.pos.x, _cursor.pos.y);
403 HandleMouseEvents();
404 break;
407 case SDL_MOUSEWHEEL:
408 if (ev.wheel.y > 0) {
409 _cursor.wheel--;
410 } else if (ev.wheel.y < 0) {
411 _cursor.wheel++;
413 break;
415 case SDL_MOUSEBUTTONDOWN:
416 if (_rightclick_emulate && SDL_GetModState() & KMOD_CTRL) {
417 ev.button.button = SDL_BUTTON_RIGHT;
420 switch (ev.button.button) {
421 case SDL_BUTTON_LEFT:
422 _left_button_down = true;
423 break;
425 case SDL_BUTTON_RIGHT:
426 _right_button_down = true;
427 _right_button_clicked = true;
428 break;
430 default: break;
432 HandleMouseEvents();
433 break;
435 case SDL_MOUSEBUTTONUP:
436 if (_rightclick_emulate) {
437 _right_button_down = false;
438 _left_button_down = false;
439 _left_button_clicked = false;
440 } else if (ev.button.button == SDL_BUTTON_LEFT) {
441 _left_button_down = false;
442 _left_button_clicked = false;
443 } else if (ev.button.button == SDL_BUTTON_RIGHT) {
444 _right_button_down = false;
446 HandleMouseEvents();
447 break;
449 case SDL_QUIT:
450 HandleExitGameRequest();
451 break;
453 case SDL_KEYDOWN: // Toggle full-screen on ALT + ENTER/F
454 if ((ev.key.keysym.mod & (KMOD_ALT | KMOD_GUI)) &&
455 (ev.key.keysym.sym == SDLK_RETURN || ev.key.keysym.sym == SDLK_f)) {
456 if (ev.key.repeat == 0) ToggleFullScreen(!_fullscreen);
457 } else {
458 char32_t character;
460 uint keycode = ConvertSdlKeyIntoMy(&ev.key.keysym, &character);
461 // Only handle non-text keys here. Text is handled in
462 // SDL_TEXTINPUT below.
463 if (!this->edit_box_focused ||
464 keycode == WKC_DELETE ||
465 keycode == WKC_NUM_ENTER ||
466 keycode == WKC_LEFT ||
467 keycode == WKC_RIGHT ||
468 keycode == WKC_UP ||
469 keycode == WKC_DOWN ||
470 keycode == WKC_HOME ||
471 keycode == WKC_END ||
472 keycode & WKC_META ||
473 keycode & WKC_CTRL ||
474 keycode & WKC_ALT ||
475 (keycode >= WKC_F1 && keycode <= WKC_F12) ||
476 !IsValidChar(character, CS_ALPHANUMERAL)) {
477 HandleKeypress(keycode, character);
480 break;
482 case SDL_TEXTINPUT: {
483 if (!this->edit_box_focused) break;
484 SDL_Keycode kc = SDL_GetKeyFromName(ev.text.text);
485 uint keycode = ConvertSdlKeycodeIntoMy(kc);
487 if (keycode == WKC_BACKQUOTE && FocusedWindowIsConsole()) {
488 char32_t character;
489 Utf8Decode(&character, ev.text.text);
490 HandleKeypress(keycode, character);
491 } else {
492 HandleTextInput(ev.text.text);
494 break;
496 case SDL_WINDOWEVENT: {
497 if (ev.window.event == SDL_WINDOWEVENT_EXPOSED) {
498 // Force a redraw of the entire screen.
499 this->MakeDirty(0, 0, _screen.width, _screen.height);
500 } else if (ev.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) {
501 int w = std::max(ev.window.data1, 64);
502 int h = std::max(ev.window.data2, 64);
503 CreateMainSurface(w, h, w != ev.window.data1 || h != ev.window.data2);
504 } else if (ev.window.event == SDL_WINDOWEVENT_ENTER) {
505 // mouse entered the window, enable cursor
506 _cursor.in_window = true;
507 /* Ensure pointer lock will not occur. */
508 SDL_SetRelativeMouseMode(SDL_FALSE);
509 } else if (ev.window.event == SDL_WINDOWEVENT_LEAVE) {
510 // mouse left the window, undraw cursor
511 UndrawMouseCursor();
512 _cursor.in_window = false;
514 break;
518 return true;
521 static std::optional<std::string_view> InitializeSDL()
523 /* Check if the video-driver is already initialized. */
524 if (SDL_WasInit(SDL_INIT_VIDEO) != 0) return std::nullopt;
526 if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) return SDL_GetError();
527 return std::nullopt;
530 std::optional<std::string_view> VideoDriver_SDL_Base::Initialize()
532 this->UpdateAutoResolution();
534 auto error = InitializeSDL();
535 if (error) return error;
537 FindResolutions();
538 Debug(driver, 2, "Resolution for display: {}x{}", _cur_resolution.width, _cur_resolution.height);
540 return std::nullopt;
543 std::optional<std::string_view> VideoDriver_SDL_Base::Start(const StringList &param)
545 if (BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 0) return "Only real blitters supported";
547 auto error = this->Initialize();
548 if (error) return error;
550 #ifdef SDL_HINT_MOUSE_AUTO_CAPTURE
551 if (GetDriverParamBool(param, "no_mouse_capture")) {
552 /* By default SDL captures the mouse, while a button is pressed.
553 * This is annoying during debugging, when OpenTTD is suspended while the button was pressed.
555 if (!SDL_SetHint(SDL_HINT_MOUSE_AUTO_CAPTURE, "0")) return SDL_GetError();
557 #endif
559 this->startup_display = FindStartupDisplay(GetDriverParamInt(param, "display", -1));
561 if (!CreateMainSurface(_cur_resolution.width, _cur_resolution.height, false)) {
562 return SDL_GetError();
565 const char *dname = SDL_GetCurrentVideoDriver();
566 Debug(driver, 1, "SDL2: using driver '{}'", dname);
568 this->driver_info = this->GetName();
569 this->driver_info += " (";
570 this->driver_info += dname;
571 this->driver_info += ")";
573 MarkWholeScreenDirty();
575 SDL_StopTextInput();
576 this->edit_box_focused = false;
578 #ifdef __EMSCRIPTEN__
579 this->is_game_threaded = false;
580 #else
581 this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread");
582 #endif
584 return std::nullopt;
587 void VideoDriver_SDL_Base::Stop()
589 SDL_QuitSubSystem(SDL_INIT_VIDEO);
590 if (SDL_WasInit(SDL_INIT_EVERYTHING) == 0) {
591 SDL_Quit(); // If there's nothing left, quit SDL
595 void VideoDriver_SDL_Base::InputLoop()
597 uint32_t mod = SDL_GetModState();
598 const Uint8 *keys = SDL_GetKeyboardState(nullptr);
600 bool old_ctrl_pressed = _ctrl_pressed;
602 _ctrl_pressed = !!(mod & KMOD_CTRL);
603 _shift_pressed = !!(mod & KMOD_SHIFT);
605 /* Speedup when pressing tab, except when using ALT+TAB
606 * to switch to another application. */
607 this->fast_forward_key_pressed = keys[SDL_SCANCODE_TAB] && (mod & KMOD_ALT) == 0;
609 /* Determine which directional keys are down. */
610 _dirkeys =
611 (keys[SDL_SCANCODE_LEFT] ? 1 : 0) |
612 (keys[SDL_SCANCODE_UP] ? 2 : 0) |
613 (keys[SDL_SCANCODE_RIGHT] ? 4 : 0) |
614 (keys[SDL_SCANCODE_DOWN] ? 8 : 0);
616 if (old_ctrl_pressed != _ctrl_pressed) HandleCtrlChanged();
619 void VideoDriver_SDL_Base::LoopOnce()
621 if (_exit_game) {
622 #ifdef __EMSCRIPTEN__
623 /* Emscripten is event-driven, and as such the main loop is inside
624 * the browser. So if _exit_game goes true, the main loop ends (the
625 * cancel call), but we still have to call the cleanup that is
626 * normally done at the end of the main loop for non-Emscripten.
627 * After that, Emscripten just halts, and the HTML shows a nice
628 * "bye, see you next time" message. */
629 extern void PostMainLoop();
630 PostMainLoop();
632 emscripten_cancel_main_loop();
633 emscripten_exit_pointerlock();
634 /* In effect, the game ends here. As emscripten_set_main_loop() caused
635 * the stack to be unwound, the code after MainLoop() in
636 * openttd_main() is never executed. */
637 if (_game_mode == GM_BOOTSTRAP) {
638 EM_ASM(if (window["openttd_bootstrap_reload"]) openttd_bootstrap_reload());
639 } else {
640 EM_ASM(if (window["openttd_exit"]) openttd_exit());
642 #endif
643 return;
646 this->Tick();
648 /* Emscripten is running an event-based mainloop; there is already some
649 * downtime between each iteration, so no need to sleep. */
650 #ifndef __EMSCRIPTEN__
651 this->SleepTillNextTick();
652 #endif
655 void VideoDriver_SDL_Base::MainLoop()
657 #ifdef __EMSCRIPTEN__
658 /* Run the main loop event-driven, based on RequestAnimationFrame. */
659 emscripten_set_main_loop_arg(&this->EmscriptenLoop, this, 0, 1);
660 #else
661 this->StartGameThread();
663 while (!_exit_game) {
664 LoopOnce();
667 this->StopGameThread();
668 #endif
671 bool VideoDriver_SDL_Base::ChangeResolution(int w, int h)
673 return CreateMainSurface(w, h, true);
676 bool VideoDriver_SDL_Base::ToggleFullscreen(bool fullscreen)
678 /* Remember current window size */
679 int w, h;
680 SDL_GetWindowSize(this->sdl_window, &w, &h);
682 if (fullscreen) {
683 /* Find fullscreen window size */
684 SDL_DisplayMode dm;
685 if (SDL_GetCurrentDisplayMode(SDL_GetWindowDisplayIndex(this->sdl_window), &dm) < 0) {
686 Debug(driver, 0, "SDL_GetCurrentDisplayMode() failed: {}", SDL_GetError());
687 } else {
688 SDL_SetWindowSize(this->sdl_window, dm.w, dm.h);
692 Debug(driver, 1, "SDL2: Setting {}", fullscreen ? "fullscreen" : "windowed");
693 int ret = SDL_SetWindowFullscreen(this->sdl_window, fullscreen ? SDL_WINDOW_FULLSCREEN : 0);
694 if (ret == 0) {
695 /* Switching resolution succeeded, set fullscreen value of window. */
696 _fullscreen = fullscreen;
697 if (!fullscreen) SDL_SetWindowSize(this->sdl_window, w, h);
698 } else {
699 Debug(driver, 0, "SDL_SetWindowFullscreen() failed: {}", SDL_GetError());
702 InvalidateWindowClassesData(WC_GAME_OPTIONS, 3);
703 return ret == 0;
706 bool VideoDriver_SDL_Base::AfterBlitterChange()
708 assert(BlitterFactory::GetCurrentBlitter()->GetScreenDepth() != 0);
709 int w, h;
710 SDL_GetWindowSize(this->sdl_window, &w, &h);
711 return CreateMainSurface(w, h, false);
714 Dimension VideoDriver_SDL_Base::GetScreenSize() const
716 SDL_DisplayMode mode;
717 if (SDL_GetCurrentDisplayMode(this->startup_display, &mode) != 0) return VideoDriver::GetScreenSize();
719 return { static_cast<uint>(mode.w), static_cast<uint>(mode.h) };
722 bool VideoDriver_SDL_Base::LockVideoBuffer()
724 if (this->buffer_locked) return false;
725 this->buffer_locked = true;
727 _screen.dst_ptr = this->GetVideoPointer();
728 assert(_screen.dst_ptr != nullptr);
730 return true;
733 void VideoDriver_SDL_Base::UnlockVideoBuffer()
735 if (_screen.dst_ptr != nullptr) {
736 /* Hand video buffer back to the drawing backend. */
737 this->ReleaseVideoPointer();
738 _screen.dst_ptr = nullptr;
741 this->buffer_locked = false;